text
stringlengths
180
608k
[Question] [ > > This question is based on [a question I asked](https://spanish.stackexchange.com/q/20685/12637) in [Spanish language](https://spanish.stackexchange.com/). Yes, I asked for an algorithm in Spanish Language. :) > > > In Spain, current license plates have this pattern: > > 1234 XYZ > > > where XYZ are three consonants taken from the full set of Spanish consonants (except the 'ร‘', I think). Sometimes, when traveling with my wife, we use to play a game. When we see a license plate, we take its three consonants and try to form a word that contains those three consonants, appearing in the same order as in the license plate. Examples (in Spanish): ``` BCD BoCaDo (valid) CaBezaDa (not valid) FTL FaTaL (valid) FLeTar (not valid) FTR FleTaR (valid, wins) caFeTeRa (valid, loses) ``` The winner is the one who uses the least number of characters, as you can see in the last example. ### The challenge Write the shortest program or function that receives a list of words and a set of three consonants and finds the shortest word in the list that contains the three consonants in the same order. For the purposes of this game, case does not matter. * The input for the word list (first parameter) will be an array of your language `string` type. The second parameter (the three consonants) will be another `string`. If it's better for your language, consider the `string` with the three consonants the last item of the whole list of parameters. The output will be another `string`. * The words in the word list won't be invented or infinite words, they will word that appear in any standard dictionary. If you need a limit, suppose no word in the word list will be longer than 50 characters. * If there are several words with the same lenght that could be the valid answer, you can return any one of them. Just make sure you return just one word, or an empty string if no words match the pattern of three consonants. * You can repeat consonants in the group, so valid inputs for the three consonants are both `FLR` and `GGG`. * The Spanish consonants are exactly the same as English, with the addition of the "ร‘". The vowels are the same with the adition of the stressed vowels: "รกรฉรญรณรบรผ". There won't be any other kind of marks such as "-" or "'". * You can suppose the case will always be the same in both the word list and the three consonants. If you want to test your algorithm with a real collection of Spanish words, you can [download a file (15.9 MB) from Dropbox](https://www.dropbox.com/s/28bqzpj6mdtucz6/es_ANY.txt?dl=0) with more than a million words. ### Test cases ``` Input: 'psr', {'hola' 'repasar' 'pasarais' 'de' 'caรญda' 'pequeรฑรญsimo' 'agรผeros'} Output: 'repasar' Input: 'dsd', {'dedos' 'deseado' 'desde' 'sedado'} Output: 'desde' Input: 'hst', {'hastรญo' 'chest'} Output: 'chest' ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program that helps me to always beat my wife wins! :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes Saved 2 bytes thanks to *Leo* ``` ส’รฆsรฅ}รฉR` ``` [Try it online!](https://tio.run/##MzBNTDJM/f//1KTDy4oPL609vDIo4f//aPWk/OTElHx1HfXkxKTUqpREICstsSQxByySllqSWgQWykktSSxSj@VKKykCAA "05AB1E โ€“ Try It Online") **Explanation** ``` ส’ # filter list, keep only members for which the following is true sรฅ # input is in the รฆ # powerset of the current word } # end filter รฉ # sort by length R # reverse ` # push separately (shortest on top) ``` I would have used `head` at the end saving a byte but that would output an empty list if there isn't a match. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~30~~ 29 bytes ``` xtog!s2$S"1G!'.*'Yc!@gwXXn?@. ``` [Try it online!](https://tio.run/##y00syfn/v6IkP12x2EglWMnQXVFdT0s9MlnRIb08IiLP3kHv/3/1guIida5q9Yz8nER1BfWi1ILE4sQiIAtMJ2YWA5kpqUAiOfHw2hSQkoLUwtLUwxsPry3OzM0H8hPTD@9JLcovVq8FAA) ### Explanation ``` x % Implicitly take first input (string with three letters). Delete. % Gets copied into clipboard G, level 1 t % Implicitly take second input (cell array of strings defining the % words). Duplicate o % Convert to numeric array of code points. This gives a matrix where % each string is on a row, right-padded with zeros g % Convert to logical: nonzeros become 1 !s % Sum of each row. This gives the length of each word 2$S % Two-input sort: this sorts the array of strings according to their % lengths in increasing order " % For each word in the sorted array 1G % Push first input, say 'xyz' ! % Transpose into a column vector of chars '.*'Yc % Concatenate this string on each row ! % Transpose. This gives a char array which, when linearized in % column-major order, corresponds to 'x.*y.*z.*' @g % Push corrent word w % Swap XX % Regexp matching. Gives a cell array with substrings that match % the pattern 'x.*y.*z.*' n % Number of matchings ? % If non-zero @ % Push cell array with current word, to be displayed as output . % Break loop % Implicit end (if) % Implicit end (for) % Implicitly display stack ``` [Answer] # [PHP](https://php.net/), 111 bytes ``` $y=array_map(str_split,preg_grep("#".chunk_split($_GET[1],1,".*")."#",$_GET[0]));sort($y);echo join($y[0]??[]); ``` [Try it online!](https://tio.run/##NY7LCoMwEEX3/YoydWFKkLpORaLGbgRBsqqEICLGPjREu/Dr0/Th6s7lnBlGK23PsVZ658kL4/VJRDUkZUqzEjCkNGFXmlE35pTT4pMF47T6spxxVlEQ5L8bighyXgGx3ho1xjSrfDbanxcjZ/0YFqxN18vedNqHAwSteo33H/G3AzjEEBwBBU7A20cIkXkyTloR6Vo17W/TMLrmUBzXAhFr3w "PHP โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12 11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ล’Pฤ‹รฐรfLรžแธฃ1 ``` A full program that accepts a list of lists of lowercase characters (the words) and a list of lowercase characters (the letters) and prints the first of the shortest words which contain a sub-sequence equal to the letters (or nothing if none exist). **[Try it online!](https://tio.run/##y0rNyan8///opIAj3Yc3HJ6Q5nN43sMdiw3///8frZSRn5OopKNUlFqQWJxYBGSB6cTMYiAzJRVIJCceXpsCUlKQWliaenjj4bXFmbn5QH5i@uE9qUX5xUqx/5UKiouUAAA "Jelly โ€“ Try It Online")** ### How? ``` ล’Pฤ‹รฐรfLรžแธฃ1 - Main link: words; characters รฐรf - filter keep words for which this is truthy: ล’P - the power-set (all sub-sequences of the word in question) ฤ‹ - count (how many times the list of characters appears) - ...note 0 is falsey while 1, 2, 3, ... are truthy รž - sort by: L - length แธฃ1 - head to index 1 (would use แธข but it yields 0 for empty lists) - implicit print (smashes together the list of lists (of length 1)) ``` [Answer] # Pyth - ~~22~~ ~~21~~ ~~19~~ ~~12~~ 11 bytes ``` h+f/yTQlDEk ``` -1 Thanks to Maltysen. Takes 2 lines as input. 1st is the 3-letter string (lowercase), and the 2nd is a lowercase list of words. [Try it here](https://pyth.herokuapp.com/?code=h%2Bf%2FyTQlDEk&input=%22ftl%22%0A%5B%22fatales%22%2C%22fatal%22%2C%22fletar%22%5D&debug=0) Explanation: ``` h+f/yTQlDEk lDE # Sort word list by length f # Filter elements T of the word list... yT # by taking the powerset... / Q # and checking whether the 3-letter string Q is an element of that. + k # Add empty string to the list (in case no results found) h # And take the first result (the shortest) ``` Old 19-byte solution: ``` h+olNf/-T"aeiou"QEk ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 11 bytes ``` tlแต’โˆ‹.&hโІ.โˆจแบธ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vyTn4dZJjzq69dQyHnW16T3qWPFw147//6OVUopTlHSAVGpKfrGSDpAuTk1MyYewUlKBdHFqCkggNvZ/FAA "Brachylog โ€“ Try It Online") Function submission. (The TIO link has a command-line argument to run a function as though it were a full program.) ## Explanation Just a direct translation of the specification againโ€ฆ ``` tlแต’โˆ‹.&hโІ.โˆจแบธ t The last element of {standard input} โˆ‹. contains the return value as an element & and h the first element of {standard input} โІ. is a subsequence of the return value โˆจ alternate behaviour if no solution is found: แบธ return empty string แต’ tiebreak override: favour answers that have a low l length ``` You can actually almost answer with `hโІ.&tโˆ‹` โ€“ swapping the evaluation order means that Brachylog will pick the shortest answer by default (as the first constraint it sees is `โІ`, which has the rather convenient "shortest" as a default tiebreak) โ€“ but in that case, Brachylog's evaluation algorithm would unfortunately go into an infinite loop if the answer is not actually found. So almost half the answer is dedicated to handling the case of there being no appropriate answer. Even then, the `lแต’` tiebreak override (which is technically a sort, making use of `โˆ‹`'s default tiebreak of preferring elements nearer the start of the list) is only two bytes; the other three come from the need to output an empty string specifically when the output is not found, as opposed to Brachylog's default "no solutions" sentinel value (because the final `.` would be implicit if we didn't have to follow it with `โˆจ`). Interestingly, there's a feature that was previously implemented in Brachylog that would have saved a byte here. At one point, you could extract elements from the input argument using `?โ‚`, `?โ‚‚`, etc. syntax; that would allow you to rearrange the program to `tlแต’โˆ‹.โЇ?โ‚โˆจแบธ`, which is only 10 bytes. Unfortunately, the implementation that was used didn't actually work (and caused many otherwise working programs to break), so it was reverted. You can think of the program as being "conceptually" 10 bytes long, though. [Answer] # Haskell ~~129~~ ~~125~~ 74 bytes ``` import Data.List l#w=sortOn length[p|p<-w,isInfixOf l$filter(`elem`l)p]!!0 ``` CREDIT to @nimi [Answer] ## Perl, 53 bytes **48 bytes code + 5 for `-paF`.** ``` $"=".*";($_)=sort{$a=~y///c-length$b}grep/@F/,<> ``` This takes advantage of the fact that lists interpolated into the `m//` operator utilise the `$"` variable which changes the initial input string from `psr` to `p.*s.*r` which is then matched for each additional word and is sorted on `length`. [Try it online!](https://tio.run/##K0gtyjH9/19FyVZJT0vJWkMlXtO2OL@opFol0bauUl9fP1k3JzUvvSRDJak2vSi1QN/BTV/Hxu7//5TiFK6U1JT8YiBZnJqYkg@iU1K5ilNTgJx/@QUlmfl5xf91CxLdAA "Perl 5 โ€“ Try It Online") [Answer] ## JavaScript (ES6), ~~77~~ ~~75~~ 72 bytes Takes the 3 consonants `c` and the list of words `l` in currying syntax `(c)(l)`. Both inputs are expected in the same case. ``` c=>l=>l.map(w=>x=!w.match([...c].join`.*`)||!x[w.length]&&x?x:w,x='')&&x ``` ### Test cases ``` let f = c=>l=>l.map(w=>x=!w.match([...c].join`.*`)||!x[w.length]&&x?x:w,x='')&&x console.log(f('psr')(['hola', 'repasar', 'pasarais', 'de', 'caรญda', 'pequeรฑรญsimo', 'agรผeros'])) // 'repasar' console.log(f('dsd')(['dedos', 'deseado', 'desde', 'sedado'])) // 'desde' ``` [Answer] ### R, 101 bytes First time golfing! I'm sure this can be condensed somehow Takes the string x and a character vector y of possible inputs ``` w=pryr::f((b=y[sapply(gsub(paste('[^',x,']'),'',y),function(l)regexpr(x,l))>0])[which.min(nchar(b))]) ``` [Try it online!](https://tio.run/##HY1BCoMwEEWv0t3MQChdC/YiYmGMUQNpkk4U9VAuuu/Og6Xq5vN4PPiS81xGWaUoOsSmXKvEMboV@zQ1GDmNBqF6gVoU1EAKQK2kusnr0QaPjsT0ZomCi3JEz0dN1TxYPdzf1qPXAws2RDVlzSPOCDEJqJtGGILjg0DMccKnhAvYppNbc67mfWuvLJrPZPbvviX7Dqfgfv8ZCQmIKP8B) Edit: My version was 135, thanks Scrooble for the -34! [Answer] # [Retina](https://github.com/m-ender/retina), 58 bytes ``` O#$^`ยถ.+ $.& s`^((.)(.)(.).*ยถ(?-s:(.*\2.*\3.*\4.*)))?.* $5 ``` [Try it online!](https://tio.run/##JcQ9DsIwDEDh3dcgQkkQHvhZWHoELoCqWtSCSEBSuz1WB5ZOTM3BQgXS@55wH15Uynll6maecAMG16BNbS26f@jnyVZbPVn0l91ivzigd85V6MEcS0kqcI8PAuFESgK/U1BoGa6Ux5YgcTdwfudRwzMC3fKHJeoX "Retina โ€“ Try It Online") Takes the three consonants on one line and then the list of words on all subsequent lines. Explanation: `O` sorts the list `ยถ.+` excluding the first line `#` numerically `$` keyed by `$.&` length. A match is then sought for a line that includes the three consonants in order. If a suitable line exists than the last, i.e. shortest, such line becomes the output, otherwise the output is empty. The `?-s:` temporarily turns off the effect of `s`` so that only one line is matched. [Answer] # [Pip](https://github.com/dloscutoff/pip), 17 bytes ``` @:qJ`.*`N_FI#_SKg ``` Takes the word list as command-line arguments, and the consonants from stdin. [Try it online!](https://tio.run/##K8gs@P/fwarQK0FPK8Ev3s1TOT7YO/3//4Liov8Z@TmJ/4tSCxKLE4v@g8nEzOL/Kan/kxMPr01J/F@QWliaenjj4bXFmbn5/xPTD@9JLcovBgA "Pip โ€“ Try It Online") ### Explanation ``` g is list of cmdline args (implicit) SKg Sort g using this key function: #_ Length of each item (puts shortest words first) FI Filter on this function: q Line of input J`.*` joined on regex .* (turns "psr" into `p.*s.*r`) N_ Count regex matches in item (keeps only words that match) @: Get first element of result (using : meta-operator to lower precedence) If the list is empty, this will give nil, which results in empty output ``` [Answer] # Java 8, ~~132~~ 126 bytes ``` s->a->{String r="";for(String x:a)r=(x.length()<r.length()|r.isEmpty())&x.matches(r.format(".*%s.*%s.*%s.*",s))?x:r;return r;} ``` -6 bytes thanks to *@Nevay*. **Explanation:** [Try it online.](https://tio.run/##lVLLbsIwELzzFatIrewK/AEE0lN764lj1cM2NsQ0iV2vA0GUT@LQe2/5sNQ8AgeQaCU/du3VjGe8c1zgwFhVzuVHm@ZIBC@oy3UPgDx6ncI8VIjK61xMqzL12pTi@RiMJt7pcvb61v9j1SFKEkhh3NIgwUGyPpyBG0dRPDWOHfN6iNyNWS1yVc58xvjIncIvJzQ9FdavGOf3tSjQp5ki5kQACAmLxMMdnWfUJ84f66GLnfKVK8HFmzYOEsOw1XseVB7FLoyWUAQDWPdo5DsvACYr8qoQpvLChhuflywVaG2@YpElFwmyuQ7MEefdcWZyBKcsEjrYr6gJpIIUm61EsOqzUs13syVdGMBZ86OcoRMSBCge3ySXJK@RSyXNjowUSrPbAy8pGZL/EmTkr6pD8s3WwM55f4m56Z1baO@qD2Xd51LXCkIIWN52mC75lx3Npv0F) ``` s->a->{ // Method with two String-array parameters and String return-type String r=""; // Result-String, starting empty for(String x:a) // Loop over the words r=(x.length()<r.length() // If a word is smaller than the current `r`, |r.isEmpty()) // or `r` is still empty &x.matches(r.format(".*%s.*%s.*%s.*",s))? // And if the word is valid x // Change `r` to the current word : // Else: r; // Leave `r` the same return r;} // Return the result ``` [Answer] # Python, 77 bytes ``` import re lambda s,a:min([x for x in a if re.search('.*'.join(s),x)],key=len) ``` [Try it online!](https://repl.it/IrAi/2) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~28~~ ~~27~~ 26 bytes ``` x"l1G@g3XNXm/@gn*v]&X<2Gw) ``` [Try it online!](https://tio.run/##y00syfn/v0Ipx9DdId04wi8iV98hPU@rLFYtwsbIvVzz/3/1guIida5q9Yz8nER1BfWCxOLEosTMYiAzJRVIJCceXpsCkihKBUuBlKQWlqYe3nh4bXFmbj6Qn5h@eE9qUX6xei0A "MATL โ€“ Try It Online") `x` - Implicitly take first input (string with three letters) and delete it. Gets copied into clipboard G, level 1 automatically (this part was inspired by [@Luis Mendo's answer](https://codegolf.stackexchange.com/a/127051/8774)). `"` - Implicitly take second input (cell array of words), iterate through it. `l` - Push 1 to be used later `1G` - Push first input (say 'psr') `@g` - Push the current word as array `3XN` - `nchoosek` - Get all combinations of 3 letters from the word `Xm` - See if the license plate code 'psr' is one of these combinations. Returns 0 for false and 1 for true. `/` - Dividing the 1 (that we pushed earlier) by this result. Changes the 0s to `Inf`s `@gn` - Get the length of the current word `*` - Multiply the length by the division result. Returns the length as it is when word contains the 3 characters, otherwise returns `Inf` `v` - vertically concatenate these results into a single array `]` - close loop `&X<` - get the index of the minimum value from that array i.e. the index where the word containing the letters and with minimum length was found `2G` - Push the second input again `w` - Bring the min index back on top of stack `)` - Index into array of words with the min index, returning the valid word with minimum length (Implicit output.) --- Older: ``` x"@g1Gy3XNXm1w/wn*v]&X<2Gw) x"@g1Gy3XNXm1w/wn*v]2Gw2$S1) ``` ]
[Question] [ **Challenge:** Get the JavaScript string value containing only the "`-`" character using code only containing the following three symbols: `+[]`. *Note: I'm not sure if this is possible*. **Scoring criterion**: The number of bytes of code used. **Why?** I've set myself a challenge to be able to write code using only the above three characters that can evaluate to ANY JavaScript number. The only thing left I am missing is having access to the "`-`" character. Once I have this, everything else becomes possible. [This question](https://stackoverflow.com/q/7202157/1541397) is what gave me inspiration for this. # Definitions Here is a list of definitions I've so far come up with to write a JavaScript expression (on the left) using only the `+[]` symbols (on the right). Most definitions reuse existing definitions. > > > ``` > > **0**: +[] > **1**: ++[[]][**0**] > **(**EXPR**)**: [EXPR][**0**] > **1**: **(**1**)** > **2**: **1**+**1** > **3**: **1**+**2** > **4**: **1**+**3** > **5**: **1**+**4** > **6**: **1**+**5** > **7**: **1**+**6** > **8**: **1**+**7** > **9**: **1**+**8** > POSITIVE_INTEGER: +**((**DIGIT1**+""****)**+DIGIT2+DIGIT3+**...)** > **""**: []+[] > EXPR**+""**: EXPR+[] > **undefined**: [][**0**] > **"undefined"**: **undefined+""** > **"undefined"**: **("undefined")** > **"u"**: **"undefined"**[**0**] > **"n"**: **"undefined"**[**1**] > **"d"**: **"undefined"**[**2**] > **"e"**: **"undefined"**[**3**] > **"f"**: **"undefined"**[**4**] > **"i"**: **"undefined"**[**5**] > **NaN**: +**undefined** > **"NaN"**: **NaN+""** > **"N"**: **"NaN"**[**0**] > **"a"**: **"NaN"**[**1**] > **Infinity**: +**(1**+**"e"**+**3**+**1**+**0)** > **"Infinity"**: **Infinity+""** > **"I"**: **"Infinity"**[**0**] > **"t"**: **"Infinity"**[**6**] > **"y"**: **"Infinity"**[**7**] > **"function find() { [native code] }"**: **(**[][**"f"**+**"i"**+**"n"**+**"d"**]**+"")** > **"c"**: **"function find() { [native code] }"**[**3**] > **"("**: **"function find() { [native code] }"**[**13**] > **")"**: **"function find() { [native code] }"**[**14**] > **"{"**: **"function find() { [native code] }"**[**16**] > **"["**: **"function find() { [native code] }"**[**18**] > **"a"**: **"function find() { [native code] }"**[**19**] > **"v"**: **"function find() { [native code] }"**[**22**] > **"o"**: **"function find() { [native code] }"**[**17**] > > ``` > > > > # Unfinished definitions These definitions contain missing pieces, highlighted in red (never mind, I can't figure out how to change the color, I'll use italics for now). > > > ``` > > ***Number***: **0**[**"con*s*t*r*ucto*r*"**] > *OBJ**.**FUNC**()***: +*{valueOf:*OBJ.FUNC*}* > *OBJ**.**FUNC**()***: *{toString:*OBJ.FUNC*}***+""** > *"-"*: **(*Number.MIN\_SAFE\_INTEGER*+"")**[**0**] > *"-"*: **(*Number.NEGATIVE\_INFINITY*+"")**[**0**] > *"-"*: **(*Number.MIN\_VALUE*+"")**[**2**] > *"-"*: **(""*.indexOf()*+"")**[**0**] > ".": **(**+**"1e*-*1")**[**1**] > > ``` > > > > --- Thanks to the amazing answers to this question, I've created a [JSFiddle](https://jsfiddle.net/davcal/0oqd8m5s/9/) that can generate any JavaScript number using those 3 characters. Input a number, tap "Go!", and then copy and paste the JavaScript into your devtools console to see it in action. You can also hover over the generated output in the explanation section for details on how it works. [Answer] # ~~260 ... 210~~ 205 bytes *Saved 5 bytes thanks to @user202729* ``` [+[[+[++[[]][+[]]+[++[[]][+[]]]+[[+[][[]]]+[][[]]][+[]][++[[]][+[]]+[+[]]]+[++[[]][+[]]]+[+[]]+[+[]]]+[]][+[]][++[[]][+[]]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[++[[]][+[]]]]+[]][+[]][++[++[[]][+[]]][+[]]] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvE/WjsaiLSBZGwskBEbi8KJBcvGRkOYEBosgaYDIo@qEUUKizYUJXhIJB2oBiHLQMj/mtb/AQ "JavaScript (Node.js) โ€“ Try It Online") ### How? We first generate the string `"11e100"` and coerce it to an number to get `1.1e+101`. By coercing it back to a string and extracting the 2nd character, we obtain a `"."` Using this `"."`, we can now generate the string `".0000001"`. When forced to a number, this gives `1e-7`, which can be used to extract a `"-"`. Below is a slightly more readable version: ``` [+[[+['11' + [[NaN] + undefined][0][10] + '100'] + []][0][1] + '0000001'] + []][0][2] ``` ### Commented ``` [ // singleton array: +[ // coerce to a number: [ // singleton array: +[ // coerce to a number: ++[[]][+[]] + // 1 + [++[[]][+[]]] + // "1" + [ // singleton array: [+[][[]]] + // "NaN" + [][[]] // undefined ][+[]] // [0] -> "NaNundefined" [ // build [10]: ++[[]][+[]] + // 1 + [+[]] // "0" ] // -> "e" + [++[[]][+[]]] // + "1" + [+[]] + [+[]] // + "0" + "0" -> "11e100" ] // -> 1.1e101 + [] // coerce to a string ][+[]] // [0] -> "1.1e101" [ ++[[]][+[]] ] // [1] -> "." + [+[]] + [+[]] + [+[]] // + "0" + "0" + "0" + [+[]] + [+[]] + [+[]] // + "0" + "0" + "0" + [++[[]][+[]]] // + "1" -> ".0000001" ] // -> 1e-7 + [] // coerce to a string ][+[]] // [0] -> "1e-7" [ // build [2]: ++[ // pre-increment: ++[[]][+[]] // 1 ][+[]] // [0] ] // -> "-" ``` [Answer] # ~~286~~ ~~256~~ ~~251~~ ~~247~~ ~~244~~ 240 bytes ``` [+[[+[++[[]][+[]]+[++[[]][+[]]]+[[][[]]+[]][+[]][++[[]][+[]]+[++[[]][+[]]][+[]]+[++[[]][+[]]][+[]]]+[++[[]][+[]]]+[+[]]+[+[]]]+[]][+[]][++[[]][+[]]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[+[]]+[++[[]][+[]]]]+[]][+[]][++[[]][+[]]+[++[[]][+[]]][+[]]] ``` Did I just outgolf *@Arnauld* in his favorite language despite barely knowing JS?! ;) EDIT: Never mind, he just golfed it the moment I post it.. Of course. XD [Try it online.](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvE/WjsaiLSBZGwskBEbi8KJBTGjwaJQEdxKcQlhmAhVB@FgMRZFCR4SSQfR7ov9r2n9HwA) **Explanation:** Techniques used: * `+[]`: 0 * `++[[]][+[]]`: 1 * `[][[]]`: `undefined` * `[EXPRESSION]+[]`: Cast to string * `+[EXPRESSION]`: Cast to a number * `"STRING"[INDEX]`: Get the INDEX'th character of the STRING * `[EXPRESSION][+[]]`: Wrap and extract to have access to the next command (necessary after we casted to a string, number, or concatted some strings together); a.k.a. it acts as wrapping the EXPRESSION in parenthesis: `(EXPRESSION)`. I first create the string `"11e100"`. Casting this to a number and then back to a string will result in `"1.1e+101"`. From this, I extract the `.`, and use it to create the string `".0000001"`. Casting this to a number and then back to a string will result in `"1e-7"`, from which we can extract the `-`. Of course I didn't come up with this myself, since I barely program in JavaScript nor JSFuck. The genius behind this is *@Lynn*, who posted the following in [this answer of his/her for the *JSF\*\*k with only 5 symbols?* challenge](https://codegolf.stackexchange.com/a/75464/52210): > > Also, we can make `"11e100"`, cast to number and back to string, to get `"1.1e+101"`, from which we extract `.` and `+`. > > > Using that `.`, in turn, we can make the string `".0000001"`, cast it to number and back, to get `"1e-7"`, winning us `-`. > > > **Code explanation:** Step 1: Create `"11e100"`: ``` ++[[]][+[]] // Push 1 +[ ] // Concat: ++[[]][+[]] // Another 1 +[...] // Concat: [][[]] // Push undefined +[] // Cast it to a string: "undefined" [ ][+[]] // Wrap it in a list, and extract it again [3] // Get the (0-based) 3rd character of this string: "e", // where the 3 is created like this: ++[[]][+[]] // Push 1 + // Add: ++[[]][+[]] // Push another 1 [ ][+[]] // Wrap it in a list, and extract it again +[++[[]][+[]]][+[]] // And do the same to add another 1 +[++[[]][+[]]] // Concat another 1 +[+[]] // Concat a 0 +[+[]] // And concat another 0 ``` Step 2: Convert it to `"1.1e+101"`: ``` +[^] // Cast "11e100" to a number +[] // And convert it back to a string ``` Step 3: Extract the `.`: ``` [^][+[]] // Wrap it in a list, and extract it again [1] // Get the (0-based) 1st character of this string: ".", // where 1 is created as before: ++[[]][+[]] // Push 1 ``` Step 4: Create `".0000001"`: ``` ^+[+[]] // Concat a 0 to the "." +[+[]]+[+[]]+[+[]]+[+[]]+[+[]] // And concat five more 0s +[++[[]][+[]]] // Concat a 1 ``` Step 5: Convert it to `"1e-7"`: ``` +[^] // Cast ".0000001" to a number +[] // And convert it back to a string ``` Step 6: Extract the `-`: ``` [^][+[]] // Wrap it in a list, and extract it again [2] // Get the (0-based) 2nd character of this string: "-", // where 2 is created like this: ++[[]][+[]] // Push 1 + // Add: ++[[]][+[]] // Push 1 [ ][+[]] // Wrap it in a list, and extract it again ``` ]
[Question] [ In Chess, a Knight on grid \$(x, y)\$ may move to \$(x-2, y-1)\$, \$(x-2, y+1)\$, \$(x-1, y-2)\$, \$(x-1, y+2)\$, \$(x+1, y-2)\$, \$(x+1, y+2)\$, \$(x+2, y-1)\$ or \$(x+2, y+1)\$ in one step. Imagine an infinite chessboard with only a Knight on \$(0, 0)\$: > > How many steps is required for moving a Knight from \$(0, 0)\$ to \$(t\_x, t\_y)\$? > > > ## Inputs Two integers: \$t\_x\$, \$t\_y\$; \$-100 < t\_x < 100\$, \$-100 < t\_y < 100\$ ## Output Minimal steps needed to move a Knight from \$(0, 0)\$ to \$(t\_x, t\_y)\$ ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ## Testcases ``` x y -> out 0, 0 -> 0 0, 1 -> 3 0, 2 -> 2 1, 1 -> 2 1, 2 -> 1 3, 3 -> 2 4, 0 -> 2 42, 22 -> 22 84, 73 -> 53 45, 66 -> 37 99, 99 -> 66 -45, -91 -> 46 -81, 1 -> 42 11, -2 -> 7 ``` ``` document.write('<div>');[..."EFEDEDCDCBCBCBCBCBCBCBCBCBCBCBCBCBCDCDEDEFE;FEDEDCDCBCBABABABABABABABABABABABCBCDCDEDEF;EDEDCDCBCBABABABABABABABABABABABABCBCDCDEDE;DEDCDCBCBABA9A9A9A9A9A9A9A9A9A9ABABCBCDCDED;EDCDCBCBABA9A9A9A9A9A9A9A9A9A9A9ABABCBCDCDE;DCDCBCBABA9A9898989898989898989A9ABABCBCDCD;CDCBCBABA9A989898989898989898989A9ABABCBCDC;DCBCBABA9A98987878787878787878989A9ABABCBCD;CBCBABA9A9898787878787878787878989A9ABABCBC;BCBABA9A989878767676767676767878989A9ABABCB;CBABA9A98987876767676767676767878989A9ABABC;BABA9A9898787676565656565656767878989A9ABAB;CBA9A989878767656565656565656767878989A9ABC;BABA98987876765654545454545656767878989ABAB;CBA9A987876765654545454545456567678789A9ABC;BABA98987676565454343434345456567678989ABAB;CBA9A987876565454343434343454565678789A9ABC;BABA98987676545434323232343454567678989ABAB;CBA9A987876565434323232323434565678789A9ABC;BABA98987676545432341214323454567678989ABAB;CBA9A987876565434321232123434565678789A9ABC;BABA98987676545432323032323454567678989ABAB;CBA9A987876565434321232123434565678789A9ABC;BABA98987676545432341214323454567678989ABAB;CBA9A987876565434323232323434565678789A9ABC;BABA98987676545434323232343454567678989ABAB;CBA9A987876565454343434343454565678789A9ABC;BABA98987676565454343434345456567678989ABAB;CBA9A987876765654545454545456567678789A9ABC;BABA98987876765654545454545656767878989ABAB;CBA9A989878767656565656565656767878989A9ABC;BABA9A9898787676565656565656767878989A9ABAB;CBABA9A98987876767676767676767878989A9ABABC;BCBABA9A989878767676767676767878989A9ABABCB;CBCBABA9A9898787878787878787878989A9ABABCBC;DCBCBABA9A98987878787878787878989A9ABABCBCD;CDCBCBABA9A989898989898989898989A9ABABCBCDC;DCDCBCBABA9A9898989898989898989A9ABABCBCDCD;EDCDCBCBABA9A9A9A9A9A9A9A9A9A9A9ABABCBCDCDE;DEDCDCBCBABA9A9A9A9A9A9A9A9A9A9ABABCBCDCDED;EDEDCDCBCBABABABABABABABABABABABABCBCDCDEDE;FEDEDCDCBCBABABABABABABABABABABABCBCDCDEDEF;EFEDEDCDCBCBCBCBCBCBCBCBCBCBCBCBCBCDCDEDEFE"].forEach(c=>document.write(c==';'?'<br>':`<span class="d-${c}">${c}</span>`)); document.write('<style>body{line-height:16px;color:rgba(255,255,255,0.2);}span{display:inline-block;width:16px;font-size:16px;text-align:center;}div{white-space:pre;}');[...'0123456789ABCDEF'].map((c,i)=>document.write(`.d-${c}{background:hsl(${60-4*i},80%,${65-2*i}%)}`)); ``` ## Related OEIS Here are some OEIS for further reading * [A018837](https://oeis.org/A018837): Number of steps for knight to reach \$(n,0)\$ on infinite chessboard. * [A018838](https://oeis.org/A018838): Number of steps for knight to reach \$(n,n)\$ on infinite chessboard. * [A065775](https://oeis.org/A065775): Array \$T\$ read by diagonals: \$T(i,j)=\$ least number of knight's moves on a chessboard (infinite in all directions) needed to move from \$(0,0)\$ to \$(i,j)\$. * [A183041](https://oeis.org/A183041): Least number of knight's moves from \$(0,0)\$ to \$(n,1)\$ on infinite chessboard. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes Using the built-in [`KnightTourGraph`](http://reference.wolfram.com/language/ref/KnightTourGraph.html). Saved 2 bytes thanks to [Mathe172](https://codegolf.stackexchange.com/users/70782/mathe172). ``` GraphDistance[KnightTourGraph@@({x,y}=Abs@{##}+4),y+2,(x-2)y-2]& ``` [Try it online!](https://tio.run/##PYyxCoMwFEV/5UFAFBPQaFszWFIodOjSoZs4pKI1g7ZoCork21NjQ6dz7z2P1wnV1p1QshKmgdxcBvFuz3JUoq/q4trLZ6vur8@w7Zz7y4RnnZ8eI18Q0mEa4Dmk2J8IDWZCS8/cBtmrwkogR2gKhMoSPOCcw7JEGCKNwTJ2pJax67HrCYbEMnX3KV3FZrJ1OvzcDsN@bxNjGBizidiRsO0Xyf5f10Co1uYL "Wolfram Language (Mathematica) โ€“ Try It Online") [![ArrayPlot@Array[GraphDistance[KnightTourGraph@@({x,y}=Abs@{##}+5),2y+3,(x-2)y-2]&,{65,65},-32]](https://i.stack.imgur.com/67t4X.jpg)](https://i.stack.imgur.com/67t4X.jpg) [Answer] # JavaScript (ES6), ~~90~~ ~~75~~ 72 bytes Inspired by the formula given for [A065775](https://oeis.org/A065775). Slow as hell for (not so) long distances. ``` f=(x,y,z=x|y)=>z<0?f(-y,x):z>1?1+Math.min(f(x-1,y-2),f(x-2,y-1)):z*3^x&y ``` [Try it online!](https://tio.run/##dc7hCoIwEAfw7z3FPsVWN/U2IYjUJ@gVArEsw1ykxCa9u12gIMxgYwe/@9/tnr/ztnhVz0425nwZyoQOt@CgT@zHiSTtD1FWcunAin2fYobbY97dgkfV8JJbieCkEvArFZUoqGujT3bthsI0rakvQW2u1MpYBHSFYGFI72pJcVS9qGpU5SnOsss6ZdFTTar/ZuPZnz2NFTA1TlaeIu2V097d8AU "JavaScript (Node.js) โ€“ Try It Online") ## How? We define **z** as the bitwise OR between **x** and **y**. ### Step #1 We first ensure that we are located in a specific quadrant by forcing both **x** and **y** to be non-negative. As long as **z < 0** (which means that either **x** or **y** is negative), we process the recursive call **f(-y, x)**: ``` (+1, -2) --> (+2, +1) (-1, +2) --> (-2, -1) --> (+1, -2) --> (+2, +1) (-1, -2) --> (+2, -1) --> (+1, +2) ``` ### Step #2 While we have **z > 1** (which means that either **x** or **y** is greater than **1**), we recursively try the two moves that bring us closer to **(0, 0)**: **f(x-1, y-2)** and **f(x-2, y-1)**. We eventually keep the shortest path. ### Step #3 When **z** is less than or equal to **1**, we're left with 3 possibilities which are processed with `z*3^x&y` (we could use `z*3-x*y` instead): * **x & y == 1** implies **x | y == 1** and means that **x = y = 1**. We need two more moves to reach **(0, 0)**: [![2 moves](https://i.stack.imgur.com/Si6GM.png)](https://i.stack.imgur.com/Si6GM.png) * **x & y == 0** and **x | y == 1** means that we have either **x = 1** / **y = 0** or **x = 0** / **y = 1**. We need three more moves to reach **(0, 0)**: [![3 moves](https://i.stack.imgur.com/MGSbD.png)](https://i.stack.imgur.com/MGSbD.png) * **x & y == 0** and **x | y == 0** means that we already have **x = y = 0**. *Graphics borrowed from [chess.com](https://www.chess.com/analysis-board-editor)* [Answer] # [Python 3](https://docs.python.org/3/), 90 bytes Thanks tsh for -11 bytes! `def f(x,y):x=abs(x);y=abs(y);s=x+y;return(.9+max(x/4,y/4,s/6)-s/2+(s==1or x==y==2))//1*2+s` [Try it online!](https://tio.run/##ZVBBbsMgELzziq16YQsOsZ1Wii0e49Ym5RCIwKnY1ztgmlMOuxpmpJlZbrT@etdv27wYMDxJwiHp6TvyhCPtgHCMOgkaw7Leg@OHs7hOiSd1kpQnqi9souoEj1q3PkDSmrTuEJVqPzoRd@tLtYZ3@PHzAib4Kxgb4gph@bPResfgJZeBNZCTs@9Qw6GvXI14kicG/yj4u5s5L/32VUJFe/hE1clKCJKpIUlNQtGh6rHJzyxjrppFxpzuj0dmyiFgs@PkLgtvnHQ4MCg0vdKlU/28N/289BasWwuWVZFVwO0B "Python 3 โ€“ Try It Online") (inline code formatting to avoid readers having to scroll. Sorry, but I have to golf my program) Very very efficient. --- ### How could I come up with this!? **1. Parity** Assumes that the whole board is colored in the checkerboard pattern (that is, cells with `x+y` odd and `x+y` even are colored with different colors). Note that each step must jump between two differently-colored cell. Therefore: * The parity of the number of steps must be equal to the parity of `x+y`. **2. Approximation** Assumes the knight starts from coordinate `(0,0)`, and have moved `n` steps, and is currently at `(x,y)`. For simplicity, assumes `x โ‰ฅ 0`, `y โ‰ฅ 0`. We can conclude: * Since each step `x` increases by at most `2`, `x โ‰ค 2ร—n`. Similarly, `y โ‰ค 2ร—n`. * Since each step `x+y` increases by at most `3`, `x+y โ‰ค 3ร—n`. Therefore, `n โ‰ฅ l(x,y)` where `l(x,y) = max(max(x,y)/2, (x+y)/3`. (note that we don't need to include `-x` or `x-y` in the formula because by assumption, `x โ‰ฅ 0 and y โ‰ฅ 0`, so `x+y โ‰ฅ max(x-y,y-x,-x-y)` and `x โ‰ฅ -x`, `y โ‰ฅ -y`) It turns out that `a(x,y) = round(0.4 + l(x,y))` is a good approximation to `n`. * Assume `a(x,y)` is an approximation with error less than `1`, the correct value is given by ``` f(x,y) = round((a(x,y) - (x+y)) / 2) * 2 + (x+y) ``` (round under subtracting `x+y` and dividing by 2) **3. Special cases that fails the formula** Assume `x โ‰ฅ 0` and `y โ‰ฅ 0`. There are 2 special cases where the algorithm fails: * `x == 1 and y == 0` or `x == 0 and y == 1`: The algorithm incorrectly returns `1` while the correct answer is `3`. * `x == y == 2`: The algorithm incorrectly returns `2` while the correct answer is `4`. So, just special-case those. Add the result by `2` if the value of `x` and `y` are one of those. [Answer] # [Python 2](https://docs.python.org/2/), 87 bytes ``` f=lambda z,a={0}:1-({z}<=a)and-~f(z,{k+1j**i*(2-i/4*4+1j)for k in a for i in range(8)}) ``` [Try it online!](https://tio.run/##Rc/LcoMgFAbgPU9xdoCVNiLxkil9km5ooymNQaNOp9Wxr24PpEk2DN/8cC7dz/jROrmutW7M6W1vYIqNnjfLLhFsnpZnbbhxe/Fbsymejw/JZxTZiElhn1SkkLxueziCdWDAX62/9sYdKlbwha@DppQCbGLAA8QLnuSfSWB6pQyUyOSe3nhJE2Tqmd5Sda@MVBIpw2OJLHyah8dbbKS2yCzzTHMCZYksS88sI8Knogx9FbK4j6GwVOIpLmPkuBMhft3GuspvPDwOXWNHRl8d5Tscq4vhDDrk18h/pdxnvXUj1Oy9PXVN9c2i6ss0rOOcg9ZYbWRnTtY/ "Python 2 โ€“ Try It Online") Takes input as a complex number `z = complex(tx, ty)`. [Answer] # TI-Basic, ~~86~~ 54 bytes Based on @user202729's older solution ``` Input :abs(X->C:abs(Y->D:C+Ans Ans+2int(.9+(S=1 or C=2 and D=2)-.5Ans+max({C/4,D/4,Ans/6 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes ``` `JEQ2J-htZjht_h@Z^2&sG=~}@Gg* ``` Input is a complex number with integer real and imaginary parts. The code is very inefficient. Its memory requirements increase exponentially with the output. It times out in TIO for the test cases with output exceeding 7. [**Try it online!**](https://tio.run/##y00syfn/P8HLNdDISzejJCoroyQ@wyEqzkit2N22rtbBPV3r/39DQ12jLAA) [Answer] ## Haskell, ~~79~~ 72 bytes ``` p l|elem(0,0)l=0|r<-[-2..2]=1+p[(x+i,y+j)|(x,y)<-l,i<-r,j<-r,(i*j)^2==4] ``` [Try it online!](https://tio.run/##HcxBCsMgFEXRrTjU@hU1GeoSugJJiwOhWg1iWkjAvVvr5HAHj/dyx9un1HtBqfnkMxYgSDKiVc0sU5yrzUhaLD5pgItG0vAJF9EsQdCsQvyDwy2ShzJm3Xp2YUcGZVfuT4RLDfuHF16@1RNk5zsM5VQN5Ww5e4FluM6NlMAU2VD/AQ "Haskell โ€“ Try It Online") Takes the input as [a singleton list](https://codegolf.meta.stackexchange.com/a/11884/34531) of pairs of numbers. A simple brute force. Needs a lot of time and memory for results > 8. Starting with a single element list of coordinates (the input), repeatedly add all positions that can be reached for every element until `(0,0)` is in this list. Keep track of the recursion level and return it as the result. Edit: -7 bytes thanks to @Lynn. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ ~~26~~ ~~25~~ 23 bytes ``` 1,-pแธคยต;Uร†แป‹ ยขแน—Sโ‚ฌ;0i 0รง1# ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//MSwtcOG4pMK1O1XDhuG7iwrCouG5l1Pigqw7MGkKMMOnMSP///8wKzFq "Jelly โ€“ Try It Online") Very slow; times out on TIO for outputs over 6. Takes a complex number as input. ### Explanation The code uses complex numbers because it was shorter in an intermediate step and it also seems a lot faster; you could also use pairs by removing `ร†i` and replacing `0` with `0,0` on the second line. ``` 1,-pแธคยต;Uร†แป‹ Helper link. No arguments. 1,- Get the pair [1,-1]. แธค Double each to get [2,-2]. p Cartesian product: get [[1,2],[1,-2],[-1,2],[-1,-2]]. ยต Start a new chain with the list of pairs as argument. U Reverse each pair. ; Append the reversed pairs to the list. ร†i Convert each pair [real,imag] to a complex number. ยขแน—Sโ‚ฌ;0i Helper link. Arguments: iterations, target ยข Call the previous link to get knight moves as complex numbers. แน— Get the iterations-th Cartesian power of the list. This will yield 8^n tuples containing move sequences. Sโ‚ฌ Sum each move sequence to get the resulting square. ;0 Add the starting square, since the zeroth iteration results in no move sequences. i Find the target squares (1-based) index in the results, or 0. 0รง1# Main link. Argument: target 0 Starting from 0, # find the 1 first number of iterations where รง calling the previous link results in a nonzero result. ``` [Answer] ## JavaScript (ES6), ~~90~~ 78 bytes ``` f=(x,y)=>y<0?f(x,-y):x<y?f(y,x):x+y<3?4-x-y&3:x-3|y-1?x-4|y-3?f(x-2,y-1)+1:3:2 ``` Edit: Saved 12 bytes thanks to @supercat pointing out that `x<0` implies either `y<0` or `x<y`. Explanation: This is a recursive solution. The first two conditions just ensure the right quadrant for the other conditions. The third condition generates the answer for coordinates near the origin, while the last two conditions deal with the other two special cases (1 byte shorter than testing both moves): ``` 0 32 2++ +2++ +++3+ ++++++ (etc.) ``` All squares marked `+` can be determined by moving directly towards the origin and then recursing. [Answer] # [Kotlin](https://kotlinlang.org), ~~148~~ ~~146~~ 140 bytes ``` fun s(x:Int,y:Int):Int=if(y<0)s(x,-y)else if(x<y)s(y,x)else if(x+y<3)4-x-y and 3 else if(x!=3||y!=1)if(x!=4||y!=3)s(x-2,y-1)+1 else 3 else 2 ``` [Try it online!](https://tio.run/##jVbbbts4EH3XV0yDYmvV8kWSYyfeuEbRbdFgLwHavAV5kG3a1kYXl6QSC02@PXuGlGzFSdsNEJnDuXLmzJA3uU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RooNL8uuZLE@5mGDlfYs7FPEVXkY5vhceZRcE1bXIV806XPsUSYN1EUlsd4BXdOeekYIznJtf7qn0RupAZb1ppKVSRaMZ/vKQWz/K@a5rBBoehVbpVMBc8bu5ihSggu@W4VMoXtYQ55L/0SOHCwiSAYNq1Sl/FPAdSObyfR2bF9@E1IqtAjksU4ZWN8OBx@0J0W/oNaWME8P0ZZ08cMTjipdVBP/Ep@tzGASZBF@l8Efq7dC1NsvVaCkF4wvAkWu5NRzNg3XNJFTMto3lVkFmOS9zMjIHp2lmsOU7bwQx8hLASWgHJuKyszt1aZFZxf5j@gSyQZcS2VgUc38jyibrNfOimVmC1qgSwcLDTIkx145Td@d1fVaPNcAltPZpD6Udwyd5oTB/4KCsCPYFZOb/BaLGZArDTXIqDor@aQO3@HmpY@a696Wx31GYHTbOcGEGLnNfriF8dtYbaiHmMtwk/JRgIEOMRg2FSSN6p6sazq9KIGndGVQqcUR4mhjZJoWodPO/shbILf7ALv0pX3V/1SxPDudZ@AmRUxYLGFCjkmCvfoXVhLgtrMXypE4zWzoDfMBDUWTbqgcNDi59ZtJCYK9JMqDSKs1YkV6q6ss@@aonkvHPpe@XMaJiXGZu7rXKraAIMQeFi2aqiq0mef/zq85o7AELoes8lkZ2gIekbyeCZpG8k/YYkIBC@JDkw3ps2@VEXmP9nwvzAG8HMcdiUx0NuOIT50TN5fvLx/3DYkK9ffh7efc80zDuQWU9OiQ3GxXMHYX3@5nn4qG49BT@hDcxjDA8OXCobITFxU74wGAMbFE8ftDO/5FoszXPO1I6Ly165mBW6J3i1sMxVH1eYWfjXFsjGZJK1jq5ef68kHjyq1v71w/XkqF2dgujo9Xdr8IHqFU0m1mBw/XDEJh/MmM2lYxYMQOfxPw "Kotlin โ€“ Try It Online") ]
[Question] [ Recently, I made a made a typo and I wrote [unicorn](https://codegolf.stackexchange.com/revisions/8f3e2c92-ba67-4354-a538-1609ca225307/view-source) instead of unicode, I did what any normal person would do and I made an [esolang](https://github.com/vihanb/Unicorn) out of it. In this challenge you will be writing a Unicorn interpreter. Because Unicorn programs are horrible long, you'll have to write a short interpreter to compensate for this. ## Example These are the transpiled result, not the actual interpreted result your program should output ``` ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ 1 ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ alert([x=(p=prompt())/2+Math.sqrt(p*p/4-prompt()),p-x]) ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„ ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ๐Ÿ "Hello, World!" ``` ## Specification * Unicorn is divided into "sections" which are space-separated * Each section represents a character * The number of unicorns (`๐Ÿฆ„`) in each section is converted to it's associated character (i.e. 32 unicorns -> `chr(32)` -> ). * If the section contains goats (`๐Ÿ`), the length of the amount of goats should be *doubled*, then converted to the associated character * If the section contains any other characters, the program should ignore the character. * Each section (character) should be joined to form a program * This resulting program should be evaluated in the language you have written the program in. (e.g. JavaScript's `eval`, Python's `exec`) * Unicorns are unicode `U+1F984`; goats are unicode `U+1F410`. * If you choose a compiled language, you may output/save the compiled, compiled unicorn code `๐Ÿฆ„` (unicorns) and `๐Ÿ` (goats) all count as one byte for this challenge. If your language doesn't support emojis, you may identify unicorns as (`u`) and goats as (`g`). You may not support emojis *and* `u`,`g` --- If you really want to see the ~~unicodes~~ unicorns, [here is a picture of this post](https://i.stack.imgur.com/cxfam.png) --- **+50 bounty:** to the shortest program in (the original) [Unicorn](https://github.com/vihanb/Unicorn) while being under 6500 chars. You must use [this](https://github.com/vihanb/Unicorn/tree/502b386698863d5973eaaaffb941eb1e21668085) version, it must run on Firefox, Chrome, or Safari. [Answer] # Unicorn (ES6), ~~5934~~ 5278 bytes Under the custom encoding, this is 5278 bytes (1 byte per char); but with UTF-8, it would 4 bytes per char (though only 1 for a space), or 20869 total. ``` (too many Unicorns and Goats to reasonably display here) ``` Instead, [here's a pastebin.](http://pastebin.com/txCaCpZ1) This Unicorn code transpiles to this JS snippet: ``` s=>eval(s.replace(/\S+ ?/g,c=>String.fromCharCode(c.length>>1<<c.charCodeAt()%2))) ``` Now, this isn't the shortest possible version; this is shorter: ``` s=>eval(s.replace(/\S+ ?/g,c=>String.fromCharCode(c.length>>1<<("๐Ÿฆ„">c)))) ``` However, the one unicorn in there would transpile to 56034 goats, thus multiplying the score by roughly 11. Here's the function I used to transpile to Unicorn: ``` function g(s){return s.replace(/./g,function(c){i=c.charCodeAt();return(i%2?"๐Ÿฆ„".repeat(i):"๐Ÿ".repeat(i/2))+" "}).slice(0,-1)} ``` ``` <textarea id=O cols=100></textarea><button id=P onclick="Q.value=g(O.value);R.innerHTML=(Q.value.length+Q.value.split(' ').length-1)/2">Run</button><br><textarea id=Q rows=10 cols=100>Output appears here.</textarea><br><p>Length: <span id=R>0</span><br></p> ``` Note: I haven't actually tested the program, as there isn't an online interpreter that I could find (although I suppose I could hook up the .js file to HTML...?) [Answer] # Pyth - ~~23~~ 17 bytes ``` .vsmC+/d\๐Ÿฆ„y/d\๐Ÿcz ``` [Try it online](http://pyth.herokuapp.com/?code=.vsmC%2B%2Fd%5C%F0%9F%A6%84y%2Fd%5C%F0%9F%90%90cz&input=%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84&debug=0). It works by splitting the input by spaces, then for each section counting the number of unicorns and number of goats \* 2 then adding them, then taking the char at the code point. It finished by summing the char array and pyth-evaling. [Answer] # Python ~~179~~ 176 bytes **EDIT**: I just learnt s.split(' ')=s.split() Here is the second "actual" programming language Unicorn interpreter. I call this version of Unicorn "UnicornPy" pronounced as "unicorn pie". I am making this much too official! ``` s=raw_input() s=s.replace('๐Ÿ','๐Ÿฆ„๐Ÿฆ„') s=s.replace('๐Ÿฆ„','u') for i in s: if i not in "ug ": s=s.replace(i,'') s=s.split() for i in s: s[s.index(i)]=chr(len(i)) exec(''.join(s)) ``` For some reason, it needs me to convert the unicorn and goat emojis to u and g. I do not know why. [Try it here!](http://ideone.com/Yw7CBL) [Answer] # Ruby, 78 Bytes ``` eval ARGV[0].gsub(/[^ug ]/,'').split.map{|b|(b.size*(b[0]=='u'?1:2)).chr}.join ``` It basically reads the first command line argument, splits it at every space character, maps the size of the block to the appropriate character and joins it all together. Edit: Forgot the requirement that all other characters should be ignored [Answer] # Unicorn ES6 (Invalid), 3379 bytes This is invalid because it uses the latest version of Unicorn with rainbows, sun with clouds, and sparkles. Thanks to @ETHproductions for the JS code to interpret unicorn. ``` code is in the paste bin below ``` Pastebin: <http://pastebin.com/raw/Q9Kd4ixA> This is only 3379 bytes if sparkles, sun/clouds, and rainbows also are 1 byte. [Answer] ## Mathematica, 118 bytes ``` a=StringCount;ToExpression@FromCharacterCode[If[#~StringTake~1=="u",#~a~"u",2IntegerLength[#~a~"g"]]&/@StringSplit@#]& ``` Performs exactly as described in the specification. I couldn't use emoji in Mathematica string literals without the interpreter exploding, so I used `u` and `g`. [Answer] # Rust, 426 bytes ``` use std::io::Write;macro_rules!c{($n:expr,$a:expr)=>(println!("{}",std::str::from_utf8(&std::process::Command::new($n).arg($a).output().unwrap().stdout).unwrap());)}fn main(){let d:String=std::env::args().skip(1).next().unwrap().split(' ').map(|s|s.chars().fold(0u8,|a,c|a+match c as char{'๐Ÿฆ„'=>1,'๐Ÿ'=>2,_=>0}) as char).collect();std::fs::File::create("o").unwrap().write_all(d.as_bytes()).unwrap();c!("rustc","o");c!("o","");} ``` This probably can be golfed the hell down, but type safety and checked errors are quite verbose. Since Rust is a compiled language, this program outputs the decoded program to a file and invokes the compiler on said file, then executes the resulting binary. Ungolfed: ``` use std::io::Write; macro_rules! command { ($name:expr,$argument:expr) => (println!("{}", std::str::from_utf8( std::process::Command::new($name) .arg($argument) .output() .unwrap() ));) } fn main() { let decoded: String = std::env::args() .skip(1) //ignore program name .next().unwrap().split(' ') //get first arg split on spaces //transform every section in a char .map(|section| section.chars() .fold(0u8, |accumulator, chr| accumulator + match chr as char { '๐Ÿฆ„' => 1, '๐Ÿ' => 2, _ => 0 }) as char) //convert iterator to string .collect(); std::fs::File::create("o").unwrap() .write_all(decoded.as_bytes()).unwrap(); command!("rustc", "o"); command!("o", ""); } ``` [Answer] # PHP, 83 ~~80~~ ~~86~~ ~~87~~ bytes ## Now Unicorn-ready For the cost of **3 bytes** I made this unicorn ready: ``` $a=mb_substr_count;foreach(explode(" ",$argv[1])as$b)echo chr($a($b,๐Ÿฆ„)+2*$a($b,๐Ÿ)); ``` Takes an input from command line, like: ``` $ unciorns.php "๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿ ๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„๐Ÿฆ„" ``` This will output `32`. **Demo** [Try before buy](https://3v4l.org/QLkmC) --- Unfortunately OS X 10.10.5 ~~doesn't support~~ is hiding Unicorns. Here's the alternative `ug`-approach (**80 bytes**): ``` $s=substr_count;foreach(explode(' ',$argv[1])as$c)echo chr($s($c,u)+2*$s($c,g)); ``` Takes an argument from command line, like: ``` $ php unicorns.php "uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuug uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu" ``` [Try the *ug*-version](https://3v4l.org/IQiSD) --- **Edits** * *Saved* **1 byte** due to massive refactoring. This version is already discarded again, since I managed to golf the original even further: [Demo discarded version](https://3v4l.org/McEoK) (**86 bytes**) ``` for($_=$argv[1].' ';$c=$_[$i++];)$t+=u==$c?1:(g==$c?2:(' '==$c?-$t+!print chr($t):0)); ``` * *Saved* **6 bytes** by replacing `for` with `foreach` * *Added* **3 bytes** making it *Unicorn-ready*. [Answer] # Ruby, 75 characters A nifty ruby interpreter that replaces all `๐Ÿฆ„` with `' '` (a space) and all `๐Ÿ` with `' '` (two spaces), and gets the length of each segment. I call this version of Unicorn ~~RubyUnicorn~~ *Rubycorn*. ``` ->s{eval s.split(a=' ').map{|r|r.gsub('๐Ÿฆ„',a).gsub('๐Ÿ',a*2).size.chr}.join} ``` [Answer] # Python 3, ~~94~~ 86 bytes This is a simple parser that works even if you mix `u` and `g` in one section. ``` s=input().split();exec(''.join(chr(sum([[0,2][j<"u"],1][j>"g"]for j in i))for i in s)) ``` As an example (using `u` and `g` in separate sections): ``` gggggggggggggggggggggggggggggggggggggggggggggggggggggggg ggggggggggggggggggggggggggggggggggggggggggggggggggggggggg uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu ggggggggggggggggggggggggggggggggggggggggggggggggggggggg gggggggggggggggggggggggggggggggggggggggggggggggggggggggggg gggggggggggggggggggg uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu ``` should parse to ``` print(1) ``` [Answer] # [Racket](https://racket-lang.org/), 200 bytes ``` (define(f s)(eval(read(open-input-string(list->string(map integer->char(map(ฮป(x)(foldl(ฮป(y a)(case y[(#\u)(add1 a)][(#\g)(+ a 2)]))0 x))(map string->list(string-split s)))))))(make-base-namespace))) ``` Ungolfed: ``` (define(f s) (eval(read(open-input-string (list->string ;;back to string (map integer->char ;;back to char (map(ฮป(x) (foldl(ฮป(y a) (case y [(#\u)(add1 a)] [(#\g)(+ a 2)])) 0 x)) (map string->list (string-split s))))))) ;;splitting by space, converting to list of chars (make-base-namespace))) ``` It starts by splitting the string into list of strings by spaces, then creates a list of chars per splitted string. Then each list of chars is reduced into a number by adding 1 if unicorn, 2 if goat. Finally, each list containing the sum is made a list of chars, then a string which is passed to eval. [Try it online!](https://tio.run/nexus/racket#zVRBjgIhELz7io5eurMhUR8wH3E9tEMPEhEJMEbf5h/80sjonPSg2UTXOlEVUlSlgYljbyByvZE8GqGWxnqBLCnPYGzuAeYFQPsJvBTF/K3Bf3V62g4@letL@r5xoO@4A4@mY@qGN4UNJELZs8MorHEXxCvrQ5tVytF6g86mrKqBbDmA9VmMRFXVa469gucTHgibndOuXx@BCWtOAscFTn5bQtZ6VsRlTw3hDzDMaUk0hQPR1fTmr6r@NBxICs7mEu@Gsm0jalVsleetpMC1FLkrDa7/AnUX) [Answer] # JavaScript, 140 154 141 bytes ``` var s='';i.split(" ").forEach((e)=>{s+=String.fromCharCode((e.split("๐Ÿฆ„").length-1)+2*(e.split("๐Ÿ").length-1));});console.log(eval(s)); ``` It splits the input string in an array of strings, using space as a needle. It then proceeds to count the amount of unicorns and goats\*2 and concatenate the summed result to what will be evaluated. More readable: ``` var s = ''; i.split(" ").forEach((e) => { s+=String.fromCharCode((e.split("๐Ÿฆ„").length-1)+2*(e.split("๐Ÿ").length-1)); }); console.log(eval(s)); ``` --- **Edit:** Updated code to accept an argument from CLI, use: `node unicorn.js "๐Ÿ๐Ÿฆ„ ๐Ÿฆ„๐Ÿฆ„"` ``` var s='';process.argv[2].split(' ').forEach((e)=>{s+=String.fromCharCode((e.split('๐Ÿฆ„').length-1)+2*(e.split('๐Ÿ').length-1));});console.log(eval(s)); ``` Ungolfed: ``` var s = ''; process.argv[2].split(' ').forEach((e) => { s+=String.fromCharCode((e.split('๐Ÿฆ„').length-1)+2*(e.split('๐Ÿ').length-1)); }); console.log(eval(s)); ``` --- **Edit 2:** Edited to accept input as a function parameter, use `node unicorn.js` ``` i=>{var s='';i.split(' ').forEach((e)=>{s+=String.fromCharCode((e.split('๐Ÿฆ„').length-1)+2*(e.split('๐Ÿ').length-1));});return eval(s);}; ``` Ungolfed: ``` i =>{ var s = ''; i.split(' ').forEach((e) => { s+=String.fromCharCode((e.split('๐Ÿฆ„').length-1)+2*(e.split('๐Ÿ').length-1)); }); return eval(s); }; ``` [Try it online!](https://tio.run/nexus/javascript-node#K0ssUkhUsP2faWtXXQZkF9uqq1tn6hUX5GSWaKgrqGvqpeUXuSYmZ2hopGoC1RRr2waXFGXmpeulFeXnOmckFjnnp6QCJWFaPsxf1gLUlZOal16SoWuoqW2khSw5YQKypKZ1raZ1UWpJaVGeQmpZYo5GMVDEmut/cn5ecX5Oql5OfrpGooYSSBulWIEahlATK4BCahQPLjzoUgkVU9uw9dhosh3NbtRO7qPJirbRPhoIo3l2tLoc9djQLqCpEppKwG7QfwA "JavaScript (Node.js) โ€“ TIO Nexus") [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 25 bytes ``` ~`๐Ÿ'๐Ÿฆ„๐Ÿฆ„'R'(๐Ÿฆ„+)%s*'{Lc}R do ``` ## Explained ``` ~ # Zero Space Segment `๐Ÿ # The String literal "๐Ÿ" '๐Ÿฆ„๐Ÿฆ„' # The String literal "๐Ÿฆ„๐Ÿฆ„" R # Replace, turning all goats into twonicorns '(๐Ÿฆ„+)%s*' # The pattern string "(๐Ÿฆ„+)%s*", which is "A fewnicorns, then as much whitespace as possible, or none. {Lc}R # Replace with the result of the function, which converts the captured subgroup to it's Length, then to a char. do # Straight up do it. ``` Once again, RProgN falls into the trap of being consistently okay. [Try it online!](https://tio.run/nexus/rprogn#@1@X8GH@hAnqH@YvawFh9SB1DRCtralarKVe7ZNcG6SQkv///3@QKkqxAjUMoSZWgHl7FA8ePOhSCRVT27D12GiyHc1u1E7uo8mKttE@GgijeXa0uhz12NAuoKkSmgA "RProgN โ€“ TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), 67 bytes ``` {use MONKEY-SEE-NO-EVAL;EVAL [~] .wordsยป.&{chr m:g/\๐Ÿฆ„/+2*m:g/\๐Ÿ/}} ``` [Answer] # SmileBASIC, 125 bytes ``` INPUT S$WHILE LEN(S$)R=ASC(POP(S$))IF R-32THEN C=C+!(R-117)+2*!(R-103)ELSE O$=CHR$(C)+O$C=0 WEND SAVE"TXT:@",CHR$(C)+O$EXEC"@ ``` Using PRGEDIT to execute the code without saving would have been a lot nicer, but also a lot longer. code: ``` INPUT CODE$ 'making the user type 1000s of characters just so I could save 2 or 3 WHILE LEN(CODE$) CHAR$=POP(CODE$) 'I convert the code backwards, since POP( is shorter than SHIFT( IF CHAR$==" " THEN UNSHIFT OUT$,CHR$(CHAR) CHAR=0 ELSE INC CHAR,(CHAR$=="u")+(CHAR$=="g")*2 ELSE WEND SAVE "TXT:@",CHR$(CHAR)+OUT$ EXEC "TXT:@" ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` รผโ”ด(gร‡%โ•ฉ[โ†‘รท>7โ™ซโ–‘ ``` [Run and debug it](https://staxlang.xyz/#p=81c128678025ca5b18f63e370eb0&i=%F0%9F%A6%84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%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F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0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F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F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F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0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F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0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%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%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%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84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%0A%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%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F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9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F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90+%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84%F0%9F%A6%84+%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90%F0%9F%90%90&m=2) ]
[Question] [ Here are the letters of the English alphabet in order by frequency: ``` e t a o i n s h r d l c u m w f g y p b v k j x q z ``` That is, `e` is the most frequently used letter, and `z` is the least common. (Data from [Wikipedia](http://en.wikipedia.org/wiki/Letter_frequency).) Your challenge is to take some ROT-n'd text, such as: ``` ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz ``` This is the text "thisisaverysecretmessagethatisverysecureandsafe" that is "encrypted" through ROT-21 (half of 42). Your program, using the frequency table above, should be able to determine by how much each character was rotated and the original text. (If you are not familiar with ROT-n, it is essentially shifting each character by `n`. For example, in ROT-2, `a -> c, b -> d, ..., x -> z, y -> a, z -> b`.) How, you ask? The (very naive) algorithm you must use is: * for each `n` from `0` to `25` inclusive, apply ROT-`-n` to the input string. (Negative `n` because we want to *reverse* the encryption. ROT-`-n` is equivalent to ROT-`26-n`, if that's any easier.) * convert each input string to a number by adding up the relative frequencies of the characters. `e` is `0`, `t` is `1`, `a` is `2`, etc. For example, the corresponding number for the string `"hello"` is 7 + 0 + 10 + 10 + 3 = 30. * find the string that has the lowest corresponding number. * output that string and its corresponding `n`. Rules: * input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.) * you may use a different algorithm, as long as it always produces identical results. For example, having `z` be 0 and `e` be 25 and choosing the highest number is also okay. * if two strings have identical scores, you can choose to output either one (or both) of them. This is an edge case and you do not have to account for it. * this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win! Test cases: Input: `ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz` Output: `21 thisisaverysecretmessagethatisverysecureandsafe` Input: `pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom` Output: `8 hellopeopleofprogrammingpuzzlescodegolfstackexchange` Input: `ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq` Output: `12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe` Input: `jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv` Output: `2 hereisthefinaltestcasethatyoumustdecrypt` In case you were wondering, [here is a JSFiddle of the JavaScript test code I wrote, which successfully decrypted all the test cases I threw at it.](http://jsfiddle.net/qLZ7W/2/) [Answer] ## Haskell - ~~192~~ 175 ``` f y=sum.map(\x->length.fst$break(==x)y) main=interact(\s->snd$minimum$[(f"etaoinshrdlcumwfgypbvkjxqz"r,show(26-n)++" "++r)|n<-[0..25],let r=map(\x->([x..'z']++['a'..])!!n)s]) ``` Running ``` % ./rot-n <<< "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom" 8 hellopeopleofprogrammingpuzzlescodegolfstackexchange ``` [Answer] # GolfScript, ~~112~~ ~~108~~ ~~102~~ 100 characters ``` {{}/]{97-}%}:b~:|;"etaoinshrdlcumwfgypbvkjxqz"b:f,:&,{:x[|{&x-+&%f?}%{+}*\]}%$0=1=:x|{&x-+&%97+}%''+ ``` I'm not happy about the repetition with the re-decrypting at the end, but meh. Ungolfed (if that makes any sense :P) and slightly older version: ``` # store input IDs (a = 0, b = 1, etc.) in s [{}/]{97-}%:s; # store frequency data IDs in f (blah, repetition) "etaoinshrdlcumwfgypbvkjxqz"[{}/]{97-}%:f # for each number from 0 to 26 (length of previous string left unpopped)... ,,{ # the number is x :x; # return an array of... [ # the score s{x 26\-+26%f?}%{+}* # and the n x ] }% # use $ort to find the n to output $0=1=:x # get the string that the n corresponded to (blah, more repetition) s{x 26\-+26%97+}%''+ ``` [Answer] # GolfScript - 87 The cheat here is to build every rotation simultaneously. Since we need to loop over every ROT then every character, let's just loop over every character, slice the whole alphabet, then zip it up. From there proceed as expected: count the score for each ROT and choose the minimum. Extra golfed: ``` {97- 26,{97+}%.+''+>}/]{27<}%zip:d{{"etaoinshrdlcumwfgypbvkjxqz"?}%{+}*}%.$0=?.26\-\d= ``` Only a little golfed: ``` # the alphabet, and by frequency 26,{97+}%.+''+:a; "etaoinshrdlcumwfgypbvkjxqz":f; # build evey ROT decryption {97-a>}/]{27<}%zip:d # calculate likelihood {{f?}%{+}*}%. # find min $0= # output rotation factor and decryption ?.26\-\d= ``` [Answer] ## JavaScript (205) ``` f='zqxjkvbpygfwmucldrhsnioate';a='abcdefghijklmnopqrstuvwxyz';for(s=prompt(o=m=n=0) ,i=27;i--;w>m&&(m=w,n=i,o=u))for(u='',w=c=0;c<s.length;w+=f.indexOf(x))u+=x=(a+a)[a .indexOf(s[c++])+i];alert((26-n)+' '+o) ``` I think it can still be golfed a bit more, so suggestions welcome! Some notes to help understand the solution * `m`, `n`, and `o` track the highest score. * `u` and `w` track the character and value result, respectively for the current `i` * `(a+a)` helps prevent overflow when wrapping around past `z`, and is shorter than doing `%26` * I have the frequency in reverse order so I can search max instead of min. Proof: <http://jsfiddle.net/J9ZyV/5/> [Answer] ## C# + Linq - ~~273~~ 264 As a function which takes the input string and returns the decoded string & offset (as per requirements): ``` static Tuple<string,int> d(string s){var r=Enumerable.Range(0,25).Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))).OrderBy(x=>(from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)).Sum()).First();return Tuple.Create(r,(s[0]-r[0]+26)%26);} ``` Ungolfed with comments: ``` static Tuple<string,int> d(string s) { var r=Enumerable.Range(0,25) // for every possible offset i .Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))) // calculate rot_i(input string) .OrderBy( // order these by their score x=>( from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c) // lookup frequency of each character ).Sum() // and sum each frequency to get the score ).First(); // get the first one (lowest score) return Tuple.Create(r,(s[0]-r[0]+26)%26); // compute offset and return results } ``` --- Little test driver (remember to compile referencing `System.Core` for Linq): ``` using System; using System.Linq; namespace codegolf { class Program { static Tuple<string,int> d(string s){var r=Enumerable.Range(0,25).Select(i=>string.Concat(from c in s select (char)((c-97+i)%26+97))).OrderBy(x=>(from c in x select "etaoinshrdlcumwfgypbvkjxqz".IndexOf(c)).Sum()).First();return Tuple.Create(r,(s[0]-r[0]+26)%26);} static void Main(string[] args) { while (true) { var input = Console.ReadLine(); if (input == null) break; var retval = d(input); Console.WriteLine(String.Format("{0} {1}", retval.Item2, retval.Item1)); } } } } ``` Giving: ``` $ mcs /reference:System.Core.dll main.cs && mono ./main.exe ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz 21 thisisaverysecretmessagethatisverysecureandsafe pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom 8 hellopeopleofprogrammingpuzzlescodegolfstackexchange ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq 12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv 2 hereisthefinaltestcasethatyoumustdecrypt thisisaverysecretmessagethatisverysecureandsafe 0 thisisaverysecretmessagethatisverysecureandsafe ``` [Answer] # dg - 137 130 129 128 bytes ``` f=t->min key:(t->sum$map 'etaoinshrdlcumwfgypbvkjxqz'.index$snd t)$map(n->n,''.join$map(c->chr$((ord c + 7-n)%26+ 97))t)(0..26) ``` Examples: ``` >>> f 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz' (21, 'thisisaverysecretmessagethatisverysecureandsafe') >>> f 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom' (8, 'hellopeopleofprogrammingpuzzlescodegolfstackexchange') >>> f 'ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq' (12, 'thiswasencryptedwithrottwelvesoitmustbeperfectlysafe') >>> f 'jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv' (2, 'hereisthefinaltestcasethatyoumustdecrypt') ``` Ungolfed code: ``` func = t -> #: Compute the score of the text `t` with respect to the frequency table. #: score :: (int, str) -> int score = t -> sum $ map 'etaoinshrdlcumwfgypbvkjxqz'.index $ snd t #: Compute rot-n of the string `t`. Return the offset and the shifted text. #: rot :: int -> (int, str) rot = n -> n, ''.join $ map (c->chr $ ((ord c + 7 - n) % 26 + 97)) t # return the minimum (computed by `score`) amongst all shifted messages min key: score $ map rot (0..26) ``` [Answer] # J - 92 char A bit of an ugly duckling, but it works. Outputs the number and then the string, on two lines. ``` (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:) ``` If you want them to be on the same line, space separated, this only goes up to **93 char**, but takes an uglier route. ``` ((":@],[:u:32,97+26|-)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])@(7+3&u:) ``` An explanation for `(/:'ctljapqhewvknfdsyigbmuoxrz')`: In this verb, we operate on the letter values as A=0, B=1, C=2, etc. To encode the letter values of the string `etaoinshrdlcumwfgypbvkjxqz`, the shortest way is actually to take the sort permutation for this weird string. This is because A is at index 4, B at index 19, C at 0, D at 14, and so on; hence the sort permutation is `4 19 0 14 8 13 ...` when you grade (`/:`) it, and you get exactly the number values for `etaoin...`. Usage: ``` (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:) 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz' 21 thisisaverysecretmessagethatisverysecureandsafe NB. naming for convenience f =: (26|](-1!:2&2&.":)(/:'ctljapqhewvknfdsyigbmuoxrz')+/@i."1(i.<./@:)26|(i.-27)+/])&.(_97+3&u:) f 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom' 8 hellopeopleofprogrammingpuzzlescodegolfstackexchange f 'wtaad' 0 wtaad ``` [Answer] # q, 97 ``` {(w;m w:g?min g:(+/')("etaoinshrdlcumwfgypbvkjxqz"!t)m:(t!u!/:rotate[;u:.Q.a]'[(-)t:(!)26])@\:x)} ``` . ``` q) tests:( "ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvazocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz"; "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom"; "ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq"; "jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv") q) f:{(w;m w:g?min g:(+/')("etaoinshrdlcumwfgypbvkjxqz"!t)m:(t!u!/:rotate[;u:.Q.a]'[(-)t:(!)26])@\:x)} q) f each tests 21 "thisisaverysecretmessagethatisverysecureandsafethisisaverysecretmessagethatisverysecureandsafe" 8 "hellopeopleofprogrammingpuzzlescodegolfstackexchange" 12 "thiswasencryptedwithrottwelvesoitmustbeperfectlysafe" 2 "hereisthefinaltestcasethatyoumustdecrypt" ``` [Answer] # APL - 70 characters ``` Fโ†{โ†‘โ‹+/'etaoinshrdlcumwfgypbvkjxqz'โณโŠƒ(โณ26){l[(โบโŒฝlโ†โŽ•UCS 97+โณ26)โณโต]}ยจโŠ‚โต} ``` Example: ``` F 'ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz' 21 F 'pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom' 8 F 'ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq' 12 F 'jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv' 2 ``` I'm sure there are ways to compress this further, and I invite any other APL users to come up with solutions for that. [Answer] # Python 188 ``` x="abcdefghijklmnopqrstuvwxyz" y=input() r=lambda n:"".join(x[x.find(i)-n]for i in y) s={sum("etaoinshrdlcumwfgypbvkjxqz".find(b)for b in r(a)):(a,r(a))for a in range(26)} print(s[min(s)]) ``` [Answer] Perl: 256 char (plus newlines for readability) including the frequency table: ``` @f=unpack("W*","etaoinshrdlcumwfgypbvkjxqz"); @c=unpack("W*",<>);$m=ord("a");$b=1E10; for$n(0..25){$s=0;$t=""; for$x(0..scalar@c){$r=($c[$x]-$n-$m)%26+$m;$t.=chr($r); for(0..scalar@f){if($r==$f[$_]){$s+=$_}}} if($s<$b){$b=$s;$w=$t;$a=$n}} printf"%d %s\n",$a,$w; ``` Text is provided like so: ``` echo "ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz" | perl ./freq.pl 21 thisisaverysecretmessagethatisverysecureandsafewm ``` Take off 12 char if you want to bake-in the values of ord(a) and the length of @f [Answer] # Elm - 465 Not going to win any golfing awards, but it makes a static webpage which displays a list of the form `[(rotation number, rotated string)]` as you type. *Note: not yet working [here](http://share-elm.com) but you can copy-paste it into [the official editor](http://elm-lang.org/try) and run it.* ``` import String as S import Char (..) import Graphics.Input (..) import Graphics.Input.Field (..) f="ETAOINSHRDLCUMWFGYPBVKJXQZ" r s n=let t c=mod(toCode c-65+n)26+65 in map(fromCode . t)(S.toList s) w s=case s of ""->0 s->sum(S.indexes(S.left 1 s)f)+w(S.dropLeft 1 s) b s=sort<|map(\x->((w . S.fromList . r s)x,(26-x,S.fromList<|r s x)))[0..25] c=input noContent main=above<~(field defaultStyle c.handle id""<~c.signal)~(asText . b . .string<~c.signal) ``` [Answer] # Python 2, 171 ``` f,R,i='zqxjkvbpygfwmucldrhsnioate',{},raw_input();a=sorted(f)*2 for n in range(26):_=''.join(a[ord(x)-71-n]for x in i);R[sum(2**f.index(x)for x in _)]=n,_ print R[max(R)] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 142 bytes ``` ->s{(0..25).map{|i|[*s.map{["etaoinshrdlcumwfgypbvkjxqz".chars.index(c=((_1.ord-97-i)%26+97).chr),c]}.transpose.map{_1.reduce:+},i]}.min[1..]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY9NTsMwEIX3nGJUqVJCG4tWglKksuwlogg5TkJMG9ux8-s2V-ACbCIEZ0LchonbDbI8743n84z98aXruB8_97vvusqCx9_34NmcvDtC1vc-Kag6nfk5vDXOhrO0opILk-vkyOqizV57FTeHt660M8Jyqg3hIkk7j-0872VFpE6C7Sbg_nz9sNhufGS0v2TRQCpNhVHSpK4xojpNapY-LYYlx3LBRbgiJBqur_pRsA_nbSiBQQLC7QZKsFBAhd5Ch86ChByjcNXY5QyddPx_Wjm-AQ69oynYKLq5jlEOrKB1badYORXoLKrEyKHGVbr2HY7JcU0UhQMSR3QSdRpH8SkcTw2eZagKs-lWEUWX743jRf8A) [Answer] # [Python](https://python.org) + [`golfing-shortcuts`](https://github.com/nayakrujul/golfing-shortcuts), ~~165~~ 161 bytes A port of [gcq's answer](https://codegolf.stackexchange.com/a/24812/114446). ``` from s import* def F(Y):R=lambda N:sj("",(Sl[Sl.find(I)-N]for I in Y));S={s("etaoinshrdlcumwfgypbvkjxqz".find(B)for B in R(A)):(A,R(A))for A in r(26)};p(S[q(S)]) ``` [Answer] # [R](https://www.r-project.org), 140 bytes ``` \(e,u=utf8ToInt,x=u(e)-97)c(n<-which.min(sapply(25:0,\(z)sum(match((x+z)%%26,u("etaoinshrdlcumwfgypbvkjxqz")-97)))),intToUtf8((x-n)%%26+97)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBNTsMwEIX3HCNSJUdNEKoEFEQPwL7sunEcO3Zcj-3Ef_EZuAGbskDiSlyCMxBKhDqb0czom_dm3t6H02dLyTAZt_vwjtXbr9cDopXfzcV2r5_BVWnnES3rh_uSIHiqIxeEXysBaMTGHCe0uX28qQ4ol6NXSGFHOEJpncvVanNXeVRQh7WAkQ_tkXgVWTeZJsg-2Vyct85RCXB7_TJLzmgNZ3T9O1o8fS8eUaFJCy0Em5WDnFTWPAOEJmsSdAtL26gcxAQBzwpX_6hRzsWkYnIqQspRZ-G9DToRzp3CMh6Vjg5wI-SomDQiaHXJM-epUNRm3cqGWSM8cy1mTNjELcWeTR1lYBvbDlazJKka7CXfd66TPvQdl4ZA6HygxHehJwHbqKMPrJtfNYRiufp0-ss_) ]
[Question] [ Your task is to output all possible ways to end a game with a tie (all rows, columns, and diagonals are completely filled and do not have 3 X's or 3 O's, and there are exactly 5 X's and 4 O's in total) in [Tic-Tac-Toe](https://en.wikipedia.org/wiki/Tic-tac-toe) (assuming X goes first): ``` OXO XXO XOX OXX XOX OOX XOX XOO XOX XXO OXO OXX XOX XOX OXX XXO OOX XOO XOO OOX XXO OXX XOX XOX XOX OXX OXO XOO XXO XXO OXX OXX OXO OOX XOX XXO OXO XXO XOX OOX XXO OXX OXX XXO XOX XOO OXO OXX ``` (It does not need to be arranged in the above way.) ## Rules * Output can be in any convenient format. * You may use different characters to represent X and O as long as they are distinct. * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โ€œล“NZjrโฝโพฦˆโ€˜+โนBUฦฌ ``` A niladic Link that yields a list of lists of lists (a 2 by 8 array of flattened boards) with `1`s representing `X`s and `0`s representing `O`s. **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//4oCcxZNOWmpy4oG94oG@xojigJgr4oG5QlXGrP// "Jelly โ€“ Try It Online")** Or see them in the format and order given in the question [here](https://tio.run/##y0rNyan8//9Rw5yjk/2isooeNe591LjvWMejhhnajxp3OoUeW/P/0KKHu/qiDY10zHVMdAxNdYx0DIG0gY6ZjqmOpY6hsY6hjqGhjoUOkGEW@3B3d/GjpjXGxSZRQArIAxoX4Z8FZINQ4z4FhUggIwvIOrTt0Lb/AA "Jelly โ€“ Try It Online"). ### How? Using only reflection in one axis is terser than using four rotational symmetries like in my original 16-byte code (below). ``` โ€œล“NZjrโฝโพฦˆโ€˜+โนBUฦฌ - Link: no arguments โ€œล“NZjrโฝโพฦˆโ€˜ - Code page indices = [30,78,90,106,114,141,142,156] +โน - add 256 -> [286, 334, 346, 362, 370, 397, 398, 412] B - to binary ฦฌ - collect up while distinct applying: U - reverse each ``` --- ##### Previous @16 bytes: ``` โ€œโพโฝส โทโ€˜แธคBsโ‚ฌ3Zแนš$ฦฌโ‚ฌ ``` A niladic Link that yields a list of lists of lists of lists (a 4 by 4 array of 2d boards) with `1`s representing `O`s and `0`s representing `X`s. **[Try it online!](https://tio.run/##AS0A0v9qZWxsef//4oCc4oG@4oG9yqDigbfigJjhuKRCc@KCrDNa4bmaJMas4oKs//8 "Jelly โ€“ Try It Online")** Or see them in the format and order given in the question [here](https://tio.run/##y0rNyan8//9Rw5xHjfseNe49teBR4/ZHDTMe7ljiVPyoaY1x1MOds1SOrQEy/x9a9HB3N1CZf0QUkAsUB5MzgaRStKGOsY6BjmFsFpAHQo37FBQigYwsIOvQtkPb/gMA "Jelly โ€“ Try It Online"). ### How? ``` โ€œโพโฝส โทโ€˜แธคBsโ‚ฌ3Zแนš$ฦฌโ‚ฌ - Link: no arguments โ€œโพโฝส โทโ€˜ - Code page indices = [142,141,165,135] แธค - double -> [284,282,330,270] B - to binary -> [[1,0,0,0,1,1,1,0,0], [1,0,0,0,1,1,0,1,0], [1,0,1,0,0,1,0,1,0], [1,0,0,0,0,1,1,1,0]] sโ‚ฌ3 - split each into threes -> [[[1,0,0], [0,1,1], [1,0,0]], [[1,0,0], [0,1,1], [0,1,0]], [[1,0,1], [0,0,1], [0,1,0]], [[1,0,0], [0,0,1], [1,1,0]]] โ‚ฌ - for each: ฦฌ - collect up while distinct applying: $ - last two links as a monad: Z - transpose } แนš - reverse } - together these rotate a quarter ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~142~~ ~~138~~ ~~123~~ ~~120~~ ~~112~~ 111 bytes -8 bytes thanks to [@fireflame](https://codegolf.stackexchange.com/users/68261/fireflame241) -1 byte thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) ``` X=x-[0...3]4+.5 \mod([23312905373,30555191537,48690981746,53478745886]/2^{3\floor(y)+\floor(X)},2)>.99\{0<X<3\} ``` [Try It On Desmos!](https://www.desmos.com/calculator/f841kp0vis) [![Rendered in desmos](https://i.stack.imgur.com/Gh7um.png)](https://i.stack.imgur.com/Gh7um.png) [Answer] # [///](https://esolangs.org/wiki////), 97 bytes ``` /g/ \/\///a/OXOgb/XXOgc/XOXgd/OXXge/XOOgf/OOX /abcdccdbcdaeabcf cfcefeefbbddbddb cbadbdccafcbcead ``` [Try it online!](https://tio.run/##ZY47DgMxCER7n8I34Ci0FNvws1Ok8/3l4M/GWUUy@Gk0DLQ3t5e33qFCvuACAAYkrAIUXYGQqoVC1YOxFkCkDCxqqhadPbgkLerFvYiYjZdUOECVi4o6W@8Rm2lUBETg/L/8o08fYn74o9INaxA34@E9sELoj2fAEvFhOJfgWbA335cM3wc "/// โ€“ Try It Online") I tried rearranging them so that more duplicates would appear together but it didn't save any bytes. I'm sure theres more that can be done here though. Good luck to whoever takes this on in Regenerate, I did not have the guts. Note: /// programs do not take any input, so don't worry about the input being used in the TIO link, lol. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes ``` ยป~qว”:แน™โ‹ยปโ‚†ฯ„ยฆโ‚ˆ+b:RJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu35xx5Q64bmZ4oGLwrvigobPhMKm4oKIK2I6UkoiLCJ24bmFdsKyduKBi2BcXG5cXG5gamAxMGBgWE9gxL8iLCIiXQ==) Port of 05AB1E thanks to Steffan. ``` ยฆ # Cumulative sums of... โ‚†ฯ„ # Base 64 digits of... ยป~qว”:แน™โ‹ยป # Compressed integer โ‚ˆ+ # + 256 b # Convert each to binary :RJ # Append each matrix reversed ``` [Answer] # [R](https://www.r-project.org/), ~~113~~ ~~111~~ 110 bytes *Edit: -1 byte, and from that idea -1 more, and then another -1 more, all thanks to pajonk* ``` for(i in 0:511)sum(a<-matrix(i%/%2^(0:8)%%2,3))==5&all(rowSums(rbind(a,t(a),diag(a),a[1:3*2+1]))%%3)&&print(a) ``` [Try it online!](https://tio.run/##FctBCsIwEEDRq3STMKMRm4RCCfYULkVhpCgDTVKmDXr7aFZ/877U@soC3HHq@jBYi1uJQJdTpF34C6zOyj2gDyMq5YxHnKZB07KA5M@1xA3kyWkGMjsQmpnp3Uo3G/zBHe0d/59HrVfh1EitPw "R โ€“ Try It Online") Outputs tic-tac-toe matrices using `1`s for Xs and `0`s for Os. Calculates 3x3 matrices of binary digits of 0...511, and checks whether any of the column sums, row sums, diagonal or antidiagonal are equal to zero modulo 3 (meaning that they're all Xs (3 = 0 mod 3) or all 0s (0)). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~90 ...~~ 45 bytes ``` "s*. -0 ".bytes{|k|puts"%09b"%$.+=k} ``` [Try it online!](https://tio.run/##KypNqvz/X6lYS4BDj4lH14CHk51DmpFPSS@psiS1uLomu6agtKRYSdXAMklJVUVP2za79v9/AA "Ruby โ€“ Try It Online") ## How it works: * If we can flatten the array, this means we only have to output 16 numbers between 115 and 412. * Instead of using the numbers directly, I sort them and use the successive difference. This limits the range to 1-115, which is within the boundaries of ASCII [Answer] # [Python 3](https://docs.python.org/3/), 64 bytes * -2 bytes suggested by pxeger. ``` for i in'ฦลŽลฃรฅยฤžลฒรฑฦŽลชรฃยญฦœลšsยต':print(f"{ord(i):09b}") ``` [Try it online!](https://tio.run/##AUsAtP9weXRob24z//9mb3IgaSBpbifGjcWOxaPDpcKdxJ7FssOxxo7FqsOjwq3GnMWac8K1JzpwcmludChmIntvcmQoaSk6MDlifSIp//8 "Python 3 โ€“ Try It Online") A really boring answer. Or [65 bytes](https://tio.run/##AUwAs/9weXRob24z//9mb3IgaSBpbifWjdWO1aPTpdKd1J7VstOx1o7VqtOj0q3WnNWa0bPStSc6cHJpbnQoYmluKG9yZChpKSlbNDpdKf//) without unprintable. --- And this is a (somehow) interesting [94 bytes](https://tio.run/##Fci7DYAgFADAVYiVWAnKR5egJUEKfEikQYIUOj3GKy@/9bzS1FouMdV@MJ3SSmmt9JY681fEqzXrZMNVUEQxobuWfnwo5QJmTzgsnggpAmEjk57x3ZEZhHNwHNRxKiFgi1v7AA) answer: ``` print(*["OXOOXXOX\n"[int(i):][:3]for i in str(0x2267c4d16c9d1787f15058d56ba14c7aacee2a628cf)]) ``` -2 bytes suggested by G B. Maybe it can be golfed more. [Answer] # [brainf\*\*\*](https://github.com/TryItOnline/brainfuck), 264 bytes ``` -.-.+.-.+.-..+.-.>.<..+...-...+.>.<.-...+...-..>.<.+.-.+..-...+.>.<.-...+..-.+.-.>.<.+.-..+...-..>.<..+...-..+.-.>.<.+.-...+..-.+.>.<.-....+...-.>.<.+.-.+.-..+.-.+.>.<.-.+..-...+.-.>.<.+...-....+.>.<.-.+.-..+.-.+.-.>.<..+..-...+..>.<..-...+..-..>.<.+.-..+.-.+.-.+. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fV09XTxuKwYSdng2IoQfiA2kQF8ICi4C4EOWY8rpw/VDD4DpgbBR5mBaYCVBFCBugGmAq4FbC1OjBtMHk4RoQvoDaA@bC7UR2I8z3//8DAA "brainfuck โ€“ Try It Online") Outputs the games separated by nulls. `รฟ` is `O` and `รพ` is `X`. It's hard-coded, manipulating address 1 to switch between `255` (`รฟ`) and `254` (`รพ`) as needed. After each game, `>.<` moves the pointer to address 2, prints `0` (null), and returns to address 1. A few bytes were saved by modifying the order of the games. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~19~~ ~~18~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` โ€ขโ€œยช?โ€™รฌยฆยพร”*โ€ขbยบ9รด ``` -9 bytes thanks to *@CommandMaster* Outputs the results as a list of flattened strings, each consisting of nine `1`/`0` for `X`/`O` respectively. [Try it online.](https://tio.run/##ATwAw/9vc2FiaWX//@KAouKAnMKqP@KAmcOswqbCvsOUKuKAomLCujnDtP924oCeT1h5U8OoM8O0SsK7LMK2P/8) (Feel free to remove the footer that pretty-prints the results to see the actual result.) **Explanation:** ``` โ€ขโ€œยช?โ€™รฌยฆยพร”*โ€ข # Push compressed integer 2639961594228296764259 b # Convert it to binary: 100011110001110011010011101010101101010110101011100011011100101101100011 ยบ # Mirror it: 100011110001110011010011101010101101010110101011100011011100101101100011110001101101001110110001110101011010101101010101110010110011100011110001 9รด # Split it into parts of size 9: ["100011110","001110011","010011101","010101101","010110101","011100011","011100101","101100011","110001101","101001110","110001110","101011010","101101010","101110010","110011100","011110001"] # (after which the list is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `โ€ขโ€œยช?โ€™รฌยฆยพร”*โ€ข` is `2639961594228296764259`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ๏ผฆโชชโ€{โˆจIโฆ„โ†ถrโ†˜Gโ€โนยซโŽšโชชฮนยณ๏ผฆโดยซ๏ผคโŸฒยปยปโ€–๏ผฆยณยซ๏ผคโŸฒ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBI7ggJ7NEQ8k/AgQhyB9IQrggpr@SjoKlpqZCNRenc05qYpGGpjUXZ0BRZl4JVG@mjoKxJkgQbJ4JWCWnS2luAVglZ1B@SWJJKphdy1XLFZSalpOaXALig9Ubg9XDlSNU1/7//1@3LAcA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Outputs all 16 3ร—3 boards consecutively without vertical separation. Explanation: ``` ๏ผฆโชชโ€{โˆจIโฆ„โ†ถrโ†˜Gโ€โนยซ ``` Split the compressed string `OXOXOXXOXXOXOOXXXOXOXXXOOXO` into three substrings of 9 letters and loop over each substring. ``` โŽš ``` Clear the canvas. ``` โชชฮนยณ ``` Split the substring into three substrings of three letters and print each on its own line. ``` ๏ผฆโดยซ ``` Repeat four times: ``` ๏ผค ``` Output the current canvas state. ``` โŸฒ ``` Rotate the canvas. ``` ยปยปโ€– ``` Reflect the last board. ``` ๏ผฆยณยซ๏ผคโŸฒ ``` Manually output three rotations, and allow the final rotation to implicitly print. Since the output is difficult to read, here's a 38 byte version which spaces out the boards: [Try it online!](https://tio.run/##RY2xCkIhFIZnfYqDk4JNtyUaawrCuC0NLSJekuwqYjWEz27qjcSD/D985zvqJoNy0uY8uQD07K2JlIhLfcuI8i@1RkE4bBiDD0Y7q2WgbIvRKZi5bF1n0ttR@p/NcBgYh4MzMyUARXBnrIPvGtvxddOi/fPhmxaNLsqoW0444VFPVqtYe@OHxv/xTqec8@plvw "Charcoal โ€“ Try It Online") Link is to verbose version of code. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 51 bytes ``` แนโ‚ƒ{{0|1}แตยฒ.c+5โˆง.{|\|โ†บสฐโ†ปแต—{bแตhแตg}|โ†บแต—โ†ปสฐโ†ฐโ‚„}แถ {โЇฤŠโ‰ }แตยฒโˆง}แถ d ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HOxkdNzdXVBjWGtQ@3Tji0SS9Z2/RRx3K96pqYmkdtu05teNS2@@HW6dVJQNkMIE6vBQkDRYDiIMkNj5paah9uW1D9qKv9SNejzgUQY4BGgERT/v//HwUA "Brachylog โ€“ Try It Online") Absurdly long but at least it's not boring hardcoding. I'm sure there are shorter ways to describe the constraints of the matrix. ### Explanation ``` แนโ‚ƒ Take a 3x3 matrix { }แถ  Find all: {0|1}แตยฒ. The matrix is filled with 0s and 1s .c+5โˆง The sum of all elements is 5 .{ }แถ  Find all: | The original matrix \| The transpose โ†บสฐโ†ปแต—{bแตhแตg}| The anti-diagonal โ†บแต—โ†ปสฐโ†ฐโ‚„ The diagonal {โЇฤŠโ‰ }แตยฒโˆง Each row must have at least two different elements d Remove duplicates ``` [Answer] # [lin](https://github.com/molarmanful/lin), 50 bytes ``` \OX9`/\ \ยญฦŽลชรฃล–ลฃรฅฦลฒรฑฤžยตฦœลšs <chars g: ``` [Try it here!](https://replit.com/@molarmanful/try-lin) Generates a list of lists where each row is a tied board. Copy-paste-friendly version for testing (includes pretty-printing): ``` \OX9`/\ ; g: ((( 3cols ( str outln ) map ) ' n\ outln ) map ) ' [173 398 362 227 342 355 229 397 370 241 157 286 181 412 346 115] ``` ## Explanation * `\OX9`/\` get all length-9 sequences of X's and O's * `\... <chars` convert string to charcodes * `g:` use charcodes as indices in list of length-9 sequences [Answer] # [Rust](https://www.rust-lang.org), 168 bytes ``` let g=|m|[7,292,146,180,56,448,73,448,84,273].iter().all(|b|b&m!=*b);let f=||(0..512).filter(|m:&u16|m.count_ones()==4&&g(*m)&&g(!m)).fold((),|_,b|print!("{b:0>9b} ")); ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JY5BbsIwEEX3nIKwiGbQ1EqCSQKRe5GqQrjEKJLtVMFZMZyETRa0Qtyot4E0q6cvPT39663rT2F4GD93-8YDnn_6YN7Kv7utw_yo2PFHQdkmo1TmlJYJrXOSsqRi9Y9SUlasPkUT6g5Q7K0F1qxjF6mlxmqMGMUMiRDrNENhGjua7LZxn-bsxFfb-7BrfX0CVErG8RGWDkdEDl9-aw8ASLwjzd9d40MEi7PeJu8bfZktEKvp768BrGaXaQzDxCc) Prints the result in binary. 1=X and 0=O [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 97 bytes ``` 9$*0512$* 1 ยถ$` +`(1+)\1 $+0 01 1 .+(.{9}) $1 G`(1.*){5} ... [$&] A`(\d)(.)*\1(?<-2>.)*(?(2)^)\1 ``` [Try it online!](https://tio.run/##K0otycxL/P@fy1JFy8DU0EhFi8uQ69A2lQQu7QQNQ23NGEMuFW0DLgNDoLCetoZetWWtJpeKIZc7UFZPS7PatJZLT0@PK1pFLZbLMUEjJkVTQ09TK8ZQw95G18gOyNSw1zDSjAOa8/8/AA "Retina 0.8.2 โ€“ Try It Online") Outputs each board with the rows marked in the format `[101][101][010]` using `1` for `X` and `0` for `O`. Explanation: ``` 9$*0512$* 1 ยถ$` ``` Count up to 511 in unary, with padding. (`0` gets listed twice, but we'll delete that later anyway.) ``` +`(1+)\1 $+0 01 1 ``` Convert to binary. ``` .+(.{9}) $1 ``` Trim the result back down to 9 digits. ``` G`(1.*){5} ``` Keep those with (at least) 5 `X`s. (Boards with 6 or more `X`s will always have at least one winning line so will get eliminated anyway.) ``` ... [$&] ``` Split into three groups of three. ``` A`(\d)(.)*\1(?<-2>.)*(?(2)^)\1 ``` Omit boards which aren't ties (i.e. wins or invalid). See my answer to [Tic-Tac-Toe - X or O?](https://codegolf.stackexchange.com/q/144116) for how the regular expression works. [Answer] # [Perl 5](https://www.perl.org/) `-Mbigint`, 65 bytes ``` say for 0xce63b1b72b558eb54e8f3c5cae35aab53a73->to_bin()=~/.{9}/g ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhLb9IwaAiOdXMOMkwydwoydTUIjXJ1CTVIs042TQ5MdXYNDExydQ40dxY164kPz4pM09D07ZOX6/aslY//f//f/kFJZn5ecX/dX1N9QwMDYB0UmZ6Zl4JAA "Perl 5 โ€“ Try It Online") Uses `1` for `X` and `0` for `O`; Outputs flat strings, one grid per line. ]
[Question] [ My stovetop has 10 different settings of heat (0 through 9) and a very odd way of cycling through them. * When I hit plus (`+`) it increments the number, *unless* the number is 9 in which case it becomes 0, or the number is 0 in which case it becomes 9. * When I hit minus (`-`) it decrements the number, *unless* the number is zero in which case it becomes 4. There are no other temperature control buttons. So when I am cooking on one temperature and I want to change to another, it's always a bit of a puzzle to figure out what the easiest way to get to that temperature is. In this challenge you will take a starting temperature and a desired temperature and give the shortest sequence of button presses to get from the starting temperature to the desired temperature. You should take input as two integers on the range 0-9 and output a sequence of instructions. You may output the instructions either as the characters/strings `+` and `-` or as the numbers `1` and `-1`. If there are two equally minimal sequences you may output either or both. 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 counted by the number of bytes. ## Test cases ``` 0 0 -> "" 0 1 -> "----" 0 2 -> "---" 0 3 -> "--" 0 4 -> "-" 0 5 -> "-+" 0 6 -> "-++" 0 7 -> "+--" 0 8 -> "+-" 0 9 -> "+" 1 0 -> "-" 1 1 -> "" 1 2 -> "+" 1 3 -> "++" 1 4 -> "--" 1 5 -> "--+" 1 6 -> "--++" 1 7 -> "-+--" 1 8 -> "-+-" 1 9 -> "-+" 2 0 -> "--" 2 1 -> "-" 2 2 -> "" 2 3 -> "+" 2 4 -> "++" 2 5 -> "+++" 2 6 -> "++++" 2 7 -> "+++++" or "--+--" 2 8 -> "--+-" 2 9 -> "--+" 8 0 -> "++" 8 1 -> "++----" 8 2 -> "++---" 8 3 -> "++--" 8 4 -> "++-" 8 5 -> "---" 8 6 -> "--" 8 7 -> "-" 8 8 -> "" 8 9 -> "+" 9 0 -> "+" 9 1 -> "+----" 9 2 -> "+---" 9 3 -> "+--" 9 4 -> "+-" 9 5 -> "+-+" 9 6 -> "---" 9 7 -> "--" 9 8 -> "-" 9 9 -> "" ``` [Answer] # JavaScript, 146 144 bytes ``` (a,b)=>{for(z=2;i=a;++z){y=z.toString(2).slice(1);for(x of y)i=x>0?i++?i%10:9:i--?i:4;if(i==b)return a-b?y[r='replaceAll'](0,'-')[r](1,'+'):''}} ``` ## Demo This snippet recreates the test cases from the post. ``` let f = (a,b)=>{for(z=2;y=z.toString(2,i=a).slice(1);++z){for(x of y)i=x>0?i++?i%10:9:i--?i:4;if(i==b)return a-b?y[r='replaceAll'](0,'-')[r](1,'+'):''}} // Test all cases from the original challenge for (const startVal of [0,1,2,8,9]){ for (const endVal of [...Array(10).keys()]){ console.log(`${startVal} ${endVal} -> "${f(startVal,endVal)}"`) } } ``` ## Explanation This is my first time golfing, but hey, there has to be a first time for everything. To explain the code, I'll first format the code and rename variables: ``` function stove(startVal, endVal) { for (iterator = 2; y = iterator.toString(2, currentVal = startVal).slice(1); ++iterator) { for (x of y) currentVal = x > 0 ? currentVal++ ? currentVal % 10 : 9 : currentVal-- ? currentVal : 4; if (currentVal - endVal == 0) return startVal-endVal?y[r = 'replaceAll'](0, '-')[r](1, '+'):'' } } ``` and then break it apart to a non-golfed version with comments ``` function stove(startVal, endVal) { // Iterate through all possible stove inputs, starting from the shortest for (let iterator = 2; true; iterator++) { // Reset the currentVal variable every loop let currentVal = startVal; // Convert iterator to binary to convert it to stove inputs later on let bin = iterator.toString(2); // Start the iterator at 2 and remove the first character // This allows for combinations such as 000/--- to appear when they normally wouldn't let buttonSequence = bin.slice(1); // Run the stove simulation for (const button of buttonSequence) { currentVal = button > 0 ? currentVal++ ? currentVal % 10 : 9 : currentVal-- ? currentVal : 4 } // If currentVal and endVal are the same, meaning we've reached the desired end state if (currentVal - endVal == 0) { // Replace ones and zeroes in the button combination with plusses and minuses, then return // If currentVal and endVal are the same, return '' instead, because no button pushes are required return (startVal-endVal) ? buttonSequence.replaceAll('0', '-').replaceAll('1', '+') : ''; } } } ``` Funnily enough, implementing the game was the easiest part, `i=x>0?i++?i%10:9:i--?i:4` runs one round of the entire game, so here's a breakdown of that: ``` // This is true for the string '1' and false for '0' if (button > 0) { // The + button was pressed if (currentVal > 0) { // If the value is not 0, increase it by one and mod 10 so 9 becomes 0 currentVal = (currentVal + 1) % 10; } else { // If the value is 0, set it to 9 as the rules require currentVal = 9; } } else { // The - button was pressed if (currentVal > 0) { // If the value is not 0, decrease it currentVal--; } else { // If the value is 0, set it to 4 currentVal = 4; } } ``` [Answer] # JavaScript (ES6), ~~88 86 75~~ 74 bytes Expects `(desired_temp)(starting_temp)`. ``` b=>g=a=>a-b?"+-"[q=a>b^b<"7489001156"[a]^!a^a<4]+g(a?q?a-1:-~a%10:9>>q):"" ``` [Try it online!](https://tio.run/##RZFNjpswGIb3OcVXSxV2HTM4P/ykA1m1iy7aRZaZpDIJpFQUJsBUGo3aE1Tqpsv2Hj3PXKBHSPGHTVig5wE@vy/2Z/VVtYemuO9EVR@zSx5f0jg5xSpOlEjXhAuyPccqSffpLQkWYeR5Ui59slW7/Qu1V7eLHT9RtT6vlZAr8V29lN4qSpIzWxFyabLzQ9Fk1Mlbh7lNpo5vizLbPFYH6jG3qzddU1Qnytz2viw6Su4qwty8bt6owyfaQpzA0wSgzDrYwscpqCmkU6gfOthBDK37RXX9dzf07sgAbyIBQt1XjNyw12awyfp1IKc8ZZQrfHyoq7YuM7es@@a45LvNh/dui2WK/JH2M2w6TMYYtwbn39@fz79/9XcHVuA8//nh9Gt9YxcPPIwlEw8kkugvbTNrWuZGNC8G1rgckGv2DaMEKHwYCI1ojgYmE2mChUZpOkiTiu@HTI68GPOlDRX4wreCFpgOw4ehNS3RWHVmk4VmaVvMTLamuW0xM8kceWkYxbeCFoyGGtpauHB0bRyacI4sDQ97Htq/50bno2qzTVCW19MJx03QHNj/CU0JTeOuRzZeo7SHpCcjG25sfj3ByEYjm00QuIR/rRHZaOTQ1ohMOPkP "JavaScript (Node.js) โ€“ Try It Online") (test cases) [Try it online!](https://tio.run/##VVLLTuMwFN3nK24j0SQKKYnUAVrXibplMSxYVqlkF6cYBZvmgTQalS9Amg1L@A@@hx/gEzrXScxDUa7te849tu/xLXtg9aaS902k9LU4FK3aNFIrqHX5IHx2DDyAvw5AKRrgom6AQgInEB8bBi5WOUG00JVvGAozMcFhAadTHMOwr@7rl4iiosbBdUmXtoWyL1zCiAKH8RgTKEFAfin0GndStTWSFaQpksaQkAHVEKJuGLmrjpPbvNl1CdlQmeE8wivMwV9CCEkAR5DEuLTwFOezvnbfRVkgk1LbiCGlJ6VQ2@YGj2nagphtj0WI7ZDOySAFIMpa/Cg3wqYOrzxC/kSqTdlei9rXgdE0qfu2vsGlFTHR/JVo2qozijh7xynogdN0SxlNWcSzrhE7ylK@5gv3bHo@i@Mk@XXqrli@HrE1W0zzcOuzbJexKJlHj@woieezNN0Fc9c9WF9Y7wuDBcWuALN2WJz3OB9w/tPwvgHfnhL5hCphXCx8HvhsSG@0QqqYlBrPhd54@IUobWcXV5e/J3VTSbWVxR8fFYLuFXbhq3Emjz56H2//3l@eMXroqPf@@uR1@@yd/eE/ "JavaScript (Node.js) โ€“ Try It Online") (all cases, checked against an ungolfed brute force search) ### How? The most natural behavior is to hit `+` when the desired temperature \$b\$ is greater than the current temperature \$a\$, and to hit `-` when it's lower. Below are all the cases where we need to do the opposite of the natural behavior, along with the corresponding test on \$b\$ according to \$a\$: ``` | 0 1 2 3 4 5 6 7 8 9 | test ---+---------------------+------- 0 | X X X X X X X - - - | b < 7 1 | - - - - X X X X X X | b > 3 2 | - - - - - - - - X X | b > 7 3 | - - - - - - - - - X | b > 8 4 | - - - - - - - - - - | none 5 | - - - - - - - - - - | none 6 | X - - - - - - - - - | !b 7 | X - - - - - - - - - | !b 8 | X X X X X - - - - - | b < 5 9 | X X X X X X - - - - | b < 6 ``` This can be encoded with the following lookup table: ``` [b < 7, b > 3, b > 7, b > 8,,, !b, !b, b < 5, b < 6][a] ``` By normalizing all tests to \$b<t\_a\$ and inverting the result when \$a\in\{1,2,3\}\$, this can be further optimized to: ``` b < "7489001156"[a] ^ !a ^ a < 4 ``` The result is XOR'ed (again) with the test `a > b`, leading to either \$0\$ for `+` or \$1\$ for `-`. We then do a recursive call where \$a\$ is updated using the same logic as in [my answer](https://codegolf.stackexchange.com/a/218367/58563) to [the reverse challenge](https://codegolf.stackexchange.com/q/218360/58563) and keep going that way until \$a=b\$. [Answer] # [Haskell](https://www.haskell.org/), 89 bytes ``` g s=f[[s]] f((w:a):x)e|e==w=a|1>0=f(x++[w!d:a++[d]|d<-[1,-1]])e 9!1=0 0!1=9 0!_=4 t!d=t+d ``` [Try it online!](https://tio.run/##HYzBjsIgAETvfMVgPMCWNsV4sE3xC9zTHgkxKFQ3ajVCg4f@e0Uv8zLJzDvbcPHX6zyfEFSvdTCG9Iyl1vL2xf3klUrKTnJbq569ikIn6lqb6czkulJLUUpjuCcNlaomdc4m516tSaROxcLN0YcIiwMUxiHdny5Ah/M9wQp8eRC42QcYW5QoFqCUo0IYj0cOdvo8uSHkZv@HbMjD3z0eY/yLz92AJb72brmFroUUK7ERjUH38@lV1Zj5DQ "Haskell โ€“ Try It Online") [Answer] # JavaScript (node.js), 125 bytes ``` g=(q,r)=>(o=[],f=((v,r)=>!o[r]||v.length<o[r].length?(o[r]=v,f(v+'+',r?(r+1)%10:9),f(v+'-',r?r-1:4)):0),f('',q),q==r?'':o[r]) ``` [Try it online!](https://tio.run/##Lc/BCoMwDAbg@57CCSMNqaKwy9Tqg4gHceo2xK5RevLdXavL4Sf/dwjk09p26fj9XaNZP/t9H5UwklGVQqu6kYMSwh79qmtuts3GUz@P66vw9b9Xwhdl5SAsAYHkSjCleEuT7IGnRl45SrM7YpZ4BJAGpVGKK4DMX8D8MmgOhFFJborUBRGexI7YE3sK3HR6XvTUx5Me3SkyBAEQu4zKIAQajzcIQsB8338 "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 65 bytes ``` t=>g=(s,o='',...r)=>s-t?g(...r,s%9?s+1:9-s,o+'+',s?s-1:4,o+'-'):o ``` [Try it online!](https://tio.run/##NcrLCoMwEIXhvU8xm5KEXKjQjdoxzyJWJUEccaSb4rOnsZfV4ec7sXt23G9h3e1CjyGNmHZsJ5RsCIUwzrlNYct295M8w/Cl8qzLurL5ooUWhj3bsr6dZYWqKY20gQyAcG0gwB2hyqu1glcB8MH4xfjD@EeAnhameXAzTTIYiAZGGZUMSjXZj@JIbw "JavaScript (Node.js) โ€“ Try It Online") --- # [Python 3](https://docs.python.org/3/), 82 bytes ``` f=lambda t,s,o="",*r:s-t and f(t,*r,[9-s,s+1][0<s<9],o+"+",[4,s-1][0<s],o+"-")or o ``` [Try it online!](https://tio.run/##Zc2xDsIgFIXh3ae4YQJ7SNro0qZ9EtIBU1GIQsNl8ekRdXQ5yf8tZ3@Ve4qnWt3ysM/LZqmAkRYhcMwT60I2buRkaQkzagZ3w2r6medxRepEJ2DOYP3DL2mhUqZUXVtPPlK28XaVQ6@mA9FHw58S7dnHIj0ooP0FeKXqGw "Python 3 โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` o8r4ยค+โนแป‹@%โต ศทล’Pแธ‚o-รงฦ’ยณโผษ—ฦ‡แธข ``` A full program that accepts the from and to values which prints a list of `-1`s and `1`s. [Don't try it online](https://tio.run/##AToAxf9qZWxsef//bzhyNMKkK@KBueG7i0Al4oG1Csi3xZJQ4biCby3Dp8aSwrPigbzJl8aH4bii////OP80 "Jelly โ€“ Try It Online") (it's checking \$2^{1000}\$ instruction strings, for golf!) **[Try it online!](https://tio.run/##AToAxf9qZWxsef//bzhyNMKkK@KBueG7i0Al4oG1CjEyxZJQ4biCby3Dp8aSwrPigbzJl8aH4bii////OP80 "Jelly โ€“ Try It Online")** (with a reduction from the powerset of \$1000\$ items to just \$12\$ so it runs in time) Or [try 10 at a time](https://tio.run/##AV0Aov9qZWxsef//bzhyNMKkK@KBueG7i0Al4oG1CjEyxZJQ4biCby3Dp8aSwq7igbzJl8aH4bii/@KBuMKpw6figbkKOcW7cEBXwrUsw6cvxZLhuZjigqwpS@KCrFn//zg "Jelly โ€“ Try It Online"), from the given value to all others. (Takes about 20 seconds; as above, but also uses the register, `ยฎ`, in place of the second program argument, `โด`, since that's not mutable.) Lastly, [this 26 byter](https://tio.run/##AWkAlv9qZWxsef//bzhyNMKkK@KBueG7i0Al4oG1CjbFu8OYLeG5l@KxruG6jsOnxpLCs@KBvMmXxofhuKL/4oG4wqnDp@KBuQo5xbtbMCwxLDIsOCw5XXDCtSzDpy/FkuG5mOKCrClL4oKsWf8 "Jelly โ€“ Try It Online") that only forms strings up to length six is much faster. ### How? ``` o8r4ยค+โนแป‹@%โต - Link 1, make a move: current value, V ([0,9]); button, B (+/-1) 8r4ยค - [8,7,6,5,4] o - V logical OR that (either [V,V,V,V,V] or [8,7,6,5,4] if V=0) +โน - add B to each of those values แป‹@ - use B to index into that list (1-indexed and modular: if B=1 the first; if B=-1 the fourth) %โต - modulo 10 ศทล’Pแธ‚o-รงฦ’ยณโผษ—ฦ‡แธข - Main Link: from, F ([0,9]); to, T ([0,9]) ศท - 1000 (saves a byte over `12`) ล’P - powerset (shorter strings come first) แธ‚ - modulo 2 o- - logical OR -1 (vectorises) ฦ‡ - filter keep those for which: ษ— - last three links as a dyad - f(instruction, T) ยณ - first program argument, V ฦ’ - reduce [V]+instruction by: รง - call last Link (Link 1) as a dyad โผ - equals T? แธข - head (gets a/the shortest string) ``` [Answer] # [R](https://www.r-project.org/), 149 bytes Or **[R](https://www.r-project.org/)>=4.1, 135 bytes** by replacing two `function` occurrences with `\`s. ``` function(a,b,x=combn(rep(-1:1,6),6),y=x[,apply(x,2,function(t){for(i in t)a=(a+i)%%10+"if"(i>0,8,-5)*i*!a;a==b})],z=y[,order(colSums(!!y))[1]])z[!!z] ``` [Try it online!](https://tio.run/##RYzNCsIwEITvPkUSEXabLTSC/8SX8Fh6SKuBgDYlttBWfPZqq@gwl/mGmTBYPdimLGrnSzCUU6sLf8tLCJcKYrVXtMbRnW5TMlV17aClJf0mNT6sD@CYK1mNRoORDhcLlUjhrAB3TGhL8QojF3FzMFrnT8yo111KPpwvAQp/PTW3O3DeIaYqy7BPOe@zwUJCLME5i49MiNkU1TfGb41IEVv/kJQjWhLbfJEcJZgPU/tZ7P4ncnoZXg "R โ€“ Try It Online") Brute-force approach. Probably porting one of the clever non-brute-force solutions would be shorter. Borrows some code from [Xi'an's answer to the related challenge](https://codegolf.stackexchange.com/a/218588/55372). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ยฎXโ€š6ะธรฆรฉ.ฮ”ยนsvDy+T%ฦตโ‚†yรจโ€šs_รจ}Q ``` Input as two separated integers; output as as a list of `-1,1` for `-+` respectively. [Try it online](https://tio.run/##ATcAyP9vc2FiaWX//8KuWOKAmjbQuMOmw6kuzpTCuXN2RHkrVCXGteKChnnDqOKAmnNfw6h9Uf//Mgo3) or [verify all test cases](https://tio.run/##AXsAhP9vc2FiaWX/wq5Y4oCaNtC4w6bDqQo5w53Do3ZEeT8iIOKGkiAiP3lgVlX/Ls6UWHN2RHkrVCXGteKChnnDqOKAmnNfw6h9WVH/fcKpP@KApm8rLcKuw6hK4oCmKMO/KTI1wq7igqxnT8K3wq5kTyvCrmdfwrcrLcO6LP8). Since I was curious: a hard-coded approach of all test cases would be **52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** in comparison: ``` โ€ขโ€กfsฮฃรฏ6รฟรฎล“ยฝIiโ€ _ยณโ€ขโ€ž+-ร…ะฒโ€ข3oโ‚‚โ‚โˆž5รปยฑร•ยธรดk,ฦ’ cร†ะผร„ล“ยบโ€ข0ลกยฃITฮฒรจ ``` Input as a pair; output as a list of `-+` characters. [Try it online](https://tio.run/##yy9OTMpM/f//UcOiRw0L04rPLT683uzw/sPrjk4@tNcz81HDgvhDm8GS87R1D7de2ARkG@c/amp61NT4qGOe6eHdhzYennpox@Et2TrHJnElH267sOdwC1DzLqBCg6MLDy32DDm36fCK//@jjXTMYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/W95eO7hxWWV9koKj9omKSjZ/3/UsOhRw8K04nOLD683O7z/8Lqjkw/t9cx81LAg/tBmsOQ8bd3DrRc2AdnG@Y@amh41NT7qmGd6ePehjYenHtpxeEu2zrFJXMmH2y7sOdwC1LwLqNDg6MJDiytDzm06vOK/l85/AA). **Explanation:** ``` ยฎXโ€š # Push pair [-1,1] 6ะธ # Repeat it 6 times as list: [-1,1,-1,1,-1,1,-1,1,-1,1,-1,1] รฆ # Take the powerset of this รฉ # Sort it by length .ฮ” # Find the first/shortest list that is truthy for: ยน # Push the first input s # Swap so the list is at the top again v # Loop over each of its items `y`: D # Duplicate the current result y+ # Add `y` to the copy T% # Modulo-10 ฦตโ‚† # Push 194 yรจ # Index `y` into it (1โ†’9; -1โ†’4) โ€š # Pair the two together s # Swap so the result is at the top again _ # Check if it's 0 (1 if 0; 0 otherwise) รจ # Index it into the pair } # Close the loop Q # Check if it's now equal to the (implicit) second input # (after which the found list is output implicitly as result) ``` ``` โ€ขโ€กfsฮฃรฏ6รฟรฎล“ยฝIiโ€ _ยณโ€ข # Push 664379026224093486851406838200392383 โ€ž+-ร…ะฒ # Convert it to custom base-"+-" # (basically convert it to base-2, and index into "+-") โ€ข3oโ‚‚โ‚โˆž5รปยฑร•ยธรดk,ฦ’\ncร†ะผร„ล“ยบโ€ข # Push 4321233211012234432210123454326543321011543233210 0ลก # Convert it to a list of digits, and prepend a 0 ยฃ # Split the list of "+-" into lists of that size I # Push the input-pair Tฮฒ # Convert it from a base-10 list to an integer รจ # Use that to index into the earlier list # (after which the list is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ฦตโ‚†` is `194`; `โ€ขโ€กfsฮฃรฏ6รฟรฎล“ยฝIiโ€ _ยณโ€ข` is `664379026224093486851406838200392383`; and `โ€ข3oโ‚‚โ‚โˆž5รปยฑร•ยธรดk,ฦ’\ncร†ะผร„ล“ยบโ€ข` is `4321233211012234432210123454326543321011543233210`. [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` f=lambda a,b,*c:a!=b<10>len(c)and min((f((-i%7+3,a+i)[a>0]%10,b,*c,i)for i in(-1,1)),key=len)or c ``` [Try it online!](https://tio.run/##HY5NDoIwEIX3nmJckMzIkLSyUInlIsbFFKg2QiGEDaevLZu3@N5P3rJv3znUMTozymR7AWHLl66Rs7FPrdpxCNiRhB4mHxAdYuWLW1mzlJ5e0qp3odVRYU9uXsFDylWaNRH/ht2kAUq4i9mUZAIq1nzlOz@oOQFkbjNfJXwG1OqgAMvqw4b5jstKFP8 "Python 3 โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 131 bytes ``` sub{($_,$w,$s,@t)=@_;@t=sort{length$$b[1]<=>length$$a[1]}@t,[$_?$_-1:4,"$s-"],[$_++?$_%10:9,"$s+"]and($_,$s)=@{pop@t}while$_-$w;$s} ``` [Try it online!](https://tio.run/##XdNbb5swFAfwdz7FEXOWRDZSnAtgGC3vk9aXvqURaleHVkuBgqtsivLZMwd8I5EicX748j9gGt4eNhe0zy7d18tphgqCjgR1JBfzLC/SXGRd3YrTgVeleEPoZUt3P7I7XT7L8pwLskXFPSoCmqyJj7rA310FY2kTukjYFbG/e65e@w06ufSpqZtcnI9v7wcuZ6JjirrzJfX2dTsDbwsLAgvI7sD3YUeGmvZ1IH/WltosrRRZWQ9iYTMAthIqcSjqCbsLxYqssEEUUB06sEDdLqhO7MwY8mJH1uMOqAkcOINCTY5Fqgt3aqzNEhu3vzSpAyt01MdS57b1atTHUqfGjmyUOBRqciwy1iN8g7rtO5N5hhGx7tXJw24eSay7wI5QJc6hic0rwCNcGbSmW3Joc3PgYvsmrESjhxfrBmw9PjbMRLdA9ekz6zITfGSrm2PKTGxH1JsInA3Cm0aYie1IPGqE6eB9PT95AB//Zkjwj4agih@L4YrLzxsVaX8Xldl3tFdjwAyaX@827Xsl9v4kCDuAqybQjwMAPS6xU6Tyvw3/LfhrApMgknOgrIW87p4qn8j1ABAH/gmohHuY1n@mkMD018MjPPycyr25/Jepd/Yu/wE "Perl 5 โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` ๏ผฎฮธโŠžฯ…โŸฆ๏ผฎฯ‰โŸง๏ผฆฯ…๏ผฆยฒ๏ผฆยฌโŠ™ฯ…โ„–ฮปฮธโŠžฯ…๏ผฅฮนโއฮฝโบฮผยง+-ฮบโއฮบโŠ–โˆจฮผโต๏นชโŠ•โˆจฮผโธฯ‡โŠŸโŠŸฯ… ``` [Try it online!](https://tio.run/##XY89C8IwEIZ3f8XhdMErqCAKTkWXDmoHN3GIbaRimrQx58evj40oigfHC/e891VU0hVW6hAy07Bfc31QDlsx7@V8qZAJdr9AENz2HTxaB8gCXjp@69p6TM0jNi0sG4@aoBVdwGfWSjZ4ItgqZ6R7oCHINV@wJkh9Zkp1x/4g6ROchfi6zgRLVThVK@NViRsX/ZPoWNmStcXM/NNZpKNh3B0/cafumNw2r@RYC2EK45Bc9RM "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes the desired temperature first and the starting temperature second. Explanation: ``` ๏ผฎฮธ ``` Input the desired temperature. ``` โŠžฯ…โŸฆ๏ผฎฯ‰โŸง๏ผฆฯ… ``` Start a breadth-first search with the starting temperature and no button presses. ``` ๏ผฆยฒ ``` Check each button. ``` ๏ผฆยฌโŠ™ฯ…โ„–ฮปฮธ ``` Stop processing once all the desired temperature has been found. ``` โŠžฯ…๏ผฅฮนโއฮฝโบฮผยง+-ฮบโއฮบโŠ–โˆจฮผโต๏นชโŠ•โˆจฮผโธฯ‡ ``` Calculate the next temperature and push that with its updated list of button presses. ``` โŠŸโŠŸฯ… ``` Output the button presses that reached the desired temperature. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 40 bytes ``` ;Xโ‰œ{โˆง1wโ‚„&{0โˆง9!|9โˆง0|+โ‚}|โˆง_1wโ‚„&{0โˆง4|-โ‚}}โฑโพ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pv@Wj@supHHctBtLV9VfWjtg2Pmpofbu0Aij3cuaj8UVNL7cOtE0C8Hdse7uqE8v9bRzzqnAPSaAhSolZtADJDscYSSBnUaD9qaqytATLjkWRNanRBwrWPGjc@atz3/z8A "Brachylog โ€“ Try It Online") Starting temperature through input variable, target temperature through output variable, prints solution at end of program ([+3 bytes if the `1`/`-1` format doesn't extend to strings](https://tio.run/##SypKTM6ozMlPN/pv@Wj@supHHctBtLV9VfWjtg2Pmpofbu0Aij3cuaj8UVNL7cOtE0C8Hdse7uqE8v9bRzzqnAPSqKStBFKkVm0AMkWxxhJIGdRoP2pqrK0BSesiSZvU6ILEax81bnzUuO//fwA); if it's permitted with a separator just replace both `w`s with `แบ‰`s). Brute-forces all sequences shortest first until one reaches the target. Can probably be shorter. [Checked against Arnauld's JS solution.](https://tio.run/##RY3dboMwDEbv9xSepUlBaQpI3VZ@Eh6kLZLDAmqFSIGqN1P36sxZ1@3CtvQdH/tEV5qb6Xi@qMF/uKXVi9Wm06QNKVuhVLgbNRlb2xLfN9ssSdL09Q13dKifqaZyc5CdoGqsSKW5@qKXNMkzY8YoR1xaP4neXYBAQ1LwKDVkPKWM4PMJILD@ODjGiAUHD8HeBfsr2IcAEMeBz77nDe5XJ2gFNip@YECTmxm1giLxF4cXUge0nty5p8aJeC/jboUpRv@RConiCCQgILs3rsYP/Mite9@J@yXA/YB8@7Z8Aw) [Answer] # Python3, 168 bytes: ``` lambda *x:min(f(*x),key=len) def f(a,b,c=''): if a==b:yield c if len(c)<10: yield from f([a+1,[9,0][a==9]][a in[0,9]],b,c+'+') yield from f([4,a-1][a!=0],b,c+'-') ``` [Try it online!](https://tio.run/##ZZPbbqMwFEWfy1e4eQHXpsIhFzsa@gn9AYgqh5iOO9yE0aiR5t8zPsYmD@WFtfE53htfxtv8e@hzPk73z6K6t7K7XCV6@T51uk@a5OUb0z/qVrSqx9FVNahJJL3QuohjfIqQbpAsisvpplV7RbX7YEuTGv9imR1Hy0AzDZ3tLCVhtBQ0O5e2S5ztC@m@zKhFmJTEJMY/mnZUpsyWPheZr0pjfNfdOEwzkmamaFKRsYHiKEMZSt/QZmOJOUrtA2obFIjcC@DdwoD7BQnwwbMTRyfI0sC9ABYLbyLmjVNA5jMw7@rGF0/ieLf6s2CauoFDEE4dfYalkAcFQqxRt8E5BWYhxdZ7A@UhxdY7E8d7z04cgnDquConeYjlJhaPxNybE8fM87LmPPw98TJfJaiQxIn9Y3f4ugjAx/A/3IcAWlddBHtAFjYJOkUw9yp/7KAI1o79IqRuisMjhgjWjnmIIbz5JoLj1gwT0vYEo0a3s5qS96FXFJlXM7Z6TuKqj7G9JE/LhenkmNjT@mqH1CTbD/VXtnB012pTpdVbZf5VJqYaY9tnjLJHPPk6FZ9w6zBGRYFqWsKEX7Q@R@Oke9s6KzMbNEL91V6N/w) [Answer] # T-SQL, 190 bytes ``` WITH C as(SELECT @ a,cast(''as VARCHAR(max))r UNION ALL SELECT(a+iif(a=0,4-5*~p/2,p))%10,r+CHAR(44-p)FROM C,(VALUES(1),(-1))X(p)WHERE len(r)<6)SELECT top 1r FROM C WHERE @2=a ORDER BY len(r) ``` **[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=e70d9e7179ac3fa6cd5a5ea526c787a9)** ]
[Question] [ *(inspired by [this post](https://puzzling.stackexchange.com/q/53927) over on Puzzling. CAUTION: SPOILERS FOR THAT PUZZLE ARE BELOW.)* The standard telephone keypad correlates letters to numbers as follows: ``` 1 -> 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -> WXYZ 0 -> ``` A given input word is defined to be an Ordered Word if, when translated to keypad presses using the above, the resulting number is either non-decreasing or non-increasing. In other words, the resultant number cannot both increase *and* decrease. For example, the word `CAT` translates to `228`, which is non-decreasing, and thus an Ordered Word. However, the word `DOG` is `364`, which both increases and decreases, and thus is not an Ordered Word. ## The challenge Given a word, output whether or not it's Ordered. ## Input * A word (not necessarily a dictionary word) consisting of ASCII alphabet (`[A-Z]` or `[a-z]`) letters only, in [any suitable format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Your choice if the input is all uppercase or all lowercase, but it must be consistent. * The word will be at least 3 characters in length. ## Output A consistent [truthy/falsey](http://meta.codegolf.stackexchange.com/a/2194/42963) value for whether the input word is Ordered (truthy) or not Ordered (falsey). ## Rules * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. ## Examples Here are some Ordered Words (i.e., truthy), and there are more on the linked Puzzling puzzle. ``` CAT TAC AAA DEMONS SKID LKJONMSRQP ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` Here are some non-Ordered Words (i.e., falsey) ``` DOG GOD ROSE COFFEE JKLMNOGHI ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~164~~ ~~148~~ ~~132~~ 77 bytes *-16 bytes thanks to [Rod's suggestion elsewhere](https://codegolf.stackexchange.com/questions/136838/is-it-an-ordered-word/136850#comment334875_136848). A frickin' -55 bytes thanks to Arnold Palmer.* ``` n=[min(int((ord(i)-58)/3.13),9)for i in input()] print sorted(n)in[n,n[::-1]] ``` [Try it online!](https://tio.run/##JU1da4MwFH3Prwi@mEC70ZXBJvTBaXSt1bTqPsWHoRkNbInElLW/3t3g4XLOuXDOvcPVnrS6mzrdC7zBnudNatP8SkWksoRo0xNJl/cP9HZ9s1rTxSP91gZLLBXMcLaEtmgwkMWjNlb0RFGpGrVQTRAsV207wUWErLkGCAP@TvJH4Nqcxbw7iIvosPuPxKUTg8WMJ8wYbebI8DWOkx@FtY/8OoyAwzAEjlnOiwpMlW1jkH2240VelceDizxFMUvS5@0u2@cFPxzLqn55fXv/@HRNngKn3LVKXjGQiCcJc2bOQ9H/Bw "Python 2 โ€“ Try It Online") Input must be uppercase. Outputs `True` or `False` based on its orderedness. --- ## Explanation The first line maps each letter to a number. ``` for i in input() # iterate over the input string ord(i) # take the ASCII ordinal -58 # subtract 58 ( )/3.13 # divide by 3.13 int( ) # chop off the fractional part min( ,9) # choose the minimum between the number and 9 n=[ ] # assign the resulting list to n ``` This works based on: ``` | 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 ----------+------------+------------+------------+------------+------------+----------------+------------+----------------- ord(x) | 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 ----------+------------+------------+------------+------------+------------+----------------+------------+----------------- x - 58 | 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 ----------+------------+------------+------------+------------+------------+----------------+------------+----------------- x รท 3.13* | 2.2 2.6 2.9| 3.2 3.5 3.8| 4.2 4.5 4.8| 5.1 5.4 5.8| 6.1 6.4 6.7| 7.0 7.3 7.7 7.9| 8.3 8.6 8.9| 9.3 9.6 9.9 10.2 ----------+------------+------------+------------+------------+------------+----------------+------------+----------------- int(x) | 2 2 2 | 3 3 3 | 4 4 4 | 5 5 5 | 6 6 6 | 7 7 7 7 | 8 8 8 | 9 9 9 10 ----------+------------+------------+------------+------------+------------+----------------+------------+----------------- min(x, 9) | 2 2 2 | 3 3 3 | 4 4 4 | 5 5 5 | 6 6 6 | 7 7 7 7 | 8 8 8 | 9 9 9 9 ``` \*Values are rounded. :P The second line outputs if the list of numbers is in ascending or descending order. ``` print # print whether... sorted(n) # n sorted... in[n,n[::-1]] # is equivalent to n or n reversed ``` [Answer] ## JavaScript (ES6), ~~83 ... 71~~ 70 bytes Returns a boolean. ``` x=>[...x].every(c=>v&=~(k=x,x=parseInt(c,35)*.32|0||10,x<k?2:x>k),v=3) ``` ### Test cases ``` let f = x=>[...x].every(c=>v&=~(k=x,x=parseInt(c,35)*.32|0||10,x<k?2:x>k),v=3) test = a => a.forEach(s => console.log(f(s) + " for '" + s + "'")) console.log('[Truthy]') test(["AAA", "CAT", "TAC", "DEMONS", "SKID", "LKJONMSRQP", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]) console.log('[Falsy]') test(["DOG", "GOD", "ROSE", "COFFEE", "JKLMNOGHI"]) ``` --- ### How? **Letter conversion** We use `parseInt(c, 35)` to convert each letter of the input string to some number in [*10* .. *34*]. Because it's base-35, *"Z"* is converted to `NaN` instead. The expression `* .32 | 0` maps this number into the interval [*3* .. *10*], leading to 8 correct groups of letters for *"A"* to *"Y"*. We need `|| 10` to get the correct value for *"Z"*. ``` | A B C| D E F| G H I| J K L| M N O| P Q R S| T U V| W X Y Z -----------+--------+--------+--------+--------+--------+-----------+--------+------------ parseInt |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 NaN -----------+--------+--------+--------+--------+--------+-----------+--------+------------ *.32|0||10 | 3 3 3| 4 4 4| 5 5 5| 6 6 6| 7 7 7| 8 8 8 8| 9 9 9|10 10 10 10 ``` **Order test** We keep track of the signs of differences between consecutive numbers into the bitmask ***v***, initially set to 3 (0b11): * bit #0: cleared when *new\_value > previous\_value* * bit #1: cleared when *new\_value < previous\_value* The previous value is stored in the same variable ***x*** as the input. This ensures that the first iteration -- where no *previous value* actually exists -- will not clear any bit, because a string containing only letters is neither greater nor less than any number: ``` ('CAT' > 5) === false ('CAT' < 5) === false ``` A word is ordered unless both signs are encountered, which leads to ***v = 0*** and makes `every()` fail. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28, 27, 25, 23, 22, 21, 19,~~ 18 bytes ``` _> Oโ€˜รง82รง88:3Iแน แธŸ0E ``` [Try it online!](https://tio.run/##y0rNyan8/z/ejsv/UcOMw8stjIDYwsrY8@HOBQ93zDdw/f9w95bD7Y@a1vz/7@jkzOXsGMIV4ujM5ejoyOXi6uvvF8wV7O3pwuXj7eXv5xscFBjABVTm4urm7uHp5e3j6@cfEBgUHBIaFh4RGcXl4u/O5e7vwhXkH@zK5ezv5ubqygVRBVQOAA "Jelly โ€“ Try It Online") This was a lot of fun to write! Explanation: ``` # Define a helper link, decrement a if a > b _ # Subtract > # Boolean greater than # Main link: O # The ordinals (ASCII points) of the input โ€˜ # Minus one รง82 # Decrement if greater than 82 รง88 # Decrement if greater than 88 :3 # Divide each number by 3 I # Consecutive differences แน  # Sign (-1 if < 0, 0 if == 0, and 1 if > 0) แธŸ0 # Remove all 0's E # All elements are equal? ``` Thanks to @ErikTheOutgolfer, @leakynun and @BusinessCat for all saving bytes. :) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 36 bytes ``` v.โ€ข1ะฝJยฉยฝรจ`ร‡Hรธยนรกโ‚‚Nยธยฐโ€ฆรˆรกร€โ€ข#Dส’yรฅ}k}ยฅ0โ€นร‹ ``` [Try it online!](https://tio.run/##AU0Asv8wNWFiMWX//3Yu4oCiMdC9SsKpwr3DqGDDh0jDuMK5w6HigoJOwrjCsOKApsOIw6HDgOKAoiNEypJ5w6V9a33CpTDigLnDi///c2tpZA "05AB1E โ€“ Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~26~~ 25 bytes ``` 1Y21K250B-Y{c&m8\dZSu|s2< ``` Input is in upper-case letters. Output is `1` or `0`. [**Try it online!**](https://tio.run/##JYu9DsIgFEZ3H0QmE0ti4uBC@bOlcFvAKo2DRkc7qZO@O17icr5vOGe@vh75kqtEK0M363qVPrflvD3fp/D@Pukui5gJZ5EsSGQcyRhDCmnBBTzBNAKnMy04G/zQF6XmQiq9b1rTWQf94EM8jMdTmkoJGqmhVB6CxOGglCzn72NIfg "MATL โ€“ Try It Online") ### Explanation ``` 1Y2 % Push 'ABC...XYZ' 1 % Push 1 K % Push 4 250B % Push 250 in binary, that is, [1 1 1 1 1 0 1 0] - % Subtract (from 4, element-wise): gives [3 3 3 3 3 4 1 4] Y{ % Convert to cell array, splitting into chunks of those lengths c % Convert to char matrix. Gives a 4-column matrix. Chunks of length 3 % are right-padded with a space &m % Implicit input. Push (linear) index of membership in char matrix 8\ % Modulo 8. Converts linear index into 0-based row index d % Consecutive differences ZS % Sign u % Unique | % Absolute value s % Sum 2< % Less than 2? Implicit display ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), ~~22 21 19~~ 18 bytes ``` ยฑSโ‚ฌแบŠโ–ฒ`แนชoยฑโ‰ค"DGJMPTW ``` Returns `1` for truthy inputs, `0` for falsy ones. Inputs must be in uppercase. Passes all test cases. [Try it online!](https://tio.run/##yygtzv6vkPuoqfHQtv@HNgY/alrzcFfXo2mbEh7uXJV/aOOjziVKLu5evgEh4f///3d2DOEKcXTmcnR05HJx9fX3C@YK9vZ04fLx9vL38w0OCgzgcnRydnF1c/fw9PL28fXzDwgMCg4JDQuPiIzicvF353L3d@EK8g925XL2d3NzdeWCqAIqBwA "Husk โ€“ Try It Online") ## Explanation ``` ยฑSโ‚ฌแบŠโ–ฒ`แนชoยฑโ‰ค"DGJMPTW Implicit input x, e.g. "CAT" `แนชoยฑโ‰ค"DGJMPTW This part transforms x into a "canonical form" corresponding to the numpad digits `แนช Table with flipped arguments oยฑโ‰ค on sign of less-than-or-equal (In Husk, โ‰ค returns extra information we don't want, so we take sign of the result to get 0 or 1.) "DGJMPTW of this string and x. This gives, for each char in x, a bit array of comparisons with the chars in the string: y = [[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[1,1,1,1,1,1,0]] แบŠโ–ฒ Maxima of adjacent pairs: [[0,0,0,0,0,0,0],[1,1,1,1,1,1,0]] Sโ‚ฌ 1-based index in y as sublist: 2 ยฑ Sign: 1 ``` [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` a=[3681/ord(c)for c in input()] print sorted(a)in[a,a[::-1]] ``` [Try it online!](https://tio.run/##JU1BboQwDLzziogLILVabStVFdIet9e99IY4uImBLBBnndCFfp46YmTNjKUZ229xIPe2R97qTAmeg51QffOCx56AK2qV5/kOl@b94/N8IjalrjpipZV1Mn6JZdVmnq2LKhBHNCVU1jXwAk1dv57bdpcDGa4afVTX29eVmfh44SGEvdAQi6yIoIUBQNjgTC6ICaM1ItN4JzcHfvgU@dEGu36w93GaHfkHh7j8PtftLzWpF@4ptZgCimjqOkzmyEux@Ac "Python 2 โ€“ Try It Online") Accepts input in lowercase. ### How it works โŒŠ3681/*x*โŒ‹ decreases from * 38 to 37 at *x* โ‰ˆ 96.8684210526, before `a`; * 37 to 36 at *x* โ‰ˆ 99.4864864865, between `c` and `d`; * 36 to 35 at *x* โ‰ˆ 102.25, between `f` and `g`; * 35 to 34 at *x* โ‰ˆ 105.171428571, between `i` and `j`; * 34 to 33 at *x* โ‰ˆ 108.264705882, between `l` and `m`; * 33 to 32 at *x* โ‰ˆ 111.545454545, between `o` and `p`; * 32 to 31 at *x* โ‰ˆ 115.03125, between `s` and `t`; * 31 to 30 at *x* โ‰ˆ 118.741935484, between `v` and `w`; * 30 to 29 at *x* โ‰ˆ 122.7, after `z`. [Answer] ## C++, ~~375~~ ~~199~~ ~~195~~ 194 bytes Thanks to Shaggy's JavaScript answer : -5 bytes thanks to Zacharรฝ ``` #include<string> int o(std::string a){std::string m="22233344455566677778889999";for(auto&b:a)b=m[b-65];int j=1,i=0,d=0;for(;j<a.size();++j){if(a[j]>a[j-1])++i;if(a[j]<a[j-1])++d;}return!(i*d);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes ``` A3 8ร—ฦต0+Sยฃยนฮดรฅฤ>โ€šรธฮต`*}.ยซ+ยฅ0K0โ€นร‹ ``` [Try it online!](https://tio.run/##AT4Awf8wNWFiMWX//0EzIDjDl8a1MCtTwqPCuc60w6XEgT7igJrDuM61YCp9LsKrK8KlMEsw4oC5w4v//2NvZmZlZQ "05AB1E โ€“ Try It Online") -1 thanks to [Magic Octopus Urn](https://codegolf.stackexchange.com/users/59376/magic-octopus-urn). [Answer] # [Retina](https://github.com/m-ender/retina), 65 bytes ``` T`_ADGJMPTW`d }T`L`_L (.)\1* $1$*1< (1+)<(?!\1) $1> 1 ^(<*|>*)>$ ``` [Try it online!](https://tio.run/##Jcq7CsIwAAXQ/f6FUCGNIGQvlZiksc@0TbQqxUbQwcVBHPXbY8H1cF739@N5DUtCtA/OT1zqom7d4G/4Ol/5qQJZxyOjiFhEWQLCVnFCNouRxTOlYMCFJPST0jiNQhDcwXEBzjmkqk1jYctcoioL09S271rwrZAq07u8KKu6MW3XW7c/DMfTGdJoaCPRG6sgTJYphf@a@w8 "Retina โ€“ Try It Online") Link includes test cases. Explanation: ``` T`_ADGJMPTW`d ``` Change the first letter on each key to a digit. (This is off by 1 but that doesn't matter for an ascending/descending check. On the other hand, zeros would make my life more difficult, so I left one filler character in.) ``` }T`L`_L ``` Shuffle all the remaining letters up 1 and repeat until they've all been converted to digits. ``` (.)\1* $1$*1< ``` Convert the digits into unary, but only once per run of identical digits. The unary values are seprated with a `<`... ``` (1+)<(?!\1) $1> ``` ... but if the LHS turns out to be greater than the RHS, correct the `<` to `>`. ``` 1 ``` Delete the `1`s which are no longer necessary. ``` ^(<*|>*)>$ ``` Check that the word is ordered. (The trailing `>` comes from the last digit which always compares greater than the empty space following it.) [Answer] # [Pyth](http://pyth.readthedocs.io), 23 bytes One of my first non-trivial Pyth answer! Saved 6 bytes thanks to @LeakyNun. The initial solution is below. ``` /{_BKmhS,9/a58Cd3.13zSK ``` [Test Suite.](http://pyth.herokuapp.com/?code=%2F%7B_BKmhS%2C9%2Fa58Cd3.13zSK&input=DOG%0AGOD%0AROSE%0ACOFFEE%0AJKLMNOGHI&test_suite=1&test_suite_input=CAT%0ATAC%0AAAA%0ADEMONS%0ASKID%0ALKJONMSRQP%0AABCDEFGHIJKLMNOPQRSTUVWXYZ%0ADOG%0AGOD%0AROSE%0ACOFFEE%0AJKLMNOGHI&debug=0) # [Pyth](http://pyth.readthedocs.io), 29 bytes ``` KmhS+9]/-Cd58 3.13w|qKSKqK_SK ``` [Test Suite.](http://pyth.herokuapp.com/?code=KmhS%2B9%5D%2F-Cd58+3.13w%7CqKSKqK_SK&input=DOG%0AGOD%0AROSE%0ACOFFEE%0AJKLMNOGHI&test_suite=1&test_suite_input=CAT%0ATAC%0AAAA%0ADEMONS%0ASKID%0ALKJONMSRQP%0AABCDEFGHIJKLMNOPQRSTUVWXYZ%0ADOG%0AGOD%0AROSE%0ACOFFEE%0AJKLMNOGHI&debug=0) --- # Explanation ``` /{_BKmhS,9/a58Cd3.13zSKQ - The Q means evaluated input and is implicit at the end { - Deduplicate _ - Reverse B - Bifurcate, Create a two-element list, [B, A(B)] K - Variable with auto-assignement to: m z - Map over the input: hS - Minimum (first element of sorted list) , - Create a two-element list, [A, B] with these elements: 9 - The numeric literal 9 / - The integer division of: a58Cd - The absolute difference between 58 and ord(current_element) 3.13 - The numeric literal 3.13 SK - K sorted / Q - Count the occurrences of the input in [K, K[::-1]] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 17 bytes ### Code ``` Aโ€ข22ฤโ‚‚โ€ขSฤsร—Jโ€กร”ยฅdร‹ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f8VHDIiOjI42PmpqArOAjjcWHp3s9alh4eMqhpSmHu///T04sAQA "05AB1E โ€“ Try It Online") or [Verify all test cases!](https://tio.run/##MzBNTDJM/V9zaGVZ5X/HRw2LjIyOND5qagKygo80Fh@e7vWoYeHhKYeWphzu/l@pdHi/lcLh/Uo6/5MTS7hKEpO5EhMTuVJSc/PzirmKszNTuHKys/LzcouLCgu4EpOSU1LT0jMys7JzcvPyCwqLiktKy8orKqu4UvLTudLzU7iK8otTuZLz09JSU7kgqoDKAQ "05AB1E โ€“ Try It Online") ### Explanation ``` A # Push the lowercase alphabet โ€ข22ฤโ‚‚โ€ข # Push the number 33333434 S # Split into an array ฤ # Get the range of indices [1 .. length] sร— # Swap and string multiply J # Join that array โ€ก # Transliterate ``` This now essentially maps the following letters to the following numbers: ``` abcdefghijklmnopqrstuvwxyz โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“โ†“ 11122233344455566667778888 ``` ``` ร” # Remove consecutive duplicates ยฅ # Compute the delta's of the list d # Check if the number is greater or equal to 0 ร‹ # Check if all elements are the same ``` [Answer] # JavaScript (ES6), ~~107~~ ~~97~~ ~~95~~ ~~92~~ ~~88~~ 85 bytes Works with mixed-case strings. Returns `1` for truthy or `0` for falsey. ``` s=>(s=(a=[...s].map(c=>(parseInt(c,36)-3)/3.13%10|0||9))+"")==a.sort()|s==a.reverse() ``` * 10 bytes saved thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod). --- ## Try It ``` o.innerText=(f= s=>(s=(a=[...s].map(c=>(parseInt(c,36)-3)/3.13%10|0||9))+"")==a.sort()|s==a.reverse() )(i.value="Cat") oninput=_=>o.innerText=f(i.value) ``` ``` <input id=i><pre id=o> ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~29~~ ~~27~~ ~~25~~ 17 [bytes](https://github.com/splcurran/Gaia/blob/master/codepage.md) ``` ฤ‹โŸจ):โ€œQXโ€™>ยฆฮฃโป3/โŸฉยฆo ``` [Try it online!](https://tio.run/##ASoA1f9nYWlh///Ei@KfqCk64oCcUVjigJk@wqbOo@KBuzMv4p@pwqZv//9DQVQ "Gaia โ€“ Try It Online") ### Explanation ``` ฤ‹ Turn the input into a list of code points โŸจ โŸฉยฆ Map this block to each code point: ) Increment it : Copy it โ€œQXโ€™ Push [81 88] >ยฆ Check if the code point is greater than each of [81 88] ฮฃ Sum the results โป Subtract from the code point 3/ Integer divide the result by 3 o Check if the resulting list is in sorted order (increasing or decreasing) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` ร‡รลพqรท8 7:ร”ยฅdร‹ ``` Whenever I see a numpad question, I have to make a pi-based answer. [Try it online](https://tio.run/##ATgAx/9vc2FiaWX//8OHw43FvnHDtzgKNzrDlMKlZMOL//9hYmRjZWZnaGlqa2xtbm9wcXJzdHV2d3h5eg "05AB1E โ€“ Try It Online") or [verify all test cases](https://tio.run/##Jcq7DcIwEADQ/qaIUkMNoiCzXPzDceyLPwSM6CkQHSswAx0FFnMZJF79KGKvRT3PuWub5bZpu1zLpdw@L1@ea1htyv394OVaF5VhgoQMEBG4sOQiRKM5jGYgZ2PwE2DPuJBqpwczWkeTDzHt58Mxn4CTAkUcAkUBjKQUAv7r178 "05AB1E โ€“ Try It Online") ``` ร‡ # ASCII code of each letter in the input ร # add 2 ลพqรท # divide by pi 8 7: # replace 8 with 7 ร” # remove duplicates ยฅ # deltas d # each >= 0 ? ร‹ # are all elements equal? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` โ€œยขร‡โบHโ€™D0แบ‹j1ล“แน—ร˜Aโธ=โ‚ฌร—"โ‚ฌ9แธŠยคFแธŸ0IแธŸ0แน E ``` [Try it online!](https://tio.run/##AVUAqv9qZWxsef//4oCcwqLDh@KBukjigJlEMOG6i2oxxZPhuZfDmEHigbg94oKsw5ci4oKsOeG4isKkRuG4nzBJ4bifMOG5oEX/w4fFkuG5mP//Q09GRkVF "Jelly โ€“ Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 133 bytes ``` using System.Linq;q=>{var u=q.Select(c=>(int)((c-58)/3.13));var z=u.Zip(u.Skip(1),(a,b)=>a-b);return!(z.Any(d=>d<0)&z.Any(d=>d>0));}; ``` [Try it online!](https://tio.run/##VVJtT6swGP3eX/FcYm7aZOO6GBMjQoLs5bo35pjvMaYrVRtn2WjRKOG3TxBhcj6056RPz9OTp0y1WRTzbaKEfILgQ2n@aqHfyhwLubEQkvSVqzVlHGYzb/DQQSliK6oUrBHkSL/XAkpTLRi8RSKECRUSk/poV1Sgn0h2onSc92rBMopWDvhxyGMegr3d2E76RmNI7I0Z8BVnGjPbwUJqgjFrHx6Rfwdm54AQq6j6tBPzVqxxYgYv@dYhLUxbS2I7tL0kVsx1Ess/@NN05QcObSc82Sd/d8rZz20ya9t4Xfmwu3tYcKUZVVyBDZK/392jMobhuQujVdKF61XUdd2KdnsTfxpUKhiddSs@Hg396SSYn8/qa6det9cf/D8bjsaTqT87nweLi8ur65vb2s0fVHTg105zP@hV3PP7/V6tSqPc0UCZ1Yj2mE@csmfAZUbQeUIQcpeUNMqbUyvgRVJFK25exULz/H9wvGekhUt2DOnPDHGhSWaQZu8M7ViWbb8A "C# (.NET Core) โ€“ Try It Online") I feel like there's some room to save, but C# is not a concise language so maybe not. Ungolfed: ``` bool Ordered(string word){ IEnumerable<int> keys = word.Select(character => (int)((character - 58)/3.13)); // convert characters to keypad number IEnumerable<int> differences = keys.Zip(keys.Skip(1), (a, b)=> a-b); // difference between consecutive elements return !(differences.Any(diff => diff<0) & differences.Any(diff => diff>0)); // false if both positive and negative differences exist } ``` In particular I think there's a shorter way to express the final check for validity, possibly a way to inline it with the `Zip`. Finding a way to express the `Zip` without needing temporary storage for the `Skip` would also save something, but I doubt there's something more concise for that. [Answer] # [Python 3](https://docs.python.org/3/), ~~143~~ ~~147~~ ~~148~~ ~~149~~ 130 bytes ``` def g(s,f=lambda c:min(int((ord(c)-58)/3.13),9)):x=[f(a)-f(b)for a,b in zip(s,s[1:])];return any(t<0for t in x)*any(t>0for t in x) ``` Best I can do for now. Crude function turns the letter into the number based off of ascii code. There are definitely some improvements to be made. 0 is truthy, 1 is falsey (sorry). Saved 10 bytes thanks to Rod, another 3 thanks to Mr. Xcoder. [Try it online!](https://tio.run/##bY9Nb4JAEIbv/IoNp50G2xrSpKW1CeWrirDK0k/jAUQsSV3Iukbtn6cMvXjoXN4nkzfPZJqT@qqF2bbFuiQbujPK0Xe2zYuMrKxtJWglFKW1LOgKBje3cGVeDk0w7gCs42hR0gwGJc2hrCXJjJxUgvxUTWfZLYbWEpb3cq32UpBMnKh6uMaawtIRLvrV4/mqRT4gU92xU90gemo7GLZtY7hexGKOxMOxizkNJyyOeDKf9bUnx/X84Hk8CadRzGbzhKcvr2/vH586WBrpppH4z4YeADTt7JzLAhQErLcmjHuYDvN9r6c/YWf@R9T@Ag "Python 3 โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~111~~ 103 bytes *-8 bytes thanks to @Arnold Palmer:no `lower()` needed* * Takes uppercase letters as input. ``` lambda x:sorted(f(x))in[f(x),f(x)[::-1]] f=lambda x:['22233344455566677778889999'[ord(i)-65]for i in x] ``` [Try it online!](https://tio.run/##PY47b4MwFIV3foU3g0SG8gpFyuDySkLAgEn6cD2kohBLCUSEgfx6iqnEGe53hvNJ9/7sL22jjfXme7yebz/lGQzOo@3631Ku5EFReEMFVXGo46xeGJOqzTKlUNM0XdcNwzBN07Ks9RTbtl@nQNp2pcyVlWWyqu0AB7wBAxuXTqGLCqhKsECuAEJIwPNjnBDRSLTzBA/RHicxybN0nr25nh@E290@OsQJTrOcFMfT@8fn12zjUCDEs5lj4gu6OAj8uf1Lkw0l5tw73vSgnp4c/wA "Python 2 โ€“ Try It Online") [Answer] # PHP 7, ~~98+1 95+1~~ 84+1 bytes a golfed port of [Arnauldยดs answer](https://codegolf.stackexchange.com/a/136845/55735). ``` for(;$c=ord($argn[$i]);$v|=$i++?$p>$k?2:$p<$k:0,$p=$k)$k=($c-58)*.32%10?:9;echo$v<3; ``` accepts uppercase; empty output for falsy, `1` for truthy. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/f26cfc8142770f319d40b92201611518aecbbcad). original post: ``` for(;$c=$argn[$i++];$p?$a[]=$p<=>$k:0,$p=$k)$k=(ord($c)-58)/3.13-($c>Y)|0;echo min($a)*max($a)>=0; ``` [Answer] # CJam, ~~37~~ ~~31~~ ~~30~~ 27 bytes ``` q{_"SVZY"#g-i3/}%_$_W%](e=g ``` [Try it Online](http://cjam.aditsu.net/#code=q%7B_%22SVZY%22%23g-i3%2F%7D%25_%24_W%25%5D(e%3Dg&input=COFFEE) Of course the ugly version ends up being shorter... ``` q{ e# For each character in string... _"SVZY"#g e# Get index of that character in "SVZY". Signum that. (returns 1 or 0 if inside string, -1 if not.) -i3/ e# Subtract value from character (i.e 'Z' becomes 'Y', 'F' becomes 'G'). Convert to int. Integer divide by 3. (this is just how the math works out for proper mapping of characters to phone digits.) }% _$_W%] e# Put mapped string, sorted version, and reverse sorted version in array. ( e# Pop mapped string from array onto stack. e= e# Count occurences of mapped string in array. g e# Signum. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~183 169 153~~ 117 bytes ``` #define a(b)(int)fmin(*(b c)/3.2,27) d(char*c){int r=1,p=1;for(;1<strlen(c);)r&=a()<=a(1+),p&=a()>=a(++);return r|p;} ``` [Try it online!](https://tio.run/##lZNNT8JAEIbv/IoGo9nlQwMeTCyYlH5ZoCzQ8hkvpVAkgdoseEL@unWgRHYzcrCHTZ7Jk503O9OwvAzDNL2ZL6JVvFACMqNkFe9otFnFpEBmSkgfHu@rpeoTzc1J@B7wQkj3YCi8Xikl9YoafXCiVmrbHV8vYhJSlfK7ekBoDY5KkZaSE73AUSxSlS92nzxW@FeiHtLjNZsAGtF9ToEv4VCJSF7X/Gfldv4W50vK/IR5SlVJ8TVdVACRommaqAAixTBd1vFEK6sg0Ws5hqgdGUntVpN1XK/f64rqpYoTNnTDtOxXp9lqux3W7fU9fzAcjSdTKfhVC104nYxHw4F/bAY9obPzalumoTekl7hu/ZUwa58lyEJkOc5RznHOiS7ZhfT/vgHPidnSkJiNFJtJAwJEim5IOwOIFMu2RAUQKU7TERVAvAhuW9oAt40U1mWiAoh3zpc2ExApw9FQVADxBKfyXzDFQ@4zzxSdI@PHY5ZlSlpWQWI2W5iz6P4WT/oh/Q6jdbDcpuX15gc "C (gcc) โ€“ Try It Online") Old solution: ``` #define a(b)(int)((int)(b*.32-17.6)*.9) d(char*c){int l=~-strlen(c),i=0,r=1,p=1;for(;i<l;++i)r&=a(c[i])<=a(c[i+1]),p&=a(c[l-i])<=a(c[l-i-1]);return r+p;} ``` Saved 8 bytes thanks to ThePirateBay. Old old solution: ``` d(char*c){char*a="22233344455566677778889999";int l=strlen(c)-1,i=0,r=1,p=1;for(;i<l;++i){if(a[c[i]-65]>a[c[i+1]-65])r=0;if(a[c[l-i]-65]>a[c[l-i-1]-65])p=0;}return r+p;} ``` Old old old solution: ``` d(char*c){char*a="22233344455566677778889999";int l=strlen(c);int i,r=1,p=1;for(;i<l-1;++i)if(a[c[i]-65]>a[c[i+1]-65])r=0;for(i=l-1;i>0;--i)if(a[c[i]-65]>a[c[i-1]-65])p=0;return r+p;} ``` [Answer] # TI-Basic, ~~92~~ 66 bytes ``` ฮ”List(int(seq(inString("BC DEF GHI JKL MNO PQRSTUV WXYZ",sub(Ans,I,1))/4,I,1,length(Ans 0โ‰คmin(Ansmax(Ans ``` Converts each character in the string to an integer from 0 to 7, and takes the difference between each consecutive element; then checks whether the minimum and maximum differences have the same sign (or either is 0). [Answer] # [Zsh](https://www.zsh.org/), ~~73 69~~ 57 bytes ***-12 bytes** by using @anders-kaseorg's `3681/code` conversion.* ``` for c (${(s::)1})((y=3681/#c,A|=y<p,D|=p&&p<y,p=y,!D|!A)) ``` ~~[Try it online!](https://tio.run/##VYxNT4NAAETv/Ipp2sNuQrXioRFLzMoCthS2BfzqwaRhl0BiIOn2IIq/HQledE6TeS/zqcu@IJQYWp0x/@ilYy2NojkhB5l9EW3b9OqbEtI603x@s7hbvJFpfnl9YVHbWpqsc9rV0eSdI1eteXSk05oT3k0YpT01xh@NqobLMmTMBWMM3ItEnCIN1xzbcCPiKE32O7B7l3t@8LDehNsoFrt9kmaPT88vrwdwESAQHIlIPbjC9z0Pv9aggx3YLWRjYEhVoMBMj/1cqhoqL5thQKXRnKQ6KTky9a7VXxaL7B8vKkM2tep/AA "Zsh โ€“ Try It Online") [Try it online!](https://tio.run/##VYxNT4NAAETv/Ipp2jS7CWqtByOWmJVdsKWwLeBXD15gCSQGCOuFir8dsV50TpN5L3PUxZATSoa8bpGCzD6Jtix6@UUJ6expenazuFu8kWl6cXW@pNby2mS93a0ak/d2M583q85s7M6c8H7CKB2oYfwcaZQVHJYgYQ4YY@AikGGM2F9zbP2NDIM42u/A7h0uXO9hvfG3QSh3@yhOHp@eX14P4NKDJzkiGQs40nWFwK816mAHdousNjCmzJFjpk/9o1AVVFrU44BSo24z1arsxNS7Vn9ZKJN/PC@NrK7U8A0 "Zsh โ€“ Try It Online")~~ [Try it online!](https://tio.run/##VYzNTsMwEITveYqpqCpbioQqJITa5lCpZ7jwAsZeJ24Sr2uHH4fw7CGUC@xpNN83O6ZmtkKK2XKEhlh/irTbye2XFCJXd/cP29sbXR6nKh9CeZqqsNmEQy5DlcvVaVodpZxlUfyME5yHVgMGpaGUgqGefUJqnUHXntn3KV4C1Is2ZOvGnduu9xwuMQ2vb@8feYThGjUbRE4EzdYS4ddadKhR7RelwHLOwmKdrnloyIN0w0sBl8DRUCRzZdQtn/6wx6fnf9y6wrCn@Rs "Zsh โ€“ Try It Online") A few things we abuse: * `((statement,statement,...))` is a sequence of *arithmetic* expressions which returns truthy if the last statement is non-zero. * The return value of a loop is the return value of the last statement in a loop. * Arithmetic operator precedences were pretty nice to us, as ~~only one pair of~~ **no** parentheses were used. One byte could be saved if `!` bound less tightly than `&`. * Unset parameters expand to `0` in arithmetic expansions. * ~~The function we use to map to the keypad number is `CODE / 3.2 - 18` (with a special case for `Z`), but~~ since we only need the *change* between codes, we don't do the linear adjustment. ``` for c (${(s::)1}) # split into characters (( y = #c-90 ? 0^(#c/3.2) : 27, # this sets y to the keypad number + 18 A |= y < p, # set the A flag if we detect it is not ascending D |= p && p < y, # ditto descending, don't compare on first iteration p = y, # save the current character !D | !A # return false if D and A are both set )) ``` 2 bytes can be saved if the truthy/falsey values can be swapped. ]
[Question] [ # Problem Given a positive integer `n` where `n < 100` Output a diamond pattern as follows: Input `n=1` ``` /\/\ \/\/ ``` Input `n=2`: ``` /\ /\ //\\/\/\//\\ \\//\/\/\\// \/ \/ ``` Input `n=3`: ``` /\ /\ //\\ /\ /\ //\\ ///\\\//\\/\/\//\\///\\\ \\\///\\//\/\/\\//\\\/// \\// \/ \/ \\// \/ \/ ``` Input `n=4`: ``` /\ /\ //\\ /\ /\ //\\ ///\\\ //\\ /\ /\ //\\ ///\\\ ////\\\\///\\\//\\/\/\//\\///\\\////\\\\ \\\\////\\\///\\//\/\/\\//\\\///\\\\//// \\\/// \\// \/ \/ \\// \\\/// \\// \/ \/ \\// \/ \/ ``` And so on. # Rules * Program and function allowed. * Trailing whitespace allowed. * Leading whitespace on lines with no `/` or `\` allowed. * Trailing and leading newlines allowed. * **Shortest code in bytes win** [This is probably pretty related](https://codegolf.stackexchange.com/questions/98588/draw-some-mountain-peaks) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 24 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ฤ.โˆซฤ;โˆซ \*+}รธโ”ผโ†”ยฑโ•ฌยก;รธฮšโ”ผ}โ•ฌยณ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxLiV1MjIyQiV1MDEwMSUzQiV1MjIyQiUyMCU1QyorJTdEJUY4JXUyNTNDJXUyMTk0JUIxJXUyNTZDJUExJTNCJUY4JXUwMzlBJXUyNTNDJTdEJXUyNTZDJUIz,inputs=NQ__) Explanation: ``` ฤ push an empty array (the main canvas) .โˆซ } iterate over the input, pushing 1-indexed iteration ฤ; push an empty array below the iteration โˆซ } iterate over the iteration counter \* push current iteration amount of slashes + append those to the 2nd array รธโ”ผ append nothing (so it'd space the array to a square) โ†”ยฑ reverse horizontally (swapping slashes) โ•ฌยก quad-palindromize with 0 overlap and swapping characters as required ; get the canvas ontop รธฮš prepend to it an empty line (so the now bigger romb would be one up) โ”ผ append horizontally the canvas to the current romb โ•ฌยณ palindromize horizontally with no overlap and swapping characters ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ 27 bytes ``` ๏ผฆโบยน๏ผฎยซ๏ผฆฮนยซ๏ผฆโดยซโ†™โปฮนฮบโ†‘โŸฒ๏ผดยปโ†ยป๏ผญฮนโ†ยปโ€–๏ผญ ``` [Try it online!](https://tio.run/##XY/BDsIgEETvfAVHSPBg0lN79WIipmn0A5BAJFJotlAPpt@OtFrTOrd9M7uTlXcB0gubkvaASW1jT/YMH10Xwzm2NwWEUopfCGfNEbNMP1KsyaQajAukPPinOykdGObG5buG4Qel1SbK/aBIee3@cOODCOoCwvW5oiUre0Tb3anha3@sGeeuxRlRo7RVMnAD4PM/VUpF2g32DQ "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: Charcoal's drawing primitives can't quite draw a diamond, because the diagonal movements stay on squares of the same parity. Edit: The new solution is to draw one side of a diamond and then rotate the entire canvas ready to draw the next side, allowing a diamond to be drawn in a loop. This loop is then contained in a loop to draw all the inner diamonds for each diamond. The outermost loop draws all diamonds adjacent to each other. Finally the image is mirrored. Note that Charcoal has since been extended and another byte could be saved by using `Increment`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~70~~ ~~69~~ 66 bytes ``` Bโ†{'/\ '['\/'โณโบโบโต]} Cโ†โŠข,โŒฝB C(โŠขโชโŠ–B)โŠƒ,/{CโŠ–Aโ†‘โŠ–' /'[โตโ‰คโˆ˜.+โจโณโต+1]}ยจโŒฝโณAโ†โŽ• ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP/OwGZ1er6MQrq0eox@uqPejc/6t0FRltja7mcgbKPuhbpPOrZ68TlrAFkPupd9ahrmpPmo65mHf1qZyDb8VHbRCClrqCvHg3U9ahzyaOOGXraj3pXgA3bqm0YW3toBdAEINcRZF7f1P9Aq/@ncxlypXMZAbExEJsAAA "APL (Dyalog Unicode) โ€“ Try It Online") Assumes `โŽ•IOโ†0`, which is standard on many systems, so the program is 0-indexed. This is a tradfn that takes input via STDIN. ### Explanation (slightly outdated) Note that `โบ` is the left argument, `โต` is the right argument and `โบโบ` is the left operator. `B` is a function that helps in mirroring the diamonds. It takes the string as the right argument and the reverse function as the left (so `B` is an operator). ``` Bโ†{'/\ '['\/'โณโบโบโต]} โบโบโต Apply โบโบ on โต '\/'โณ Find the index of the reflected string in '\/' (if the character is not found in `'\/'`, then return an index out of the bounds of the string, ie `2` if the character is a space) '/\ '[ ] Use these indexes on '/\ ' to reflect the '/\' characters ``` And now we go to the main part of the program. ``` Aโ†โŽ• Assign the input to variable A โณ Create a range 0 .. A-1 โŒฝ Reverse it so that it becomes A-1 .. 0 ยจ For each element do (the right argument is the element): โณโต+1 Create a range 0 .. โต โˆ˜.+โจ Create an addition table using the range to result in a matrix like so: 0+0 0+1 0+2 .. 0+โต 1+0 1+1 1+2 .. 1+โต 2+0 2+1 2+2 .. 2+โต ... โต+0 โต+1 โต+2 .. โต+โต โตโ‰ค The elements of the matrix that are greater than or equal to the โต, this creates a triangle matrix that looks like this: 0 0 .. 0 1 0 0 .. 1 1 .. 1 1 .. 1 1 ' /'[...] Index it in ' /' to get a character matrix (ie replace 0s with spaces and 1s with '/'s) โŠ– Flip this vertically Aโ†‘ Pad the top spaces ``` This is necessary to ensure that all the triangles created for every element in the range `โŒฝโณA` have the same height so that they can be later concatenated with each other. ``` โŠ– Flip the matrix vertically again to go back to the original state (โŠข, ) Concatenate it with โŒฝB itself, but flipped horizontally ,/ Concatenate all triangles formed by the range operator โŠƒ The resulting matrix is nested, so this operator "un-nests" it ``` Now the top left part of the pattern is complete. All that's remaining is to flip it vertically and then horizontally. ``` (โŠขโชโŠ–B) Concatenate the resulting matrix with itself but flipped vertically (the vertically flipped matrix is concatenated below of the original matrix) Now the left part of the pattern is complete (โŠข,โŒฝB) Concatenate the resulting matrix with itself flipped horizontally ``` And that's it! The output is a character matrix with `/\`s and padded with spaces. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~43~~ ~~41~~ ~~35~~ ~~34~~ ~~33~~ 32 bytes ``` '/ร—ฮทฮทvyโˆž.C.Bรธโ‚ฌโˆžยนNฮฑGรฐ.รธ}})รธรญJ.Bยปโˆž ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fXf/w9HPbz20vq3zUMU/PWc/p8I5HTWuA7EM7/c5tdD@8Qe/wjtpazcM7Dq/10nM6tBso8/@/MQA "05AB1E โ€“ Try It Online") (-4 bytes thanks to @Emigna who suggested 3 improvements) --- This explanation was for the earlier version, there have been a few iterations since then. ``` > # [2] '/ร— # ['//'] ฮท # ['/','//'] โ‚ฌฮท # [['/'], ['/', '//']] vy } # {For each element...} โˆž # Mirror horizontally. ยถยก # Split mirror on newlines. Nยฃ # Shave each diamond down a layer. .C # Horizontal center. .B # Pad for the transpose. รธ # Transpose. โ‚ฌโˆž # Mirror each (vertically). ยนNฮฑFรฐ.รธ} # Pad each list for transpose (verticaly). ) # Wrap back to list... โ‚ฌ.B # Pad each horizontally. ยฆ # Remove the random numbers? รธ # Back to horizontal... โ‚ฌR # Reverse to get correct order. J # Join, no spaces. ยป # Join newlines. โˆž # Final horizontal mirror. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~65~~ 63 bytes ``` q~_,:)_W%\+f{_2*S*a@2$-*\_,f{)'/*\Se[_W%'/'\er+}_W%Wf%+1$++}zN* ``` [Try it online!](https://tio.run/##S85KzP3/v7AuXsdKMz5cNUY7rTreSCtYK9HBSEVXKyZeJ61aU11fKyY4NRoora6vHpNapF0LZIanqWobqmhr11b5af3/bwoA "CJam โ€“ Try It Online") ### Explanation In this explanation, I will refer to the input number as `n`. ``` q~ e# Read and eval the input (push n to the stack). _, e# Copy it an get the range [0 .. n-1]. :) e# Increment each element to get [1 .. n]. _W% e# Copy it and reverse it. \+ e# Prepend the reverse to the original range, resulting in [n n-1 .. 1 1 .. n-1 n]. f{ e# Map over each number x in the range using n as an extra parameter: _2*S*a e# Push a string containing n*2 spaces, and wrap it in an array. @2$- e# Push n-x. * e# Repeat the space string from before n-x times. \ e# Bring x back to the top. _, e# Copy it and get the range [0 .. x-1]. f{ e# Map over each number y in this range, using x as an extra parameter: ) e# Increment y. '/* e# Repeat '/' y times. \Se[ e# Pad the resulting string to length x by adding spaces to the left. _W% e# Copy the result and reverse it. '/'\er e# Replace '/' with '\' in that. + e# Concatenate to the other string. This forms one row of one diamond. } e# (end map, now we have the top half of a diamond of size x) _W% e# Copy the half-diamond and reverse it. Wf% e# Reverse each row. + e# Concatenate to the top half. Now we have a full diamond of size x. 1$++ e# Put the spaces from before at the beginning and end. This is to pad the top e# and bottom of the smaller diamonds. } e# (end map) z e# Transpose. N* e# Join with newlines. Implicit output. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~152~~ ~~147~~ ~~143~~ 140 bytes -1 byte thanks to musicman523 ``` n=input() r=range(n) r+=r[::-1] for x,i in enumerate(r):a,b='/\\\/'[i<x::2];s=' '*(n+~i);print''.join((s+a*n)[:n-j]+(b*-~i+s)[j:]for j in r) ``` [Try it online!](https://tio.run/##Fc2xDoMgEIDh3adgA0RratLllCdBBkxoeyQ9zYmJXXx1Wrd/@v71m98L9aWQRVr3rHTFlgO9oqJ/GssOoL376rmwOBoUSCLS/okcclSsITSzld00TZ10OB4AvR82K4WsFZkT9bAyUpbylhYkpTYTatIOqE3eqLluTzSbdgn8NUgXz7qUxw8 "Python 2 โ€“ Try It Online") This works by chopping the inner columns of the largest diamond to make the smaller ones, using `[0,..,n,n,..,0]` to control the amount of columns to remove. [Answer] # Pyth, ~~35~~ 32 bytes ``` j.tsm+Jm.[yQS*"\/"k\ Sd_M_Js__BS ``` [Test suite](https://pyth.herokuapp.com/?code=j.tsm%2BJm.%5ByQS%2a%22%5C%2F%22k%5C+Sd_M_Js__BS&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=0) Done to see how my and @LeakyNun's approaches would differ. [Answer] # Dyalog APL, 46 ``` {โŠƒ,/โตโˆ˜{'/ \'[2+((-โชโŠ–)โŒฝ,-)(-โบ)โ†‘โˆ˜.โ‰ฅโจโณโต]}ยจ(โŒฝ,โŠข)โณโต} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 49 bytes ``` LC.tb)L+_b.rb"\/"js_,J'MsMCyMy_Mm'Myd._._*\/Q__MJ ``` [Try it online!](http://pyth.herokuapp.com/?code=LC.tb%29L%2B_b.rb%22%5C%2F%22js_%2CJ%27MsMCyMy_Mm%27Myd._._%2a%5C%2FQ__MJ&input=4&debug=0) [Answer] # [V](https://github.com/DJMcMayhem/V), 38 bytes ``` ร€รก/ร€รก\รฒ2ร™lX$xรฒรรฎ รฒYGpVรฆHร„ร“ยฏยจยฏ*รœ*ยฉรœ/ ยฑ ``` [Try it online!](https://tio.run/##AUEAvv92///DgMOhL8OAw6Fcw7Iyw5lsWCR4w7LDjcOuCsOyWUdwVsOmSMOEw5PCr8Kowq8qw5wqwqnDnC8gwrEg////NQ "V โ€“ Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 13 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ๏ผจ๏ผจ๏ผ๏ฝŽ๏ฝ๏ผโ•ฌ๏ผ‹๏ฝโคข๏ฝ’๏ผโ•‘ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjI4JXVGRjBGJXVGRjRFJXVGRjVEJXVGRjAxJXUyNTZDJXVGRjBCJXVGRjVEJXUyOTIyJXVGRjUyJXVGRjAxJXUyNTUx,i=NA__,v=8) ]
[Question] [ Everyone knows [log scales are for quitters](https://xkcd.com/1162/). Therefore, you must write a program or function that *de-quitifies* a bar graph with a log scale given a base. The bar graph input is taken as a single string which is a list of bars, where each bar of the log scale bar graph is separated by the printable (or whitespace) delimiter of your choosing (so `0x09-0x0A + 0x20-0x7E`) and composed of a printable non-whitespace (so `0x21-0x7E`) filler character of your choosing. The program or function outputs a single string which is a list of bars, where each bar is separated by the same delimiter the input was separated by and is composed of the same filler character the input was composed of. # Example We choose a delimiter of `"\n"` (one newline) and a filler character of `"#"`. The input passed to our program or function is: base=`2` and string= ``` #### ## ###### ### ``` The code would find that the lengths of the bars are `[4,2,6,3]`. It would compute the anti-log of each length with base `2` to get `[2^4,2^2,2^6,2^3]` = `[16,4,64,8]`. Then, the lengths are output in linear scale bar format: ``` ################ #### ################################################################ ######## ``` # Input / Output Your program or function may input and output in any [reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). The input base is guaranteed to be an integer greater than 1. You may assume the base is less than 256. The string input is guaranteed to fully match the regex [`(f+s)+f+`](https://regex101.com/r/ttGCOg/1), where `f` and `s` are replaced with your filler and delimiter respectively. The string output must fully match the regex [`(f+s)+f+`](https://regex101.com/r/ttGCOg/1), where `f` and `s` are replaced with the same filler and delimiter respectively. The output may optionally have a trailing newline. The output and input may also be a list of strings instead of delimited by a substring, though it must be possible to understand which bar is which. # Testcases (assume filler is `#` and delimiter is `\n`) ``` base - input string - output string ----- 2 - #### ## ###### ### - ################ #### ################################################################ ######## ----- 3 - ## # ### # - ######### ### ########################### ### ----- 100 - # I am not the delimiter ### nor the filler - Anything (You do not have to handle input which does not match the regex) ----- 1 - ### ####### ################################################### - Anything (You do not have to handle bases less than or equal to 1). ----- 5 - #### ## ### # - ################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################# ######################### ############################################################################################################################# ##### ----- 2 - # # ## ## # ## # # # # ## ## # # ## # - ## ## #### #### ## #### ## ## ## ## #### #### ## ## #### ## ``` [Answer] ## x86 32-bit machine code function, 21 bytes ## x86-64 machine code function, 22 bytes The 1B saving in 32-bit mode requires using separator = filler-1, e.g. `fill=0` and `sep=/`. The 22-byte version can use an arbitrary choice of separator and filler. --- **This is the 21-byte version, with input-separator = `\n` (0xa), output-filler = `0`, output-separator = `/` = filler-1. These constants can be easily changed.** ``` ; see the source for more comments ; RDI points to the output buffer, RSI points to the src string ; EDX holds the base ; This is the 32-bit version. ; The 64-bit version is the same, but the DEC is one byte longer (or we can just mov al,output_separator) 08048080 <str_exp>: 8048080: 6a 01 push 0x1 8048082: 59 pop ecx ; ecx = 1 = base**0 8048083: ac lods al,BYTE PTR ds:[esi] ; skip the first char so we don't do too many multiplies ; read an input row and accumulate base**n as we go. 08048084 <str_exp.read_bar>: 8048084: 0f af ca imul ecx,edx ; accumulate the exponential 8048087: ac lods al,BYTE PTR ds:[esi] 8048088: 3c 0a cmp al,0xa ; input_separator = newline 804808a: 77 f8 ja 8048084 <str_exp.read_bar> ; AL = separator or terminator ; flags = below (CF=1) or equal (ZF=1). Equal also implies CF=0 in this case. ; store the output row 804808c: b0 30 mov al,0x30 ; output_filler 804808e: f3 aa rep stos BYTE PTR es:[edi],al ; ecx bytes of filler 8048090: 48 dec eax ; mov al,output_separator 8048091: aa stos BYTE PTR es:[edi],al ;append delim ; CF still set from the inner loop, even after DEC clobbers the other flags 8048092: 73 ec jnc 8048080 <str_exp> ; new row if this is a separator, not terminator 8048094: c3 ret 08048095 <end_of_function> ; 0x95 - 0x80 = 0x15 = 21 bytes ``` The 64-bit version is 1 byte longer, using a 2-byte DEC or a `mov al, output_separator`. Other than that, the machine-code is the same for both versions, but some register names change (e.g. `rcx` instead of `ecx` in the `pop`). Sample output from running the test program (base 3): ``` $ ./string-exponential $'.\n..\n...\n....' $(seq 3);echo 000/000000000/000000000000000000000000000/000000000000000000000000000000000000000000000000000000000000000000000000000000000/ ``` **Algorithm**: Loop over the input, doing `exp *= base` for every filler char. On delimiters and the terminating zero byte, append `exp` bytes of filler and then a separator to the output string and reset to `exp=1`. It's very convenient that the input is guaranteed not to end with both a newline *and* a terminator. On input, any byte value above the separator (unsigned compare) is treated as filler, and any byte value below the separator is treated as an end-of-string marker. (Checking explicitly for a zero-byte would take an extra `test al,al` vs. branching on flags set by the inner loop). --- The rules only allow a trailing separator when it's a trailing newline. My implementation always appends the separator. **To get the 1B saving in 32-bit mode, that rule requires separator = 0xa (`'\n'` ASCII LF = linefeed), filler = 0xb (`'\v'` ASCII VT = vertical tab).** That's not very human-friendly, but satisfies the letter of the law. (You can hexdump or `tr $'\v' x` the output to verify that it works, or change the constant so the output separator and filler are printable. I also noticed that the rules seem to require that it can accept input with the same fill/sep it uses for output, but I don't see anything to gain from breaking that rule.). --- NASM/YASM source. Build as 32 or 64-bit code, using the `%if` stuff included with the test program or just change rcx to ecx. ``` input_separator equ 0xa ; `\n` in NASM syntax, but YASM doesn't do C-style escapes output_filler equ '0' ; For strict rules-compliance, needs to be input_separator+1 output_separator equ output_filler-1 ; saves 1B in 32-bit vs. an arbitrary choice ;; Using output_filler+1 is also possible, but isn't compatible with using the same filler and separator for input and output. global str_exp str_exp: ; void str_exp(char *out /*rdi*/, const char *src /*rsi*/, ; unsigned base /*edx*/); .new_row: push 1 pop rcx ; ecx=1 = base**0 lodsb ; Skip the first char, since we multiply for the separator .read_bar: imul ecx, edx ; accumulate the exponential lodsb cmp al, input_separator ja .read_bar ; anything > separator is treated as filler ; AL = separator or terminator ; flags = below (CF=1) or equal (ZF=1). Equal also implies CF=0, since x-x doesn't produce carry. mov al, output_filler rep stosb ; append ecx bytes of filler to the output string %if output_separator == output_filler-1 dec eax ; saves 1B in the 32-bit version. Use dec even in 64-bit for easier testing %else mov al, output_separator %endif stosb ; append the delimiter ; CF is still set from the .read_bar loop, even if DEC clobbered the other flags ; JNC/JNB here is equivalent to JE on the original flags, because we can only be here if the char was below-or-equal the separator jnc .new_row ; separator means more rows, else it's a terminator ; (f+s)+f+ full-match guarantees that the input doesn't end with separator + terminator ret ``` **The function follows the x86-64 SystemV ABI, with signature `void str_exp(char *out /*rdi*/, const char *src /*rsi*/, unsigned base /*edx*/);`** It only informs the caller of the length of the output string by leaving a one-past-the-end pointer to it in `rdi`, so you could consider this the return value in a non-standard calling convention. It would cost 1 or 2 bytes (`xchg eax,edi`) to return the end-pointer in eax or rax. (If using the x32 ABI, pointers are guaranteed to be only 32 bits, otherwise we have to use `xchg rax,rdi` in case the caller passes a pointer to a buffer outside the low 32 bits.) I didn't include this in the version I'm posting because there are workarounds the caller can use without getting the value from `rdi`, so you could call this from C with no wrapper. We don't even null-terminate the output string or anything, so it's only newline-terminated. It would take 2 bytes to fix that: `xchg eax,ecx / stosb` (rcx is zero from `rep stosb`.) The ways to find out the output-string length are: * rdi points to one-past-the-end of the string on return (so the caller can do len=end-start) * the caller can just know how many rows were in the input and count newlines * the caller can use a large zeroed buffer and `strlen()` afterwards. They're not pretty or efficient (except for using the RDI return value from an asm caller), but if you want that then don't call golfed asm functions from C. :P --- **Size/range limitations** The max output string size is only limited by virtual memory address-space limitations. (Mainly that current x86-64 hardware only supports 48 significant bits in virtual addresses, [split in half because they sign-extend instead of zero-extend. See the diagram in the linked answer](https://stackoverflow.com/a/38983032/224132).) Each row can only have a maximum of 2\*\*32 - 1 filler bytes, since I accumulate the exponential in a 32-bit register. The function works correctly for bases from 0 to 2\*\*32 - 1. (Correct for base 0 is 0^x = 0, i.e. just blank lines with no filler bytes. Correct for base 1 is 1^x = 1, so always 1 filler per line.) It's also blazingly fast on Intel IvyBridge and later, especially for large rows being written to aligned memory. [`rep stosb` is an optimal implementation of `memset()` for large counts with aligned pointers on CPUs with the ERMSB feature](https://stackoverflow.com/questions/33480999/how-can-the-rep-stosb-instruction-execute-faster-than-the-equivalent-loop). e.g. 180\*\*4 is 0.97GB, and takes 0.27 seconds on my i7-6700k Skylake (with ~256k soft page-faults) to write to /dev/null. (On Linux the device-driver for /dev/null doesn't copy the data anywhere, it just returns. So all of the time is in the `rep stosb` and the soft page-faults that triggers when touching the memory for the first time. It's unfortunately not using transparent hugepages for the array in the BSS. Probably an `madvise()` system call would speed it up.) **Test program**: Build a static binary and run as `./string-exponential $'#\n##\n###' $(seq 2)` for base 2. To avoid implementing an `atoi`, it uses `base = argc-2`. (Command-line length limits prevent testing ridiculously large bases.) This wrapper works for output strings up to 1 GB. (It only makes a single write() system call even for gigantic strings, but Linux supports this even for writing to pipes). For counting characters, either pipe into `wc -c` or use `strace ./foo ... > /dev/null` to see the arg to the write syscall. This takes advantage of the RDI return-value to calculate the string length as an arg for `write()`. ``` ;;; Test program that calls it ;;; Assembles correctly for either x86-64 or i386, using the following %if stuff. ;;; This block of macro-stuff also lets us build the function itself as 32 or 64-bit with no source changes. %ifidn __OUTPUT_FORMAT__, elf64 %define CPUMODE 64 %define STACKWIDTH 8 ; push / pop 8 bytes %define PTRWIDTH 8 %elifidn __OUTPUT_FORMAT__, elfx32 %define CPUMODE 64 %define STACKWIDTH 8 ; push / pop 8 bytes %define PTRWIDTH 4 %else %define CPUMODE 32 %define STACKWIDTH 4 ; push / pop 4 bytes %define PTRWIDTH 4 %define rcx ecx ; Use the 32-bit names everywhere, even in addressing modes and push/pop, for 32-bit code %define rsi esi %define rdi edi %define rsp esp %endif global _start _start: mov rsi, [rsp+PTRWIDTH + PTRWIDTH*1] ; rsi = argv[1] mov edx, [rsp] ; base = argc sub edx, 2 ; base = argc-2 (so it's possible to test base=0 and base=1, and so ./foo $'xxx\nxx\nx' $(seq 2) has the actual base in the arg to seq) mov edi, outbuf ; output buffer. static data is in the low 2G of address space, so 32-bit mov is fine. This part isn't golfed, though call str_exp ; str_exp(outbuf, argv[1], argc-2) ; leaves RDI pointing to one-past-the-end of the string mov esi, outbuf mov edx, edi sub edx, esi ; length = end - start %if CPUMODE == 64 ; use the x86-64 ABI mov edi, 1 ; fd=1 (stdout) mov eax, 1 ; SYS_write (Linux x86-64 ABI, from /usr/include/asm/unistd_64.h) syscall ; write(1, outbuf, length); xor edi,edi mov eax,231 ; exit_group(0) syscall %else ; Use the i386 32-bit ABI (with legacy int 0x80 instead of sysenter for convenience) mov ebx, 1 mov eax, 4 ; SYS_write (Linux i386 ABI, from /usr/include/asm/unistd_32.h) mov ecx, esi ; outbuf ; 3rd arg goes in edx for both ABIs, conveniently enough int 0x80 ; write(1, outbuf, length) xor ebx,ebx mov eax, 1 int 0x80 ; 32-bit ABI _exit(0) %endif section .bss align 2*1024*1024 ; hugepage alignment (32-bit uses 4M hugepages, but whatever) outbuf: resb 1024*1024*1024 * 1 ; 2GB of code+data is the limit for the default 64-bit code model. ; But with -m32, a 2GB bss doesn't get mapped, so we segfault. 1GB is plenty anyway. ``` --- **This was a fun challenge that lent itself very well to asm, especially x86 string ops**. The rules are nicely designed to avoid having to handle a newline and then a terminator at the end of the input string. An exponential with repeated multiplication is just like multiplying with repeated addition, and I needed to loop to count chars in each input row anyway. I considered using one-operand `mul` or `imul` instead of the longer `imul r,r`, but its implicit use of EAX would conflict with LODSB. --- **I also tried SCASB instead of load and compare**, but I needed `xchg esi,edi` before and after the inner loop, because SCASB and STOSB both use EDI. (So the 64-bit version has to use the x32 ABI to avoid truncating 64-bit pointers). Avoiding STOSB is not an option; nothing else is anywhere near as short. And half the benefit of using SCASB is that AL=filler after leaving the inner loop, so we don't need any setup for REP STOSB. SCASB compares in the other direction from what I had been doing, so I needed to reverse the comparisons. My best attempt with xchg and scasb. Works, but isn't shorter. (**32-bit code, using the `inc`/`dec` trick to change filler into separator**). ``` ; SCASB version, 24 bytes. Also experimenting with a different loop structure for the inner loop, but all these ideas are break-even at best ; Using separator = filler+1 instead of filler-1 was necessary to distinguish separator from terminator from just CF. input_filler equ '.' ; bytes below this -> terminator. Bytes above this -> separator output_filler equ input_filler ; implicit output_separator equ input_filler+1 ; ('/') implicit 8048080: 89 d1 mov ecx,edx ; ecx=base**1 8048082: b0 2e mov al,0x2e ; input_filler= . 8048084: 87 fe xchg esi,edi 8048086: ae scas al,BYTE PTR es:[edi] 08048087 <str_exp.read_bar>: 8048087: ae scas al,BYTE PTR es:[edi] 8048088: 75 05 jne 804808f <str_exp.bar_end> 804808a: 0f af ca imul ecx,edx ; exit the loop before multiplying for non-filler 804808d: eb f8 jmp 8048087 <str_exp.read_bar> ; The other loop structure (ending with the conditional) would work with SCASB, too. Just showing this for variety. 0804808f <str_exp.bar_end>: ; flags = below if CF=1 (filler<separator), above if CF=0 (filler<terminator) ; (CF=0 is the AE condition, but we can't be here on equal) ; So CF is enough info to distinguish separator from terminator if we clobber ZF with INC ; AL = input_filler = output_filler 804808f: 87 fe xchg esi,edi 8048091: f3 aa rep stos BYTE PTR es:[edi],al 8048093: 40 inc eax ; output_separator 8048094: aa stos BYTE PTR es:[edi],al 8048095: 72 e9 jc 8048080 <str_exp> ; CF is still set from the inner loop 8048097: c3 ret ``` For an input of `../.../.`, produces `..../......../../`. I'm not going to bother showing a hexdump of the version with separator=newline. [Answer] ## Mathematica ~~41~~ 38 Bytes -3 Bytes thanks to LLlAMnYP This takes input as a list of strings followed by an integer. Output is also a list of strings. ``` ""<>"#"~Table~#&/@(#2^StringLength@#)& ``` Explanation: ``` StringLength@# & - find length of each string in first input #2^ & - raise to power of second input /@( ) - Uses each of these numbers on an inner function of ... "#"~Table~#& - Create arrys of specific length using character "#" ""<> - Join arrays of characters together to make strings ``` Old version, 41 Bytes ``` "#"~StringRepeat~#&/@(#2^StringLength@#)& ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes Takes the graph as an array of strings with `"` as the filler, and the base as an integer. ``` ยฃQpVpXl ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=o1FwVnBYbA==&input=WyciJywnIiInLCciIiInLCciIiIiJ10sMg==) Add `}R` to the end in order to take the graph as a newline separated string instead. ([Try it](http://ethproductions.github.io/japt/?v=1.4.4&code=o1FwVnBYbH1S&input=JyIKIiIKIiIKIiIiIicsMg==)) --- ## Explanation ``` :Implicit input of array U. ยฃ :Map over the array, replacing each element with ... Q :the " character ... p :repeated ... V :integer input ... p :to the power of ... Xl :the length of the current element times. :Implicit output of result. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 11 bytes ``` Y'iw^1HL(Y" ``` Delimiter is space. Filler is any character other than space. [Try it online!](https://tio.run/nexus/matl#@x@pnlkeZ@jhoxGp9P@/urKyAhCCSHUuYwA "MATL โ€“ TIO Nexus") ### Explanation ``` % Implicit input: string % STACK: '## # ### #' Y' % Run-length encoding % STACK: '# # # #', [2 1 1 1 3 1 1] i % Input: number % STACK: '# # # #', [2 1 1 1 3 1 1], 3 w % Swap % STACK: '# # # #', 3, [2 1 1 1 3 1 1] ^ % Power, element-wise % STACK: '# # # #', [9 3 3 3 9 3 3] 1 % Push 1 % STACK: '# # # #', [9 3 3 3 27 3 3], 1 HL % Push [2 2 1j]. When used as an index, this means 2:2:end % STACK: '# # # #', [9 3 3 3 27 3 3], 1, [2 2 1j] ( % Write specified value at specified entries % STACK: '# # # #', [9 1 3 1 27 1 3] Y" % Run-length decoding % STACK: '######### ### ########################### ###' % Implicit display ``` [Answer] ## [Haskell](https://www.haskell.org/), ~~37~~ 33 bytes *4 bytes shaved off thanks to sudee* ``` \b->map(\x->'#'<$[1..b^length x]) ``` Description: ``` \b-> -- take an integer b as the first input input map(\x-> ) -- apply the following to every element x in the second input '#'<$[1..b^length x] ---- replicate '#' (b^(length x)) times ``` Disappointingly, this is ~~2 bytes~~ much shorter than the way-harder-to-read pointfree version: ``` map.(flip replicate '#'.).(.length).(^) ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` f b=map$foldr(\_->([1..b]>>))"#" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hyTY3sUAlLT8npUgjJl7XTiPaUE8vKdbOTlNTSVnpf25iZp6CrUJKPpcCEACV@ioUlJYElxT55CmoKKQpGClEKykDgZKOEpSA85SVYsGa4OqVlHAYYgw2BKQJqhHEiv0PAA "Haskell โ€“ Try It Online") Example usage: `f 3 ["##","#","###","#"]` returns `["#########","###","###########################","###"]`. Use `mapM putStrLn $ f 3 ["##","#","###","#"]` to get a more visually pleasing output: ``` ######### ### ########################### ### ``` [Answer] # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 105 bytes ``` #import math (\d+)\n((;.*\n)*)(_+)/$1\n$2;$1^d<$4>/^\d+\n((;\d+\n?)+)$/$1/^((_*\n)*);(\d+)/$1u<$3>/#input ``` [Try it online!](https://tio.run/nexus/reregex#@6@cmVuQX1SikJtYksGlEZOirRmTp6FhracVk6eppakRr62pr2IYk6diZK1iGJdio2Jipx8HVAVWBKbtNbU1VYBq9OM0NOIhuqzB5gDFSm1UjO30lTPzCkpL/v834ooHAi4wgrLiAQ "ReRegex โ€“ TIO Nexus") ReRegex is like Retina's ugly cousin that gives *all* the effort to Regular Expressions, instead of having it's own fancy operators. Of course, it also has `#import` and `#input` to save both hardcoding input, and re-writing the same expressions over and over again. # Explained. Takes input in the form of: ``` 2 ____ __ ______ ___ ``` on STDIN, and gives output like ``` ________________ ____ ________________________________________________________________ ________ ``` Firstly, the program imports the [Math Library](https://github.com/TehFlaminTaco/ReRegex/blob/master/export/lib/math.rr), which of course is entirely written in ReRegex. The bulk of this is then three regular expressions. ``` (\d+)\n((;.*\n)*)(_+) -> $1\n$2;$1^d<$4> ^\d+\n((;\d+\n?)+)$ -> $1 ^((_*\n)*);(\d+) -> $1u<$3> ``` The first matches our input base, and seeks a line of unary after it. it then, replaces that line with `;$1^d<$4>`, which is the base, to the power of the (In Decimal) Unary. The Math library handles the base conversion and the exponent. A ; is placed at the start to identify it later as finished. The second, matches the base, then many lines of ;, before ending. If this matches the entire thing, it snips off the base. leaving uf with just the answers and `;`s. The last, matches just unary at the start, optionally, then a `;` answer. It then transforms that answer into unary again, without the `;`. Because the output isn't matched by the first regex, it doesn't loop infinitely, and so our solution is outputted. [Answer] # [Python 2](https://docs.python.org/2/), ~~52~~ 36 bytes Input and output are taken as arrays of strings. `#` is the filler. ``` lambda s,n:['#'*n**len(l)for l in s] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQrJNnFa2urK6Vp6WVk5qnkaOZll@kkKOQmadQHPu/oCgzr0QhTQOoAgjUdRTUYSSCr6weq6NgpMmFrBYsA5MGs4FqjFHVoJkHV2aKogzJJCQSnYlGYJdHWGGk@R8A "Python 2 โ€“ TIO Nexus") [Answer] # [Rรถda](https://github.com/fergusq/roda), 19 bytes ``` f n,s{s|["#"*n^#_]} ``` [Try it online!](https://tio.run/##K8pPSfz/P00hT6e4urgmWklZSSsvTjk@tvZ/bmJmXjVXom2CsjKXMghwgWkwO0E/gSuBK03BSCexJjpeB8iJ5ar9DwA "Rรถda โ€“ Try It Online") Takes an array as input and returns a stream of values as output. ### Explanation ``` f n,s{s|["#"*n^#_]} n is the number and s is the array of strings consisting of #s s| Push the each value of s to the stream [ ] For each push "#"* "#" repeated n^#_ n raised to the length of the string ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes Bars are seperated by spaces, output character is same as input character. ``` ยฌล #โ‚ฌgmร—รฐรฝ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0JqjC5QfNa1Jzz08/fCGw3v//1cGAgUwgrKUuYwA "05AB1E โ€“ Try It Online") ``` ยฌล #โ‚ฌgmร—รฐรฝ Arguments: n, s ยฌ Head, get bar character ล  Rearrange stack to get: s, n, bar-character # Split s on spaces โ‚ฌg Map to length m n to that power ร— That many bar-characters รฐรฝ Join on space Implicit output ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://github.com/abrudz/SBCS) Anonymous tacit infix function taking base as left argument and list of strings as right argument ``` *โˆ˜โ‰ขยจโดยจโŠข ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@tRx4xHnYsOrXjUuwVIdC36n/aobcKj3r5HXc2PeteARNcbP2qb@KhvanCQM5AM8fAM/g8UMFJIU1BXBgJ1EKUOYcMY6ly6urpcQFXGEFUgUagMiAWTNYSaoa6gANOPwiYFwA01xeIwFFshLoc7SR3FgepIUtiVIHEUAA "APL (Dyalog Unicode) โ€“ Try It Online") `*โˆ˜โ‰ขยจ`โ€ƒbase to the power of the length of each string `โดยจ`โ€ƒcyclically reshapes each `โŠข`โ€ƒstring [Answer] # [Julia](http://julialang.org/), 22 bytes ``` x$b="#".^b.^length.(x) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v0IlyVZJWUkvLkkvLic1L70kQ0@jQvN/tJIyEChxKUEJOE9ZKVbFSKHGTiEls7ggJ7GSi6ugKDOvJCdPQ5OLKxqqHKoSxIpVMUZS/R8A "Julia 1.0 โ€“ Try It Online") input and output are lists of strings [Answer] # [Risky](https://github.com/Radvylf/risky), 6 bytes ``` _?_!?_?[*+? ``` [Try it online!](https://radvylf.github.io/risky?p=WyJfP18hP18_WyorPyIsIltbXCJAQEBAXCIsIFwiQEBcIiwgXCJAQEBAQEBcIiwgXCJAQEBcIl1dIiwxXQ) Inputs and outputs an array like `["@@", "@@@@"]`. Unfortunately, the output is implicitly concatenated. 6 more bytes to have it joined by newlines: # [Risky](https://github.com/Radvylf/risky), 12 bytes ``` _*+_0+_0+_0*_?_!?_?[*+? ``` [Try it online!](https://radvylf.github.io/risky?p=WyJfKitfMCtfMCtfMCpfP18hP18_WyorPyIsIltbXCJAQEBAXCIsIFwiQEBcIiwgXCJAQEBAQEBcIiwgXCJAQEBcIl1dIiwxXQ) [Answer] # PHP, 69 Bytes ``` <?foreach($_GET[1]as$l)echo str_pad("",$_GET[0]**strlen($l),"#")." "; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUol3dw2xjVYyVtKJVlIGAiUdJSgBJpViY63/p@UXpSYmZ2iAFUcbxiYWq@RopiZn5CsUlxTFFySmaCgp6UAkDWK1tICCOal5GkA1IAM09ZS4lKz//wcA "PHP โ€“ TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แนL*@ยฅยฅโ‚ฌ ``` A monadic link taking and returning lists of the bars (themselves lists of characters, AKA strings) the filler character is flexible. **[Try it online!](https://tio.run/nexus/jelly#@/9wZ6OPlsOhpYeWPmpa8//w8sj//6OVlJWVdJTAGMqK/W8MAA "Jelly โ€“ TIO Nexus")** (the footer prettifies the resulting list by joining its elements with newlines.) ### How? ``` แนL*@ยฅยฅโ‚ฌ - Main link: list of list of characters, bars; number, base ยฅโ‚ฌ - last two links as a dyad for โ‚ฌach bar in bars: ยฅ - last two links as a dyad: L - length (of a bar) *@ - exponentiate (swap @rguments) (base ^ length) แน - mould like (e.g. moulding "##" like 8 yields "########") ``` --- Alternative 7-byter: `แน"Lโ‚ฌ*@ยฅ` - get length of each bar (`Lโ‚ฌ`), raise `base` to that power (`*@`), then zip (`"`) the list and that applying the mould dyad (`แน`) between the two. [Answer] # [Ruby](https://www.ruby-lang.org/), 29 bytes ``` ->x,y{x.map{|z|?#*y**z.size}} ``` [Try it online!](https://tio.run/nexus/ruby#S7ON@a9rV6FTWV2hl5tYUF1TVWOvrFWppVWlV5xZlVpb@79AIU1PI1pdWV1HQV0ZSiqrx@ooGGly4ZQz1vwPAA "Ruby โ€“ TIO Nexus") Yeah, I found out last week that `?#` produces a single-character string. I've no idea why this feature exists but I'm sure glad it does. [Answer] # JavaScript (ES8), 39 bytes Takes the base as an integer and the graph as an array of strings with any character as the filler, using currying syntax. ``` b=>a=>a.map(x=>x.padEnd(b**x.length,x)) ``` --- ## Try it ``` f= b=>a=>a.map(x=>x.padEnd(b**x.length,x)) oninput=_=>o.innerText=f(i.value)(j.value.split`\n`).join`\n` o.innerText=f(i.value=2)((j.value=`####\n##\n######\n###`).split`\n`).join`\n` ``` ``` *{box-sizing:border-box}#i,#j{margin:0 0 5px;width:200px}#j{display:block;height:100px ``` ``` <input id=i type=number><textarea id=j></textarea><pre id=o> ``` --- ## Alternative, 49 bytes This version takes the graph as a newline separated string, again with any character as filler. ``` b=>s=>s.replace(/.+/g,m=>m.padEnd(b**m.length,m)) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `r`, 6 bytes ``` ฦ›Lโฐeร—* ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=r&code=%C6%9BL%E2%81%B0e%C3%97*&inputs=%5B%22**%22%2C%22*%22%2C%22***%22%2C%22*%22%5D%0A3&header=&footer=) Inputs and outputs a list of strings; uses `*` as the filler character 'cuz that's easy in Vyxal. ``` ฦ›Lโฐeร—* ฦ› # For each bar in the string e # Raise... โฐ # the base... L # to the power of the bar's length ร—* # Push that many *s ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` แบˆฦ“*แน@" ``` [Try it online!](https://tio.run/##y0rNyan8///hro5jk7Ue7mx0UPp/uD3yv/H/aCVlZSUdJTCGsmIB "Jelly โ€“ Try It Online") Takes a list of lines on the left and the base on STDIN ## How it works ``` แบˆฦ“*แน@" - Main link. Takes a list of lines L on the left แบˆ - Get the lengths of each line ฦ“ - Read the base b from STDIN * - Raise b to the power of each length " - For each pair (length, original_line): @ - Reverse the arguments as (original_line, length): แน - Mold the original_line to the length ``` [Answer] # Excel, 24 bytes ``` =REPT("#",A1^LEN(A2:A5)) A1 is the base A2:A5 are the input lines ``` [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 21 bytes ``` ;=y+0P W=xP O*"#"^yLx ``` [Try it online!](https://tio.run/##rVlbU9vIEn62f8VgCksjy4ksOFVbNjJFspCilgALyckDeIOQZVCtLHslGcIS9q/ndPdcNLJNzt54kDQz3T1fX6a7x0Td2yj6tplkUboYx7tFOU5mr@6GTXMmTW5qU1H5OI@XiPIku61NlclU0IzjSZLFLE1ZOstu6dHUsx9OPr5nvWp48eGc@dXwv/vnbKcaHp68ZT9Uw/OPrFcRHx5fGLQnH48N0o8n7/cvfrILzmx8tNkfvf9wvbp/AduKxeguzJnDKwaTCrBqEcMh26nW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ryPgVAKQvKSTcNsAWH1@ApnUcsb9ASYhixTLNISf0ygzXUiVCRdk0ZtWbNdnU@TLIlHeS9Tei8D0WS7NSqP7u1hijXzEbTOxmk8ZtcV7Gst5Qm/RMNmbFIpM0Rh3a4acyJvSFLHgP6s8@MuBfFSQcRkWMuXQT1b7jEzKeyaxwNZ@/LnuDYTBHus1kDSpMuMLIkyPMGpSrEv6gPSbgRQhYzuaAiHFUNrNp712TSeRnMMs4wNr/f@qSrDf0GVoVJlY40ugdRFqrL3svXFrmsg4/IeqxH4msJXhXVjHc5qoNVTGckUoOG1q7SIuqyrGXsmp8wlmv/rn@GXScgQo/kHVt@krrW/y7RBlY3ry3/5gqN63uqGg3SN2i1Hp0KiQYmjoMZtpEnkQIpOR7MJyJ9APfFrmNmA1rRjZk8j2Y7q3TySGvx7fn/bMMs7cZUIjM6rYxam1btTJi8krj4L27VG90IYeknoYLkU@utK4TbX/YGvuXdo8v80SggM3@iKSF8KdJtk9kw@aIi7dnrYPFHjIOJfLNKLKDryJMDu43gSQpIEzVTnmWSwmIzpx6UwKqFMWVuRhb0oznD2wu0WhekaCF2i/IFhGiYZNrEszG8jl4Q6Dnzfc/wZi@6d@N8d2yM09evd87ft5ib8weN/) Had to actually fix a bug in the interpreter on this one. Delimiter is newline, filler is `#` (although it doesn't check this, it just checks the length) ``` # read base, coerce to int ; = base + 0 PROMPT # read all lines : WHILE (= line PROMPT) # output base ^ length(line) #'s OUTPUT(* "#" (^ base LENGTH(line))) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rl`, ~~9~~ 8 bytes ``` 0XaE#*Sg ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgebSSblGOUuyCpaUlaboWKwwiEl2VtYLTIVyo6IItRlzKQMAFRlCWMkQOAA) Takes the base followed by the bar graph (using any non-whitespace symbol) from stdin; outputs a bar graph of `0`s to stdout. ### Explanation ``` g List of lines of stdin (due to -r flag) S All but the first element #* Length of each aE First line of stdin raised to each of those powers 0X 0 repeated that many times Autoprint (implicit), one element per line (due to -l flag) ``` [Answer] # Mathematica, 86 bytes ``` (s=#2^StringLength[StringSplit@#1];StringJoin/@Table[Table["#",s[[i]]],{i,Length@s}])& ``` **input** > > ["####\n##\n######\n###", 2] > > > [Answer] # Octave, 42 bytes ``` @(b,s)[(1:max(k=b.^sum(s'>32)')<=k)+32 ''] ``` \*The string input/output doesn't fully match the regex but it is possible to understand which bar is which. A function takes as input base `b` and a 2D array of chars `s` containing `"!"` and the output is also an array of chars. [Try it online!](https://tio.run/nexus/octave#@@@gkaRTrBmtYWiVm1ihkW2bpBdXXJqrUaxuZ2ykqa5pY5utqW1spKCuHvs/zVYhMa/YmivJ1siai6vYNlpPT49LXREI1EGUOoQNY6jHAhWlgU3n@g8A "Octave โ€“ TIO Nexus") Explanation: ``` s'>32 % logical array of input represents 1 for filler and 0 for spaces sum( )' % an array containing length of each string k=b.^ % exponentiate ( lengths of output) 1:max( ) % range form 1 to max of output lengths <=k % logical array of output represents 1 for filler and 0 for spaces [( )+32 ''] % convert the logical array to char array. ``` [Answer] # CJam, 20 bytes ``` q~:A;N/{,A\#"#"e*N}% ``` ## Input format Input is required in the following format: ``` "## #### ######"2 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` ๏ผฎฮฒ๏ผท๏ผณยซ๏ผฐ๏ผธฮฒ๏ผฌฮนโ†“ ``` [Try it online!](https://tio.run/nexus/charcoal#@@@ZV1Ba4leam5RapJGkac1VnpGZk6qgARYOLinKzEvX0NRUqObi9C3NKcksAAqUaATkl4NU6yj4pOall2RoZGpqAnVy@uaXpWpYueSX5wF5tf//G3HpAgEXGEFZulz/dcv@6xbnAAA "Charcoal โ€“ TIO Nexus") Link is to verbose version of code. I/O is as a list of strings of `-` characters (note that you need an empty line to terminate the list). [Answer] # [V](https://github.com/DJMcMayhem/V), 27 bytes The basic idea is that we add a `'` to each row (n^0), and then for each `#` we replace the `'`s in the line with `[input] * '`. At the end I swapped all of the `'` for `#` again ``` ร€รฉ'ld0รŽA' รฒ/# "_xร“'/"รฒร'/# ``` [Try it online!](https://tio.run/nexus/v#@3@44fBK9ZwUg8N9jupchzfpK3MpxVccnqyuL6R0eNPhXnV95f//lZWVuYBQ@b8RAA "V โ€“ TIO Nexus") [Answer] # [R](https://www.r-project.org/), 35 bytes ``` function(s,b)strrep('#',b^nchar(s)) ``` an anonymous function which takes the strings as a list and the base, and returns a list of strings. [Try it online!](https://tio.run/nexus/r#S7P9n1aal1ySmZ@nUayTpFlcUlSUWqChrqyukxSXl5yRWKRRrKn5P00jGSgGBOo66lACzlNW19Qx0vwPAA "R โ€“ TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` U|v1Xygmร—, ``` The filer character is `1` and the delimiter is a newline. [Try it online!](https://tio.run/nexus/05ab1e#@x9aU2YYUZmee3i6zv//RlyGQMAFRlCWIQA "05AB1E โ€“ TIO Nexus") ``` U # Store the base in X | # Get the rest of input as a list of lines v # For each... 1 # Push 1 X # Push the base y # Push this bar g # Get the length m # Push a**b ร—, # Print a string of #s with that length ``` [Answer] # [Retina](https://github.com/m-ender/retina), 62 bytes ``` ms`^(?=.*ยถ(.*)) #;$1$*#; {`#(?=#*;(#+);#) $1 }m`#$ ;#+;|ยถ.*$ ``` [Try it online!](https://tio.run/nexus/retina#@59bnBCnYW@rp3Vom4aelqYml7K1iqGKlrI1V3WCMlBCWctaQ1lb01pZk0vFkKs2N0FZhYvLWlnbuubQNj0tFa7//5WBgAuMoCxlLiMA "Retina โ€“ TIO Nexus") After all, a bar graph is just a list of unary numbers. Takes input as the graph (using `#`s) followed by the base in decimal (to avoid confusion). Explanation: The first replacement prefixes 1 and the base to each line of the graph. The second replacement then multiplies the first number on each line by the second, as long as the third number is nonzero. The third replacement then decrements the third number on each line. These two replacements are repeated until the third number becomes zero. The last replacement deletes the base everywhere, leaving the desired result. ]
[Question] [ In that Coding Golf, you should convert one coding convention with TitleCase to lower\_case\_with\_underscores. And... vice versa! # Specification Change the casing in a following way: * If underscore character is a delimiter, change the casing to Title Case without any of delimiter. * If there are multiple words with no delimiter, change the casing to lower case and add an underscore character as a delimiter. * In case of only one word (or one character): change the casing to Title Case if the word starts with lower case; change the casing to lower case if the word starts with the upper case. Allowed characters: * A to Z * a to z * underscore (`_`). Input with mixed cased words are disallowed. Examples of disallowed cases: * `Coding_Convention_Conversion` * `a_BC` # Example Cases ``` Input | Expected Output =========================================================== CodingConventionConversion | coding_convention_conversion coding_convention_conversion | CodingConventionConversion abc | Abc Abc | abc ABC | a_b_c a_b_c | ABC a | A A | a ``` # Rules * It is allowed to use `ToUpper`, `ToLower` and `ToTitleCase` functions. * Using regular expressions is allowed. * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest code in bytes wins! [Answer] # Jolf, 35 bytes *Saves 1 byte thanks to @Cยทยฅรจโ€ฆยฅยทยฅรจย ร„ O'Bย ร„โ€ฆโ„ขยทยฅรกโ€ฆยฅ*. This is encoded in ISO 8859-7. ``` ? hI'_ล’รบGI'_dpyH0pxRGIL0"(?=[A-Z])'_ ``` Woohoo my first Jolf program! ## Explanation ``` // I = input ? hI'_ // If input contains _ GI'_ // Split on _ ล’รบ d // Loop, then join pyH0 // Make the first character uppercase // ELSE... RGIL0"(?=[A-Z]) // Split *after* all uppercase chars '_ // join with _ px //Make lowercase ``` [Try it online](http://conorobrien-foxx.github.io/Jolf/#code=PyBoSSdfEM6cR0knX2RweUgwcHhSR0lMMCIoPz1bQS1aXSknXw) [Answer] # [Retina](https://github.com/mbuettner/retina), 37 Thanks to @ MartinBโˆšยบttner for saving 4 bytes! ``` ^|[A-Z] _$0 T`Ll`lL`_. ^_|_(?=[A-Z]) ``` (Note the trailing newline.) [Try it online.](http://retina.tryitonline.net/#code=bWBefFtBLVpdCl8kMApUYExsYGxMYF8uCm1gXl98Xyg_PVtBLVpdKQo&input=Q29kaW5nQ29udmVudGlvbkNvbnZlcnNpb24KY29kaW5nX2NvbnZlbnRpb25fY29udmVyc2lvbgphYmMKQWJjCkFCQwphX2JfYwphCkE) Note this includes extra `m`` to configure a couple of lines to treat each input line separately so all testcases may be run in one go. This is not a requirement of the question, so these are not counted in the score. * Lines 1 and 2 insert `_` either at the beginning of input or before uppercase letters. All words are now `_`-separated, regardless of case. * Line 3 swaps case of the first letter in each word. * Lines 4 and 5 remove `_` either at the start of input, or when followed by an uppercase letter. [Answer] # GNU Sed, 46 Thanks to @TobySpeight for saving 2 bytes! Score includes +1 for `-E` (or `-r`) option to `sed`. ``` s/(^|_)([a-z])/\u\2/g t s/[A-Z]/_\l&/g s/^_// ``` [Try it online.](https://ideone.com/MqSbzl) Fairly straightforward sed: * Line 1 substitutes beginning of line or `_`, followed by a lowercase letter with the upper case of that letter. The `g` flag to `s` performs this substitution for each instance found * `t` jumps to the `:` unnamed label if there were any matches for the above substitution. This label is implicitly at the end. * Otherwise all uppercase letters are substituted with `_` the lower case of that letter * This leaves a leading `_` before the first letter. `s/^_//` removes that. [Answer] # Pyth, 25 bytes ~~29 33 35 40~~ *Saved 2 bytes thanks to @Dennis* *Saved 4 bytes thanks to @FryAmTheEggman* ``` ?rIz0smrd4cz\_tsXzrG1*\_G ``` [Try it online](http://pyth.herokuapp.com/?code=%3FrIz0smrd4cz%5C_tsXzrG1%2a%5C_G&input=CodingConventionConversion&test_suite=1&test_suite_input=CodingConventionConversion%0Acoding_convention_conversion%0Aabc%0Aa_b_c%0AABC&debug=0) [Answer] # JavaScript (ES6), 87 bytes ``` s=>s.replace(/[A-Z]|(^|_)(.)/g,(c,_,l,i)=>l?l.toUpperCase():(i?"_":"")+c.toLowerCase()) ``` ## Explanation Depending on which part of the regex matched, it replaces the match with the opposite case. ``` s.replace( /[A-Z]|(^|_)(.)/g, (c,_,l,i)=> l? (i?"_":"")+c.toLowerCase() :l.toUpperCase() ) ``` ## Test ``` var solution = s=>s.replace(/[A-Z]|(^|_)(.)/g,(c,_,l,i)=>l?l.toUpperCase():(i?"_":"")+c.toLowerCase()) ``` ``` <input type="text" id="input" value="coding_convention_conversion" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # PHP 160 bytes not the shortest but for completeness here my solution in PHP, $s holds the string to convert: ``` trim(preg_replace_callback('/((^[a-z]|_[a-z])|([A-Z]))/',function($m){return empty($m[2])?'_'.strtolower($m[3]):strtoupper(str_replace('_','',$m[2]));},$s),'_') ``` [Answer] # Ruby, ~~101~~ ~~87~~ 75 bytes ``` ->s{s.gsub(/^.|[A-Z]/,'_\0').gsub(/_./,&:swapcase).gsub(/_(?=[A-Z])|^_/,'')} ``` Unfortunately, this does exactly the same thing as the Retina solution, as that method ended up being shorter than anything else I came up with. [Answer] # Python 3, 130 bytes Quick and dirty attempt using regex to split at the caps. Pretty brute force: if anyone can come up with a different approach I'm sure this can be beaten. ``` import re lambda s:('_'.join(re.findall('[A-Z][a-z]*',s)).lower(),''.join([a[0].upper()+a[1:]for a in s.split('_')]))[s.islower()] ``` [Answer] # ๏ฃฟรนรฎยบ๏ฃฟรนรฏรค๏ฃฟรนรฏร‘๏ฃฟรนรฏรถ๏ฃฟรนรฏรผ 3, 15 chars / 32 bytes (noncompetitive) ``` โ€šรผร†โ€”ยฎยซยฑโˆšร˜โ€šรผร˜โ€šรขโ€ โˆšร˜?โ€šร–โ€ :โ€”ยฎยปรฉโ€”ยฎโˆ†รฉโˆšร˜ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=CodingConventionConversion&code=%E2%9F%AE%D1%A8%C7%B1%C3%AF%E2%9F%AF%E2%89%A0%C3%AF%3F%E2%85%A0%3A%D1%A8%C8%8E%D1%A8%C6%8E%C3%AF)` v3 was released after this challenge, with a bunch of bugfixes and library updates. # Explanation This is just a mashup of builtins. ``` โ€šรผร†โ€”ยฎยซยฑโˆšร˜โ€šรผร˜โ€šรขโ€ โˆšร˜?โ€šร–โ€ :โ€”ยฎยปรฉโ€”ยฎโˆ†รฉโˆšร˜ // implicit: โˆšร˜=input โ€šรผร†โ€”ยฎยซยฑโˆšร˜โ€šรผร˜โ€šรขโ€ โˆšร˜? // check if โˆšร˜ is NOT in snake_case โ€šร–โ€  // if so, then convert to snake_case :โ€”ยฎยปรฉโ€”ยฎโˆ†รฉโˆšร˜ // otherwise, convert to camelCase and make the first letter UPPERCASE ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` eโ€šร‡ยจโˆšรฒAยทโˆรคkโ‰ˆรญljโ€šร„รน_$ย รฃโ€šร…รฆ_ yโ‰ˆรญtยทโˆโ‰คโˆ†โ‰ค}ยทโˆซโˆ? ``` [Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMcH@7oyj46KSfrUcPceJVT3Y8a98UrVB6dVPJwx6Zjm2of7tph/9/6UcMcBV07BaAS68PtXIfbgToj//9Xcs5PycxLd87PK0vNK8nMzwOzioqBLCUdpWSwZHwyXBbChEnnJeamAik/EAUA "Jelly โ€šร„รฌ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 86 bytes ``` lambda s,u='_':''.join([u[i>u:]+i.lower()for i in(s<u)*s]or[u]+s.title().split(u))[1:] ``` [Try it online!](https://tio.run/##hc1NCsIwEAXgfU4x0MUkKgVxV1TQHqOWktZWR2pS8qN4@hojuKvNJg/m473h5a5abcZudxp7ea/PEuzK77DCDDG9aVK88AXtfVYuKe31szVcdNoAQTjZrRcLW2pT@HJpU0eub7lI7dCT416IYp2V40fboIEzzPWZ1CXX6tEqR1rFZGxIuAKABJoIquYnvjEShv@uoSCB6X6Gsm7iyMRL4FA3DA9zSkZ1zGdUVVfBxW9ahs1jHtS/rqjC4pyRTGQwGFKOd9wKMb4B "Python 3 โ€šร„รฌ Try It Online") Also [works in Python 2](https://tio.run/##hc1NCsIwEAXgfU4x0MUkKgVdFhW0x6ilpLXVkZqU/CievsYI7mqzyYP5eG94uatWm7HbncZe3uuzBLvyO6wwQ0xvmhQvfEF7n5VLSnv9bA0XnTZAEE5268XCltoUvlza1JHrWy5SO/TkuBeiWGfl@NE2aOAMc30mdcm1erTKkVYxGRsSrgAggSaCqvmJb4yE4b9rKEhgup@hrJs4MvESONQNw8OcklEd8xlV1VVw8ZuWYfOYB/WvK6qwOGckExkMhpTjHbdCjG8). Making use of the convenient fact that the ascii value for `_` (95) is right in between those of the uppercase (65-90) and lowercase (97-122) letters, which allows for easy string comparisons. [Answer] # [Perl 6](http://perl6.org), ~~ยฌโ€ 73ยฌโ€ 72ยฌโ€ 71ยฌโ€ ~~ยฌโ€ 68 bytes ``` {.comb(/<:Lu><:Ll>*|<:Ll>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x?/<:Lu>/)} # 73 {.comb(/<:Lu><:Ll>*|<:L>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x?/<:Lu>/)} # 72 {/<:Lu>/??S:g/(^)?(<:Lu>)/{$0||'_'}$1.lc()/!!S:g/[^|_](<:Ll>)/$0.tc()/} # 71 {.comb(/<:Lu><:Ll>*|<:L>+/).map({/<:Lu>/??.lc!!.tc}).join('_'x!/_/)} # 68 ``` ### Usage: ``` # give it a lexical name my &code = {...} for <CodingConventionConversion coding_convention_conversion abc Abc ABC a_b_c a A> { say .&code } ``` ``` coding_convention_conversion CodingConventionConversion Abc abc a_b_c ABC A a ``` ### Explanation: ``` { .comb( / <:Lu><:Ll>* | <:L>+ / ) # grab the "words" only .map({ /<:Lu>/ # if the word has uppercase ?? .lc # lowercase the whole word !! .tc # otherwise titlecase the word }) .join( # join the words '_' # with '_' x # repeated !/_/ # zero times if it had a _, otherwise once ) } ``` You may be wondering why I used the Unicode properties (`<:Lu>`, `<:Ll>`) instead of just a character class. In [Perl 6](http://perl6.org) they are no longer spelled `[a-z]` they are spelled `<[a..z]>` which is 1.6 times as big. The brackets `[ยฌโ€ โ€šร„ยถยฌโ€ ]` are used for non-capturing grouping instead which was spelled as `(?:ยฌโ€ โ€šร„ยถยฌโ€ )` in Perlยฌโ€ 5. [Answer] # Japt, 40 bytes ``` UfV="%A" ?UrV@'_s!Y +Xv} :Ur"^.|_."_sJ u ``` [Test it online!](http://ethproductions.github.io/japt?v=master&code=VWZWPSIlQSIgP1VyVkAnX3MhWSArWHZ9IDpVciJeLnxfLiJfc0ogdQ==&input=ImFfYl9jIg==) # How it works ``` // Implicit: U = input string UfV="%A" // Set variable V to the string "\\A", and get all matches in U. ? // If the list is not null: UrV@ } // Replace each match X and its index Y with this function: '_s!Y +Xv // Return "_".slice(!Y) (1 for Y=0, 0 for anything else) + X.toLowerCase(). : // Otherwise: Ur"^.|_." // Replace the char at the beginning and each char following an underscore with: _sJ u // The last char of the match (the letter) .toUpperCase(). ``` [Answer] # Perl 5, 42 bytes 40 bytes plus 2 for `-p` (thanks, [dev-null](/u/48657)) ``` s/[A-Z]/_\l$&/g||s/(^|_)(.)/\u$2/g;s/_// ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 129 bytes ``` : f bounds dup c@ 32 xor emit 1+ ?do i c@ '_ < if ." _"i c@ 32 + emit then i c@ '_ > if i 1- c@ '_ = 32 * i c@ + emit then loop ; ``` [Try it online!](https://tio.run/##jc5NDoIwEAXgvad4YWMiwUTcGFH84SANlIJNtNPQavT0SAsaN6LddKb9Mm8qauwpqit3te0aFQq6qtKgvGrwPZYx7tRAXKTFIsSuJEj3PmXYQFaYB2CBHGTYO3sS6q1SpyQW0dBvHZz135/@TKSRdBtoxC7bPrTwS8QrRMgLA6NzLoxLRJQi6FblDZKJCZBRKVWdkboJZSUpXzWmqzoL7Qj3hPG36csBeZIX3PEvx5PDH@SY/SI5K9j3OT0ZmfEKGiftEw "Forth (gforth) โ€šร„รฌ Try It Online") ### Code Explanation ``` : f \ start a new word definition bounds \ convert string address and length to beginning and ending address dup c@ \ get the first character 32 xor emit \ convert to the opposite case and output 1+ \ add 1 to beginning of string (skip starting char) ?do \ begin counted loop over string character addresses i c@ '_ < \ check if char is uppercase if \ if it is: ." _" \ output underscore i c@ \ get current char 32 + emit \ convert to lowercase and output then \ end if block i c@ '_ > \ check if lowercase (not '_') if \ if it is: i 1- c@ \ get the previous character '_ = 32 * \ if it's an underscore, multiply by 32 (true = -1 in forth) i c@ + \ add result to current char (make uppercase if previous was '_') emit \ output resulting char then \ end if block loop \ end loop ; \ end word definition ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 37 bytes ``` '_Na?UC@_.@>_Ma^'_(LC_MRXU.XL.'+a)J'_ ``` [Try it online!](https://tio.run/##K8gs@P9fPd4v0T7U2SFez8Eu3jcxTj1ew8c53jcoIlQvwkdPXTtR00s9/v///875KZl56c75eWWpeSWZ@XlgVlExkAUA "Pip โ€šร„รฌ Try It Online") Lot of underscores in this one. [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 43 bytes ``` {("_"/(&x<_x)__x;,/`c$t-32*~<'t:"_"\x)x~_x} ``` [Try it online!](https://tio.run/##PYnRCoJAEEX/ZYjaLUWwN9cX298IJl1TRJgFW2Ig8te3UbGXw7n3jCn1FGNXfBQgZOrIJbJGZJNkD3cI6TU/z@UpFFLvrHlG/saLCqaTT4H17UC99fR@Uhg8rTa9xMCAWyO6f910z3XjhNXGm10ebFBWAvWCCrSOPw "K (ngn/k) โ€šร„รฌ Try It Online") * `x~_x` check if the input `x` is all lowercase * `(...;...)` index into this two-item list depending on that value (i.e., return the first item in the list if `x` contains an uppercase letter, and the second item if it does not) * When `x` contains an uppercase letter: + `(&x<_x)` identify indices of uppercase letters + `(...)__x` split the lowercased input on those indices + `"_"/` join the resulting chunks with underscores * When `x` is all lowercase: + `t:"_"\x` split input on underscores, storing in variable `t` + `t-32*~<'t` capitalize the first letter in each chunk (this converts to integers) + `,/`c$` convert back to characters, flattening the list [Answer] # Japt, 37 bytes ``` a'_ โˆšร‘?Uq'_ ยฌร†hZu g} q:Uโˆšโ‰ค@Yc <#a} q'_ v ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=YSdfIMQ/VXEnXyCuaFp1IGd9IHE6VfJAWWMgPCNhfSBxJ18gdg==&input=WyJIZWxsb1RoZXJlIiwKImhlbGxvX3RoZXJlIl0KLW0=) Explanation: ``` There are some unicode chars that a shortcuts for common groups of chars, like โˆšร‘ is +1. This is the expanded version. // U = input string a'_ // get index of "_" in string, -1 if not found +1 // add 1 to make -1 falsy ? // if truthy, ie. if there is an underscore in the input text Uq'_ // split on underscores m_ // map h // replace character (first char by default) Zu g // the first letter of the string converted to uppercase (Zug) } q // close function and join : // else, ie. the string doesn't have any underscores Uโˆšโ‰ค // runs func on every pair of chars, splits them if it returns true @Yc <#a } // returns true if the second char code is less than "a", ie. uppercase q'_ // join with underscores v // make lowercase implicit print ``` First Japt program, I beat the creator, and Zu g! [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~27~~ 26 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I fear I may have gone in the wrong direction with this; stuck on 27 and can't seem to do any better. ``` r"^.|_.|%A"โˆšร โˆšรฅc^H i'_pYยฌยฉXโˆšรคu ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciJeLnxfLnwlQSLIzGNeSCBpJ19wWalYynU&input=WwoiQ29kaW5nQ29udmVudGlvbkNvbnZlcnNpb24iCiJjb2RpbmdfY29udmVudGlvbl9jb252ZXJzaW9uIgoiIgoiYWJjIgoiQWJjIgoiIgoiQUJDIgoiYV9iX2MiCiIiCiJhIgoiQSIKXQotbVI) ``` r"^.|_.|%A"โˆšร โˆšรฅc^H i'_pYยฌยฉXโˆšรคu :Implicit input of string r :Replace "^.|_.|%A" :RegEx /^.|_.|[A-Z]/g โˆšร  :Pass each match X at 0-based index Y through the following function โˆšรฅ : Last character of X c : Charcode ^H : Bitwise XOR with 32 i : Prepend '_p : "_" repeated Yยฌยฉ : Logical AND of Y and Xโˆšรค : Length of X u : Mod 2 ``` ]
[Question] [ This is the second in a series, the third is [Two roads diverged in a yellow wood (part 3)](https://codegolf.stackexchange.com/questions/114420/two-roads-diverged-in-a-yellow-wood-part-3) This is based on [Two roads diverged in a yellow wood (part 1)](https://codegolf.stackexchange.com/questions/114253/two-roads-diverged-in-a-yellow-wood), a previous challenge of mine. It was fairly well received, but it was also fairly trivial (a Java answer in 52 bytes!) So I made something more complex... ## The inspiration This challenge is inspired by Robert Frost's famous poem, "The Road Not Taken": > > Two roads diverged in a yellow wood, > > And sorry I could not travel both > > And be one traveler, long I stood > > And looked down one as far as I could > > To where it bent in the undergrowth; > > > ...2 paragraphs trimmed... > > > I shall be telling this with a sigh > > Somewhere ages and ages hence: > > Two roads diverged in a wood, and I โ€” > > I took the one less traveled by, > > And that has made all the difference. > > > Notice the second to last line, `I took the one less traveled by,`. Your goal is to find the road least travelled by in your string input. You must output one of 2 values that are distinct from each other that signal which way you should turn to take the road less traveled by. Once the road forks (the trail of hexagons changes to numbers) you are at the intersection. From there, there will be 2 paths made up of digits. The path whose digits has the lowest sum will be the road not taken. Note that the road not taken may have a larger path but a lower path sum. Here are some examples / test cases from a program that prints "left" or "right" for the path not taken: ``` 1 2 1 2 1 2 # # # left (3 < 6) 1 2 2 2 1 1 # # # left (4 < 5) 12 2 11 2 1 1 # # # right (6 > 5) 99 989 99 89 99 99 99 99 # # # # left (72 < 79) 1111 1110 001 111 11 11 11 11 # ## ## ## left (9 < 10) (Note: 1111 is interpreted as 1+1+1+1=4, not 1111=1111) 1 1 0 1 1 1 1 1 1 1 1 1 1 1 # # # # # left (6 < 7) 1 1 0 1 1 1 1 1 1 1 1 1 1 1 # # # # # left (6 < 7) ``` ## Things to assume & remember * There will always be 2 paths. No more, no less. * You can take input from STDIN one line at a time, a string containing LF characters, or a string containing a literal backslash and a n. If you need input in any other way, ask for approval in the comments. * You don't have to worry about invalid input or tied paths. Those will never be inputted to your program / function. * The input can be of any length in width or height, less than the string limit of your language. * There will never be a `#` and a number in the same line. * All digits in the path are positive integers 0 to 9. * Input or output with a trailing newline is allowed. * See [my JS ES6 answer](https://codegolf.stackexchange.com/a/114380/58826) below for an example. * There will always be at least 1 space between the 2 paths. * The 2 paths will always have the same height for each map, but may be different on other maps. * If you are confused about a specific test case, please tell me. * **1111 is interpreted as 1+1+1+1=4, not 1111=1111. The map is a series of one-digit numbers, not numbers of arbitrary length.** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! * [Standard loopholes forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) **If you have any questions about this challenge, ask me in the comments, and good luck!** [Answer] ## [Retina](https://github.com/m-ender/retina), 28 bytes ``` \d $* %r`1\G - Os`. +`-1 1+ ``` [Try it online!](https://tio.run/nexus/retina#rY@xDsIwDET3@wpLpRKiKoozEeUDGDuwZsjAzAD/r2AnTUlRgQUPvqfkfJbDDR6X6D36vUgKV@wO6O@Rwxkjpkc8YogjAzykRExaFpRJVSALdauOxmpfVt622iWVf1idE3AnJw@KFVyr71NllKUknw3ImExl30qrXbu2TgeplPybCvm6b/rhAGqE5uw592@pTw "Retina โ€“ TIO Nexus") Prints `0` for left and `1` for right. Assumes that there are not trailing spaces on any lines. ### Explanation ``` \d $* ``` Convert each digit `N` to a run of `N` ones. ``` %r`1\G - ``` One each line (`%`), match consecutive (`\G`) ones from the end (`r`) and replace each of them with `-` (i.e. turn the right branch into `-`s). ``` Os`. ``` Sort all characters, so that all `-`s are directly in front of all `1`s. ``` +`-1 ``` Repeatedly cancel a pair of `-` and `1`. ``` 1+ ``` Try to match at least one `1` (if so, there were more weights in the left path). [Answer] # [Chip](https://github.com/Phlarx/chip), 216 bytes ``` EZ,Z~. E~]x-.| F].>vm' Ax]}#----------------. Bx]}#---------------.|z. Cx]}#------------.,Z|##' E Dx]}#---------.,Z|`@@('A~^~t E.>#------.,Z|`@@-(' A~S`#v--.,Z|`@@-(' *f,--<,Z|`@@-(' e |,Z|`@@-(' ,Z|`@@-(' >@@-(' a ``` [Try it online!](https://tio.run/nexus/chip#@6/gGqUTVafH5VoXW6GrV8PlFqtnV5arzuVYEVurrIsG9LicsAjr1VTpcTmjS@jpRNUoK6sruHK5oEiBxBMcHDTUHevi6kq4FFz17JRRZHQ1gLbXBScol6EIaaXp6OraIPipCjUIDoJlB6ES//9XMFQAASMuIIbSQCFDEKWgjEwCAA "Chip โ€“ TIO Nexus") A little bigger than the answer for [part 1](https://codegolf.stackexchange.com/a/114296/56819)... ### Overview Chip is a 2D language inspired by actual circuitry, and it deals with the component bits of each byte in a byte stream. This solution keeps a running sum of the digits it sees, flipping the sign of the input each time it encounters a stretch of whitespace, then terminating upon the first `#`. So, for input ``` 11 12 2 2 1 1 # # # ``` We get `1 + 1 - 1 - 2 + 2 - 2 + 1 - 1 = -1`. The sign of the result is given as the output, a negative number produces the result `1`, and positive is `0`. Therefore, output of `1` means that the left path is less taken, and `0` means right. ### Explanation At a high level, this is how it works: The main diagonal with the `@` elements is the accumulator, output is decided by the `a` at the bottom. (Eight pairs of `@` means eight bits, but the highest bit is the sign, so this solution can handle a maximum difference of +127 or -128. Overflowing partway through is okay, as long as we come back before terminating.) The four lines that start like `Ax]}#--`... are reading the input, and in the case of a digit, negating it (if necessary) and passing the value into the adders. The first three lines decide if we are looking at a digit, or a sequence of whitespace, and keep track of whether the digits need to be negated. The remaining elements wedged in under the inputs and the elements at far right handle the termination condition, and map the output to ASCII (so that we get characters `'0'` or `'1'` instead of values `0x0` or `0x1`. This ASCII mapping required no extra bytes, otherwise I wouldn't have included it.) [Answer] # [Python 2](https://docs.python.org/2/), ~~95~~ ~~89~~ ~~88~~ 87 bytes Here is my first go at this in python. Definitely not optimal but a decent start. ``` f=lambda x,i:sum(sum(map(int,y))for y in x.split()[i::2]if"#"<y) lambda x:f(x,1)>f(x,0) ``` [Try it online!](https://tio.run/nexus/python2#hYxBCsMgFET3OcWgGz9IiV1K24uULizF8CGmkqSgpzdKSDdddGDmzeoVfx1deL4ckma7fIJqDS4qnladifx7RgZPSKcljrwqurO15wd7IcUlUzd8BdarpA3dGnoqca4KDEoIYbDHdOiPA/OH9Rg0Qv7sAchqp7IB "Python 2 โ€“ TIO Nexus") [Answer] # JavaScript (ES6), 55 bytes ``` x=>x.replace(/\d(?=.*( )|)/g,(d,s)=>t-=s?d:-d,t=0)&&t<0 ``` Assumes there are no trailing spaces on each line, and outputs `true` for `right`, `false` for `left`. The trick is to match each digit in the input, and if there is a space after it on the same line, subtract it from the total; otherwise, add it to the total. If the final total is less than 0, the right road is the one less traveled by, and vice versa. Try it out: ``` f=x=>x.replace(/\d(?=.*( )|)/g,(d,s)=>t-=s?d:-d,t=0)&&t<0 ``` ``` <textarea placeholder = "paste in a map here..." oninput = "document.querySelector('div').innerText = f(this.value)"></textarea> <div></div> ``` [Answer] # [Python 3](https://docs.python.org/3/), 85 94 bytes ``` import re g=lambda s,i:sum(map(int,''.join(re.findall('\d+',s)[i::2]))) lambda s:g(s,0)>g(s,1) ``` [Try it online!](https://tio.run/nexus/python3#jY3BCsIwDIbve4qCh6ZYhu3JFuaLqIfK1lFpt9LO55/p0A1BxED@LwS@ZHYhjmkiqav6xptwaw3J3On8CBBMBDdMnNL6ProBUldbN7TGe6CXdk95Zmentbwyxiq72rqHzA/sVCDYHBPeAAuUCFJKkmVAIEuS3RYUL30R5CqI34J8fxD/CUrhTh0xy/Si2vChLo3@/AQ "Python 3 โ€“ TIO Nexus") Curses! Didn't read the problem close enough. Added a the fix (`''.join()`), but at the cost of 9 bytes. [Answer] ## Python 2, 78 bytes -1 byte thanks to @math\_junkie [Try it online](https://tio.run/nexus/python2#ZY0xDsIwFENncgorGZqIgtKBDIUw9gI9AQpEikTb6LecP3wKLODBz/bicr1FdLqvyVvTCsSJEJBG9Ps539OiedykWKnqFFra@vkx6OGSdRqXOhhzJL8jgUzcQWdbOi2ldM7hLecE7JoOAmuyzObD385Dgxeh/vwLKD4w5Qk) ``` def F(S,r=0): for c in S.split(): if'#'<c:r+=sum(map(int,c));r=-r print r>0 ``` Prints `False` for left path and `True` for right [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 15 bytes Outputs **0** for left and **1** for right. ``` |vy#รตKโ‚ฌSO})รธO`โ€บ ``` [Try it online!](https://tio.run/nexus/05ab1e#@19TVql8eKv3o6Y1wf61mod3@Cc8atj1/78hECgAsQGXgoEBmMWloAAWQqIVFJRBpDKIBBHKygoA "05AB1E โ€“ TIO Nexus") **Explanation** ``` |v # for each line in input y# # split on spaces รตK # remove empty strings โ‚ฌS # split each string into a list of chars O # sum each sublist } # end loop )รธ # wrap stack in a list and zip O # sum each sublist (side of the tree) `โ€บ # compare left to right ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 180 bytes Byte count assumes ISO 8859-1 encoding. ``` ^(?=( *(0|(1|(?<3>2|(?<3>3|(?<3>4|(?<3>5|(?<3>6|(?<3>7|(?<3>8|(?<3>9))))))))))+.+ยถ)+)(.+ (0|(?<-3>1|(?<-3>2|(?<-3>3|(?<-3>4|(?<-3>5|(?<-3>6|(?<-3>7|(?<-3>8|(?<-3>9))))))))))+ยถ)+ *# ``` [Try it online!](https://tio.run/nexus/retina#rc9LDoIwEAbgfU8xCTEpNJK2PBsQDuHWGE/gCTiXB/Bi2OkMWIyPjbPo9wemP@F0FZ04XrpO7KRnPsvxICGTepJmkmNfDJYoiJKoiJpoiJZw6ToqV/dbqlKZK8DKsd8Xg2EtW7AlW7E127AtG/djO2TJPIMBHCsgJNSHACSbU0Sr9rlq3q/atdX8WHXOB9c6/wDjElzs6y26avz4fqMFaB0SfW/jso4nHgleBBr/Xi8h/N03P/wARAB3c@/fWh8 "Retina โ€“ TIO Nexus") I thought I'd also try a regex-only solution (the above is a plain .NET regex which matches only inputs where the right path should be taken, except for using `ยถ` as a shorthand for `\n`). It's annoyingly repetitive, but that's what happens when you have to treat each possible digit individually. The solution is a fairly straight-forward application of [balancing groups](https://stackoverflow.com/a/17004406/1633117): first we sum the digits in the left branch by pushing `N` captures onto stack `3` for each digit `N`. Then we try to reach the `#`, while popping from stack `3` `N` times for each digit `N` in the right branch. This is only possible if the sum of digits in the left branch is greater than that in the right branch (since you can't pop from an empty stack). [Answer] ## JavaScript (ES6), 106 104 bytes ``` s=b=>(b=b.split`\n`,c=0,d=0,b.forEach(a=>{a=a.match(/\d+/g)||[],c+=+(a[0]?a[0]:0),d+=+(a[1]?a[1]:0)}),c<d) ``` ``` s=b=>(b=b.split("\n"),c=0,d=0,b.forEach(a=>{a=a.match(/\d+/g)||[],c+=+(a[0]?a[0]:0),d+=+(a[1]?a[1]:0)}),c<d) ``` `s` is a function that returns `true` if the road not taken is on the left. Ungolfed: ``` var proc = function(str){ str = str.split("\n"); var left = 0; var right = 0; str.forEach(item=>{ var match = item.match(/\d+/g) || []; console.log(match); left += +(match[0] ? match[0] : 0); right += +(match[1] ? match[1] : 0); }); return left < right; }; ``` ``` s=b=>(b=b.split`\n`,c=0,d=0,b.forEach(a=>{a=a.match(/\d+/g)||[],c+=+(a[0]?a[0]:0),d+=+(a[1]?a[1]:0)}),c<d) ``` ``` <textarea placeholder = "paste in a map here..." oninput = "document.querySelector('div').innerText = s(this.value)"></textarea> <div></div> ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), ~~19~~ 18 bytes ``` qN/Sf%z{'1*:~:+}/> ``` [Try it online!](https://tio.run/nexus/cjam#@1/opx@cplpVrW6oZVVnpV2rb/f/v4KhkQIQGHEpKBgaQmgFQwVDEKWgjEwCAA "CJam โ€“ TIO Nexus") Prints `0` for left and `1` for right. ### Explanation ``` q e# Read all input. N/ e# Split into lines. Sf% e# Split each line around runs of spaces. z e# Transpose to group each branch. e# Note that each branch will have the same number of digit segments e# now but the first branch will also have all the #s at the end in e# separate segments. { e# For each branch... '1* e# Join the segments into a single string with 1s as separators. e# This will add the same number of 1s between digit segments in e# both branches (which won't affect their relative sum) and it e# will also insert a 1 before each # in the first branch. :~ e# Evaluate each character. The digit characters are simply turned e# into their values, but # is the exponentiation operator in CJam. e# This is why we inserted those additional 1s, because 1# is a no-op. :+ e# Sum the digits in the branch. }/ > e# Check whether the left branch's sum is greater than the right one's. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 80 bytes ``` $args-split'\s|#'-ne''|%{$a+=(($i=[char[]]$_-join'+'|iex),-$i)[($x=!$x)]};$a-gt0 ``` [Try it online!](https://tio.run/nexus/powershell#TcXBCsIwDADQX4lbJC0zYHaVfkktWmTMiFRZdyhYv70iXry81zAuc@b8vOtKx1x74jQR1e0L4@CMQXX@co2LDwFPfHtoooGqTsXuGNV6g8VtsNjwPmDked231joZAWA8JxD5DQLyDfp/uw8 "PowerShell โ€“ TIO Nexus") *(Just squeaking under the Python answers. :D)* Outputs `True` for the left path and `False` for the right path. Takes input as a string delineated with ``n`, which is the PowerShell equivalent of *"a string containing a literal backslash and a n"*, or as a literal multiline string. We then `-split` that input on `\s` (whitespace including newlines) or `#` and filter out all the empty results `-ne''`, so we're left with just an array of the digits. Those are fed into a loop `|%{...}`. Each iteration, we first take the current element `$_`, cast it as a `char` array, `-join` it together with a plus sign `+`, and pipe it to `iex` (short for `Invoke-Expression` and similar to `eval`). That's stored into `$i` so we properly sum up the digits on this particular chunk of the path. We then use that and its negative as the two elements of an array `($i, -$i)`, indexed into by flipping a Boolean value back and forth. Meaning, the first iteration through this loop, the first left path chunk, we'll index into `-$i`; the next time, we'll take `$i`; and so on. Those are accumulated into `$a` with `+=`. Finally, we evaluate whether `$a` is `-g`reater`t`han `0`. If it is, then the right path had a larger sum, otherwise the left path had a larger sum. That Boolean result is left on the pipeline, and output is implicit. [Answer] # [Python 3](https://docs.python.org/3/), 84 bytes Since all the current Python submissions are functions, I thought I'd contribute a full program. ``` x=0 try: while 1: for n in input().split():x=-x+sum(map(int,n)) except:print(x>0) ``` Prints `True` if the left path is less traveled, `False` otherwise. [Try it online!](https://tio.run/nexus/python3#@19ha8BVUlRpxaVQnpGZk6pgCGQppOUXKeQpZIJQQWmJhqZecUFOJpC2qrDVrdAuLs3VyE0s0MjMK9HJ09TkSq1ITi0osSooAgpoVNgZaP7/r2BpqaCgYGlhCTQMxIQxLJFpBQVldFJZAQA "Python 3 โ€“ TIO Nexus") For each line of input, this splits on whitespace, sums the digits of each resulting element, and adds it to a tally while flipping the sign of the tally at each step. It continues reading lines of input until it hits one with a `#`, at which point `map(int,n)` raises an exception and we exit the loop, printing `True` if the tally is positive and `False` otherwise. [Answer] # Mathematica, ~~80~~ 77 bytes *Thanks to Martin Ender for saving 3 bytes!* ``` #<#2&@@Total@Partition[Tr/@ToExpression[Characters@StringSplit@#/."#"->0],2]& ``` Pure function taking a newline-delimited string as input, and returning `True` to take the left path, `False` to take the right path. Damn those long Mathematica command names; this is like 10 tokens. [Answer] # Java 10, ~~219~~ ~~216~~ ~~208~~ ~~162~~ 146 bytes ``` s->{int l=0,i;for(var x:s.split("\n"))for(i=2;!x.contains("#")&i-->0;)for(int c:x.trim().split("\\s+")[i].getBytes())l+=i>0?48-c:c-48;return l>0;} ``` Bit longer than [~~52~~ 21 bytes](https://codegolf.stackexchange.com/a/114368/52210) this time. ;) Returns `false` for right and `true` for left. -24 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##tVBBbsIwELzzim0iVbZorARxIEShUu/lwhE4GBOQqeOg2FAQyttT20GhtKpKq9YHz9irnZ3ZDd3TYLN8qZmgSsEz5fLUAeBSZ@WKsgzG9gmwKAqRUQkMTXTJ5RoUTkyh6phrDBLSWgWjk2kDkYYPPFkVJdrTEg5DRdRWcI28mfQwtv887SV3B8IKqc04hTzfw/c8CEZh0tSNChseiBmUI9y2z1TXw1M@J@tMPx11phDGopvyUfjYHwRsyIL@ICkzvSslCKNV1Yl1t90tBGegNNUG9gVfQm7GnnNM50BxE9FmhxxSkNmreyAXEWByVDrLSbHTZGt6tJAoJ5Iw5EFk69CbSXDUEcMaBP8aTPyfCPbeCUa/F@xdHEZ/IRjHph4PYttiecvia/JJ3IEPN8yIzDFuo9C0hKGjZ/8fSKvqwN2@DzeNgOZYmbBlbv3fEbs9@DrhBW/ap5OFs4tG939MVJ2qfgM) **Explanation:** ``` s->{ // Method with String parameter & boolean return-type int l=0, // Counter, starting at 0 i; // Temp integer `i` for(var x:s.split("\n")) // Loop over the lines: for(i=2;!x.contains("#")& // Skip lines that doesn't contain "#": i-->0;) // Inner loop `i` in the range (2,0]: for(int c:x.trim() // Remove the leading/trailing whitespaces from // the current line .split("\\s+") // Then split it on whitespaces [i] // Get the `i`'th part .getBytes()) // And inner loop over the bytes of this part: l+=i>0? // If `i` is 1: 48-c // Decrease the counter by this digit : // Else (`i` is 0): c-48; // Increase the counter by this digit return l>0;} // Return whether the counter is positive ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~19~~ 18 bytes ``` LR+XDax:-x+$+$0SGx ``` Takes input as a single string on the command line (which will need quoting and escaping of newlines if run on an actual command line). Outputs `-1` for left, `1` for right. [Try it online!](https://tio.run/nexus/pip#@@8TpB3hklhhpVuhraKtYhDsXvH//39DIFAAYgMuBWMDAzBTQYFLQQEsikQrKCiDSGUQCSKUlRUUAA "Pip โ€“ TIO Nexus") ### Explanation Loops over runs of digits, adding the digit sums to a tally. The sign of the tally is swapped each time, with the end result that the left-hand values are negative and the right-hand values are positive. Then we print the sign of the final tally (`-1` or `1`). ``` a is 1st cmdline arg; XD is regex `\d`; x is "" (implicit) Note that "" in a math context is treated as 0 +XD Apply regex + to XD (resulting in `\d+`) LR a Loop over matches of that regex in a: $0 Regex match variable containing the full match $+ Sum digits by folding on + x:-x+ Swap the sign of the tally and add this sum SGx After the loop, print the sign of the tally ``` [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` g=sum.map fromEnum f(a:b:r)|a>"#"=g a-g b+f r|1<3=0 (>0).f.words ``` [Try it online!](https://tio.run/nexus/haskell#XcaxCoMwFEbhPU/xYzooxWDp0kjj1ge5tk3icBNJFBffPUKhULqc8xVn8sqKaYZNkR9hZWFr6sc@NTsNlayMA7UO49ki7Zf71XTCm3roGmXVFtMrF6YpwGAKyzvRc8EJ2ccNCr5AawD6pgU@/EL/HpD/lTgA "Haskell โ€“ TIO Nexus") Usage: The anonymous function `(>0).f.words` takes a newline separated string as argument and returns `False` for left and `True` for right. **Explanation:** Given an input ``` 99 989 99 89 99 99 # # # ``` that is the string `" 99 989\n 99 89\n 99 99\n #\n #\n #"`, then `words` strips all newlines and spaces and returns a list of the remaining strings: `["99","989","99","89","99","99","#","#","#"]`. The function `f` takes the first two elements `a` and `b` from this list and checks whether `a` is a string of digits by comparing it to the string "#". (Because the char `'#'` is smaller than all the digit chars `'0'`, `'1'`, ... every string starting with a digit will be lexicographically larger than `"#"`.) The function `g` maps each char in a string to its ascii character code and returns their sum. In `f` we apply `g` to `a` and `b` and compute `g a - g b`, that is the value of the left path minus the value of the right one, and add it to a recursive call to `f` to handle the following lines. If the left path is more travelled the result from `f` will be negative and otherwise positive for the right path, so `(>0)` checks if the result is larger than zero. [Answer] ## Batch, 169 bytes ``` @echo off set/as=0 :l set/pr= if not %r: =%==# call:c - %r%&goto l cmd/cset/a"s>>9 exit/b :c call:r + %3 :r set/as%1=%2%%10,d=%2/10 if %d% gtr 0 call:r %1 %d% ``` Prints `0` for left, `-1` for right. Note: Reads lines until it finds one with a `#`, then stops reading. The difference in path sums is limited to 511 (add 1 byte to support larger differences). No more than 9 digits in each row of each path (supports any number of rows). Explanation: The `d` subroutine takes two parameters: whether to add or subtract and the digit(s). It extracts the last digit by modulo by 10 and the remaining digits by dividing by 10 and calls itself recursively while there are still digits remaining. The `c` subroutine takes three parameters: whether to add or subtract, the digits to add or subtract, and further digits to add. It calls the `d` subroutine to handle the digits to add and then falls through to handle the first two parameters. This means that calling the `c` subroutine with the parameters of `-` and the left and right digits will add the right digits and subtract the left digits. Finally the result is shifted to extract the sign. [Answer] # Octave, 46 bytes ``` @(a)diff((a(:)-48)'*(bwlabel(a>35)(:)==1:2))<0 ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaiZkpmWpqGRqGGlqWtioamupZFUnpOYlJqjkWhnbKoJFLa1NbQy0tS0MfifZquQmFdszZVoG62np8elbqigoGCozqWuYABmKABZCnAxAiwgE6pDQUFZHTuNYABZsdZcaUDn/gcA "Octave โ€“ TIO Nexus") A function that takes a 2D character array `a` as input. Explanation: ``` a= 1 1 0 1 1 1 1 1 1 1 1 1 1 1 # # # # # a > 35 %convert the matrix to a binary matrix %where there is a number corresponing %element of the binary matrix is 1. * * * * * * * * * * * * * * bwlabel(a>35) %label each connected component. 1 2 1 2 1 2 1 2 1 2 1 2 1 2 B=bwlabel(a>35)(:)==1:2 % a binary `[n ,2]` matrix created % each column related to one of labels A=(a(:)-48)' % convert array of characters to array of numbers A * B % matrix multiplication that computes % the sum of numbers under each label diff(A*B)<0 % check if the left is grater than the right ``` [Answer] # Batch ~~104~~ 223 bytes * missed the fact that numbers must be counted on a per charcater basis. Answer updated ``` @Echo off&Set/aa=0&For /f "tokens=1,2" %%1 in (%1)Do (Set c=%%1&Set d=%%2 For %%n in (c d)Do For /l %%i in (0 1 9)Do Call Set %%n=%%%%n:%%i=%%i+%%%% 2>nul Call Set/Aa+=%%c%%0,a-=%%d%%0) IF %A% GTR 0 (Echo(R)Else echo(L ``` * Input is from file passed as argument - `%1` * splits each line into two tokens * inserts a + character between each number [building a sum] * Increments `a` with sum of left token, decrements with sum of right token * Outputs L or R --- Sidenote: the test cases in this question dont fail if taking the path of just summing the 1st and 2nd column of each line. I made use of the follwing test case: ``` 034 060 1 1 2 0 0 2 # # # # ``` ]
[Question] [ A sturdy square (akin to a [magic square](https://en.wikipedia.org/wiki/Magic_square)) is an arrangement of the integers 1 to \$N^2\$ on an \$N\$ by \$N\$ grid such that every 2 by 2 subgrid has the same sum. For example, for \$N = 3\$ one sturdy square is ``` 1 5 3 9 8 7 4 2 6 ``` because the four 2 by 2 subgrids ``` 1 5 9 8 ``` ``` 5 3 8 7 ``` ``` 9 8 4 2 ``` ``` 8 7 2 6 ``` all sum to the same amount, 23: $$23 = 1 + 5 + 9 + 8 = 5 + 3 + 8 + 7 = 9 + 8 + 4 + 2 = 8 + 7 + 2 + 6$$ Now there are sturdy squares for higher values of N and even rectangular versions but your only task in this challenge is to output all possible 3 by 3 sturdy squares. There are exactly 376 distinct 3 by 3 sturdy squares, including those that are reflections or rotations of others, and not all of them have the same sum of 23. Write a program or function that takes no input but prints or returns a string of all 376 sturdy squares in any order, separated by empty lines, with up to two optional trailing newlines. Each square should consist of three lines of three space separated nonzero decimal digits. Here is a valid output example: ``` 1 5 3 9 8 7 4 2 6 1 5 6 8 7 3 4 2 9 1 5 6 8 9 3 2 4 7 1 5 7 9 6 3 2 4 8 1 6 2 8 9 7 4 3 5 1 6 2 9 7 8 4 3 5 1 6 3 9 8 7 2 5 4 1 6 7 8 5 2 3 4 9 1 6 7 9 4 3 2 5 8 1 7 2 9 4 8 5 3 6 1 7 2 9 6 8 3 5 4 1 7 4 8 3 5 6 2 9 1 7 4 9 2 6 5 3 8 1 7 6 9 2 4 3 5 8 1 8 2 5 9 4 6 3 7 1 8 3 6 5 4 7 2 9 1 8 3 9 2 7 4 5 6 1 8 4 5 7 2 6 3 9 1 8 4 6 9 3 2 7 5 1 8 4 9 3 6 2 7 5 1 8 6 7 3 2 4 5 9 1 9 2 5 6 4 7 3 8 1 9 2 6 4 5 7 3 8 1 9 2 6 8 5 3 7 4 1 9 2 8 3 7 4 6 5 1 9 3 7 2 5 6 4 8 1 9 3 7 6 5 2 8 4 1 9 4 5 8 2 3 7 6 1 9 4 6 7 3 2 8 5 1 9 4 8 2 5 3 7 6 1 9 5 7 2 3 4 6 8 1 9 5 7 4 3 2 8 6 2 3 5 9 8 6 4 1 7 2 3 6 9 7 5 4 1 8 2 4 3 8 9 7 5 1 6 2 4 3 9 7 8 5 1 6 2 4 6 7 8 3 5 1 9 2 4 7 8 9 3 1 5 6 2 4 8 9 6 3 1 5 7 2 5 3 9 4 8 6 1 7 2 5 4 9 3 7 6 1 8 2 5 4 9 8 7 1 6 3 2 5 7 6 8 1 4 3 9 2 5 7 6 9 1 3 4 8 2 5 8 7 6 1 3 4 9 2 5 8 9 4 3 1 6 7 2 6 1 7 9 8 5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 2 3 4 9 7 6 1 8 5 3 4 1 9 7 6 2 8 5 3 4 2 9 6 7 1 8 5 6 1 2 3 9 4 7 8 5 6 1 7 3 4 9 2 8 5 7 1 6 2 4 9 3 8 6 2 1 4 7 9 5 3 8 6 3 2 1 7 9 5 4 8 6 4 3 2 7 5 9 1 8 6 7 1 3 2 5 9 4 8 6 7 2 1 3 5 9 4 8 7 4 1 3 5 6 9 2 8 7 5 1 2 4 6 9 3 9 1 5 3 6 7 8 2 4 9 1 5 3 8 7 6 4 2 9 1 6 2 8 5 7 3 4 9 1 6 4 3 7 8 2 5 9 1 6 5 2 8 7 3 4 9 1 7 3 4 5 8 2 6 9 1 7 3 8 5 4 6 2 9 1 8 2 7 3 6 4 5 9 1 8 4 2 5 7 3 6 9 1 8 4 6 5 3 7 2 9 1 8 5 4 6 3 7 2 9 2 4 3 7 8 6 5 1 9 2 6 1 7 4 8 3 5 9 2 6 4 1 7 8 3 5 9 2 6 5 3 8 4 7 1 9 2 7 1 8 3 6 5 4 9 2 7 4 5 6 3 8 1 9 2 8 5 1 6 4 7 3 9 3 4 1 8 6 7 5 2 9 3 6 1 8 4 5 7 2 9 3 6 2 7 5 4 8 1 9 3 8 1 4 2 7 5 6 9 3 8 1 6 2 5 7 4 9 4 3 1 6 7 8 5 2 9 4 3 2 5 8 7 6 1 9 4 7 1 2 3 8 5 6 9 4 8 1 3 2 6 7 5 9 4 8 2 1 3 6 7 5 9 5 3 1 4 7 8 6 2 9 5 4 2 1 7 8 6 3 9 5 4 2 3 7 6 8 1 9 5 7 1 2 3 6 8 4 ``` Your program must produce these same 376 sturdy squares, just not necessarily in this order. The output does not need to be deterministic, i.e. you could output them in different orders on different runs as long as they are all there. **The shortest code in bytes wins.** The topic of sturdy squares originated with [this chat message](https://chat.stackexchange.com/transcript/message/24810050#24810050) of mine which led to a large amount of discussion on their properties and how to generate them. Props to [Peter Taylor](https://chat.stackexchange.com/users/5294), [feersum](https://chat.stackexchange.com/users/127072), and [Sp3000](https://chat.stackexchange.com/users/17335/sp3000) for continuing the discussion, and especially to [El'endia Starman](https://chat.stackexchange.com/users/14404) for [drafting](https://oeis.org/draft/A263542) a corresponding [OEIS sequence](https://oeis.org/A263542). [Answer] ## Python 3, ~~169~~ ~~168~~ 164 bytes Took the program I used to investigate these sturdy squares/rectangles and golfed it wayyyy down. Golfed off 4 bytes thanks to otakucode. ``` from itertools import* r=range(1,10) for p in permutations(r,6): x,y=p[0],p[5];q=p[:5]+(x+p[3]-p[2],y,y+p[1]-x,p[2]+y-x) if set(q)==set(r):print('%s %s %s\n'*3%q) ``` ### Explanation Given a partially-filled sturdy square like this, ``` a b c d e ? g ? ? ``` The remaining three entries are uniquely determined, and are `a+d-c`, `a+b-g`, and `c+g-a`. So I generate all permutations of 0..8 with six elements, calculate the rest, and then check to see whether the set of this is the same as the set of 0..8. If it is, I print out the grid. --- For reference, here's the original (with comments and extraneous code removed): ``` from itertools import permutations as P n = 3 m = 3 permutes = P(range(m*n), m+n) counter = 0 for p in permutes: grid = [p[:n]] for i in range(m-1): grid.append([p[n+i]]+[-1]*(n-1)) grid[1][1] = p[-1] s = p[0]+p[1]+p[n]+p[-1] has = list(p) fail = 0 for y in range(1,m): for x in range(1,n): if x == y == 1: continue r = s-(grid[y-1][x-1] + grid[y-1][x] + grid[y][x-1]) if r not in has and 0 <= r < m*n: grid[y][x] = r has.append(r) else: fail = 1 break if fail: break if not fail: counter += 1 print(counter) ``` [Answer] # Pyth, ~~38~~ ~~34~~ ~~33~~ 32 bytes ``` Vfq2l{sMX2.DR2.:T5b.pS9Vc3NjdH)k ``` *5 bytes saved in formatting by Jakube* *1 byte saved by switching to Peter Taylor's substrings of length five, remove the middles approach* Takes about a minute and a half to run on my machine. How it works at the high level: * Generate all permutations (`.pS9`) * Form length 5 substrings (`.:T5`) * Remove the center element of each (`.DR2`) * Append a newline to the center element, marking it with a necessarily different sum (`X2 ... b`) * Filter for the squares where all such sums are equal (`fq2l{`) * Format and print (`V ... Vc3NjdH)k`) [Answer] # CJam, ~~40~~ 38 bytes ``` A,1>e!3f/{2{2few:::+z}*:|,1=},Ma*Sf*N* ``` *Thanks to @PeterTaylor for golfing off 2 bytes!* This finishes instantly using the Java interpreter. It works using the online interpreter as well, but it requires a little patience. [Try it online.](http://cjam.aditsu.net/#code=A%2C1%3Ee!3f%2F%7B2%7B2few%3A%3A%3A%2Bz%7D*%3A%7C%2C1%3D%7D%2CMa*Sf*N*) ### Test run ``` $ cjam sturdy-squares.cjam | head -n 8 1 5 3 9 8 7 4 2 6 1 5 6 8 7 3 4 2 9 $ cjam sturdy-squares.cjam | tail -n 8 9 5 4 2 3 7 6 8 1 9 5 7 1 2 3 6 8 4 $ ``` ### How it works ``` A,1> e# Push [1 ... 9]. e! e# Push the array of all permutations of that array. 3f/ e# Split each into rows of length 3. { e# Filter; push the permutation, then: 2{ e# Do the following twice: 2few e# Split each row into overlapping splices of length 2. e# [a b c] -> [[a b] [b c]] :::+ e# Reduce each innermost vector to its sum. e# [[a b] [b c]] -> [a+b b+c] z e# Transpose rows with columns. }* e# The result is [[s t] [u v]], the sums of all 2x2 squares. :| e# Perform set union of the pairs of sums. ,1= e# Check if the length of the result is 1 (unique sum). }, e# Keep the array if the result was 1. { e# For each kept array: Sf* e# Join the elements of its rows, separating by spaces. ~M e# Dump the resulting strings and an empty string on the stack. }% e# Collect everything in an array. N* e# Join the strings, separating by linefeeds. ``` [Answer] # Python 3.5, 135 bytes ``` from itertools import* for x in permutations(range(1,10)):eval((("=="+"+x[%s]"*3)*4)[2:]%(*"013125367578",))and print("%d %d %d\n"*3%x) ``` Directly checks the sum of each square, minus the middle. Most likely still golfable by the "`itertools` is unnecessary" rule-of-thumb. [Answer] # Mathematica ~~147 166 155~~ 149 bytes This generates the permutations of {1,2,3...9} and selects cases for which (sum of digits at positions {1,2,4,5}) = (sum of digits at positions {2,3,5,6}) = (sum of the digits at positions {4,5,7,8}) = (sum of the digits at positions {5,6,8,9}) ``` f@s_:=Length@Tally[Tr@Extract[s,#]&/@Table[{{0},{1},{3},{4}}+k,{k,{1,2,4,5}}]]>1; Row[Grid/@(#~Partition~3&/@Select[Permutations@Range@9,f@#&]),"\n"] ``` **Output** (a partial look) [![output](https://i.stack.imgur.com/mjb49.png)](https://i.stack.imgur.com/mjb49.png) --- ``` Length[%] ``` > > 376 > > > [Answer] ## CJam (39 37 bytes) ``` A,1>e!{5ew{2Mtz}2*::+)-!},3f/Ma*Sf*N* ``` [Online demo](http://cjam.aditsu.net/#code=A%2C1%3Ee!%7B5ew%7B2Mtz%7D2*%3A%3A%2B)-!%7D%2C3f%2FMa*Sf*N*) (warning: may take over a minute to run, triggering "Abort this script?" prompts from the browser). Works by filtering all possible grids using `5ew` to map ``` [a b c d e f g h i] ``` to ``` [[a b c d e] [b c d e f] [c d e f g] [d e f g h] [e f g h i]] ``` and then discarding the middle element and the middle element of each other element to get ``` [[a b d e] [b c e f] [d e g h] [e f h i]] ``` which are the four squares. [Answer] # Python2 ~~327~~ ~~271~~ ~~270~~ ~~263~~ 260 bytes ``` z,v,s={},3,range(1,10) while len(z)<376: for i in range(8):v=hash(`v`);s[i],s[v%9]=s[v%9],s[i] m=map(lambda i:sum(s[i:i+5])-s[i+2],[0,1,3,4]);T=tuple(s) if all(x==m[0] for x in m) and not T in z: z[T]=1;print '%i %i %i\n'*3 % tuple(s[0:3]+s[3:6]+s[6:9]) ``` ## ------------ This is... not so short but it uses no libraries. This randomly permutes a square, checks it for magicness, prints it, and records it to prevent duplicates. After it has printed 376 unique magic squares, it stops. I borrowed the Pseudo Random Number Generator from Keith Randall's entry for the golf named " [Build a random number generator that passes the Diehard tests](https://codegolf.stackexchange.com/questions/10553/build-a-random-number-generator-that-passes-the-diehard-tests) " ``` z,v={},3 def R(x,y):global v;v=hash(`v`);return v while len(z)<376: s=sorted(range(1,10),cmp=R) m=[sum(q) for q in map(lambda p:s[p[0]:p[1]+1]+s[p[2]:p[3]+1], [[i,i+1,i+3,i+4] for i in [0,1,3,4]] )] if all(x==m[0] for x in m) and not tuple(s) in z.keys(): z[tuple(s)]=1;print '%i %i %i\n'*3 % tuple(s[0:3]+s[3:6]+s[6:9]) ``` De-golfed ``` # each magic square is an array of 9 numbers # #for example [1 9 3 7 2 5 6 4 8] # #represents the following square # #1 9 3 #7 2 5 #6 4 8 # # to generate a random square with each number represented only once, # start with [1 2 3 4 5 6 7 8 9] and sort, but use a random comparison # function so the sorting process becomes instead a random permutation. # # to check each 2x2 subsquare for sums, look at the indexes into the # array: [[0,1,3,4] = upper left,[1,2,4,5] = upper right, etc. # # to keep track of already-printed magic squares, use a dictionary # (associative array) where the 9-element array data is the key. from random import * def magic(s): quads=[] for a,b,c,d in [[0,1,3,4],[1,2,4,5],[3,4,6,7],[4,5,7,8]]: quads+=[s[a:b+1]+s[c:d+1]] summ=[sum(q) for q in quads] same= all(x==summ[0] for x in summ) #print quads #print 'sum',summ #print 'same',same return same magicsquares={} while len(magicsquares.keys())<376: sq = sorted(range(1,10),key=lambda x:random()) if magic(sq) and not magicsquares.has_key(tuple(sq)): magicsquares[tuple(sq)]=1 print sq[0:3],'\n',sq[3:6],'\n',sq[6:9],'\n' ``` [Answer] # Ruby 133 ``` a=[] [*1..9].permutation{|x|[0,1,3,4].map{|i|x[i]+x[i+1]+x[i+3]+x[i+4]}.uniq.size<2&&a<<x.each_slice(3).map{|s|s*' '}*' '} $><<a*' ' ``` Straightforward brute force approach. Test it [here](http://ideone.com/mO09Mj). [Answer] # J, 83 bytes ``` ([:;@,(<LF),.~[:(<@(LF,~":)"1@#~([:*/2=/\[:,2 2+/@,;._3])"2)(3 3)($"1)1+!A.&i.])@9: ``` This is a function that outputs a string containing the 376 sturdy squares. Uses brute-force, generates all permutations of 1 thru 9, shape each into a 3x3 array, and filters it by checking if the sums of each 2x2 subarray are equal. Completes in half a second. ## Usage ``` f =: ([:;@,(<LF),.~[:(<@(LF,~":)"1@#~([:*/2=/\[:,2 2+/@,;._3])"2)(3 3)($"1)1+!A.&i.])@9: $ f '' NB. A function has to take something to be invoked, NB. but in this case it is not used by the function 37 {. f '' NB. Take the first 37 characters 1 5 3 9 8 7 4 2 6 1 5 6 8 7 3 4 2 9 _38 {. f '' NB. Take the last 38 characters 9 5 4 2 3 7 6 8 1 9 5 7 1 2 3 6 8 4 NB. The output string ends with two newlines ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 38 bytes ``` sโŒฟโจ1=โ‰ขโˆ˜โˆชโค1โช+/,โคโŠขโŒบ1 2 2โŠขsโ†3 3โดโค1โŒ‚pmat 9 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97X/xo579j3pXGNo@6lz0qGPGo45Vj3qXGD7qXaWtrwNkPepa9Khnl6GCkYIRkFn8qG2CsYLxo94tYEU9TQW5iSUKliCT/qdxAQA "APL (Dyalog Extended) โ€“ Try It Online") Uses the builtin `dfns.pmat` to generate required permutations. Will add an explanation soon. Made with golfing help from Adรกm, who also ran the program on his machine for checking. โ†“ [![enter image description here](https://i.stack.imgur.com/IQbdl.gif)](https://i.stack.imgur.com/IQbdl.gif) ## Explanation ``` sโŒฟโจ1=โ‰ขโˆ˜โˆชโค1โช+/,โคโŠขโŒบ1 2 2โŠขsโ†3 3โดโค1โŒ‚pmat 9 1โŒ‚pmat 9 matrix of permutations of 1..9 sโ†3 3โดโค convert each to 3x3 matrix, and store in s โŠขโŒบ1 2 2โŠข get all overlapping 2x2 squares in each of those 1โช+/,โค sum the flattened 2x2's of each 1=โ‰ขโˆ˜โˆชโค is there only 1 unique sum? this creates a bitmask for filtering each 3x3 sโŒฟโจ filter s by that ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` 9ล’!sโ‚ฌ3+ฦโ‚ฌZ$โบFEฦฒฦ‡Gโ‚ฌjโพยถยถ ``` [Try it online!](https://tio.run/##y0rNyan8/9/y6CTF4kdNa4y1j80FUlEqjxp3ubke23Ss3R3IzXrUuO/QtkPb/v8HAA "Jelly โ€“ Try It Online") *Very* inefficient. Times out on TIO, and takes around 4m30s on my local computer. Uses [Dennis](https://codegolf.stackexchange.com/a/61437/66833)' method for finding the sums of the 2x2 submatrices. The last 6 bytes could be removed if the output format was more permissive. Outputs in the same order as in the question. ## How it works ``` 9ล’!sโ‚ฌ3+ฦโ‚ฌZ$โบFEฦฒฦ‡Gโ‚ฌjโพยถยถ - Main link. No arguments 9ล’! - Yield all permutations of [1, 2, 3, 4, 5, 6, 7, 8, 9] sโ‚ฌ3 - Split each into a 3x3 matrix ฦฒฦ‡ - Keep those for which the following is true: ฦโ‚ฌ - Over each neighbouring pair in each row: + - Take the sum Z - Transpose $โบ - Do this again F - Flatten E - Are all elements equal? Gโ‚ฌ - Join each row by spaces and then join rows by newlines jโพยถยถ - Join the final matrices with two newlines ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 34 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) +9 bytes for the output formatting :\ ``` 9รต รก mรฒ3 kรˆยฎรค+รƒร•ยฎรค+รƒrรข รŠร‰รƒยฎmยธยทรƒqRยฒ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=OfUg4SBt8jMga8iu5CvD1a7kK8Ny4iDKycOubbi3w3FSsg&input=IjEgNSAzCjkgOCA3CjQgMiA2Ig) ]
[Question] [ For example, let's look at the following ASCII art: ``` /\ - encloses a total of 2 cells - half a cell per slash \/ /\ - encloses 4 cells fully and half of 8 cells, for a total of 8 / \ \ / \/ ``` Your challenge is to write a program that determines (and outputs) the total area enclosed by ASCII art composed only of spaces, slashes and newlines. Slashes won't necessarily be a part of a shape with non-zero area. A point is defined as enclosed *iff* it is unreachable from any point outside the art's bounding box, if slashes are impassable. Slashes have zero area and cells are assumed to be \$1\times1\$ squares. `/`s represent lines that connect the lower left corner with the upper right corner, and `\`s represent lines the connect the upper left corner with the lower right corner of the corresponding cells. Spaces represent empty space. ## Test cases ``` /\/\ \ \ \/\/ ``` Encloses 3 cells fully and 10 partially, for a total of 8. ``` ///\\\ // \\ / /\ \ \ \/ / \\ // \\\/// ``` Encloses 12 cells fully (the four innermost slashes have both corresponding half-cells enclosed) and half of 12 cells, for a total of 18. ``` /\/\ /\/\ /\/\ ``` Encloses 0 cells. ``` /\ / \ \/\/ /\/\ \ / \/ ``` Encloses 8 cells fully and 12 cells partially, for a total of 14. ``` /\ / \ / \ \ / / \ \ \/ \/ \ \ / \ \ \/\/ ``` Encloses 25 cells fully and half of 18 cells, for an area of 34. This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins. [Answer] # JavaScript (ES6), ~~228 195 192~~ 185 bytes Expects a matrix of characters as input. This can be quite slow on some inputs, such as the last test case. ``` m=>m.map((r,Y)=>r.map((_,X)=>n+=(g=(x,y,z,q=z&2,r=m[y],v=r&&r[x])=>v?(v|=64+(v>{})+!++v)^(r[x]|=v|4<<z)?g(x+--q*~z%2,y-q*z%2,z^2)&g(x,y,v&3?z^=v&2|1:z+1&3)|!(r[x]=v):1:0)(X,Y,0)),n=0)|n ``` [Try it online!](https://tio.run/##TZDBcoIwFEX3@Yq4KOaVGBCdLhyDq/YH3OgY7TAIlA4EDTQjiP11mtBFu8m97@Xcu3ifkY7qWOWXZiarczKkfCh5WLIyuhCi6B54qH6Hd7ozg3Q5yTi50ZZ29Mo7J6CKl4f2SDVXjqMOt6Oh9Ibonr8sXaLD@wPcietqOBH723PdL9frDjYZubmz2fX5u3sKaGuM1e4UgJON/dpZbLoT107Qz1edO3cW0E/GDq5hNV/5QHZ0T30AKrkPvRxUcv3KVUKmaT0FppLo/JYXybaVMfGBNdW2UbnMCLD6UuQNmQoppAHTSr1G8QepMQ/xHWEcV7KuioQVVUZSUv/hBra3UBY8MMbUEQDQAwZPeAIjgTEWCBvvIeR5nhDCiNkZwQYQhhDGIWFIz4owlEFN4t@DLItsDo1V49ImbDX@AQ "JavaScript (Node.js) โ€“ Try It Online") ## How? ### Grid encoding We divide each cell into 4 areas as follows: [![areas](https://i.stack.imgur.com/maPxf.png)](https://i.stack.imgur.com/maPxf.png) The current position is encoded as \$(x,y,z)\$, where \$(x,y)\$ is the position in the matrix and \$z\$ is the ID of the area. The characters in the original matrix are converted on the fly to 7-bit integers as they are visited: ``` +---------> a marker to tell that this tile has been converted (always 1) | +--> 4 bits to tell whether a given area has been visited | | | | +-----> set to 1 if the cell contains an anti-slash | ____|____ | +--> set to 1 of the cell contains a slash | / \ | | 1 z3 z2 z1 z0 AS S ``` The conversion is done with: ``` v |= 64 + (v > {}) + !++v ``` The expression `(v > {})` is only *true* for `'\'` and `!++v` is *true* for either `'/'` or `'\'`. If `v` is already an integer, it is left unchanged. ### Algorithm Evaluating the area enclosed by slashes is equivalent to counting the number of cells from which we can't escape from the grid, starting from a given area ID. We arbitrary start from area #0, but that would work with any of them as long as it is consistent. We iterate on all possible starting points and process some kind of flood-filling that takes the area IDs into account. For each visited cell, we try to move to an adjacent cell (left figure) and to another area within the same cell (right figure). [![moves](https://i.stack.imgur.com/WtDn0.png)](https://i.stack.imgur.com/WtDn0.png) The recursion stops either when we escape the grid or when we get trapped. [Answer] # [J](http://jsoftware.com/), ~~108~~ ~~95~~ ~~93~~ ~~91~~ ~~83~~ ~~80~~ 77 bytes *-13 due using 4x4 instead of 3x3 masks* *-7 thanks to Jonah* *-~~2~~ 5 thanks to Bubbler* This expands the ASCII to a 4 times as big bit map that gets searched in for enclosed spaces. Maybe you can do the calculations on the original map, but at least this approach works for now. :-) ``` [:+/@,12%~1=2|.@|:@(2(>.*])/\,)^:4^:_[:,"_1/^:2((+./~#:9),-.(,:|.)=i.4){~' \'i.] ``` [Try it online!](https://tio.run/##nZAxT8MwEIV3/4qnIhq7de@IlQVHriKQmBADa67JRKWw0q1R/nqwk1QIBioYfHc6vfvu@d7HFWVHBI8MFnfw8e0Ij6/PT2Ptt1zZ3N0OeXA9Vb2vtNN72hwMizWNLxrf1t6u2pwb7zKWbN3RWee7KA42WO/6DQ@m6qgqRuDlgQD1R6rekf6O66gw5yFt6@ig/ovVW@Lhxt8bGxdY35MJCxgz2Iynt49TIOi6pNaZ@TiKhUUJAFGIJSujFl1K5fBDzSwiMUV9TGBBmpZYKYkUTkmi6gomLf0Kv2qRVMne5O5il5PbK4NIozFMf0sRE2luTKYTI7UnHpYr4HIHpcujWdMe/bzgEw "J โ€“ Try It Online") ### How it works Ungolfed: ``` 12 +/@,@:%~ 1= ((,-)=i.2) (] * >./@:(|.!.2))^:_ ((+./~#:9) , -. (,:|.)=i.4) ,"_1/^:2@:{~ ' \/'i. ] ``` Build up 3x4x4 masks, where `0` is a wall: ``` ((+./~#:9) , -. (,:|.)=i.4) 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 1 ``` That expands each character ' \/'. So from a 3x4 drawing we get a 12x16 bit mask. The empty space has 12 1's (while still allowing traversal) and each side of a slash has 6. ``` ,"_1/^:2@:{~' \/'i.] ``` Then shift the matrix in the four directions by rotating the matrix. At the borders `2` gets shifted in. The resulting matrices are added up together by taking the highest value (so 2 expands), while `0` in the matrix deletes (so borders blocks expansions). We do this until the result does not change `(โ€ฆ)^:_`. ``` 2|.@|:@(2(>.*])/\,)^:4^:_ ``` We are interested in the 1's that still stand. And because of our bit masks, we can simply divide by 12 of the total sum of all 1's to get the result. ``` 12 +/@,@:%~ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~114~~ ~~100~~ ~~96~~ 91 bytes ``` ๏ผท๏ผณโŠžฯ…ฮน๏ผฆฯ…ยซ๏ผชโฐโบยณโ…‰๏ผฆฮนยซ๏ผญยณโ†’โ‰กฮบ/๏ผฐ/ยฒ\๏ผฐ\ยฒยปยปโ‰”โบยฒ๏ผฌฮธฮธโ‰”โบยฒ๏ผฌฯ…ฯ…๏ผชยฑยนยฑยน๏ผขร—ยณฮธร—ยณฯ…ฯˆยค#๏ผฆฯ…๏ผฆฮธยซ๏ผชร—ยณฮบร—ยณฮน๏ผฐXยฒยปโ‰”๏ผฉรทโปร—โŠ—ฯ…โŠ—ฮธโ„–๏ผซ๏ผก#โดฮธโŽšฮธ ``` [Try it online!](https://tio.run/##bVFRS8MwEH5ufsVRX65QqU6f5tPcEBQnRfeg0JfaxTYsa9Ym2RTZb6@X1JUiQsjdfd@X5L5LUeVtoXLZdYdKSA54X@@seTGtqEuMIkitrtDGIKIb9qFaQBvBNwse7Ha3UngRQyqtxqsY3khNmsCLhBcFS7Xnjps@i7Iyjg30QZiiAtz0iiLXHMIknMLSSiN29KzBaRLDxKt7Osv@8NmJPzJaRzbTWpQ1@lYmMTzyujQVNlEUQ0O6/2nraEv0r5cnXuaG4yWhQ0rsrfrEldhyb7IhcigsFV@kuBNSYngWjibkYzOe1HBqM75C@JGNrb321gZP81wb@hOzEHux5rgUNZnozy@UfZd8ja6PU@49z5Wlq1LONzPqjADXHIXr00DmkuctUpL6RwnqOgBIMtoYRYDMJT5mwBLoMUaViwnzOGHMK53G7QmxrDvfyx8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Assumes rectangular input. Explanation: ``` ๏ผท๏ผณโŠžฯ…ฮน ``` Input the art. ``` ๏ผฆฯ…ยซ๏ผชโฐโบยณโ…‰ ``` Loop over each row of the art. ``` ๏ผฆฮนยซ๏ผญยณโ†’ ``` Loop over each cell of the art. ``` โ‰กฮบ/๏ผฐ/ยฒ\๏ผฐ\ยฒยปยป ``` Output it at three times its original size. ``` โ‰”โบยฒ๏ผฌฮธฮธโ‰”โบยฒ๏ผฌฯ…ฯ… ``` Adjust the size of the art for a notional 1-square border on each side. ``` ๏ผชยฑยนยฑยน๏ผขร—ยณฮธร—ยณฯ…ฯˆ ``` Draw a notional box around the notional border. This allows the border to be filled without actually having drawn anything. ``` ยค# ``` Fill the exterior of the art with `#`. Sadly Charcoal doesn't support multiline fill patterns. (Its fill was designed for the challenge, [Bake a slice of Pi](https://codegolf.stackexchange.com/q/93615/17602).) ``` ๏ผฆฯ…๏ผฆฮธยซ๏ผชร—ยณฮบร—ยณฮน๏ผฐXยฒยป ``` Draw `X`s at every position (including the notional border), overwriting all the existing spaces and slashes. This means that each square now has only four `#`s (or fewer if it didn't get completely filled in). ``` โ‰”๏ผฉรทโปร—โŠ—ฯ…โŠ—ฮธโ„–๏ผซ๏ผก#โดฮธ ``` Calculate the number of `#`s that there would have been had the art originally been empty (including the border), subtract the number of `#`s actually filled, then divide by 4. ``` โŽšฮธ ``` Clear the canvas and output the result. Alternative solution, based on @xash's idea of 4ร—4 masks, also 91 bytes: ``` โ‰”โชซ โญ†ฮธ ฮธโŠžฯ…ฮธ๏ผท๏ผณโŠžฯ…โชซ ฮนโŠžฯ…ฮธ๏ผขร—โด๏ผฌฮธร—โด๏ผฌฯ…ฯˆ๏ผฆ๏ผฌฯ…๏ผฆ๏ผฌฮธยซ๏ผชร—โดฮบร—โดฮนโ‰กยงยงฯ…ฮนฮบ ยซโ†˜๏ผต๏ผฒยฒยป/ยซโ†“โ†“โ†“โ†—โดยปโ†˜โดยปโ†–ยค#โ‰”๏ผฉโปร—๏ผฌฯ…๏ผฌฮธรทโ„–๏ผซ๏ผก#ยนยฒฮธโŽšฮธ ``` [Try it online!](https://tio.run/##hVI9b8IwEJ3jX3FKl4uUKipiSicKqgQCCVHYWKxgEotg58MGqorfntoOhIgOXXx3z@@9u5yTZLRKJM2bZlTXPBU4k1ygD@CH8KUqLtIFLbAMwQc/CEIog3ey1HWGus3PGc8Z4FQUWrV8DAK4M3pmPHhSfsgLrvmR1TgMYc5EqjIsTYdnTNu230awlxXgAyReHyhN1x/ieTN9LNbyYXzoO7oZPK8@c5VkgCM1FTt26aK2DCtprRJaM/vZsau8hTwxjCfyLFY8zZRz8lYsUVSkOcOBA66dLvqrayX/1UuzRIXxpnBtQhh2xju2pzpXMdwo3SwP0pW0dptizvZ2xk@e5@i/@Ca9PfCY1goXXOj6tqVupb1nMPlUqAk/8R3DsdSm3ZKxw8iYmSvrF8LbILj/EeOc0QrtA7vJDNQ0ABBtzUFMBNjaxMUtkAhajJjKxog43GDEMS3HnpG5Jc3rKf8F "Charcoal โ€“ Try It Online") Link is to verbose version of code. Assumes rectangular input. Explanation: ``` โ‰”โชซ โญ†ฮธ ฮธโŠžฯ…ฮธ ``` Generate a padding row. ``` ๏ผท๏ผณโŠžฯ…โชซ ฮน ``` Input the art padded on both sides. ``` โŠžฯ…ฮธ ``` Add padding to the bottom of the art. ``` ๏ผขร—โด๏ผฌฮธร—โด๏ผฌฯ…ฯˆ ``` Draw a notional box around the padded art. This allows the padding to be filled without actually having drawn anything. ``` ๏ผฆ๏ผฌฯ…๏ผฆ๏ผฌฮธยซ ``` Loop over each cell of the art. ``` ๏ผชร—โดฮบร—โดฮน ``` Jump to the cell. ``` โ‰กยงยงฯ…ฮนฮบ ยซโ†˜๏ผต๏ผฒยฒยป/ยซโ†“โ†“โ†“โ†—โดยปโ†˜โด ``` Draw the cell at four times size, except that space becomes a dot. This means that it takes up the same amount of space as a `/` or `\` but without impeding the flood fill. ``` ยปโ†–ยค# ``` Move the cursor off the last dot so that the exterior of the art can be flood filled with `#`. ``` โ‰”๏ผฉโปร—๏ผฌฯ…๏ผฌฮธรทโ„–๏ผซ๏ผก#ยนยฒฮธ ``` Divide the number of `#`s by 12, and subtract that from the padded size of the art. ``` โŽšฮธ ``` Clear the canvas and output the result. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 67 [bytes](https://github.com/abrudz/SBCS) ``` 12รทโจโ‰ขโธ1=(โ‰โˆ˜โŒฝ2(โŒˆโˆงโŠข)/2,โŠข)โฃ4โฃโ‰กโŠƒโช/,/({(โˆ˜.โˆจโจ1=3|โณ4)(โŒฝโต)โต}โˆ˜.โ‰ โจโณ4)[' /'โณโŽ•] ``` [Try it online!](https://tio.run/##bU@xSkNBEKy9r9guL5C4vJcgNvmSrEVAYhPQVmKqgN4LOcFCsBKNhcFWgjZp9E/mR56zp4UYi9tZdmdm50Znk@7x@WhyetIgXo2bsvp8Q1qjXiG9l4MCqUa8w3JbFVhGxGcsVm2tOg5IT30@1I9YzJFetKPFtCB9H3FNk3LQu0B67bcp3SJtKNjM8rp@8Bu@GrZEW@xwfXvkCZq9ccDlzRTpfvbhlF5QU5NgImJB2Gv4yzkIqmpmBJIIQoVRYuyCUaoORlb43/9X2TUXX/n1fDyT3NLD7LAPA3OSwJLzepUs/x7kTC70cTaRn59J/tsX "APL (Dyalog Unicode) โ€“ Try It Online") A port of [xash's excellent J answer](https://codegolf.stackexchange.com/a/206001/78410). ### How it works ``` 12รทโจโ‰ขโธ1=(โ‰โˆ˜โŒฝ2(โŒˆโˆงโŠข)/2,โŠข)โฃ4โฃโ‰กโŠƒโช/,/({(โˆ˜.โˆจโจ1=3|โณ4)(โŒฝโต)โต}โˆ˜.โ‰ โจโณ4)[' /'โณโŽ•] โŠƒโช/,/({(โˆ˜.โˆจโจ1=3|โณ4)(โŒฝโต)โต}โˆ˜.โ‰ โจโณ4)[' /'โณโŽ•] โ Preprocessing ( ) โ Create 3 bitmasks โˆ˜.โ‰ โจโณ4 โ Negated identity matrix of size 4 { (โŒฝโต)โต} โ Strand with its reflection, and (โˆ˜.โˆจโจ1=3|โณ4) โ Self OR outer product of 1 0 0 1 [' /'โณโŽ•] โ Convert three chars ' /\' to respective bitmasks ,/ โ Join horizontally adjacent arrays horizontally โช/ โ and vertically adjacent ones vertically โŠƒ โ Remove nesting 12รทโจโ‰ขโธ1=(โ‰โˆ˜โŒฝ2(โŒˆโˆงโŠข)/2,โŠข)โฃ4โฃโ‰ก โ Flood fill from the outside, and find the answer ( 2,โŠข) โ Prepend 2 on each row 2(โŒˆโˆงโŠข)/ โ Pairwise reduce: (x,y)โ†’lcm(max(x,y),y) โ Effectively, if left is 2 and right is nonzero, make it 2; โ keep the right one otherwise โ‰โˆ˜โŒฝ โ Rotate the matrix 90 degrees โฃ4โฃโ‰ก โ Repeat on the four sides, until the flood fill is complete 12รทโจโ‰ขโธ1= โ Count ones, and divide by 12 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~51~~ ~~50~~ 49 bytes ``` Ji^G8\*TTYa3XytPJ*-X*Xj~4&1ZIt1)0hm3thZCS6:Y)~Yms ``` Input is a char matrix, with `;` as row separator. [Try it online!](https://tio.run/##y00syfn/3yszzt0iRiskJDLROKKyJMBLSzdCKyKrzkTNMMqzxFDTICPXuCQjyjnYzCpSsy4yt/j//2h1/Rj9GAV1awX1GAUFhRgQQwEooq8eCwA) Or [verify all test cases](https://tio.run/##TY/BCsIwDIbvPkVOlg0kjomIHhXEnQR32GaU7TbFnuxBL3v1mqZx7NSvSb4/re3cy7e@eNyPG0rLsu7y6uvORbqo0uo5rOZZc3JZsuxt7vpmf1lv62So7dsfmk/prwYJCcwODAEABQCuoLnNuIdIJDVEbkYCnqcoEF@E2EUlYinKHCPC9AwN0IWo@2TdZDCE6TsgCvBXGFiCyIJjFIxxwQPSiDCN6soPleWTHP8D) ### Explanation The approach is similar to that used in my answer to [this other challenge](https://codegolf.stackexchange.com/questions/194987/slash-the-matrix). ``` J % Push imaginary unit, j i % Take input: char matrix ^ % Element-wise power of j raised to the code points of the input. % This gives -j, 1, 1 for '/', '\' and ' ' respectively G % Push input again 8\ % Modulo 8, element-wise. This gives 7, 4 0 for '/', '\' and ' ' % respectively. The specific values do not matter; it only matters % that ' ' gives 0 and the other chars give nonzero * % Multiply. Now we have a matrix that contains -7, 4 and 0 for % '/', '\' and ' ' (*) TTYa % Pad array with a 2D frame of zeros of length 1 3Xy % Push 3ร—3 identity matrix tP % Duplicate, flip vertically J*- % Multiply by imaginary unit and subtract. This gives the matrix % [1 0 -j; 0 1-j 0; -j 0 1] (**) X* % Kronecker product. This replaces each entry of (*) by its % product with (**) Xj % Real part. We now have a matrix where '/', '\' and ' ' have been % transformed into [0 0 -7; 0 -7 0; -7 0 0], [4 0 0; 0 4 0; 0 0 4] % and [0 0 0; 0 0 0; 0 0 0] respectively ~ % Negate. We now have a matrix with "pixelated" versions of the % input chars at 3 times greater resolution, with an empty frame. % Pixels equal to 1 are empty space, and pixels equal to 0 are % borders corresponding to the original slash chars 4&1ZI % Label connected components based on 4-neighbourhood. This % transformes the pixels which contained 1 into different numbers % We are interested in the area not occupied by the outer % connected component and the borders t1) % Duplicate. Value of the upper-left corner. This gives the label % of the outer component 0h % Append 0. This is the value of the borders m % Ismember: this gives true for pixels that are outer component % or border. Each original cell corresponds to a 3ร—3 block of % pixels. Each of those blocks will contain 9 zeros for cells % that were fully enclosed; 6 zeros for cells with its two halves % enclodes but with a border in between; 3 zeros for cells with % one of its halves enclosed, and 0 zeros for cells not enclosed 3thZC % Matrix where each distinct 3ร—3 block has been arranged into % a column of length 9 S % Sort. This sends 1 to the bottom and 0 to the top 6:Y) % Keep the first 6 rows. This effectively transforms columns with % 9 zeros into columns of 6 zeros. So now we have 0, 3 or 6 zeros % for not covered, partically covered or fully covered cells ~ % Logical negation Ym % Mean of each column. This transforms the 0, 3, and 6 numbers % referred to above into 0, 0.5 or 1 s % Sum. Implicit display ``` ]
[Question] [ In sporting competitions, it often happens that winners are presented on podiums, with the first-place person on the highest in the middle, the second-place person on the middle height to the left, and the third-place person on the lowest and to the right. We're going to recreate that here with some special tweaks. The podiums are presented below: ``` @---@ | @ | @---@| | | | @ || | | | | || | |@---@ | | || | || @ | ``` This will form the basis for this challenge. The next step is to make the podiums wide enough to fit the people (printable ASCII strings) that are on them. However, we want to ensure aesthetic beauty (because this is a fantastic photo opportunity), so each podium needs to be the same width, and the width must be odd. Additionally, the people will (obviously) want to stand in the center of the podium, so the strings must be centered as best as possible. (You can align to either the left or the right, and it doesn't need to be consistent.) The above podiums are the minimum size, and are considered `3` wide. For example, given the input `["Tom", "Ann", "Sue"]` representing first-, second-, and third-place respectively, output the following podiums: ``` Tom @---@ Ann | @ | @---@| | | | @ || | | Sue | | || | |@---@ | | || | || @ | ``` However, if we have `Anne` instead of `Ann`, we'll need to go up to the next size, `5`, and center the strings as best as possible. Here, I'm aligning so the "extra" letter of `Anne` is to the left of center, but you can choose which side to align to. ``` Tom @-----@ Anne | @ | @-----@| | | | @ || | | Sue | | || | |@-----@ | | || | || @ | ``` Let's go for some longer names. How about `["William", "Brad", "Eugene"]`: ``` William @-------@ Brad | @ | @-------@| | | | @ || | | Eugene | | || | |@-------@ | | || | || @ | ``` Here we can see that `Brad` has a lot of whitespace, `Eugene` less so, and `William` fits just right. For a longer test case, how about `["A", "BC", "DEFGHIJKLMNOPQRSTUVWXYZ"]`: ``` A @-----------------------@ BC | @ | @-----------------------@| | | | @ || | | DEFGHIJKLMNOPQRSTUVWXYZ | | || | |@-----------------------@ | | || | || @ | ``` Finally, we have the smallest possible input, something like `["A", "B", "C"]`: ``` A @---@ B | @ | @---@| | | | @ || | | C | | || | |@---@ | | || | || @ | ``` --- * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * The input is guaranteed non-empty (i.e., you'll never receive `""` as a name). * 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 acceptable, so long as the characters line up appropriately. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # JavaScript (ES8), 196 bytes ``` a=>`141 101 521 031 236 330 332`.replace(/./g,n=>[...`@-@ |@||||`.substr(n*3,3)].join(' -'[+!+n].repeat(m/2))||a[n-=4].padStart(m+l[n]+3>>1).padEnd(m+3),m=Math.max(2,...l=a.map(s=>s.length))&~1) ``` [Try it online!](https://tio.run/##jU3bUoMwEH3nKyIPNhFIG1J9C9OL1Xqpt1arIjPEklI6ITBAHR8Yfx1Dn9VxZ86e2bPn7G75By9XRZJXjsoi0axZw5kXkj4xSI8Yxy4xepQYLj0xKO1puCEuRC75SsAu7sa2Yp6PMQ4HzgAAUA9qXSEud@9lVUB1RG2KArzNEgU7wOn41oGlgvaC4BVMuy5Cdc195bB@gHMezSteaN2Svgos6nkEtepERVqjyE7ZjFcbnPJP6Nr6q2RcDzksmVdiKVRcbRA6/CKoWWWqzKTAMovhGvrmIktNG5hDpVqa74QZIGAB802ZyPjdLP7hXiZSJnyfGBU8anmyi4X6MzTc28dtP52cnU8vLq@uZze3d/cP88Xj0/L55VWnf4yZI41xu22@AQ "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Groovy](http://groovy-lang.org/), ~~187~~, ~~176~~, ~~156~~, 150 bytes ``` f={n->m=n*.size().max()|1;h=' '*(m/2);'30734715746756276647665'*.toLong().sum{(n*.center(m+2)+[' '*(m+2),"@${'-'*m}@","|$h@$h|","|$h|$h|",'\n'])[it]}} ``` [Try it online!](https://tio.run/##fYxLT4NAFIX3/AoyIbkzlKKlwCwaDFXrq76pVsUuiE4LCTMYCqYK/HYcWheuXNxzT3K@c1Z5ln1@te3Sq0T/gHtCN9fJN8PE5NEGk3owij1QQcd8zyIjGO7ToU0HDrVd6rgWdV1bngO6WWRBnOWFLK5LXmG588ZEwXLMexbphbsNaQ3kaxX0QeeNjwxUa7GvxfXO1VsHrwIWJEyKRdO0H3kiilTgJQ5hlnEwYCyE1KBkEiLKb64ipCh/2XmSpkkkeRUO8@i9@5NyxcT/rfGWP@r0eHJyenZ@Mb28ur65vbsPZg@P86fnl67e/gA "Groovy โ€“ Try It Online") (note: the tio groovy interpreter could not handle indexing Lists using Long values even though groovy 2.5.6 can. Thus the tio answer is using `*.toShort()` instead of `*.toLong()` which adds a byte) Defines a closure `f` which can be called via: ``` println(f(['tom','ann','sue'])) ``` where `f` returns a string. ### Explanation: Unobfuscating the code, we have: ``` f={n-> m=n*.size().max()|1 h=' '*(m/2) a=n*.center(m+2)+[' '*(m+2),"@${'-'*m}@","|$h@$h|","|$h|$h|",'\n'] '30734715746756276647665'*.toLong().sum{a[it]} } ``` * `f={n->` - define closure f with one in-param `n` * `m=n*.size().max()|1` - find max name len, binary-or to odd number * `h=' '*(m/2)` - h will contain floor(m/2) spaces, used later * `a=...`- creates an encoding list with elements: + indexes 0,1,2 - names, centered to max len + index 3 - m+2 spaces + index 4 - `@---@` pattern, padded to len + index 5 - `| @ |` pattern, padded to len + index 6 - `| | |` pattern, padded to len + index 7 - newline * `'307...'*.toLong().sum{a[it]}`- use indicies into the encoding list to build the result. `.sum` uses the fact that string + string in groovy is valid. * note that the expression `'3073...'*.toLong()` uses the `*.` spread operator to call `toLong()` on each character, returning a list of numbers. * note in the answer the variable `a` has been inlined,nelines removed etc. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 45 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ๏ฝ’๏ผ“๏ผ•๏ผ‘โฐ๏ฝ›|๏ผŠ@๏ผ›โˆ”๏ผ›๏ผชโ””๏ฝŒ๏ผ’๏ผญ๏ผ’๏ผ…ยฑโ”œ ร—ร—๏ฝŒโ‡ตโ•ท-ร—โ””๏ผ‹-ฮฑโˆ”๏ฝ‹๏ผ‹โ”‚โˆ”โ‡ต๏ผ›๏ฝโ”๏ผ‹๏ผ‹โ‡ต ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjUyJXVGRjEzJXVGRjE1JXVGRjExJXUyMDcwJXVGRjVCJTdDJXVGRjBBQCV1RkYxQiV1MjIxNCV1RkYxQiV1RkYyQSV1MjUxNCV1RkY0QyV1RkYxMiV1RkYyRCV1RkYxMiV1RkYwNSVCMSV1MjUxQyUyMCVENyVENyV1RkY0QyV1MjFGNSV1MjU3Ny0lRDcldTI1MTQldUZGMEItJXUwM0IxJXUyMjE0JXVGRjRCJXVGRjBCJXUyNTAyJXUyMjE0JXUyMUY1JXVGRjFCJXVGRjVEJXUyNTEwJXVGRjBCJXVGRjBCJXUyMUY1,i=JTVCJTIyQUFBQUFBJTIyJTJDJTIwJTIyQiUyMiUyQyUyMCUyMkNEJTIyJTVE,v=8) Explanation: ``` r Center the input, preferring left. Converts to an ASCII-art object which pads everything with spaces. This is the bulk of the magic. 251โฐ{ .... } for each number in [2, 5, 1]: |* repeat "|" vertically that many times @;โˆ” prepend an "@" - a vertical bar for later ; swap top 2 stack items - put the centered art on top J push the 1st line of it (removing it from the art) โ”” order the stack to [remaining, "@ยถ|ยถ|..", currentLine] l get the length of the current line 2M max of that and 2 2% that % 2 ยฑโ”œ (-that) + 2 ร—ร— prepend (-max(len,2)%2) + 2 spaces l get the length of the new string โ‡ตโ•ท ceil(len / 2) -1 -ร— repeat "-" that many times - half of the podiums top โ”” order stack to [art, currLine, "@ยถ|ยถ|..", "----"] + append the dashes to the vertical bar = "@-----ยถ|ยถ|.." -ฮฑโˆ” vertically add "-" and the original vertical bar - "-ยถ@ยถ|ยถ|.." k remove the last line of that to make up for the middles shortness + and append that horizontally - half of the podium without the name โ”‚ palindromize the podium โˆ” and prepend the name โ‡ต reverse vertically so the outputs could be aligned to the bottom ; and get the rest of the centered input on top Finally, โ” remove the useless now-empty input ++ join the 3 podium parts together โ‡ต and undo the reversing ``` Abuses "and it doesn't need to be consistent", making it pretty unintelligible. [Answer] # [Python 2](https://docs.python.org/2/), ~~197~~ 190 bytes ``` n=input() w=max([3]+map(len,n)) w+=~w%2;W=w+2 S=('{:^%d}'%w).format x,y,s='@| ' a,b,c=map(S,n);A,B,C=x+'-'*w+x,y+S(x)+y,y+S(y)+y for l in-~W*s+a,s*W+A,s+b+s+B,A+C,B+C+s+c,C+C+A,C+C+B:print l ``` [Try it online!](https://tio.run/##TU9NT4NAFLzvr9hsQvh4rx4wXtpsImzrt1alitrUZNuiksCWAA0QtX8dF7xwmZnMvDfJZE35tVNuK@bTGc8ZY63iscr2pWWTiqeytpbHK0hlZiWRQmVrF/ihMtxJyCtwScAt83v8bmx/TaOyjz52eSpLUmODBTdPf6hJJK5xw7uGQP9PPPRR8BrMkelUoA8hsGobml40WhDdQRMaq9EhdAqQWDgheFjAGgrw0QOBPgitNyg0ez364yyPVUmTVk8gJKqjDe0mOSftki12KUPKPKU6CvYRW5GhGw3tME6SWPaRn8ttx7P9Z6T@U6/3RYfT2dn5xeXV9c3t3fz@4TFYPD2HL69vg7MOBFv9AQ "Python 2 โ€“ Try It Online") -6 bytes, thanks to Andrew Dunai [Answer] # [Python 2](https://docs.python.org/2/), 157 bytes ``` a=input() i=7 while i:print''.join(([a[k/2]]+list('-@|||| '))[7-i-k].center(max(map(len,a))|1,'- '[i+k!=6]).join('@ |'[cmp(i+k,6)]*2)for k in(2,0,4));i-=1 ``` [Try it online!](https://tio.run/##JYzRCoIwGIXve4rlzfbnZimhUAzsGepu7EJk4d90DptU4Lvbog8OB74Dx39CN7piXRuJzs@BwQZltXl12BuCJz@hC5RmjxEdY6pRdl9onfb4DIyKeomQCAVQlUBhddYaF8zEhuYd41lvHG8AlpxTQajC1G5lqeF/SGuyUNUOnkXPS9C7Au7jRCyJY8EP/AhwRiHzdVXJbRwSTpKLc@bX19kk@gs "Python 2 โ€“ Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes ``` โ‰”รทโŒˆ๏ผฅฮธ๏ผฌฮนยฒฮท๏ผฆยณยซ๏ผชร—ฮนโบยณโŠ—ฮทโŠ—๏นชโปยนฮนยณโŸฆโ—งยงฮธฮนโบโŠ•ฮทโŠ˜โŠ•๏ผฌยงฮธฮนโŸงโ‰”โปโทโ…‰ฮน๏ผฐโ†“ฮน@ฮท๏ผฐโ†“ฮน๏ผฐโ†“@@ยนฮท๏ผฐโ†“ฮน@ ``` [Try it online!](https://tio.run/##jU9PS8MwFD@vnyL09ArxMHsQ3GWTClZW6GEgMnqITdY@SJPaJnUgfvaadBUrghgIL@@937@UNetKzeQ47voeKwWpMgkOyAVk7IyNbVxt4ZWSvVCVqQGjKKLk2t062gQn3RGII/IerB5t0x40HLARPSAlubQ9xJQk2r5IwaGeiF9dprmVGjJUDrWmBN0udohNsMo7VAaOOeN7cTKwM6ni4uwjeNAkm6qyE41QZtKl5IHJwT2X4znuD/Z0Cu8xf/Zif0PJM/hw6FeZlQbbKcNtot/UPL6kCrfhd1P/Af89DrdL7vp/MkvXj3E8HsMnlBJZEzrBu45xX@9tJZQIi2K8GuQn "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` โ‰”รทโŒˆ๏ผฅฮธ๏ผฌฮนยฒฮท ``` Calculate the number of spaces in each half of a podium. ``` ๏ผฆยณยซ ``` Loop over each place. Note that input is expected to be in the order 2nd, 1st, 3rd. ``` ๏ผชร—ฮนโบยณโŠ—ฮทโŠ—๏นชโปยนฮนยณ ``` Position to the start of the line that will have the text. ``` โŸฆโ—งยงฮธฮนโบโŠ•ฮทโŠ˜โŠ•๏ผฌยงฮธฮนโŸง ``` Output the text with enough left padding to centre it. ``` โ‰”โปโทโ…‰ฮน ``` Get the height of the podium. ``` ๏ผฐโ†“ฮน@ฮท๏ผฐโ†“ฮน๏ผฐโ†“@@ยนฮท๏ผฐโ†“ฮน@ ``` Draw the podium. Alternative approach, also 63 bytes: ``` โ‰”รทโŒˆ๏ผฅฮธ๏ผฌฮนยฒฮท๏ผฆยณยซ๏ผชร—ฮนโบยณโŠ—ฮทโŠ—๏นชโปยนฮนยณโŸฆโ—งยงฮธฮนโบโŠ•ฮทโŠ˜โŠ•๏ผฌยงฮธฮนโชซ@-@ร—-ฮทโŸง๏ผฅโปโทโ…‰โชซโชซ||ยง|@ยฌฮบร— ฮท ``` [Try it online!](https://tio.run/##VY8/a8MwEMXn@FMITWeQh9ZDhyxJSaEOcfEQKMVkUCzFPipLqS2bQN3P7kp20j8CcdLpvZ/eFRVvCsPVOK7bFksNibYb7FFISPkF66529QwfjOykLm0FGIYhI/duV@EyOJmGQBySz2Cx7erz3sAea9kCMpKproWYkY3pjkoKqCbj7ZYa0SkDKWqnumME3VvsFMtgkTWoLeQZFzt5srC2iRby4iN40YRNdNHIWmo7cRl55qp3x7/ta9x/7mkxsjWoga6iFWVkjksj6ucJD7//@6nndA@MvMGPbzYPgzPc2HTwpBdj4X3iX5lkZvqZvsYxz@krKoW8dm362HDh61NXSi3p4TBGvfoG "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` โ‰”รทโŒˆ๏ผฅฮธ๏ผฌฮนยฒฮท ``` Calculate the number of spaces in each half of a podium. ``` ๏ผฆยณยซ ``` Loop over each place. Note that input is expected to be in the order 2nd, 1st, 3rd. ``` ๏ผชร—ฮนโบยณโŠ—ฮทโŠ—๏นชโปยนฮนยณ ``` Position to the start of the line that will have the text. ``` โŸฆโ—งยงฮธฮนโบโŠ•ฮทโŠ˜โŠ•๏ผฌยงฮธฮน ``` Output the text with enough left padding to centre it. ``` โชซ@-@ร—-ฮทโŸง ``` Also output the top of the podium by inserting `-`s between the characters of the string `@-@` to reach the correct width. ``` ๏ผฅโปโทโ…‰โชซโชซ||ยง|@ยฌฮบร— ฮท ``` Print the remainder of the podium by spacing the `|`s appropriately, except that the middle character is a `@` on the first row. [Answer] # R 308 302 299 -6 bytes thanks to @JAD -3 bytes thanks to @Guiseppe, now I'm under 300 ``` function(a){i=max(1,nchar(a)%/%2) e=2*i+1 `~`=rep g=' ' s=g~e+2 b='@' p='|' t=c(b,'-'~e,b) x=c(p,g~i,b,g~i,p) h=sub(b,p,x) a=lapply(a,function(q){r=nchar(q);l=(e-r)/2+1;if(r%%2<1)c(g~l,q,g~l+1)else c(g~l,q,g~l)}) cat(s,a[[1]],s,s,t,s,a[[2]],x,s,t,h,s,x,h,a[[3]],h,h,t,h,h,x,fill=length(t)*3,sep='')} ``` There's probably a better way to create the layout; I should try what options I have for data frames. [Try it online](https://tio.run/##fVBba8IwFH7Pr@hLSWIj0vqogU3n7nfdVQTTLr1ArDFNocPZv@6OHewCMk7ywXfhnJOYrVbCxkuzKJx@29nGZR7ZbJkTQdcZX4iK@CyPUmFAcDtuQJHkQSvzfDSv59xIjRKOHYwKntTSC1DI8QFGmuMPjCyPSMhwG9eShRRVQDVL6oyFDWqKUl6UIWQ0qygSXAmt1TsR7HuLFV0b/jV/RXuKE9k2tBN4fi@LiXHdoO/TiCS1YivoqTyfSlVI55dENxRFwpKCienUn81YAWVZQwOgVUNTwAoQxC6IKZRtsGJxphRXMk9sSixtdVkh4XmYbn5@jkQEY9YcStEf@TDPQZ4sF4DjUu7z5b@BgRFvYD3BFpnYhUZlIvM9jcAaDAGORscnp2fnF5dX1ze3d/fjycPj88vr/jzc4c7ZfgI) [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 209 bytes ``` import StdEnv,Data.List k=[' @|||||'] $l#m=max(maxList(map length l))3/2*2+1 =flatlines(transpose[(spaces(n*2)++g)%(0,6)\\n<-[1,0,2],g<-[k:[[c,'-':tl if(i==m/2)k[' '..]]\\c<-cjustify m(l!!n)&i<-[0..]]]++[k]]) ``` [Try it online!](https://tio.run/##JU@xasMwFNz9FQpNKymWHceFDiGGUpKhkKGQoYOsQZVlV7UkG0suDfTbq8rkwePdvePgTmjJbTBDM2sJDFc2KDMOkwcX35zsNzlyz/Ozcj7pKwrB8@8ykCVrfWcqw39Q3EWOdwRa2s5/Ao3x47bclOkuqVrNvVZWOuQnbt04OEmRG7mIH7spcZp2@B4V5AnXtT1kdEcKUjLSRdjvKRUEZnDvNVAtUlVltiXuYwwA85yxuhaHTHzNzqv2CgzSq5XFDypai0VmaUp7xnC4eB4LVWANKIXvSmvFDWQEUPgy8eaGTnMnrYSMhT8RM3cuZK/ncLxabpS4kbdYpR0mE7KPfw "Clean โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 188 bytes ``` a,b,c=l=input() s=max(map(len,l))/2or 1 A='@'+'--'*s+'-@' D=(' '*s).join C=D('|@|') D=D('|||') d=str.center S=s*2+3 for l in' '*S+d(a,S),' '*S+A,d(b,S)+C,A+D,C+D+d(c,S),D+D+A,D+D+C:print l ``` [Try it online!](https://tio.run/##JYxNDsIgEIX3nILdQJnWWHcmJEW4QU9Af4w1lDYUE0169wq6ee99@TKzfuJj8fVxWOywl05Ofn1FxskmZ/tms12ZGz06zk/1EuiZKAkNCChLKLZUDRAjGdBEvHoukydaGgZ7swNPJs89z0FuMVT96OMYSCu3ohYXck8fHZ18Pm/FwCy2HP@gcGBdQqFRCYNamOT77E2a6pf6uobJR@qOg4ECpHCzObXtgH8B "Python 2 โ€“ Try It Online") -5 thanks to [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld). [Answer] # PHP, 147 bytes golfed 93 bytes off my initial idea, a straight forward `<?=`: ``` for(;~$v=_616606256046543440445[++$i];)echo$b="@ || "[$v],str_pad(($v&4?"|@":$argv)[$v&3],max(array_map(strlen,$argv))," -"[!$v],2),$b," "[$i%3]; ``` takes names from command line arguments. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/5b1c14f47645d5669540cd7c0f9c32ae86cb147b). Requires PHP 7; yields warnings in PHP 7.2 (and later, presumably). See the TiO for a +5 byte fix. ## mapping: ``` 0:@---@ = top border 1,2,3 = $argv with spaces 4: "| | |" = default 5: "| @ |" = below top 6: " " = empty ``` ## breakdown: ``` for(;~$v=_616606256046543440445[++$i];)echo # loop through map: $b="@ || "[$v], # print left border str_pad( # print padded string: ($v&4?"|@":$argv)[$v&3], # string to be padded max(array_map(strlen,$argv)), # pad length = max argument length " -"[!$v], # pad with: dashes if top border, spaces else 2 # option: center text (pad on both sides) ), $b, # print right border "\n"[$i%3] # add linebreak every three items ; ``` The pre-increment for `$i` saves me from any tricks for the newlines. The blank for `6` can also be empty; so I did that. But using `$argv[0]` for the top border string `-` was the nicest golf ever. (and saved 9 bytes!) [Answer] # Go, 436 bytes Go is terrible for golf. But: ``` package main;import ("fmt";"os");func main(){;z:=os.Args;f:=3;for i:=1;i<4;i++{;if len(z[i])>f{;f=len(z[i]);};};f+=1-f%2;p:=(f-1)/2+1;b:="@";for j:=0;j<f;j++{;b+="-";};b+="@";x:=fmt.Sprintf("|%*v%*v",p,"@",p,"|");y:=fmt.Sprintf("|%*v%[1]*v",p,"|");fmt.Printf("%*v%*v\n%*v%v\n%*v%*v\n%v%v\n%v%v%*v\n%v%v%v\n%v%v%v",f+2,"",p+1+len(z[1])/2,z[1],f+2,"",b,p+1+len(z[2])/2,z[2],2*f+3-p-len(z[2])/2,x,b,y,x,y,p+1+len(z[3])/2,z[3],y,y,b,y,y,x)} ``` Broken down: ``` package main import ( "fmt" "os" ) func main() { z:=os.Args f:=3 for i:=1;i<4;i++{ if len(z[i])>f{ f=len(z[i]) } } f+=1-f%2 p:=(f-1)/2+1 b:="@" for j:=0;j<f;j++{ b+="-" } b+="@" x:=fmt.Sprintf("|%*v%*v",p,"@",p,"|") y:=fmt.Sprintf("|%*v%[1]*v",p,"|") fmt.Printf("%*v%*v\n%*v%v\n%*v%*v\n%v%v\n%v%v%*v\n%v%v%v\n%v%v%v", f+2,"",p+1+len(z[1])/2,z[1], f+2,"",b, p+1+len(z[2])/2,z[2],2*f+3-p-len(z[2])/2,x, b,y, x,y,p+1+len(z[3])/2,z[3], y,y,b,y,y,x) } ``` [Answer] # Java 8, ~~399~~ ~~394~~ 373 Bytes This solution is probably way too long, but it is a solution :) ``` static String r(String[]p){String s="";int l[]=new int[]{p[0].length(),p[1].length(),p[2].length()},m=Math.max(l[0],Math.max(l[1],l[2]))+2,i,q,j,a,k,t;if(m%2==0)m++;if(m==3)m=5;for(i=0;i<7;i++){for(q=0;q<3;q++)for(j=0;j<m;j++){a=(2*q+1)%3;k=2*a;t=(m-l[a])/2;s+=i==k?j>=t&j<t+l[a]?p[a].charAt(j-t):" ":i==k+1?j%(m-1)==0?"@":"-":i>=k+2?j%(m-1)==0?"|":j==m/2?i==k+2?"@":"|":" ":" ";}s+="\n";}return s;} ``` Saved 5 Bytes by directly iterating in order (a=1,0,2 instead of q=0,1,2; a=f(q)) ``` static String r(String[]p){String s="";int l[]=new int[]{p[0].length(),p[1].length(),p[2].length()},m=Math.max(l[0],Math.max(l[1],l[2]))+2,i,j,a,k,t;if(m%2==0)m++;if(m==3)m=5;for(i=0;i<7;i++){for(a=1;a<4;a=a==1?0:a+2)for(j=0;j<m;j++){k=2*a;t=(m-l[a])/2;s+=i==k?j>=t&j<t+l[a]?p[a].charAt(j-t):" ":i==k+1?j%(m-1)==0?"@":"-":i>=k+2?j%(m-1)==0?"|":j==m/2?i==k+2?"@":"|":" ":" ";}s+="\n";}return s;} ``` Saved 21 Bytes thanks to @KevinCruijssen: ``` static String r(String[]p){String s="";int l[]=new int[3],m=0,i,j,a,k,t;for(String x:p)l[m++]=x.length();m=Math.max(l[0],Math.max(l[1],l[2]))+2;m+=m%2<1?1:m==3?2:0;for(i=0;i<7;i++,s+="\n")for(a=1;a<4;a=a==1?0:a+2)for(j=0,k=2*a,t=(m-l[a])/2;j<m;j++)s+=i==k?j>=t&j<t+l[a]?p[a].charAt(j-t):" ":i==k+1?j%~-m<1?"@":"-":i>=k+2?j%~-m<1?"|":j==m/2?i==k+2?"@":"|":" ":" ";return s;} ``` As @KevinCruijssen suggested, one could also use `var` instead of `String` in Java 10+ and save some extra Bytes. I don't do this for the simple reason that I don't have Java 10 yet :D also, lambdas could be used. But this would only reduce the amount of bytes if we would leave out assigning it to a `Function<String[],String>` variable. In expanded form: ``` static String r(String[]p){ String s=""; //The string that will be returned int l[]=new int[3], //An array containing the lengths of our three names m=0, //tmp variable for filling l i,j,a,k,t; //some declarations to save a few bytes lateron for(String x:p) l[m++]=x.length(); m=Math.max(l[0],Math.max(l[1],l[2]))+2; m+=m%2<1? //ensure odd length of the podests 1 :m==3?2:0; //ensure the length is at least 3 (in my code, m is the length of the podests + 2) for(i=0;i<7;i++,s+="\n") //iterate by row for(a=1;a<4;a=a==1?0:a+2) //iterate by place: a=1,0,2 for(j=0,k=2*a,t=(m-l[a])/2;j<m;j++) //iterate by column //k is the row number from top in which the a-th name goes //t is the column at which the name starts //now, append the right char: s+=i==k? //write the name j>=t&j<t+l[a]? p[a].charAt(j-t) :" " :i==k+1? //write the top of the podest ("@---@") j%~-m<1? "@" :"-" :i>=k+2? //write the bottom of the podest ("| |@ |") j%~-m<1? //the left and right edge of the podest "|" :j==m/2? //the center of the podest i==k+2? //are we at the first row of the bottom? "@" //the case where we have to write "| @ |" :"|" //the case "| | |" :" " :" " ; return s; } ``` The input has to be given as `String`-array of length 3. An example looks like this: ``` public static void main(String[] args){ System.out.print(r(new String[]{"Anthony", "Bertram", "Carlos"})); } ``` Output: ``` Anthony @-------@ Bertram | @ | @-------@| | | | @ || | | Carlos | | || | |@-------@ | | || | || @ | ``` [Answer] # C(GCC) ~~302~~ ~~293~~ ~~292~~ ~~289~~ 287 bytes -6 byte thanks to ceilingcat ``` #define P(h,n)r=w+2-L[n];i/h?printf("%*s%*s%*s",-~r/2,D,L[n],i>h?D:N[n],r/2,D):printf(~i/h?"@%s@":"|%*s%c%*s|",~i/h?D+1:w/2,D,i>h-3?64:'|',w/2,D); f(int**N){char L[3],w=3,i=3,r,D[99]={};for(;i--;)w=w<(L[i]=strlen(N[i]))?L[i]|1:w;memset(D+1,45,w);for(i=7;i--;puts(D)){P(4,1)P(6,0)P(2,2)}} ``` [Run it here](https://tio.run/##LU/BboMwDL33K6JMVWNq1JV2nUqW0UkcK1RpuyEOFQsj0kirQMUB6K@zhE5ybOvZ7/kl93/yfByfvmWhtCQnVqIGI9pl4B9TnXG1KqOrUbopGJ179SMo@nezCjBGt4PqvYziMHHthEL4z7g7Nj3M6wMNae@4uU09xWkQL9dhO6lYAX8T7bbhol/gBAGfFcxqeF4CXV6eDTmmmwxbsUFln8E43e8z0Q28uBjGle9zaEX7xo6pykTdmF@pWWJ7gMhBvT3FK1nVsmH2Lm5fsIWJq8TrRL/emprFAN2JbXENJ7bDZ5sDDGAYRmuFVGelGcy6GSHOkUcSa4kI0tGvS0WR0A@tpaufN0kHwu1ewRL7k2H8Aw) Ungolfed and explained (technically you can't have comments after back slashes in macros, so this won't run) ``` #define P(h,n)\ r=w+2-L[n];\ //get leftover width i/h?\ //if i >= h printf("%*s%*s%*s",-~r/2,D,L[n],i>h?D:N[n],r/2,D):\//if too high print all spaces, otherwise center the name printf(~i/h?"@%s@":"|%*s%c%*s|",~i/h?D+1:w/2,D,i>h-3?64:'|',w/2,D); //if (i == h - 1) print top row using D calculated if row right below top, else print '@'(64) in center, otherwise '|' f(int**N){ char L[3],//lengths of each string w=3,//width (init to minimum) i=3,//index, used in for loops l,//left padding r,//right padding D[99]={};//string of '-' of correct length (max 99) but first char is null for empty string for(;i--;)//i was set to 3 before, i will be {2,1,0} w=w<(L[i]=strlen(N[i]))?//set length to str len and compare to longest width so far L[i]|1://set it to length if longer, but make sure it is odd w;//do not replace memset(D+1,45,w); //set the first w bits of D to '-', leaves a null terminator for(i=7;i--;puts(D)){//i will be {6...0} P(4,1)//print second place, 4 high P(6,0)//print first place, 6 high P(2,2)//print thrid place, 2 high } } ``` Here is the calling code ``` int main() { char* N[3] = {"Tom", "Anne", "Sue"} ; f(N); } ``` and output ``` Tom @-----@ Anne | @ | @-----@| | | | @ || | | Sue | | || | |@-----@ | | || | || @ | ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) for Windows, ~~231~~ 223 bytes ``` param($a)$w=($a|% le*|sort)[-1] if(3-gt$w){$w=3}$w+=1-$w%2 0..6|%{$r=$_ -join($a|%{$m=' -'[5-eq($o=$r+2*(++$i%3))] $e=' @|||||'[$o] $x=(,''*4+$_,'','@'+,'|'*4)[$o] "$e$($x|% *ft(($x.Length+$w)/2-.1)$m|% *ht $w $m)$e"})} ``` [Try it online!](https://tio.run/##nVVrj5pAFP3Or7gh1w4I2Kptv5Ggdtttu33uttvWbDakOz4aHhYxmDj@dnsZUJGFXeskCJ5z7uGeYTIzCxMezSfc8zY4AhtWm5kbub6Gro6JTTfRAI83xTyMYn1otW@U6UjrWuMYE31Fiu4aE8NuW5g0OsqzVuulaKwwsvFWsf6E00AarNC3GVhs@MLifzUMbYyMTlMzDJw2urp@oyAnPh2OSAcbYkjg0tZMxprPDbylu8kcZphMEKBLXkWOGi6pv@Yo1uipdcGDcTwxqLOnHavV1tFPyUkMmAD6OnJ1ra83a0VxNEUxNUW@UWO9ICD3q9Cn38sFZ7opmawjIDx7YEXYsSzLOYTJBgQ4dBVhKRQgSrAUZjC9sgCLHJZ192FZxxS91D9/IEAxQzlGFmQb5TAMh7RnB/LODyPJUCDuk3nJjkzTFUmxJ3OfajL3KUXtR@4dhbyeet7UTeOeLcY8qEgMuQTqcm@T77MXJel7IAvnwD5keQ6yWQBRKdkV7yVZt4cScSDZ@dZLdr7luRnQfPToenX2@s3523fvLz58/PT5y9fLq2/fr3/8/FUxSQ@M3lEq9pjlNk95OP9j2R8UBaJoX4NXW9Y2I2psHresbabesubzVFqKoyxrc51uWZurvOjyNTcor64eHLdrQh9O2jVhAKfsmjr9bcBKCjBwfT43kS9n/HfM7@j0o2NLMhGfL7yYgCd0KGY6Sag5o9JBpu4K1WKRst78Aw "PowerShell โ€“ Try It Online") Input is array `@('second','first','third')`. Unrolled version: ``` param($arr) $width=($arr|% length|sort)[-1] if(3-gt$width){$width=3} $width+=1-$width%2 0..6|%{ $row=$_ # 7 rows -join($arr|%{ # 3 joined columns. Each column array contains 11 lines. $offset = $row+2*(++$i%3) # (2,4,0) -> offset in column array # 0: $middle = ' -'[5-eq$offset] # 1: $edge = ' @|||||'[$offset] # 2: $center = ('','','','',$_,'','@','|','|','|','|')[$offset] # 3: # 4: name # pad $x to a center # 5: @---@ $center = $center|% PadLeft (($center.Length+$width)/2-.1) $middle # 6: | @ | $center = $center|% PadRight $width $middle # 7: | | | # 8: | | | # add the $edge # 9: | | | "$edge$center$edge" # 10: | | | }) } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 43 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ยฟโŒcFโ—„ร รซ+ยฑโˆšยผโˆ™]โ•”5B\dโ˜บโ†จmโ–ˆewฯ„โ”€ยบโ•žโ•รณโ—‹โ™ฃzG-โ–ˆKโ†จร„Vโ”ยงx ``` [Run and debug it](https://staxlang.xyz/#p=a8a963461185892bf1fbacf95dc935425c6401176ddb6577e7c4a7c6cda209057a472ddb4b178e56bf1578&i=[%22Tom%22,+%22Anne%22,+%22Sue%22]%0A[%22William%22,+%22Brad%22,+%22Eugene%22]%0A[%22A%22,+%22BC%22,+%22DEFGHIJKLMNOPQRSTUVWXYZ%22]%0A[%22A%22,+%22B%22,+%22C%22]&a=1&m=2) ]
[Question] [ In **[pancake sorting](http://en.wikipedia.org/wiki/Pancake_sorting)** the only allowed operation is to reverse the elements of some prefix of the sequence. Or, think of a stack of pancakes: We insert a spatula somewhere in the stack and flip all the pancakes above the spatula. For example, the sequence `6 5 4 1 2 3` can be sorted by first flipping the first `6` elements (the whole sequence), yielding the intermediate result `3 2 1 4 5 6`, and then flipping the first `3` elements, arriving at `1 2 3 4 5 6`. As there is only one operation, the whole sorting process can be described by a sequence of integers, where each integer is the number of elements/pancakes to include pr flip. For the example above, the *sorting sequence* would be `6 3`. Another example: `4 2 3 1` can be sorted with `4 2 3 2`. Here's the intermediate results: ``` 4 2 3 1 flip 4: 1 3 2 4 flip 2: 3 1 2 4 flip 3: 2 1 3 4 flip 2: 1 2 3 4 ``` # The task: Write a program which takes a list of integers and prints a valid pancake sorting sequence. The list to sort can either be a space separated list from stdin, or command line arguments. Print the list however it is convenient, as long as it's somewhat readable. This is codegolf! ### Edit: As I said in the comments, **you don't need to optimize the output** (finding the shortest sequence [is NP-hard](http://bit.ly/uvtNe4)). *However*, I just realized that a cheap solution would be to throw out random numbers until you get the desired result (a [new?] type of bogosort). None of the answers so far have done this, so I now declare that **your algorithm should not rely on any (pseudo-)randomness**. While you're all kicking yourselves, here's a bogopancakesort variant in Ruby 2.0 (60 characters), to rub it in: ``` a=$*.map &:to_i a=a[0,p(v=rand(a.size)+1)].reverse+a[v..-1]while a!=a.sort ``` [Answer] ## Python, 91 90 chars ``` L=map(int,raw_input().split()) while L:i=L.index(max(L));print-~i,len(L),;L=L[:i:-1]+L[:i] ``` Flip the biggest pancake to the top, then flip the whole stack. Remove the biggest pancake from the bottom and repeat. `i` is the index of the biggest pancake. `L=L[:i:-1]+L[:i]` flips `i+1` pancakes, flips `len(L)` pancakes, then drops the last pancake. [Answer] ## GolfScript, 34 / 21 chars (Thanks @PeterTaylor for chopping 4 chars off) ``` ~].{,,{1$=}$\}2*${.2$?.p)p.@\-+}/, ``` [Online test](http://golfscript.apphb.com/?c=OyIyIDEgMSIKfl0ueywsezEkPX0kXH0yKiR7LjIkPy5wKXAuQFwtK30vLA%3D%3D) A shorter, 21 character version works for lists with unique items only ``` ~].${.2$?.p)p.@\-+}/, ``` [Online test](http://golfscript.apphb.com/?c=OyI0IDIgMyAxIgp%2BXS4key4yJD8ucClwLkBcLSt9Lyw%3D) Both versions produce sub-optimal solutions. --- Explanation for the shorter solution: ``` ~] # read input from stdin .$ # produce a sorted copy from lowest to highest { # iterate over the sorted list .2$? # grab the index of the element .p # print the index )p # increment and print the index .@\-+ # move the element to the front }/ , # leave the length of the list on the stack # this flips the reverse sorted list to become sorted ``` This uses a different algorithm to most of the others posted. Basically it grabs the smallest element of the list, and with two flips moves it to the front, preserving the other elements' order. To move the nth element to the front: ``` 1 2 3 4 5 6 7 # let's move the 3rd (0-based) element to the front # flip the first 3 elements 3 2 1 4 5 6 7 # flip the first 3+1 elements 4 1 2 3 5 6 7 ``` It repeats this operation for each element in order, and ends up with a reverse sorted list. It then flips the whole list to leave it fully sorted. --- In fact the algorithm is a variation of a 90-char Python solution (my own, of course): ``` d=map(int,raw_input().split());i=0 while d:n=d.index(max(d));d.pop(n);print n+i,n-~i,;i+=1 ``` [Answer] ## Ruby 1.9 - 109 88 79 characters Much more compact version based on Keith's great python solution: ``` a=$*.map &:to_i;$*.map{p v=a.index(a.max)+1,a.size;a=a[v..-1].reverse+a[0,v-1]} ``` Original version: ``` a=$*.map &:to_i a.size.downto(2){|l|[n=a.index(a[0,l].max)+1,l].map{|v|v>1&&n<l&&p(v);a[0,v]=a[0,v].reverse}} ``` If you don't care about spurious operations (reversing stacks of size 1, or reversing the same stack twice in a row) you can make it a bit shorter (96 chars): ``` a=$*.map &:to_i a.size.downto(2){|l|[a.index(a[0,l].max)+1,l].map{|v|p v;a[0,v]=a[0,v].reverse}} ``` Takes the unsorted list as command-line args. Example usage: ``` >pc.rb 4 2 3 1 4 2 3 2 ``` [Answer] ### GolfScript, 31 29 characters ``` ~].${1$?).p.2$.,p>-1%\@<+)}%, ``` Another GolfScript solution, can also be tested [online](http://golfscript.apphb.com/?c=OyIzIDQgMSAyIgoKfl0uJHsxJD8pLnAuMiQuLHA%2BLTElXEA8Kyl9JSw%3D&run=true). Previous version: ``` ~].$-1%{1$?).2$>-1%@2$<+.,\);}/ ``` How does it work: it flips the largest item to the top and then to the last place in the list. Since it is now in the correct position we can remove it from the list. ``` ~] # Convert STDIN (space separated numbers) to array .$-1% # Make a sorted copy (largest to smallest) { # Iterate over this copy 1$?) # Get index of item (i.e. largest item) in the remaining list, # due to ) the index starts with one . # copy (i.e. index stays there for output) 2$> # take the rest of the list... -1% # ... and reverse it @2$< # then take the beginning of the list + # and join both. # Note: these operations do both flips together, i.e. # flip the largest item to front and then reverse the complete stack ., # Take the length of the list for output \); # Remove last item from list }/ ``` [Answer] ## Perl, ~~103~~ 100 characters Expects input on the command line. ``` for(@n=sort{$ARGV[$a]<=>$ARGV[$b]}0..$#ARGV;@n;say$i+1,$/,@n+1) {$i=pop@n;$_=@n-$_-($_<=$i&&$i)for@n} ``` The solutions it prints are decidedly sub-optimal. (I had a program with much nicer output about 24 characters ago....) The logic is kind of interesting. It starts by cataloguing the index of each item, were it in sorted order. It then iterates through this catalog from right to left. So applying a flip involves adjusting indexes below the cutoff value, instead of actually moving values around. After some finagling I also managed to save a few characters by doing both flips per iteration simultaneously. [Answer] ## Python 2 (254) Simple BFS-search, some stuff is inlined, probably could be compressed more without changing the search style. Hopefully this shows maybe how to start golfing a bit (too much to be in a simple comment). Use: ``` python script.py 4 2 3 1 ``` (2 spaces = tab) ``` import sys t=tuple i=t(map(int,sys.argv[1:])) g=t(range(1,len(i)+1)) q=[i] p={} l={} while q: c=q.pop(0) for m in g: n=c[:m][::-1]+c[m:] if n==g: s=[m] while c!=i:s+=[l[c]];c=p[c] print s[::-1] sys.exit() elif n not in p:q+=[n];p[n]=c;l[n]=m ``` [Answer] **Python2: 120** ``` L=map(int,raw_input().split()) u=len(L) while u:i=L.index(max(L[:u]))+1;L[:i]=L[i-1::-1];L[:u]=L[u-1::-1];print i,u;u-=1 ``` It's not efficient: it wont find the best sorting sequence, and the given sequence can even contain no-ops(i.e. flipping only the first element), nevertheless the output is valid. The output is given in the form: ``` n_1 n_2 n_3 n_4 n_5 n_6 ... ``` Which should be read as the sequence of flips: `n_1 n_2 n_3 n_4 n_5 n_6 ...`. If you want to obtain an output like: n\_1 n\_2 n\_3 n\_4 n\_5 n\_6 ... Simply add a comma in the `print` statement. [Answer] ## Python - 282 characters ``` import sys s=sys.argv[1] l=s.split() p=[] for c in l: p.append(int(c)) m=sys.maxint n=0 while(n==(len(p)-1)): i=x=g=0 for c in p: if c>g and c<m: g=c x=i i+=1 m=g x+=1 t=p[:x] b=p[x:] t=t[::-1] p=t+b a=len(p)-n; t=p[:a] b=p[a:] t=t[::-1] p=t+b print p n+=1 ``` My first ever code golf; I'm under no illusions I'll *win*, but I had a lot of fun. Giving everything one-character names sure makes it frightening to read, let me tell you! This is run from the command line, sample implementation below: ``` Python PancakeSort.py "4 2 3 1" [1, 3, 2, 4] [2, 1, 3, 4] [1, 2, 3, 4] ``` There's nothing particularly special or inventive about the way I've gone about this, but the FAQ suggests posting a non-golfed version for interested readers, so I've done so below: ``` import sys pancakesStr = sys.argv[1] pancakesSplit = pancakesStr.split() pancakesAr = [] for pancake in pancakesSplit: pancakesAr.append(int(pancake)) smallestSorted = sys.maxint numSorts = 0 while(numSorts < (len(pancakesAr) - 1)): i = 0 biggestIndex = 0 biggest = 0 for pancake in pancakesAr: if ((pancake > biggest) and (pancake < smallestSorted)): biggest = pancake biggestIndex = i i += 1 smallestSorted = biggest #you've found the next biggest to sort; save it off. biggestIndex += 1 #we want the biggestIndex to be in the top list, so +1. top = pancakesAr[:biggestIndex] bottom = pancakesAr[biggestIndex:] top = top[::-1] #reverse top to move highest unsorted number to first position (flip 1) pancakesAr = top + bottom #reconstruct stack alreadySortedIndex = len(pancakesAr) - numSorts; top = pancakesAr[:alreadySortedIndex] bottom = pancakesAr[alreadySortedIndex:] top = top[::-1] #reverse new top to move highest unsorted number to the bottom position on the unsorted list (flip 2) pancakesAr = top + bottom #reconstruct list print pancakesAr #print after each flip numSorts += 1 print "Sort completed in " + str(numSorts) + " flips. Final stack: " print pancakesAr ``` The basic algorithm I used is the one mentioned in the [wiki article linked in the question](http://en.wikipedia.org/wiki/Pancake_sorting): > > The simplest pancake sorting algorithm requires at most 2nโˆ’3 flips. In this algorithm, a variation of selection sort, we bring the largest pancake not yet sorted to the top with one flip, and then take it down to its final position with one more, then repeat this for the remaining pancakes. > > > [Answer] # [Haskell](https://www.haskell.org/), ~~72~~ 71 bytes ``` h s|(a,x:b)<-span(<maximum s)s=map length[x:a,s]++h(reverse b++a) h e=e ``` [Try it online!](https://tio.run/##VY4xagMxEEV7neJjUkhILpJ0i/cUKY2LMau1hEdaodGGLXz3jQIG42Zg3n/D/EBy98z7HiAPTW4bruZ0lEJZnxJtMa0JYmRMVMA@31o4bwM5uVgbdPW/vorH1VoyKsCPfheMOH@6L/ft@rwoNfNSIMidP33d6O47EANrMdWe90Uliv/StCiUtf20isPMsciAQyc15oYP9JqvuHpZucV8A0dpb9688MR4/tb9yux/ "Haskell โ€“ Try It Online") Finds the maximum, flips it to the back and recursively sorts the remaining list. *Edit: -1 byte thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo)* [Answer] # Perl 5.10 (or higher), 66 bytes Includes `+3` for `-n` The `use 5.10.0` to bring the language to level perl 5.10 is considered free ``` #!/usr/bin/perl -n use 5.10.0; $'>=$&or$.=s/(\S+) \G(\S+)/$2 $1/*say"$. 2 $."while$.++,/\S+ /g ``` Run with the input as one line on STDIN: ``` flop.pl <<< "1 8 3 -5 6" ``` Sorts the list by repeatedly finding any inversion, flipping it to the front then flipping the inversion and flipping everything back to its old position. And that is equivalent to swapping the inversion so I don't need to reverse (which is awkward on strings since it would reverse the digits of the values converting e.g. `12` to `21`) [Answer] **C# - 229** ``` using System;using System.Linq;class P{static void Main(string[] a){ var n=a.ToList();Action<int>d=z=>{Console.Write(z+" ");n.Reverse(0,z);}; int c=n.Count;foreach(var s in n.OrderBy(x=>0-int.Parse(x))){ d(n.IndexOf(s)+1);d(c--);}}} ``` readable version ``` using System; using System.Linq; class P { static void Main(string[] a) { var n = a.ToList(); Action<int> d = z => { Console.Write(z + " "); n.Reverse(0, z); }; int c = n.Count; foreach (var s in n.OrderBy(x => 0 - int.Parse(x))) { d(n.IndexOf(s) + 1); d(c--); } } } ``` ]
[Question] [ The totient function \$\phi(n)\$, also called Euler's totient function, is defined as the number of positive integers \$\le n\$ that are relatively prime to (i.e., do not contain any factor in common with) \$n\$, where \$1\$ is counted as being relatively prime to all numbers. (from [WolframMathworld](http://mathworld.wolfram.com/TotientFunction.html)) ## Challenge Given an integer \$N > 1\$, output the lowest integer \$M > N\$, where \$\phi(N) = \phi(M)\$. If \$M\$ does not exist, output a non-ambiguous non-positive-integer value to indicate that M does not exist (e.g. 0, -1, some string). Note that \$\phi(n) \geq \sqrt n\$ for all \$n > 6\$ ## Examples ``` Where M exists 15 -> 16 (8) 61 -> 77 (60) 465 -> 482 (240) 945 -> 962 (432) No M exists 12 (4) 42 (12) 62 (30) ``` Standard loopholes apply, shortest answer in bytes wins. [Related](https://codegolf.stackexchange.com/q/83533/90146) [Answer] # JavaScript (ES6), ~~83 ... 76~~ 74 bytes Returns `true` if \$M\$ does not exist. Derived from [this answer](https://codegolf.stackexchange.com/a/83636/58563) by xnor. ``` f=(n,q,P=(n,d=n)=>p=--d&&P(n,d)+1-P(n%d?1:d))=>P(n)^q?p>q*q||f(n+1,q||p):n ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6dQJwBEpdjmadraFdjq6qaoqQWABDS1DXWBDNUUe0OrFE2gJJCjGVdoX2BXqFVYU5OmkadtqANkFGha5f1Pzs8rzs9J1cvJT9dQj/ZVSK3ILC4pjlXXtOZClkrTMDTV1EQTMjPEEDIxw1RmaQISQxFUj8mLzstXwGedEabZmEJmQKH/AA "JavaScript (Node.js) โ€“ Try It Online") ## How? ### Computing \$\phi(n)\$ This is based on the formula: $$\sum\_{d|n}\phi(d)=n$$ which implies: $$\phi(n)=n-\sum\_{d|n,d<n}\phi(d)$$ But in the JS implementation, we actually compute: $$\begin{align}P(n)&=\sum\_{d=1}^{n-1}1-\delta\_{d|n}P(d)\\ &=n-1-\sum\_{d|n,d<n}P(d)\end{align}$$ It leads to the same results, except \$P(1)=0\$ instead of \$\phi(1)=1\$. This is fine because we don't need to support \$n=1\$, as per the challenge rules. And this allows us to do the following recursive call: ``` P(n % d ? 1 : d) ``` which evaluates to \$0\$ if \$d\$ is not a divisor of \$n\$. ### Wrapper code At each iteration, we compute \$p=P(n)\$. The result of the first iteration is saved into \$q\$. We then increment \$n\$ until \$p=q\$ (success) or \$p>q^2\$ (failure). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` rยฒร†แนชแบนแธข$+โธแธข ``` A monadic Link accepting a positive integer which yields a non-negative integer (`0` if no \$M\$ exists). **[Try it online!](https://tio.run/##y0rNyan8/7/o0KbDbQ93rnq4a@fDHYtUtB817gDS////NzMEAA "Jelly โ€“ Try It Online")** ### How? ``` rยฒร†แนชแบนแธข$+โธแธข - Link: integer, n ยฒ - (n) squared r - (n) inclusive range (nยฒ) ร†แนช - Euler totient (vectorises) $ - last two links as a monad: แธข - head - i.e. yield totient(n) and leave [totient(n+1),...,totient(nยฒ)] แบน - indices of (i.e. a list of offsets to higher Ms) โธ - chain's left argument (n) + - add (vectorises) (i.e. a list of higher Ms) แธข - head (note head-ing an empty list yields zero) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~57~~ 52 bytes *-5 bytes using the `.&` operator thanks to Jo King* ``` {first *.&($!={grep 1,($_ Xgcd^$_)})==.$!,$_^..$_ยฒ} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi2zqLhEQUtPTUNF0bY6vSi1QMFQR0MlXiEiPTklTiVes1bT1lZPRVFHJT5OT08l/tCm2v/FiZUKaUA1mgpp@UUKhqY6CmaGOgomZkCGpQmQMDQC8oDYzOg/AA "Perl 6 โ€“ Try It Online") Returns `Nil` if no solution was found. ### Explanation ``` { } # Anonymous block $_ Xgcd^$_ # gcds of m and 0..m-1 grep 1, # Filter 1s { } # Totient function ($!= ) # Assign to $! first ,$_^..$_ยฒ # First item of n+1..nยฒ where *.& ==.$! # ฯ•(m) == ฯ•(n) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes ``` rยฒร†แนช=โ‚ฌแธข$T+โธแธข ``` [Try it online!](https://tio.run/##y0rNyan8/7/o0KbDbQ93rrJ91LTm4Y5FKiHajxp3ABn/rR81zFHQtVN41DDX@nA71@F2oILI//8tdAyNdAxNdUyMdMwMdcyMAA "Jelly โ€“ Try It Online") A monadic link taking an integer and returning the next integer with shared totient or zero. ## Explanation ### Main link (takes integer argument z) ``` rยฒ | Range from z to z ** 2 inclusive ร†แนช | Totient function of each $ | Following as a monad =โ‚ฌแธข | - Check whether each equal to the first, popping the first before doing so T | Truthy indices +โธ | Plus z แธข | - Head (returns 0 if the previous link yielded an empty list) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~10~~ ~~9~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L+.ฮ”โ€šร•ร‹ ``` -1 byte with help from *@ExpiredData*. -2 bytes thanks to *@Grimmy*. Outputs `-1` if no \$m\$ exists. [Try it online](https://tio.run/##yy9OTMpM/f/fR1vv3JRHDbMOTz3c/f@/mSEA) or [verify all test cases](https://tio.run/##AUIAvf9vc2FiaWX/dnk/IiDihpIgIj95wqnDkP9MKy7OlMKu4oCaw5XDi/99LP9bMTUsNjEsNDU2LDk0NSwxMiw0Miw2Ml0). **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer n] + # Add the (implicit) input-integer n to each to make the range [n+1, 2n] .ฮ” # Get the first value of this list which is truthy for # (or results in -1 if none are truthy): โ€š # Pair the current value with the (implicit) input-integer n ร• # Get the Euler's totient of both ร‹ # Check whether both are equal to each other # (after which the result is output implicitly) ``` Most answers use \$n^2\$ as the range to check in, but this answer uses \$2n\$ instead to save a byte. If we look at the [Mathematica implementation on the oeis sequence A066659](https://oeis.org/A066659) we can see it also uses the range \$[n+1, 2n+1)\$ to check in. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 11 bytes ``` :sUtยฆแน‡=โˆ†:+ยฟ ``` [Try it online!](https://tio.run/##S0/MTPz/36o4tOTQsoc7220fdbRZaR/a//8/AA "Gaia โ€“ Try It Online") ``` :s | push n,n^2 U | push range [n, n + 1, ..., n^2] tยฆ | calculate [phi(n),phi(n+1), ..., phi(n^2)] แน‡ | push [phi(n+1), phi(n+2), ..., phi(n^2)], phi(n) =โˆ† | find 1-based index of first in the list equal to phi(n), returning 0 if none : | dup the index +ยฟ | if the index is falsey, do nothing (leaving 0 on the stack) | otherwise add (implicitly) n | and implicitly print top of stack ``` [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` lambda N:next((j for j in range(N+1,max(6,t(N)**2))if t(j)==t(N)),0) t=lambda n:sum(k/n*k%n>n-2for k in range(n*n)) ``` [Try it online!](https://tio.run/##jc7BCoJAEIDhc/sUcxFnbKVcVEiwR9gXqA4buqXmFLpCPr1lCNGtyxyGn2/mMbrrndVk8@N0M@25MKAzLp8OsQZ776CGiqEzfClRryPZmiem0qGmIFBElQWHNeX5vCG5JeHyheGsH1psNhw0Hu85VLPWfDUOmGh6dBU78F03uOvoi7nRc3OIEplGMk4TuYuTUyZWS@kVEO7hPdEryPdQS/s@/fmIhFgia259@cspGas/mekF "Python 2 โ€“ Try It Online") Returns `0` for falsey. The totient function `t` is based on [Dennis's answer](https://codegolf.stackexchange.com/a/145316/69880) to a previous question. Times out on TIO for `N=62`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~70~~ 68 bytes ``` ->n{(n+1..n*n).find{|m|g=->g{(1..g).sum{|h|1/h.gcd(g)}};g[m]==g[n]}} ``` [Try it online!](https://tio.run/##bcrBCsIgHIDx@55it2mpoTghwr2IeKiG/3VQpCUY6rPbHqDv@ON7p8e3O93pEgoKZ85YOAXM3CuspfoKmi5Q0MGA2Z58qVvll43Bc0WAW7uB8VZrMMG21g2fieJEqplc5WyZv8dSc42jycSZbG0bYvrs40SPpsFwQaQgSvw7@w8 "Ruby โ€“ Try It Online") Returns `nil` if not found. [Answer] # [Python 3](https://docs.python.org/3/), ~~160~~ 121 bytes Saved 39 bytes thanks to @JoKing! Returns `None` if no \$M\$ exists: ``` import math t=lambda n:sum(math.gcd(i,n)<2for i in range(n)) def s(x): n=x while n<x*x: n+=1 if t(n)==t(x):return n ``` [Try it online!](https://tio.run/##PU7LCoMwELznK5aektYKsVaomP5LWqMGzCox0hTx29P10oV9DTPDzN8wTHhLybp58gGcDgMLatTu1WrAelkdP7C8f7fcZiiaops8WLAIXmNvOArBWtPBwqOoGaCKDD6DHQ1gE8@RIMCLkrRsB4HoSoWD6k1YPQKmvx@X9wwqmUFZ0fEoaciCPuqqOLypZm8x8NO2w/UJ237KSU35KBoFsEKI9AM "Python 3 โ€“ Try It Online") If throwing an exception is allowed when no \$M\$ exists: # [Python 3](https://docs.python.org/3/), ~~145~~ 114 bytes Saved 31 bytes thanks to @JoKing! ``` lambda n:[t(i+1)for i in range(n,n*n)].index(t(n))-~n import math t=lambda n:sum(math.gcd(i,n)<2for i in range(n)) ``` [Try it online!](https://tio.run/##XYxBC4JQEITv/opFEHbrFWjlQapb/Ynq8MqXLuQq721Ql/66mQcPDQwDw8zXvbVuZdWH3bl/2OZaWpDipMjzlO6tBwYW8FYqh2JkJnRZspTuhYpCtPhIxE3XeoXGah3pbmKEZ4O/blndSmQjtM3@eUT9VGG6MZCnBtLMwHpwnlERwSD17wI6z6IYJwEWe0hCnAxICMhENI7c6@Y6hcMY3Mrf42gfwcUJU/8F "Python 3 โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` lambda x,n=1:[n>x*x,x+n][t(x+n)==t(x)]or s(x,n+1) t=lambda n:sum(k//n*k%n>n-2for k in range(n*n)) ``` [Try it online!](https://tio.run/##VcvRCoIwFAbge59iEMGmlsxMUJgvYl5YWQ3dmWwT5tOvc1FhBw4/H@c/8@peGk5BqlkbR@xqI9yjHZwZbouxUsMklXS0wmGRFZcw9ep674lPQfC6hcbHPvUJdK2jGEwITNZpQyzFTsJZ5MTnB2q7KDpmGcTjHho45A/sjUQCMT08BwoxMBZmI8FRS/mZseiLkm9QlNtTVWzFc8Tu1/xTiQpv "Python 3 โ€“ Try It Online") Totient function taken from [Chas Brown's answer](https://codegolf.stackexchange.com/a/196653/76162), originally from [Dennis](https://codegolf.stackexchange.com/a/145316/69880).Returns `True` for cases where `M` doesn't exist, though if that doesn't satisfy you, a far less efficient version that returns `False` is only [two bytes longer](https://tio.run/##VYvhCoIwFIX/@xSDCDa1ZGaC0noR88dKq6G7k23CfPq1oCIvHA7fOfdMi30qOHghJ6UtMouJgvamt7q/zdoIBaOQwuIqHIkMu/iRy2vHkUuB0bqBk4sd4tAhg0OUUJK6BNrG4mCEseCkjSz7rKA2s8RDlkE8bOEMu/yuNBqQAKQ5PHoMMRDiJy3AYoPpkZBo86WS/lNRrsqqeONvmK9eV1QG8i8). [Answer] # [J](http://jsoftware.com/), ~~42~~ 31 bytes ``` (1{]) ::0[([+[:I.{=}.)5 p:i.@*: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQyrYzUVrKwMojWitaOtPPWqbWv1NE0VCqwy9Ry0rP5rcnH5OekphGekFqUq@CqkVmQWlxQrcKUmZ@QraFinaarZKRiaKpgZKpiYmSpYmphClPvlw9WiKjVSMDFSMDP6DwA "J โ€“ Try It Online") Returns `0` if no \$M\$ exists. ## Explanation : (of the previous version) The argument is `n` ``` @*: find n^2 and i. make a list 0..n^2-1 + to each number in the list add ] the argument (n) -> list n..n^2+n-1 5 p: find the totient of each number in the above list @( ) use the above result as an argument for ( ) the next verb = compare {. the head of the list ] with each number in the list [:I. get the indices where the above is true ( ) ::0 try the verb in parentheses and return 0 if it failed 1{] get the second (0-based indexing) element + and add n to it ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~21~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` รดU ร…รฆรˆo รจjX ยฅUo รจjU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9FUgxebIbyDoalggpVVvIOhqVQ&input=WzE1LDYxLDQ2NSw5NDUsMTIsNDIsNjJdClsxNiw3Nyw0ODIsOTYyLG4sbixuXQotbQotUQ) ``` รดU range [input ...input + input] ร… cut off first element รฆรˆ return the first element to return a truty value when passed to: o range [0... next element] รจ number of elements that are.. jX coprime to next element. ยฅ equal to Uo รจjU num of coprimes of input ``` Outputs `null` if no \$m\$ exists. Thanks to @Shaggy for reminding me of รด() which gives the range needed ]
[Question] [ I've been scrolling around this site for a while, but just recently got really interested in actually trying out some of the challenges. I was intending to try my hand at some of the existing code-golf topics, but I didn't have Internet access for a while yesterday, and in the meantime, I thought up my own challenge. Your task is to create a program or function that takes an array of Floats `a` and an integer `n`, then sets each value in `a` to the average of the two beside it, `n` times. When repeatedly used with increasing values of `n`, this generates a wave-like motion: ![wave motion](https://www.dropbox.com/s/9n6kvqbko0i445v/WaveTest.gif?raw=1) **Specifics:** * If there happens to be only one item in `a`, or if `n` is 0 or less, the program should return the original array. * Inputs and outputs can be in any format you desire, as long as they are visibly separated. **For each step:** * The first item in `a` should become the average of itself and the next item. * The last item in `a` should become the average of itself and the previous item. * Any other item in `a` should become the average of the previous item and the next item. * Make sure you are calculating off the previous step's array and not the current one! Test cases: **NOTE: Your inputs/outputs do not have to be in this format!** ``` [0, 0, 1, 0, 0], 1 -> [0, 0.5, 0, 0.5, 0] [0, 0, 1, 0, 0], 2 -> [0.25, 0, 0.5, 0, 0.25] [0, 0, 1, 0, 0], 0 -> [0, 0, 1, 0, 0] [0, 0, 1, 0, 0], -39 -> [0, 0, 1, 0, 0] [0, 16, 32, 16, 0], 1 -> [8, 16, 16, 16, 8] [0, 1, 2, 3, 4, 5], 1 -> [0.5, 1, 2, 3, 4, 4.5] [0, 64], 1 -> [32, 32] [0], 482 -> [0] [32, 32, 32, 16, 64, 16, 32, 32, 32], 4 -> [33, 27, 40, 22, 44, 22, 40, 27, 33] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. The winner will be chosen in one week (on August 1). Good luck! **Edit:** Congrats to the winner, [@issacg](https://codegolf.stackexchange.com/a/53801/42545), with a whopping **18 bytes!** [Answer] # Pyth, ~~46~~ 18 bytes ``` ucR2sV+hGGt+GeG.*Q ``` This code expects input in the form `iterations, [wave1, wave2, wave3 ...]`, as seen at the first link below. [Demonstration.](https://pyth.herokuapp.com/?code=ucR2sV%2BhGGt%2BGeG.*Q&input=4%2C+%5B32%2C+32%2C+32%2C+16%2C+64%2C+16%2C+32%2C+32%2C+32%5D&debug=0) [Test Harness.](https://pyth.herokuapp.com/?code=FQ%2B%5DQ.QucR2sV%2BhGGt%2BGeG.*Q&input=1%2C+%5B0%2C+0%2C+1%2C+0%2C+0%5D%0A2%2C+%5B0%2C+0%2C+1%2C+0%2C+0%5D%0A0%2C+%5B0%2C+0%2C+1%2C+0%2C+0%5D%0A-39%2C+%5B0%2C+0%2C+1%2C+0%2C+0%5D%0A1%2C+%5B0%2C+16%2C+32%2C+16%2C+0%5D%0A1%2C+%5B0%2C+1%2C+2%2C+3%2C+4%2C+5%5D%0A1%2C+%5B0%2C+64%5D%0A482%2C+%5B0%5D%0A4%2C+%5B32%2C+32%2C+32%2C+16%2C+64%2C+16%2C+32%2C+32%2C+32%5D&debug=0) The program works by applying the code within the reduce (`u`) function to the input list, as many times as the number of iterations. I will demonstrate the wave propagation function on the list `[0, 1, 2, 3, 4, 5]`, which is in `G`: `+hGG` prepends `G`'s first element to `G`, forming `[0, 0, 1, 2, 3, 4, 5]`. `t+GeG` appends `G`'s last element to `G` and removes its first element, forming `[1, 2, 3, 4, 5, 5]`. `sV` first forms pairs from the lists, giving `[[0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 5]]` with the final element of the first list truncated away. Then, the pairs are summed via the `s` function, giving `[1, 2, 4, 6, 8, 9]`. `cR2` uses floating point division to divide all of the numbers by 2, giving the desired result, `[0.5, 1.0, 2.0, 3.0, 4.0, 4.5]`. [Answer] # [Snowman 1.0.0](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.0-beta), 219 chars ``` {vg" "aS:10sB;aM0aa,AAg**-:|al|'NdE'0nRal@(%}{->:1*?{0AaG;:?{;bI:dUNiNwR'NdEwRaC;aM(~:?{(()1wR]0wRaC*))#'wRaC|*#|(()#aLNdEdUNdEwR]wR]aCwR*))#aC;:0wRdUaCwR*?{#aC;#bI:*#0aA'|aa|'!*+'(()#1aA*))#|,aa|'*`nA2nD;aM|*0*;bR|tSsP ``` With linebreaks for "readability": ``` {vg" "aS:10sB;aM0aa,AAg**-:|al|'NdE'0nRal@(%}{->:1*?{0AaG;:?{;bI:dUNiNwR'NdEwRaC; aM(~:?{(()1wR]0wRaC*))#'wRaC|*#|(()#aLNdEdUNdEwR]wR]aCwR*))#aC;:0wRdUaCwR*?{#aC;# bI:*#0aA'|aa|'!*+'(()#1aA*))#|,aa|'*`nA2nD;aM|*0*;bR|tSsP ``` Ungolfed / unminified version: ``` {vg" "aS:10sB;aM // input space-separated list of numbers 0aa,AAg // get first element and array of all-but-first elements ** // discard original input and the 0 // execute the following (input[0]) times -: |al|'NdE'0nR // get range from (0..input.length-1] al@(%}{->:1*?{0AaG;:?{;bI // chop off first element if any :dUNiNwR'NdEwRaC;aM // map n -> [n-1 n+1] // if the input consisted of a single element, append [0 0] // otherwise prepend [0 1] and append [len-2 len-1] (~:?{(()1wR]0wRaC*))#'wRaC|*#|(()#aLNdEdUNdEwR]wR]aCwR*))#aC; :0wRdUaCwR*?{#aC;#bI // map indeces to avg(input[i1], input[i2]) :*#0aA'|aa|'!*+'(()#1aA*))#|,aa|'*`nA2nD;aM // replace old input, reset permavar |*0* ;bR |tSsP // output result ``` Sample I/O format: ``` llama@llama:...Code/snowman/ppcg53799waves$ snowman waves.snowman 4 32 32 32 16 64 16 32 32 32 [33 27 40 22 44 22 40 27 33] ``` [Answer] # Pyth - 25 24 bytes Uses enumerate, reduce to do iterations. ``` u.ecs@L++hGGeG,khhk2GvzQ ``` [Try it online here](http://pyth.herokuapp.com/?code=u.ecs%40L%2B%2BhGGeG%2Ckhhk2GvzQ&input=4%0A%5B32%2C+32%2C+32%2C+16%2C+64%2C+16%2C+32%2C+32%2C+32%5D&debug=1). [Answer] # Racket, ~~164~~ 145 bytes ``` (define(f a n)(if(< n 1)a(f(let([l(length a)][r list-ref])(for/list([i(in-range l)])(/(+(r a(max(- i 1)0))(r a(min(+ i 1)(- l 1))))2)))(- n 1)))) ``` ### Ungolfed ``` (define (f a n) (if (< n 1) a (f (let ([l (length a)] [r list-ref]) (for/list ([i (in-range l)]) (/ (+ (r a (max (- i 1) 0)) (r a (min (+ i 1) (- l 1)))) 2))) (- n 1)))) ``` Note, you may need the `#lang racket` line to run this. [Answer] # R, 109 bytes ``` function(x,n){l=length(x);t=if(l>2)c(.5,0,.5)else if(l==2)c(.5,.5)else 1;for(i in 1:n)x=filter(x,t,c=T);c(x)} ``` This creates an unnamed function that accepts a vector and an integer and returns a vector. The approach here is to treat the input as a univariate time series and apply a linear convolution filter. Ungolfed + explanation: ``` f <- function(x, n) { # Define filter coefficients t <- if (length(x) > 2) c(0.5, 0, 0.5) else if (length(x) == 2) c(0.5, 0.5) else 1 # Apply the filter n times for (i in 1:n) { # The circular option wraps the filter around the edges # of the series, otherwise the ends would be set to NA. x <- filter(x, t, circular = TRUE) } # Returned the modified input, stripped of the extraneous # properties that the filter function adds. c(x) } ``` Examples: ``` > f(c(32, 32, 32, 16, 64, 16, 32, 32, 32), 4) [1] 33 27 40 22 44 22 40 27 33 > f(0, 482) [1] 0 > f(c(0, 64), 1) [1] 32 32 ``` [Answer] # Haskell, 76 characters The trick is to add the first number to the beginning of the list and the last one to the end of the list instead of dealing with the boundary conditions. ``` f a@(x:s)=(/2)<$>zipWith(+)(x:a)(s++[last s]) f x=x a#n|n<1=a|n>0=f a#(n-1) ``` Tests: ``` ฮป: [0, 0, 1, 0, 0]#1 [0.0,0.5,0.0,0.5,0.0] ฮป: [0, 0, 1, 0, 0]#2 [0.25,0.0,0.5,0.0,0.25] ฮป: [0, 0, 1, 0, 0]#0 [0.0,0.0,1.0,0.0,0.0] ฮป: [0, 0, 1, 0, 0]#(-39) [0.0,0.0,1.0,0.0,0.0] ฮป: [0, 16, 32, 16, 0]#1 [8.0,16.0,16.0,16.0,8.0] ฮป: [0, 1, 2, 3, 4, 5]#1 [0.5,1.0,2.0,3.0,4.0,4.5] ฮป: [0, 64]#1 [32.0,32.0] ฮป: [0]#482 [0.0] ฮป: [32, 32, 32, 16, 64, 16, 32, 32, 32]#4 [33.0,27.0,40.0,22.0,44.0,22.0,40.0,27.0,33.0] ``` [Answer] # CJam, ~~23~~ 22 bytes ``` q~{_(@)@@+@@+.+.5f*}*` ``` [Try it online](http://cjam.aditsu.net/#code=q~%7B_(%40)%40%40%2B%40%40%2B.%2B.5f*%7D*%60&input=%5B32%2032%2032%2016%2064%2016%2032%2032%2032%5D%204) The input is in CJam list format, e.g. for the last example: ``` [32 32 32 16 64 16 32 32 32] 4 ``` The output is also a CJam list: ``` [33.0 27.0 40.0 22.0 44.0 22.0 40.0 27.0 33.0] ``` The basic approach is that in each step, the vector is shifted one position to the left and one position to the right. Each of the two vectors is padded with the first/last element, and then the average of the two vectors is calculated. Explanation: ``` q~ Get and interpret input. { Loop over repeat count. _ Copy list. ( Pop off left element. @ Get original list to top. ) Pop off right element. @@ Get first element and list with last element removed to top. + Concatenate. This gives right-shifted list with first element repeated. @@ Get list with first element removed and last element to top. + Concatenate. This gives left-shifted list with last element repeated. .+ Perform vector addition of two shifted lists. .5f* Multiply sum by 0.5 to give average. }* End loop over repeat count. ` Convert result array to string. ``` [Answer] **Java, 181 bytes** Here's the golfed version: ``` float[]g(float[]i,int n){float[]c=i.clone();int l=c.length,s=1;if(n>0&&l>1){c[0]=(i[0]+i[1])/2f;c[--l]=(i[l]+i[l-1])/2f;while(s<l)c[s]=(i[s-1]+i[++s])/2f;return g(c,n-1);}return i;} ``` Ungolfed: ``` float[] g(float[] i, int n) { float[] c = i.clone(); int l = c.length,s=1; if(n>0&&l>1) { c[0] = (i[0]+i[1])/2f; c[--l] = (i[l]+i[l-1])/2f; while(s<l) c[s] = (i[s-1] + i[++s]) / 2f; return g(c, n-1); } return i; } ``` I tried to shorten assignments and conditionals as much as possible with Java. Improvements are welcome, of course. [Answer] # JavaScript (ES6), ~~153~~ ~~132~~ 67 chars I come back to my first answer 6 months later and what do I do? Golf off 50%, that's what. ;) ``` s=(a,n)=>n<1?a:s(a.map((j,i)=>(a[i&&i-1]+a[a[i+1]+1?i+1:i])/2),n-1) ``` This version calls itself repeatedly until `n` is less than 1, decrementing `n` by 1 each time. A non-recursive solution (~~151~~ ~~130~~ 78 chars): ``` (a,n)=>n<1?a:eval("while(n--)a=a.map((j,i)=>(a[i&&i-1]+a[a[i+1]+1?i+1:i])/2)") ``` ## Ungolfed: (outdated) ### Recursive: ``` s = function (a, n) { if (n < 1) return a; b = []; l = a.length; x = y = 0; for(var i = 0; i < l; i++) { x = a[(i < 1) ? 0 : i-1]; y = a[(i > l-2) ? i : i+1]; b[i] = (x + y)/2; } if (n > 2) return b; return s(b,n-1); } ``` ### Non-recursive: ``` s = function (a, n) { if (n < 1) return a; b = []; l = a.length; x = y = 0; while(n-- > 0) { for(var i = 0; i < l; i++) { x = a[(i < 1) ? 0 : i-1]; y = a[(i > l-2) ? i : i+1]; b[i] = (x + y)/2; a = b.slice(0); // setting a to a copy of b, for copyright reasons } return b; } ``` [Answer] # Java, 203 bytes Trying my first put with Java. Improvement tips are welcome:) ``` double[]f(double[]a,int n){int j,s,i=0;s=a.length-1;if(n<1||s<1)return a;double b[]=a;for(;i++<n;a=b.clone()){b[0]=.5*(a[0]+a[1]);b[s]=.5*(a[s]+a[s-1]);for(j=1;j<s;++j)b[j]=.5*(a[j-1]+a[j+1]);}return b;} ``` Pretty printed: ``` double[] g(double[] a, int n) { int j, s, i = 0; s = a.length - 1; if (n < 1 || s < 1) return a; double b[] = a; for (; i++ < n; a = b.clone()) { b[0] = .5 * (a[0] + a[1]); b[s] = .5 * (a[s] + a[s - 1]); for (j = 1; j < s; ++j) b[j] = .5 * (a[j - 1] + a[j + 1]); } return b; } ``` [Answer] # Python 2, 98 Bytes Took the straightforward approach, used `exec` to get out of using a while loop. I think there's a better way of doing the logic to figure out special case positions, but this works for now. Input should be formatted like `[list], times`. ``` b,c=input() k=~-len(b) exec'b=[(b[x-(0<x<k)]+b[x+(x<k)-(x==k)])/2.for x in range(-~k)];'*c print b ``` Ungolfed: ``` BASE,TIME = input() TEMP = [0]*len(BASE) # Temporary array as to not modify base. while TIME: for x in xrange(len(BASE)): if x == 0: TEMP[x] = (BASE[x] + BASE[x+1])/2.0 # First element special case. elif x == len(BASE)-1: TEMP[x] = (BASE[x] + BASE[x-1])/2.0 # Last element special case. else: TEMP[x] = (BASE[x-1] + BASE[x+1])/2.0 # Every other element. BASE = TEMP # Set base to temporary array. TEMP = [0]*len(BASE) # Reset temporary array to 0s. TIME = TIME - 1 print BASE ``` [Answer] # Mathematica, 81 bytes I have a feeling it could be golfed more if I could figure out a better way to handle the positivity condition. ``` f[l_,_]:=l;f[l_,n_/;n>0]:=Nest[.5{1,0,1}~ListConvolve~ArrayPad[#,1,"Fixed"]&,l,n] ``` Worth noting: Mathematica offers lots of potential built-in solutions in its range of list-processing and filter functions, as well as `CellularAutomaton`. I chose `Nest[... ListConvolve ...]` because it was the easiest way to work out the kinks at the ends of the list, but other angles might prove shorter. [Answer] ## Matlab , 109 ``` function a=f(a,n) if numel(a)>1&n>0 for k=1:n a=[a(1)+a(2) conv(a,[1 0 1],'valid') a(end-1)+a(end)]/2;end end ``` Examples: ``` >> f([0, 0, 1, 0, 0], 1) ans = 0 0.5000 0 0.5000 0 >> f([0, 0, 1, 0, 0], 2) ans = 0.2500 0 0.5000 0 0.2500 >> f([0, 0, 1, 0, 0], 0) ans = 0 0 1 0 0 >> f([0, 0, 1, 0, 0], -39) ans = 0 0 1 0 0 >> f([0], 482) ans = 0 >> f([], 10) ans = [] ``` [Answer] # Scala, ~~195 characters (186 with lazy output, i.e. `Stream`)~~ 187 characters ``` (t:Seq[Float],n:Int)โ‡’t.size match{case 0|1โ‡’t;case 2โ‡’{val a=t.sum/2;Seq(a,a)};case iโ‡’(t/:(1 to n)){(s,_)โ‡’(s.take(2).sum/2)+:s.sliding(3).map(l=>(l(0)+l(2))/2).toList:+(s.drop(i-2).sum/2)}} ``` probably not optimal, mapping `sliding(3)` is very useful in this case. ### tests: ``` scala> (t:Seq[Float],n:Int)โ‡’t.size match{case 0|1โ‡’t;case 2โ‡’{val a=t.sum/2;Seq(a,a)};case iโ‡’(t/:(1 to n)){(s,_)โ‡’(s.take(2).sum/2)+:s.sliding(3).map(l=>(l(0)+l(2))/2).toList:+(s.drop(i-2).sum/2)}} res0: (Seq[Float], Int) => List[Float] = <function2> scala> res0(Seq(0, 0, 1, 0, 0), 1) res1: Seq[Float] = List(0.0, 0.5, 0.0, 0.5, 0.0) scala> res0(Seq(0, 0, 1, 0, 0), 2) res2: Seq[Float] = List(0.25, 0.0, 0.5, 0.0, 0.25) scala> res0(Seq(0, 0, 1, 0, 0), 0) res3: Seq[Float] = List(0.0, 0.0, 1.0, 0.0, 0.0) scala> res0(Seq(0, 0, 1, 0, 0), -39) res4: Seq[Float] = List(0.0, 0.0, 1.0, 0.0, 0.0) scala> res0(Seq(0, 16, 32, 16, 0), 1) res5: Seq[Float] = List(8.0, 16.0, 16.0, 16.0, 8.0) scala> res0(Seq(1, 2, 3, 4, 5), 1) res6: Seq[Float] = List(1.5, 2.0, 3.0, 4.0, 4.5) scala> res0(Seq(0,64), 1) res7: Seq[Float] = List(32.0, 32.0) scala> res0(Seq(0), 482) res8: Seq[Float] = List(0.0) scala> res0(Seq(32, 32, 32, 16, 64, 16, 32, 32, 32), 4) res9: Seq[Float] = List(33.0, 27.0, 40.0, 22.0, 44.0, 22.0, 40.0, 27.0, 33.0) ``` [Answer] # q (27 characters) ``` {avg x^/:1 -1 xprev\:x}/[;] ``` Examples ``` q)f:{avg x^/:1 -1 xprev\:x}/[;] q)f[4;32 32 32 16 64 16 32 32 32] 33 27 40 22 44 22 40 27 33f //1-length input q)f[10;enlist 1] ,1f //0-length input q)f[10;`float$()] `float$() ``` [Answer] # R, 93 Bytes As an unnamed function ``` function(a,n){l=length(a);while((n=n-1)>=0)a<-colMeans(rbind(c(a[-1],a[l]),c(a[1],a[-l])));a} ``` Expanded ``` function(a,n){ l=length(a); # get the length of the vector while((n=n-1)>=0) # repeat n times a<-colMeans( # do the column means and assign to a rbind( # create an array c(a[-1],a[l]), # shift the vector left and duplicate last c(a[1],a[-l]) # shift the vector right and duplicate first ) ); a # return the vector } ``` Tests ``` > f=function(a,n){l=length(a);while((n=n-1)>=0)a<-colMeans(rbind(c(a[-1],a[l]),c(a[1],a[-l])));a} > f(c(0, 0, 1, 0, 0), 1) [1] 0.0 0.5 0.0 0.5 0.0 > f(c(0, 0, 1, 0, 0), 2) [1] 0.25 0.00 0.50 0.00 0.25 > f(c(0, 0, 1, 0, 0), 0) [1] 0 0 1 0 0 > f(c(0, 0, 1, 0, 0), -39) [1] 0 0 1 0 0 > f(c(0, 16, 32, 16, 0), 1) [1] 8 16 16 16 8 > f(c(0, 1, 2, 3, 4, 5), 1) [1] 0.5 1.0 2.0 3.0 4.0 4.5 > f(c(0, 64), 1) [1] 32 32 > f(c(0), 482) [1] 0 > f(c(32, 32, 32, 16, 64, 16, 32, 32, 32),4) [1] 33 27 40 22 44 22 40 27 33 > ``` [Answer] # C++14, 158 bytes ``` #define D(a,b)d[i]=(c[a]+c[b])/2; auto f(auto c,int n){while(n-->0&&c.size()>1){auto d{c};int i{};D(0,1)while(++i<c.size()-1)D(i-1,i+1)D(i,i-1)c=d;}return c;} ``` Requires input to be a container `value_type==double`, like `vector<double>`. Ungolfed: ``` #define D(a,b) d[i] = (c[a]+c[b])/2; //average auto f(auto c, int n) { while(n-- > 0 && c.size() > 1) { //breaks auto d{c}; //copy container int i{}; D(0,1) //left while(++i < c.size()-1) //count up to right D(i-1,i+1) //interior D(i,i-1) //right c=d; //overwrite container } return c; } ``` [Answer] ## Racket 223 bytes ``` (let p((l l)(m 0)(g list-ref))(cond[(> n m)(let*((j(length l))(k(for/list((i j))(cond[(= i 0)(/(+(g l 0)(g l 1))2)] [(= i(- j 1))(/(+(g l(- j 2))(g l(- j 1)))2)][else(/(+(g l(+ i 1))(g l(- i 1)))2)]))))(p k(+ 1 m) g))][l])) ``` Ungolfed: ``` (define(f l n) (let loop ((l l) (m 0) (lr list-ref)) (cond [(> n m) (let* ((j (length l)) (k (for/list ((i j)) (cond [(= i 0) (/ (+ (lr l 0) (lr l 1)) 2)] [(= i (- j 1)) (/ (+ (lr l (- j 2)) (lr l (- j 1))) 2)] [else (/ (+ (lr l (+ i 1)) (lr l (- i 1))) 2)]) ))) (loop k (+ 1 m) lr))] [else l] ))) ``` Testing: ``` (f '[32 32 32 16 64 16 32 32 32] 4) ``` Output: ``` '(33 27 40 22 44 22 40 27 33) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` .แป‹แนšjแนก3 .แป‹โฑฎร†mยตยก ``` [Try it online!](https://tio.run/##y0rNyan8/1/v4e7uhztnZT3cudBYAcR5tHHd4bbcQ1sPLfz//3@0sZGOAgwbmukomJlAaIR47H8TAA "Jelly โ€“ Try It Online") Full program. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~160~~ 144 bytes ``` float[]a(float[]b,int c)=>c>0&b.Length>1?a(b.Select((_,w)=>w<1?(b[w]+b[w+1])/2:w>b.Length-2?(b[w]+b[w-1])/2:(b[w-1]+b[w+1])/2).ToArray(),c-1):b; ``` Uses good ol' recursion. [Try it online!](https://tio.run/##xZLfT4MwEMff@SsuezBtOJAyXHQMFh/0aW@a@ECIKU1xJBMSqBJD@NtnO4YYtz3bH9fr3efSb3IVjSOaYr/PdxVXScrJ0cmwKBUIGsUi9q4ydyPLN7WN2ZqTzH2SOykUIa/YaqBdsTXJkja1tbFZSq/9ZRuPJY4/JZ0hSQZ3wqn7XN3XNf8iFIXD6DILR0FJCko2CiLorFK2cAxD5yHoxQ7W6xF@xj9gJxBbIMz94Zy4UwxBQ3OEAOHmMrYIfiu68Og55C9kJI3bSFsEk9Rh91YfWp@8BhWZSv0HkrRj6KOHzvwO2WEGtz4GmrPyqiYGziMvzFemT8emh7ltU6uztAJOTDzJUzTGdHpTNIpQ97GqH7jYkvLjPYpf6kJJ49ozhBmloSk9BDdFKcmZe7//Bg "C# (Visual C# Interactive Compiler) โ€“ Try It Online") [Answer] # Japt, ~~39~~ 37 bytes I just wanted to see how well my golfing language could hold up to my first challenge. ``` Vm0 o r_ยฃZgYยฉY-1 +ZgY>Zl -2?Y:ยฐY)/2}U ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=Vm0wIG8gcl+jWmdZqVktMSArWmdZPlpsIC0yP1k6sFkpLzJ9VQ==&input=WzMyLCAzMiwgMzIsIDE2LCA2NCwgMTYsIDMyLCAzMiwgMzJdLCA0) ``` Vm0 o r_ยฃZgYยฉY-1 +ZgY>Zl -2?Y:ยฐY)/2}U Vm0 o // Generate the range of integers [0, max(V,0)). r_ }U // Reduce it with this function, with a starting value of U: ยฃ // Return the argument, with each item X, index Y, and the full array Z mapped by this function: ZgYยฉY-1 + // Return (Z[max(Y-1,0)] plus ZgY>Zl -2? // Z[Y > Z.length-2? Y:ยฐY) // Y:--Y],) /2 // divided by two. // Implicit: output last expression ``` ]
[Question] [ In chess, the Fool's Mate is the fastest possible way to reach checkmate. It is reached with Black's second move. In chess notation, one possible sequence of moves that achieves Fool's Mate is `1.f3 e6 2.g4 Qh4#`. [![Position after 1.f3 e6 2.g4 Qh4#](https://i.stack.imgur.com/PVtzc.png)](https://i.stack.imgur.com/PVtzc.png) This is not the only possible way to achieve this checkmate (in the same number of moves). There are three things that can be varied while still taking the same number of moves: 1. White can move the f-pawn first or the g-pawn first, 2. White can move the f-pawn to f3 or f4, and 3. Black can move the e-pawn to e6 or e5. This gives 8 possible games that end in Fool's Mate. Print them all in standard chess notation. They are: ``` 1.f3 e5 2.g4 Qh4# 1.f3 e6 2.g4 Qh4# 1.f4 e5 2.g4 Qh4# 1.f4 e6 2.g4 Qh4# 1.g4 e5 2.f3 Qh4# 1.g4 e5 2.f4 Qh4# 1.g4 e6 2.f3 Qh4# 1.g4 e6 2.f4 Qh4# ``` The order in which the games are printed does not matter, so e.g. this is OK: ``` 1.g4 e5 2.f4 Qh4# 1.f3 e6 2.g4 Qh4# 1.g4 e6 2.f4 Qh4# 1.f4 e5 2.g4 Qh4# 1.f4 e6 2.g4 Qh4# 1.g4 e5 2.f3 Qh4# 1.g4 e6 2.f3 Qh4# 1.f3 e5 2.g4 Qh4# ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 61 This is a pretty good challenge for [bash brace expansions](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) ``` printf '1.%s Qh4# ' f{3,4}\ e{5,6}\ 2.g4 g4\ e{5,6}\ 2.f{3,4} ``` [Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUHdUE@1WCEww0SZS10hrdpYx6Q2RiG12lTHDEgb6aWbKKSbIAtAlPz/DwA "Bash โ€“ Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 80 bytes *-2 bytes by using a full program, as suggested by [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)* *-2 bytes thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* ``` for(n=8;n--;)print(`1.${n&2?G='g4':F} e${6-n%2} 2.${n&2?F=`f${n&4||3}`:G} Qh4#`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sI6T1fXWrOgKDOvRCPBUE@lOk/NyN7dVj3dRN3KrVYhVaXaTDdP1ahWwQgq52abkAZimdTUGNcmWLnXKgRmmCgnaP7/DwA "JavaScript (V8) โ€“ Try It Online") ### How? We iterate from \$n=7\$ to \$n=0\$ and use each bit to decide what should be displayed: ``` bit : 2 1 0 | | | | | +--> use 'e5' if set, use 'e6' if clear | +----> g-pawn first if set, f-pawn first if clear +------> use 'f4' if set, use 'f3' if clear ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 36 bytes ``` \f43f+56fแบŠโ€›g4vJ:RJฦ›รท`1.ฮ  eฮ  2.ฮ  Qh4# ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiXFxmNDNmKzU2ZuG6iuKAm2c0dko6UkrGm8O3YDEuzqAgZc6gIDIuzqAgUWg0IyIsIiIsIiJd) This was... annoying ``` แบŠ # Cartesian product of... \f43f+ # ["f3", "f4"] 56f # and [5, 6] โ€›g4vJ # Append "g4" to each :RJ # Reverse each and append to the original ฦ› # Over each... รท # Push each into the stack `1.ฮ  eฮ  2.ฮ  Qh4# # Format into the final output. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~104~~ ~~99~~ ~~90~~ 89 bytes ``` f(i){for(i=9;--i;printf("1.%c%d e%d 2.%c%d Qh4#\n",102+i/5,4+3/~i,6-i%2,103-i/5,4-i/7));} ``` [Try it online!](https://tio.run/##S9ZNT07@n5uYmaehqVDNpQAEaRqa1ly1/9M0MjWr0/KLNDJtLa11dTOtC4oy80rSNJQM9VSTVVMUUoHYCMIMzDBRjslT0jE0MNLO1DfVMdE21q/L1DHTzVQ1Agoa64IFgaS5pqZ17f///5LTchLTi//rlgMA "C (gcc) โ€“ Try It Online") -3 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan) -1 byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) -9 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) -1 byte thanks to [c--](https://codegolf.stackexchange.com/users/112488/c) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~62~~ 60 bytes ``` g4#f3ยถf3#g4 # e5 2. .+ 1.$& Qh4# 3 $&$%'ยถ$%`4 5 $&$%'ยถ$%`6 ``` [Try it online!](https://tio.run/##K0otycxL/P@fK91EOc340LY0Y@V0Ey5lLoVUUwUjPS49bS5DPRU1hcAME2UuYy4VNRVV9UPbVFQTTLhMkXhm//8DAA "Retina 0.8.2 โ€“ Try It Online") Edit: Saved 2 bytes thanks to @DLosc. Explanation: ``` g4#f3ยถf3#g4 ``` Insert the two pawn orders for White. ``` # e5 2. ``` Insert Black's first move in between each pair. ``` .+ 1.$& Qh4# ``` Append Black's second move to each pair. ``` 3 $&$%'ยถ$%`4 ``` Duplicate each game but with `f3` changed to `f4`. ``` 5 $&$%'ยถ$%`6 ``` Duplicate each game but with `e5` changed to `e6`. [Answer] # [Python 3](https://docs.python.org/3/), 76 bytes ``` print('1.%s%s e%%s 2.%s%s Qh4#\n'*4%(*'g4f3g4f4f4g4f3g4',)*2%(*'55556666',)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ91QT7VYtVghVRVIGEHYgRkmyjF56lomqhpa6ukmacZADIQQlrqOppYRSMIUCMyAACig@f8/AA "Python 3 โ€“ Try It Online") Can definitely be improved. ### [Python 3](https://docs.python.org/3/), 73 bytes ``` for x in 5,6:print(f'1.%c%c e{x} 2.%c%c Qh4#\n'*4%(*'g4f3g4f4f3g4f4g4',)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SKFCITNPwVTHzKqgKDOvRCNN3VBPNVk1WSG1uqJWwQjCDswwUY7JU9cyUdXQUk83STMGYiiZbqKuo6n5/z8A "Python 3 โ€“ Try It Online") This is 3 bytes shorter, but prints an empty line in the middle. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~380~~ 378 bytes ``` [S S S T S S S N _Push_n=8][N S S N _Create_Label_LOOP][S S S T N _Push_1][T S S T _Subtract:_n=n-1][S N S _Duplicate_n][N T T S N _If_negative_Jump_to_Label_EXIT][S S S T N _Push_1][T N S T _Print_as_number][S S S T S T T T S N _Push_46_.][T N S S _Print_as_character][S N S _Duplicate_n][S S S T S S N _Push_4][T S T S _Integer_divide][S S S T T S S T T S N _Push_102][T S S S _Add][T N S S _Print_as_character][S S S T S S N _Push_4][S S S T T N _Push_3][S T S S T S N _Copy_0-based_2nd:_n][S S S T S N _Push_2][T S S S _Add][T S T S _Integer_divide][T S S T _Subtract][T N S T _Print_as_number][S S S T S S S S S N _Push_32_<space>][T N S S _Print_as_character][S S S T T S S T S T N _Push_101_e][T N S S _Print_as_character][S N S _Duplicate_n][S S S T S N _Push_2][T S T T _Modulo][S S S T T S N _Push_6][S N T _Swap_top_two][T S S T _Subtract][T N S T _Print_as_number][S S S T S S S S S N _Push_32_<space>][T N S S _Print_as_character][S S S T S N _Push_2][T N S T _Print_as_number][S S S T S T T T S N _Push_46_.][T N S S _Print_as_character][S N S _Duplicate_n][S S S T S S N _Push_4][T S T S _Integer_divide][S S S T T S S T T T N _Push_103][S N T _Swap_top_two][T S S T _Subtract][T N S S _Print_as_character][S N S _Duplicate_n][S S S T T S N _Push_6][T S T S _Integer_divide][S S S T S S N _Push_4][S N T _Swap_top_two][T S S T _Subtract][T N S T _Print_as_number][S S S T S S S S S N _Push_32_<space>][T N S S _Print_as_character][S S S T S T S S S T N _Push_81_Q][T N S S _Print_as_character][S S S T T S T S S S N _Push_108_h][T N S S _Print_as_character][S S S T S S N _Push_4][T N S T _Print_as_number][S S S T S S S T T N _Push_35_#][T N S S _Print_as_character][S S S T S T S N _Push_10_\n][T N S S _Print_as_character][N S N N _Jump_to_Label_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [**Try it online**](https://tio.run/##jVBBCoAwDDunr@jXRAS9CQo@v65pq/MgygiUJE3KjnnZp20dxslMVdEg0uCzwAlRAYoQOqBwCk46nGxmcAQh9FGkSoXbmZUOvpIiIYMzKlqvHq9BaHHY267@PxZdUnlwe/SrCfU3uYmH2h3CiG6NcwsXsxM) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** Port of [*@jdt*'s C answer](https://codegolf.stackexchange.com/a/252165/52210), with `3+(i>1)` replaced with `4-3/(n+2)`: ``` Integer n = 8 Start LOOP: n = n - 1 If (n < 0): Stop program with an error, by jumping to an undefined label Print "1." Print n//4+102 as character Print 4-3//(n+2) as integer Print " e" Print 6-n%2 as integer Print " 2." Print 103-n//4 as character Print 6-n//4 as integer Print " Qh4#\n" Go to next iteration of LOOP ``` [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 42 bytes ``` 1.(f[34] e[56] 2.g4|g4 e[56] 2.f[34]) Qh4# ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWN7UM9TTSoo1NYhVSo03NYhWM9NJNatJN4DywnKZCYIaJMkQHVOMCKA0A) ### Explanation The logic is a bit clunkier than I'd like, but Regenerate doesn't have any string-based conditionals (yet). ``` 1.(f[34] e[56] 2.g4|g4 e[56] 2.f[34]) Qh4# 1. Match 1. ( | ) Then match one of these two patterns: f[34] f3 or f4 e[56] followed by e5 or e6 2.g4 followed by 2.g4 or g4 g4 e[56] followed by e5 or e6 2.f[34] followed by 2.f3 or 2.f4 Qh4# Finally, match Qh4# The -a flag outputs all possible matches ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 56ฤรŒ'fรฌรขโ€žg4ฮดลกDรญยซฮต`"1.รฟ eรฟ 2.รฟ Qh4#", ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f1CzS53CPetrhNYcXPWqYl25ybsvRhS6H1x5afW5rgpKh3uH9CqlAbARiBGaYKCvp/P//X1c3L183J7GqEgA) If outputting as a list of lines is allowed, the trailing `",` can be removed for -2 bytes: [try it online](https://tio.run/##yy9OTMpM/f/f1OxI4@Ee9bTDaw4vetQwL93k3JajC10Orz20@tzWBCVDvcP7FVKB2AjECMwwUf7/HwA). **Explanation:** ``` 56 # Push 56 ฤ # Push a list in the range [1,length] (without popping): [1,2] รŒ # Increase each by 2: [3,4] 'fรฌ '# Prepend an "f" to each: ["f3","f4"] รข # Get the cartesian product of these two: # [[5,"f3"],[5,"f4"],[6,"f3"],[6,"f4"]] ฮด # Map over each inner list: โ€žg4 ลก # Prepend string "g4" to the list # [["g4",5,"f3"],["g4",5,"f4"],["g4",6,"f3"],["g4",6,"f4"]] D # Duplicate this list of lists รญ # Reverse each inner list: # [["f3",5,"g4"],["f4",5,"g4"],["f3",6,"g4"],["f4",6,"g4"]] ยซ # Merge the two lists together ฮต # Foreach over each inner list: ` # Pop and push the items of the list to the stack "1.รฟ eรฟ 2.รฟ Qh4#" # Push this string, where the `รฟ` are automatically one by one filled # with the items , # Pop and print it with trailing newline ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` ๏ผฆ๏ผฅ34โบg4fฮน๏ผฆโชชฮนยฒ๏ผฅ56โชซโŸฆ1.โปฮนฮบ eฮป 2.ฮบ Qh4#โŸงฯ‰ ``` [Try it online!](https://tio.run/##JYzBCsIwEER/ZVkvG4iCNXrxD4RCxaN4CMXapUtSYtXPXzd6e8y8mX6Mpc9RVIdcgNo4E@4Ceujk9SR8hMGYnXPw6y@z8ELsobGkK5yW/2R/MO2UOdEVtxvjlpPtTZycB4S7RVKhqeVU6TyGFd48fOz8qKrrt3wB "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฆ๏ผฅ34โบg4fฮน ``` Loop over the strings `g4f3` and `g4f4` representing the alternatives for White's pairs of moves. ``` ๏ผฆโชชฮนยฒ ``` Loop over each of White's possible moves from the current pair. ``` ๏ผฅ56โชซโŸฆ1.โปฮนฮบ eฮป 2.ฮบ Qh4#โŸงฯ‰ ``` Map over the characters `5` and `6` and output the following joined together for each line: * The literal string `1.` * The other move for White from the current pair * The literal string `e` * The character `5` or `6` from the innermost loop * The literal string `2.` * The move for White from the inner loop * The literal string `Qh4#` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โ€œแธฒแนšแบ‰ฤ‹โ€˜แธคDโ€œfegโ€ลผโฑฎ;แนšโ‚ฌ$โ€œ1.โ€œโ€œ2.โ€œQh4#โ€ลผโฑฎKโ‚ฌY ``` A full program that prints the eight games. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHOzY93Dnr4a7OI92PGmY83LHEBSiYlpr@qGHu0T2PNq6zBso@alqjAhQ11AMSQGQEogMzTJRharyBCiL//wcA "Jelly โ€“ Try It Online")** ``` โ€œแธฒแนšแบ‰ฤ‹โ€˜แธคDโ€œfegโ€ลผโฑฎ;แนšโ‚ฌ$โ€œ1.โ€œโ€œ2.โ€œQh4#โ€ลผโฑฎKโ‚ฌY - Main Link: no arguments โ€œแธฒแนšแบ‰ฤ‹โ€˜ - code-page indices = [177,182,227,232] แธค - double -> [354,364,454,464] D - decimal digits -> [[3,5,4],[3,6,4],[4,5,4],[4,6,4]] โ€œfegโ€ - "feg" ลผโฑฎ - map with zip -> [[['f',3],['e',5],['g',4]],[['f',3],['e',6],['g',4]],[['f',4],['e',5],['g',4]],[['f',4],['e',6],['g',4]]] $ - last two links as a monad: แนšโ‚ฌ - reverse each -> [[['g',4],['e',5],['f',3]],[['g',4],['e',6],['f',3]],[['g',4],['e',5],['f',4]],[['g',4],['e',6],['f',4]]] ; - concatenate -> [[['f',3],['e',5],['g',4]],[['f',3],['e',6],['g',4]],[['f',4],['e',5],['g',4]],[['f',4],['e',6],['g',4]],[['g',4],['e',5],['f',3]],[['g',4],['e',6],['f',3]],[['g',4],['e',5],['f',4]],[['g',4],['e',6],['f',4]]] โ€œ1.โ€œโ€œ2.โ€œQh4#โ€ - ["1.","","2.","Qh4#"] ลผโฑฎ - map with zip -> [[["1.",['f',3]],[[],['e',5]],["2.",['g',4]],["Qh4#"]],[["1.",['f',3]],[[],['e',6]],["2.",['g',4]],["Qh4#"]],[["1.",['f',4]],[[],['e',5]],["2.",['g',4]],["Qh4#"]],[["1.",['f',4]],[[],['e',6]],["2.",['g',4]],["Qh4#"]],[["1.",['g',4]],[[],['e',5]],["2.",['f',3]],["Qh4#"]],[["1.",['g',4]],[[],['e',6]],["2.",['f',3]],["Qh4#"]],[["1.",['g',4]],[[],['e',5]],["2.",['f',4]],["Qh4#"]],[["1.",['g',4]],[[],['e',6]],["2.",['f',4]],["Qh4#"]]] Kโ‚ฌ - space-join each -> [["1.",['f',3],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#"],["1.",['f',3],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#"],["1.",['f',4],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#"],["1.",['f',4],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#"],["1.",['g',4],' ',[],['e',5],' ',"2.",['f',3],' ',"Qh4#"],["1.",['g',4],' ',[],['e',6],' ',"2.",['f',3],' ',"Qh4#"],["1.",['g',4],' ',[],['e',5],' ',"2.",['f',4],' ',"Qh4#"],["1.",['g',4],' ',[],['e',6],' ',"2.",['f',4],' ',"Qh4#"]] Y - newline-join -> ["1.",['f',3],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['f',3],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['f',4],' ',[],['e',5],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['f',4],' ',[],['e',6],' ',"2.",['g',4],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',5],' ',"2.",['f',3],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',6],' ',"2.",['f',3],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',5],' ',"2.",['f',4],' ',"Qh4#",'\n',"1.",['g',4],' ',[],['e',6],' ',"2.",['f',4],' ',"Qh4#"] - implicit, smashing print ``` [Answer] # MATLAB, 72 bytes Somewhat straight-forward, but it's not how the tutorial tells you to do it. [Uses this little-known syntax](https://codegolf.stackexchange.com/a/111979). ``` function a b ``` is equivalent to ``` function('a','b') ``` Which means that two string inputs `'a'` and `'b'` can be entered `a b` instead of `('a','b')`, saving 6 bytes. --- First make a string template that is equal to a row, but with "wild cards" for the characters that varies. All strings have `1.`, `e`, `2.`, `Qh4#\n`. All other characters are stored in the string in the end. I tried to find a way to use the pattern with similarities between rows, but string manipulation is verbose in Octave. ``` printf 1.%c%c e%c 2.%c%c Qh4#\n f35g4f36g4f45g4f46g4g45f3g45f4g46f3g46f4 ``` [Try it online!](https://tio.run/##y08uSSxL/f@/oCgzryRNQ91QTzVZNVkhFYiNIMzADBPlmDx1HfU0Y9N0kzRjMyBhAmKZAFnpJqZpxiACyDIDsczSTNQ1//8HAA "Octave โ€“ Try It Online") [Answer] # C (gcc), 156 131 130 111 105 103 90 bytes Some bytes lost because of @Steffan. ``` main(i){for(;i++<9;printf("1.%c%d e%d 2.%c%d Qh4#\n",102|i>5,4-3/i,5+i%2,102|i<6,4-i/8));} ``` Explained: * import modules * declare main * declare iterator * keep looping 8 times * + print according to the format specifiers * + - if i is lesser than 5, the first character is f, else g * + - if i is less than 3, the first number is 3, else 4 * + - if i is odd and is less than six, or is six, then 5, else 6 * + - if i is less than 5, then 'g', else 'f' * + - if i is less than 5 or is even, then 4, else 3. * + add a newline [Answer] # [Python 3](https://docs.python.org/3/), 118 bytes ``` for f in 0,1: x='f3','f4';y='g4', if f:y,x=x,y [print(f'1.{w} e{r} 2.{W} Qh4#')for w in x for W in y for r in[5,6]] ``` [Try it online!](https://tio.run/##HcyxCoMwFAXQPV9xocNr4SG1ph0s@YhODuLYV7NECYIJId@eGrcznTVu8@K6UmTxEFiHO7e9QjAkHTGJpnc09NPEClYgfeRgAkeFcfXWbVehtkl7xjf5jEeThozPrC90q@Nex4DKoTKe9AfHJ7@mqZQ/ "Python 3 โ€“ Try It Online") ]
[Question] [ You're a chef and you love cooking with your spices, but recently you've taken a liking to organizing your spices based on how often you use them. But you have no time to be writing down when you used your spice last. Simply, you swap and move spices around, and this seems to do the trick. But of course you're a chef and that means you have some cooks with you. You decide to tell them the simple rules of engagement with your spices. 1. If you recently used a spice, move it up one in the spice rack 2. If you didn't use any spices at all, e.g. `[]` empty movement list, then the spice list is not affected. 3. You may put any spice into my spice holder, but if you use it, make sure to move it. 4. The list can contain anything. But because these are spices we are working with. It is preferred that you use names of spices. 5. Spices should be unique. Too many of the same spices spoil the broth... or however that saying goes Normal code-golf rules apply. ### Example of Oregano being used again and again. ``` pepper pepper pepper pepper oregano paprika paprika paprika oregano pepper salt salt oregano paprika paprika cumin oregano salt salt salt oregano cumin cumin cumin cumin ``` ## Task Input a list of spices, and a list of what spices got used, then output the final list. ## Example Input ``` [pepper, paprika, salt, cumin, oregano], [oregano, cumin, cumin, salt, salt, salt] ``` Output ``` [salt, pepper, paprika, cumin, oregano] ``` How this looks ``` pepper pepper pepper pepper pepper pepper salt paprika paprika paprika paprika paprika salt pepper salt salt salt cumin salt paprika paprika cumin oregano cumin salt cumin cumin cumin oregano cumin oregano oregano oregano oregano oregano ``` Input ``` [pepper, paprika, salt, cumin, oregano], [salt, salt, salt, salt, salt, salt, salt, salt, salt, salt, salt, salt, oregano] ``` Output ``` [salt, pepper, paprika, oregano, cumin] ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes `foldl(?)` is an anonymous function taking two list arguments and returning a list, with all elements of the same (`Eq`-comparable) type. Use as `foldl(?)["pepper", "paprika", "salt", "cumin", "oregano"]["oregano", "cumin", "cumin", "salt", "salt", "salt"]`. ``` foldl(?) (x:y:r)?n|y==n=y:x:r|s<-y:r=x:s?n s?n=s ``` [Try it online!](https://tio.run/##rY7BasMwDIbvfgqT7mBDkgcw80IZo5dRCmOnLAeROq2poxg5oQnrnj1LOho22GlMIP5PQr@kI4STcW58T1b8eb3dvK43T/xxt@Or5IOxGixqi60hKNu7Dp1FE9IavGB8inBszmmHZUc08CoVZGCv1EtLFg/Jg8i/qIhvIOXVJtPrHsYq/TZWjds7kUkmejUokhleBq1RD6pXdAn3ydTUvQoZsil1GEeRR954byiKeeTBkz3BjAFcO2vZ1RZnaMgcAJuoiHm@FN8HFrhZf2gx/fSnU79u@0ddjkn2CQ "Haskell โ€“ Try It Online") * `foldl(?) s m` starts with the (spice rack) list `s` and combines it with each element (spice) from `m` in order, using the operator `?`. * `s?n` uses the spice `n` from the spice rack `s` and returns the resulting spice rack. + If `s` has at least two elements, `?` checks whether the second one is equal to `n`, and if so switches the first two elements. If not equal, `?` keeps the first element fixed and recurses on the rest. + If `s` has at most one element, `?` returns it unchanged. [Answer] # [Chef](http://search.cpan.org/~smueller/Acme-Chef/), ~~875~~ 843 bytes ``` S. Ingredients. 1 g T 0 g Z J I Method. Put Z into mixing bowl.Take I from refrigerator.B I.Put I into mixing bowl.Take I from refrigerator.B until bed.Take I from refrigerator.V I.Put Z into 2nd mixing bowl.N T.Fold J into mixing bowl.Put J into mixing bowl.Remove I.Fold T into mixing bowl.Put J into 2nd mixing bowl.N until ned.Fold T into mixing bowl.Put T into mixing bowl.Fold J into 2nd mixing bowl.Put J into mixing bowl.C T.Stir for 1 minute.Put Z into mixing bowl.Fold T into mixing bowl.C until ced.Fold T into 2nd mixing bowl.G T.Put T into mixing bowl.Fold T into 2nd mixing bowl.G until ged.Put I into mixing bowl.Fold T into mixing bowl.Take I from refrigerator.V until ved.Fold T into mixing bowl.L T.Put T into 2nd mixing bowl.Fold T into mixing bowl.L until led.Pour contents of 2nd mixing bowl into baking dish. Serves 1. ``` -32 bytes thanks to *Jonathan Allan* by removing `the` where I wouldn't think it will work. Chef has no string types, so the ingredients are positive integers. 0 is used to separate the starting list from used ingredients and to end the used ingredients list. See the TIO link for an example. **Pseudocode explaination:** ``` A, B: stack T, J, IN: int T = 1 A.push(0) // used as the marker for the bottom of the stack IN = input() // input the first list while(IN): A.push(IN) IN = input() IN = input() // for each used ingredient while(IN): B.push(0) while(T): // move all ingredients up to and including the one we are moving right now to the second stack T = A.peek() - IN B.push(A.pop()) A.push(B.pop()) if(A.peekUnderTop() != 0): A.swapTopTwoItems() T = B.pop() // move the ingredients from the second stack back to the first while(T): A.push(T) T = B.pop() T = IN // to make it non-zero for next iteration IN = input(0 print(A.inverted()) ``` [Try it online!](https://tio.run/##lZPBToQwEIbv8xTzBM2yetCrm2jYrMYI8bA3oAM0C52kFPTtsVgOLktJDElDpnz/fG1pUVM5jokAiHVlSCrSthMQYYUp7Nx4hiPEAK9ka5YC3nuLZ1TaMrbqW@kKc/5qRJpdCGMsDbdoqDSqIpNZNuIJYzEx8b@YXlvVYE4y/NHnHDzL7LW8Cn/DVDxzI/F423jCVsof1PLgmnku3eRu23ll7ZS38JXyX8tlbMD04BaXWGWwZIORm9K9JRE4mpDOYVYuFspLhxfXbEs9iPn4ysUHfoCQ2caZ@8xhY5dP17pLrTDmo5tJl3uDBWs73QXkchni6Ty7TAWputrdnoTMQB1GYhzvYQ938ADRI@zcy/rzO/kD "Chef โ€“ Try It Online") [Answer] # JavaScript, 61 bytes ``` a=>b=>b.map(v=>(p=a.indexOf(v))&&a.splice(p-1,2,a[p],a[p-1])) ``` Input format: * f(list\_of\_spices)(list\_of\_what\_spices\_got\_used) * two list are array of string Output: * list\_of\_spices is modified in-place. ``` f= a=>b=>b.map(v=>(p=a.indexOf(v))&&a.splice(p-1,2,a[p],a[p-1])) a = ['pepper', 'paprika', 'salt', 'cumin', 'oregano']; b = ['salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'salt', 'oregano']; f(a)(b); document.write(JSON.stringify(a)) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 14 bytes ``` Fฮปแนโ†”`CโฐtMoโ†’=ยขโฐ ``` Inputs are lists of strings (it also works on other kinds of lists). [Try it online!](https://tio.run/##yygtzv7/3@3c7oc7Gx@1TUlwftS4ocQ3/1HbJNtDi4Ds////RysVpBYUpBYp6SgVJBYUZWYnAlnFiTklQCq5NDczD0jnF6WmJ@blK8UCVUOlqErBzQcA "Husk โ€“ Try It Online") -1 byte thanks to H.PWiz ## Explanation ``` Fฮปแนโ†”`CโฐtMoโ†’=ยขโฐ Implicit inputs (two lists). F Fold second input using the first as initial value ฮป with this anonymous function: Arguments x (list of spices) and s (used spice). For example, x=["a","b","c","d"] and s="c". ยขโฐ Repeat x infinitely: ["a","b","c","d","a","b","c","d".. M For each item, = test equality to s: [0,0,1,0,0,0,1,0.. oโ†’ and increment: [1,1,2,1,1,1,2,1.. t Drop first element: [1,2,1,1,1,2,1.. `Cโฐ Cut x to these lengths: [["a"],["b","c"],["d"]] แนโ†” Reverse each slice and concatenate: ["a","c","b","d"] ``` I have to repeat `x` infinitely, since otherwise the list would lose its last element when we use the topmost spice. It would be enough to add a trailing 1, but repetition takes fewer bytes. A better way would be to rotate the list instead of dropping its first element, but Husk has no built-in for that. [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ ~~71~~ 69 bytes New answer, in the spirit of my original attempt. ``` r,u=input() for x in u:i=r.index(x);r.insert(i/~i+i,r.pop(i)) print r ``` [Try it online!](https://tio.run/##VYvBCsIwEETv/Yq9JcFQwaPSLyk9BI26qLvLNoH04q9Hg1j09N4MM7KkK9OuVvV5QJKcrOvOrFAACfIeB@2RTrHY4g5N56jJ4vaJG/TaC4tF5zpRpARa62gkikQ1HoyEd30LTedwT43H/EBqwhovgdhMHsY1/A5W@V7/@cH0Ag "Python 2 โ€“ Try It Online") Other solution: # [Python 2](https://docs.python.org/2/), 69 bytes ``` r,u=input() for x in u:i=r.index(x)-1;r[i:i+2]=r[i:i+2][::-1] print r ``` [Try it online!](https://tio.run/##VYvBCsIwEETv/Yq9pcVWaI@RfEnIIWjURd0sawLx66NBWvT03gwz/ErXSEutMmaDxDn1Q3eOAgWQIGs0skc6hdKXYZoPYlHjbnFmFav1NLuOBSmB1GoVB@YgagTF/lPffNOnv6fGY34gNYkSLp6iciPYLfwONlmv//zCvQE "Python 2 โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 80 bytes ``` def g(r,q): for s in q: i=r.index(s) if i:r[i-1],r[i]=r[i],r[i-1] return r ``` [Try it online!](https://tio.run/##VYyxDsIwDERn8hXekkoGCcZKZeQn2gyBpiUCnNRNJfj6khRRweK7Z58vvOLV02GeW9tBrxiHohTQeYYRHMGQAFzFO0etfaqxyNiBK7l2273GJLrKAz8LAWzjxAS8FJ6UwXMq3AR2FCEByoaaWB0l9stNiJOqZbAhWJYIMpgUvZlsR3OPWS/Tw1E2nm1vyEuNUK/wG1jN9/VPdTG/AQ "Python 2 โ€“ Try It Online") [Answer] # Java 8, ~~87~~ ~~86~~ 76 bytes ``` a->b->b.forEach(x->{int i=a.indexOf(x);a.set(i,a.set(i>0?i-1:i,a.get(i)));}) ``` Takes two inputs as `ArrayList<String>` and modifies the first List instead of returning a new one to save bytes. -10 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##zZDBbsIwDIbvfQqLUyK10XZdodM0badNO3CcdjAhMEObREnKQIhn71JaQBoITTtNiuw4v@X/ixe4wsxYpRfTZUOVNS7AIr6JOlApHpzDzQv5kCeXNX9BmNVaBjJaPBrt60q5az3P/SVPZInewyuShm0C4AMGknDQh0eU4Tg40vMihcP8c60oQMIIGsyKSTxiZtwTyk@2zoot6QA0QkF6qtZvM7bmOQqvAqO0z8XNPWW3d209b2vOeb7jTZ5ELFtPyojV060MTaGKyKwzfv8A5C09wBkTeEtS@Yil1ddJZt0eBfp9NbDKWuVSsGgdLTEFj2VIQdYV6RSMU3PUZiC8LSl2pzBo6faOUqC15YZ1PlyglMoGdtWtn3ec36fO8xR/@PWG440PqhKmDiKy6lDqg3en78N//PXP7/01Xub61XZ2ya75Bg) ``` a->b->{ // Method with two ArrayList<String> parameters and no return-type b.forEach(x->{ // Loop over the second input-List int i=a.indexOf(x); // Get the index of the current item in the first input-List a.set(i,a.set( // Swap items: i>0? // If the current item is not the top item yet: i-1 // Use the item above it : // Else: i, // Use itself a.get(i))); // And swap it with the current item }) // End of loop // End of method (implicit / single-line body) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 18 bytes ``` vDyk>Igโ€šยฃ`U`2(@)Xยซ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/zKUy284z/VHDrEOLE0ITjDQcNCMOrf7/P1o9vyg1PTEvX11HQT25NDczD4VRnJhTgkHHckWrF6QWFKQWgYQKEguKMrMTkVXBtcPMjgUA "05AB1E โ€“ Try It Online") **Explanation** ``` v # for each used spice D # duplicate current spice order yk # get the index of the current spice > # increment Igโ€š # pair with the number of unique spices ยฃ # split the spice list into pieces of these sizes ` # split as 2 separate lists to stack U # store the list of spices below the current one in X ` # push the current spice and all above separately to stack 2(@ # swap the second item to the top of the stack ) # wrap in a list Xยซ # append the rest of the spices ``` [Answer] ## C#, 125 117 81 79 bytes ``` (c,n)=>{foreach(var i in n){var j=c.IndexOf(i);if(j!=0){c[j]=c[--j];c[j]=i;}}}; ``` [Try it on .NET Fiddle](https://dotnetfiddle.net/2ZATyE) golfed off 36 bytes thanks to [raznagul](https://codegolf.stackexchange.com/users/42502/raznagul) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` vรykยฉDฤ€-DUรจยฎวyXว ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/7PCEyuxDK12ONOi6hB5ecWjd8bmVEcfn/v8frVScmFOipKNAMzq/KDU9MS9fKZYrWqkgtaAgtQgkWpBYUJSZnYisMLk0NzMPRQcA "05AB1E โ€“ Try It Online") [Answer] # Mathematica, 52 bytes but it is my first post here so please be kind if counted incorrectly :) ``` Keys@Sort@Merge[{PositionIndex@#,-Counts@#2},Total]& ``` And an example: ``` Keys@Sort@Merge[{PositionIndex@#, -Counts@#2}, Total] &[ {pepper, paprika, salt, cumin, oregano} , {oregano, cumin, cumin, salt, salt, salt} ] ``` > > {salt, pepper, paprika, cumin, oregano} > > > [Answer] # [CJam](https://sourceforge.net/p/cjam), 18 bytes ``` l~{a\_@#__g-e\}%~` ``` [Try it online!](https://tio.run/##S85KzP3/P6euOjEm3kE5Pj5dNzWmVrUu4f//aKWC1IKC1CIlBaWCxIKizOxEIKs4MacESCWX5mbmAen8otT0xLx8pViFaJgUVSm4@QA "CJam โ€“ Try It Online") ]
[Question] [ **This question already has answers here**: [Operation Unzรƒรฑรƒยจรƒรบรƒโˆซรƒยจaร•รกร•รฑรƒร˜ร•รฎร•รขlรƒรผรƒโ‰ gร•รฏรƒรนรƒยบร•รกร•รฌรƒโ„ขร•รงoรƒยจรƒรนร•รงรƒฯ€รƒยช](/questions/188472/operation-unz%cc%96%cc%ac%cc%9c%cc%ba%cc%aca%cd%87%cd%96%cc%af%cd%94%cd%89l%cc%9f%cc%adg%cd%95%cc%9d%cc%bc%cd%87%cd%93%cc%aa%cd%8do%cc%ac%cc%9d%cd%8d%cc%b9%cc%bb) (12 answers) Closed 2 years ago. Write a program or function that, given a string, will strip it of zalgo, if any exists. ## Zalgo For this post, zalgo is defined as any character from the following Unicode ranges: * Combining Diacritical Marks (0300โ€šร„รฌ036F) * Combining Diacritical Marks Extended (1AB0โ€šร„รฌ1AFF) * Combining Diacritical Marks Supplement (1DC0โ€šร„รฌ1DFF) * Combining Diacritical Marks for Symbols (20D0โ€šร„รฌ20FF) * Combining Half Marks (FE20โ€šร„รฌFE2F) <https://en.wikipedia.org/wiki/Combining_character#Unicode_ranges> ## Input * May be passed via command line arguments, STDIN, or any other standard method of input supported by your language * Will be a string that may or may not contain zalgo or other non-ASCII characters ## Output Output should be a string that does not contain any zalgo. ## Test Cases ``` Input -> Output HEร•ยถร•รถรƒโˆ รƒรฌCร•รขOรƒรณร•รฏรƒร‰Mร•รฅร•รดร•รœEรƒรฃรƒร‰ร•โ€ขTร•รฅรƒโ€ ร•รฏHรƒยงรƒร˜ร•รต -> HE COMETH Cร•รขรƒรคodรƒรฌeร•รฎร•รน รƒรœGร•ร„รƒรซร•รŸoร•รบlร•รฎรƒร˜ร•รคfร•รขร•รง -> Code Golf aaaร•รŸร•ยฉaร•รฏรƒโˆžaรƒรฒร•รฏรƒรซaaร•รนร•ยขรƒรถaaร•รณร•ยขรƒรธ -> aaaaaaaaa โˆšยฑnรƒร‰ -> โˆšยฑn โ€šรถยฐโ€šร‰ยง -> โ€šรถยฐ ``` ## Scoring As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. [Answer] ## [Retina](https://github.com/m-ender/retina), 35 bytes ``` T`รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜ ``` [Try it online!](https://tio.run/nexus/retina#DcxBCoJQAIThvafwAu8UIbmJNh6gB9Uq8AqCIGgGiYplCRKVVAvd6c4LzBxCL@AR7K0@GH5mtjZwBOvh24jh1w@tI4a2H92zGN1@6koxdfU8mwbfzNHpiBf018iYwl0x5JWegSNcviyGKJmaeKLmTVMZAnuLeMeEhQ5vSQcRK5v3AxOVBHv6PGlSSlb8SHXYSFwUkVoKPpArM2X/Bw "Retina โ€šร„รฌ TIO Nexus") Simply removes all characters in the ranges given in the challenge from the input. The code is super unreadable of course, but the code is conceptually no different from something like `T`0-9A-Za-z` which would delete all alphanumeric characters. [Answer] # [Python 3](https://docs.python.org/3/), ~~73~~ 69 bytes *-4 bytes thanks to L3viathan.* Not sure if participating in your own challenge is ok or not but... Stole the regex ~~and essentially the idea as well ><~~ straight from the JS and Retina answers. ``` lambda s:re.sub('[รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜]','',s) import re ``` [Try it online!](https://tio.run/nexus/python3#VY29asJQAIV3nyLbTcDrAxQ6FalLcXFrHa6YgKBGEt0DFwR/ChUVW1tBSltpO8ROZsvQ9ZyHiC/gI6R3Kjh98HE@jnd5l7dVp9FUVngRuKVw0LDFLSLJOPvay@w7zQ6RzA7pUT/Io05PyVaekrguikIUQ6fQ6vT8oG8Fbt4LWt2@7dmiUuYH10gszK84qmLFJfQNp3zisIwJNN9rnGLLZQVviPksHKfwX5sEY7@JucsFNxaG14ww487nS5sLMx97HPH@rFFKccdPZY72Co8GM2M2fMXacGWYnu1/f7rQxuR/ "Python 3 โ€šร„รฌ TIO Nexus") [Answer] ## JavaScript (ES6), 55 bytes ``` f= s=>s.replace(/[รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜]/g,'') ``` ``` <textarea oninput=o.textContent=f(this.value)></textarea><pre id=o> ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 37 bytes ``` r"[รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜] ``` [Try it online!](https://tio.run/nexus/japt#AVwAo///ciJbzIAtza/hqrAt4au/4beALeG3v@KDkC3ig7/vuKAt77ivXf//IkhFzabNmsy4IMyTQ82JT8yXzZXMg03NjM2ZzYZFzIvMg82lVM2MzKDNlUjMpMyvzZsgIg "Japt โ€šร„รฌ TIO Nexus") [Answer] # PHP, 67 Bytes shorter as the write out ``` <?=preg_replace("#[รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜]#u","",$argn); ``` [Try it online!](https://tio.run/nexus/php#JYxBS8JgHIfv@xTjtYOB@wRaO4QoQXTpphIv63U7yDYWnSIYDATNIFGxLEGikvIwu@RuO3j9/z7E/AJ@hPWHTg88PDwV03d8re0FSlpOsSHqVXxiRolOoxP0zmmKCUVnGOAZ3SrdU4SPCwxogUmd3inGiygJDqnvXdFIYYy5Tt0aQhpi6eG1gzFH/TZ6eNA5lVJiiS/J17WkJ8aQzRxvNGNOmSlXp9vfwGZuf1yKREteH8jAdg9vNfM4r5hHfqDsy0D5HWmpoig0KDQQZ99rI1ul2SY0sk26ix6NXZTuk4WxT@JW4YZvovS/KefKcjzRdJuuKGt3@R8 "PHP โ€šร„รฌ TIO Nexus") # PHP, 115 Bytes ``` <?=preg_replace("#[\u{300}-\u{36f}\u{1ab0}-\u{1aff}\u{1dc0}-\u{1dff}\u{20d0}-\u{20ff}\u{fe20}-\u{fe2f}]#u","",$argn); ``` [Try it online!](https://tio.run/nexus/php#LY0xS8NQEID3/Irw6lChQhrBpdUMUiyCuLg1Rc7kvWQoSYh0KgEhUGitQ2lLtVoQ0ZZO6iJuDl3vflM8eU7f3cfHXd1JwsRQcSrBC8st0WzQihb4beLkmAbnOKcZ5mc0ogfqN/AWc3q7oBE@06yJr/hOj6IiOMRh7ONE0pSWJvZP6AbHtI7pqUNTjoaKBnRncgoAtKYN8NUPwHvGmM2SXnDBnDN/uDrdfqUBc/sZYS7acL0DaRDt9gznqKg7h0kqg8tUJh3wZFmUWm63t29Z2d4fD1TGqMKV3qugtPC9f@FrYVu@FralhZK2FjyorF3q8n9R0Y9rhfTCWLiRG4makRW/ "PHP โ€šร„รฌ TIO Nexus") # PHP, 35 Bytes Valid for the given Testcases it removes all Marks ``` <?=preg_replace("#\pM#u","",$argn); ``` [Try it online!](https://tio.run/nexus/php#JczBSgJRFMbx/TzFcG1hYE@gNYsQRZA27ZqIw3SdWcjcy41WEQQDkmYLUbGmhAxLWlmbaNfC7flewheZDrT68x1@nFpgE@t1jNMUJeUT1azjHTn/@Dw@RP@IZ5hy1sYQj@jV@Y4zvB1jyC@YNnnJazypihLIA3POY40J5j73GrjhEVYGz11MBA066OPeF0pEWOGD5Osn8YNkJJc5XjmXzqS/olqbbxfvtQzfuljm5ivlTLrNF9tsqU7pYodcnO5eecFBUQv2rdPxmdO2S5Euq1Jo26VL4aryz6qFjhKjwjRMVdW7Lv4A "PHP โ€šร„รฌ TIO Nexus") [Answer] # Python 3, ~~127~~ 118 bytes Just a straightforward answer for now, let's see how golfable it is. ``` lambda y:"".join(chr(x)for x in map(ord,y)if not(767<x<880or 6831<x<6912or 7615<x<7680or 8399<x<8448or 65055<x<65072)) ``` Changelog: * When will I ever learn that comprehensions are shorter than functional stuff (-9 bytes). [Answer] # Bash + coreutils, 41 ``` tr -d 'รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜' ``` Simply strips out characters in the given ranges. [Try it online](https://tio.run/nexus/bash#PY5PasJQEMb3OcXwaHH1rtCNSN2UbnqBh3mhQskrSZZdBAKC1oKi4p9WkNJW2i7izuxygfkOES/gEeJQsLP5wTc/vhkvcBElNk46JrbUDUm1W/jCigviSRP9W55jxtkNhlii1@JnzvB5hyFvMGvzB@d4VaRE5IHzeWIxxZq4d42Ux9g6vD1gKtIgQB8vYhpjsMW3kdKd4YVgLMka77wSzoWl8nznkcxj1A2TgNRlTPqKFF2c//zb2s69I/WfKXqqk4i0Tw1ONfLqZ6er37Lap7ral4dspA9ZeSw2@ljkjfpcIKdCW58A). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 43 bytes ``` '[รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜]'โ€šรฉรฏR'' ``` [Try it online!](https://tio.run/nexus/apl-dyalog#Fcw9qsJAGIXh/q4i3VSzCpFrI4LYicWAWolCVhAYCPiLokGNCir@oBbRynQpbM9ZRGYDLiFOqvfw8fBlrvGnog5PMkrvT5k@kvTtyfSdGD2VRiffeC@/cdQQZhJUhcgyV5SKvDBE7GBeYL@CJQPoMkdc0y9iCM1zjSPsGZRwQsSN@HOFlRj0mpi3uODOgf9PDzNee9x2uLBq0Gaf45wqpXjlTdm3T4WVzcxedjwitF3aJjn7vLrQ@TDhweiTI34 "APL (Dyalog Unicode) โ€šร„รฌ TIO Nexus") PCRE **R**eplace all those with nothing --- 44 byte version not using RegEx or strange character literals (and thus single byte per character): ``` โ€šรงรป~โ€šรฉรฏUCSโ€šร รค65055 8399 7615 6831 767+โ€šรงโ‰ฅยฌยฎ16โˆšรณ2 6~โ€šรงยฎโ€šรงโ‰ฅ7 ``` [Try it online!](https://tio.run/nexus/apl-dyalog#DYy9asJgGIX3XMW3u5hKvugcRJfiUL2AD7RTaSAXIIWAxtQIoiEaa2mL9Weq4uIm1PU9N/HeSHyn55zDw@FoGBScfPZ5kna8J45i7ZQdR1UrtZpyte0oXa3YktwSJ@f/va1v2YPSfU720t2Co2ERWM06tsjpomjmYdSiDCmFjxhjiUGd3inEbxtj@kLapA39YWUFlogU@12a9TDHWtGggTeaYufj4wVzkeJnjJCIaYzBDgcjp0dDC8FUljV@KBdmwqtYt9MrhULOvzncqDs "APL (Dyalog Unicode) โ€šร„รฌ TIO Nexus") `โ€šรงโ‰ฅ7`โ€ƒ1โ€šร„ยถ7 (1 2 3 4 5 6 7) `2 6~โ€šรงยฎ`โ€ƒexcept 2 and 6 (1 3 4 5 7) `16โˆšรณ`โ€ƒmultiply by 16 (16 48 64 80 112) `โ€šรงโ‰ฅยฌยฎ`โ€ƒ1โ€šร„ยถ each (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16, 1 2 3โ€šร„ยถ, โ€šร„ยถ110 111 112) `+`โ€ƒadd offset to each list (65056 65057 65058โ€šร„ยถ, โ€šร„ยถ877 878 879) `โ€šร รค`โ€ƒenlist (flatten) `โ€šรฉรฏUCS`โ€ƒconvert to corresponding Unicode character `โ€šรงรป~`โ€ƒget text input and remove all such characters [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` โ€šร„รบโ‰ˆยชยปโˆ‘'โ€šร…โˆซยฌยถ60โˆ†โ‰ ยทฯ€รฑ_WTโ€ฆยถ7ยทยชยง|ยทฯ€ยดYโ€ฆโ€ Fโ€šร„รดbยปโˆ‘5r2/Fยทยชรฅยทโˆรผ@ ``` [Try it online!](https://tio.run/##AXQAi/9qZWxsef//4oCcxbvItyfigbrCpjYwxq3huZZfV1TJpjfhu6R84bmrWcmgRuKAmWLItzVyMi9G4buM4bifQP///yJIRc2mzZrMuCDMk0PNiU/Ml82VzINNzYzNmc2GRcyLzIPNpVTNjMygzZVIzKTMr82bIg "Jelly โ€šร„รฌ Try It Online") # Explanation ``` โ€šร„รบโ‰ˆยชยปโˆ‘'โ€šร…โˆซยฌยถ60โˆ†โ‰ ยทฯ€รฑ_WTโ€ฆยถ7ยทยชยง|ยทฯ€ยดYโ€ฆโ€ Fโ€šร„รดbยปโˆ‘5r2/Fยทยชรฅยทโˆรผ@ Main link โ€šร„รบโ‰ˆยชยปโˆ‘'โ€šร…โˆซยฌยถ60โˆ†โ‰ ยทฯ€รฑ_WTโ€ฆยถ7ยทยชยง|ยทฯ€ยดYโ€ฆโ€ Fโ€šร„รด Base 250 compressed integer; 768008790683206911076160767908400084476505665071 bยปโˆ‘5 Convert into base 100000; [768, 879, 6832, 6911, 7616, 7679, 8400, 8447, 65056, 65071] r2/ Inclusive range on non-overlapping slices of length 2 F Flatten ยทยชรฅ chr; cast to character from codepoints ยทโˆรผ@ Filter; remove all characters from input that are in the characters generated before ``` [Answer] # Java 8, 57 bytes ``` s->s.replaceAll("[รƒร„-ร•ร˜ยทโ„ขโˆž-ยทยดรธยทโˆ‘ร„-ยทโˆ‘รธโ€šร‰รช-โ€šร‰รธร”โˆโ€ -ร”โˆร˜]","") ``` [Try it here.](https://tio.run/##hY/PSgJRFMb3PcVhVjPQzAtIQYTkRlvUTlzcxjHGxjuDMwoRgjAgaAaJimUJFpZUC22lu1m0PechZl7AR5huNdsQzuU79/z53e@WWZ2ptmPwcvEi1i3mupBlJr/aATC5Z1RLTDcg93MFOPGqJj8HXU4SV0mJekMcEa7HPFOHHHDYg9hV912tajiWWD@wLFnKY1OlRfi@VMOPIFw11XAVRP6tGvnBZj1VN@tFQdqVJCVO/eGc2pklcAm1bptFqAhfydP5AjAlMXXpekZFs2ue5oiWZ3GZa7osZdL0SmNcA/YPqX2MIxqin6Uu3VMrjdfo08spdXFKwwzOcEEPkvL7nf@JAoMdu4h9gwY0AWwdURN7NLfp0aKBQHRK1KabrRzGGM3pjQlDS4Z3QnqiMqFnHAsdCQ22Mr4@Ofpbp6LxU@TPkrHGTiP@Bg) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 32 bytes ``` โ€šร„ยข3xIล’ยฑEล’ยชยฌยงโ€šร„รดโˆšยงโ€šร‡รœฦ’รœkโ€“ยบโ€“ยบ`0โˆšร‡9"ยฌยฅโ€šร„ยขโ‰ˆรฆHโ€“โ‰ค2โˆšยฅvyโ‰ˆโˆโˆšรŸK ``` [Try it online!](https://tio.run/##AWcAmP8wNWFiMWX//@KAojN4Sc6xRc67wqTigJnDpOKChsSGa9C80LxgMMOCOSLCtOKAosW@SNCyMsO0dnnFuMOnS///Q82JzIpvZMyTZc2UzZ0gzIZHzYDMkc2nb82cbM2UzK/NimbNic2N "05AB1E โ€šร„รฌ Try It Online") ]
[Question] [ *Note: This challenge only allows answers in compiled languages* ## Task Your task is pretty simple, make two different programs that when compiled result in the same output. ## Scoring Here is where the fun comes in. Your score will be the number of unique **bytes** present in exactly one program. For example if your two programs (encoded in [IBM Code page 437](https://en.wikipedia.org/wiki/Code_page_437)) are ``` โ˜ปโ˜ปProgram A ``` and ``` โ˜บProgram B ``` The characters that are in exactly one program are ``` โ˜ปโ˜บAB ``` Thus the score is 4. Note that `โ˜ป` appears twice in the first program but is only counted once. Your goal is to get the highest score, the highest score possible is 256. [Here](https://tio.run/nexus/python2#S7QtTi3RUFJSKi/KLEnVUPJIzcnJ11Eozy/KSVFU0gRKaHIloahRR1GiDlLxv6AoM69EISc1T0MjsSZJU1cjUS1JU/P/fwA) is a scoring program that works for ASCII encoded programs. ## Stipulations * Every byte in both programs should be able to be replaced with a different byte causing either the program to compile into a different result or fail to compile all together. Removing any byte should do the same. * You may use any compilation flags as long as both programs are run with the same flags. * The resulting compilation should be static (i.e. should not vary from run to run), if results vary from machine to machine indicate the machine it is intended to run on. * The output of compilation should be byte for byte identical not "equivalent" or "similar enough". * The output of the compilation should be non-empty * Warnings/Errors need not be the same between compilations * If either the programs or the compilation include unprintable characters be sure to include a hexdump. Although it is not technically required. [Answer] # Perl, score 254 + 2 = 256 Here's a hex dump of one program: ``` 00000000: 6c65 6e67 7468 2700 0102 0304 0506 0708 length'......... 00000010: 090a 0b0c 0d0e 0f10 1112 1314 1516 1718 ................ 00000020: 191a 1b1c 1d1e 1f20 2123 2425 2628 292a ....... !#$%&()* 00000030: 2b2c 2d2e 2f30 3132 3334 3536 3738 393a +,-./0123456789: 00000040: 3b3c 3d3e 3f40 4142 4344 4546 4748 494a ;<=>?@ABCDEFGHIJ 00000050: 4b4c 4d4e 4f50 5152 5354 5556 5758 595a KLMNOPQRSTUVWXYZ 00000060: 5b5d 5e5f 6061 6263 6465 6667 6869 6a6b []^_`abcdefghijk 00000070: 6c6d 6e6f 7071 7273 7475 7677 7879 7a7b lmnopqrstuvwxyz{ 00000080: 7c7d 7e7f 8081 8283 8485 8687 8889 8a8b |}~............. 00000090: 8c8d 8e8f 9091 9293 9495 9697 9899 9a9b ................ 000000a0: 9c9d 9e9f a0a1 a2a3 a4a5 a6a7 a8a9 aaab ................ 000000b0: acad aeaf b0b1 b2b3 b4b5 b6b7 b8b9 babb ................ 000000c0: bcbd bebf c0c1 c2c3 c4c5 c6c7 c8c9 cacb ................ 000000d0: cccd cecf d0d1 d2d3 d4d5 d6d7 d8d9 dadb ................ 000000e0: dcdd dedf e0e1 e2e3 e4e5 e6e7 e8e9 eaeb ................ 000000f0: eced eeef f0f1 f2f3 f4f5 f6f7 f8f9 fafb ................ 00000100: fcfd feff 273d 3d32 3533 6f72 2078 2829 ....'==253or x() ``` and here's the other program: ``` "\\" ``` Perl isn't normally thought of a compiled language, but it is; it's first compiled to bytecode, and then the bytecode is executed. You can apply a filter on the bytecode (e.g. to dump it rather than running the program) using the `-MO` option. Both these programs compile into the following bytecode (disassembled using `-MO=Terse`): ``` LISTOP (0x564fcd99f020) leave [1] OP (0x564fcd99f148) enter COP (0x564fcd99f068) nextstate OP (0x564fcd99f100) null [5] ``` ## Explanation Perl replaces all statements with no effect (such as string literals on their own) with a hardcoded "statement with no effect" statement in the resulting bytecode, so both programs compile to the same thing. In terms of character replacements, replacing most of the characters from program 1 with apostrophes will cause it to fail to compile (or replacing the apostrophes with `0`). In program 2, replacing the any character with `c` will cause the program to fail to compile (as `\c` takes an argument). As for character deletions, the first version of this answer predated the "radiation hardening rule" (that deleting any character must change the behaviour of the program). This updated, radiation-hardened version works via the use of a checksum; if deleting a character doesn't outright cause a syntax error, the code will compile into a call to the nonexistent function `x`. The Perl compiler doesn't optimize out the call in the case where it's made (and in general doesn't seem aware that the function doesn't exist), and thus the output is different. However, Perl's constant folder is capable of seeing that the un-mutated program is a single statement with no effect, and thus optimizes the whole thing down into a single statement like before. I originally misread the question as counting only unique characters from one program, and tried to optimize for that. Clearly, program 2 needs to contain at least one character in order to generate the "statement with no effect" opcode, meaning that the best possible score in one program is 255. I haven't yet found a way to include a backslash in program 1 in such a way that the character immediately following it can't be replaced in such a way as to cause the program to break, but it wouldn't surprise me if it were possible (leading to a score of 255 + 1 = 256). [Answer] # C, 231 ### Program A ``` i[]={'','','','','','','',',' ',' ',' ','','','','','','','','','','','','','','','','','','',' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~','','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ','๏ฟฝ'};main(){} ``` Lots of unprintables above. Here's the xxd hexdump: ``` 00000000: 695b 5d3d 7b27 0127 2c27 0227 2c27 0327 i[]={'.','.','.' 00000010: 2c27 0427 2c27 0527 2c27 0627 2c27 0727 ,'.','.','.','.' 00000020: 2c27 0827 2c27 0927 2c27 0b27 2c27 0c27 ,'.','.','.','.' 00000030: 2c27 0e27 2c27 0f27 2c27 1027 2c27 1127 ,'.','.','.','.' 00000040: 2c27 1227 2c27 1327 2c27 1427 2c27 1527 ,'.','.','.','.' 00000050: 2c27 1627 2c27 1727 2c27 1827 2c27 1927 ,'.','.','.','.' 00000060: 2c27 1a27 2c27 1b27 2c27 1c27 2c27 1d27 ,'.','.','.','.' 00000070: 2c27 1e27 2c27 1f27 2c27 2027 2c27 2127 ,'.','.',' ','!' 00000080: 2c27 2227 2c27 2327 2c27 2427 2c27 2527 ,'"','#','$','%' 00000090: 2c27 2627 2c27 5c27 272c 2728 272c 2729 ,'&','\'','(',') 000000a0: 272c 272a 272c 272b 272c 272c 272c 272d ','*','+',',','- 000000b0: 272c 272e 272c 272f 272c 2730 272c 2731 ','.','/','0','1 000000c0: 272c 2732 272c 2733 272c 2734 272c 2735 ','2','3','4','5 000000d0: 272c 2736 272c 2737 272c 2738 272c 2739 ','6','7','8','9 000000e0: 272c 273a 272c 273b 272c 273c 272c 273d ',':',';','<','= 000000f0: 272c 273e 272c 273f 272c 2740 272c 2741 ','>','?','@','A 00000100: 272c 2742 272c 2743 272c 2744 272c 2745 ','B','C','D','E 00000110: 272c 2746 272c 2747 272c 2748 272c 2749 ','F','G','H','I 00000120: 272c 274a 272c 274b 272c 274c 272c 274d ','J','K','L','M 00000130: 272c 274e 272c 274f 272c 2750 272c 2751 ','N','O','P','Q 00000140: 272c 2752 272c 2753 272c 2754 272c 2755 ','R','S','T','U 00000150: 272c 2756 272c 2757 272c 2758 272c 2759 ','V','W','X','Y 00000160: 272c 275a 272c 275b 272c 275c 5c27 2c27 ','Z','[','\\',' 00000170: 5d27 2c27 5e27 2c27 5f27 2c27 6027 2c27 ]','^','_','`',' 00000180: 6127 2c27 6227 2c27 6327 2c27 6427 2c27 a','b','c','d',' 00000190: 6527 2c27 6627 2c27 6727 2c27 6827 2c27 e','f','g','h',' 000001a0: 6927 2c27 6a27 2c27 6b27 2c27 6c27 2c27 i','j','k','l',' 000001b0: 6d27 2c27 6e27 2c27 6f27 2c27 7027 2c27 m','n','o','p',' 000001c0: 7127 2c27 7227 2c27 7327 2c27 7427 2c27 q','r','s','t',' 000001d0: 7527 2c27 7627 2c27 7727 2c27 7827 2c27 u','v','w','x',' 000001e0: 7927 2c27 7a27 2c27 7b27 2c27 7c27 2c27 y','z','{','|',' 000001f0: 7d27 2c27 7e27 2c27 7f27 2c27 8027 2c27 }','~','.','.',' 00000200: 8127 2c27 8227 2c27 8327 2c27 8427 2c27 .','.','.','.',' 00000210: 8527 2c27 8627 2c27 8727 2c27 8827 2c27 .','.','.','.',' 00000220: 8927 2c27 8a27 2c27 8b27 2c27 8c27 2c27 .','.','.','.',' 00000230: 8d27 2c27 8e27 2c27 8f27 2c27 9027 2c27 .','.','.','.',' 00000240: 9127 2c27 9227 2c27 9327 2c27 9427 2c27 .','.','.','.',' 00000250: 9527 2c27 9627 2c27 9727 2c27 9827 2c27 .','.','.','.',' 00000260: 9927 2c27 9a27 2c27 9b27 2c27 9c27 2c27 .','.','.','.',' 00000270: 9d27 2c27 9e27 2c27 9f27 2c27 a027 2c27 .','.','.','.',' 00000280: a127 2c27 a227 2c27 a327 2c27 a427 2c27 .','.','.','.',' 00000290: a527 2c27 a627 2c27 a727 2c27 a827 2c27 .','.','.','.',' 000002a0: a927 2c27 aa27 2c27 ab27 2c27 ac27 2c27 .','.','.','.',' 000002b0: ad27 2c27 ae27 2c27 af27 2c27 b027 2c27 .','.','.','.',' 000002c0: b127 2c27 b227 2c27 b327 2c27 b427 2c27 .','.','.','.',' 000002d0: b527 2c27 b627 2c27 b727 2c27 b827 2c27 .','.','.','.',' 000002e0: b927 2c27 ba27 2c27 bb27 2c27 bc27 2c27 .','.','.','.',' 000002f0: bd27 2c27 be27 2c27 bf27 2c27 c027 2c27 .','.','.','.',' 00000300: c127 2c27 c227 2c27 c327 2c27 c427 2c27 .','.','.','.',' 00000310: c527 2c27 c627 2c27 c727 2c27 c827 2c27 .','.','.','.',' 00000320: c927 2c27 ca27 2c27 cb27 2c27 cc27 2c27 .','.','.','.',' 00000330: cd27 2c27 ce27 2c27 cf27 2c27 d027 2c27 .','.','.','.',' 00000340: d127 2c27 d227 2c27 d327 2c27 d427 2c27 .','.','.','.',' 00000350: d527 2c27 d627 2c27 d727 2c27 d827 2c27 .','.','.','.',' 00000360: d927 2c27 da27 2c27 db27 2c27 dc27 2c27 .','.','.','.',' 00000370: dd27 2c27 de27 2c27 df27 2c27 e027 2c27 .','.','.','.',' 00000380: e127 2c27 e227 2c27 e327 2c27 e427 2c27 .','.','.','.',' 00000390: e527 2c27 e627 2c27 e727 2c27 e827 2c27 .','.','.','.',' 000003a0: e927 2c27 ea27 2c27 eb27 2c27 ec27 2c27 .','.','.','.',' 000003b0: ed27 2c27 ee27 2c27 ef27 2c27 f027 2c27 .','.','.','.',' 000003c0: f127 2c27 f227 2c27 f327 2c27 f427 2c27 .','.','.','.',' 000003d0: f527 2c27 f627 2c27 f727 2c27 f827 2c27 .','.','.','.',' 000003e0: f927 2c27 fa27 2c27 fb27 2c27 fc27 2c27 .','.','.','.',' 000003f0: fd27 2c27 fe27 2c27 ff27 7d3b 6d61 696e .','.','.'};main 00000400: 2829 7b7d 0a (){}. ``` ### Program B ``` i[]={1,2,3,4,5,6,7,010,011,013,014,016,017,020,021,022,023,024,025,026,027,030,031,032,033,034,035,036,037,040,041,042,043,044,045,046,047,050,051,052,053,054,055,056,057,060,061,062,063,064,065,066,067,070,071,072,073,074,075,076,077,0100,0101,0102,0103,0104,0105,0106,0107,0110,0111,0112,0113,0114,0115,0116,0117,0120,0121,0122,0123,0124,0125,0126,0127,0130,0131,0132,0133,0134,0135,0136,0137,0140,0141,0142,0143,0144,0145,0146,0147,0150,0151,0152,0153,0154,0155,0156,0157,0160,0161,0162,0163,0164,0165,0166,0167,0170,0171,0172,0173,0174,0175,0176,0177,-0200,-0177,-0176,-0175,-0174,-0173,-0172,-0171,-0170,-0167,-0166,-0165,-0164,-0163,-0162,-0161,-0160,-0157,-0156,-0155,-0154,-0153,-0152,-0151,-0150,-0147,-0146,-0145,-0144,-0143,-0142,-0141,-0140,-0137,-0136,-0135,-0134,-0133,-0132,-0131,-0130,-0127,-0126,-0125,-0124,-0123,-0122,-0121,-0120,-0117,-0116,-0115,-0114,-0113,-0112,-0111,-0110,-0107,-0106,-0105,-0104,-0103,-0102,-0101,-0100,-077,-076,-075,-074,-073,-072,-071,-070,-067,-066,-065,-064,-063,-062,-061,-060,-057,-056,-055,-054,-053,-052,-051,-050,-047,-046,-045,-044,-043,-042,-041,-040,-037,-036,-035,-034,-033,-032,-031,-030,-027,-026,-025,-024,-023,-022,-021,-020,-017,-016,-015,-014,-013,-012,-011,-010,-7,-6,-5,-4,-3,-2,-1};main(){} ``` These compile to precisely the same object code. GCC embeds the filename in the object code, so you'll need to give the files the same name (in different directories). I was worried that the fact that there are no references to `i` might cause the compiler to optimize this variable out completely, but I think that making it a global guarantees that it will be present in the object. This may be verified by inspection of the generated assembly: ``` .file "diffchar.c" .globl i .data .align 32 .type i, @object .size i, 1012 i: .long 1 .long 2 .long 3 .long 4 .long 5 .long 6 .long 7 .long 8 .long 9 .long 11 .long 12 .long 14 .long 15 .long 16 .long 17 .long 18 .long 19 .long 20 .long 21 .long 22 .long 23 .long 24 .long 25 .long 26 .long 27 .long 28 .long 29 .long 30 .long 31 .long 32 .long 33 .long 34 .long 35 .long 36 .long 37 .long 38 .long 39 .long 40 .long 41 .long 42 .long 43 .long 44 .long 45 .long 46 .long 47 .long 48 .long 49 .long 50 .long 51 .long 52 .long 53 .long 54 .long 55 .long 56 .long 57 .long 58 .long 59 .long 60 .long 61 .long 62 .long 63 .long 64 .long 65 .long 66 .long 67 .long 68 .long 69 .long 70 .long 71 .long 72 .long 73 .long 74 .long 75 .long 76 .long 77 .long 78 .long 79 .long 80 .long 81 .long 82 .long 83 .long 84 .long 85 .long 86 .long 87 .long 88 .long 89 .long 90 .long 91 .long 92 .long 93 .long 94 .long 95 .long 96 .long 97 .long 98 .long 99 .long 100 .long 101 .long 102 .long 103 .long 104 .long 105 .long 106 .long 107 .long 108 .long 109 .long 110 .long 111 .long 112 .long 113 .long 114 .long 115 .long 116 .long 117 .long 118 .long 119 .long 120 .long 121 .long 122 .long 123 .long 124 .long 125 .long 126 .long 127 .long -128 .long -127 .long -126 .long -125 .long -124 .long -123 .long -122 .long -121 .long -120 .long -119 .long -118 .long -117 .long -116 .long -115 .long -114 .long -113 .long -112 .long -111 .long -110 .long -109 .long -108 .long -107 .long -106 .long -105 .long -104 .long -103 .long -102 .long -101 .long -100 .long -99 .long -98 .long -97 .long -96 .long -95 .long -94 .long -93 .long -92 .long -91 .long -90 .long -89 .long -88 .long -87 .long -86 .long -85 .long -84 .long -83 .long -82 .long -81 .long -80 .long -79 .long -78 .long -77 .long -76 .long -75 .long -74 .long -73 .long -72 .long -71 .long -70 .long -69 .long -68 .long -67 .long -66 .long -65 .long -64 .long -63 .long -62 .long -61 .long -60 .long -59 .long -58 .long -57 .long -56 .long -55 .long -54 .long -53 .long -52 .long -51 .long -50 .long -49 .long -48 .long -47 .long -46 .long -45 .long -44 .long -43 .long -42 .long -41 .long -40 .long -39 .long -38 .long -37 .long -36 .long -35 .long -34 .long -33 .long -32 .long -31 .long -30 .long -29 .long -28 .long -27 .long -26 .long -25 .long -24 .long -23 .long -22 .long -21 .long -20 .long -19 .long -18 .long -17 .long -16 .long -15 .long -14 .long -13 .long -12 .long -11 .long -10 .long -9 .long -8 .long -7 .long -6 .long -5 .long -4 .long -3 .long -2 .long -1 .text .globl main .type main, @function main: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl $0, %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE0: .size main, .-main .ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609" .section .note.GNU-stack,"",@progbits ``` Note that in program B, (most of) the char values are given in octal. They could have also been given in decimal, but by using octal, we gain a couple of extra characters - `8` and `9` - in the difference set. GCC doesn't seem to like CR, LF and (for obvious reasons) NUL characters inside of single quotes `''`. [Try it online and score](https://tio.run/nexus/bash#hdhrd9vGEQbg7/gViNxYUsqxuAAWCzhyeknttkkbt03vSdoubjZjS1RFJbHruH/dfWcIvYDUE0E@w7PG7A6JZ5dDie/OXnSbyzSmTdLGq/SjNJ50m2Fon8fLB69edenpaXr4@OmTw2Q9/jxMy9o3qe/yLg1NFtK1w0PW6ijjKMdDuvniq0dvDh8crsYYazjU2M8qON9zVHIUtMZqtn5WI2ONivNrjhqO2jtq5KzRc/5wPXJrjtwdN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9PDeeyff7C5Pms35ycXrq@fb8@ReKh9I2m67zfmzh@lmt5Wq8rU4r9eTJD7a9VdHBwcHh/ppIheX/YMuXsVbZZE/TppbU7e7qx@ca1fSl/350VH8vjmWo3i/OT7Whc18oX5gTU96c9Nmz3Bzp2YVUG/XbrH84nWyv1/@/927/wE). [Answer] # Python, score ~~16~~ ~~26~~ ~~27~~ 28 Unique Characters: `-+;132547698<ACBEDFOXabopsx|` [Calculate the score](https://tio.run/nexus/python2#S7QtTi3RUFJSSklNU6jU0LTiUshMUzCwUjCocHJ2dHMxqDGIcK3RMMg3sbEx8DfRrDGxsObiUihKLSktylMwAGrU5ErCYQZEka6uoZGxmam5pYG2hkGSoaGhARBocikUJBYXoxr0v6AoM69EISc1T0MjsSZJU1cjUS1JU/P/fwA "Python 2 โ€“ TIO Nexus") ### Program 1: ``` def y(): if 0: 0xBCAFD0|0XE|(0o4<<0O4)|48; return 0 ``` In program 1, there are 5 spaces in the seemingly blank line. ### Program 2: ``` def y(): if 0:return--12365790+(0b1110000) pass return 0 ``` Some help was found with the [peephole optimiser source code](https://hg.python.org/cpython/file/118d6f49d6d6/Python/peephole.c). Tested with this helper script: [Try it online!](https://tio.run/nexus/python3#rVDLbsMgELzvVyBOoBIErftKk0Of1157i2yDJaTYICCKLfnfXajTJlUP7aErIUY7s8Owk2md9RHZAAfkhk1tW2e2@rOjTABQukE9KVlFl4CatXW6IzjqELkbMMN7TFOb772JmpQfuN7aoEmCNvBdNK0@0RPJJE1UPRsd3@SH@6ilDPsKU@51qbJbSsPTOREAct50kdT012TVn5Op/0ymKADyOu58l768VgAwEz3BGOfVDiTv1TRILJHoHx7vX57EKN6eRyJssVqJ14KOxc0doFxfXiJNM/TTYqYXC3l@cXV5fSvOiKiklCJVzlSG8M2C0ml6Bw "Python 3 โ€“ TIO Nexus") [Answer] # Python 3.6, ~~2 3 5~~ 6 Program 1: ``` z=11_11;a=41_68;y=None;x=5_2_7_9;x*x ``` Program 2: ``` z=1111;a=4168;y=None;x=1111+4168;x*x ``` Python isn't normally compiled, but it does compile its source code into pyc files. Crucially, such compiling includes an optimization pass which changes "1111+4168" into 5279. The underscores serve two purposes: one of them is to add one to the score, and the other is the keep the length, which is stored in the pyc header the same. All of the variable assignments other than 'x' are to keep the `co_consts` in the right order. The `x*x` at the end serves to keep the `co_stacksize` the same. [Answer] # FASM, 254 ``` 00000000h: 64 62 20 27 01 02 03 04 05 06 07 08 0B 0C 0E 0F ; db '............ 00000010h: 10 11 12 13 14 15 16 17 18 19 1B 1C 1D 1E 1F 21 ; ...............! 00000020h: 22 23 24 25 26 28 29 2A 2B 2D 2E 2F 3A 3B 3C 3D ; "#$%&()*+-./:;<= 00000030h: 3E 3F 40 41 43 45 46 47 48 49 4A 4B 4C 4D 4E 4F ; >?@ACEFGHIJKLMNO 00000040h: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F ; PQRSTUVWXYZ[\]^_ 00000050h: 60 61 63 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 ; `acefghijklmnopq 00000060h: 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 ; 00000070h: 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 ; 00000080h: 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 ; 00000090h: A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 ; 000000a0h: B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 ; 000000b0h: C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF D0 D1 ; 000000c0h: D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 ; 000000d0h: E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF F0 27 ; 000000e0h: 0D 64 62 20 27 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB ; 000000f0h: FC FD FE FF 27 ; DB 1,2,3,4,5,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,33,34,35,36,37,38,40,41,42,43,45,46,47,58,59,60,61,62,63,64,65,67,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,99,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 DB 252,253,254,255 ``` no 0x00 and 0x1A because fasm doesn't support the two symbols ]
[Question] [ This is sequel to [this](https://codegolf.stackexchange.com/questions/69770/cheating-a-multiple-choice-test) challenge by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). If you like this challenge, chances are you'll like the other one too. Check it out! --- A multiple choice test with 8 questions each with 4 choices might have the answers: `BCADBADA`. Converted to four different arrays, with true and false if the current letter is the answer, it will look like this ``` Q#: 1 2 3 4 5 6 7 8 B C A D B A D A A: [0, 0, 1, 0, 0, 1, 0, 1] B: [1, 0, 0, 0, 1, 0, 0, 0] C: [0, 1, 0, 0, 0, 0, 0, 0] D: [0, 0, 0, 1, 0, 0, 1, 0] ``` This can be compressed using a bit of logic. Each of the choices `A`, `B`, `C` and `D` can be represented by two true/false values shown below: ``` A: 1 0 B: 0 1 C: 0 0 D: 1 1 ``` Using this logic, we can compress the four vectors above to just two: ``` 1 2 3 4 5 6 7 8 B C A D B A D A [0, 0, 1, 1, 0, 1, 1, 1] [1, 0, 0, 1, 1, 0, 1, 0] ``` That is, the solution to your test is simply: `00110111`, `10011010`. By concatenating these, we get the binary number `0011011110011010`, or `14234` in decimal. Use this decimal value to cheat on your test! **Challenge** Take a number `N` in the (inclusive) range `[0, 65535]`, and output a string with the answer to the multiple choice test. **Test cases:** ``` 14234 BCADBADA 38513 ABBDCAAB 0 CCCCCCCC 120 CBBBBCCC 65535 DDDDDDDD 39253 ABCDABCD ``` The output may be in upper or lower case letters, but you can not use other symbols. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ ~~18~~ 16 bytes ### Code: ``` ลพH+bยฆ2รครธCโ€™cโ€ฐยฑโ€™sรจ ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=xb5IK2LCpjLDpMO4Q-KAmWPigLDCseKAmXPDqA&input=MTQyMzQ) ### Explanation: First, we add `65536` to the number (`ลพH` is a constant defined to `65536`), which is also `10000000000000000` in binary. This is to pad the number with zeroes. Let's take the number `14234` as an example. `14234 + 65536` is equal to `79770`. Which in binary is: ``` 10011011110011010 ``` We remove the first character, resulting in: ``` 0011011110011010 ``` We split the string into two pieces using `2รค`: ``` 00110111, 10011010 ``` After that, we zip the array with `รธ`: ``` 01, 00, 10, 11, 01, 10, 11, 10 ``` Converting them back into decimal (using `C`) results in: ``` 1, 0, 2, 3, 1, 2, 3, 2 ``` Now, we only need to index it with the string `cbad`. The compressed version for this string is `โ€™cโ€ฐยฑโ€™`, which can also be tested [here](http://05ab1e.tryitonline.net/#code=4oCZY-KAsMKx4oCZ&input=MTQyMzQ). Finally, we get the characters at the index of the above array. For the above example, this results in: ``` 1, 0, 2, 3, 1, 2, 3, 2 b c a d b a d a ``` [Answer] ## JavaScript (ES6), ~~55~~ 48 bytes ``` f=(n,i=8)=>i--?"CBAD"[n>>i&1|n>>i+7&2]+f(n,i):'' console.log(f(14234)); // BCADBADA console.log(f(38513)); // ABBDCAAB console.log(f(0)); // CCCCCCCC console.log(f(120)); // CBBBBCCC console.log(f(65535)); // DDDDDDDD console.log(f(39253)); // ABCDABCD ``` ### Non-recursive version (55 bytes) Using a regular expression, we can do: ``` n=>"76543210".replace(/./g,i=>"CBAD"[n>>i&1|n>>+i+7&2]) ``` [Answer] # Python 2, 53 bytes ``` f=lambda n,k=8:k*'_'and f(n/2,k-1)+'CBAD'[n>>7&2|n&1] ``` Test it on [Ideone](http://ideone.com/ZcvrzF). [Answer] ## [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly, 24 DECLEs (30 bytes) This code is intended to be run on an [Intellivision](https://en.wikipedia.org/wiki/Intellivision). (1) A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. The actual function is 24 DECLEs long, starting at `$4809` and ending at `$4820`. The CPU registers are however 16-bit wide, so it will support any input value in `0x0000` .. `0xFFFF`. ``` ROMW 10 ; use 10-bit ROM ORG $4800 ; start program at address $4800 4800 0002 EIS ; enable interrupts (to enable display) ;; ---- usage example 4801 0001 SDBD ; load parameter in R0 4802 02B8 009A 0037 MVII #14234, R0 ; 4805 0004 0148 0009 CALL cheat ; call function 4808 0017 DECR PC ; infinite loop ;; ---- 'Cheat Your Test' function cheat PROC 4809 0082 MOVR R0, R2 ; copy R0 to R2 480A 0040 SWAP R0 ; swap LSB/MSB in R0 480B 02BC 0214 MVII #$214, R4 ; R4 = pointer to 2nd row of screen memory 480D 01DB @@loop CLRR R3 ; clear R3 480E 0052 RLC R2 ; extract highest bit of R2 to carry 480F 0053 RLC R3 ; inject carry into R3 4810 0050 RLC R0 ; extract highest bit of R0 to carry 4811 0053 RLC R3 ; inject carry into R3 4812 0001 SDBD ; add pointer to lookup table to R3 4813 02FB 001D 0048 ADDI #@@tbl, R3 ; 4816 029B MVI@ R3, R3 ; read character value 4817 0263 MVO@ R3, R4 ; write it to screen memory (also does R4++) 4818 037C 021C CMPI #$21C, R4 ; 8 characters written? ... 481A 0225 000E BLT @@loop ; ... if not, jump to @@loop 481C 00AF JR R5 ; return 481D 011F 0117 @@tbl DECLE $11F, $117 ; characters 'B', 'C', 'A' and 'D' 481F 010F 0127 DECLE $10F, $127 ; in white, using the built-in font ENDP ``` ### Output [![screenshot](https://i.stack.imgur.com/YwEWM.gif)](https://i.stack.imgur.com/YwEWM.gif) --- (1) Granted that at least [one compiler, several emulators](http://spatula-city.org/~im14u2c/intv/) and copyright-free [replacement ROM files](http://knox.ac.free.fr/files/intv-mini-roms.zip) are freely available, I think that it doesn't infringe any PPCG submission rule. But please let me know if I'm wrong. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` dโน+โนBZแธ„แธŠแป‹โ€œBADC ``` [Try it online!](http://jelly.tryitonline.net/#code=ZOKBuSvigblCWuG4hOG4iuG7i-KAnEJBREM&input=&args=MTQyMzQ) or [verify all test cases](http://jelly.tryitonline.net/#code=ZOKBuSvigblCWuG4hOG4iuG7i-KAnEJBREPigJ0KxbzDh-KCrFnigqxq4oCcwrbCtg&input=&args=MTQyMzQsIDM4NTEzLCAwLCAxMjAsIDY1NTM1LCAzOTI1Mw). ### How it works ``` dโน+โนBZแธ„แธŠแป‹โ€œBADC Main link. Argument: n dโน Divmod 256; yield [n : 256, n % 256]. +โน Add 256; yield [n : 256 + 256, n % 256 + 256]. B Binary; convert both integers to base 2. Z Zip; group the quotient bits with corresponding remainder bits. แธ„ Unbinary; convert from base 2 to integer. แธŠ Dequeue; discard the first integer, which corresponds to the dummy value introduced by adding 256 to quotient and remainder. แป‹โ€œBADC Index into that string, mapping [1, 2, 3, 0] to "BADC". ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 22 bytes ``` ri2bG0e[8/:.{1$=)^'A+} ``` [Try it online!](http://cjam.tryitonline.net/#code=cmkyYkcwZVs4LzouezEkPSleJ0ErfQ&input=MTQyMzQ) ### Explanation Powered by magic... The mapping of bit pairs to letters in this challenge is a bit arbitrary. If we represent `ABCD` by `0, 1, 2, 3` (so we can just add them to the character `A`) then we want the following mapping: ``` i1 i2 o 0 0 2 0 1 1 1 0 0 1 1 3 ``` This mapping can be computed with a magical little formula: `((i1 == i2) + 1) ^ i1`, where the equality check returns `0` or `1`. Check out the following table, where each column corresponds to one input, each row corresponds to one operation, and each cell will show the stack at that point: ``` [i1, i2]: [0, 0] [0, 1] [1, 0] [1, 1] copy i1: [0, 0, 0] [0, 1, 0] [1, 0, 1] [1, 1, 1] equals: [0, 1] [0, 0] [1, 0] [1, 1] inc: [0, 2] [0, 1] [1, 1] [1, 2] xor: [2] [1] [0] [3] ``` With that in mind here is the full breakdown of the source code: ``` ri e# Read input, convert to integer. 2b e# Get binary representation. G0e[ e# Pad to 16 bits with zeros. 8/ e# Split into two halves of 8 bits each. :.{ e# For each pair of bits, i1 and i2... 1$ e# Copy i1. = e# Check equality with i2. ) e# Increment. ^ e# Bitwise XOR. 'A+ e# Add to 'A' } ``` An alternative solution with the same byte count which is decidedly less magical: ``` ri2bG0e[8/z2fb"CBAD"f= ``` And in case it's useful to anyone, if you turn the `i1` and `i2` bits back into a single number (i.e. when you want the mapping `0 -> 2, 1 -> 1, 2 -> 0, 3 -> 3`) this can be computed even more easily as `(~n - 1) & 3` or `(~n - 1) % 4` if your language gets modulo on negative values right. I think this can be written concisely as `3&~-~n` in many languages. In CJam this turns out to be a byte longer, because of the additional conversion back from base 2. [Answer] # PHP, 57 Bytes ``` for($i=8;$i--;)echo CBAD[($n=$argv[1])>>$i+7&2|$n>>$i&1]; ``` Version without Bitwise operators 70 Bytes ``` for(;$i<8;)echo CABD[($s=sprintf("%016b",$argv[1]))[$i]+$s[8+$i++]*2]; ``` [Answer] # Mathematica, ~~75~~ ~~73~~ ~~68~~ 66 bytes ``` StringPart["CBAD",#+##+1]&@@IntegerDigits[#,2,16]~Partition~8<>""& ``` Thanks to @MartinEnder for saving 2 bytes. [Answer] # Perl, 42 bytes Includes +1 for `-n` Give input on STDIN: ``` perl -nE 'say+(A..D)[2-($`>>8-$_&257)%127]for/$/..8' <<< 39253 ``` Just the code: ``` say+(A..D)[2-($`>>8-$_&257)%127]for/$/..8 ``` [Answer] # JavaScript, ~~113~~ ~~93~~ ~~90~~ 88 bytes *A big thanks to @Neil for helping me save 20 bytes! -3 bytes thanks to @Cyoce* ``` n=>{r="";b=("0".repeat(15)+n.toString(2)).slice(-16);for(i=0;i<8;i++)r+="CBAD"[parseInt(b[i]+b[i+8],2)];return r} ``` ``` n=>{r="";b=(65536+n).toString(2).slice(1);for(i=0;i<8;i++)r+="CBAD"[+b[i+8]+2*b[i]];return r} ``` ``` n=>eval('r="";b=(65536+n).toString(2).slice(1);for(i=0;i<8;i++)r+="CBAD"[+b[i+8]+2*b[i]]') ``` ``` n=>eval('r="";b=n.toString(2).padStart(16,0);for(i=0;i<8;i++)r+="CBAD"[+b[i+8]+2*b[i]]') ``` Sadly, JavaScript lacks functions like `decbin`, `bindec`, and `str_pad` that PHP has. [Answer] # MATL, 16 bytes ``` 16&B8eXB'BADC'w) ``` [**Try it Online!**](http://matl.tryitonline.net/#code=MTYmQjhlWEInQkFEQyd3KQ&input=MTQyMzQ) or [Verify all test cases](http://matl.tryitonline.net/#code=YAoxNiZCOGVYQidCQURDJ3cpCkRUXQ&input=MTQyMzQKMzg1MTMKMAoxMjAKNjU1MzUKMzkyNTM) **Explanation** ``` % Implicitly grab input 16&B % Convert to binary string with at least 16 bits 8e % Reshape the resulting string to have 8 rows and 2 columns XB % Convert each row from binary to decimal 'BADC' % Push this string literal w) % Use the decimal numbers to index into this string (modular indexing) % Implicitly display the resulting string ``` [Answer] # Julia, 73 Bytes Gives a function f taking N as input and returning the answer as string. ``` f(N)=(b=bin(N,16);join(["CBAD"[parse("0b$(b[i])$(b[i+8])")+1]for i=1:8])) ``` [Try it](http://julia.tryitonline.net/#code=ZihOKT0oYj1iaW4oTiwxNik7am9pbihbIkNCQUQiW3BhcnNlKCIwYiQoYltpXSkkKGJbaSs4XSkiKSsxXWZvciBpPTE6OF0pKQpmb3IgTiA9IFsxNDIzNCwgMzg1MTMsIDAsIDEyMCwgNjU1MzUsIDM5MjUzXQogIHByaW50bG4oZihOKSkKZW5k&input=&args=) Depending if a char array counts as string, one can omit the join (**67 Bytes**) ``` f(N)=(b=bin(N,16);["CBAD"[parse("0b$(b[i])$(b[i+8])")+1]for i=1:8]) ``` [Try it](http://julia.tryitonline.net/#code=ZihOKT0oYj1iaW4oTiwxNik7WyJDQkFEIltwYXJzZSgiMGIkKGJbaV0pJChiW2krOF0pIikrMV1mb3IgaT0xOjhdKQpmb3IgTiA9IFsxNDIzNCwgMzg1MTMsIDAsIDEyMCwgNjU1MzUsIDM5MjUzXQogIHByaW50bG4oZihOKSkKZW5k&input=&args=) [Answer] ## R, 110 bytes Came up with a vectorized solution in R. This should probably by golfable by coming up with a smarter conversion int to binary conversion. ``` x=as.integer(intToBits(scan()));cat(LETTERS[1:4][match(paste0(x[16:9],x[8:1]),c("10","01","00","11"))],sep="") ``` ]
[Question] [ In a fictional 2D world, a set of 2D printing instructions for an object can be represented by a list of integers as follows: ``` 1 4 2 1 1 2 5 3 4 ``` Each number represents the height of the object at that particular point. The above list translates to the following object when printed: ``` # # # # # ### ## #### ######### ``` We then fill it with as much water as we can, resulting in this: ``` # #~~~~#~# #~~~~### ##~~#### ######### ``` We define the *capacity* of the object to be the units of water the object can hold when completely full; in this case, 11. Strictly speaking, a unit of water (`~`) can exist at a location if and only if it is surrounded by two solid blocks (`#`) in the same row. ## Challenge Take a list of positive integers as input (in any format), and output the capacity of the object printed when the list is used as instructions. You can assume the list contains at least one element and all elements are between 1 and 255. ## Test Cases ``` +-----------------+--------+ | Input | Output | +-----------------+--------+ | 1 | 0 | | 1 3 255 1 | 0 | | 6 2 1 1 2 6 | 18 | | 2 1 3 1 5 1 7 1 | 7 | | 2 1 3 1 7 1 7 1 | 9 | | 5 2 1 3 1 2 5 | 16 | | 80 80 67 71 | 4 | +-----------------+--------+ ``` [Answer] ## Haskell, 53 bytes ``` f l=sum(zipWith min(scanl1 max l)$scanr1 max l)-sum l ``` *Thanks to Wheat Wizard for saving 1 byte. See also [their shorter 48-byte solution](https://codegolf.stackexchange.com/a/249130/20260).* The expressions `scanl1 max l` and `scanr1 max l` compute the running maximum of the list reading forwards and backwards, i.e. the profile of the water plus land if water would go flow one direction. Orig: ``` # # # # # ### ## #### ######### ``` Left: ``` #~~ #~~~~#~# #~~~~### ##~~#### ######### ``` Right: ``` ~~~~~~# ~#~~~~#~# ~#~~~~### ~##~~#### ######### ``` Then, the profile of the overall picture is the minimum of these, which corresponds to where the water does not leak either direction. Minimum: ``` # #~~~~#~# #~~~~### ##~~#### ######### ``` Finally, the amount of water is the sum of this list, which contains both water and land, minus the sum of the original list, which contains only land. [Answer] ## Jelly, 10 bytes ``` Uยป\Uยซยป\S_S ``` While APL requires multiple parentheses, and J two-character symbols, the algorithm is beautiful in Jelly. ``` ยป\ Scan maximums left to right Uยป\U Scan maximums right to left ยซ Vectorized minimum S_S Sum, subtract sum of input. ``` Try it [here](http://jelly.tryitonline.net/#code=VcK7XFXCq8K7XFNfUw&input=&args=WzIsMSwzLDEsNSwxLDcsMV0). [Answer] # [MATL](https://esolangs.org/wiki/MATL), 14 My Matlab answer translated to MATL. xnor's algorithm. ``` Y>GPY>P2$X<G-s ``` ## Explanation `Y>`: `cummax()` (input is implicitly pushed on the stack) `G`: push input (again) `P`: `flip()` `Y>`: `cummax()` `P`: `flip()` `2$X<`: `min([],[])` (two-argument minimum) `G`: push input (again) `-`: `-` `s`: `sum()` [Answer] # [Haskell](https://www.haskell.org), 48 bytes ``` q!u@(x:t)=q-x+maximum u`min`max q x!t q!_=q ``` ``` (0!) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN40KFUsdNCqsSjRtC3UrtHMTKzJzS3MVShNyM_MSgDyFQoUKxRKuQsV420KuNFsNA0VNqM4zuYmZeQq2Cin5XAoKuYkFvvEKGgVFmXklCnoKaZpAMQWFaIVow1gwSwfI0lEw1lEwMjXVUUAImgFFgHwwAjLM4BIQUWMwaQomzZH1IUubY0qbwow1hplsCpezMNBRAGEzoA5zqJZYiJ9goQIA) [Answer] ## Dyalog APL, 17 bytes ``` +/โŠข-โจโŒˆ\โŒŠโŒฝโˆ˜(โŒˆ\โŒฝ) ``` This is a monadic train that takes the input array on the right. The algorithm is pretty much the same as xnor's, although I found it independently. It scans for the maximum in both directions (backwards by reversing the array, scanning, and reversing again), and finds the vectorized minimum of those. Then it subtracts the original array and sums. The other way to do this would be to split the array at each location, but that's longer. Try it [here](http://tryapl.org/?a=%28+/%u22A2-%u2368%u2308%5C%u230A%u233D%u2218%28%u2308%5C%u233D%29%29%202%201%203%201%205%201%207%201&run). [Answer] # Matlab, 47 Also using xnor's algorithm. ``` @(x)sum(min(cummax(x),flip(cummax(flip(x))))-x) ``` [Answer] ## MATLAB, ~~116~~ ~~113~~ ~~109~~ 106 Bytes ``` n=input('');s=0;v=0;l=nnz(n);for i=1:l-1;a=n(i);w=min([s max(n(i+1:l))]);if a<w;v=v+w-a;else s=a;end;end;v ``` This works by storing the high point on the left, and while iterating through each next point, finds the highest point to the right. If the current point is less than both the high points, then it adds the minimum difference to the cumulative volume. Ungolfed code: ``` inputArray = input(''); leftHighPoint = inputArray(1); volume = 0; numPoints = nnz(inputArray); for i = 1:numPoints-1 currentPoint = inputArray(i); % Current value lowestHigh = min([max(inputArray(i+1:numPoints)) leftHighPoint]); if currentPoint < lowestHigh volume = volume + lowestHigh - currentPoint; else leftHighPoint = currentPoint; end end volume ``` First time I've tried to golf anything, MATLAB doesn't seem the best to do it in.... [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` lambda l:sum(min(max(l[:i+1]),max(l[i:]))-v for i,v in enumerate(l)) ``` [Try it online!](https://tio.run/##dU1BDsIgELz7ij1CxEOpbQ2Jv/BWOWCk6SZAG4Sqr6@UpsaLyWR3dmdndnyHfnB87s7X2Sh7uysw4hEtseiIVS9iWoH7QlK2DigkpYcJusEDsgnQgXbRaq@CJobS@dmj0XDxUYsdwOjRBegIujEGkuS2kLuWMygY8MRSKxPL8zHX8rutGDQM6ixwtviafPEPzZpcb@bET1swz6h@cpdv8gM "Python 2 โ€“ Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 19 bytes ``` $+J(ST0XgZD1`0.*0`) ``` Takes input numbers as command-line arguments. Or, add the `-r` flag to take them as lines of stdin: [Try it online!](https://tio.run/##K8gs@P9fRdtLIzjEICI9ysUwwUBPyyBB8/9/Qy4TLiMuQyA04jLlMuYy@a9blAMA "Pip โ€“ Try It Online") ### Explanation Unlike all the other answers, in Pip it was actually shorter to construct (a modified version of) the ASCII-art and count the water units. We start with `g`, the list of arguments. ``` [1 4 2 1 5 2 3] ``` `0Xg` produces a list of strings of *n* zeros for each *n* in `g`. ``` [0 0000 00 0 00000 00 000] ``` `ZD1` then zips these strings together, using `1` to fill in any gaps in the resulting rectangular nested list: ``` [[0 0 0 0 0 0 0] [1 0 0 1 0 0 0] [1 0 1 1 0 1 0] [1 0 1 1 0 1 1] [1 1 1 1 0 1 1]] ``` `ST` converts this list to a string. The `-l` flag specifies that lists are formatted as follows: every nested list is joined together without a separator, and at the top level the separator is newline. So we get this multiline string--essentially, the diagram of the object, but upside down: ``` 0000000 1001000 1011010 1011011 1111011 ``` We then find all matches of the regex ``0.*0``. This matches the two outermost walls and everything between them on each line. ``` [0000000 001000 011010 0110] ``` `J` joins these strings together into one big string, and `$+` sums it, giving the number of `1`s--which is equal to the amount of water the object can hold. ``` 6 ``` [Answer] # Rust, 112 bytes ``` |l:&[u8]|{(0..).zip(l).scan(0,|a,(b,c)|{*a=(*a).max(*c);Some((*a).min(*l[b..].iter().max()?)-c)}).sum::<u8>()}; ``` [Playground Link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ccfad37f5e1c98ee9ba14e3e0185d497) Basically `min(max(..index),max(index..)-value` [Answer] ## ES6, 101 bytes ``` a=>(b=[],a.reduceRight((m,x,i)=>b[i]=m>x?m:x,0),r=m=0,a.map((x,i)=>r+=((m=x>m?x:m)<b[i]?m:b[i])-x),r) ``` Another port of @xnor's alghorithm. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` แน˜ษ–โˆดแน˜?ษ–โˆดรžโˆตฮตโˆ‘ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4bmYyZbiiLThuZg/yZbiiLTDnuKItc614oiRIiwiIiwiWzFdXG5bMSwzLDI1NSwxXVxuWzYsMiwxLDEsMiw2XVxuWzIsMSwzLDEsNSwxLDcsMV1cblsyLDEsMywxLDcsMSw3LDFdXG5bNSwyLDEsMywxLDIsNV1cbls4MCw4MCw2Nyw3MV0iXQ==) ]
[Question] [ 5 Years ago, [this](https://www.youtube.com/watch?v=aOT_bG-vWyg) happened, and then it became sort of a meme. # Challenge The Challenge today is, to check if a "[magic square](https://en.wikipedia.org/wiki/Magic_square)" is a valid parker square. What is a **Real Magic square**? * All the numbers must be natural or sometimes 0 * The sum of rows, columns and diagonals must be same. * There must be no repeating numbers What Matt tried to achieve is a real magic square but with all the numbers being squares. But what he did is a semi-magic square, sometimes called [The Parker Square](http://theparkersquare.com/). What **is** a valid parker square (rules made by me)? * It must be a \$3\times3\$ "magic square" * There **must** be at least one number that appear twice in the square * The rows and columns must add up to the same number * At least one diagonal must add up to the same number too. * Each number must be the square of an integer # Rules * Input must be given in a form of a list (flat or 2-dimensional), or just 9 inputs from top left to bottom right * Input is guaranteed to represent a \$3โˆšรณ3\$ square * Output must be a Boolean, 1 or 0, no output or some output * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins! # Examples ``` Classic Parker Square: In: [841, 1, 2209, 1681, 1369, 1, 529, 1681, 841] Out: True 0-Square In: [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Out: 1 Mirrored Square: In: 4, 9, 1, 9, 1, 9, 1, 9, 4 Out: 0 Random Square: In: 1, 2, 4, 3, 4, 9, 8, 9, 0 Out: False Real Magic Square: In: [[8, 1, 6], [3, 5, 7], [4, 9, 2]] Out: Pythagorean triple (by Arnauld): In: [25, 0, 0, 0, 16, 9, 0, 9, 16] Out: false Non integer (Suggested by Luis): In: [841.45, 1, 2209, 1681, 1369, 1, -529, 1681, 841] Out: false Almost real magic square of squares (Suggested by Jonathan): In: [[16129, 2116, 3364], [4, 12769, 8836], [5476, 6724, 9409]] Out: 0 ``` Disclaimer: I put magic square in quotes, because most people don't think it is a magic square if the numbers repeat. But it doesn't mean it is easy to make a "magic square" with only a few numbers repeating, all squares and on of the diagonals working. Good work Matt! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 23 bytes -1 byte thanks to [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy)! ``` โˆšร‡โ€šร„รถล’ยตโˆšร–\ยฌโ„ขIโˆšโˆยฌยดOโˆšรฃ}โˆšโ€ Iร€รบโˆšรชโˆšรดโˆšรคsโˆšร–ยฌโ‰คPP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cNOjhlnnth5ujTm0yvPwjkOr/Q931x5e4Hl6zuEJh2ce7io@3HpoU0DA///R0RYmhjoKQGRkZGAZq6MQbWhmARIwNrMEkiABUyMQCywKVBsbCwA "05AB1E โ€šร„รฌ Try It Online") or [Try all cases!](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/2/3DTo4ZZ57Yebo05tMrz8I5Dq/0Pd9ceXuB5es7hCYdnHu4qPtx6aFNAwH@gWi6u8ozMnFSFotTEFIXMPK6UfC4FBf38ghJ9iJFQCs0WGwUVsNq81P/R0RYmhjoKQGRkZGAZq6MQbWhmARIwNrMEkiABUyMQCywKVBsbyxUdbaCjAEIgWSxMkAoTHQWYfkuw8RCzwaImYBUgK0FsoLAxkIaqsACrgJhhAdZoBlVhqqNgDmJCTDYCqzAyRbHd0AxqigHEdjOgIgA) **Commented:** ``` โˆšร‡โ€šร„รถ # pair the input with its reverse ล’ยต } # map over each of them: โˆšร–\ # take the main diagonal ยฌโ„ข # append this to the input Iโˆšโˆ # push the input transposed ยฌยด # and concatenate this to the list O # sum rows, columns and the diagonal โˆšรฃ # are all sums equal? โˆšโ€  # is one of the two results a 1? Iร€รบ # push the input and flatten it โˆšรช # triplicate โˆšรดโˆšรค # does the uniquified flat input not equal the flat input? s # swap to flattened input โˆšร–ยฌโ‰ค # for every number: is it a square integer? P # are all square? P # take the product (AND reduction) of all results ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 34 bytes ``` ยทฯ€รฒ"vโˆšรปDโˆ†รตhโ€šร รซ;??โˆšโˆTJvโ€šร รซ$Mโˆ†รตfโ€šรขร ;a?fDUโ€šรขโ€ $โ€šร รœยฌโ‰คAWล’โ€  ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%98%22v%C3%9ED%C6%9Bh%E2%88%91%3B%3F%3F%C3%B8TJv%E2%88%91%24M%C6%9Bf%E2%89%88%3Ba%3FfDU%E2%89%A0%24%E2%88%86%C2%B2AW%CE%A0&inputs=%5B%5B841%2C%201%2C%202209%5D%2C%20%5B1681%2C%201369%2C%201%5D%2C%20%5B529%2C%201681%2C%20841%5D%5D&header=&footer=) Bug fixes make it even messier. [Answer] # JavaScript (ES7), ~~ยฌโ€ 129ยฌโ€ ~~ 120 bytes Expects a flat array of 9 values. Returns **0** for Parker, or **1** for non-Parker. ``` a=>new Set([A,B,C,D,E,F,G,H,I]=a).size>8|a.some(x=>x**.5%1)|[D+E+F,G+H+I,A+D+G,B+E+H].some(x=>x-A-B-C)|E+I!=B+C&E+G!=A+B ``` [Try it online!](https://tio.run/##bY3NasMwEITvfQrl0GJl1yZWYlU5yGDZru1zj8YHkSolJbVKHdpQ/O6uotIfimEZdodvZ570mx52r4eXU9jbBzPt5aRl2pt3cm9OQZuhwhwLLPEOK6yx6aSm0XD4MKkYdTTYZxOcZXpeLqPkOqZjW0AJDoUaGsyggAqVc@ruFw2zUIU5HUtoFlJBflNCtZAZqGln@8EeTXS0j8E@aMUmRuKGsdXWLVxczjXfejNhP57jOkqv/n2vkMzPDHspQbJBsvbqkoXXOVb4eu7ZBMnt9webYVnypzjmX5leY@7w6RM "JavaScript (Node.js) โ€šร„รฌ Try It Online") Or **[117 bytes](https://tio.run/##bY1Pa8JAEMXvfor1YEmcSTCr2a6HDeSfSc4excOia7HYbGlEpeS7p5u1liKB4c3M4zfz3uVFNruv4@fZq/VedQfRSRHV6krW6uxsYkwwxQxzXGGBJVZbIV2/OX6riLfSb/SHcm4iuk2nfjgJ3DaDHFZe7CVe2hZQQvU7Z1DYnkNpnL5XY5FA@pJDMRYxJN1O140@Kf@k35yDs@GLAIkpSmdLMzDer3O2tGZI/zzDbV139HQ9QzJcA2wfgmSBZG7VfOZWh1hu45llQySvjws6wNLwX3DA7j@tBszg3Q8)** if we can just return truthy / falsy values. ### How? We split the input array into 9 distinct variables. ``` A B C D E F G H I ``` At the same time, we turn the input array into a set and check its size. If it's greater than \$8\$, then all values are distinct and this is not a Parker square. ``` new Set([A, B, C, D, E, F, G, H, I] = a).size > 8 ``` We test whether at least one of the values is not a square: ``` a.some(x => x ** .5 % 1) ``` We test the sum of the values in the 2nd row, 3rd row, 1st column and 2nd column. If one of them is not equal to the sum of the values in the 1st row, this is not a Parker square. ``` [D + E + F, G + H + I, A + D + G, B + E + H].some(x => x - A - B - C) ``` **Note**: We don't have to test the 3rd column. It's trivial to prove that we have \$F+I=A+B\$ (and therefore \$C+F+I=A+B+C\$) if all other sums described above are correct. Finally, we test whether both diagonals have an invalid sum: ``` E + I != B + C & E + G != A + B ``` [Answer] # [R](https://www.r-project.org/), ~~106~~ ~~105~~ 104 bytes ``` function(m,`?`=colSums)all(table(m)<2)|sd(c(?m,s<-?t(m)))|any(m^.5%%1)|sum(diag(m))-s&&sum(m[1:3*2+1])-s ``` [Try it online!](https://tio.run/##lY9vS8MwEMbf@ykCsnHRTJq0jZ1s9EP4UrSLXSfFpNX8AYV993pNqaCIOjiO3HN3v@dih9ZVXe@rF2WfG1u516Bssx0Ooat923dg2K7cbete3wbjqNIavHrUDRi6EfTo9lBDaZjbrEqPGqVH1b2DebjKFwuO/WBg36qnsbVyy@VYmzt@k16IS36P0o/2YJS37Ruii4wzgiFEssaHLMYyleso5uJTwznKUkrJOTko7Zqz37DJvydryBiZzL7lbLbzNvzFGO/HDUbSmHG7iDk5gVFEYxkZOSPXM0mcwBC4mMzB5XTD9Cf5BTN8AA "R โ€šร„รฌ Try It Online") Output is reversed\*: `TRUE` if it is *not* a Parker square, `FALSE` otherwise. **Ungolfed code** (still the right way around): ``` is_parker_square= function(m){ twice=any(table(m)-1) # some number must appear twice rowscols=!sd(c(rowSums(m),s<-colSums(m))) # rows & cols must have same sum diags=any(c(sum(diag(m)),sum(diag(m[3:1,])))==s) # at least one diag must have same sum squares=!any(m^.5%%1) # all numbers are squares twice && rowscols && diags && squares } ``` \*Add [+5 bytes](https://tio.run/##jY9vS8MwEMbf@ykypOMCN2nTNuvA0Q/hS9EtZp0Ek07zB/TT1zSlgopSOB5yx3O/52IH5Q6vwr509uDegrDdfjiHXnp16cHgsT3u5UXfBeOo6D/AiyfdgaGbgq5X7gQSWoPudtP6OKR0LbSGlXm8qbOsQJepPpPggoGTEs@jA8fG3EsoscYtfYg7vw4AI7xV75HdVAWSWIzlu/jgzdiWfJeGNfuaRR/FklJyTbwN3dVfxHyJSUKFZIr4odUcchba/QcYT452JGXSuNokzZcCmhTJE6BGsp0xbCmAxa18roJP6dNX@HfG8Ak) to output `TRUE` for a Parker square. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ยฌโ€ 27ยฌโ€ ~~ 25 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page) ``` S;ยฌรŸfโˆ†รซโ€šยฑร†,Uโ‰ˆรญDยทโˆยข$โ€šร‡ยจยฌรŸโˆ†โ‰คยทโˆซโˆยปรŸโˆšรœยฌโ‰คยปยถยปรŸโ€šร…โˆFQโˆ†รซ ``` Parker: `0`, non-Parker: `1` - just like it always seems to be! ;p **[Try it online!](https://tio.run/##y0rNyan8/z/Y@tDytGMTH21cpxN6dJLLwx2LVB41rTm0/Nimh7t2nFh@uO3QphPLTix/1LjDLfDYxP///0dHG5oZGlnqKBgZGprpKBgbm5nE6ihEm@goGBqZmwHFLSyMzUAipibmQHkzcyOglKWJgWVsLAA "Jelly โ€šร„รฌ Try It Online")** ### How? ``` S;ยฌรŸfโˆ†รซโ€šยฑร†,Uโ‰ˆรญDยทโˆยข$โ€šร‡ยจยฌรŸโˆ†โ‰คยทโˆซโˆยปรŸโˆšรœยฌโ‰คยปยถยปรŸโ€šร…โˆFQโˆ†รซ - Link: 3 by 3 matrix, M S - column sums (M) ยฌรŸ - row sums (M) ; - (column sums) concatenate (row sums) โˆ†โ‰ค - last four links as a monad - f(M): U - reverse each row (of M) , - (M) pair (reversed row version) $โ€šร‡ยจ - for each: โ‰ˆรญD - diagonals ยทโˆยข - head ยฌรŸ - sums -> [sum(main diagonal), sum(anti-diagonal)] โ€šยฑร† - map with: โˆ†รซ - is invariant under: f - (column-and-row-sums) filter keep (diagonal-sum) ยทโˆซโˆ - any? โˆšรœยฌโ‰ค - is square (vectorises across M) ยปรŸ - logical AND -> 0 or [[is r1c1 square?,...],...] ยปยถ - contains no zero when flattened? ยปรŸโ€šร…โˆ - logical AND with M -> 0 or M F - Flatten -> [0] or flattened M โˆ†รซ - is invariant under: Q - deduplicate ``` [Answer] # [J](http://jsoftware.com/), 59 57 bytes ``` ((<.@%:-:%:)*]>&#~.)@,*3>+/(2#.{.~:])@,1&#.,],&(2{+//.)|. ``` [Try it online!](https://tio.run/##hZDBTgMhEIbvfYqJa7fQTmdhYFmW2E2jiSfjwfvGg7ExXnyAmr76Cqw1jbvGABP4@b@fCe/DFa0OsAuwAgQFIa4twd3Tw/0gxA3tl2EblkGu@64sTiT3uDbdphJc0JFOoY@CLgvCHkvBx01VkfykQS4ebwnmedOJ/3i5eH15@wANOziAieMavNUIcTKrNm6cT0fj2izW/KNF3xRWo6QuJIswsr@qnVrTq5gAg9@Yz3Um1ecYl601QnMGeGrleK/OU7sxcWzEzQRbTbb@@wee577gMsDpZGCdXjLG2dyZ5ibx3puo1raJ1TWcWraqHb4A "J โ€šร„รฌ Try It Online") * `(<.@%:-:%:)` All are perfect squares. * `]>&#~.` Length of uniq is less than length (ie, has repeats) * The remainder first creates a single list of all 8 relevant sums (cols, rows, diagonals): + `],&(2{+//.)|.` Get the `/` diagonal sum of both the input and the input with rows reversed. This gives us both diagonal sums. + `1&#.,` Prepend row sums. + `+/...,` Prepend col sums. * `{.~:]` Turn that list into a boolean list indicating which elements are *not* equal to the first element. * `2#.` Interpret that result as a binary number. * `3>` Check if it is less than 3 (will only be true if at most 1 diagonal fails to match the other sums) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~165 163~~ 161 bytes ``` l=>l.some(e=>e**.5%1)|(I=([c,i=3])=>l[c]+l[c+=i]+l[c+=i]!=l[0]+l[1]+l[2])([0,4])&I([2,2])|[[0],[1],[2],[3,1],[6,1]].some(I)|l.every(e=>l.map(g=>z+=g==e,z=0)|z<2) ``` [Try it online!](https://tio.run/##fVDbaoQwEH3vV6QPLck6lRg1VWh89xtCHsRGsWTXZV0WKv67zcSltLQIw2Ru55yZfDS3Zmovw/n6chrf7dqp1anKxdN4tNSqyh4Ocf6UsIXWiuoWBpUa5gd0ayLvIjV8v4/KaY5Zgk4YRjWHzLDnmmoBPl@074Nvg@@CTgEj6b3Z5Gq2uNje7OUTlV18bM60V9UcqV4pC7PibJnfBFvb8TSNzsZu7GlHtS6yBIg3IXhpgOhEFlhIZek9FnKBUaj6Wa/XueZKGWMPf6gCkURQCiQH8ophBsQTiD0gB4KG0/@EO8CNO6xZBvHthFDN9oAi/6WTyDuUb4RyD4ufhfTbmdkdWQTkz23XLw "JavaScript (Node.js) โ€šร„รฌ Try It Online") This feels too long. Outputs 1 for non-Parker and 0 for Parker. +38 to fix bug [Answer] # [MATL](https://github.com/lmendo/MATL), 30 bytes ``` t!GXdGPXd&hsdXB2>GX^1\=Gun9<vA ``` Input is a 3โˆšรณ3 matrix. Output is `1` if it is a Parker square, `0` if not. [Try it online!](https://tio.run/##y00syfn/v0TRPSLFPSAiRS2jOCXCycjOPSLOMMbWvTTP0qbM8f//aAsTQx0FIDIyMrC0VjA0swBxjc0sgaS1gqkRiAaLAdXFAgA) Or [verify all test cases](https://tio.run/##dU89C8JADN39FXFxqtLkPnrHqaAIXR0cilpR6OCgLlbx39ckXUQRQi7Jy3svdz21l@7YtcOyasp11YzO96Za0rysDriflY9bnD4X3Wr72nS7YDEDDqI8JkAfpDU@ck7gSF6d8V492OUZSCT4LhizGfSsqIKiphPLmBhwlcBwViwoJryg614xl0GRoFcixsh9@KBXZt77eKFanFj3//7xzwfQo4wIRcwYb9UNqRBGCIbPcLZgzBckZ9g81m8). ### Explanation ``` t! % Implicit input: 3โˆšรณ3 matrix. Duplicate GXd % Push input again. Diagonal as a column vector GPXd % Push input, flip vertically. Diagonal as a column vector (this is the % anti-diagonal of the input) &h % Concatenate everything horizontally. This gives a 8โˆšรณ3 matrix whose % columns are: the 3 columns of the input, the 3 rows of the input, the % diagonal and the anti-diagonal s % Sum of eah column. Gives a row vector of length 8 (*) d % Consecutive differences. Gives a row vector of length 7 XB % Convert from binary expansion to number. This treats nonzero values in % the input as 1 2> % Is it greater than 3? (**) This gives false if and only if all entries % in (*) are equal except perhaps the last or second-to-last, but not both % (The result will be false for a valid input) GX^ % Push input. Square root of each entry 1\ % Modulo 1. (***) (All entries give 0 for a valid input) = % Equal? Since the modulus is always less than 1, equality means that all % entries in (***) were 0, as was (**). (This gives a matrix containing % only true for a valid input) Gun % Push input again, unique elements as a row vector, number of elements 9< % Less than 9? (True for a valid input) v % Concatenate everything into a column vector A % All: gives true if all entries are true. Implicit display ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~154~~ 144 bytes ``` lambda a:1-any([len({*a})>8,{(s:={sum(a[i%7:i%5*3:i%4])-a[4]for i in b"\r@@@+?"}).pop()}-{a[0]+a[8],a[2]+a[6]},s,sum(i<0 or i**.5%1for i in a)]) ``` `@` represents unprintables chars Outputs 1 for Parker, 0 for not Parker [Try it online!](https://tio.run/##dVBRa8MgEH7P2x7GXqVQiKkp0aixYd1@iJVhWcMCbRpM@lBCfnvmGdaNrRP5OL@77zvv2mv/cW5y1bqp2u6moz3t3y2yJU1tc4318dDEQ2JH/KLIEHfldugup9jqelmU9VIkuUducGo1N9XZoRrVDdovdu7h8Wn1uhjxuj23MR7TwerMrKxWhljNIJJmJB0Bu/o5Q6BNkrVY0puNxQZP/aHru7feXQ5oi7RWnBLkL2PZxgdSwTOXm0AKduN8nSFIZwTdv8ZE0Wxd2WM3e3OCZp9fyMEJevqQoDygp1XADJIqlMqQFAQVXyUMkkz8aEzlrJrtZRBzuubi/6nSv2NRSYFjFOzyXPLQkLICJErlnhW88CgLBj/h2QYGhs1a5@wVtvu92DJC/rSubvq4ikMBxtH8xvdEYWV3VdMn "Python 3.8 (pre-release) โ€šร„รฌ Try It Online") A pretty messy solution ^^ ## How it works: * `1-any([...])` will return 1 if all elements are `False` * `len({*a})>8` length of the set of `a`, returne `True` if equal to `9` (no duplicates) * `(s:={sum(a[i%7:i%5*3:i%4])-a[4]for i in b"\r@@@+?"})` create the set of the sums of all lines and columns (name it `s`). I used the impicit conversion of bytes into ints to store the values for the slices. * `{ .pop()}-{a[0]+a[8],a[2]+a[6]}` remove an element of `s` and verify if it is equal to the sum of one diagonal. I used set substraction. If it is present, return the empty set (=> False) else, return itself (=>True) * `s` verify if `s` is empty (=> False if `s` had exactly one element before the pop) * `sum(i<0 or i**.5%1for i in a)` verify both than i is positive and i is a square. If any `i` is lower than 0, `i<0` will be True and the sum will no longer be nul. If any `i` is not a sqare, `i**.5` (sqrt(i)) will have a decimal part and `i**.5%1` won't be nul. ]
[Question] [ # Task 1. Take a single Unicode character as input. 2. Output a program in the same language that also obeys this specification, but which does not contain the input character. 3. If your program is run with input *a*, and then the output program is then run with input *b*, then the program *it* outputs is **ALLOWED** to contain character *a*. However, *b* is still not allowed to appear in this program. In other words, only the input into the most recent incarnation of the program is forbidden to appear. 4. Regardless of what the title may say, standard quine rules apply. Shortest program wins. Program must be at least one byte long. # Example If the program is ABCD. (# is an comment) ``` > slangi "ABCD" A EBCD # "FBCD" "JGGJ" "UGDKJGDJK" are all OK > slangi "EBCD" C ABGD # "EBGD" "UIHDAIUTD" are all OK > slangi "ABGD" B AFCD > slangi "AFCD" Z ABCD ``` Where `slangi` is an interpreter for a fictitious language. [Answer] # CJam, ~~45~~ ~~41~~ ~~38~~ 35 bytes ``` {`"OX$_?"+_l&{{H)+`}/"\He,}":)}&}_~ ``` If the input character is none of the characters `"$&)+,/:?HOX\_`el{}`, this program prints the following, slightly modified version of itself. [Try it online!](http://cjam.tryitonline.net/#code=e2AiT1gkXz8iK19sJnt7SCkrYH0vIlxIZSx9IjopfSZ9X34&input=fg) ``` {`"OX$_?"+_l&{{H)+`}/"\He,}":)}&}OX$_? ``` Otherwise, the program prints the following, obfuscated version of the modification. [Try it online!](http://cjam.tryitonline.net/#code=e2AiT1gkXz8iK19sJnt7SCkrYH0vIlxIZSx9IjopfSZ9T1gkXz8&input=SA) ``` ''r'4'a'j'6'q'Q'4'='q'~'8'''Z';'='r''A'4'n'Z'w'>''4'L';''8''a'j'6'q'Q]If-~ ``` Note that some of the characters are unprintable. [Try it online!](http://cjam.tryitonline.net/#code=J8KNJ3InNCdhJ2onNidxJ1EnNCc9J3Enfic4J8KNJ8KNJ1onOyc9J3Inwo8nQSc0J24nWid3Jz4nwo8nNCdMJzsnwo8nOCfCjydhJ2onNidxJ1FdSWYtfg&input=SQ) ### How it works ``` {`"OX$_?"+_l&{{H)+`}/"\He,}":)}&}_~ { } Define a code block. _~ Push a copy and execute the copy. ` Push a string representation of the block. "OX$_?" Push that string. +_ Concatenate and push a copy. l& Intersect the copy with the input. { }& If the intersection is non-empty: { }/ For each character of the concat. strings: H) Push 18. + Add it to the character. ` Inspect; turn 'c into "'c". "He,}" Push that string. :) Increment each char. Pushes "If-~" ``` In the first possible output program, we avoid using `~` to be able to use it in the other program. Therefore, instead of `_~`, the modified program ends with `OX$_?`, which works as follows. ``` O Push "" (falsy). X$ Push a copy of the code block. _ Push yet another copy. ? Ternary if; since "" is falsy, execute the second copy. ``` Finally, in the remaining output program, ``` ''r'4'a'j'6'q'Q'4'='q'~'8'''Z';'='r''A'4'n'Z'w'>''4'L';''8''a'j'6'q'Q] ``` wraps all those characters in an array, therefore pushing the following string. ``` "'4aj6qQ4=q~8'Z;=r'104nZw>'4L;'8'j6qQ" ``` `If-` subtracts 18 from each character code, pushing the string ``` "{`\"OX$_?\"+_l&{{H)+`}/\"\He,}\":)}&}OX$_?" ``` which `~` the evaluates. [Answer] ## JavaScript (ES6), 356 340 327 308 303 263 Now using `Function`...```` for the second program: ``` f=(b=y=>[for(x of`f=${f};f()`)x.charCodeAt().toString(y).toUpperCase()])=>alert([`eval('\\${b(8).join('\\')}')`,`eval(String.fromCharCode(${b(10).map(x=>'+9-8'.repeat(x))}))`,'Function`\\x'+b(16).join('\\x')+'```'][1+"0e1v2a3l4(5'6'7)\\".indexOf(prompt())%2]);f() ``` --- The function packs itself into one of three possible programs: 1. The first program calls `eval` on a string literal containing the function's code with each character escaped as an octal value. ``` eval('\146\165...') ``` 2. The second program redirects the browser to a `javascript:` URL containing the function's code with each character URL encoded. This is the only way I could think to evaluate code without using parentheses. It also escapes the letters in 'eval'. ``` window["\x6coc\x61tion"]["hr\x65f"]="j\x61\x76\x61script:%66%75..." ``` 3. The last program is painfully long. It builds the function's code by adding one (`+9-8`) at a time to get each character code. This is to avoid using the octal digits. ``` eval(String.fromCharCode(+9-8+9-8+9-8+9-8...)) ``` The correct program is indexed by searching a carefully constructed string for the input character: ``` [`program_1`,`program_3`,`program_2`][1+"0e1v2a3l4(5'6'7)\\".indexOf(prompt())%2] ``` Here's an ungolfed, untested version. It might not work because of newlines in the source. ``` function f() { // convert source code of current function to bytes var bytes = Array.map(f + 'f()', x => x.charCodeAt()); // pack this function's code in one of three possible programs, // depending on the input var input = prompt(); // PROGRAM 1 - only contains characters: eval(')01234567\ // eval('\146\165...') var source = "eval('\\" + bytes.map(x => x.toString(8)).join('\\') + "')"; // PROGRAM 2 - doesn't contain characters: eval('') // window["\x6coc\x61tion"]["hr\x65f"]="j\x61\x76\x61script:%66%75..." // -> window["location"]["href"] = "javascript:..." if ("eval(')".includes(input)) { source = 'window["\\x6coc\\x61tion"]["hr\\x65f"]="j\\x61\\x76\\x61script:%'; source += bytes.map(x => x.toString(16).toUpperCase()).join('%') + '"'; } // PROGRAM 3 - doesn't contain characters: 01234567\ // eval(String.fromCharCode(+9-8+9-8+9-8+9-8...)) if ('01234567\\'.includes(input)) { source = "eval(String.fromCharCode("; source += bytes.map(x => '+9-8'.repeat(x)).join(',') + '))'; } console.log(source); } f() ``` ]
[Question] [ Given a properly-parenthesized string as input, output a list of all nonempty substrings within matching parentheses (or outside of all parentheses), with nested parentheses removed. Each substring should be the sequence of characters in exactly the same matching parentheses. Substrings should be listed in order of depth, and substrings of the same depth should be listed in the order they occur in the string. Assume the input is always correctly parenthesized. You may assume that the input contains only lower-case ASCII letters and parentheses. Your answer should be a function that, when given a string, returns a list of strings. ## **Examples:** ``` 'a(b)c(d)e' -> ['ace', 'b', 'd'] 'a(b(c)d)e' -> ['ae', 'bd', 'c'] 'a((((b))))' -> ['a', 'b'] 'a()b' -> ['ab'] '' -> [] 'a' -> ['a'] '(((a(b)c(d)e)f)g)h' -> ['h', 'g', 'f', 'ace', 'b', 'd'] 'ab(c(((d)ef()g)h()(i)j)kl)()' -> ['ab', 'ckl', 'hj', 'efg', 'i', 'd'] ``` Fewest bytes wins. [Answer] # JavaScript ES6, 91 ~~93 104 133 148~~ **Edit2** 2 bytes saved thx user81655 **Edit** Using more strings and less arrays Test running the snippet below in an EcmaScript 6 compliant browser ``` f=s=>[...s].map(c=>l+=c<')'||-(o[l]=(o[l]||'')+c,c<'a'),o=[],l=0)&&(o+'').match(/\w+/g)||[] // Less golfed u=s=>{ o=[]; l=0; [...s].map(c=>{ if (c>'(') // letters or close bracket o[l]=(o[l]||'')+c, // add letter or close bracket to current level string l-=c<'a' // if close bracket, decrement level else ++l // open bracket, increment level }) o = o+'' // collapse array to comma separated string return o.match(/\w+/g)||[] // fetch non empty strings into an array } // TEST console.log=x=>O.innerHTML+=x+'\n' ;[ 'a(b)c(d)e' // ['ace', 'b', 'd'] , 'a(b(c)d)e' // ['ae', 'bd', 'c'] , 'a((((b))))' // ['a', 'b'] , 'a()b' // ['ab'] , '' // [] , 'a' // ['a'] , '(((a(b)c(d)e)f)g)h' // ['h', 'g', 'f', 'ace', 'b', 'd'] , 'ab(c(((d)ef()g)h()(i)j)kl)()' // ['ab', 'ckl', 'hj', 'efg', 'i', 'd'] ].forEach(t=>console.log(t +" -> " + f(t))) ``` ``` <pre id=O></pre> ``` [Answer] # Julia, ~~117~~ ~~86~~ 83 bytes ``` v->(while v!=(v=replace(v,r"(\(((?>\w|(?1))*)\))(.*)",s"\g<3> \g<2>"))end;split(v)) ``` It's a regex solution. Ungolfed: ``` function f(v) w="" while v!=w w=v v=replace(v,r"(\(((?>\w|(?1))*)\))(.*)",s"\g<3> \g<2>")) end split(v) end ``` `r"(\(((?>\w|(?1))*)\))(.*)"` is a recursive (`(?1)` recurses group 1) regex that will match the first outermost balanced parentheses (that don't contain unbalanced/reversed parentheses), with the second group containing everything inside the parentheses (not including the parentheses themselves) and the third group containing everything after the parentheses (until the end of the string). `replace(v,r"...",s"\g<3> \g<2>")` will then move the second group to the end of the string (after a space, to act as a delimiter), with the relevant parentheses removed. By iterating until v==w, it is ensured that the replace is repeated until there are no parentheses left. Because matches are moved to the end, and then the next match goes for the first parenthesis, the result will be the string broken down in order of depth. Then `split` returns all of the non-whitespace components of the string in the form of an array of strings (that have no whitespace). Note that `w=""` is used in the ungolfed code to make sure that the while loop runs at least once (except if the input string is empty, of course), and is not needed in the golfed form. Thanks to Martin Bรผttner for assistance with saving 3 bytes. [Answer] # Python, 147 bytes ``` def f(s): d=0;r=[['']for c in s] for c in s: if c=='(':d+=1;r[d]+=[''] elif c==')':d-=1 else:r[d][-1]+=c return[i for i in sum(r,[])if i] ``` Unit tests: ``` assert f('a(b)c(d)e') == ['ace', 'b', 'd'] assert f('a(b(c)d)e') == ['ae', 'bd', 'c'] assert f('a((((b))))') == ['a', 'b'] assert f('a()b') == ['ab'] assert f('') == [] assert f('a') == ['a'] assert f('(((a(b)c(d)e)f)g)h') == ['h', 'g', 'f', 'ace', 'b', 'd'] assert f('ab(c(((d)ef()g)h()(i)j)kl)()') == ['ab', 'ckl', 'hj', 'efg', 'i', 'd'] ``` I like this puzzle; it's very cute! [Answer] # Pyth, 32 bytes ``` fTscR)uX0.<GJ-FqLH`()@[Hdk)Jzmkz ``` [Test suite](https://pyth.herokuapp.com/?code=fTscR%29uX0.%3CGJ-FqLH%60%28%29%40%5BHdk%29Jzmkz&test_suite=1&test_suite_input=a%28b%29c%28d%29e%0Aa%28b%28c%29d%29e%0Aa%28%28%28%28b%29%29%29%29%0Aa%28%29b%0A%0Aa%0A%28%28%28a%28b%29c%28d%29e%29f%29g%29h%0Aab%28c%28%28%28d%29ef%28%29g%29h%28%29%28i%29j%29kl%29%28%29&debug=0) Loosely based off of @Quuxplusone's approach. Builds up space separated lists of the characters at each depth, then splits them and filters out the empty groups. The working list is rotated to keep the current depth's list in front at all times. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~44~~ 41 bytes ``` +`\(((\w|(\()|(?<-3>.))*).(.*) $4 $1 S_` ``` Run with the `-s` flag. Notice the space at the end of the last line. I came up with this solution independently of Glen O but it turns out to be identical. The idea is to match the first pair of parentheses, remove it, and insert its contents at the end of the output (repeatedly). Due to .NET's lack of recursion in regex, I had to use balancing groups which is four bytes longer. If you don't understand the first regex, let me refer you [to my SO answer about balancing groups](https://stackoverflow.com/a/17004406/1633117). Since the input is guaranteed to be correctly parentheses, we can save two bytes by matching `)` with `.` instead of `\)`. Then we simply match the rest of the string with `(.*)`. `$4 $1` first writes back said rest of the string (omitting both the parentheses and their content), and then the content of the parentheses after a space. The `+`` tells Retina to repeat this step until the string stops changing (which only happens once all parentheses have been removed). Empty parentheses will result in two consecutive spaces, so finally we split the entire string on spaces (`S`` activates split mode and the regex is a single space). The `_` option tells Retina to omit empty parts of the split, so we don't include the empty results in the output. [Answer] ## Common Lisp, 160 ``` (lambda(x)(labels((g(l)(cons(#1=format()"~(~{~A~}~)"(#2=remove-if'listp l))(mapcan #'g(#2#'atom l)))))(remove""(g(read-from-string(#1#()"(~A)"x))):test'equal)))) ``` This could be four bytes less if the case conversion wasn't necessary. The idea is to add left and right parenthesis to each side of the input string, treat it as a list, write the top level elements of the list to a string, and then process the sublists the same way. [Answer] # Sed, 90 bytes ``` : s/^(\w*)\((.*)\n?(.*)/\1\n\3_\2/M s/(\n\w*_)(\w*)\)(.*)/\3\1\2/M t s/[_\n]+/,/g s/,$// ``` Uses extended regexes (`-r` flag), accounted for by +1 byte. Also, this uses a GNU Extension (the `M` flag on the `s` command). **Sample Usage:** ``` $ echo 'ab(c(((d)ef()g)h()(i)j)kl)()' | sed -r -f deparenthesize.sed ab,ckl,hj,efg,i,d ``` **Explanation:** Since sed does not support stuff like recursive regexes, manual work is required. The expression is split up into multiple lines, each representing a level of nesting depth. The individual expressions on the same depth (and hence on the same line) are separated by an `_`. The script works through the input string one bracket at a time. The remaining input is always kept on the end of the line that corresponds to the current nesting level. [Answer] ## Haskell, ~~114~~ ~~112~~ 111 bytes ``` ')'%(h:i:t)=("":i):t++[h] '('%l=last l:init l c%((h:i):t)=((c:h):i):t g x=[a|a<-id=<<foldr(%)(x>>[[""]])x,a>""] ``` Usage example: `g "ab(c(((d)ef()g)h()(i)j)kl)()"` -> `["ab","ckl","hj","efg","i","d"]`. I'm going backward through the input string. The intermediate data structure is a list of list of strings. The outer list is per level and the inner list is per group within a level, e.g. `[["ab"],["ckl"],["hj"],["efg","i"],["d"]]` (note: the real list has a lot of empty strings in-between). It all starts with a number of empty strings equal to the length of the input - more than enough, but empty lists are filtered out anyway. The outer lists either rotates on `(`/`)` or adds the character to the front element. `)` also starts a new group. Edit: @Zgarb has found a byte to save. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~21~~ ~~17~~ 16 bytes Thanks to @ovs for -2 Thanks to @ovs for additional -4 ``` ฮฃลพuSQร†ยฎ+ยฉ}'(ยก')ะผ ``` [Try it online!](https://tio.run/##AT0Awv9vc2FiaWX//86jxb51U1HDhsKuK8KpfScowqEnKdC8//9hYihjKCgoZCllZigpZyloKCkoaSlqKWtsKSgp "05AB1E โ€“ Try It Online") The program contains empty strings in the output, which should be ignored. In case that's not allowed it's +3 for `ส’gฤ€`. [Answer] # Python, 161 bytes Here's what I came up with, a one-line functional python solution: ``` p=lambda s:filter(None,sum([''.join([s[i]for i in range(len(s))if s[:i+1].count('(')-s[:i+1].count(')')==d and s[i]!=')']).split('(')for d in range(len(s))],[])) ``` This challenge was inspired by <https://github.com/samcoppini/Definition-book>, which outputs a long string with word defined in parentheticals. I wanted to write code that would give me each sentence, with parenthesis removed. The functional solution is too slow to be effective on long strings, but imperative solutions (like @Quuxplusone's solution) are much faster. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 56 bytes ``` {aโ†โฌโ‹„(ร—โ‰ขยจa)/aโ†a,โŠ‚'\([^()]*\)'โŽ•R{''โŠฃa,โ†โŠ‚โต.Match~'()'}โฃโ‰กโต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzrxUduER71rHnW3aBye/qhz0aEViZr6IMFEnUddTeoxGtFxGpqxWjGa6o/6pgZVq6s/6loMlAJq6mp61LtVzzexJDmjTl1DU732Ue/iR50LgYK1/9PApvY96moGmd275dB640dtE4EmBAc5A8kQD8/g/2kK6okaSZrJGimaqepcEJ5GsiaCBwRJmkAA5WomgRkQHpgEKoCboJmmma6ZAZEEGgOUAgqmaYAENTQ1MjWzNLNzNIGuBAA "APL (Dyalog Unicode) โ€“ Try It Online") A dfn which uses repeated regex replacement, and returns a list of strings (unordered). ]
[Question] [ You may be aware of the famous old rhyme, *["I before E, except after C"](https://en.wikipedia.org/wiki/I_before_E_except_after_C)*. It is a rule taught to aid in the spelling of certain English words. Quoting Wikipedia: > > If one is not sure whether a word is spelled with the digraph *ei* or *ie*, the rhyme suggests that the correct order is *ie* unless the preceding letter is *c*, in which case it is *ei*. > > > It is well known that this rule is not always correct (e.g. `weird`, `leisure`, `ancient`). That is why you will be asked to write an algorithm which accurately determines the spelling of these words. ## Task The following wordlist (found [here](https://pastebin.ubuntu.com/p/cXfzCckRM3/)) consists of 2967 valid words, each of which contains either `ei` or `ie` as a substring. The input is a single word \$ w \$ from the wordlist, **but the `ie`s and `ei`s may be flipped** (all occurrences of `ie` are replaced with `ei`, and vice versa). You are to output a boolean value indicating whether \$ w \$ was flipped. The values do not need to be `True` and `False`, so long as they are consistent. Your program must work correctly for all words, including their flipped counterparts (for a total of 5934 cases to consider). [Here](https://pastebin.ubuntu.com/p/PKcNFFvMbs/) I've provided of a list of all possible test cases. **Note that you are not given this list as input.** You must find a way to determine, for any word in the list, whether or not it is flipped but you cannot take the list itself as input. Just to clarify, no word in the wordlist contains `iei` or `eie` as a substring, nor do a word and its flipped version both exist in the wordlist. As such, these ambiguous cases do not need to be considered. However, words such as `friendlier` or `eighties` which contain more than one occurrence of `ei` or `ie` do exist in the wordlist, in which case both occurrences are flipped (`friendlier` -> `freindleir`, `eighties` -> `ieghteis`). Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. *As a side note, simply applying the "I before E, except after C" rule will be correct for `4954/5934` of the cases.* [Answer] # JavaScript (ES6), 338 bytes A regex-based solution. This can probably be optimized some more. Returns `0` (not flipped) or `1` (flipped). ``` w=>/dief|egh|etei|it?ei/.test(w)|/^(a?th0[rs]|d0st|r?0|h0r?[1s]|w0r)|b0[gt]|c0(l|t[es1]|v)|cl01|d0(f|n[1es]|ra|tie|ty)|0([aijop]|c1|[df]o|g[hln]|na?[fgor]|rlo|[rs]u|s[ahims]|tf|tm)|f0n?[at]|g0g|h0(fe|k|n|re)|ip01|k0n|n0t|no?th0|o0s|r0n1|rel01|rg0st|s0(l|ne|z)|t0n[es1]|u0n|un01|v0(l|n[1es])|yth0/.test(w.replace(/ei|ie/,0)+1)^/ei/.test(w) ``` [Try it online!](https://tio.run/##ZX1NkuS4kt7@nSKtF9NV9lqd1duR9fRKpyjrMWMGESQrSYANgBEZqZwbyEwbLaV76DxzAR3hyd2/zwHmTFtX@AeHAwRB/DgcDuSP4TaUS172@l9iGsM/rr//4/77vzyPS7h@hGn@CDUsH0v9IyzPv9ZQ6pf714/nf/0y/FHnb99z@fNj/FbqR/7j28f8Lf/x/Tfh3L/lrx8v375P9c@Py7cv60f9Hspvf37cvn5c1m@/SYov14/4/bcgsnn4qEv4qI@vH9@@fB@WH2mXRL99fB@vf6aP6fu8xj8/4vDH9@uUsoiv6UOfenyU78O8bJJDvX7U7evH9Vv84/sgT5y@TVKUL9fw8foRP3L4@rHs8tDXb/EjfqsfMWnJP9K38pG/xd9EQIuUJ32LooWN4eP960f9FlHoQ9IdUURuFmml/vrxkDy8Pn7NYV@HS/jyrDUVnn/59vXvv3391@dTjf3jkmKpT@siP78//TS8LKE8y@@6VKA1vCSp8lFgTHkbWkQJy0pisQYywRInIojGGsJSNsVHHpnFZRjDBnQJpaRMnLZ9iPbIho1/5OECOC/hpkUjbHR0sMkTz9gTaQEJGsuBlfmyjMsVz/7rkIddQkcnZjzz7VHAyKMuN3/FerQaU4xXlPo88MvAmxAtkscrZqrrdYkOl7BKGaZgTzFSjGrFTlImk5qmzKpwtD4EJ9TilAOSL5nZERRFi9aPkiKvtL6ERcm0WGWtS4j4HWpoYGyoOLLsCROTuFyLU@k1TPzmAvNEZJWvREN1yPsStLIbFPYmrdS@gIFqdDpYS/K5HUV5D6B95Vclyh31aEFxWNNEVBMapzyp1Ew4pxsRngyqNQykURPq0ahW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g9pDYGi6w/37Tvfv@wJFAxQM6A4ExiLDgzBm3P1amHviX4shMBbPyBLIcxOWvKAmkl@hYjZkUnj15FPVncYkUhcxymYJ0DiStw2J@A2kWgUPVMEDao6ImYMVSXl@H6C/vif9a3Yk5adfi8wC9ctPzz99/a9/@5tork@yZEn56fenbxqWFcWv15T/mygKX@5Pv//L03//29OT3gqQ1vCrKEhfvj99@@Xpt6c/f92G/ct1XXYXenrSzGSxJ1n9p78QOf3yVFTQEvyh@Penn8Pys@Cfl/Dz0z8j9M9P5esvlpf@l4PIPV2/SJ5aVrDqkePTd33OLyrwC6R@95x//n//93/@@//@X/Kruf3973i5f/qnp5///f/8j5///PWHDGBffnrSl396@revPfz1b/8mPH9TS/YFif/@9BPq6Ev5@tPXf/x/ "JavaScript (Node.js) โ€“ Try It Online") (The total number of errors is reported in the *Debug* section of TIO, so you can collapse the *Footer* and *Output* sections if you just want to see that.) ### How? We first get rid of a few edge cases with the following regular expression: ``` /dief|egh|etei|it?ei/ ``` which matches these flipped inputs (for which it's especially hard to tell that they are indeed flipped): ``` diefeid, diefeis, ieghteis, ieghteith, inhomogenieteis, pompiei, soceiteis, wieghteir, wieghteist ``` Otherwise, we replace the first occurrence of either `ei` or `ie` in the input word with `0` and append a trailing `1`: ``` w.replace(/ei|ie/, 0) + 1 ``` We test whether the resulting string is matched by a large regular expression consisting of 23 patterns which are associated to words for which `0` must be `ei`. Examples: * `ath0stically1` is matched by `^(a?th0[rs]|d0st|r?0|h0r?[1s]|w0r)` * `rec0ved1` is matched by `c0(l|t[1es]|v)` * `mad0ra1` is matched by `d0(f|n[1ens]|ra|tie|ty)` * `ineffic0ncy1` is not matched by any expression [Answer] # [Python 3](https://docs.python.org/3/), ~~770~~ 642 bytes ``` import zlib,base64 A=zlib.decompress(base64.b85decode(b'c$_7UYjVRd2!yY)S5qWp)5uZ=uru!IySP90V_|rGMa^-E&VNdB;H1S_2f|8290;)j7yV7J%d^Wq23sMpSzu$qo;^u@D9IyHvE~Y_aZ`-##Ee}q7bO~)P3UUc!*KBGJAe35sGn4Dg*q$hg)r7k+@W(Z-3BEF?F-tdS^~S|4-B0443B>&x}e|ad5xF>_ITn*?1VMqLoI4vi7nBIZ6>m-KsG}&MdPkJnYWr$LA@PyH5$<?F;L6Jv~;{Uj}p&oDC6}95|fNJ')).decode('utf-8').split() g=lambda i:i[:2]=='ei'or i.replace('ei','')in'dst hr hrs hst rn thr thrs thst vn wr brun lorel nucl taip'.split()or any(w in i for w in A) f=lambda i:'eei'in i or'eii'in i or(not('eie'in i or'iei'in i)and(i.index('ei')<i.index('ie')if'ei' in i and 'ie' in i else('ie'in i)^g(i.replace('ie','ei')))) ``` [Try it online!](https://tio.run/##dZ1rtyS7UaY/41/RXnjcpxnbC3zBgMeAPWCwuQxrDGbBzNiTu1JVlWdnprIlZdWuPTZ/ndE1K943dHr1hx1PRYZCSkmpu7ZHuNr1e/8ZjA@nwRv/4ccfPn78OLyYyX/49p9/@Nkwe/O14WUyWfxnt2dpngIrRIRKs3mxo5lGqZXZZEahtlq3DNpew2jTm2kmEYxl4AhM64UImlyDiYEvzGLIi/TIT2Zm2YyKOCY1eIkgpn53o4p@gRD50zCaBdUyQqWT8d46UiuQFO2yDSu@nwN6DeGtHQws7m448bOJodrVTLeUE6RaYhqMiizxxXShV9RpopUUwZd1uk7m8LW5H5GSRwbNUWaeoVNAqTCA/HyaxulMbzEhfF2f9/heTpDCFY0dtnY1MeULpOT6vMdXfTIQcCajRmtPDxKtMIxtiK@IykphmMfCrquUCpWi02pYVGIltguFJHqS36Q8mV08HCWP4psQ0/tmDypEHxLjGFUIijEvzPKdns/Tys8Vho/FWkm8pIuBZM@iB1nWl5f0MiGERMD@5eK4RDc0PxBSeWqkqFU2Gch4WfYIoPK@WKrUIkD/nKEoR@cwkCkSR7IPADjxK/GIMKkr8JJMslpIohflYo7fZhAnI72YYzxIHILRZNTIK4TluzLL9pUt/RiYjtnHIZig2ptjyqNUYwBgVMQzgTdakSXTbEc9I63O5s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kC19KBqSQ35PbAaepSFFiIWj7LSQri4b3DAfpE9AvFBLOIziPeB1ha@D7iU8N0uLzKAInsEIoAiHgF8/PjxO36LPZ4vPv7v9eOn/yxXpn94n6eXb70M3vzx97/2kx8n6TujSSsgXKwjvyg/fOflT36Q4Gi@ePl4@sZvfvgv//blr/7n@N2vP/7t0y9/8Plft08/2P/9x7vbv/7zxy//6U//8Fe/@a37m38Yfv3tv/7mr/5x/OmP/vaPfvmb755/@yff/dM//NGnL3/4@NUPf/Ffxl//6@fvfs//w/bL9/0bn@2Pfr3/5V/96c8ff3v76//4t98M//5/v/37v//X5neff/jyP/7j0z9971/@5fT1P/i7n/7NL35ivvcD/zfr9//q8gefv3G9fHI/fP2vf/mvX/z7t7/307/@2V/87Nth/OWv/@OXv/3@t3/6h9///vd@@ufffPud@e0w/uDtZ3/@m5//8/oHf/FHv/qHz39vf/792/TD9ac///c//vPl23/n/@Z33/yH8Z9ef7H@27@6b/z9T/7ynx5/@4Nv/Le/@NmP/v6Pf3H7jx/9v3/58nfbN@1f/fc//t2f/uC353/8xcdPn75TE@TjHs7f/pOPn2rafvra5cfzsLyMw4fpz6b/9Wff/T8//vFHM3207sP0nXR/7HCKz0TwrY8fP03rxzG@4KuL//2Ha/zTrR9CFEOSQwK39cPdfXhx@/phts7MH9Lthh/SBq72Nj9F08P6@OL@Ibaupg/nKOY/f/Lpa@enKx9NDDMrWBeDP/7@YrUh@WOOH6eq@GlYxy@m76Rv1Vv2@NN/O6So/mk6J1gCjaofEiySiZkx62Qzv758IWIe6beysfivZUH/8F9Lbk/p8bQj4hRznf@zr/3e8K2XDz@O6VazbcrJHz997fem8wcf3BfnL4ZPnz58/ccfXqLq76VjSaLOP6cS87MhDa/@2cdvDVH79/Iq5q8lp6JeVfvJPOeQ/Idt8N6MX492//P/Aw "Python 3 โ€“ Try It Online") Ungolfed ``` l = 'eigh ceiv eing eism eign einv reins reim feit veil seiz neit einf odu eird istic rna igl tera seil eiss reini heists tm rpr isu eip heik dece ceil feint herein fy ido eish nceit ucl rlo olt noe eio dri caf trad rote icat hein iress heife mr ji oly mad iru ifo eia egr cys alb uein reic onot nthe ndee kein isin isan inon iger code cave beig weirs veins veine seine reine deity deists atheist'.split() def f(i): if 'eei' in i or 'eii' in i: return True if 'eie' in i or 'iei' in i: return False if 'ie' in i and 'ei' in i: return i.index('ei')<i.index('ie') # there now can't be 'ei' and 'ie' in i if 'ei' in i: return goodei(i) return not goodei(j) def goodei(i): if i[:2] == 'ei': return True if i in 'brunei lorelei nuclei taipei deist heir heirs heist rein their theirs theist vein weir'.split(): return True for w in l: if w in i: return True return False ``` The basic idea is that most of the time, if 'ie' is in the word, then it's a real word. So the code first gets rid of cases where there are both ei and ie in the word, and then checks if the word (with ie's replaced with ei's) is a real word. The way it checks if a word with ei is a real word, is it uses a big list of strings that are present in only real words. [Answer] # [Python 3](https://python.org), ~~12,707~~ 12,219 bytes (Thanks to ovs and caird coinheringaahing) ``` import zlib,base64 print(input()in str(zlib.decompress(base64.a85decode(b'Gar>nl]U9ZcgCa<oj+@,\'?AS1nH1b=o[Rk#ee2NMWifr*#`LJC+U"3NCT@F/s/+P^XUT5B[lgj.<d`u6:Hb_TF^sV:L\'l=S/;0*L>"WSdNO[-TSF4jrG//I)2&?mN5GuDk*e_R=A\\%t.fC[LC&pH#7g?%!p7&73\\!d/)tIu4%`Y7HlX^It/F:BMTia&e3ae-Y3celTM.]6\\TLJbPK,^(?D(X.bh5A<^KUa(%76YA)Ge/]f)J@<GsX^IT5JFBJrdM/`>?O\\s@r8]YHpbSR2r>cm]VXSSgK/Zfd@X&nGlV?=Za;Fbe`25!/?3&=j]p1R+)V1n;)E*3JF.qr[=S\'&8gq^@"Q@[FOkho\\c:Y["8!Bd3WhGrrf_@ljZA!urR#*n-Dk_NrTdje9\'sib*]PU(e+(4#jV""]]ETlM=WW*"Ch.CMkGjTT4/2.`W->F_\'mT%bif6o!R#Z3Uf&:B+Y)3]/1_;qR`U:C4X\\6a`F!SH0([s@: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Qe_N6CP@QE[7"oX>CSYjcp:7=Ug#9jN.B9I`er^:Dc;T[;p"`_Aj>hEUZ#K@tSgb+b$5GsV1o^]!Y^Mn7fQGJ(iK+m<QkQs&/p\\<V2;RqZ]oFZ4dGn8juc?0\\!?Hm)o-!P9Qg0X>EleK"HLN#hWqrDlD7X5@&:;I>R(\'8#\\`H)`VE8>KD:1?5WNN[L,QHYDKKi>4Khp;\'\\,`\\4"a\\kt\\d!89R2VOme\\4,[]<0U9A#XEejmIIe<=3sMK>XGLkc<I+2;b\'SgTjT$j16pT$C.i9s-^#Q9&GNM[6!]cIr,lhX.19:ur>cdigjUUL;W0\\J;m$m]8J.Qe;p?egMoI1lcW=NdEO4YORd)S")Q+d)jW"8hSIj_2g^Nm<37m3*(rssg.bO,'))).split('\\r\\n')) ``` Searches for the input in a compressed string. Definitely could use some improvement. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~439~~ 418 bytes ``` โ€œยฃษฆ^โ€œPศฎโ€™แธถแธคโ€˜2ยฆร—3โ€˜Fแธƒร˜โตแป‹ร˜Jโพโ€œยปjโฑฎVล’l;โ€œรพรฐxiแน„แธ‚รžแบนแน…ลปรžร‘ษ—รฐแนแน™GmยณLโฝแบ‰แน‡/yฦฅษ แปตแปŠยฃnลผsCยตยฎแปตโพแปศงฦ‡แบฦ‘tNgลปแปŠโบแบˆษ“แปคษผส‚rฦ“ฤ—ษ“แบ“รธb6^แธแธƒ"vแน‚แปดรทฦญVแน–แบ‡ฦฅฦ‘ยครฆโฑฎแบ†แบ“\6SNแธŒ|ยขYแปคแน˜โฝr&Aยตwฦ“TแนƒแนญแนšHแบ‡ยถ(ศฎรงรฐแนร‘Lแบ‰แนƒฤฑ-ร†แบธbCแน„ยขษฒส‚ยงศฆSยณแป‹แบ†uโฝแบกฤฐ*แนยฉรŸยฌแธŒZษ—แบ’ยฆแนซแนƒร‘+แนฌแบ ยฝแน ศทแธ‚รฐศงรงโพxแธฅแบน)แบ’ษ—Jฤฟแธส‹ฦฒแนšษ _yแปด\9j6แธฅแธฦ˜แธฅร‡2Hฦ™แนƒโธแปคยฐแนญยนแธŒแนญรฑ9แบŽยฒแบˆแธyแบ‡ฦ‡[แนƒฤฐแธ…โพยตแปŒรธยง}UแธณแปคแธทCs4แน—ศค7ศฆฤ ฦฒลผแธค,:แนกร‘jb`AOแบ“แธทแปดฦฒYยฝ;แบน5ยฃแบˆแน‚Q:แน€ยนแธ‹4q+ยฃร˜ยณฤ–ฤŠศท#4&ยถCโพรžแบ’ฦฒแนพฤฑ0"ษฒFษ รฐฦแธŠแธ…8yแนชรnล’Nยงiยฒศง2แบ†ฦˆUแปŒแปคแธŸยฅ$ยฒฦjยณแธฅ-ฦคแนขแน†ฦ‘ฤกโฝแนซฦฅG_Bแบˆแน‡ร˜_ยฌรฑแบน)ยคrล€แธฦ‘ส‚แปดแธž`โทยนแธคdฦ˜bแปziยณยฉEยปแธฒยคแธŸโ€œรŸGWโ‚ฌ)ฦŠ6ษฑ8ส‚แน–แน—ยฅแน™ยฎร—ษ“ฦฒโนยปแธฒยค;;โ‚ฌโ€s$$e@ ``` [Try it online!](https://tio.run/##LVPrThNBFP7PUxAkRESiQUSwiRGJQAhBDYJBCRC0MW2QIHihRpNuEYpc1LYJLUahQC9BoGm3Qmd2AZMz28kub3H2ReqZxl9nZ/ac8132W793aipQqbjBn7DnZMaoPrRzbnAT2QmylBtMtEBGxG/QQzeyBZFwtWM0V0Wiz9XO1ZDpdwu54XJ0ykMncS7y8z7kn5GFxBYaHPli2RRbIuLERR65hnyz5xUU@13tDI0vyMPXAjLtJNGkpSuwN10@neuCY8jRBe1Hc93OyjAa32TkzcDLsklNrmagsezE0Ew5pxehWRmz4nQyYoJNto0hWyeWde@Qh9D8I0ryaBj5BhphmZYRSIkMkUVjidpH2wYHkK19hN0RWoWchJ3NNnTC8XsZe4x8AfkR8h@9NAonl@2cyFb5i0h/lfeCVWgWtIZNdpFa2HX0ixBk7cwgFMkdQnhbVbhj5a/QFOyLbTgktKdOHI0oZJAf0A4RaUJ@iEYSzpAn7ZIyLW9nRZakzyNLk3@N1O7E@6y/JOxiVepEyUmOB0jbaIe/TfWwdZmgKsItvXKTlroaIz1AZI@AEyRVUehA4yvo5Bu1B5Qb4WdKQx7ZImEBmb8mGGQ/DSErKjdYqWuuFXncTt2yM1ZS6uVTCsPV28h3RMQ/OdH5gBykLuIh9RE48xDVm7CnAHjoEbUFFfZq6@sm2BMJKFob1opdutTaACddBKiiEVVizq3C9TpH73aSIi81ZCtEqD2A/Lf4Pl2ODkDWB7qdbSE/5fIQkaxy24Z0PehS85PXLN0s6ePtIl@SEWtHmc4PZLpn/F6VS1gkxuFQFJSTkJotB5VdkQuVDWRbE65WUjxTL2RikrL2wQdF2L8PJjIdFJBK9HbPEzd02ChX2pxCO01Smngc0hRkyAlKntRdjf8f8Xio1Q3@mquv996tqB@itvlOLV14RLhG5TFM70cqlRmfd/a5t2bG66PyDw "Jelly โ€“ Try It Online") A monadic link taking a string as input and outputting `0` for incorrect and `1` for correct. Takes advantage of the dictionary in Jelly, but has to add some additional non-dictionary words as remove a few that are in the dictionary. Slow when used repeatedly because the dictionary is generated each time. Now generates the dictionary purely using Jelly (rather than calling Python code directly) [Answer] # [Python 3](https://docs.python.org/3/), 3384 bytes ``` import re,zlib,base64 G,H=["".join(map(chr,zlib.decompress(base64.a85decode(x)))).split()for x in[b'Gar?3CQa?!%"PP@eS)db*<_:.:\\C<.o7j7C6bYeu*^[Y=?7CpeN&,$aRJ0:HPcnf*]g<auqG$d6NX]:OM9:<gI?X".<gEtbcgB8TRe!nBg,QG?+FR.jgR`H-nMCOR(e>rR["sGCjjaHAkSMe#S]7`d73cUEKGOh0hl2pKYh+5uL\\N-U_#nCoV!Dn]i(Q,eK,+?HhOW>JC)p>Tijak_Zn+`5f=$0;nGHbL_f=\'$`a:$T7_OX<Shd8l!7b%tP0%Ca%EsK[K.D6*G9+4ok-($\'"@GfPTLm1qq/`Ng/`he.\\W#pb1=;,UbtsJ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wX3vqiXx9PDxaxDs3bYv/b7m5yqhpehssmwWIy2U9PWD/uuP4vKpLgnZ/G2@8exfViZPb74vvhd5M/uyF/pNy43963rSHKh/nZ9r7XyC//hoSVKgOjNr/@27Itbvl7FoRBxsq43yPHXx7PffjrODVDOcD/iDrSVXyn1UZDqpXMwX@fZLv8MFKGpbTLf0mtl3bbdTLvLeSZZXaf71PaNVueiYDvuvE6ur8Vh4HAXm52aLl3x4EsqLs@n0n2VNoMU5Q59oFc2cl5x0T2Q1rJ1Ism5JNye0xJjToKTGWo7fwn7NnDz@y7Phuk9a/auJkX@tldd/raO2/rgWifxvdVI7mZv/U//8s6R5wfxrMjX/NGc9G/bHsqhX/vkPvzyZy7IQXoZNGImcfJ7oE/OvqfnTf6ynktZGT4kJWz/H3d8iEfPH@UmsdpL@5z@sOamzlFeO/I/leU8P@we0prGMP36yip/4O7S1k8AU5pH//R8 "Python 3 โ€“ Try It Online") You could probably save more bytes with a smarter regex. Basically, just a tradeoff between longer regex and shorter encoded strings. `G` is the list of true cases, `H` is a list of false cases. `s in G or` makes it so if it's a true case, it gets marked as such. `s not in H and` makes it so if it's a false case, it gets marked as such. If neither is true, then it is checked with the regex `/seil|ie(?!ng|sm)|eing|eism/`. Finding a longer regex to match even just like 3-4 more words is certainly worth it, I just didn't want to spend too much time. ]
[Question] [ ## Background Binary Sudoku, also known as [Takuzu](https://en.wikipedia.org/wiki/Takuzu), Binario, and Tic-Tac-Logic, is a puzzle where the objective is to fill a rectangular grid with two symbols (0s and 1s for this challenge) under the following constraints: 1. **Each row/column cannot have a substring of `000` or `111`, i.e. one symbol cannot appear three times in a row, horizontally or vertically.** * A row/column of `1 0 0 0 1 1` violates this rule since it contains three copies of `0` in a row. 2. **Each row/column should contain exactly as many 0s as 1s, i.e. the counts of two symbols must be the same.** * A row/column of `1 0 1 1 0 1` violates this rule since it has four 1s but only two 0s. * Some examples of rows that meet the first two requirements include: ``` [1 0 0 1] [1 1 0 0] [1 1 0 1 0 0] [1 1 0 0 1 0 0 1] ``` 3. (Not relevant to this challenge) The entire grid cannot have two identical rows or columns. Note that the constraint 2 enforces the grid size to be even in both dimensions. Here are some examples of completed Binary Sudoku: ``` (4x4, using 0s and 1s) 1 1 0 0 0 1 1 0 1 0 0 1 0 0 1 1 (6x8, using Os and Xs) O O X O X O X X X X O X O X O O X O X O X X O O O O X X O O X X X X O X O O X O O X O O X X O X ``` ## Challenge Given a positive integer `n`, calculate the number of distinct valid Binary Sudoku rows of length `2n`; that is, the number of permutations of `n` 0s and `n` 1s which do not have `000` and `111` as a substring. The sequence is [A177790](http://oeis.org/A177790), leading 1 removed and 1-based. ## Test cases Here are the first 20 terms of this sequence (1-based): ``` 2, 6, 14, 34, 84, 208, 518, 1296, 3254, 8196, 20700, 52404, 132942, 337878, 860142, 2192902, 5598144, 14308378, 36610970, 93770358 ``` ## Scoring and winning criterion Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest submission in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ลปcแนš$+แธŠ$ยฒS ``` **[Try it online!](https://tio.run/##y0rNyan8///o7uSHO2epaD/c0aVyaFPw////TQE "Jelly โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##ASQA2/9qZWxsef//xbtj4bmaJCvhuIokwrJT/1LFvMOH4oKsR///MjA "Jelly โ€“ Try It Online"). ### How? This code is calculating $$\sum\_{k=\lceil\frac{n}{2}\rceil}^{n}\big(\binom{k}{n-k}+\binom{k+1}{n-(k+1)}\big)^2$$ (where \$k\$ starts at \$0\$ rather than \$\lceil\frac{n}{2}\rceil\$ ...the additional terms are \$0\$ but allows a reversal trick) ``` ลปcแนš$+แธŠ$ยฒS - Link: integer, n e.g. 7 ลป - zero range [0, 1, 2, 3, 4, 5, 6, 7] $ - last two links as a monad: แนš - reverse [7, 6, 5, 4, 3, 2, 1, 0] c - n-choose-k [0, 0, 0, 0, 4, 10, 6, 1] $ - last two links as a monad: แธŠ - dequeue [0, 0, 0, 4, 10, 6, 1] + - add [0, 0, 0, 4, 14, 16, 7, 1] ยฒ - square [0, 0, 0, 16,196,256, 49, 1] S - sum 518 ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 77 bytes ``` n->polcoeff([x,0,1,0]*[0,x,1,0;0,0,1,0;x,0,0,1;x,0,0,0]^(2*n-1)*[1,1,1,1]~,n) ``` [Try it online!](https://tio.run/##LYlLCsMwDESvErKSjAxyoCvjXMS4UEJUAkE2pousenXny8Cbx0z51MV@S5PQ1I4lr1OeRSBuxOSIk4lM22me78Wfz2FPc3rDYNQ6NNHRlfQnxSa5ggZHL6ZSF/2Bdn1nxwMCiohtBw "Pari/GP โ€“ Try It Online") This uses a nice method involving automata and is quite efficient. Consider the automaton that checks if a string satisfies condition one. Besides the initial state and a sink state, it has four interesting states. They signify that everything is still okay, what the last letter was and whether it was the same as the one before. When we replace the `x` with `1` in the matrix that occurs in the program, it describes the possibilities to get from one of these states to another. Usually we should not ignore the initial state, but since it will not be entered again, we can handle it by starting with the vector `[1,0,1,0]` that describes all the states that can be reached after one step. Multiplying this vector with the matrix raised to the `(m-1)`th power gives a vector that tells us how many words of length `m` lead to each state. To get their sum, we multiply with the transpose of the all-one vector. There doesn't seem to be a shorter way to get the sum of the entries of a vector. However, we still have condition two. It could be handled by the automaton, but that would need more states, depend on `n` and be complicated to create. Instead, we change the matrix (and starting vector) to have an `x` for each transition that corresponds to reading a `1`. This way, the computation will not compuite a number, but a polynomial where each term `a*x^k` means that there are `a` words accepted by the automaton (i.e. satisfying condition one) that contain `k` `1`s. For example, for `n=3` (words of length 6) that polynomial is `6*x^4+14*x^3+6*x^2`. So we just have to take the coefficient of `x^n`. [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~123~~ ~~121~~ 119 bytes ``` dc<<<[sD1q]so[sD0q]szz`seq -f"%0.fdsK$1lK-[dsk0>zdsndlk>z[d2>od1-d2<F*]dsFxlklFxlnlk-lFx*/]dsCx1lK+d$1r-lCx+d*+" 0 $1`p ``` [Try the test suite online!](https://tio.run/##HY5BCoMwFET3PcUnpBslNnGtbixuPIIItv6IxZBUfxchpWdP027mMQ8G5n6jNS7uAA8PC29VFKX8nADQpQAg/QLGPfsXPa8OhE1CQV03wCLOVVUNdFX7SC5RJoYwkd5BLOwsiwWp58r0YkDaZBOQLJqtCQOWjUMlsKy6bETqvNlMCms2kZhdkmt9GubI1SFM63PMcgYSuJqe8ffP6vgF "Bash โ€“ Try It Online") --- I've added an explanation of this obscure-looking code at the end of the answer! --- *Shaved off 2 bytes by moving the definitions of macros F and C to the first place they're used, and then another 2 bytes by eliminating two single-quotes that were no longer required after the macros were moved.* This is another, completely different bash solution. Unlike my other (shorter) solution, this one is very fast -- [TIO can compute the value for 1800](https://tio.run/##DcvLCsMgEIXhV5FgN4rtTFZdiJuUbPIIEkjbaSg45NLZiC9v3ZwPDvyvp3xrpbf3PsoDz1n2JjRLWeRzKrd2F7iuJJNGnlwkSRAKyUacQonUh53QUe9HM5OMmRO32Ti5prm1b8gttKTx53jIloztFCiNy1FrxTvAHw) in just under its 60-second limit. Because it uses `dc`, it can handle arbitrarily large integers. The program is based on the binomial coefficient formula from OEIS, which is computed using `dc`. Since loops are such a pain to write in `dc`, I use `seq` instead to unroll the loop into a giant `dc` script to compute the specific number requested, and the `dc` script is then executed. If you're curious (and don't want to wait the 60 seconds at TIO), here's the 1800th term in the sequence: `105480721405474718567404887164925416724980133926539712143845881075284\ 901677297738964136155557073029386229070488343605298871231397783837622\ 530014641802254048917232853438125993571007137377212907244683700588015\ 444444467026455576839621404814982031106756318549435412359204504183866\ 493764320992226326910391777276272125030010740526937030702909019208912\ 640538519829602971756125307274565635138616156817423412863412177199151\ 055856207069714084657310495058759139542900519171388443547871558507573\ 948937524889911140590562675224573515451638678334944353358816689952838\ 021105461897807233248789972151274044554176393928054238190520484054350\ 689148029614875765339478833688339093323537661478061731620258929292671\ 03260220166411748225093782409130224917917686956257637269268564` --- **How it works:** Overall, the structure of the program is: `dc<<<...`, so bash calls dc with a script to run. But the dc script part isn't written out fully; it's actually generated itself by a program (the dc script is customized for the specific argument `n` that was passed in $1 to bash). The dc script starts with a prologue string that's taken verbatim, then a call to `seq` to generate the bulk of the `dc` code, and then a final command to print the result. ***PROLOGUE*** The prologue is: `[sD1q]so [sD0q]sz z` (spaces added for clarity -- they don't affect the code). 1. `[sD1q]so` This defines a macro o which replaces the item at the top of the stack with `1`. It's intended to be called from another macro. In more detail: ``` [ Start a string (to be used as a macro definition). sD Pops an item from the stack and stores it in register D. (I only do this because dc doesn't provide a way to just pop an item from the stack without doing something with it, and storing it an otherwise unused register is innocuous.) 1 Push `1` onto the stack. q Return from this macro and the macro which called it. ] End the string. so Save the macro in register o. ``` 2. `[sD0q]sz` This defines a macro z which replaces the top of the stack with `0`. It works the same way as macro `o` above. 3. `z` This pushes the current stack depth onto the stack. But the stack is currently empty, so it just pushes `0` onto the stack. This initializes the running total for the binomial coefficient sum that we're going to be computing. (The reason for using `z` instead of `0` for pushing a `0` is that a number is coming next; so if I used a `0` to push the 0 here, I'd need to put an extra space after it to separate it from the number coming up. So using `z` saves a byte.) ***CALL TO seq*** The `seq` command is of the form `seq -f %0.f... 0 $1`, where the ... is dc code. This takes each number k from 0 to n (the bash argument $1), replaces %0.f (in the first argument to seq) with k, and writes each of those strings on a line: ``` 0... 1... 2... . . . n... ``` where the `...` at the end of each line is the dc code in the argument to seq. So the loop that one would imagine for computing $$\sum\_{k=0}^n \big( \binom{k}{n-k}+\binom{k+1}{n-k-1}\big)^2$$ is actually unrolled into a simple but long computation for the specific \$n\$ that we have. There are actually two macro definitions embedded in the dc code. (You can often a save a byte in dc by waiting to define a macro until the first time you use it.) I'm going to describe those macros first, because I think it's clearer that way. **The first** of the two embedded macros, `[d2>od1-d2<F*]` computes the factorial of the number at the top of the stack. The macro is saved in register F, so it calls itself recursively: Assumption: The argument x is on the stack when the macro is called. ``` [ Start macro definition d Duplicate the item at the top of the stack, so x is there twice. 2>o Pop that number. If it's < 2, call macro o to pop the extra copy of the argument, and return from F with 1 on the stack. (This is the right answer for x! when x<2.) If it's >= 2: d Pop the argument. 1- Subtract 1. d Duplicate the top of the stack, so x-1 is there twice. 2<F If it's > 2, call F recursively to compute (x-1)!. * Multiply the top of stack, which is (x-1)!, by the 2nd item on the stack, which is x, yielding x! as desired. ] End macro definition ``` The above macro will be saved in register F. **The second** of the two embedded macros computes the binomial coefficient $$\binom{n}{k} = \frac{n!}{k! (n-k)!},$$ where \$k\$ is the number on the top of the stack and \$n\$ is the second number on the stack. The binomial coefficient macro is: `[dsk0>zdsndlk>z[d2>od1-d2<F*]dsFxlklFxlnlk-lFx*/]`, which is saved in register C. (Note that the definition of macro F is actually embedded inside the definition of C.) Here's how C works (when it's called, `k` is at the top of the stack, and `n` is second): ``` [ start of macro d Duplicate k at the top of the stack. sk Pop one k and save it in register k. 0>z Pop the other k, and if it's < 0, call macro z to return 0 from C (which is the right value for the binomial coefficient when k<0). If k >= 0: d Duplicate n (so there are now two n's at the top of the stack). sn Pop one n and save it in register n. d Duplicate n (so there are now two n's again at the top of the stack). lk>z If n<k, call macro z to return 0 from C (which is the right value for the binomial coefficient when k>n). [d2>od1-d2<F*] This is the definition of macro F, as described earlier, embedded in C. d Duplicate the F macro string on the stack. sF Pop one copy of the macro F string, and save it in register F. x Pop the stack to get a copy of the macro string F and call it. So now the n at the top of the stack has been replaced by n! lk Load k. lFx Compute k!. lnlk- Compute n-k. lFx Compute (n-k)! * Multiply k! (n-k)!. / Compute n!/(k! (n-k)!). ] End of macro C. ``` So now let's go back to see what the dc code does with each value k from 0 to n. (Below I've written C(n,k) for \$\binom{n}{k}\$ since TeX doesn't seem to work inside code-sample formatting.) ``` %0.f seq replaces this with k, so k is pushed on the stack. d Duplicate the top of the stack, so k is now on the stack twice. sK Pop one of the k's off the stack and store it in register K. $1 Push n on the stack. ($1 has already been replaced by n due to bash's parameter expansion.) lK Push k back on the stack (load it from register K). - Pop n and k, and push n-k onto the stack. [dsk0>zdsndlk>z[d2>od1-d2<F*]dsFxlklFxlnlk-lFx*/] This is the embedded defintion of C, with the definition of F embedded in it. d Duplicate the string defining C, so it's there twice. sC Save the macro for C in register C. x Call the macro C. This pops k and n-k, and replaces them with C(k,n-k). 1 Push 1. lK Push k. + Compute k+1. d Duplicate k+1 on the stack. $1 Push n. r Swap n and the k+1 that comes next. (So the stack now has k+1 at the top, then n, then k+1 again.) - Replace k+1 and n at the top of the stack with n-k-1. lCx Replace n-k-1 and k+1 with C(k+1,n-k-1). + Add the two binomial coefficients. d* Square the sum of the two binomial coefficients. + Add it onto the running total. ``` The above is done for each k, so after they're all done, the top of the stack contains the value we want. ***EPILOGUE*** The epilogue is fixed code that's hit last. It just consists of the single dc command `p` which prints the result, with a newline after it. It may be worth mentioning that the macro F is redefined every time C is called (because the definition of F is embedded in C), but that's OK -- it's defined the same way every time. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes *a(n) = Sum\_{k=0..n} (C(k, n-k) + C(k+1, n-k-1))^2* ``` Sum[Tr@Binomial[{k,k+1},{#,#-1}-k]^2,{k,0,#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P7g0NzqkyMEpMy8/NzMxJ7o6Wydb27BWp1pZR1nXsFY3OzbOSAcoaKCjXBur9j@gKDOvREHfIV3fISgxLz3Vwcjg/38A "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~50~~ 48 bytes *@Grimmy saved 2 bytes* ``` $_=grep!/000|111/&&y/1//==y/0//,glob"{0,1}"x2x$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ja9KLVAUd/AwKDG0NBQX02tUt9QX9/WtlLfQF9fJz0nP0mp2kDHsFapwqhCJf7/f0MuIy5jLhMuUy6zf/kFJZn5ecX/dQtyAA "Perl 5 โ€“ Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~114~~ \$\cdots\$ ~~93~~ 89 bytes Saved 15 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!!! Saved 4 bytes thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!!! ``` lambda n:sum([*map(bin(i).count,('000','111','1'))]==[0,0,n]for i in range(4**n//8,4**n)) ``` [Try it online!](https://tio.run/##RYoxDgIhEAC/sh27ZOOBWphLeMl5BaeiJLIQ5Apfj6GymSlmyre9spx6cNf@9mm7e5D5sydcdPIFtygY6XDLuzRGZYxRrKy1g4podW4xbFjWkCtEiALVy/OBZ61lmi48TNRHlX@1bI80Q6lRGgpDwDH9AA "Python 3 โ€“ Try It Online") Brute force! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` ๏ผฎฮธ๏ผฉ๏ผฌฮฆ๏ผฅ๏ผธโดฮธโญ†โ—งโ˜ฮนยฒโŠ—ฮธฮฃฮปโ€บโผโ„–ฮน0โ„–ฮน1ฮฃ๏ผฅยฒโ„–ฮนร—ยณ๏ผฉฮป ``` [Try it online!](https://tio.run/##TU7LDoIwELz7FYTTkmCiyI2b@IgJGhL9gQUKNCkU@tDPr1sf0T3NzuzMbN2jqiUK507jZM3FDhVTMEfZolR8NJCjNlCwsTM9HLgwJJ5xglI@CKVxMEdxcDV02r1obArWGtiiZm8WeBwkdLOTthKsoWRvsAOIyKOjYugz97NFoSGXljrJEq5CUn/rOvz6fE3yJ934wDRsiPGf@tTPZM6lbnkX@AQ "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฎฮธ๏ผฉ๏ผฌฮฆ๏ผฅ๏ผธโดฮธ ``` Loop from `0` to `2ยฒโฟ`. ``` โญ†โ—งโ˜ฮนยฒโŠ—ฮธฮฃฮป ``` Generate all binary strings of length `2n`. ``` โ€บโผโ„–ฮน0โ„–ฮน1 ``` Check that the number of `0`s and `1`s is the same. ``` ฮฃ๏ผฅยฒโ„–ฮนร—ยณ๏ผฉฮป ``` Check that the string does not contain 3 repeated digits. [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~86~~ 75 bytes ``` n=$1;e()(egrep "(21*){$n}"|grep -v 111);seq $[10**(2*n)]|e|tr 12 21|e|wc -l ``` [Try it online!](https://tio.run/##S0oszvj/P89WxdA6VUNTIzW9KLVAQUnDyFBLs1olr1apBiygW6ZgaGioaV2cWqigEm1ooKWlYaSVpxlbk1pTUqRgaKRgZAhklicr6Ob8///fBAA "Bash โ€“ Try It Online") The input is passed as argument, and the output is written to stdout. It's very slow -- TIO times out at \$n=5\$. --- **How it works:** The function e is a filter; it only allows a line through if: (a) it doesn't have 3 `1`s in a row, and (b) it has a substring consisting of just `1`s and `2`s, with exactly `n` `2`s. The seq command counts from \$1\$ to \$10^{2n}\$. These are all numbers of at most \$2n\$ digits (except for the \$10^{2n}\$ at the end). We'll count numbers consisting of just `1`s and `2`s, not `1`s and `0`s, since otherwise we wouldn't get numbers starting with `0`s. The filter e is applied, and then it's applied to the same string with the `1`s and `2`s switched around. So a number is allowed through if: (a) it doesn't have 3 `1`s in a row; (b) it doesn't have 3 `2`s in a row; (c) it has a substring consisting of just `1`s and `2`s, with exactly `n` `2`s; and (d) it has a substring consisting of just `1`s and `2`s, with exactly `n` `1`s. Since the numbers being produced are decimal numbers with at most \$2n\$ digits, it follows that we're only letting through numbers with exactly \$n\$ `1`s and exactly \$n\$ `2`s. (The \$10^{2n}\$ at the end is an exception with \$2n+1\$ digits, but it won't have passed through the filter anyway.) Finally, `wc -l` counts the lines remaining. --- The earlier 86-byte version used dc instead of seq, so it can handle arbitrarily large numbers, not limited by bash's maximum integer size. But that's more or less moot because it's too slow anyway. Here's the old version: `n=$1;e()(egrep "(21*){$n}"|grep -v 111);dc<<<"O$1d+^[d1-pd0<f]dsfx"|e|tr 12 21|e|wc -l` You can see more about that one (including a faster version that's 2 bytes longer, counting in base 3 instead of base 10) in the edit history. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 8 bytes *Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/201104/6484)* ``` รร‚cDร€+nO ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8NzDTckuhxu08/z//zcHAA "05AB1E โ€“ Try It Online") Old 13-byter: ``` xLร‰ล“รชส’รผ3โ‚ฌร‹ร‹}g ``` [Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//3hMw4nFk8OqypLDvDPigqzDi8OLfWf//zQ "05AB1E โ€“ Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes ``` +.ร—โจ1,2+/โŠข(-!โŠข)โณ,โŠข ``` [Try it online!](https://tio.run/##DY67SoNREIRfZeyUPzF7OZc9tY2pBOMLBCQ2gdhaC4EETtBCrLVKIVjoE8Q32Rf53WZmd/mWmeXjenr/tFxvHkY/vM1vfPtC43D59@79yBMZZr7/PJ@ehV54/5mEj6tgvB98/@z9y/vv6Vt9@xrfi9ur0Lvr@WIUFHCCJliCkCGzgaUVqOQ4ckxClQhZEiWwSksC1WrVYIU4NuEmjQQ5N@MUUFKyIKClMLVKaForaTb47gORHc1WpyN4iK5C/w "APL (Dyalog Unicode) โ€“ Try It Online") Bubbler's port of the Jelly solution(-14 bytes!). # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ 32 bytes ``` {+/(ร—โจ((โต-1+โŠข)!1+โŠข)+โŠข!โจโต-โŠข)โณ1+โต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6u19TUOT3/Uu0JD41HvVl1D7UddizQVIRSIUARKgSRA/Ee9m4ESvVtr/6cB9T7q7XvU1fyod82j3i2H1hs/apsINDU4yBlIhnh4Bv9PUzAFAA "APL (Dyalog Unicode) โ€“ Try It Online") or [Verify all test cases](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6u19TUOT3/Uu0JD41HvVl1D7UddizQVIRSIUARKgSRA/Ee9m4ESvVtr/6cB9T7q7XvU1fyod82j3i2H1hs/apsINDU4yBlIhnh4Bv9/1Lsq7RBQ72YjAwA "APL (Dyalog Unicode) โ€“ Try It Online") Uses the formula from the Bash answer(which is very, very cool, go upvote it!). Requires `โŽ•IOโ†0` for 0-indexing. -3 bytes from ovs (Converted inner dfn to train, removing assignment to n). ## Explanation ``` {+/{ร—โจ((n-โต+1)!โต+1)+(n-โต)!โต}โณ1+nโ†โต} nโ†โต store input in n โณ1+ range 0..n { } apply the following to it's elements k: (n-โต)!โต k C (n-k) + plus ((n-โต+1)!โต+1) (k+1) C (n-(k+1)) ร—โจ squared +/ sum the resulting array ``` # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 42 bytes ``` {+/(โ‰ข=2ร—+/)ยจ{โต/โจ{โฑ/0 3โˆŠโต}ยจ3+/ยจโต}โ†“โ‰โŠคโณ2*2ร—โต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6u19TUedS6yNTo8XVtf89CK6ke9W/Uf9YLojfoGCsaPOrqAIrWHVhhr6x9aAWI@apv8qLfzUdeSR72bjbSA@kCC/9OApj3q7XvU1fyod82j3i2H1hs/apsItCc4yBlIhnh4Bv9PUzAFAA "APL (Dyalog Extended) โ€“ Try It Online") Brute force method, which is much slower and longer. [Answer] # JavaScript (ES6), ~~80 76~~ 70 bytes A port of the Maple solution presented on OEIS. ``` f=(i,j=i,k=2)=>i*j<0?0:i|j?(k<4&&f(i-1,j,k<3?3:4))+(k&&f(i,j-1,k>1)):1 ``` [Try it online!](https://tio.run/##HYpBDoMgEADvvmIPxuwWbKTai4J@RWOlAQw02vRifTslPc1kMnb6TPu8mde79OGxxKgVGm6V4U7dSPXmYmU1VK352gGdbIpCoykFt9zJeqjbhoih@1duU3e9IGpF1GFDDwpEBx5k4j0JYwRHBjAHv4d1ua7hieOE@eFPSm9@aPR0jtRlZ/wB "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Far too long and *extremely* inefficient! :\ ``` รงA รก รข ร‹ยซรธ56ยครฒ3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=50Eg4SDiIMur%2bDU2pPIz&input=NA) [Answer] # [Ruby](https://www.ruby-lang.org/), 75 bytes ``` ->n{([0,1]*n).permutation.uniq.count{|r|r.chunk{|n|n}.all?{|k,v|v.size<3}}} ``` [Try it online!](https://tio.run/##Tcm9DoIwFEDhnae4CQs1eCOimz8v4WYcalNCU7hgaTHa9tmrE2H7To5xz09q4AxpeyFf3Hdl9dgQw1Ga3llu1UDoSL1QDI6sDyYYFK0j7QMFisi77uqDLucw46S@8lTHGNMIDYr/KiqWLd6vXK98YFkOSx0Z5HDjWk7A4d2qTqYf "Ruby โ€“ Try It Online") ## Explanation This is a naive solution that generates the permutations and counts the valid ones. ``` ->n{([0,1]*n).permutation.uniq.count{|r|r.chunk{|n|n}.all?{|k,v|v.size<3}}} # This gets all the unique permutations of `0`s and `1`s of size `2n`. ([0,1]*n).permutation.uniq # This counts all instances where the inner block evaluates to true count{ } # This chunks together consecutive `0`s and `1`s. |r|r.chunk{|n|n} # This checks that all consecutive `0`s and `1`s are shorter than 3 all?{|k,v|v.size<3} ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 79 bytes ``` f(i,j,k){i=i*j<0?0:i|j?(k<4)*f(i-1,j,3+k/3)+!!k*f(i,j-1,k>1):1;}a(x){f(x,x,2);} ``` A port of [Arnauld's solution](https://codegolf.stackexchange.com/a/201100), and, by extension, the Maple solution on the OEIS page. I spent way too much time working on an alternate solution. Here's what I came up with that didn't work: * The number of numbers that don't meet the requirements of rule 1 is `2(x-1)`, or `4(x-1)` in this challenge's input scheme. * The number of numbers that do meet the requirements of rule 2 is `(n)!/(floor(n/2)!)^2`, or `(2n)!/(n!)^2`. * These cannot be combined because some numbers meet both the requirements, some meet neither, and the rest meet only one. *-6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!* [Try it online!](https://tio.run/##HY3BjoIwFEX3/YqnZpK@UgYZZ2VBf8RNU6w@qsUgmhqGX59avKube05yTX4yJkbLSbbS4Ug1ibZa79db@mv33FW/KBLMy4Q3mSs2mC0WTnz8NLpdidtSTZoHHC0PMsgfVFNckTeXR3OE6j401H2fd4yRH@CqyfNnRw2ykUGK7Xo@gwA1lAoKkVoF5C15Gl4gCgUhy/Djzrn1ybZ8@dUc/FLC/IuKTfHf2Is@3WN@1b05114P9Dy@AQ "C (gcc) โ€“ Try It Online") ]
[Question] [ This was inspired by a Minecraft mini-game. The rules are pretty simple: you run and jump around, and every block you step on disappears once you've stepped on it. The goal is to be the last one left. Your bot should be a complete program. It should accept input as a command line argument. The input will be a map of the "world"; here is an example: ``` xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxx xxxxxxxxxxxxxxxxxxxxxxxxxxx xxx xxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxx x xxxxxxxxxxxxx@xxxxxxxxxxx xxxxxx1xxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxxxxxxx x x xxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxx xxxxxxxxxxxxxx xxxxxxxxxxxxxxxxx xxxxxxxxxxxxxx xxx xx3xxxxxxxxxx xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx x xxxxxxxxxxxxxxxxxxxxxxxxxxx xx xxxxxxxxxxxxxxxxxxxxxxxxx 2 xxxxxxxxxxxxxxxxxxxxxxx ``` The legend is as follows: `x: solid block` `: empty air` `@: your bot` `1,2,3,4,5,6,7,8,9,0: other bots` Your bot should output your move as a pair of integers. Example: `-1, 2` will move 1 block to the left and 2 blocks down (coordinates origin is in the top left corner). You may move up to four blocks, manhattan distance, from your current location. If you try to move further than that, the move is invalid. Any move that would move you past the edge will put you on the edge instead. Invalid moves will be ignored. Once you land on a block it is removed; if you remain on the same block next turn you will fall. Two bots may land on the same block on the same turn and both survive; if this happens, both bots will only see themselves and not the other bot. If you need to store files for persistence, please do so in a folder with the name of your bot. You may not read other bots' persistent data if any exists. The match controller is available at <https://paste.ee/p/Xf65d>. Please use languages that can be run on a standard Linux or OSX install. Current results (100 rounds): ``` JumpBot 31 LookBot 27 ShyBot 26 Slow Bot 15 KnightBot 2 Moat Builder 0 UpBot 0 Random Bot 0 ``` [Answer] # Slow Bot (Python) He moves in a line pattern and checks his moves before making them (also suicides when he's the last one alive to prevent long runtimes) He won 195/200 Battels in my test tournament. ``` import sys import re class vec2(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return vec2(self.x + other.x, self.y + other.y) def __sub__(self, other): return vec2(self.x - other.x, self.y - other.y) def __iadd__(self, other): return self + other def __isub__(self, other): return self - other def __neg__(self): return vec2(-self.x, -self.y) def xy_to_i(vec=vec2(0, 0)): vec -= vec2(1, 1) vec.y += (vec.x - vec.x % 32) / 32 return vec.x + vec.y * 33 def i_to_xy(i=0): vec = vec2(0, 0) vec.x = i % 33 vec.y = (i - vec.x) / 32 + 1 vec.x += 1 return vec class World(object): def __init__(self, map=''): self.map = map def getPlayerPosition(self): return i_to_xy(re.search('@', self.map).start()) def getNumOtherBots(self): return len(re.findall('([0123456789])', ' ' + self.map + ' ')) def get_tile(self, vec=vec2(0, 0)): i = xy_to_i(vec) return self.map[i:i + 1] world = World(sys.argv[1]) pos = world.getPlayerPosition() def check_moveV(vecd=vec2(0, 0)): try: vecn = pos + vecd if vecn.x > 32 or vecn.x < 1 or vecn.y > 32 or vecn.y < 1 \ or abs(vecd.x) + abs(vecd.y) > 4: return False # Note: this will also avoid positions other bots are on (will disappear in the next step). return world.get_tile(vecn) == 'x' except: raise return False def check_move(x=0, y=0): return check_moveV(vec2(x, y)) def run(): if world.getNumOtherBots() == 0: return '0 0' # Suicide if we are the only one left. # this creates the "line" pattern if check_move(0, -1): return '0 -1' if check_move(0, 1): return '0 1' if check_move(1, 0): return '1 0' if check_move(1, -1): return '1 -1' # If we get here, we are desperate and need to find a safe place to jump. for dx in range(-2, 2): for dy in range(-2, 2): if check_move(dx, dy): return '%i %i' % (dx, dy) # If we can't find a place to jump in close range, try long range. for dx in range(-4, 4): for dy in range(-4, 4): if check_move(dx, dy): return '%i %i' % (dx, dy) # If we get here, we are dead no matter what; accept our fate. return '0 0' print(run()) ``` *I'm not an expert in python and there are probably 100 ways of doing it shorter/better* [Answer] # JumpBot (C) Try to jump to field with most possible moves in next round. ``` #include <stdio.h> #include <stdlib.h> typedef struct map { char *raw_map; int size; int lines; char *pos; } *MAP; typedef struct cdata { int result; MAP m; int x; int y; } *CDATA; typedef struct mdata { int x; int y; int moves; int bx; int by; MAP m; } *MDATA; int numberOfMoves(MAP, int, int); char getAt(MAP, int, int); int abs(int x) { return x < 0 ? x*-1 : x; } void count(void *data, int x, int y) { CDATA d = (CDATA)data; char c = getAt(d->m, d->x + x, d->y + y); if(c != 'x') return; d->result++; } void choose(void *data, int x, int y) { MDATA m = (MDATA)data; char c = getAt(m->m, m->x + x, m->y + y); if(c != 'x') return; int moves = numberOfMoves(m->m, m->x+x, m->y+y); if(moves > m->moves || (!m->bx && !m->by)) { m->moves = moves; m->bx = x; m->by = y; } } MAP parse_input(char *input) { MAP m = malloc(sizeof *m); if(!m) { fprintf(stderr, "failed to alloc map\n"); return NULL; } m->size=0; m->lines=1; m->pos=0; char *temp; for(temp = input;*temp;temp++) { switch(*temp) { case '\n': m->lines++; break; default: break; } } m->size = (temp + 1) - (input + m->lines); m->raw_map = malloc(m->size); if(!m->raw_map) { fprintf(stderr, "failed to alloc raw_map\n"); return NULL; } int index = 0; for(temp = input; *temp; temp++) { if(*temp == '@') m->pos = m->raw_map + index; if(*temp != '\n') m->raw_map[index++] = *temp; } return m; } char getAt(MAP m, int x, int y) { return m->raw_map[x + y*(m->size / m->lines)]; } void posToXY(MAP m, int *x, int *y) { int index = m->pos - m->raw_map; int length = m->size / m->lines; *x = index % length; *y = index / length; } typedef void (*DOFUNC)(void *, int, int); void processMoves(MAP m, int x, int y, DOFUNC proc, void *data) { int length = m->size / m->lines; int left = x>=4 ? 4 : x; int right = x + 4 <= length ? 4 : length - (x + 1); int up = y >= 4 ? 4 : y; int down = y + 4 <= m->lines ? 4 : m->lines - (y + 1); for(int i=-left; i<=right; i++) { for(int j=-up; j<=down; j++) { if((abs(i) + abs(j) <= 4) && (i || j)) (*proc)(data, i, j); } } } int numberOfMoves(MAP m, int x, int y) { struct cdata d; d.result = 0; d.x = x; d.y = y; d.m = m; processMoves(m, x, y, &count, &d); return d.result; } void getMove(MAP m, int *x, int *y) { struct mdata d; posToXY(m, &d.x, &d.y); d.moves = 0; d.bx = 0; d.by = 0; d.m = m; processMoves(m, d.x, d.y, &choose, &d); *x = d.bx; *y = d.by; } int main(int argc, char *argv[]) { if(argc != 2) { fprintf(stderr, "bad number of arguments %d\n", argc); return -1; } MAP m = parse_input(argv[1]); int x=0, y=0; getMove(m, &x, &y); printf("%d %d\n", x, y); return 0; } ``` [Answer] # LookBot (C) Simple bot that is similar in performance to Slow Bot, except that this one makes random possible moves. Plan to improve this to PredictBot. ``` #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <assert.h> #include <sys/time.h> #define WORLDSZ (32) #define WORLDSZ_2 (WORLDSZ*WORLDSZ) int max(int a,int b){return a>b?a:b;} int min(int a,int b){return a<b?a:b;} struct Position{ int x,y; }; typedef struct Position Position; struct World{ Position me; double enemymap[WORLDSZ][WORLDSZ]; //chance of enemy present bool open[WORLDSZ][WORLDSZ]; }; typedef struct World World; void world_read(World *world,const char *arg){ int x,y,i=0; for(y=0;y<WORLDSZ;y++,i++){ for(x=0;x<WORLDSZ;x++,i++){ if(arg[i]=='@'){world->me.x=x; world->me.y=y;} world->enemymap[y][x]=arg[i]>='0'&&arg[i]<='9'; world->open[y][x]=arg[i]=='x'; } } } //returns relative position Position world_calcmove(World *world){ const int mex=world->me.x,mey=world->me.y; int dx,dy; Position poss[40]; int nposs=0; for(dy=max(-mey,-4);dy<=min(WORLDSZ-1-mey,4);dy++){ const int absdy=abs(dy); for(dx=max(-mex,absdy-4);dx<=min(WORLDSZ-1-mex,4-absdy);dx++){ if(!world->open[mey+dy][mex+dx])continue; poss[nposs].x=dx; poss[nposs++].y=dy; } } if(nposs==0){ poss[0].x=poss[0].y=0; return poss[0]; } return poss[rand()%nposs]; } int main(int argc,char **argv){ if(argc!=2){ fprintf(stderr,"Call with world!\n"); return 1; } struct timeval tv; gettimeofday(&tv,NULL); srand(tv.tv_sec*1000000ULL+tv.tv_usec); World world; world_read(&world,argv[1]); Position move=world_calcmove(&world); printf("%d %d\n",move.x,move.y); } ``` [Answer] # Moat Builder (Python) If I dig a moat around myself, nobody outside it can screw me over. ...also known as "Paint yourself into a corner simulator 2016". ``` import numpy import sys import math import os if not os.path.exists('./moatbuilder'): os.mkdir('./moatbuilder') raw_field = sys.argv[1] field = numpy.array([numpy.array(list(i)) for i in raw_field.splitlines()]) field_size = len(field) x, y = raw_field.replace('\n','').index('@')%field_size, int(raw_field.replace('\n','').index('@')/field_size) # If there are no holes, it's the first round - reset persistence if raw_field.count(' ')==0: open('./moatbuilder/persistent','w').write('') def bigmove(target): if x < target[0]: return min(4, target[0] - x), 0 elif x > target[0]: return max(-4, target[0] - x), 0 elif y < target[1]: return 0, min(4, target[1] - y) else: return 0, max(-4, target[1] - y) def smallmove(target): if x < target[0]: try: return min(max(1, list(field[y][x:x+4]).index('x')), target[0] - x), 0 except: return 0, 0 elif x > target[0]: try: return max(min(-1, 0-list(reversed(field[y][x-4:x])).index('x')), target[0] - x), 0 except: return 0, 0 elif y < target[1]: try: return 0, min(max(1, list(field[:,x][y:y+4]).index('x')), target[1] - y) except: return 0, 0 else: try: return 0, max(min(-1, 0-list(reversed(field[:,x][y-4:y])).index('x')), target[1] - y) except: return 0, 0 try: mode = int(open('./moatbuilder/persistent').read()) except: mode = 1 # Modes: # 1 - go to the center # 2 - go to an outside edge # 3 - dig moat if mode==1: dx, dy = bigmove((int(field_size/2), int(field_size/2))) if dx==0 and dy==0: open('./moatbuilder/persistent', 'w').write('2') mode = 2 if mode==2: dx, dy = bigmove((int(field_size-1), int(field_size/2))) if dx==0 and dy==0: dy = 1 open('./moatbuilder/persistent', 'w').write('3') mode = 3 elif mode==3: direction = max(field_size-x, field_size-y)%2 if direction == 1: if x > y: dx, dy = smallmove((y, y)) else: dx, dy = smallmove((x, field_size - 1)) if dx==0 and dy==0: dx = 1 else: if y > x: dx, dy = smallmove((x, x)) else: dx, dy = smallmove((field_size - 1, y)) if dx==0 and dy==0: dy = 1 print "%i %i" % (dx, dy) ``` [Answer] # Monte (Python) Sorry, that pun just had to be made. Anyway, this bot works by doing a [Monte Carlo Tree Search](https://en.wikipedia.org/wiki/Monte_Carlo_tree_search) on all of the possible move sets. Think of JumpBot, only more in-depth. To run, it needs an extra command line argument (can be specified in the controller). It controls how much time the bot should search for (in ms); I used 750-1500 in testing. Code: ``` import sys import math import copy #from profilestats import profile pmap = sys.argv[2].split("\n") pmap = [list(r) for r in pmap] #find a player #@profile def find(tmap,bot): r,c=-1,-1 for row in range(len(tmap)): for col in range(len(tmap[row])): if tmap[row][col]==bot: r,c=row,col return r,c mer,mec=find(pmap,'@') bots=[(mer,mec)] #find all the other players for b in range(10): r,c=find(pmap,str(b)) if r != -1: bots.append((r,c)) #getter function, treats oob as spaces def get(tmap,r,c): if r<0 or r>=len(tmap) or c<0 or c>=len(tmap[r]): return ' ' return tmap[r][c] #returns manhattan distance between 2 positions def dist(r1,c1,r2,c2): return abs(r1-r2)+abs(c1-c2) #gets all possible moves from a map #@profile def moves(tmap,ther=-1,thec=-1): if ther==-1: ther,thec = find(tmap,'@') pos=[] for r in range(-4,5): for c in range(-4,5): if abs(r)+abs(c)<=4 and get(tmap,ther+r,thec+c)=='x': pos.append((r,c)) return pos ttlmoves = 40 #monte-carlo tree node class MCNode: def __init__(self): self.wins=0 self.simu=0 self.chld=[] self.cmap=[[]] self.prnt=None self.r=-1 self.c=-1 def add(self, cnode): self.chld.append(cnode) cnode.prnt = self #used to balance exploitation and exploration #@profile def param(self,cin): return self.chld[cin].wins/self.chld[cin].simu\ + 1.414 * math.sqrt( math.log(self.simu) / \ self.chld[cin].simu ) #finds the child with the highest param #@profile def best(self): vals = [self.param(x) for x in range(len(self.chld))] binx = 0 bval = vals[0] for x in range(len(vals)): if vals[x]>bval: binx=x bval=vals[x] return self.chld[binx] #update all the parents #@profile def backprog(leaf): par = leaf.prnt if not (par is None): par.wins+=leaf.wins par.simu+=leaf.simu backprog(par) #expand all the moves from a position #@profile def expand(rootn): ther,thec = rootn.r,rootn.c for r,c in moves(rootn.cmap,rootn.r,rootn.c): nmap = copy.deepcopy(rootn.cmap) nmap[ther+r][thec+c] = '@' nmap[ther][thec]=' ' nnode = MCNode() nm = moves(nmap,ther+r,ther+c) nnode.wins = len(nm) nnode.simu = ttlmoves nnode.r=ther+r nnode.c=thec+c nnode.cmap = nmap rootn.add(nnode) backprog(nnode) root = MCNode() m = moves(pmap,mer,mec) root.wins = len(m) root.simu = ttlmoves root.cmap=copy.deepcopy(pmap) root.r=mer root.c=mec expand(root) #simulate a bunch of outcomes import time curt = lambda: int(round(time.time() * 1000)) strt = curt() ttme = int(sys.argv[1]) while curt()-strt < ttme: tnode=root while tnode.chld: tnode=tnode.best() expand(tnode) #choose the most explored one bnode = max(root.chld,key=lambda n:n.simu) #output print("{} {}".format((bnode.c-mec),(bnode.r-mer))) ``` # Trials 25 rounds: ``` MonteBot 14 JumpBot 6 ShyBot 5 LookBot 1 KnightBot 0 SlowBot 0 ``` 100 rounds: ``` JumpBot 38 MonteBot 36 ShyBot 15 LookBot 14 SlowBot 2 KnightBot 0 ``` 200 rounds: ``` MonteBot 87 JumpBot 64 LookBot 33 ShyBot 21 SlowBot 5 KnightBot 0 ``` All of the simulations above used search time 750. This bot would probably be even better with a longer search time (I don't know what the max allowed is). ## Improvements This bot still needs improvements in: 1. Performance: it needs the entire time to search. 2. Prediction: it won't account for other bot's moves. 3. Balance: I'm not sure if the UCT formula I am using to calculate which node I should explore is optimal. [Answer] # ShyBot (Python) This bot really doesn't like other bots and will try to keep itself away if possible. ShyBot is also really careful about where it steps; it won't even step on other bots. However, ShyBot still looses often which makes insecure. ``` import sys map = sys.argv[1] map = map.split("\n") map = [list(r) for r in map] def find(map,bot): r,c=-1,-1 for row in range(len(map)): for col in range(len(map[row])): if map[row][col]==bot: r,c=row,col return r,c mer,mec=find(map,'@') bots=[(mer,mec)] for b in range(10): r,c=find(map,str(b)) if r != -1: bots.append((r,c)) avg=[0,0] for b in bots: avg[0]+=b[0] avg[1]+=b[1] avg[0] = avg[0]/len(bots) avg[1] = avg[1]/len(bots) def get(map,r,c): if r<0 or r>=len(map) or c<0 or c>=len(map[r]): return ' ' return map[r][c] def dist(r1,c1,r2,c2): return abs(r1-r2)+abs(c1-c2) pos=[] for r in range(-4,5): for c in range(-4,5): if abs(r)+abs(c)<=4 and get(map,mer+r,mec+c)=='x': pos.append((r,c)) if len(pos)==0: bestr,bestc=0,0 else: bestr,bestc=pos[0] for r,c in pos: if dist(mer+r,mec+c,avg[0],avg[1])>dist(mer+bestr,mec+bestc,avg[0],avg[1]): bestr,bestc=r,c print(str(bestc)+" "+str(bestr)) ``` [Answer] # KnightBot (Java) It's works like chess, and is named like Twitch... ... ......... ............................sorry... ``` public class KnightBot{ private static String[] map; private static int myx; private static int myy; public static void main(String[] args){ map=args[0].split("\n"); for(int y=0;y<map.length;y++){ if(map[y].indexOf("@")!=-1){ myy = y; myx = map[y].indexOf("@"); break; } } System.out.println(move((int)(Math.random()*4),4)); } public static String move(int dir,int tries){ if(tries==0)return "0 0"; int x=dir<2?1:-1; int y=dir%2==0?2:-2; if((myx+x<0||myx+x>=map[0].length()||myy+y<0||myy+y>=map.length)||map[y+myy].charAt(myx+x)!='x'){ x=dir<2?2:-2; y=dir%2==0?1:-1; } if((myx+x<0||myx+x>=map[0].length()||myy+y<0||myy+y>=map.length)||map[y+myy].charAt(myx+x)!='x') return move(++dir>3?0:dir,tries-1); return x+" "+y; } } ``` # SwirlyBot (Java) These are clearly not the optimal solutions, but I hope will be useful for midlevel testing. ``` public class SwirlyBot{ private static String[] map; private static int myx; private static int myy; public static void main(String[] args){ map=args[0].split("\n"); for(int y=0;y<map.length;y++){ if(map[y].indexOf("@")!=-1){ myy = y; myx = map[y].indexOf("@"); break; } } System.out.println(move(0)); } public static String move(int dir){ switch(dir){ case 0: if(!safe(0,1)){ if(safe(1,1)){ return "1 1";//Down-Right }else{ if(safe(1,0)){ return "1 0";//Right } } } break; case 1: if(!safe(1,0)){ if(safe(1,-1)){ return "1 -1";//Up-Right }else{ if(safe(0,-1)){ return "0 -1";//Up } } } break; case 2: if(!safe(0,-1)){ if(safe(-1,-1)){ return "-1 -1";//Up-Left }else{ if(safe(-1,0)){ return "-1 0";//Left } } } break; case 3: if(!safe(-1,0)){ if(safe(-1,1)){ return "-1 1";//Down-Left }else{ if(safe(0,1)){ return "0 1";//Down } } } break; case 4: if(safe(0,-1))return "0 -1"; break; case 5: if(!safe(0,2)){ if(safe(1,2)){ return "1 2";//Down-Right }else{ if(safe(2,2)){ return "2 2"; }else{ if(safe(2,1)){ return "2 1"; }else{ if(safe(2,0)){ return "2 0";//Right } } } } } break; case 6: if(!safe(2,0)){ if(safe(2,-1)){ return "2 -1";//Up-Right }else{ if(safe(2,-2)){ return "2 -2"; }else{ if(safe(1,-2)){ return "1 -2"; }else{ if(safe(0,-2)){ return "0 -2";//Up } } } } } break; case 7: if(!safe(0,-2)){ if(safe(-1,-2)){ return "-1 -2";//Up-Left }else{ if(safe(-2,-2)){ return "-2 -2"; }else{ if(safe(-2,-1)){ return "-2 -1"; }else{ if(safe(-2,0)){ return "-2 0";//Left } } } } } break; case 8: if(!safe(-2,0)){ if(safe(-2,1)){ return "-2 1";//Down-Left }else{ if(safe(-2,2)){ return "-2 2"; }else{ if(safe(-1,2)){ return "-1 2"; }else{ if(safe(0,2)){ return "0 2";//Down } } } } } break; } if(dir<8)return move(dir+1); return "0 -1"; } public static boolean safe(int x, int y){ return !((myx+x<0||myx+x>=map[0].length()||myy+y<0||myy+y>=map.length)||map[y+myy].charAt(myx+x)!='x'); } } ``` [Answer] # Random Bot, UpBot Two starting bots to compete against: **Random Bot:** An example bot that moves randomly. ``` import random x = random.randint(-4, 4) y = random.randint(max(-4, -4 + abs(x)), min(4, 4 - abs(x))) print x, y ``` **UpBot:** An example bot that moves up. ``` print '0 -1' ``` [Answer] # StalkerBot (Python) Will get as close as possible to the closest bot it sees. Targets Slow Bot's (pointless) automatic suicide. (If I'm on the same square as it and there are no other players, it won't see me and will suicide.) ``` #!/usr/bin/python3 from math import inf from sys import argv class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __neg__(self): return Vector(-self.x, -self.y) def __abs__(self): return self.x ** 2 + self.y ** 2 # Technically the square of the magnitude, but we only need it for comparison. def __iter__(self): yield self.x yield self.y def get_location(grid, target='@'): for i, line in enumerate(grid): for j, char in enumerate(line): if char == target: return Vector(i, j) def main(grid): my_location = get_location() min_distance = inf min_distance_direction = None for i in range(10): enemy_location = get_location(str(i)) if enemy_location is not None: direction = enemy_location - my_location distance = abs(direction) if distance < current_min: min_distance = distance min_distance_direction = direction if distance == 1: break if min_distance_direction is not None: return min_distance_direction for d in range(1, 5): for x in range(-d, d): for y in (d - abs(x), abs(x) - d): if grid[x][y] == ' ': return x, y return 0, 0 if __name__ == '__main__': print(*main(argv[1].splitlines())) ``` ]
[Question] [ *Redivosite is a portmanteau word invented for the sole purpose of this challenge. It's a mix of Reduction, Division and Composite.* ## Definition Given an integer **N > 6**: * If **N** is prime, **N** is not a Redivosite Number. * If **N** is composite: + repeatedly compute **N' = N / d + d + 1** until **N'** is prime, where **d** is the smallest divisor of **N** greater than 1 + **N** is a Redivosite Number if and only if the final value of **N'** is a divisor of **N** Below are the 100 first Redivosite Numbers (no OEIS entry at the time of posting): ``` 14,42,44,49,66,70,143,153,168,169,176,195,204,260,287,294,322,350,414,462,518,553,572,575,592,629,651,702,726,735,775,806,850,869,889,891,913,950,1014,1023,1027,1071,1118,1173,1177,1197,1221,1235,1254,1260,1302,1364,1403,1430,1441,1554,1598,1610,1615,1628,1650,1673,1683,1687,1690,1703,1710,1736,1771,1840,1957,1974,2046,2067,2139,2196,2231,2254,2257,2288,2310,2318,2353,2392,2409,2432,2480,2522,2544,2635,2640,2650,2652,2684,2717,2758,2760,2784,2822,2835 ``` ## Examples * **N = 13**: 13 is prime, so 13 is not a Redivosite Number * **N = 32**: 32 / 2 + 3 = 19; 19 is not a divisor or 32, so 32 is not a Redivosite Number * **N = 260**: 260 / 2 + 3 = 133, 133 / 7 + 8 = 27, 27 / 3 + 4 = 13; 13 is a divisor or 260, so 260 is a Redivosite Number ## Your task * Given an integer **N**, return a truthy value if it's a Redivosite Number or a falsy value otherwise. (You may also output any two distinct values, as long as they're consistent.) * The input is guaranteed to be larger than **6**. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] ## Haskell, ~~91~~ ~~85~~ ~~83~~ ~~80~~ ~~75~~ 74 bytes ``` n#m=([n#(div m d+d+1)|d<-[2..m-1],mod m d<1]++[mod n m<1&&m<n])!!0 f x=x#x ``` [Try it online!](https://tio.run/##FcmxCsMgEADQvV9xwRISTMTr0kW/RBwCF6nUu4Y0FIf@uyHj472W73stpTVR7IcgaqD8AwbSpHH8k5vDwxieMU78oSscRq3DBQF22PfsJI5dZ28Jqq@qNl6ygIdtz3LAHVIux7pDgvA0Bq21sZ0 "Haskell โ€“ Try It Online") ``` f x=x#x -- call # with x for both parameters n#m |d<-[2..m-1],mod m d<1 -- for all divisors d of m [n#(div m d+d+1) ] -- make a list of recursive calls to #, -- but with m set to m/d+d+1 ++ [mod n m<1&&m<n] -- append the Redivosite-ness of n (m divides n, -- but is not equal to n) !!0 -- pick the last element of the list -- -> if there's no d, i.e. m is prime, the -- Redivosite value is picked, else the -- result of the call to # with the smallest d ``` Edit: -2 bytes thanks to @BMO, -3 bytes thanks to @H.PWiz and ~~-5~~ -6 bytes thanks to @ร˜rjan Johansen [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ?ยฌแน ยฆฮฉแน—oฮ“~+โ†’ฮ pแน— ``` [Try it online!](https://tio.run/##yygtzv7/3/7Qmoc7Fxxadm7lw53T889NrtN@1Dbp3IICIO////9GFsamAA "Husk โ€“ Try It Online") -3 thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~94~~ 89 bytes ``` m,n;o(k){for(m=1;m++<k;)if(k%m<1)return m;} F(N){for(n=N;m=o(n),m-n;n=n/m-~m);N=m<N>N%n;} ``` [Try it online!](https://tio.run/##NcxNCsIwEEDhvacohUCGJEgWupnEpcu5g8RGQpiphHYl9erxD/fve8ndUuqdreCsKzzy3DRHj2xMqAgl66o4eGjTsjYZGLfdWdOvk0jIcdYClp2gRNmzezIgRQ50IiW4db4U@QOKRzSGgp8O3/XnBPdWZMl6VFc7jJbgbV4 "C (gcc) โ€“ Try It Online") # Explanation ``` m,n; // two global integers o(k){ // determine k's smallest divisor for(m=1;m++<k;) // loop through integers 2 to n (inclusive) if(k%m<1)return m;} // return found divisor F(N){ // determine N's redivosity for(n=N; // save N's initial value m=o(n), // calculate n's smallest divisor (no name clash regarding m) m-n; // loop while o(n)!=n, meaning n is not prime // (if N was prime, the loop will never be entered) n=n/m-~m); // redivosite procedure, empty loop body N=m<N>N%n;} // m<N evaluates to 0 or 1 depending on N being prime, // N%n==0 determines whether or not N is divisible by n, // meaning N could be redivosite => m<N&&N%n==0 // <=> m<N&&N%n<1 <=> m<N&&1>N%n <=> (m<N)>N%n <=> m<N>N%n ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ร†แธŒแธŠ ร‡.แป‹Sโ€˜ยตร‡ยฟeร‡ ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//w4bhuIzhuIoKw4cu4buLU@KAmMK1w4fCv2XDh/83w4cxMDAj/w "Jelly โ€“ Try It Online") ### How it works ``` ร†แธŒแธŠ Helper link. Argument: k ร†แธŒ Yield k's proper (including 1, but not k) divisors. แธŠ Dequeue; remove the first element (1). ร‡.แป‹Sโ€˜ยตร‡ยฟeร‡ Main link. Argument: n ยต Combine the links to the left into a chain. ร‡ยฟ While the helper link, called with argument n, returns a truthy result, i.e., while n is composite, call the chain to the left and update n. ร‡ Call the helper link. .แป‹ At-index 0.5; return the elements at indices 0 (last) and 1 (first). This yields [n/d, d]. S Take the sum. โ€˜ Increment. ร‡ Call the helper link on the original value of n. e Test if the result of the while loop belongs to the proper divisors. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~97~~ 91 bytes ``` r=0;e=d=i=input() while r-e:e=i;r=[j for j in range(2,i+1)if i%j<1][0];i=i/r-~r d%e<1<d/e<q ``` [Try it online!](https://tio.run/##TY5ND8FQEEX38ysmTSQE4fF8tX1LlmzsxKLawRSvNZ5g469XKxLd3MlNzpzc/OWOmR0UcZYQGvQ8rxDTD8gkhg3b/O6aLXgc@UwoXfLJcCBmk@I@E0yRLUpkD9QcdLitWrxHbqSh2m7626B870n3LZA0KFRh0qPwWpT@n20td/IB0cmrOoj0pBirGd@WC1uHi@h8qzo9Y8odLqMLzUUy8WtMJfoj89WiRuyEolOhhqA0qBFoDbrMMegJ6Cno2Qc "Python 2 โ€“ Try It Online") Outputs via exit code. ### Ungolfed: ``` r = 0 # r is the lowest divisor of the current number, # initialized to 0 for the while loop condition. e = d = i = input() # d remains unchanged, e is the current number # and i is the next number. while r != e: # If the number is equal to its lowest divisor, # it is prime and we need to end the loop. e = i # current number := next number r = [j for j in range(2, i+1) # List all divisors of the number in the range [2; number + 1) if i%j < 1][0] # and take the first (lowest) one. i = i/r+r+1 # Calculate the next number. # We now arrived at a prime number. print d%e == 0 and d != e # Print True if our current number divides the input # and is distinct from the input. # If our current number is equal to the input, # the input is prime. ``` [Try it online!](https://tio.run/##jVNLc9owEL7rV2zJZAYGpo2p0wcpx/TaS29MDoq1FBEjOSs5JP3zdFeyUyBPz/ip9ffaVfMQV95Nd5U3CHMYDAY74vsZvHacAIENEFcItd9iiGDsnQ2ewC/T16olQhfBtZtrpAlYZ6PVtf2LBqJn9CXXSuF2ZWsB8Q1U3hmu8k6JEMOnldM1bRyOnggwQLjR1gVoXbXS7g@aCWCv6pAftDMM1q05vO8XVKYn@DAHnL1g1WZLHRSD4G2ra7FhYzjyz06jlDRkN5hot0KYXYfoGyWYmLy9HO6R@tn8QLPUSIsW65TimiMCkgCGU6YfFyNGqC1r0nXd6wp9Y3oXLr2l32Axvei/j6EYqUcl7NyeruEHFFeLs6sDiWIt6htMMEtLTDfMUYzAO0wYqX2faEzj4nmbuq7aWkd80hZ48zhJwfotaCJ7x/lq9tvF3oHwC2doTjltmWdRbFKj90ByzW9qUcz6lo6zl/wM5sFJo5hnKfBCiNZVEZbkN/@XP75L@/Nc@6P1CDjZo@4Ha8e7tBtdkT5jzkgPszxb91iBbGYlzxU2ES5//bwk8pQLrgn1za74rIpSFeeqLFXJ1y@q/KrKb6r8/g8 "Python 2 โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes ``` [Dp#ร’ฤ‡ยฉsP+>]ร–ยฎp* ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2qVA@fCkI@2HVhYHaNvFHp52aF2B1v//RmYGAA "05AB1E โ€“ Try It Online") **Explanation** ``` [ # start loop Dp# # break if current value is prime ร’ # get prime factors of current value ฤ‡ยฉ # extract the smallest (d) and store a copy in register sP # take the product of the rest of the factors +> # add the smallest (d) and increment ] # end loop ร– # check if the input is divisible by the resulting prime ยฎp # check if the last (d) is prime (true for all composite input) * # multiply ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` <P_QiI.WtPHh+/ZKhPZK ``` **[Try it here!](https://pyth.herokuapp.com/?code=%3CP_QiI.WtPHh%2B%2FZKhPZK&input=42&debug=0)** ## How it works ``` iI.WtPHh+/ZKhPZK || Full program. .W || Functional while. It takes two functions as arguments, A and B. || While A(value) is truthy, turn the value into B(value). The || starting value is the input. tPH || First function, A. Takes a single argument, H. PH || .. The prime factors factors of H. t || .. Tail (remove first element). While truthy (H is composite): h+/ZKhPZK || The second function, B. Takes a single argument, Z: /Z || .. Divide Z, by: KhP || .. Its lowest prime factor, and assign that to K. h || .. Increment. + K || And add K. iI || Check if the result (last value) divides the input. ``` And the first 4 bytes (`<P_Q`) just check if the input is not prime. With help from [Emigna](https://codegolf.stackexchange.com/users/47066/emigna), I managed to save 3 bytes. [Answer] # [Python 3](https://docs.python.org/3/), 149 bytes ``` def f(N): n=N;s=[0]*-~N for p in range(2,N): if s[p]<1: for q in range(p*p,N+1,p):s[q]=s[q]or p while s[n]:n=n//s[n]-~s[n] return s[N]>1>N%n ``` [Try it online!](https://tio.run/##RU9BboMwEDzbr9hLFZwCiRMKgRae4A8gDkiYxhJZHNtViaLk69TOpZfR7s7szqy@ufOMx3Ud5AhjJFhFCdbi09btvtsmT0HJOBvQoBBMj98yOsQvEVEj2FZ3Xzw0L9H1X6S3OhbvPNassu21qwOEM5T8ntUk/SZ2Fda424UqeQakxEj3Y9CTomt4I95wVRc9Gwf2ZmlwWIKDb1LrBoWpkf0wKZQRS62elItCMG0Uumhzf0DSwP2xSf3ipXeRT7nEAP7JwC@MUcLYyjPIDpB5LCHPodgD/wCeAy@An4CXUMAJSuB@zv8A "Python 3 โ€“ Try It Online") Using a sieve approach. Should be fast (`O(N log log N)` = time complexity of the sieve of Eratosthenes) even with large `N` (but stores `O(N)` integers in memory) Note: * It can be proven that all intermediate values of `n` does not exceed `N`, and for `N > 7` `p` can be in `range(2,N)` instead of `range(2,N+1)` for sieving. * `/` doesn't work, `//` must be used, because of list index. * Storing `range` into another variable doesn't help, unfortunately. Explanation: * `-~N` == `N+1`. * At first, the array `s` is initialized with `N+1` zeroes (Python is 0-indexing, so the indices are `0..N`) * After initialization, `s[n]` is expected to be `0` if `n` is a prime, and `p` for `p` the minimum prime which divides `n` if `n` is a composite. `s[0]` and `s[1]` values are not important. * For each `p` in range `[2 .. N-1]`: + If `s[p] < 1` (that is, `s[p] == 0`), then `p` is a prime, and for each `q` being a multiple of `p` and `s[q] == 0`, assign `s[q] = p`. * The last 2 lines are straightforward, except that `n//s[n]-~s[n]` == `(n // s[n]) + s[n] + 1`. --- # [Python 3](https://docs.python.org/3/), 118 bytes ``` def f(N): n=N;s=[0]*-~N for p in range(N,1,-1):s[2*p::p]=(N-p)//p*[p] while s[n]:n=n//s[n]-~s[n] return s[N]>1>N%n ``` [Try it online!](https://tio.run/##FY9NboMwEIXX9ilmU8VG/MQphUAFR/AFEAskTGOJDJbtqkRRcnVqb57evE@jN2Me/rbh53HMaoGFSd5Sgp38dt1wHpPsLSlZNgsGNIKd8EcxmYo0E7x1wyUxbWvGjsnM8KIwyWBGSv5uelXgBhxb7LAoosveUSmxyv9aDFCOvejlBx76bjbrwT0cjT177AlD7vysMbdqmleNivHcmVV7Fs8zVqNnp@cLsh6er1MeFu@TZ5SQPQUIX0S@c04J54coobxAGbSBqoL6DOILRAWiBnEF0UANV2hAhFz8Aw "Python 3 โ€“ Try It Online") At the cost of slightly worse performance. (This one runs in `O(N log N)` time complexity, assume reasonable implementation of Python slices) --- The equivalent full program is [117 bytes](https://tio.run/##NU7LbsIwELzvV6xcVYqjpMGU8ggyF@75gSiKUnDAUlhbttOWC7@emkIvo53RzM7Yazgbep9e0Hwp5/RRoSY7hoRjP9IhaEOYkHGXbhiueFIBOxw0KeyduTysHL3BcO4CBuWDphNqj6rzWjk4qv7/X@ll236OeogW37ZvT3lrnaaQ@IzlO2SZoqNkjG@dCqMj9AD7yNlEspJ33zPFwct61qT5rYLeOLSxBV1HJ5VUmchyEevqeWrL0jYyqXLLi8KmtW3g@6wHhb6mpiRJRXG/8tsd4bmkrpqd2FWvxKfYvAVQP@qQsEdwX/6xPWd8EgtYzGERcQPLJaxmID5ALEGsQKxBbGAFa9iAiLr4BQ). [Answer] # [Haskell](https://www.haskell.org/), 110 bytes ``` f n|mod(product[1..n-1]^2)n>0=1<0|1>0=n`mod`u n<1 u n|d<-[i|i<-[2..],n`mod`i<1]!!0=last$n:[u$n`div`d+d+1|d/=n] ``` [Try it online!](https://tio.run/##JYpBDoIwEADvvmJJOGiQ2uViQlo/0tSUWIgby0KgeOrfaxMvM4eZ97B/xhBynoDTvPjzui3@eEWDQnCL9tld@CE1KpmwmF153AGs8FSYvGoNJSrshLDXfyaFtqqkDsMea@7NUbPz9HW@8Q0mf9Ns8zwQg4Z1I45Qw0QhjhtMYO5CoJTS5h8 "Haskell โ€“ Try It Online") Not very happy... [Answer] # [Octave](https://www.gnu.org/software/octave/), 92 bytes ``` function r=f(n)k=n;while~isprime(k)l=2:k;d=l(~mod(k,l))(1);k=k/d+d+1;end;r=~mod(n,k)&k<n;end ``` [Try it online!](https://tio.run/##HU3LDsIgELz3K/ZkIG0i1YNJcT/GdCGSpYvBqrf@OgJzmMwjmUnr/vi6UvxH1j0kgYxeiWYU@3uG6I7wfuWwOcU64mVhSxjVsSVSPEWt1awtI59ppHG2Tshm7K1MrE98l5YVnzIIINyWqzFmgIrgof103UD1p3rbg7YzNCp/) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 50 bytes ``` {(0=n|โต)โˆงโต>nโ†{โฌโ‰ขkโ†o/โจ0=โต|โจoโ†2โ†“โณโต:โˆ‡1+d+โตรทdโ†โŒŠ/kโ‹„โต}โต} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OAZLWGgW1ezaPerZqPOpYDKbs8kOCj3jWPOhdlA5n5@o96VxjYAmWAilbkA0WMHrVNftS7GShi9aij3VA7RRvIPLw9BSj1qKdLP/tRdwtQoBaE///XMAfKbjY0MNAEmZN2aAWMz5WmYGhgaAKhTAE "APL (Dyalog Unicode) โ€“ Try It Online") [Answer] # Japt, ~~25~~ 24 bytes I fear I may have gone in the wrong direction with this but I've run out of time to try a different approach. Outputs `0` for false or `1` for true. ``` j ?VยฉvU :รŸU/(U=k g)+ยฐUNg ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=aiA/Vql2VSA631UvKFU9ayBnKSuwVU5n&input=MjgzNQ==) [Answer] # [Perl 5](https://www.perl.org/), 291+1(-a) = 292 bytes Darn Perl for not having a native prime checker. ``` use POSIX;&r($_,$_); sub p{$n=shift;if($n<=1){return;}if($n==2||$n==3){return 1;}if($n%2==0||$n%3==0){return;}for(5..ceil($n/2)){if($n%$_==0){return;}}return 1;} sub r{$n=shift;$o=shift;if(&p($n)){print $o%$n==0&&$n!=$o?1:0;last;}for(2..ceil($n/2)){if($n%$_==0){&r(($n/$_)+$_+1, $o);last;}}} ``` Ungolfed version, ``` use POSIX; &r($_,$_); sub p{ my $n=shift; if($n<=1){ return; } if($n==2||$n==3){ return 1; } if($n%2==0||$n%3==0){ return; } for(5..ceil($n/2)){ if($n%$_==0){ return; } } return 1; } sub r{ my $n=shift; my $o=shift; if(&p($n)){ print $o%$n==0&&$n!=$o ? 1 : 0; last; } for(2..ceil($n/2)){ if($n%$_==0){ &r(($n/$_)+$_+1, $o); last; } } } ``` [Try it online!](https://tio.run/##fVHLjtpAELz3VxBpQKB9ZLrn0TMhVs45JVIuuaFNBFpLyEbGnFh@PU41uxHKZQ9Tnunqqn74sB32aZpOx@3s@7cfX3@uF8PSbe7dZrWm4@nX7HB2XXN8bnfjut0tXfe54dV52I6noVtfrpGmkZcX@4R/xIzfqLk0jTdyHnC56Xb9sEyPj7@37R5ZH2W1Or/mu81/eZeb37WZ4daM629dLQ7QwuMwtN04c/3cuvGLhes@NK7/wp/8ev90HF/ryjt1MbvFMfyd29zxPbxWb9LLZZo4UhSKwEo5k3riGIgTTi44lVgzcU0kPpJkT1KUpEYKIhSSp2gWWShxoQRdUtw1UapCWeCaGLZCKrAPiRRc8ZkKtAX@peBUpsqBKmLsYchegoEClIkZ5swaDBDjChABIXBkSVBYbxxQiEPGM/pgo9g8EXnJUlK1kdgbQJbFnlYy63XeK6hNjZiagVqyBmxArY0Sve0CKVWjbSQDMvbBoQIqnhIYgGoAEFIKIeQN7IYFScBmJHooYrBbAZuwTahsxZhIMgqJtQYAkQsIZfhpgovab1CLFZOVkP70h7Htu@P08PQX "Perl 5 โ€“ Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes Straightforward implementation using recursive pattern replacement (replacing "\[Divides]" with the ๏ปฟ"โˆฃ" symbol saves 7 bytes) ``` (g=!PrimeQ@#&)@#&&(#//.x_/;g@x:>x/(c=Divisors[x][[2]])+c+1)\[Divides]#& ``` [Try it online!](https://tio.run/##FczNCgIhFEDhV7khiMNITkEEheGiZYt@ljcJMceEnGCUEKJnt2lxNt/iRJMfLpocrKm9rMzL2XEM0Z0Uoc0UZUSIebmJrVdlsyuCWbkP75BeY8KiEZdaN61tF80V/353SRNap8eQ1cU9nc34IRx6Rb5AQSg4m8E7XHNYdZ3mcDAp6/oD "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~128~~ ~~117~~ 114 bytes ``` import StdEnv @n#v=hd[p\\p<-[2..]|and[gcd p i<2\\i<-[2..p-1]]&&n rem p<1] |v<n= @(n/v+v+1)=n ?n= @n<n&&n rem(@n)<1 ``` [Try it online!](https://tio.run/##Lc1BC4IwGIDhu7/ig0AU0VCILht6qEPQzaPbYbhpI/c5dA0Cf3urqOvDC28/KYHBzPIxKTBCY9DGzouD1skz@qjBnac32VnGLMm7qij4JlB2Yy/BgiYVY/rnNi85j2OERRmwpOTR5glSaBLc@8xnZUoxqr@ABP9d0mBKytA6sbiIghN3BdUBkkFPTi1QQ3f8DNPw6odJjGvIL9dweqIwul/f "Clean โ€“ Try It Online") [Answer] # [J](http://jsoftware.com/), 35 bytes ``` (~:*0=|~)(1+d+]%d=.0{q:)^:(0&p:)^:_ ``` [Try it online!](https://tio.run/##y/r/P81WT6POSsvAtqZOU8NQO0U7VjXFVs@gutBKM85Kw0CtAETH//dz0lNwS8wpTq3kSk3OyFdIUzA0hrGMjbi4QPIhRaUlGQh5ExjLxAjGMjIz@A8A "J โ€“ Try It Online") The minimum divisor being the first prime factor was stolen from @Dennis's Jelly solution (previously I was using `<./@q:`). There should be a better way to do the iteration, but I can't seem to find it. I thought of avoiding doing the primality test (`^:(0&p:)`) and instead using adverse but it seems like that will be a bit longer since you'll need a `_2{` and some changes which might not give a net reduction. I really feel like there must be a way to avoid having parens around the primality check, too. # Explanation (expanded) ``` (~: * 0 = |~)(1 + d + ] % d =. 0 { q:) ^: (0&p:) ^:_ Input: N (1 + d + ] % d =. 0 { q:) ^: (0&p:) ^:_ Find the final N' ^: ^:_ Do while 0&p: N is not prime q: Get prime factors (in order) 0 { Take first (smallest divisor) d =. Assign this value to d 1 + d + ] % d Compute (N/d) + 1 + d (~: * 0 = |~) Is it redivosite? 0 = |~ N = 0 (mod N'), i.e. N'|N * And ~: N =/= N', i.e. N is not prime ``` [Answer] # APL NARS, 43 chars, 85 bytes ``` {(โตโ‰ค6)โˆจ0ฯ€โต:0โ‹„โต{1=โดtโ†ฯ€โต:0=โต|โบโ‹„โบโˆ‡1+โ†‘t+โตรทโ†‘t}โต} ``` (hoping that it converge for all number>6) test: ``` hโ†{(โตโ‰ค6)โˆจ0ฯ€โต:0โ‹„โต{1=โดtโ†ฯ€โต:0=โต|โบโ‹„โบโˆ‡1+โ†‘t+โตรทโ†‘t}โต} vโ†โณ100 v,ยจhยจv 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 1 15 0 16 0 17 0 18 0 19 0 20 0 21 0 22 0 23 0 24 0 25 0 26 0 27 0 28 0 29 0 30 0 31 0 32 0 33 0 34 0 35 0 36 0 37 0 38 0 39 0 40 0 41 0 42 1 43 0 44 1 45 0 46 0 47 0 48 0 49 1 50 0 51 0 52 0 53 0 54 0 55 0 56 0 57 0 58 0 59 0 60 0 61 0 62 0 63 0 64 0 65 0 66 1 67 0 68 0 69 0 70 1 71 0 72 0 73 0 74 0 75 0 76 0 77 0 78 0 79 0 80 0 81 0 82 0 83 0 84 0 85 0 86 0 87 0 88 0 89 0 90 0 91 0 92 0 93 0 94 0 95 0 96 0 97 0 98 0 99 0 100 0 ``` The idea of using 2 anonymous functions I get to other Apl solution. ``` {(โตโ‰ค60)โˆจฯ€โต:0โ‹„ -- if arg โต is prime or <=6 return 0 โต{1=โดtโ†ฯ€โต:0=โต|โบโ‹„ -- if list of factors โต has length 1 (it is prime) -- then return โบmodโต==0 โบโˆ‡1+โ†‘t+โตรทโ†‘t}โต} -- else recall this function with args โบ and 1+โ†‘t+โตรทโ†‘t ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 44 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` โ†โป0`ล•โบฤฤฯผโ†“ฤ3ศ˜โ‡นรท+โบฤแน—ยฌโ‡นโปโ‡นล‚ล•รกฤ0โฆ‹ฤโ†”ฤลโปโฆ‹โบ|ยฌโ‡นแน—โ‡น3ศ˜โŠฝ ``` See the code below for an explanation - the only differences are (1) that N is decremented before to account for the incrementation at the beginning of the loop, and (2) it uses NOR instead of OR. [Try it online!](https://tio.run/##K6gs@f//UduER427DRKOTn3UuOvIhCMTzu951Db5yATjEzMete88vF0bLPxw5/RDa4B8oFIgebTp6NTDC49MMHi0rPvIhEdtU45MONoIklrWDVRdA1YJ1AEkQaZ07f3/38QYAA) --- I made this before I re-read the question and noticed that it only wanted a true/false. # Pyt, 52 bytes ``` 60`ล•โบฤฤฯผโ†“ฤ3ศ˜โ‡นรท+โบฤแน—ยฌโ‡นโปโ‡นล‚ล•รกฤ0โฆ‹ฤโ†”ฤลโปโฆ‹โบ|ยฌโ‡นฤแน—โ‡น3ศ˜โˆจล‚โ‡นฤฦฅโ‡นล•1ล‚ ``` Prints an infinite list of Redivosite numbers. Explanation: ``` 6 Push 6 0 Push unused character ` ล‚ ล‚ ล‚ Return point for all three loops ล• Remove top of stack โบ Increment top of stack (n) ฤฤ Triplicate top of stack (n) ฯผโ†“ Get smallest prime factor of n (returns 1 if n is prime) ฤ Duplicate top of stack 3ศ˜โ‡น Manipulate stack so that the top is (in descending order): [d,(N,N'),d] รท+โบ Calculates N'=(N,N')/d+d+1 ฤแน—ยฌ Is N' not prime? โ‡นโปโ‡น Decrement N' (so the increment at the beginning doesn't change the value), and keep the boolean on top - end of innermost loop (it loops if top of stack is true) ล• Remove top of stack รก Convert stack to array ฤ Duplicate array 0โฆ‹ฤ Get the first element (N) โ†”ฤลโปโฆ‹ Get the last element ((final N')-1) โบ Increment to get (final N') |ยฌ Does N' not divide N? โ‡นฤแน— Is N prime? โ‡น3ศ˜โˆจ Is N prime or does N' not divide N? - end of second loop (loops if top of stack is true) โ‡นฤฦฅโ‡นล• Print N, and reduce stack to [N] 1 Push garbage (pushes 1 so that the outermost loop does not terminate) ``` [Try it online!](https://tio.run/##K6gs@f//UdsEg4SjUx817joy4ciE83setU0@MsH4xIxH7TsPb9cGCz/cOf3QGiD/UeNuIHm06ejUwwuPTDB4tKz7yIRHbVOOTDjaCJJa1g1UXQNWCdYDpEHmdKw42gQWOrYUpHuq4dGm///NAA) ]
[Question] [ # Background At the time of writing this, the P vs NP problem is still unsolved, but you might have heard of [Norbert Blum's new paper](https://arxiv.org/abs/1708.03486) claiming proof that P != NP, which is already [suspected to be erroneous](https://cstheory.stackexchange.com/a/38832) (but we will see). The problem discussed in this paper is the [clique problem](https://en.wikipedia.org/wiki/Clique_problem). At least that's what I read in a newspaper article, so correct me if I'm wrong, but in any case, I'd like you to write a program that solves the following variant: # The task Assume we have a large school with lots of students. Each of these students has some friends at this school. A **clique** of students is a group consisting only of students who are friends with **each other member**. Your program will receive pairs of students who are friends as its input. From this information, the program must find the **size of the largest clique**. Students are identified by *integer IDs*. If you prefer mathematical terms, this means you're fed the edges of an undirected graph, identified by two nodes each. ### Input Your input will be a non-empty list of positive integer pairs, e.g. `[[1,2],[2,5],[1,5]]`. You can take this input in any sensible form, e.g. as an array of arrays, as lines of text containing two numbers each, etc ... ### Output The expected output is a single number `n >= 2`: the size of the largest clique. With the example input above, the result would be `3`, as all students (`1`, `2` and `5`) are friends with each other. ### Test cases ``` [[1,2]] => 2 [[1,2],[3,1],[3,4]] => 2 [[1,2],[2,5],[1,5]] => 3 [[2,5],[2,3],[4,17],[1,3],[7,13],[5,3],[4,3],[4,1],[1,5],[5,4]] => 4 (the largest clique is [1,3,4,5]) [[15,1073],[23,764],[23,1073],[12,47],[47,15],[1073,764]] => 3 (the largest clique is [23,764,1073]) [[1296,316],[1650,316],[1296,1650],[1296,52],[1650,711],[711,316],[1650,52], [52,711],[1296,711],[52,316],[52,1565],[1565,1296],[1565,316],[1650,1565], [1296,138],[1565,138],[1565,711],[138,1650],[711,138],[138,144],[144,1860], [1296,1860],[1860,52],[711,1639]] => 6 (the largest clique is [52,316,711,1296,1565,1650]) ``` You can use this (stupid) [reference implementation](https://tio.run/##rVfrT9tIEP/uv2KbitROAkp4qBIpnCiCHjpKUe/QnUQRcuxNsuCsXT94FPG3c7Pet70@@HD5ANl578xvZifR@iKKXl7eExolVYzRp6KMSbqx3PcsUkJmTVpO6ILRvPcxnhOK0Zfv3y7Orw9/vzj7A21tKvLpydnR54vj06MzNBlvbnte@Zhh4CEwUUUl@rMEg1T9n3bwv@RplVmHqec5RLwnD8GnIL/wdYlWeDXD@WFaMcNtepiFESkfOUsGMhhwbjH1nls@hHkCciS29HiA85xgGivVsCSRLVDwQ4H20NPYELpLSYwGD6swSdLIF2Gyf4FwyQXS2Q2GaPaQIRjwOMgc@e84P0D4gZT@0T8nf10fH5ycXnw/EkI5LqucIi4GUTb955jbFd6SeIRej0UqKXFHRDWBa7PPPMeYyQtJ9ukK@fkNgYdx/LUumm8le7AY6bIWMnoW1mJ938AG2ttDmiJQ0Qy5JYCGeybop21JVmWVUk0dKclu24M6kekc7qD0rIRo8qV9meHwCtwWZo5UDha4FN99DmGZk3maI4k6AurjKfz7pNC6YTYSGg5JMzkspw3h4pJcre9DcSC54EhW0CHlqPPYGT6U2R2@LjLLuNEbLIEybwWPRjUunEW7blhYYM7dfFmcbpFC8zQm@/LO0B12H3ZW6Vt@8Ka7mgWNzbYrAsT4Zsbi//Atu@iY38bXKTc6aCZDMK4WqgyM0Cxo3XxmsMPA9MgulYV5gc9DkvtRSosSRcswR4MEno3AGLShLBg7zNSBIa6IQjr3mcII9dZitBb3RqgPCvB3xkAH2NtsYlXfjSfQynVIzJmkr@4QnVmiRvJCnQoj35PXYF7XIFri6PaAxuDnMCE/K@yca1HNcg43ON3S9J5@fjxIEohauO1ocG7Imh/u/pZmNb6t/GRAt23pxm66v@Hub8B95mxBFsFNoHSfrHHJ6t5SKy5v1Kyp2zywdJ5aA1feZTJtsWYwsG9t8rPX/lZ3WW2mK1KrDGPbYsPJswENZlirNguhe0tiQD8LDSgVOMyj5WmYLyCvtXADRU0YSXKW4zuSVsX/9Th0YVr5d7wJ1lvHUiKlA/vl3ke@jtdiNaPoknMiWqSiXDFgC89aSBAYS9o0mJIEbNA374GTAreicl5LxdRRVZ7H4oSe43xVMTYMUFkj2qqo8GEvx4PIeCypsXFEIvkQUIFLPxqh8Qi5BGwvFD@UjueXkW2DjFLbdIjYJo1UNs2qYlqmJdUyb4jy@7cbo89j6rdETdTXlPslSTDyWQNQ1xYUAXiBR7qmglyn78Psb1IuwbBP@pMAsss0h0N7TqgBy5HYahRp5spW65ZzGSGvaZMrE8tK7E1ptGa33Wt6mKrGaOcLssI32rF7XNa/JCQg6wOLobkzK4Y46w7WDawbrd5D2FYxq@aX@gcspMljD@EqJLReyuDq0Bx8axnA4c58hWPQXui4GTaYPEysCer30Tv4YRmtMka7u5xcwf6yHveCQKlNBAIF3uawfRS@iGlk/Kpm0zMmNGA29T4lBAOJY9f6MDWaoWOeOCY8VFdME2E6y@G2c5/H/RvqJQwQbJnjGWZ430VrSfWD9tAubGn1N/snkF/RgiwojlGS0kXg2kqkN5bG2lWz90QYPeFWlH@3F7iXkDfvQG1ESk9822xvPfX@4UJ5VpUMK/6HH/SDet8MENuWTOTaGTeXx5eXTbTjbaItbxtNPnoT@PIRTba8nZpSU4G4A@dt72U9/hc) (prints extra output with `-d` flag) for verifying the results of other test cases. # The rules 1. Your program doesn't need a defined result on invalid input. So you can assume that: * you will always get **at least one pair** of IDs * each pair consists of two different IDs * no pair appears twice (swapping the places of the IDs would still be the same pair) 2. Your algorithm isn't allowed to set an upper bound on input size. Purely technical limitations and limitations set by your language/environment (like stack size, computation time, etc) are of course inevitable. 3. Standard loopholes are forbidden. 4. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, measured in bytes, wins. 5. If your algorithm has polynomial time complexity, you score `-1` immediately regardless of your code size, but in that case, you might want to submit your solution somewhere else. ;) [Answer] # Mathematica, 34 bytes ``` Tr[1^#&@@FindClique[#<->#2&@@@#]]& ``` Basically [FindClique](http://reference.wolfram.com/language/ref/FindClique.html) does the job and "finds a largest clique in the graph g." All the other stuff is converting input-list into graph **Input** > > [{{2, 5}, {2, 3}, {4, 17}, {1, 3}, {7, 13}, {5, 3}, {4, 3}, {4, > 1}, {1, 5}, {5, 4}}] > > > **Output** > > 4 > > > **Input** > > [{{1296, 316}, {1650, 316}, {1296, 1650}, {1296, 52}, {1650, > 711}, {711, 316}, {1650, 52}, {52, 711}, {1296, 711}, {52, > 316}, {52, 1565}, {1565, 1296}, {1565, 316}, {1650, 1565}, {1296, > 138}, {1565, 138}, {1565, 711}, {138, 1650}, {711, 138}, {138, > 144}, {144, 1860}, {1296, 1860}, {1860, 52}, {711, 1639}}] > > > **Output** > > 6 > > > *thanx @Kelly Lowder for -10 bytes* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15 18~~ 16 [bytes](https://github.com/DennisMitchell/jelly/Code-page) +3 bytes to fix bugs in my method. -2 bytes thanks to miles (noting that **nร—(n-1)รท2 = nC2**) ``` แบŽQLยฉc2โผLศงยฎ ล’Pร‡โ‚ฌแน€ ``` A monadic link taking the list of friendships (edges) and returning an integer. **[Try it online!](https://tio.run/##y0rNyan8///hrr5An0Mrk40eNe7xObH80Dquo5MCDrc/alrzcGfD////o6MNTXUMDcyNY3WijYx1zM1MIAyokKGRjok5kDYx1zE0BfGBwmBFsQA "Jelly โ€“ Try It Online")** forms the power-set of the edges in memory so is inefficient both in space and time (yep,that's **O(2n)** folks)! ### How? ``` แบŽQLยฉc2โผLศงยฎ - Link 1, isClique?: list, edges e.g. [[1,3],[2,3],[3,4],[4,1],[4,2],[2,1]] แบŽ - tighten [ 1,3 , 2,3 , 3,4 , 4,1 , 4,2 , 2,1 ] Q - de-duplicate (gets unique ids) [1,3,2,4] L - length (get number of people involved) 4 ยฉ - (copy to the register) c2 - combinations of 2 (z-choose-2) 6 L - length (of edges) 6 โผ - equal? 1 ยฎ - recall value from register 4 ศง - logical and 4 - (Note: the number of edges of a clique of size n is n*(n-1) and we're - guaranteed no repeated edges and that all edges are two distinct ids) ล’Pร‡โ‚ฌแน€ - Link: list of lists, edges ล’P - power-set (all possible sets of edges (as lists)) ร‡โ‚ฌ - call last link (1) as a monad for โ‚ฌach แน€ - maximum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ล’PแบŽโ‚ฌยตQLโ€™=ฤ‹รโ‚ฌ`แบ ยตรfแนชQL ``` [Try it online!](https://tio.run/##y0rNyan8///opICHu/oeNa05tDXQ51HDTNsj3YcnALkJD3ctOLT18IS0hztXBfr8//8/OtpIxzRWB0gaA0kTHUNzIGUI5pjrGIIoU6gMVB4sbQoWN4mNBQA "Jelly โ€“ Try It Online") Of course this doesn't deserve the million :p This would've beat Pyth, if not for the `ยต(...)ยต` and 2-byte `รf`. [Answer] # [J](http://jsoftware.com/), 36 bytes ``` [:>./](#(]*[=2!])#@~.@,)@#~2#:@i.@^# ``` [Try it online!](https://tio.run/##ZYzBCsIwEETv/YqRvbQi0WzSBgKV/EeNHsSiXvoH/fW4G/CgZZcd9g0z71JmjBFTPJtjbqnN@2nkXe4orSYdukQrU0wvk67UNI/7c8GMGyNfYMEbACfXwW8NRi/a/xoKNeNhQw3KdcKUVKoRmf8@qToFB5bA4FXqaxk@6H59MUv5AA "J โ€“ Try It Online") Runs in time *O*(2*n*) where *n* is the number of pairs. A faster solution for 65 bytes is ``` 3 :'$>{._2{~.@((+.&(e.&y)&<|.)@(-.,-.~)&>/#&,/:~@~.@,&.>/)~^:a:y' ``` [Try it online!](https://tio.run/##ZU7bDoIwDH33K5poBkQY7gouSPgQozFGY3zx2Wj4dWwLGIVs7c5lp9u9666wC2AgRKv6JY/61comjtdSxBcpnomo3jJp4kymmWwTUedLkeahbfBWKmSdJ@0hnMIzWiwu59sDrnDUUO1BgZ4J@IjCsnNDg8PT/RskUsaCKjiI3aBGCqsUwTWdh6M2hQGNAW/pYKo02IL26KM5CeqtB6M8KO82PSCFGSOne1IoxfW9iwZukvgeAeRkU8R5NzQeR@ib/NFNObAR8Dwi45tMqKztq/TDz3pEbfyHN9uu@wA) ## Explanation ``` [:>./](#(]*[=2!])#@~.@,)@#~2#:@i.@^# Input: list of pairs # Length 2 ^ 2^n i.@ Range [0, 2^n) #:@ Binary #~ Copy ( )@ For each , Flatten ~.@ Unique #@ Length ( ) Dyad with RHS at previous and LHS as next ] Get RHS 2! Binomial coefficient, choose 2 = Equals [ Get LHS * Times ] Get RHS # Length [:>./ Reduce using maximum ``` [Answer] # Pyth, 19 bytes ``` l{ef.AqLtl{T/LTTsMy ``` [Try it here.](http://pyth.herokuapp.com/?code=l%7Bef.AqLtl%7BT%2FLTTsMy&input=%5B%5B15%2C1073%5D%2C%5B23%2C764%5D%2C%5B23%2C1073%5D%2C%5B12%2C47%5D%2C%5B47%2C15%5D%2C%5B1073%2C764%5D%5D&debug=0) [Answer] # [Python 2](https://docs.python.org/2/), 180 bytes ``` G=input() m=0 L=len for i in range(2**L(G)): u=[];p=sum([G[j]for j in range(L(G))if 2**j&i],u) for j in p:u+=[j][j in u:] m=max(m,L(u)*all(p.count(j)==L(u)-1for j in u)) print m ``` [Try it online!](https://tio.run/##RYtBCoMwFET3OUVWJbFpaWxFsPy1G28QspCibcTEYP3Qnj6NQexmhpl547/La3J5CDUY53FhnFi4kAbGzpF@mqmhxtG5dc@O5VnWsJrzilAEpe8e3miZqtWgV3L4kwkzPY2P4WC0QE7ojvgKjxA/KiWsNKEWbPthVjQMedaOI/Pnx4RuYQMHWMuT3O/IOfGzcQu1ISiVi0KLqNeoNyHLaDKFUsjVim3Z9jQXqb9p/QM "Python 2 โ€“ Try It Online") -2 thanks to [shooqie](https://codegolf.stackexchange.com/users/51530/shooqie). -1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). -3 thanks to [recursive](https://codegolf.stackexchange.com/users/527/recursive). [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 774 703 bytes (I just **had** to do this, my C64 can do everything ... hehe) **hexdump:** ``` 00 C0 A9 00 A2 08 9D 08 00 CA 10 FA A2 04 9D FB 00 CA 10 FA 20 54 C0 B0 20 AD C9 C2 AE CA C2 20 92 C1 B0 31 8D 31 C0 AD CB C2 AE CC C2 20 92 C1 B0 23 A2 FF 20 FE C1 90 DB 20 6A C2 20 C1 C1 B0 05 20 6A C2 50 F6 A5 FB 8D D3 C2 20 43 C1 A9 CD A0 C2 20 1E AB 60 A2 00 86 CC 8E 61 C0 20 E4 FF F0 FB A2 FF C9 0D F0 10 E0 0B 10 0C 9D BD C2 20 D2 FF E8 8E 61 C0 D0 E5 C6 CC A9 20 20 D2 FF A9 0D 20 D2 FF A9 00 9D BD C2 AA BD BD C2 F0 5C C9 30 30 0E C9 3A 10 0A 9D CD C2 E8 E0 06 F0 4C D0 E9 C9 20 D0 46 A9 00 9D CD C2 E8 8E BC C0 20 EB C0 AD D3 C2 8D C9 C2 AD D4 C2 8D CA C2 A2 FF A0 00 BD BD C2 F0 0F C9 30 30 21 C9 3A 10 1D 99 CD C2 C8 E8 D0 EC A9 00 99 CD C2 20 EB C0 AD D3 C2 8D CB C2 AD D4 C2 8D CC C2 18 60 38 60 A2 FF E8 BD CD C2 D0 FA A0 06 88 CA 30 0A BD CD C2 29 0F 99 CD C2 10 F2 A9 00 99 CD C2 88 10 F8 A9 00 8D D3 C2 8D D4 C2 A2 10 A0 7B 18 B9 53 C2 90 02 09 10 4A 99 53 C2 C8 10 F2 6E D4 C2 6E D3 C2 CA D0 01 60 A0 04 B9 CE C2 C9 08 30 05 E9 03 99 CE C2 88 10 F1 30 D2 A2 06 A9 00 9D CC C2 CA D0 FA A2 08 A0 04 B9 CE C2 C9 05 30 05 69 02 99 CE C2 88 10 F1 A0 04 0E D3 C2 B9 CE C2 2A C9 10 29 0F 99 CE C2 88 10 F2 CA D0 D9 C8 B9 CD C2 F0 FA 09 30 9D CD C2 E8 C8 C0 06 F0 05 B9 CD C2 90 F0 A9 00 9D CD C2 60 85 0A A4 09 C0 00 F0 11 88 B9 D5 C2 C5 0A D0 F4 8A D9 D5 C3 D0 EE 98 18 60 A4 09 E6 09 D0 01 60 A5 0A 99 D5 C2 8A 99 D5 C3 98 99 D5 C4 18 60 A6 0B E4 09 30 01 60 BD D5 C5 C5 0B 30 09 A9 00 9D D5 C5 E6 0B D0 E9 A8 FE D5 C5 8A 29 01 D0 02 A0 00 BD D5 C4 59 D5 C4 9D D5 C4 59 D5 C4 99 D5 C4 5D D5 C4 9D D5 C4 A9 00 85 0B 18 60 A8 A5 0C D0 08 A9 20 C5 0D F0 21 A5 0C 8D 1E C2 8D 21 C2 A5 0D 09 60 8D 1F C2 49 E0 8D 22 C2 8C FF FF 8E FF FF E6 0C D0 02 E6 0D 18 60 86 0E 84 0F A5 0D 09 60 8D 54 C2 49 E0 8D 5F C2 A6 0C CA E0 FF D0 10 AC 54 C2 88 C0 60 10 02 18 60 8C 54 C2 CE 5F C2 BD 00 FF C5 0E F0 04 C5 0F D0 E0 BD 00 FF C5 0E F0 04 C5 0F D0 D5 38 60 A2 00 86 FC 86 FD 86 FE BD D5 C4 A8 A6 FE E4 FC 10 11 BD D5 C7 AA 20 2B C2 90 14 E6 FE A6 FE E4 FC D0 EF A6 FD BD D5 C4 A6 FC E6 FC 9D D5 C7 E6 FD A6 FD E4 09 D0 16 A6 FB E4 FC 10 0F A2 00 BD D5 C7 9D D5 C6 E8 E4 FC D0 F5 86 FB 60 A0 00 84 FE F0 B5 ``` ### [Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"clique.prg":"data:;base64,AMCpAKIInQgAyhD6ogSd+wDKEPogVMCwIK3Jwq7KwiCSwbAxjTHArcvCrszCIJLBsCOi/yD+wZDbIGrCIMHBsAUgasJQ9qX7jdPCIEPBqc2gwiAeq2CiAIbMjmHAIOT/8Pui/8kN8BDgCxAMnb3CINL/6I5hwNDlxsypICDS/6kNINL/qQCdvcKqvb3C8FzJMDAOyToQCp3NwujgBvBM0OnJINBGqQCdzcLojrzAIOvArdPCjcnCrdTCjcrCov+gAL29wvAPyTAwIck6EB2ZzcLI6NDsqQCZzcIg68Ct08KNy8Kt1MKNzMIYYDhgov/ovc3C0PqgBojKMAq9zcIpD5nNwhDyqQCZzcKIEPipAI3Two3UwqIQoHsYuVPCkAIJEEqZU8LIEPJu1MJu08LK0AFgoAS5zsLJCDAF6QOZzsKIEPEw0qIGqQCdzMLK0PqiCKAEuc7CyQUwBWkCmc7CiBDxoAQO08K5zsIqyRApD5nOwogQ8srQ2ci5zcLw+gkwnc3C6MjABvAFuc3CkPCpAJ3NwmCFCqQJwADwEYi51cLFCtD0itnVw9DumBhgpAnmCdABYKUKmdXCipnVw5iZ1cQYYKYL5AkwAWC91cXFCzAJqQCd1cXmC9DpqP7VxYopAdACoAC91cRZ1cSd1cRZ1cSZ1cRd1cSd1cSpAIULGGCopQzQCKkgxQ3wIaUMjR7CjSHCpQ0JYI0fwkngjSLCjP//jv//5gzQAuYNGGCGDoQPpQ0JYI1UwkngjV/CpgzK4P/QEKxUwojAYBACGGCMVMLOX8K9AP/FDvAExQ/Q4L0A/8UO8ATFD9DVOGCiAIb8hv2G/r3VxKim/uT8EBG91ceqICvCkBTm/qb+5PzQ76b9vdXEpvzm/J3Vx+b9pv3kCdAWpvvk/BAPogC91ced1cbo5PzQ9Yb7YKAAhP7wtQ=="%7D,"vice":%7B"-autostart":"clique.prg"%7D%7D) Usage: Start with `sys49152`, then enter the pairs one per line like e.g. ``` 15 1073 23 764 23 1073 12 47 47 15 1073 764 ``` Backsapce **isn't** handled during input (but if you use `vice`, just copy&paste your input into the emulator). Enter an empty line to start calculation. This is too large to post an explanatory disassembly listing here, but [you can browse the ca65-style assembly source](https://github.com/Zirias/c64clique/tree/0eb3304f7461b59ff6da74e48c30ca29f2aec8b2). The algorithm is very inefficient, it generates every possible permutation of the nodes and with each of these greedily builds a clique by checking all the edges. This allows for a *space efficiency* of **O(n)** (kind of important on a machine with this little RAM), but has **horrible** *runtime efficiency* **(\*)**. The theoretical limits are up to 256 nodes and up to 8192 edges. * -71 bytes: optimized routine for checking edges and zeropage usage --- There's a larger (883 805 bytes) version with better features: * visual feedback during calculation (each permutation of the nodes changes the border color) * uses bank switching to store the edges in the RAM "hidden" by the ROMs to conserve space * outputs the size **and** the nodes of the maximal clique found **[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"clique.prg":"data:;base64,AMCpAKIInQgAyhD6ogSd+wDKEPogX8CwIK0vw64wwyCgwbA8jTHArTHDrjLDIKDBsC6i/yAiwpDbeKkFhQGtINCFCCCOwu4g0CDPwbAFII7CUPOpB4UBWKUIjSDQIOHCYKIAhsyObMAg5P/w+6L/yQ3wEOALEAydI8Mg0v/ojmzA0OXGzKkgINL/qQ0g0v+pAJ0jw6q9I8PwXMkwMA7JOhAKnTPD6OAG8EzQ6ckg0EapAJ0zw+iOx8Ag9sCtOcONL8OtOsONMMOi/6AAvSPD8A/JMDAhyToQHZkzw8jo0OypAJkzwyD2wK05w40xw606w40ywxhgOGCi/+i9M8PQ+qAGiMowCr0zwykPmTPDEPKpAJkzw4gQ+KkAjTnDjTrDohCgexi5ucKQAgkQSpm5wsgQ8m46w245w8rQAWCgBLk0w8kIMAXpA5k0w4gQ8TDSogapAJ0yw8rQ+qIQoAS5NMPJBTAFaQKZNMOIEPGgBA45wy46w7k0wyrJECkPmTTDiBDyytDWyLkzw/D6CTCdM8PoyMAG8AW5M8OQ8KkAnTPDYIUKpAnAAPARiLk7w8UK0PSK2TvE0O6YGGCkCeYJ0AFgpQqZO8OKmTvEmJk7xRhgpgvkCTABYL07xsULMAmpAJ07xuYL0Omo/jvGiikB0AKgAL07xVk7xZ07xVk7xZk7xV07xZ07xakAhQsYYL07w405w707xI06wyBOwakzoMNMHquopQzQCKkgxQ3wIaUMjULCjUXCpQ0JoI1DwgngjUbCjP//jv//5gzQAuYNGGCGDoQPpQ0JoI14wklAjYPCpgzK4P/QEKx4wojAoBACGGCMeMLOg8K9AP/FDvAExQ/Q4L0A/8UO8ATFD9DVOGCiAIb8hv2G/r07xaim/uT8EBG9O8iqIE/CkBTm/qb+5PzQ76b9vTvFpvzm/J07yOb9pv3kCdAWpvvk/BAPogC9O8idO8fo5PzQ9Yb7YKAAhP7wtakAhf6NOsOl+405wyBOwakzoMMgHqupICDK8albIMrxpv69O8eqIAzC5v6m/uT78AepLCDK8ZDoqV0gyvGpDUzK8Q=="%7D,"vice":%7B"-autostart":"clique.prg"%7D%7D)** **[Browse source](https://github.com/Zirias/c64clique/tree/master)** --- **(\*)** The last test case takes something between 12 and 20 hours (I was sleeping when it finally finished). The other test cases finish at worst within some minutes. [![Screenshot of last test case](https://i.stack.imgur.com/eFO8M.png)](https://i.stack.imgur.com/eFO8M.png) [Answer] # Pyth, 28 bytes ``` l{sSef<T.{SMQm.{ft{T.Cd2yS{s ``` [Try it online](http://pyth.herokuapp.com/?code=l%7BsSef%3CT.%7BSMQm.%7Bft%7BT.Cd2yS%7Bs&input=[%282%2C5%29%2C%282%2C3%29%2C%284%2C17%29%2C%281%2C3%29%2C%287%2C13%29%2C%285%2C3%29%2C%284%2C3%29%2C%284%2C1%29%2C%281%2C5%29%2C%285%2C4%29]&debug=0) ### Explanation ``` l{sSef<T.{SMQm.{ft{T.Cd2yS{s S{sQ Get the distinct nodes in the (implicit) input. y Take every subset. m .Cd2 Get the pairs... ft{T ... without the [x, x] pairs... .{ ... as sets. f<T Choose the ones... .{ Q ... which are subsets of the input... SM ... with edges in sorted order. e Take the last element (largest clique). l{sS Get the number of distinct nodes. ``` [Answer] # [Python 3](https://docs.python.org/3/), 162 159 bytes ``` lambda x,f=lambda x:{i for s in x for i in s}:len(f(x))if all([(y,z)in x or(z,y)in x for y in f(x)for z in f(x)if y<z])else max(c(x.difference({y}))for y in x) ``` [Try it online!](https://tio.run/##RYzNCsIwEITvPkXAyy4sYvpjoeiTqIdaEwzEVFoPSYvPXrOx6mlnduabR3jeOpfP7eE02@Z@uTbCkz58ZT0ZobteDMI44ZM0LIdXbZUDDR7RaNFYC0cINGKqdT2MFPCHBEa4y2b8msiF/XhGZQcl7o2HFvzmarRWvXKtgim8EH@4x/nRG/eMrQlkSXJb5UiQ5VTtio9YXjKjooq3qEiW7OM7leLcav0fyYjTjJgpSDIik4kcn3JJljzFZfqnqfkN "Python 3 โ€“ Try It Online") Function c takes vertices in the form of a set of sorted tuples ({(x,y),...} where x is less than y). A function called "entry" is in the TIO header to test with data in list of unsorted lists format. If clique, returns length. If not clique, returns max clique size of vertices, minus a vertice for each vertice in vertices. Exceeds time on last test case in TIO Update: "or(z,y)in x" portion added to remove dependency on sortedness "f=lambda x:{i for s in x for i in s}" instead of itertools.chain wrapped in set. -minus 3 bytes thanks to @Jonathan Allen [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` รฆโ‚ฌหœส’Dร™g<s{ฮณโ‚ฌgQP}ฮธร™g ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8LJHTWtOzzk1yeXwzHSb4upzm4H89MCA2nM7gAL//0dHG@mYxuoASWMgaaJjaA6kDMEccx1DEGUKlYHKg6VNweImsbEA "05AB1E โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` ล“^eยณ;Uยค ล’cรง/รfล“|แนขยฅ/โ‚ฌQยตรฤฟ-แป‹แธขL ``` [Try it online!](https://tio.run/##y0rNyan8///o5LjUQ5utQw8t4To6Kfnwcv3DE9KOTq55uHPRoaX6j5rWBB7aenjCkf26D3d3P9yxyOf////R0YZGlmY6xoZmsTrRhmamBjAmSBTEh7FNjWAKzA0NgUwgiawLLG1qBJUE64AwgWIQZUCGoamZKUgWSOmAlMDYSObAlICtN7aAq0YwoTYYW8CcB3IJVB4kaGICYpmY6BhamMFdD2MDKYhTwZrMjC1jYwE "Jelly โ€“ Try It Online") Faster solution that is able to solve the last test case in a second on TIO. [Answer] # Java + Guava 23.0, 35 + 294 = 329 bytes ``` import com.google.common.collect.*; a->{int l=0,o=1,c,z=a.size();for(;o>0&l<z;){o=0;c:for(Iterable<int[]>s:Sets.combinations(a,l*(l+1)/2)){Multiset<Integer>m=TreeMultiset.create();for(int[]x:s){m.add(x[0]);m.add(x[1]);}c=m.elementSet().size();for(int e:m.elementSet())if (m.count(e)!=c-1)continue c;l+=o=1;break;}}return z<3?2:l;} ``` This algorithm is not graphing, but instead is generating all combinations of pairs, of a specific size. I feed all pair-combinations into a multiset and check that they all have the expected size (the number of unique entries - 1). If they do, I found a clique and I go look for a bigger one. From the Guava library, I use the new `combinations` method, and the tool-collection-type `Multiset`. # Ungolfed ``` import com.google.common.collect.*; import java.util.function.*; public class Main { public static void main(String[] args) { ToIntFunction<java.util.Set<int[]>> f = a -> { int l = 0, o = 1, c, z = a.size(); for (; o > 0 & l < z;) { o = 0; c: for (Iterable<int[]> s : Sets.combinations(a, l * (l + 1) / 2)) { Multiset<Integer> m = TreeMultiset.create(); for (int[] x : s) { m.add(x[0]); m.add(x[1]); } c = m.elementSet().size(); for (int e : m.elementSet()) { if (m.count(e) != c - 1) { continue c; } } l += o = 1; break; } } return z < 3 ? 2 : l; }; int[][][] tests = { {{1, 2}}, {{1, 2}, {3, 1}, {3, 4}}, {{1, 2}, {2, 5}, {1, 5}}, {{2, 5}, {2, 3}, {4, 17}, {1, 3}, {7, 13}, {5, 3}, {4, 3}, {4, 1}, {1, 5}, {5, 4}}, {{15, 1073}, {23, 764}, {23, 1073}, {12, 47}, {47, 15}, {1073, 764}}, {{1296, 316}, {1650, 316}, {1296, 1650}, {1296, 52}, {1650, 711}, {711, 316}, {1650, 52}, {52, 711}, {1296, 711}, {52, 316}, {52, 1565}, {1565, 1296}, {1565, 316}, {1650, 1565}, {1296, 138}, {1565, 138}, {1565, 711}, {138, 1650}, {711, 138}, {138, 144}, {144, 1860}, {1296, 1860}, {1860, 52}, {711, 1639}} }; for (int[][] test : tests) { java.util.Set<int[]> s = new java.util.HashSet<int[]>(); for (int[] t : test) { s.add(t); } System.out.println(f.applyAsInt(s)); } } } ``` [Answer] # [Python 2](https://docs.python.org/2/), 102 bytes ``` def f(g): x=g while x:y=x;x=map(set,{tuple(u|v)for u in x for v in x if u^v in g}) return len(y[0]) ``` [Try it online!](https://tio.run/##bVDLboMwELzzFT6CtAf8hKTiS6JUqlRDkChBFFIQzbfTXWOnoepldzwzuztyNw@XayvW9d2WrIyr5Bixqagi9nWpG8um41xML1Px8dbFn3aAZRi7xsbj9y0prz0bWd2yiRG8bbAu2fjqcHVPItbbYexb1tg2nk/pOVm7vm4HPHRaOIj7OYn2BCwSuKvqP1GAxsqx7sSNFiCxKuCZ89AjA05Ne8XrfgXxf69o4GlGNiEhM2oDnuICFK1WuNXFQNqZ9ivEwYDkhgxGpwESS@@AtQiGjFMgrM9TTtbCi25ig8htNgRcG5cDG5Al4Kc9weLOy/zh/oX@gsxDPEridSIVfQJW4Ll5pA8Y2xbVDRl5wL9YfwA "Python 2 โ€“ Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~790 778 757 748 731 687 642~~ 632 bytes ``` typedef struct F F;typedef struct{int c,p;F**m;}g;struct F{int d;g f;};g*a,S,y,q,*x=&y,*p=&q,Q;A(g*g,F*s){g->c++[g->m=g->c-g->p?g->m:realloc(g->m,(g->p+=32)*20)]=s;}i,c[999],b,j,k,l,*s;*B(d){s=0;for(i=S.c;i--;)s=S.m[i]->d-d?s:S.m[i];!s?s=calloc(5,4),*s=d,A(&S,s):0;s=s;}F*u,*v;E(){for(i=-1;b=++i<S.c;b&&A(x,S.m[i]))for(l=x->c;k=l--*b;b&=!k)for(j=(Q=x->m[l]->f).c;j--&&(k=Q.m[j]->d-S.m[i]->d););x->c>p->c?a=x,x=p,p=a:0;x->c=0;}main(){for(;~scanf("%d %d",&a,&b)&&A(&(u=B(a))->f,v=B(b))|~A(&v->f,u););for(E();b<S.c;)c[b]>=b?c[b++]=0:E(S.m[b]=a,S.m[i]=S.m[b],a=S.m[i=b%2*c[b]++]);for(printf("%d,",i=p->c);i--;)printf(" %d",p->m[i]->d);} ``` This is a slightly golfed version of the reference implementation. Thanks to @jdt for -5. [Try it online!](https://tio.run/##VVJNb@JADL3zK1IkopmJsyKBZIFZg1qp3BFHlEM@IAoEmhJAIJb@dWpnoKs9jOfZzx/Pk6Runqb3@@FSLbPlyqoP@2N6sKbWVP8fuha7g5VCpadKbfUt18/Mhsh0bq30Tecqhjlc4BPUGe0LqArtT5jpV5GrHKaqltfcHaeOs6Bri4xdMtWE3dF@GZflRyrYAbaVgz1fKr8rI6z1rYB0MRwOI0hgDRsoQdVavYlMXmvs6tXHXhQ4/5XqwnW1rAluF0XkjjM3m9Qj4@mXelJjauYE0JfUAzN4FfYcajnq6poHTdUR1Em/C3k1XV1PJ@g4xR9un9j2qziDaSglZ5R4plX0BkvXVQll4MumIdYoZsxtFyUpWUkqX7uubYsNzqh@3cj7ESq11NxoXJGZxHiGM1ZQYUzCOE5b3rZxsXvo0l91Gu9Wot3JrE7WBjsGO5GszhZHfBOxlDQTTgQTKf9@UfzEgSPP4Qa0oE6anWS6SKIxJhO6HSfC7uhdsKwkwvixKRofYvOwmHR8xVWUbrpVe/oVGjXQhgJ5B2m@xZNpVFb8Go91b/e75w9Dq@eFLS8MugZwhD2DAt9Qvz2vRedfLhGB34SbPAbkM02XF4RBi43FpEE/lYZsxvQGj6wnaPr1BkYAz2sYDvT7LTqWNwgfygwiw1Ka1LA3/AY "C (gcc) โ€“ Try It Online") Slightly golfed less ``` typedef struct F F; // student group typedef struct{ int c, // count p; // capacity F**m; // members }g; // student struct F{ int d; // id g f; // friends }; g*a,S,y,q,*x=&y,*p=&q,Q; A(g*g,F*s){ g->c++[g->m=g->c-g->p?g->m:realloc(g->m,(g->p+=32)*20)]=s; } i,c[999],b,j,k,l,*s; *B(d){ s=0; for(i=S.c;i--;) s=S.m[i]->d-d?s:S.m[i]; !s? s=calloc(5,4), *s=d, A(&S,s) : 0; s=s; } F*u,*v; E(){ for(i=-1;b=++i<S.c;b&&A(x,S.m[i])) for(l=x->c;k=l--*b;b&=!k) for(j=(Q=x->m[l]->f).c;j--&&(k=Q.m[j]->d-S.m[i]->d);); x->c>p->c? a=x, x=p, p=a : 0; x->c=0; } main(){ for(;~scanf("%d %d",&a,&b)&&A(&(u=B(a))->f,v=B(b))|~A(&v->f,u);); for(E();b<S.c;) c[b]>=b? c[b++]=0 : E(S.m[b]=a,S.m[i]=S.m[b],a=S.m[i=b%2*c[b]++]); for(printf("%d,",i=p->c);i--;) printf(" %d",p->m[i]->d); } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes ``` l{seq#.c{sT2tySSM ``` [Try it online!](https://tio.run/##K6gsyfj/P6e6OLVQWS@5ujjEqKQyONj3///oaCMd01gdIGkMJE10DM2BlCGYY65jCKJMoTJQebC0KVjcJDYWAA "Pyth โ€“ Try It Online") * `SSM`: Sort each edge, then sort the edges. * `y`: Form all subsets of edges, with each subset in sorted order. The subsets are ordered by increasing length. * `t`: Remove the first subset, which is the empty subset, as it would cause the program to crash. * `q#`: Filter over the subsets on the following resulting in an identical list of edges as the particular subset. * `{sT`: Sum the list and deduplicate, giving all vertices in any of the edges. If the subset was a clique, the vertices will be in sorted order. * `.c ... 2`: All distinct pairs of vertices, in sorted order. * `e`: The filter returns all cliques. Take the last clique, which is the largest clique. * `{s`: Sum and deduplicate, giving the vertices in the largest clique. * `l`: Length of the longest clique. Apparently, during the brief window from May 2017 to Nov. 2017, during which this challenge was posted, `sY` returned an empty list, rather than 0, as it currently does, so the `t` could have been removed for -1 byte. Before and after, this would cause a crash. See [commit 5b973af89b](https://github.com/isaacg1/pyth/blob/5b973af89bbd0bf3d0a255e3d2dfffbda72c1d0b/macros.py#L983), which was the most recent commit when this challenge was posted. ]
[Question] [ This: [![enter image description here](https://i.stack.imgur.com/x5VNu.png)](https://i.stack.imgur.com/x5VNu.png) is a *Glider*. In Conway's Game of Life, the [glider](https://en.wikipedia.org/wiki/Glider_(Conway%27s_Life)) is a famous pattern that rapidly traverses across the board. For today's challenge, we are going to draw an ASCII art Game of Life Board, and place a glider on it. The board we are starting with is this: ``` |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| ``` This board is made up entirely of pipes `|` and underscores `_`, and is 10x10. You must write a program or function that takes in two integers, 'x' and 'y', and outputs this same board with a glider at those coordinates. For example, if you had a glider at position `(1, 1)` (0-indexed), you must output the following: ``` |_|_|_|_|_|_|_|_|_|_| |_|_|*|_|_|_|_|_|_|_| |_|_|_|*|_|_|_|_|_|_| |_|*|*|*|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| ``` You can assume that the glider will never be placed out of bounds, so both x and y will always be in the `[0-7]` range. You may also choose to take the coordinates 1-indexed, but you must specify this in your answer. In this, case the inputs will always be in the `[1-8]` range. Here are some examples (all 0-indexed): ``` 0, 0: |_|*|_|_|_|_|_|_|_|_| |_|_|*|_|_|_|_|_|_|_| |*|*|*|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| 7, 7: |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|*|_| |_|_|_|_|_|_|_|_|_|*| |_|_|_|_|_|_|_|*|*|*| 7, 4: |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|*|_| |_|_|_|_|_|_|_|_|_|*| |_|_|_|_|_|_|_|*|*|*| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| 5, 2: |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|*|_|_|_| |_|_|_|_|_|_|_|*|_|_| |_|_|_|_|_|*|*|*|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| ``` As usual, you may take your IO in any reasonable format. This includes, but is not limited to a string with newlines, an array of strings, a 2d array of strings, or writing to a file/STDOUT. You may also choose what order to take *x* and *y* in. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard loopholes are banned, and make the shortest code that you can! [Answer] # [MATL](https://github.com/lmendo/MATL), ~~35~~ ~~32~~ 30 bytes ``` 20*+'|_'5E:21:I$)42b' 34'Q+( ``` The code contains unprintable chars. Input is 0-based. **[Try it online!](https://tio.run/##y00syfn/38hAS1u9Jl7d1NXKyNDKU0XTxChJnUdOwdhEPVBb4/9/cy4TAA "MATL โ€“ TIO Nexus")** [Answer] # [V](https://github.com/DJMcMayhem/V), ~~31~~, 30 bytes ``` 10Oยฑยฐ_|ร€Gjjร€|3r*kr*kh.ร*รผ_/|& ``` [Try it online!](https://tio.run/##K/v/39DA/9DGQxvia6QPN7hnZR1uqDEu0soGogy9w71ah/fE69eo/f//3@i/EQA "V โ€“ Try It Online") Hexdump: ``` 00000000: 3130 4fb1 b05f 7c1b c047 6a6a c07c 3372 10O.._|..Gjj.|3r 00000010: 2a6b 722a 6b68 2ecd 2afc 5f2f 7c26 *kr*kh..*._/|& ``` This takes input as program arguments, and 1-indexed. Explanation: ``` 10O " On the following 10 lines, insert: ยฑยฐ_ " 10 '_' characters | " And a '|' <esc> " Return to normal mode ร€G " Go to the a'th line jj " Move down two lines ร€| " Go to the b'th column 3r* " and replace the next 3 characters with asterisks k " Move up a line r* " And replace this char with an asterisk kh " Move up a line and to the left . " And repeat the last change we performed (replace with asterisk) " ร " On every line, substitute: * " An asterisk รผ " OR _ " An underscore / " With: |& " A bar followed by the matched pattern ``` [Answer] # Java 10, ~~165~~ ~~144~~ ~~138~~ ~~135~~ ~~129~~ ~~127~~ 125 bytes ``` x->y->{var r="";for(int i=0,j;++i<11;r+="|\n")for(j=0;j<10;)r+=i==x&j==y|i==x+1&++j==y|i==x+2&j<y+3&j>=y?"|*":"|_";return r;} ``` 1-indexed. -14 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##lY9NT4MwHMbvfIp/eiDUjgZmNMZSvJl48LSjGlMZW1qhkFLIyOCzY4kTE2Myvf2el8PzKNGJUG3fJ1nWlbGgnKatlQXdtTqzstL0/gTM87JCNA08CqmPHkBjhZUZfOXJg7b5PjerX5yNNVLv0xQy4DAdwrQP02MnDBiOENtVJpDaguTRSjFCZBLHzBCOhmeN8JwqHjGVxBHDzpacH3zFeT/MRGKfkG@19lXSk0tfpby/Q8MFukXDK2Imt63RYNg4uR8AdftWuO2nC10lt1C6W8Hn0KcXgeeHAJu@sXlJq9bS2iW20EFGRV0XfbDGC2B2rhzjBc6Xb/AC/yhf/aF8/WPz6I3TBw) ``` x->y->{ // Method with two integer parameters and String return-type var r=""; // Result-String, starting empty for(int i=0,j;i<10 // Loop over the rows: ; // After every iteration: r+="|\n") // Append a "|" and newline to the result-String for(j=0;++j<11;) // Inner loop over the columns: r+=i==x&j==y|i==x+1&++j==y|i==x+2&j<y+3&j>=y? // If this coordinate should contain a '*' "|*" // Append "|*" to the result-String : // Else: "|_"); // Append "|_" to the result-String return r;} // Return the result-String ``` [Answer] # [Perl 5](https://www.perl.org/), 67 bytes ``` sub{map{($_-join('',@_)~~[1,12,20..22]?"|*":"|_")."|\n"x/9$/}0..99} ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jm@7@4NKk6N7GgWkMlXjcrPzNPQ11dxyFes64u2lDH0EjHyEBPz8go1l6pRkvJSqkmXklTT6kmJk@pQt9SRb8WKGlpWfvfmqugKDOvREFNJU3DQMdAU0dBCagEWdRcxxyLqAlWUVMdI5jofwA "Perl 5 โ€“ Try It Online") Input Parameters: y, x [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 35 bytes ``` ศท2b1 แธŒ+โ€œยฃร†รŸรฆรงโ€˜แนฌ+ยขsโตj3;0$โ‚ฌFแนญ0แป‹โ€œ_*ยถ|โ€ ``` [Try it online!](https://tio.run/nexus/jelly#AUYAuf//yLcyYjEK4biMK@KAnMKjw4bDn8Omw6figJjhuawrwqJz4oG1ajM7MCTigqxG4bmtMOG7i@KAnF8qwrZ84oCd////Niwz) **How it works** ``` ศท2b1 - the literal [1,1,1,1,...,1,1,1] with 100 elements แธŒ+โ€œยฃร†รŸรฆรงโ€˜แนฌ+ยขsโตj3;0$โ‚ฌFแนญ0แป‹โ€œ_*ยถ|โ€ - input (x,y) แธŒ - convert (x,y) to 10*x+y + - add, to get the five "*" positions, โ€œยฃร†รŸรฆรงโ€˜ - the literal [2,13,21,22,23] แนฌ - return an array with those positions as truthy elements +ยข - Now we format: pad to length 100 with the above literal sโตj3 - add newlines (represented by 3) to each set of 10 ;0$โ‚ฌF - add pipes (represented by 0) to each แนญ0 - add a 0 to the beginning แป‹โ€œ_*ยถ|โ€ - index into the string โ€œ_*ยถ|โ€ ``` [Answer] # [Python 2](https://docs.python.org/2/), 151 bytes Will golf more. ``` def f(x,y):r,x=[list('|_'*10+'|')for i in[1]*10],x*2;r[y][x+3]=r[y+1][x+5]=r[y+2][x+1]=r[y+2][x+3]=r[y+2][x+5]='*';print'\n'.join(''.join(i)for i in r) ``` [Try it online!](https://tio.run/nexus/python2#Tc1NCsIwEAXgfU@R3eRnkCS1FCw9SQxuNBCRVGIXKfTuMdWiWc33Hg8mX2@OOJpwYaeIaTQP/5oprBfgSgpYgbkpEk98MMqWymLieohmsSaJ1o5FQm3uvtabVeW2ctkAh@EZfZjhHOBwn3ygsF//e0Uiy45KlKz5bBtHe@zrcPwHjd0e8hs "Python 2 โ€“ TIO Nexus") [Answer] # [Ruby](https://www.ruby-lang.org/), 87 bytes ``` ->x,y{[a=(b='|_')*10+?|]*y+%w(|_|*|_ |_|_|* |*|*|*).map{|r|b*x+r+b*(7-x)+?|}+[a]*(7-y)} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7I6OtFWI8lWvSZeXVPL0EDbviZWq1JbtVyjJr5GqyZeAUgBGQpANhBq6uUmFlTXFNUkaVVoF2knaWmY61ZoAvXUakcnxoJ4lZq1/wtKS4oV0qINdAxidexj8rigfHMdcxS@iY4Jmjwq30jHFMz/DwA "Ruby โ€“ Try It Online") [Answer] # [Perl 6](http://perl6.org/), 88 bytes ``` ->\x,\y{(^10 ยป*ยปi X+ ^10).map:{<|* |_>[$_!= (1-2i|2-i|0|1|2)+x+y*i+2i]~"| "x(.re==9)}} ``` * Complex numbers are used to represent the coordinates. * `^10 ยป*ยป i X+ ^10` generates the grid of all complex numbers with integer components from zero through nine. * Returns a list of strings, each one holding one line. [Answer] # JavaScript (ES6), 99 bytes ``` x=>y=>eval('for(i=0,o="";i<101;o+=((d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_")+(++i%10?"":`|\n`))o') ``` Takes input via currying: `f(5)(2)` for x=5, y=2. Coordinates are zero-indexed. ## Test Snippet ``` f= x=>y=>eval('for(i=0,o="";i<101;o+=((d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_")+(++i%10?"":`|\n`))o') xi.oninput=yi.oninput=_=>O.innerHTML=f(xi.value)(yi.value) O.innerHTML=f(xi.value=5)(yi.value=2) ``` ``` <style>*{font-family:Consolas;}input{width:2.5em;}</style> x: <input id="xi" type="number" min="0" max="7">, y: <input id="yi" type="number" min="0" max="7"> <pre id="O"> ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 40 bytes ``` '*'@((โณ2)โˆ˜ร—ยจโŽ•โˆ˜+ยจโธโŠค1 5 3)โŠข'|',โจ10 20โด'|_' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97b@6lrqDhsaj3s1Gmo86ZhyefmjFo76pQJY2kNG741HXEkMFUwVjzUddi9Rr1HUe9a4wNFAwMnjUu0W9Jl4dZMT/NC5zBXMA "APL (Dyalog Extended) โ€“ Try It Online") A full program, accepting x and y as input. Calculate coordinates, and uses `@` to modify them. [Answer] # [Python 3](https://docs.python.org/3/), 97 bytes ``` def f(x,y): b=(["|_"]*10+["|\n"])*10 for c in[1,13,22,23,24]:b[c+11*y+x]="|*" return"".join(b) ``` [Try it online!](https://tio.run/##VcdBCsMgEEDRvaeQWTlmKGpSAoGcJJWCaaTpQoNYiJC722wK7ebz31byM4a21sfiuRc7FRwYd6OY4LiDlVo1590CWDyfcR8Tn/kaJk26JWPInO3s4Ka50VqWZrcjHBIYT0t@pwBwecU1CId1S2vIwgtFCpF91VP/p@5Hhq6I9QM "Python 3 โ€“ Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 96 bytes ``` r=[0..9] x#y=['|':(r>>=(\i->[last$'_':['*'|elem(i-x,j-y)$zip[1,2,0,1,2][0,1,2,2,2]],'|']))|j<-r] ``` Takes in two integers (`x` and `y`) and returns a list of `String`s, i.e. a 2D list of type `[[Char]]`. --- **Test suite:** ``` import System.Environment main :: IO () main = do args <- getArgs let (x, y) = (read $ args !! 0, read $ args !! 1) mapM_ putStrLn (x#y) ``` [Answer] ## Mathematica, ~~115~~ 113 bytes ``` x๏’ก(a="|_"~Table~10~Table~10;(a[[##]]="|*")&@@(#+x)&/@({{0,1,2,2,2},{1,2,0,1,2}}๏‡);""<>Riffle[#<>"|"&/@a,"\n"]) ``` where This takes input in `{row, col}` format, and is 1-indexed, but can be turned into 0-indexed without adding bytes. Some notes: 1. `\n` is a newline character, takes 1 byte. 2. `๏’ก` is `\[Function]`, takes 3 bytes. 3. `๏‡` is `\[Transpose]`, takes 3 bytes. Note that "array of string" is allowed, so I can just remove `Riffle`, gives ## Mathematica, ~~98~~ 97 bytes ``` x๏’ก(a="|_"~Table~10~Table~10;(a[[##]]="|*")&@@(#+x)&/@({{0,1,2,2,2},{1,2,0,1,2}}๏‡);#<>"|"&/@a) ``` [Answer] # [Python 2](https://docs.python.org/2/), 133 bytes ``` x,y=input() a=[[z for z in'_'*10]for o in'|'*10] b=a[y+2] a[y][x+1]=a[y+1][x+2]=b[x]=b[x+1]=b[x+2]="*" for b in a:print o+o.join(b)+o ``` [Try it online!](https://tio.run/##JYzNCsMgEITvPsWSS34MpUqhUPBJlqXoodQeXAkGNPTdbbSXmfm@w8SS3hx0rXktxoe4p2kW1iAe8OINDvBhfI6LulJDbvjtKJyxWKQmcRZhloq6UG1rMg5zj@bdXw3LINqLO1/APuLmQwKWfPmwD5ObJdd6X28/ "Python 2 โ€“ Try It Online") [Answer] # [Zsh](https://zsh.sourceforge.io/), 85 bytes [try it online!](https://tio.run/##qyrO@P8/Lb9IIVNBw0jB0FjByFDByEjByFjTPTpTW8VQxSjWVosLqqDaUE/P0MCgVrOgKDOvJE0hpkalGqgs1ko3vlZNTUMjU9XQQFOzpsbGxiam5v///2b/zQA) ``` for i (2 13 21 22 23)G[i+$1$2]=* for i ({1..100})printf \|${G[i]:-_}&&((i%10))||<<<\| ``` *Saved 12 bytes by moving the glider char `*` assignments to a function. Saved another 4 bytes by removing the function and adding a ternary to the `printf` stuff (at the expense of readability!). Saved another 7 by inlining some data instead of constructing an array. Saved another 10 by simplifying some expressions. Removed `{}` for another -1. Saved 11 by using [parameter expansion](https://zsh.sourceforge.io/Doc/Release/Expansion.html#Parameter-Expansion) `${name:-word}` instead of convoluted ascii logic.* ~~[130 bytes](https://tio.run/##qyrO@P8/Lb9IIUNBo9pQT8/QwKBW0z06I9Y2nivFVsVQxUjBPdpIOyXWVgvIMDSGsYwM4Sy4rBFElgtkXCaScdUFRZl5JWkKMTUq7tGZsdYaGpmqhgY2hpqaamo2NjYxNda1////N/lvCgA)~~ ~~[118 bytes](https://tio.run/##qyrO@P8/Lb9IIUNBo9pQT8/QwKBW0z06I9Y2nitXA8hSMdROibXV4kqxVTFUMbLOVQBhQ2MQwxBEgIWMuUBGZCIZUV1QlJlXkqYQU6PiHp0Za62hkalqaGBjqKmppmZjYxNTY137//9/k/@mAA)~~ ~~[114 bytes](https://tio.run/##LckxDsIwDADAnVdYqqlskKrYASFICurUR6RZK7IAKkykeXtYuPW@73utQ08KYkEFVEEtu/m5QALCgceAIe1RUGPsd5t/ZOk6MaZwfi3p8ZlhWjFTw0iEzRhSvJrbQS/nI3NxRGkrxgtz23rvp9WVWqutpx8)~~ ~~[107 bytes](https://tio.run/##LcoxDsIwDADAnVdYqqlskKrYASFogLGPSLNWZCmoMJHm7Wbh5vu@H2bTc4EMpCAeVEAV1PMQMeY9CmpK193mf4p0nThXubyWPH8mGFcs1DASYTPEnG7uftDL@chce6K8FReEuW1DCOPaVzPzdvoB)~~ ~~[97 bytes](https://tio.run/##LcoxDoMwDADAnVdYIpVsIaHYgaEQxMgjgBU1C1S0U5O83WXg5vt9XqrbcUIAFGAHwiAC4miaQ2XYyDpwcYfIdc3WZorvM@zfDZZkIpZkEK@9jo10z5Yo94jhwZYoJe/9krKqNur@)~~ ~~[96 bytes](https://tio.run/##qyrO@P8/Lb9IIVNBw0jB0FjByFDByEjByFjTPTpTW8VQxSjW1pALqqDaUE/P0MCgVrOgKDOvJE0hpkalWkNZU0VDA6g41t7EyMrSVFOzVk1NQyNT1dBAU7OmxsbGJqbm////Zv/NAA)~~ [Answer] # JavaScript, 98 bytes Based on [this answer](https://codegolf.stackexchange.com/a/124047/116593) ``` x=>y=>eval('for(i=0,o="";i<101;o+=(d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_",o+=++i%10?"":`|\n`)o') ``` We can save 1 byte if use `o+=a,o+=b` instead of `o+=(a)+(b)` Try it: ``` f= x=>y=>eval('for(i=0,o="";i<101;o+=(d=i-x-y*10)==1|d==12|d>19&d<23?"|*":"|_",o+=++i%10?"":`|\n`)o') xi.oninput=yi.oninput=_=>O.innerHTML=f(xi.value)(yi.value) O.innerHTML=f(xi.value=5)(yi.value=2) ``` ``` <style>*{font-family:Consolas;}input{width:2.5em;}</style> x: <input id="xi" type="number" min="0" max="7">, y: <input id="yi" type="number" min="0" max="7"> <pre id="O"> ``` # JavaScript, 101 bytes This answer may be more efficient with another pattern ``` x=>y=>eval("for(i=0,s='';i<101;s+=[1,12,20,21,22].includes(i-x-y*10)?'|*':'|_',s+=++i%10?'':`|\n`)s") ``` Try it: ``` f= x=>y=>eval("for(i=0,s='';i<101;s+=[1,12,20,21,22].includes(i-x-y*10)?'|*':'|_',s+=++i%10?'':`|\n`)s") xi.oninput=yi.oninput=_=>O.innerHTML=f(xi.value)(yi.value) O.innerHTML=f(xi.value=5)(yi.value=2) ``` ``` <style>*{font-family:Consolas;}input{width:2.5em;}</style> x: <input id="xi" type="number" min="0" max="7">, y: <input id="yi" type="number" min="0" max="7"> <pre id="O"> ``` [Answer] # [SOGL](https://github.com/dzaima/SOGL), 23 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` LIฮ–|_ฮŸLโˆ™.ยซ."ยพ'โ”ผฮžฮงโŒ ยฒโ€˜5nลพ ``` note: this expects input to be 1-indexed Explanation: ``` LI push 11 ฮ–|_ push "|" and "_" ฮŸ make an altrenates string [with 11 separators, which are "|" and parts "_"] Lโˆ™ get an array of 10 of those .ยซ take input and multiply by 2 (x pos) . take input (y pos) "ยพ'โ”ผฮžฮงโŒ ยฒโ€˜ push "_|*|__|_|**|*|*" - the glider in the map 5n split into an array with items of length 5 ลพ replace in the 1st [grid] array at positions [inp1*2, inp2] to 2nd array [glider] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ๏ผต๏ผฏยฒยนฯ‡|_๏ผชร—๏ผฎยฒ๏ผฎโ€œ "}๏ผฉyE%%m๏ผฌ๏ผข๏ผญฯ†/โ€ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98/KSc/L13DyFBHwdBAR0GpJl5J05rLqzS3ICRfQ0vDM6@gtMSvNDcptUhDU0fBCIhRhIBqA4oy80o0gBprtGriY/KANJAFpLVAEGjY///mXOb/dcv@6xbnAAA "Charcoal โ€“ Try It Online") Link to verbose mode for description. [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes ``` def f(x,y): b=(["|_"]*10+["|\n"])*10 for c in[1,13,22,23,24]:b[c+11*y+x]="|*" return"".join(b) ``` [Try it online!](https://tio.run/##VcdBCsMgEEDRvaeQWTlxKGpTAoGcJJVC0kjThQYxECF3t24K7ebz35bTK3hTynNx3ImDMvaMT4MY4XyAbbSS9e4eLNZn3IXIZ776UZO@kjFkalvbT@MstW6yPOwAZwOMxyXt0QNc3mH1YsKyxdUn4YQihci@6qj7U/sjQzfE8gE "Python 2 โ€“ Try It Online") [Answer] # [QBasic](https://en.wikipedia.org/wiki/QBasic), ~~113~~ 107 bytes Uses 0-indexing. ``` INPUT x,y s=11*y+x FOR i=1TO 110 ?"|"+CHR$(95+53*((i=s+2)+(i=s+14)-(i>s+22)*(i<s+26))+85*(i/11=i\11)); NEXT ``` We model the grid as 110 `|`s each followed by some character, for which we calculate the ASCII code: * Every 11th character is a newline (character code 95 - 85 = 10) * If we calculate the start index of the glider as `s = 11 * y + x`, then indices `s + 2`, `s + 14`, `s + 23`, `s + 24`, and `s + 25` are asterisks (character code 95 - 53 = 42) * The rest are underscores (character code 95) --- Original version using `LOCATE` (1-indexed): ``` INPUT x,y CLS FOR i=0TO 9 FOR j=0TO 9 ?"|_"; NEXT ?"| NEXT LOCATE y,2*x+2 ?"* LOCATE,2*x+4 ?"* LOCATE,2*x ?"*|*|* ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 24 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` |_๏ผกร—|๏ผ‹๏ผก๏ผŠ *ยถ *ยถ***โˆ™๏ผŠโ”˜ยซโ•ถโ•‹ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JTdDXyV1RkYyMSVENyU3QyV1RkYwQiV1RkYyMSV1RkYwQSUyMColQjYlMjAlMjAqJUI2KioqJXUyMjE5JXVGRjBBJXUyNTE4JUFCJXUyNTc2JXUyNTRC,i=NiUwQTM_,v=8) Takes 1-indexed position in form ``` x y ``` as input. Only beaten by [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)['s SOGL answer](https://codegolf.stackexchange.com/a/124048/78186) at time of writing. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 (or 24?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` โ€ž|_ั‚ะธโ€ž|*โ€ขA|,โ€ขโ‚‚ะฒI+วTรดJโ‚ฌฤ†ยป ``` 0-based indexing. [Try it online](https://tio.run/##yy9OTMpM/f//UcO8mviLTRd2gBhajxoWOdboAMlHTU0XNnl6aR@fG3J4i9ejpjVH2g7t/v8/2lDHMBYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fx/1DCvJv5i04UdIIbWo4ZFjjU6QPJRU9OFTZVe2sfnhhze4vWoac2RtkO7/@sc2mb/PzraQMcgVifaUMcQSJrrmINJEyBpqmMUGwsA). Could be 1 byte less (the `J`) if we could take the input-coordinates joined together as single integer: [Try it online](https://tio.run/##yy9OTMpM/f//UcO8mviLTRd2gBhajxoWOdboAMlHTU0XNnlqH58bcniL16OmNUfaDu3@/9/QEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fx/1DCvJv5i04UdIIbWo4ZFjjU6QPJRU9OFTZXax@eGHN7i9ahpzZG2Q7v/6xzaZv8/2sBAx9BQx9xcx9xEx9QoFgA). **Explanation:** ``` โ€ž|_ # Push string "|_" ั‚ะธ # Repeat it 100 times as list of strings โ€ž|* # Push string "|*" โ€ขA|,โ€ข # Push compressed integer 681976 โ‚‚ะฒ # Convert it to base-26 as list: [1,12,20,21,22] IJ # Push the input-pair, and join it together to an integer + # Add it to each value in the list [1,12,20,21,22] โ€ž|* ว # Insert the "|*" string at those (0-based) indices to the list of "|_" Tรด # Split the list into 10 parts of 10 strings each J # Join each inner list together to a string โ‚ฌ # Map over each line: ฤ† # Enclose; append its own head (the "|") ยป # Join the list of strings by newlines # (After which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `โ€ขA|,โ€ข` is `681976` and `โ€ขA|,โ€ขโ‚‚ะฒ` is `[1,12,20,21,22]`. ]
[Question] [ Using our familiar mathematical symbols: +, x, parenthesis, and any rational number, it's easy to create expressions that evaluates to some desired number. For example: `1+(2x3)=7`, `(1+2)+(3x6.5)=22.5` and so on. Boring enough. In this challenge, we'll use a new operator: `ยฑ`. The use of `ยฑ` in an expression means you need to evaluate the expression by replacing the `ยฑ`'s by `+` or `-` in all possible ways, and return the set of all possible values. For example: * `1ยฑ2ยฑ3 = {-4,0,2,6}` because `1ยฑ2ยฑ3` can be any of `1+2+3`, `1+2-3`, `1-2+3` and `1-2-3` and their values are `6,0,2,-4` respectively. * `(ยฑ2)x(2ยฑ3) = {-10,-2,2,10}` for similar reasons. Now, as it turns out, given any set of distinct real numbers, it's possible to create an expression with `+`,`x`,`(`,`)`,`ยฑ`, and real numbers that evaluates to the given set. ### Task Your task is to write a program or function in a language of your choice, that takes a sequence (list/array/any convenient format) of *integers* and outputs an expression (as a string) consisting of `+`,`x`,`(`,`)`,`ยฑ`, and *rational numbers* that evaluates to the set of the given numbers. * Note that the exact character `ยฑ` doesn't matter; you can use any other character of your choice as long as it's distinguishable from the other characters you're using. But you must mention which character you are using in your submission. * The input is allowed to consist of decimal approximations (up to reasonable accuracy) of the rational numbers used. * Input and output can be taken in any of the standard ways. * Standard loopholes are forbidden. * You can assume the given integers will be distinct, and provided in increasing order. * Output may contain spaces and newlines. ### Winning Criterion This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ### Examples ``` Input | Possible output -------------+----------------------------- [1,2,3] | 2ยฑ0.5ยฑ0.5 [-7,-3,1,21] | (1ยฑ2)x(3ยฑ4) ``` Idea taken from a question in the [Tournament of Towns, Fall 2015](http://www.math.toronto.edu/oz/turgor/archives/TT2015F_SAproblems.pdf). [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` f=lambda h,*t:t and"(.5?.5)*(%s+%%s)+"%f(*t)%-h+`h`or`h` ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCho1ViVaKQmJeipKFnaq9nqqmloVqsraparKmtpJqmoVWiqaqboZ2QkZBfBCT@FxRl5pUopGnoGuuY6hgZaP4HAA "Python 2 โ€“ TIO Nexus") The `?` stands for `ยฑ`. Example usage: ``` f(-3,5,20) -> (.5?.5)*((.5?.5)*(20+-5)+5+3)+-3 ``` The idea is that we can take an expression `E` and adjoin a new value `h` to its set of values by doing `(.5ยฑ.5)*(E+-h)+h`. [Answer] # [Haskell](https://www.haskell.org/), 52 bytes ``` f(h:t)=shows h"+(.5?.5)*("++f[x-h|x<-t]++")" f e="0" ``` [Try it online!](https://tio.run/nexus/haskell#@5@mkWFVomlbnJFfXqyQoaStoWdqr2eqqaWhpK2dFl2hm1FTYaNbEqutraSpxJWmkGqrZKD0PzcxM0/BVqGgKDOvREFFIU0h2lDHWMc89j8A "Haskell โ€“ TIO Nexus") Uses `?` for `ยฑ`. Example: ``` f [1,3,7] -> 1+(.5?.5)*(2+(.5?.5)*(4+(.5?.5)*(0))) ``` The function `shows` does `shows a b=(show a)++b`, a trick I learned from Lynn. ``` shows 12 "abc" -> "12abc" ``` [Answer] # [Haskell](https://www.haskell.org/), 58 bytes Using `#` for `ยฑ`, as it's one less byte. `f` takes a list of integers and returns a string. ``` f[x]=show x f(x:r)=show x++"+(.5#.5)x("++f((-x+)<$>r)++")" ``` Result is of the form `n+(.5#.5)x(rest)`, where `n` is the first element of the list and `rest` is the representation of all the others with `n` subtracted from each. [Try it online!](https://tio.run/nexus/haskell#y03MzLPNzCtJLUpMLlFJ0ytKTUz5nxZdEWtbnJFfrlDBlaZRYVWkCeVpaytpa@iZKuuZalZoKGlrp2lo6FZoa9qo2BVpAuU0lf7/jzbQMdQxjgUA "Haskell โ€“ TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` โ€œ(ยค)โ€j.โพ+ร—j;โ€( I;@แธขjยข;โ€)แบ‹โธLยคยค ``` Prints **v+(0.5ยค0.5)ร—(i1+(0.5ยค0.5)ร—((i2+(0.5ยค0.5)ร—(...(in)...)))** where **v** is the first number in the input array and **in** is the **nth** incremental difference between elements of the input array. **[Try it online!](https://tio.run/nexus/jelly#@/@oYY7GoSWajxrmZuk9atynfXh6ljWQo8Hlae3wcMeirEOLQFzNh7u6HzXu8Dm05NCS////RxvqGOnoGuuY6Oia6pjFAgA "Jelly โ€“ TIO Nexus")** ### How? ``` โ€œ(ยค)โ€j.โพ+ร—j;โ€( - Link 1, adjoining list: no input โ€œ(ยค)โ€ - literal ['(','ยค',')'] . - literal 0.5 j - join ['(',0.5,'ยค',0.5,')'] โพ+ร— - literal ['+','ร—'] j - join ['+',['(',0.5,'ยค',0.5,')'],'ร—'] โ€( - literal '(' ; - concatenate ['+',['(',0.5,'ยค',0.5,')'],'ร—','('] I;@แธขjยข;โ€)แบ‹โธLยคยค - Main link: list a e.g. [-1,5,2] I - incremental differences(a) [6,-3] แธข - head(a) [-1] ;@ - concatenate (rev @rgs) [-1,6,-3] ยข - last link (1) as a nilad ['+',['(',0.5,'ยค',0.5,')'],'ร—','('] j - join [-1,['+',['(',0.5,'ยค',0.5,')'],'ร—','('],6,['+',['(',0.5,'ยค',0.5,')'],'ร—','('],-3] ยค - nilad followed by link(s) as a nilad ยค - nilad followed by link(s) as a nilad โธ - link's left argument, a L - length 3 โ€) - literal ')' แบ‹ - repeat [')',')',')'] ; - concatenate [-1,['+',['(',0.5,'ยค',0.5,')'],'ร—','('],6,['+',['(',0.5,'ยค',0.5,')'],'ร—','('],-3,')',')',')'] - implicit print -1+(0.5ยค0.5)ร—(6+(0.5ยค0.5)ร—(-3)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` 0ยธยซยฅX;D"+(รฟยฑรฟ)*("รฝยนg<')ร—J ``` [Try it online!](https://tio.run/nexus/05ab1e#ATEAzv//MMK4wqvCpVg7RCIrKMO/wrHDvykqKCLDvcK5ZzwnKcOXSv//Wy03LC0zLDEsMjFd "05AB1E โ€“ TIO Nexus") **Explanation** ``` 0ยธยซ # prepend a 0 to input list ยฅ # calculate delta's X;D # push 0.5 twice "+(รฟยฑรฟ)*(" # push this string and interpolate 0.5 where "รฟ" is รฝ # merge the list of delta's with this string as a separator ยนg<')ร—J # add the closing parenthesis ``` Building the expression from the right unfortunately ends up at that the same byte count with `0ยธยซยฅยคsยจRvX;Dy"รฟ+(รฟยฑรฟ)*(รฟ)`. The 8 bytes used for the setup is the big waste here. [Answer] # Haskell, 54 bytes ``` f[]="0" f(x:s)=show x++"+(.5?.5)*("++f(map(-x+)s)++")" ``` the +- sign is `'?'`. example: ``` f[1,2,3,4] = "1+(.5#.5)*(1+(.5#.5)*(1+(.5#.5)*(1+(.5#.5)*(0))))" ``` [Answer] ## JavaScript (ES6), ~~56~~ 51 bytes ``` f=([v,...a],x=v)=>x?x+`+([[emailย protected]](/cdn-cgi/l/email-protection))*(${f(a,a[0]-v)})`:0 ``` Based on @JonathanAllan's formula. `@` stands for `ยฑ`. ]
[Question] [ ## Introduction A hypercube/tesseract is the 4 dimensional equivalent of a normal cube. It's made by taking a cube net, extending it to the 3rd dimension, then โ€“ using the 4th dimension โ€“ folding it into a hypercube. It's basically a cube, where each side is a cube. To create a hypercube, you need 16 4d vectors (a vector with an `x`, a `y`, a `z` and a `w` component). These vectors are the following: ``` A(0, 0, 0, 0); B(1, 0, 0, 0); C(1, 0, 1, 0); D(0, 0, 1, 0); E(0, 1, 0, 0); F(1, 1, 0, 0); G(1, 1, 1, 0); H(0, 1, 1, 0); I(0, 0, 0, 1); J(1, 0, 0, 1); K(1, 0, 1, 1); L(0, 0, 1, 1); M(0, 1, 0, 1); N(1, 1, 0, 1); O(1, 1, 1, 1); P(0, 1, 1, 1); ``` The hypercube has 24 faces. The following list contains all of them (every group marks a quad): ``` ABFE, CDHG, BCGF, DAEH, DCBA, FEHG IJNM, KLPO, JKON, LIMP, LKJI, PMNO ABJI, DCKL, BCKJ, DAIL, FEMN, GHPO, FGON, EHPM, EAIM, BFNJ, CGOK, HDLP ``` With all this information, you technically have a hypercube in code. To rotate this, you need 6 different matrices for each rotational plane, one for the YZ, XZ, XY, XW, YW and ZW planes. After you have every matrix, you need to multiply the cube's vertices with them. The following images show the structure of each matrix: For the rotation on the YZ plane: ![](https://i.stack.imgur.com/0t20y.png) For the rotation on the XZ plane: ![](https://i.stack.imgur.com/c79Fa.png) For the rotation on the XY plane: ![](https://i.stack.imgur.com/i9t1M.png) For the rotation on the XW plane: ![](https://i.stack.imgur.com/D6GJR.png) For the rotation on the YW plane: ![](https://i.stack.imgur.com/njB47.png) For the rotation on the ZW plane: ![](https://i.stack.imgur.com/cVyfP.png) The rotations get applied in this order. After all this, you have a rotated hypercube. Now you need to draw it. You should use an orthogonal projection combined with a perspective projection to send `(x, y, z, w)` to `(2x/(2+z), 2y/(2+z))`. ## Input Your input is 6 integers between 0 (inclusively) and 360 (exclusively). These represent the rotations in degrees on the different rotational planes of the hypercube. ## Output Your output should be a single image containing the hypercube. The display can be a rasterized image, a vector image or an ASCII art. The output image should be at least 100 \* 100 pixels, and the cube needs to take up at least 50% of the screen. Any default image output format is allowed. ## Test cases ``` 0 0 0 0 0 0 ``` ![](https://i.stack.imgur.com/3VdbD.png) ``` 0 0 0 0 0 30 ``` ![](https://i.stack.imgur.com/UlwJQ.png) ``` 30 0 0 0 0 30 ``` ![](https://i.stack.imgur.com/SbkYT.png) ``` 0 0 0 30 30 30 ``` ![](https://i.stack.imgur.com/kwo1G.png) ``` 45 45 45 0 0 0 ``` ![](https://i.stack.imgur.com/alRsv.png) ``` 45 45 45 45 45 45 ``` ![](https://i.stack.imgur.com/EmB8F.png) Open the images in a new tab, to see them in full size. ## Rules * Default rules apply * Standard loopholes are forbidden * Shortest code in bytes wins [Answer] ## Postscript ~~1075~~ ~~732~~ ~~683~~ ~~640~~ ~~631~~ ~~601~~ ~~590~~ ~~545~~ ~~542~~ ~~526~~ ~~514~~ ~~478~~ 470 Uses [mat.ps](https://github.com/luser-dr00g/xpost/blob/master/data/mat.ps) and [G](https://github.com/luser-dr00g/G). *Edit:-343* Applied binary-encoding generation of vectors and Eulerian circuit ~~stolen~~ borrowed from other answers. And applied binary-token-strings from the G library. *Edit:-49* Redefined `sin` `cos` and `neg` to shorter names. *Edit:-43* Defined short names for sequences `0 0` `0 1` `1 0`. *Edit:-9* `al` (ie. `aload`) is shorter than `(")@`. Factored 3 calls to `idi` (ie. `idiv`) at the cost of a do-nothing `1 idiv`. *Edit:-30* Applied *implicit definition block* from G. *Edit:-10* A few more triply-used sequences. *Edit:-45* Remove variables `i` `j` `k` `l` `m` `n` for the angles and always define the current angle as `t` and functions of angles use the value of the (global) `t` variable. Defer execution of the code-description of the rotation matrix until its `t` value is ready. *Edit:-3* Remove `<16>$` ie. `closepath`. And a space. *Edit:-16* Factor-out array brackets from unit vectors in the rotation matrices (`J` `K` `L` and `M`). Re-apply dropped `mo` for `mod` and `su` for `sub`. *Edit:-12* In-line the *project-and-draw* function and remove (now empty) enclosing dictionary. *Edit:-36* Encoded the circuit (ie. the *faces*) in a string. *Edit:-8* Remove definition of vertices array `V`. Instead, leave on stack and `dup` working copies as needed (once, at first, and again at the end of the loop). Also, translated a few operators from binary-token-strings back to abbreviated names where the BTS gave no savings, so `(I)$` is now `fora` (ie. `forall`). `if du` could be `(T8)$`, but `if du` is clearly a better choice (it's *golf*, not *obfuscation* per se). Also, perform the `scale` *before* `translate`, so translated coordinates can be `3` and `4` instead of `300` and `400`. ``` (mat.ps)run 3(G)run $ t sin A neg t cos 0 0 0 1 1 0 2 mu Z 2(!V)@ idi 2 mo .5 su (>8)$ [F D] [D E] [E D] [D F] 3 4 100(&>88)$(,)# div(<N)#[E 15{[I 1 H I 2 H I 4 H ex 8 H]}fo]E 5{ARGUMENTS 1(XK/)$/t ex d{{J[0 C B 0][0 A C 0]K}{[C 0 A 0]L[B 0 C 0]K}{[C B D][A C D]M K}{[C D A]L M[B D C]}{J[0 C 0 B]M[0 A 0 C]}{J L[D C B][D A C]}}(>K)$[(>?)$]transpose matmul}fo du(019;:89=?;37?>:26><804<=576451320){48 su get al po{W Z Y X}{(>3)$}fora X G Y G{li}(D)#{mov}if du}fora(HB)# ``` The `3` `4` and `100` in the first line of the second block are parameters representing center-x, center-y and scale, respectively, of the drawing on the page (center coordinates are scaled by `scale`). (300,400) is roughly the center of US letter-sized paper (612,792) in PS units. If you can roughly follow postscript, the important bizarre things are the *implicit procedure block* and the encoded operator strings. As shown by comments in the workfile, below, each line of the first block is implicitly named by A, B, C, etc. So, eg. `F E D` would produce `1 0 0 1 0 0`. For the encoded operator strings, anything that is an argument to `$` `#` or `@` is a sequence of operator calls, using the bytes to select operators from the system name table, PLRM 3ed Appendix F. These features and more are available for PostScript with the G library (now includes the mat.ps functions too). Workfile: ``` (mat.ps)run 3(G)run $ t sin %/A A neg %/B t cos %/C 0 0 %/D 0 1 %/E 1 0 %/F 2 mu Z 2(!V)@ %/G %ad div %add div %108 1 54 idi 2 mo .5 su %idiv mod sub %/H %106 169 51 (>8)$ %/I %exch dup [F D] %/J [D E] %/K [E D] %/L [D F] %/M 3 4 100(&>88)$ %currentlinewidth exch dup dup %38 (,)# %scale %139-95=44 div(<N)# %div setlinewidth %54 155-95=60 %translate %173-95=78 %/V [E 15{[ I 1 H I 2 H I 4 H ex 8 H]}fo] E 5{ARGUMENTS 1(XK/)$ %index get cvr %88 75 47 /t ex d %exch def %62 51 {{J[0 C B 0][0 A C 0]K} {[C 0 A 0]L[B 0 C 0]K} {[C B D][A C D]M K} {[C D A]L M[B D C]} {J[0 C 0 B]M[0 A 0 C]} {J L[D C B][D A C]}} (>K)$ %exch get %62 75 [ (>?)$ %exch exec %62 63 ] transpose matmul }fo %for du %dup %d %def %{transpose matmul}fora d %[E 9 11 10 8 9 13 15 11 3 7 15 14 10 2 6 14 12 8 0 4 12 13 5 7 6 4 5 1 3 2 0] %<0001090b0a08090d0f0b03070f0e0a02060e0c0800040c0d050706040501030200> % abcdef %0123456789:;<=>? (019;:89=?;37?>:26><804<=576451320) {48 su get % 169 75 %V (>K)$ %sub %exch get al po %aload pop %2 117 {W Z Y X}{(>3)$ %exch def }fora %forall %2 117 62 51 73 X G Y G {li}(D)# %stopped {mov} if du%(T8)$ %if %84 du %dup 56 } %<49a7a1>$ %forall stroke showpage %73 167-95=72 161-95=66 fora(HB)# ``` Ungolfed and lightly commented: ``` 300 400 translate %roughly center of letter paper currentlinewidth 100 dup dup scale div setlinewidth %scale x100, reduce line-width/100 (mat.ps)run %load matrix library ARGUMENTS aload pop{f e d c b a}{exch cvr def}forall %define args as % a,b,etc and convert to real numbers /m{2 mod .5 sub}def /P{aload pop{w z y x}{exch def}forall %P: [x y z w] project-and-draw - x 2 mul z 2 add div y 2 mul z 2 add div {lineto}stopped{moveto}if %catch(&handle!) nocurrentpoint error in lineto }bind def /V[0 1 15{ % generate vectors with a for-loop [ exch dup m 1 index 2 idiv m 2 index 4 idiv m 4 3 roll 8 idiv m ] }for] [[[1 0 0 0][0 a cos a sin neg 0][0 a sin a cos 0][0 0 0 1]] [[b cos 0 b sin 0][0 1 0 0][b sin neg 0 b cos 0][0 0 0 1]] [[c cos c sin neg 0 0][c sin c cos 0 0][0 0 1 0][0 0 0 1]] [[d cos 0 0 d sin][0 1 0 0][0 0 1 0][d sin neg 0 0 d cos]] [[1 0 0 0][0 e cos 0 e sin neg][0 0 1 0][0 e sin 0 e cos]] [[1 0 0 0][0 1 0 0][0 0 f cos f sin neg][0 0 f sin f cos]]] {transpose matmul} forall def % apply array of rotations and define %Eulerian circuit (borrowed and adjusted for 0-based indexing) [0 1 9 11 10 8 9 13 15 11 3 7 15 14 10 2 6 14 12 8 0 4 12 13 5 7 6 4 5 1 3 2 0] % the main program! % on the stack is the Eulerian circuit array { V exch get %lookup index in (sextuply-transformed) vertex array P %call project-and-draw } forall closepath stroke %draw it, don't just think about it showpage % gs's cmd-line-args option automatically sets -dBATCH, % so without a showpage, gs will immediately exit before you % can look at the picture :( ``` Some of my outputs are mirror images of the question's examples. For `gs -- hc.ps 0 0 0 0 0 0`, I get: [![enter image description here](https://i.stack.imgur.com/cNS0q.png)](https://i.stack.imgur.com/cNS0q.png) `gs -- hc.ps 0 0 0 0 0 30` [![enter image description here](https://i.stack.imgur.com/E3hHJ.png)](https://i.stack.imgur.com/E3hHJ.png) `gs -- hc.ps 30 0 0 0 0 30` [![enter image description here](https://i.stack.imgur.com/wZquU.png)](https://i.stack.imgur.com/wZquU.png) `gs -- hc.ps 0 0 0 30 30 30` [![enter image description here](https://i.stack.imgur.com/xKJXa.png)](https://i.stack.imgur.com/xKJXa.png) `gs -- hc.ps 45 45 45 0 0 0` [![enter image description here](https://i.stack.imgur.com/7V5Kd.png)](https://i.stack.imgur.com/7V5Kd.png) `gs -- hc.ps 45 45 45 45 45 45` [![enter image description here](https://i.stack.imgur.com/TvsMB.png)](https://i.stack.imgur.com/TvsMB.png) Bonus animation I just made with this program. This image corresponds to the rotation sequence 0 30 60 0 *i* *i*, where i ranges from 0 to 360 by 2. [![enter image description here](https://i.stack.imgur.com/YZ4BL.gif)](https://i.stack.imgur.com/YZ4BL.gif) [Answer] # Octave, ~~474~~ ~~433~~ 429 bytes ``` function H(a,b,c,d,e,f) C=@cosd;S=@sind;R=[1,0,0,0;0,C(e),0,-S(e);0,-S(e)*S(f),C(f),-C(e)*S(f);0,S(e)*C(f),S(f),C(e)*C(f)]*[C(c)*C(d),-S(c)*C(d),0,S(d);S(c),C(c),0,0;0,0,1,0;-C(c)*S(d),S(c)*S(d),0,C(d)]*[C(b),S(a)*S(b),C(a)*S(b),0;0,C(a),-S(a),0;-S(b),S(a)*C(b),C(a)*C(b),0;0,0,0,1]*(dec2bin(0:15)'-48.5);Z=R(3,:)+2;R=2*R./Z;Q=[1,2,10,12,11,9,10,14,16,12,4,8,16,15,11,3,7,15,13,9,1,5,13,14,6,8,7,5,6,2,4,3,1];plot(R(1,Q),R(2,Q)); ``` **Rotated:** ``` function H(a,b,c,d,e,f) C=@cosd;S=@sind; R=[1,0,0,0;0,C(e),0,-S(e);0,-S(e)*S(f),C(f),-C(e)*S(f);0,S(e)*C(f),S(f),C(e)*C(f)]* [C(c)*C(d),-S(c)*C(d),0,S(d);S(c),C(c),0,0;0,0,1,0;-C(c)*S(d),S(c)*S(d),0,C(d)]* [C(b),S(a)*S(b),C(a)*S(b),0;0,C(a),-S(a),0;-S(b),S(a)*C(b),C(a)*C(b),0;0,0,0,1]* (dec2bin(0:15)'-48.5); Z=R(3,:)+2; R=2*R./Z; Q=[1,2,10,12,11,9,10,14,16,12,4,8,16,15,11,3,7,15,13,9,1,5,13,14,6,8,7,5,6,2,4,3,1]; plot(R(1,Q),R(2,Q)); ``` The rotation matrices still consume a lot of bytes, but the Eulerian cycle worked out quite well, reducing the number of vertices visited from ~~96~~ 120 down to 33. Vertices are generated by taking the 4-bit binary representation of `[0:15]` and considering the msb to be the x-coordinate and the lsb the w-coordinate. Edit: Pre-multiplying all of the rotation matrices was a nightmare, which is why I didn't use it initially, but pre-multiplying them in pairs saved 41 bytes. ~~Now to look for the optimum combination. :)~~ Multiplying the matrices by threes was worse than no pre-multiplication at all, so I'll be happy with the pair-wise approach. --- **Output:** ``` H(0,0,0,0,0,0) ``` [![H(0,0,0,0,0,0)](https://i.stack.imgur.com/qIQM0.png)](https://i.stack.imgur.com/qIQM0.png) ``` H(0,0,0,0,0,30) ``` [![H(0,0,0,0,0,30)](https://i.stack.imgur.com/2lI1b.png)](https://i.stack.imgur.com/2lI1b.png) ``` H(30,0,0,0,0,30) ``` [![H(30,0,0,0,0,30)](https://i.stack.imgur.com/Dk3ja.png)](https://i.stack.imgur.com/Dk3ja.png) ``` H(0,0,0,30,30,30) ``` [![H(0,0,0,30,30,30)](https://i.stack.imgur.com/eKzPp.png)](https://i.stack.imgur.com/eKzPp.png) ``` H(45,45,45,0,0,0) ``` [![H(45,45,45,0,0,0)](https://i.stack.imgur.com/7f26j.png)](https://i.stack.imgur.com/7f26j.png) ``` H(45,45,45,45,45,45) ``` [![H(45,45,45,45,45,45)](https://i.stack.imgur.com/pmnuh.png)](https://i.stack.imgur.com/pmnuh.png) [Answer] # C# + Unity, ~~1060~~ ~~845~~ 835 bytes C# โ‰ˆ Java Assumes that this function is in a script placed on `MainCamera`. Edit: Thanks to @TuukkaX for the suggestions to save 19 bytes Saved ~200 bytes using the Eulerian cycle. Golfed: ``` void d(float[]r){transform.position=Vector3.back*2;GetComponent<Camera>().backgroundColor=Color.black;Vector4[]p=new Vector4[16];Matrix4x4[]m=new Matrix4x4[6];int i=0;for(;i<16;i++)p[i]=new Vector4(i%2,i/2%2,i/4%2,i/8%2)-new Vector4(.5f,.5f,.5f,.5f);int[,]X={{6,8,1,12,7,11},{5,0,0,0,5,10},{10,10,5,15,15,15}};for(i=0;i<6;i++){m[i]=Matrix4x4.identity;r[i]=Mathf.Deg2Rad*r[i];float c=Mathf.Cos(r[i]),s=Mathf.Sin(r[i]);m[i][X[1,i]]=c;m[i][X[2,i]]=c;m[i][X[0,i]]=s;m[i][X[0,i]%4*4+X[0,i]/4]=-s;}for(i=0;i<16;i++)foreach(Matrix4x4 x in m)p[i]=x*p[i];int[]F={0,1,9,11,10,8,9,13,15,11,3,7,15,14,10,2,6,14,12,8,0,4,12,13,5,7,6,4,5,1,3,2,0};LineRenderer l=new GameObject().AddComponent<LineRenderer>();l.SetVertexCount(33);l.material=new Material(Shader.Find("Sprites/Default"));l.SetWidth(.03f,.03f);for(i=0;i<33;i++)l.SetPosition(i,p[F[i]]); ``` Newlines + indentation + Full shell: ``` using UnityEngine; using System.Collections; public class h : MonoBehaviour { void d(float[]r) { transform.position=Vector3.back*2.5f; GetComponent<Camera>().backgroundColor=Color.black; Vector4[]p=new Vector4[16]; Matrix4x4[]m=new Matrix4x4[6]; int i=0; for(;i<16;i++)p[i]=new Vector4(i%2,i/2%2,i/4%2,i/8%2)-new Vector4(.5f,.5f,.5f,.5f); int[,]X={{6,8,1,12,7,11},{5,0,0,0,5,10},{10,10,5,15,15,15}}; for (i=0;i<6;i++){ m[i]=Matrix4x4.identity; r[i]=Mathf.Deg2Rad*r[i]; float c=Mathf.Cos(r[i]); float s=Mathf.Sin(r[i]); m[i][X[1,i]]=c; m[i][X[2,i]]=c; m[i][X[0,i]]=s; m[i][X[0,i]%4*4+X[0,i]/4]=-s; } for (i=0;i<16;i++)foreach(Matrix4x4 x in m)p[i]=x*p[i]; int[]F={0,1,9,11,10,8,9,13,15,11,3,7,15,14,10,2,6,14,12,8,0,4,12,13,5,7,6,4,5,1,3,2,0}; LineRenderer l=new GameObject().AddComponent<LineRenderer>(); l.SetVertexCount(33); l.material=new Material(Shader.Find("Sprites/Default")); l.SetWidth(.03f,.03f); for (i=0;i<33;i++) l.SetPosition(i,p[F[i]]); l.gameObject.tag = "Player"; } public float[] input; void Start() { d(input); } } ``` ~~I couldn't figure out a simple formula for constructing the rotation matrices nor the "faces" which to draw, so that cost a lot of bytes to hard-code.~~ I borrowed the Eulerian cycle from @beaker. Also, Unity built-ins are extremely verbose. You can verify all test cases [online](https://jediguy13.github.io/hypercube). [Answer] # Javascript ES6, 584 bytes ``` f=(...R)=>(P=s=>[...s].map(i=>parseInt(i,16)),C=document.createElement`canvas`,X=C.getContext`2d`,X.translate((C.width=300)/2,(C.height=300)/2),X.lineWidth=0.01,X.scale(100,100),X.beginPath(),P("0267fd9804c8ab915dcefb37546ea2310").map((e,i)=>{[x,y,z]=P("084c2a6e195d3b7f").map(i=>[...(1e3+i.toString(2)).slice(-4)].map(i=>i-0.5)).map(e=>(R.map((R,i,_,M=Math,C=M.cos(r=R*M.PI/180),S=M.sin(r))=>((a,b,s=1)=>[e[a],e[b]]=[C*e[a]-s*S*e[b],s*S*e[a]+C*e[b]])(...[[1,2],[0,2,-1],[0,1],[0,3,-1],[1,3],[2,3]][i])),e))[e];[x,y]=[2*x/(2+z),2*y/(2+z)];i?X.lineTo(x,y):X.moveTo(x,y)}),X.stroke(),C) ``` "Ungolfed": ``` f=(...R)=>( // function that accepts rotations in the following form: f(a,b,c,d,e,f) P=s=>[...s].map(i=>parseInt(i,16)), // function to convert strings to hex-arrays V=P("084c2a6e195d3b7f") // vertices encoded as hex values ( [0,1,1,0] -> 6 ) .map(i=>[...(1e3+i.toString(2)).slice(-4)].map(i=>i-0.5)) // convert hex values to vertices, center the hypercube .map(e=>(R.map((R,i,_,M=Math,C=M.cos(r=R*M.PI/180),S=M.sin(r))=> // convert angles to degrees, precalculate sin and cos values ((a,b,s=1)=>[e[a],e[b]]=[C*e[a]-s*S*e[b],s*S*e[a]+C*e[b]]) // apply matrix transforms to all vertices (...[[1,2],[0,2,-1],[0,1],[0,3,-1],[1,3],[2,3]][i])),e)), // list of encoded matrix transforms C=document.createElement`canvas`,X=C.getContext`2d`, // create image to draw on X.translate((C.width=300)/2,(C.height=300)/2), // setup image dimensions, center transform X.lineWidth=0.01,X.scale(100,100),X.beginPath(), // setup line, scale the transform and begin drawing P("0267fd9804c8ab915dcefb37546ea2310").map((e,i)=>{ // hypercube edge path indices encoded as hex values [x,y,z]=V[e];[x,y]=[2*x/(2+z),2*y/(2+z)]; // project vertex i?X.lineTo(x,y):X.moveTo(x,y)}),X.stroke(), // draw vertex C) // return image ``` See it in action (modified to continuously rotate): ``` with(document)with(Math)with(document.getElementById`canvas`)with(getContext`2d`){render=()=>{requestAnimationFrame(render);clearRect(0,0,width,height);save();K=performance.now();R=[K*0.01,K*0.02,K*0.03,K*0.04,K*0.05,K*0.06];X=s=>[...s].map(i=>parseInt(i,16));V=X("084c2a6e195d3b7f").map(i=>[...(1e3+i.toString(2)).slice(-4)].map(i=>i-0.5)).map(e=>(R.map((R,i,_,C=cos(r=R*PI/180),S=sin(r))=>((a,b,s=1)=>[e[a],e[b]]=[C*e[a]-s*S*e[b],s*S*e[a]+C*e[b]])(...[[1,2],[0,2,-1],[0,1],[0,3,-1],[1,3],[2,3]][i])),e));translate((width=300)/2,(height=300)/2);lineWidth=0.01;scale(100,100);beginPath();X("0267fd9804c8ab915dcefb37546ea2310").map((e,i)=>{[x,y,z]=V[e];[x,y]=[2*x/(2+z),2*y/(2+z)];i?lineTo(x,y):moveTo(x,y)});stroke();restore();};render();} ``` ``` <html><body><canvas id="canvas"></canvas></body></html> ``` The function returns a HTML5 canvas object, you need to add it to the page by doing `document.body.appendChild(f(0,0,0,0,0,0))` for example. Currently, the rotations are applied out of order, I'm working on the reordering, but as is, it rotates a hypercube correctly. [Answer] # Mathematica, ~~453~~ 415 bytes\* Shortened by using the Eulerian tour and cleaning it all up into a single statement without defining functions in variables. This makes the code slower for some reason. I'm guessing Mathematica reevaluates the functions multiple times now that they are not stored in a variable. ``` Graphics[Line[Table[{2#/(2+#3),2#2/(2+#3)}&@@Map[Dot@@Table[Table[If[n==m==#2||n==m==#,Cos[#3],If[n==#2&&m==#,If[#2==1&&(#==3||#==4),1,-1]Sin[#3],If[n==#&&m==#2,If[#2==1&&(#==3||#==4),-1,1]Sin[#3],If[n==m,1,0]]]],{n,4},{m,4}]&[k[[1]],k[[2]],a[[k[[3]]]]ยฐ],{k,{{4,3,6},{4,2,5},{4,1,4},{2,1,3},{3,1,2},{3,2,1}}}].#&,Tuples[{0,1},4]-.5,{1}][[i]],{i,{1,2,10,12,11,9,10,14,16,12,4,8,16,15,11,3,7,15,13,9,1,5,13,14,6,8,7,5,6,2,4,3,1}}]]] ``` \* I am counting `ยฐ` and `==` as single bytes each since they are represented as a single character in Mathematica. I think this is fair since lots of languages use weird character encodings. Ungolfed with comments. The input is hard coded at the top as `a={30,0,0,0,0,30};`. I didn't count that toward my score. ``` a = {45, 45, 45, 45, 45, 45}; (* #2,#-th rotation matrix as a funciton of #3 *) (* Using the \ #-notation saved 6 bytes over the more common function definition \ notation*) r = Table[If[n == m == #2 || n == m == #, Cos[#3], If[n == #2 && m == #, If[#2 == 1 && (# == 3 || # == 4), 1, -1] Sin[#3], If[n == # && m == #2, If[#2 == 1 && (# == 3 || # == 4), -1, 1] Sin[#3], If[n == m, 1, 0]]]], {n, 4}, {m, 4}] &; (* Total rotation matrix. Need six of them. Function of the six \ angles to rotate.*) u = Dot @@ Table[r[k[[1]], k[[2]], \[Degree]* a[[k[[3]]]]], {k, {{4, 3, 6}, {4, 2, 5}, {4, 1, 4}, {2, 1, 3}, {3, 1, 2}, {3, 2, 1}}}].# &; (* List of all vertices of the hypercube *) t = Tuples[{0, 1}, 4]; t -= .5; v = Map[u, t, {1}]; (*projection*) p = {2 #/(2 + #3), 2 #2/(2 + #3)} &; (*Eulerian tour*) l = Table[ p @@ v[[i]], {i, {1, 2, 10, 12, 11, 9, 10, 14, 16, 12, 4, 8, 16, 15, 11, 3, 7, 15, 13, 9, 1, 5, 13, 14, 6, 8, 7, 5, 6, 2, 4, 3, 1}}]; Graphics[Line[l]] ``` `0 0 0 0 0 30` [![](https://i.stack.imgur.com/UXPTg.png)](https://i.stack.imgur.com/UXPTg.png) `0 0 0 30 30 30` [![enter image description here](https://i.stack.imgur.com/QQBqb.png)](https://i.stack.imgur.com/QQBqb.png) `405 10 -14 -8 -9 205` [![enter image description here](https://i.stack.imgur.com/qjd0w.png)](https://i.stack.imgur.com/qjd0w.png) ]
[Question] [ You are a web developer, and your boss has decided to update the company's website. He has decided that less color is better, but he wants the site to look the same. You justly decide that he has no idea what he's talking about, but you're going to try anyway, because you're bored. Since the company has thousands of webpages, and each one has its own CSS, you decide to write a script to do the necessary changes. [Parsing HTML](https://stackoverflow.com/a/1732454/2415524) not required. All of the pages currently use a string like `rgb(255,0,0)` for a color. **Given the three decimal values** representing the RGB values of a CSS color attribute (in that order), return or print the shortest string representation of that color, such that it's usable for CSS like so: `color:<your-result-here>;`. Here is a complete table of valid [**CSS Color Keywords**](http://www.w3.org/TR/SVG/types.html#ColorKeywords). They are case-insensitive. ### Examples: Note that colors can be defined with 12 or 24 bits. The pattern `#ABC` is a shorter version of `#AABBCC`. [Chuck Norris is a color](https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color). Your program will only take in 3 integers, not a string (with the exception of the *"bonus"* mentioned later). ``` 0, 0, 0 -> #000 (same as #000000, but shorter) 255, 0, 0 -> red 0, 128, 128 -> TEAL 139, 0, 0 -> DarkRed (OR #8B0000) 72, 61, 139 -> #483D8B 255, 255, 254 -> #fffffe 255, 85, 255 -> #f5f (same as #ff55ff, but shorter) ``` ### Scoring / Rules * Shortest code wins! * [Standard loopholes are disallowed](http://meta.codegolf.stackexchange.com/q/1061/34718), with the exception of built-ins. * **-50% bytes** (the bonus is rounded down) if you accept *any\** valid color selector and output the shortest. So `DarkSlateBlue` would output `#483D8B`, `#F00` outputs `red`, etc. + \*This only includes RGB, hex codes, and names. + Note that some colors have alternate names due to [X11](https://en.wikipedia.org/wiki/X11_color_names#Clashes_between_web_and_X11_colors) (like `Fuchsia` and `Magenta`, or `Cyan` and `Aqua`). The alternate names are included in the linked list of CSS Color Keywords according to the W3 standard. * [CSS3 is Turing Complete](https://stackoverflow.com/questions/2497146/is-css-turing-complete). That'd be worth a bounty. Edit: * **PLEASE RUN YOUR CODE ON THE TEST CASES!** [Answer] # C#6 527 bytes / 2 bonus = 264 **EDIT:** Woot! I finally got the bonus answer with a lower score than the basic answer! I've written just a function. It requires a `using` statement (included.) C# has a nice list of known colours to work with, but it insists on including the Alpha channel. The known colours also includes all system colours, two of which have names less than 7 characters long, so these needed to be stripped out. Here's the bonus solution, supporting formats such as: * `12, 34, 56` * `#123` * `#123456` * `DarkSlateBlue` Completely golfed: ``` using System.Drawing;int H(string s,int i,int l)=>Convert.ToInt32(s.Substring(i*l+1,l),16)*(l<2?17:1);string D(string a){int i=17,j=a.Length/3,n;var d=a.Split(',');Color k,c=a[0]<36?Color.FromArgb(H(a,0,j),H(a,1,j),H(a,2,j)):Color.FromName(a);c=c.A>0?c:Color.FromArgb(int.Parse(d[0]),int.Parse(d[1]),int.Parse(d[2]));j=c.R%i+c.G%i+c.B%i<1?3:6;n=c.ToArgb();a="#"+(j<6?c.R/i<<8|c.G/i<<4|c.B/i:n&0xffffff).ToString("x"+j);for(i=26;i++<167;k=Color.FromKnownColor((KnownColor)i),a=n==k.ToArgb()&k.Name.Length<=j?k.Name:a);return a;} ``` Indentation and new lines for clarity: ``` using System.Drawing; int H(string s,int i,int l)=>Convert.ToInt32(s.Substring(i*l+1,l),16)*(l<2?17:1); string C(string a){ int i=17,j=a.Length/3,n; var d=a.Split(','); Color k,c=a[0]<36 ?Color.FromArgb(H(a,0,j),H(a,1,j),H(a,2,j)) :Color.FromName(a); c=c.A>0?c:Color.FromArgb(int.Parse(d[0]),int.Parse(d[1]),int.Parse(d[2])); j=c.R%i+c.G%i+c.B%i<1?3:6; n=c.ToArgb(); a="#"+(j<6?c.R/i<<8|c.G/i<<4|c.B/i:n&0xffffff).ToString("x"+j); for(i=26;i++<167; k=Color.FromKnownColor((KnownColor)i), a=n==k.ToArgb()&k.Name.Length<=j?k.Name:a ); return a; } ``` # C#, 265 bytes Here's the basic solution. ``` using System.Drawing;string C(int r,int g,int b){int i=17,c=r<<16|g<<8|b,j=r%i+g%i+b%i<1?3:6;var o="#"+(j<6?r/i<<8|g/i<<4|b/i:c).ToString("x"+j);for(i=26;i++<167;){var k=Color.FromKnownColor((KnownColor)i);o=c<<8==k.ToArgb()<<8&k.Name.Length<=j?k.Name:o;}return o;} ``` Indentation and new lines for clarity: ``` using System.Drawing; string C(int r,int g,int b){ int i=17, c=r<<16|g<<8|b, j=r%i+g%i+b%i<1?3:6; var o="#"+(j<6?r/i<<8|g/i<<4|b/i:c).ToString("x"+j); for(i=26;i++<167;){ var k=Color.FromKnownColor((KnownColor)i); o=c<<8==k.ToArgb()<<8&k.Name.Length<=j?k.Name:o; } return o; } ``` [Answer] # Mathematica ~~207 242~~ 500-250=250 bytes Update: This works with inputs consisting of rgb triples, color names, or hex numbers. (12 bit) color-depth output now works fine, thanks to an excellent article on [Color Bit Depth Reduction](http://computingvoyage.com/982/color-bit-depth-reducer/). The basic idea is that, if an RGB triple {r,g,b}, where r, g, and b are in the range of 0-255, (i.e. hex 00-ff) can be represented without loss as a number in the range of 0-15 (i.e. 0-f), then one may use the 3 digit hex number instead of the 6 digit number. Turns out that this will occur whenever 17 (i.e 255/15) divides r, g, and b. Only built-in functions are used. Mathematica has rules for replacing HTML colors names with RGB triples. For example, one rule is `"Teal"-> RGBColor[0, 128, 128]`. When such rules are inverted, rgb values (recalibrated to the range, {0, 255}) can be replaced with color names. ``` q=ColorData["HTML","ColorRules"]; j=q/.{(c_ -> RGBColor[r_,g_,b_]):> (Floor[255{r,g,b}]-> c)}; k=Reverse/@j; v@l_:=And@@IntegerQ/@(l/17); y@l_:=If[v@l,l/17,l]; h@l_:="#"<>(IntegerString[#,16,If[v@l,1,2]]&/@y@l) o@h_:=Module[{c=(StringLength[h1=StringDrop[h,1]]==6)},FromDigits[#,16]&/@StringPartition[h1,If[c,2,1]]*If[c,1,17]] u@l_:=ToString[l/.j] m@s_:=s/.q/.RGBColor[r_,g_,b_]:>Floor[255{r,g,b}] f@n_:=SortBy[{u@n,h@n},StringLength][[1]] z@d_:= (If[StringQ@d,If[StringTake[d,1]=="#",e=o@d,e=m@d],e=d];f@e) ``` --- **Examples** ``` z /@ {{0, 0, 0}, {255, 0, 0}, {0, 128, 128}, {139, 0, 0}, {255, 255, 255}, {72, 61, 139}, {255, 255, 254}, {255, 85, 255}} ``` > > {"#000", "Red", "Teal", "#8b0000", "#fff", "#483d8b", "#fffffe","#f5f"} > > > --- ``` z /@ {"Red", "DarkSlateBlue", "Teal", "Black"} ``` > > {"Red", "#483c8b", "Teal", "#000"} > > > --- ``` z /@ {"#000", "#f00", "#008080", "#8b0000", "#fff", "#483d8b", "#fffffe", "#f5f"} ``` > > {"#000", "Red", "Teal", "#8b0000", "#fff", "#483d8b", "#fffffe", \ > "#f5f"} > > > --- ## Commented, Ungolfed Code (\* rules for replacing a color name with a color swatch, e.g. `RGBColor{255,17,0}` ``` q=ColorData["HTML","ColorRules"]; ``` --- (\* rules for replacing a list of 3 integers with the respective color name, if one exists. And the same rules, reversed. \*) ``` rulesListsToColorNames=(q)/.{(c_ -> RGBColor[r_,g_,b_]):> (Floor[255{r,g,b}]-> c)}; rulesColorsToLists=Reverse/@rulesListsToColorNames; ``` --- (\*tests whether a 24 bit hex color can be represented as a 12 bit color with no loss. `reduce` can change the 24 bit expression to a 12 bit expression. \*) ``` depthReducible[l_List]:=And@@IntegerQ/@(l/17); reduce[l_List]:=If[depthReducible@l,l/17,l]; ``` --- (\*RGB list changed to a Hex number \*) ``` fromListToHex[l_List]:="#"<>(IntegerString[#,16,If[depthReducible@l,1,2]]&/@reduce[l]) ``` --- (\* Hex number changed to RGB list. \*) ``` fromHexToList[h_String]:=Module[{c=(StringLength[h1=StringDrop[h,1]]==6)}, FromDigits[#,16]&/@StringPartition[h1,If[c,2,1]]*If[c,1,17] ] ``` --- (\* More conversions \*) ``` fromListToColorName[l_List]:=ToString[l/.rulesListsToColorNames] fromColorNameToHex[s_String]:=fromListToHex[s/.rulesColorsToLists] fromColorNameToList[s_String]:=s/.q/.RGBColor[r_,g_,b_]:>Floor[255{r,g,b}] ``` --- (\* choses the shortest valid CSS expression of a color \*) ``` f@n_List:=SortBy[{fromListToColorName[n],fromListToHex[n]},StringLength][[1]] ``` --- (\* converts any input into an RGB list and calls `f` \*) ``` returnShortestColor[d_]:= (If[StringQ[d], If[StringTake[d,1]=="#", e=fromHexToList@d, e=fromColorNameToList@d], e=d]; f@e) ``` [Answer] # Perl, 212 - 50% = 106 bytes ``` use aliased Graphics::ColorNames,G;sub c{tie%c,G,CSS;$_=pop;$c={reverse%c}->{$_=sprintf'%02x'x(@0=/(\d+, ?)((?1))(\d+)/)||$c{s/#(.)(.)(.)$|#/\1\1\2\2\3\3/r},@0};s/(.)\1(.)\2(.)\3|/#\1\2\3/;y///c>length$c&&$c||$_} ``` With newlines added: ``` use aliased Graphics::ColorNames,G; sub c{ tie%c,G,CSS;$_=pop; $c={reverse%c}->{ $_=sprintf'%02x'x(@0=/(\d+, ?)((?1))(\d+)/)||$c{s/#(.)(.)(.)$|#/\1\1\2\2\3\3/r},@0 }; s/(.)\1(.)\2(.)\3|/#\1\2\3/; y///c>length$c&&$c||$_ } ``` --- **Test Cases** ``` use feature say; say c '#f00'; say c '#FF0000'; say c '#112233'; say c '#f0ffff'; say c 'azure'; say c 'DARKSLATEBLUE'; say c 'rgb(255, 127, 80)'; say c 'rgb(255, 255, 254)'; say c 'rgb(255,228,196)'; ``` **Output** ``` red red #123 azure azure #483d8b coral #fffffe bisque ``` --- # Perl, no bonus, 144 bytes ``` use aliased Graphics::ColorNames,G;sub c{tie%c,G,CSS;$c={reverse%c}->{$_=sprintf'%02x'x3,@_};s/(.)\1(.)\2(.)\3|/#\1\2\3/;y///c>length$c&&$c||$_} ``` With newlines added: ``` use aliased Graphics::ColorNames,G; sub c{ tie%c,G,CSS; $c={reverse%c}->{ $_=sprintf'%02x'x3,@_ }; s/(.)\1(.)\2(.)\3|/#\1\2\3/; y///c>length$c&&$c||$_ } ``` `Graphics::ColorNames` isn't a core module, but it's been around since 2001. You may need to install it via: ``` cpan install Graphics::ColorNames cpan install Graphics::ColorNames::CSS ``` The hex representation is preferred if the color name has the same length. --- **Test Cases** ``` use feature say; say c 0, 0, 0; say c 255, 0, 0; say c 0, 128, 128; say c 139, 0, 0; say c 72, 61, 139; say c 255, 255, 254; say c 255, 85, 255; ``` **Output** ``` #000 red teal #8b0000 #483d8b #fffffe #f5f ``` [Answer] # CoffeeScript, ~~411 404 388 384~~ 382/2 = 191 **UPD:** Pretty sure it is final result Hope, it's okay to use `window.document.*`. Check `rgb` function and `eval` call. ``` s=(c,rgb=(r,g,b)->(2**24+(r<<16)+(g<<8)+b).toString 16)->d=y=document.body;r=(q=(a)->y.style.color=a;d[b='#'+eval(getComputedStyle(y).color)[1...].replace /(.)\1(.)\2(.)\3/,'$1$2$3']=a;b) c;(d='NavyGreenTealIndigoMaroonPurpleOliveGraySiennaBrownSilverPeruTanOrchidPlumVioletKhakiAzureWheatBeigeSalmonLinenTomatoCoralOrangePinkGoldBisqueSnowIvoryRed'.match /.[a-z]+/g).map(q);d[r]||r ``` ### Test results ``` rgb( 0, 0, 0 ) -> #000 rgb( 255, 0, 0 ) -> Red rgb( 0, 128, 128 ) -> Teal rgb( 139, 0, 0 ) -> #8b0000 rgb( 72, 61, 139 ) -> #483d8b rgb( 255, 255, 254 ) -> #fffffe rgb( 255, 85, 255 ) -> #f5f darkslateblue -> #483d8b indigo -> Indigo #f00 -> Red ``` ### Commented code ``` s = ( c, rgb = ( r, g, b ) -> return ( 2 ** 24 + ( r << 16 ) + ( g << 8 ) + b ) .toString( 16 ) ) -> ``` This will save some bytes. ``` d = y = document.body ``` `q` function will place input color to `document.body.style.color` and get compiled color as `rgb(...)`. Also it will store result as `hexColor:inputColor` in `d`. Notice `eval` use. `rgb(100,100,100)` is a valid JavaScript function call with three number arguments. `rgb` function will convert arguments to single 24/12 HEX notation (like `#fff`, `#f0f0f0`). ``` r = ( q = ( a ) -> y.style.color = a b = '#' + eval( getComputedStyle( y ).color )[ 1... ].replace( /(.)\1(.)\2(.)\3/, '$1$2$3' ) d[ b ] = a return b )( c ) ``` Split string to array of color names, create lookup object. ``` ( d = 'NavyGreenTeal...'.match( /.[a-z]+/g )).map( q ) ``` And return HEX if no shorter variant in `d`. ``` return d[ r ] or r ``` [Answer] # Stylus, ~~238~~ 234/2 = 117 More CSS-like solution! Stylus already has great support for color manipulation, so desired function is pretty small and not golfed a lot. `f(c){for n in split(' ''navy green teal indigo maroon purple olive gray sienna brown silver peru tan orchid plum violet khaki azure wheat beige salmon linen tomato coral orange pink gold bisque snow ivory red'){lookup(n)==c?c=s(n):c}}` ### Test it [here](https://learnboost.github.io/stylus/try.html) ``` body color f(rgb(0, 0, 0)) color f(rgb(255, 0, 0)) color f(rgb(0, 128, 128)) color f(rgb(139, 0, 0)) color f(rgb(72, 61, 139)) color f(rgb(255, 255, 254)) color f(rgb(255, 85, 255)) color f(darkslateblue) color f(indigo) color f(#f00) color f(rgba(255,0,0,1)) color f(rgba(255,0,0,0.5)) ``` [Answer] # Matlab 617 A lot of preprocessing and hardcoding. The minimal set of colour names you have to consider are [these.](http://pastebin.com/VGzFRaaZ) Too bad Matlab does not have built in color names=/ ``` function s=f(r,g,b); t=255; c=[r,g,b]; a=[0 t t;240 t t;245 245 220;t 228 196;0 0 t;165 42 42;t 127 80;0 t t;t 215 0;75 0 130;t t 240;240 230 140;0 t 0;250 240 230;t 165 0;218 112 214;205 133 63;t 192 203;221 160 221;t 0 0;250 128 114;160 82 45;t 250 250;210 180 140;t 99 71;238 130 238;245 222 179;t t t;t t 0]; s=textscan('aqua azure beige bisque blue brown coral cyan gold indigo ivory khaki lime linen orange orchid peru pink plum red salmon sienna snow tan tomato violet wheat white yellow','%s'); i=find(ismember(a,c,'rows')); k=1; if i>0;s=s{1}{i};elseif ~any(mod(c,16));k=16;end;d=dec2hex(c/k,2-(k>1))';s=['#',d(:)'] ``` [Answer] # Python 3, ~~857~~ 795 bytes Having to manually specify all of the accepted colours required did increase the byte count on this one :/ ~~`c(a)` takes one argument, `a`, which comes in the form of `rgb(#,#,#)`. From that, the rgb and brackets are removed and the string is then split by commas into an array.~~ `c(x,y,z)` takes 3 ints, the r, g and b values of the rgb colour to process. We put those together in an array `a`. We then use Python's built-in `hex` function which converts a Base 10 number to a Base 16 number on our array and create a hex string (this is done in the `for` loop). The `if` statements convert colours like `000000` to `000`, and replace the known colours using a dictionary. Here it is (thanks to @undergroundmonorail for tip about `;` in Python): ``` def c(x,y,z): a=[x,y,z];b=""; for i in a: i=hex(i)[2:] if len(i)<2:i="0"+i; b+=i k={"00ffff":"AQUA","f0ffff":"AZURE","f5f5dc":"BEIGE","ffe4c4":"BISQUE","0000ff":"BLUE","a52a2a":"BROWN","ff7f50":"CORAL","ffd700":"GOLD","808080":"GRAY","008000":"GREEN","4b0082":"INDIGO","fffff0":"IVORY","f0e68c":"KHAKI","00ff00":"LIME","faf0e6":"LINEN","800000":"MAROON","000080":"NAVY","808000":"OLIVE","ffa500":"ORANGE","da70d6":"ORCHID","cd853f":"PERU","ffc0cb":"PINK","dda0dd":"PLUM","800080":"PURPLE","ff0000":"RED","fa8072":"SALMON","a0522d":"SIENNA","c0c0c0":"SILVER","fffafa":"SNOW","d2b48c":"TAN","008080":"TEAL","ff6347":"TOMATO","ee82ee":"VIOLET","f5deb3":"WHEAT","ffff00":"YELLOW"} if b[:3]==b[3:]:b=b[:3]; if b in k:b=k[b]; else:b="#"+b; return b ``` Old Version: ``` def c(a): a=a[4:-1].split(",") b="" for i in a: i=hex(int(i))[2:] if len(i)<2: i="0"+i b+=i k = {"00ffff":"AQUA","f0ffff":"AZURE","f5f5dc":"BEIGE","ffe4c4":"BISQUE","0000ff":"BLUE","a52a2a":"BROWN","ff7f50":"CORAL","ffd700":"GOLD","808080":"GRAY","008000":"GREEN","4b0082":"INDIGO","fffff0":"IVORY","f0e68c":"KHAKI","00ff00":"LIME","faf0e6":"LINEN","800000":"MAROON","000080":"NAVY","808000":"OLIVE","ffa500":"ORANGE","da70d6":"ORCHID","cd853f":"PERU","ffc0cb":"PINK","dda0dd":"PLUM","800080":"PURPLE","ff0000":"RED","fa8072":"SALMON","a0522d":"SIENNA","c0c0c0":"SILVER","fffafa":"SNOW","d2b48c":"TAN","008080":"TEAL","ff6347":"TOMATO","ee82ee":"VIOLET","f5deb3":"WHEAT","ffff00":"YELLOW"} if b[:3]==b[3:]: b=b[:3] if b in k: b=k[b] else: b="#"+b return "color:"+b+";" ``` Maybe I'll add the bonus to it, I don't know yet. It could definitly do with 50% bytes off! -Toastrackenigma [Answer] # JavaScript (ES6), 499 ~~611~~ *Edit* Added the test cases in the question Note: I kept just the color names that are shorter than the hex equivalent. ~~Note 2: this can surely be golfed more...~~ ``` f=(r,g,b,k='#'+(r%17|g%17|b%17?1<<24|r<<16|g<<8|b:4096|(r*256+g*16+b)/17).toString(16).slice(1))=> ("#d2b48cTAN#f00RED#ff7f50CORAL#f5deb3WHEAT#ff6347TOMATO#ffd700GOLD#008000GREEN#faf0e6LINEN#f5f5dcBEIGE#da70d6ORCHID#4b0082INDIGO#ffc0cbPINK#f0e68cKHAKI#008080TEAL#ee82eeVIOLET#dda0ddPLUM#fa8072SALMON#ffa500ORANGE#a0522dSIENNA#800000MAROON#800080PURPLE#ffe4c4BISQUE#f0ffffAZURE#fffff0IVORY#cd853fPERU#808000OLIVE#c0c0c0SILVER#fffafaSNOW#a52a2aBROWN#000080NAVY#808080GRAY" .match(k+'([A-Z]+)')||[,k])[1] // TEST ;[[0,0,0,'#000'],[255,0,0,'red'],[0,128,128,'TEAL'],[139,0,0,'#8B0000'],[72,61,139,'#483D8B'],[255,255,254,'#fffffe'],[255,85,255,'#f5f']] .forEach(([r,g,b,t])=>(x=f(r,g,b),o+=r+','+g+','+b+' -> '+x+' '+(x.toUpperCase()==t.toUpperCase()?'ok':'error('+t+')')+'\n'),o='') O.innerHTML=o function go() { var r,g,b [r,g,b] = I.value.match(/\d+/g) O.innerHTML=r+','+g+','+b+' -> '+f(r,g,b)+'\n'+O.innerHTML } ``` ``` R,G,B: <input id=I><button onclick="go()">--></button> <pre id=O></pre> ``` **Less golfed** ``` f=(r,g,b) => ( k='#'+( r%17|g%17|b%17 ? 1<<24|r<<16|g<<8|b : 4096|r/17<<8|g/17<<4|b/17 ).toString(16).slice(1), s = "#d2b48cTAN#f00RED#ff7f50CORAL#f5deb3WHEAT#ff6347TOMATO#ffd700GOLD#008000GREEN#faf0e6LINEN#f5f5dcBEIGE#da70d6ORCHID#4b0082INDIGO#ffc0cbPINK#f0e68cKHAKI#008080TEAL#ee82eeVIOLET#dda0ddPLUM#fa8072SALMON#ffa500ORANGE#a0522dSIENNA#800000MAROON#800080PURPLE#ffe4c4BISQUE#f0ffffAZURE#fffff0IVORY#cd853fPERU#808000OLIVE#c0c0c0SILVER#fffafaSNOW#a52a2aBROWN#000080NAVY#808080GRAY", m = s.match(k+'([A-Z]+)'), // names are upper, hex codes are lower (m || [,k])[1] // if no match use the code ) ``` [Answer] ## Python 3 + matplotlib, 193 bytes ``` import matplotlib.colors as M def f(c): H=h=M.rgb2hex([i/255for i in c]).upper() if all(v%17<1for v in c):h=h[::2] for n,x in M.CSS4_COLORS.items(): if H==x and len(n)<len(h):h=n return h ``` Input is taken as a tuple or array of integers. [**Try it here**](https://onecompiler.com/python/3ynxnphm2) ### Less golfed: ``` import matplotlib.colors as mcolors def f(c): # Save two copies of the uppercase hex value. # Inconvenient, but it takes decimals instead of integers, # and it returns lowercase, but the dictionary has uppercase. :'( H=h=mcolors.rgb2hex([i/255 for i in c]).upper() # Check if all 3 integers are divisible by 17, # because that means in hex the digits are the same, # similar to how that works for multiples of 11 in base 10, # or multiple of N+1 in base N. if all(v%17<1 for v in c): # Get every other character from the hex string h=h[::2] # Loop through the dictionary. Way too verbose for me to appreciate. for n,x in mcolors.CSS4_COLORS.items(): # If the name is shorter, use it. # H is needed, because "h" is the shortened. if H==x and len(n)<len(h):h=n return h ``` `CSS4_COLORS` contains a dictionary of the color names and hex values. Unfortunately, the dictionary is "backwards" from what I'd like. Also, this could likely be used to create a better score using the bonus, though I don't think it'd win. ]
[Question] [ Quite a few people here are probably avid XKCD readers. So, I figure I'd challenge you guys to do something that Megan can do easily: make a script that generates thousands of reassuring parables about what computers can never do. [![XKCD #1263](https://i.stack.imgur.com/NtDma.png "'At least humans are better at quietly amusing ourselves, oblivious to our pending obsolescence' thought the human, as a nearby Dell Inspiron contentedly displayed the same bouncing geometric shape screensaver it had been running for years.")](http://xkcd.com/1263/) Your script * Can be written in any language * Must be code-golfed * Must take an input (on `stdin` or your language equivalent) on the number of parables it will spit out (you can assume this will not exceed `MAX_INT` or equivalent). * Will output a number of **randomly** generated parables. The parables are as follows * Starts with `'Computers will never '` * Next, one of 16 unique English verbs which you can choose freely to optimize your program, but *must* include `code-golf` and `understand`. * Next, one of 16 unique English nouns which again, you can choose freely to optimize your program, but *must* include `a salad` and `an octopus`. * Next, one of 16 unique English clauses which you can choose freely to optimize your program, but *must* include `for fun` and `after lunch`. * Ends with a newline (`\n` or equivalent) character So, for example, if the input is `2`, a valid output would be ``` Computers will never code-golf a salad for lunch Computers will never hug a tree in vain ``` Program size is counted in bytes, not characters (so no unicode gibberish). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny "Standard loopholes") are not allowed. This is my first challenge, so if I should make some obvious changes, please comment. **Edit:** I am contemplating to substract the dictionary size from the byte count, to encourage dictionary 'compression'. I will see from future answers if this is remotely feasible ; if it is, you can count on a bonus. [Answer] Here's a slightly different approach: # Python, 368 308 297 bytes EDIT, I actually golfed it this time. Shaved off 60 characters. ``` from random import* from en import* C=choice v=["code-golf","understand","go","do"] n=["salad","octopus","fun","lunch"] for f,l in("verbs",v),("nouns",n):exec"l.append(str(C(wordnet.all_"+f+"()))[:-4]);"*12 exec'print"Computers will never",C(v),noun.article(C(n)),C(("for","after")),C(n);'*input() ``` Here is the golf-trick that I'm most proud of: ``` for f,l in("all_verbs",v),("all_nouns",n): ``` I didn't even know python could do that! Here's a simpler explanation: ``` for (a, b) in ((0, 1), (1, 2), (2, 3)): ``` assigns a and b to 0 and 1, and then to 1 and 2, and then to 2 and 3. --- This uses NodeBox's linguistics library to generate a list of verbs/nouns/clauses, and then randomly selects from them. This library is not that great for generating random words (hence the 368 bytes), but the nice thing about this approach is you get some pretty random reassuring parables with it. Here is what I mean. ``` Computers will never attempt a syria for synchronization. Computers will never understand a salad for change of mind. Computers will never brim an electric company for synchronization. Computers will never pivot a dusk for fun. Computers will never bedaze an electric company for genus osmerus. Computers will never brim a salad for vital principle. Computers will never attempt an erythroxylum after lunch. Computers will never understand an uuq for water birch. Computers will never brim an ictiobus for change of mind. Computers will never brim an ictiobus for 17. Computers will never lie in an octopus for change of mind. Computers will never happen upon a toothpowder for water birch. Computers will never typeset an electric company for change of mind. Computers will never brim a french oceania after lunch. Computers will never bring out an ictiobus for glossodia. Computers will never bedazzle an animal fancier for ash cake. Computers will never attempt a dusk for genus osmerus. Computers will never understand an animal fancier for genus osmerus. Computers will never accredit a prickly pear cactus for 17. Computers will never typeset an erythroxylum for water birch. ``` But hey, I don't think anybody else's program will generate the saying: "Computers will never bedazzle an animal fancier for ash cake." Here's an ungolfed version (574 bytes): ``` import random import en v = ["code-golf", "understand"]#list of verbs n = ["a salad", "an octopus"]#list of nouns c = ["for fun", "after lunch"]#list of clauses for i in range(14): v.append(str(random.choice(en.wordnet.all_verbs()))[:-4]) n.append(en.noun.article(str(random.choice(en.wordnet.all_nouns()))[:-4])) c.append("for "+str(random.choice(en.wordnet.all_verbs()))[:-4]) N=input("Enter the number of reassuring phrases you want: ") for i in range(N): print "Computers will never"+' '+random.choice(v)+' '+random.choice(n)+' '+random.choice(c )+'.' ``` And lastly but definitely not leastly, here are some of my favorite reassuring parables, that I predict will become really popular catch-phrases in the next 10-15 years. ``` Computers will never move around a methenamine for godwin austen. Computers will never conk an adzuki bean for bitterwood tree. Computers will never jaywalk a cross-dresser for fun. Computers will never hyperbolize an accessory after the fact for norfolk island pine. Computers will never dissolve a salad for earth wax. Computers will never acetylise an incontrovertibility for dictatorship. Computers will never reciprocate a strizostedion vitreum glaucum for commelinaceae. Computers will never goose an action replay for star chamber. Computers will never veto a bottom lurkers for jackboot. Computers will never reciprocate a visual cortex for oleaginousness. Computers will never baptise a special relativity after lunch. Computers will never understand a gipsywort for citrus tangelo. Computers will never get it a brand-name drug for electronic computer. Computers will never deforest a paperboy after lunch. Computers will never bundle up a nazi for repurchase. Computers will never elapse a bernhard riemann for counterproposal. ``` and my personal favorite: ``` Computers will never romanticise a cockatoo parrot for cross-fertilization. ``` [Answer] ## CJam, ~~238~~ 232 (or 209) bytes ``` ri{'C"!fmQ$h/q6fW*LC*hBd11(kA>.TfqJ0++#<>A]XThJkY b~os;vMg_D-}zYX%_,PozNxe5_8`}$H;2IUZ]&$c+m~HJ*|!n\A^:W-*O\"V-/8Kg ,_b(N#M/1Zh6*%\#t22'#|\"BJN=Za2_.R"32f-96b28b" -"'{,W%+f=)/(\[G/~["for ""after "]\m*\(a\"a "f{\+}+\]{mr0=}%S*N}* ``` This uses many verbs/nouns/clauses from already posted answers but some are new too. I have base converted the characters to shave off some extra bytes. The base converted string can be golfed 24 more bytes (to get a [209 byte solution](https://mothereff.in/byte-counter#ri%7B%27C%229%C3%B3%C3%9F%C3%82%2F%C3%83%C2%87C%20e%C2%98G%3Fdc%C3%85o%C3%B8%C2%A3gaC%23Y%C3%A4%C2%A9%C3%8F%C2%A1%C3%A1q%C2%B6hm%C2%90%29%C3%B0%C2%ADa%C2%81%C3%A2%25%C3%98No%3D%C2%85%C3%B3%C3%8Frb%C2%8C%C3%81z%C2%B4%C2%BE%C2%9D%3Bq%C2%B7u%C2%AC%C2%87%26%C3%B1*%C2%B1%C3%A4%C3%B4%C2%A9%406W%C2%B1U%C2%B9%C2%A5%C2%A2%29%C3%82%C2%B7%C2%AB%C3%85x%C2%B6%C3%B3V%C2%8A%C2%93%C2%AC%C2%9C%C2%ACdhj%C2%82a%C2%92%C2%BC%20%C2%AA%5C%22r%5B%C3%A7%C3%8B74%C3%84%C2%93%C2%85%C3%A3%C3%90%C2%B3%C3%AE%2C%C3%B33g%C3%88%24A%C3%AFL%2232f-222b28b%22%20-%22%27%7B%2CW%25%2Bf%3D%29%2F%28%5C%5BG%2F~%5B%22for%20%22%22after%20%22%5D%5Cm*%5C%28a%5C%22a%20%22f%7B%5C%2B%7D%2B%5C%5D%7Bmr0%3D%7D%25S*N%7D*); Note that you have to consider the character count instead of byte count as all characters have an ASCII code of less than 255 but the site still consider some has unicode) but I wanted the string to consist only printable ASCII characters. Just for reference, here is the 209 bytes version: ``` ri{'C"9รณรŸร‚/รƒC eG?dcร…oรธยฃgaC#Yรคยฉรยกรกqยถhm)รฐยญaรข%ร˜No=รณรrbรzยดยพ;qยทuยฌ&รฑ*ยฑรครดยฉ@6WยฑUยนยฅยข)ร‚ยทยซร…xยถรณVยฌยฌdhjaยผ ยช\"r[รงร‹74ร„รฃรยณรฎ,รณ3gรˆ$AรฏL"32f-222b28b" -"'{,W%+f=)/(\[G/~["for ""after "]\m*\(a\"a "f{\+}+\]{mr0=}%S*N}* ``` Takes the number of lines to print from STDIN like: ``` 12 ``` Output: ``` Computers will never code-golf an octopus for fun Computers will never code-golf a bag after za Computers will never eat a hem after tip Computers will never eat an octopus for tip Computers will never get a fax for you Computers will never dry a gym for za Computers will never get a guy for tip Computers will never do a pen for fun Computers will never see a bar after you Computers will never tax a pen for ex Computers will never get a hem for lunch Computers will never win a pen for ex ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # JavaScript ES6, 331 336 bytes ``` n=prompt(a='') r=s=>s+Math.random()*16>>0 p=q=>'OctopusSaladCutCueBatJamKidPenDogFanHemDotTaxSowDyeDigCode-golfUnderstandLunchFunMeYouUsItAdsPaZaMenTwoIceJamWarRumWax'.match(/[A-Z][^A-Z]+/g)[q].toLowerCase() while(n-->0)y=r(0),z=r(18),a+=`Computers will never ${p(r(2))} a${y?'':'n'} ${p(y)} ${z<18?'afte':'fo'}r ${p(z)} ` alert(a) ``` ``` n=prompt() a='' function r(s){return s+Math.random()*16>>0} function p(q){return' '+'OctopusSaladCutCueBatJamKidPenDogFanHemDotTaxSowDyeDigCode-golf\ UnderstandLunchFunMeYouUsItAds\ PaZaMenTwoIceJamWarRumWax'.match(/[A-Z][^A-Z]+/g)[q].toLowerCase()} while(n-->0) y=r(0),z=r(18), a+='Computers will never'+p(r(2))+(y?' a':' an')+p(y)+(z<18?' after':' for')+p(z)+'\n' alert(a) ``` I picked words that work as both verbs and nouns to shorten the list, but let me know if that is not allowed. Try it out above using Stack Snippets (The code there has been formatted to use ES5) or at <http://jsfiddle.net/5eq4knp3/2/>. Here is an example output: ``` Computers will never hem a cut for ads Computers will never dot a pen after lunch Computers will never code-golf a bat for free Computers will never sow a dog for me Computers will never cut an octopus for fun ``` [Answer] # Python - ~~390 385~~ 383 ``` from pylab import* S=str.split n=input() while n:n-=1;i,j,k=randint(0,16,3);print"Computers will never",S("buy cut dry eat fax get pay rob see sue tax tow wax win code-golf understand")[i],"a"+"n"*(j<1),S("octopus salad bag bar bee bow boy bra dad fax gym guy hat man mom pet")[j],"for "*(k>2)+S("after lunch,naked,ever,fun,me,you,us,tip,gas,cash,air,oil,beer,love,food,dope",",")[k] ``` Random example output: ``` Computers will never pay an octopus for oil Computers will never cut a bra for beer Computers will never eat a bee for us Computers will never rob a pet for you Computers will never tax a pet for tip Computers will never buy a salad for cash Computers will never sue a boy naked Computers will never see a bar for you Computers will never wax a bra for beer Computers will never sue an octopus for us ``` [Answer] # Perl - 366 ``` @w="Code-golfUnderstandBeDoTieSeeSawEatCutCapSitSetHateZapSipLoveSaladOctopusSeaBeeCatDogHatBatJobManLapCapRapMapDotAnt0fun1that1noon1work0good0sure0reason0nothing0you1you1lunch1all0me0nowToday1me"=~s/\d/("For ","After ")[$&]/reg=~/([A-Z][^A-Z]+)/g;print"Computers will never ".lc"$w[rand 16] a".$w[16+rand 16]=~s/^[AO]?/(n)[!$&]." $&"/re." $w[32+rand 16] "for 1..<> ``` Here is a test: ``` $ perl ./parables.pl <<<3 Computers will never do an ant after noon Computers will never do a lap after all Computers will never love an octopus for sure ``` [Answer] ## CJam, ~~353~~ ~~317~~ 301 bytes I'm using Falko's word list, for fairness, so that the only difference in golfing is due to the languages and not the content (I might change the word list if people start golfing the content as well). ``` "Computers will never ""buy cut dry eat fax get pay rob see sue tax tow wax win code-golf understand"N/[" an octopus"" a ""salad bag bar bee bow boy bra dad fax gym guy hat man mom pet"{N/\f{\+}~]}:F~S["after lunch""naked""ever""for ""fun me you us tip gas cash air oil beer love food dope"Fm*m*m*mr0= ``` [Answer] ## NetLogo, 396 I also used Falko's word list, with two exceptions (which don't change the length of program). ``` to f let a["after lunch""ever""alone"]type(word"Computers will never "one-of["buy""cut""dry""eat""fax""get""pay""rob""see""sue""tax""tow""wax""win""code-golf""understand"]" a"one-of["n ocotpus"" salad"" bag"" bar"" bee"" bow"" boy"" bun"" dad"" fax"" gym"" guy"" hat"" man"" mom"" pet"]" "one-of fput word"for "one-of["fun""me""you""us""tip""gas""cash""air""oil""beer""love""food""dope"]a"\n")end ``` Depending on how you define "program", you can remove the first five and last three characters, thus a score of 388. ]
[Question] [ In this challenge, you need to simulate a frog jumping back and forth on lily pads. The pond is infinitely big, has a line of an infinite number of lily pads, and the frog can jump across as many lily pads as he likes. This frog likes to jump back and forth: **after jumping forward, he always jumps backwards**, and vice versa. You are passed a list of integers, which represents his jumps. You need to output the result of his jumps. For example, say you are passed `[2,3,6,8,2]`: Our frog starts by jumping 2 lily pads forward: ``` _2 ``` Then 3 lily pads back: ``` 3__2 ``` Then 6 lily pads forward: ``` 3__2__6 ``` 8 back: ``` 8_3__2__6 ``` Then finally, 2 lily pads forward (notice how the 2 overwrites the 3): ``` 8_2__2__6 ``` To be more explicit: Your input is an an array of numbers `S`, you need to output `S[K]` at the position `S[K] - S[K-1] + S[K-2] - S[K-3]...`. * If multiple numbers are to be printed at a certain location, print only the one with the highest index. * You are to use `_` if a particular location is empty * If a number has multiple digits, it does not take up multiple locations. (In other words, a location can consist of multiple characters) * You can assume that your list is non-empty, and that all integers are greater than 0. # Test cases: ``` 5 ____5 2,2 2_2 4,3,2,1 3124 5,3,2,1 _3125 2,3,6,8,2 8_2__2__6 10,3,12,4,1,12,16 ___12__3__10____41__1216 100,4,7,2,2 _______________________________________________________________________________________________4___1002_2 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so answer it in as few characters as possible! [Answer] # [MATL](https://github.com/lmendo/MATL), ~~35~~ 34 bytes *Thanks to [@Emigna](https://codegolf.stackexchange.com/users/47066/emigna) for saving 1 byte!* ``` 32Oittn:oEq*Yst1hX<-Q(Vh' 0'95ZtXz ``` [Try it online!](https://tio.run/nexus/matl#@29s5J9ZUpJnle9aqBVZXGKYEWGjG6gRlqGuYKBuaRpVElH1/3@0kY6xjpmOhY5RLAA) Or [verify all test cases](https://tio.run/nexus/matl#S/hvbOSfWVKSZ5XvWqgVWVximBFhoxuoEZahrmCgbmkaVRJR9d8l5H@0aSxXtImOsY6RjiGQZQpnGQFZZjoWOkZAtqEBkGNopGOiYwiiDM3AYgZAvjlQtVEsAA). ### How it works *Golf your code, not your explanations!* The following uses input `[2,3,6,8,2]` as an example. To see intermediate results in the actual code, you may want to insert a `%` (comment symbol) to stop the program at that point and see the stack contents. For example, [this](https://tio.run/nexus/matl#@29s5J9ZUpJnle9aqBVZrFpimBFhoxuoEZahrmCgoG5pGlUSUfX/f7SRjrGOmY6FjlEsAA) shows the stack after statement `Ys` (cumulative sum). ``` 32 % Push 32 (ASCII for space) O % Push 0 i % Input array % STACK: 32, 0, [2,3,6,8,2] t % Duplicate % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2] tn: % Push [1 2 ... n] where n is length of input array % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,2,3,4,5] o % Modulo 2 % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,0,1,0,1] Eq % Multiply by 2, subtract 1 % STACK: 32, 0, [2,3,6,8,2], [2,3,6,8,2], [1,-1,1,-1,1] * % Multiply elementwise % STACK: 32, 0, [2,3,6,8,2], [2,-3,6,-8,2] Ys % Cumulative sum % STACK: 32, 0, [2,3,6,8,2], [2,-1,5,-3,1] % The top-most array is the positions where the entries of the second-top % array will be written. But postions cannot be less than 1; if that's % the case we need to correct so that the minimum is 1. If this happens, % it means that the frog has gone further left than where he started t % Duplicate 1hX< % Append 1 and compute minimum. So if the original minimum is less than 1 % this gives that minimum, and if it is more than 1 it gives 1 % STACK: 32, 0, [2,3,6,8,2], [2,-1,5,-3,1], -3 - % Subtract % STACK: 32, 0, [2,3,6,8,2], [5 2 8 0 2] Q % Add 1 % STACK: 32, 0, [2,3,6,8,2], [6 3 9 1 3] ( % Assign values (top array) to specified positions (second-top) into array % which contains a single 0 (third-top). Newer values overwrite earlier % values at the same position % STACK: 32, [8 0 2 0 0 2 0 0 6] V % Convert to string. This produces spaces between the numbers % STACK: 32, '8 0 2 0 0 2 0 0 6' h % Concatenate with initial 32 (space). This converts to char % STACK: ' 8 0 2 0 0 2 0 0 6' % Thanks to this initial space, all zeros that need to be replaced by '_' % are preceded by spaces. (In this example that initial space would not % be needed, but in other cases it will.) Other zeros, which are part of % a number like '10', must not be replaced ' 0' % Push this string: source for string replacement % STACK: ' 8 0 2 0 0 2 0 0 6', ' 0 ' 95 % Push 95 (ASCII for '_'): target for string replacement % STACK: ' 8 0 2 0 0 2 0 0 6', ' 0 ', 95 Zt % String replacement % STACK: ' 8_2__2__6' Xz % Remove spaces. Implicit display % STACK: '8_2__2__6' ``` [Answer] # [R](https://www.r-project.org/), ~~100~~ ~~97~~ 96 bytes ``` function(x){p=cumsum(x*c(1,-1))[seq(x^0)] p=p+max(1-p,0) v=rep('_',max(p));v[p]=x cat(v,sep='')} ``` [Try it online!](https://tio.run/##XU3LCoMwELz7Fbllt10hSa0t2HyJtUWCQg9q6ouA9NvTCEWkl53HzjC9r9ktZr6eWjO@uhYcLlabqRmmBtzBgKRYIuZD9Qb3EFhEVttjUzqQsSWB0az7ygJ/clpNi5jNuS20i0w5wkxDZTXn@PHdNK5Dux221OFmbA3yextCUQiBgTPijylSG0/oRIrkps9/WgWd0nXXkCJYUlFCcgWZ7j4iuJfQVwzR@y8 "R โ€“ Try It Online") Line 1 finds all positions where to jump. First, all jumps in `x` are multiplied by 1 or โˆ’1 and then transformed to final positions using cumulative summation. The vector `c(-1,1)` is recycled if necessary, however, when `x` is of length 1, `x` is recycled instead. Therefore only `seq(x^0)` (equivalent to `seq_along(x)`) sums are considered. (A warning is generated when the length of `x` is not a multiple of 2 but it does not affect the result) Line 2 increases the jumping positions so that all are at least 1. Lines 3 and 4 create the output and print it. *โˆ’1 byte from [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)* [Answer] # PHP, ~~100~~ ~~101~~ ~~99~~ 104 bytes ``` for($p=-1;$d=$argv[++$k];+$i<$p?:$i=$p,$x>$p?:$x=$p)$r[$p+=$k&1?$d:-$d]=$d;for(;$i<=$x;)echo$r[$i++]?:_; ``` takes input from command line arguments; run with `-nr`. **breakdown** ``` for($p=-1; // init position $d=$argv[++$k]; // loop $d through command line arguments +$i<$p?:$i=$p, // 3. $i=minimum index $x>$p?:$x=$p // 4. $x=maximum index ) $r[ $p+=$k&1?$d:-$d // 1. jump: up for odd indexes, down else ]=$d; // 2. set result at that position to $d for(;$i<=$x;) // loop $i to $x inclusive echo$r[$i++]?:_; // print result at that index, underscore if empty ``` [Answer] ## JavaScript (ES6), ~~99~~ 107 bytes *Edit: Because the OP clarified that the only limit should be the available memory, this was updated to allocate exactly the required space instead of relying on a hardcoded maximum range.* ``` f=(a,x='',p=M=0)=>a.map(n=>x[(p-=(i=-i)*n)<m?m=p:p>M?M=p:p]=n,i=m=1)&&x?x.join``:f(a,Array(M-m).fill`_`,-m) ``` ### How it works This function works in two passes: * During the first pass: + The 'frog pointer' `p` is initialized to `0`. + The `x` variable is set to an empty string, so that all attempts to modify it are simply ignored. + We compute `m` and `M` which are respectively the minimum and maximum values reached by `p`. + At the end of this pass: we do a recursive call to `f()`. * During the second pass: + `p` is initialized to `-m`. + `x` is set to an array of size `M-m`, filled with `_` characters. + We insert the numbers at the correct positions in `x`. + At the end of this pass: we return a joined version of `x`, which is the final result. ### Test cases ``` f=(a,x='',p=M=0)=>a.map(n=>x[(p-=(i=-i)*n)<m?m=p:p>M?M=p:p]=n,i=m=1)&&x?x.join``:f(a,Array(M-m).fill`_`,-m) console.log(f([5])); // ____5 console.log(f([4,3,2,1])); // 3124 console.log(f([5,3,2,1])); // _3125 console.log(f([2,3,6,8,2])); // 8_2__2__6 console.log(f([10,3,12,4,1,12,16])); // ___12__3__10____41__1216 console.log(f([100,4,7,2,2])); // _..._4___1002_2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 (and further allowing another -2) thanks to FrownyFrog (use the [post-challenge] functionality of the prefix application quick, `ฦค`) ``` แนšฦคแธ…-ยตCแน€ยป0+ยตแนฌโ‚ฌร—"ยณแนšo/oโ€_;โท ``` **[Try it online!](https://tio.run/##AUMAvP9qZWxsef//4bmaxqThuIUtwrVD4bmAwrswK8K14bms4oKsw5ciwrPhuZpvL2/igJ1fO@KBt////1syLDMsNiw4LDJd "Jelly โ€“ Try It Online")** Full program, for a test suite using the same functionality, click [here](https://tio.run/##y0rNyan8///hzlnHljzc0ap7aKvzw50Nh3YbaB/a@nDnmkdNa7gOT1c63A5UkK@f/6hhbrz1o8btXIfbgTL///@PjjaN1Yk20jECkiY6xjpGOoZAlimcZQRkmelYgOUNDYAcQyMdEx1DEGVoBhYzAPLNdUAmxAIA "Jelly โ€“ Try It Online"). ### How? ``` แนšฦคแธ…-ยตCแน€ยป0+ยตแนฌโ‚ฌร—"ยณแนšo/oโ€_;โท - Main link: list a e.g. [ 5, 3, 2, 1] ฦค - prefix application of: แนš - reverse e.g. [[5],[3,5],[2,3,5],[1,2,3,5]] - - literal minus one แธ… - from base (vectorises) e.g. [ 5, 2, 4, 3]= ยต - start a new monadic chain - call that list c - [code to shift so minimum is 1 or current minimum] C - complement (vectorises) e.g. [-4,-1,-3,-2] แน€ - maximum e.g. -1 ยป0 - maximum of that & zero e.g. 0 + - add to c (vectorises) e.g. [ 5, 2, 4, 3] ยต - start a new monadic chain - call that list d แนฌโ‚ฌ - untruth โ‚ฌach e.g. [[0,0,0,0,1],[0,1],[0,0,0,1],[0,0,1]] ยณ - the program input (a) ร—" - zip with multiplication e.g. [[0,0,0,0,5],[0,3],[0,0,0,2],[0,0,1]] แนš - reverse [[0,0,1],[0,0,0,2],[0,3],[0,0,0,0,5]] o/ - reduce with or e.g. [0,3,1,2,5] โ€_ - '_' o - or (replace 0 with '_') e.g. ['_',3,1,2,5] ;โท - concatenate a newline e.g. ['_',3,1,2,5, '\n'] - implicit print ``` Notes: The final concatenation of a newline, `;โท` is for cases when no `_` appear in the output, in which case the implicit print would display a representation of the list, e.g. `[3, 1, 2, 4]`, rather than something like the example, `_3125`. For no trailing newline one could replace `;โท` with `;โ€œโ€œ` to append a list of character lists, `[[''],['']]` (no close `โ€` required as it's the last character of a program). The untruth function, แนฌ, gives a list with `1`s at the indexes in it's input, for a single natural number, **n** that is **n-1** `0`s followed by a `1` allowing the input numbers to be placed at their correct distance from the left by multiplication. The reversal, `แนš`, is required to have *later* frog-visits overwrite rather than *earlier* ones when the reduction with or, `o/`, is performed. [Answer] # Javascript (ES6), 109 bytes ``` f=x=>x.map((y,i)=>o[j=(j-=i%2?y:-y)<0?o.unshift(...Array(-j))&0:j]=y,o=[],j=-1)&&[...o].map(y=>y||'_').join`` ``` ``` <!-- snippet demo: --> <input list=l oninput=console.log(f(this.value.split(/,/)))> <datalist id=l><option value=5><option value="4,3,2,1"><option value="5,3,2,1"><option value="2,3,6,8,2"><option value="10,3,12,4,1,12,16"><option value="100,4,7,2,2"></datalist> ``` ### Commented: ``` f=x=>x.map((y,i)=>o[j=(j-=i%2?y:-y)<0?o.unshift(...Array(-j))&0:j]=y,o=[],j=-1)&&[...o].map(y=>y||'_').join`` /* initialize output array [] and index j at -1: */ o=[],j=-1 x.map((y,i)=> /* iterate over all items in input x (y=item, i=index) */ ) (j-=i%2?y:-y) /* update j +/-y based on if index i is odd */ <0? /* if resulting j index is less than zero */ o.unshift(...Array(-j)) /* prepend -j extra slots to the output array */ &0 /* and give result 0 */ :j /* else give result j */ j= /* assign result to j */ o[ /* assign y to output array at index j */ ]=y /* short-circuit && then spread output array to fill any missing entries */ &&[...o] /* fill falsey slots with '_' */ .map(y=>y||'_') /* join with empty spaces */ .join`` ``` [Answer] # [Perl 6](https://perl6.org), ~~68~~ 67 bytes ``` {(my @a)[[[\+] |(1,-1)xx*Z*$_].&{$_ X-min 1,|$_}]=$_;[~] @a X//"_"} ``` [Try it online!](https://tio.run/nexus/perl6#XczBCoJAEAbgu08xyCKrjelsaoEIPYa0LYsHhQ52kUJRe/VtgsDoND/fPzOPoYVnUXr9BEEHlZslp3MTaq2vOwOLJIwpHMfoEglr9sEsLNRxf7sD4SLsaiphS/0yfAN1kvjWX93QTNCBzMPS@8YMD6iQNsj/QTEUeEK1EaVspDBD@gwqfquU@cgveN@9AQ "Perl 6 โ€“ TIO Nexus") ### How it works First it determines the cumulative jump locations: ``` [[\+] |(1,-1)xx*Z*$_] $_ # Input array. e.g. 2, 3, 6, 8, 2 |(1,-1)xx* # Infinite sequence: 1,-1, 1,-1, 1... Z* # Zip-multiplied. e.g. 2,-3, 6,-8, 2 [\+] # Cumulative addition. e.g. 2,-1, 5,-3,-1 ``` Then it turns them into 0-based array indices by subtracting the minimum number (but at most 1) from all the numbers: ``` .&{$_ X-min 1,|$_} # e.g. 5, 2, 8, 0, 2 ``` Then it creates an array with the input numbers assigned to those indices: ``` (my @a)[ ]=$_; # e.g. 8, Nil, 2, Nil, Nil, 2 Nil, Nil, 6 ``` Finally it concatenates the array to a string, with the underscore in place of undefined elements: ``` [~] @a X//"_" # e.g. 8_2__2__6 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~45~~ 30 bytes[SBCS](https://github.com/abrudz/SBCS) ``` {โˆŠโ•ยจโต@iโดโˆ˜'_'โŒˆ/1+iโ†(โŠข-1โŒŠโŒŠ/)-\โต} ``` [Try it online!](https://tio.run/##tU8xasNAEOz1ius2wQjfns6KSOWHBA5BUBARyBg1IbgLQVZ8wY3Btas8IG5S5in7EXlOgdjYtYfldtmZHebyWRU/vuRV/dTL56as5X2t@wLvq7Sd@M3vl/j9tBT/Le2WHMmqHfOohOBGul3MsupQ49v4AbpF3zfDqd/LcjfHWIj/uaciLyvChP1cPt6ofqZFNFFnaMgBE4qMMueMcYYiqxIwfLpP2FiC1QXhwAxWiUpVdjRsKHPGhUopYg2ajbK4ReN0iMAgEzQd4lgOCx7EGsI79Z/uL@8VYUMYrcPfDw "APL (Dyalog Unicode) โ€“ Try It Online") `-\โต` scan the argument with alternating `-` and `+` `(โŠข - 1 โŒŠ โŒŠ/)` from that (`โŠข`) subtract 1 or the minimum (`โŒŠ/`), whichever is smaller (`โŒŠ`) `iโ†` assign to `i` `โŒˆ/ 1+` increment and take the maximum `โดโˆ˜'_'` produce that many underscores `โต@i` put the numbers from the argument (`โต`) at positions `i` `โˆŠโ•ยจ` format each and flatten [Answer] # [Ruby](https://www.ruby-lang.org/), 85 bytes ``` ->a{i=1;j=c=0;a.map{|x|[c-=x*i=-i,x]}.to_h.sort.map{|x,y|[?_*[x+~j,0*j=x].max,y]}*''} ``` [Try it online!](https://tio.run/##tZDRasMwDEXf@xXFL4VMCZbjZIWi7UOEMVlYaQKlpfPAJc5@PbOTUVjX110MAt0jdOXL59t12tOUvzRDR7jrqSW5a4pjcx6CD9zm5LOO8g68GQt3sofi43RxPz5cA7/ajP3TVw8y68mb6MS2GbPNZpx4xVwZWP@VsFGVMBAJBeoBI5RVi6@hBAV4x4gSlV6A6jFgI3FbUUIN27tFYmuVTa9eKJQRQwUaMBWsZzpFxQiVscgUW2Nq4G1IxoFn@H3FfN8/SqdQUs5/tDLFe9MehuDCeb1nx9IYIsdoxukb "Ruby โ€“ Try It Online") Records the positions after each jump, converts the resulting array to hash to remove duplicates (preserving the last value at each duplicated position), and then glues the values with the required amount of underscores. [Answer] # [Python 2](https://docs.python.org/2/), ~~113~~ 110 bytes ``` J=input() i=sum(J) l=['_']*2*i v=i, d=1 for j in J:i+=d*j;d=-d;l[i]=`j`;v+=i, print''.join(l[min(v):max(v)+1]) ``` [Try it online!](https://tio.run/##FcpLDsIgFEDROavojE/RCBoHJW8D3QIh1oQYH@GX2ja6emwn90xu/S3vknVrI2Cu68I4QfisiY2cRLD0QZ3QAskGKIkHRV5l7kKHuRsH7MGLYDycvIkWHUxhMlt/nHXGvFB6DgUzizbt3fiQnt@dXjnemlUXeZVKy5tUB@ru/g "Python 2 โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Zยท'_ะธsvyยฎyNรˆi+รซ-}ยฉวยฎ0โ€นiยคยฎร„ะธy0ยฉวรฌ]ยครœJ ``` [Try it online](https://tio.run/##AUwAs/9vc2FiaWX//1rCtydf0LhzdnnCrnlOw4hpK8OrLX3Cqcedwq4w4oC5acKkwq7DhNC4eTDCqcedw6xdwqTDnEr//1syLDMsNiw4LDJd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/6hD29XjL@woLqs8tK7S73BHpvbh1bq1h1Yen3toncGjhp2Zh5YcWne45cKOSgOQ4OE1sYeWHJ7j9V9JL0zHUOPQypj/0dGmsTrRRjpGQNJEx1jHSMcQyDKFs4yALDMdC7C8oQGQY2ikY6JjCKIMzcBiBkC@uQ7IhFgA). **Explanation:** ``` Z # Get the maximum of the (implicit) input-list (without popping) ยท # Double it '_ะธ '# Pop and push a list with 2*max amount of "_" s # Swap so the input-list is at the top v # Loop over each of its integers `y`: y # Push the current integer `y` ยฎ # Push integer `ยฎ` (-1 the first iteration) y # Push integer `y` again N # Push the 0-based loop-index รˆi # If the index is even: + # Add the `y` to `ยฎ` รซ # Else (the index is odd): - # Subtract the `y` from `ยฎ` instead } # Close the if-else clause ยฉ # Store it as new `ยฎ` (without popping) ว # Insert the `y` at this index `ยฎ` in the "_"-list # (no-op with pops if index `ยฎ` is out of bounds, e.g. negative) ยฎ0โ€นi # If `ยฎ` is negative (<0): ยค # Push the last item "_" (without popping the list) ยฎร„ # Push the absolute value of `ยฎ` ะธ # Pop both and push a list with that amount of "_" y # Push integer `y` again 0 # Push 0 ยฉ # Replace `ยฎ` with this 0 (without popping) ว # Insert the `y` at index 0 in the second "_"-list รฌ # Prepend the two lists together ] # Close both the if-statement and loop ยค # Push the last item "_" again (without popping the list) รœ # Trim all trailing "_" from the list J # Join the list together # (after which the result is output implicitly) ``` `Nรˆi+รซ-}` could alternatively be `โ€ž+-Nรจ.V` for the same byte-count: [Try it online](https://tio.run/##AU0Asv9vc2FiaWX//1rCtydf0LhzdnnCrnnigJ4rLU7DqC5WwqnHncKuMOKAuWnCpMKuw4TQuHkwwqnHncOsXcKkw5xK//9bMiwzLDYsOCwyXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/6hD29XjL@woLqs8tK7yUcM8bV2/wyv0wg6tPD730DqDRw07Mw8tObTucMuFHZUGIMHDa2IPLTk8x@u/kl6YjqHGoZUx/6OjTWN1oo10jICkiY6xjpGOIZBlCmcZAVlmOhZgeUMDIMfQSMdExxBEGZqBxQyAfHMdkAmxAA). ``` โ€ž+- # Push string "+-" Nรจ # (Modulair) index the loop-index into it .V # Evaluate and execute this character as 05AB1E code ``` ]
[Question] [ [Fermat's polygonal number theorem](https://en.wikipedia.org/wiki/Fermat_polygonal_number_theorem) states that every positive integer can be expressed as the sum of at most \$n\$ \$n\$-gonal numbers. This means that every positive integer can be expressed as the sum of up to three triangle numbers, four square numbers, five pentagonal numbers etc. Your task is to take a positive integer \$x\$, and an integer \$s \ge 3\$, and to output the [\$s\$-gonal](https://en.wikipedia.org/wiki/Polygonal_number) integers which sum to \$x\$. The \$n\$-th \$s\$-gonal integer, where \$n \ge 1\$ and \$s \ge 3\$, can be defined in a couple of ways. The non-math-y way is that the \$n\$th \$s\$-gonal number can be constructed as a regular polygon with \$s\$ sides, each of length \$n\$. For example, for \$s = 3\$ (triangular numbers): [![triangles](https://i.stack.imgur.com/qtWuZ.gif)](https://i.stack.imgur.com/qtWuZ.gif) See [here](https://en.wikipedia.org/wiki/Polygonal_number#Definition_and_examples) for examples with a larger \$s\$. The math-y definition is by using the formula for \$P(n, s)\$, which yields the \$n\$-th \$s\$-gonal number: $$P(n, s) = \frac{n^2(s-2) - n(s-4)}{2}$$ which is given in the Wikipedia page [here](https://en.wikipedia.org/wiki/Polygonal_number#Formula). ## Input Two positive integers, \$s\$ and \$x\$, with the condition \$s \ge 3\$. You may input these integers in the most natural representation in your language (decimal, unary, Church numerals, integer-valued floating point numbers etc.). ## Output A list of integers, \$L\$, with a maximum length of \$s\$, where the sum of \$L\$ is equal to \$x\$ and all integers in \$L\$ are \$s\$-gonal integers. Again, the integers may be outputted in the natural representation in your language, with any distinct, consistent separator (so non-decimal character(s) for decimal output, a character different from that used for unary output etc.) ## Rules * The inputs or outputs will never exceed the integer limit for your language * \$L\$ does not have to be ordered * In case of multiple possible outputs, any or all are acceptable * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ## Test cases ``` x, s => L 1, s => 1 2, s => 1, 1 5, 6 => 1, 1, 1, 1, 1 17, 3 => 1, 6, 10 17, 4 => 1, 16 17, 5 => 5, 12 36, 3 => 36 43, 6 => 15, 28 879, 17 => 17, 48, 155, 231, 428 4856, 23 => 130, 448, 955, 1398, 1925 ``` [Answer] # [Haskell](https://www.haskell.org/), 55 bytes ``` n%s=[l|l<-mapM(\_->scanl(+)0[1,s-1..n])[1..s],sum l==n] ``` [Try it online!](https://tio.run/##HctBCsIwEAXQq8yigRYnpTFt3Bhv4AnSIEEEi5OhOLrz7rHp5v3Ph/9M8noQlcJKfKAfnXVO67Wdb/oi98TUHrohGBRt@p5jF7aQiPLNQN5zLDktDB7qCdb3wh9oIBhlEY6VSTkEc6p1c9ydEKyry2iVi@UP "Haskell โ€“ Try It Online") Outputs all possible solutions. Defines the s-gonal numbers as the cumulative sum of the arithmetic progression ``` 1, s-2, 2*s-3, 3*s-4, ... ``` [Answer] # [Haskell](https://www.haskell.org/), ~~78 80~~ 77 bytes We compute the cartesian product of the first \$n\$ s-gonal numbers, and then find the first entry that sums to \$n\$. ``` s#n=[x|x<-mapM(map(\n->s*(n^2-n)`div`2+n*(2-n)))([0..n]<$[1..s]),sum x==n]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1g5zza6oqbCRjc3scBXA0hoxOTp2hVraeTFGenmaSakZJYlGGnnaWmAeJqaGtEGenp5sTYq0YZ6esWxmjrFpbkKFba2ebGKigb/i21NufJsDS25chMz82wLijLzSlQUgFb8BwA "Haskell โ€“ Try It Online") [Answer] # JavaScript (ES6), ~~83~~ 80 bytes A fast recursive search which maximizes the smallest term of the output. Takes input as `(s)(x)`. ``` s=>g=(x,n=0,a=[],y=~n*(~-n-n*s/2))=>x<y?x|a[s]?0:a:g(x,n+1,a)||g(x-y,n,[...a,y]) ``` [Try it online!](https://tio.run/##bc7LasMwEAXQfb9CSykdP/S0HarkQ4wXIk1MSpBLFIoNJr/ujlqTFseghWDOnTsf7suFw/X8eUt8936cTnYKdtda2oO3OThbNzDYu9/Qe@ITvwmZYMzu@rdh34@uDs0@37ptG/krB8fGEf/JAB7qNE0dDA2bDp0P3eWYXrqWniiRjBJCOGMkywh/WZ2KeQrPwPwA/Qceb3UVLx7SoMmXSC0QN0uh/wuNQqwWSfMrpFm9WMm5AjeIckFwOyVlUc2kAKJKLNLRSjxKPSUEdqpSz51c5ohipooZLqsYr4SevgE "JavaScript (Node.js) โ€“ Try It Online") ### Formula It turns out to be shorter to use a 0-based formula to compute the \$s\$-gonal numbers in JS, i.e. to start with \$n=0\$ and to compute \$P(n+1,s)\$: $$\begin{align}P(n+1,s)&=((n+1)^2(s-2)-(n+1)(s-4))/2\\ &=(n^2(s-2)+ns+2)/2\\ &=-(n+1)((n-1)-ns/2) \end{align}$$ which can be written in 14 bytes: ``` ~n*(~-n-n*s/2) ``` ### Commented ``` s => // main function taking s g = ( // recursive function g x, // taking x n = 0, // start with n = 0 a = [], // a[] = list of s-gonal numbers y = // y = P(n + 1, s) ~n * (~-n - n * s / 2) // = -(n + 1) * ((n - 1) - n * s / 2) ) => // x < y ? // if x is less than P(n + 1, s): x | a[s] ? // if x is not equal to 0 or a[] is too long: 0 // failed: return 0 : // else: a // success: return a[] : // else: // process recursive calls: g(x, n + 1, a) || // preferred: try to increment n g(x - y, n, [...a, y]) // fallback : try to use the current s-gonal number ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes *Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/194053/6484).* ``` รIร*>.ยฅยนรฃ.ฮ”OQ ``` [Try it online!](https://tio.run/##ASAA3/9vc2FiaWX//8ONScOdKj4uwqXCucOjLs6UT1H//zMKOA) [Answer] # [Ruby](https://www.ruby-lang.org/), 79 bytes Computes the first \$n\$ \$s\$-gonal numbers and zero, gets the cartesian product of itself \$s\$ times, and finds the first entry that matches. Later test cases run out of memory on TIO but theoretically work. \$\frac{n^2(s-2)-n(s-4)}{2}\$ is reorganized into \$\frac{n(ns-2n-s+4)}{2}\$ because it saves bytes in Ruby. ``` ->n,s{a=(0..n).map{|i|i*(i*s-2*i-s+4)/2};a.product(*[a]*~-s).find{|a|a.sum==n}} ``` [Try it online!](https://tio.run/##Nc3tCoIwFAbg/17FkIht6crPoLAbiZDlRx2YU9wkQu3W15Q6vx7ec15OP9zfps6Mf5GeGnmGD4xJwhrejRNMQDFQ5YcUfLWLyT6cz5x1fVsOhcb0ym/04yvCapDlOPGJMzU0WSbn2byeICr0qLRykJ0O1azgQmC6yZnqBGjseu76B29Pus2BEKeSpbG3gYdQtLTCPxKL1CI4/pIV8R@JRZQuqy8 "Ruby โ€“ Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 111 bytes ``` \d+ * ~(`$ $" 0%["^_+ "|""]'$L$`\G_(?<=(?=___(_*))_+) ((_(?($.(2*$>`))$1\$.(2*$>`)))$*) 1%|' L$`\G_ $$.$.($`$>` ``` [Try it online!](https://tio.run/##RYsxDoJAEEX7OcVkM4SZJSEuCwsmIiWNNxCdJdHCxsJYEq@@QixsXvL@y3/d34/n7FLGY0zTrQALH44EZGCXnc1VCzSLMZecThSnUXk49Dz0qspqRbQQYF5XppIrS8coQm76i5AVcNmS4@8PROVaKa41pYANeHQt1BuaDR59gIC1B9di1@6h8lh3TfgC "Retina โ€“ Try It Online") Link includes test cases. Takes input in the order `s n`. Explanation: ``` \d+ * ``` Convert to unary. ``` ~(` ``` After processing the remaining stages, treat them as a Retina program and execute them on the same input. ``` $ $" ``` Duplicate the line. ``` 0%["^_+ "|""]'$L$`\G_(?<=(?=___(_*))_+) ((_(?($.(2*$>`))$1\$.(2*$>`)))$*) ``` Replace the first copy with a regular expression that skips over the first number and then matches `s` `s`-gonal numbers. The numbers themselves are captured in odd capture groups and the even capture groups are used to ensure that all of the numbers are `s`-gonal. ``` 1%|' L$`\G_ $$.$.($`$>` ``` Replace the second copy with a space-separated list of the odd capture groups. As an example, the generated code for an input of `5 17` is as follows: ``` ^_+ ((_(?(2)__\2))*)((_(?(4)__\4))*)((_(?(6)__\6))*)((_(?(8)__\8))*)((_(?(10)__\10))*)$ $.1 $.3 $.5 $.7 $.9 ``` [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` def f(s,x,n=0,a=[]):y=~n*(~-n-n*s/2);return(x<1)*a*(len(a)<=s)if x<y else f(s,x,n+1,a)or f(s,x-y,n,a+[y]) ``` [Try it online!](https://tio.run/##VY7LbsMgEEX3/YqRugFnrHrA@NHYXxJlgVSsRopIZLuS2eTXXQiKHSQWw5xzL9zd/Huzcl1/zAADm3BB2xeo@9OZf7v@YTP2yG1us@lL8ONo5r/RsqUjnumMXY1lmnf9xC8DLJ0Dc53Mq@VAqPltjNfcoUV9OLkzX@/jxc5sYCARAIhz@AT6SLcibvEdVAGoDWwnjVL9MrxPxQ7LBFK1E7UTP5JIC2X1JLJKf1LKWOUTotkQ1QhN3Ubk57LxhSo40j9avplCYtmo2E2y8DC4bXBJtiHWCrX@Aw "Python 3 โ€“ Try It Online") *Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/194054/87681), so make sure to upvote him!* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833) ``` xโ€™2;โ€™ร„ร„xโธล’PSโผยฅฦ‡ ``` A (very very inefficient) dyadic Link accepting `s` on the left and `x` on the right which yields a list of many possible `L` lists, with repeats. **[Try it online!](https://tio.run/##y0rNyan8/7/iUcNMI2sgcbjlcEvFo8YdRycFBD9q3HNo6bH2////m/03AgA "Jelly โ€“ Try It Online")** - not much point trying it for much higher values! ### How? ``` xโ€™2;โ€™ร„ร„xโธล’PSโผยฅฦ‡ - Link: s, x e.g. 5, 17 x - repeat (s) (x) times [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5] โ€™ - decrement (vectorises) [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] 2; - prepend a two [2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] โ€™ - decrement (vectorises) [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] ร„ - cumulative sums [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52] ร„ - cumulative sums [1, 5, 12, 22, 35, 51, 70, 92, 117, 145, 176, 210, 247, 287, 330, 376, 425, 477] xโธ - repeat (each of those) (s) times [1, 1, 1, 5, ..., 425, 477, 477, 477] ล’P - power-set [[], [1], [1], ..., [1, 1], ..., [5, 22, 70], ... etc] (this has 2^(x(s+1)) entries ...this example would have 2^(17(5+1)) = 2^102 = 5070602400912917605986812821504 entries!) (Note: the lengths increase left to right) ฦ‡ - filter keep if: ยฅ - last two links as a dyad: S - sum โผ - equals (x)? [[5,12], ... , [5,12], [1, 1, 5, 5, 5], ... , [1, 1, 5, 5, 5], [1, 1, 1, 1, 1, 12], ...] ``` [Answer] # [C++ (clang)](http://clang.llvm.org/), 198 bytes ``` #import<vector> using V=std::vector<int>;V f(int n,int s){V _{0};int z=1,a=0,b=1,i,t;for(;a<n;b+=s-2)_.push_back(a+=b),++z;V o;for(t=a=0;t-n;b=++a)for(o=V(s),t=i=0;b;b/=z)t+=o[i++]=_[b%z];return o;} ``` [Try it online!](https://tio.run/##ZZLdjqJAEIXveYpaN5tAaHf59wfaJ9hrbxxjANElqw2BdmI0Prt7CsVhdojBPl@dquoqzet6nB9Stb/fv5fHump08l7kumoWxqkt1Z6WstXb@fwBk1LpRbyknYkDKcHv1rouaXN1bjGri3RFKh2R4bsUOt5VjRmniYozW7Zjz9r8rE/tn02W5n/N1JaZJWz7gopV59QSubEewy5tO7WYVXJptpbQskQoi7Nf8mJpW1ar0rbXcrPKflzWcVPoU6NQ5YYxVH44bQtKyqrVTZEe@1FUeizaOs0Lwkix8V6VW6ob3Npc0tm6Gnl10kkyohWNYgOtqZuyoDmdCWEqd2bxTTqWQXjYTEmCMF4jzrgZPRut31QHuhb7SqUH@ryxl1WhoaBRkrTcWS64UHcnMrFlJVrL4kL8MDympTItukJ2ZU1X@DA8zt7gHIrodXYngwBEMBThS/jRwBb4gwKhL1znpaaTmXAnH85pGAlvkCmCYHAN1@HMwUwo5vNQH8TFjT4B/38QfAFfCPpgFiD@cZ5/Bweru0OeBVHLy/3NUbdXLivvpcQDhABRD14fRLAsIv8ZicCcHga9PepJyASVXA8Ei30m@mzAavsOcHhTIOwE5TrkiAeeGMSLRrkOo2gw5RDHfPQKkNitHrJz@MgM2DNjj@vP2D7zwn8 "C++ (clang) โ€“ Try It Online") ``` V=vector<int> V _{0}; // initialized with one element =0 int z=1, // vector size a=0,b=1,i,t;for(;a<n;b+=s-2)_.push_back(a+=b),++z; // pushes polygons in V V o; // vector to be returned for(t=a=0;t-n;b=++a) // ends when t=n // loop to generate multi-dimension indexes // for example a=1234 z=10 // a%z->4 , a/=z , a%z-> 3 , ... 2 , 1 for(o=V(s),t=i=0;b;b/=z)// loop to extract indexes t+=o[i++]=_[b%z]; // put the sum in t and values in o return o ``` [Answer] # APL(NARS), 149 chars, 298 bytes ``` rโ†f w;n;s;i;k (n s)โ†wโ‹„rโ†โฌโ‹„โ†’0ร—โณs<3โ‹„iโ†1 โ†’0ร—โณn<kโ†2รทโจ(iร—iร—s-2)-iร—s-4โ‹„rโ†r,kโ‹„i+โ†1โ‹„โ†’2 hโ†{0=โ‰ขbโ†((vโ†โ†‘โต)=+/ยจa)/aโ†{0=โ‰ขโต:โŠ‚โฌโ‹„m,(โŠ‚1โŒทโต),ยจmโ†โˆ‡1โ†“โต}fโต:vโด1โ‹„kโ†โ†‘โ‹โ‰ขยจbโ‹„kโŠƒb} ``` if not find solutions "0=โ‰ขb" than return for (n s) input, n times 1; else it would return the sum of s numbers that has less addend... test: ``` h 1 3 1 h 2 8 1 1 h 5 6 1 1 1 1 1 h 17 3 1 6 10 h 17 4 1 16 h 17 5 5 12 h 36 3 36 h 43 6 15 28 h 879 17 17 48 155 231 428 h 4856 23 321 448 596 955 2536 +/h 4856 23 4856 ``` The problem of this: It not find some solution has some number repeat in the sum... ]
[Question] [ I drew this map of the regions of an imaginary word in a few minutes in MS Paint: ![my map](https://i.stack.imgur.com/weDlq.png) I think that being able to generate maps like this programmatically would be really cool. # Challenge Write a program that takes in positive integers `W` and `H`, and a non-empty set of positive integers `S`. Generate a standard [true color](http://en.wikipedia.org/wiki/Color_depth#True_color_.2824-bit.29) image that is `W` pixels wide by `H` pixels tall. For each integer `i` in `S`, draw a planar region in the image whose area in pixels is proportional to `i`, using a color different from any neighboring regions. Specifically, the number of pixels in the region should be `W * H * i / sum(S)`, rounded either up or down to **ensure that every pixel in the image belongs to a region**. A planar region is a set of pixels with the property that any pixel in the region can be reached from any other by staying within the region and [only moving orthogonally](http://en.wikipedia.org/wiki/Von_Neumann_neighborhood) (and not diagonally). My map above has 10 planar regions. All the pixels in a planar region must be the same color, which must be different than the color of any neighboring regions. Regions may be the same color if they are not neighbors. Otherwise, there are no limitations on how you shape, position, or color your regions. This is a popularity-contest. The goal is to create a program that makes realistic maps of imaginary worlds, physical or political, with any geography, at any scale. Naturally, please show off your best output images, not just your code. # Details * Take input from file, command line, stdin, or similar. Save the image in any standard format or display it to the screen. * Your program should be deterministic for identical inputs. That is, the output image should always be the same for some particular `H`, `W`, and `S`. (Note that **`S` is a set**, not a list, so its ordering doesn't matter.) Otherwise you may employ randomness where desired, though you are not required to (but I highly suggest it). * The output image geography does not need to "scale" for different values of `W` or `H` (though it could). It may be completely different. * You may randomly assign colors, disregarding the neighbor-color rule, as long as there at least 32 random color possibilities, since it would be unlikely for two neighbors to get colored the same. * The regions stop at the image boundaries. There is no [wrap around](http://en.wikipedia.org/wiki/Periodic_boundary_conditions). * Regions may contain zero pixels (and thus be nonexistent), as would be the case when there are more regions than pixels. # Example Input A valid submission might have generated my map above with the parameters: ``` W = 380 H = 260 S = {233, 420, 1300, 3511, 4772, 5089, 9507, 22107, 25117, 26744} ``` These `S` values are the exact same as the number of pixels in each region but that need not be the case. Remember that `S` is a set, so it is not necessarily always sorted. [Answer] I agree with the others, This was a surprisingly difficult challenge. Partially due to the requirement to have adjacently connected pixels of the same region type, but also due to the aesthetic challenge to make the regions look like a map of countries. Here is my attempt... it is horribly inefficient but seems to produce reasonable output. Continuing the trend of using common input for comparison purposes: **Parameters : 380 260 233 420 1300 3511 4772 5089 9507 22107 25117 26744** ![enter image description here](https://i.stack.imgur.com/KmILq.png) **Parameters : 380 260 8 5 6 7 8 4 5 6 7 9 4 6 9 5 8 7 5** ![enter image description here](https://i.stack.imgur.com/rn4tn.png) **Dark Age of Camelot 213 307 1 1 1** ![enter image description here](https://i.stack.imgur.com/QYtFr.png) **My larger example: (640 480 6 1 7 2 9 3 4 5 6 1 9 8 7 44 3 1 9 4 5 6 7 2 3 4 9 3 4 5 9 8 7 5 6 1 2 1 2 1 2 6 7 8 9 63 3)** ![enter image description here](https://i.stack.imgur.com/i8mQk.png) **An example with more countries: 640 480 6 1 7 2 9 3 4 5 6 1 9 8 7 44 3 1 9 4 5 6 7 2 3 4 9 3 4 5 9 8 7 5 6 1 2 1 2 1 2 6 7 8 9 63 5 33 11 88 2 7 9 5 6 2 5 7** ``` package GenerateRealisticMaps; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import javax.imageio.ImageIO; public class GenerateRealisticMaps { private static final Random rand = new Random(3); private static final Color[] paletteizedColours = new Color[100]; // create colour palette static { paletteizedColours[0] = new Color(0xFF000000); for (int i = 1; i < paletteizedColours.length; i++) { paletteizedColours[i] = Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), 0.5f + rand.nextFloat() * 0.4f); } } /** * Represents a pixel that is the boundary of a region * @author default * */ public static class BoundaryPixel { public BoundaryPixel(int x, int y, int otherRegionId) { super(); this.x = x; this.y = y; this.otherRegionId = otherRegionId; } int x; int y; int otherRegionId; } /** * Group of adjacent pixels that represent a region (i.e. a country in the map) * @author default * */ public static class Region { static private int masterId = 0; Region(int desiredSize) { this.desiredSize = desiredSize; id = ++masterId; } int desiredSize; int size = 0; int id; List<BoundaryPixel> boundary = new ArrayList<GenerateRealisticMaps.BoundaryPixel>(); } /** * Container of regions * @author default * */ public static class Regions { List<Region> regionList = new ArrayList<GenerateRealisticMaps.Region>(); Map<Integer, Region> regionMap = new HashMap<Integer, GenerateRealisticMaps.Region>(); } public static void main(String[] args) throws IOException { int width = Integer.parseInt(args[0]); int height = Integer.parseInt(args[1]); int[] s = new int[args.length - 2]; // read in the region weights int sum = 0; for (int i = 0; i < args.length - 2; i++) { sum += s[i] = Integer.parseInt(args[i + 2]); } int totalPixels = width * height; double multiplier = ((double) totalPixels) / sum; // convert region weights to pixel counts int runningCount = 0; for (int i = 0; i < s.length - 1; i++) { runningCount += s[i] = (int) (multiplier * s[i]); } s[s.length - 1] = totalPixels - runningCount; Regions regions = new Regions(); int[][] map = new int[width][height]; // initialise region starting pixels for (int v : s) { Region region = new Region(v); regions.regionList.add(region); regions.regionMap.put(region.id, region); int x; int y; do { x = rand.nextInt(width); y = rand.nextInt(height); } while (map[x][y] != 0); map[x][y] = region.id; region.size++; } // initialise a "height" map that provides cost to claim a unclaimed region. This allows for more natural shaped countries int[][] heightMap = new int[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { heightMap[i][j] = rand.nextInt(50); } } boolean equal = false; // main loop do { growRegions(map, heightMap, width, height, regions); // determine whether regions have reached their desired size equal = true; for (Region region : regions.regionList) { equal = equal && region.size == region.desiredSize; } if (equal) { HashMap<Integer, Set<Integer>> commonIsolatedRegions = new HashMap<Integer, Set<Integer>>(); int isolatedRegionId = 0; int[][] isolatedRegions = new int[width][height]; List<Integer> isolatedRegionSize = new ArrayList<Integer>(); isolatedRegionSize.add(-1); // add dummy entry at index 0 since region ids start at 1 // go though each pixel and attempt to identify an isolated region from that point if it as not // yet been identified... i.e. an enclosed area. for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (isolatedRegions[i][j] == 0) { isolatedRegionId++; Point point = new Point(i, j); int size = identifyEnclosedArea(map, isolatedRegions, width, height, point, isolatedRegionId); // add this isolated region id to the group of isolated regions associated with the region at this pixel Set<Integer> isolatedRegionSet = commonIsolatedRegions.get(map[i][j]); if (isolatedRegionSet == null) { isolatedRegionSet = new HashSet<Integer>(); commonIsolatedRegions.put(map[i][j], isolatedRegionSet); } isolatedRegionSet.add(isolatedRegionId); isolatedRegionSize.add(size); } } } // only keep the largest isolated region in each group. Mark the other members in the group areas as unclaimed. for (Region region : regions.regionList) { Set<Integer> isolatedRegionSet = commonIsolatedRegions.get(region.id); // find the largest isolatedRegion mapped to this region int largestIsolatedRegionId = -1; int largestIsolatedRegionSize = -1; for (Integer isolatedRegionIdentifier : isolatedRegionSet) { if (isolatedRegionSize.get(isolatedRegionIdentifier) > largestIsolatedRegionSize) { largestIsolatedRegionSize = isolatedRegionSize.get(isolatedRegionIdentifier); largestIsolatedRegionId = isolatedRegionIdentifier; } } // remove the largest isolated region (i.e. retain those pixels) isolatedRegionSet.remove(largestIsolatedRegionId); if (isolatedRegionSet.size() > 0) { equal = false; // for all remaining isolated regions mapped to this region, convert to unclaimed areas. for (Integer isolatedRegionIdentifier : isolatedRegionSet) { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (isolatedRegions[i][j] == isolatedRegionIdentifier) map[i][j] = 0; } } } } } } } while (!equal); saveOutputImage("out.final.png", map); } /** * Renders and saves the output image * * @param filename * @param map * @throws IOException */ public static void saveOutputImage(String filename, int[][] map) throws IOException { final int scale = 1; final int width = map.length; final int height = map[0].length; BufferedImage image = new BufferedImage(width * scale, height * scale, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { g.setColor(paletteizedColours[map[i][j]]); g.fillRect(i * scale, j * scale, scale, scale); } } ImageIO.write(image, "png", new File(filename)); } /** * Grows the regions of the world. Firstly by unclaimed cells and then by distributing cells amongst the regions. * * @param map * cell to region map * @param heightMap * the "height" cost of unclaimed cells. Used to give more natural shapes. * @param width * @param height * @param regions */ public static void growRegions(int[][] map, int[][] heightMap, int width, int height, Regions regions) { // reset region sizes for (Region region : regions.regionList) { region.size = 0; region.boundary.clear(); } // populate corners with adjacent pixel region id... these pixels cannot ever be "grown" into. map[0][0] = map[1][0]; map[width - 1][0] = map[width - 1][5]; map[width - 1][height - 1] = map[width - 2][height - 1]; map[0][height - 1] = map[1][height - 1]; int i, x, y, dx = 0, dy = 0, currHeight, currentId = -1, pixelRegionId; Region currRegion = null; ; // calculate initial region sizes for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { if (map[x][y] > 0) regions.regionMap.get(map[x][y]).size++; } } // expand regions into surrounding unclaimed pixels. // construct a list of region boundary pixels in the process. for (y = 1; y < height - 1; y++) { for (x = 1; x < width - 1; x++) { int cellId = map[x][y]; if (cellId > 0) { if (cellId != currentId) { currRegion = regions.regionMap.get(map[x][y]); currentId = currRegion.id; } currHeight = heightMap[x][y]++; for (i = 0; i < 4; i++) { switch (i) { case 0: dx = x - 1; dy = y; break; case 1: dx = x + 1; dy = y; break; case 2: dx = x; dy = y - 1; break; case 3: dx = x; dy = y + 1; break; } pixelRegionId = map[dx][dy]; switch (pixelRegionId) { // unclaimed cell... case 0: if (heightMap[dx][dy] < currHeight) { map[dx][dy] = currRegion.id; currRegion.size++; } break; // claimed cell... default: if (pixelRegionId != currRegion.id) { currRegion.boundary.add(new BoundaryPixel(dx, dy, pixelRegionId)); } break; } } } } } HashMap<Integer, List<BoundaryPixel>> neighbourBorders = new HashMap<Integer, List<BoundaryPixel>>(); // for all regions... for (Region region : regions.regionList) { // that are less than the desired size... if (region.size < region.desiredSize) { neighbourBorders.clear(); // identify the boundary segment per neighbour of the region for (BoundaryPixel boundaryPixel : region.boundary) { List<BoundaryPixel> neighbourBorderSegment = neighbourBorders.get(boundaryPixel.otherRegionId); if (neighbourBorderSegment == null) { neighbourBorderSegment = new ArrayList<GenerateRealisticMaps.BoundaryPixel>(); neighbourBorders.put(boundaryPixel.otherRegionId, neighbourBorderSegment); } neighbourBorderSegment.add(boundaryPixel); } out: // for each neighbour... for (int id : neighbourBorders.keySet()) { Region neighbourRegion = regions.regionMap.get(id); int surplusPixelCount = neighbourRegion.size - neighbourRegion.desiredSize; // that has surplus pixels... if (surplusPixelCount > 0) { // and convert the border segment pixels to the current region... List<BoundaryPixel> neighbourBorderSegment = neighbourBorders.get(id); int index = 0; while (surplusPixelCount-- > 0 && index < neighbourBorderSegment.size()) { BoundaryPixel boundaryPixel = neighbourBorderSegment.get(index++); map[boundaryPixel.x][boundaryPixel.y] = region.id; region.size++; regions.regionMap.get(boundaryPixel.otherRegionId).size--; // until we reach the desired size... if (region.size == region.desiredSize) break out; } } } } // if region contains more pixels than desired... else if (region.size > region.desiredSize) { // and the region has neighbours if (region.boundary.size() > 0) { // choose a neighbour to off load extra pixels to Region neighbour = regions.regionMap.get(region.boundary.remove(rand.nextInt(region.boundary.size())).otherRegionId); ArrayList<BoundaryPixel> adjustedBoundary = new ArrayList<>(); // iterate over the boundary neighbour's boundary pixels... for (BoundaryPixel boundaryPixel : neighbour.boundary) { // and then for those pixels which are of the current region, convert to the neighbour region if (boundaryPixel.otherRegionId == region.id) { map[boundaryPixel.x][boundaryPixel.y] = neighbour.id; neighbour.size++; region.size--; // stop when we reach the region's desired size. if (region.size == region.desiredSize) break; } else { adjustedBoundary.add(boundaryPixel); } } neighbour.boundary = adjustedBoundary; } } } } /** * identifies the area, starting at the given point, in which adjacent pixels are of the same region id. * * @param map * @param isolatedRegionMap * cells identifying which area that the corresponding map cell belongs * @param width * @param height * @param point * the starting point of the area to be identified * @param isolatedRegionId * the id of the region to assign cells with * @return the size of the identified area */ private static int identifyEnclosedArea(int[][] map, int[][] isolatedRegionMap, int width, int height, Point point, final int isolatedRegionId) { ArrayList<Point> stack = new ArrayList<Point>(); final int EXPECTED_REGION_ID = map[point.x][point.y]; stack.add(point); int size = 0; while (stack.size() > 0) { Point p = stack.remove(stack.size() - 1); int x = p.x; int y = p.y; if (y < 0 || y > height - 1 || x < 0 || x > width - 1 || isolatedRegionMap[x][y] > 0) continue; int val = map[x][y]; if (val == EXPECTED_REGION_ID) { isolatedRegionMap[x][y] = isolatedRegionId; size++; stack.add(new Point(x + 1, y)); stack.add(new Point(x - 1, y)); stack.add(new Point(x, y + 1)); stack.add(new Point(x, y - 1)); } } return size; } } ``` # Explanation (from comments) The algorithm is pretty simple: Firstly initialise the map with random weights, choose random seed pixels for each of the country regions. Secondly "grow" each region by attempting to claim unclaimed adjacent pixels. This occurs when the weight of the current pixel exceeds the unclaimed weight. Each pixel in a region increases its weight each growth cycle. Additionally if a region has neighbours then if the current region being considered has less pixels than desired, then it will steal pixels from its neighbour if the neighbour has more pixels than desired. If the current region has more pixels than its neighbour then it randomly chooses a neighbour and then give all the surplus pixels to that neighbour. When all regions are of the correct size, then the third phase occurs to identify and convert any regions that have been split and are no longer continuous. Only the largest split of the region is kept and the other splits are converted into unclaimed pixels and the second phase starts again. This repeats until all pixels in a region are adjacent and all regions are of the correct size. [Answer] This challenge is surprisingly difficult. I wrote a map generator in Python using Pygame. The program grows the color area into free space, and results in an image that might look like a map (if you squint). My algorithm does not always complete the countries as the remaining area may not have enough space, but I thought it resulted in an interesting effect, and I will not be spending anymore time on it. The odd blue patches left can be considered large lakes, and the speckled blue features between countries are the rivers that mark the border (it is a feature, not a bug!). In order to compare with the Super Chafouin, I used their parameter examples. **Parameters : 380 260 233 420 1300 3511 4772 5089 9507 22107 25117 26744** ![Standard test](https://i.stack.imgur.com/fbXEq.png) **Parameters : 380 260 8 5 6 7 8 4 5 6 7 9 4 6 9 5 8 7 5** ![Example 2](https://i.stack.imgur.com/trFmr.png) **Dark Age of Camelot (213 307 1 1 1)** ![Example 3](https://i.stack.imgur.com/s7viZ.png) **My larger example: (640 480 6 1 7 2 9 3 4 5 6 1 9 8 7 44 3 1 9 4 5 6 7 2 3 4 9 3 4 5 9 8 7 5 6 1 2 1 2 1 2 6 7 8 9 63 3)** ![My larger example featuring East Europe?](https://i.stack.imgur.com/ESgpH.png) This example looks a little like East Europe? **An example with more countries: 640 480 6 1 7 2 9 3 4 5 6 1 9 8 7 44 3 1 9 4 5 6 7 2 3 4 9 3 4 5 9 8 7 5 6 1 2 1 2 1 2 6 7 8 9 63 5 33 11 88 2 7 9 5 6 2 5 7** ![More countries with mellow colors](https://i.stack.imgur.com/Ch2I7.png) I changed the color generator with this example to `colors = [(80+ri(100), 80+ri(100), 80+ri(100)) for c in counts]` so as to get a more mellow (and map-like) range. Python Code: ``` from pygame.locals import * import pygame, sys, random BACK = (0,0,200) ORTH = [(-1,0), (1,0), (0,-1), (0,1)] PI = 3.141592 random.seed(9999) def ri(n): return int(random.random() * n) args = [int(v) for v in sys.argv[1:]] W, H = args[:2] shares = sorted(args[2:]) ratio = float(W*H) / sum(shares) counts = [int(s*ratio) for s in shares] for i in range(W*H - sum(counts)): counts[i] += 1 colors = [(2+ri(250), 2+ri(250), 2+ri(250)) for c in counts] countries = range(len(counts)) random.shuffle(countries) border = ( set((x,y) for x in (0,W-1) for y in range(H)) | set((x,y) for x in range(W) for y in (0,H-1)) ) screen = pygame.display.set_mode((W,H)) screen.fill(BACK) pix = screen.set_at def look(p): if 0 <= p[0] < W and 0 <= p[1] < H: return screen.get_at(p) else: return None clock = pygame.time.Clock() while True: dt = clock.tick(300) pygame.display.flip() if countries: country = countries.pop() color = colors[country] if not countries: color = (20,20,200) # last fill color to be water count = counts[country] frontier = set() plotted = 0 loc = border.pop() while plotted < count: pix(loc, color) if plotted % 50 == 0: pygame.display.flip() plotted += 1 direc = [(loc[0]+dx, loc[1]+dy) for dx,dy in ORTH] for dloc in direc: if look(dloc) == BACK: frontier.add(dloc) border |= frontier if frontier: loc = frontier.pop() border.discard(loc) else: print 'Country %s cover %u of %u' % ( shares[country], plotted, count) break if not countries: fn = 'mapper%u.png' % ri(1000) pygame.image.save(screen, fn) for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) if not hasattr(event, 'key'): continue if event.key == K_ESCAPE: sys.exit(0) ``` [Answer] Let's be lazy and adapt my answer from [this question](https://codegolf.stackexchange.com/questions/34962/draw-an-image-with-a-snake/35009#35009) ! 1. The algorithm computes a "snake path" starting from upper left corner that fills the whole rectangle. The snake can go only up, down, left, right. 2. The snake path is followed and is filled with the first color, then the second color, etc... taking in account the color percentages 3. This algorithm produces a lots of straight lines; to improve it, I detect them and replace them with "waves" that keep the same amount of pixels. **Parameters : 380 260 233 420 1300 3511 4772 5089 9507 22107 25117 26744** ![enter image description here](https://i.stack.imgur.com/8VZwZ.png) **Parameters : 380 260 8 5 6 7 8 4 5 6 7 9 4 6 9 5 8 7 5** ![enter image description here](https://i.stack.imgur.com/sf08d.png) **Dark Age of Camelot (213 307 1 1 1)** ![enter image description here](https://i.stack.imgur.com/0edHg.png) The code: ``` package map; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; public class GenMap2 { private enum State { NO, YES, SHIFT }; public final static int TOP = 1, BOTTOM = 2, LEFT = 4, RIGHT = 8; enum Action { ADD_LINE_TOP, ADD_LINE_LEFT, DOUBLE_SIZE, CREATE}; public static void main(String[] args) throws IOException { int w = Integer.parseInt(args[0]), h = Integer.parseInt(args[1]); List<Integer> areas = new ArrayList<Integer>(); int total = 0; for (int i = 2; i < args.length; i++) { int area = Integer.parseInt(args[i]); areas.add(area); total += area; } Collections.sort(areas); Collections.reverse(areas); int [][] tab = build(w, h); BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); int [] black = {0, 0, 0}; for (int j = 0; j < dest.getHeight(); j++) { for (int i = 0; i < dest.getWidth(); i++) { dest.getRaster().setPixel(i, j, black); } } int x = 0, y = -1; int go = BOTTOM, previous = BOTTOM; List<Color> colors = new ArrayList<Color>(); Random rand = new Random(0); // prog must be deterministic while (colors.size() < areas.size()) { Color c = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)); boolean ok = true; for (Color existing : colors) { if (existing.equals(c)) { ok = false; break; } } if (ok) { colors.add(c); } } int [][] map = new int[w][h]; int cpt = 0; while (true) { if (go == BOTTOM) y++; if (go == TOP) y--; if (go == LEFT) x--; if (go == RIGHT) x++; int tmp = (int)(((long)cpt) * total / (w * h)); int i = 0; for (i = 0; i < areas.size(); i++) { int area = areas.get(i); if (tmp < area) { break; } tmp -= area; } map[x][y] = i; previous = go; go = -1; if ((tab[x][y] & TOP) != 0 && previous != BOTTOM) go = TOP; if ((tab[x][y] & BOTTOM) != 0 && previous != TOP) go = BOTTOM; if ((tab[x][y] & LEFT) != 0 && previous != RIGHT) go = LEFT; if ((tab[x][y] & RIGHT) != 0 && previous != LEFT) go = RIGHT; if (go == -1) break; cpt++; } String [] src0 = srcPattern(16); String [] repl0 = destPattern(16); while (findPattern(map, src0, Arrays.asList(repl0, flip(repl0)))){} while (findPattern(map, rotate(src0), Arrays.asList(rotate(repl0), rotate(flip(repl0))))){} String [] src1 = srcPattern(8); String [] repl1 = destPattern(8); while (findPattern(map, src1, Arrays.asList(repl1, flip(repl1)))){} while (findPattern(map, rotate(src1), Arrays.asList(rotate(repl1), rotate(flip(repl1))))){} String [] src2 = srcPattern(4); String [] repl2 = destPattern(4); while (findPattern(map, src2, Arrays.asList(repl2, flip(repl2)))){} while (findPattern(map, rotate(src2), Arrays.asList(rotate(repl2), rotate(flip(repl2))))){} for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { Color c = colors.get(map[x][y]); dest.getRaster().setPixel(x, y, new int[] {c.getRed(), c.getGreen(), c.getBlue()}); } } ImageIO.write(dest, "png", new FileOutputStream("map.png")); } private static Random randPat = new Random(0); private static String [] srcPattern(int size) { String [] ret = new String[size*2]; for (int i = 0; i < size*2; i++) { ret[i] = ""; for (int j = 0; j < size*4; j++) { ret[i] += i < size ? "1" : "2"; } } return ret; } private static String [] destPattern(int size) { String [] ret = new String[size*2]; for (int i = 0; i < size*2; i++) { ret[i] = ""; for (int j = 0; j < size*2; j++) { //int target = (int)((1 + Math.sin(j * Math.PI * .5/ size) * .4) * size); int target = (int)((1 + (Math.cos(j * Math.PI/ size) - 1) * .2) * size); ret[i] += (i < target) ? '1' : '2'; } } for (int i = 0; i < size*2; i++) { for (int j = 0; j < size*2; j++) { ret[i] += ret[size*2 - 1 - i].charAt(size*2 - 1 - j) == '1' ? '2' : '1'; } } return ret; } private static String [] flip(String [] pat) { String [] ret = new String[pat.length]; for (int i = 0; i < ret.length; i++) { ret[i] = new StringBuilder(pat[i]).reverse().toString(); } return ret; } private static String [] rotate(String [] pat) { String [] ret = new String[pat[0].length()]; for (int i = 0; i < ret.length; i++) { ret[i] = ""; for (int j = 0; j < pat.length; j++) { ret[i] += pat[j].charAt(i); } } return ret; } private static boolean findPattern(int [][] map, String [] src, List<String []> dest) { for (int y = 0; y < map[0].length - src.length; y++) { for (int x = 0; x < map.length - src[0].length(); x++) { int c1 = -1, c2 = -1; boolean wrong = false; for (int y1 = 0; y1 < src.length; y1++) { for (int x1 = 0; x1 < src[0].length(); x1++) { if (src[y1].charAt(x1) == '1') { if (c1 == -1) { c1 = map[x+x1][y+y1]; } else { if (c1 != map[x+x1][y+y1]) { wrong = true; } } } if (src[y1].charAt(x1) == '2') { if (c2 == -1) { c2 = map[x+x1][y+y1]; } else { if (c2 != map[x+x1][y+y1]) { wrong = true; } } } if (c1 != -1 && c1 == c2) wrong = true; if (wrong) break; } if (wrong) break; } if (!wrong) { System.out.println("Found match at " + x + " " + y); String [] repl = dest.get(randPat.nextInt(dest.size())); for (int y1 = 0; y1 < src.length; y1++) { for (int x1 = 0; x1 < src[0].length(); x1++) { map[x+x1][y+y1] = repl[y1].charAt(x1) == '1' ? c1 : c2; } } return true; } } } return false; } public static int [][] build(int width, int height) { List<Action> actions = new ArrayList<Action>(); while (height>1 && width>1) { if (height % 2 == 1) { height--; actions.add(Action.ADD_LINE_TOP); } if (width % 2 == 1) { width--; actions.add(Action.ADD_LINE_LEFT); } if (height%2 == 0 && width%2 == 0) { actions.add(Action.DOUBLE_SIZE); height /= 2; width /= 2; } } actions.add(Action.CREATE); Collections.reverse(actions); int [][] tab = null; for (Action action : actions) { if (action == Action.CREATE) { tab = new int[width][height]; if (height >= width) { for (int i = 0; i < height-1; i++) { tab[0][i] = TOP|BOTTOM; } tab[0][height-1] = TOP; } else { tab[0][0] = TOP|RIGHT; for (int i = 1; i < width-1; i++) { tab[i][0] = RIGHT|LEFT; } tab[width-1][0] = LEFT; } } if (action == Action.DOUBLE_SIZE) { tab = doubleTab(tab); } if (action == Action.ADD_LINE_TOP) { int [][] tab2 = new int[tab.length][tab[0].length+1]; for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab[0].length; j++) { tab2[i][j+1] = tab[i][j]; } } tab2[0][0] = BOTTOM|RIGHT; for (int i = 1; i < tab.length-1; i++) { tab2[i][0] = RIGHT|LEFT; } tab2[tab.length-1][0] = TOP|LEFT; mirror(tab2); tab = tab2; } if (action == Action.ADD_LINE_LEFT) { int [][] tab2 = new int[tab.length+1][tab[0].length]; for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab[0].length; j++) { tab2[i+1][j] = tab[i][j]; } } tab2[0][0] = BOTTOM|RIGHT; tab2[1][0] |= LEFT; tab2[1][0] -= TOP; for (int i = 1; i < tab[0].length-1; i++) { tab2[0][i] = TOP|BOTTOM; } tab2[0][tab[0].length-1] = TOP|BOTTOM; flip(tab2); tab = tab2; } } return tab; } private static void mirror(int [][] tab) { for (int i = 0; i < tab.length/2; i++) { for (int j = 0; j < tab[0].length; j++) { int tmp = tab[tab.length - 1 - i][j]; tab[tab.length - 1 - i][j] = tab[i][j]; tab[i][j] = tmp; } } for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab[0].length; j++) { if ((tab[i][j] & LEFT)!=0 && (tab[i][j] & RIGHT)==0) { tab[i][j] -= LEFT; tab[i][j] |= RIGHT; } else if ((tab[i][j] & RIGHT)!=0 && (tab[i][j] & LEFT)==0) { tab[i][j] -= RIGHT; tab[i][j] |= LEFT; } } } } private static void flip(int [][] tab) { for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab[0].length/2; j++) { int tmp = tab[i][tab[0].length - 1 - j]; tab[i][tab[0].length - 1 - j] = tab[i][j]; tab[i][j] = tmp; } } for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab[0].length; j++) { if ((tab[i][j] & TOP)!=0 && (tab[i][j] & BOTTOM)==0) { tab[i][j] -= TOP; tab[i][j] |= BOTTOM; } else if ((tab[i][j] & BOTTOM)!=0 && (tab[i][j] & TOP)==0) { tab[i][j] -= BOTTOM; tab[i][j] |= TOP; } } } } public static int [][] doubleTab(int [][] tab) { boolean [][] shiftTop = new boolean[tab.length][], shiftLeft = new boolean[tab.length][], shiftBottom = new boolean[tab.length][], shiftRight = new boolean[tab.length][]; for (int i = 0; i < tab.length; i++) { shiftTop[i] = new boolean[tab[i].length]; shiftLeft[i] = new boolean[tab[i].length]; shiftBottom[i] = new boolean[tab[i].length]; shiftRight[i] = new boolean[tab[i].length]; } int x = 0, y = -1; for (int i = 0; i < tab.length; i++) { if ((tab[i][0] & TOP) != 0) { x = i; } } int go = BOTTOM, previous = BOTTOM; boolean init = false; while (true) { if (go == BOTTOM) y++; if (go == TOP) y--; if (go == LEFT) x--; if (go == RIGHT) x++; previous = go; go = -1; if ((tab[x][y] & TOP) != 0 && previous != BOTTOM) go = TOP; if ((tab[x][y] & BOTTOM) != 0 && previous != TOP) go = BOTTOM; if ((tab[x][y] & LEFT) != 0 && previous != RIGHT) go = LEFT; if ((tab[x][y] & RIGHT) != 0 && previous != LEFT) go = RIGHT; if (previous == BOTTOM) { shiftTop[x][y] = y==0 ? init : shiftBottom[x][y-1]; } if (previous == TOP) { shiftBottom[x][y] = shiftTop[x][y+1]; } if (previous == RIGHT) { shiftLeft[x][y] = shiftRight[x-1][y]; } if (previous == LEFT) { shiftRight[x][y] = shiftLeft[x+1][y]; } if (go == -1) break; if (previous == BOTTOM && go == LEFT) { shiftLeft[x][y] = !shiftTop[x][y]; } if (previous == BOTTOM && go == RIGHT) { shiftRight[x][y] = shiftTop[x][y]; } if (previous == BOTTOM && go == BOTTOM) { shiftBottom[x][y] = shiftTop[x][y]; } if (previous == TOP && go == LEFT) { shiftLeft[x][y] = shiftBottom[x][y]; } if (previous == TOP && go == RIGHT) { shiftRight[x][y] = !shiftBottom[x][y]; } if (previous == TOP && go == TOP) { shiftTop[x][y] = shiftBottom[x][y]; } if (previous == RIGHT && go == TOP) { shiftTop[x][y] = !shiftLeft[x][y]; } if (previous == RIGHT && go == BOTTOM) { shiftBottom[x][y] = shiftLeft[x][y]; } if (previous == RIGHT && go == RIGHT) { shiftRight[x][y] = shiftLeft[x][y]; } if (previous == LEFT && go == TOP) { shiftTop[x][y] = shiftRight[x][y]; } if (previous == LEFT && go == BOTTOM) { shiftBottom[x][y] = !shiftRight[x][y]; } if (previous == LEFT && go == LEFT) { shiftLeft[x][y] = shiftRight[x][y]; } } int [][] tab2 = new int[tab.length * 2][]; for (int i = 0; i < tab2.length; i++) { tab2[i] = new int[tab[0].length * 2]; } for (int i = 0; i < tab.length; i++) { for (int j = 0; j < tab[0].length; j++) { State left = State.NO, right = State.NO, top = State.NO, bottom = State.NO; if ((tab[i][j] & LEFT) != 0) { left = shiftLeft[i][j] ? State.SHIFT : State.YES; } if ((tab[i][j] & TOP) != 0) { top = shiftTop[i][j] ? State.SHIFT : State.YES; } if ((tab[i][j] & RIGHT) != 0) { right = shiftRight[i][j] ? State.SHIFT : State.YES; } if ((tab[i][j] & BOTTOM) != 0) { bottom = shiftBottom[i][j] ? State.SHIFT : State.YES; } int [] comp = compute(left, top, right, bottom); tab2[i*2][j*2] = comp[0]; tab2[i*2+1][j*2] = comp[1]; tab2[i*2][j*2+1] = comp[2]; tab2[i*2+1][j*2+1] = comp[3]; } } return tab2; } private static int [] compute(State left, State top, State right, State bottom) { // | // --+ // if (left == State.YES && top == State.SHIFT) { return new int[] {LEFT|BOTTOM, TOP|BOTTOM, TOP|RIGHT, TOP|LEFT};// "v^>^"; } if (left == State.SHIFT && top == State.YES) { return new int[] {TOP|RIGHT, LEFT|BOTTOM, LEFT|RIGHT, LEFT|TOP}; //"^<>^"; } // // --+ // | if (left == State.YES && bottom == State.YES) { return new int[] {LEFT|RIGHT, LEFT|BOTTOM, RIGHT|BOTTOM, LEFT|TOP}; //">vv<"; } if (left == State.SHIFT && bottom == State.SHIFT) { return new int[] {RIGHT|BOTTOM, LEFT|BOTTOM, LEFT|TOP, TOP|BOTTOM}; //">v^v"; } // | // +-- // if (right == State.SHIFT && top == State.SHIFT) { return new int [] {RIGHT|BOTTOM,LEFT|TOP,TOP|RIGHT, LEFT|RIGHT}; //" v<>>"; } if (right == State.YES && top == State.YES) { return new int [] {TOP|BOTTOM,RIGHT|BOTTOM,TOP|RIGHT,TOP|LEFT}; //"v>>^"; } // // +-- // | if (right == State.YES && bottom == State.SHIFT) { return new int [] {RIGHT|BOTTOM, LEFT|RIGHT, TOP|RIGHT, LEFT|BOTTOM}; //"v<>v"; } if (right == State.SHIFT && bottom == State.YES) { return new int [] {RIGHT|BOTTOM, LEFT|BOTTOM, TOP|BOTTOM, RIGHT|TOP}; //"v<v^"; } // // --+-- // if (right == State.YES && left == State.YES) { return new int [] {LEFT|BOTTOM, RIGHT|BOTTOM, TOP|RIGHT, LEFT|TOP}; } if (right == State.SHIFT && left == State.SHIFT) { return new int [] {RIGHT|BOTTOM, LEFT|BOTTOM, LEFT|TOP, RIGHT|TOP}; } // | // + // | if (top == State.YES && bottom == State.YES) { return new int [] {TOP|RIGHT, LEFT|BOTTOM, BOTTOM|RIGHT, LEFT|TOP}; } if (top == State.SHIFT && bottom == State.SHIFT) { return new int [] {RIGHT|BOTTOM, LEFT|TOP, RIGHT|TOP, LEFT|BOTTOM}; } // // +-- // if (right == State.YES && bottom == State.NO && left == State.NO && top == State.NO) { return new int [] {BOTTOM, RIGHT|BOTTOM, TOP|RIGHT, LEFT|TOP}; } if (right == State.SHIFT && bottom == State.NO && left == State.NO && top == State.NO) { return new int [] {RIGHT|BOTTOM, LEFT|BOTTOM, TOP, RIGHT|TOP}; } // | // + // if (top == State.YES && bottom == State.NO && left == State.NO && right == State.NO) { return new int [] {TOP|RIGHT, LEFT|BOTTOM, RIGHT, LEFT|TOP}; } if (top == State.SHIFT && bottom == State.NO && left == State.NO && right == State.NO) { return new int [] {BOTTOM|RIGHT, LEFT|TOP, TOP|RIGHT, LEFT}; } // // + // | if (bottom == State.YES && top == State.NO && left == State.NO && right == State.NO) { return new int [] {RIGHT, LEFT|BOTTOM, BOTTOM|RIGHT, LEFT|TOP}; } if (bottom == State.SHIFT && top == State.NO && left == State.NO && right == State.NO) { return new int [] {BOTTOM|RIGHT, LEFT, TOP|RIGHT, LEFT|BOTTOM}; } // // --+ // if (left == State.YES && bottom == State.NO && right == State.NO && top == State.NO) { return new int [] {LEFT|BOTTOM, BOTTOM, TOP|RIGHT, LEFT|TOP}; } if (left == State.SHIFT && bottom == State.NO && right == State.NO && top == State.NO) { return new int [] {BOTTOM|RIGHT, LEFT|BOTTOM, LEFT|TOP, TOP}; } return null; } } ``` ]
[Question] [ A "rhyme scheme" is a string of letters `a` to `z`, such that the first occurrences of the characters are in ascending order (without gaps), starting from `a`. For example (with first occurrences marked): ``` abccdbebdcfa ^^^ ^ ^ ^ ``` The number of rhyme schemes of length `N` is given by the *Bell numbers* `B(N)`. ([OEIS A000110](https://oeis.org/A000110)) ## The Challenge Your task is to implement an enumeration of these rhyme schemes, i.e. a bijective mapping from integers to rhyme schemes. You're given a positive integer `N <= 26`, as well as a non-negative integer `0 <= i < B(N)`. Alternatively, you can use the range `1 <= i <= B(N)`. You should output a rhyme scheme of length `N`, such that every `i` yields a different string. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. You may use either lower or upper case letters (consistently). Your code must be able to handle any valid input in reasonable amount of time (e.g. **not more than a few hours** for `N = 26`, worst case `i`). This should allow solutions that scale exponentially with `N` (for small bases), even in slow languages but prohibit solutions that scale linearly with `i` (i.e. `B(N)`). In particular, that means you cannot just iterate through all valid rhyme schemes of length `N` until you've discard `i` schemes. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Examples The exact assignment of the `i` to schemes (i.e. the order of the schemes for a given `N`) is up to you. But say you chose lexicographical ordering, your solution should correspond to the following table (with `-` denoting invalid input): ``` N\i 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 a - - - - - - - - - - - - - - 2 aa ab - - - - - - - - - - - - - 3 aaa aab aba abb abc - - - - - - - - - - 4 aaaa aaab aaba aabb aabc abaa abab abac abba abbb abbc abca abcb abcc abcd ``` [Here is a short CJam script](http://cjam.aditsu.net/#code=%22a%22%5D%7B%7B_%3Ae%3E))%2C97%3E%5Cf%7B%5C%2B%7D%7D%25%3A~%7Dri(*'%2C*&input=6) which generates all valid rhyme schemes for any given length (but don't try more than 10 or you'll wait a while). ### Related Challenges * [Translate a Glypho program](https://codegolf.stackexchange.com/q/70657/8478) * [Check if words are isomorphs](https://codegolf.stackexchange.com/q/50472/8478) [Answer] # Python 2, 153 ``` u=[1]*999;i=60;exec"u[i]=i%30*u[i-30]+u[i-29];i+=1;"*900 def x(l,n,a=0):m=u[30*l+a];c=n>=a*m;return'.'*l and chr(65+min(n/m,a))+x(l-1,[n%m,n-m*a][c],a+c) ``` It uses alphabetical order and 0-based indexing. Let `l` denote the length of a suffix of the letters and `a` denote the number of distinct letters that were used in the preceding part. Then a function `p(l,a)` that calculates the number of ways to select the remaining letters could be 40 bytes: ``` p=lambda l,a:l<1or a*p(l-1,a)+p(l-1,a+1) ``` However, this is too slow for the challenge, so instead the necessary values are precalculated and stored in the `u` array. At each stage of the calculation, if the next letter is the one of the `a` already used, the *n = k \* p(l - 1, a) + n'* where *k* is the 0-indexed letter of the alphabet and *n'* is the value of `n` for the next function call, which contains the information about the remaining letters. If a new letter is used, then *n = a \* p(l - 1, a) + n'*. [Answer] # Haskell (GHC 7.10), 150 bytes ``` s=(1,\_->[]):s k!((y,b):l@((x,a):_))|let h i|i<x=k:a i|(p,q)<-divMod(i-x)y=p:b q=(x+k*y,h):(k+1)!l n#i=(['a'..]!!).fromEnum<$>snd(iterate(0!)s!!n!!0)i ``` The operator `n # i` computes the `i`th (zero-indexed) rhyme scheme of length `n`. It runs in O(nยฒ) (big-integer) operations, taking advantage of Haskellโ€™s lazy infinite lists for automatic memoization. Sample runs: ``` *Main> 26 # 0 "abcdefghijklmnopqrstuvwxyz" *Main> 26 # 1 "abcdefghijklmnopqrstuvwxya" *Main> 26 # 2 "abcdefghijklmnopqrstuvwxyb" *Main> 26 # 49631246523618756271 "aaaaaaaaaaaaaaaaaaaaaaaabb" *Main> 26 # 49631246523618756272 "aaaaaaaaaaaaaaaaaaaaaaaaab" *Main> 26 # 49631246523618756273 "aaaaaaaaaaaaaaaaaaaaaaaaaa" *Main> [1 # i | i <- [0..0]] ["a"] *Main> [2 # i | i <- [0..1]] ["ab","aa"] *Main> [3 # i | i <- [0..4]] ["abc","aba","abb","aab","aaa"] *Main> [4 # i | i <- [0..14]] ["abcd","abca","abcb","abcc","abac","abaa","abab","abbc","abba","abbb","aabc","aaba","aabb","aaab","aaaa"] ``` (If the maximum N were 25 instead of 26, the `.fromEnum` could be removed, because B(25) fits in a 64-bit `Int`.) [Answer] ## ~~Perl 257 + 1 (-p flag) = 258~~ ## Perl 182 + 10 (-pMbignum flags) = 192 ``` ($n,$i)=split;@m=[@a=(1)x($n+1)];while($a[2]){push@m,[@a=map{$a[$_]*$_+$a[$_+1]}0..$#a-1]}$_='';$y=1;while($w=pop@m){$c=int($i/($v=$$w[$y]));$c=$y++if($c>=$y);$i-=$c*$v;$_.=chr$c+65} ``` Thanks to [dev-nul](https://codegolf.stackexchange.com/users/48657/dev-null) for saving many bytes! I've now rewritten it based on what I learnt from doing the CJam version. Calculates the rhyme in ascending alphabetical order, 0 indexed. Two parts: Part 1 is ~~128~~ 90 bytes and calculates a matrix for Part 2. Part 2 is ~~129~~ 92 bytes and does some simple maths to calculate each letter. ~~If I could get rid of the matrix and replace it with two simple numbers, I could calculate a single path through the matrix for each number and save a lot of bytes!~~ Apparently, that idea doesn't work! ~~Unfortunately, it doesn't output the right rhymes for values of `i` higher than 9007199254740992, but it works beautifully for low values!~~ ~~I've added the Bignum library at a cost of 11 bytes.~~ It's run from the command line with `perl -pMbignum bell-rhyme.pl`. `-pMbignum` = 10 bytes. It's also very fast for any input value. [Answer] ## CJam, ~~68~~ 66 bytes ``` r~:W)1a*{__(;\);_,,.*.+}W(*r~{X@\=_2$\/:CX<!{X:C):X;}&C*-C'a+o}W*; ``` [Try it online.](http://cjam.aditsu.net/#code=r~%3AW%291a*%7B__(%3B%5C)%3B_%2C%2C.*.%2B%7DW(*r~%7BX%40%5C%3D_2%24%5C%2F%3ACX%3C!%7BX%3AC)%3AX%3B%7D%26C*-C'a%2Bo%7DW*%3B&input=26%2049631246523618756273) This is my first CJam program. It started life as a port of my Perl solution and was initially over 130 bytes long. Further golfing suggestions are welcome. As with my Perl program, it is in two parts. ``` Part 1: r~:W | Read the first input (n) and store it in W )1a* | Create an array of n+1 1s { }W(* | Repeat n-1 times: __ | Duplicate array twice (;\); | Remove first element of 1st array. Swap | arrays. Remove last element of 2nd array _,, | Duplicate array. Count items. Create range .*.+ | Multiply arrays. Add 1st array to result Part 2: r~ | Read the second input (i) { }W* | Repeat n times: X@ | Push y (initially 1). Bring item 2 (last array) to top \= | Swap top two items. Pop array[y] (v) _2$ | Duplicate v. Copy item 2 (i) to top \/:CX | Swap i & v. i/v. Store in C (c). Push y <!{ }& | If !(i/v < c): X:C):X; | c = y. ++y (store in X) C*-C'a+o | i -= c * v. Push y. Push "a". Add c. Print ; | Discard top item (integer 0) ``` To debug the arrays created by Part 1 add `]_`o~` between Parts 1 & 2. If n is `5`, the arrays will look like this: `[[1 1 1 1 1 1] [1 2 3 4 5] [2 5 10 17] [5 15 37] [15 52]]`. The 0 indices of each array aren't used, they just make it easier by not having to calculate offsets. The arrays are calculated like this: ``` [2 5 10 17] [2 5 10 17] [2 5 10 17] | Duplicate twice [2 5 10 17] [2 5 10 17] [5 10 17] | Discard first item of array [2 5 10 17] [5 10 17] [2 5 10 17] | Swap last two arrays [2 5 10 17] [5 10 17] [2 5 10] | Discard last item of array [2 5 10 17] [5 10 17] [2 5 10] [2 5 10] | Duplicate array [2 5 10 17] [5 10 17] [2 5 10] 3 | Count items in array [2 5 10 17] [5 10 17] [2 5 10] [0 1 2] | Integer to range 0 - n-1 [2 5 10 17] [5 10 17] [0 5 20] | Multiply arrays [2*0 5*1 10*2] [2 5 10 17] [5 15 37] | Add arrays [5+0 10+5 17+20] ``` It keeps a copy of the old array while calculating the next one. The arrays are read and discarded in reverse order by Part 2. [Answer] # Oracle SQL 11.2, ~~412~~ ~~284~~ 283 bytes ``` WITH a AS(SELECT CHR(96+LEVEL)d,LEVEL b FROM DUAL CONNECT BY LEVEL<=:i),v(s,c,n)AS(SELECT d,1,1 FROM a WHERE b=1 UNION ALL SELECT s||d,b,LENGTH(REGEXP_REPLACE(s||d,'([a-z])\1+','\1'))FROM v,a WHERE(b<=n OR b=c+1)AND LENGTH(s)<:n)SELECT s FROM v WHERE:n=LENGTH(s)AND:i<=:n ORDER BY 1; ``` Unfortunately it only runs up to a length of 8. Any greater value results in : ORA-01489: result of string concatenation is too long Un-golfed ``` WITH a AS(SELECT CHR(96+LEVEL)d,LEVEL b FROM DUAL CONNECT BY LEVEL<=:i), v(s,c,n) AS ( SELECT d,1,1 FROM a WHERE b=1 UNION ALL SELECT s||d,b,LENGTH(REGEXP_REPLACE(s||d,'([a-z])\1+','\1')) FROM v,a WHERE (b<=n OR b=c+1) AND LENGTH(s)<:n ) SELECT s FROM v WHERE LENGTH(s)=:n AND :i<=:n ORDER BY 1; ``` The a view generate the :i letters in column a and their value in b. The recursive view v takes the string being constructed as parameter v, the value of the last letter used in c and the value of the greatest letter used in n. The n parameter is equal to the length of the string without any duplicate letter, thats what the regex is for. A letter is valid if its value is <= the value of the greatest letter already used or it is the next letter to be used. Somehow the query needs the LENGTH(s)<:n part to run, I must be missing something in how the query works. The main SELECT takes care of filtering out the invalid inputs and the shorter strings built before the length targeted is reached. 412 bytes version ``` WITH a AS(SELECT * FROM(SELECT d,b,ROW_NUMBER()OVER(PARTITION BY b ORDER BY d)l FROM(SELECT CHR(64+DECODE(MOD(LEVEL,:i),0,:i,MOD(LEVEL,:i)))d,CEIL(LEVEL/:i)b FROM DUAL CONNECT BY LEVEL<=:i*:n))WHERE l<=b),v(s,c,p)AS(SELECT d,1,l FROM a WHERE b=1 UNION ALL SELECT s||d,c+1,l FROM v,a WHERE c+1=b AND(l<=LENGTH(REGEXP_REPLACE(s,'([A-Z])\1+','\1'))OR l=p+1))SELECT s FROM v WHERE LENGTH(s)=:n AND :i<=:n ORDER BY 1; ``` Do not try the 412 bytes query with 26. It puts the database in restricted mode, at least on my xe version running in a docker container on a macbook. I could try on the exadata at work, but sadly I still need to work for a living. [Answer] ## Mathematica, 136 bytes ``` (For[j=2^#-1;t=#2,c=1;m=0;x=t;r=If[#>0,++m,c*=m;d=x~Mod~m+1;x=โŒŠx/mโŒ‹;d]&/@j~IntegerDigits~2;;c<=t,t-=c;--j];FromCharacterCode[r+64])& ``` For completeness, here is my golfed reference implementation. As opposed to the existing answers this does not run in polynomial time (it's exponential in `N` with base 2) but does meet the time constraint (the worst case would still run in under half an hour). The idea is this: * For each rhyme scheme we can identify the positions where the maximum character so far increases: ``` ABCDEFGHDIJDEKBBIJEIKHDFII ^^^^^^^^ ^^ ^ ``` We can treat those markings as a binary number which makes it easy to iterate over all such structures. We need to iterate from 2n-1 to 2n (or the other way round) which is where the exponential time complexity comes from. * For each such structure it's easy to determine how many such strings there are: only the gaps between the markings can be freely chosen, and the maximum in front of the gap tells us how many different characters are valid in each position. This is a simple product. If this number is smaller than `i`, we subtract it from `i`. Otherwise, we've found the structure of the requested rhyme scheme. * To enumerate the schemes in the given structure, we simply represent `i` (or what remains of it) as a mixed-base number, where the weights of the digits are determined by the number of allowed characters in the remaining positions. I wonder if this would allow for a shorter solution in some of the other languages that were submitted since it doesn't require any memoisation or precomputation. ]
[Question] [ Given an integer n โ‰ฅ 0 , output it in a non-positional base-3 notation, using digits `139ABCDEโ€ฆ` and a 1-character separator. Every digit is a consecutive power of 3 and the digits on the left side of the separator are negated, e.g. **A931|B** โ†’ 81โˆ’(1+3+9+27) โ†’ **41**. A digit may appear only once. Rigorously, let the value of a digit be: * its value if the digit is 1, 3 or 9 * 27 if the digit is `A` * 3 times the value of the digit right before it for `B`..`Z` Your output should satisfy **sum(value of digits to the right of `|`) - sum(value of digits to the left of `|`) == input** . ### Examples ``` input output ---------------- 0 | 1 |1 7 3|91 730 |D1 9999 FEDC|GA9 ``` You may use a different **non-space** character as a separator. You are also allowed to have no separator, in which case the largest digit starts the positive sequence. You donโ€™t need to handle anything larger than 232โˆ’1 (`PMIGDCBA9|RQNLH3`). You may write a full program or function, and input and output may be provided on any of the usual channels. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shorter your answer the better! [Answer] # Java 10, ~~120~~ ~~113~~ ~~112~~ ~~109~~ ~~107~~ ~~102~~ 92 bytes ``` n->{var r="|";for(var c='1';n++>0;c+=c>64?1:c*4%22%9,n/=3)r=n%3<1?c+r:n%3>1?r+c:r;return r;} ``` -3 bytes by using part of the trick of [*@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/160550/52210), changing `i=0` and `i++<1?49:i<3?51:i<4?57:i+61` to `i=4` and `++i>9?i+55:i>8?57:++i+43`. -6 bytes thanks to *@Arnauld* directly, by getting rid of `i`. -10 bytes thanks to *@ceilingcat*. Order of output: Highest-to-lowest, `|`-delimiter, lowest-to-highest. **Explanation:** [Try it online.](https://tio.run/##hZDBTsMwDIbvPIU1qVpDWFnWCbSGtE/ALhwRh@B1KKNzJzethEafvWSs16mWLfn3d/h/@WA7uzjsvgesbNPAq3V0vgNw5EveWyxhe5EAb54dfQHGgQAJHY59mNCNt94hbIHAwECL/NxZBjaz35ne1xxfFJq5mmuSMl9qlAbzp3WhMrxfR6tVtHmgR5MKNhSlL6pAyVnYclWwxIw1l75lAtb9oK@Op/azCo6jcVe7HRxD7via8f3DijHzT@PLY1K3PjkF4iuKKcF4Kf7j3@Rqgj9P8XTKYRNKjD/shz8) ``` n->{ // Method with integer parameter and String return-type var r="|"; // Result-String, starting at the delimiter "|" for(var c='1'; // Character, starting at '1' n++>0 // Loop as long as `n` is larger than 0 // Increasing it by 1 with `n++` at the start of every iteration ; // After every iteration: c+= // Change character `c` to: c>64? // If the current `c` is an uppercase letter: 1 // Simply go to the next letter using `c+=1` : // Else: c*4%22%9, // Change '1' to '3', '3' to '9', or '9' to 'A' n/=3) // Integer-divide `n` by 3 r= // Change the result to: n%3<1? // If `n` modulo-3 is 0: c+r // Prepend the character to the result :n%3>1? // Else-if `n` modulo-3 is 2: r+c // Append the character to the result : // Else (`n` modulo-3 is 1): r; // Leave `r` unchanged return r;} // Return the result-String ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~103~~ ~~99~~ 91 bytes 4 bytes thanks to Lynn. 8 bytes thanks to ovs. ``` def f(n,s="|",b=0):c=('139'+chr(b+62)*b)[b];return n and f(-~n//3,[s,s+c,c+s][n%3],b+1)or s ``` [Try it online!](https://tio.run/##DctBCoMwEADArwShmO1usTYg2JKXhByaaLCXVTbpQZB@PXXus@1lWdnUOs1JJc2UbXM0FOwdntHqtjdji3ERHXB4wDWAC/4lc/kKK1Zvns50@3HXGXKZMkaKmL3ji/EUsIdVVK6bfLjopMcTQP0D "Python 3 โ€“ Try It Online") Credits to [xnor](https://codegolf.stackexchange.com/a/41762/48934) for the logic. [Answer] # JavaScript (ES6), ~~82~~ ~~80~~ 79 bytes Outputs in lowercase, which should hopefully be fine. ``` f=(n,s=(k=4,'|'),c=++k>8?k.toString(36):++k-5)=>n?f(++n/3|0,[c+s,s,s+c][n%3]):s ``` [Try it online!](https://tio.run/##ZctLDoMgFIXheffRyPWitWJfJugiOjQODBVjMZdGSEfunTptOP/sS857@A5OrfPHZ2RfYwhaMuJOMiMrnmwJcCURTXNvTe7t068zTUxcod4xu4BsqNUMkU5iK3in0PE9VH1HR9FD7YKy5Owy5oudmGYFwOFfzpHcYhHx77EvwjJNRQkQfg "JavaScript (Node.js) โ€“ Try It Online") Similar to [Leaky "Ninja Master" Nun's answer](https://codegolf.stackexchange.com/a/160548/58563) and also based on [xnor's answer](https://codegolf.stackexchange.com/a/41762/58563). ### Digit conversion We start with **k = 4**. While **k** is less than **9**, we increment it twice at each iteration and subtract **5**. After that, we increment it only once and convert it to base-36. ``` k | ++k > 8 | k.toString(36) | ++k - 5 | result -----+---------------+----------------+----------+-------- 4 | k=5 -> false | | k=6 -> 1 | 1 6 | k=7 -> false | | k=8 -> 3 | 3 8 | k=9 -> true | '9' | | '9' 9 | k=10 -> true | 'a' | | 'a' 10 | k=11 -> true | 'b' | | 'b' ... | ... | ... | ... | ... ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` โ€˜:3ฦŠโนรยกโ€˜%3แบนรโ‚ฌ0,2แป‹139D;ร˜AยคY ``` [Try it online!](https://tio.run/##y0rNyan8//9Rwwwr42Ndjxp3Hp5waCGQp2r8cBeQ/ahpjYGO0cPd3YbGli7Wh2c4HloS@f//fxMjSxNLM3MjSzMA "Jelly โ€“ Try It Online") Use a newline as the separator. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 80 bytes ``` {map({|(1,3,9,|('A'..'Z'))[grep :k,*%3==$^v,($_,-+^*div 3...0)]},1,2).join.flip} ``` [Try it online!](https://tio.run/##DYpLCsIwFACv8hbVfHw@mgSUKll4DcVKwUairQ0RCqXt2WOGWcxiQhu7Q@on2Dqwae6bwOeFKzRY4cLZhRGxKxPi9optgNMH5cZYW9Qj8uKB@10tn34EQ0SluK@oUAt6D/5LrvNhTb9mApdPAW6IUCIohGPW5KwyCFpKo8/pDw "Perl 6 โ€“ Try It Online") No separator. Based on [xnor's answer](https://codegolf.stackexchange.com/a/41762/58563). [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~30~~ 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ยฃโ””โ‰คโ˜ปโ•˜pรฟโ•–โ•กA[รด%รฆฯ„โŒ}โ–บยบรดรŸHl4โŒกฯ€%^ ``` [Run and debug it](https://staxlang.xyz/#p=9cc0f302d47098b7b5415b932591e7a97d10a793e1486c34f5e3255e20&i=0%0A1%0A7%0A730%0A9999&a=1&m=2) Port of my Stax answer in [Balanced Ternary Converter](https://codegolf.stackexchange.com/questions/41752/balanced-ternary-converter). ## Explanation Uses the unpacked version to explain. ``` 139$VA+cz{;3%+,^3/~;wY1|I@'|ay2|I@L 139$VA+c "139AB...Z", make a copy z Empty array to store the digits { w Do the following until 0. ;3%+ Append `b%3` to the digits Originally, `b` is the input ,^3/ `b=(b+1)/3` ~; Make a copy of `b` which is used as the condition for the loop Y Save array of digits in `y` for later use 1|I Find index of 1's @ Find the characters in "139AB...Z" corresponding to those indices '| A bar ay2|I@ Do the same for 2's L Join the two strings and the bar and implicit output ``` [Answer] # [J](http://jsoftware.com/), ~~69 64~~ 58 bytes ``` ('931',~u:90-i.26){~0(>,&I.<)(29$3)((+1&|.-3&*)]-*)^:_@#:] ``` [Try it online!](https://tio.run/##y/r/P81WT0FD3dLYUF2nrtTK0kA3U8/ITLO6zkDDTkfNU89GU8PIUsVYU0ND21CtRk/XWE1LM1ZXSzPOKt5B2Sr2f2pyRr5DmkJqWWpRpYKxgqGpgoGCubGBgiUQ6BjFGRv9BwA) [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~71~~ 69 bytes uses no separator. The negative and positive parts are in "roman order" (largest digit first) ``` #!/usr/bin/perl -p $n=$_}{s/@{[$n++%3]}\K/]/,$n/=3,y/?-]/>-]/for($_=21)x31;y/>?@12/139/d ``` [Try it online!](https://tio.run/##K0gtyjH9/18lz1Ylvra6WN@hOlolT1tb1Ti2NsZbP1ZfRyVP39ZYp1LfXjdW3w6I0/KLNFTibY0MNSuMDa0r9e3sHQyN9A2NLfVT/v83MbI0sTQzN7I0@5dfUJKZn1f8X7fgv66vqZ6hgZ4hAA "Perl 5 โ€“ Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~87~~ ~~84~~ 82 bytes Saved 2 bytes thanks to @benj2240. ``` ->n,s=[?1,?3,?9,*?A..?Z],r=[""]*3{r[-m=n%3]+=s.shift n=n/3+m/2 n>0?redo:r[1,2]*?|} ``` [Try it online!](https://tio.run/##DcFLDoMgEADQvacgmG50xA8LY5Nh0muUsOhHYxfSBnDRIGenfc/t929eMDfKgkdNPZAEmqCiixB0NeBQc24qGZ1uNrQnaWr0wq@vJRQWbSvrrR0Kqzpy8/N9drqHwVR0pKw76GGEUXYw/Rkx3x4ri0c42GcPnvEyhsRQsTIuOpjEU/4B "Ruby โ€“ Try It Online") [Answer] # [J](http://jsoftware.com/), 129 bytes ``` f=:3 :0 a=.'139',u:65+i.26 s=.'|'while.y>0 do.if.1=c=.3|y do.s=.s,{.a end.y=.<.y%3 if.c=2 do.s=.s,~{.a y=.1+y end.a=.}.a end.s ) ``` [Try it online!](https://tio.run/##PY3RCsIwDEXf8xV9kSIbYV1xsmL8l9G1rCLuoQwpTn@9ZjKbp5PcE@4tZ09GC9PAQCiV7mW9mO5UBWw7iHxa5XMKd4fp2ohxxuBRkSXUa9pWNmL9wkG4x4iJ8ILpoIElS23JP5sAnKoq/USueu8/EY7Z2WkWXjSwg/rDuYAuYc@Tvw "J โ€“ Try It Online") Too lengthy, especially for a J program... ## Explanation: ``` f =: 3 : 0 a =. '139',u:65+i.26 NB. a list '139ABC...Z' s =. '|' NB. initialize the list for the result while. y>0 do. NB. while the number is greater than 0 c =. 3|y NB. find the remainder (the number modulo 3) y =. <.y%3 NB. divide the number by 3 if. c = 1 do. NB. if the remainder equals 1 s =. s,{.a NB. Append the current power of 3 to the result end. if. c = 2 do. NB. if the remainder equals 2 s =. s,~{.a NB. prepends the result with the current power of 3 y =. 1+y NB. and increase the number with 1 end. a =. }.a NB. next power of 3 end. s NB. return the result ) ``` [Answer] # C, `int`: ~~138~~ 123 bytes, `long`: ~~152~~ 131 bytes I have created two versions of this, as the challenges' limit of a working max input of `0x100000000` seemed a bit odd. One version works with 32 bit integers (which fails the limit for obvious reasons), the other version works with 64 bits (which goes way beyond the given limit, at the cost of ~~14~~ 8 extra bytes). 32 bit version: ``` char b[22],*r=b;f(v,l)char*l;{v%3>1?*r++=*l,v++:0;v&&f(v/3,l+1);v%3?*r++=*l:0;}g(v){f(v,"139ABCDEFGHIJKLMNOPQR");*r=0;r=b;} ``` 64 bit version: ``` char b[22],*r=b;f(long v,char*l){v%3>1?*r++=*l,v++:0;v&&f(v/3,l+1);v%3?*r++=*l:0;}g(long v){f(v,"139ABCDEFGHIJKLMNOPQR");*r=0;r=b;} ``` This is identical except that it declares the integer variable to be `long` (which is 64 bits on linux). The ungolfed `long` version: ``` char buffer[22],*result=buffer; f(long value,char*letter){ if(value%3>1){ *result++=*letter,value++; } if(value){ f(value/3,letter+1); } if(value%3){ *result++=*letter; } } g(long value){ f(value,"139ABCDEFGHIJKLMNOPQR"); *result=0; result=buffer; } ``` As you can see, this works by recursive decent: If the remainder is 1, the respective character is appended to the output string after the recursive call. If the remainder is 2, the output is performed before the recursing. In this case, I also increment the value by one to handle the negative digit correctly. This has the added benefit of changing the remainder to zero, allowing me to use `value%3` as the condition for the post-recursion if. The result of the conversion is placed into the global buffer. The `g()` wrapper has the job of zero terminating the resulting string correctly, and to reset the `result` pointer to its start (which is also how `g()` "returns" the result). Test the `long` version with this code: ``` #include <stdio.h> char b[22],*r=b;f(long v,char*l){v%3>1?*r++=*l,v++:0;v&&f(v/3,l+1);v%3?*r++=*l:0;}g(long v){f(v,"139ABCDEFGHIJKLMNOPQR");*r=0;r=b;} void printConversion(long value) { g(value); printf("%ld: %s\n", value, r); } int main() { for(long i = 0; i <= 40; i++) { printConversion(i); } printConversion(0x7fffffff); printConversion(0xffffffffu); printConversion(0x100000000); } ``` --- Possible further, but destructive golfing: * -4 bytes: make the function a one-shot by removing the pointer reset in `g()`. * -5 bytes: force the caller to perform the string termination, returning the string without termination in `buffer`, and the end of the string in `result`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ๏ผฎฮธ๏ผฆยณโŠžฯ…โŸฆโŸง๏ผฆโบ139ฮฑยซโŠžยงฯ…ฮธฮนโ‰”รทโŠ•ฮธยณฮธยป๏ผฆยฒยซร—|ฮนโ†‘โŠŸฯ… ``` [Try it online!](https://tio.run/##NY0/D4IwEEdn@RQXpmtSB2VCJhIXFsOgk3FAOKUJFOgfYqJ89tpKvOmXl5d3dVupeqg65wo5WnOy/Z0UTiyLHoMCTBiUVrdoOVxvf1h2VmO8S9KYQ8UYvKPNT8pNIRt6BXliHIT3N7nW4imxkOYoZtGQX7WinqShBoOVsGBn0bK292tOCWnwLHryjz5xaIXYig@XkUM5jGgDXJxL/bnt3H0B "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฎฮธ ``` Input the value. ``` ๏ผฆยณโŠžฯ…โŸฆโŸง ``` Push three empty lists to the predefined empty list. ``` ๏ผฆโบ139ฮฑยซ ``` Loop through the characters `139` and the uppercase alphabet. ``` โŠžยงฯ…ฮธฮน ``` Cyclically index the list of lists with the value and push the current character to it. ``` โ‰”รทโŠ•ฮธยณฮธยป ``` Divide the value by 3 but round it by adding 1 first. ``` ๏ผฆยฒยซร—|ฮน ``` Loop twice. The second time, print a `|`. ``` โ†‘โŠŸฯ… ``` Each loop we pop the last entry from the list; the first time this gives us the entries that had a remainder of `2` (which corresponds to a balanced ternary digit of `-1`), while the second time this gives us the entries corresponding to a balanced ternary digit of `1`. The resulting array would normally print vertically, but rotating the print direction upwards cancels that out. [Answer] # C# .NET, ~~103~~ 100 bytes ``` n=>{var r="|";for(var c='1';n++>0;c+=(char)(c>64?1:c*4%22%9),n/=3)r=n%3<1?c+r:n%3>1?r+c:r;return r;} ``` -3 bytes thanks to *@ceilingcat*. Port of [my Java 10 answer](https://codegolf.stackexchange.com/a/160563/52210). If a direct port (except for `n->` to `n=>`) would have been possible, I would have edited my Java answer with this polyglot. Unfortunately however, having `c=49` isn't possible in C#, nor the `c+=` without `(char)` cast, hence this loose ported answer. [Try it online.](https://tio.run/##jc6xasMwEAbg3U9xBEykKk2jOLTEiuTB0KmZOnQWVyUVpGc4KYGS@tldhy7d6pvuPz74D9M9dhwGPPmUYH8tAFL2OSJcuvgOex9JyNsV4PUr5fC5fD4T7iLlxQg50tFBC3Yg664Xz8B29j0zh47FLaGd67khpdzKoLICPzxLge5x0@ga7zblel1u5YIebCXZUlntdIOK63FzumGFNRsO@cwEbPrBFH8faTtK3Sks3zjm8BIpiFaspDT/GT3BPE0x1ZS27Ti/rC/64Qc) [Answer] # [Perl 5](https://www.perl.org/), ~~92~~ 89 bytes Inspired by the java and python answers. ``` sub n{($n,$r,$c,@a)=(@_,'|',1,3,9,'A'..'Z');$n?n(int++$n/3,($c.$r,$r,$r.$c)[$n%3],@a):$r} ``` [Try it online!](https://tio.run/##FYxBCsIwEEX3nmIoI0naIbYNRWoQ6zUUKTVUEGSUxAqinj2mj7d4m/8fo781MYbpDPyRyISe0FE3qK3sesq@GVVkqCWxF1qLg1AWecfyys@iQF4Zkuj0PJrV6NQReWlO88MG/S9OYYRXo6vSLsLwBpbYK7jcPZQEFcE6aVK2CYI6z01t4x8 "Perl 5 โ€“ Try It Online") With some white space: ``` sub n { ($n, $r, $c, @_) = (@_, "|", 1, 3, 9, 'A' .. 'Z'); $n ? n( int++$n/3, ($c.$r, $r, $r.$c)[$n%3], @_) : $r } ``` [Answer] # PHP, 73 bytes ``` for(;0|$n=&$argn;$n/=3)${$n++%3}.=_139[++$i]?:chr(61+$i);echo${2},_,${1}; ``` ## port of [xnorยดs answer](https://codegolf.stackexchange.com/a/41762/58563), 53 bytes ``` for(;0|$n=&$argn;$n/=3)$s="0+-"[$n++%3].$s;echo$s??0; ``` Run as pipe with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/1b0dee6c43d3a8be99bec41701bf4114c9fa5af7). ]
[Question] [ For each row and then column of a matrix, we can add an extra entry with the sum of the last two entries in that row or column. For example with the following input matrix: ``` [ 1 1 1 ] [ 2 3 4 ] ``` The resulting matrix would be: ``` [ 1 1 1 2 ] [ 2 3 4 7 ] [ 3 4 5 9 ] ``` Given an input of an integer N and an [X,Y] matrix of size at least 2x2, perform the above expansion N times and output the result. The resulting matrix will always be of size [X+N,Y+N]. ### Examples: ``` Input: Output: 2, [ 0 0 ] [ 0 0 0 0 ] [ 0 0 ] [ 0 0 0 0 ] [ 0 0 0 0 ] [ 0 0 0 0 ] 3, [ 1 1 1 ] [ 1 1 1 2 3 5 ] [ 2 3 4 ] [ 2 3 4 7 11 18 ] [ 3 4 5 9 14 23 ] [ 5 7 9 16 25 41 ] [ 8 11 14 25 39 64 ] ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 13 ~~14~~ ~~15~~ ~~16~~ ~~20~~ ~~21~~ bytes ``` 2*:"!tP2:Y)sv ``` Thanks @Zgarb for removing 1 byte! [**Try it online!**](http://matl.tryitonline.net/#code=Mio6IiF0UDI6WSlzdg&input=MwpbMSAxIDE7IDIgMyA0XQ) ``` 2* % implicitly input number N and multiply by 2 : % create vector [1,2,...,2*N] " % for loop: do this 2*N times ! % transpose. Implicitly input matrix in the first iteration tP % duplicate and flip vertically 2: % vector [1,2] Y) % pick submatrix formed by the first two rows s % sum of each column v % append as a new row % end for % implicit display ``` [Answer] ## J, 19 bytes ``` (v"1@v=.,[+&{:}:)^: ``` This defines an adverb, which takes the number on its left, and produces a verb taking the matrix on its right. For the second example, it gives ``` 3 ((v"1@v=.,[+&{:}:)^:) 2 3 $ 1 1 1 2 3 4 1 1 1 2 3 5 2 3 4 7 11 18 3 4 5 9 14 23 5 7 9 16 25 41 8 11 14 25 39 64 ``` ## Explanation ``` (v"1@v=.,[+&{:}:)^: Left argument x, right argument y ( )^: Repeat x times: v=. Bind the following verb to v, and apply to y: [ }: y and y-without-last-item +&{: Sum of their last items , Append that to y (v automatically threads to rows) v"1@ then apply v to columns ``` [Answer] # K, 23 bytes ``` {x(2({x,+/-2#x}'+)/)/y} ``` In action: ``` {x(2({x,+/-2#x}'+)/)/y}[3;(1 1 1;2 3 4)] (1 1 1 2 3 5 2 3 4 7 11 18 3 4 5 9 14 23 5 7 9 16 25 41 8 11 14 25 39 64) ``` Try it [here](http://johnearnest.github.io/ok/index.html?run=%20%7Bx%282%28%7Bx%2C%2B%2F-2%23x%7D'%2B%29%2F%29%2Fy%7D%5B3%3B%281%201%201%3B2%203%204%29%5D). [Answer] # Jelly, ~~15~~ ~~13~~ 12 bytes *-1 byte by @Dennis* ``` แนซ-S;@"Z ร‡แธค}ยก ``` Like @LuisMendo's MATL answer, this transposes the array before doing the transformation along one axis. Therefore, we need to call the function 2\*n times. ``` แนซ-S;@"Z Helper link. Input: x (2D array) - Numeric literal: -1 แนซ Get x[-1:], i.e. last two rows in x S Sum ;@" Append each to x. " is 'zipWith'; @ switches argument order. Z Transpose the array. ร‡แธค}ยก Main link. Input: a, n ร‡ Call the last link on a แธค} 2n ยก times. ``` Try it [here](http://jelly.tryitonline.net/#code=4bmrLVM7QCJaCsOH4bikfcKh&input=&args=WzEsMSwxXSxbMiwzLDRd+Mw). [Answer] ## ES6, 134 bytes ``` (n,a)=>[...a.map(b=>[...b,...Array(n)].map(c=>(c<1/0?0:c=a+d,d=a,a=c))),...Array(n)].map(b=>(b?0:b=[...a].map((c,j)=>c+d[j]),d=a,a=b)) ``` Explanation: ``` (n,a)=> // arguments n is number to expand, a is original array [... a.map(b=> // for each row in a [...b,...Array(n)] // append n elements to the row .map(c=>(c<1/0?0:c=a+d,d=a,a=c))) // scan the elements and fill the new ones by summing the previous two ,...Array(n)] // append n rows .map(b=>(b?0:b=[...a].map((c,j)=>c+d[j]),d=a,a=b)) // scan the rows and fill the new rows by summing the previous two rows ``` [Answer] ## Haskell, 67 bytes ``` o%m=m++[o(+)(last m)$last$init m] (!!).iterate(map(id%).(zipWith%)) ``` Usage example: ``` *Main> ( (!!).iterate(map(id%).(zipWith%)) ) [[1,1,1],[2,3,4]] 3 [[1,1,1,2,3,5],[2,3,4,7,11,18],[3,4,5,9,14,23],[5,7,9,16,25,41],[8,11,14,25,39,64]] ``` How it works: ``` (!!).iterate( ... ) -- repeatedly apply ... to the first agrument and -- pick the iteration defined by the second arg (zipWith%) -- for one iteration add a new row and map(id%) -- then a new element at the end of each each row o%m -- add row or element at the end of a row resp. -- argument o is a "modify function" -- m the whole matrix or a row m++[ (last m)(last$init m)] -- take m and append the result of combining the -- last and 2nd last element of m o(+) -- with a modified version of (+) -- modification is none (aka. id) when adding an -- element to the end of a row and -- zipping elementwise (zipWith) when adding a row ``` [Answer] ## CJam, ~~17~~ 16 bytes ``` q~2*{~_2$.+]z}*p ``` Input format is the matrix first (as a CJam-style 2D array) and the number of iterations afterwards. [Test it here.](http://cjam.aditsu.net/#code=q~2*%7B~_2%24.%2B%5Dz%7D*p&input=%5B%5B%201%201%201%20%5D%20%5B%202%203%204%20%5D%5D%203) ### Explanation Turns out this is the same solution as everyone else's: ``` q~ e# Read and evaluate input. 2* e# Double the iteration count. { e# Run this block that many times... ~ e# Dump all rows on the stack. _ e# Copy the last row. 2$ e# Copy the penultimate row. .+ e# Vectorised addition. ] e# Wrap all rows in a new array. z e# Transpose such that the next iteration processes the other dimension. }* p e# Pretty-print. ``` [Answer] ## Seriously, 20 bytes ``` ,,ฯ„"โ”ฌ`;d@d@X+@q`M"ยฃn ``` Takes input the matrix (as a 2D list), then `N`. Outputs a 2D list. This version doesn't work on the online interpreter for some reason, but does work with [this pre-challenge commit](https://github.com/Mego/Seriously/tree/5a97f8b14b4cf38b5e21bd11fa29359a813ea01b). A version that works online, for 23 bytes: ``` ,ฯ„",โ”ฌ`;d@d@X+@q`M"nkฮฃยฃฦ’ ``` Takes input in the opposite order (`N`, then matrix). [Try it online!](http://seriously.tryitonline.net/#code=LM-EIizilKxgO2RAZEBYK0BxYE0ibmvOo8KjxpI&input=MwpbWzEsMSwxXSxbMiwzLDRdXQ) I will add an explanation after I sleep for a little while. Working around interpreter bugs is never fun. [Answer] # Pyth, ~~13~~ 12 bytes ``` u+Rs>2dCGyEQ ``` [Try it online.](https://pyth.herokuapp.com/?code=u%2BRs%3E2dCGyEQ&input=%5B%5B1%2C+1%2C+1%5D%2C+%5B2%2C+3%2C+4%5D%5D%0A3&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=u%2BRs%3E2dCGyEQ&test_suite=1&test_suite_input=%5B%5B1%2C+1%2C+1%5D%2C+%5B2%2C+3%2C+4%5D%5D%0A1%0A%5B%5B0%2C+0%5D%2C+%5B0%2C+0%5D%5D%0A2%0A%5B%5B1%2C+1%2C+1%5D%2C+%5B2%2C+3%2C+4%5D%5D%0A3&debug=0&input_size=2) Uses the same algorithm to most answers. Takes as input the matrix as a 2D array on the first line and `n` on the second line. ### Explanation ``` u yEQ do 2*N times, starting with input matrix: CG transpose +R append to each row: s sum of >2d last 2 elements of row ``` [Answer] # Matlab, 60 bytes I was first messing about with Matlab's fancy indexing methods (i.e., `A(end+1,:)=sum...`) before I figured that in this rare case, simple concatenation is actually cheaper in Matlab. Too bad I had to convert this into an actual function. Should work with Octave as well. ``` function A=f(A,n) for i=1:2*n A=[A;sum(A(end-1:end,:))]';end ``` I suppose this is a prime example of how **not** to make algorithms. For A=2x2, n=1000 this algorithm already takes 5 seconds on my laptop, n=2000 it's almost 50 seconds! (or approximately 30s if A is a `gpuArray` thanks to my trusty Quadro 1000M) [Answer] # Java, 2179 bytes Just Worked it out:- This code is on Java Language. ``` import java.util.Scanner; public class FebonnaciMatrix { static Scanner scan=new Scanner(System.in); public static void main(String[] args) { int x,y; System.out.println("For the Array to Work Upon:- "); System.out.println("Enter the Row:- "); int row=scan.nextInt(); System.out.println("Enter the Column:- "); int col=scan.nextInt(); int inpArr[][]=new int[row][col]; System.out.println("Enter the values"); inpArr=inpValues(row,col); System.out.println("The Input Array is:- "); display(inpArr,row,col); System.out.println("Input the Array size of Febonacci Array "); System.out.println("Enter the Row"); int frow=scan.nextInt(); System.out.println("Enter the Column"); int fcol=scan.nextInt(); int febArr[][]=new int[frow][fcol]; febArr=copyValue(inpArr,febArr,row,col); for(x=0;x<row;x++) { for(y=col;y<fcol;y++) febArr[x][y]=febArr[x][y-2]+febArr[x][y-1]; } for(x=row;x<frow;x++) { for(y=0;y<fcol;y++) febArr[x][y]=febArr[x-2][y]+febArr[x-1][y]; } System.out.println(); System.out.println("The Febonacci Array:-"); display(febArr,frow,fcol); } static void display(int[][] arr,int row,int col) { int x,y; for(x=0;x<row;x++) { for(y=0;y<col;y++) System.out.print(arr[x][y]+"\t"); System.out.println(); } } static int[][] inpValues(int row,int col) { int arr[][]=new int[row][col]; int x,y; for(x=0;x<row;x++) { for(y=0;y<col;y++) { System.out.print("Enter the value:- "); arr[x][y]=scan.nextInt(); } } return arr; } static int[][] copyValue(int[][] old, int[][] ne, int row,int col) { int x,y; for(x=0;x<row;x++) { for(y=0;y<col;y++) ne[x][y]=old[x][y]; } return ne; } } ``` [Answer] # Python, 103 ~~105~~ bytes ``` f=lambda n,L:f(n-1,[l+[sum(l[-2:])]for l in L])if n else L lambda n,L:zip(*f(n,map(list,zip(*f(n,L))))) ``` Anonymous function takes list of list and passes to recursive function `f`. Output is transposed and then passed to `f` again, then the output of the second go is re-transposed. Output is a list of tuples Saved two bytes thanks to [bakuriu](https://codegolf.stackexchange.com/users/5219/bakuriu) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 17 bytes ``` {โ‰โต,โŠข/2+/โต}โฃ2โฃโŽ•โŠขโŽ• ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/5XP@rtfNS7VedR1yJ9I219ILP2Ue9iIyAGKgQKAsn/QIX/07getU3UMFAw0AQTXEZc6upcEEFDBSDU1DBSMFYw0eQyBgA "APL (Dyalog Classic) โ€“ Try It Online") [Answer] # [Perl 6](http://perl6.org), ~~87ย 73~~ 71 bytes ``` ->\c,\m{for ^c {.[+*]=[+] .[*X-1,2]for m;m.push: [map {[+] m[*X-1,2;$_]},m[0].keys]};m} ->\c,\m{for ^c {.[+*]=[+] .[*X-1,2]for m;m[+*]=[m[*-2;*] ยป+ยซm[*-1]]};m} ->\c,\m{for ^c {.[+*]=[+] .[*X-1,2]for m;m[+*]=[m[*-2;*]Z+m[*-1;*]]};m} ``` ``` -> \c, \m { for ^c { # 0 ..^ c # each row .[+*] # new column at the end of row ($_) = [+] .[ * X- 1,2 ] # add up the last two entries in row ($_) for m; # for every row # too bad this was longer than the above code # m[*;+*]=map *+*,m[*;*-2,*-1] # each column m[ +* ] # add new row = [ # make it an Array rather than a List m[ *-2; * ] # the second to last row ยป+ยซ # added columnwise with m[ *-1 ] # the last row ] }; m # return the result } ``` ### Usage: ``` use v6.c; # give it a lexical name my &code = ->\c,\m{ โ€ฆ } my @return = code 3,[[1,1,1],[2,3,4]]; put '[ ', $_ยป.fmt('%2d'), ' ]' for @return; put ''; put @return.perl ~~ {S:g/' '//}; ``` ``` [ 1 1 1 2 3 5 ] [ 2 3 4 7 11 18 ] [ 3 4 5 9 14 23 ] [ 5 7 9 16 25 41 ] [ 8 11 14 25 39 64 ] [[1,1,1,2,3,5],[2,3,4,7,11,18],[3,4,5,9,14,23],[5,7,9,16,25,41],[8,11,14,25,39,64]] ``` ]
[Question] [ You have been chosen to make a program that creates some pretty ASCII [bar charts](https://en.wikipedia.org/wiki/Bar_chart). Here is the input format: ``` [List of words (they can have spaces)] [an integer >= 0] Bar 3 This is so cool 4 IDK-Why 6 ``` The input will have multiple lines in this format, each one representing one bar in the graph. The output format of a graph will be like this: ``` _ _ _ _ |_|_|_|_| | | | | | | | + [name of 4th bar] | | + [name of 3rd bar] | + [name of 2nd bar] + [name of 1st bar] ``` Here are some examples: ``` In: Cool 4 Kool 6 Out: _ | | _| | | | | | | | | | | |_|_| | | | + Kool + Cool In: Graph 5 Bar 3 Out: _ | | | |_ | | | | | | |_|_| | | | + Bar + Graph In: Very 4 Large 5 Bar 3 Graph 5 Out: _ _ _| | | | | | |_| | | | | | | | | | | | |_|_|_|_| | | | | | | | + Graph | | + Bar | + Large + Very In: Bars can be 0 0 Large-bars_are$nice2 6 average)(@#$ 3 neato 5 Out: _ | | _ | | | | | |_| | | | | | | | | | _|_|_|_| | | | | | | | + neato | | + average)(@#$ | + Large-bars_are$nice2 + Bars can be 0 ``` Functions or full programs are allowed. [Answer] # sh + awk + tac, 173 Mostly an `awk` script that prints the graph bottom up which is then reversed by `tac`. ``` awk '{n[NR]=$NF;$NF="";$0=p" + "$0;p=" |"p}1;END{for(print p;p~/\|/;print p (k>($0=0)?"|":""))for(i=k=p="";i<NR;p=p (j>0||k>0?"|":" ")(!k||$0?"_":" ")){j=k;k=n[++i]--}}'|tac ``` ### Description **awk, first part, executed for each input line** ``` { n[NR]=$NF; # store the value, here n[1]=0, n[2]=6, n[3]=3, n[4]=5 $NF=""; # remove the value from the label $0=p" + "$0; # add a prefix (initially empty) and a " + " in the front p=" |"p # grow the prefix for the next string }1; # implicitly print $0 ``` **Output** ``` + Bars can be 0 | + Large-bars_are$nice2 | | + average)(@#$ | | | + neato ``` **awk, second part, executed once in the end** ``` END{ for(print p;p~/\|/;print p (k>($0=0)?"|":"")) for(i=k=p="";i<NR;p=p (j>0||k>0?"|":" ")(!k||$0?"_":" ")) {j=k;k=n[++i]--}} ``` ungolfed: ``` END{ print p; # print the prefix again for(;p~/\|/;) # for each line, bottom up. no more "|" -> we're done { p=""; # string to be built i=k=0; # i: bar index, k: heigth of the previous bar for(;i<NR;) # for each bar, left to right { j=k; # store the previous bars heigth in j k=n[++i]--; # get the current bars remaining height and decrement it p=p (j>0||k>0?"|":" ")(!k||$0?"_":" "); # if the bar to the left or this one have some height remaining, draw a border in between them, else a space # if this bars remaining heigth is exactly 0, draw a top # if $0 is set, draw the bottom } print p (k>0?"|":""); # draw (or not) the rightmost border, finally print $0=0; # unset $0, only to detect first run } } ``` **Output** ``` | | | | # the prefix _|_|_|_| # the strings built by the nested loops | | | | | | | | | v | |_| | | | | | | | _ _ # no more "|" in the string, we're done ``` **tac reverses the lines** ``` _ | | _ | | | | | |_| | | | | | | | | | _|_|_|_| | | | | | | | + neato | | + average)(@#$ | + Large-bars_are$nice2 + Bars can be 0 ``` [Answer] # JavaScript (ES6), 270 ~~262 270 287~~ *Bug fix* added a missing row of '|' under the bars ``` l=>{t=p=o='';l=l.split` `.map(r=>([,b,c]=r.match(/(.*) (\d+)/),[' + '+b,+c>t?t=c:c]));for(++t;t--;o+=` `)l.map(x=>o+=x[1]<t?'y y':x[1]>t?t?'x x':'x_x':'y_y');return o.replace(/(yx)|(xy)|(xx?)/g,'|').replace(/y+/g,' ')+[...l,' '].map(x=>p+x[p+=' |',0]).reverse().join` `} ``` **Test** Test in Firefox, as Chrome does not support ES6 [Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) ``` F=l=>{ t=p=o='';l=l.split`\n`.map(r=>([,b,c]=r.match(/(.*) (\d+)/),[' + '+b,+c>t?t=c:c])); for(++t;t--;o+=`\n`)l.map(x=>o+=x[1]<t?'y y':x[1]>t?t?'x x':'x_x':'y_y'); return o.replace(/(yx)|(xy)|(xx?)/g,'|').replace(/y+/g,' ') +[...l,' '].map(x=>p+x[p+=' |',0]).reverse().join`\n` } function test() { var i=I.value O.textContent=F(i) } test() ``` ``` textarea { display:block; width:50%; height:5em} ``` ``` Input <textarea id=I>Bars can be 0 0 Large-bars_are$nice2 6 average)(@#$ 3 neato 5</textarea> <button onclick='test()'>go</button><br> Output <pre id=O></pre> ``` [Answer] # 421 bytes - Python 2 ``` import sys l=sys.stdin.read().split('\n') b=[(' '.join(x[:-1]),int(x[-1])) for x in map(str.split,l[:-1])] a=len(b) e=enumerate m=[' '*(a+1)+'|'*x[1] for i,x in e(b)]+[' '*(len(b)+1)+'|'*b[-1][1]] h=[' '*i+'+'+'|'*(a-i)+'_'+' '*(x[1]-1)+'_' for i,x in e(b)] c=m+h c[::2]=m c[1::2]=h c=[''.join(' ' if not x else x for x in l) for l in map(None,*c)] for i,(n,_) in e(b): c[a-i-1]+='\b'*i*2+n c='\n'.join(c[::-1]) print(c) ``` ## Tests ``` a 1 b 2 c 3 _ _| | _| | | |_|_|_| | | | | | + c | + b + a ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~208~~ ~~194~~ ~~190~~ ~~168~~ ~~167~~ 164 bytes ``` (($h=$args|%{$t,$n=$_-split'(?=\d+$)';$r=,"$c + $t"+$r;$c+=' |';$n})|sort)[-1]..0|%{$i=$_ &{-join($h|%{($p,($p=' |'[$i-lt$_])|sort)[-1];' _'[$i-in0,$_]})+$p}} $c $r ``` [Try it online!](https://tio.run/##fZJPT4NAEMXv@ykmOu2yARr6Ry8NsdGDBz17qQ3Z0m3B4EKWjcYAnx2nCK0xqZvsYeb33pvZZIv8U5kyUVnW4h5CqFrHwSREaQ5lParQeqhDjPyyyFLLnbvwdeei4Es0oXeFMbiA9spFs8TYDTnURHQj6jI3Vqz96WYyCY4xKWWwceW/5ammfGo5WHh0O88aUz@zGG1@GZccog6kOvAINcLFomkYxgxN2zC2chjzHAD@kOcZLLjHgA5/Ola3HERP76UpIZYatgoCCAbZMz1Q@VuCkTQKdRqrGdl6Kj@UkQclnNU1wnzoaiVtDjfn7Ecji4QaPadRJD7RF2W@znt1A/9q@2LIOVnXWr4ryPcwLS3QkhuYDtoTmundJTQ3F9HCJgM6ThNQwwiqTjSmD7CKfvT@P4ezpv0G "PowerShell โ€“ Try It Online") Unrolled: ``` # parse input $heights = $args|%{ $title,$number=$_-split'(?=\d+$)' # the title contains a trailing space. It's allowed by the author $rows=,"$columns + $title"+$rows $columns+=' |' Write-Output $number } # draw bars ($heights|sort)[-1]..0|%{ # max($heights)..0 $lineNum=$_ &{ # execute the scriptblock to reset inner variables -join( $heights|%{ $currLeftBorder = ' |'[$lineNum -lt $_] Write-Output ($prev,$currLeftBorder|sort)[-1] # max Write-Output ' _'[$lineNum -in 0,$_] $prev=$currLeftBorder } )+$prev } } # draw bottom columns and titles Write-Output $columns Write-Output $rows ``` [Answer] ## Java, 613 for the printing function It may be possible to save a few bytes by the "usual" transformations of `for(i=0;i<n;i++)` to `for(;i++<n;)`, simplifying the ternary conditionals, or with more elegant computations of the "labels" and "heights", but it's a start. ``` package stackoverflow.codegolf.barchart; import static java.util.stream.Stream.of; import java.util.stream.IntStream; public class BarChartTest { public static void main(String[] args) { String input0[] = { "Cool 4", "Kool 6", }; String input1[] = { "Graph 5", "Bar 3", }; String input2[] = { "Very 4", "Large 5", "Bar 3", "Graph 5", }; String input3[] = { "Bars can be 0 0", "Large-bars_are$nice2 6", "average)(@#$ 3", "neato 5", }; runTest(input0); runTest(input1); runTest(input2); runTest(input3); } private static void runTest(String input[]) { System.out.println("In:"); for (String string : input) { System.out.println(string); } System.out.println("Out:"); BarChartTest b = new BarChartTest(); b.print(input); } void p(String a[]){int h[]=of(a).map(this::s).mapToInt(Integer::parseInt).toArray(),M=IntStream.of(h).max().getAsInt(),C=a.length,r,c,y;Object t[]=of(a).map(this::p).toArray();String s="",p=" + ",w="";char n=10,v='|',i=32,u=95,e;for(r=0;r<=M;r++){e=r==M?'_':' ';y=M-r;for(c=0; c<C; c++){s+=h[c]>y?v:c>0?h[c-1]>y?v:e:r==0?e:i;s+=h[c]==y?u:e;}s+=h[C-1]>y?v:e;s+=n;}for(r=0;r<C;r++){for(c=0;c<C-r;c++){s+=" |";}s+=r>0?p+t[C-r]:w;s+=n;}s+=p+t[0];System.out.println(s);}int b(String s){return s.lastIndexOf(" ");}String p(String s){return s.substring(0,b(s));}String s(String s){return s.substring(b(s)+1,s.length());} } ``` [Answer] ## Haskell, 323 bytes ``` f x|(p,q)<-unzip$map((\l->(unwords$init l,(read$last l))).words)$lines x=unlines(reverse$init.(zip((zipWith max=<<tail)$0:q++[0])(q++[0])>>=).(!)<$>[0..maximum q])++v p++'\n':(0#p) v=(>>" |") _#[]="" l#(h:t)=(l+1)#t++v[1..l]++" + "++h++"\n" 0!(0,_)=" _" 0!_="|_" i!(j,k)|i<j=(i==k)?'|'|1<2=(i==k)?' ' i?c|i=c:"_"|1<2=c:" " ``` Usage example: ``` *Main> putStr $ f "Bars can be 0 0\nLarge-bars_are$nice2 6\naverage)(@#$ 3\nneato 5" _ | | _ | | | | | |_| | | | | | | | | | _|_|_|_| | | | | | | | + neato | | + average)(@#$ | + Large-bars_are$nice2 + Bars can be 0 ``` How it works (rough overview, details maybe later): ``` (p,q)<-unzip$map((\l->(unwords$init l,(read$last l))).words)$lines x -- breaks the input into a list of labels (-> p), e.g. -- ["Bars can be 0","Lagerge-basr_asr$niche",...] and a list of heights -- (-> q), e.g. [0,6,3,5] unlines(reverse$init.(zip((zipWith max=<<tail)$0:q++[0])(q++[0])>>=).(!)<$>[0..maximum q]) -- builds the bars v p++"\n" -- builds the first row of "|" underneath the zero line (0#p) -- build the label section ``` The parsing part (`(p,q)<-unlines...`) takes a lot of bytes, maybe I can it golf further down. [Answer] ## Python 2, 345 bytes ``` B,H=zip(*[(a,int(b))for a,b in[x.rsplit(' ',1)for x in input().split('\n')]]) h=max(H) L=len(B) b=['|'*H[0]]*(L*2+1) for i in range(L):b[2+i*2]='|'*max(H[i],H[min(i+1,L-1)]);b[1+i*2]=('_'+' '*(H[i]-1)+'_')[:H[i]+1] b=[x.ljust(h+1)for x in b] for l in zip(*b)[::-1]:print ''.join(l) print' |'*L for i in range(-1,-L-1,-1):print' |'*(L+i),'+',B[i] ``` ]
[Question] [ # Input The board: A 2D container (matrix, list of lists, etc.) of letters like: ``` ["B", "C", "C", "C", "C", "B", "B", "C", "A", "A"], ["B", "A", "C", "B", "B", "A", "B", "B", "A", "A"], ["B", "C", "B", "C", "A", "A", "A", "B", "C", "B"], ["B", "B", "B", "A", "C", "B", "A", "C", "B", "A"], ["A", "A", "A", "C", "A", "C", "C", "B", "A", "C"], ["A", "B", "B", "A", "A", "C", "B", "C", "C", "C"], ["C", "B", "A", "A", "C", "B", "B", "C", "A", "A"] ``` If you choose a list of lists you may assume that all of the sublists are of the same length. # Rules * To make a valid rectangle you need all rectangle corners with the same 'letter'. * Example, look the *sample board with* **X** bellow. You can see 'X' on (1,0) also on (4,0) also on ( 1,3) and on (4,3) then you have the rectange [1,0,4,3] that means from (1,0) to (4,3): *Sample board with* **X**: ``` ["B", "X", "C", "C", "X", "B", "B", "C", "A", "A"], ["B", "A", "C", "B", "B", "A", "B", "B", "A", "A"], ["B", "C", "B", "C", "A", "A", "A", "B", "C", "B"], ["B", "X", "B", "A", "X", "B", "A", "C", "B", "A"], ["A", "A", "A", "C", "A", "C", "C", "B", "A", "C"], ["A", "B", "B", "A", "A", "C", "B", "C", "C", "C"], ["C", "B", "A", "A", "C", "B", "B", "C", "A", "A"] ``` * The goal is to find the rectangle or one of the rectangles with the largest area, calculated by (right-left+1)\*(bottom-top+1) * If there are multiple rectangles with the same maximum area, output any one. Optionally the one with (top coordinate, left coordinate, right coordinate, bottom coordinate) lexicographically smallest. * Rectangles must have edges parallel to the board's edge. * Each letter is a printable ASCII char from A to Z (both included). # Output The output should be the left-up and right-down positions of the largest area rectangle corners. For the first sample "board" the big square is the yellow one: [![enter image description here](https://i.stack.imgur.com/ZIkkF.png)](https://i.stack.imgur.com/ZIkkF.png) And the answer should be: > > [1, 1, 8, 4] > > > ### A second example test case An input of: ``` ["C", "D", "D", "D", "A", "A"], ["B", "D", "C", "D", "A", "A"], ["B", "D", "D", "C", "A", "C"], ["B", "D", "B", "C", "A", "C"] ``` Should yield one of these three coordinate lists identifying an area six rectangles: > > [1, 0, 2, 2] > > [1, 0, 3, 1] > > [3, 2, 5, 3] > > > This question is posted on Stack Overflow with title: [How to find the largest rectangle in a 2D array formed by four identical corners?](https://stackoverflow.com/questions/49708412/how-to-find-the-largest-rectangle-in-a-2d-array-formed-by-four-identical-corners) and with this rude JS solution (I can say "rude" because is my code ;) : Ok, is my first post, be tolerant with me please. I will change all you say to improve the quiz. [Answer] # [Python 2](https://docs.python.org/2/), ~~148~~ 130 bytes ``` lambda x,e=enumerate:min(((a-c)*(d-b),b,a,d,c)for a,y in e(x)for c,k in e(x)for b,g in e(y)for d,h in e(y)if g==h==k[b]==k[d])[1:] ``` [Try it online!](https://tio.run/##fZDLCoMwEEX3/YrBVVLGRbsUsrD5DJtFYuIDaxSxoF9vqdpiNO3mMgfmXIZpx75o7HXK2H16yFppCQMaZuyzNp3sTVSXlhAiw5SeiQ4VRYUSNaY0azqQOEJpwZBhxhSrLSrMFxxn1Fh8sMwgZ6xgrEqUeKcWNLlEYmq70vaQkSQJbgFCwD1x@8aM8RICTwCrFXt2Yw@6Fvf2Ouq6srV2lfw3rtaul7vTwd9ah/OPV3PH4n@F4w8FnV4 "Python 2 โ€“ Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~163~~ 162 bytes ``` Lw$`(?<=(.*\n)*((.)*))(?=(.))((.)*(?<=(.*))\4)((.*\n)*((?>(?<-3>.)*)(?=\4)(?>(?<-6>.)*))\4)? $.7,$#1,$.2,-$.($5$#9*$5),$.2,$#1,$.7,$.($#1*_$#9* 4{N` )m`^.*?, 0G` ``` [Try it online!](https://tio.run/##LYqxCsIwFEX3/EbekBfSYLRVBG1IE3ARv6BoHBwc7CCCgx8f32s6Xe455/34PKe7K@X8haz84aisHifUSlnUiMoToOG3WMSxZbBkvifebHrOqWZX0XZGHHsBdmdAOgN2bRqwCjqQew0dzqQaKkhIp2/sRPu7ZIGvfLXaGyFWp1xKTCmFIIYU66QYIs1A8wc "Retina โ€“ Try It Online") Edit: Saved 1 byte because the trailing `)` matching the `$.(` is implicit. Explanation: ``` Lw$`(?<=(.*\n)*((.)*))(?=(.))((.)*(?<=(.*))\4)((.*\n)*((?>(?<-3>.)*)(?=\4)(?>(?<-6>.)*))\4)? ``` This regular expression matches rectangles. The groups are as follows: 1) Top row (as capture count) 2) Left column (as length) 3) Balancing to ensure the left corners align 4) Letter for the corners 5) Width + 1 (as length) 6) Balancing to ensure the right corners align 7) Right column (as length) 8) unused 9) Height (as capture count). The `w` option ensures that all possible widths of rectangles are matched for each given top left corner. The `$` options lists the results using the following substitution pattern. ``` $.7,$#1,$.2,-$.($5$#9*$5),$.2,$#1,$.7,$.($#1*_$#9* ``` The substitutions are as follows: The right column, the top row, the left column, the negation of the area of the rectangle (literally calculated as the length of repeating the width string by one more than height number of times), the left column, the top row, the right column, followed by an expression that evaluates to the bottom row (a capture would have cost 12 bytes plus I've run out of single-digit variables). The first four captures represent the sort order in order of priority. As Retina sorts stably, a multicolumn sort can be established by sorting by each sort column in turn from least to greatest priority. (The area must be sorted in descending order, so a single string sort cannot be used.) ``` 4{N` ``` Four numeric sorts are then performed. ``` )m`^.*?, ``` The sort column is then deleted after each sort. ``` 0G` ``` The first entry is therefore now the desired result. Note: The restriction on the choice of rectangle of a given area has since been relaxed and the following ~~144~~ 143-byte version prefers a wider rather than a taller rectangle: ``` Lw$`(?<=(.*\n)*((.)*))(?=(.))((.)*(?<=(.*))\4)((.*\n)*((?>(?<-3>.)*)(?=\4)(?>(?<-6>.)*))\4)? -$.($5$#9*$5);$.2,$#1,$.7,$.($#1*_$#9* N` 0G` .*; ``` [Try it online!](https://tio.run/##LYpBCsIwEEX3c43MIhPSYNQqUm1IE3AjnqDQuHDhpgsRPH6csV09/nv//fy85oev9fbFosP5op0ZZzJaOzJEOrBgyFor0bgXsd5Cz77Z9XLnt7RFHf5KzgEadBpbVCeDLXXothaVt@iOVoLyZpIG9wKbawFnOqg15ZxjhCGnBTnFxBgYPw "Retina โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (27?) ~~29~~ 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 27 if 1-based indexing is allowed - remove trailing `โ€™` ``` Fแน™1s2;Uล“แป‹ยณEaZIโ€˜P ZLpLล’ฤ‹ร‡รžแนชFโ€™ ``` A full program. **[Try it online!](https://tio.run/##y0rNyan8/9/t4c6ZhsVG1qFHJz/c3X1os2tilOejhhkBXFE@BT5HJx3pPtx@eN7DnavcHjXM/P//f3S0kpOSjoKSMxbCCU6AuY4QIlaHSwGqyRGLUkcsXBRNzlhNRdEJVYKkCc1AZ9xciCY0U51RWRjakTRhOB3Tyc7ImpzxqscMvVgA "Jelly โ€“ Try It Online")** (or see the other [test case](https://tio.run/##y0rNyan8/9/t4c6ZhsVG1qFHJz/c3X1os2tilOejhhkBXFE@BT5HJx3pPtx@eN7DnavcHjXM/P//f3S0krOSjoKSCyrhCCFidbgUopWc4MLOhBQgVDlCWOgKnDAUxAIA "Jelly โ€“ Try It Online")) ### How? ``` Fแน™1s2;Uล“แป‹ยณEaZIโ€˜P - Link 1, areaOrZero: list of pairs [[b,l],[t,r]] F - flatten the input [b,l,t,r] แน™1 - rotate left one [l,t,r,b] s2 - split into twos [[l,t],[r,b]] U - upend the input [[l,b],[r,t]] ; - concatenate [[l,t],[r,b],[l,b],[r,t]] ยณ - program's input ล“แป‹ - multidimensional index into E - all equal? X Z - transpose the input [[b,t],[l,r]] a - logical AND (vectorises) (if not X we now have [[0,0],[0,0]] I - incremental differences [t-b,r-l] (or [0,0] if not X) โ€˜ - increment (vectorises) [t-b+1,r-l+1] (or [1,1] if not X) P - product area (or 1 if not X) ZLpLล’ฤ‹ร‡รžแนชFโ€™ - Main link: list of lists Z - transpose the input L - length L - length of the input p - Cartesian product ล’ฤ‹ - pairs with replacement รž - (stable) sort by: ร‡ - last link (1) as a monad แนช - tail (note that the rightmost pre-sort represents the bottom-right 1x1 - so cannot be superseded by a non-matching rectangle) F - flatten โ€™ - decrement (vectorises) (to get to 0-based indexing) ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~83~~ 73 bytes ``` {([X] (^$^a[0]X ^$a)xx 2).max:{[eq] $a[.[*;1];.[*;0]]and[*] 1 X-[Z-] $_}} ``` [Try it online!](https://tio.run/##hZDLDoJADEX3fEVDiAECBFy4kLiA@hETm2ImUVbiAzcQ47cjiDK8optO79x7Os1cj/lpVWUlLFLYVA@TBIOZGIkknwUkhrSKApaWl8li/aDjjcGQ5JEdBhw2h88szweyGQIQLu3cOrB/Pqu7LCE1jb0F6SXXSCMddQf07bBEbWGn9uPuFv/4KhS13ciPJ77WJL4Z0dnYyXiG678bdZZKRjOyz@DszAH4iShGDMeNJPbkmxnNxGGHY1oxk7Wn@2KPwZ/x6b9pHFYv "Perl 6 โ€“ Try It Online") Returns a list of lists `((x0 y0) (x1 y1))`. ### Explanation ``` { ([X] # Cross product of corner pairs. (^$^a[0] # Range of x coords. X # Cross product of coords. ^$a # Range of y coords. )xx 2 # Duplicate list. ).max: # Find maximum of all ((x0 y0) (x1 y1)) lists { # using the following filter. [eq] # All letters equal? $a[.[*;1];.[*;0]] # Multidimensional subscript with y and x coord pairs. and # Stop if false. [*] # Multiply 1 X-[Z-] $_ # for each axis 1 - (c0 - c1) == c1 - c0 + 1. } } ``` [Answer] # [Haskell](https://www.haskell.org/), 144 bytes ``` import Data.Array o=assocs f r=snd$maximum[((c-a+1)*(d-b+1),[a,b,c,d])|((a,b),x)<-o r,((c,d),y)<-o r,x==y,r!(a,d)==r!(c,b),x==r!(a,d),a<=c,b<=d] ``` [Try it online!](https://tio.run/##PY7NasMwDMfveQqt9GBvyugug0F0sN23KD2occtM4yTYGSTQd8/kdMwY6//xA/mb8/3adesa4jikCY488btJiZdqIM55aHN1g0S59/vIc4g/8aRUW/Pbh35Vvr7IxBPjBVv0Z/1QSrTGWTf1AAkFRa9x@bMz0YLpRRiviUS0G7zJkiE3JFFD/rxmjmN3BYIu5Gn7ESh1wING9YWfWsPOyjHGOeOssdY5cVa0eFOi52u2onCClOv@20I7s6sih57GFPoJ9nCD5@L1Fw "Haskell โ€“ Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` XLแนญLp`โ‚ฌp/โบล“แป‹โ‚ฌEษ—รfIโ€˜Pษ—รž0แนช ``` [Try it online!](https://tio.run/##RZC9TsMwFIX3PMWVGNpKQfw8AFISlx8pAyNVVQlTbhsX145iR1W3wtKBBYkBBsQDoDJDQWKpGHiM5EXCTSKCB/v4@pxP13eCUs6L4izM1q9hfJ7frOKd/Prj@z77vKVL9@dhczc6yRePp6Sed7P1S7FZ0kO2/qK9B9n7W754gpAbC1KoK2hvlh0XeBzLOZCDDyMXUoXk57IpTLRQcDEHhTMKIbR7naLowxZMU2lFLBEsEnDIDRqXXHgJHEZaW0zA6pq@jYRynH7L83y/5bj1OSDIPiQ4tFyNJRqYCRuB4VMEniB3XAoEjDHPKyM@CxrFAi@olV@qQWX1/ICVxe7h0XHFVvofXrNLLBzAXu2vVt3NX7YS3UqxhtN8VMdWTGk0RsvUCq0MmIgnQo3BRjQGTZ4RTUInChPHGfwC "Jelly โ€“ Try It Online") `โบ` proves to be useful. Output format: *[top,bottom],[left,right]*. 1-indexing. [Answer] # JavaScript (ES6), 121 bytes *-1 byte thanks to @l4m2* *-1 byte thanks to @tsh* *+2 bytes to comply with the new rectangle scoring rule* Takes input as a matrix of strings. Returns 0-indexed coordinates: **[x0, y0, x1, y1]**. ``` a=>a.map(b=(r,y)=>r.map((v,x)=>a.map((R,Y)=>R.map((V,X)=>V+R[x]+r[X]!=v+v+v|(A=(x+~X)*(y+~Y))<b||(o=[x,y,X,Y],b=A)))))&&o ``` [Try it online!](https://tio.run/##fZFNasMwEIX3PoXrRRhF01wgUUCWT@BFsBFayGlSWpIoOMXYYHJ113V@ZamRYNBD73uMRt@60qd1@XX8eT@Yj023ZZ1mSz3b6yMUDEpsCFuWg4QKa3K7gxTzXqQXscKsFyuaylrRUmbqjVW03y1wBjU9Z2QKDT3nhCyKtgXDZI0NZpgrLBgnf2syMd3aHE5mt5ntzCdsQQZhKKM4wjASnhLfyyD5pSh8UNzj5R5pU8Kba6FXyzM1ihT/yys1yhX2yeGfKad9t2thUeIl4M4wUITMA99vDLbELp4ZJvfIl45k/HLHETuOobfuFw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 38 bytes ``` aโŠƒโจโŠƒโ’ร—/1+-/โ†‘2 2โˆ˜โดยจaโ†โธโ‰ขยจโ†‘โˆ˜.(โˆฉยจ)โจโˆ˜.โˆฉยจโจโ†“โŽ• ``` [Try it online!](https://tio.run/##bU29CsIwEN7vKRwVqdW@QXJ5kVCpFAoVnJyFWsWIP4hODk5xd3BxqW9yL1Lv4qjhyPeT777YaRGN57YoJ1Fa2NksT1vanvKSqt0QqF5mraX1gpwP9@F9jkf9KKZqn3QSqi/kHo23HCb3pNWt8fzC9qBL9b3xPdljFYTw6sjlLde2GUhy8yJ3/R3QyEdrVAq0YqJ4mKI4igG0Fl8G2EGFIiDEUJYBAwsN8O8vQGOMdBr8guESBt7ADw "APL (Dyalog Classic) โ€“ Try It Online") [Answer] # Java 8, ~~208~~ 205 bytes ``` m->{int r=0,R[]={},i=m.length,j,y,z,u,t,T;for(;i-->0;)for(j=m[i].length;j-->0;)for(y=i*j;y-->0;)if((T=m[i][j])==m[u=y/j][z=y%j]&T==m[i][z]&T==m[u][j]&r<(t=(i-u)*(j-z))){r=t;R=new int[]{z,u,j,i};}return R;} ``` Can definitely be golfed.. I now use the most obvious approach of using ~~four~~ three nested for-loops. -3 bytes thanks to *@ceilingcat* combining the inner loops of rows and columns into a single loop. **Explanation:** [Try it online.](https://tio.run/##vZLBToQwEIbvPkVjomlNQe@1JlCuelj3QEI4VGS1FbqmFA1LePZ1Cqte7B5MlAxh6P9N6fyMlm8y0o8v@6qRXYdupTLjCULKuNpuZFWjO/86LxQlqnD1LG1RQtoSBsIEN0TnpFMVukMGcbRvo5sReGT5FV0VJR8nqngbN7V5cs9U04HuaE8dXbPN1mKmoujmihGfa94WqjyQTH8LA1cXmg3LgtpgvJ7JQpeEQ9bz4VKXxY4PZ7o8X/NF3B3S3nPn9ho7jlXUkwusox0hZLTcsRU39fvS3uiPpama2GRr11uDVmzas6XF1/6hgRYPnb5t1SNqwSx876wyT0UpyWLU/dC5uo23vYtfQXGNwRo8jnunmjixVg5d7LZLFTZxhf3nP11dtkDoNBVwpalIklOgBchzKSb0i0hATyDChPD1CTyCROp38REioF4kwjNBwh9B@POGCDEDP/QyAxP8CBZyLqz8wlORZdkRtzJxVM1E2IM0S0Pq/7WX50Lk3ub8T0cmT5P8z0cm/xyZ/NjITCfT/gM) ``` m->{ // Method with char-matrix parameter and int-array return-type int r=0, // Largest area found, starting at 0 R[]={}, // Result coordinates, starting empty i=m.length,j, // x,y indices of the first corner y,z, // x,y indices of the second corner u,t,T; // Temp integers to reduce bytes for(;i-->0;) // Loop `i` over the rows for(j=m[i].length;j-->0;)// Inner loop `j` over the columns for(y=i*j;y-->0;) // Inner loop over the rows and columns if((T=m[i][j])==m[u=y/j][z=y%j] // If the values at coordinates [i,j] and [y,z] are equal &T==m[i][z] // as well as the values at [i,j] and [i,z] &T==m[u][j] // as well as the values at [i,j] and [y,j] &r<(t=(i-u)*(j-z))){ // And the current area is larger than the largest r=t; // Set `r` to this new largest area R=new int[]{z,u,j,i};} // And save the coordinates in `R` return R;} // Return the largest rectangle coordinates `R` ``` ]
[Question] [ Here is an ASCII-art of a 4-way intersection: ``` | | | | | | | | | | | | | -----+-----+----- | | - - -| |- - - | | -----+-----+----- | | | | | | | | | | | | | ``` (Note how the horizontal roads are 3 rows tall, while the vertical roads are 5 columns wide. This is for aesthetic reasons, because of the rectangular font.) Your challenge is to produce this ASCII art. However, as I'm sure you all know, not every intersection has a road travelling off in every single direction. This particular intersection goes `NESW`, but some intersections might go, for example, `NW`: ``` | | | | | | | | | | | | | -----+-----+ | | - - -| | | | -----+-----+ ``` Or it might go `SWE`: ``` -----+-----+----- | | - - -| |- - - | | -----+-----+----- | | | | | | | | | | | | | ``` Or it may even go `E`, just a single direction (although you can hardly call this an *intersection*, but try to avoid being overly pedantic): ``` +-----+----- | | | |- - - | | +-----+----- ``` You need to write a program or function that can easily generate *any* of these combinations. More specifically, your challenge is to write a program or function that takes a string of directions, consisting of `NESW`, as input, and outputs or returns this ASCII art of an intersection with roads pointing in those directions. These directions may appear in any order, but the input *will not* contain any characters except for `N`, `E`, `S`, or `W`. If you like, you may request inputs to be lowercase instead, but you must specify this in your answer. You may also assume that all inputs will contain at least one direction. The last example had leading spaces on each line, because there is no road going west. If you do not have a road going west, these leading spaces are optional. This: ``` +-----+----- | | | |- - - | | +-----+----- ``` Would also be an acceptable output. Similarly, if `N` or `S` is gone, empty lines in there place are optional. One trailing newline is allowed, and trailing spaces are allowed as long as the output is *visually* the same. You may take input and output in any reasonable format, such as STDIN/STDOUT, command line args, files, function arguments/return values, etc. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to get the shortest possible answer in whatever language you happen to use! # Sample IO: ``` NESW: | | | | | | | | | | | | | -----+-----+----- | | - - -| |- - - | | -----+-----+----- | | | | | | | | | | | | | NS: | | | | | | | | | | | | | +-----+ | | | | | | +-----+ | | | | | | | | | | | | | S: +-----+ | | | | | | +-----+ | | | | | | | | | | | | | EW: -----+-----+----- | | - - -| |- - - | | -----+-----+----- SE: +-----+----- | | | |- - - | | +-----+----- | | | | | | | | | | | | | ``` [Answer] ## Javascript (ES6), ~~190~~ ~~187~~ 185 bytes This is an attempt to build this ASCII art character per character by iterating on a 17x15 matrix. Therefore, the output is always made of 15 rows of 17 columns with the intersection of the roads centered in the middle. ``` p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]") ``` ### Ungolfed and commented ``` for(y = 15, s = ''; y--; s += `\n`) // iterate on y, from 14 to 0 / append line feeds for(x = 17; x--;) // iterate on x, from 16 to 0 s += ' |-+' [ // append next character to string +[ a = y > 4, // a = outside South area? b = y < 10, // b = outside North area? c = x > 4, // c = outside East area? d = x < 12 ] // d = outside West area? .every((c, i) => // for each area, see if either: c | // - we're currently outside it p.search('SNEW' [i]) + 1 // - or it's an allowed area (p = function param.) ) // if all tests pass, add a: && // - vertical bar (encoded as 1) if: !((z = x - 8 || y & 1 | a & b) // - x=8, y is even and we're not in the middle && z * z - 9) // - OR x=5 OR x=11 (<=> (x-8)*(x-8) = 9) + 2 * // - horizontal bar (encoded as 2) if: !((z = y - 7 || x & 1 | c & d) // - y=7, x is even and we're not in the middle && z * z - 4) // - OR y=5 OR y=9 (<=> (y-7)*(y-7) = 4) ] // (vertical + horizontal = 3, which leads to '+') ``` ### Matrix Below is the matrix with the coordinates used in the code. [![matrix](https://i.stack.imgur.com/5ik6G.png)](https://i.stack.imgur.com/5ik6G.png) ### Demo The following snippet allows to try any road configuration. ``` let f = p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]") function update() { document.getElementById("o").innerHTML = f(document.getElementById("s").value); } update(); ``` ``` <input id="s" size=4 value="NSEW" oninput="update()"> <pre id="o" style="font-size:9px"></pre> ``` [Answer] ## PowerShell v3+, ~~226~~ ~~204~~ ~~192~~ 191 bytes ``` param([char[]]$a)($n=0..4|%{($x=' '*5*($b=87-in$a))+('| | |',($w='| |'))[$_%2]})*(78-in$a) ($z=($y='-'*5)*$b+"+$y+"+$y*($c=69-in$a)) $x+$w '- - -'*$b+$w+'- - -'*$c $x+$w $z $n*(83-in$a) ``` Takes input as a string of capital letters, explicitly casts it as a `char` array. Constructs the "North" segment via looping from `0` to `4`. Each loop, constructs a string of 5 spaces (if `W`/`87` is present in the input), stores that in `$x`, then either `| |` (stored in `$w`) or `| | |`, depending upon whether we're currently even or odd. That array of strings is stored into `$n`, and multiplied by whether `N`/`78` is `-in` the input. That will determine if `$n` is placed on the pipeline or not. Then, we construct the middle portion. The first line, `$z` is the "top" of the east-west route, using the same logic for `W` and `E`/`69`, and surrounded in parens to also place a copy on the pipeline. We use helper variable `$y` to save a byte on the `-----` sections. The next line is just the appropriate number of spaces (i.e., `$x`) string-concatenated with the correct-width pipes (i.e., `$w`). Then, the middle striped line, again with `W` and `E` logic and `$w` filling in the middle. Then `$x+$w` and `$z` again. Finally, since the South road is the same as the north, put `$n` on the pipeline if `S`/`83` is `-in` `$a`. All of those resultant strings are gathered from the pipeline and output is implicit at the end of program execution. Abuses the default `Write-Output` delimiter to insert a newline between elements. --- ### Examples ``` PS C:\Tools\Scripts\golfing> .\4-way-intersection.ps1 'EN' | | | | | | | | | | | | | +-----+----- | | | |- - - | | +-----+----- PS C:\Tools\Scripts\golfing> .\4-way-intersection.ps1 'SNW' | | | | | | | | | | | | | -----+-----+ | | - - -| | | | -----+-----+ | | | | | | | | | | | | | PS C:\Tools\Scripts\golfing> .\4-way-intersection.ps1 'WE' -----+-----+----- | | - - -| |- - - | | -----+-----+----- ``` [Answer] # C++ ~~317~~ ~~280~~ 276 bytes ``` int i(char*j){for(int y=0;y<15;++y)for(int x=0;x<18;++x)putchar(x-17?y<5&!strchr(j,'N')|y>9&!strchr(j,'S')|x<5&!strchr(j,'W')|x>11&!strchr(j,'E')?' ' :x==5|x==11?y==5|y==9?'+':'|':y==5|y==9?x==5|x==11?'+':'-':x==8&y%2|y==7&x%2?' ':x==8&(y/5-1)?'|':y==7&(x/6-1)?'-':' ':'\n');} ``` Ungolfed: ``` int i (char* j) { for (int y=0; y<15; ++y) for (int x=0; x<18; ++x) putchar( x-17 ? y<5 & !strchr(j,'N') | y>9 & !strchr(j,'S') | x<5 & !strchr(j,'W') | x>11 & !strchr(j,'E') ? ' ' : x==5 | x==11 ? y==5 | y==9 ? '+' : '|' : y==5 | y==9 ? x==5 | x==11 ? '+' : '-' : x==8 & y%2 | y==7 & x%2 ? ' ' : x==8 & (y / 5 - 1) ? '|' : y==7 & (x / 6 - 1) ? '-' : ' ' : '\n'); } ``` [Answer] # Python 3, 186 bytes ``` S=' -- - -- - --' lambda d:'\n'.join(S[r//4:15*('W'in d):3]+'||+ - -| - - -||+'[r%4::3]+S[r//4:15*('E'in d):3]for r in[0,1,0,1,0,6,1,9,1,6,0,1,0,1,0][5-5*('N'in d):10+5*('S'in d)]) ``` An anonymous lambda called with a string of directions, e.g. 'NWS' ### Explanation to follow [Answer] # sed 234 ``` s,$,@+-----+@| |@! !@| |@+-----+@, :l;tl /N/s,^,#,;t :r /S/s,@$,#,;t /E/{s,!@,|- - -@,;s,+@,+-----@,g} /W/{s,@!,@- - -|,;s,@+,@-----+,g;s,@|,@ |,g} y,@!NSEW,\n| , q : s,#,@| | |@| |@| | |@| |@| | |, tr ``` It just builds the different parts if the proper character is on the line. Uses `@` instead of `\n` and subs `\n` back in at the end. The north and south parts are identical, so I use what's basically a function to insert them. [Answer] ## Batch, ~~351~~ ~~344~~ 341 bytes ``` @echo off set/pi= set t= if not "%i:n=%"=="%i%" call:l set l=----- set r=%l% if "%i:w=%"=="%i%" set l=%t% if "%i:e=%"=="%i%" set r= for %%s in (%l%+-----+%r% "%t%|%t%|" "%l:--=- %|%t%|%r:--=- %" "%t%|%t%|" %l%+-----+%r%) do echo %%~s if "%i:s=%"=="%i%" exit/b :l call :m call :n :n echo %t%^|%t%^| :m echo %t%^| ^| ^| ``` Note: The line `set t=` ends in five spaces, and the line `if "%i:e=%"=="%i%" set r=` ends in a space. Takes case-insensitive input from STDIN. Edit: Saved 7 bytes by eliminating the `d` variable. Saved 3 bytes by using a `for` loop to print the middle section. If I'm allowed separate command-line parameters instead, then for ~~326~~ ~~319~~ 316 bytes: ``` @echo off set t=%* set/an=s=e=w=5,%t: ==%=0 set t= call:%n% set r=-----%t% call set l=%%r:~%w%,5%% call set r=%%r:~%e%%% for %%s in (%l%+-----+%r% "%t%|%t%|" "%l:--=- %|%t%|%r:--=- %" "%t%|%t%|" %l%+-----+%r%) do echo %%~s goto %s% :0 call :1 call :2 :2 echo %t%^|%t%^| :1 echo %t%^| ^| ^| :5 ``` [Answer] ## Python 2, 290 bytes ``` t,s,r,i=[],[],range(5),raw_input() for n in r:t+=[" "*5*("W"in i)+"| "+("|"," ")[n%2]+" |"] exec"s+=['-'*5];s[:1]+=' '*5,;"*2;s[:2]+="- - -", if"N"in i:print'\n'.join(t) print'\n'.join([s[n]*("W"in i)+("| |","+-----+")[`n`in"04"]+s[n]*("E"in i)for n in r]) if"S"in i:print'\n'.join(t) ``` [Answer] # GolfScript, 154 bytes ``` {a?1+}:x;'-'5*:e;' '5*:b;"+"e+"+"+:f;{b'|'b'|'b n}:k;{'W'x{e}{b}if\'E'x{e}{}if n}:y;{x{b"| | | "+:c k c k c}{}if}:z;1/:a;'N'z f y k'|'b+'|'+ y k f y'S'z ``` [Try it online!](http://golfscript.tryitonline.net/#code=e2E_MSt9Ong7Jy0nNSo6ZTsnICc1KjpiOyIrImUrIisiKzpmO3tiJ3wnYid8J2Igbn06azt7J1cneHtlfXtifWlmXCdFJ3h7ZX17fWlmIG59Onk7e3h7YiJ8ICB8ICB8CiIrOmMgayBjIGsgY317fWlmfTp6OzEvOmE7J04neiBmIHkgayd8J2IrJ3wnKyB5IGsgZiB5J1Mneg&input=TlNFVw) [Answer] # Pyth (385 380 373 353 bytes) Golfed: ``` K" | | |\n | |\n"?}\Nz++KKPKk?}\Wz?}\Ez+++*5\-*2+\+*5\-"\n | |\n- - -| |- - -\n | |\n"+*5\-*2+\+*5\-++*2+*5\-\+"\n | |\n- - -| |\n | |\n"*2+*5\-\+?}\Ez+" "+*2+\+*5\-"\n | |\n | |- - -\n | |\n +-----+-----"++" +-----+\n"*3" | |\n"" +-----+"?}\Sz++KKPKk ``` Ungolfed: ``` K" | | |\n | |\n" //sets K to first two lines of north ?}\Nz //if north in the input ++KKPK //then: return K + K + K[:-1] k //else: return "" ?}\Wz //if West in input ?}\Ez //if East in input +++*5\-*2+\+*5\-"\n | |\n- - -| |- - -\n | |\n"+*5\-*2+\+*5\- //then: Return E+W string ++*2+*5\-\+"\n | |\n- - -| |\n | |\n"*2+*5\-\+ //else: Return W string ?}\Ez //else: if east in input (and not W) +" "+*2+\+*5\-"\n | |\n | |- - -\n | |\n +-----+-----" //return East without West String ++" +-----+\n"*3" | |\n"" +-----+" \\Return empty left and right intersection ?}\Sz //if south in input ++KKPK //return north string k //return "" ``` Of course, if there are any improvements please tell me. Saved 5 bytes thanks to Maltysen [You can try it here](http://pyth.herokuapp.com/?code=K%22+++++%7C++%7C++%7C%5Cn+++++%7C+++++%7C%5Cn%22%3F%7D%5CNz%2B%2BKKPKk%3F%7D%5CWz%3F%7D%5CEz%2B%2B%2B%2a5%5C-%2a2%2B%5C%2B%2a5%5C-%22%5Cn+++++%7C+++++%7C%5Cn-+-+-%7C+++++%7C-+-+-%5Cn+++++%7C+++++%7C%5Cn%22%2B%2a5%5C-%2a2%2B%5C%2B%2a5%5C-%2B%2B%2a2%2B%2a5%5C-%5C%2B%22%5Cn+++++%7C+++++%7C%5Cn-+-+-%7C+++++%7C%5Cn+++++%7C+++++%7C%5Cn%22%2a2%2B%2a5%5C-%5C%2B%3F%7D%5CEz%2B%22+++++%22%2B%2a2%2B%5C%2B%2a5%5C-%22%5Cn+++++%7C+++++%7C%5Cn+++++%7C+++++%7C-+-+-%5Cn+++++%7C+++++%7C%5Cn+++++%2B-----%2B-----%22%2B%2B%22+++++%2B-----%2B%5Cn%22%2a3%22+++++%7C+++++%7C%5Cn%22%22+++++%2B-----%2B%22%3F%7D%5CSz%2B%2BKKPKk&input=N%0AW%0AE%0AS%0ANW%0ANE%0ANS%0ASW%0ASE%0ASN%0A&test_suite=1&test_suite_input=E&debug=0) [Answer] # Groovy (274 Bytes) ## Ungolfed ``` r{ l-> t='+-----+' s=' '; m='| |' x='-----' v=(1..5).collect{s} nsR=(1..5).collect{[s,((it%2)?'| | |':m),s]} ewR=[x,s,'- - -',s,x] c=[l[3]?ewR:v,[t,m,m,m,t],l[1]?ewR:v] (l[0]?nsR.collect{it}:[])+((0..4).collect{x->((0..2).collect{y->c[y][x]})}โ€‹)โ€‹+โ€‹(l[2]?nsR.collect{it}:[]) } ``` ## Golfed ``` def i(l) {t='+-----+';s=' ';m='| |';x='-----';v=(1..5).collect{s};n=(1..5).collect{[s,((it%2)?'| | |':m),s]};e=[x,s,'- - -',s,x];c=[l[3]?e:v,[t,m,m,m,t],l[1]?e:v];(l[0]?n.collect{it}:[])+((0..4).collect{x->((0..2).collect{y->c[y][x]})}โ€‹)โ€‹+โ€‹(l[2]?n.collect{it}:[])} ``` Try it: <https://groovyconsole.appspot.com/script/5082600544665600> ]
[Question] [ A [nonogram](http://en.wikipedia.org/wiki/Nonogram) is a two-dimensional logic puzzle that looks something like this (screenshots from the game [Pixelo](http://www.64levels.com/game/pixelo), my favourite nonogram game): ![An empty nonogram board](https://i.stack.imgur.com/JBBC5.png) The goal of the game is to figure out what image those numbers are encoding. The rules are simple: A number on a column or row means that somewhere in that column or row, that many boxes are filled in in a row. For example, the bottom row in the above image must have no boxes filled in, while the one above it must have all of its boxes filled. The third row from the bottom has 8 filled boxes, and they will all be in a row. Two or more numbers for the same column or row mean that there are multiple "runs" of filled boxes, with at least one space between, with those lengths. The order is preserved. For example, there are three filled in boxes on the very right column of the above image, at least one space below them, and then one more filled in box. Here's that same puzzle, almost completed: ![A nearly finished nonogram board](https://i.stack.imgur.com/coJv0.png) (The Xs aren't important, they're just a hint the player leaves for themself to say "This square is definitely not filled in". Think flags in Minesweeper. They have no rules meaning.) Hopefully you can see that, for example, the middle columns with hints that say "2 2" have two 2-length runs of filled in boxes. Your mission, should you choose to accept it, is to write a program or function that will create a puzzle like this. You are given the size of the board as a single integer (5 <= n <= 50) on stdin or as an argument (there's no reason why a nonogram puzzle has to be square, but for this challenge it will be). After that, you will be given a series of 1s and 0s representing filled and unfilled squares in the image, respectively. The first n of them are the top row, then the next row, etc. You will return or print to stdout a board of 2\*1 cells (because they look better, and it gives you room for 2-digit hints for a column), all of them empty, with hints corresponding to the input data. # Output Format ![Output Format](https://i.stack.imgur.com/uRy1b.png) # Sample Input: ``` ./nonogram <<< '5 0 1 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 1 0' OR n(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0]) ``` Image: ![First example image](https://i.stack.imgur.com/25WML.png) Output: ``` 1 2 1 2 3 2 1 2 3 +---------- 3| 2 2| 1 1 1| 2 2| 3| ``` Input: ``` ./nonogram <<< '15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 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 1 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 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1' ``` Image: ![Second example image](https://i.stack.imgur.com/2x36k.png) Output: ``` 1 1 1 1 3 3 5 5 3 3 1 7 2 3 2 4 2 3 210 2 3 0 4 215 +------------------------------ 2| 1| 1| 1| 1| 1 1| 3 3 1 1| 1 5 1 1| 3 5 3| 1 5 1| 1 3 1| 1 1 1 1 1| 1 1 1 1 1 1 1 1| 11 3| 11 3| ``` # Clarifications * Your output need not be a solvable puzzle. Not all nonograms are solvable, but that isn't your concern. Just output the hints that correspond to the input, whether they make for a good puzzle or not. * A program that takes arguments on the command line is allowed. This is kind of stated above, but it's possible to get the wrong idea. That's what clarifications are for. * Printing a `0` for a row or column that has no filled in boxes is mandatory. I don't say this with words anywhere but it's in the sample data. [Answer] ### GolfScript, 128 characters ``` ~](:k/.{{1,%{,}%.!,+}%}:^~{' ':s*}%.{,}%$-1=:9{s*\+9~)>'|'n}+%\zip^.{,~}%$0=){.~[s]*@+>{s\+-2>}%}+%zip{9)s*\n}%\[9s*'+''--'k*n]\ ``` The input has to be provided on STDIN as space separated numbers. You can test the example [here](http://golfscript.apphb.com/?c=OyIxNSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDEgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMSAxIDEgMSAwIDAgMCAwIDEgMSAxIDAgMCAxIDAgMSAwIDAgMSAwIDAgMCAxIDEgMSAxIDEgMCAxIDAgMSAxIDEgMSAwIDAgMCAxIDEgMSAxIDEgMCAxIDEgMSAxIDAgMCAwIDAgMCAxIDEgMSAxIDEgMCAwIDAgMSAxIDAgMCAwIDAgMCAwIDEgMSAxIDAgMCAwIDAgMSAxIDAgMCAwIDEgMCAwIDAgMSAwIDAgMCAxIDAgMSAxIDAgMSAwIDEgMCAxIDAgMSAwIDEgMCAxIDAgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMCAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMCAxIDEgMSIKCn5dKDprLy57ezEsJXssfSUuISwrfSV9Ol5%2BeycgJzpzKn0lLnssfSUkLTE9Ojl7cypcKzl%2BKT4nfCdufSslXHppcF4ueyx%2BfSUkMD0pey5%2BW3NdKkArPntzXCstMj59JX0rJXppcHs5KXMqXG59JVxbOXMqJysnJy0tJ2sqbl1c&run=true). *Commented code:* ``` # Parse the input into an 2D array of digits. The width is saved to variable k ~](:k/ # Apply the code block ^ to a copy of this array . { # begin on code block { # for each line 1,% # split at 0s (1, => [0]) (leading, trailing, multiple 0s are # removed because of operator % instead of /) {,}% # calculate the length of each run of 1s .!,+ # special case: only zeros, i.e. [] # in this case the ! operator yiels 1, thus [0], else [] }% # end for }:^ # end of code block ~ # apply # Format row headers {' ':s*}% # join numbers with spaces .{,}%$-1=:9 # calulate the length of the longest row header # and save it to variable <9> { # for each row s*\+ # prepend padding spaces 9~)> # and cut at length <9> from the right '|'n # append '|' and newline }+% # end for # Format column headers \zip^ # transpose input array and apply the code block ^ # i.e. calculate length of runs .{,~}%$0=) # determine (negative) length of the longest column header { # for each column .~[s]*@+ # prepend enough spaces > # and cut at common length (from right) {s\+-2>}% # format each number/empty to 2 chars width }+% # end for zip # transpose column header into output lines {9)s*\n}% # prepend spaces to each line and append newline # Inject separator line \[ 9s* # spaces '+' # a plus sign '--'k* # k (width) number of '--' n # newline ]\ ``` [Answer] # Ruby, 216 ~~255~~ ``` n=$*.shift.to_i;k=*$*.each_slice(n) u=->k{k.map{|i|r=i.join.scan(/1+/).map{|i|"%2d"%i.size} [*[" "]*n,*r[0]?r:" 0"][-n,n]}} puts u[k.transpose].transpose.map{|i|" "*(n-~n)+i*""}," "*n+?++"--"*n,u[k].map{|i|i*""+?|} ``` While this doesn't produce the exact sample output given in the question, it does follow the specs. The only difference to the examples is that I print a few leading spaces/newlines. Example: ``` $ ruby nonogram.rb 15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 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 1 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 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 # empty lines removed for brevity 1 1 1 1 3 3 5 5 3 3 1 7 2 3 2 4 2 3 210 2 3 0 4 215 +------------------------------ 2| 1| 1| 1| 1| 1 1| 3 3 1 1| 1 5 1 1| 3 5 3| 1 5 1| 1 3 1| 1 1 1 1 1| 1 1 1 1 1 1 1 1| 11 3| 11 3| ``` ### Changelog: * 240 -> 231: Changed input format to use command line arguments instead of stdin. * 231 -> 230: Eliminated a space by moving the value check from `chunk` to `map`. * 230 -> 226: Subtract `[nil]` instead of calling `Array#compact`. * 226 -> 216: Simplify hint generation. [Answer] # Ruby, 434 ``` n=$*[i=0].to_i a,b=[],[] a.push $*.slice!(1..n)*""while $*.size>1 (b.push a.map{|c|c[i]}*"";i+=1)while i<n a,b=*[a,b].map{|c|c.map{|d|e=d.split(/[0]+/).map(&:size).select{|f|f>i=0}.map &:to_s;(e.size>0)?e:[?0]}} m,k=*[a,b].map{|c|c.map(&:size).max} s=" "*m k.times{$><<s+" "+b.map{|c|(" "+((c.size==k-i)?(c.shift):(" ")))[-2..-1]}*"";i+=1;puts} puts s+" "+?++?-*n*2 a.each{|c|puts" "*(m-c.size)+" "+c.map{|d|(" "+d)[-2..-1]}*""+?|} ``` [Answer] ## GolfScript ~~149~~ 147 ### The Code ``` ~](:s/.zip{{[0]%{,`}%['0']or}%.{,}%$)\;:ยถ;{.,ยถ\-[' ']*\+}%}:f~ยถ:v;\[f~]\zip{{{.,2\-' '*\+}%''*}:d~ยถ2*)' '*:z\+{puts}:o~}%z(;'+'s'-'2**++o~{d'|'+o}/ ``` Edits: * removed useless space * defined a reusable one-char function for `puts` to save one more char ### Online demos * [Small board](http://golfscript.apphb.com/?c=Oyc1IDAgMSAxIDEgMCAxIDEgMCAxIDEgMSAwIDEgMCAxIDEgMSAwIDEgMSAwIDEgMSAxIDAnCgp%2BXSg6cy8uemlwe3tbMF0leyxgfSVbJzAnXW9yfSUueyx9JSQpXDs6wrY7ey4swrZcLVsnICddKlwrfSV9OmZ%2BwrY6djtcW2Z%2BXVx6aXB7e3suLDJcLScgJypcK30lJycqfTpkfsK2MiopJyAnKjp6XCt7cHV0c306b359JXooOycrJ3MnLScyKiorK29%2Be2QnfCcrb30v&run=true) * [Big board](http://golfscript.apphb.com/?c=OycxNSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDEgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMCAwIDAgMSAwIDAgMCAwIDAgMSAxIDEgMSAwIDAgMCAwIDEgMSAxIDAgMCAxIDAgMSAwIDAgMSAwIDAgMCAxIDEgMSAxIDEgMCAxIDAgMSAxIDEgMSAwIDAgMCAxIDEgMSAxIDEgMCAxIDEgMSAxIDAgMCAwIDAgMCAxIDEgMSAxIDEgMCAwIDAgMSAxIDAgMCAwIDAgMCAwIDEgMSAxIDAgMCAwIDAgMSAxIDAgMCAwIDEgMCAwIDAgMSAwIDAgMCAxIDAgMSAxIDAgMSAwIDEgMCAxIDAgMSAwIDEgMCAxIDAgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMCAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMSAxIDEgMCAxIDEgMScKCn5dKDpzLy56aXB7e1swXSV7LGB9JVsnMCddb3J9JS57LH0lJClcOzrCtjt7LizCtlwtWycgJ10qXCt9JX06Zn7Ctjp2O1xbZn5dXHppcHt7ey4sMlwtJyAnKlwrfSUnJyp9OmR%2BwrYyKiknICcqOnpcK3twdXRzfTpvfn0leig7JysncyctJzIqKisrb357ZCd8JytvfS8%3D&run=true) ### A somewhat annotated version of the code ``` # split lines ~](:s/ # make transposed copy .zip #prepare numbers to show in the header {{[0]%{,`}%['0']or}%.{,}%$)\;:ยถ;{.,ยถ\-[' ']*\+}%}:f~ยถ:v; # prepare numbers to show in the left column \[f~]\zip #print header (vertical hints) { {{.,2\-' '*\+}%''*}:d~ ยถ2*)' '*:z\+puts}% #print first line z(;'+'s'-'2**++puts #print horizontal hints ~{d'|'+ puts}/ ``` [Answer] # Javascript (E6) 314 ~~334 357 410~~ ``` N=(d,l)=>{J=a=>a.join(''),M=s=>(s.match(/1+/g)||['']).map(x=>x.length),f=' '.repeat(d+1),c=[n='\n'],o=n+f+'+'+'--'.repeat(d);for(i=-1;++i<d;)c[i]=M(J(l.map((e,p)=>p%d-i?'':e))),o+=n+(f+J(M(J(l).substr(i*d,d)).map(P=n=>n>9?n:n<10?' '+n:' '))+'|').slice(-d-2);for(;--i;)o=n+f+' '+J(c.map(e=>P(e.pop())))+o;return o} ``` **Ungolfed** ``` N=(d,l)=> { J = a => a.join(''), M = s => (s.match(/1+/g)||['']).map(x=>x.length), f=' '.repeat(d+1), c=[n='\n'], o=n+f+'+'+'--'.repeat(d); for(i = -1; ++i < d;) c[i] = M(J(l.map((e,p)=>p%d-i?'':e))), o += n+(f+J(M(J(l).substr(i*d,d)).map(P=n=>n>9?n:n<10?' '+n:' '))+'|').slice(-d-2); for(;--i;) o=n+f+' '+J(c.map(e=>P(e.pop())))+o; return o } ``` **Usage** `N(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0])` `N(15,[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,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,1,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,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,0,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1])` **Edit history** 1 Removed regexp used to find columns.Overkill 2 Simpler is better. Output to a string, not to an array. Removed helper function FILL (F) 3 Even simpler. I can't do better than this. Still can't compare to Golfscript :( [Answer] ## R, 384 chars ``` a=scan();p=function(x)paste(x,collapse="");P=paste0;s=sapply;l=length;f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0});g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p);c=P(g(f(1),2),"|");d=g(f(2),1);h=p(rep(" ",nchar(c[1])-1));e=P(h,"+",p(rep("-",nchar(d[1]))));d=P(h," ",d);cat(d,e,c,sep="\n") ``` With indentations and some explanations: ``` a=scan() #Takes input p=function(x)paste(x,collapse="") #Creates shortcuts P=paste0 s=sapply l=length #This function finds the number of subsequent ones in a line (using rle = run length encoding). #It takes 1 or 2 as argument (1 being row-wise, 2 column-wise f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0}) #This function takes the result of the previous and format the strings correctly (depending if they are rows or columns) g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p) c=paste0(g(f(1),2),"|") #Computes the rows d=g(f(2),1) #Computes the columns h=p(rep(" ",nchar(c[1])-1)) e=paste0(h,"+",p(rep("-",nchar(d[1])))) #Prepare vertical border d=paste0(h," ",d) #Pad column indices with spaces cat(d,e,c,sep="\n") #Prints ``` Usage: ``` > a=scan();p=function(x)paste(x,collapse="");P=paste0;s=sapply;l=length;f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0});g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p);c=P(g(f(1),2),"|");d=g(f(2),1);h=p(rep(" ",nchar(c[1])-1));e=P(h,"+",p(rep("-",nchar(d[1]))));d=P(h," ",d);cat(d,e,c,sep="\n") 1: 15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 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 1 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 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 227: Read 226 items 1 1 1 1 3 3 5 5 3 3 1 7 2 3 2 4 2 3 210 2 3 0 4 215 +------------------------------ 2| 1| 1| 1| 1| 1 1| 3 3 1 1| 1 5 1 1| 3 5 3| 1 5 1| 1 3 1| 1 1 1 1 1| 1 1 1 1 1 1 1 1| 11 3| 11 3| ``` [Answer] # C - 511 C was definitely not made for formatting output nicely. Character count includes only necessary spaces/new lines. Input is from STDIN, numbers separated by spaces. ``` #define P printf #define L(x) for(x=0;x<s/2+1;x++) #define l(x) for(x=0;x<s;x++) #define B(x,y) x[i][j]||y==s/2?P("%2d",x[i][j]):P(" "); a[50][50],i,j,s,h[25][50],v[50][25],H[50],V[50],x[25],y[25]; main(){ scanf("%d",&s); L(j)x[j]=y[j]=s/2+1; l(i)l(j)scanf("%d",&a[i][j]); for(i=s-1;i>=0;i--) for(j=s-1;j>=0;j--) a[i][j]? !H[j]&&(x[j]--,H[j]=1), h[x[j]][j]++, !V[i]&&(y[i]--,V[i]=1), v[i][y[i]]++: (H[j]=V[i]=0); L(i){ L(j)P(" "); P(" "); l(j)B(h,i); P("\n"); } L(i)P(" "); P("+"); l(i)P("--"); P("\n"); l(i){ L(j)B(v,j); P("|\n"); } } ``` [Answer] It's been a few days and no one's answered in python, so here's my (probably pretty poor) attempt: # Python 2.7 - ~~404~~ ~~397~~ 380 bytes ``` def p(n,m): k=str.join;l=[];g=lambda y:[[' ']*(max(map(len,y))-len(t))+t for t in[[' '*(a<10)+`a`for a in map(len,k("",c).split('0'))if a]or[' 0']for c in y]] while m:l+=[map(str,m[:n])];m=m[n:] x=g(l);j=k('\n',[' '*max(map(len,x))+'+'+k("",a)for a in zip(*[list(a)+['--']for a in g(zip(*l))])]);return j.replace('+',' ',j.count('+')-1)+'\n'+k('\n',[k("",a+['|'])for a in x]) ``` ~~I'll post an ungolfed version soon, but at the moment I think it's pretty readable. :)~~ **EDIT:** While writing the ungolfed version, I noticed some improvements I could make that added up to be fairly significant! For some reason that I can't explain, it now has additional newlines at the top and spaces at the left (even though I don't think I changed anything functional), but it still meets spec. ~~Ungolfed version is coming!~~ Ungolfed: ``` def nonogram(board_size, pixels): def hints(board): output = [] for row in board: # Convert the row to a string of 1s and 0s, then get a list of strings # that came between two 0s. s = "".join(row).split('0') # A list of the length of each string in that list. l = map(len, s) # We now have our horizontal hints for the board, except that anywhere # there were two 0s consecutively we have a useless 0. # We can get rid of the 0s easily, but if there were no 1s in the row at # all we want exactly one 0. # Solution: output.append([h for h in l if h != 0] or [0]) # In this context, `foo or bar` means `foo if foo is a truthy value, bar # otherwise`. # An empty list is falsey, so if we strip out all the strings we hardcode # the 0. return output def num_format(hints): # For both horizontal and vertical hints, we want a space before single- # digit numbers and no space otherwise. Convert hints to strings and add # spaces as necessary. output = [] for row in hints: output.append([' '*(a < 10) + str(a) for a in row]) # Multiplying a string by n repeats it n times, e.g. 'abc'*3=='abcabcabc' # The only numbers that need a space are the ones less than 10. # ' '*(a < 10) first evaluates a < 10 to get a True or False value. # Python automatically converts True to 1 and False to 0. # So, if a is a one digit number, we do `' '*(1) + str(a)`. # If it's a two digit number, we do `' '*(0) + str(a)`. return output def padding(hints): output = [] longest = max(map(len, hints)) # how long is the longest row? for row in hints: output.append([' ']*(longest - len(row)) + row) # Add ' ' to the beginning of every row until it's the same length # as the longest one. Because all hints are two characters wide, this # ensures all rows of hints are the same length. return output board = [] while pixels: # non-empty list == True # Make a list of the first (board_size) pixels converted to strings, then # add that list to board. Remove those pixels from the list of pixels. # When pixels is empty, board has a seperate list for each row. board.append([str(n) for n in pixels[:board_size]]) pixels = pixels[board_size:] horizontal_hints = padding(num_format(hints(board))) vertical_hints = padding(num_format(hints(zip(*board)))) # zip(*l) is a common way to transpose l. # zip([1,2,3], [4,5,6], [7,8,9]) == [(1, 4, 7), (2, 5, 8), (3, 6, 9)] # the star operator unpacks an iterable so the contents can be used as # multiple arguments, so # zip(*[[1,2,3],[4,5,6],[7,8,9]]) is the same as what we just did. # Transposing the board and getting the horizontal hints gives us the # vertical hints of the original, but transposed. We'll transpose it back, # but we'll also add '--' to the end of all of them to make up the line vertical_hints = zip(*[a + ['--'] for a in vertical_hints]) # add n spaces, where n is the length of the longest horizontal hint, plus # one space to the beginning of each line in the vertical hints, then join # with newlines to make it all one string. vertical_hints = '\n'.join([' '*max(map(len, horizontal_hints)) + '+' + ''.join(a) for a in vertical_hints]) # find the number of plus signs in the string # replace the first (that many - 1) plus signs with spaces vertical_hints = vertical_hints.replace('+', ' ', vertical_hints.count('+')-1) # add a pipe to each row of horizontal hints, then join it with newlines horizontal_hints = '\n'.join([''.join(a + ['|']) for a in horizontal_hints]) # add and return return vertical_hints + '\n' + horizontal_hints ``` A few changes were made for readability sake (`g` being split into three named functions, complex list comprehensions made into `for` loops) but logically it works exactly the same way. Which is why it's confusing that this one doesn't print extra spaces and newlines, while the golfed one does. ยฏ\\_(ใƒ„)\_/ยฏ ]
[Question] [ This challenge takes place on a grid. ``` +----------+ | | | | | | | | | | | | | | | | | | +----------+ ``` This one's 10 x 10, but it can be any rectangular shape. There are four directions on this grid. Up, down, left and right. The task is to draw a path starting with an upper case direction initial. In this example, will go directly upward from the U. ``` +----------+ | | | | | | | | | | | | | | | | | U | +----------+ ``` The path will go upwards and be comprised of full-stop characters (.), until it hits a wall, when it will terminate with an asterisk (\*). ``` +----------+ | * | | . | | . | | . | | . | | . | | . | | . | | U | +----------+ ``` In addition to path starts, there's also direction changers, represented by a lower case direction initial. ``` +----------+ | | | | | | | r.....*| | . | | . | | . | | . | | U | +----------+ ``` Also, an upper case X us an obstacle which will terminate the path. ``` +----------+ | | | | | | | | | r...*X | | . | | . | | . | | U | +----------+ ``` --- # Rules * The input is a string consisting of a frame, (consisting of |, - and + characters) containing characters denoting path starts, direction changers, and obstacles. * Your code should add full stop characters to follow the path described by starts and direction changers, and an asterisk when/if the path meets a wall or obstacle. * There can be multiple path starts. * The code will still terminate without error if the path describes a loop. * If a path meets a path start, it will act as a direction changer. * It's code golf, low-byte code and no standard loopholes, please. * I always prefer links to an on-line interpreter. --- # Test Cases ## 1: Simple ``` +----------+ | | | | | | | | | | | | | | | | | U | +----------+ +----------+ | * | | . | | . | | . | | . | | . | | . | | . | | U | +----------+ ``` ## 2: Right turn ``` +----------+ | | | | | | | r | | | | | | | | | | U | +----------+ +----------+ | | | | | | | r.....*| | . | | . | | . | | . | | U | +----------+ ``` ## 3: Crossroads ``` +----------+ | | | | | | | r d | | | | u l | | | | | | U | +----------+ +----------+ | * | | . | | . | | . r..d | | . . . | | u....l | | . | | . | | U | +----------+ ``` ## 4: 4 Crossing paths ``` +----------+ | D | | | | | |R | | | | L| | | | | | U | +----------+ +----------+ | * D | | . . | | . . | |R........*| | . . | |*........L| | . . | | . . | | U * | +----------+ ``` ## 5: First Loop ``` +----------+ | | | | | | | r d | | | | u l | | | | | | U | +----------+ +----------+ | | | | | | | r..d | | . . | | u..l | | . | | . | | U | +----------+ ``` ## 6: Starter as changer ``` +----------+ | | | | | | | L | | | | | | | | | | U | +----------+ +----------+ | | | | | | |*..L | | . | | . | | . | | . | | U | +----------+ ``` ## 7: Straight Loop ``` +----------+ | | | | | | | | | r l | | | | | | | | U | +----------+ +----------+ | | | | | | | | | r..l | | . | | . | | . | | U | +----------+ ``` ## 8: Tight Knot ``` +----------+ | | | | | | | d l | | r u | | r u | | | | | | U | +----------+ +----------+ | * | | . | | . | | d..l | | .r.u | | r.u | | . | | . | | U | +----------+ ``` ## 9: An Obstacle ``` +----------+ | | | | | | | | | r X | | | | | | | | U | +----------+ +----------+ | | | | | | | | | r...*X | | . | | . | | . | | U | +----------+ ``` ## 10: S Shape ``` +----------+ |r d | | | | XXXXXXXX| | d l | |ul | |XXXXXXX | | | |R u | | | +----------+ +----------+ |r.....d | |. * | |. XXXXXXXX| |.d......l | |ul . | |XXXXXXX . | | . | |R.......u | | | +----------+ ``` ## 11: 4-Way Knot ``` +----------+ | D | | | | r | |R d | | | | u L| | l | | | | U | +----------+ +----------+ | * D | | . . | | r.....*| |R....d. | | .... | | .u....L| |*.....l | | . . | | U * | +----------+ ``` ## 12: Busy Junctions ``` +----------+ |rrrrr rrrd| | rlrl | |ul rrd | |ruX X | |udl ll | |ull | |rlr | |rdr d | |Uruull | +----------+ +----------+ |rrrrr.rrrd| |.rlrl .| |ul rrd .| |ruX.X. .| |udl.ll .| |ull. .| |rlr. .| |rdr..d .| |Uruull *| +----------+ ``` ## 13: Starts Into Edge ``` +----------+ | U | | | | | | | | | | | | | | | | | +----------+ +----------+ | U | | | | | | | | | | | | | | | | | +----------+ ``` ## 14: Crossing Dead Paths ``` +----------+ | | | | | | | R | | | | | | | | | | U| +----------+ +----------+ | *| | .| | .| | R..*| | .| | .| | .| | .| | U| +----------+ ``` [Answer] # JavaScript (ES6), ~~191 183~~ 181 bytes *Thanks to @tsh for helping fix a bug* Takes input as a matrix of characters. Outputs by modifying the input. ``` f=(a,X,Y,d,n=0)=>a.map((r,y)=>r.map((v,x)=>(a+0)[i=' .*dlurDLUR'.indexOf(v),n]?X?X-x+~-d%2|Y-y+(d-2)%2?0:~i?f(a,x,y,i>2?i&3:d,n+1,r[x]=i?v:'.'):n?a[Y][X]='*':0:i>6&&f(a,x,y,i&3):0)) ``` [Try it online!](https://tio.run/##vZZtb9owEIC/71eckErikqSMTvuQKUTb2KRtSJ1gaKkQHzycgivXiRybgdb1rzObhFfB6HiZI6Jc7s5@fPHdcY9HOOsLmkqXJySeTu8CGzuRc@sQhwdVFNSx94BT2xbORAsiF0bOWAs2rlRRlwYWeJeEKdFodlqWRzmJxzd39gg5vBdGYeSOK08uuag93rqTik3cGrqohVX/iYZ3eqmxM3FovRbS8rWvl6y8dER33AtoOPItz0I@D3H3tteNeoF1aflVn9Zfl8sLx/I18qsITWWcSQjAllSy2AGCJUYQ1OEX9BOeJSz2WDLItegNaHdtbIy8LGVU2taVhWY7E8ap63me6CFtuOqMlwbCu08oty0LGaPfL16Y5e1Smz6kLC45sDZKFXcxKlePS8XjuYXOXFglKKGCtkUHQwlSCb5KfDCtOC/te5FkmUgwyU5FS7ZplHlgR9O@ghkv5QNIsRwWzFtpG/sWa@3fVPM42o9U6OxpJkl61tiCie7xsW1LLGQsAGfQH2I@iIWhPpi2ed5z25YCzxJtLbynqQnieeH8B9pvM9QvPJGnOAkk51vQqoVQPB9J@5bDzY9M4v5a0T1ZbAGik54EaA9xutkeNmjzKro9faJiGIHk75nRKLZiVtj8pY6oTc32CuZ@x5PnnYTGvobQmu9pawTVegVjh8T2ncom8FnxvqS6Y8@JN2NrBugfMVMKJth8fh1B/bYQhIogWmgIA8YWZmzJpP1XBCKWO@wIpeY@uytYBp@4TOADGcS7ukPnP/1PgP2d13SyRowJfC3a2TFZ1joBbWcHbTPRpMzcfuLJrnrb0N/LXGBOwvwzEjN/kVd5Yh2igTUzlV8R26Sd/gE "JavaScript (Node.js) โ€“ Try It Online") ### Commented ``` f = ( a, // a[] = input matrix X, Y, // X, Y = coordinates of the previous cell d, // d = current direction (0 .. 3) n = 0 // n = number of iterations for the current path ) => // a.map((r, y) => // for each row r[] a position y in a[]: r.map((v, x) => // for each character v at position x in r[]: (a + 0)[ // i = ' .*dlurDLUR' // i = index of the character .indexOf(v), // blocking characters '-', '|' and 'X' gives -1 n // by testing (a + 0)[n], we allow each cell to be ] // visited twice (once horizontally, once vertically) ? // if it is set: X ? // if this is not the 1st iteration: X - x + ~-d % 2 | // if x - X is not equal to dx[d] Y - y + (d - 2) % 2 ? // or y - Y is not equal to dy[d]: 0 // ignore this cell : // else: ~i ? // if this is not a blocking character: f( // do a recursive call: a, // pass a[] unchanged x, y, // pass the coordinates of this cell i > 2 ? i & 3 : d, // update d if v is a direction char. n + 1, // increment n r[x] = i ? v : '.' // if v is a space, set r[x] to '.' ) // end of recursive call : // else (this is a blocking character): n ? // if this is not the 1st iteration: a[Y][X] = '*' // set the previous cell to '*' : // else: 0 // do nothing : // else (1st iteration): i > 6 && // if v is a capital letter: f(a, x, y, i & 3) // do a recursive call with this direction : // else ((a + 0)[n] is not set): 0 // we must be in an infinite loop: abort ) // end of inner map() ) // end of outer map() ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~283~~ ~~279~~ ~~293~~ ~~288~~ 279 bytes ``` e=enumerate def f(M): s=[(x,y,c)for y,l in e(M)for x,c in e(l)if'A'<c<'X'];v=set(s) for x,y,C in s: d=ord(C)%87%5;q=d>1;X,Y=x-d+q*3,y+~-d-q;c=M[Y][X];N=(X,Y,[C,c]['a'<c<'x']) if'!'>c:M[Y][X]='.' if(c in'-|X')*('/'>M[y][x]):M[y][x]='*' if(c in'udlr. *')>({N}<v):v|={N};s+=N, ``` [Try it online!](https://tio.run/##zVdRb9owEH5efoVXqXJiwk10mjZBjTQVVXugncSElorxQDFomVygDqlAY/vrzI6TYKKU0C60GCHy5c72d1/Ol2O2nP@cTs7W6xEdTcK7kRjMRxYbjdHYvnLqFgpoz164S3fojKcCLV2O/AkaSZuCC3eoIXf8Mf6Mz4fn2MP9xgMNRnM7cCykvZbuhfIL6tYbRqeC2RfO6aePpx8a95Q1aw3PvaGLKqvck/fusvK3yqr3jSG96t30e16/cU1t6eD2Ltxhv4cH0SYL3HesN3LPt7g5rMeeFANWN21FCldXHnaIjd/h5lVv2e8t@k49vqCYGI4h4wIQwU7T/n395/zBqT@sqLxqBBV67a6/ffn6ndYiSS7tgXurRBE1ejeY2dwP5u4Aghn35zb@McGOitgWNfkjzjYutxmXmfAnc7UIFWcW8sdI7SGXjdSKBBa1euSEMfya@hOpr6XGpX1yclKppqNirVA6VocG3QSYDCQhN48UMWfC4cBjpJz/VEu8qFr7kgI1yFGqxfIsobrg5apFzJmwA0i1WApAKxGRUiLyA6nVKgq2Uyxqu@yT2DLjgxzQgXiQrIUklvbOBTQp8pK5hVR28dc7iSxfhvBwubUPsfbR1S2ZQe1jrfLZROPHUOWzicaPRC2m9UnVClMQX5esFjGXgUcA0/poAAIMUhAeVW4h5B1fbgHxSsutPLl0G5Vfv714KMD0fa4sITfcYp8dL9IwaymUS7dRMSkdHUmAQQqYfvNtkQKTFJhbg/kiLSL1jBZCbEfOHnvC4XYLwcs5ii3z9EFORxpFzozeQI4NCJMWgkC2@wKTFHmCWkINJL9MzRZc8CQ@@bDk3RiI0ENeamEccZ668Y0mcr4BmNgo3BVhmMwpzi01ICYFCSkwSYEmBR4kFsYh2kC7cZ2SoEkZgMVdB5ikyP651X2hP4roKbn12qRKKPOdEoh1n1LmiTkT8kEnbeZ3uu0E3T3VasnUVB@kkj45RkzFF9d1XdifY0FbbqH@ePvkVkIKIlJxXWYqvriuA4dnWmDLLSFVeBLjR9hK4upuwsiEUODprP8B "Python 2 โ€“ Try It Online") Takes a list of lists. Outputs by modifying the input array. [Answer] # Perl 5, ~~203~~ ~~188~~ 166 bytes ``` $l='\K[ a-z](?=';$t='([-|X])?';$s=$_;/ /;$n='.'x"@-";{$_|=s/(?|R[.*]*$l$t)|$t${l}[.*]*L)|D$n(?:[.*]$n)*$l$n$t)|$t$n$l$n([.*]$n)*U))/$&eq$"?$1?'*':'.':uc$&/es?redo:$s} ``` [TIO](https://tio.run/##zVVNa8JAEL37KxYZ3ESJsYdeEsL24K2ehEDAikg3h8IQ7SYLpa5/vWm2@VCDbcBGzUBg3s7HvrzMbrahwMc0BfToy/OCrK3PpcE86kLiUWNhqWBpsgzFHqxcu2e7EHl0TD/6T1bf3cFKebFtMDVfjIfLISAkpoIEdrj/WZiZagqRwRyNIDJ1RlTkRNo3yoBvmjYMwnfoM3hgdEidbBdHvsLADmMmQr5xIN6nmgil6ciqbNRTpDJ1beCX4IRB71I@ont8@LmI1A62y2fa1G7eTHvWEX2IVghv/71mHZufulh4Xz48Z1DxkRUo/HvrQ0hwBX3yW@X8oAaFacDzddQRiUdpRc4fZ1LWIxefd3Ham/@mgjw97/gffbSR7OG6SKDAskOmQrZaACEDElQRjgSxSsPDrln9EeDi8A6@kLKsadDHv9H/i7Q@z/MW@Pg1Pl@bbfK2ieLU2k4m3w) How it works * `$s=$_` to save input into `$s` to restore lowercase changers. `$_|=$s` because bitwise or with space will not change `.` and `*`, lowercase letters `urld` will be restored with bitwise or operation. * `/\n/;$n='.'x"@-"` to get "width" and `$n` to match any character "width" times * `$l='\K[ a-z](?=';$t='([-|X])?'` to reduce regex length ; `$l` to match a lowercase letter `urld` or a space on a path, `$t` to match a terminator. After replacement : `(?| R[.*]*\K[ a-z](?=([-|X])?) | ([-|X])?\K[ a-z](?=[.*]*L) | D$n(?:[.*]$n)*\K[ a-z](?=$n([-|X])?) | ([-|X])?$n\K[ a-z](?=$n([.*]$n)*U) )` * switches `/e` to eval, `/s` so that `.` (inside `$n`) matches also a newline character * `$&eq$"?$1?'*':'.':uc$&` if matched is a space, if termiator matched `*` otherwise `.` otherwise uppercase. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 409 bytes ``` import StdEnv,Data.List q=flatlines $m=foldl(zipWith\a b|a=='*'||b=='*'='*'=max a b)(q m)[q(foldl(\m(_,y,x)=[[if(b<>x||a<>y)if(k=='*')'.'k'*'\\k<-r&b<-[0..]]\\r<-m&a<-[0..]])m(last(takeWhile(not o hasDup)(inits(f 0y 0x)))))\\l<-m&y<-[0..],c<-l&x<-[0..]|isUpper c] where f a y b x=let(u,v)=(a+y,b+x)in(case toLower((m!!u)!!v)of' '=[((a,b),u,v):f a u b v];'r'=f 0u 1v;'l'=f 0u -1v;'u'=f -1u 0v;'d'=f 1u 0v;_=[]) ``` [Try it online!](https://tio.run/##hZNRa6swFMef66c4XUdNbrXrXjctXOh9GBR2YYwNVEbUuIYm2sbY6ua@@vUm2pZxX24gnPxyzv@fEyUJpyTvRJFWnIIgLO@Y2BVSwZNKf@UHZ0UUma9Zqay9n3GiOMtpaV0LPyt4ytEH270wtQkJxC3xffuH3bZxH/spSA06hdEeBA72aBCFAr05jVNjPwhYhmJvWbct8ZYN1rTt1die21sdw3DruXIae26wmM@jKAyl54opOTMWiJNSIUW29GXDOEV5oaCADSlX1Q4jljNVogwWDSxqbEYYcuPQnBycxHP5tD5Ry8rn3Y5KSCLruKGSQqb7byCG2udUoco5YB@RWePEsxqzHCWkpKCKdXGkEiExHld4PD7gIrPB9gOEiBNjx6jujFGljQ7RvS1tX7dUwe3h3uantWugMuDeVrDQkBoY1m9@EOHLn2lKRcX84dF6UkTz0RpNAPU/xoEjBh8kJelPztdmy6RvbibQ53Xuc/I5ScLQXFvvfOnPocMA5Zc18uF6KB3ub43@9TqfdTqKHgh/eIR3qkxFX9D2BuAt4epK4/@aG@kzURAkEIaQgOfe9fJoCGVkVL1poXRDR1bSs6RPdTP3MmZWK80APdPWakFyycEMDRXX2@kJZPUKr5dMyoHzS9mgGMq4/AaphrPBs6yqs@Z7B38S/Ujey859WHerJieCJQP81m8nK6To3Pgv "Clean โ€“ Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 250 bytes ``` def f(G,e=enumerate): for i,k in e(G): for j,l in e(k): v=X=x=y=m,=l, while(m in'-X|')<(l in'DLRU')>(X in v):v+=X,;y,x=zip((1,0,0,-1,y),(0,-1,1,0,x))['DLRU dlru'.find(m)%5];G[i][j]=(m,'.*'[G[i+y][j+x]in'-X|'])[m<'!'];i+=y;j+=x;X=x,i,j;m=G[i][j] ``` [Try it online!](https://tio.run/##nVJRa8IwEH6evyJ7GJcsp8zBXqzZ00CEPQ2EQsjDoCmmJrWU1rXD/96lTpwd2ukIfNx9uS/33ZGsLpbr9LFpIh2TmM5QC52WTufvhWaTAYnXOTG4IiYlms48c9MyCdpvZtUyZCNCUYlaOBQWff6xNFZT50tgGG6BTWlbDi@vbwtgzzRstRs22XARYlBjJT5NRukYH/wZjrFmSHdBy1SMyZ2SRDYvYRSbNKKO3T2pYCaNkokS1CGM7kH6nNee4ZXad1ZMuincggoMF3WQcFEF3ioaTAIn9vpmLkyalQVlg5jO2SDLTVqQeSMlcEACw6uBg0IiYdvG@TkgJ7iohe2R@qfIdiNyDo7VZbf8V5@/1PnhifBwH17XO@oasL32Tzvvn7bHue1u@kp1dEJ90dYW3dWVF8/9/7@mvgA "Python 2 โ€“ Try It Online") Takes a list of lists of 1-char strings, as explicitly allowed by the OP. Changes the list in place. For easier I/O, use [this](https://tio.run/##TZBda8MgGIWvl1/hLoY6bdgKvUnqrgalsKtBIZAJLWioqdpgki6O/PdM@0VfUTyP5/jV@G5/tPNpErICFVpRyaTtjXS7TuIsAdXRAUUPQFkg0SqQp0hqqi/kEAk4sYINzDNDmaZB/@6VlsgEC5wVI8RLFO3w8@t7A/EHKmL2hLMTYQXNPR3Yn2oQeqdvoc3eqccUnSeRDBiX5yQQ2vUwrZQVyOCXBc9XpeJlzRkyFKavsAya@EDIwK8nc1yaJXyGPFeE@bwmbMjDVamidW7YNT8p0xxdB1rfJmtmdg3Squ1okGnbCWVTJ3cC4bRttOoQ/LEQ46RC6zDEz4mPWWeNU7bbqm05z7IFn8jsXiQZXSwQuhiTETjtNIgVRK8DFlfh@gIU9xWhgdZ32yVxsWn3IEQQtw02ru9vmccb/AM). ]
[Question] [ Imagine an arsonist walking around the town and picking its victims according to a very specific pattern (Or, alternatively, *Imagine a bee flying around the garden and picking its flowers to pollenize according to a very specific pattern*). Let's say the town is an **N ร— N** matrix, where **N** is an integer higher than or equal to **2**. The arsonist starts from the upper-left corner and successively sets the house **M** spots in front of them (where **M** is the number of the house they're currently in), while changing the direction it's moving in after each fire, in the order East โŸถ South โŸถ West โŸถ North โŸถ East โŸถ South... and so on. The *lullaby* of the arsonist is the value of **M** that makes them exit the town (i.e. the last house they visit before stopping the abomination). This is way easier to understand with an example. Take the following matrix for instance: ``` 3 2 3 2 7 3 1 4 1 6 2 5 3 1 1 4 4 3 2 4 1 1 1 1 1 ``` * We start in the upper-left corner, so **M = 3** (`X` marks the current and previous positions of the arsonist): ``` X 2 3 2 7 3 1 4 1 6 2 5 3 1 1 4 4 3 2 4 1 1 1 1 1 ``` * According to the known order, it first goes east **M (3)** spots and lands on a **2** so **M** changes accordingly: ``` X 2 3 X 7 3 1 4 1 6 2 5 3 1 1 4 4 3 2 4 1 1 1 1 1 ``` * Then it goes south **2** spots and **M** is now **1**: ``` X 2 3 X 7 3 1 4 1 6 2 5 3 X 1 4 4 3 2 4 1 1 1 1 1 ``` * Now it moves **1** spot to the West and **M** becomes **3**: ``` X 2 3 X 7 3 1 4 1 6 2 5 X X 1 4 4 3 2 4 1 1 1 1 1 ``` * After it moves **3** spots north, it exits the town! Therefore, **3** is this arsonist's lullaby: ``` ย ย ย ย X X 2 3 X 7 3 1 4 1 6 2 5 X X 1 4 4 3 2 4 1 1 1 1 1 ``` Given an **N ร— N** matrix (you can optionally take **N** as input too), find the lullaby of the arsonist. I've written a program with which you can generate more test cases and visualise the path of the arsonist: [Try it online!](https://tio.run/##jVLRitswEHy2vmIxlLM4n0kuaQumvre@lb4U2kJqihIrWK0iGVnhbOi/pyvLsnNtwgUjsKTd2dHMNL2ttVqdTuLQaGOh7VtCKr6HHVM/n5n8nQjLjVAV73IQyqZwYNYI3EjR4q7baW2q8aqfNxQenmCrtcxJpI3gyjIrtAIoAEu42Uyw8AbWJYkqhGNqx7HAT9h46HLjUbFE7OEcqigg/shaG@OIyHB7NAomlPuRDHwAyVXiISmJuLyA8kUfbX0Fprsd5ht/SWZk8DDDPRWwuNL8GdV/waG70k2IZ4FCbZwHSKpJBvmlUDxrGylsQimFvTbDEdrhbM1aWwmVGc6qhI5l8Q8V05IMjjg8r2caFEnHN6WBXklm24rAsAgPdfSGv9ZhJYsUFghOnmsh@YU8hSiFEIX80PymNNyUqv@FPsvMSPu@mCR@NR/drS1TFkIIXu2YA9BdaJkfhrOXJPI6Z6xpuKqS5B8FKSENlqPBn45Ssm2fx@kVIdHbP/BVtEeGYfJs9B5szaFhts5dQAhxUUKfehclPxl5BjyEKtGAu@9301Tsyn5poYZsSnbYVgy6PIaz09YaNJ7SwAsTezqt4BHcek9WsIQ1rnfkEd6C2y3JGk/c7ZosYfz@Ag "Python 3 โ€“ Try It Online") * You may assume that the arsonist *does* have a lullaby (that is, it can actually get out of the matrix). * The matrix will only contain positive integers less than or equal to **9** (digits), for simplicity. Solutions that handle any positive integer are completely welcome. * Note that the arsonist *can* land on a spot they've already burned, in case the sense they're moving in is different from the first time. In such a scenario, just take the value of that element and move again as usual. * You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins. ## Test cases ``` ------------- 9 2 3 1 7 2 8 7 6 Lullaby: 9 ------------- 2 1 2 1 3 1 1 2 1 2 2 1 1 1 1 3 Lullaby: 2 ------------- 3 2 3 2 7 3 1 4 1 6 2 5 3 1 1 4 4 3 2 4 1 1 1 1 1 Lullaby: 3 ------------- 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 Lullaby: 2 ------------- 3 2 1 2 1 1 1 2 3 2 3 2 1 1 2 1 1 1 3 1 2 3 1 1 1 1 1 1 4 5 2 3 1 1 1 1 2 1 2 1 2 2 1 2 2 3 2 1 2 Lullaby: 3 ------------- ``` The matrices in a different format: ``` [[9, 2, 3], [1, 7, 2], [8, 7, 6]] [[2, 1, 2, 1], [3, 1, 1, 2], [1, 2, 2, 1], [1, 1, 1, 3]] [[3, 2, 3, 2, 7], [3, 1, 4, 1, 6], [2, 5, 3, 1, 1], [4, 4, 3, 2, 4], [1, 1, 1, 1, 1]] [[1, 2, 1, 2, 1, 2], [1, 2, 1, 2, 1, 2], [1, 2, 1, 2, 1, 2], [1, 2, 1, 2, 1, 2], [1, 2, 1, 2, 1, 2], [1, 2, 1, 2, 1, 2]] [[3, 2, 1, 2, 1, 1, 1], [2, 3, 2, 3, 2, 1, 1], [2, 1, 1, 1, 3, 1, 2], [3, 1, 1, 1, 1, 1, 1], [4, 5, 2, 3, 1, 1, 1], [1, 2, 1, 2, 1, 2, 2], [1, 2, 2, 3, 2, 1, 2]] ``` The fifth test case is [very interesting to visualise](https://tio.run/##jVJdi9swEHy2fsViKGdxPpOP64s531vfSl8KbSE1RYkVrKsiGVnhbOh/T1eWZefahAvBwSvvzo5mpultrdX6dBKHRhsLbd8SUvE97Jj69crk70RYboSqeJeDUDaFA7NGYCFFi1W309pU46d@Lig8PMNWa5mTSBvBlWVWaAVQALZws5lg4QM8liSqEI6pHccGv2HjocuNR8UWsYdzqKKA@BNrbYwrIsPt0SiYUO5HMvAEkqvEQ1IScXkB5as@2voKTHc7zHf@lszI4GGGey5gcWX4C6r/hkN3ZZoQzwKF2jgPkFSTDPJLoXjWNlLYhFIKe22GI7TD2Zq1thIqM5xVCR3b4p8qpiUZHHF4Xs80KJKOd0oDvZLMthWBYREu6ugNb63DShYpLBCcvNZC8gt5ClEKIQr5oflNabgpVf8LfZaZkfZ9MUn8bj66W0emLIQQvDsxB6C7MDJfDHcvSeR1zljTcFUlyT8KUkIabEeDPx@lZNs@j9MrQqK3f@CbaI8Mw@TZ6D3YmkPDbJ27gBDiooQ@9S5KfjPyDHgIVaIBdz/upq04lb1ooYZsSnbYVgy6PIaz09YaNJ7SwAsTezqtYQXL4cEfWYGr/ZmrhlOssYOsx8p3PsLHodNXywllhZ3D/4iy@gs). [Answer] # [MATL](https://github.com/lmendo/MATL), 32 bytes ``` JQ6*`G5thYay&Zj3$)wyJ2@-^*+8M]b& ``` [Try it online!](https://tio.run/##y00syfn/3yvQTCvB3bQkIzKxUi0qy1hFs7zSy8hBN05L28I3Nknt//9oYwUjBRA2twZShgomQGxmDeSbgrmG1kARE7ACE2sQHwJjAQ) Or [verify all test cases](https://tio.run/##y00syfmfEOFZ8d8r0EwrwdO0JCMysVItKstYRbO80svIQTdOS9vCNzZJ7X@ES1lFyP9oSx0FIx0FY2sFQx0FcyDbWsECzDCL5YoGShiCpQ2tFYzBbEOwCoggRNwQJm4M1GAMMQxMmsP0mIBJM2uQoKkOzCBrkLgJTLEJkkEgBDQLajOctFaglQjc4XAhiAPhXoHLQgQRXoaZaKyD6nyY/0xh2uGC6HajhifCGbEA). ### How it works The input matrix is padded with a frame of five zeros, so for example ``` 3 2 3 2 7 3 1 4 1 6 2 5 3 1 1 4 4 3 2 4 1 1 1 1 1 ``` becomes ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2 3 2 7 0 0 0 0 0 0 0 0 0 0 3 1 4 1 6 0 0 0 0 0 0 0 0 0 0 2 5 3 1 1 0 0 0 0 0 0 0 0 0 0 4 4 3 2 4 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` The frame of zeros is used to detect when the ~~arsonist~~ bee has exited the matrix. The extension with five zeros ensures that a *modular* displacement of length up to `9` in any direction from any of the nonzero entries will correctly land in a zero without wrapping around to some non-zero entry. In matrix coordinates, the bee starts at entry `(6,6)` of the extended matrix. It reads that entry, and updates the coordinates as required, applying a (modular) displacement of the read length in the corresponding direction. This is repeated in a loop until the read value is `0`. The entry that was read before that one (i.e. the last non-zero entry) is the output. The coordinates are actually stored as a complex number, so for example `(6,6)` becomes `6+6j`. This way the four cyclic directions can be realized as powers of the imaginary unit. The corresponding power (`j`, `1`, `-j` or `-1`) is multiplied by the read entry to obtain the complex displacement which is used for updating the coordinates. The successively read values are kept on the stack. When the loop is exited, the stack contains all non-zero read values in order, then the last read value which is `0`, then the latest complex coordinates. So the third-top element is the required output. [Answer] # JavaScript (ES6), ~~70~~ 68 bytes ``` m=>(g=d=>(n=(m[y]||0)[x])?g(--d&3,x-=d%2*(y+=--d%2*n,L=n)):L)(x=y=0) ``` [Try it online!](https://tio.run/##tVFLDoIwEN17CjaaVouhlo@ajF6AGzRdGFCi0WLUGEi8O5ZC@QWXbibT9968@fRyeB@e0eN8f9kyjY/FCYob7FACsYoS0I3n4vNxMM8E3ifItuMZI5kN8XQ1R/kCFKAySUKQGG9DjDLIwcFFlMpnej0ur2mCTojzDbFWxGKCWJwSK1CvMl3r1BcC48mwQsmpLqKlkukXresqwnDUcGzUiFWtdQxaL1dHvwQU4WkFrR1dTVclbq@FVox1qWdtYjvmH7Hf6zYis1JzgoY3cHu@thPr7tu7i2dMOvBwruEvsd7ExRc "JavaScript (Node.js) โ€“ Try It Online") ### Commented ``` m => ( // given m = input matrix g = d => // g = recursive function taking the direction d (n = (m[y] || 0)[x]) ? // let n be the content of the current cell; if it's defined: g( // do a recursive call: --d & 3, // with the next direction (0 = E, 3 = S, 2 = W, 1 = N) x -= // update x by subtracting ... d % 2 * ( // ... ((d - 1) % 2) * n y += --d % 2 * n, // and update y by adding ((d - 2) % 2) * n L = n // save n into L ) // end of x update ) // end of recursive call : // else: L // stop recursion and return L )(x = y = 0) // initial call to g() with x = y = d = 0 ``` Given that the sign of the modulo in JS is that of the dividend, the direction is updated this way: ``` d | d' = --d&3 | dx = -(d%2) | dy = --d%2 | direction ---+------------+--------------+------------+------------------ 0 | 3 | -(-1%2) = +1 | -2%2 = 0 | (+1, 0) = East 3 | 2 | -( 2%2) = 0 | 1%2 = +1 | ( 0, +1) = South 2 | 1 | -( 1%2) = -1 | 0%2 = 0 | (-1, 0) = West 1 | 0 | -( 0%2) = 0 | -1%2 = -1 | ( 0, -1) = North ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 18 bytes ``` ๏ผฐ๏ผณโ†ถ๏ผท๏ผซ๏ผซยซโ‰”ฮนฮธร—๏ผฉฮนยถโ†ทยปโŽšฮธ ``` [Try it online!](https://tio.run/##JYyxDoIwFEVn3lc0ndoEh1dGJ8NkoglRN3FoSIUXa0FacDB@ey24nZuTe5pOj02vbYzHyQYaRnJB7N0whXNI3Aopt1DR3IeDuQeRxrsja5iojHkkyT6Q7byn1gnK2Sv5rFobF3oaL0rtgyCZM147Lle7tE7UdmvsC6U1elzwf0uFGK@c8xoUKoQCUQGqRIhYQBK3uJntDw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฐ๏ผณ ``` Print the input string, but don't move the print position. ``` โ†ถ ``` Rotate the pivot left, so that the print direction is now up. ``` ๏ผท๏ผซ๏ผซยซ ``` Repeat while there is a character under the print position. ``` โ‰”ฮนฮธ ``` Save the character in a variable. ``` ร—๏ผฉฮนยถ ``` Cast the character to a number and print that many newlines. As the print direction is now up, this ends up printing horizontally. The upshot is that we've moved the print position in the desired direction by the amount given by the number under the print position. ``` โ†ทยป ``` Rotate the pivot so that the next newlines move the print position in the next direction clockwise for the next pass of the loop. ``` ๏ผฆโŸฆฯ‰ฮธโŸงยฟฮนฮนโŽš ``` Unfortunately we still have the input cluttering our canvas, and even more unfortunately, if we clear the canvas we also clear our variable. So, this is a bit of a trick: a list of the empty string and the variable is looped over. On the first pass of the loop, the loop variable is empty, so the canvas and the loop variable and the result variable are all cleared. But the loop is not finished! On the second pass of the loop, we still get to access our variable carefully preserved in our loop list. It simply remains to print it. ``` โŽšฮธ ``` Clear the canvas and print the saved variable. (Thanks to @ASCII-only for the fix to Charcoal.) [Answer] # [Python 2](https://docs.python.org/2/), ~~85~~ 84 bytes ``` a=input();x=y=e=0;d=1 while-1<y<len(a)>x>=0:v=a[y][x];x+=v*d;y+=e*v;d,e=-e,d print v ``` [Try it online!](https://tio.run/##tVA9b4MwEJ3Dr/BGPogUB9JKcS5bunbpZnmg@KSgRoAsQu1fT20TA8ne5cn33t3zu2tMe62rfV/UEgmQOI77HMqqubfLFdNgAGHHJNDo91recEtP5nTDapmvzvoMu2MHOTeCa8H0Brq1ZGYDuO6YTBC2mMioUWXVkq63xoMF@VJ3PEaLVhmLC9RYEPd5ZJ8FNi25fH5clKqVU78V5j895/uE0IQ4FAnhqa8c4apBCBoNWipExF2rVQZ8n2Yzj2@OsMLBd9CHQ@blYSR7svQdzvWRZcQpxj9y0zojGSKPK456oKdzTM7pfJ@nvQ/BZEa/5ni9ejpL@Ac "Python 2 โ€“ Try It Online") Tip o' the hat to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for 1 byte. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ ~~49~~ ~~46~~ ~~34~~ ~~33~~ 26 bytes ``` ๏ผฎฮธ๏ผฅฮธ๏ผณ๏ผญฮธโ†‘๏ผท๏ผซ๏ผซยซ๏ผญ๏ผฉฮนโœณโŠ—๏ผฌฯ…โŠžฯ…ฮนยปโŽšโŠŸฯ… ``` [Try it online](https://tio.run/##LY5BDoIwEEX3PUWX0wQXQiIqS9iYiGliPEDFCTTWtpQWF8az10Kc3Zv3Z/K7QbjOCBXjSdvgL@F1Rwcjqwh3UntohYUxo6u8@rTqgbFkWzPjIo43m@g9SIUUOOIzafohNM0aqcXkQbKMNtJh56XR0JhwV/iAM@reDxDY@nC54GFKnFGZ@EtqhcIB@xfhxi7RKsaCHPKCbMuc7Mtd3MzqBw) Link is to the verbose version of the code Input must be **N** on its own line, then the lines of the array on separate lines after that. Any ways to knock off bytes are welcome and wanted, as I am not a good golfer in Charcoal! -12 bytes thanks to @Neil! -1 byte thanks to @ASCII-only! -7 bytes thanks to @ASCII-only (changed a bug that made `Clear` reset variables) [Answer] # [Red](http://www.red-lang.org), 145 bytes ``` func[b][h:[0 1 0 -1 0]x: y: 1 i: 0 until[y: h/(i: i % 4 + 1) *(t: b/(y)/(x)) + y x: h/(i + 1) * t + x none = b/(y) or(x < 1 or(x > length? b))]t] ``` [Try it online!](https://tio.run/##pVDLbsMgELz7K@ZSCVpFNsZ5obb5h1wRFzd2bCkikUUk/PXuGmji9lpZa2aGYXZhaE7TsTlpk7Vqau/2S9dGd0oXECiwop/xCqMi2isU2d26/qKJdzkjoccLKrxBcLwyp1DnbOQ585yTOMJHXzLAEfCwV9vgI1pxHZjHO6UH8IlLY8@uO6Dm3Dgz3YbeOrTQeo8S0kALbFHSuqN1Y0z2dJSUQkV7kpAIrlmJmgia/HVCzplU23SmotoQLrFGyCBckTp7qkfGrC9TQtdYqeN/2d8Zox7niRNHNfJ0s5QjIZ5fmH8d/D980WfxQvLRefoG "Red โ€“ Try It Online") ## More readable: ``` f: func[b][ h: [0 1 0 -1 0] ; step lengths (combined for x and y) x: y: 1 ; starting coords (1,1) i: 0 ; step counter until[ y: h/(i: i % 4 + 1) * (t: b/(y)/(x)) + y ; next y; t stores the lullaby x: h/(i + 1) * t + x ; next x none = b/(y) or (x < 1 or (x > length? b)) ; until x or y are not valid indices ] t ; return the lullaby ] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 62 bytes ``` {$^w;$^m[0,{$_+$m[$_]*(1,$w,-1,-$w)[$++%4]}...{!$m[$_]}][*-2]} ``` [Try it online!](https://tio.run/##RY3dDoIwDIXv9xQ1qYafQdwYoEF9kWUQL@RKosELQpBnnysjkqVNe87pt/ejfxa2G@HQwtVOWA8V1p0@8gmbGDuNjYkCwXHgieAJDqHGON4rM6dpOu18YDY6SqSZ7ec@Qht8sQmhffUsuLAzSMiYgBIkO7lesBuHLOTkZeS5Kt0kQLkqmIQcaBNMOYVc5a7XR7f5diuWIt1zvEabzxNHLuyNoBxfwqox8adIl1z6SpH0VxlW9gc "Perl 6 โ€“ Try It Online") Takes the matrix as flat list and width. [Answer] # [Clean](https://clean.cs.ru.nl), 141 bytes ``` import StdEnv d=[0,1,1,0,0,-1,-1,0:d] $m[x,y]n[a,b:l]#r=size m #u=x+a*n #v=y+b*n |0>u||0>v||u>=r||v>=r=n= $m[u,v]m.[u,v]l ?m= $m[0,0]m.[0,0]d ``` [Try it online!](https://tio.run/##VU9Nb4MwDL3nV0TKTqu7EthnpbSX7TBph0k9Ig4plCkSCRNNEAz462MGStvJll/8nDy/xNlBml7nicsOVEtleqW/88LSnU3eTEkSEXrAMTyMJR/SWycRudFhBXVkQgn7dRaxQhzVDyoQ5kS1kLeGsFLUiz0eWm/jWixl27qNKNq2xCqMoKjhoIz03QgZ2eqRw00DN0DS76wsLFmtGJqzhaqooE3zAj4EHTQcnsBHfEZ87DpyfYk1LADqA@VzHbID2mA3Tc7zmeZzBtOzgQ6u6LNIcw/0Yda4sPz/Qn@UOLHX@/zRa@pMbFVu0O2WiEs7/aH/jdNMfh375ftH/1obqVU8NZ@ZtGle6D8 "Clean โ€“ Try It Online") Defines the function `? :: {#{#Int}} -> Int`, taking an unboxed array of unboxed arrays of integers and returning the result. [Answer] # Java 8, 121 bytes ``` m->{int l=m.length,x=0,y=0,f=0,r=0;for(;x*y>=0&x<l&y<l;x+=f<1?r:f==2?-r:0,y+=f==1?r:f>2?-r:0,f=++f%4)r=m[y][x];return r;} ``` [Try it online.](https://tio.run/##3VRNb4JAEL37K/ZSA3Ul8qG24uovqBePhANFsFhYzbJaCNnfToeFxPbm9FjgkTDMy7x5M9lTdIump8NnG@dRWZK3KOPNiJCMy0SkUZyQXfepAyQ24B2EQUgK04eoAsBTykhmMdkRThhpi@mm6ZJzVlh5wo/yg1ZsRmtAChBs5qdnYfjVc71hs3G1zsf1OverCUvX9lasUsac7VSsgAIhxnRsM4RSNpmkT54pWBHUYVCFvkjkVXAifNX6vZzL9T0HOYOq2zk7kAK6MvZSZPwI4iOzb2lflzIprPNVWhf4JXNucCs2ePJFhj6b5pU61FVU5z9wNTZdUgeR/wL5C6VM7edjkhxqgygbUcQFho2S1VXA1bB1DRfXitu5C1gim/EACwTHoXOqTUBwPKjSafPQJnR1UDboefZAzui/s9Db1BNxk@53sGfjeMPSIxt0qX2/URs51zqxvB@G/uEQcH@PQo1U@w0) Alternative with same **121 bytes** byte-count: ``` m->{int l=m.length,x=0,y=0,f=0,r=0;try{for(;;x+=f<1?r:f==2?-r:0,y+=f==1?r:f>2?-r:0,f=++f%4)r=m[y][x];}finally{return r;}} ``` Uses try-finally instead of checking if the `x,y`-coordinate is still within bounds. [Try it online.](https://tio.run/##3VRNb4JAEL33V@ylCcSVyIfaSld/Qb14JBy2yFosrGZZrYTsb6fDQtL25vRY4JEwzMu8eTPZI7/y6XH/0WUlr2vyygvZPhBSSJ0rwbOcbPtPGyCZA@8kTVJSuTFEDQCeWnNdZGRLJGGkq6brtk8uWeWVuTzod3pjM9oABECxWaxV04qTcuL4NmHixd@olWAs2EzVChIhxJiNrceQYJOJeIxcxaqkSZNbGhtRSF6WTatyfVGSqNiYLh7knC9vJcgZVV1PxZ5U0JWz06qQBxDP3aGlXVPrvPJOF@2d4ZcupSO9zJH5Jxn7bNtnGtDQUJt/x9X6dEkDRP4T5C@Mca2f90kKqA@ifESREBg@SlZfAVfDtzVCXCth7y5giWwmAiwQnIDOqTUBwYmgSq8tQpvQ10HZYOc5ADmj/85Cb9NAxE162MGBjeONS49sMKT@943ayLnVieX9MPQPh0D4exTmwXRf) **Explanation:** ``` m->{ // Method with integer-matrix parameter and integer return-type int l=m.length, // Dimensions of the matrix x=0,y=0, // x,y coordinate, starting at [0,0] f=0, // Direction-flag, starting at 0 (east) r=0; // Result-integer for(;x*y>=0&x<l&y<l // Loop as long as the x,y coordinates are still within bounds ; // After every iteration: x+=f<1? // If the direction is east: r // Increase the `x` coordinate by `r` :f==2? // Else-if the direction is west: -r // Decrease the `x` coordinate by `r` : // Else (it's north/south): 0, // Leave the `x` coordinate the same y+=f==1? // If the direction is south: r // Increase the `y` coordinate by `r` :f>2? // Else-if the direction is north: -r // Decrease the `y` coordinate by `r` : // Else: 0, // Leave the `y` coordinate the same f=++f%4) // Go to the next direction (0โ†’1โ†’2โ†’3โ†’0) r=m[y][x]; // Set `r` to the value of the current cell return r;} // Return the last `r` before we went out of bounds ``` [Answer] # [Perl 5](https://www.perl.org/), 92 bytes ``` sub b{1while eval join'&&',map{/./;map"(\$$_$&=".'$n=$_[$y][$x])'.$',x,'y'}'+<@_','->=0';$n} ``` [Try it online!](https://tio.run/##PYzbCoJAEIbvfYpFBkdpPeeVGV511xOYyAqChumSWYr46m3rgRhmhu/n4@fFsw6E6Pqc5JP7Kau6IMWb1eTeVg1qGtIH45Nt2aH8qn4DyECLVAuhiSBLYEwTGFIDLUA6UBxxxsMpzpCieY4cDKGZBe@7MmY0iS/pPHVsJLkeM0P4xCPuunIUjyy8ZQutqWRpKP5Om3kkwWpu5P5bPGmud2/xvi1/VW3TCfMaWI7rCJPxHw "Perl 5 โ€“ Try It Online") ## How? The set of nested maps and the join produce this: ``` ($x+=$n=$_[$y][$x])<@_&&($y+=$n=$_[$y][$x])<@_&&($x-=$n=$_[$y][$x])>=0&&($y-=$n=$_[$y][$x])>=0 ``` which is then evaluated to determine if the loop ends. Because the Boolean is evaluated left to right, the value of `$n` actually changes (up to) four times during the evaluation. Because Boolean logic short-circuits in Perl, the value of `$n` is the lullaby when the loop is exited. [Answer] # [Python 3](https://docs.python.org/3/), ~~85~~ 84 bytes xcoder: -1 (I never remember the +~ trick) ``` def f(x): r=c=0 while-1<r:d=x[r][c];r,c=len(x)-c+~d,r;x=[*zip(*x)][::-1] return d ``` [Try it online!](https://tio.run/##pVJNT4NAEL3vr5j0AqttIx@2inLwYmLSf4AcEBZLJAtZ1pTa6F@vMwttKRovTrIwH2/fvNndeqvXlfT2@0zkkNstDxioMA2vGGzWRSlmzr0KsrCNVByl8Z2apmEpJOJm6eVXNlV3bRhdfBS1fdHyOAqCmRMjgdDvSkK216LRDYRgWRabDY3dggsec2AJLrvB74Kx1XtZJi/bAG5HWBccRDvMwz96jCKKHRN7g53uaKdHXXAtzV4f1wLZrsEwMR8zVPV7JsqduLwRl9HQrX/5f6vtUKSkU97lHNZnjXK3P4mDZh8ncqHPDXsdz8r70Xs8Hd0QXmXM8kpBWUgBhQRzffNGK7xfPm/qstBUamx6JWhFbqCISJRuNoVe2xaSWX2ZrFaF1Dah@DHX4ovATofQOKL8jWw1pEpw24GsE2PzCN8bP2ciUwilx8yOGRpLVRuaqj1RnhTmFro7RHxanI1Lz1K0tUi1yGCXfE7htdKIRQd20eTx4Wk1mU6qt2Q7iSMVhkk85Dif7tS6nSd1LWRmR9RDcqNQkr7hfDHffwM "Python 3 โ€“ Try It Online") Instead of moving in different directions (E,S,W,N), this solution always moves east and rotates the grid counter clockwise after every move. After rotating, what was the last column is now the first row, so if the row index is less than zero it means we ran off the board. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 161 bytes ``` . $.%`*_#$&* (?<=(.+ยถ)+|^) A ยถA$#1* ~(K`{`^X\1YZยถ1S$4ยถ1XYZยถ2$4$2$4$3ยถ2XYZยถ3Sยถ3XY\1ZยถS X (_$*)(A_$*) Y ( _$*) Z (?=\n\D$*\2\b.$*\3#(_+)) )`S $$4$$2$$3 L$0`_+ $.0 ``` [Try it online!](https://tio.run/##HY2/CsJADMb3PEWhUe4PHE2ubhYpuOnWpS1HewoOLh3ETfGx@gB9sZprQr7vlxCS1@P9nG60rg4ydLtoxhz3BtTpWClnl1nb76Chzpa5xpwM/NQlfuLQBur6ZaYGS9E2MWOJqbzgNvCNVNsFEm6gBTWi0apOCh2obINeXlVhCmc0gcPdiflcjVZr0LEBlINyFT1csYijBXTFunomJiJgL5lcGk8MnraA8sAJgdIes3ja4z8 "Retina โ€“ Try It Online") ]
[Question] [ A [Lyndon word](https://en.wikipedia.org/wiki/Lyndon_word) is a string that is strictly [lexicographically smaller](https://en.wikipedia.org/wiki/Lexicographical_order) than any of its cyclic rotations. Given a binary string, determine if it's a Lyndon word in as few bytes as possible. For example, `001011` is a Lyndon word. Its rotations, listed below, are obtained by repeatedly moving the first symbol to the end. ``` 001011 010110 101100 011001 110010 100101 ``` Of these, the original string comes lexicographically first, or equivalently, represents the smallest binary number. However, `001001` is not a Lyndon word because one of its rotations is the same as itself, which ties it for lexicographically earliest. [A related problem.](https://codegolf.stackexchange.com/q/2862/20260) **Input:** A non-empty binary string or list of digits `0` and `1`. You may *not* use numbers, like `5` to represent `101`. **Output:** A consistent Truthy or Falsey value that says whether the string is a Lyndon word. Built-ins specifically for Lyndon words are not allowed. **Test cases:** The Lyndon words with length up to 6 are: ``` 0 1 01 001 011 0001 0011 0111 00001 00011 00101 00111 01011 01111 000001 000011 000101 000111 001011 001101 001111 010111 011111 ``` The non-Lyndon words of length up to 4 are: ``` 00 10 11 000 010 100 101 110 111 0000 0010 0100 0101 0110 1000 1001 1010 1011 1100 1101 1110 1111 ``` **Leaderboard:** ``` var QUESTION_ID=62587,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/63075/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 2, 42 It seems to be good enough to compare with suffixes instead of bothering with a rotation. ``` f=lambda s,i=1:i/len(s)or s<s[i:]*f(s,i+1) ``` The setup of the recursion does not seem very nice; maybe it could be done better. This 44-byte version makes it more obvious what's going on: ``` lambda s:all(s<=s[i:]for i in range(len(s))) ``` [Answer] ## Haskell, ~~43~~ 38 bytes ``` f x=all(x<=)$init$scanl(const.tail)x x ``` `scanl(const.tail)x x` builds a list of all suffixes of `x`, including the empty string `""` at the end, which is stripped off with `init`. Edit: @feersum spotted a bug in my first version and [came up with the idea](https://codegolf.stackexchange.com/a/63086/34531) that comparing to suffixes is enough. [Answer] # Pyth, 9 bytes ``` !f>z>zTUz ``` [Demonstration](https://pyth.herokuapp.com/?code=%21f%3Ez%3EzTUz&input=001011&test_suite=1&test_suite_input=0%0A1%0A01%0A001%0A011%0A0001%0A0011%0A0111%0A00%0A10%0A11%0A000%0A010%0A100%0A101%0A110%0A111%0A0000&debug=0) Uses Vihan et. al.'s suffixes approach. [Answer] # J, 11 char Outputs `1` on Lyndon words and `0` otherwise. ``` 0=0({/:)<\. ``` `<\.` takes suffixes and then `/:` tells us how to sort them lexicographically. `{` takes the entry at the `0`-th index and `0=` checks if it's zero: if it is, we have a Lyndon word, because the biggest suffix wouldn't change place in a sort; if it's nonzero, it is not a Lyndon word, because some suffix is lexicographically earlier. ``` 0=0({/:)<\. '001011' 1 0=0({/:)<\. '001001' 0 ``` [Answer] # [ShapeScript](https://github.com/DennisMitchell/ShapeScript), ~~57~~ 47 bytes ``` 0?1'@"2"@+"20"$""~"21"$""~@2?2?>1<*'3?_1-*!@#@# ``` I created ShapeScript for [this competition](https://codegolf.stackexchange.com/a/62064). The [interpreter on GitHub](https://github.com/DennisMitchell/ShapeScript) has a slightly modified syntax. [Try it online!](http://shapescript.tryitonline.net/#code=MD8xJ0AiMiJAKyIyMCIkIiJ-IjIxIiQiIn5AMj8yPz4xPConMz9fMS0qIUAjQCM=&input=MDExMTEx) [Answer] # CJam, ~~15~~ 14 bytes ``` r_,,\fm<(f>1-! ``` Try [this fiddle](http://cjam.aditsu.net/#code=r_%2C%2C%5Cfm%3C(f%3E1-!&input=001011) in the CJam interpreter or [verify all test cases](http://cjam.aditsu.net/#code=qN%2F%7B_%2C%2C%5Cfm%3C(f%3E1-!%7D%2F&input=0%0A1%0A01%0A001%0A011%0A0001%0A0011%0A0111%0A00001%0A00011%0A00101%0A00111%0A01011%0A01111%0A000001%0A000011%0A000101%0A000111%0A001011%0A001101%0A001111%0A010111%0A011111%0A00%0A10%0A11%0A000%0A010%0A100%0A101%0A110%0A111%0A0000%0A0010%0A0100%0A0101%0A0110%0A1000%0A1001%0A1010%0A1011%0A1100%0A1101%0A1110%0A1111) at once. ### How it works ``` r e# Read a token from STDIN. _, e# Push the length of a copy. , e# Turn length L into [0 ... L-1]. \fm< e# Rotate the token 0, ..., and L-1 units to the left. ( e# Shift out the first rotation, i.e., the original token. f> e# Compare all other rotations with this one. 1- e# Remove 1 from the resulting array of Booleans. ! e# Apply logical NOT to turn an empty array into 1, and a e# non-empty one into 0. ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 10 bytes ``` xeยปxยซxS(iยฉ ``` Very golf, much short. [Try it online](http://vihanserver.tk/p/TeaScript/) ### Explanation && Ungolfed ``` xe(#x<=xS(i)) xe(# // Loop through x // Check if all iterations return true x <= // Input is less than or equal to... xS(i) // Input chopped at current index ) ``` [Answer] ## Haskell, 29 ``` f s=all(s<=)$init$scanr(:)[]s ``` Checks whether `s` is at most each of its non-empty suffixes, like [nimi's answer](https://codegolf.stackexchange.com/a/63080/20260). The expression `scanr(:)[]` generates the list of suffixes by listing. ``` >> scanr(:)[] "abcd" ["abcd","bcd","cd","d",""] ``` The `init` then gets rid of the empty string at the end. Finally, `all(s<=)` checks whether every suffix `x` satisfies `s<=x`. Since the first suffix is `s` itself, a `<=` is needed. [Answer] # Ruby, 37 bytes ``` ->s{(1...s.size).all?{|i|s[i..-1]>s}} ``` Testing: ``` lyndon_words = %w(0 1 01 001 011 0001 0011 0111 00001 00011 00101 00111 01011 01111 000001 000011 000101 000111 001011 001101 001111 010111 011111) not_lyndon_words = %w(00 10 11 000 010 100 101 110 111 0000 0010 0100 0101 0110 1000 1001 1010 1011 1100 1101 1110 1111) f=->s{(1...s.size).all?{|i|s[i..-1]>s}} p lyndon_words.all? &f # => true p not_lyndon_words.any? &f # => false ``` [Answer] ## Burlesque, 15 bytes ``` JiRJU_j<]x/==&& ``` Mainly 8 of those 7 bytes are to check if it doesn't tie. Otherwise you can go with simply `JiR<]==`. **Explanation:** ``` J -- duplicate word iR -- all rotations J -- duplicate list of all rotations U_ -- check if list contains no duplicates j -- swap <] -- find minimum of the list x/ -- rotate top == -- compare minimum with the original word && -- and results of min == orig and list unique ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` แบvว”g= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo92x5RnPSIsIiIsIlwiMDAxMDExXCIiXQ==) ``` vว” # Rotate by each of... แบ # 0 to len(x) g # Does the (lexicographic) minimum = # Equal the input? ``` [Answer] # Pyth - 12 bytes Hope to golf a little bit. ``` .A<Lzt.<Lzlz ``` [Try online](http://pyth.herokuapp.com/?code=.A%3CLzt.%3CLzlz&input=001011&test_suite=1&test_suite_input=0%0A1%0A01%0A001%0A011%0A0001%0A0011%0A0111%0A00%0A10%0A11%0A000%0A010%0A100%0A101%0A110%0A111%0A0000&debug=0). [Answer] # Javascript (ES6), 129 bytes ``` a=Array;s=prompt();console.log(a.from(a(s.length),(x,i)=>i).map(n=>(s.substring(n)+s.substring(0,n--))).sort().pop().contains(s)) ``` [Answer] # Javascript, ~~91~~ 87 bytes ``` f=x=>(y=(x+x).slice(1,-1),x[0]==x||!(y.indexOf(x)+1)&&!x.indexOf('0')&&x.slice(-1)==1); ``` I'm basically concatenating the word with itself and check if it's still there. To check if it is the smallest number possible, I just check that it start with a 0 and end with a 1. ### Tests ``` [ ['0',1], ['1',1], ['01',1], ['001',1], ['011',1], ['0001',1], ['0011',1], ['0111',1], ['00001',1], ['00011',1], ['00101',1], ['00111',1], ['01011',1], ['01111',1], ['000001',1], ['000011',1], ['000101',1], ['000111',1], ['001011',1], ['001101',1], ['001111',1], ['010111',1], ['011111',1], ['00',0], ['10',0], ['11',0], ['000',0], ['010',0], ['100',0], ['101',0], ['110',0], ['111',0], ['0000',0], ['0010',0], ['0100',0], ['0101',0], ['0110',0], ['1000',0], ['1001',0], ['1010',0], ['1011',0], ['1100',0], ['1101',0], ['1110',0], ['1111',0] ].forEach(t =>{ r=f(t[0]) x=t[1] console.log('Test '+(r==x?'OK':'Fail (Expected: ' + x +')') +'\nInput: '+t[0]+'\nResult: ' +r+'\n') }) ``` [Answer] # Mathematica, 86 bytes ``` (s=Table[#~StringRotateLeft~i,{i,StringLength@#}];Last@s==First@Sort@s&&s~Count~#==1)& ``` **input** > > ["1111"] > > > [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 85 bytes ``` param($k)($w=0..($l=$k.Length-1)|%{-join$k[-$_..($l-$_)]}|sort)[0]-eq$k-and$w[1]-ne$k ``` [Try it online!](https://tio.run/##dZTdaoNAEIXvfYpFJkUhG3YfQAjkttDS9E4kWDNpGo2m7ooF47Pb1TQ/0BlvhHNmvzlnEU9Vi7XZY1HIrKpxgF3UDae0To8B5GEAbaQWiwCKCPLFM5afdi91eJ518lB9lZDHEjaT795h0p9NVdswVonEb8hlWm6hjXUiS4R86D1vGXjCPfNl4Ct/LsDWDYY3Sf@XFKWRoiYnmfM0gCYoBkyTuYXkRjYIk0RxCZmIbHQuOxOeLcW14mqRnFHbpYV5/BJIUROiIs8rGsDs0uQyOgKTgQxBp1Cai0yyNVeFkTVdkWnOVKe7MxfF3dTjdCjOYia6yQaLxq5Sg87GnxNmFrciErC5uDWaprBOeILdfdabzPh1vWqMrY4vHwd3LlleiOOzbrIMjRlBfwT3D7ovuM35744oRqQ/zt74V//tuv6KmZze673hFw "PowerShell Core โ€“ Try It Online") 1. Generates all the rotations of the input 2. Sorts them 3. Checks that the first one equals the input and the second one does not [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 (or 8?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ฤ._{QJR ``` Outputs a 05AB1E truthy/falsey result, where truthy is a `1` padded with leading 0s up to the input-length, and falsey anything else. But since the challenge description mentions 'consistent' truthy/falsey value, a trailing `ฮ˜` (05AB1E-truthify builtin: `==1`) can be added for consistent `1`/`0` outputs. [Try it online](https://tio.run/##yy9OTMpM/f//SKNefHWgV9D//wYGhkAEAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R8SZOJzbsvhxafnKBkYGBoYGiqAKANDJeVDq8sq7ZUUHrVNUlCyr3T5f6RRL7460Cvov4t9ppKCRklRaUlGpabS4dVATlpiTnEqkFOr8x8A). **Explanation:** ``` ฤ # Push a list in the range [1, (implicit) input-length] (without popping) ._ # Rotate the input that many times (vectorized) towards the left { # Sort this list of rotations Q # Check for each rotation whether it's equal to the (implicit) input J # Join the checks together R # Reverse this string # (after which the result is output implicitly) ``` ]
[Question] [ This problem is an extension of what happens to me on a regular basis: I have to have $1.00 in coins and have to be able to give change to somebody. I discovered rather quickly that the ideal coins to have were 3 quarters, 1 dime, 2 nickels, and 5 pennies. This is the smallest number of coins (11 total) that allows me to make any number of cents 1-99. ### The Challenge Write a program that, given an integer input \$x\$ between 2 and 100 (inclusive), outputs the smallest arrangements of coins that does *both* of the following: 1. The total value of the coins is \$x\$ cents. 2. You can use those same coins to make every number of cents less than \$x\$. ### Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code (in bytes) wins. * Standard loopholes are forbidden * The output can be a list, a four-digit number, or any reasonable representation of the number of coins needed. These coins must be in either ascending or descending order but they do not need to be clearly denoted, only consistently formatted. + In other words, all of the following are valid: `[1, 2, 3, 4]` `[1 2 3 4]` `4321` `1 2 3 4` `1P 2N 3D 4Q` `PNNDDDQQQQ`. Simply state somewhere whether your output is listed in ascending or descending order; it must be the same order for all outputs. * In the case that an optimal solution has *none* of a given coin, your output *must* contain a "0" (or other similar character, so long as it is used exclusively and consistently for "0"). This rule does not apply if you use the PNDQ or QDNP format. * The only coins that exist are the penny, nickel, dime, and quarter, being worth 1, 5, 10, and 25 cents respectively. * An arrangement of coins is considered "smaller" than another if the total *number* of coins is less; all coins are weighted equally. ### Test Cases ``` x Output (Ascending four-digit number) 2 2000 3 3000 4 4000 5 5000 6 6000 7 7000 8 8000 9 4100 10 5100 11 6100 12 7100 13 8100 14 4200 15 5200 16 6200 17 7200 18 8200 19 4110 20 5110 21 6110 22 7110 23 8110 24 4210 25 5210 26 6210 27 7210 28 8210 29 4120 30 5120 31 6120 32 7120 33 8120 34 4220 35 5220 36 6220 37 7220 38 8220 39 4130 40 5130 41 6130 42 7130 43 8130 44 4230 45 5230 46 6230 47 7230 48 8230 49 4211 50 5211 51 6211 52 7211 53 8211 54 4121 55 5121 56 6121 57 7121 58 8121 59 4221 60 5221 61 6221 62 7221 63 8221 64 4131 65 5131 66 6131 67 7131 68 8131 69 4231 70 5231 71 6231 72 7231 73 8231 74 4212 75 5212 76 6212 77 7212 78 8212 79 4122 80 5122 81 6122 82 7122 83 8122 84 4222 85 5222 86 6222 87 7222 88 8222 89 4132 90 5132 91 6132 92 7132 93 8132 94 4232 95 5232 96 6232 97 7232 98 8232 99 4213 100 5213 ``` [Answer] # JavaScript (ES6), 57 bytes A significantly shorter version suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh), who managed to get rid of the edge case \$n<9\$. Returns an array of 4 integers in reverse order (quarters to pennies). ``` n=>[z=(n-=x=(n-4)%5+4)/25-.7|0,(n=n/5-5*z-1)/2|0,n%2+1,x] ``` [Try it online!](https://tio.run/##TdRNbtNQGIXhuVdxVamyL2kc/8YJyGVUBgxg0GHpIEqc4iq6Lnao2gI7QOqEIeyD9bABlhC@45vziaiKnjpx3@j2KLer@9Ww7tu7/dR1m@awrQ@uPr96qiM3rR/wXNjTclLYWVZO4@prcha52s3KafniaZrKVbniTrNJevZwfeibT5/bvonC7RDauG9Wmzftrrl8dOsosfG@u9z3rbuJbDzc7dp9dPLBndh42/UXq/XHaDD1ufkSGHNl3Jnpm8Fcm9oMx/fOzGRmX8mrTi5OHLTu3NDtmnjX3UTu/79@t9pcuE1UWDMxby/fv4uH8ZV2@xhtI2dxOTTyMzHj7/JB75t@aOTO2651URhaU9fjJ3htwj8/f/z9/Ryal8Jf30Nrg2/2kJnxkSVJEuTeOVx4F3DpXcJz7zlceVfwwnsBL4/3puI08feOTv29o324Gu3Di9E@XGSwD5ejfXg@2oer0T68GL08dtMkyNiF2YXZhdmF2YXZhdmF2YXZhdnN5AzZhdmF2YXZhdmF2YXZhdmF2YXZzeX/xS7MLswuzC7MLswuzC7MLswuvORZpUGZ8KzEKc9KnPGsxDnPSlzwrMQlz0o851mJK56VeMGzErMrnrMLswuzC7MLs5uL2YXZhdmF2YXZFVfswuzC7MLswrqrLKh0V2LdlVh3JdZdiXVXWbDQXYl1V2LdlVh3JdZdiXVXYt2VWHcl1l2JdVdZsNRdiXVXYt2VWHcl1l2JdVdi3ZVYdyXWXYl1V7l8byTHs8r/AQ "JavaScript (Node.js) โ€“ Try It Online") --- # Original version, 73 bytes Returns an array of 4 integers. ``` n=>n<9?[n,0,0,0]:[x=4-~n%5,y=(z=n/25-.96|0)+(n-=x)/5&1||2,n/5-y-z*5>>1,z] ``` [Try it online!](https://tio.run/##TdRNbtNQFIbhuVdxVQnsSxLH/z8Fp6MyYACDDEMGUeIUV9F1sANqQssKkJgwhH2wHjbAEsI5vvmOaDt4mtR9pdNPvV99XvXrrtkfJqbd1OdtdTbVzLwqbxZmHPDn8nrxUCWTr@ZZOj5W3qky0yid@GX2GOiRZybVg56mz8PHx2hspunkODm9SGezcHxanrv646emqz1327va7@rV5nWzq@dHs/YC7R/a@aFrzJ2n/X6/aw7e1Xtzpf1t292u1h@8XlUz9cVRaqHMWHV1r5aqUv3lZ6dqNNUv6V1DL44Ma92avt3V/q6988z/v32/2tyajZdoNVJv5u/e@v3wTrM9elvPaH7ZVfQ1UsP3/n3bGM91taqqoXuj3D8/f/z9/d1V18Rf31ytnSd9jtTwEQVB4MTWMTuxTtipdcrOrDN2bp2zC@uCXV6eDclhYJ8dHNpnB9twPtiGi8E2nERsG04H23A22IbzwTZcDC4v3TBwInTZ6LLRZaPLRpeNLhtdNrpsdNnoRnRDdNnostFlo8tGl40uG102umx02ejG9PdCl40uG102umx02eiy0WWjy0aXXeJWoZMGuBU5xK3IEW5FjnErcoJbkVPcipzhVuQctyIXuBUZXXKGLhtdNrpsdNnoxmR02eiy0WWjy0aXnKPLRpeNLhtdtuwqcnLZFVl2RZZdkWVXZNlV5BSyK7Lsiiy7IsuuyLIrsuyKLLsiy67Isiuy7CpyStkVWXZFll2RZVdk2RVZdkWWXZFlV2TZFVl2FdP/jeByq/gf "JavaScript (Node.js) โ€“ Try It Online") [Answer] # Excel, 106 bytes ``` =IF(A1<9,A1*1000,LET(p,MOD(A1+1,5)+4,b,(A1-p)/5-1,q,(b>2)*INT((b-3)/5),c,b-5*q,p&(MOD(c,2)+1)&INT(c/2)&q)) ``` [Answer] ## JavaScript (ES6), ~~47~~ ~~45~~ 44 bytes ``` f= n=>[25,10,5,1].map(v=>(n-=v*=c=-~n/v-1|0,c)) ``` ``` <input type=number min=2 max=100 oninput=o.textContent=f(this.value)><pre id=o> ``` Port of my latest Charcoal answer, so outputs in reverse order. [Answer] # [Jelly (cairdcoinheringaahing's fork)](https://github.com/cairdcoinheringaahing/jellylanguage), ~~23~~ 19 bytes ``` ล’แน—ล’PยงแธŸ@ษ—ฦฅRแธŸฦฅโ€œยขยฆยฝฤฑโ€˜แนช ``` Extremely inefficient, and probably also bad in terms of golf. The highest number I could test it on is 18. Outputs a list of the needed coins in ascending order. The naive conversion to Jelly would be +2 bytes. You can [Try it online!](https://tio.run/##y0rNyan8///opIc7px@dFHBo@cMd8x1OTj88AUgHATGY8ahhzqFFh5Yd2ntk46OGGQ93rvr//7@hAQA "Jelly โ€“ Try It Online") *-4 bytes by changing the output format* ## Explanation ``` ล’แน—ล’PยงแธŸ@ษ—ฦฅRแธŸฦฅโ€œยขยฆยฝฤฑโ€˜แนช Main monadic link ล’แน— Integer partitions, sorted from longest to shortest ฦฅ Keep those where the result is empty: ษ— ( ล’P Power set ยง Sum each sublist แธŸ@ Remove the resulting numbers R from the range [1..input] ษ— ) ฦฅ Keep those where the result is empty: แธŸ Filter out โ€œยขยฆยฝฤฑโ€˜ [1,5,10,25] แนช Tail (last item) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~90~~ 87 bytes ``` MinimalBy[Length@Expand@Exp[Log[1+$^d].#]>#.d&&#&/@FrobeniusSolve[d={1,5,10,25},#],Tr]& ``` [Try it online!](https://tio.run/##FcXBCsIgGADgh/nDS7Y02HHDBXVaENRNDP7SbcLUMItGtFc3@i6fwzQYh8neMHdVPlhvHY7bSbbG92kQu/cdvf4n29BLvlxctCpA1VBoQoCsxT6Gq/H2@TiF8WWkrj6clpQzuim/FBQ9R0XyMVqfJKzqToAicxMjTjNnLP8A "Wolfram Language (Mathematica) โ€“ Try It Online") ``` FrobeniusSolve[d={1,5,10,25},#] (* Find nonnegative integer vectors s where {1,5,10,25}.s==x. *) Length@Expand@ (* If the number of terms in the expansion of *) Exp[Log[1+$^d].s] (* (1+$)^s1(1+$^5)^s2(1+$^10)^s3(1+$^25)^s4 *) >#.d&&#&/@ % (* for each s is not greater than x (=x+1), discard it. *) MinimalBy[ % ,Tr]& (* Select the s with the least sum. *) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~80~~ 71 bytes ``` .+ $* (1{25}(?=1{24}))*(1{10}(?=1{9}))*(1{5}(?=1{4}))*(1+) $.4$#3$#2$#1 ``` [Try it online!](https://tio.run/##K0otycxL/K@nzaWidWgbF5eKXgKEw6VhWG1kWqthbwukTWo1NbWAAoYGEAFLKB8qD5XW1gRqN1FRNlZRNlJRNvyfmxCnYW9jq6EHNFkTJKlsqMBl5Jjw39DAAAA "Retina 0.8.2 โ€“ Try It Online") Link includes test suite that automatically generates numbered results ranging from `2` to the input value. Explanation: ``` .+ $* ``` Convert to unary. ``` (1{25}(?=1{24}))* ``` Match quarters, but leaving at least 24 cents. ``` (1{10}(?=1{9}))* ``` Match dimes, but leaving at least 9 cents. ``` (1{5}(?=1{4}))* ``` Match nickels, but leaving at least 4 cents. ``` (1+) ``` Match the remaining cents. ``` $.4$#3$#2$#1 ``` Output the remaining cents, plus the number of nickels, dimes and quarters. 38 bytes if outputting a list of coin values is acceptable: ``` .+ $* M!`1(1{24}|1{9}|1{4}|)(?=\1) %`1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLVzHBUMOw2siktsaw2hJEAFmaGva2MYaaXKoJhv//GxoYAAA "Retina 0.8.2 โ€“ Try It Online") No test suite yet. Explanation: ``` .+ $* ``` Convert to unary. ``` M!`1(1{24}|1{9}|1{4}|)(?=\1) ``` Try all coin values in descending order. For each coin value, ensure that there are enough cents left for one less than that value. ``` %`1 ``` Convert to decimal. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 98 bytes ``` Counts@Join[h={1,5,10,25},FirstCase[IntegerPartitions[#,#,h],s_/;Tr[1^Union[Tr/@Subsets@s]]>#]]-1& ``` [Try it online!](https://tio.run/##DcyxCsIwEADQXxECTidpip2kEigUdCpapxAlSkgy9AK56yR@e@z6hrc4jn5xnD6uhr4OeUUmfc0JTey/CjpQDbTdD8ZUiAdH3lyQffBlcoUTp4xkBAiIFuglT3Mx6vnAjc1cpL6vb/JbSNaehbUHta9TScg7qYPUN4fBmxaOja31Dw "Wolfram Language (Mathematica) โ€“ Try It Online") -13 bytes from @att [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes Quite inefficient, TIO only reaches 15. ``` ~+{1|5|10|25}แต.&โŸฆ~{โЇ+}แต› ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahl6qOmpmobQwNDtdrqciUFXTsFpXK1R20bHjW1PNy24NDOjIe7Omtrgcz/ddrVhjWmNYYGNUamtQ@3TtBTezR/WV31o652bSB39v//AA "Brachylog โ€“ Try It Online") ``` ~+{1|5|10|25}แต.&โŸฆ~{โЇ+}แต› ~+ A list of numbers (which sum is the input) {1|5|10|25}แต where each number is 1, 5, 10, or 25 . is the output. &โŸฆ For [0,1,โ€ฆ,N]: ~{โЇ+}แต› every element is the sum of a subset of the output. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~61~~ ~~51~~ ~~30~~ 29 bytes ``` ๏ผฎฮธ๏ผฆโŸฆยฒโตฯ‡โตยฆยนโŸงยซโ‰”รทโ†”โปฮนโŠ•ฮธฮนฮท๏ผฉฮทโ‰งโปร—ฮนฮทฮธ ``` [Try it online!](https://tio.run/##Tc69DoIwFAXgGZ6i421SEzBhYiK6MGCMcTMOFSq9CVywPyzGZ69FFoeznOR8Oa2Wpp3kEEJNs3cnPz6UgRcv0@dkGNz2hWB5Jlhx5@ydJpW12BPU5I64YKegethp8E5Bg@QtoGA1tUaNipzqosO5YBijo5icDZKDg7QONF@LRs6beMFeu80Q7Iqj@lE6Dtcrn/RvGc0yhDzLwm4Zvg "Charcoal โ€“ Try It Online") Link is to verbose version of code. Edit: Reversed the order in which coins are printed to save bytes. Explanation: ``` ๏ผฎฮธ ``` Input `x`. ``` ๏ผฆโŸฆยฒโตฯ‡โตยฆยนโŸงยซ ``` Loop over all the denominations in descending order. (Charcoal's predefined `c` variable for `10` conveniently avoids two of the separators here.) ``` โ‰”รทโ†”โปฮนโŠ•ฮธฮนฮท ``` Find how many coins I can use. Unless the original input was less, we need to be able to form an amount one less than this coin's value, so we take the absolute difference from this value (which handles inputs less than the value of the coin) before integer dividing by the coin's value. ``` ๏ผฉฮท ``` Print that number. ``` โ‰งโปร—ฮนฮทฮธ ``` Subtract the value of the coins. ]
[Question] [ Let's play some code-golf! The challenge is to find the winner of a game of Tic-Tac-Toe. This has been done many times by giving a board that has one clear winner but here is the twist: The cells are numbered like this: ``` 1|2|3 -+-+- 4|5|6 -+-+- 7|8|9 ``` You get an array of exactly 9 moves like that: ``` {3, 5, 6, 7, 9, 8, 1, 2, 3} ``` This is parsed as follows: * Player 1 marks cell 3 * Player 2 marks cell 5 * Player 1 marks cell 6 * Player 2 marks cell 7 * Player 1 marks cell 9 * **Player 1 has won** Note: The game does not stop after one player has won, it may happen that the losing player manages to get three in a row after the winning player, but only the first win counts. Your job is now to get 9 numbers as input and output the winning player and the round in which the win occured. If no one wins, output something constant of your choice. You can receive input and provide output through any standard mean / format. Have fun! Some more examples as requested: ``` {2,3,4,5,6,7,1,8,9} => Player 2 wins in round 6 {1,2,4,5,6,7,3,8,9} => Player 2 wins in round 8 {1,2,3,5,4,7,6,8,9} => Player 2 wins in round 8 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 114 bytes ``` (.)(.) $1O$2X ^ 123;;456;;789ยถX {`(.)(.*ยถ)(.)\1 $3$2 }`.*(.)(.)*\1(?<-2>.)*(?(2)(?!))\1.*ยถ(..)* $1$#3 .*ยถ T T`d`Rd ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ08TiLhUDP1VjCK44rgMjYytrU1MzaytzS0sD22L4KpOACvROrQNpDDGkEvFWMWIqzZBTwuiVSvGUMPeRtfIDsjUsNcw0tSwV9QEqgPp0NADCgLNVlE25gLxuUK4QhJSEoJS/v83NbQ0NjIxtzADAA "Retina โ€“ Try It Online") Based on my answer to [Tic-Tac-Toe - X or O?](https://codegolf.stackexchange.com/questions/144116). Outputs `X<N>` if the first player wins after `N` turns, `O<N>` if the second player wins, `T` if neither wins. Explanation: ``` (.)(.) $1O$2X ^ 123;;456;;789ยถX ``` Creates an internal board, and also marks each move with the player whose move it is. ``` {`(.)(.*ยถ)(.)\1 $3$2 ``` Applies a move. ``` }`.*(.)(.)*\1(?<-2>.)*(?(2)(?!))\1.*ยถ(..)* $1$#3 ``` Searches for a win, and if one is found, then replace the board with the winner and the number of remaining moves. ``` .*ยถ T ``` If the moves are exhausted and nobody has won then the game is a tie. ``` T`d`Rd ``` Calculate the number of the round from the number of remaining moves. [Answer] # [MATL](https://github.com/lmendo/MATL), 39 bytes ``` 3:g&+XIx"IX@oXK@(XIt!yXdyPXd&hK=Aa?KX@. ``` Output is * `1` and `R`, in separate lines, if user 1 wins in round *R*; * `0` and `R`, in separate lines, if user 2 wins in round *R*; * empty if no one wins. [Try it online!](https://tio.run/##y00syfn/39gqXU07wrNCyTPCIT/C20EjwrNEsTIipTIgIkUtw9vWMdHeO8JB7///aGMdBVMdBTMdBXMdBUsdBQsdBUMdBSMdBeNYAA) Or [verify all test cases](https://tio.run/##y00syfmf8N/YKl1NO8KzQskzwiE/wttBI8KzRLEyIqUyICJFLcPb1jHR3jvCQe9/bKy6rq6ueoRLyP9oYx1THTMdcx1LHQsdQx0jHeNYrmggqWMCFTcEilsCxUByMDFjJDGQfhOgmBlYDAA). ### Explanation ``` 3: % Push [1 2 3] g % Convert to logical. Gives [true true true] &+ % Matrix of all pairs of additions. Gives a 3ร—3 matrix, which represents % the board in its initial state, namely all cells contain 2. This value % means "cell not used yet". 1 will represent "cell marked by user 1", % and 0 will represent "cell marked by user 2" XI % Copy into clipboard I x % Delete " % Implicit input: array with moves. For each move I % Push current board state X@ % Push iteration index (starting at 1), that is, current round number o % Modulo 2: gives 1 or 0. This represents the current user XK % Copy into clipboard K @ % Push current move ((that is, cell index) ( % Write user identifier (1 or 0) into that cell. Cells are indexed % linearly in column-major order. So the board is transposed compared % to that in the challenge, but that is unimportant XI % Copy updated board into clipboard I t! % Duplicate and transpose y % Duplicate from below: push copy of board Xd % Extract main diagonal as a 3ร—1 vector y % Duplicate from below: push copy of transposed board PXd % Flip vertically and extract main diagonal. This is the anti-diagonal % of the board &h % Concatenate stack horizontally. This concatenates the board (3ร—3), % transposed board (3ร—3), main diagonal (3ร—1 vector) and anti-diagonal % (3ร—1) into an 3ร—8 matrix K= % Push current user identifier. Test for equality with each entry of the % 3ร—8 matrix A % For each column, this gives true if all its entries are true. Note % that the first three columns in the 3ร—8 matrix are the board columns; % the next three are the board rows; and the last two columns are the % main diagonal and anti-diagonal. The result is a 1ร—8 vector a % True if any entry is true, meaning the current user has won ? % If true K % Push current user identifier X@ % Push current round number . % Break for loop % Implicit end % Implicit end % Implicit display ``` [Answer] # Javascript (ES6), 130 bytes ``` m=>m.reduce((l,n,i)=>l||(b[n-1]=p=i%2+1,"012,345,678,036,147,258,048,246".replace(/\d/g,m=>b[m]).match(""+p+p+p)&&[p,i+1]),0,b=[]) ``` ``` f=m=>m.reduce((l,n,i)=>l||(b[n-1]=p=i%2+1,"012,345,678,036,147,258,048,246".replace(/\d/g,m=>b[m]).match(""+p+p+p)&&[p,i+1]),0,b=[]) console.log(JSON.stringify(f([3,5,6,7,9,8,1,2,3]))) console.log(JSON.stringify(f([2,3,4,5,6,7,1,8,9]))) console.log(JSON.stringify(f([1,2,4,5,6,7,3,8,9]))) console.log(JSON.stringify(f([1,2,3,5,4,7,6,8,9]))) ``` ## Explanation ``` m=>m.reduce((l,n,i)=> // Reduce the input array with n as the current move l||( // If there is already a winner, return it b[n-1]=p=i%2+1, // Set the cell at b[n-1] to the current player p "012,345,678,036,147,258,048,246" // For every digit in the list of possible rows: .replace(/\d/g,m=>b[m]) // Replace it with the player at the cell .match(""+p+p+p) // If any of the rows is filled with p: &&[p,i+1] // Return [p, current move] ),0,b=[]) ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 445 bytes ``` int[] t(int[]m){int[][]f=new int[3][3];boolean z=false;for(int i=0;i<9;i++){f[m[i]%3][m[i]/3]=z?2:1;if(f[m[i]%3][0]==(z?2:1)&&f[m[i]%3][1]==(z?2:1)&&f[m[i]%3][2]==(z?2:1)||f[0][m[i]/3]==(z?2:1)&&f[1][m[i]/3]==(z?2:1)&&f[2][m[i]/3]==(z?2:1)||m[i]%3+m[i]/3==2&&f[0][2]==(z?2:1)&&f[1][1]==(z?2:1)&&f[2][0]==(z?2:1)||m[i]%3==m[i]/3&&f[0][0]==(z?2:1)&&f[1][1]==(z?2:1)&&f[2][2]==(z?2:1)){return(new int[]{(z?2:1),++i});}z=!z;}return(new int[]{0,0});} ``` [Try it online!](https://tio.run/##jZHLbsIwEEXX8BUuUlEiu9QJfVHX6hd0xTLywkCChiZOlBiq5vHtqfOgoQqLSpZGvvfOuYs5yJO8ixNfHXafdXLchLBF21BmGfqQoFAxnfRipqU24xTDDkXGstY6BbX3BJLpPrOb5ASUNn9AHGlL@V@o/RcOccmSPJBH8kSeyQtZVTYz4fV3pv1oER/1IjEkHSoLPCrwDM0weI5oQ9W06607tLbaGdlFOz0R8HPPUpjHNnEc@lKhnAcyzHwWxGmzgoBTBm8rBhjbReBFHohbs9HM@6Xg@bv76jAIrMGignOr1e35fJCd67I7yGUZmOVf9GXauS67Y7ksOzLuDM7dJkj/FPVEZwSjYw7nHain0H9QLprsIvX1MVUXR@0dgjGYc1Y5v8lZNUpRQhu3ruof "Java (OpenJDK 8) โ€“ Try It Online") Return value {1,8} means that player 1 won in round 8. Return value {0,0} means draw. [Answer] # [Kotlin](https://kotlinlang.org), 236 bytes ``` i.foldIndexed(l()to l()){o,(a,b),p->fun f(i:(Int)->Int)=b.groupBy(i).any{(_,v)->v.size>2} if(f{(it-1)/3}|| f{it%3}|| listOf(l(1,5,9),l(3,5,7)).any{b.containsAll(it)}){return p%2+1 to o} b to a+p}.let{null} fun l(vararg l:Int)=l.toList() ``` ## Beautified ``` i.foldIndexed(l() to l()) { o, (a, b), p -> fun f(i: (Int) -> Int) = b.groupBy(i).any { (_, v) -> v.size > 2 } if (f { (it - 1) / 3 } || f { it % 3 } || listOf(l(1, 5, 9), l(3, 5, 7)).any { b.containsAll(it) }) { return p % 2 + 1 to o } b to a + p }.let { null } fun l(vararg l:Int)= l.toList() ``` ## Test ``` fun f(i: List<Int>): Pair<Int, Int>? = i.foldIndexed(l()to l()){o,(a,b),p->fun f(i:(Int)->Int)=b.groupBy(i).any{(_,v)->v.size>2} if(f{(it-1)/3}|| f{it%3}|| listOf(l(1,5,9),l(3,5,7)).any{b.containsAll(it)}){return p%2+1 to o} b to a+p}.let{null} fun l(vararg l:Int)=l.toList() data class Test(val moves: List<Int>, val winner: Int, val move: Int) val tests = listOf( Test(listOf(3, 5, 6, 7, 9, 8, 1, 2, 3), 1, 5), Test(listOf(2, 3, 4, 5, 6, 7, 1, 8, 9), 2, 6), Test(listOf(1, 2, 4, 5, 6, 7, 3, 8, 9), 2, 8), Test(listOf(1, 2, 3, 5, 4, 7, 6, 8, 9), 2, 8) ) fun main(args: Array<String>) { tests.forEach { (input, winner, move) -> val result = f(input) if (result != winner to move) { throw AssertionError("$input ${winner to move} $result") } } } ``` ## TIO [TryItOnline](https://tio.run/##fZJRb9sgEMff/SluVSqBevHkuEnbqPGUSX2oNGmTtveJJDhFo2ABdpdRf/YMcJKl0jY/4OO435/jDz+0k0Lts7pVUBMxh0/CuvtH5So6hy9MmBgjxMQHWOxFXmu5eVQb/pNviCTUaQgj9RoJwxXFZlwdpUiA6LiK42KVb41um487ImjO1M6T79iFxS634hevJn0malJ7Ity4oO/L/vUVai/cZYpkaOlzHXYrcIp3FCUpQ3BDB6VVvtbKMaHsUsogQHvqDXetUdBcTq4KCC3qPlvFP7tq+lxy51UrZZ8OLUnHDDNbkPPUqcydjh4Qus82zDFYS2YtfOMh1TEJz7rj9swmhJh9EUpxM4dk1rEsTWmWxbkLvIXF8SwZHL6ke0iWCFOEGcINwh3CLUKBMEEoaYqmFP+KxQqE6zO4SHBwKtKzf2CD9jlWnmO3/8WGVq8TNnuLZeHE0djncCUkGBvMWhrDdvdfnRFqW1HwSTg5Ep6TeWDrJ/BAhGra4N5gJSYHKYyrUxfRRsNtK13wsR7K6WlV1EAOq+8WB5F45YOMP9WlrZ+MfoGltdw4odWDMdqQi1FShJF/C/cwGnQv/mzWZ8PY738D) [Answer] # [Python 2](https://docs.python.org/2/), 170 bytes ``` q=map(input().index,range(1,10)) z=zip(*[iter(q)]*3) o='', for l in[q[2:7:2],q[::4]]+z+zip(*z): r=[n%2for n in l];y=all(r)*2+1-any(r) if y:o+=[max(l)+1,y], print min(o) ``` [Try it online!](https://tio.run/##HctBbsMgEEDRPadgU4Uxk6oQp2moOAligVSnQcIDRo5kfHnHye4v3i9tvmfS2zbZMRQRqTxmAZ@R/oYFa6D/QShUXwBstWssonNxHqqYwHcnYNkeDshuufLEI7nJaXMx2uPkjOm9l6t8PysYxqt19KFflnbLk/9tNqQkKnRaqmOgtifj8cabydK6MSwigVTYPLJSI818jCQybJvTeMIez/iNF1T4g1f/BA "Python 2 โ€“ Try It Online") or [Try all test cases](https://tio.run/##TY/BbsMgDIbveQouU6Bxp0HSpmViL4I4RCrpkBKSUCY1efnMMKnazf/nz2DPa/yevNj3m@1JTxcmC7KosZvp8u78zT4hdP5uKQf@wVhBNrW5mR60izagbQ41wkmVJRSknwIZiPN60UK2UhhYtJSNMdVW5aktvU6C0v5NZNujTQbzuapuGGhgB1HxY@dXLFF0PVnlVCk9dk86sIrDavCbYONP8GR0nk5sj/YRH0prATU0cIIztMDhAlcDmoN4sfofq5E1yM4v9mddMbepj6zOWSC/QOq32Tvl6RZzto0p0hlph3RJ3gVPnIPzMScoj18l9DTVrNh/AQ "Python 2 โ€“ Try It Online") ``` #swap cell number / turn q=map(input().index,range(1,10)) #split in 3 parts (rows) z=zip(*[iter(q)]*3) #starting value for the list with the results #since string are "greater" than lists, this will #be the output value when there is a draw o='', #iterate over diagonals, rows and columns for l in[q[2:7:2],q[::4]]+z+zip(*z): #use %2 to separate between player 1 and 2 r=[n%2 for n in l] #store in y the value of the player if the trio is a valid win, 0 otherwise #it's a win if all moves are from the same player y=all(r)*2+1-any(r) #if y has a valid player, add the highest turn of the trio, and the player to o if y:o+=[max(l)+1,y], #output the smaller turn of the valid winning trios print min(o) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 38 bytes ``` ;โตs2Zแนฌแธค2ยฆSแน–s3ยต,แนšJแป‹"$โ‚ฌ;;ZEรfแน€แธขยต$ฦคยตTแธข,แป‹ยฅ ``` [Try it online!](https://tio.run/##AV4Aof9qZWxsef//O@KBtXMyWuG5rOG4pDLCplPhuZZzM8K1LOG5mkrhu4siJOKCrDs7WkXDkGbhuYDhuKLCtSTGpMK1VOG4oizhu4vCpf///zEsMiwzLDUsNCw3LDYsOSw4 "Jelly โ€“ Try It Online") Player 1 win: `[round, 1]` Player 2 win: `[round, 2]` Tie: `[0, 0]` [Answer] ## Python 3.6+, 137 bytes ``` n=m=c=z=0 for a in input():m+=1<<~-int(a);c+=1;z=z or f'{c&1}:{c}'*any(m&t==t for t in[7,56,448,73,146,292,273,84]);n,m=m,n print(z or-1) ``` Output format is `winner number:round` or `-1` for a tie. Player 2 is `0` Player 1 is `1`. Input in the form of a undeliminated string of 1-indexed square numbers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 9s3,ZU$$;ล’D$โ‚ฌแบŽfโ‚ฌโธLโ‚ฌ3e s2Zร‡ฦคโ‚ฌZFTแธข;แธ‚$ ``` A monadic link taking a list of the moves and returning a list, `[move, player]` where the players are identified as `1` (first to act) and `0` (second to act). **[Try it online!](https://tio.run/##y0rNyan8/9@y2FgnKlRFxfroJBeVR01rHu7qSwNSjxp3@AAp41SuYqOow@3HlgA5UW4hD3cssn64o0nl////RjrGOiY6pjpmOuY6hjoWOpYA "Jelly โ€“ Try It Online")** ### How? ``` 9s3,ZU$$;ล’D$โ‚ฌแบŽfโ‚ฌโธLโ‚ฌ3e - Link 1: any winning play?: list of player's moves: 9s3 - (range of) nine split into threes = [[1,2,3],[4,5,6],[7,8,9]] $ - last two links as a monad: $ - last two links as a monad: Z - transpose = [[1,4,7],[2,5,8],[3,6,9]] U - upend = [[7,4,1],[8,5,2],[9,6,3]] , - pair = [[[1,2,3],[4,5,6],[7,8,9]],[[7,4,1],[8,5,2],[9,6,3]]] $โ‚ฌ - last two links as a monad for โ‚ฌach: ล’D - diagonals = [[1,5,9],[2,6],[3],[7],[4,8]] or [[7,5,3],[4,2],[1],[9],[8,6]] ; - concatenate = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[2,6],[3],[7],[4,8]] or [[7,4,1],[8,5,2],[9,6,3],[7,5,3],[4,2],[1],[9],[8,6]] แบŽ - tighten = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[2,6],[3],[7],[4,8],[7,4,1],[8,5,2],[9,6,3],[7,5,3],[4,2],[1],[9],[8,6]] - i.e.: row1 row2 row3 diag\ x x x x col1 col2 col3 diag/ x x x x - where x's are not long enough to matter for the rest... โธ - chain's left argument, list of player's moves fโ‚ฌ - filter to keep those moves for โ‚ฌach of those lists to the left Lโ‚ฌ - length of โ‚ฌach result 3e - 3 exists in that? (i.e. were any length 3 when filtered down to only moves made?) s2Zร‡ฦคโ‚ฌZFTแธข;แธ‚$ - Main link: list of the moves e.g. [2,3,4,5,6,7,1,8,9] s2 - split into twos [[2,3],[4,5],[6,7],[1,8],[9]] Z - transpose [[2,4,6,1,9],[3,5,7,8]] ฦคโ‚ฌ - for ฦคrefixes of โ‚ฌach: ร‡ - call last link (1) as a monad [0,0,0,0,0] [0,0,1,1] Z - transpose [[0,0],[0,0],[0,1],[0,1],[0]] F - flatten [0,0,0,0,0,1,0,1,0] T - truthy indices [ 6 8 ] แธข - head (if empty yields 0) 6 $ - last two links as a monad: แธ‚ - modulo by 2 (evens are player 2) 0 ; - concatenate [6,0] ``` [Answer] # Python 2, 168 bytes ``` import itertools as z f=lambda g:next(([i%2+1,i+1]for i in range(9) if any(c for c in z.combinations([[0,6,1,8,7,5,3,2,9,4][j]for j in g[i%2:i+1:2]],3)if sum(c)==15)),0) ``` Outputs (player,round) or 0 for a tie. Maps the game onto a 3-by-3 magic square and looks for sets of 3 Os or Xs that sum to 15. [Answer] # [Clean](https://clean.cs.ru.nl), ~~244~~ ... 220 bytes ``` import StdEnv f[a,b]i#k= \l=or[and[isMember(c+n)(take i l)\\c<-:"123147159357"%(j,j+2)]\\j<-[0,3..9]&h<-:"\0\0",n<-[h-h,h,h+h]] |k a=(1,i*2-1)|i>4=(0,0)|k b=(2,i*2)=f[a,b](i+1) @l=f(map(map((!!)l))[[0,2..8],[1,3..7]])1 ``` [Try it online!](https://tio.run/##JVDJTsMwEBXi1q9wg6A2caI4C2lQjXqAA1I59Wj74GzEieNUaUBC6rdjEqrRHN4ivXlT6Eoa2w/ll65AL5Wxqj8N4wSOU/lmvlc1kzgX6q6jgGs6jEyakqnzR9Xn1QgL1yA4ya4CCmjEebHznh0SRiROSZJFSercwxa3bogE5@3OYwGOfD8TD81ivL3hAQ8cbGah8Ro8j9sIsbp0QFJIsHoMPYIu6iWmMMABmvmcwnDhEb0eBpVL0GqvaQ17efpfuF4jjRCbs0Lf3wrMyBKaCoGIPU5y7kYB2AO2IWGcPKXRNtsI@1vUWn6erfd@sK8/RvaquIL5DweV/wE "Clean โ€“ Try It Online") The string iterated into `h` contains nonprintables, and is equivalent to `"\003\001\000\000"`. [Answer] # [Python 2](https://docs.python.org/2/), ~~140~~ ~~136~~ 134 bytes ``` lambda a,i=0:i<9and(any(set(a[i%2:i+1:2])>=set(map(int,t))for t in'123 456 789 147 258 369 159 357'.split())and(i%2+1,i+1)or f(a,i+1)) ``` [Try it online!](https://tio.run/##VY7BTsMwEETP5Cv2guJVRwjbcRxHpMf@RMnBqI2w1KZR60u/PqyLAHGbfTM7u8s9f15ms07D@3qK549DpIg0vPbpLcT5oOJ8V7djVnGfnk2fNro3I2@Hgs5xUWnOyMzT5UqZ0lxrY6lxLfkukG48GdeRbUW7QNb5@uW2nFJWzKVbGjca0smyPqn4kLwejhPtVOS@elquckAeonrY1igZrqqd2luQA7UgDwqgDqRBBtSMXGwDiwYOLTw0OoRvrGF@sf2PreBGcPuHrQxBLCdIF/Mn7R55L6gEupHXLw "Python 2 โ€“ Try It Online") EDIT: 4 bytes + 2 bytes thx to Eric the Outgolfer. Outputs a tuple (playerNumber, roundNumber) or False if there is no winner. ]
[Question] [ The other day, my son asked me to build him a staircase using Lego-ish blocks. And I came up with something like this: [![Staircase](https://i.stack.imgur.com/EzQUOm.jpg)](https://i.stack.imgur.com/EzQUOm.jpg) Then my kid asked me for a program using the least number of bytes that generated a similar staircase in a computer screen. I am not that good at [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so I need your help. I need a program that: * Receives a positive integer with the number of levels the staircase needs to have. * Outputs a drawing of a staircase, with the pattern you see in the image. The output will be in text format but the bricks can be distinguished one from another. For instance, you may use the 'โ–ˆ' character as half a block and paint it in any color you want, or just choose any character of your choice. Restrictions: * Blocks need to be of three different colors, which will be used as long as possible (if input is 1 or 2 there are not enough blocks to use all three colors). If you want, you may use the 'โ–‘โ–’โ–“' characters, for instance, or just select three different characters. * No two blocks of the same color or pattern can be side to side in a single row. My son does not really care about trailing spaces or new lines as long as a staircase is drawn. Examples (sorry for the bad choice of characters): ``` Input: 1 Output: โ–ˆโ–ˆ Input: 2 Output: โ–ˆโ–ˆ โ–“โ–“ Input: 3 Output: โ–ˆโ–ˆ โ–“โ–“ โ–ˆโ–ˆโ–‘โ–‘ Input: 5 Output: โ–ˆโ–ˆ โ–ˆโ–ˆ โ–ˆโ–ˆโ–‘โ–‘ โ–ˆโ–ˆโ–‘โ–‘ โ–ˆโ–ˆโ–‘โ–‘โ–“โ–“ ``` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` i=2 exec"print(i%2*' '+`2%i*1122`*i)[:i];i+=1;"*input() ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWiCu1IjVZqaAoM69EI1PVSEtdQV07wUg1U8vQ0MgoQStTM9oqM9Y6U9vW0FpJKzOvoLREQ/P/f0MDAA "Python 2 โ€“ Try It Online") Cycles between blocks of `22, 44`, except the top row is `00`. For example, on input 10, prints ``` 00 22 2244 2244 224422 224422 22442244 22442244 2244224422 2244224422 ``` Prints rows of increasing length `i=2,3,..` by creating a space for odd lengths, repeating the pattern `i` times, and trunctating to length `i`. The pattern is `2244` for all rows except the first one `i=2` for which it's `0`. This is achieved with the arithmetic expression `2%i*1122`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21 19~~ 16 [bytes](https://github.com/DennisMitchell/jelly) ``` d2SR+%3x2โถ;แน™แธ‚ยตโ‚ฌY ``` A full program printing the result. Uses `00`, `11`, and `22` as the blocks. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//ZDJTUislM3gy4oG2O@G5meG4gsK14oKsWf///zc)** ### How? ``` d2SR+%3x2โถ;แน™แธ‚ยตโ‚ฌY - Main link: number n ยตโ‚ฌ - for โ‚ฌach "row" in n (i.e. for row, r = 1 to n inclusive): d2 - divmod 2 -> [integer-divide by 2, remainder] i.e. [r/2, r%2] S - sum -> r/2 + r%2 R - range -> [1, 2, 3, ..., r/2 + r%2] + - add r -> [r+1, r+2, r+3, ..., r + r/2 + r%2] %3 - modulo 3 -> [r%3+1, r%3+2, r%3+0, ..., (r + r/2 + r%2)%3] - e.g.: r: 1 , 2 , 3 , 4 , 5 , 6 , 7 , ... [2], [0], [1,2], [2,0], [0,1,2], [1,2,0], [2,0,1,2], ... x2 - times 2 - repeat each twice (e.g. [2,0,1,2] -> [2,2,0,0,1,1,2,2] โถ - literal space character ; - concatenate (add a space character to the left) แธ‚ - r mod 2 (1 if the row is odd, 0 if it is even (1 at the top)) แน™ - rotate (the list) left by (r mod 2) Y - join with newlines - implicit print (no brackets printed due to the presence of characters) ``` [Answer] # JavaScript (ES6), 80 bytes ``` n=>eval(`for(s=11,i=1;i++<n;)s+='\\n'+(' '+'2233'.repeat(n)).substr(i%2,i+1);s`) ``` ``` f= n=>eval(`for(s=11,i=1;i++<n;)s+='\\n'+(' '+'2233'.repeat(n)).substr(i%2,i+1);s`) console.log(f(+prompt())) ``` --- # JavaScript (ES6), 87 bytes Previous solution. ``` n=>[11,...Array(n).fill(' '+'2233'.repeat(n)).map((r,n)=>r.slice(n%2,n+3+n%2))].join` ` ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~21~~ ~~20~~ ~~18~~ 17 bytes Uses the interesting fact that `4^(N+2)/5 = [3,12,51,204,...] = b[11,1100,110011,11001100,...]` ``` F4NรŒm5รทbDรฐรฌ}rยทIF, ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fzcTvcE@u6eHtSS6HNxxeU1t0aLunm87//4YGAA "05AB1E โ€“ Try It Online") **Explanation** ``` F # for N in 0...input-1 do 4 # push 4 NรŒ # push N+2 m # push 4^(N+2) 5รท # integer division by 5 b # convert to binary D # duplicate รฐรฌ # prepend a space to the copy } # end loop r # reverse stack ยท # multiply top of stack by 2 IF # input times do , # print with newline ``` [Answer] # [SOGL](https://github.com/dzaima/SOGL), ~~31~~ ~~28~~ ~~27~~ 25 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` โˆซยณ2\@*O"ยฒbโ€œ2โตI%*r*;IยปยซnKp ``` Explanation: ``` โˆซ iterate input times, pushing 1-indexed counter ยณ get 3 total copies of it on stack 2\ 1 if divides by 2, else 0 @* get that many spaces O output in a new line "ยฒbโ€œ push 1122 2โตI%* multiply 1122 by 2%(iteration+1) r convert to string * multiply by iteration ;Iยปยซ get one iteration variable ontop of stack n increase, floor divide by 2, multiply by 2 (gets the amount of bricks in a line) Kp split that multiplied string in pieces of that length ``` using [this technique](https://codegolf.stackexchange.com/a/124558/59183) Example output for 9: ``` 00 22 2244 2244 224422 224422 22442244 22442244 2244224422 ``` ### 22 bytes ``` โˆซยณ2\@*O"ยฒbโ€œ2โตI%*;Iยปยซmp ``` The command `m` has been documentated on [the 1st SOGL commit](https://github.com/dzaima/SOGL/blob/f271baa60c11a24abec684cb9406f11c287ed315/charDefsParser/data/charDefs.txt#L359), just not implemented. [Answer] ## PHP, ~~61~~ 59 ``` aa<?for(;++$i<$argn;)echo" ",str_pad(" "[~$i&1],2+$i,bbcc); ``` works pretty much like the python versions but uses all three colors if possible. No trailing new line. ``` -2 bytes by @user63956. Thanks ! ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 29 bytes ``` VQI!%hN2pd)Vh/N2p*2@G%+NH3)pb ``` [Test it online!](https://pyth.herokuapp.com/?code=VQI%21%25hN2pd%29Vh%2FN2p%2A2%40G%25%2BNH3%29pb&input=7&debug=0) **Explanations** ``` VQI!%hN2pd)Vh/N2p*2@G%+NH3)pb VQ For N in range(0, input) I!%hN2pd) If N is odd, print a leading space Vh/N2 ) For H in range(0, N / 2 + 1) @G%+NH3 Select the letter at position (N + H) % 3 in the alphabet *2 Then make it a two letters string ("aa" or "bb" or "cc") p Print it pb End the line by printing a new line ``` I am sure there are a lot of ways to shorten that code, but I am king of tired right now... Will try later. [Answer] ## Batch, 125 bytes ``` @set s=โ–ˆ @for /l %%i in (2,1,%1)do @call:c :c @set s= %s:โ–ˆ= % @set s=%s:โ–“=โ–ˆ% @set s=%s:โ–‘=โ–“% @set s=%s: =โ–‘โ–‘% @echo %s% ``` Note: Save this in CP437 or CP850 or some such. Works by rotating the colours each time. Since I can't map over the string to perform the rotation, I use four replacements, using spaces as a temporary stage. This then also allows me to prefix a space every line, so that two spaces turn into a new block. Sample output: ``` โ–‘โ–‘ โ–“โ–“ โ–‘โ–‘โ–ˆโ–ˆ โ–“โ–“โ–‘โ–‘ โ–‘โ–‘โ–ˆโ–ˆโ–“โ–“ ``` ]
[Question] [ [![xkcd: Scheduling Conflict](https://imgs.xkcd.com/comics/scheduling_conflict.png "Neither a spokesperson for the organization nor the current world champion could be reached for comment.")](http://xkcd.com/1542) (I meant to post this while [1542: Scheduling Conflict](http://xkcd.com/1542) was still the current xkcd, but I had a scheduling conflict.) ## Input The input will be a list of `3n` elements, which represent `n` events. The first element in each group of 3 will be the name of an event; the second and third, the start and end time respectively. For example: ``` foo 12 34 bar 56 78 ``` represents an event `foo` that starts at "time 12" (times are represented simply by integers; you can think of them as minutes past midnight) and ends at 34, and a second event `bar` that starts at 56 and ends at 78. The names of events will always consist of only alphanumeric characters, and the times will always be integers โ‰ฅ 0 and < 1440. The end time will always be at least 1 greater than the start time. They are not guaranteed to be sorted in any way. If you would like, you may take this as a single space-separated string; otherwise it should be taken as an array, list, vector, or your language's equivalent. ## Output The output should be a space-separated list of event names. The rules for which event names to output are as follows: * None of the events that you output may conflict with each other. For example, with the input `a 0 10 b 5 15`, you may not output both `a` and `b` because the times conflict (that is, partially overlap). If an event ends exactly as another one starts, you may include both. * You may not output the event called `NSCC` ("National Scheduling Conflict Competition"), of which there will *always* be exactly one of in the input. You also **must** output at least one event that conflicts (partially overlaps) with `NSCC` (and there will always be at least one of those as well). * You must output as many events as possible while following the above two rules. (This is so that you look as busy as possible, so that missing the NSCC seems more credible.) This may also be output as either a single space-separated string or an array, list, vector, etc. There can be more than one possible output. ## Test cases Note that the outputs listed are only examples. Your code may output something different, as long as it still follows the three rules above (notably, this means there must be the same *amount* of events as the example). In: `UnderwaterBasketWeavingConvention 50 800 NSCC 500 550` Out: `UnderwaterBasketWeavingConvention` In: `SconeEating 0 50 RegexSubbing 45 110 CodeGolfing 95 105 NSCC 100 200` Out: `SconeEating CodeGolfing` In: `VelociraptorHunting 0 300 NerdSniping 200 500 SEChatting 400 700 DoorknobTurning 650 750 NSCC 725 775` Out: `NerdSniping DoorknobTurning` In: `NSCC 110 115 A 100 120 B 120 140 C 105 135 D 100 105 E 135 500` Out: `C D E` In: `A 800 900 NSCC 700 1000 B 650 750 C 950 1050 D 655 660 E 660 665 F 1030 1040 G 1040 1060` Out: `A D E F G` In: `A 10 11 B 11 12 C 12 13 D 13 14 NSCC 15 1090 E 10 16` Out: `E` Feel free to add more test cases in an edit if there are edge-cases that I missed. ## Rules * Your code must complete within 30 seconds for all of the provided test cases (this is more of a sanity check, as it should probably complete much faster for all the test cases combined) on a reasonable personal machine. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # SWI-Prolog, ~~537~~ ~~524~~ ~~516~~ ~~502~~ ~~447~~ 436 bytes ``` z(A:B:C,[D:E:F|G]):-(A=D;B>=F;E>=C),(G=[];z(A:B:C,G)). u([A|B],C):-z(A,C),(B=[];u(B,C)). y([A,B,C|D])-->[A:B:C],(y(D);{_=_}). d-->[A:_],{write(A),tab(1)},d;{_=_}. l([H|T],R):-T=[],R=H;length(H,N),l(T,X),length(X,M),(N>M,R=H;R=X). v([],_,R,R). v([A|T],Z,B,R):-u(A,A),\+z(Z,A),v(T,Z,[A|B],R);v(T,Z,B,R). s([E|T],[F|N]):-E=F,(N=[];s(T,N));s(T,[F|N]). x(A):-y(A,D,[]),K="NSCC":_,select(K,D,E),setof(L,s(E,L),B),v(B,K,[],R),l(R,S),d(S,[]),!. ``` Brief explanation of what each predicate does: * `z(A,B)` checks that an event A doesn't conflict with any event of a list of events B * `u(A,B)` checks that every event of a list A does not conflict with any event of a list B (used to check that there are no conflicts in list A by calling `u(A,A)`) * `y(A,B,C)` splits a List into a list of triplets (to transform inputs into a list of events) * `d(A)` prints the names of events in a list A * `l(A,R)` evaluates the longest list of events R contained in the list of lists A * `v(A,NSCC,C,R)` returns a list R containing every list of events in A that have no internal conflict and that conflict with the event NSCC * `s(A,B)` true if B is a subset of A * `x(A)` main predicate, A is the input. **Test cases**: execute `test.` in the interpreter after loading the code above with the following added after it: ``` test:- x(["UnderwaterBasketWeavingConvention",50,800,"NSCC",500,550]), nl, x(["SconeEating",0,50,"RegexSubbing",45,110,"CodeGolfing",95,105,"NSCC",100,200]), nl, x(["VelociraptorHunting",0,300,"NerdSniping",200,500,"SEChatting",400,700,"DoorknobTurning",650,750,"NSCC",725,775]), nl, x(["NSCC",110,115,"A",100,120,"B",120,140,"C",105,135,"D",100,105,"E",135,500]), nl, x(["A",800,900,"NSCC",700,1000,"B",650,750,"C",950,1050,"D",655,660,"E",660,665,"F",1030,1040,"G",1040,1060]), nl, x(["A",10,11,"B",11,12,"C",12,13,"D",13,14,"NSCC",15,1090,"E",10,16]). ``` This took me way more time than I thought it would. This can probably be golfed significantly more. Also you could probably use the various constraint programming libraries that exist to get shorter solutions. **Edit:** Thanks to @Oliphaunt for the idea of using `A:B:C` instead of `[A,B,C]` for triplets. Saves 14 bytes. **Edit2:** Thanks again to @Oliphaunt for pointing out that the predicate ``t/3`was useless. Saves 55 bytes **Edit3:** Gained 11 bytes using definitive clause grammar on predicates `y` and `d`. [Answer] # Pyth, 45 bytes ``` AGH.gqhk"NSCC"m,hdrFtdcQ3hMef&.{KseMT@KehHtyG ``` This one was quite tough to golf. Found quite a few 45 byte solutions, this one is probably the most exotic one, since it uses `A` (pair-assign) and `.g` (group-by). Try it online: [Demonstration](http://pyth.herokuapp.com/?code=AGH.gqhk%22NSCC%22m%2ChdrFtdcQ3hMef%26.%7BKseMT%40KehHtyG&input=%22A%22%2C%2010%2C%2011%2C%20%22B%22%2C%2011%2C%2012%2C%20%22C%22%2C%2012%2C%2013%2C%20%22D%22%2C%2013%2C%2014%2C%20%22NSCC%22%2C%2015%2C%201090%2C%20%22E%22%2C%2010%2C%2016&debug=0) or [Test harness](http://pyth.herokuapp.com/?code=QFQ.QAGH.gqhk%22NSCC%22m%2ChdrFtdcQ3hMef%26.%7BKseMT%40KehHtyG&input=%22Test%20cases%3A%22%0A%22UnderwaterBasketWeavingConvention%22%2C%2050%2C%20800%2C%20%22NSCC%22%2C%20500%2C%20550%0A%22SconeEating%22%2C%200%2C%2050%2C%20%22RegexSubbing%22%2C%2045%2C%20110%2C%20%22CodeGolfing%22%2C95%2C%20105%2C%20%22NSCC%22%2C%20100%2C%20200%0A%22VelociraptorHunting%22%2C%200%2C%20300%2C%20%22NerdSniping%22%2C%20200%2C%20500%2C%20%22SEChatting%22%2C%20400%2C%20700%2C%20%22DoorknobTurning%22%2C%20650%2C%20750%2C%20%22NSCC%22%2C%20725%2C%20775%0A%22NSCC%22%2C%20110%2C%20115%2C%20%22A%22%2C%20100%2C%20120%2C%20%22B%22%2C%20120%2C%20140%2C%20%22C%22%2C%20105%2C%20135%2C%20%22D%22%2C%20100%2C%20105%2C%20%22E%22%2C%20135%2C%20500%0A%22A%22%2C%20800%2C%20900%2C%20%22NSCC%22%2C%20700%2C%201000%2C%20%22B%22%2C%20650%2C%20750%2C%20%22C%22%2C%20950%2C%201050%2C%20%22D%22%2C%20655%2C%20660%2C%20%22E%22%2C%20660%2C%20665%2C%20%22F%22%2C%201030%2C%201040%2C%20%22G%22%2C%201040%2C%201060%0A%22A%22%2C%2010%2C%2011%2C%20%22B%22%2C%2011%2C%2012%2C%20%22C%22%2C%2012%2C%2013%2C%20%22D%22%2C%2013%2C%2014%2C%20%22NSCC%22%2C%2015%2C%201090%2C%20%22E%22%2C%2010%2C%2016&debug=0) ### Explanation ``` implicit: Q = input list cQ3 split Q into triples m map each triple d to: , the pair containing hd - d[0] (name) rFtd - range from start-time to end-time .g group these tuples k by: qhk"NSCC" k[0] == "NSCC" AGH pair assign to G,H. This assigns all tuples != NSCC to G, and the NSCC one to H yG generate all subsets of G t remove the first one (the empty subset) f filter for subsets T, which satisfy: eMT get the last item (the range) for all tuples in T s and combine them (sum) K assign to K .{ check for uniqueness of K (no overlapping times) & and @KehH check the intersection of K and H[0][1] e take the last element (most events) hM get the first item (name) for each event and implicitly print this list ``` [Answer] # JavaScript (*ES6*), 228 Second try, I hope this one works. My target is the longest sequence of events that has a timing conflict, but no timing conflict when the event NSCC is removed. This modified sequence with NSCC removed is the output requested. I use a Breadth First Search examining a queue of candidate solutions, starting with longest (the first is the initial list). From a candidate solution of *n* events I build and enqueue *n* more candidate solutions, removing one of the events and keeping the others. A candidate solution is valid if there is a timing conflict 'as is', but when the NSCC event is filtered out there is no conflict. I use a subfunction K to check for conflicts. Probably could be golfed a little more... Test running the snippet below (being EcmaScript 6, FireFox only) ``` F=l=>(K=>{ l.map(v=>l.push(l.splice(0,3)));// I'm particularly proud of this trick for grouping in triplets (in pith it's "cQ3") for(S=[l.sort((a,b)=>a[1]-b[1])];!K(l=S.shift())|K(m=l.filter(x=>x[0]!='NSCC'));) l.map((v,i)=>(S.push(n=[...l]),n.splice(i,1))); })(l=>l.some(x=>[p>+x[1],p=+x[2]][0],p=0))||m.map(x=>x[0]) // Less golfed and ES5 function Find(l) { var n,m; var Check = function(l) { // check timing conflict comparing start time and end time of previous event (events must be sorted) var p = 0 // previous event end time, init to 0 return l.some( function(x) { var err = p > +x[1]; // unary plus convert string to number p = +x[2]; // update end time return err; }); }; // group initial array in triplets // forEach repeats for the initial number of elements in l, even if l becomes shorter // so it loops more times than necesary, but it works anymay l.forEach(function() { l.push(l.splice(0,3)); // remove first 3 elements and add to back as a triple }) l.sort(function(a,b) { return a[1]-b[1]} ); // sort by start time var S=[l]; // S is the main queue, start with complete list while (l = S.shift(), // current list m = l.filter( function(x) { return x[0]!='NSCC'} ), // current list with NSCC removed !Check(l)|Check(m)) // loop while list ha no errors or filtered list do have errors { // build new candidate to check l.forEach ( function(v,i) { n = l.slice(); // make a copy of l n.splice(i,1); // remove ith element S.push(n); // put in S }); } // when exiting while, m has the list with NSCC removed return m.map( function(x) { return x[0]; }); // keep the event name only } // Test out=(...x)=>O.innerHTML += x + '\n'; test=[ ['UnderwaterBasketWeavingConvention 50 800 NSCC 500 550','UnderwaterBasketWeavingConvention'] , ['SconeEating 0 50 RegexSubbing 45 110 CodeGolfing 95 105 NSCC 100 200','SconeEating CodeGolfing'] , ['VelociraptorHunting 0 300 NerdSniping 200 500 SEChatting 400 700 DoorknobTurning 650 750 NSCC 725 775' ,'NerdSniping DoorknobTurning'] , ['NSCC 110 115 A 100 120 B 120 140 C 105 135 D 100 105 E 135 500','C D E'] , ['A 800 900 NSCC 700 1000 B 650 750 C 950 1050 D 655 660 E 660 665 F 1030 1040 G 1040 1060','A D E F G'] , ['A 10 11 B 11 12 C 12 13 D 13 14 NSCC 15 1090 E 10 16','E'] ] test.forEach(x=>{ var l=x[0].split(/\s+/), r=F(l).sort().join(' '), e=x[1].split(/\s+/).sort().join(' '); out('Test ' + (r==e ? 'OK':'FAIL')+'\nInput: '+x[0]+'\nResult: '+r+'\nExpected: '+e) } ) ``` ``` <pre id=O></pre> ``` [Answer] # Java, 828 bytes There's probably a more concise Java implementation out there, but here's my stab: ``` String s(String e){String[] a=e.split(" ");String m="";String[] c=g(a.length/3);int l=0;for(int i=0;i<a.length;i+=3)if(a[i].equals("NSCC"))l=i/3;for(String p:c)if(p.indexOf(l+"")==-1&&!h(p,a)&&h(p+l,a)&&p.length()>m.length())m=p;String r="";for(int i=0;i<m.length();i++)r+=a[3*(m.charAt(i)-48)]+((i==m.length()-1)?"":" ");return r;}boolean h(String c, String[] e){for(int i=0;i<c.length()-1;i++){int p=c.charAt(i)-48;for(int j=i+1;j<c.length();j++){int q=c.charAt(j)-48;if((Integer.parseInt(e[3*p+1])-Integer.parseInt(e[3*q+2]))*((Integer.parseInt(e[3*p+2])-Integer.parseInt(e[3*q+1])))<0)return true;}}return false;}String[] g(int n){if(n>1){String[] result=new String[(int)Math.pow(2,n)];String[] l=g(n-1);for(int i=0;i<l.length;i++){result[2*i]=l[i];result[2*i+1]=l[i]+(n-1);}return result;}else return new String[]{"","0"};} ``` [Answer] # Python, 373 characters ``` import itertools as j a=zip(*[iter(input())]*3) f,g,r=[],0,"NSCC" p=f for q in a: p=(p,q)[q[0]==r] for h in range(1,len(a)+1): for i in j.combinations(a,h): s,i,l,m=0,sorted(i,key=lambda k:int(k[1])),-1,len(i) for n in i: s=(s,1)[p[1]<n[2]or p[2]<n[1]] if r==n[0]or n[1]<l: m=-1 break else: l=n[2] if s*m>g: g,f=m,i for o in f: print o[0] ``` Creates all possible combinations and checks each one. ### Test **Input:** `["NSCC",110,115,"A",100,120,"B",120,140,"C",105,135,"D",100,105,"E",135,500]` **Output:** ``` D C E ``` ]
[Question] [ FizzBuzz is where a range of positive integers is taken, and numbers divisible by 3 are replaced with "Fizz", divisible by 5 with "Buzz" and divisible by 15 with "FizzBuzz". I've got some FizzBuzz output here. Unfortunately, it's been shuffled: ``` 4 Fizz Fizz Buzz 2 ``` A bit of logic shows us that this is `2, Fizz, 4, Buzz, Fizz` shuffled. Your challenge is to take a range of FizzBuzz, shuffled, and put it in any order such that it's valid FizzBuzz. For example, given `Fizz, Fizz, Buzz, 11` we can work out that the correct order is `Fizz, Buzz, 11, Fizz` (corresponding to `9, 10, 11, 12`) Input will always be rearrangeable into valid FizzBuzz. You may choose any values that cannot appear as integers to represent Fizz, Buzz and FizzBuzz. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! ## Testcases ``` 1, 2, Fizz, 4, Buzz -> 1, 2, Fizz, 4, Buzz Fizz, 4, Buzz, 1, 2 -> 1, 2, Fizz, 4, Buzz Fizz, Fizz, Buzz, 11 -> Fizz, Buzz, 11, Fizz Fizz, Buzz, 8, Buzz, 7, Fizz -> Buzz, Fizz, 7, 8, Fizz, Buzz Buzz, Fizz -> either way 29, 31, FizzBuzz -> 29, FizzBuzz, 31 28, Fizz, FizzBuzz, 29 -> Fizz, 28, 29, FizzBuzz 8, 7 -> 7, 8 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~21~~ 15 bytes ``` แน–รžโˆžฦ›โ‚โ‚ƒโ‚…Tโˆจ;รžS$โ†”h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZbDnuKInsab4oKN4oKD4oKFVOKIqDvDnlMk4oaUaCIsIiIsIjI4LCBbMF0sIFswLCAxXSwgMjkiXQ==) Why use clever mathematics when you can just generate infinite FizzBuzz? *-6 thanks to Steffan and emanresuA* ## Explained ``` แน–รžโˆžฦ›โ‚โ‚ƒโ‚…Tโˆจ;รžS$โ†”h แน– # All permutations of the input รžโˆž # An infinite list of positive integers starting at 1 ฦ› ; # To each number n: โ‚โ‚ƒโ‚… # [n % 3 == 0, n % 5 == 0] T # Truthy indices of that โˆจ # Logical or that with the number. This gets either the indices of where Fizz or Buzz would usually be or n รžS # Sublists of the infinite fizzbuzz $โ†” # Remove sublists which don't have everything from the input h # Get the first item of that ``` [Answer] # [J](http://jsoftware.com/), 54 bytes ``` (-:&(/:~)"1#])#]\1((,~{~0=])2-@#.0=5 3|])@+#i.@+9>.>./ ``` [Try it online!](https://tio.run/##jZBda4MwFIbv/RUvFaZSTU3saCtYZINdjQ3GLitiS4qOMctiKcPhX3fHRmtvBr0IyXnOcz7IRzth1h5RCAsufIR0PIbHt@en1vbCO3sWNs6Em4ljJhtu225TN36UOMKLTeZH9wh@EyeemgWLp6s1W7NZ6xgvDwx2wZr6lioqMeQuL7EHdyFcpHTN6RIDXmKhn9a7VBV2mZLK0oRDkI852fBC1KzrMrL/pSGmnJYIdCHvHlfSgHvp3GhBG2l@LYqOCkqmvSxWSAMEYzsCFKXBZaBY9tLF0I0DwlrqRg3J8Rtej9XhWClsyyrHKftROOXyS4fZt8ShVKrYfkpr@MHz3kb7Bw "J โ€“ Try It Online") \_1, \_2, \_3 represent Fizz, Buzz, FizzBuzz. * Generate all integers from 1 to `<list length>` + max(9, `<max value>`) * Fizz Buzz them * Sliding window across them of size `<list len>` * Find ones which set equal the input [Answer] # JavaScript (ES6), 82 bytes *Saved 2 bytes thanks to a suggestion by [@emanresuA](https://codegolf.stackexchange.com/users/100664/emanresu-a)* Expects and returns `-1` for *Fizz*, `-2` for *Buzz*, `-3` for *FizzBuzz*. ``` f=(a,i=k=0)=>[...b=a.sort().map(_=>-!(++i%3)-2*!(i%5)||i)].sort()+''==a?b:f(a,++k) ``` [Try it online!](https://tio.run/##VY9tT8IwFIW/71dcSEhb2zWwaXgxxcRE/gAfJzFldFiZHa7DRBi/fXRvUb@095ycPuf2Q35LG@f6WPgm26mqSgSWTIuDGBOxjDjnWyG5zfICE/4pj/hNLP0BplSPQuIHdwOsRw@kLDXZdCmKkBDyabtIHIjSA6ly9XXSucIosYjwXMndSqdq/WNiPCa8yNZFrs3e8e0x1QUevpoh4UmWv8j4HVsQS7h4AKkqQIIA28UQA9Su1ETwZaXP5wX4EwbPp2YKGNRep8IriewGyhKoJY8OGGfGZqniabbHbteWZWpWhPp3dUl/1x7aRAYohA3HEMe5kso1dlUM7tt2759iUEc6rz07e@L9lbN@mLYxr1XNGMwZhJPfH3nBrGf1luuYe86d3gA "JavaScript (Node.js) โ€“ Try It Online") The underlying algorithm is the same as in [my answer to the twin challenge](https://codegolf.stackexchange.com/a/249239/58563). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 55 bytes ``` ๏ผท๏ผณโŠžฯ…ฮนโฎŒโŠŸฮฆ๏ผฅโท๏ผฅ๏ผฅฯ…โปโบโŒˆ๏ผฅฯ…ฮฃโบฯˆฮฝฮบฮผโˆจโบโއ๏นชฮปยณฯ‰Fizzโއ๏นชฮปโตฯ‰Buzz๏ผฉฮปโฌคฮนโผโ„–ฮนฮปโ„–ฯ…ฮป ``` [Try it online!](https://tio.run/##ZU/NasMwDL7nKURPCrinUTroaS0N7BAW1r2A6cxiqtipbbVrX96Tk/Y0gazvDwkfex2OXlPO196SAXx3I6dDCtb9YF1Dx7FHVmDrTdWJmPDTXEyIBjs/YmMpmYCtHnGtoIzSEm@t44gdydPqXzvw8HQOAif9psDVUgpO0kMBH2G2vkxwOtyw9d9MHknBi7hXBYvG3u8Lwf8Tq0diyyUhZKdjQpovvBGhVbA/s6aIO8/yD@FUYhPhQuba5FyuVGVR9TqPdTVJeXmhPw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผท๏ผณโŠžฯ…ฮน ``` Input the shuffled range. ``` โŒˆ๏ผฅฯ…ฮฃโบฯˆฮฝ ``` Calculate the largest integer in the range. ``` ๏ผฅฯ…โปโบ...ฮบฮผ ``` Calculate a descending range of integers starting with that integer, but also offset by the outer loop index (see below). ``` ๏ผฅ...โˆจโบโއ๏นชฮปยณฯ‰Fizzโއ๏นชฮปโตฯ‰Buzz๏ผฉฮป ``` Calculate the FizzBuzz output for that range. ``` โฎŒโŠŸฮฆ๏ผฅโท...โฌคฮนโผโ„–ฮนฮปโ„–ฯ…ฮป ``` Calculate 7 ranges sliding up by 1 each time, and output one which matches the input, reversing it to put it back into order. (7 is needed for the edge case of `Buzz Fizz`.) 37 bytes for a boring numeric version: ``` ๏ผฉโฎŒโŠŸฮฆ๏ผฅโท๏ผฅ๏ผฅฮธโปโบโŒˆฮธฮบฮผโˆจยฑโบยฌ๏นชฮปยณโŠ—ยฌ๏นชฮปโตฮปโฌคฮนโผโ„–ฮนฮปโ„–ฮธฮป ``` [Try it online!](https://tio.run/##XU49C8IwFPwrGV8hGVREwUmqbq3FtXSIbdDga9N8Ff99TJrNg7t7j7vh@jc3veIYQmPk5KDk1sFDLMJYAY2a4SbRCQMVn@FASbJEHU85eQsNRqn4V45@BF1Q8okciyh3A7V4cSdyp1YOKjV4VICU7FLjovwTxfAX7YsESnDVMyJISq7ac7RQKh83yhRSkh@dmytOIbQt21DCtpQcs8XRbNN1gS34Aw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Uses `-1` for Fizz, `-2` for Buzz and `-3` for Fizzbuzz. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` โˆžฮตD35Sร–ฦถ(Oโ€š0Kฮธ}Igโ€žรผรฟ.V.ฮ”{I{Q ``` Not too happy about this.. I have the feeling this can be a lot shorter.. :/ [Try it online](https://tio.run/##yy9OTMpM/f//Uce8c1tdjE2DD087tk3D/1HDLAPvcztqPdMfNcw7vOfwfr0wvXNTqj2rA///jzbR0TUEIyMdo1gA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8fdcw7t9XF2DT48LRj2zT8HzXMMvA@t6P20Lr0Rw3zDu85vF8vTO/clOpD66oD/9fq/I@ONtHRNQQjIx2jWJ1oQx0jEA8oCuJBWTqGOlAeRKGhIZRnpGMBIsyB4iARIwhtZKljDJQ0BjEtwFqMdYwsgTwLHXMwCRQyB1kQCwA). **Explanation:** ``` โˆž # Push the infinite positive list: [1,2,3,...] ฮต # Map each value to: D # Duplicate the current value 35S # Push pair [3,5] ร– # Check if the value is divisible by 3 and/or 5 ฦถ # Multiply the check by their 1-based index ( # Negate them O # Sum them (-1 if only divisible by 3; -2 if only 5; -3 if both; # 0 if neither) โ€š # Pair it with the current value 0K # Remove all 0s ฮธ # Pop and keep the last value } # Close the map Ig # Push the length of the input-list โ€žรผรฟ # Push string "รผ<length>" .V # Evaluate and execute it as 05AB1E code, # `รผn` created overlapping lists of size `n` .ฮ” # Then find the first which is truthy for: { # If it's sorted Q # is equal to I{ # the sorted input-list ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 149 bytes ``` lambda a,e=enumerate:{p for p in permutations(a)if all(j in(l:=k+i-n,-(l%3<1)-2*(l%5<1))for k,j in e(p)for n,i in e(p)if i>0)} from itertools import* ``` [Try it online!](https://tio.run/##fVHBTuMwEL37K@aCYoNT0XRRabXhsBJc97I34GCWCTV1YstxBAXx7d2ZpKHtCpGD8@a9N@M3SdiklW9mlyFuq/Ju60z98GjAaCyx6WqMJuHyPUDlIwSwDQSMdZdMsr5ppVG2AuOcfCZJumW5PrN5o3PpTmY/pyovTgldEFLcv9ZsA5ShLxttx5Km2Ktz9SGq6GuwCWPy3rVg6@BjOt1GrMr37Ma@vWXLfKoh@9X1sCDI7K6cfYiXlXUIf2KHSwGQ4oZfQPcEDb5LUDLsklSTNjibZAb5FWRqNEH/lHBrmyQpR62AsxGY2PbRPlGHAnQtAkW6Zf6@/zSMeBkaMQ6maOq@nxsiT6skiYpvwte/GBJc/765jtHHIeFDRLPe0m60E6@k4YcG3osDfkGLo0r3lu@tw7lzT9l7zAwOcUhejmA@iNw0EINr3lv2HWIvshVtWmGEF7MRxULDbHfFuBVzY82qKD6H7elisU/K@mGToHrOMufoi8Mwo3DE0b/6f4F/ "Python 3.8 (pre-release) โ€“ Try It Online") Uses `-1` for `Fizz`, `-2` for `Buzz` and `-3` for `FizzBuzz`. Returns all possible options. The idea is to try all permutations and then, for each permutation, find the first integer in the list and check if the rest of the list agrees with that one. [Answer] # Python3, 276 bytes: ``` def v(r,l,k=[]): if any([r,l])==0:yield k;return for i,a in enumerate(l): if a==r[0]or(type(a)==str and r[0]%{'Fizz':3,'Buzz':5,'FizzBuzz':15}[a]==0):yield from v(r[1:],l[:i]+l[i+1:],k+[a]) def f(l): c=0 while(c:=c+1): if(V:=next(v([*range(c,c+len(l))],l),0)):return V ``` [Try it online!](https://tio.run/##bY@xbsIwEIb3PMUtFXZzQwJFgCsvHfoILJaHKDhgxTiRa2hD1WdPbRJoEUw@3//9d/@1nd81drZsXd9vVAVH4tBgzYWkLAFdQWE7IkJPUs4z1mllNlC/OuUPziZQNQ40FqAtKHvYK1d4RUy0nr2cO5HJxhHftYoUYcSHd2HkBmL/6Xvyrk@nCZvh5O0QizmeO8Mnn/@IQoatdFxbuWYfA4qcSTSCaZkaodP4q9OA0iReUA37S54l8LnTRpGS8TLNx1BkzbhVX54ciXh2hd0GHcvUKBt8NMylmFHKhgNh3bdOW08qInKEKcKQGOEllOeYktLkytypCNH2kLm@FzB/jI3y8q9cXMy3hlF9IE1XCLN8lO5TT5f/0lyRkHt1gwVqERr9Lw) ]
[Question] [ ### Challenge Given a set `T` of subsets of a finite set `S={1,2,3,...,n}`, determine whether `T` is a *topology* or not. ### Explanation The *powerset* `P(S)` of some set `S` is the set of all subsets of `S`. Some examples: ``` S = {}, P(S) = {{}} S = {1}, P(S) = {{}, {1}} S = {1,2}, P(S) = {{}, {1}, {2}, {1,2}} S = {1,2,3}, P(S) = {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} ``` A *topology* `T` on the set `S` is a subset of `P(S)` with following properties: * `{}` is in `T` and `S` is in `T` * If `A` and `B` are in `T` then so is their intersection `A โˆฉ B` * If `A` and `B` are in `T` then so is their union `A โˆช B` \* \* This definition is not quite correct, but it is true for finite sets, which is sufficient for the purposes of this challenge. The actual axiom would allow for infinite unions as well, but that is irrelevant in the finite case. ### Details * You can assume that `S = {1,2,...,n}` (or alternatively `S = {0,1,...,n}`) where `n` is the largest integer that appears in the sets of `T`. * The input format is flexible: You can use a string, a list of lists or set of lists or any similar format your langauge can handle. You can also use sets like `S = {0,1,...,n}` if it is more convenient. * The output must be truthey or falsey. * You are allowed to take `n` (or alternatively `n+1` or `n-1`) as an additional input. * If you work with ordered lists, you can assume that the numbers within a set are sorted. You can also assume that the list has a certain order (e.g. lexicographical. * As we represent sets, you can assume that no two entries of their list-representation are equal. ### Examples **Topologies** ``` {{}} over {} {{},{1}} over {1} P(S) over S (see in the explanation) {{},{1},{1,2}} over {1,2} {{},{1},{2,3},{1,2,3}} over {1,2,3} {{1}, {1,2,3}, {1,4,5,6}, {1,2,3,4,5,6}, {}, {2,3}, {4,5,6}, {2,3,4,5,6}} {{}, {1}, {2,3}, {2}, {4,5,6}, {5,6}, {5}, {2,5,6}, {2,5}, {1,5}, {1,2,3,4,5,6}, {1,2,3}, {1,2}, {1,4,5,6}, {1,5,6}, {1,2,5,6}, {2,3,4,5,6}, {2,3,5,6}, {2,3,5}, {1,2,3,5}, {2,4,5,6}, {1,2,5}, {1,2,3,5,6}, {1,2,4,5,6}} {{}, {1}, {1,2}, {1,2,3}, {1,2,3,4}, {1,2,3,4,5}, {1,2,3,4,5,6}, {1,2,3,4,5,6,7}, {1,2,3,4,5,6,7,8}, {1,2,3,4,5,6,7,8,9}} {{}, {1}, {1,2,3}, {1,2,3,4,5}, {1,2,3,4,5,6,7}, {1,2,3,4,5,6,7,8,9}} ``` **non-Topologies** ``` {{1}} because {} is not contained {{},{2}} because {1,2} is not contained {{},{1,2},{2,3}} because the union {1,2,3} is not contained {{},{1},{1,2},{2,3},{1,2,3}} because the intersection of {1,2} and {2,3} is not contained {{},{1},{2},{3},{1,2},{2,3},{1,2,3}} because the union of {1} and {3} is not contained {{}, {1}, {2,3}, {2}, {4,5,6}, {5,6}, {5}, {2,5,6}, {2,5}, {1,5}, {1,2,3,4,5,6}, {1,2,3}, {1,2}, {1,4,5,6}, {1,5,6}, {1,2,5,6}, {2,3,4,5,6}, {2,3,5,6}, {2,3,5}, {2,4,5,6}, {1,2,5}, {1,2,3,5,6}, {1,2,4,5,6}} because {1,2,3,5} is missing {{}, {1}, {2}, {1,2,3}, {1,2,3,4,5}, {1,2,3,4,5,6,7}, {1,2,3,4,5,6,7,8,9}} because {1,2} is missing ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~117~~ ~~99~~ ~~97~~ 91 bytes ``` n,x=input();sum(set.union(*x))!=n*-~n/2>q [map(x.index,(i-i,i|j,i&j))for i in x for j in x] ``` [Try it online!](https://tio.run/##1VNNc4IwEL3zK7Z2poITbYVqqx17s8f20N4cDqjrGIuBQhhhbPvXaUKQD9GTpzLDZPfl5e1uePgJX3vMTBfeEietVitlJJ5Q5kdcN57CaKuHyHsRox7TO7FhXE1Yp/vLbs3nL222dXw97lG2xJjotEsJ/d4QerMxjJUXAAXKIAYZbrLQToW@tltTF@EjiHCsAfAgkYt4MMYFyC5U6geUcWi/eoBB4AVtTTIW6HN4Txh34qlE86PXgFufJ@BShjBHvkNkQjni6wQctoSV44YJLJwQw4p4qTh9e6nLMQ@yKwAXV1yB8wCdz@LIuNZkdrid3pGZuCzdsEHr5yHZ939szaxk4iWmwKwaZhJL7YjV1oZkJlHIgSy4JwMyLLAiVRqwz3kFq@Rkcgda/6fkmrUDh0URCpWBKjloVq42ZzZ6rHAaHeVJNSzl8wZqVarbJXoYb3Q0XtFO2Z4sXZvg3DgqJQ8NgDyegMjodPla3Uaxk@qZlLRNZpiKOeQwe2ULq2GjY@McmUq81hnmP/HERUYwL/wc5W8rftg/ "Python 2 โ€“ Try It Online") Output is via exit code [Answer] # [Haskell](https://www.haskell.org/), ~~95 89 74~~ 78 bytes ``` import Data.List t#n=all(`elem`t)$sort<$>[1..n]:[]:([union,intersect]<*>t<*>t) ``` [Try it online!](https://tio.run/##FcnBCoMwDADQ@76iYA86SkGPop523B@EgGEEVpZGabPv79zhnd6b6odFWkv5PIq5BxnFZ6p2s05XEul3Fs67Db5ev/gNxhgVZ8C5h6@mQ0NS41L5ZbjcN/sbWqakbnVnudJ5B4ABxjAhdlP7AQ "Haskell โ€“ Try It Online") Explanation: ``` ([union,intersect]<*>t<*>t) -- create all unions & intersections [1..n]:[]: -- add the empty list and the full list sort<$> --sort them all -- (as 'union' does not necessarily produce sorted outputs) all(`elem`t)$ -- check whether they are all already contained ``` [Answer] # Mathematica, ~~87~~ ~~73~~ ~~66~~ 63 bytes ``` Outer[{#โ‹‚#2,#โ‹ƒ#2}&,#,#,1]~Flatten~2โ‹ƒ{{},Range@#2}==#โ‹ƒ#& ``` Takes `[T, n]` as input. ### Explanation ``` {#โ‹‚#2,#โ‹ƒ#2}& ``` Function that returns the intersection and the union of the inputs ``` Outer[ ... ,#,#,1] ``` Map that function onto the input list at level 1. ``` ... ~Flatten~2 ``` Flatten the result (the `Outer` part returns a bunch of nested `List`s). ``` ... โ‹ƒ{{},Range@#2} ``` Take the union between the flattened list and `{{}, S}`. This removes duplicates and adds `{}` and `S` to the resulting list. ``` ... ==#โ‹ƒ# ``` Check whether the list from above is equal to the sorted version of the input. [Answer] # [MATL](https://github.com/lmendo/MATL), 38 bytes ``` !t~hXAs1>GXBXH2Z^!"@Z}Z|1MZ&hHm]vAGn~+ ``` Input is a binary matrix where each row is a set, each column is an element, and each entry indicates membership. For example, `{{},{1},{1,2}}` is expressed as `[0 0;1 0;1 1]`. Use the linked [Octave program](https://tio.run/##jY7NCoMwEITvfYq9JYGloP05tAh9lagRAlkjJimK@OxpqkVpTz0szMwO366tvHyqGAcoQLdd8JwxcT9QsiQHXiljcpJ@EU1o@YNX4mcjBMKAwEKrG9uTDT5hGEIjjVNCJNqYaF8A7UhRqXqe3QjhX9QKSsXc@Z7XNpRG7X@MR7Ycq7Xr@ChinKZsRpgyzPG0ijNe8Lplu33Pp7Rle2F@AQ) to convert to this format. [Try it online!](https://tio.run/##y00syfn/X7GkLiPCsdjQzj3CKcLDKCpOUckhqjaqxtA3Si3DIze2zNE9r077//9oQwUDGLRWMARDOAfEAAvBZKAcA2Q9Bsh6DJD1GCD0xAIA "MATL โ€“ Try It Online") Or [verify all test cases](https://tio.run/##5VOxDoIwEN39iuLg4nLPtYlR40BI3BwIRKMbg7pInNRfR2s5etJbGJwMCe29u3v3Sh/nY31qDnnWJPWzypdXzLN8laezYp@MF8WjuGNTTKr0vLsts8tz2qy3TbkblWQN3GLej3UvA7fAR3ARfA4@B59zS9toOyQi6hV/mAwxHwxCQH4cd4EDkj0ke0j2UOhhFW2dHCr7yUDggYoCsdiHeo@jwyFqpHJ5PohZ8qgQs9DjR6fHZ7731PEHbejxyBrGlS8Uf6dYtUCgIFAQKAgUBAoCBRmiWteoK9Lnf@zK/qZvawfDRWj8d7BGyzdFfBc23Mu/ePY3PqUBPh3mgRc). ### Explanation ``` ! % Implicit input. Transpose t~ % Push a negated copy h % Horizontally concatenate both matrices XA % All: true for columns containing only 1 s % Sum 1> % Does it exceed 1? If so, both the empty set and the total % set are in the input G % Push input again XB % Convert each row from binary to decimal. This gives a column % vector of numbers that encode each set's contents. Union and % intersection will be done as bitwise XOR and AND XH % Copy to clipboard H 2Z^! % Cartesian square transposed: gives all pairs of numbers as % columns of a matrix " % For each column @ % Push current column Z} % Split into the two numbers Z| % Bitwise XOR 1M % Push the two numbers again Z& % Bitwise AND h % Concatenate the two results horizontally Hm % Are they members of the vector of encoded sets? This gives % a row vector with the two results ] % End v % Concatenate all stack contents into a vertical vector A % Does it only contain ones? This is the main result: true iff % input is a non-empty topology. The empty input gives false, % and so it needs to be special cased G % Push input again n~ % Is it empty? + % Add thw two results. Implicit display ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~92 71~~ 122 bytes * Thanks a lot to @ovs for a heavy 19 bytes reduction: `&` and `|` shorthands for set operations. * Thanks @notjagan for 5 bytes * Thanks to @ovs for 2 bytes: `set()` as `i-i` Lambda that takes a list of sets as input, and returns True/false. Simply checks if there is an empty set and the union and intersection of each sets(two sets iterated as `i` and `j`) exists in the given list of sets. ``` lambda x:x.sort()or all(k in x[-1]for k in range(1,max(x[-1])))and all(a in x for i in x for j in x for a in[i-j,i|j,i&j]) ``` [Try it online!](https://tio.run/##VY7LDoIwEEV/pSvTJsUEfCxM/JLKYgygg1hIqUkN@u3YB4@66My903On7d763spsrM6XsYHntQBiTmbbt0pT1ioCTUMfBCUxIknzyk68UyBvJU35Ewz1N4wxkIXHwePEsbjKepUOEJjUHD/2bOqcjZ1CqUlFRV9qimzJouxe9iOWEMOXkyF1JeM731zZ8wM/OjG3AEzOCp@am03yJeHtJEKLriJm2RVlnYllEH@royejaUDyHw "Python 2 โ€“ Try It Online") [Answer] ## CJam (23 bytes) ``` {[,M2$2m*{_~&\~|$}/]^!} ``` [Online test suite](http://cjam.aditsu.net/#code=q%22%7B%7D%2C%22%22%5B%5D%20%22erN%25%7B%0A~%3AE%3B%20e%23%20Store%20expected%20output%20for%20later%20check%0A%3A%3A(%20e%23%20Switch%20from%201..(n%2B1)%20to%200..n%0A_e_W%2B%24W%3D)%20e%23%20n%2B1%20as%20additional%20parameter%0A%0A%7B%5B%2CM2%242m*%7B_~%26%5C~%7C%24%7D%2F%5D%5E!%7D%0A%0A~E%3Do%7D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%2C%20%7B5%2C6%7D%2C%20%7B5%7D%2C%20%7B2%2C5%2C6%7D%2C%20%7B2%2C5%7D%2C%20%7B1%2C5%7D%2C%20%7B1%2C2%2C3%2C4%2C5%2C6%7D%2C%20%7B1%2C2%2C3%7D%2C%20%7B1%2C2%7D%2C%20%7B1%2C4%2C5%2C6%7D%2C%20%7B1%2C5%2C6%7D%2C%20%7B1%2C2%2C5%2C6%7D%2C%20%7B2%2C3%2C4%2C5%2C6%7D%2C%20%7B2%2C3%2C5%2C6%7D%2C%20%7B2%2C3%2C5%7D%2C%20%7B2%2C4%2C5%2C6%7D%2C%20%7B1%2C2%2C5%7D%2C%20%7B1%2C2%2C3%2C5%2C6%7D%2C%20%7B1%2C2%2C4%2C5%2C6%7D%7D%200%0A%7B%7B%7D%2C%20%7B1%7D%2C%20%7B2%7D%2C%20%7B1%2C2%2C3%7D%2C%20%7B1%2C2%2C3%2C4%2C5%7D%2C%20%7B1%2C2%2C3%2C4%2C5%2C6%2C7%7D%2C%20%7B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%7D%7D%200). This is an anonymous block (function). I assume `S = {0,1,...,n}`; the block takes an array of sorted arrays and `n+1` as parameters and leaves `0` or `1` on the stack. In the case `{{}}` the code and test framework assume that `n+1 = 0`. [Answer] # Pyth, ~~24~~ 23 bytes ``` q@aasm,@Fd{Ssd*QQYJUEyJ ``` [Test suite](https://pyth.herokuapp.com/?code=q%40aasm%2C%40Fd%7BSsd%2aQQYJUEyJ&test_suite=1&test_suite_input=%5B%5B%5D%5D%0A0%0A%5B%5B%5D%2C+%5B0%5D%5D%0A1%0A%5B%5B%5D%2C+%5B0%5D%2C+%5B1%2C+2%5D%2C+%5B0%2C+1%2C+2%5D%5D%0A3%0A%5B%5B%5D%2C+%5B0%5D%2C+%5B1%5D%2C+%5B4%5D%2C+%5B0%2C+1%5D%2C+%5B0%2C+4%5D%2C+%5B1%2C+2%5D%2C+%5B1%2C+4%5D%2C+%5B4%2C+5%5D%2C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2C+5%5D%2C+%5B3%2C+4%2C+5%5D%2C+%5B0%2C+1%2C+4%2C+5%5D%2C+%5B0%2C+3%2C+4%2C+5%5D%2C+%5B1%2C+2%2C+4%2C+5%5D%2C+%5B1%2C+3%2C+4%2C+5%5D%2C+%5B0%2C+1%2C+2%2C+4%2C+5%5D%2C+%5B0%2C+1%2C+3%2C+4%2C+5%5D%2C+%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+%5B0%2C+1%2C+2%2C+3%2C+4%2C+5%5D%5D%0A6&debug=0&input_size=2) This program takes input as an ordered list of ordered lists. The inner lists must be in ascending order and the order list must be sorted by length then lexicographically. I have confirmed that this is an allowed input format. Numbers start at 0, and N+1 is also taken as input. As for how it works, we filter out anything not in P(S), then add S, `[]`, the intersection of every pair and the union of every pair, deduplicate, and check that the result is equal to the input. [Answer] # Axiom, 358 bytes ``` t(a,s)==(aa:=sort(removeDuplicates(a));ss:=sort(removeDuplicates(s));a:=sort(a);s:=sort(s);a~=aa or s~=ss=>false;a:=map(sort, a);~member?([],a) or ~member?(s,a)=>false;for x in a repeat(for j in x repeat if ~member?(j,s) then return false;for y in a repeat if ~member?(sort(setIntersection(x,y)),a) or ~member?(sort(setUnion(x,y)),a) then return false);true) ``` ungolfed and results: ``` -- all the List have to be sorted because in list [1,2]~=[2,1] -- So here "set" means: "List without duplicate, sorted with sort() function" -- Return true if -- 1) a,s are set for above definition -- 2) a is in P(s) -- 3) s,[] are in a -- 4) for all x and y in a => xUy is in a and x intersect y is in a t1(a:List List INT, s:List INT):Boolean== aa:=sort(removeDuplicates(a));ss:=sort(removeDuplicates(s)) a :=sort(a); s :=sort(s) a~=aa or s~=ss =>false -- they are not sets but list with element duplicate a:=map(sort, a) -- subset of a has to be sorted too ~member?([],a) or ~member?(s,a)=>false for x in a repeat for j in x repeat if ~member?(j,s) then return false for y in a repeat if ~member?(sort(setIntersection(x,y)),a) or ~member?(sort(setUnion(x,y)),a) then return false true (4) -> t([[]], []) (4) true Type: Boolean (5) -> t([[],[1]], [1]) (5) true Type: Boolean (6) -> t([[],[1],[2,1]], [1,2]) (6) true Type: Boolean (7) -> t([[],[1],[2,3],[1,2,3]], [3,1,2]) (7) true Type: Boolean (8) -> t([[1], [1,2,3], [1,4,5,6], [1,2,3,4,5,6], [], [2,3], [4,5,6], [2,3,4,5,6]], [1,2,3,4,5,6]) (8) true Type: Boolean (9) -> t([[], [1], [2,3], [2], [4,5,6], [5,6], [5], [2,5,6], [2,5], [1,5], [1,2,3,4,5,6], [1,2,3], [1,2], [1,4,5,6], [1,5,6], [1,2,5,6], [2,3,4,5,6], [2,3,5,6], [2,3,5], [1,2,3,5], [2,4,5,6], [1,2,5], [1,2,3,5,6], [1,2,4,5,6]], [1,2,3,4,5,6]) (9) true Type: Boolean (10) -> t([[], [1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5], [1,2,3,4,5,6], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8,9]], [1,2,3,4,5,6,7,8,9]) (10) true Type: Boolean (11) -> t([[], [1], [1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8,9]], [1,2,3,4,5,6,7,8,9]) (11) true Type: Boolean (2) -> t([[1]], [1]) (2) false Type: Boolean (4) -> t([[],[2]], [1,2]) (4) false Type: Boolean (5) -> t([[],[1,2],[2,3]], [1,2,3]) (5) false Type: Boolean (6) -> t([[],[1],[1,2],[2,3],[1,2,3]], [1,2,3]) (6) false Type: Boolean (7) -> t([[],[1],[2],[3],[1,2],[2,3],[1,2,3]] , [1,2,3]) (7) false Type: Boolean (8) -> t([[], [1], [2,3], [2], [4,5,6], [5,6], [5], [2,5,6], [2,5], [1,5],[1,2,3,4,5,6], [1,2,3], [1,2], [1,4,5,6], [1,5,6], [1,2,5,6], [2,3,4,5,6], [2,3,5,6], [2,3,5], [2,4,5,6], [1,2,5], [1,2,3,5,6], [1,2,4,5,6]], [1,2,3,4,5,6]) (8) false Type: Boolean (9) -> t([[], [1], [2], [1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8,9]] , [1,2,3,4,5,6,7,8,9]) (9) false Type: Boolean (10) -> t([[], [1], [2,3], [2], [4,5,6], [5,6], [5], [2,5,6], [2,5], [1,5],[1,2,3,4,5,6], [1,2,3], [1,2], [1,4,5,6], [1,5,6], [1,2,5,6], [2,3,4,5,6], [2,3,5,6], [2,3,5], [2,4,5,6], [1,2,5], [1,2,3,5,6], [1,2,4,5,6]], [1,2,3,4,5,6]) (10) false Type: Boolean ``` [Answer] # Python, 87 bytes `lambda n,T:(set(range(n))in T)&all(x in T for i in T for j in T for x in [i-i,i&j,i|j])` Takes the number `n` and a list of sets `T` as input. ]
[Question] [ ## Challenge Implement the 1-indexed sequence [A054049](https://oeis.org/A054049), which starts like this: ``` 1, 2, 3, 6, 13, 5, 9, 377, 21, 11, 89, 14, 8, 233, 16, 987, 18, 2584, 20, 6765, 55, 23, 28657, 25, 75025, 27, 196418, 29, 514229, 31, 1346269, 33, 3524578, ... ``` This sequence is the lexicographically smallest sequence of positive integers, so that indexing into the sequence twice yields the regular Fibonacci sequence: $$ a(a(1)) = a(1) = 1 \\ a(a(2)) = a(2) = 2 \\ a(a(3)) = a(3) = 3 \\ a(a(4)) = a(6) = 5 \\ a(a(5)) = a(13) = 8 \\ a(a(6)) = a(5) = 13 \\ a(a(7)) = a(9) = 21 \\ \vdots $$ The value of \$a(34)\$, the first term that does not fit into the OEIS page, is equal to \$F(377+1)\$, or ``` 4444705723234237498833973519982908519933430818636409166351397897095281987215864 ``` ## I/O and scoring The following I/O methods are allowed: * Take no input, and output the sequence indefinitely. * Take the value of \$n\$ (**1-indexed**), and output the value of \$a(n)\$. + This should follow the definition of \$a(1) = 1\$, \$a(2) = 2\$, and so on. The sequence is broken otherwise. * Take the value of \$n\$, and output first \$n\$ values of the sequence. Due to the indexing nature of this sequence, the indexing is fixed to 1-indexing. The sequence can be considered 0-indexed by including \$a(0) = 1\$ in front of the sequence; you may use this alternative definition for any of the I/O methods. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 226 bytes ``` g=input()+2 f=lambda n,x=1,y=1:n and f(n-1,y,x+y)or x k={1:1,2:2,3:3} s=set(k) x=4 y=6 while g/x: while g/x|g/y:k[y]=f(x);k[x]=y;s|={x};x,y=y,f(x) x,y=sorted(set(range(1,max(s)+3))-s)[:2];s|={y} print map(k.get,range(1,g-1)) ``` [Try it online!](https://tio.run/##PY3BioMwFEXXzVdkmYdxSuIwhcj7EnGRwZiKNYrJ0Bdav93WgZnduVzOvUtO1znoffc4hOUnCSg06/Fmp@/O8iAJlcyoTOA2dLwXoXxnSUWGeeXERnwoo6Q2Wlam2ljE6JIYgRF@soxf7H4dbo77Mxl2@uenP2czNrnFXhDUY0Mt5jo@8UFbTe@/LI@CnQ6O85pcJ47d1QbvhJKTJRGhqADKCI3R7a@bN7asQ0h8sosYP7xL8k/wpQLY98sL "Python 2 โ€“ Try It Online") -33 bytes thanks to ovs [Answer] # [Haskell](https://www.haskell.org/), ~~181~~ 149 bytes ``` 1:2:3:4#(0:1:z) n#(0:x:y:t)|x<1=n#((n+1):f!!n:y:t)|m<-n+2=n#(m:x:f!!n:t) n#(x:t)|(a,_:b)<-splitAt(f!!n-n-1)t=x:(n+1)#(a++f!!x:b) f=1:scanl(+)1f z=0:z ``` [Try it online!](https://tio.run/##JYxBDsIgEEX3PUWbuoAgSWldTcrCA3gDk2ZsijYCIcICG88uQt3Nf//9eaB/LlonlNckoIcBTi3pQMBGK1uuCG8I9BNHIXMmlgkKqmnsH5uRW9aXxmRz52EfxtISPE5woyP3Tq/hHEgRuOWCBhlh/9USZCzjmL1KSQF@RqsJo0JVm@xgSwZXKw26y1S712rDIeBzqYehxvSdlca7T3x27gc "Haskell โ€“ Try It Online") The infinite (1-indexed) sequence (it breaks after the 33rd element because of integer overflow, but the algorithm should in principle work for arbitrarily large numbers). [Here](https://tio.run/##LY2xTsQwEER7f0Wio7BljOzjqlVcINEgQUWLdFqCfVhnL1biwkSIT8ckB93szNuZd5zPLsYWUv6YSnePBW8ew1wY74U9OXJTGB/ozVWG9qUZ2MMtHHZcg4FFMNpUhU8o4qsOxq43J2kE@J7@3DQokvstSCu42eXyVreQ4/U3P8KrEIP633rOMZS7wldSkTKi2AqXyh1HKX1fV5p5a2AekSKXwni2WA1LSxjIJsxPxy5PgcpVwbPrjNa6w/Yz@oinuakx518 "Haskell โ€“ Try It Online") you can find a version that uses the same algorithm with arbitrary precision `Integers` (and, incidentally, is also much more efficient). ## How? To understand the algorithm I've implemented, imagine an infinite array `a` indexed by the positive integers, and a pointer `^` that moves along this array. --- **Step 0**. Initially, the array looks like this: ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 . 13 . . . . . . . . ^ ``` We hardcode into the array the values at positions `1`, `2`, `3` and `5`, and all the other cells of the array are empty. The pointer starts at position `4`, and will only move forwards. --- **Step 1**. Assume the pointer is pointing at an empty cell (otherwise, go to **step 2**), say at position `n`. In the initial configuration, `n=4`. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 . 13 . . . . . . . . ^ ``` Let `m` be the index of the first empty cell after `n`. Conveniently, either `m=n+1` or `m=n+2`, since at most one of `n+1` and `n+2` is a Fibonacci number, and all non-Fibonacci-indexed cells after `n` are empty. Then we write `m` at position `n` and `f(n)` at position `m`, where `f(n)` is the `n`-th Fibonacci number. In the example, `m=6` since cell `5` is not empty; we set `a(4)=6` and `a(6)=f(4)=5`: ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 . . . . . . . ^ ``` After that, we go to **step 2** *without moving the pointer*. --- **Step 2.** Let `n` be the position of the pointer. If we got to this point, there is a number (say `x`) at position `n`. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 . . . . . . . ^ ``` In this example, `x=6`. It's not hard to see that cell `f(n)` will always be empty (except for this example, where `a(5)` was hardcoded). Then we write the number `f(x)` at position `f(n)`. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 . . . . . . . ^ ``` After that, we advance the pointer by `1` and we go back to **step 1**. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 . . . . . . . ^ ``` --- Here are the next few steps of the algorithm. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 . 337 . . . . . ^ ``` โ†‘ **Step 2.** Write `f(13)=337` at position `f(5)=8`; advance the pointer. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 . 337 . . . . 8 ^ ``` โ†‘ **Step 2.** Write `f(5)=8` at position `f(6)=13`; advance the pointer. ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 a(n) | 1 2 3 6 13 5 9 337 21 . . . 8 ^ ``` โ†‘ **Step 1.** Write `m=9` at position `7`; write `f(7)=21` at position `m=9`. [Answer] # JavaScript (ES6), ~~181~~ 171 bytes This is really just a port of [@hyper-neutrino's answer](https://codegolf.stackexchange.com/a/223810/58563). Returns the \$n\$th term of the sequence. ``` n=>(s=new Set(k=[A=n=>s.has(++n)?A(n):s.add(n)|n,1,2,3]),h=(x,y)=>x>n?k[n]:(g=(x,y)=>x>n+1&y>n+1?h(A``,A``):g(y,k[k[s.add(x)|x]=y]=(F=p=>x--?F(q,q+=p):p)(q=1)))(x,y))(4,6) ``` [Try it online!](https://tio.run/##TY7BboQwDETv@xU5rCpbCah0qx7YGsRlf6BHhES0BGhBDmxQC2L5dpq2lx48Hj3Zo/nQn9pdb@/DFLCtzF7TzpSAIzZf4s1M0FGekUcubLUDKRnTDBhjF@qq8ubOKlJP6lSgaglmtSAlc8Jpl3MRQ/MPyehh@dG0hawslR@MG1hUl3f5X9qM97mgpSC40OB/giC9wKhGSQPGA8JIESL@JiI8qxfca3uD3kyCBYno7NcridOjN1KiWA9CXC0725uwtw2UGo4rb@hvj2vtu28lng/b/g0 "JavaScript (Node.js) โ€“ Try It Online") ### Commented **Helper function `A`** ``` A = n => // expects n zero'ish on the initial call s.has(++n) ? // increment n; if n belongs to the set: A(n) // do a recursive call : // else: s.add(n) | n // add n to the set and return n ``` **Main function** ``` n => ( // n = input s = new Set( // create a set s containing: k = [, 1, 2, 3] // the values of the array k = [undefined, 1, 2, 3] ), // (undefined will be quietly ignored thereafter) h = (x, y) => // outer recursive function h taking (x, y): x > n ? // if x is greater than n: k[n] // we're done: return k[n] : // else: ( g = (x, y) => // inner recursive function g taking (x, y): x > n + 1 & // if min(x, y) is greater than n + 1: y > n + 1 ? // h(A``, A``) // do a recursive call to h with the next two // values that are not yet in the set : // else: g( // do a recursive call to g: y, // pass x = y k[ // update k[y]: k[s.add(x) | x] // add x to the set and do k[x] = y = y // ] = ( // set k[y] to the x-th Fibonacci number F = p => // using yet another recursive function F x-- ? // to compute it F(q, q += p) // : // p // )(q = 1) // initial call to F ) // end of recursive call )(x, y) // initial call to g )(4, 6) // initial call to h ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~191~~ 143 bytes\* ``` from itertools import* s=lambda n:[l for l in product(*[range(1,9**9**n)]*9**9**n)if all(l[l[i]]+l[l[i+1]]==l[l[i+2]]for i in range(n))][0][:n] ``` The function `s` takes an integer `n` and returns a tuple of length `n` which starts with `(1, 1, 2, 3, 6, ...)`. This is simple brute force, and is practically infeasible for even `n=2`. To make sure this works you can switch the `9**9**n` for an `8` and it should work for all \$n\le4\$ **\*NOTE:** this assumes that \$\forall\left\{n\ge1\right\}:a\left(n\right)<9^{9^n}\$. I think it's fine as the regular Fibonacci sequence grows as less than \$2^n\$, but if that's false then we might switch this out for triple/quadruple exponentials for an extra cost of 6 bytes per extra exponential for both (just add `9**` before the first `9` on both occurrences in the code) -30 bytes thanks to Bubbler (`import*` and reducing indentation) -18 bytes thanks to Roee Sinai (converting `s` to a one-liner) ]
[Question] [ Make a program that takes a length and list of intervals and outputs a ruler of that length with longer ticks for each interval using the line drawing characters `โ”Œ โ”ฌ โ” โ”‚ โ•ต` * The first row of the output should begin with the tick for 0 with `โ”Œ` and end with a tick for the length with `โ”`, with a `โ”ฌ` being used for every character in between. There will be a total of `length` + 1 line drawing characters in this first row. * A tick should be lengthened vertically by half-character increments using `โ•ต` and `โ”‚` based on the input intervals. * Intervals are listed from smallest to largest, relative to the interval before it. To elaborate: + The first interval tells how many base ticks (the first row - one character per tick) are in the second-smallest interval (the smallest interval being 1). For example, [3] will lengthen every third tick by a half-character. + The second and subsequent intervals are in terms of the next smallest interval. For example [3, 5] will lengthen every 15th base tick by a full character and [3, 5, 2] will lengthen every 30th base tick by a character and a half. + A sub-interval of 1 is valid and effectively means that the last interval lines are lengthened by a full character instead of a half-character. * The example test cases should help to clarify how this works. ## Examples/Test Cases 3, []: ``` โ”Œโ”ฌโ”ฌโ” ``` 9, [3]: ``` โ”Œโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ” โ•ต โ•ต โ•ต โ•ต ``` 30, [5, 2]: ``` โ”Œโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ” โ”‚ โ•ต โ”‚ โ•ต โ”‚ โ•ต โ”‚ ``` 32, [4, 2, 2, 2]: ``` โ”Œโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ” โ”‚ โ•ต โ”‚ โ•ต โ”‚ โ•ต โ”‚ โ•ต โ”‚ โ”‚ โ•ต โ”‚ ``` 48, [5, 3, 2] ``` โ”Œโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ” โ”‚ โ•ต โ•ต โ”‚ โ•ต โ•ต โ”‚ โ•ต โ•ต โ”‚ โ•ต โ•ต ``` 24, [7, 3] ``` โ”Œโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ” โ”‚ โ•ต โ•ต โ”‚ ``` 17, [3, 2, 1] ``` โ”Œโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ”ฌโ” โ”‚ โ•ต โ”‚ โ•ต โ”‚ โ•ต โ•ต โ•ต โ•ต ``` 1, [23, 19, 13, 11, 7, 5, 3, 2, 1] ``` โ”Œโ” โ”‚ โ”‚ โ”‚ โ”‚ โ•ต ``` ## Other Rules/Notes * Input and output can use any convenient format * The ruler doesn't have to end on a major tick * The interval list may be empty * The zeroth tick is *always* within all intervals. * You may assume the ruler length and intervals will always be a positive integers less than 120 * Trailing whitespace is fine, but leading whitespace is not. * Any fixed-single-wide space is allowed as a spacing character if you, for some reason, want to use something other than ASCII spaces. Happy Golfing! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 123 bytes ``` l=>g=([p,q,...t],h='โ”Œ'.padEnd(l,'โ”ฌ')+`โ” `)=>p?h+g(t,h.replace(/\S/g,c=>'โ•ตโ”‚ '[c>'โ•ด'||++i%p?2:i/p%q<1|0],i=-1)):h ``` [Try it online!](https://tio.run/##NY69boMwFEZ3nsJLhC0cE0OitGlNpjxBR9dSLPNbWeCA1Ympc4cO6Vt0bF@IF6EGEulK9ztHn679Jt9lp9rK2HXdpNmYs1GzpGCQG3zBhBArcMn84frpEyPTU51CjR3@@Cg4D9cv74xYYo5lUECLS9JmRkuVwfD1JSywYok/fP8N1w/gczXlX7/vg6BamWN0qEKzujzTfiNwxdYUoUM52qyzSnYZYIB7PMaAC4E9/uhCPKd44@IOg2ihyNHW0TKz2z4sjfguIlfgeydmovvp1tyni3AcOUHdI3TaTrjO7cKtJbz7z0jetCepSgi5xsAKBFgCVFN3jc6IbgqYQ42gRQg9jf8 "JavaScript (Node.js) โ€“ Try It Online") Use this function as `f(20)([5, 2])`. --- Thanks Arnauld, saves 4 bytes. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~130 122 102~~ 92 bytes *-10 bytes thanks to nwellnhof!* ``` {'โ”Œ'~'โ”ฌ'x$^a-1~'โ”',|map {[~] <<' 'โ•ต โ”‚>>[:1[$_ X%%@_]for 0..$a]},batch [\*] @^b: 2} ``` [Try it online!](https://tio.run/##Zc69DoIwEAfw3ae4ASySSmhB8ZPwGCa1mGIkDhqNOkhQBmcHB3wLV1@IF8GDuDVN2ub/6/XuuDnthvU@g24Kc6hzUpVPUuD@IVcjVn3W3F@E3vbqCLkoJMxmBEj1/kJVPsJQTJgwVrAwzWgl08MJXMcxlLzTRF3WWxBLW0IUJxPg9zq1PApC9hz8y7Kds8p6005qjTH0qBZ7LuYDynXgCD7lzdLQH7VVgJ105D5igKgJC9ohAL9mOqJxRIaTsubEAN//u2gV9Q8 "Perl 6 โ€“ Try It Online") Ah yes, much shorter than my previous method. This is an anonymous code block that returns a list of lines. ### Explanation: ``` { } # Anonymous code block 'โ”Œ'~'โ”ฌ'x$^a-1~'โ”', # Return the first line |[\*] @^b # Get the cumulative product of the input list .batch(2) # And split it into pairs .map:{ } # Map each pair to for 0..$a # For each interval :1[$_ X%%@_] # Whether it is divisible by none of the pair, one of the pair, or both <<' 'โ•ต โ”‚>>[ ] # Map to a list of characters [~] # And join ``` [Answer] # Dyalog APL, ~~66~~ ~~64~~ ~~58~~ 52 [bytes](https://github.com/abrudz/SBCS) ``` {'โ”Œโ”'@0โต@0โ‰('โ”ฌโ”‚',โŽ•UCS 9589)/โค1โจ1,โ‰0 2โŠคโŠฅยจโจ0=(โต+1)โดโณโบ} ``` [Try it online!](https://tio.run/##JYs9CsJAEIX7PcV0STDizm5CjCAIHkE8gKARQV3xpxCxsRAUVyxiaadgYac2lh5lLhInkYHH45vvdSbDcnfZGZp@RsfzwND2JLOEc@VQeqD05DQk2XceO5fRg9KN47PabrYgDquxVyF7RbJ39FmRoGh/pf3te2ck6y5vS@iRfZF9kv2ss4zsAxLQSri@9rjFQkGYE8klv@D/VqALHlSFhoiLCgRCThPASJC9wHQxnoFZzMEkMOqNzHRZK/hfC3mFCKgBY1DF7Ac "APL (Dyalog Unicode) โ€“ Try It Online") ~~ยฏ2~~ ~~ยฏ8~~ ยฏ14 bytes thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn)! [Answer] # [Python 3](https://docs.python.org/3/), ~~173~~ 172 bytes ``` def f(w,n): print('โ”Œ'+'โ”ฌ'*~-w+'โ”');R=r=range(w+1) for i,j in zip(*[iter(n+[0])]*2):a=r[::i];r=j*[0]and a[::j];print(''.join(' โ•ตโ”‚'[(v in a)+(v in r)]for v in R)) ``` [Try it online!](https://tio.run/##vZOxboMwEIZ3P8WJxTbQKkCqtESsPEBWxIAUkprBICtq1A4dMndgoG/RtS@UF0kPMCSUKoqUKujAx1m6@@4/u3jdPOfSOxyW6QpWbGtL7hMolJAbRvfVB7Xw@0XN97tt7ZWUzxeBClQi1ynbWg4nsMoVCDsDIeFNFMyMxCZVTFrRJOax6XI/CVTk@yKeqyAzMZrIJSQYyeK5LkTvs1xIRmH/@b2vdjRiL3W6hFuto3hcV2n8BecNbNjB1tQgOSEh82yIYk4MwyDIjuCNlU0gZE@46423x1YS5AAYfHQOb4JJHmxwL8lzpSFGtQPQDLic/@sIXSScImFrN@Ac0rZAF/pdhyePbug00vc2fWzV927Z2NVj@3Ne54NkrMJIJa2Ji7OOZqjJvwtSHqfT4xydfijOrL5XzWlzrmHQ5doLN/J6RU7WDgDruwjg4AV36hUDyKTPyS@qpsrwbRMdfgA "Python 3 โ€“ Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 51 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` รฮตyIฮทPร–O2โ€ฐโ€ข5ยทW4โ€ข2รครงร—SIยฏQiฮตรต}}โ€ขรกฮฃ=Yรดโ€ข3รครงyยนQyฤ€+รจลก}ฮถJยป ``` Not too happy with the `IยฏQiฮตรต}}` as work-around for empty input-lists.. And can definitely be golfed at some other parts as well.. NOTE: Uses compressed integers converted to the required characters, because using the required characters directly means I'll have to count the entire program in UTF-8, increasing it by too much for all 05AB1E's builtin characters as well. [Try it online](https://tio.run/##yy9OTMpM/f//8NxzWys9z20PODzN3@hRw4ZHDYtMD20PNwHSRoeXHF5@eHqw56H1gZnnth7eWlsLFD288Nxi28jDW4BMY5CCykM7AyuPNGgfXnF0Ye25bV6Hdv//b8wVHQsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa9kpaCkU5kQ6hL2//Dcc1srI85tDzg8zd/oUcOGRw2LTA9tDzcB0kaHlxxefnh6cMSh9YGZ57Ye3lpbCxQ9vPDcYtvIw1uATGOQgsrIwMojDdqHVxxdWHtum9eh3f91Dm2z/x8dbawTHRuroxBtqRNtDGYYG@hEm@oYQdhGOtEmOkYgCOabWIDkjKE8IxOdaHMdEzDb0ByoH6jOEMLTiTYy1jG01DEEkoY65jqmOiZAbUDJWAA). **Explanation:** ``` ร # Create a list in the range [0, first (implicit) input-integer] ฮต # Map each value `y` to: Iฮท # Get the prefixes of the second input-list P # Get the product of each prefix y ร– # Check for each if its evenly dividing the value `y` O # Take the sum of that 2โ€ฐ # And then the divmod 2 โ€ข5ยทW4โ€ข # Push compressed integer 94749589 2รค # Split into two equal-sized parts: [9474,9589] รง # Convert each to a character: ["โ”‚","โ•ต"] ร— # Repeat each based on the divmod 2 result S # And convert it to a flattened list of characters IยฏQi } # If the second input-list was empty: ฮตรต} # Map each list to an empty string # (for some reason `โ‚ฌรต` doesn't work here..) โ€ขรกฮฃ=Yรดโ€ข # Push compressed integer 948495169488 3รค # Split into three equal-sized parts: [9484,9516,9488] รง # Convert each to a character: ["โ”Œ","โ”ฌ","โ”"] yยนQ # Check if the value `y` is equal to the first input-integer # (1 if truthy; 0 if falsey) yฤ€ # Check if the value `y` is NOT 0 (1 if truthy; 0 if falsey) + # Add both checks together รจ # Use it to index into the list ["โ”Œ","โ”ฌ","โ”"] ลก # And prepend the result in front of the other characters }ฮถ # After the map: zip/transpose; swapping rows and columns (with space filler) J # Join every inner list together to a single string ยป # Join the lines with newline delimiter (and output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `โ€ข5ยทW4โ€ข` is `94749589` and `โ€ขรกฮฃ=Yรดโ€ข` is `948495169488`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` โ‰”๏ผฅฮทฮ โ€ฆฮทโŠ•ฮบฮทโชซโ”โ”Œร—โ”ฌโŠ–ฮธโ†™โ†“๏ผฅ๏ผฅโŠ•ฮธฮฃ๏ผฅฮทยฌ๏นชฮนฮปโบร—โ”‚โŠ˜ฮนร—โ•ต๏นชฮนยฒโ€– ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DN7FAI0NHIaAoP6U0uUTDuTI5J9U5Ix8s6JmXXJSam5pXkpqika0JBDoKGZrWXAFFmXklGl75mXkaSo@mTHg0pUdJRyEkMze1GMRfA@S4pCI0FoI0WnP55pelali55Jfn@aSmlcBNAYvoKIBcAcLINhYCrQsuzYW50C@/RMMX6MicfI1MHYUcTYh7AnJKizXgdjcB7fZIzCkD6s4EycIkpm4FSiA0G2lC3BSUmpaTCvS0pvX//9EmFjoK0aY6CsZA@djY/7plOQA "Charcoal โ€“ Try It Online") Link is to verbose version of code. Box-drawing characters have a 3 byte representation in Charcoal, so the above string is only 40 characters long. Explanation: ``` โ‰”๏ผฅฮทฮ โ€ฆฮทโŠ•ฮบฮท ``` Calculate the cumulative product of the intervals. ``` โชซโ”โ”Œร—โ”ฌโŠ–ฮธโ†™ ``` Print the first row of tick marks. The left and right characters are the wrong way around because the result is reflected later. ``` โ†“๏ผฅ๏ผฅโŠ•ฮธฮฃ๏ผฅฮทยฌ๏นชฮนฮปโบร—โ”‚โŠ˜ฮนร—โ•ต๏นชฮนยฒ ``` Calculate the number of intervals that are a factor of each tick mark. Generate a string of `โ”‚`s of half that length and add `โ•ต` for odd lengths. Print each string downwards with subsequent strings in previous columns, i.e. reverse order. ``` โ€– ``` Reflect everything to get the ruler in left-to-right order. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~42~~ ~~41~~ 40 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` โ”โ€โ”ฌโ€โ”Œโ€๏ผฏโธโ•ทร—๏ฝ๏ฝโ•ต๏ผˆ๏ผ๏ผ‰โท๏ฝ›๏ผŠ๏ผชโ•ต๏ผ›โˆ”๏ฝ๏ฝ๏ฝ›๏ผ’๏ฝŽโ€œโ•ตโ€ร—๏ผ›โ€œโ”‚โ€ร—ร—๏ผฝโคข ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTEwJXUyMDFEJXUyNTJDJXUyMDFEJXUyNTBDJXUyMDFEJXVGRjJGJXUyMDc4JXUyNTc3JUQ3JXVGRjRGJXVGRjRGJXUyNTc1JXVGRjA4JXVGRjEwJXVGRjA5JXUyMDc3JXVGRjVCJXVGRjBBJXVGRjJBJXUyNTc1JXVGRjFCJXUyMjE0JXVGRjVEJXVGRjREJXVGRjVCJXVGRjEyJXVGRjRFJXUyMDFDJXUyNTc1JXUyMDFEJUQ3JXVGRjFCJXUyMDFDJXUyNTAyJXUyMDFEJUQ3JUQ3JXVGRjNEJXUyOTIy,i=MzIlMEElNUI0JTJDJTIwMiUyQyUyMDIlMkMlMjAyJTVE,v=8) ([with a font that monospaces the output](https://dzaima.github.io/Canvas/?u=JXUyNTEwJXUyMDFEJXUyNTJDJXUyMDFEJXUyNTBDJXUyMDFEJXVGRjJGJXUyMDc4JXUyNTc3JUQ3JXVGRjRGJXVGRjRGJXUyNTc1JXVGRjA4JXVGRjEwJXVGRjA5JXUyMDc3JXVGRjVCJXVGRjBBJXVGRjJBJXUyNTc1JXVGRjFCJXUyMjE0JXVGRjVEJXVGRjREJXVGRjVCJXVGRjEyJXVGRjRFJXUyMDFDJXUyNTc1JXUyMDFEJUQ3JXVGRjFCJXUyMDFDJXUyNTAyJXUyMDFEJUQ3JUQ3JXVGRjNEJXUyOTIycmVzdWx0LnN0eWxlLmZvbnQlM0QlMjIxMnB4JTIwRGVqYVZ1JTIwU2FucyUyME1vbm8lMjIlM0JVJXVGRjAz,i=MzIlMEElNUI0JTJDJTIwMiUyQyUyMDIlMkMlMjAyJTVE,v=8)) [Answer] # [Emacs Lisp](https://www.gnu.org/software/emacs/), 303 bytes ``` (defun f(a)(princ'โ”Œ)(dotimes(i(1-(car a)))(princ'โ”ฌ))(princ'โ”)(let((m 1))(while(cadr a)(let((q(caadr a))(w (cadadr a)))(princ"\n")(dotimes(i(1+(car a)))(cond((if w(= 0(mod i(* m q w))))(princ'โ”‚))((= 0(mod i (* m q)))(princ'โ•ต))(t(princ" "))))(setq m(* m q(if w w 1)))(setcdr a`(,(cddadr a))))))) ``` Use this function as `(f '(30 (5 2)))`. Better readable version: ``` (defun f (a) (princ 'โ”Œ) (dotimes (i (1- (car a))) (princ 'โ”ฌ)) (princ 'โ”) (let ((m 1)) (while (cadr a) (let ((q (caadr a)) (w (cadadr a))) (princ "\n") (dotimes (i (1+ (car a))) (cond ((if w (= 0 (mod i (* m q w)))) (princ 'โ”‚)) ((= 0 (mod i (* m q))) (princ 'โ•ต)) (t (princ " ")))) (setq m (* m q (if w w 1))) (setcdr a `(,(cddadr a))))))) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~42~~ 41 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` โ€˜Rmร—\}แนฌโ‚ฌ+2/ โฝ!แนฃ;โ€œยฝยฅรทIโ€˜ร„แปŒแน™-;โถ แธถยฌ;.แธค~W;รฑแป‹ยขY ``` A full program. **[Try it online!](https://tio.run/##AWEAnv9qZWxsef//4oCYUm1QxqR94bms4oKsKzIvCuKBvSHhuaM74oCcwr3CpcO3SeKAmMOE4buM4bmZLTvigbYK4bi2wqw7LuG4pH5XO8Ox4buLwqJZ////MzL/WzQsMiwyLDJd "Jelly โ€“ Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8//9Rw4yg3MPTY2of7lzzqGmNtpE@16PGvYoPdy62ftQw59DeQ0sPb/cEKjrc8nB3z8OdM3WtHzVu43q4Y9uhNdZ6D3csqQu3Njza8HB396FFkf@PTnq4c4bO4eX6kZpZjxr3Hdp2aNv//9HRxjoK0bGxQMISiI3BLGMDIGGqo2AE4RkBCRMgD4LAYiYWEBXGMAEjoIJoc6AAmGdoDtIHVm8IEQApAQoYAi0xBNFAAaAaqAlgVbEA "Jelly โ€“ Try It Online") Note: this code has been altered from a full program -- `รฑ` (next link as a dyad) has been replaced with `1ล€` (link at index 1 as a dyad) to allow it to be called multiple times by the footer. ### How? ``` โ€˜Rmร—\}แนฌโ‚ฌ+2/ - Link 1, lower interval tick types: length; intervals e.g. 7; [3,2] โ€˜ - increment length 8 R - range [1,2,3,4,5,6,7,8] } - use right argument for this monad as if it were a dyad: ร—\ - cumulative reduce by multiplication [3,6] m - modulo slice (vectorises) [[1,4,7],[1,7]] แนฌโ‚ฌ - untruth โ‚ฌach [[1,0,0,1,0,0,1],[1,0,0,0,0,0,1]] +2/ - pairwise reduce with addition [[2,0,0,1,0,0,2]] - -- yielding a list of types for each row of characters below the first - where 0 is a space, 1 is a short tick-mark and 2 is a long tick-mark โฝ!แนฃ;โ€œยฝยฅรทIโ€˜ร„แปŒแน™-;โถ - Link 2, make character set: no arguments โฝ!แนฃ - literal 9474 โ€œยฝยฅรทIโ€˜ - list of code-page indices = [10,4,28,73] ; - concatenate [9474,10,4,28,73] ร„ - cumulative addition [9474,9484,9488,9516,9589] แปŒ - to characters "โ”‚โ”Œโ”โ”ฌโ•ต" แน™- - rotate left by -1 "โ•ตโ”‚โ”Œโ”โ”ฌ" โถ - literal space character ' ' ; - concatenate "โ•ตโ”‚โ”Œโ”โ”ฌ " แธถยฌ;.แธค~W;รฑแป‹ยขY - Main link: length, L; intervals, I แธถ - lowered range [ 0, 1, 2, ..., L-1] ยฌ - logical Not [ 1, 0, 0, ..., 0] . - literal 0.5 ; - concatenate [ 1, 0, 0, ..., 0, 0.5] แธค - double [ 2, 0, 0, ..., 0, 1] ~ - bitwise NOT [-3,-1,-1, ...,-1,-2] W - wrap that in a list [[-3,-1,-1, ...,-1,-2]] รฑ - call next Link (1) as a dyad (f(L, I)) ; - (left) concatenated with (right) ยข - call last Link (2) as a nilad (f()) แป‹ - (left) index into (right) (1-indexed and modular) Y - join with newline characters - implicit print ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 126 bytes ``` ->l,i{y=1;[?โ”Œ+?โ”ฌ*~-l+?โ”]+i.each_slice(2).map{|j,k|x=y*j;y=k&&x*k;(0..l).map{|z|'โ”‚โ•ต '[(z%x<=>0)+(k ?z%y<=>0:1)]}*''}} ``` [Try it online!](https://tio.run/##NY9LbsMgFEXnWQUT/4llIFXSuiQLQahKrET1J1JUN5KxcQcdd9BBuotOuyFvxH1gR0Jwz@HqId6uBzWe@LjcVjjvFCep2A23rwi23/BjWZnwLaM8Pu6z15e6yrOjT4P4vL90usClbrgKi1Tx0nWbsEz9JI6r@brV3nD7HH7@kCf81mme@TYJIr9Eu9ZRBp5IIPvQ8/p@FIJhJKTEC/EIgdnEEogPGNGJKNAKaFrWrTZTg90FhYJYg7BE1maW7ZNJAFMQBB4h5gQBnXmCbS2k/Wqna5zry/W9RicBUaYm9@M/ "Ruby โ€“ Try It Online") Looks rather verbose with all that `each_slice` stuff, but will do for now, unless I manage to find a golfier approach. Takes input as `l` for length and `i` for intervals, returns an array of strings. [Answer] # [R](https://www.r-project.org/), ~~175~~ 170 bytes ``` function(l,i,`&`=rep)rbind(c('โ”Œ','โ”ฌ'&l-1,'โ”'),if(i)sapply(rowSums(!outer(0:l,cumprod(i),`%%`)),function(j,x=j%/%2,y=j%%2)c('โ”‚'&x,'โ•ต'&y,' '&(1+sum(1|i))/2-x-y))) ``` [Try it online!](https://tio.run/##bZDBTsMwDIbvPEU4tLGFy5Z009hEn4IjIHXrWilTm0ZpK1qJE2cOHOAtuPJCvMhwd5iQ1kPi@P/s31b8sRD30bHobNaa2kJJhtIwTXzu0O@M3UMG8vfzXRLf3zIsIzW@PiSSKcBgs3WuHMDXLw9d1cB13bW5h/mmpKyrnK/3XENpEKSIdB5yoD45BLNA08Ax0Hia8SbDnr2/fmQ4kBQyBHXTdBWoV4M401EfDYh4dD5v2@HWeWNbXl2cXSsURe3BCGOF2lheiSXMti1Uj4aeST5ZSU3uEinx6r8LFBDTHC/ENcWXYjynDJakcQJpRgvSk3Bxd@qLJ6FeMFyN4y6QWjHiLlJTkJmOSag1nzEqEisSSxKcaM7HD/sD "R โ€“ Try It Online") Takes empty intervals as `0`, returns a matrix of characters. TIO link displays the output pretty-printed. [Answer] # [Haskell](https://www.haskell.org/), ~~167~~ ~~164~~ 149 bytes ``` n%l=unlines$("โ”Œ"++([2..n]>>"โ”ฌ")++"โ”"):[do p<-[0..n];let(j#a)b|1>p`rem`product(take j l)=a|1>0=b in(i-1)#(i#"โ”‚"$"โ•ต")$" "|i<-[1,3..length l]] ``` [Try it online!](https://tio.run/##ZY4xTsMwFIZ3TvHkpJKtpFFsB5UCyQnYGKNIdalF3bpulDpbJ2YGBrgFKxfqRcJz6ZIi2Xry9@n9v9fqsNXWDoOb2LJ31jh9iCk5fb6TJKG1yDLXVBW@vwlLEpwfhN3Xqz20j9M6D/bBak83kWLLI6/aRad3i7bbr/oXT73aatiAZaVCl5dLMI6aKWcRNRFmvZGYnL5@CIsJkKPBRJ7KLLPavfo12KYZdso4KAH7bqDt/bPvnhzEABImUDdjNg9MjqHMA7xNQVxxEXiB/O@MbXF32ZL/lCiCmqEacz47t5/T@NXHeFACHZ/jDZOngBGXgrAw/AI "Haskell โ€“ Try It Online") Slightly golfed different approach by [ฮŸurous](https://codegolf.stackexchange.com/users/18730/%ce%9furous). --- ``` n%l|let c=take(n+1).cycle;m&(x:y:r)=c('โ”‚':init([1..y]>>(m*x)!" "++"โ•ต"))++'\n':(m*x*y)&r;m&[x]=c$'โ•ต':(m*x)!" ";m&e=[]='โ”Œ':n!"โ”ฌ"++"โ”\n"++1&l n!s=[2..n]>>s ``` [Try it online!](https://tio.run/##ZY4xboMwFIb3nOKBEozjyKqBKg2Vc4JuHQkDcpGKYpwIqARSp84dOtBbdO2FuAh9JllIJVt@@j69//drVh9zrcfRrPS7zhtQssmOuW@YoFx1SuePpee3cRdXVCqfDP0HiQtTNH4iOO/S/d4v1y11XHAZc4fvX5dSxsjBkNiKdUe9ChOSNpVqSdBf@LSAPJdJKjH0k8TGcYf@Z0rpvw4GB@HphXFqmQScG2yqxzIrDEh4OcECzm/Nc1M9GVgChLCCJJ2znWXhHIZ3Ft5vILjhgeUR8suZ2@jhuhX@U0Fk1RbVnIvt1D6liZuPCasCdGKH175iAxhxLbAL4x8 "Haskell โ€“ Try It Online") There are still some redundancies which look like they could be exploited, but so far they withstood all further golfing attempts. --- [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 152 bytes ``` param($t,$i)"โ”Œ$('โ”ฌ'*--$t)โ”" $i|%{$s=++$s*$_-1;$p=".(.{$s}|.*$)" if($r){$r-replace$p,'โ”‚$1';rv r}else{$r=' '*($t+2)-replace$p,'โ•ต$1'}} if($r){$r} ``` [Try it online!](https://tio.run/##1VXdTsIwFL7fUzTNwa2wEbdhUMkSnsBXMIglLg6d3UCTsRuuueAC38JbX4gXwdNuyPidCWhi06zdOadfv/P1L3x@5SJ64EGwgB7xSLIIO6LTNyA2wWd0PpuAoc9nH3rVsiBm89mUauCPKglEXq0GURVuLbsFoUfrRh2N6aheBUY1v2eAYAkIS/Aw6HQ5hCbijMHWW2JIRMqDiKPb04lexdlqDluLfP/EyDRd4aSLVNPahqaZhmuStsFMQggiTpCcqlOdSeeVdLrSW3Ru16luaqRQ5JSErH0yQPdcIl6YxCkHPbJucsp4zcayVaSwOfyXU3Yk5QZSzqrS6nep709gI5GM6w/75XDFkstQtCwVaVzmi@gu5fgDNU6l3uYW2Ln2pca94FuqlakqRylVnYZUtYmqnvhoHDoIBUarTpahImU31Q2gdr59xFIfXo3sjtjRK5N5s81JS84Okrbx/rJlixZMJN@xeSZZIocO2U6y/zoeZZISMTIiFZKogRD73cebQf@OC5OA/xRzMewEEfb5W8i7Mb/Hhwxus1jBo0EQo@EM37fCyMJAFUjBoHkwtfgL/cai7HrfjLQ4hZYuvgA "PowerShell โ€“ Try It Online") Unrolled: ``` param($ticks,$intervals) "โ”Œ$('โ”ฌ'*--$ticks)โ”" # implicit output $intervals|%{ $step=++$step*$_-1 $pattern=".(.{$step}|.*$)" if($row){ $row-replace$pattern,'โ”‚$1' # implicit output Remove-Variable row }else{ $row=' '*($ticks+2)-replace$pattern,'โ•ต$1' } } if($row){$row} # implicit output ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 204 bytes ``` a=>b=>{Write("โ”Œ"+"โ”\n".PadLeft(++a,'โ”ฌ'));for(int i=1;;i++,WriteLine())for(int j=0;j<a;){var m=b.Select((c,d)=>b.Take(d+1).Aggregate((e,f)=>e*f)).Count(c=>j++%c<1);Write(m<1|i>m?" ":m<2?"โ•ต":"|");}} ``` [Try it online!](https://tio.run/##NY@9TsMwHMR3niKyhOp/HSwCU@uPqkJiyoBEJYbC4Dp25EAcKXFhSPMGDAzlLVh5obxIcEEsJ51OP92d7i5056bbvdfc@ZCudXCN57nrwslLKa2YlJA7IfuH1gWD0Xh8RyTqx6NH9E4VubEBE6LS2Xj8mgEw27Q4sokTGWOOkPQXzJ03GOA/rMQlq7hi0L@qNqnFjt6bF6MDxjotIBbSjXo2uCAZ0HVZtqZUsRyb1MbQzC0AvWn2PmAtZEXIueYZsL@FNc8OTtYrlKBlza9WaPz8Rkt0QMCGYWJnFi8Ae/O2feqvB7ppTmfjMjb9AA "C# (Visual C# Interactive Compiler) โ€“ Try It Online") Outputs, but gets stuck in an infinite loop. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~221~~ ~~201~~ ~~195~~ 162 bytes ``` import StdEnv $n l=[["โ”Œ":repeatn(n-1)"โ”ฌ"]++["โ”"]:[[if(?(i-1))if(?i&&l%(i,i)>[])"โ”‚""โ•ต"" "\\p<-[0..n],let?j=1>p rem(prod(l%(0,j))) ]\\i<-[1,3..length l]]] ``` [Try it online!](https://tio.run/##NY@xTgMxEET7fMXKCpGtOKccKZAiLmmgQKJACp3PheX4gk/2@uQzCFpqCgr4C1p@KB/C4STQ7c68kWa0MwoHH7aPzoBXFgfruxATbNL2Gp9GYwRXCUH2H29kGU1nVEKKs5Jl5YvI6fRgvRO5FMI2dE1tttjhspOJO6OWW7YS8kC/ErL//CYESF13lzMxLwqU3Jm0bqty1UE0nnYxbGmOzXnLGBvJuraZLPmiKJzBXXoAJ6Ucmhg83JvnBH9ltVN9f1RoGyxy0AG1SoyDxT4p1OaEb1K0uBttksqhCo5w7oMEQh7f/ceAjqG8ALHg57yUbPjRjVO7fpjd3A5XL6i81afnzqnUhOh/AQ "Clean โ€“ Try It Online") Returns a list of lists of UTF-8 characters (as strings, since Clean has no innate UTF-8 support). Works by generating the first line, then taking the product of prefixes of the list provided in groups of two, and checks which mark to draw based on whether the product divides the current character position. Ungolfed: ``` $ n l = [ ["โ”Œ": repeatn (n - 1) "โ”ฌ"] ++ ["โ”"]: [ [ if(? (i - 1)) if(? i && l%(i, i) > []) "โ”‚" "โ•ต" " " \\ p <- [0..n] , let ? j = 1 > p rem (prod (l%(0, j))) ] \\ i <- [1, 3.. length l] ] ] ``` ]
[Question] [ While doing some research for a different challenge I'm formulating, I came across a [Cayley graph](https://en.wikipedia.org/wiki/Cayley_graph), specifically [this one](https://upload.wikimedia.org/wikipedia/commons/d/d2/Cayley_graph_of_F2.svg). Since I'm [one of the top](https://codegolf.stackexchange.com/tags/ascii-art/topusers) [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge writers, of course I had to make an ASCII art challenge for this. Your challenge is to produce this ASCII art depiction of a Cayley graph of the free group on two generators as follows: ``` + +++ + | + ++-+-++ + | + + | + +++ | +++ + | | | + ++-+----+----+-++ + | | | + +++ | +++ + | + + | + +++ | +++ + | + | + | + ++-+-++ | ++-+-++ + | + | + | + + | | | + +++ | | | +++ + | | | | | + ++-+----+-----------+-----------+----+-++ + | | | | | + +++ | | | +++ + | | | + + | + | + | + ++-+-++ | ++-+-++ + | + | + | + + +++ | +++ + +++ + | + +++ + | + | + | + ++-+-++ | ++-+-++ + | + | + | + + | + | + | + +++ | +++ | +++ | +++ + | | | + | + | | | + ++-+----+----+-++ | ++-+----+----+-++ + | | | + | + | | | + +++ | +++ | +++ | +++ + | + | + | + + | | | + +++ | | | +++ + | + | | | + | + ++-+-++ | | | ++-+-++ + | + | | | + | + + | | | | | + +++ | | | | | +++ + | | | | | | | + ++-+----+-----------+--------------------------+--------------------------+-----------+----+-++ + | | | | | | | + +++ | | | | | +++ + | | | | | + + | + | | | + | + ++-+-++ | | | ++-+-++ + | + | | | + | + +++ | | | +++ + | | | + + | + | + | + +++ | +++ | +++ | +++ + | | | + | + | | | + ++-+----+----+-++ | ++-+----+----+-++ + | | | + | + | | | + +++ | +++ | +++ | +++ + | + | + | + + | + | + | + ++-+-++ | ++-+-++ + | + | + | + +++ + | + +++ + +++ | +++ + + | + | + | + ++-+-++ | ++-+-++ + | + | + | + + | | | + +++ | | | +++ + | | | | | + ++-+----+-----------+-----------+----+-++ + | | | | | + +++ | | | +++ + | | | + + | + | + | + ++-+-++ | ++-+-++ + | + | + | + +++ | +++ + | + + | + +++ | +++ + | | | + ++-+----+----+-++ + | | | + +++ | +++ + | + + | + ++-+-++ + | + +++ + ``` ## Input No input, unless your language explicitly requires input to run. ## Output The ASCII art representation shown above. ## MD5 Hashes Since this is a pretty large output, to check your work here are some MD5 hashes of example forms of output (all are UTF-8 without BOM): * Square space padding, `CR/LF` linefeeds, and trailing newline -- `954B93871DAAE7A9C05CCDF79B00BF3C` -- this is the representation used above. * Square space padding, `CR/LF` linefeeds, no trailing newline -- `28405EF91DA305C406BD03F9275A175C` * Square space padding, `LF` linefeeds, and trailing newline -- `8CA65FB455DA7EE5A4C10F25CBD49D7E` * Square space padding, `LF` linefeeds, no trailing newline -- `FDB1547D68023281BB60DBEC82C8D281` * No trailing spaces, `CR/LF` linefeeds, and trailing newline -- `77FDE8CE5D7BD1BDD47610BA23264A19` * No trailing spaces, `CR/LF` linefeeds, no trailing newline -- `EAD390C3EFD37F0FCACE55A84B793AB5` * No trailing spaces, `LF` linefeeds, and trailing newline -- `1F6CAB740F87881EB2E65BED65D08C36` * No trailing spaces, `LF` linefeeds, no trailing newline -- `7D41CE1E637619FEA9515D090BFA2E9C` * If there is an additional MD5 you would like for comparison, please let me know and I'll create it and update the challenge. ### Rules * Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](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 (ES6), ~~204~~ ~~195~~ ~~188~~ 180 bytes ``` f= _=>[...Array(9119)].map((_,i)=>~i%96?g(48+~(i/96),47-i%96,5):` `,g=(x,y,z,n=(1<<z)-z)=>x|y?(x=x<0?-x:x)+(y=y<0?-y:y)<n?` |-+`[2*!x+!y]:z--?x>y?g(x-n,y,z):g(x,y-n,z):` `:`+`).join`` ;document.write(`<pre>`+f()) ``` Square space padding, LF linefeeds, ~~and~~ no trailing newline, although I haven't checked the MD5. ``` f= m=>[...Array((w=(4<<m)-m*-~m-2)*~-w)].map((_,i)=>~i%w?g(w/2+~(i/w),w/2-i%w-1,m):` `,g=(x,y,z,n=(1<<z)-z)=>x|y?(x=x<0?-x:x)+(y=y<0?-y:y)<n?` |-+`[2*!x+!y]:z--?x>y?g(x-n,y,z):g(x,y-n,z):` `:`+`).join`` ``` ``` <input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>+ ``` Parametrised version for ~~222~~ ~~216~~ ~~207~~ 199 bytes. Explanation: The output size is 9119 ASCII characters, including 46 newlines. (For the parametrised version, the output size is calculated including the trailing newline.) Each character is individually determined, firstly by checking whether a newline is due, otherwise by calling a function on the coordinates relative to the origin in the middle of the final diagram. The function recursively checks the point against the nearest crosses of each size to the point, and returns the appropriate character depending on whether the point is discovered to lie on the centre or axis of a cross. [Answer] # [Rรถda](https://github.com/fergusq/roda), ~~284~~ ~~280~~ ~~238~~ 234 bytes ``` {a=[1,-1]t=[]seq 1,95|t+=[" "]*95,_ f={|x,y,i,d|{s=[27,12,5,2,1][i]i++ a|{|j|{seq y,y+s*j|t[_][x]="|"f x,y+s*j,i,2-j}if[d!=2+j]}_ a|{|j|{seq x,x+s*j|t[y][_]="-"f x+s*j,y,i,3-j}if[d!=3+j]}_}if[i<5] t[y][x]="+"}f 47,47,0,0 t|print _&""} ``` [Try it online!](https://tio.run/nexus/roda#Tc1LCoMwEAbgvadIs@jCjGBiRYTmJGEIgg1EqLQ1i0iSs9toSynMZh7fP/fBzmELg1QcKo5OKlxuT8Khb6NjUlFCsexb0IWRIXpYwcIYwyKV6IALaEEAR2XRMlYMMcQpL3PACitbyik6pVF5lDRSQ/xnmCNENSVr1HiSgk2Y9D/14L90xawlrXZ6wP1786PNQffGXlssjvv9FaPJkEsHuWqoCxcfLzs7os@Upi1tbw "Rรถda โ€“ TIO Nexus") This is an anonymous function. I used newlines instead of semicolons so it is very nicely formatted! The recursive function `f` creates the graph in a two-dimensional array `t`, which is then printed at the last line. I didn't find a way to calculate `27,12,5,2,1` in few bytes, so they are hard-coded. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ 43 bytes ``` ๏ผฆยณยฒโดยซ๏ผฐ++โ†ท๏ผก๏ผฅโ€ฆยนยฆโตโˆงยฌ๏นชฮน๏ผธยณฮบโป๏ผธยฒโบฮบยนโบฮบยฒฮต๏ผฆโบฮตโฎŒฮตยฟฮบยซ+ฮบโ†ถ ``` [Try it online!](https://tio.run/nexus/charcoal#NY47DoMwEAVrc4oV1VoxBZBUqehDhLgBEguxjGyEDSkizu6YXzk7T9rxnZkA8@zO4Rexch6cHCepHca3W8yfEavkYlwt@4/DDQtrZa@xbEasG90TpgIeXEChW3wbh6Vp58GgFFCZL02YC1Cch0Ep9WzxOGbBDoGUgHRzF2R8n9L2aO8q2hZJQE0LTZaQgo4Ykx2g2nsZq87YvfVCdcKW/qLuKGdrtHrvk8UndvgD "Charcoal โ€“ TIO Nexus") Link is to verbose version of code. I originally tried various reflections and rotations but they either didn't do what I want or in some cases were buggy. I then tried a nested loop approach but I've now switched to this iterative method which works by drawing a number of lines between each inner cross depending on how many powers of 3 the step number is divisible by. It can even be readily modified to accept a size parameter at a cost of only 4 bytes: ``` ๏ผฎฮฒ๏ผฆร—โด๏ผธยณฮฒยซ๏ผฐ++โ†ท๏ผก๏ผฅโ€ฆยทยนฮฒโˆงยฌ๏นชฮน๏ผธยณฮบโป๏ผธยฒโบฮบยนโบฮบยฒฮต๏ผฆโบฮตโฎŒฮตยฟฮบยซ+ฮบโ†ถ ``` Edit: I've since worked out how to use `RotateShutterOverlap` to achieve this task, but annoyingly it takes me 44 bytes: ``` ๏ผกโฐฮท๏ผฆโถยซ๏ผกฮทฮณ๏ผกโปโบ๏ผธยฒฮนฮทฮนฮท๏ผชฮทโฐ๏ผฐ-ฮณ+ยฟฮณโŸฒ๏ผณ๏ผฏยฒโถโปร—ยฒฮณยนยปโ€–โŸฒ๏ผณ๏ผฏโนโต ``` If `RotateShutterOverlap` accepted a variable rotations integer, that would reduce it to 40 bytes: ``` ๏ผกโฐฮท๏ผฆโถยซ๏ผกโˆจฮทยนฮณ๏ผกโปโบ๏ผธยฒฮนฮทฮนฮท๏ผชฮทโฐ๏ผฐ+ฮณ+โŸฒ๏ผณ๏ผฏโއโ€นฮนโต๏ผฌฮฒยฒโดโถฮณ ``` As it is, using a rotations list parameter takes 45 bytes: ``` ๏ผกโฐฮท๏ผฆโถยซ๏ผกโˆจฮทยนฮณ๏ผกโปโบ๏ผธยฒฮนฮทฮนฮท๏ผชฮทโฐ๏ผฐ+ฮณ+โŸฒ๏ผณ๏ผฏโŸฆโถร—ยฒโบยนโผโตฮนโŸงโปร—ยฒฮณยน ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 620 bytes ``` โ€ข1dOล“หœโ€˜Avโ€“Qsโ€ ฦ’Fรฃ&รคuรŒรŠยนร2bรฝรกdร™Iโ€™ยดร‹ล“ยผ)Yยป+โ„ขรŸโ€บ[Vgโ€œร’ยขJรน1no<V<*ร‰t*-ยข&รข-รŸBร†ร—090`11-รธsยตโ€“ยถ1Vร›==รผ:ยผรทร˜รปรZโ€žรฆยน=#รนรžVยซยกfรค&รŽห†'รซห†ร=รค^โ€ฐยค?รŠรงรน!ร˜รจร˜r-3รฎร›+รชรฒโ€šรปยขยฝยฐBรฉGยฆUโ€รœ1ลพห†r6Sโ€นโ€œลฝKRKยฐAยนยชยฟรข9]}ร—uยฌ]ลพโ€žรŽรฏโ€บVยฆร‚ยถ4รƒรฏยขvยฃร—รฉยดรœ2ร„ลพiqรด>ยง17F*รŽaรฑnรญร†4]s8mรโ€บHSร771รญยดโ€ฐd3ยดรž|ร€]Uร {รพรฑรฝqรธโ€™eโ€žXรฟF4โ€“:Yl&uqลพรร’รฟยพu9ยคjรณHPโ€ฐรงรชoร’Nล X-ยฐxpร’รฟ*ejรD0ร‹+GnรŠ-/ยง3รœJร™ห†ฦ’รŒ=ล’ร’OXโ€ฐ|O%wรฆ[nโ€นรฃ4)รดF+~ยดร–{aร„$(รžรญยผโ€รทuโ€“qรฟBรฒfร‚รญรœรฌTรณโ€“xรwรปยพ])<ยงOยซ\โ€šeยฐโ€กยพโ€นKโ€ฆZDPรด;ยต!รƒร‚ยฒ&ร”ยผยจ1gล โ€”ลธยฆยฉzWยขยพร—4Kยฑร”ร„_รฌรปร„โ€š3ยถร‘>โ€šbรนnยฑล“ร—)ร™CรขRรถรจยฃยถโ€ห†1รŸร‘รยฎร–ยฑ[ZรฉRรฏyร“xร“EยจcWหœ{รƒโ€™รนoEโ€บยฅรšvAยจโ€นรชร†รฝร‘YยฝRรŽ5ยดโ€˜รŠโ„ขuรฅร„r"รฃYรฐรทI!0ยค)รฅโ€กรซลพโ€>รบรจWรฒ}รฉโ‚ฌ@.ร˜รฑรˆQโ‚ฌรฑ{รโ€žโ€˜รœโ€™โ€ฐ~ร‡รฑ=โ€ฆ|โ€œรšฦ’ร„ยฌcรณร‡kรพร›ร‡โ€“ลก;{ยกยฆยฝร•rรŽรฉโ€“ร Tzโ‚ฌKรฌ2ร ^|ยขรจห†รŽxลพโ€œรฅ$ล“2รดยปEidล“รพFrSSยฅรรœโ€”Xยกรก~รฎรพQหœNรœGรฑยฅQ)aรจโ€ข4B"1230"" +-|"โ€ก48รดรปโ‚ฌรปยป ``` [Try it online!](https://tio.run/nexus/05ab1e#FZN9UxpnFMW/SqUpLTK0LNAaE7HVRkzCTIya4FtJa6LJJG2xYjE2EGdrGGxNxBFsEF0UlhdBSQQlKOHFmXtm8w/fYr@IvfvfzjN773PO75znUhVlYWZIibYlVdzuW1TF6PCCKiY/RRxI65Hx4Q3WqIaE5SGaSM0gfksV41TBayVKDcME1Y1qUMa@Kn6ccj1RRQkRkm@jJnjmelw9nfj3z04TyXrIJuz3I4SYudv8iyCYcL5AH/gyqgou7NrtaFyjBs6wjTrWJ1VxDzmq2T9HDXsuOqLUY2T0CLdDX@KoHULCjswDVSxR5nus4QC1Dh7MY9trsuI9do04xIkq7qBOMjWp1I/CIOXuq2ICkqC02iHvd6OqWGO1StM54qRSH9XokC4gd7tfIuajoltpaRrCOGZjLsphhao2vMIxyYuURgwFRiBZEFRaT@dR6aUDocvRifA0yh68Q8jmXrj6OzZ4@OYoNrq6BLyjCguesfLcXgCi@z6SfrRQRnMe54x0lu8bx4XDxlCuTfym980rLawjggtq@bop8wynN@/yBnZ7OIfIHSU5bqLS0h/aH52zz7Bxw4zXxkEP1kzf0IEV0m3E26FPEbyxKxFEhsZ5NjD0xXPkpjzsHWmbARWHcZn1vPVPI3jlK@yxyIYG6czHIuZx0Y@Tx1hhPxKK93DKh0tIPGeqLbehhw6G6OgnpjxLJVVMEQOrOVUxN3njLirX6UMH41qhEz22qEF54YmSVMUt5ZxyVHgxxrm0ELM5qYwtBH9GkWMP8i4rVbHZyx8PUfNQWYkiZkD8R8gjqCJPaaqyvnZIwD42sU7v8ZbKU5MojOD4L7C66ADlH421JT9eMVPU5gY4AspiZ7GP8prtQ@5gE5sT1BxB@Fstk22scYN9yCLo1SE9gRLObnWYKWNAln3hSKtCohcfkR/DyUsU1JXiD19z38r4Z5i/Ufbjbw5P28RvKM6cl7GKsp1ZBLQHscMhBKn4CKdY/ZUj38Uqk1RS1/2UYhpN/OflohX4DMl7L3ijE0ULkg8CJCPPZQ8vaQokZK8oUQsqVB94OsNgWg7v6ChbS2i3bo1TCqllLn9ruC3dgTSIMmWHDdNg17KtXydYrGad7jOjKaBjU7arqKCuia9T/fLyfw "05AB1E โ€“ TIO Nexus") All I did was cut the pattern into fourths, converted the symbols to base-4, compressed 1/4 of the pattern into base-214 and then flipped it over the lines of symmetry. I'm working on something smarter using the actual algorithm, but until I finish that this is what'll be here for me. [Answer] # Python 3, 264 bytes ``` def F(g,p,d,k): for c in'-|'[d.real!=0]*(2**k-k-1):g[p]=c;p+=d P(g,p,k-1) def P(g,p,k): if'+'==g.setdefault(p,'+')and k: for d in[1,1j,-1,-1j]:F(g,p+d,d,k) g={} P(g,0j,5) print('\n'.join(''.join(g.get(r+c*1j,' ')for c in range(-47,48))for r in range(-47,48))) ``` Uses a pair of mutually recursive functions. F draws the lines and P inserts the '+'s. Can be golfed more, but out of time for now. [Answer] # C, 236 bytes ``` char t[95][95],i=95;f(x,y,s,n,m){if(t[y][x]<33){m=~s+(1<<s);for(n=~m;n++<m;)t[y][x+n]='-',t[y+n][x]=n==0?'+':'|';if(s--)f(x+n,y,s),f(x-n,y,s),f(x,y+n,s),f(x,y-n,s);}}main(){memset(t,32,9025);f(47,47,5);while(i--)printf("%.95s\n",t[i]);} ``` Just building the character table recursively before displaying it. [Try it online!](https://tio.run/nexus/c-gcc#RY5tCsIwDIavIgNpSlOZziGzKx5k9ofIhgUbZS2o6Lz6zBAUEngCeT/G4@nQz1JTlW5a9LYqTQd3fGBEwiCfvoPUPFxzd3VRyGew76hgWddRmu7SA9l3MKRUHYz8/ilyVmiBfDGyzpK1@U4osRUvYdgvai05Q9GUIpFR/xFZ9UM9oRmGcPAEHN6G2CZIWKywylclV4D1BnkYbyd/bsGz97X3lDrI5ouqjHvKuIp3bDOOHw "C (gcc) โ€“ TIO Nexus") Thanks @Neil for making me realize that the length of the branches follow an actual rule. [Answer] # Deadfish~, 11547 bytes ``` {iii}ii{cccc}ccccccc{i}ic{d}d{cccc}ccccccc{dd}ddc{ii}ii{cccc}cccccc{i}iccc{d}d{cccc}cccccc{dd}ddc{ii}ii{cccc}ccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}ccccc{dd}ddc{ii}ii{cccc}cccc{i}icciicddciicddcc{d}d{cccc}cccc{dd}ddc{ii}ii{cccc}ccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}ccccc{dd}ddc{ii}ii{cccc}cc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cccc}cc{dd}ddc{ii}ii{cccc}c{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cccc}c{dd}ddc{ii}ii{cccc}{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}{dd}ddc{ii}ii{ccc}ccccccccc{i}icciicddciiccccddciiccccddciicddcc{d}d{ccc}ccccccccc{dd}ddc{ii}ii{cccc}{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}{dd}ddc{ii}ii{cccc}c{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cccc}c{dd}ddc{ii}ii{cccc}cc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cccc}cc{dd}ddc{ii}ii{ccc}ccccc{i}ic{d}d{c}c{{i}d}iic{{d}i}dd{c}c{i}ic{d}d{ccc}ccccc{dd}ddc{ii}ii{ccc}cccc{i}iccc{d}d{c}{{i}d}iic{{d}i}dd{c}{i}iccc{d}d{ccc}cccc{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}cc{i}icciicddciicddcc{d}dcccccccc{{i}d}iic{{d}i}ddcccccccc{i}icciicddciicddcc{d}d{ccc}cc{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}{i}ic{d}dcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{i}ic{d}d{ccc}{dd}ddc{ii}ii{cc}ccccccccc{i}iccc{d}dccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}ccccccccc{dd}ddc{ii}ii{cc}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccccccc{dd}ddc{ii}ii{cc}ccccccc{i}icciicddciiccccddcii{c}cddcii{c}cddciiccccddciicddcc{d}d{cc}ccccccc{dd}ddc{ii}ii{cc}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccccccc{dd}ddc{ii}ii{cc}ccccccccc{i}iccc{d}dccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}ccccccccc{dd}ddc{ii}ii{ccc}{i}ic{d}dcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{i}ic{d}d{ccc}{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}cc{i}icciicddciicddcc{d}dcccccccc{{i}d}iic{{d}i}ddcccccccc{i}icciicddciicddcc{d}d{ccc}cc{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{cc}{i}ic{d}d{c}ccc{i}iccc{d}d{c}{{i}d}iic{{d}i}dd{c}{i}iccc{d}d{c}ccc{i}ic{d}d{cc}{dd}ddc{ii}ii{c}ccccccccc{i}iccc{d}d{c}ccc{i}ic{d}d{c}c{{i}d}iic{{d}i}dd{c}c{i}ic{d}d{c}ccc{i}iccc{d}d{c}ccccccccc{dd}ddc{ii}ii{c}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccc{{i}d}iic{{d}i}dd{cc}cccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}cccccccc{dd}ddc{ii}ii{c}ccccccc{i}icciicddciicddcc{d}d{cc}ccc{{i}d}iic{{d}i}dd{cc}ccc{i}icciicddciicddcc{d}d{c}ccccccc{dd}ddc{ii}ii{c}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccc{{i}d}iic{{d}i}dd{cc}cccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}cccccccc{dd}ddc{ii}ii{c}ccccc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cc}c{{i}d}iic{{d}i}dd{cc}c{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{c}ccccc{dd}ddc{ii}ii{c}cccc{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}{{i}d}iic{{d}i}dd{cc}{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{c}cccc{dd}ddc{ii}ii{c}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccccccccc{{i}d}iic{{d}i}dd{c}ccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccc{dd}ddc{ii}ii{c}cc{i}icciicddciiccccddciiccccddciicddcc{d}d{c}cccccccc{{i}d}iic{{d}i}dd{c}cccccccc{i}icciicddciiccccddciiccccddciicddcc{d}d{c}cc{dd}ddc{ii}ii{c}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccccccccc{{i}d}iic{{d}i}dd{c}ccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccc{dd}ddc{ii}ii{c}cccc{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}{{i}d}iic{{d}i}dd{cc}{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{c}cccc{dd}ddc{ii}ii{c}ccccc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cc}c{{i}d}iic{{d}i}dd{cc}c{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{c}ccccc{dd}ddc{ii}iicccccccc{i}ic{d}d{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{i}ic{d}dcccccccc{dd}ddc{ii}iiccccccc{i}iccc{d}d{c}{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}{i}iccc{d}dccccccc{dd}ddc{ii}iicccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dcccccc{dd}ddc{ii}iiccccc{i}icciicddciicddcc{d}dcccccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}ddcccccccc{i}icciicddciicddcc{d}dccccc{dd}ddc{ii}iicccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dcccccc{dd}ddc{ii}iiccc{i}ic{d}dcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{i}ic{d}dccc{dd}ddc{ii}iicc{i}iccc{d}dccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddccc{i}iccc{d}dcc{dd}ddc{ii}iic{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}dc{dd}ddc{iii}iiicciicddciiccccddcii{c}cddcii{cc}ccccccddcii{cc}ccccccddcii{c}cddciiccccddciicddcc{ddd}dddc{ii}iic{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}dc{dd}ddc{ii}iicc{i}iccc{d}dccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddccc{i}iccc{d}dcc{dd}ddc{ii}iiccc{i}ic{d}dcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{i}ic{d}dccc{dd}ddc{ii}iicccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dcccccc{dd}ddc{ii}iiccccc{i}icciicddciicddcc{d}dcccccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}ddcccccccc{i}icciicddciicddcc{d}dccccc{dd}ddc{ii}iicccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dcccccc{dd}ddc{ii}iiccccccc{i}iccc{d}d{c}{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}{i}iccc{d}dccccccc{dd}ddc{ii}iicccccccc{i}ic{d}d{c}c{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{cc}cccccc{{i}d}iic{{d}i}dd{c}c{i}ic{d}dcccccccc{dd}ddc{ii}ii{c}ccccc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cc}c{{i}d}iic{{d}i}dd{cc}c{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{c}ccccc{dd}ddc{ii}ii{c}cccc{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}{{i}d}iic{{d}i}dd{cc}{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{c}cccc{dd}ddc{ii}ii{c}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccccccccc{{i}d}iic{{d}i}dd{c}ccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccc{dd}ddc{ii}ii{c}cc{i}icciicddciiccccddciiccccddciicddcc{d}d{c}cccccccc{{i}d}iic{{d}i}dd{c}cccccccc{i}icciicddciiccccddciiccccddciicddcc{d}d{c}cc{dd}ddc{ii}ii{c}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccccccccc{{i}d}iic{{d}i}dd{c}ccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}ccc{dd}ddc{ii}ii{c}cccc{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}{{i}d}iic{{d}i}dd{cc}{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{c}cccc{dd}ddc{ii}ii{c}ccccc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cc}c{{i}d}iic{{d}i}dd{cc}c{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{c}ccccc{dd}ddc{ii}ii{c}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccc{{i}d}iic{{d}i}dd{cc}cccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}cccccccc{dd}ddc{ii}ii{c}ccccccc{i}icciicddciicddcc{d}d{cc}ccc{{i}d}iic{{d}i}dd{cc}ccc{i}icciicddciicddcc{d}d{c}ccccccc{dd}ddc{ii}ii{c}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccc{{i}d}iic{{d}i}dd{cc}cccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{c}cccccccc{dd}ddc{ii}ii{c}ccccccccc{i}iccc{d}d{c}ccc{i}ic{d}d{c}c{{i}d}iic{{d}i}dd{c}c{i}ic{d}d{c}ccc{i}iccc{d}d{c}ccccccccc{dd}ddc{ii}ii{cc}{i}ic{d}d{c}ccc{i}iccc{d}d{c}{{i}d}iic{{d}i}dd{c}{i}iccc{d}d{c}ccc{i}ic{d}d{cc}{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}cc{i}icciicddciicddcc{d}dcccccccc{{i}d}iic{{d}i}ddcccccccc{i}icciicddciicddcc{d}d{ccc}cc{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}{i}ic{d}dcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{i}ic{d}d{ccc}{dd}ddc{ii}ii{cc}ccccccccc{i}iccc{d}dccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}ccccccccc{dd}ddc{ii}ii{cc}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccccccc{dd}ddc{ii}ii{cc}ccccccc{i}icciicddciiccccddcii{c}cddcii{c}cddciiccccddciicddcc{d}d{cc}ccccccc{dd}ddc{ii}ii{cc}cccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cc}cccccccc{dd}ddc{ii}ii{cc}ccccccccc{i}iccc{d}dccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cc}ccccccccc{dd}ddc{ii}ii{ccc}{i}ic{d}dcccc{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}dd{c}c{{i}d}iic{{d}i}ddcccc{i}ic{d}d{ccc}{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}cc{i}icciicddciicddcc{d}dcccccccc{{i}d}iic{{d}i}ddcccccccc{i}icciicddciicddcc{d}d{ccc}cc{dd}ddc{ii}ii{ccc}ccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}dccccccccc{{i}d}iic{{d}i}ddccccccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{ccc}ccc{dd}ddc{ii}ii{ccc}cccc{i}iccc{d}d{c}{{i}d}iic{{d}i}dd{c}{i}iccc{d}d{ccc}cccc{dd}ddc{ii}ii{ccc}ccccc{i}ic{d}d{c}c{{i}d}iic{{d}i}dd{c}c{i}ic{d}d{ccc}ccccc{dd}ddc{ii}ii{cccc}cc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cccc}cc{dd}ddc{ii}ii{cccc}c{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cccc}c{dd}ddc{ii}ii{cccc}{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}{dd}ddc{ii}ii{ccc}ccccccccc{i}icciicddciiccccddciiccccddciicddcc{d}d{ccc}ccccccccc{dd}ddc{ii}ii{cccc}{i}ic{d}dc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddcccc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}{dd}ddc{ii}ii{cccc}c{i}iccc{d}dccc{{i}d}iic{{d}i}ddccc{i}iccc{d}d{cccc}c{dd}ddc{ii}ii{cccc}cc{i}ic{d}dcccc{{i}d}iic{{d}i}ddcccc{i}ic{d}d{cccc}cc{dd}ddc{ii}ii{cccc}ccccc{i}ic{d}dc{{i}d}iic{{d}i}ddc{i}ic{d}d{cccc}ccccc{dd}ddc{ii}ii{cccc}cccc{i}icciicddciicddcc{d}d{cccc}cccc{dd}ddc{ii}ii{cccc}ccccc{i}ic{d}dc{{i}d}iic{{d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/uMt/mcH2v9xlv8zg+1/uMt/mcFV/uMt/mcF7m8x9aqqvDBeuX61VV7mlglqgl+0Ev2glqglgrzH1qqrwwXrl+tVVXubzF/uMt/mcFV/uMt/mcH2v9xlv8zg+1/uMt/mcFV/uMt/mcF7m8x9aqqvDBeuX61VVXuavMVf7jLf5nB9r/cZb/M4Ptf7jLf5nBV7mrzH1qqqvDBeuX6t7m8xVf7jLf5nB9r/cZb/M4Ptf7jLf5nBVe5vMfVvDBeuX6tV7m8xf7jLf5nBe5vMVVVf7jLf5nBVVV7m8xf7jLf5nBe5vMfVqvDBeuX6tXuaWCWCvMVVV/uMt/mcFVVe5pYJYK8x9WrwwXrl+rVe5vMX+4y3+ZwXubzFVVX+4y3+ZwVVVe5vMX+4y3+ZwXubzH1arwwXrl+rVXuavMfb/cZb/M4Pt7mrzH1aq8MF65fq1Ve5vMfa/3GW/zOD7XubzH1aqvDBeuX6rV7m8xVf7jLf5nBVe5vMfVavDBeuX6rXuavMVf7jLf5nBV7mrzH1WvDBeuX6re5vMX+4y3+ZwVX+4y3+ZwVX+4y3+ZwXubzH1W8MF65fq1VVXuaWCWqCWqCWCvMfVqqqvDBeuX6re5vMX+4y3+ZwVX+4y3+ZwVX+4y3+ZwXubzH1W8MF65fqte5q8xV/uMt/mcFXuavMfVa8MF65fqtXubzFV/uMt/mcFV7m8x9Vq8MF65fqtVXubzF/uMt/mcF7m8x9Vqq8MF65fqtVe5pYJYK8x9VqrwwXrl+q1Ve5vMX+4y3+ZwXubzH1WqrwwXrl+q1VXuavMfVaqrwwXrl+q1VV7m8x9Vqqru7u7u7uA) Because why not? ]
[Question] [ Today we'll look at a sequence \$a\$, related to the Collatz function \$f\$: $$f = \begin{cases} n/2 & \text{if } n \equiv 0 \text{ (mod }2) \\ 3n+1 & \text{if } n \equiv 1 \text{ (mod }2) \\ \end{cases}$$ We call a sequence of the form \$z, f(z), f(f(z)), โ€ฆ\$ a *Collatz sequence*. The first number in *our* sequence, \$a(1)\$, is \$0\$. Under repeated application of \$f\$, it falls into a cycle \$0\to0\to0\to\:\cdots\$ The smallest number we haven't seen yet is 1, making \$a(2)=1\$. Under repeated application of \$f\$, it falls into a cycle \$1\to4\to2\to1\to\cdots\$ Now we have seen the number \$2\$ in the cycle above, so the next smallest number is \$a(3) = 3\$, falling into the cycle \$3\to10\to5\to16\to8\to4\to2\to1\to4\to\cdots\$ In all above cycles we've seen \$4\$ and \$5\$ already, so the next number is \$a(4) = 6\$. By now you should get the idea. \$a(n)\$ is the smallest number that was not part of any Collatz sequences for all \$a(1), ..., a(n-1)\$ Write a program or function that, given an positive integer \$n\$, returns \$a(n)\$. Shortest code in bytes wins. --- Testcases: ``` 1 -> 0 2 -> 1 3 -> 3 4 -> 6 5 -> 7 6 -> 9 7 -> 12 8 -> 15 9 -> 18 10 -> 19 50 -> 114 ``` (This is [OEIS sequence A061641](https://oeis.org/A061641).) [Answer] ## Haskell, ~~93~~ 92 bytes ``` c x|x<2=[[0,2]!!x]|odd x=x:c(3*x+1)|1<2=x:c(div x 2) ([y|y<-[-1..],all(/=y)$c=<<[0..y-1]]!!) ``` Usage example: `([y|y<-[-1..],all(/=y)$c=<<[0..y-1]]!!) 10` -> `19`. `c x` is the Collatz cycle for `x` with a little bit of cheating for `x == 1`. The main functions loops through all integers and keeps those that are not in `c x` for `x` in `[0..y-1]`. Pretty much a direct implementation of the definition. As Haskell index operator `!!` is 0-based, I start at `-1` to prepend a (otherwise useless) number to get the index fixed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` แธŸ@Jแธขร—3โ€˜$Hแธ‚?รฤฟ;แนš ร‡ยกแนช ``` [Try it online!](http://jelly.tryitonline.net/#code=4bifQErhuKLDlzPigJgkSOG4gj_DkMS_O-G5mgrDh8Kh4bmq&input=NTA) or [verify all test cases](http://jelly.tryitonline.net/#code=4bifQErhuKLDlzPigJgkSOG4gj_DkMS_O-G5mgrDh8Kh4bmqCsKi4bmEw58&input=MQoyCjMKNAo1CjYKNwo4CjkKMTAKNTA). ### How it works ``` ร‡ยกแนช Main link. No explicit arguments. Default argument: 0 ยก Read an integer n from STDIN and do the following n times. ร‡ Call the helper link. แนช Tail; extract the last element of the resulting array. แธŸ@Jแธขร—3โ€˜$Hแธ‚?รฤฟ;แนš Helper link. Argument: A (array) J Yield all 1-based indices of A, i.e., [1, ..., len(A)]. Since 0 belongs to A, there is at least one index that does belong to A. แธŸ@ Filter-false swapped; remove all indices that belong to A. แธข Head; extract the first index (i) that hasn't been removed. รฤฟ Call the quicklink to the left on i, then until the results are no longer unique. Collect all unique results in an array. แธ‚? If the last bit of the return value (r) is 1: $ Apply the monadic 3-link chain to the left to r. ร—3โ€˜ Yield 3r + 1. H Else, halve r. แนš Yield A, reversed. ; Concatenate the results array with reversed A. ``` After **n** iterations, the value of **a(n + 1)** will be at the beginning of the array. Since we concatenate the new array with a reversed copy of the old one, this means that **a(n)** will be at the end. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~46~~ 40 bytes ``` Oiq:"tX>Q:yX-X<`t0)to?3*Q}2/]h5M1>]Pv]0) ``` [**Try it online!**](http://matl.tryitonline.net/#code=T2lxOiJ0WD5ROnlYLVg8YHQwKXRvPzMqUX0yL11oNU0xPl1Qdl0wKQ&input=MTA) ### Explanation The code has an outer `for` loop that generates `n` Collatz sequences, one in each iteration. Each sequence is generated by an inner `do...while` loop that computes new values and stores them in a *sequence vector* until a `1` or `0` is obtained. When we are done with the sequence, the vector is reversed and concatenated to a *global vector* that contains the values from all previous sequences. This vector may contain repeated values. The reversing of the sequence vector ensures that at the end of the outer loop the desired result (the starting value of the last sequence) will be at the end of the global vector. **Pseudo-code**: ``` 1 Initiallization 2 Generate n sequences (for loop): 3 Compute initial value for the k-th sequence 4 Generate the k-th sequence (do...while loop) 5 Starting from latest value so far, apply the Collatz algorithm to get next value 6 Update sequence with new value 7 Check if we are done. If so, exit loop. We have the k-th sequence 8 Update vector of seen values 9 We now have the n sequences. Get final result ``` **Commented code**: ``` O % Push 0 1 iq: % Input n. Generate [1 2 ... n-1] ยท " % For loop: repeat n-1 times. Let k denote each iteration 2 t % Duplicate vector of all seen values ยท 3 X>Q % Take maximum, add 1 ยท ยท : % Range from 1 to that: these are potential initial values ยท ยท y % Duplicate vector of all seen values ยท ยท X-X< % Set difference, minimum: first value not seen ยท ยท ` % Do...while: this generates the k-th Collatz sequence ยท 4 t0) % Duplicate, push last value of the sequence so far ยท ยท 5 to % Duplicate, parity: 1 if odd, 0 if even ยท ยท ยท ? % If odd ยท ยท ยท 3*Q % Times 3, plus 1 ยท ยท ยท } % Else ยท ยท ยท 2/ % Half ยท ยท ยท ] % End if ยท ยท ยท h % Concatenate new value of the sequence ยท ยท 6 5M % Push the new value again ยท ยท 7 1> % Does it exceed 1? This is the loop condition ยท ยท ยท ] % End do...while. The loops ends when we have reached 0 or 1 ยท ยท P % Reverse the k-th Collatz sequence ยท 8 v % Concatenate with vector of previously seen values ยท ยท ] % End for ยท 0) % Take last value. Implicitly display. 9 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~70~~ ~~67~~ ~~65~~ ~~63~~ 62 bytes ``` ,[]:?:1ih. ,0<=X=,?'eXg{t{:2/.*?|:3*+.}gB,(?.sB;?:Bc:2&.)}:?c. ``` [Try it online!](http://brachylog.tryitonline.net/#code=LFtdOj86MWloLgosMDw9WD0sPydlWGd7dHs6Mi8uKj98OjMqKy59Z0IsKD8uc0I7PzpCYzoyJi4pfTo_Yy4&input=NTA&args=Wg) [Answer] # Python 2, ~~97~~ 96 bytes ``` r,=s={-1} exec'n=r=min({r+1,r+2,r+3}-s)\nwhile{n}-s:s|={n};n=(n/2,3*n+1)[n%2]\n'*input() print r ``` Takes advantage of the fact that all multiples of **3** are pure. Test it on [Ideone](http://ideone.com/rzzgz1). ### How it works On the first line, `r,=s={-1}` sets **s = {-1}** (set) and **r = -1**. Next we read an integer from STDIN, repeat a certain string that many times, then execute it. This is equivalent to the following Python code. ``` for _ in range(input()) n=r=min({r+1,r+2,r+3}-s) while{n}-s: s|={n} n=(n/2,3*n+1)[n%2] ``` In each iteration, we start by finding the smallest member of **{r+1, r+2, r+3}** that does not belong to **s**. In the first iteration, this initializes **r** as **0**. In all subsequent runs, **s** may (and will) contain some of **r+1**, **r+2** and **r+3**, but never all of them, since all multiples of **3** are pure. To verify this statement, observe that no multiple **m** of **3** is of the form **3k + 1**. That leaves **2m** as the only possible pre-image, which is also a multiple of **3**. Thus, **m** cannot appear in the Collatz sequence of any number that is less than **m**, and is therefore pure. After identifying **r** and initializing **n**, we apply the Collatz function with `n=(n/2,3*n+1)[n%2]`, adding each intermediate value of **n** to the set **s** with `s|={n}`. Once we encounter a number **n** that is already in **s**, `{n}-s` will yield an empty set, and the iteration stops. The last value of **r** is the desired element of the sequence. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 32 bytes ``` VtQ=+Y.u?%N2h*3N/N2Z)=Zf!}TYhZ)Z ``` [Test suite.](http://pyth.herokuapp.com/?code=VtQ%3D%2BY.u%3F%25N2h%2a3N%2FN2Z%29%3DZf%21%7DTYhZ%29Z&test_suite=1&test_suite_input=1%0A2%0A3%0A10%0A50&debug=0) [Answer] # Java, 148 bytes ``` int a(int n){if(n<2)return 0;int f=a(n-1),b,i,c;do{f++;for(b=1,i=1;i<n;i++)for(c=i==2?4:a(i);c>1;c=c%2>0?c*3+1:c/2)b=c==f?0:b;}while(b<1);return f;} ``` [Ideone it!](http://ideone.com/qJCxbQ) (Warning: exponential complexity due to zero optimization.) Converting it from a `do...while` loop to a `for` loop would be golfier, but I am having trouble doing so. Golfing advice is welcome as usual. [Answer] ## Perl6, 96 ``` my @s;my $a=0;map {while ($a=@s[$a]=$a%2??3*$a+1!!$a/2)>1 {};while @s[++$a] {}},2..slurp;$a.say; ``` Based on the [Perl 5 answer](https://codegolf.stackexchange.com/a/89755/14109). A bit longer since Perl6 syntax is less forgiving than Perl5 syntax, but I'll settle with this for now. [Answer] # PHP, ~~233~~ 124 bytes ``` <?$n=$argv[1];for($c=[];$n--;){for($v=0;in_array($v,$c);)$v++;for(;$n&&!in_array($v,$c);$v=$v&1?3*$v+1:$v/2)$c[]=$v;}echo$v; ``` +4 for function: ``` function a($n){for($c=[];$n--;){for($v=0;in_array($v,$c);)$v++;for(;$n&&!in_array($v,$c);$v=$v&1?3*$v+1:$v/2)$c[]=$v;}return$v;} ``` [Answer] # Perl 5 - 74 bytes ``` map{0 while 1<($a=$c[$a]=$a%2?$a*3+1:$a/2);0 while$c[++$a]}2..<>;print$a+0 ``` This is a pretty straightforward solution. It repeatedly applies the Collatz function to the variable `$a` and stores in the array `@c` that the value has been seen, then after reaching 0 or 1 it increments `$a` until it's a number that hasn't been seen yet. This is repeated a number of times equal to the input minus 2, and finally the value of `$a` is outputted. [Answer] # Mathematica, 134 bytes ``` f=If[EvenQ@#,#/2,3#+1]&;a@n_:=(b={i=c=0};While[i++<n-1,c=First[Range@Max[#+1]~Complement~#&@b];b=b~Union~NestWhileList[f,c,f@#>c&]];c) ``` Easier-to-read format: ``` f = If[EvenQ@#, #/2, 3#+1] &; Collatz function a@n_ := ( defines a(n) b = {i = c = 0}; initializations b is the growing sequence of cycles already completed While[i++ < n - 1, computes a(n) recursively c = First[Range@Max[# + 1]~Complement~# & @b]; smallest number not in b b = b~Union~NestWhileList[f, c, f@# > c &] apply f to c repeatedly until the answer is smaller than c, then add this new cycle to b ] ; c) output final value of c ``` ]
[Question] [ If you don't know already, a quaternion is basically a 4-part number. For the purposes of this challenge, it has a *real* component and three *imaginary* components. The imaginary components are represented by the suffix `i`, `j`, `k`. For example, `1-2i+3j-4k` is a quaternion with `1` being the real component and `-2`, `3`, and `-4` being the imaginary components. In this challenge you have to parse the string form of a quaternion (ex. `"1+2i-3j-4k"`) into a list/array of coefficients (ex. `[1 2 -3 -4]`). However, the quaternion string can be formatted in many different ways... * It may be normal: `1+2i-3j-4k` * It may have missing terms: `1-3k`, `2i-4k` (If you have missing terms, output `0` for those terms) * It may have missing coefficients: `i+j-k` (In this case, this is equivalent to `1i+1j-1k`. In other words, a `i`, `j`, or `k` without a number in front is assumed to have a `1` in front by default) * It may not be in the right order: `2i-1+3k-4j` * The coefficients may be simply integers or decimals: `7-2.4i+3.75j-4.0k` There are some things to note while parsing: * There will always be a `+` or `-` between terms * You will always be passed valid input with at least 1 term, and without repeated letters (no `j-j`s) * All numbers can be assumed to be valid * You can change numbers into another form after parsing if you want (ex. `3.0 => 3`, `0.4 => .4`, `7 => 7.0`) Parsing/quaternion builtins and standard loopholes are disallowed. This includes `eval` keywords and functions. Input will be a single string and output will be a list, an array, values separated by whitespace, etc. As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. ### Tons o' test cases ``` 1+2i+3j+4k => [1 2 3 4] -1+3i-3j+7k => [-1 3 -3 7] -1-4i-9j-2k => [-1 -4 -9 -2] 17-16i-15j-14k => [17 -16 -15 -14] 7+2i => [7 2 0 0] 2i-6k => [0 2 0 -6] 1-5j+2k => [1 0 -5 2] 3+4i-9k => [3 4 0 -9] 42i+j-k => [0 42 1 -1] 6-2i+j-3k => [6 -2 1 -3] 1+i+j+k => [1 1 1 1] -1-i-j-k => [-1 -1 -1 -1] 16k-20j+2i-7 => [-7 2 -20 16] i+4k-3j+2 => [2 1 -3 4] 5k-2i+9+3j => [9 -2 3 5] 5k-2j+3 => [3 0 -2 5] 1.75-1.75i-1.75j-1.75k => [1.75 -1.75 -1.75 -1.75] 2.0j-3k+0.47i-13 => [-13 0.47 2.0 -3] or [-13 .47 2 -3] 5.6-3i => [5.6 -3 0 0] k-7.6i => [0 -7.6 0 1] 0 => [0 0 0 0] 0j+0k => [0 0 0 0] -0j => [0 0 0 0] or [0 0 -0 0] 1-0k => [1 0 0 0] or [1 0 0 -0] ``` [Answer] # Retina, 115 ``` \b[ijk] 1$& ^(?!.*\d([+-]|$)) 0+ ^(?!.*i) +0i+ ^(?!.*j) 0j+ ^(?!.*k) 0k+ O$`[+-]*[\d.]*(\w?) $1 - +- ^\+ S`[ijk+]+ ``` [Try it online!](http://retina.tryitonline.net/#code=XGJbaWprXQoxJCYKXig_IS4qXGQoWystXXwkKSkKMCsKXig_IS4qaSkKKzBpKwpeKD8hLipqKQowaisKXig_IS4qaykKMGsrCk8kYFsrLV0qW1xkLl0qKFx3PykKJDEKLQorLQpeXCsKClNgW2lqaytdKw&input=MWotNS4wLWk) 1 byte saved thanks to [@Chris Jester-Young](https://codegolf.stackexchange.com/users/3). A bug fixed and 6 bytes saved thanks to [@Martin Bรผttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) Found a couple bugs involving some edge cases, bumped up byte count quite a bit. Returns the numbers newline separated. Anyway, this has a mostly elegant solution that sort of gets ruined by edge cases but hey I got to use sort mode, that means I used the right tool for the job, right? ### Explanation: Stage by stage, as usual. ``` \b[ijk] 1$& ``` The only characters in the input that can create word boundaries are `-+.`. This means that if we find a boundary followed by a letter, we have an implicit `1` which we add in with the replacement. `$&` is a synonym for `$0`. ``` ^(?!.*\d([+-]|$)) 0+ ``` Big thanks to Martin for this one, this one adds in the implicit `0` for the real part if it was missing in the input. We make sure that we can't find a number that is followed by a plus or minus sign, or the end of the string. All the complex numbers will have a letter after them. ``` ^(?!.*i) +0i+ ``` The next 3 stages are all pretty much the same, barring which letter they impact. All of them look to see if we can't match the letter, and if we can't we add a `0` term for it. The only reason `i` has an extra `+` before it is to prevent the real value from being unreadable with the `i`s coefficient, the other numbers are all separated by their complex variable. ``` O$`[+-]*[\d.]*(\w?) $1 ``` Ah, the fun part. This uses the newish sort stage, denoted by the `O` before the option separator backtick. The trick here is to grab the whole number followed optionally by a word character, which in this case will only ever match one of `ijk`. The other option used is `$` which causes the value used to sort these matches to be the replacement. Here we just use the optional letter left over as our sort value. Since Retina sorts lexicographically by default, the values are sorted like they would be in a dictionary, meaning we get the matches in `"", "i", "j", "k"` order. ``` - +- ``` This stage puts a `+` sign in front of all the minus signs, this is needed if we have a negative value for `i` in the split stage, later. ``` ^\+ ``` We remove the leading `+` to make sure we have no extra leading newline. ``` S`[ijk+]+ ``` Split the remaining lines on runs of the complex variables or the plus sign. This nicely gives us one value per line. [Answer] # Pyth, 48 bytes ``` jm+Wg\-K--e|d0G\+K1+]-I#GJczfT.e*k<b\.zm/#dJ"ijk ``` [Demonstration](https://pyth.herokuapp.com/?code=jm%2BWg%5C-K--e%7Cd0G%5C%2BK1%2B%5D-I%23GJczfT.e%2ak%3Cb%5C.zm%2F%23dJ%22ijk&input=0.42i%2Bj-k&debug=0) [Test suite](https://pyth.herokuapp.com/?code=jdm%2BWg%5C-K--e%7Cd0G%5C%2BK1%2B%5D-I%23GJczfT.e%2ak%3Cb%5C.zm%2F%23dJ%22ijk&test_suite=1&test_suite_input=1%2B2i%2B3j%2B4k%0A-1%2B3i-3j%2B7k%0A-1-4i-9j-2k%0A17-16i-15j-14k%0A7%2B2i%0A2i-6k%0A1-5j%2B2k%0A3%2B4i-9k%0A42i%2Bj-k%0A6-2i%2Bj-3k%0A1%2Bi%2Bj%2Bk%0A-1-i-j-k%0A16k-20j%2B2i-7%0Ai%2B4k-3j%2B2%0A5k-2i%2B9%2B3j%0A5k-2j%2B3%0A1.75-1.75i-1.75j-1.75k%0A2.0j-3k%2B0.47i-13%0A5.6-3i%0Ak-7.6i%0A0%0A0j%2B0k%0A-0j%0A1-0k&debug=0) The output format is newline separated. The test suite code uses space separation, for ease of reading, but is otherwise the same. Outputs a `-0` in the last 2 cases, which I hope is OK. Explanation to follow. [Answer] ## Perl 5, 125 bytes ``` #!perl -p %n=(h,0,i,0,j,0,k,0);$n{$4//h}=0+"$1@{[$3//$5//1]}"while/([+-]?)(([\d.]+)?([ijk])|([\d.]+))/g;s/.*/@n{qw(h i j k)}/ ``` [Answer] # [Lua](http://www.lua.org/), ~~185~~ ~~187~~ ~~195~~ ~~183~~ 166 bytes ([try it online](http://www.lua.org/cgi-bin/demo)) [used regex] Thanks to *[@Chris Jester-Young](https://codegolf.stackexchange.com/users/3/chris-jester-young)* for the improved regex. Thanks to *[@Katenkyo](https://codegolf.stackexchange.com/users/41019/katenkyo)* for bringing it down to 166 bytes. Golfed: ``` r={0,0,0,0}for u in(...):gsub("([+-])(%a)","%11%2"):gmatch("-?[%d.]+%a?")do n,i=u:match("(.+)(%a)")r[i and(" ijk"):find(i)or 1]=(n or u)end print(table.concat(r," ")) ``` Ungolfed: ``` n = "42i+j-k+0.7" result = {0,0,0,0} for unit in n:gsub("([+-])(%a)","%11%2"):gmatch("-?[%d.]+%a?") do num, index = unit:match("(.+)(%a)") if index == "i" then result[2] = num elseif index == "j" then result[3] = num elseif index == "k" then result[4] = num else result[1] = unit end end print(table.concat(result," ")) ``` [Answer] # C, 236 bytes ``` char j,n[9][9],s[9],y[9],i=8,k,*p=n[8];main(c){for(**n=48;c=getchar(),c+1;)c-32&&(c<46&&(k&&(y[1]=i),k=0,s[--i]=c-43,p=n[i])||c>57&&(k||(*p=49),k=0,y[c-103]=i)||(*p++=c,k=1));for(k&&(y[1]=i);++j<5;)printf("%c%s ",s[y[j]]?45:0,n[y[j]]);} ``` (For values like -0 or -0.0, the minus sign is also printed in the output, ~~but since the challenge states that "you can change numbers into another form after parsing if you want", and if -0 appears in the input, it follows that it's also acceptable in the output.~~ @GamrCorps has now clarified that this is ok.) [Answer] ## JavaScript (ES6), ~~103~~ 100 bytes ``` f=s=>s.replace(/(?=.)(\+|-|)([\d.]*)(\w?)/g,(_,s,x,c)=>a[c.charCodeAt()&3]=+(s+(x||1)),a=[0,0,0,0])&&a ``` Edit: Saved 3 bytes by switching from `parseInt` to `charCodeAt`, which conveniently just needs `&3` to get me the correct array index. [Answer] # JavaScript (ES6) 106 ``` s=>(s.replace(/([+-]?)([\d.]*)(\w?)/g,(a,b,c,d)=>a&&(s[d||9]=b+(c||1)),s={}),[...'9ijk'].map(i=>+s[i]||0)) ``` **Test** ``` f=s=>(s.replace(/([+-]?)([\d.]*)(\w?)/g,(a,b,c,d)=>a&&(s[d||9]=b+(c||1)),s={}),[...'9ijk'].map(i=>+s[i]||0)) function Test() { var t,k,r,ts=TS.value.split('\n') O.textContent=ts.map(x=>x.trim()&&( [t,k]=x.split('=>').map(x=>x.trim()), console.log(t,'*',k), k=k.match(/[\d+-.]+/g).map(x=>+x), r=f(t), t+' => '+r+(r+''==k+''?' OK':' KO (check: '+k+')') )).join('\n') } Test() ``` ``` #TS { width:90%; height:10em} ``` ``` <pre id=O></pre> Test data (modify if you like)<button onclick='Test()'>repeat test</button> <textarea id=TS> 1+2i+3j+4k => [1 2 3 4] -1+3i-3j+7k => [-1 3 -3 7] -1-4i-9j-2k => [-1 -4 -9 -2] 17-16i-15j-14k => [17 -16 -15 -14] 7+2i => [7 2 0 0] 2i-6k => [0 2 0 -6] 1-5j+2k => [1 0 -5 2] 3+4i-9k => [3 4 0 -9] 42i+j-k => [0 42 1 -1] 6-2i+j-3k => [6 -2 1 -3] 1+i+j+k => [1 1 1 1] -1-i-j-k => [-1 -1 -1 -1] 16k-20j+2i-7 => [-7 2 -20 16] i+4k-3j+2 => [2 1 -3 4] 5k-2i+9+3j => [9 -2 3 5] 5k-2j+3 => [3 0 -2 5] 1.75-1.75i-1.75j-1.75k => [1.75 -1.75 -1.75 -1.75] 2.0j-3k+0.47i-13 => [-13 0.47 2.0 -3] 5.6-3i => [5.6 -3 0 0] k-7.6i => [0 -7.6 0 1] 0 => [0 0 0 0] 0j+0k => [0 0 0 0] -0j => [0 0 0 0] 1-0k => [1 0 0 0] </textarea> ``` [Answer] # PowerShell, 178 bytes ``` param($a);$p="(-?)([\d.]+)?";$g={param($s)if($a-match"$p$s"){if(($r=$matches)[2]){$r[1]+$r[2]}else{$r[1]+1}}else{0}};$a-match"$p(\+|-|$)">$null;+$matches[2];"i","j","k"|%{&$g $_} ``` --- **Ungolfed with Explanation** ``` # Get the whole string into a variable param($a) # Pattern shared getting both imaginary and real numbers. $p="(-?)([\d.]+)?" # Anonymous function that will locate a imaginary number using a letter sent as a parameter. # If no value is assigned a signed 1 is returned. If no value is matched 0 is returned $g={param($s)if($a-match"$p$s"){if(($r=$matches)[2]){$r[1]+$r[2]}else{$r[1]+1}}else{0}} # Locate the real component if any. Null is converted to 0 $a-match"$p(\+|-|$)">$null;+$matches[2] # Call the anonymous function using each of the imaginary suffixes. "i","j","k"|%{&$g $_} ``` Not super impressed but it is a result nonetheless. [Answer] # PHP, 179 bytes ``` $a=[''=>0,'i'=> 0,'j'=>0,'k'=>0];preg_match_all("/([-+]?)(\d*(\.\d+)?)([ijk]?)/",$argv[1],$m,2);foreach($m as$n)if($n[0])$a[$n[4]]=$n[1].($n[2]===''?1:$n[2]);echo implode(',',$a); ``` Try the [test suite](https://3v4l.org/gODeF). [Answer] # Python 3.5 - 496 bytes [using Regular Expressions]: ``` from re import* def wq(r): a=sub('[+](?![0-9])','+1',sub('[-](?![0-9])','-1',r));q=lambda x:(not x.isdigit(),''.join(filter(str.isalpha,x))) for z in findall('(?<![0-9])[a-z]',a):a=a.replace(z,('+1{}'.format(z))) if not str(sorted(((sub('[.]','',sub('[+-]',' ',a))).split(' ')),key=q)[0]).isdigit():a+='+0, ' for i in list(set(findall('[a-z]',a))^{'i','j','k'}):a+='+0{}, '.format(i) print(findall('[-]?\d+(?:\.\d+)?',''.join(sorted(sub('(?<=[A-Za-z0-9])(?=[+-])',', ',a).split(' '),key=q)))) ``` It may be long, but in my defense, it works perfectly in doing what the OP wants, since all the test cases given were successful using my code. # Ungolfed version with explanation included: ``` from re import* def w(r): # Substitute all minus (-) and plus (+) signs NOT followed by a number (if there are any) with a "-1"/"+1", respectively. a=sub('[+](?![0-9])','+1',sub('[-](?![0-9])','-1',r)) # Lambda function created for later use to sort the Quaternion. This function, when given as a key to the "sorted" function, arranges the input Quaternion in the order where the whole number comes first, and then the rest are placed in order of increasing letter value (i,j,k in this case) q=lambda x:(not x.isdigit(),''.join(filter(str.isalpha,x))) # The following "for" loop replaces the letters NOT preceded by a number with a one followed by that letter for z in findall('(?<![0-9])[a-z]',a): a=a.replace(z,('+1{}'.format(z))) # The following first substitutes all pluses and minuses (+ and -) with a space, and then that new string is split at those spaces, and returned as a list. After that, the list is sorted according the the "lambda" function shown above. Then, the first item in that list, which is supposed to be a lone number, is checked to make sure that it indeed is a lone number. If it isn't, then "+0, " is appended to the Quaternion. if not str(sorted(((sub('[.]','',sub('[+-]',' ',a))).split(' ')),key=q)[0]).isdigit(): a+='+0, ' # The following "for" loop finds ALL the letters NOT in the list, by finding the symmetric difference between a set of all the letters found, and a set containing all the letters needed. For the letters not in the list, a '+0' is added the quaternion, followed by that letter, and then a comma and a space. for i in list(set(findall('[a-z]',a))^{'i','j','k'}): a+='+0{}, '.format(i) # Finally, in this last step, a ", " is added IN BETWEEN unicode characters and pluses/minuses (+/-). Then, it splits at those spaces, and the commas separate different parts of the Quaternion from each other (otherwise, you would get something like `12i+3j+4k` from `2i+3j+4k+1`) in a returned list. Then, that list is sorted according to the lambda expression "q" (above), and then, finally, the NUMBERS (of any type, courtesy to Regex) are extracted from that joined list, and printed out in the correct order. print(findall('[-]?\d+(?:\.\d+)?',''.join(sorted(sub('(?<=[A-Za-z0-9])(?=[+-])',', ',a).split(' '),key=q)))) ``` If the above is a little too hard to read, basically what is happening is that: 1. If there are any, all + or - signs NOT followed by a number are replaced with a "+1"/"-1", respectively. 2. A `lambda` function is defined, which, when used in a `sorted` function as a key, sorts the list according to putting the whole number first, and then ordering the rest in increasing letter value ("i",then "j", then "k" in this instance). 3. The Quaternion, now having all +/- signs replaced with a 1 if needed, is searched, using Regular Expressions, for ALL letters NOT preceded by at least one number, and those letters that match are replaced with a "+1" followed by that letter. 4. The "if" statement then replaces ALL +/- signs with a space, and then the modified Quaternion is now "split" at those spaces, and returned in a list. Then, the list is sorted according to the lambda function explained earlier. Finally, the first item in that list is checked to make sure it's a number, since it's supposed to be, and if it's not, then a "+0, " is added to the Quaternion. 5. The second "for" loop finds ALL the letters NOT in the Quaternion by finding a symmetric difference between a set of those letters found in the expression, and then a set including all letters required. If any are found, then a "+0" followed by the missing letter and a space is added to the Quaternion. 6. Finally, in this last step, a ", " is added *in between* each character followed by a +/- symbol, and then the Quaternion is split at those spaces, then the list returned is sorted, for the last time, according to the lambda function defined as "q" earlier on. The commas in the expression separate each part of the quaternion (otherwise, you would be getting something like `14i+5j+6k` from `4i+5j+6k+1`). Lastly, that now sorted list is joined together into a string, and only the **numbers** *of any type* (courtesy of Regular Expressions) are extracted, and finally returned in a list, in the correct order, every single time. ]
[Question] [ [Bytebeat](http://canonical.org/~kragen/bytebeat/) is a style of music one can compose by writing a simple C program that's output is piped to `aplay` or `/dev/dsp`. ``` main(t){for(;;t++)putchar(((t<<1)^((t<<1)+(t>>7)&t>>12))|t>>(4-(1^7&(t>>19)))|t>>7);} ``` There is a good deal of information on the [bytebeat site](http://canonical.org/~kragen/bytebeat/), a [javascript implementation](http://wurstcaptures.untergrund.net/music/), and more demos and example compositions in [this thread](http://www.metafilter.com/111959/Todays-formulaic-music). Very simple rules : Try to write a pretty sounding composition. Most up votes wins since that's obviously subjective, although not that subjective considering the usual results. [Answer] (Signed 16-bit little endian, 8000Hz mono (`--format=S16_LE`)) ## Music **Much** better than before! (although it's quite long) `main(t){for(;;t++)putchar(((7&(((t>>17)+1)>>2)+((t>>10)&1+2*(t>>18&1))*(("23468643"[7&t>>12]-48)+(3&t>>11))+((3&t>>17)>0)*(3&t>>9)*!(1&t>>10)*(((2+t>>10&3)^(2+t>>11&3))))*t*"@06+"[3&t>>15]/32));}` (You can listen this [at here](http://snd.sc/zFYrxo)) I wrote this, but even I don't know how some part works, like `>0` and (especially) the first `7&`. Change for loop to `for(;!(t>>22);t++)`... to listen it 'once'. I don't know whether it "loops" exactly the same way, however. ## Melody (base of above music) I love this melody I made (C-G-A-F ftw), but it's too 'plain'... `main(t){for(;;t++)putchar(((t>>10)&1)*(t*("23468643"[7&t>>12]-48)+t*(3&t>>11))*"@06+"[3&t>>15]/32);}` ## Simple music (which I made before) `main(t){for(;;t++)putchar(t*(3&t>>11)+(t&t>>11)*4*!((t>>11)%3));}` [Answer] The [ruler function](http://oeis.org/A001511) in C minor: ``` #include <math.h> #include <stdio.h> #define PI 3.14159265358979323846 #define step(freq, n) ((freq) * pow(2, (n) / 12.0)) #define note(n) step(440, n) #define MIDDLE_C note(-9) int count_zeros(unsigned int n) { int count = 0; for (; (n & 1) == 0; n >>= 1) count++; return count; } int minor_note(int note) { int octave = note / 7; int scale[] = {0, 2, 3, 5, 7, 8, 10}; note %= 7; if (note < 0) { note += 7; octave--; } return scale[note] + octave*12; } int main(void) { double t = 0.0; double freq = MIDDLE_C * 2; double step = PI * 2 / 8192; int n = 0; int i = 0; for (i = 1;; t += step, i++) { if (i == 1024) { i = 0; n++; freq = step(MIDDLE_C, minor_note(count_zeros(n))); } putchar(sin(t * freq) * 50.0 + 128.0); } return 0; } ``` [Answer] ``` main(t){for(;;t+=(t%6)?1:2)putchar((((t<<t^(t>>8))|(t<<7))*((t<<t&(t>>12))|(t<<10))));} ``` [Answer] Emphasising "beat" over "byte": ``` #include<math.h> double s(double,double);double r(double,double);double d(double);double f(double); char bytebeat(int t){return (d(f(t/4000.)/3) + 1) * 63;} double f(double t){ double sn=s(1./2,t-1); sn*=(sn*sn); return 3*s(1./4,1/s(1,t))+3*s(4,1/sn)/2+s(4,1/(sn*sn*sn*sn*sn))/4 +2*s(55+18.3*r(1./2,t),t)+s(110+s(5,t)/4000,t)*s(1,t)+s(220+110*r(1,t)+55*r(3,t),t)/5 +s(880+440*r(1./2,t)-220*r(1,t)+110*r(2,t)+s(5,t)/4000,t) *(2+s(1760+438*r(3./2,t)-1234*r(2,t)+423*r(5,t),t))/9 +s(s(1,t)+s(1./2,t)+s(1./4,t)+s(1./8,t),t)*s(s(1,t)+s(1./2,t)+s(1./4,t)+s(1./8,t)+1,t) +r(264+11*r(1./20,t),t)*s(1./20,t); } double s(double f,double t){return d(sin(f*3.14159265*(t+999)));} double r(double f,double t){return s(f,t)<0;} double d(double a){return tanh(a+a*a/4);} main(t){for(;;++t)putchar(bytebeat(t));} ``` To be used at 8 kHz, uint8 mono. Sounds best over decently bass-capable loudspeakers. [Answer] ``` main(){for(;;)putchar(rand());} ``` Sounds like the ocean ;-) [Answer] Combined melody and harmony: ``` r=3, r=3, m=(t*(t>>12|t>>13|t>>14|t>>15|t>>16|t>>17|t>>18))&63, h= ((t&t>>7&t>>6)|t*5&t>>8-c^t*6&t>>9-c|t*7&t>>12-c^t*9&t>>11-c^t*11&t>>22^t*19&t>>20^t*14&t>>20|t*23&t>>15-c|t*12&t>>9|t*30&t>>30|t>>5|t>>4)-31, m|h ``` ]
[Question] [ Sometimes, when writing a program, you need to use a prime number for some reason or other (e.g. cryptography). I assume that sometimes, you need to use a composite number, too. Sometimes, at least here on PPCG, your program has to be able to deal with arbitrary changes. And in circumstances conveniently contrived to make an interesting PPCG question, perhaps even the numbers you're using have to be resistant to corruptionโ€ฆ ## Definitions A *composite number* is an integer โ‰ฅ 4 that isn't prime, i.e. it is the product of two smaller integers greater than 1. A *bitflip-resistant composite number* is defined as follows: it's a composite positive integer for which, if you write it in binary in the minimum possible number of bits, you can change any one or two bits from the number, and the number is still composite. ## Example For example, consider the number 84. In binary, that's `1010100`. Here are all the numbers which differ by no more than 2 bits from that: ``` 0000100 4 2ร—2 0010000 16 4ร—4 0010100 20 4ร—5 0010101 21 3ร—7 0010110 22 2ร—11 0011100 28 4ร—7 0110100 52 4ร—13 1000000 64 8ร—8 1000100 68 4ร—17 1000101 69 3ร—23 1000110 70 7ร—10 1001100 76 4ร—19 1010000 80 8ร—10 1010001 81 9ร—9 1010010 82 2ร—41 1010100 84 7ร—12 1010101 85 5ร—17 1010110 86 2ร—43 1010111 87 3ร—29 1011000 88 8ร—11 1011100 92 4ร—23 1011101 93 3ร—31 1011110 94 2ร—47 1100100 100 10ร—10 1110000 112 8ร—14 1110100 116 4ร—29 1110101 117 9ร—13 1110110 118 2ร—59 1111100 124 4ร—31 ``` The first column is the number in binary; the second column is the number in decimal. As the third column indicates, all of these numbers are composite. As such, 84 is a bitflip-resistant composite number. ## The task You must write one of the following three programs or functions, whichever makes the most sense for your language: * A program or function that takes a nonnegative integer *n* as input, and outputs the first *n* bitflip-resistant composite numbers. * A program or function that takes a nonnegative integer *n* as input, and outputs all bitflip-resistant composite numbers less than *n* (or if you prefer, less than or equal to *n*, i.e. you can choose whether *n* is included in the output if bitflip-resistant). * A program or function that takes no input, and outputs all bitflip-resistant composite numbers. (This must use an output mechanism capable of producing output while the program is still running, such as printing to stdout, a lazy list, or a generator; you can't just calculate the entire list and then print it.) ## Test cases Here are the first few bitflip-resistant composite numbers: ``` 84, 184, 246, 252, 324, 342, 424, 468, 588, 636, 664, 670, 712, 730, 934, 958 ``` ## Clarifications * It's only the numbers you produce that have to be resistant to bitflips. This isn't a task about making the program that finds them resistant to bitflips; use whatever numbers in the program itself that you like. * The numbers you output don't have to be resistant to a bitflip in the "leading zeroes"; imagine that the numbers will be stored in the minimum possible number of bits, and only those bits have to be immune to flipping. However, the initial 1 bits on the numbers you output do have to be immune to bitflips. * Use any algorithm you like that produces the right result; you aren't being marked on efficiency here. * If you can prove that there are finitely many bitflip-resistant composite numbers, then a) the restrictions on output format are lifted, and b) hardcoding the list will be allowed (although probably more verbose than just calculating it). This rule is mostly just for completeness; I don't expect it to be relevant. ## Victory condition This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so as usual, shorter is better. Also as usual, the length of the program will be measured in bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20? 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` BยตJล’ฤ‹;0แนฌ^ยตแธ„ยตร†PoแปŠแน€ยฌ โดร‡# ``` **[Try it online!](https://tio.run/nexus/jelly#AS0A0v//QsK1SsWSxIs7MOG5rF7CteG4hMK1w4ZQb@G7iuG5gMKsCuKBtMOHI////zc)** Yields the first **n** such numbers. *Maybe the `;0` can be removed (without it we don't check if the number itself is composite - are there any primes with all bit-flips composite?)* Note that it is **not** sufficient to perform the test `not(any(is prime))` to the set of bit-flipped numbers. We must also test that `0` is not in the set. This is because `0` is not prime and not composite (`1` is too, but see below). The need to check for `0` may be seen by a counter-example: * `131136` (**217+26**) has the following bit-flip set: ``` [0, 64, 65, 66, 68, 72, 80, 96, 192, 320, 576, 1088, 2112, 4160, 8256, 16448, 32832, 65600, 131072, 131073, 131074, 131076, 131080, 131088, 131104, 131136, 131137, 131138, 131139, 131140, 131141, 131142, 131144, 131145, 131146, 131148, 131152, 131153, 131154, 131156, 131160, 131168, 131169, 131170, 131172, 131176, 131184, 131200, 131264, 131265, 131266, 131268, 131272, 131280, 131296, 131328, 131392, 131393, 131394, 131396, 131400, 131408, 131424, 131520, 131584, 131648, 131649, 131650, 131652, 131656, 131664, 131680, 131776, 131904, 132096, 132160, 132161, 132162, 132164, 132168, 132176, 132192, 132288, 132416, 132672, 133120, 133184, 133185, 133186, 133188, 133192, 133200, 133216, 133312, 133440, 133696, 134208, 135168, 135232, 135233, 135234, 135236, 135240, 135248, 135264, 135360, 135488, 135744, 136256, 137280, 139264, 139328, 139329, 139330, 139332, 139336, 139344, 139360, 139456, 139584, 139840, 140352, 141376, 143424, 147456, 147520, 147521, 147522, 147524, 147528, 147536, 147552, 147648, 147776, 148032, 148544, 149568, 151616, 155712, 163840, 163904, 163905, 163906, 163908, 163912, 163920, 163936, 164032, 164160, 164416, 164928, 165952, 168000, 172096, 180288, 196608, 196672, 196673, 196674, 196676, 196680, 196688, 196704, 196800, 196928, 197184, 197696, 198720, 200768, 204864, 213056, 229440] ``` All of which, except `0` are composite, yet `0` is not prime. `1` is also non-prime and non-composite and could appear in the set. However we can, if we want, leave this as if it were a composite: * all inputs less than or equal to `3` (if being considered at all) contain a `0` anyway (in fact all less than `7` do). * to reach `1` in one bit flip the original number must be of the form **2k+20**, and if this is greater than `3`, i.e. **k>1**, then we can reach `3` by flipping off the **k**-bit and setting the **1**-bit (**21+20=3**). * to reach `1` in two bit flips the original number must be of the form **2k** and if this is greater than `3` we can reach `2` in two flips instead, and `2` is prime. As it stands the code is handling both `0` and `1` together using the "insignificant" atom, `แปŠ`. ### How? ``` โดร‡# - Main link: n โด - 16 # - count up from 16 finding the first n matches of ร‡ - last link (1) as a monad BยตJล’ฤ‹;0แนฌ^ยตแธ„ยตร†PoแปŠแน€ยฌ - Link 1, test a number: i B - convert to a binary list ยต - start a new monadic chain J - range(length): [1,2,...,nBits] ล’ฤ‹ - pairs with replacement: [[1,1],[1,2],...,[1,nBits],[2,2],[2,3],...,[2,nBits],...,[nBits-1,nBits]] ;0 - concatenate a zero แนฌ - untruth (makes lists with ones at those indexes - the [1,1], [2,2], etc make the one-flips, the zero makes the no-flip, the rest make the two-flips) ^ - exclusive or with the binary list version of i (flip the bits) ยต - start a new monadic chain แธ„ - un-binary (get the integer values of each of the flipped versions) ยต - start a new monadic chain ร†P - is prime? (make a list of 1s for primes and 0 for non-primes) แปŠ - is insignificant (abs(v)<=1) o - logical or (now we have true for any primes, 0 or 1 - hence non-composites) แน€ - maximum (1 if any non-composite was found) ยฌ - not (1 if all were composite) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~32~~ 38 bytes ``` 2<โ‰œ.ยฌ(แธƒโ†ฐโ‚‚โ†ฐโ‚‚~แธƒโ‰œ{แน—|โ„•<2}โˆง) k~k|tgTโˆง?kโ†ฐ:Tc ``` [Try it online!](https://tio.run/nexus/brachylog2#@29k86hzjt6hNRoPdzQ/atvwqKkJQtaB@J1zqh/unF7zqGWqjVHto47lmlzZddk1JekhQLZ9NlChVUjy////owA "Brachylog โ€“ TIO Nexus") This is a function/predicate `โ†ฐโ‚€` that returns a generator that generates all such numbers. (The TIO link only prints the first number, so that something's observable. Running it locally has produced many more, though.) Now updated to handle numbers which are within two bitflips of 0 or 1 (which are neither prime nor composite) correctly. ## Explanation **Helper predicate** `โ†ฐโ‚‚` (returns a list that's equal to the input, except for maybe one element) ``` k~k|tgTโˆง?kโ†ฐ:Tc | Either: ~k the output is produced by appending an arbitrary element k to the input minus its last element Or: ?k take the input minus its last element, โ†ฐ call this predicate recursively on that, T :Tc then append g the singleton list consisting of t the last element of the input ``` I'd love it if there were a terser way to do this relatively simple recursion, but I'm not sure there is yet; there are some promising-looking features in the specification, but they're marked as unimplemented. **Main program** `โ†ฐโ‚€` ``` 2<โ‰œ.ยฌ(แธƒโ†ฐโ‚‚โ†ฐโ‚‚~แธƒโ‰œ{แน—|โ„•<2}โˆง) 2<โ‰œ For each integer greater than 2 . generate it if ยฌ( ) it does not have the following property: แธƒ converting it to binary, โ†ฐโ‚‚โ†ฐโ‚‚ running the helper predicate twice, ~แธƒ and converting back to decimal โ‰œ does not allow us to find a specific value { } that is: แน— prime; | or: โ„•<2 nonnegative and less than 2 โˆง (disable an unwanted implicit constraint) ``` [Answer] ## JavaScript (ES6), 96 bytes A full program that prompts for the number of matching integers and displays them one by one, using `alert()`. ``` for(i=prompt(n=2);i;n+=2)(g=b=>b>n?alert(n,i--):(C=(n,x=n)=>n%--x?C(n,x):x>1)(n^b|1)&&g(b*2))(1) ``` Unless your browser is set up to use Tail Call Optimization, this will eventually break because of a recursion overflow. Below is a non-recursive version (102 bytes). ``` for(i=prompt(n=2);i;n+=2){for(c=b=1;b<n;b*=2,c&=C)for(C=k=2,x=n^b|1;k<x;k++)C|=!(x%k);c&&alert(n,i--)} ``` ### Assumption This algorithm relies on the assumption that all bitflip-resistant composite numbers are even. This leads to a rather important simplification: instead of flipping every possible pair of bits, we only flip bit #0 and another one (or no other bit at all) and check that all resulting numbers are composite. However, I can't figure out any obvious proof that an odd bitflip-resistant composite number doesn't actually exist. It just happens to never be the case for small numbers (I checked up to 1,000,000), and it seems like the probability of finding one is decreasing as the number of bits is increasing (but this is basically just my intuition about it). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 17 bytes ``` BJล’ฤ‹แนฌUแธ„^;โธร†แธแน‚แปŠยตรแธŸ ``` [Try it online!](https://tio.run/nexus/jelly#ASwA0///QkrFksSL4bmsVeG4hF474oG4w4bhuI3huYLhu4rCtcOQ4bif////MTAwMA "Jelly โ€“ TIO Nexus") ### How it works ``` BJล’ฤ‹แนฌUแธ„^;โธร†แธแน‚แปŠยตรแธŸ Main link. Argument: n ยต Combine all links to the left into a chain. รแธŸ Filter-false; keep only integers k from [1, ..., n] for which the chain returns 0. B Convert k to binary. J Get the indices of all digits. ล’ฤ‹ Take all combination of two indices, with replacement. แนฌ Untruth; map each index pair [i, j] to the Boolean array of length j that has 1's at (and only at) indices i and j. U Upend; reverse each Boolean array. แธ„ Unbinary; convert each array from base 2 to integer. ^ XOR the resulting numbers with k. ;โธ Append k to the resulting list. ร†แธ Count the number of proper divisors of each result. แน‚ Take the minimum. แปŠ Insignificant; test if the minimum is 0 or 1. ``` [Answer] # Python 2, 113 bytes ``` r=range lambda N:[n for n in r(1,N)if 1-any((bin(k).count('1')<3)*all((n^k)%q for q in r(2,n^k))for k in r(n+1))] ``` (The second line is an unnamed function which returns a list of all bitflip-resistant composite numbers which are less than the input to the function.) The syntax `all(u%q for q in range(2,u))` will evaluate to `True` whenever `u` is either prime or less than or equal to `2`, and otherwise will evaluate to `False`. (It is vacuously `True` if `u` is less than or equal to `2`.) In other words, `all(u%q for q in range(2,u))` is equal to `0` if and only if `u` is composite. If the function's input is less than `2`, then function returns an empty list (as desired). So assume the input `N` is at least `2`, and suppose `1 <= n < N`. For each `k` from `0` through `n` (inclusive), the code will check whether `n` XOR'd with `k` is composite, and it also checks whether `k` has at most two `1`'s in its binary representation. If `n^k` is composite, or if `k` has more than two `1`'s, then it moves on to the next value of `k`. If it gets through all the values of `k` from `0` through `n` this way, then it includes `n` in the list. On the other hand, if there's a value of `k` with at most two `1`'s such that `n^k` is not composite, then `n` is not included in the list. [Answer] # [Perl 6](http://perl6.org/), ~~87~~ 85 bytes ``` {grep {!grep {$_%all 2..^$_},($_ X+^grep {.base(2)~~m:g/1/ <3},^(2+<.log(2)))},2..$_} ``` Returns all such numbers that are smaller or equal to the input number. ### How it works For each number *n* from 2 to the input, it does the following: 1. ``` ^(2 +< .log(2)) ``` Generates all non-negative integers that have the same or shorter bit length than *n*. 2. ``` grep {.base(2) ~~ m:g/1/ < 3}, ``` Filters numbers from this list that have less than three bits set (using a regex). 3. ``` $_ X+^ ``` XOR's *n* with each of those numbers, yielding all valid "mutations" of *n*. 4. ``` !grep {$_ % all 2..^$_} ``` Only lets *n* be part of the output list if none of the mutations are non-composite (checked by taking each mutation *x* modulo an all-Junction of numbers between 2 and *x*-1). [Answer] # Mathematica, 115 bytes *~~1~~ 4 byte saved thanks to @MartinEnder* ``` Cases[4~Range~#,x_/;And@@CompositeQ[Fold[#+##&]/@Select[{0,1}~Tuples~BitLength@x,Tr@Abs[#-x~IntegerDigits~2]<3&]]]& (* or *) (s=Select)[4~Range~#,x๏’กAnd@@CompositeQ[Fold[#+##&]/@s[{0,1}~Tuples~BitLength@x,Tr@Abs[#-x~IntegerDigits~2]<3&]]]& ``` Very inefficient because it generates all numbers up to 2^ceil(lg(n)). Second code uses U+F4A1 (`Function` function) [Answer] # [Floroid](https://github.com/TuukkaX/Floroid), ~~95~~ 109 bytes ``` Bj:[n KnIw(j)Fp(Cao(hm("".y(k)))Mhm("".y(k))>1KkIcd("10"*Z(hi(n)),Z(hi(n)))FT(a!=b Ka,bIq(hi(n),"".y(k)))<3)] ``` Returns a list of bitflip-resistant numbers up to `input - 1`. Handles the edgy situations (0 and 1) as well. Floroid is an old language of mine, that I have used only a couple of times. Haven't touched it for a loooong time, hence the size of the program. Translates to the following Python code, which I think could be reduced with recursion. ``` lambda j:[n for n in range(j) if all( not functions.isPrime( functions.fromBinStr("".join(k))) and functions.fromBinStr("".join(k))>1for k in functions.combinations_with_replacement("10"*len( functions.pureBin(n)),len( functions.pureBin(n))) if sum (a!=b for a,b in zip( functions.pureBin(n),"".join(k)))<3)] ``` Each function used here is predefined in Floroid. [This page](https://github.com/TuukkaX/Floroid/blob/master/functions.py) contains all of the functions and their definitions. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~30~~ ~~28~~ ~~27~~ 26 bytes ``` :GBnW:qtB!s3<)!Z~tZpw~+a~f ``` [Try it online!](https://tio.run/nexus/matl#@2/l7pQXblVY4qRYbGyjqRhVVxJVUF6nnViX9v@/kYHBfwA "MATL โ€“ TIO Nexus") Outputs all bitflip-resistant composite numbers up to (and including) n. Uses ideas from both Jelly solutions - only considers 0 as a problematic non-prime; and generates a list of numbers within a distance 2 first, then takes an xor. Alternate solution, by looping (30 bytes): ``` :"@BnW:qt@Z~B!s3<)Zp1M~ha~?@D] ``` Outputs all bitflip-resistant composite numbers up to (and including) n. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~34~~ 33 bytes ``` ri{_2b,,2\f#_m*::|0+f^:mp:+!},2>p ``` Calculates all bitflip-resistant composites strictly less than *n*. Like Jonathan Allan, I'm not sure if it's actually necessary to check for 0 bitflips. If it turns out that no prime number has all of its bitflips result in composite numbers, the `0+` can be removed. [Try it online!](https://tio.run/nexus/cjam#@1@UWR1vlKSjYxSTphyfq2VlVWOgnRZnlVtgpa1Yq2NkV/D/v6WpJQA "CJam โ€“ TIO Nexus") **Explanation** ``` ri Take an integer from input (n) { Filter out all numbers in the range 0...n-1 for which the following block is false _ Duplicate the number 2b, Convert to binary, get the length , Range from 0 to length-1 2\f# Map each number in that range as a power of 2 results in all powers of 2 less than or equal to n _m* Cartesian product with itself ::| Reduce each Cartesian pair with btiwse OR results in all numbers that have 1-2 1 bits in binary 0+ Add 0 to that list f^ Bitwise XOR the number we're checking with each of these This computes all the bitflips :mp Map each result to 0 if it's prime, 1 if it's composite :+! Take the sum of the list, check if it's 0 If it is, then none of the results were prime }, (end of filter block) 2> Discard the first 2 numbers, since 0 and 1 always pass p Print the list nicely ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes *Thanks to Jonathan Allan for a correction.* ``` q:Q"@BtnFTZ^=~!s3<fqt2>)Zp~?@ ``` This takes a number *n* and outputs all bitflip-resistant composite numbers up to *n*. ### How it works [**Try it at MATL Online!**](https://matl.io/?code=q%3AQ%22%40BtnFTZ%5E%3D%7E%21s3%3Cfqt2%3E%29Zp%7E%3F%40&inputs=300&version=19.8.0) ``` q:Q % Input n implicitly. Push range [2 3 ... n] " % For each k in [2 3 ... n] @ % Push k B % Convert to binary. Gives a row vector of zeros and ones, say v tn % Duplicate. Number of elements, say m FT % Push [0 1] Z^ % Cartesian power of [0 1] raised to m. This gives a matrix, % where each row is a binary number of length m =~ % Compare with v, with broadcast !s % Sum of each row. Gives a row vector. This is the number of % bit flips 3< % True for numbers that are less than 3 bit flips away from k fq % Find their indices and subtract 1 to convert to decimal form. % This gives a vector of numbers that are less than 3 bit flips % away from k t2>) % Remove 0 or 1 Zp~ % Test each entry for non-primeness ? % If all entries are true @ % Push k % End (implicit) % Display stack (implicit) ``` ]
[Question] [ Recently I read the novel ["The Solitude of Prime Numbers"](https://en.wikipedia.org/wiki/The_Solitude_of_Prime_Numbers_(novel)) where the main characters are somewhat compared to [twin prime numbers](https://en.wikipedia.org/wiki/Twin_prime) ("*always together, but never touching*"). > > A **twin prime** is a prime number that is either \$\require{cancel}2\$ less or \$2\$ more than another prime number โ€”for example, the twin prime pair \$(41, 43)\$. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. [Wikipedia](https://en.wikipedia.org/wiki/Twin_prime) > > > Although I didn't like much the depressing novel, and since I have fallen into PPCG lately, that raised a question in my mind... ## Task: Given a positive integer number \$N > 4\$, **find the *lonely prime numbers* (AKA [isolated prime numbers](https://en.wikipedia.org/wiki/Twin_prime#Isolated_prime)) between the closest couples of twin primes**. Please note that in this case with the term *lonely prime numbers*, I mean *all the prime numbers that are not twin primes and between couples of twin primes*. That's why \$N > 4\$ because the first two couples of prime numbers are \$(3, 5)\$ and \$(5, 7)\$. ## Example: 1. \$N = 90\$. 2. Find the first two couples of twin primes \$< N\$ and \$> N\$. They are: \$(71, 73)\$ and \$(101, 103)\$. 3. Find the *lonely primes* in the range \$> 73\$ and \$< 101\$. 4. They are: \$79, 83, 89, 97\$. ## Special cases: - If N is in between two twin prime numbers, find the closest couples of twin primes \$> N+1\$ and \$< N-1\$. Example: \$N=72\$, find the closest couples of twin primes \$> 73\$ and \$< 71\$ then exclude from the list \$71\$ and \$73\$ because they are not \*lonely primes\*. So for \$N = 72\$ the expected result is: \$67, \cancel{71}, \cancel{73}, 79, 83, 89, 97\$ - If N belongs to a couple of twin primes, for example \$N = 73\$, the closest couples of twin primes are \$(71, 73)\$ and \$(101, 103)\$. If \$N = 71\$, the closest couples of twin primes are \$(59, 61)\$ and \$(71, 73)\$. ## Test cases: ``` N = 70 > Lonely primes are: 67 N = 71 > Lonely primes are: 67 N = 72 > Lonely primes are: 67, 79, 83, 89, 97 (not the twins 71 and 73) N = 73 > Lonely primes are: 79, 83, 89, 97 N = 90 > Lonely primes are: 79, 83, 89, 97 N = 201 > Lonely primes are: 211, 223 N = 499 > Lonely primes are: 467, 479, 487, 491, 499, 503, 509 ``` ## Rules: * Write a full program or function that will take the number N from standard input. * Output the list of *lonely primes* in a readable format as csv, list, array, etc. * Shortest code wins. * Please include (when possible) a testable online fiddle. [Answer] ## PowerShell v2+, ~~237~~ ~~149~~ ~~147~~ ~~231~~ ~~216~~ ~~181~~ ~~174~~ ~~169~~ 166 bytes ``` param($n)filter f($a){'1'*$a-match'^(?!(..+)\1+$)..'}for($i=$n;!((f $i)-and(f($i+2)))){$i++}for(){if(f(--$i)){if((f($i-2))-or(f($i+2))){if($i-lt$n-1){exit}}else{$i}}} ``` Takes input `$n`. Defines a new function `f` as the [regex prime function](https://codegolf.stackexchange.com/a/57636/42963) (here returning a Boolean if the input is a prime or not). The next part sets `$i` to be equal to `$n`, then loops upward until we find the *bottom* half of our twin prime pair upper bound. E.g., for input `90`, this stops at `$i=101`. Then, we loop from the upper bound downward. I know, it looks like an infinite loop, but it'll eventually end. If the current number is a prime (`f(--$i)`), *but* its `+/- 2` *isn't* a prime, we add `$i` to the pipeline. However, if its `+/- 2` is a prime, we check whether we're lower than `$n-1` (i.e., to account for the situation when it's inside a twin prime pair), at which point we `exit`. At program completion, the pipeline is printed to screen via implicit `Write-Output`. *NB - Due to the looping structure, prints the primes in descending order. OP has clarified that's OK.* ### Examples *Output here is space-separated, as that's the default stringification method for an array.* ``` PS C:\Tools\Scripts\golfing> 70,71,72,73,90,201,499,982|%{"$_ --> "+(.\the-solitude-of-prime-numbers.ps1 $_)} 70 --> 67 71 --> 67 72 --> 97 89 83 79 67 73 --> 97 89 83 79 90 --> 97 89 83 79 201 --> 223 211 499 --> 509 503 499 491 487 479 467 982 --> 1013 1009 997 991 983 977 971 967 953 947 941 937 929 919 911 907 887 ``` [Answer] # Haskell, 105 bytes ``` p x=all((>0).mod x)[2..x-1] a%x=until(\z->p z&&p(z+2*a))(+a)x f n=[x|x<-[(-1)%n+1..1%n-1],p x,1%x>x,(-1)%x<x] ``` [Try it Online](https://ideone.com/fork/8bWtai "Try it Online") [Answer] # JavaScript, ~~186~~ ~~183~~ ~~168~~ 158 Bytes ``` // solution: function d(d){function p(n){for(i=n;n%--i;);return!--i}u=d;for(;!p(d--)||!p(--d););for(;!p(u++)||!p(++u););for(;++d<u;)if(p(d)&&!p(d-2)&&!p(d+2))console.log(d)} // runnable test cases: console.info('Test ' + 70); d(70); console.info('Test ' + 71); d(71); console.info('Test ' + 72); d(72); console.info('Test ' + 73); d(73); console.info('Test ' + 90); d(90); console.info('Test ' + 201); d(201); console.info('Test ' + 499); d(499); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 27 bytes ``` ร†Rf+ยฅ2แนชรฆRร†n+2แบ’ยฌฦŠยฟรฐ_;+แบ’แบธยตรแธŸ2 ``` [Try it online!](https://tio.run/##y0rNyan8//9wW1Ca9qGlRg93rjq8LOhwW5620cNdkw6tOdZ1aP/hDfHW2kDew107Dm09POHhjvlG/3UOtx@d9HDnDBVvzcj//80NdBTMDYHYCIiNdRQsgXwjA6CAiaUlAA "Jelly โ€“ Try It Online") -2 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) ## How it works ``` ร†Rf+ยฅ2แนชรฆRร†n+2แบ’ยฌฦŠยฟรฐ_;+แบ’แบธยตรแธŸ2 - Main link. Takes N on the left ร†R - Yield all primes โ‰ค N; Z ยฅ2 - Group the previous 2 links into a dyad f(Z, 2): + - Add 2 to each element in Z f - Keep all elements in both Z and Z+2 แนช - Take the last number This is the largest twin prime < N, T ยฟ - While loop: ฦŠ - Condition f(X): +2 - X+2 ยฌ - Is not: แบ’ - Prime ร†n - Body: X is the next prime after X รฆR - Prime range; Yield a list of primes T โ‰ค P โ‰ค X รฐ ยต 2 - Define a dyadic chain f(P, 2): _ - P-2 + - P+2 ; - [P-2, P+2] แบ’ - Test if each is prime แบธ - Are either true? รแธŸ - Filter the range T โ‰ค P โ‰ค X, keeping those for which f(P, 2) is false ``` [Answer] # Actually, 47 bytes This solution deals with the case where `n` is between two twin primes, by checking if the **lower bound** is the **larger** of a pair of twin primes (eliminating the twin prime to the left of us from being our lower bound) and if the **upper bound** is the **smaller** of a pair of twin primes (eliminating the twin prime to the right of us from being our upper bound). To prevent the twin primes from being included in our range once we have the lower and upper bounds, we need to remove primes `p` where `p-2` OR `p+2` are prime, hence the logical OR and negate in the code. This is a little long and can probably be golfed further. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWXMWDilZwrO-KMkHBAcCZg4pWTRuKVnCsxYOKVnC07wqxwQHAmYOKVk0bilZwteGA7O8KscEDijJBwfFlAcCZg4paR&input=NDk5) ``` โ•—1`โ•œ+;โŒp@p&`โ•“Fโ•œ+1`โ•œ-;ยฌp@p&`โ•“Fโ•œ-x`;;ยฌp@โŒp|Y@p&`โ–‘ ``` **Ungolfing** ``` โ•— Store implicit input n in register 0. 1`...`โ•“ Get the first value x for which the following function f returns a truthy value. โ•œ Push n from register 0. + Add x to n. ;โŒ Duplicate n+x and add 2 to a copy of n+x. p Check if n+x+2 is prime. @p Swap n+x to TOS and check if n+x is prime. & Logical AND the two results. F Push the first (and only) result of previous filtering โ•œ+ Add that result to n to get the upper bound for our solitude. 1`...`โ•“ Get the first value x for which the following function f returns a truthy value. โ•œ Push n from register 0. - Subtract x from n. ;ยฌ Duplicate n-x and subtract 2 from a copy of n-x. p Check if n-x-2 is prime. @p Swap n-x to TOS and check if n-x is prime. & Logical AND the two results. F Push the first (and only) result of previous filtering. โ•œ- Subtract that result from n to get the lower bound for our solitude. x`...`โ–‘ Push values of the range [a...b] where f returns a truthy value. Variable m. ;; Duplicate m twice. ยฌp Check if m-2 is prime. @โŒp Check if m+2 is prime. |Y Logical OR the results and negate. This eliminates any numbers with neighboring primes. @p Check if m is prime. & Logical AND primality_check(m) and the previous negation. This keeps every other prime number in the range. ``` [Answer] # PHP, 207 bytes ~~47~~ 54 bytes for the `is_prime` function that PHP does not have. Iยดd beat Mathematica without that. :-D ``` function p($n){for($i=$n>1?$n:4;$n%--$i;);return$i<2;}if(p($n=$argv[1])&p($n+2)|$z=p($n-1)&p($n+1))$n-=2;for($n|=1;!p($n)|!p($n-2);$n--);for($z++;$z--;$n+=2)for(;$n+=2;)if(p($n)){if(p($n+2))break;echo"$n,";} ``` run with `-r`. prints a trailing comma. **breakdown** ``` // is_prime function: // loops from $n-1 down to 1, breaks if it finds a divisor. // returns true if divisor is <2 (==1) // special case $n==1: initialize $i=4 to prevent warnings function p($n){for($i=$n>1?$n:4;$n%--$i;);return$i<2;} // is $n between primes? if($z=p(1+$n=$argv[1])&p($n-1)) // set $z to go to the _second_ twin pair above $n-=2; // no: else if(p($n)&p($n+2))$n-=2; // $n is part of the upper pair // p($n)&p($n-2): // $n is part of the lower pair // else: // this is a lonely (isolated) prime // 1. find closest twins <=$n for($n|=1;!p($n)|!p($n-2);$n--); // 2. list primes until the next twin primes L: for(;$n+=2;)if(p($n)) if(p($n+2))break; // next twin primes found: break loop else echo"$n,"; // isolated prime: print // 3. if ($z) repeat (once) $n+=2; // skip twin pair if($z--)goto L; ``` **Note**: The `is_prime` function actually returns `true` for `$n<2`; but at least it doesnยดt produce a warning. Insert `$n=` before `$n>1` to fix. [Answer] # Mathematica, ~~169~~ 157 bytes ``` Select[PrimeQ]@Sort@Flatten@{If[q@#,0,#],Most@NestWhileList[i-=2;#+i&,#,!q@#&]&/@(i=3;q=PrimeQ@#&&Or@@PrimeQ[{2,-2}+#]&;#+{1,-1}(1+Boole@PrimeQ[{1,-1}+#]))}& ``` [Answer] ## Racket 228 bytes ``` (ฮป(n)(let*((t 0)(lr(ฮป(l i)(list-ref l i)))(pl(drop(reverse(for/list((i(in-naturals))#:when(prime? i)#:final(and(> i n) (= 2(- i t))))(set! t i)i))2)))(for/list((i(length pl))#:break(= 2(-(lr pl i)(lr pl(add1 i)))))(lr pl i)))) ``` Disadvantage of this version is that it finds all prime numbers till N and not just those around N. Ungolfed version: ``` (define (f n) (let* ((t 0) (lr (ฮป(l i) (list-ref l i))) (pl (drop(reverse (for/list ((i (in-naturals)) #:when (prime? i) #:final (and (> i n) (= 2 (- i t)))) (set! t i) i)) 2))) (for/list ((i (length pl)) #:break (= 2 (- (lr pl i) (lr pl (add1 i)))) ) (lr pl i))) ) ``` Testing: ``` (f 90) ``` Output: ``` '(97 89 83 79) ``` [Answer] ## Racket 245 bytes ``` (ฮป(n)(let((pl(reverse(let lp((n n)(t 0)(ol '()))(set! t(prev-prime n))(if(and(>(length ol)0) (= 2(-(car ol)t)))(cdr ol)(lp t 0(cons t ol)))))))(let lq((n n)(t 0)(ol pl))(set! t(next-prime n)) (if(= 2(- t(car ol)))(cdr ol)(lq t 0(cons t ol)))))) ``` Ungolfed version: ``` (require math) (define f (lambda(n) (let ((pl (reverse (let loop ((n n) (t 0) (ol '())) (set! t (prev-prime n)) (if (and (> (length ol) 0) (= 2 (- (car ol) t))) (cdr ol) (loop t 0 (cons t ol))))))) (let loop2 ((n n) (t 0) (ol pl)) (set! t (next-prime n)) (if (= 2 (- t (car ol))) (cdr ol) (loop2 t 0 (cons t ol)))))) ) (f 90) ``` Output: ``` '(97 89 83 79) ``` [Answer] # Python 2.7: 160 bytes ``` t=lambda n:all(n%d for d in range(2,n)) def l(n): i=n while t(i)*t(i+2)-1:i+=1 while t(n)*t(n-2)-1:n-=1 print[x for x in range(n,i)if t(x)&~(t(x-2)|t(x+2))] ``` suggestions are welcome :) ]
[Question] [ The world is a five by five array of cells. **It wraps on all sides.** It can be visualized like... ``` XXXXX XXXXX XXOXX XXXXX XXXXX ``` You are an O. You love to travel the world, and you do so according to the following rules (let C be the current day): * On [prime](https://en.wikipedia.org/wiki/Prime_number) days, you feel nostalgic. Return to where you started yesterday. * On [odd](https://en.wikipedia.org/wiki/Parity_(mathematics)) days, you feel homesick. Move one horizontal step closer to home, if possible, and one vertical step closer to home, if possible. Ignore world wrapping for the purpose determining closeness. * On [even](https://en.wikipedia.org/wiki/Parity_(mathematics)) days, you feel adventurous. Move C / 2 steps south. * On [square](https://en.wikipedia.org/wiki/Square_number) days, you feel adventurous. Move to the east wall. * On [Fibonacci](https://en.wikipedia.org/wiki/Fibonacci_number) days, the world expands southward by one row. * On [triangular](https://en.wikipedia.org/wiki/Triangular_number) days, the world expands eastward by one column. If two or more of the above rules would apply at the same time, apply them in the order listed. For example, on an odd prime day, first return to where you started yesterday, and then move one step closer to home. You live at the center of the (initial) world, i.e. position (2,2), zero-indexed from the Northwest corner. You begin your journey there on day one. **Input** A single integer, N. **Output** Your X and Y coordinate on the Nth day, zero-indexed from the Northwest corner, separated by a single space. **Test Case With Explanation** Given an input of `3`, the correct output is: ``` 2 3 ``` We can work through this one day at a time. Starting on day 1, we need to apply the following moves: 1. Odd, square, Fibonacci, and triangular 2. Prime, even, and Fibonacci 3. Prime, odd, Fibonacci, and triangular In visual form: ``` Day 1 Day 2 Day 3 XXXXX XXXXXX XXXXXX XXXXXXX XXXXX XXXXXX XXXXXX XXXXXXX XXOXX -> XXXXOX -> XXXXXX -> XXXOXXX XXXXX XXXXXX XXOXXX XXXXXXX XXXXX XXXXXX XXXXXX XXXXXXX XXXXXX XXXXXX XXXXXXX XXXXXX XXXXXXX XXXXXXX ``` **Additional Test Cases** Courtesy of [Martin Bรผttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner)'s [reference solution](http://goo.gl/fosKCS) (please note that you should output only a single coordinate, not all of them): ``` Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Output: 4 2 2 3 3 2 6 4 2 2 2 5 2 2 2 6 7 5 7 0 6 4 6 0 5 3 5 10 4 9 9 6 3 8 3 6 2 7 2 6 2 5 2 4 2 4 ``` This is code golf. The shortest submission wins. [Answer] # Haskell, 394 bytes ``` z=0<1 p d y c|all((0<).mod d)[2..d-1]=y|z=c g x=x-signum(x-2) e d(x,y)h|odd d=(g x,g y)|z=(x,mod(y+div d 2)h) s d c@(_,y)w|d==(floor$sqrt$fromIntegral d)^2=(w-1,y)|z=c f d a b m|b>d=m|b==d=(+1)<$>m|z=f d b(a+b)m d%m@(w,h)|elem d[div(n*n-n)2|n<-[1..d+1]]=(w+1,h)|z=m i=fst.c j=snd.c c d|d<1=((2,2),(5,5))|z=(s d(e d(p d(i$d-2)$i$d-1)$snd$j$d-1)$fst$j$d-1,d%(f d 1 1$j$d-1)) main=readLn>>=print.i ``` It can definitely be optimised and also after quickly checking for correctness ~~it looks like I'm getting different results than the one posted~~. I'll come back and check more thoroughly my code when I have more time ^^ Nice problem by the way! EDIT: edited my solution taking into account the precious advice given by [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb). It now works perfectly! EDIT2: thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) I have made the code even smaller. I am now also doing the checks for even and odd in one function instead of two which overall decreases the count from 446 to 414 bytes. EDIT3: further improved from 414 to 400 bytes. Thanks [nimi](https://codegolf.stackexchange.com/users/34531/nimi) for another 2 bytes, you're on fire! :) EDIT4: 4 more bytes by [nimi](https://codegolf.stackexchange.com/users/34531/nimi) :) [Answer] # C, ~~425~~ 396 bytes ``` typedef struct{int x,y,b,r}c;S,p,n;s(d){return(S=sqrt(d))*S==d;}c m(d){if(!d)return(c){2,2,4,4};c q,l=m(d-1);for(p=1,n=d;--n;p=p*n*n%d);if(p&&d>1)q=m(d-2),l.x=q.x,l.y=q.y;if(d%2)l.x-=l.x>2?1:l.x<2?-1:0,l.y-=l.y>2?1:l.y<2?-1:0;else l.y+=d/2,l.y=l.y>l.b?l.y-l.b-1:l.y;if(s(d))l.x=l.r;if(s(5*d*d+4)||s(5*d*d-4))l.b++;if(s(8*d+1))l.r++;return l;}main(i){scanf("%d",&i);printf("%d %d",m(i).x,m(i).y);} ``` There are parts to this that could be improved, but [it works for the test cases](https://ideone.com/hTWT1t). --- ## Explanation ``` typedef struct { int x,y,b,r } c; //c will hold the information for each day //determines if a number is a perfect square S,p,n; s(d) { return (S=sqrt(d))*S==d; } c m(d) { if(!d) return (c){2,2,4,4}; //returns the initial information if the day is 0 c q,l=m(d-1); //gets the information for the previous day for (p=1,n=d;--n;p=p*n*n%d); //tests if the number is prime if (p&&d>1) q=m(d-2),l.x=q.x,l.y=q.y; //changes the position to what it was at the end of the day 2 days ago if the day is prime if (d%2) l.x-=l.x>2?1:l.x<2?-1:0,l.y-=l.y>2?1:l.y<2?-1:0; //moves the position towards (2,2) if the day is odd else l.y+=d/2,l.y=l.y>l.b?l.y-l.b-1:l.y; //moves down if the day is even if (s(d)) l.x=l.r; //moves east if the day is a perfect square if (s(5*d*d+4)||s(5*d*d-4)) l.b++; //expands world down if the day is a fibonacci number if (s(8*d+1)) l.r++; //expands world right if the day is a triangular number return l; } main(i) { scanf("%d",&i); printf("%d %d",m(i).x,m(i).y); } ``` [Answer] ## Pyth, ~~157~~ ~~156~~ 153 bytes ``` =Z=b5aYA,2 2FNtUhQI&!tPN<1NA@Y_2)Iq*2/N2NA,G%+H/N2b)EL-+b<b2<2bAyM,GH)J@N2Iq/NJJA,tZH)=TU2W<hTNIqNeT=hbBE=TX_T1sT))=J0W!<NJIqN/*JhJ2=hZBE=hJ))aY(GH;jd,GH ``` [You can try it out here.](https://pyth.herokuapp.com/?code=%3DZ%3Db5aYA%2C2+2FNtUhQI%26%21tPN%3C1NA%40Y_2%29Iq%2a2%2FN2NA%2CG%25%2BH%2FN2b%29EL-%2Bb%3Cb2%3C2bAyM%2CGH%29J%40N2Iq%2FNJJA%2CtZH%29%3DTU2W%3ChTNIqNeT%3DhbBE%3DTX_T1sT%29%29%3DJ0W%21%3CNJIqN%2F%2aJhJ2%3DhZBE%3DhJ%29%29aY%28GH%3Bjd%2CGH&input=15&debug=0) This was a fun problem to golf! I'm still getting used to Pyth, but it's a really great language. [Answer] # Perl 5, 284 bytes ``` @s=([2,2]);@n=(2,2);@f=(0,1);$w=$h=5;for(1..<>){$f[$_+1]=$f[$_]+$f[$_-1];$t[$_]=$_*($_+1)/2;$s[$_]=[@n];@n=@{$s[$_-1]}if(1 x$_)!~/^1$|^(11+?)\1+$/;($_%2)&&($n[0]-=($n[0]<=>2),$n[1]-=($n[1]<=>2))or$n[1]=($n[1]+$_/2)%$h;$n[0]=$w-1if(int sqrt$_)**2==$_;$h++if$_~~@f;$w++if$_~~@t}say"@n" ``` 283 bytes, plus 1 for `-E` flag instead of `-e` Same code but with more whitespace, more parentheses, and longer variable names: ``` @start=([2,2]); @now=(2,2); @fibonacci=(0,1); $width = ($height=5); for my $iterator (1 .. <>) { $fibonacci[$iterator+1] = $fibonacci[$iterator] + $fibonacci[$iterator-1]; $triangular[$iterator] = $iterator * ($iterator+1) / 2; $start[$iterator] = [@now]; @now = @{ $start[$iterator-1] } if ((1 x $iterator) !~ /^1$|^(11+?)\1+$/); # prime $now[0] -= ($now[0] <=> 2) , $now[1] -= ($now[1] <=> 2) if ($iterator % 2 != 0); # odd $now[1] = ($now[1] + $iterator / 2) % $height if ($iterator % 2 == 0); # even $now[0] = $width - 1 if ((int sqrt $iterator) ** 2 == $iterator); # square $height ++ if $iterator ~~ @fibonacci; $width ++ if $iterator ~~ @triangular; } say "@now"; ``` I am confident that this can be golfed further. [Answer] # Javascript, 361 359 bytes ``` N=>{for(c=1,x=y=v=w=j=k=2,h=z=5;c<=N;c++,j=v,k=w,v=x,w=y){m=Math;p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0;[x,y]=c==2||p(c,2)&&c!=1?[j,k]:[x,y];p=x=>x+(x<2?1:x>2?-1:0);c%2?[x,y]=[p(x),p(y)]:y+=c/2;m.sqrt(c)==~~m.sqrt(c)?x=z-1:0;f=(n,c,d)=>d<c?0:d==c?1:f(c,n+c,d);f(1,2,c)||c==1?h++:0;t=(n,c)=>n*++n/2==c?1:--n*n/2>c?0:t(++n,c);t(1,c)?z++:0;x%=z;y%=h}return x+" "+y} ``` The code use [Destructuring assignment](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). It's only supported in Firefox and Safari right now. ## Explanation ``` N=>{ // C => the day, x,y => position, v,w => position at the start of the day, // j,k => position of yesterday for(c=1,x=y=v=w=j=k=2,h=z=5;c<=N;c++,j=v,k=w,v=x,w=y){ m=Math; // Prime Function for C > 2. Recursive call to save a loop. p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0; // Assign x and y to yesterday [x,y]=c==2||p(c,2)&&c!=1?[j,k]:[x,y]; // Function to move closer to home p=x=>x+(x<2?1:x>2?-1:0); c%2?[x,y]=[p(x),p(y)]:y+=c/2; // Square check m.sqrt(c)==~~m.sqrt(c)?x=z-1:0; // Fibonnacci function for C > 1 f=(n,c,d)=>d<c?0:d==c?1:f(c,n+c,d); f(1,2,c)||c==1?h++:0; // Triangle function t=(n,c)=>n*++n/2==c?1:--n*n/2>c?0:t(++n,c); t(1,c)?z++:0; // Stay in bounds x%=z;y%=h } // Output return x+" "+y} ``` ]
[Question] [ Given an array of any depth, draw its contents with borders of `+-|` around each subarray. Those are the ASCII characters for plus, minus, and vertical pipe. For example, if the array is `[1, 2, 3]`, draw ``` +-----+ |1 2 3| +-----+ ``` For a nested array such as `[[1, 2, 3], [4, 5], [6, 7, 8]]`, draw ``` +-----------------+ |+-----+---+-----+| ||1 2 3|4 5|6 7 8|| |+-----+---+-----+| +-----------------+ ``` For a ragged array such as `[[[1, 2, 3], [4, 5]], [6, 7, 8]]`, draw ``` +-------------------+ |+-----------+-----+| ||+-----+---+|6 7 8|| |||1 2 3|4 5|| || ||+-----+---+| || |+-----------+-----+| +-------------------+ ``` Notice that there is more space after drawing `[6, 7, 8]`. You may either draw the contents on the top-most, center, or bottom-most line, but whichever you choose, you must remain consistent. This challenge was inspired by the [box](http://www.jsoftware.com/help/dictionary/d010.htm) verb `<` from J. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. * Builtins that solve this are not allowed. * The input array will contain only nonnegative integer values or arrays. Each array will be homogenous, meaning that its elements will either by only arrays or only integers, but never a mix of both. * Each subarray may be nested to any depth. * The output may either by as a string or as an array of strings where each string is a line of output. ## Test Cases ``` [] ++ || ++ [[], []] +---+ |+++| ||||| |+++| +---+ [[], [1], [], [2], [], [3], []] +-----------+ |++-++-++-++| |||1||2||3||| |++-++-++-++| +-----------+ [[[[[0]]]]] +---------+ |+-------+| ||+-----+|| |||+---+||| ||||+-+|||| |||||0||||| ||||+-+|||| |||+---+||| ||+-----+|| |+-------+| +---------+ [[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]] +---------------------------------+ |+-------------+---------+-----+-+| ||+-----------+|+-------+|+---+|1|| |||+---------+|||+-----+|||2 1|| || ||||+-------+|||||3 2 1|||+---+| || |||||4 3 2 1|||||+-----+|| | || ||||+-------+|||+-------+| | || |||+---------+|| | | || ||+-----------+| | | || |+-------------+---------+-----+-+| +---------------------------------+ ``` [Answer] ## JavaScript (ES6), ~~223~~ 203 bytes ``` f=(a,g=a=>a[0].map?`<${a.map(g).join`|`}>`:a.join` `,s=g([a]),r=[s],t=s.replace(/<[ -9|]*>|[ -9]/g,s=>s[1]?s.replace(/./g,c=>c>`9`?`+`:`-`):` `))=>t<`+`?r.join`\n`.replace(/<|>/g,`|`):f(a,g,t,[t,...r,t]) ``` Port of @MitchSchwartz's Ruby solution. Previous version which worked by recursively wrapping the arrays (and therefore worked for arbitrary content, not just integers): ``` f=(...a)=>a[0]&&a[0].map?[s=`+${(a=a.map(a=>f(...a))).map(a=>a[0].replace(/./g,`-`)).join`+`}+`,...[...Array(Math.max(...a.map(a=>a.length)))].map((_,i)=>`|${a.map(a=>a[i]||a[0].replace(/./g,` `)).join`|`}|`),s]:[a.join` `] ``` Note: Although I'm using the spread operator in my argument list, to obtain the desired output, provide a single parameter of the original array rather then trying to spread the array; this has the effect of wrapping the output in the desired outer box. Sadly the outer box costs me 18 bytes, and space-separating the integers costs me 8 bytes, otherwise the following alternative visualisation would suffice for 197 bytes: ``` f=a=>a.map?[s=`+${(a=a.map(f)).map(a=>a[0].replace(/./g,`-`)).join`+`}+`,...[...Array(Math.max(0,...a.map(a=>a.length)))].map((_,i)=>`|${a.map(a=>a[i]||a[0].replace(/./g,` `)).join`|`}|`),s]:[``+a] ``` [Answer] # [Dyalog APL](http://dyalog.com/download-zone.htm), 56 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Thanks to ngn for helping removing about a third of the bytes. ``` {โตโ‰กโˆŠโต:โ‰โชโ‰โ•โตโ‹„(โŠข,โŠฃ/)โŠƒ,/(1โŠ–('++','|'โดโจโ‰ข),'-'โชโฃ2โ†‘)ยจโ†“โ†‘โ†“ยจโˆ‡ยจโต}โŠ‚ ``` ### TryAPL [Define the function](http://tryapl.org/?a=f%u2190%7B%u2375%u2261%u220A%u2375%3A%u2349%u236A%u2349%u2355%u2375%u22C4%28%u22A2%2C%u22A3/%29%u2283%2C/%281%u2296%28%27++%27%2C%27%7C%27%u2374%u2368%u2262%29%2C%27-%27%u236A%u23632%u2191%29%A8%u2193%u2191%u2193%A8%u2207%A8%u2375%7D%u2282&run), then run each test case and compare to the built-in `]Display` utility. [`[1, 2, 3]`](http://tryapl.org/?a=%5Ddisplay%20a%u21901%202%203%20%u22C4%20f%20a&run) [`[[1, 2, 3], [4, 5], [6, 7, 8]]`](http://tryapl.org/?a=%5Ddisplay%20a%u2190%281%202%203%29%284%205%29%286%207%208%29%20%u22C4%20f%20a&run) [`[[[1, 2, 3], [4, 5]], [6, 7, 8]]`](http://tryapl.org/?a=%5Ddisplay%20a%u2190%28%281%202%203%29%284%205%29%29%286%207%208%29%20%u22C4%20f%20a&run) [`[]`](http://tryapl.org/?a=%5Ddisplay%20%u236C%20%u22C4%20f%u236C&run) [`[[], []]`](http://tryapl.org/?a=%5Ddisplay%20%u236C%u236C%20%u22C4%20f%u236C%u236C&run) [`[[], [1], [], [2], [], [3], []]`](http://tryapl.org/?a=%5Ddisplay%20a%u2190%u236C%28%2C1%29%u236C%28%2C2%29%u236C%28%2C3%29%u236C%20%u22C4%20f%20a&run) [`[[[[[0]]]]]`](http://tryapl.org/?a=%5DDisplay%20a%u2190%u2282%u2282%u2282%u2282%2C0%20%u22C4%20f%20a&run) [`[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]]`](http://tryapl.org/?a=%5DDisplay%20a%u2190%28%u2282%u2282%u22824%203%202%201%29%28%u2282%u22823%202%201%29%28%u22822%201%29%28%2C1%29%20%u22C4%20f%20a&run) # Explanation Overall, this is an anonymous function `{...}` atop an enclose `โŠ‚`. The latter just adds another level of nesting prompting the former to add an outer frame. The anonymous function with white-space (`โ‹„` is the statement separator): ``` { โต โ‰ก โˆŠโต: โ‰ โช โ‰ โ• โต (โŠข , โŠฃ/) โŠƒ ,/ (1 โŠ– ('++' , '|' โดโจ โ‰ข) , '-' โชโฃ2 โ†‘)ยจ โ†“ โ†‘ โ†“ยจ โˆ‡ยจ โต } ``` Here it is again, but with separated utility functions: ``` CloseBox โ† โŠข , โŠฃ/ CreateVertical โ† '++' , '|' โดโจ โ‰ข AddHorizontals โ† 1 โŠ– CreateVertical , '-' โชโฃ2 โ†‘ { โต โ‰ก โˆŠโต: โ‰ โช โ‰ โ• โต CloseBox โŠƒ ,/ AddHorizontalsยจ โ†“ โ†‘ โ†“ยจ โˆ‡ยจ โต } ``` Now let me explain each function: `CloseBox` takes a table and returns the same table, but with the table's first column appended on the right of the table. Thus, given the 1-by-3 table `XYZ`, this function returns the 1-by-4 table `XYZX`, as follows: โ€ƒ`โŠข`โ€ƒthe argument (lit. what is on the right) โ€ƒ`,`โ€ƒprepended to โ€ƒ`โŠฃ/`โ€ƒthe leftmost column (lit. the left-reduction of each row) `CreateVertical` takes a table and returns the a string consisting of the characters which would fit `|`s on the sides of the table, but with two `+`s prepended to match two rows of `-`. Eventually the table will be cyclically rotated one row to get a single `+---...` row above and below. Thus, given any three row table, this function returns `++|||`, as follows: โ€ƒ`'++' ,`โ€ƒtwo pluses prepended to โ€ƒ`'|' โดโจ`โ€ƒa stile reshaped by โ€ƒ`โ‰ข`โ€ƒthe (rows') tally of the argument `AddHorizontals` takes a list-of-lists, makes it into a table, adds two rows of `-`s on top, adds the corresponding left edge characters on the left, then rotates one row to the bottom, so that the table has a border on the top, left, and bottom. As follows: โ€ƒ`1 โŠ–`โ€ƒrotate one row (the top row goes to the bottom) of โ€ƒ`CreateVertical ,`โ€ƒthe string `++|||...` prepended (as a column) to โ€ƒ`'-' โชโฃ2`โ€ƒminus added twice to the top of โ€ƒ`โ†‘`โ€ƒthe argument transformed from list-of-lists to table `{`The anonymous function`}`: If the argument is a simple (not nested) list, make it into a character table (thus, given the 3-element list `1 2 3`, this function returns the visually identical 1-by-five character table `1 2 3`). If the argument is not a simple list, ensure the elements are simple character tables; pad them to equal height; frame each on their top, bottom, and left; combine them; and finally take the very first column and add it on the right. As follows: โ€ƒ`{`โ€ƒbegin the definition of an anonymous function โ€ƒโ€ƒ`โต โ‰ก โˆŠโต:` if the argument is identical to the flattened argument (i.e. it is a simple list), then: โ€ƒโ€ƒโ€ƒ`โ‰`โ€ƒtranspose the โ€ƒโ€ƒโ€ƒ`โช`โ€ƒcolumnized โ€ƒโ€ƒโ€ƒ`โ‰`โ€ƒtransposed โ€ƒโ€ƒโ€ƒ`โ• โต`โ€ƒstringified argument; else: โ€ƒโ€ƒ`CloseBox`โ€ƒAdd the leftmost column to the right of โ€ƒโ€ƒ`โŠƒ ,/`โ€ƒthe disclosed (because reduction encloses) concatenated-across โ€ƒโ€ƒ`AddHorizontalsยจ`โ€ƒadd `-`s on top and bottom of each of โ€ƒโ€ƒ`โ†“ โ†‘ โ†“ยจ`โ€ƒthe padded-to-equal-height\* of โ€ƒโ€ƒ`โˆ‡ยจ โต`โ€ƒ this anonymous function applied to each of the arguments โ€ƒ`}`โ€ƒend the definition of the anonymous function \* Lit. make each table into a list-of-lists, combine the lists-of-lists (padding with empty strings to fill short rows) into a table, then split the table into a list of lists-of-lists [Answer] ## Brainfuck, 423 bytes ``` ->>+>>,[[>+>+<<-]+++++[>--------<-]>[<+>-[[-]<-]]>[[-]<<[>>>>+<<<<<<-<[>-<-]>>>- ]<<<[-<<<<<<-<]>+>>>]<<<[>>+>>>>>+<<<<<<<-]>>>>>>>>>,]<<+[<<,++>[-[>++<,<+[--<<< <<<<+]>]]<[-<+]->>>>[<++<<[>>>>>>>+<<<<<<<-]>>>-[<++>-[>>>>+<<<<<++<]<[<<]>]<[>> +<<<<]>>>+>+>[<<<-<]<[<<]>>>>->+>[-[<-<-[-[<]<[<++<<]>]<[<++++<<]>]<[>+<-[.<<<,< ]<[<<]]>]<[-<<<<<]>>[-[<+>---[<<++>>+[--[-[<+++++++<++>>,]]]]]<+++[<+++++++++++> -]<-.,>>]>>>>+>>>>]<<-] ``` Formatted with some comments: ``` ->>+>>, [ [>+>+<<-] +++++[>--------<-] > [ not open paren <+>- [ not paren [-]<- ] ] > [ paren [-] << [ close paren >>>>+<<<< <<-<[>-<-]>>> - ] <<< [ open paren directly after close paren -<<<<<<-< ] >+>>> ] <<<[>>+>>>>>+<<<<<<<-]>>> >>>>>>, ] <<+ [ <<,++> [ - [ >++< ,<+[--<<<<<<<+] > ] ] <[-<+] ->>>> [ <++<<[>>>>>>>+<<<<<<<-]>>>- [ at or before border <++>- [ before border >>>>+<<<< <++< ] <[<<] > ] < [ after border >>+<< << ] >>>+>+> [ column with digit or space <<<-< ] <[<<] >>>>->+> [ middle or bottom - [ bottom <-<- [ at or before border - [ before border < ] < [ at border <++<< ] > ] < [ after border <++++<< ] > ] < [ middle >+< -[.<<<,<] <[<<] ] > ] <[-<<<<<] >> [ border char or space - [ not space <+>--- [ not plus <<++>> + [ -- [ - [ pipe <+++++++<++>>, ] ] ] ] ] <+++[<+++++++++++>-]<-.,>> ] > >>>+>>>> ] <<- ] ``` [Try it online.](http://brainfuck.tryitonline.net/#code=LT4-Kz4-LFtbPis-Kzw8LV0rKysrK1s-LS0tLS0tLS08LV0-WzwrPi1bWy1dPC1dXT5bWy1dPDxbPj4-Pis8PDw8PDwtPFs-LTwtXT4-Pi1dPDw8Wy08PDw8PDwtPF0-Kz4-Pl08PDxbPj4rPj4-Pj4rPDw8PDw8PC1dPj4-Pj4-Pj4-LF08PCtbPDwsKys-Wy1bPisrPCw8K1stLTw8PDw8PDwrXT5dXTxbLTwrXS0-Pj4-WzwrKzw8Wz4-Pj4-Pj4rPDw8PDw8PC1dPj4-LVs8Kys-LVs-Pj4-Kzw8PDw8Kys8XTxbPDxdPl08Wz4-Kzw8PDxdPj4-Kz4rPls8PDwtPF08Wzw8XT4-Pj4tPis-Wy1bPC08LVstWzxdPFs8Kys8PF0-XTxbPCsrKys8PF0-XTxbPis8LVsuPDw8LDxdPFs8PF1dPl08Wy08PDw8PF0-PlstWzwrPi0tLVs8PCsrPj4rWy0tWy1bPCsrKysrKys8Kys-PixdXV1dXTwrKytbPCsrKysrKysrKysrPi1dPC0uLD4-XT4-Pj4rPj4-Pl08PC1d&input=KCgoKCg0IDMgMiAxKSkpKSgoKDMgMiAxKSkpKCgyIDEpKSgxKSkK) Expects input formatted like `(((((4 3 2 1))))(((3 2 1)))((2 1))(1))` with a trailing newline, and produces output of the form: ``` +---------------------------------+ |+-------------+---------+-----+-+| ||+-----------+|+-------+|+---+| || |||+---------+|||+-----+||| || || ||||+-------+||||| |||| || || |||||4 3 2 1||||||3 2 1||||2 1||1|| ||||+-------+||||| |||| || || |||+---------+|||+-----+||| || || ||+-----------+|+-------+|+---+| || |+-------------+---------+-----+-+| +---------------------------------+ ``` The basic idea is to calculate which character to print based on the depth of nesting. The output format is such that the row index of a box's top border is equal to the corresponding array's depth, with symmetry across the middle row. The tape is divided into 7-cell nodes, with each node representing a column in the output. The first loop consumes the input and initializes the nodes, keeping track of depth and whether the column corresponds to a parenthesis (i.e., whether the column contains a vertical border), and collapsing occurrences of `)(` into single nodes. The next loop outputs one row per iteration. Within this loop, another loop traverses the nodes and prints one character per iteration; this is where most of the work takes place. During the initialization loop, the memory layout of a node at the beginning of an iteration is `x d 0 c 0 0 0` where `x` is a boolean flag for whether the previous char was a closing parenthesis, `d` is depth (plus one), and `c` is the current character. During the character printing loop, the memory layout of a node at the beginning of an iteration is `0 0 d1 d2 c p y` where `d1` indicates depth compared with row index for top half; `d2` is similar to `d1` but for bottom half; `c` is the input character for that column if digit or space, otherwise zero; `p` indicates phase, i.e. top half, middle, or bottom half; and `y` is a flag that gets propagated from left to right, keeping track of whether we have reached the middle row yet. Note that since `y` becomes zero after processing a node, we can use the `y` cell of the previous node to gain more working space. This setup allows us to avoid explicitly calculating the max depth during the initialization phase; the `y` flag is back-propagated to update the `p` cells accordingly. There is a `-1` cell to the left of the nodes to facilitate navigation, and there is a cell to the right of the nodes that keeps track of whether we have printed the last row yet. [Answer] # Ruby, 104 bytes ``` ->s{r=s=s.gsub'}{',?| r=[s,r,s]*$/while s=s.tr('!-9',' ').gsub!(/{[ |]*}/){$&.tr' -}','-+'} r.tr'{}',?|} ``` Anonymous function that expects a string. For example, `{{{{{4 3 2 1}}}}{{{3 2 1}}}{{2 1}}{1}}` produces ``` +---------------------------------+ |+-------------+---------+-----+-+| ||+-----------+| | | || |||+---------+||+-------+| | || ||||+-------+||||+-----+||+---+| || |||||4 3 2 1||||||3 2 1||||2 1||1|| ||||+-------+||||+-----+||+---+| || |||+---------+||+-------+| | || ||+-----------+| | | || |+-------------+---------+-----+-+| +---------------------------------+ ``` You can use this code for testing: ``` f=->s{r=s=s.gsub'}{',?| r=[s,r,s]*$/while s=s.tr('!-9',' ').gsub!(/{[ |]*}/){$&.tr' -}','-+'} r.tr'{}',?|} a=[] a<<'[1, 2, 3]' a<<'[[1, 2, 3], [4, 5], [6, 7, 8]]' a<<'[[[1, 2, 3], [4, 5]], [6, 7, 8]]' a<<'[]' a<<'[[], []]' a<<'[[], [1], [], [2], [], [3], []]' a<<'[[[[[0]]]]]' a<<'[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]]' a.map{|s|s.gsub! '], [','}{' s.tr! '[]','{}' s.gsub! ',','' puts s puts f[s],''} ``` This starts from the middle row and works outwards. First, instances of `}{` are replaced with `|`. Then, while there are still braces, all innermost `{...}` strings are transformed into the appropriate `+-` sequences while characters other than `|{}` are turned into spaces. At the end, the intermediate braces are turned into pipes. [Answer] # PHP+HTML, not competing (~~170~~ ~~141~~ ~~135~~ 130 bytes) saved 29 bytes inspired by SteeveDroz ``` <?function p($a){foreach($a as$e)$r.=(is_array($e)?p($e):" $e");return"<b style='border:1px solid;float:left;margin:1px'>$r</b>";} ``` not competing because itยดs no ascii output and because I let the browser do all the interesting work [Answer] # JavaScript (ES6), 221 A non recursive function returning an array of strings (still using a recursive subfunction inside) ``` a=>[...(R=(a,l)=>a[r[l]='',0]&&a[0].map?'O'+a.map(v=>R(v,l+1))+'C':a.join` `)([a],l=-1,r=[],m='')].map(c=>r=r.map(x=>x+v[(k<0)*2+!k--],k=l,1/c?v='-- ':(v='-+|',c>'C'?k=++l:c>','&&--l,c='|'),m+=c))&&[...r,m,...r.reverse()] ``` This works in 2 steps. Step 1: recursively build a string representation of the nested input array. Example: `[[[1, 2, 3], [],[4, 5]], [6, 7, 8]]` -> `"OOO1 2 3,,4 5C,6 7 8CC"` `O` and `C` mark open and close subarray. Simple numeric subarrays are rendered with the elements separated by space, while if array members are subarrays they are separated by commas. This string keeps track of the multilevel structure of the input array, while I can get the middle row of the output just replacing `OC,` with `|`. While recursively building this temp string, I also find the max depth level and initialize an array of empty strings that will contain the half top part of the output. Note: the outer box is tricky, I nest the input inside another outer array, then I have drop the first row of output that is not needed Step 2: scan the temp string and build the output Now I have an array of empty strings, one for each level. I scan the temp string, keeping track of the current level, that increases for each `O` and decreases for each `C`. I visualize this like that: ``` [[[1, 2, 3], [],[4, 5]], [6, 7, 8]] OOO1 2 3,,4 5C,6 7 8CC + + + + + + ++ + |||1 2 3||4 5||6 7 8|| ``` The plus the goes up and down follow the current level For each char, I add a character to every row of output, following the rules: - if digit or space, put a '-' at the current level and below, put a space above - else, put a '+' at the current level, put a '-' if below and put a '|' if above ``` OOO1 2 3,,4 5C,6 7 8CC +--------------------+ |+------------+-----+| ||+-----++---+| || |||1 2 3||4 5||6 7 8|| ``` During the temp scan, I also build the middle row replacing `OC,` with `|` At the end of this step, I have the top half and the middle row, I only have to mirror the top to get the bottom half and I'm done *Less golfed, commented code* ``` a=>{ r = []; // output array R = ( // recursive scan function a, // current subarray l // current level ) => ( r[l] = '', // element of r at level r, init to "" a[0] && a[0].map // check if it is a flat (maybe empty) array or an array of arrays ? 'O'+a.map(v=>R(v,l+1))+'C' // mark Open and Close, recurse : a.join` ` // just put the elements space separated ); T = R([a],-1)]; // build temp string // pass the input nested in another array // and start with level -1 , so that the first row of r will not be visible to .map // prepare the final output m = '' // middle row, built upon the chars in T l = -1 // starting level [...T].map(c => // scan the temp string { k = l; // current level 1/c // check if numeric or space ? v = '-- ' // use '-','-',' ' : ( v = '-+|', // use '-','+','|' c > 'C' ? k=++l // if c=='O', increment level and assign to k : c>'A'&&--l, // if c=='C', decrement level (but k is not changed) c='|' // any of O,C,comma must be mapped to '|' ); m += c; // add to middle row r = r.map( (x,i) => // update each output row // based on comparation between row index and level // but in golfed code I don't use the i index // and decrement l at each step x + v[(k<i)*2+!(k-i)] ) }) // almost done! return [...r,m,...r.reverse()] ``` ) **Test** ``` F= a=>[...(R=(a,l)=>a[r[l]='',0]&&a[0].map?'O'+a.map(v=>R(v,l+1))+'C':a.join` `)([a],l=-1,r=[],m='')].map(c=>r=r.map(x=>x+v[(k<0)*2+!k--],k=l,1/c?v='-- ':(v='-+|',c>'C'?k=++l:c>','&&--l,c='|'),m+=c))&&[...r,m,...r.reverse()] out=x=>O.textContent = x+'\n'+O.textContent ;[[1,2,3] ,[[[1, 2, 3], [4, 5]], [6, 7, 8]] ,[] ,[[], []] ,[[], [1], [], [2], [], [3], []] ,[[[[[0]]]]] ,[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]] ].forEach(t=> out(JSON.stringify(t)+'\n'+F(t).join`\n`+'\n') ) function update() { var i=eval(I.value) out(JSON.stringify(i)+'\n'+F(i).join`\n`+'\n') } update() ``` ``` #I { width:90%} ``` ``` <input id=I value='[[[1, 2, 3], [],[4, 5]], [6, 7, 8]]' oninput='update()'> <pre id=O></pre> ``` [Answer] # Ruby, ~~245~~ 241 bytes The overhead needed to wrap everything in boxes as well as align everything is pretty heavy... Outputs arrays of strings, with one string per line, as per the spec. Bottom-aligned instead of the top-aligned sample test cases because it saves 1 byte. [Try it online!](https://repl.it/EKQz/3) ``` V=->a{a==[*a]?(k=a.map(&V);k[0]==[*k[0]]?[h=?++?-*((k.map!{|z|z[1,0]=[' '*~-z[0].size+?|]*(k.map(&:size).max-z.size);z};f=k.shift.zip(*k).map{|b|?|+b.reduce{|r,e|r+e[1..-1]}+?|})[0].size-2)+?+,*f,h]:[h="+#{?-*(f=k*' ').size}+",?|+f+?|,h]):a} ``` [Answer] # PHP, 404 Bytes All solutions works with maximum depth of the array lesser then 10. for greater values the depth must store in an array and not in a string. ``` <?foreach(str_split(json_encode($_GET[a]))as$j){$j!="]"?:$c--;$r=($j==",")?($l=="]"?"":" "):$j;$r=$r=="]"?"|":$r;$r=$r=="["?($v=="]"?"":"|"):$r;if($r!=""){$n.=$r;$d.=+$c;}$v=$l;$l=$j;$j!="["?:$c++;$m>=$c?:$m=$c;}for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++)$z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" "));echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` Expanded ``` foreach(str_split(json_encode($_GET[a]))as$j){ # split JSON representation of the array $j!="]"?:$c--; $r=($j==",")?($l=="]"?"":" "):$j; $r=$r=="]"?"|":$r; $r=$r=="["?($v=="]"?"":"|"):$r; if($r!=""){ $n.=$r; # concanate middle string $d.=+$c; # concanate depth position } $v=$l; $l=$j; $j!="["?:$c++; $m>=$c?:$m=$c; # maximum depth of the array } for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++) $z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" ")); # Build the strings before the middle string dependent of value middle string and depth echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); #Output ``` ## for 425 Bytes we can make this with REGEX ``` <?$n=($p=preg_filter)("#\]|\[#","|",$r=$p("#\],\[#","|",$p("#,(\d)#"," $1",json_encode($_GET[a]))));preg_match_all("#.#",$r,$e,256);foreach($e[0] as$f){$f[0]!="]"&&$f[0]!="|"?:$c--;$d.=+$c;$f[0]!="|"&&$f[0]!="["?:$c++;$m>=$c?:$m=$c;}for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++)$z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" "));echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` Expanded ``` $r=preg_filter("#\],\[#","|",preg_filter("#,(\d)#"," $1",json_encode($_GET[a]))); preg_match_all("#.#",$r,$e,256); $n=preg_filter("#\]|\[#","|",$r); # concanate middle string foreach($e[0] as$f){ $f[0]!="]"&&$f[0]!="|"?:$c--; $d.=+$c; concanate depth position $f[0]!="|"&&$f[0]!="["?:$c++; $m>=$c?:$m=$c; # maximum depth of the array } # similar to the other ways for($x=0;$x<strlen($n);$x++) for($y=0;$y<$m;$y++) $z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" ")); echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` ## 455 Bytes for a recursive solution ``` <?function v($x,$t=0,$l=1){global$d;$d.=$t;$s="|";$c=count($x);foreach($x as$k=>$v){if(is_array($v))$e=v($v,$t+1,$k+1==$c);else{$e=$v." "[$k+1==$c];$d.=str_pad("",strlen($e),$t+1);}$s.=$e;}$d.=$l?$t:"";$s.=$l?"|":"";return$s;}$n=v($_GET[a]);$m=max(str_split($d));for($x=0;$x<strlen($n);$x++)for($y=0;$y<$m;$y++)$z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" "));echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` Expanded ``` function v($x,$t=0,$l=1){ global$d; # concanate depth position $d.=$t; $s="|"; $c=count($x); foreach($x as$k=>$v){ if(is_array($v)){$e=v($v,$t+1,$k+1==$c);} else{$e=$v." "[$k+1==$c];$d.=str_pad("",strlen($e),$t+1);} $s.=$e; } $d.=$l?$t:""; $s.=$l?"|":""; return$s; } $n=v($_GET[a]); # concanate middle string $m=max(str_split($d)); # maximum depth of the array # similar to the other ways for($x=0;$x<strlen($n);$x++) for($y=0;$y<$m;$y++) $z[$y].=$y==$d[$x]&&$n[$x]=="|"?"+":($y<$d[$x]?"-":($y>$d[$x]&&$n[$x]=="|"?"|":" ")); echo join("\n",$z),"\n$n\n".(join("\n",array_reverse($z))); ``` ]
[Question] [ In this challenge, you are passed two words: Your job is to determine if they are *adjacent*. Two letters are adjacent if: 1. They are the same letter, or 2. They are lexicographically adjacent. *For example, **J** is adjacent to **I**,**J**, and **K** only. **Z** is not adjacent to **A*** Two words are adjacent if: 1. They are the same length, and 2. Each letter is adjacent to a unique letter in the other word. *For example, **CAT** is adjacent to **SAD**, as **C>D, A>A, T>S**. **FREE** is not adjacent to **GRRD** (each **E** needs a letter to pair with)*. ## Input/Output You are passed two strings, and you need to return a truthy value if they are adjacent, otherwise a falsy value. You should return within a minute for all test cases below. You can assume that the strings will only contain uppercase, alphabetic letters. The two strings can be passed as a list, or concatenated, with or without quotes. ## Test Cases Truthy: ``` A A A B C B DD CE DE FC ABCD BCDE AACC DBBB DJENSKE FDJCLMT DEFGHIJKL HJLEHMCHE IKLIJJLIJKKL LJLJLJLJLJHI ACEGIKMOQSUWY BLNPRDFTVHXJZ QQSQQRRQSTTUQQRRRS PQTTPPTTQTPQPPQRTP ELKNSDUUUELSKJFESD DKJELKNSUELSDUFEUS ``` Falsy: ``` A C A Z B J JK J CC BA CE D DJENSKE GDJCLMT DEFGHIJKL HJLHMCHE IJKLIJKLKIJL LIJLLHJLJLLL AWSUKMEGICOQY RSHXBLJLNQDFZ QQSQQRRQSTTUQQQRRS PQTTPPTTQTPQPPQRTT ELKNSDUVWELSKJFESD DKJELKNSUELSDUFEUS ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer wins! [Answer] # CJam, ~~14~~ ~~13~~ 12 bytes ``` r$r$.-:)3,-! ``` [Try it online!](http://cjam.tryitonline.net/#code=ciRyJC4tOikzLC0h&input=RUxLTlNEVVVVRUxTS0pGRVNEIERLSkVMS05TVUVMU0RVRkVVUw) or [verify all test cases at once](http://cjam.tryitonline.net/#code=MjV7ciRyJC4tOikzLC0hfSo&input=QSBBCkEgQgpDIEIKREQgQ0UKREUgRkMKQUJDRCBCQ0RFCkFBQ0MgREJCQgpESkVOU0tFIEZESkNMTVQKREVGR0hJSktMIEhKTEVITUNIRQpJS0xJSkpMSUpLS0wgTEpMSkxKTEpMSkhJCkFDRUdJS01PUVNVV1kgQkxOUFJERlRWSFhKWgpRUVNRUVJSUVNUVFVRUVJSUlMgUFFUVFBQVFRRVFBRUFBRUlRQCkVMS05TRFVVVUVMU0tKRkVTRCBES0pFTEtOU1VFTFNEVUZFVVMKQSBDCkEgWgpCIEoKSksgSgpDQyBCQQpDRSBECkRKRU5TS0UgR0RKQ0xNVApERUZHSElKS0wgSEpMSE1DSEUKSUpLTElKS0xLSUpMIExJSkxMSEpMSkxMTCAKQVdTVUtNRUdJQ09RWSBSU0hYQkxKTE5RREZaClFRU1FRUlJRU1RUVVFRUVJSUyBQUVRUUFBUVFFUUFFQUFFSVFQKRUxLTlNEVVZXRUxTS0pGRVNEIERLSkVMS05TVUVMU0RVRkVVUw). ### Algorithm Let **s** and **t** be two sorted words of the same length. For **s** and **t** to be lexicographically adjacent (LA), it is necessary and sufficient that all pairs of its corresponding characters are also LA. The condition is clearly sufficient for all words, and necessary for words of length **1**. Now, assume **s** and **t** have length **n > 1**, and let **a** and **b** be the first characters, resp., of **s** and **t**. Since **s** and **t** are LA, there is some bijective mapping **ฯ†** between the characters of **s** and the characters of **t** such that **x** and **ฯ†(x)** are LA for all **x** in **s**, meaning that **|x - ฯ†(x)| โ‰ค 1** for all **x** in **s**. Let **c = ฯ†(a)** and **d = ฯ†-1(b)**. Because of **a**'s and **b**'s minimality, **a โ‰ค d (1)** and **b โ‰ค c (2)**. Furthermore, since **b** and **d**, and **a** and **c**, and LA, **d โ‰ค b + 1 (3)** and **c โ‰ค a + 1 (4)**. By combining **(1)** and **(3)**, and **(2)** and **(4)**, we get that **a โ‰ค d โ‰ค b + 1** and **b โ‰ค c โ‰ค a + 1**, from which we deduce that **a - 1 โ‰ค b โ‰ค a + 1** and, therefore, that **a** and **b** are LA. Now, by combining **(1)** and **(4)**, and **(2)** and **(3)**, we get that **c - 1 โ‰ค a โ‰ค d** and **d - 1 โ‰ค b โ‰ค c**, from which we deduce that **c - 1 โ‰ค d โ‰ค c + 1** and, therefore that **c** and **d** are LA. Thus, if we redefine **ฯ†** by **ฯ†(a) = b** and **ฯ†(d) = c**, **|x - ฯ†(x)| โ‰ค 1** will still hold for all **x** in **s** and, in particular, for all **x** in **s[1:]**. This way, **s[0] = a** and **t[0] = b**, and **s[1:]** and **t[1:]**, are LA. Since **s[1:]** has length **n - 1**, this proves the necessity by induction. ### Code ``` r e# Read the first word from STDIN. $ e# Sort its characters. r e# Read the second word from STDIN. $ e# Sort its characters. .- e# Perform vectorized subtraction. e# This pushes either the difference of char codes of two e# corresponding characters or a character that has no does not e# correspond to a character in the other, shorter word. :) e# Increment all results. e# In particular, this maps [-1 0 1] to [0 1 2]. 3, e# Push the range [0 1 2]. - e# Perform set difference, i.e., remove all occurrences of 0, 1 and e# 2 from the array of incremented differences. ! e# Apply logical NOT. This gives 1 iff the array was empty iff e# all differences gave -1, 0 or 1. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 ~~12~~ ~~17~~ bytes ``` c!S!odXl2< ``` This uses [Dennis' approach](https://codegolf.stackexchange.com/a/70096/36398): sort first and compare characters in matching positions. Input is an array of strings, with the format `{'CAT 'SAD'}`. Output is an array of zeros and ones. A result is truthy iff it contains all ones (this is [agreed](https://codegolf.meta.stackexchange.com/q/2190/36398) to be truthy). Uses [current release (10.2.1)](https://github.com/lmendo/MATL/releases/tag/10.2.1), which is earlier than this challenge. *EDIT:* Function `Xl` has been renamed to `|` in newer versions of the language (and `o` is no longer necessary). The link below includes those modifications. [**Try it online!**](http://matl.tryitonline.net/#code=YyFTIWR8Mjw&input=eydBQ0VHSUtNT1FTVVdZJyAnQkxOUFJERlRWSFhKWid9Cg) **Explanation**: ``` c % implicitly cell array of strings and convert to 2D char array. % This pads with spaces if needed !S! % sort each row o % convert array from char to double d % difference between elements in the same column Xl % absolute value of each entry 2 % number literal < % each entry becomes 1 if smaller than 2 (adjacent letters), and 0 otherwise ``` --- Old approach, which accepts the strings as separate inputs: **12 bytes**: ``` SiSXhcodXl2< ``` *EDIT*: the code in the link has been modified acording the changes in the language; see comment above. [**Try it online**!](http://matl.tryitonline.net/#code=U2lTWGhjZHwyPA&input=J0FDRUdJS01PUVNVV1knCidCTE5QUkRGVFZIWEpaJwo) **Explanation**: ``` S % implicitly input first string and sort iS % input second string and sort Xh % build cell array with these two strings c % convert to 2D char array. This pads with spaces if needed o % convert array from char to double d % difference between elements in the same column Xl % absolute value of each entry 2 % number literal < % each entry becomes 1 if smaller than 2 (adjacent letters), and 0 otherwise ``` [Answer] # C, 233 bytes ``` #include <stdlib.h> #include <string.h> #define h char #define r return int c(void*a,void*b){r*(h*)a-*(h*)b;}int a(h*s,h*t){int l=strlen(s),m=strlen(t);if(l!=m)r 0;qsort(s,l,1,c);qsort(t,m,1,c);while(l--)if(abs(s[l]-t[l])>1)r 0;r 1;} ``` You can test it by saving that as `adj.h` and then using this `adj.c` file: ``` #include <stdio.h> #include "adj.h" int main() { char aa[] = "A", A[] = "A"; char b[] = "A", B[] = "B"; char cc[] = "C", C[] = "B"; char d[] = "DD", D[] = "CE"; char e[] = "DE", E[] = "FC"; char f[] = "ABCD", F[] = "BCDE"; char g[] = "AACC", G[] = "DBBB"; char hh[] = "DJENSKE", H[] = "FDJCLMT"; char i[] = "DEFGHIJKL", I[] = "HJLEHMCHE"; char j[] = "IKLIJJLIJKKL", J[] = "LJLJLJLJLJHI"; char k[] = "ACEGIKMOQSUWY", K[] = "BLNPRDFTVHXJZ"; char l[] = "QQSQQRRQSTTUQQRRRS", L[] = "PQTTPPTTQTPQPPQRTP"; char m[] = "ELKNSDUUUELSKJFESD", M[] = "DKJELKNSUELSDUFEUS"; char n[] = "A", N[] = "C"; char o[] = "A", O[] = "Z"; char p[] = "B", P[] = "J"; char q[] = "JK", Q[] = "J"; char rr[] = "CC", R[] = "BA"; char s[] = "CE", S[] = "D"; char t[] = "DJENSKE", T[] = "GDJCLMT"; char u[] = "DEFGHIJKL", U[] = "HJLHMCHE"; char v[] = "IJKLIJKLKIJL", V[] = "LIJLLHJLJLLL"; char w[] = "AWSUKMEGICOQY", W[] = "RSHXBLJLNQDFZ"; char x[] = "QQSQQRRQSTTUQQQRRS", X[] = "PQTTPPTTQTPQPPQRTT"; char y[] = "ELKNSDUVWELSKJFESD", Y[] = "DKJELKNSUELSDUFEUS"; char *z[] = {aa,b,cc,d,e,f,g,hh,i,j,k,l,m,n,o,p,q,rr,s,t,u,v,w,x,y}; char *Z[] = {A ,B,C ,D,E,F,G,H ,I,J,K,L,M,N,O,P,Q,R ,S,T,U,V,W,X,Y}; for(int _=0;_<25;_++) { printf("%s %s: %s\r\n", z[_], Z[_], a(z[_], Z[_]) ? "true" : "false"); } return 0; } ``` Then compile using `gcc adj.c -o adj`. The output is: ``` A A: true A B: true C B: true DD CE: true DE CF: true ABCD BCDE: true AACC BBBD: true DEEJKNS CDFJLMT: true DEFGHIJKL CEEHHHJLM: true IIIJJJKKKLLL HIJJJJJLLLLL: true ACEGIKMOQSUWY BDFHJLNPRTVXZ: true QQQQQQQRRRRRSSSTTU PPPPPPPQQQQRTTTTTT: true DDEEEFJKKLLNSSSUUU DDEEEFJKKLLNSSSUUU: true A C: false A Z: false B J: false JK J: false CC AB: false CE D: false DEEJKNS CDGJLMT: false DEFGHIJKL HJLHMCHE: false IIIJJJKKKLLL HIJJJLLLLLLL: false ACEGIKMOQSUWY BDFHJLLNQRSXZ: false QQQQQQQQRRRRSSSTTU PPPPPPQQQQRTTTTTTT: false DDEEEFJKKLLNSSSUVW DDEEEFJKKLLNSSSUUU: false ``` [Answer] # Python 2, 90 bytes ``` lambda A,B:all(ord(b)-2<ord(a)<ord(b)+2for a,b in zip(sorted(A),sorted(B)))*len(A)==len(B) ``` Simple anonymous function, I have to have a separate check for length because `zip` will just contatenate. Theres a similar function in `itertools` (`zip_longest`) which would pad empty strings, but that would be quite costly. Testing with ``` f=lambda A,B:all(ord(b)-2<ord(a)<ord(b)+2for a,b in zip(sorted(A),sorted(B)))*len(A)==len(B) for case in testCases.split('\n'): print case, f(*case.split()) ``` produces: ``` A A True A B True C B True DD CE True DE FC True ABCD BCDE True AACC DBBB True DJENSKE FDJCLMT True DEFGHIJKL HJLEHMCHE True IKLIJJLIJKKL LJLJLJLJLJHI True ACEGIKMOQSUWY BLNPRDFTVHXJZ True QQSQQRRQSTTUQQRRRS PQTTPPTTQTPQPPQRTP True ELKNSDUUUELSKJFESD DKJELKNSUELSDUFEUS True A C False A Z False B J False JK J False CC BA False CE D False DJENSKE GDJCLMT False DEFGHIJKL HJLHMCHE False IJKLIJKLKIJL LIJLLHJLJLLL False AWSUKMEGICOQY RSHXBLJLNQDFZ False QQSQQRRQSTTUQQQRRS PQTTPPTTQTPQPPQRTT False ELKNSDUVWELSKJFESD DKJELKNSUELSDUFEUS False ``` [Answer] # JavaScript (ES6), 86 ~~90 94~~ **Edit** 4 bytes saved thx @Neil **Edit 2** 4 bytes save thx @Mwr247 ``` (a,b)=>[...[...a].sort(),0].every((x,i)=>parseInt(x+([...b].sort()[i]||0),36)%37%36<2) ``` Note: adjacency check on a pair of letters. Take the pair as a base 36 number *n*, if the letters are equal, then `n = a*36+a = a*37`. If there is a difference of 1 then `n = a*36+a+1 = a*37+1` or `n = a*36+a-1 = a*37-1`. So `n % 37` must be 0, 1 or 36. And `n%37%36` must be 0 or 1. Note 2: the added '0' is used to ensure that a and b are the same length. It's shorter then `a.length==b.length` ``` F=(a,b)=>[...[...a].sort(),0].every((x,i)=>parseInt(x+([...b].sort()[i]||0),36)%37%36<2) console.log=x=>O.textContent+=x+'\n'; testOK=[['A','A'],['A','B'],['C','B'],['DD','CE'],['DE','FC'], ['ABCD','BCDE'],['AACC','DBBB'],['DJENSKE','FDJCLMT'], ['DEFGHIJKL','HJLEHMCHE'],['IKLIJJLIJKKL','LJLJLJLJLJHI'], ['ACEGIKMOQSUWY','BLNPRDFTVHXJZ'], ['QQSQQRRQSTTUQQRRRS','PQTTPPTTQTPQPPQRTP'], ['ELKNSDUUUELSKJFESD','DKJELKNSUELSDUFEUS']]; testFail=[['A','C'],['A','Z'],['B','J'],['JK','J'],['CC','BA'],['CE','D'], ['DJENSKE','GDJCLMT'],['DEFGHIJKL','HJLHMCHE'], ['IJKLIJKLKIJL','LIJLLHJLJLLL',''], ['AWSUKMEGICOQY','RSHXBLJLNQDFZ'], ['QQSQQRRQSTTUQQQRRS','PQTTPPTTQTPQPPQRTT'], ['ELKNSDUVWELSKJFESD','DKJELKNSUELSDUFEUS']]; console.log('TRUE') testOK.forEach(t=>{ var a=t[0],b=t[1],r=F(a,b) console.log(r+' '+a+' '+b) }) console.log('FALSE') testFail.forEach(t=>{ var a=t[0],b=t[1],r=F(a,b) console.log(r+' '+a+' '+b) }) ``` ``` <pre id=O></pre> ``` [Answer] # JavaScript ES6, ~~117 bytes~~ ~~116 bytes~~ ~~111 bytes~~ 109 bytes ``` (j,k)=>j.length==k.length&&(f=s=>[...s].sort())(j).every((c,i)=>Math.abs(c[h='charCodeAt']()-f(k)[i][h]())<2) ``` ## Test Cases ``` a=(j,k)=>j.length==k.length&&(f=s=>[...s].sort())(j).every((c,i)=>Math.abs(c[h='charCodeAt']()-f(k)[i][h]())<2); // true console.log('A A:', a('A', 'A')); console.log('A B:', a('A', 'B')); console.log('C B:', a('C', 'B')); console.log('DD CE:', a('DD', 'CE')); console.log('DE FC:', a('DE', 'FC')); console.log('ABCD BCDE:', a('ABCD', 'BCDE')); console.log('AACC DBBB:', a('AACC', 'DBBB')); console.log('DJENSKE FDJCLMT:', a('DJENSKE', 'FDJCLMT')); console.log('DEFGHIJKL HJLEHMCHE:', a('DEFGHIJKL', 'HJLEHMCHE')); console.log('IKLIJJLIJKKL LJLJLJLJLJHI:', a('IKLIJJLIJKKL', 'LJLJLJLJLJHI')); console.log('ACEGIKMOQSUWY BLNPRDFTVHXJZ:', a('ACEGIKMOQSUWY', 'BLNPRDFTVHXJZ')); console.log('QQSQQRRQSTTUQQRRRS PQTTPPTTQTPQPPQRTP:', a('QQSQQRRQSTTUQQRRRS', 'PQTTPPTTQTPQPPQRTP')); console.log('ELKNSDUUUELSKJFESD DKJELKNSUELSDUFEUS:', a('ELKNSDUUUELSKJFESD', 'DKJELKNSUELSDUFEUS')); // false console.log('A C:', a('A', 'C')); console.log('A Z:', a('A', 'Z')); console.log('B J:', a('B', 'J')); console.log('JK J:', a('JK', 'J')); console.log('CC BA:', a('CC', 'BA')); console.log('CE D:', a('CE', 'D')); console.log('DJENSKE GDJCLMT:', a('DJENSKE', 'GDJCLMT')); console.log('DEFGHIJKL HJLHMCHE:', a('DEFGHIJKL', 'HJLHMCHE')); console.log('IJKLIJKLKIJL LIJLLHJLJLLL:', a('IJKLIJKLKIJL', 'LIJLLHJLJLLL')); console.log('AWSUKMEGICOQY RSHXBLJLNQDFZ:', a('AWSUKMEGICOQY', 'RSHXBLJLNQDFZ')); console.log('QQSQQRRQSTTUQQQRRS PQTTPPTTQTPQPPQRTT:', a('QQSQQRRQSTTUQQQRRS', 'PQTTPPTTQTPQPPQRTT')); console.log('ELKNSDUVWELSKJFESD DKJELKNSUELSDUFEUS:', a('ELKNSDUVWELSKJFESD', 'DKJELKNSUELSDUFEUS')); ``` ``` <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> ``` ## Credit * @rink.attendant.6 shaved off 5 bytes * @user81655 shaved off 2 bytes [Answer] # JavaScript (ES6), 87 bytes ``` (a,b)=>![...a].sort().some((d,i)=>(d[c='charCodeAt']()-([...b].sort()[i]||c)[c]())/2|0) ``` Uses a zero-centric symmetrical range check by dividing by the max value, then truncating with a bitwise "or" (`|`). Shorter than having to do two checks, or one with `Math.abs()`. [Answer] ## Haskell, ~~67~~ 63 bytes ``` import Data.List f a=any(null.(a\\)).mapM(\x->[pred x..succ x]) ``` Usage example: `f "FREE" "GRRD"` -> `False`. How it works (note: `f` is partially point-free and the second parameter `b` does not appear in the definition): ``` mapM(\x->[pred x..succ x]) -- for each letter of b make a list of the -- predecessor, the letter itself and the successor. -- Make a list of every possible combination -- thereof, e.g "dr" -> -- ["cq","cr","cs","dq","dr","ds","eq","er","es"] any(null.(a\\)) -- see if the difference between any of the -- combinations and the other parameter a is -- empty, i.e. they have the same elements ``` Edit: @xnor found 4 bytes to save. Thanks! [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 27 bytes **Solution:** ``` 2>|/x*x:-/(|/#:'x)$x@'<:'x: ``` [Try it online!](https://tio.run/##FcYxCoAwEATAv0QhUQgByyjiE24v6ytS2F6Rv5861fT8dPftHMVWq7mkUaYabZntiseXmgLQAFU08v6jLexBQIqQoEAESgmL@ws "K (oK) โ€“ Try It Online") **Examples:** ``` 2>|/x*x:-/(|/#:'x)$x@'<:'x:("QQSQQRRQSTTUQQRRRS";"PQTTPPTTQTPQPPQRTP") 1 2>|/x*x:-/(|/#:'x)$x@'<:'x:("DEFGHIJKL";"HJLHMCHE") 0 2>|/x*x:-/(|/#:'x)$x@'<:'x:("AAA";"AAA") 1 2>|/x*x:-/(|/#:'x)$x@'<:'x:("AAA";"AA") 0 ``` **Explanation:** First sort each string, then pad to be the same length, then take one from the other (ASCII values of chars), square result as there is no built-in `abs`, take the maximum difference and check whether that is less than 2. ``` 2>|/x*x:-/(|/#:'x)$x@'<:'x: / the solution x: / save input to variable x <:' / ascending sorted indices (<:) for each (') list x@' / apply (@) each (') of these indices to the input (x) ( )$ / pad #:'x / count (#:) each (') list (x) |/ / max (|) over (/) to get maximum -/ / subtract (-) over (/) to take 2nd list from 1st x: / save in variable x x* / multiply by x (so square) |/ / max over to get maximum distance 2> / is 2 greater than (>) to this maximum? returns 1 (true) or 0 (false) ``` [Answer] # C, 172 bytes ``` #define q(x)qsort(x,strlen(x),1,c) c(x,y)char*x,*y;{return*x-*y;}main(a,v,w)char**v,*w,*a;{for(q(w=v[1]),q(a=v[2]);*w&&*a&&abs(*w-*a)<2;w++,a++);printf("%d",abs(*w-*a)<2);} ``` ## Test Cases ``` $ bash -x test.sh + bash -x test.sh + ./a.out A A 1+ ./a.out A B 1+ ./a.out C B 1+ ./a.out DD CE 1+ ./a.out DE FC 1+ ./a.out ABCD BCDE 1+ ./a.out AACC DBBB 1+ ./a.out DJENSKE FDJCLMT 1+ ./a.out DEFGHIJKL HJLEHMCHE 1+ ./a.out IKLIJJLIJKKL LJLJLJLJLJHI 1+ ./a.out ACEGIKMOQSUWY BLNPRDFTVHXJZ 1+ ./a.out QQSQQRRQSTTUQQRRRS PQTTPPTTQTPQPPQRTP 1+ ./a.out ELKNSDUUUELSKJFESD DKJELKNSUELSDUFEUS 1+ ./a.out A C 0+ ./a.out A Z 0+ ./a.out B J 0+ ./a.out JK J 0+ ./a.out CC BA 0+ ./a.out CE D 0+ ./a.out DJENSKE GDJCLMT 0+ ./a.out DEFGHIJKL HJLHMCHE 0+ ./a.out IJKLIJKLKIJL LIJLLHJLJLLL 0+ ./a.out AWSUKMEGICOQY RSHXBLJLNQDFZ 0+ ./a.out QQSQQRRQSTTUQQQRRS PQTTPPTTQTPQPPQRTT 0+ ./a.out ELKNSDUVWELSKJFESD DKJELKNSUELSDUFEUS 0++ ``` [Answer] ## PowerShell, 140 bytes ``` param($a,$b)(($a=[char[]]$a|sort).Count-eq($b=[char[]]$b|sort).Count)-and(($c=0..($a.Count-1)|%{+$a[$_]-$b[$_]}|sort)[0]-ge-1-and$c[-1]-le1) ``` Might be possible to get this shorter. It's not currently competitive with Python or JavaScript, but it uses a slightly different approach, so I figured I'd post it. ### Explanation This code is really confusing for someone not fluent in PowerShell, so I'll try to break it down into English as best I can... We start with taking input `param($a,$b)` as normal. The whole rest of the code is actually one statement, and can be broken as `(...)-and(...)` to test two Boolean statements with the `-and` operator. The left-hand parens can be broken as `(... -eq ...)` to test equality of two objects. In this instance, the objects are the `.Count`s (that is, the length) of two new char-arrays. Each inner paren `($a=[char[]]$a|sort)` takes the original input word, re-casts it as a char-array, then sorts it and re-saves back into the same variable. We do that for both `$a` and `$b`. The left-hand side thus verifies that the input words are the same length. If they are not the same length, this half of the outer Boolean statement will fail and `False` will be output. Moving to the right-hand side, we're again testing two Boolean statements with `(... -and ...)`. The left-hand side tests whether *something* is greater-than-or-equal-to negative 1 with `-ge-1`. The *something* is the zeroth-element of a constructed array `$c`, which is created by: * taking a range of the allowed indices `0..($a.count-1)` * piped into a loop `|%{...}` * each iteration of the loop, we take the ASCII values of the indexed character in `$a` and subtract the ASCII value of the indexed character in `$b` * which is then `|sort`ed by numerical value The other side of the statement takes the maximal value `$c[-1]` of the array and ensures it's less-than-or-equal to 1 with `-le1`. Thus, if the two input strings are indeed adjacent, the `$c` array will be something like `@(-1,-1,-1...0,0,0...1,1,1)`. So the first element will be `-1` and the last element will be `1`. If they are not adjacent, the difference in ASCII values for a particular pair will either be `< -1` or `> 1`, so this half of the outer Boolean test will fail, and `False` will be output. Only if both sides pass will `True` be output, and the strings are therefore LA. [Answer] # Pyth, ~~37~~ 31 bytes ``` &qZ-FmldK.zqY-m.a-FdCmmCkSdK[Z1 ``` [Try it online with all test cases!](https://pyth.herokuapp.com/?code=%26qZ-FmldK.zqY-m.a-FdCmmCkSdK%5BZ1&input=A%0AA&test_suite=1&test_suite_input=A%0AA%0AA%0AB%0AC%0AB%0ADD%0ACE%0ADE%0AFC%0AABCD%0ABCDE%0AAACC%0ADBBB%0ADJENSKE%0AFDJCLMT%0ADEFGHIJKL%0AHJLEHMCHE%0AIKLIJJLIJKKL%0ALJLJLJLJLJHI%0AACEGIKMOQSUWY%0ABLNPRDFTVHXJZ%0AQQSQQRRQSTTUQQRRRS%0APQTTPPTTQTPQPPQRTP%0AELKNSDUUUELSKJFESD%0ADKJELKNSUELSDUFEUS%0AA%0AC%0AA%0AZ%0AB%0AJ%0AJK%0AJ%0ACC%0ABA%0ACE%0AD%0ADJENSKE%0AGDJCLMT%0ADEFGHIJKL%0AHJLHMCHE%0AIJKLIJKLKIJL%0ALIJLLHJLJLLL+%0AAWSUKMEGICOQY%0ARSHXBLJLNQDFZ%0AQQSQQRRQSTTUQQQRRS%0APQTTPPTTQTPQPPQRTT%0AELKNSDUVWELSKJFESD%0ADKJELKNSUELSDUFEUS&debug=0&input_size=2) Shaved off 6 bytes by using the shortened reduce notation (`-F` instead of `.U-bZ`) Solution inspired by [Dennis](https://codegolf.stackexchange.com/a/70096/36398) First submission to codegolf! ## Explanation We can split the expression in two parts, which are compared with `&` to output the result. I'll try to explain by writing some pseudo-Python First we check that the length of the two words are the same ``` mldK.z lengths = map(lambda d: len(d), K=all_input()) .U-bZmldK.z diff = reduce(lambda b, Z: b - Z, lengths) qZ.U-bZmldK.z diff == 0 ``` Then, we apply Dennis' method: ``` K # ['CAT', 'SAD'] m SdK sort = map(lambda d: sorted(d), K) # ['ACT', 'ADS'] mmCkSdK ascii = map(lambda d: sorted(d), map(lambda k: ord(k), K)) # [[65, 67, 84], [65, 68, 83]] CmmCkSdK zipped = zip(*ascii) # [[65, 65], [67, 68], [84, 83]] m.U-bZd CmmCkSdK map(lambda d: d[0] - d[1], zipped) # [0, -1, 1] m.a.U-bZd CmmCkSdK map(lambda d: abs(d[0] - d[1]), zipped) # [0, 1, 1] ``` We then use the `-` operator to filter all elements of that list that are not in `[Z1` (`[0, 1]`), and check that the result is an empty list with `qY` [Answer] **Rust, ~~269~~ 264 bytes** ``` fn a(w:&str,x:&str)->bool{if w.len()==x.len(){return{let mut c:Vec<char>=w.chars().collect();let mut d:Vec<char>=x.chars().collect();c.sort();d.sort();for(e,f)in c.iter().zip(d.iter()){if(((*e as u8)as f64)-((*f as u8)as f64)).abs()>1f64{return false}}true}}false} ``` Expanded: ``` fn are_adjacent(w: &str, x: &str)->bool{ if w.len() == x.len(){ return { let mut c : Vec<char> = w.chars().collect(); let mut d : Vec<char> = x.chars().collect(); c.sort(); d.sort(); for (e,f) in c.iter().zip(d.iter()){ if (((*e as u8) as f64) - ((*f as u8) as f64)).abs() > 1f64{ return false } } true } } false } ``` Test Cases: ``` fn main(){ assert_eq!(true,are_adjacent("A","B")); assert_eq!(true,are_adjacent("A","B")); assert_eq!(true,are_adjacent("C","B")); assert_eq!(true,are_adjacent("DD","CE")); assert_eq!(true,are_adjacent("DE","FC")); assert_eq!(true,are_adjacent("ABCD","BCDE")); assert_eq!(true,are_adjacent("AACC","DBBB")); assert_eq!(true,are_adjacent("DJENSKE","FDJCLMT")); assert_eq!(true,are_adjacent("DEFGHIJKL","HJLEHMCHE")); assert_eq!(true,are_adjacent("IKLIJJLIJKKL","LJLJLJLJLJHI")); assert_eq!(true,are_adjacent("ACEGIKMOQSUWY","BLNPRDFTVHXJZ")); assert_eq!(true,are_adjacent("QQSQQRRQSTTUQQRRRS","PQTTPPTTQTPQPPQRTP")); assert_eq!(true,are_adjacent("ELKNSDUUUELSKJFESD","DKJELKNSUELSDUFEUS")); assert_eq!(false,are_adjacent("A","C")); assert_eq!(false,are_adjacent("A","Z")); assert_eq!(false,are_adjacent("B","J")); assert_eq!(false,are_adjacent("JK","J")); assert_eq!(false,are_adjacent("CC","BA")); assert_eq!(false,are_adjacent("CE","D")); assert_eq!(false,are_adjacent("DJENSKE","GDJCLMT")); assert_eq!(false,are_adjacent("DEFGHIJKL","HJLHMCHE")); assert_eq!(false,are_adjacent("IJKLIJKLKIJL","LIJLLHJLJLLL")); assert_eq!(false,are_adjacent("AWSUKMEGICOQY","RSHXBLJLNQDFZ")); assert_eq!(false,are_adjacent("QQSQQRRQSTTUQQQRRS","PQTTPPTTQTPQPPQRTT")); assert_eq!(false,are_adjacent("QQSQQRRQSTTUQQQRRS","PQTTPPTTQTPQPPQRTT")); assert_eq!(false,are_adjacent("ELKNSDUVWELSKJFESD","DKJELKNSUELSDUFEUS")); } ``` [Answer] # APL, 59 bytes (characters) (61 if we have to supply the { and }, 63 with fโ†) I'm not the greatest APLer, but it's just too much fun. `(0=+/2โ‰ค|ยจโˆŠ-/{โŽ•avโณโต}ยจ(โบ{โŒˆ/โดยจโบโต}โต)โดยจโบ[โ‹โบ]โต[โ‹โต])โˆง=/โดยจโˆŠยจโบโต` `=/โดยจโˆŠยจโบโต` are the inputs equally long? `โˆง` and all of the below `(โบ{โŒˆ/โดยจโบโต}โต)โดยจโบ[โ‹โบ]โต[โ‹โต]` sort both inputs and shape them to be as long as the longest of the two (they wrap around if you make them longer than they are) `|ยจโˆŠ-/{โŽ•avโณโต}` convert both char vectors to int vectors of their ascii values, do a vector subtraction and absolute all values `0=+/2โ‰ค` sum up values larger than or equal to two and check if the result is equal to 0 [Answer] # J, 27 bytes ``` [:*/@(2>|)[:-/,:&(3&u:@/:~) ``` ## ungolfed ``` [: */@(2 > |) [: -/ ,:&(3&u:@/:~) ``` ## explained * `&(3&u:@/:~)` sorts both arguments, and converts to them to ascii numbers * `,:` creates a 2 x n matrix, where n is the number of chars of the args * `-/` subtracts one row from the other, giving a list of length n representing the distance of corresponding chars * `(2>|)` returns 1 if the absolute value of the distance is less than 2, 0 otherwise * `*/` multiplies all those `0`s and `1`s together: hence, the final result is 1 iff all pairs of corresponding chars are adjacent. [Try it online!](https://tio.run/##hdHPa8IwFAfw@/srHjuoHU6Hu8Uptklqm8TaNKk/D0PEImMwmHoYbPvXu1TnDptjhO8jvBcCn@SxLHbYI3iLLuWSXLcHjU7/zVuSm3aT1Bp3tQMZtMmHV3pw1cJ60SN1bOI7wWIHsH857LevvRY27gdd0m09dLzTTeCj7xIAdWEMKQfGMaTgB5ShCwffpxRZELi54ImRbswEVSPrTobDKBZSYSQUj0Y04hBLFQvhIl1bifOKYvApH8ZyNNYmn84xUEmasdBOoplYgNZG6yzTxtq82mQGU21tmlqrbarTVGc2Ba5kYlie51wZKUJuGDIpjt2qxfKQ5wY8gGL1tPtD62S4gAAFCOmKowU@UI7sWze8pPvCiUonlYyFw7miokqnFII/NbkcOSEd6zlmJpoFbpJoFv7U6Ys6e9ZNpv/oNuvtMxbtAenjZrXe4ulvf7WPb1B@Ag "J โ€“ Try It Online") ]
[Question] [ You are the sonar captain aboard an underwater submarine. The way sonar works is that every submarine sends out a ping at regular intervals. Each interval is a whole number of seconds. Each submarine has an identifying amplitude, that is no two submarines send out pings at the same amplitude. The amplitude is always a positive integer, so when two submarines send out pings at the same time, they constructively interfere and it appears on your ship's readout as a single ping at the sum of the amplitudes. However, there are imposters in the deep sea. An imposter will send out pings at a different submarine's amplitude to imitate them. That means that when there's an imposter in the midst there will be two submarines pinging at the same amplitude. If you see the following readout over a 10 second interval ``` 0,1,1,0,1,1,0,1,1,0 ``` Then you know there must be an imposter. The `1` pings don't occur at regular intervals. However if you see the following: ``` 0,3,3,0,3,3,0,3,3,0 ``` You can't be certain there's an imposter. There might be an imposter imitating the `3` submarine: ``` 0,3,0,0,3,0,0,3,0,0 0,0,3,0,0,3,0,0,3,0 ``` Or there might be 3 submarines with two of them interfering: ``` 0,1,0,0,1,0,0,1,0,0 0,2,0,0,2,0,0,2,0,0 0,0,3,0,0,3,0,0,3,0 ``` Now the interference can make things pretty complicated. Can you tell quickly whether there's an imposter in the following readout: ``` 5,7,5,3,9,4,5,7 ``` It's possible, but it's also possible there's no imposter: ``` 0,4,0,0,4,0,0,4 3,3,3,3,3,3,3,3 0,0,0,0,0,1,0,0 2,0,2,0,2,0,2,0 ``` So you'd like to write a computer program which takes a readout and tells you quickly, without having to do any working by hand, whether there is definitely an imposter. ## Task Given a readout of your submarine's sonar as a list of non-negative integers, output a value if there is definitely an imposter, and output a different distinct value otherwise. Your submarine is under a lot of pressure so your code should be pressurized as well. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes. ## Test cases ### Imposter ``` [0,1,1,0,1,1,0,1,1,0] [0,1,1] [1,1,2] [9,2,8,7,3,6,1,1] [9,10,7,3,8,8,2,2] [2,9,2,6,1] ``` ### Maybe imposter ``` [9] [9,9] [9,9,9] [9,9,9,9] [0,3,3] [3,1,1] [1,2,3,4,5,6,7,8] [9,9,9,9,9,9,9,9,1] [5,7,5,3,9,4,5,7] ``` [Answer] # [Python](https://www.python.org), ~~180~~ ~~173~~ ~~169~~ 166 bytes *-7 bytes thanks to @gsitcia* *-3 bytes thanks to @naffetS* ``` lambda a,r=range:(l:=len(a))!=a in[[*map(sum,zip(*s))]for s in product(*[[((*i//l*[0],-~p)*l)[i%l:i%l+l]for i in r(l*l+1)]for p in r(max(a))])] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY7NasQgFIXXzVPYgYI6ymSaTQn4JNaF7cRU8A9jhraLPkV33QRK5536NtU4hRlEvfdcznfu1ym8pRfvlu-RPf7MSdGH35OR9ukggSSRRenGoYemZ2ZwUCJ0yyTQjnNsZYDTbMm7DhBPCAnlI5jyDIToD_NzgphzCLHe7QzmrSD0IyBsENd3ps93a1aHLo4IDTbbfWWEqlj5WvIEEo2K3gKdhpi8NznCBh8TPm_7mRhvbnhL9vlcvYL862tVtPtcZV5OOZaU1IeoXYIjPCLUNLXZUEo3uVNnbke61d9dkNqScc1Sl6y627LU_w8) *Very* inefficient for inputs with larger maximum values. Brute force solution -- goes through every set of submarines which does not contain an imposter and checks if any of them produce the given input. [Answer] # JavaScript (ES10), 198 bytes Returns *true* for *imposter* or *false* for *maybe imposter*. Looks like this code could be pressurized some more... ``` f=([v,...a],c=[],F=(n,l=[],i=1)=>n?i>n||F(n-i,[i,...l],++i)&&F(n,l,i):f(a,[...c,l]))=>v+1?F(v):c.flat().some(v=>(m=(s=c.map(l=>l.includes(v)|!++a).join``).match(/(10*)1/))&&!m[1].repeat(a).match(s)) ``` [Try it online!](https://tio.run/##dZBNasMwEIX3PUWzSaR6ovinaeKAnJ2hi55ANURV5FZBlk3kGgq5uztOaWnAZkCIN997M9JJdtKrs2napauPuu9LTkQHjDFZgOKigJwTB3a4GR5Rnrm9ydzlkhO3NCDMgNoCgsDQ@TwfUDB0VxIJAjsKbEHR1AXRPicd3SlWWtkSynxdadLxjFSceK5YJRtieWaZccp@HrVH@jILAknZqTbucKCItOqDrEgUPtBoRXHerBJRwc660ZgpfwlPaa9q52urma3fyUI8V03tW30uFvTuf6ckIoQI6@bEjUepEX3g4xE9hRi2sIEEniacKUThFdhixT8hN8zi1YkX@fWm78309ulo8oQ6rY92QlwuGdGTyb@I0fEIa3zzBrbTs/5qLGWN3jXmpNekDRL9Nw "JavaScript (Node.js) โ€“ Try It Online") [Answer] # Python3, 677 bytes: ``` lambda b:next(C(b),0)!=0 R,T,U,M=range,sorted,lambda x:''.join(map(str,x)).lstrip('0'),lambda r,k:any(all(j==K for j,K in zip(U(i),U(k)))for i in r) def C(b): q,S=[([],0)],[] while q: r,c=q.pop(0);L=len(b) if all(a==sum(j)for a,j in zip(b,zip(*r)))and r:yield r if c==L:continue if not b[c]:q+=(r,c+1),;continue for i in{*R(1,b[c]+1)}-{j for k in r for j in k}: for g in R(1,L+1): k=[0]*L;k[c]=i;I=1 while I*g+c<L or-I*g+c>=0: if-I*g+c>=0:k[-I*g+c]=i if I*g+c<L:k[I*g+c]=i I+=1 if all(a>=sum(j)for a,j in zip(b,zip(*r+[k])))and not M(r,k)and T(r+[k])not in S: q+=(K:=r+[k],c+1),;S+=T(K), if b[c]>sum(j[c]for j in K):q+=(K,c), ``` [Try it online!](https://tio.run/##fVBNj9owEL3zK1z1gE0GFEIpEGouPaGwlwVOaQ4hBNZJcEIIKrur/e107CR0A1VlyR6/N28@XvZavKRyMM7y647/uib@YbP1ycaW4aWgP@mGgcm@cLP1DCtYwxPPfbkP4ZTmRbiFKvtit9u9KBWSHvyMnoocLoz1EgxERttmm9WJOcS2L1@pnyQ04twhuzQnEThESPKGuWsqGKxpzBhTjFB4zlrbcEfUKHaLHGHJXep6OJUHrtciv19EEpIjUlg94MdelmbUZNMFT0KJGsTFjqiGPuen84FGurQPUd10A@ru5NjUl1uS268iTPAtlQHnCztIZSHkOSwhmRZk4waefTQ4xaZGn8H0U0o9@nvnmfZBZWLGR/c90kyslyo3V2H8oWbX/736K80CBRolMXdNr7OYxliFi@mc9zVcbj3v7I3gx4KkeVeHM26WKpzyLxK7ZYz6mqyVyDWpuVE1qD2b/d8zw429yjflyhPaEevfipacQlGzrOZSjjk211xl3NLgK@owuM2mDJvprhjcbHKYttuBgME1y4Us6I66JvTxNG6cp9XkG4jKsRqIBROw4HuZ9/UGK3AMIxgo6pHsm5ob47F0QbISh/BE0nNRlW532x3L/NRo0mg7gYf/v5A7zMSegwYyeFhR50DjvrPAQuwbDHGzEYzvN2ueu8WHqBiieqL1IySvfwA) [Answer] # [Python](https://www.python.org), ~~157~~ 155 bytes *-2 bytes thanks to [@97.100.97.109](https://codegolf.stackexchange.com/users/113573/97-100-97-109)* ``` f=lambda p,n=1:all(x>=0for x in p)and(sum(p)<1or n<=max(p)and any(f([p-n*(i%h==o)for i,p in enumerate(p)],n+1)for h in range(1,len(p)+2)for o in range(h))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZJLboMwEIbVLaewVFWym4nEowSI4l4EsXAVU5DAWGAkcpZssmnv1J6mgymPxCOB__nmt0cD1299MUWjbrev3uT7-Oea80rUH2dBNCjuHUVV0eGdu3nTkoGUimgm1Jl2fU01O3mYVSdei4HaPBHqQnOa6r16peVLwXnDRmcJevRK1deyFUZidQZq51lYjKgV6lNSDyqpEO58S5qVFIyxqcXfp87IznSEk9QhuFIXPIy7ZwYbNIuR-P_imaQJ-BBDBAEcNlUWeK7Nxxj-Ykl9GC2H9cD5nSwb2G4fxCpdPDuYRXB_ObaI9A1CvCiCeNvVfWw8IVaG6EqsL0KQOc7yxey0jra2zDHFcXDZpMel21IZyqyWVScfSU4Hxpxp9vNv8gc) [Answer] # [Desmos](https://desmos.com/calculator), 220 bytes ``` m=l.max g(N,K,b)=mod(floor(bN/b^{[1...K]}),b) A=[1...m][g(a,m,2)=1] L=l.length B=A.length P=g(p,B,L)+1 M=P.max f(l)=0^{โˆ‘_{a=1}^{2^m}โˆ‘_{p=0}^{L^B}โˆ‘_{d=0}^{M^B}0^{โˆ‘_{i=1}^L(total(0^{mod(i-g(d,B,M)-1,P)}A)-l[i])^2}} ``` Guys please tell me if there is anything wrong... I have spent a while planning out this answer (I literally wrote out all my steps on a txt file before doing any of the desmos coding lol) but I may have missed some crucial details. Because of the very inefficient brute force methods used in this answer, it can only handle the smallest of test cases, so I went ahead to make some of my own. I did test those new test cases against other answers here to compare and they seem to match, so this gives me a little more confidence that this answer should mostly be correct. The test cases given in the question that the code could run in a reasonable amount of time also do match as well. As an aside, it actually did not come out as long as I expected; I was expecting at least 300 bytes when I initially started planning this out. [Try It On Desmos!](https://www.desmos.com/calculator/ncsuxgqlxx) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/2uslczl0w7) [Answer] # [Scala](https://www.scala-lang.org/), 202 bytes. Golfed version. [Try it online!](https://tio.run/##dZFRT4MwEMff9ynuRdIqkLElJkNYookPS/TJGB@WxVQoo6aUBjrDZHx2PGA@ILO5ptdf/73eXcuISdbmH588MvDMhIK6jXkCCdH@kyjNdqPMzlY@LqFH/Yc8l5ypULtJXjApyfs6nFPLItotD1ngnU5EBXiascqyatSQNHA8MDloV3K1N@mNd5cHzhwOyggJKT0KLuPuOfdb6Ddh0o2KeYUBdB2xkhNtCxqutaOuCRFXaRjm1I3yTLOCk4TJklPa2OrGo43LK0y4JCLmGNscKaUtQFdMhnURVuxLH@6Lgh23L6YQar@jPrwqYSCEegY4vpgEwzEGkq540lMY/LkNXm8XHGpfUI7hoFyM4cKGFUIbbif68W71Z4v3puQ/OOGY4BJtDJfnrHtGZ/2CHwikgsAZ2kLPfQIQCXJXlI@ZxkafIYDGthqpyC/h@D@Tw4RUdBA0s242s/YH) ``` def f(p:List[Int],n:Int=1):Boolean=p.forall(_>=0)&&(p.sum<1||(n<=p.max&&{for(h<-1 to p.length+1;o<-0 until h)yield f(p.zipWithIndex.map{case(p,i)=>p-n*((i%h==o).compare(false))},n+1)}.exists(identity))) ``` Ungolfed version. [Try it online!](https://tio.run/##dZJfS8MwFMXf@ynOiyPRWjYFwbkKCj4ICoKID0MkrukaSdPQZtKp@@zzJquT/RECSX733Nvbc9NMhBbLZfX2LicO90IZfEVAJnPkzA5xpxo3vjXuJYYZgg5IMeBDXFeVlsLQzctXCYXUVtZbWUXIilF1@6rKngrAh9CY2Uw4mT0Qtsmnss/KFbcmk21SCosvTEQjwWwMxZFewuIYBodgKmdM4QAF0hQV5wNITco@x6KrnrPf2tQEjugvQmAVtkle1UJr9orL1Gf1evSVpJmVGGGA728wg5HvqRRtCJIerMDomMKuooCWZuoKX/gCled9zIxTGgXHXEmdrf0hU8gP6oLzRLZkVcNUJknr5pz7rhZRN4KS5sFEPW2GuKprMR8/ulqZ6QvZ92SUW3vnnXOSChHx3rPun8O5H2MQ1p4Dj/coN@FKebIJT2KcE4xxtqPfvJ1vXSlvl/wHdzg1eEprE552XQfGo7CF6bR@CsEWvn5jKieeqOamtOR2B2n@ZKvThv0S/3h2gjlr@d@jWUSLaLn8AQ) ``` object Main { def f(p: List[Int], n: Int = 1): Boolean = { def helper(p: List[Int], h: Int, o: Int, n: Int): Boolean = { val updatedP = p.zipWithIndex.map { case (p, i) => p - n * (if((i % h == o))1 else 0) } f(updatedP, n + 1) } p.forall(_ >= 0) && (p.sum < 1 || (n <= p.max && (for (h <- 1 to p.length + 1; o <- 0 until h) yield helper(p, h, o, n)).exists(identity))) } def main(args: Array[String]): Unit = { val tests = List( List(0, 1, 1, 0, 1, 1, 0, 1, 1, 0), List(0, 1, 1), List(1, 1, 2), List(2, 9, 2, 6, 1), List(), List(9), List(9, 9), List(9, 9, 9), List(9, 9, 9, 9), List(0, 3, 3), List(3, 1, 1) ) for (x <- tests) { if (x.isEmpty) println() else println(f(x)) } } } ``` ]
[Question] [ Given a positive integer < 100 (from 1 to 99, including 1 and 99), output that many lockers. A locker is defined as the following: ``` +----+ | | | | | | | nn | +----+ ``` where `nn` is the locker number, in base 10. If there is 1-digit number, it is expressed with a 0 in front of it. For example, locker number 2 displays the number `02`. Lockers can be stacked, but only up to 2 high: ``` +----+ | | | | | | | on | +----+ | | | | | | | en | +----+ ``` `on` denotes an odd number, `en` an even number. Lockers can also be put next to each other. ``` +----+----+ | | | | | | | | | | 01 | 03 | +----+----+----+ | | | | | | | | | | | | | 02 | 04 | 05 | +----+----+----+ ``` Notice that locker number 5 is an odd-numbered locker that is on the bottom. This is because when you have odd-numbered input, the last locker should be placed on the floor (because a hovering locker costs too much). The above example therefore is the expected output for n=5. n=0 should return an nothing. **Rules:** Standard methods of input/output. Input in any convenient format, output as a string. Standard loopholes apply. **Test cases:** ``` Input Output --------------------- 1 +----+ | | | | | | | 01 | +----+ --------------------- (newlines optional in case 1) 4 +----+----+ | | | | | | | | | | 01 | 03 | +----+----+ | | | | | | | | | | 02 | 04 | +----+----+ --------------------- 5 +----+----+ | | | | | | | | | | 01 | 03 | +----+----+----+ | | | | | | | | | | | | | 02 | 04 | 05 | +----+----+----+ --------------------- 16 +----+----+----+----+----+----+----+----+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | 01 | 03 | 05 | 07 | 09 | 11 | 13 | 15 | +----+----+----+----+----+----+----+----+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | 02 | 04 | 06 | 08 | 10 | 12 | 14 | 16 | +----+----+----+----+----+----+----+----+ ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # [Pyth](https://github.com/isaacg1/pyth), 66 bytes ``` A.[Y2m+.rKXJr6j" | "++km.[\02`kdkjkUT;" -|+"+*3]KJ_.T_McSQ2js[GHhH ``` [Test suite.](http://pyth.herokuapp.com/?code=A.%5BY2m%2B.rKXJr6j%22+%7C+%22%2B%2Bkm.%5B%5C02%60kdkjkUT%3B%22+-%7C%2B%22%2B%2a3%5DKJ_.T_McSQ2js%5BGHhH&test_suite=1&test_suite_input=1%0A4%0A5%0A16&debug=0) [Answer] # Python 2, ~~201~~ ~~191~~ ~~185~~ ~~175~~ ~~171~~ ~~166~~ ~~164~~ 163 bytes ``` n=input() for j in 0,1:c=n/2+n%2*j;m='+----'*c+'+\n';print['\n',m+('| '*c+'|\n')*3+''.join('| %02d '%-~i for i in range(j,n-n%2,2)+n%2*j*[~-n])+'|\n'+m*j][c>0], ``` [Try it Online!](https://tio.run/nexus/python2#JY3LDoMgFET3/Qo25AoXWsRdDf0RyqKxj0DC1Ri7M/66hTqryZxkzk4u0vRdGnF6jzNLLBIzqr0Oji4WiVuZ@uwAdQnIAQHvBP00R1o8lKoyNrCykj9dyyRkhwDnNEaqiBv7ZMD1Flk1xGqYH/R5NUmRLgZlxSGSftMUxPGCWabgh5sJat/bHw) [Answer] # PHP, 191 Bytes ``` for(;a&$k="01112344453"[$i++];print"$l\n")for($l="",$b="+||"[$k%3],$n=0;$n++<$a=$argn;)$l.=$i<6&$n%2&$n!=$a|$i>5&($n%2<1|$n==$a)?($l?"":"$b").["----+"," |",sprintf(" %02d |",$n)][$k%3]:""; ``` [Try it online!](https://tio.run/nexus/php#JY7BDoIwEETvfgVOFkJTJJSCB0rlQ5ADxKANpBL02H/HgnPYw9vZma2b5bWcqF@fVstSbeN7jVUf0aSRCSFyWRRFKdGS4bxTy2rsFzTfLdjupFkDCQ0a3DlvmkLZJWR1pshyXlOvj2TFaE41mfoakQ1zP85@4cjcyijeSS2cv/KMNT6zASrQAJa2uHhxJAi8HJLP8cEYIwiz/LETsqz7F1eA2rYf "PHP โ€“ TIO Nexus") # PHP, 235 Bytes ``` for(;$i++<$a=$argn;)$r[$i==$a|1-$i&1][]=($p=str_pad)($i,2,0,0);for(;$j<6;)$l[]=($a<2&$j<3?"":[$p("+",$c=($j<3?floor:ceil)($a/2)*5+1,"----+"),$p("|",$c," |"),"| ".join(" | ",$r[$j/3])." |"])[$j++%3]."\n";echo strtr("01112344453",$l); ``` Case 1 with optional newlines [Try it online!](https://tio.run/nexus/php#JY7NjsMgDITvfYrI8lZQaBpC2pVKUB8kiyqU/hFFAbE95t2zTtcnz@cZa9pLeqUN@vyc7LdZHjEzg0GIFr39UMMxdxgsqVntMWyV65xlmOzvO1@Tv3GGQdaykhU3//GhPVFq/Nh8W28J6AvAucPEQIDEng4re4wx5nN/DyM98Yea745CSdjTCOBytc@rXUJBMxOCuYByiGFiUNAq127DQTtekgbHSQnxpV0JPxOYe/@KBdV8ZwaVUqrWTdMcNcVGbpblDw "PHP โ€“ TIO Nexus") Expanded ``` for(;$i++<$a=$argn;) $r[$i==$a|1-$i&1][]=($p=str_pad)($i,2,0,0); # make an 2D array 0:odd values 1:even values and last value for(;$j<6;) # create 6 strings for each different line $l[]=($a<2&$j<3 # if last value =1 and line number under 3 ?"" # make an empty string empty [] as alternative :[$p("+",$c=($j<3 # else make the 0 or 3 line and store the count for next line ?floor # if line number =0 count=floor ($a/2) multiply 5 and add 1 :ceil)($a/2)*5+1,"----+") # else count= ceil($a/2) multiply 5 and add 1 ,$p("|",$c," |") # make lines 1 and 4 ,"| ".join(" | ",$r[$j/3])." |"])[$j++%3]."\n"; #make lines 2 odd values and 5 even values and last value echo strtr("01112344453",$l); # Output after replace the digits with the 6 strings ``` # PHP, 300 Bytes ``` for(;$i++<$a=$argn;)$r[$i==$a||!($i%2)][]=($p=str_pad)($i,2,0,0);echo strtr("01112344453",($a>1?[$p("+",$c=($a/2^0)*5+1,"----+")."\n",$p("|",$c," |")."\n","| ".join(" | ",$r[0])." |\n"]:["","",""])+[3=>$p("+",$c=ceil($a/2)*5+1,"----+")."\n",$p("|",$c," |")."\n","| ".join(" | ",$r[1])." |\n"]); ``` replace `["","",""]` with `["\n","\n","\n"]` if you want newlines for case `1` [Try it online!](https://tio.run/nexus/php#pY5NbgIxDIX3PUVquVJCAk3mZ0MIHCRNq2iYliA0E6Usc/epQUIcoJYX9ntP/rw75FN@wVh@Jmd6u3zPhVtMUu4wurtsBRaPydFW6yvH9NaI4IPjmN3vtXzleBSkqkZppYUdh9PMSL8WDtoY07Rd1/UtKI5xbw4eMwcJCgc6EN@bTy1WvTQK1lQSxAY@JnIpVG8hBYyqPnSoDDbnOU0cGI2KPtOBPFbJDVsPFLl1ENK3bv9kDWO63Hn/pJknTdhl@QM "PHP โ€“ TIO Nexus") [Answer] # Ruby, ~~256~~ ~~239~~ ~~201~~ ~~191~~ 183 bytes ``` n=gets.to_i;a=n/2;z=a+n%2;t=a*2;q="+----+";r=->x{q*x+?\n+("| |"*x+?\n)*3+"| n |"*x+?\n};u=r[a]+r[z]+q*z;n.times{|i|j=2*i+1;u[?n]="%02d"%(i<a ?j:i>=t ?j-t:j-t+1)};puts u.squeeze'+|' ``` This is awfully long. I'll work on golfing it more. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~426~~ ~~335~~ ~~300~~ ~~294~~ ~~282~~ ~~252~~ ~~249~~ ~~246~~ ~~244~~ 237 bytes This really needs to be golfed down ``` #define L puts("") #define P(s)printf(&s[i>1] #define F(x)for(i=0;i++<x;)P( #define O(x,y)F(x)"+----+"));for(j=0;L,j++<3;)F(x)"| |"));j=y;F(x)"| %02d |") e,i,j;f(n){e=n/2+n%2;O(n/2,-1),j+=2);L;O(e,0),j+=i^e?2:2-n%2);L;F(e)"+----+"));} ``` [Try it online!](https://tio.run/nexus/c-gcc#jc/Pa8IwFAfwe/6KEnG8RxOWpM7Dsm43TwW9bw5EE0xhUayDivpn79wl1blRelgOj@R9P/nVDFbGOm@SItl@7iugFMlPawYVbnfO7y3cVa/uWc5v0QRqtJsduFxol6ZPtcYZ3NIp1OyA0dCUh5FSRB15GXjByrAh05f8lIRxinmZH/S1NRRqFZvEMMdKbcHj0eT@XqV@qPQUwoxxieGgXKEuQscw0S7du3lRj4oHF4MJmL9PODcfC@cByTHeSmKxIFC3s8v333zUXLSV02tmQfYp2VWqT6muyvpU1lWjPjXqqod/KTnuYXL8y8i5@fIbvlws1@Yb "C (gcc) โ€“ TIO Nexus") [Answer] ## Batch, 305 bytes ``` @echo off set/a"n=%1&-2 if %1 gtr 1 call:l %n% 1 call:l %1 2 echo %s: =-% exit/b :l set s=+ set "t=| for /l %%i in (%2,2,%n%)do call:c %%i if %1 gtr %n% call:c %1 for %%s in ("%s: =-%" "%s:+=|%" "%s:+=|%" "%s:+=|%" "%t%")do echo %%~s exit/b :c set s=%s% + set i=0%1 set "t=%t% %i:~-2% | ``` `+----+` and `| |` are both similar to `+ +` in that they can be generated via a single substitution, and it turns out to be slightly shorter than generating them separately (the extra quoting needed for `|`s doesn't help). [Answer] # Pyth - ~~97~~ ~~74~~ ~~86~~ ~~80~~ 75 bytes ``` V3K+:?&NtQ2 1Q2?NQYIlK+*+\+*\-4lK\+IqN2BFTU4+sm?qT3.F"| {:02d} "d+\|*\ 4K\| ``` [Try it here](https://pyth.herokuapp.com/?code=V3K%2B%3A%3F%26NtQ2+1Q2%3FNQYIlK%2B%2a%2B%5C%2B%2a%5C-4lK%5C%2BIqN2BFTU4%2Bsm%3FqT3.F%22%7C+%7B%3A02d%7D+%22d%2B%5C%7C%2a%5C+4K%5C%7C&input=15&debug=0) [Answer] # JavaScript ES6, 224 bytes ``` n=>(r=(s,k)=>s.repeat(k),s="",[0,1].map(i=>(c=(n/2+n%2*i)|0,c&&(s+="+"+r(l="----+",c)+` |`+r(r(" |",c)+` |`,3),[...Array(c).keys()].map(j=>s+=` ${(h=2*j+(i+!(i&j>c-2&n%2)))>9?h:"0"+h} |`),s+=` `+(i?`+${r(l,c)} `:"")))),s) ``` Used some ideas from [math junkie's Python answer](https://codegolf.stackexchange.com/a/117804/69583) ## Test Snippet ``` f= n=>(r=(s,k)=>s.repeat(k),s="",[0,1].map(i=>(c=(n/2+n%2*i)|0,c&&(s+="+"+r(l="----+",c)+` |`+r(r(" |",c)+` |`,3),[...Array(c).keys()].map(j=>s+=` ${(h=2*j+(i+!(i&j>c-2&n%2)))>9?h:"0"+h} |`),s+=` `+(i?`+${r(l,c)} `:"")))),s) O.innerHTML=f(I.value); ``` ``` <input id="I" value="5" type="number" min="0" max="99" oninput="O.innerHTML=f(this.value)"> <pre id="O"></pre> ``` ## Cleaned up ``` n => { r=(s,k)=>s.repeat(k); s=""; [0,1].map(i => { c = (n/2 + n%2 * i)|0; if (c) { s += "+" + r(l="----+", c) + "\n|" + r(r(" |",c) + "\n|", 3); [...Array(c).keys()].map(j => { s += ` ${(h = 2*j + (i + !(i & j>c-2 & n%2))) > 9 ? h:"0"+h} |`; }); s += "\n" + (i ? `+${r(l,c)}\n` : ""); } }); return s; }; ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` ๏ผฎฮธ๏ผฆโ€ฆยทยนฮธยซ๏ผฆโตยฟ๏นชฮนยฒยฟโผฮนฮธโ†’โ†—โ†“๏ผขโถยฑโถโ†—โ†’โ†’0๏ผฐโ†โฎŒ๏ผฉฮนโ†โ†โ†™ ``` [Try it online!](https://tio.run/##dY7LCsIwEEXX@hWDqwlUUEEXuvOxEFSk4AfEOq2BmLR5VEH89mi0iCIu7zl3HtmRm0xzGcJSld5t/GlPBis2aefaAC5VJr0VNaVcFYT9BCrG4NpuPe2QgcgB1/rgpUaRwIC9yKLyXNpIYn2ta8JxKoqjY0DSUkN25S@b67N6HG9N9QVHCWyo4I5wxCL7nnqDd9waoVyTE@j0Os@Ol06UL7Oi/CFSqslYwhm3DgX7WB39vxQfa8gthP4wdGt5Bw "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฎฮธ ``` Input the number of lockers into `q`. ``` ๏ผฆโ€ฆยทยนฮธยซ ``` Loop over the lockers from `1` to `q` inclusive. ``` ๏ผฆโตยฟ๏นชฮนยฒยฟโผฮนฮธโ†’โ†—โ†“ ``` Calculate the direction to the next locker, and repeat that 5 times (golfier than using jump movements). ``` ๏ผขโถยฑโถ ``` Draw the locker, starting at the bottom left corner. (The bottom right corner also takes 4 bytes while the top right corner takes 5. The top left corner only takes 3 bytes but then the locker number would take longer to draw.) ``` โ†—โ†’โ†’0 ``` Draw the leading zero of the locker number, if necessary. ``` ๏ผฐโ†โฎŒ๏ผฉฮน ``` Draw the locker number reversed and right-to-left, effectively right justifying it. ``` โ†โ†โ†™ ``` Move back to the bottom left corner ready to calculate the direction to the next locker. Edit: Later versions of Charcoal support this 32-byte solution: ``` ๏ผฆโชชโ€ฆยทยน๏ผฎยฒยซ๏ผฆโฎŒฮนยซโ†—โ†’โ†’0๏ผฐโ†โฎŒ๏ผฉฮบโ†–โ†–โ†–โ†‘๏ผต๏ผฒโถยป๏ผญโตฯ‡ ``` [Try it online!](https://tio.run/##lY/LDoIwEEXX8BUNq2mCCZjgQpeuSNQYDB9QyQCNtTSl7cbw7ZWHr63Le86dm0zVMl11THhfd5rARQluIJeVsD13WDDZIKQxyaWy5mTvV9RAaUzWlJJHGMw3BTrUPQJfWHDsHMK2VAVvWkN3H/LNZ82leYGYREm0tKwwXC3qgPVo3st71hu4UfozVqqp8ieYQ4GVGd8SCJspD@Gis5ikyQgG79PMr5x4Ag "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฆโชชโ€ฆยทยน๏ผฎยฒยซ ``` Take the numbers from `1` to the input number inclusive pairwise. (If the input number is odd the last array will only have one element.) ``` ๏ผฆโฎŒฮนยซ ``` Loop over each pair in reverse order. ``` โ†—โ†’โ†’0 ``` Draw the leading zero of the locker number, if necessary. ``` ๏ผฐโ†โฎŒ๏ผฉฮน ``` Draw the locker number reversed and right-to-left, effectively right justifying it. ``` โ†–โ†–โ†–โ†‘๏ผต๏ผฒโถ ``` Move to the top left of the locker and draw it. This is also the bottom left of the next locker, so we're ready to draw the second locker of the pair if applicable. ``` ยป๏ผญโตฯ‡ ``` Move to the next pair of lockers. (This should be before the inner loop for a saving of 1 byte but Charcoal generates incorrect output for an input of 1 for some reason.) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 127 bytes ``` ยฝโŒŠ:\+4-*\++,3(:\|4๊˜*\|+,)?ษพ'โˆทnโฐโ‰ โˆง;ฦ›S:โ‚ƒ[0p]`| `pรฐ+;แน…\|+,?ยฝโŒˆ:\+4-*\++,3(:\|4๊˜*\|+,)?ษพ'โ‚‚nโฐ=nโˆทโˆงโˆจ;ฦ›S:โ‚ƒ[0p]`| `pรฐ+;แน…\|+,?ยฝโŒˆ:\+4-*\++, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%BD%E2%8C%8A%3A%5C%2B4-*%5C%2B%2B%2C3%28%3A%5C%7C4%EA%98%8D*%5C%7C%2B%2C%29%3F%C9%BE%27%E2%88%B7n%E2%81%B0%E2%89%A0%E2%88%A7%3B%C6%9BS%3A%E2%82%83%5B0p%5D%60%7C%20%60p%C3%B0%2B%3B%E1%B9%85%5C%7C%2B%2C%3F%C2%BD%E2%8C%88%3A%5C%2B4-*%5C%2B%2B%2C3%28%3A%5C%7C4%EA%98%8D*%5C%7C%2B%2C%29%3F%C9%BE%27%E2%82%82n%E2%81%B0%3Dn%E2%88%B7%E2%88%A7%E2%88%A8%3B%C6%9BS%3A%E2%82%83%5B0p%5D%60%7C%20%60p%C3%B0%2B%3B%E1%B9%85%5C%7C%2B%2C%3F%C2%BD%E2%8C%88%3A%5C%2B4-*%5C%2B%2B%2C&inputs=17&header=&footer=) This is horrible. ]
[Question] [ # Introduction The [Dragon's Curve](https://en.wikipedia.org/wiki/Dragon_curve) is a fractal curve that notably appears on section title pages of the Jurassic Park novel. It can very simply be described as a process of folding a paper strip, as explained in the Wikipedia article about this curve. The first few iterations of the generation of this curve look like this (credits to Wikipedia for the image): ![enter image description here](https://i.stack.imgur.com/J7bZL.gif) # The challenge Write a program or function that, given an integer n as input, outputs the n-th iteration of the dragon curve as ASCII art using only the symbols `_` and `|` * You have to output the figure using only `|`, `_` and spaces. You may not output the curve as a plot or anything else. * You can take the input as a program argument, in STDIN or as a function parameter. * Inputs will always be an integer >= 0. Your program should work for reasonable values of inputs, 12 being the highest in the test cases offered. * The first iterations shall look like this + Iteration 0 is ``` _ ``` + Iteration 1 is ``` _| ``` + Iteration 2 is ``` |_ _| ``` * One trailing line at the end is ok. No trailing spaces allowed besides filling the line up to the rightmost character in the curve * No standard loopholes abuse as usual # Test Cases * Input `0` Output ``` _ ``` * Input `3` Output ``` _ |_| |_ _| ``` * Input `5` Output ``` _ _ |_|_| |_ _ _| _| |_|_|_ |_|_| |_ _|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_| |_| |_|_|_| |_|_|_| |_|_|_|_|_|_|_|_|_|_|_| |_|_|_| |_|_|_|_|_|_ _ _|_| _|_| _|_|_|_|_|_|_|_|_|_| _|_| _|_|_|_|_|_|_|_| |_| |_| |_| |_|_|_|_|_|_|_|_ |_| |_| |_|_|_|_|_|_ _ _|_|_|_|_|_|_|_| _|_|_|_|_|_|_|_| _ |_|_|_|_|_| |_|_ _ |_|_|_|_|_| |_|_ _|_| _|_|_|_| _|_| _|_| _|_|_|_| _|_| |_|_ _|_|_|_|_ |_| |_|_ _|_|_|_|_ |_| _|_|_|_|_|_|_|_| _|_|_|_|_|_|_|_| |_| |_|_|_| |_|_ |_| |_|_|_| |_|_ _|_| _|_| _|_| _|_| |_| |_| |_| |_| ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. [Answer] # Ruby, ~~239~~ 201 bytes This is a lambda function which should be called in the same manner as the one in the ungolfed version. Golfing improvements include: assignment of `8<<n/2` to a variable for re-use; `upto` loop instead of `each` loop; ternary operator instead of `if..else..end`; use of `[y,y+=d].max` to calculate where to print the `|`; use of `?_` and `?|` instead of the equivalent `'|'`and `'_'`; and elimination of redundant `%4` (thanks Sp3000.) ``` ->n{a=Array.new(m=8<<n/2){" "*m} p=q=1+x=y=m/2 r=3 1.upto(1<<n){|i|d=(r&2)-1 r%2>0?(a[y][x+=d]=?_ x+=d):(a[[y,y+=d].max][x]=?| p=x<p ?x:p q=x>q ?x:q) r+=i/(i&-i)} a.delete(a[0]) puts a.map{|e|e[p..q]}} ``` It relies on the following formula from Wikipedia: > > First, express n in the form k\*(2^m) where k is an odd number. The direction of the nth turn is determined by k mod 4 i.e. the remainder left when k is divided by 4. If k mod 4 is 1 then the nth turn is R; if k mod 4 is 3 then the nth turn is L. > > > Wikipedia gives the following code: > > There is a simple one line non-recursive method of implementing the above k mod 4 method of finding the turn direction in code. Treating turn n as a binary number, calculate the following boolean value: > `bool turn = (((n & โˆ’n) << 1) & n) != 0` > > > I improved this to `i/(i&-i)%4` which uses the same technique of using the expression `i&-i` to find the least significant digit but my expression gives 1 (for left turn)or 3 (for right turn) directly, which is handy as I track direction as a number `0..3` (in order north, west, south, east for golfing reasons.) **Ungolfed original in test program** ``` f=->n{ a=Array.new(8<<n/2){" "*(8<<n/2)} #Make an array of strings of spaces of appropriate size p=q=1+x=y=4<<n/2 #set x&y to the middle of the array, p&q to the place where the underscore for n=0 will be printed. r=3 #direction pointer, headed East (1..1<<n).each{|i| #all elements, starting at 1 d=(r&2)-1 #d is +1 for East and South, -1 for West and North if r%2>0 #if horizontal a[y][x+=d]='_' #move cursor 1 position in direction d, print underscore, x+=d #and move again. else #else vertical a[(y+([d,0].max))][x]='|' #draw | on the same line if d negative, line below if d positive y+=d #move cursor p=x<p ?x:p #update minimum and maximum x values for whitespace truncation later q=x>q ?x:q #(must be done for vertical bars, to avoid unnecesary space in n=0 case) end r=(r+i/(i&-i))%4 #update direction } a.delete(a[0]) #first line of a is blank. delete all blank lines. puts a.map!{|e|e[p..q]} #use p and q to truncate all strings to avoid unnecessary whitespace to left and right. } f.call(0) f.call(2) f.call(3) f.call(11) ``` [Answer] # Python 2, ~~270~~ 222 bytes ``` y=X=Y=0 i=m=x=1 D={} k=2**input() while~k+i:j=Y+(y>0);s={2*X+x};D[j]=D.get(j,s)|s;m=min(m,*s);Y+=y;X+=x;exec i/(i&-i)*"x,y=y,-x;";i+=1 for r in sorted(D):print"".join(" | _"[(n in D[r])+n%2*2]for n in range(m,max(D[r])+1)) ``` Now using the formula for the nth turn. I saw the `(((n & โˆ’n) << 1) & n)` formula on Wikipedia, but didn't realise how useful it was until I saw it in [@steveverrill's answer](https://codegolf.stackexchange.com/a/53064/21487). I actually drop the `%4` as well, so there's a lot of rotating going on, making larger inputs take a while. --- Side remark: This isn't graphical output, but here's some golfed turtle code: ``` from turtle import* for i in range(1,2**input()+1):fd(5);lt(i/(i&-i)*90) ``` [Answer] ## C#, 337 bytes There's a bit of rules abuse here. There's no restriction on leading space. Unfortunately, the canvas is finite, so there is an upper limit for *n*. Indented for clarity: ``` using C=System.Console; class P{ static void Main(string[]a){ int n=int.Parse(a[0]),d=2,x=250,y=500; var f="0D"; while(n-->0) f=f.Replace("D","d3t03").Replace("T","10d1t").ToUpper(); C.SetBufferSize(999,999); foreach(var c in f){ n=c&7; d=(d+n)%4; if(n<1){ var b=d%2<1; x+=n=b?1-d:0; y+=b?0:2-d; C.SetCursorPosition(x*2-n,y+d/3); C.Write(b?'_':'|'); } } } } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~65~~ 64 bytes[SBCS](https://github.com/abrudz/SBCS) ``` ('_|'โดโจโ‰ขa)@aโดโˆ˜''โŠƒ1+โŒˆ/aโ†(โŠข-โŒŠ/)โŒˆ2+/รทโˆ˜ยฏ2 1ยจ11 9โˆ˜โ—‹ยจ+\0,(โŠข,0j1ร—โŒฝ)โฃโŽ•,1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862tP@a6jH16g/6t3yqHfFo85FiZoOiSBOxwx19UddzYbaj3o69BOBqjUedS3SfdTTpa8JFDHS1j@8Hajm0HojBcNDKwwNFSyBvEfTuw@t0I4x0AGp1THIMjw8/VHPXs1HvYuBVuoY/gda9z@Ny4BLXZ0rjcsQQhlBKGMIZQqVg6kx4gIA "APL (Dyalog Unicode) โ€“ Try It Online") `(โŠข,0j1ร—โŒฝ)โฃโŽ•,1` generates a list of steps as complex numbers. It starts from `1` and repeatedly appends (`,`) a reversed (`โŒฝ`) copy of the list multiplied by `0j1`=sqrt(-1). `+\0,` prepend 0 and compute prefix sums `11 9โˆ˜โ—‹ยจ` decompose complex into (real;imaginary) pairs `รทโˆ˜ยฏ2 1ยจ` divide the real parts by -2 `2+/` sums of adjacent pairs `โŒˆ` ceiling `(โŠข-โŒŠ/)` subtract the minima from all, so that coords are non-negative `aโ†` assign to `a` `โดโˆ˜''โŠƒ1+โŒˆ/` create an empty char matrix such that the max coords can fit `('_|'โดโจโ‰ขa)@a` put alternating `_` and `|` at the coordinates from `a` [Answer] # JavaScript (ES6), 220 Using the wikipedia formula for left and right turns. ``` n=>(d=>{for(i=x=y=d;i<1<<n;d+=++i/(i&-i))z=d&2,(w=d&1)?y+=z/2:x+=1-z,g=x<0?g.map(r=>[,,...r],x=1):g,g=y<0?[y=0,...g]:g,r=g[y]=g[y]||[],r[x]='_|'[w],w?y-=!z:x+=1-z})(0,g=[])||g.map(r=>[...r].map(c=>c||' ').join``).join` ` ``` *Less golfed* ``` n=>{ g=[]; for(i=x=y=d=0;i<1<<n;d+=++i/(i&-i)) z=d&2, (w=d&1)?y+=z/2:x+=1-z, g=x<0?g.map(r=>[,,...r],x=1):g, g=y<0?[y=0,...g]:g, r=g[y]=g[y]||[], r[x]='_|'[w], w?y-=!z:x+=1-z return g.map(r=>[...r].map(c=>c||' ').join``).join`\n` } ``` ``` F= n=>(d=>{for(i=x=y=d;i<1<<n;d+=++i/(i&-i))z=d&2,(w=d&1)?y+=z/2:x+=1-z,g=x<0?g.map(r=>[,,...r],x=1):g,g=y<0?[y=0,...g]:g,r=g[y]=g[y]||[],r[x]='_|'[w],w?y-=!z:x+=1-z})(0,g=[])||g.map(r=>[...r].map(c=>c||' ').join``).join` ` function update() { var n=+I.value O.textContent=F(n) } update() ``` ``` pre { font-size: 8px } ``` ``` <input id=I value=5 type=number oninput='update()'><pre id=O></pre> ``` ]
[Question] [ If you haven't played the game [Baba is You](https://hempuli.com/baba/), I think you [really](https://www.youtube.com/watch?v=YH0NR1kmMUo) should. Whether youโ€šร„รดve played it or not, have a go at implementing it as a code golf. The idea behind this challenge is to have a bit more complicated, non-standard task with a bit longer answers. ## Game rules Alas, the challenge is not to implement [the entire game](https://www.youtube.com/watch?v=Jf5O8S5GiOo), impressive though that may be (I'm sure there is a single 05ab1e instruction for it. If not, someone should submit an issue. It's a gross omission from the language ๏ฃฟรผรฒรข). This will be a simplified version of the game: * There are only 3 entities: `Baba`, `Rock` and `Flag` and the corresponding nouns (*lowercase* `baba`, `rock` and `flag`) * There is only one operator - `is` * There are only 3 properties: `you`, `win` and `push` * Everything is always `stop` (N.b. `stop` is not a property which exists on the board) This prevents anything from overlapping and makes the management of the game grid simpler. * *Because* everything is always `stop`, there is an alternate win condition. You can win if: + `noun is you` and `noun is win` -- just like in the original + `noun` which is `you` attempts to push something which is `win`, but that something cannot move (whether because it's not `push`, or it is `push` and is somehow blocked form moving). See examples for more details. * Just like in the main game text (nouns `you`, `win` and `push` and the operator `is`) are always `push` * There is only one level. This one: ``` . . . . . . . . . . . . . . r i p . . . . R R R . . . . . . . . . R . . . R . . b i y . B . R . F . R . . . . . . . . R . . . R . . f i n . . . . R R R . . . . . . . . . . . . . . . ``` where uppercase letter correspond to entities and lowercase to their respective nouns. `.` is empty, `p` is `push`, `y` is `you` and `n` is `win` (originally I've implemented walls, and there was a namesake crash so I've made win `n` instead). * The grid is parsed for rules just like in the original game. There are two types of rules: + `noun is property`, for example `baba is you` or `flag is push`. These type of rules are referred to as *behaviours*. + `noun is noun`, for example `baba is rock`. These type of rules are referred to as *swaps*. Since this grid does not have two of any of the nouns, one does not have to worry about the case like `rock is rock` (which would, otherwise, affect the execution of other rules) * The rules work only from left to right, and from top to bottom. * The only allowed moves are up, down, left and right. No idle, no undo. * When a move is made, every entity which is `you` attempts to move in the direction specified. * The order of actions in a single step is as follows: + Search the grid for all the current rules + Parse the rules into behaviours and swaps + Apply all the swaps to the grid in an alphabetical order *(Only one swap per cell)* + Perform an action for the turn according to the behaviours Here is an example game where the rule `rock is push` has been changed into `rock is win`. ![rock_is_win](https://raw.githubusercontent.com/MarcinKonowalczyk/baba/master/animation/gifs/rock_is_win.gif) ## Golfing challenge rules Your task is to implement the above game of Baba is You, using the smallest number of source code bytes (the usual). Your program will take a sequence of moves as an input, and output `1`, or `True`, or otherwise something meaningful if this sequence of moves leads to a victory on the above grid (and only on this grid. Just hardcode it in). Otherwise, the program will output `0`, or `False` or nothing. You can assume that every sequence of moves is a *valid* sequence in any format. I've used symbols `^V<>^` for example, but you're most welcome to assume it's `udlr` instead. You can assume any input sequence either ends on a win, or does not lead to one. This means you do not have to worry about there being any more moves past the winning one. If such sequence is passed to your program, it's an undefined behaviour and your program can do anything. I've implemented this version of the game in python. You can find it [here](https://github.com/MarcinKonowalczyk/baba). Some of the more tricky behaviour is specified in the readme (If you find any weird edge cases I haven't thought of let me know or send me a PR). There is a minimal self-contained version of the code in `/golf/golfing_full.py` and the abbreviated version in `/golf/golfing_short.py`. The sum total comes to 1930 bytes (sans the test at the end). ## Test cases ``` - Fastest win 1: >>^>>V - Fastest loss (you don't actually have to check for loss explicitly) 0: <^<V - Baba is win 1: <VV<V<<^V>>^< - Rock is baba 1: <^^^<<V>V<>> - Rock is you 1: <^^^<<V^<<VV>><<^>><< - Rock is win 1: <VVV<^<^>V>^^V<<<<^^^>^>>>>VVV<^>>> - Rock is win but also push 1: <^<<<<V>>>V>VV<<^^^>^<VV>>V<V<^^>^<V>>>>>>>V<^^^^>^<<<<<<<<< - Baba is flag 0: <V<<<<V>>V>^^>>^^>>^>>V - Baba is you is win 0: <V<<<<V>>V>>^^VV>^^ - Flag is rock is win 1: <V<<V^<V>>>^^<^>^^<<V^<<VV>>>^>VVVV^^^<<<<^>>^>VVVV>>V^<<V>>^^>> - Flag is rock is win, but win on what used to be the flag 1: >VV>^^<^>V>^VV<<<<<<<V^>V>>^>V^^<<^>^^<<V^<<VV>>>^>VVVV^^^<<<<^>>^>VVVVV^^>>>>>> - Rules don't work upside down 0: <V<<<<V>>V>>>^V<<<^>V>>^V<<^>V>>^^^>>^>>V - Rules don't work backwards 0: <V<<<<V>>V>>>^V<<<^>V>>^V<<^>><^^^>V>V<^<V<VV>>>>^<<<>^^>>^>>V - Rules (swaps) are applied alphabetically 1: <^<<<<V>>^<<^^>>V^<<VV>>^><V><V><<<VVV>^^<^>>V>^^<^>VVV>VV<<^^^<^>V>^<^>><<V<<^>>>>>V<^<VV<< - Rules (swaps) are applied alphabetically, case 2 1: <^<<<<V>>^<<^^>>VV<V>V>>VV<<^V<<^>^^^<^>^>VV>V<V<V>^^>V>V>>>^^<< - Rock is baba is flag 0: <^^^<<V^<<V><VVVVV>>^V<<^>^<^>< - Rock is baba is flag, case 2 0: <^^^<<V^<<V>>>><<<V>>><<<<VVVV>>^V<<<^^>>>><<<<V>>>><<<<^^>>>>< - Walk into the corner for a while and make a circle around the board 1: VVVV>>>>>>>>^^^^^^^>^^>^>^<<<<<<<<<<<<<VVVVVVV^^>>>>>>>>^> - Win at the last moment 1: >>V>V<<<V<<<^V<<^><^^^^^>>V^<<V><VV>< ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~707~~ ~~646~~ 615 bytes ``` e=enumerate S=eval(input()) exec('''g=[[int(k/10**i)%10FiIrange(11,-2,-1)]FkI[0,71800004440,40004,51902040304,40004,61000004440,0]];g[5][3]=10 R=lambda a,b:(4<a<8)*any([*r[i:i+3]]==[a,1,b]FrI[*g,*zip(*g)]Fi,pIe(r[2:])) FsIS: G=[[([b-3FbI(5,6,7)if R(c+3,b)]+[c])[0]FcIr]FrIg] F_I' '*s:G=[*zip(*G)][::-1] Fj,rIe(G): r=G[j]=[*r] Fk,CIe(G[j]): l=0 if R(C+3,9): Fi,cIe(r[:k]):l=(c<2or c>4or R(c+3,8))and[l,i+1][c<1] if l<1:0<k and R(r[k-1]+3,10)and E else:r[l-1:k]=r[l:k+1];r[k]=0 g=G F_Irange(s):g=[*zip(*g[::-1])] FaI5,6,7:R(a,10)and R(a,9)and E'''.replace("I"," in ").replace("F","for ")) ``` [Try it online!](https://tio.run/##lVVtb6M4EP7Or7A4nbBTN4Em6QsLllarTYV0Op1aiS8cVIS4WTYEOEM27f353owd0r02PelQAva8PPPMjF/a5/5bU09f5JMsHrpelfU6tG37RYay3m2lyntp3YfyR17Rsm53PWXMQlvqOM46TJKy7ulm4rmjUcl@9dxFGam8Xkvqefz8gp97LF1sosTlV961C89sNnP5DAd87t24F@7MncLY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t4Yg2X4Sg0vCGIvPke/QSYv/wA "Python 3 โ€šร„รฌ Try It Online") (all testcases, simulates stdin) Essentially a rewrite from the ground up, loosely based on MarcinKonowalczyk's `golfing_full.ipynb`. Takes input through STDIN as a list of integers, where 0,1,2,3 correspond to left, up, right, down respectively. Throws an error on win and does not throw on loss as per [this default](https://codegolf.meta.stackexchange.com/a/11908/68261). * -61 bytes: use integers instead of characters, take input through STDIN instead of as function, other small changes * -31 bytes: exec-replace on `for` and `in` ### Ungolfed ``` def grid_has_rule(grid, rule): return any(rule in ''.join(row) for g in [grid, zip(*grid)] for row in g) def print_grid(grid): print('\n'.join(''.join(row) for row in grid), end='\n\n') def play(sequence): grid = [[x for x in row] for row in '.............|.rip....RRR..|.......R...R.|.biy.B.R.F.R.|.......R...R.|.fiw....RRR..|.............'.split('|')] for step in sequence: # (clone) new_grid = [row*1 for row in grid] # Perform swaps # automatically alphabetical order because 'bfr' is sorted new_grid = [ [ ( [b.upper() for b in 'bfr' if grid_has_rule(grid,chr(ord(c)+ord('a')-ord('A'))+'i'+b)] # priorities "<c>ib", then "<c>if", then "<c>ir" +[c] # then no rule: c unchanged )[0] for c in row ] for row in grid ] # we can't modify grid because it stores the current rules # grid = new_grid # Step # re-orient new_grid until movement direction is left for _ in range(step): # rotate 90 CCW: transpose followed by reflect new_grid = [*zip(*new_grid)][::-1] for j, row in enumerate(new_grid): new_grid[j] = list(row) for k, cell in enumerate(new_grid[j]): if not grid_has_rule(grid,chr(ord(cell)-ord('A')+ord('a'))+"iy"): # cell is not you new_grid[j][k] = cell continue # try pushing left from (j, k) # might not be push: B,F,R # get the rightmost cell to the left which isn't push: last_unpushable_i = [i for i,c in enumerate(new_grid[j][:k]) if c in 'BFR' and not grid_has_rule(grid,c.lower()+'ip')] last_unpushable_i = last_unpushable_i[-1] if last_unpushable_i else -1 last_gap = [i for i,c in enumerate(new_grid[j][:k]) if c=='.' and last_unpushable_i<i] # (maybe slice from list(enumerate)) if not last_gap: # no gaps left, unpushable if k > 0: if grid_has_rule(grid, chr(ord(new_grid[j][k-1])-ord('A')+ord('a')) + 'iw'): # object can't move and is win return True new_grid[j][k] = cell else: # maybe del trick? L = last_gap[-1] new_grid[j][L:k] = new_grid[j][L+1:k+1] new_grid[j][k] = '.' grid = new_grid # revert orientation (maybe just take this-last instead) for _ in range(step): # rotate 90 CW: reflect followed by transpose grid = [*zip(*grid[::-1])] # I'm leaving this here for future debugging # print('<^>V'[step]) # print_grid(grid) # Check for you is win condition # Doesn't need to be at top because can't have yiw at start for a in 'bfr': if grid_has_rule(grid, a+'iw') and grid_has_rule(grid, a+'iy'): return True ``` ### Golfed, commented (old) ``` # does grid g have the rule u, either horizontally or vertically? R=lambda g,u:any(u in''.join(r)for g in[g,zip(*g)]for r in g) e=enumerate # main: play, given sequence S # "<^>v" --> [0,1,2,3] def P(S): # generate grid g g=[*map(list,['.'*13,'.rip....RRR..','.......R...R.','.biy.B.R.F.R.','.......R...R.','.fiw....RRR..','.'*13])] # for each step s for s in S: G=[ # create a new grid G, which consists of the swaps applied to g [ ( [b.upper()for b in'bfr'if R(g,chr(ord(c)+32)+'i'+b)]# priorities "<c>ib", then "<c>if", then "<c>ir" +[c])[0] # then no swap: plain c for c in r ] for r in g ] # rotate grid counter-clockwise s times until movement direction pointing left for _ in range(s):G=[*zip(*G)][::-1] # for each row of the rotated grid G for j,r in e(G): # side effect of the zip is that it produces tuples # no good since we have to modify them r=G[j]=[*r] # go from left to right in the row # this allows us to modify the row for k,C in e(G[j]): # test if the cell is you if R(g,chr(ord(C)+32)+"iy"): l=0 # l shall be 1 more than index of the last empty cell to the left of this cell but not # to the left of an entity that is not push; 0 if none exists # Travel from left to right in the list of cells to the left of this cell # (negative logic) If the cell is an entity and is not push, then l=0 for i,c in e(r[:k]):l=(c not in'BFR'or R(g,c.lower()+'ip')) and\ [l,i+1][c=='.'] # otherwise set l=i+1 if c is empty, else l # l<1: no empty cell to the left exists # If not at the edge # and the cell to the left is win, throw a NameError: win if l<1:0<k and\ R(g,chr(ord(r[k-1])+32)+'iw') and\ E # there is an empty cell at index l-1, so push # shift cells over by one; set the cell you are pushing from to empty else:r[l-1:k]=r[l:k+1];r[k]='.' g=G # rotate grid clockwise s times until back to normal for _ in range(s):g=[*zip(*g[::-1])] # test for X is win and X is you: for a in'bfr':R(g,a+'iw')and R(g,a+'iy')and E ``` [Answer] # Python, ~~1930~~ ~~1927~~ 1686 bytes * 1927 (-3) by replacing tabs with spaces * 1686 (-241) Thanks to @pppery (silently ignoring errors) This is the 'proof-of-principle' solution. I'm sure some more bytes can be shaved off with better [eval tricks](https://codegolf.stackexchange.com/a/97/68200). [Expanded code + explanation](https://github.com/MarcinKonowalczyk/baba/tree/master/golf) [Try it online!](https://tio.run/##jVbbbts4EAWS2g/6CtaLQGSqGHHT7oNkCmiBBlhgEQRJIaBVJUOWaZutbqbkxM7l27MzpOQkm@yiQh3xMnNm5swh1WrbLMvi5OFBcFGsc6GSRnhXXIkroWox8xrerKtMeDf8RlbWOW@ova0Km3lnOJzOFQy/4PDz6YXNLLERKbVt27xldVBveueeLPF95kmB7y9eow7qMCV7ae@GHm5Y5M1h3tArqhjbU71NZB9QavMsyaezhGxc22GHH1mHrgB1ThtFF4x5Kj@oYTg3k2W7023j2s1BvXiGt9B4HwBvrsqcpGWWibSRZVETmVelashMrNbCmok5EQ2txYq5FrnmepXmySYTBT9hnuQnFtmb9PKkotfDpKpEMXNaayKP@Ahfc1KUDZGu5COPbKXIZqSh10yDn0KKYCvXXWaNS2VJm/A4YkkBhuEo4tyWNs7MzvuIlYrIygyZV/MwgiRUb4FB95oeJKyY24e4ck0b5tZtYlTDOsbNaqnX4Vuv9De89mtgR8xobfK/wFAWmfLbwp3JtKE39Nyhp0lWCyD4BHpZ9M7uuxx/OklPuYYTKCBh7jT8GYVJxL8qYJsQAX5PIoO9jjl1nkdNGlo5UwwMfaAV8vHdQtAKUgW6hra7X1mABkvGgvORCybLjuYUaBZQMHI8DdM3UWhXtiY27dHDc@fwzEH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1syyCd0t3@p3daYfrRJ9tvPPamwCukCNy/unykhzZeM19o50b/Ddh54gfcWK/Jaef/vqbvLXBvVKyaOjcvu3M738Utwbz3mYP/wA "Python 3 โ€šร„รฌ Try It Online") <- With the tests appended at the end ``` e=enumerate;v=reversed;t=tuple;z=zip P=t('ypn');N=t('bfr');E=t('BFR') exec('''exec('ip%sxP;io%sxN;ie%sxE;tr%s[c cz(*x)];f%s[t(v(r))rx]'%(('=lambda x:',)*5)) exec('rp%sf(tr(g));rm%str(f(g));rh%sf(tr(f(tr(g))));rz%sg'%(('=lambda g:',)*4)) from collections import deque def et(seq): w=deque(maxlen=3);i=3 _map(w.append,seq): i-=1 if not i:i=1; yield t(w) def F(g): iu=lambda t:(io(t[0])and t[1]=='i')and(io(t[2])or ip(t[2]));s=[] rg: tet(r):if iu(t):s.append((t[0],t[2])) cz(*g): tet(c):if iu(t):s.append((t[0],t[2])) sorted(s) def R(r): b={n:dict(z(P,(False,)*3))nN};s=[] j,ar: if ip(a):b[j][a]=True else:s.append((j,a)) b,sorted(s) def at(p,b): len(p)or Z if p[0]=='.':p elif len(p)==1:Z h=lambda c:(ie(c)and b[c]['p'])or c(*P,*N,'i') if not h(p[0]):Z if p[1]=='.':(p[1],p[0],*p[2:]) else:q=at(p[1:],b);(q[0],p[0],*q[1:]) S=t('^V<>') qp=dict(z(S,(rz,rh,rp,rm)));qm=dict(z(S,(rz,rh,rm,rp))) def T(g,b,s): g=qp[s](g);h=[['.'_r]rg];iy=lambda c:ie(c)and b[c]['y'];iw=lambda c:ie(c)and b[c]['n'] j,re(g): k,celle(r):if not iy(cell):h[j][k]=cell;continuep=[h[l][k]lv(range(j))]try: q=at(p,b) l,me(v(q)):h[l][k]=m h[j-1][k]=cellexcept: len(p)and iw(p[0])and Z h[j][k]=cell qm[s](h) def S(g,s): h=[[c cr]rg] a,bs: j,re(g):k,ce(r): if ie(c)and c==a and h[j][k]is c:h[j][k]=b.upper() h def Y(q): g=[[c cr]r('.'*13+'|.rip....RRR..|.......R...R.|.biy.B.R.F.R.|.......R...R.|.fin....RRR..|'+'.'*13).split('|')] try: p(*q,None):b,s=R(F(g))nb: if b[n]['y']and b[n]['n']:Zg=S(g,s)if p:g=T(g,b,p) except:1 0'''.translate({2:"for ",3:"return ",4:".lower()",5:" in ",6:"\n "})) ``` [Answer] # [J](http://jsoftware.com/), ~~456~~ ~~441~~ 399 bytes Takes in the list of directions, with `V < ^ >` as `0 1 2 3`. ``` 0=[:+./@,@><@(4 o@,&4(4 o@,&0])13#.inv 36bdnnshw5d 85686 36ba491bbil 85686 36bbvydg17b)([:(([*0=[:+/@,y*w)r)@(([:><@[([+-~/@]*(={.))~&.>/@,~[:<"1@\:~@;e(<@(l,.4-~])~"{~+&4)~])r)(4-[)o(o=:|.@|:~&0)(([*0=[:+/@,y*1|.(w=:e.l&11)*0=p)([((*-.)+_1|.*)2=[:z&.|.(p*0<[)>.2*(y=:e.l&10)*1|.p=:((0=[:(z=:(2*4<3#.|:@,:)/\.)*@[+e.)e-.l&10,(l=:#&e@e.~(4+(e=:1+i.4),.5)&,.)&12))])(r=:3[\"1(,@,|:))@])&.>/@,~<"0@|.@] ``` [Try it online!](https://tio.run/##pVVLb9s4EL7nVxAuYJOyzFiOk@2qFCG0QE/FHnrgHhRrQclsrUaRDMmO69bwX88OH3LjrZ20WCJyyBFn5ptvHvry2KODtrhHUYgGyEdjFMIzoujdxw/vH8dREg7pZezHnMV4iurY70/d//GMBFevaFE9oKubbF5V7WJzPUevr29e32iJnP4ZZFlR/pBkD9v55@CPjOAkxDjxjHUwvvU2pCExiEJwk@BkONpfxjMPR98pIfs@5XBpn4SsF8S34T5@ozCgKX06He1nZN/7vh/2pwS2DcHTUUJqXEfhjsa7cN8fk2NPwY7iTRQqWvaDgMCLJaDB2BtRMvwHXnpkAne/9SncW3pjlhBOJx7eOpUx0RaWEeDXNvE32E28KQMidmHsh@TylhIvToaKEjUyGj4uo/BVX8WK7vF0iFUUBsOCTolPr0nfp6QfTAiZEdxE4VVy2wuwH/u7kJB4RlzorDeOIZ7ZI3n86y1F72W7Uu0KbYrqIkAR0ukbCJbyASooGnCeci4GF0@vlnXbIryt12heV4MVkvlqLctyixbyQaFVjfKFyu/Qp7qxV9XXZVnkxarckovxzy5YypyDtzKTqGjPYWFCMMFYKgAUsxofa3AEGhlonlRJ05QxwQXj/FgD4D@joB9wA870z7HmeXRwgKPgaQowmTal2QP@9Bv@XwRgB2VroK9sa7Rct4vTeLQloY2AGWfTYNNc2AO3Sx@NoFvHpH4q5eeT9AvnQePm9jmkvFPWyXahP29Cx64NuYoBn1qveYk6Q7kOJNUMPk0BgAH6hEmLSYc9gy@TWIP3rDPfEKyJriu0WcgVWrdqrks0g0JdKEMKOrdO9oOJzmZZCEe0SE3kACllvwZfpKlNmiuJdala102burlD62VbzBVINi8Szk2xWQSi2xxn8SfzmczvNrKZt79tnJsK1A0F@bIRmorjpzzidiOXLUGyUUguYQgA97JcLmSmVkVuRsYZmg9lrwlNXbINxyDUf/roMsG7jIhDi9j82Oa1sG1/6AnCfg@hj3LZKjT5JZRCjxpuUQhbCqaeddXofjUtJrgr9BMzrGtU9H/W6SF7qErOhO0gBxEeNnjW3jmUB25ecMg5d0OM2cSJrrBS3gm7jRNZav6WJTitoF91s@Z1U6nGfFckdHNRQs6qObqXd7BBedHkWtLUaxDq@1kNJf5iR1s4dqV2cTO4fwzSDvWTvtWl6DDCdIHBoh2W8IFE9/W9qlanv6W6CkxFuvJg1h0/5EUH/i8 "J โ€šร„รฌ Try It Online") Or [play around with the version](https://tio.run/##VVHBTsMwDP2VqEipnaZes2UDQlNFIO3EiQMcsoKoVqBobNOQmMaq/PrI0CTEwbL1/Gw/2@@HhNLP7oNZw1ImWcFMtJzYzd3t9OBNVTrQbOUk1ydf1KhGZ9Qtv9ho0syXy8@37XjOLsaTi8kRedaXqmm6xR/SfO3mr@q8QfAGwIvCepMNnNyJLW7QReg4xoPP8jBwtQC7J8TAqYqk4E2ZKDczwV21ENUsJOk81BiSfci4xhhuEHTucQUra3pyvQm8wP@TVE@wtaalBVcKY2Id1QCInDB7ikmBw8j95hR5a1GUHisaCtidSgo8dljbqP/YE75jNBS6jIfojZMGBzNC4XzWErb5b4WEhTVnvHUtBdAZtNaorCONksbIJSFXQ8QaYWPNyM8SBdLJ3iC6Gk@rl0nh4j71AQ8pXU/vHpqXzbbbLdcp2wcWvzZj6X35WKWsI5ZW1WNV3ac/ "J โ€šร„รฌ Try It Online") that prints the board after each step. ### How it (roughly) works It goes quite well as an tacit definition, as we're just working on the matrix itself. It maps the characters to numbers according to the list in `level`. Ungolfed: ``` NB. map stored as base 13, then padded with floors and walls walls=:4 rot@,&4(4 rot@,&0])13#.inv 36bdnnshw5d 85686 36ba491bbil 85686 36bbvydg17b NB. rotate matrix x times rot=:|.@|:~&0 NB. BFRW as numbers objs=:1 2 3 4 NB. get all 1x3 lists of the original and the transposed matrix rules=:(3 [\"1 (,@,|:)) NB. check if rule exists, e.g isrule&10 -> things that can be pushed isrule =: (#&objs@e.~ (4 + objs ,. 5)&,.) NB. 0 2 0 0 1 1 2 1 0 -> 0 2 0 0 2 2 2 0 0 NB. used for checking which fields can move/get pushed red=:(2* 4< 3#. |: @ ,:)/\. NB. places that can be walked into pass=:((0 = [: red *@[ + e.) objs -. isrule&10 , isrule&12) NB. win place can't be walked into (not pushable or blocked), NB. with a you-entity that walks down -> won wonpush=: ([ * 0 = [: +/@, (e. isrule&10) * 1 |. (e. isrule&11) * 0 = pass) NB. exists entity that is you and win? wonyou =: ([ * 0 = [: +/@, (e. isrule&10) * (e. isrule&11)) NB. calculate which places gets moved or pushed down in a step shifts=:( 2 = [: red&.|. ( pass * 0 < [) >. 2 * (e. isrule&10) * 1 |. pass) NB. actually move down entities move_down=:([ ((*-.)+_1 |. *) shifts) NB. get all rules of the form (objs is objs), sort them, replace them replace=: ([: > <@[ ([ + -~/@] * (={.))~&.>/@,~ [: <"1@\:~@; objs (<@(isrule ,. 4-~])~"{~ +&4)~ ]) NB. rotate so movement goes down, check wonpush, move down, rotate back, replace, check wonyou move=: ([: (wonyou rules)@(replace rules) (4-[) rot rot (wonpush move_down ]) rules@] ) NB. append moves to the matrix and reduce from right to left with move, NB. e.g. 0 move 1 move 0 move walls sim2=: (<@walls move&.>/@,~ <"0@|.@]) NB. after everything is finished, does contain matrix only 0? if yes -> won ``` [Answer] # BaBa Is You, ~~663~~ 615 bytes File `.l`: ``` 00000000: 4143 4854 554e 4721 0501 4d41 5020 0200 ACHTUNG!..MAP .. 00000010: 0000 0000 4c41 5952 b301 0000 0300 0f00 ....LAYR........ 00000020: 0000 0c00 0000 0c00 0c00 00ff 0000 0000 ................ 00000030: 0000 0000 0000 803f 0000 803f 0000 0100 .......?...?.... 00000040: 0080 3fff ffff 024d 4149 4e87 0000 0078 ..?....MAIN....x 00000050: 5e63 2004 5819 3959 19b9 5958 d9b9 9918 ^c .X.9Y..YX.... 00000060: 9919 3919 9999 1819 58b8 9958 9840 1a39 [[emailย protected]](/cdn-cgi/l/email-protection) 00000070: 99d8 18b8 1959 3838 1919 9959 8098 9389 .....Y88...Y.... 00000080: 8583 1bcc 061b cbc2 0085 dc40 9a1b c666 [[emailย protected]](/cdn-cgi/l/email-protection) 00000090: 038a 02a5 ffe3 040c 6059 4ea0 7ddc cc30 ........`YN.}..0 000000a0: 45cc 0c20 08e2 3160 e865 6680 a802 d150 E.. ..1`.ef....P 000000b0: bd40 3770 b3fc ffcf 0894 018b 32fd ff8f [[emailย protected]](/cdn-cgi/l/email-protection)... 000000c0: 9045 b618 532f c8fd 5c44 d98b 6c0e a160 .E..S/..\D..l..` 000000d0: 0400 5728 8923 4441 5441 0100 0000 0030 ..W(.#DATA.....0 000000e0: 0000 0078 5e63 4603 0c0c cc0c 70c0 8cc4 ...x^cF.....p... 000000f0: 060a 6270 3135 3380 84c0 4ae1 7220 21b8 ..bp153...J.r !. 00000100: 30d0 7466 10c6 2ecb 0cb6 8199 1000 006d 0.tf...........m 00000110: d701 660f 0000 000c 0000 000c 000c 0000 ..f............. 00000120: ff00 0000 0000 0000 0000 0080 3f00 0080 ............?... 00000130: 3f00 0001 0000 803f ffff ff02 4d41 494e ?......?....MAIN 00000140: 1600 0000 785e fb4f 1660 e4c4 af8d 91f9 ....x^.O.`...... 00000150: ff28 4009 0100 74d2 62ba 4441 5441 0100 .(@...t.b.DATA.. 00000160: 0000 0012 0000 0078 5e63 c60d 18d0 a418 .......x^c...... 00000170: 9807 0900 00bc 3402 170f 0000 000c 0000 ......4......... 00000180: 000c 000c 0000 ff00 0000 0000 0000 0000 ................ 00000190: 0080 3f00 0080 3f00 0001 0000 803f ffff ..?...?......?.. 000001a0: ff02 4d41 494e 0d00 0000 785e fb3f 0ae8 ..MAIN....x^.?.. 000001b0: 1202 00e6 5866 a844 4154 4101 0000 0000 ....Xf.DATA..... 000001c0: 0b00 0000 785e 631e 8200 00bf 9a02 1d ....x^c........ ``` File `.ld`: ``` [tiles] changed_short=016,082, object082_name=text_phantom changed_count=2 object016_name=text_feeling changed=object016,object082, object016_argtype=2, ``` [![enter image description here](https://i.stack.imgur.com/2OMOi.png)](https://i.stack.imgur.com/2OMOi.png) Summon a `phantom` item to detect win Weaken thing that are on others `feeling` and `phantom` looks bad since image take extra bytes ]
[Question] [ # Background [Nonogram](https://en.wikipedia.org/wiki/Nonogram), also known as Picross or Griddlers, is a puzzle where the objective is to determine if each cell on the 2D grid should be colored or left blank, using the numbers of consecutive colored cells on each line. The following is an example Nonogram puzzle with solution. ![](https://i.stack.imgur.com/Pn9qI.png) The problem is, some commercial Nonogram games/mobile apps have puzzles which are not solvable by hand (e.g. have multiple solutions, or require deep backtracking). However, they also offer some lives to the player, where **one life is lost when you try to color a cell whose correct answer is blank**. So now it's time to brute-force those nasty "puzzles"! In order to simplify the task, imagine just one line with its clue and nothing else: ``` 3 7 | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ``` The `[3,7]` are the clues, and the line length is 15 cells. Since it has multiple possible solutions, we need to risk some lives in order to fully solve this line (i.e. determine all colored cells). # Challenge Given a line with clues (a list of positive integers) and the line length, find the maximum number of lives you will lose, assuming that you brute-force the line with optimal strategy. Note that **you always guess colored cells**. In actual games, guessing empty cells (either right or wrong) have no effect on your lives, so you can't "solve" the puzzle that way. Also, you can assume the input always represents a valid Nonogram line, so you don't need to worry about something like `[6], 5`. # Explanation Let's look at some simpler examples first. ### `[1,2], 5` There are exactly three possibilities for this line (`O` is a colored cell, `.` is an empty one): ``` O . O O . O . . O O . O . O O ``` If we try coloring cell 0 (0-based index from left), one of the following happens: * The cell is correctly colored. Now we have two possibilities, and we can choose between cell 2 and cell 4 in order to fully solve the line. Either case, we will lose one life in the worst case. * The cell is empty, and we lose a life. In this case, we have already identified the unique solution to this line, so we're done with 1 life lost. Therefore, the answer for `[1,2], 5` is 1. ### `[5], 10` Binary search? Nope. The most obvious first choice is 4 or 5, which will reveal one possibility if it's blank (at a cost of 1 life). Let's say we chose 4 first. If cell 4 is indeed colored, we extend it to the left, i.e. try 3, 2, 1 and 0 until a life is lost (or cell 0 is colored, then we end up spending no lives at all). Whenever a life is lost, we can uniquely determine the solution, e.g. if we see something like this: ``` _ _ X O O _ _ _ _ _ ``` then we already know the answer is this: ``` . . . O O O O O . . ``` Therefore, the answer for `[5], 10` is also 1. ### `[3,7], 15` Start with cell 11, which, if empty, will reveal the following solution right away. ``` O O O . O O O O O O O X . . . ``` Then try 12, which, if empty, gives two possibilities which can be solved at the cost of 1 extra life. ``` O O O . . O O O O O O O X . . . O O O . O O O O O O O X . . ``` Now try 2. If empty, it leads to three possibilities which can be solved similarly to the `[1,2], 5` example. ``` . . X O O O . O O O O O O O . . . X O O O . . O O O O O O O . . X . O O O . O O O O O O O ``` If you keep minimizing the risk in this manner, you can reach any solution with max. 2 lives spent. # Test Cases ``` [1,2] 5 => 1 [2] 5 => 2 [1] 5 => 4 [] 5 => 0 [5] 10 => 1 [2,1,5] 10 => 0 [2,4] 10 => 2 [6] 15 => 2 [5] 15 => 2 [4] 15 => 3 [3,7] 15 => 2 [3,4] 15 => 3 [2,2,4] 15 => 4 [1,1,1,1,1,1,1] 15 => 2 [2,1,1,3,1] 15 => 3 [1,1,1,2,1] 15 => 5 ``` For the last two cases, the optimal strategy is *not* going through the minimum blanks, but simply going from left to right (or right to left). Thanks to @crashoz for pointing it out. # Rules Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest valid submission in bytes wins. # Bounty If someone comes up with a polynomial-time algorithm (with the proof of correctness), I will award +100 bounty to such a solution. [Answer] # [Ruby](https://www.ruby-lang.org/), 85 bytes ``` f=->l,n,s=n-l.sum-l.size+1{*a,b=l;b&&s>0?(a[0]?1+f[a,n-b-2,s-1]:(n.to_f/b).ceil-1):0} ``` [Try it online!](https://tio.run/##VYvRCoIwFIav8ymGgqSdmWdagWE9yBjhYoKgFpkXpT67JRluDM6@7z//ebTyNY55Sk8l1NCkNS2Dpq2mWbzVBjs/A5mWR@m6zSk8rzMeijNucp5BTSVl0FAUyboOnrdLvpVecFVFSdFLwmHk1opzBCaA7ARMoiEuuND3IxjOXUAwPdZsP7F@NXOscQQHw/QdA2Y4gvaM3pRERvZrsX9miaDK7l2venInttOpgThdzn0lBnsYPw "Ruby โ€“ Try It Online") ## Explanation The first step is to establish a recursive divide and conquer strategy to solve subproblems. I will use the variables \$l=[l\_1,l\_2,...,l\_x]\$ for the list of clues, \$x\$ for the number of clues and \$n\$ for the number of cells. Try to fit the last clue \$l\_x\$: We test the cell at \$n-l\_x\$ **(1)** If it's empty: then all of the clues are before \$n-l\_x\$. So we lose a life and we call recursively \$1+f(l,n-l\_x)\$ **(2)** If it's colored: We are not sure how to place the last clue, so we test every cells to the right until finding an empty one The worst case is finding the empty cell at the last index, we lose a life, but we have placed the last clue so we can call recursively \$1+f(\tilde{l},n-l\_x-2)\$ where \$\tilde{l}\$ is \$l\$ without the last clue. So we can get the number of lives with this function $$ f(l,n)=\begin{cases} 0, & \text{if } \sum\_1^xl\_i+x-1 \geq n\\ \lceil \frac{n}{l\_x} \rceil - 1 & \text{if } x= 1\\ 1+\max\begin{cases} f(l,n-l\_x)\\ f(\tilde{l},n-l\_x-2) \end{cases}, & \text{otherwise} \end{cases} $$ Here is an example `_` are unknown, `X` is a known space, `O` is a known colored cell and `L` is life lost ``` [2,2,4] 15 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ (1) -> [2,2,4] 11 _ _ _ _ _ _ _ _ _ _ _ L X X X (1) -> [2,2,4] 7 _ _ _ _ _ _ _ L X X X L X X X 0 X X X L X X X L X X X L X X X (2) -> [2,2] 5 _ _ _ _ _ X O O O O L L X X X 0 O O X O O X O O O O L L X X X (2) -> [2,2] 9 _ _ _ _ _ _ _ _ _ X O O O O L (1) -> [2,2] 7 _ _ _ _ _ _ _ L X X O O O O L (1) -> [2,2] 5 _ _ _ _ _ L X L X X O O O O L 0 O O X O O L X L X X O O O O L (2) -> [2] 3 _ _ _ X O O L L X X O O O O L 1 O O L X O O L L X X O O O O L (2) -> [2] 5 _ _ _ _ _ X O O L X O O O O L 2 O O L L X X O O L X O O O O L ``` It makes a binary tree, to get the number of lives lost, we just need to count the maximum height of the tree. However this makes it \$\mathcal{O}(2^n)\$ because we evaluate all of the branches. We can do better. Let's define a cost function \$h\$ that will help us "choose" the right branch at each step. $$ h(l,n)=n - \sum\_1^xl\_i-x+1 $$ \$h\$ counts the number of superfuous spaces we have if we pack all the clues with one space in between. So it is essentially an indicator of how much lives we are going to need to solve the instance, the higher it is, the more lives are necessary. The idea is to apply this indicator on our recursive formula. By definition of \$h\$ we have, $$ \begin{align} h(l,n-l\_x) &= n - l\_x - \sum\_1^xl\_i-x+1\\ & =(n - \sum\_1^xl\_i-x+1) - l\_x\\ & = h(l,n) - l\_x \end{align} $$ And, $$ \begin{align} h(\tilde{l},n-l\_x-2) &= n - l\_x - 2 - \sum\_1^{x-1}l\_i-(x-1)+1\\ & =(n - \sum\_1^xl\_i-x+1) - 1\\ & = h(l,n) - 1 \end{align} $$ Then, $$ h(l,n)=\begin{cases} \leq 0, & \text{if } \sum\_1^xl\_i+x-1 \geq n\\ n - l\_x, & \text{if } x=1\\ \max\begin{cases} h(l,n-l\_x)+l\_x\\ h(\tilde{l},n-l\_x-2)+1 \end{cases}, & \text{otherwise} \end{cases} $$ We want to **maximize** \$h\$ at each step to get the worst case so let's check the difference between the two expressions in the recurrence $$ [h(l,n-l\_x)+l\_x] - [h(\tilde{l},n-l\_x-2)+1]\\ \begin{align} &= n-l\_x-n - \sum\_1^xl\_i-x+1 + l\_x - [n-l\_x-2 -\sum\_1^{x-1}l\_i-(x-1)+1+1]\\ &=-2 \end{align} $$ $$ \begin{align} [h(l,n-l\_x)+l\_x] - [h(\tilde{l},n-l\_x-2)+1] &=-2\\ [h(l,n-l\_x)+l\_x] - [h(\tilde{l},n-l\_x-2)+1] &< 0\\ [h(l,n-l\_x)+l\_x] &< [h(\tilde{l},n-l\_x-2)+1] \end{align} $$ So the 2nd expression is always the max, we can remove the first one $$ h(l,n)=\begin{cases} \leq 0, & \text{if } \sum\_1^xl\_i+x-1 \geq n\\ n - l\_x, & \text{if } x=1\\ h(\tilde{l},n-l\_x-2)+1 & \text{otherwise} \end{cases} $$ Finally this recursive definition of \$h\$ shows us that option **(2)** in function \$f\$ is always the worst case (giving the maximum number of possibilities i.e. maximizing \$h\$) $$ f(l,n)=\begin{cases} 0, & \text{if } \sum\_1^xl\_i+x-1 \geq n\\ \lceil \frac{n}{l\_x} \rceil - 1 & \text{if } x= 1\\ 1+ f(\tilde{l},n-l\_x-2), & \text{otherwise} \end{cases} $$ Every step we decrease \$n\$ by at least 3 and there is now a single recursive call, complexity is \$\mathcal{O}(n)\$ [Answer] ## Python, ~~303~~ 289 bytes First golf in a long time, so there may be a lot of excess fat. (Thanks [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for finding 14 bytes-worth.) Function f generates all the possible arrangements (though always with a blank as the first character, but that's fine as long as we increment the length by 1 before we call it). Function g picks the position with the fewest number of blanks and recurses. Function h puts them together. ``` f=lambda l,n:["."*i+"X"*l[0]+c for i in range(1,n-l[0]+1)for c in f(l[1:],n-i-l[0])]if l else["."*n] def g(q,n):O,X=min([[[p[:i]+p[i+1:]for p in q if p[i]==u]for u in".X"]for i in range(n)],key=lambda x:len(x[0]));return(len(q)>1)*1and max(1+g(O,n-1),g(X,n-1)) h=lambda l,n:g(f(l,n+1),n+1) ``` The examples all run fine: ``` >>> h([3,7],15) 2 >>> h([3,4],15) 3 >>> h([1,1,1,2,1],15) 6 ``` ]
[Question] [ Today's challenge is to draw a [binary tree](https://en.wikipedia.org/wiki/Binary_tree) as beautiful [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") like this example: ``` /\ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ /\ /\ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ /\ /\ /\ /\ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ /\ /\ /\ /\ /\ /\ /\ /\ / \ / \ / \ / \ / \ / \ / \ / \ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ``` You will be given a positive integer as input. This input is the [height of the tree](https://stackoverflow.com/a/2603707/3524982). The above example has a height of six. You may submit either a full-program or a function, and you are free to use any of our [default IO methods](http://meta.codegolf.stackexchange.com/q/2447/31716). For example, printing the tree, returning a string with newlines, returning a 2d char array, saving the tree to a file, etc. would all be allowed. Trailing spaces on each line are permitted. Here are some examples of inputs and their corresponding outputs: ``` 1: /\ 2: /\ /\/\ 3: /\ / \ /\ /\ /\/\/\/\ 4: /\ / \ / \ / \ /\ /\ / \ / \ /\ /\ /\ /\ /\/\/\/\/\/\/\/\ 5: /\ / \ / \ / \ / \ / \ / \ / \ /\ /\ / \ / \ / \ / \ / \ / \ /\ /\ /\ /\ / \ / \ / \ / \ /\ /\ /\ /\ /\ /\ /\ /\ /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ``` Unfortunately, the output grows exponentially, so it's hard to show larger examples. [Here is a link](https://gist.github.com/DJMcMayhem/77a25b711283bf844698edb032dc924c) to the output for 8. As usual, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so standard loopholes apply, and try to write the shortest program possible in whatever language you choose. Happy golfing! [Answer] ## Python 2, 77 bytes ``` S=s=i=2**input() while s:print S/s*('/'+' '*(s-i)+'\\').center(s);i-=2;s/=s/i ``` Prints with trailing spaces, terminating with error. I took this code from [my submission](http://golf.shinh.org/reveal.rb?Branching%20tree/xnor_1477113229&py) to [a challenge I posed on Anarchy Golf](http://golf.shinh.org/p.rb?Branching+tree), plus a [one-byte improvement](http://golf.shinh.org/reveal.rb?Branching+tree/xsot+%28xnor%29_1478252053&py) found by xsot. The hardcoded value of 128 was changed to `2**input()`. The idea is that each row of the output is a segment copied one or more times. The half after the input split has one copy of each segment, the quarter after the next split has two copies, and so on, until the last line with many segments of `/\`. Each segment had a `/` and `\`, with spaces in between, as well as on the outside to pad to the right length. The outer padding is done with `center`. The variable `s` tracks the current with of each segment, and the number of segments is `S/s` so that the total width is the tree width `S`. The line number `i` counts down by 2's, and whenever the value `s` is half of it, a split occurs, and the segment width halves. This is done via the expression `s/=s/i`. When `i` reaches `0`, this gives an error that terminates the program. Since anagolf only allows program submissions, I didn't explore the possibility of a recursive function, which I think is likely shorter. [Answer] # [V](https://github.com/DJMcMayhem/V), 32 bytes ``` รฉ\รฉ/ร€ยญรฑLyPร„lx$X>>รฎรฒ^llร„lxxbPรฒ | ``` [Try it online!](https://tio.run/nexus/v#@394ZczhlfqHGw6tPbxRzKcy4HBLToVKhJ3d4XWHN8Xl5IC4FUkBhzdx1fz/DwA "V โ€“ TIO Nexus") Hexdump: ``` 00000000: e95c e92f c0ad f116 4c79 50c4 6c78 2458 .\./....LyP.lx$X 00000010: 3e3e eef2 5e6c 6cc4 6c78 7862 50f2 0a7c >>..^ll.lxxbP..| ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` /โ•‘โ•ถโ•ท๏ผป๏ฝŒ๏ผผ๏ผ›โˆ”โ†”โ•‘ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=LyV1MjU1MSV1MjU3NiV1MjU3NyV1RkYzQiV1RkY0QyV1RkYzQyV1RkYxQiV1MjIxNCV1MjE5NCV1MjU1MQ__,i=NQ__,v=2) Explanation: ``` /โ•‘ push `/\` ("/" palindromized so this is a Canvas object) โ•ถโ•ท[ repeat input-1 times l get the width of the ToS \ create a diagonal that long ;โˆ” prepend that to the item below โ†” reverse the thing horizontally โ•‘ and palindromize it horizontally ``` [Answer] # [Haskell](https://www.haskell.org/), ~~140 138~~ 135 bytes ``` e n=[1..n]>>" " n!f=(e n++).(++e n)<$>f f 0=[] f n=1!f(n-1)++['/':e(2*n-2)++"\\"] b n|n<2=f 1|t<-b$n-1,m<-2^(n-2)=m!f m++zipWith(++)t t ``` [Try it online!](https://tio.run/nexus/haskell#FY1Ba4QwEIXv/oq3Iqw2TboKhVKMUHrpsdBDD64F3U0wNI6isYWy/92Op/fNzDc8N0zjHPA6UphHr16mybtLG9yPgZSw44wyqfDbu0sPt8CRX6/myon32eyM0eKtXb6N93hSp2ho@aYxreEjzFBYyTsyC1OHBI@bAek6V4qaqooRR3SwOuWlEJlKhWDKuNFGFiddNxyk80NqE5J5JkR9fDg@m7S4I1nwGJ/PcRN1oBuVhbbIb6GU3e7eD6UsvtJd0wP/Y2D9z02fLvRckwWEbfsH "Haskell โ€“ TIO Nexus") Call with `b 5`, returns a list of strings. **Pretty print usage:** ``` *Main> putStr . unlines $ b 5 /\ / \ / \ / \ / \ / \ / \ / \ /\ /\ / \ / \ / \ / \ / \ / \ /\ /\ /\ /\ / \ / \ / \ / \ /\ /\ /\ /\ /\ /\ /\ /\ /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ``` (some) **Explanation:** * `e n` generates a string of `n` spaces * `n!f` pads each string in the list of strings `f` with `n` spaces left and right * `f n` draws a "peak" in a `n` by `2n` rectangle * `b n` draws the binary tree by concatenating two smaller trees and centers a new peak above them Edit: -3 bytes thanks to Zgarb! [Answer] ## [J](http://jsoftware.com/), ~~49 43~~ 42 bytes ``` ' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-)) ``` This evaluates to a verb that takes a number and returns a 2D character array. [Try it online!](https://tio.run/nexus/j#@5@uYGuloK6gH6NeXadRo6ejq6lk6KBh65Cp56AM5MRZadhYJWjoWDnoqGnpamr@T03OyFdIVzD5DwA "J โ€“ TIO Nexus") ## Explanation I first construct a matrix of the values -1, 0 and 1 by iterating an auxiliary verb, and then replace the numbers by characters. The auxiliary verb constructs the right half of the next iteration, then mirrors it horizontally to produce the rest. In the following explanation, `,` concatenates 2D arrays vertically and 1D arrays horizontally. ``` ' /\'{~(|.,-)"1@(=@i.@#,-)^:(<:`(,:@,&*-)) Input is n. ^:( ) Iterate this verb <: n-1 times `( ) starting from ,&*- the array 1 -1 (actually sign(n), sign(-n)) ,:@ shaped into a 1x2 matrix: Previous iteration is y. # Take height of y, i.@ turn into range =@ and form array of self-equality. This results in the identity matrix with same height as y. ,- Concatenate with -y, pad with 0s. ( )"1@( ) Then do to every row: |.,- Concatenate reversal to negation. ' /\'{~ Finally index entry-wise into string. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ๏ผฆ๏ผฎยซโ†’โ†—โŒˆ๏ผธยฒโŠ–ฮนโ€–๏ผญ ``` [Try it online!](https://tio.run/##HYyxCoMwEEBn8xUZL2CXDh10bJcOigh@gE1PPYg5OaIdpN9@DX3jg/f8MornMahOLBaecdtTu68vFHDOnqZo@ECoepqX5GpTdEIxQTVsf1PaO1KgOEPHn5xcS/tAL7hiTPgGcpkc9TgF9KkhEc7f2nxVb3o5wg8 "Charcoal โ€“ Try It Online") Link is to verbose version of code. Explanation: ``` ๏ผฎ Input as a number ๏ผฆ ยซ Loop over implicit range โ†’ Move right (because mirroring moves the cursor) ฮน Current index โŠ– Decremented ๏ผธยฒ Power of 2 โŒˆ Ceiling โ†— Draw diagonal line โ€–๏ผญ Mirror image ``` The line lengths are 1, 1, 2, 4, 8 ... 2^(N-2), thus the awkward calculation. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~20~~ 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` โ‰กmXโ–‘Rโ—‹kโ•ฃโˆ™โ•’ab^โ—˜โŒโ•–xโ–ผ; ``` [Run and debug it](https://staxlang.xyz/#p=f06d58b052096bb9f9d561625e08a9b7781f3b&i=1%0A3&a=1&m=2) [Answer] ## JavaScript (ES6), 105 bytes ``` f=n=>n<2?"/\\":" "+f(n-1).split`/`[0].replace(/|/g,"$`$'$'/$`$`\\$'$'$` \n")+f(n-1).replace(/.*/g,"$&$&") ``` Works by building the result up recursively from the base case `/\`. The bottom half is just the previous case with each line duplicated. The top half was a little trickier; it looks as if you want to take the previous case and only keep the two sides but you also have to worry about padding the strings to double the width, so instead I do some regex magic. By taking the leading spaces from the previous case and splitting at every point, I can consider the spaces before and after that point. At each match the spaces before increase by 1 and the spaces after decrease by 1; this can be used to position the `/` and `\` in the correct places. The newlines and padding are also added here; this takes care of all the padding except a trailing space on each line and a leading space on the first line which I have to add manually. (Leading spaces on subsequent lines come from the matched string). [Answer] ## Batch, 218 bytes ``` @echo off set/a"n=1<<%1" set s=set t= %s%/\ set l=for /l %%i in (2,1,%n%)do call %l% %s% %%t%% %l%:l :l echo %t% set/an-=1,m=n^&n-1 %s%%t: /=/ % %s%%t:\ = \% if %m% neq 0 exit/b %s%%t:/ =/\% %s%%t: \=/\% ``` Note: Line 6 ends in a space. Works by moving the branches left and right appropriately each time, except on rows that are 2n from the end, in which case the branches get forked instead. [Answer] # Haxe, 181 bytes ``` function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n"); ``` Or, with some optional whitespace: ``` function g(n):String return (n -= 2) == -1 ? "/\\" : [ for (y in 0...1 << n) [ for (x in 0...4 << n) x + y + 1 == 2 << n ? "/" : x - y == 2 << n ? "\\" : " " ].join("") ].concat([ for (y in g(n + 1).split("\n")) y + y ]).join("\n"); ``` I was working for a while on a solution which created an array of space characters of the right size first, then iteratively put the forked paths lower and lower (and more densely at each iteration). It remained 230+ bytes, though. The approach here is pretty much what @Laikoni's Haskell approach is. I couldn't get away with not having `:String`, because Haxe is not smart enough to identify that the return type will always be a String. This is a function only, here's a full programme to test it: ``` class Main { public static function main(){ function g(n):String return(n-=2)==-1?"/\\":[for(y in 0...1<<n)[for(x in 0...4<<n)x+y+1==2<<n?"/":x-y==2<<n?"\\":" "].join("")].concat([for(y in g(n+1).split("\n"))y+y]).join("\n"); Sys.println(g(Std.parseInt(Sys.args()[0]))); } } ``` Put the above in `Main.hx`, compile with `haxe -main Main.hx -neko frac.n` and test with `neko frac.n 4` (replace `4` with the desired order). [Answer] # PHP, 188 Bytes [Online Version](http://sandbox.onlinephpfunctions.com/code/fb264f1f0ef523faff29b2f0fb25c05cf792a7f0) ``` function f($l,$r=0,$m=1){global$a;for(;$i<$l;$i++)$i<$l/2?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m):f($l/2^0,$r+$l/2,2*$m);}f(2**$argv[1]/2);echo join("\n",$a); ``` Expanded ``` function f($l,$r=0,$m=1){ global$a; for(;$i<$l;$i++) $i<$l/2 ?$a[$i+$r]=str_repeat(str_pad("/".str_pad("",2*$i)."\\",2*$l," ",2),$m) :f($l/2^0,$r+$l/2,2*$m); } f(2**$argv[1]/2); echo join("\n",$a); ``` ]
[Question] [ You can create a list of all rationals 0 < r โ‰ค 1 by listing them ordered first by denominator and then by numerator: ``` 1 1 1 2 1 3 1 2 3 4 1 5 1 2 3 4 5 - - - - - - - - - - - - - - - - - 1 2 3 3 4 4 5 5 5 5 6 6 7 7 7 7 7 ``` Note that we skip any rational number that already occurred before. E.g. 2/4 is skipped because we already listed 1/2. In this challenge we're interested in the numerators only. Looking at the list above, write a function or program taking a positive integer *n* that returns the *nth* **numerator** from the list. --- Testcases: ``` 1 -> 1 2 -> 1 3 -> 1 4 -> 2 5 -> 1 6 -> 3 7 -> 1 8 -> 2 9 -> 3 50 -> 4 80 -> 15 ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~17~~ 13 bytes ``` :tt!/XR6#uG)) ``` [Try it online!](http://matl.tryitonline.net/#code=OnR0IS9YUjYjdUcpKQ&input=ODA) Or [verify all test cases](http://matl.tryitonline.net/#code=IkAKOnR0IS9YUjYjdUApKQ&input=WzEgMiAzIDQgNSA2IDcgOCA5IDUwIDgwXQ). Input size may be limited by floating point accuracy. All test cases give the correct result. ### Explanation This generates all fractions `k/m` with `k`, `m` in `[1 2 ...n]`, as an `n`ร—`n` matrix. The row indicates the numerator and the column indicates the denominator. Actually the matrix entry contains the inverse fraction `m/k`, instead of `k/m`, but this is irrelevant and can be ignored in the rest of the explanation. Matrix entries are implicitly considered to be sorted in column-major order. In this case this corresponds to the required order: denominator, then numerator. Three types of entries need to be disregarded from this matrix: 1. Entries `k/m`, `k>m`, that have the same value as a previous entry (for example, `2/4` is disregarded because it is the same as `1/2`) 2. Entries `k/k`, `k>1`. Entries that have a numerator exceeding the denominator 3. Entries `k/m`, `k<m` (these are not part of the problem). Disregarding entries is done with a `unique` function, which stably removes duplicate values and outputs the indices of the surviving entries. With this, entries of type 1 above are automatically removed. To deal with types 2 and 3, the matrix entries at the diagonal and below are set to `0`. This way, all zero entries will be removed except the first (corresponding to the valid fraction `1/1`). Consider input `4` as an example. ``` : % Input n implicitly. Push range [1 2 ...n] % STACK: [1 2 3 4] t % Duplicate % STACK: [1 2 3 4], [1 2 3 4] t! % Duplicate and transpose % STACK: [1 2 3 4], [1 2 3 4], [1; 2; 3; 4] / % Divide element-wise with broadcast: gives matrix with all pairs % STACK: [1 2 3 4], [1 2 3 4; 0.5000 1 1.5000 2; 0.3333 0.6667 1 1.3333; 0.2500 0.5000 0.7500 1 ] XR % Upper triangular part above the diagonal. This sets to 0 all entries % corresponding to fractions that equal or exceed 1. (Since the matrix % actually contains the inverse fractions, nonzero entries will contain % values greater than 1) % STACK: [1 2 3 4], [0 2 3 4; 0 0 1.5000 2; 0 0 0 1.3333; 0 0 0 0 ] 6#u % Indices of first appearance of unique elements % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15] G % Push input n again % STACK: [1 2 3 4], [1; 5; 9; 10; 13; 15], 4 ) % Index: get the n-th entry from the array of indices of unique elements % STACK: [1 2 3 4], 10 ) % Index (modular): get the corresponding real part. Display implicitly % STACK: 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` gRแปŠTยตโ‚ฌFแป‹@ ``` [Try it online!](http://jelly.tryitonline.net/#code=Z1Lhu4pUwrXigqxG4buLQA&input=&args=OQ) or [verify all test cases](http://jelly.tryitonline.net/#code=Z1Lhu4pUwrXigqxG4buLQAo5Ujs1MDs4MMK1xbzDh-KCrEc&input=). ### How it works ``` gRแปŠTยตโ‚ฌFแป‹@ Main link. Argument: n ยตโ‚ฌ Map the monadic chain to the left over [1, ..., n]; for each k: R Range; yield [1, ..., k]. g Compute the GCD of k and each j in [1, ..., k]. แปŠ Insignificant; yield 1 for 1; 0 for 2, ..., k. T Truth; yield all indices of 1's, i.e., all coprimes with k. F Flatten the resulting 2D array. แป‹@ At-index swapped; return the n-th element. ``` [Answer] ## Haskell, 40 bytes ``` ((0:[n|d<-[1..],n<-[1..d],gcd n d<2])!!) ``` An anonymous function. Pretty straightforward: uses a list comprehension to generate an infinite list, looping over all numerators `n` and relatively prime denominators `d`. To convert zero-index to one-indexed, we prepend a `0`, which takes `4` bytes. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ 49 bytes ``` (Join@@Array[Pick[r=Range@#,r~GCD~#,1]&,#])[[#]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V/DKz8zz8HBsagosTI6IDM5O7rINigxLz3VQVmnqM7d2aVOWccwVk1HOVYzOlo5Nlbtv6Y1l0ZAUWZeiYNWmqa@A1e1oY6CkY6CsY6CiY6CqY6CmY6CuY6ChY6CJZBrAGQZ1P4HAA "Wolfram Language (Mathematica) โ€“ Try It Online") [Answer] # Pyth, 13 bytes ``` @smfq1idTUhdh ``` [Try it online.](https://pyth.herokuapp.com/?code=%40smfq1idTUhdh&input=80&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A50%0A80&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=%40smfq1idTUhdh&input=80&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A50%0A80&debug=0) [Answer] # Pyth, 11 bytes ``` @sm.mibdhdS ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%40sm.mibdhdS&input=50) ### Explanation: ``` @sm.mibdhdSQQ implicit Qs at the end (Q = input number) m SQ map each denominator d from [1, 2, ..., Q] to: .m hd select the numerators b from [0, 1, ..., d] ibd for which gcd(b, d) == 1 (which is the smallest possible gcd) this gives [0, 1] for d=1, [1] for d=2, [1,2] for d=3, ... s combine all lists to a big one @ Q print the Qth element ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 15 bytes This answer is based on [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/98621/47581). I use `HN` at the end to avoid issues with 0-indexing and needing to decrement n and swap at the beginning or end. `H` gets the first `n` members of the list of numerators that results and `N` gets the last member of that selection, i.e. the `n`th numerator, all without fiddling about with stack operations. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O1JgO3I7KeKZgOKUpOKWkWBNzqNITg&input=OQ) ``` ;R`;r;)โ™€โ”คโ–‘`MฮฃHN ``` **Ungolfing** ``` Implicit input n. ; Duplicate n. Leave one n on the stack for getting the nth numerator at the end. R`...`M Map the following function over the range [1..n]. Variable m. ; Duplicate m. Leave one m on the stack for checking coprimality later. r Push the range [0...m]. ;) Move a duplicate of range [0...m] to BOS. โ™€โ”ค Push a list of 0's and 1's where a 1 denotes a number coprime to m (a numerator), and 0 denotes a fraction we have counted before. โ–‘ Filter the second list (range [0...m]) by the truthy values in the first list (our coprime check). ฮฃ Sum all of the lists in the result into one list. H Push result[:n] using the duplicate of n from the beginning of the program. N Push result[:n][:-1], which is the same as result[n-1], our nth numerator. Implicit return. ``` [Answer] ## Python, ~~111~~ 110 bytes ``` from fractions import* def g(n): x,y=1,1 while n>1: x+=1 if x>y:x,y=1,y+1 if gcd(x,y)<2:n-=1 return x ``` The fraction is represented with `x/y`. The argument `n` is decremented when a new fitting fraction is found (the `gcd` from `fractions` checks can the fraction be reduced). In each iteration of the loop, `x` is incremented, then, if `x>=y`, a new series of fractions with `y+1` is started, `>` because of the "special case" `(x,y)=(2,1)`, golfed to `x>y`. I am sure this can be golfed more, but I am missing where I could improve it. Found it. [Link to code and test cases](https://repl.it/EPse/1) [Answer] ## JavaScript (ES6), 95 bytes ``` n=>[...Array(n*n).keys()].filter(i=>i%n<=i/n&g(i%n+1,i/n+1|0)<2,g=(a,b)=>b?g(b,a%b):a)[n-1]%n+1 ``` Works by generating all `nยฒ` fractions with numerators and denominators from `1` to `n` and filtering out those greater than `1` or previously seen, then taking the `n`th. [Answer] # Perl, 82 + 2 (`-pl` flag) = 84 bytes ``` perl -ple '{{$d>$n?($n++,(grep!($n%$_||$d%$_),2..$d)&&redo):($n=1,$d++)}++$i!=$_&&redo;$_=$n}' ``` Ungolfed: ``` while (<>) { # -p flag chomp(); # -l flag my $i = 0; my $n = 0; my $d = 0; for (;;) { for (;;) { if ($d <= $n) { $n = 1; $d++; last; } else { $n++; last unless grep { !($n % $_) && !($d % $_) } 2 .. $d; } } if (++$i == $_) { $_ = $n; last; } } } continue { print($_, "\n"); } ``` [Answer] # JavaScript (ES6), 76 ``` x=>eval("for(g=(a,b)=>b?g(b,a%b):a,d=n=0;x;g(n,d)-1||--x)n=++n>d?(++d,1):n") ``` *Less golfed* ``` x=>{ g=(a,b) => b ? g(b,a%b) : a; // gcd for (d=n=0; x; ) { ++n; if (n > d) { ++d; n=1; } if (g(n,d) == 1) // if the fraction is irreducible --x; } return n } ``` **Test** ``` f= x=>eval("for(g=(a,b)=>b?g(b,a%b):a,d=n=0;x;g(n,d)-1||--x)n=++n>d?(d++,1):n") ;`1 -> 1 2 -> 1 3 -> 1 4 -> 2 5 -> 1 6 -> 3 7 -> 1 8 -> 2 9 -> 3 50 -> 4 80 -> 15`.split`\n`.forEach( r=>{ var [a,k]=r.match(/\d+/g),r=f(a) console.log(r==k?'OK':'KO',a,r) } ) ``` [Answer] # Clojure, 85 bytes ``` #(if(= 1 %)1(numerator(nth(distinct(for[i(range)j(range 1(inc i))](/ j i)))(dec %)))) ``` Uses list comprehension to generate list of all rationals, then filters it to get only distinct ones. Takes `nth` item of the list and returns its numerator. Also separate condition is needed for the first element because Clojure isn't able to take numerator of an integer. (for whatever reason considering an integer to be not Rational โ€“ <https://goo.gl/XETLo2>) See it online โ€“ <https://ideone.com/8gNZEB> ]
[Question] [ **Challenge:** You are given a string containing only digits. Your task is to output the minimum number of primes which must be concatenated to form the string. If this is impossible, output `0`. **Test Cases:** Input -> Output: ``` 252 -> 3 235 -> 2 92 -> 0 31149 -> 2 ``` [Answer] # JavaScript (ES6), ~~123~~ ~~121~~ 120 bytes ``` f=(s,v)=>(p=n=>--n-1?s%n&&p(n):1)(s)||[...s].map((_,i)=>!(n=i&&(a=f(s.slice(0,i)))&&(b=f(s.slice(i)))&&a+b)|n>v?0:v=n)|v ``` *Saved a byte thanks to @Neil!* ## Explanation Takes a single string as input. Due to the prime checking method (recursive trial division), the greatest number that can be safely checked is `13840`. Some numbers above this will fail due to the maximum call stack size being exceeded. It does, however, finish instantly for every case it can handle. ``` f=(s,v)=> (p=n=>--n-1?s%n&&p(n):1)(s) // if s is prime, return 1 ||[...s].map((_,i)=> // else for each index in s, split s into 2 !(n=i&& // v = return value (initialised to undefined) (a=f(s.slice(0,i)))&& (b=f(s.slice(i)))&& a+b )|n>v?0:v=n // if i, a, b and n are all > 0 and !(n > v), v = n )|v // cast v to an integer and return it // Test var testCases = [ "252", "235", "92", "3149", "24747" ]; document.write("<pre>" + testCases.map(c => c + ": " + f(c)).join("\n")); ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~26~~ 24 bytes ``` 0in:"GUtZq@Z^V10ZA=a?x@. ``` It takes a few seconds for some of the test cases. [**Try it online!**](http://matl.tryitonline.net/#code=MGluOiJHVXRacUBaXlYxMFpBPWE_eEAu&input=JzIzNSc) ### Explanation ``` 0 % Push 0 in: % Take input. Generate array [1,2,...,N] where N is input length " % For each. In each iteration the number of used primes is increased GU % Push input. Convert to number tZq % Duplicate. Array of primes smaller than the input @ % Push number of primes to bes tested in this iteration Z^ % Cartesian power V % Convert to 2D array. Each row is a combination of primes 10ZA % Convert each row to base 10, disregarding spaces =a % Do any of the results equal the input number? ? % If so x % Remove the 0 that's at the bottom of the stack . % Break for each loop % Implicitly end if % Implicitly end for each % Implicitly display ``` [Answer] # Pyth, 16 bytes ``` lhaf!f!P_sYT./zY ``` [Test suite](https://pyth.herokuapp.com/?code=lhaf%21f%21P_sYT.%2FzY&test_suite=1&test_suite_input=252%0A235%0A92%0A1&debug=0) Explanation to follow. [Answer] # Pyth - ~~19~~ ~~17~~ 16 bytes ``` lhf.AmP_sdTa./zY ``` [Test Suite](http://pyth.herokuapp.com/?code=lhf.AmP_sdTa.%2FzY&input=252&test_suite=1&test_suite_input=252%0A235%0A92%0A31149&debug=0). [Answer] # Bash + coreutils, ~~169~~ ~~158~~ 149 bytes ``` c() { test $1||echo a for i in `seq ${#1}` do factor ${1::$i}|grep -q ': \w*$'&&printf b%s\\n `c ${1:$i}` done } c $1|sort|sed '/a/!d;s/..//;q'|wc -c ``` We count in unary, outputting a line with one `b` for each prime and a terminating `a` at the end of line (so that `printf` has a token to work with). The primality test is `factor $n | grep -q ': \w*$'`, which determines whether the number has exactly one prime factor. We recursively partition the input; if the left half is prime, we filter the results of the right half by adding one to each value. Returning `a` for a zero-length input terminates the recursion. Finally, we take all the results and sort to find the shortest (ignoring any that don't have the `a` to indicate success); we must delete two (for the inserted `a` and for the newline), then count characters to give the result. ### Tests ``` $ for i in 252 235 92 31149 111; do echo "$i:"$'\t'"$(./77623.sh $i)"; done 252: 3 235: 2 92: 0 31149: 2 111: 0 ``` I added `111` to the tests to show that `1` is correctly considered non-prime. [Answer] # Mathematica, ~~142~~ 135 bytes ``` Min[Length/@Select[Join@@@Permutations/@IntegerPartitions@Length[a=#],And@@PrimeQ@*FromDigits/@a~Internal`PartitionRagged~#&]]/.โˆž->0& ``` As you can see, Mathematica was not built for this task. Takes a list of digits. [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ยฌโˆžรฟโ•”>รทโ–€โ†“โ˜ผ~รฎโ˜ผรณโ™€Rร Ex ``` [Run and debug it](https://staxlang.xyz/#p=aaec98c93ef6df190f7e8c0fa20c52854578&i=%22252%22%0A%22235%22%0A%2292%22%0A%2231149%22&m=2) ]
[Question] [ Given an input of four integers *x1*, *y1*, *x2*, and *y2*, output whether a white king in chess (with coordinates (*x1*, *y1*)) could catch a black pawn (with coordinates (*x2*, *y2*)) and capture it if the pawn is moving to promote to a queen as fast as possible. The coordinates of the board are as follows: ``` first coordinate (x) 12345678 1 .#.#.#.# 2 #.#.#.#. 3 .#.#.#.# second 4 #.#.#.#. coordinate 5 .#.#.#.# (y) 6 #.#.#.#. 7 .#.#.#.# 8 #.#.#.#. ``` Assume it is white to move (the king's turn) and that both players play optimally (the king will move as fast as possible to catch the pawn, and the pawn will move as fast as possible to promote). The input coordinates will always be distinct, and the pawn will never start with a y-coordinate of 8. The king moves one square in any direction every turn (it can move diagonally), and the pawn can only move one space forwards (decrease its y-coordinate), unless it's at its initial position (with our coordinate system, y-coordinate of 7), in which case it can move two spaces forwards. The input can be given as a whitespace-/comma-separated string, an array of strings/integers, or four function/command line/etc arguments. The coordinates can be given in whichever order is most convenient/golfy (so, accepting input as [y2, y1, x1, y2] is okay as long as it's consistent). The output must be a [truthy or falsy value](http://meta.codegolf.stackexchange.com/q/2190/3808). Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. **Truthy test cases**: `5 3 3 2` ![](https://i.stack.imgur.com/NLjW7.jpg) `6 1 1 7` ![](https://i.stack.imgur.com/NJcsm.jpg) `3 3 3 2` ![](https://i.imgur.com/s5av7Isb.jpg) `4 1 4 7` ![](https://i.stack.imgur.com/FsKXP.jpg) `7 7 1 7` ![](https://i.stack.imgur.com/hXiU5b.png) `1 8 1 7` ![](https://i.stack.imgur.com/cL7Fib.png) **Falsy test cases**: `6 4 3 2` ![](https://i.stack.imgur.com/IWdfx.jpg) `8 8 1 7` ![](https://i.stack.imgur.com/lUQDjb.png) `3 4 3 2` ![](https://i.imgur.com/mR0w3Pib.jpg) [Answer] ## Python 2, 53 40 ``` lambda x,y,p,q:y-2<q>=abs(x-p)+q/7+y/8*5 ``` The king has coordinates `(x, y)` and the pawn `(p, q)`. There are three significant cases: 1. The pawn is on rank 7 and the king on rank 8. To capture the pawn, the king must be on the same file or an adjacent one. Result: `q = 7 โ‹€ y = 8 โ†’ |x - p| โ‰ค 1` 2. The pawn is on rank 7. To capture the pawn, the king must be within six files. Result: `q = 7 โ†’ |x - p| โ‰ค 6` 3. The pawn is on a lower rank. To capture the pawn, the king must be able to reach the promotion square at most one move after the pawn. Result: `q < 7 โ†’ |x - p| โ‰ค q โ‹€ y - 1 โ‰ค q` My solution is just these conditions golfed down. Hopefully there aren't mistakes this time. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` โ€˜ยปฦ“_2<ยฎ ฦ“ยฉ<7 :5+ฦ“>7$ยค<1.4 ฦ“_ฦ“A2ยฃฤฟ ``` This program reads the coordinates as `x2\nx1\ny2\ny1` from STDIN. [Try it online!](http://jelly.tryitonline.net/#code=4oCYwrvGk18yPMKuCsaTwqk8Nwo6NSvGkz43JMKkPDEuNArGk1_Gk0EywqPEvw&input=Mwo1CjIKMw) ### Non-competing version Unfortunately, the Jelly interpreter had a bug when this question was posted. Said bug prevented it from accepting more than two command-line arguments. The newest version of Jelly can solve the given task in **23 bytes**. ``` โถ>7ร—5 _A+โต>6$ยค+ยขโ€™ยปโถ_2<โต ``` [Try it online!](http://jelly.tryitonline.net/#code=4oG2PjfDlzUKX0Er4oG1PjYkwqQrwqLigJnCu-KBtl8yPOKBtQ&input=&args=Mw+NQ+Mg+Mw) [Answer] # Prolog, ~~48~~ 42 bytes **Code:** ``` p(X,Y,P,Q):-Y-2<Q,Q>=abs(X-P)+Q//7+Y//8*5. ``` **Examples:** ``` p(1,8,1,7). true p(3,4,3,2). false ``` Not a bad challenge for Prolog compared to most. **Edit:** Saved 6 bytes by switching to the formula used in [grc's Python 2 answer](https://codegolf.stackexchange.com/a/68754/47066). Unfortunately Prolog can't chain comparisons as python can and integer division is 1 byte longer than float division. Try it online [here](http://swish.swi-prolog.org/p/oKqhHlpM.pl) [Answer] # JavaScript (ES6), 52 ``` (x,y,u,t,d=x>u?x-u:u-x)=>(d>=y?d:y-1)<=(d<2|t<7?t:6) ``` I hope to have saved bytes not using Math.abs, Math.min, Math.max The pawn at row seven can escape moving 2 spaces, if and only if the king is not in a near column - that's why there is a check on `d` before substituting 7 with 6. Test case to run in console: ``` ;[f(5,3,3,2),f(6,1,1,7),f(3,3,3,2),f(1,8,1,7),f(6,4,3,2),f(8,8,1,7),f(3,4,3,2)] ``` Result: `[true, true, true, true, false, false, false]` [Answer] # Ruby, 50 bytes ``` def f(a,b,c,d)(a-c).abs<=(d==7?6-b/8*5:d)&&b-d<2;end ``` Arguments are (king x, king y, pawn x, pawn y), all integers. ]
[Question] [ **Premise** One night, I was just contemplating on numbers. I found out about something unique about numbers like 7, 10, 12, 13, and more. They are squares of squares! Meaning, that when squared, are comprised of squares themselves. The OEIS calls them Squares which are a decimal concatenation of two or more squares. Examples of such numbers include 7 (49 has 22 and 32) 13 (169 has 42 and 32) and 20 (400 has 22 and 02). Other examples include 37, as 1369 is a term as it can be partitioned as 1, 36 and 9. 1444 (382) is a term as it can be partitioned as 1, 4, 4, 4. I asked about this on Math.SE, and it was named after [me!](https://math.stackexchange.com/questions/1499423/squares-with-squares#comment3054384_1499423) **Challenge** Design a program that prints TanMath numbers. Given the number n (starting at 1), print the nth TanMath number, T(n). As a code example: ``` >> 1 >> 7 ``` or ``` >> 4 >> 13 ``` Reference Python implementation(thanks @MartinBรผttner and @Sp3000!): ``` from math import sqrt n = input() def r(digits, depth): z = len(digits) if z < 1: return (depth > 1) else: for i in range(1, z+1): t = int(digits[:i]) if sqrt(t).is_integer() and r(digits[i:], depth+1): return True return False i=0 t=0 while t < n: i += 1 if r(str(i**2), 0): t += 1 print i ``` Here is a list of the first 100 numbers: > > 7 10 12 13 19 20 21 30 35 37 38 40 41 > 44 50 57 60 65 70 80 90 95 97 100 102 105 107 108 110 112 119 120 121 > 125 129 130 138 140 150 160 170 180 190 191 200 201 204 205 209 210 > 212 220 223 230 240 250 253 260 270 280 285 290 300 305 306 310 315 > 320 325 330 340 342 343 345 348 350 360 369 370 375 379 380 390 397 > 400 402 405 408 410 413 420 430 440 441 450 460 470 475 480 487 > > > This is a code golf, so the shortest code wins! Good luck! [Answer] # Pyth, ~~23~~ ~~21~~ 20 bytes ``` e.ff!-sMT^R2Z./`^Z2Q ``` *Thanks to @isaacg for golfing off 1 byte!* [Try it online.](http://pyth.herokuapp.com/?code=e.ff%21-sMT%5ER2Z.%2F%60%5EZ2Q&input=5) ### How it works ``` (implicit) Store the evaluated input in Q. .f Q Filter; find the first Q positive integers Z such that: ^Z2 Compute the square of Z. ` Cast to string. ./ Compute all partitions of the string. f Filter; find all partitions T such that: sMT Cast all elements of T to integer. ^R2Z Compute the squares of all integers in [0, ..., Z-1]. - Remove the squares from the integers in T. ! Compute the logical NOT of the result. This returns True iff all integers in T are squares of numbers less than Z. Keep T if `!' returned True. Keep Z if `!' returned True for at least one T. e Retrieve the last of the Q matches. ``` [Answer] # Julia, ~~189~~ 145 bytes ``` n->(c=m=0;while c<n m+=1;d=["$(m^2)"...];for p=partitions(d) d==[p...;]&&!any(โˆšmap(parse,map(join,p))%1.>0)&&endof(p)>1&&(c+=1;break)end;end;m) ``` This creates an unnamed function that accepts an integer and returns an integer. To call it, give it a name, e.g. `f=n->...`. Ungolfed: ``` function tanmath(n::Integer) # Initialize the number to check (c) and the nth TanMath # number (m) both to 0 c = m = 0 # While we've generated fewer than n TanMath numbers... while c < n # Increment the TanMath number m += 1 # Get the digits of m^2 as characters d = ["$(m^2)"...] # Loop over the unordered partitions of the digits for p in partitions(d) # Convert the partition of digits to parsed numbers x = map(parse, map(join, p)) # If the partition is in the correct order, none of the # square roots of the digits are non-integral, and p is # of length > 1... if d == [p...;] && !any(sqrt(x) % 1 .> 0) && endof(p) > 1 # Increment the check c += 1 # Leave the loop break end end end # Return the nth TanMath number return m end ``` Thanks to Dennis for some help and ideas and thanks to Glen O for saving 44 bytes! [Answer] # JavaScript ES6, 126 ~~127~~ The reference implementation, converted to Javascript with some golf trick. Using eval to avoid explicit return. Test running the snippet below in an EcmaScript 6 compliant browser, with spread operator, default parameters and arrow functions (I use Firefox) ``` F=n=>eval('for(i=t=0;t<n;t+=k([...i*i+""]))++i',k=(s,l=1,n="")=>s[0]?s.some((d,i)=>Math.sqrt(n+=d)%1?0:k(s.slice(i+1),l-1)):l) // Less golfed U=n=>{ k = (s,l=1,n="") => s[0] ? s.some((d,i) => Math.sqrt(n+=d)%1 ? 0 : k(s.slice(i+1),l-1) ) : l; for(i=t=0; t<n; ) { ++i; t += k([...i*i+""]) } return i } function test() { R.innerHTML=F(+I.value) } test() ``` ``` <input id=I value=100><button onclick='test()'>-></button> <span id=R></span> ``` [Answer] # JavaScript (ES6), 143 bytes ``` f=n=>{for(i=c=0;c<n;c+=1<g(++i*i+""))g=s=>{for(var l=0;s[l++];)if(!(Math.sqrt(s.slice(0,l))%1)&&!s[l]|(r=!!g(s.slice(l))))return 1+r};return i} ``` ## Usage ``` f(100) => 487 ``` ## Explanation ``` f=n=>{ for( i= // i = current number to check c=0; // c = number of TanMath numbers found so far c<n; // keep looping until we have found the required TanMath number c+=1< // increment the count if it has multiple squares in the digits g(++i*i+"") // check if the current number is a TanMath number ) g=s=>{ // this function is passed a number as a string and returns the // number of squares found (max 2) or undefined if 0 for(var l=0;s[l++];) // loop through each digit // ('var' is necessary because the function is recursive) if( !(Math.sqrt( // check if the square root of the digits is a whole number s.slice(0,l) // get the digits to check )%1)&& !s[l]| // finish if there are no more digits left to check (r=!! // r = true if number of squares in remaining digits > 0 g(s.slice(l)) // get number of squares in remaining digits ) ) return 1+r // return number of squares found }; return i // return the number that the loop finished at } ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 44 bytes ``` {grep({$^aยฒ~~/^<{(^$a)>>ยฒ}>+$/},1..*)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUCjWiUu8dCmujr9OJtqjTiVRE07u0Obau20VfRrdQz19LQ0o1XiY2v/FydWKqQpxBlaWP8HAA "Perl 6 โ€“ Try It Online") The runtime of this inflates fast, due to bruteforcing the combination of powers in the regex. If this were a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") instead, then the submission could just be that central codeblock instead. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 12 bytes ``` ยฒล’แน–แธŒแน–ร†ยฒPฦ‡ยต#แนช ``` [Try it online!](https://tio.run/##y0rNyan8///QpqOTHu6c9nBHD5A83HZoU8Cx9kNblR/uXPX/v6GBAQA "Jelly โ€“ Try It Online") ## How it works ``` ยฒล’แน–แธŒแน–ร†ยฒPฦ‡ยต#แนช - Main link. Takes no arguments ยต# - Read n from STDIN and run the following over k = 1, 2, 3, ... until n integers return True: ยฒ - Yield kยฒ ล’แน– - Yield all partitions of kยฒ's digits แธŒ - Convert each list of digits back into a number ร†ยฒ - Yield 1 for perfect squares and 0 otherwise Pฦ‡ - Remove all lists with any zeros This returns an empty list (falsy) for non-TanMath numbers and a non-empty list (truthy) for TanMath numbers แนช - Return the last element i.e. the nth number for which the above is true ``` [Answer] # Lua, 148 bytes ``` c=...r=load"a=a or...==''for p=0,...and n-1or-1 do p='^'..p*p..'(.*)'r(p.match(...,p))end"n=-1repeat n=n+1r(n*n)c,a=c-(a and 1or 0)until c<1print(n) ``` Lua 5.3 is required ``` $ lua program.lua 1 7 $ lua program.lua 10 37 $ lua program.lua 100 487 ``` [Answer] # Python 3, ~~283~~ 243 bytes This is a brute-force implementation. Golfing suggestions welcome. ``` from itertools import* def t(n): a=m=0 while a<n:m+=1;d=str(m*m);r=range(1,len(d));c=[i*i for i in range(m)];a+=any(all(p in c for p in q)for q in[[int(d[x:y])for x,y in zip((0,)+j,j+(None,))]for i in r for j in combinations(r,i)]) return m ``` **Ungolfed:** ``` import itertools def tanmath(n): a = 0 m = 0 while a < n: m += 1 d = str(m*m) squares = [i*i for i in range(m)] z = [] # partitions code for i in range(1, len(d)): for j in itertools.combinations(range(1, len(d)), i): partition_indices = zip((0,)+j, j+(None,)) z.append([int(d[x:y]) for x, y in partition_indices] # end partitions code if any(all(p in squares for p in q) for q in z): a += 1 return m ``` ]
[Question] [ *This challenge is loosely inspired by the Zachtronics game [Infinifactory](http://www.zachtronics.com/infinifactory/).* You are given a top-down view of a rectangular grid of conveyors, represented by `>v<^`. There may be cells without conveyors, represented by spaces. Here is an example: ``` > <vv < v ^ >v v >v^^>vv^ ^>^ v > v<v >> >v v<^ ``` This setup is implicitly surrounded by an infinite number of spaces. Furthermore, you are given the dimensions of a rectangular piece of cargo which is placed onto the conveyors in the top left corner of the grid. Your task is to figure out whether the cargo ever comes to rest or whether it will end up moving in a loop. Of course, the cargo is likely to cover several conveyors at once, so here are the rules for figuring out the direction of the cargo in each step: 1. Opposite conveyors cancel each other. So if a 3x2 cargo covers any of the following patches (outlined with hyphens and pipes for clarity), the result would be the same: ``` +---+ +---+ +---+ |>>^| | ^| |v^^| |^<<| |^ | |^^v| +---+ +---+ +---+ ``` The same goes for these: ``` +---+ +---+ +---+ |v^<| | | |><>| |>>>| |>> | |>><| +---+ +---+ +---+ ``` Since the exact position of a conveyor underneath the cargo is irrelevant, it doesn't matter which pairs you cancel. This cancellation is applied before the other rules. Therefore, for the other rules there will only be conveyors in at most two directions. 2. If the cargo doesn't cover any conveyors at all (either because all conveyors cancel, because it covers only spaces or because it moved fully off the grid), it comes to rest. 3. If the cargo covers more conveyors of one direction than of the other, the cargo moves in that direction. E.g., if a 3x2 cargo covered the following patch ``` >> ^>^ ``` it would move to the right, because there are more `>` than `^`. On the other hand, if it covered ``` >>^ ^ ``` this rule would not apply, because there's a tie between `>` and `^`. 4. This leaves only cases in which there is a tie between adjacent directions (a tie between opposite directions would have cancelled). In this case, the cargo keeps moving along the axis it is already moving in. E.g. if a right-moving *or* left-moving 3x2 cargo is now covering the patch ``` >>^ ^ ``` it would move to the right. If it had arrived on this patch moving up or down, it would now move up instead. If this kind of conflict occurs on the very first step of the simulation, assume that the cargo had been moving to the right. ## Detailed Examples Consider the conveyor grid at the top and a 3x2 cargo. The following is a step-by-step visualisation of the process. Each step consists of the grid, with the cargo represented by `#`, a small box which shows the conveyors covered by the cargo, another box with the conveyors after cancellation, and the rule that determines where the cargo moves: ``` ###vv < > <vv < > <vv < > <vv < > <vv < > <vv < ###^ >v v ###^ >v v v ^ >v v v ^ >v v v ^ >v v v ^ >v v >v^^>vv^ ###v^^>vv^ ###v^^>vv^ ###^^>vv^ ###^>vv^ >###>vv^ ^>^ v ^>^ v ### ^>^ v ###^>^ v ###>^ v ###^ v > v<v >> > v<v >> > v<v >> > v<v >> > v<v >> > v<v >> >v v<^ >v v<^ >v v<^ >v v<^ >v v<^ >v v<^ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ |> <| | | | v | | v | | >| | >| | >v| | >v| |>v^| |> ^| |v^^| | ^^| | v | | v | | >| | >| | | | | | | | | | ^| | | | ^>| | >| +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ Rule 3 Rule 4 Rule 3 Rule 4 Rule 4 Rule 3 ================================================================================ > <vv < > <### < > <vv < v ###v v v ###v v v ###v v >###>vv^ >v^^>vv^ >###>vv^ ^>^ v ^>^ v ^>^ v > v<v >> > v<v >> > v<v >> >v v<^ >v v<^ >v v<^ +---+ +---+ +---+ +---+ +---+ +---+ |^ >| | >| |vv | | v | |^ >| | >| |v^^| | ^^| |^ >| | >| |v^^| | ^^| +---+ +---+ +---+ +---+ +---+ +---+ Rule 3 Rule 4 Rule 3 ``` At this point, the cargo enters a loop between the last two frames. Now consider a 2x3 cargo instead: ``` ##<vv < >##vv < > <vv < > <vv < > <vv < > <vv < ## ^ >v v ##^ >v v ##^ >v v v ^ >v v v ^ >v v v ^ >v v ##>v^^>vv^ ##v^^>vv^ ##v^^>vv^ ##v^^>vv^ ##^^>vv^ >v^^>vv^ ^>^ v ^>^ v ## ^>^ v ## ^>^ v ##^>^ v ##^>^ v > v<v >> > v<v >> > v<v >> >##v<v >> > ##<v >> > ##<v >> >v v<^ >v v<^ >v v<^ >v v<^ >v v<^ ## v<^ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ |> | |> | | <| | | |v | |v | | >| | >| |>v| |>v| | | | | | v| | v| |v | |v | | >| | >| | | | | | | | | | v| | v| | | | | | >| | | | | | | | | | | | v| | v| |>v| |>v| +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ Rule 4 Rule 3 Rule 4 Rule 3 Rule 3 Rule 3 ================================================================================ > <vv < > <vv < > <vv < v ^ >v v v ^ >v v v ^ >v v >v^^>vv^ >v^^>vv^ >v^^>vv^ ^>^ v ^>^ v ^>^ v > ##<v >> > v<v >> > v<v >> ## v<^ ## v<^ >v v<^ ## ## ## ## ## ## +--+ +--+ +--+ +--+ +--+ +--+ | v| | v| |>v| |>v| | | | | |>v| |>v| | | | | | | | | | | | | | | | | | | | | +--+ +--+ +--+ +--+ +--+ +--+ Rule 3 Rule 4 Rule 2 ``` In the last step, rule 2 applies because the cargo has moved off the grid, so it comes to rest and there won't be a loop. ## Rules and Assumptions Your input will be the conveyor grid as described above along with the width and height of the cargo. You may take these three parameters in any convenient order and format. For the grid, this means that you can read a single string with lines separated by newlines or other characters, or an array of strings, or an array of arrays of characters, as long as the individual grid cells are still represented by the characters `>v<^` and spaces. You should output a [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value if the setup results in a loop of at least two frames or a [falsy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) value if the cargo will come to rest. You may assume that the grid will be padded to a rectangle with spaces, and that the cargo will initially fit into the grid. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. This is code golf, so the shortest answer (in bytes) wins. ## Test Cases The test cases are grouped by grids. ``` Grid (2x2): >v ^< Width Height Loop? 1 1 True 1 2 True 2 1 True 2 2 False Grid (3x3): > v ^ < Width Height Loop? 1 1 False 1 2 False 1 3 False 2 1 False 2 2 True 2 3 True 3 1 False 3 2 True 3 3 False Grid (4x3): >^>v v^v ^ << Width Height Loop? 2 2 False Grid (6x5): >v>v>v ^v^v^v ^v^v^v ^>^>^v ^<<<<< Width Height Loop? 1 1 True 1 2 False 2 1 True 2 2 True 2 4 True 2 5 False 3 1 False 3 2 True 3 3 True 3 5 True 6 2 False 6 3 True 6 5 False Grid (10x6): > <vv < v ^ >v v >v^^>vv^ ^>^ v > v<v >> >v v<^ Width Height Loop? 1 1 False 2 3 False 2 6 False 3 2 True 5 4 False 6 1 True 10 6 False ``` As an additional set of test cases, consider that any input where the grid consists solely of spaces must yield a falsy result. I've checked all the test cases manually, so let me know if you think I've made a mistake. [Answer] # Python 2, 207 bytes ``` def f(L,w,h,u=0,v=0,D=1,S=[]):a,b,c,d=map(`[r[u*(u>0):u+w]for r in L[v*(v>0):v+h]]`.count,"v^><");D=cmp(abs(a-b),abs(c-d))<D;T=u,v,D;return T in S or a-b|c-d and f(L,w,h,u+cmp(c,d)*D,v+cmp(a,b)*0**D,D,S+[T]) ``` Input the grid as a list of rows, e.g. ``` ['>v>v>v', '^v^v^v', '^v^v^v', '^>^>^v', '^<<<<<'] ``` followed by the width and height. Returns `0` or `True` accordingly. ## Explanation ``` def f(L, # Grid w,h, # Width, height of cargo u=0,v=0, # Position of top-left of cargo, initially (0, 0) D=1, # Moving left/right = 1, up/down = 0 S=[] # Seen (pos, axis) pairs, initially empty ): # Arrows under cargo - no need for "".join since we only need to count v^<> A = `[r[u*(u>0):u+w]for r in L[v*(v>0):v+h]]` # Count for each arrow a,b,c,d=map(A.count,"v^><") # Golfed form of abs(a-b) < abs(c-d) or (abs(a-b) == abs(c-d) and D == 1) D=cmp(abs(a-b),abs(c-d))<D T=u,v,D return (T in S # Return True if (pos, axis) previously seen or a-b|c-d # Return 0 if all conveyors cancel and f(L,w,h, # Otherwise, recurse u+cmp(c,d)*D, # Update u if moving left/right v+cmp(a,b)*0**D, # Update v if moving up/down D, S+[T] # Add (pos, axis) to seen ) ) ``` [Answer] # Julia - ~~394~~ ~~300~~ ~~246~~ 214 bytes ``` f(A,x,y)=(Z=sign;(S,T)=size(A);X=x+1;Y=y+1;G=fill(5,S+2y,T+2x);G[Y:S+y,X:T+x]=A;C=0G;D=1;while C[Y,X]!=D C[Y,X]=D;i,j=sum(i->1-[19 8]i%82%3,G[Y:Y+y-1,X:X+x-1]);D=Z(2i^2-2j^2+(i!=0)D);X+=Z(i+D*i);Y+=Z(j-D*j)end;D^2) ``` Returns 1 if the cargo loops, and 0 if it comes to a stop. It's not "strictly" truthy/falsy, in that Julia doesn't permit 0 and 1 in boolean contexts... but I consider values `x` for which `bool(x)==true` are truthy and `bool(x)==false` are falsy. Input `A` should be of the form of a character array. If you're copy/pasting the conveyor grid, you'll need to get it into the appropriate form. To save you from having to manually handle it, use the following: ``` A=foldl(hcat,map(collect,split("""(PASTE GRID HERE)""","\n")))' ``` Where obviously, `(PASTE GRID HERE)` should be replaced with the grid itself. Double-check the spaces at the end of each line, to make sure it actually has all of the spaces (it doesn't check to make sure that all lines are equal length). Note that this line isn't part of the actual solution code, just a convenient piece of code to make using the solution code a bit easier. Ungolfed: ``` function f(A,x,y) # Determine size of grid for use later (S,T)=size(A) # Initialise starting position (performed here to save characters) X=x+1 Y=y+1 # Create an expanded field that is functionally "spaces" (to provide # spaces at edges for the cargo to stop in) G=fill(5,S+2y,T+2x) # Put the conveyor grid into centre of the expanded field G[Y:S+y,X:T+x]=A # Create an array storing the most recent movement direction: # will use 1=horizontal, -1=vertical, 0=stopped C=0G # Initialise current direction (same system as C) D=1 # Loop until it finds itself repeating a coordinate/direction pair while C[Y,X]!=D # Mark current coordinate/direction pair in array C[Y,X]=D # Determine the net coordinate pairing, stored in two variables # for golf purposes *SEE NOTE* i,j=sum(i->1-[19 8]i%82%3,G[Y:Y+y-1,X:X+x-1]) # Determine new movement axis (if D=0, cargo stopped) D=sign(2i^2-2j^2+(i!=0)D) # Update X or Y depending on signs of D and the appropriate direction X+=sign(i+D*i) Y+=sign(j-D*j) end # if D=ยฑ1, return 1 (cargo is still moving), otherwise return 0 return D^2 end ``` Note: `1-[19 8]i%82%3` has been chosen to map the five possible characters to the appropriate coordinate pairs by the most efficient method I could find. This is also the reason for using 5 to fill the spaces when creating `G` - it's a single-digit character that maps to `[0 0]`. Example of usage: ``` julia> A=foldl(hcat,map(collect,split(""">v>v>v ^v^v^v ^v^v^v ^>^>^v ^<<<<<""","\n")))'; julia> f(A,2,1) true julia> f(A,3,3) true julia> f(A,5,2) false ``` [Answer] # Ruby, ~~306 298 251 204~~ 198 ``` ->g,w,h{m=->y,x,d,v=[]{q=y,x r=->s{([""]*h+g)[y+h,h].map{|l|(?x*w+l)[x+w,w]}.join.count s} z=k=r[?v]-r[?^],j=r[?>]-r[?<] q[d=[d,1,0][j*j<=>k*k]]+=z[d]<=>0 v&[q<<d]!=[]?q!=v[-1]:m[*q,v<<q]} m[0,0,1]} ``` **Edit:** Thanks a lot to Ventero who shortened the code a lot by applying some amazing tricks! ### Input and output The code represents a ruby function that takes three parameters: * the grid, represented as an array of strings (each row is a different string) * the width of the cargo * the height of the cargo It returns `1` (truthy) in case there's a loop, or `nil` (falsy) in case the cargo rests. ### Tests Here it is passing all of Martin's tests: <http://ideone.com/zPPZdR> ### Explanation There are no clever tricks in the code; it's a pretty straightforward implementation of the rules. In the code below, `move` is a recursive function that makes a move according to the rules, and: * returns truthy in case of a loop * returns falsy in case of a rest * otherwise calls itself to execute the next move A more readable version is available [here](http://pastebin.com/YKLippCU). ***Note:** the golfed code has undergone several modifications and is no longer similar to the readable version.* ]
[Question] [ ### Background A [bijective base **b** numeration](https://en.wikipedia.org/wiki/Bijective_numeration), where **b** is a positive integer, is a bijective positional notation that makes use of **b** symbols with associated values of **1** to **b**. Unlike its non-bijective counterpart, no symbol has a value of **0**. This way, each non-negative integer **n** has a *unique* representation in bijective base **b**. Popular bijective numerations include unary, bijective base 2 (used in [bzip2's run-length encoding](https://codegolf.stackexchange.com/q/53062)) and bijective base 26 (used to number columns in spreadsheets). ### Definition In this challenge, we define the set **M** of symbols as ``` 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<=> ``` and a function **i** from **M** to the natural number such that **i('1') = 1, โ€ฆ, i('>') = 64**. Given a base **b** between **1** and **64** (both inclusive), we define that each non-negative integer **n** corresponds to the string **akโ€ฆa0**, consisting of symbols of **M**, such that **n = bki(ak)+โ€ฆ+b0i(a0)**. This correspondence is well-defined and bijective. Since an empty sum is defined as **0**, the integer **0** can be encoded as an empty string. ### Task Accept three strings as input: * An input base **b** between **1** and **64**, encoded as a bijective base **64** string. * A non-negative integer **n**, encoded as a bijective base **b** string. * An output base **B** between **1** and **64**, encoded as a bijective base **64** string. Given these three inputs, encode **n** as a bijective base **B** string. ### Test cases All test cases specify the input in the order **b**, **n**, **B**. ``` Input: "4" "" "8" Output: "" Input: "A" "16" "2" Output: "1112" Input: "2" "122" "A" Output: "A" Input: "3" "31" "1" Output: "1111111111" Input: ">" "Fe" "a" Output: "RS" ``` ### Rules * You may read the three strings in any convenient order, as such, an array of strings, a string representation thereof, concatenated or separated by single-character delimiters of your choice. * If you choose to print the output to STDOUT, you may only print the symbols and (optionally) a trailing newline. * Base conversion built-ins of all kinds are allowed. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # CJam, 43 ``` qA,s"?[a{A<":,:^+:Mf#):B;(bLa{(Bmd)M=\j\+}j ``` 3 bytes eradicated with [help](https://codegolf.stackexchange.com/a/54348/7416) from Dennis :) [Try it online](http://cjam.aditsu.net/#code=qA%2Cs%22%3F%5Ba%7BA%3C%22%3A%2C%3A%5E%2B%3AMf%23)%3AB%3B(bLa%7B(Bmd)M%3D%5Cj%5C%2B%7Dj&input=%3EFea) **Explanation:** The input is taken as `bnB`, concatenated into a single string. ``` q read the input A,s make an array of numbers from 0 to 9 and convert to string "?[a{A<" push this string, which contains the ends of 3 character ranges: uppercase letters: ['A'โ€ฆ'[') lowercase letters: ['a'โ€ฆ'{') "<=>": ['<'โ€ฆ'?') they're in a special order for the symmetric difference below :, for each character, make a range of all characters smaller than it :^ fold/reduce these 6 ranges using symmetric difference + concatenate with the digits before :M save in M; this is like the M from the statement, except it starts with a zero (for matching indexes) f# find the indexes in M of all characters from the input string ) take out the last value from the array :B; save it in B and pop it ( take out the first value b use it as a base and convert the remaining array to a number this works even if some of the digits are not in the "normal" range La{โ€ฆ}j calculate with memoized recursion, using an empty string for value 0 ( decrement the number Bmd divide by B and get the quotient and remainder ) increment the remainder (this is the last digit in bijective base B) M= get the corresponding character from M \j swap with the quotient, and convert the quotient recursively \+ swap again and concatenate ``` [Answer] # Pip, ~~84~~ ~~80~~ 78 bytes ``` m:J[,tAZLCAZ"<=>"]p:$+(m@?^b)*(m@?a)**RV,#bs:m@?cWn:px:(mn-(p:n//s-!n%s)*s).xx ``` [GitHub repository for Pip](http://github.com/dloscutoff/pip) Algorithms adapted from the Wikipedia article. Here's the explanation for a slightly ungolfed earlier version: ``` Implicit: initialize a,b,c from cmdline args; t=10; AZ=uppercase alphabet; x="" m: Build lookup table m: (J,t) 0123456789 (i.e. join(range(10)))... .AZ plus A-Z... .LCAZ plus lowercase a-z... ."<=>" plus <=> f:{ Define f(a,b) to convert a from bijective base b to decimal: $+ Sum of... (m@?^a) list of index of each character of a in m * multiplied item-wise by b**RV,#a b to the power of each number in reverse(range(len(a))) } t:{ Define t(a,b) to convert a from decimal to bijective base b: x:"" Reset x to empty string (not needed if only calling the function once) Wa{ While a is not zero: p:a//b-!a%b p = ceil(a/b) - 1 (= a//b if a%b!=0, a//b-1 otherwise) x:m@(a-p*b).x Calculate digit a-p*b, look up the corresponding character in m, and prepend to x a:p p becomes the new a } x Return x } (t Return result of calling t with these arguments: (f Result of calling f with these arguments: b 2nd cmdline arg m@?a) 1st cmdline arg's decimal value m@?c 3rd cmdline arg's decimal value ) Print (implicit) ``` Sample run: ``` dlosc@dlosc:~/golf$ python pip.py bijectivebase.pip ">" "Fe" "a" RS ``` [Answer] # Octave, 166 bytes ``` function z=b(o,x,n) M=['1':'9','A':'Z','a':'z','<=>'];N(M)=1:64;n=N(n);x=polyval(N(x),N(o));z='';while x>0 r=mod(x,n);t=n;if r t=r;end;z=[M(t),z];x=fix(x/n)-(r<1);end ``` Multi-line version: ``` function z=b(o,x,n) M=['1':'9','A':'Z','a':'z','<=>']; N(M)=1:64; n=N(n); x=polyval(N(x),N(o)); z=''; while x>0 r=mod(x,n); t=n;if r t=r;end; z=[M(t),z]; x=fix(x/n)-(r<1); end %end // implicit - not included above ``` Rather than create a map to convert a character to an index value, I just created the inverse lookup table `N` for ascii values `1..'z'` and populated it with the indices at the appropriate values. `polyval` evaluates the equation > > c1xk + c2xk-1 + ... + ckx0 > > > using the decimal-converted input value as the vector of coefficients `c` and the original base as `x`. (Unfortunately, Octave's `base2dec()` rejects symbols out of the normal range.) Once we have the input value in base 10, calculation of the value in the new base is straightforward. Test driver: ``` % script bijecttest.m a=b('4','','8'); disp(a); a=b('A','16','2'); disp(a); a=b('2','122','A'); disp(a); a=b('3','31','1'); disp(a); a=b('>','Fe','a'); disp(a); ``` Results: ``` >> bijecttest 1112 A 1111111111 RS >> ``` [Answer] # Perl, ~~261~~ ~~248~~ 229 bytes ``` sub t{$b=0;$b*=$_[1],$b+=ord($1=~y/0-9A-Za-z<=>/\0-A/r)while$_[0]=~/(.)/g;return$b}sub r{$n=$_[0];$n-=$m=($n-1)%$_[1]+1,$d=(chr$m)=~y/\0-A/0-9A-Za-z<=>/r.$d,$n/=$_[1]while$n;print$d}@a=split/,/,<>;r(t(@a[1],t@a[0],64),t@a[2],64) ``` multi-line, while loops ungolfed: ``` sub t{ # convert bijective base string to number $b=0; while($_[0]=~/(.)/g) {$b*=$_[1];$b+=ord($1=~y/0-9A-Za-z<=>/\0-A/r)} return$b} sub r{ # convert number to bijective base string $n=$_[0]; while($n) {$n-=$m=($n-1)%$_[1]+1;$d=(chr$m)=~y/\0-A/0-9A-Za-z<=>/r.$d;$n/=$_[1]} print$d} @a=split/,/,<>; # parse input r(t(@a[1],t@a[0],64),t@a[2],64) ``` `t` is a function to parse a number from a bijective-base string of a given base. `r` is a function to generate a bijective-base string of a given base from a number. The 3 comma-separated parameters are parsed from stdin and the functions are called as needed. Converting a positive number to a bijective base string is similar to a normal base. However where you would do something like this for a normal base: ``` string s = "" while(n) { c = (n % base) s = (c + '0') + s n -= c // not necessary because the division will take care of it n /= base } ``` you adjust the mod to give a range from 1 to base instead of 0 to base - 1: ``` string s = "" while(n) { c = (((n-1) % base)+1) s = (c + '0') + s n -= c // necessary in the case c = base n /= base } ``` [Answer] # Python 2, ... ~~317~~ ~~307~~ ~~298~~ 311 bytes Definitely golfable. I really hate how strings have no item assignment and lists have no `find`. I'll look into a better way than my fast fix that I have now. My method is to convert the input to a decimal number, then to the output base, then convert that to the bijective base. **Edit**: Found that my program didn't work when converting to Unary. It cost 13 bytes to fix with `e=F(o)<2`, etc. [**Try it here**](http://ideone.com/hgbqj0) ``` R=range;M="".join(map(chr,R(48,58)+R(65,91)+R(97,123)))+"<=>" b,s,o=input() F=M.find e=F(o)<2 B=lambda n:n and B(n/F(o)-e)+M[n%F(o)+e]or"" n=B(sum(F(s[~j])*F(b)**j for j in R(len(s)))) i=n.find('0') n=list(n) while-~i:n=n[:i-1]+[M[F(n[i-1])-1]]+[o]+n[i+1:];n=n["0"==n[0]:];i="".join(n).find('0') print"".join(n) ``` [Answer] # Python 2, 167 Bytes No special tricks in here really, except for the `[2::5]` slicing to get the charset at a lower byte count. ``` x=range;A=`map(chr,x(49,58)+x(65,91)+x(97,123))`[2::5]+'<=>' r=A.find b,n,B=input() B=r(B)+1 d=0;s='' for c in n:d=d*-~r(b)+r(c)+1 while d:d-=1;s=A[d%B]+s;d/=B print s ``` Tests: ``` "4","","8" >>> (empty string) ">","Fe","a" >>> RS "3","31","1" >>> 1111111111 "A","16","2" >>> 1112 "2","122","A" >>> A ``` [Answer] # CJam, ~~73~~ ~~70~~ ~~69~~ ~~55~~ ~~51~~ 48 bytes Latest version uses the CJam base conversion operator for the conversion from the source base, which I hadn't thought of until I saw @aditsu's solution. It also applies a recent tip by @Dennis for constructing the "digit" string (<https://codegolf.stackexchange.com/a/54348/32852>), as well as some other ideas shared on chat. ``` lA,s'[,_el^+"<=>"+:Lf#Ll#bLl#:K;{(Kmd)L=\}hs-]W% ``` Input format is the value, followed by the source and destination base, with each of them on a separate line. For the empty string, leave the first line empty. Example input: ``` 122 2 A ``` [Try it online](http://cjam.aditsu.net/#code=lA%2Cs'%5B%2C_el%5E%2B%22%3C%3D%3E%22%2B%3ALf%23Ll%23bLl%23%3AK%3B%7B(Kmd)L%3D%5C%7Dhs-%5DW%25&input=Fe%0A%3E%0Aa) Explanation: ``` l Get and interpret value from input. A,s Build the list of 64 "digits". Start with [0..9] '[, Build character sequence from \0 to Z. _el Lower case copy of the same sequence. ^ Symmetric set difference gives only letters from both sequences. + Concatenate with sequence of decimal digits, creating [0..9A..Za..z]. "<=>" Remaining 4 characters. + Concatenate, resulting in full 64 character "digit" string. :L ... and store it in variable L for repeated use. f# Look up input characters in digit list. Ll# Get source base from input, and look up value in digit list. b Base conversion. This produces the input value. Ll# Get destination base from input, and look up value in digit list. :K; Store it in variable K for use in loop, and pop it off stack. { Loop for generating output digits. ( Decrement to get ceiling minus 1 after division. Kmd Calculate divmod of current value with destination base. ) Increment mod to get 1-based value for digit. L= Look up digit character for digit value. \ Swap. Digit stays on stack for output, remaining value is processed in next loop iteration until it is 0. }h End of loop for generating output digits. s Final value is 0. Covert it to a string. - And subtract it from second but last value. This eliminates the 0, as well as the second but last value if it was a \0 character. ] Wrap digits in array. W% Reverse array, to get result from MSB to LSB. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ร˜BแธŠ;โ€œ<=>โ€ i@โ‚ฌโ‚ฌยขแธ…แธƒ2ฦญ/แป‹ยข ``` [Try it online!](https://tio.run/##y0rNyan8///wDKeHO7qsHzXMsbG1e9QwlyvT4VHTGiA6tOjhjtaHO5qNjq3Vf7i7@9Ci////R6u7parrKKjbgYhE9VgA "Jelly โ€“ Try It Online") ]
[Question] [ When I saw the title of [this closed question](https://codegolf.stackexchange.com/questions/5786/converting-infix-expressions-to-postfix-expressions), I thought it looked like an interesting code golf challenge. So let me present it as such: ### Challenge: Write a program, expression or subroutine which, given an arithmetical expression in [infix notation](http://en.wikipedia.org/wiki/Infix_notation), like `1 + 2`, outputs the same expression in [postfix notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation), i.e. `1 2 +`. (Note: [A similar challenge was posted earlier in January.](https://codegolf.stackexchange.com/questions/4620/convert-from-infix-notation-to-prefix-notation) However, I do feel the two tasks are sufficiently different in detail to justify this separate challenge. Also, I only noticed the other thread after typing up everything below, and I'd rather not just throw it all away.) ### Input: The input consists of a valid infix arithmetical expression consisting of **numbers** (non-negative integers represented as sequences of one or more decimal digits), balanced **parentheses** to indicate a grouped subexpression, and the four infix binary **operators** `+`, `-`, `*` and `/`. Any of these may be separated (and the entire expression surrounded) by an arbitrary number of space characters, which should be ignored.1 For those who like formal grammars, here's a simple BNF-like grammar that defines valid inputs. For brevity and clarity, the grammar does not include the optional spaces, which may occur between any two tokens (other than digits within a number): ``` expression := number | subexpression | expression operator expression subexpression := "(" expression ")" operator := "+" | "-" | "*" | "/" number := digit | digit number digit := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ``` 1 The only case where the presence of spaces may affect the parsing is when they separate two consecutive numbers; however, since two numbers not separated by an operator cannot occur in a valid infix expression, this case can never happen in valid input. ### Output: The output should be a postfix expression equivalent to the input. The output expression should consist only of numbers and operators, with **a single space character** between each pair of adjacent tokens, as in the following grammar (which *does* include the spaces)2: ``` expression := number | expression sp expression sp operator operator := "+" | "-" | "*" | "/" number := digit | digit number digit := "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" sp := " " ``` 2 Again for simplicity, the `number` production in this grammar admits numbers with leading zeros, even though they're forbidden in the output by the rules below. ### Operator precedence: In the absence of parentheses, the following precedence rules apply: * The operators `*` and `/` have higher precedence than `+` and `-`. * The operators `*` and `/` have equal precedence to each other. * The operators `+` and `-` have equal precedence to each other. * All operators are left-associative. For example, the following two expressions are equivalent: ``` 1 + 2 / 3 * 4 - 5 + 6 * 7 ((1 + ((2 / 3) * 4)) - 5) + (6 * 7) ``` and they should both yield the following output: ``` 1 2 3 / 4 * + 5 - 6 7 * + ``` (These are the same precedence rules as in the C language and in most languages derived from it. They probably resemble the rules you were taught in elementary school, except possibly for the relative precedence of `*` and `/`.) ### Miscellaneous rules: * If the solution given is an expression or a subroutine, the input should be supplied and the output returned as a single string. If the solution is a complete program, it should read a line containing the infix expression from standard input and print a line containing the postfix version to standard output. * Numbers in the input *may* include leading zeros. Numbers in the output *must not* have leading zeros (except for the number 0, which shall be output as `0`). * You are not expected to evaluate or optimize the expression in any way. In particular, you should not assume that the operators necessarily satisfy any associative, commutative or other algebraic identities. That is, you should not assume that e.g. `1 + 2` equals `2 + 1` or that `1 + (2 + 3)` equals `(1 + 2) + 3`. * You may assume that numbers in the input do not exceed 231 โˆ’ 1 = 2147483647. These rules are intended to ensure that the correct output is uniquely defined by the input. ### Examples: Here are some valid input expressions and the corresponding outputs, presented in the form `"input" -> "output"`: ``` "1" -> "1" "1 + 2" -> "1 2 +" " 001 + 02 " -> "1 2 +" "(((((1))) + (2)))" -> "1 2 +" "1+2" -> "1 2 +" "1 + 2 + 3" -> "1 2 + 3 +" "1 + (2 + 3)" -> "1 2 3 + +" "1 + 2 * 3" -> "1 2 3 * +" "1 / 2 * 3" -> "1 2 / 3 *" "0102 + 0000" -> "102 0 +" "0-1+(2-3)*4-5*(6-(7+8)/9+10)" -> "0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -" ``` (At least, I *hope* all these are correct; I did the conversion by hand, so mistakes might have crept in.) Just to be clear, the following inputs are all invalid; it does *not* matter what your solution does if given them (although, of course, e.g. returning an error message is nicer than, say, consuming an infinite amount of memory): ``` "" "x" "1 2" "1 + + 2" "-1" "3.141592653589793" "10,000,000,001" "(1 + 2" "(1 + 2)) * (3 / (4)" ``` [Answer] ## Shell utils -- 60 chars ``` bc -c|sed -re's/[@iK:Wr]+/ /g;s/[^0-9]/ &/g;s/ +/ /g;s/^ //' ``` Fixed the various problems, but it got a lot longer :( [Answer] ## C, 250 245 236 193 185 chars ``` char*p,b[99];f(char*s){int t=0;for(;*p-32? *p>47?printf("%d ",strtol(p,&p,10)):*p==40?f(p++),++p: t&&s[t]%5==2|*p%5-2?printf("%c ",s[t--]):*p>41?s[++t]=*p++:0:++p;);} main(){f(p=gets(b));} ``` Here's a readable version of the ungolfed source, that still reflects the basic logic. It's actually a rather straightforward program. The only real work it has to do is to push a low-associativity operator onto a stack when a high-associativity operator is encountered, and then pop it back off at the "end" of that subexpression. ``` #include <stdio.h> #include <stdlib.h> static char buf[256], stack[256]; static char *p = buf; static char *fix(char *ops) { int sp = 0; for ( ; *p && *p != '\n' && *p != ')' ; ++p) { if (*p == ' ') { continue; } else if (*p >= '0') { printf("%ld ", strtol(p, &p, 10)); --p; } else if (*p == '(') { ++p; fix(ops + sp); } else { while (sp) { if ((ops[sp] == '+' || ops[sp] == '-') && (*p == '*' || *p == '/')) { break; } else { printf("%c ", ops[sp--]); } } ops[++sp] = *p; } } while (sp) printf("%c ", ops[sp--]); return p; } int main(void) { fgets(buf, sizeof buf, stdin); fix(stack); return 0; } ``` [Answer] # Python 2, ~~290~~ ~~272~~ ~~268~~ ~~250~~ ~~243~~ 238 bytes Now finally shorter than the JS answer! This is a full program which uses a basic implementation of the [shunting yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm). Input is given as a quoted string, and the result is printed to `STDOUT`. ``` import re O=[];B=[] for t in re.findall('\d+|\S',input()):exec("O=[t]+O","i=O.index('(');B+=O[:i];O=O[i+1:]","while O and'('<O[0]and(t in'*/')<=(O[0]in'*/'):B+=O.pop(0)\nO=[t]+O","B+=`int(t)`,")[(t>'/')+(t>')')+(t>'(')] print' '.join(B+O) ``` ### [**Try it online!**](https://tio.run/nexus/python2#RY7BboMwDIbvPIWVS2wCFNa126DswAvksCNEajVSLRMLEcq0HvbuzEiVdvFv//rs36v7CvMSYbGJbnvTdFyS67xABOfZLa7Oj5dpQjmM6nd4k5nz4TsiUW1v9h0Fb0WjtMiEa3XBsL2hRElNp1rd1840mtWpqjbM/Hy4yYKGix8ZOum@NNziFibTnaRTi5t3n@rtRhHmgCUN/j@J7bPzESOdM0E9xlfJtNqU7sofmCQsTEmQxefsPHZK07qKMq9A4UMOe6D0MT9AisccnxQ80@5FVSWJPw) --- **Explanation:** The first thing we need to do is convert the input into tokens. We do this using by finding all matches of the regex `\d+|\S`, roughly translated to "any group of digits, and any non-space character". This removes whitespace, parses adjacent digits as single tokens, and parses operators seperately. For the shunting yard algorithm, there are 4 distinct token types we need to handle: * `(` - Left parenthesis * `)` - Right parenthesis * `+-*/` - Operators * `9876543210` - Numeric literals Thankfully, the ASCII codes of these are all grouped in the order shown, so we can use the expression `(t>'/')+(t>')')+(t>'(')` to calculate the token type. This results in **3** for digits, **2** for operators, **1** for a right parenthesis and **0** for a left parenthesis. Using these values, we index into the large tuple after `exec` to get the corresponding snippet to execute, based on the token type. This is different for each token and is the backbone of the shunting yard algorithm. Two lists are used (as stacks): `O` (operation stack) and `B` (output buffer). After all the tokens have been run, the remaining operators on the `O` stack are concatenated with the output buffer, and the result is printed. [Answer] ## Bash w/ Haskell w/ ~~C preprocessor~~ sed, 180 ~~195~~ ~~198~~ ~~275~~ ``` echo 'CNumO+O-O*fromInteger=show CFractionalO/ main=putStr$'$*|sed 's/C\([^O]*\)/instance \1 String where /g s/O\(.\?\)/a\1b=unwords\[a,b,\"\1\"];/g'|runghc -XFlexibleInstances 2>w ``` At last, it's not longer than the C solution anymore. The crucial Haskell part is almost as lazy as the bc solution... Takes input as command-line parameters. A file `w` with some ghc warning messages will be created, if you don't like this change to `runghc 2>/dev/null`. [Answer] # [Prolog (SWI-Prolog)](http://www.swi-prolog.org), 113 bytes ``` c(Z,Q):-Z=..[A,B,C],c(B,S),c(C,T),concat_atom([S,T,A],' ',Q);term_to_atom(Z,Q). p(X,Q):-term_to_atom(Z,X),c(Z,Q). ``` [Try it online!](https://tio.run/nexus/prolog-swi#@5@sEaUTqGmlG2WrpxftqOOk4xyrk6zhpBOsCaScdUKAVH5ecmJJfGJJfq5GdLBOiI5jrI66gjpQl3VJalFufEk@RA5kjh5XgUYE2Dw0qQiQcWAV//8XaKgb6BpqaxjpGmtqmeiaammY6WqYa1to6ltqGxgaaIKM1gMA "Prolog (SWI) โ€“ TIO Nexus") SWI Prolog has a much better set of builtins for this than GNU Prolog does, but it's still held back somewhat by the verbosity of Prolog's syntax. ## Explanation `term_to_atom` will, if run backwards, parse an infix-notation expression (stored as an atom) into a parse tree (obeying the usual precedence rules, and deleting leading zeroes and whitespace). We then use the helper predicate `c` to do a structural recursion over the parse tree, converting into postfix notation in a depth-first way. [Answer] ## Javascript (ES6), 244 bytes ``` f=(s,o={'+':1,'-':1,'*':2,'/':2},a=[],p='',g=c=>o[l=a.pop()]>=o[c]?g(c,p+=l+' '):a.push(l||'',c))=>(s.match(/[)(+*/-]|\d+/g).map(c=>o[c]?g(c):(c==')'?eval(`for(;(i=a.pop())&&i!='(';)p+=i+' '`):c=='('?a.push(c):p+=+c+' ')),p+a.reverse().join` `) ``` **Example:** Call: `f('0-1+(2-3)*4-5*(6-(7+8)/9+10)')` Output: `0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -` (with a trailing space) **Explanation:** ``` f=(s, //Input string o={'+':1,'-':1,'*':2,'/':2}, //Object used to compare precedence between operators a=[], //Array used to stack operators p='', //String used to store the result g=c=> //Function to manage operator stack o[l=a.pop()]>=o[c]? // If the last stacked operator has the same or higher precedence g(c,p+=l+' '): // Then adds it to the result and call g(c) again a.push(l||'',c) // Else restack the last operator and adds the current one, ends the recursion. )=> (s.match(/[)(+*/-]|\d+/g) //Getting all operands and operators .map(c=> //for each operands or operators o[c]? //If it's an operator defined in the object o g(c) //Then manage the stack :(c==')'? //Else if it's a closing parenthese eval(` //Then for(;(i=a.pop())&&i!='(';) // Until it's an opening parenthese p+=i+' ' // Adds the last operator to the result `) :c=='('? //Else if it's an opening parenthese a.push(c) //Then push it on the stack :p+=+c+' ' //Else it's an operand: adds it to the result (+c removes the leading 0s) ) ) ,p+a.reverse().join` `) //Adds the last operators on the stack to get the final result ``` [Answer] # R, 142 bytes R is able to parse itself, so rather than re-invent the wheel, we just put the parser to work, which outputs prefix notation, and use a recursive function to switch it to postfix notation. ``` f=function(x,p=1){ if(p)x=match.call()[[2]] if((l=length(x))>1){ f(x[[2]],0) if(l>2)f(x[[3]],0) if((z=x[[1]])!="(")cat(z,"") }else cat(x,"") } ``` The `p` argument is to control the use of non-standard evaluation (the bane of R programmers everywhere), and there are a few extra `if`s in there to control the outputting of brackets (which we want to avoid). Input: `(0-1+(2-3)*4-5*(6-(7+8)/9+10))` Output: `0 1 - 2 3 - 4 * + 5 6 7 8 + 9 / - 10 + * -` Input: `(((((1))) + (2)))` Output: `1 2 +` As a bonus, it works with arbitrary symbols, and any pre-defined functions with up to two arguments: ### Euler's identity Input: `e^(i*pi)-1` Output: `e i pi * ^ 1 -` ### Dividends of 13 between 1 and 100 Input: `which(1:100 %% 13 == 0)` Output: `1 100 : 13 %% 0 == which` ### Linear regression of baby chicken weight as a function of time Input: `summary(lm(weight~Time, data=ChickWeight))` Output: `weight Time ~ ChickWeight lm summary` The last example is perhaps a little outside the scope of the OP, but it does use postfix notation, so... [Answer] # [Perl 5](https://www.perl.org/), 177 bytes Exploiting Perl operator overloading: ``` sub{use overload nomethod=>sub{bless[@_[3,0,1]]};sub new{shift;bless[0,@_]}sub p{$_[0][0]?join$",(map$_[0][$_]->p,1,2),$_[0][0]:$_[0][1]}eval(pop=~s/0*(\d+)/new main($1)/gr)->p} ``` [Try it online!](https://tio.run/##fY9dT4MwFIbv9ytOmuraUUILbn4Q5u5N3I13k5CZgaIbrWN@ZcG/Pk9BozK0gXB43@e8Pcek6@VwR7NoVz7dbJ/KFPQzSnq@gEKv0s2dXkRja90s07KcTZJZIKRQcVyFqEKRvmzLuzzbhI0vxSSJK@uYLU1mMsbn/F7nBSWCream0WgSu2MjlPC5@KLOmkLFVfo8XzKjTfReenLArhcO9/AeWM3zglHFvds1x/ZqF2Z6zXoAMyCKwN6JxlAbsfhkwAGfdDHgg/PNgZQKkAXpA/mHY/YozjmyzMcv6eaU45Pu2VqcnQ/fgHRxELRZVquc7LFI7ucOunMDNH6x3t@sZ@lvtubABdVmm1QF7m@W1XBrXssi@TNXKmk3k3hau6Euf04rXeUw3w344MgdDtjIZcfOCfdOHSXxGuwhsg736zmP7KowhBEcwwlWp7gQDoSJaDSz8m3P3rZ6YzQvjKDpq@HRhCbhp0xv9SY6pFlt80Y167zYZOTAHZUAKEfWQx17IxuApe2yrdcFqTMhfQT7f97XD/2z/uX0CqYX/bBX7T4A "Perl 5 โ€“ Try It Online") ]
[Question] [ ## Haplology Haplology is a linguistic term: > > the omission of one occurrence of a sound or syllable that is repeated within a word, for example probly for probably. > > > For this challenge, it means specifically, replacing any sequences of two or more letters that are repeated two or more times with just one copy. For example: * haplology -> haplogy * [boobook](https://en.wikipedia.org/wiki/Australian_boobook) -> book * couscous -> cous * [ngorongoro](https://en.wikipedia.org/wiki/Ngorongoro_Conservation_Area) -> ngoro * hehehe -> he * [whakakakakaka](https://books.google.com.au/books?id=IIShzeI-l2IC&pg=PA212&lpg=PA212&dq=%22whakakakakaka%22&source=bl&ots=iAvoUxdspI&sig=ACfU3U2NmOv8IKilvNty_Efm8HSd5x_2ww&hl=en&sa=X&ved=2ahUKEwjq_5D9k8X3AhUBH7cAHRTjBRUQ6AF6BAgoEAM#v=onepage&q=%22whakakakakaka%22&f=false) -> whaka * [lerderderg](https://en.wikipedia.org/wiki/Lerderderg_Gorge) -> lerderg If there are multiple, non-overlapping repeating sequences, they all get replaced: * cancangogo -> cango * yadayadablahblah -> yadablah Only a single round of replacements is performed, taking the longest possible sequences first, then working from left to right: * mississippi -> missippi * mymememymemebooboo -> mymemeboo * aaaabaaaab -> aaaab This means the returned result can contain repeating sequences: * babambambadingding -> babambading It cans also mean the end result is longer that it would be if replacement happened strictly left to right: * bababababababadoobababababababadoo -> bababababababadoo (not badoobadoo) Any spaces or hyphens that occur between elements of a repeating section must be stripped out, and otherwise retained: * [lang lang](https://en.wikipedia.org/wiki/Lang_Lang) -> lang * [cha-cha-cha](https://en.wikipedia.org/wiki/Cha-cha-cha_(dance)) -> cha * hi-di-hi-di-hi-di-ho -> hi-di-ho * tut-tutting -> tutting * lady gaga -> lady ga * banana-cocoa agar agar -> bana-coa agar * [who put the bop in the bop shoo bop shoo bop who put the dip in the dip da dip da dip](https://www.youtube.com/watch?v=lXmsLe8t_gg) -> who put the bop in the bop shoo bop who put the dip in the dip da dip * [hare krishna hare krishna krishna krishna hare hare hare rama hare rama rama rama hare hare](https://en.wikipedia.org/wiki/Hare_Krishna_(mantra)) -> hare krishna krishna hare hare rama rama hare ### Challenge Write a function/program/etc which applies haplology, as defined above, to a single input string. ### Inputs and outputs Each input will match this regex: `^[a-z]([a-z -]?[a-z])*$` Your output is a lowercase string containing the haplologised input. No extraneous characters. Standard rules for taking input and output. ### Scoring Code golf. Standard rules and exclusions apply. ### Updates #### Additional test cases and clarification The algorithm (ignoring punctuation) is: * find the longest chunk of letters that is repeated at least twice, giving precedence to the left-most chunk * replace those repeated chunks with one chunk * repeat, until none left * never allow any any letter to be processed as part of different chunks * mamapapatatat -> mapatat (there is no duplicated sequence longer than 2 characters, so work left to right: mama, papa, tata) * babababa -> baba ([baba] x2) * ratratatat -> ratat ([rat] x2, [at] x2) #### Questions > > Why does babambambadingding give babambading instead of bambading (from [baba][mbamba][dingding])? > > > In order of priority, the chunks are [ding], [bam]. The chunk [mba] is the same length as [bam], but [bam] occurs to its left. > > Why doesn't the "hare krishna" test case greedily take the third consecutive hare? > > > Because the longer [hare rama] takes precedence over the shorter [hare] [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~45~~ 38 bytes ``` แธทโฑฎjโฑฎฦคโ€œโ€œ โ€œ-โ€แบŽส‹ฦคแน–e@โ‚ฌi1แธฃ@ศฏ ล’แน–ร‡ฦ‘รแธŸแบˆแนขแนšฦฒรžแนชร‡โ‚ฌ ``` [Try it online!](https://tio.run/##y0rNyan8///hju2PNq7LAuJjSx41zAEiBSDWfdQw9@GuvlPdx5Y83Dkt1eFR05pMw4c7FjucWM91dBJQ6HD7sYmHJzzcMf/hro6HOxc93Dnr2KbD8x7uXHW4Haj2/8PdWw5t1TncngUyT9dOAWTczhbNhztnAwX@/8/NLC4GoYKCTK5EGAAA "Jelly โ€“ Try It Online") ~~Should be correct [for real this time](https://tio.run/##y0rNyan8///hju2PNq7LAuJjSx41zAEiBSDWfdQw9@GuvlPdx5akOjxqWpNp@HDHYgeuo5Me7px2uP3YxMMTHu6Y/3BXx8Odix7unHVs0@F5D3euOtwOVPn/4e4th7bqHG7PAhmla6cAMmlni@bDnbOBAv//5ybmJhYAYQkIAgA) thanks to Tanner Swett.~~ Should be correct [*for real this time*](https://tio.run/##y0rNyan8///hju2PNq7LAuJjSx41zAEiBSDWfdQw9@GuvlPdx5Y83Dkt1eFR05pMw4c7FjucWM91dBJQ6HD7sYmHJzzcMf/hro6HOxc93Dnr2KbD8x7uXHW4Haj2/8PdWw5t1TncngUyT9dOAWTczhbNhztnAwX@/8/NLC4GoYKCTK5EGAAA). It's [even less performant now](https://tio.run/##XYxNSsRAEIX3fYraCvbCC8hcpfJDumNMD0kGmd0gAxEEURcu/AWdlYiiKKbHncEg3qJykVgJkpnY1e@r19WPCv0omjYNFe/182PIqhb17JIvsGQ9u6Ll0c9htSB75o/q/Qe9RcXd6PtJfJ3yqMyrk/KYihtaHpC9JXtevZTXZO/LnLMNfbx@vm2Wedjuk9vQrrPzDbIXPGga5ON0EBHGAbQQrkL5J6G09LQc0IhskklWpjkcoTeFAAMUDsZc0jWuQeBB0kHsKQPjSQaZ8sExY9Bxb1NlzNCshz3dh1vr4VoTChMfdhKdqhhh8Pjfu88VEtzFNbdCHxGYdBVomWL8Cw)! Now designed from the ground up to handle spaces and hyphens, but there's got to be a shorter way to do `โ€œโ€œ โ€œ-โ€`... ``` แธทโฑฎjโฑฎฦคโ€œโ€œ โ€œ-โ€แบŽส‹ฦคแน–e@โ‚ฌi1แธฃ@ศฏ Monadic helper link: de-n-plicate an entire string ส‹ฦค For each prefix of the argument: โฑฎ create a list of, for each element of the argument แน– but one, แธท a copy of the prefix; ฦค for each prefix of that list, j join the copies on โฑฎ โ€œโ€œ โ€œ-โ€ each of the empty string, a space, and a hyphen; แบŽ flatten the results. e@โ‚ฌ Check if the argument is in each of those, i1 get the first index of 1, แธฃ@ and return the argument truncated to that length ศฏ or unchanged if it's 1 long and got clobbered. ล’แน–ร‡ฦ‘รแธŸแบˆแนขแนšฦฒรžแนชร‡โ‚ฌ Main link ล’แน– All ways to partition the input. ฦฒรž Sort them by แบˆ the lengths แนขแนš sorted descending of รแธŸ the slices which are not ฦ‘ unchanged by ร‡ the helper link, แนช take the last, ร‡โ‚ฌ and map the helper over its slices. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .ล“ฮตDรผ2ฮตร‹yฮตโ€ž -SNiร›รซรœ}}ร‹~yโ‚ฌgโ‰ P*}Zi_1ลกรJรซยฏ]หœรฉIยชะฝ ``` Very slow, but should work for all test cases including those in the comments. [Try it online](https://tio.run/##yy9OTMpM/f9f7@jkc1tdDu8xOrf1cHflua2PGuYp6Ab7ZR6efXj14Tm1tYe76yofNa1Jf9S5IECrNioz3vDowsP9XodXH1ofe3rO4ZWeh1Zd2Pv/f0ambkqmLpTMBwA) or [verify some of the smaller test cases](https://tio.run/##jY8xS8NAFMf3forjRmkKOlakgzrooILgoBS9pOEaGnMhd9HeEBEHQToIOlpER63gFHFQhB6dhOBnyBeJeWd7trh493@P97/HPd6PcWJ7boHXgjAWvI5wY2n40shSXNRG11m6ot4WslT1ZJbmp7fI2t7w1I0aqH6SqN6JzM@eaH5xtzWX7Hr786N7dbmuBsPn5mdfPcjh49d7gWs7Cd6MxfT0Cl5mUeQ6AkUuj33BG7iqXo/kAV7thuWz26oj9bGIiCNi4kON8vOr8rNUvWqxh9suXFxF2GasVAdKh8UcAuo2CX3mMyrB@KQlESWUgAkoi5hOuuVGLS2qJ5CgFGVU90h5bJ3AHXqcg8LQA9sllhbUIhZWGUI3jtuko68eYdkWhPOzRkARpLFBdMagPw5pS2wHNyvAPOY1sAZ0BtNA/vJN4Ka4DJLhGZNMUUwIzPb/Wdys/A0). (Some of the test cases are slightly modified in the test suite.) **Explanation:** ``` .ล“ # Get all partitions of the (implicit) input-string ฮต # Map over each partition-list: D # Duplicate the partition-list รผ2 # Get the overlapping pairs of the strings ฮต # Map over each pair: ร‹ # Check if both strings in the pair are the same y # Push the pair again ฮต # Map over it: โ€ž -S # Push pair ["-"," "] Ni # If the inner map-index is 1 (thus the right item): ร› # Strip the leading "-"/" " รซ # Else (it's 0, thus the left item): รœ # Strip the trailing "-"/" " } # Close the if-else statement }ร‹ # After the inner-most map: check if both values are the same ~ # Check if either of the two checks is truthy y # Push the pair yet again โ‚ฌg # Get the length of each part โ‰  # Check for each length that it's NOT 1 P # Take the product to check whether it's truthy for both * # Check if both checks are truthy } # Close the inner map Z # Push the maximum (without popping the list) i # Pop, and if this is truthy: _ # Invert all booleans in the list 1ลก # Prepend an additional leading 1 ร # Only leave the string-parts at the truthy indices J # And join them together to a string รซ # Else: ยฏ # Push an empty list instead ] # Close the if-else statement and outer map หœ # Flatten to remove all empty lists รฉ # Sort the strings by length Iยช # Append the input in case it's empty ะฝ # Pop and leave the first/shortest one # (which is output implicitly as result) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 196 bytes ``` import re def f(s,*r): for l in range(-len(s),-2): for i in range(len(s)-~l): if p:=re.match("(\w[\w -]*\w)(-? ?\\1)+$",x:=s[i:i-l]):s=re.sub(x,"{%s}"%len(r),s);r+=p[1], return s.format(*r) ``` [Try it online!](https://tio.run/##bVJtb5swEP6eX3GKVtW0uFK3LxNT1B8S8uEIBlsxtmUbpajq/npmk43kWLkXH89zHHcHborSmh8/nb9c1OCsj@DFphUddCyUT76oNtBZDxqUAY@mF4xrYVgoSv49kzOrbuyV5L/1TILqwFU7L14GjEfJtqw@7@sz8MNTfS4Yf4O3un4tnr9ty/dqF/aqUlwfiirkR8LYsPdy@/EQPrcPua4vylD88s87t389lJvUaRy9gfCSekj1WWr34rwykXXsUaLTVtt@eiyKzYKq1mqMnoJHZQwOdrCGwI21SU801Y4hGwFNb72dHYGlyEKgs8TTIoTRwrez9vR9aJL2tqelJ2wxW6NRZiPkoELI6pyi@DSIJLO/zkZoTFczO7qFBA6ztsr02f6jb9KmsmuAjpmGgezolBL5X6MbVLxVnHhaLo6RJ4vrrjS2E/TY46pXk4Qf7dEiJNLPbvWBLLgxQpQCGuvyf/0vDNJaGtwnt2pJzmGLdwedCb2Ak1dBGgRysz5n8uY8DngX3dySst40fLHqBQaKY7xKAi9/AA "Python 3.8 (pre-release) โ€“ Try It Online") ## Credits * Port of [my Java answer](https://codegolf.stackexchange.com/a/247200/16236). * -8 bytes, thanks to [Blue](https://codegolf.stackexchange.com/users/42855/blue) * -5 bytes, thanks to [Ivo Merchiers](https://codegolf.stackexchange.com/users/86502/ivo-merchiers) * -25 bytes, thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) * -2 bytes, thanks to [Jakque](https://codegolf.stackexchange.com/users/103772/jakque) [Answer] # [Java (JDK)](http://jdk.java.net/), 308 bytes ``` s->{var r=new java.util.Stack();for(int l=s.length(),i;l>1;l--)for(i=0;i<=s.length()-l;){var x=s.substring(i,l+i++);var p=java.util.regex.Pattern.compile("(\\w[\\w -]*\\w)(-? ?\\1)+").matcher(x);s=p.matches()&&r.add(p.group(1))?s.replace(x,"%"+r.size()+"$S"):s;}return"".format(s.toLowerCase(),r.toArray());} ``` [Try it online!](https://tio.run/##jVPBbuM2EL3zKwZCs6DWlrC5UusEiwV62hYFckxyoCVaYkyRXJKKrS78FT30UqA/0S/qF/QP0iEtO7Z3gd2Q8zjDN3xDapwn/syLp2b9IntrXIAnjMshSFWuBl0HaXT5tiJfkXc111q4itSKew@/cKnhCwGww1LJGnzgAZdnIxvokaN3wUnd3j8Cd63PUyrAz1OF93t2vl9uYLV48cXNl2fuwC202JzWDbxe07xaGUelDqAWvlRCt6Gj@VxW6ua6UkWRJ3rxrpLvT/hCVXkS3eKmH5Y@laNyrmZyNsurSNnFay0nWrEtf@MhCKfL2vRWKkEz@vCwuUeD4vEtLjktbuH24eE6n2V52fNQd8LRbV75hZ1CT/M3b1zJm4basnVmsPQ6z289VrCK14Ju59lVNnOll78Lijo/3WU589XOiTA4nWUlvgelqC@D@WQ2wn3kHhPnDuMPzvGR5nm1e6nSVw1uBBrf4mEB8etNvaJ3ow@iL6XODw0A2HT4JkDhjvtfxTbQEw4gqgThAwr5UiP9SWqsW3qrZKAZy/LqLFdqO8TkeOb@3eM5KbZW1EE0B/76gnfCDyqeXpXcWjXSpHZRoTbOoQpmHeRK8XngytP98ZP06blmCKXFRocVza48XHmGdqWz@VHrFrJ///ojAwbZf3//@Q8yqfIcLiR35IA7snvpuFVGmXZkyWtHsjQG55pFILUZfDQWgejWOJOAJSSdiIN1gmw6vj4OliKihGvSbNnebQn2EGdrWsPSSkbe8GhLxbto7BCQXnofp7WS9ZND@rEXOBLuL8qOAeH4t0zAEpIlhn2aDf6LRGPTVvQT/ToalLvcYF/tEIXXhggsAqk7XkzG0Egni0YWZ2jYwSFhCAVaiDeZVhRsRmh5y9nk4b00jqI2teGAhEvAlvvN/RZ@cAPxZxo6AUtjsdlH13fGnDunyY08Jke34ScL@xHV74qRjjsBayd9pzmcBZdrIl/B8Z6feK9wTGHflLtQOB6J3YLULkj9gpbwsB8swv8 "Java (JDK) โ€“ Try It Online") ## Explanation This algorithm takes all substrings that exist, from longest, to smallest and checks if that one is a repetition with spaces or dashes. If it is, it takes the repeated value and stores it in a list (the `Stack` in the code) and replaces that long substring to something with special characters (`%1$S` with 1 being any number, actually) so that it's not matched anymore later on. After all repetitions are found, the string, taken as lowercase, is actually a formattable that can be properly formatted to wrap up the replacements with `String.format`. ## Credits * -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). * -3 bytes by backporting [Jakque](https://codegolf.stackexchange.com/users/103772/jakque)'s regex suggestion from my Python answer. [Answer] # Python3, 283 bytes: ``` R,L=range,len def f(s): m=[] for x in R(L(s)): for y in R(x+2,L(s)): S=s;T=s[x:y];K=0;X=x while S[(F:=(X+(X<L(S)and S[X]in[' ','-']))):][:L(T)]==T:K+=1;X=F+L(T) if K>1:m+=[[s[:x],T,len(T*K),s[X:]]] return s if[]==m else f((M:=max(m,key=lambda x:x[2]))[0])+M[1]+f(M[-1]) ``` [Try it online!](https://tio.run/##bZPNjpswEIDveYq5YQpIm@2lInWPe0ly2XCIZPngBANWwEY20cLTp2O2JWta5gfzzWjsGaCfhsbo7z96@3i8pwdqha5l2kq9KWUFFXFxvoGOMr6BylgYQWl4JwfkPjCz6ZONyWu6cDhRtyuoY2M@8d2evuzOdPT8o1GthBMjbzkl54Scfx7IKRa6RHbmSrMIojTKIh5jIc7yAyliTmmR7xO6xSJviSe@kqpg/2ubdwllzLF85Gnhz02Kb/s4deycc46HtnK4Ww0O0xnW6UC2TmJf5JjTToykS29yoq3oLqWAMR/ZK@7MXnicHNmWJxU5smzL40dvlR5IRaJG9K1pTT1FcbxZqCpNKwYbwosxqLeAXc3deQugro01swtwI70E6KMRt0WCSCttOWsd7ic0am3qsPQkSuHt0orGWxDslHNe@16FfOokyuw/ewvCAq/L7MIpIOxmLZWuvf0TfkqJZdcgbBObAe/CLhuR/bFwgiorVRb4sNxwHzK0YX2qVpQT1KIWq7NqlOxqrkYABu3sVi/IQH8fYGgkXEzvf42/S9cYEy6@JpdqSfZL/Bqft7AnYSXcrHKNFhA8rO9z8Oms6MSX1dMtKetJw39GvWAIeYeVepTBC0YevwE) A no-import solution in Python. ]
[Question] [ Write a "palipolyquine": a program that is a [quine](https://en.wikipedia.org/wiki/Quine_(computing)), a [polyglot](https://en.wikipedia.org/wiki/Polyglot_(computing)), and a [palindrome](https://en.wikipedia.org/wiki/Palindrome). Rules: * The number of polyglot languages is more preferable than code size. * The shortest answer (in bytes) wins, in case of a tie. * Polyglot and Quine rules see here: [Write a Polyquine](https://codegolf.stackexchange.com/q/37464/15660). My example (I have a repository [Freaky-Sources](https://github.com/KvanTTT/Freaky-Sources) with tests): ## C#/Java (1747 bytes): ``` /**///\u000A\u002F\u002A using System;//\u002A\u002F class Program{public static void//\u000A\u002F\u002A Main//\u002A\u002Fmain (String[]z){String s="`**?`@#_^using System;?_#^class Program{public static void?@#_^Main?_#main^(String[]z){String s=!$!,t=s;int i;int[]a=new int[]{33,94,38,64,35,95,96,63,36};String[]b=new String[]{!&!!,!&n!,!&&!,!&@!,!&#!,!&_!,!`!,!?!,s};for(i=0;i<9;i++)t=t.?@#_^Replace?_#replace^(!!+(char)a[i],b[i]);t+='*';for(i=872;i>=0;i--)t=t+t?@#_^[i];Console.Write?_#.charAt(i);System.out.printf^(t);}}/",t=s;int i;int[]a=new int[]{33,94,38,64,35,95,96,63,36};String[]b=new String[]{"\"","\n","\\","\\u000A","\\u002F","\\u002A","/","//",s};for(i=0;i<9;i++)t=t.//\u000A\u002F\u002A Replace//\u002A\u002Freplace (""+(char)a[i],b[i]);t+='*';for(i=872;i>=0;i--)t=t+t//\u000A\u002F\u002A [i];Console.Write//\u002A\u002F.charAt(i);System.out.printf (t);}}/*/}};)t( ftnirp.tuo.metsyS;)i(tArahc.F200u\A200u\//etirW.elosnoC;]i[ A200u\F200u\A000u\//t+t=t)--i;0=>i;278=i(rof;'*'=+t;)]i[b,]i[a)rahc(+""( ecalperF200u\A200u\//ecalpeR A200u\F200u\A000u\//.t=t)++i;9<i;0=i(rof;}s,"//","/","A200u\\","F200u\\","A000u\\","\\","n\",""\"{][gnirtS wen=b][gnirtS;}63,36,69,59,53,46,83,49,33{][tni wen=a][tni;i tni;s=t,"/}};)t(^ftnirp.tuo.metsyS;)i(tArahc.#_?etirW.elosnoC;]i[^_#@?t+t=t)--i;0=>i;278=i(rof;'*'=+t;)]i[b,]i[a)rahc(+!!(^ecalper#_?ecalpeR^_#@?.t=t)++i;9<i;0=i(rof;}s,!?!,!`!,!_&!,!#&!,!@&!,!&&!,!n&!,!!&!{][gnirtS wen=b][gnirtS;}63,36,69,59,53,46,83,49,33{][tni wen=a][tni;i tni;s=t,!$!=s gnirtS{)z][gnirtS(^niam#_?niaM^_#@?diov citats cilbup{margorP ssalc^#_?;metsyS gnisu^_#@`?**`"=s gnirtS{)z][gnirtS( niamF200u\A200u\//niaM A200u\F200u\A000u\//diov citats cilbup{margorP ssalc F200u\A200u\//;metsyS gnisu A200u\F200u\A000u\///**/ ``` Compilation available on ideone.com: [C#](https://ideone.com/NbfYj6), [Java](https://ideone.com/kFGoxI). [Answer] ## [CJam](https://sourceforge.net/p/cjam)/[GolfScript](http://www.golfscript.com/golfscript/), 2 languages, 50 bytes ``` {`"0$~e#"+0$-1%"":n}0$~e##e~$0}n:""%1-$0+"#e~$0"`{ ``` [Try it CJam!](https://tio.run/nexus/cjam#@1@doGSgUpeqrKRtoKJrqKqkZJVXCxZQTq1TMajNs1JSUjXUVTHQVgILKCVU//8PAA "CJam โ€“ TIO Nexus") [Try it in GolfScript!](https://tio.run/nexus/golfscript#@1@doGSgUpeqrKRtoKJrqKqkZJVXCxZQTq1TMajNs1JSUjXUVTHQVgILKCVU//8PAA "GolfScript โ€“ TIO Nexus") Huh, this went unanswered surprisingly long. ### Explanation It's probably easiest to explain this by showing how I turned the basic quine in each language into a palindromic polyglot quine. So the basic quines in both languages are: ``` {".~"}.~ ``` ``` {"_~"}_~ ``` In GolfScript and CJam, respectively. These are quite similar thanks to the fact that CJam was originally inspired by GolfScript (but has since deviated quite a lot). The first difference we notice is that one uses `.` for duplicating the top of the stack and the other uses `_`. A common trick to avoid this problem is to use `0$`, since both languages have the "copy-nth-item-on-stack" operator `$`. So we get `{"0$~"}0$~`, although that still needs a trailing linefeed in GolfScript. But let's worry about that at the end. First, we need to make it a palindrome. The obvious solution to this is to append a comment and put the source code there in reverse. This is quite simple, because CJam uses `e#` for comments, and in GolfScript `e` does nothing at all, and `#` is a comment. So if we append `e#...` that works for both languages. Here is what we've got: ``` {"0$~"}0$~e##e~$0}"~$0"{ ``` Of course, that doesn't actually *print* the part from `e#` onward. We can reconstruct this quite easily from the source code itself. Both languages can turn the initial block into a string with ``` and append the `"0$~"` part with `+`, so that we get the entire unmirrored source code in a single string. To append a mirrored copy, all we need to do is duplicate the string with `0$` again and then reverse it with `-1%`, which also works in both languages. So now we've got this: ``` {`"0$~e#"+0$-1%}0$~e##e~$0}%1-$0+"#e~$0"`{ ``` This is a valid palindromic quine in CJam, and it also works in GolfScript but still prints that pesky trailing linefeed. The usual way to prevent this is to assign an empty string to `n`, because what GolfScript really does is print the contents of `n` at the end. So what we need is `"":n`. So what about CJam? Thankfully, this does nothing at all. `""` is also an empty string (or empty list, they're the same thing in CJam), and `:` maps the operator `n` (print with linefeed) over the list. But since the list is empty, mapping an operator over it does nothing at all. Hence, we can get rid of the linefeed, without messing with CJam, and end up with the final solution: ``` {`"0$~e#"+0$-1%"":n}0$~e##e~$0}n:""%1-$0+"#e~$0"`{ ``` [Answer] # [Perl 5](https://www.perl.org/)/[Ruby](https://www.ruby-lang.org/)/[PHP](https://php.net/)/JavaScript (Browser), 4 languages, 513 bytes ``` $_='$z=0?"$&".next: eval("printf=console.log;atob`JCc`");printf("%s_=%s%s%s;eval(%s_);//#//;)_%s(lave;%s%s%s=_%s",$d=$z[0]||h^L,$q=$z[1]||h^O,$_,$q,$d,$d,$q,"0"?$_.split("").reverse().join(""):~~reverse,$q,$d)';eval($_);//#//;)_$(lave;')d$,q$,esrever~~:)""(nioj.)(esrever.)""(tilps._$?"0",q$,d$,d$,q$,_$,O^h||]1[z$=q$,L^h||]0[z$=d$,"s%_=s%s%s%;eval(s%_);//#//;)_s%(lave;s%s%s%=_s%"(ftnirp;)"`cCJ`bota;gol.elosnoc=ftnirp"(lave :txen."&$"?0=z$'=_$ ``` [Try the Perl online!](https://tio.run/##TZDdisIwEIVfpcxONYES68XeNIReeCeCDyCadjVqJTS1CSIivrqbH2GXDEPmmzPhTAY16u/3G6WY4kOUNeAEWK/urspKxtrnU91aTWAYu94dxd701mjFtDnx1pmfZrnYN0B5ahPIrRS5DYfHOV9TPpt9zWacytwS3d4UTwLhayjwIPCxKbd1zNV5tyrwGtA8onlA6wKlp14b41pACTVKZgfdOQJA2ahuarSKUHYxXR9QlYVFautG3yMoafV6fVTpKcqnySL@c4jJ4JTTAxZXLJSNM69XFXr@NjpbwwQhqygA6TtzYZR8VCwg1@nBMom19xheOMTwF4nFeneutvPNA@uYhaergMqIQhZeCzaXIv5Qngz6@s@hzZPFJBC@BnJ0fTcOnEKzXyybH@NafjKaKW1sb/YitSHOPZ8tY2VWubvqWVikLsUDp0Li@/0L "Perl 5 โ€“ Try It Online") [Try it online!](https://tio.run/##TZDdisIwEIVfRWanmkCJ9TYh9MI7EXwA0Vg1aqU02mTFLcVXd/Mj7JJhyHxzJpxJ973/eb9RyQn2sigBx8Ba/XR8VDBWDYN@VA2BW1e37iQPprWm0awxZ1E5s98t5ocdUJHaBDKrZGbDEXHO11RMp1/TqaAqs6SpHlokgfQ15HiU2K@LTRkzv2yXOd4DmkU0C2iVo/LUa2PccyigRMXsrakdAaCs0w/dWU0ou5q6DYiPwiKldZ3vEVSUv14fVXqKikmyiP8cYjI4EfSI@R1zbePM68VDz986Z0sYI4w4BSBtba6Mko@KBeTq5maZwtJ7DC8cY/iLwny1vfDNbN1jGbP0dBlQEVHI0mvBZkrGH8qSQV//ObRZspgE0tdATq6tu5ugsDvMF7u9cZU4m4bpxtjWHGRqQ5wbhoqxYsTdU7csLFIWsseJVPh@/wI "Ruby โ€“ Try It Online") [Try the PHP online!](https://tio.run/##TZDdisIwEIVfpcxONYES622zIRfeieADiKZdjVopTW2CiIiv7uZH2CXDkPnmTDiT4Ty8v@XgMyoxxYcoJeAEWK/vrspKxprnU9@ajsAwtr07ir3prek068yJN8781MvFvgbKU5tAbpXIbTg8zvma8tnsazbjVOWWdM1N8yQQvoYCDwIfm3IrY67Ou1WB14DmEc0DWheoPPXaGNcCSpComB261hEAykZ906PVhLKLafuAqiwsIq0bfY@gotXr9VGlpyifJov4zyEmg1NOD1hcsdA2zrxeVej52@ishAlCVlEA0rfmwij5qFhAru0GyxRK7zG8cIjhLwqL9e5cbeebB8qYhaergMqIQhZeCzZXIv5Qngz6@s@hzZPFJBC@BnJ0fTsOnEK9XyzrH@MafjId052xvdmL1IY493w2jJVZ5e66Z2ERWYoHToXC9/sX "PHP โ€“ Try It Online") [Validate it online!](https://tio.run/##7ZXNauMwEMfvfQqjHdcWOIpz6MVC@NBbKfQBuq3iOGrt4rUcSZvtBpNXz@oj0NLS7gsIi0HznxkxY35Im0Z3p5NoO5ksxiQDzrKfWQYHVtYILhEZxaupkpKQZp7FvhlyNKl@NE@slaOWgyCDfKaNkZv1zXW7RpiGcI5SzVmq3Ud9nfUxXS5/LJcU81TnQ7MXNCQw66MCtgwO9@VD7W3VPd4WsHPSyksrJ90VwK1qc/3aFahENXCip6E3OUKYKLEXSosckxfZj06qEjdIrY2ysRw4ro7Hc1Y4ClM3cugS3jUJoUcfxFsodlAI7SuPx8qF7U4ZXaNLQEmFEcrHXr4QnJ@ziJNMP0yacKhtp@6ErV92w6G4e@yqh9X9AWpvmVVvnVR6yVlmc5FOOfP/KQ09Wv@tSZ2GLkMCsz7Kn8zYq4litG6vb9YbaRr6LAciBqlH2bIQRr5unhtCyqQyr2IkbpC6ZAdwIzMO2fxre0UvHBzBRkQiIh8RsXO8x2TqpmShIiWRkq8ukkmoIVmIiEhE5CtE1O/N34hIROS7WyS@M5GQz4S4x2V218eZkwhLhOX/sMx/2mTR0ovT6R8 "Bash โ€“ Try It Online") ``` $_='$z=0?"$&".next: eval("printf=console.log;atob`JCc`");printf("%s_=%s%s%s;eval(%s_);//#//;)_%s(lave;%s%s%s=_%s",$d=$z[0]||h^L,$q=$z[1]||h^O,$_,$q,$d,$d,$q,"0"?$_.split("").reverse().join(""):~~reverse,$q,$d)';eval($_);//#//;)_$(lave;')d$,q$,esrever~~:)""(nioj.)(esrever.)""(tilps._$?"0",q$,d$,d$,q$,_$,O^h||]1[z$=q$,L^h||]0[z$=d$,"s%_=s%s%s%;eval(s%_);//#//;)_s%(lave;s%s%s%=_s%"(ftnirp;)"`cCJ`bota;gol.elosnoc=ftnirp"(lave :txen."&$"?0=z$'=_$ ``` ]
[Question] [ In crossword terminology, the *grid* is the region into which the crossword answers are inserted, consisting of white and black squares. The crossword answers, called *entries*, are inserted into contiguous sequences of white squares in a row or column, separated by black squares. [![Example of a crossword grid](https://i.stack.imgur.com/dCsJi.png)](https://i.stack.imgur.com/dCsJi.png) For straight (American) crosswords, the grids usually follow a specific set of rules: * They should have 180 degree rotational symmetry (if there is a black square in the \$x\$th row and \$y\$th column, there should be a black square in the \$x\$th-to-last row and \$y\$th-to-last column). * All entries must be at least 3 squares long. * All white squares must be joined in a single region. * No row/column can be completely filled with black squares. * Every white cell/square must be the intersection of both a horizontal and a vertical entry. Some examples of invalid and valid crossword grids: [![Valid and invalid crossword grids](https://i.stack.imgur.com/tpPif.png)](https://i.stack.imgur.com/tpPif.png) **Your challenge:** given a grid consisting of two unique values representing black and white squares, determine if it's a valid crossword grid. Assume that it's a square grid with \$n\$ rows and columns (so there are \$n^2\$ white/black cells), where \$n \geq 3\$. (You can take input in any reasonable format -- e.g. a 2D array.) For example, if \$n=3\$ there is only one valid grid (I'm using `.` for white cells and `#` for black cells): ``` ... ... ... ``` If \$n=4\$, there are 3 valid grids: ``` .... #... ...# .... .... .... .... .... .... .... ...# #... ``` If \$n=5\$, there are 12 valid grids: ``` ..... #.... ##... #.... ##... ##... ..... ..... ..... #.... #.... ##... ..... ..... ..... ..... ..... ..... ..... ..... ..... ....# ....# ...## ..... ....# ...## ....# ...## ...## ....# ...## ....# ...## ...## #...# ..... ..... ....# ....# ...## ..... ..... ..... ..... ..... ..... ..... ..... ..... #.... #.... ##... ..... #.... ##... #.... ##... ##... #...# ``` Examples: | Input | Output | Explanation | | --- | --- | --- | | `.........` | True | Valid grid | | `#..............#` | True | Valid grid | | `...#........#...` | True | Valid grid | | `.........................` | True | Valid grid | | `##...#.............#...##` | True | Valid grid | | `.................................................` | True | Valid grid | | `........................#........................` | True | Valid grid | | `....###.....##......##.....##......##.....###....` | True | Valid grid | | `................................................................` | True | Valid grid | | `##....####....##...........##......##...........##....####....##` | True | Valid grid | | `...##.......#...........##.....##.....##...........#.......##...` | True | Valid grid | | `#...............` | False | No 180 degree symmetry | | `#...#......#...#` | False | 2-letter entries | | `#..##..##..##..#` | False | 2-letter entries, filled-in columns | | `#........................` | False | No 180 degree symmetry | | `.......#...###...#.......` | False | 1-letter and 1-letter entries | | `######....#....#....#....` | False | No 180 degree symmetry, filled-in column & row | | `######...##...##...######` | False | Filled-in columns & rows | | `...#......#......#......#......#......#......#...` | False | White squares not contiguous, filled-in column | | `.................###....#....###.................` | False | 1-letter entries | | `...#......#...............##.....................` | False | No 180-degree symmetry | | `....#.......#.......#........######........#.......#.......#....` | False | White squares not contiguous | | `..#.........#.......#......##......#.......#.......#.........#..` | False | 1-letter and 2-letter entries | | `.#......#..............................................#......#.` | False | 1-letter entries, white squares not contiguous | | `...........................##......#............................` | False | No 180-degree symmetry | | `####............................................................` | False | No 180-degree symmetry | | `#......##......##......##......##......##......##......##......#` | False | Filled-in columns | Standard loopholes are forbidden. Shortest code wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~40 35~~ 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -5 thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)! ``` ;Zยตล’gยงโ€™:2;ยงศฆ ล’แนชแธขแบกยงแปŠแบธส‹ฦ‡@ฦฌiฦŠศงร‡ศงUโผแนšฦŠ ``` A monadic Link that accepts a list of lists of `1`s (white) and `0`s (black) that yields `1` if valid or `0` if not. **[Try it online!](https://tio.run/##y0rNyan8/9866tDWo5PSDy1/1DDTysj60PITy7iOTnq4c9XDHYse7lp4aPnD3V0Pd@041X2s3eHYmsxjXSeWH24/sTz0UeOehztnHev6/3D3Fv@HO5oOrTnc/v@/srIeECgrcyEYehDABeaiM8CKuDB0AQA "Jelly โ€“ Try It Online")** Or see the [test-suite](https://tio.run/##pVK9bsIwEN7vNb4uLBk6lqUPgMTUhb2qWrF1YqMdiBQ2tnYrQy1VjEUKf4sjoqhvYV7EQFOcc7BNpJ7ku5zvvrvPl3u67/cHWrd7cr6dPEixG77dXLelKD5pO1GLL5VO1fJDCrVK1DL9GefxbT57zJNCZHEh7nYva7V4zxOtVt9y/tzJRnJz1VXpq5xlcUtrRJaAjsp4h@O8KIUinxDAYQYL@DHeWr4AggigjP@ZyOci/JKmJMs6wMlynnZL7lT5xBMc6Bp9K@33knBGqYyYQ7g0YpiJoHqX4WirKsLVUdjGNDTn47d6Ak7GcK8BEFiK@uRYP9bGmUa8VS0DCABPX@RjfEEMKrSlaFKbAOB/a@5e6caWYP847AE "Jelly โ€“ Try It Online"). ### How? ``` ;Zยตล’gยงโ€™:2;ยงศฆ - Link 1 (check entry lengths & presence): list of lists of 1/0, Grid ;Z - concatenate the columns ยต - start a new monadic chain - f(rows + columns) ล’g - group runs of equal elements of each row/column ยง - sums of each run โ€™ - decrement (i.e... all black: -1, 1:0, 2:1, 3:2, 4:3, 5: 4, ...) :2 - integer divide by two -1 0 0 1, 1, 2, ... ยง - {rows + columns} sums ; - concatenate ศฆ - any and all? -> 0 if either: an entry of length 1 or 2 exists, or any row or column has no entry else 1 ล’แนชแธขแบกยงแปŠแบธส‹ฦ‡@ฦฌiฦŠศงร‡ศงUโผแนšฦŠ - Main Link: list of lists of 1/0, Grid ล’แนช - multidimensional truthy indices -> "WhiteCoordinates) ฦŠ - last three links as a monad - f(WhiteCoordinates): แธข - head (first coordinate -> initial "Current") ฦฌ - collect up while distinct, applying: @ - with swapped arguments - i.e. f(WhiteCoordinates, Current): ฦ‡ - filter keep those (of WhiteCoordinates) for which: ส‹ - last four links as a dyad - i.e. f(WhiteCoordinates, Current): แบก - absolute difference (vectorises) ยง - sum each แปŠ - insignificant? (effectively "in (0,1)?") แบธ - any? - i.e. any are neighbours/same? i - index of {WhiteCoordinates} in that (or 0) -> 1 if white cells are fully connected else 0 ร‡ - call link 1 ศง - logical AND ฦŠ - last three links as a monad - f(Grid): U - {Grid} reverse each แนš - {Grid} reverse โผ - equal? -> 1 if 180-degree symmetry else 0 ศง - logical AND ``` --- Also at 33 as a lone Link (although it performs redundant checks): ``` ,Zยตล’gยงโ€™:2;UโผแนšฦŠ;ล’แนชแธขแบกยงแปŠแบธส‹ฦ‡@ฦฌiฦŠ$;ยง)ศฆ ``` [Answer] # Python3, 562 bytes: ``` E=enumerate def g(b,B): q=[(x,y)for x,y in B if b[x][y]=='.'] Q=[q.pop(0)];S=[Q[0]] for x,y in Q: for X,Y in[(1,0),(-1,0),(0,-1),(0,1)]: u=(x+X,y+Y) if u in B and u not in S and'.'==b[x+X][y+Y]:Q+=[u];S+=[u] return not{*q}-{*S} F=lambda x,l,c=0,k=0:k if not x else F(x[1:],l,(T:=c+(x[0]==l))*(x[0]==l),max(k,T)) def f(n,b): B=[(x,y)for x,r in E(b)for y,_ in E(r)] D=[(x,y)for x,y in B if'#'==b[x][y]] return all((n-x-1,n-y-1)in D for x,y in D)and g(b,B)and all(F(i,'.')>2and F(i,'#')<n for i in b)and all(F(i,'.')>2and F(i,'#')<n for i in zip(*b)) ``` [Try it online!](https://tio.run/##pVZbb9owFH5efoVXS4sNDiKdJlV03kPV8jgJgbZWWdQmYGjU4FAnWWFtfzs7ThRIINxUS2Af51y@8/n4Mlskj5H8ejFTy@UNFzKdCuUlwhiJMZoQn13RjoGeuUPmbEHHkULQo0CiKxSMke/MXWfhcm62TNdAPe48t2bRjLSpe9nnTs9puzBdsuqBs0y@ZXcgO8RmbcqIlXdtZtlZZ1NXK6KUk3nzli2ad1SLEDHNY3tyBEMZJVrsaxEQcA54mreAqHnndnpN7qQAI@sMpESSKqlNXhvP79Zro/9udHnoTf2RB@hCNuRt9sTbnScdRnueIxHGAnXJ3LE7LmiQQYcPmyC2IeOQ0sZqyKbenDyxAaUZb2Mima95u6rwpjTYG@Jn4oLd56KigO66nmAT50lpktc5eGFIiLTmwJq0FkAZaF@XWb6mmp989fRIG3RJwIAj@uNcz2QSNul3mdkF2so/QfdfMCMNn9KlTjeJ7v3IUyMSQ86fJA9kQkIhQWw0Wt/oZUE9c2In6ARN6a78KE9OBCx4rs4kcGEMbvoDxNHZ2Znx0Craw9tApeLtlxcGkJkKRsYDblUarlHR06vv9V6OU9kLAq@tAUTXg6qpt99sdf5wGdDaL96H69h2gg98og@McwtckLFDxCfi@EBqeSyMi76cXRVWWVjr7ygWXMNQNduq17LK4SpuFQX0M0L2RRuNxEQJgeLFdCoStcj0cflX6J9boUgSoZCQiQpEzNA4CEMxsmCXDaMwncp4O9jRUSulWC7RwtAuwusTw97AotdixWv1b3/g7STQF6Sil5LD8p9uhcPuZva5ZVze8Ud2hcvfj0EC2J5TT4k4uyKGkUyCSRqlNXTX1HSFAox3rsI2f1u4tkp574JatQu6Wcm4hLMEr1btGE50FNza4QbjPd6LUW11nW@zgw8cWnvPOLyTd4ZeDqS32/cxkA4tEsYYf@xQPOC//jQ8ut@51wx9eRvG6pqHvQG0kp@RFAzp@70Vz8IgIeYfaVL9aPCYD@8hjoLiw5tJYTaOhUrgOdVYPTE8eItZtksp4hyJv14IzynDmCn95jATEScxmmmz0WeTLv8D) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~186~~ 183 bytes ``` \. - s`^(?!(.)+.?(?<-1>\1)+$(?(1)^)).+ ms`.*^#+$.*|.*(?<!-)--?(?!-).* O$`. $.%` ms`.*^#+$.*|.*(?<!-)--?(?!-).* 1`- @ +m`^((.)*)(@|-)(.*ยถ(?<-2>.)*(?(2)$))?(?!\3)[@-] $1@$4@ ^[ยถ#@]+$ ``` [Try it online!](https://tio.run/##hY0xDsIwDEV336KKkeJEsZTCiJrcgAO0jcLAwAADZey5eoBeLDhQxIgH/6fvb/3H5Xm9n0sZGBxMOenQaCbLQYej893gyaIO2lMiYgtwmzKbpCyymdlIqHHknKRF2QCcMDMg7/LfpM8OItibdEqjIR1nR5rNutTqthNPiltCovo07KmPbgT0EQ8RUr8uKo4WS2FmpWQBV/pCHXj7YsKm6nfash@o9AI "Retina 0.8.2 โ€“ Try It Online") Takes input as a square array and outputs `1` for valid, `0` for invalid. Explanation: ``` \. - ``` Change `.`s to `-`s are they're easier to match. ``` s`^(?!(.)+.?(?<-1>\1)+$(?(1)^)).+ ``` Delete everything if it isn't rotationally symmetric. ``` ms`.*^#+$.*|.*(?<!-)--?(?!-).* ``` Delete everything if there is a row of `#`s or if there are one or two `-`s on their own. ``` O$`. $.%` ``` Transpose the array. ``` ms`.*^#+$.*|.*(?<!-)--?(?!-).* ``` Check the transpose for a row of `#`s or one or two `-`s on their own. ``` 1`- @ ``` Change one `-` to a `@`. ``` +m`^((.)*)(@|-)(.*ยถ(?<-2>.)*(?(2)$))?(?!\3)[@-] $1@$4@ ``` Flood fill `-`s with `@`s. Note that I use `(?(2)$)` although I used `(?(1)^)` above because this is a multiline match and so the final character could be at the beginning of a line. ``` ^[ยถ#@]+$ ``` Check that all of the `-`s were filled. [Answer] # JavaScript (ES11), 176 bytes *Saved 1 byte thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)* Expects a binary matrix, with `1` for white cells and `0` for black cells. Returns a Boolean value. ``` f=(m,i)=>m<(h=z=>m=m.map((r,y)=>r.map((v,x)=>z?/^(0*222+)+0*$/.test(r.join``)?m[x][m.length-1-y]:z:v&[-1,0,1,2].some(d=>m[y+d%2]?.[x+~-d%2]==i)?i=2:v)))()?f(m,i):h``+""==h(h``) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVTLjpswFFWlrrzqJ1h42tiBeBKkSlWmHlZTqduO1A1DBUrMo-KRAsnkofRHZpPFzL6_0_maGggJEEhnroTvw_f43Htt8fAYRlO-2z3NU3vw6e8fm-FA8Qi7Dj5jl62FZgENrBnGsbIS4bhwFspSOGvt8gce9lVVlYk87F9c0pQnKY7pz8gLTZNogb409ID6PHRSdzAarIzxerz4oA9GylAZKapBkyjgeCpo9JU8fa8aGtWX8u9BZjLmEc1j6nhBCMFEs_PKxq5pypLEmIuFRYq6n9-8m0RhEvmc-pGDJf275XtTQyJXIOa_5l7MsWQnEqExt6ZfPJ_frsIJHhKaRrdp7IUOJjSZ-V6KpbtQpNlRfGNNXJxAdg03AELPzmwGJYnADaxx3YX613BR8sGYp_M4vIJbgfJ5Cu8hg8l-ArDfh0P6UYFBHgysVHB8487NcoZNurnY3G-3pgJ7To-QfM45v04pTYzcn2S-nCkGe1RkiQZhrRwxpCy43Q9m9_z2gZYCEKJtghBobCCQLQcvw7YF2qWgqZ-ICppOTOdZXRvtnZQItO-0bLjLRWc5XlxkcQ5Cpa7WWaesOsd8UE1oQTfKr6XlQdC8QAoqd5CbWQBVvxPIEVuhQLXLBAgdqq4vx53qkknl5bxQnV5IjbPlFZ9yVKDdPTZHfnzghzY700CVqpGB0BlgaYGuiv8jB9S5d9usoFUAapvlKwQ0-32tLn5S_wA) ### How? The same helper function `h` is used to process two passes: 1. We flood-fill the matrix, replacing `1`'s with `2`'s. We start at the first empty cell located on a border. If it doesn't exist, the grid is invalid anyway and will be identified as such during the next pass. 2. We rotate the matrix 3 times by 90ยฐ. We convert each resulting row to a string and make sure that it matches the following regular expression: ``` /^(0*222+)+0*$/ ``` i.e. the entire string is made of groups of three or more `2`'s (with at least one such group) and optional groups of `0`'s. Finally, we make sure that the 3rd rotation leads to the same matrix as the 1st one to validate the 180ยฐ rotational symmetry. ### Commented ``` f = ( // f is a recursive function taking: m, // m[] = input binary matrix i // i = flag used during flood-filling, ) => // initially undefined m < ( // compare m[] with its updated version h = z => // h is a helper function ... m = // ... which updates m[] m.map((r, y) => // for each row r[] at index y in m[]: r.map((v, x) => // for each value v at index x in r[]: z ? // if z is truthy: /^(0*222+)+0*$/ // if r[], once converted to a string, .test(r.join``) ? // matches this regular expression: m[x] // apply a 90ยฐ rotation [m.length - 1 - y] // : // else: z // force the final test to fail (*) : // else: v & // if v = 1 [-1, 0, 1, 2] // and there's some direction d .some(d => // such that: m[y + d % 2] // the neighbor cell ?.[x + ~-d % 2] // in that direction == i // is equal to i ) ? // then: i = 2 // set i and the cell to 2 : // else: v // leave this cell unchanged ) // end of inner map() ) // end of outer map() )() ? // if m[] was modified after flood-filling: f(m, i) // try to flood-fill some more : // else: h`` + "" == h(h``) // do the 1st and 3rd rotation match? ``` (\*) For the 1st and 2nd rotations, `z` is set to `['']`, which is coerced to an empty string. For the 3rd rotation, it is set to the result of the 2nd rotation. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 67 bytes ``` ๏ผฆฮธโŠžฯ…๏ผณยฟโผฯ…๏ผฅโฎŒฯ…โฎŒฮนยฟโฌคโบฯ…๏ผฅฮธโญ†ฮธยงฮปฮบโˆงโ„–ฮน.โฌคโชชฮน#รทโŠ–๏ผฌฮปยฒยซ๏ผฅฯ…โญ†ฮนโއโผฮป.ฯˆฮป๏ผชโŒ•ฮธ.โฐยค.ยฟโ€น๏ผฌ๏ผซ๏ผก๏ผฌฮฃฯ…โŽšยซโŽšยน ``` [Try it online!](https://tio.run/##TZDLbsIwEEXX8VdYZDOW0qjtlhXiIaWiUlT4gSgZwGLiJI6Niiq@PfVAUuqFfX3ndezyVNiyKWgYDo2V0CmZ@/4EPpGZab3bOavNEZSaC32QsO58QT1HP4sWvvCCtkfwKpGT1iosybkLIsjJ/2V3iXx0Gy8Ll5kKv4ESeeai4JgKlo03DnQiZ@mMrdBk15J@WDFbmXErfdEVwgpLizUahxVs0RzdCYj7vKs7xI@I8jDPAQ/0/6eHXnu0prDX6UU0Dbwmkrh6LqIPX7f7BjY6YHVT/JUjGx2w@B40P3WLfT8R5IhnpmaQ0dr5OvwRIy0JCwtchtQjE0ZPa6R9Y30Tt2FI0zSOwyZSVpPgJe5@MMV4xs/QmPsQrIaXC/0C "Charcoal โ€“ Try It Online") Link is to verbose version of code. Takes input as a square array of strings and outputs a Charcoal boolean, i.e. `-` for valid, nothing if not. Explanation: ``` ๏ผฆฮธโŠžฯ…๏ผณ ``` Input the square array. ``` ยฟโผฯ…๏ผฅโฎŒฯ…โฎŒฮน ``` Check that it's rotationally symmetric. ``` ยฟโฌคโบฯ…๏ผฅฮธโญ†ฮธยงฮปฮบโˆงโ„–ฮน.โฌคโชชฮน#รทโŠ–๏ผฌฮปยฒยซ ``` Concatenate the array with its transpose and check that each row contains a `.` but when split on `#`s does not contain runs of exactly `1` or `2` `.`s. ``` ๏ผฅฯ…โญ†ฮนโއโผฮป.ฯˆฮป ``` Write just the `#`s from the array to the canvas. ``` ๏ผชโŒ•ฮธ.โฐ ``` Jump to a position where there should be a `.`. ``` ยค. ``` Fill the canvas with `.`s starting from here. ``` ยฟโ€น๏ผฌ๏ผซ๏ผก๏ผฌฮฃฯ…โŽš ``` If this didn't fill all of the original `.`s then just clear the canvas. ``` ยซโŽšยน ``` If all of the `.`s were connected then clear the canvas and output `-`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 245 bytes ``` s=>new Set([...s].map(p=(c,i,a)=>c^1||[n=s.length**.5|0,(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0].at?b(v[0]):v)(s)[0]=v:s)(m(a[p=~i+~n]=[p],p-~n),p+1),+a.at(~i),a[i+~n]|a[i-~n]&a[i-~n*2],a[i-1]|a[i+1]&a[i+2]]).flat(1/0)).size<4*!s[-p]*/^1/m.test(s) ``` [Try it online!](https://tio.run/##pVZfb9s2EH@OPsUVBCLSlim7Wx/mVAk6YAX2MGRAC@xBU1dapmwGMiWQtNMsbr56epIsW0rtBN0ISCTvz@@OdzySN2IjbGpU6Ua6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j2o7hpb5JLnxYJmFF8xIPFUx@vm8Rs "JavaScript (Node.js) โ€“ Try It Online") Input a multi line string, 1 for white cells, 0 for black cells, line break (`\n`) separate each rows. Output true or false. --- # JavaScript, 263 bytes ``` a=>new Set(a.map((r,y)=>[r.map(e=(c,x)=>!c||[(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),e=a.at(~y).at(~x),a[y-1]?.[x]||a[y+1]?.[x]&&a[y+2]?.[x],r[x-1]||r[x+1]&&r[x+2]]),e,a.some(r=>r[y])]).flat(1/0)).size<3 ``` ``` f= a=>new Set(a.map((r,y)=>[r.map(e=(c,x)=>!c||[(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),e=a.at(~y).at(~x),a[y-1]?.[x]||a[y+1]?.[x]&&a[y+2]?.[x],r[x-1]||r[x+1]&&r[x+2]]),e,a.some(r=>r[y])]).flat(1/0)).size<3 const parse = (s, n = s.length ** .5) => [...Array(n)].map((_, i) => [...s.slice(i * n, (i + 1) * n)].map(v => v === '.')); const testcases = ` ......... True ##.....................## True #..............# True ...#........#... True ...#........#... True ......................... True ##...#.............#...## True ................................................. True ........................#........................ True ....###.....##......##.....##......##.....###.... True ................................................................ True ##....####....##...........##......##...........##....####....## True ...##.......#...........##.....##.....##...........#.......##... True #............... False #...#......#...# False #..##..##..##..# False #........................ False .......#...###...#....... False ######....#....#....#.... False ######...##...##...###### False ...#......#......#......#......#......#......#... False .................###....#....###................. False ...#......#...............##..................... False ....#.......#.......#........######........#.......#.......#.... False ..#.........#.......#......##......#.......#.......#.........#.. False .#......#..............................................#......#. False ...........................##......#............................ False ####............................................................ False #......##......##......##......##......##......##......##......# False `.trim().split('\n').map(r => [parse(r.split(' ')[0]), r.endsWith('True')]) testcases.forEach(([i, e]) => { console.log(f(i), e); }); ``` Input boolean matrix, output true or false. ``` a=>new Set( a.map((r,y)=>[ r.map(e=(c,x)=>!c||[ // for each cell, which is either empty or // generate an unique symbol for its connected area (m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]), // its 180 rotated position is non-empty e=a.at(~y).at(~x), // its ^ cell is non-empty or its v and vv cells are non-empty a[y-1]?.[x]||a[y+1]?.[x]&&a[y+2]?.[x], // its < cell is non-empty or its > and >> cells are non-empty r[x-1]||r[x+1]&&r[x+2] ]), // at least one non-empty cell this row e, // at least one non-empty cell this column a.some(r=>r[y]) ]).flat(1/0) ).size<3 // if every non-empty cell connected, they have same symbol (count as 1) // if all other condition holds, they will be all true (count as 1) ``` Transpose the matrix also costs 263 bytes, maybe someone can golf one of them a bit ``` m=>new Set([m,m.map((r,y)=>r.map((_,x)=>m[x][y]))].map(a=>a.map((r,y)=>[r.map(e=(c,x)=>!c||[a==m||(m=(s,t,v=a[t])=>v&&''+v!=s?(b=v=>v[0][1]?v:b(v[0]))(s)[0]=v:s)(m(a[p=x+[,y]]=[p],[x-1,y]),[x,y-1]),e=a.at(~y).at(~x),r[x-1]||r[x+1]&&r[x+2]]),e])).flat(1/0)).size<3 ``` [Answer] # [R](https://www.r-project.org), ~~196~~ ~~185~~ ~~184~~ ~~177~~ 176 bytes ``` \(x,`~`=t,`+`=sum,a=apply,e=~which(x,T),i=~~e[,1],`?`=any){while(+i<+(i=e[,a(e,2,\(y)?colSums((i-y)^2)<2)]))1 +i-+e?x-rev(x)?a(rbind(x,~x),1,\(y,z=rle(y))?!(z$v*z$l-1)%/%2&+y)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVRBTuswEN2w8ilCBpCHOEXpikWtHAJ2bb8SwAVLaShJCkkRuQibfgn2XOf_S3AF3AYSJ60LjBSP7XnP82Zi-flvsnyZWAP3dZ5N3NN_byOas6AMeMYCJ-DpfMpCHs5mUcEELx9u5OWNApwjk7wsxZB5Yxb4AQ_jAh9VNBLUkQOHSq5iIRWsz0a0QP_yNjqbT1NKpVvgnz4O-jhG9IgjXUf4uZuIe5qjH9LkQsZXKkOZI_NWXLbgiTq1QPT36eLg_nhxELkeHp4c9o-cAp8q3f_33kWuqrCitVaaZkk6i2TWTGzotQzIaqhX6tu6URnpmYwA6LSaC2DmGM8yBcAUWDMAqvin65mWsDPHj0VW5wB8eV1nO6W-aPBEB2xhd-S3YOtN0m3HagP0bwPRQLUDofXrCECtsT00EX1YmXZjfug229_KCZvCN3NoVHON3QY3F7su0wgjeqoOAmAH8WtGTIq_sZq165Z2FWw1Att6-Qsj3Xp_64l2udZTm1n2aBTbOBx647Fa2Mgs9driNMwSmdPc4tyyewoWJ7cPFrfSuySjkYivM_XkojKSVo-byNkEq3dvuaz8Bw) A function taking a square matrix of logical values and returning a single logical value. This was inspired by and works more or less the same as [@JonathanAllanโ€™s Jelly answer](https://codegolf.stackexchange.com/a/266007/42248) so be sure to upvote that one too! Thanks to [@pajonk](https://codegolf.stackexchange.com/users/55372/pajonk) for saving 9 bytes! [Answer] # [J](https://www.jsoftware.com), 95 93 92 bytes ``` (2<*#])@((#;._2"1@,.&0,&,0=1&#.)@,|:)*/@,(-:|."1@|.),&,[:(]+.+./ .*)^:_~1=[:|@-/~$j./@#:I.@, ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVTBSsNAED15yVdsO5rNpskk6UHs2sCiUBDFg3hrYxGxLUUQtD0IoT_ipR78qPoBfoeRbZLdNEnTgd3J7rx9M7Mzm8-v-XpzfXuBxLI9YXX7NkRMWHCO4y6z_X7HY-1AOGj6wui1eBCdtniPUqONdEJCTihxiE94Mlwkl3c3g-_lYuKebUYZleTakjim44eBCciEE3OWuHQsl8eYmGNkiXXIraiDHfQI2uyBj1dBOOSxcL3V8Rw9AfwKhSN9_Bz9MmMWInHFCRdAohGhSM3QmCZ7Q04mO4bnp9krofdvy8XsgxpyOU1sqdBsC1AToCo4M4J2ptZSdIBVosQAKmNGC9CAZT97FQKqDPpRAAncKqxaQjOvh8cvmQFSraagB6EucrxetxRZQlPITIOBrPO2sQaPL-9qXxWvUmsvUEdl45UdVmIArUfUy8kS1acSiDr9S1lDN1Q1ddbCgd0sa7wqHA1upljJ_Elmd1IJU5lyXwUoQA1D-qUwVSSzR7JTjd5OMaZS0Wt_WDiVTAX_h-qcSedU8gEqf_frtdR_) *-2 thanks to Neil's idea of catting transpose with input instead of using over* Takes input as a 0-1 matrix, where 1 means empty space. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 61 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` หœฦถIgรดฮ”2Fรธ0ฮด.รธ}2Fรธโ‚ฌรผ3}*ฮตฮตร…syรธร…sยซร ]หœ0Kร™gIDรธยซฮตร…ฮณsร3@Dgฤ€ยช}หœ`Iร‚รญQP ``` Input as as matrix of `1`s for white squares and `0`s for black squares. Outputs a 05AB1E-truthy/falsey result, so `1` as truthy, and `0` or a positive integer as falsey. [Try it online](https://tio.run/##yy9OTMpM/f//9Jxj2zzTD285N8XI7fAOg3Nb9A7vqAUxHzWtObzHuFbr3NZzWw@3Flce3gEkD60@vCD29BwD78Mz0z1dDu84tBokeW5z8eF@YweX9CMNh1bVnp6T4Hm46fDawID//6OjDXVA0AAIwaxYHaiIIRYRQ7gIXD1EJVgEiQ8WwdSFYi6KCMyuWAA) or [verify all test cases](https://tio.run/##pVM9SwNBEO3zK8K@QpBzCaYTJAqHjYUJgo0EjHocAYkh2QgpAhKwtrERUthq9BqTcKDVrtgE7kf4R86c9@Gu7t1FHLid25l5b2Z3Zs@7jeOm5V@QasdirL/W7jRbzDotNlvtHtsoEqNv2kxMTP5iFMj2Ces1zhJf5WP4uL9Ca/x@s0D2eiyyEn8@ep9xxxYT72Z9R7glb0KFOwh@FwjxWh5wZ9WbelNx1e0Ld7Hysbirz0elXXFrc8cULh8HXu@5K67LW6b9dskfBvPREXfEUDzVqj6hBwafVfxDQmMhBgFVBAtToJJ9GEXTJGCADEhQQBYugy/NhRwMEEZEiqZtkZPnD6WGXECs5WrVtPLmOz66bGhOqFavssghv1sYmyD1IjRB/jRATReQXBnkYydHUBfZJy@BKIO1pNJ1SckMpNQO/cwAmRP084KlnFIqbdgXBWhKDJABjf8CCuTMeubTQM5YYxn2qIf/fRn6V7C0ljtC6p8). **Explanation:** Step 1: Verify rule "*All white squares must be joined in a single region.*": ``` หœ # Flatten the (implicit) input-matrix to a single list ฦถ # Multiply each value by its 1-based index (so all 1s become unique) Igรด # Convert this list back into a matrix equal of the input-dimensions ฮ” # Loop until it no longer changes to flood-fill: 2Fรธ0ฮด.รธ} # Add a border of 0s around the matrix: 2F } # Loop 2 times: รธ # Zip/transpose; swapping rows/columns ฮด # Map over each row: 0 .รธ # Add a leading/trailing 0 2Fรธโ‚ฌรผ3} # Convert it into overlapping 3x3 blocks: 2F } # Loop 2 times again: รธ # Zip/transpose; swapping rows/columns โ‚ฌ # Map over each inner list: รผ3 # Convert it to a list of overlapping triplets * # Multiply each 3x3 block by the value in the (implicit) input-matrix # (so the 0s remain 0s) ฮตฮตร…syรธร…sยซร  # Get the largest value from the horizontal/vertical cross of each 3x3 # block: ฮตฮต # Nested map over each 3x3 block: ร…s # Pop and push its middle row y # Push the 3x3 block again รธ # Zip/transpose; swapping rows/columns ร…s # Pop and push its middle rows as well (the middle column) ยซ # Merge the middle row and column together to a single list ร  # Pop and push its maximum ] # Close the nested maps, flood-fill loop, and outer loop หœ # Flatten the resulting flood-filled matrix 0K # Remove all 0s (the black squares) ร™ # Uniquify the values of each island g # Pop and push its length (which is 1 if it was a single island of 1s) ``` [Try just step 1 online for all test cases.](https://tio.run/##pVNBS8MwFL7vV4T3DoLUMPUmyBCGIF4UwYvsUF2shdGNJRN62EXwH3gRdvAqk522MdBTA14G/RH@kdratSaathMfJC/J@973XvJeuty@dFl0Cyd9JoS/1eu7nmBt4nq9gdgjYPlNR8hpM3i1anBwJQZ2J7c1Pu5ezjboafC8X4MjTsQN6zNiE@56TocRl3dsr02612SbN2I0RMvR@zyYOHIaPuwcykU9nFK5GCbLmEm@7Q6DyWY4C2fynvtyEc/BWD61lqP6sXx0IqDnLviMgxyD14WhFcwb0QXQTMACpJpgfJSofJ@iaJEkDKg65F6IZX4lfEUmrPBBTBErRYu2WBHnD6mmXIiZVrPVw6qbb/zqsdFwQz17nUWF/C5hdoRKLdIjVIfB0VAFzJ8M1WvnV9An1aZOiWiNtaYyVUmLjFiQO5p7BrG0g34@sBJTCWWEfVEgLcAglrhmq4QCK3q99GtgRVvjOuyrGv73Z5h/wdparQi0PgE) Step 2: Verify rules "*All entries must be at least 3 squares long.*" and "*No row/column can be completely filled with black squares.*": ``` I # Push the input-matrix again D # Duplicate it รธ # Zip/transpose the copy; swapping its rows/columns ยซ # Merge the two matrices together ฮต # Map over each inner list: ร…ฮณ # Run-length encode it; pushing a list of values and lengths s # Swap so the values are at the top ร # Only keep the lengths for the truthy (==1) values 3@ # Check for each whether it's >= 3 D # Duplicate this list g # Pop and push its length ฤ€ # Check whether it's truthy (>= 0) ยช # Append this check to the list }หœ # After the map: Flatten the list of lists ` # Pop and dump all values to the stack ... P # Take the product of all values on the stack ``` [Try just step 2 online for all test cases.](https://tio.run/##pVPNSsNAEL77FMPOwUuMh94EqULOUhG8iGAa13Zxu6nJxpJDQQTPvoAvoPXmD4K3xJvQh/BFYmKauKv5qTiQnezMfN/M7sy6vt1nNDknPY9KGa6NPSYkPQYmxoHcAGKE1kDGj1b0aqyQbUcGNi993Y/L@71Vcze63Ux9HgWbc6BCeoz6YEvg1PYldMA/C2wvNXFXDGB7xwLmgxzSFCBc8NzJuuPyYCTAcUdjTiXlIZwwztMqJkwOoc9t57Qg6aZpSWLFL9Fs/hRfzR/8@LqzZQ3eLqK76fvNUS8h5j4jIfVJPCPCJVMjeu4mB8QshBgETU0wNWWq3OdRZp1kDKgCShRiE66Br86FLRjEPGKhzLottuT5Q6k5F2Kh1Wr1tOrmO35x2VhxQr16nUUN@d3CwoRKL3ITql8FsKILWF4Zqscuj6Avqk9dMtEGa0lV1SUtM2JN7Vg9M4iNE/TzgpWcSqrKsC8KNGtiEBugxV9GgS2z3vg0sGWscRn2RQ//@zKqX8HSWu0IOfwE) Step 3: Verify rule "*They should have 180 degree rotational symmetry.*": ``` I # Push the input-matrix yet again ร‚ # Bifurcate it; short for Duplicate & Reverse รญ # Also reverse each inner row Q # Check if the two matrices are still the same ``` [Try just step 3 online for all test cases.](https://tio.run/##pVO9TsMwEN55ipNvYAlmYENCVaXOiAqJBTG4wbQWrl0ShyoDS98GARtiYWvehBcJCfnBBicp4qT44rv7vjv7zjpmM8Hze3IWcWPSg1UklOHXINQqMcdAgnQyN9nrZPse7JFxaBImW9/oY/N8vk@n28eTwhdxYFICVyYSPAZmQHIWGziC@C5hUWGSWs1hfDoBEYNZ8AKgNER6fRhqmSwVhHq5ktxwmcKNkLKoYi3MAmaShbcNyahIS/Jsk71Mc0IvBEl5TLInojR5CLZvo/yS0EZIQJA6goWpVO2@iqJdUjKgDWhRiH24Hr4uFw5gEKuIWtGuLQ7k@UOpFRdio@1q3bT25ju@vmz0nNCt3mWxQ363sDGh1YvKhPbnAXq6gO2VoX3s9gjuYvvspRRnsHZUvi45mRE7akf/zCD2TtDPC7ZyWqm8YV8USDtiEHugzV9JgQOz3vs0cGCscRf2uof/fRn@V7CztjtCrj4B) Step 4: Combine all checks and output the result: ``` P # Pop all values on the stack and push its product # (which is output implicitly as result) ``` ]
[Question] [ Today Neil Sloane of the OEIS [sent out an email](http://list.seqfan.eu/pipermail/seqfan/2020-October/020991.html) asking for a confirmation of the current terms, and computation of some larger terms of the latest OEIS sequence [A337663](https://oeis.org/A337663) with the keyword "nice". Here's how this sequence works: You label \$n\$ cells on the infinite square grid with \$1\$s, and then > > place the numbers \$2,3,4,\dots,m\$ in order, subject to the rule that when you place \$k\$, the sum of its [horizontal, vertical, and diagonal] neighbors must equal \$k\$. Then \$A337663(n)\$ is the maximum \$m\$ that can be achieved over all initial placings of the \$1\$-cells. > > > Here's an illustration of \$A337663(2) = 16\$: ``` +----+----+----+----+----+----+ | 9 | 5 | 10 | 11 | | | +----+----+----+----+----+----+ | | 4 | 1 | | | | +----+----+----+----+----+----+ | 12 | 8 | 3 | 2 | | 16 | +----+----+----+----+----+----+ | | | | 6 | 1 | 15 | +----+----+----+----+----+----+ | | | 13 | 7 | 14 | | +----+----+----+----+----+----+ ``` Notice that the \$2\$-cell has two \$1\$-cells as neighbors (and \$1 + 1 = 2\$); the \$3\$-cell has a \$1\$-cell and a \$2\$-cell as neighbors (and \$1 + 2 = 3\$); etc. # The challenge. Like [this previous challenge](https://codegolf.stackexchange.com/q/194056/53884), the goal of this [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") is to compute as many terms as possible in this sequence, which begins `1, 16, 28, 38` and where the \$n\$-th term is \$A337663(n)\$. Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code to generate it. If two users post the same number of terms, then whoever posts their last term earliest wins. [Answer] # C + OpenMP, N=5 *New version with a proper handling of the 112-1113 case.* ``` a(5) = 49 0 46 26 0 0 0 0 0 0 0 0 35 0 0 20 0 6 28 48 0 0 0 0 34 1 36 39 19 1 2 3 17 0 30 0 0 33 0 37 0 0 18 7 1 4 9 0 21 32 0 0 0 0 40 0 8 38 5 43 10 11 0 44 0 0 0 0 22 0 13 0 15 0 1 12 0 0 0 47 23 0 14 27 0 31 16 29 0 0 0 0 0 24 1 0 41 0 0 0 45 0 0 0 0 49 25 0 42 0 0 0 0 0 0 0 0 0 ``` ### How it works The program will only work for N=5, for higher numbers you'd need some adjustments. First lets take a look how an easier approach for N=4 would look like. We need at least 112 next to each other in some arrangement. Because there are only two 1s left, every other number cannot be made only by new 1s. So starting from the six possible starting positions for 112: ``` 1 1 1 2 1 1 _ 1 1 _ 1 _ _ 1 _ _ 2 _ _ 2 _ 2 1 _ 2 1 _ 2 _ _ _ 1 ``` we can take a look at every space placed two spots away and check their sum (Note: with some proper case handling, you should be fine to check the direct neighbors, though I took the safe route). ``` 0 0 0 0 0 0 0 1 2 2 1 0 ``` 1 1 -> 0 3 . . 1 0 2 \_ 0 3 . 4 1 0 0 2 2 2 0 0 0 0 0 0 0 0 For every spot: check if the sum is the next needed number (in this case 3) or if we can still place some 1s: is the sum plus some newly added 1s the next needed number. In the latter case, we need to make sure that the new 1s don't interfere with existing numbers > 1, e.g. ``` 3 1 1 1 1 2 ``` wouldn't be valid as the 2-placement would have been illegal, but ``` 1 1 2 3 1 1 ``` would be fine. Note that I only increase the bounding box for two spots around non-1 numbers. So for the lower right corner, the next spots to try are as following: ``` 1 _ _ _ _ 3 1 _ _ 1 _ _ _ _ _ _ x ``` The `x` spot wouldn't get checked, as its number would only neighbor new 1s โ€“ and for N=4 this is not possible as mentioned before. For N>4 this get a little more complicated: it is not guaranteed that every number will be connected to the first 112. Another cluster might start independently: 1113. But after that every number cannot be made only of new 1s, thus will be connected to either 1113 or 112. Note that we don't have to handle anything else in the N=5 case (but would need for N>5): having two clusters with 1 and 11114 will already be handled, as 2 and 3 must also be placed in 11114; so every 11114 will already be checked by 112 or 1113. So we need to get a bounding box to find out how close 112 and 1113 can be placed. For this we run two boards that cannot touch, scoring them by the sum of the distances they managed to get away from the starting position. This is the best they manage: ``` 0 0 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 11 10 5 0 0 0 0 0 0 0 1 4 12 0 0 0 0 0 0 0 2 1 13 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 โ€ฆ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 17 9 0 3 1 0 0 0 0 8 1 6 1 0 0 0 0 16 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` They cannot leave 5 tiles. So if we place the initial 3 within a 20x20 (+ a padding of 4 for off-by-one-errors :-)) field centered around the 2, we either get two disconnected clusters that have a score independent on where they are exactly, or two clusters that eventually will join up. So anything up to ``` 1 1 _ _ _ _ _ _ _ _ _ _ _ 1 1 _ 2 a b c d e _ e d c b a 3 1 ``` will be checked with 11 spaces in between; enough that they cannot meet up. With all this, then just recursively try out all the possibilities in a depth-first-search. Always modifying only one board, we only need memory for `a(N)` recursive steps. OMP is only used to check the initial boards in parallel. This is far from a balanced workload; the final position needs about twice as long as the others. However, it is the easiest to implement. :-) ### The program Compiled with `clang -O3 -o main main.c -fopenmp` and ran with `time OMP_NUM_THREADS=4 ./main`. ``` #include <stdint.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <stdlib.h> typedef uint8_t mem_t; typedef uint16_t sum_t; #define S 64 const int startx = S/2, starty = S/2; // for N > 5, adjust the unrolled loops in step #define MAX_CELL 5 #define MAX_BOARDS 2 #define MAX(x,y) (x>y?x:y) #define MIN(x,y) (x<y?x:y) const int ys[8] = {0,1,1,1,0,-1,-1,-1}; const int xs[8] = {1,1,0,-1,-1,-1,0,1}; inline void add_sum(sum_t v, int y, int x, sum_t sum[S][S]) { for(int d=0;d<8;d++) sum[y+ys[d]][x+xs[d]] += v; } inline void add_placed(sum_t v, int y, int x, mem_t placed[S][S]) { for(int d=0;d<8;d++) placed[y+ys[d]][x+xs[d]] += v; } typedef struct board { int y0, y1, x0, x1; mem_t b[S][S], placed[S][S]; sum_t sum[S][S]; } board_t; void st_print(int c, int max, board_t *b) { printf("%d cells, %d max\n", c, max); for(int y=b->y0;y<=b->y1;y++){ for(int x=b->x0;x<=b->x1;x++) printf("%*d", 3, b->b[y][x]); puts("\n"); } } void step(int c, mem_t max, board_t *bs, int bl, mem_t *best_max, board_t best_b[MAX_BOARDS], int optimize_spread) { // check board size for(int i=0;i<bl;i++) { if (bs[i].y0 < 2 || bs[i].y1 >= S - 2 || bs[i].x0 < 2 || bs[i].x1 >= S - 2) { st_print(c, max, &bs[i]); printf("board too small %d %d %d %d", bs[i].y0, bs[i].y1, bs[i].x0, bs[i].x1); exit(1); } } // new best if (c == MAX_CELL) { int score = 0; if (optimize_spread) { for (int i=0;i<bl;i++) score += MAX(starty - bs[i].y0, MAX(bs[i].y1 - starty, MAX(startx - bs[i].x0, bs[i].x1 - startx))); } else { score = max; } if (*best_max < score) { for (int i=0;i<bl;i++) memcpy(&best_b[i], &bs[i], sizeof(board_t)); *best_max = score; } } // place with 0 new 1-cells if(!optimize_spread || max != 2) for(int i=0;i<bl;i++) { board_t *b=bs+i; for(int y=b->y0;y<=b->y1;y++) for(int x=b->x0;x<=b->x1;x++) if(b->sum[y][x] == max + 1 && !b->b[y][x]) { b->b[y][x] = max + 1; add_sum(max+1,y,x,b->sum); add_placed(1,y,x,b->placed); int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1; b->y0 = MIN(b->y0, y-2); b->y1 = MAX(b->y1, y+2); b->x0 = MIN(b->x0, x-2); b->x1 = MAX(b->x1, x+2); step(c, max + 1, bs, bl, best_max, best_b, optimize_spread); b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o; add_placed(-1,y,x,b->placed); add_sum(-(max+1),y,x,b->sum); b->b[y][x] = 0; } } // sorry for the repetition, couldn't get clang to optimize it otherwise // place with 1 new 1-cells if(!optimize_spread || max != 2) if(c + 1 <= MAX_CELL) for(int i=0;i<bl;i++) { board_t *b=bs+i; for(int y=b->y0;y<=b->y1;y++) for(int x=b->x0;x<=b->x1;x++) if(b->sum[y][x] == (max + 1) - 1 && !b->b[y][x]) { for(int d1=0;d1<8;d1++) { if (b->placed[y+ys[d1]][x+xs[d1]]) continue; b->b[y+ys[d1]][x+xs[d1]] = 1; b->b[y][x] = max + 1; add_sum(max+1,y,x,b->sum); add_sum(1,y+ys[d1],x+xs[d1],b->sum); add_placed(1,y,x,b->placed); int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1; b->y0 = MIN(b->y0, y-2); b->y1 = MAX(b->y1, y+2); b->x0 = MIN(b->x0, x-2); b->x1 = MAX(b->x1, x+2); step(c + 1, max + 1, bs, bl, best_max, best_b, optimize_spread); b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o; add_placed(-1,y,x,b->placed); add_sum(-(max+1),y,x,b->sum); add_sum(-1,y+ys[d1],x+xs[d1],b->sum); b->b[y+ys[d1]][x+xs[d1]] = 0; b->b[y][x] = 0; } } } // place with 2 new 1-cells if(!optimize_spread || max != 2) if(c + 2 <= MAX_CELL) for(int i=0;i<bl;i++) { board_t *b=bs+i; for(int y=b->y0;y<=b->y1;y++) for(int x=b->x0;x<=b->x1;x++) if(b->sum[y][x] == (max + 1) - 2 && !b->b[y][x]) { for(int d1=0;d1<8-1;d1++) { if (b->placed[y+ys[d1]][x+xs[d1]]) continue; for(int d2=d1+1;d2<8;d2++) { if (b->placed[y+ys[d2]][x+xs[d2]]) continue; b->b[y+ys[d1]][x+xs[d1]] = 1; b->b[y+ys[d2]][x+xs[d2]] = 1; b->b[y][x] = max + 1; add_sum(max+1,y,x,b->sum); add_sum(1,y+ys[d1],x+xs[d1],b->sum); add_sum(1,y+ys[d2],x+xs[d2],b->sum); add_placed(1,y,x,b->placed); int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1; b->y0 = MIN(b->y0, y-2); b->y1 = MAX(b->y1, y+2); b->x0 = MIN(b->x0, x-2); b->x1 = MAX(b->x1, x+2); step(c + 2, max + 1, bs, bl, best_max, best_b, optimize_spread); b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o; add_placed(-1,y,x,b->placed); add_sum(-(max+1),y,x,b->sum); add_sum(-1,y+ys[d1],x+xs[d1],b->sum); add_sum(-1,y+ys[d2],x+xs[d2],b->sum); b->b[y+ys[d1]][x+xs[d1]] = 0; b->b[y+ys[d2]][x+xs[d2]] = 0; b->b[y][x] = 0; } } } } // place with 3 new 1-cells if(c + 3 <= MAX_CELL) for(int i=(optimize_spread && max == 2);i<bl;i++) { board_t *b=bs+i; for(int y=b->y0;y<=b->y1;y++) for(int x=b->x0;x<=b->x1;x++) if(b->sum[y][x] == (max + 1) - 3 && !b->b[y][x]) { for(int d1=0;d1<8-2;d1++) { if (b->placed[y+ys[d1]][x+xs[d1]]) continue; for(int d2=d1+1;d2<8-1;d2++) { if (b->placed[y+ys[d2]][x+xs[d2]]) continue; for(int d3=d2+1;d3<8;d3++) { if (b->placed[y+ys[d3]][x+xs[d3]]) continue; b->b[y+ys[d1]][x+xs[d1]] = 1; b->b[y+ys[d2]][x+xs[d2]] = 1; b->b[y+ys[d3]][x+xs[d3]] = 1; b->b[y][x] = max + 1; add_sum(max+1,y,x,b->sum); add_sum(1,y+ys[d1],x+xs[d1],b->sum); add_sum(1,y+ys[d2],x+xs[d2],b->sum); add_sum(1,y+ys[d3],x+xs[d3],b->sum); add_placed(1,y,x,b->placed); int y0o = b->y0, y1o = b->y1, x0o = b->x0, x1o = b->x1; b->y0 = MIN(b->y0, y-2); b->y1 = MAX(b->y1, y+2); b->x0 = MIN(b->x0, x-2); b->x1 = MAX(b->x1, x+2); step(c + 3, max + 1, bs, bl, best_max, best_b, optimize_spread); b->y0 = y0o, b->y1 = y1o, b->x0 = x0o, b->x1 = x1o; add_placed(-1,y,x,b->placed); add_sum(-(max+1),y,x,b->sum); add_sum(-1,y+ys[d1],x+xs[d1],b->sum); add_sum(-1,y+ys[d2],x+xs[d2],b->sum); add_sum(-1,y+ys[d3],x+xs[d3],b->sum); b->b[y+ys[d1]][x+xs[d1]] = 0; b->b[y+ys[d2]][x+xs[d2]] = 0; b->b[y+ys[d3]][x+xs[d3]] = 0; b->b[y][x] = 0; } } } } } } void set_starting_board(board_t* b, int i) { int x0 = startx, y0 = starty; b->b[y0][x0] = 2; if (i == 0) b->b[y0-1][x0-1] = 1, b->b[y0+1][x0+1] = 1; if (i == 1) b->b[y0-1][x0-1] = 1, b->b[y0][x0+1] = 1; if (i == 2) b->b[y0][x0-1] = 1, b->b[y0][x0+1] = 1; if (i == 3) b->b[y0-1][x0] = 1, b->b[y0][x0+1] = 1; if (i == 4) b->b[y0-1][x0-1] = 1, b->b[y0-1][x0+1] = 1; if (i == 5) b->b[y0-1][x0] = 1, b->b[y0-1][x0+1] = 1; for(int y=1;y+1<S;y++) for(int x=1;x+1<S;x++) for(int yd=-1;yd<=1;yd++) for(int xd=-1;xd<=1;xd++) if(yd!=0||xd!=0) b->sum[y][x] += b->b[y+yd][x+xd]; for(int y=1;y+1<S;y++) for(int x=1;x+1<S;x++) for(int yd=-1;yd<=1;yd++) for(int xd=-1;xd<=1;xd++) b->placed[y][x] += b->b[y+yd][x+xd] > 1; } int get_bounding_box() { int x0 = startx, y0 = starty; board_t best_b[6][3] = {0}; mem_t best_max[6] = {0}; #pragma omp parallel for for(int i=0;i<6;i++) { board_t bs[] = {(board_t){y0 - 3, y0 + 3, x0 - 3, x0 + 3, {0}, {0}, {0}}, (board_t){y0, y0, x0, x0, {0}, {0}, {0}}}; set_starting_board(&bs[0], i); step(2, 2, bs, 2, &best_max[i], best_b[i], 1); } int best_i=0, mm = 0; for(int i=0;i<6;i++) if (best_max[i] > mm) mm = best_max[i], best_i = i; printf("most spread of distant 112 and 1113: %d\n", best_max[best_i]); st_print(MAX_CELL, best_max[best_i], &best_b[best_i][0]); st_print(MAX_CELL, best_max[best_i], &best_b[best_i][1]); return best_max[best_i] + 4; } int main(int argc, char **argv) { int bb = get_bounding_box(); int x0 = startx, y0 = starty; board_t best_b[6][3] = {0}; mem_t best_max[6] = {0}; #pragma omp parallel for for(int i=0;i<6;i++) { board_t bs[] = {(board_t){y0 - bb, y0 + bb, x0 - bb, x0 + bb, {0}, {0}, {0}},}; set_starting_board(&bs[0], i); step(2, 2, bs, 1, &best_max[i], best_b[i], 0); } int best_i=0, mm = 0; for(int i=0;i<6;i++) if (best_max[i] > mm) mm = best_max[i], best_i = i; st_print(MAX_CELL, best_max[best_i], &best_b[best_i][0]); return 0; }; ``` [Answer] # C (Perl) n=6 My first^Wsecond pass at this is available [on github](https://github.com/hvds/seq/tree/master/A337663) ; I think this should in principle be able to calculate up to a(8), but that'll take a while even now it has been recoded in C. On my machine it takes 42s for a(4) and 14ks for a(5), traversing 63,200,517 and 18,371,175,865 board positions respectively; rewriting in C gave about a 250x speedup from the initial Perl prototype. Solution found for a(5) = 49: ``` . . 39 . . . 47 . 49 46 20 19 . 40 . 23 24 25 26 . 1 18 . 22 . 1 . . 6 2 7 8 . 14 . 42 . 28 3 1 38 13 27 41 . . 48 17 4 5 . . . . . . . 9 43 15 31 . . . . 30 . 10 . 16 . . . . . 21 11 1 29 45 . . . . 32 . 12 . . . . 34 33 . 44 . . . . 35 1 . . . . . . . . 36 37 . . . . . . ``` (Oh, that's a symmetry of xash's solution, I somehow expected it to be different.) Confirming a(6) = 60 took around 10 CPU-weeks (manually sharded) and traversed 4.57e12 positions. Solution found: ``` . 56 42 . 60 . . . . . . . . . . . 14 28 32 . . . . . . . . . . 29 10 4 . 35 . . . . . . . . . 44 5 1 3 46 . . . . . . . . . . . 31 2 6 . 37 . . . . . . 55 . . 11 9 1 7 30 . . . . . . 54 1 12 45 . 25 8 15 . . . . . . 27 26 13 . . 33 . 40 16 34 51 . . . 53 . 39 52 . . . . 1 17 . . . . . . . . . . . 57 18 . 36 . . . . . . . . . . . 38 19 . . . . . . . . . . . . 58 1 20 41 . . . . . . . . . . 59 . 21 . . 47 . . . . . . . . . . 43 22 23 24 . . . . . . . . . . . . 1 48 . . . . . . . . . . . 50 49 . ``` Finding a(7) would, by extrapolation, take 200-250 times as long as a(6). I don't plan to attempt this. The approach is a) to insert the **1**s lazily as needed, and b) to store unconnected groups separately, coalescing them as needed. Extending beyond a(8) would require allowing for the possibility that we need to simultaneously coalesce 3 or more groups. I won't bother trying to solve that unless I get the speed of a(8) down to under a day or so. The core work is done by the [Board->try](https://github.com/hvds/seq/blob/master/A337663/lib/Board.pm#L46) function (C: [try\_board](https://github.com/hvds/seq/blob/master/A337663/board.c#L91)), which tries each possible way to place the next number in the current board, then recurses. The [Group->coalesce](https://github.com/hvds/seq/blob/master/A337663/lib/Group.pm#L310) (C: [coalesce\_group](https://github.com/hvds/seq/blob/master/A337663/group.c#L332)) function was the last and trickiest part to write: given two groups, the location within each that will form the common point at which the new value will be inserted, and the number of additional **1**s that must be placed around it, this algorithm: * fixes the orientation of the first group, and tries out each of the 8 possible orientations of the second group; * first checks the immediate neighbourhood of the common location, looking for orientations that allow the two groups to coexist and leave room for enough additional **1**s; * then tries to overlay one group on the other, checking for further clashes; * finally generates the k of n combinations of the n available cells around the common location into which the k additional **1**s requested can be placed. The hardest bit is going to be finding bugs, since there are so few data points to check against. I've added more tests, but I don't have confidence that I've found all bugs. Hugo [2020-10-10: added precise timings and position counts] [2020-10-13: progress in C, a(5) found] [2020-11-05: a(6) = 60 confirmed] ]
[Question] [ I've become alarmed with the growing [hatred of spaces](https://codegolf.stackexchange.com/questions/35818/i-hate-spaces-in-file-names) and [this answer](https://codegolf.stackexchange.com/a/35801/7464) has inspired me to make sure Morse code is safe from this insidious removal of whitespace. So, your task will be to create a program that can successfully translate Morse code with all of the spaces removed. ![Morse code](https://i.stack.imgur.com/iaa9g.jpg) **Rules:** 1. Input will be a string consisting only of dashes and dots (ASCII 2D and 2E). Output is undefined for input containing any other characters. Feel free to use any method convenient to your language of choice to receive the input (stdin, text file, prompt user, whatever). You can assume that the Morse code input only consists of the letters A-Z, and matching numbers or punctuation is not required. 2. Output should include only words contained in [this dictionary file](http://pastebin.com/SKMrBLVV) (again, feel free to use any convenient method to access the dictionary file). All valid decodings should be output to stdout, and all dots and dashes in the input must be used. Each matched word in the output should be separated by a space, and each possible decoding should separated by a newline. You can use upper case, lower case, or mixed case output as convenient. 3. All restrictions on [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply with one exception as noted above, you may access the dictionary file referenced in requirement 2 via an internet connection if you really want to. URL shortening is acceptable, I believe that [goo.gl/46I35Z](http://goo.gl/46I35Z) is likely the shortest. 4. This is code golf, shortest code wins. **Note:** Posting the dictionary file on Pastebin changed all of the line endings to Windows style 0A 0E sequences. Your program can assume line endings with 0A only, 0E only or 0A 0E. **Test Cases:** Input: > > ......-...-..---.-----.-..-..-.. > > > Output must contain: > > hello world > > > Input: > > .--..-.-----..-..-----..-.--..--...---..--...-.......--.-..-.-.----...--.---.-....-. > > > Output must contain: > > programming puzzles and code golf > > > Input: > > -.....--.-..-..-.-.-.--....-.---.---...-.----..-.---..---.--....---...-..-.-......-...---..-.---..-----. > > > Output must contain: > > the quick brown fox jumps over the lazy dog > > > [Answer] ## Ruby, 210 ``` (1..(g=gets).size).map{|x|puts IO.read(?d).split.repeated_permutation(x).select{|p|p.join.gsub(/./,Hash[(?a..?z).zip"(;=/%513':07*)29@-+&,4.<>?".bytes.map{|b|('%b'%(b-35))[1,7].tr'01','.-'}])==g}.map{|r|r*' '}} ``` If there exists such a practice as "over-golfing", I suspect I have partaken this time around. This solution generates an array of arrays of repeated permutations of *all of the dictionary words*, from length 1 up to the length of the input. Given that "a" is the shortest word in the dictionary file and its code is two characters long, it would have been sufficient to generate permutations of length up to half the size of the input, but adding `/2` is tantamount to verbosity in this domain, so I refrained. Once the permutation array has been generated (*NB*: it is of length 45404104 in the case of the pangrammatic example input), each permutation array is concatenated, and its alphabetic characters are replaced with their Morse code equivalents via the rather convenient `(Regexp, Hash)` variant of the `#gsub` method; we've found a valid decoding if this string is equal to the input. The dictionary is read (several times) from a file named "d", and the input must not contain a newline. **Example run** (with a dictionary that'll give the program a fighting chance at ending before the heat death of the universe): ``` $ cat d puzzles and code dummy golf programming $ echo -n .--..-.-----..-..-----..-.--..--...---..--...-.......--.-..-.-.----...--.---.-....-. | ruby morse.rb programming puzzles and code golf ^C ``` [Answer] ## Haskell, 296 characters * Dictionary file: must be a text file named "d" * Input: stdin, may have a trailing newline but no internal whitespace ``` main=do f<-readFile"d";getLine>>=mapM(putStrLn.unwords).(words f&) i!""=[i] (i:j)!(p:q)|i==p=j!q _!_=[] _&""=[[]] d&i=do w<-d j<-i!(w>>=((replicate 97"X"++words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..")!!).fromEnum) n<-d&j [w:n] ``` Explanation of elements: * `main` reads the dictionary, reads stdin, executes `&`, and formats the output of `&` with appropriate whitespace. * `(replicate 97"X"++words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..")!!)` (an expression inside of the definition of `&`) is a list whose indices are character codes (97 is the code of `'a'`) and values are Morse sequences. * `!` (a function named as an infix operator) matches a string against a prefix; if the prefix is present it returns the remainder in a one-element list (success in the list monad), otherwise the empty list (failure in the list monad) * `&` uses the list monad for โ€œnondeterministicโ€ execution; it 1. picks an entry of `d` (a dictionary word), 2. uses `!` to match the Morse form of that word (`w>>=((โ€ฆ)!!).fromEnum`, which is equivalent to `concatMap (((โ€ฆ)!!) . fromEnum) w`) against the input string `i`, 3. calls itself (`d&j`) to match the rest of the string, and 4. returns the possible result as a list of words `w:n`, in the list monad `[w:n]` (which is the shorter, concrete equivalent to `return (w:n)`).Note that every line after line 6 is part of the `do` expression started on line 6; this takes exactly the same number of characters as using semicolons on a single line, but is more readable, though you can only do it once in a program. This program is extremely slow. It can be made faster (and slightly longer) easily by storing the morsified words next to the originals in a list rather than recomputing them at each pattern match. The next thing to do would be to store the words in a binary tree keyed by Morse symbols (a 2-ary [*trie*](http://en.wikipedia.org/wiki/Trie)) so as to avoid trying unnecessary branches. It could be made slightly shorter if the dictionary file did not contain unused symbols such as "-", allowing removal of `replicate 97"X"++` in favor ofย doing `.(-97+)` before the `!!`. [Answer] # Python - ~~363~~ 345 **Code:** ``` D,P='-.';U,N='-.-','.-.' def s(b,i): if i=='':print b for w in open('d').read().split(): C=''.join([dict(zip('abcdefghijklmnopqrstuvwxyz-\'23',[P+D,D+3*P,U+P,'-..',P,D+N,'--.',4*P,2*P,P+3*D,U,N+P,2*D,D+P,D*3,'.--.',D+U,N,P*3,D,'..-',3*P+D,'.--','-..-',U+D,'--..']+['']*4))[c]for c in w]);L=len(C) if i[:L]==C:s(b+' '+w,i[L:]) s('',input()) ``` **Explanation:** The dictionary must be stored as a plain text file named "d". `D`, `P`, `U` and `N` are just some helper variables for a shorter definition of the morse lookup table. `s(i)` is a recursive function that prints the previously translated message part `p` and each valid translation of the remaining code part `i`: If `i` is empty, we reached the end of the code an `b` contains the whole translation, thus we simply `print` it. Otherwise we check each word `w` in the dictionary `d`, translate it into morse code `C` and, if the remaining code `i` starts with `C`, we add the word `w` to the translated beginning `b` and call the function `s` recursively on the remainder. **Note on efficiency:** This is a pretty slow but golfed version. Especially loading the dictionary and constructing the morse lookup table (`dict(zip(...))`) in each iteration (to avoid more variables) costs a lot. And it would be more efficient to translate all words in the dictionary file once in advance and not in each recursion on demand. These ideas lead to the following version with 40 more characters but *significant* speed-up: ``` d=open('d').read().split() D,P='-.';U,N='-.-','.-.' M=dict(zip('abcdefghijklmnopqrstuvwxyz-\'23',[P+D,D+3*P,U+P,'-..',P,D+N,'--.',4*P,2*P,P+3*D,U,N+P,2*D,D+P,D*3,'.--.',D+U,N,P*3,D,'..-',3*P+D,'.--','-..-',U+D,'--..']+['']*4)) T=[''.join([M[c]for c in w])for w in d] def s(b,i): if i=='':print b for j,w in enumerate(d): C=T[j];L=len(C) if i[:L]==C:s(b+' '+w,i[L:]) s('',input()) ``` [Answer] # Haskell - 418 This decoing problem can be solved efficiently by dynamic programming. I know this is a codegolf, but I love fast code. Say we have the input string `s`, then we build an array `dp`, `dp[i]` is the list of all valid decoding results of substring `s[:i]`. For each word `w` in the dictionary, first we encoding it to `mw`, then we can compute part of `dp[i]` from `dp[i - length(mw)]` if `s[i - length(mw):i] == mw`. The time complexity of building `dp` is `O({count of words} {length of s} {max word length})`. Finally, `dp[length(s)]`, the last element, is what we need. In fact, we don't need to store the whole decoding as the element of each `dp[i]`. What we need is the last decoded word. This make the implementation a lot faster. It cost less than 2 seconds to finished the "hello world" case on my i3 laptop. For other cases posted in the question, the program will not finish pratically since there are too many to output. Using the dynamic programming technique, we can compute **the number of valid decodings**. You can find the code [here](http://pastebin.com/hGL8Hzti). Results: ``` input: ......-...-..---.-----.-..-..-.. count: 403856 input: .--..-.-----..-..-----..-.--..--...---..--...-.......--.-..-.-.----...--.---.-....-. count: 2889424682038128 input: -.....--.-..-..-.-.-.--....-.---.---...-.----..-.---..---.--....---...-..-.-......-...---..-.---..-----. count: 4986181473975221635 ``` ## Ungolfed ``` import Control.Monad morseTable :: [(Char, String)] morseTable = zip ['a'..'z'] $ words ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.." wordToMorse :: String -> Maybe String wordToMorse xs = return . concat =<< mapM (`lookup` morseTable) xs slice :: (Int, Int) -> [a] -> [a] slice (start, end) = take (end - start) . drop start decode :: String -> String -> IO () decode dict s = trace (length s) [] where dict' = [(w, maybe "x" id . wordToMorse $ w) | w <- lines dict] dp = flip map [0..length s] $ \i -> [(j, w) | (w, mw) <- dict', let j = i - length mw, j >= 0 && mw == slice (j, i) s] trace :: Int -> [String] -> IO () trace 0 prefix = putStrLn . unwords $ prefix trace i prefix = sequence_ [trace j (w:prefix) | (j, w) <- dp !! i] main :: IO () main = do ws <- readFile "wordlist.txt" decode ws =<< getLine ``` ## Golfed ``` import Control.Monad l=length t=zip['a'..]$words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.." h s=return.concat=<<mapM(`lookup`t)s f d s=g(l s)[]where g 0 p=putStrLn.unwords$p;g i p=sequence_[g j(w:p)|(j,w)<-map(\i->[(j,w)|(w,m)<-[(w,maybe"x"id.h$w)|w<-lines d],let j=i-l m,j>=0&&m==(take(i-j).drop j$s)])[0..l s]!!i] main=do d<-readFile"d";f d=<<getLine ``` [Answer] ## Perl (5.10+), 293 characters Dictionary file should be saved as "d" (and should be in unix format if you don't want CRs between words), morse input on stdin, with no trailing newline (use `echo -n`). ``` open D,d;chomp(@w=<D>);@m{a..z}=map{substr(sprintf("%b",-61+ord),1)=~y/01/.-/r} 'BUWI?OKMATJQDCLSZGE@FNHVXY'=~/./g;%w=map{$_,qr#^\Q@{[s/./$m{$&}/reg]}#}@w; @a=[$i=<>];while(@a){say join$",@{$$_[1]}for grep!$$_[0],@a; @a=map{$x=$_;map{$$x[0]=~$w{$_}?[substr($$x[0],$+[0]),[@{$$x[1]},$_]]:()}@w}@a} ``` (linebreaks only for formatting). ### Ungolfed code: ``` # Read the word list open my $dictionary, '<', 'd'; chomp(my @words = <$dictionary>); # Define morse characters my %morse; @morse{'a' .. 'z'} = map { $n = ord($_) - 61; $bits = sprintf "%b", $n; $bits =~ tr/01/.-/; substr $bits, 1; } split //, 'BUWI?OKMATJQDCLSZGE@FNHVXY'; # Make a hash of words to regexes that match their morse representation my %morse_words = map { my $morse_word = s/./$morse{$_}/reg; ($_ => qr/^\Q$morse_word/) } @words; # Read the input my $input = <>; # Initialize the state my @candidates = ({ remaining => $input, words => [] }); while (@candidates) { # Print matches for my $solution (grep { $_->{remaining} eq '' } @candidates) { say join " ", @{ $solution->{words} }; } # Generate new solutions @candidates = map { my $candidate = $_; map { $candidate->{remaining} =~ $morse_words{$_} ? { remaining => substr( $candidate->{remaining}, $+[0] ), words => [ @{ $candidate->{words} }, $_ ], } : () } @words } @candidates; } ``` ### Modus Operandi: Morse code symbols are stored by changing "." and "-" into binary digits 0 and 1, prepending a "1" (so that leading dots aren't gobbled up), converting the binary number into decimal, and then encoding the character with the value 61 higher (which gets me all printable chars and nothing that needs backslashing). I thought of this as a kind of partitioning problem, and built a solution based on that. For each word in the dictionary, it constructs a regex object that will match (and capture) that word's spaceless morse representation at the beginning of a string. Then it begins a breadth-first search by creating a state that has matched no words and has the entire input as "remaining input". Then it expands each state by looking for words that match at the beginning of the remaining input, and creating new states that add the word to the matched words and remove the morse from the remaining input. States that have no remaining input are successful and have their list of words printed. States that can't match any words (including successful ones) generate no child states. Note that in the ungolfed version the states are hashes for readability; in the golfed version they're arrays (for shorter code and less memory consumption); slot `[0]` is the remaining input and slot `[1]` is the matched words. ### Commentary This is ungodly slow. I'm wondering if there's a solution that isn't. I tried to build one using Marpa (an Earley parser with the ability to give multiple parses for a single input string) but ran out of memory just constructing the grammar. Maybe if I used a lower-level API instead of the BNF input... [Answer] # PHP, ~~234~~ 226 bytes ``` function f($s,$r=""){$s?:print"$r ";foreach(file(d)as$w){for($i=+$m="";$p=@strpos(__etianmsurwdkgohvf_l_pjbxcyzq,$w[$i++]);)$m.=strtr(substr(decbin($p),1),10,"-.");0!==strpos($s,$m)?:g(substr($s,strlen($m)),$r.trim($w)." ");}} ``` recursive function, takes dictionary from a file named `d`. Fails for every word in the dictionary containing a non-letter. You can use any file name if you `define ("d","<filename>");` before calling the function. Add 2 or 3 bytes for faster execution: Remove `$s?:print"$r\n";`, insert `$s!=$m?` before `0!==` and `:print$r.$w` before `;}}`. **breakdown** ``` function f($s,$r="") { $s?:print"$r\n"; // if input is empty, print result foreach(file(d)as$w) // loop through words { // translate to morse: for($i=+$m=""; // init morse to empty string, $i to 0 // loop while character is in the string $p=@strpos(__etianmsurwdkgohvf_l_pjbxcyzq,$w[$i++]) ;) $m.= // 4. append to word morse code strtr( substr( decbin($p) // 1: convert position to base 2 ,1) // 2: substr: remove leading `1` ,10,"-.") // 3. strtr: dot for 0, dash for 1 ; 0!==strpos($s,$m) // if $s starts with $m ?:f( // recurse substr($s,strlen($m)), // with rest of $s as input $r.trim($w)." " // and $r + word + space as result ) ; } } ``` [Answer] **Groovy ~~377~~ 337** ``` r=[:];t={x='',p=''->r[s[0]]=p+x;s=s.substring(1);if(p.size()<3){t('.',p+x);t('-',p+x)}};s='-eishvuf-arl-wpjtndbxkcymgzqo--';t() m=('d'as File).readLines().groupBy{it.collect{r.get(it,0)}.join()} f={it,h=[]->it.size().times{i->k=it[0..i] if(k in m){m[k].each{j->f(it.substring(i+1),h+[j])}}} if(it.empty){println h.join(' ')}} f(args[0]) ``` *Notes* The dict must be a file named `d`. The morse string is passed by command line. e.g.: ``` % groovy morse.groovy ......-...-..---.-----.-..-..-.. | grep 'hello world' hello world ``` For "morse code compression" I am using a [binary tree](https://en.wikipedia.org/wiki/File:Morse_code_tree3.png) ]
[Question] [ # Background The official currency of the imaginary nation of Golfenistan is the *foo*, and there are only three kinds of coins in circulation: 3 foos, 7 foos and 8 foos. One can see that it's not possible to pay certain amounts, like 4 foos, using these coins. Nevertheless, all large enough amounts can be formed. Your job is to find the largest amount that can't be formed with the coins (5 foos in this case), which is known as the [coin problem](https://en.wikipedia.org/wiki/Coin_problem). # Input Your input is a list `L = [n1, n2, ..., nk]` of positive integers, representing the values of coins in circulation. Two things are guaranteed about it: * The GCD of the elements of `L` is 1. * `L` does not contain the number 1. It may be unsorted and/or contain duplicates (think special edition coins). # Output Since the GCD of `L` is 1, every large enough integer `m` can be expressed as a non-negative linear combination of its elements; in other words, we have ``` m = a1*n1 + a2*n2 + ... + ak*nk ``` for some integers `ai โ‰ฅ 0`. Your output is the largest integer that *cannot* be expressed in this form. As a hint, it is known that the output is always less than `(n1 - 1)*(nk - 1)`, if `n1` and `nk` are the maximal and minimal elements of `L` ([reference](http://www.cis.upenn.edu/~cis511/Frobenius-number.pdf)). # Rules You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. If your language has a built-in operation for this, you may not use it. There are no requirements for time or memory efficiency, except that you should be able to evaluate the test cases before posting your answer. After I posted this challenge, user @vihan pointed out that Stack Overflow has an [exact duplicate](https://stackoverflow.com/questions/3465392/code-golf-frobenius-number). Based on [this Meta discussion](http://meta.codegolf.stackexchange.com/questions/6896/duplicates-on-other-se-sites), this challenge will not be deleted as a duplicate; however, I ask that all answers based on those of the SO version should cite the originals, be given the Community Wiki status, and be deleted if the original author wishes to post their answer here. # Test Cases ``` [3, 7, 8] -> 5 [25, 10, 16] -> 79 [11, 12, 13, 14, 13, 14] -> 43 [101, 10] -> 899 [101, 10, 899] -> 889 [101, 10, 11] -> 89 [30, 105, 70, 42] -> 383 [2, 51, 6] -> 49 ``` [Answer] # Perl, ~~60~~ ~~54~~ 51 bytes 50 bytes code + 1 bytes command line ``` $.*=$_,$r.=1x$_."|"}{$_=$.while(1x$.--)=~/^($r)+$/ ``` The basic approach is to let the regex engine do the hard work with string matching. For example, it will construct a regex similar to `^(.{3})*(.{7})*(.{8})*$` and match against a string of length `n` where `n` descends from the product of the inputs until it fails to match. Note that this will become exponentially slow as the number of arguments increases. Usage: Arguments are read in from STDIN (new line separated), for example: ``` printf "101\n10" | perl -p entry.pl ``` [Answer] # Pyth, 23 bytes ``` ef!fqTs.b*NYQY^UTlQS*FQ ``` It's very slow, as it checks all values up to the product of all the coins. Here's a version that is almost identical, but 1) reduces the set of coins to those not divisible by each other and 2) only checks values up to `(max(coins) - 1) * (min(coins) - 1)` (47 bytes): ``` =Qu?.A<LiHdG+GHGQYef!fqTs.b*NYQY^UTlQS*thSQteSQ ``` ## Explanation ``` S range 1 to *FQ product of input f filter by UT range 0 to T ^ lQ cartesian power by number of coins f filter by s.b*NYQY sum of coin values * amounts qT equals desired number T ! nothing matching that filter e take last (highest) element ``` [Answer] # [R](https://www.r-project.org/), 84 78 72 bytes For an arbitrary entry of coprimes, \$a\_1, a\_2,\ldots\$, [Frobenius' amount](https://en.wikipedia.org/wiki/Coin_problem) is given by ``` a=scan();max((1:(b<-min(a)*max(a)))[-colSums(combn(outer(a,0:b),sum(!!a)))]) ``` [Try it online!](https://tio.run/##FcpBCoAgEAXQq@TuTxhomyDqFC2jhUqC0ChUA93ecPt4d41rjZLDm0qGI3YfYGf4ZeDUoG/iiGgfQrk24QehsM8o8p43nDazJ/0IQ6nWDqoRAXbSnTUjUf0B "R โ€“ Try It Online") since it is always smaller than the product of the extreme \$a\_i\$'s. It is then a matter of combining all possible combinations (and more) within that range. Thanks to Cole Beck for suggesting `outer` with no "\*" and `colSums` rather than `apply(...,2,sum)'. A faster but longer (by two bytes) version only considers `max(a)`: ``` a=scan();max((1:(min(a)*(b<-max(a))))[-colSums(combn(outer(a,0:b),sum(!!a)))]) ``` A slightly shorter version (72 bytes) that most often takes too log or too much space to run on [Try it online](https://tio.run/##FctBCsIwEAXQu3T1fxmh050FTxKyGEOjQpOUmkA9fdT14x093npsOdRXyTAmOwFdYE79aG72pLvYvm8fhJLuGaXV9YDJtPxVhnGgbGt@1OdvU2Z5t0TPHhGgV9FJyf4F) is ``` a=scan();max((1:(b<-prod(a)))[-colSums(combn(outer(a,0:b),sum(!!a)))]) ``` [Answer] # Python2, 188 187 bytes ``` def g(L): M=max(L);i=r=0;s=[0]*M;l=[1]+s[1:] while 1: if any(all((l+l)[o:o+min(L)])for o in range(M)):return~-s[r]*M+r if any(l[(i-a)%M]for a in L):l[i]=1 else:r=i s[i]+=1;i=(i+1)%M ``` The second indentation is rendered as 4 spaces on SO, those should be tabs. Actually a 'fast' solution, not bruteforce, uses 'Wilf's Method' as described [here](http://www.math.univ-montp2.fr/%7Eramirez/Tenerif1.pdf). [Answer] # Javascript ES6, ~~120~~ ~~130~~ ~~126~~ ~~128~~ ~~127~~ 125 chars ``` f=a=>`${r=[1|a.sort((a,b)=>a-b)]}`.repeat(a[0]*a[a.length-1]).replace(/./g,(x,q)=>r[q]|a.map(x=>r[q+x]|=r[q])).lastIndexOf(0) ``` Alternative 126 chars version: ``` f=a=>{r=[1];a.sort((a,b)=>a-b);for(q=0;q<a[0]*a[a.length-1];++q)r[q]?a.map(x=>r[q+x]=1):r[q]=0;return r.join``.lastIndexOf(0)} ``` Test: ``` "[3, 7, 8] -> 5\n\ [25, 10, 16] -> 79\n\ [11, 12, 13, 14, 13, 14] -> 43\n\ [101, 10] -> 899\n\ [101, 10, 899] -> 889\n\ [101, 10, 11] -> 89\n\ [30, 105, 70, 42] -> 383\n\ [2, 51, 6] -> 49".replace(/(\[.*?\]) -> (\d+)/g, function (m, t, r) { return f(JSON.parse(t)) == r }) ``` [Answer] # [Ruby](https://ruby-doc.org/), 108 bytes ``` ->a{b=[0];m=a.min (1..1.0/0).map{|n|c=p a.map{|x|c|=(b!=b-[n-x])} c&& b<<=n return n-m if b[-m]&&b[-m]>n-m}} ``` [Try it online!](https://tio.run/##dc/daoMwFADg@zzFGQNpwWSJP1Vp44uEXBhpwYtk4ia0VJ/dnVi2EdcFQv6@c3LOMJrbchnezdl144dcaN3cjVRcH61smO0c2QnGBONvfM9s098nN7WyJ83jcJ3aSe7MizRUOXrV@5m0UQTmdJKODOfPcXDgqIXuAkZRq6NoXWq8m@elh5@flUpjKGIotYbNeJU15CSwSR6D4DgPG@5tUYVYCIQJTvxBZN8rBnqcpRvMvebPqyir6qmO/UsQsuryPy1EmP@RO8Spdxz7LHCTJb8BHqflpmxsL8fkhz91rz1Wyxc "Ruby โ€“ Try It Online") # Explanation ``` ->a{ input list b=[0]; list of representable integers m=a.min minimum input (1..1.0/0).map{|n| n in range 1.. c=p c = false a.map{|x|c|=(b!=b-[n-x])} check if n goes in b c&& b<<=n put n in b return n-m if b[-m]&&b[-m]>n-m}} return if m values in a row ``` ]
[Question] [ A De Bruijn sequence is interesting: It is the shortest, cyclic sequence that contains all possible sequences of a given alphabet of a given length. For example, if we were considering the alphabet A,B,C and a length of 3, a possible output is: ``` AAABBBCCCABCACCBBAACBCBABAC ``` You will notice that every possible 3-character sequence using the letters `A`, `B`, and `C` are in there. Your challenge is to generate a De Bruijn sequence in as few characters as possible. Your function should take two parameters, an integer representing the length of the sequences, and a list containing the alphabet. Your output should be the sequence in list form. You may assume that every item in the alphabet is distinct. An example generator can be found [here](http://en.wikipedia.org/wiki/De_Bruijn_sequence) [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply [Answer] # Pyth, 31 bytes This is the direct conversion of the algorithm used in my [CJam answer](https://codegolf.stackexchange.com/a/42730/31414). Tips for golfing welcome! ``` Mu?G}H+GG+G>Hefq<HT>G-lGTUH^GHk ``` This code defines a function `g` which takes two arguments, the string of list of characters and the number. Example usage: ``` Mu?G}H+GG+G>Hefq<HT>G-lGTUH^GHkg"ABC"3 ``` Output: ``` AAABAACABBABCACBACCBBBCBCCC ``` Code expansion: ``` M # def g(G,H): u # return reduce(lambda G, H: ?G # (G if }H # (H in +GG # add(G,G)) else +G # add(G, >H # slice_end(H, e # last_element( f # Pfilter(lambda T: q # equal( <HT # slice_start(H,T), >G # slice_end(G, -lGT # minus(Plen(G),T))), UH # urange(H)))))), ^GH # cartesian_product(G,H), k # "") ``` [Try it here](http://isaacg.scripts.mit.edu/pyth/index.py) [Answer] # CJam, ~~52 49~~ 48 bytes This is surprisingly long. This can be golfed a lot, taking in tips from the Pyth translation. ``` q~a*{m*:s}*{:H\:G_+\#)GGHH,,{_H<G,@-G>=},W=>+?}* ``` The input goes like ``` 3 "ABC" ``` i.e. - String of list of characters and the length. and output is the De Bruijn string ``` AAABAACABBABCACBACCBBBCBCCC ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # CJam, ~~52~~ 49 bytes Here is a different approach in CJam: ``` l~:N;:L,(:Ma{_N*N<0{;)_!}g(+_0a=!}g]{,N\%!},:~Lf= ``` Takes input like this: ``` "ABC" 3 ``` and produces a Lyndon work like ``` CCCBCCACBBCBACABCAABBBABAAA ``` [Try it here.](http://cjam.aditsu.net/) This makes use of [the relation with Lyndon words](http://en.wikipedia.org/wiki/Lyndon_word). It generates all Lyndon words of length *n* in lexicographic order (as outlined in that Wikipedia article), then drops those whose length doesn't divide *n*. This already yields the De Bruijn sequence, but since I'm generating the Lyndon words as strings of digits, I also need to replace those with the corresponding letters at the end. For golfing reasons, I consider the later letters in the alphabet to have lower lexicographic order. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` แนL*ยฅล’!;`wโฑฎแบ ษ—ฦ‡แน—แธข ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//4bmBTCrCpcWSITtgd@KxruG6oMmXxofhuZfhuKL/w6f//yIxMCL/Mw "Jelly โ€“ Try It Online") Pretty slow, uses a brute force approach with around an \$O(n \times m \times (n \times m)!)\$ complexity, where \$n\$ is the integer input and \$m\$ is the length of the string. Times out if both \$n\$ and \$m\$ are greater than 3 on TIO ## How it works The length of the De Bruijn sequence will always be \$m^n\$ and each symbol in the provided alphabet will occur the same number of times, \$m^{n-1}\$. Therefore, we generate the string with that many symbols, then filter its permutations to find valid De Bruijn sequences. ``` แนL*ยฅล’!แบ‹2wโฑฎแบ ส‹ฦ‡แน—แธข - Main link. Takes an alphabet A on the left and n on the right ยฅ - Last 2 links as a dyad f(A, n): L - Length of A * - Raised to the power n แน - Mold A to that length ล’! - All permutations แน— - Powerset; Get all length n combinations of A. Call that C ส‹ฦ‡ - Filter the permutations P on the following dyad g(P, C): แบ‹2 - Repeat P twice โฑฎ - For each element E in C: w - Is it a sublist of P? แบ  - Is this true for all elements of C? แธข - Take the first one ``` [Answer] # JavaScript (ES6) 143 Using Lyndon words, like Martin's aswer, just 3 times long... ``` F=(a,n)=>{ for(w=[-a[l='length']],r='';w[0];) { n%w[l]||w.map(x=>r+=a[~x]); for(;w.push(...w)<=n;); for(w[l]=n;!~(z=w.pop());); w.push(z+1) } return r } ``` **Test** In FireFox/FireBug console ``` console.log(F("ABC",3),F("10",4)) ``` *Output* ``` CCCBCCACBBCBACABCAABBBABAAA 0000100110101111 ``` [Answer] # Python 2, 114 bytes I'm not really sure how to golf it more, due to my approach. ``` def f(a,n): s=a[-1]*n while 1: for c in a: if((s+c)[len(s+c)-n:]in s)<1:s+=c;break else:break print s[:1-n] ``` [**Try it online**](https://repl.it/EgeQ/1) **Ungolfed:** This code is a trivial modification from [my solution](https://codegolf.stackexchange.com/a/101991/34718) to more recent challenge. ``` def f(a,n): s=a[-1]*n while 1: for c in a: p=s+c if p[len(p)-n:]in s: continue else: s=p break else: break print s[:1-n] ``` The only reason `[:1-n]` is needed is because the sequence includes the wrap-around. [Answer] # Powershell, ~~164~~ 96 bytes *-68 bytes with -match `O($n*2^n)` instead recursive generator `O(n*log(n))`* ``` param($s,$n)for(;$z=$s|% t*y|?{"$($s[-1])"*($n-1)+$x-notmatch-join"$x$_"[-$n..-1]}){$x+=$z[0]}$x ``` Ungolfed & test script: ``` $f = { param($s,$n) # $s is a alphabet, $n is a subsequence length for(; # repeat until... $z=$s|% t*y|?{ # at least a character from the alphabet returns $true for expression: "$($s[-1])"*($n-1)+$x-notmatch # the old sequence that follows two characters (the last letter from the alphabet) not contains -join"$x$_"[-$n..-1] # n last characters from the new sequence }){ $x+=$z[0] # replace old sequence with new sequence } $x # return the sequence } @( ,("ABC", 2, "AABACBBCC") ,("ABC", 3, "AAABAACABBABCACBACCBBBCBCCC") ,("ABC", 4, "AAAABAAACAABBAABCAACBAACCABABACABBBABBCABCBABCCACACBBACBCACCBACCCBBBBCBBCCBCBCCCC") ,("ABC", 5, "AAAAABAAAACAAABBAAABCAAACBAAACCAABABAABACAABBBAABBCAABCBAABCCAACABAACACAACBBAACBCAACCBAACCCABABBABABCABACBABACCABBACABBBBABBBCABBCBABBCCABCACABCBBABCBCABCCBABCCCACACBACACCACBBBACBBCACBCBACBCCACCBBACCBCACCCBACCCCBBBBBCBBBCCBBCBCBBCCCBCBCCBCCCCC") ,("ABC", 6, "AAAAAABAAAAACAAAABBAAAABCAAAACBAAAACCAAABABAAABACAAABBBAAABBCAAABCBAAABCCAAACABAAACACAAACBBAAACBCAAACCBAAACCCAABAABAACAABABBAABABCAABACBAABACCAABBABAABBACAABBBBAABBBCAABBCBAABBCCAABCABAABCACAABCBBAABCBCAABCCBAABCCCAACAACABBAACABCAACACBAACACCAACBABAACBACAACBBBAACBBCAACBCBAACBCCAACCABAACCACAACCBBAACCBCAACCCBAACCCCABABABACABABBBABABBCABABCBABABCCABACACABACBBABACBCABACCBABACCCABBABBABCABBACBABBACCABBBACABBBBBABBBBCABBBCBABBBCCABBCACABBCBBABBCBCABBCCBABBCCCABCABCACBABCACCABCBACABCBBBABCBBCABCBCBABCBCCABCCACABCCBBABCCBCABCCCBABCCCCACACACBBACACBCACACCBACACCCACBACBACCACBBBBACBBBCACBBCBACBBCCACBCBBACBCBCACBCCBACBCCCACCACCBBBACCBBCACCBCBACCBCCACCCBBACCCBCACCCCBACCCCCBBBBBBCBBBBCCBBBCBCBBBCCCBBCBBCBCCBBCCBCBBCCCCBCBCBCCCBCCBCCCCCC") ,("01", 3, "00010111") ,("01", 4, "0000100110101111") ,("abcd", 2, "aabacadbbcbdccdd") ,("0123456789", 3, "0001002003004005006007008009011012013014015016017018019021022023024025026027028029031032033034035036037038039041042043044045046047048049051052053054055056057058059061062063064065066067068069071072073074075076077078079081082083084085086087088089091092093094095096097098099111211311411511611711811912212312412512612712812913213313413513613713813914214314414514614714814915215315415515615715815916216316416516616716816917217317417517617717817918218318418518618718818919219319419519619719819922232242252262272282292332342352362372382392432442452462472482492532542552562572582592632642652662672682692732742752762772782792832842852862872882892932942952962972982993334335336337338339344345346347348349354355356357358359364365366367368369374375376377378379384385386387388389394395396397398399444544644744844945545645745845946546646746846947547647747847948548648748848949549649749849955565575585595665675685695765775785795865875885895965975985996667668669677678679687688689697698699777877978878979879988898999") ,("9876543210", 3, "9998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888788688588488388288188087787687587487387287187086786686586486386286186085785685585485385285185084784684584484384284184083783683583483383283183082782682582482382282182081781681581481381281181080780680580480380280180077767757747737727717707667657647637627617607567557547537527517507467457447437427417407367357347337327317307267257247237227217207167157147137127117107067057047037027017006665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555455355255155054454354254154053453353253153052452352252152051451351251151050450350250150044434424414404334324314304234224214204134124114104034024014003332331330322321320312311310302301300222122021121020120011101000") ) |% { $s,$n,$e = $_ $r = &$f $s $n "$($r-eq$e): $r" } ``` Output: ``` True: AABACBBCC True: AAABAACABBABCACBACCBBBCBCCC True: AAAABAAACAABBAABCAACBAACCABABACABBBABBCABCBABCCACACBBACBCACCBACCCBBBBCBBCCBCBCCCC True: AAAAABAAAACAAABBAAABCAAACBAAACCAABABAABACAABBBAABBCAABCBAABCCAACABAACACAACBBAACBCAACCBAACCCABABBABABCABACBABACCABBACABBBBABBBCABBCBABBCCABCACABCBBABCBCABCCBABCCCACACBACACCACBBBACBBCACBCBACBCCACCBBACCBCACCCBACCCCBBBBBCBBBCCBBCBCBBCCCBCBCCBCCCCC True: AAAAAABAAAAACAAAABBAAAABCAAAACBAAAACCAAABABAAABACAAABBBAAABBCAAABCBAAABCCAAACABAAACACAAACBBAAACBCAAACCBAAACCCAABAABAACAABABBAABABCAABACBAABACCAABBABAABBACAABBBBAABBBCAABBCBAABBCCAABCABAABCACAABCBBAABCBCAABCCBAABCCCAACAACABBAACABCAACACBAACACCAACBABAACBACAACBBBAACBBCAACBCBAACBCCAACCABAACCACAACCBBAACCBCAACCCBAACCCCABABABACABABBBABABBCABABCBABABCCABACACABACBBABACBCABACCBABACCCABBABBABCABBACBABBACCABBBACABBBBBABBBBCABBBCBABBBCCABBCACABBCBBABBCBCABBCCBABBCCCABCABCACBABCACCABCBACABCBBBABCBBCABCBCBABCBCCABCCACABCCBBABCCBCABCCCBABCCCCACACACBBACACBCACACCBACACCCACBACBACCACBBBBACBBBCACBBCBACBBCCACBCBBACBCBCACBCCBACBCCCACCACCBBBACCBBCACCBCBACCBCCACCCBBACCCBCACCCCBACCCCCBBBBBBCBBBBCCBBBCBCBBBCCCBBCBBCBCCBBCCBCBBCCCCBCBCBCCCBCCBCCCCCC True: 00010111 True: 0000100110101111 True: aabacadbbcbdccdd True: 0001002003004005006007008009011012013014015016017018019021022023024025026027028029031032033034035036037038039041042043044045046047048049051052053054055056057058059061062063064065066067068069071072073074075076077078079081082083084085086087088089091092093094095096097098099111211311411511611711811912212312412512612712812913213313413513613713813914214314414514614714814915215315415515615715815916216316416516616716816917217317417517617717817918218318418518618718818919219319419519619719819922232242252262272282292332342352362372382392432442452462472482492532542552562572582592632642652662672682692732742752762772782792832842852862872882892932942952962972982993334335336337338339344345346347348349354355356357358359364365366367368369374375376377378379384385386387388389394395396397398399444544644744844945545645745845946546646746846947547647747847948548648748848949549649749849955565575585595665675685695765775785795865875885895965975985996667668669677678679687688689697698699777877978878979879988898999 True: 9998997996995994993992991990988987986985984983982981980978977976975974973972971970968967966965964963962961960958957956955954953952951950948947946945944943942941940938937936935934933932931930928927926925924923922921920918917916915914913912911910908907906905904903902901900888788688588488388288188087787687587487387287187086786686586486386286186085785685585485385285185084784684584484384284184083783683583483383283183082782682582482382282182081781681581481381281181080780680580480380280180077767757747737727717707667657647637627617607567557547537527517507467457447437427417407367357347337327317307267257247237227217207167157147137127117107067057047037027017006665664663662661660655654653652651650645644643642641640635634633632631630625624623622621620615614613612611610605604603602601600555455355255155054454354254154053453353253153052452352252152051451351251151050450350250150044434424414404334324314304234224214204134124114104034024014003332331330322321320312311310302301300222122021121020120011101000 ``` --- See also: [One Ring to rule them all. One String to contain them all](https://codegolf.stackexchange.com/a/172936/80745) [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` f=lambda a,n:(a[:n]in a[1:])*a[n:]or max((f(c+a,n)for c in{*a}),key=len) ``` [Try it online!](https://tio.run/##Pcq7DkAwFADQ3Vd0ay8dCFMTAz6j6XA9Gg2uRgxEfHt1sp4cf5/zTmUItl5x60dkKEkJ1IqMI4a6UAZS1KTMfrANLyGsGLKYwEYYmKMnxRfkMt31OhEEfzg6Y@JN23FZAiS/FDmXFUD4AA "Python 3 โ€“ Try It Online") ]
[Question] [ This challenge is to write fast code that can perform a computationally difficult infinite sum. **Input** An `n` by `n` matrix `P` with integer entries that are smaller than `100` in absolute value. When testing I am happy to provide input to your code in any sensible format your code wants. The default will be one line per row of the matrix, space separated and provided on standard input. `P` will be [positive definite](https://en.wikipedia.org/wiki/Positive-definite_matrix) which implies it will always be symmetric. Other than that you don't really need to know what positive definite means to answer the challenge. It does however mean that there will actually be an answer to the sum defined below. You do however need to know what a [matrix-vector product](https://www.youtube.com/watch?v=Awcj447pYuk) is. **Output** Your code should compute the infinite sum: > > [![enter image description here](https://i.stack.imgur.com/q4hqV.gif)](https://i.stack.imgur.com/q4hqV.gif) > > > to within plus or minus 0.0001 of the correct answer. Here `Z` is the set of integers and so `Z^n` is all possible vectors with `n` integer elements and `e` is the [famous mathematical constant](https://en.wikipedia.org/wiki/E_(mathematical_constant)) that approximately equals 2.71828. Note that the value in the exponent is simply a number. See below for an explicit example. **How does this relate to the Riemann Theta function?** In the notation of this paper on [approximating the Riemann Theta function](http://page.math.tu-berlin.de/~bobenko/papers/2003_Bob_DHvHS.pdf) we are trying to compute [![enter image description here](https://i.stack.imgur.com/fegP6.png)](https://i.stack.imgur.com/fegP6.png). Our problem is a special case for at least two reasons. * We set the initial parameter called `z` in the linked paper to 0. * We create the matrix `P` in such a way that the minimum size of an eigenvalue is `1`. (See below for how the matrix is created.) **Examples** ``` P = [[ 5., 2., 0., 0.], [ 2., 5., 2., -2.], [ 0., 2., 5., 0.], [ 0., -2., 0., 5.]] Output: 1.07551411208 ``` In more detail, let us see just one term in the sum for this P. Take for example just one term in the sum: [![enter image description here](https://i.stack.imgur.com/pFOEs.gif)](https://i.stack.imgur.com/pFOEs.gif) and `x^T P x = 30`. Notice that`e^(-30)` is about `10^(-14)` and so is unlikely to be important for getting the correct answer up to the given tolerance. Recall that the infinite sum will actually use every possible vector of length 4 where the elements are integers. I just picked one to give an explicit example. ``` P = [[ 5., 2., 2., 2.], [ 2., 5., 4., 4.], [ 2., 4., 5., 4.], [ 2., 4., 4., 5.]] Output = 1.91841190706 P = [[ 6., -3., 3., -3., 3.], [-3., 6., -5., 5., -5.], [ 3., -5., 6., -5., 5.], [-3., 5., -5., 6., -5.], [ 3., -5., 5., -5., 6.]] Output = 2.87091065342 P = [[6., -1., -3., 1., 3., -1., -3., 1., 3.], [-1., 6., -1., -5., 1., 5., -1., -5., 1.], [-3., -1., 6., 1., -5., -1., 5., 1., -5.], [1., -5., 1., 6., -1., -5., 1., 5., -1.], [3., 1., -5., -1., 6., 1., -5., -1., 5.], [-1., 5., -1., -5., 1., 6., -1., -5., 1.], [-3., -1., 5., 1., -5., -1., 6., 1., -5.], [1., -5., 1., 5., -1., -5., 1., 6., -1.], [3., 1., -5., -1., 5., 1., -5., -1., 6.]] Output: 8.1443647932 P = [[ 7., 2., 0., 0., 6., 2., 0., 0., 6.], [ 2., 7., 0., 0., 2., 6., 0., 0., 2.], [ 0., 0., 7., -2., 0., 0., 6., -2., 0.], [ 0., 0., -2., 7., 0., 0., -2., 6., 0.], [ 6., 2., 0., 0., 7., 2., 0., 0., 6.], [ 2., 6., 0., 0., 2., 7., 0., 0., 2.], [ 0., 0., 6., -2., 0., 0., 7., -2., 0.], [ 0., 0., -2., 6., 0., 0., -2., 7., 0.], [ 6., 2., 0., 0., 6., 2., 0., 0., 7.]] Output = 3.80639191181 ``` **Score** I will test your code on randomly chosen matrices P of increasing size. Your score is simply the largest `n` for which I get a correct answer in less than 30 seconds when averaged over 5 runs with randomly chosen matrices `P` of that size. **What about a tie?** If there is a tie, the winner will be the one whose code runs fastest averaged over 5 runs. In the event that those times are also equal, the winner is the first answer. **How will the random input be created?** 1. Let M be a random m by n matrix with m<=n and entries which are -1 or 1. In Python/numpy `M = np.random.choice([0,1], size = (m,n))*2-1` . In practice I will set `m` to be about `n/2`. 2. Let P be the identity matrix + M^T M. In Python/numpy `P =np.identity(n)+np.dot(M.T,M)`. We are now guaranteed that `P` is positive definite and the entries are in a suitable range. Note that this means that all eigenvalues of P are at least 1, making the problem potentially easier than the general problem of approximating the Riemann Theta function. **Languages and libraries** You can use any language or library you like. However, for the purposes of scoring I will run your code on my machine so please provide clear instructions for how to run it on Ubuntu. **My Machine** The timings will be run on my machine. This is a standard Ubuntu install on an 8GB AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. --- **Leading answers** * `n = 47` in **C++** by Ton Hospel * `n = 8` in **Python** by Maltysen [Answer] # C++ No more naive approach. Only evaluate inside the ellipsoid. Uses the armadillo, ntl, gsl and pthread libraries. Install using ``` apt-get install libarmadillo-dev libntl-dev libgsl-dev ``` Compile the program using something like: ``` g++ -Wall -std=c++11 -O3 -fno-math-errno -funsafe-math-optimizations -ffast-math -fno-signed-zeros -fno-trapping-math -fomit-frame-pointer -march=native -s infinity.cpp -larmadillo -lntl -lgsl -lpthread -o infinity ``` On some systems you may need to add `-lgslcblas` after `-lgsl`. Run with the size of the matrix followed by the elements on STDIN: ``` ./infinity < matrix.txt ``` `matrix.txt`: ``` 4 5 2 0 0 2 5 2 -2 0 2 5 0 0 -2 0 5 ``` Or to try a precision of 1e-5: ``` ./infinity -p 1e-5 < matrix.txt ``` `infinity.cpp`: ``` // Based on http://arxiv.org/abs/nlin/0206009 #include <iostream> #include <vector> #include <stdexcept> #include <cstdlib> #include <cmath> #include <string> #include <thread> #include <future> #include <chrono> using namespace std; #include <getopt.h> #include <armadillo> using namespace arma; #include <NTL/mat_ZZ.h> #include <NTL/LLL.h> using namespace NTL; #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_roots.h> double const EPSILON = 1e-4; // default precision double const GROW = 2; // By how much we grow the ellipsoid volume double const UPSCALE = 1e9; // lattice reduction, upscale real to integer double const THREAD_SEC = 0.1; // Use threads if need more time than this double const RADIUS_MAX = 1e6; // Maximum radius used in root finding double const RADIUS_INTERVAL = 1e-6; // precision of target radius int const ITER_MAX = 1000; // Maximum iterations in root finding unsigned long POINTS_MIN = 1000; // Minimum points before getting fancy struct Result { Result& operator+=(Result const& add) { sum += add.sum; elapsed += add.elapsed; points += add.points; return *this; } friend Result operator-(Result const& left, Result const& right) { return Result{left.sum - right.sum, left.elapsed - right.elapsed, left.points - right.points}; } double sum, elapsed; unsigned long points; }; struct Params { double half_rho, half_N, epsilon; }; double fill_factor_error(double r, void *void_params) { auto params = static_cast<Params*>(void_params); r -= params->half_rho; return gsl_sf_gamma_inc(params->half_N, r*r) - params->epsilon; } // Calculate radius needed for target precision double radius(int N, double rho, double lat_det, double epsilon) { Params params; params.half_rho = rho / 2.; params.half_N = N / 2.; params.epsilon = epsilon*lat_det*gsl_sf_gamma(params.half_N)/pow(M_PI, params.half_N); // Calculate minimum allowed radius auto r = sqrt(params.half_N)+params.half_rho; auto val = fill_factor_error(r, &params); cout << "Minimum R=" << r << " -> " << val << endl; if (val > 0) { // The minimum radius is not good enough. Work out a better one by // finding the root of a tricky function auto low = r; auto high = RADIUS_MAX * 2 * params.half_rho; auto val = fill_factor_error(high, &params); if (val >= 0) throw(logic_error("huge RADIUS_MAX is still not big enough")); gsl_function F; F.function = fill_factor_error; F.params = &params; auto T = gsl_root_fsolver_brent; auto s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, low, high); int status = GSL_CONTINUE; for (auto iter=1; status == GSL_CONTINUE && iter <= ITER_MAX; ++iter) { gsl_root_fsolver_iterate (s); low = gsl_root_fsolver_x_lower (s); high = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval(low, high, 0, RADIUS_INTERVAL * 2 * params.half_rho); } r = gsl_root_fsolver_root(s); gsl_root_fsolver_free(s); if (status == GSL_CONTINUE) throw(logic_error("Search for R did not converge")); } return r; } // Recursively walk down the ellipsoids in each dimension void ellipsoid(int d, mat const& A, double const* InvD, mat& Accu, Result& result, double r2) { auto r = sqrt(r2); auto offset = Accu(d, d); // InvD[d] = 1/ A(d, d) auto from = ceil((-r-offset) * InvD[d]); auto to = floor((r-offset) * InvD[d]); for (auto v = from; v <= to; ++v) { auto value = v * A(d, d)+offset; auto residu = r2 - value*value; if (d == 0) { result.sum += exp(residu); ++result.points; } else { for (auto i=0; i<d; ++i) Accu(d-1, i) = Accu(d, i) + v * A(d, i); ellipsoid(d-1, A, InvD, Accu, result, residu); } } } // Specialised version of ellipsoid() that will only process points an octant void ellipsoid(int d, mat const& A, double const* InvD, mat& Accu, Result& result, double r2, unsigned int octant) { auto r = sqrt(r2); auto offset = Accu(d, d); // InvD[d] = 1/ A(d, d) long from = ceil((-r-offset) * InvD[d]); long to = floor((r-offset) * InvD[d]); auto points = to-from+1; auto base = from + points/2; if (points & 1) { auto value = base * A(d, d) + offset; auto residu = r2 - value * value; if (d == 0) { if ((octant & (octant - 1)) == 0) { result.sum += exp(residu); ++result.points; } } else { for (auto i=0; i<d; ++i) Accu(d-1, i) = Accu(d, i) + base * A(d, i); ellipsoid(d-1, A, InvD, Accu, result, residu, octant); } ++base; } if ((octant & 1) == 0) { to = from + points / 2 - 1; base = from; } octant /= 2; for (auto v = base; v <= to; ++v) { auto value = v * A(d,d)+offset; auto residu = r2 - value*value; if (d == 0) { if ((octant & (octant - 1)) == 0) { result.sum += exp(residu); ++result.points; } } else { for (auto i=0; i<d; ++i) Accu(d-1, i) = Accu(d, i) + v * A(d, i); if (octant == 1) ellipsoid(d-1, A, InvD, Accu, result, residu); else ellipsoid(d-1, A, InvD, Accu, result, residu, octant); } } } // Prepare call to ellipsoid() Result sym_ellipsoid(int N, mat const& A, const vector<double>& InvD, double r, unsigned int octant = 1) { auto start = chrono::steady_clock::now(); auto r2 = r*r; mat Accu(N, N); Accu.row(N-1).zeros(); Result result{0, 0, 0}; // 2*octant+1 forces the points into the upper half plane, skipping 0 // This way we use the lattice symmetry and calculate only half the points ellipsoid(N-1, A, &InvD[0], Accu, result, r2, 2*octant+1); // Compensate for the extra factor exp(r*r) we always add in ellipsoid() result.sum /= exp(r2); auto end = chrono::steady_clock::now(); result.elapsed = chrono::duration<double>{end-start}.count(); return result; } // Prepare multithreaded use of sym_ellipsoid(). Each thread gets 1 octant Result sym_ellipsoid_t(int N, mat const& A, const vector<double>& InvD, double r, unsigned int nr_threads) { nr_threads = pow(2, ceil(log2(nr_threads))); vector<future<Result>> results; for (auto i=nr_threads+1; i<2*nr_threads; ++i) results.emplace_back(async(launch::async, sym_ellipsoid, N, ref(A), ref(InvD), r, i)); auto result = sym_ellipsoid(N, A, InvD, r, nr_threads); for (auto i=0U; i<nr_threads-1; ++i) result += results[i].get(); return result; } int main(int argc, char* const* argv) { cin.exceptions(ios::failbit | ios::badbit); cout.precision(12); double epsilon = EPSILON; // Target absolute error bool inv_modular = true; // Use modular transform to get the best matrix bool lat_reduce = true; // Use lattice reduction to align the ellipsoid bool conservative = false; // Use provable error bound instead of a guess bool eigen_values = false; // Show eigenvalues int threads_max = thread::hardware_concurrency(); int option_char; while ((option_char = getopt(argc, argv, "p:n:MRce")) != EOF) switch (option_char) { case 'p': epsilon = atof(optarg); break; case 'n': threads_max = atoi(optarg); break; case 'M': inv_modular = false; break; case 'R': lat_reduce = false; break; case 'c': conservative = true; break; case 'e': eigen_values = true; break; default: cerr << "usage: " << argv[0] << " [-p epsilon] [-n threads] [-M] [-R] [-e] [-c]" << endl; exit(EXIT_FAILURE); } if (optind < argc) { cerr << "Unexpected argument" << endl; exit(EXIT_FAILURE); } if (threads_max < 1) threads_max = 1; threads_max = pow(2, ceil(log2(threads_max))); cout << "Using up to " << threads_max << " threads" << endl; int N; cin >> N; mat P(N, N); for (auto& v: P) cin >> v; if (eigen_values) { vec eigval = eig_sym(P); cout << "Eigenvalues:\n" << eigval << endl; } // Decompose P = A * A.t() mat A = chol(P, "lower"); // Calculate lattice determinant double lat_det = 1; for (auto i=0; i<N; ++i) { if (A(i,i) <= 0) throw(logic_error("Diagonal not Positive")); lat_det *= A(i,i); } cout << "Lattice determinant=" << lat_det << endl; auto factor = lat_det / pow(M_PI, N/2.0); if (inv_modular && factor < 1) { epsilon *= factor; cout << "Lattice determinant is small. Using inverse instead. Factor=" << factor << endl; P = M_PI * M_PI * inv(P); A = chol(P, "lower"); // We could simple calculate the new lat_det as pow(M_PI,N)/lat_det lat_det = 1; for (auto i=0; i<N; ++i) { if (A(i,i) <= 0) throw(logic_error("Diagonal not Positive")); lat_det *= A(i,i); } cout << "New lattice determinant=" << lat_det << endl; } else factor = 1; // Prepare for lattice reduction. // Since the library works on integer lattices we will scale up our matrix double min = INFINITY; for (auto i=0; i<N; ++i) { for (auto j=0; j<N;++j) if (A(i,j) != 0 && abs(A(i,j) < min)) min = abs(A(i,j)); } auto upscale = UPSCALE/min; mat_ZZ a; a.SetDims(N,N); for (auto i=0; i<N; ++i) for (auto j=0; j<N;++j) a[i][j] = to_ZZ(A(i,j)*upscale); // Finally do the actual lattice reduction mat_ZZ u; auto rank = G_BKZ_FP(a, u); if (rank != N) throw(logic_error("Matrix is singular")); mat U(N,N); for (auto i=0; i<N;++i) for (auto j=0; j<N;++j) U(i,j) = to_double(u[i][j]); // There should now be a short lattice vector at row 0 ZZ sum = to_ZZ(0); for (auto j=0; j<N;++j) sum += a[0][j]*a[0][j]; auto rho = sqrt(to_double(sum))/upscale; cout << "Rho=" << rho << " (integer square " << rho*rho << " ~ " << static_cast<int>(rho*rho+0.5) << ")" << endl; // Lattice reduction doesn't gain us anything conceptually. // The same number of points is evaluated for the same exponential values // However working through the ellipsoid dimensions from large lattice // base vectors to small makes ellipsoid() a *lot* faster if (lat_reduce) { mat B = U * A; P = B * B.t(); A = chol(P, "lower"); if (eigen_values) { vec eigval = eig_sym(P); cout << "New eigenvalues:\n" << eigval << endl; } } vector<double> InvD(N);; for (auto i=0; i<N; ++i) InvD[i] = 1 / A(i, i); // Calculate radius needed for target precision auto r = radius(N, rho, lat_det, epsilon); cout << "Safe R=" << r << endl; auto nr_threads = threads_max; Result result; if (conservative) { // Walk all points inside the ellipsoid with transformed radius r result = sym_ellipsoid_t(N, A, InvD, r, nr_threads); } else { // First grow the radius until we saw POINTS_MIN points or reach the // target radius double i = floor(N * log2(r/rho) / log2(GROW)); if (i < 0) i = 0; auto R = r * pow(GROW, -i/N); cout << "Initial R=" << R << endl; result = sym_ellipsoid_t(N, A, InvD, R, nr_threads); nr_threads = result.elapsed < THREAD_SEC ? 1 : threads_max; auto max_new_points = result.points; while (--i >= 0 && result.points < POINTS_MIN) { R = r * pow(GROW, -i/N); auto change = result; result = sym_ellipsoid_t(N, A, InvD, R, nr_threads); nr_threads = result.elapsed < THREAD_SEC ? 1 : threads_max; change = result - change; if (change.points > max_new_points) max_new_points = change.points; } // Now we have enough points that it's worth bothering to use threads while (--i >= 0) { R = r * pow(GROW, -i/N); auto change = result; result = sym_ellipsoid_t(N, A, InvD, R, nr_threads); nr_threads = result.elapsed < THREAD_SEC ? 1 : threads_max; change = result - change; // This is probably too crude and might misestimate the error // I've never seen it fail though if (change.points > max_new_points) { max_new_points = change.points; if (change.sum < epsilon/2) break; } } cout << "Final R=" << R << endl; } // We calculated half the points and skipped 0. result.sum = 2*result.sum+1; // Modular transform factor result.sum /= factor; // Report result cout << "Evaluated " << result.points << " points\n" << "Sum = " << result.sum << endl; } ``` [Answer] # Python 3 **12 secs n=8 on my computer, ubuntu 4 core.** Really naive, have no clue what I'm doing. ``` from itertools import product from math import e P = [[ 6., -3., 3., -3., 3.], [-3., 6., -5., 5., -5.], [ 3., -5., 6., -5., 5.], [-3., 5., -5., 6., -5.], [ 3., -5., 5., -5., 6.]] N = 2 n = [1] while e** -n[-1] > 0.0001: n = [] for x in product(list(range(-N, N+1)), repeat = len(P)): n.append(sum(k[0] * k[1] for k in zip([sum(j[0] * j[1] for j in zip(i, x)) for i in P], x))) N += 1 print(sum(e** -i for i in n)) ``` This will keep on increasing the range of `Z` that it uses until it gets a good enough answer. I wrote my own matrix multiplication, prolly should use numpy. [Answer] # Python, numpy **one example program using `numpy` is as follows**. Really naive, have no clue what I'm doing. ``` import numpy as np from itertools import product from math import e from time import time n=9 is_randomized=False if is_randomized: m = n // 2 M = np.random.choice([0, 1], size=(m, n)) * 2 - 1 P = np.identity(n) + np.dot(M.T, M) print(P) else: if n==4: P = [[5., 2., 2., 2.], [2., 5., 4., 4.], [2., 4., 5., 4.], [2., 4., 4., 5.]] P = np.array(P) print(P) elif n==5: P = np.array([[6., -3., 3., -3., 3.], [-3., 6., -5., 5., -5.], [3., -5., 6., -5., 5.], [-3., 5., -5., 6., -5.], [3., -5., 5., -5., 6.]]) P = np.array(P) print(P) elif n==9: P = [[7., 2., 0., 0., 6., 2., 0., 0., 6.], [2., 7., 0., 0., 2., 6., 0., 0., 2.], [0., 0., 7., -2., 0., 0., 6., -2., 0.], [0., 0., -2., 7., 0., 0., -2., 6., 0.], [6., 2., 0., 0., 7., 2., 0., 0., 6.], [2., 6., 0., 0., 2., 7., 0., 0., 2.], [0., 0., 6., -2., 0., 0., 7., -2., 0.], [0., 0., -2., 6., 0., 0., -2., 7., 0.], [6., 2., 0., 0., 6., 2., 0., 0., 7.]] P = np.array(P) print(P) # estimate how much N should be chosen? based on matrix P or size n ? if n==9: N = 2 elif n==5: N = 4 elif n==4: N = 5 else: N = 3 n_list = [] start_time=time() for x in product(range(-N, N+1), repeat=len(P)): x = np.array(x) summand = np.dot(np.dot(x, P), x.T) n_list.append(summand) result = sum(e**-i for i in n_list) print(result) print(f"duration: {time()-start_time}") ``` 8 secs, n=9 on my computer. ]
[Question] [ # [Pronouncing Hex](http://www.bzarg.com/p/how-to-pronounce-hexadecimal/) For those of you uninitiated with the show Silicon Valley, this challenge is inspired by an exchange that goes like this ([YouTube](https://www.youtube.com/watch?v=_zTpwNR5Bf4)): ``` Kid - Here it is: Bitโ€ฆ soup. Itโ€™s like alphabet soup, BUTโ€ฆ itโ€™s ones and zeros instead of letters. Erlich Bachman - {silence} Kid - โ€˜Cause itโ€™s binary? You know, binaryโ€™s just ones and zeroes. Erlich Bachman - Yeah, I know what binary is. Jesus Christ, I memorized the hexadecimal times tables when I was fourteen writing machine code. Okay? Ask me what nine times F is. Itโ€™s fleventy-five. I donโ€™t need you to tell me what binary is. ``` It should be noted that technically, `0x9 * 0xF = 0x87`, not 'fleventy-five', but this brings up an important question - how would you actually pronounce hex in conversation? It's not like `oh ex eff eff` flows off the tongue easily, so what should we do? Here's a handy pronunciation chart we will follow. ``` A = ay A0 = atta- B = bee B0 = bibbity- C = cee C0 = city- D = dee D0 = dickety- E = ee E0 = ebbity- F = eff F0 = fleventy- ``` We can split a 4-length hex number into two groups of two, and determine the pronunciation from the table above, as well as common English pronunciation for numbers. So, for the example `0xFFAB`, we would get `Fleventy-eff bitey atta-bee`. If a number is included, such as `0xF5AB`, you would print `Fleventy-five bitey atta-bee`. Also, if a number starts one of the groups, you should use it's "tens" pronunciation. For example, `0x5FAA` would become `Fifty-eff bitey atta-ay`. In the case where you have something like `0x1FAC`, this would be `Effteen bitey atta-cee`. But, if this rule were to be used for `0x1AF4`, `a-teen` could be confused for `eighteen`, so you must prepend a Y. So, the correct output would be `Yayteen bitey fleventy-four` In the case of `0xD0F4`, instead of doing `Dickety-zero bitey fleventy-four`, we would ignore the zero and print `Dickety-bitey fleventy-four`. Hyphens should only appear within the groups of two, i.e. bitey should not be connected to either group with a hyphen unless the first group is only one word! So `0x04F4` would be `four-bitey fleventy-four`, but `0x44F4` would be `forty-four bitey fleventy-four`. As *trichoplax* said, bitey should only be hyphened when following a round number. For a comprehensive look at how this will work, check out the example I/O below. # Objective Create a *program or function* that will take a hexadecimal string as **input or a function argument** and produce it's pronunciation. The output must have proper capitalization. You may assume that the length of this number will always be 4. # Example I/O ``` "0xFFFF" -> "Fleventy-eff bitey fleventy-eff" "0x0000" -> "Zero" "0x0010" -> "Ten" "0x0100" -> "One-bitey zero" "0x1110" -> "Eleven-bitey ten" "0xBEEF" -> "Bibbity-ee bitey ebbity-eff" "0x9999" -> "Ninety-nine bitey ninety-nine" "0xA1B2" -> "Atta-one bitey bibbity-two" "0x3C4F" -> "Thirty-cee bitey forty-eff" "0x17AB" -> "Seventeen-bitey atta-bee" "0x1AFB" -> "Yayteen-bitey fleventy-bee" "0xAAAA" -> "Atta-ay bitey atta-ay" ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins. [Answer] # Pyth - 312 293 286 251 bytes Time to start reducing the data, more coming. Holy biggest Pyth program I've ever written! There is still huge compression possible with the data, both algortihimically and base conversion, but just wanted to put this up. ``` Kcs@LGjC"qNjร†ร‰รฝ(7lรคQยซI?sfรงร‚ร˜^รรปรผยป u$รรƒoรณ}Qร›รฃยดHfยฎ?Nรขยฒ-YรœZร”7ร‚รพรฆX#\"รฅร˜"26\q=+K>K11J.e?+?bnb\|@K+16k"ty"-kTbc" twen | for | | | | | atta bibbi ci dicke ebbi fleven"d.srj"bitey "m?++@Kd?k<d18"teen"\-<d32+j\-@V,JKfT.Dd16\ ?Gh=G.DQ256tG4\- ``` I interpret input as hex literal through Q which it automatically detect with the `0x`. Then I divmod it 256 into the bytes, and remove the first byte if its zero, then map it through two arrays, one for `0-1F` and then `20-F0`. The second one gets a divmod through the first array also. The first option gets a hypen at the end, and the second get a hyphen at the middle and a space at the end. Join by `"bitey "`, capitalize with range, and strip hyphens with `.s` and we're good. The base compression part is also interesting because I first started out with basic 128 -> 256 conversion. But now, what I am doing is using `"q"` as the separator instead of space. Thus I can now consider the string as a base 26 string with `xLG`, improving compression tremendously. [Try it here online](http://pyth.herokuapp.com/?code=Kcs%40LGjC%22%1E%0Eq%16Nj%C3%86%0B%C3%89%C3%BD(7l%C3%A4Q%C2%ABI%3Fsf%10%C2%8F%03%C3%A7%C3%82%C3%98%5E%C3%90%C3%BB%C3%BC%08%C2%BB%C2%98%09%C2%83%08u%24%C3%90%C3%83o%C3%B3%7D%0EQ%C3%9B%01%C3%A3%C2%B4Hf%C2%AE%C2%8A%C2%94%3FN%C3%A2%C2%B2-%C2%9AY%C3%9C%C2%9EZ%C3%947%C3%82%C3%BE%C3%A6X%23%1D%5C%22%C3%A5%C3%98%2226%5Cq%3D%2BK%3EK11J.e%3F%2B%3Fbnb%5C%7C%40K%2B16k%22ty%22-kTbc%22++twen+%7C+for+%7C+%7C+%7C+%7C+%7C+atta+bibbi+ci+dicke+ebbi+fleven%22d.srj%22bitey+%22m%3F%2B%2B%40Kd%3Fk%3Cd18%22teen%22%5C-%3Cd32%2Bj%5C-%40V%2CJKfT.Dd16%5C+%3FGh%3DG.DQ256tG4%5C-&input=0x1AFB&debug=1). [Test suite](http://pyth.herokuapp.com/?code=Kcs%40LGjC%22%1E%0Eq%16Nj%C3%86%0B%C3%89%C3%BD(7l%C3%A4Q%C2%ABI%3Fsf%10%C2%8F%03%C3%A7%C3%82%C3%98%5E%C3%90%C3%BB%C3%BC%08%C2%BB%C2%98%09%C2%83%08u%24%C3%90%C3%83o%C3%B3%7D%0EQ%C3%9B%01%C3%A3%C2%B4Hf%C2%AE%C2%8A%C2%94%3FN%C3%A2%C2%B2-%C2%9AY%C3%9C%C2%9EZ%C3%947%C3%82%C3%BE%C3%A6X%23%1D%5C%22%C3%A5%C3%98%2226%5Cq%3D%2BK%3EK11J.e%3F%2B%3Fbnb%5C%7C%40K%2B16k%22ty%22-kTbc%22++twen+%7C+for+%7C+%7C+%7C+%7C+%7C+atta+bibbi+ci+dicke+ebbi+fleven%22dV.Q.srj%22bitey+%22m%3F%2B%2B%40Kd%3Fk%3Cd18%22teen%22%5C-%3Cd32%2Bj%5C-%40V%2CJKfT.Dd16%5C+%3FGh%3DG.DN256tG4%5C-&input=0xFFFF%0A0x0000%0A0x0010%0A0x0100%0A0x1110%0A0xBEEF%0A0x9999%0A0xA1B2%0A0x3C4F%0A0x17AB%0A0x1AFB%0A0xAAAA&debug=0). [Answer] ## Java - 856 bytes Not short but at least the second answer ;) It's a method called `String p(String n)` which will do the job: ``` String p(String n){String[]b={"","ten","twen","thir","for","fif","six","seven","eigh","nine", "atta","bibbi","ci","dicke","ebbi","fleven"};String[]s={"zero","one","two","three","four", "five","six","seven","eight","nine","ay","bee","cee","dee","ee","eff"};String[]t={"ten", "eleven","twelve","thir","four","fif","six","seven","eigh","nine","yay","bee","cee","dee", "ee","eff"};int w=Byte.valueOf(n.substring(2,3),16);int x=Byte.valueOf(n.substring(3,4),16); int y=Byte.valueOf(n.substring(4,5),16);int z=Byte.valueOf(n.substring(5,6),16);String r=(w== 1?t[x]+(x>2?"teen":""):((w==0?"":b[w]+(w>1&&w!=10?"ty":"")+"-")+(w==0&&x==0?"":s[x])))+((w==0 &&x>0||w==1&&x<3||w>0&&x==0)?"-":w==0&&x==0?"":" ")+(w>0||x>0?"bitey ":"")+(y==1?t[z]+(z>2? "teen":""):((y==0?"":b[y]+(y>1&&y!=10?"ty":"")+"-")+(y>1&&z!=0||y==0?s[z]:"")));return (char) (r.charAt(0)-32)+r.substring(1);} ``` [Answer] ## Javascript - 577 719 bytes ``` function h(e){for(e=e.match(/.{1,2}/g),r="",i=1;i<e.length;i++)j=parseInt("0x"+e[i]),0!=j?r+=c(parseInt("0x"+e[i]))+"bitey ":i>1?r+="zero-bitey":0;return r=""==r?"Zero":r[0].toUpperCase()+r.substr(1,r.length-7),null!==r[r.length-1].match(/[-\s]$/g)?r=r.substr(0,r.length-1):0,r}function c(e){return d=["zero","one","two","three","four","five","six","seven","eight","nine","ay","bee","cee","dee","ee","eff","ten","eleven","twelve","thir","four","fif","six","seven","eigh","nine","yay","bee","cee","dee","ee","eff"],p=["twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety","atta","bibbity","city","dickety","ebbity","fleventy"],1>e?"":e>31?p[Math.floor(e/16)-2]+"-"+d[e%16]+" ":17>e?d[e]+"-":d[e]+"teen-"} ``` I'm sure there are improvements to be made. Added bonus, it parses arbitrary length hex strings. EDIT: Whoops, it doesn't work right when there are leading zeros. Hm. EDIT 2: Fixed, I think. [JSFiddle](https://jsfiddle.net/82zyc8ne/) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 4 years ago. [Improve this question](/posts/19163/edit) # 9-hole mini-golf: Description * 9 (mostly fairly easy) code golfing challenges of varying difficulty * Penalties for using the same language more than once * All challenges about a specific theme (this theme: Text Manipulation) * Input and output can be anywhere reasonable (i.e. STDIN and STDOUT, reading from/writing to a file, function argument and return value, etc.) but must NOT be hardcoded into the program * Heavily inspired by [9 Hole Challenge](https://codegolf.stackexchange.com/q/16707/3808) and [Text Mechanic](http://textmechanic.com/) # Holes 1. ## Code-golf bag Take two strings as input. Output the first string's character count, while ignoring any occurence of any character in the second string. Example: `f("foobarbaz", "ao")` => `5` 2. ## A pre-text for golfing Take two strings as input. Output the first string, with every line prefixed with the second. Example: `f("foo\nbar\nbaz", "a")` => `"a foo\na bar\na baz"` 3. ## War of tabs vs spaces Take a string `s`, a number `n`, and a boolean `b` (specified however you want) as input. If `b` is true, output `s` with every tab converted to `n` spaces. Else, output the `s` with every `n` spaces converted to tabs. Example: `f("if (x) {\n\tdoStuff();\n}", 4, true)` => `"if (x) {\n[sp][sp][sp][sp]doStuff();\n}"` (`[sp]` means space) 4. ## Pillars of golf Take a string `s`, a number `n`, and another number `m` as input. Output `s` in columns of `n` lines each and `m` characters per column. Also have padding of one space between the columns. Example: `f("this is some placeholder text, foo bar baz...", 3, 5)` => ``` this aceho foo is so lder bar b me pl text, az... ``` 5. ## Friendly letters Take a string `s` and a number `n` as input. Output the most common group of `n` letters in `s`. If there is a tie, output any or all of them. Example: `f("abcdeabcfghiabc", 3)` => `"abc"` 6. ## Scrambled ~~eggs~~ letters for breakfast Take a string as input. Output the string with all of its words scrambled (letter order randomized) except their first and last letters. For simplicity, assume that the input will be a list of "word"s, space separated (i.e. in `@$&_():;" foo bar`, `@$&_():;"` is considered a "word.") Example: `f("this is a sentence that will be scrambled")` => `"tihs is a stcneene that wlil be sclamrbed"` 7. ## ASCIIfy Take a string as input. If the string only contains numbers and spaces, then replace the numbers with their respective ASCII characters (removing the spaces). Else, do the reverse (characters to numbers). Example: `f("ASCIIfy challenge")` => `"65 83 67 73 73 102 121 32 99 104 97 108 108 101 110 103 101"` Example 2: `f("65 83 67 73 73 102 121 32 99 104 97 108 108 101 110 103 101")` => `"ASCIIfy challenge"` 8. ## Mini-mini-markdown transformation Take a string as input. Output the string converted with mini-markdown, as used in comments on Stack Exchange. This is an even mini-er version: you only need to handle `**bold**`, `*italics*`, and ``code``. You need not handle invalid nesting, like `**foo *bar** baz*`. Also assume that when you see a delimiter (`*` or ```), it will *always* mean to format (i.e. `te**st**ing` => `te<b>st</b>ing`, and `foo* bar *baz` => `foo<i> bar </i>baz`). Example: `f("**foo** *bar **baz*** `qux`")` => `"<b>foo</b> <i>bar <b>baz</b></i> <code>qux</code>"` 9. ## Only the best characters Take a string `s`, number `n`, and string `r` as input. Output the `n`th character of each word in `s`. (0-indexed, words are space-separated). If the length of the word is less than `n`, use `r` for that word instead. Example: `f("this is a test sentence foo bar baz", 2, "-")` => `"i--snorz"` # Scoring Your score is the sum of the character counts of your programs. For every repeated language, multiply by 110%. For example, if you have three Ruby solutions, and the total character count of all of your solutions is 1000, your score is 1000 \* 1.1 \* 1.1 = 1210. Round down if you have a non-integer score. # Good luck! [Answer] # Score: 382 \* 1.12 = 462 Languages prone to change. ## 1. APL, ~~8~~ 4 Thanks @marinus for shaving 4 chars off. ``` fโ†โด~ ``` Called with the strings as the left and right arguments, eg. ``` 'foobarbaz' f 'ao' 5 ``` ## 2. Ruby, ~~35~~ 31 Thanks @DoorknobofSnow for shaving 4 chars off. ``` f=->s,r{s.gsub(/(?<=^)/,r+' ')} ``` ## 3. Python, 48 ``` f=lambda s,n,b:s.replace(*['\t',' '*n][::2*b-1]) ``` ## 4. GolfScript, 20 ``` {@//zip{' '*}%n*}:f; ``` Assumes that the arguments are on the stack. [Test online](http://golfscript.apphb.com/?c=e0AvL3ppcHsnICcqfSVuKn06ZjsKInRoaXMgaXMgc29tZSBwbGFjZWhvbGRlciB0ZXh0LCBmb28gYmFyIGJhei4uLiIgMyA1IGY%3D) ## 5. J, 50 ``` f=:({~[:(i.>./)+/"1@=@(}.~0-1{$))@|:@([$~],1+[:$[) ``` Called with the string as the left argument and the number as the right, eg. ``` 'abcdeabcfghiabc' f 3 abc ``` ## 6. Ruby, 61 ``` f=->s{s.gsub(/(?<!^| )[^ ]+(?!$| )/){[*$&.chars].shuffle*''}} ``` ## 7. GolfScript, ~~39~~ ~~35~~ 34 ``` {[.10,' '*-{{}/]' '*}{~]''+}if}:f; ``` Again, assumes the argument is on the stack. [Test online](http://golfscript.apphb.com/?c=e1suMTAsJyAnKi17e30vXScgJyp9e35dJycrfWlmfTpmOwpbIkFTQ0lJZnkgY2hhbGxlbmdlIiAiNjUgODMgNjcgNzMgNzMgMTAyIDEyMSAzMiA5OSAxMDQgOTcgMTA4IDEwOCAxMDEgMTEwIDEwMyAxMDEiXXtmIHB1dHN9Lw%3D%3D) ## 8. Perl, 98 ``` sub f{$_=@_[0];s!\*\*(.+?)\*\*!<b>$1</b>!g;s!\*(.+?)\*!<i>$1</i>!g;s!`(.+?)`!<code>$1</code>!g;$_} ``` ## 9. Haskell, 36 ``` f s n r=[(x++cycle r)!!n|x<-words s] ``` [Answer] ## Python - 697 ร— 1.19 โ‰ˆ 1644 Gee, I sure love lambdas. **Note**: 3 and 5 were shamelessly copied from [Volatility's answer](/a/19168/14202), as I couldn't find a better alternative. Also, this was done *just for fun*. ``` f=lambda a,b:sum([x not in b for x in a]) # 1, 41 chars f=lambda a,b:b+' '+a.replace('\n','\n'+b+' ') # 2, 43 chars f=lambda s,n,b:s.replace(*['\t',' '*n][::b*2-1]) # 3, 47 chars f=lambda s,n,m:'\n'.join([' '.join([s[x:x+m]for x in range(y*m,len(s),m*n)])for y in range(n)]) # 4, 94 chars f=lambda s,n:max([s[x:x+n]for x in range(len(s)+1-n)],key=s.count) # 5, 66 chars import random;f=lambda s:' '.join([''.join(sorted(y,key=lambda*x:random.random()))for y in s.split()]) # 6, 102 chars f=lambda s:s.replace(' ','').isdigit()and ''.join(map(chr,map(int,s.split())))or ' '.join(map(str,map(ord,s))) # 7, 110 chars import re;f=lambda s:re.sub('`(.*?)`','<code>\\1</code>',re.sub(r'\*(.*?)\*','<i>\\1</i>',re.sub(r'\*\*(.*?)\*\*','<b>\\1</b>',s))) # 8, 128 chars f=lambda s,n,r:''.join([len(x)>n and x[n]or r for x in s.split()]) # 9, 66 chars ``` **EDIT**: Thanks to Volatility for the tips. [Answer] # Score 513 \* 1.15 = 826 Took quite a beating by the same-language penalty. Solved most of these in Ruby just to finish them as fast as I could. Might change some languages later. Added a small recap/explanation on each answer. # 1: Python (46) ``` f=lambda a,b:len([x for x in a if not x in b]) ``` First, shorter answer in **Ruby 2.0 (30)** that gives more penalty and higher overall score: ``` p (gets.chars-gets.chars).size ``` # 2: Ruby 1.9+ (37) Returns each line of `s` prefixed with `t`: ``` f=->s,t{s.split(?\n).map{|x|t+x}*?\n} ``` # 3: Ruby 1.9+ (48) Returns `s` with tabs replaced by `n` spaces or vice versa, depending on `b`: ``` f=->s,n,b{r=[" "*n,?\t];b||r.reverse!;s.gsub *r} ``` # 4: Ruby 1.9+ (95) Somebody shoot me. ``` f=->s,n,m{[*s.chars.each_slice(m).map{|w|w*''}.each_slice(s.size/m/n)].transpose.map{|w|w*' '}} ``` # 5: Ruby 1.9+ (58) Returns most common run of `n` characters in `s`: ``` f=->s,n{(a=s.chars.each_slice(n)).max_by{|v|a.count v}*''} ``` # 6: J (47) Scrambles the text somehow; Shamelessly stolen verbatim from [marinus](https://codegolf.stackexchange.com/a/9263/4372): ``` ''[1!:2&4('\w(\w+)\w';,1)({~?~@#)rxapply 1!:1[3 ``` # 7: Ruby (57+1) Prints input ASCIIfied or de-ASCIIfied. Run with the `-p` switch. ``` ~/\d/?gsub(/\d+\s*/){$&.to_i.chr}:gsub(/./){"#{$&.ord} "} ``` # 8: Sed (87) Prints input converted from (mini)markdown to HTML: ``` s:\*\*([^*]+)\*\*:<b>\1</b>:g; s:\*([^*]+)\*:<i>\1</i>:g; s:`([^`]+)`:<code>\1</code>:g ``` # 9 Ruby 1.9+ (37) Returns a string of the `n`th characters of each first word in `s`, or `r`: ``` f=->s,n,r{s.split.map{|w|w[n]||r}*''} ``` [Answer] Work in progress ## 1. Java - 66 ``` int f(String s,String b){for(char c:b)s=s.replace(b,"");return s;} ``` ## 2. Java - 64 ``` String f(String i,String r){return i.replaceAll("(?m)^",r+" ");} ``` ## 3. Python - 58 ``` def f(s,n,b):t=" "*n;a=t,'\t';print s.replace(a[b],a[b^1]) ``` ## 4. Python - 84 ``` def f(s,n,m): a=['']*n;c=0 while s:a[c%n]+=s[:m]+" ";s=s[m:];c+=1 for i in a:print i ``` ## 5. ## 6. ## 7. Befunge 98 - 9 ``` &,5j3.~@# ``` ## 8. ## 9. ]
[Question] [ The 15 Puzzle is a famous puzzle involving sliding 15 tiles around on a 4x4 grid. Starting from a random configuration, the goal is to arrange the tiles in the correct order. Here is an example of a solved 15 Puzzle: ``` 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 ``` Each move on the puzzle is of the form Up/Down/Left/Right. The move "Down" consists of sliding the tile that is above the empty spot downward. The move "Right" consists of sliding a tile to the right, into the empty spot. Here is how the board looks after the moves Down and Right. ``` 01 02 03 04 05 06 07 08 09 10 11 13 14 15 12 ``` --- The goal of this challenge is to write a program that can output the series of moves needed to solve the 15 Puzzle. The winner is the program who solves the five test cases (below) in the fewest total moves. The generated solution does not need to be a perfect solution, it merely has to be better than the competitors. For each individual test case, the program should not take more than ten seconds on a reasonable machine. Your program must be able to solve any puzzle that is solvable, I'm just using these five test cases as the scoring. Your program will receive the unsolved 15 Puzzle as input in the format of a 2D array. The 2D array can be formatted according to the language used, or changed if the language does not have 2D arrays. The first element of the first sub-array will be the number in the upper left, and the last element of the first sub-array will be the number in the upper right. A `0` will be the empty space. As output, your program should print a list of moves in the order that they need to be performed. Each step should be numbered in order to increase the usability of the results. EDIT: Based on comments, I will allow output to be in either the form of Down/Up/etc or in the form of the coordinates of the piece to move. As this is not code golf, the most important part is to solve the puzzle. Some other general rules involve no using an outside source, etc. --- Test Case 1 ``` ([5,1,7,3],[9,2,11,4],[13,6,15,8],[0,10,14,12]) ``` Example Output: ``` 1: Down 2: Down 3: Down 4: Left .... ``` Test Case 2 ``` ([2,5,13,12],[1,0,3,15],[9,7,14,6],[10,11,8,4]) ``` Test Case 3 ``` ([5,2,4,8],[10,0,3,14],[13,6,11,12],[1,15,9,7]) ``` Test Case 4 ``` ([11,4,12,2],[5,10,3,15],[14,1,6,7],[0,9,8,13]) ``` Test Case 5 ``` ([5,8,7,11],[1,6,12,2],[9,0,13,10],[14,3,4,15]) ``` [Answer] # PyPy, 195 moves, ~12 seconds computation Computes optimal solutions using IDA\* with a 'walking distance' heuristic augmented with linear conflicts. Here are the optimal solutions: ``` 5 1 7 3 9 2 11 4 13 6 15 8 0 10 14 12 Down, Down, Down, Left, Up, Up, Up, Left, Down, Down, Down, Left, Up, Up, Up 2 5 13 12 1 0 3 15 9 7 14 6 10 11 8 4 Left, Down, Right, Up, Up, Left, Down, Down, Right, Up, Left, Left, Down, Right, Right, Right, Up, Up, Left, Left, Down, Left, Up, Up, Right, Down, Down, Left, Up, Up, Right, Right, Right, Down, Left, Up, Right, Down, Down, Left, Left, Down, Left, Up, Up, Right, Up, Left 5 2 4 8 10 0 3 14 13 6 11 12 1 15 9 7 Left, Up, Up, Right, Right, Down, Left, Up, Left, Left, Down, Down, Right, Right, Up, Left, Left, Down, Down, Right, Right, Up, Right, Up, Left, Left, Up, Right, Down, Down, Right, Down, Left, Left, Up, Up, Left, Up 11 4 12 2 5 10 3 15 14 1 6 7 0 9 8 13 Down, Left, Down, Right, Up, Left, Left, Left, Down, Down, Right, Right, Right, Up, Left, Left, Left, Down, Right, Right, Up, Left, Up, Up, Left, Down, Down, Right, Down, Right, Up, Up, Right, Up, Left, Left, Left, Down, Right, Right, Right, Up, Left, Down, Left, Down, Left, Up, Up 5 8 7 11 1 6 12 2 9 0 13 10 14 3 4 15 Up, Right, Down, Left, Left, Down, Left, Up, Right, Up, Right, Down, Down, Right, Up, Up, Left, Left, Left, Down, Down, Down, Right, Right, Up, Right, Down, Left, Up, Left, Up, Left, Down, Right, Down, Left, Up, Right, Down, Right, Up, Up, Left, Left, Up ``` And the code: ``` import random class IDAStar: def __init__(self, h, neighbours): """ Iterative-deepening A* search. h(n) is the heuristic that gives the cost between node n and the goal node. It must be admissable, meaning that h(n) MUST NEVER OVERSTIMATE the true cost. Underestimating is fine. neighbours(n) is an iterable giving a pair (cost, node, descr) for each node neighbouring n IN ASCENDING ORDER OF COST. descr is not used in the computation but can be used to efficiently store information about the path edges (e.g. up/left/right/down for grids). """ self.h = h self.neighbours = neighbours self.FOUND = object() def solve(self, root, is_goal, max_cost=None): """ Returns the shortest path between the root and a given goal, as well as the total cost. If the cost exceeds a given max_cost, the function returns None. If you do not give a maximum cost the solver will never return for unsolvable instances.""" self.is_goal = is_goal self.path = [root] self.is_in_path = {root} self.path_descrs = [] self.nodes_evaluated = 0 bound = self.h(root) while True: t = self._search(0, bound) if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated if t is None: return None bound = t def _search(self, g, bound): self.nodes_evaluated += 1 node = self.path[-1] f = g + self.h(node) if f > bound: return f if self.is_goal(node): return self.FOUND m = None # Lower bound on cost. for cost, n, descr in self.neighbours(node): if n in self.is_in_path: continue self.path.append(n) self.is_in_path.add(n) self.path_descrs.append(descr) t = self._search(g + cost, bound) if t == self.FOUND: return self.FOUND if m is None or (t is not None and t < m): m = t self.path.pop() self.path_descrs.pop() self.is_in_path.remove(n) return m def slide_solved_state(n): return tuple(i % (n*n) for i in range(1, n*n+1)) def slide_randomize(p, neighbours): for _ in range(len(p) ** 2): _, p, _ = random.choice(list(neighbours(p))) return p def slide_neighbours(n): movelist = [] for gap in range(n*n): x, y = gap % n, gap // n moves = [] if x > 0: moves.append(-1) # Move the gap left. if x < n-1: moves.append(+1) # Move the gap right. if y > 0: moves.append(-n) # Move the gap up. if y < n-1: moves.append(+n) # Move the gap down. movelist.append(moves) def neighbours(p): gap = p.index(0) l = list(p) for m in movelist[gap]: l[gap] = l[gap + m] l[gap + m] = 0 yield (1, tuple(l), (l[gap], m)) l[gap + m] = l[gap] l[gap] = 0 return neighbours def slide_print(p): n = int(round(len(p) ** 0.5)) l = len(str(n*n)) for i in range(0, len(p), n): print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n])) def encode_cfg(cfg, n): r = 0 b = n.bit_length() for i in range(len(cfg)): r |= cfg[i] << (b*i) return r def gen_wd_table(n): goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)] goal[-1][-1] = n - 1 goal = tuple(sum(goal, [])) table = {} to_visit = [(goal, 0, n-1)] while to_visit: cfg, cost, e = to_visit.pop(0) enccfg = encode_cfg(cfg, n) if enccfg in table: continue table[enccfg] = cost for d in [-1, 1]: if 0 <= e + d < n: for c in range(n): if cfg[n*(e+d) + c] > 0: ncfg = list(cfg) ncfg[n*(e+d) + c] -= 1 ncfg[n*e + c] += 1 to_visit.append((tuple(ncfg), cost + 1, e+d)) return table def slide_wd(n, goal): wd = gen_wd_table(n) goals = {i : goal.index(i) for i in goal} b = n.bit_length() def h(p): ht = 0 # Walking distance between rows. vt = 0 # Walking distance between columns. d = 0 for i, c in enumerate(p): if c == 0: continue g = goals[c] xi, yi = i % n, i // n xg, yg = g % n, g // n ht += 1 << (b*(n*yi+yg)) vt += 1 << (b*(n*xi+xg)) if yg == yi: for k in range(i + 1, i - i%n + n): # Until end of row. if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g: d += 2 if xg == xi: for k in range(i + n, n * n, n): # Until end of column. if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g: d += 2 d += wd[ht] + wd[vt] return d return h if __name__ == "__main__": solved_state = slide_solved_state(4) neighbours = slide_neighbours(4) is_goal = lambda p: p == solved_state tests = [ (5,1,7,3,9,2,11,4,13,6,15,8,0,10,14,12), (2,5,13,12,1,0,3,15,9,7,14,6,10,11,8,4), (5,2,4,8,10,0,3,14,13,6,11,12,1,15,9,7), (11,4,12,2,5,10,3,15,14,1,6,7,0,9,8,13), (5,8,7,11,1,6,12,2,9,0,13,10,14,3,4,15), ] slide_solver = IDAStar(slide_wd(4, solved_state), neighbours) for p in tests: path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80) slide_print(p) print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves)) print(cost, num_eval) ``` [Answer] # JavaScript (ES6) total steps 329 for all 5 test cases in ~1min **Edit** Same strategy, different targets, better solution. Slower ... This is more or less how I solve it by hand: using intermediate targets After each target the relative tiles are not moved again Each intermediate target is reached using a parametric BSF function. The 2 params are the loop condition L (repeat while true) and the select condition S (select what tile can be moved). The steps: 1. Place 1 top/left 2. Place 2 3. Place 5 4. Place 3,4 - top row ok 5. Place 9,13 - left column ok 6. All the rest *Side note* I don't check the position of tiles 14 and 15. Unsolvable puzzles like `[11,4,12,2,,15,10,3,5,,14,1,6,7,,0,9,8,13]` will have 14 and 15 swapped. ``` F=b=>( s=[], [[_=>b[0]!=1, (o,p)=>b[o+p]] ,[_=>b[1]!=2, (o,p)=>(p=b[o+p])>1&&p] ,[_=>b[5]!=5, (o,p)=>(p=b[o+p])>2&&p] ,[_=>b[2]!=3|b[3]!=4, (o,p)=>(p=b[o+p])>2&&p!=5&&p] ,[_=>b[10]!=9|b[15]!=13, (o,p)=>(p=b[o+p])>5&&p] ,[_=>b[6]!=6|b[7]!=7|b[8]!=8|b[11]!=10|b[12]!=11|b[13]!=12|b[18]!=0, (o,p)=>(p=b[o+p])>5&&p!=9&&p!=13&&p] ].forEach(([L,S])=>{ for(v={},v[b]=1,t=0,m=[];L();) { b.forEach((x,p)=> x=='0'&&[-1,5,1,-5].forEach((o,d)=> (x=S(o,p))&&(c=b.slice(0),c[p]=x,c[o+p]=0,v[k=''+c]?0:v[k]=m.push([c,s.concat(d)])) ) );[b,s]=m[t++] } }), ,s.map((d,i)=>i+': '+'RULD'[d]).join('\n') // multi line output // ,s.map(d=>'RULD'[d]).join(' ') // single line output (easier to test) ) ``` Open snippet to test or play (Firefox only) ``` F=b=>( s=[], [[_=>b[0]!=1, (o,p)=>b[o+p]] ,[_=>b[1]!=2, (o,p)=>(p=b[o+p])>1&&p] ,[_=>b[5]!=5, (o,p)=>(p=b[o+p])>2&&p] ,[_=>b[2]!=3|b[3]!=4, (o,p)=>(p=b[o+p])>2&&p!=5&&p] ,[_=>b[10]!=9|b[15]!=13, (o,p)=>(p=b[o+p])>5&&p] ,[_=>b[6]!=6|b[7]!=7|b[8]!=8|b[11]!=10|b[12]!=11|b[13]!=12|b[18]!=0, (o,p)=>(p=b[o+p])>5&&p!=9&&p!=13&&p] ].forEach(([L,S])=>{ for(v={},v[b]=1,t=0,m=[];L();) { b.forEach((x,p)=> x=='0'&&[-1,5,1,-5].forEach((o,d)=> (x=S(o,p))&&(c=b.slice(0),c[p]=x,c[o+p]=0,v[k=''+c]?0:v[k]=m.push([c,s.concat(d)])) ) );[b,s]=m[t++] } }), //,s.map((d,i)=>i+': '+'RULD'[d]).join('\n') // multi line output //,s.map(d=>'RULD'[d]).join(' ') // single line output (easier to test) s ) B.value=PZ.value,show() function show(s='') { var b = eval(B.value) var t = b.map((c,i)=>'<td>'+c+'</td>').join() .replace(/,,/g,'</tr><tr>').replace(/,/g,'') G.innerHTML='<tr>'+t+'</tr>' S.value=s } function solve() { show('... solving ...') var b = eval(B.value) setTimeout(_=>{ var s = F(b), zp = b.indexOf(0), sp = 0 S.value=s.map(d=>'RULD'[d]).join(' '); (A=_=>{ d=[-1,5,1,-5][m=s[sp++]] b[zp]=b[zp+d],zp+=d,b[zp]=0 var t = b.map((c,i)=>'<td>'+c+'</td>').join() .replace(/,,/g,'</tr><tr>').replace(/,/g,'') G.innerHTML='<tr>'+t+'</tr>' if (sp<s.length) setTimeout(A, 300); })() },100) } ``` ``` #D { position: relative } #D input { position: absolute; width: 300px; top:2px; left:2px; border:0 none } #D select { position: relative; width: 400px; height:1.8em; top:0; left:0; } textarea{ width: 600px; height: 40px } td{ width: 1.5em; text-align:right } ``` ``` Puzzles (select or edit) <div id=D> <select id=PZ onchange="B.value=PZ.value,show()"> <option>[5,1,7,3,,9,2,11,4,,13,6,15,8,,0,10,14,12]</option> <option>[2,5,13,12,,1,0,3,15,,9,7,14,6,,10,11,8,4]</option> <option>[5,2,4,8,,10,0,3,14,,13,6,11,12,,1,15,9,7]</option> <option>[11,4,12,2,,5,10,3,15,,14,1,6,7,,0,9,8,13]</option> <option>[5,8,7,11,,1,6,12,2,,9,0,13,10,,14,3,4,15]</option> </select> <button onclick="solve()">Solve</button> <input id=B> </div> <textarea id=S></textarea> <table id=G></table> ``` **Test suite** In Firefox/FireBug console ``` T=~new Date ;[[5,1,7,3,,9,2,11,4,,13,6,15,8,,0,10,14,12] ,[2,5,13,12,,1,0,3,15,,9,7,14,6,,10,11,8,4] ,[5,2,4,8,,10,0,3,14,,13,6,11,12,,1,15,9,7] ,[11,4,12,2,,5,10,3,15,,14,1,6,7,,0,9,8,13] ,[5,8,7,11,,1,6,12,2,,9,0,13,10,,14,3,4,15]] .forEach(t=>console.log(t+'',F(t))) console.log('Time ms ',T-=~new Date) ``` *Output* ``` "5,1,7,3,,9,2,11,4,,13,6,15,8,,0,10,14,12" "D D D L U L D L U R R U U L D D L U U" "2,5,13,12,,1,0,3,15,,9,7,14,6,,10,11,8,4" "D R U L U L L U R D L D R D L U R U L D R D L U R U L U R R R D L L U R D R U L L D L D R U U L D R U R D L U L D D R R U L U L D R U L" "5,2,4,8,,10,0,3,14,,13,6,11,12,,1,15,9,7" "R U U L D D R U L D D R U U L L D D R U L D L U U R R D L U R R D L L U L D D R U U L D D R U U U R R D L L U R R D L L L U R D D L U R D R U U L L D R D L U U" "11,4,12,2,,5,10,3,15,,14,1,6,7,,0,9,8,13" "D L D R U L D D R U L L D L U R R D L U R U R D L U R U L L D R D L L D R U U L D R D L U R U U L D R R U L D R R U L L D L D R U U L D R R D L L U U R D R U L L" "5,8,7,11,,1,6,12,2,,9,0,13,10,,14,3,4,15" "D D R U L L L D R U R D L U U R R D L U L U R D D L U U L D D D R U U L D D R U U U R D R U L D D L U U R D R U L D L L D R U L U R D L D R R U L L U R D D L U U" "Time ms " 62234 ``` [Answer] I started working on this problem and wanted to contribute with my code so far. As stated by Gareth, the problem is comparable to the 8-tile puzzle and so the code is based on the magnificient solution of Keith Randall and thus in Python. This solution can solve all 5 test cases with a total sum of less than 400 moves, and other puzzles, too. It contains an optimized and a brute force solution. The code is a bit bloated by now. Output is abbrevated like "llururd.." Hope its helpful. <http://www.penschuck.org/joomla/tmp/15Tile.txt> (explanation) <http://www.penschuck.org/joomla/tmp/tile15.txt> (python code) ``` # Author: Heiko Penschuck # www.penschuck.org # (C) 2012 # import os;os.chdir('work') # os.getcwd() # def execfile(file, globals=globals(), locals=locals()): # with open(file, "r") as fh: exec(fh.read()+"\n", globals, locals) # # # execfile("tile15.py"); # ## run these # solve_brute(); # solve(); # some boards to play with board2=(15,14,7,3,13,10,2,9,11,12,4,6,5,0,1,8); # best: 76(52) # 72(56) # 68(51) uurddlurrulldrrdllluuruldrddlururulddruurdllldrurddlurdruuldrdluurdd board3=(13, 8, 9, 4, 15, 11, 5, 3, 14, 6, 12, 7, 1, 10, 2, 0) # best: 106(77) #best: 90(64) ullldruuldrrdrlluurulldrrdldluruulddrulurrdrddlluuurdldrrulddrulldrurullldrdluurrrddllurdr board4=(4, 8, 12, 1, 13, 7, 3, 11, 9, 15, 6, 14, 5, 2, 10, 0) ;# best 100(74) board5=(15,2,3,4,5,6,7,8,9,10,11,12,13,1,14,0); # best 44(32) board6=( 1, 2, 3, 4, 6, 11, 0, 12, 8, 14, 9, 13, 5, 10, 7, 15); # testcases board7=(5,1,7,3,9,2,11,4,13,6,15,8,0,10,14,12); # 15 (7) board8=(2,5,13,12,1,0,3,15,9,7,14,6,10,11,8,4); # 124 (94) board9=(5,2,4,8,10,0,3,14,13,6,11,12,1,15,9,7) ; # 72 (56) board10=(11,4,12,2,5,10,3,15,14,1,6,7,0,9,8,13) ;# 71 (57) board11=(5,8,7,11,1,6,12,2,9,0,13,10,14,3,4,15) ;# 99 (73) board12=(1,2,3,4,5,6,7,8,9,10,11,12,13,0,14,15); #pretty simple board board13=(4, 10, 5, 12, 11, 7, 15, 2, 13, 1, 14, 8, 6, 3, 9, 0) board=board3 ; # used by solve() bboard=list(board) ;# used by solve_brute() # init clean=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0) i=0; solution={}; invsolution={}; E={board:0} # derived from Keith Randall 8-tile solution # a: a board, d: offset to move from i: index in board def Y(a,d,i): b=list(a); # b is now an indexable board b[i],b[i+d]=b[i+d],0; # make a move (up down left right) b=tuple(b); # now back to searchable if b not in E:E[b]=a;# store new board in E def Calc(): ii=0; # memory error when x is 21 for x in ' '*14: if ii>10: print(ii); ii+=1 for a in E.copy(): # for all boards, make possible moves (up,left,right,down) and store the new boards i=list(a).index(0) if i>3:Y(a,-4,i) if i%4:Y(a,-1,i) if i%4 <3:Y(a,1,i) if i<12:Y(a,4,i) def weigh(a,goal): factor=[26,8,4,6, 8,8,4,4, 4,4,1,1, 3,2,1,0] weight=0; for element in a: i=list(a).index(element); ix,iy=divmod(i,4); # ist if element == 0: # special for gap weight=weight+ix; #weight+=(ix+iy) continue; i=list(a).index(element); ix,iy=divmod(i,4); # ist j=list(goal).index(element); sx,sy=divmod(j,4); # soll #k=list(a).index(0); # gap #kx,ky=divmod(k,4) # try solving from topleft to bottom right (because clean board has gap at bottomright) tmp= abs(sx-ix)*abs(sx-ix)*factor[j]+ abs(sy-iy)*abs(sy-iy)*factor[j] #tmp += ((sx!=ix )& (sy!=iy)) *(4-sx)*(4-sy)*4 weight+=tmp #(10-sx-sy-sy) # 8*abs(sx-ix) + (16-j)*(sx!=ix) #print('%2d %2d_%2d (%2d_%2d)=> %d'%(element,i,j,(sx-ix),(sy-iy),weight)) return weight # read numbers seperated by a whitespace def readboard(): global E,D,board,clean,i reset() g=[] for x in' '*4:g+=map(int,input().split()) board=tuple(g) # read 'a' till 'o' def readasciiboard(): global E,D,board,clean,i trans={"0":0,"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15} reset() g=[] vec=tuple(input().split()); for x in vec: g.append(trans[x]) board=tuple(g) def printasciiboard(a): trans={"0":0,"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15} itrans={} for x in trans: itrans[trans[x]]=x g=[] for x in a: g.append(itrans[x]) for i in(0,4,8,12): print('%s %s %s %s'%tuple(g[i:i+4])) # find the board with the smallest weight def minimum(): global minn,E,clean minn=1111111;# start with a huge number qq=board for q in E: if weigh(q,clean) < minn: minn=weigh(q,clean) qq=q return qq # run this and printsolution() # (you might have to reverse the order of the printed solution) def solve(): global start,board,E,clean,minn,solution start=board; solution={}; E={ board:0 } for x in range(0,11): Calc(); # walks all possible moves starting from board to a depth of 10~20 moves if clean in E: print('Solution found') q=clean; tmp=[]; while q: tmp.append(q) q=E[q] for x in reversed(tmp): solution[len(solution)]=x; printsolution(); return q=minimum(); # calculates the "weight" for all Calc()-ed boards and returns the minimum #print("Len %3d"%len(E)) print("weight %d"%minn) # stitch solution newboard=q; tmp=[]; while q: tmp.append(q) q=E[q] for x in reversed(tmp): solution[len(solution)]=x; board=newboard; E={board:0}; #reset the Calc()-ed boards print("No Solution") # collects and prints the moves of the solution # from clean board to given board # (you have to reverse the order) def printsolution(): global invsolution,solution,moves,clean,start moves="" g=start; # start from board to clean y=g #invsolution[clean]=0; for x in solution: # uncomment this if you want to see each board of the solution #print(g); g=solution[x]; #sys.stdout.write(transition(y,g)) if (transition(g,y)=="E"): continue moves+=transition(g,y) # or as squares #print('%10s %d %s'%("step",len(moves),transition(g,y))); #print(" %s -- %s "%(y,g)) #for i in(0,4,8,12): print('%2d %2d %2d %2d'%g[i:i+4]) y=g llen=len(moves) print(" moves%3d "%llen) print(moves) # processing moves. funny, but occysionally ud,du,lr or rl appears due to the stitching while 'lr' in moves: a,b,c=moves.partition('lr') moves=a+c llen-=2 while 'rl' in moves: a,b,c=moves.partition('rl') moves=a+c llen-=2 while 'ud' in moves: a,b,c=moves.partition('ud') moves=a+c llen-=2 while 'du' in moves: a,b,c=moves.partition('du') moves=a+c llen-=2 # processing moves. concatenating lll to 3l while 'lll' in moves: a,b,c=moves.partition('lll') moves=a+' 3l '+c llen-=2 while 'rrr' in moves: a,b,c=moves.partition('rrr') moves=a+' 3r '+c llen-=2 while 'uuu' in moves: a,b,c=moves.partition('uuu') moves=a+' 3u '+c llen-=2 while 'ddd' in moves: a,b,c=moves.partition('ddd') moves=a+' 3d '+c llen-=2 while 'll' in moves: a,b,c=moves.partition('ll') moves=a+' 2l '+c llen-=1 while 'rr' in moves: a,b,c=moves.partition('rr') moves=a+' 2r '+c llen-=1 while 'uu' in moves: a,b,c=moves.partition('uu') moves=a+' 2u '+c llen-=1 while 'dd' in moves: a,b,c=moves.partition('dd') moves=a+' 2d '+c llen-=1 print(" processed:%3d "%llen) print(moves) return def transition(a,b): # calculate the move (ie up,down,left,right) # between 2 boards (distance of 1 move and a weight of 1 only) i=list(a).index(0); j=list(b).index(0); if (j==i+1): return "l" if (j==i-1): return "r" if (j==i-4): return "d" if (j==i+4): return "u" #print("transition not possible") return "E" ################################################### # below this line are functions for the brute force solution only # added for comparision # # its using a global variable bboard and works destructively on it def solve_brute(): global bboard,board; bboard=list(board); # working copy move(1,0);move(2,1); move(3,14); # <== additional move, move 3 out of way move(4,2);move(3,6); gap_down();gap_down();gap_right();gap_right();gap_up();gap_up();gap_up();gap_left();gap_down(); #first line solved print("first line");printbboard(); move(5,4);move(6,5);move(7,14);move(8,6);move(7,10); gap_down();gap_down();gap_right();gap_right();gap_up();gap_up();gap_left();gap_down(); #second line solved (upper half) print("2nd line");printbboard(); move(9,15);move(13,8);move(9,9) gap_down();gap_left();gap_left();gap_up();gap_right(); print("left border");printbboard(); #left border solved move(10,15);move(14,9);move(10,10); gap_down();movegap(1+3*4);gap_up();gap_right(); print("left half");printbboard(); #left half solved #rotating last 4 tiles 5 times for x in ' '*5: gap_right();gap_down(); # gap is now on 15 if (bboard==[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0]): print("solution found");printbboard(); return; gap_left();gap_up(); print("No solution found"); printbboard(); return def printbboard(): global bboard for i in(0,4,8,12): print('%2d %2d %2d %2d'%tuple(bboard[i:i+4])) def gap_up(): global bboard i=bboard.index(0); if (i<4): print("Err up()") return bboard[i],bboard[i-4] = bboard[i-4] , 0 ; def gap_down(): global bboard i=bboard.index(0); if (i>11): print("Err down()") return bboard[i],bboard[i+4] = bboard[i+4] , 0 ; def gap_left(): global bboard i=bboard.index(0); if (i%4<1): print("Err left()") return bboard[i],bboard[i-1]= bboard[i-1] , 0 ; def gap_right(): global bboard i=bboard.index(0); if (i%4>2): print("Err right()") return bboard[i],bboard[i+1] = bboard[i+1] , 0 ; def movegap(d): global bboard; # d: destination location (0-15) k=bboard.index(0); ky,kx=divmod(k,4); dy,dx=divmod(d,4); # moving the gap while (ky>dy): gap_up();ky-=1; while (ky<dy): gap_down();ky+=1; while (kx>dx): gap_left();kx-=1; while (kx<dx): gap_right();kx+=1; def move(s,d): global bboard i=bboard.index(s); iy,ix=divmod(i,4); dy,dx=divmod(d,4); #moving a number while (ix<dx): move1right(s); print("1right "); ix+=1; while (ix>dx): move1left(s); ix-=1; print("1left "); while(iy<dy): move1down(s); print("1down "); iy+=1; while(iy>dy): move1up(s); print("1up"); iy-=1; def move1up(s): global bboard i=bboard.index(s); iy,ix=divmod(i,4); k=bboard.index(0); ky,kx=divmod(k,4); if (ky<iy): # above: move 1 above, then leftorright, then 1 down movegap(kx+4*(iy-1)) movegap(ix+4*(iy-1)) movegap(ix+4*iy) return; # fin if (ky==iy): # if equal, then first try 1 down # (not nescessary if gap is right of s) if (kx<ix): if (ky<=2): movegap(kx+4*(iy+1)) movegap(ix+1+4*(iy+1)); # 1right 1down of s movegap(ix+1+4*(iy-1)); # 1right 1up of s movegap(ix+4*(iy-1));# right over s gap_down(); # fin return; # bottom border, must go up first movegap(kx+4*(iy-1)); movegap(ix+4*(iy-1)); gap_down(); return; # fin else: movegap(ix+1+4*iy); # move 1 right of s gap_up() gap_left() gap_down(); return; # fin movegap(ix+1+4*ky); # move 1 right of s movegap(ix+1+4*(iy+1)); # move 1 right and 1 down of s gap_up(); gap_up(); gap_left(); gap_down(); def move1left(s): global bboard i=bboard.index(s); iy,ix=divmod(i,4); k=bboard.index(0); ky,kx=divmod(k,4); if (ky<iy): # if above gap move 1 over s if (kx<ix): movegap(kx+4*iy); movegap(ix+4*iy); return;# fin if (kx==ix): #gap over s if (ix<3): # try to move under s and then left if (iy<3): movegap(ix+1+4*ky) movegap(ix+1+4*(iy+1)) movegap(ix-1+4*(iy+1)) movegap(ix-1+4*iy) movegap(ix+4*iy) return; #fin # have to move left movegap(kx-1+4*ky) movegap(ix-1+4*iy) movegap(ix+4*iy) return;# fin # move 1 right of s if (iy==3): # cant go under, have to go left over movegap(kx+4*(iy-1)) movegap(ix-1+4*(iy-1)) movegap(ix-1+4*iy) movegap(ix+4*iy); return; #fin movegap(ix+1+4*(iy-1)) gap_down();gap_down();gap_left();gap_left();gap_up();gap_right(); return; #fin if (ky==iy): if (kx<ix): movegap(ix-1+4*iy) gap_right(); return; # fin if (ky<3): gap_down(); ky+=1; else: #have to move up movegap(ix+4*(iy-1)) movegap(ix-1+4*(iy-1)) movegap(ix-1+4*iy) gap_right(); return; #fin # gap below s movegap(ix+4*(iy+1)); gap_left();gap_up();gap_right(); def move1right(s): global bboard i=bboard.index(s); iy,ix=divmod(i,4); k=bboard.index(0); ky,kx=divmod(k,4); if (ky<iy): if (kx==ix): movegap(kx+1+4*ky) movegap(kx+1+4*iy) movegap(ix+4*iy); return; #fin movegap(kx+4*iy) if (kx>ix): movegap(ix+4*iy); return; #fin movegap(kx+4*(iy+1)) movegap(ix+1+4*(iy+1)) movegap(ix+1+4*iy); movegap(ix+4*iy); return; #fin if (ky==iy): if (kx<ix): if (ky>2): # bottom row, left of s, have to move 1 up gap_up() # move 1 right 1 up of s movegap(ix+1+4*(ky-1)); gap_down() gap_left() return; # fin # first 1 down movegap(kx+4*(ky+1)) # to the right of s movegap(ix+1+4*(ky+1)) gap_up() gap_left() return; # fin # already 1 right of s movegap(ix+4*iy); return; #fin # move gap 1 right and 1 down of s movegap(kx+4*(iy+1)) movegap(ix+1+4*(iy+1)) gap_up(); gap_left(); def move1down(s): global bboard i=bboard.index(s); iy,ix=divmod(i,4); k=bboard.index(0); ky,kx=divmod(k,4); if (ky<iy): # gap is over s, move it below if (kx==ix): if (ix>2): # right border, have to move 1 to the left movegap(kx+4*(iy-1)) movegap(kx-1+4*(iy-1)) movegap(kx-1+4*(iy+1)) gap_up(); return; #fin # move right of s movegap(kx+4*(iy-1)) movegap(kx+1+4*(iy-1)) movegap(kx+1+4*(iy+1)) movegap(kx+4*(iy+1)) gap_up(); #fin movegap(kx+4*(iy+1)) movegap(ix+4*(iy+1)) gap_up(); #fin if (ky==iy): gap_down(); ky+=1; # gap is below s, move 1 under s movegap(ix+4*(iy+1)) gap_up(); #fin ``` ]
[Question] [ A classic example to introduce people to the concept of a discrete probability distribution is the [bean machine](https://en.wikipedia.org/wiki/Bean_machine). This machine has a large amount of marbles fall from a narrow passageway at the top, after which they hit rows of interlaced pins, where at each pin the marble hits it might fall to the left or the right of the pin. Finally, the pins are collected in vertical bins at the bottom of the machine. A simple diagram of this machine looks like this: ``` | O | | ^ | | ^ ^ | | ^ ^ ^ | | ^ ^ ^ ^ | | ^ ^ ^ ^ ^ | |_|_|_|_|_|_| ``` In this diagram, the `O` signifies the location from which the marbles fall. Each `^` is a pin at which the marble has a 50% chance to move to the square either to the left or the right of the pin. The marbles then gather at the bins on the bottom of the device, and for a large enough number of marbles, the height of the marble stacks in the bins will resemble a discrete binomial distribution. ### Challenge For this challenge, you will be calculating the resulting probability distribution of bean machines based on diagrams like the above one. The diagrams are interpreted as a two-dimensional 'program' that the marbles pass through, either towards fields at the side or fields below the current field. When the marbles reach the bottom of the machine they are counted for the probability distribution. To keep it interesting, these diagrams will contain a few more fields than just the simple source and pins. An example diagram is: ``` | O | | ^ | | ^ / | | ^ | ^ | | <^- = v | | ^ ^ ^ ^ ^ | ``` Furthermore, the marbles now each have a rotation direction. This direction is set by some fields and determines to which next field the marble moves in several other fields. The following fields are defined: * `O`: Source. Spawns marbles directly below it. The direction of these marbles is 50% left, 50% right. Each source produces the same amount of marbles. * `U`: Sink. Any marbles which enter this field are removed from the bean machine. * : Empty space. If a marble arrives at this field, it will move to the field below. * `-`: Floor. If a marble arrives at this field, it will move to either the field to the left or the field on the right, depending on its current direction. * `^`: Splitter. If a marble arrives at this field, it has a 50% of moving to the field to the right or the field to the left of the splitter. This also determines the direction of the marble. * `v`: Join. If a marble arrives at this field, it will move to the field below. * `/`: Slanted pad. If a marble arrives at this field, it will move to the field on the left of the pad, setting the direction of the marble. * `\`: Same as the previous, but to the right. * `|`: Reflector. If a marble arrives at this field, it will reverse the direction of the marble, and move the marble to the field to the right or the left, based on this reversed direction. * `=`: Cannon. If a marble arrives at this field, it will move it to the right or the left in the current direction, until the marble encounters a field that is not , `-` or `O`. * `<`: Same as the previous, but will always set the direction and move towards the left. * `>`: Same as the previous, but to the right. The following guarantees are given regarding the diagram. * Each input row will have exactly the same length in fields. * The leftmost and rightmost field of each row will always be a `|`. * The diagram will not contain any possible paths through which marbles can get stuck in the machine for an indeterminate amount of iterations, like `\/` or `^^`. * The diagram will only contain the above mentioned fields. * There are one or more sources ### Result Your task will be to generate an 16-line tall ASCII bar graph of the probability distribution in which the marbles exit the bottom side of the graph, scaled so the largest probability covers all 16 characters. So for the following problem: ``` | O | | ^ | | ^ ^ | | ^ ^ ^ | | ^ ^ ^ ^ | | ^ ^ ^ ^ ^ | ``` Your program should produce the following solution (note that it should have the same width as the input program, including the pipes to the side: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ``` ### Examples The following is an example that should test the functionality of all different field types: ``` | O O | | O ^ / <^\\\ | | ^ > ^ | | ^ ^ ^ =| | ^ ^ | ^ <^ O | | ^ > ^ | ^ O ^> v | || ^U ^ | = ^\ | | ^ ^ ^ ^U ^\ ---^ | | = ^ ^ = v | ``` It should result in the following output: ``` # # # # # # # # # # # # # # # # # # # # # # # # # # ## # # # ## # # # # # ### # # # # # # ### # # # # # # ### # # # # ``` ### Rules Both functions and full programs constitute valid answers for this challenge. You will receive the diagram as a newline-separated string, and you should return the output graph in the given format. [Default input/output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. While trailing and leading newlines are allowed in the output, each row should have exactly the same width as the input. As to allow more creative solutions, it is only required that your program outputs the correct result more than 90% of the time for the same diagram. It is a probability simulation after all. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), ~~431~~ ~~429~~ 410 bytes ``` def t(a):e=enumerate;p=a.split("\n");o=[0]*len(p[0]);{m(i,j,p,o,1):m(i,j,p,o,-1)for i,r in e(p)for j,c in e(r)if"O"==c};[print("".join(" #"[round(16*r/max(o)+i)>15]for r in o))for i in range(16)] def m(r,k,p,o,l,x=1): while r<len(p): c=p[r][k] if"^"==c:x/=2;m(r,k-l,p,o,l,x) if"U"==c:return if c in" vO":r+=1;continue l=[1,l,-1,l,-l,1][ord(c)%6];k-=l while";"<c<"?"and p[r][k]in" O-":k-=l o[k]+=x ``` [Try it online!](https://tio.run/##TU/BbuIwEL3zFaOpVrKLUzZdlUMS00/IqacklqJgtoZgR95AqUq/nfU4tGUsWzNv3jy/Gd7HV2f/XC5rvYGRtTzTUtvDXvt21Pkg24d/Q29GhrVFnjtZ/W7ue23ZEBKef@yZEVsxCCdSnv0USco3zoMR4VrQbIjlVnRT6bnZYIlSdp95NXhjgz4@bJ2xDOEOK@8Ods3S5b1f7NsTc3xu@Cp9akgkKjo@6VPuW/tXBzJvZrTDnnmxiyZ6cZLB1QzeXk2vwRfRNwHQyaHyTbVrQh6sKLKSnRbyMY/jSf8lwCfCSyR4PR68jQjQJgjHEjM/l2neOTsae9Ch2csqDaNJfHqRNpXza9bxX8sm3yWyD5RoCHMsugKfsbVruNohzTLBbOK5gMzl6TIyj4hnoChvXorz7BxLBQuAQtV1fYMTvIKbUFdcxXMTMuIEnqdGoaZvCCeRr0YJagXHiNPACw2FFsgoX8O3jqJmAJIkUVc/MipM/0Y@6YTN@OU/ "Python 3 โ€“ Try It Online") This answer is a collaborative effort between Wheat Wizard and CensoredUsername. For reference, [this](https://tio.run/##lVTBbuIwEL3zFVPvxSlOaboSh4rwC5x6IlgK1BCj4CAntLtS/p2dMQ5NQlq0jhQpb968eTO2c/xbZYX5fT6/qy1Uqqx4GryOANfRFjubHiCG9Kk85rriLDEscDGrylNelRhbPsO2sKBBmyZj@bxaOZYLCEshZU4HZdNKcU/yRRraXmy6NNsi0NJb2MQxW7AuTOuQ2nWueCS02AsvL7xDEQX/xw8xwWVkSu@yS4u2OJl3zqPpow0mh/QP9@QgcN5dgx5qNe7Q1Oyw0rTVzNFqg6NkT/tCG85@MWqNZ2MdwDyGaAoqLxUwfEglIxVvJUBntEvePzpfC7DFp4BNkYtm@qKxIiBX28pX/sx0rogMDzHiZmAbNnGzf0hbLVFzNepN/603fauqkzVXSOWeJ3u8luPJiyDLqD6OBod/Ny@M7m3yd7YmPVs0nzjqQKTfgq6pSTKUG94kj4eSw16uK0ICt9R6sEyH@5MCnhYGH/1LgoPr@irV4OWaDVwuKoJ3IBriz7/nh9Edv1@H8ubUuSYW4YB4V8bvvssZ0@Fdn90PzDLGasdftN606lHtPiVMAGYySZIWTvC8XU16XLqntWKHE1hfAjN5KUM4iTSBBcg5fDicEt4oCUM4H5JN4KojKYhAGIbS@4mdwqWu45MOdhac/wE) is the ungolfed algorithm. *-2 bytes from Mr. Xcoder* *-19 bytes from CensoredUsername* [Answer] # [Python 2](https://docs.python.org/2/), 731 bytes ``` i=raw_input l=i() c=[] while l:c,l=c+[l],i() p=[[0]*len(l)for l in c]+[[0]*max(map(len,c))] S=lambda r,C,p:r>=0and C>=0and r<len(p)and C<len(p[r]) def U(r,C,P,D,N=0): if S(r,C,p):p[r][C]+=P if S(r,C,c): K=c[r][C] if K in' O':U(r+1-N,C+D*N,P,D,N) elif'v'==K:U(r+1,C,P,D) elif'-'==K:U(r,C+D,P,D,N) elif'^'==K:U(r,C-1,P/2,-1);U(r,C+1,P/2,1) elif'/'==K:U(r,C-1,P,-1) elif'\\'==K:U(r,C+1,P,1) elif'='==K:U(r,C+D,P,D,1) elif'>'==K:U(r,C+1,P,1,1) elif'<'==K:U(r,C-1,P,-1,1) elif'|'==K:U(r,C-D,P,-D) for r in range(len(c)): for C in range(len(c[r])): if'O'==c[r][C]:U(r+1,C,1.,1);U(r+1,C,1.,-1) p=p[-1][::-1] s=16/max(p) f=['#'*min(int(n*s),16)+' '*min(int(16-n*s),16)for n in p] print('\n'.join(map(''.join,zip(*f)))[::-1]) ``` [Try it online!](https://tio.run/##ZZJNb6MwEIbP8a@wtAdjsJvQQw5snAu9RUoiVT3xUbEEtl45jkWz7e6K/5712JDQ1kiA32fmHTOD@Xt@Oen7y0WKrnp/ltr8PiMlZEBRLbICvb9I1WCV1EyJOspUwQAZkWWLIlSNDhRtTx1WWGpcF5GTj9Wf4FiZwGJWU1qgR6Gq449DhTuWMpN0a7Go9AGnw7NbgZGhTvPvWVdQdGha/BRAzp49sK1Y0ARh2eJHpxmaQFiWFpHYT/TaRs02ovYMzSzY2NMRvCOJdYtivmVp9BBuvStFs0bJlrwRITY@wBccAR8BZH3MKW@Ix2w/v2c8pt99qN/HY@j8YygEDiTPJwUAXYn4UvmK1p9zbmj1pdKN9RMGjtx@JYyvg/F1lf7ZwNACOzTbaQDpJwBzgf5ar531Gpp8bVt8x3wDxh18phEm43GRJYm9o1cRL@fwhxhbWmTkGwmPUgdSnwMdvlIWL2lE8E2Ml3zU4UAaDmQKZDqAJNfk7tfJhsL/Rvw7@ydNELaUUl@SXi49hrWb3GH1qHfbEs8xXpV5nk90kNd4sspBL901WcLpIPYerEpfBnQwGcEOl2v85nRIeIIki7Bw9jm@@pQArcA5L4fzCOfg67p454P@Aw "Python 2 โ€“ Try It Online") -17 bytes thanks to caird coinheringaahing -12 bytes thanks to Nathan Shiraini -56 bytes by switching to mixed indentation (Python 2) -28 thanks to CensoredUsername because the probabilities are normalized in the end, so it's not necessary that the end probabilities always add up to 1. -7 bytes thanks to Calculator Feline by using a shorter ending `elif` statement. -218 bytes by merging the two functions [Answer] # C, ~~569~~ ~~568~~ 556 Bytes ## Golfed ``` #define A s[1] #define c(i,j,k) break;case i:x=j;y=k; w,S,i,j,d,x,y,z;main(int*a,char**s){w=strchr(&A[1],'|')+2-A;a=calloc(w,4);for(;i++<'~~';j=0){for(;A[j];){if(A[z=j++]==79){d=rand()%2;x=4;y=7;z+=w;for(;z<strlen(A);){z+=x%3-1+(y%3-1)*w;switch(A[z]){case 85:goto e;c(32,x/3*(3+1),y/3*(3+1))c(45,d*2+3,7)c(94,(d=rand()%2)*2+3,7)c(118,4,8)c(47,3,7)d=0;c(92,5,7)d=1;c(124,(d=!d)*2+3,7)c(60,x,y)case 62:d=A[z]/2%2;case 61:x=d*8;y=4;}}a[z%w]++;e:;}}}for(i=-1;++i<w;S=a[i]>S?a[i]:S);for(j=17;j-->1;puts(""))for(i=0;i<w-1;printf("%c",a[i++]*16./S+0.6<j?32:35));} ``` ## Ungolfed ``` //Variable Definitions //direction - marbles current direction, 0 -> left, 1-> right //arrwidth - width of array //x - change in x of marble in base 3 - 0 -> Left, 1 -> stay, 2-> right //y - change in y of marble in base 3 - 0 -> Up, 1 -> stay, 2-> Down //z - position of marble //i - iterator on runs of program //j - iterator on string //k - iterator on outputstring //argc - array holding all buckets #define c(i,j,k) break;case i:x=j;y=k; arrwidth,scale,i,j,direction,x,y,z; main(int *argc, char**argv){ arrwidth=strchr(&A[1],'|')+2 - A; //get width argc=calloc(arrwidth,4); for(;i++<'~~';j=0){ for(;A[j];){ if(A[z=j++] == 79){ //if it finds an O, start sim direction=rand()%2; x=4; y=7; z+=arrwidth; for(;z<strlen(A);){ z+=x%3-1 + (y%3-1)*arrwidth; switch (A[z]){ case 85://marble dies dont record goto e; c(32,x/3*(3+1),y/3*(3+1)) //case ' ' c(45,direction*2+3,7) //case - c(94,(direction=rand()%2)*2+3,7) //case ^ c(118,4,8) //case v c(47,3,7) //case / direction=0; c(92,5,7) //case '\' direction=1; c(124,(direction=!direction)*2+3,7) c(60,x,y) //case < case 62: //case > direction=A[z]/2%2; case 61: //case = x=direction*8; y=4; } } argc[z%arrwidth]++; e:; } } } //get output answer in terms of '#' for(i=-1;++i<arrwidth;scale=argc[i]>scale?argc[i]:scale); for(j=17;j-->1;puts("")) for(i=0; i < arrwidth-1;printf("%c",argc[i++]*16./scale+0.6<j?32:35)); } ``` ## Edits Saved 12 bytes by changing my case macro. ## Notes My code uses a system of base 3 integers to determine where the marble is headed and will be headed after (for cannons and stuff). I tried so had to beat that python solution, I really did. ]
[Question] [ A void list is a list that at no level contains any non-list objects. Or if you prefer a recursive definition * The empty list is void * A list containing only other void lists is void All void lists have a finite depth. Here are some examples of void lists (using python syntax): ``` [] [[]] [[],[]] [[[]]] [[[]],[]] [[],[[]]] ``` Here are some examples of things that are *not* void lists: ``` ["a"] [[...]] [1] 2 [[],([],[])] ``` --- # Task Write two separate functions (or programs if you prefer). One should take a positive integer (you may also include zero if you wish) as an argument and return a void list the other should take a void list and return it an integer. These two functions should always be inverses of each other. That is if you pass the output of `f` into `g` you should get the original input of `f` as the result of `g`. This means the mapping must be 1:1, i.e. for every integer, there may only exist **exactly one** void list for which `g` gives that integer and for every void list there should be exactly one integer for which `f` gives that void list. You are essentially creating a Bijection You may choose to use a string representation of a void list (with or without commas and spaces) instead of your languages native list type. # Scoring Your score will be the lengths of your two functions together. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to minimize this sum. [Answer] # Pyth, 27 + 29 = 56 bytes `f`: ``` L?bol`NS{sm[d+d]Y]d)ytb]Y@y ``` [Test suite](https://pyth.herokuapp.com/?code=L%3Fbol%60NS%7Bsm%5Bd%2Bd%5DY%5Dd%29ytb%5DY%40y&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4&debug=0) `g`: ``` L?bol`NS{sm[d+d]Y]d)ytb]Yxyl` ``` [Test suite](https://pyth.herokuapp.com/?code=L%3Fbol%60NS%7Bsm%5Bd%2Bd%5DY%5Dd%29ytb%5DYxyl%60&test_suite=1&test_suite_input=%5B%5D%0A%5B%5B%5D%5D%0A%5B%5B%5B%5D%5D%5D%0A%5B%5B%5D%2C+%5B%5D%5D%0A%5B%5B%5B%5B%5D%5D%5D%5D&debug=0) The system is very simple: I generate all possible lists with no more than a certain number of `[`'s. Then, I sort them in such a way that the lists I haven't generated yet would be near the end. This is all done by the function `y`, identical in both programs. It is written as ``` L?bol`NS{sm[d+d]Y]d)ytb]Y ``` Then, I index into this list for `f`, and search through it for `g`. The number of lists I generate is chosen to be large enough that I have generated all possible lists which would appear at or before the desired location in the infinite sorted list. The programs allow/return 0 as an option. [Answer] # [Python 2](https://docs.python.org/2/), 96 bytes [Try it online!](https://tio.run/nexus/python2#NYzNCoQwDITP26foaUn8wb9b0ScpOUS0odDNiuz7uxb1MGG@mSFHmBJ/5oVtcmlVSMi62ADJt4RFX3bjmKFzhEaeqTotvNC59ALagL5rxaZHKgXykznqlWE94BG@u402qt1ZZYWhRWde2x71Z2MVQCAiVvkac6XG8OS9p8rTqdsQ3W0AxtsKZHiIjz8 "Python 2 โ€“ TIO Nexus") to test the bijection. ``` f=lambda l:len(l)and f(l[0])*2+1<<f(l[1:]) ``` Takes void lists to non-negative integers. 42 bytes. ``` g=lambda n:n*[g]and[g(n/(n&-n)/2)]+g(len(bin(n&-n))-3) ``` Takes non-negative integers to void lists. 54 bytes. A more recursive attempt gave the same length. ``` g=lambda n,i=0:n*[g]and[g(n/2,i+1),[g(n/2)]+g(i)][n%2] ``` [Answer] # Java 7, 725 bytes `f(int)` (**325 bytes**): ``` String f(int i){String s="";for(int j=0,e=0;e<i;e+=v(s))s=Integer.toBinaryString(j++);return"["+s.replace("1","[").replace("0","]")+"]";}int v(String s){for(;!s.isEmpty();s=s.replaceFirst("1","").replaceFirst("0",""))if(s.replace("1","").length()!=s.replace("0","").length()|s.charAt(0)<49|s.endsWith("1"))return 0;return 1;} ``` `g(String)` (**75 + 325 bytes**): ``` int g(String s){int r=0;for(String i="10";!i.equals(s);i=f(++r));return r;} ``` Since method `g` uses method `f` to calculate it's result by looping over possible void-list until it founds the one equal to the one inputted, the bytes of `f` are counted twice (since both methods should be able to run without the other for this challenge). **Explanation:** In general, method `f` simply loops over all binary String-representations of integers, and increase a counter every time a valid one is found. Valid binary-Strings for this challenge comply to the following rules: They start with a `1`, and end with a `0`; they have an equal number of 1s and 0s; and every time you remove the first `1` and `0` and validate what is left again, these two rules still apply. After the counter equals the input, it converts that binary-String to a String void-list, by replacing all `1` with `[` and all `0` with `]`. As for method `g`: We start with `"[]"` (representing void-list `0`), and then continue using method `f` while increasing an integer, until it matches the input-String. ``` String f(int i){ // Method `f` with integer parameter and String return-type String s=""; // Start with an empty String for(int j=0,e=0;e<i; // Loop as long as `e` does not equal the input e+=v(s)) // And append increase integer `e` if String `s` is valid s=Integer.toBinaryString(j++); // Change `s` to the next byte-String of integer `j` // End of loop (implicit / single-line body) return"["+ // Return the result String encapsulated in "[" and "]" s.replace("1","[").replace("0","]")+"]"; // after we've replaced all 1s with "[" and all 0s with "]" } // End of method `f` int v(String s){ // Separate method with String parameter and integer return-type for(;!s.isEmpty(); // Loop as long as String `s` isn't empty s=s.replaceFirst("1","").replaceFirst("0","")) // After each iteration: Remove the first "1" and "0" if(s.replace("1","").length()!=s.replace("0","").length() // If there isn't an equal amount of 1s and 0s |s.charAt(0)<49 // or the String doesn't start with a 1 |s.endsWith("1")) // or the String doesn't end with a 0 return 0; // Return 0 (String is not valid) // End of loop (implicit / single-line body) return 1; // Return 1 (String is valid) } // End of separate method int g(String s){ // Method `g` with String parameter and integer return-type int r=0; // Result integer for(String i="[]";!i.equals(s); // Loop as long as `i` does not equal the input String i=f(++r)); // After each iteration: Set `i` to the next String in line return r; // Return the result integer } // End of method `g` ``` **Example input & output cases:** [Try it here.](https://tio.run/nexus/java-openjdk#pZJNb@IwEIbv@RWDTx6lioK0HLbGh11pK/XAqYceEIcsmHSqxFB7oEJsfjudkFBoqx5W5GBrXvt95sOZV0WMMNkfHjiQL2GpyTMQ7vs4WqXMchWO8rPNb5zNjRuTcand6ogY7b1nV7qQ8eo3@SLsOqd@TlM0wfEmeDVVacyCW1fF3Gk1VDei4FnIRZgpTGUxTZtoq0/pcd8mN4OYUfxTr3mn0UT7DrujELkjnoG9mB9FpKX@lFtuVs6X/KRxYOPHMi7O/sVs/lSEX6xzHP/4KaHzi/hIciYYxK43yPsmYWiapC2@vCi@jYNMrG2iV8mqqfQ5oMy9bIoqyhAN2aVO04CngUEwzQFgvflb0RwiFyzbdkULqAvyPWk6gwL3Ccg3gRosePcKE5nPUTq9GUl2oPFwJKu8SHcf4GEX2dXZasPZWmBceU2QgroFJVudyX@AbdyHpe4k7OlNknxDUaP8zBjlXyGitZTO342EpfjjUL6D8mVppeZTGZ1xOrvCeo1ZvNeYxd5v/49pkubwBg) (NOTE: It's pretty slow for the last few test cases. Will take around 10-15 sec for all of them.) ``` 0 <-> [] 1 <-> [[]] 2 <-> [[][]] 3 <-> [[[]]] 4 <-> [[][][]] 5 <-> [[][[]]] 6 <-> [[[]][]] 7 <-> [[[][]]] 8 <-> [[[[]]]] 9 <-> [[][][][]] 10 <-> [[][][[]]] 11 <-> [[][[]][]] 12 <-> [[][[][]]] 13 <-> [[][[[]]]] 14 <-> [[[]][][]] 50 <-> [[[][[[]]]]] 383 <-> [[[][]][[[][]]]] ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 49 bytes ``` {$[#x;2/,/1,'&:'o'x;0]} {$[x;o'|-1+-1-':&|2\x;()]} ``` [Try it online!](https://tio.run/##VYxNCoMwEIX3nmKkxUyof3HXzMYT9AKtYCGxiBJBXUTUXt3GIoUuhnmP9/E1kXmZbdNyPt9PlrIkTETIAsk6ZiktVk/ti6WOLZG4RCJiMliyhyXkxbqN@zi9e1mBpbJrCMvqWbdkaaLeAV4lVa5zmtObPzqLLVaGyCl0t3/kLn9LeLRjdQkSGPUwgkKNLedQD9A6n87Vv8/P0h@rUaFxbNX1YKA2kMaxuG4f "K (ngn/k) โ€“ Try It Online") uses the formula from the example in [Bijection: tree-like lists - natural numbers](https://codegolf.stackexchange.com/questions/169623/bijection-tree-like-lists-natural-numbers?noredirect=1#MathJax-Element-1-Frame) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 82 bytes ``` f=(n,i)=>n?n&1<<i?[f(i),...f(n>>-~i)]:f(n,-~i):[] g=([a,...b])=>a?g(b)*2+1<<g(a):0 ``` [Try it online!](https://tio.run/##TYvLCsMgEADvfkjZbY30cShI1A8RDyaNsiWspSk95teNORR6G2aYZ/zGZXzT69NxeUy1JgMsCY1lx4dL35PzCQilUioBW9uthEE3lDtpH0Q24OPeh9C26DIMeLye2pshoj7XsfBS5knNJUOC2x1R/KufRFE3 "JavaScript (Node.js) โ€“ Try It Online") xnor's idea [Answer] # [Python 3](https://docs.python.org/3/) - sign/abs, 73 bytes ``` f=lambda n:[[[]]*(n<0),[[]]*abs(n)] g=lambda l:[-1,1][not l[0]]*len(l[1]) ``` [Try it online!](https://tio.run/##Nco7DgIhEADQfk8x3c4YSEA7ol5kQsHGBUlw2LA0nh5/sXvF2579XuU0RryU8FhuAcQxs/cHlLMh9WVYdhTyU/qf4lhbZT1L7VDYvE9ZBQtbTyPWBhmyQAuSVtRHZQ25CbaWpWNWs77OKmKmnxJ@TDRe "Python 3 โ€“ Try It Online") Straight forward implementation, supports negative numbers. Integer `i` is encoded `[sign(i), abs(i)]`, where `sign(i)=[] if i > 0 else [[]]` and `abs(i)=[[]] * i`, i.e. a list of empty lists with length abs(i). # [Python 3](https://docs.python.org/3/) - binary, 126 bytes This is a more elaborate version (and a lot longer...), where the absolute value is encoded in a binary list representation. ``` f=lambda n:[[[]]*(n<0),[[[]]*int(i)for i in f"{n:+b}"[1:]]] g=lambda l:[-1,1][not l[0]]*int(''.join(map(str,map(len,l[1]))),2) ``` [Try it online!](https://tio.run/##PY5BDsIgFET3PQXpBr7@mlJ3RL0IYUFjqRj6aZCNMZ4drVVX8zZvZuZ7vkTal@KOwU792TJSWmtjNoIOLeDKnrLw4GJinnlirn6Q2vbPWktljKnGnxuUbiRKoylmFnT7VTnfXaMnMdlZ3HLCJcNAGLQ0AIAdlH93sjQOoulQtqAqNqfPNvLmxNG9T6w0ioUBygs "Python 3 โ€“ Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 33 total bytes These programs are inverses of each other. They convert to and from all void lists and all non-negative integers, so that includes 0. This seems like it's maybe a famous function from some kind of algebra I don't know. In order to wrap my head around it, I first implemented the programs as functions in python. ``` def convert_to_void(n): lst = [] while n > 0: n -= 1 choices = len(lst) + 1 choice = n % choices cutpoint = len(lst) - choice n //= choices newgroup = lst[cutpoint:] del lst[cutpoint:] lst.append(newgroup) return lst def convert_from_void(lst): n = 0 while lst != []: newgroup = lst.pop() n *= len(lst) + len(newgroup) + 1 n += len(newgroup) + 1 lst.extend(newgroup) return n ``` The stax programs have the same behavior. ### Non-negative integer โ†’ Void list, 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ฦ’รขโ‚ง~โ””3BIโ”€ยฟ-rร…;รฌ ``` [Run and debug it](https://staxlang.xyz/#p=9f839e7ec0334249c4a82d728f3b8d&i=0%0A1%0A2%0A3%0A123%0A54321&a=1&m=2) ### Void list โ†’ Non-negative integer, 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ร‡รครช[!ฯƒ`cโ†‘ร–ยงโ–‘NRโ•ฅรง=ร† ``` [Run and debug it](https://staxlang.xyz/#p=8084885b21e56063189915b04e52d2873d92&i=[]%0A[[]]%0A[[],+[]]%0A[[[]]]%0A[[[[]]],+[[]],+[],+[]]%0A[[[[[]],+[[],+[[]]]],+[[],+[]]]]&a=1&m=2) ]
[Question] [ Right hand brace is a style of code bracketing in which curly braces and semicolons are all aligned to a single point on the right side of a a file. ![Example Image go here](https://pbs.twimg.com/media/CvH9gfFWcAA2knK.jpg) Generally, this is considered bad practice, for several reasons. ## The Challenge Take a multiline string through any method, and convert it's brace style to Right Hand Brace. For this challenge, you only need it to work on Java code, however, it should theoretically work on any code that uses Braces and Semicolons. You must grab all `{};` characters in a row, with any amount of whitespace between them. EG. `}}`, `; }` `}\n\t\t}`, and line them up on the right side of the file through the use of whitespace. for example: ``` a { b; {c ``` should become ``` a { b ;{ c ``` Or, more abstractly, push any and all whitespace from the left of all `{};` characters, to the right. Indentation of lines should be otherwise preserved. Lines only containing whitespace after the movement of the `{};` characters may optionally be removed. For example: ``` a{ b{ c; } } d; ``` May become either ``` a { b { c;}} d ; ``` or ``` a { b { c;}} d ; ``` Pushed to the right refers to all the `{};` characters being aligned to a point no shorter than the longest line. Any amount of space after that is acceptable. So all the below is acceptable: ``` a { bc; a { bc ; a { bc ; ``` etc... Lines in any code may contain `{};` characters between other non-whitspace characters, the handling of this case isn't necessary, although if you're inclined, you should leave them in place. Lines may also not contain any `{};` characters at all, and this should be handled correctly. As is shown below. ``` a { b ; c d } ``` Because we don't want [Code Review](https://codereview.stackexchange.com/) to see the horrible things we're doing, you need to make your code as small as possible. ## Examples / Testcases **Generic Java** ``` public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello, World!"); } } ``` becomes... ``` public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!") ;}} ``` **The image itself** ``` public class Permuter{ private static void permute(int n, char[] a){ if (n == 0){ System.out.println(String.valueOf(a)); }else{ for (int i=0; i<= n; i++){ permute(n-1, a); swap(a, n % 2 == 0 ? i : 0, n); } } } private static void swap(char[] a, int i, int j){ char saved = a[i]; a[i] = a[j]; a[j] = saved; } } ``` becomes... ``` public class Permuter { private static void permute(int n, char[] a) { if (n == 0) { System.out.println(String.valueOf(a)) ;} else { for (int i=0; i<= n; i++) { permute(n-1, a) ; swap(a, n % 2 == 0 ? i : 0, n) ;}}} private static void swap(char[] a, int i, int j) { char saved = a[i] ; a[i] = a[j] ; a[j] = saved ;}} ``` **Not so Perfectly Generic Python** For contrast ``` def Main(): print("Hello, World!"); Main(); ``` becomes... ``` def Main(): print("Hello, World!") ; Main() ; ``` ## Notes * [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply * [Standard IO](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) applies * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins! * I am not Liable for damages related to programming in Right Hand Brace style * Have Fun! ## Edit Notes I reworded the challenge details, Hopefully I didn't break anyone's view of the rules, I assure you it was unintentional. This should be a much more clear and less self-conflicting spec. [Answer] # [V](https://github.com/DJMcMayhem/V) + Bash utilities, ~~64~~ ~~62~~ ~~61~~ ~~60~~ 62 bytes *1 byte saved thanks to @DJMcMayhem for putting the ex commands together* ``` :se ve=all|%!wc -L y$uรฒ/^ *<93>[{};] xk$pรฒรฒ/<84> {};][{};]ยซ$ lDรฎ^R0|p ``` `^R` is the character literal for `<C-r>` (`0x12`) and `<84>` is `0x84` and `<94>` is `0x94`. `wc -L` works on most \*nix based systems, but not macOS. For macOS, you have to do `gwc -L` after getting coreutils using brew, if you haven't already. [Try it online! (Java)](https://tio.run/nexus/v#@29VnKpQlmqbmJNTo6pYnqyg68NVqVJ6eJN@nILWocnR1bXWsVwV2SoFhzcBxQ61KIAEwKKHVqtw5bgcXidkUFPw/39BaVJOZrJCck5icbGCR2pOTn54flFOSjWXAhBAJYtLEkuAVFl@ZopCbmJmnkZwSVFmXnp0rEJiUXqxJkQtCARXFpek5urll5boFQBVlOTkaSiBzdRRAJuqqKRpDVZcy1ULAA "V โ€“ TIO Nexus") [Try it online! (Python)](https://tio.run/nexus/v#@29VnKpQlmqbmJNTo6pYnqyg68NVqVJ6eJN@nILWocnR1bXWsVwV2SoFhzcBxQ61KIAEwKKHVqtw5bgcXidkUFPw/39KapqCb2JmnoamFZcCEBQUZeaVaCh5pObk5OsohOcX5aQoKmlac3FBFFkDAA "V โ€“ TIO Nexus") [Try it online! (Java again)](https://tio.run/nexus/v#dZDBTsJAEIbvPfoEvwkkRQpWj9TGi0cTTTgSTNay1a3LdtPdFgn05hv4GCYeeAR4MNzdogLGuczMl39m/sx2oCgqGhPOl@3TWYLerTdvlZvV@QPO1u@jRR2NvdeXltysDFu/wQJH1x8tj99sPk/CpdxuZfnIWYKEE6VwT4tpqWmx8GBCFqwimkJpoo2kytkEslH4TGiIAMkzKUZjkE4zYYOl8AXiGOEetDGcK02n/bzUfbNZaC78oTbFU78ivKR3qU86nehnpKZc0cMNaV7AXWZxGIFdxRAmdbtHh5z3nU/RuwiMveiPQM2I9EkAgTYunV1cg2GA0LAjfe0dVvW/73Fbv58SwHltUrZn0gqgSEUniEFGbPx7znYOZgcws9BNRDsH9Rc "V - TIO Nexus") This preserves all blank lines and does not handle tabs, only spaces. Hexdump: ``` 00000000: 3a73 6520 7665 3d61 6c6c 7c25 2177 6320 :se ve=all|%!wc 00000010: 2d4c 0a79 2475 f22f 5e20 2a93 5b7b 7d3b -L.y$u./^ *.[{}; 00000020: 5d0a 786b 2470 f2f2 2f84 207b 7d3b 5d5b ].xk$p../. {};][ 00000030: 7b7d 3b5d ab24 0a6c 44ee 1230 7c70 {};].$.lD..0|p ``` ### Explanation First we need to be able to move the cursor anywhere in the buffer, so we use ``` :se ve=all|... ``` and we chain this with another ex command using `|` We need to get the length of the longest line in the input. This can be done with the shell command `wc -L`. ``` ...|%!wc -L ``` This overwrites the current buffer (containing the input) with the result of `wc -L`. It gives an output of something like: ``` 42 ``` and the cursor lands on the `4` in `42`. Then we copy this number by using `y$`: yank text from the cursor's position to the end of the line. This conveniently stores this number in register `0`. But more on that later. The input is replaced with this number, so to revert back, we `u`ndo. Now say the input looked somewhat like this: ``` public class HelloWorld{ public static void main(String[] args){ System.out.println("Hello, World!"); } } ``` we need to move the braces `}` from the end of the buffer to just after the `println` statement. ``` รฒ " recursively do this until a breaking error: /^ *<93>[{};] " this compressed regex becomes /^ *\zs[{};] " this finds any character from `{};` after leading spaces " the cursor then goes to the `{};` x " delete character k$ " go to the end of the line above p " and paste รฒ ``` If the regex cannot be found, a breaking error happens and breaks out of the recursion caused by `รฒ`. Now comes the main part of this program, move all braces and semi-colons and align them as stated in the question. ``` รฒ " starts recursion /<84> {};][{};]ยซ$ " compressed form of [^ {};][{};]\+$ " finds a sequence of `{};`s at the end of the line with a non-`{};` char to preceding it l " move the cursor 1 to the right (since we were on the non-`{};` char now) D " delete everything from this position to the end of line " the deleted text contains `{};` รฎ " execute as normal commands: ^R0 " contains what's in register `0`, ie the length of the longest line | " now go to the column specified by that number p " and paste the contents " implicit ending `รฒ` ``` Again, this recursion will be stopped by a breaking error caused when the regex could not be found in the buffer. ### Edits * Used `D` instead of `d$` (I don't even know why I missed that in the first place) * Compressed `[^` (in the regex) to `<84>` * Fixed bug by using `\zs` (compressing it into `<93>`) and by removing the `$` in `$xk$pรฒ` * Removed useless newline * Changed regex to make submission compliant with new rules and gained 2 bytes [Answer] # Ruby, ~~100~~ ~~114~~ 108 bytes Reads file name as command line argument. If no file name is supplied, it'll read from STDIN. Does not handle tabs. [Try it online!](https://tio.run/nexus/ruby#Lcy9DoIwFAXgnaeopNEWzDU6CurqzuCADFUKqSk/6S1GJX12BPQs9ybnyxmKA43BSJFDid2NbdIrRr3LArrhPV2CNb5H/PVq5Tx6jOPirxgEJ87SSYZ8plvQjw4tK0CrWiJUomXLPaqP5OP/4iHduWFou5tWd3LXApGcpdbNpTE67z0y5l@iFXY8z0blpBKqZok1qi7TjAhTIv/ZKckbrayg6Sy0o7C6Zv68uSbz6sLn0Yyd574 "Ruby โ€“ TIO Nexus") ``` f=$<.read.gsub(/[\s;{}]*$/){$&.tr" ",''} $><<f.gsub(/(.*?)([;{}]+)$/){$1.ljust(f.lines.map(&:size).max)+$2} ``` [Answer] # [Perl](https://www.perl.org/), 90 bytes 88 bytes of code + `-p0` flags. ``` \@a[y///c]for/.*/g;s/(.*?)\K[{};]$/$"x(@a-$1=~y%%%c).$&/gme;1while s/ * *([{};]+)$/$1/m ``` [Try it online!](https://tio.run/nexus/perl#dVDBUsIwFLzzFau2TlpK03q0duDuQWc41h5iCRCmDZ0mBRmm/jqmARVwfJf3srO7b/PubmrelBjV0eFtwrIdpbTI5@uGhj5dJIqS0B97b8/Zvktyhzq3H2TCRk6cfu5c1y280Lmni4on8XYpSg5F4Q/gE0sfekYQ0@pwqNv3UhQoSqYUXnlTtZo3@wFM1Y3YMG2UmmlD2azFDPWRQYTUkAGKJWuyHMw7KvoScxCJNEV0BvY13SnNq3Dd6tA4S11KMtVmWIQbVrb8ZU6Y5yU/ko6Xil86mL/DbhZplEA8pZCmDYdXi2z2U045igMTL/lDUFtWExZAwsWDjYsxBB4RGeyK3w0up@7f81jX76MEsFmPbXUWsidAsQ2fIQXLRP67rn9ZcHUBrnrQKpJTgu4L "Perl โ€“ TIO Nexus") *Short explanations:* `\@a[y///c]for/.*/g;` counts the length of the longest line: for each line, it defines the element at index `y///c` (ie the size of the line) of the array `@a`. At the end, the max index of `@a` (ie. the size of `@a`) is the size of the longest line. `s/(.*?)\K[{};]$/$"x(@a-$1=~y%%%c).$&/gme` places the `{};` characters at the end of the lines. `1while s/ *\n *([{};]+)$/$1/m` makes makes the braces on empty lines go on the line above. Thanks to [@primo](https://codegolf.stackexchange.com/users/4098/primo) from whom I partially "stole" the beginning of my code from [here](https://codegolf.stackexchange.com/a/106666/55508) to count the length of the longest line. [Answer] # Python 2: 228 Bytes ``` import re g=re.search def b(a): s,l="",a.split('\n') r=max([len(k)for k in l]) for k in l: n,m=g('[;}{]',k),g('[\w]',k) if n:n=n.start() if m:m=m.start() if n>m and m!=None:s+="\n"+k[:n]+" "*(r-n) s+=k[n:] print s ``` [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), 133 bytes ``` '\s+([;{}])' '$1'repl lines{!n'[\s;{}]+$'match''join:n\'$'+del\,}"!tr:$size"!$MAXmap@k{e i:e[' 'k i#rpad]"!}map tr[' 'join]map' 'join ``` [Try it online!](https://tio.run/nexus/stacked#rVHBitswEL3nKyapQQ4JWnpNWGih7FLY7aU9FJIcJvJkrcaRjDRm4wZ/eyppN7GXpYdCdZCs9@a9Nx6JmxvgUntgUqXRCquqhXA1lgFhh4qta6WUo1C3bRi@QmETqdCRBM2x@NCCsgXB4stIVeg93JMhh0F692IApxGEpazx7JoI5VtbtNMXOK7Yg4wY3EI8lonp0p42OpLKddAPRBUxOPLLK6B3eW8Ui9Eosjt4wMO2wIHyokb35EPid0a1p0I@ET@g528pSPqIzvvWJDrN7XT5xiXkBwNDzxeT67/3rcxTzkDYAVWe/tln4NA3KOvGl3mQD1hH3DjTz2Ywx6BhrULQkfOkDzmDwYTXaxz9aGsqrvT8XUvvoy61MhlP/xZLxxIb/3@SXyM6cRZrP8tXy1O3mQoQ2UfhqK6g0ob8aWzEau0jN8vEAVmVQvyy2izMWmRiVlC1nneTMbtF5vVvmoyzx88/D1h/2p8I9IJWwXEP@oOrsdhMxl2ggF1Eo8smXMUofZ5tw@c/ "stacked โ€“ TIO Nexus")I could be heavily overthinking this... but whatevs. I'll look at it again tomorrow. Some nice tips: 1. `"!` can often be used in place of `map`, saving a byte or two, depending on if the next token starts with a word. However, it can only be used when each atom of the array is wanting to be mapped over. It's similar to a deep map. 2. A space is not needed after a quoted function, so `$MAXmap` is equivalent to `$MAX map`, which in turn is equivalent to `[MAX] map`. (Maps each array to its maximal element.) [Answer] ## JavaScript (ES Proposal), ~~139~~ 121 bytes ``` f= s=>s.replace(/^(.*?)\s*(([;{}]\s*)+)$/gm,(_,t,u)=>t.padEnd(Math.max(...s.split` `.map(s=>s.length)))+u.replace(/\s/g,``)) ``` ``` <textarea rows=10 cols=40 oninput=o.textContent=f(this.value)></textarea><pre id=o> ``` Requires Firefox 48/Chrome 57/Opera 44/Safari 10/Edge 15 for `padEnd`. Edit: Saved 18 bytes thanks to @ValueInk. [Answer] # PHP, ~~201~~ ~~194~~ ~~185~~ ~~172~~ 167 bytes ``` foreach($f=file(f)as$s)$x=max($x,strlen($a[]=rtrim($s,"{} ; ")));foreach($a as$i=>$c)echo str_pad($c,""<$c|!$i?$x:0),trim(substr($f[$i],strlen($c)))," "[""==$a[$i+1]]; ``` takes input from file f; assumes single byte linebreaks and no tabs; preserves blank lines. * +2 bytes for delimiting whitespace: append `+1` to the second `str_pad` parameter. * -6 bytes if it was guaranteed that no code line consists of a single `0`: Remove `""<` and replace `""==` with `!`. **breakdown** ``` foreach($f=file(f)as$s) // loop through file $x=max($x,strlen( // 3. set $x to maximum code length $a[]= // 2. append to array $a rtrim($s,"{} ;\n") // 1. strip trailing whitespace and braces )); foreach($a as$i=>$c)echo // loop through $a str_pad($c, // 1. print code: !$i|""<$c // if first line or not empty ?$x // then padded to length $x :0 // else unpadded (= print nothing) ), trim(substr($f[$i],strlen($c))), // 2. print braces "\n"[""==$a[$i+1]] // 3. if next line has code, print newline ; ``` [Answer] # Java 8, ~~312~~ 305 bytes ``` s->{String t="([;{}]+)",z[],r="",a;s=s.replaceAll(t+"[\\s\\n]*","$1").replaceAll(t,"$1\n");int m=0,l;for(String q:s.split("\n"))m=m>(l=q.length())?m:l;for(String q:s.split("\n")){z=q.split("((?<="+t+")|(?="+t+"))",2);for(a="",l=0;l++<m-z[0].length();a+=" ");r+=z[0]+a+(z.length>1?z[1]:"")+"\n";}return r;} ``` **Explanation:** [Try it here.](https://tio.run/##lZRNj9owEIbv/Iqp1Up2HSLYI8ag3nrptlIPPSQ5eINhTR2TtQ1Vofnt1HECAlr6ISVKMn5n5pkZO2uxE8NNLc168fVYauEcfBDKHAYAynhpl6KU8Nh@Anz2VpkVlLh/cYQFexPucDkvvCrhEQxwOLrh7NCrPEc4Y4emoAQl@6xILEcoEcxxl1pZ65DgndbYU5TluctzU7xFCXo9RuRquTXlBhEWsKDio0Sz5caeUF4mLnW1Vh6jVkQqXs2w5i@plmblnzEh82ryR4/DPqh7A8bzKUc0IJEfeN6/BfoHEiOItgDNR0xTOq2G@2xUnPMwQTmCgGkpbxeooHjfr87G8302LiYIEdomZY2VfmsNWNYc2SA0sd4@6dDEvpe7jVpAFabRM2eFIP0kvjsvq3Sz9WkdVrw22KQlRr1/N8f3UuvNl43Vi0NuWq@/RQdhV4704jtpchTDJhADv8pDpZ2@yU0TmsT@ne@TtNU2bLETnVU74eUVXt1JcDtzk0D5LGyLecmoloDDluMwurTegegqTXdCb@XHJRbkRB8rkNrJmxhh3BCzqzBuUFMOJjwovc0VC@hhzXCcBEb2q8J9EzUWSTgib@AhMsMcFExgFGy3Ds0F2bnF9xoVI5/ak0Ak7h7rS9RWAU7s5CIcUpGp4iJn@xmt62vrurVGn/@Z9EIu448Ek8mZ2vjfb5/cdErWR20GzfEn) ``` s->{ // Method with String parameter and String return-type String t="([;{}]+)", // Temp regex-String we use multiple times z[],a, // Temp String-array and temp String r=""; // Result-String s=s.replaceAll(t+"[\\s\\n]*","$1") // We replace all ;{} in the input with zero or more whitespaces/newlines to just ;{} .replaceAll(t,"$1\n"); // and then add a single newline after each group of ;{} int m=0,l; // Two temp integers for(String q:s.split("\n")) // Loop (1) over the lines m=m>(l=q.length())?m:l; // To determine the longest line // End of loop (1) for(String q:s.split("\n")){ // Loop (2) over the lines again z=q.split("((?<="+t+")|(?="+t+"))",2); // Split on groups of ;{}, but keep them in the array for(a="",l=0;l++<m-z[0].length();a+=" "); // Amount of spaces we should add r+=z[0]+a+(z.length>1?z[1]:"")+"\n"; // Append this line to the result-String } // End of loop (2) return r; // Return the result-String } // End of method ``` ]
[Question] [ In his xkcd [about the ISO 8601 standard date format](https://xkcd.com/1179/) Randall snuck in a rather curious alternative notation: [![enter image description here](https://i.stack.imgur.com/b1ZUO.png)](https://i.stack.imgur.com/b1ZUO.png) The large numbers are all the digits that appear in the current date in their usual order, and the small numbers are 1-based indices of the occurrences of that digit. So the above example represents `2013-02-27`. Let's define an ASCII representation for such a date. The first line contains the indices 1 to 4. The second line contains the "large" digits. The third line contains the indices 5 to 8. If there are multiple indices in a single slot, they are listed next to each other from smallest to largest. If there are at most `m` indices in a single slot (i.e. on the same digit, and in the same row), then each column should have be `m+1` characters wide and left-aligned: ``` 2 3 1 4 0 1 2 3 7 5 67 8 ``` *See also [the companion challenge](https://codegolf.stackexchange.com/q/67128/8478) for the opposite conversion.* ## The Challenge Given an ISO 8601 date (`YYYY-MM-DD`), output the corresponding xkcd date notation. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. Any year from `0000` to `9999` is valid input. Trailing spaces are allowed, leading spaces are not. You may optionally output a single trailing newline. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test Cases ``` 2013-02-27 2 3 1 4 0 1 2 3 7 5 67 8 2015-12-24 2 3 1 4 0 1 2 4 5 5 67 8 2222-11-11 1234 1 2 5678 1878-02-08 1 3 24 0 1 2 7 8 57 6 8 2061-02-22 2 4 1 3 0 1 2 6 5 678 3564-10-28 1 4 2 3 0 1 2 3 4 5 6 8 6 5 7 8 1111-11-11 1234 1 5678 0123-12-30 1 2 3 4 0 1 2 3 8 5 6 7 ``` [Answer] # JavaScript (ES6), 168 ~~173~~ As an anonymous function. Using template strings, there is a newline near the end that is significant and included in the byte count. ``` d=>d.replace(/\d/g,c=>m=(l=((o[c]=o[c]||[b,c,b])[p/2&~1]+=++p).length)>m?l:m,t=[m=p=b='',b,b],o=[])&o.map(x=>x&&x.map((x,i)=>t[i]+=(x+' ').slice(0,m+1)))||t.join` ` ``` **Less golfed** ``` f=d=>( // get the indices in o and the columns width in m m=0, p=0, o=[], d.replace(/\d/g,c=>( o[c] = o[c]||['',c,''], // for each found digit :array with top indices, digit, bottom indices o[c][p/2 & ~1] += ++p, // (p/2 and not 1) maps 0..3 to 0, 4..7 to 2 l = o[c].length, m = l>m ? l : m // max indices string length in m )), // build the output in t t=['','',''], o.map(x=> x && x.map( (x,i) => t[i]+=(x+' ').slice(0,m+1)) // left justify, max value of m is 4 ), t.join`\n` // return output as a newline separated string ) ``` **Test snippet** ``` f=d=> d.replace(/\d/g,c=>m=(l=((o[c]=o[c]||[b,c,b])[p/2&~1]+=++p).length)>m?l:m,t=[m=p=b='',b,b],o=[])& o.map(x=>x&&x.map((x,i)=>t[i]+=(x+' ').slice(0,m+1))) ||t.join`\n` console.log=x=>O.textContent+=x+'\n' ;['2013-02-27','2015-12-24','2222-11-11','1878-02-08','2061-02-22','3564-10-28','1111-11-11'] .forEach(t=>console.log(t+'\n'+f(t)+'\n')) ``` ``` <pre id=O></pre> ``` [Answer] # Ruby, ~~200~~ ~~195~~ ~~189~~ ~~178~~ ~~162~~ 157 characters (156 characters code + 1 character command line option) ``` o={} i=0 $_.gsub(/\d/){o[$&]||=['',''] o[$&][i/4]+="#{i+=1}"} o=o.sort.map &:flatten puts [1,0,2].map{|i|o.map{|c|c[i].ljust o.flatten.map(&:size).max}*' '} ``` Sample run: ``` bash-4.3$ ruby -n xkcd-date.rb <<< '2013-02-27' 2 3 1 4 0 1 2 3 7 5 67 8 bash-4.3$ ruby -n xkcd-date.rb <<< '2222-11-11' 1234 1 2 5678 bash-4.3$ ruby -n xkcd-date.rb <<< '3564-10-28' 1 4 2 3 0 1 2 3 4 5 6 8 6 5 7 8 ``` [Answer] # Python 2.7, ~~308~~ 310 bytes ``` i=raw_input().replace("-","") s,w=sorted(set(i)),len x,m={},0 for c in s: q,v=i,[""]*2 while c in q:a=str(-~q.index(c)+(w(i)-w(q)));v[int(a)>4]+=a;q=q[q.index(c)+1:] m,x[c]=max(m,max(map(w,v))),v for l in[0,1]:print"".join((lambda x:x+(-~m-w(x))*" ")("".join(x[n][l]))for n in s)+"\n"+(" "*m).join(s)*(-l+1) ``` Wow, fixing it only costed 2 bytes! The date doesn't have to be separated, the date can be any length, it doesn't have to be a date, it could be any string (but dashes are removed). The middle part looks pretty golfable to me. [Answer] # Pyth, 86 78 bytes ``` JS{K-z\-=GheS.nmmlkd=N,mf<T5d=ZmmhkxdcK1Jmf>T4dZjbmjkmj"".[|k\ \ Gd[hNm]dcJ1eN ``` I will try to golf this down as soon as my brain has recovered. I was happy just to see it work. [Answer] ## C#, 456 Golfed: ``` string x(string p){string s=p.Replace("-", ""),a="",d="",e="";var u=new Dictionary<char,List<int>>();for(int i=0;i<s.Length;i++)if(u.ContainsKey(s[i]))u[s[i]].Add(i+1);else u.Add(s[i],new List<int>{i+1});foreach (var c in u.Keys.OrderBy(k=>k)){var t=String.Join("",u[c].Where(i=>i<5));var b=String.Join("",u[c].Where(i=>i>4));var l=Math.Max(t.Length,b.Length);var m=c+"".PadRight(l);a+=t.PadRight(l)+" ";e+=m;d+=b.PadRight(l)+" ";}return a+"\n"+e+"\n"+d;} ``` Ungolfed: ``` string x(string p) { string s = p.Replace("-", ""),a = "", d = "", e = "";; var u = new Dictionary<char, List<int>>(); for (int i = 0; i < s.Length; i++) if (u.ContainsKey(s[i])) u[s[i]].Add(i + 1); else u.Add(s[i], new List<int>{ i + 1 }); foreach (var c in u.Keys.OrderBy(k => k)) { var t = String.Join("", u[c].Where(i => i < 5)); var b = String.Join("", u[c].Where(i => i > 4)); var l = Math.Max(t.Length, b.Length); var m = c + "".PadRight(l); a += t.PadRight(l) + " "; e += m; d += b.PadRight(l) + " "; } return a + "\n" + e + "\n" + d; } ``` [Answer] # Perl6, 265 bytes Golfed ``` my$i=get;$i~~s:g/\-//;my@b=$i.comb.unique.sort;my$f={$i.comb[$_[1]-1]eq$_[0]??$_[1]!!''};my$g={[~] .map: $f};my$h={(@b X @^a).rotor(4).map: $g}my@a=$h(1..4);my@c=$h(5..8);my$s=max(|@aยป.chars,|@cยป.chars)+1;my$x='%-'~$s~'s';for @a,@b,@c {say [~] @_.map: *.fmt($x)} ``` Ungolfed (slightly) ``` my $i = get; $i ~~ s:g/\-//; my @b = $i.comb.unique.sort; my $f = { $i.comb[$_[1]-1] eq $_[0] ?? $_[1] !! '' }; my $g = { [~] .map: $f }; my $h = { (@b X @^a).rotor(4).map: $g } my @a = $h(1..4); my @c = $h(5..8); my $s = max(|@aยป.chars, |@cยป.chars)+1; my $x = '%-'~$s~'s'; for @a,@b,@c { say [~] @_.map: *.fmt($x) } ``` [Answer] # Python 3, 306 bytes I'm investigating ways to determine, before assembling the top and bottom lines, what the maximum width of any given column will be. Once I've got that, I should be able to build the spaces into the lines directly instead of using all those `join` functions. ``` j=''.join def t(d): c,*l={},;i,*n=0, for e in d.replace('-',''): i+=1 try:c[e]+=[i] except:c[e]=i, m=sorted(c) for x in m: l+=[j(str(p)for p in c[x]if p<5)] n+=[j(str(p)for p in c[x]if p>4)] f='<'+str(max(map(len,l+n))) return'\n'.join(map(lambda o:' '.join(format(i,f)for i in o),(l,m,n))) ``` [Answer] # Powershell, ~~174~~ ~~170~~ ~~168~~ 167 bytes ``` $a=@{} $args|% t*y|?{$_-45}|%{if(!$a.$_){$a.$_="","","$_"}$a.$_[++$i-gt4]+=$i} 0,2,1|%{$r=$_ -join($a.Keys|sort|%{$a.$_[$r]}|% p*ht(1+($a|% v*|%{$_|% l*h}|sort)[-1]))} ``` Less golfed test script: ``` $f = { $a=@{} # a hash table for a result $args|% toCharArray|?{$_-45}|%{ # for each digit from argument strings except a '-' if(!$a.$_){$a.$_="","","$_"} # create an array if there are no values for the current digit $a.$_[++$i-gt4]+=$i # append the character to the relative row (0 - top, 1 - bottom) and increment position number } # the result is a hash table in which the key is a char of a digit and the value is an array of string # for example, first lines for the first test case: # @{ # [char]48: ("2","5","0") # [char]49: ("3","","1") # [char]50: ("1","67","2") # ... # } $l=1+($a|% Values|%{$_|% Length}|sort)[-1] # calc the maximum width of strings 0,2,1|%{ # for each number 0,2,1 $r=$_ # store it as row number -join( $a.Keys|sort| # for each keys (digit of the dates) in the sorted order %{$a.$_[$r]}| # push to pipe the relative string % padRight $l # for which to execute the 'padright' method to pad with spaces ) # and finally join the row } } @( ,("2013-02-27", "2 3 1 4 ", "0 1 2 3 7", "5 67 8") ,("2015-12-24", "2 3 1 4", "0 1 2 4 5", " 5 67 8 ") ,("2222-11-11", " 1234 ", "1 2 ", "5678 ") ,("1878-02-08", " 1 3 24 ", "0 1 2 7 8 ", "57 6 8 ") ,("2061-02-22", "2 4 1 3 ", "0 1 2 6 ", "5 678 ") ,("3564-10-28", " 1 4 2 3 ", "0 1 2 3 4 5 6 8 ", "6 5 7 8 ") ,("1111-11-11", "1234 ", "1 ", "5678 ") ,("0123-12-30", "1 2 3 4 ", "0 1 2 3 ", "8 5 6 7 ") ) | % { $d, $expected = $_ $result = &$f $d $d $j=0 $result|%{ "$($_.trimEnd() -eq $expected[$j].TrimEnd()): |$_|" # Vertical bars only to see trailing and leading spaces $j++ } } ``` Output (vertical bars only to see trailing and leading spaces): ``` 2013-02-27 True: |2 3 1 4 | True: |0 1 2 3 7 | True: |5 67 8 | 2015-12-24 True: |2 3 1 4 | True: |0 1 2 4 5 | True: | 5 67 8 | 2222-11-11 True: | 1234 | True: |1 2 | True: |5678 | 1878-02-08 True: | 1 3 24 | True: |0 1 2 7 8 | True: |57 6 8 | 2061-02-22 True: |2 4 1 3 | True: |0 1 2 6 | True: |5 678 | 3564-10-28 True: | 1 4 2 3 | True: |0 1 2 3 4 5 6 8 | True: |6 5 7 8 | 1111-11-11 True: |1234 | True: |1 | True: |5678 | 0123-12-30 True: |1 2 3 4 | True: |0 1 2 3 | True: |8 5 6 7 | ``` ]
[Question] [ It's friday! Which means it's time for beer! Sadly though, today we will be golfing beer instead of drinking it. :( ### Challenge Output a beer and drink it. The amount of sips you take changes your output. ### Sips Your program should take one input string. This string can solely consist out of concatenated `sip`s. If the input is an empty string, you should output a full beer glass, including foam. The more sips you take, the emptier your beer glass will be. If you take 0 sips, your beer still has foam. The output of this foam is always the same (see examples). If you take 1 sip, you should output the beer glass, followed by a new line and the string `Yuck, foam.`. If you take 1 or more sips, your beerglass should not contain anymore foam, but should show the top of your glass. Drinking the foam counts as one sip. If you take 6 or more sips, you should output an empty beer glass, followed by a new line and the string `Burp`. For each sip you take, your beer glass should become emptier. How full your beerglass is depends on the amount of bubbles `ยฐ` (`&#176;`) in your beer. For each sip you take after the foam, a line of bubbles should be removed. Each line of beer can contain a minimum of `1` and a maximum of `5` bubbles. The position of these bubbles should be 100% random. ### Examples **input** `empty input string, or no input at all` **output** ``` oo o oo oooooooooooo o| ยฐ ยฐ |\ | ยฐ | \ | ยฐยฐ ยฐ |} | | ยฐ ยฐ | / | ยฐ ยฐ|/ \__________/ ``` **input** `sip sip sip` **output** ``` ____________ | |\ | | \ | ยฐ |} | |ยฐ ยฐ ยฐ | / | ยฐ ยฐ |/ \__________/ ``` **input** `sip sip sip sip sip sip sip sip sip sip` **output** ``` ____________ | |\ | | \ | |} | | | / | |/ \__________/ Burp ``` [This pastebin](http://pastebin.com/AsdYR60G) contains a list of inputs and outputs. Remember that the bubbles in the beerglass should be random! ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins! Happy ~~drinking~~ golfing! [Answer] # [Japt](https://github.com/ETHproductions/Japt), 189 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859) I almost went insane while trying to get this to work properly... ``` U?S+'_pC +R:" oo o oo\n "+'opC +"\no")+"\\, \\,} |, /,/"q', ยฃ(V=(!YยซU?"|: |" +SpA +'|+X,(1+5*Mr)o mZ=>Ul <Y*4+4ยฉ(V=Vh2+A*Mr ,'ยฐ ),V)qR +"\n \\"+'_pA +'/+R+(Ul ยฅ3?"Yuck, foam.":Ug22 ?`Bยจp: ``` ### [Try it online!](http://ethproductions.github.io/japt?v=9b914b60365b0031f09d30c79d98d504131f1328&code=VT9TKydfcEMgK1I6IiAgb28gIG8gb29cbiAiKydvcEMgKyJcbm8iKSsiXFwsIFxcLH0gfCwgLywvInEnLCCjKFY9KCFZq1U/Inw6IHwiICtTcEEgKyd8K1gsKDErNSpNcilvIG1aPT5VbCA8WSo0KzSpKFY9VmgyK0EqTXIgLCewICksVilxUiArIlxuIFxcIisnX3BBICsnLytSKyhVbCClMz8iWXVjaywgZm9hbS4iOlVnMjIgP2BCqHA6&input=InNpcCBzaXAgc2lwIg==) (Note: This program was made for an older version of Japt, and doesn't currently work in the latest version. To get around this, the older version is specified in the URL. Unfortunately, this also means the top-right code box doesn't work.) This is *by far* the longest program I have ever written in Japt. Here's a breakdown: **Step 1:** Create the top of the beer mug. ``` U?S+'_pC +R:" oo o oo\n "+'opC +"\no") // Implicit: U = input string // Begin the ASCII art with: U?S+ // If U is not an empty string, a space + '_pC +R: // "_".repeat(12) + a newline. :"..."+ // Otherwise, this string + 'opC + // "o".repeat(12) + "\no") // a newline and an "o". ``` If U is an empty string, this makes: ``` oo o oo oooooooooooo o ``` Otherwise, this makes: ``` ____________ ``` **Step 2:** Create the middle rows of the mug. ``` +"\\, \\,} |, /,/"q', ยฃ(V=(!YยซU?"|: |" +SpA +'|+X, +"..." // Add to the previous string: this string, q', ยฃ( // split at commas, with each item X and its index Y mapped to: V=( // Set variable V to the result of concatenating: !YยซU? // If Y is 0 and U is an empty string, "|: |" // "|"; otherwise, " |"; +SpA // 10 spaces, '|+X, // "|", and X. ``` This results in the previous string plus: ``` | |\ | | \ | |} | | | / | |/ ``` **Step 3:** Add the bubbles. ``` (1+5*Mr)o mZ=>Ul <Y*4+4ยฉ(V=Vh2+A*Mr ,'ยฐ ),V) // Note: We're still looping through the five rows at this point. (1+5*Mr) // Generate a random integer between 1 and 5. o // Create an array of this many integers, starting at 0. mZ=> // Map each item Z in this range to: Ul <Y*4+4ยฉ // If the length of U is less than Y*4+4, // (in other words, if there's less than Y+1 "sip"s) (V=Vh 'ยฐ // Insert "ยฐ" at position 2+A*Mr // 2 + random number between 0 and 9. ),V)qR // Finally, return V, and join the five rows with newlines. ``` At this point, the mug looks something like this: ``` ____________ | |\ | | \ | ยฐ |} | |ยฐ ยฐ ยฐ | / | ยฐ ยฐ |/ ``` **Step 4:** Add the final row and optional text. ``` +"\n \\"+'_pA +'/+R+(Ul ยฅ3?"Yuck, foam.":Ug22 ?`Bยจp: +"\n \\" // Add a newline and " \". +'_pA // Add 10 "_"s. +'/+R // Add a slash and a newline. +(Ul ยฅ3? // If the length of U is 3 (i.e. 1 "sip"), "..." // add the string "Yuck, foam.". :Ug22 ? // Otherwise, if U has a character at position 22 (six or more "sip"s), `Bยจp // decompress this string ("Burp") and add it. : // Otherwise, add nothing. ``` Now everything is ready to be sent to output, which is done automatically. If you have any questions, feel free to ask! [Answer] # JavaScript (ES6), ~~283~~ 281 bytes ``` s=>` `+(u=`_________`,(s=s&&s.split` `.length)?u+`___ `:` oo o oo oooooooooooo o`)+(i=0,l=q=>`|`+[...u].map(_=>Math.random()>.8&i>=s&&b++<5?`ยฐ`:` `,b=0,i++).join``+(b|i<s?` `:`ยฐ`)+`|`+q+` `)`\\`+l` \\`+l`} |`+l` /`+l`/`+`\\`+u+`_/ `+(s&&s<2?`Yuck, foam.`:s>5?`Burp`:``) ``` ## Explanation ``` s=> ` `+(u=`_________`, // u = 9 underscores (s=s&&s.split` `.length) // s = number of sips ?u+`_ `:` oo o oo oooooooooooo o`) // print glass top or foam // Print glass lines +(i=0, // i = line number l=q=> // l = print glass line `|`+[...u].map(_=> // iterate 9 times Math.random()>.8 // should we put a bubble here? &i>=s // has this line already been sipped? &&b++<5 // have we already placed 5 bubbles? ?`ยฐ`:` `, // if not, place the bubble! b=0, // reset the number of placed bubbles i++ // increment the line counter ).join`` // put the 9 spaces and bubbles together +(b|i<s?` `:`ยฐ`) // place a bubble at 10 if none were placed +`|`+q+` ` // print the suffix of this glass line )`\\` +l` \\` +l`} |` +l` /` +l`/` +`\\`+u+`_/ ` // print the bottom of the glass +(s&&s<2?`Yuck, foam.` :s>5?`Burp`:``) // print the message ``` ## Test ``` Input: <input type="text" id="sips" /><button onclick="result.innerHTML=( s=>` `+(u=`_________`,(s=s&&s.split` `.length)?u+`___ `:` oo o oo oooooooooooo o`)+(i=0,l=q=>`|`+[...u].map(_=>Math.random()>.8&i>=s&&b++<5?`ยฐ`:` `,b=0,i++).join``+(b|i<s?` `:`ยฐ`)+`|`+q+` `)`\\`+l` \\`+l`} |`+l` /`+l`/`+`\\`+u+`_/ `+(s&&s<2?`Yuck, foam.`:s>5?`Burp`:``) )(sips.value)">Go</button><pre id="result"></pre> ``` [Answer] # PHP, ~~277~~ ~~265~~ 263 bytes Assuming 1-byte-linebreak. Add one to `14` and `17` on Windows. ``` $r=str_pad(($i=$argc-1)?"":" oo o oo",16).str_pad(" ",14,_o[!$i])." ".($s=" | |")."\\ $s \\ $s} |$s / $s/ \__________/ ".($i<6?$i-1?"":"Yuck, foam.":burp)if(!$i){$r[34]=o;$i=1;}for(;$i++<6;)for($n=rand(1,5);$n--;)$r[17*$i+rand(2,11)]="ยฐ";echo$r; ``` Run with `-r`. line breaks may need escaping. **breakdown** ``` // draw beer glass $r= // first line: empty or foam str_pad(($i=$argc-1)?"":" oo o oo",16) // second line: top or foam .str_pad("\n ",14,_o[!$i]) // other lines: empty glass+bottom ." ".($s="\n | |")."\\ $s \\ $s} |$s / $s/\n \__________/\n" // lyrics .($i<6?$i-1?"":"Yuck, foam.":burp) ; // add foam left to the glass if(!$i){$r[34]=o;$i=1;} // add bubbles for(;$i++<6;) for($n=rand(1,5);$n--;) $r[17*$i+rand(2,11)]="ยฐ"; // output echo$r; ``` ]
[Question] [ Suppose you're given some distinct uppercase letters scattered in a rectangular array of otherwise-blank cells. Each cell in the array *belongs* to the letter *nearest* to it, defined as the letter reachable in the smallest number of horizontal and/or vertical steps -- no diagonal steps. (If a cell is equidistant from two or more nearest letters, it belongs to whichever of those letters is first in alphabetical order. A cell with an uppercase letter in it belongs to that letter.) *Boundary*-cells are those that are horizontally or vertically adjacent to one or more cells that do not belong to the letter that they themselves belong to. **Write a procedure subprogram** with the following behavior, producing a kind of [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) ... **Input**: Any ASCII string composed only of dots, uppercase letters, and newlines, such that when printed it displays a rectangular array of the kind described above, with dots acting as blanks. **Output**: A printout of the input string with each blank boundary-cell replaced by the lowercase version of the letter it belongs to. (The subprogram does the printing.) **Example 1** Input: ``` ......B.. ......... ...A..... ......... .......D. ......... .C....... .....E... ......... ``` Output: ``` ...ab.B.. ....ab.bb ...A.abdd aa...ad.. cca.ad.D. ..caeed.. .C.ce.edd ..ce.E.ee ..ce..... ``` A sketch highlighting the boundaries: ![A sketch highlighting the boundaries](https://i.stack.imgur.com/1XwIQ.gif) **Example 2** Input: ``` ............................U........... ......T................................. ........................................ .....................G.................. ..R.......S..........F.D.E............I. .........................H.............. .....YW.Z............................... ......X................................. ........................................ ........................................ ......MN...........V.................... ......PQ................................ ........................................ .............L...............J.......... ........................................ ........................................ ....C...........K....................... ........................................ ..................................A..... ...........B............................ ``` Output: ``` ..rt.....ts...sg......gduu..U.....ui.... ..rt..T..ts...sg......gddeu......ui..... ...rt...ts....sg......gddeeu....ui...... ....rttts.....sggggggGgdde.euuuui....... ..R.rywss.S....sfffffFdDdEeeeeeei.....I. ...ryywwzs.....sf....fddhHhhhhhhhi...... ..ryyYWwZzs..sssffff.fddh.......hi...... ..rxxxXxzzs.sllvvvvvffddh....hhhhi...... rrrxxxxnzzssl.lv....vfddh...hjjjjii..... mmmmmmmnnnnnl.lv.....vvdh..hj....jai.... mmmmmmMNnnnnl.lv...V...vvhhj.....jaai... ppppppPQqqql...lv.......vhj......ja.ai.. ppppp.pq.ql....lkv.....vjj.......ja..aii cccccppqql...L.lkkv...vj.....J...ja...aa .....cpqqlll..lk..kvvvvj........ja...... ......cccbbbllk....kkkkj.......ja....... ....C...cb..bk..K......kj.....ja........ .......cb....bk........kjjjjjja......... ......cb......bk.......kaaaaaa....A..... .....cb....B...bk......ka............... ``` Color enhancement: ![color enhancement](https://i.stack.imgur.com/IuKCW.gif) [Answer] # Python 3 - 424 422 417 332 295 characters: ``` def v(s): w=s.find("\n")+1;n=(-1,1,-w,w);r=range(len(s));x=str.replace;s=x(x(s,*".~"),*"\n~")+"~"*w;t=0 while s!=t:t=s;s=[min(s[i+j]for j in n).lower()if"~"==s[i]and(i+1)%w else s[i]for i in r]+["~"]*w print(x("".join(s[i]if any(s[i]!=s[i+j].lower()!="~"for j in n)else"."for i in r),*"~\n")) ``` There are three parts, each of which needs to be on its own line due to Python's syntax: 1. The first line sets up the variables. `w` is the width of a row of the board (including the newline at the end, which will be recycled as a padding column). `r` is a `range` object that indexes all the characters in `s`. `n` is a tuple of index offsets to get at the neighbors of a character (so if you wanted to allow the letters to spread out diagonally, you'd just need to add `-w-1,-w+1,w-1,w+1` to the tuple). `x` is a short name for the `str.replace` method, which gets used several times in the later code (the calls will look odd though, since I use `x(s,*"xy")` to save characters, rather than the conventional `s.replace("x", "y")`). The `s` parameter string is modified slightly at this point as well, with its `.` characters and newlines being replaced by `~` characters (because they sort after all letters). A row's worth of padding `~` characters are also added to the end. `t` will later be used as a reference to the "old" version of `s`, but it needs to be initialized to something not equal to `s` at the start, and zero takes only one character (a more Pythonic value would be `None`, but that's three extra characters). 2. The second line has a loop that repeatedly updates `s` using a list comprehension. As the comprehension iterates over the indexes of `s`, `~` characters are replaced by the `min` of their neighbors. If a `~` character was completely surrounded by other `~`s, this will do nothing. If it was next to one or more letters, it will become the smallest of them (favoring `"a"` over `"b"`, etc.). The newlines that were turned to `~` characters are preserved by detecting their indexes with the modulus operator. The padding row at the end isn't updated in the list comprehension (because the range of indexes, `r`, was calculated before they were added to `s`). Instead, a fresh row of `~` characters is added after the comprehension is done. Note that `s` becomes a list of characters rather than a string after first pass of the loop (but because Python is flexible about types we can still index to get at the characters in the same way). 3. The last line hollows out the insides of the diagram and rebuilds the characters into a string to be printed. First, any letter that is surrounded only by other copies of itself (or `~` characters from the padding) gets replaced by `.`. Next, the characters are all concatenated together into a single string. Finally, the padding `~` characters are converted back to newlines and the string is printed. [Answer] ### GolfScript, 138 144 137 characters ``` :^n%,,{{^n/1$=2$>1<.'.'={;{@~@+@@+\{^3$?^<n/),\,@-abs@@-abs+99*+}++^'. '-\$1<{32+}%}++[0..1.0..(.0]2/%..&,(\0='.'if}{@@;;}if}+^n?,%puts}/ ``` Input is given to the subprogram as a single string on the stack. Unfortunately I had to use a `puts` because of the requirement that the routine has to print the result. **Explanation of the code** The outer block essentially loops over all position (x,y) according to the size of the input rectangles. Within the loop the coordinates x and y are left on the stack each time. After each line is complete the result is printed to console. ``` :^ # save input in variable ^ n%,,{{ # split along newlines, count rows, make list [0..rows-1] ??? # loop code, see below }+^n?,%puts}/ # ^n?, count columns, make list [0..cols-1], loop and print ``` The code executed within the loop first takes the corresponding character of the input. ``` ^n/ # split input into lines 1$= # select the corresponding row 2$>1< # select the corresponding col ``` Then basically we check, if we have a `.`, i.e. if we (possibly) have to replace the character. ``` .'.'={ # if the character is '.' ; # throw away the '.' ??? # perform more code (see below) }{ # else @@;; # remove coordinates, i.e. keep the current character # (i.e. A, B, ... or \n) }if # end if ``` Again, the inner code starts with a loop, now over all coordinates (x,y) (x,y+1) (x+1,y) (x,y-1) (x-1,y) ``` { @~@+@@+\ # build coordinates x+dx, y+dy ??? # loop code }++ # push coordinates before executing loop code [0..1.0..(.0]2/% # loop over the coordinates [0 0] [0 1] [1 0] [0 -1] [-1 0] ``` The recent inner code snippet simply returns the (lower case) letter of the nearest point, given the two coordinates. ``` { # loop ^3$?^< # find the current letter (A, B, ...) in the input string, # take anything before n/ # split at newlines ), # from the last part take the length (i.e. column in which the letter is) \, # count the number of lines remaining (i.e. row in which the letter is) @-abs@@-abs+ # calculate distance to the given coordinate x, y 99*+ # multiply by 99 and add character value (used for sorting # chars with equal distance) }++ # push the coordinates x, y ^'. '- # remove '.' and newline \$ # now sort according to the code block above (i.e. by distance to letter) 1<{32+}% # take the first one and make lowercase ``` So from the five nearest letters for the coordinates (x,y) (x,y+1) (x+1,y) (x,y-1) (x-1,y) take the first, if not all are equal, otherwise take a `.`. ``` . # copy five letter string .&,( # are there distinct letters? \0= # first letter (i.e. nearest for coordinate x,y) '.' # or dot if # if command ``` [Answer] ## Python, 229 226 chars ``` def F(s): e,f,b='~.\n';N=s.index(b)+1;s=s.replace(f,e) for i in 2*N*e:s=''.join(min([x[0]]+[[y.lower()for y in x if y>b],all(y.lower()in f+b+x[0]for y in x)*[f]][x[0]!=e])for x in zip(s,s[1:]+b,s[N:]+b*N,b+s,b*N+s)) print s F("""......B.. ......... ...A..... ......... .......D. ......... .C....... .....E... ......... """) ``` Does a flood fill to compute the result. The trailing `for`/`zip` combo generates an array `x` for each cell containing the value in that cell and its four neighbors. Then we use Blckknght's trick and `min` a bunch of possibilities for each cell. Those are the original cell value, any neighbors if the cell has not been visited yet, or a `.` if it has been visited and all neighbors are `.` or equal to the cell itself. ]
[Question] [ Your input is an array of integers in the range `[-1,4]`. An array element of `-1` means that there might be a bomb in that position. A non-negative element means that there is not a bomb in that position and also the numeric value tells how many bombs there are **within distance 2**. For example, if we have the following array: `[1,2,-1,-1,4,-1,-1,-1,1]` it's possible to infer that every `-1` except the last one contains a bomb. Your task is to take indicate which `-1` **for sure doesn't** contain a bomb by outputting it's index (0 or 1 based). There is always at least one guranteed bombfree square (and thus the input length is at least two). You can use another number instead of `-1` to represent an unknown square. If there are multiple possibilities output at least one of them. Shortest code wins. To reiterate, you **have to be certain** that the index you output **cannot contain a mine**. If you were clearing mines IRL, you probably would also like to know that you won't accidentally step on one. # Test cases ``` [-1,0] -> 0 [0,1,-1,-1] -> 2 [-1,-1,-1,0] -> 1 or 2 [1,-1,-1,-1,2] -> 1 [-1,2,-1,-1,4,-1,-1] -> 0 [-1,-1,3,-1,-1,2,2,-1] -> 3 [2,-1,-1,-1,2,-1,-1,-1,2] -> 3 or 5 [-1,-1,1,-1,-1,-1,-1,1,0] -> 6 [-1,-1,1,-1,-1,2,-1,-1,2,-1,-1,2,-1,1] -> 0 or 1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~55~~ ~~48~~ 47 bytes ``` โ‰”โŒ•๏ผกฮธยฑยนฮท๏ผฆ๏ผฅ๏ผธยฒ๏ผฌฮทฮฆฮท๏นชรทฮน๏ผธยฒฮผยฒ๏ผฆโฌคฮธโˆจโ€นฮบโฐโผฮบ๏ผฌฮฆฮนโ€บยณโ†”โปฮผฮปโ‰”โปฮทฮนฮท๏ผฉฮท ``` [Try it online!](https://tio.run/##TU/LbgIxDLz3K3x0JCOV5chpRUtViaXcEYeUTTdWTVKSLP38kIUU1fLBj/HM@Gh1OHotObcx8uBwza5vRfBMsDWDTgbnShFYtXz68gGw0z@4878mYEOwMW5IFu2EWLOkMrUEne9H8fju0gtfuDfIBI@T04RtVAm48VWtj4AbEyN@EzwXwOt51HLrqkRlL0xvweipXBC0n9HLWCx27MaIJwJRfwH1n/uquOL6xS6wS7jSMU2@lznv9w3N5jX/l4dDnl3kCg "Charcoal โ€“ Try It Online") Link is to verbose version of code. Outputs all possible bombfree positions. Explanation: ``` โ‰”โŒ•๏ผกฮธยฑยนฮท ``` Create a list of all the positions of `-1`s in the input. ``` ๏ผฆ๏ผฅ๏ผธยฒ๏ผฌฮทฮฆฮท๏นชรทฮน๏ผธยฒฮผยฒ ``` Create all possible mine layouts and loop over them. ``` ๏ผฆโฌคฮธโˆจโ€นฮบโฐโผฮบ๏ผฌฮฆฮนโ€บยณโ†”โปฮผฮป ``` If for all non-negative values there are the correct number of mines within a distance of 2, then... ``` โ‰”โปฮทฮนฮท ``` ... remove the positions that might have a mine. ``` ๏ผฉฮท ``` Output the positions that didn't have a mine. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 110 bytes ``` a->forvec(v=[[k=0,1]|i<-s=a],i=1;[t+1|t<-a,polcoef(Polrev(v)*Pol([1,1,5,1,1]),i++)!=t]||s+=v);[k|t<-s,t<0*k++] ``` [Try it online!](https://tio.run/##bY5BCsMgEEWvYrvSOIIGukrMGboXFxJikYRGjAiF3D3VpoXQFv4w7/EZGG@CYze/WSQ3wzo7hzT0OEmlRslB6NW1bJFGg5OiUZGKNbbMgJ@nfh4svs5TGBJOpMqElQABlzxCE3CUkpOMel0XKhNp1FhOF4gtr0ZK9Wa8nx7YINYhH9w9ZjwXOSOLDSGAlGICuM6QPwFWUoS9ea8@klMXrw/@Ve14OHgZ/63qf1toTbYn "Pari/GP โ€“ Try It Online") 1-indexed. Ungolfed: ``` { a -> /* Define a function with argument a: */ s = a; /* Let s = a. */ forvec(v = [[0, 1] | i <- a], /* Let v loops over all binary vectors with length #a. */ if( /* If */ prod(i = 1, #a, /* for all i in range 1..#a */ a[i] == -1 || /* a[i] is -1 or */ polcoef( /* the coefficient of x^(i + 1) in */ Polrev(v) /* the polynomial with coefficients v */ * Pol([1 ,1, 5, 1, 1]), /* times (1 + x + 5*x^2 + x^3 + x^4) */ i + 1 ) == a[i] /* equals a[i] */ ), s += v /* Then add v to s */ ) ); [k | k <- [1..#a], s[k] == -1] /* Find all k in range 1..#a such that s[k] is -1 */ } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 102 bytes ``` Position[#+Total@Cases[{0,1}~Tuples~Tr[1^#],v_/;MatchQ[ListConvolve[{1,1,5,1,1},v,3,0],#/.-1->_]],-1]& ``` [Try it online!](https://tio.run/##bY3NCsIwEIRfJRDw4sZ2K57EUuhVoUJvIUqQSgNtI03spcRXj6k/ICrMsvMxO2wrbV210qqT9Gey8YU2yirdcTovtZVNlktTGT7GgO5WXi9NZW5lz/FABQzHaL2T9lTv@VYZm@tu0M1Q8REBYRUGHQywhFgAjRYMWXoUAhiKmS961VlOCUvJmVMhyIxEGRlHhhA7INO7cBg0AXv5Z/SGoGTi5IO/oqf9KDwo/o2Sfxud83c "Wolfram Language (Mathematica) โ€“ Try It Online") A port of my [PARI/GP answer](https://codegolf.stackexchange.com/a/243314/9288). 1-indexed. [Answer] # JavaScript (ES6), 127 bytes The output is 0-indexed. ``` a=>a.findIndex((v,i)=>!~v&[...Array(1<<a.length)].every((_,k)=>a.some((v,j)=>~v*(g=x=>x+3?g(x-1)-(!~a[x+=j]&k>>x|x==i):v)(2)))) ``` [Try it online!](https://tio.run/##hZDRaoMwFIbv@xT2ppysJjUp20VpMna5ZxAZoUartWbEElIYvrpLVgalFT0cCOfi@/6TU0sru4Opvi@41bkaCj5ILiQpqjb/bHPlAGxcIS6WvV2lhJAPY@QV6H4vSaPa8nJEGVFWmSvAV3xCge30WQWs9lNvX6Dkjgu33r6X4DBFGJa9TN2a19nqJIT7cZxXaGcRMORrOOi2040ijS6hgBTTOMkQimZrs4mSxQOcxDTGoecMHmaL5@Rbz@V7mEbaPBv@Bb7ZpCMYHmF2B096PLwN8a/jH7hb4m9KRg1v0zAbe29XDXcP8XT4BQ "JavaScript (Node.js) โ€“ Try It Online") --- # JavaScript (ES6), 118 bytes Slightly shorter but stack-overflows on the last test case. ``` a=>a.findIndex((v,i)=>!~v&(h=k=>k>>a.length||a.some((v,j)=>~v*(g=x=>x+3?g(x-1)-(!~a[x+=j]&k>>x|x==i):v)(2))&h(-~k))()) ``` [Try it online!](https://tio.run/##hY/LasMwEEX3@QpnY2Yay/GDZhEYdd1vCFmIWH5XKrYRWhj/uisnFEISYnE3QnPOHdXCiP7SVb8DUzqTc06zIC7CvFLZt8qkBTBBhcS3k/GhpIZ4w917K1UxlOMowl7/yGWodkOT@YCCLHG7S78KsCxGBttJnOyO6rPvSDtaogqPBiFB9EtgU4MIiPNFq163Mmx1ATmcWBxEZ0Rv9ez3XrR5gKMgDtiSNYODk81z8y1r/Q6OPd09G/4FLslbx2J4hJM7@K3HwelS//n6A3dLXG/RS8Nh/gM "JavaScript (Node.js) โ€“ Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 112 bytes ``` a=>eval("for(i=k=-1;j=4*--i;~a[k]|i>>k&!a.some(v=>((j&9)+(j/2&9))*9/8&7^v|(j/=2)&2&&~v)&&(i=2**a.length,k++))k") ``` [Try it online!](https://tio.run/##hZDfCoIwFIfvewrrYuyoU7f@E/NFomDULJ250NhV9Oq2FUGU6Dhw2OD7fmenEEY0hzq/3kilj7LNeCt4Ko0o8STTNc654oRuCj7zCck3D7FVu3uepgqNRdToi8SGpxgXaA0BLmJmO/jreIWWe3O3D5wBYgg9DCBkZcz3RVTK6nQ7hyoIANQE2oOuGl3KqNQnnOEtoWGyA/AGTxx7yegHTkIaEldDBguz0X/yu4byLUw9Xf8bPgJbrNfhDL8w@4J7PRaeuvh59we@hnjdkk7Doh9mXf29Vbd3F0/bJw "JavaScript (Node.js) โ€“ Try It Online") ``` // for each cell `k` // for each possible mine placement `i` // convert `i` to binary, the nth lsb means nth cell is a mine for(i=k=0;++i<2**a.length;) if( // Current cell is not unknown, or ~a[k]| // current mine placement have a mine on position `k`, and i>>k& // it is a valid mine placement !a.some(v=> // (mine count is incorrect or current is mine) and current is not -1 ((j&9)+(j/2&9))*9/8&7^v|(j/=2)&2&&~v,j=i*4) // we try next `k` )i=0,k++; ``` [Answer] # [Python](https://www.python.org) NumPy, 127 bytes ``` lambda L:where(L<-sum((T:=r_[:1<<(l:=len(L))]>>(a:=c_[:l])&1)*~any(((5//-~abs(a-a.T<<1)@T).T-L)*~L,1),1))[0] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVBBasMwEKRXXfsBkUOzCpJjOSQUY4c-wMfcXFOUxiYCWTa20-JL-oH-oJdAaf_UvqaS5UIIgUXLzuzsDPr4rvtuX-nTZxE_fh26gt3_vClRbncCJ-HrPm9ySCLWHkqATRg3T2nIowhUGKtcQ0JItl6DCONnQ6iM3HEyOwrdA8ByPmdHsW1BMOFtooiThw3xNiwxGwnlxBRJ_QwVTVVifSjrHsuyrppuNsZ4dyNu-xYVVYMVltoOXtvtpPaaXOyU1HkLJEQYY0krHGPltbWSHUwwW-MJGQgDm9z5i1AgSWahWUUNWIoaLEqrUTTFxmZKBlXdSN2BOUoLoyIu0-n35jZlnPqZPe-jlFMz2WcAFhYILGRqMXZmIccvUcquLvBxwbcBVij16cgMaDDIXDlnbveC0X70cARKg3PfC3phdcv_c2fqYXK3V5d0cK2f5eXIfc4f) ### Old [Python](https://www.python.org) NumPy, 134 bytes (@alephalpha) ``` def f(L):t=len(L);T=c_[:1<<t]>>r_[:t]&1;return where(L<-sum(T[~any((T@triu(tril(L**0,2),-2)+4*T-L)*(L+1),1)],0))[0] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bU9LbsMgFNxziqcsGnAgMu5HVX7qAbz0DlmV1WAFCWML41bedNlVb9BNNu0pepHcpmA7UhRVQvBmhhmGr5-md4faHI_fnSvZ4-ljL0socUpWbqul8cM62748ixXfbFy-21k_uvyGr610nTXwdpBW4nTD2q7CmXgvTI9x9uSs6rDfNE6jKKYJoSwhi7soYymJcLrghHKS05gQEeeotHUFpquaHlTV1NZFU5vPEULbt6isLWhQJoBl6_bKLK0s9loZ2WKyQgCgaA1b0Mu20crhGbAdzMggeNo3l6-FxorkgYpq6smqaHBgaT2Z5uCfmZPB1VhlHPahtPQuMnY6nn4F4zTOQ3qMREw5ZWENRIIEm_B0hYdAT59Zv5JRQCK54K7l2-C7P8dduAc0Zj9cy8l_59gsDnkcjZ_4Aw) ### Old [Python](https://www.python.org) NumPy, 141 bytes ``` def f(L):m=L<0;t=sum(m);T=c_[:1<<t]>>r_[:t]&1;v=any((T@triu(tril(L**0,2),-2)[m]-L)*~m,1);return where(m)[0][~any(T[~v],0)] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bU9BasMwELzrFUsOjWTkILu0lDgOfYCPuQlRTGMTgSUZWU7xJS9oX9BLLu0r-pH8ppLtQCgFIWlmNLOjz-92cAejz-ev3tXx0-VjX9VQ44KsVV5sWObyrldYkWyXv77wdbLZOLHdWn914i7JjnmpB4x3z87KHvutwUUUMZoSGqeEKxEXJDopmpDMVq63Gt4Ola18IGeCn4J5x09HQRkRqLZGge5VO4BUrbEumku9TxC6oUO1sdCA1AGsOreXemWrct9IXXWYrBEASGogh2bVtY10eAHxFhZkFDztq1fHssHSD_RUZKgnVdniwFIzm5bgxyzJ6Gqt1A77UFp7F5k6nS8_PE4oEyGdIc5oQuOwRiJFPJ7x_CQJgZ6-sn6lk4B4esP9le-D7-Ead-Me0ZT9-FdO_zunZizkJWj6xC8) ### Old [Python](https://www.python.org) NumPy, 149 bytes ``` def f(L):m=L<0;M=triu(tril(L**0),-2);t=sum(m);T=c_[:1<<t]>>r_[:t]&1;v=any((T@(M^M.T)[m]-L)*~m,1);return where(m)[0][~any(T[~v],0)] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bU9BasMwELzrFUsOjWRkI7u0lDgOfYBz8024xTQ2EViykeUUX_KCXnvqJZf2Ff1IflPJdiCEwiJpZndmR18_7WD2jTqdvntT-U_nz11ZQYVTspJJumbxNjFa9NgeNU49jxHqRyQ2SddLLEmcJW-vfBWu1ybfbLR9mvwujA9JoQaMs2e8fdkGGeEy91PiHSUNSaxL02sF7_tSl9aCs5wf3XjGj4ecMpKjSjcSVC_bAYRsG228OdzHBKEbOlQ1GmoQyoGgMzuhAl0Wu1qossNkhQBA0AYSqIOurYXBC_A3sCBjw9I2bHkoaizsQkt5DbWkLFrsWNrMoiXYNUsyqlotlMHWlFZWRaZMp_Mv90PKcufOEGc0pL6rkYgQ92c8j4TO0NIX1lY0NRCPrrjb9r3TPVzsrtQjmrwfb9vRf_eUjDm_EE2f-AM) Brute-force approach using matrix algebra. Takes a numpy array and returns the indices (0-based) of all safe squares. Matrix `T` contains all patterns of bombs at -1 positions as columns. `triu(tril...` is essentially an adjacency matrix capturing the geometry of hint/bomb squares. By multiplying T with this matrix we get for each pattern in `T` the corresponding pattern of hints it would generate. A square is safe if each pattern of bombs where it is set creates a pattern of hints that is not the given one. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ยฎQฦถ0K<รUรฆส’XรฐrKวโ‚‚S.รธรผ5ส’ร…sd}ฮตร…syยฎยขQ}P}หœK ``` Outputs all possible results. Inspired by [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/243297/52210). [Try it online](https://tio.run/##yy9OTMpM/f//0LrAY9sMvG0OTwg9vOzUpIjDG4q8j8991NQUrHd4x@E9pqcmHW4tTqk9txVIVR5ad2hRYG1A7ek53v//RxvqGOnoGoKQCZQGIsNYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL2P9D6wKPbTPwtjk8IfTwslOTIg9viKj0Pj73UVNTsN7hHYf3mJ6adLi1OKX23FYgVXlo3aFFgbUBtafneP/X@R8dbahjpKNrCEImUBqIDGN1FKKBtAGINtCBCkMFIQgsZYjQYgSVRTMNoccYphCsBCRuhKQb0yCQMxCiYJ4BppQRNtowNhYA) or [try it online with added debug-lines](https://tio.run/##XVLBahRBEL3nK4q9qLC7JoKXEAlBiYQ9aBKFgATSO13jFOnpnnT3ZJmDl4Bng2e95OAxeEnw4GkHFBTyEf7IWt09YzbCHLq7qt579eYZJ6aEi8VgR1e1X4fB5pP59ebK4Dl6EErB/dXRVDiUD4C0pAwdmBxGazA15dSF9vnl7o/r1clGGntlqVKUCY9Afgz73lgEoxEyUzUMAafCkpgqhKODozEEFl8gVGaG1vGFwYU2/GTjRCBoz1@3X54l@G1Snku@IPdvZn0Ftsk6DxZLc4pcNA6ZR9UsNremjFpHvXxF3MrkAfrm6qCZvEvQsIeVEhlGPf2CQXG4UzBnFEeF7xh6wBn5AlwVRmUtXcLdab82Pz/30FtScq0sG1AoJOm3D70VpPgAlWDtQ15aBiINmcVgHi9ilaiq0HJSk/Z1pdB34H/OzvbH7bf2@@Oe4IVWDRwjVlHt0gDM2Mq0U0lSsu/snEaKDot@T9DG3q6QSH59bN87edgRPC0wO4ac21BkRbBakL4rDiiPPKI0tfbLMQmceFILBd4sSUk8N1fM08wv5xe7d8kYjvw9B97Wvmgidwjkf268TDNbecoFQh4jMkxno5SZRZu7sMR/6ECwJwrzmPf2Q5ctJbxHncIV2kLx96dU3OuzhWXKVIC/dSEmgzdeTtqQvSf2itFMbbnZ1SpiToaLxZtHw9Fa9y0fD/8C). **Explanation:** ``` ยฎQฦถ0K< # Get a list of (0-based) indices of the -1s: # (05AB1E unfortunately lacks a builtin for this..) ยฎQ # Check for each value in the (implicit) input-list if its equal to -1 ฦถ # Multiply each (0 or 1) check by its 1-based index 0K # Remove all 0s < # Decrease the 1-based indices to 0-based indices ร # Triplicate this list of bomb-indices U # Pop and store one of them in variable `X` รฆ # Pop another one and get its powerset ส’ # Filter this powerset by: # (implicitly push the current powerset-list) X # Push list `X` with the bomb-indices รฐ # Push a space character r # Reverse so the stack-order goes to space, `X`, powerset-list K # Remove the values of the powerset-list from bomb-indices list `X` ว # Replace those bombs with spaces in the (implicit) input-list, # to mark those bombs as duds โ‚‚S.รธ # Surround this list with leading/trailing [2,6] # (any leading/trailing pair that isn't -1 would be fine here) รผ5 # Pop and push all overlapping quintuplets ส’ # Filter this list of quintuplets by, keeping those where: ร…s # The middle item d # is a non-negative integer (so neither a -1 bomb nor " " dud) }ฮต # After the inner filter: map over the remaining quintuplets ร…s # Check if the middle item Q # is equal to yยฎยข # the amount of -1 bombs }P # After the map: check if all were truthy by taking the product }หœ # After the filter: flatten the list of powersets that were truthy K # Remove those from the bomb-indices list we've triplicated at the start # (after which the result is output implicitly) ``` [Answer] # Python3, 580 bytes: ``` def r(d,p,v): d,c=eval(str(d)),[] for i in p: if 0<=i and i<len(d)and d[i]<0:d[i]=v;c+=[1] return c and[d] def f(d,c=0): def g(d,c,o,u): if o==1: for i in r(d,[c-1],u)+r(d,[c+1],u):yield from f([*i],c+1) return for i in r(d,[c-2,c-1],u)+r(d,[c+1,c+2],u):yield from f([*i],c+1) if len(d)==c:yield d;return if d[c]in[2,1,0]:yield from g(d,c,d[c],[-2,-3][d[c]==0]) else:yield from f(d,c+1) def F(d): v={} for i in f(d): if -3 in i:return i.index(-3) for j,k in enumerate(i): if k==-2:v[j]=v.get(j,0)+1 return min(v,key=lambda x:v[x])if v else d.index(-1) ``` [Try it online!](https://tio.run/##fVHLboMwELzzFT7axY54XCoSX/MTlg8Um9QJGEQISlT12@kukDRJH5Ile2dnZ3bX7aV/b3z62nbjaGxJOmp4yweWBcTwQtohr@ixB5QxrnRAyqYjjjhPWmAQV5JoIx3JvSFuU1kPPHwb5fQmyvCSw7oIpYqhtrP9qfOkQLoyOkC/kqJNNPlBuMOQN/zEFvlGyhif38bYoSpErIEUzkE4BdnF2cqQsmtqkFUvTnPIMCyenYOfKgl/VoKa5F81aGoeVMpiIZn11QCSRhXaeZXwmEf6XmWeDdNcgbFItcJAykiDrK2O9tHTzIa4li3YwRYG@fF59wXljKKpSBFw2bJit3Le2DMVKVuG3vMDMqw/1bbLe0vdVIq1BylFkg1qD3@12tme7nnEwvj2X7XzdOAHe5FVXr@ZnJyBfNYMSoepbWKudjEb2875nm6pEjg/Y8ENiGAjAs8DKhbwiXxF4SQPieQu8Rdnxu4kpij6h5P8dmOj4xc) [Answer] # Python 3, ~~408~~404 bytes ``` e=enumerate def v(m): for i,u in e(m): if u>-1 and m[max(0,i-2):i+3].count(-2)>u:return 0 return 1 def p(m): for i,u in e(m): if u>0 and m[max(0,i-2):i+3].count(-2)<u:return 1 return 0 def b(m): r=[] for i,u in e(m): if u==-1:t=m.copy();t[i]=-2;r+=b(t)if p(t)else[t]if v(t)else[] return r def s(m): t=b(m) for i,u in e(m): if u==-1: n=1 for u in t: if u[i]==-2:n=0 if n:return i ``` [Try it online!](https://tio.run/##hZPBatwwEIbveophc6jF2sH2kh6cKlBKcy5tbo4IzlomgrXWyHJInn4rjSTbu9AtGGyN/vlm5pc8fJq3o9qdToIJNfVCN0aQVnTwnvS0ItAdNch0AqlA@AjIDqaHrIBGtdDXffOR5KnMSlrJ7Y7f7o@TMoldPkyVFmbSCnIC4atA9HAdnf@P/G0mFzM5R/Kr52hW83/yGcuKyrDe8obPhN6bWnKWlfd6y14TQ6Xrz1BxGEVtuHRGhBWfi2ksNnqoYa7q9XL2GxQr3MvJUGQwihrXgW2hUiwnPqTihPJkxGhe9s0oRmBQY05SZ0Wa8xTqnNM0hPK0SDP3uHi5xLMQ9glF6rbgBmwbZVBEQeY2nWZJLldbF6pdeockC7o7K7XC4Qrrfr1s6BJ79sYZ7ECc@k4LwgkZmtGb8KQnQbpGHibtTeHEmw/OKzyAeJWTxT3q/R60tLdo86ye1ZNTu70KNrCF0ehEUooq8TGIvRGtpTuCtQTDWuyFfMfwiGh3AGdY8zNkLszIohfK3wG2KCM@KGU3R3CoyPGDrFg4yA87CPxyHrWbMIS9tVe0j9bBWYuKaPBjYzPncHT6thkGoVrrESHuL0H1manfDwd/BP66DrGZpZEg/HPsxVrZylZ9MZiwWbsUS9PTXw "Python 3 โ€“ Try It Online") Saved 4 bytes with suggestion from [Neil](https://codegolf.stackexchange.com/users/17602/neil) ]
[Question] [ Your task is to read an image containing a handwritten digit, recognize and print out the digit. **Input:** A 28\*28 grayscale image, given as a sequence of 784 plain-text numbers from 0 to 255, separated by space. 0 means white and 255 means black. **Output:** The recognized digit. **Scoring:** I will test your program with 1000 of the images from the [MNIST database](http://yann.lecun.com/exdb/mnist/index.html) training set (converted to ASCII form). I have already selected the images (randomly), but will not publish the list. The test must finish within 1 hour, and will determine `n` - the number of correct answers. `n` must be at least 200 for your program to qualify. If the size of your source code is `s`, then your score will be calculated as `s * (1200 - n) / 1000`. Lowest score wins. **Rules:** * Your program must read the image from the standard input and write the digit to the standard output * No built-in OCR function * No third-party libraries * No external resources (files, programs, web sites) * Your program must be runnable in Linux using freely available software (Wine is acceptable if necessary) * The source code must use only ASCII characters * Please post your estimated score and a unique version number every time you modify your answer **Example input:** ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 18 18 18 126 136 175 26 166 255 247 127 0 0 0 0 0 0 0 0 0 0 0 0 30 36 94 154 170 253 253 253 253 253 225 172 253 242 195 64 0 0 0 0 0 0 0 0 0 0 0 49 238 253 253 253 253 253 253 253 253 251 93 82 82 56 39 0 0 0 0 0 0 0 0 0 0 0 0 18 219 253 253 253 253 253 198 182 247 241 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 156 107 253 253 205 11 0 43 154 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 14 1 154 253 90 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 139 253 190 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 11 190 253 70 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 35 241 225 160 108 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 81 240 253 253 119 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 186 253 253 150 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 16 93 252 253 187 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 249 253 249 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 46 130 183 253 253 207 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 39 148 229 253 253 253 250 182 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24 114 221 253 253 253 253 201 78 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23 66 213 253 253 253 253 198 81 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 171 219 253 253 253 253 195 80 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 172 226 253 253 253 253 244 133 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 136 253 253 253 212 135 132 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` By the way, if you prepend this line to the input: ``` P2 28 28 255 ``` you will obtain a valid image file in pgm format, with inverted/negated colors. This is what it looks like with correct colors: ![digit](https://i.stack.imgur.com/0ZtAi.png) **Example output:** ``` 5 ``` **Standings:** ``` No.| Name | Language | Alg | Ver | n | s | Score ---------------------------------------------------------------- 1 | Peter Taylor | GolfScript | 6D | v2 | 567 | 101 | 63.933 2 | Peter Taylor | GolfScript | 3x3 | v1 | 414 | 207 | 162.702 ``` [Answer] ## GolfScript 6D (v2: estimated score 101 \* 0.63 ~= 64) This is a very different approach to my earlier GolfScript answer, so it makes more sense to post it as a separate answer at v1 than to edit the other answer and make this v2. ``` ~]:B;569'!EM,R.==|%NL2+^=1'{{32-}%95{base}:^~\^}:&~2/{~B=<}%2^10'#]8Y,;KiZfnnRsDzPsvQ!%4C&..z,g,$m'&= ``` ### Ungolfed ``` ~]:B; [30 183 21 378 31 381 7 461 113 543 15 568] 2/{~B=<}%2base 7060456576664262556515119565486100005262700292623582181233639882 10base = ``` ### Explanation The raw problem is classification of points in a 784-dimensional space. One standard approach is dimension reduction: identifying a small subset of dimensions which provide sufficient distinguishing power to do the classification. I evaluated each dimension and each possible threshold to identify 18 pairs of (dimension, range of threshold) which looked promising. I then picked the centre of each range of threshold, and evaluated 6-element subsets of the 18 pairs. Finally I optimised the threshold for each dimension of the best 6-D projection, improving its accuracy from 56.3% to 56.6%. Because the projection is into 6 dimensions and for each dimension I apply a simple threshold, the final lookup table only needs 64 elements. It doesn't seem to be particularly compressible, so the main golfing is to base-convert both lookup tables (the list of dimension and thresholds; and the halfspace vector to digit map) and share the base-conversion code. [Answer] ## GolfScript 3x3 (v1: estimated score 207 \* 0.8 ~= 166) ``` ~]28/10:?/{zip?/{[]*0-!!}/}%2{base}:^~'"yN(YZ5B 7k{&w,M`f>wMb>}F2A#.{E6T9kNP_s 3Q?V`;Z\'C-z*kA5M@?l=^3ASH/@*@HeI@A<^)YN_bDI^hgD>jI"OUWiGct%7/U($*;h*<"r@xdTz6x~,/M:gT|\\:#cII8[lBr<%0r&y4'{32-}%95^?^2/{))*~}%= ``` Or in overview, ``` ~]28/10:?/{zip?/{[]*0-!!}/}%2{base}:^~'MAGIC STRING'{32-}%95^?^2/{))*~}%= ``` ### Explanation My approach at a high level is: 1. Threshold the pixels: if the pixel is above `t1` then set it to `1`; otherwise to `0`. 2. Group the pixels. Initially I broke the 28x28 grid into a 4x4 grid (each subgrid being 7x7 pixels); but breaking it into a 3x3 grid (subgrids being 10x10, 10x8, or 8x8 pixels) gives a massive reduction in lookup table size while dropping accuracy rate from about 56% to about 40%. 3. Sum the pixels in each group and threshold again: if the number of set pixels is above `t2` then score the group as `1`; otherwise as `0`. 4. Do a table lookup by the vector of group scores. (The table is compressed using run-length encoding and the standard base-conversion trick. Most choices of `t1` and `t2` leave between 50% and 63% of the table as "don't care" values, which can be combined with adjacent values to increase run lengths; the average run length in my v1 table is 3.6). It turns out that setting `t1=t2=0`, although not optimal, isn't far off the best values of `t1` and `t2` in terms of accuracy; is pretty good in terms of table compressibility; and allows me to combine the two thresholding operations into `[]*0-!!` (flatten 2D array to 1D; remove `0`s; check whether it's empty). The lookup table gives the most likely candidate for the given vector of group scores. It may well be possible to improve the score by identifying table entries which can be changed such that the improved compressibility of the table outweighs the decreased accuracy. ]
[Question] [ *You know how many and which kinds of chess pieces were murdered. Can you come up with* any *possibility for who killed whom and how?* ## Background During the course of a game of chess, there are between 2 and 32 pieces on the board. Call the collection of all pieces on the board (both white and black), without regard to position, the **material content** of the board. The game begins with 16 pieces per side, often represented together as `KQRRBBNNPPPPPPPPkqrrbbnnpppppppp`. (Capital letters represent white, lowercase letters represent black. The pieces are **K**ing, **Q**ueen, **R**ook, **B**ishop, k**N**ight, and **P**awn.) ## The challenge Write a program that receives as input a possible *material content* of the board, and produces as output a *legal sequence of moves* that achieves this content at the end of the sequence of moves. The program need only work for *subcollections* of the initial 32 pieces (that include the white king `K` and the black king `k`). In other words, there is no need to consider crazy situations like multiples queens per side. That also means that promotion is not *necessary*, but it is still allowed. ## Input format You may take input in a format convenient to you. For example, the following formats are acceptable: 1. A string like `KQRRBBNPPPPPPPPkqrrbbnpppppp` or `QRRBBNPPPPPPPPqrrbbnpppppp` (kings implied). 2. A list like `['Q', 'R', 'R', 'B', 'B', 'N', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'q', 'r', 'r', 'b', 'b', 'n', 'p', 'p', 'p', 'p', 'p', 'p']`. 3. A tuple of piece counts like \$(1,2,2,1,8,1,2,2,1,6)\$ representing \$(Q,R,B,N,P,q,r,b,n,p)\$ or like \$(1,1,2,2,2,2,1,1,8,6)\$ representing \$(Q,q,R,r,B,b,N,n,P,p)\$. 4. A dictionary of piece counts like `{'K': 1, 'Q': 1, 'R': 2, 'B': 2, 'N': 1, 'P': 8, 'k': 1, 'q': 1, 'r': 2, 'b': 2, 'n': 1, 'p': 6}` (or without the implied kings). 5. A string like `Nnpp` (or list `['N','n','p','p']`, or tuple \$(0,0,0,1,0,0,0,0,1,2)\$, or dictionary) representing which pieces are *missing*, or in line with the title, have been *murdered*! ## Output format The output format is also flexible, but it must be parseable by a standard game engine. That means that the following are acceptable formats: 1. Standard algebraic notation, like `Nf3 e5 Nxe5 Ne7 Nxd7 Nec6 Nxb8 Nxb8`. 2. "UCI" long algebraic notation, like `g1f3 e7e5 f3e5 g8e7 e5d7 e7c6 d7b8 c6b8`. (These sample outputs are solutions to the sample inputs before. These games appear to leave the original pieces in their starting squares, but this is not necessary nor in fact the case here.) The output can be a string or a list, or it can be output to the screen. There is no need to number your moves, but you may if you want. (However, they must of course alternate between white and black, as well as follow other rules of chess!) ## Scoring This is almost a standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question, meaning that submissions are scored by the length of the program in bytes. However, in case not all subcollections are solved correctly (whether intentionally or unintentionally), that does not invalidate a submission. Instead, an additional one byte penalty will be assessed **per** subcollection of pieces that is not solved correctly. Note that because white could have 0 or 1 queens; 0, 1, or 2 rooks; and so forth, there are \$2\cdot 3\cdot 3\cdot 3\cdot 9 = 486\$ possible material contents per color, and thus \$486^2 = 236196\$ total possible material content inputs. Thus it is strongly advisable to solve the vast majority of inputs correctly! The following program enumerates the possible inputs, and also produces the various example input formats listed above: ``` count = 0 for Q in range(2): for R in range(3): for B in range(3): for N in range(3): for P in range(9): for q in range(2): for r in range(3): for b in range(3): for n in range(3): for p in range(9): s1 = ("K" + "Q" * Q + "R" * R + "B" * B + "N" * N + "P" * P + "k" + "q" * q + "r" * r + "b" * b + "n" * n + "p" * p) s2 = ("Q" * Q + "R" * R + "B" * B + "N" * N + "P" * P + "q" * q + "r" * r + "b" * b + "n" * n + "p" * p) l1 = [piece for piece in s1] l2 = [piece for piece in s2] t1 = (Q, R, B, N, P, q, r, b, n, p) t2 = (Q, q, R, r, B, b, N, n, P, p) d1 = {"K": 1, "Q": Q, "R": R, "B": B, "N": N, "P": P, "k": 1, "q": q, "r": r, "b": b, "n": n, "p": p} d2 = {"Q": Q, "R": R, "B": B, "N": N, "P": P, "q": q, "r": r, "b": b, "n": n, "p": p} murders = ("Q" * (1-Q) + "R" * (2-R) + "B" * (2-B) + "N" * (2-N) + "P" * (8-P) + "q" * (1-q) + "r" * (2-r) + "b" * (2-b) + "n" * (2-n) + "p" * (8-p)) murderl = [piece for piece in murders] murdert1 = (1-Q, 2-R, 2-B, 2-N, 8-P, 1-q, 2-r, 2-b, 2-n, 8-p) murdert2 = (1-Q, 1-q, 2-R, 2-r, 2-B, 2-b, 2-N, 2-n, 8-P, 8-p) murderd = {"Q": 1-Q, "R": 2-R, "B": 2-B, "N": 2-N, "P": 8-P, "q": 1-q, "r": 2-r, "b": 2-b, "n": 2-n, "p": 8-p} count += 1 print(count) ``` ## Verifier The following Python3.7+ sample demonstrates how to check that a game achieves a given collection of pieces: ``` import chess import chess.pgn import io pieces = "KQRBNPkqrbnp" def piece_key(x): return pieces.find(x) def sort_pieces(ps): return sorted(ps, key=piece_key) def only_pieces(s): return filter(lambda x: piece_key(x) >= 0, s) def final_pieces(moves): board = chess.Board() for move in moves: board.push(move) return "".join(sort_pieces(only_pieces(str(board)))) def moves_from_pgn_string_parser(s): pgn = io.StringIO(s) game = chess.pgn.read_game(pgn) return game.main_line() def moves_from_uci_list(l): return [chess.Move.from_uci(x) for x in l] def moves_from_uci_string(s): return moves_from_uci_list(s.split()) print(final_pieces(moves_from_pgn_string_parser( "1. Nf3 e5 2. Nxe5 Ne7 3. Nxd7 Nec6 4. Nxb8 Nxb8"))) # KQRRBBNPPPPPPPPkqrrbbnpppppp print(final_pieces(moves_from_uci_list( ["g1f3", "e7e5", "f3e5", "g8e7", "e5d7", "e7c6", "d7b8", "c6b8"]))) # KQRRBBNPPPPPPPPkqrrbbnpppppp ``` ## Potential clarifications * Pieces with the same name and color, such as the two white rooks, are indistinguishable. That is, you need not ensure that the a1 rook specifically be killed. * The input format is quite flexible. If you wish to have the black pieces before the white, or the pieces in alphabetical order, you're welcome to. * The output games need not be the simplest or shortest possible in any sense; they must merely be legal. Intricacies like the fifty-move/seventy-five-move rule, draw by threefold/fivefold repetition, and insufficient material may be ignored. Key rules like *check*, *checkmate*, and *stalemate* may not be ignored. * The output game need not terminate with mate. It can just end after an arbitrary move. * You *may* use chess libraries available in your language or platform. [Answer] # JavaScript (ES10), ~~499~~ 450 bytes Expects `[[q,r,b,n,p], [Q,R,B,N,P]]`, where each variable is the number of missing pieces. Returns an array of strings in standard algebraic notation. ``` M=>M.map((a,w)=>a.map(h=(v,i)=>v--?[(q=[...'002//2770/222/2772/220/000//27n0/0n02/b77/277b/20/2n22/b7b/b0b'.split`/`[i*2+v]].map(d=>"abcdefgh"[y=(s+=parseInt(d,36)-17)>>3,s%8]+(w?1+y:8-y),s=52),c=q.pop())?[...q,"x"+c,q.reverse(),w?'e7':'e2']:q,h(v,i)]:[]).flat(10).map((s,i)=>o+=w?(i&1?"Ne2N":"Ng1N")+s:"N"+s+(i&1?S:"Ng8")),o=S="Ne7")&&`a3a6c4c5e3e6g4g5h3h6Ne2${o}Ng3Ng6Nf5Nf4${b=M[1][3]>1?'Ne2Kxe2':'',M[0][3]>1?S+b+`Kxe7`:'Ng3'+b}`.split(/(?<=\d)/) ``` [Try it online!](https://tio.run/##PVDNjpswEL7nKSy0Xdv1BIxJQkRrkHqrqqC2ORKkAHEIKwokpslGq3321JBtjGTm@5nxzLxk50wXp6rrp027U7e9vK1kuLL/ZB0hGVyoDLMRHCQ5Q2XgeTqNEnKUiW3bmHPhOML3uSOEGAJzCe5wzge6MVFjHLnvD1ruGEk0YiByJ@c5tnVXV/3W2SbVZ8HOaTo@tZOhleXFTu3Lg5VcJdFMdtlJq@9NT3bgLejU9WkYeqA/LVNGLpHLrsFyeqWg5VxQKOTR7tqOUBoNXR7BerVYAUf7pM7K1CEULhFWPg6wEjgNjnAYh0uDJKX2vs564nJ634Eeh26ZvESkenYjK1YitgIrLt3YokybyGKajdp6oJcWpdDKtTRO36LPz9vMyxbFrJgrTy3KWTk/eIeFqfL01r7HpReXi3g/j/ezp7dcrhI3Tbw0dCNsHD9eTXsBxrBK@Ae9ZjnbGt7fBtgkY5a/b@9bJA6JvsrNjjr01ivdI4lIDuhCkQzR2wShWvVIG3ZPkoE3k760VUMwwvSLkYu20W2t7LotiTab6uqsUMTZrBlB5qKRU8KQHyLGKsQQthE2Pw2oMkU5HahNg@nkfTJxHGTOEU6QQwPdAH7Bb/gGMfycDM2RhMP9c1NAD8BTikyui4qs6/@e1MPrGlHAcvDeQwHzu1c8zPrD7Y7yw/0fjO6srpHHHxm3fw "JavaScript (Node.js) โ€“ Try It Online") ### How? 1. We first play **1. a3 a6 2. c4 c5 3. e3 e6 4. g4 g5 5. h3 h6 6. Ne2 Ne7**: [![position 1](https://i.stack.imgur.com/erSVj.png)](https://i.stack.imgur.com/erSVj.png) 2. The White king's knight follows some pre-computed paths to capture each Black piece except the Black king's knight, avoiding the squares **c7**, **d6**, **f6** and **g7** that would put the Black king in check. It also avoids **c3**, because **Nc3** would be ambiguous. It goes back to **e2** after each capture. Meanwhile, the Black king's knight moves back and forth between **e7** and **g8** and ends up on **e7**. For instance, to capture the queen: **7. Nd4 Ng8 8. Nc6 Ne7 9. Nxd8 Ng8 10. Nc6 Ne7 11. Nd4 Ng8 12. Ne2 Ne7** 3. We do the same thing with the Black king's knight. 4. We play **Ng3 Ng6** / **Nf5 Nf4**: [![position 2](https://i.stack.imgur.com/e8N87.png)](https://i.stack.imgur.com/e8N87.png) **Note:** All pieces are shown in the above diagram, but only the kings and the king's knights are guaranteed to still be on the board at this point. 5. White play **Ne7** if the White king's knight has to be captured, or **Ng3** otherwise. This is followed by **Ne2 Kxe2** if the Black king's knight has to be captured. Finally, Black play **... Kxe7** if the White king's knight has to be captured. *Images generated with [www.365chess.com](https://www.365chess.com/board_editor.php).* [Answer] # Python 3.7+, 299 bytes Expects a dictionary like `{'K': 1, 'Q': 1, 'R': 2, 'B': 2, 'N': 2, 'P': 6, 'k': 1, 'q': 1, 'r': 2, 'b': 2, 'n': 2, 'p': 5}` indicating how many of each piece should remain at the end of the game. Outputs a game in standard algebraic notation, complete with move numbering, like `1. d4 a6 2. g4 a5 3. c3 d5 4. Bd2 f6 5. c4 e5 6. b4 Nc6 7. e3 Nge7 8. f4 Bxg4 9. Bd3 b6 10. Qc2 Ng6 11. fxe5 Qe7 12. exf6 dxc4 13. Nc3 Rg8 14. Bxc4`. Obeys the trickier rules of chess, including the 75-move rule, repetition, and insufficient mating material. On average, takes approximately one second per desired material content on my computer; I have checked all possible inputs. ``` from chess import* from random import* S=Board def f(t): seed(0);b=S() while 1: for m in choices([*b.legal_moves],k=9): b.push(m) if max(d:=[str(b).count(x)-t[x]for x in t])<1:return S().variation_san(b.move_stack) if b.is_game_over()+b.is_check()-min(d)<1:break b.pop() else:b=S() ``` ## How? Beginning at the starting position , we randomly play moves. A move is not played if it results in too few of a desired piece on the board. (That is, we pick another random move instead, up to nine times before giving up.) A move is also not played if it results in check or any game-ending condition (checkmate, stalemate, draw by 75-move-rule, etc), except on the final move. Promotions are played occasionally, just like any other move, if the pawn is not necessary for the desired material content. There is no backtracking of individual moves beyond this "one move lookahead" mentioned already; in the event of failure, we restart from the beginning with a fresh starting board and fresh random moves. The function is deterministic because we explicitly set the seed to 0. As a result, most of the games begin exactly the same, differing only when a capture is or is not allowed to be made, or when the entire attempt is a failure and we have to start over. *PS*. When I started working on this challenge, I planned on a knight-based approach like [Arnauld's](https://codegolf.stackexchange.com/a/216406/49643). I didn't know whether random would work out, but I'm glad it did! ## Example games * [Kk](https://lichess.org/RlIemnPt): Reaching King versus king takes 166 moves and features 3 promotions, to two white rooks and a black bishop. * [KBkqrr](https://lichess.org/fC3DAk3x): Features 6 promotions (to `RRnbNQ`) in 282 moves ending in check. * [KRNPPPk](https://lichess.org/fKj7Frmc): Three promotions to black queens. White ends with three pawns on the seventh rank, but doesn't promote any because they're part of the desired material content. * [KQRRBNNPPPPPPPkrbnppppp](https://lichess.org/48xitDdZ#83): Mate in 42. * [KQBNNPPPPkqrbppppppp](https://lichess.org/gfFk8mCV#21): Features capture en passant on move 21. * [KQRRBNNPPPPPPPPkrrbnppppppp](https://lichess.org/VxA7KaLC): Both sides castle, consecutively but in opposite directions. * [KQRRBBNNPPPPPPPkrnnppp](https://lichess.org/RrOUo0Qe): Knight delivers mate. ]