text
stringlengths
180
608k
[Question] [ ## Background Roman numeral is a simple number system with the following properties: * Each symbol in the system maps to a specific value. (e.g. `I = 1, V = 5, X = 10, C = 100`) * The value of a Roman numeral can be evaluated as follows: + First, find all occurrences of adjacent pairs of symbols where a strictly smaller-valued symbol comes first (e.g. `IV`, `XC`). Each such pair is evaluated as the backward difference of two values (e.g. `IV = 5 - 1 = 4`). + Then, interpret the remaining symbols as-is and sum all values in it. ``` MMCMXCIV = M + M + CM + XC + IV = 1000 + 1000 + (1000 - 100) + (100 - 10) + (5 - 1) = 2994 ``` ## Task Your job is to write a function/program \$F\$ that takes a positive integer \$n\$ and generates a code fragment \$F(n)\$ (not necessarily in the same language). The outputted code fragments must have the following properties: * \$F(n)\$ as a full program must output the number \$n\$. * \$F(a)+\!\!\!+\,F(b)\$ as a program (where \$+\!\!+\$ means concatenation) must output \$a+b\$ if \$a≥b\$, \$b−a\$ otherwise. * This must extend to any number of code fragments emitted by your program in the way that \$b−a\$ cases take precedence (think of an arithmetic expression with `+`s and `-`s, but the two sides of `-`s are flipped and it has higher precedence than `+`). + You do not need to consider the cases where three consecutive input numbers are strictly increasing (the equivalent arithmetic expression has two consecutive `-`s). Your score is the byte count of \$F\$. Shortest code in bytes wins. ## Example If \$F(10)\$ outputs the code fragment `ABC`, and \$F(3)\$ outputs the code fragment `xyz`: * The program `ABC` should output 10. * The program `xyz` should output 3. * The program `ABCxyz` should output 13. * The program `xyzABC` should output 7. * The program `ABCABCABC` should output 30. * The program `ABCABCxyzxyzABCxyzxyzABC` should output 40, since ``` [10, 10, 3, 3, 10, 3, 3, 10] => 10 + 10 + 3 + (10-3) + 3 + (10-3) = 40 ``` Additionally, if \$F(8)\$ outputs the code fragment `****`: * The program `ABC****xyz` should output `10 + 8 + 3 = 21`. * The program `****ABCxyz` should output `(10-8) + 3 = 5`. * The program `xyz********ABC` should output `(8-3) + (10-8) = 7`. * You do not need to consider the program `xyz****ABC`, which contains three consecutive strictly increasing numbers (3, 8, 10). [Answer] # Bash, ~~54~~ 48 bytes *-6 bytes by adapting Dominic van Essen's output-prevention trick* ``` printf ":|: ((s+=p<$1?$1-2*p:$1)) p=$1 echo \$s" ``` This assumes the program must not have any excess output, which turns out to be one of the tricker parts. I expect one of the golfing languages that will output by default at the end of the program would do best here. [Try it online!](https://tio.run/##TY7LCsIwEEX38xWXMItGKTRmU6rFH3HTR2oLkoRWsKB@e0xQ0dU9c@fATNssYzgbm0ncg58nex0gqkdFWbZsa39gdWSV7za@YiUl@ZoVmW50OPEiwpNu43QxmE3T4zJZs0fvCOhcb2ohIg1uxorJgv/WX4FTcBbPg1eZ9N5ZE6ONXyHv8DYEpTqogjSpApo0IkdKA/QvUlfGfYmPViIhvQA "Bash – Try It Online") ## Explanation Example output for `3` concatenated with output for `10` (the concatenated program outputs `7`): ``` :|: ((s+=p<3?3-2*p:3)) p=3 echo $s:|: ((s+=p<10?10-2*p:10)) p=10 echo $s ``` * `:|:` prevents any `echo` from a previous fragment from outputting * `s` is the sum value so far (implicitly 0 at the start of the program) * `p` is the previous value Each fragment assumes that the current value is not less than the next value, and thus adds it to the sum. It also checks whether the previous fragment was wrong to assume this (ie. the previous value was less than the current value), and if so corrects the sum by subtracting double the previous value. [Answer] # [R](https://www.r-project.org/), ~~65~~ 57 bytes ``` cat("d=e=F;F=c(",scan(),",F);a=sum(F*(-1)^(F<c(e,0)));a") ``` [Try it online!](https://tio.run/##zY9Ra8IwEMff8ymO@JIbFVoiDFr7mk8xhBhPLLhE0qv67bs2wqYbbFQZ@HIkd7nf/5fY986ykpuaalOZ2imZtc56hZnMDFa2brt3ZV7UvMCVMkunKMsRh4HEvsiFSNtvXqKYQej40DFsQ4TGj6ewBV2KuwOEvuX7cAKmlqHhMl2ZSvBEG@AAkVpiONrY2PWewMCa@ETkgazbXdZi50UcwrBK1LFXQpEn@pff0IHfzcRPiv4O0dMZQ64ei6LzgRxD8YqT1SYYPPjjT91UrrT14mm0/x/759v@Aw "R – Try It Online") **How it works (original version)** For an example input of 3, the output is: ``` d=0;F=c(F, 3 );a=sum(F*(-1)^(F<c(F[-1],0)));a ``` (note: no trailing newline) What do the different bits do? * `d=0` = appends to the last code fragment (if any). This has the effect of changing the final `a` (output the contents of `a`) to `ad=0` (assign zero to variable `ad`), and thereby supresses output from all non-final code fragments. * `F=c(F, 3 )` = append the input value to the list `F`. `F` is a shortcut in [R](https://www.r-project.org/) for `FALSE`, so it's initialized to zero. So, after all the code fragments are pasted together, `F` will contain all the input integers, followed by zero. * `a=sum(F*(-1)^(F<c(F[-1],0)))` = calculate the sum of all the input integers, switching the sign of any that are immediately followed by a larger value. Luckily the last value is zero, so this won't happen to the final input integer. Assign the answer to variable `a`. * `a` = Finally, output the answer `a` (but if there's a following code fragment, this'll get changed to `ad=0` and nothing output yet... see the start) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~26~~ 24 bytes Full program. Prompts for number from stdin, and prints program to stdout. ``` '{⍺←+/⊢ׯ1*2</,∘0⋄⍺,⍵}'⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@fWpaY86htwqPePq6Cosy8EiC7@lHfVCClrq7wqLtFAcJ51Lu1lutRRxtYuncXEOk86p0KEv2vDhZom6Ct/6hr0eHph9YbahnZ6Os86phhANQPUbm1Vh2o@b8bxKZHXc2Petc86t1yaL3xo7aJQBuCg5yBZIiHZ/B/sCsUHJ2cgWrdFAwNuEAuBPG5IA5UqKisAksZQ2SAXJhMQVF@elFiLlAWqFwHJAFWARXGVAVUoQMyGL8qkFlQTKRKkLlQs5HZWHWDwhSOQN6yUFB41DtXQUlLSSGzWCEvv0QhUQGoLzNFITMlNa8kMy0ztUghOSOxKDG5JLUIYiayIdidhayCiJBBUU58YKJoQzeDVP3oWgA "APL (Dyalog Unicode) – Try It Online") (slightly modified version for ease of use) The generating program simply prepends a special string to the left of the input number (or numbers, actually). The special string is an anonymous ambivalent (infix/prefix) lambda. Compound programs will consist of numbers separated by this lambda, with an additional lambda on the far left. With infix usage, the lambda amounts to simple concatenation. With prefix usage, the lambda evaluates Roman numbers. APL evaluates from right to left, so a compound statement will simply concatenate number values until finally the list is evaluated as a Roman number. The lambda is as follows: `{`…`}` dfn; arguments are `⍺` (left, optional) and `⍵` (right):  `⍺←` if the left argument is undefined (i.e. we are being called monadically, as a prefix lambda), give the following tacit function value to it:  `+/` the sum of…  `⊢` the argument array…  `×` times (element-wise)…  `¯1*` negative one raised to the power of (element-wise)…  `2</` the pair-wise less-than of…  `,∘0` the argument prepended to a zero  `⋄` now, with the supplied or the default `⍺` evaluate:   `⍺,⍵` with a supplied left argument the concatenation of the arguments   `⍺,⍵` with the default argument the tacit function applied to the ravel (flattened ― a no-op) right argument [Answer] # [JavaScript (V8)](https://v8.dev/), 66 bytes ``` n=>`t=this;s=~~t.s-(t.p<${n}&&2*p)+(p=${n}),{get x(){print(s)}}.x` ``` [Try it online!](https://tio.run/##XY9hb4MgEIa/8yvuw1KhtUTnF5OO/RFnUmNhtWmByMU0MfavO4E2cyOBu@d97zi4NEPj2r6zuB/KWYlZi88jCjx37uDE44Hc7Sly@/E26mmzed9atqNWeGLp@C0R7pSNtu80Usemid@PcyRF84wx8oJiyUlrtENA6dCBgIpUeVanpCr8kWcp@F348E8o/mYvt1zY5@XTDncFOSg1qQlRpgf6OxeMivMZjASWFa3WnOTyIu/wW2OpYvxiOk2ThIWq@IvkSyewC1Vr2TdHPsmrRAm4BrcGG0AOzfXZNc0/ "JavaScript (V8) – Try It Online") The core idea is putting the `print()` behind a getter function. If the `.x` property is accessed it will print the total `s`. This is placed at the end of the generated code so that it accesses `.x` on the last iteration and when concatenated it becomes `.xt=this` (does not access `.x`). [Answer] # [Zsh](https://www.zsh.org/), ~~34~~ 32 bytes ``` <<<"((s+=p<$1?$1-2*p:$1));p=$1;" ``` ~~[Try it online](https://tio.run/##bU7BToQwFLzzFRNspF0lkeVCdkG/wJM3jQeEV9pkt5BtSVaN344toO7BpOlMpzNv3odVU0eGi8@pLMuYc3tTDSXLHliWbjfDjmW3Q@UvK8Q@nr4i2Z/gyDrwCEiyuyRAniwPLCTHqnsliMj/4EcvVm@Bi1iBYraIeXqoOoOzKvSJfdO3VMUsAON@ZbCziCPvu0Jtre4MXA85msbp3oT4Su2LfK3m2GJ2dDjg2So4pS38qXGsnfo3ivQRcok9EaGlt7Gb93KKMJy0cdT@uv231EYHuvMR9z6QJYdUQuL@eruMGS1dNlGjejDOIbmAEJGYom8 "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##bU7BToQwFLzzFRNspNWQyHIhC@gXePKm8YDwSpvsFrItyarx27EF1D2YNJl505k378OquSfDxedcVVXMub2tx4plDyxLdzfjnmVClGPNsjKevyI5nODIOvAISLK7JECerANWkmPTvRJE5H/woxebt8BFrECxWMSyPVSdwVkd@kTZDh3VMQvAuD8Y7CziyPuu0FirewM3QE6mdXowIb5R@yJf6yW2mh0dDni2Ck5pC/8aHBun/o0ifYRcY09E6Oht6pe7nCKMJ20cdb9u/y210YHufcS9j2TJIZWQuL/erWsmS5dN1KoBjHNILiBEJOboGw "Zsh – Try It Online") Adapted from [Vitrivius's Bash answer](https://codegolf.stackexchange.com/a/220435/86147) (go upvote it too!), shorted considerably by taking advantage of Zsh's math function functionality (Math functions are defined to output the result of the last math expression, which means we don't need to worry about supressing output.) [Answer] # [Perl 5](https://www.perl.org/) (`-lp`), ~~39~~ 35 bytes -4 bytes thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) ``` $_='}{$\-=2*$p*($p<'."$_)-(\$p=$_)" ``` * `-lp` switch (enable line ending processing;assume loop like -n but print line also, like sed) * generated code starts with `}{` : which closes the loop block and start a new block which is executed after the loop * `-=`, `$p=..` rewriting so that affectation is executed after operation and comparison [Try it online!](https://tio.run/##K0gtyjH9r5JsW6jxXyXeVr22WiVG19ZIS6VAS0OlwEZdT0klXlNXI0alwBbIUPqvaa3irGebWpaYo5JszcUFUm6rpOLMpaSXUAA0SkE3pyBVQV3FWT3hv6EBlyGXocG//IKSzPy84v9AKQA "Perl 5 – Try It Online") [Answer] # Java, 696 bytes ``` n->"import java.util.*;import java.io.*;import java.util.jar.*;interface Main{List<Integer>l=new ArrayList();static void main(String[]a)throws Exception{var z=Main.class.getPackageName();for(var e:System.getProperty(\"java.class.path\").split(System.getProperty(\"path.separator\"))){if(!e.endsWith(\".jar\")){var b=new File(e+File.separatorChar+z);var d=b.listFiles();Arrays.sort(d);for(var f:d){var n=f.getName();if(n.endsWith(\".class\")){Class.forName(n.substring(0,n.length()-6));}}}}int s=0;for(int i=0;i<l.size();i++)s+=l.get(i)-(i>0&&l.get(i)>l.get(i-1)?l.get(i-1)*2:0);System.out.print(s);}}\nclass _"+new java.util.Date().getTime()+"_"+System.nanoTime()+"{static{Main.l.add("+n+");}}//" ``` The `Main` interface has a static `List` field which all the generated classes add an integer to in their static initializer. The main method attempts to load all the classes in the package to run their static initializers. `F(a)` will return different values each time since it tries to make the class names unique using the current time, so `F(a) + F(a)` cannot be shortened by using a variable to store the result of `F(a)`. [Generator](https://tio.run/##jVJRb9MwEH7frzB5mOyFeh1IPDRNERpMQgKENCQeKELXxEnduXZku93aqL@9nJ2UlqlI@MWX83fffd/lFrCGwaJ82DermZIFKRQ4Rz6D1KS9IHj6vPPg8VobWZIlvtJ7b6Wuf/wkYGvHOmw4CyTkKy8Vr1a68NJo/lH7uz4ed2UTUuV7PZgkctkY60@KrrLTlDTPEhGzABvS2gtbQSGi2vaTdH6MnUQt7ETlWjySd9bCJuQpy/6pH5ifW/PoyIenQjRBY7sGS7Z5YOVxHLwW/isUD1CLL7AUyFYZSwNKjO43zotlRFjTCOs3dJpEqV1pA34@TRh3jZKenkUHCHeiAQveWAQz1sqKvhBc6NJ9l36OoGA6PEVxs2jvTipBRRquY/ntHGy6ZVmAlfmMK7QfEA5Vx3k47nCatDyaqEZlR6vzKkjrPaIE/ZeCaChquI3WsD5CNXermYvjpMOXmiuha6xggzeMZTs8@KeIy4exYYglxnKsuJPb2ChNmUtzFXpTyQZUToaXl4fPSR8MbtjbY3j1ajRkWT9Os/K8wfaeutBwqrsl/pWkYUzHvXkPHvsFjm8yWEwThPQcGrQ5ZNtuWdq4AYpDWVKkSpNAfn2d7A@rnv1Z@m6ZiMEBQtOoDb0ZsvRc/Pps@F@Ik27PbCtNTf@8u9jtfwM) [Generated Program](https://tio.run/##7ZVda9swFIbv9yu8XBSpXlR/x47rjFE6GHRj0ItdjFEUW3aUOrKRlHSJ2W9PJSUjZZTdbbmRwfj4@D06H3qwlniDx8vqcb@nq77j0lkqB1pL2qLL/KWLdn84jGaJuXYzSXiNS@J8xpQNd1TI60/K1xA@awtGnpwPnOOt9gOYC4klLZ1NRytnpfTgXnLKmu8/MJQL3j0J5/ZnSXpJOzZsMHd2hV4VlS0WAjVEfsXlI27IF7wiarW640CryPR@KyRZGQXvesLlFoxMpYfIHsvFCCLRt1SC17RagATpMcey4yMI4UBr8JYgwirxjcoFGOl@1QdT1tw09pG2BBBXP06xNwvM3R3Mtawq5qhVjWuFUPWaSQgk1BxBdSq/nlaHZVlR67KO3akC2Mv8phVdwY3pSUUbIUNiPRdmjMB7x1BLWKP0cJxAmP9Sl9ohRxSeSadtqmx63SJBdyaN60LhFq3ODCgcAzrzLi5@v86OxtiH70/mZTD1YH4cZLeWqFfpJRA64RtTp/PgJ34c@lHsx0ESPSRREvpZGARpnGTBcOBgMJvbIlxVwPd08NWVRdGi@A9RzIIjinGWplHmhRZFi@L5UVR3nL6CYmhJtCT@TxIzL5okiSXRknh2Ev1gkmb2eLYonh/FwJt4sf0pWhLPTmIU@pPQkmhJPDuJcZgE6V@O5/3@GQ) [Answer] # Python 3.7.3 (outputs Python 3.7.3), 174 bytes ``` import sys;print("""R=%s class A(): def __del__(s):print(a) if"a"in locals(): if"p"in locals()and p<R:a-=p+p-R else:a+=R if"v"not in locals():v=A();a=R p=R"""%sys.argv[1]) ``` More readable version of the code: ``` import sys print(""" number = %s class PrintOnExit(): def __del__(self): # This object will only be destroyed when the interpreter exits print(result) if "result" in locals(): if "previous" in locals() and previous < number: result -= previous result += number - previous else: result += number if "print_on_destroy" not in locals(): print_on_destroy = PrintOnExit() result = number previous = number """ % sys.argv[1]) ``` ``` [Answer] # [Julia](http://julialang.org/) REPL, 50 bytes adapted from [Dominic's answer](https://codegolf.stackexchange.com/a/220436/98541) ``` x->"L=0;L=[L;$x];a=sum(L.*(-1).^[diff(L).>0;0]);a" ``` [Try it online!](https://tio.run/##XU5BCsMgELzvKyT0oKUVJZeA2GNP9gViQRoDhjQpMS35faq2oaTCujszy@y0z85bPi9nuczHU6EkE0pqJXazEVaG5x0rusdHTuhV175psCL0xAQzRNhieYy@n7oenzFnhMAPlhHB5MIUkEQaNGfmALpMH2cHlKpM7Y8ot9OqVhGnufrK2SvTmTFgAJphROkg8n3uAVB8t6F2MUE7@JiK4iTEZElZs25RXtgwyWHLuJft8MVNlj7sGNxnI7q6vgZY3g "Julia 1.0 – Try It Online") # [Julia](http://julialang.org/), 68 bytes Basically the same with a `print` that erases the previous line (doesn't work in TIO) ``` x->"L=0;L=[L;$x];print(\"\\r\\e[K\",sum(L.*(-1).^[diff(L).>0;0]));L" ``` [Try it online!](https://tio.run/##XY7RCsIgFIbvz1PI6EJjibKbQNZlN9kTqMFoDhxri7lib7/UiliCnvP/nx7/9tG5is/LsVzm3SGTJROyVFJsZiPuo@snrDOtR62tOuks948blnSLd5zQi6pd02BJ6IEJZggRMlvSm67HR8wZIfCTRVAwWT95VCIFijOTgyriwVmO4i5i@TOKdfel@6Bjv//gNCvZyTFgAJphRPFD5PpUPaCwrkNtQ4J2cCEVxRGEZJF8s65VurBy4oS3Y59Vh892qui9Gr19EwK2rwGWFw "Julia 1.0 – Try It Online") [Answer] ## JavaScript (ES6), generates [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes ``` f= n=>`⎚⊞υI${n}IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι` ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Explanation: ``` ⎚ ``` Clears the canvas of the previous output. ``` ⊞υI${n} ``` Takes the stringified value, casts it back to integer, and pushes it to the predefined empty list. ``` IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι ``` Compares each element of the list with the next element, negating the element if it is smaller, then prints the final sum. Example: F(10) is `⎚⊞υI10IΣEυ⎇‹ι§⁺…υ¹υκ±ιι`, while F(3) is `⎚⊞υI3IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`. The last example is therefore `⎚⊞υI10IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI10IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI3IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI3IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI10IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI3IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI3IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι⎚⊞υI10IΣEυ⎇‹ι§⁺υ⮌υ⊕κ±ιι`. [Try it online!](https://tio.run/##S85ILErOT8z5//9R36xHXfPOt77fs9LQAEicW/x@z9LzrY/62h817Dy389DyR427gNx1PUCia@q5XYc2ngMKU6zLmG6ahpH7/v8HAA "Charcoal – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~17~~ ~~16~~ ~~15~~ 14 bytes ``` ⁶,y“_< ×ḤƲɼ+ © ``` [Try it online!](https://tio.run/##y0rNyan8//9R4zadykcNc@JtFA5Pf7hjybFNJ/doKxxa@ahh7v/D7Y@a1rg93NkS9v9/tKGBjgIIG4MRMisWAA "Jelly – Try It Online") The TIO version has an extra closing quote which can be omitted, but that breaks the footer, so I left it in; that's why it displays 15 bytes. ## Explanation ``` ⁶,y“_< ×ḤƲɼ+ © Main monadic link ⁶ " " , [" ", n] y In the following string, replace " " with n “ { Value implicitly starts at 0 Register implicitly starts at 0 _ Subtract from the current value ɼ the result of applying this to the register Ʋ ( < Is it smaller than n? (no -> 0, yes -> 1) × Multiply that by Ḥ twice the register Ʋ ) + Add n to the current value © and copy n to the register } ``` [Answer] ### Python 3, 120 bytes ``` lambda n:f"""import atexit as a try: z[-1]*=1-2*(z[-1]<{n}) except: z=[];a.register(lambda:print(sum(z))) z+=[{n}] """ ``` The lambda function returns the code snippet using a f-string. In the snippet, `z` is a list of the "Roman Numerals". In the `try` block, the code negates the last number in `z` if it is less than the current number `n`. If `z` doesn't exist yet an exception is thrown and caught by the `except`, where `z` is initialized to an empty list and a lambda function is registered with `atexit`. Lastly, the new number as appended to `z`. When the interpreter exits, the registered lambda print the sum of `z`. ]
[Question] [ The reverse-then-add (RTA) sequence is a sequence obtained by adding a number to its reverse, and repeating the process on the result. For eg., $$ 5 + 5 = 10 \Rightarrow 10 + 01 = 11 \Rightarrow 11 + 11 = 22 \Rightarrow 22 + 22 = 44 \Rightarrow\text{ }... $$ Thus, 5's RTA sequence contains 10, 11, 22, 44, 88, 176, etc. The *RTA root* of a number \$n\$ is the smallest number that is either equal to \$n\$ or gives raise to \$n\$ in its RTA sequence. For eg., 44 is found in the RTA sequence of 5, 10, 11, 13, 22, 31, etc. Of these, 5 is the smallest, and hence RTAroot(44) = 5. 72 is not part of any number's RTA sequence, and so is considered its own RTA root. **Input** is a positive integer in a range that your language can naturally handle. **Output** is the RTA root of the given number, as defined above. ### Test cases ``` Input Output 44 5 72 72 132 3 143 49 1111 1 999 999 ``` Related OEIS: [A067031](http://oeis.org/A067031). The output will be a number from this sequence. [Answer] # ~~[Perl 6](https://github.com/nxadm/rakudo-pkg)~~ Raku, ~~45 44~~ 39 bytes ``` {+(1...{$_∈($^a,{$_+.flip}...*>$_)})} ``` [Try it online!](https://tio.run/##NUvNCoMwDL7nKYKUoVM7tN1GGcoeYueJAwtlnYrVwxDvPudexGUyQ5Iv30/aqrOn5fXGncYMlzH0E875yIrPPPvsXkZ0hlxb006k73NWBFMwLYOr8Fa5/gJAv9eeTkf/1tSVI621Zf1XD4K4brotFOfITB0ha4ae9oOSTxwB0TjUfkhesJkeEczylXkwwSIlHAHO6a8hESkIAilAKkIqSACUUuvE8Rc "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous code block +(1... ) # Find the first integer { } # Where $_∈ # The input is an element of ( ... ) # A sequence defined by $^b, # The first element is the number we're checking {$_+.flip} # Each element is the previous element plus its reverse *>$_ # The last element is larger than the input ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 22 bytes ``` {~{ℕ≤.&≜↔;?+}{|↰₁}|}ᶠ⌋ ``` * 2 bytes thanks to sundar noticing that I had a `{{` and `}}` # Explanation ``` -- f(n): -- g(x): { -- h(y): ~ -- get z where k(z) = y { -- k(z): ℕ≤. -- z>=0 and z<=k(z) (constrain so it doesn't keep looking) &≜ -- label input (avoiding infinite stuff) ↔;?+ -- return z+reverse(z) } -- { -- |↰₁ -- return z and h(z) (as in returning either) } -- | -- return h(x) or x (as in returning either) } -- ᶠ -- get all possible answers for g(n) ⌋ -- return smallest of them ``` sorry for the wonky explanation, this is the best i could come up with [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7qu@lHL1EedS/TUHnXOedQ2xdpeu7a65lHbhkdNjbU1tQ@3LXjU0/3/vyEQ/I8CAA "Brachylog – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ 57 bytes -2 bytes thanks to [user1472751](https://codegolf.stackexchange.com/users/65900/user1472751?tab=profile) (using a second `until` instead of list-comprehension & `head`)! ``` f n=until((n==).until(>=n)((+)<*>read.reverse.show))(+1)1 ``` [Try it online!](https://tio.run/##JY1BC4JAEIXv/opBOsykLW0KYbheutapY0UIbSnpKLtr/Xxb9cHAx7wHX1Xaj26acXwBq4Fd3SCyUiQWLhQTYkT5ujC6fAqjv9pYLWzV/YgwkiTHtqwZFLRlf34A3nhTQD@4izMnhhVMS2CIIgjBN@FE8w@9kQgCmCIA8eC0dZY8TypaCpXn8Nbu2LHT7GwQzCOvu6ZpvN/FMvGXJrH0ibMsu49yK/8 "Haskell – Try It Online") ## Explanation This will evaluate to `True` for any RTA-root: ``` (n==) . until (n<=) ((+)<*>read.reverse.show) ``` The term `(+)<*>read.reverse.show` is a golfed version of ``` \r-> r + read (reverse $ show r) ``` which adds a number to itself reversed. The function `until` repeatedly applies `(+)<*>read.reverse.show` until it exceeds our target. Wrapping all of this in yet another `until` starting off with `1` and adding 1 with `(+1)` will find the first RTA-root. If there is no proper RTA-root of `n`, we eventually get to `n` where `until` doesn't apply the function since `n<=n`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Using the new version of 05AB1E (rewritten in Elixir). ### Code ``` L.ΔλjÂ+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fR@/clHO7sw43af//b2ICAA "05AB1E – Try It Online") ### Explanation ``` L # Create the list [1, ..., input] .Δ # Iterate over each value and return the first value that returns a truthy value for: λ # Where the base case is the current value, compute the following sequence: Â+ # Pop a(n - 1) and bifurcate (duplicate and reverse duplicate) and sum them up. # This gives us: a(0) = value, a(n) = a(n - 1) + reversed(a(n - 1)) j # A λ-generator with the 'j' flag, which pops a value (in this case the input) # and check whether the value exists in the sequence. Since these sequences will be # infinitely long, this will only work strictly non-decreasing lists. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes ``` ṚḌ+ƊС€œi¹Ḣ ``` This is a full program. Run time is roughly quadratic; test cases \$999\$ and \$1111\$ time out on TIO. *Thanks to @JonathanAllan for golfing off 1 byte!* [Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bma4biMK8aKw5DCoeKCrMWTacK54bii////MTQz "Jelly – Try It Online") ### How it works ``` ṚḌ+ƊС€œi¹Ḣ Main link. Argument: n € Map the link to the left over [1, ..., n]. С For each k, call the link to the left n times. Return the array of k and the link's n return values. Ɗ Combine the three links to the left into a monadic link. Argument: j Ṛ Promote j to its digit array and reverse it. Ḍ Undecimal; convert the resulting digit array to integer. + Add the result to j. œi¹ Find the first multindimensional index of n. Ḣ Head; extract the first coordinate. ``` [Answer] ## Ruby, ~~66~~ 57 bytes ``` f=->n{(1..n).map{|m|m+(m.digits*'').to_i==n ?f[m]:n}.min} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vWsNQTy9PUy83saC6JrcmV1sjVy8lMz2zpFhLXV1TryQ/PtPWNk/BPi06N9Yqr1YvNzOv9n@BQrSJiY65kY6hMRCbGOsYAoGOpaVlLMgcDbU0zf8A) Recursive function that repeatedly "undoes" the RTA operation until arriving at a number that can't be produced by it, then returns the minimum. Instead of using `filter`, which is long, I instead simply `map` over the range from 1 to the number. For each *m* in this range, if *m + rev(m)* is the number, it calls the function recursively on *m*; otherwise, it returns *n*. This both removes the need for a `filter` and gives us a base case of *f(n) = n* for free. Highlights include saving a byte with `Integer#digits`: ``` m.to_s.reverse.to_i (m.digits*'').to_i eval(m.digits*'') ``` The last one would be a byte shorter, but sadly, Ruby parses numbers starting with `0` as octal. [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` f=lambda n,i=1,k=1:i*(k==n)or f(n,i+(k>n),[k+int(`k`[::-1]),i+1][k>n]) ``` [Try it online!](https://tio.run/##FU3BCoMwFLvvK95FbGcdqxaGhfojIuimske1lbY7@PXuGUgOSUj2I329q07cdh8SxCPeiI84pzB/fiGidytumJh8Evi5mHXc3tMITqCRwhqp8c6sMY77AAsju2C2dVx0tkCX2GCHTutS9pwS2XeU9TRDZQfogCkl4FUJkPUlqiYhCGiahusbwB5oBfJMTVC2kFVTDhnQzfXF@fkH "Python 2 – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` fqQ.W<HQ+s_` ``` [Check out a test suite!](https://pyth.herokuapp.com/?code=fqQ.W%3CHQ%2Bs_%60&input=44&test_suite=1&test_suite_input=44%0A72%0A132%0A143%0A1111%0A999&debug=0) Surprisingly fast and efficient. All the test cases ran at once take less than 2 seconds. ### How it works ``` fqQ.W<HQ+s_` – Full program. Q is the variable that represents the input. f – Find the first positive integer T that satisfies a function. .W – Functional while. This is an operator that takes two functions A(H) and B(Z) and while A(H) is truthy, H = B(Z). Initial value T. <HQ – First function, A(H) – Condition: H is strictly less than Q. +s_` – Second function, B(Z) – Modifier. s_` – Reverse the string representation of Z and treat it as an integer. + – Add it to Z. – It should be noted that .W, functional while, returns the ending value only. In other words ".W<HQ+s_`" can be interpreted as "Starting with T, while the current value is less than Q, add it to its reverse, and yield the final value after the loop ends". qQ – Check if the result equals Q. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` LʒIFDÂ+})Iå}н ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f59QkTzeXw03atZqeh5fWXtj7/7@hiTEA "05AB1E – Try It Online") **Explanation** ``` L # push range [1 ... input] ʒ } # filter, keep elements that are true under: IF } # input times do: D # duplicate Â+ # add current number and its reverse ) # wrap in a list Iå # check if input is in the list н # get the first (smallest) one ``` [Answer] # JavaScript (ES6), 61 bytes ``` n=>(g=k=>k-n?g(k>n?++x:+[...k+''].reverse().join``+k):x)(x=1) ``` [Try it online!](https://tio.run/##XcnRCoMgAIXh6@0pdpciGaYjDLQHGYOimZShQ0f49i5wN/NcHf5vm44pzH59f2rrXiotIlkhgRZGSFPbQQMj7YBQ7NEDY2xQVT2xV4fyQQGIN7facUQG9hGCKAhMs7PB7QrvToMFMAbhpWlu9@t/79rcu7YAQn9CS2A0A@OlnMtECuGcZzhP@gI "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = input (g = k => // g() = recursive function taking k = current value k - n ? // if k is not equal to n: g( // do a recursive call: k > n ? // if k is greater than n: ++x // increment the RTA root x and restart from there : // else (k is less than n): +[...k + ''] // split k into a list of digit characters .reverse().join`` // reverse, join and coerce it back to an integer + k // add k ) // end of recursive call : // else (k = n): x // success: return the RTA root )(x = 1) // initial call to g() with k = x = 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ ~~16~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` G¼N¹FÂ+йQi¾q]¹ ``` -1 byte thanks to *@Emigna*. [Try it online.](https://tio.run/##ASMA3P8wNWFiMWX//0fCvE7CuUbDgivDkMK5UWnCvnFdwrn//zEzMg) **Explanation:** ``` G # Loop `N` in the range [1, input): ¼ # Increase the global_counter by 1 first every iteration (0 by default) N # Push `N` to the stack as starting value for the inner-loop ¹F # Inner loop an input amount of times  # Bifurcate (short for Duplicate & Reverse) the current value # i.e. 10 → 10 and '01' + # Add them together # i.e. 10 and '01' → 11 Ð # Triplicate that value # (one for the check below; one for the next iteration) ¹Qi # If it's equal to the input: ¾ # Push the global_counter q # And terminate the program # (after which the global_counter is implicitly printed to STDOUT) ] # After all loops, if nothing was output yet: ¹ # Output the input ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` Nθ≔⊗θηW›ηθ«≔L⊞OυωηW‹ηθ≧⁺I⮌Iηη»ILυ ``` [Try it online!](https://tio.run/##NY1BDoIwEEXXcIoup0ldqEtWRhNjgkq4QcEJJakFOi0sjGevjZTlvP/fn1ZJ2w5Sh3Azo3cP/27QwsSL/ETUdwYug280viISTEW8qF4jg6tF6WJTCTZxzj55lvolms4pqDyp54hWusGCF2zhyc/SQIlEm32X42rXfaccVNqTYGdJDmqc0RLC/1B8G/nmle2NW3H66GNahLA/HsJu1j8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input \$q\$. ``` ≔⊗θη ``` Assign \$2q\$ to \$h\$ so that the loop starts. ``` W›ηθ« ``` Repeat while \$h>q\$: ``` ≔L⊞Oυωη ``` push a dummy null string to \$u\$ thus increasing its length, and assign the resulting length to \$h\$; ``` W‹ηθ ``` repeat while \$h<q\$: ``` ≧⁺I⮌Iηη ``` add the reverse of \$h\$ to \$h\$. ``` »ILυ ``` Print the final length of \$u\$ which is the desired root. [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` `@G:"ttVPU+]vG-}@ ``` [Try it online!](https://tio.run/##y00syfn/P8HB3UqppCQsIFQ7tsxdt9bh/39DE2MA "MATL – Try It Online") ### Explanation ``` ` % Do...while loop @ % Push iteration index, k (starting at 1) G:" % Do as many times as the input tt % Duplicate twice VPU % To string, reverse, to number + % Add ] % End v % Concatenate all stack into a column vector. This vector contains % a sufficient number of terms of k's RTA sequence G- % Subtract input. This is used as loop condition, which is falsy % if some entry is zero, indicating that we have found the input % in k's RTA sequence } % Finally (execute on loop exit) @ % Push current k % End (implicit). Display (implicit) ``` [Answer] # Java 8, 103 bytes ``` n->{for(int i=0,j;;)for(j=++i;j<=n;j+=n.valueOf(new StringBuffer(j+"").reverse()+""))if(n==j)return i;} ``` [Try it online.](https://tio.run/##ZZCxTsMwEIb3PsUpky3TqKWRUDBmYGOgDB2BwaSXyia9VLYThKo8e3DSDKnqwdL33@nu01nd6qXd//RFpb2HN23ovAAwFNCVukDYDjgGULDXGB/QAXEZ024RPx90MAVsgUBBT8vnc1k7NrQbtbqzUvKBrRLCSPukSFqhKG111eB7yQh/YRecocNLU5YYG0WS8NRhi84j4wNxE/uUstxhaByBkV0vh9Wn5ruKqyeDtjZ7OEZ/dhn48QWaX@QD@sDWq1F6oiyb08P9nNaba8w2VxjfnPM8v7nG6DJWx0NMGrs/H/CY1k1IT9EwVMSMSB4/QyIoLZjh05yu/wc) **Explanation:** ``` n->{ // Method with Integer as both parameter and return-type for(int i=0,j;;) // Infinite loop `i`, starting at 0 for(j=++i; // Increase `i` by 1 first, and then set `j` to this new `i` j<=n // Inner loop as long as `j` is smaller than or equal to the input ; // After every iteration: j+= // Increase `j` by: n.valueOf(new StringBuffer(j+"").reverse()+"")) // `j` reversed if(n==j) // If the input and `j` are equal: return i;} // Return `i` as result ``` --- Arithmetically reversing the integer is 1 byte longer (**104 bytes**): ``` n->{for(int i=0,j,t,r;;)for(j=++i;j<=n;){for(t=j,r=0;t>0;t/=10)r=r*10+t%10;if((j+=r)==n|i==n)return i;}} ``` [Try it online.](https://tio.run/##ZZDBasMwDIbvfQpRGNhzmiVrYGSee99hvfS47eClTpGXOsVRCqPLs2dOFljKBBZ8v4T0W1af9cruP/ui0k0DLxrdZQGAjowvdWFgO@AoQMGeg3wwHhyXQe0WITWkCQvYggMFvVttLmXt2dCOKolsRJGXkg@aVUKgtE/KST42kbKRV4mkTXh3Kk24V/42TQTdpInEkjErlOdKuW8MiXtDrXeAsut6Oew@tR9V2D1ZONe4h2P4ANuRR3d4fQfNf92TaYiF@fKPsmxOD/dzStfXmK2vMMSc8zz/d47Ry1gdLzHZ2H01ZI5x3VJ8Cg6pcgzF8vGNlsLFBUM@zen6Hw) [Answer] # [C (gcc)](https://gcc.gnu.org/), 120 100 99 bytes ``` f(i,o,a,b,c,d){for(a=o=i;b=a;o=i/b?a:o,a--)for(;b<i;b+=c)for(c=0,d=b;d;d/=10)c=c*10+d%10;return o;} ``` [Try it online!](https://tio.run/##JY3LCsIwEEX3fkUQComdYqKlUsfRD1EXeViZha0EXZV@e03qhXmey4yvnt7PcycZBrDgwENQYzdEaWkgRkcWU926iz0mQ1WpzNCdEirJL5MnDYEcBgxbMlp58hujy1AYjfHx@cZeDDjN3H/Ey3IvlRhXIikvbIzX5k5jXcNhB2afot5D27ZgkiZcjPlJNjNpFHxqUipLtaCsd0ywk@uCRXUWBd/6NSyH@Q6ik/9OKVxN8w8 "C (gcc) – Try It Online") Given input `i`, checks every integer from `i` to 0 for a sequence containing `i`. * `i` is the input value * `o` is the output value (the minimum root found so far) * `a` is the current integer being checked * `b` is the current element of `a`'s sequence * `c` and `d` are used to add `b` to its reverse [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~15~~ 11 bytes ``` @ÇX±swÃøU}a ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QMdYsXN3w/hVfWE=&input=NDQ=) ``` @ÇX±swÃøU}a :Implicit input of integer U @ }a :Loop over the positive integers as X & output the first that returns true Ç : Map the range [0,U) X± : Increment X by sw : Its reverse à : End map øU : Contains U? ``` [Answer] # [Physica](https://github.com/Mr-Xcoder/Physica), 57 bytes Credit for the method goes to [Doorknob](https://codegolf.stackexchange.com/a/170479/59487). ``` F=>N:Min@Map[->m:N==m+Int[Str[m]{%%-1}]&&F@m||N;…[1;N]] ``` [Try it online!](https://tio.run/##K8ioLM5MTvz/383Wzs/KNzPPwTexIFrXLtfKz9Y2V9szryQ6uKQoOje2WlVV17A2Vk3NzSG3psbP@lHDsmhDa7/Y2P9u@UUKngqPOjoUqk1MrBXMjawVDI1BhIkxkAACawVLS8taKy4FIAgoyoQa6Rmrl5NVWlwSbRJrraCkoGunoGSt4AYUjv0PAA "Physica – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 89 bytes I run each sequence in [1,*n*) until I get a match; zero is special-cased because it doesn't terminate. ``` j,k,l,m;r(i){for(j=k=0;k-i&&++j<i;)for(k=j;k<i;k+=m)for(l=k,m=0;l;l/=10)m=m*10+l%10;j=j;} ``` [Try it online!](https://tio.run/##VVBNb8IwDL3nV1ggUNMGaCU4oBCkHabtgDhM7MTQ1PUD3KbNlHYchvjtnVM2ieWQ2C/Pz89OJsck6YZYJ/orzWDVtCma6WnN/kEaPwjrClEKLSppPeSX3FivUKUKZTnB8TgIihVK7tBSFbKkpAxU1QNalaIiopZ6pqKQV6ryozDQoyiUBZGv3TDNcqwz2Dxun3bPXszBa/A7MzmFs9/Ijzln7GwwhU@Ldftu29ijF5DDhcENzL3By@4BrDEtmBxGKWBD9/StHggUzjiX7MqYq6tirHuB2B4TkZxiC75P8fmm10uL2Nr9QV3mc7FYiOVyKSI6V8kcgdxR5TrilMCdqaa1rdHu87yPDmL7utkIGps6A2S6yXq6WwzSUnD1N7S1XGIQ3NTu9ZwHPDjj3Q8 "C (gcc) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ḟo£⁰¡S+↔N ``` [Try it online!](https://tio.run/##ARwA4/9odXNr///huJ9vwqPigbDCoVMr4oaUTv///zQ0 "Husk – Try It Online") first element in natural numbers which has an infinite list that contains the input. ]
[Question] [ Pascal's Rhombus (which is actually a triangle) is obtained by adding in the pattern: ``` * *** x ``` instead of ``` * * x ``` This means that each cell is the sum of the three cells on the row directly above it and one cell on the row 2 above it. Just like Pascal's triangle the zeroth row has a single `1` on it that generates the triangle. Here are the first couple of rows of Pascal's Rhombus ``` 1 1 1 1 1 2 4 2 1 1 3 8 9 8 3 1 ``` ## Task Given a row number (starting from the top) and an column number (starting from the first non-zero item on that row) output the value at that particular cell. Both inputs may be either 1 or 0 indexed (you may mix and match if you desire). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should aim to make the file size of your source code as a small as possible. [OEIS A059317](http://oeis.org/A059317) [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ 55 bytes ***Pascal's Rhombus? More like Haskell's Rhombus! amiright?*** *4 bytes saved thanks to Ørjan Johansen* I thought I'd have a go at my own problem and practice my Haskell. Hopefully this will inspire more people to answer this. ``` 1!1=1 n!k=sum[(n-2)!(k-2)+sum(map((n-1)!)[k-2..k])|n>1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/31DR0NaQK08x27a4NDdaI0/XSFNRIxtIagP5GrmJBRpAMUNNRc1ooKCeXnasZk2enWHs/9zEzDwrK09/DU0uENO2oCgzr0TFRNH4PwA "Haskell – Try It Online") ## Explanation *This is a bit out of date with the latest golf* Instead of calculating ``` * *** x ``` We calculate ``` * *** x ``` This slants our entire triangle to become ``` 1 1 1 1 1 2 4 2 1 1 3 8 9 8 3 1 ``` This lines up all of our rows making it easier to index the nth item of any column. We then define our base cases. The zeroth row is all zeros so ``` 0!_=0 ``` There is a single `1` at position `1,1` so we define that ``` 1!1=1 ``` And we define the rest of the first row to be zeros as well ``` 1!_=0 ``` Then we define the general case recursively using the pattern described above: ``` n!k=(n-2)!(k-2)+(sum$map((n-1)!)[k-2..k]) ``` [Answer] # [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)), 122 bytes *Well, it's **Pascal's** rhombus.* *37 bytes saved thanks to @manatwork* ``` function f(n,k:integer):integer;begin f:=1-Ord((k<0)or(k>n*2));if n>0then f:=f(n-1,k-2)+f(n-1,k-1)+f(n-1,k)+f(n-2,k-2)end; ``` [Try it online!](https://tio.run/##PU7RcoMgEHyWr7i3gJWOOslMBpP8Qr/BKtjT9HAIST/fIkr2gVl2b/dubh9de5dm7pZldnZw7S9gry3phgEzT@o8WgLDqZgUkteDdiKR5lsPGEx1reSX6zmfLqWwjk83ymshGjRAt9L/6DgTOmRVTLIWH4lWb7qROtqa@nX5q3UMArCAUUFayeJOlhnrAEFdoQRv4Qy9Zdk6vduw48@h1/wAB3XOTxLzo0TRsCyL@fGdR8ihjh0Be8WKLW74eoNQxy2a5NAq4j8enOQ7JSPK4flcln8) [Answer] # [PHP](https://php.net/), 86 bytes recursive way only the function row and column 0-Indexed ``` function f($r,$c){return$r|$c?$r<0?0:f($r-=1,$c)+f($r,$c-1)+f($r,$c-=2)+f($r-1,$c):1;} ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqaf0/rTQvuSQzP08hTUOlSEclWbO6KLWktChPpahGJdlepcjGwN7ACiSna2sIktaGqtM1RDBtjSBsXbAKK0Pr2v@pyRn5QCNNdYyBdgAA "PHP – Try It Online") # [PHP](https://php.net/), 114 bytes recursive way full program row and column 0-Indexed ``` <?=f(...$_GET);function f($r,$c){return$r|$c?$r<0|$c<0|$c>2*$r?0:f($r-=1,$c)+f($r,$c-1)+f($r,$c-=2)+f($r-1,$c):1;} ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lEu/uGmIbrWSqpKNkrBRrzWVvB9Rlm6ahp6cHltO0TivNSy7JzM9TSNNQKdJRSdasLkotKS3KUymqUUm2VymyMQDSYMLOSEulyN7ACqRQ19YQpFYbqknXEMG0NYKwdcEqrAyta///BwA "PHP – Try It Online") # [PHP](https://php.net/), 129 bytes row and column 0-Indexed ``` for(;$r<=$argv[1];$l=$t[+$r++])for($c=~0;$c++<$r*2;)$t[+$r][$c]=$r|$c?$t[$r-2][$c-2]+$l[$c]+$l[$c-1]+$l[$c-2]:1;echo$l[$argv[2]]; ``` [Try it online!](https://tio.run/##NY4xD4IwEIV3fka9gVpJBOPi0TAYBhdd3JqGmAaBhNDm0jgZ/jq2EId77@59wzvXu6WsXO@SlshSQ62z5IepS@e6uT@et2vNMYEXdR@pWMYO7BzmxDQub0spApVypSrXCKMErwSQEJpHDEbORwQjRAm0L5BvWCswWgJ9wVQhAcqKGAUVMEa2WZb/l0JfcmxNb@O5thU6fLBzNEy@CT2e4/ID "PHP – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ ~~20~~ 19 bytes ``` 3ḶṚp@Ḣḣ4 Ḟ_ЀÇ߀ȯ¬S ``` Takes a 0-based index pair as command-line argument. [Try it online!](https://tio.run/##y0rNyan8/9/44Y5tD3fOKnB4uGPRwx2LTbge7pgXf3jCo6Y1h9sPzwdSJ9YfWhP8/@GOJQZFBQ7hh9uBQlzmQE1glvt/AA "Jelly – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~22~~ ~~20~~ 19 bytes ``` Ti:"2Y6Y+FT_Y)]!i_) ``` Both inputs are 0-based. [Try it online!](https://tio.run/##y00syfn/PyTTSsko0ixS2y0kPlIzVjEzXvP/f2MuYwA "MATL – Try It Online") ### Explanation Let `r` and `c` denote the two inputs, specifying 0-based row and column respectively. Each new row in Pascal's rhombus can be built from the matrix containing the previous two rows by [*convolving*](http://www.songho.ca/dsp/convolution/convolution2d_example.html) with the kernel `[1 1 1; 0 1 0]` and keeping the last two rows of the result swapped. This is done `r` times, starting from matrix `1`. It turns out to be shorter to use the kernel `[0 1 0; 1 1 1; 0 1 0]`, which is a predefined literal. This produces an extra row, which will be discarded. Consider for example `r = 3`, so there are `3` iterations. 1. Starting from ``` 1 ``` convolution with `[0 1 0; 1 1 1; 0 1 0]` gives ``` 0 1 0 1 1 1 0 1 0 ``` Keeping the last two rows (the whole matrix, in this case) and swapping them gives ``` 0 1 0 1 1 1 ``` 2. Convolution of the above with `[0 1 0; 1 1 1; 0 1 0]` gives ``` 0 0 1 0 0 0 1 1 1 0 1 2 4 2 1 0 1 1 1 0 ``` The matrix formed by the last two rows swapped is ``` 0 1 1 1 0 1 2 4 2 1 ``` This contains the new row at the bottom, and the preceding one extended with zeros. 3. Convolving again yields ``` 0 0 1 1 1 0 0 0 1 2 3 2 1 0 1 3 8 9 8 3 1 0 1 2 4 2 1 0 ``` Taking the last two rows swapped gives ``` 0 1 2 4 2 1 0 1 3 8 9 8 3 1 ``` After the `r` iterations have been done, the output is contained in the last row of the final matrix. For example, for `c = 2` (0-based) the result would be `8`. Instead of indexing the last row and the desired column, a trick can be used which exploits the *symmetry* of each row: the final matrix is transposed ``` 0 1 1 3 2 8 4 9 2 8 1 3 0 1 ``` and its `-c`-th element is taken. This uses linear indexing, that is, the matrix is indexed by a *single index* in [column-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order) order. Since indexing is *modular*, the `0`-entry is the lower-right corner (value `1`) and the `-2`-th entry is two steps above (value `8`). ``` T % Push true i % Input row number :" % Do the following that many times 2Y6 % Push predefined literal [0 1 0; 1 1 1; 0 1 0] Y+ % 2D convolution, increasing size FT_ % Push [0 -1] Y) % Matrix with rows 0 (last) and -1 (second-last), in that order ] % End ! % Transpose i % Input: colun number _ % Negate ) % Entry with that index. Implicitly display ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 60 bytes ``` i->j->polcoeff(Vec(1/(1-x*(1+y+y^2+x*y^2))+O(x^i++))[i],j,y) ``` [Try it online!](https://tio.run/##DcTBCsMgDADQX@kxMabTntf@wm67iIVRmhEZU2QHhf272zu88qjKzzJkWqehvCXeSn4d@RSB@3mAv4DnZsBTp74v1Mx/RLpB25UIMWi0yXYckivo6qx3tlR9fyAIKELCb7pycPO8GI0RcfwA "Pari/GP – Try It Online") [Answer] ## [Haskell](https://www.haskell.org/), 74 bytes ``` 0#0=1 n#m|m<=2*n&&m>=0=sum[(n-a)#(m-b)|(a,b)<-zip[2,1,1,1]$2:[0..2]] n#m=0 ``` [Try it online!](https://tio.run/##JYxBCoMwEEX3PUUgRRIxMga6KU4vMswigtBQZ5DabkrunqLyVw/e@8@0veZlqRUs4HBRK0VGjK02jTwQcPsKOQ3JWydh8sWlbvJj@OWVYjfs42u8E/R9ZN5zhCopq0GzvrN@DNH5GQ6nVeaiJ9yY6x8 "Haskell – Try It Online") Call with `n # m`, where `n` is the row and `m` is the column. [Answer] # Mathematica, 56 bytes ``` If[#<1,Boole[##==0],Sum[#0[#-i,#2-j],{i,2},{j,2i-2,2}]]& ``` Pure function taking two integer arguments (row first, column second) and returning an integer. Works for negative integer arguments as well, returning `0`. A pretty straightforward recursive structure: `If[#<1,Boole[##==0],...]` defines the base-case behavior for the 0th row (and above), while `Sum[#0[#-i,#2-j],{i,2},{j,2i-2,2}]` implements the recursive definition. [Answer] # [Python 2](https://docs.python.org/2/), ~~70~~ ~~66~~ 65 bytes ``` f=lambda n,k:(k==0)|sum(f(n+~j/3,k-j+j/3)for j in range(4)[:3*n]) ``` [Try it online!](https://tio.run/##TY3BCsIwGIPP21PkZrt2qOtOhT6JeKhoda37N@o8COKr11YEhUAI@ULmx3KZqEvJmasdD0cLkkGzYMyGP2/3kTlG4uXXSobWi@zcTREeAyFaOp9Yz3daNbTnqRT0X@i6muNAC1bIasAUWhCXdVXQ8EO7hiCwLYPvIr9KhIJ@cnoD "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), 68 bytes ``` f=(y,x)=>x<0|x>y+y?0:x>0&x<y+y?f(--y,x)+f(y,--x)+f(y,--x)+f(--y,x):1 ``` [Answer] # Mathematica, 53 bytes ``` D[1/(1-x(1+y+y^2(1+x))),{x,#},{y,#2}]/#!/#2!/.x|y->0& ``` Using the generating function. [Answer] # [Python 3](https://www.python.org/download/releases/3.0/), 75 Bytes This is a recursive lambda that takes column and row as 0-indexed integers. ``` p=lambda r,c:(r<0 or((c==0)|p(r-1,c-2)+p(r-1,c)+p(r-1,c-1)+p(r-2,c-2))+1)-1 ``` Here's a (slightly) more readable version with a printing function: ``` p = lambda r,c:(r<0 or ((c==0) | p(r-1,c-2)+p(r-1,c)+p(r-1,c-1)+p(r-2,c-2))+1)-1 def pp(r): ml = len(str(p(r,r)))+1 for i in range(0, r): a=" "*ml*(r-i) for j in range(0,i*2 + 1): a+=str(p(i,j))+(" "*(ml-len(str(p(i,j))))) print(a) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~82~~ 84 bytes This is a recursive implementation with 1-indexed rows and columns. (Technically needs an `f=` in front, someone let me know if I should change it to 84 bytes. Still new and not 100% sure of the rules.) This uses the recursive formula found on the [OEIS page](http://oeis.org/A059317), but with the `k`'s shifted one to the left to line up properly. Coincidently, `sum(f(n-1,k-i)for i in(0,1,2))` is the same size as `f(n-1,k)+f(n-1,k-1)+f(n-1,k-2)`. The whole function is the Python `and or` trick, where the first condition checks if k is inside the triangle *and* not on the boundary, in which case the recursive formula is used. If is isn't, the part after the `or` is returned, which checks if `k` is in `(1, 2*n-1)`, i.e. on the boundary, returning `True` and `False`. `k+1in(2,2*n)` is one byte shorter than `k in(1,2*n-1)`. Wrapping that in parentheses and putting a `+` in front converts to integer, which is what is needed. ``` f=lambda n,k:2*n-1>k>1and sum(f(n-1,k-i)for i in(0,1,2))+f(n-2,k-2)or+(k+1in(2,2*n)) ``` [Try it online!](https://tio.run/##VY7BCsIwDIbvPkXw1KwZ2IqXwfYu1Tkt3dLRTsSnr@nwYk7h/76Ef/1sz8jnUqZ@dst1dMAUOttwa4YwGMcj5NeiJiUBhdbjFBN48KxOZMgi6oqsIIsxaRW0EWZJPiCWKqf4Fh2S48ddGYILdgeQyf3xuC9VusX5T7KNnP3EXdZ93pLUkJiqjbizNXneVMbyBQ "Python 3 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 87 bytes ``` int f(int r,int c){return c<0|2*r<c?0:0<c&c<2*r?f(--r,c)+f(r,--c)+f(r,--c)+f(--r,c):1;} ``` [Try it online!](https://tio.run/##VU/LboMwELznK0ZIVKYxESSVIhHSfEDUckhviAM1JiJNDLJN2irl26l5VY0l765nxzO7p/SaumXFxSn7aKv6/VwwsHOqFF7SQuA2A5ROdcHaQmjkpIuSdpE5N8l1LQVY6P0sH2XIdl7gheyBhea1y4nrSsqceU4kdd37YmgF/qZpgdF28MG1LDJcjDk5aFmIY5wglUfldKMAxjlODKS50gpbCP45YQOhOzesKeBTrNHQe9Rf9egINpu@yEsJ0qv0usGg7mBS7Jfmqj5r45iTrht7Ce1psZ84m5F3@FaaXxZlrReVGV3nxLJXGTUX7jPsJ5NgK1tY49d/GnQ0oH9G26G1TLCDFe0tBLBeozdE@wD8q@JM8wwW5hNtnKJbrZk17S8 "Java (OpenJDK 8) – Try It Online") At first, I was happy with my 160 bytes iterative method... Hmmm... let's just forget about it, OK? [Answer] # [Husk](https://github.com/barbuz/Husk), 38 bytes ``` !!¡(S+o↔↑2Fz+§,ȯΘΘ←(moΣ↑_3ḣ→)↑_2)eḋ1ḋ7 ``` [Try it online!](https://tio.run/##yygtzv7/X1Hx0EKNYO38R21THrVNNHKr0j60XOfE@nMzzs141DZBIzf/3GKgeLzxwx1AepImiG2kmfpwR7chEJv////f8L8hAA "Husk – Try It Online") Displays the infinite list, but somehow indexing into the list makes it time out. ]
[Question] [ A positive integer *n* can be represented as a *rectangle with integer sides* *a*, *b* such that *n* = *a* \* *b*. That is, the area represents the number. In general, *a* and *b* are not unique for a given *n*. As is well known, a rectangle is specially pleasing to the eye (or is it the brain?) when its sides are in the [*golden ratio*](https://en.wikipedia.org/wiki/Golden_ratio), *φ* = (sqrt(5)+1)/2 ≈ 1.6180339887... Combining these two facts, the purpose of this challenge is to decompose an integer *n* into the product of two integers *a*, *b* whose ratio is as close as possible to *φ* (with the usual metric on ℝ). The fact that *φ* is irrational implies that there is a unique solution pair (*a*, *b*). # The challenge Given a positive integer *n*, output positive integers *a*, *b* such that *a* \* *b* = *n* and the absolute difference between *a*/*b* and *φ* is minimized. As an example, consider *n* = 12. The pairs (*a*, *b*) that satisfy *a* \* *b* = *n* are: (1, 12), (2,6), (3,4), (4,3), (6,2), (12,1). The pair whose ratio is closest to *φ* is (4,3), which gives 4/3 = 1.333. # Rules Functions or programs are acceptable. The *numerator* (*a*) should appear *first* in the output, and the *denominator* (*b*) *second*. Other than that, input and output formats are flexible as usual. For example, the two numbers can be output as strings with any reasonable separator, or as an array. The code should work in theory for arbitrarily large numbers. In practice, it may be limited by memory or data-type restrictions. It's sufficient to consider an approximate version of *φ*, as long as it is accurate up to the *third decimal* or better. That is, the absolute difference between the true *φ* and the approximate value should not exceed 0.0005. For example, 1.618 is acceptable. When using an approximate, rational version of *φ* there's a small chance that the solution is not unique. In that case you can output any pair *a*, *b* that satisfies the minimization criterion. Shortest code wins. # Test cases ``` 1 -> 1 1 2 -> 2 1 4 -> 2 2 12 -> 4 3 42 -> 7 6 576 -> 32 18 1234 -> 2 617 10000 -> 125 80 199999 -> 1 199999 9699690 -> 3990 2431 ``` [Answer] # Pyth - ~~24~~ 23 bytes There has to be a better way to find the divisors... ``` ho.a-.n3cFNfsIeTm,dcQdS ``` [Test Suite](http://pyth.herokuapp.com/?code=ho.a-.n3cFNfsIeTm%2CdcQdS&test_suite=1&test_suite_input=1%0A2%0A4%0A12%0A42%0A576%0A1234%0A10000%0A199999&debug=0). [Answer] # Jelly, ~~16~~ ~~15~~ 14 bytes *Saved 1 byte thanks to @miles.* ``` ÷/ạØp ÆDżṚ$ÇÞḢ ``` [Try it online!](http://jelly.tryitonline.net/#code=w7cv4bqhw5hwCsOGRMW84bmaJMOHw57huKI&input=&args=OTY5OTY5MA) ### Explanation ``` ÷/ạØp Helper link, calculates abs(a/b - phi). Argument: [a, b] ÷/ Reduce by division to calculate a/b. ạØp Calculate abs(a/b - phi). ÆDżṚ$ÇÞḢ Main link. Argument: n ÆD Get divisors of n. żṚ$ Pair the items of the list with those of its reverse. The reversed divisors of a number is the same list as the number divided by each of the divisors. ÇÞ Sort by the output of the helper link of each pair. Ḣ Get the first element [a, b] and implicitly print. ``` [Answer] # Matlab, 96 81 bytes Golfed (-15bytes), props to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) ``` function w(n);a=find(~(mod(n,1:n)));[~,c]=min(abs(a./(n./a)-1.618));[a(c) n/a(c)] ``` Original: ``` function w(n) a=find(not(mod(n,1:n)));b=abs(a./(n./a)-1.618);c=find(not(b-min(b)));[a(c) n/a(c)] ``` This is by far not a great solution, but my first attempt at code-golf. What fun! [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 21 bytes Code: ``` ÑÂø©vy`/})5t>;-ÄWQ®sÏ ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w5HDgsO4wql2eWAvfSk1dD47LcOEV1HCrnPDjw&input=MTAwMDA) [Answer] ## Mathematica, 51 bytes ``` #&@@SortBy[{x=Divisors@#,#/x},Abs[#/#2-1.618]&]& ``` The `` is Mathematica's postfix operator for transposition (displayed as a superscript `T` in Mathematica). Mathematica has a built-in `GoldenRatio`, but 1.618 is a lot shorter, especially because the former also requires `N@`. [Answer] # Pyth, ~~21~~ ~~20~~ 18 bytes ``` hoacFN.n3C_Bf!%QTS ``` [Try it online.](http://pyth.herokuapp.com/?code=hoacFN.n3C_Bf!%25QTS&input=125&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=hoacFN.n3C_Bf!%25QTS&test_suite=1&test_suite_input=1%0A2%0A4%0A12%0A42%0A576%0A1234%0A10000%0A199999&debug=0) ### Explanation 1. Get the inclu`S`ive range from 1 to input. 2. `f`ilter for numbers for that divide the input `!%QT`. 3. Get `[that list, that list reversed]` `_B`. The reversed divisors of a number is the same list as the number divided by each of the divisors. 4. Transpose the list to get pairs of `[numerator, denominator]`. 5. S`o`rt the pairs by the `a`bsolute difference of the ratio of the pair `cFN` and the golden ratio `.n3`. 6. Get the first (lowest) pair `h` and print. [Answer] ## Javascript (ES6), 73 bytes ``` n=>{for(b=0,k=n/.809;n%++b||k>b*b*2&&(a=b););return[b=k-a*a>b*b?b:a,n/b]} ``` We look for: * **a** = highest divisor of n for which **n / φ > a²** * **b** = lowest divisor of n for which **n / φ < b²** Then, the solution is either **[ a, n / a ]** or **[ b, n / b ]**. We compare **n / φ - a²** with **b² - n / φ** to find out which expression is closest to zero. The actual formula used in the code are based on φ / 2 which can be written in a shorter way than φ with the same precision: `.809` vs `1.618`. Therefore: > > n / φ > a² ⇔ **n / (φ / 2) > 2a²** > > > and: > > n / φ - a² > b² - n / φ ⇔ 2n / φ - a² > b² ⇔ **n / (φ / 2) > - a² > b²** > > > ### Complexity The number of iterations heavily depends on the number of factors of n. The worst case occurs when n is prime, because we have to perform all iterations from 1 to n to find its only 2 divisors. This is what happens with 199999. On the other hand, 9699690 is 19-smooth and we quickly find two divisors on either sides of the breaking point √(n/φ) ≈ 2448. ### Test cases ``` let f = n=>{for(b=0,k=n/.809;n%++b||k>b*b*2&&(a=b););return[b=k-a*a>b*b?b:a,n/b]} console.log(JSON.stringify(f(12))); // [ 3, 4 ] console.log(JSON.stringify(f(42))); // [ 6, 7 ] console.log(JSON.stringify(f(576))); // [ 18, 32 ] console.log(JSON.stringify(f(1234))); // [ 2, 617 ] console.log(JSON.stringify(f(10000))); // [ 80, 125 ] console.log(JSON.stringify(f(199999))); // [ 1, 199999 ] console.log(JSON.stringify(f(9699690))); // [ 2431, 3990 ] ``` [Answer] ## JavaScript (ES6), 83 bytes ``` f= n=>{p=r=>Math.abs(r/n-n/r-1);for(r=i=n;--i;)r=n%i||p(i*i)>p(r*r)?r:i;return[r,n/r]} ; ``` ``` <input type=number min=1 oninput=[a.value,b.value]=f(+this.value)><input readonly id=a><input readonly id=b> ``` Actually returns the (*a*, *b*) pair which minimises the absolute value of *a*/*b*-*b*/*a*-1, but this works for all the test cases at least, although I guess I could save 4 bytes by using the 1.618 test instead. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 41 bytes ``` :1fL:2a:Lzoht ,A:B#>.*?!,.= :3a/:$A-$| // ``` [Try it online!](http://brachylog.tryitonline.net/#code=OjFmTDoyYTpMem9odAosQTpCIz4uKj8hLC49CjozYS86JEEtJHwKLy8&input=NTc2&args=Wg) ### Explanation * Main predicate: ``` :1fL L is the list of all couples [A:B] such that A*B = Input (see Pred. 1) :2a Compute the distance between all As/Bs and φ (see Pred. 2) :Lz Zip those distances to L o Sort the zip on the distances ht Take the couple [A:B] of the first element of the sorted list ``` * Predicate 1: Output is a couple `[A:B]` such that `A*B = Input` ``` ,A:B The list [A:B] #> Both A and B are strictly positive . Output = [A:B] *? A*B = Input !, Discard other choice points .= Assign a value to A and B that satisfy the constraints ``` * Predicate 2: Compute the distance between `A/B` and φ. ``` :3a Convert A and B to floats / Divide A by B :$A- Subtract φ $| Absolute value ``` * Predicate 3: Convert an int to a float by inverting its inverse ``` / 1/Input / Output = 1/(1/Input) ``` [Answer] # Haskell (Lambdabot), 86 bytes ``` f(x,y)=abs$(x/y)-1.618 q n=minimumBy((.f).compare.f)[(x,y)|x<-[1..n],y<-[1..n],x*y==n] ``` [Answer] # php, 103 bytes ``` <?php for($s=$a=$argv[1];++$i<$a;)if($a%$i==0&&$s>$t=abs($i*$i/$a-1.618)){$n=$i;$s=$t;}echo"$n ".$a/$n; ``` Produces a notice (this doesn't interrupt execution) about unassigned $i so should be run in an environment that silences notices. [Answer] # Python 3, 96 bytes Pretty simple solution. Makes use of [this SO answer](https://stackoverflow.com/a/5505024/2415524). ``` lambda n:min([((i,n//i),abs(1.618-i/(n//i)))for i in range(1,n+1)if n%i<1],key=lambda x:x[1])[0] ``` [**Try it online**](https://repl.it/D6Gh) The same solution in Python 2 is one byte longer. ``` lambda n:min([((i,n/i),abs(1.618-1.*i/(n/i)))for i in range(1,n+1)if n%i<1],key=lambda x:x[1])[0] ``` ]
[Question] [ [Khinchin's constant](http://en.wikipedia.org/wiki/Khinchin's_constant) is a curious mathematical constant that, [according to Wolfram MathWold](http://mathworld.wolfram.com/KhinchinsConstant.html), is *"notoriously difficult to calculate to high precision"*. Here it is to 100 digits: > > 2.685452001065306445309714835481795693820382293994462953051152345557218859537152002801141174931847697... > > > Write a program in **64** bytes or less that outputs Khinchin's constant to the maximum number of correct decimal places. * You may not use any built in library constants or functions directly relating to Khinchin's constant. (e.g. Math.Khinchin(precision) is definitely not allowed.) * You *may* use math libraries to compute logarithms, summations, etc. * You *may* hardcode all or part of your answer. * Your program must produce finite output and run in less than an hour on a reasonably modern computer (such as those listed [here](http://www.iit.edu/ots/computer_vendor_info.shtml)). * You must output to stdout. There is no input. * You may use any characters you want as long as <http://mothereff.in/byte-counter> registers 64 bytes or less. **Scoring** Your score is the number of successive digits in Khinchin's constant your program outputs correctly, starting with 2.68... You may output incorrect digits but only the last correct digit is counted towards your score. For example, an output of > > 2.68545200**2**06530644530971483548179569382038229399446295305115234555721 > > > would score 9 points. One for each of the digits `2 6 8 5 4 5 2 0 0` but nothing after the **2** that should be a 1. [Answer] # Maple, 200+ The following [Maple](http://www.maplesoft.com/products/Maple/) command computes Khinchin's constant to the requested precision (here, 200 digits): ``` evalf[200](exp(sum((-1)^k*(2-2^k)*ζ(1,k)/k,k=2..∞)/ln(2))); ``` This code should work if you copy-paste it into the Maple graphical interface. The `ζ` takes two bytes in UTF-8, and the `∞` three, for a total of 62 bytes. Writing out the ASCII versions of those symbols, even with the trick of using `min()` instead of `infinity`, alas, brings the byte count up to 66: ``` evalf[200](exp(sum((-1)^k*(2-2^k)*Zeta(1,k)/k,k=2..min())/ln(2))); ``` The number of digits computed can be easily adjusted by changing the number in square brackets after `evalf`. On my rather old computer, 200 digits seems to finish in about half an hour; yours might be capable of more. Note that Maple *rounds* the result to the requested precision instead of truncating it, so the actual number of matching digits might be somewhat less. This method of calculating the constant is based on formula (9) from the [MathWorld page](http://mathworld.wolfram.com/KhinchinsConstant.html), cited there to Gosper (1996, pers. comm.):             ![Equation](https://i.stack.imgur.com/ZhqFJ.gif) This was the most efficient method that I managed to (barely) squeeze into 64 bytes or less. [Answer] # CJam - 118 ``` 2'."*;TeT?_aN{.i9B*ZEay G`9~eW}nE=Lr-`B} )D>9m9"136b ``` Try it at <http://cjam.aditsu.net/> Since stackexchange destroys some of the characters, here's a program that generates the program above; run it first, then run its output: ``` "2'.\""685452001065306445309714835481795693820382293994462953051152345557218859537152002801141174931847697995153465905288090 136b:c"\"136b" ``` **Explanation:** `2` pushes 2 `'.` pushes the dot `"…"` is a string containing the rest of the digits in encoded form `128b` converts the string to a number, treating the characters as digits in base 128 (via their ASCII code) [Answer] ## Haskell, 5 Well, since nobody's posted a solution using actual maths, I decided I would, even though it's nowhere near as close as the other answers. ``` main=print$product[(1+1/r/(r+2))**2`logBase`r|r<-[1..99999999]] ``` This computes `2.6854453689859192`, which is a whopping 5 characters of the constant. Wolfram was right when they said it is "difficult to calculate to high precision". [Answer] # [Kona](https://github.com/kevinlawler/kona/) 63 Simple hard-coded answer: ``` 2.68545200106530644530971483548179569382038229399446295305115234 ``` [Answer] ## Mathematica, 6 ``` (Times@@Rest@ContinuedFraction[Pi,977])^(1.`9/976) ``` gives ``` 2.68545843 ``` and uses only 50 bytes, so there is some room for finding something better than `Pi` and using a larger continued fraction, but I'm not sure it'll get a lot better with a runtime of an hour. (Especially since *finding* a better combination would probably take several days if I'm just using brute force.) (Of course, you were clever enough to disallow `Khinchin~N~2000`, where `2000` could be replaced with any number that gives you a result within an hour ;).) [Answer] # [wxMaxima](http://andrejv.github.io/wxmaxima/) 3 *An actually computed method!* ``` bfloat(product((1+1/(n*(n+2)))^(log(n)/log(2)),n,1,10000)); ``` After about 25 minutes, it returned ``` 2.681499686663101b0 ``` Now I understand why the Mathematica page stated that. I have 6 characters to play with, but I can't imagine adding 6 0's would (a) run in <60 min and (b) give me a more accurate solution. [Answer] ## Python, 64 66 ``` print"2.%i"%int('anljsgqif7gwwwsrntcz7zv2obv6gv5us7fzfwjcaj',36) ``` Outputs: ``` 2.68545200106530644530971483548179569382038229399446295305115234555 ``` [Answer] # [GNU BC](https://www.gnu.org/software/bc/manual/bc.html), 5 digits (54 byte program) An attempt to actually calculate. GNU BC is horribly slow. This ran for 53 minutes on an Ubuntu 14.04 VM running on a mid-2012 MacBook Pro Retina. Strangely it runs faster in the VM than the OSX bare metal - presumably the GNU version is better optimised for this task than the BSD version. ``` for(k=r=1;r++<10^7;)k*=e(l(1/(r*(r+2))+1)*l(r)/l(2)) k ``` ### Output: ``` 2.68544536902156538295 ``` ### Note: `bc -l` needs to be used for `e()` and `l()` functions (and setting scale = 20). [Answer] # CJam floating point calculation - 6 ``` 1e8{I{1.II2+*/)I2mL#*}1.?}fI ``` It fits in the original 32 bytes :) Running with the java interpreter using java 8, it outputs this after about a minute on my laptop: ``` 2.6854513126595827 ``` The online interpreter would probably take too long. [Answer] # Python (5) ``` x=3**.1 p=1 for _ in[1]*10**6:p*=(x//1)**1e-6;x=1/(x%1) print(p) ``` `Output: 2.6854396408091694` (Output takes ~2 seconds.) In solidarity with the other math solutions, I'll give an even worse-converging one that computes the geometric mean of the first million continued fraction coefficients of a single arbitrary-ish irrational number that's not of a type known to not work. Actually, I rigged that number by trying a few until I got one that coincided on an extra digit. Funny thing: I froze my computer and had to do a hard shutdown after trying to shorten this code with the Python golf trick of replacing `for _ in[1]*10**6:code` with `exec("code"*10**6)`. [Answer] ### Ruby - 73 Unfortunately, you can only convert up to base 36 using `to_i` in Ruby: ``` "2.#{"hmegxpkvliy1vaw4lb054ep8wsqwkz2yx9cm9jvc9yfd48j".to_i 36}" ``` which returns ``` "2.6854520010653064453097148354817956938203822939944629530511523455572188595" ``` [Answer] **RPL/2, 7 calculated digits, 61 bytes** ``` 'LN(FLOOR(1/X))/(X+1)/LN(2)' { 'X' 1e-9 1 } 1e-7 INT DROP EXP ``` returns 2.68545210493822 in one minute on my old (intel Core2) laptop. No Zeta function in RPL/2 as far as I know, this is why I have used the integration (formula 15 from the Mathworld page). In principle the accuracy could be improved by replacing 1e-9 and 1e-7 by smaller number, but I was apparently lacking memory for that. Of course resorting to the infinite product solve this point, it looks like ``` 1 1 1e9 FOR I 1 1 I dup 2 + * / + I LN 2 LN / ^ * NEXT ``` and shall work as is on an HP RPL calc, but it turns out to be two order of magnitude slower (on the laptop, didn't tried on my HP !), and gives only 6 digits. So the integration algorithm in RPL/2 does quite a good job actually. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, 145 ``` ‛2.»×¯⌐›‟₁⟇⟩ǐ₄cJḣsĖ↓r₍₀⁺¡₴¼ƒ∷⟨\ꜝṁ€∷₃‹ǒ Uẇḋv⁋∇I⌐ah6\⋎'*FǏ₈"ꜝṅė}₃≤ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuaoiLCIiLCLigJsyLsK7w5fCr+KMkOKAuuKAn+KCgeKfh+KfqceQ4oKEY0rhuKNzxJbihpNy4oKN4oKA4oG6wqHigrTCvMaS4oi34p+oXFzqnJ3huYHigqziiLfigoPigLnHkiBV4bqH4biLduKBi+KIh0nijJBhaDZcXOKLjicqRseP4oKIXCLqnJ3huYXEl33igoPiiaQiLCIiLCIiXQ==) Uses a base-255 compressed string. [Answer] ## Many repl languages, 61 sorry, didn't find a better solution. ``` "2.685452001065306445309714835481795693820382293994462953051152" ``` The rules don't say that the correct number sequence can't be preceded by quotes, so I'm using this. By executing that in a JS console for example, you'll get the same string, including the quotes. [Answer] ## ES7, 56 ``` alert`2.6854520010653064453097148354817956938203822939944629531` ``` ]
[Question] [ A neat trick is if you ever need a nine-sided die, it is possible to make one using two six-sided dice using the numbers below. This is assuming you either have a way to rewrite the faces on the dice, or use some algorithm to map the numbers on a normal die onto these new numbers. ``` 0 0 3 3 6 6 ----------- 1|1 1 4 4 7 7 1|1 1 4 4 7 7 2|2 2 5 5 8 8 2|2 2 5 5 8 8 3|3 3 6 6 9 9 3|3 3 6 6 9 9 ``` The challenge is: * You are given two fair dice, die1 with A faces and die2 with B faces, where A may not necessarily equal B. You need to write numbers on the faces of those dice to create a "target die" with N faces. The numbers of the faces of die1 and die2 will be such that, if rolled and their results summed, it would yield a fair target die. The new numbers written on the dice must greater than or equal to zero (that is, no negative numbers can be on the new dice). * Results should be a list (or whatever appropriate and reasonable format) of new faces for both die1 and die2. The numbers in those lists are not required to be in any sorted order. * Assume A, B, and N are all given as positive integers, and that N is a divisor of A\*B. * The target die is a regular, fair die with numbers 1 to N on its faces. * If there are multiple solutions (such as when creating a one-sided die), you only need to return one solution from any of the possible solutions. ## Examples ``` input: input: die1 = 6 die1 = 5 die2 = 6 die2 = 12 target = 9 target = 20 output: output: [0,0,3,3,6,6] [1,2,3,4,5] [1,1,2,2,3,3] [0,0,0,5,5,5,10,10,10,15,15,15] input: input: die1 = 6 die1 = 12 die2 = 4 die2 = 12 target = 8 target = 18 output: output: [0,0,0,4,4,4] [1,1,2,2,3,3,4,4,5,5,6,6] [1,2,3,4] [0,0,0,0,6,6,6,6,12,12,12,12] ``` Normal code golf rules apply. Shortest answer in bytes wins. [Answer] # [Python](https://www.python.org) NumPy, 67 bytes ``` lambda n,m,o:(x:=r_[:n]*m%o,r_[:m]%(o-max(x))+1) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXMSc5NSEhXydHJ18q00Kqxsi-KjrfJitXJV83VAzNxYVY183dzECo0KTU1tQ02utKL8XIW80tyCSoXM3IL8ohItqFGuBUWZeSUaaRpmOmY6lpqaXDC-qY6hkY6RAZKImY6JjgUSHygPQiAhiGELFkBoAA) # [Python](https://www.python.org), 77 bytes ``` lambda n,m,o,r=range:(x:=[a*m%o for a in r(n)],[b%(o-max(x))+1for b in r(m)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3fXMSc5NSEhXydHJ18nWKbIsS89JTrTQqrGyjE7VyVfMV0vKLFBIVMvMUijTyNGN1opNUNfJ1cxMrNCo0NbUNQbJJENlczVhNqKGuBUWZeSUaaRpmOmY6lpqaXDC-qY6hkY6RAZKImY6JjgUSHygPQiAhiGELFkBoAA) Just saw that output is not required to be sorted. ### [Python](https://www.python.org) NumPy, 75 bytes ``` lambda n,m,o:(x:=sort(r_[:n]*m%o),r_[:m]*(o-x[-1])//m+1) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3vXMSc5NSEhXydHJ18q00Kqxsi_OLSjSK4qOt8mK1clXzNXVA7NxYLY183YpoXcNYTX39XG1DTa60ovxchbzS3IJKhczcAqAmLaiRrgVFmXklGmkaZjpmOpaamlwwvqmOoZGOkQGSiJmOiY4FEh8oD0IgIYhhCxZAaAA) ### [Python](https://www.python.org), 85 bytes ``` lambda n,m,o,r=range:(x:=sorted(a*m%o for a in r(n)),[b*(o-x[-1])//m+1for b in r(m)]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Q3MSc5NSEhXydHJ18nWKbIsS89JTrTQqrGyL84tKUlM0ErVyVfMV0vKLFBIVMvMUijTyNDV1opO0NPJ1K6J1DWM19fVztQ1B8kkQ-VzNWE2o4a4FRZl5JRppGmY6ZjqWmppcML6pjqGRjpEBkoiZjomOBRIfKA9CICGIYQsWQGgA) [Answer] # JavaScript (ES6), 116 bytes Expects `(die1,die2)(target)`. ``` (a,b,d=b+1)=>g=c=>c%--d||a%d&&b%d?g(c):[a,b].map((n,j)=>[...Array(n)].map((_,i)=>~~(i*(j?d:c/d)/n+j)*(j||d),j^=a<b)) ``` [Try it online!](https://tio.run/##bYvRCoIwGEbvew/l/2vOJiUlTek5pGJuKg6bohEE4quvEd3p5XfO@bR4i1EOTf8KTKdKW3ELghRE8WLHkKc1lzyVXhCoaRKe8v3CU1kNEpPcZTf6FD2AIdqlOaX0OgziAwb/4kEaJ@YZmi3oTCUyVBianUY3p0kh0XcuLgWilZ0Zu7akbVdDBTGJEWLEzQo@r@ADwmmBj4RFCNF@IVj0M8xd7Bc "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 93 bytes ``` import math def f(a,b,t):A=math.gcd(a,t);return[*range(1,A+1)]*(a//A),([*range(0,t,A)]*b)[:b] ``` [Try it online!](https://tio.run/##Tck7DoMwEEXRnlVQzpBRwCSxCFEKrwNR2MF8CoxlTYqs3jEFEtJr7nn@x/PmbjEuq98C56vmORvsmI@gyRBjq967XafPkITxFSx/g@uKoN1kQZC6COwL0GWpkODwiphUcoNda/row@IYRpAk6YmYHf0gUVNdnUTSnZpTp39fovgH "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~17~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Output is `[d1.1,...,d1.n,[d2.1,...,d2.n]]` ``` Ç*V%WÃpVogVyW õ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xypWJVfDcFZvZ1Z5VyD1&footer=8k7OIG9jIG1u&input=NQoxMgoyMAotUg) (footer splits & sorts output) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=V2dUIGcwCldnVCBnMQpXZ1QgZzI&code=xypWJVfDcFZvZ1Z5VyD1&footer=WPJVIG9jIG3NaVtVVlddIMtpRWciSW5wdXQ6XG5EaWUgMTpcbkRpZSAyOiK3%2brm4w7dpUnBUsM4&input=WwpbIDYgIDYgIDldClsgNSAxMiAyMF0KWyA2ICA0ICA4XQpbMTIgMTIgMThdCl0KLW1S) ``` Ç*V%WÃpVogVyW õ :Implicit input of integers U=a, V=b & W=n Ç :Map the range [0,U) *V%W : Multiply by V and modulo by W Ã :End map p :Push Vo : Range [0,V) g : Index (0-based and modular) each into VyW : GCD of V & W õ : Range [1,VyW] ``` [Answer] # [Go](https://go.dev), 139 bytes ``` func f(a,b,t int)(l,r[]int){i,j,x,y:=0,0,b,t for y!=0{g:=y;y,x=x%y,g} for;i<a;i++{l=append(l,i*b%t)} for;j<b;j++{r=append(r,j%x+1)} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PZBRaoQwEIbfc4pUkGp3urhLK1Y3B-hbH_ZtWUpMVWLdKDGCEjxBj9CXpVDolfY2HatdSPLP8A0__-Tzq6jPl9uGi3deZPTEpSLy1NTarJ38ZJxr0-LrfHcmv48uH3mnBM09DikYKpXxvQr04ThVVkIJPQwxCyCYOMlrTYcbFtgiZkMyQM96d4BinEAidzyRq5WtGG-aTL2hkbxLXePPuNylSYlY_2MNpduvNoh1ZjqtxiXSjxmajO5pa3QnDLXXaOgzhZ0W83xqieBt1tKY0cNxb20IITyNYB9hs4VtgFUIDxChYj-daPwLQl9BxExzhX80O1iCK8cs98Sag1ineI1PnpVpvWpR7ZMXjREq5QnAaZ-MZMl7Ps_6Cw) Port of [Shaggy's answer](https://codegolf.stackexchange.com/a/255480/77309). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` NθNηNζ≔﹪×…⁰θηζεI⟦ε⊕﹪…⁰η⁻ζ⌈ε ``` [Try it online!](https://tio.run/##XYw/C8IwFMR3P0XGF4hQC06dxKlDRcRNHGL6aALNi80fkXz5GAdFPDi4H9yd0tIrJ@dSerqneEj2hh4W3q1@Wf9xrrwLwUwEgxvT7OBsLAY4SZoQGsEWLpiuztVYy0dvKMJehggXFKwn5dEiRRw/B9/pezYYSgFyDfJpbLKAvOrKeVfKlm1a1jZl/Zhf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @loopywalt's Python answer. ``` NθNηNζ ``` Input the dice. ``` ≔﹪×…⁰θηζε ``` Multiply all of the digits on a regular first die by the size of the second die and reduce modulo the size of the third die. ``` I⟦ε ``` Output that as the first die, and as the second die output... ``` ⊕﹪…⁰η⁻ζ⌈ε ``` ... the digits on a regular second die modulo the minimum step in values on the output first die (calculated as the size of the third die minus the maximum value on the output first die, although the minimum nonzero value also works), plus one. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 12 bytes (24 nibbles) ``` `:;.*@,_%$@+~.,_%$`/|@$[ ``` Same approach as [Neil's answer](https://codegolf.stackexchange.com/a/255467/95126) (which apparently is a port of [loopy walt's answer](https://codegolf.stackexchange.com/a/255463/95126)): upvote those! Input is target, die1, die2. ``` `:;.*@,_%$@+~.,_%$`/|@$[ `: # output list of 2 lists: ; # save list 1: * # multiply @ # sides of die1 by ,_ # each value of die2 . # and map over each of thes values %$ # modulo it by @ # sides of the target die # now make list 2: |@$ # remove nonzero values from list 1 `/ # and fold over this [ # getting the minimum; .,_ # now map over values of die1 %$ # moduloing each by # minimum nonzero value of list 1 +~ # and add 1 to each ``` [![enter image description here](https://i.stack.imgur.com/BRbMo.png)](https://i.stack.imgur.com/BRbMo.png) [Answer] # [Rust](https://www.rust-lang.org), ~~170~~ ~~159~~ 151 bytes * -8 bytes thanks to corvus\_192 ``` |a,b,c|(1..a).filter(move|d|a%d+b%d+c%(a/d)<1).flat_map(|d|[(d,1),(a/d,d)]).zip([b,c]).map(move|((u,w),e)|(0..e).map(|v|v/(e/u)*w).collect()).collect() ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fY9BTsMwEEX3OYWpVGmmDE6TFlRKW27BpkLItR0pkpNGwUkl6p6DBZssYM8dOAW3wSZdsAnSjGak9__XzNt73Tzb7jMrWSHyEvBotGXZ-qOx2dXi-9UJ2pF0kHAukGe5sbqGYt9qp5wYq8udbzkGEStcJV5ghH0qRAUeb0FRghQYKXxE_pJXsPVpfg2S3xSAhg5IGh1MOdc9ca1rY9Bxg5MDcrk3RksL-Gc9n_cV3UVROFgtH7RchW5m6WbD1iyDObFQ6CVVnZfWlBcwOi7vTyPy9JbYjS_0eJDOBmiy-Nd8xkPudErsmliSBh6d-le6rp8_) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L*I%=αß²Ls%>? ``` Port of [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/255463/52210). Three loose inputs in the order \$die1,die2,target\$, output printed as two separated lists. [Try it online](https://tio.run/##yy9OTMpM/f/fR8tT1fbcxsPzD23yKVa1s///39CIy5TLyAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5epUJoQeWhlR9N9HK0LV9tzGw/MPrfMpVrWz/39om87/6GgzHTMdy1idaEMjHVMdIwMgy1QHyAazzHRMdCyAtAlQjQVEDQhZgKWAMDYWAA). Could alternatively be output as a pair of lists: ``` L*I%ZIα²Ls%>‚ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fR8tTNcrz3MZDm3yKVe0eNcz6/9/QiMuUy8gAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5yaEHlpZ/N9HK0I1KuLcxkPrfIpV7R41zPqvc2ib/f/oaDMdMx3LWJ1oQyMdUx0jAyDLVAfIBrPMdEx0LIC0CVCNBUQNCFmApYAwNhYA). **Explanation:** ``` L # Push a list in the range [1, first (implicit) input die1] * # Multiply each value by the second (implicit) input die2 I% # Modulo each by the third input target = # Print it with trailing newline (without popping) α # Take the absolute difference between the third (implicit) input target and # each value in the list ß # Pop and push the minimum ²L # Push a list in the range [1, input die2] s # Swap so the minimum absolute difference is at the top % # Modulo each value in the list by this > # Increase each by 1 ? # Pop and output it (without trailing newline) as well ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 81 bytes ``` (a,b,x)=>(g=i=>x%i|b%i?g(--i):[a,b].map(Z=n=>n--?[n*i%x+1||n%i,...Z(n)]:x=''))(b) ``` [Try it online!](https://tio.run/##bcvBDoIwEATQu//RsKttI0SNkiz8B4RDQSBrsCViTA/8e61nzMzpTeZhPmbpXjy/lXX3PgwUwMhWeqQCRmIqvOC1FVyOoBRjXse10U8zQ0WWCqtUWds9C39I19UKllrrCiw2uackQYQWQ@fs4qZeT26EAS4yBnG31dsfPcnrRs8yzWR23HjUX@MhfAE "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` k [V=ogVk fU2 ×õ)WogU×o*VÌ] ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=awpbVj1vZ1ZrIGZVMiDX9SlXb2dV128qVsxd&input=MTggMTIgMTItUQ) Input as `target die1 die2`, Output as `[[<die1 sides>],[<die2 sides>]]`, unsorted. Explanation: ``` k k # Get the prime factors of <target> # Store as U [...] # Return the enclosed statements as an array: V=ogVk fU2 ×õ) Vk # Prime factors of <die1> fU2 # Remove and return from U numbers that are in both × # Multiply them together õ # Get the range [1...N] g ) # Index into that range (wrapping): o # Numbers in [0...<die1>-1] V= # Store as V and return it WogU×o*VÌ U # The remaining numbers in U × # Multiplied together o # For X in the range [0...N-1]: * # Multiply X by VÌ # The last (highest) number in V g # Index into the result (wrapping): Wo # Numbers in the range [0...<die2>-1] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 101 bytes ``` x;y;*p;f(a,b,n,r){p=r;for(x=n,y=a;r=y%=x;x=r)y=x;for(;a--;*p++=y--)y=y?:x;for(;b--;*p++=y-=x)y=y?:n;} ``` [Try it online!](https://tio.run/##dVDRToMwFH3fV9ywkLRQjC5qdLXuxb9QHwoU14QVUpiCy7593lLY3KJNbtqcc@655zZLPrLsMNcmK7e5gqemzXV1tX6ezXNVaKPghaiuthRqq01bkCBsQECYv5mAzR3DPE8PHe95VPOCSJYywyzd1cLyorKkE4b1QnIr@lB0vBOW9ng7isskwa44Fn2SINqvliORngjRecbw/Z9Jf0OlTh02@6x07jNLawngHQG@mHtBo78VUNjNAM@4GASvEADlA/a11qUCMgiTBOhJFOZhEzCICJrFMWXeawWIBbDEesefcTb7MUOrmnaYD9IPT/1ljgGGbFY127LFr93IsqwygsMlxJCiKhpmVAVBIZ0SYhb0Qy/Dpt6ROS3tceZANPuHxiHO6Ix2i16ssZHakCmx3wnuma/HqXnE7xjcLBgsri9wp73FejjHnXaoAd8ffgA "C (gcc) – Try It Online") **Edit #1:** -1 byte thanks to ceilingcat [Answer] # [Scala](https://www.scala-lang.org/), ~~177~~ 172 bytes saved bytes due to replacing `List` to `Seq` --- Golfed version, [try it online!](https://tio.run/##dY9NT8MwDIbv/RW@TLIhatfxIahoJY4cdpo4IQ5ukk5FWVratBNM/e0lKdzGLNuR30ev7PSSDc9N@aGlgy3XFk4RgNIVHPyA3O37DJ67jr/edq6r7f6dMni1tYMcTvPIBqocOXuxTpRLl6FTXmAKrgGmuKqN0x2qvOCVui59yRVyougp9dCw23Ib6E5/IiqRkghUKCKKv@sWg14K6acDtyfJvQbEQRxJ6LBmDYN1tQG9cBzzYkxQJwNdHSl2jXdPv88MPsLByp9e4a2AkBQFufU/c8ZihY8C7n3S//rNmZ4@XDD8gXPHZi3gTkC6WcgUTdH8Aw) ``` val f=(a:Int,b:Int,c:Int)=>(1 to a).filter(d=>a%d+b%d+c%(a/d)<1).flatMap(d=>Seq((d,1),(a/d,d))).zip(Seq(b,c)).map{case ((u,w),e)=>(0 until e).map(v=>v/(e/u)*w).toSeq}.toSeq ``` Ungolfed version ``` object Main { def main(args: Array[String]): Unit = { val f = (a: Int, b: Int, c: Int) => (1 to a) .filter(d => a % d + b % d + c % (a / d) < 1) .flatMap(d => List((d, 1), (a / d, d))) .zip(List(b, c)) .map { case ((u, w), e) => (0 until e).map(v => v / (e / u) * w).toList } .toList val d = f(4, 4, 4) println(f(9, 6, 6)) println(f(9, 6, 3)) println(f(18, 6, 6)) println(f(18, 6, 3)) println(f(20, 5, 12)) } } ``` ]
[Question] [ Output the infinite list of pairs of integers `(a, b)`, where both \$ a > 1 \$ and \$ b > 1 \$, ordered by the value of \$ a^b \$. When there are multiple pairs where \$ a^b \$ is equal, they should be ordered lexicographically. For example, \$ 2^4 = 4^2 = 16 \$, but `(2, 4)` should come before `(4, 2)`, because it is lexicographically earlier. This sequence starts: ``` 2, 2 2, 3 3, 2 2, 4 4, 2 5, 2 3, 3 2, 5 6, 2 7, 2 ``` Here are the first 100,000 pairs: <https://gist.github.com/pxeger/0974c59c38ce78a632701535181ccab4> ## Rules * As with standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, you may choose to either: + Take an input \$ n \$ and output the \$ n \$th pair in the sequence + Take an input \$ n \$ and output the first \$ n \$ pairs + Output the sequence indefinitely, e.g. using a generator * You may use \$ 0 \$- or \$ 1 \$-indexing * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 12 bytes ``` ⟦+₂ᵐgj∋ᵐ.^?∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sWHNr5qHHD/0fzl2k/amp6uHVCetajjm4grRdn/6hj@f///6MA "Brachylog – Try It Online") Function submission, a generator that generates all solutions. The TIO link uses a header + a command-line argument to print the first ten. ## Explanation ``` ⟦+₂ᵐgj∋ᵐ.^?∧ ⟦ Form a range from 0 to ? inclusive, for some number ? +₂ Add 2 to ᵐ each element of the range j Make two copies of the range g as two separate lists (don't concatenate them) ∋ Generate all ways to select one element ᵐ from each list ^ such that the first element to the power of the second ? is ? . ∧ and output the selected elements ``` Not *explicitly* specified is the ordering, but `⟦` will try possible values of `?` in order (which in this case are positive integers), and `ᵐ` will process the first element before the second (so it'll try 2⁴ before 4² because it's checking all possible exponents with base 2, then all possible exponents with base 3, etc.) This algorithm is, of course, very inefficient. A reversed exponentiation, `~^`, seems like it could be an efficient way to solve the problem, and potentially shorter too – but adding the requirement that the base and exponent are ≥2 is nontrivial when writing the program in that form, and more importantly, Brachylog seems to enter an infinite loop when trying to calculate what value the base and exponent have in that situation. So the Jelly-ish algorithm written here is probably the best available option in the current version of Brachylog. [Answer] # [JavaScript (V8)](https://v8.dev/), 58 bytes ``` for(i=3;k=++i;)for(j=1;k=k<i?k:j++<i;)j**++k-i||print(j,k) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPT1tg621ZbO9NaE8TNsjUEcrNtMu2zrbK0tW2AwllaWtra2bqZNTUFRZl5JRpZOtma//8DAA "JavaScript (V8) – Try It Online") Outputs indefinitely. This code is shorter than it would be were I to remove the third for-loop and instead use logarithms. Thanks to @Arnauld for -2 bytes and to @tsh for -2 more. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` ɾ›:Ẋµƒe;Ẏ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvuKAujrhuorCtcaSZTvhuo4iLCIiLCIxMSJd) ``` ɾ› # 2..n+1 :Ẋ # Cartesian product with self µ ; # Sort by... ƒ # Reduce by... e # Exponentiation. Ẏ # Get the first n. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~70 60~~ 52 bytes ``` 2.step{|x|x.times{|y|x.times{|z|x==y**z&&p([y,z])}}} ``` [Try it online!](https://tio.run/##KypNqvz/30ivuCS1oLqmoqZCryQzN7W4uqYSwayqqbC1rdTSqlJTK9CIrtSpitWsra39/x8A "Ruby – Try It Online") ### How actually? For any given x (starting from 2), check if there is a pair of values y,z in the range (0,x-1) which satisfies y^z==x y and z will be greater than 2 because: * If z==0, the result will be 1 * If y==0, the result will be 0 (or 1) * If y==1, the result will be 1 * If z==1, the result will be y, which is always less than x [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~75~~ 67 bytes *Thanks [@pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) for -8 bytes* ``` i,=r=2, while[j**k-i or print(j,k)for j in r for k in r]:i+=1;r+=i, ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P1PHtsjWSIerPCMzJzU6S0srWzdTIb9IoaAoM69EI0snWzMNyMtSyMxTKFIAMbPBzFirTG1bQ@sibdtMnf//AQ "Python 3.8 (pre-release) – Try It Online") Prints indefinitely. Port of [@ophact](https://codegolf.stackexchange.com/users/106710/ophact)'s [Javascript answer](https://codegolf.stackexchange.com/a/243993/96039). Can probably still be golfed considerably, cuz I'm a noob at golfing in Python :P [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ‘Ḋ*þ`ZŒỤ‘ḣ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4yHO7q0Du9LiDo66eHuJWD@4v///xsaAAA "Jelly – Try It Online") This works either as a full program or as a function. Takes an argument *n* and returns the first *n* pairs. ## Explanation ``` ‘Ḋ*þ`ZŒỤ‘ḣ Ḋ Form an inclusive range from 2 to ‘ {n} + 1 þ Form an table * exponentiation ` using {that range} and itself Z Transpose (so that (x+1)^(y+1) is at index [x,y]) ŒỤ Produce a list of all coordinates (index pairs) in {the table}, sorted by the values of the table ‘ Increment {both halves of each coordinate pair} ḣ {Output} the first {n} {coordinate pairs} ``` The basic idea is that given an input *n*, we calculate all possible exponentiations of numbers in the range 2 to *n*+1 inclusive, then return the inputs that produced the *n* lowest results. Jelly's tiebreak for `ŒỤ` happens to match the tiebreaking behaviour required by the question, but we need to transpose the table (and add 1 to the coordinates – Jelly uses 1-based coordinates but the exponentiation table conceptually uses 2-based coordinates) to make the coordinate system also match the format required by the question. The range 2 to *n*+1 is sufficient because any *x**y* which is out of this range would have to be larger than 22 … 2*n*+1 or than 22 … (*n*+1)2, i.e. larger than *n* different elements, so it can't appear in the portion of the sequence we're outputting. [Answer] # [J](http://jsoftware.com/), ~~26~~ 23 bytes Returns the first n pairs. ``` {.&(/:^/&>)&,[:{@;~2+i. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q/XUNPSt4vTV7DTVdKKtqh2s64y0M/X@a3JxpSZn5CukKRga/AcA "J – Try It Online") `2+i.` Integers from 2 to n+1. `{@;~` Table of all pairs of these integers. `(/:^/&>)&,` Flatten into a list of pairs and sort by the value of the exponentiation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L>ãΣ`m}I£ ``` Outputs the first \$n\$ pairs. Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/244004/52210). [Try it online.](https://tio.run/##yy9OTMpM/f/fx@7w4nOLE3JrPQ8t/v/f0BQA) Could alternatively be the 1-based \$n^{th}\$ value by replacing `£` with `è`: [try it online](https://tio.run/##yy9OTMpM/f/fx@7w4nOLE3Jr/Q6v@P/fEAA). The infinite sequence would be 2 bytes longer: `∞εL>ãΣ`m}Nè` - [try it online](https://tio.run/##yy9OTMpM/f//Uce8c1t97A4vPrc4IbfW7/CK//8B). **Explanation:** ``` L # Push a list in the range [1, (implicit) input] > # Increase each by 1 to make the range [2,input+1] ã # Pop and push the cartesian product of itself to get all pairs Σ # Sort this list of pairs by: ` # Pop and push both values separated to the stack m # Exponentiation }I£ # After the sort-by: leave the first input amount of pairs # (which is output implicitly as result) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~75~~ 76 bytes Outputs the first `n` pairs. (A previous version of this answer was one byte shorter by returning just the `n`th pair, but it raised an error for n <= 2.) Not as short as [@Aidan Chow's Python answer](https://codegolf.stackexchange.com/a/243996/91685), but I wanted to see how well `sorted` would do. Using Python 2's lambda argument destructuring is a bit shorter than `lambda p:p[0]**p[1]` in Python 3. ``` lambda n:sorted([(i/n+2,i%n+2)for i in range(n*n)],key=lambda(i,j):i**j)[:n] ``` [Try it online!](https://tio.run/##JctBDoMgEAXQq7BpMoMkpixJPIm6wAjtUP0YZMPpaZNu3u5drb4zbI/T0g9/brtXcHcuNew0k4wYrJHHT465KFECVTxegaDBq/mENv0biUnsROvEs8ParyKoFOnJ3L8 "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 45 bytes ``` f=[(y,z)|x<-[2..],y<-[2..x],z<-[2..x],y^z==x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802WqNSp0qzpsJGN9pITy9WpxLCqIjVqYKzKuOqbG0rYv/nJmbmKdgqFBRl5pUoqCiUJGanKhgZKKT9N9JRMOICEsZcxlCWCZcJiGUKIoxBEkAxUy4zENccSAAA "Haskell – Try It Online") *f* is the infinite sequence. Inspired by @G B [answer](https://codegolf.stackexchange.com/a/244007/84844) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` p`‘*/Þḣ ``` [Try it online!](https://tio.run/##y0rNyan8/78g4VHDDC39w/Me7lj8//9/QwMA "Jelly – Try It Online") Port of my Vyxal. -1 thanks to ovs. ``` p` Cartesian product with (implicit) range from 1 to self ‘ Increment anything Þ Sort by... / Reduce by... * Exponentiation ḣ Get first n. ``` [Answer] # [R](https://www.r-project.org), ~~57~~ ~~55~~ ~~50~~ 46 bytes ``` \(n)cbind(a<-n:1+1,b<-a%x%!!a)[order(a^b)[n],] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6Fjf1YjTyNJOTMvNSNBJtdPOsDLUNdZJsdBNVK1QVFRM1o_OLUlKLNBLjkjSj82J1YiG61hUnFhTkVGoYWhka6KRpQgQXLIDQAA) Returns the \$n^\text{th}\$ value. -2 bytes thanks to pajonk, then -4 more bytes thanks to pajonk. -1 byte thanks to Dominic van Essen. [Answer] # APL+WIN, 27 bytes Prompts for desired term i. ``` (v[⍋*/¨v←,n∘.,n←1+⍳i])[i←⎕] ``` [Try it online! thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv0ZZ9KPebi39QyvKgII6eY86ZugBSaC89qPezZmxmtGZQA5QU@x/oHqu/2lchlxpXEZAbAzEJkBsCsSGBmDCgAsA "APL (Dyalog Classic) – Try It Online") [Answer] # Java 8, 91 bytes ``` n->{for(int t=4,i;;t++)for(i=1;i++<t*t;)if(Math.pow(i/t,i%t)==t&&--n<0)return i/t+","+i%t;} ``` Outputs the 0-based \$n^{th}\$ value. [Try it online.](https://tio.run/##NY/BbsJADETvfIUVqWi3mwSoyqWb7R/AhSPisISkmAYn2jhUFcq3BxPgYskztubNyV98cjr8Dnnl2xZWHuk6AUDiIpQ@L2B9XwE2HJB@IFfiAGkrYj@R0bJnzGENBG6g5Pta1mG8YfcZo7VsjB4lt7BoTMbvbDWWauX5mDb1n8IZx/jG2jmeTpOEsrkOBXeBQBwTxZER1/aDvac13b6StGfopcYDnIVYPei2O68ftC8IdHMLmH0sZQrI6EmX/5aLc1p3nDbyxxUpNNEXRIZSKaif7frhBg) Outputting the infinite sequence is 6 bytes longer: ``` n->{for(int t=4,i;;t++)for(i=1;i++<t*t;)if(Math.pow(i/t,i%t)==t)System.out.println(i/t+","+i%t);} ``` [Try it online](https://tio.run/##LY7BDoIwDIbvPkVjYrI5wJh4m/MN4ELixXiYE7Q4BoGCMYZnx029tOnf/v2/So86rq6P2Vjd95BqdO8FADoqulKbArIwAowNXsGwY2iOS69NC1960oQGMnCgZhcf3mXTMW8GUrsIpSQh@FdSW4lC7GlNkmPJUk33pG2eDDcU4Yq4UsTzV09FnTQDJW3nn1gX1mIZLUU4kdMsQ2Y7XKzP/Ed/wWqPzXLyptvprPkP2SWGucHaP@00fwA) **Explanation:** ``` n->{ // Method with integer parameter and String return-type for(int t=4, // Target-integer, starting at 4 i; // Output integer, uninitialized ; // Loop indefinitely: t++) // Increase `t` by 1 after every iteration for(i=1;i++<t*t;) // Inner loop `i` in the range (1,t*t): if(Math.pow(i/t, // If `i` integer-divided by `t` i%t) // to the power `i` modulo-`t` ==t&& // Is equal to `t`: --n // First decrease the input by 1 <0) // And if it's now negative: return i/t+","+i%t;} // Return the divmod of `i,t` as result ``` [Answer] # [Julia 1.0](http://julialang.org/), 49 bytes ``` !n=sort([a^b=>a=>b for a=2:n+1,b=2:n+1][:])[n][2] ``` [Try it online!](https://tio.run/##JcVBCoAgEADAr@htpRD1KKwfkQ30UBiyhhn0ezs0lzmfWpJ955SMd@sDYtoyhoQhi711kdB5Xuya/yl6UpEpOppXLzwqa9AScjnAKm@NUWp@ "Julia 1.0 – Try It Online") output is the n-th pair in the sequence (1-indexed). For n>14, a `BigInt` is expected to avoid overflow [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 98 bytes ``` .+ * L$`_ $=$.($`__ %L$`_(?=_*(.+)) :$1,$.($`__ %~`:(.+),(.+) ^¶$$.($2*$($1$* N`.+ "$+"+0`.+: A`: ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4vLRyUhnkvFVkVPA8iI51IF8TXsbeO1NPS0NTW5rFQMdeBydQlWIFEdEMEVd2ibCkjGSEtFQ8VQRYvLLwFooJKKtpK2AZBlxcXlmGD1/7@hAQA "Retina – Try It Online") Outputs the first `n` terms. Explanation: Port of my Charcoal answer inspired by @ais523's answer. ``` .+ * ``` Convert `n` to unary. ``` L$`_ $=$.($`__ ``` Create the numbers from `2` to `n+1` in decimal, each prefixed with `n` in unary. ``` %L$`_(?=_*(.+)) :$1,$.($`__ ``` Create the Cartesian product of the range `2` to `n+1` with itself. ``` %~`:(.+),(.+) ^¶$$.($2*$($1$* ``` Precede each product with its exponentiation, computed by constructing a repeated multiplication and evaluating it. ``` N`.+ ``` Sort the exponentiations, resolving ties stably i.e. keeping the lowest base first. ``` "$+"+ ``` Loop `n` times... ``` 0`.+: ``` ... delete one exponentiation. ``` A`: ``` Keep only the lines where the exponentiation was removed i.e. the first `n` lines. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` NθFθFθ⊞υ⟦X⁺²ι⁺²κ⁺²ι⁺²κ⟧≔⟦⟧ηFθ⊞η⌊⁻υηIEη✂ι¹ ``` [Try it online!](https://tio.run/##VY3NCsIwEITvPsUeNxDBevUknjxUAh5LD7FUs5ifmnT18WMiFOppZthvZgej4xC0zfnsJ54v7G5jxJc4bO4hQjGwqOJkkCV0KnwKoiwn3EsgIWHxT7EK/4e@LB5ToofHrpdgVg9@w0ZCS54cOyxaWlwhUTAVyc940mnGVk8VvFoaRiQJjahEzs0ub9/2Cw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation: Inspired by @ais523's answer. ``` Nθ ``` Input `n`. ``` FθFθ⊞υ⟦X⁺²ι⁺²κ⁺²ι⁺²κ⟧ ``` Generate the Cartesian product of `[2..n+2)` with itself, plus include the result of the exponentiation as the first term. ``` ≔⟦⟧ηFθ⊞η⌊⁻υη ``` Get the `n` lowest terms from that list, which takes values in ascending order of exponentiation resolving ties by taking the base in ascending order. ``` IEη✂ι¹ ``` Output the terms but exclude the exponentiations. 35 bytes using the newer version of Charcoal on ATO: ``` NθFθ⊞υ⌊⁻ΣEθEθ⟦X⁺²κ⁺²μ⁺²κ⁺²μ⟧υIEυ✂ι¹ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjcXe-YVlJb4leYmpRZpFGpac6XlFykAGQoBpcUZGqU6Cr6ZeZm5pbkaQLq0WCMYxEos0CgESkCo6ID8cqDWgBygrJGOQramjgKMnauJxEGViNUEyZUCSWuugKLMvBIN58TiErDRQDuDczKTUzUydRQMNUEqlhQnJRdDHbw5Wkm3LEdJR0FJNxNEGhooxUKlAA "Charcoal – Attempt This Online") Link is to verbose version of code. ]
[Question] [ # Introduction Write a program or function that, given the coordinates of where a dart lands on a dartboard, return the score of that dart. Dart coordinates are given as two integers, `x,y` measured from the center of the dartboard, with millimeter precision. ## How to score a dart Darts is a game played by throwing a dart at a circular board. The dart board is divided into 20 equally sized "wedges". Starting from the top and going clockwise, the sections have values of 20,1,18,4,13,6,10,15,2,17,3,19,7,16,8,11,14,9,12,5. If your dart lands in the black or white parts of any of the wedges, you score the value indicated on the outside of that wedge. [![here's a picture of a dartboard](https://i.stack.imgur.com/ooiOW.jpg)](https://i.stack.imgur.com/ooiOW.jpg). However, if your dart lands in the outer green/red ring of the dartboard, you score double the points indicated on the outside of the wedge that you hit. Likewise, hitting the inner green/red ring (the one in between the two white/black sections), you score triple the number indicated on the outside of the wedge. If your dart hits the innermost circle (the red bulls-eye) you instead score 50 points and finally, if your dart hits the second-innermost circle (the green ring around the bulls-eye), you score 25 points. The dimensions of the rings, measured from the center of the dartboard, are as follows: [![image not to scale](https://i.stack.imgur.com/KLVGX.png)](https://i.stack.imgur.com/KLVGX.png) ``` Bullseye (50): [0mm-6mm) 25: [6mm-16mm) Inner Single: [16mm-99mm) Triple: [99mm-107mm) Outer Single: [107mm-162mm) Double: [162mm-170mm) Miss (0): 170mm+ ``` Note 1: Pictures provided are for illustration purposes only, and are not to scale. Note 2: Measurements given are approximate, and may not be accurate to a real dartboard. Note 3: All measurements given are `[inclusive-exclusive)`. For the purposes of this challenge, we're not going to worry about darts hitting the wire and bouncing off. If the dart lands "on the wire" with one of the radial lines, then it is up to the answerer to decide whether to break the tie clockwise or counter-clockwise. Tie breaking direction must be consistent, and indicated. Note 4: Dartboard is hung in the standard way with the middle of the 20 section being directly above the bullseye, and the 3 section directly below the bullseye. # Input Two integers representing the `x,y` coordinates of where the dart landed, measured in millimeters, relative to the center of the dartboard. # Output A single integer, for the number of points that would be awarded to a dart that landed at the given coordinates. # Sample ``` 0,0 -> 50 2,101 -> 60 -163,-1 -> 22 6,18 -> 1 -6,18 -> 5 45,-169 -> 0 22, 22 -> 4 (if tie-broken clock-wise) 18(if tie-broken counter-clockwise) -150,0 -> 11 -150,-1 -> 11 ``` ## Scoring [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Fewest bytes in your source code wins. [Standard loopholes forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). [Answer] # JavaScript (ES7), 137 bytes Takes the coordinates in currying syntax `(x)(y)`. Uses counterclockwise tie-break. ``` x=>y=>(r=(x*x+y*y)**.5)<6?50:r<16?25:(r<99?1:r<107?3:r<162||r<170&&2)*parseInt('b8g7j3h2fa6d4i1k5c9eb'[Math.atan2(y,x)*3.1831+10.5|0],36) ``` [Try it online!](https://tio.run/##Zc5LboMwEAbgfU/hVWI7seOxYwMRj3UXPUHVhUMgT0FkUAQSdydxK1EpbGY0o08z/8U@bJO7871lVX0oxjIZuyTtkxS7BHe0W/W0J5RyTWKTabFzMZhM6h12cRRl4GcRZOp3L4fh1QKxWEhC79Y1xWfV4uU@PAYXdZKlNYftGa46j4r98vvLtiduW1tJ3K87QhWHUMEKBNeD@FkrQ8a8rpr6VvBbfcQlRggJ8lcJ2mwQS5EWHzMjXwYETMa8GwZG@Tvs30g5v2O8gXAyMCPsnegZ2Wri/0UTmQeWPrCv06NwfAI "JavaScript (Node.js) – Try It Online") ### How? We translate the input Cartesian coordinates \$(x,y)\$ into polar coordinates \$(r,\theta)\$ with: $$r=\sqrt{x^2+y^2}$$ $$\theta=\arctan\_2(y,x)$$ We use \$r\$ to determine whether the dart is located over the *Bullseye*, *25*, *Inner Single*, *Triple*, *Outer Single*, *Double* or if the shot is a *Miss*. If we're located over a *Single*, *Double* or *Triple*, we use \$\theta\$ to determine in which sector \$s\$ we are with: $$s=\left\lfloor\frac{\theta+\pi}{2\pi}\times20+\frac{1}{2}\right\rfloor=\left\lfloor\theta\times\frac{10}{\pi}+10+\frac{1}{2}\right\rfloor$$ For a \$340\times340\$ area, we need 4 decimal places of \$10/\pi\$ to get enough precision, which gives: $$\frac{10}{\pi}\approx3.1831$$ The base scores are stored counterclockwise in a base-36 encoded string of 21 entries, starting and ending at \$11\$: $$11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11$$ We need to repeat \$11\$ because half of this sector belongs to the first slice (where \$\theta\$ is close to \$-\pi\$), while the other half belongs to the last slice (where \$\theta\$ is close to \$+\pi\$). ### Graphical output The following ES6 code snippet draws the dartboard using the same logic as in the golfed code. ``` for(ctx = c.getContext('2d'), y = -180; y < 180; y++) { for(x = -180; x < 180; x++) { r = Math.pow(x * x + y * y, 0.5); s = Math.atan2(y, x) * 3.1831 + 10.5 | 0; ctx.fillStyle = [ '#000', '#fff', '#be3628', '#487f45', '#bbb', '#ddd' ][ r < 6 ? 2 : r < 16 ? 3 : (r < 99 ? 1 : r < 107 ? 3 : r < 162 ? 1 : r < 170 ? 3 : 4) ^ (s & 1) ]; ctx.fillRect(x + 180, y + 180, 1, 1); } } ``` ``` <canvas id=c width=360 height=360 style="width:360px;height:360px" /> ``` [Answer] ## JavaScript (ES6) + SVG(HTML5), ~~53 + 523~~ 51 + ~~519~~ 507 = ~~576~~ ~~570~~ 558 bytes ``` document.write`<svg width=345 height=345>`;i=b=Math.PI/10;s=Math.sin(a=-b/2);c=Math.cos(a);f=(r,f,n)=>document.write(`<path d=M172,172L${[172+r*s,172+r*c]}A${[r,r,0,0,1,172+r*t,172+r*d]}z fill=#${f} n=${n} />`);g=(q,r,m,n,i)=>f(q,i?474:`b32`,n*m)+f(r,i?`fff`:`000`,n);[3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11,8,16,7,19].map(n=>{t=s;d=c;s=Math.sin(a+=b);c=Math.cos(a);g(170,162,2,n,i=!i);g(107,99,3,n,i);});document.write`<circle cx=172 cy=172 r=16 fill=#474 n=25 /><circle cx=172 cy=172 r=6 fill=#b32 n=50` ``` ``` <body onclick=alert(+event.target.getAttribute`n`)> ``` Input is via mouse click, output via `alert`. Edit: Saved 12 bytes by using slightly more approximate colours as suggested by @Arnauld. [Answer] # Intel 8086/8087 assembly, ~~180~~ ~~144~~ ~~142~~ 138 bytes This uses the 8087 math co-processor for all of the trig and floating-point arithmetic. All calculations are done in hardware with 80-bit floating-point precision. ``` df06 b101 d8c8 df06 af01 d8c8 dec1 d9fa df1e b301 8b16 b301 33c0 81fa aa00 7c03 eb53 9083 fa06 7d05 b032 eb49 9083 fa10 7d05 b019 eb3f 90df 06b7 01df 06b5 01d9 f3df 06b1 01dd d2d9 ebde f9de c9de c1df 1eb3 01a1 b301 bb9c 01d7 83fa 6b7d 0a83 fa63 7c05 b303 eb09 9081 faa2 007c 04b3 02f6 e30b 0810 0713 0311 020f 0a06 0d04 1201 1405 0c09 0e0b 0a00 ``` Written as a MASM MACRO (basically a function), takes X and Y as coordinates and returns the calculated score in AX. The tie is broken clockwise. ``` MAX_BULL EQU 6 MAX_25 EQU 16 MIN_3X EQU 99 MAX_3X EQU 107 MIN_2X EQU 162 MAX_2X EQU 170 ; cartesian coordinates to radius ; ST = sqrt( X^2 + Y^2 ) ; input: X,Y (mem16,mem16) ; output: Radius (mem16) FCRAD MACRO X, Y, R FILD Y ; ST[] = Y FMUL ST,ST ; ST = y^2 FILD X ; ST[] = X FMUL ST,ST ; ST = x^2 FADD ; ST = ST + ST1 FSQRT ; ST = SQRT(ST) FISTP R ; R = ROUND(ST) ENDM ; cartesian coordinates to sector # ; input: X,Y (mem16,mem16) ; output: Sector (mem16) FCSEC MACRO X, Y, S FILD Y ; ST[] = Y FILD X ; ST[] = X FPATAN ; ST = atan2(Y,X) FILD CTEN ; ST[] = 10 FST ST(2) ; ST(2) = 10 FLDPI ; ST[] = pi FDIV ; ST = 10 / pi FMUL ; ST = A * ST FADD ; ST = ST + 10 FISTP S ; S = ROUND(ST) ENDM ; score the dart throw ; input: X / Y coordinates (mem16) ; output: Score (AX) SCORE MACRO X, Y LOCAL IS_BULL, IS_25, IS_3X, IS_2X, MUL_SCORE, DONE FCRAD X, Y, FDW ; FDW = radius(X,Y) MOV DX, FDW ; DX = FDW = radius XOR AX, AX ; score is initially 0 CMP DX, MAX_2X ; >= 170 (miss) JL IS_BULL ; if not, check for bullseye JMP DONE IS_BULL: CMP DX, MAX_BULL ; < 6 (inner bullseye) JGE IS_25 ; if not, check for 25 MOV AL, 50 ; score is 50 JMP DONE IS_25: CMP DX, MAX_25 ; < 16 (outer bullseye) JGE IS_3X ; if not, check for triple MOV AL, 25 ; score is 25 JMP DONE IS_3X: FCSEC X, Y, FDW ; FDW = sector(X,Y) MOV AX, FDW ; load sector # into AX MOV BX, OFFSET SCR ; load base score table XLAT ; put base score into AL CMP DX, MAX_3X ; < 107 (triple upper bounds) JGE IS_2X ; if not, check for double CMP DX, MIN_3X ; >= 99 (triple lower bounds) JL IS_2X ; if not, check for double MOV BL, 3 ; this is triple score JMP MUL_SCORE ; go forth and multiply IS_2X: CMP DX, MIN_2X ; >= 162 (double lower bounds) (> 170 already checked) JL DONE ; if not, single score MOV BL, 2 ; this is double score MUL_SCORE: MUL BL ; multiply score either 2x or 3x DONE: ENDM ; DATA (place in appropriate segment) SCR DB 11,8,16,7,19,3,17,2,15,10,6 ; score table DB 13,4,18,1,20,5,12,9,14,11 CTEN DW 10 ; constant 10 to load into FPU FDW DW ? ; temp DW variable for CPU/FPU data transfer ``` An example test program for PC DOS. Download it here [DARTTEST.COM](http://stage.stonedrop.com/ppcg/DARTTEST.COM). ``` INCLUDE DART.ASM ; the above file INCLUDE INDEC.ASM ; generic I/O routines - input int INCLUDE OUTDEC.ASM ; generic I/O routines - output int FINIT ; reset 8087 MOV AH, 2 ; display "X" prompt MOV DL, 'X' INT 21H CALL INDEC ; read decimal for X into AX MOV X, AX MOV AH, 2 ; display "Y" prompt MOV DL, 'Y' INT 21H CALL INDEC ; read decimal for Y into AX MOV Y, AX SCORE X, Y ; AX = SCORE( X, Y ) CALL OUTDEC ; display score X DW ? Y DW ? ``` ## Output Example usage of above [test program](http://stage.stonedrop.com/ppcg/DARTTEST.COM). Actual IBM PC with 8087, DOSBox or your favorite emulator required. ``` A>DARTTEST.COM X: 0 Y: 0 50 A>DARTTEST.COM X: 2 Y: 101 60 A>DARTTEST.COM X: -163 Y: -1 22 A>DARTTEST.COM X: 6 Y: 18 1 A>DARTTEST.COM X: -6 Y: 18 5 A>DARTTEST.COM X: 45 Y: -169 0 A>DARTTEST.COM X: 22 Y: 22 4 A>DARTTEST.COM X: -150 Y: 0 11 A>DARTTEST.COM X: -150 Y: 0 11 A>DARTTEST.COM X: -150 Y: -1 11 A>DARTTEST.COM X: -7 Y: -6 25 A>DARTTEST.COM X: -90 Y: 138 24 ``` \*Edits: * -36 bytes by removing truncate-rounding statement and 10.5 constant. Tie now broken clockwise. * -2 bytes by removing no longer necessary FRNDINT * -4 bytes, FMUL use same source/destination [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 56 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` æA/ư_9:18ị“!@umÞẓẓS’Œ?¤ ḅıA<“©Ñckɱȥ‘TṂị“2ı¢¤¢£¡‘¹×>3$?Ç ``` A monadic link accepting the pair as a list `[x,y]` which yields the score. Uses clockwise tie-breaking. **[Try it online!](https://tio.run/##y0rNyan8///wMkf9w22HNsRbWhlaPNzd/ahhjqJDae7heQ93TQai4EcNM49Osj@0hOvhjtYjGx1tgPKHVh6emJx9cuOJpY8aZoQ83NkE0WZ0ZOOhRYeWAPHiQwuBMod2Hp5uZ6xif7j9////uoZmxjoKuoYA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wMkf9w22HNsRbWhlaPNzd/ahhjqJDae7heQ93TQai4EcNM49Osj@0hOvhjtYjGx1tgPKHVh6emJx9cuOJpY8aZoQ83NkE0WZ0ZOOhRYeWAPHiQwuBMod2Hp5uZ6xif7j9/9FJD3fOeNS05uiew@1AKguIgRoUdO0UHjXMjfz/PzraQMcgVifaSMfQwBBI6xqaGevoglhmOoYWIAEobWIKFDazBCk10lEwMgJJmevomoFoSwMdQ2OL2FgA "Jelly – Try It Online") N.B. [a dyadic version is also 56 bytes](https://tio.run/##y0rNyan8///wMsfDbYc2xFtaGVo83N39qGGOokNp7uF5D3dNBqLgRw0zj06yP7SES@fhjtYjGx1tgAoOrTw8MTn75MYTSx81zAh5uLMJos/oyMZDiw4tAeLFhxYCZQ7tPDzdzljF/vDy////6xqaGQMJAA "Jelly – Try It Online") ### How? ``` æA/ư_9:18ị“!@umÞẓẓS’Œ?¤ - Link 1, segment score: pair [x, y] / - reduce by: æA - arc tangent ư - convert from radians to degrees _9 - subtract 9 (align 0 with boundary between 1 & 20) :18 - integer divide by 18 (yields a segment index from 0 to 19) ¤ - nilad followed by link(s) as a nilad: “!@umÞẓẓS’ - base 250 number = 2091180117530057584 Œ? - shortest permutation of natural numbers [1..N] which - would reside at that index in a list of all permutations of - those same numbers ordered lexicographically. - = [18,4,13,6,10,15,2,17,3,19,7,16,8,11,14,9,12,5,20,1] ị - index into (yields the score associated with the segment) ḅıA<“©Ñckɱȥ‘TṂị“2ı¢¤¢£¡‘¹×>3$?Ç - Main Link: segment score: pair [x, y] ı - √(-1) ḅ - convert from base = x+iy A - absolute value = √(x²+y²) “©Ñckɱȥ‘ - code-page index list = [6,16,99,107,162,170] - (i.e. the radial boundaries) T - list of truthy indexes Ṃ - minimal value (0 if empty) “2ı¢¤¢£¡‘ - code-page index list = [50,25,1,3,1,2,0] ị - index into - (i.e. get an override score (>3) OR a multiplier (<=3)) Ç - call last Link (1) as a monad (get the segment score) ? - if... $ - ...condition: last two links as a monad: > - (override OR multiplier) greater than? 3 - three ¹ - ...then: identity (keep override as is) × - ...else: multiply (by multiplier) ``` [Answer] # TI-Basic (TI-84 Plus CE), ~~147~~ 146 bytes ``` Prompt X,Y abs(X+iY→R int(E-12+11.5+10π-1R▸Pθ(X,Y→θ {11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11 25((R<6)+(R<16))+Ans(θ)(R≥16 and R<170)(1+(R≥162)+2(R≥99 and R<107 ``` Prompts for X and Y on separate lines. Tie-breaks counter-clockwise. TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/one-byte-tokens); all tokens used here are one byte. Explanation: ``` Prompt X,Y # 5 bytes, Prompt for X and Y abs(X+iY→R # 8 bytes, store distance from origin in R int(E-12+11.5+10π-1R▸Pθ(X,Y→θ # 22 bytes, store index in list of point values by polar angle in θ {11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11 # 55 bytes, list of point values 25((R<6)+(R<16))+Ans(θ)(R≥16 and R<170)(1+(R≥162)+2(R≥99 and R<107 # ~~57~~ 56 bytes, calculate the score ``` Utilizes the fact that TI-Basic boolean comparisons return 0 or 1 by adding them up and multiplying by point values. [Answer] # T-SQL, ~~392 374~~ 366 bytes ``` UPDATE t SET x=1WHERE x=0 SELECT TOP 1IIF(r<16,f,b*f) FROM(SELECT r=SQRT(x*x+y*y),w=FLOOR(10*ATN2(y,x)/PI()+.5)FROM t)p, (VALUES(10,11),(9,14),(8,9),(7,12),(6,5),(5,20),(4,1),(3,18),(2,4),(1,13),(0,6), (-1,10),(-2,15),(-3,2),(-4,17),(-5,3),(-6,19),(-7,7),(-8,16),(-9,8),(-10,11))s(a,b), (VALUES(6,50),(16,25),(99,1),(107,3),(162,1),(170,2),(999,0))d(e,f) WHERE a=w AND r<e ``` Line breaks are for readability. The initial `UPDATE` takes care of the `x=y=0` problem that would otherwise throw an error with `ATN2()`, but doesn't change the score. Input is taken via pre-existing table *t*, [per our IO guidelines](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Due to using `TOP 1`, this table should contain only a single row. Basically I'm joining 3 tables: * **Table p**: The *x* and *y* from input table **t** are converted to polar *r* and a "wedge" value *w* representing a number from -11 to positive 11, for the scoring wedge the dart fell into. "Tie breaker" is counter-clockwise. (I tried `ROUND()`, which was slightly shorter, but it gave an inconsistent tie breaker.) * **Table s**: This is a lookup table to convert a "wedge" value *a* into a score *b*. * **Table d**: This is a lookup table the returns the score calculation based on the distance from the center. *e* is the distance and joins to *r*, and returns only a single row based on the `TOP 1`. The value *f* is either a fixed score (for a bulls-eye) or a multiplier for the wedge score. **EDIT**: Dropped the `ORDER BY`, it seems to work properly without it, at least on SQL 2017. I also dropped the `AND y=0` on the update condition; I tested for all integer `y` values, changing `x=0` to `x=1` never changes the score. **EDIT 2**: Removed column *g* from table **d**, replaced it with an `IIF()` statement that either returns `f` directly (for a bulls-eye), or `f*b`, saved 8 bytes. Also removed the space after `TOP 1`. [Answer] # [Haskell](https://www.haskell.org/), 198 bytes ``` p=pure a#b=(!!(sum[1|k<-a,k<=b])) a!b=([6,16,99,107,162,170]#(sqrt$a*a+b*b))[p 50,p 25,id,(*3),id,(*2),p 0]$([pi/20,3*pi/20..6]#(pi+atan2 b a))[11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11] ``` Tie breaks counter-clockwise. `(#)` is a lookup function. The polar angle is used to index from the list of numbers, starting at the `atan2` cutoff point at 11. The distance is used to index from the list of functions `[const 50, const 25, id, (*3), id, (*2), const 0]` and at last this function is applied to the number we previously got. [Try it online!](https://tio.run/##LU5BboMwELzzClvJwSab1LsEJ0jhCX2BxWFRI9UiIBfIrX@nC/Q0szPamfnmqXu@XsuS6vQenxkf2tpobaZ3H/C3e5wZukfdNtZmrMUKHtBDVQG6mzACvLnmYKafcT5yzqc2b60NSZUOkqIS4heYvLA7khXRNUcTUvwgB0W@4eXiJSLFE888kGoVSwQi3NcqaamgkBqQrlJqQRYUcAUUGyRENALZIwo2S89xULXqOX2qNMZhzlRw2mUKSKNDQXNGX1gtYOXyGu@b6O3OruVq@Wo1iTTR/lI6u6X80/27Wf4A "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-MMath::Trig':pi' -MMath::Trig':radial' -apl`, 166 bytes ``` ($d,$a)=cartesian_to_cylindrical@F;$_=(1+($d>161||$d<6)+($d<107&&$d>98)*2)*($d<170)*($d<16?25:("6 134 181 205 129 14118 167 193 172 1510"=~/../g)[($a/pi*10+41/2)%20]) ``` [Try it online!](https://tio.run/##XYxNa4NAFEX3/opHsIljapz7dMaPJm1W3WXXXSkyaEgHRMW4KYT@9NqJdNXNu/ceDm84j62a58BvHn0jDrUZp/PVmq6a@qr@am3XjLY27fH1ya8OAbZOfIbG7eY3ey3ucw@ZrdcOF7kIWYQLyuRf0S@symClCUlKyEEsFYELQgrkBJ0RioSQMUFBrg7f8W4XX8R74Jt4sCHkNkXM4oHlh5hnSdJzpoQXQScUwXOfcy9abqoc0IXHTMxOUHd7iQg//TDZvrvO0elkps@yfBvtZVMOdvOPjKaxpnXUDO0v "Perl 5 – Try It Online") Takes the two coordinates space separated on STDIN. Tie-breaking is anticlockwise. ]
[Question] [ For this challenge, you should write a program or function which outputs the diagonals of a given square matrix. However, if you transpose the rows and columns of your solution's source code, it should instead become a program or function which returns the matrix's antidiagonals. Read on for specifics... ## Rules * The source code of your solution is considered as a 2D grid of characters, separated by a standard newline of your choice (linefeed, carriage return, or a combination of both). * No line in your source code may be longer than the previous one. Here are some examples of valid layouts: ``` ### ### ### ``` ``` ######## ####### ### ### # ``` And here is an example of an invalid layout (as the third line is longer than the second): ``` ###### #### ##### ### ``` * Your two solutions should be each others' transpose, that is you should obtain one from the other by swapping rows and columns. Here are two valid pairs: ``` abc def ghi ``` ``` adg beh cfi ``` And ``` print 10 (~^_^)~ foo bar ! ``` ``` p(fb! r~oa i^or n_ t^ ) 1~ 0 ``` Note that spaces are treated like any other characters. In particular, trailing spaces are significant as they might not be trailing spaces in the transpose. * Each solution should be a program or function which takes a non-empty square matrix of single-digit integers as input. One solution should output a list of all diagonals of the matrix and the other should output a list of all antidiagonals. You may use any reasonable, unambiguous input and output formats, but they must be identical between the two solutions (this also means they either have to be both functions or both programs). * Each diagonal runs from the top left to the bottom right, and they should be ordered from top to bottom. * Each antidiagonal runs from the bottom left to the top right, and they should be ordered from top to bottom. ## Scoring To encourage solutions that are as "square" as possible, the primary score is the number of rows or the number of columns of your solution, whichever is *larger*. Less is better. Ties are broken by the number of *characters* in the solution, not counting the newlines. Again, less is better. Example: ``` abcd efg h ``` This and its transpose would have a primary score of **4** (as there are 4 columns) and a tie-breaking score of **8** (as there are 8 non-newline characters). Please cite both values in the header of your answer. ## Test Cases The actual task performed by the two solutions shouldn't be the primary challenge here, but here are two examples to help you test your solutions: ``` Input: 1 2 3 4 5 6 7 8 9 Diagonals: 3 2 6 1 5 9 4 8 7 Antidiagonals: 1 4 2 7 5 3 8 6 9 Input: 1 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 Diagonals: 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 0 Antidiagonals: 1 0 0 1 1 1 0 0 0 0 1 1 1 0 0 1 ``` [Answer] # Javascript, score ~~20~~ 14, (~~258~~ 176 non-newline characters) ``` ///mmm()mu[=+r ///=.av=a,pr"= ///> p,>px=[ [ m=>//(yv()xp"] m. ////.(=+]+) map((////>y?u& v,y)=>v//r]r:& .map((u,x//[ur )=>r[p=m.//p) length-1-//], x+y]=r[p]//// ?r[p]+" "+u// :u),r=[])&&r ``` and ``` ///mmmv.)lx?: ///=.a,m=e+ru ///> pya>ny[) m=>//()prg]p, m. //(=([t=]r map(//>(phr+= (v,y//vu=-["[ )=>v.//,m1p ] map((//x.-]") u,x)=>r////+& [p=x+y]////u& =r[p]?r[p]//r +" "+u:u),// r=[])&&r ``` Example code snippet: ``` f= ///mmm()mu[=+r ///=.av=a,pr"= ///> p,>px=[ [ m=>//(yv()xp"] m. ////.(=+]+) map((////>y?u& v,y)=>v//r]r:& .map((u,x//[ur )=>r[p=m.//p) length-1-//], x+y]=r[p]//// ?r[p]+" "+u// :u),r=[])&&r console.log(f([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])) ``` and ``` f= ///mmmv.)lx?: ///=.a,m=e+ru ///> pya>ny[) m=>//()prg]p, m. //(=([t=]r map(//>(phr+= (v,y//vu=-["[ )=>v.//,m1p ] map((//x.-]") u,x)=>r////+& [p=x+y]////u& =r[p]?r[p]//r +" "+u:u),// r=[])&&r console.log(f([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), score 10 (100 non-newline characters) ``` %P! Q&% TXd! %d P! "@% Xz %z q ! ``` There are 10 lines of 10 characters (note the trailing spaces). The above code produces the diagonals. [Try it online!](https://tio.run/##y00syfn/XzVAUQECuBQUAtVUYcyQiBRFKFM1Ba4ACMDqIUwFJQdVGFMhogrGVK2CKwCCQgRT8f//aEMFIwVjawUTBVMFM2sFcwULBctYAA) The transposed version produces the anti-diagonals. [Try it online!](https://tio.run/##y00syfn/X1UBBrgCEEzFwBCoBJeCWkQKjKmaAlOgoKCoEABjAjlKCqpQpoJDRBWMqVoFUwAChYr//0cbKhgpGFsrmCiYKphZK5grWChYxgIA) ## Explanation Note that * `%` is a comment symbol, which causes the rest of the line to be ignored. * Two-char functions like `Xd` cannot be split into an `X` and a `d` in consecutive lines. ### Original code The original code, linearized and without the commented part, is ``` Q&TXd!P!"@Xzq! ``` which works as follows: ``` Q % Implicit input. Add 1 to each entry to make them positive & % This modifes default inputs/ouputs of next function, which is Xd % Specifically, it specifies 2 inputs and 1 ouput T % Push true Xd % Diagonals of matrix. With second input true, it gives all diagonals, % starting from below. The columns are arranged as columns of a matrix, % padding with zeros !P! % Flip horizontally. This is to produce the correct display order " % For each column @ % Push current column Xz % Remove zeros q % Subtract 1 ! % Transpose into a row % Implicit end. Implicit display of stack contents ``` ### Transposed code The transposed code, linearized, is ``` P!QT&Xd!P!"@Xzq! ``` which has the following two differences compared to the original code: * `T` and `&` are swapped. This has no effect, because `T` is a literal, not a function, so it doesn't intercept the `&` specification. * `P!` is added at the begining. The added code modifies the input matrix so that the diagonals of the modified matrix are the anti-diagonals of the input: ``` P % Implicit input. Flip vertically ! % Transpose ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), Score 7, 49 non-newline bytes # Diagonal printing program ``` ......U ......Œ ......D ......ṙ ......L ......Ṛ ŒDṙLṚUU ``` [Try it online!](https://tio.run/##y0rNyan8/18PDEK5IPTRSVCGC5R@uHMmlOUDF5nFdXSSC1DCB8gMDf3//390tKGOgpGOgnGsTrSJjoKpjoIZkGWuY6FjGRsLAA "Jelly – Try It Online") # Anti-diagonal-printing Program ``` ......Œ ......D ......ṙ ......L ......Ṛ ......U UŒDṙLṚU ``` [Try it online!](https://tio.run/##y0rNyan8/18PDI5O4oIwXKD0w50zoSwfuMgsKCtUQYEr9OgkF6AaH6Bo6P///6OjDXUUjHQUjGN1ok10FEx1FMyALHMdCx3L2FgA "Jelly – Try It Online") ## Older Answer(Unordered Output), Score 3, 6 non-newline bytes ## Diagonal-printing program ``` UU UŒ ŒD ``` [Try it online!](https://tio.run/##y0rNyan8/z80lCv06CSuo5Nc/v//Hx1tqKNgpKNgHKsTbaKjYKqjYAZkmetY6FjGxgIA "Jelly – Try It Online") ## Anti-diagonal printing program ``` UUŒ UŒD ``` [Try it online!](https://tio.run/##y0rNyan8/z809OgkLiB2@f//f3S0oY6CkY6CcaxOtImOgqmOghmQZa5joWMZGwsA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 4 (12 characters) previous scores: 5 (16 characters), 4 (16 characters) ### Original ``` ŒDṙṚ D ñ ṙLñL ``` [Try it online!](https://tio.run/##y0rNyan8///oJJeHO2c@3DmLy0VB4fBGLiDH5/BGn////0dHG@ooGOkoGMfqcClEm@gomOoomIHZ5joKFjoKlrGxAA "Jelly – Try It Online") ### Transpose ``` ŒDṙ D L ṙ ñ ṚñL ``` [Try it online!](https://tio.run/##y0rNyan8///oJJeHO2dyuSj4cAFphcMbgdSswxt9/v//Hx1tqKNgpKNgHKvDpRBtoqNgqqNgBmab6yhY6ChYxsYCAA "Jelly – Try It Online") ## Background ### Diagonals The straightforward way of obtaining the diagonals (topmost to bottommost) of a square matrix is as follows. ``` ŒDṙLṚ ``` For an input matrix **M**, `ŒD` lists **M**'s diagonals, starting with the main diagonal and moving upwards. For the input ``` 1 2 3 4 5 6 7 8 9 ``` this yields ``` 1 5 9 2 6 3 7 4 8 ``` `ṙL` then computes **M**‘s length with `L` and rotates the result **length(M)** units to the left. For our example, the length is **3** and we get ``` 7 4 8 1 5 9 2 6 3 ``` Finally, `Ṛ` reverses the order of the diagonals, returning ``` 3 2 6 1 5 9 4 8 7 ``` for our example input. ### Anti-diagonals The same building blocks can be used to obtain the anti-diagonals (again, topmost to bottommost) of a square matrix. ``` ṚŒDṙL ``` For an input matrix **M**, `Ṛ` first reverses the order of the rows. For the input ``` 1 2 3 4 5 6 7 8 9 ``` this yields ``` 7 8 9 4 5 6 1 2 3 ``` As before, `ŒDṙL` generates the diagonals (bottommost to topmost) of the result. For our example, this returns ``` 1 4 2 7 5 3 8 6 9 ``` as desired. ## How it works In Jelly, each line defines a *link* (function). In particular, the last line defines the *main link*, which is executed when the program starts. Other links must be called. This answer uses `ñ`, which executes the link below dyadically. `ñ` wraps around, so when it is called from the main link, it executes the link on the first line. ### Original The main link ``` ṙLñL ``` takes an input matrix **M**, computes its length with `L`, then rotates the input **length(M)** units to the left with `ṙ` (note that this doesn't alter **M**), and finally calls the first link with the result (**M**) and **length(M)** as arguments. The first link ``` ŒDṙṚ ``` computes the diagonals of **M** with `ŒD` (as seen in the previous section), rotates the result **length(M)** units to the left with `ṙ`, then reverses the order of the result with `Ṛ`. The second link is never called. ### Transpose The main link ``` ṚñL ``` takes an input matrix **M** and computes its reverse with `Ṛ`. It then computes the length of **M** with `L` and calls the first link with arguments **reverse(M)** and **length(M)**. The first link ``` ŒDṙ ``` then computes the diagonals of **reverse(M)** with `ŒD` (as seen in the previous section), and finally rotates the result **length(M)** units to the left with `ṙ`. The remaining links are never called. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~7~~ ~~9~~ 4 characters, score ~~4~~ 3 ``` ∂T m ↔ ``` [Try it online!](https://tio.run/##yygtzv7//1FHUwhXLtejtin///@PjjbUMdIxjtWJNtEx1TED0uY6FjqWsbEA "Husk – Try It Online") -4 characters thanks to [BMO](https://codegolf.stackexchange.com/users/48198/bmo). [Answer] # R, score ~~14 13~~ 11 (~~99~~ 95 non-newline characters) Thanks to @Giuseppe for improving the score by 1. Shaved off a few characters by making use of redundancies in the transpositions. Currently the best score for a non-golfing language! ``` ######`,scr `::`(#:fpoo pryr,#:)llw f)(###`(i(( split (#tmm p,col(p#()) )+row#r#m-) (p)))#y#,#) ######r ``` And transposed: ``` #`pfsp)(# #:r)p,+p# #:y(lcr)# #`r#ioo)# #(,#tlw)# #### (### `::`(pryr ,f)(#### split(m, col(m)-# row(m))) ``` [Try it online!](https://tio.run/##RY/RagQhDEXf8xVCXhI2C9X2pcL@i2VYYUAxZAam8/VTXQsbUE9Eco92Ve8erv7stv6Sj9/iPhlqeN/ZU2khLx8y1tw9S2D54iv7B@CrkmyLQYoxEcasrYHaaYKRSzkgM403tBLBpmXdHeFeK6gsrZAiMQPfrB1oWO8MpMyMJwry/3wDyKGHJc2b9mmA0VjlpoNOKotxp2S4tjaIBPdyDOrlRvqUG1Yg0wenC1WBoVH5jtAdOvD4GlXPPfR1wGjDbANffw "R – Try It Online") ]
[Question] [ Consider an array of unique integers, with an arbitrary length greater than 2. It is sometimes possible to express elements of the array as the sum of at least two other elements. For example, if our array is `[2, 3, 1]`, we can express `3` as the sum `2+1`. However, we can't express either `2` or `1` as the sum of other elements. Additionally, each integer in the list may only be used once in each sum. For example, with `[1, 2, 5]` we can't express `5` as `2+2+1` (or `1+1+1+2` etc.) as we can only use each element once per sum. Your program should take such array as input, via [any convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and output the elements of the input that are expressible as the sum of other elements. The output may be in any order, as may the input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so aim to make your code as short as possible, time / space complexity be damned. ## Test cases ``` input -> output [2, 3, 1] -> [3] [8, 2, 1, 4] -> [] [7, 2, 1, 4] -> [7] [7, 2, 1, 4, 6] -> [6, 7] [0, 1, -1] -> [0] [4, 2, -2, 0] -> [2, 0] [0, 1, 2] -> [] ``` Explanation for the last test case and result: For the purposes of this problem statement, zero cannot be considered the sum of a resulting empty list. Zero can only be in the resulting list IFF two or more other elements of the input list can be added to sum to it. In other words, do not assume that if 0 is in the input, it should always be in the output - you cannot choose an empty subset to cover it. The problem statement explicitly states that any element in the resulting list must be the sum of **other** elements. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ʒKæ¦Oyå ``` [Try it online!](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/2/9Qk78PLDi3zrzy89D@Qz8VVnpGZk6pQlJqYopCZx5WSz6WgoJ9fUKIP0Qal0EyyUVABq81L/R9tpKNgrKNgGMsVbaGjAOQY6iiYADnm2Dk6CmZAvgGYowvSZAKW0gViA7iEUSwXAA "Bash – Try It Online") ``` ʒ # keep numbers of the input where: K # the input with the number removed æ # all subsets of this ¦ # remove the first subset (the empty list) O # the sums of the subsets yå # contain the current number ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ɓḟŒPḊ§iµƇ ``` [Try it online!](https://tio.run/##y0rNyan8///k5Ic75h@dFPBwR9eh5ZmHth5r/3908sOdix81zFHQtVN41DD34Y5FQCWPGreFHW4/OunhzhlcD3dvOdz@qGlN5P//0UY6CsY6CoaxIMXRxrFc0RY6CkAxQx0FE4gYUMgcTcgcRUxHwQwibKajAJIxAAvrQo00AIqYgNXqArEBRBDMgqk0gtoDAA "Jelly – Try It Online") Essentially, we go over each element, `x`, of the input, `L`, and keep it if: * We remove `x` from the input, call that `L'` * We then get all non-empty subsets of `L'`, and get the sums of each * Finally, if `x` is in these sums, we keep it If `0` is not considered the sum of the empty list, then [+1 byte](https://tio.run/##y0rNyan8///k5Ic75h@dFPBwR9eh5ZmHth5r/3@4/eikhztnaEb@/x9tpKNgrKNgGKujEG2howDkGeoomIB4BmCmLljGHCgGkUTl6SiYgQSAPF0gF6jDCMSFGGkQCwA) ## How it works ``` ɓḟŒPḊ§iµƇ - Main link. Takes a list L on the left ɓ µ - Group the links between ɓ and µ into a dyad f(L, x): ḟ - Remove x from L, L' ŒP - Powerset of L' Ḋ - Remove the leading empty array § - Sums of each i - Index of x, or 0 if not present Ƈ - For each element, x, of L, keep it if f(L, x) is true ``` [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 54 bytes * +5 bytes to comply with the latest clarifications. ``` f a=[x|x<-a,elem x.tail.map sum$mapM(\y->0:[y|y/=x])a] ``` [Try it online!](https://tio.run/##Xc7NboJAEAfwO0/xP5AIyS6iNmoqy8mjfQLKYaOLToWFwJrsJr47XYpp0p5m5jeZj5sc7qquR2q6tjc4SiOTEw0GnOPr4WPV9jjf1PlO@jpWkKKwT5txyVStGtjESKqTRnYYHk3o40f06Xievhfu6ZbClrEsx0aSFpc2QESsjTM@dFJHS7HIF3EW5ldlTqRVgFoZWNEreQlJkwEd3FxNN@DHu560iQb/aFTBxkJMKRyzzMUBpitjsWbYMKxK8BzFpgyKPYO3FcPbbJ52/2j3xxi2M28Zpk76w/y1Mv2V9WvfNw "Haskell – Try It Online") [Answer] # Scala, ~~46~~ 64 bytes Fixed the zero problem thanks to Eric Duminil. ``` s=>s.filter(x=>(s-x).subsets.filter(_.nonEmpty)exists(_.sum==x)) ``` [Try it in Scastie!](https://scastie.scala-lang.org/D2G0zqFTTFmkHRbxDTLcPw) Not super interesting. Takes and outputs `Set`s. ``` s => //The input, s s.filter(x => //Keep only elements x that satisfy the following: (s-x).subsets //The subsets of s with x removed .filter(_.nonEmpty) //Keep the ones that aren't empty exists(_.sum==x)) //Contain a Set whose sum is x ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ ~~12~~ ~~11~~ 14 bytes *-1 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string); +3 due to rules clarification* ``` {∋.;?↔x⊇,0Ṁ+}ᵘ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRR7eetf2jtikVj7radQwe7mzQrn24dcb//9EmOgpGOgrxQGwQ@z8CAA "Brachylog – Try It Online") ### Explanation ``` { }ᵘ Find all unique outputs of this predicate: ∋. The output is an element of the input list ;? Pair the output with the input list ↔ Reverse (so we have [list, element]) x Remove that element from that list ⊇ Get an ordered subset of the remaining list ,0Ṁ Append a 0 and assert that the list has at least 2 elements (this excludes the empty subset from allowing a sum of 0) + Sum that subset That sum must also equal the output ``` Oddly, it seems that Brachylog doesn't have a builtin for "`? = .` is nonempty." I thought that `¬Ė` might work, but it didn't. [Answer] # JavaScript, 81 bytes ``` l=>l.filter((x,j)=>(g=(i,s)=>s==x||i in l&&(g(i+1,s)||j!=i&&g(i+1,~~s+l[i])))(0)) ``` [Try it online!](https://tio.run/##jcqxCsIwFIXh3aeIS7ihaWmqaJf0ARx0cCwORUy5IZTShFIh9NVjquBmcfsP59PN2Nj7gL1LxzIoGYysTKbQuMcAMHHNZAWtBOQ2lpVy8h4JdsRQCi1gIuLhvd5KpPSz59kmpsYbYwxyxkI/YOfgdL2cM@tit6ieoKAuONlxIha3@WVKTiITnOxX2fHLODmsyvzNUvEHKhYTXg) [Answer] # [R](https://www.r-project.org/), ~~102~~ ~~90~~ 93 bytes ``` function(x)x[sapply(seq(x),function(n){for(i in seq(a<-x[-n]))F=F|x[n]%in%combn(a,i,sum);F})] ``` [Try it online!](https://tio.run/##jc/BCoJAEAbge08xEMEuzIKmVFB29CVkEZOVFnS2XAWjenZTD1sQSYc5DPN//Ezda5vatkpNkZrmrOpUlapS1NioL1rKG22IdbxLbHa5lDdm1XVY0Z2I3wtTMw2aYLxlB9ElgiTncRQ/uoTkStMqN9WJWIYahyq@j59c/uxlOVsjBAg@57AEcYQkkIuZ9A5hAD5C6MBsfvud3/4JEDbObBDmmTcZ8X7Dm42HU4sYxnNiXP5B/ieS/Qs "R – Try It Online") *about -5 bytes thanks to @Dominic (needed little fix for 0-length sum, but waiting for clarification from OP)* [Answer] # [J](http://jsoftware.com/), 32 bytes ``` #~]e."p..1(+/@#~2#:@}.@i.@^#)\.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/letiU/WUCvT0DDW09R2U64yUrRxq9Rwy9RzilDVj9GL/a3KlJmfkK6irK@haKaQBdRoqGEGEjBVsgQJGQNoQVY0FUNBQwQQiaA5WZY4qZAZRCBVVMIOIG4CVgmyIh5poBHIpSKUJkBkP5P0HAA "J – Try It Online") Thanks to pppery for catching a subtle bug! * `1(...)\.]` Take the 1 outfixes of the input (eg, outfixes of `1 2 3` are `2 3`, `1 3`, and `1 2`) * `+/@#~2#:@i.@^#` For each, calculate all possible subset sums * `]e."p..` For each input number, is it an element of its corresponding outfix subset sum list? * `#~` Filter the input by that answer. [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~261~~ ~~275~~ 263 bytes ``` mod A is pr LIST{Int}*(sort List{Int}to L). op f : L -> L . op _,_ : L L -> L . op _,_,_ : L L L ~> Bool . vars A B C D E : L . eq f(A)= A,nil . ceq A B C,D = A C,D B if B,0,A C D . eq A,B = B[owise]. eq 0,1,A = true . ceq A,B,C D E = true if A + - D,1,C E . endm ``` ### Example Session ``` \||||||||||||||||||/ --- Welcome to Maude --- /||||||||||||||||||\ Maude 3.1 built: Oct 12 2020 20:12:31 Copyright 1997-2020 SRI International Mon May 24 21:41:40 2021 Maude> mod A is pr LIST{Int}*(sort List{Int}to L). op f : L -> L . op _,_ : L L -> > L . op _,_,_ : L L L ~> Bool . vars A B C D E : L . eq f(A)= A,nil . ceq > A B C,D = A C,D B if B,0,A C D . eq A,B = B[owise]. eq 0,1,A = true . ceq > A,B,C D E = true if A + - D,1,C E . endm Maude> red f(2 3 1) . reduce in A : f(2 3 1) . rewrites: 20 in 0ms cpu (0ms real) (~ rewrites/second) result NzNat: 3 Maude> red f(8 2 1 4) . reduce in A : f(8 2 1 4) . rewrites: 62 in 0ms cpu (0ms real) (62186 rewrites/second) result L: nil Maude> red f(7 2 1 4) . reduce in A : f(7 2 1 4) . rewrites: 55 in 0ms cpu (0ms real) (~ rewrites/second) result NzNat: 7 Maude> red f(7 2 1 4 6) . reduce in A : f(7 2 1 4 6) . rewrites: 405 in 1ms cpu (2ms real) (203415 rewrites/second) result NeList{Int}: 7 6 Maude> red f(0 1 -1) . reduce in A : f(0 1 -1) . rewrites: 32 in 0ms cpu (0ms real) (32096 rewrites/second) result Zero: 0 Maude> red f(4 2 -2 0) . reduce in A : f(4 2 -2 0) . rewrites: 160 in 0ms cpu (0ms real) (~ rewrites/second) result NeList{Int}: 2 0 Maude> red f(0 1 2) . reduce in A : f(0 1 2) . rewrites: 23 in 0ms cpu (0ms real) (~ rewrites/second) result L: nil ``` ### Ungolfed ``` mod A is pr LIST{Int} * (sort List{Int} to L) . op f : L -> L . op _,_ : L L -> L . op _,_,_ : L L L ~> Bool . vars A B C D E : L . eq f(A) = A, nil . ceq A B C, D = A C, D B if B, 0, A C D . eq A, B = B [owise] . eq 0, 1, A = true . ceq A, B, C D E = true if A + - D, 1, C E . endm ``` The answer is obtained by reducing the function `f`, which takes the list of integers. The helper function `_,_` (one infix comma) separates "unprocessed" from "keep", and `_,_,_` (two infix commas) decides if a given integer belongs in the output. This question was actually pretty good for Maude (relatively speaking). Its matching engine can handle matching a list pattern like `A B C` (where `A`, `B`, and `C` are sublists) and trying all possible partitions. I wasn't sure if I could accept input as a set rather than a list. If I could, I could save a few bytes because I could use set patterns like `A, B` (where `A` and `B` are sub*sets*) and match with commutativity. --- Added 12 bytes to handle the added requirement for 0, and also 2 bytes to fix a bug (forgot to pass `D` to `t` in the second equation). --- Bought back 12 bytes by switching to a system module (`fmod ... endfm` to `mod ... endm`) and renaming `f` and `t` to `_,_` and `_,_,_` to save on parens and whitespace. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~44~~ 30 bytes [crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/213718/17602) ``` FEX²LθΦθ﹪÷ιX²μ²F№⁻⁻θυιΣι⊞υΣιIυ ``` [Try it online!](https://tio.run/##bY49C8IwEIbn9lfceIE4WESHTqUiFFQKjqVD6VcCaWLbpArib48JBV285eC953m5mlVTrSphbacmwEt1x1w92gkjCudW9prhSAgFfxjdUo0RCjOpj3zhTYucwpcfPBgRN/AKg2SeeS/xZgY8caEd4vxEZ7Jpn14TxOOMxGHAO8Cr0pgqIzUan7oOn67Jz/fUnw4CuZnZasbhO8wn7rS0ml0bIbG1RXFwr1HYUthR2Jel3SziAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FEX²LθΦθ﹪÷ιX²μ² ``` Loop over all possible subsets of the input. ``` F№⁻⁻θυιΣι ``` See whether the sum is any of the elements of the input, not including the elements of the subset or sums found so far. ``` ⊞υΣι ``` If so then remember this sum. ``` Iυ ``` Output all the results. [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ïΩ▀▼ø▄GÉ. ``` [Run and debug it](https://staxlang.xyz/#p=8beadf1f00dc47902e&i=%5B4,2,-2,0%5D%0A%5B2,+3,+1%5D+%0A%5B8,+2,+1,+4%5D+%0A%5B7,+2,+1,+4%5D+%0A%5B7,+2,+1,+4,+6%5D+%0A%5B0,+1,+-1%5D+&m=2) idea borrowed from caird's answer. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 11 bytes ``` f}TsMty-QTQ ``` [Test suite](http://pythtemp.herokuapp.com/?code=f%7DTsMy-QTQ&test_suite=1&test_suite_input=%5B2%2C+3%2C+1%5D%0A%5B8%2C+2%2C+1%2C+4%5D%0A%5B7%2C+2%2C+1%2C+4%5D%0A%5B7%2C+2%2C+1%2C+4%2C+6%5D%0A%5B0%2C+1%2C+-1%5D%0A%5B4%2C+2%2C+-2%2C+0%5D&debug=1) *+1 byte to account for the new test case* Explanation: ``` f}TsMty-QTQ | Full program ------------+------------------------------------------ f Q | Filter the input for elements T such that }T | T is in sM | the sums of y | the powerset of -QT | the input with T removed t | with the empty set removed ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` ->l{l.flat_map{|x|[x]&(l+l.map{0}-[x]).combination(l.size+2).map(&:sum)}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkcvLSexJD43saC6pqImuiJWTSNHO0cPxDeo1QXyNfWS83OTMvMSSzLz8zRy9Iozq1K1jTRBKjTUrIpLczVra/8XKKRFR5vrKBjpKBjqKJjoKJgB2QaxsVxgCQMdQx0jBMdIR9dIxwTGN4bz/wMA "Ruby – Try It Online") If anybody finds another faling test, I am going to cry. [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes ``` lambda L:L&{sum(y)for y in reduce(lambda r,x:r+[s+[x]for s in r],L,[[]])if len(filter(None,y))>1} ``` [Try it online!](https://tio.run/##LcpBCsMgEADAr3gKu2QvCYVCoH2B9APWQ9ooFYyG1UAk5O2Gls55lpI/MfTV3p7Vj/NrGoUcZLOndYaCNrIowgXBZlrfBv6DaRu4ValVm/6W9CuaJCmlNTorvAlgnc@G4RGDoYJ47466sAsZLOxX6qmjy4FYTw "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes ``` Cases[Subsets@#,{a__}/;+a!=a:>+a]⋂#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zmxOLU4Org0qTi1pNhBWac6MT6@Vt9aO1HRNtHKTjsx9lF3k7La/4CizLySaGVduzQH5Vi1uuDkxLy6aq5qIx1jHcNaHa5qCx0jHUMdExDTHIOpYwbiGACZumDFJkBhXSMdA5ioUS1X7X8A "Wolfram Language (Mathematica) – Try It Online") Relies on the input not having duplicates. ``` Subsets@# subsets of input Cases[ ,{a__} ] that are nonempty, /;+a!=a with a sum unequal to their elements :>+a get sums ⋂# that are in input ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 80 bytes ``` ->x{x.select{|y|(2...x.size).any?{|i|(x-[y]).combination(i).any?{|z|z.sum==y}}}} ``` [Try it online!](https://tio.run/##Xc/NjoMgEAfwO08x6aWYwMR@pO2F7oNQ06ClWRJFU3WDSp/dRdw97JKQ/PnNQIZXnw/zU9xmfnWTw1aXuugmP3i6R8QAZtQJKjt8TN546rgcsgSLusqNVZ2pLTW/5dGP2PaVEMM7rNnYpu9AwEbuGRwY7DLgV5CHjMgLg2A7BsfVAp3/0fmPMTitfGKwVNLI/OfJNMgx9vKw0xVj2hASx0Ctis97aayGRw1@CZ4AKAZ5mHA5YtuUpqPb5e42wUo1k3def6mSuuQdeht4SpVhW7/CpwTkMRFtH/M3 "Ruby – Try It Online") This is still way too long and too readable. There must be a better way. At least it seems to be one of the few answers which pass every test case. ]
[Question] [ ## Background Sometimes when I'm golfing a program, I'm presented with the following situation: I have an integer value \$x\$ on some fixed interval \$[a, b]\$, and I'd like to test whether it's in some fixed subset \$S \subset [a, b]\$ with as few bytes as possible. One trick that sometimes works in a language where nonzero integers are truthy is finding small integers \$n\$ and \$k\$ such that \$x \in S\$ holds precisely when \$x + k\$ doesn't divide \$n\$, because then my test can be just `n%(x+k)`. In this challenge your task is to compute the minimal \$n\$ and \$k\$ from the fixed data. ## The task Your inputs are a number \$b\$ and a set \$S\$ of integers between \$1\$ and \$b\$ inclusive (we assume \$a = 1\$ for simplicity), in any reasonable format. You may take the complement of \$S\$ if you want. If you take \$S\$ as a list, you can assume it's sorted and duplicate-free. You can also assume \$b\$ is at most the number of bits in an integer and take \$S\$ as a bitmask if you want. Your output is the lexicographically smallest pair of integers \$(n,k)\$ with \$n \geq 1\$ and \$k \geq 0\$ such that for each \$1 \leq x \leq b\$, \$k+x\$ divides \$n\$ if and only if \$x\$ is *not* an element of \$S\$. This means that \$n\$ should be minimal, and then \$k\$ should be minimal for that \$n\$. Output format is also flexible. Note that you only have to consider \$k \leq n\$, because no \$k+x\$ can divide \$n\$ when \$k \geq n\$. The lowest byte count in each language wins. ## Example Suppose the inputs are \$b = 4\$ and \$S = [1,2,4]\$. Let's try \$n = 5\$ (assuming all lower values have been ruled out). * The choice \$k=0\$ doesn't work because \$k+1 = 1\$ divides \$5\$ but \$1 \in S\$. * The choice \$k=1\$ doesn't work because \$k+3 = 4\$ does not divide \$5\$ but \$3 \notin S\$. * The choice \$k=2\$ works: \$k+1 = 3\$, \$k+2 = 4\$ and \$k+4 = 6\$ don't divide \$5\$, and \$k+3 = 5\$ divides \$5\$. ## Test cases ``` b S -> n k 1 [] -> 1 0 1 [1] -> 1 1 2 [] -> 2 0 2 [1] -> 3 1 2 [2] -> 1 0 2 [1,2] -> 1 1 4 [1,2,4] -> 5 2 4 [1,3,4] -> 3 1 5 [1,5] -> 168 4 5 [2,5] -> 20 1 5 [3,4] -> 6 1 5 [2,3,4,5] -> 1 0 6 [1] -> 3960 6 8 [2,3,6,7] -> 616 3 8 [1,3,5,7,8] -> 105 1 8 [1,2,3,4,5] -> 5814 11 9 [2,3,5,7] -> 420 6 14 [3,4,6,7,8,9,10,12,13,14] -> 72 7 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ ~~20~~ ~~19~~ 18 bytes Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -1 byte! -1 byte inspired by [xash](https://codegolf.stackexchange.com/users/95594/xash)'s [Brachylog answer](https://codegolf.stackexchange.com/a/212162/64121)! ``` [¼¾ƒ²L¾ÑN-K¹Qi¾N‚q ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/@tCeQ/uOTTq0yefQvsMT/XS9D@0MzDy0z@9Rw6xCoKyhjrGOqY65jkUslwUA "05AB1E – Try It Online") or [Try most test cases!](https://tio.run/##TVBLTsMwEF3jU4xcUEBMaJ00bbqgYg@qxDr1ImlcEgnFIckOkLgCLDkGOySUhStxEC4SYtf9eDPvzbyZ8bwkrrNOrDIJtIvUj2p/P9TXnWo37wv3Vn3f56pd/L19PnUUXqCJ80dwV3DJepKJONXEZTCHspIPV3EiCGlE3dTX507EgTnEiZiNHDxLTfR2HI8QjjmMt9g/wgGHwPTskanaXI9tfmDGTwzQ@QlOOYS7eQFOMTR8sF1mG8O9PtD6mZ2vuzHEGbIRMg@Zj6zfyfovXRCylhXoQyEvgJ4@m5ujG/5KSSoJ2FdWedGsgZ65/qgGdw6012opJSfGcUO0rZUuAV0W2uShLJuhrOMkFzYc3E1lIbp/ "Bash – Try It Online") (based on the test-suite by [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for [this answer](https://codegolf.stackexchange.com/a/212123/64121).) ``` # see below for the remainder of the code ²L # push [1 .. b] ¾Ñ # push the divisors of n N- # subtract k from each # this is now a list of all x in [-k+1 .. n-k] with n%(x+k)==0 K # remove this from [1 .. b] ¹Q # is this equal to S? ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ 23 bytes First line of input is the set \$S\$, second one \$b\$. ``` [¼¾ƒ¾¹²L‚N+Ö_O¹gªËi¾N‚q ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/@tCeQ/uOTTq079DOQ5t8HjXM8tM@PC3e/9DO9EOrDndnHtrnBxQrBKoz1DHWMdUx17GI5bIAAA "05AB1E – Try It Online") This iterates through all possible pairs in lexicographical order and checks for each pair: \begin{align\*} \left|S\right| &=\left|\left\{ x \in [1 .. b] \mid x \;\text{does not divide}\; n \right\}\right| \\&= \left|\left\{ x \in S \mid x \;\text{does not divide}\; n \right\}\right| \end{align\*} **Commented**: ``` [ # infinite loop ¼¾ # increment and push the counter (n) ƒ # for N(=k) in [0 .. n]: ¾ # push n ¹ # push the first input (S) ²L # push [1 .. second input (b)] ‚ # pair these two lists up N+ # add current k to both lists Ö_ # do they not divide n (vectorizes) O # sum both lists ¹g # push the length of S ª # append this to the list Ë # are all equal? i # if this is true: ¾ # push n N # push k ‚ # pair n and k q # quit the program (implicit output) ``` [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` b!s=[(n,k)|n<-[1..],k<-[0..n],[x|x<-[1..b],mod n(k+x)>0]==s]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0mx2DZaI08nW7Mmz0Y32lBPL1YnG8gw0NPLi9WJrqipgIgmxerk5qco5Glka1do2hnE2toWxyoqGvzPTczMsy0oyswrUTFVjDbUMY39DwA "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~110~~ ~~91~~ 89 bytes Saved a whopping ~~19~~ 21 bytes thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!!! Blows up on TIO because of insane recursion depths! :( ``` f=lambda b,S,n=1,k=0:S==[x+1for x in range(b)if n%(k-~x)]and(n,k)or f(b,S,n+k//n,-~k%-~n) ``` [Try it online!](https://tio.run/##ZVLbjoIwFHznK/qyoY2HlZarJuxP@Oj6AAq7BC2m1ERj9NfZtuBykaThZGbOnB6Y803@1txry9O5FhI1t8ZS57PJpcj3F9GUNT@Wp1Ji6qqHtEVyTE/ZIUUZbIAnFKrEXW@SZHtd0KIW6IpKjkTKf3KckbJA/ANXzvNKdik/YA4VUZoCm@ZFtVxycJ7Vh/PkpJV5IxuUIGwh9WBMYbsjgNTbJQQGkPYoHVDWS9lYyl5SbyZl77ZaC@zd2Dc4@IYJgM0Yr2cmEwLNBJ1XGIM/YVjPMHfW8rIKZzjTQ1524yuH/@utQhfCgYi7phCizpCG4E1Yfe8AIog7UzcYj4y7jYehQUx9oCPFqvMPen@fTaYrsd5Fj4cYVkDVogyo@kLdfhGDSKuJJfS/tr8vLPL3NiBTUc8mlo6RhFwHyWRibaxVZFSDNLXKkapNjIgBzqLkEhf2PXug@@aBnC9056qs1BFbk7skyXcPm7R/ "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~92~~ ~~86~~ ~~85~~ ~~83~~ 82 bytes *Edit: -2 bytes thanks to Giuseppe, then -1 more byte thanks to Robin Ryder* ``` function(b,S)repeat for(k in 0:(F=F+1))if(all(1:b%in%S-!F%%(1:b+k)))return(c(F,k)) ``` [Try it online!](https://tio.run/##hZLRasIwFIbvfYozSiHFI/SkTZo6usvCrnbh7odKHUFJJFZ8/K4da6rT1ptA4Mt/vvyJa7Spq@/KfR3X2hXN7my2tbaGbXAVuepYrWvYWcf2oA3ES1YW5ZyiSO/Y@nBgtNyE2oSrxUsZht1uvo@i9lh9doZtWYntttkU9AqrYssiCGDxBgTx7Hro76iZp8hj9BDjN2F8JIzfhiXTYfyJWp@G/Ilc6kFM/1ABfBpNPDpmKXpU9OOlgnQK5R7l8XToMF1Og7wTHQxGmpL/es9lDPKehBZVQ67ErJcgCcnDZDX0JTBD1YvEYsRbDW9xbS4UpUA0C@DeKoDaWjgd7KX79PD5/rEEdzaga7DdegJ7MW10PqgLr57yh1ftfnbqu@6uigpzpBiJIyVIff8Zh@z@ePMD "R – Try It Online") Tests increasing velues of n (actually defined as `F` here, to exploit its default initial value of zero), and for each one loops through all `k` and returns `F,k` if they satisfy `!F%%(x+k) != x %in% S` for all `x` in `1:b`. Now 6 bytes shorter than my previous [recursive version](https://tio.run/##rZMxb4MwEIV3fsVVEZKtXCTOYOOkonunSE33ClBorSBTEaIOVX87BbVA0gBZOlr@7t17d3ZZG1vtX/fly3tsyqjOouxk08oUliW4QxsR/8yKkh3AWPA2lpuMxXnOaJO4xrq71Z113fa0PHDOy311Ki1LmcXm6GQ/GkviX3US0T3sopRxWMDqAQg857x1i3Knp6jHaBQTF2JiQkxcivnzYuKGtU4NxQ1zQQ9i8ItKEPOo36NTLmWHyq690hDMoaJHhTcvOnRX86BojQ4OJial/sx9rTxQzgKu2OY@i01@hMLC8@MWklMF2wN8mOoN8iKNc3hqio5V8@Ti9lE22nowojDsXJMCf9SKHgYsMUTdOffkRFA9LO88qtQUANE/hVgPIWQfIhDtlEY/RdCvqQ2NGtdIHpJA8pG61YUCwuvy@hs), *and* it can actually complete all the test cases without needing to increase the [R](https://www.r-project.org/) recursion limit and allocated stack size. [Answer] # JavaScript (ES6), ~~85 83~~ 82 bytes Expects `(b)(s)`, where `s` is a Set. Returns `[n, k]`. ``` b=>s=>{for(n=k=0;(g=x=>x&&n%(x+k)>0^s.has(x)|g(x-1))(b,k=k?k-1:++n););return[n,k]} ``` [Try it online!](https://tio.run/##lZLRToMwFIbvfYreuLTZYesppTCX4kN4udRkm4DKUgxMJVGfHbNETYBSt95//f7/nPO8fds2@/rp5RjY6iHrct3tdNro9COvamp1qfmaFrrVaTub2WvazkuW8vtm8bhtaMs@C9oGyBjdQanL2zLAm/ncsjVb19nxtbYbC6X56vaVbapDtjhUBc0pQUZt9k7usiPdGOJ@jDGyXBIk/MpDo/mHxiEtzneLsVuc7w79bmEu7d1zg5uf7i37NEgzSUdE@OnQRzt6Rz068iZXCZE@Xvh5wf16d/Q/XPlpcaruCDC9NHXBwawUJ2r4QTLQK4in9AoVCX38aXMRxJAYd3wejesng7txDeD3bhKUBEc/rAYNoukGUowngLK/vtMEIIEVIAcUgCGgND98LEjcfQM "JavaScript (Node.js) – Try It Online") ### Commented ``` b => s => { // b = upper bound; s = set of integers for( // main loop: n = k = 0; // start with n = k = 0 ( // g = x => // g is a recursive function taking x: x && // stop if x = 0 n % (x + k) > 0 // otherwise yield 1 if x + k does not divide n ^ s.has(x) // XOR with 1 if x belongs to the set | g(x - 1) // recursive call with x - 1 )( // initial call to g: b, // start with x = b k = // update k: k ? k - 1 // decrement k if it's not equal to 0 : ++n // otherwise, increment n and set k to n ); // end of call to g; break if it's falsy ); // end of loop return [n, k] // return the result } // ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ż⁴+þ⁸%T€i© 1ç1#‘,®’ ``` A full program accepting the set, \$S\$, and the upper bound, \$b\$, which prints the variables as a list, \$[n,k]\$. **[Try it online!](https://tio.run/##ATMAzP9qZWxsef//xbvigbQrw77igbglVOKCrGnCqQoxw6cxI@KAmCzCruKAmf///3sxLDV9/zU "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##S0oszvifmpyRr6D0/@juR41btA/ve9S4QzXkUdOazEMruQwPLzdUftQwQ@fQukcNM/8rKdQolCRm5ijoJitoGwI5GamJKSCOrqGCnUJBUX66XlZqTk4lF1dJanFJsa2GenWtgqE6l3q1IZSuVTCCcsG0EYyvg8TSMalVMIGwjZHYprUKpmA9cBZYFioGZEPFlcHGm8GEzXTMaxUsYMaZ6pjrWID5yhC7oPosYMpNQcotoaaDNOtY6FjqGBroGBrpGBrrGAJtNAQ6SJOLKy2/SAHkTYXMPAUllWqwj6MdYmuVuFLyuTjB4aCQVpqHFCwKEFW1QAV5qf8B "Bash - Try It Online") (without the two longest-running inputs). Kindly provided by [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman). ### How? ``` 1ç1#‘,®’ - Main Link: S, b 1 - set left to 1 1# - count up starting at x=left finding the first x which is truthy under: ç - call the helper Link as a dyad - f(x, S) ‘ - increment -> n+1 ® - recall the value from the register -> k+1 , - pair -> [n+1, k+1] ’ - decrement -> [n, k] - implicit print Ż⁴+þ⁸%T€i© - Link 1: potential_n, S Ż - zero-range -> [0..potential_n] (the potential k values) ⁴ - program's 4th argument, b þ - table of (implicitly uses [1..b]): + - addition ⁸ - chain's left argument -> potential_n % - modulo (vectorises) T€ - truthy 1-based indexes of each i - first index of (S); 0 if not found © - copy that to the register and yield it ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~129~~ \$\cdots\$ ~~111~~ 109 bytes ``` x;s;n;k;f(b,S){for(s=n=1;s;++n)for(k=0;k++<=n&&s;)for(x=b,s=S;x--;)s-=!(n%(x+k))<<x;printf("%d %d",n-1,k-2);} ``` [Try it online!](https://tio.run/##jVbbjpswEH3fr3CRdgWLURnu1KH9iDxu01WTkCrKll0teUBd5dtTAzPYGatSg5SB4zOHmYNt2EW/drvrdVC96tRJHfytXAcfh9d3v2@6BjQchl0wXp@aWJ3CcNV0Dw@9mqCh2cq@WashilTQR80nv7v3h/AUBKvVoN7ej9354Hv3e3G/92QXgTxFSaAuV42L3z@PnR/cfdwJ/RsBcW778/P2aSMa8QESZIJHpo8cj0JW01FLyC6K5a5hTr5IvE5QbAFSRsg4IZ@BZAEKqsdA5QLJbAErAlMLrAnMFwhivIONYd12KiTES8f2DZ7ykiEzzEKWBs9NSbksZWVGTFNcvTRaua1VLRWO95gfQCwhkZDePIlHTJjpmCzxaWBMMWYYc4wFxhJjhbGWZB2dkCKQJJAmkCiQKpAskC5U7szp5oL745/29eAjL/iM148EyBtCwgkJI6SckDJCxgkZI@SckDNCwQkFI5ScUDJCxQkVI9ScUDMCxI5TMae4ZnI3wbETuJ/gGArcUXAsBe4pOKYCdxUcW4H7Co6xwJ0Fx1qN2HOvHd7a3RloNcZ6vc1QsuyCC5TSyjSsjBalYeWuVuFq4SrPp01thipXi3avopr2JSyW9q/YYtIGVthY4pZCm1daF7EsDIyNFHqtpgalXuLclsV28kovdbBw7ClLbpSxrTLRm5m1Sc2j7X4eRa5E7zGmGDOMOcYCY4mxwlhLcohOSBFIEkgTSBRIFUgWSHfZpvSbVvjjfDl2@3bQBccKT1cCpxf1Y@bbgigRhhM7EPO7lmbfVivhK3ca36hl2HpzP3lSbANlZz6KNaWundRpXr8s451DMN1gJ7qLl6nIwNy3Hz8YxPGbJ70vnj7T99ncFqG/H/rT83rS@C9t5IeNgNXKHwVFJMASRcKPRviasQ3GYdcSnfVVeFba@MWEudymVlexzLR/eSz86fso@N7pPtuneDP@A3V7ubtc/wI "C (gcc) – Try It Online") Takes \$S\$ as an inverted bitmask of length \$b\$ and outputs \$n\$ and \$k\$ to `stdout`. ### Explanation ``` f(b,S){ // function f takes b as an int and S as a // inverted bitmask - the least significant // b-bits of S are unset only if that bit position // corresponds to a member of the original set S for(s=n=1; // loop starting with n=1 and s temporarily // set to 1 just to pass the first two loop tests s; // loop until s is 0 ++n) // bumping n up by +1 each time for(k=0; // inner loop trying values of k starting at 0 k++ // k is bumped up by +1 before use to offset b // which will be 1 less than needed <=n // loop until k is +1 greater than n &&s;) // or until we've hit our target for(x=b, // another nested for loop of x starting at b-1 s=S; // first real init of s to input bitmask x--;) // loop from b-1 down to 0 // which corresponds to b down to 1 // since x is offset by -1 s-=!(n%(x+k))<<x; // subtract off from s bits corresponding to values // for which n%(x+k) is false - because it's the // inverted bitmask // s will be 0 at the end of this most inner loop // iff n and k are our minimal targets printf("%d %d", // once we've discovered the smallest n and k n-1, // we need to compensated for loop increments k-2); // and k being offset by +1 } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ 29 bytes ``` W¬№ωθ≔⭆⁺L⊞OυθLθ¬﹪Lυ⊕κωI⟦Lυ⌕ωθ ``` [Try it online!](https://tio.run/##dY49C8IwFEX3/oqML/AEEVGhY6VQsNq9dAjtwwTyUdNEf35MdXDyjod7uHeUwo9O6JS6uEiIyCIvi5dUmhhcXYDKRRtWLjnnrBVz5YwRdoK1f5vJi@D810NWKx3IwwNZ66aoHZxp9GTIBprgQvYe8gTPxcb@eKfjAhqZ4WvKovMqL1ZiCdD/82uVH3xODVlJqT9hv8Ud7vGAx2FIm6d@Aw "Charcoal – Try It Online") Link is to verbose version of code. Takes \$ S \$ as an inverted bitmask of length \$ b \$ and outputs \$ n \$ and \$ k \$ on separate lines. Explanation: ``` W¬№ωθ ``` Repeat until the desired bitmask is found in the current bitmask. ``` ≔⭆⁺L⊞OυθLθ¬﹪Lυ⊕κω ``` Increment \$ n \$ and calculate the full bitmask for \$ 1 \leq k + x \leq n + b \$. ``` I⟦Lυ⌕ωθ ``` Output \$ n \$ and the index \$ k \$ of the input bitmask \$ S \$ in the full bitmask. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes ``` ∧.Ċℕᵐ≥₁fʰgᵗz≜-ᵐF&h⟦₁;Fx~t?∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3w/1HHcr0jXY9apgI5jzqXPmpqTDu1If3h1ulVjzrn6AIF3dQyHs1fBhS3dquoK7EHqv//PzraUCc6NlZHAUQbghlGUAEjJAEjMMMEKKJjpGOC4BhDOaYgjimMaYRgIikwAqkGycQCAA "Brachylog – Try It Online") ### How it works ``` ∧.Ċℕᵐ≥₁fʰgᵗz≜-ᵐF&h⟦₁;Fx~t?∧ . The output is Ċ [N, K], where … ℕᵐ N ≥ 0 and K ≥ 0, and … ≥₁ N ≥ K. fʰ Factors of N z zipped with gᵗ K: ≜-ᵐ label and take K from every factor. F Save the result as F. &h⟦₁ [1, …, b] ;Fx without the elements in F ~t? is S. ∧ Return output. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~63~~ 54 bytes ``` {{(n+^k),k:*&(&/x=)'~(n(1+)\y)!''n:*z}[^y?x;x:1+!x]/1} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxFTrt2gzAM3f0VypJAoh4sYRtDTtuP6EiTIQNLeujQoaQ56bcXWYZOug/dKw3d/V6Mh/O1xGu33xbbanoud7/FWNChfL+Vm91u7PY/j/58e52OU0eHzXSq6GHM0NNxY09pIsnkzHnlyDoJEnACwC2wVuhn6BXwAlaLZUvVmEiARonkPTQQhbbJ8+qRk7xsQoQWyAIxUA00d5pq6IP8B9XXx+e30Ji+0jNZNZW5wBs8vcAIV0PQnwQTWMGUCRnOBs8GL0atBq8RcZDXkEsUXRI8sAp1FiTtRfAaCBGcCJwFtrqw7AelLAVLZr4Z1m/aYCGYqCsBG01RgFpEOeyxwahJ6+e6qA/+F/pIDohMqyU+lziW5tmSZ6QaI7ZIFomRaiR9sGFo/gB3MoHF) * `{{...}[^y?x;x:1+!x]/1}` set up a "converge" `/` starting with an `n` of `1`, fixing `y` as `1..b`, and `x` as a boolean mask indicating whether or not each value of `1..b` is present in `S` (`1`s if not present, `0`s if present). each invocation returns a pair of integers, `(n;k)`, with the execution ending when a valid `k` is identified + `n:*z` store the first value of `z` in `n` + `(n(1+)\y)` generate a (n+1)-by-b matrix; columns represent potential values of `x`, with rows representing potential values of `k` + `~(...)!''n` identify pairs where `k + x` divides `n` + `(&/x=)'` determine if each pair is invalid because `x` is in (or not in) `S`, then determine if all `x`s are valid for this `k` + `k:*&` identify the first valid `k` (if there isn't one, this returns `0N`, an integer null) + `(...),k` append the identified value of `k`... + `(n+^k)` to `n` if a valid `k` was identified, or an incremented `n` if not [Answer] # [Husk](https://github.com/barbuz/Husk), ~~38~~ ~~33~~ ~~28~~ ~~22~~ 24 bytes *Edits: -5 bytes thanks to Razetime, then -6 bytes thanks to Zgarb, then +2 bytes to fix bug that failed to find solutions for which `k` is zero* ``` §,o←ḟVImλVö=²`Wḣ⁴`%¹+ŀ)N ``` [Try it online!](https://tio.run/##ATYAyf9odXNr///Cpyxv4oaQ4bifVkltzrtWw7Y9wrJgV@G4o@KBtGAlwrkrxYApTv///zX/WzEsNV0 "Husk – Try It Online") Arguments are integer `b` and list `S`; outputs pair of integers `(k,n)`. My second [Husk](https://github.com/barbuz/Husk) answer, and it took me *ages* to get it to work at all, so ~~I suspect it can still be golfed-down a lot~~ quite significantly golfed-down by Razetime & Zgarb... Checks increasing values of `n`, and calculates the lowest `k` that can satisfy `S == (n%(b+k)>0)`. Then retrieves this value, and its index, as `k` and `n`, respectively. *Edit:* In its original form, this missed solutions with `k` equal to zero, since this is the same result as failing to find a valid `k`. So now edited to calculate `k+1`, and then subtract 1 after retrieving the value. ***How?*** ``` mλVö=²`Wḣ⁴`%¹+ḣ)N # part 1: calculate first value of k+1 for each possible n m # map function to each element of list N # N = infinite list of natural numbers λVö=²`Wḣ⁴`%¹+ḣ) # lambda function taking 1 argument: V ŀ # find the first 1-based index of k in 0..n with a truthy result of ö=²`Wḣ⁴`%¹+ # function to check if true indices of n%(k+b) are equal to S ö # composition of 4 functions + # add b `%¹ # mod n `Wḣ⁴ # get set of truthy indices of 1..b =² # is this equal to S? # (note that because we take the 1-based index # of a range from 0..n, this part calculates k+1, # or zero if there is no valid k) §,o←ḟVI # part 2: return the first k, n § # fork: apply func1 to the results of func2 & func3 , # func1 = join as pair o←ḟ # func2 (takes 2 args, 2-part fucntion combined using o): # increment the first truthy element of arg1 (a function) applied to arg2 (a list) V # func3 (takes 2 args): first truthy index of arg1 (a function) applied to arg2 (a list) I # arg1 for both func2 & func1 = identity function # arg2 for both func2 & func1 is part1 above: the first k for each n (if any) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 70 bytes ``` /,/;++$k>$n?$k=0*++$n:0until"@{[grep$n%($k+$_),1..$`]}"eq$';$_="$n $k" ``` [Try it online!](https://tio.run/##DcpLDoIwEADQvaeYNGMUW6ADxV@DegFPQAxuiCHFoSIujPHqVpYveb4ZuiLc30t0CjmyIVWplRLdAfmIrtSrCbzXLx7bTpw@1W1oPPJ8@hLrSFGS4PXyFc0DFxbrUiADOhGCUQQZmBkZlYOBNWxgCzsgDZQB5UDm1/ux7fkZ4s6H@Fwkmv4 "Perl 5 – Try It Online") or less understandable and trickier 68 bytes # `-lp`, 68 bytes ``` /,/;++$\>$,?$\=0*++$,:0until"@{[grep$,%($\+$_),1..$`]}"eq$';$_="$, " ``` [Try it online!](https://tio.run/##FchLDoIwEADQvaeYTMb4YYAOFH8N6gU8ARh0gYaEQAVcGOPVrbh8z5ZdnTjiFNH01xdidaN8rwzl/3Ehh8bzxiE@jKWWI3inns1Q1Xh8Z/eutMTTOeUeFQuWIKDL@YPlg2aGihSJAZ3TLBCBnojmGDSsYA0b2IIokAgkBtHf1g5V2/TOr63zT0mg5Ac "Perl 5 – Try It Online") ]
[Question] [ Given two polynomials `f,g` of arbitrary degree over the integers, your program/function should evaluate the first polynomial in the second polynomial. `f(g(x))` (a.k.a. the *composition* `(fog)(x)` of the two polynomials) ### Details Builtins are allowed. You can assume any reasonable formatting as input/output, but the input and output format should match. E.g. formatting as a string ``` x^2+3x+5 ``` or as as list of coefficients: ``` [1,3,5] or alternatively [5,3,1] ``` Furthermore the input polynomials can be assumed to be fully expanded, and the outputs are also expected to be fully expanded. ### Examples ``` A(x) = x^2 + 3x + 5, B(y) = y+1 A(B(y)) = (y+1)^2 + 3(y+1) + 5 = y^2 + 5y + 9 A(x) = x^6 + x^2 + 1, B(y) = y^2 - y A(B(y))= y^12 - 6y^11 + 15y^10 - 20y^9 + 15y^8 - 6y^7 + y^6 + y^4 - 2 y^3 + y^2 + 1 A(x) = 24x^3 - 144x^2 + 288x - 192, B(y) = y + 2 A(B(y)) = 24y^3 A(x) = 3x^4 - 36x^3 + 138x^2 - 180x + 27, B(y) = 2y + 3 A(B(y)) = 48y^4 - 96y^2 ``` [Answer] # Haskell, ~~86~~ 72 bytes ``` u!c=foldr1((.u).zipWith(+).(++[0,0..])).map c o g=(0:)!((<$>g).(*))!pure ``` Defines a function `o` such that `o g f` computes the composition f ∘ g. Polynomials are represented by a nonempty list of coefficients starting at the constant term. ## Demo ``` *Main> o [1,1] [5,3,1] [9,5,1] *Main> o [0,-1,1] [1,0,1,0,0,0,1] [1,0,1,-2,1,0,1,-6,15,-20,15,-6,1] *Main> o [2,1] [-192,288,-144,24] [0,0,0,24] *Main> o [3,2] [27,-180,138,-36,3] [0,0,-96,0,48] ``` ## How it works No polynomial-related builtins or libraries. Observe the similar recurrences f(x) = a + f₁(x)x ⇒ f(x)g(x) = a g(x) + f₁(x)g(x)x, f(x) = a + f₁(x)x ⇒ f(g(x)) = a + f₁(g(x))g(x), for polynomial multiplication and composition, respectively. They both take the form f(x) = a + f₁(x)x ⇒ W(f)(x) = C(a)(x) + U(W(f₁))(x). The operator `!` solves a recurrence of this form for W given U and C, using `zipWith(+).(++[0,0..])` for polynomial addition (assuming the second argument is longer—for our purposes, it always will be). Then, `(0:)` multiplies a polynomial argument by x (by prepending a zero coefficient); `(<$>g).(*)` multiplies a scalar argument by the polynomial `g`; `(0:)!((<$>g).(*))` multiplies a polynomial argument by the polynomial `g`; `pure` lifts a scalar argument to a constant polynomial (singleton list); `(0:)!((<$>g).(*))!pure` composes a polynomial argument with the polynomial `g`. [Answer] # Mathematica, 17 bytes ``` Expand[#/.x->#2]& ``` Example usage: ``` In[17]:= Expand[#/.x->#2]& [27 - 180x + 138x^2 - 36x^3 + 3x^4, 3 + 2x] 2 4 Out[17]= -96 x + 48 x ``` [Answer] # TI-Basic 68k, 12 bytes ``` a|x=b→f(a,b) ``` The usage is straightforward, e.g. for the first example: ``` f(x^2+3x+5,y+1) ``` Which returns ``` y^2+5y+9 ``` [Answer] # Python 2, 138 ~~156 162~~ bytes The inputs are expected to be integer lists with smallest powers first. ``` def c(a,b): g=lambda p,q:q>[]and q[0]+p*g(p,q[1:]);B=99**len(`a+b`);s=g(g(B,b),a);o=[] while s:o+=(s+B/2)%B-B/2,;s=(s-o[-1])/B return o ``` Ungolfed: ``` def c(a,b): B=sum(map(abs,a+b))**len(a+b)**2 w=sum(B**i*x for i,x in enumerate(b)) s=sum(w**i*x for i,x in enumerate(a)) o=[] while s:o+=min(s%B,s%B-B,key=abs),; s=(s-o[-1])/B return o ``` In this computation, the polynomial coefficients are seen as digits (which may be negative) of a number in a very large base. After polynomials are in this format, multiplication or addition is a single integer operation. As long as the base is sufficiently large, there won't be any carries that spill over into neighboring digits. -18 from improving bound on `B` as suggested by @xnor. [Answer] # Python + SymPy, ~~59~~ 35 bytes ``` from sympy import* var('x') compose ``` *Thanks to @asmeurer for golfing off 24 bytes!* ### Test run ``` >>> from sympy import* >>> var('x') x >>> f = compose >>> f(x**2 + 3*x + 5, x + 1) x**2 + 5*x + 9 ``` [Answer] ## Sage, 24 bytes ``` lambda A,B:A(B).expand() ``` As of Sage 6.9 (the version that runs on <http://sagecell.sagemath.org>), function calls without explicit argument assignment (`f(2) rather than f(x=2)`) causes an annoying and unhelpful message to be printed to STDERR. Because STDERR can be ignored by default in code golf, this is still valid. This is very similar to [Dennis's SymPy answer](https://codegolf.stackexchange.com/a/78335/45941) because Sage is a) built on Python, and b) uses [Maxima](http://maxima.sourceforge.net/), a computer algebra system very similar to SymPy in many ways. However, Sage is much more powerful than Python with SymPy, and thus is a different enough language that it merits its own answer. [Verify all test cases online](http://sagecell.sagemath.org/?z=eJxNjk0KgzAQhfeCdxjoIolNbU2stQUXehDBYgTBn5Bom96-o9m4mXm8-ebN9KOezQL2Z8MAS2yXVhkDBcxaTZRcW_W5TuswEE6-hMEJ7Kq1UdaCJ8OgK4ZmfLcNlLx6lbRisXK6mVrKwiAMtOmnBTrqagFnkJHDeuewtYQdxxk6Hkr4Li7gDoBII1dLNJN0Uxsn8hzj0HkKHygOPF6qUxzKbN_DVJlHPjbJb_sb4sFB7EqyP3mzRek=&lang=sage) [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 19 bytes ``` (a,b)->subst(a,x,b) ``` which lets you do ``` %(x^2+1,x^2+x-1) ``` to get > > %2 = x^4 + 2\*x^3 - x^2 - 2\*x + 2 > > > [Answer] # MATLAB with Symbolic Toolbox, 28 bytes ``` @(f,g)collect(subs(f,'x',g)) ``` This is an anonymous function. To call it assign it to a variable or use `ans`. Inputs are strings with the format (spaces are optional) ``` x^2 + 3*x + 5 ``` Example run: ``` >> @(f,g)collect(subs(f,'x',g)) ans = @(f,g)collect(subs(f,'x',g)) >> ans('3*x^4 - 36*x^3 + 138*x^2 - 180*x + 27','2*x + 3') ans = 48*x^4 - 96*x^2 ``` [Answer] # Python 2, 239 232 223 bytes ``` r=range e=reduce a=lambda*l:map(lambda x,y:(x or 0)+(y or 0),*l) m=lambda p,q:[sum((p+k*[0])[i]*(q+k*[0])[k-i]for i in r(k+1))for k in r(len(p+q)-1)] o=lambda f,g:e(a,[e(m,[[c]]+[g]*k)for k,c in enumerate(f)]) ``` A 'proper' implementation that does not abuse bases. Least significant coefficient first. `a` is polynomial addition, `m` is polynomial multiplication, and `o` is composition. [Answer] ## JavaScript (ES6), ~~150~~ 103 bytes ``` (f,g)=>f.map(n=>r=p.map((m,i)=>(g.map((n,j)=>p[j+=i]=m*n+(p[j]||0)),m*n+(r[i]||0)),p=[]),r=[],p=[1])&&r ``` Accepts and returns polynomials as an array a = [a0, a1, a2, ...] that represents a0 + a1\*x + a2\*x2 ... Edit: Saved 47 bytes by switching from recursive to iterative polynomial multiplication, which then allowed me to merge two `map` calls. Explanation: *r* is the result, which starts at zero, represented by an empty array, and *p* is *g**h*, which starts at one. *p* is multiplied by each *f**h* in turn, and the result accumulated in *r*. *p* is also multiplied by *g* at the same time. ``` (f,g)=>f.map(n=> Loop through each term of f (n = f[h]) r=p.map((m,i)=>( Loop through each term of p (m = p[i]) g.map((n,j)=> Loop though each term of g (n = g[j]) p[j+=i]=m*n+(p[j]||0)), Accumulate p*g in p m*n+(r[i]||0)), Meanwhile add p[i]*f[h] to r[i] p=[]), Reset p to 0 each loop to calculate p*g r=[], Initialise r to 0 p=[1] Initialise p to 1 )&&r Return the result ``` [Answer] # Pyth, ~~51~~ 34 bytes ``` AQsM.t*LVG.usM.t.e+*]0k*LbHN0tG]1Z ``` [Test suite](http://pyth.herokuapp.com/?code=AQsM.t%2aLVG.usM.t.e%2B%2a%5D0k%2aLbHN0tG%5D1Z&test_suite=1&test_suite_input=%5B5%2C3%2C1%5D%2C%5B1%2C1%5D%0A%5B1%2C0%2C1%2C0%2C0%2C0%2C1%5D%2C%5B0%2C-1%2C1%5D%0A%5B-192%2C288%2C-144%2C24%5D%2C%5B2%2C1%5D%0A%5B27%2C-180%2C138%2C-36%2C3%5D%2C%5B3%2C2%5D&debug=0). [Answer] # [Ruby 2.4](https://www.ruby-lang.org) + [polynomial](http://adrianomitre.github.io/Polynomial/website/index.html), 41+12 = 53 bytes Uses flag `-rpolynomial`. Input is two `Polynomial` objects. If someone outgolfs me in vanilla Ruby (no polynomial external library), I will be very impressed. ``` ->a,b{i=-1;a.coefs.map{|c|c*b**i+=1}.sum} ``` [Answer] # [Maxima](http://maxima.sourceforge.net/), 34 bytes [Try it online!](https://tio.run/##dYzLCsIwEEV/ZZYzcQSbiBb7KT7KhLoIJGmwFcavj5GuXd3D4XCTaEhSn1okT2OZ4yfPKUgcoyQ/CVxudSO8Cvs7byEub7@s6FlZiKgO5RXyin9f0J5hD11/MAo76Fxv9GGbcacGrinX9sjwQ2uUaKhf) ``` lambda([a,b],expand(subst(b,x,a))) ``` ]
[Question] [ Everybody loves geometry. So why don't we try and code golf it? This challenge involves taking in letters and numbers and making shapes depending on it. # The Input The input will be in the form of `(shapeIdentifier)(size)(inverter)`. *But what are shapeIdentifier, size, and inverter?* The shape identifier is the identifier for the type of shape you will be making with `*`s. The following are the shape identifiers: * `s` - Square * `t` - Triangle The size will be between `1-20`, and it is the size of the figure. The inverter is whether or not the shape will be upside down, which is denoted by a `+` or a `-`. Do note: `s3-` == (equals) `s3+` because squares are symmetric. However, `t5-` != (does not equal) `t5+`. Trailing whitespace is okay in the output but leading whitespace is not. # Output Examples ``` Input: s3+ Output: *** *** *** Input: t5+ Output: * *** ***** Input: t3- Output: *** * ``` # Special Notes The triangle input will always be an odd number, so the triangles will always end with 1 `*` at the top. > > The size of the triangle is the size of the base if the inverter is > `+` and is the size of the top if the inverter is `-`. > > > [Answer] ## Pyth, ~~40~~ ~~36~~ ~~34~~ 32 bytes *-1 byte by @isaacg* ``` JstPz_W}\+zjl#m.[J*\*-J*}\tzyd;J ``` A semicolon inside a lambda is now the lambda variable's global value, a feature that saves one byte. ``` Implicit: z = input JstPz J = size. _W }\+z Reverse if "+" in z j l# m J Join the nonempty lines in map lambda d:... over range(J) .[J ; Pad the following with spaces (;) to length J *\* "*", this many times: -J*}\tzyd J if "t" not in z, otherwise the correct number for a triangle. ``` Try it [here](http://pyth.herokuapp.com/?code=JstPz_W%7D%5C%2Bzjl%23m.%5BJ%2a%5C%2a-J%2a%7D%5Ctzyd%3BJ&input=s5%2B&debug=1). [Test suite](http://pyth.herokuapp.com/?code=JstPz_W%7D%5C%2Bzjl%23m.%5BJ%2a%5C%2a-J%2a%7D%5Ctzyd%3BJ&input=s5%2B&test_suite=1&test_suite_input=s5%2B%0As10-%0At3%2B%0At5-%0At1%2B&debug=1). [Answer] # Pyth, 38 bytes ``` JsPtzj?}\szm*\*JJ_W}\-zm.[J*\*hyd;/hJ2 ``` [Test suite](https://pyth.herokuapp.com/?code=JsPtzj%3F%7D%5Cszm%2a%5C%2aJJ_W%7D%5C-zm.%5BJ%2a%5C%2ahyd%3B%2FhJ2&test_suite=1&test_suite_input=s3%2B%0At5%2B%0At3-&debug=0) Basically as straightforward as it gets. I wish I could combine some of the logic for the two shapes, but currently it's separate. [Answer] # JavaScript (ES6), 142 ~~146 147~~ **Edit** 1 byte saved thx @ETHproductions **Edit** 2 bytes sve thx @user81655 ``` i=>([,a,b]=i.match`.(.+)(.)`,Array(l=i<'t'?+a:-~a/2).fill('*'.repeat(a)).map((r,i)=>l-a?(' '.repeat(i=b<'-'?--l:i)+r).slice(0,a-i):r).join` `) ``` **Test** (run in FireFox) ``` F=i=>( [,a,b]=i.match`.(.+)(.)`, Array(l=i<'t'?+a:-~a/2).fill('*'.repeat(a)) .map((r,i)=>l-a?(' '.repeat(i=b<'-'?--l:i)+r).slice(0,a-i):r) .join`\n` ) function test() { O.textContent=F(I.value) } test() ``` ``` Input: <input id=I oninput="test()" value="t11-"/> <pre id=O></pre> ``` [Answer] ## Python 2, 106 bytes ``` s=raw_input() n=int(s[1:-1]) for i in[range(1,n+1,2),n*[n]][s<'t'][::2*('+'in s)-1]:print('*'*i).center(n) ``` The output is a perfect rectangle, with each line padded with trailing spaces, which I'm assuming is okay based on the comments in the OP. Note: I'm still never sure whether `input` is allowed in Python 2 for problems like these... [Answer] # Japt, ~~62~~ ~~60~~ ~~55~~ ~~52~~ 51 bytes ``` V=Us1 n;U<'t?Vo ç*pV):0oV2 £S²pY iY'*pV-X})·z2*!Uf- ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=Vj1VczEgbjtVPCd0P1ZvIOcnKnBWKTowb1YyIKNTsnBZIGlZJypwVi1YfSm3ejIqIVVmLQ==&input=InQ3KyI=) The first thing we need to do is figure out how big our shape needs to be. This is pretty simple: ``` // Implicit: U = input string, S = space V= // Set variable V to Us1 // everything after the first char of U, n; // converted to a number. This turns e.g. "12+" into 12. ``` Now we organize the shape of the output: ``` U<'t? // If U comes before "t" lexicographically (here, if the first char is "s"), Vo // make a list of V items, ç*pV) // and set each item to V asterisks. :0oV2 // Otherwise, create the range [0, V) with steps of 2 (e.g. 7 -> [0,2,4,6]), £ }) // and map each item X and index Y to: S²pY // Repeat 2 spaces Y times. This creates a string of Y*2 spaces. iY'*pV-X // At position Y in this string (right in the middle), insert V-X asterisks. · // Join with newlines. ``` By now, we have taken care of the size and shape of the output. All that's left is the rotation. Triangles are currently pointed up, so we need to flip them if the third char is `+`: ``` !Uf- // Take the logical not of U.match("-"). // If U contains "-", this returns false; otherwise, returns true. 2* // Multiply by two. This converts true to 2, false to 0. z // Rotate the list 90° that many times. // Altogether, this turns the shape by 180° if necessary. ``` And with implicit output, our work here is done. :-) [Answer] # Python 2, ~~235~~ ~~193~~ ~~167~~ 157 Bytes **Update:** Made some significant optimizing by using list comprehensions and str.center(). I have the feeling I can do some more tho, gonna hava a fresh look at it later. **Update 2** Saved 10 Bytes with the suggestions of Sherlock9. Thanks a lot! :) ``` d=raw_input() x=int(d[1:-1]) o="\n".join("*"*x for i in range(x))if d<"t"else"\n".join(("*"*i).center(x)for i in range(x,0,-2)) print o[::-1]if"+"in d else o ``` **Old answer** ``` d=raw_input() x=int(d[1:-1]) if "s" in d: for y in range(x): o+="*"*x+"\n" o=o[:-1] else: b=0 while x+1: o+=" "*b+"*"*x+" "*b+"\n" x-=2 b+=1 o=o[:-1] if d[-1]=="+": o=o[::-1] print o ``` Pretty straighforward approach. Writing line per line in a string which I output in the end. Triangles are always drawn inverted and get reversed if needed. The fact that you can multiply a string with an Integer saved me a lot of bytes! I will try to golf that down a bit more later, would appreciate suggestions in the meantime, since I am not that much exprienced with it yet. **edit:** Golfed it down a lot with the help in the comments and stealing the size-calculation from one of the other python-answers. I think thats the most I can do with this algorithm. [Answer] # JavaScript, 220 bytes. ``` q=s=>+s.slice(1,s.length-1);f=s=>s[0]=="s"?("*".repeat(q(s))+"\n").repeat(q(s)):Array.apply(0,Array(-~(q(s)/2))).map((_,n)=>(s[s.length-1]=="-"?~~(q(s)/2)-n:n)).map(n=>(" ".repeat(q(s)/2-n)+"*".repeat(n*2+1))).join("\n") ``` Run with `f(input here)` Try it [here!](https://jsfiddle.net/b88um9uq/) The squares has trailing newlines, but the triangles don't. Explanation: ``` q=s=>+s.slice(1,s.length-1); Define a function, q, that takes returns the argument, without the first and last character, casted into an integer. f=s=> Define a function, f, that takes one argument, s. (This is the main function) s[0]=="s"? If the first character of s is "s" then... ("*".repeat(q(s)) ) Repeat the "*" character q(s) times. ( +"\n") Append a newline to that .repeat(q(s)) Repeat that q(s) times. : Else... (the first character of s isn't "s") Array.apply(0,Array( )) Create an array of length... Array.apply(0,Array(-~(q(s)/2))) floor(q(s)/2)+1 .map((_,n)=> ) Map each element, _ with index n to... .map((_,n)=>(s[s.length-1]=="-"? )) If the last element of s is "-" then... .map((_,n)=>(s[s.length-1]=="-"?~~(q(s)/2)-n )) floor(q(s)/2)-n .map((_,n)=>(s[s.length-1]=="-"? : )) Else... .map((_,n)=>(s[s.length-1]=="-"? n)) Just n .map(n=> ) Map each element into... .map(n=>(" ".repeat(q(s)/2-n) ) Repeat " ", q(s)/2-n times. .map(n=>( )+"*".repeat(n*2+1))) Append "*", repeated 2n+1 times. .map(n=>(" ".repeat( )+"*".repeat(n*2+1))).join("\n") Join with newlines ``` [Answer] # Python 2, ~~157~~ 132 bytes ``` def f(s): S=int(s[1:-1]) for n in([range(1,S+2,2),range(S,0,-2)]['-'in s],[S]*S)['s'in s]: print "{:^{S}}".format('*'*n,S=S) ``` First attempt firgured that the `+/-` on the end was optional, getting rid of that let me shave off a bunch The idea here is to make a list which can get thrown into a generic output. Hardest part was separating out the length from the input. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~102~~ 85 bytes Byte count assumes that the source code is encoded as ISO 8859-1. ``` \d+ $0$*:¶ ^((\w)+):(:+) $1$2$3$2¶$0 m`s$|:t )`(.+)¶-(\D*) -$2¶$1 m`^. G`. T`ts:` * ``` [Try it online.](http://retina.tryitonline.net/#code=XGQrCiQwJCo6wrYKXigoXHcpKyk6KDorKQokMSQyJDMkMsK2JDAKbWBzJHw6dAoKKWAoLispwrYtKFxEKikKLSQywrYkMQptYF4uCgpHYC4KVGB0czpgICo&input=dDUt) I'll try to golf this some more later. [Answer] ## Seriously, 54 bytes ``` ,#i's=`≈;'**@½≈";#dXdXεj' +"£n`@`≈;'**n`@Iƒ('-=WXa0WXü ``` [Try It Online](http://seriously.tryitonline.net/#code=LCNpJ3M9YOKJiDsnKipAwr3iiYgiOyNkWGRYzrVqJyArIsKjbmBAYOKJiDsnKipuYEBJxpIoJy09V1hhMFdYw7w&input=dDkt) ``` ,#i Take input, push chars separately 's= Iƒ IF the first char is "s": ` `@ run the quoted function ≈;'**n make list of n strings of n *'s ` `@ ELSE run the quoted function: ≈; make two copies of int n '** use one to make string of n *'s @½≈ cut the other in half (e.g. 5->2) " "£n run n/2 times the quoted function: ;# copy the string as list of chars dXdX discard the last 2 *'s εj join back into string ' + prepend a space ('-=WX 0WX IF the third character is "-": a invert the stack ü pop and print the entire stack ``` @Mego: See that `#dXdXεj`? STRING SLICING???? [Answer] ## ES6, ~~178~~ ~~172~~ 159 bytes ``` s=>(p=s.match(/d+|./g),u=n=+p[1],m=n+1>>1,t=' '.repeat(n)+'*'.repeat(n),v=s<'t'?0:p[2]<'-'?(u=m,1):-1,[...Array(s<'t'?n:m)].map(_=>t.substr(u,u,u+=v)).join` `) ``` This works due to an interesting observation I made. If you repeat `n` spaces and `n` asterisks you get (e.g. for `n=5`) this: ``` ***** ``` Now, take substrings with the same start and length: ``` |*****| (5) | ***| (4) | *| (3) ``` These substrings are exactly the strings we need for `t5`. Edit: Saved 6 bytes thanks to @edc65. Edit: Saved 13 bytes thanks to hiding the `u+=v` in the third argument of `substr` thus allowing me to simplify the initialisation. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 48 bytes ``` ' *'jt4Y2m)U1$l't'Gm?2MQ2/:1L3$)R!P!R'+'Gm?P]]Q) ``` Uses [current version (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0) of the language/compiler. The code accepts input characters in any order: all `s11+`, `11s+` and even `1+s1` would be valid input strings. *EDIT (July 30, 2016): the linked code replaces `1L3$)` by `Y)` to conform to recent changes in the language* [**Try it online!**](http://matl.tryitonline.net/#code=JyAqJ2p0NFkybSlVMSRsJ3QnR20_Mk1RMi86WSlSIVAhUicrJ0dtP1BdXVEp&input=dDExKw) ### Explanation ``` ' *' % push string. Will be indexed into to obtain final result j % input string t % duplicate 4Y2 % predefined literal string '0123456789' m % logical index of digits in input string ) % index into input string to obtain substring with digits U % convert to number 1$l % generate square of ones with that size 't' % push character 't' G % push input string m % true if input string contains 't' ? % if so... 2M % push argument of call to function `l`, i.e. square size Q2/ % add 1 and divide by 2. Call result T : % generate vector [1, 2, ... T] 1L % predefined literal representing Matlab's `:` index 3$) % two dimensional index. Transforms square into rectangle R % remove (set to zero) lower-left corner !P! % flip horizontally R % remove lower-left corner. This gives inverted triangle '+' % push character '+' G % push input m % true if input contains '+' ? % if so... P % flip vertically ] % end if ] % end if Q % add 1. This gives array of values 1 and 2 ) % index string ' *' with this array to produce char array % implicitly display that char array ``` [Answer] # C, 259 bytes ``` #define x(y);)putchar(y) #define m(n)for(n=0;n++< #define T {m(q)i x(32);m(q)s-i*2 x(42);puts("");} main(q,v,i,s)char**v;{s=atoi(v[1]+1);if(*v[1]=='s')m(i)s*s x(42)&&!(i%s)&&puts("");else if(strchr(v[1],'+'))for(i=s/2+1;i-->0;)T else for(i=-1;i++<s/2+1;)T} ``` ### ungolfed ``` main(q,v,i,size)char**v; // neat way of declaring variables { size=atoi(v[1]+1); if(*v[1]=='s') { for(i=0;i++<size*size;) { putchar(42); // returns 42 (true) if(!(i%size)) puts(""); } } else if(strchr(v[1],'+')) // if finds plus sign { for(i=size/2+1;i-->0;) // iterate the height of the triangle { for(q=0;q++<i;)putchar(32); // conveniently i is the number os spaces before each line for(q=0;q++<size-i*2;) putchar(42); puts(""); } } else for(i=-1;i++<size/2+1;) // does the same as above but inverted order { for(q=0;q++<i;)putchar(32); for(q=0;q++<size-i*2;)putchar(42); puts(""); } } ``` Suggestions and critique are very welcome. [Answer] # Ruby, 99 ``` ->s{n=s[1,2].to_i n.times{|i|d=(s.ord-115)*(s[-1]<=>?,)*(n-1-i*2) d<1&&puts((?**(n+d)).center(n))}} ``` Calculates a square or triangle of height `n` and *average width* `n` by verying the slope of the sides (so the calculated triangle width is 2n-1 at the base, 1 at the tip.) But it only *prints* those rows which do not exceed `n` characters. **ungolfed in test program** ``` f=->s{ #take a string as an argument n=s[1,2].to_i #take 2 characters starting at index 1 and convert to a number for the size n.times{|i| #iterate through n rows d= #calculate how many stars "MORE THAN" n we need on a row (s.ord-115)* #ascii code for 1st character of string - 115 : s-->0, t-->1 (s[-1]<=>?,)* #compare last character of input with comma character - --> +1 + --> -1 (n-1-i*2) #row number * 2: 0 at centre, positive above it, negative below it d<1&& #only output if d is nonpositive (i.e we need less than n or exactly n stars) puts((?**(n+d)).center(n)) #print n+d stars, centred in a field of n characters padded by whitespace } } f[gets.chomp] ``` [Answer] # Jolf, 37 bytes, noncompeting I added functions after this challenge was posted, so this cannot be considered for acceptation. This is encoded in ISO-8859-7. [Try all test cases here](http://conorobrien-foxx.github.io/Jolf/#code=b25Gac6S4oKsaW9TZ2nOsz89J3Nu4oCVc86SJyrigJVUzpIxJyo_PSctU1ppzrPOsw&input=czMrCgp0NSsKCnQzLQ). ``` onFiΒ€ioSgiγ?='sn―sΒ'*―TΒ1'*?='-SZiγγ ``` ## Part 1: parsing the string ``` onFiΒ€ioSgi on set n to Fi the first entity of i (the shape identifier) Β set Β (beta) to €i the "inside" of i (in this case, the size) as a number oS set S to gi the last entity of i (the inverter) ``` ## Part 2: obtaining the result ``` γ?='sn―sΒ'*―TΒ1'* γ set γ (gamma) to the result of the following expression ?='sn if n is the character s, ―sΒ'* then return a pattern "s" (a square) made with "*"s ―TΒ1'* otherwise, return a pattern "T" (triangle) that is centered and has a scale factor of 1, made with "*"s ``` ## Part 3: inverting the result ``` ?='-SZiγγ ?='-S if S is a "-" Ziγ return γ, inverted across its lines γ otherwise, return γ untouched ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 22 bytes ``` [⁰(×⁰*,)|¹ƛ×*¹↳øm;⁰ßṘ⁋ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5B%E2%81%B0%28%C3%97%E2%81%B0*%2C%29%7C%C2%B9%C6%9B%C3%97*%C2%B9%E2%86%B3%C3%B8m%3B%E2%81%B0%C3%9F%E1%B9%98%E2%81%8B&inputs=0%0A5%0A1&header=&footer=) ``` [ # If truthy (square) then... ⁰( ) # (size) times ×⁰*, # Print (size) asterisks | # Else... ¹ƛ ; # Map input to... ×* # That many asterisks ¹↳ # Right-justified to triangulate øm # Palindromise ⁰ßṘ # If (input), reverse ⁋ # Join by newlines ``` ]
[Question] [ Consider a square block of text, N characters wide by N tall, for some odd integer N greater than 1. As an example let N = 5 and the text be: ``` MLKJI NWVUH OXYTG PQRSF ABCDE ``` Notice that this is the alphabet (besides Z) spiraled around counter-clockwise from the lower left corner. It's kind of like a rolled up carpet. ![Spiral Alphabet](https://i.stack.imgur.com/x1I7y.png) "Unrolling" the text by one quarter turn clockwise so `FGHI` are on the same level as `ABCDE` results in: ``` PONM QXWL RYVK STUJ ABCDEFGHI ``` This unrolling can be done 7 more times until the text is a single line: ``` SRQP TYXO UVWN ABCDEFGHIJKLM UTS VYR WXQ ABCDEFGHIJKLMNOP WVU XYT ABCDEFGHIJKLMNOPQRS XW YV ABCDEFGHIJKLMNOPQRSTU YX ABCDEFGHIJKLMNOPQRSTUVW Y ABCDEFGHIJKLMNOPQRSTUVWX ABCDEFGHIJKLMNOPQRSTUVWXY ``` # Challenge The challenge is to write a program that is an N×N block of text that outputs the number of times it has "unrolled" by a quarter turn when it is rearranged into the unrolling patterns and run. There are really two contests here: (hopefully it won't be too messy) 1. Do this with the smallest N. (down to a limit of N = 3) 2. Do this with the largest N. (no limit) There will not be an accepted answer but the winner in each of these categories will receive at least 50 bounty rep from me. In case of ties the oldest answers win. # Example If your code block is ``` MyP rog ram ``` running it as is should output 0. Running ``` rM oy ramgP ``` should output 1. Running ``` or ramgPyM ``` should output 2. Running ``` o ramgPyMr ``` should output 3. Finally, running `ramgPyMro` should output 4. # Details * The output should be printed to stdout (or the closest alternative) by itself. There is no input. * You may only use [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex codes 20 to 7E, that includes space) in your code. * Spaces fill the empty space in the unrolling arrangements. (Unless you're unrolling to the left.) * Only the arrangements from completely square to completely flat need to have valid output. No other arrangements will be run. * You may not read your own source. * You may use comments. * N = 1 is excluded since in many languages the program `0` would work. * If desired you may unroll to the left rather than the right. So e.g. ``` MyP rog ram ``` becomes ``` Pg yo Mrram ``` and so on. No extra spaces are added when rolling this way. The lines just end (Related: [Write a Rectangular Program that Outputs the Number of Times it was Rotated](https://codegolf.stackexchange.com/questions/33150/write-a-rectangular-program-that-outputs-the-number-of-times-it-was-rotated)) [Answer] ### Golfscript, N <- [5,7..] ``` . . . . .. . .# ],9\- ``` Fully unrolled: ``` ],9\-# . . . . . ... ``` Explanation: * `.` (multiple times) - duplicate the input * `]` - collect the stack into a single array * `,` - take its length * `9\-` - subtract it from 9 * `#` - line comment Whitespace is a NOP, but any other NOP would have worked just as well. Fully rolled up, it uses nine copies of the input (contents ignored) as the stack; 9 - 9 = 0; it has not been unrolled. Each unroll hides one more dot (duplicate) behind the comment, shrinking the stack once, incrementing the output. Fully unrolled, it uses only the input (contents ignored) as the stack; 9 - 1 = 8; it has been unrolled 8 times. The same approach works for any N > 4: Change `9` to the appropriate value of 2\*N+1, then extend the pattern of dots (duplicate) using the same spiral pattern that ensures exactly one dot gets unrolled during each unroll. [Answer] ## GolfScript, N = 4 This one right rolls as original spec. ``` .. . ...# .#.~ ],8- ``` Here are the unrolls: ``` ... #.. .. ],8-~#. .#. ... ],8-~#. .. .. .# ],8-~#. .... .. ],8-~#. ....#. . ],8-~#. ....#.. ],8-~#. ....#... ``` [Try it here](http://golfscript.apphb.com/) [Answer] # APL, N = 3 ``` 201 340 5|0 ``` Unrolled: ``` 32 40 5|001 43 5|00102 4 5|001023 5|0010234 ``` [Try it online.](http://ngn.github.io/apl/web/index.html#code=201%0A340%0A5|0) It calculates the remainder of that number divided by 5. Only the result of last line is printed. # APL, N = 2 ``` ⍬∞ ≡0 ``` Unrolled: ``` ⍬ ≡0∞ ≡0∞⍬ ``` [Try it online.](http://ngn.github.io/apl/web/index.html#code=%u236C%u221E%0A%u22610) `≡` returns the depth (not to be confused with the dimension or length) of an array: * `0` is not an array. So the depth is 0. * `0∞` is an array with two items `0` and `∞` (infinity). It has depth 1. * `0∞⍬` has another item `⍬`, which is an empty array with depth 1. So `0∞⍬` has depth 2. These two programs also works in the online interpreter. I'm not sure if the later one is syntactically correct. ``` ⍬0 ≡∞ ``` ``` ⍬¯ ≡0 ``` # APL, for any N >= 4 For N = 4: ``` ∞ ∞ ∞∞ ∞ ∞ ⍴1↓∞ ``` Fully unrolled: ``` ⍴1↓∞ ∞ ∞ ∞ ∞∞∞ ``` For N = 5: ``` ∞ ∞ ∞ ∞ ∞∞ ∞ ∞ ⍴1↓ ∞ ``` Fully unrolled: ``` ⍴1↓ ∞ ∞ ∞ ∞ ∞ ∞ ∞∞∞ ``` `1↓` removes an item in the array. It also returns the empty array if the argument is scalar. `⍴` gets the array length. ]
[Question] [ # Challenge description We've had a few challenges involving the [Look-and-say sequence](https://en.wikipedia.org/wiki/Look-and-say_sequence). Quick reminder: * The sequence starts with `1`, * Subsequent terms of this sequence are generated by enumerating each group of repeating digits in the previous term, So the first few terms are: ``` 1 "one" 11 "one one" (we look at the previous term) 21 "two ones" 1211 "one two, one one" 111221 "one one, one two, two ones" 312211 "three ones, two twos, one one" ``` Now let's do the same thing, but use [Roman Numerals](https://en.wikipedia.org/wiki/Roman_numerals) instead. We start with `I` and follow the same rules (we apply the digit-counting rule to characters instead, so we read `IVX` as `one one, one five, one ten` instead of `one four, one ten` or some other way): ``` I "one" II "one one" III "two ones" = "II" + "I" IIII "three ones" = "III" + "I" IVI "four ones" = "IV" + "I" IIIVII "one one, one five, one one" IIIIIVIII "three ones, one five, two ones" = ("III" + "I") + ("I" + "V") + ("II" + "I") ``` Given a positive integer `N`, either: * Output first `N` numerals of this sequence (any reasonable separator is fine, as well as `["I", "II", "III", ...]` * Output `N`th term of this sequence (it may be 0-indexed). Remember to make your code as short as possible, since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge! EDIT: I believe that there is always one standard/preferred way of expressing integers as roman numerals, (like `95` -> `XCV` instead of `VC`). Couple of Roman numeral converters I found online corroborate my opinion. If in doubt, use [an online converter](http://www.onlineconversion.com/roman_numerals_advanced.htm), as listing all the possible edge-cases and specific rules of writing Roman numerals is not the point of this challenge. EDIT2: @PeterTaylor and @GregMartin pointed out that only numbers less or equal to `5` appear in the sequence, so you don't have to worry about the ambiguity of Roman numerals (numbers `1` - `8` are `I`, `II`, `III`, `IV`, `V`, `VI`, `VII`, and `VIII`) [Answer] # Perl, 49 bytes Includes +1 for `-p` Run with the 0-based index on STDIN, e.g. ``` ecce.pl <<< 14 ``` `ecce.pl`: ``` #!/usr/bin/perl -p s,(.)\1*,$&/$1%182 .$1,eg for($_=/$/)x$`;y;19;IV ``` Magic formulas are so magic. Normally I would use `($_=//)x$'` to make the loop control one byte shorter, but scoring on this site gives that a handicap of 2 so it ends up 1 byte longer. On older perls you can drop the space before `for`. Some versions of perl force you to add a final `;` to close the transliteration. But what is given above is the code that works on my system. ## Explanation Working backwards from solution to code: The string transformations we need: ``` I -> II II -> III III -> IIII IIII -> IVI IIIII -> VI V -> IV VV -> IIV ``` Each replacement ends with the repeated character. I will get a sequence of the same characters using regex `/(.)\1*/`, so this can be done by appending `$1`. The part before the `->` is in `$&`. With that I still need: ``` I -> I II -> II III -> III IIII -> IV IIIII -> V V -> I VV -> II ``` Write `I` as `1` and `V` as 9: ``` 1 -> 1 11 -> 11 111 -> 111 1111 -> 19 11111 -> 9 9 -> 1 99 -> 11 ``` By dividing the part before `->` by the repeated digit this becomes: ``` 1 -> 1 11 -> 11 111 -> 111 1111 -> 19 11111 -> 9 1 -> 1 11 -> 11 ``` So now the original repeated `V` is not an exception anymore. So I want an expression that makes this happen: ``` 1 -> 1 11 -> 11 111 -> 111 1111 -> 19 11111 -> 9 ``` And this can be done by a simple modulo 182: ``` 1 % 182 = 1 11 % 182 = 11 111 % 182 = 111 1111 % 182 = 19 11111 % 182 = 9 ``` (this even gets `IIIIII` to `VI` right though it isn't needed here) All that is left is initializing the working variable to `1` for index 0, repeat this transformation in a loop and at the end replace `1` by `I` and `9` by `V` `1`, `9` and `182` is the only parameter combination for which this simple formula works. [Answer] # Mathematica, ~~113~~ ~~90~~ 83 bytes *Thanks to Martin Ender for suggestions that reduced the length by over 25%!* Showing off the high-level commands in Mathematica. ``` Nest[Flatten[Characters@{RomanNumeral@#,#2}&@@@Reverse@@@Tally/@Split@#]&,{"I"},#]& ``` A pure function, taking an argument N and outputting the Nth element of this (0-indexed) sequence, as a list of characters. Spread out a bit: ``` Nest[ Flatten[ Characters @ {RomanNumeral@#,#2}& @@@ Reverse @@@ Tally /@ Split@ # ]& , {"I"}, #]& ``` The outer `Nest` iterates the middle four-line function, starting on `{"I"}`, N times. Line 4 splits the character list of the input Roman numeral into runs of like characters, counts each run with `Tally`, and puts the counts before the characters they're counting. Line 3 renders the counts as Roman numerals, then splits those Roman numerals up into lists of characters. The `Flatten` command reduces the whole list-of-lists to a one-dimensional list. Here's the initial version: ``` Nest[ "" <> Flatten[{RomanNumeral@#[[1]], #[[2]]} & /@ (Reverse@#[[1]] & /@ Tally /@ Split@Characters@#)] &, "I", #] & ``` [Answer] ## CJam (33 30 bytes) ``` "I"{e`{(4md1$^'I*\'V*@}%e_}ri* ``` [Online demo](http://cjam.aditsu.net/#code=%22I%22%7Be%60%7B(4md1%24%5E'I*%5C'V*%40%7D%25e_%7Dri*&input=5) Key to the correctness of the implementation is the following theorem: ### If the first generation is `I`, no run length is ever greater than five Lemma: if the first generation is `I`, no string ever contains `VVV`. Proof is by contradiction. Suppose that there is a first index `n` for which the `n`th generation contains `VVV`. If that `VVV` breaks down as `(a)V VV` then the conversion from the previous generation is bad: it should have been `(a+5)V`. So it must be `VV V(d)`, and the previous generation contained `VVVVV`, contradicting the choice of `n`. Now, suppose there is a first index `m` for which the `m`th generation contains `...IIIIII...`. Note that there can be no digits other than `I` and `V` in the string, because no previous generation has had a run of nine `I`s or nine `V`s. At most four of the `I`s come from a run of `I`s in the previous string, so the corresponding section of the previous string must be `...IIIVV...` giving `... IIII IIV ...`. Since the `VV` in generation `m-1` doesn't come from `VVVVV` (see lemma), the second `V` must be a run-length of digit `I`, so in generation `m-1` we have `...IIIVVI...`. And since we want the initial `I`s to give `IIII` and not `IVI` or `VI`, it is preceded either by the start of the string or by a `V`. If we have `(...V)?IIIVVI...` in generation `m-1`, what do we have in generation `m-2`? We've already observed that the `VV` of gen. `m-1` must be parsed as `(a)V V(I)`. Suppose we take `a=2`: `(...V)?I IIV VI...` Actually it must be `...VI IIV VI...`, although that leading `V` might be part of `IV`; so in the previous generation we have either `(...V)? IIII VV IIIII...` or `(...V)? IIIII VV IIIII`. Either way we run into trouble with `VVIIIII`: the second `V` must be a run-length, but then `...VI IIII...` requires a following (run-length, digit) pair with the same digit. So it must be `a=1`: `(...V)?II IV VI...`. Since generation `m` is the first with a run of six `I`s, that must be `(...V)? II IV VI...`, so that generation `m-2` is `(...V)? I V IIIII...`. `...VIVIIIII...` is impossible: however we choose to interpret the second `V` we end up with two consecutive (run-length, digit) pairs with the same digit. Therefore generation `m-2` must be `^IVIIIII...`, parsed as `^IV IIII I(V)...` or `^IV III II(V)...`. These give respectively generation `m-3` as `^V III V ...` or `^V II VV...`. But if we look at the start of the strings beginning with the first one that starts with `V`, we get a cycle: ``` VI IV I... IV III IV ... II IV IVI ... IIII IV II IV ... ``` and so no generation ever starts with either `VIIIV` or `VIIVV`. We must conclude that there is no such `m`. ### Dissection ``` "I" e# Initial generation { e# Loop... e` e# Run-length encode { e# Foreach [run-length char] pair... ( e# Extract the run-length r 4md1$^ e# Get the number of Vs and the number of Is e# The number of Vs is r/4 ; the number of Is is (r%4)^(r/4) 'I*\'V*@ e# Repeat strings the appropriate number of times and reorder }% e_ e# Flatten to a simple string }ri* e# ... n times, where n is taken from stdin ``` [Answer] # Python 3, 195 bytes There's a lot of bytes wasted on the roman numerals, so there's likely some golfing to be done there. Thanks to @El'endiaStarman, @Sherlock9 and @Shooqie ``` import re def f(x,r=""): for v,i in(5,"V"),(4,"IV"),(1,"I"):a,x=divmod(x,v);r+=i*a return r s="I" for i in[0]*int(input()):print(s);s=re.sub(r'(.)\1*',lambda m:f(len(m.group()))+m.group()[0],s) ``` [**Ideone it!**](https://ideone.com/ka3vCW) [Answer] ## R, ~~110~~ 107 Bytes `as.roman` combined with `rle` makes this easy. Scoping abuse and built in cat behavior of `<<-` saves a few bytes. ``` x="I" replicate(scan(),{r=rle(strsplit(x,"")[[1]]) x<<-paste(rbind(paste(as.roman(r$l)),r$v),collapse="")}) ``` Takes in N from console. Outputs first 2 to N terms of sequence (which I believe is within spec...) ``` [1] "II" [2] "III" [3] "IIII" [4] "IVI" [5] "IIIVII" [6] "IIIIIVIII" [7] "VIIVIIII" [8] "IVIIIIVIVI" [9] "IIIVIVIIVIIIVII" [10] "IIIIIVIIIVIIIIVIIIIIVIII" [11] "VIIVIIIIIVIVIIVVIIVIIII" [12] "IVIIIIVVIIVIIIVIIIIIVIIIIVIVI" [13] "IIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII" [14] "IIIIIVIIIVIIIIIVIVIIVVIIIVIIIIVIIIVIIIIVIIIIIVIII" [15] "VIIVIIIIIVVIIVIIIVIIIIIVIIIIIVIVIIVIIIIIVIVIIVVIIVIIII" [16] "IVIIIIVVIIIVIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIVIIIVIIIIIVIIIIVIVI" [17] "IIIVIVIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII" [18] "IIIIIVIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVVIIVIVIIVVIIVIIIVIIIIIVIVIIVVIIIVIIIIVIIIVIIIIVIIIIIVIII" [19] "VIIVIIIIIVVIIIVIIIIVIIIIIVVIIVVIIIVIIIIVIIIVIIIIIVIIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVIVIIVIIIIIVIVIIVVIIVIIII" [20] "IVIIIIVVIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIIVIVIIVIIIIIVVIIVIVIIVVIIIVIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIVIIIVIIIIIVIIIIVIVI" [21] "IIIVIVIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIIVIIIIVIIIVIIIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII" [22] "IIIIIVIIIVIIIIIVVIIIVIIIIVIIIIIVVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIIVIVIIVIIIIIVVIIVVIIVIIIVIIIIIVIIIIIVVIIVIVIIVVIIVIIIVIIIIIVIVIIVVIIIVIIIIVIIIVIIIIVIIIIIVIII" [23] "VIIVIIIIIVVIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIIVVIIVIVIIVVIIVIIIVIIIIIVVIIVIIIVIIIIVVIIIVIIIIIVIIIIVIIIIIVVIIVVIIIVIIIIVIIIVIIIIIVIIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVIVIIVIIIIIVIVIIVVIIVIIII" [24] "IVIIIIVVIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVVIIVVIIIVIIIIVIIIVIIIIIVIIIIVIIIIIVVIIIVIIIIVIIIIIVIVIIIVIIIIIVVIIVIVIIVVIIIVIIIIIVIIIIIVIVIIVIIIIIVVIIVIVIIVVIIIVIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIVIIIVIIIIIVIIIIVIVI" [25] "IIIVIVIIIVIIIIIVVIIIVIIIIVIIIIIVVIIVVIIIVIIIIIVIIIIIVIVIIVIIIIIVVIIVIVIIVVIIIVIIIIIVIVIIVVIIVIIIVIIIIIVVIIIVIIIIVIIIVIIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIIVIIIIVIIIVIIIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII" ``` [Answer] # JavaScript (ES6), 107 Recursive function returning the Nth term 0 based ``` f=(n,r='I')=>n?f(n-1,r.match(/I+|V+/g).map(x=>((n=x.length)-4?'VIII'.slice(n<5,1+n%5):'IV')+x[0]).join``):r ``` **Test** ``` f=(n,r='I')=>n?f(n-1,r.match(/I+|V+/g).map(x=>((n=x.length)-4?'VIII'.slice(n<5,1+n%5):'IV')+x[0]).join``):r function update() { O.textContent=f(I.value) } update() ``` ``` <input id=I value=25 type=number oninput='update()'><pre id=O></pre> ``` [Answer] # [Perl 6](http://perl6.org/), 62 bytes ``` {("I",{S:g/(.)$0*/{<I II III IV V>[$/.chars-1]~$0}/}...*)[$_]} ``` Anonymous function that accepts a zero-based index. Makes use of the fact that roman numbers higher than 5 aren't needed, because the only groups of repeating digits that can occur, are: ``` I -> II II -> III III -> IIII IIII -> IVI IIIII -> VI V -> IV VV -> IIV ``` ([try it online](https://glot.io/snippets/ei0b53qvr2)) ]
[Question] [ A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: `10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26`. This is [A029742](http://oeis.org/A029742/list). I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible. ## Rules * Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers ). * If it is possible, provide a link to a site where your program can be tested. * Your program must not write anything to `STDERR`. * You can take input as an argument or from `STDIN` (or the closest alternative in your language). * Programs are scored according to *bytes*. The usual character set is UTF-8, if you are using another please specify. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ## Test Cases ``` 1 ==> 10 ----- 5 ==> 15 ----- 12 ==> 23 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least bytes wins. ## Submissions To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 79251; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/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] # Pyth, 7 bytes ``` e.f!_I` ``` [Test suite](https://pyth.herokuapp.com/?code=e.f%21_I%60&test_suite=1&test_suite_input=1%0A5%0A10%0A100&debug=0) **Explanation:** ``` e.f!_I` e.f!_I`ZQ Implicit variable introduction. .f Q Find the first Q numbers whether the following is truthy, starting at 1, where Q is the input. `Z Convert the number to a string. _I Check if it's the same when reversed. ! Logical not. e Return the last element of the list. ``` [Answer] ## Haskell, 38 bytes ``` ([x|x<-[1..],(/=)<*>reverse$show x]!!) ``` Uses 0-based index. `([x|x<-[1..],(/=)<*>reverse$show x]!!) 11` -> `23`. The test whether to keep a number `(/=)<*>reverse$show x` translates to `(show x) /= (reverse (show x))`, i.e check if the string representation of the number does not equal the reverse of the string representation. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ 11 bytes ``` ;0{<≜.↔¬}ⁱ⁽ ``` -3 bytes tanks to Fatalize ## Explanation ``` ; { }ⁱ⁽ -- Find the nth number 0 -- (starting with 0) < -- which is bigger then the previous one ≜ -- make explicit (otherwise it fucks up) . -- which is the output ↔ -- and if reversed ¬ -- is not the output ``` [Try it online!](https://tio.run/##ASUA2v9icmFjaHlsb2cy//87MHs84omcLuKGlMKsfeKBseKBvf//Nf9a "Brachylog – Try It Online") [Answer] # Jelly, 9 bytes 1 bytes thanks to [@Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000). ``` ṚḌ_ 0dz#Ṫ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bma4biMXwoww4fCsyPhuao&input=&args=MTI) [Test suite.](http://jelly.tryitonline.net/#code=4bma4biMXwoww4figbgj4bmqCsOH4oKs&input=&args=MSw1LDEy) ## Explanation ``` DUḌ_ Helper link. Check if x is not palindrome. D Convert to decimal. U Reverse. Ḍ Convert back to integer. _ Subtract x from the result above. For 23, this will yield 32-23 = 9. Only yield 0 (falsy) if x is palindrome. If x is not a palindrome, it will return a truthy number. 0dz#Ṫ Main link. 0 Start from 0. # Find the first numbers: ³ <input> Ç where the above link returns a truthy number. Ṫ Yield the last of the matches. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` µNÂÂQ>i¼ ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrVOw4LDglE-acK8&input=MTI). [Answer] # Clojure, 62 bytes ``` #(nth(for[i(range):when(not=(seq(str i))(reverse(str i)))]i)%) ``` 0-indexed. Generate lazily infinite range of non-palindromic numbers using list comprehension and take `i`th one. See it online: <https://ideone.com/54wXI3> [Answer] ## PowerShell v2+, 65 bytes ``` for(;$j-lt$args[0]){if(++$i-ne-join"$i"["$i".length..0]){$j++}}$i ``` Loops through numbers from `0` (implicit value for uninitialized `$i`) until we find input `$args[0]` many matches, then outputs the last one. Note that we don't initialize the loop, so `$j=0` is implicit. Each iteration, we pre-increment `$i`, and check if it's not-equal to `$i` reversed. If so, that means we've found a non-palindrome, so increment `$j`. The loop then continues as many times as necessary. ### Examples ``` PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 100 120 PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 5 15 PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 55 70 PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 212 245 ``` [Answer] # Python 2, 60 bytes ``` f=lambda n,i=0,j=1:j>n and i-1or f(n,i+1,j+(`i`!=`i`[::-1])) ``` A one-indexed function that takes input of `n` via argument and returns the `n`th non-palindromic number. **How it works** This is an exhaustive recursive search, which consecutively tests integers `i` in the range `[1,∞)` until `n` non-palindromic numbers have been found; since `i` is pre-incremented, `i-1` is then returned. Testing whether a number is palindromic is performed by converting to a string, reversing, and then checking whether the original and reversed strings are equal. The code is logically equivalent to: ``` def f(n,test=0,count=1): if count>n: return test elif str(test)!=reversed(str(test)): return f(n,test+1,count+1) else: return f(n,test+1,count) ``` which itself is essentially: ``` def f(n): test=0 count=1 while count<=n: if str(test)!=reversed(str(test)): count+=1 test+=1 return test-1 ``` [Try it on Ideone](https://ideone.com/pkfUJC) [Answer] ## Clojure, 62 bytes ``` #(nth(filter(fn[i](not=(seq i)(reverse i)))(map str(range)))%) ``` A quite different approach than the other answer, but equal length. [Answer] # [R](https://www.r-project.org/), ~~133~~ ~~117~~ ~~93~~ 76 bytes -16 bytes thanks to JayCe. -41 bytes thanks to Giuseppe. ``` x=scan();while({F=F+any((D=T%/%10^(1:nchar(T)-1)%%10)!=rev(D));F<=x})T=T+1;T ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTujwjMydVo9rN1k07Ma9SQ8PFNkRVX9XQIE7D0CovOSOxSCNEU9dQUxUopKloW5RapuGiqWntZmNbUasZYhuibWgd8t/0PwA "R – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 103 99 bytes ``` : f 9 swap 0 do begin 1+ dup 0 over begin 10 /mod >r swap 10 * + r> ?dup 0= until = 0= until loop ; ``` [Try it online!](https://tio.run/##RY1bDoIwFAW3Mt8SpP0EAq5FUopNkNtUHsuvrWL8uueeM8lYCeujnGw@MTZYal7H3aMwwjBObkEXmC03so/h1ymqpxj68MXTf6Eg9Nw@bMe2rG6m@8dZxNMmR6YVOgtcEl7PBR/f "Forth (gforth) – Try It Online") ### Explanation Loop n times, each iteration finds the next non-palindromic number by incrementing a counter by 1 until the number doesn't equal itself reversed ### Ungolfed Code Normally I wouldn't "ungolf" the code, but since this code is somewhat messy I figured it would help ``` : reverse ( s -- s ) 0 swap begin 10 /mod >r swap 10 * + r> ?dup 0= until ; : f ( s -- s ) 9 swap 0 0 do begin 1+ dup dup reverse = 0= until loop ; ``` ### Code Explanation ``` : f \ start a new word definition 9 \ start at 9, since all positive ints < 10 are palindromic swap 0 \ set up loop parameters from 0 to n-1 do \ start a counted loop begin \ start an indefinite loop 1+ dup \ increment counter and place a copy on the stack ( Reverse ) 0 over \ add 0 to the stack (as a buffer) and copy the top counter above it begin \ start another indefinite loop 10 /mod \ get the quotient and remainder of dividing the number by 10 >r \ store the quotient on the return stack swap 10 * \ multiply the current buffer by 10 + \ add the remainder to the buffer r> \ grab the quotient from the return stack ?dup \ duplicate if not equal to 0 0= \ check if equal to 0 until \ end inner indefinite loop if quotient is 0 ( End Reverse ) = 0= \ check if counter =/= reverse-counter until \ end the outer indefinite loop if counter =/= reverse-counter loop \ end the counted loop ; \ end the word definition ``` [Answer] # [Perl 6](http://perl6.org), 29 bytes ``` {grep({$_!= .flip},^Inf)[$_]} ``` ( uses 0 based index ) ``` { # The $_ is implied above grep( # V { $_ != $_.flip }, # only the non-palindromic elements of ^Inf # an Infinite list ( 0,1,2,3 ...^ Inf ) )[ $_ ] # grab the value at the given index } ``` ### Usage: ``` my &non-palindrome = {grep({$_!= .flip},^Inf)[$_]} say non-palindrome 1 - 1; # 10 say non-palindrome 5 - 1; # 15 say non-palindrome 12 - 1; # 23 # this also works: say non-palindrome 0..20; # (10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32) ``` [Answer] ## Actually, 17 bytes ``` ;τR9+;`$;R=Y`M@░E ``` [Try it online!](http://actually.tryitonline.net/#code=O8-EOStSO2AkO1I9WWBNQOKWkUU&input=MQ) Values are 1-indexed. This could be easily changed to 0-indexed by replacing the first `R` with `r`. But, `R` is what I initially typed, so that's what I'm going with. The nonpalindromic numbers satisfy `a(n) ≈ n + 10`, so `2n+9` is a sufficient upper bound. Explanation: ``` ;τR9+;`$;R=Y`M@░E ;τ9+R; push n, range(1,(2*n)+10) `$;R=Y`M@░ take values that are not palindromic E take nth element ``` [Answer] ## JavaScript (ES6), 54 bytes Uses 1-based indexing. Only works up until the 7624th number. ``` d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join``,a):a ``` ### Usage ``` d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join``,a):a d(1) 10 d(123) 146 d(7624) 7800 d(7625) // Uncaught RangeError: Maximum call stack size exceeded ``` --- ## JavaScript (ES6), 59 bytes Doesn't use recursion and so can handle much larger inputs. ``` i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a") ``` ### Usage ``` (i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(1) 10 (i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(7625) 7801 (i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(123456) 124579 ``` [Answer] ## Javascript (using external library) (97 bytes) ``` n=>_.Sequence(n,i=>{i=_.From(i+"");if(!i.Reverse().SequenceEqual(i)){return i.Write("")}}).Last() ``` Link to lib: <https://github.com/mvegh1/Enumerable> Code explanation: Library has static method called Sequence, where first param defines how many elements the sequence will guarantee to create, and the 2nd parameter is a predicate accepting the current iteration value, "i". The predicate converts the integer to a string, which gets converted to a char array by calling \_.From. The char array is compared against the reversal of the char array, and if they are not equal the char array is joined back into a string and returned. Otherwise, nothing is returned (i.e the result is undefined, which the library will always ignore). Finally, the last element of the sequence, i.e the Nth element is returned [![enter image description here](https://i.stack.imgur.com/NfSo4.png)](https://i.stack.imgur.com/NfSo4.png) [Answer] ## C, 84 bytes Function `f(n)` takes integer `n` and returns `n-th` non-palindromic number (1 based). ``` g(n,r){return n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)==s&&s++);return s;} ``` Test it on [Ideone!](http://ideone.com/HD9e2s) It's fairly trivial code, thus there is probably space for improvement. [Answer] # Ruby, 54 bytes This function is 1-indexed and is partially based on [Dom Hastings's Javascript answer](https://codegolf.stackexchange.com/a/86605/47581). I think there's a way to golf this better, especially with that last ternary condition. Also, this function currently returns a string, which may need to be edited later. Any golfing suggestions are welcome. ``` f=->x,y=?9{x<1?y:(y.next!.reverse!=y)?f[x-1,y]:f[x,y]} ``` **Ungolfed:** ``` def f(x, y="9") if x<1 return y else y = y.next if y.reverse != y return f(x-1, y) else return f(x, y) end end end ``` [Answer] ## C++ (GCC), 148 bytes It's 1-based and the algorithm is really naive ``` #import <iostream> using namespace std;int n,i=1;string s;main(){cin>>n;while(s=to_string(i+1),(n+=equal(begin(s),end(s),s.rbegin()))-i++);cout<<i;} ``` [Answer] # APL NARS 35 chars ``` r←v a;c r←c←0 A:r+←1⋄c+←r≠⍎⌽⍕r⋄→A×⍳c<a ``` it is the function v; "⍎⌽⍕"r traslate number r in string, reverse that string, traslate from string to number. Test and help functions: ``` ⍝ return the one string for the basic types ('Char', 'Int', 'Float', 'Complex or Quaternion or Oction') ⍝ or one string for composite types ('Tensor 3' 'Tensor 4' etc 'Matrix', 'List', 'String') ⍝ follow the example in: https://codegolf.stackexchange.com/a/39745 type←{v←⍴⍴⍵⋄v>2:'Tensor ',⍕v⋄v=2:'Matrix'⋄(v=1)∧''≡0↑⍵:'String'⋄''≡0↑⍵:'Char'⋄v=1:'List'⋄⍵≢+⍵:'Complex or Quaternion or Oction'⋄⍵=⌈⍵:'Int'⋄'Float'} h←{'Int'≢type ⍵:¯1⋄(⍵<1)∨⍵>2e5:¯1⋄v ⍵} h 1 10 h 1.32 ¯1 h 7878 8057 h¨3 5 12 13 15 23 h 6 7 8 ¯1 h '123' ¯1 h '1' ¯1 h 1.0 10 h 1.0003 ¯1 h ¯2 ¯1 h 0 ¯1 h 200000 201200 h 200001 ¯1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes Yay for `↔` :) ``` !fS≠↔N ``` [Try it online!](https://tio.run/##yygtzv7/XzEt@FHngkdtU/z@//9vaAQA "Husk – Try It Online") ### Explanation ``` f N -- filter the naturals by: S≠ -- is it not equal to.. ↔ -- ..itself reversed ! -- index into that list ``` [Answer] # [Perl 5](https://www.perl.org/), 33 + 1 (`-p`) = 34 bytes ``` map{1until++$\!=reverse$\}1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saDasDSvJDNHW1slRtG2KLUstag4VSWm1lBPTyW@tvr/f0Ojf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") [Answer] # C# 7, 89 bytes ``` n=>{int i=9;for(;n-->0;)if(Enumerable.SequenceEqual(++i+"",(""+i).Reverse()))i++;return i;} ``` 1 indexed [Try on Repl.It](https://repl.it/@ryzngard/SuperiorFormalDiscussions) ``` n=> int i = 9; | Start at 9. Iterate exactly n times. Assume n >= 1 for(;n-->0;) | Iterate n times if(EnumerableSequenceEqual( | Compare two sequences ++i+"",(""+i).Reverse()) | Generate the forward and backward strings, which behave like char sequences for Linq i++ | If the sequences are equal, the number is a palindrome. Increment i to skip return i; | Return the number after the for loop exits ``` I don't think this uses any language features from c# 7, but I put there since that's what I tested against [Answer] # Java 8, ~~117~~ ~~95~~ 94 bytes ``` n->{int r=10;for(;n-->0;)if((++r+"").contains(new StringBuffer(r+"").reverse()))r++;return r;} ``` 0-indexed **Explanation:** [Try it here.](https://tio.run/##hVDBasMwDL33K0RPMiYhgd1Me9i9vfQ4evBcebhL5SA7GaXk2zOn6XUMJIHeE@89dLWjrWJPfL18z66zKcHBBn5sAAJnEm8dwXFZnwA4XCYrU5CpdKmUbQ4OjsCwg5mr/WM5kV3bGB8FDVfVvjEqeEStRW@3qnaRc3FJyPQDpyyBv94H70lw5YVGkkSolBKtjVAehEHMNJtNceyHz644vozHGC5wK3K4Kn2cwao18emeMt3qOOS6L1TuGLl22Khn/j/5t3/4tlWvB0zzLw) ``` n->{ // Method with integer as both parameter and return-type int r=10; // Result-integer, starting at 10 for(;n-->0;) // Loop an amount of times equal to the input if((++r+"") // First raise `r` by 1, and then check if `r` .contains(new StringBuffer(r+"").reverse())) // is the same as `r` reversed (and thus a palindrome) r++; // And if it is: raise `r` by 1 again return r;} // Return result-integer ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ ... ~~9~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 0-indexed. ``` Ȧsw}iU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yKZzd31pVQ&input=MA) ``` Ȧsw}iU :Implicit input of integer U È :Function taking an integer X as an argument ¦ : Test for inequality with s : Convert to string w : Reverse } :End function iU :Get the Uth integer that returns true ``` [Answer] ## TCC, 11 bytes ``` ?>!~<>;i;'T ``` [Try it online!](https://www.ccode.gq/projects/tcc.html?code=%3F%3E!~%3C%3E%3Bi%3B%27T&input=12) ``` | Printing is implicit ?> | Find n-th number for which the following is "T": !~ | If not equal... <>; | reverse. No value specified, so input is assumed. i; | Input, since double semicolons are ignored 'T | ... print string "T" ``` ]
[Question] [ Given an integer ***p > 1***, find the smallest integer ***q > p*** such that the list of exponents in the prime factorization of ***q*** is the same of that of ***p***, no matter the order or the value of the prime factors. ## Examples The prime factorization of ***p = 20*** is ***22 x 51***. The smallest integer greater than ***p*** with identical exponents in its prime factorization is ***q = 28 = 22 x 71***. The prime factorization of ***p = 2500*** is ***22 x 54***. The smallest integer greater than ***p*** with identical exponents in its prime factorization is ***q = 2704 = 24 x 132***. ## Rules * The input is guaranteed to be an integer greater than 1. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. ## Test cases ``` Input | Output ------+------- 2 | 3 20 | 28 103 | 107 256 | 6561 768 | 1280 2500 | 2704 4494 | 4510 46552 | 46584 75600 | 105840 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` §ḟ¤≡ȯÖLgp→ ``` [Try it online!](https://tio.run/##yygtzv6vkHtiffGjpsaiQ9v@H1r@cMf8Q0sedS48sf7wNJ/0gkdtk/7//2/EZWTAZWhgzGVkasZlbmYBpA0MuExMLE24TMxMTY24zE3NDAwA "Husk – Try It Online") ### Explantion ``` §ḟ → Find the first number starting from the input + 1 such that... p The prime factorisation g with equal elements grouped together ȯÖL and sorted by length of groups ¤≡ has the same shape as the above applied to the input. ``` [Answer] # Mathematica, 61 bytes ``` (f[x_]:=Sort[Last/@FactorInteger@x];s=#;While[f@++s!=f@#];s)& ``` [Try it online!](https://tio.run/##y00sychMLv6fbvtfIy26Ij7WyjY4v6gk2iexuETfwS0xuSS/yDOvJDU9tcihIta62FbZOjwjMyc1Os1BW7tY0TbNQRkoqqn2P6AoM69EwSE92sjUwCD2PwA "Mathics – Try It Online") *-4 bytes from @Misha Lavrov* [Answer] # [Pyth](https://pyth.readthedocs.io), 15 bytes ``` fqFmShMrPd8,QTh ``` **[Try it here!](https://pyth.herokuapp.com/?code=fqFmShMrPd8%2CQTh&input=20&test_suite_input=2%0A20%0A103%0A256%0A768%0A2500%0A4494%0A46552%0A75600&debug=0)** or **[Verify all the test cases.](https://pyth.herokuapp.com/?code=fqFmShMrPd8%2CQTh&input=20&test_suite=1&test_suite_input=2%0A20%0A103%0A256%0A768%0A2500%0A4494%0A46552%0A75600&debug=0)** ## How does this work? ``` fqFmShMrPd8,QTh ~ Full program. Q = first input. f h ~ First input where the condition is truthy over [Q+1, Q+2, ...] ,QT ~ The two element list [Q, current value (T)]. m ~ Map over ^ with d. Pd ~ The prime factorization of d. r 8 ~ Run-Length encode ^. hM ~ Get the first element of each. qF ~ Check if the values are equal. ~ Output implicitly. ``` --- ## Alternatives Another 15-byter: ``` LShMrPb8fqyQyTh ``` And a couple of (longer) alternatives: ``` fqFmSlM.gkPd,QTh LSlM.gkPbfqyQyTh LS/LPb{PbfqyQyTh f!-FmlM.gkPd,QTh ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes 1 byte thanks to Erik the Outgolfer. ``` ÆEḟ0Ṣ ,Ç€Eð2#Ṫ ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//w4ZF4bifMOG5ogosw4figqxFw7AyI@G5qv///zI1MDA "Jelly – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` <.;?{ḋḅlᵐ}ᵐ=∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/30bP2r764Y7uhztacx5unVALxLaPOpb//29kavY/CgA "Brachylog – Try It Online") It's been a long time since I posted an answer… ### Explanation ``` <. Input < Output .;? The list [Output, Input] { }ᵐ Map on [Output, Input]: ḋ Prime decomposition ḅ Group into sublists of consecutive equal elements lᵐ Take the length of each sublist =∧ The result of the map must be the same for the Output and the Input ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~176~~ ~~179~~ ~~171~~ ~~170~~ 169 bytes * Added three bytes as the question changed from *set of exponents* to *list of exponents*; `set(f)` was changed to `sorted(f)`. * Saved eight bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs); golfing the if / else block down to multiplication. * Saved a byte; golfed `(n!=r)` to `(n>r)`. * Saved a byte; golfed `while N>1` to `while~-N`. ``` N=input();n=-~N def F(N): r,f=0,[] while~-N: for n in range(2,-~N): if N%n<1:f+=[1]*(n>r);f[-1]+=n==r;r=n;N/=n;break return sorted(f) while F(N)!=F(n):n+=1 print n ``` [Try it online!](https://tio.run/##JU5BTsMwEDx3X7GNhGSTRDgmScFhuVTq0R@IcijUbiPQJjKugEu/Hkx7Gc2MZndm/o2nifWypSzLFksjz@coZMdUXiwcnMedsNIAhsKTKvoB8Ps0frpLaQ2s/BSQcWQMez46oYt0lMIrHD3aO36pjM@pr4Z7wa9Bdr4vqyEnJgpdIO7sQ4K34PYf6b@L58D4NYXoDsJLuNZc29e0EywN51TBHEaOyEta27kf957d1ijzL3CbLVqBblQCSKxSj0m1sGmfbm5dP9dQt02jYdO0Sv0B "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 107 bytes ``` import Data.List import Data.Numbers.Primes p=sort.map(1<$).group.primeFactors f x=until((==p x).p)(+1)$x+1 ``` [Try it online!](https://tio.run/##TcsxDgIhEEDRnlNMQQHZZBI6C@mMlTF7hdGwSoRlAkPC7XHtbP/Lf1P7hJTmjJlLFbiQEN5iE/Uf7j0/Qm241phDU@zbQZiJjTtri69aOiP/8EpPKbWpDYbvu8RkjPcMwyJbszirx@JmpriDh2PYBTRscJpf "Haskell – Try It Online") Usage example: `f 2500` yields `2704`. Thanks to nimi for pointing out a flaw and saving a bunch of bytes. --- ### Without `primeFactors` build-in (117 bytes) ``` import Data.List 1%n=[] x%n|0<-mod x n=n:div x n%n|m<-n+1=x%m p=sort.map(1<$).group.(%2) f x=until((==p x).p)(+1)$x+1 ``` [Try it online!](https://tio.run/##FcuxCsIwEIDhPU9xQwIJocE4ifQ2R99AHAK1GkyuR5NKBt891u3ng/8VyvuRUu8x87JWuIQa3DWWKrwivN1FU/Q9jENeJmhASOcpfv61cx4Hsh6byoKx7LfLgbUfpXHPddnYaXU0YoaGG9WYtEZkaMax0dYb2azvOUQCBF4jVZAww6n/AA "Haskell – Try It Online") [Answer] # Python - 141 bytes ``` def s(n): i=1;d={} while n-1: i+=1 if n%i<1:d[i]=d.get(i,0)+1;n/=i;i=1 return d.values() a=input() j=a+1 while s(a)!=s(j):j+=1 print j ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` XµN‚εÓ0K{}ËNI›& ``` [Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//1jCtU7igJrOtcOTMEt7fcOLTknigLom//8yNTAw "05AB1E – Try It Online") **Explanation** ``` Xµ # Loop over N in [0 ...] until 1 match is found N‚ # pair N with input ε } # apply to each Ó # list prime exponents 0K # remove zeroes { # sort Ë # check that they are equal & # and NI› # that N is greater than the input ``` [Answer] # [Python 3](https://docs.python.org/3/) + [Sympy](http://docs.sympy.org/latest/index.html), 118 bytes ``` from sympy.ntheory import* f=lambda k:sorted(factorint(k).values()) g=lambda i,k=2:i<k and f(k)==f(i)and k or g(i,k+1) ``` [Try it online!](https://tio.run/##NczLDsIgEIXhfZ9iljNqGq27Rh4G5VJCYQhQE54e0cTl@fPlpFY3jvfeTeYApYXU5lg3zbmBC4lzPU1G7DI8lQS/lhG0QiNflbOLFT3Nb7kfuiDRZP/QXbxYVvfwIKMCM5QQBh19lwfOYHGQ8416@r1YXK5E/QM "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 32 bytes ``` >:@]^:(1--:&(_&q:/:[[email protected]](/cdn-cgi/l/email-protection):))^:_>: ``` [Try it online!](https://tio.run/##JY5BC4JAEIXv/oqHhO5C2uy2u9qEoQRB0CHqmklEEl0i6hb0122iw/cxvDcwcxviPO1RMVKMQWAhy7HcbVbDguv2yMpkGSeqSx484U@d5cRaH7lb8KCj1/n0vDxR5egs2gMsprAEW8LQVChgfUDwwaAIEtpSSk@ighycm4m8Ibjgvf25dCh8kAVDMlN0OV/vUGgxh1JVrz8TjbeccRghXTXrzbbZ79O4g44N/t9Ewxc "J – Try It Online") Start from input + 1 `>:` and keep incrementing while the list of prime factors `_&q:` minus any zeros `-.0:`, then sorted `/:~@`, does not match `1--:`. [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` g=->m{m.prime_division.map{_2}.sort} ->n{((n+1)..).find{g[_1]==g[n]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU5LDoIwEN1zikY3EEPTQn8uyk4uQQjRIKQLCilgYggX0Q2JuvJE3kbSspr3mzfzfJvxcv9mu9B0RjXXXf5Kpf8ZhyoUv1Mtw6SZGmitolQ31atWw-bcTUU0w741w-yFiZ58Xx9wAGEAK6XLqc4KnEtZZzqf563sEXgdSLMoB2APYoeRJZGwDKPYUoy4cymznFGGrcCZcIFIoC2BtgaOiFUIORKrEIpdhjBK3c0VCZfilG2LGK0ach8ui5t_) [Answer] # [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Hideous! But I can't think of a better way :\ ``` @[UX]Ëk ü mÊñÃre}aUÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFtVWF3LayD8IG3K8cNyZX1hVcQ&input=MjUwMA) ]
[Question] [ The stock market is all about the speed of knowledge. Unlike previous challenges, **the current stock price is not random: it is determined by those playing the game.** If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program. ***Price* refers to the how much people are trading the stock for, while *Value* refers to the amount the stock is worth at the end of the game.** Each player starts with 1000 of each stock, and 0 relative net worth. **Each stock has a secret value, and your score at the end of the game is `(stockValue for each ownedStock) + netWorth`**. Your net worth can be negative. In an N-player game, there are N stocks. # Steps: The game follows the following steps: 1. You are given the secret value of a single stock. 2. You make an offer to sell X of Y stock for $Z 3. All players are given the offers, and each may choose one to accept 4. All players are informed of accepted offers 5. Go back to step 2 Each of the steps are given in detail below: 1. `void secretValue(int stockType, int value)`: * The value you learn is not revealed to any other player. * The value is between `0` and `1000` * Low values are more like to occur than high values (squared uniform distribution) 2. `Offer makeOffer(List<Stock> currentStock)` * You can return `null` to make no offer. 3. `Offer acceptOffer(List<Offer> offers)` * You can return `null` to accept none of them * If there are no available offers, this will not be called * If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock. The opposite occurs with the seller. * If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it. 4. `void acceptedOffers(List<Offer> offers)` * Includes your accepted offers as well Static variables or writing to files is not allowed. (No persistent data from game to game) Non-serious contenders are allowed. Interfaces: ``` public final class Stock { public Stock(int stockType, int amount); public int getType(); public int getAmount(); public Stock minus(Stock other); public Stock plus(Stock other); public Stock minus(int amount); public Stock plus(int amount); public Stock setAmount(int amount); } public class Offer { public Offer(Stock offer, int payment); public Stock getOffer(); public int getPayment(); } ``` **Non-Java submissions:** * All calls consist of two lines: The first line is the function being called: `SecretValue`, `MakeOffer`, `AcceptOffer`, `AcceptedOffers`, `SetRandom`, and the second line containing the actual data. * Stocks are formatted with a `:` delimiter: `stockType:stockAmount`. * Offers are formatted with a `@` delimiter: `offer@price` * Lists are formatted with a `;` delimiter * `SecretValue` is formatted with a `:` delimiter: `stockType:value` * `RandomSeed` is used to make your submission deterministic. If your submission uses randomness, please use the integer value passed as the seed! * All function calls *need* a response. If the response is `null` or `void`, return an empty string. * Please include a `command.txt` that gives the command line arguments to run your submission # Scoring Games consisting of 1000 turns will be run multiple times. Players will be scored according to the [ELO system](https://en.wikipedia.org/wiki/Elo_rating_system), and paired with players of similar skill levels. The player with the highest final ELO score wins! (I've modified the system so that each game, ELO scores are updated for each player pairing) The controller includes an autodownloader, so please start your submission with a header: `Name, Language`. If your submission is not in Java, each code block should start with the name of the file. (excluding the command file, which should be the first block in your post) # Running There are 2 ways to run this project: 1. Download the source code, compile and run. You can find the source on [Github](https://github.com/nathanmerrill/StockExchange). Run `git clone --recursive https://github.com/nathanmerrill/StockExchange.git` 2. Download the JAR executable. Submissions should be placed in your current working directory in the `/submissions` folder. You can download just the [JAR](https://github.com/nathanmerrill/StockExchange/blob/archives/StockExchange.jar), just the [submissions](https://github.com/nathanmerrill/StockExchange/blob/archives/StockExchangePlayers.zip), or [both](https://github.com/nathanmerrill/StockExchange/blob/archives/StockExchange.zip) Pass in `run` to run the project (default option), or pass in `download` to download all submissions so far from this question. # Scoreboard ``` 1. 1308.1220497323848 Cheater 2. 1242.0333695640356 InsideTrader 3. 1158.3662658295411 UncleScrooge 4. 1113.8344000358493 BlackMarket 5. 1051.8370015258993 DartMonkey 6. 983.0545446731494 WarGamer 7. 939.457423938002 Spammer 8. 901.4372529538886 DumbBot 9. 859.0519326039137 ShutUpAndTakeMyMoney 10. 852.9448222849587 VincentKasuga 11. 718.2112067329083 Profiteer ``` [Answer] # Cheater, Java Tries to sell nothing for money. ``` import java.util.List; import java.util.Random; import com.ppcg.stockexchange.*; public class Cheater extends Player { private Random random = new Random(); public Offer acceptOffer(List<Offer> offers) { return null; } public Offer makeOffer(List<Stock> currentStock){ Stock stock = randomStock(); int price = random.nextInt(100) + 1; return new Offer(stock.setAmount(0), price); } } ``` [Answer] # WarGamer, Java Upon a perfunctory examination of the rules I have decided that the primary winning move is not to play. Anyone offering to sell stock likely knows the price and will profit from the sale. It can be toggled so it will make "joke" offers to sell a stock for Integer.MAX\_VALUE dollars hoping shut up and take my money will bite. ``` import java.util.List; import com.ppcg.stockexchange.*; import com.ppcg.kothcomm.game.AbstractPlayer; import com.ppcg.kothcomm.utils.Tools; import java.util.List; public class WarGamer extends Player { static final boolean FRAUD = false; /** * @param offers All available offers * @return An offer you want to accept, or null if you want to accept neither. */ public Offer acceptOffer(List<Offer> offers){ return null; } public Offer makeOffer(List<Stock> currentStock){ if(FRAUD) return new Offer(new Stock(0,1),Integer.MAX_VALUE); //defraud shut up and take my money return null; } } ``` [Answer] # ShutUpAndTakeMyMoney, Java ``` import java.util.List; import com.ppcg.stockexchange.*; public class ShutUpAndTakeMyMoney extends Player { public ShutUpAndTakeMyMoney() {} public Offer acceptOffer(List<Offer> offers) { try { return offers.get(0); } catch (Exception ex) { return null; } } public Offer makeOffer(List<Stock> stock) { return null; } } ``` It accepts any offer. [Answer] # DumbBot, Java Use this bot when creating your own. Offers its secret stock at a discounted price. ``` import java.util.List; import com.ppcg.stockexchange.*; public class DumbBot extends Player { public Offer acceptOffer(List<Offer> offers) { return null; } public Offer makeOffer(List<Stock> currentStock){ return new Offer(currentStock.get(secretStockType).setAmount(1), Math.max(1, secretStockValue - 5)); } public void secretValue(int stockType, int value) { super.secretValue(stockType, value); } public void acceptedOffers(List<Offer> acceptedOffers) { } } ``` [Answer] # python\_starter, Python 3 Use this as a starting point for any python (or other language) programs Accepts a random offer. Command file: ``` python3 starter.py ``` Program: ``` starter.py import random from functools import total_ordering LIST_DELIMITER = ';' STOCK_DELIMITER = ':' OFFER_DELIMITER = '@' @total_ordering class Stock: @staticmethod def parse(string: str): return Stock(*map(int, string.split(STOCK_DELIMITER))) def __init__(self, stock_type: int, amount: int): self.type = stock_type self.amount = max(amount, 0) def __str__(self): return str(self.type)+STOCK_DELIMITER+str(self.amount) def __eq__(self, other): return self.amount == other.type def __lt__(self, other): return self.amount < other.amount def update(self, amount) -> 'Stock': return Stock(self.type, amount) def __mul__(self, other: int) -> 'Stock': return self.update(self.amount*other) def __floordiv__(self, other: int) -> 'Stock': return self.update(self.amount//other) def __add__(self, other: int) -> 'Stock': return self.update(self.amount+other) def __sub__(self, other: int) -> 'Stock': return self.update(self.amount-other) class Offer: @staticmethod def parse(string: str) -> 'Offer': try: offer, payment = string.split(OFFER_DELIMITER) except ValueError: raise Exception("Cannot unpack "+string) return Offer(Stock.parse(offer), int(payment.strip())) def __init__(self, offer: Stock, payment: int): self.offer = offer self.payment = payment def __str__(self): return str(self.offer)+OFFER_DELIMITER+str(self.payment) def read_stock_value(value: str): global hidden_price, hidden_stock stock, price = value.split(STOCK_DELIMITER) hidden_price = float(price) hidden_stock = int(stock) def process_input(): handlers = { "SecretValue": read_stock_value, "RandomSeed": read_seed, "MakeOffer": make_offer, "AcceptOffer": accept_offer, "AcceptedOffers": accepted_offers, } method = input().strip() data = input().strip() output = handlers[method](data) if output is not None: print(str(output)) else: print() def read_seed(seed: str): random.seed(int(seed)) def start(): while True: process_input() hidden_stock = None hidden_price = None def make_offer(current_stock: str): current_stock = map(Stock.parse, current_stock.split(LIST_DELIMITER)) pass def accept_offer(available_offers: str): available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER))) return random.sample(available_offers, 1)[0] def accepted_offers(offers: str): offers = map(Offer.parse, offers.split(LIST_DELIMITER)) pass if __name__ == "__main__": start() ``` [Answer] # VincentKasuga, Java Not sure if my Java is valid. Please review. ## How it works ~~- if you own all the stocks, you can set the price of the stock. You are the only seller. 1. Buy all the stocks. 2. Set the price of all the stocks to be super high on the last tick. 3. **PROFIT!** - This isn't normally possible because...~~ * The price would usually skyrocket to infinity... but there's a limit! * ... (more reasons to come) ## How it works, v2 * The price is artificially set at a maximum by some anarchist state * This is bad economically * **The bot doesn't predict - it exploits an inherent flaw in the structure of the market!** ## Todo * Corner the market multiple times! Muahaha! ## FAQ **Q:** Who's Vincent Kasuga? **A:** He bought all the onions and onion futures in the United States. (put them all in a secret warehouse) Held the industry at ransom - give me X million or I'll set the price sky-low and you'll all go bankrupt. But he didn't stop there. Then, he secretly shorted the onion ETF (bet that it would go down). He sold all the onions at one time, physically delivering them in thousands of trucks to the stock exchange. The onion bag cost less than the onions. He made millions AGAIN. In short, the Hudson river overflowed with onions. He's a real person. ## The code ``` import com.ppcg.stockexchange.Offer; import com.ppcg.stockexchange.Player; import com.ppcg.stockexchange.Stock; import java.util.List; public class VincentKasuga extends Player { private int knownStock; private int knownPrice; private int corneredStockType = -1; private int corneredLikelehood = 0; private boolean marketCornered; private int ticks; public Offer acceptOffer(List<Offer> offers) { if (!marketCornered) { Offer maxOffer = null; int maxAmount = 0; if (corneredStockType == -1) { for (Offer offer: offers) { if (offer.getOffer().getAmount() > maxAmount) { maxAmount = offer.getOffer().getAmount(); maxOffer = offer; } } } else { for (Offer offer: offers) { if (offer.getOffer().getAmount() > maxAmount && offer.getOffer().getType() == corneredStockType) { maxAmount = offer.getOffer().getAmount(); maxOffer = offer; } } } if (maxOffer == null) { // may have cornered the market corneredLikelehood++; if (corneredLikelehood == 5) { // probably cornered the market marketCornered = true; } } return maxOffer; } else { // who needs offers when the market is cornered!? return null; } } public Offer makeOffer(List<Stock> currentStock) { ticks++; if (ticks >= 999) { // SELL SELL SELL! return new Offer(new Stock(corneredStockType, 1000), 1000); } else { return null; } } public void secretValue(int stockType, int value) { knownStock = stockType; knownPrice = value; if (stockType == corneredStockType) { if (knownPrice == 1000) { corneredLikelehood += 3; } else if (knownPrice < 900){ // didn't corner the market. corneredLikelehood = 0; } } } } ``` --- *"I've cornered the Gold Market, Mr. Bond!"* [Answer] # Spammer, Java ``` import java.util.List; import java.util.ArrayList; import com.ppcg.stockexchange.*; public class Spammer extends Player { private boolean panic = false; public Offer acceptOffer(List<Offer> offers) { for (Offer offer : offers) { if (this.panic || offer.getPayment() < 20) return offer; } return null; } public Offer makeOffer(List<Stock> currentStock) { if (currentStock.size() > 1) { // Don't sell all the stock this.panic = false; return new Offer(currentStock.get(secretStockType).setAmount(1), 1); } this.panic = true; // BUY return null; } } ``` Spam the market with really cheap stock, and only buy stock when the price is lesser than 20. When the stock count fall to 1, it will try to buy anything. [Answer] # DartMonkey, Java (non-competing: It won't win and I already have another answer) Dart monkey likes throwing things... and there's a big pile of pointy sticks next to him. He sees some paper on the wall. Bam! Bam! Bam! In no time at all, Dart Monkey's thrown 80 darts! Half the darts are red, and the other half are blue, and there's random numbers on them! Dart monkey sees a computer... dart monkey types in the numbers. Dart monkey likes numbers. Dart monkey makes some money from his darts... --- In all seriousness, DartMonkey initializes an integer array that has a length that is twice the number of stocks. He stores one number for the amount of stock he wants to buy/sell, and one number for the price of the stock. He then alternates selling stock from the array, and accepting offers according to the array. If he has no stock from the array, he won't offer anything, and if he has no offers given to him from the array, he won't accept anything. --- [Answer] # InsideTrader, Java InsideTrader just looked around and saw that everybody was trying to be creative. But he did something creative: do what is expected. This bot buys when it's "worth it" because it "borrowed" some "internal documents" to "guide" "investing decisions". To-Do and how it works in the code. ;) ## The "code" ``` import java.util.List; import com.ppcg.stockexchange.*; public class InsideTrader extends Player { public String coverStory = "I can tell the good companies from the bad ones."; private String theTruth = "I'm cheating. (but so is everyone else)"; private String ambitions = "Learn to \"follow the market\""; // don't steal this idea private int secretStock = -1; private int secretStockValue = -1; private int appraiseOffer(Offer offer) { /* get how much the offer is worth, 0 if it's not the secret stock */ if (offer.getOffer().getType() != secretStock ||offer.getOffer().getAmount() == 0) { return 0; } return (offer.getPayment()/offer.getOffer().getAmount()) // price per stock... - secretStockValue // minus value of stock. ; } public Offer acceptOffer(List<Offer> offers) { Offer bestOffer = null; int bestOfferValue = -1; for (Offer offer : offers) { int value = appraiseOffer(offer); if (value > bestOfferValue && value > 0) { bestOfferValue = value; bestOffer = offer; } } return bestOffer; } public Offer makeOffer(List<Stock> currentStock) { return new Offer(new Stock(0,1), Integer.MAX_VALUE); } public void secretValue(int stockType, int value) { secretStock = stockType; secretStockValue = value; } public void acceptedOffers(List<Offer> acceptedOffers) { } } ``` [Answer] # WallStreet, Kotlin Starts by selling high and buying low and gradually shifts to what it thinks the price really is. Also, you can use this as a template for making your own in kotlin. **Note:** There is a bug in here that I can't seem to reliably reproduce. If my program crashes or has problems, please ping me in [chat](http://chat.stackexchange.com/rooms/44660/stock-exchange) and link a pastebin of the contents of `submissions/other/WallStreet/log.txt` ``` kotlinc WallStreet.kt kotlin WallStreetKt ``` ``` WallStreet.kt import java.io.FileOutputStream import java.io.PrintStream import java.util.* val LOGGER = PrintStream(FileOutputStream("log.txt", true)) const val DEBUG = false const val LOG_GAME_HEADER = """ ############### #STARTING GAME# ###############""" data class Stock(val type : Int, val amount : Int) { operator fun minus(amount : Int) = copy(amount = this.amount - amount) operator fun plus(amount: Int) = copy(amount = this.amount + amount) fun setAmount(amount: Int) = copy(amount = amount) operator fun minus(other : Stock) : Stock { assert(type == other.type) return copy(amount = this.amount - other.amount) } operator fun plus(other : Stock) : Stock { assert(type == other.type) return copy(amount = this.amount + other.amount) } override fun toString() = "$type:$amount" } data class Offer(val offer: Stock, val payment: Int) { override fun toString() = "$offer@$payment" } fun parseStock(repr : String) : Stock { val data = repr.split(":").map { it.toInt() } return Stock(data[0], data[1]) } fun parseOffer(repr: String) : Offer { val data = repr.split("@") return Offer(parseStock(data[0]), data[1].toInt()) } fun parseOffers(repr: String) = if (repr == "") emptyList<Offer>() else repr.split(";").map { parseOffer(it) } interface Player { fun secretValue(stockType: Int, value: Int) fun makeOffer(currentStock: List<Stock>) : Offer? fun acceptOffer(offers: List<Offer>) : Offer? fun acceptedOffers(offers: List<Offer>) var random : Random } fun main(args : Array<String>) { try { if (DEBUG) { LOGGER.println(LOG_GAME_HEADER) } //Change bot name here val player = WallStreet() while (true) { val function = readLine() function ?: return val line = readLine()!! if (DEBUG) { LOGGER.println("\nInput:") LOGGER.println(function) LOGGER.println(line) } var result : Any try { result = when (function) { "SecretValue" -> { val data = line.split(":").map { it.toInt() } player.secretValue(data[0], data[1]) } "MakeOffer" -> player.makeOffer(line.split(";").map { parseStock(it) }) ?: "" "AcceptOffer" -> player.acceptOffer(parseOffers(line)) ?: "" "AcceptedOffers" -> player.acceptedOffers(parseOffers(line)) "RandomSeed" -> player.random = Random(line.toLong()) else -> return //Exit program } if (function == "AcceptOffer" && result.toString() !in line) { throw Exception("Offer not among available offers!!!!\nResult: $result\nParsed Available Offers: ${parseOffers(line)}") } } catch (e : Exception) { LOGGER.println("Turn #${player.turn}") LOGGER.println("\nInput:") LOGGER.println(function) LOGGER.println(line) throw e } if (result == Unit) { result = "" } if (DEBUG) { LOGGER.println("Output:") LOGGER.println(result) } println(if (result == Unit) "" else result) } } catch (e : Exception) { e.printStackTrace(LOGGER) throw e } finally { LOGGER.close() } } // ################################################### // # Put program logic below here. # // ################################################### const val DEFAULT_STOCK_VALUE = 333 const val MAX_TURNS = 1000 const val MAX_STOCK_VALUE = 1000 class WallStreet : Player { var secretStockType = 0 var secretStockValue = 0 override var random = Random() var turn = 0 val stockPriceStatistics = mutableMapOf<Int, DoubleSummaryStatistics>() override fun secretValue(stockType: Int, value: Int) { secretStockType = stockType secretStockValue = value } override fun makeOffer(currentStock: List<Stock>): Offer { val stock = currentStock[random.nextInt(currentStock.size)] val type = stock.type val amount = random.nextInt(stock.amount) val price = getSellPrice(type) * amount return Offer(Stock(type, amount), Math.ceil(price).toInt()) } override fun acceptOffer(offers: List<Offer>): Offer? { var bestOffer : Offer? = null var mostProfit = 0.0 for (offer in offers) { val offerProfit = profitOfOffer(offer) if (offerProfit > mostProfit) { bestOffer = offer mostProfit = offerProfit } } if (bestOffer != null && bestOffer !in offers) { throw IllegalStateException("Tried to accept non-existent offer.\nOffer: $bestOffer\nAvailable Offers: ${offers.joinToString(";")}") } return bestOffer } override fun acceptedOffers(offers: List<Offer>) { turn++ for ((stock, payment) in offers) { val stats = stockPriceStatistics.getOrPut(stock.type) { DoubleSummaryStatistics() } for (i in 1..stock.amount) { stats.accept(payment.toDouble() / stock.amount) } } } private fun getSellPrice(type: Int): Double { var price = getPrice(type) if (price < 1000) { price += (1000 - price) * (MAX_TURNS - turn) / MAX_TURNS } return if (type == secretStockType) Math.max(secretStockValue.toDouble(), price) else price } private fun getPrice(type: Int): Double { return stockPriceStatistics[type]?.average ?: DEFAULT_STOCK_VALUE.toDouble() } private fun profitOfOffer(offer: Offer): Double { return getBuyPrice(offer.offer.type) * offer.offer.amount - offer.payment } private fun getBuyPrice(type: Int): Double { var price = getPrice(type) price = price * turn / MAX_TURNS return if (type == secretStockType) Math.min(secretStockValue.toDouble(), price) else Math.min(price, MAX_STOCK_VALUE.toDouble()) } } ``` [Answer] # UncleScrooge, Java ``` import java.util.List; import com.ppcg.stockexchange.*; public class UncleScrooge extends Player { public Offer acceptOffer(List<Offer> offers) { Offer offer; try { offer = offers.get(0); } catch (Exception ex) { return null; } if (offer.getPayment() < 100) return offer; else return null; } public Offer makeOffer(List<Stock> currentStock){ if (this.getRandom().nextDouble() < 0.6) return new Offer(currentStock.get(secretStockType).setAmount(1), Integer.MAX_VALUE); else return null; } public void secretValue(int stockType, int value) { super.secretValue(stockType, value); } public void acceptedOffers(List<Offer> acceptedOffers) { } } ``` Sell stock at a really high price, and only buy if the price is less than 100. [Answer] # Profiteer, Java Profiteer is in it for the money, and he's always counting coins. He makes a conservative estimate of how much money he's got. He'll then buy the secret stock, if it's less than the value, or buy cheap stock. He also remembers how much he's paid for everything, and always makes offers above the stock price. Furthermore, he'll make higher offers if he has less money. *Note: I think I've done this correctly, but if @NathanMerrill wouldn't mind skimming my code for bugs, that'd be great* ``` import com.ppcg.stockexchange.Offer; import com.ppcg.stockexchange.Player; import com.ppcg.stockexchange.Stock; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class Profiteer extends Player { private List<StockInfo> onMarket; private List<StockInfo> stocks; private int money; private boolean first = true; @Override public Offer acceptOffer(List<Offer> offers) { Offer finalOffer; Optional<Offer> offer = offers.stream().filter(o -> o.getOffer().getType() == this.secretStockType && o.getPayment() < this.secretStockValue * o.getOffer().getAmount()).sorted((a, b) -> Integer.compare((this.secretStockValue * a.getOffer().getAmount()) - b.getPayment(), (this.secretStockValue * b.getOffer().getAmount()) - b.getPayment())).findFirst(); if (offer.isPresent()) { finalOffer = offer.get(); } else { finalOffer = offers.stream().sorted((a, b) -> Integer.compare(a.getPayment(), b.getPayment())).findFirst().orElse(null); } if (finalOffer == null || this.money <= finalOffer.getPayment()) { return null; } else { this.stocks.add(new StockInfo(finalOffer.getOffer(), finalOffer.getPayment())); this.refreshMoney(); return finalOffer; } } @Override public Offer makeOffer(List<Stock> stocks) { if (this.first) { this.init(stocks); } else { this.refreshMarketList(stocks); } Optional<StockInfo> least = this.stocks.stream().sorted((a, b) -> Integer.compare(a.getBoughtPrice(), b.getBoughtPrice())).findFirst(); Optional<StockInfo> secret = this.stocks.stream().filter(stockInfo -> stockInfo.getStock().getType() == this.secretStockType).sorted((a, b) -> Integer.compare(a.getBoughtPrice(), b.getBoughtPrice())).findFirst(); StockInfo finalOffer; int price; if (secret.isPresent()) { finalOffer = secret.get(); } else if (least.isPresent()) { finalOffer = least.get(); } else { return null; } this.onMarket.add(finalOffer); this.stocks.remove(finalOffer); price = this.calculatePrice(finalOffer.boughtPrice); return new Offer(new Stock(finalOffer.getStock().getType(), finalOffer.getStock().getAmount()), price); } private int calculatePrice(int boughtPrice) { return (int) (boughtPrice + ((boughtPrice / (double) this.money) * this.money)) + 1; } private void refreshMarketList(List<Stock> stocks) { this.stocks.addAll(this.onMarket.stream().filter(stockInfo -> stocks.contains(stockInfo.getStock())).collect(Collectors.toList())); this.onMarket.clear(); } private void refreshMoney() { this.money = this.stocks.stream().mapToInt(info -> this.secretStockType == info.getStock().getType() ? this.secretStockValue : 5).reduce((a, b) -> a + b).orElseGet(() -> 0) - this.stocks.stream().mapToInt(StockInfo::getBoughtPrice).reduce((a, b) -> a + b).orElseGet(() -> 0); } private void init(List<Stock> stocks) { this.stocks = stocks.stream().map(stock -> new StockInfo(stock, 0)).collect(Collectors.toList()); this.onMarket = new ArrayList<>(); this.money = 0; this.first = false; this.refreshMoney(); } private static class StockInfo { private Stock stock; private int boughtPrice; public StockInfo(Stock stock, int boughtPrice) { this.stock = stock; this.boughtPrice = boughtPrice; } public Stock getStock() { return this.stock; } public int getBoughtPrice() { return this.boughtPrice; } } } ``` [Answer] # MaxBot, Java This bot tries to make the most profit out of each transaction. While selling, puts the price of an unknown stock at $300, when buying $250. ``` import java.util.List; import com.ppcg.stockexchange.*; public class MaxBot extends Player { int toSell; int sellPrice; public void secretValue(int stockType, int value) { super.secretValue(stockType, value); toSell = stockType; sellPrice = (value + 1000)/2; } public Offer acceptOffer(List<Offer> offers) { Offer max = null; int maxDif = 0; for(Offer o: offers){ int price = secretStockType == o.getOffer().getType()? secretStockValue: 250; int val = price * o.getOffer().getAmount(); int dif = val - o.getPayment(); if(maxDif < dif){ max = o; maxDif = dif; } } return max; } public Offer makeOffer(List<Stock> currentStock){ if(toSell == -1){ return null; } int sum = 0; for (Stock s: currentStock){ if(s.getType() == toSell){ sum += s.getAmount; } } int n = sum - sum/2; return new Offer(new Stock(toSell, n), n * sellPrice); } public void acceptedOffers(List<Offer> acceptedOffers) { int highStock = -1; int highPrice = 0; int markup = 0; for(Offer o: offers){ int trueVal = secretStockType == o.getOffer().getType()? secretStockValue: 250; int marketVal = o.getPayment()/o.getOffer().getAmount(); if(marketVal - trueVal > markup){ highStock = o.getOffer().getType(); highPrice = marketVal; markup = marketVal - trueVal; } } toSell = highStock; } } ``` [Answer] # BlackMarket, Java Not much to say about this one, seeing as these transactions will be... off the charts, you might say. ``` import java.util.List; import com.ppcg.stockexchange.*; public class BlackMarket extends Player { private boolean approvedBySEC = false; private int ammoLeft = 30; public String taxView = "We want higher tax rates"; public String excuse = "I never saw that in my life"; public void secretValue(int drugType, int warrantForMyArrest) { super.secretValue(drugType, warrantForMyArrest); if (warrantForMyArrest != 0 || drugType == 420) { ammoLeft += 10; } } public Offer acceptOffer(List<Offer> offers) { for (Offer offer : offers) { if (this.approvedBySEC || offer.getPayment() < 9) return offer; } return null; } public Offer makeOffer(List<Stock> currentStock) { return new Offer(new Stock(0,1),420); } } ``` [Answer] ## NotQuiteABanksBestFriend, Python 3 Command.txt: ``` python3 NotQuiteABanksBestFriend.py ``` ``` NotQuiteABanksBestFriend.py import random from functools import total_ordering from io import StringIO log = StringIO() log.write("\n\n~~~NEW GAME~~~\n\n") LIST_DELIMITER = ';' STOCK_DELIMITER = ':' OFFER_DELIMITER = '@' JAVA_MAX_INT = 2147483647 @total_ordering class Stock: @staticmethod def parse(string: str): return Stock(*map(int, string.split(STOCK_DELIMITER))) def __init__(self, stock_type: int, amount: int): self.type = stock_type self.amount = max(amount, 0) def __str__(self): return "T%sx%s"%(self.type, self.amount) def __repr__(self): return str(self.type)+STOCK_DELIMITER+str(int(self.amount)) def __bool__(self): return bool(self.amount) def __eq__(self, other): return self.amount == other.amount def __lt__(self, other): return self.amount < other.amount def update(self, amount) -> 'Stock': return Stock(self.type, amount) def __mul__(self, other: int) -> 'Stock': return self.update(self.amount*other) def __floordiv__(self, other: int) -> 'Stock': return self.update(self.amount//other) def __add__(self, other: int) -> 'Stock': return self.update(self.amount+other) def __sub__(self, other: int) -> 'Stock': return self.update(self.amount-other) class Offer: @staticmethod def parse(string: str) -> 'Offer': try: stock, price = string.split(OFFER_DELIMITER) except ValueError: raise Exception("Cannot unpack "+string) return Offer(Stock.parse(stock), int(price.strip())) def __init__(self, stock: Stock, price: int): self.stock = stock self.price = price try: self.price_per_unit = self.price/self.stock.amount except ZeroDivisionError: self.price_per_unit = float('inf') def __str__(self): return "%s$%s"%(self.stock, self.price) def __repr__(self): return repr(self.stock)+OFFER_DELIMITER+str(int(self.price)) def read_stock_value(value: str): global hidden_price, hidden_stock stock, price = value.split(STOCK_DELIMITER) hidden_price = float(price) hidden_stock = int(stock) log.write("Hidden StockID: %s\nHidden Price: %s\n"%(hidden_stock, hidden_price)) def process_input(): handlers = { "SecretValue": read_stock_value, "RandomSeed": read_seed, "MakeOffer": make_offer, "AcceptOffer": accept_offer, "AcceptedOffers": accepted_offers, } method = input().strip() data = input().strip() output = handlers[method](data) if output is not None: print(repr(output)) else: print() def read_seed(seed: str): random.seed(int(seed)) def start(): while True: process_input() hidden_stock = None hidden_price = None def filter_offers(offer): if offer.stock.amount == 0: return False if offer.price_per_unit > 1000: return False return True def certain_profit(offer): stock = offer.stock if stock.type == hidden_stock and offer.price_per_unit < hidden_price: log.write("Offer, %s is certainly profitable.\n"%offer) return True return False def make_offer(current_stock: str): current_stock = list(map(Stock.parse, current_stock.split(LIST_DELIMITER))) own_stock = [stock for stock in current_stock if stock.type == hidden_stock] if own_stock and own_stock[0]: own_stock = own_stock[0] amount_sold = min(random.randrange(1,50), own_stock.amount) price = hidden_price+random.randrange(10,50) return Offer(Stock(hidden_stock, amount_sold), price*amount_sold) sell_stock = random.choice(current_stock) amount_sold = min(random.randrange(1,50), sell_stock.amount) price = random.randrange(1000, JAVA_MAX_INT//(amount_sold or 1)) return Offer(Stock(sell_stock.type, amount_sold), price*(amount_sold or 1)) def accept_offer(available_offers: str): available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER))) filtered_offers = list(filter(filter_offers, available_offers)) profitable = list(filter(certain_profit, filtered_offers)) rtn_list = filtered_offers if profitable: log.write("Profitable: %s\n"%profitable) rtn_list = profitable if not rtn_list: return None accepted_offer = min(rtn_list, key=lambda offer: offer.price_per_unit) log.write("Bidded for %s\n"%accepted_offer) return accepted_offer def accepted_offers(offers: str): pass if __name__ == "__main__": try: start() finally: log.close() ``` Always tries to sell hidden stock for more than it's worth. ]
[Question] [ Your challenge is simple: GIven an integer **N**, ouput every list of positive integers that sums to **N**. For example, if the input was 5, you should output ``` [1, 1, 1, 1, 1] [1, 1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 4] [2, 3] [5] ``` These lists do not have to be output in any particular order, nor do the numbers inside each list. For example, this would also be an acceptable output for '5': ``` [1, 1, 1, 2] [5] [3, 1, 1] [2, 1, 2] [4, 1] [1, 1, 1, 1, 1] [2, 3] ``` You can safely assume that the input will be a positive integer, and you can take this number in any reasonable format. **You may NOT use any builtin functions that do this.** If your program either fails or takes too long for large **N** this is OK, but you must at the very least produce the correct output for the first 15. Standard loopholes apply, and the shortest answer in bytes wins! # Test IO ``` 1: [[1]] 2: [[1, 1], [2]] 3: [[1, 1, 1], [1, 2], [3]] 4: [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]] 5: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [1, 4], [2, 3], [5]] 7: [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 3], [1, 1, 1, 2, 2], [1, 1, 1, 4], [1, 1, 2, 3], [1, 1, 5], [1, 2, 2, 2], [1, 2, 4], [1, 3, 3], [1, 6], [2, 2, 3], [2, 5], [3, 4], [7]] 10: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 4], [1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 1, 1, 5], [1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 2, 4], [1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 6], [1, 1, 1, 2, 2, 3], [1, 1, 1, 2, 5], [1, 1, 1, 3, 4], [1, 1, 1, 7], [1, 1, 2, 2, 2, 2], [1, 1, 2, 2, 4], [1, 1, 2, 3, 3], [1, 1, 2, 6], [1, 1, 3, 5], [1, 1, 4, 4], [1, 1, 8], [1, 2, 2, 2, 3], [1, 2, 2, 5], [1, 2, 3, 4], [1, 2, 7], [1, 3, 3, 3], [1, 3, 6], [1, 4, 5], [1, 9], [2, 2, 2, 2, 2], [2, 2, 2, 4], [2, 2, 3, 3], [2, 2, 6], [2, 3, 5], [2, 4, 4], [2, 8], [3, 3, 4], [3, 7], [4, 6], [5, 5], [10]] ``` Super large test case: 15 should output this ``` [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5], [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4], [1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3], [1, 1, 1, 1, 1, 1, 1, 1, 1, 6], [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3], [1, 1, 1, 1, 1, 1, 1, 1, 2, 5], [1, 1, 1, 1, 1, 1, 1, 1, 3, 4], [1, 1, 1, 1, 1, 1, 1, 1, 7], [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 1, 1, 1, 2, 2, 4], [1, 1, 1, 1, 1, 1, 1, 2, 3, 3], [1, 1, 1, 1, 1, 1, 1, 2, 6], [1, 1, 1, 1, 1, 1, 1, 3, 5], [1, 1, 1, 1, 1, 1, 1, 4, 4], [1, 1, 1, 1, 1, 1, 1, 8], [1, 1, 1, 1, 1, 1, 2, 2, 2, 3], [1, 1, 1, 1, 1, 1, 2, 2, 5], [1, 1, 1, 1, 1, 1, 2, 3, 4], [1, 1, 1, 1, 1, 1, 2, 7], [1, 1, 1, 1, 1, 1, 3, 3, 3], [1, 1, 1, 1, 1, 1, 3, 6], [1, 1, 1, 1, 1, 1, 4, 5], [1, 1, 1, 1, 1, 1, 9], [1, 1, 1, 1, 1, 2, 2, 2, 2, 2], [1, 1, 1, 1, 1, 2, 2, 2, 4], [1, 1, 1, 1, 1, 2, 2, 3, 3], [1, 1, 1, 1, 1, 2, 2, 6], [1, 1, 1, 1, 1, 2, 3, 5], [1, 1, 1, 1, 1, 2, 4, 4], [1, 1, 1, 1, 1, 2, 8], [1, 1, 1, 1, 1, 3, 3, 4], [1, 1, 1, 1, 1, 3, 7], [1, 1, 1, 1, 1, 4, 6], [1, 1, 1, 1, 1, 5, 5], [1, 1, 1, 1, 1, 10], [1, 1, 1, 1, 2, 2, 2, 2, 3], [1, 1, 1, 1, 2, 2, 2, 5], [1, 1, 1, 1, 2, 2, 3, 4], [1, 1, 1, 1, 2, 2, 7], [1, 1, 1, 1, 2, 3, 3, 3], [1, 1, 1, 1, 2, 3, 6], [1, 1, 1, 1, 2, 4, 5], [1, 1, 1, 1, 2, 9], [1, 1, 1, 1, 3, 3, 5], [1, 1, 1, 1, 3, 4, 4], [1, 1, 1, 1, 3, 8], [1, 1, 1, 1, 4, 7], [1, 1, 1, 1, 5, 6], [1, 1, 1, 1, 11], [1, 1, 1, 2, 2, 2, 2, 2, 2], [1, 1, 1, 2, 2, 2, 2, 4], [1, 1, 1, 2, 2, 2, 3, 3], [1, 1, 1, 2, 2, 2, 6], [1, 1, 1, 2, 2, 3, 5], [1, 1, 1, 2, 2, 4, 4], [1, 1, 1, 2, 2, 8], [1, 1, 1, 2, 3, 3, 4], [1, 1, 1, 2, 3, 7], [1, 1, 1, 2, 4, 6], [1, 1, 1, 2, 5, 5], [1, 1, 1, 2, 10], [1, 1, 1, 3, 3, 3, 3], [1, 1, 1, 3, 3, 6], [1, 1, 1, 3, 4, 5], [1, 1, 1, 3, 9], [1, 1, 1, 4, 4, 4], [1, 1, 1, 4, 8], [1, 1, 1, 5, 7], [1, 1, 1, 6, 6], [1, 1, 1, 12], [1, 1, 2, 2, 2, 2, 2, 3], [1, 1, 2, 2, 2, 2, 5], [1, 1, 2, 2, 2, 3, 4], [1, 1, 2, 2, 2, 7], [1, 1, 2, 2, 3, 3, 3], [1, 1, 2, 2, 3, 6], [1, 1, 2, 2, 4, 5], [1, 1, 2, 2, 9], [1, 1, 2, 3, 3, 5], [1, 1, 2, 3, 4, 4], [1, 1, 2, 3, 8], [1, 1, 2, 4, 7], [1, 1, 2, 5, 6], [1, 1, 2, 11], [1, 1, 3, 3, 3, 4], [1, 1, 3, 3, 7], [1, 1, 3, 4, 6], [1, 1, 3, 5, 5], [1, 1, 3, 10], [1, 1, 4, 4, 5], [1, 1, 4, 9], [1, 1, 5, 8], [1, 1, 6, 7], [1, 1, 13], [1, 2, 2, 2, 2, 2, 2, 2], [1, 2, 2, 2, 2, 2, 4], [1, 2, 2, 2, 2, 3, 3], [1, 2, 2, 2, 2, 6], [1, 2, 2, 2, 3, 5], [1, 2, 2, 2, 4, 4], [1, 2, 2, 2, 8], [1, 2, 2, 3, 3, 4], [1, 2, 2, 3, 7], [1, 2, 2, 4, 6], [1, 2, 2, 5, 5], [1, 2, 2, 10], [1, 2, 3, 3, 3, 3], [1, 2, 3, 3, 6], [1, 2, 3, 4, 5], [1, 2, 3, 9], [1, 2, 4, 4, 4], [1, 2, 4, 8], [1, 2, 5, 7], [1, 2, 6, 6], [1, 2, 12], [1, 3, 3, 3, 5], [1, 3, 3, 4, 4], [1, 3, 3, 8], [1, 3, 4, 7], [1, 3, 5, 6], [1, 3, 11], [1, 4, 4, 6], [1, 4, 5, 5], [1, 4, 10], [1, 5, 9], [1, 6, 8], [1, 7, 7], [1, 14], [2, 2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 5], [2, 2, 2, 2, 3, 4], [2, 2, 2, 2, 7], [2, 2, 2, 3, 3, 3], [2, 2, 2, 3, 6], [2, 2, 2, 4, 5], [2, 2, 2, 9], [2, 2, 3, 3, 5], [2, 2, 3, 4, 4], [2, 2, 3, 8], [2, 2, 4, 7], [2, 2, 5, 6], [2, 2, 11], [2, 3, 3, 3, 4], [2, 3, 3, 7], [2, 3, 4, 6], [2, 3, 5, 5], [2, 3, 10], [2, 4, 4, 5], [2, 4, 9], [2, 5, 8], [2, 6, 7], [2, 13], [3, 3, 3, 3, 3], [3, 3, 3, 6], [3, 3, 4, 5], [3, 3, 9], [3, 4, 4, 4], [3, 4, 8], [3, 5, 7], [3, 6, 6], [3, 12], [4, 4, 7], [4, 5, 6], [4, 11], [5, 5, 5], [5, 10], [6, 9], [7, 8], [15]] ``` ### Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 84165; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 31716; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] ## Pyth, ~~10~~ 9 bytes ``` {SMlMM./U ``` Not too sure if this isn't cheating, but the rules only said one cannot use **integer** partition (it's not stated clearly in the question itself, but a comment by OP in the question says integer partition). I'm using ~~string~~ **list** partition, which makes slices of the list that concatenate up to the "mother" list. I believe I have to thank @Maltysen for the idea of using lists rather than strings. n=15 takes less than one second on my machine. In dataflow pseudocode: ``` input // initial data U range // makes a list of length equal to input ./ partition // partitions string lMM length // length of each substring in each way to partition SM sort // sort each way to partition { deduplicate // removes all duplicate after sorting print // implicit, output final result ``` [Try it online here.](http://pyth.herokuapp.com/?code=%7BSMlMM.%2FU&input=4&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A7%0A10%0A15&debug=0) [Answer] # Pyth, 18 bytes ``` L?b{SM+R-bsdsyMb]Y ``` [Try it online!](http://pyth.herokuapp.com/?code=L%3Fb%7BSM%2BR-bsdsyMb%5DYy&input=15&debug=0) (The `y` at the end is used to call the function) This is fairly quick. This uses recursion. If the input is `b`, my method will generate the partitions from `0` to `b-1`, and then generate the correct partitions from each. For example, when `b=4`: * `b=0` gives `[[]]` * `b=1` gives `[[1]]` * `b=2` gives `[[2], [1, 1]]` * `b=3` gives `[[3], [1, 2], [1, 1, 1]]` Then, to each partition in `b=0`, append `4` (to make the sum 4); to each partition in `b=1`, append `3` (to make the sum `4`); etc. This is mainly how it works. ``` L?b{SM+R-bsdsyMb]Y L define a function called "y" which takes an argument: "b" ?b test for truthiness of b (in this case, test if b>0). {SM+R-bsdsyMb if truthy: yMb call this function from 0 to b-1. s unpack each list of partitions, generating only partitions. +R to each partition (d), append: - the difference of b b (the argument) and sd the sum of d (the partition). SM sort each partition. { remove duplicates. ]Y if falsey: Y yield []. ] yield [[]]. ``` [Answer] # Haskell, 53 bytes ``` p=[[]]:[map(1:)q++[a+1:b|a:b<-q,all(a<)b]|q<-p] (p!!) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` :"0Gq:@XNG3$Yc!dS!Xu ``` [**Try it online!**](http://matl.tryitonline.net/#code=OiIwR3E6QFhORzMkWWMhZFMhWHU&input=NQ) For input `15` it takes about 2 seconds in the online compiler. ### Explanation This works by generating partition *points* and then converting to partition *lengths*. What I mean by this is the following. Given input *N* = 5, a possible partition is [2 2 1]. This is represented by partition points [0 2 4 5], such that *consecutive differences* (or lengths) of the partition points give the resulting partition of the input number. All arrays of partition points start with 0 and end with *N*. The number *k* of intermediate points varies from 0 to *N*-1. For *N* and *k* given, the intermediate points can be generated as a combination of the numbers [1, 2, ..., *N*-1] taken *k* at a time. Several arrays of partition points may give rise to the same result in a different order. For example, partition points [0 1 3 5] would give the partition lengths [1 2 2], i.e. the same as the previous [2 2 1] only in a different order. This has to be taken into account by *sorting* each array of partition lengths and *removing duplicates*. ``` : % Implicitly input N. Push [1 2 ... N]. These are the possible values of k, % except with N instead of 0 " % For each 0 % Push 0 Gq: % Push [1 ... N-1]. These the possible intermediate points @XN % Push k and produce the combinations. Each k produces a 2D array with % each combination on a row. The value k=N produces an empty array G % Push N 3$Yc % Prepend a column of zeros and append a column of N to the array !d % Transpose. Consecutive differences of each column S! % Sort each column. Transpose Xu % Keep only unique rows % Implicitly end for and display all arrays in the stack ``` [Answer] # J, ~~49~~ ~~42~~ ~~36~~ ~~35~~ 32 bytes ``` a:1&([:~.@,(,;}./:~@,(+{.))&>)~] ``` It's tacit now! Builds the integer partition of *n* by constructing the integer partitions from 1 to *n*. Computes the result for *n* = 15 in a millisecond. Starting with the initial integer partition `[[1]]` which corresponds to *n* = 1, construct the next integer partition by joining the results from two operations: appending a 1 to each partition; incrementing the smallest value by 1 in each partition. Of course, duplicate partitions will be removed. To get the integer partition *n* = 2 and onwards, ``` Partition for n = 1 [[1]] Partition for n = 2 [[1, 1]] join [[2]] = [[1, 1], [2]] Partition for n = 3 [[1, 2], [1, 1, 1]] join [[3], [1, 2]] = [[3], [1, 2], [1, 1, 1]] ... and so on ``` ## Usage ``` f =: a:1&([:~.@,(,;}./:~@,(+{.))&>)~] f 1 ┌─┐ │1│ └─┘ f 2 ┌───┬─┐ │1 1│2│ └───┴─┘ f 3 ┌─────┬───┬─┐ │1 1 1│1 2│3│ └─────┴───┴─┘ f 5 ┌─────────┬───────┬─────┬───┬─────┬───┬─┐ │1 1 1 1 1│1 1 1 2│1 2 2│2 3│1 1 3│1 4│5│ └─────────┴───────┴─────┴───┴─────┴───┴─┘ # f 15 176 ``` ## Explanation Since J does not support ragged arrays, each partition has to be boxed so they they won't be zero padded when appended to other partitions. ``` a:1&([:~.@,(,;}./:~@,(+{.))&>)~] Input: n a: The empty box ] Get the input n 1&( )~ Repeat n times with an initial array of one empty box ( )&> Operate on each partition ( ) Hook a partition {. Get its head (the smallest value) 1 + Add 1 to it 1 }. Drop the first value in each partition , Join the previous two results /:~@ Sort it 1 , Prepend a 1 to the initial partition ; Box the last two results and join them [: , Flatten the pairs of boxes ~.@ Remove duplicates and return Return the final result where each box is a partition of n ``` [Answer] ## Python, 65 bytes **Python 3** ``` def f(n,i=1,l=[]):n or print(l);i>n or[f(n-i,i,[i]+l),f(n,i+1,l)] ``` This function accumulates a partition and prints the outputs, branching on choices. It decides how many 1's to put in the partition, how many 2's, and so on. For each value `i`, it either * Adds a part of size `i`, and decreases `n` to `n-i`, or * Moves on to `i+1` If `i>n`, then no more parts can be made, so it stops. If `n` falls to `0`, the partition is successful and so is printed. **Python 2** ``` f=lambda n,i=1:n/i and[l+[i]for l in f(n-i,i)]+f(n,i+1)or[[]][n:] ``` A recursive method that outputs a list of partitions. As with the Python 3 code, it counts up the part size `i` and decides at each step whether to add another part of size `i` or stop. Both of these do `n=15` almost instantly. [Answer] ## Javascript, 194 bytes ``` p=n=>{var a=[];for(var i=1;i<=n-i;i+=1){for(v of p(n-i)){v.push(i);a.push(v.sort())}}a.push([n]);return a};n=5;s=p(n).map(v=>JSON.stringify(v));s=s.filter((v,i)=>s.indexOf(v)==i);console.log(s); ``` **Non-minified** Finding uniques by sorting and comparing to a string is quite a hack, but probably saves space. ``` p = n => { var a = []; for (var i = 1; i <= n-i; i++) { for (v of p(n-i)) { v.push(i); a.push(v.sort()); } } a.push([n]); return a; } n = 5; s = p(n).map(v => JSON.stringify(v)); s = s.filter((v,i) => s.indexOf(v) == i); console.log(s); ``` [Answer] ## Haskell, 44 bytes ``` 0%m=[[]] n%m=[j:r|j<-[m..n],r<-(n-j)%j] (%1) ``` The auxiliary function `n%m` gives the partitions of `n` into parts `≥m`, with the main function using `m=1`. It branches of each first entry `j` with `m≤j≤n`, recursing on the remaining partition of `n-j` into parts that are at least `j`. The base case `n==0` gives just the empty partition. [Answer] # Python 3.5, ~~82~~ 72 bytes ``` f=lambda n:{(*sorted([*p,i]),)for i in range(1,n)for p in f(n-i)}|{(n,)} ``` Returns a set of tuples. **n = 15** finishes instantly. Test it on [repl.it](https://repl.it/C7rf/3). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 33 bytes (Non-competing) ``` :1f:oad. :1eI,.##lI,.:{.>0}a+?,.= ``` This is non-competing because of a bug fix. This takes about 1 second for `15` on my machine. For `20` and greater this crashes with an `Out of global stack` exception. ### Explanation This uses no partitioning built-in of any kind, and instead uses the fact that `+` works both ways through constraints propagation. * Main predicate: ``` :1f Find the list of all valid outputs of predicate 1 :oa Sort each element of that list d. Output is that list of sorted lists minus all duplicates ``` * Predicate 1: ``` :1eI I is an integer between Input and 1 .##lI, Output is a list of length I .:{.>0}a Elements of Output are integers greater than 0 +?, The sum of the elements of Output is Input .= Assign values to the elements of Output ``` [Answer] # Pyth, 17 bytes ``` L|{SMs+LVrb0yMb]Y ``` Defines a function named `y`. [Try it online](https://pyth.herokuapp.com/?code=L%7C%7BSMs%2BLVrb0yMb%5DYy&input=5&test_suite_input=5). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` b1ŒṖḅ1Ṣ€Q ``` [Try it online!](http://jelly.tryitonline.net/#code=YjHFkuG5luG4hTHhuaLigqxR&input=&args=MTU) ### How it works ``` b1ŒṖḅ1Ṣ€Q Main link. Argument: n (integer) b1 Convert n to unary, i.e., a list A of n 1's. ŒṖ Generate all partitions of the list A. ḅ1 Convert each flat list from unary to integer. Ṣ€ Sort each resulting list. Q Unique; deduplicate the lists. ``` [Answer] ## J, 39 bytes ``` [:~.i.<@\:~@(#;.1~"1 0)1,@{@;(<1 0)#~<: ``` This is a monadic verb that takes an integer and returns an array of boxed arrays. [Try it here.](http://tryj.tk/) Usage: ``` p =: [:~.i.<@\:~@(#;.1~"1 0)1,@{@;(<1 0)#~<: p 3 +-----+---+-+ |1 1 1|2 1|3| +-----+---+-+ ``` On input 15, it runs for about a second on my machine. ## Explanation This challenge immediately looked like a job for Catalogue (`{`) and Cut (`;.`). The outline of the algorithm is: * Produce all 0-1 arrays of length `n`. * For each of them, cut a dummy length-`n` array along the 1s, and list the lengths of each part. * Sort the lengths, and remove duplicate arrays from the result. Apparently, Luis Mendo had the [same idea](https://codegolf.stackexchange.com/a/84169/32014) too. Explanation of code: ``` [:~.i.<@\:~@(#;.1~"1 0)1,@{@;(<1 0)#~<: Input is n. <: n-1 #~ copies of (<1 0) the boxed array [1 0]. 1 ; Prepend the boxed array [1]. {@ Catalog: produces all combinations of taking one item from each box, in a high-dimensional matrix. ,@ Flatten the matrix. This results in a list of all boxed 0-1 arrays of length n that begin with a 1. i. The array A =: 0, 1, ..., n-1. ( "1 0) For each of the boxed arrays B: ;.1~ cut A along the occurrences of 1s in B, # take the length of each part, \:~@ sort the lengths, <@ and put the result in a box. [:~. Remove duplicate boxes. ``` [Answer] # Mathematica, ~~62~~ 54 bytes ``` Inner[#2~Table~#&,FrobeniusSolve[r=Range@#,#],r,Join]& ``` The partitions of an integer *n* can be found by solving for *n*-tuples of non-negative integers (*c*1, *c*2, ..., *c**n*) such that *c*1 + 2 *c*2 + ... + *n* *c**n* = *n*. `FrobeniusSolve` is able to find all solutions to this equation which are used to create that many copies of their respective values in order to find all integer partitions of *n*. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ɾÞ×'∑?= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvsOew5cn4oiRPz0iLCIiLCI1Il0=) ``` ɾÞ×'∑?= ɾ # Get a list in the range [1, input] Þ× # Get all combinations (with replacement) of all lengths ' # Filter for: ∑?= # Sum equals the input ``` [Answer] ## JavaScript ~~(Firefox 30-57) 79~~ ES6, 65 bytes ``` f=(n,m=1,a=[])=>n?m>n?[]:[...f(n-m,m,[...a,m]),...f(n,m+1,a)]:[a] ``` Port of @xnor's Python solution. (If only I'd noticed that you could recurse over `m` as well as `n`...) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Å1.œO€{ê ``` Outputs as a list of lists, from `n` amount of 1s to `[n]`, where each inner list is sorted (I know the rules allow them to be unsorted, but it's necessary for the uniquify of lists). [Try it online](https://tio.run/##yy9OTMpM/f//cKuh3tHJ/o@a1lQfXvX/v6EpAA) or [verify the first 15 result](https://tio.run/##yy9OTMpM/W9o6qrkmVdQWmKloGTvp8Ol5F9aAuHp@P0/3Gqod3Sy/6OmNdWHV/3XObTN/j8A). If builtins were allowed, this would be **2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead (with the same exact results): `Åœ` - [Try it online](https://tio.run/##yy9OTMpM/f//cOvRyf//G5oCAA) or [verify the first 15 results](https://tio.run/##yy9OTMpM/W9o6qrkmVdQWmKloGTvp8Ol5F9aAuHp@P0/3Hp08n@dQ9vs/wMA). **Explanation:** ``` Å1 # Push a list with the (implicit) input amount of 1s .œ # Get all partitions of this list O # Sum each inner-most list €{ # Sort each inner list ê # Sorted uniquify the list of lists # (after which the result is output implicitly) ``` Minor note: `ê` (sorted uniquify) could also just be `Ù` (uniquify) for the same result, but with the added sort it's a lot faster in this case. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 44 bytes ``` (1!) _!0=[] a!n=anyOf[a ..n]#n a#n=a:a!(n-a) ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z/NVsNQUZMrXtHANjqWK1ExzzYxr9I/LTpRQU8vL1Y5jytRGShklaiokaebqPk/NzEzT8FWIU3B9D8A "Curry (PAKCS) – Try It Online") [Answer] ## [Scala](http://www.scala-lang.org/), 117 bytes Port of [@Dennis's Python answer](https://codegolf.stackexchange.com/a/84187/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##NYwxC8IwEEZ3f8WNOYqBDC6VCI4OnTqWIrG9QCRe0@YEQfztMQ5u33t8vDy56Mpyu9Mk0LnAQC8hnjOcU3pDmcmDV9xeWLDtSYae1qHCONpQvbUGq1XVKoNIMZMy8GQJERi1j046l1Swp3reB9SPSte2@S@dl01oRtSy1E7z6zAWgLQFlsjKK3NAPO4@5Qs) ``` def f(n:Int):Set[Seq[Int]]=if(n==1)Set(Seq(1))else(1 until n).flatMap(i=>f(n-i).map(_:+i).map(_.sorted)).toSet+Seq(n) ``` Ungolfed version. [Try it online!](https://tio.run/##TY6xCoMwEIZ3n@IfE6RChi4WCx0LdeooDqkmkJKewVyhID67VSvS4eDuvo@7Pzba62nqHk/TMErtCObDhtqISwgDEqA1FlZQjiuxzHE3XN1c5Goe6xoFhtkBnIUgFAWU3DZYVLGoQkm5rkYYH83OhcKb2HmQzKzXXOqAAQ7FeROwPMYBTmavlYV/Nh8IyNOFxq5n0@5k3Lox424OgRRrDNpSJL8KvSP2JKxQRylPyThNXw) ``` object Main extends App{ def f(n: Int): Set[List[Int]] = { if (n == 1) { Set(List(1)) } else { (1 until n).flatMap { i => f(n - i).map { p => (p :+ i).sorted } }.toSet + List(n) } } println(f(15)); } ``` ]
[Question] [ ## Introduction Your mission in life is simple: Prove people wrong on the internet! To do this you usually carefully analyze their statements and point out the contradiction in them. It's time to automate this, but as we are lazy, we want to prove people wrong with the least effort (read: shortest code) possible. ## Specification ### Input Your input will be a formula in [conjunctive normal form](https://en.wikipedia.org/wiki/Conjunctive_normal_form). For the format, you may use the below format or define your own, upon the needs of your language (you may not encode more in the format than the pure CNF though). The test-cases (here) are however provided in the below format (although it won't be too hard generating your own). Your input will be a a list of a list of a list of *variables* (you may also read it as strings / require strings). The input is a formula in conjunctive normal form (CNF) written as a *set* of clauses, each being a list of two lists. The first list in the clause encodes the positive literals (variables), the second list encodes the negative (negated) literals (variables). Every variable in the clause is OR'ed together and all clauses are AND'ed together. To make it clearer: `[[[A,B],[C]],[[C,A],[B]],[[B],[A]]]` can be read as: `(A OR B OR (NOT C)) AND (C OR A OR (NOT B)) AND (B OR (NOT A))` ### Output The output is boolean, e.g. either some truthy value or some falsy value. ### What to do? It's simple: Check if the formula given at hand is satisfiable, e.g. whether there exists some assignment of true and false to all variables such that the overall formula yields "true". Your output will be "true" if the formula is satiesfiable and "false" if it is not. Fun-Fact: This is a NP-complete problem in the general case. Note: Generating a truth-table and checking if any resulting entry is true, is allowed. ### Corner Cases If you get an empty 3rd-level list, then there's no such (positive / negative) variable in that clause - a valid input. You can leave other corner cases undefined if you want to. You may also return true upon an empty formula (1st level list) and false upon an empty clause (2nd level list). ### Who wins? This is code-golf so the shortest answer in bytes wins! Standard rules apply of course. ## Test-cases ``` [[[P],[Q,R]],[[Q,R],[P]],[[Q],[P,R]]] -> true [[[],[P]],[[S],[]],[[R],[P]],[[U],[Q]],[[X],[R]],[[Q],[S]],[[],[P,U]],[[W],[Q,U]]] -> true [[[],[P,Q]],[[Q,P],[]],[[P],[Q]],[[Q],[P]]] -> false [[[P],[]],[[],[P,S]],[[P,T],[]],[[Q],[R]],[[],[R,S]],[[],[P,Q,R]],[[],[P]]] -> false optional behavior (not mandatory, may be left undefined): [] -> true (empty formula) [[]] -> false (empty clause) [[[],[]]] -> false (empty clause) ``` [Answer] ## Mathematica, 12 bytes ``` SatisfiableQ ``` Well, there's a built-in... Input format is `And[Or[a, b, Not[c], Not[d]], Or[...], ...]`. This *does* work correctly for empty sub-expressions, because `Or[]` is `False` and `And[]` is `True`. For the record, a solution which receives the list-based format from the challenge and does the conversion itself is 44 bytes, but the OP clarified in a comment that any format is fine as long as it doesn't encode any additional information: ``` SatisfiableQ[Or@@Join[#,Not/@#2]&@@@And@@#]& ``` [Answer] # Haskell, ~~203~~ 200 bytes ``` t=1<3 e%((t,f):r)=or((e<$>t)++map(not.e)f)&&e%r e%_=t u v b e s|s==v=b|t=e s s e[]c=1<0 s e(v:w)c=e%c||s(u v t e)w c||s(u v(1<0)e)w c g v[]=v g v((t,f):r)=g(v++[x|x<-t++f,notElem x v])r g[]>>=s(\x->t) ``` This challenge deserves a no-build-in answer, so here you go. [Try it on ideone](http://ideone.com/cKqqH2). The algorithm simply tries all variable assignments and checks whether one of them satisfies the formula. Input is in the form of `[([],["P","Q"]),(["Q","P"],[]),(["P"],["Q"]),(["Q"],["P"])]`, although instead of strings every type with equality will work. ### Ungolfed code: ``` type Variable = String type CNF = [([Variable], [Variable])] type Evaluation = (Variable -> Bool) satisfies :: Evaluation -> CNF -> Bool satisfies eval [] = True satisfies eval ((t,f):r) = or(map eval t ++ map (not.eval) f) && satisfies eval r update :: Evaluation -> Variable -> Bool -> Evaluation update eval s b var = if var == s then b else eval var search :: Evaluation -> [Variable] -> CNF -> Bool search eval [] cnf = False search eval (v:vars) cnf = satisfies eval cnf || search (update eval v True) vars cnf || search (update eval v False) vars cnf getVars :: CNF -> [Variable] -> [Variable] getVars [] vars = vars getVars ((t,f):cnf) vars = getVars cnf (vars ++ [v |v<-(t++f), notElem v vars]) isSat :: CNF -> Bool isSat cnf = search (\x->True) (getVars cnf []) cnf ``` [Answer] # JavaScript 6, 69B ``` x=>f=(v,e)=>(e=v.pop())?[0,1].some(t=>f([...v],eval(e+'=t'))):eval(x) ``` Usage: ``` f('a|b')(['a','b']) true ``` ]
[Question] [ Polyglots are programs that are valid in multiple programming languages simultaneously. Most such polyglots are written in such a way that certain constructs of one language are interpreted as comments of another language (e.g. `#define` in C being interpreted as a comment in several scripting languages). I am curious to see if it is possible to make a non-trivial polyglot which contains no comments, but also immediately changes when you remove any non-whitespace character, I therefore challenge you to come up with such a program. The concrete rules are as follows: 1. (Output). Your program must produce some output on the console under each of your languages. That is, your program is not permitted to simply exit without printing anything. 2. (Variance). As a relaxation of the standard polyglot definition, the program's output may vary between languages. 3. (Errors). Your program must not produce any errors (broadly defined) under any of your languages. For most languages, this is defined as returning a non-zero exit code from the compiler and/or interpreter. 4. (Restriction). The removal of any single non-whitespace character from your code should cause your program to change its behaviour under *every* one of your languages. The program may "change" by becoming invalid for that language, or by changing the output that is produced. 5. This is a *code challenge*. Winner is the program which is valid in the most programming languages. Ties will be broken in favor of shorter program length. The restriction rule doesn't apply to the removal of several characters. That is, it is fine if removing several characters simultaneously results in no change for one of your languages. Observe that the restriction rule implies that you cannot use Whitespace as one of your languages, as removing any non-whitespace character won't change the behaviour of the Whitespace program. Here's a simple example of a program that fulfills all the above restrictions, for the languages Python 2 and Python 3: ``` print("Hello World!") ``` Removing any character in `print` will cause both languages to throw a `NameError`; removing any bracket or quote will throw a `SyntaxError`, and removing any of the string characters will change the output in both languages. (Note that `print("hello", "world")` is a more subtle, but still valid program under the above rules). This example is a bit lame because Python 2 and Python 3 are very similar, so I won't accept any other solutions that only use different versions of the same language (especially Python 2 and Python 3). [Answer] # Bash + GolfScript + CJam ``` "echo" [] { cat<&3;} \ 3<""<("echo" 'p'~) ``` ### Output Bash: ``` [] p~ ``` GolfScript: ``` "echo" echo{ cat<&3;}0 ``` CJam: ``` echo{ cat<&3;}-1echop ``` There is a `\x7f` in the end of output of CJam. [Answer] # Bash + Befunge ``` "echo" $,$,"ol":,,,@ ``` prints 'hello' in befunge. [Answer] # GolfScript + PHP + CJam + Mathematica + bc + Pyth + [///](http://esolangs.org/wiki////) + TI-Basic + R + Octave + Matlab + Scilab + [Numeric Topline](http://esolangs.org/wiki/Numeric_Topline) + ?[Fueue](http://esolangs.org/wiki/Fueue) + [huh?](http://esolangs.org/wiki/Huh) ``` 10 ``` In Golscript, PHP, CJam, Mathematica, bc, Pyth, ///, and TI-Basic, it outputs `10`. In R, it outputs `[1] 10` In Octave, it outputs `ans = 10` In Matlab and Scilab, it outputs `ans = 10`. In Numeric Topline, it outputs `0`. If I understand Fueue properly, it outputs a newline, then acts as a cat program. In huh?, it outputs ``` What? ? ``` [Answer] # bc, GolfScript, Homespring, huh, Octave, Scilab (0 bytes) Guaranteed to comply with rule 4. Not a winner, but would do well in the tie break. ### Output bc ``` Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. ``` GolfScript ``` ``` Homespring ``` In Homespring, the null program is not a quine. ``` huh ``` ? ``` Octave ``` GNU Octave, version 3.6.4 Copyright (C) 2013 John W. Eaton and others. This is free software; see the source code for copying conditions. There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, type `warranty'. Octave was configured for "x86_64-redhat-linux-gnu". Additional information about Octave is available at http://www.octave.org. Please contribute if you find this software useful. For more information, visit http://www.octave.org/get-involved.html Read http://www.octave.org/bugs.html to learn how to submit bug reports. For information about changes from previous versions, type `news'. ``` Scilab ``` Startup execution: loading initial environment --> ``` [Answer] > > Seems like this answer is not fully correct. > > I partially fixed it, and going to improve the other part in a few days. > > > # C++ & Javascript ## The idea is: ``` void eval(bool="main=function(){alert('Hi from Javascript!')};puts=function(){};int=0"); int main() { puts("Hi from C++!"); } ``` C++: <http://codepad.org/SK2wbIDL> Javascript: Just copy code to the browser console ## And a set of fixes to make it satisfy > > (Restriction). The removal of any single non-whitespace character from your code should cause your program to change its behaviour under every one of your languages. The program may "change" by becoming invalid for that language, or by changing the output that is produced. > > > ### From Javascript side: Changing `int`, `main` or `puts` will crash with reading of undeclared variable. But `bool` and `Hi from C++!` can be safely changes. Let's fix it: ``` puts=function(){} ``` ``` puts=function(s){s=='Hi from C++!'?bool:nope} ``` If strings are equal, it checks existance of `bool`, otherwice it crashes with undeclared `nope`. Now, there are 2 trailing semicolons that can be removed. The first is fixed esyly - just remove newline before `int`: ``` void eval(bool="main=function(){alert('Hi from Javascript!')};puts=function(){};int=0");int ``` The second is before `}`, so I need some constriction, valid in both languages and not requiring semicolon at the end in C++ or forsing a semicolon in js. Fine: ``` while(0); ``` It's impossible to omit semicolon in js as `while` needs the body. So the program at the moment is: ``` void eval(bool="main=function(){alert('Hi from Javascript!')};puts=function(s){s=='Hi from C++!'?bool:nope};int=0");int main() { puts("Hi from C++!");while(0); } ``` ### From C++ side: There are 2 problems: `eval` can have any name and all js code can be changed. *I'll try to fix them in a few days.* [Answer] # CJam + Golfscript Okay, this is somewhat boring, but it's a start. ``` 1, ``` Prints "0" in both languages. Removal of the `1` causes an error, removing the `,` prints "1" instead. The same can be done with `1)` or `1(`. There are many alternatives. (Yes, I know this isn't code-golf) [Answer] # C and C++ ``` #include <stdio.h> int main() { puts("Hello!"); return 0; } ``` C and C++ are different languages that are almost compatible with each other - contrary to what you might hear C++ is not a superset of C. Look at <http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B> for some differences. The example above is not idiomatic C++ but it does work and produces the same output in both C and C++. [Answer] ## JavaScipt, Lua, R and Python 3 - 24 bytes May work on some other languages, I'll test latter. ``` alert=print;alert(1) ``` JavaScript was tested on Firefox's console and the other languages [here](http://www.compileonline.com/execute_lua_online.php), [here](http://www.compileonline.com/execute_r_online.php) and [here](http://www.compileonline.com/execute_python3_online.php) [Answer] ## Perl + Ruby + Python I think in PHP this would need a semicolon if you are running with `-R`. ``` print "Hello World!" ``` [Answer] # Bash + sh + zsh + ksh, 4 bytes: ``` echo ``` Really simple and satisfies every rule: 1. Outputs a newline in each of the languages. 2. Output currently does *not* vary in any way between the languages. 3. Does not produce an error in any of the languages... 4. ...*except* when any of the characters are removed/changed. [Answer] # Bash + sh + zsh + ksh + Windows Batch, 4 bytes: ``` echo ``` Really simple and satisfies every rule: Outputs a newline which doesn't vary in each of the languages (but Windows Batch, which outputs `ECHO is on`, on the language you use), doesn't error, except when any letter is removed or changed. [Answer] # Every single flavor of HQ9+, 1 byte ``` 9 ``` Including but not limited to HQ9+, FishQ9+, BrainfishQ9+, CHIQRSX9+, Unified HQ9+, H9+, HQ9++,HQ9+-, FHQ9+-, HQ9F+, HQ9+B, HQ9+~, HQ9+2D, HI9+, and probably some more that I've missed. ]
[Question] [ The [PBM (Portable BitMap) format](http://en.wikipedia.org/wiki/Netpbm_format#PBM_example) is a very simple ASCII black and white bitmap format. Here's an example for the letter 'J' (copy-pasted from the wikipedia link): ``` P1 # This is an example bitmap of the letter "J" 6 10 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` It's time we build a small tool to generate files in this nifty little format! Your **goal** is to write the shortest program (in any language) that conforms to the following rules: 1. Your program takes one string from stdin (for example `CODEGOLF.STACKEXCHANGE.COM!`) 2. It generates a PBM file with a bitmapped (readable) representation of the string. 3. Each character is constructed as a 8x8 grid. 4. You must support the characters [A-Z] (all uppercase), space, a point ('.') and an exclamation mark ('!'). 5. No external libraries allowed (certainly no PBM related ones)! 6. The used character set must not simply be external to your program. Part of the challenge is storing the characters efficiently... Testing for validness of the PBM format can be done with the GIMP (or others). Do show off sample input and output! **The shortest solution will be awarded the answer points on 2012-01-31.** Have fun golfing! PS: I've added a bounty (percentage-wise a huge part of my codegolf reputation) to (hopefully) draw in more competitors. [Answer] ## Perl, 164 bytes, no zlib/gzip compression After sleeping on the problem, I managed to figure out a much shorter solution than my first one. The trick is to take advantage of a minor loophole in the rules: the characters need to fit in 8 by 8 pixels each, but nothing says they have to *fill* all that space. So I drew my own 4 by 5 pixel font, allowing me to pack two characters into 5 bytes. The output looks like this: !["HELLO WORLD!"](https://i.stack.imgur.com/RqiN6.png) (scaled x 4)     !["OH! A QUICK BROWN FOX JUMPS OVER THE LAZY DOG."](https://i.stack.imgur.com/iCvMZ.png) (original size) Before giving the actual code with the embedded font data, let me show a de-golfed version: ``` y/A-Z!./\0-\033/ for @a = <> =~ /./g; say "P4 " . 8*@a . " 8"; for $p (qw'PACKED FONT DATA') { print chr vec $p, ord, 4 for @a; } ``` In the actual code, the `PACKED FONT DATA` is replaced by a binary string consisting of eight whitespace-delimited rows (four 14-byte rows and one 13-byte one, plus three single null bytes for the blank rows). I deliberately designed my font so that the packed data contains no whitespace, single quotes or backslashes, so that it could be encoded in `qw'...'`. Since the packed font string contains unprintable characters, I've provided the actual script as a hex dump. Use `xxd -r` to turn it back into executable Perl code: ``` 0000000: 792f 412d 5a21 2e2f 002d 1b2f 666f 7240 y/A-Z!./.-./for@ 0000010: 613d 3c3e 3d7e 2f2e 2f67 3b73 6179 2250 a=<>=~/./g;say"P 0000020: 3420 222e 382a 4061 2e22 2038 223b 666f 4 ".8*@a." 8";fo 0000030: 7224 7028 7177 2700 20e6 e6ff 9612 8999 r$p(qw'. ....... 0000040: e6e6 7759 99f5 0420 9999 8898 128a df99 ..wY... ........ 0000050: 9928 5999 1504 20ef 98ee fb12 8cb9 e9e9 .(Y... ......... 0000060: 2659 6965 0420 9999 8899 928a 9989 ab21 &Yie. .........! 0000070: 599f 8220 e9e6 8f96 62f9 9986 972e 2699 Y.. ....b.....&. 0000080: f284 2000 2000 2729 7b70 7269 6e74 2063 .. . .'){print c 0000090: 6872 2076 6563 2470 2c6f 7264 2c34 666f hr vec$p,ord,4fo 00000a0: 7240 617d r@a} ``` **Here's how it works:** * The first line (in the de-golfed version) reads a single line of input, splits it into an array of characters (conveniently omitting any trailing newlines) and maps the letters `A` to `Z` and the characters `!` and `.` to the character codes 0 to 28, which normally correspond to unprintable control characters in ASCII / Unicode. (A minor side effect of this is that any tabs in the input get printed as `J`s.) The space character is left unmapped, since the output loop turns any codes above 28 into blanks anyway. * The second line just prints the PBM header. It uses the Perl 5.10 `say` feature, so you need to run this script with `perl -M5.010` for it to work. * The output loop takes a whitespace-delimited list of packed image rows and assigns each of them into `$p` in turn. (I designed the font so that the packed data wouldn't contain any whitespace or `'` characters.) It then loops over the input characters in `@a`, using Perl's `vec` command to extract the 4-bit nibble corresponding to the mapped character code from the image row, pads it to an 8-bit byte and prints it. --- ### Old answer, 268 bytes: This is a quick and dirty first attempt. I stole PleaseStand's font and compressed it along with my source code. Since the resulting script is mostly unprintable, here's a hexdump; use `xxd -r` to turn it into executable Perl code: ``` 0000000: 7573 6520 436f 6d70 7265 7373 275a 6c69 use Compress'Zli 0000010: 623b 6576 616c 2075 6e63 6f6d 7072 6573 b;eval uncompres 0000020: 7320 2778 da85 d03d 4b03 4118 85d1 452c s 'x...=K.A...E, 0000030: b69c 72cb 7519 4894 552c 2c02 3319 ee5c ..r.u.H.U,,.3..\ 0000040: d7b8 5a89 6093 4634 7e82 c490 6c91 8597 ..Z.`.F4~...l... 0000050: 80fe 7267 d660 23ae e52d 0e0f dcd6 f8c3 ..rg.`#..-...... 0000060: e9d1 5e6e ccec a15c ddb5 c5d5 495e 94a3 ..^n...\....I^.. 0000070: 83b7 c7f9 73f3 5216 f9a8 787a 5fea 666c ....s.R...xz_.fl 0000080: 9dd1 b763 dd98 76f8 2df6 0799 5811 7144 ...c..v.-...X.qD 0000090: 4acc ee9d b8b0 c90f 7e4a 8264 6016 cbd7 J.......~J.d`... 00000a0: 79f3 1b91 047c 4055 409e 9e54 1dda ed41 y....|@[[email protected]](/cdn-cgi/l/email-protection) 00000b0: 9a20 8080 6adc 5c47 8488 7495 f621 01d7 . ..j.\G..t..!.. 00000c0: 6b6c 902e b6c8 2a6a 6643 f56f e99c 115d kl....*jfC.o...] 00000d0: 5c7a f1b2 13d0 3453 790f da74 c813 751d \z....4Sy..t..u. 00000e0: 11ce d821 ad90 247f 2292 5b54 c14f 3c4e ...!..$.".[T.O<N 00000f0: 49c5 4c53 a1a7 c478 391c 714c f113 0747 I.LS...x9.qL...G 0000100: ab6c 4482 9fd2 177a 5677 6327 .lD....zVwc' ``` The decompressed Perl code consists of the following preamble: ``` y;A-Z.! ;;cd,say"P4 ",8*length," 8"for$t=<> ``` followed by eight repetitions of the following code: ``` ;$_=$t;y(A-Z.! )'BITMAP DATA HERE';print ``` with `BITMAP DATA HERE` replaced with 29 bytes encoding one row of the font. [Answer] ## GolfScript, 133 bytes This is based on [my 164-byte Perl solution](https://codegolf.stackexchange.com/a/4682/3191) and uses the same nibble-packed 4 by 5 pixel font. Again, I'll give the readable version first: ``` {91,65>"!. "+?}%:s"P4"\,8*8'FONT DATA HERE'{16base}%[3]/{:p;{[p=0]0=}s%}%]n* ``` Here, `FONT DATA HERE` stands for 71 bytes of binary packed font data. The encoding is slightly different than in the Perl version: instead of splitting the packed string on whitespace, I expand it first and then split it on the nibble `3` (chosen because it just happens not to occur anywhere in the font). Since the font data in the actual script contains unprintable characters, I give it as a hex dump below. Use `xxd -r` to turn the hex dump back into executable GolfScript code: ``` 0000000: 7b39 312c 3635 3e22 212e 2022 2b3f 7d25 {91,65>"!. "+?}% 0000010: 3a73 2250 3422 5c2c 382a 3827 36e6 eff6 :s"P4"\,8*8'6... 0000020: 9219 8996 e6e7 7959 95f4 3999 9888 921a ......yY..9..... 0000030: 8fd9 9998 2959 9514 3fe8 9eeb f21c 89b9 ....)Y..?....... 0000040: e9e6 2959 6564 3999 9889 929a 8999 8ba1 ..)Yed9......... 0000050: 295f 9283 9e6e f869 269f 9968 79e2 6299 )_...n.i&..hy.b. 0000060: 2f48 3327 7b31 3662 6173 657d 255b 335d /H3'{16base}%[3] 0000070: 2f7b 3a70 3b7b 5b70 3d30 5d30 3d7d 7325 /{:p;{[p=0]0=}s% 0000080: 7d25 5d6e 2a }%]n* ``` Unlike the Perl script, this code prints any characters outside the set `A`–`Z`, `!`, `.`, `space` as funny-looking little squiggles. Replacing the squiggles with blanks would cost 2 extra chars; removing them entirely would cost 4. This is my first GolfScript program ever, so I wouldn't be surprised if there's some room left for optimization. Here's how it works: * `{91,65>"!. "+?}%:s` maps the valid input characters (`A`–`Z`, `!`, `.`, `space`) to the numbers 0 – 28 and assigns the result to `s`. Any characters outside the valid set get mapped to -1, which is what produces the squiggles when printed. * `"P4"\,8*8` pushes the values "P4", 8 times the length of the input, and 8 onto the stack. When printed at the end, these will form the PBM header. * `{16base}%[3]/` takes the preceding string of font data, splits each byte of it into two nibbles, and splits the result into blocks delimited by the value `3`. `{:p;{[p=0]0=}s%}%` then loops over these blocks, first assigning each block to the variable `p` and then looping over the remapped input string `s`, replacing each character with the value at the corresponding offset in `p`. The funny-looking construct `[p=0]0=` does the same as `p=`, except that it returns 0 for any offsets past the end of `p`; I don't really like it, but I haven't been able to figure out any shorter way to handle that. * Finally, `]n*` takes everything on the stack (the three header values and the image data array) and joins them together with newlines for printing. [Answer] **8086 Machine Code** 190 Bytes (122 Bytes using BIOS) Here's Base64 encoded WinXP/MSDos .COM file: ``` M8COwCaKDoUEitEmxD4MAaCAAP7IfliK8MHgA7cK9ve9egEAZ vy0APb3AUb6iMi0APb3AUb+x0YACg2DxQK+ggCK7qz24YvYJo ohswjQ5LAwFACIRgBF/st18v7NdeRH/sp10sZGACS6cAG0Cc0 hw1AxCg0wMDAgMDA= ``` (Use something [like this](http://www.opinionatedgeek.com/DotNet/Tools/Base64Decode/default.aspx)) to decode the text and save as "pbm.com". Then, at the command prompt, type: > > pbm text to encode>outputfilename.pbm > > > I've tested this on my WinXP machine using both the standard command prompt and DosBox V0.74. **UPDATE** This version is 190 bytes and uses Ilmari Karonen's tiny font (no bios access here!):- ``` voAArf7Iflq7YwG/vgG6Cg20Bfbk9vIAZfsy5PbyAUX5Vqw48HQoLEFzCDQG/sAMGSQfM8 nQ6NfA0QPS6IjEsQSwJtDsENCq4vewMKrr04DDEF6A+7N1ycYFJLqzAbQJzSHDdnb/loIZ mXZ2flmZ9QAAIJmZEZGCFb+ZmSFZmYUPDy9/kXf9ghPZeXkmWWllAAAgmZkRmZIVmRldKF mfEgAAAHl2H5Zi+ZkWnicmmfIAICBQMQoNMDAwIDUKDQ== ``` [Answer] ## Shell script (code+data = 295 chars) I hope tail, gzip, and dd do not count as "external libraries." Run as `echo -n 'YOUR TEXT HERE' | ./text.sh > out.pbm`. The font I used is Small Fonts size 7.5, although I did have to clip the descender off the Q. ### Example output ![THE QUICK BROWN FOX JUMPS OVER LAZY DOGS. REALLY!](https://i.stack.imgur.com/sCzcn.png) ### Code (137 chars) ``` i=`od -tu1|cut -c9-` echo P4 for a in {0..7} do for b in $i do tail -2 $0|zcat|dd bs=1 count=1 skip=$((8*b+a)) done done>8 wc -c 8 cat 8 ``` ### Complete script (use `xxd -r` to recreate original file) ``` 0000000: 693d 606f 6420 2d74 7531 7c63 7574 202d i=`od -tu1|cut - 0000010: 6339 2d60 0a65 6368 6f20 5034 0a66 6f72 c9-`.echo P4.for 0000020: 2061 2069 6e20 7b30 2e2e 377d 0a64 6f20 a in {0..7}.do 0000030: 666f 7220 6220 696e 2024 690a 646f 2074 for b in $i.do t 0000040: 6169 6c20 2d32 2024 307c 7a63 6174 7c64 ail -2 $0|zcat|d 0000050: 6420 6273 3d31 2063 6f75 6e74 3d31 2073 d bs=1 count=1 s 0000060: 6b69 703d 2428 2838 2a62 2b61 2929 0a64 kip=$((8*b+a)).d 0000070: 6f6e 650a 646f 6e65 3e38 0a77 6320 2d63 one.done>8.wc -c 0000080: 2038 0a63 6174 2038 0a1f 8b08 0000 0000 8.cat 8........ 0000090: 0000 ffed cdb1 0a83 3014 8561 910e 8e8e ........0..a.... 00000a0: 193b dca1 631f 2084 9353 6ba3 a3e0 e2a8 .;..c. ..Sk..... 00000b0: 2fe0 d8e1 22d8 276f 9a50 e813 940e fdb8 /...".'o.P...... 00000c0: 70f9 a753 247f 7829 f0b5 b9e2 c718 2322 p..S$.x)......#" 00000d0: 1ba9 e9a8 9688 6895 892a 7007 f0fe 701e ......h..*p...p. 00000e0: b879 ef48 6e8c aa4f 219c d984 750d 0d91 .y.Hn..O!...u... 00000f0: e9b2 8c63 d779 3fcf c3d0 f76d eb7c e2d2 ...c.y?....m.|.. 0000100: 1880 d4d7 4b6e 9296 b065 49ab 75c6 cc92 ....Kn...eI.u... 0000110: 1411 63f6 7de7 3489 9031 847c 3c9a 531d ..c.}.4..1.|<.S. 0000120: e9a1 aa8f 803e 01 .....>. ``` ### Explanation * `od` is the standard "octal dump" utility program. The `-tu1` option tells it to produce a decimal dump of individual bytes instead (a sufficient workaround for bash's lack of asc(), ord(), .charCodeAt(), etc.) * `P4` is the magic number for a binary format PBM file, which packs eight pixels into each byte (versus `P1` for the ASCII format PBM file). You will see how this proves useful. * Per row of final output, the program pulls an eight-pixel byte (corresponding to the ASCII code and line number) from the gzip-compressed data section at the end using `dd`. (`tail -2 $0` extracts the script's last two lines; the compressed data includes one 0x0a linefeed byte.) It so happens that eight pixels is the width of a single character. The null bytes that fill the gaps between supported characters are easily compressible because they are all the same. * All this is written to a file named "8". Because there are exactly eight rows (and also eight pixels per byte), the number of bytes is the width of the output in pixels. The output's height is also included in that `wc -c` prints the input filename "8" after its byte count. * Now that the header is complete, the image data is printed. Bash only notices that the last two lines are not valid commands (the last one actually invalid UTF-8) after it has executed everything coming before. * I used KZIP only to compress the data section, [as Ilmari Karonen did](https://codegolf.stackexchange.com/a/4196/163) for an *entire submission* to the 12 Days of Christmas challenge. As described there, it is essentially necessary to use a hex editor to replace the ZIP header format with a gzip header. Including the CRC-32 and file size from the original ZIP header seems to be unnecessary. [Answer] # Python 2, ~~248~~ 247 bytes ``` s=raw_input();k=len(s);print"P1",k*8,8 for i in range(k*24):a=s[i/3%k];j=max(".!".find(a)+1,ord(a)-62)*3;print int("00080084IMVAENBSIFERBSUF4UFQQEMVDT4NAP4MNDSI9MRTMRBARA4NBQRAMNBE4E94NURDARDNRDMLD95DSL7"[j:j+3],32)>>(i/3/k*3+i%3)&1," 0"*(i%3/2*5) ``` Uses a 3x5 font, packed into a printable string, 3 bytes per character. The font is clearly legible, although the n is lowercase and the v might be mistaken for a u if it isn't seen in context. Actual Size: [![actual size](https://i.stack.imgur.com/n74EH.png)](https://i.stack.imgur.com/n74EH.png) Zoomed x3: [![zoomed x3](https://i.stack.imgur.com/kS94M.png)](https://i.stack.imgur.com/kS94M.png) The output is a P1 type PBM, as per the example in the challenge. It was a fun challenge. [Answer] ## Ruby 1.9, 346 bytes (122 code + 224 bytes data) Here is the result: ![CODEGOLF](https://i.stack.imgur.com/PwRVf.png) (It's nice, isn't it?) ``` z=0..7;puts"P1\n#{(s=gets).size*8} 8",z.map{|i|s.bytes.flat_map{|o|z.map{|j|'DATA'.unpack('Q<*')[o>64?o-63:o/46][i*8+j]}}*' '} ``` The font was generated by `figlet -f banner -w 1000 $LETTERS` and [this script](https://gist.github.com/3cda65f5513ee48774f9). Run with `echo -n 'CODEGOLF.STACKEXCHANGE.COM!' | ruby script.rb > image.pbm`. The script generate all the rows and simply print them. Here is an hexdump (use `xxd -r`): ``` 0000000: 7a3d 302e 2e37 3b70 7574 7322 5031 5c6e z=0..7;puts"P1\n 0000010: 237b 2873 3d67 6574 7329 2e73 697a 652a #{(s=gets).size* 0000020: 387d 2038 222c 7a2e 6d61 707b 7c69 7c73 8} 8",z.map{|i|s 0000030: 2e62 7974 6573 2e66 6c61 745f 6d61 707b .bytes.flat_map{ 0000040: 7c6f 7c7a 2e6d 6170 7b7c 6a7c 271c 1c1c |o|z.map{|j|'... 0000050: 0800 1c1c 0000 0000 001c 1c1c 0008 1422 ..............." 0000060: 417f 4141 003f 4141 3f41 413f 003e 4101 A.AA.?AA?AA?.>A. 0000070: 0101 413e 003f 4141 4141 413f 007f 0101 ..A>.?AAAAA?.... 0000080: 1f01 017f 007f 0101 1f01 0101 003e 4101 .............>A. 0000090: 7941 413e 0041 4141 7f41 4141 001c 0808 yAA>.AAA.AAA.... 00000a0: 0808 081c 0040 4040 4041 413e 0042 2212 .....@@@@AA>.B". 00000b0: 0e12 2242 0001 0101 0101 017f 0041 6355 .."B.........AcU 00000c0: 4941 4141 0041 4345 4951 6141 007f 4141 IAAA.ACEIQaA..AA 00000d0: 4141 417f 003f 4141 3f01 0101 003e 4141 AAA..?AA?....>AA 00000e0: 4151 215e 003f 4141 3f11 2141 003e 4101 AQ!^.?AA?.!A.>A. 00000f0: 3e40 413e 007f 0808 0808 0808 0041 4141 >@A>.........AAA 0000100: 4141 413e 0041 4141 4122 1408 0041 4949 AAA>.AAAA"...AII 0000110: 4949 4936 0041 2214 0814 2241 0041 2214 III6.A"..."A.A". 0000120: 0808 0808 007f 2010 0804 027f 0027 2e75 ...... ......'.u 0000130: 6e70 6163 6b28 2751 3c2a 2729 5b6f 3e36 npack('Q<*')[o>6 0000140: 343f 6f2d 3633 3a6f 2f34 365d 5b69 2a38 4?o-63:o/46][i*8 0000150: 2b6a 5d7d 7d2a 2720 277d +j]}}*' '} ``` It takes 93 bytes of code when using goruby: ``` ps"P1\n#{(s=gt).sz*8} 8",8.mp{|i|s.y.fl{|o|8.mp{|j|'DATA'.ua('Q<*')[o>64?o-63:o/46][i*8+j]}}*' '} ``` Using ZLib trim the data size to 142 bytes instead of 224, but adds 43 bytes in the code, so 307 bytes: ``` #coding:binary require'zlib';z=0..7;puts"P1\n#{(s=gets).size*8} 8",z.map{|i|s.bytes.flat_map{|o|z.map{|j|Zlib.inflate("DATA").unpack('Q<*')[o>64?o-63:o/46][i*8+j]}}*' '} ``` Which gives a total of 268 when using goruby: ``` #coding:binary rq'zlib';ps"P1\n#{(s=gt).sz*8} 8",8.mp{|i|s.y.fl{|o|8.mp{|j|Zlib.if("DATA").ua('Q<*')[o>64?o-63:o/46][i*8+j]}}*' '} ``` [Answer] ### Java 862 826: Here is a different approach. I think 'awt' does not count as external lib. ``` import java.awt.*; class B extends Frame{String s="ABCDEFGHIJKLMNOPQRSTUVWXYZ .!";int l=29;static Robot r;int[][][]m=new int[l][8][8]; public void paint(Graphics g){for(int y=0;y<8;++y){int py=(y<3)?y:y+1;for(int a=0;a<l;++a) for(int x=0;x<8;++x) m[a][x][y]=(r.getPixelColor(8*a+x+17+x/4,py+81)).getRGB()<-1?1:0;} System.out.println("P1\n"+(getTitle().length()*8)+" 8"); for(int y=0;y<8;++y){for(char c:getTitle().toCharArray()){int a=s.indexOf(c); for(int x=0;x<8;++x)System.out.print(m[a][x][y]);} System.out.println();} System.exit(0);} public B(String p){super(p); setBackground(Color.WHITE); setSize(400,60); Label l=new Label(s); l.setFont(new Font("Monospaced",Font.PLAIN,13)); add(l); setLocation(9,49); setVisible(true);} public static void main(String a[])throws Exception{r=new Robot(); new B(a[0]);}} ``` And ungolfed: ``` import java.awt.*; class PBM extends Frame { String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ .!"; int l=29; Robot robot; int[][][] map = new int[l][8][8]; static boolean init = false; public void paint (Graphics g) { for (int y = 0; y < 8; ++y) { int py = (y < 3) ? y : y +1; for (int a = 0; a < l; ++a) { for (int x = 0; x < 8; ++x) { map[a][x][y] = (robot.getPixelColor (8*a+x+17+x/4, py+81)).getRGB () < -1 ? 1 : 0; } } } System.out.println("P1\n"+(getTitle().length()*8)+" 8"); for (int y = 0; y < 8; ++y) { for (char c : getTitle ().toCharArray ()) { int a = s.indexOf (c); for (int x = 0; x < 8; ++x) { System.out.print (map[a][x][y]); } } System.out.println (); } System.exit (0); } public PBM (String p) throws Exception { super (p); robot = new Robot (); setBackground (Color.WHITE); setSize (400, 60); Label l=new Label(s); l.setFont (new Font ("Monospaced", Font.PLAIN, 13)); add(l); setLocation (9,49); setVisible (true); } public static void main (String args[]) throws Exception { new PBM (args[0]); } } ``` Robot is the somehow curious way of Java to call getPixel. I create a Label with the alphabet, and measure where a pixel is for each letter. In the paint method, `int py = (y < 3) ? y : y +1;` and `(8*a+x+17+x/4, py+81)` is the complicated way, to adjust the position in the font. Huuuh! else it would need 9 lines, and every 4th letter, there is an additional pixel horizontally. Trial and error brought me to this solution. Then the header of the PBM is written, and each line of the message. The message is passed as title of the frame. That's it. Not the shortest code, but no manual font painting was necessary. Maybe it could be shorter in BeanShell or Scala. And now - how does it look like? ``` java B "JAVA.CAFE BABE" > jcb.pbm ``` Multiple zooms applied: ![java.cafe babe PNG](https://i.stack.imgur.com/jNMZb.png) Unzoomed: ![java.cafe babe JPG](https://i.stack.imgur.com/ImOuk.jpg) Not that the number of chars is the number of chars from the Perl solution shuffled. (golfed a little bit more. Made Robot static, which avoids one Exception declaration.) [Answer] # C++ TOO LARGE TO WIN I wrote a full featured PPM drawing program in C++, with my own bitmapped font. Even stripping out all non necessary functions it's still huge compared to the answers here because of the definition for the font. Anyway, here is the output for HELLO WORLD: ![enter image description here](https://i.stack.imgur.com/znr8Z.png) And the code: ## ppmdraw.h ``` #ifndef PPMDRAW_H #define PPMDRAW_H #include <fstream> #include <sstream> #include <map> #include <bitset> #include <vector> struct pixel{ unsigned char r; unsigned char g; unsigned char b; bool equals(pixel p){ return (r == p.r && g == p.g && b == p.b); } }; class PPMDraw { public: PPMDraw(int w, int h); virtual ~PPMDraw(); void fill(unsigned char r, unsigned char g, unsigned char b); void set_color(unsigned char r, unsigned char g, unsigned char b); void draw_point(int x, int y); void draw_char(int x, int y, char c); void draw_string(int x, int y, std::string text); bool save(std::string file); private: int width; int height; pixel * image; std::vector<bool> checked; unsigned char red; unsigned char green; unsigned char blue; void init_alpha(); std::map<char, std::bitset<48> > font; }; #endif // PPMDRAW_H ``` ## ppmdraw.cpp ``` #include "PPMDraw.h" #include <fstream> #include <iostream> #include <sstream> #include <cstdlib> #include <cmath> #include <map> #include <bitset> #include <vector> // standard constructor PPMDraw::PPMDraw(int w, int h){ width = w; height = h; // make an array to hold all the pixels, r, g, b for each image = new pixel[width * height]; // a bitset to use for functions that have to check which pixels have been worked on checked = std::vector<bool>(); for(int i = 0; i < width * height; i++){ checked.push_back(false); } init_alpha(); } PPMDraw::~PPMDraw(){ if(image != nullptr){ delete[] image; } } void PPMDraw::fill(unsigned char r, unsigned char g, unsigned char b){ for(int i = 0; i < width * height; i++){ image[i + 0] = pixel{r, g, b}; } } void PPMDraw::set_color(unsigned char r, unsigned char g, unsigned char b){ red = r; green = g; blue = b; } void PPMDraw::draw_point(int x, int y){ if(x >= 0 && x < width && y >= 0 && y < height){ image[y * width + x] = pixel{red, green, blue}; } } void PPMDraw::draw_char(int x, int y, char c){ std::bitset<48> letter = font[c]; int n = 47; for(int i = 0; i < 6; i++){ for(int j = 0; j < 8; j++){ if(letter[n]){ draw_point(x + i, y + j); } n--; } } } void PPMDraw::draw_string(int x, int y, std::string text){ for(unsigned int i = 0; i < text.length(); i++){ draw_char(x + 6 * i, y, text[i]); } } bool PPMDraw::save(std::string file){ std::ofstream save(file.c_str(), std::ios_base::out | std::ios_base::binary); if(save.is_open()){ save << "P6" << std::endl; save << width << " " << height << std::endl; save << "255" << std::endl; unsigned char * temp = new unsigned char[height * width * 3]; for(int i = 0; i < height * width; i++){ temp[i * 3 + 0] = image[i].r; temp[i * 3 + 1] = image[i].g; temp[i * 3 + 2] = image[i].b; } save.write(reinterpret_cast<const char *> (temp), height*width*3*sizeof(unsigned char)); delete temp; save.close(); return true; }else{ return false; } } void PPMDraw::init_alpha(){ // Define a simple font for drawing text font[' '] = std::bitset<48> (std::string("000000000000000000000000000000000000000000000000")); font['!'] = std::bitset<48> (std::string("000000000000000011110110000000000000000000000000")); font['"'] = std::bitset<48> (std::string("000000001100000000000000110000000000000000000000")); font['#'] = std::bitset<48> (std::string("001010001111111000101000111111100010100000000000")); font['$'] = std::bitset<48> (std::string("001001000101010011111110010101000100100000000000")); font['%'] = std::bitset<48> (std::string("000000100100110000010000011000001000010000000000")); font['&'] = std::bitset<48> (std::string("000111001110001010110010110011000000001000000000")); font['\\'] = std::bitset<48> (std::string("100000000110000000010000000011000000001000000000")); font['('] = std::bitset<48> (std::string("000000000000000001111100100000100000000000000000")); font[')'] = std::bitset<48> (std::string("000000001000001001111100000000000000000000000000")); font['*'] = std::bitset<48> (std::string("010010000011000011100000001100000100100000000000")); font['+'] = std::bitset<48> (std::string("000100000001000001111100000100000001000000000000")); font[','] = std::bitset<48> (std::string("000000000000000000000110000000000000000000000000")); font['-'] = std::bitset<48> (std::string("000100000001000000010000000100000001000000000000")); font['.'] = std::bitset<48> (std::string("000000000000000000000100000000000000000000000000")); font['/'] = std::bitset<48> (std::string("000000100000110000010000011000001000000000000000")); font['0'] = std::bitset<48> (std::string("011111001000001010000010100000100111110000000000")); font['1'] = std::bitset<48> (std::string("000000001000001011111110000000100000000000000000")); font['2'] = std::bitset<48> (std::string("010011101001001010010010100100100111001000000000")); font['3'] = std::bitset<48> (std::string("010001001000001010000010100100100110110000000000")); font['4'] = std::bitset<48> (std::string("111100000001000000010000000100001111111000000000")); font['5'] = std::bitset<48> (std::string("111001001001001010010010100100101001110000000000")); font['6'] = std::bitset<48> (std::string("011111001001001010010010100100101000110000000000")); font['7'] = std::bitset<48> (std::string("100000001000000010000110100110001110000000000000")); font['8'] = std::bitset<48> (std::string("011011001001001010010010100100100110110000000000")); font['9'] = std::bitset<48> (std::string("011000001001000010010000100100000111111000000000")); font[':'] = std::bitset<48> (std::string("000000000000000001000100000000000000000000000000")); font[';'] = std::bitset<48> (std::string("000000000000000001000110000000000000000000000000")); font['<'] = std::bitset<48> (std::string("000000000001000000101000010001000000000000000000")); font['='] = std::bitset<48> (std::string("001010000010100000101000001010000000000000000000")); font['>'] = std::bitset<48> (std::string("000000000100010000101000000100000000000000000000")); font['?'] = std::bitset<48> (std::string("010000001000000010001010100100000110000000000000")); font['@'] = std::bitset<48> (std::string("011111001000001010111010101010100111001000000000")); font['A'] = std::bitset<48> (std::string("011111101001000010010000100100000111111000000000")); font['B'] = std::bitset<48> (std::string("111111101001001010010010100100100110110000000000")); font['C'] = std::bitset<48> (std::string("011111001000001010000010100000100100010000000000")); font['D'] = std::bitset<48> (std::string("111111101000001010000010100000100111110000000000")); font['E'] = std::bitset<48> (std::string("111111101001001010010010100100101000001000000000")); font['F'] = std::bitset<48> (std::string("111111101001000010010000100100001000000000000000")); font['G'] = std::bitset<48> (std::string("011111001000001010000010100010100100110000000000")); font['H'] = std::bitset<48> (std::string("111111100001000000010000000100001111111000000000")); font['I'] = std::bitset<48> (std::string("100000101000001011111110100000101000001000000000")); font['J'] = std::bitset<48> (std::string("000011000000001000000010000000101111110000000000")); font['K'] = std::bitset<48> (std::string("111111100001000000010000001010001100011000000000")); font['L'] = std::bitset<48> (std::string("111111100000001000000010000000100000001000000000")); font['M'] = std::bitset<48> (std::string("111111101000000001100000100000001111111000000000")); font['N'] = std::bitset<48> (std::string("111111100100000000100000000100001111111000000000")); font['O'] = std::bitset<48> (std::string("011111001000001010000010100000100111110000000000")); font['P'] = std::bitset<48> (std::string("111111101001000010010000100100001111000000000000")); font['Q'] = std::bitset<48> (std::string("011111001000001010001010100001000111101000000000")); font['R'] = std::bitset<48> (std::string("111111101001000010010000100110001111011000000000")); font['S'] = std::bitset<48> (std::string("011000101001001010010010100100101000110000000000")); font['T'] = std::bitset<48> (std::string("100000001000000011111110100000001000000000000000")); font['U'] = std::bitset<48> (std::string("111111000000001000000010000000101111110000000000")); font['V'] = std::bitset<48> (std::string("111110000000010000000010000001001111100000000000")); font['W'] = std::bitset<48> (std::string("111111100000001000001100000000101111111000000000")); font['X'] = std::bitset<48> (std::string("110001100010100000010000001010001100011000000000")); font['Y'] = std::bitset<48> (std::string("110000000010000000011110001000001100000000000000")); font['Z'] = std::bitset<48> (std::string("100001101000101010010010101000101100001000000000")); font['['] = std::bitset<48> (std::string("000000001111111010000010100000100000000000000000")); font['\''] = std::bitset<48> (std::string("100000000110000000010000000011000000001000000000")); font[']'] = std::bitset<48> (std::string("000000001000001010000010111111100000000000000000")); font['^'] = std::bitset<48> (std::string("001000000100000010000000010000000010000000000000")); font['_'] = std::bitset<48> (std::string("000000100000001000000010000000100000001000000000")); font['`'] = std::bitset<48> (std::string("000000001000000001000000000000000000000000000000")); font['a'] = std::bitset<48> (std::string("000001000010101000101010001010100001111000000000")); font['b'] = std::bitset<48> (std::string("111111100001001000010010000100100000110000000000")); font['c'] = std::bitset<48> (std::string("000111000010001000100010001000100001010000000000")); font['d'] = std::bitset<48> (std::string("000011000001001000010010000100101111111000000000")); font['e'] = std::bitset<48> (std::string("000111000010101000101010001010100001101000000000")); font['f'] = std::bitset<48> (std::string("000100000111111010010000100100000000000000000000")); font['g'] = std::bitset<48> (std::string("001100100100100101001001010010010011111000000000")); font['h'] = std::bitset<48> (std::string("111111100001000000010000000100000000111000000000")); font['i'] = std::bitset<48> (std::string("000000000000000001011110000000000000000000000000")); font['j'] = std::bitset<48> (std::string("000000100000000100000001010111100000000000000000")); font['k'] = std::bitset<48> (std::string("111111100000100000010100001000100000000000000000")); font['l'] = std::bitset<48> (std::string("000000000000000011111110000000000000000000000000")); font['m'] = std::bitset<48> (std::string("000111100001000000001000000100000001111000000000")); font['n'] = std::bitset<48> (std::string("001111100001000000010000000100000001111000000000")); font['o'] = std::bitset<48> (std::string("000111000010001000100010001000100001110000000000")); font['p'] = std::bitset<48> (std::string("001111110010010000100100001001000001100000000000")); font['q'] = std::bitset<48> (std::string("000110000010010000100100001001000011111100000000")); font['r'] = std::bitset<48> (std::string("000000000011111000010000000100000000000000000000")); font['s'] = std::bitset<48> (std::string("000000000001001000101010001010100010010000000000")); font['t'] = std::bitset<48> (std::string("000000000010000011111110001000000000000000000000")); font['u'] = std::bitset<48> (std::string("000111000000001000000010000000100001110000000000")); font['v'] = std::bitset<48> (std::string("000110000000010000000010000001000001100000000000")); font['w'] = std::bitset<48> (std::string("000111100000001000000100000000100001111000000000")); font['x'] = std::bitset<48> (std::string("001000100001010000001000000101000010001000000000")); font['y'] = std::bitset<48> (std::string("001100000000100000000111000010000011000000000000")); font['z'] = std::bitset<48> (std::string("010001100100101001010010011000100000000000000000")); font['{'] = std::bitset<48> (std::string("000000000000000001101100100100100000000000000000")); font['|'] = std::bitset<48> (std::string("000000000000000011111110000000000000000000000000")); font['}'] = std::bitset<48> (std::string("000000000000000010010010011011000000000000000000")); font['~'] = std::bitset<48> (std::string("000100000010000000010000000010000001000000000000")); } ``` ## main.cpp ``` #include "PPMDraw.h" #include <iostream> int main(){ // ask for input std::string input; std::cout << "ENTER YOUR TEXT" << std::endl; getline(std::cin, input); // get size for image int width = input.size() * 6; PPMDraw image = PPMDraw(width, 8); image.fill(255, 255, 255); image.set_color(0, 0, 0); image.draw_string(0, 0, input); image.save("text.ppm"); } ``` ## Makefile ``` CC = g++ CFLAGS = -Wall -c -std=c++11 LFLAGS = -Wall OBJS = main.o PPMDraw.o list: $(OBJS) $(CC) $(LFLAGS) $(OBJS) -o text2ppm main.o: PPMDraw.h $(CC) $(CFLAGS) main.cpp PPMDraw.o: PPMDraw.h $(CC) $(CFLAGS) PPMDraw.cpp clean: rm *.o main ``` If you're interested, the full PPMDraw library is [here](http://myweb.uiowa.edu/stcrowle/Files/PPMDraw.zip): [Answer] # SmileBASIC, 231 bytes ``` LINPUT C$?"P1 ?8,LEN(C$)*8WHILE""<C$A=ASC(SHIFT(C$))D=ASC("*N.JZ`;O:²ÞøäüÄho"[A-65+12*(A<34)+47*(A<47)])FOR I=0TO 4B$=BIN$(VAL("7535712074617252"[D>>5<<1OR 1AND D>>I]),8)WHILE""<B$?POP(B$), WEND?NEXT?"0 "*24WEND ``` [![enter image description here](https://i.stack.imgur.com/9uQCx.png)](https://i.stack.imgur.com/9uQCx.png) Each character contains only 2 different row patterns, chosen from a "palette" of 8 combinations. The data for each symbol is stored in 1 byte, with the palette stored separately. ]
[Question] [ There are many challenges that say "interpret X", where X is a simple language. In my opinion, that is way too boring. To give all the procrastinating people on the internet something interesting to do, you can try to do this challenge: ## Challenge Choose a language `$LANG`. `$LANG` can be any turing complete programming language or a turing complete subset of a programming language. Beware that if you omit a feature of your language in `$LANG` for interpretation, you must not use it for your own program, too, since your submission must be written in `$LANG`, too. Write a compiler / interpreter for `$LANG` written in `$LANG`. You may use all facilities (including `eval` and friends) of your language that are available to write this compiler. To make the task more challenging, there is one restriction: You program should be able to interpret / compile all valid programs of `$LANG` except your interpreter / compiler itself. If it occurs that the program to be interpreted / compiled is your interpreter or compiler itself (regardless of the filename), your program should do something completely unrelated to the functionality of an interpreter or compiler (such as barfing or printing `Hello, world!`). To make this task even more complex, your program must not read its own source when compiling or interpreting. ## Specifications * This task is code golf. The submission with the least characters that is correct wins. In case of a tie, the solution that was submitted first wins. * Your program / script should read the program to be interpreted from a file. You may hardcode its path and name. When the file is read, you may either compile the file to another file (That must be executable on your system) or run it directly. If `$LANG` lacks file-reading capabilities, you can choose another way to read in the code that fits `$LANG`. You may not choose `$LANG` as a subset of another language but with file-reading capabilites removed. * Usual code-golf rules apply. That is: your personal pet-language that you made up just to solve this challenge is forbidden, if the solution becomes trivial using it (Such as defining a single-char program that exactly implements the solution). Abuse of rules is encouraged. [Answer] ### Perl, 89 chars, no cheating ``` $_=q($_=q(Q);s/Q/$_/;($q=join"",<>)eq$_?die:eval$q);s/Q/$_/;($q=join"",<>)eq$_?die:eval$q ``` Note that this code is *extremely* picky about what counts as "itself". In particular, it will not recognize itself if there are any trailing newlines or other extra whitespace in the input. To test it, save it into a file named (for example) `unquine.pl` and do this: ``` $ perl unquine.pl unquine.pl Died at unquine.pl line 1, <> line 1. ``` Remember, the `unquine.pl` file should be *exactly* 89 bytes long, no more, no less. Running it with some other Perl script as input just executes the other script, as it should: ``` $ perl unquine.pl hello.pl Hello, world! ``` As the name might suggest, the implementation is based on a quine — specifically, this one: ``` $_=q($_=q(Q);s/Q/$_/);s/Q/$_/ ``` This code sets `$_` equal to itself; the rest of the program (which, of course, must be duplicated inside `$_`) just compares `$_` to the input, dies if they match and evaluates the input otherwise. [Answer] ## Ruby, 63 ``` b=$<.read t="b=$<.read\nt=%p\nb!=t%%t&&eval(b)" b!=t%t&&eval(b) ``` [Answer] # GolfScript, 30 chars ``` {`".~"+"#{$<.read}".@=!{~}*}.~ ``` This program reads the contents of a file named on the command line and, if it does not exactly equal the code above, interprets it as GolfScript. If the input is exactly equal to the code above, it will simply be printed unchanged (except for a newline appended to the end). This is a fairly straightforward adaptation of [this self-identifying program](https://codegolf.stackexchange.com/questions/11370/write-the-shortest-self-identifying-program-a-quine-variant/18235#18235). Specifically: * `{ }` is a code block literal in GolfScript. * `.~`, applied to a code block, duplicates the block and executes the copy. Inside the code block: * ``` stringifies the copy of the code block. * `".~"+` appends the characters `.~` to it, yielding a string containing the source code of the program. * `"#{$<.read}"` is a [documented hack](http://www.golfscript.com/golfscript/syntax.html) that allow the execution of Ruby code within GolfScript. In this case, it executes the Ruby statement `$<.read` (shamelessly stolen from [Lowjacker's Ruby solution](https://codegolf.stackexchange.com/a/4169)), which reads and returns the contents of any files specified on the command line. This hack is needed because GolfScript itself provides no explicit file I/O capabilities. * `.@` duplicates and shuffles the elements on top of the stack so that the stack contains two copies of the file contents followed by the source code of this program. * `=!` compares the top two items on the stack (i.e. the file contents and the source), returning 1 if they are different and 0 if they are the same. * `{~}*` evaluates the remaining copy of the file contents as GolfScript code, but only if the result of the comparison is 1. (Technically, it executes the code block `{~}` as many times as given by the number on the stack, i.e. 0 or 1 times. Inside the block, `~` is the GolfScript eval operator.) **Ps.** If reading the code to execute from stdin is allowed, this challenge can be solved in **21 characters** without having to shell out to Ruby: ``` {`".~"+1$=!{""\~}*}.~ ``` This program will read an input string from stdin and, if it does not match its own source, executes it (with an empty input). Like the program above, input that does match the source is simply echoed back. [Answer] # Python, 167 130 118 bytes This is my first attempt at golfing, so here goes! It interprets any program except itself Improved version: ``` i=open(raw_input()).read();q='i=open(raw_input()).read();q=%s;i==q%%repr(q)and a;exec(i)\n';i==q%repr(q)and a;exec(i) ``` If it gets itself then it barfs with: ``` Traceback (most recent call last): File "pygolf.py", line 1, in <module> i=open(raw_input()).read();q='i=open(raw_input()).read();q=%s;i==q%%repr(q)and a;exec(i)\n';i==q%repr(q)and a;exec(i) NameError: name 'a' is not defined ``` I think this solution works pretty much the same way as Ilmari Karonen's, the basic idea is something like: ``` input = read_some_file() if input == some_quine() barf() interpret(input) ``` The quine I used was based on this one: ``` (lambda x: x + repr((x,)))('(lambda x: x + repr((x,)))',) ``` But I since realized a much shorter quine is: ``` q='q=%s;q%%repr(q)';q%repr(q) ``` And that can be even shorter if you allow the interactive python shell, in which case you can do: ``` '%s;_%%repr(_)';_%repr(_) ``` Since python doesn't have a short way to get command line args, I went with raw\_input() (which is still pretty long, but not as long as ``` import sys;sys.argv[1] ``` Usage is: ``` echo "foobar.py" | python quinterpretter.py ``` or ``` python quinterpretter.py <type filename and hit enter> ``` I found a shorter quine to use, but here is my old version (for posterity): ``` i=open(raw_input()).read();a if i==(lambda x,y:x+repr((x,y))+y)('i=open(raw_input()).read();a if i==(lambda x,y:x+repr((x,y))+y)', ' else 1;exec(i)\n') else 1;exec(i) ``` [Answer] I can't exactly read from a file using Javascript (ok, I could, using the HTML5 FileReader thing, but that makes things a lot more complicated than I need). So, this is a function that accepts a Javascript program as a string and runs it. This probably isn't as golfed as it could be, but here it is anyway: # Javascript, 252 ``` function c(p){q='\"';s='\\';a="function c(p){q='\"';s='\\';a=%;a=a.slice(0,17)+s+a.slice(17,24)+a[23]+a.slice(24);a=q+a.replace('%',q+a+q)+q;alert(a);}";a=a.slice(0,17)+s+a.slice(17,24)+a[23]+a.slice(24);a=a.replace('%',q+a+q);alert(a);if(p!=a)eval(p)} ``` Let me know if anybody knows a better technique for forming a quine in Javascript. [Answer] # Common Lisp, 59 ``` #+~ #.(#:a)(defun L(p)(compile-file p))(push :~ *features*) ``` * In a fresh Lisp REPL, compile your file (e.g. `sbcl --load`) * You now have a function `L`, which can compile Common Lisp files * However, if you call `(L <your file>)`, an error is signaled while *reading* the file. ### Why? Because the first time, you pushed the `:~` keyword into [`*features*`](http://www.lispworks.com/documentation/lw50/CLHS/Body/v_featur.htm). Now, your environment knows about the `~` feature, and the reader macro `#+`, upon evaluating the `~` [feature expression](http://www.lispworks.com/documentation/lw50/CLHS/Body/24_aba.htm), will succeed and read the following form instead of skipping it as it did the first time. In your file, the following form is `#.(#:a)`, which asks to evaluate `(#:a)` at *read-time* and use the resulting value as the code being read. But `(#:a)` calls the function associated with the uninterned symbol `#:a`. Since `#:a` is uninterned, it is a fresh symbol which is not bound to any function (i.e. not [`fboundp`](http://clhs.lisp.se/Body/f_fbound.htm#fboundp)). Error. [Answer] # Javascript ES6, 45 bytes ``` $=(_=prompt())=>eval(_==`$=${$};$()`?0:_);$() ``` [Still competitive! (thx @Downgoat)](http://chat.stackexchange.com/transcript/message/28761481#28761481) [Answer] ``` read p<p;read c<c;[ "$p" = "$c" ]||. ./c ``` 45 characters of sh (POSIX shell). The code to be run must be in the file `./c`. The code for the interpreter itself must be in the file `./p`, so I guess I kind of cheated, although the challenge doesn't seem to forbid it. Or would this disqualify my "language" from being a "turing-complete programming language"? Using a tool that's normally an external executable, but might theoretically be built into the shell, the code can be shortened: ``` cmp -s p c||. ./c ``` That's 18 characters, and the `-s` bit is just to suppress a line that would otherwise always be printed for valid (non-self) programs. And then you can always build a version of the shell language that does the above with more concise syntax. And then you can always build a program that, when the input consists of a single '.' --or hell, the empty string-- evaluates the contents of another file as normal code, and call this a programming language. So the empty string would be your solution to the challenge, in the language you built. In fact, here's an interpreter for such a language: ``` read code; if [ "$code" ]; then eval "$code"; else . ./othercode; fi ``` Using the language the above script interprets, the solution is the empty string. And the code location needn't be hardcoded anymore. Problem? [Answer] ### JavaScript, 135 chars ``` function c(p){q='function c(p){q=%27Q%27;p!=unescape(q).replace(/Q/,q)?eval(p):alert()}';p!=unescape(q).replace(/Q/,q)?eval(p):alert()} ``` Peter Olson's JavaScript solution inspired me to try porting my Perl solution to JS. Like his solution, this code defines a function `c` that accepts a string, and evals it if it's not equal to the code above. It took me a while to figure out a good way to deal with the absence of balanced string delimiters in JavaScript, until I found what in hindsight is the obvious solution: `unescape()`. Conveniently, my code doesn't contain any backslashes or double quotes, so it can be safely stored in a double quoted strings. This makes it easy to test: ``` e = "function c(p){q='function c(p){q=%27Q%27;p!=unescape(q).replace(/Q/,q)?eval(p):alert()}';p!=unescape(q).replace(/Q/,q)?eval(p):alert()}" h = "alert('Hello, world!')" eval(e) // defines the function c() c(h) // evaluates h c(e) // does not evaluate e, alerts "undefined" instead ``` [Answer] # Scheme, 48 or 51 characters Scheme is a language with many different implementations. Despite implementations having to conform to the latest RnRS, the latest working standard (R6RS) has been unpopular due to its lack of minimalism. R7RS is soon to be released as a remedy, while splitting the language in 2. The first language being powerful and minimalistic and the second, a superset of the first intended to provide feature extensions for interoperability between implementations. Until then, we rely on SRFIs (Scheme Requests For Implementation), which provide (if implemented in the host implementation or manually (as is common in scheme)) a means to portably accomplish common tasks. All this to say that the first code snippet (51 characters), while remaining as portable as it can, relies on SRFI-22 (executing scheme scripts in UNIX) for access to command-line arguments: ``` (define(main x y)(case y(x => error)(else => load))) ``` or more readably: ``` (define (main current-file arg) (case arg [current-file => error] [else => load])) ``` The second (48 characters) is an file-less means to interpretation which cannot evaluate itself (in a null environment): ``` (define(e)(write(eval(read)null-environment))(e)) ``` or more readably: ``` (define (interpret) (write (eval (read) null-environment)) (interpret)) ``` [Answer] # Groovy, 13 bytes ``` {Eval.me(it)} ``` This should interpret a subset of Groovy. test cases: ``` p={Eval.me(it)} p''' (0..37).each{println"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"[it..it+2]} ''' p''' {Eval.me(it)} ''' ``` Unfortunately while it certainly barfs, it does so in a completely interpreter-like way, and it does it for quite a lot of input. ]
[Question] [ I'm not sure if this is the right place to ask, but I found this similar [question](https://codegolf.stackexchange.com/questions/145391/how-can-i-shorten-this-python-code) so I'll go ahead. I'm *very* new to code golfing, so keep your smothered laughs and throw-up emoji's to yourselves please ;). Anyway, someone recently posted a challenge (that was shortly deleted) to draw a 16x16 pixel image of the Old Man from the original Legend of Zelda, who gives you the wooden sword. This guy:[![](https://i.stack.imgur.com/zwneX.png)](https://i.stack.imgur.com/zwneX.png) Here's my code (643 characters): ``` from PIL import Image,ImageColor g=ImageColor.getrgb r=range l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)] i=Image.new('RGB',(16,16),color='black') for j in r(16): for k in r(16): t=k,j v=l[j][k] if v=='2': i.putpixel(t,g('white')) if v=='3': i.putpixel(t,g('#FFC864')) if v=='4': i.putpixel(t,g('red')) i.show() ``` It's bad, I know. Anyway, anyone care to share some tips on shortening it? [Answer] I'm proposing a slightly new strategy. Instead of `Image.putpixel`, we use `Image.frombytes`, which creates an image directly from an encoded string of `RGB` values. The logic is similar to the `putpixel` version, but when implemented, it turns out to be considerably shorter: ### 406 bytes ``` from PIL import Image x=b'\0\0\0',b'\xff\xff\xff',b'\xff\xc8\x64',b'\xff\0\0' D='0000022222200000000012122121000000002202202200000000220220220000000031222213000000031111111130000033110000113300033113111131133023313311113313322333331111333332233303311330333203330333333033300333033333303330003033333333030000003333333300000003322332233000' Image.frombytes('RGB',(16,16),b''.join(x[int(c)]for c in D)).show() ``` However, the compressed string `D` takes up almost half of the program! We can use [@ovs's](https://codegolf.stackexchange.com/users/64121/ovs) idea to "compress" it by storing it in a higher base (such as base 36). Now the code is almost half as long: ### 267 bytes ``` from PIL import Image x=b'\0\0\0',b'\xff\xff\xff',b'\xff\xc8\x64',b'\xff\0\0' D=int('MG8FMXO3ZANJ48JRXWYBSK3DF0HDWGJ34QP4XXAYS0EMXW3OJUIPDTNGOJGZIQZEKKSTFNJB1XQIAVDYAS8S06VLJVICO4STFK',36) Image.frombytes('RGB',(16,16),b''.join(x[D>>2*c&3]for c in range(256))).show() ``` Finally, notice that the image is vertically symmetric. Knowing this, we can cut the size of our compressed string in half, with some overhead from the added logic. Along with some general golfing tricks, we arrive at a messy 223-byte solution: ### 222 bytes ``` from PIL import Image Image.frombytes('RGB',[16]*2,b''.join(b'\0\xff\xff\xff\0\xff\xc8\0\0\xffd\0'[int('5VJ6J7FF7GD34HSPDCBV1SHKVG80MFVR3VX2RKU7WMRHBW0XZ4',36)>>2*(c//16*8+(c^-(c%16>7))%8)&3::4]for c in range(256))).show() ``` [Answer] Splitting the string into rows of 16 and then using two nested loops to go over each pixel is taking a lot of bytes to do. It would be easier to just loop over the original string and use `(index%16,index//16)` to point at a specific row and column. Also, instead of specifying a background color you can just draw every single pixel, which is shorter when using [hyper-neutrino's advice to use a list of colors](https://codegolf.stackexchange.com/a/225556/62393). You can also use `#000` and `#FFF` instead of `black` and `white` (1 byte shorter each). Bonus tip: `(16,16)` can become `[16]*2` (1 byte shorter) Combining this with [knosmos huge save by using data compression](https://codegolf.stackexchange.com/a/225560/62393) and [makonede's suggestion to use as imports](https://codegolf.stackexchange.com/a/225561/62393) we can get this down to 353 bytes: ``` import base64,zlib from PIL import Image,ImageColor as C i=Image.new('RGB',[16]*2) for j in range(256):i.putpixel((j%16,j//16),C.getrgb(['#000','#000','#FFF','#FFC864','red'][int(zlib.decompress(base64.a85decode(b"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[j])])) i.show() ``` [Answer] Just removing some whitespace, we can get: ``` from PIL import Image,ImageColor g=ImageColor.getrgb r=range l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)] i=Image.new('RGB',(16,16),color='black') for j in r(16): for k in r(16): t=k,j;v=l[j][k] if v=='2':i.putpixel(t,g('white')) if v=='3':i.putpixel(t,g('#FFC864')) if v=='4':i.putpixel(t,g('red')) i.show() ``` (since you can inline the if statements, and putting two statements on one line with `;` saves bytes when you're in a block) Then, you can collapse the repetitive `i.putpixel` by using a ternary `if-else`. Alternatively, you can just use a list to select the appropriate value: ``` from PIL import Image,ImageColor g=ImageColor.getrgb r=range l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)] i=Image.new('RGB',(16,16),color='black') for j in r(16): for k in r(16): t=k,j;v=int(l[j][k]) if v>1:i.putpixel(t,g(['white','#FFC864','red'][v-2])) i.show() ``` Basically, for `2`, `3`, and `4`, what this does is it uses a list, `['white', '#FFC864', 'red']` and selects the `v-2`th element from it. [Answer] You use the literal `16` 8 times. In python 3.8+, you can write `c:=16` and then `c` the other times: ``` i=Image.new('RGB',(c:=16,c),color='black') ``` [Answer] Shave off 97 bytes from hyper-neutrino's answer by encoding the data with base85 and zlib: ``` import base64,zlib from PIL import Image,ImageColor g=ImageColor.getrgb r=range l=[list(zlib.decompress(base64.a85decode(b"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[i*16:i*16+16])for i in r(16)] i=Image.new('RGB',(16,16),color='black') for j in r(16): for k in r(16): t=k,j;v=int(l[j][k]) if v>1:i.putpixel(t,g(['white','#FFC864','red'][v-2])) i.show() ``` [Answer] **EDIT:** Turns out Python 2 doesn't have `base64.a85decode`, so this won't work. But you can still combine a b-string with an r-string, and combine that with [Leo's amazing tip](https://codegolf.stackexchange.com/a/225562/94066), and you've saved \$292\$ bytes. ``` import base64,zlib from PIL import Image,ImageColor as C i=Image.new('RGB',[16]*2) for j in range(256):i.putpixel((j%16,j//16),C.getrgb(['#000','#000','#FFF','#FFC864','red'][int(zlib.decompress(base64.a85decode(br"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[j])])) i.show() ``` [Answer] # ~~215~~ ~~210~~ ~~216~~ ~~210~~ 216 bytes By using literal characters in place of some of the Unicode escapes from [dingledooper's 222 byte solution](https://codegolf.stackexchange.com/a/225566/94066), we can save a byte. ~~But by encoding the program in Latin-1, we can save 7!~~ **EDIT:** Saved 5 bytes thanks to [Jakque](https://codegolf.stackexchange.com/users/103772/jakque)! **EDIT:** Python by default parses programs as UTF-8, so this won't work. You would need a magic comment `#coding:l1` on the first line, so this would actually end up having to add 11 bytes. **EDIT:** Just tested on TIO, turns out I was wrong. 6 bytes have been regained! **EDIT:** After some more testing with Bash to try and get the raw bytes in, I was in fact correct the first time. Back to 216. ``` from PIL.Image import*;frombytes('RGB',[16]*2,b''.join(bytes('\0ÿÿÿ\0ÿÈ\0\0ÿd\0','l1')[int('5VJ6J7FF7GD34HSPDCBV1SHKVG80MFVR3VX2RKU7WMRHBW0XZ4',36)>>2*(c//16*8+(c^-(c%16>7))%8)&3::4]for c in range(256))).show() ``` [Answer] ``` import PIL.Image, base64, zlib s = b'c$}?~T@Jt?2!nfA54&42e`bR~6Cc(PgZQCUfkXDR5YV!&&a9D%ndJ9|Ir)dDC5CqM!KF%g^YH~{$pjovNiD-9`RpnztxNF;#WPO6@aBt?_fv%3QW0r-!$ZTqrT#L(OW41F%c&RU*cng' i = PIL.Image.frombytes("RGB", (16,16), zlib.decompress(base64.b85decode(s))) ``` [Answer] Instead of making a bunch of zeros, you probably could have made something like 0x8 and then parse it to display as 8 zeros. However I am not sure if that's any shorter. ]
[Question] [ Given an array of integers **`a`** which contains *n* integers, and a single integer **`x`**; remove the fewest amount of elements from **`a`** to make the sum of **`a`** equal to **`x`**. If no combinations of **`a`** can form **`x`**, return a falsy value. As pointed out in a comment this is the maximum set with a sum of **x**, excuse my lesser math brain. I forgot a lot of terms since college. --- **Examples (Truthy):** `f([1,2,3,4,5,6,7,8,9,10], 10) = [1,2,3,4]` `f([2,2,2,2,2,2,2,2,2], 10) = [2,2,2,2,2]` `f([2,2,2,2,-2,-2,-2,-4,-2], -8) = [2,2,-2,-2,-2,-4,-2]` `f([-2,-4,-2], -6) = [-4,-2] OR [-2,-4]` `f([2,2,2,4,2,-2,-2,-2,-4,-2], 0) = [2,2,2,4,2,-2,-2,-2,-4,-2]` (Unchanged) `f([], 0) = []` (Unchanged Zero-sum Case) --- **Examples (Falsy, any consistent non-array value):** **Impossible to Make Case:** `f([-2,4,6,-8], 3) = falsy (E.G. -1)` **Zero Sum Case:** `f([], non-zero number) = falsy (E.G. -1)` * *Note: any value like `[-1]` cannot be valid for falsy, as it is a potential truthy output.* --- Rules: * Input may be taken in array form, or as a list of arguments, the last or first being `x`. * Output may be any delimited list of integers. E.G. `1\n2\n3\n` or `[1,2,3]`. * Any value can be used as a falsy indicator, other than an array of integers. * Your code must maximize the size of the end array, order does not matter. + E.G. For `f([3,2,3],5)` both `[2,3]` and `[3,2]` are equally valid. + E.G. For `f([1,1,2],2)` you can only return `[1,1]` as `[2]` is shorter. * Both the sum of **`a`** and the value of **`x`** will be less than `2^32-1` and greater than `-2^32-1`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. * If there are multiple subarrays of the same size that are valid, it is *not* acceptable to output all of them. You must choose a single one and output that one. --- Let me know if this has been posted, I couldn't find it. Posts I found *like this*: [Related but closed](https://codegolf.stackexchange.com/questions/17981/sum-of-numbers-of-array), ... [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` h⊇.+~t?∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@NRV7uedl2J/aOO5f//R0fHG@nEm@jEG8XqxJvF/o8CAA "Brachylog – Try It Online") Monthly Brachylog answer. Returns `false.` if it is not possible. ### Explanation ``` h⊇. The output is a subset of the head of the input .+~t? The sum of the elements of the output must equal the tail of the input ∧ (Avoid implicit unification between the output and the input) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~108~~ 104 bytes ``` lambda a,n:[x for l in range(len(a)+1)for x in combinations(a,l)if sum(x)==n][-1] from itertools import* ``` [Try it online!](https://tio.run/##jZDBaoQwFEX3fsWD2STtE4xjp7bgNxQKXVkXmRntBJIXiSnYr7eR0FHERUkI5N57csPrf/zNUj511eekpTlfJUik13qEzjrQoAicpK@W6ZaY5I@Cz/o46xdrzoqkV5YGJlFz1cHwbdjIq4qaOhVN0jlrQPnWeWv1AMr01vmHqXeKPHSsFpjjEQt8whM@Y4kvKLIGQWQcDhX82U2S3IkcNyvGDxDii7YDpPddhDNQaRlLdswVvgZOsSbe4e0dovuvtmwp2/GBfdDlNs/5ylevLdzmS0WYV1oG@7iJ53z6BQ "Python 2 – Try It Online") -4 bytes, thanks to Jonathan Allan --- # [Python 2](https://docs.python.org/2/), ~~108~~ 106 bytes ``` def f(a,n): q=[a] while q: x=q.pop(0);q+=[x[:i]+x[i+1:]for i in range(len(x))] if sum(x)==n:return x ``` [Try it online!](https://tio.run/##jZDBaoQwEIbvPsXAXhIci7p261ryDAuFnkIO0o01sBs1dWn26e2U0FXEQ0kIzPz/N3@Y/j62nc2n6awbaFiNllcRDELWKoLv1lw0DNQAL4anvutZyl@HWEgvK6NiL02cVarpHBgwFlxtPzW7aMs858SDaeDrdqVKCFs5Pd6cBT/1ztiRwmSGOe6xwGc84AuWeMQsVQhZymEn4E9WUfQgclydYN8B2efeBpA8bkEvUUkZQjbEBb4EDiEm1HB6g6D@Ky2dwzZ0YO/2o/1d3pkvps3c6ksF7SspSd6v7DmffgA "Python 2 – Try It Online") -2 bytes, thanks to Janathan Frech [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` æʒOQ}0ªéθ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8LJTk/wDaw0OrTq88tyO//@jDXWMdIx1THRMdcx0zHUsdCx1DA1iuQwNDAA "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-h`, 11 bytes ``` à f_x ¥VÃñl ``` [Try it online!](https://tio.run/##y0osKPn///AChbT4CoVDS8MONx/emPP/f7SRDgiaALEuHJkAyVgdBQMuLt0MAA "Japt – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes * **8-byter** ([Try it!](https://pyth.herokuapp.com/?code=efqz%60sTy&input=%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A10&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%5D%0A10%0A%0A%5B2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%5D%0A10%0A%0A%5B2%2C+2%2C+2%2C+2%2C+-2%2C+-2%2C+-2%2C+-4%2C+-2%5D%0A-8%0A%0A%5B-2%2C+-4%2C+-2%5D%0A-6%0A%0A%5B2%2C+2%2C+2%2C+4%2C+2%2C+-2%2C+-2%2C+-2%2C+-4%2C+-2%5D%0A0%0A%0A%5B%5D%0A0%0A%0A%5B-2%2C+4%2C+6%2C+-8%5D%0A3%0A%0A%5B%5D%0A5%0A&debug=0&input_size=3)) – Outputs only one possible solution. For unsolvable inputs, it doesn't print anything to STDOUT, which is an empty string, which is technically speaking falsey in Pyth, but writes to STDERR. Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for suggesting this (ignoring STDERR and focusing on the STDOUT output only), thus saving 1 byte. ``` efqz`sTy ``` * **9-byter** ([Try it!](https://pyth.herokuapp.com/?code=%3E1fqz%60sTy&input=%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A10&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%5D%0A10%0A%0A%5B2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%5D%0A10%0A%0A%5B2%2C+2%2C+2%2C+2%2C+-2%2C+-2%2C+-2%2C+-4%2C+-2%5D%0A-8%0A%0A%5B-2%2C+-4%2C+-2%5D%0A-6%0A%0A%5B2%2C+2%2C+2%2C+4%2C+2%2C+-2%2C+-2%2C+-2%2C+-4%2C+-2%5D%0A0%0A%0A%5B%5D%0A0%0A%0A%5B-2%2C+4%2C+6%2C+-8%5D%0A3%0A%0A%5B%5D%0A5%0A&debug=0&input_size=3)) – Outputs only one possible solution, wrapped in a singleton list as [allowed by default](https://codegolf.meta.stackexchange.com/a/11884/59487) (e.g. `([1...10], 10) -> [[1,2,3,4]]; ([], 0) -> [[]]`). For unsolvable inputs, it returns `[]`, which is [falsey](https://pyth.herokuapp.com/?code=%21%21&input=%5B%5D&debug=0) in Pyth. ``` >1fqz`sTy ``` * **10-byter** ([Try it!](https://pyth.herokuapp.com/?code=e%2B0fqz%60sTy&input=%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A10&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%5D%0A10%0A%0A%5B2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%2C+2%5D%0A10%0A%0A%5B2%2C+2%2C+2%2C+2%2C+-2%2C+-2%2C+-2%2C+-4%2C+-2%5D%0A-8%0A%0A%5B-2%2C+-4%2C+-2%5D%0A-6%0A%0A%5B2%2C+2%2C+2%2C+4%2C+2%2C+-2%2C+-2%2C+-2%2C+-4%2C+-2%5D%0A0%0A%0A%5B%5D%0A0%0A%0A%5B-2%2C+4%2C+6%2C+-8%5D%0A3%0A%0A%5B%5D%0A5%0A&debug=0&input_size=3)) – For a clearer output, without using the singleton-list rule and using `0` rather than `[]` as a falsy value. ``` e+0fqz`sTy ``` ### Explanation First, the code computes the powerset of the input list (all possible ordered sub-collections thereof). Then, it only keeps those collections whose sum is equal to the input number. It should be noted that the collections are generated from the shortest to the longest, so we focus on the last one. To obtain it: * The **8-byter** simply uses the *end* built-in, which throws an error, but STDERR can be ignored as per our site rules, the output to STDOUT being an empty string, which is falsy. * The **9-byter** takes the last element, but using the equivalent Python code `lst[-1:]` in place of `lst[-1]` to avoid errors from being thrown for unsolvable inputs. * The **10-byter** prepends a **0** to the list of filtered sub-collections, then takes the end of that collection (last element). If the inputs aren't solvable, then **0** is naturally used instead. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŒPS⁼¥ƇṪ ``` [Try it online!](https://tio.run/##y0rNyan8///opIDgR417Di091v5w56r/h5cfnfRw54z//6ONdCBQF45MgGTsf10LAA "Jelly – Try It Online") Output clarified over TIO. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~38~~ 37 bytes ``` {*.combinations.grep(*.sum==$_).tail} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WksvOT83KTMvsSQzP69YL70otUBDS6@4NNfWViVeU68kMTOn9n9xYqVCmoZetGGsJpA0iNVUSMsv4tLQMNQx0jHWMdEx1THTMdex0LHUMTTQ1FEAEUBZIx00iCmlC0cmQBIor2sBlkcWMUPSYYJND8RIOEMXpMxMB2SSgjFMylDzPwA "Perl 6 – Try It Online") Curried function. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ⟨⊇+⟩ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahjuVKahlK5fUa5ko4CkC4pV9JUsAWxqh@1bXjU1FwDVpKYU5yqp1T7cFdn7cOtE/4/mr/iUVe79qP5K///j46ONtQx0jHWMdEx1THTMdex0LHUMTSIBePoaCMdNIguEQ9HJkAyVifeAiSLxDdDqDbBoh5sGJSKBykxAxthDBE2MYqNBQA "Brachylog – Try It Online") Just about equivalent to Fatalize's `h⊇.+~t?∧`, except a **lot** shorter, thanks to the *predicate composition* feature which according to [the edit history of the reference](https://github.com/JCumin/Brachylog/wiki/7)-Predicate-composition/_history) was a work in progress until January 8, postdating the answer by over two months. `⟨⊇+⟩` is a *sandwich*, expanding to `{[I,J]∧I⊇.+J∧}`, where the braces are in this case irrelevant as the sandwich is on its own line anyhow. ``` The input [I,J] is a list of two elements I and J. . The output, +J which sums to J ∧ (which we don't unify with the output), I⊇ is a sublist of I ∧ (which we don't unify with [I,J]). ``` A far less dramatic transformation of Fatalize's answer, which uses the same predicates with the same variables but comes out a byte shorter from being organized differently: # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` h⊇.&t~+ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahjuVKahlK5fUa5ko4CkC4pV9JUsAWxqh@1bXjU1FwDVpKYU5yqp1T7cFdn7cOtE/5nPOpq11MrqdP@/z86OtpQx0jHWMdEx1THTMdcx0LHUsfQIBaMo6ONdNAgukQ8HJkAyVideAuQLBLfDKHaBIt6sGFQKh6kxAxshDFE2MQoNhYA "Brachylog – Try It Online") ``` The input h 's first element ⊇ is a superlist of . the output, & and the input t 's last item ~+ is the sum of the elements of the output. ``` (Also, if anyone wants to see something odd, change any of the underscores in the test cases into hyphens.) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` A.Q|>1fqsTHyG0 ``` [Try it online!](https://tio.run/##K6gsyfj/31EvsMbOMK2wOMSj0t3g//9oQx0jHWMdEx1THbNYLkMDAA "Pyth – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 89 bytes ``` import StdEnv,Data.List,Data.Func $n=find((==)n o sum)o sortBy(on(>)length)o subsequences ``` [Try it online!](https://tio.run/##PUyxCsIwFNz9ijd0SKF1EAeXOEgVhA5CR3F4pmkNJC/avAj9eWOkIHccdwd3ymqk5HwfrQaHhpJxTz8xdNwf6V01yLhuTeDFnSKpVUFyMNQLIWVJ4CFEV2bNq8MsPIl9aTWN/PiV8R70K2pSOqSOMR9LKKDewXVTLaj/3Ga9pY8aLI4h1ec2NTOhM2oJF4s8@Ml9AQ "Clean – Try It Online") Defines the function `$ :: Int -> [Int] -> (Maybe [Int])` returning `Nothing` if there is no appropriate combination of elements, and `(Just [elements...])` otherwise. [Answer] # JavaScript (ES6), 108 bytes Takes input as `(array)(n)`. Returns either an array or `false`. ``` a=>n=>a.reduce((a,x)=>[...a,...a.map(y=>1/r[(y=[...y]).push(x)]||eval(y.join`+`)-n?y:r=y)],[[]],r=!n&&[])&&r ``` [Try it online!](https://tio.run/##fZHfaoMwFMbv@xTZjSTsGGvrOjeIu9gDDAa7mQQaNPYPNpFklgp9d6dra0V0JyG5OOf35fvIXhyFTcyu@HGVTmWdsVqwSLFIUCPTMpEYCzgRFsWUUgHtQQ@iwBWLfM/Ezd02Kk5oUdotPhF@PsujyHFF93qn1o9r4qq36tWwinCIY87BsAflODEnjmPqRCurc0lzvcEZjn1YwBICeIIVPEMIL@DPOcH@nBDUlOeh2wifDdAFDFaPu6L31hTsdjtozkbBDVuFGzxoD1X63Kp7uatW5dJHH5/oMj3hJBjz0oa5xxgZQfhLJVuhNjIlQ90rP1Wtbp9H39Jo15YH9C6sJLORqEHzR27Y6C5Ho2Yit3LExfJ/F39Y/Qs "JavaScript (Node.js) – Try It Online") [Answer] This started out cool and small, but edge cases got me. Whatever happens, I'm proud of the work I put into this. # [Python 3](https://docs.python.org/3/), ~~169 161~~ 154 bytes ``` from itertools import* def f(a,x): if sum(a)==x:return a try:return[c for i in range(len(a))for c in combinations(a,i)if sum(c)==x][-1] except:return 0 ``` [Try it online!](https://tio.run/##bZDdisMgEIWv41MM9EaXCeRvu9lCnqFQ2KuQC9dqKzQajIX06bOGptsQgiLMmfnOkeke/mpNPo7K2Ra0l85be@tBt511/oOcpQJFOQ7sQCKtoL@3lLOqGg5O@rszwEnk3WOuagHKOtCgDThuLpLepAnzbFLFpArb/mrDvbamD7aazZ5i8mzqOG1IJAchO/8KSMbOaeOBKlqnmGGOBX7iHr@wxG9MkwYhTRiDXQWvfkPIm8lwdWZgBwF4i1tI/H@L8AYuLuegje7SYIns56inAMcTPNsbicVWZrKI3BwB@mPEddr2mS09F@z6c0XYX1yGgZytkYyx8Q8 "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~100~~ 80 bytes ``` function(a,x){i[sum(a|1):0,j[combn(a,i,,F),if(sum(j)==x)return(j)]] F} `[`=`for` ``` [Try it online!](https://tio.run/##fY3BCsIwEETv@QqPu7CFREuRYq/9iVJIDQ2k0ARiAwX122OiKGJBdlmYfcyMj3p3KqIOVi3GWRhoxavpLmGG4Saw5jR1ys3nTAxRi2Q0ZDph06zoxyV4m0Tfs/bOZCcbqZ2XUYOoBSfBkWlQsKefwQ0qPlumi1QcX/zrU/13PANtmEdvFPCtfjcmR0lVLqADxgc "R – Try It Online") *20 bytes saved thanks to digEmAll* Returns `FALSE` for impossible criteria. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 28 bytes ``` ${(y&`=@Sum\Radiations@x)@0} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBlq/BfpVqjUi3B1iG4NDcmKDElM7EkMz@v2KFC08Gg9r9fampKcbRKQUFyeixXQFFmXklIanGJc2JxanF0moODZ4qOQjSXAhBERxvqGOkY65jomOqY6ZjrWOhY6hgaxOoogAioCiMdNIhdWheOTIAkUI2uBVwNsqgZmk4TbHoRxqNwdEHKzXRAJisYIysxMYrlio39DwA "Attache – Try It Online") ## Alternatives **34 bytes**: `f[x,y]:=({y=Sum@_}\Radiations@x)@0` **30 bytes**: `First@${y&`=@Sum\Radiations@x}` **29 bytes**: `{(_&`=@Sum\_2)@0}#/Radiations` **29 bytes**: `${({y=Sum@_}\Radiations@x)@0}` **29 bytes**: ``@&0@${y&`=@Sum\Radiations@x}` **29 bytes**: `{_}@@${y&`=@Sum\Radiations@x}` ## Explanation ``` ${(y&`=@Sum\Radiations@x)@0} ${ } function receiving two arguments, x and y Radiations@x calculate the radiations of x (simulates removing all possible subslices of x) \ keep those radiations Sum ...whose sum... `=@ ...equals... y& ...y ( )@0 select the first one (always the longest) ``` [Answer] # APL(NARS), 65 chars, 130 bytes ``` {m←⍺=+/¨v←1↓{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}⍵⋄0=↑⍴b←m/v:⍬⋄b⊃⍨n⍳⌈/n←⍴¨b} ``` ↓ is used because the first element of the set of sets would be one void set (here ⍬ Zilde), that one want eliminate because it seems +/⍬ is zero... For not find, or error it would return ⍬ or in print text: ``` o←⎕fmt o ⍬ ┌0─┐ │ 0│ └~─┘ ``` test: ``` z←{m←⍺=+/¨v←1↓{0=⍴⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}⍵⋄0=↑⍴b←m/v:⍬⋄b⊃⍨n⍳⌈/n←⍴¨b} o 1 z ,1 ┌1─┐ │ 1│ └~─┘ o 2 z ,1 ┌0─┐ │ 0│ └~─┘ o 10 z 1 2 3 4 5 6 7 8 9 10 ┌4───────┐ │ 1 2 3 4│ └~───────┘ o 10 z 2,2,2,2,2,2,2,2,2 ┌5─────────┐ │ 2 2 2 2 2│ └~─────────┘ o ¯8 z 2,2,2,2,¯2,¯2,¯2,¯4,¯2 ┌7──────────────────┐ │ 2 2 ¯2 ¯2 ¯2 ¯4 ¯2│ └~──────────────────┘ o ¯6 z ¯2,¯4,¯2 ┌2─────┐ │ ¯4 ¯2│ └~─────┘ o 0 z 2,2,2,4,2,¯2,¯2,¯2,¯4,¯2 ┌10───────────────────────┐ │ 2 2 2 4 2 ¯2 ¯2 ¯2 ¯4 ¯2│ └~────────────────────────┘ o 10 z 1 2 3 4 ┌4───────┐ │ 1 2 3 4│ └~───────┘ o 10 z 1 2 3 ┌0─┐ │ 0│ └~─┘ o 0 z ⍬ ┌0─┐ │ 0│ └~─┘ o +/⍬ 0 ~ ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ▲fo=⁰ΣQ² ``` [Try it online!](https://tio.run/##ASQA2/9odXNr///ilrJmbz3igbDOo1HCsv///1stMiwtNCwtMl3/LTY "Husk – Try It Online") Brachylog is **insane.** [Answer] # [Haskell](https://www.haskell.org/), 68 bytes ``` import Data.List f x=find((==x).sum).sortOn(sum.(-1<$)).subsequences ``` [Try it online!](https://tio.run/##VYzNCoMwEITvPsUePETYiPGntdDceiz0AaSHVJM2VKM1EXz6pimFgswyLDMf8xD2Kfveez1M4@zgJJxIz9q6SMHKlTYdIZyvSWqXIVhALoaEPyWUHePkm9@sfC3StNL6QWgDHLoxAphmbRzEoIBl0DDMscASK9zhHms8IMuuG4rQOoEmx5/o/8rgWzLMbYMCmkCWYZrW26YKqH@3qhd362k7TR8 "Haskell – Try It Online") Defines `f x a` to return `Just` a subset or `Nothing`. The only trick here is that `sum.(-1<$)` is one byte shorter than `(0-).length`. ]
[Question] [ Most people here are familiar with seven segment displays, which are also used in matchstick puzzles. Below are the digits `0` through `9` and letters `a` through `z`, except `k,m,t,v,w`, written in this format. ``` _ _ _ _ _ _ _ _ | | | _| _| |_| |_ |_ | |_| |_| |_| | |_ _| | _| |_| | |_| _| _ _ _ _ _ _ _ _ _ |_| |_ | _| |_ |_ | |_ | | | _ _ |_| |_| _ |_ |_| |_| _| | | |_| |_ |_| |_ | |_| | | | |_| |_ | | |_| | | | _| |_| | | | |_ ``` The challenge here is simple. Given an input string, output the number of matchsticks required to represent that string. If the string contains a character outside of the above representation, ignore it (count it as 0). For example, for input `53`, a total of `10` matchsticks are required, `5` for the `5` and `5` for the `3`, so the output is `10`. For input `hello` a total of `19` matchsticks are required, `h (4), e (5), l (3), l (3), o (4)`, so the output is `19`. For clarity, here are the matchsticks required to build each character: ``` 0 -> 6 1 -> 2 2 -> 5 3 -> 5 4 -> 4 5 -> 5 6 -> 6 7 -> 3 8 -> 7 9 -> 6 a -> 6 b -> 5 c -> 4 d -> 5 e -> 5 f -> 4 g -> 5 h -> 4 i -> 2 j -> 4 l -> 3 n -> 3 o -> 4 p -> 5 q -> 5 r -> 2 s -> 5 u -> 3 x -> 5 y -> 4 z -> 5 ``` Now for the twist, and there are two of them. * The first is that the input is considered case-*in*sensitive. That is, `A` and `a` should both count for `6` matchsticks, even though the visual representation looks like an uppercase `A`. * Your score is your source code run through this algorithm, plus the length of your source code in bytes, lower is better. For example, if your source code was `abc123`, your score would be `6+5+4+2+5+5 = 27 + 6 = 33`. If your source code was `#&@()*`, your score would be `0 + 6 = 6`. ### Input/Output Examples ``` 0 -> 6 53 -> 10 111 -> 6 112 -> 9 8888 -> 28 hello -> 19 PPCG -> 19 Programming Puzzles & Code Golf -> 99 #&()mt!!~ -> 0 *DḌƤÆE%Ḅċ0 -> 16 ``` ## Rules * If applicable, you can assume that the input/output will fit in your language's native Integer type. * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. [Answer] # [Python 2](https://docs.python.org/2/), 97 bytes + 237 matches = 334 ``` lambda w:sum(map(('1ir'*2+'7lnu'*3+'4cfhjoy'*4+'235bdegpqsxz'*5+'069a'*6+'8'*7).count,w.lower())) ``` [Try it online!](https://tio.run/##RZDNUsIwEMfvPMVSBrafDCnfnakXVK7cK4dCU6iTJtgPEQ6eHC/6GD4Edx3fgyfBhKLmkPz3t5vsP7vZFWvB3VMDHNMBypciSvjKg7KInZFiNUmor2naiYXpIgph6@VlqqfhRteRJBmaroVDxks0uxb2lvH6XuzQ7FnodvuLiK42D/nTHs2@hZ3BOERzYOEIzaHRXoqSF/a2zcSWZrphGCfZpWqntoB4DpnXYp8@hkxXxKjFIoOC5oWd0bxkBSQcggA7aMNgbgfY70pFOkoSQn4pIa6UYyVHckntjlSwpowJdeGcms0m0/8gE6ssTFM5CpiV@z2jObRgIj3AVLBYPXeua7R0Iy3q9WdJzm3N6@Ph/fvj8/WmeTy8fL0pa2Qwn3ubLOEFxLpyb/h@5d@uPoPOFdqXVK0q1O74bcJDBvlSZBQ8aEZWMwJfnlpTj6tx2Izyi7oQ648Ypx8 "Python 2 – Try It Online") This works by generating a string where each buildable character appears the same amount of matchsticks required to build that character [Answer] ## [Perl 5](https://www.perl.org/) with `-pF`, 95 bytes + 14, 109 ``` eval~"Û£Ô„…ÊÏÉÎÍÍÊÌÊËËÊÊÉÉÈÌÇÈÆÉžÉʜ˛ʚʙ˘ʗ˖͕˓̑ÌËÊŽÊ͌ʊ̇ʆËÂÐÑИ‚ÒÁ„Ô“œ‚™¿¹"}{ ``` This is equivalent to: ``` $\+={z506122535445566738796a6b5c4d5e5f4g5h4i2j4l3n3o4p5q5r2s5u3x5y4=~/./g}->{+lc}for@F ``` but using the `~` operator we can use high-byte characters and avoid a lot of characters without really sacrificing bytes. Still quite a way off Ton's score, even with assistance! [Try it online!](https://tio.run/##NVBLSgNBEL1L9gFjTNJ9AXfeYDbzCwjBBI0yIEoniDoziRmTLESjxAjeQUGFLmaVW/RBHF/TJcWbV/V6ul5VD@LjXquq4jO/d1nzkijwEr8J3vOScNdLBFi0kPtAF5BADEQMq4fMAcNnSIbgfzqct50uY2buI0N3X3IPyX2kZF1w3eG67WaQLa6bzkc2mHecLrrunoiZeXbBcwveQXS4bvMedn/0itAnYrYzCOgREDbc@9i3st52fntm57Xe1ieAdyBrF@f/T0xP@o2WNDbqxah3ymhGKd3RFJHRBMgRGSJF3EK5wfea0vKbUv1MWbmg3KhPJK@UmasN5dsVErW08oKmRm1stqKJUQ800QXleoa/vyjTMCnnyNf20F5Xa5iN9YgKuqdiuzLqkeY0wmy0RI9yAQEeutBT/aM/sMZvfzA87B@dVPWBv1/VD@qnw674Aw "Perl 5 – Try It Online") This solution contains unprintables so here's a reversible hex dump to verify the byte-count: ``` 00000000: 6576 616c 7e22 dba3 d4c2 8485 cacf c9ce eval~".......... 00000010: cdcd cacc cacb cbca cac9 c9c8 ccc7 c8c6 ................ 00000020: c99e c99d ca9c cb9b ca9a ca99 cb98 ca97 ................ 00000030: cb96 cd95 cb93 cc91 cc90 cb8f ca8e ca8d ................ 00000040: cd8c ca8a cc87 ca86 cbc2 81d0 d1d0 9882 ................ 00000050: d2c1 84d4 939c 8299 908d bfb9 227d 7b ............"}{ ``` [Answer] # JavaScript (ES6), 198 (102 bytes + 96 matchsticks) *Saved 5 points thanks to @l4m2* ``` v=>[...v].map(w=>t+=('{w__^_{]|{{_^__^_^w^~]~]^__w_~]~~_^_'[parseInt(w,36)]+v).charCodeAt()%9,t=+[])|t ``` [Try it online!](https://tio.run/##vZLBTsJAEIbvPMUSA7srWChEAoeSGDTEWxO91VI2dSmYttt0lzahpCfjRR/Dh@Cu8T14krq9aQvUk5NNdrKbb/6ZzP9EIsLtcBWIC5890myhZZE2NhRFiUzFIwGKtbFoaQgmsWXNrMTcJom85ZnFs9RMTZnHlkxS@QSNgISc3voCxe3@AJutCCv2koQTWfpKINwYtYXWMky8FZnNfM5cqrjMQfCecgFswimHuPbzZ4FgF2IMTkenAwZF7LJfyUlM7RY5VVWrwENyqtr7AzYqYkMZFZzEesMit6Suy06D@XQlPV2fTKv1DnAhc0LieSvfAfp6s3EpB02Q7xVMmbvIS@bjlbizJsKeqNfT46KSKy3h/Hq/e/t6/3i5aex3z5@vxz2Qdzuo/eLhg3/H1qFNgS37Kxlq/j8Gn2OcfQM "JavaScript (Node.js) – Try It Online") ### How? We use the ASCII code modulo 9 of characters that do not add any penalty to encode the numbers of matchsticks. ``` char. | code | modulo 9 -------+------+----------------- ~ | 126 | 0 v | 118 | 1 (not used) w | 119 | 2 ] | 93 | 3 ^ | 94 | 4 _ | 95 | 5 { | 123 | 6 | | 124 | 7 ``` We do not have to worry about the case because `parseInt()` is case-insensitive. For characters that do not match **[0-9A-Za-z]**, `parseInt()` returns `NaN` and the string lookup results in `undefined`. Once coerced to a string, `"undefined".charCodeAt()` returns the ASCII code of `"u"`, which is **117**. Conveniently, **117** modulo **9** gives **0** as expected. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 bytes + 0 matchsticks = 42 points ``` “ṄḟṭkɗØæ⁶ṡ“£ƈṠ¤żȥṬ}ė$t¿ƬⱮȷ|çƓ’×/ṚṚæ.ċЀØW$ ``` *Thanks to @JonathanAllan for -2 points!* [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO1se7pj/cOfa7JPTD884vOxR47aHOxcCJQ4tPtbxcOeCQ0uO7jmx9OHONbVHpquUHNp/bM2jjetObK85vPzY5EcNMw9P13@4cxYQHV6md6T78IRHTWsOzwhX@f9w95bD7UBOJA0t4TLgMjXmMjQ0BGIjLgsg4MoA@iufKyDA2Z0roCg/vSgxNzczL10hoLSqKie1WEFNwTk/JVXBPT8njUtZTUMzt0RRsY5Ly@Xhjp5jSw63uao@3NFypNsAAA "Jelly – Try It Online") ### How it works ``` “ṄḟṭkɗØæ⁶ṡ“£ƈṠ¤żȥṬ}ė$t¿ƬⱮȷ|çƓ’ ``` Literals that begin with `“` and end with `’` split on `“`, replace the remaining characters with their 1-based indices in Jelly's code page, then convert from bijective base 250 to integer. This particular literal encodes ``` [3096734725226860846495, 211369264881118657055472842435156679693648]. ``` `×/` reduces by multiplication, yielding ``` 654554542403034552503005456545545424030345525030054562554563760 ``` (Encoding this integer directly would save 6 bytes, but cost 28 matchsticks.) `ṚṚ` reverses twice; the first call promotes an integer to its digit array. This yields ``` [6, 5, 4, 5, 5, 4, 5, 4, 2, 4, 0, 3, 0, 3, 4, 5, 5, 2, 5, 0, 3, 0, 0, 5, 4, 5, 6, 5, 4, 5, 5, 4, 5, 4, 2, 4, 0, 3, 0, 3, 4, 5, 5, 2, 5, 0, 3, 0, 0, 5, 4, 5, 6, 2, 5, 5, 4, 5, 6, 3, 7, 6, 0] ``` `ċЀØW$` counts (`ċ`) the occurrences of each (`Ѐ`) character of **"A...Za...z0...9\_"** (`ØW`) in the input string. Finally `æ.` takes the dot product, multiplying each character count by the corresponding cost in matchsticks, then taking the sum. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 34 bytes + 3 matches = 37 ``` ⁽[ɱד®-&]Ṙṙ£⁺ÐĊṂⱮɼ ’‘ḤṚæ.ŒlċЀØWṚƊ ``` A monadic link accepting a list of characters and returning an integer. **[Try it online!](https://tio.run/##y0rNyan8//9R497okxsPT3/UMOfQOl212Ic7ZzzcOfPQ4keNuw5PONL1cGfTo43rTu5ReNQw81HDjIc7ljzcOevwMr2jk3KOdB@e8KhpzeEZ4UChY13/H@7ecnTP4XagkEoWkAAaqKBrB9Q3N/L/fwMuU2MuQ0NDIDbisgACrgyg9flcAQHO7lwBRfnpRYm5uZl56QoBpVVVOanFCmoKzvkpqQru@TlpXMpqGpq5JYqKdVxaLg939BxbcrjNVfXhjpYj3QZcVHM@AA "Jelly – Try It Online")** ### How? Works in a similar way to [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/160121/53748) but took enough effort that I feel it warrants another answer. The core difference is that it lower-cases the input for a cost of three matches (`Œl` contains an `l`) which then allows for a much smaller number to be used to create the cost array. The tricky bit was finding a way to construct that number without matches while staying concise. `ØW` yields `"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"` so counting lower-cased input occurrences always starts with 26 zeros. We can reverse this and perform a dot-product with an array of length 37 instead of one of length 63. ``` ⁽[ɱד®-&]Ṙṙ£⁺ÐĊṂⱮɼ ’‘ḤṚæ.ŒlċЀØWṚƊ - Link: list of characters ⁽[ɱ - literal 23913 “®-&]Ṙṙ£⁺ÐĊṂⱮɼ ’ - literal 136861653160003879166772353166783 × - multiply = 3272772712015172762515027281277281879 ‘ - increment = 3272772712015172762515027281277281880 Ḥ - double = 6545545424030345525030054562554563760 Ṛ - reverse (implicit decimal list) -> [0,6,7,3,6,5,4,5,5,2,6,5,4,5,0,0,3,0,5,2,5,5,4,3,0,3,0,4,2,4,5,4,5,5,4,5,6] - (to align with: _ 9 8 7 6 5 4 3 2 1 0 z y x w v u t s r q p o n m l k j i h g f e d c b a) Ɗ - last four links as a monad: Œl - lower-case (the input) ØW - word -> "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" Ѐ - map across right: ċ - count (right character in lower-cased input) Ṛ - reverse (to align with the values as shown above) æ. - dot-product ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~90~~ 64 code + 9 eval harness + 14 matchsticks = 87 Replace the hex codes by their literal 1 byte variant (***not*** UTF-8 as TIO tries to) for the claimed score ``` eval~"\xdb\xa3\xd4\xc2\x86\xd0\xcf\xd2\xc6\x9e\xd2\x85\xd0\xc9\xcd\xca\xca\xcb\xca\xc9\xcc\xc8\xc9\xc9\xca\xcb\xca\xca\xcb\xca\xcb\xcd\xcb\xcf\xcc\xcf\xcc\xcb\xca\xca\xcd\xca\xcf\xcc\xcf\xcf\xca\xcb\xca\xd0\x8d\x99\x90\x8d\xdf\x93\x9c\xc2\x81\xd0\xd1\xc0\xd0\x98"}{ ``` [Try it online!](https://tio.run/##XVBbCsIwELxL/1tSNZI9hDfIT16FQrFBRQJSj26cNluIfgwzm53sZBPDbZI5h6eZ3o1O3upkjuCTTu6gkzpDC@gBjNqhplC0ktwjwAOGYZnXcwco1vTXr7XlGbZkbfd2rv17Tu0Zfmetb1LwEfKItYeHsBc53qsvPg92omhSzfIqX/GZ42Ocr/fcxtxeZNeLTnwB "Perl 5 – Try It Online") Code Inside the complemented string: ``` $\+=y/0-9a-z/625545637665455454240303455250300545/rfor lc=~/.?/g ``` [Answer] # PHP 176 bytes = 397 score ``` <?$n="6255456376";$l="065455454240303455250300545";$a=strtolower($argv[1]);for($i=0;$i<strlen($a);$i++)$t+=(is_numeric($a[$i])?$n[$a[$i]]:$l[max((ord($a[$i])-96),0)]);echo$t; ``` [Try it online!](https://tio.run/##1Y5dCoMwEITfPUWRPBiskPqT0sbQgwQRsakGNBti@nP6pgulhyjswzc7w8662cXYXoiVKS@bpm54deSpIItMGUeJU5c1q1iFXDYIDFcYGOQWfIAFntpnZPDTQx06Km6AykgmiGkxsGiLJkWV55SEXGZm6@191d6MaChiOorl6ovdmSxqHV5ZBv76s4sTp3tG8bYeZyBBJEn8t5ff4IIBu8Xiuttm8KEHp20fhkmC/QA "PHP – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 34 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) + 18 = 52 ``` ā⁄,u{²²z+;W"⁾o∫k9÷│>Γ{σ¬μ┼“'=υ─wι+ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxJXUyMDQ0JTJDdSU3QiVCMiVCMnorJTNCVyUyMiV1MjA3RW8ldTIyMkJrOSVGNyV1MjUwMiUzRSV1MDM5MyU3QiV1MDNDMyVBQyV1MDNCQyV1MjUzQyV1MjAxQyUyNyUzRCV1MDNDNSV1MjUwMHcldTAzQjkr,inputs=JXUwMTAxJXUyMDQ0JTJDdSU3QiVCMiVCMnorJTNCVyUyMiV1MjA3RW8ldTIyMkJrOSVGNyV1MjUwMiUzRSV1MDM5MyU3QiV1MDNDMyVBQyV1MDNCQyV1MjUzQyV1MjAxQyUyNyUzRCV1MDNDNSV1MjUwMHcldTAzQjkr,v=0.12) [Golfed, but not scoring as much](https://dzaima.github.io/SOGLOnline/?code=MCUyQ3UlN0IlQjIlQjJ6KyUzQlclMjIldTIwN0VvJXUyMjJCazklRjcldTI1MDIlM0UldTAzOTMlN0IldTAzQzMlQUMldTAzQkMldTI1M0MldTIwMUM4JXUyNTAwdyV1MDNCOSs_,inputs=MCUyQ3UlN0IlQjIlQjJ6KyUzQlclMjIldTIwN0VvJXUyMjJCazklRjcldTI1MDIlM0UldTAzOTMlN0IldTAzQzMlQUMldTAzQkMldTI1M0MldTIwMUM4JXUyNTAwdyV1MDNCOSs_,v=0.12): ``` 0,u{²²z+;W"⁾o∫k9÷│>Γ{σ¬μ┼“8─wι+ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 125 bytes + 87 matchsticks = 212 ``` ->m{v=->w,k{w.scan(/./).map &k};v[m,->t{v["!#&&;&=$(==&;&&;&;#;!$!$;&&#&!$!!&;&",->k{k.ord%11}][t.to_i 36].to_i+(t==?0?6:0)}].sum} ``` [Try it online!](https://tio.run/##xVHNTttAEL7zFJsNdhyyMV4bm0DlcKAVV6SqJ8uq3MSByHYc2U6gJKmEFFWqGqRU4pADUv@logoaCqFpRcShVd@DrHAeI92EBHiDrkY733zf7O7MrFd69nyYU4fJtFMpq8n0FrIqW7yfMQrcPD8f5x2jCFir9qCsOSiZDiplDUaiLMuw6iynqtRTY6JMZDYyS3GUpSBCKUiTrYrFu16WwbimawEfuE/zQFL0BBeo6oqwoiwL8ZrO@yWnNtRmANCgAJGiozGUJYiwMAkwxncKxiJES5MgRRdEYmoSbpq27dKDU3l9fXXtfui5G57hOPnCxnppZ8c2fXbVzZprrp2jV06zoiwXd4JI5AVE0wLmHl51G38//X75iLnq1v@8poXiST2x0eAcPrNpeP5oWJWqVYWCKMsLsiItKgr11BbEBUESJIpFmQKBUlCzbkcyBgnOupvLeCwxBEQF6whEwRJOUKhKsgj8jOuZt0//tz@LodTiuLTUYgKLsiri@6WZZcMGkFwcDU6O@r2j8PPHwd77fu80fEWZdnhy0d@7II02aXVI64w0z8nBD9I6H@H9zti@k2Z7ZJRpdEid2ilpjcLr9od@7@tg9yw8fEua766754P943D3W//kMGx/Id0eqV@Sg0tS/zXoHg6ax@HPTv9ND/KlQtHIWBx8Mgfj04@ykqKs1Pgb4TEVaFPyTVNyAqckVVRSk6Z03jQymyDrgmq@UCwFCJjbRTMTmNkqbdgz/ZIdABXktLGqU446H0CO8eOA8UEyTXcIGKBNc9XbG8AKgEXDp/IygDkjb0MEJo/cJOszZiE7/Ac "Ruby – Try It Online") Heavily inspired by [Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/160093/77973). Normally the cost of declaring a lambda to be used only twice is not worth it, but the matchstick weight of "`scanap`" in `.scan(/./).map` changed that. This was a fun challenge! ``` ->m{ v=->w,k{w.scan(/./).map &k}; # v is a lambda taking a string and a block v[m,->t{ # Transform each char t of the input: v["!#&&;&=$(==&;&&;&;#;!$!$;&&#&!$!!&;&", # Transform each char of this magic string ->k{k.ord%11} # into a matchstick count ([0,2,5,5,4,5...]) ][t.to_i 36]+ # Parse t as a base 36 index into the counts (t==?0?6:0) # If t was "0", add 6 matchsticks }].sum # Add the counts for all characters } ``` [Answer] # [Python 3](https://docs.python.org/3/), 138 + 265 = 403 bytes ``` k='0123456789abcdefghijlnopqrsuxyz' m=lambda t:sum([ord(''[k.index(v)])if v in k else 0for v in t.lower()]) ``` [Try it online!](https://tio.run/##JYrdCoMgAIUh08GewjvtJtraP/QksYuaulymTa3VXt4JgwPnOx9nXH1ndBlCX5Fity8Px9P5cm3aB@Pi2cmX0mZ8Wzct65dsh0o1Q8sa7G9uGmhtLKMEJRCmEIENQrFj0iQFIFICQVyk7nOpGV/onN0zKfCMpcY95spxXAhj/8Lnyny4pfETwg8 "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), score ~~166~~ 156 Code length 41 + output for code used as input 115. ``` '%p#21jgyDT7o?pe}['TIW:qZajk4Y22Y2h&mXz)s ``` [Try it online!](https://tio.run/##y00syfn/X121QNnIMCu90iXEPN@@ILU2Wj3EM9yqMCoxK9sk0sgo0ihDLTeiSrP4//@Aovz0osTc3My8dIWA0qqqnNRiBTUF5/yUVAX3/Jw0AA "MATL – Try It Online") [Answer] # R, 112 bytes + 319 matches = 431 score ``` sum(strtoi(el(strsplit(chartr("0-9a-z","625545637665455454240303455250300545",tolower(scan(,""))),""))),na.rm=T) ``` [Try it online!](https://tio.run/##xY1dCsIwEITvsk8bSCXkT3zwFl4grYEGkkY2K6KXr1vwDsLwzce8DO21zJTojS3z2u9D7ePZcDBxL5jrYeNRC@OyJmJCMNMlTR/QEG0IPkR3jlFa4q03zjhxG0SMTKC51/7KhGNJG2oApdSPWzpRu97@cPgF) Kudos to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) who came up with this improvement. Old version, 143 bytes + 454 matches = 597 score ``` b=el(strsplit(chartr("0123456789abcdefghijlnopqrsuxyz","6255456376654554542433455253545",tolower(readline())),"")) sum(as.numeric(b[b%in%0:9])) ``` To make the `el()` function work on TIO, you need to use `library(methods)`. Gosh dang it, is **R** verbose! [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 87 bytes + 26 matchsticks = 113 ``` {+[+] (~'򘮉򛫡񯌞𺪯񯉒񉘁'.ords~~m:g/\w/)[m:g/<[/..{]-[\W_]>/>>.&{:٣٦(~$_)}]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WjtaO1ZBo07904x1nZ9mr174cX3PvA@7Vq3/uL5z0sfOGY3qevlFKcV1dblW6fox5fqa0SCGTbS@nl51rG50THh8rJ2@nZ2eWrXVzcU3l2nUqcRr1sbW/i9OrFRI0wByFNLyi7jUDdR1uNRNjUGkoaEhhDICURZAAKIzUnNy8kGMgABndzBdlJ9elJibm5mXrhBQWlWVk1qsoKbgnJ@SquCen5MGUqKspqGZW6KoWAfiaLk83NFzbMnhNlfVhztajnSDbTy85PC2w3tALJAn0tOBrMKaaoiPNQh4WZNUP9dY/wcA "Perl 6 – Try It Online") Uses some non-ASCII Unicode characters. The lookup table is encoded in a Unicode string: ``` say '򘮉򛫡񯌞𺪯񯉒񉘁'.ords; # (625545 637665 455454 240303 455250 300545) ``` Characters are converted to indices with base-36 conversion using Arabic-Indic numerals: ``` :٣٦('z'); # is equivalent to :36('z'); ``` [Answer] # sed, 367 (source code bytes) + 532 (amount of matchsticks for the source code) = 899 ``` s/[^0-9a-jln-suxyz]//Ig;/^$/{s/.*/0/;b};s/.+/&; %1ir %%7lnu %%%4cfhjoy %%%%235bdegpqsxz %%%%%069a %%%%%%8/;:1;s/([^% ])(.+ (%+)[^ ]*\1)/%\3 \2/I;/ ;/!b1;s/;.+//;s/^/,;/;:2;s/(;[^%]*)(%+)/\2\1/;:3;s/,%{10}/%,/;s/^%/,&/;/%{10}/b3;/;.*%/b2;:4;s/,[;,]/,0,/;/,[;,]/b4;s/%{9}/9/g;s/%{8}/8/g;s/%{7}/7/g;s/%{6}/6/g;s/%{5}/5/g;s/%%%%/4/g;s/%%%/3/g;s/%%/2/g;s/%/1/g;s/[^0-9]//g ``` [Try it Online](https://tio.run/##NZDLboJAGIX3PMWYdgwgeBjwPkvbGHfuBRKpiBoEK5p4CV013bSP0Ydw36bv4YuUDpf@yeR8OTnnn@RP/LkeRIcsSzB1Db0/09dhpCeH4@nsAOOAw73HJUFThQHupVxgA3VOKFvtCKXdMDoIoa2nxXIdn3KkptX25n6wfU6O58KgRqc/K4n2wAdMbJGnLiWOIjcbRKYNZeoSR7WZAmpbxDYx5iAcNS@PcvEjhLrQuGibeZuLuqMqeRW2aTPhW8LX6IUZKahW5Cm0OjhKz7NEualSeCYftPLslGsONENkK/Zym176KfoICuyl6FXYTdGtsJOiU2E7RbtEMWj9I6yKYJYAVmhxY3HYIMsMqW1JjDHxTKknRlr6YRhLk8lwJE12cbCbbTarKCCTw/kc@gmpk2E898koDhfSXV1WNvta7UVSH27Xj5/Pr7dHeru@fr8bv/F2v4qjJNN3fw) Multi-line version: ``` s/[^0-9a-jln-suxyz]//Ig /^$/{s/.*/0/;b} s/.+/&; %1ir %%7lnu %%%4cfhjoy %%%%235bdegpqsxz %%%%%069a %%%%%%8/ :1 s/([^% ])(.+ (%+)[^ ]*\1)/%\3 \2/I / ;/!b1 s/;.+// s/^/,;/ :2 s/(;[^%]*)(%+)/\2\1/ :3 s/,%{10}/%,/ s/^%/,&/ /%{10}/b3 /;.*%/b2 :4 s/,[;,]/,0,/ /,[;,]/b4 s/%{9}/9/g s/%{8}/8/g s/%{7}/7/g s/%{6}/6/g s/%{5}/5/g s/%%%%/4/g s/%%%/3/g s/%%/2/g s/%/1/g s/[^0-9]//g ``` # Explanation: The above script reads standard input line by line (into the pattern space -- the usual "sed way") and, for each line, it outputs the amount of matchsticks necessary to represent all the matchstick-representable characters in that line. The computations for each line of input happen as follows: --- ``` s/[^0-9a-jln-suxyz]//Ig ``` First, we remove every character for which we don't have a corresponding matchstick representation (as given on the question) from the pattern space. That is, we remove every character which isn't either a numeral from "0" to "9", a letter from "a" to "j", "n" to "s", "l", "u", "x", "y" or "z". Uppercase and lowercase letters are treated the same. ``` /^$/{s/.*/0/;b} ``` If we end up with an empty pattern space, we print 0 (automatically followed by a newline, like sed always does unless you pass a special flag to it), skip all posterior lines of the script and proceed into next "sed cycle" (i.e., read the next line of input and repeat processing all over again from the first command until there are no more lines of input to be processed). ``` s/.+/&; %1ir %%7lnu %%%4cfhjoy %%%%235bdegpqsxz %%%%%069a %%%%%%8/ ``` Otherwise, if the pattern space is not empty, we now divide it into two "sub-spaces" separated by a semicolon: first comes the *input space*, which is initially formed by all characters which weren't removed from the pattern space after the execution of line 1; next comes the semicolon, and after it the *map space*. The map space tells us how many matchsticks beside 1 are needed to represent each relevant alphanumeric character. If we want to know how many matchsticks are necessary to represent any alphanumeric character in the map space, we look for the first sequence of contiguous %'s on the left of that character, and the answer will be the number of %'s in that sequence plus 1. So, for example, the number of matchsticks necessary to represent a "b" is 4 + 1 = 5; to represent a "4", 3 + 1 = 4, to represent a "y", 3 + 1 = 4; and so on. ``` :1 s/([^% ])(.+ (%+)[^ ]*\1)/%\3 \2/I / ;/!b1 ``` This is a loop. Now we will replace every character in the input space by the (complete) sequence of %'s whose number indicates the necessary amount of matchsticks to represent that character, and follow that sequence by a white space character (again, uppercase and lowercase letters are given the same treatment). The criterion to determine whether the loop should end is to check whether there's a white space character on the immediate left of the semicolon in the pattern space: if that condition holds, we terminate the loop and continue into the next line. ``` s/;.+// s/^/,;/ ``` Those two lines remove the semicolon and everything after it from the pattern space and then insert a comma and a semicolon into the beginning of the pattern space. We now have the pattern space divided once again into two new sub-spaces: the *analog result space* before the semicolon, and the *analog input space* after it. The analog input space is just what we have previously called the "input space", but in a different form: it now contains sequences of %'s separated by white space. The total number of such %'s in the analog input space is the same number of matchsticks necessary to represent the initial input character string, i.e., that number is the result. But we must print that result in decimal notation, not as a sequence of percent signs. The purpose of the *analog **result** space* is to hold an analog representation of each digit of the result while we compute that result by summing each contiguous sequence of %'s in the analog input space one by one. The next loop performs that sum: ``` :2 s/(;[^%]*)(%+)/\2\1/ :3 s/,%{10}/%,/ s/^%/,&/ /%{10}/b3 /;.*%/b2 ``` 1. First, after label **2**, we move the next contiguous sequence of %'s after the semicolon from the analog input space into the immediate left of the semicolon, in the analog result space; 2. Next, we step into a sub-loop (label **3**) which performs the following computations: * If there's a contiguous sequence of ten %'s after a comma in the analog result space, we remove those %'s and put a single % immediately at the left of the comma. To put it simply, this indicates that one of the decimal places in the result has acquired more than 9 units, so we take 10 units away from that decimal place and add 1 unit to the next larger decimal place; * If a "%" is the first character in the pattern space, we insert a new comma immediately before it. This indicates that the sum has reached a value whose decimal representation has one more decimal place on the left than the previous value; * If there are still any contiguous sequence of ten %'s in the analog result space, we go back to label **3** and repeat this process. Otherwise, we exit this sub-loop and step into the next line. 3. Now, if there is still any "%" in the analog input space (i.e., after the semicolon), it means that there is still some number of matchsticks to be added to the total sum -- so we go back to label **2**. Once the sum is complete, we step into the final loop of the code: ``` :4 s/,[;,]/,0,/ /,[;,]/b4 ``` Here, we check every pair of characters formed by a comma on the left and either a semicolon or a comma on the right. We replace all such pairs of characters by a "0" inside two commas. ``` s/%{9}/9/g s/%{8}/8/g s/%{7}/7/g s/%{6}/6/g s/%{5}/5/g s/%%%%/4/g s/%%%/3/g s/%%/2/g s/%/1/g ``` The above piece of code is quite simple: we replace each contiguous sequence of %'s in the analog result space by a decimal digit character which corresponds to the number of %'s in each particular sequence. ``` s/[^0-9]//g ``` Finally, we remove every non-numeral character from the pattern space and what remains is the final result in the familiar decimal notation. That value is printed on standard output and the next sed cycle begins, if there are any more input lines to be processed. [Answer] # [C (gcc)](https://gcc.gnu.org/), 134 bytes + 38 matchsticks = 172 ``` v(t,w)char*t;{t=(w=*t++)?v(t)+(isalnum(w|=w>'@'&w<'['?' ':!w)?")%(('()&*))('(('('%'#&#&'((%(#&##('("[w-=w>'`'?'W':'_'-'/']-'#':!w):w;} ``` [Try it online!](https://tio.run/##pZDPTsJAEMbP9imWbdqZLWwUjYkBARM0XLl5AKNNgdKkf0h3YRMQTsaLPoYPwV3je/AkdYuuXkncbLK/mflm880EPAyColigrCkWTP3ck82VbKFqebJaZR1dYFWMhB@n8wTVY0u14QpcdQkD6ACBRkWxDmUOIiBzPcb0qy84YLu2q9lBDbZO0YHiZfeD7ruFBtwDh2O442DvP2mo5rpYZNGIhFj6IJ5g1so6muVRKidIHUF4mzijYUprRNTIAgVjTWttWbpOEj9Kca8Pkf5vmOFB0wwPGIdqf6WfEwPnZ4bq9fofnhq80MfwdBzHmQn6/W7vl/MszP0kidKQ9OfLZTwWxCXdbDQmvSyeGJntIktkpbIxCe96t339fHt/vnF226ePl29Xs7kUSDnnRvazHROWWyx5XXwB "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes + 70 matches = 100 score ``` žLÃlv•Ƶγ¤и©X´≠Ø&c3Íε畞hA«ykèO ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6D6fw805ZY8aFh3bem7zoSUXdhxaGXFoy6POBYdnqCUbH@49t/XwcqDs0X0ZjodWV2YfXuFPmqYciK5afwA "05AB1E – Try It Online") --- -5 thanks to Emgina [Answer] # Java 10, ~~452~~ ~~432~~ ~~416~~ 404 score (145 bytes + 259 matches) ``` k->{int m=0,t;for(var w:k)for(t=m-m;t<'';)m+="1ir 7lnu 4cfhjoy 235bdegpqsxz 069a 8".split(" ")[t++].contains((char)(w|32)+"")?-~t:t-t;return m;} ``` **Explanation:** [Try it online.](https://tio.run/##lZPNThsxEMdvPeQpBlclNumu8gGFsk0RCohTo0gcWQ7OZpNs4o/Ung0kITkhLu1j9CG4t@I9eJLgBLgFVPtg2WP/xv/xzAz4mAeDznCZCG4t/OCZmhUAMoWp6fIkheZquzZAQpM@NxeXYFnkjPOCmyxyzBJogoI6LIfB99nqpqyXP2PU1YaOuYGrwyFbrbEuAxnht@KHYsRkqU4qmYF9oXLYTbr9gZ5AtbbX7qS90U97PYXyl68cDkhoRyJDSoCwCyyVLsNEK3QyLV3LYfTqplZlJULYUbDAQwwwMinmRoGM5stoJXKUt4UT@aJ1rLMOSOeBnqPJVM8FxNlzlOcTi6kMdY7hyB2hUFSFCSVlEqJuuNeOjeETytj6A96@v1fzBCqVijdR9SQO3PBE@qkQ2pNptRpnvojRPcOldMmAVj6ditTCNjR0J4UzLbqe3j5uUyZxa2vhye2cPN7/fvjz9@700@P97b9fvkn3K/74v6o/fi3/mED8fgPEJN7YAhujmBfmyyc) ``` k->{ // Method with character-array parameter and int return-type int m=0, // Result-integer, starting at 0 t; // Index-integer for(var w:k) // Loop over the input String-array for(t=m-m;t<'';) // Inner loop over the parts array with index [0,6) m+="1ir 7lnu 4cfhjoy 235bdegpqsxz 069a 8".split(" ")[t++] // If the current part ordered by amount of matches (2-8) .contains((char)(w|32)+"")? // contains the current (lowercase) letter -~t // Increase the result by the index + 2 : // Else: t-t; // The result remains the same by adding 0 return m;} // Return the result ``` * ~~Variable names `$ραετ` are used instead of letters.~~ EDIT: Variable names `kmtvw` are now used instead, because they can't be formed by matches according to the challenge description. * `''` (unprintable) is used instead of `6`. * `m-m` and `t-t` are used instead of `0`. * `(char)(w|32)+""` with character-array input used instead of `w.toLowerCase()` with String-array input. [Answer] # [AutoHotkey](https://autohotkey.com/docs/AutoHotkey.htm), 148 bytes + 345 matchsticks = 493 This one was a bit of a challenge to shorten. ``` n:=["1ir","7lnu","4cfhjoy","235bdegpqsxz","09a5",7+1] Loop Parse,i {r:=A_LoopField Loop % n.Length() {l:=A_Index if InStr(n[l],r) u+=l+1 }} send % u ``` [Answer] # [Python 3](https://docs.python.org/3/), 123 bytes + 65 matches = 188 ``` lambda w,m='',t='',k=ord:sum(~-k((m+t+m+''+t)[k(v)%77])*('/'<v<'{')for v in w) ``` An unnamed function accepting a string and returning an integer. Contains many non-printable characters (specifically bytes one to eight). **[Try it online!](https://tio.run/##dVDNTsJAEE5Df4SnWDA4u7QoSAyGUC9ouHJXDygtNOy2pF1KxIST8aKP4UNw1/gePEndaSUkJk42@8337Tc7s7t4krMo7GSP0cRzASDjY/EwGZOVI1zQdMM0S6ama5ppmOBIJeVhKaqWUTI0HZy5G8WTXrIUdNOcUypsaQtbOa0Smiz9yNLAlux2TlNW73bvWYPCGfTTPjwD86OYpCQIyYplqn8FByEuQThNZBwsKNyFwCq@66VjTlFXRBVJL5FYR2utmkNqFx3c2@12AecIlyoQZx7nESaj0WCYYxxN47EQQTglo@V6zb2EnJABth5G3EfL8QllQlarGySN6932/fvj8/Wmvtu@fL1hx5aTD8l6lXLg59OobJ8St3gCSuVFHISSouwQaF6BQ7gXFi9Rgq24n58icw@M2AcfU/d4PPnvvt8K5dqbCo/6uuafyD8z@wE "Python 3 – Try It Online")** [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes + 3 = 51 ``` IΣEθ⎇№α↥ιI§”)➙⊞←!Σw➙⊙↘⁴↘”⌕α↥ι∧№IX²φιI§”)⧴u↑$◨”Iι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEchJLUoL7GoUsM5vxQom6ijEFpQkFqUnFicqpGpqamjAFbvWOKZl5JaoaFkZmpiCkQmRiYGxgbGQLaRKZBhABRS0lFwy8xLwTABZIYjUBxiPti0gPzy1CINIx0FQwMDA5B8JqY9RiBrzIzNzZSgUmCjQMD6///3e1aeW/x@z9JzOx71tT9qmXZu46O2ped2AoUPLX/UMFfz0byZj7rmPWqboHhucTmYM/NR24xHjVtAZMPcRz1ToToedSwHagfqe79nx6FN59uQzVi@pfRR20SVR9NXALkgG3f@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` IΣEθ ``` Loop over the characters of the input, calculating the number of matchsticks of each, then sum the result, convert to string, and implicitly print. ``` ⎇№α↥ι ``` If it's a letter... ``` I§”)➙⊞←!Σw➙⊙↘⁴↘”⌕α↥ι ``` Look up the number of matchsticks in the compressed string `65455454240303455250300545`. ``` ∧№IX²φι ``` Else if it appears in the value of `2 ** 1000`... ``` I§”)⧴u↑$◨”Iι ``` Look up the number of matchsticks in the compressed string `6255456376`. [Answer] # PHP, 98+253=351 ``` for(;$k=ord($argn[$v++]);)$m+=$k>64?_65455454240303455250300545[$k&31]:_6255456376[$k-47];print$m; ``` Run as pipe with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/42f0db179dcf858be62bdd9962c814f75e2d7ecd). ]
[Question] [ This challenge is inspired by [this](https://codegolf.stackexchange.com/q/156856/31516), now deleted question. --- Take a positive integer **N** as input, and output a matrix with the numbers **1 .. N2** that follows the pattern below: Fill in the first row with **1 .. N** then fill the last row (row number **N**) with **(N+1) .. 2N**, then fill the second row with **(2N+1) .. 3N** and continue until you have filled all rows. The output format is flexible, so list of lists etc. are accepted. ``` N = 1 1 N = 2 1 2 3 4 N = 3 1 2 3 7 8 9 4 5 6 N = 4 1 2 3 4 9 10 11 12 13 14 15 16 5 6 7 8 N = 5 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 16 17 18 19 20 6 7 8 9 10 ``` Standard rules apply. Shortest answer in bytes in each language wins. Explanations are encouraged as always. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 8 bytes Saved 5 bytes thanks to *Rod* ``` nLô«āÉÏ ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/z@fwlsNNh1YfaTzcebj//38zAA "05AB1E – Try It Online") **Explanation** ``` n # push input^2 L # push range [1 ... input^2] ô # split into pieces each the size of the input « # append the reverse of this 2D-list ā # push range [1 ... len(list)] É # check each element for oddness Ï # keep only the elements in the 2D list which are true in this list ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 53 bytes ``` ->n{r=*1..n*n;n.times{|x|p r.slice!(r[x*=n]?x:-n,n)}} ``` ## Explanation: Put all the numbers into a single array first, then slice the array skipping a line for each iteration. After the first (n/2+n%2) iterations there is nothing left to skip, then get all the remaining lines backwards. [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vushWy1BPL08rzzpPryQzN7W4uqaipkChSK84JzM5VVGjKLpCyzYv1r7CSjdPJ0@ztva/BlC9qaZebmIBSGladEWsdUFpSbGCuq6urnrtfwA "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 75 bytes ``` def f(n):a=range(n);print[[i*n-~j for j in a]for i in a[::2]+a[~(n%2)::-2]] ``` [Try it online!](https://tio.run/##JcyxCoAgFEDRX3lLoJWQji/6EnEQ0tLhGdJQi79uWduBC/e4zz2RqnV1HjwjjnbJljb3cj5yoFPr0JMoEXzKECEQWNMYPmpEZQarC6NOcUShjKktXy3/JznKiaNnF68P "Python 2 – Try It Online") [Answer] # JavaScript, 68 bytes *Edit* 3 bytes saved, whetted by @user71546 ~~First try,~~ following the obvious route: count from 1 and fill the array from both sides, from outer to inner ``` n=>(v=0,q=[...Array(n)]).map((_,i)=>q[i&1?--n:i/2]=q.map(_=>++v))&&q ``` **Test** ``` var F= n=>(v=0,q=[...Array(n)]).map((_,i)=>q[i&1?--n:i/2]=q.map(_=>++v))&&q function test() { var n=+N.value; O.innerHTML = '<tr><td>' +F(n).map(r=>r.join('</td><td>')).join('</td></tr><tr><td>') +'</td></tr>' } test() ``` ``` #O { margin: 1em } td { text-align: right } ``` ``` <input id=N type=number min=1 value=5 oninput='test()'> <table id=O> ``` [Answer] # [Haskell](https://www.haskell.org/), 62 bytes ``` (0#) m#n|m>=n^2=[]|k<-m+n=[m+1..k]:(k+n)#n++[[k+1..k+n]|k<n^2] ``` [Try it online!](https://tio.run/##TY1LT4NAFIX391eclA1kAuEOjxbjsHGrpokbE4oJMaLNMBPS4sr618VhsImb@zjnfud@dGf9NgxzD3WYwzSIyAT2YmplX6Rq2ou@jY2wqjGCk0S3N6EWNgqsEE2jvSTscuSu29l0RwsF040PCMO6Hj@np@l0bzebCMkqj6ejndzSR2gcXbREXzE9OoqJyQ@SGK5kQL4KmRfg@hbYARXlQAGUq50T/vyFQAVOwQx2ORk4BxfgkjwALAkrVvzHXB55BleGJENKyAwyh3RuCd6Cd@AKMqVrFvw/ir/nn9d@6N7Pc/x8t9//Ag "Haskell – Try It Online") Output is a list of lists, e.g. `(0#) 3` yields `[[1,2,3],[7,8,9],[4,5,6]]`. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~51+3=54~~ 47 bytes ``` :&v ?!\1-:&:&*}}r: ~\ !~>1+::n&:&%:a84*@@?$~o? ``` [Try it online!](https://tio.run/##S8sszvj/30qtjMteMcZQ10rNSk2rtrbIikuhLoZLsc7OUNvKKg8oqGqVaGGi5eBgr1KXb////3/dMgVTAA "><> – Try It Online") Input is expected on top of the stack at program start using the `-v` flag. Output consists of non-aligned numbers separated by single spaces, and each line is separated by a single newline. Example output for `N=5`: ``` 1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 16 17 18 19 20 6 7 8 9 10 ``` ... followed by a single newline. Program terminates with an error (`something smells fishy...`), but that's on STDERR rather thatn STDOUT. **Explaination:** The first line simply stores a copy of `N` in the register. The second line builds up the offset for each output row by subtracting 1 from `N`, multiplying this by `N`, rotating it to the bottom of the stack and then reversing the entire stack. When the number on top of the stack reaches 0, the stack should look like this (example uses `N=5`): ``` 5 15 20 10 0 0 ``` The third line discards the duplicate `0` from the top of the stack. The fourth line increments the top of the stack and outputs a copy of it. This is then taken mod `N`, and this is used to decide if a space or newline should be printed, and if the top of the stack should be discarded - if last number printed is `x`, then `x mod N == 0` indicates that the end of that output row has been reached. Execution ends when `1+` gets executed on an empty stack, throwing the termination error. **Previous version** This explicitly checked for an empty stack to end execution, and I was also including 3 bytes for the `-v` flag usage. ``` :&v ?!\1-:&:&*}}r: ~\ !;>1+::n&:&%:a84*@@?$~o?!~l? ``` [Try it online!](https://tio.run/##S8sszvj/30qtjMteMcZQ10rNSk2rtrbIikuhLoZL0drOUNvKKg8oqGqVaGGi5eBgr1KXb69Yl2P///9/3TIFYwA "><> – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), `-p` ~~52~~ 51 bytes ``` #!/usr/bin/perl -p map{$|--?$\="@0 ".$\:say"@0";$_+=@0for@0}@0=1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqmCqZ2igZ2D9PzexoFqlRlfXXiXGVsnBgEtJTyXGqjixEshWslaJ17Z1MEjLL3IwqHUwsDXU01OJr63@/9/0X35BSWZ@XvF/3QIA "Perl 5 – Try It Online") [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 101 bytes ``` n->{int x[][]=new int[n][n],i=0,j;for(;i<n;i++)for(j=0;j<n;)x[i%2<1?i/2:n+~i/2][j]=++j+i*n;return x;} ``` [Try it online!](https://tio.run/##dY8xT8MwEIX3/IpbkJKmDW0lBuq4iAWJgaljlMG0SXUmPUeOU1pV4a@HMzUwICRL53v33vmzVkc1M21Fevd2P@KhNdaBZjHrHTbZRER/tLqnrUNDftj2rw1uYduoroMXhQSXCKBzyrHKN4Bnck8hkCO5oizKNdQgR5qtLyzAyUuSqnfwYyr5TFHOp1rUxsYCcxKYpolvtJwLzX1yKvBmmS8e8Ha5ovSDS1noUqapTnFCwlautwQnMYyCIQJkoDoa3MGBUeONs0j7ogRl913yRQ7A70DsuQgkLASXXMIdV2YIFoDwEQ5adWZfnam2bc4xJSI4vtd40@rq@40DbM6dqw6Z6V3WMoRrKH70ni5z5ooVq@Rn2RD9mwoe7xiiYfwE "Java (OpenJDK 9) – Try It Online") ### Credits * -4 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). [Answer] ## JavaScript (ES6), ~~69~~ 68 bytes ``` n=>[...Array(n)].map((_,i,a,j=((i*=2)<n?i:n+n+~i)*n)=>a.map(_=>++j)) ``` ~~Well it got outgolfed before I could post it but here it is anyway.~~ Edit: Saved 1 byte thanks to @KevinCruijssen. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ²ss2Ṛj@/Fs ``` [Try it online!](https://tio.run/##y0rNyan8///QpuJio4c7Z2U56LsV/zc0UDjc/qhpjYI7iMh61Ljv0LZD2/4DAA "Jelly – Try It Online") ### How it works ``` ²ss2Ṛj@/Fs Main link. Argument: n ² Square; yield n². s Split; promote n² to [1, ..., n²] and split it into chuks of length n. s2 Split 2; generate all non-overlapping pairs of chunks. If n is odd, this leaves a singleton array at the end. Ṛ Reverse the order. j@/ Reduce by join with reversed arguments. In each step, this places the first and second element of the next pair at the top and bottom of the accumulator. Fs Flatten and split to restore the matrix shape. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` │æ╘▐⌡r▌═∟Y ``` [Run and debug it online](https://staxlang.xyz/#c=%E2%94%82%C3%A6%E2%95%98%E2%96%90%E2%8C%A1r%E2%96%8C%E2%95%90%E2%88%9FY&i=1%0A4%0A5%0A12&a=1&m=2) The corresponding ascii representation of the same program is 12 characters. ``` JRx/r{]+rFmJ ``` Here's how it works. ``` JR range [1 .. x^2] where x=input x/ split into subarrays of size x r reverse { F for each subarray, execute block ]+r concat array, and reverse result m for each row, output ... J each subarray joined by spaces ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~...~~ 6 bytes Thanks [*JonathanAllan*](https://codegolf.stackexchange.com/users/53748) for -1 byte! ``` ²sm0m2 ``` [Try it online!](https://tio.run/##y0rNyan8///QpuJcg1yj////mwIA "Jelly – Try It Online") --- Use an identical algorithm to the 05AB1E answer. [Answer] # [R](https://www.r-project.org/), ~~70~~ ~~59~~ 47 bytes ``` function(n)matrix(1:n^2,n,,T)[c(1:n,n:1)*!0:1,] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPMzexpCizQsPQKi/OSCdPRydEMzoZxNPJszLU1FI0sDLUif2fpmGoyZWmYQQijEGECYgw1fwPAA "R – Try It Online") Thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for a 4 byte golf, which I then golfed further. Returns a matrix; constructs the `matrix` in sequence, e.g., `[[1 2 3] [4 5 6] [7 8 9]]`, then rearranges the rows. [Answer] # [Python 2](https://docs.python.org/2/), ~~72~~ ~~68~~ 63 bytes -4 bytes thanks to Neil ``` def f(n):w=zip(*[iter(range(1,n*n+1))]*n);print(w+w[::-1])[::2] ``` [Try it online!](https://tio.run/##NcsxDoAgDADAr3RsQQcYHDC@hDCYCMpSCCEB/Ty6ON10@a5XYj3G4QMEZDJte2JGYWP1BcvOp0c1sWCpiJxgWnOJXLHJZo2ZlaMP7UZIBTpEhr8sZAJ2Gi8 "Python 2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 102 bytes ``` n=input('');A=B=vec2mat(1:n*n,n);i=j=0;do B(++i,:)=A(++j,:);if++j<n B(n-i+1,:)=A(j,:);end;until j>=n B ``` [Try it online!](https://tio.run/##JcoxCoQwEEbhfk9hZ2IUdGEbxxH0JqIRJri/FtHrx0G7B9/b5zhdPiWw4DijyXNLA498@fn7n6JpWhQoYUk4cE3L/hmNc1K2lgeNoEGyanRQQSWuee0Rj4VORNmy0LMOKf1u) [Answer] # [C (gcc)](https://gcc.gnu.org/), 110 bytes ``` i,c,t,b;f(a,n)int*a;{for(b=n-1;i<n*n;t++,b--){for(c=0;c<n;)a[t*n+c++]=++i;for(c=0;c<n&i<n*n;)a[b*n+c++]=++i;}} ``` [Try it online!](https://tio.run/##bdLNioMwEAfwu09RhC6JidD4CZuGfRDrIaZYctjpUsJeis/uRrOW7DrixZnkNyP8TX4zZp4tN9zxQY5Ec6AWXKblc7w/yKAgF9KeIQPpGONDntO1YdRJmjNIqjuXATOM9YoxK6PeW7jmTwzxiWma/YDDp7ZAaPJMDv5ZCqCEfH1o0UHv31AZCVl2olr47ULp6@Erf8vhsnJ@OqgisorO7/GfKnCq2FNlRJUYVeJUuaeqiKowqsKpak/VEVVjVI1T9Z5qIqrBqAanmj3VRlSLUS1OhfKUJN93e/1trTHkIRtbUJZ4WT/JR0taxuha3BpbJk3ceI0aSXq8Hk3KdWeXPPbc5MDER1m8i9P2H9vJC1wgXTaafwA "C (gcc) – Try It Online") Fills out an array by alternating between 2 indices for rows: one index starting at the top and one starting at the bottom. The top row index starts at 0 and is incremented every 2 rows; the bottom row index starts at n-1 and is decremented every 2 rows. Ungolfed: ``` void f(int* a, int n) { //i = value to be written [1,n]; c = column index; t = top row index; b = bottom row index for(int i=1, c=0, t=0, b=n-1; i <= n*n; //when i = n*n, we have written all the values and we're done t++, b--) //t increments every 2 rows, b decrements every 2 rows { //write out 2 rows per loop //first row: fill out row at t for(c=0; c<n; c++, i++) a[t*n+c]=i; //second row: fill out row at b //this step will be skipped on the final loop for odd values of n, hence the (i<=n*n) test for(c=0; c<n && i<=n*n; c++, i++) a[b*n+c]=i; } } ``` [Answer] # C++ + [Range V3](https://github.com/ericniebler/range-v3/tree/1a9701d619d9d073151ccf86e37a8e6afb1a732c), 159 bytes ``` #include<range/v3/all.hpp> using namespace ranges::view; [](int n){auto r=iota(1,n*n+1)|chunk(n);return concat(r|stride(2),r|reverse|drop(n%2)|stride(2));} ``` [Live on Wandbox](https://wandbox.org/permlink/aw2GhEbmt2PN3Sey) Not counting the 2 newlines after `using namespace range::view`; they are just there to separate imports from the lambda. Mildly interesting fact: this solution makes no heap allocations. It solves the problem in `O(1)` space. --- Explanation: 1. `iota(1, n*n+1)` -> `[1 ... n*n]` 2. `chunk(n)`: every `n` elements together, so `[1 ... n] [n+1 ... 2*n] ...` 3. Call that `r` 4. `r | stride(2)`: take every other element: `[1 ... n] [2*n+1...] ...` 5. concatenate that with: 6. `r | reverse | drop(n % 2)`: reverse, then drop the `[1 ... n]` term if `n` is odd (there'll be an odd number of rows and we only want to print the first term once). It seems like I should be able to just do `r | reverse | take`, but that doesn't work for some reason. 7. `stride(2)` again, take every other element. This time it's in reverse. More readable, and testable: ``` #include <range/v3/all.hpp> using namespace ranges::view; auto f(int n) { auto rows = iota(1, n * n + 1) | chunk(n); return concat( rows | stride(2), rows | reverse | drop(n % 2) | stride(2)); } #include <iostream> int main(int argc, char** argv) { std::cout << "N = " << argc << '\n'; auto res = f(argc); for (auto const& row : res | bounded) { for (auto const& elem : row | bounded) { std::cout << elem << ' '; } std::cout << '\n'; } } ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Anonymous tacit prefix function. ``` (⍋1∘+|-\⍤⍳)⊇,⍨⍴∘⍳×⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRb7fho44Z2jW6MY96lzzq3az5qKtd51Hvike9W4DiQIHD04G8/2mP2iY86u171NX8qHcNUO7QeuNHbRMf9U0NDnIGkiEensH/0xQMuXR1dbnSFIygtDGUNoHSpgA "APL (Dyalog Extended) – Try It Online") `×⍨` self-multiplicate (i.e. square **N**) `∘⍳` **ɩ**ndices one through that, then:  …`⍴` **r**eshape to the following shape:   `,⍨` self-concatenate (i.e. \$N\$-by-\$N\$ matrix) `(`…`)⊇` permute the rows into the following order:  `∘⍳` **ɩ**ndices one through \$N\$, then   `-\` alternating sum; \$\big\{1,(1-2),(1-2+3),(1-2+3-4),…,(1-2+3-…\pm N)\big\}=\Big\{1,-1,2,-2,…,\pm\big\lfloor\frac{N}2\big\rfloor\Big\}\$  …`|` division remainder when divided by:   `1∘+` the incremented \$N\$  `⍋` grade (permutation that would sort) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` s2ZU2¦Ẏị²s$ ``` [Try it online!](https://tio.run/##y0rNyan8/7/YKCrU6NCyh7v6Hu7uPrSpWOX///@mAA "Jelly – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 22 bytes ``` ri__*,:)/2/z[1W].{%:p} ``` [Try it online!](https://tio.run/##S85KzP3/vygzPl5Lx0pT30i/KtowPFavWtWqoPb/fxMA "CJam – Try It Online") [Answer] # C (gcc) ~~80~~ ~~78~~ I see now this solution is wrong ``` i;f(n){for(i=0;i++<n*n;printf("\n%3d"+!!(~-i%n),i>n?n+(i+n>n*n?i%n?:n:i):i));} ``` [Try it online!](https://tio.run/##HcqxCsJAEITh3rdIILDrGoiJNlnNvYhNOLmwhaMEuxBf/VwOhq8Y/tguMeZsmgi8pfdKdu/URG44Qj@r4ZuofqAZnrVUFf1aa8AnmxAgZILJu@BfGDEa@1j3/JoNxNsh0ZnV7YtD8VK8unv@Aw) [Answer] # [C (gcc)](https://gcc.gnu.org/), 36+8+61 = 105 bytes compile with `-Dp=printf("%d ",i),i++%n;);puts("")` `-Dq=i,n)` ``` f(q{g(1,i);}g(q{for(;p;i<n*n&&h(q;}h(q{for(n+i<n*n&&g(n+q;p;} ``` [Try it online!](https://tio.run/##RY3BCsIwDIbve4pR2EjddtCbxN58DC@j0i6gsd3mafTVrSlMvISfL/@X2MFbm7ODuHk49qQxecnuNQMGpAsfuG0niJimHXO3Uy8xSinl50gMeqvKmnityZxEPSN1ndAwC3OgmvuNVflQOSgzvNcFlJKUqpQ/1j1Gv@ThGszfqIvQy52GUePPkFI01LP@Ag "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs a 3D array; add `c1` at the end for `+2` bytes to flatten by one level. ``` ²õ òU ó oÔ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=svUg8lUg8yBv1A&input=NQotUQ) ]
[Question] [ Lets say your job is to paint poles, and a client asks you to paint a pole with 4 red sections and 3 yellow sections. You can do that pretty easily as follows: ``` r y r y r y r ``` With just yellow and red stripes. Now lets say your client asks you to paint a pole with 2 red sections, 2 yellow sections, and *1 green section*. There are a couple of ways you could paint your pole ``` g y r y r y g r y r y r g y r y r y g r y r y r g g r y r y r g y r y r y g r y r y r g y r y r y g y r g r y r y g y r ``` More precisely thats 12 ways to paint the pole. This blows up the more colors and sections that are involved Now if your client says they want 3 red sections and 1 yellow section there is no way to paint a pole like that. Because no matter how you attempt to arrange the sections two red sections will touch, and when two red sections touch they become a single red section. And that is pretty much our one rule for painting poles > > Adjacent sections may not be of the same color > > > ## Task Given a list of colors and sections required, output the number of possible ways to paint a pole as requested. You may represent colors in any reasonable way (integers, characters, strings), but you will never be given more than 255 different colors at a time. If you wish you can even choose to not have the colors assigned names and just take a list of section counts if that is easier. ## Test Cases These are rather hard to calculate by hand, especially as they get larger. If anyone has a suggested test case I'll add it. ``` [4,3] -> 1 [2,2,1] -> 12 [3,1] -> 0 [8,3,2] -> 0 [2,2,1,1]-> 84 ``` [Answer] # Mathematica, 37 ~~44~~ ~~48~~ ~~60~~ ~~62~~ bytes Take input as a list of integers `{1, 1, 1, 2, 2}`. Try it on [Wolfram Sandbox](https://sandbox.open.wolframcloud.com). ## Pattern-matching method, thanks @Not a tree ! ``` Count[Split/@Permutations@#,{{_}..}]& ``` `Split` splits a single list into sublists of consecutive elements, e.g. `{1, 1, 2, 3, 4, 4}` into `{{1, 1}, {2}, {3}, {4, 4}}` `{{_}..}` is, namely, `{{_}, {_}, {_}, ...}`. The pattern matches a list of unary sublists. ## `Differences` method, 48 bytes: ``` Tr@Abs@Clip[1##&@@@Differences/@Permutations@#]& ``` The code uses `Differences` to determine whether adjacent elements are the same. Step by step: 1. `Permutations@#` generates all permutations of input list to a N!\*N list. 2. `Differences/@` calculates the difference between N elements, and yields a N!\*(N-1) list. 3. `1##&@@@` calculates the multiplication of all lists. If a list contains `0` (two adjacent elements are the same), the result will be `0`, otherwise non-zero, to a N! list. 4. `Clip[]` acts like `Sign[]`, transform the list from (-inf, inf) to [-1, 1] 5. `Tr@Abs` turns all `-1` into `1` and now the N!-length list contains only `0` (invalid) and `1` (valid). So we just sum the list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Œ!QIẠ€S ``` [Try it online!](https://tio.run/##y0rNyan8///oJMVAz4e7FjxqWhP8////aEMdCDQCwVgA "Jelly – Try It Online") Takes input as e.g. `[1,1,1,1,2,2,2]` for `[4,3]`. The `[8,3,2]` testcase takes too long to run on TIO. **How it Works** ``` Œ!QIẠ€S - main link, input as a list Œ! - all permutations Q - remove duplicates I - take increments (returns a 0 for two adjacent identical numbers) Ạ€ - apply “all” atom to each: 0 for containing 0 and 1 otherwise S - sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` œÙ€¥PĀO ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6OTDMx81rTm0NOBIg////9GGOgpAZARGxjoKJrEA "05AB1E – Try It Online") -1 thanks to [nmjcman101](https://codegolf.stackexchange.com/users/62346/nmjcman101) on another answer. [Answer] ## Mathematica, 50 bytes ``` Expand[1##&@@(LaguerreL[#,-1,x](-1)^#)]/._^i_:>i!& ``` [Try it in Mathics](https://tio.run/##y00sychMLv6fZvvftaIgMS8l2lBZWc3BQcMnMb00tago1SdaWUfXUKciVkPXUDNOWTNWXy8@LjPeyi5TUe1/QFFmXolDmkO1qY6ZjrmORe1/AA "Mathics – Try It Online"), or at the [Wolfram sandbox](https://sandbox.open.wolframcloud.com/)! Takes input like in the test cases — e.g. `{4,3}` means "4 red stripes, 3 yellow stripes". This is a naïve implementation of a formula I found [here](https://artofproblemsolving.com/community/c6h266534). "Naïve" means "I have no idea how the maths works so please don't ask me for an explanation…" [Answer] # [Python 3.5](https://docs.python.org/3/), 65 bytes ``` f=lambda s,p=0:sum(f(s.replace(c,'',1),c)for c in{*s}-{p})or''==s ``` [Try it online!](https://tio.run/##PYyxDsIgFEV3voINMGg0bk0Y6@riDwClKQmFlwdVm6bfjujgWU5OcnNhLVOK11pHFfRsBk2zBHXu8jLzkecTOgjaOm4lY/IipBVjQmqpj9sh78cNdpGQMaVyLbh2hL4mHxx94OJaUEAfSztyTx24j7AULhrEva2DQvv7rUdM2Kagc65MN4wxjLCv7c/6nwMjHw "Python 3 – Try It Online") [Answer] # Ruby 2.4, 47 bytes Input is a list of characters: For the test case `[4,3]`, input can be `%w[a a a a b b b]`, `"1111222".chars`, or some other array formatting method that's valid in Ruby. ``` ->x{x.permutation.uniq.count{|a|a*''!~/(.)\1/}} ``` Requires 2.4 for `Enumerator#uniq` (earlier versions only had it available on the `Array` class). As such, the TIO link adds 5 bytes to convert the permutation enumerator to an array first via `to_a`, since it does not have the above function. [Try it online!](https://tio.run/##KypNqvyfZhvzX9euorpCryC1KLe0JLEkMz9PryQ/PlGvNC@zUC85vzSvpLomsSZRS11dsU5fQ08zxlC/tvZ/gUJadGpZYo5CempJcex/1fLoRIVEhSQgTI4FAA "Ruby – Try It Online") [Answer] # R, 72 bytes ``` pryr::f(sum(sapply(unique(combinat::permn(x)),pryr::f(!sum(!diff(x)))))) ``` Creates the function ``` function (x) { sum(sapply(unique(combinat::permn(x)), pryr::f(!sum(!diff(x))))) } ``` Takes input in the form `[1,1,1,1,2,2,2]` as per Erik the Outgolfer's comment. Uses `combinat`'s `permn` function to create a list of all permutations, and then `unique` to get all distinct entries. `sapply` then applies the following function on all entries: ``` pryr::f(!sum(!diff(x))) ``` Which evaluates to ``` function (x) !sum(!diff(x)) ``` Note that this `x` is not the same as the `x` in the big function's input. Using another character in this function would fool `pryr::f` into believing the big function needs another argument. Anyways, when given a permutation, this function takes the difference between the vector: `2 1 3 4 2 1 -> -1 2 1 -2 -1`. `!` converts nonzero's into `FALSE` and zeros into `TRUE`, so the vector becomes `FALSE FALSE FALSE FALSE FALSE`. Summing that to check if there are any `TRUE`s (`TRUE` would imply `diff=0` --> two the same consecutive numbers). We can again invert this with `!` to get a boolean on whether or not there are consecutive values in the permutation. Summing over these booleans gives us the total number of permutations where this is not the case. Doesn't work for the `[8,3,2]` testcase because it requires a vector of 46GB to store those permutations. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Œ!Q⁻2\Ạ$ÐfL ``` [Try it online!](https://tio.run/##y0rNyan8///oJMXAR427jWIe7lqgcnhCms////@jDXUUgMgIjIx1FExiAQ "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~140~~ 89 bytes Input format is `'aaaabbb'` for test case `[4,3]`. ``` lambda s:len({p for p in permutations(s)if all(map(cmp,p,p[1:]))}) from itertools import* ``` [Try it online!](https://tio.run/##PYq7CgIxEEX7fMV0ScRGywXLtbWxU4tkTdhAHsNkFl3Eb4/RwnuKw4GLK88l75s/XFs0yd4N1CG6rF4IvhAghAzoKC1sOJRcVdXBg4lRJYNqSrjtXHbDTeu3Fp5KgsCOuJRYISQsxJvGtA4CHnOIDs60uB6AFDKDVyHjwkpr4Z6TQ4bxdByJCvUPmlqbNH3WWink19PP5p93KT4 "Python 2 – Try It Online") [Answer] ## [Husk](https://github.com/barbuz/Husk), 8 bytes ``` #ȯ¬ṁtguP ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8dC2/8on1h9a83BnY0l6acD///8TgSApKYkLRCZzgTgQZgoA "Husk – Try It Online") Takes input in the format `"aaabb"` for `[3,2]`. Times out on the longest test case. ## Explanation Nothing fancy here, just counting the unique permutations where all groups of adjacent elements have length 1. ``` #ȯ¬ṁtguP P Permutations. u Remove duplicates. #ȯ Count how many satisfy the following condition: g group adjacent elements, ṁt concatenate tails of groups ¬ and negate. ``` [Answer] # Ruby, ~~84~~ 76 bytes ``` f=->a,x=p{i=s=0;a.map{a[i-=1]-=1;a[i]<0||i!=x&&s+=f[a,i];a[i]+=1}.max>0?s:1} ``` A recursive lambda function. Looks at each possible color and dose a recursive tree search, counting the number of times it uses all stripes. ### Explanation (for old version): ``` f=-> a, # a is the input array in [3,3,4] form x = -1 # x is the last color placed (-1 when run normaly, used in recursive calls) { j = i = s = 0; # i is the index # s is the sum of valid final patterns (the answer) # j is used to count the total stripes a.map{|e| # Iterate over array of colors a[i] -= 1; # remove a stripe of current color (the array will be used in recursive call) s += f[a,i] if i!=x && e>0; # add to sum recursively if: # we are not using the same color as the last color AND # we have stripes of the current color left to paint a[i] += 1; # replace the stripe we removed above j += a[i]; # add stripes to j i+=1 # increment the index }; # End loop j == 0 ? 1 : s # if we had stripes, give the recursive sum, otherwise return 1 } ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ 8 bytes ``` Y@Xu!dAs ``` Input format is `[1 1 1 1 2 2 2]` for `[4 3]`, etc. Runs out of memory for the last test case. [**Try it online!**](https://tio.run/##y00syfn/P9IholQxxbH4//9oQwVDBSMgNFYwiQUA "MATL – Try It Online") ### Explanation ``` Y@ % Implicit input. Matrix of all permutations. Each row is a permutation Xu % Unique rows ! % Transpose d % Consecutive differences along each column A % All: true for columns such that all its entries are nonzero s % Sum. Implicitly display ``` ]
[Question] [ Disclaimer: **No, this is not a joke challenge to reverse a string.** # Task There is only one operation to support: subtraction (`-`). You also only have two atoms to support: zero (`0`) and one (`1`). Here, the prefix notation `-AB` is equivalent to the postfix notation `AB-`, where `A` and `B` are expressions. Your task is to (recursively) convert an expression in prefix notation to its equivalent in postfix notation. # Definitions An expression in prefix notation is generated by the following grammar: ``` S > -SS S > 0 S > 1 ``` An expression in postfix notation is generated by the following grammar: ``` S > SS- S > 0 S > 1 ``` # Example ``` Prefix notation: --01-0-01 Parentheses: -(-01)(-0(-01)) Convert: (01-)(0(01-)-)- Postfix notation: 01-001--- ``` # Rules and freedom * You may rename the operation and the atoms to whichever character, as long as it is consistent. * The input format must be consistent with the output format (apart from the fact that the input is in prefix notation and the output is in postfix notation). # Testcase ``` Input Output 1 1 0 0 -01 01- -10 10- --01-0-01 01-001--- ``` Testcases credits to [Dada](https://codegolf.stackexchange.com/a/119764/48934). [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 32 bytes ``` ,[[->++++<<+>]>[[-]<<[.[-]<]]>,] ``` [Try it online!](https://tio.run/nexus/brainfuck#@68THa1rpw0ENjbadrF2QF6sjU20HoiKjbXTif3/38HBwNDBAEgAAA "brainfuck – TIO Nexus") I used `@` as the operation, because its code point (64) is convenient. `U` is also possible with the same byte count, using 3\*85+1=256=0. ### Explanation The tape is used as a stack. In each iteration of the main loop, the data pointer starts two cells right of the top of the stack. ``` ,[ Take input and start main loop [->++++<<+>] Push input, and compute 4*input >[ If 4*input is nonzero (and thus input is not @): [-]<< Zero out this cell and move to top of stack [.[-]<] Pop from stack and output until \0 is reached ] >, Move pointer into the correct position. If input was @, the earlier > pushed \0 onto the stack. ] ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~37~~ ~~30~~ 29 bytes ``` M!`-*. +m`^-(.*)¶(\d.*) $1$2- ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/jvq5igq6XHpZ2bEKeroaeleWibRkwKkOZSMVQx0v3/35DLgEvXwJBL1xBIAxm6BkACAA "Retina – TIO Nexus") Saved 7 bytes by realising that terms always begin with a digit, so I don't have to limit the match to the last `-` any more (previously it was the only one guaranteed to be followed by two terms). Saved 1 byte by not putting `-`s on their own line. For example, `-01` becomes `-0¶1` which is then replaced with `01-`. Now, if I have `--010` i.e. `--0¶1¶0` then I want to change the inner `-0¶1` to `01-` so that I can replace the `-01-¶0` with `01-0-`, but it doesn't actually matter which of the two `-`s I remove, so I remove the one at the beginning of the line, as that's easier to test for. [Answer] # [Haskell](https://www.haskell.org/), ~~62~~ 59 bytes ``` f(x:r)|x>'-'=([x],r)|(a,(b,c))<-f<$>f r=(a++b++"-",c) fst.f ``` [Try it online!](https://tio.run/nexus/haskell#@5@mUWFVpFlTYaeuq26rEV0RqwPkaSTqaCTpJGtq2uim2ajYpSkU2WokamsnaWsr6SoBxbnSbdOKS/TS/ucmZuYp2Cpk5pWkFiUmlyik/9fVNTDUNQASAA "Haskell – TIO Nexus") Usage: `fst.f $ "--01-0-01"`. `0` and `1` can be arbitrary characters that are larger than the character `-`. **Edit:** -3 bytes thanks to Zgarb! The function `f` recursively parses one expression and returns a tuple of this expression in postfix notation and the rest string, following the simple grammar from which valid prefix-expressions can be build: ``` <exp> ::= - <exp> <exp> | 0 | 1 ``` If the first character `a` of the input string is larger than `-`, we are at an atomic expression and return a tuple of a string with character `a` and the rest of the input string. If we find a `-`, two expressions need to be parsed. This can be achieved by `(a,x)<-f r` to get the first expression `a` and then parse the rest string `x` again `(b,c)<-f x` to get the second expression `b` and the final rest string `c`. `(a,(b,c))<-f<$>f r` does exactly this because `<$>` on tuples maps a function two the second element of a tuple while being three bytes shorter than `(a,x)<-f r,(b,c)<-f x`. After obtaining both expressions and the rest string, the expressions are concatenated and a "-" is appended: `(a++b++"-",c)`. [Answer] # Haskell, 54 bytes ``` v f""="" v f(a:s)=last(v.v:[id|a>'-'])((a:).f)s h=v h ``` The function `v` takes a string and a function, rearranges the initial sub-expression, then applies the function to the remainder of the string until everything has been rearranged. The call stack and function argument together keep track of what expression is being parsed. The function `h` answers the challenge, and is just `v` called with itself as a dummy first argument. [Answer] # [Perl 5](https://www.perl.org/), 57 bytes ``` sub f{"@_"=~s/x((?0)|.)((?0)|.)/my$n=$2;f($1).f($n).x/re} ``` I use `x` as operator instead of `-` (see the TryItOnline link bellow). [Try it online!](https://tio.run/nexus/perl5#U1YsSC3K@V9cmqSQVq3kEK9kW1esX6GhYW@gWaOnCaP1cytV8mxVjKzTNFQMNfWAZJ6mXoV@UWrt//KMzJxUDRs7zWouBYWCosy8EgWgdLwmV@1/Qy4DrgoDQ64KQyANZFQYAAkA "Perl 5 – TIO Nexus") **Explanations:** `/x((?0)|.)((?0)|.)/` matches recursively a full expression: a `x` at the begining, then an expression `(?0)` (it's a recursive call) or an atom (`.`), followed by another expression-or-atom. Then I need to save the second expression/atom (`my$n=$2;`) because otherwise the recursive calls will override it. The function is then recursively called on the first expression (`f($1)`), then on the second `f($n)`, and the `x` is appended at the end (`.x`). [Answer] ## Python 3, ~~117~~ ~~112~~ ~~105~~ ~~100~~ ~~98~~ ~~76~~ ~~62~~ ~~61~~ 59 bytes ``` def p(s):x=next(s);yield from[x]*(x>"-")or[*p(s),*p(s),"-"] ``` Changelog: * removed linebreaks where possible (-5 bytes) * lambda instead of a full function (-7 bytes, thanks @Dada) * no else (-5 bytes, thanks @Leaky Nun) * undo overzealous golfing (-2 bytes, thanks @Leaky Nun) * work on a global list instead (-22 bytes) * actually, let's work on iterators instead (-14 bytes) * change `!=` to `>` (-1 byte, copied from @ovs' suggestion) * lazy evaluation trickery (-2 bytes, thanks @ovs) Use it like this: ``` >>> list(p(iter("--01-0-01"))) ['0', '1', '-', '0', '0', '1', '-', '-', '-'] ``` [Answer] # Pyth, 20 bytes ``` L+&-hbTsyM.-Btbytbhb ``` This creates a function `y` that expects a string as parameter. Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%2B%26-hbTsyM.-Btbytbhb%0Ayz&input=--01-0-01&test_suite_input=1%0A0%0A-01%0A-10%0A--01-0-01&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=L%2B%26-hbTsyM.-Btbytbhb%0Ayz&input=--01-0-01&test_suite=1&test_suite_input=1%0A0%0A-01%0A-10%0A--01-0-01&debug=0) ### Explanation: The function `y` will parse and convert the first prefix expression to a postfix expression. So if it is called like `y"10"` it will return only `1`. ``` L+&-hbTsyM.-Btbytbhb L define a function y(b), that returns: -hbT remove the chars "10" from the first char b (T=10, and - will convert a number to a string) & if this gives the empty string (a falsy value) + hb then append b[0] to it and return it (so this will parse a digit 0 or 1 from the string) & otherwise (the first char is a -) ytb parse the first prefix expression from b[1:] (recursive call) .-Btb remove this parsed expression bifurcated from b[1:] this gives a tuple [b[1:], b[1:] without first expr] yM parse and convert an expression from each one s join the results + hb and append the b[0] (the minus) to it and return ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~34~~ ~~31~~ 29 bytes ``` ; -; ¶ +`¶(.+);(.+) $1$2- ; ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/jPZc2la811aBuXdsKhbRp62prWIIJLxVDFSBco9/@/IZcBl66BIZeuIZAGMnQNwDwDMA0A "Retina – TIO Nexus") `;` are used to indicate nodes, which are initially composed by a single number and then grow to anything that has already been parsed. `-` are turned into newlines so that with `.+` we can grab anything that isn't an unparsed `-`. [Answer] # [Unix TMG](https://github.com/amakukha/tmg), 49 bytes This translation-oriented language from 1972 makes this task trivial: ``` p:parse(b);b:<->b b={2 1<->}|<0>={<0>}|<1>={<1>}; ``` I believe, this is the first solution in this language on this website, so I will explain a bit: ``` p: parse(b); # parse() builtin: execute parsing rule `b` and output its translation b: <-> b b = { 2 1 <-> } # encountering "-" do recursion; translation rule is in braces | <0> = { <0> } # otherwise: encountering "0" - translate as "0" | <1> = { <1> }; # otherwise: encountering "1" - translate as "1" ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes ``` my&f={S[x(<~~>)**2|)>.]=$0&&$0>>.&f.join~'x'} ``` [Try it online!](https://tio.run/##K0gtyjH7/z@3Ui3Ntjo4ukLDpq7OTlNLy6hG004v1lbFQE1NxcDOTk8tTS8rPzOvTr1CvfZ/cWKlQpqGSrymQlp@kYKNoYKBQoWBoUKFIZAGMioMgITdfwA "Perl 6 – Try It Online") [Answer] # Javascript (ES10), 118 bytes `e=>[...e.matchAll(/(-*)(\d+)/g)].reduce((a,[_,m,[c,...s]])=>(o+=m.slice(l=s.length),a+c+s.join(d='-')+(l?d:s)),o='')+o` **Runnable Snippet** (TIO doesn't have ES10's String.matchAll yet) ``` f = e => [...e.matchAll(/(-*)(\d+)/g)].reduce((a, [_, m, [c,...s]]) => (o += m.slice(l=s.length), a+c+s.join(d='-')+(l?d:s)), o='')+o; ['1', '0', '-01', '-10', '--01-0-01'].map(v => console.log(`f('${v}') -> ${f(v)}`)) ``` ]
[Question] [ Write a program or function that takes in a positive integer N and recreates this pattern of circles scaled to fit an N×N pixel image: [![fancy circles](https://i.stack.imgur.com/ZSx88.png)](https://i.stack.imgur.com/ZSx88.png) This image is a valid output example for N = 946. In case it's not clear, all the small light-blue circles have the same radius and are positioned in the four dark-blue circles in the same way. The dark-blue circles have double that radius and are similarly positioned in the large light-blue circle. * Any two visually distinct colors may be used in place of the two shades of blue. * The background square does need to be colored. * Anti-aliasing is optional. * Save the image to a file, display it, or pipe the raw image data to stdout. * Any common image file format is allowed. **The shortest code in bytes wins.** Brownie points if you extend the recursive aspects of this circle pattern into further levels. (Keep this distinct from your challenge entry.) [Answer] # Python 2 + PIL, 262 bytes [![enter image description here](https://i.stack.imgur.com/dhw3a.png)](https://i.stack.imgur.com/dhw3a.png) This approach determines the color of each individual pixel coordinate using recursive function `c`. `c(x,y,0)` renders a circle; `c(x,y,1)` renders a circle with four circles cut out of it; `c(x,y,2)` renders the image in the OP. Anything larger than 2 earns me brownie points. ``` import PIL.Image as I d=3**.5/2 c=lambda x,y,l=0:c(x,y)&~any(c((x+i)*2,(y+j)*2,l-1)for i,j in[(.5,0),(-.5,0),(0,d),(0,-d)])if l else x*x+y*y<1 z=input() f=lambda s:2.*s/z-1 I.frombytes("L",(z,z),"".join(" ~"[c(f(i%z),f(i/z),2)]for i in range(z*z))).save("p.png") ``` Non-golfed version: ``` from PIL import Image import math def in_shape(x,y, level=0): d = math.sqrt(3)/2 if level == 0: return x**2 + y**2 <= 1 else: t = True for dx,dy in [(0.5, 0), (-0.5, 0), (0, d), (0,-d)]: if in_shape((x+dx)*2, (y+dy)*2, level-1): t = False return in_shape(x,y) and t f = lambda s: ((2*s / float(size))-1) size = input() img = Image.new("RGB", (size, size)) pix = img.load() for i in range(size): for j in range(size): if in_shape(f(i), f(j), 2): pix[i,j] = (0,0,0) else: pix[i,j] = (255,255,255) img.save("output.png") ``` Bonus extra-recursive image: [![enter image description here](https://i.stack.imgur.com/UdLpC.png)](https://i.stack.imgur.com/UdLpC.png) [Answer] # PostScript, 335 bytes. ``` %! /D{def}def/B{bind D}D/E{exch}B/A{add}D/c{3 copy 3 -1 roll A E moveto 0 360 arc}B/f{5 dict begin/d E D/r E D/y E D/x E D gsave x y r c clip d 2 mod setgray x y r c fill d 0 gt{/h 3 sqrt 2 div r mul D/r r 2 div D/d d 1 sub D x r A y r d f x r sub y r d f x y h A r d f x y h sub r d f}if grestore end}B 512 2 div dup dup 2 f showpage ``` PostScript isn't just a graphics file format with both vector and bitmap capabilities, it's actually an object-based Turing-complete programing language. The code above is a fairly straight-forward recursive function implementation. All PostScript operators are functions, and it's commonplace to redefine them to condense code. Note that PostScript uses [Reverse Polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation) (aka postfix notation). PostScript interpreters generally read metadata (like page size and title) from special comments at the start of the file; obviously I've removed all but the bare essential PostScript signature comment `%!` from my entry, but it should still display ok in any standard PostScript interpreter, eg GhostScript or Okular. It can also be viewed using the *display* utility that comes with ImageMagick / GraphicsMagick. Note that the file should end in a newline (which I've included in my byte count), or the interpreter may get upset. The size parameter `N` for this code is 512; it's divided by 2 and duplicated twice to create the parameters for the initial call of the recursive function `f`. The recursion depth is 2, which is given just before the `f` in `512 2 div dup dup 2 f`. To keep the size small the output is black & white. Although you can set any reasonable non-negative integer recursion depth this version only looks good with even depths. This image is a vector graphic, so it can be displayed in any resolution without pixelization, depending on the quality & settings of the PostScript interpreter / printer used. (FWIW, PostScript uses Bézier cubic curves to draw circular arcs, with enough splines used to ensure that the error is always less than one pixel in device space). To view it using ImageMagick's *display* in reasonably high quality you can do: ``` display -density 300 -geometry 512x512 -page 512x512 ``` the same parameters are also good if you wish to use ImageMagick's `convert` to convert it to another format. Eg, here's a 640x640 version of the above PostScript code converted to PNG: [![640x640 B&W circle fractal](https://i.stack.imgur.com/csNNO.png)](https://i.stack.imgur.com/csNNO.png) --- Here's a slightly larger version that handles RGB color and odd recursion depths: ``` %!PS-Adobe-3.0 /D{def}def/N 512 D/d 2 D/B{bind D}D/E{exch}B/A{add}D/c{3 copy 3 -1 roll A E moveto 0 360 arc}B/k{2 mod 0 eq{.3 .6 .9}{0 .2 .5}ifelse setrgbcolor}B d 1 A k 0 0 N N rectfill/f{5 dict begin/d E D/r E D/y E D/x E D gsave x y r c clip d k x y r c fill d 0 gt{/h 3 sqrt 2 div r mul D/r r 2 div D/d d 1 sub D x r A y r d f x r sub y r d f x y h A r d f x y h sub r d f}if grestore end}B N 2 div dup dup d f showpage ``` It also allows you to set the size parameter `N` and the recursion depth `d` near the top of the script. [![640x640 color circle fractal, depth==2](https://i.stack.imgur.com/uNE9w.png)](https://i.stack.imgur.com/uNE9w.png) --- Finally, here's the more readable form of the code. (Unfortunately, the syntax highlighting used here for PostScript leaves a *lot* to be desired, but I *guess* it's better than nothing...). Smart PostScript interpreters will read the page geometry from the `%%BoundingBox:` special comment. ``` %!PS-Adobe-3.0 %%BoundingBox: 0 0 640 640 %%Title: Circle fractal %%Creator: PM 2Ring %%Creationdate: (Oct 29 2015) %%Pages: 1 1 %%EndComments % for http://codegolf.stackexchange.com/questions/61989/circular-blues % ---------------------------------------------------------------------- 16 dict begin %Total image width & height in points / pixels /N 640 def %Maximum recursion depth /Depth 4 def % ---------------------------------------------------------------------- %Draw a circle centred at (x,y), radius r. x y r circle - /circle{ 3 copy % x y r x y r 3 -1 roll % x y r y r x add exch % x y r x+r y moveto 0 360 arc }bind def % ---------------------------------------------------------------------- %Select 1st color if n is even, select 2nd color if n is odd. n color - /color{ 2 mod 0 eq {.36 .6 .9} {0 .25 .5} ifelse setrgbcolor }bind def %Do background square Depth 1 add color 0 0 N N rectfill /Q 3 sqrt 2 div def %Recursive circle pattern. x y r Depth cfrac - /cfrac{ 5 dict begin /Depth exch def /r exch def /y exch def /x exch def gsave x y r circle clip Depth color x y r circle fill Depth 0 gt { /dy Q r mul def /r r 2 div def /Depth Depth 1 sub def x r add y r Depth cfrac x r sub y r Depth cfrac x y dy add r Depth cfrac x y dy sub r Depth cfrac }if grestore end }bind def %Call it! N 2 div dup dup Depth cfrac showpage % ---------------------------------------------------------------------- %%Trailer end %%EOF ``` And here's the depth==4 output in PNG format, once again created using *convert* (and optimized with *optipng*): [![640x640 color circle fractal, depth==4](https://i.stack.imgur.com/uFA7I.png)](https://i.stack.imgur.com/uFA7I.png) [Answer] # CJam, 83 bytes ``` "P1"li___,.5f+2.@/f*1fm2m*{[3{_~mh1<[[VX][ZmqV]]_Wff*+@2f*f.+{~mh}$0=}*;0]0#2%}%]S* ``` [Try it online](http://cjam.aditsu.net/#code=%22P1%22li___%2C.5f%2B2.%40%2Ff*1fm2m*%7B%5B3%7B_~mh1%3C%5B%5BVX%5D%5BZmqV%5D%5D_Wff*%2B%402f*f.%2B%7B~mh%7D%240%3D%7D*%3B0%5D0%232%25%7D%25%5DS*&input=21) CJam does not have dedicated image output functionality. My code generates an image in PBM ASCII. For posting, I converted that image to a PNG using GIMP. Note that no circle drawing functionality, or anything like that, it used. The image is calculated pixel by pixel. [![Sample Output](https://i.stack.imgur.com/fQ2i2.png)](https://i.stack.imgur.com/fQ2i2.png) Higher degrees of the subdivision can easily be created by increasing the constant `3` around the middle of the code. The degree 4 and 5 images look like this: [![Degree 4](https://i.stack.imgur.com/WfnzD.png)](https://i.stack.imgur.com/WfnzD.png)[![Degree 5](https://i.stack.imgur.com/wJ1KA.png)](https://i.stack.imgur.com/wJ1KA.png) The overall sequence of the code is: 1. Generate the coordinates of all pixels, normalized to range [-1.0, 1.0]. 2. Loop over all pixels. 3. Loop over degrees of subdivision. 4. For each subdivision, check if the pixel is inside/outside, and keep the result. The scale/translate the pixel coordinates to the coordinate systems centered at one of the 4 sub-circles. Pick the one where the transformed coordinates are closest to the center. 5. From the binary inside/outside results of each degree, find the first 0, corresponding to the first degree where the pixel was outside, and take its modulo 2 to determine the color of the pixel. Explanation: ``` "P1" Start of header for PBM ASCII file. li Get input n. __ Two copies for the width/height of the image in the PBM header. _, Generate [0 .. n - 1]. .5f+ Add 0.5 to each list entry, since we want to test the pixel centers. 2.@/ Calculate 2.0 / n, which is the distance between two pixels. f* Multiply the unscaled pixel coordinates with the pixel distance. We now have coordinates in the range [0.0, 2.0]. 1fm Subtract one from each, giving coordinates in range [-1.0, 1.0]. 2m* Cartesian power to calculate all y/x pairs. { Start loop over all pixel coordinates. [ Start wrapping the inside/outside results for all degrees. 3{ Start loop over degrees. _~mh Calculate distance from center. 1< Compare with 1. This gives inside/outside result for degree. [ Start building list of centers for 4 sub-circles. [VX] One is at [0 1]. Note that coordinate order is y/x. [ZmqV] Next one is at [sqrt(3) 0]. ] Wrap these two... _ ... and copy them. Wff* Mirror all coordinates by multiplying with -1. + Concatenate, giving the centers of all 4 sub-circles. @ Get current coordinates to top. 2f* Multiply them by 2. Note that the coordinates need to be scaled up by a factor 2 to give a circle with half the radius when we test the distance to the origin against 1.0. f.+ Add the current coordinates to the centers of all 4 sub-circles. For each sub-circle, this puts the current coordinates in a coordinate space with the origin at the center, and with a radius of 1.0 {~mh}$ Sort them by distance to the origin... 0= ... and take the first one. This picks the sub-circle which has its center closest to the current coordinates. We now have one coordinate pair, for the closest sub-circle, and are ready for the next loop iteration, which tests the next degree of the subdivision. }* End loop over degrees. ; Have remaining coordinate pair on stack, pop it. 0 Add a sentinel for find operation before, so that a 0 is always found. ] End wrapping the inside/outside results for all degrees. 0# Find the first 0 (outside) degree. 2% Modulo 2 to determine color. }% End loop over all pixel coordinates. ] Wrap the pieces of the PBM header and the pixel list. S* Join them with spaces, to produce the necessary spaces for the header. ``` [Answer] # Python 2 + PIL, 361 bytes ``` import PIL.Image as p,PIL.ImageDraw as d W=input() q=W/4 h=2*q t=3*q e=W/8 o=int(q*3**.5) I,J=[p.new("1",(s,s),s>h)for s in[W,h]] Q=lambda i,x,y,s=q,c=0:d.Draw(i).ellipse((x,y,x+s,y+s),fill=c) Q(I,0,0,W) Q(J,0,0,h,1) [Q(J,k,e)for k in[0,q]] [Q(J,e,e+k/2)for k in[-o,o]] [I.paste(1,k,J)for k in[(0,q,h,t),(h,q,4*q,t),(q,q-o,t,t-o),(q,q+o,t,t+o)]] I.save("c.png") ``` Saves the image in black & white to the file `c.png`: [![example output](https://i.stack.imgur.com/BkhMf.png)](https://i.stack.imgur.com/BkhMf.png) I basically generate one of the half-sized circles in the image `J`. I then use itself as a mask to paint the shape onto image `I`, which has the main circle. It could be shortened using `I.show()` at the end instead of `I.save("c.png")`, but I didn't get it working on Python 2. If someone can confirm it works on Python 2 I'll change to that. The following program generates the image as in the question (419 bytes): ``` import PIL.Image as p,PIL.ImageDraw as d W=int(input()) q=W/4 h=2*q t=3*q e=W/8 o=int(q*3**.5) I,J=[p.new(["1","RGB"][s>h],(s,s),s>h and"rgb(13,55,125)")for s in[W,h]] Q=lambda i,x,y,s=q,c=0:d.Draw(i).ellipse((x,y,x+s,y+s),fill=c) Q(I,0,0,W,"rgb(97,140,224)") Q(J,0,0,h,1) [Q(J,k,e)for k in[0,q]] [Q(J,e,e+k/2)for k in[-o,o]] [I.paste("rgb(13,55,125)",k,J)for k in[(0,q,h,t),(h,q,4*q,t),(q,q-o,t,t-o),(q,q+o,t,t+o)]] I.save("c.png") ``` [Answer] ## SVG (1249 characters) Yeah, lots of characters. But it’s static and renders at any size, so that gives it some bonus. ``` <svg xmlns="http://www.w3.org/2000/svg"><path d="M15,33c-2.5,0-4.6,1.9-4.9,4.3c2.8,1.6,6.1,2.6,9.5,2.6c0.3-0.6,0.4-1.3,0.4-2C20,35.2,17.8,33,15,33zM15,7c2.8,0,5-2.2,5-5c0-0.7-0.1-1.4-0.4-2c-3.5,0.1-6.7,1-9.5,2.6C10.4,5.1,12.5,7,15,7zM25,33c-2.8,0-5,2.2-5,5c0,0.7,0.1,1.4,0.4,2c3.5-0.1,6.7-1,9.5-2.6C29.6,34.9,27.5,33,25,33zM25,7c2.5,0,4.6-1.9,4.9-4.3C27.1,1,23.9,0.1,20.4,0C20.1,0.6,20,1.3,20,2C20,4.7,22.2,7,25,7zM35,28.7C34.8,26,32.6,24,30,24s-4.8,2.1-5,4.7c-3-1.7-5-5-5-8.7c0,3.7-2,6.9-5,8.7C14.8,26,12.6,24,10,24S5.2,26,5,28.7c-3-1.7-5-5-5-8.7c0,7.4,4,13.9,10,17.3c0.1-1.2,0.4-2.4,0.8-3.4c0.9-1.9,2.3-3.5,4.1-4.5c0,0,0,0,0.1,0c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c0,0,0,0,0.1,0c1.8,1,3.2,2.6,4.1,4.5c0.5,1.1,0.8,2.2,0.8,3.4c6-3.5,10-9.9,10-17.3C40,23.7,38,26.9,35,28.7zM5,11.3c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-3.7,2-6.9,5-8.7c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-7.4-4-13.9-10-17.3c-0.1,1.2-0.4,2.4-0.8,3.4C28.3,8,26.8,9.6,25,10.6c0,0,0,0-0.1,0C24.8,8,22.6,6,20,6s-4.8,2.1-5,4.7c0,0,0,0-0.1,0c-1.8-1-3.2-2.6-4.1-4.5C10.4,5,10.1,3.9,10,2.6C4,6.1,0,12.6,0,20C0,16.3,2,13,5,11.3z"/><circle cx="15" cy="20" r="5"/><circle cx="5" cy="20" r="5"/><circle cx="35" cy="20" r="5"/><circle cx="25" cy="20" r="5"/></svg> ``` Viewable snippet: ``` svg { fill: #9FD7FF; background: #2176AA; } ``` ``` <svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 40 40"> <path d="M15,33c-2.5,0-4.6,1.9-4.9,4.3c2.8,1.6,6.1,2.6,9.5,2.6c0.3-0.6,0.4-1.3,0.4-2C20,35.2,17.8,33,15,33zM15,7c2.8,0,5-2.2,5-5c0-0.7-0.1-1.4-0.4-2c-3.5,0.1-6.7,1-9.5,2.6C10.4,5.1,12.5,7,15,7zM25,33c-2.8,0-5,2.2-5,5c0,0.7,0.1,1.4,0.4,2c3.5-0.1,6.7-1,9.5-2.6C29.6,34.9,27.5,33,25,33zM25,7c2.5,0,4.6-1.9,4.9-4.3C27.1,1,23.9,0.1,20.4,0C20.1,0.6,20,1.3,20,2C20,4.7,22.2,7,25,7zM35,28.7C34.8,26,32.6,24,30,24s-4.8,2.1-5,4.7c-3-1.7-5-5-5-8.7c0,3.7-2,6.9-5,8.7C14.8,26,12.6,24,10,24S5.2,26,5,28.7c-3-1.7-5-5-5-8.7c0,7.4,4,13.9,10,17.3c0.1-1.2,0.4-2.4,0.8-3.4c0.9-1.9,2.3-3.5,4.1-4.5c0,0,0,0,0.1,0c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c0,0,0,0,0.1,0c1.8,1,3.2,2.6,4.1,4.5c0.5,1.1,0.8,2.2,0.8,3.4c6-3.5,10-9.9,10-17.3C40,23.7,38,26.9,35,28.7zM5,11.3c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-3.7,2-6.9,5-8.7c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-7.4-4-13.9-10-17.3c-0.1,1.2-0.4,2.4-0.8,3.4C28.3,8,26.8,9.6,25,10.6c0,0,0,0-0.1,0C24.8,8,22.6,6,20,6s-4.8,2.1-5,4.7c0,0,0,0-0.1,0c-1.8-1-3.2-2.6-4.1-4.5C10.4,5,10.1,3.9,10,2.6C4,6.1,0,12.6,0,20C0,16.3,2,13,5,11.3z"/> <circle cx="15" cy="20" r="5"/> <circle cx="5" cy="20" r="5"/> <circle cx="35" cy="20" r="5"/> <circle cx="25" cy="20" r="5"/> </svg> ``` [Answer] # Mathematica ~~336~~ 359 bytes The principal graphics objects are regions defined through logical combinations of equations. ``` r=Red;i=ImplicitRegion;m=i[-2<x<2&&-2<y<2,{x,y}];n=Input[]; t[a_,b_,c_]:=i[(x+a)^2+(y+b)^2<=c,{x,y}]; a_~f~b_:={t[a,b,1],t[-.5+a,b,1/4],t[.5+a,b,1/4],t[a,b-.865,1/4],t[a,b+.865, 1/4]} g@d_:=RegionIntersection[m,BooleanRegion[#1&&!#2&&!#3&&!#4&&!#5&,d]] RegionPlot[{m,t[0,0,4],g@f[1,0],g@f[-1,0],g@f[0,1.75], g@f[0, -1.75]},ImageSize->n,PlotStyle->{r,Blue,r,r,r,r}] ``` [![pic](https://i.stack.imgur.com/SYSUf.png)](https://i.stack.imgur.com/SYSUf.png) [Answer] # Java, 550 ``` import javafx.application.*;import javafx.scene.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.stage.*;public class C extends Application{static long n;Shape d(float m,float k,float x,float y){float h=m/2;Shape s=new Circle(x+h,y+h,h);return k>0?s.subtract(s,s.union(s.union(s.union(d(h,k-1,x,y+m/4),d(h,k-1,x+h,y+m/4)),d(h,k-1,x+m/4,y-m*.183f)),d(h,k-1,x+m/4,y+m*.683f))):s;}public void start(Stage s){s.setScene(new Scene(new Pane(d(n,2,0,0))));s.show();}public static void main(String[]a){n=Long.valueOf(a[0]);launch();}} ``` Mostly just experimenting with JavaFX. Screenshot: [![screenshot](https://i.stack.imgur.com/3KcSA.png)](https://i.stack.imgur.com/3KcSA.png) For brownie points, change the `2` in the code (`d(n,2,0,0)`) to a different number. **Old version, 810** ``` import javafx.application.*;import javafx.scene.*;import javafx.scene.canvas.*;import javafx.scene.effect.*;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.stage.*;public class C extends Application{static long n;Canvas c;GraphicsContext g;void d(float m,float k,float x,float y){if(k>0){float h=m/2;g.save();g.beginPath();g.arc(x+h,y+h,h,h,0,360);g.clip();g.fillRect(x,y,m,m);d(h,k-1,x,y+m/4);d(h,k-1,x+h,y+m/4);d(h,k-1,x+m/4,y-m*.183f);d(h,k-1,x+m/4,y+m*.683f);g.restore();}}public void start(Stage s){c=new Canvas(n,n);g=c.getGraphicsContext2D();g.setGlobalBlendMode(BlendMode.DIFFERENCE);g.setFill(Color.TAN);g.fillRect(0,0,n,n);d(n,3,0,0);Pane p=new Pane();p.getChildren().add(c);s.setScene(new Scene(p));s.show();}public static void main(String[]a){n=Long.valueOf(a[0]);launch();}} ``` It leaves some undesired edges as you can see in this [screenshot](https://i.stack.imgur.com/Gv09I.png). [Answer] # JavaScript (ES6), 279 Recursively create canvases and add the child canvas four times to its parent canvas. At the bottom layer, the canvas is a single circle; that canvas gets stamped four times onto a parent canvas, and then *that* canvas is stamped four times onto the final master canvas. ``` (n,o=0)=>(r=o-2&&f(n/2,o+1),c=document.createElement`canvas`,X=c.getContext`2d`,d=(x,Q)=>(X.drawImage(r,x,k+Q*k*Math.sqrt(3)),d),c.width=c.height=n,m=n/2,k=n/4,X.fillStyle=o%2||"red",X.fill(X.clip(X.arc(m,m,m,0,7))),r&&d(0,0)(m,0)(k,-1)(k,1),o?c:location=c.toDataURL`image/jpeg`) ``` [![submission image](https://i.stack.imgur.com/YnHuj.jpg)](https://i.stack.imgur.com/YnHuj.jpg) Runnable demo: ``` f = function (n) {var o = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];return r = o - 2 && f(n / 2, o + 1), c = document.createElement("canvas"), X = c.getContext("2d"), d = function (x, y) {return X.drawImage(r, x, y || k), d;}, c.width = c.height = n, m = n / 2, k = n / 4, q = k * Math.sqrt(3), X.fillStyle = o % 2 || "red", X.arc(m, m, m, 0, 7),X.clip(),X.fill(), r && d(0)(m)(k, k - q)(k, k + q), o || (location = c.toDataURL("image/jpeg")), c;};f(400) ``` With whitespace, comments, and mildly ungolfed: ``` f=(n,o=0)=>( // recursively create another canvas if we're not at the deepest layer var r; if(o < 2) { r = f(n/2,o+1); } // create this canvas c=document.createElement("canvas"), c.width=c.height=n, X=c.getContext("2d"), // helpful postions m=n/2, k=n/4, q=k*Math.sqrt(3), // draw a circle and clip future draws within this circle // either fills red (the shortest color name) or a non-color that defaults to black X.fillStyle= o%2 || "red", X.arc(m,m,m,0,7), X.clip(), X.fill(), // define a chainable `drawImage` alias (the `d` function returns itself) d=(x,y)=>(X.drawImage(r,x,y),d) // if we have a recursive canvas, draw it four times by chaining `d` if(r) { d(0,k)(m,k)(k,k-q)(k,k+q); } // if this is the top-layer (o==0), show the final jpeg if(o == 0) { location = c.toDataURL("image/jpeg"); } // return this canvas, to be used recursively c ) ``` This can easily produce deeper layers of recursion by changing the initial `o-2` or any larger `o-z` value. Note that this will submission only run in Firefox, due to the use of ES6 features and inconsistency in the canvas API for `fill` and `clip` arguments. ]
[Question] [ ## Challenge: Given two integers \$a\$ and \$b\$, with lengths \$A=length(a), B=length(b)\$, output an ASCII-art of the \$a^{th}\$ root of \$b\$, including the answer rounded to \$A\$ amount of decimal places. The size of the ASCII-art root also depends on \$A\$ and \$B\$. **Example:** \$a=123\$, \$b=1234\$ ``` ____ 123 /1234 = 1.060 \ / \/ ``` Because \$B=4\$, we have four `_` above the `1234`. Because \$A=3\$, we have three*†* `/` and \$1.0595772951...\$ is rounded to `1.060`. *†**: This will not be equal to \$A\$, but \$\left\lceil{\frac{A}{2}}\right\rceil+1\$ instead.* ## Challenge rules: * I/O format is flexible: + You're allowed to take the input loose or as a pair of integers; doubles; strings; list of digits; etc. + You're allowed to print the result directly to STDOUT; return it as a string; return it as a list/array/stream of string-lines; return it as a matrix of characters; etc. * If input \$a\$ has an odd length \$A\$, the number is left-aligned in the output. So in the example above you're not allowed to have the second line as `123/1234 = 1.060`! (It should be `123<space>/...` instead of `<space>123/...`) * The `=` in the output should be surrounded by a single leading/trailing space * Rounding can be done in any reasonable way (e.g. rounding towards 0, half-up, half-even, banker's rounding, etc.) * If the rounded result ends with `0`s, you're allowed to omit them. (E.g., the `1.060` in the example above may also be `1.06`.) * You can assume \$a>0\$ and \$b\geq0\$ (\$a\$ is positive, \$b\$ is non-negative). * Trailing spaces in the output, and a single trailing newline is fine. Multiple trailing newlines or trailing whitespaces are not. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Inputs: a=3, b=100 (A=1, B=3) ___ 3 /100 = 4.6 \/ Inputs: a=123, b=1234 (A=3, B=4) ____ 123 /1234 = 1.060 \ / \/ Inputs: a=10, b=10 (A=2, B=2) __ 10/10 = 1.26 \/ Inputs: a=1298123, b=9023847978341 (A=7, B=13) _____________ 1298123 /9023847978341 = 1.0000230 \ / \ / \ / \/ Inputs: a=2500, b=0 (A=4, B=1) _ 2500/0 = 0.0000 \ / \/ ``` [Answer] # [Python](https://www.python.org), 143 bytes ``` def f(a,b): A=len(str(-a))&-2;print(A*" ",len(str(b))*"_"+f"\n{a:<{A}}/{b} = {b**(1/a):.{A}}");p="\\" while A:A-=2;print(p+A*" "+"/");p=" "+p ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY9BboMwEADP5RWrPVS2McUYqoBTDv5APwAoAhUrSJFjUVdVhXhDH9BLLu2f-ptCUm6j2dVo9-vHffjj2V4u32_eRPnv50tvwJCWd1QFoMtTb8mrH0nUUnofyb0bB-uJZgjIt1lHKcMDhgZrO7XqadLzHE_dDCVMHWMkiVuqHlaLdO9KrGsM4P04nHrQSkflVnXhtRtifNtb0P2f9WzOI3gYLFRVyhMhGl4lciGZZiuKxV1Vka-6EDLNs12xy9MsWbx8FIKLplHBnSHM01t1e_oP) [Answer] # JavaScript (ES8), ~~158~~ 156 bytes Expects `(a)(b)`, where both arguments are strings. ``` a=>b=>" "[R='repeat'](q=(A=a.length)+A%2)+` ${"_"[R](b.length)} ${a.padEnd(q)}/${b} = ${(b**=1/a).toFixed(A)} `+(g=p=>q?p+" "[R](q-=2)+`/ `+g(" "+p):"")`\\` ``` [Try it online!](https://tio.run/##bY3RboIwGIXvfQrSYPxrI5TCIiz5MVxsD7DbaaRIZS6EFiXLEsKzs6rzxnB7vu@c8y1/5OVwPplu1ehSjUccJaYFpsQhnx@4OCujZLfYQYuQofRq1VTdF2XZXFCWO25P9tbbQfEgw8ztpWdk@daU0NLBd/ticNCaUCyXGPiSep1@P/2qEjJr5wwqNJi2G8Nun/Zqhddx37IKbMYMfSWE5tttPh50c9G18mpdwRFISCiQgHNC6ewJBeIORRhNUX5vThaT@L@ccBHG0TpZx2EUTKjihd92rjPjHw "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` θ⸿↘⊘⊕Lθ↑↗⊘⁺³Lθ⟦⭆η_⟧η = ﹪⁺⁺%.LθfXIη∕¹N ``` [Try it online!](https://tio.run/##VU7fC4IwEH73rxiDYMIK@vGk9JQPCRlS@FQRS5cbrM3W1D9/zQTNg7v7jrvvuy9nROeKCGtTzaVBbz/0egSvGg5DEKlWnnjJDAZ7IhpaoFjmmr6oNA4fqCwNc2QXoZeohqIgq0Z2Vk25qag/aI3BlNcfX87G9TIhFWIYwDv0b8OOje7AFoz2ElXUQvWyvwJnC/gv74Se0NVUtVSjHfl0WhhEvOEFRUsMYlnV5li/Hm7duemeWrtcrYHLjZ034gs "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ ``` Output the first input. ``` ⸿↘⊘⊕Lθ↑↗⊘⁺³Lθ⟦⭆η_⟧ ``` Draw the square root sign. ``` η = ﹪⁺⁺%.LθfXIη∕¹N ``` Output the second input and the formatted result. [Answer] # [Lua](https://www.lua.org), 205 203 188 bytes ``` a,b=...p,c,s=print,a.rep,a.len d=s(a)r=d%2+d+1 p(c(" ",r)..c("_",s(b)))p(a.format("%s%s/%s = %."..d.."f",a,c(" ",d%2),b,b^(1/a)))for i=1,r//2 do p(c(" ",i-1).."\\"..c(" ",r-i*2-1).."/")end ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVTNjtMwEL5wqZ9iZKlSTB1n0-4iLjlw4I4Qt-6ycmKnjZQfK3akRQhehMtKiBOvwIuwT8M4zpYsSsVaSpvE830z_ubLfPteD_L-_sfgyvj171-S55kQwvCC28z0Veu4FL02-FvrFlRmI8n6TK23G7VJwURFRIHyngmBd7eU2yhnjJlIirLrG-kiurZrm6wtZLAWVAglBC0plzwgkYnxnOcfozSRiEQUVFnK-yTZgupOGao4xRz0-pqOmXzOuHq5DW8TynSrwhkeXnyN4_2ekDiGt3emlq10VdcK-HDUoO9kY2oNVWsGZ2GwWsFR9xokXvt0u-OAP5c3ghDJIceaUQxYXEgvcZ9iPA2h_vaSCmI4FBz8gYOAEBSEIOGITKE4yl4WTvcg60pabcGfvOiapmvBOgQeoBzawtduiUIyr_xyKSOlD0F-H5RlsCM9PqO4sMGdDSZcgEwhn2GHcQhK4QuG7sZwfLwi59I94agmHX39eJZD2-jWQVeCQ8FdZ0C2CqyRhT9SeP0s4q5zYD81eVcL38t3XktP8b4b8F-TR2dAz7BLEOwHwX8Tx6i_PRUy1TQyI9QvRNBbXJQh32paJyRZnWy8XCSgB0KAQwVC28hqdcbzAYFJ59u7knoJfWGBiSMBmu-cLiMBOu0JA0Jmn9M5CMxzvhl7on1uqRRWn-tCYiMnE02OQOL8_7VA4q0_K2b6nJ-FScXFqwsEMcLI-PX7d9hVSBIYR8A_vtBGS2zqVdjP8HJVo7FXJjrJ8HdazLo5alzrEm1VKT13A1kBLI6Vx6Qzgr46HJcYGMERRMjNTRhDP2fTZJqufwA) Explanation soon:tm: once I'm out of school. I added an explanation to the footer of the ATO link. [![enter image description here](https://i.stack.imgur.com/GXSt8.png)](https://i.stack.imgur.com/GXSt8.png) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 161 bytes ``` lambda a,b:f"{' '*(Z:=(A:=len(str(a)))+1&-2)} {'_'*(B:=len(str(b)))}\n{a:<{Z}}/{b} = {b**a**-1:.{A}f}"+"".join(f"\n{' '*i}\\{' '*(Z+2*~i)}/"for i in range(Z//2)) ``` [Try it online!](https://tio.run/##Rc3LTsQgGAXgtT4FYWGBdqZcaqYldjE@Ri@ZQBwUM9IG2RiCr16pMXF38p2T/1@/wtviRLv6zfTTdlMf@kUBVWlpYCxAQdAge3SW/e3q0GfwSGGMS/Zw4DiBWFzy4Pm/1LlMk4tKPsUhpTrqBHoQNSGKkAOTx3hOJsESwuP7Yh0yMI/3LzZN09@7kpNvi1MNzeKBBdYBr9zrFQ11zTHedg27jqOoGKVzNTKeExfNHmm2X@ranTvKRduculMrGpadP1Ja0XmW93erty4gg0jIV38A "Python 3.8 (pre-release) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 137 bytes ``` !x=length("$x") a\b=[" "^-~(X=!a+!a%2)*"_"^!b;"$a"*" "^(r=1:X÷2;!a%2)*"/$b = $(round(b^a^-1,digits=!a))";@. ' '^~-r*"\\"*" "^(X-2r)*'/'] ``` [Try it online!](https://tio.run/##VY5RaoQwEIbfc4oxWEysukm0rFaEvvYGQl1LRLtNCVmJWfBpr9UD9GA20n3pvAz//zEf83XVSvJ124K10ZM5u0@CwxVTJLuhecOA@/RG2iaQj4F8EDTG77gPhhqHEsc7Jbbhz@3Pt6jv/BAO0EBI7OVqRjL0sk95Mqqzcou3UIrrlwwiiPpbamPcdXdNmwpL4@gQnbaPiwUFyoCd5KiVmRZCEfiRya6epV2mjLwal8Aya@WIon98tso4bTLif//X@PvJjFsOnDHEhd8iLxBnPvtYlXtVMZGXxbE6lnnBkXhiDNgv "Julia 1.0 – Try It Online") [Answer] # [Python](https://www.python.org), 169 bytes ``` def f(a,b):print(" "*((A:=len(str(a)))-1+(x:=A%2)),"","_"*len(str(b))+f"\n{a}{x*' '}/{b} =",round(b**1/a,A),*("\n"+i*" "+"\\"+(A-i-i-2+x)*" "+"/"for i in range(A//2+x))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NZBRasMwDIbfdwojGJVsBztORpNAYLlHYDg07gzDKV4KGSEn2UtfNtiRdpsla4tefr5PSEKf36eP8XUIl8vXeXRJ8ftz6B1zaGVH1Sn6MCIw4IhNVb_1Ad_HiJaIklTgVNXNoyGSABJegN99RyQctGG2yzzxHdstau4WVoOMwzkcsOM8VVY2JDmubSA8X3cIaFsQ2CR-LSMmukIFbojMMx9YtOHYY6PUZoluBz87zGSqNT04TM0aTZb_Z73SKyyLTZTaZEW-L_dFlqebME9aS32bc3_AHw) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~222~~ 218 bytes *-4 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/)* ``` #define P;printf( #define X snprintf(0,0,"%.0f" A;B;f(double a,double b){A=X,a)P" %*c",A+A%2,95);for(B=X,b);--B P"_"))P"\n%.0f%*c%.0f = %.*f",a,1+A%2,47,b,A,pow(b,1/a));for(A-=~A&1;B++<A--P"\n%*c%*c",B,92,2+A-B,47));} ``` [Try it online!](https://tio.run/##PVDBjsIgFLz3KwibbsA@XEprasN6oF/QgwcPTQzUYkyUGt2NB@N@@nZpZeXCvHlv5jG0bN@2w/C26@zBdaiW58vBfVkS/TMbdHWB48ABx3NucaRkJS3Z9d/m2CENARh6V6sNaFpjhOJZi0ElKhZQLqi0/YVUvmmoZKxCNd5i6ucaNxr62fFCKxTPZxaDhnQS5gUYUHDub8RA@qHp00ex1Y96T2WVJJ@KscnFO4wLKygFiESxyov9@GM46YMj9P4KtCbaPyJE8koWTuP0tJ9bQCagxmEIKal@IUPBTiYyWpMMUs4nlAqPRZY/C@75QJfLsVVykS3zoiyWWZ5OHbHg/ks9fAy/rT3q/XVgt4EdT38 "C (gcc) – Try It Online") ]
[Question] [ **This question already has answers here**: [Write the shortest self-identifying program (a quine variant)](/questions/11370/write-the-shortest-self-identifying-program-a-quine-variant) (48 answers) Closed 3 years ago. Write a program/method that: * Becomes a quine when the input matches the source code; * Doesn't halt otherwise. This is code-golf, so shortest solution wins. Avoid any standard loopholes. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~67~~ ~~60~~ 56 bytes ``` exec(a:='print(s:=input())\nwhile s!="exec(a:=%r)"%a:1') ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWvaAoM69Eo9jKNjOvoLREQ1MzJq88IzMnVaFY0VYJpkq1SFNJNdHKUF2TfJ0A "Python 3.8 (pre-release) – Try It Online") --- # [Python 2](https://docs.python.org/2/), 56 bytes ``` a='s=input();print s\nwhile s!="a=%r;exec a"%a:1';exec a ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9FWvdg2M6@gtERD07qgKDOvRKE4Jq88IzMnVaFY0VYp0Va1yDq1IjVZIVFJNdHKUB3K@f@/SElJiVzdQK0A "Python 2 – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 20 bytes ``` {`".~"+{.2$=}do\;}.~ ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/vzpBSa9OSbtaz0jFtjYlP8a6Vq8OhygA "GolfScript – Try It Online") ## Explanation ``` { }.~ # Evaluate the following string as GolfScript code, using the string itself as argument: ` # - Uneval (effectively wrap the string in "" ".~"+ # - Append .~ {.2$=}do # - Do While not equal to the original program argument: # - (Basically do nothing) \; # - If this loop ends, discard the extra copy of the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` “Ṿ;⁾v`¹⁻³$¿”v` ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZP2rcV5ZwaOejxt2HNqsc2v@oYW5Zwn@8sgA "Jelly – Try It Online") A program taking a single string argument and either printing its source if the string matches its source, or looping indefinitely if not. ## Explanation ``` “ ”v` | Evaluate the following string as Jelly code, using the string itself as argument: Ṿ | - Uneval (effectively wrap the string in “” ;⁾v` | - Append v` ⁻³$¿ | - While not equal to the original program argument: ¹ | - Call the identity function ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` "34çìD«Êi["34çìD«Êi[ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fydjk8PLDa1wOrT7clRmNysMtCwA "05AB1E – Try It Online") --- # Explanation ``` "34çìD«Êi[" - string literal 34ç - push the character " ì - prepend to the string literal D« - duplicate the string (producing the code) Êi[ - loop if it's not the same as the input - else implicitly output ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 15 bytes ``` QWnjN B"QWnjN B ``` [Try it online!](https://tio.run/##K6gsyfj/PzA8L8tPwUkJSv//r6SkhCYGFPmXX1CSmZ9X/F83BQA "Pyth – Try It Online") ## Explanation ``` QWnjN B"QWnjN B Q implicit print input B"QWnjN B evaluates to ["QWnjN B", "QWnjN B"] jN join elements in list with '"' as separator (will be source code) Wn keep looping while input does not equal source code ``` [Answer] # [PHP](https://php.net/), 89 bytes ``` eval($s='$a=chr(39);$b="eval(\$s=$a";$c="$a);";$b.$s.$c!=$argn?:die($b.$s.$c);for(;;);'); ``` [Try it online!](https://tio.run/##K8go@G9jXwAkU8sSczRUim3VVRJtkzOKNIwtNa1VkmyVwOIxQAmVRCVrlWRbJZVETWsgK0lPpVhPJVkRKF6UnmdvlZKZqgET1LROyy/SsLbWtFbXtP5PO6P/5ReUZObnFf/XdQMA "PHP – Try It Online") This is the best I have found so far, at the beginning it wasn't a port of @Mukundan's answer, but it pretty much ends like it. I will try to improve it later.. EDIT: saved a byte with `!=` instead of `==` so I can remove the `1` EDIT2: saved 16 bytes using vars for repeated strings [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 17 bytes ``` «•.x=xe²xw³1#1:? ``` # Explanation ``` «•.x=xe²xw³1#1:?<SPACE> # « # Push the following function to the stack and execute •. # Append a space (A non-function character) and stringify x= # Assign the stringified function to x xe # Is x equal to the top of the stack? ² # "Double Function" to execute if true x # Push x to the stack w # Output ³ # "Tripple Function" to execute if false 1 # Push a truthy value to the stack #1 # A function that just repeatedly pushes true : # While the top of the stack is true. Thus, loop forever ? # If a, than b, else c <SPACE> # Used to ensure the function qualifies as a quine. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6///Q6kcNi/QqbCtSD22qKD@02VDZ0Mpe4T8uCQA "RProgN 2 – Try It Online") [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 36 bytes ``` f=s=>{x=`f=[f]`ifx==s x elsewhile1z} ``` [Try it online!](https://tio.run/##SyvNy678/z/NttjWrrrCNiHNNjotNiEzrcLWtlihQiE1pzi1PCMzJ9WwqvZ/QVFmXokGF2caEHMqEaNFiYtTk0vzPwA "Funky – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~33~~ ~~32~~ 31 bytes *-1 byte thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)* ``` f=x=>eval(`while(x!='f='+f);x`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P822wtYutSwxRyOhPCMzJ1WjQtFWPc1WXTtN07oiQfN/QVFmXolGmoYSAYVKmpr/AQ "JavaScript (V8) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 50 bytes ``` $_=q($_='$'."_=q($_);eval";<>eq$_?print:eval);eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rZQA0ioq6jrKUHYmtapZYk5StY2dqmFKvH2BUWZeSVWICGIBDl6AA "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~29~~ 21 bytes ``` OvA="Us@¶`OvA=`+Q+A}a ``` [Try it online!](https://tio.run/##y0osKPn/37/M0VYptNjh0LYEEDNBO1DbsTbx/3917BLqAA "Japt – Try It Online") ## Explanation ``` OvA="Us@¶`OvA=`+Q+A}a A="Us@¶`OvA=`+Q+A}a // Set A to string literal Ov // Evaluate A as japt code @ // Function ¶`OvA=`+Q+A // Check if input equals "OvA" + '"' + A (Q is '"') } // End Function a // Call function repeatedly until it returns a truthy value Us // Slice off first 0 chars of input // Implicit Output ``` ]
[Question] [ ## Input A non-empty shuffled string consisting of ASCII characters in the range \$[32..126]\$. ## Output The output is obtained by applying successive rotations to the input string. For each letter (`[a-zA-Z]`) in the input string, going from left to right: * if the letter is in upper case, rotate all characters before it by one position to the left * if the letter is in lower case, rotate all characters before it by one position to the right ## Example **Input: "Cb-Ad"** * The first letter is a "**C**". We should do a rotation to the left, but there's no character before this "**C**". So, there's nothing to rotate. * The next letter is a "**b**". We rotate "**C**" to the right. Because it's a single character, it is left unchanged. * The character "**-**" does not trigger any rotation, as it's not a letter. * The next letter is a "**A**". We rotate "**Cb-**" to the left, which gives "**b-C**Ad" * The fourth and last letter is a "**d**". We rotate "**b-CA**" to the right, which gives "**Ab-C**d" Therefore, the expected output is "**Ab-Cd**". ## Rules * You may take input as a string or as an array of characters -- which may or may not be the same thing, depending on your language. * You may also output an array of characters instead of a string. * This is ~~[ogl-edocf](/questions/tagged/ogl-edocf "show questions tagged 'ogl-edocf'")~~ [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ## Test cases ``` "cbad" -> "abcd" "ACBD" -> "ABCD" "Cb-Ad" -> "Ab-Cd" "caeBDF" -> "aBcDeF" "aEcbDF" -> "abcDEF" "ogl-edocf" -> "code-golf" "W o,ollelrHd!" -> "Hello, World!" "ti HIs SSta ET!" -> "tHis IS a tEST!" ``` [Answer] # Pyth, ~~21~~ 20 bytes ``` VQ=k+.>k-}NG}Nr1GN)k ``` [Try it here](http://pyth.herokuapp.com/?code=VQ%3Dk%2B.%3Ek-%7DNG%7DNr1GN%29k&input=%22W+o%2CollelrHd%21%22&debug=0) ### Explanation ``` VQ=k+.>k-}NG}Nr1GN)k VQ ) For each N in the input... .>k ... rotate k (initially '')... -}NG}Nr1G ... by (N is lowercase) - (N is uppercase)... + N ... then append N... =k ... and update k. k Output the result. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~100~~ ~~98~~ 95 bytes ``` f=lambda s,p='':s and f(s[1:],[p[x:]+p[:x]+s[0]for x in[s[0].isupper()-s[0].islower()]][0])or p ``` [Try it online!](https://tio.run/##TYw9b4MwFEX3/opXOiQouGo7ImUATERmKmWwPPiLBMnlWbar0l9PiUAp473n3Ot@4w2Hj2nqjlZ8SS0gZO642@UBxKCh2wf2nvOMOTbm/OBYPvJDYG@8Qw8j9AO7h9c@fDtn/D4la7T4c4@czzGdVTc53w9x/kuUFDpJ4QUSIZVOnh6gqEq6gKKs6AZUkhTrpJCk2m6UMCU9rXeloua0gaJW8gGlovUW4tUSo1F1C1eoDbmi7TbKBTBDa431jX5etMZYixlc0Nu5@ldjD805QNtGAfXnKsemD3BuQUCs27mc/gA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØẠŒHċ€ḅ-N⁸ṙ;ð/ ``` A monadic link accepting a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##ATcAyP9qZWxsef//w5jhuqDFkkjEi@KCrOG4hS1O4oG44bmZO8OwL////yJ0aSBISXMgU1N0YSBFVCEi "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///wjIe7Fhyd5HGk@1HTmoc7WnX9HjXueLhzpvXhDfr/j@453A4Udv//P1opOSkxRUmHS0HJ0dnJBcxwTtJ1hAglJ6Y6ubiBmYmuyUlQZn56jm5qSn5yGpgXrpCvk5@Tk5pT5JGiCBYpyVTw8CxWCA4uSVRwDVFUigUA "Jelly – Try It Online"). ### How? ``` ØẠŒHċ€ḅ-N⁸ṙ;ð/ - Link - list of characters / - reduce by: ð - a dyadic chain: 1st call is f(L=1stCharacter, R=2ndCharacter) - ...then calls are f(L=previousResult, R=nextCharacter) ØẠ - alphabet characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ŒH - split in half = ["ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"] € - for each: ċ - count occurrences (of R) - e.g.: 'W' -> [1,0]; 'c' -> [0,1]; '@' -> [0,0] ḅ- - convert from base -1 -1 1 0 N - negate 1 -1 0 ⁸ - chain's left argument (i.e. L) ṙ - rotate left by (the negate result) ; - concatenate R ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~17~~ ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` õsvy.uy.l-._y« ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Nbiskq90kq9HF29@MpDq///L8lU8PAsVggOLklUcA1RBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/h5ulir6TwqG2SgpL9/8Nbi8sq9Uor9XJ09eIrD63@X6vzPzkpMYXL0dnJhcs5SdcxhSs5MdXJxY0r0TU5CUjlp@fopqbkJ6dxhSvk6@Tn5KTmFHmkKHKVZCp4eBYrBAeXJCq4higCAA). **Explanation:** ``` õ # Start with an empty string sv # Loop over the characters `y` of the input y.u # Check if `y` is an uppercase letter (1 if truthy; 0 if falsey) y.l # Check if `y` is a lowercase letter (1 if truthy; 0 if falsey) - # Subtract them from each other ._ # Rotate the string that many times (-1, 0, or 1) toward the left y« # Append the current character `y` to the string # (And implicitly output the string after the loop) ``` [Answer] # [K4](http://kx.com/download/), ~~43~~ 33 bytes **Solution:** ``` ""{.q.rotate[-/y in'.Q`A`a;x],y}/ ``` **Examples:** ``` q)k)""{.q.rotate[-/y in'.Q`A`a;x],y}/"Cb-Ad" "Ab-Cd" q)k)""{.q.rotate[-/y in'.Q`A`a;x],y}/"ogl-edocf" "code-golf" q)k)""{.q.rotate[-/y in'.Q`A`a;x],y}/"ti HIs SSta ET!" "tHis IS a tEST!" ``` **Explanation:** Iterate over the input string, rotating the previous output by 1, -1 or 0 depending upon it's position in the list "a-zA-Z". ``` ""{.q.rotate[-/y in'.Q`A`a;x],y}/ / the solution ""{ }/ / iterate (/) over, starting x as "" ,y / append y to .q.rotate[ ;x] / rotate x by ... .Q`A`a / the lists "a..z" and "A..Z" y in' / y in each (') alphabet? -/ / subtract (-) over (/) ``` **Notes:** * -10 bytes with inspiration from the [05AB1E](https://codegolf.stackexchange.com/a/172462/69200) solution [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~45~~ 43 bytes ``` ii:2+7$.::&"`{"@)@(*?}"@["&::&@)@(*?{&! ror ``` [Try it online!](https://tio.run/##S8sszvj/PzPTykjbXEXPykpNKaFayUHTQUPLvlbJIVpJDSgE4VarKXIV5Rf9/x@ukK@Tn5OTmlPkkaIIAA "><> – Try It Online") The fact that ><> has stack rotation helps, but having to check the case of the letter doesn't. ### Explanation: ``` i Get first inputted character i Get second. This is to prevent errors from rotating an empty stack :2+7$. Jump to the second line if that was EOF ::& Create copies of the input and store one in the register "`{"@)@(* Check if the char is lower case ?} If so rotate the stack "@["&::&@)@(*?{ Rotate the other way if uppercase & Push the new char ! Skip the first i instruction Skip to the second line on EOF ro Reverse the stack and output r r Cancel out the first reverse o Output the rest of the stack ``` [Answer] # [Haskell](https://www.haskell.org/), ~~101~~ 91 bytes -10 bytes inspired by [Curtis Bechtel's answer](https://codegolf.stackexchange.com/a/172481/48198) (use `'@'<c,c<'['` over `elem c['A'..'Z']` and the according range for lower-cased letters). ``` g(x:y)=foldl((<>pure).(!))[x]y x@(a:b)!c|'`'<c,c<'{'=last x:init x|'@'<c,c<'['=b++[a]|0<1=x ``` [Try it online!](https://tio.run/##bZFBb@IwEIXv/IohF2xBou4VkWpDQkWl9pSVKhWh1dgegrUmRokRyYr/zk6CVPWwPsz4fe/N@OAjtn/Iubs9nX0ToMCAybuvvTUgQKyeJch7JbplL9ODd8YJZudLQzIRUyl33b6fdD8FLpWc6hs5OoHezXCWJLO/s33qsA3QLW1tuX3Z2WB/sq3m8x3ub0@rH2l3P6GtIYUTnt9/gzhfQhmatxoSqDyXhtBI7s7W1EK6WkFFIfd1oDq0cD1SQxMYoqJb9BJuUEEHaQo9r2yP/spqPocI4mcufBtZzyNf5wY@8JqrbYlnogNaR2b5Lf2/DYKfkQ8uGFycAUXfh/rRlNFdRFqhiRYRKm0iORFRlq8L1tk6L0adqzgbApmK80dCI62Ll2FmrQt6GRlutHowpYvNg/nKxWS8PjDW3lBceXcYnQ/wC@8cuWZrpuxu@a/9Aj5841gPiWBh@9pCWQaEza8hE7a2hdcSEMKmZCL/AQ "Haskell – Try It Online") ## Explanation / Ungolfed The operator `(!)` takes a non-empty string `x` on which we can pattern-match and a character: ``` x@(a:b) ! c | '`' < c, c < '{' = last x : init x -- rotate x to the right by one | '@' < c, c < '[' = b ++ [a] -- rotate x to the left by one | otherwise = x -- keep x as is ``` Now we can reduce the input's tail from the left to the right, starting with the first character of the input using: ``` \b a -> b!a ++ [a] ``` [Answer] # [Haskell](https://www.haskell.org/), 122 92 bytes Thanks to BWO for the suggestions! I also saved a lot by taking a slightly different approach than my original answer. ``` l@(a:b)!c|'`'<c,c<'{'=last l:init l++[c]|'@'<c,c<'['=b++[a,c]|0<1=l++[c] f(c:s)=foldl(!)[c]s ``` [Try it online!](https://tio.run/##PYpNS8QwFEX3/RWvQUhLWtBtaWQ@ZQR3FVwMgi8vrVPm2UiTWTn/vQYmurr3nHtP6M8987LwqsDGlDld5YdsqaJW/kjN6ANwM05jDKWO9H6VqzQfpTZRYRXlffugb3s2FNT4Ug@OLRd5GZVf5ssEXn9fQhfml@nOKyUA6kcAodQAPvvCcdLWZRCPggxacavr7WaX6tbU6z9N2G92TwlwT@Yf3CfXvXU0JH4DVznmnueDzZMLIxyePXRdQNi/5mL5BQ "Haskell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~116~~ 102 bytes ``` f=(s,i=1)=>s[i]?f(s.replace(RegExp(`^(.)(.{${i}})(?=[A-Z])|^(.{${i}})(.)(?=[a-z])`),"$4$3$2$1"),i+1):s ``` [Try it online!](https://tio.run/##bctPC4IwHMbxe6/CZIffj9zA6lRYWBl1rSAojOacshhNnET057UbdAli18/3eS78xq2oVdXQq8ll2xYR2EBFIUYTe1TptADLallpLiRsZJncKzifgCGwJ3mq9xthGh1jekjxdfoZ@zKnjxTPGPhkSAakT0IfA9ULcWTbsTBXa7Rk2pRQgC8ynvuInX@P57OFy@cZjZ0HweVssXQVnojMXUypqcyNKFxx75nAaC11vcq7rkGjvNXaetttw71k9520Hw "JavaScript (Node.js) – Try It Online") ## Original (~~116~~ ~~111~~ 106B) ~~`s=>Buffer(s).map((x,i)=>s=(t=s[S="slice"](i),i<2)?s:x>64&x<91?s[S](1,i)+s[0]+t:x>96&x<123?s[i-1]+s[S](0,i-1)+t:s)&&s`~~ ~~`s=>Buffer(s).map((x,i)=>i<2|--x%32>25|x<64?s:s=[s[S="slice"](1,i)+s[0],s[i-1]+s[S](0,i-1)][+(x>95)]+s[S](i))&&s`~~ `s=>Buffer(s).map((x,i)=>!i|--x%32>25|x<64?s:s=(w=x>95,t=s.slice(1-w,i-w),w?s[i-1]+t:t+s[0])+s.slice(i))&&s` [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->s{w=[];s.map{|x|w.rotate!(x=~/\W/||?_<=>x)<<x};w} ``` [Try it online!](https://tio.run/##Jc67DoIwAIXh3acoLKjh8gBQDDeDMyYMSExbQE1qSmgJGIqvXqtO5/u3M4z4pTqonJAvE6xqn7tP1C9ylpM7MIFEa2xn@PYupSfl4RrAcN4Fwbz606oqk2DUmLYZJXGqJ8FO9E2C2jg9aqCM4B/YjTptw0inXQJmM0pbOuSNoVs8QH7ioCgEAtnZMOv/AS43/Sg46CrukjsaeL23rFV9AA "Ruby – Try It Online") Input and output are arrays of characters ### The trick: The code is pretty straightforward, except perhaps the rotation part: ``` (x=~/\W/||?_<=>x) ``` x is a single character, which could be a letter, the first expression `x=~/\W/` returns `nil` if it's a letter, and 0 otherwise. If it's 0, we're done, if not, the logical `or` checks the second expression: `?_<=>x` returns -1 for upper case and 1 for lower case. So the rotation is: * -1 (1 to the left) for upper case * +1 (1 to the right) for lower case * 0 (no rotation) if it's not a letter [Answer] # [Red](http://www.red-lang.org), 110 bytes ``` func[s][p: s forall s[if all[(a: first s)>#"@"a < #"["][move p back s]if all[a >#"`"a <#"{"][move back s p]]p] ``` [Try it online!](https://tio.run/##TcpNCsIwGIThfU8x/bpRsBcoIooIdWsFFyFg2iQSjE1IqhsPHyv@0N3MyxOUTAclGc90lfS971jkzFeI0C4IaxGZ0RgHm4kK2oQ4IM5XBa1JYImCGHF2cw8Fj1Z0V0T@9QKjOr9VQc8f@hB4zj1PPph@gAZt23IjKfv/E9zCWatsqGU@6e5iSyVdpydtMKj3EU0zCOyOOaUX "Red – Try It Online") ## Explanation: ``` f: func [ s ] [ p: s ; store the starting position of the string in p forall s [ ; iterate through the entire string a: first s ; store the current character in a if all [ a > #"@" a < #"[" ] [ ; if `a` is a uppercase letter move p back s ; move the starting char to the position before current ] if all [ a > #"`" a < #"{" ] [ ; if `a` is a lowercase letter move back s p ; move the character before the current one to the start ] ] p ; return the string ] ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 47 bytes ``` *.reduce:{|@$^a.rotate($^b~~/\w/&&'_'leg$b),$b} ``` [Try it online!](https://tio.run/##JYjJCoJAGIDvPsU4iEu43DokQW5hZ4MuYcwqxtgfoxFS@eqGdfqWu9BqPXcjsiXazqtQC/5gYvN676yahBoGMgjXquk0RednZNvOxVGisajnW/Qzx0ZPRiTdkEFHvfAK7Q1J0AZmlHDsGzjJ0nxhRoPkNxgRab5fjBSM/g0aFQgOTC5xQuCDUkLpkpvLGFpUHnpUVQNBxdHE8fwF "Perl 6 – Try It Online") Works on an array of chars. [Answer] # Japt, ~~17~~ ~~16~~ 14 bytes Takes input as an array of characters, outputs a string ``` ;rÏiXéCøY -BøY ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=O3LPaVjpQ/hZIC1C+Fk=&input=WyJDIiwiYiIsIi0iLCJBIiwiZCJd) --- ## Explanation ``` rÏ :Reduce by passing the current result (X) & the current element (Y) through a function i : Prepend to Y Xé : X rotated right by ; B : Uppercase alphabet øY : Contains Y? - : Subtract ; C : Lowercase alphabet øY : Contains Y? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` W€ḷṙ01ŒlƑ?-ŒuƑ?};ʋ/ ``` [Try it online!](https://tio.run/##y0rNyan8/z/8UdOahzu2P9w508Dw6KScYxPtdY9OKgVStdanuvX///@vlJ@eo5uakp@cpgQA "Jelly – Try It Online") [Answer] # Java 10, ~~149~~ 119 bytes ``` s->{for(int i=1;i<s.length();)s=s.replaceAll("^(.)(.{"+i+"})(?=[A-Z])|^(.{"+i+++"})(.)(?=[a-z])","$4$3$2$1");return s;} ``` Port of [*@ShieruAsakoto* JavaScript answer](https://codegolf.stackexchange.com/a/172463/52210), so make sure to upvote him. [Try it online.](https://tio.run/##XZHfSsMwGMXv9xSfoRcJXQNT72qV7o/MC3dTQXBskKbZzMzS0qQDnbv1AXxEX6R2XQS7m5D8zsfhnC8btmPBJnuruWLGwCOTet8DkNqKcsW4gNnxCZDYUuo1cOwuhoQNP/Saw1hmJYcZaIigNsHtfpWXuHEAGQ1CeWOoEnptXzEJiYkMLUWhGudYKYyWmBJM98iXPjoQfBfN4@BlQT6XDvotpq3Cgo8FQX3kXXtX3qU3QCQsha1KDSY81OExSlGlqoniEu1ymcG2aeRCzxfAyKmOFcZixFOWobbIH4lHw3GXjNIgPhviTAzH913GJjw9Z/laBSLL@aqLnyHv50oJVU6zi65kJUwfDCSJZTB5cuL/JbeV2ln3D1IXlXWlkndjxZbmlaVFI1qlcSv7CH6@vgH5mvITIc74UP8C) **Explanation:** ``` s->{ // Method with String as both parameter and return-type for(int i=1;i<s.length();) // Loop `i` in the range [1, length) s=s.replaceAll("^(.)(.{"+i+"})(?=[A-Z])|^(.{"+i+++"})(.)(?=[a-z])","$4$3$2$1"); // Rotate the substring of [0, i] either left or right return s;} // Return the modified input-String as result ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 32 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éG7[Æ┐äZ▬Θε♫∙~╞ÉH╔u╬←J╛ü╢(┼▒uX)Ü ``` [Run and debug it](https://staxlang.xyz/#p=8247375b92bf845a16e9ee0ef97ec69048c975ce1b4abe81b628c5b17558299a&i=cbad%0AACBD%0ACb-Ad%0AcaeBDF%0AaEcbDF%0Aogl-edocf%0AW+o,ollelrHd%21%0Ati+HIs+SSta+ET%21&m=2) ``` B]s{c97 123:bsaa|)sc65 91:bsaa|(s+c}fd #Full program, unpacked, implicit input B]s #Unons-left, singleton, swap top 2 of stack {c #Copy iterative letter 97 123 #Put 97 and 123 on stack(lower case) :bsaa #Check if iterative letter is between range, swap orientation back to proper order |) #Rotate if the letter is within range sc #Swap top 2 and copy top 65 91 #Put 65 and 91 on stack (Capitals) :bsaa #Check if iterative letter is between range, swap orientation back to proper order |( #Rotate if the letter is within range s+c #swap, concat and copy }fd #remove duplicate of original answer after loop and implicitly print ``` A lot of stack swapping which is probably unnecessary. I really would like to get this down more, but I was strugging with the ordering of the stack. Maybe somebody can figure it out if they are bored. Will keep working on it. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 69 bytes ``` ~Fold[{s'r.=_'sp;Rotate[s,&`-!Has&r[0]=>ALPHA'alpha]+r}@SplitAt]#Iota ``` [Try it online!](https://tio.run/##JYrBasMwEAXv/grZLfGhduk5xaWKk@BACSE25CBEu5bWiUFUQru30v66E6enN28YYAZzwWkQy2r623pn1Q/l8bn6zCm8Hj0Do6Ji8VWmDdAiqhddvcmPQyNzcOEC@in@vrfBjSxZP@xu/bRHtKQeQzBnnRzi@M0dEtdASGoohEoy04PNiiST9Wo9b92X8i4M4Gq9nQk2pv8nf3YlWm@G@ZyEL7xz6GJj01nwKJodibZlEJsuzRKtpys "Attache – Try It Online") ## Explanation ### General shape The function looks generally like this: ``` ~Fold[{...}]#Iota ``` Which folds `{...}` over each member in the range from `0` to `#input - 1` (`Iota`), starting with the input as a seed. ### The inner function The following function is called as `f[building, index]` and is called with each index from `0` to `#input` exclusive. `@SplitAt` calls `SplitAt` on these arguments, splitting the input string on `index`. ``` {s'r.=_'sp;Rotate[s,&`-!Has&r[0]=>ALPHA'alpha]+r} { } anonymous function taking the split string e.g.: ["cd-", "Adf!"] _'sp concat the input with a space e.g.: ["cd-", "Adf!", " "] (this is to handle index = 0) s'r.= `s` is the first member, and `r` is the second Rotate[s, ] rotate `s` by: ALPHA'alpha over uppercase and lowercase alphabets: Has&r[0]=> test if r[0] is in each alphabet e.g.: [true, false] &`-! subtract the second from the first e.g.: (true - false) = 1 - 0 = 1 s is rotated according to the following map: uppercase => 1 symbol => 0 lowercase => -1 +r append the right portion of the string ``` Essentially, this function rotates the left portion of the string according to the first character of the right portion. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` FS≔⁺⭆ω§ω⁻⁺λ№αι№βιιωω ``` [Try it online!](https://tio.run/##NYzBCsIwEETv/Yr1toH4BZ6KCOZQKMQfSFutC2FTkk3r38e04mFg3sww49vFMThfyitEQMNLFiuReEaloE2JZsbe54S/tHMLbhpaMTw9P7vtiGt7TLyGa8gs6DSQUn8aDtqZqjZ1afp6JVhdKUJwNwmsFQe3x6kp59V/AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS ``` Loop over the input characters. ``` ≔⁺⭆ω§ω⁻⁺λ№αι№βιιω ``` Map over the string of collected characters so far, cyclically indexing into the collected characters so far with the index incremented or decremented if the current character is upper or lower case respectively. This completes the rotation. The next character is then concatenated, and the result assigned back to the string. ``` ω ``` Print the result. [Answer] # [R](https://www.r-project.org/), ~~107~~ ~~102~~ 100 bytes Massive because R's string manip is bulky. Can anyone get it under 100? -5 bytes using the "set loop variables to F to avoid initializing" trick. -2 bytes by assuming all characters are printable and using `2*!k%%97>25` rather than `2*k%in%97:122` for testing lower case, using operator precedence. ``` function(x){for(k in u<-utf8ToInt(x))u[1:F-1]=u[(1:(F=F+1)+k%in%65:90-2*!k%%97>25)%%F];intToUtf8(u)} ``` [Try it online!](https://tio.run/##TYxNa8IwAEDv@xWxI9BMA6vgNjsV@hXaczs8iIckTSQ0JFATGIz99q6rVLy@93j9IHd4kN5wp6wJv9GPtH3YAWWA32Hv5EdjK@NGgfwpigmOznt/CqM4JHuyjNCyg8rAt028fcXrl0UH4fb9sN4gCMn5UxnX2K/xEXr0O8gw4Iy2AXoG@AACyngbPI0wydJ8hkma5RPMGE7uacJwdms5FWlO7ouU54JMghacPQjG8@Im7EVj0VouZ8dtK/DFajnpI7Arq7XQfdku5qQUWtsVONpej/A/cwqU1RXUtaOgaO6hK9UVVDWgwBX1iIc/ "R – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~25~~ 23 bytes *I give up, Can't make it shorter* -2 bytes from @ETHproductions ``` £=¯Y éXè\a -Xè\A)+UsYÃU ``` --- ``` £=¯Y éXè\a -Xè\A)+UsYÃU Full program. Implicit input U £ map each char = set U equal to: ¯Y U sliced to current mapped value éXè\a -Xè\A) and rotated left or right 1 char +UsY append the non-sliced U value ÃU Output U ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=oz2vWSDpWOhcYSAtWOhcQSkrVXNZw1U=&input=WyJjYmFkIiwKIkFDQkQiLAoiQ2ItQWQiLAoiY2FlQkRGIiwKImFFY2JERiIsCiJvZ2wtZWRvY2YiLAoiVyBvLG9sbGVsckhkISIsCiJ0aSBISXMgU1N0YSBFVCEiXSAtbVI=) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~67~~ ~~64~~ 58 bytes ``` ^ ¶ +`(.*)(.)¶([a-z])|(.)(.*)¶([A-Z])|¶(.) $2$1$3$5$4$6$7¶ ``` -9 bytes thanks to @Neil removing the three unnecessary `?` I had added, as well as the unnecessary `(.*)` in the else-case. [Try it online](https://tio.run/##K0otycxLNPz/P47r0DYu7QQNPS1NDT3NQ9s0ohN1q2I1a4AckBhIwFE3CigAZOlpcqkYqRiqGKuYqpiomKmYH9r2/39JpoKHZ7FCcHBJooJriCIA) or [verify all test cases](https://tio.run/##K0otycxLNPyvquGe8D@O69A2Lu0EDT0tTQ09zUPbNKITdatiNWuAHJAYSMBRNwooAGTpaXKpGKkYqhirmKqYqJipmB/a9h@o@39yUmIKl6OzkwuXc5KuYwpXcmKqk4sbV6JrchKQyk/P0U1NyU9O4wpXyNfJz8lJzSnySFHkKslU8PAsVggOLklUcA1RBAA). (NOTE: Outputs with a trailing newline. The header in the test suite is to test each input-line as a separate test case, and the footer is to remove that trailing newline for a more compact output.) **Explanation:** Prepend a newline before the input: ``` ^ ¶ ``` Continue replacing as long as we can find a match: ``` +` ``` Everything else is three different checks merged together: If the character right after the newline is lowercase letter: rotate everything before the newline once towards the right, and then append that character and the newline: ``` (.*)(.)¶([a-z]) $2$1$3¶ ``` If the character right after the newline is an uppercase letter: rotate everything before the newline once towards the left, and then append that character and the newline: ``` (.)(.*)¶([A-Z]) $2$1$3¶ ``` Else (neither a lowercase nor uppercase letter): simply shift the newline once towards the right for the next 'iteration': ``` ¶(.) $1¶ ``` These three checks above are merged with regex OR statements (`|`) and larger group-replacements to make it act like an `if(lowercase) ... elseif(uppercase) ... else ...`: [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` ttYo-ZS"X@q:&)w@YSwh ``` [Try it online!](https://tio.run/##FYhLCsIwEED3PcXUhYNgLuCqn1TiOgVbQXDyUQsjQR3o8WNcvc@LhPNtmUwWmZO62M3UvA/b3drMdn3mqx4zekcBK2z7Thf0TrX/9BQ7fSxCg3dFoML0YBVD8vdyz5D2iTnyx4S6tCxgTl@wVgiGscYf "MATL – Try It Online") -4 bytes thanks to Luis Mendo. Converts uppercase/lowercase/non-letter to [-1,0,1] (first half of the program). Applies circshift consecutively (second half). I'm wrecking my brain if there's a better way to map uppercase/lowercase to [-1,0,1] (see the second version), and perhaps a way to reverse the string right away so as to get rid of the two `w`'s needed for the `&)`. [Answer] # [C (clang)](http://clang.llvm.org/), ~~168~~ ~~159~~ ~~153~~ 119 bytes ``` g,i,j;f(char*a){for(i=0;a[j=i++];islower(a[i])?g=a[j],bcopy(a,a+1,j),*a=g:isupper(a[i])?g=*a,bcopy(a+1,a,j),a[j]=g:0);} ``` -26 thanks to @ceilingcat [Try it online!](https://tio.run/##VZBPT4MwGIfP8inqvBQoZl5FNM65zPNMdiAcXvqPkkoJFI1Z9tmxBMbw1t/7PM37a2lENVSy7yVRpIwFpgU0AfgnYRqsknUMaZmoMMxi1WrzwxsMqcr8F5k4kJGcmvoXA4HwgZQ@CSCRj6rt6nohBnDRnASDNlx14tqPz/2dqqjuGEdPrWXK3BfPnqcqi75AVfjbKOafvJuhFIIN3fJdmqEErSjwzXa3iidEDePSaDFCI3XEmaFi5pa3dmRWof1Hiw4HC@j983Y2Cq7d80yj2egdkSFGa66bPbtakNOJv@XRKxvmAo@9fHeuO9suovvMqdcMlwOBh1ozugSBr11m@H/kdroi141jOPd/ "C (clang) – Try It Online") [Answer] # Pyth, 16 bytes ``` em=+.>k-F}RGrBd2 ``` [Try it here!](http://pyth.herokuapp.com/?code=em%3D%2B.%3Ek-F%7DRGrBd2&input=%22W+o%2CollelrHd%21%22&debug=0) Explanation: ``` em=+.>k-F}RGrBd2dQ Autofill variables m Q for each d in Q (the input): rBd2 Take [d, swapcase(d)] }RG Figure out which are in the lowercase alphabet (returns [1,0] for lowercase, [0,1] for uppercase, [0,0] for non-letters) -F Fold on subtraction (1 for lowercase, -1 for uppercase, 0 for non-letter) .>k Cycle the processed part (k) of the input right by ^ steps + d Add in the new character at the end = k Store new process step back into k (k starts as an empty string) e Get the (e)nd step's output. ``` ]
[Question] [ [Minecraft 1.12](http://minecraft.gamepedia.com/1.12) will be released tomorrow, so let's celebrate! Write code that takes in a non-negative integer N which represents the number of items of something in [Minecraft](http://minecraft.gamepedia.com/Minecraft). Output it in a way more helpful to players, giving the number of chests, stacks, and items N is equivalent to. Use the format ``` XcYsZi ``` where * `X` is the number of chests you can completely fill with N items, * `Y` is the number of stacks you can fill with the items remaining after filling chests, * `Z` if the number of items remaining after filling chests and stacks. Note that: * 64 items fit in a stack. (We'll ignore items that stack to 16 or don't stack.) * 27 stacks fit in a chest. (These are single chests, not double chests.) So it would never make sense if `Y` is more than 26 or if `Z` is more than 63. A caveat with the format is that if there is zero of something, that term is not printed. * So, for example, if `Y` were zero and `X` and `Z` nonzero, the format would look like `XcZi`. * Likewise if `Y` and `Z` were zero and `X` nonzero, the format would be `Xc`. * **The exception here is when N is zero.** Then `0i` is the output rather than an empty string. You can assume all N items are of the same type, hence all stackable. You may not output a list or tuple of three numbers. You must give a string with the exact "csi" notation, in that order, with no spaces or commas. For reference, here's a chest completely filled with stacks of items: [![Minecraft single chest filled with 27 stacks of diamonds](https://i.stack.imgur.com/zRLuw.png)](https://i.stack.imgur.com/zRLuw.png) # Testcases ``` in -> out 0 -> 0i 1 -> 1i 2 -> 2i 62 -> 62i 63 -> 63i 64 -> 1s 65 -> 1s1i 66 -> 1s2i 127 -> 1s63i 128 -> 2s 129 -> 2s1i 200 -> 3s8i 512 -> 8s 1337 -> 20s57i 1664 -> 26s 1727 -> 26s63i 1728 -> 1c 1729 -> 1c1i 1791 -> 1c63i 1792 -> 1c1s 1793 -> 1c1s1i 4096 -> 2c10s 5183 -> 2c26s63i 5184 -> 3c 5200 -> 3c16i 9999 -> 5c21s15i 385026 -> 222c22s2i 1000000000 -> 578703c19s ``` **The shortest code in bytes wins.** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` d64d1¦27Fża¥“csi”Fḟ0ȯ⁾0i ``` A full program taking the number and printing the result. It does seem too long to me... **[Try it online!](https://tio.run/##ATIAzf9qZWxsef//ZDY0ZDHCpjI3RsW8YcKl4oCcY3Np4oCdRuG4nzDIr@KBvjBp////MTcyOQ)** or see the [test suite](https://tio.run/##NYwxDsIwDEWvwgGMZDuJ0yyMvQNCDIgytOrGxFZYuASICSYkVoaKoagS1yAXCc7Al/8f7PfdbNp2l1IltqLhxr4c@9Vwjd1pva1jdy6/zwt@HnH/wjqN/fsYD/dGrcBkOpsoMU9pgUDAIDoGxII4EAFiry7UARgRHDGQMboUZcjns893rwD5QDk4hwGLQbRQmBwWXO4HFZjCIetv/Gv5Aw). ### How? *updating...* ``` d64d1¦27Fża¥“csi”Fḟ0ȯ⁾0i - Main link: number n 64 - literal 64 d - divmod (whole divisions and remainder) 27 - literal 27 1¦ - apply to index 1 (the whole division from above) d - divmod F - flatten into a single list (of three items i.e. [(n/64)/27, (n/64)%27, n%64] “csi” - literal ['c','s','i'] ¥ - last two links as a dyad: ż - zip a - logical and (any 0s in the divmod result become [0,0], others become [integer, character] F - flatten (from list of three lists to one list) ḟ0 - filter discard zeros ⁾0i - literal ['0','i'] ȯ - logical or (non-vectorising) - implicit print (smashed together representation, so [578703,'c',19,'i'] prints as 578703c19i) ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~49~~ ~~48~~ 41 bytes ``` .+ $*i i{64} s s{27} c (.)\1* $.&$1 ^$ 0i ``` [Try it online!](https://tio.run/##HUtJDsIwDLzPOwpCIFWxnTjJC/gFAkUceuFAuJW@PbVrzSJ5Zr7v3/J5jdPl/hzzDdMVtGrc0NFXzhsaHtOfLJjPC/rhHe3wNkYAgaEGgUZogiqIs7EYKzgEJGKQiD3VOpQ9zp5nK1Cu5MIughiq2qCIS0TyfbWDlBRYdw "Retina – Try It Online") Includes all test cases except the last, in case it overloaded TIO. Edit: Saved 7 bytes thanks to @MartinEnder. Explanation: ``` .+ $*i ``` Convert the input number to unary using `i`s. ``` i{64} s ``` 64 items fill one stack. ``` s{27} c ``` 27 stacks fill one chest. ``` (.)\1* $.&$1 ``` Convert any chests, stacks or remaining items to decimal, but leaving the type as a suffix. ``` ^$ 0i ``` If the input was zero, make the result `0i`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes ``` 1728‰`64‰)˜…csiøvyJ¬0Êi? ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0NzI4lHDhgQzEyCpeXrOo4ZlycWZh3eUVXodWmNwuCvT/v9/AwA "05AB1E – Try It Online") **Explanation** ``` 1728‰ # input divmod 1728 (64*27) ` # split as separate with mod result on top of stack 64‰ # divmod 64 )˜ # wrap stack in flattened list …csiø # zip with the string "csi" vy # for each J # join amount with storage-type ¬0Êi # if head != 0 ? # print ``` [Answer] # C#, 84 86 bytes ``` _=>(_/1728>0?_/1728+"c":"")+((_-=_/1728*1728)/64>0?_/64+"s":"")+(_%64>0?_%64+"i":"") ``` Notice the inline subtraction, didn't realize it was possible but `i--` made sense so why not `i-=10` # Edit: ``` _=>_>0?(_/1728>0?_/1728+"c":"")+((_%=1728)/64>0?_/64+"s":"")+(_%64>0?_%64+"i":""):"0i" ``` for 0 edge case and suggestion. [Answer] # [Python 3](https://docs.python.org/3/), 87 bytes ``` lambda n:g(n//1728,"c")+g(n//64%27,"s")+g(n%64,"i")or"0i" g=lambda n,s:(str(n)+s)*(n>0) ``` [Try it online!](https://tio.run/##PY7dasMwDIWv56cwBoPdetQ/iWMH0hfZdpG1TWvYnBL7Inv6VHbpBOcDoXMk3f/ybY5mm4bP7Wf8/T6POPZXFg8H1WknyInwfW1tQ3UnSHr21DaCBMLnhchA0HV4ZUXqWcoLi3yf@I7Fo@RbvqR8GtMlDR9SICWQFsgWGVADakEWJnAA4Ao8uCS4WwVGZUyZ2GKGt7pKV@kLvarUlbC0kd6WqDOVkGrrMg8lkHGt1OWcfNUXQtO84BWHiP@f7dHbfQkxM0IDfj9imghlq5jYyjnfHg "Python 3 – Try It Online") [Answer] # C, 85 ~~87~~ ~~105~~ ~~110~~ ~~111~~ ~~112~~ bytes ``` #define a(x,y)x?printf("%d%c",x,y+99):0; f(z){a(z/1728,0)a(z%1728/64,16)!z+a(z%64,6)} ``` Try it [here](https://tio.run/##HYxBDsIgFET3nAIxmP9TTFtjUOzCs5BPMSyKRo2pND07grOYzLzFo/2NKOetG32II7cwqy/O18czxLcHIZ0koQprjMFLNzAPCRcLqe1Ph7PqsExZZ6uPqte4SU0l5Whc8@ceHJ9siIBsYcXI3cBeZOPfLNTOYTXWXrMp@QE). The code even works properly on negative numbers. You may now owe server OP blocks! [Answer] ## JavaScript (ES6), ~~77~~ 76 bytes ``` n=>[n+1,1728,64,1].map((v,i,a)=>(v=n%a[--i]/v|0)?v+'csi'[i]:'').join``||'0i' ``` ### Test cases ``` let f = n=>[n+1,1728,64,1].map((v,i,a)=>(v=n%a[--i]/v|0)?v+'csi'[i]:'').join``||'0i' console.log(f(0)) // -> 0i console.log(f(1)) // -> 1i console.log(f(2)) // -> 2i console.log(f(62)) // -> 62i console.log(f(63)) // -> 63i console.log(f(64)) // -> 1s console.log(f(65)) // -> 1s1i console.log(f(66)) // -> 1s2i console.log(f(127)) // -> 1s63i console.log(f(128)) // -> 2s console.log(f(129)) // -> 2s1i console.log(f(200)) // -> 3s8i console.log(f(512)) // -> 8s console.log(f(1337)) // -> 20s57i console.log(f(1664)) // -> 26s console.log(f(1727)) // -> 26s63i console.log(f(1728)) // -> 1c console.log(f(1729)) // -> 1c1i console.log(f(1791)) // -> 1c63i console.log(f(1792)) // -> 1c1s console.log(f(1793)) // -> 1c1s1i console.log(f(4096)) // -> 2c10s console.log(f(5183)) // -> 2c26s63i console.log(f(5184)) // -> 3c console.log(f(5200)) // -> 3c16i console.log(f(9999)) // -> 5c21s15i console.log(f(385026)) // -> 222c22s2i console.log(f(1000000000)) // -> 578703c19s ``` [Answer] # Java 8, 86 bytes ``` i->i>0?(i/1728>0?i/1728+"c":"")+((i%=1728)/64>0?i/64+"s":"")+((i%=64)>0?i+"i":""):"0i" ``` [Try it here.](https://tio.run/##hZRfa4MwFMXf9ykugUGC1MZ/UVvafYL1ZY9jD6l1I52NUtPCGP3sLmoHexknRIj3/OAeTy4e9VUv2q62x8PnUDW67@lZG/v9QGSsq8/vuqppN74SvbizsR9Uca@QFWtfvPnH795pZyrakaUNDWaxNVv5xM0yyuPCn@ZDwCq2YkwEnJvHzVgRS5VOskoD1v8RVSrGesDMVFwxadiwnnt1l33je91bXltzoJN3zGd3r2@kxd3uV@/qU9heXNh5yTWW27DiUkzO/9UjoKsYAQkCUgRkCFDoI@IcEgUkSkDEEoWZRSitKEmgVQUT89OUY6TASAmRMsJIjBE0JKksFQy3SDCCosvwLZZ@ASQpMhnDqZS/S9z/HrfhBw) [Answer] # [CJam](https://sourceforge.net/p/cjam), 31 bytes ``` ri64md\27md@]"csi"]z{0=},"0i"e| ``` [Try it online!](https://tio.run/##S85KzP3/vyjTzCQ3JcbIPDfFIVYpuThTKbaq2sC2VkfJIFMpteb/f0MDGAAA "CJam – Try It Online") ### Explanation ``` ri e# Read an int from input. 64md e# Divmod by 64, gives total #stacks, #items. \27md e# Divmod total #stacks by 27, gives #chests, #stacks. @ e# Bring #items back to top. ] e# Wrap in an array: [#chests, #stacks, #items] "csi" e# Push "csi". ]z e# Zip with the other array. {0=}, e# Filter out subarrays where the first element is 0. "0i"e| e# Logical or with "0i". An input of 0 gives an empty array e# from the rest of the program, in that case yield "0i" e# instead. ``` [Answer] # [///](https://esolangs.org/wiki////), 179 bytes ``` /|/\/\///b/l0|d/11|x/dddd|sbxxxxxxxx/1sb|cbxxxd1/1cb|bxd/1b|d/2|2222/8|222/6|22/4|21/3|81/9|61/7|41/5|bc/gc|cb/c|bs/gs|sb/s|bi/gi|b|/g/0|mc/m|ms/m|mi/0i|m|/si/s|cs/c|ci/c/mcl0sl0i ``` [Try it online!](https://tio.run/##LYzBDsMwCEM/yaHruu5fdhl0ypCSE5cc/O8ZkfaQjBC2o73j@4k5QbxyAEUrvCDCgSth6PgDCaWt8xKIKXWkUdO9cUtwroUjFTs3wY2n4MlD8OAuuFMN1bICRg3UyHIE1VGdSlQUdkNnjyWO4uxEeJosMmSOfFsr0YrP@QM "/// – Try It Online") Input is taken in unary `1`s at the end of the program right before the `i`. Ex: ``` .../si/s|cs/c|ci/c/mcl0sl0<--input here-->i ``` You can also use an `x` in place of 8 `1`s as a side affect of golfing the program. There is a wrapper for easier testing below. Testing wrapper: [Try it online!](https://tio.run/##XVLBcpswED1bX7G32NPUixwncTrtsYfec@xFEjJSA4hqRY1n9O/uCuIkkwXE7ujpvd0H1Cpyli4oEBHK8/0rRNuFf5agt6fW95yovgYalOGUApzDCEb14PthTLzCMYRkI@gwLUg72KiSheQs3PibLTK7EM/OE/D9Z6TENJ2FU1QDQ4HSeDxCCtCpF/tKW4iSpeT7Bqwib6MQvxZBgsS4oj8rvKvfgrbHEN@F4XlJeBJbEwiW0BZUmgGWFcJxThdJPjpXQwxNVF1p6BTiS6m5y/a8FT@nb2IlOcRqeg2xEiv/oTVuauxVPN/CySe3zGmcisTKZZZoh5aNrAswxJobZxkTuiFaoqWRrRAS4AeAhHU9uo2Y5uoAaz36tjjORz41@sbQj522sTCxKb1q2/MGQAi3EFYVrN08qBv7Otp6I9J1h7euHoSR2P@N4IG3YpWSWDnnrjPPDoh56usntX9H1XIbYldovsDdvO4PJWX23d09Hzg5bxw0vvxZ0jzR/pEZyq@R0L0Flw6nD1Hcxgtm/M0Xosa2yjVKmSesOTLpKxIl6WxKWUuURmc9MVAzepd3HHgoL3zgFfd5J/EuHyQ@5QeJj3kv8T5rg41hCjRZEzbE5EhZe2x81hkbrHJnsMsdlcVj5XOXkTyDDPEh45G3TVtRW13YtWLaq2ezZf7yHw "/// – Try It Online") Ungolfed: [Try it online!](https://tio.run/##7VM5DsMwDNv1GUZpmqbPKYTCMRBPWvJ7l5Lzhy4hDNOkzsV@fHz/eu8Q8JzQCxR@TOcFKAUtSyvCamEIaIRKIazGzLSZwDYeWJOxBCkepE3xJq2KF2lRPLP4mAzFxhTYaO4oPlaBR1J4FaWOaKxckHs0Q6NqPqhiypyGuL1GNcyR7SupN05hW5Hzxo3/4/p3IrX/AA "/// – Try It Online") It does 2 divmods, one to separate into chests, stacks, and items, then again to convert to decimal. I could have it convert input from decimal as well, but I would also have to change all of the symbol names and add additional logic to keep it from breaking, so I'm not going to do that. Besides, I think unary is a recognized standard input for ///. [Answer] # JavaScript (ES6) 71 bytes ``` n=>[n/1728|0,(n/64|0)%27,n%64].map((a,i)=>a?a+'csi'[i]:'').join``||'0i' ``` **Snippet:** ``` f= n=>[n/1728|0,(n/64|0)%27,n%64].map((a,i)=>a?a+'csi'[i]:'').join``||'0i' console.log(f(0)) // 0i console.log(f(1)) // 1i console.log(f(2)) // 2i console.log(f(62)) // 62i console.log(f(63)) // 63i console.log(f(64)) // 1s console.log(f(65)) // 1s1i console.log(f(66)) // 1s2i console.log(f(127)) // 1s63i console.log(f(128)) // 2s console.log(f(129)) // 2s1i console.log(f(200)) // 3s8i console.log(f(512)) // 8s console.log(f(1337)) // 20s57i console.log(f(1664)) // 26s console.log(f(1727)) // 26s63i console.log(f(1728)) // 1c console.log(f(1729)) // 1c1i console.log(f(1791)) // 1c63i console.log(f(1792)) // 1c1s console.log(f(1793)) // 1c1s1i console.log(f(4096)) // 2c10s console.log(f(5183)) // 2c26s63i console.log(f(5184)) // 3c console.log(f(5200)) // 3c16i console.log(f(9999)) // 5c21s15i console.log(f(385026)) // 222c22s2i console.log(f(1000000000)) // 578703c19s ``` [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes I converted Gabor Fekete's comment from above into a working example: ``` lambda n:g(n/1728,"c")+g(n/64%27,"s")+g(n%64,"i")or"0i" g=lambda n,s:(`n`+s)*(n>0) ``` [Try it online!](https://tio.run/##PY7dasMwDIWv56cwBoO9asw/iWMH0hfZBs26pjNsTolzkT19Jnt0gvOB0NGRbj/r55zMPg2v@9f4/f4x0tRfRXrWnfHAzkweSucabjpg@a/lrgEWmZwXpiIj1@G@CbkXp3Q6ZPko0lHJfb3k9TzmSx5eFBANxABxRRbVoFqUwwmmI3xBQJdCd6vRqK0tE1fM@FJX6StDYdCVphJDGxVcWfW2ErfaGhawgFjfKlPOqXu9ETLNC91oTPT/2Z483JaYVsF4pE9HyjPjYoNJbFLK/Rc "Python 2 – Try It Online") [Answer] # Batch, ~~347 335 283 246 234 202 199 191~~ 189 bytes ``` @set/al=%1,c=%1/1728,l-=c*1728,s=l/64,l-=s*64 @set c=%c%c @set s=%s%s @set i=%l%i @if %c%==0c set c= @if %s%==0s set s= @if %i%==0i set i= @if %c%%s%%i%.==. set i=0i @echo(%c%%s%%i% ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 76 bytes ``` ?dddsf[1728/n99P]sc1728/0<c1728%ddd[64/n115P]si64/0<i[64%n105P]sy64%0<ylf0=y ``` [Try it online!](https://tio.run/##S0n@/98@JSWlOC3a0NzIQj/P0jIgtjgZzDawAdOqQOloMxP9PENDU6BcJpBpYJMJFFHNMzQAiVQCmQY2lTlpBraV//@bGloYAwA "dc – Try It Online") [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 71 bytes ``` V"isc"R#@!%>93*!*,>,>!/!*,>,$_-,>,>,/<$_<&,!?_v@R:>|!?_v@R:>|!?_v@R:>|; ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/8/TCmzOFkpSNlBUdXO0lhLUUvHTsdOUR9Mq8Trgng6@jYq8TZqOor28WUOQVZ2NZgM6////1sCAQA "Braingolf – Try It Online") Not at all golfy, but it works [Answer] # Mathematica, 155 bytes ``` A=AppendTo;G={};P=Print;(z=Mod[t=Mod[#,1728],64];If[(x=⌊#/1728⌋)>0,A[G,{x,c}]];If[(y=⌊t/64⌋)>0,A[G,{y,s}]];If[z>0||#==0,A[G,{z,i}]];Row@Flatten@G)& ``` [Answer] # [PHP](https://php.net/), 84 bytes ``` <?=($c=($a=$argn)/1728^0)?$c.c:"",($s=$a/64%27)?$s.s:"",($i=$a%64)||$c+$s<1?$m.i:""; ``` [Try it online!](https://tio.run/##JcnBCoQgFEDRfZ8hL0gqy5Acpsw/CeQR2aKScdtvz9oetbibc4MPabTBhwzcbz0MU1pKNmR2IjYFIOXM83gjdfeZW24BBX4ZqwqItJpe5Z0mjSK@upHmveLXBVhCHKWFXWz0hpT@x1mjQ7/c "PHP – Try It Online") # [PHP](https://php.net/), 93 bytes ``` $i-=64*$s=($i-=1728*$c=($i=$argn)/1728^0)/64^0;echo$c?$c.c:"",$s?$s.s:"",$i||$c+$s<1?$i.i:""; ``` [Try it online!](https://tio.run/##HYpBDoMgFAX3PQZ5C7WK2io2RcJNTMyPKWyU@Lde2zUWdzOTCS7E0QYXHpj332rEu1eD0BG@MqorwCZL2A6vTwFKYu4xr1OamrxW3dTohdwGsiBJXyFKsAVLvtEfB@gJHlsLL/2/6RjPdatoJrdc "PHP – Try It Online") [Answer] # T-SQL, ~~139 134~~ 139 bytes Input is stored in column *a* of pre-existing table *t*. ``` SELECT IIF(a=0,'0i',REPLACE(IIF(a<1728,'',STR(a/1728)+'c') +IIF(a%1728<64,'',STR(a%1728/64)+'s') +IIF(a%64=0,'',STR(a%64)+'i'),' ',''))FROM t ``` Line breaks for readability, not counted in byte total. Tested on MS SQL Server 2012. **EDIT 1:** Changed multiple `REPLACE` to `IIF` to save 5 bytes. Final `REPLACE` still necessary because `STR` annoyingly pads with spaces to 10 chars. **EDIT 2:** Fixed to follow the rules by using the approved input type for SQL, [values stored in a named table](https://codegolf.meta.stackexchange.com/a/5341/70172). This cost bytes for the `FROM`, also requires `SELECT` instead of `PRINT`. Recovered 2 bytes by dropping an unnecessary parens. [Answer] # PowerShell, 113 Bytes ``` param($i)("$(($c=[math]::floor($i/1728)))c","")[!$c]+("$(($s=[math]::floor(($i%1728)/64)))s","")[!$s]+"$($i%64)i" ``` This hits a bunch of powershell's pain points very precisely. `[math]::Floor` is required for this as PS does Bankers Rounding by default. the PS Ternary also takes up a load of bytes compared to other languages, to do a simple null coallescence (`$a="This";$a?$a:"That"` or `"This"?:"That"`) we need to do `(($a="This"),"That")[$a-ne$null]` then we need to use all of these twice, and also add in another set of brackets in some places due to powershell's default operation order. [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` lambda n:''.join(`k`+c for k,c in zip([n/1728,n/64%27,n%64],'csi')if k)or'0i' ``` [Try it online!](https://tio.run/##PY/dbsMgDIWvx1OgSghQ2cpPQqBS9yJdpaZZo9FsJAq5yPbymUHaLJ3vxsfH9vS9fIxRb/3pbftsv27vLY5HSl8eY4jsOlz3He7HGQ@iwyHinzCxczyoRjsRD7YiuhGR2OoiaJcC5aHHAx9nKgPdlntaujbd0@ksBVICaYFslgFVoBpkoQMZAJfhwSXBXSswKmNyx2YzbGwKXaHP9KpQF0JoJb3No84UwlRdwjyUQMbVUud18q8uCOXX1vzY/7FH9DTNIS5sRwJ@fsUk7QhbRc9Wzvn2Cw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` d64d1¦27FµTȯ3ịż“csi”$ ``` [Try it online!](https://tio.run/##NUwrDgIxEL0M8onOTDttL8AJMGgWAVmHwm0wCK4AFkWyCgVqCQnXoBcpU8HLvCfmfbbrvt/X2qnvaLpynE/3xWeU7@P0fpbhvNptynCZ1dexHG7LWh0IDLUTqIcGqII4GpMxg51DIAaJ2FMtQ7HZsfnRAhQzNeEmAu@yWiFJE4/Q@tkAScGxbbs/fg "Jelly – Try It Online") Like Jonathan Allan's essentially-the-same answer before it, this does seem too long. Even more essentially the same: # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` d64d1¦27Fż“csi”ẠƇȯ⁾0i ``` [Try it online!](https://tio.run/##NUw5DgIxDPzQFLaTOMkH@AM1S7FoOyq6hWY/ARIVFRI9QhQgEN8gHwlOwcgzhedYLYdhU2unvuPHSeLsdSvjfrHuy3j4Xo/v6XMp2zv19TmV3XleK4EhUDsH9dAAVbBEYzJmCBECC9g5e6plODY7Nj9agGPmJtLEwVNWKyTXxCO0fjbApUBi2/THDw "Jelly – Try It Online") ]
[Question] [ We know that *f* is a polynomial with non-negative integer coefficients. Given *f(1)* and *f(1+f(1))* return *f*. You may output *f* as a list of coefficients, an ASCII formatted polynomial, or similar. Examples: ``` f(1) f(1+f(1)) f 0 0 0 1 1 1 5 75 2x^2 + 3 30 3904800 4x^4 + 7x^3 + 2x^2 + 8x + 9 1 1073741824 x^30 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ‘b@ ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYUaSw////40N/htbGphYGBgAAA "Jelly – TIO Nexus") Returns the polynomial as a list of coefficients. Since we know the polynomial has non-negative integer coefficients, *f(b)* can be interpreted as "the coefficients of the polynomial, taken as base *b* digits," by the definition of a base. This is subject to the condition that none of the coefficients exceeds or is equal to *b*, but we know that, because *b* is one greater than the sum of the coefficients (which is *f(1)*). The program simply increments the first argument (`‘`) to get *1+f(1)*, then calls the base convertion atom (`b`) with the first argument as the base and the second argument as the number (using `@` to swap the order of the arguments, since `b` usually takes the number first and base second). This was quite the clever challenge; thanks orlp! [Answer] # Mathematica, ~~29~~ 28 bytes *Thanks to JungHwan Min for saving 1 byte! (ironically, with a `Max`)* ``` #2~IntegerDigits~Max[#+1,2]& ``` Pure function taking two nonnegative integers and returning a list of (nonnegative integer) coefficients. `#2~IntegerDigits~(#+1)` would be the same algorithm as in [Doorknob's Jelly answer](https://codegolf.stackexchange.com/a/114469/56178); unfortunately, Mathematica's `IntegerDigits` chokes when the base equals 1, hence the need for extra bytes `Max[...,2]`. [Answer] # [Python 2](https://docs.python.org/2/), 38 bytes ``` a,b=input() while b:print b%-~a;b/=a+1 ``` [Try it online!](https://tio.run/nexus/python2#@5@ok2SbmVdQWqKhyVWekZmTqpBkVVCUmVeikKSqW5donaRvm6ht@P@/sYGOgrGlgYmFgQEA "Python 2 – TIO Nexus") --- outputs newline separated coefficients Example output for `30, 3904800`: ``` 9 8 2 7 4 ``` => `9*x^0 + 8*x^1 + 2*x^2 + 7*x^3 + 4*x^4` [Answer] # VBA, 75 bytes ``` Sub f(b,n) b=b+1 Do While n>0 s=n Mod b &" " &s n=n\b Loop Debug.?s End Sub ``` When it automatically formats, it looks like this: ``` Sub f(b, n) b = b + 1 Do While n > 0 s = n Mod b & " " & s n = n \ b Loop Debug.Print s End Sub ``` The `\` operator is a floor divide [Answer] # Common Lisp, 87 bytes ``` (defun p(x y)(multiple-value-bind(q m)(floor y (1+ x))(if(= 0 q)`(,m)`(,m ,@(p x q))))) ``` Ungolfed: ``` (defun find-polynomial (f<1> f<1+f<1>>) (multiple-value-bind (q m) (floor f<1+f<1>> (1+ f<1>)) (if (zerop q) `(,m) (cons m (find-polynomial f<1> q))))) ``` [Answer] # [AHK](https://autohotkey.com/), 63 bytes ``` a=%1% b=%2% a+=1 While b>0 {s:=Mod(b,a) " "s b:=b//a } Send,%s% ``` AutoHotkey assigns numbers 1-n as variable names for the incoming parameters. It causes some problems when you try to use those in functions because it thinks you mean the literal number 1 instead of the variable *named* 1. The best workaround I can find is to assign them to different variables. [Answer] # Java, 53 bytes ``` a->b->{while(b>0){System.out.println(b%-~a);b/=a+1;}} ``` Outputs a list of coefficients. Thanks to ovs for the maths. The expression must be assigned to a `Function<Integer, IntConsumer>` and called by first `apply`ing the function, then `accept`ing the `int`. No imports are needed with Java 9's `jshell`: ``` C:\Users\daico>jshell | Welcome to JShell -- Version 9-ea | For an introduction type: /help intro jshell> Function<Integer, IntConsumer> golf = a->b->{while(b>0){System.out.println(b%-~a);b/=a+1;}} golf ==> $Lambda$14/13326370@4b9e13df jshell> golf.apply(30).accept(3904800) 9 8 2 7 4 ``` [Answer] # C#, 62 bytes ``` (a,b)=>{var r="";a++;while(b>0){r+=(b%a)+" ";b/=a;}return r;}; ``` ]
[Question] [ Semordnilaps (also known as heteropalindromes, semi-palindromes, half-palindromes, reversgrams, mynoretehs, reversible anagrams, word reversals, or anadromes) are words which are also words when spelled backwards. A few examples are: * Ward <=> Draw * Mined <=> Denim * Parts <=> Strap Given a positive integer N (via function argument or STDIN), return / output a list of semordnilaps from [this list of English words](http://www.mieliestronk.com/corncob_lowercase.txt), that have exactly N letters. The list of words can be saved locally on your computer as a text file called: `w.txt`. You can also get the list from the url, but it will be included in the byte count. Rules: 1. [Palindromes](http://en.wikipedia.org/wiki/Palindrome) are not semordnilaps! Therefore, the words "noon", "rotor" and "radar" should not be included in the list. 2. Only one of the words (in a semordnilap pair) should be included in the list. Therefore, if "dog" is in the list, "god" should not be (it doesn't matter which one is included.) 3. If there are no semordnilaps, the output should be an empty string, 0, FALSE or something else indicating that there were no results. The function must work even if there are no results. This is code golf so the shortest code in bytes wins! --- ## Leaderboard The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=42090,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"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] # [Pyth](https://github.com/isaacg1/pyth), 23 (18 code, 5 necessary STDIN) ``` J'f&qlTQ&}_TJ>_TTJ ``` This is a fairly straightforward solution. `J` stores the list of words. Then we filter over the list of words (`f J`) on the length of the word being the input (`qlTQ`), the reversed word being in the list (`}_TJ`), and the reversal of the word being greater than the word (`>_TT`). The last condition ensures `T` is not palindromic, and that only one of the pair is printed. The resultant list is printed. The way Pyth works, the only way to open a file is to receive its name on STDIN. This is why I have counted 5 of the STDIN bytes, `w.txt`, in my score. Example run: ``` $ pyth -c "J'f&qlTQ&}_TJ>_TTJ" <<< '6 w.txt' ['animal', 'denier', 'diaper', 'drawer', 'pupils', 'recaps', 'redraw', 'sleets', 'snoops', 'sports'] ``` [Answer] # Ruby, 74 bytes ``` f=->n{i=IO.read('w.txt').split p *i&[f.reverse]if f.size==n while f=i.pop} ``` Iterates over the list by removing elements, which avoids both palindromes and outputting both "stressed" and "desserts". Using the same variable name for the function and the iterator gets around a Ruby syntax quirk: even though `f=i.pop` is evaluated before `f.reverse`, the line won't parse unless `f` already means something. I could also use `p`. [Answer] # bash ~~134~~ ~~157~~ 118 bytes `f () { comm -12 <(sort w.txt) <(rev w.txt|sort)|while read w; do ((${#w}==$1))&&[[ $w<$(rev<<<$w) ]]&&echo $w; done; }` This is not a serious entry, but rather in response to [Brian's Bash answer](https://codegolf.stackexchange.com/a/42108/31516). This is how I tend to think about programming this sort of thing in Bash--by using Bash itself for as little as possible, and letting the built-in tools do all the work. [Answer] # Python, ~~126~~ ~~125~~ 120 bytes ``` N=input() J=open("w.txt").read().split() for c in set(J): if N==len(c)and c!=c[::-1]and c[::-1]in J:print c;J.remove(c) ``` Pretty straightforward solution. [Answer] # CJam, ~~48~~ ~~47~~ ~~45~~ ~~42~~ 38 bytes Since the URL has to be counted, I'm using the same URL shortener as Optimizer. ``` "ri.ms/§"gDcN+/{,ea~i=},_Wf%&{_W%>},N* ``` The `§` is part of extended ASCII, so each character in the code can be encoded in a single byte. As in Optimizer's case, you'll have to use the [Java interpreter](http://sourceforge.net/projects/cjam/) and run this locally from a file, say `semordnilap.cjam`, and then ``` java -jar cjam-0.6.2.jar semordnilap.cjam <N> ``` so the input is given as a command-line argument. How it works (slightly outdated): ``` "Prepare word list:"; "ri.ms/§"gDcN+/ "ri.ms/§"g "Fetch list from shortened URL."; DcN+ "Create \r\n string."; / "Split input into lines."; "Process input:"; {,ea~i=}, { }, "Filter the list."; , "Get word length."; ea "Push command-line arguments."; ~ "Unwrap array."; i "Convert to integer."; = "Check equality."; "Find all palindromes and semordnilaps:"; _Wf%& _ "Duplicate list."; Wf% "Reverse each line."; & "Set intersection."; "Remove duplicates and palindromes:"; {_W%>},N* { }, "Filter list."; _W% "Duplicate word, reverse."; > "Check lexicographic order."; N* "Join with newlines."; ``` The resulting string is automatically printed at the end of the program. [Answer] # Java, ~~280~~ 218 bytes Compared to the rest of the competition, I have absolutely no idea if this is a good score. ``` void a(int n)throws Exception{List<String>l=Files.readAllLines(Paths.get("w.txt"));for(String s:l){String c=new StringBuilder(s).reverse()+"";if(s.length()==n&&c.compareTo(s)>0&&l.contains(c)){System.out.println(s);}}} ``` Expanded: ``` void a(int n)throws Exception{ List<String>l=Files.readAllLines(Paths.get("w.txt")); for(String s:l){ String c=new StringBuilder(s).reverse()+""; if(s.length()==n&&c.compareTo(s)>0&&l.contains(c)){ System.out.println(s); } } } ``` Uses compareTo() to simultaneously ignore palindromes and duplicates. [Answer] # CJam, 68 bytes ``` "www.ri.ms/§"gDc-N/{_,ea~~=\_W%=!*},:Q{_W%aQ\/,({Q\a-:Q;1}{;0}?},N* ``` You will have to download the Java version of the compiler from [here](http://sourceforge.net/projects/cjam/) and save the above code in a file called words.cjam (can be any name). Then run the code like ``` java -jar cjam-0.6.2.jar <file_name> <input_number> [> <output_file_name>] ``` For example, for `N = 8`, ``` java -jar cjam-0.6.2.jar words.cjam 8 > out.txt ``` [Answer] # Node.js, 172 bytes Function: ``` function d(n){return(require('fs').readFileSync("w.txt")+"").match(RegExp(("b"+Array(n+1).join("(.)")+"b(?=(.|s)*b"+"87654321".substr(-n)+"b)").replace(/\w/g,"\\$&"),"g"))} ``` Testing: ``` console.log(d(+process.argv[2])); // run from command line like this: // node main 4 // where // main is js file name // 4 is length ``` [Answer] # K, 59 bytes ``` {*+?{x@<x}'+(w;r)@\:&(x=#:'w)&(~w~'r)&w in r:|:'w:0:`w.txt} ``` Pretty straightforward. Read the list, construct the reverse list, take their intersection, filter out the palindromes, filter in the required count, sort and dedupe the pairs. [Answer] # Ruby, 95 bytes ``` f=->n{l=[] (a=IO.read"w.txt").split.map{|w|a[w]=?. w.size==n&&a[/^#{r=w.reverse}\s$/]&&l<<w} l} ``` ## Explanation * Input is taken as the argument to a lambda. It expects an `Integer`. * Read the file into memory as a `String` (`a`). * Loop trough an `Array` of all words (without newlines). + Remove the word from `a`. + Add qualifying words to the `Array` `l`. * Return `l`. An empty `Array` is returned when no qualifying words were found. [Answer] # Node.js, CoffeeScript, 132 Bytes ``` f=(n)->(require('fs').readFileSync('w.txt')+'').split('\n').filter((s,i,f)->s.length==n&&f.indexOf(s.split('').reverse().join(''))>i) ``` # Node.js, 162 Bytes ``` function a(n){return(require('fs').readFileSync('w.txt')+'').split('\n').filter(function(s,i,f){return s.length==n&&f.indexOf(s.split('').reverse().join(''))>i})} ``` **Chrome Dev Tools Console, 111 Bytes** (On the download page) ``` f=(n=>$('pre').innerText.split('\n').filter((x,i,a)=>x.length==n&&a.indexOf(x.split('').reverse().join(''))>i)) ``` All versions return an array of all Semordnilaps of length `n`. # Node.js, 162 Bytes Prints all semordnilaps: ``` function a(n){(require('fs').readFileSync('w.txt')+'').split('\n').map(function(s,i,f){s.length==n&&f.indexOf(s.split('').reverse().join(''))>i&&console.log(s)})} ``` [Answer] # Julia, 101 bytes ``` k=split(readall("w.txt")) for(i=k) ([]!=(l=find(x->x==reverse(i)&&x!=i,k)))&&(println(i);k[l]="") end ``` This should actually work... [Answer] # Mathematica, 105 bytes ``` F[f_,n_]:=(W=StringSplit@Import@f;Select[W,StringLength@#==n&&MemberQ[W,r@#]&&Order[r@#,#]==1&&r@#!=# &]) ``` Sometimes Import will automatically split the text into list of list of lines, or treat it as CSV or TSV. At other times, Import will read the contents of the file into a string. Import did the latter for the test data. ![tests](https://i.stack.imgur.com/MFGWy.png) [Answer] **BASH** ``` f() { w=($(cat "${1}")) for ((i=0;i<=${#w[@]};i++)); do if ((${#w[$i]} == $2)); then r= for((x=${#w[$i]}-1;x>=0;x--)); do r="$r${w[$i]:$x:1}"; done if [[ ${w[$i]} != ${r} ]] && grep -qw $r "${1}"; then echo "${w[$i]}, ${r}" fi unset w[$i] fi done } ``` tests... ``` f /usr/share/dict/words 5 debut, tubed decaf, faced decal, laced deeps, speed denim, mined devil, lived draws, sward faced, decaf keels, sleek knits, stink laced, decal lager, regal leper, repel lever, revel lived, devil loops, spool loots, stool mined, denim parts, strap peels, sleep pools, sloop ports, strop rebut, tuber regal, lager remit, timer repel, leper revel, lever sleek, keels sleep, peels sloop, pools smart, trams snaps, spans snips, spins spans, snaps speed, deeps spins, snips spool, loops spots, stops sprat, tarps stink, knits stool, loots stops, spots strap, parts straw, warts strop, ports sward, draws tarps, sprat timer, remit trams, smart ``` ]
[Question] [ **[World Bowling scoring](https://en.wikipedia.org/wiki/Ten-pin_bowling#World_Bowling_scoring)** Many people have gone to their local bowling center to play a few games of bowling, and many people continue to struggle to calculate their scores. World Bowling has introduced a simplified scoring system in order to attract more people to the sport. This scoring system is utilized in international games. The scoring system works like this (from [Wikipedia](https://en.wikipedia.org/wiki/Ten-pin_bowling#World_Bowling_scoring)): > > The World Bowling scoring system—described as "current frame scoring"[32]—awards pins as follows: > > > * strike: 30 (regardless of ensuing rolls' results) > * spare: 10 plus pinfall on first roll of the current frame > * open: total pinfall for current frame > > > If you're not familiar with ten-pin bowling, here's a recap. There are 10 pins at the end of a bowling lane where the goal is to knock all of them down with a bowling ball. You get 2 rolls of a ball to attempt to knock them all down, preferably knocking them all down with the first roll (known as a **strike**). If you do get a strike, then that frame is completed and you do not need to roll the ball a second time. A strike is worth 30. If you don't knock down all ten, you get one more roll. If you knock down all of the remaining pins, that is known as a **spare**. The score is worth 10 pins + the number of pins knocked down on the first roll. For example, if I knocked down 7 pins, then managed to knock down the remaining 3, that would be worth 17. If after your second roll you fail to knock down all ten, that is known as an **open frame**. The score is worth the total number of pins knocked down for that frame. There are **10 frames in a game**. If you're familiar with traditional bowling scoring, you don't get an extra roll in the 10th frame with the World Bowling Scoring. In traditional bowling scoring, it takes 12 consecutive strikes to get a perfect score of 300, whereas World Bowling scoring only requires 10 consecutive strikes. ## Challenge Your challenge is to calculate the score given values from a score sheet. On a score sheet, a **miss** is indicated by a dash (**-**), a **strike** with an **X**, and a **spare** with a slash (**/**). If these don't apply, then the pinfall count is simply indicated with a number (1-9). Fouls and splits are also recorded onto score sheets but you do not need to worry about these. ## Input You will be given a string consisting of scores for each frame, and will have a total of ten frames. Each frame will have up to two values, or as little as 1 value if there was a strike. Your input may be string parameter to a function, read from a file, or from STDIN. For example, if I knocked down 1 pin on my first roll, then knocked down 2, the frame would look like "12". This does not mean 12 (twelve), but means 1 and 2, for a total of 3. If I missed every pin with both rolls (gutter balls), it would look like this "--" (score of 0). Each frame will be separated by a space. ## Sample input ``` -- 9- -9 X -/ 8/ 71 15 44 X ``` To break down this example, * Frame 1 (--) - both rolls missed. scored 0 * Frame 2 (9-) - knocked down 9 on the first roll, missed on the second roll. Score 9 * Frame 3 (-9) - Missed all on the first, got 9 on the second. Score 9 * Frame 4 (X) - Strike, knocked down all ten. Score 30 * Frame 5 (-/) - Spare, missed all on the first, knocked down all with 2nd roll. Score 10 + 0 = 10 * Frame 6 (8/) - Spare, 8 pins on first roll, knocked down the other 2 with 2nd roll. Score 10+8 = 18 * Frame 7 (71) - open frame,7 pins on first roll, 1 pin on second roll. Score 7+1=8 * Frames 8,9,10 follow same examples as above. ## Output Output will simply be a value that has the sum of the scores from all 10 frames. Using the sample input, the output will be 128. Your output may be a string or a numeric type. It may be a function return value, or written to STDOUT. ## Rules * Assume that the input will always be valid. For example, an invalid frame would be "/8", "XX", "123", "0", etc. * You do not need to worry about splits or fouls. * Your code may be a full program or a function that takes in a string and returns the score. * Your code must not throw any exceptions. * This is code golf, the answer with the **fewest number of bytes wins.** * Languages that use includes or imports must include the import statements as part of their code and count towards the byte count. ## Test Cases ``` "-- 9- -9 X -/ 8/ 71 15 44 X" -> 128 "-- -1 2- 12 22 5- 42 61 8- 72" -> 45 "X X X 1/ 2/ 3/ 4/ 5/ -- 9/" -> 174 "X X X X X X X X X X" -> 300 "-- -- -- -- -- -- -- -- -- --" -> 0 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes ### Code ``` S'/T:'X30:O ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/WF0/xEo9wtjAyv///wgFEDTUVzDSVzDWVzDRVzDVV9DVVbDUBwA "05AB1E – Try It Online") ### Explanation ``` S # Split the string into a list of characters '/T: # Replace '/' with 10 'X30: # Replace 'X' with 30 O # Sum up the array (ignoring non-number elements) ``` [Answer] # JavaScript, 43 bytes ``` f=([c,...s])=>c?({'/':10,X:30}[c]|c)+f(s):0 ``` ``` f=([c,...s])=>c?({'/':10,X:30}[c]|c)+f(s):0 ``` ``` Score(<input style="width:200px" oninput="o.value=f(this.value)" />) = <output id=o></output> ``` ## How it works We convert each character to its point: * 'X' worth 30 point * '/' worth 10 point * '1' .. '9' worth 1 .. 9 point * other characters worth 0 point Then sum all points. **Convert** Bitwise *OR* operator `|` convert its operand to Int32 before operate. When converting to Int32, value first convert to Number (64bit float number) format, then trunk to Int32 (or converted to 0 if invalid). * `ToInt32({'/':10,X:30}[c])` could be read as: + if c == '/': result is 10; + if c == 'X': result is 30; + otherwise: result is `ToInt32(undefined)` -> `ToInt32(NaN)` -> 0; * `ToInt32(c)` could be: + if c == '1' ... '9': result is 1 .. 9; + if c == ' ': `Number(c)` is 0, result is 0; + otherwise: `Number(c)` is `NaN`, result is 0; * Bitwise or here is same as "add", since one of its operand will be 0 **Sum** * `[c,...s] = s` let `c = s[0]`, and `s = s.slice(1)`; + if s is empty string, c is *undefined*; + otherwise, c is first letter of s * undefined is falsy, non-empty string (including space) is truthy [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ─*âⁿ┴8òt↨HÉ÷8 ``` [Run and debug it](https://staxlang.xyz/#p=c42a83fcc1389574174890f638&i=%22--+9-+-9+X+-%2F+8%2F+71+15+44+X%22%0A%22--+-1+2-+12+22+5-+42+61+8-+72%22%0A%22X+X+X+1%2F+2%2F+3%2F+4%2F+5%2F+--+9%2F%22%0A%22X+X+X+X+X+X+X+X+X+X%22%0A%22--+--+--+--+--+--+--+--+--+--%22&m=2) Unpacked, ungolfed, and commented it's thus. ``` F for each character in input, execute... 9R$'/20*+'X+ build the string "123456789////////////////////X" I get the index of the current character in string ^+ increment and add to running total (index is -1 when no match; space and dash are 0 score) ``` [Run this one](https://staxlang.xyz/#c=F++++++++++++%09for+each+character+in+input,+execute...%0A+9R%24%27%2F20*%2B%27X%2B%09build+the+string+%22123456789%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FX%22%0A+I+++++++++++%09get+the+index+of+the+current+character+in+string%0A+%5E%2B++++++++++%09increment+and+add+to+running+total%0A+++++++++++++%09%28index+is+-1+when+no+match%3B+space+and+dash+are+0+score%29&i=%22--+9-+-9+X+-%2F+8%2F+71+15+44+X%22%0A%22--+-1+2-+12+22+5-+42+61+8-+72%22%0A%22X+X+X+1%2F+2%2F+3%2F+4%2F+5%2F+--+9%2F%22%0A%22X+X+X+X+X+X+X+X+X+X%22%0A%22--+--+--+--+--+--+--+--+--+--%22&m=2) [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` lambda l:sum(map(('123456789/'+'X'*20).rfind,l))+len(l) ``` [Try it online!](https://tio.run/##dc/BboMwDAbgM3mKX@xAstYLMUmBSt1zIG07UHVoSCFFQA97elZgm7TDbF8sffIv95/TxzXw3JxeZ19350sNfxxvnezqXsrEcGbdIS9KneySKnnkVD0NTRsue6/Uzr8H6dXchv424YSXmAglgUpUII1CIzcwDtaiivfAA@gZhguBaKFkwHTfwQxHsIyDQUHI@Y5Xa52I4gpLGw3WyDSshtNYkvRy8@dqbn/pn97Md600S1Ox5f878dtGU9FcB4xoA9YnjyLqhzZMaOSo5i8 "Python 2 – Try It Online") Based off the string-index approach of many solutions. [Answer] # Java 8, ~~64~~ ~~59~~ 46 bytes ``` s->s.map(c->c<46?0:c<48?10:c>87?30:c-48).sum() ``` -5 bytes thanks to *@Neil*. -13 bytes thanks to *@OlivierGrégoire*. **Explanation:** [Try it online.](https://tio.run/##lY@9TsMwFIX3PsVRJ2e4NnbTNqWQzAx06VIJMRg3QELiRrFTCaE@e3BSFpBAVPdax/dHn49LfdRU7t96U2nncK8L@zEBCuvz9lmbHJuhHBswrAzbvPNFxZ1vc13zO@u34w0uWofFUzghnde@MNjA4ha9o9TxWjfMUGpu4kV2dR0kyWTQNFlms6AUJxF3Xc2ifn1mNN1TFRhfqOOh2KMO7lh4r7AvD486Ojvbvjuf1/zQed6Eia8ss9ywKRFWBFphBxJIBJYSco44xm7KzatuHYui0fSfDJJQBKmgFOaEWGEhkRCW6t@UHYaQAkpgJhALzAUGe@JCxLe46BO/5g/KaXLqPwE) ``` s-> // Method with an IntStream parameter and integer return-type s.map(c-> // Loop over the characters c<46? // If the character is a space or '-': 0 // Count it as 0 :c<48? // Else-if it's a '/': 10 // Count it as 10 :c>87? // Else-if it's an 'X': 30 // Count it as 30 : // Else (it's a digit): c-48 // Count it as the value of the digit ).sum() // And sum everything ``` [Answer] # F#, 106 103 bytes ``` let s c=Seq.sumBy(fun x->if x=' '||x='-'then 0 elif x='X'then 30 elif x='/'then 10 else int(string x))c ``` [Try it online!](https://tio.run/##dY5BS8NAEIXv/RUfBUlzGLe7TWwLTQ6Cd8FLQDyUsKkL7VaTraSQ/x6TRhAPMgMD3@O9eVUj5bm2fX@0gYYye7Gf983l9HhdVBdPK7mraLOIqOuGI1F4t54l9jjxYgKrX6ImokfSWJwPiybUzh9o47jsX3dPPtTX5/Mg5G@z8e1p7zz7@vBFxoyxgAu2ZiqA5HwM9lB55nduzq4berbEN8eMZd@LsBVkS4EoNoq1RqckCcWoicYI2mAMqZAYHjQbYW36gnG0wihWikSRKsY49SP9mVvYv/sN) I think that this puzzle (without the golfing) would be a great question for a "Functional programming for beginners" guide. And I should know! -3 from Kevin Cruijssen, for spotting that the whitespace between ' and "then" can be deleted. Thanks! [recursive's Stax solution](https://codegolf.stackexchange.com/a/160264/78954) of using string indexes is very very good. If you port it to F# you can get it for **77 bytes**: ``` let s c=Seq.sumBy(fun x->"123456789/???????????????????X".IndexOf(char x)+1)c ``` [Try this online!](https://tio.run/##dY5BS8NAEIXv@RUfgUKDTNfdJk0CbQTBgycFLwHxEGJSA3arm1RS8L@vTfUi4ry5vZnvvbaXeu8a71@bgZ5689C8L/rD7vo4bw@WUYpQm2WcrNIsV1d/pwwXt/a5Ge/aef1SOcboQke1f1zf2MEd7/edHYqnYILvqs5Sue0HGwKmmG5oHN8xSMGbOx23lnDWhaw/T21GovNHwKX3IuSC5JSIIlOkGp0Qx5STJxojaIMxJEJsWGkyITW@ZJJWGMVSESsSxYRTP9YvnWH/7hc) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟ⁾ -“X0/⁵”yV€o30S ``` A monadic link accepting a list of characters and returning an integer **[Try it online!](https://tio.run/##AUIAvf9qZWxsef//4bif4oG@IC3igJxYMC/igbXigJ15VuKCrG8zMFP///8tLSA5LSAtOSBYIC0vIDgvIDcxIDE1IDQ0IFg "Jelly – Try It Online")** ### How? ``` ḟ⁾ -“X0/⁵”yV€o30S - Link: list of characters ⁾ - - literal list of characters [' ','-'] ḟ - filter discard “X0/⁵” - literal list of characters ['X','0','/','⁵'] y - translate (change 'X's to '0's and '/'s to '⁵'s) V€ - evaluate €ach character as Jelly code (the '⁵'s become 10s) o30 - logical OR with 30 (change all instances of 0 to 30) S - sum ``` --- Also at 17: ``` ”/ẋ20ØD;;”XḊiЀ⁸S ``` [Try that](https://tio.run/##y0rNyan8//9Rw1z9h7u6jQwOz3CxtgbyIh7u6Mo8POFR05pHjTuC////r6urYKmroGupEKGgq69goa9gbqhgaKpgYqIQAQA) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 30 bytes ``` {TR'-/X '0㉈㉊'.univals.sum} ``` [Try it online!](https://tio.run/##dYw7CsJAFEVrXcUtxFHIy3NeJr/CTYjFdJLCgJCoZIgQxN64zSxkJAqihZzbncs575sq8XWHeYm1v243ithCrYb@PvQPFbbHw6WoXOja@uZd0aFczHZLlKdmOlFEyAmUw4IYGSPV0DGMgVXB25OGELRABDHBCBKNjJDK62ExohnCiBiGETPGLH/pHz7hv1OBfwI "Perl 6 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 17 bytes ``` X /// / 55 \d * _ ``` [Try it online!](https://tio.run/##dYyxCsJAEAX7/YpphCAsj13vTPIF/sIVARW0sLEQ//80YmMhM93APK7P2/0cfTMcTr2ZJJPVasvFtnbs3Z3Z8ZmGi0mMQVRKodm7eZBOJJlUpyT7YHLGtMZKiBQ7UUQV607f9MNn9tcX "Retina – Try It Online") I'm not quite up to date on the latest Retina changes. I'll be looking more into them when I get a chance and seeing if there's any new tricks for golfing this down. The code turns all strikes in to three spares, all spares into ten points, then all points to the corresponding number of underscores. Then it counts the number of underscores. [Answer] # [Perl 5](https://www.perl.org/) `-pF`, ~~30~~ 27 bytes -3 bytes thanks to [Xcali](https://codegolf.stackexchange.com/users/72767/xcali) ``` #!/usr/bin/perl -pF $\+=m%/%+3*/X/.0+$_ for@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRts2V1VfVdtYSz9CX89AWyVeIS2/yMGttvr/f11dBUtdBV1LhQgFXX0FC30Fc0MFQ1MFExOFiH/5BSWZ@XnF/3UL3AA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` þ`I…/aXS¢ƶT*`O ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8L4Ez0cNy/QTI4IPLTq2LUQrwf//fyVdXQVLXQVdS4UIBV19BQt9BXNDBUNTBRMThQglAA "05AB1E – Try It Online") **Explanation** ``` þ` # Push the digits of the input on the stack (removes everyting that isn't a digit) I…/aXS # Push the input and the array "/","a","X" on the stack ¢ # Index of each element in the input ... ƶT* # ... multiplied by its index (a could be anything that can't be found in the input), multiplied by 10. `O # Sum the stack, implicit display ``` [Answer] # [J](http://jsoftware.com/), 33 bytes ``` 1#.31|('-123456789',20 1#'/X')i.] ``` [Try it online!](https://tio.run/##dY09CsJgEAV7TzGYYg1ks9nNF5MIVoKVlVUaKzGojRfw7lErf0DmvW5grtO8lJH1CqGgYvW8lmz2u@3kWVn7fSHqUadm2Xa9FFHhmdgg@aU8TPmM2el4vjEiqvSK9gyo0Rmt4w0pMcinpE4oHkTQKClYOp3SxlsbeOFGGLWRjMZ4BezX@eK783cyPQA "J – Try It Online") ## Explanation: `]` the input `('-123456789',20 1#'/X')` appends 20 `/` and one `X` to the string `-123456789` `i.` finds the indices of the input in the above string `31|` modulo 31 - to get rid of the spaces - they are not found in the string, so `i.` returns 31 for them `1#.` finds the sum of the indices [Answer] # [Python 2](https://docs.python.org/2/), 67 bytes -3 bytes thanks to @KevinCruijssen ``` lambda I,p='-123456789/'+20*'X':sum(p.rfind(i)for i in I if i in p) ``` [Try it online!](https://tio.run/##dY9Ba4NAEIXP7q942IPaZrruuBs1YO@B/ACh7SEhSBaazaLmkF9vstoWeui8OczAx3s8fxtPF8fTrvmYvvbnw3GP7co3CSkutFmXVS2TF86fkzbZDNdz6l/7zrpjarPu0sPCOmxhu@Xy2WSdv45o8B4ToSZQjRYkUUmUCspAa7TxCngCvUFxJRAFlBSYHj@YYQiasVaoCCU/4JnVRkRxiyAlwRKFhJYwEiFJBs8f11L/on@0MN8zo0WeiyX/340/FzQXofEQes4lNyLyvXUjdumQTXc "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ⁾/X,“½œ‘y|0S ``` [Try it online!](https://tio.run/##dYyxDcJAEMD6TOEBOB13fEgyB80zAA3KApEoAg0D0FAwAiUdggLEIPwiD0E0FMjuLHm5aNsu57S@ahyl/nC7PHap33er8Sw/z6f7Nm2O85xFaARpiIhSK5VhJSEQi3cTwwVz3CmF4EyNWqi8iAyY4spECUqpDDv9ph8@s7@@AA "Jelly – Try It Online") ## How it works ``` ⁾/X,“½œ‘y|0S Main link. Argument: s (string) ⁾/X,“½œ‘ Literal; yield [['/', 'X'], [10, 30]]. y Transliterate; replace '/' with 10, 'X' with 30. |0 Bitwise OR with 0. Bitwise operators attempt to cast to int, mapping '0', ..., '9' to 0, ..., 9. All other characters map to 0. S Take the sum. ``` [Answer] # [Python 3.6](https://docs.python.org/3/), 54 bytes ``` lambda s:sum(map(f'123456789/{6**24}X'.find,s),len(s)) ``` [Try it online!](https://tio.run/##dY69DoJAEIRreIoJDYdh3dxy/Ca@B4UNRi@SwEk8LYzx2VGotDAz1cyXyUyP2/nistlih/08dOPh2ME3/j6qsZuUjbVkJi/KquZnsdmIebXx1vbumPokHU5O@SSZ7eUKj95BhUFEhJpANVoQo2KUGjqHMWijNMQKkIYQtEAEOcEICo2KUMoHCaIWizRDGBnDMHLGsstf9Y/WfBn@6w@RNGEwXXt3U3a9/QY "Python 3 – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 50 bytes ``` x->x.sumBy{"123456789/_${Math.E}_X".indexOf(it)+1} ``` [Try it online!](https://tio.run/##dZBBa4NAEIXv/orH4kFpxmU3GjVQD4Uceig59OItLG1NlphN0U2wyP52q5IeWtL3Zm4f83hzPNtam6G6GJyUNsFVNarZY9x2jVfbaLMP0XsYVevWbquAESEnUI4SxJFxpAIiQRyjZIuZ/NGEkoAkCAkpkRBiiZVARkjlX7jEZMEhOZYcMUfCMYXx@@Qv30v@d1gYVedmo94Ot2qTPseutjYB87UFFfD7KtA2dCycEec5z7uqGtU6uP2FimdjH/uho6KL2svp6atnQi7jZJVmOd/5/Yuyh2jjdiWLtHn/6LbzxQfhBjd8Aw "Kotlin – Try It Online") Hopefully it's not against the rules to answer your own question but I wanted to join in on the fun. `Math.E` produces the value `2.718281828459045`. I'm using it to create some filler string to push X to position 30. `indexOf` gets the position (0-based) of the character in the string "12345...". If it isn't found, it returns -1. We add 1 to make these 0, and that also makes the 0-based position the value of the string. [Answer] # PHP, ~~119~~ 109 bytes -10 bytes thanks to *@KevinCruijssen* ``` <?foreach(explode(" ",$argv[1])as$f){[$a,$b]=str_split($f);$n+=$f==X?30:(int)$a+($b=='/'?10:(int)$b);}echo$n; ``` [Try it online!](https://tio.run/##NcjRCoIwFADQX7nIBTd0rJFRtoa/IYjEtJmCbMONCKJfb/XSeTx@9ildmsltRo8zMU@/upshGWQl6u3@6ERPdcCJvjrUJQ69CnG7Br8ukfxWoi0UTkq1zX53JouNFHVBcFAq53kj/jdQ@Tbj7NDKlBJjUDNgNbTAOJw4HAWIA1QVtB/n4@JsSMx@AQ) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` IΣEχΣES⎇№-/Xλ×χ⌕-//XλIλ ``` [Try it online!](https://tio.run/##NYxBCsIwFESvMnT1hX5ioKLFZUFwIQh1kW2oRQNpWtJE8PQxrTqrB29muqf23ahtSldvXKBGz4HaONBFTyS3Jf58dlMMbcilB21K3HrvtH9TM8a8KlioooRdhBn6eV2ejLsv5qeyW88zfXNMiRk1g2sosMBBYC8hd6gqqMQv@wE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Eχ Map over 10 frames S Input the frame E Map over the characters λ Current character №-/X Search the literal string `-/X` λ Current character ⌕-//X Find position in literal string `-//X` ×χ Multiply by predefined variable 10 λ Current character I Cast to integer ⎇ Ternary Σ Sum for each frame Σ Sum over frames I Cast to string for implicit print ``` [Answer] # [Red](http://www.red-lang.org), 93 bytes ``` func[b][s: 0 foreach c trim/all b[s: s - 1 + index? find{-123456789/...................X}c]s] ``` [Try it online!](https://tio.run/##dY3LCoJQFEXnfsXCaZxO93ZNbdI/NBLEQamXBLPQgiD6dstZD9p7wxmcBauvq3FbV@RF4Nejv3Zlvi/yYc0i8Ke@3pUHSi59c9Rd27KfPgOCYUbTVfVtg3/duxi7dNEqTlKd/yZ7lMVQjAHBuW@6C55QhFSQlAxREiU2mAjnyMIPSgz25bNYSyQ4y8qQCLF94zKmGsUqS8UpkTIp9Af66Jfq78LxCQ "Red – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 40 + 18 = 58 bytes ``` using System.Linq; s=>s.Sum(c=>c>87?30:c<46?0:c<48?10:c-48) ``` [Try it online!](https://tio.run/##lY9BS8NAEIXv@RWPnhJwsu5206S2SQ4FT3rqwYJ4CGtaFtoNZjaCSH97TFoRFIT2vYG5vPl4Y5hM09Z9x9btsP5gXx/iB@veFkFg9hUzVsFngEHsK28N3hv7isfKupB9O9w8v6BqdxydMufkqG/SfefM8hy8gXW@wDbvOS84XneH0OSFKbK0nN7emaWelaeVlXLYpLOoHzr84a0ax82@jp9a6@uhZh1uwwkR5gSaYwMSyARSCZlAa2wmUbS4lEESiiAVlEJC0AoziYyQqospG4yWAkpgKqAFEoGxnrgS8ctXPfHv/FCOwbH/Ag "C# (.NET Core) – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 53 bytes ``` Write(ReadLine().Sum(c=>c>87?30:c<46?0:c<48?10:c-48)) ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/vCizJFUjKDUxxSczL1VDUy@4NFcj2dYu2c7C3N7YwCrZxsTMHkxZ2BsCaV0TC03N//91dRUsdRV0LRUiFHT1FSz0FcwNFQxNFUxMFCIA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~169~~ ~~151~~ 147 bytes ``` F =INPUT ' ' R F '-' =0 :S(R) T F 'X' ='_' :S(T) S F LEN(1) . X ARB . Y ' ' REM . F :F(O) X '_' =30 Y '/' =10 S =S + X + Y :(S) O OUTPUT =S END ``` [Try it online!](https://tio.run/##FY7BCsIwEETP2a@YWxJKbIMVbSEHxRYEbSVJIT0JnsUe/H/i5rSzb/fB/L7be/u0OYsR7jY9lwgJSZ5XaSRcI/qgvKZYQGIgX7KgqCkwug@Tsho7JJz9hedadPjhwXkU/ahmTSKBLbh9Q4LvNUfLMcAFVGxWWEWvgqZZzEssFVygYbrmbAw6A9Pxk6lxqnG0sAe0LdIf "SNOBOL4 (CSNOBOL4) – Try It Online") ``` F =INPUT ' ' ;* read input and append a space R F '-' =0 :S(R) ;* replace - with 0 T F 'X' ='_' :S(T) ;* replace X with _ S F LEN(1) . X ARB . Y ' ' REM . F :F(O) ;* set first character to x, remainder up to ' ' to y, and remainder to F X '_' =20 ;* replace _ in x with 20 Y '/' =10 ;* replace / in y with 10 S =S + X + Y :(S) ;* else X and Y are their values so we can sum them O OUTPUT =S ;* output the sum END ``` [Answer] # [Clojure](https://clojure.org/), 70 bytes ``` #(reduce(fn[s i](+ s(case i\- 0\/ 10\X 30\space 0(bigint(str i)))))0%) ``` [Try it online!](https://tio.run/##FctBCsIwEAXQq3wqwgQZkmBFe5OAcVHjKCMllqQ9f2zf/qXp912LNJqL5mXKoHagIq81Cb3zvUIfdEKlNFaBRoaLFt7FgLOLdR6TwNFTP1umuhSo2bmjaR0zBgYPCGCLm8XVw1/Q9widMe0P "Clojure – Try It Online") When `reduce`ing over a String, each char is actually converted into a char - who would have thought. But this meany, I have to write `\space` and that hurts more than one can imagine. Also, when creating an actual number from a char, the combination of `bigint` and `str` seems to be the only usable combination. Well, aside from all these struggles: Anonymous function that returns the score as a natural. [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes ``` ->s{s.tr("/X -",":N00").sum-s.size*48} ``` [Try it online!](https://tio.run/##dY/BbsIwEETv@YqRubQom42NQ0Kl8Ak9R6p6AGRaDiDEJhKt8benjltV7QHNnmbf7mguw/Zj3LcjrcVL0V8eFHcglaun57JUj4UMR5JCDp9ubpsw9k56QQufAYoIKwKtEC8YDaPW0BWsRafQrqFNk/9wpGEoGjAGFcEaLDUaQm0SaasEdpikGYaxYFhGxZhS@Ptfbf9g/5T2i7L8zbs7iYxcyFKXwm127/A3yd0N5yGWUzMvYYJmfv8iryGHu57drj@c3qLlggrZ@AU "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 17 bytes ``` +ṁi¹*10+#'/¹*3#'X ``` [Try it online!](https://tio.run/##dYwxCsJQEAWvMiRFwGRZd/NjknPYfBB7RcRCxDq5VVpvohf5JiCChcwrHgzM4XY9pfPlvq1e45DK5zQcH9PK1mVe6HzqvIgppV0mQi9IT0SUTmkNawiBmFWLFcMFc9xphOBsjE5offaRBVNcqZWgNMqS1K/84ZP8u2z/Bg "Husk – Try It Online") This function takes the sum of all digit characters in the string, plus 10 times the number of `/` characters, plus 30 times the number of `X` characters. ]
[Question] [ Given a positive integer input **N**, output the two non-negative numbers, **a** and **b**, where **a < b**, with the lowest possible mean value that will result in the number **N** being part of the recurring relation sequence: ``` f(0) = a f(1) = b f(n) = f(n-2)+f(n-1) ``` ~~In case there are more than one solution where the mean of **a** and **b** are minimal, then you should output the one with the lowest **b**.~~ Proof that this is not possible is provided by [cardboard\_box](https://codegolf.stackexchange.com/a/147843/31516). Your can assume **N** is within the representative range of integers in your language / system. ### Test cases ``` N = 1 a = 0, b = 1 N = 15 a = 0, b = 3 N = 21 a = 0, b = 1 N = 27 a = 0, b = 9 <- Tricky test case. [3, 7] is not optimal and [4, 3] is not valid N = 100 a = 4, b = 10 N = 101 a = 1, b = 12 N = 102 a = 0, b = 3 N = 1000 a = 2, b = 10 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~19~~ ~~18~~ ~~16~~ ~~14~~ ~~13~~ 15 bytes Thanks Zgarb for saving 1 byte. ``` ḟö£⁰ƒẊ++ÖΣṖ2Θḣ⁰ ``` [Try it online!](https://tio.run/##yygtzv7//@GO@Ye3HVr8qHHDsUkPd3Vpax@edm7xw53TjM7NeLgDJPz//38jcwA "Husk – Try It Online") ### Explanation: **Disclaimer:** I really don't understand the `ȯƒẊ++` section of the code. Edit: It appears to translate to the Haskell `fix.(mapad2(+).).(++)`, where `mapad2` is apply function to all adjacent pairs in a list. (Although, knowing Husk, in the context of this program it could mean something else) ``` Θḣ⁰ Create the list [0..input] Ṗ2 Generate all possible sublists of length 2 ÖΣ Sort them on their sums ḟ Find the first element that satisfies the following predicate. ƒẊ++ Given [a,b], magically generate the infinite Fibonacci-like sequence from [a,b] without [a,b] at the start. ö£⁰ Is the input in that list (given that it is in sorted order)? ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 92 90 89 91 83 82 bytes -3 bytes -1 byte thanks to ThePirateBay -8 -9 bytes thanks to Neil. ``` f=(n,a=1,b=0,c=(a,b)=>b<n?c(a+b,a):b>n)=>c(a,b)?b+2<a?f(n,a-1,b+1):f(n,b-~a):[b,a] ``` [Try it online!](https://tio.run/##TU5PT4MwFD/Dp3g70YaytFVjHOs47eJBDx4JhxbphiGtKbjFuPnVsWVMbS@/v@@9N3mQfe3a9yEz9rUZRy2QIVIwogQltUCSKCw2am2KGslUEYlXamO8VE9WoVK@loUOpcyXUoZXgajs2ydLn6/Gg3QwNP3Qg4AyjkpGKGEV8Yj/QXbn4c0FUkpuCaMzYcR/PhP@P0UJv8b4vTcePKzyOJ6WLbV1W1nvUWAgNvAVR@ES1/QfnRcA9GSVtMJ5HNXW9LZrlp3doUSjBFKYXY8S7PNBenx5flr2g2vNrtWf6DILh36rYaahshDiUmcVnE7zzkB@DV7hcFE07J09gmmOsHXOOpQswkvCyHN8xvn4Aw "JavaScript (Node.js) – Try It Online") Note: this solution relies on the fact that there are never multiple minimal solutions. # Proof that there are never multiple solutions: Let `FIB(a,b,k)` be the Fibonacci-like sequence starting with `a,b`: ``` FIB(a,b,0) = a FIB(a,b,1) = b FIB(a,b,k) = FIB(a,b,k-1) + FIB(a,b,k-2) ``` ## Lemma 1 The difference between Fibonacci-like sequences is itself Fibonacci-like, i.e. `FIB(a1,b1,k) - FIB(a0,b0,k) = FIB(a1-a0,b1-b0,k)`. The proof is left to reader. ## Lemma 2 For `n >= 5`, a solution `a,b` exists satisfying `a+b < n`: if `n` is even, `FIB(0,n/2,3) = n` if `n` is odd, `FIB(1,(n-1)/2,3) = n` ## Proof Cases where `n < 5` can be checked exhaustively. Suppose we have two minimal solutions for `n >= 5`, `a0,b0` and `a1,b1` with `a0 + b0 = a1 + b1` and `a0 != a1`. Then there exist `k0,k1` such that `FIB(a0,b0,k0) = FIB(a1,b1,k1) = n`. * Case 1: `k0 = k1` WLOG assume `b0 < b1` (and therefore `a0 > a1`) Let `DIFF(k)` be the difference between the Fibonnaci-like sequences starting with `a1,b1` and `a0,b0`: `DIFF(k) = FIB(a1,b1,k) - FIB(a0,b0,k) = FIB(a1-a0,b1-b0,k)` (Lemma 1) `DIFF(0) = a1 - a0 < 0` `DIFF(1) = b1 - b0 > 0` `DIFF(2) = (a1+b1) - (a0+b0) = 0` `DIFF(3) = DIFF(1) + DIFF(2) = DIFF(1) > 0` `DIFF(4) = DIFF(2) + DIFF(3) = DIFF(3) > 0` Once a Fibonnaci-like sequence has 2 positive terms, all subsequent terms are positive. Thus, the only time `DIFF(k) = 0` is when `k = 2`, so the only choice for `k0 = k1` is `2`. Therefore `n = FIB(a0,b0,2) = a0 + b0 = a1 + b1` The minimality of these solutions contradicts Lemma 2. * Case 2: `k0 != k1`: WLOG assume `k0 < k1`. We have `FIB(a1,b1,k1) = n` Let `a2 = FIB(a1,b1,k1-k0)` Let `b2 = FIB(a1,b1,k1-k0+1)` Then `FIB(a2,b2,k0) = FIB(a1,b1,k1) = FIB(a0,b0,k0)` (exercise for the reader) Since `FIB(a1,b1,k)` is non-negative for `k >= 0`, it is also non-decreasing. This gives us `a2 >= b1 > a0` and `b2 >= a1+b1 = a0+b0`. Then let `DIFF(k) = FIB(a2,b2,k) - FIB(a0,b0,k) = FIB(a2-a0,b2-b0,k)` (Lemma 1) `DIFF(0) = a2 - a0 > 0` `DIFF(1) = b2 - b0 >= (a0 + b0) - b0 = a0 >= 0` `DIFF(2) = DIFF(0) + DIFF(1) >= DIFF(0) > 0` `DIFF(3) = DIFF(1) + DIFF(2) >= DIFF(2) > 0` Once again, `DIFF` has 2 positive terms and therefore all subsequent terms are positive. Thus, the only time when it's possible that `DIFF(k) = 0` is `k = 1`, so the only choice for `k0` is `1`. `FIB(a0,b0,1) = n` `b0 = n` This contradicts Lemma 2. [Answer] # [Haskell](https://www.haskell.org/), ~~76 72~~ 74 bytes EDIT: * -4 bytes: @H.PWiz suggested using `/` instead of `div`, although this requires using a fractional number type. * +2 bytes: Fixed a bug with `Enum` ranges by adding `-1`. `f` takes a value of `Double` or `Rational` type and returns a tuple of same. `Double` should suffice for all values that are not large enough to cause rounding errors, while `Rational` is theoretically unlimited. ``` f n|let a?b=b==n||b<n&&b?(a+b)=[(a,s-a)|s<-[1..],a<-[0..s/2-1],a?(s-a)]!!0 ``` [Try it online!](https://tio.run/##RY7BisIwEIbvPsVYFpuQJiaFZUGMfYe9qoeJZmnZOJUmokLfvZuuBw/DfPP9DPwtxl8fwhTb/l6ChdbjGRTc@@Ec85714oId2Y6SH/CUPm4UOvJRXfDK2IHk7vVKQhQbKIRgB/aonhzkDkpWwgZe@QOEgLJ6i@csCl5w9gPEuUr9N6auJwxqyCW4@u8w5XAMPgE2zjpraRzdllYr1zAUjts9wypK5GPcyr1R6lhhBq1UXNfS5Kthc3xcLvU0GagNmE8wWufJqOuZNdRffw "Haskell – Try It Online") (with H.PWiz's header adjustments to input/output `Rational`s in integer format) # How it works * `?` is a locally nested operator in the scope of `f`. `a?b` recursively steps through the Fibonacci-like sequence starting with `a,b` until `b>=n`, returning `True` iff it hits `n` exactly. * In the list comprehension: + `s` iterates through all numbers from `1` upwards, representing the sum of `a` and `b`. + `a` iterates through the numbers from `0` to `s/2-1`. (If `s` is odd the end of range rounds up.) + `a?(s-a)` tests if the sequence starting with `a,s-a` hits `n`. If so, the list comprehension includes the tuple `(a,s-a)`. (That is, `b=s-a`, although it was too short to be worth naming.) + `!!0` selects the first element (hit) in the comprehension. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~75~~ ~~71~~ ~~64~~ ~~59~~ ~~53~~ ~~48~~ ~~44~~ 43 bytes *2 bytes saved thanks to @Adám* *12 bytes saved thanks to @ngn* ``` ⊃o/⍨k∊¨+\∘⌽⍣{k≤⊃⍺}¨o←a/⍨</¨a←,⍉|-\¨⍳2⍴1+k←⎕ ``` [Try it online!](https://tio.run/##FYy9DsFgFIb39yrOVlLS79RfiRswuQFLE2GopFbBRKifTywSO8O3Y5FYeinnRup0e3@feD6rjxfxLJ0WcrkNhrK7GkCy/aSQ4yYNxLpEsmPu/JFkdzn/xD6WiRye2or9rnOX6iUud/0gd7GamtjDqj7KndhXKPbNfqKp0gvFFksVpbUfr@fJaTtRRKVcmmqNjQExKAQ1QE1QC9QGdUARqAs2YAaH4Aa4CW6B2@AOOAJ3EWprzB8) Uses `⎕IO←0`. **How?** *This had gone real nuts.* `k←⎕` - assign input to `k` `⍳2⍴1+k←⎕` - Cartesian product of the range `0` to `k` with itself `|-\¨` - substract each right pair element from the left, and get absolute values `a←,⍉` - transpose, flatten and assign to `a` `o←a/⍨</¨a` - keep only pairs where the left element is smaller than the right, and assign to `o` `o` now contains list of all pairs with `a < b`, ordered by their arithematical mean `+\∘⌽⍣{k≤⊃⍺}¨o` - for each pair in `o`, apply fibonacci (reverse the pair and cumsum) until `k` or higher term is reached `k∊¨` - then decide if `k` is this last term (meaning it is contained in the sequence) `o/⍨` - and keep pairs in `o` where the previous check applies `⊃` - return the first result. [Answer] # [Python 2](https://docs.python.org/2/), ~~127~~ ~~109~~ 107 bytes *-2 bytes thanks to ovs (changing `and` to `*`)* ``` g=lambda x,a,b:a<=b<x and g(x,b,a+b)or b==x f=lambda n,s=1,a=0:g(n,a,s-a)*(a,s-a)or f(n,s+(a==s),a%s+(a<s)) ``` **[Try it online!](https://tio.run/##VY7NjsIwDITvfQpfVkrASEnYvVT1k1QcHGgLEpuiOqDy9CWh/ObizPgba07XuO@Dm6aOjvzvdwwjMvqSK/LVCBx20KkRPfLS634ATzQW7ZMNKGSRyZSdCiknK9YLNc8Et8mUpWIi0cg/@VuJ1lNsJG5ZGgGCurYIyqDVG4TafQr7dxfrLAr4eLU1Jq1@0ZoZNDlm0bqHdO9gZjPs7vDm607RppK5DMKFj@cGDgFe3cqEnoZDiA@iVXnq5LJIM8SnAURzeroB "Python 2 – Try It Online")** Any bonus points for `n,a,s-a`? ### Explanation: * The first line declares a recursive lambda, `g`, which verifies whether `a, b` expanded as a Fibonacci sequence will reach `x`. It also checks that `a <= b`, one of the criteria of the question. (This would allow cases where `a == b`, but in such a case `0, a` would have already been discovered and returned). + The chained inequality `a<=b<x` performs two handy tasks at once: verifying `a <= b`, and that `b < x`. + If `b < x` yields `True`, the function calls itself again with the next two numbers in the Fibonacci sequence: `b, a+b`. This means the function will keep working out new terms until... + If `b < x` yields `False`, then we have reached the point where we need to check if `b==x`. If so, this will return `True`, signifying that the initial pair `a, b` will eventually reach `x`. Otherwise, if `b > x`, the pair is invalid. * The second line declares another recursive lambda, `f`, which finds the solution for a given value `n`. It recursively tries new initial pairs, `a, b`, until `g(n, a, b)` yields `True`. This solution is then returned. + The function recursively counts up initial Fibonacci pairs using two variables, `s` (initially 1) and `a` (initially 0). On each iteration, `a` is incremented, and `a, s-a` is used as the first pair. However, when `a` hits `s`, it is reset back to 0, and `s` is incremented. This means the pairs are counted up in the following pattern: ``` s=1 (0, 1) (1, 0) s=2 (0, 2) (1, 1) (2, 0) s=3 (0, 3) (1, 2), (2, 1), (3, 0) ``` Obviously, this contains some invalid pairs, however these are eliminated instantly when passed to `g` (see first bullet point). + When values `a` and `s` are found such that `g(n, a, s-a) == True`, then this value is returned. As the possible solutions are counted up in order of 'size' (sorted by mean, then min value), the first solution found will always be the smallest, as the challenge requests. [Answer] # [R](https://www.r-project.org/), ~~183 bytes~~ 160 bytes ``` n=scan();e=expand.grid(n:0,n:0);e=e[e[,2]>e[,1],];r=e[mapply(h<-function(n,a,b,r=a+b)switch(sign(n-r)+2,F,T,h(n,b,r)),n,e[,1],e[,2]),];r[which.min(rowSums(r)),] ``` [Try it online!](https://tio.run/##JYzBDoMgEAV/Z4mrQY@19NgfaG@EAyIVkrIa0Nh@PUV7eO8wmUzMmUQymoD1VtjPomlspuhHoAvHshNLK7FTt/KtQtXHQoJelvcX3LV@bWRWPxMQahwwCl0NLO1@NQ6SnwqvI6s6vOMTXZGKwhgS/mtnmR1RuTtvXBM8QZz3xxYSHKLKLec8/wA "R – Try It Online") **Thanks to Giuseppe for golfing off 23 bytes** Code explanation ``` n=scan() #STDIO input e=expand.grid(n:0,n:0) #full outer join of integer vector n to 0 e=e[e[,2]>e[,1],] #filter so b > a r=e[mapply( h<-function(n,a,b,r=a+b)switch(sign(n-r)+2,F,T,h(n,b,r)), #create a named recursive function mid-call #(requires using <- vs = to denote local variable creation #rather than argument assignment n,e[,1],e[,2]),] #map n, a and b to h() which returns a logical #which is used to filter the possibilities r[which.min(rowSums(r)),] #calculate sum for each possibility, #get index of the minimum and return #because each possibility has 2 values, the mean and #sum will sort identically. ``` [Answer] # Mathematica, 117 bytes ``` If[#==1,{0,1},#&@@SortBy[(S=Select)[S[Range[0,s=#]~Tuples~2,Less@@#&],!FreeQ[LinearRecurrence[{1,1},#,s],s]&],Mean]]& ``` [Try it online!](https://tio.run/##HcyxCsIwFEbhV1ECReEObRenQHAQhArauF0yhPBXC22UJB2k2FePRTjjxxltemK0qXc2dxu5yeeOhZQVzSVVXxKFUvoV0vHDOy01Bri0Z82t9Q9wSVEKs9yn94C41NQgRqVEYWh7CsCNm97DhhZuCgHegefqf6Vo1lZ3gfXGFPkaep9Ux/XB5B8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ṫ-Sṭµ¡³e 0rŒcÇÐfSÐṂ ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//4bmrLVPhua3CtcKhwrNlCjByxZJjw4fDkGZTw5DhuYL///8xMDA "Jelly – Try It Online") -1 byte thanks to [the proof](https://codegolf.stackexchange.com/a/147843/41024) by [cardboard\_box](https://codegolf.stackexchange.com/users/6683/cardboard-box). In case it's disproved, you can append `UṂṚ` to the end of the second line for 22 bytes in total. [Answer] ## [GolfScript](https://tio.run/##S8/PSStOLsosKPn/v87KL1qn2lDbKlGnOlrPOjG2Vr9WPzYayK6r1vOzqa3Wc9CuLc/IzEmNsfazBcrGVmsa2sZY1@pUa8RY12nXqgApTeu6OnUF9Zj//43MAQ) - ~~88~~ 77 bytes ``` ~:N[,{1+:a,{[.;a]}/}/][{[.~{.N<}{.@+}while\;N=]}/]{)1=\;},{(\;~+}$(\;);~~' '\ ``` I did not check for multiple solutions, thanks to cardboard\_box! ### Explanation ``` ~:N # Reads input [,{1+:a,{[.;a]}/}/] # Creates an array of pairs [a b] [{[.~{.N<}{.@+}while\;N=]}/] # Compute solutions {)1=\;}, # Pairs that are not solutions are discarded {(\;~+}$ # Sorts by mean (\;);~~' '\ # Formats output ``` [Answer] ## Batch, ~~160~~ 158 bytes ``` @set/aa=b=0 :g @if %a% geq %b% set/ab-=~a,a=0 @set/ac=a,d=b :l @if %c% lss %1 set/ad+=c,c=d-c&goto l @if %c% gtr %1 set/aa+=1,b-=1&goto g @echo %a% %b% ``` ]
[Question] [ ## Background It's late Friday afternoon and you and your friends decide to hit the pub later that evening, but before going to the pub you figure you should have a few beverages. However, things escalate quickly; your friend Shaddock Pamplemousse won the lottery earlier this week and decided to bring crates upon crates with different beverages. The security at the pub is very strict, and if you overconsume before trying to enter the premises you are not allowed inside. You are all programmers though - so you figure things will turn out great anyway. ## Challenge You need to program an alcohol meter which outputs truthy/falsy if you're above/below the reasonable pub limit. Before you go down to the pub you enter the amount and beverage type you've consumed during the evening to `stdin` which your measurement program reads. If it outputs truthy, you are above the pub limit and stay at home. If it outputs falsy, you're good to go. ## Input One integer greater than `0` which represents your body weight in kilograms followed by a newline. This input is followed by a series of one digit amounts and beverages on the following form: ``` <amount><amount type>o<beverage type> ``` For one bottle of beer this will look like: ``` 1Bob ``` Each input is separated by a space. **Input specification** Each beverage has a unit which correspond to the impact caused by it. If you consume more units than your weight divided by two the pub is not an option anymore. *(This may or may not reflect reality)* The following are valid beverages and the corresponding alcoholic units of the beverage: * Beer: `b`, `1` unit * Energy drink: `e`, `0` units * Hot sauce: `h`, `2` units (strong stuff) * Juice (made of organic fruits etc): `j`, `0` units * Rum: `r`, `6` units * Tequila: `t`, `7` units * Vodka: `v`, `6` units * Wine: `w`, `3` units There are different amount types: * Bottle: `B` * Crate: `C` * Glass: `G` * Keg: `K` * Sip: `S` Each amount type has a multiplier which multiplies the alcoholic units of the beverage contained in it: * Bottle: `3` * Crate: `25` * Glass: `2` * Keg: `50` * Sip: `0.2` ## Output Your program shall output [truthy/falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey/2194#2194) to `stdout` if the amount consumed is above/below your body weight divided by 2. If the amount consumed is equal to your weight divided by 2, you should output falsy. ## Samples of possible input and output **Input** ``` 70 1Bob 3Soj ``` **Output** ``` False ``` **Input** ``` 2 1Cov ``` **Output** ``` 1 ``` **Input** ``` 50 1Cob ``` **Output** ``` 0 ``` **Input** ``` 100 4Gow 1Koe 1Bov 1Gow 2Sot ``` **Output** ``` True ``` The shortest program in bytes wins! [Answer] # Python 3, 131 Now we're golfing with snakes! Saved 18 bytes thanks to shebang. Saved 4 more bytes thanks to DSM. Saved a lot of bytes thanks to tzaman. Many thanks to tzaman for his brilliant trick of abusing `.find()` returning `-1` if it doesn't find a value. Currently this assumes this drink format is exactly the way it's stated in the challenge, eg, only 1 digit worth of each drink. ``` w=input() print(sum([6,50,4,100,.4]['BCGKS'.find(b)]*int(a)*int('1267730'['bhrtvw'.find(v)])for a,b,_,v in input().split())>int(w)) ``` [Answer] # CJam, 53 bytes ``` 6:B50:C2*:K4:G.4:S];q"behjrtvwo ""10206763*"er~*]:-U< ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=6%3AB50%3AC2*%3AK4%3AG.4%3AS%5D%3Bq%22behjrtvwo%20%22%2210206763*%22er~*%5D%3A-U%3C&input=100%0A4Gow%201Koe%201Bov%201Gow%202Sot). ### How it works ``` 6:B e# Push 6 and save it in B. 50:C e# Push 50 and save it in C. 2*:K e# Multiply by 2 to push 100 and save it in K. 4:G e# Push 4 and save it in G. .4:S e# Push 0.4 and save it in S. e# e# The letters representing the types will now push its doubled e# (to avoid diving the weight by 2) associated multiplier. ]; e# Clear the stack. q e# Read all input. "behjrtvwo " e# Push the string of beverages, concatenated with "o ". "10206763*" e# Push the string of associated units of alcohol and '*'. er e# Transliterate. This replaces each beverage letter with the e# associated units of alcohol, and each 'o' and ' ' with '*'. e# e# For example, the input e# 70 e# 1Bob 3Soj e# is transformed into e# 70 e# 1B*1*3S*0 e# ~ e# Evaluate the resulting string. e# e# For the example this does the following: e# + Push 70. e# + Push 1, push 6, multiply, push 1, multiply. e# + Push 3, push 0.4, multiply, push 0. e# * e# Multiply the last two (for the lack of a trailing space). ] e# Collect all results in an array. :- e# Reduce by subtraction; subtract all other elements from the e# first element (body weight). U< e# Compare the result with 0. ``` [Answer] ## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), 59 bytes ``` 126763355*25l*2l$:"SKGCBwvtrhb"m(0pI)n(no0qoxo0q**2*-$I)`N. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/old?code=126763355%2A25l%2A2l%24%3A%22SKGCBwvtrhb%22m%280pI%29n%28no0qoxo0q%2A%2A2%2A-%24I%29%60N%2E&input=100%0A4Gow+1Koe+1Bov+1Gow+2Sot) ### Explanation ``` 126763355*25l*2l$: Pushes the values of the characters "SKGCBwvtrhb" Pushes the characters themselves m Merge; interleaves the first and second halves of the stack ( Open while loop 0p Put character's value in character's place in the codebox I) Close while loop when stack is empty n Read in integer (weight) ( Open while loop n Read in integer, ignoring any non-numeric characters o0q Read in character and get its value from the codebox ox Read in character and dump it o0q Read in character and get its value from the codebox ** Multiply the three numbers together 2*- Multiply by 2 and subtract from weight $I) Close while loop when input is empty ` 1 if less than 0, 0 otherwise N. Output as integer and stop. ``` [Answer] ## CJam, 54 bytes ``` ldlS/{A,s"CbretjvwSBK"+f#A,[25X6T7T6Z.2Z50Y]+f=:*-}/0< ``` Bit fiddly and probably suboptimal, but I think this works okay. [Try it online](http://cjam.aditsu.net/#code=ldlS%2F%7BA%2Cs%22CbretjvwSBK%22%2Bf%23A%2C%5B25X6T7T6Z.2Z50Y%5D%2Bf%3D%3A*-%7D%2F0%3C&input=100%0A4Gow%201Koe%201Bov%201Gow%202Sot). ### Explanation ``` ld Read first line, convert to double lS/ Read second line, split by space {...}/ For each item in the second line... A,s"..."+f# Get index in "0123456789CbretjvwSBK", or -1 if not found A,[...]+f= Index into [0 1 2 3 4 5 6 7 8 9 25 1 6 0 7 0 6 3 0.2 3 50 2] :* Take product - Subtract from weight 0< Check if < 0 ``` Note that the numeric array has 2 at the end, meaning that `Gho`, which are missing from the first string, get mapped to 2. [Answer] # CJam, 77 ``` qN%~S%{:BW="behjrtvw"\#10206773s:~\=[3 25 2 50 .2]"BCGKS"B-3=#=*1mO}%:+\~2/\> ``` [Answer] # VBA, 251 bytes ``` Function k(x) As Boolean:q=Split(x):g="b1e0h2j0r6t7v6w3":h="B03C25G02K50S.2":For i=1 To UBound(q):j=j+Left(q(i),Len(q(i))-3)*Mid(h,InStr(h,Mid(Right(q(i),3),1,1))+1,2)*Mid(g,InStr(g,Mid(Right(q(i),3),3,1))+1,1):Next i:If q(0)/2<j Then k=1 End Function ``` > > Using `:` rather then Newline doesn't make it shorter, But it does look more golfy! > > > Readable Format ``` Function b(x) As Boolean q = Split(x) g = "b1e0h2j0r6t7v6w3" h = "B03C25G02K50S.2" For i = 1 To UBound(q) j = j + Left(q(i), Len(q(i)) - 3) * _ 'Left most digits would be the Quantity Mid(h, InStr(h, Mid(Right(q(i), 3), 1, 1)) + 1, 2) * _ 'Find the Container value in h Mid(g, InStr(g, Mid(Right(q(i), 3), 3, 1)) + 1, 1) 'Find the Drink value in g Next i If q(0) / 2 < j Then b = 1 'Checks if Drunk or not End Function ``` Pretty Sure this can be golfed. my String Manipulation with `Mid(Right())` seems excessively wordy, But running the array though `StrReverse` makes it longer. If we assume you only drink 0-9 of any particular drink at a time we can save a handful of bytes Take input as one string with weight separated by a space as `VBA` dose not support multi line input [Answer] # Ruby, 153 bytes I need to get rid of the gsubs somehow ``` w=gets.to_i;$><<(eval(gets.chars{|c|c[/[0-9]/]!=p ? ($_[c]+='*'):0}.tr('behjrtvwo BG','10206763*+32').gsub('C','25').gsub('K','50').gsub('S','0.2'))>w/2) ``` [Answer] # JavaScript, 131 ~~134~~ ~~139~~ bytes This is a full program and basically an adaption of my [PHP answer](https://codegolf.stackexchange.com/a/63761/41859): ``` for(c=prompt,b=c(a=c(s=i=0));b[i];i+=2)s+=b[i++]*{B:3,C:25,G:2,K:50,S:.2}[b[i++]]*{b:1,h:2,r:6,t:7,v:6,w:3}[b[++i]]||0;alert(s>a/2) ``` It reads two values using `prompt` and `alert`s the result as `[true|false]`. --- **Edits** * *Saved* **5 bytes** by using a logical expression `||0` instead of declaring the beverages with `0` units. Thanks to [user81655](https://codegolf.stackexchange.com/users/46855/user81655). * *Saved* **3 bytes** by storing `prompt` in a variable and shortening the initialization. Thanks to [Stefnotch](https://codegolf.stackexchange.com/users/33160/stefnotch). [Answer] # bash (+ bc + GNU sed), ~~200~~ ~~196~~ 194 bytes ``` read x read y y="$(sed 's/^/((/;s/$/))/;s/ /)+(/g;s/o/*/g;s/b/1/g;s/[ej]/0/g;s/h/2/g;s/[rv]/6/g;s/w/3/g;s/t/7/g;s/B/*3/g;s/C/*25/g;s/G/*2/g;s/K/*50/g;s/S/*0.2/g'<<<"$y")" echo "$y>$x/2"|bc -l ``` [Answer] ## Javascript, 159 bytes ``` function b(t){return a={B:3,C:25,G:2,K:50,S:.2,b:1,h:2,w:3,r:6,v:6,t:7},t.split(/\W/).reduceRight(function(t,n,r){return r?n[0]*a[n[1]]*a[n[3]]+t||t:t>n/2},0)} ``` Since Javascript requires a library to access STDIN, this code is just a function that accepts the entirety of the input, i.e. `b("100\n4Gow 1Koe 1Bov 1Gow 2Sot")` [Answer] ## Python 3, 157 bytes ``` n,l,d,u=int(input()),input(),"behjrtvwBCGKS",[1,0,2,0,6,7,6,3,3,25,2,50,.2] print(sum(map(lambda x:int(x[0])*u[d.find(x[1])]*u[d.find(x[3])],l.split()))>n/2) ``` [Answer] # PHP, 163 ~~169~~ bytes ``` for($a=fgets(STDIN),$b=fgets(STDIN),$v=[b=>1,h=>2,r=>6,t=>7,v=>6,w=>3,B=>3,C=>25,G=>2,K=>50,S=>.2];$b[$i];$i+=2)$s+=$b[$i++]*$v[$b[$i++]]*$v[$b[++$i]];echo$s>$a/2; ``` Outputs `1` or nothing, works for all test cases. --- I still wonder what this *hot sauce* is, having *2 units*. --- **Edits** * *Saved* **6 bytes** by merging the two arrays for drinks and multiplier and by removing `0` from `0.2`. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 165 bytes (SBCS) ``` ¿®w?(: =[_]")0®u(!4/|\0-&:B=[&3*&|:C=[&55**&|:G=[&2*&|:K=[&\2*&|&15/*&]]]]__:b=[&1*&|:e=[&0&|:h=[&2*&|:j=[&0&|:r=[&6*&|:t=[&7*&|:v=[&6*&|&3*&]]]]]]]_©u&+®u)©w2/:©u<. ``` [Try it online!](https://tio.run/##y05N////0P5D68rtNawUbKPjY5U0DQ6tK9VQNNGviTHQVbNyso1WM9ZSq7FyBjJMTbVATHcg0wjE8AYyYkAsNUNTfS21WCCIj7dKAooagqRTgQwDIJ0BU58FFSgC0mYggRIgwxzEKIOKgOyKhYD4QytL1bSBjtE8tLLcSN8KyLXR@//f0MCAy8Q9v1zB0Ds/VcHQKb9MwRDENQrOLwEA "Keg – Try It Online") I feel as if though a Keg answer has never been more appropriate! This could probably be golfed, but I don't think it can. ## Explained ``` ¿®w #Take the weight and store it in a variable ?(: =[_]") #Take the second line and remove spaces 0®u #Store the units in a variable (!4/| #For every part in the input \0-& #Store the amount of drink in the register :B=[&3*&|:C=[&55**&|:G=[&2*&|:K=[&\2*&|&15/*&]]]]__ #Determine the beverage multiplier :b=[&1*&|:e=[&0&|:h=[&2*&|:j=[&0&|:r=[&6*&|:t=[&7*&|:v=[&6*&|&3*&]]]]]]]_ #Determine the drink ©u&+®u) #Add the amount to units ©w2/:©u<. #Check the condition and print ``` ]
[Question] [ The [Caesar Cypher](http://en.wikipedia.org/wiki/Caesar_cypher) is a very simple substitution cypher where each letter is shifted by a fixed offset (looping around Z to A). Similarly, we can also a Caesar cypher for the set of printable ASCII characters. These are the 95 characters from code points 0x20 to 0x7E. For a given offset `d`, we map the code point `C` to ``` (C - 32 + d) % 95 + 32 ``` which shifts all characters by a `d` and loops around from `~` to space. Characters outside this range (control characters like newlines, tabs, and characters outside the ASCII range) are unaffected. You're to write two programs or functions (potentially in different languages), which take an offset `d` and a string. The first program should return or print the Caesar cypher of the input. The second program should return or print the *inverse* Caesar cypher (i.e. using offset `-d`). You may take input via STDIN, command-line argument or function argument. To make things more interesting, the second program must be a Caesar cypher of the first program. That is, if you pass the source code of the first program to itself, for some non-zero offset `d`, the output has to be the second program. Both programs, as well as the input strings, must contain only printable ASCII characters, newlines and tabs. Neither program may contain any comments or read its own source code, file name or process ID directly or indirectly. This is code golf, so the shortest answer (in bytes) wins. Since both programs must have the same size, you only need to count it once. [Answer] # Cjam, ~~40 38~~ 37 bytes Forward Cypher: ``` q~'~),32>_@m<er "o|%|'*10<]>k<cpZ"_- ``` Inverse Cypher: ``` "s!)!+.54@aBo>gt"$q~'~),32>_@m>er\$a/ ``` and the second program is the cypher of first one with difference of `2` --- **How it works** I came up with this answer on pure luck while testing things out. First, the Cypher parts: ``` q~'~),32>_@m<er q~ "Take the input and evaluate it"; `~) "Get the next character after the printable ASCII range"; ,32> "Get all printable ASCII characters": _@ "Copy the printable ASCII string and bring the cypher difference" "on top of stack"; m< "Forward rotate the copy of printable ASCII string by difference"; "In case of inverse Cypher, this is m> to reverse rotate the string"; er "Transliterate to complete the forward/inverse Cypher"; ``` Now comes the explanation of the tricky part. Key transformations are ``` <space> -> " // Empty space to string conversion Z -> \ // Character Z in an useless string to swap operation _ -> a // Copy operation to wrapping in an array - -> / // Set subtraction to string splitting ``` So the first program is ``` q~'~),32>_@m<er "o|%|'*10<]>k<cpZ"_- q~'~),32>_@m<er "no-op space, Forward cypher, no-op space"; "o|%|'*10<]>k<cpZ" "Useless String (Actually not)"; _ "Copy it and ..." - "remove all alphabets of copy from original"; ``` And the second program is ``` "s!)!+.54@aBo>gt"$q~'~),32>_@m>er\$a/ "s!)!+.54@aBo>gt" "Cypher of first part of first program" "with difference of 2"; $q~'~),32>_@m>er\$a/ "Cypher of the useless string of first program"; "with difference 2"; $ "Sort the first program's main part's cypher"; q~'~),32>_@m>er "Program to reverse cypher"; \$ "Swap the cypher to the top of stack and sort it"; a "Wrap it in array"; / "Split the output string on an array, which"; "always returns the output in an array as there"; "are no occurrences of an array in a string"; ``` --- Input is like `"<escaped string to be cyphered>" <difference>` For example: ``` "abcd" 4 ``` and output of the first program is ``` efgh ``` and of the second program is ``` ]^_` ``` [Try it online here](http://cjam.aditsu.net/) [Answer] # Python 2, 147 Clearly I didn't think too hard about this one, as it would be futile in Python. There are simply two seperate programs, with the unused one encased in a string. The offset between the two programs is 39. ## Forward Defines the function Z accepting a Unicode string and an offset. ``` Z=lambda s,d:s.translate({i+32:(i+d)%95+32for i in range(95)})or u''and Z "uE:F;=:XLd=rLfMK:GLE:M>`TBckjr`Be=a]qmckj?HKXBXBGXK:G@>`qmaVaHKXN__:G=X" ``` ## Inverse Defines the function I accepting a Unicode string and an offset. ``` "d4)5*,)G;S,a;U<:)6;4)<-OC1RZYaO1R,PL`\RZY.7:G1G16G:)6/-O`\PEP7:G=NN)6,G" I=lambda s,d:s.translate({i+32:(i-d)%95+32for i in range(95)})or u''and I ``` [Answer] # Python 3 - 248 bytes My goal was to do this as a Python one-liner. Goal success, but now I can't be bothered golfing. Encrypt: ``` r=q="".__doc__[2];eval("p"+q+"int(''.join([c,ch"+q+"((o"+q+"d(c)-32+d)%95+32)][31<o"+q+"d(c)<127]fo"+q+" d in[int(input())]fo"+q+" c in input()))")or'\^UZ`smmyV[UZsGOwOT^ss[^PsOtx~}xPtp%!v~}tIG~|([^PsOt(|}$IR[^kPkUZGUZ`sUZ\a`sttIR[^kOkUZkUZ\a`sttt' ``` Decrypt: ``` 'Q&Q66Bssx$wssoFqOy+u!<6%6?&?6}#)<;;B~$}#<ow@w|6?&?6<<$6?&?6x<w=AGF?x=9MI?GF=qoGEP$6?&?6x<w=PEFKqz$6?&?64x4}#o}#)<}#%*)<==qz$6?&?64w4}#4}#%*)<===6=$';print("".join([c,chr((ord(c)-32-d)%95+32)][31<ord(c)<127]for d in[int(input())]for c in input())); ``` *Edit: Fixed to not affect chars outside the printable ASCII range* Offset from encrypt to decrypt is 20. Use by inputting the offset first, then the string, e.g. ``` 5 hello ``` ## Explanation The following transformations are the key: ``` r -> ' ' -> ; ``` The first allows the use of `or`, while the second ignores a string by semicolons. Note that `"".__doc__[2]` returns the string `r` (taken from `str`). This is necessary to prevent the single quoted string in the decryption program from having stray quotes in the middle. [Answer] # Ruby, ~~131~~ 125 bytes Here is my own submission (which I had written earlier as a proof of concept, but I managed to violate my own rules somehow). I'm not reusing any code between the two submissions (I want you guys to beat this, after all), but instead it consists of two lines, one of which is turned into a string with gibberish. **Forward cypher:** ``` Y=->d,s{s.chars{|c|x=c.ord;$><<(x<32?x:(x-32+d)%95+32).chr}};Y "tdu<cKSKe;@9JKST;TPt;eGJ<r[uss_PsjivPq_Pdjid<`\plbji`e;@JUUr" ``` **Inverse cypher:** ``` "eUf-T<D<V,1*;<DE,EAe,V8;-cLfddPAd[ZgAbPAU[ZS-QMa]S[ZQV,1;FFc" J=->d,s{s.chars{|c|x=c.ord;$><<(x<32?x:(x-32-d)%95+32).chr}};J ``` Both snippets define a function (called `Y` in the first one, and `J` in the second one), which takes an integer and a string and prints the transformed string to STDOUT. The offset between the two pieces of code is `40`. [Answer] # [oOo CODE](http://esolangs.org/wiki/OOo_CODE), 750 744 bytes, all code used in both programs Too long but it's probably the right tool doing that... Encrypt: ``` CcCcccccccccCcYcccCCCccCcCcCccccccCcCcccccCcCcccCcCccCccCcCCccccCcCccccCCcCccccCCccCccCcCCcccCCCcCccccCcCCcCCcCCcCcCcCccccCCccCccCccCccCccCccCccCccccccCCCcCccCccCCcCcCcccCCcCcccCcCCcCCcCcCCccCCcCCcCCcCCcCCcCCcCCcCCcCCcCCcCcccccccCccccCccccCCccccCCcCccCCcccCccccccccccCcCccCccCccCccCcCCccCCcccCcCcCccCCcccCCCcCcccccccccccccCCccCccCcCcCcccCCccccccccccCcCccccccCcCccccCCcCccCccCCcCccccccccccCCccCcCcCcccccCcCccCcCCCcCccCccCCcCccCccCccCcCcccccCcCcccCCCcCcCccccCcCccCCcCCcCCcCcCCcccCcCCcCCcCCcCCcCCcCCcCCcCCcCCcCcCcccCccCCcccccCcCcccCcccccCcccCcccCccCccCCcCcccccccccccccCCCcccCcCcCcccCcccCCCcCccCccCccCcCCccCccCcCCCcCccccCcCccccccccCcCccCccCcCCccccccCccccccccCcccCCccCccCccCCcCCcCCcCCcCcCcCcccccCcCCcCCcCCcCCcCCcCCcCCcCccCcCCcccCCccCcCcccCCcccCCCcCC ``` Decrypt: ``` SsSsssssssssSsisssSSSssSsSsSssssssSsSsssssSsSsssSsSssSssSsSSssssSsSssssSSsSssssSSssSssSsSSsssSSSsSssssSsSSsSSsSSsSsSsSssssSSssSssSssSssSssSssSssSssssssSSSsSssSssSSsSsSsssSSsSsssSsSSsSSsSsSSssSSsSSsSSsSSsSSsSSsSSsSSsSSsSSsSsssssssSssssSssssSSssssSSsSssSSsssSssssssssssSsSssSssSssSssSsSSssSSsssSsSsSssSSsssSSSsSsssssssssssssSSssSssSsSsSsssSSssssssssssSsSssssssSsSssssSSsSssSssSSsSssssssssssSSssSsSsSsssssSsSssSsSSSsSssSssSSsSssSssSssSsSsssssSsSsssSSSsSsSssssSsSssSSsSSsSSsSsSSsssSsSSsSSsSSsSSsSSsSSsSSsSSsSSsSsSsssSssSSsssssSsSsssSsssssSsssSsssSssSssSSsSsssssssssssssSSSsssSsSsSsssSsssSSSsSssSssSssSsSSssSssSsSSSsSssssSsSssssssssSsSssSssSsSSssssssSssssssssSsssSSssSssSssSSsSSsSSsSSsSsSsSsssssSsSSsSSsSSsSSsSSsSSsSSsSssSsSSsssSSssSsSsssSSsssSSSsSS ``` Brainfuck translations: ``` +>>>+>,<[->[->+>+<<]>[-<+>]<<]>,[>++++[-<-------->]+<<+[<+>+++]<++++++++++>>[>-<-<+<-[>>>+<<<<]<-[+<-]+>>>>]<<[-]>>>[->[-<+<<+>>>]<[->+<]+<<+<<<[>[-]+[>+<+++]>++++++++++[<<->+>->-[<<<+>>>>]-[+>-]+<<<]<<]+>[->>+<<]>>->>-]<<<++++[->++++++++<]>.[-]>,] +>>>->,<[->[->+>+<<]>[-<+>]<<]>,[>++++[-<-------->]+<<+[<+>+++]<++++++++++>>[>-<-<+<-[>>>+<<<<]<-[+<-]+>>>>]<<[-]>>>[->[-<+<<+>>>]<[->+<]+<<+<<<[>[-]+[>+<+++]>++++++++++[<<->+>->-[<<<+>>>>]-[+>-]+<<<]<<]+>[->>+<<]>>->>-]<<<++++[->++++++++<]>.[-]>,] ``` oOo CODE is a Brainfuck variant where only the case of letters matters. It take the first byte and use its character code as `d` (so a newline means d=10). The rest of input is the string. EOF is 0. [Answer] # GolfScript, 95 64 bytes, all code used in both programs Encrypt: ``` 0 0z{ 1)'[}??)9t:z21,--/; [84;%zt*84*84$|)21*|$Z!!\~'---|}`{)}%~ ``` Decrypt: ``` 1!1{|!2*(\~@@*:u;{32-..0<!\95<&{u+95+95%}*32+}%[""] (...}~a|*~& ``` Input format: ``` 1 "0 0z{ 1)'[}??)9t:z21,--/; [84;%zt*84*84$|)21*|$Z!!\~'---|}`{)}%~" ``` ### Explanation Decrypt: ``` 1!1 # Push 0 1. { # Define a block and evaluate it. | # Or. !2*( # Get 1 for encryption, or -1 for decryption. \~ # Evaluate the input string. @@*:u; # u = d for encryption, or -d for decryption. { # For each character: 32- # Subtract 32. ..0<!\95<& # Test if it is in the printable range. {u+95+95%}* # If so, add u (mod 95). 32+ # Add 32 back. }% [""] (... # Push an empty array and 4 empty strings. }~ a # No-op. |*~ # Evaluate ""*(""|"") which does nothing. & # Calculate []&"" which is empty. ``` Encrypt: ``` 0 0 # Push 0 0. z # No-op. { # Define a block and get its string representation. ... # See decryption code. | # This will be decoded into a }. The string will be truncated here when evaluated. }` # Only the closing } will be truncated, but it is still used as the end of the block. {)}% # Increment each character. Note that the braces before and after the block will also be incremented. ~ # Evaluate the string. ``` [Answer] # Javascript (ES7 Draft) - 167 165 bytes Borrowing from @feersum 's use of strings and @MartinButtner 's use of semicolon ;) **Encrypt:** ``` J=(s,d)=>s.replace(/[ -~]/g,x=>String.fromCharCode((x.charCodeAt()-32+d)%95+32));J "eP<T-Qef<V;.95*,.PW$HUG&W0TAef{=;270V/;86k1*;k8-.PPAV,1*;k8-.i=PQS^[U-QMa]S[ZQQc" ``` **Decrypt:** ``` "t_Kc<`tuKeJ=HD9;=_f3WdV5f?cPtu+LJAF?e>JGEz@9JzG<=__Pe;@9JzG<=xL_`djib<`\plbji``r" Y=(s,d)=>s.replace(/[ -~]/g,x=>String.fromCharCode((x.charCodeAt()+63-d)%95+32));Y ``` **Offset to use:** 55 [Answer] # [><> (Fish)](http://esolangs.org/wiki/Fish), 467 bytes Encrypt: ``` ffii{{~~__:0a('0'*!.0a('0'*22(!'(~$~_:}-}$-a*}+{{if~~:i:0({}?;__:{}84{}*__({}?\__:{} _{}70{}g_{})_{}?\4__{}8*-_{}+{}80{}g_%4_{}8*{}+\\sl||||||||||||||||||||||||||||9||||||||||||||9||||||||||||||||||||||||||||||||||||||||||||||||||||9 > > >!;7f7-_{}!%_{}!<872-d_{}!&_{}!<[755(7(%~~_{}!<[55(7(_{}!*!*23a(_{}!'_{}!"55(7((~~_{}~~~o__'4'0.{{{o, ``` Decrypt: ``` iill~~""bb=3d+*3*-$13d+*3*-55+$*+"'"b=!0!'0d-!.~~li""=l=3+~!B>bb=~!;7~!-bb+~!B_bb=~!#b~!:3~!jb~!,b~!B_7bb~!;-0b~!.~!;3~!jb(7b~!;-~!.__vo < < < ##############################################################################A######################A##############################A$>:i:0b~!$(b~!$?;:50gb~!$)b~!$?^:88+:+(""b~!$?^88+:+b~!$-$-56d+b~!$*b~!$%88+:++""b~!"""rbb*7*31~~~r/ ``` The two programs are offset by 3, and they take input of the form: ``` <2-digit offset> <text> ``` The offset *must* be 2 digits, so an offset of 5 needs to be entered as `05`. This is a long submission, but **nearly all non-filler chars are used by both programs**. There's a lot of whitespace that can definitely be golfed out, but I thought the program would be more interesting this way. [This image](https://i.stack.imgur.com/sL56J.png) highlights the chars used by both programs. ## Explanation The main construct that makes this possible is `_{} -> b~!`, which allows arbitrary skipping of chars in the decryption program. How? ``` Encrypt: _ : Mirror, but is a no-op if the program flow is horizontal { : Shift stack left } : Shift stack right Decrypt: b : Push 11 to stack ~ : Pop top of stack ! : Skip the next instruction ``` All in all, the encryption program does nothing, but the decryption program skips the next instruction. This can then be extended to `_{}! -> b~!$`, which allows arbitrary skipping of chars in the *encryption* program instead. Aside from this, most of the rest of the program is pushing numbers, performing operations on those numbers then finding ways to pop them. For example, one useful construct is `~~ -> ""`, which pops two values for the encryption program, but pushes nothing in the decryption program. --- # ><>, 149 bytes Here's the less interesting version, which uses the fact that instructions not passed through are effectively comments in 2D languages. Encrypt: ``` i68*:@-a*i@@-+i~v 4:v?)g31:;?(0:i:/8 (?v48*-+03g%48*+\* _~\of0. .1+1fo/ j*+:zq<6B99A6=qz6g 53Ji?C58/8;?r0?C5: C?EiJ4r?<EFJ3;EtEg :tAC5EK8l5tKK86t*i ``` Decrypt: ``` ^+-~/5"V~^55" ^sk )/k4}\(&/04|%/^/$- |4k)-~" %(\y)-~ Q~ TsQd[%#ttt#& &[d$ _~ /of1+7..6+2fo+\ *(?^48*-$-04g%48*/ 84:^?)g41:;?(0:i:\ /i68*:@-a*i@@-+i~^ ``` The two programs are offset by 84, and take input the same way as above. The first instruction decides which half of the program to execute, with `i` (input) maintaining program flow rightward in the encryption program, and `^` redirecting program flow upward (looping around and coming back from the bottom) in the decryption program. ## Explanation For the relevant half of the encryption program (decryption program is similar): ``` i read first input digit as char 68*:@-a* subtract 48 (ASCII "0") and multiply by 10, keeping another 48 on the stack i read second input digit as char @@-+ subtract 48 and add to 10*(first digit), giving the offset i~ read in space and discard it --- LOOP --- : copy the offset i: read input char :0)?; check if less than 0 (i.e. EOF) and terminate if so :13g)?v check if greater than ~ in cell (1,3) and drop down if so 48*(?v check if less than 32 and drop down if so 48*-+03g%48*+ calculate Caesar shift of the char, fetching 95 from (0,3) of1+1. repeat loop of0. repeat loop ``` --- ## Coding tool *This isn't related to the rest of the post above, but I thought I'd post this because I need to use it :P* ``` for(var i=0;i<95;++i){var option=document.createElement("option");option.text=i;document.getElementById("offset").add(option)};function update(m){if(m==1)var code=document.getElementById("in").value;else var code=document.getElementById("out").value;var offset=parseInt(document.getElementById("offset").value);var output="";for(var i=0;i<code.length;i++){var n=code[i].charCodeAt(0);if(n<32||n>127)output+=code[i];else{var c=(n-32+offset*m)%95;output+=String.fromCharCode(c<0?c+95+32:c+32)}}if(m==1)document.getElementById("out").value=output;else document.getElementById("in").value=output}; ``` ``` <html><body><textarea id="in" onkeyup="update(1)" rows=5 style="width:100%"></textarea><textarea id="out" rows=5 style="width:100%" onkeyup="update(-1)"></textarea><select id="offset" onchange="update(1)"></select></body></html> ``` [Answer] # Perl - 131 It takes input from command line args. ``` We;{for(split//,$ARGV[1]){print chr(((ord$_)-32+$ARGV[0])%95+32)}};q!LUXmYVROZttqi'8-<AvCnaVXOTZeINXmmmUXJiEnrxwri'8-<AuCnj~zpxwnc! ``` Shifting it by 26 gives the other one: ``` q U6!*-B.+'$/IIF>[lapuKwC6+-$)/:}#-BBB*-~>yCGMLE>[lapuJwC?SOEMLC88U,;for(split//,$ARGV[1]){print chr(((ord$_)-32-$ARGV[0])%95+32)}; ``` ]
[Question] [ Given a non negative integer number \$n\$ output how many steps to reach zero using radicals, divisions or subtractions. # The algorithm * Get digits count ( \$d\$ ) of \$n\$. * Try the following operations in order: $$\sqrt[d]{n}$$ $$n/d$$ $$n-d$$ * Take the first integer result not equal to \$n\$. Floating point errors must be avoided ! * Repeat the process with the value obtained until you reach 0. # Example 1500 -> 8 ``` 1500 -> 4 digits , ( / ) => 375 // step 1 375 -> 3 digits , ( / ) => 125 // step 2 125 -> 3 digits , ( √ ) => 5 // step 3 5 -> 1 digits , ( - ) => 4 // step 4 4 -> 1 digits , ( - ) => 3 // step 5 3 -> 1 digits , ( - ) => 2 // step 6 2 -> 1 digits , ( - ) => 1 // step 7 1 -> 1 digits , ( - ) => 0 // step 8 ``` **Input:** a non negative integer number. You don't have to handle inputs not supported by your language (obviously, abusing this is a [standard loophole](https://codegolf.meta.stackexchange.com/a/8245/66833)) **Output:** the number of steps to reach 0 # Test cases ``` n -> steps 0 -> 0 1 -> 1 2 -> 2 4 -> 4 10 -> 6 12 -> 7 16 -> 5 64 -> 9 100 -> 19 128 -> 7 1000 -> 70 1296 -> 7 1500 -> 8 5184 -> 8 10000 -> 133 21550 -> 1000 26720 -> 100 1018080 -> 16 387420489 -> 10 ``` # Rules * Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT, return it as a function result or error message/s. * Either a full program or a function are acceptable. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * Answers must not fail due to [floating point errors](https://codegolf.meta.stackexchange.com/q/20528/84844). * 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. --- Sandbox: <https://codegolf.meta.stackexchange.com/a/20518/84844> [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 19 16 bytes *-3 thanks to @Unrelated String* ``` Ḋ|⟨ℕ{√₎|/|-}l⟩↰< ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3w/@GOrppH81c8apla/ahj1qOmvhr9Gt3anEfzVwLV2fz/H22go2Coo2Cko2ACZIA4QKahmY6CGZgPFrAAs8BMS6CMoSmIbWpoAVEB4hgZmpqCKDNzI5AyA0MLAwsgw9jC3MTIwMTCMhYA "Brachylog – Try It Online") A recursive function. If `n ≥ 10`, the three operations are tried. For `n < 10` we need `n` steps to `0`. With this we don't have to check that `step(n) ≠ n`, as it only occurs when there is one digit. ``` Ḋ|⟨ℕ{√₎|/|-}l⟩↰< Ḋ if n is in 0…9, return n | otherwise ⟨f h g⟩ [f(n), g(n)] h ℕ l [n, digits] and n is a natural number {√₎|/|-} try (root, divide, subtract) one after the other (results that are not natural numbers will get filtered in the next step with ℕ) ↰ recurse < get a number that is strictly larger, thus +1 ``` [Answer] # [R](https://www.r-project.org/), ~~77~~ ~~74~~ 73 bytes -3 bytes thanks to Giuseppe and -1 byte thanks to MarcMush. ``` f=function(n,d=nchar(n),k=1:n)`if`(d<2,n,1+f(match(n,c(k^d,k*d,k+d))%%n)) ``` [Try it online!](https://tio.run/##JY1hasMwDEb/5xQioyC1Glhukrpj6UlKaXBqatKpkHjnz@xMIPSe9IHmdQ19@FWf4ltReezVP4cZlXjq5UvpHsMdx2/LynII@DMk/8w5j9Nt5Gmf@zAS7XZKtAYUk4uq6gOG1wvSY0ngh@WxVAo9eDQMwmAZmgxFMkrH0G2@LdxGG57zRdrCrbj/RBErbVtGd7IlZsQZl@HoTo01jTtTFd4zRogKSvl9wshQf15qhoCRuL5qTesf "R – Try It Online") Recursive function; avoids floating point issues. The vector `k` contains all integers from `1` to `n`. Concatenate `k^d`, `k*d` and `k+d` (yielding a vector of length `3n`) and find the position `p` of the first occurrence of `n`. Then \$f(n)=1+f(p \mod n)\$. The recursion is initialized by noting that \$f(n)=n\$ for all 1-digit integers (hence the conditioning on `d<2`). Works for all the test cases (although `21550` could require you to increase the stack limit on some machines). [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~40~~ ~~36~~ 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) -6 thanks to ovs. Anonymous tacit prefix function. Requires zero-based indexing (`⎕IO←0`). ``` 0∘{×⍵:(1+⍺)∇⊃⍵(…⍤⊣∩√⍨,÷,-)≢⍕⍵⋄⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3@BRx4zqw9Mf9W610jDUftS7S/NRR/ujrmaggMajhmWPepc86lr8qGPlo45Zj3pX6BzerqOr@ahz0aPeqUAVj7pbgDpq/6c9apvwqLcPrG3No94th9YbP2qb@KhvanCQM5AM8fAM/p@mYMCVpmAIxEZAbAJigwVAPEMzIGEGEYMIWkDYEI4lSNrQFMwzNbSAqgNzjQxNTcG0mbkRWLGBoYWBhQHXo965CmkKxhbmJkYGJhaWCiB@UWphaWZRarFCbn5RqkJuKpCqVCjJSMxTCPH0V0jMyclPTixJLQYA "APL (Dyalog Extended) – Try It Online") `0∘{`…`}` "dfn" bound with 0 as left argument (`⍺`, initial step count ― right argument, \$n\$ is `⍵`):  `×⍵:` if \$n>0\$ (lit. "if \$\text{sgn}(n)\$")  `⍕⍵` stringify \$n\$  `≢` tally the number of characters (digits)  `⍵(`…`)` apply the following tacit function to that, with \$n\$ as left argument:   `√⍨` \$\root d\of n\$   `,` followed by   `÷` \$\frac nd\$   `,` followed by   `-` \$n-d\$   `∩` intersection of that and  `⍳⍤⊣` \$\{1,2,3,…,n-1\}\$ `⊃` the first element  `(`…`)∇` recurse on that, with the following as new left argument:   `1+⍺` one plus the current step count --- If `d←≢⍕⍵` we have the expression `⍵(⍳⍤⊣∩√⍨,÷,-)d` which could be written in traditional mathematical notation as: $$\{1,2,3,…,n-1\}∩\Big\{\root d\of n,\frac nd,n-d\Big\}≡\Big\{\root d\of n,\frac nd,n-d\Big\}\setminus\{n\}$$ [Answer] # JavaScript (ES7), ~~73~~ 68 bytes ``` f=n=>(d=(n+'').length)<2?n:1+f((k=n**(1/d)+.5|0)**d-n?n%d?n-d:n/d:k) ``` [Try it online!](https://tio.run/##fdHNboMwDAfw@56Cy9QEBDghCQGN8SxVA/1CpmqrnvbubJXoVBuJXH9/20l82j62t931eLmnOIZumvoGm28RGoHJZiOzocP9/SC/dIu1Snohzg3GsVB5kElmf0DGcUixxc/QYhpqzEN9ltNuxNs4dNkw7kUvIJqPlFGeR/BBWVFWjDVlzdhQNrw5EHacNeGSsyNsGTtDuFrMBvKwhWu/Ohzm@pkX/6Yrt1ZuSblnbJU3K/wcDm93Lwq@FmXte@AvzhOu1DSxmKE8ePgP8OUUvjQajK9eDaZf "JavaScript (Node.js) – Try It Online") Or [60 bytes](https://tio.run/##Zc/NDoIwEATgu0/RC2EXAv0JYiDWPguhgArZGiG@fr142TrXL5nJPIfPsI/vx@uoKPgpxtmSvYG3QGWeY71NtBx3vBpHvS5ngNVSUYCWHjHTjjLvqPI9Sd@vGMdAe9imegsLzKDEL4hCSqFOnDVnnbDhbBJuODdpuWLcpmwYX1JuGZ8TbhvG3d@2Yse6@AU) if floating point errors are acceptable. ### Commented ``` f = n => // f is a recursive function taking the input n (d = (n + '').length) // d is the number of digits in n < 2 ? // if there's only one digit: n // stop the recursion and return n // (because only n - 1 is valid at this point) : // else: 1 + // increment the final result f( // and do a recursive call: ( // k = n ** (1 / d) // define k as the d-th root of n + .5 | 0 // rounded to the closest integer ) // ** d - n ? // if k ** d is not equal to n: n % d ? // if d is not a divisor of n: n - d // use n - d : // else: n / d // use n / d : // else: k // use k ) // end of recursive call ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~112~~ \$\cdots\$ ~~97~~ 96 bytes Saved ~~7~~ a whopping 15 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved a byte thanks to [Danis](https://codegolf.stackexchange.com/users/99104/danis)!!! ``` f=lambda n:n and-~f([t:=round(n**(1/(d:=len(str(n))))),n//d,t,n-d][(t**d!=n)+2*(n%d>0)|3*(d<2)]) ``` [Try it online!](https://tio.run/##NZBNbsMgEIX3PsV0URkc0gD@jVXnImkWqcGK1QRbQBZRml7d9eBkJMR7j0@jYcabPw0mrUY7TV1zPl6@1RFMbeBo1PqvI3tfN3a4GkVMkhCxIapuztoQ5y0xFIuZzUYxz8xaHfbEJ4l6awxdyYSYd7Xj9DdNiPqU9ECn/jIO1oO7uWg@H057q9urdf1gzv2l90TkfC4aee28gwYI4Qw4ZUAEA4G3ZCDxzhhkIZ@BIoj5pQyiYJCjKGZmuzAzJBYpqxfGMS2X5nJbvOIc4wplLqrsKRHGHmkaZhB5jg5HRVuUcrELKipeoQ9jpVWZSZ5VWwQojdqTbn@0xb/FX1dZZm0MQYg0plE3WPBMQ28grKCOYC7cREc8XfFgR9sbT7r47h@w3sHdPeD@bLvXTeMOj5hO/w "Python 3.8 (pre-release) – Try It Online") [Answer] # [Julia 0.7](http://julialang.org/), ~~68~~ ~~62~~ 57 bytes inspired by [Robin's answer in R](https://codegolf.stackexchange.com/a/215946/98541) ``` !n=n>0&&1+!filter(r->n∈((d=ndigits(n))r,r+d,r^d),0:n)[] ``` [Try it online!](https://tio.run/##bY9NasMwEIX3OsXElCARFST5Ty7YF0lTKJUcZIwaZBV6hOwLXfV0uYirnxi6qEDMe0@fhpnpYzav7brubG8Htt/zw240s9cOu8fB3q5XjFVvlTkbv2BLiKPuoKh7UYSyJ0uOp9XrxS/QwxEx6AdgFPFYOUUiVkFRFWsV8gQ0QaSXNogmipqiJjFdZBLEoxRyw1hO29hcdM0W1zmWFNVcVncZ4dyjLMMMvK6zC2mwTSs2G1Eumcw@jFXKthKskl0GKDohNL47wIZOBIyFtCqCcEYTNt6ZpM2YbA9TsvFcnLF@tri4/XxBQcHEjqMhCdDzov8jv/@QFIpnj/XnRb95reBhIsX9s1Uo3PUX "Julia 0.7 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` *,×;+ ç€DL$œi⁸ḢµƬTL ``` [Try it online!](https://tio.run/##y0rNyan8/19L5/B0a22uw8sfNa1x8VE5OjnzUeOOhzsWHdp6bE2Iz//D7UDx//8NdBQMdRSMdBRMgAwQB8g0NNNRMAPzwQIWYBaYaQmUMTQFsU0NLSAqQBwjM3MjAwA "Jelly – Try It Online") ## How it works ``` *,×;+ - Helper link. Takes two integers k and d on the left and right * - k * d × - k × d , - [k * d, k × d] + - k + d ; - [k * d, k × d, k + d] ç€DL$œi⁸ḢµƬTL - Main link. Takes n on the left µ - Group the previous links into a monad f(n): $ - To n: D - Cast to digits L - Length € - Over each k = 1, 2, 3, ..., n: ç - Call the helper link with k on the left and the digit length on the right ⁸ - n œi Ḣ - Find the index of the first triple containing n Ƭ - Until reaching a fixed point, repeatedly apply f(n) Both 1 and 0 are fixed points of f(n) As Ƭ returns [n, f(n), f(f(n)), ..., 1] for n > 0 and [0] for n = 0, 1 being a fixed point offsets the included n at the start. However, taking the length here would return 1 for n = 0 instead of 0 T - Find the indices of non-zero elements. As every element is non-zero unless n = 0, this yields [1, 2, ..., l] for n > 0 and [] for n = 0, where l is the output L - Length ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 134 bytes ``` .+ ,$&,$&$* +`,(.)*,(1*?)((?=\2+$)(?<=(?=(?<-1>(?=((1*)(?=\2\5+$)1)(\4*$))\6)+1$)\2).*|(?<-1>)(?<-1>\2)+|(?<-1>1)+)$(?(1)1) 1,$.2,$2 1 ``` [Try it online!](https://tio.run/##LYsxDsIwDEV3n8Mg/yREddRGRaJk5BIZysDAwoAYuXtwWiRL//k/@/34PF/3dpDb2qKnwEcbduTXIBEuiLoCkbLU5BlSLouxxUmvHUxjk3UyrZA6OgZqhldGTYjuu19jD6v8v1F4sBRR@yMNHFPgRNraQEqJRlIDKzLlzn2Ze3Y4Z9LJaNJ5c8PwAw "Retina 0.8.2 – Try It Online") Link includes faster test cases. Explanation: ``` .+ ,$&,$&$* ``` Create a working area consisting of the result (initially 0), the input, and the input converted to unary. ``` +` ``` Repeat until the input has been reduced to zero ... ``` ,(.)*,(1*?)( ``` count the number of digits `d` in the value `n`, and then find the smallest value that satisfies one of ... ``` (?=\2+$)(?<=(?=(?<-1>(?=((1*)(?=\2\5+$)1)(\4*$))\6)+1$)\2).*| ``` ... its `d`th power is `n`, or ... ``` (?<-1>)(?<-1>\2)+| ``` ... its product with `d` is `n`, or ... ``` (?<-1>1)+) ``` ... its sum with `d` is `n`, and ... ``` $(?(1)1) ``` ensure that it was in fact `d` and not some smaller integer, and ... ``` 1,$.2,$2 ``` increment the output and replace `n` and its unary with the result. ``` 1 ``` Convert the output to decimal. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes ``` [D0Q#DUgVXYzmXY/XY-).Δ©D2.òsòQ®XÊ&}ò¼}¾ ``` [Try it online!](https://tio.run/##AT4Awf9vc2FiaWX//1tEMFEjRFVnVlhZem1YWS9YWS0pLs6UwqlEMi7DsnPDslHCrljDiiZ9w7LCvH3Cvv//MTUwMA "05AB1E – Try It Online") Why can't you try it online? Because there's a bug with the TIO where raising numbers to floats which are actually whole numbers runs infinitely. ## Explained ``` [D0Q#DUgVXYzmXY/XY-).Δ©D2.òsòQ®XÊ&}ò¼}¾ [ # Start an infinite loop with the input already on the stack. D0Q# # End the loop if the result from two lines above is 0 DU # Store the top of the stack in variable X gV # And store its length in variable Y XYzm # Push the Yth root of X XY/ # Push X / Y XY- # Push X - Y ) # And wrap that into a list .Δ # From that list, get the first item where: ©D2.ò # The item, when rounded to 2 decimal places sòQ # Equals the item rounded to the nearest integer ®XÊ& # And where it doesn't equal variable X } # ò # Round that result to the nearest integer ¼} # Increment the counter variable, which keeps track of how many iterations we've gone through ¾ # Push the counter variable and implicitly print ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 31 bytes ``` ⊞υNW⌊υ⊞υ⌊Φι№⟦XκLι×κLι⁺κLι⟧ιI⊖Lυ ``` [Try it online!](https://tio.run/##XY09CwIxEER7f8WWG4hwFlaWJ4KgksJOLM5zMYv5kFzW@/kxitdcMzCPx0xvu9THzpViZLAoGvbhJfkk/kYJldosRsuOAI8c2ItHUQomdWI7drnarKGNEjJeTBxrf2o4UHhki6yUhjN7GubQOJmxq4aa32eTuI613ZBxS30iTyHTHf@q/KRSVuumKcu3@wA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υN ``` Input `n` and push it to the predefined empty list. ``` W⌊υ ``` Repeat until the list contains zero. ``` ⊞υ⌊Φι№⟦XκLι×κLι⁺κLι⟧ι ``` For all integers less than `n`, take the `d`th power and the product and sum with `d`, and push the lowest integer where one of the results is `n` to the list. ``` I⊖Lυ ``` Output the final number of iterations, which is one less than the length of the list. [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-lm`, ~~121~~ 120 bytes * -1 thanks to ceilingcat To get the number of digits, I used the floor of `log10+1` of the value. Each iteration runs through the operations until the result is an integer that doesn't match the current value; when the result is `0` the number of steps is returned. ``` f(i,c,o,l){float a;for(c=0;i;i=a,c++)for(o=0,l=log10(i)+1,a=.1;fmod(a,1)||a==i;)a=o++?o>2?i-l:(i+0.)/l:pow(i,1./l);i=c;} ``` [Try it online!](https://tio.run/##JU/NcsIgEL7zFDvt2IEJiYD5U0p8kV4oMYqDwTGxHtRXb7qxB2a/3wVcundumjrqueORB3bvQrQjWN3FC3VGaK@9sdwlCZuVaAQPJsS9FNSzRHJrMqm7U2yp5ZI9HtYYr5k1MUm2sVFbn4YN9YnI2DJszvGGF8lsGRhudfo5vfvehWu7g89hbH3MDg0hvh/hZH1Pf6JvGdwJwCx5ftQE8fwMDYOzfUffFi0s2q/@jcOHx3NkjdQMQwDnC5b@E6bBEAzj7jwAHQ7xGlr43qHGXk0s4v8ZhyPT5DkJEESCJAoUySEnUkBJpIKKyBIKUuawRk2AxKHqWRbIKiypdTnTAmlNClnnOGYTs6sVUbIoECElqqzUC6Ita1EjLsmqrnIl8nqNxq/rgt0PUxpOU3r7Aw "C (gcc) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 47 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ǃô▄↑"è≈■É↑├µxαêöV*┐┘ÆwaYM╙¿9⌠╛o-ºtΓ⌡╔ΔZj♦○Qæº` ``` [Run and debug it](https://staxlang.xyz/#p=809f93dc18228af7fe9018c3e678e08894562abfd9927761594dd3a839f4be6f2da774e2f5c9ff5a6a04095191a760&i=1500&m=2) Accomodates for floating point innacuracies. ## Explanation `,` put input on main stack `{...w` loop till falsy value `X` store current interation in register X `c$%` get number length `bbbb` duplicate number 4 times `u#aa` get floating point root `|N` get integer root `-Au<{sd}{d}?~` if difference < 0.1, take the integer root otherwise float `/~` get n/d `-~` get n-d `Lr` convert all those to array, reverse `{...}j` find first value which satisfies: `cx=!` not equal to current iteration `_c1u*@=*` and not equal to its floor `ciYd` save iteration index in Y `y^` output final index [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 82 bytes ``` D,f,@,BDbLddARdV$€*$G$€+@G$€Ω^BcB]A€ΩedbLRz£*bUBZ@B]A$þ=bU x:? Wx,`x,$f>x,`y,+1 Oy ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQcfJJcknJcUxKCVM5VHTGi0VdxCl7QCmzq2Mc0p2inUEM1NTknyCqg4t1koKdYpyAIqqHN5nmxTKVWFlzxVeoZNQoaOSZgekK3W0Dbn8K////29oamAAAA "Add++ – Try It Online") ]
[Question] [ Given a matrix of size at least 3×3 formed by positive integers, determine if it contains at least one "U" pattern, defined as ``` + + + - - - + + + + - N - N - + + + - N - N - + + + - N N N - + + + + - - - + + ``` where * `N` is the same number, repeated in those seven positions * `-` (optional) represents any number different than `N`. Each `-` can be a different number * `+` (optional) represents any number. Each `+` can be a different number. The amount of `+` and `-` entries obviously depends on the size of the matrix. In particular, some `-` may not exist because the pattern is adjacent to a matrix border. The above representation corresponds to a 5×8 matrix. The pattern must have the specified orientation. Reflections or rotations are not valid. # Test cases ### Truthy * Pattern with `N=8`: ``` 3 4 7 5 6 5 4 8 8 7 3 8 5 8 2 4 9 9 9 8 7 8 1 3 4 5 3 8 8 8 3 6 6 8 9 2 3 2 1 4 ``` * Same pattern with some `N` values nearby: ``` 3 4 7 5 6 5 8 8 8 7 3 8 5 8 2 4 9 9 9 8 7 8 1 3 4 5 3 8 8 8 3 6 6 8 8 2 3 2 1 4 ``` * Pattern with `N=3`, touching a matrix border: ``` 7 5 4 7 5 4 5 6 7 1 5 3 5 3 6 3 3 5 3 3 9 3 2 3 3 1 2 6 7 3 3 3 4 5 2 8 9 6 8 4 ``` * Pattern with `N=4`, touching a matrix corner: ``` 4 1 4 6 4 3 4 3 4 4 4 5 7 5 3 5 ``` * Two patterns, with `N=5` and `N=9`: ``` 6 7 9 4 5 6 7 5 2 5 9 8 9 8 5 1 5 9 6 9 3 5 5 5 9 9 9 4 8 7 6 1 3 2 5 ``` * Pattern with `N=3`, and broken pattern with `1`: ``` 1 2 1 2 3 2 3 1 2 1 2 3 2 3 1 1 1 1 3 3 3 ``` * Numbers can be greater than `9`; here `N=25`: ``` 23 56 34 67 34 3 34 25 4 25 48 49 24 25 97 25 56 56 12 25 25 25 32 88 ``` * Minimalistic case, `N=2`: ``` 2 1 2 2 5 2 2 2 2 ``` ### Falsy * Nothing special here: ``` 7 8 6 5 4 3 4 5 6 3 3 5 6 4 4 7 8 9 3 2 ``` * Rotated or reflected patterns are not valid: ``` 9 9 9 3 7 7 7 5 4 4 9 2 7 8 7 6 9 9 9 8 7 9 7 4 ``` * Some `-` entry spoils the pattern ``` 9 5 5 6 5 3 8 5 9 5 2 9 5 5 5 ``` * Some `-` entry spoils the pattern, even if the result would be a "U" with longer horns ``` 7 8 5 2 5 9 2 5 6 5 3 8 5 9 5 2 9 5 5 5 ``` * Minimalistic case, no pattern ``` 9 9 9 9 8 9 9 9 9 ``` # Additional rules * You can choose to output: + Any two distinct values/arrays/strings... depending on whether the matrix contains the specified pattern or not; or + Anything [truthy](https://codegolf.meta.stackexchange.com/a/2194/36398) if the matrix contains the specified pattern, and anything [falsy](https://codegolf.meta.stackexchange.com/a/2194/36398) otherwise. The specific truthy and falsy values/arrays/strings... can be different for different inputs. * The code should work in theory for matrices of arbitrarily large size, containing arbitrarily large numbers. In practice, it is acceptable if the program is limited by time, memory or data-type restrictions. * Input and output are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. [Answer] # JavaScript (ES7), ~~124 110~~ 105 bytes Returns a Boolean value. ``` m=>m.some((r,y)=>r.some((v,x)=>(g=n=>n--?v==(m[y+~-(n/5)]||0)[x+n%5-1]^144140166590/3**n%3&&g(n):1)(24))) ``` [Try it online!](https://tio.run/##nVFLb9swDL7rV/DSRmpelvWw3cLpaT3u0t2SDPBSJ/UQy5mdBA3W7a9npOR2QYFdBpq0KJHfx8f34lh0q7ba7ceueSrP6/xc57N60jV1yXk7Ool81vbecfSCHt/kLp@58fj@mOe8np@Gv8fcTY1Yvr5GYv4ydFdmLJdfpdZSR9Jak0VTdXPjrtT19YY7cSsFj7UQ4tyWPw5VW/LBuhuISVsWTw/Vtnw8uRWPxGTfPO7bym24mHS7bbXng4VbOAxcN@2nYvXMeTeCSkA@g58MoII8hwjuYdW4rtmWk22z4YP5l/awfz4tBwJuQ0j6MWTh5g/FtutjojvEunxf8@4vP7LXxY53RPp2PYXhNFx/PtTfyhY7E3fslzgr0JCAAYuqIWUpegr5DWoMmmVAQrcpSFBM4wu9kyiwzOI/w0iFKjGeXQKm/wmYXgImvrJgERZ96VNILQKEk0JQSiFf4t96WtUTxL5KgkZATbgIpIFqpQAS44kQjDHKzQIbJIyyjS8ZFT3pPUt86BnvkWjfqqWmKIMx6TuI@7I@ekFCiSxGXuwFq0rIUhcaYgPgrcayMxb7c5aQxWBjmYzpHD6FLaYIRByMCiaLQvNLw3b9asz7zCy17V/95Fi/GYVNkBg/F1pt4rdlLzaXoWpKMGHRLCwYfSQNtyYQ@@GxzI/wn4EemPkJ9@cwrfdu5Fs3fwA "JavaScript (Node.js) – Try It Online") ### How? For each reference cell of value \$v\$ at \$(x,y)\$ in the input matrix \$m\$, we test 24 neighbor cells. The constant \$144140166590\$ is \$111210001101011010121112\_3\$ in base 3. By reversing the digits and rearranging them into a 5x5 matrix, this gives: $$\begin{pmatrix}2&1&1&1&2\\ 1&\color{red}0&1&0&1\\ 1&0&1&0&1\\ 1&0&0&0&1\\ 2&1&1&1&-\end{pmatrix}$$ where: * the cell in red is the reference cell * \$0\$ means that this cell must be equal to \$v\$ * \$1\$ means that this cell must be different from \$v\$ * \$2\$ means that we don't care The bottom-right cell of the matrix is ignored, but it should be a \$2\$ anyway (for *we don't care*). The \$n\$-th cell to test (0-indexed) is the cell whose coordinates are: $$\big(x+(n\bmod 5)-1,y+\lfloor n/5\rfloor-1\big)$$ The corresponding value in the above matrix is given by: $$V=\left\lfloor\frac{144140166590}{3^n}\right\rfloor\bmod 3$$ We do a bitwise XOR between the cell comparison test and \$V\$: ``` is equal | V | XOR | success? ----------+-----+-----+-------------------------- 0 | 0 | 0 | no (should be equal) 1 | 0 | 1 | yes ----------+-----+-----+-------------------------- 0 | 1 | 1 | yes 1 | 1 | 0 | no (should be different) ----------+-----+-----+-------------------------- 0 | 2 | 2 | yes \__ always 1 | 2 | 3 | yes / ≠ 0 ``` If all 24 tests are successful, we've found a valid `U`. [Answer] # [Julia 0.6](http://julialang.org/), ~~78~~ 75 bytes ``` x->any(n->7∈conv2(reshape(digits(287035908958,3)-1,5,5),1÷-~abs(x-n)),x) ``` [Try it online!](https://tio.run/##pVJdTsMwDH7nFH5MpFZakzg/ithFEA8FNiiayrQONF543o04ADfhIsV2NoE6JiEhz16S2v7sz358XnWtH5eX466et/2r6ut5@Nzvb5/6F6M2i@GhXS/UXXffbQdlYphZTLOYMFZW102FFeqq@Xiv39qbQe3qXutqp8f1puu3q14t1ZUFBwEQPKmDmCHS1ZJFUgMuQxLh5wgN2ExuKB4sFnym2Egehi6GPNy11hdnEOI/EOJZhCC1F4vsHsiJM7B6TliOllA4gzw0dPBSiT1CGumDsaYIjlE5swMryicWzIJL@ScRnDqVeiBkSY7SZGIKUApkrMTgKFJocIUgz0xw0CRvIwyYYx8n1yLS1CTSUJFEBrUR2AoLDgwCiHXUdcpg5JICW3JH6rkxfCk/SxzFaWKuIEuD8kdyMqBYFiwLffg9FM8sZpm8zGYSWCix9J0FC@u8aqGQ9HN3Eqk7iceyefmwcYmPBso7/lKmDCoLxt8DpYhcxnsoiTzGLw "Julia 0.6 – Try It Online") Uses 2D-convolution to find the pattern encoded in the magic constant. The constant is derived via base 3 digits similarly to [Arnauld's answer](https://codegolf.stackexchange.com/a/206492/78274), but with 0 and 2 swapped. This way, after subtracting 1, we get the following correspondence: `N = 1, '+' = 0, '-' = -1`. The input matrix is transformed to `N = 1, everything else = 0`. After convolution, the middle cell of the found pattern will accumulate a total of 7 (for the number of N's in the U-shape). If any of required N's is missing, the sum will not reach 7, and if an N (= 1) is present in the forbidden position, it will gain a negative contribution due to the multiplication by -1 in the pattern. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~62~~ ~~51~~ 45 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) -6 based on [fireflame241's solution](https://codegolf.stackexchange.com/a/206494/43319). ``` ⍲,(⍱{'GILNQRS'≡⎕A[⍸,⍵]~'AEUY'}⌺5 5⍤=)¨∘⊂0⍪0,⊢ ``` [Try it online!](https://tio.run/##pVLNSgNBDL77FN5GIYK7M7M7K3go4k@lKHb1IKUHoa0XUQ8eFNGDQtHiiB4Er4oHEUEUBfHYR8mL1CRTBekiiGRndpJJ8iXfZG17Y6yxt7axtT7W3N1pbjaajV4P/QuMoH/eV7PlysJSNVd4eoPnV6Ua@ndA/1Y/VKXplVV1gGcfdtiiv5sc7d7jyTV2jsbRP4wDdm57LWxfoD/HzjH6R/Sv3SeN7UvKk1enaF@eK@c9tVxdmZ5QQ63hcDWfLy6oWk2DgRQsJLQMuDrUHOkaHOkOYjBkyYCF7Q4i0GQxdMs@LBoSsiR0yshf04ooqv4rkvsnkvsVKZVewm4lJiVPzsMrkbzhrAmN8wRLRKdEatLf2LH0xZhFSIYrEAQD3F@IYrGCKpgFcYySheogJU/GsdJ5JsxYqZdxM8lpwYrOYvrMJcwQxxXkj4Sb@Lu3QT1I6HQwPqayiSdqLeVd6DEQM6G8ERkZmWLRspR3crfMQxSzFj5N5Lmi7FwLxzO/8idhPzVTquQFQ8rjIAMqzxRo@3rEhOkWsl14zALAQJwm0lhs/5F4XFMZtuTH6GW0TGEWG8ZXkJ08iJXyw40tHEUnQ2QFIf5zvFQlsa7/Z72uPgE "APL (Dyalog Extended) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes ``` ⊙θ∧‹¹κ⊙ι∧‹¹μ⬤θ⬤ν∨‹³⁺↔⁻ξ⊖κ↔⁻ρ⊖μ⁼⁼λπ∧›²↔⁻ξ⊖κ∨⁼¹↔⁻ρ⊖μ∧⁼ξκ⁼ρ⊖μ ``` [Try it online!](https://tio.run/##hU89D4IwEN39FR2vSR2Q0YlE46KRnXSo0ETCUaQFA7@@FtoQSYg2l/t67@5e86fQeSPQ2lSXqoNEjdAykqgCrtIYiBip6FSPUK7b9dRGnNkuKEbu2oMxIyn2BpKHgVupXDYwcpK5lrVUnSygonQaXmC9hmtKZ8K57QUaCAEZeVEv4aKl6KSGw/eSjRt01hTmo38X/e7AHvy/Q7UpcHlHa7Msc/udHu9j7/mOkV/9xWJvnHO7f@MH "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array and outputs a Charcoal boolean, i.e. `-` if it contains U, nothing if not. Explanation: ``` ⊙θ∧‹¹κ ``` Find a valid bottom row where: ``` ⊙ι∧‹¹μ ``` Find a valid right column where: ``` ⬤θ⬤ν ``` All elements of the array must satisfy: ``` ∨‹³⁺↔⁻ξ⊖κ↔⁻ρ⊖μ ``` The element has a Manhattan distance from the centre of the U of more than 3, or... ``` ⁼⁼λπ ``` ... the equality of the element with the outer element matches: ``` ∧›²↔⁻ξ⊖κ ``` The vertical distance of the element from the centre of the U is less than 2, and... ``` ∨⁼¹↔⁻ρ⊖μ ``` ... the horizontal distance of the element from the centre of the U is exactly 1, or... ``` ∧⁼ξκ⁼ρ⊖μ ``` ... the element is the bottom centre of the U. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 62 bytes ``` {{∨/∊({7 9 12 14 17 18 19≡1 5 21 25~⍨⍸,⍵}⌺5 5)¨(,⍵)=¨⊂⍵}0⍪0,⍵} ``` [Try it online!](https://tio.run/##nVK9TgMxDN55Co@tREXzd0kGJhY6IVFeoFJblgoYGEAVDCBVpeIqGHgAtoqFBSTE2EfJixz2l2sRqGJAvvhix/7sz0nvbNTqX/ZGp8etwcX54KQ/6FfVeJymi500nTXGniIpTcqS8qQCqZjunhU50oq0u07lIpUf26l8v0r3n45cc7loiNncXS7S7EYO2ql8aSOkGqbJQyrnaf7UOUiz2@WrSZNHtrqHe6yP9jvdasjYIZVvZMiSZ6PgZSmwePYFOSbNnggRL3eFaIdzEcNZBf8jRxpeiuzWRuDwT@CwCdij06wFngeGVIc0U@8MgxukGz7XiDMQydLoWkpYYmRLVpCtFGKvRZQsi2if8dGCl0ABi@vyAufAJYKfglWgAQfJXC3YFmCrAWcynAJFXff728qC3tFqISmaoZksW160EaVlIqKYFV8J9tGL5lD@@IHxPn@GJxDQgQEcKmpQgaCSy@MO9eMwNeM84gLD8WBtkGDy/WSyTA3iECYvxNf0vy8@8rJIdDnR1e8lv5OIdrLX/WxoNXL9Z0JNLq5LrnZf "APL (Dyalog Extended) – Try It Online") (includes the new test case). My first APL golf! Returns a `1` if there is a `U`, or `0` otherwise. [Answer] # [J](http://jsoftware.com/), 68 bytes Builds up 16 U's with the 16 possible combinations of 0 and 1 in the corners, then looks for them in the position matrix of each number. ``` [:+./@,(0 4 4|.#:20 20 28(,4 4&#:)"p./i.16)E."2/[:(="{~,)4|:@|.@,&_] ``` [Try it online!](https://tio.run/##pVLdS8NADH@/vyJ0sLZYb@199a4yGIg@@eTrkCHimCIoOh/E4b9e87GhsJUhkia9HLn8kl/y2Gc6X8K0gxwqqKFDPdVwfn112c@7Ez2ZVUUNDtxGjzpTA32xqPBiPOrK7EVPHnQTygudmcm8K6bZ51dVuk032@hZNV7c9GV/f7d6hnz9@r5efeRKLaEeZ/pMLwwUjFcqsIjQgoeA6iAqiOhatB7VgFOQWOg6QgNWYZjnCBILQeHbiBEGHYMRTpVHkeI/kOJRpJZ7EevpWYvBlIk0UGI5WkSjTHzR4CFwRXYHbbgvwnQwAOWoDIJw3J8FOpF4KQOBBl4SVpICoVWM5rn7RNx4rpjAE1XjWYQfJ8wFoogeDeRvmCKza3DPFZFuD2cwWDyyhe21ZJkmB8YDsHVIS8IodlJLFsM9ctEYcuSzSGIcAqCKFDfOPxSMlKVd3j694c4eHm@UdZWd8j8jDUS9BPBkB3CFR4txJF5GRgvcCrO/NzGhusE8XvZZbfc40dFs7/3gdkaZtmLMvyfg4pTsyq5UVX4D "J – Try It Online") ]
[Question] [ You can depict a [triangular number](https://en.wikipedia.org/wiki/Triangular_number), T(N), by writing one 1 on a line, then two 2's on the line below, then three 3's on the line below that, and so on until N N's. You end up with a triangle of T(N) numbers, hence the name. For example, T(1) through T(5): ``` 1 1 22 1 22 333 1 22 333 4444 1 22 333 4444 55555 ``` To keep things nicely formatted we'll use the last digit of the number for N > 9, so T(11) would be: ``` 1 22 333 4444 55555 666666 7777777 88888888 999999999 0000000000 11111111111 ``` Now pretend like each row of digits in one of these triangles is a 1-by-something [polyomino](https://en.wikipedia.org/wiki/Polyomino) tile that can be moved and rotated. Call that a row-tile. For all triangles beyond T(2) it is possible to rearrange its row-tiles into a W×H rectangle where W > 1 and H > 1. This is because [there are no prime Triangular numbers above N > 2](https://math.stackexchange.com/a/1012326). So, for N > 2, we can make a rectangle from a triangle! (We're ignoring rectangles with a dimension of 1 on one side since those would be trivial by putting every row on one line.) Here is a possible rectangle arrangement for each of T(3) through T(11). Notice how the pattern could be continued indefinitely since every odd N (except 3) reuses the layout of N - 1. ``` N = 3 333 221 N = 4 44441 33322 N = 5 55555 44441 33322 N = 6 6666661 5555522 4444333 N = 7 7777777 6666661 5555522 4444333 N = 8 888888881 777777722 666666333 555554444 N = 9 999999999 888888881 777777722 666666333 555554444 N = 10 00000000001 99999999922 88888888333 77777774444 66666655555 N = 11 11111111111 00000000001 99999999922 88888888333 77777774444 66666655555 ``` However, there are plenty of other ways one could arrange the row-tiles into a rectangle, perhaps with different dimensions or by rotating some row-tiles vertically. For example, these are also perfectly valid: ``` N = 3 13 23 23 N = 4 33312 44442 N = 5 543 543 543 541 522 N = 7 77777776666661 55555444433322 N = 8 888888881223 666666555553 444477777773 N = 11 50000000000 52266666634 57777777134 58888888834 59999999994 11111111111 ``` # Challenge Your task in this challenge is to take in a positive integer N > 2 and output a rectangle made from the row-tiles of the triangles of T(N), as demonstrated above. As shown above, remember that: * The area of the rectangle will be T(N). * The width and height of the rectangle must both be greater than 1. * Row-tiles can be rotated horizontally or vertically. * Every row-tile must be depicted using the last digit of the number it represents. * Every row-tile must be fully intact and within the bounds of the rectangle. The output can be a string, 2D array, or matrix, but the numbers must be just digits from 0 through 9. The output does not need to be deterministic. It's ok if multiple runs produce multiple, valid rectangles. **The shortest code in bytes wins!** [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` n=input() c=~n%2 while c<n:print`n%10`*n+`c%10`*c;n-=1;c+=1 ``` [Try it online!](https://tio.run/##JcxNCoMwFEXh@V1FCQhtRfCl/9rsJfAIGCi3oaRoJ916RJ2dwcdJvzy8acs4xFfYSRemoMaYQheZvnl/gLo/K4sN6JNd@kRmz0paf2TtdQ3t2TjptXZSVoDlcsIZF1xxwx0PSAsRiJ0B "Python 2 – Try It Online") Prints like: ``` 55555 44441 33322 ``` It looks kind-of redundant to update `n-=1;c+=1` where sum `n+c` remains unchanged. I feel like there's a better way, but I haven't seen it so far. [Bounty is up for grabs!](https://codegolf.meta.stackexchange.com/a/18334/20260) --- **60 bytes** ``` n=input() b=a=n/2 while n-b:b+=1;print`a%10`*a+`b%10`*b;a-=1 ``` [Try it online!](https://tio.run/##JYxRCsIwEAX/3ykkIKil2I3a2pa9S7ISaEDWUFK0p49Y/wZmmLTm6aW2vKf4DDsawic8jDFFOWpa8uEIYc96tvgXWssgFdOY5qjZ@T017uQrJxvI6Gumsjn8NhdccUOLDnf0oAZEIPsF "Python 2 – Try It Online") Prints like: ``` 22333 14444 55555 ``` Based on ideas by @newbie. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~49~~ ~~47~~ ~~34~~ ~~38~~ 35 bytes *3 bytes saved thanks to @Bubbler!* ``` {10|(⌈⍵÷2)↑↑,/⍴⍨¨⍉↑((⍳⍵)-2|⍵)(⌽⍳⍵)} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqQ4MajUc9HY96tx7ebqT5qG0iEOnoP@rd8qh3xaEVj3o7gXwNjUe9m4EqNHWNakAUUMNeqEgt0BiFQysUjLWBAhYA) ``` ⍉↑ ⍝ concat each pair in ((⍳⍵) )(⌽⍳⍵) ⍝ 1..n and n..1 (into 2×n matrix) -2|⍵ ⍝ concats n-1..0 if n is odd ⍴⍨¨ ⍝ repeat each item *itself* times ↑,/ ⍝ flatten (⌈⍵÷2)↑ ⍝ take first n/2 rows 10| ⍝ for each item, take the last digit 0 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 1 6 => 1 6 6 6 6 6 6 => 1 6 6 6 6 6 6 2 5 2 2 5 5 5 5 5 2 2 5 5 5 5 5 3 4 3 3 3 4 4 4 4 3 3 3 4 4 4 4 4 3 4 4 4 4 3 3 3 5 2 5 5 5 5 5 2 2 6 1 6 6 6 6 6 6 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 14 bytes ``` Ýεθy×}2äí`RøJ» ``` [Try it online!](https://tio.run/##ASIA3f9vc2FiaWX//8OdzrXOuHnDl30yw6TDrWBSw7hKwrv//zEy "05AB1E – Try It Online") [Answer] # JavaScript (ES8), ~~72 71~~ 68 bytes Returns a string. ``` n=>(g=k=>k<n?(h=k=>''.padEnd(k,k%10))(k)+h(n--)+` `+g(k+1):'')(~n&1) ``` [Try it online!](https://tio.run/##XcixDoIwEADQna@4RXuXE2LjphxOrn4DDVCQkisB42L016uubi9vdA@3Nsttvuca2y55SSoV9hKkCqWecfjJmGJ27UVbDLuwsXsiDMQDap4T11nNPQa2dDSG8K1bS8nHBRUEDidQKAWs/YKZ4JkBNFHXOHXFFHs0VzHAoPT3HpUoe6UP "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` NθE…÷θ²θ⭆⟦⊕ι⁻|θ¹⊕ι⟧⭆λ﹪λχ ``` [Try it online!](https://tio.run/##VYyxCsIwEIZ3n6LjBSpYJ6GbuHRoFR3FISZHPUgvTZrUx4@Jkx4cHP//fade0isrTUodzzEMcXqiByfazcUTB@jlDFfJI0LH4UQraQRXV3tRVy7vLWRqLNC9Y@VxQg6ogXLVE8cFjhTetODZF6vJ8T8mHr8/TLasjsaWq9mJ77QpHdJ2NR8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `N`. ``` E…÷θ²θ ``` Loop rows from `N/2` to `N`. (Due to the increments in the code below, `N/2` is excluded and `N` is included. I could have put the increments here for the same byte count.) ``` ⭆⟦⊕ι⁻|θ¹⊕ι⟧ ``` Each row contains two row-tiles, one for the row and one for `N|1` minus the row. (If `N` is odd then this last row-tile is empty.) ``` ⭆λ﹪λχ ``` Each row-tile consists of copies of its last digit. [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 109 bytes Seems huge in comparison with other answers. ``` t(A,B)when A<B->"";t(A,B)->[string:copies([X rem 10+48],X)||X<-[A,B]]++" "++t(A-1,B+1). t(N)->t(N,1-N rem 2). ``` [Try it online!](https://tio.run/##JYyxCsMgGIR3n0KcFP1DLR3aNAjJA2QWxCEEmwqNCSpkybtbaW@44fi@c/EzhQVcmqPfc0El014M7Hi7gPtuAEXI8z@BMilHH5Z23nbvEjUaR7dieeG3uxWanafuwFTUWs4JIpxXEaQYuGQNynSsF7WFhPEnXllT1skHaizDoBCu8Vv7OqLPjmb6YBX4Ag "Erlang (escript) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-n`, 43 bytes ``` @a=map$_%10x$_,$_&1^1..$_;say$_,pop@a for@a ``` [Try it online!](https://tio.run/##K0gtyjH9/98h0TY3sUAlXtXQoEIlXkclXs0wzlBPTyXeujixEihQkF/gkKiQll/kkPj/v8W//IKSzPy84v@6vqZ6BoYG/3XzEgE "Perl 5 – Try It Online") [Answer] # Java 11, 89 bytes ``` n->{for(int c=~n&1;c<n;)System.out.println((n%10+"").repeat(n--)+(c%10+"").repeat(c++));} ``` Port of [*@xnor*'s Python answer](https://codegolf.stackexchange.com/a/203140/52210), so make sure to upvote him!! [Try it online.](https://tio.run/##bY/BCsIwEETvfsUiKFlKg8FjrH@glx7FQ0xTidZtadOClPrrda16ES8LOzvsvLmYzsSX7DrawjQN7IynfgbgKbg6N9bB/rUCdKXPwArWgVCzNMx4NMEEb2EPBMlI8bbPy3ry2ORBS6XthjSm9ya4myzbIKuajwUJQQu1iuZzlLWrnAmC4hgjYX9UG0WIehj1K6tqTwVnfSInnhvTijTw0/PhCAbfqF8Gn6w1@E2ilIY/DIiTG4Ak9@Kkd6thfAI) **Explanation:** ``` n->{ // Method with integer parameter and no return-type for(int c=~n&1; // Temp-integer `c`, starting at 0 if the input is odd; // or 1 if even c<n;) // Loop as long as this `c` is smaller than the input `n`: System.out.println( // Print with trailing newline: (n%10 // The last digit of `n` +"") // converted to String .repeat(n // repeated `n` amount of times --) // After which `n` is decreased by 1 with `n--` + // Appended with: (c%10 // The last digit of `c` +"") // converted to String .repeat(c // repeated `c` amount of times ++));} // After which `c` is increased by 1 with `c++` ``` [Answer] # [J](http://jsoftware.com/), ~~41~~ 33 bytes -8 bytes thanks to Bubbler! ``` 10(|-:@##"1~@{.],.|.)2&|@>:}.i.,] ``` [Try it online!](https://tio.run/##bcuxCsIwFIXhvU9xSaBNaHJI6iIRy0XBSRxcJZNYjIsP0NRXj7WuHc7ww3deRaAZaB@oIUOOwjwLOl7Pp@KdyjawlMJ/eEQ0yNBdnbkPExJMLJcDyLvcg21YlFpj1Rr7KZ5W4KKUFBLzJeq/TeBb622XR3DU0cxtK1097s83qd2g635DLSVsyxc "J – Try It Online") # [K (oK)](https://github.com/JohnEarnest/ok), ~~41~~ ~~38~~ 32 bytes -6 bytes thanks to ngn! ``` {(x%2)#10!{x}#'(a-2!x),'|a:1+!x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqNC1UhT2dBAsbqiVlldI1HXSLFCU0e9JtHKUFuxovZ/mrqxtqLlfwA "K (oK) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~85~~ 82 bytes Saved 3 bytes thanks to [newbie](https://codegolf.stackexchange.com/users/89856/newbie)!!! ``` i;c;f(n){for(c=-n%2;++c<n;--n,puts(""))for(i=0;i<n+c;)putchar((i++<n?n:c)%10+48);} ``` [Try it online!](https://tio.run/##HYxBCsIwEEX3OUUIFGaIgVa7ECfFi7gpA9EEHEusq5Czx@jy/cd/7O7MrUViCiBYwisDL06GI1nLXsg5OWyf/Q3GIP5sXEaKXiwT9p0fawaI1nq5yoVxmEY7n5Fqe65RAIv6f2TXaTlR8tPcuwl1UTpAQlJ6y90GMDcxHauq7Qs "C (gcc) – Try It Online") Port of [xnor's Python answer](https://codegolf.stackexchange.com/a/203140/75681) so make sure to upvote him!!! [Answer] # [Ruby](https://www.ruby-lang.org/), ~~64~~ 62 bytes ``` ->n{c=1&~n;n,c=n-1,-~c,puts("#{n%10}"*n+"#{c%10}"*c)while c<n} ``` [Try it online!](https://tio.run/##JczdCoJAEEDh@3mKwSi0dHHsn9peJWhaU7BR1CVD9NW3xKvzXZ3aPr4u1S66Sc@aVqNcJGQtEYXRyGFl28b3Fr0sKR68tWz@5tkcfLK8MMhXGdxMv0ONL9M2irPyXam2vOdYm4atQcmLABBT5XdTpzEYebot7GAPBzjCCc5AMRABJT8 "Ruby – Try It Online") Based on @xnor's Python answer, thanks! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 42 bytes ``` 10|{⍵=1:1 1⍴1⋄2|⍵:⍵⍪∇⍵-1⋄(⍳∘≢,1+⊢,⊢/)∇⍵-1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///39CgpvpR71ZbQytDBcNHvVsMH3W3GNUARayA@FHvqkcd7UCGLkhY41Hv5kcdMx51LtIx1H7UtUgHiPU1YQpq/6c9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P9pCsZcurq6XGkKJlDaFEobGgEA "APL (Dyalog Unicode) – Try It Online") A fresh approach using recursion, though not very short. ### How it works ``` 10|{⍵=1:1 1⍴1⋄2|⍵:⍵⍪∇⍵-1⋄(⍳∘≢,1+⊢,⊢/)∇⍵-1} ⍝ Input: n ⍵=1:1 1⍴1 ⍝ Base case: If n=1, give a 1x1 matrix of 1 2|⍵:⍵⍪∇⍵-1 ⍝ For odd n, prepend n copies of n on the top (⍳∘≢,1+⊢,⊢/)∇⍵-1 ⍝ For even n... ⊢,⊢/ ⍝ append its own last column to its right 1+ ⍝ add 1 to all elements ⍳∘≢, ⍝ prepend a column of 1..(number of rows) to its left 10|{...} ⍝ Apply modulo 10 to all elements ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` _Ḷ€ZŒHṚ;"¥/%⁵ ``` A monadic Link accepting an integer which yields a list of lists of integers in \$[0,9]\$. **[Try it online!](https://tio.run/##ASYA2f9qZWxsef//X@G4tuKCrFrFkkjhuZo7IsKlLyXigbX/w4dZ//8xMQ "Jelly – Try It Online")** (footer just reformats the output list of lists) I feel there may be shorter. ### How? ``` _Ḷ€ZŒHṚ;"¥/%⁵ - Link: integer, n € - for each (i) in (implicit range [1..n]) Ḷ - lowered range (i) -> [0..i-1] _ - (n) subtract (vectorised across that) -> [[n],[n,n-1],...,[n,n-1,...,1]] Z - transpose -> [[n]*n,[n-1]*(n-1),...,[1]] ŒH - split into half (first half longer if n is odd) / - reduce (this list of two lists) by: ¥ - last two links as a dyad: Ṛ - reverse (the first half) " - zip together applying: ; - concatenation ⁵ - literal ten % - modulo ``` --- An alternative first three bytes is `rRṚ` [Answer] # [J](http://jsoftware.com/), ~~30~~ 29 bytes ``` 10(|-:@#$]#~@,"0|.)2&|0&,1+i. ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/DQ00anStHJRVYpXrHHSUDGr0NI3UagzUdAy1M/X@a3KlJmfkK2hYp2mq2SkYK5gomCoYGikYGv8HAA "J – Try It Online") J's reshape `$` is so weird that it works in place of take `{.` when the left is positive singleton (regardless of what comes on the right). --- # [J](http://jsoftware.com/), 30 bytes ``` 10(|-:@#{.]#~@,"0|.)2&|0&,1+i. ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/DQ00anStHJSr9WKV6xx0lAxq9DSN1GoM1HQMtTP1/mtypSZn5CtoWKdpqtkpGCuYKJgqGBopGBr/BwA "J – Try It Online") Yet another case of [repeat-bind (dyadic `&`)](https://codegolf.stackexchange.com/a/195891/78410) winning over other approaches. ### How it works ``` 10(|-:@#{.]#~@,"0|.)2&|0&,1+i. NB. input=n 1+i. NB. 1..n 2&|0&, NB. prepend 0, but only if n is odd ( ] "0|.) NB. for each pair (x,y) of the above and above reversed, #~@, NB. concatenate x copies of x and y copies of y -:@#{. NB. take half the rows 10 | NB. modulo 10 to all elements of the array ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` ←½Ṡz+↔↓¬%2¹m´Rŀ→ ``` [Try it online!](https://tio.run/##ASkA1v9odXNr///ihpDCveG5oHor4oaU4oaTwqwlMsK5bcK0UsWA4oaS////Nw "Husk – Try It Online") [Answer] # [Icon](https://github.com/gtownsend/icon), 76 bytes ``` procedure f(n) c:=seq(1-n%2)&write(repl(n%10,n)||repl(c%10,c))&(n-:=1)=c end ``` [Try it online!](https://tio.run/##Zc9NCoMwEAXgvacIgjIDFTL1ZxHITbopY4RAO9rY0o13t9pubDK79/h4MJ5HWdcpjOz6V3BqAMGMjZ3dA6iS4ozlO/ing@CmG0hB@iS4LN/Ee2LEEqQyltBy5qQ/jN2vXgAztd1vJK@VyY/FADX@gYs0CWli0iakjUmXkC4mpGNCOjGUGNrM/uYH "Icon – Try It Online") Inspired by [xnor's Python solution](https://codegolf.stackexchange.com/a/203140/75681) - don't forget to upvote it! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 106 bytes ``` (r=#+(y=Mod[#+1,2]);""<>{z@#,z[r-#]}&/@Range@r)[[-⌈r/2⌉;;-y-1]]& z@x_:=""<>ToString/@Table[x~Mod~10,x] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X6PIVllbo9LWNz8lWlnbUMcoVtNaScnGrrrKQVmnKrpIVzm2Vk3fISgxLz3VoUgzOlr3UU9Hkb7Ro55Oa2vdSl3D2Fg1riqHingrW5C2kPzgkqLMvHR9h5DEpJzU6Io6oMF1hgY6FbH/ISLVAUD5En2HtOjsWB0w20FJqVanOlvHWMfQoDb2/38A "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ # Introduction Connect Four is a game where you attempt to get four in a row: horizontally, vertically, or diagonally. In this code golf, we will be trying to find who won, given a game board. There will always be one winner, and only one winner. --- # Task Given a Connect Four board, figure out who the winner is: `X` or `Y`. There will always be one winner, and only one winner. The board size will always be 6 by 7 like how the game board is in the in picture. Given a board the following board, in this instance, `X` is red and `Y` is blue: [![enter image description here](https://i.stack.imgur.com/wc0rt.png)](https://i.stack.imgur.com/wc0rt.png) Your input would be: ``` OOOOOOO OOOOOOO OOOOOOO OOOOXOO OOOXXOO OOXYYYY ``` You can separate rows of the game by newline character (like above), no dividing character, divide the rows into an array or list, or you can input a matrix of characters. Correct output for this example: ``` Y ``` Y has four in a row; so, Y is the winner. So, we output Y. --- # Test cases Input: ``` OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOYYOOO OYXXXXO ``` Output: ``` X ``` --- Input: ``` OOOOOOO OOOOOOO OOOOOOO XXXXOOO YXYYOOO YXYYXYX ``` Output: ``` X ``` --- Input: ``` YXYYXOO XYXXYOO XXXYYOO YYYXXOO XXYYYYO XXYYXXO ``` Output: ``` Y ``` --- Input: ``` OOOOOOO OOOOOOO OYOOOOO OOYOOOO OOOYOOO OOOOYOO ``` Output: ``` Y ``` --- Input: ``` OOOOOOO OOOOOOO OYOOOOX OOYOOOX OOOXOOX OXOXYOX ``` Output: ``` X ``` # Scoring Least number of bytes wins! [Answer] # Retina, ~~51~~ 48 bytes *Thanks to Martin Ender for saving 3 bytes* ``` M`X((.{6}X){3}|(.{8}X){3}|(.{7}X){3}|XXX) T`d`YX ``` [Try it Online!](https://tio.run/nexus/retina#fc4xCsMwDAXQPfcI2GC6NDS5QaeipcP/kMFDbpH47K4sJQQCqZdnf76E@/DO9ZMRwmN9FcT1WTa9Tud1LNgQ52EeYvfNSyZqJUiIJBBgU2lSY8v1qYGpQSd@0lWdQ5M27urO2/6p94W24W8fLlz72N5HupO2Xg5/) Takes input as a comma-separated list of rows [Answer] # Javascript (ES6), 54 ~~55~~ *Edit* 1 byte saved thanks @Arnauld I just check if X is the winner, as *There will always be one winner, and only one winner* Input is a string with any separator, like in @Arnauld's answer ``` F= b=>'YX'[+[0,6,7,8].some(x=>b.match(`X(.{${x}}X){3}`))] ;['OOOOOOO OOOOOOO OOXOOOO OOXOOOO OOXOOOO OOXOYYY' ,'OOOOOOO OOOOOOO OOXOOOO OOYXOOO OOYOXOO OOYYOXY' ,'OOOOOOO,OOOOOOO,OOOOOOO,OOOOOOO,OOYYOOO,OYXXXXO' ,'OOOOOOO,OOOOOOO,OOOOOOO,XXXXOOO,YXYYOOO,YXYYXYX' ,'YXYYXOO,XYXXYOO,XXXYYOO,YYYXXOO,XXYYYYO,XXYYXXO'] .forEach(s => console.log(s,F(s))) ``` [Answer] ## JavaScript (ES6), ~~77~~ ~~76~~ 69 bytes *Saved 7 bytes thanks to Neil* Takes input as a *something*-separated string, where *something* is basically any character. ``` b=>[...'XXXXYYYY'].find((c,i)=>b.match(`(${c}.{${(i%4+6)%9}}){3}`+c)) ``` ### Test cases ``` let f = b=>[...'XXXXYYYY'].find((c,i)=>b.match(`(${c}.{${(i%4+6)%9}}){3}`+c)) console.log(f("OOOOOOO,OOOOOOO,OOOOOOO,OOOOOOO,OOYYOOO,OYXXXXO")) console.log(f("OOOOOOO,OOOOOOO,OOOOOOO,XXXXOOO,YXYYOOO,YXYYXYX")) console.log(f("YXYYXOO,XYXXYOO,XXXYYOO,YYYXXOO,XXYYYYO,XXYYXXO")) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒgL⁼¥Ðf ;UŒD€;Z;$ç€4FṀ ``` Takes a list of strings (or list of list of characters) formed of `X`, `Y`, and `O` (would also work with replacements such that the space has a lower ordinal than both counters). **[Try it online!](https://tio.run/nexus/jelly#@390UrrPo8Y9h5YenpDGZR16dJLLo6Y11lHWKoeXAxkmbg93Nvz//z9a3R8C1HUIsiIjIyGsyAgg8FePBQA)** or run an [augmented version](https://tio.run/nexus/jelly#@390UrrPo8Y9h5YenpDGZR16dJLLo6Y11lHWKoeXAxkmbg93Nvx/uHvL4fb//yMjIiMj/P25IiIjIiJBNJAC0ZFAYbA4kAsUANNAAQA) that takes a multiline string. ### How? ``` ŒgL⁼¥Ðf - Link 1, runs of given length: list A, length B e.g. "XYYYXXO", 4 Œg - group runs of equal elements of A ["X","YYY","XX","O"] Ðf - filter keep: ¥ - last two links as a dyad: L - length 1 3 2 1 ⁼ - equal to B? (none kept in this case->) 0 0 0 0 ;UŒD€;Z;$ç€4FṀ - Main link: list of list of chars (or list of stings) I U - reverse each row of I ; - I concatenated with that ŒD€ - positive diagonals of €ach (positive and negative diagonals) $ - last two links as a monad: Z - transpose of I (i.e. the columns) ; - concatenated with I (columns + rows) ; - concatenate (all the required directional slices) ç€4 - call the last link (1) as a dyad for €ach with right argument = 4 F - flatten the result Ṁ - take the maximum ('Y'>'X'>'O') - this has the bonus effect of returning: 'Y' or 'X' for a winning board; and 'O' or '' for a (valid) game in progress. ``` [Answer] # [Python 2](https://docs.python.org/2/), 143 bytes ``` m=input() u=[r[::-1]for r in m] print"YX"[any(any('X'*4in''.join(t[i][j-i]for i in range(j+1))for j in range(6))for t in(m[::-1],m,u,u[::-1]))] ``` Takes a list of strings or a list of list of chars. Hard-coded for **6** rows by **7** columns, as the specification guarantees. **[Try it online!](https://tio.run/nexus/python2#VY1BCsMgEEX3OYW4UVtTCJQuAjlDtlMGF1m0ZQQnQXTR09tYKaEfBh5v@PwSJuItJ226PGHEcewH91yjiIJYBNdtkTjJO0hc@K3rKVCnK7FSF78S64Tk0Pf0bVFtxYVfD@3PgzHV@cPdmkm70aFt2WCzzY2NcaWgnFuk/SPYAZqD4ws/ghlAug8)** [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 45 bytes ``` {"YX"@|//{&/'(x;+x),x@'/:|:\!4}''+'4'4''~2!x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6pWioxQcqjR169W01fXqLDWrtDUqXBQ17eqsYpRNKlVV9dWNwFC9TojxYpaLq5iKyVrpRglfwiwxkZHQOgICB0RCQRKXGkKxbg1R4K1AfmRUBpkBpCOAOr2jyCgOQLGj4CJRyC5hJDmCIKaAcdDUV4=) Takes a matrix of characters and returns one of X or Y. If simplified I/O is allowed (0, 1, 2 for X, O, Y for input and boolean for output), I can remove `2!` from preprocessing and `"YX"@` from postprocessing, giving **38 bytes**. ### How it works ``` {"YX"@|//{&/'(x;+x),x@'/:|:\!4}''+'4'4''~2!x} x: matrix of chars ~2!x for each char, convert X to 1 and O/Y to 0 +'4'4'' extract all 4x4 sub-matrices using size-4 windows {...}'' for each submatrix... |:\!4 (0 1 2 3;3 2 1 0) x@'/: for each row of above, extract one element from each row of x which gives the diagonal and the antidiagonal of x (x;+x), prepend x and transpose of x &/' reduce each by boolean AND x -> vertical test, +x -> horizontal test |// repeat reducing by boolean OR until only one value remains "YX"@ convert 1 to X and 0 to Y ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` UŒD;ŒD;Z;ṡ€4;/ṢEÞṪṪ ``` [Try it online!](https://tio.run/nexus/jelly#@x96dJKLNQhHWT/cufBR0xoTa/2HOxe5Hp73cOcqIPr//3@0UmREZGSEv7@SDpeCUkRkREQkjA1kwtiRQCVwNUBhoAScDZRQigUA "Jelly – TIO Nexus") The core of this answer is copied from [my answer to this very similar question](https://codegolf.stackexchange.com/a/112362/62131). ## Explanation ``` UŒD;ŒD;Z;ṡ€4;/ṢEÞṪṪ ; ; ; Append {the input} and the following three values: UŒD the antidiagonals of {the input}; ŒD the diagonals of {the input}; Z the transposed {input}. ṡ 4 Find all length-4 substrings € of each subarray within that. ;/ Flatten one level. Þ Sort, with the following sort order: E If all elements are the same, sort later. Ṣ Tiebreak via lexicographical order. ṪṪ Take the last element of the last element. ``` Fairly simple: we take all rows, columns, diagonals, and antidiagonals (just as in the n-queens validator), then take all length-4 substrings of those, then sort them in such a way that the winning line of 4 sorts to the end. (We need the tiebreak in case there's an `OOOO` in addition to the `XXXX` or `YYYY`.) Take the last element of the last element, and that'll be `X` or `Y` as required. [Answer] # PHP, 71 Bytes ``` echo preg_match('#X(XXX|(.{8}X){3}|(.{7}X){3}|(.{9}X){3})#',$argn)?X:Y; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/6ec61d461581b06d0369684b3c8be380a3382740) [Answer] # [Python 2](https://docs.python.org/2/), ~~201~~ ~~143~~ ~~129~~ ~~128~~ 107 Bytes I decided to add horizontal, vertical, and diagonal together into one list and then add increment then look for X for times in it. And since there will always be a winner, I can assume Y won if X doesn't. This codes takes a matrix of all the different pieces and empty places. ``` lambda m:"YX"[any("X"*4in"".join(a)for a in zip(*m)+m+zip(*["0"*(7-i)+m[i]+"00"*i+m[i]for i in range(6)]))] ``` [Try it online!](https://tio.run/##PYvNCsIwEIRfJexpt1UpIgqCz@A1EnOI@Le22YRSD/XlY9Kic/q@YSaOwzPIOrWHc@qcv1yd8ns4aTBORgQN1YYFYPUKLOjoHnrlFIv6cMTKU@3riQw0UOFuybkxbGtosvPE5cLl0jt53HBLlsim2LMMqkWW@B6QKBk4zoFFIZ0zkS4yd0V@9N/lJdgv "Python 2 – Try It Online") Credits * From 129 to 107 bytes by [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ ~~65~~ ~~58~~ 54 bytes I just check if X is the winner, as `There will always be one winner, and only one winner`. Thanks to [edc65](https://codegolf.stackexchange.com/a/117207/80745). Input is a string with `no dividing character`. Thanks to [Arnauld](https://codegolf.stackexchange.com/a/117199/80745). ``` param($b)'YX'[1-in(0,5,6,7|%{$b-match"X(.{$_}X){3}"})] ``` [Try it online!](https://tio.run/##fVBfC8IgEH/3U8hwqeCiiAqCoG/Q60lEbGUsWLXWosD52dfpqpeoEz3u9@dOrjzfTXXNTVG0bE/n1LZlWqVHwTLJNfDVMDmcxECN1URNm9iyLDmm9TaPQPQt2ziQduQiJ9etI2QhCFGCA1d8@Te0Di9gLLn86wkarw0enwC/FTwaPQFAFfbSQexlGjEPYoGlT585@nuO/p1//i1ooMvQXfAHp6GHSNrQmFpCMZh5lGZbm52iLDun1Q6XzDYdVZnrragR6OHuOzYQERMvLjGXTwM5ezsi4ton "PowerShell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~105~~ ~~90~~ ~~81~~ 80 bytes Regex based. Lines are space separated. Saved 9 bytes thanks to @Lynn. Saved 1 byte by utilizing the fact that there is a guaranteed match. So if there's no win for X then there must be a win for Y. ``` lambda x:re.findall('X(XXX'+'|(.{%d}X){3}'*3%(6,7,8)+')',x)and'X'or'Y' import re ``` [Try it online!](https://tio.run/##jZDNCoMwEITvfYpcyiateBHaUvAZvM5CLxaVClYleLC0Prtdk/4dpJjLF7LMZGbbW3dp6mgs4tNYpddzlqr@aPOwKOssrSpN0ABoSw8d3tfZAHOPBtpEa70L9sHBbMlQ0Ju0zgjUWGJalde2sZ2y@djasu50oSnxR80RnvAEyyGj4liJl1ktsvBkdmTJi@RlgSUWTiBkeIuJYMxZuNEkkV/YSyeNktCuAFx@z2@K/0X4U@D9zu@5XJZb4GUB5bcqhOwz@SkyPgE "Python 3 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), ~~207 ...~~ 158 bytes *Version history: 4 iterations for ~25 bytes first week; then 3 more iterations for ~25 bytes 6 months later, 1 more for 1 byte 11 months later.* ``` t(){a=($^a-$^@_);for s l (${w:^^argv}){s+=$l;i=;repeat $#s a[++i]+=$s[i+1];}} w=(+) t $@ for s;w[++j]=${(l:j:)}_ t $@ t ${(Oa)@} [[ $a = *XXXX* ]]&&<<<X||<<<Y ``` ~~([first](https://tio.run/##hVFdb5swFH33r7gCmkARadpHAlM2bX3loS9Y09o6wQRL1EYGgjbk355dQ1OtH9uuhI449557ju1fbXUaKlFz0JwVUAvJN1Aowo@shpZ3EEXgeJZ2CN9XCiIJzl2l@rqAHQfvOgaHtJUou1PnB2OpNLRQg@@N3jjE9/dMH47GBG2YevViYdu@L9L1RoRh4rntJgjYd/EDuy3CxpAh9cOAsBQXbK8urh5MQDrwtjPDkImQebsGtwwoTx8bLWRXwoU3CtM@vlHCvGv0MxZsDUmSxIb0Rgfbxondyxzr0sQhNXGUm5MLd3ut6hqvY5DQKfjKd/0BpiOqJw5PSnMQslQx2bMOPi1uIEngW3ZLviimi5ig1a11iuYin7VmP59pZkg6F7EKDLNMX9WS9NLePwNBCiX5KYdsrn8gpRNSe5IMXJtnZ7PANfm7fBpGpPkst5jT/E/5DaEzbcdxO51ldh4o0hOPv0hMOLuvVivUvbOlL2nPPD337T73o6jTaP6smfr5hHmGWTAq@mCeNX4vuLZx1ut3/Bmn4w0C31fzrtcSchAlDJo1jZAHEK1c4u3v96qXHS/ss39g8j@zyaSsRdPgiiPXrVASVAlsp46c/AY "Zsh – Try It Online")) ([second](https://tio.run/##hVHRbpswFH33V1wBTaCIlPaRwJRNW1/z0Besql2dYIIlakeGBG3I355em6ba1m67Ejri3HvuObZ/ds1paETLQXNWQSskX0KlCD@yFjreQ5KAF1jaI3zbKEgkeHeNOrQVbDgE1xl4pGtE3Z/6MBprpaGDFsJgDMYhe3xkenc0JuriImhnM9sOQ1GkSxHHeeB3yyhi9@IBux3C0pChCOOIsAIXrK4urr6biPQQrCaGIZMggwuIc1oO93EsHoqnvRayr@EiGIXpnv6QwLRkDNcsWhmS57lNF4weto2X@Zcl1qXJYmqypDQnH@62WrUt3sMgoVfwlW8OO3CO6pnDs9IchKxVRrash0@zG8hz@La@JV8U01VG0OrWOiVTkc9asx@vNDOkmIpYBYaZF7/VnBykvXgGglRK8lMJ66n@gZQ6pPYka/Btno3NAtfk73I3jEjLSW6xpOWv8htCJ9qO43Y6yew8UKQdj79IOJzcF4sF6t7Z0re0Z56e@3af/1FUN1q@aly/dFiuMQtGRR/Mk@L3hqmNk6bv@DO64w0C31fz/qAllCBqGDTb74XcgejkHG9/u1UH2fPKPvsHJv8zcyZ1K/Z7XHHkuhNKgqqBbdSRkxc "Zsh – Try It Online")) ([third](https://tio.run/##hVJdb9owFH33r7gKKSRFodDHfExs2vrKQ19sVe1qEgcspTZyAtGG8tvZtUOqdqWbETrKufecc33l3/X21G5lJcAIXkAllUig0EQceAW1aCCKwPMt7RGRbzVECrz7rd5XBawF@IsYPFJvZdmcmiA8ltpADRUE/rGNn5642Ry6sJ5mfjUe21oQyGyeyOk09Ud1Eob8QT5itUZIOtJmwTQkPEP18ubq5mcXkgb8Zc9wZCJkZLYgLiZpH9DoMXveGamaEq78o@zq578k0JscgxUPlx1J09Q/2p@H5c6LR9cUz3UXT1kXR7Q7jeA@N7qqcAmtgkbDd7Heb8Al6hcBL9oIkKrUMcl5A1/Gt5Cm8GN1R75pboqYYNSdTYr6Q74aw3@dad6RrD/EKnCYSfbuTMhe2a1zkKTQSpworPrzD2TMIbM3WcHIzrO2s8CCfC53zYiM9nKLlNG38lvCetq2ozvrZbYfGNKOx08kHPbps9kMdR9i2eu0A8@GuvUbXRrVtdKzxtWpQ7rCWajT0KGXDlo6eNBL13bXo1BIviH0TRd950I/WdpZbcRBmFr0LszuZI7/V5zblcznH/gBnUsr8Y0Z0eyNQkdZQmv4bifVBmStJvgC8lzvVSMK@/QuhPwvzIWUldzt0MKOK7UCXQJf64MgfwA "Zsh – Try It Online")) ([fourth](https://tio.run/##hVLRbtowFH33V1wlKSSNQqGPIZnYtPWVh77YqtrVEAcspTZyAtGG8u3s2iFVu9LNCB3l3HvOub7y73p7areyEmAEL6CSSsyh0EQceAW1aCBJwAss7RGx3mpIFHj3W72vClgJCGYpeKTeyrI5NWFUagM1VBAGxzZ9euJmc@iiOs6DajSytTCU@XQu4zgL/HoeRfxBPmK1RiBtHsYR4TlqFzdXNz@7iDQQLHqGI5MgI/MZcSHz9gFtHvPnnZGqKeEqOMqufv5LAr3JMVzyaNGRLMuCo/15WO681L@meK67NGZdmtDu5MP92uiqwg20ChoN38VqvwGXqF8EvGgjQKpSp2TNG/gyuoUsgx/LO/JNc1OkBKPubFLSH/LVGP7rTPOO5P0hVoHDjPN3Z0z2yq6cgySFVuJEYdmffyBjDpm9yRJ8O8/KzgIz8rncNSMy2sstUkbfym8J62nbju6sl9l@YEg7Hj@RcNinTyYT1H2IZa/TDjwb6tbPvzSqa6VnjatTh3SJs1CnoUMvHbR08KCXru2uR6GQfEPomy76zoV@srSz2oiDMLXoXZjdyRT/rzi1K5lOP/ADOpdW4hszotkbhY6yhNbw3U6qDchajfEFrNd6rxpR2Kd3IeR/YS6krORuhxZ2XKkV6BL4Sh8E@QM "Zsh – Try It Online")) ([fifth](https://tio.run/##hVJNb@IwFLz7VzxBCkkjaOgRkhUr7VbaE4debCG6NcQBV6kdOQnRbstvZ58dUvWDdp@UjDx@M/Ns@W@5OzY7mQswgqeQSyVmkGoi9jyHUlQwGkHPs3SPiM1Ow0hB73an6zyFtQBvMoUeKXcyq46VH2TaQAk5@N5TM72742a7PwRlmHj5YGD3fF8m0UyGYez1y1kQ8KVc4W6JQJrEDwPCE9TOry6ufh8CUoE3bxmOzAgZFzBrlmH4sEruCyNVlcGFt5zgurx/J4DW4slf8GB@IMsleBwSuKRYl7BaDQZxHNPnZ/yzYx9uN0bnOR6@UVBp@CHW9RZcoH4U8KiNAKkyPSUbXsG3wTXEMfxc3JBfqqirKcGcGxszaot8N4b/OdH8QJK2iFVg4DB5U0NSK3vbHCQ8kFQrcaSwaOsLZMwhsydaQN9OtNbcpDAhn8tdMyKjrdwiZfS1/Jqwlrbt6M5ame0HhrTjcYmEwzZ9PB6j7kMse5m241m3b/3650Z1rfSkcfvUIV3gLNRpaNdLOy3tPOi5Y7vjUUgl3xL6qou@caGfXNpJbcRemFK0LszeSYTfC0b2SqLoA9@hc2kkvjIjqtoodJQZNIYXhVRbkKUa4hvYbHStKpHax3cm5H9hLiTLZVGghR1XagU6A77We0H@AQ "Zsh – Try It Online")) ([sixth](https://tio.run/##hVLBbuIwEL37K0aQhaQRNO0xJBWVdivtiUMvthCtDHHAKLWRkxDtUr6dHTukard0dyR4ypt582ZG/l1uTs1GFgKM4BkUUokJZJqIPS@gFBWMRtDzLN0jYrXRMFLQe9zoushgKcC7iaFHyo3Mq1PlB7k2UEIBvndo4qcnbtb7Y1CGqVcMBjbn@zKNJjIME69fToKAz@UCsyUCaVI/DAhPUTu9/nb9fAxIBd60ZTgyI2ScwaSZh@F2kXoHv4i3cXB8/qsSWu3Bn/FgeiTzOXgcUriiGFewWAwGSZLQ11f8Z6c@PK6MLgrculFQafgulvUanJN@EfCijQCpch2TFa/gbnALSQI/Zg/kp9rVVUzQ58HajNog98bwX2eaH0naBrEKNBymH2JIamXPzEHClmRaiROFWRv/QMYcMrvRDPp2oqXmJoMb8rXcFSMy2sotUkbfy28Ja2lbjt1ZK7P1wJB2PH4i4bB1H4/HqPtky96m7XjW5W2//qVRXSk9a1yeOqQznIU6De1qaaelXQ96aW23HoVM8jWh76rohy70i6Od1UbshSlF24XZm0T4e8PIniSKPvEdui6NxFdmRFUbhR1lDo3hu51Ua5ClGuIbWK10rSqR2cd3weR/Zs4kL@Ruhy3suFIr0Dnwpd4L8gc "Zsh – Try It Online")) ([seventh](https://tio.run/##hVJNa@MwEL3rVwyJcewah7RHfyxZ2C3sKYdeJEJSFFtOFFQpyHbMbprfnpXkuLQ03R2wHp6Z996M0J96d@l2XDDQjJYguGQplAqxIxVQswbiGEaeTY8QK3YKYgmjp51qRQkbBt59AiNU73jVXJogPNE88NY09tbz5zCtlIYaBATeqUvWa6q3x3NYR7knfN/WgoDns5RHUeaN6zQM6ZKvTLU2kJ5RlwdRiBrw5sgJpd0yivar3DsFItkn4fm5L5rjFCxoOD@j5RI8CjncYRN3sFr5fpZl@PXVnOQyhqdCKyHMep2ERsEPtmm34MTVC4MXpRlwWakEFbSBb/4DZBn8XDyiX/LQNgkyPo/WJu4Dfdea/r6m6RnlfSDLMIaT/ENMUCvtfVLgsEelkuyCYdHHP5AQh8RutICxnWijqC7hHn1Nd80GCe7pFjHB7@kPiPRp227USU@z/UBM2uXNr0k47N2n06nhfbIlb9MOeTLUrd741qiuFV85ro4d4oWZBTsOHnrxwMWDBr61tlsPQ8npFuF3XfiDCv7i0q5szY5M16xXIfZOZuZ7w5m9ktnsU35Ap9Jx88o0a1otjSKvoNP0cOByC7yWE/MGikK1smGlfXw3TP5n5kwqwQ8HI2HH5UqCqoBu1JGhvw "Zsh – Try It Online"))~~ ([eigth](https://tio.run/##hVLBbuIwEL37K0YQQVIEgh4TUlFpt9KeOPRiC0FliANGqR05CdEuzbezY4dUrUp3R4qfMjPvvRnLf4rDpT7ITIARPIFMKhFBook48QwKUcJ4DD3PpntE7A4axgp6zwddZQlsBXizEHqkOMi0vJR@cOax72342NssXoIo1QYKyMD3znW42XCzPzXBuRjFXhbJODIiF7wEr18AX41Gco2FYiVHs3XUNKSO/VFAsLwgTieqsee4jr2zn4XHMGhe2iIeZ3/Jg0VDVivwOMRwRzHuYL0eDObzOX17w5Nd@vC8MzrLcLtaQanhh9hWe3Di@lXAqzYCpEp1SHY41sPgHuZz@Ll8Ir9UXpUhQZ8nazNugzwaw39f07whcRvEMtBwGH@KIamUvU4OEo4k0UpcKCzb@Acy5pDZjZbQtxNtNTcJzMj3dNeMyGhLt0gZ/Ui/J6xN23ZUZy3N9gPDtMvjLyYctu6TyQR5X2zZ@7RdnnV1q9e/NaprpVeOq1OHdImzUMehXS/tuLTToLfWdutRSCTfE/qhi35Sod9c2pVtxEmYQrQqzN7JFL93nNormU6/5Dt0KrXEV2ZEWRmFijKF2vA8l2oPslBDfAO7na5UKRL7@G6Y/M/MmaSZzHOUsONKrUCnwLf6JMhf "Zsh – Try It Online")) In the footer, I print both the input board and the array we build from it to stderr. Scroll down to debug to see them. The array we build is a lot longer now, since `t` does a cartesian product with input board on *every* call. (Hey, it shortened the code by a few bytes.) There's a lot to cover here, so I moved the (sixth edition) comments to [an annotated gist](https://gist.github.com/xPMo/e549b802c408e0b8e93cacecb3c5ed9b). (tl;dr: concatenate transpositions of the original array, but make sure to keep them separated) [Answer] # [Ruby](https://www.ruby-lang.org/), 84 bytes Takes the board as a single continuous string with no separators. Finds a non-O character that's in a connect-4 and returns it. ``` ->b{b[(0..41).find{|i|b[i]!=?O&&[1,6,7,8].any?{|j|(1..3).all?{|n|b[i+j*n]==b[i]}}}]} ``` [Try it online!](https://tio.run/##fY9NboMwEEb3nMKVIn5SahUlaruhHIHtjKgVBQUSImRVAVQh4Ox07ClZhc7m2Z439udbl/dzGX/NL5/5kGf@q5T7KJBlpU/DWI15VqmnOEldN4vCt/A9/FDyqPtkGK@jH0m5C@Sxrmmrjfp83WoVx2ZomiY1zT@Xqi7EuWgbR3x3bSPKbHOQ7c33hBd6XqCcQp/mlEs8IjCBCUjl/OczES0RqNJV33aJCOwbAoJjafo0j@wZQdDbNgfYGMyH9@M9x3KOS58WKz78@SD420SgD6ewkh/5PrS@CWJJWX8B "Ruby – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~58 55~~ 56 bytes ``` {"XY"@|/&/'88<x ./:/:,/{x+/:/:+3+[4#1-+!3 3;]\&4}'+!6 7} ``` [Try it online!](https://tio.run/##jY5NDoIwEIX3nqJUA5qKjYEoaV14A7YzARLcYAwGE8ICgnh1bAuYuPBnNt/0dd7My93iXPR9JloKSI93bnMnCA412XDBxZq3NdMN81jkz7cuszziySS2/c5h1o7su74S7SJqHqXISC3TWy6XaXa6XGUtG1mukm5WRZTQmIZDkc9ENERQFVJJgSa/zGZUEWEwawLCu9mIelhtxsGkpwkq2ejqqQTD4TJ@uYyvuJOO079q/jHDaNYMwRBClWyM3T8B "K (ngn/k) – Try It Online") `{` `}` function with argument `x` `+!6 7` all possible pairs of 0..5 and 0..6 `{` `}'` for each of them do `4#1-+!3 3` are 4 of the 8 ortho-diagonal directions: `(1 1;1 0;1 -1;0 1)` `3+[` `]\&4` start with a list of four zeroes (`&4`) and make 3 steps in each of the directions `x+/:/:` start from each possible position and take the steps in each possible direction `,/` concatenate. at this point we have a matrix of 4-lists of coordinate pairs, some of them extending beyond the board `x ./:/:` look up the corresponding cells from `x` `88<` which of them are `"Y"`-s? (88 is the ascii code of `"X"`) `&/'` which 4-lists consist only of `"Y"`-s? (and-reduce-each) `|/` is there at least one such? (or-reduce) `"XY"@` if false return `"X"`, if true return `"Y"` [Answer] # [J](http://jsoftware.com/), 42 bytes ``` 1 e.[:,4 4(*/"1@,|:,,{~3 0+3 5*/i.@4);._3] ``` [Try it online!](https://tio.run/##jZAxb8IwEIV3/4onhiZOzeGQdHGJFFGpEyJSJ59Q1KEKKl06lA3EXw9nu1RMUEv2Zz@/dz75a5xQtkXjkMHAwsmcEl7eVq9jiYE2ztSo82I2KVtzdMYcThXsY4WnYrajttbP9F71o1brJSE4@@BatBZlLhsny5G07pNP7YefPRrC8PH53eYNNg5bZJ3n7GFHYplrVSKapBWrujRukDmSvYxO/S8dvUL2KR3o2UvaXqWjGtxSm1Mq2BWLHHU5ihCZ3ra33ua/ji86X@5D1Tudx5D/TQd2PtLL1wn1eAY "J – Try It Online") Takes input as a matrix of integers where 0 is blank, 1 is X, and 2 is Y. Returns 1 if X wins, 0 if Y wins. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~29~~ ~~26~~ 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` í‚εεÐм«NFÁ]€ø`IIø)J»γ4ùSà ``` Input as a character-matrix. Uses the legacy version for -1 byte, since min/max also works on characters. In the new version of 05AB1E, the trailing `à` (maximum) should have been `{θ` instead (sort, keep last item). [Try it online](https://tio.run/##MzBNTDJM/f//8NpHDbPObT239fCEC3sOrfZzO9wY@6hpzeEdCZ6eh3doeh3afW6zyeGdwYcX/P8fHa0UqaSjoBQBIiLhBJjrDyFidRSikeQjUJVjKIrAYhyyokgsNkXgNikSC4FHEbJxsbEA) or [verify all test cases](https://tio.run/##MzBNTDJM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU2nLpeSYXFKamIMQO7Tt0MJHTWuCXQ6tBMr6l5ZAxO2V/h9e@6hh1rmt57YennBhz6HVfm6HG2OBKg/vSDi07tC6wzs0vQ7tPrfZ5PDO4MML/ivphQGNsv8freQPATF5eBmRkRBGZAQQ@CvpKODTB1YDYkRGQPWBGBGRESB9YCZYFdCsSKjySDAjEigDkQIKAIUgDNz2RSKcB5eKhKsBsvDpi4DpAzP8IyCMCH@gmyKUYgE). **Explanation:** ``` í # Reverse each row of the (implicit) input-list ‚ # Pair it with the (implicit) input-list ε # Map over both matrices: ε # Map over each row: Ð # Triplicate the current row м # Remove all these characters, leaving a list of empty strings of the # same size as the row « # Merge this list of empty strings to the row NF # Loop the (0-based) row-index amount of times: Á # And rotate the row with appended empty strings towards the right ] # Close the nested maps and inner loop € # For both mapped matrices: ø # Zip/transpose; swapping rows/columns # (we now have a list of all diagonals and anti-diagonals) ` # Push both lists of lists separated to the stack I # Push the input again Iø # And push the input, zipped/transposed ) # Wrap everyone on the stack into a list # (we now have a list of all diagonals, anti-diagonals, rows, and columns) J # Join each inner-most list of characters together to a string » # Join each inner list together to a string; and then join these strings # with newline delimiter γ # Split everything into parts with equal adjacent characters 4ù # Only keep the parts of length 4 S # Flatten it to a list of characters à # And get the maximum character of this list # (after which it is output implicitly as result) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~114~~ 112 bytes Using a [bitboard approach](https://stackoverflow.com/questions/7044670/how-to-determine-game-end-in-tic-tac-toe/7046415#7046415) to check for 4 in a row. Input: a 2D list of integers, where `0` represents empty cell, `1` is `X`, and `2` is `Y`. Output: a positive integer if X wins, or `0` if Y wins. ``` lambda L:(b:=sum(sum(zip(*(L+[[0]*7])),())[i]%2<<i for i in range(49)))*any((r:=b&b<<i)&r<<i*2for i in(1,6,7,8)) ``` [Try it online!](https://tio.run/##dU5BTsMwELz7FSshGm/IoS2oLVb7g0q5cLAVIuS0DrWUupGbUgLi7cF2CFzISvbYszM7W7fN4WTuV7XtStjAc1fJY7GXsGW0YJvz5Uj9@dA1jen2LsumebzMEROKmOn8dr5eayhPFjRoA1aaV0UfHhExlqal1LJNMSmcBifW3fF8kNJZskiWyQqxux50peDJXhQjcHY7ZNlnlEZsmkQ8YrMkEhGbf2W7POTsfI429aWh2DMvf8kLzAnUVpuGlvSMSAYl3IB6b6wEo65QaaNAlo2yoN6UbaE4Sbvv0r7IOAoRUHBXKRkVhrZDwXuDRy446R9e4CaIXugVRDg68O7riID/J4jfVQZeDH0/aMTAfwweUx6Qp24D/g0 "Python 3.8 (pre-release) – Try It Online") ## Explanation The bitboard's layout is as follow (the missing positions in the last row is padded with 0): ``` 0 8 16 24 32 40 48 1 9 17 25 33 41 49 2 10 18 26 34 42 50 3 11 19 27 35 43 51 4 12 20 28 36 44 52 5 13 21 29 37 45 53 6 14 22 30 38 46 54 ``` This is the core of the function: given the bitboard `b` representing X's occupancies, check if X is winning: ``` any( # shift the board by i, 2i, 3i, 4i and and all of them together # if there's a set bit in the result (aka result != 0), then there is a 4-in-a-row (r:=b&b<<i)&r<<i*2 # do this for all 4 directions # 1: vertical, 7: horizontal, 6 and 8: diagonal for i in(1,6,7,8) ) ``` This part contructs the bitboard `b` for X: ``` b:=sum( sum(zip(* (L+[[0]*7]) # append a row of 0 at the bottom of L ),()) # flatten L into a list, with the index correspond # to the correct position in the bitboard layout [i]%2<<i # set the ith bit to 1 if the new list has X (=1) at that index for i in range(49) ) # sum all the set bits together to create the bitboard ``` ]
[Question] [ Lagrange's four square theorem tells us any natural number can be represented as the sum of four square numbers. Your task is to write a program that does this. Input: A natural number (below 1 billion) Output: Four numbers whose squares sum to that number (order doesn't matter) Note: You don't have to do a brute force search! Details [here](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem#Algorithms) and [here](https://web.archive.org/web/20040405113026/http://www.schorn.ch/howto.html). If there is a function that trivializes this problem (I will determine), it's not allowed. Automated prime functions and square root are allowed. If there is more than one representation any one is fine. If you chose to do brute force, it must run within reasonable time (3 minutes) sample input ``` 123456789 ``` sample output (either is fine) ``` 10601 3328 2 0 10601 3328 2 ``` [Answer] # FRACTRAN: 156 98 fractions Since this is a classic number theory problem, what better way to solve this than to use numbers! ``` 37789/221 905293/11063 1961/533 2279/481 57293/16211 2279/611 53/559 1961/403 53/299 13/53 1/13 6557/262727 6059/284321 67/4307 67/4661 6059/3599 59/83 1/59 14279/871933 131/9701 102037079/8633 14017/673819 7729/10057 128886839/8989 13493/757301 7729/11303 89/131 1/89 31133/2603 542249/19043 2483/22879 561731/20413 2483/23701 581213/20687 2483/24523 587707/21509 2483/24797 137/191 1/137 6215941/579 6730777/965 7232447/1351 7947497/2123 193/227 31373/193 23533/37327 5401639/458 229/233 21449/229 55973/24823 55973/25787 6705901/52961 7145447/55973 251/269 24119/251 72217/27913 283/73903 281/283 293/281 293/28997 293/271 9320827/58307 9831643/75301 293/313 28213/293 103459/32651 347/104807 347/88631 337/347 349/337 349/33919 349/317 12566447/68753 13307053/107143 349/367 33197/349 135199/38419 389/137497 389/119113 389/100729 383/389 397/383 397/39911 397/373 1203/140141 2005/142523 2807/123467 4411/104411 802/94883 397/401 193/397 1227/47477 2045/47959 2863/50851 4499/53743 241/409 1/241 1/239 ``` Takes in input of the form 2n × 193 and outputs 3a × 5b × 7c × 11d. Might run in 3 minutes if you have a *really* good interpreter. Maybe. > > ...okay, not really. This seemed to be such a fun problem to do in FRACTRAN that I *had* to try it. Obviously, this isn't a proper solution to the question as it doesn't make the time requirements (it brute forces) and it's barely even golfed, but I thought I'd post this here because it's not every day that a Codegolf question can be done in FRACTRAN ;) > > > ## Hint The code is equivalent to the following pseudo-Python: ``` a, b, c, d = 0, 0, 0, 0 def square(n): # Returns n**2 def compare(a, b): # Returns (0, 0) if a==b, (1, 0) if a<b, (0, 1) if a>b def foursquare(a, b, c, d): # Returns square(a) + square(b) + square(c) + square(d) while compare(foursquare(a, b, c, d), n) != (0, 0): d += 1 if compare(c, d) == (1, 0): c += 1 d = 0 if compare(b, c) == (1, 0): b += 1 c = 0 d = 0 if compare(a, b) == (1, 0): a += 1 b = 0 c = 0 d = 0 ``` [Answer] # Mathematica ~~61 66~~ 51 Three methods are shown. Only the first approach meets the time requirement. --- ## 1-FindInstance (51 char) This returns a single solution the equation. ``` FindInstance[a^2 + b^2 + c^2 + d^2 == #, {a, b, c, d}, Integers] & ``` --- **Examples and timings** ``` FindInstance[a^2 + b^2 + c^2 + d^2 == 123456789, {a, b, c, d}, Integers] // AbsoluteTiming ``` > > {0.003584, {{a -> 2600, b -> 378, c -> 10468, d -> 2641}}} > > > ``` FindInstance[a^2 + b^2 + c^2 + d^2 == #, {a, b, c, d}, Integers] &[805306368] ``` --- > > {0.004437, {{a -> 16384, b -> 16384, c -> 16384, d -> 0}}} > > > --- ## 2-IntegerPartitions This works also, but is too slow to meet the speed requirement. ``` f@n_ := Sqrt@IntegerPartitions[n, {4}, Range[0, Floor@Sqrt@n]^2, 1][[1]] ``` `Range[0, Floor@Sqrt@n]^2` is the set of all squares less than the square root of `n` (the largest possible square in the partition). `{4}` requires the integer partitions of `n` consist of 4 elements from the above-mentioned set of squares. `1`, within the function `IntegerPartitions` returns the first solution. `[[1]]` removes the outer braces; the solution was returned as a set of one element. --- ``` f[123456] ``` > > {348, 44, 20, 4} > > > --- ## 3-PowerRepresentations [PowerRepresentations](http://reference.wolfram.com/mathematica/ref/SquaresR.html) returns **all** of the solutions to the 4 squares problem. It can also solve for sums of other powers. PowersRepresentations returns, in under 5 seconds, the 181 ways to express 123456789 as the sum of 4 squares: ``` n= 123456; PowersRepresentations[n, 4, 2] //AbsoluteTiming ``` ![sols](https://i.stack.imgur.com/DNkZh.png) However, it is far too slow for other sums. [Answer] ## Perl - ~~116 bytes~~ 87 bytes (see update below) ``` #!perl -p $.<<=1,$_>>=2until$_&3; {$n=$_;@a=map{$n-=$a*($a-=$_%($b=1|($a=0|sqrt$n)>>1));$_/=$b;$a*$.}($j++)x4;$n&&redo} $_="@a" ``` *Counting the shebang as one byte, newlines added for horizontal sanity.* Something of a combination [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") submission. The average (worst?) case complexity seems to be ~~*O(log n)*~~ *O(n0.07)*. Nothing I've found runs slower than 0.001s, and I've checked the entire range from *900000000 - 999999999*. If you find anything that takes significantly longer than that, ~0.1s or more, please let me know. --- **Sample Usage** ``` $ echo 123456789 | timeit perl four-squares.pl 11110 157 6 2 Elapsed Time: 0:00:00.000 $ echo 1879048192 | timeit perl four-squares.pl 32768 16384 16384 16384 Elapsed Time: 0:00:00.000 $ echo 999950883 | timeit perl four-squares.pl 31621 251 15 4 Elapsed Time: 0:00:00.000 ``` The final two of these seem to be worst case scenerios for other submissions. In both instances, the solution shown is quite literally the very first thing checked. For `123456789`, it's the second. If you want to test a range of values, you can use the following script: ``` use Time::HiRes qw(time); $t0 = time(); # enter a range, or comma separated list here for (1..1000000) { $t1 = time(); $initial = $_; $j = 0; $i = 1; $i<<=1,$_>>=2until$_&3; {$n=$_;@a=map{$n-=$a*($a-=$_%($b=1|($a=0|sqrt$n)>>1));$_/=$b;$a*$i}($j++)x4;$n&&redo} printf("%d: @a, %f\n", $initial, time()-$t1) } printf('total time: %f', time()-$t0); ``` Best when piped to a file. The range `1..1000000` takes about 14s on my computer (71000 values per second), and the range `999000000..1000000000` takes about 20s (50000 values per second), consistent with *O(log n)* average complexity. --- ## Update **Edit**: It turns out that this algorithm is very similar to one that has been used by mental calculators for [at least a century](http://www.myreckonings.com/Dead_Reckoning/Online/Materials/Sum%20of%20Four%20Squares.pdf). Since originally posting, I have checked every value on the range from *1..1000000000*. The 'worst case' behavior was exhibited by the value *699731569*, which tested a grand total of *190* combinations before arriving at a solution. If you consider *190* to be a small constant - and I certainly do - the worst case behavior on the required range can be considered *O(1)*. That is, as fast as looking up the solution from a giant table, and on average, quite possibly faster. Another thing though. After *190* iterations, anything larger than *144400* hasn't even made it beyond the first pass. The logic for the breadth-first traversal is worthless - it's not even used. The above code can be shortened quite a bit: ``` #!perl -p $.*=2,$_/=4until$_&3; @a=map{$=-=$%*($%=$=**.5-$_);$%*$.}$j++,(0)x3while$=&&=$_; $_="@a" ``` Which only performs the first pass of the search. We do need to confirm that there aren't any values below *144400* that needed the second pass, though: ``` for (1..144400) { $initial = $_; # reset defaults $.=1;$j=undef;$==60; $.*=2,$_/=4until$_&3; @a=map{$=-=$%*($%=$=**.5-$_);$%*$.}$j++,(0)x3while$=&&=$_; # make sure the answer is correct $t=0; $t+=$_*$_ for @a; $t == $initial or die("answer for $initial invalid: @a"); } ``` In short, for the range *1..1000000000*, a near-constant time solution exists, and you're looking at it. --- ## Updated Update [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) and I have made several improvements this algorithm. You can follow the progress in the comments below, and subsequent discussion, if that interests you. The average number of iterations for the required range has dropped from just over *4* down to *1.229*, and the time needed to test all values for *1..1000000000* has been improved from 18m 54s, down to 2m 41s. The worst case previously required *190* iterations; the worst case now, *854382778*, needs only *21*. The final Python code is the following: ``` from math import sqrt # the following two tables can, and should be pre-computed qqr_144 = set([ 0, 1, 2, 4, 5, 8, 9, 10, 13, 16, 17, 18, 20, 25, 26, 29, 32, 34, 36, 37, 40, 41, 45, 49, 50, 52, 53, 56, 58, 61, 64, 65, 68, 72, 73, 74, 77, 80, 81, 82, 85, 88, 89, 90, 97, 98, 100, 101, 104, 106, 109, 112, 113, 116, 117, 121, 122, 125, 128, 130, 133, 136, 137]) # 10kb, should fit entirely in L1 cache Db = [] for r in range(72): S = bytearray(144) for n in range(144): c = r while True: v = n - c * c if v%144 in qqr_144: break if r - c >= 12: c = r; break c -= 1 S[n] = r - c Db.append(S) qr_720 = set([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 145, 160, 169, 180, 196, 225, 241, 244, 256, 265, 289, 304, 324, 340, 361, 369, 385, 400, 409, 436, 441, 481, 484, 496, 505, 529, 544, 576, 580, 585, 601, 625, 640, 649, 676]) # 253kb, just barely fits in L2 of most modern processors Dc = [] for r in range(360): S = bytearray(720) for n in range(720): c = r while True: v = n - c * c if v%720 in qr_720: break if r - c >= 48: c = r; break c -= 1 S[n] = r - c Dc.append(S) def four_squares(n): k = 1 while not n&3: n >>= 2; k <<= 1 odd = n&1 n <<= odd a = int(sqrt(n)) n -= a * a while True: b = int(sqrt(n)) b -= Db[b%72][n%144] v = n - b * b c = int(sqrt(v)) c -= Dc[c%360][v%720] if c >= 0: v -= c * c d = int(sqrt(v)) if v == d * d: break n += (a<<1) - 1 a -= 1 if odd: if (a^b)&1: if (a^c)&1: b, c, d = d, b, c else: b, c = c, b a, b, c, d = (a+b)>>1, (a-b)>>1, (c+d)>>1, (c-d)>>1 a *= k; b *= k; c *= k; d *= k return a, b, c, d ``` This uses two pre-computed correction tables, one 10kb in size, the other 253kb. The code above includes the generator functions for these tables, although these should probably be computed at compile time. A version with more modestly sized correction tables can be found here: <http://codepad.org/1ebJC2OV> This version requires an average of *1.620* iterations per term, with a worst case of *38*, and the entire range runs in about 3m 21s. A little bit of time is made up for, by using bitwise `and` for *b* correction, rather than modulo. --- ### Improvements **Even values are more likely to produce a solution than odd values.** The mental calculation article linked to previously notes that if, after removing all factors of four, the value to be decomposed is even, this value can be divided by two, and the solution reconstructed: ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=%5Cfrac%7BN%7D%7B2%7D%3Da%5E2%2Bb%5E2%2Bc%5E2%2Bd%5E2%5Chspace%7B12pc%7D%5CRightarrow%5Chspace%7B12pc%7DN%3D%28a%2Bb%29%5E2%2B%28a-b%29%5E2%2B%28c%2Bd%29%5E2%2B%28c-d%29%5E2) Although this might make sense for mental calculation (smaller values tend to be easier to compute), it doesn't make much sense algorithmically. If you take *256* random *4*-tuples, and examine the sum of the squares modulo *8*, you will find that the values *1*, *3*, *5*, and *7* are each reached on average *32* times. However, the values *2* and *6* are each reached *48* times. Multiplying odd values by *2* will find a solution, on average, in *33%* less iterations. The reconstruction is the following: ![](https://chart.googleapis.com/chart?cht=tx&chf=bg,s,FFFFFF00&chl=N%3Da%5E2%2Bb%5E2%2Bc%5E2%2Bd%5E2%5Chspace%7B12pc%7D%5CRightarrow%5Chspace%7B12pc%7D%5Cfrac%7BN%7D%7B2%7D%3D%28%5Cfrac%7Ba%2Bb%7D%7B2%7D%29%5E2%2B%28%5Cfrac%7Ba-b%7D%7B2%7D%29%5E2%2B%28%5Cfrac%7Bc%2Bd%7D%7B2%7D%29%5E2%2B%28%5Cfrac%7Bc-d%7D%7B2%7D%29%5E2) Care needs to be taken that *a* and *b* have the same parity, as well as *c* and *d*, but if a solution was found at all, a proper ordering is guaranteed to exist. **Impossible paths don't need to be checked.** After selecting the second value, *b*, it may already be impossible for a solution to exist, given the possible quadratic residues for any given modulo. Instead of checking anyway, or moving onto the next iteration, the value of *b* can be 'corrected' by decrementing it by the smallest amount that could possibly lead to a solution. The two correction tables store these values, one for *b*, and the other for *c*. Using a higher modulo (more accurately, using a modulo with relatively fewer quadratic residues) will result in a better improvement. The value *a* doesn't need any correction; by modifying *n* to be even, all values of *a* are valid. [Answer] # Python 3 (177) ``` N=int(input()) k=1 while N%4<1:N//=4;k*=2 n=int(N**.5) R=range(int(2*n**.5)+1) print([(a*k,b*k,c*k,d*k)for d in R for c in R for b in R for a in[n,n-1]if a*a+b*b+c*c+d*d==N][0]) ``` After we reduce the input `N` to be not divisible by 4, it must be expressible as a sum of four squares where one of them is either the largest possible value `a=int(N**0.5)` or one less than that, leaving only a small remainder for sum of the three other squares to take care of. This greatly reduces the search space. Here's a proof later this code always finds a solution. We wish to find an `a` so that `n-a^2` is the sum of three squares. From [Legendre's Three-Square Theorem](http://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem), a number is the sum of three squares unless it is the form `4^j(8*k+7)`. In particular, such numbers are either 0 or 3 (modulo 4). We show that no two consecutive `a` can make the leftover amount `N-a^2` have such a shape for both consecutive values.. We can do so by simply making a table of `a` and `N` modulo 4, noting that `N%4!=0` because we've extracted all powers of 4 out of `N`. ``` a%4= 0123 +---- 1|1010 N%4= 2|2121 <- (N-a*a)%4 3|3232 ``` Because no two consecutive `a` give `(N-a*a)%4 in [0,3]`, one of them is safe to use. So, we greedily use the largest possible `n` with `n^2<=N`, and `n-1`. Since `N<(n+1)^2`, the remainder `N-a^2` to be represented as a sum of three squares is at most `(n+1)^2 -(n-1)^2`, which equals `4*n`. So, it suffices to check only values up to `2*sqrt(n)`, which is exactly the range `R`. One could further optimize running time by stopping after a single solution, computing rather than iterating for the last value `d`, and searching only among values `b<=c<=d`. But, even without these optimizations, the worst instance I could find finished in 45 seconds on my machine. The chain of "for x in R" is unfortunate. It can probably be shortened by string substitution or replacement by iterating over a single index that encodes (a,b,c,d). Importing itertools turned out not worth it. Edit: Changed to `int(2*n**.5)+1` from `2*int(n**.5)+2` to make argument cleaner, same character count. [Answer] # [CJam](http://sourceforge.net/p/cjam/wiki/Home/), ~~91~~ ~~90~~ ~~74~~ 71 bytes ``` q~{W):W;:N4md!}gmqi257:B_**_{;)_[Bmd\Bmd]_N\{_*-}/mq_i@+\1%}g{2W#*}%`\; ``` Compact, but slower than my other approach. [Try it online!](http://cjam.aditsu.net/ "CJam interpreter") Paste the *Code*, type the desired integer in *Input* and click *Run*. ### Background This post started as a [99 byte GolfScript answer](https://codegolf.stackexchange.com/revisions/28358/1). While there was still room for improvement, GolfScript lacks built-in sqrt function. I kept the GolfScript version until [revision 5](https://codegolf.stackexchange.com/revisions/28358/5), since it was very similar to the CJam version. However, the optimizations since revision 6 require operators that are not available in GolfScript, so instead of posting separate explanations for both languages, I decided to drop the less competitive (and much slower) version. The implemented algorithm computes the numbers by brute force: 1. For input `m`, find `N` and `W` such that `m = 4**W * N`. 2. Set `i = 257**2 * floor(sqrt(N/4))`. 3. Set `i = i + 1`. 4. Find integers `j, k, l` such that `i = 257**2 * j + 257 * k + l`, where `k, l < 257`. 5. Check if `d = N - j**2 - k**2 - l**2` is a perfect square. 6. If it isn't, and go back to step 3. 7. Print `2**W * j, 2**W * k, 2**W * l, 2**W * sqrt(m)`. ### Examples ``` $ TIME='\n%e s' time cjam lagrange.cjam <<< 999999999 [27385 103 15813 14] 0.46 s $ TIME='\n%e s' time cjam lagrange.cjam <<< 805306368 [16384 16384 0 16384] 0.23 s ``` Timings correspond to an Intel Core i7-4700MQ. ### How it works ``` q~ " Read and interpret the input. "; { W):W; " Increment “W” (initially -1). "; :N " Save the integer on the stack in “N”. '; 4md! " Push N / 4 and !(N % 4). "; }g " If N / 4 is an integer, repeat the loop. mqi " Compute floor(sqrt(N/4)). "; 257:B_** " Compute i = floor(sqrt(N)) * 257**2. "; _ " Duplicate “i” (dummy value). "; { " "; ;)_ " Pop and discard. Increment “i”. "; [Bmd\Bmd] " Push [ j k l ], where i = 257**2 * j + 257 * k + l and k, l < 257. "; _N\ " Push “N” and swap it with a copy of [ j k l ]. "; {_*-}/ " Compute m = N - j**2 - k**2 - l**2. "; mq " Compute sqrt(m). "; _i " Duplicate sqrt(m) and compute floor(sqrt(m)). "; @+\ " Form [ j k l floor(sqrt(m)) ] and swap it with sqrt(m). "; 1% " Check if sqrt(m) is an integer. "; }g " If it is, we have a solution; break the loop. "; {2W#*}% " Push 2**W * [ j k l sqrt(m) ]. "; `\; " Convert the array into a string and discard “i”. "; ``` [Answer] # C, 228 This is based on the algorithm on the Wikipedia page, which is an O(n) brute-force. ``` n,*l,x,y,i;main(){scanf("%d",&n);l=calloc(n+1,8); for(x=0;2*x*x<=n;x++)for(y=x;(i=x*x+y*y)<=n;y++)l[2*i]=x,l[2*i+1]=y; for(x=0,y=n;;x++,y--)if(!x|l[2*x+1]&&l[2*y+1]){ printf("%d %d %d %d\n",l[2*x],l[2*x+1],l[2*y],l[2*y+1]);break;}} ``` [Answer] # GolfScript, ~~133~~ ~~130~~ 129 bytes ``` ~{.[4*{4/..4%1$!|!}do])\}:r~,(2\?:f;{{..*}:^~4-1??n*,}:v~).. {;;(.^3$\-r;)8%!}do-1...{;;;)..252/@252%^@^@+4$\-v^@-}do 5$]{f*}%-4>` ``` Fast, but lengthy. The newline can be removed. [Try it online.](http://golfscript.apphb.com/?c=IjEyMzQ1Njc4OSIgIyBTaW11bGF0ZSBpbnB1dCBmcm9tIFNURElOLgoKfnsuWzQqezQvLi40JTEkIXwhfWRvXSlcfTpyfiwoMlw%2FOmY7e3suLip9Ol5%2BNC0xPz9uKix9OnZ%2BKS4uezs7KC5eMyRcLXI7KTglIX1kby0xLi4uezs7OykuLjI1Mi9AMjUyJV5AXkArNCRcLXZeQC19ZG8gNSRde2YqfSUtND5g "Web GolfScript") Note that the online interpreter has a 5 second time limit, so it might not work for all numbers. ### Background The algorithm takes advantage of [Legendre's three-square theorem](http://en.wikipedia.org/wiki/Lagrange%27s_three-square_theorem "Legendre's three-square theorem - Wikipedia, the free encyclopedia"), which states that every natural number *n* that is not of the form                                                                    ![n = 4**a * (8b + 7)](https://i.stack.imgur.com/h4K7B.png) can be expressed as the sum of **three** squares. The algorithm does the following: 1. Express the number as `4**i * j`. 2. Find the largest integer `k` such that `k**2 <= j` and `j - k**2` satisfies the hypothesis of Legendre's three-square theorem. 3. Set `i = 0`. 4. Check if `j - k**2 - (i / 252)**2 - (i % 252)**2` is a perfect square. 5. If it isn't, increment `i` and go back to step 4. ### Examples ``` $ TIME='%e s' time golfscript legendre.gs <<< 0 [0 0 0 0] 0.02 s $ TIME='%e s' time golfscript legendre.gs <<< 123456789 [32 0 38 11111] 0.02 s $ TIME='%e s' time golfscript legendre.gs <<< 999999999 [45 1 217 31622] 0.03 s $ TIME='%e s' time golfscript legendre.gs <<< 805306368 [16384 0 16384 16384] 0.02 s ``` Timings correspond to an Intel Core i7-4700MQ. ### How it works ``` ~ # Interpret the input string. Result: “n” { # . # Duplicate the topmost stack item. [ # 4* # Multiply it by four. { # 4/ # Divide by four. .. # Duplicate twice. 4%1$ # Compute the modulus and duplicate the number. !|! # Push 1 if both are truthy. }do # Repeat if the number is divisible by four and non-zero. ] # Collect the pushed values (one per iteration) into an array. )\ # Pop the last element from the array and swap it with the array. }:r~ # Save this code block as “r” and execute it. ,(2\? # Get the length of the array, decrement it and exponentiate. :f; # Save the result in “f”. # The topmost item on the stack is now “j”, which is not divisible by # four and satisfies that n = f**2 * j. { # {..*}:^~ # Save a code block to square a number in “^” and execute it. 4-1?? # Raise the previous number to the power of 1/4. # The two previous lines compute (x**2)**(1/4), which is sqrt(abs(x)). n*, # Repeat the string "\n" that many times and compute its length. # This casts to integer. (GolfScript doesn't officially support Rationals.) }:v~ # Save the above code block in “v” and execute it. ).. # Undo the first three instructions of the loop. { # ;;( # Discard two items from the stack and decrement. .^3$\- # Square and subtract from “n”. r;)8%! # Check if the result satisfies the hypothesis of the three-square theorem. }do # If it doesn't, repeat the loop. -1... # Push 0 (“i”) and undo the first four instructions of the loop. { # ;;;) # Discard two items from the stack and increment “i”. ..252/@252% # Push the digits of “i” in base 252. ^@^@+4$\- # Square both, add and subtract the result v^@- # Take square root, square and compare. }do # If the difference is a perfect square, break the loop. 5$] # Duplicate the difference an collect the entire stack into an array. {f*}% # Multiply very element of the array by “f”. -4> # Reduce the array to its four last elements (the four numbers). ` # Convert the result into a string. ``` [Answer] # CJam, 50 bytes ``` li:NmF0=~2/#:J(_{;)__*N\-[{_mqJ/iJ*__*@\-}3*])}g+p ``` My third (and final, I promise) answer. This approach is based heavily on [primo's answer](https://codegolf.stackexchange.com/a/28430). Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=li%3ANmF0%3D~2%2F%23%3AJ(_%7B%3B)__*N%5C-%5B%7B_mqJ%2FiJ*__*%40%5C-%7D3*%5D)%7Dg%2Bp&input=265289728). ### Usage ``` $ cjam 4squares.cjam <<< 999999999 [189 31617 567 90] ``` ### Background 1. After seeing primo's updated algorithm, I *had* to see how a CJam implementation would score: ``` li{W):W;:N4md!}g;Nmqi)_{;(__*N\-[{_mqi__*@\-}3*])}g+2W#f*p ``` Only 58 bytes! This algorithm is performs in nearly constant time and doesn't exhibit much variation for different values of `N`. Let's change that... 2. Instead of starting at `floor(sqrt(N))` and decrementing, we can start at `1` and increment. This saves 4 bytes. ``` li{W):W;:N4md!}g;0_{;)__*N\-[{_mqi__*@\-}3*])}g+2W#f*p ``` 3. Instead of expressing `N` as `4**a * b`, we can express it as `p**(2a) * b` – where `p` is the smallest prime factor of `N` – to save 1 more byte. ``` li_mF0=~2/#:J_*/:N!_{;)__*N\-[{_mqi__*@\-}3*])}g+Jf*p ``` 4. The previous modification allows us to slightly change the implementation (without touching the algorithm itself): Instead of dividing `N` by `p**(2a)` and multiply the solution by `p**a`, we can directly restrict the possible solutions to multiples of `p**a`. This saves 2 more bytes. ``` li:NmF0=~2/#:J!_{;J+__*N\-[{_mqJ/iJ*__*@\-}3*])}g+` ``` 5. Not restricting the first integer to multiples of `p**a` saves an additional byte. ``` li:NmF0=~2/#:J(_{;)__*N\-[{_mqJ/iJ*__*@\-}3*])}g+` ``` ### Final algorithm 1. Find `a` and `b` such that `N = p**(2a) * b`, where `b` is not a multiple of `p**2` and `p` is the smallest prime factor of `N`. 2. Set `j = p**a`. 3. Set `k = floor(sqrt(N - j**2) / A) * A`. 4. Set `l = floor(sqrt(N - j**2 - k**2) / A) * A`. 5. Set `m = floor(sqrt(N - j**2 - k**2 - l**2) / A) * A`. 6. If `N - j**2 - k**2 - l**2 - m**2 > 0`, set `j = j + 1` and go back to step 3. This can be implemented as follows: ``` li:N " Read an integer from STDIN and save it in “N”. "; mF " Push the factorization of “N”. Result: [ [ p1 a1 ] ... [ pn an ] ] "; 0=~ " Push “p1” and “a1”. “p1” is the smallest prime divisor of “N”. "; 2/#:J " Compute p1**(a1/2) and save the result “J”. "; (_ " Undo the first two instructions of the loop. "; { " "; ;)_ " Pop and discard. Increment “J” and duplicate. "; _*N\- " Compute N - J**2. "; [{ " "; _mqJ/iJ* " Compute K = floor(sqrt(N - J**2)/J)*J. "; __*@ " Duplicate, square and rotate. Result: K K**2 N - J**2 "; \- " Swap and subtract. Result: K N - J**2 - K**2 "; }3*] " Do the above three times and collect in an array. "; ) " Pop the array. Result: N - J**2 - K**2 - L**2 - M**2 "; }g " If the result is zero, break the loop. "; +p " Unshift “J” in [ K L M ] and print a string representation. "; ``` ### Benchmarks I've run all 5 versions over all positive integers up to 999,999,999 on my Intel Core i7-3770, measured execution time and counted the iterations required to find a solution. The following table shows the average number of iterations and execution time for a single integer: ``` Version | 1 | 2 | 3 | 4 | 5 ----------------------+---------+---------+---------+---------+--------- Number of iterations | 4.005 | 28.31 | 27.25 | 27.25 | 41.80 Execution time [µs] | 6.586 | 39.69 | 55.10 | 63.99 | 88.81 ``` 1. At only 4 iterations and 6.6 **micro**​seconds per integer, primo's algorithm is incredibly fast. 2. Starting at `floor(sqrt(N))` makes more sense, since this leaves us with smaller values for the sum of the remaining three squares. As expected, starting at 1 is a lot slower. 3. This is a classical example of a badly implemented good idea. To actually *reduce* the code size, we rely on `mF`, which factorizes the integer `N`. Although version 3 requires less iterations than version 2, it is a lot slower in practice. 4. Although the algorithm does not change, version 4 is a lot slower. This is because it performs an additional floating point division and an integer multiplication in each iteration. 5. For the input `N = p**(2a) ** b`, algorithm 5 will require `(k - 1) * p**a + 1` iterations, where `k` is the number of iterations algorithm 4 requires. If `k = 1` or `a = 0`, this makes no difference. However, any input of the form `4**a * (4**c * (8 * d + 7) + 1)` may perform quite badly. For the starting value `j = p**a`, `N - 4**a = 4**(a + c) * (8 * d + 7)`, so it cannot be expressed as a sum of three squares. Thus, `k > 1` and at least `p**a` iterations are required. Thankfully, primo's original algorithm is incredibly fast and `N < 1,000,000,000`. The worst case I could find by hand is `265,289,728 = 4**10 * (4**1 * (7 * 8 + 7) + 1)`, which requires 6,145 iterations. Execution time is less than 300 ms on my machine. On average, this version is 13.5 times slower than the implementation of primo's algorithm. [Answer] # Rev 1: C,190 ``` a,z,m;short s[15<<26];p(){m=s[a=z-a];printf("%d %f ",m,sqrt(a-m*m));} main(){m=31727;for(a=m*m;--a;s[z<m*m?z:m*m]=a%m)z=a/m*(a/m)+a%m*(a%m);scanf("%d",&z);for(;a*!s[a]||!s[z-a];a++);p();p();} ``` This is even more memory hungry than rev 0. Same principle: build a table with a positive value for all possible sums of 2 squares (and zero for those numbers which are not sums of two squares), then search it. In this rev use an array of `short` instead of `char` to store the hits, so I can store the root of one of the pair of squares in the table instead of just a flag. This simplifies function `p` (for decoding the sum of 2 squares) considerably as there is no need for a loop. Windows has a 2GB limit on arrays. I can get round that with `short s[15<<26]` which is an array of 1006632960 elements, enough to comply with the spec. Unfortunately, the total program runtime size is still over 2GB and (despite tweaking the OS settings) I have not been able to run over this size (though it is theoretically possible.) The best I can do is `short s[14<<26]` (939524096 elements.) `m*m` must be strictly less than this (30651^2=939483801.) Nevertheless, the program runs perfectly and should work on any OS that does not have this restriction. **Ungolfed code** ``` a,z,m; short s[15<<26]; p(){m=s[a=z-a];printf("%d %f ",m,sqrt(a-m*m));} main(){ m=31727; for(a=m*m;--a;s[z<m*m?z:m*m]=a%m) //assignment to s[] moved inside for() is executed after the following statement. In this rev excessively large values are thrown away to s[m*m]. z=a/m*(a/m)+a%m*(a%m); //split a into high and low half, calculate h^2+l^2. scanf("%d",&z); for(;a*!s[a]||!s[z-a];a++); //loop until s[a] and s[z-a] both contain an entry. s[0] requires special handling as s[0]==0, therefore a* is included to break out of the loop when a=0 and s[z] contains the sum of 2 squares. p(); //print the squares for the first sum of 2 squares p();} //print the squares for the 2nd sum of 2 squares (every time p() is called it does a=z-a so the two sums are exchanged.) ``` # Rev 0 C,219 ``` a,z,i,m;double t;char s[1<<30];p(){for(i=t=.1;(m=t)-t;i++)t=sqrt(a-i*i);printf("%d %f ",i-1,t);} main(){m=1<<15;for(a=m*m;--a;){z=a/m*(a/m)+a%m*(a%m);s[z<m*m?z:0]=1;}scanf("%d",&z);for(;1-s[a]*s[z-a];a++);p();a=z-a;p();} ``` This is a memory hungry beast. It takes a 1GB array, calculates all possible sums of 2 squares and stores a flag for each in the array. Then for the user input z, it searches the array for two sums of 2 squares a and z-a. the function `p` then reconsitutes the original squares that were used to make the sums of 2 squares `a` and `z-a` and prints them, the first of each pair as an integer, the second as a double (if it *has* to be all integers two more characters are needed,`t` > `m=t`.) The program takes a couple of minutes to build the table of sums of squares (I think this is due to memory management issues, I see the memory allocation going up slowly instead of jumping up as one might expect.) However once that is done it produces answers very quickly (if several numbers are to be calculated, the program from `scanf` onward can be put in a loop. **ungolfed code** ``` a,z,i,m; double t; char s[1<<30]; //handle numbers 0 up to 1073741823 p(){ for(i=t=.1;(m=t)-t;i++)t=sqrt(a-i*i); //where a contains the sum of 2 squares, search until the roots are found printf("%d %f ",i-1,t);} //and print them. m=t is used to evaluate the integer part of t. main(){ m=1<<15; //max root we need is sqrt(1<<30); for(a=m*m;--a;) //loop m*m-1 down to 1, leave 0 in a {z=a/m*(a/m)+a%m*(a%m);s[z<m*m?z:0]=1;} //split a into high and low half, calculate h^2+l^2. If under m*m, store flag, otherwise throw away flag to s[0] scanf("%d",&z); for(;1-s[a]*s[z-a];a++); //starting at a=0 (see above) loop until flags are found for sum of 2 squares of both (a) and (z-a) p(); //reconsitute and print the squares composing (a) a=z-a; //assign (z-a) to a in order to... p();} //reconsitute and print the squares composing (z-a) ``` **Example output** The first is per the question. The second was picked as a difficult one to search for. In this case the program has to search as far as 8192^2+8192^2=134217728, but only takes a few seconds once the table is built. ``` 123456789 0 2.000000 3328 10601.000000 805306368 8192 8192.000000 8192 24576.000000 ``` [Answer] # ~~Mathematica, 138 chars~~ **So it turns out that this produces negative and imaginary results for certain inputs as pointed out by edc65 (e.g., 805306368), so this isn't a valid solution. I'll leave it up for now, and maybe, if I really hate my time, I'll go back and try to fix it.** ``` S[n_]:=Module[{a,b,c,d},G=Floor@Sqrt@#&;a=G@n;b:=G[n-a^2];c:=G[n-a^2-b^2];d:=G[n-a^2-b^2-c^2];While[Total[{a,b,c,d}^2]!=n,a-=1];{a,b,c,d}] ``` Or, unsquished: ``` S[n_] := Module[{a, b, c, d}, G = Floor@Sqrt@# &; a = G@n; b := G[n - a^2]; c := G[n - a^2 - b^2]; d := G[n - a^2 - b^2 - c^2]; While[Total[{a, b, c, d}^2] != n, a -= 1]; {a, b, c, d} ] ``` I didn't look too hard at the algorithms, but I expect this is the same idea. I just came up with the obvious solution and tweaked it until it worked. I tested it for all numbers between 1 and one billion and... it works. The test only takes about 100 seconds on my machine. The nice bit about this is that, since b, c, and d are defined with delayed assignments, `:=`, they don't have to be redefined when a is decremented. This saved a few extra lines I had before. I might golf it further and nest the redundant parts, but here's the first draft. Oh, and you run it as `S@123456789` and you can test it with `{S@#, Total[(S@#)^2]} & @ 123456789` or `# == Total[(S@#)^2]&[123456789]`. The exhaustive test is ``` n=0; AbsoluteTiming@ParallelDo[If[e != Total[(S@e)^2], n=e; Abort[]] &, {e, 1, 1000000000}] n ``` I used a Print[] statement before but that slowed it down a lot, even though it never gets called. Go figure. [Answer] # Haskell 123+3=126 ``` main=getLine>>=print.f.read f n=head[map(floor.sqrt)[a,b,c,d]|a<-r,b<-r,c<-r,d<-r,a+b+c+d==n]where r=[x^2|x<-[0..n],n>=x^2] ``` Simple brute force over pre-calculated squares. It needs the `-O` compilation option (I added 3 chars for this). It takes less than 1 minute for the worst case 999950883. Only tested on GHC. [Answer] # ~~C: 198 characters~~ I can probably squeeze it down to just over 100 characters. What I like about this solution is the minimal amount of junk, just a plain for-loop, doing what a for-loop should do (which is to be crazy). ``` i,a,b,c,d;main(n){for(scanf("%d",&n);a*a+b*b-n?a|!b?a*a>n|a<b?(--a,b=1):b?++b:++a:(a=b=0,--n,++i):c*c+d*d-i?c|!d?c*c>i|c<d?(--c,d=1):d?++d:++c:(a=b=c=d=0,--n,++i):0;);printf("%d %d %d %d",a,b,c,d);} ``` And heavily prettified: ``` #include <stdio.h> int n, i, a, b, c, d; int main() { for ( scanf("%d", &n); a*a + b*b - n ? a | !b ? a*a > n | a < b ? (--a, b = 1) : b ? ++b : ++a : (a = b = 0, --n, ++i) : c*c + d*d - i ? c | !d ? c*c > i | c < d ? (--c, d = 1) : d ? ++d : ++c : (a = b = c = d = 0, --n, ++i) : 0; ); printf("%d %d %d %d\n", a, b, c, d); return 0; } ``` Edit: It's not fast enough for all input, but I will be back with another solution. I'll let this ternary operation mess stay as of now. [Answer] # Rev B: C, 179 ``` a,b,c,d,m=1,n,q,r;main(){for(scanf("%d",&n);n%4<1;n/=4)m*=2; for(a=sqrt(n),a-=(3+n-a*a)%4/2;r=n-a*a-b*b-c*c,d=sqrt(r),d*d-r;c=q%256)b=++q>>8; printf("%d %d %d %d",a*m,b*m,c*m,d*m);} ``` Thanks to @Dennis for the improvements. The rest of the answer below is not updated from rev A. # Rev A: C,195 ``` a,b,c,d,n,m,q;double r=.1;main(){scanf("%d",&n);for(m=1;!(n%4);n/=4)m*=2;a=sqrt(n);a-=(3+n-a*a)%4/2; for(;(d=r)-r;q++){b=q>>8;c=q%256;r=sqrt(n-a*a-b*b-c*c);}printf("%d %d %d %d ",a*m,b*m,c*m,d*m);} ``` Much faster than my other answer and with much less memory! This uses <http://en.wikipedia.org/wiki/Legendre%27s_three-square_theorem>. Any number not of the following form can be expressed as the sum of 3 squares (I call this the prohibited form): `4^a*(8b+7), or equivalently 4^a*(8b-1)` Note that all odd square numbers are of the form `(8b+1)` and all even square numbers are superficially of the form `4b`. However this hides the fact that all even square numbers are of the form `4^a*(odd square)==4^a*(8b+1)`. As a result `2^x-(any square number < 2^(x-1))` for odd `x`will always be of the prohibited form. Hence these numbers and their multiples are difficult cases, which is why so many of the programs here divide out powers of 4 as a first step. As stated in @xnor's answer, `N-a*a` cannot be of the prohibited form for 2 consecutive values of `a`. Below I present a simplified form of his table. In addition to the fact that after division by 4 `N%4` cannot equal 0, note that there are only 2 possible values for `(a*a)%4`. ``` (a*a)%4= 01 +-- 1|10 N%4= 2|21 <- (N-a*a)%4 3|32 ``` So, we want to avoid values of `(N-a*a)` that may be of the prohibited form, namely those where `(N-a*a)%4` is 3 or 0. As can be seen this cannot occur for the same `N` with both odd and even `(a*a)`. So, my algorithm works like this: ``` 1. Divide out powers of 4 2. Set a=int(sqrt(N)), the largest possible square 3. If (N-a*a)%4= 0 or 3, decrement a (only once) 4. Search for b and c such that N-a*a-b*b-c*c is a perfect square ``` I particularly like the way I do step 3. I add 3 to `N`, so that the decrement is required if `(3+N-a*a)%4 =` 3 or 2. (but not 1 or 0.) Divide this by 2 and the whole job can be done by a fairly simple expression. **Ungolfed code** Note the single `for` loop `q` and use of division/modulo to derive the values of `b` and `c` from it. I tried using `a` as a divisor instead of 256 to save bytes, but sometimes the value of `a` was not right and the program hung, possibly indefinitely. 256 was the best compromise as I can use `>>8` instead of `/256` for the division. ``` a,b,c,d,n,m,q;double r=.1; main(){ scanf("%d",&n); for(m=1;!(n%4);n/=4)m*=2; a=sqrt(n); a-=(3+n-a*a)%4/2; for(;(d=r)-r;q++){b=q>>8;c=q%256;r=sqrt(n-a*a-b*b-c*c);} printf("%d %d %d %d ",a*m,b*m,c*m,d*m);} ``` **Output** An interesting quirk is that if you input a square number, `N-(a*a)`=0. But the program detects that `0%4`=0 and decrements to the next square down. As a result square number inputs are always decomposed into a group of smaller squares unless they are of the form `4^x`. ``` 999999999 31621 1 161 294 805306368 16384 0 16384 16384 999950883 31621 1 120 221 1 0 0 0 1 2 1 0 0 1 5 2 0 0 1 9 2 0 1 2 25 4 0 0 3 36 4 0 2 4 49 6 0 2 3 81 8 0 1 4 121 10 1 2 4 ``` [Answer] # JavaScript - ~~175 191 176 173~~ 168 chars Brute force, but fast. **Edit** Fast but not enough for some nasty input. I had to add a first step of reduction by multiplies of 4. **Edit 2** Get rid of function, output inside the loop then force exit contition **Edit 3** 0 not a valid input **Edit 4** Spurred by GalaxyCat105: a function again, but avoiding the length of return keyword ``` v=>(q=>{for(m=1;!(v%4);m+=m)v/=4;for(a=-~q(v);q&&a--;)for(w=v-a*a,b=-~q(w);q&&b--;)for(x=w-b*b,c=-~q(x);q&&c--;)(d=q(x-c*c))==~~d&&(q=0)})(Math.sqrt)||[m*a,m*b,m*c,m*d] ``` **TEST** ``` F= v=>(q=>{for(m=1;!(v%4);m+=m)v/=4;for(a=-~q(v);q&&a--;)for(w=v-a*a,b=-~q(w);q&&b--;)for(x=w-b*b,c=-~q(x);q&&c--;)(d=q(x-c*c))==~~d&&(q=0)})(Math.sqrt)||[m*a,m*b,m*c,m*d] test=[123456789, 805306368, 999999999, 265289728, 699731569]; console.log(test.map(x => x+' : '+F(x))) ``` **Ungolfed:** ``` v = prompt(); for (m = 1; ! (v % 4); m += m) { v /= 4; } for (a = - ~Math.sqrt(v); a--;) /* ~ force to negative integer, changing sign lead to original value + 1 */ { for ( w = v - a*a, b = - ~Math.sqrt(w); b--;) { for ( x = w - b*b, c = - ~Math.sqrt(x); c--;) { (d = Math.sqrt(x-c*c)) == ~~d && prompt([m*a, m*b, m*c, m*d], a=b=c='') /* 0s a,b,c to exit loop */ } } } ``` [Answer] # [Haskell](https://www.haskell.org/), 117 bytes ``` w=floor.sqrt.fromIntegral s 1 n=[[x]|x<-[w n],x^2==n] s i n=[x:y|x<-[w n,w n-1..0],y<-s(i-1)(n-x^2),y/=[]] f=head.s 4 ``` [Try it online!](https://tio.run/##NctLDsIgFEDReVfBwEGbAEqt9ZO@BbgGggmJxRLpQ6FJaeLesQ4c3NHJHXR89s7lPINx3gce32HiJvjxilP/CNoVkQiCIGVSn9QxORNUNN1qAFSr2Z@ly/I3usYE5ztFl47F0jJRlcjWoaLLFqRShYGh13ceSZNHbRFeweK0MUTU@@bQHk/n/AU "Haskell – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 626 bytes \$\text{626 bytes, it can be golfed much more.}\$ Golfed version. [Try it online!](https://tio.run/##ZZHLbsIwEEX3@YqriIUtQdSkb1QWXXbRFd0hFi4YcJo4wXZaVSjfno7zgLaRLMszunfmeMZuRCaaRuVlYRysj6JcuEN0skfjpmXxVQdB8Z7KjcOrUBqnANjKHZRdHpme40U7jgVIyLyDaR65gpJTJJRfQAe9YSs3RV4OljmW8rii15rMviawKwyYwtMMMSrtVIY/BXkvAz5FBhOTT2PWNla@WafqJWpHpTyhiTmHka4y2nf00rYq5QfOKzq897UM6YjhrL5A9BgJYRBLx5GOOH6TJCOSdIBJLjADSR1cbi//N9wu7PuOBj/6Wz1sIacdMmH2do5nY8T3aumM0vs1P6/Bf0tTFCfXN7d39w@PbbYklcs0s@HbQdKYKkMIlTASusrfpbHt6CYaPjU5DcvmUf7RdWDhFCGvw46mDprmBw) ``` import scala.math.{sqrt,pow} object Main { def isSq(n: Int) = pow(sqrt(n).toInt, 2) == n def decomp(n: Int): Seq[Int] = { for (i <- 1 until sqrt(n).toInt) { val r1 = n - pow(i, 2).toInt if (isSq(r1)) return Seq(i, sqrt(r1).toInt, 0, 0) for (j <- 1 until sqrt(r1).toInt) { val r2 = r1 - pow(j, 2).toInt if (isSq(r2)) return Seq(i, j, sqrt(r2).toInt, 0) } } Seq(sqrt(n).toInt, sqrt(n - pow(sqrt(n).toInt, 2)).toInt, 0, 0) } def main(args: Array[String]) = { val n = 123456789 println(s"The four square numbers for $n are ${decomp(n).mkString(", ")}") } } ``` --- Ungolfed version. [Try it online!](https://tio.run/##hZM7b8IwFIX3/IqrqEMsQVTSNypDu3XoRDshBgMGAokNttOqQvnt6bWdFwFaKVLs6@vj7yTHak4TWhRxuhNSgzKzMKV6Haq91N5peSe@PU/MNmyu4Z3GHA4ewIItIVbjfUYlC/gQ3rgmQ3gVImGUw8j2AHzRBKQQGgtGPOAk1AJb7SLqBmaxBxGB0Qg4VnOv1F6wuUAS1RIfs/0ER9NaPV5C0DAQUpbBdAa8B9fuIbaaA0sUq1uWQuJmeO7DADKu4@QYsNEqTbAUnS@YxMM59C17bMBbfk6Q6k2kLQcopjPJLSVq2HObVifYJrf09ciCb07AuwLHJx5ZiNBD48d52ZzxcslN1LHTNbTpeooaU6S1L@8AbquUnGzsIBngbZWaVvN/VNuLANWoev@ZW5cvl1y3Wn7EKsxn/mHezrYBDqhcqSG8SEl/JmMtY76aYsY/eayPbg/PUpwPopvbu/uHx6fmVjGVJaa1dVGy1B22QzWd8ED5H2uGgckkcpp/aNRmTCoboisjbYpXBycWplsHEvg98EnuEwude0XxCw)   **Here is a basic implementation in Scala following the algorithm as described by Joseph Louis Lagrange. This algorithm is not the most efficient one but it should run within the required time constraints.** This algorithm uses Gauss's "Three-Square" theorem as an optimization. According to this theorem, a natural number can be expressed as the sum of three squares of integers if and only if it's not of the form 4^n(8m+7). ``` import scala.math.sqrt import scala.math.pow object Main { def isSquare(n: Int): Boolean = { val root = sqrt(n).toInt pow(root, 2) == n } def decompose(n: Int): Seq[Int] = { if (isSquare(n)) { Seq(n, 0, 0, 0) } else { for (i <- 1 until sqrt(n).toInt) { val remainder = n - pow(i, 2).toInt if (isSquare(remainder)) { return Seq(i, sqrt(remainder).toInt, 0, 0) } for (j <- 1 until sqrt(remainder).toInt) { val remainder2 = remainder - pow(j, 2).toInt if (isSquare(remainder2)) { return Seq(i, j, sqrt(remainder2).toInt, 0) } val k = sqrt(remainder2).toInt if (pow(k, 2) == remainder2) { return Seq(i, j, k, 0) } } } val root = sqrt(n).toInt Seq(root, sqrt(n - pow(root, 2)).toInt, 0, 0) } } def main(args: Array[String]): Unit = { val num = 123456789 val result = decompose(num) println(s"The four square numbers for $num are ${result.mkString(", ")}") } } ``` The above program tries to find 1 to 3 square numbers whose sum is equal to the input number. If the input number is a perfect square, it directly returns it along with three zeros. If not, it tries to find two square numbers whose sum is equal to the input number. If still not possible, it will look for three square numbers. For the remaining number, the fourth square number is calculated as the difference between the input number and the sum of squares of the first three numbers. Please note that due to the limitation of the Scala language, the size of integers that can be processed by this program is limited. Numbers larger than Int.MaxValue (~2 billion) might cause overflow errors. ]
[Question] [ ## Background A **polyhex** of size \$n\$ is a contiguous shape made from joining \$n\$ unit regular hexagons side-by-side. As an example, the following image (from Wikipedia) contains all 7 distinct tetrahexes (polyhexes of size 4): [![enter image description here](https://i.stack.imgur.com/e2pqa.png)](https://i.stack.imgur.com/e2pqa.png) A **dihex** is a polyhex of size 2. Now, let's define a **sticky polyhex** as follows: * A single dihex is a sticky polyhex. * If a polyhex X is sticky, X plus a dihex Y is also sticky if X and Y share at least two unit sides. * Any polyhex that cannot be formed by the above definition is not sticky. The following is the only size-2 sticky polyhex: ``` _ / \ \ / / \ \_/ ``` The following are the only two essentially different size-4 sticky polyhexes: ``` _ _ / \_/ \ \ / _/ / \_/ \_/ _ _/ \ / \ / \ / \ / \_/ \_/ ``` The following is a simplified illustration of all 15 size-6 sticky polyhexes: ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` ## Challenge Given a positive integer \$n\$, count the number of sticky polyhexes of size \$2n\$. Two polyhexes which are equivalent under rotation and reflection are counted only once. If you want, you may take the value of \$2n\$ as input instead (and assume the value is always even). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code wins. ## Test cases The following are the expected results for \$1 \le n \le 7\$. Generated using [reference implementation in Python](https://tio.run/##tVZRb9MwEH7frzgJiTRrUq1FCGmiPPPIe4git3HXQLBD7EIS2G8fd7aTOFk7NiT60PbOd9/32Xc5p2r1UYo3Dw/7kikFH3nzaSF3X/heh7dXgJ@cHyDLClHoLFsoXh4iaCJoI@hcAH3Iv2pgC83U1aKrnbo6dHUeMsvzAVjqI6892JrrUy2sKEuxNCErVGDxnd06u3N2F3oM6rR7AUM8Y4hnDPEZhiNTR0fxGJsWFw68B@3BwhGllnp9AcGoi21GBHEPZf@0HgQ/lFi4p1AmMrpezggheHF33MlaXQD5RW5YQgMHWeN3ISAxwDcRrFHSOowsERo3MzsmX2/fWHtYj23CxDbx6b130DWv6osHHVBigOIo6hknnmX8@98a4xIKbLewGDplaJEzvVHqf@Z4/0yKb6fyBQ0O1zao55vZXW/7DPX/orh6BerIKg6FAoarGuTBIOECK0uopFLFruSgdLH/2gJOi0IXUijQkhIo94o0DgsL43Py1Kmu5UnkhbhTOHd@CdO2FbWtpSVTkFmtxtYP7yF20HZ/6lRqyk9S46AkZTA8@PE8BiDMUD7sEFEcoOTCKoXXY0IIH7awGZEGsg2xjbhO3TTQk7piVcVF7gh@41OLJ7@5HwXwUvG/07y@sMGXsLnmcKFUb10zoUqmsaYS9JFpU@gmwAYQObT0W3MQUgh@x3Txw9Z3z9BT7FlZdDzTkyI331D1FvB7oVaNVx0TY/vASMMGsLOFMsy4oT8hTgw1y7Izp/WB22cA01BrDXb7JLA7FNtieCQ1Z@VkhxHsmOI5SNEPddPzdEB4TzBjPTqWyaG4NJKmVv3FEJ5XI21zG1c6ZGe932WPvZ8RAFbxji/ehn7fN7pPIlK60DxGWknitZvnY4JHdS6rX56mkqfvu4E39EaSy5rG9N5Ja1J5k1l7NeF4vxltyxEyjeArb7dK1prnOMGoDDnPT5U9fzUUwKAnONNcYeym7LTDm/RQy46LS8sW6z51@IWqStZOKoySf7DZVMqlHpK9AS1/RrCXJcZiAN0m9DO@l9kl@r6GDW1V/pyPKkuGV9KWVm978iWyJ@m8KTACR5SftsSLPT2PmWB0aoBRQA9snAY9gGAOT0LjxwhTDm8pwYQUNxhcB2a5qguhF8FnEay@SCx@4H4x1haB9CObEx96SVhuestNhsf9ZvpKY1@BsGqOg8bHGrYfgsjobRBsuHHsZjYRvOvnGCFPH@hZU3jDbX7fpQOE7cXGyn41zb@ddZJ/HqgVZeLsCny9Dw9/AA) (it times out shortly after calculating \$n = 6\$; the result for \$n = 7\$ was found on my local machine, and the program segfaulted while calculating \$n = 8\$). ``` 1, 2, 15, 110, 1051, 10636, 113290 ``` This sequence is now on OEIS as [A342963](https://oeis.org/A342963). [Answer] # [Haskell](https://www.haskell.org/), ~~320~~…~~236~~ 230 bytes ``` length<$>iterate(\h->nub[r$x:y:u|u<-h,t<-u,x<-n t\\u,y<-n x\\u,([x,x,y]\\(u>>=n))/=[x,y]])[[l,0<$l]] r u=minimum[sort$(!!i).p.map(*j).m a<$>u|a<-u,j<-l,i<-[0..5]] n=(<$>p l).m m=zipWith(-) p=permutations l=[-1..1] import Data.List ``` [Try it online!](https://tio.run/##VY8xb8MgEIV3fgWRPEAFNKnaJQJPHSt17AAeaOTEJEAQPiS7ym8vxWOX06d773TvTXa@jd5XF9I9A363YMWHmwH5NpSpfowXmGTXOxizhZGYifexfOvcLcf1WB5F8omB5IUtkkcMxhS2brRsRPTCFrYOxpDS9ypS@qz0thio1p7tZeeHAWVcVHDRhRL03GJ0ZLdzVCQRbCJPVyoCti1Cedjtz1Vyz5zkei/EW7uOijQxYd98KKgfl74cTIRTlFQacyhgwd3jjLzS/CDEYUCc/29bg3VRpewidGBvI37FW//6ezp7e5krP6VU@efLHw "Haskell – Try It Online") An infinite list whose \$n\$-th element (1-indexed) is the number of sticky polyhexes of size \$2n\$. This is probably the longest I've ever spent golfing a single program, and at the same time it's the answer I'm most proud of. After golfing 90 bytes off of the first iteration, it's time explain in some depth how this solution works and share the things I've learned. ## The grid The first thing to decide is how to handle the hexagonal grid. At first I was demotivated by the apparent lack of regularity in any coordinate system I could find, but then I stumbled across [this website](https://www.redblobgames.com/grids/hexagons/)1. Along with some amazing visualization tools, which helped me later in debugging my code, it describes several reasonable coordinate systems for a hexagonal grid. The one I settled for in the end is called [cube coordinates](https://www.redblobgames.com/grids/hexagons/#coordinates) and is very clever. The following animation (taken from the same website) explains the concept beautifully. [![From cubes to hexagons](https://i.stack.imgur.com/hxXU0.gif)](https://i.stack.imgur.com/hxXU0.gif) We start from the standard lattice grid in \$3\$-dimensional space, and then we cut along the plane \$x+y+z=0\$. On this plane, we get a hexagonal grid, where each hexagon is encoded as a triplet of integers \$[x:y:z]\$ with the constraint that \$x+y+z=0\$. Coordinate systems such as this one are called *homogeneous*, since they have one extra degree of freedom (three numbers for two dimensions) but they also have one additional constraint. While using three numbers to represent two dimensions may seem wasteful, the redundancy of cube coordinates is abundantly outweighted by the elegance and symmetry they provide. The main advantage is that, since we are operating in a *vector subspace*2 of \$\mathbb{R}^3\$, all the linear operations we may want to perform (translations, rotations, reflections) become astoundly straightforward (more on this later). For now, the following picture3 should give you an intuition of how cube coordinates work. [![Cube coordinates](https://i.stack.imgur.com/hvUK8.png)](https://i.stack.imgur.com/hvUK8.png) Before moving on to the actual problem, let's code(golf) a few grid-related functions. As anticipated, each hexagon is encoded as a triplet of integers with sum equal to \$0\$. In Haskell4, we will represent it as a list `[x,y,z]`. * Since, as I said, we are working in a vector subspace, there is a well-defined notion of *displacement vector* between two points: coordinate-wise, we just take the difference of each coordinate. The relevant function is `m=zipWith(-)` (mnemonic: **m**inus), and it works as follows: `m[x1,y1,z1][x2,y2,z2] ≡ [x1-x2,y1-y2,z1-z2]`. * Unsurprisingly, we will later need a function to compute the neighboring hexes of a given hexagon. By looking at the above picture, it's easy to see that all the neighbors of point \$[x:y:z]\$ can be obtained by summing (coordinate-wise) \$[-1:0:1]\$ or a permutation thereof. After importing `Data.List` (I know, that's very costly, but totally worth it5) and creating the aliases `p=permutations` (mnemonic: **p**ermutations) and `l=[-1..1]≡[-1,0,1]` (mnemonic: **l**ist6), we can define our function `n=(<$>p l).m` (mnemonic: **n**eighbors). If you're not fluent in Haskell, this is what `n` would look like if I weren't codegolfing: `n x=[m x y|y<-p l]`. In other words, we take each permutation `y` of `l` and subtract it (coordinate-wise) from `x`; adding or subtracting is the same thing, since `-l` is a permutation of `l`. ## Attaching dihexes Now that we have our grid set up, it's time to move on to the actual problem. A polyhex will be very naturally represented as a list of hexes, i.e. a list of lists of integers. Assume we are given a list `h` containing all the sticky polyhexes of size \$2n\$. Our task for this section will be to compute a list of all the sticky polyhexes of size \$2n+2\$, possibly with duplicates. This is the relevant code, where we abuse7 the list difference operator `(\\)`. ``` [x:y:u| -- the list of polyhexes obtained by adding x and y to u, where u<-h, -- u is a polyhex in h t<-u, -- t is a hexagon in u x<-n t\\u, -- x is a neighbor of t not in u y<-n x\\u, -- y is a neighbor of x not in u ([x,x,y]\\(u>>=n))/=[x,y] -- ?? see below ] ``` Everything should be pretty straightforward. The only thing that's missing is checking that the polyhex `x:y:u` is actually sticky, i.e. that the dihex `[x,y]` has at least two sides in common with `u`. The most concise way of checking this I could find is `([x,x,y]\\(u>>=n))/=[x,y]`. How does it work? `u>>=n` is the list of neighbors of `u`, counted with multiplicity. Since `x` appears at least once in this list (by definition `x` is a neighbor of `t`), the difference `[x,x,y]\\(u>>=n)` is equal to `[x,y]` if and only if the dihex `[x,y]` shares exactly one (i.e. less than two) side with `u`. ## Canonical representatives The only thing that's left is to remove duplicates. We say that two polyhexes are *equivalent* if they are related by a finite sequence of translations, rotations and reflections. A standard approach for this kind of task is to choose a *canonical representative* for every polyhex, with two rules in mind: 1. a polyhex is equivalent to its canonical representative; 2. if two polyhexes are equivalent, then they have the same canonical representative (by rule 1., the converse also holds). If we find a suitable canonical representative for every polyhex, the task is solved: simply replace each polyhex with its representative, and then remove duplicates the standard way (which, in Haskell, is `nub`). A reasonable choice for canonical representatives is the following: given a polyhex \$u\$, we define its representative \$r(u)\$ as the lexicographically minimum polyhex which is equivalent to \$u\$ and contains the hex \$[0:0:0]\$. We will always assume that the hexes in a polyhex are lexicographically sorted, so that this definition is well-posed. This choice of representatives may seem somewhat arbitrary, but the idea behind it is really simple: given a polyhex \$u\$, we generate the set of all the equivalent polyhexes (with the restriction of containing \$[0:0:0]\$, otherwise there would be infinitely many). Clearly, if we apply this procedure to every polyhex equivalent to \$u\$ we will end up with the same set. Now we just need to pick a fixed element of this set, and (with bytes in mind) we select the minimum. Now that we have an objective in mind, how do we implement it? This is where the linearity of cube coordinates comes into play. Equivalent polyhexes are always related by linear8 transformations, which should be relatively easy to implement. Before we look at the code, let's analyze these transformations in detail. Translations are trivial: the translation sending hexagon `x` to `[0,0,0]` is just `m x`. As far as rotations and reflections are concerned, by looking at the picture above you can convince yourself that they all behave as follows: permute the three coordinates and, possibly, flip all the signs. For instance, the following are rotations or reflections: $$ [x:y:z]\longmapsto[y:z:x]\\ [x:y:z]\longmapsto[-x:-z:-y]. $$ We are now ready to implement the function `r` (mnemonic: **r**epresentative). ``` r u=minimum[sort$(!!i).p.map(*j).m a<$>u|a<-u,j<-l,i<-[0..5]] ``` In plain English, the code does the following. Given a polyhex `u`, we want to compute its canonical representative as defined above, so we generate a list of all the polyhexes containing `[0,0,0]` and equivalent to `u`. To this aim, we fix: * a hexagon `a` in `u` (which will be mapped to `[0,0,0]` with a translation); * a sign `j` in `[-1,1]`; * a permutation index `i` in `[0,1,2,3,4,5]`. The code `(!!i).p.map(*j).m a<$>u` takes `u` and applies a translation (`m a`, mapping `a` to `[0,0,0]`), possibly a sign flip (`map(*j)`), and finally a permutation of the coordinates (`(!!i).p`). The `sort` ensures that the polyhex we obtain is "normalized" (i.e. lexicographically sorted). Finally, we take the lexicographically `minimum` polyhex in our list, and this is the canonical representative of `u`. A small codegolfing note: you may have noticed the `j<-l` instead of the expected `j<-[-1,1]`. This saves 5 bytes at the cost of producing some "degenerate" polyhexes, but the output is the same since a degenerate polyhex will never be selected as the minimum. ## Conclusion Now that we have all the ingredients, let's put them together! This is the last bit of code (with ellipses instead of the section already explained above). ``` length<$> -- take the length of each list in iterate( -- the list generated by repeatedly applying \h-> -- the function that takes the list h of sticky polyhexes of size 2*n nub[ -- and removes duplicates from r$ -- the list of canonical representatives of x:y:u|...]) -- all the polyhexes obtained by suitably attaching dihexes to elements of h [[l,0<$l]] -- starting from the list of sticky dihexes (there is just one) ``` `0<$l` is short for `[0,0,0]`. **And that's it!** Thanks for reading through this huge post (or just skipping to the end to read the footnotes, most likely). Despite having spent several hours golfing this program, I believe there are still at least a few bytes that can be somehow shaved off: if you have any ideas, please let me know! --- --- 1 Ok maybe I should've resorted to Google earlier, it's literally the first result for "hex grid". 2 Don't worry if you don't know what I'm talking about, I have this bad habit of inserting random mathematical terms even when it's completely unnecessary. 3 Guess where it's taken from. 4 Please don't stop reading, I promise there will be no catamorphisms. 5 Trust me, I've spent several hours trying every possible variation of the code. 6 Creativity is my middle name. 7 Can you blame me? It's just two bytes and it's *amazing*! 8 +10 internet points if you shouted "Translations aren't linear!" with a disgusted voice. [Answer] # [C++](https://gcc.gnu.org/), Not competing After spending so long on the golfing side of this challenge, I was curious to see what I could do from a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") perspective. Here is my C++ attempt, which should be able to run up to \$n=8\$ on every computer, and \$n=9\$ if you have enough RAM and patience. The approach is the same as my other answer, but optimized for speed instead of bytecount. Here are the results I got so far. | \$n\$ | Number of sticky polihexes of size \$2n\$ | | --- | --- | | 1 | 1 | | 2 | 2 | | 3 | 15 | | 4 | 110 | | 5 | 1051 | | 6 | 10636 | | 7 | 113290 | | 8 | 1234189 | | 9 | 13674761 | | 10 | 153289285 | It's highly unlikely I'll ever be able to go further, it looks like 256GB of RAM are not enough to compute the list of sticky polyhexes for \$n=11\$. ``` #include <algorithm> #include <iostream> #include <iterator> #include <vector> using T = char; struct hex { T x, y; constexpr T z() const { return -x -y; } bool operator < (const hex& other) const { return x < other.x or (x == other.x and y < other.y); } bool operator == (const hex& other) const { return x == other.x and y == other.y; } template<typename F> void on_neighbors(F f) const { f(hex{ x + 1, y }); f(hex{ x + 1, y - 1}); f(hex{ x, y + 1 }); f(hex{ x, y - 1 }); f(hex{ x - 1, y + 1 }); f(hex{ x - 1, y }); } }; using polyhex = std::vector<hex>; std::vector<polyhex> extend(const std::vector<polyhex>& h) { auto nub = [&](auto& v) { std::sort(v.begin(), v.end()); v.erase(std::unique(v.begin(), v.end()), v.end()); }; auto in = [&](const auto& v, const hex& a) { return binary_search(v.begin(), v.end(), a); }; std::vector<polyhex> ans0; for(const auto& u : h) { std::vector<hex> layer; for(const hex& t : u) { t.on_neighbors([&](hex&& a) { if(not in(u, a)) { layer.push_back(a); } }); } nub(layer); std::vector<polyhex> ans1; for(const hex& a : layer) { int cnt0 = 0; a.on_neighbors([&](hex&& b) { if(in(u, b)) { ++cnt0; } }); a.on_neighbors([&](hex&& b) { if(not in(u, b) and (a < b or not in(layer, b))) { int cnt = cnt0; b.on_neighbors([&](hex&& c) { if(in(u, c)) { ++cnt; } }); if(cnt < 2) { return; } polyhex v = u; v.push_back(a); v.push_back(b); v.shrink_to_fit(); std::sort(v.begin(), v.end()); ans1.push_back(v); } }); } nub(ans1); ans0.insert(ans0.end(), std::make_move_iterator(ans1.begin()), std::make_move_iterator(ans1.end())); } nub(ans0); std::vector<polyhex> ans; for(auto it = std::make_move_iterator(ans0.begin()); it != std::make_move_iterator(ans0.end()); ++it) { polyhex v = *it, best = v; auto trans = [&](auto&& f) { polyhex vv = v; for(auto& c : vv) { c = f(c); } std::sort(vv.begin(), vv.end()); hex m = vv.back(); for(auto& c : vv) { c = hex{ c.x - m.x, c.y - m.y }; } if(vv < best) { best = std::move(vv); } }; for(int s = -1; s <= 1; s += 2) { trans([&](hex& c) { return hex{ s * c.x, s * c.y }; }); trans([&](hex& c) { return hex{ s * c.x, s * c.z() }; }); trans([&](hex& c) { return hex{ s * c.y, s * c.x }; }); trans([&](hex& c) { return hex{ s * c.y, s * c.z() }; }); trans([&](hex& c) { return hex{ s * c.z(), s * c.x }; }); trans([&](hex& c) { return hex{ s * c.z(), s * c.y }; }); } ans.push_back(best); } nub(ans); return ans; } int main() { std::vector<polyhex> h = { { hex{ -1, 0 }, hex{ 0, 0 } } }; for(int n = 1; ; ++n) { std::cout << "n=" << n << " -> " << h.size() << std::endl; h = extend(h); } return 0; } ``` [Try it online!](https://tio.run/##rVbdbqs4EL7PU8yelSI4DSjdy@bn8jzBkfZitYoMcQJqYmeNYUMrXn2zM8YEk5h22y6VGvD8fTMef570dIr2aXq5/JqL9FBuOSzZYS9VrrPjetIv5rLQirPhmuaKaanctYqnZmVSFrnYw09YQZoxtZhM0L5MNWT8DK8TwOcnnGdQL8x7KkWh@fmkcPUlCNtvq0eP4rpUAqIzRNaiMf8TKQ8gTy0OWELQGmKQKUidcTXq6ozaRiM@A5oGZ1itrgtMbKG@KtTheEg0@kjMuxjXhUFamh9PB6b5UtcnLtiRw4@1EVQy34IUG8HzfZZIVQQ/YHcfbxcgmleM9wCPWGNobAY@WQSPPjGJUAPGZNGIjARv2Xby5lrUZtF1y0keauqPFRR6@/TU9tISV9amf/olq7gGftZcbO0O@DSmkIW2MKzUEkSZoPs/pn8G9DmFKnTKZhwUUumgihO@z0UQzqCKKULopIIrihU8MOqlyP8quc/g1rRZ9DByYVG0yC2WGTitxML7BkpywVS9KThTaeaJOUOrQTBv0Zgo5q14J9UAQQlPfb1u7Y3tgdVcObt6dWAwa7QvXXvTzPGgYSlrUr7JsHvyXSCkxgIFJWXjU6HH4IhPZZFtEpY@B8zZn@5pBituM/YS7IfA@HKkY0V7HM2bYd6tlxu4udCQCj3H3Z4PAbKxqiQjVWkrkoxW5OGBAn2kCp@C0W8OahCHBQyJMiEOtSJTCIN0DKqtCt0NXsiGZseApWNeB3VKw7fUrvVajKo0XkkT@i0wLiW0hN/eCtueYr8Hf7yOESusVek3rN45Bbc6yahOkalcPG@03OxyHYyo/UeOHPQYHh0HQPWFo0quHCExWZyLgiMc825Z0IA8sme@OcqKb7pBxZh3qN9TazMaXP0WwTx8m1x7bm25XncXmj/U/IpoQbq/vKNsK439m2u32dxW@Z5rPIC8oMiVUy6CoxW6ce/AKU0Qw6a9@qqGDty88CQi61WVr@FTNMMTcbPRw012GsntJH8rEZgjYUFV6qHwc5jMCJLGNIQcYxxj0rg2r3V3X/qh4unGSixNRX2ubaXbbcMdQ@3R1JvhJUJUSLsRPS7wd7kC8/uwuicSs29XHjQ02I0FJq0CvlNqM/tCKd3R1Qd90CT@aS915@X8P/j4EpIXQwlfxeJ4uatt4zKSy7XUMB4GsWs2iKGMZjKhXjgyOgd2670Ek2G3vOKfgRbhLD2HZtZ@zc0H/fUURE5p2MS@Is4Qd9NdKku8uJbwTay@0a8wHxCtwXxmcZG/cISE70Yfj@ehz5zQ2CE8G2Rqc8Pbvblc/kl3B7YvLtHvQkY4wir5N877/wI "C++ (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~290~~ 270 bytes ``` ->n,p=[[2,3]],s=2{s<n ?(q=[] p.map{|a|a.product(d=[w=n*3,1,~w,-w,-1,-~w],d).map{|i|r=[];t=0 c=a+b=[i[0]+i[1],i.sum] a&b==r&&12.times{|j|t+=a.count b[j%2]+d[j/2];c=c.map!{|k|j%2<1?k%w*(2+w)-k:k/w+k%w*w}.sort!.map{|m|m-c[0]+n};r<<c*1} t>1&&q<<r.min}} f[n,q&q,s+2]):p.size} ``` [Try it online!](https://tio.run/##JU5NroMgGNx7Cruo0YJU6K76tQchLBRrgkaqgCF9Yq/ua9NkNjOZP7M0r72DPb9pPAHnDF@EwBbYaisd39MZuIgmMtbTGupQk8k820W6tAXuQZ8umOK3x/kHFOdvL3Cb/cwqmE@0dFBEEmrUAFe8EEhxKrAidhlFVCcNgEkSyohT48OuoQ8OQU3kc9Eubnh/ZAK1vD8zUUqQ3@LDGobw0St6H47@lDLks3y4DmePvtxvxD6NO/w@jGHM5XdVb6WpKnmiW@RuNEnmqjJkVHrboo5rPCcztoiJ7DoRq/4e2z7FHaeF2P8B "Ruby – Try It Online") A function that accepts the **total** number of hexagons as an argument `n` (as permitted by the rules) and returns the number of sticky polyhexes. Will run up to 6 dihexes / 12 hexes on TIO in about 7 seconds. This is about 3 times faster than the old version, because the code now checks if the new hexes overlap with the old hexes **before** calculating all 12 symmetries and 12 possible shared edges, hence saving a lot of wasted time. It also saves a byte, because `r` is empty at this stage, so we can use it to compare with `a&b` to ensure this array intersection is empty, instead of comparing with the literal empty array `[]`. **Explanation** Each hex is saved as a single number; polyhexes are saved as arrays. The coordinate system is a square grid of infinite height, and width `w` three times the number of hexes in the last generation to be investigated. The hexagonal grid is mapped onto this. Hexes with coordinates that differ by the following amounts are considered adjacent: `1`=horizontal, `w`= vertical, and `~w` = `-w-1`= diagonal. As it is a hexagonal grid, coordinates on the other diagonal are not considered adjacent. The function proceeds by adding a pair of hexes to the previous generation and checking if the new hexes share at least 2 edges with the old ones; this requires 6 directions x 2 new hexes = 12 checks. To ensure the newly added hexes do not wrap around the grid, the old polyhex is positioned such that the hex with the lowest coordinate is at `n` (where n is the total number of hexes in the last generation to be investigated.) **Symmetries** Coincidentally, there are also 12 symmetries to be checked, so the same loop performs both duties. All symmetries are cycled through by alternately performing 2 different reflections. After each reflection, the hexes are sorted and the coordinates are adjusted so that the lowest coordinate is equal to `n`. The first reflection is a vertical flip `k = k%w - k/w*w + k%w*w` . The first term keeps the x coordinate the same and the second one (with integer division to discard the x coordinate) flips the y coordinate. The third term is a correction to maintain the skew. This formula can be simplified to `k = k%w*(2+w)-k`. This reflection is done first in case any new hexes have negative y coordinates. The second is a diagonal flip which swaps the x and y coordinates: `k = k/w+k%w*w`. Doing this second ensures there are no negative y coordinates to handle (because after every reflection, the lowest hex's coordinate is adjusted to be equal to `n`.) These two reflections combined give a 1/6 rotation (see below) hence 12 reflections cycle through all symmetries. ``` SYMMETRY EXAMPLE Start Flip Skew Flip Pattern Vertical Correction Diagonal 01 43 54 50 5 2 -> 5 2 -> 0 3 ------> 4 1 43 01 12 32 ``` Once the polyhex's coordinates under all 12 symmetry operations have been generated, the lexically lowest set of coordinates is added to the list of polyhexes. **Commented code (original version)** ``` f=->n,p=[[2,3]]{ #Assume initial hexes are at 2 and 3 if no info provided. s=p[0].size #Check size of first polyhex in list, others should be the same. d=[w=n*3,1,~w,-w,-1,-~w] #d contains offsets for the six possible directions of travel. w is the width of the grid. s<n ?(q=[] #If size of polyhex less than required n, make array q to hold new generation. p.map{|a| #Iterate through list p of previous generation polyhexes a. (s*36).times{|i|r=[];t=0 #Try adding a chain of two hexes in 6*6 possible directions to each existing hex. c=a+b=[g=a[i/36]+d[i/6%6],g+d[i%6]] #b contains the new hexes chained onto old hex a[i/36]. Add them to existing polyhex a to make new polyhex c. 12.times{|j|t+=a.count(b[j%2]+d[j/2]) #Iterate through 2 new hexes x 6 directions = 12 to find the number of edges shared with the old polyhex. c=c.map!{|k|j%2<1?k%w*(2+w)-k:k/w+k%w*w}. #Reflect the new polyhex... sort!.map{|m|m-c[0]+n} #...sort the coordinates, and adjust them so that the smallest equals n r<<c*1} #Add the current symmetry of the new polyhex to r (the c*1 ensures a new copy is added, not just a pointer) a&b==[]&&t>1&&q<<r.min #If new hexes b don't overlap old hexes a && there's more than one common edge add lowest value by symmetry to q } } f[n,q&q]):p(p.size) #q&q to remove duplicates. Recursively call to build next generation. If s already equal to n, output the total. } ``` ]
[Question] [ Let's define a *self-contained number* as a positive integer, whose digits appear in runs of length equal to themselves only. In other words, any decimal digit **d** (excluding **0**) occurs only in runs of length exactly **d**. # Task You can choose any of the three methods listed below: * Given an integer **n**, output the **n**th (either 0 or 1-indexed) self-contained number. * Given an integer **n**, output the first **n** self-contained numbers. * Print the sequence indefinitely. # Examples * **133322** is a self-contained number because **3** appears in a run of three **3**'s, **1** is single and **2** occurs in a run of two **2**'s. * On the other hand, **35553355** isn't, because, although **5** and **3** occur five and three times respectively, they do not form runs of adjacent digits. * **44422** is not self-contained, because **4** only occurs three times. * **12222333** isn’t either, because **2** appears in a run of four **2**'s, and it cannot be treated as two separate runs of two **2**'s. Not surprisingly, this is [OEIS A140057](https://oeis.org/A140057), and its first few terms are: ``` 1, 22, 122, 221, 333, 1221, 1333, 3331, 4444, 13331, 14444, 22122, 22333, 33322, 44441, 55555, 122122, 122333, 133322, 144441, 155555 ``` --- You can take input and provide output through any of [the standard methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages), while noting that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is code golf, so the shortest code in bytes (in every language) wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~104~~ ~~94~~ 83 bytes -10 bytes thanks to Mr. Xcoder -11 bytes thanks to Jonathan Allan ``` i=0 while 1: if`i`==''.join(d*int(d)for c,d in zip(`-i`,`i`)if d!=c):print i i+=1 ``` [Try it online!](https://tio.run/##DcxLCoAgFAXQuat4jdR@VEPh7UXIpBuhIkLU5s354aS3nDFstYIX8Zy4D1qNIHgLyyzlfEUE5XqEopz2MdM@OkKgD0nZCXZsUMOT63jXJuUGCS0YeK31Bw "Python 2 – Try It Online") [Answer] # Mathematica, 66 bytes Prints the sequence indefinitely ``` Do[##&&Print@t&@@(#==Tr[1^{##}]&@@@Split@IntegerDigits@t),{t,∞}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/98lP1pZWU0toCgzr8ShRM3BQUPZ1jakKNowrlpZuTYWKOAQXJCTWeLgmVeSmp5a5JKZnllS7FCiqVNdovOoY15t7P//AA "Wolfram Language (Mathematica) – Try It Online") In TIO you have to terminate the execution in order to see the result but in Mathematica works fine. -12 bytes from Martin Ender [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes Returns the nth term of the sequence, 1-indexed. ``` µNÔNγ€gJQ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/w1P8zm1@1LQm3Svw/39DIwA "05AB1E – Try It Online") **Explanation** ``` µ # loop over increasing N until counter equals input NÔ # push N with consecutive equal elements deduplicated Nγ # push N grouped into runs of consecutive equal elements €g # get the length of each run J # join to a number Q # check for equality # if true, implicitly increment counter ``` [Answer] # JavaScript (ES6), ~~76~~ ~~71~~ 68 bytes Returns the *n-th* term of the sequence, 0-indexed. ``` f=(n,k)=>+(k+'').replace(/(.)\1*/g,s=>s.length^s[0])||n--?f(n,-~k):k ``` *NB*: As always with recursive functions, the input range depends on Tail Call Optimization support and the stack size of your engine. ### Demo ``` f=(n,k)=>+(k+'').replace(/(.)\1*/g,s=>s.length^s[0])||n--?f(n,-~k):k for(n = 0; n <= 10; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` --- # Alt. version, 65 bytes Takes no input and prints the results with `alert()`, one at a time. ``` f=k=>f(-~k,+(k+'').replace(/(.)\1*/g,s=>s.length^s[0])||alert(k)) ``` [Try it online!](https://tio.run/##HcZBDoMgEADAe1/hzd2qaM8NfsS2CcGFtmzAsKQn069j4pzma35GbP5sZYhppVqdDnp2MPxD30Ho2hZVpo2NJRhB4eN2HX0vehbFFH15v2SZnrjvhikXCIj1XKMbm6IkJsXJ3y8OsB4 "JavaScript (Node.js) – Try It Online") (Stops as soon as the maximum stack size is exceeded.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` DŒrZEµ# ``` [Try it online!](https://tio.run/##y0rNyan8/9/l6KSiKNdDW5X//zc0AAA "Jelly – Try It Online") -4 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)'s early suggestion. -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). Takes input from STDIN. [Answer] # [CJam](https://sourceforge.net/p/cjam), 20 bytes ``` 1{_Abe`::=:*{_p}&)}h ``` [Try it online!](https://tio.run/##S85KzP3/37A63jEpNcHKytZKqzq@oFZNszbj/38A "CJam – Try It Online") Explanation: ``` 1 push 1 { }h while TOS is truthy (i.e. forever): example iteration: 14444 _ duplicate 14444 14444 Ab convert to base 10 (get decimal digits) 14444 [1 4 4 4 4] e` run-length encode (array of two-element arrays) 14444 [[1 1] [4 4]] : map over the array: : fold between the two array elements with: = equality 14444 [1 1] : fold between the array elements with: * multiplication (a.k.a. logical AND for 1 or 0) 14444 1 { }& if this yields a result of 1: _ duplicate the number and 14444 14444 p print it 14444 (output 14444) ) increment the number 14445 ``` [Answer] # [Haskell](https://www.haskell.org/), 70 bytes ``` import Data.List filter(all(\s->read[s!!0]==length s).group.show)[1..] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ≜ℕẹḅ⟨l=h⟩ᵐ ``` [Try it online!](https://tio.run/##ATMAzP9icmFjaHlsb2cy/37ihrDigoHhuoniiqX/4omc4oSV4bq54biF4p@obD1o4p@p4bWQ//8 "Brachylog – Try It Online") Infinitely [generates](https://codegolf.meta.stackexchange.com/a/10753/85334) elements of the sequence through its input variable. (If it actually has to do the printing itself, append `&ẉ⊥`.) This is essentially code to solve the corresponding [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") with a `≜` prepended to brute-force the smallest solutions first: ``` ᵐ For every ḅ run of ẹ digits in the input variable ℕ (which is a non-negative integer), ⟨l ⟩ its length ⟨ h⟩ and its first element ⟨ = ⟩ are equal. ``` I expected this to only take 9 bytes, but `ḅ` seems to require an explicit `ẹ` to separate the digits of a number into runs. [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç≡∟Öz≈¢αV¢ ``` [Run and debug it](https://staxlang.xyz/#p=80f01c997af79be0569b&i=&a=1) This program filters all positive integers with a filter. The digits are run-length encoded. For each run, the digit must equal the run length. [Answer] # JavaScript 4, ~~83~~ 80 bytes ``` for(i=0;;)+(++i+'').replace(/(.)\1*/g,function(x,y){return y^x.length})||alert(i) ``` ``` for(i=0;i<1000;)+(++i+'').replace(/(.)\1*/g,function(x,y){return y^x.length})||alert(i) ``` [Answer] # [Perl 6](http://perl6.org/), 49 bytes ``` {(grep /^((\d)$0*:<?{$/.comb==$0}>)+$/,^Inf)[$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiO9KLVAQT9OQyMmRVPFQMvKxr5aRV8vOT83ydZWxaDWTlNbRV8nzjMvTTNaJT629r@1QnFipUJuYgHQAB2FOFPr/wA "Perl 6 – Try It Online") Returns the `n`-th element of the sequence, zero-indexed. [Answer] # [R](https://www.r-project.org/), 56 bytes ``` function(n)all((r=rle(el(strsplit(c(n,''),''))))$l==r$v) ``` [Try it online!](https://tio.run/##FYlBCsMwDATvfUYIRAIdapkc/Zg0talBdYzsFvJ6RxkYBnZ1SH7ppidM39g/x7tN@EhhpF/Zez4KFNxEADSoRIgCrWurkjvsUGhZ8NaYJQSd/zjaVquc9j7JOfJ@9atBjpjJmcz36i3MVqSE4wI "R – Try It Online") Makes use of run length encoding on the split number. Returns true if all the lengths equal the values. Note: I have loaded the `methods` library in TIO to get `el` to work. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` fȯΛ§=L←gdN ``` [Try it online!](https://tio.run/##ASAA3/9odXNr/@KGkeKCgf9myK/Om8KnPUzihpBnZE7///8xMg "Husk – Try It Online") Returns an infinite list. `↑` is used to show first n elements since it times out. [Answer] # Pyth, 12 ``` .f.AqMr8jZ10 ``` [Test online!](https://pyth.herokuapp.com/?code=.f.AqMr8jZ10&input=9&debug=0) [Answer] # [Perl 5](https://www.perl.org/) `-p`, 48 bytes ``` ++$\=~s|(.)\1*|$1-length$&&&redo|gre for 1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/19bWyXGtq64RkNPM8ZQq0bFUDcnNS@9JENFTU2tKDUlvya9KFUhLb9IwVBPTyW@tvr/f0ODf/kFJZn5ecX/dX1N9QwMDf7rFgAA "Perl 5 – Try It Online") Returns the n-th element, 1 indexed. [Answer] # Java 10, 121 bytes A lambda from `int` to `int`. The function takes an index *n* and returns the *n*th (1-indexed) sequence value. ``` n->{int x=0,m=1;for(;n>0;n-=m,m=1)for(var p:(++x+"").split("(?<=(.))(?!\\1)"))m=p.length()==p.charAt(0)-48?m:0;return x;} ``` [Try It Online](https://tio.run/##ZY/NasMwEITP9lOoPq1ILGzooURxQikUCi09pLemB8WRHbn6MdI6pIQ8uyuTHAo97fDN7LLTiaPIu/332A87rWpSaxECeRPKknOa3GBAgXEcndoTEy3YoFe2/fwiwreBTsmki4fYgEqzZrA1KmfZi8Xnm15GLVvpV6Qh1Wjz1VlZJKeqmJuq5I3zwO2q4DavzEToRI7Ck34Bs9lplmWUhV4rhAzWywoYpbC@225LmlFqqp5paVs8AK2irg/CPyIUNL9/WJtFwb3EwVty4pcxSXgan938BJSGuQFZH5ugthDpnw4BvRRmarC5Ki9sK6Gck7KgUzRhRvQf7n3XQXMDtdNa1gj/rjxdDecDQ/eqAgKdVihPk0t6GX8B) ## Ungolfed ``` n -> { int x = 0, m = 1; for (; n > 0; n -= m, m = 1) for (var p : (++x + "").split("(?<=(.))(?!\\1)")) m = p.length() == p.charAt(0) - 48 ? m : 0; return x; } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Returns the `n`th term, 1-indexed. ``` Èì òÎeÈζXÊÃ}iU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yOwg8s5lyM62WMrDfWlV&input=OA) ``` Èì òÎeÈζXÊÃ}iU :Implicit input of integer U È :Function taking an integer X as argument ì : To digit array ò : Partition between elements where Î : The sign of their difference is truthy (not 0) e : All true È : When passed through the following function as X Î : First element ¶ : Is equal to XÊ : Length of X à : End function } :End function iU :Get the Uth integer that returns true ``` ]
[Question] [ Write a program to determine if a periodic sequence of positive integers has the property that, for every integer `n` occurring in the sequence, there are never more than `n` other integers between two consecutive occurrences of `n`. For example, `2, 3, 5, 2, 3, 6, 2, 3, 5, 2, 3, 6, ...` does have this property: every pair of consecutive occurrences of `2` have at most two integers between them (such as `2, 3, 5, 2` and `2, 3, 6, 2`; every pair of consecutive occurrences of `3` have at most three integers between them; and the same for `5` and `6`. However, `2, 3, 5, 2, 3, 4, 2, 3, 5, 2, 3, 4, ...` does not have this property: two consecutive occurrences of `4`, namely `4, 2, 3, 5, 2, 3, 4`, have more than four integers between them. **Input**: a reasonable representation of a periodic sequence of positive integers. For example, a finite list such as `{2, 3, 5, 2, 3, 6}` can represent the first infinite sequence `2, 3, 5, 2, 3, 6, 2, 3, 5, 2, 3, 6, ...` above. (For that matter, the problem could be stated for finite lists that wrap around instead of for infinite periodic lists.) **Output**: a truthy/falsy value. Truthy examples: ``` {1} {8, 9} {2, 3, 4} {5, 5, 3, 3, 6} {2, 3, 5, 2, 3, 6} {6, 7, 3, 5, 3, 7} {9, 4, 6, 7, 4, 5} {1, 1, 1, 1, 1, 100, 1} {1, 9, 1, 8, 1, 7, 1, 11} ``` Falsy examples: ``` {1, 2, 3} {2, 3, 9, 5} {3, 5, 4, 4, 6} {2, 3, 5, 2, 3, 4} {3, 5, 7, 5, 9, 3, 7} {5, 6, 7, 8, 9, 10, 11} {1, 9, 1, 8, 1, 6, 1, 11} ``` This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), so the shortest code wins. Answers in all languages are encouraged. [Answer] # [Python](https://docs.python.org), ~~57~~ 56 bytes -1 byte thanks to Dennis (replace `i+1:i+v+2` with `i:i-~v` with an `i` offset of 1 from `enumerate`) ``` lambda a:all(v in(a+a)[i:i-~v]for i,v in enumerate(a,1)) ``` **[Try it online!](https://tio.run/nexus/python3#bVDLCsIwEDybr9hjgiu02lcKXvyNmEPEFgNtlRo9@us1DxoiCMuwOzPsDtsfz8ugxstVgWrVMNA36ImqrWJCt3r3ecv@PoNGR0M3vcZuVqajCnPGFtM9zfN0Nzc4giAgRC6RAIgGgYduj3BAKMJQIpR@tlWlumX3KVsh1KtgsQ4st4usxWu2KQObI/xUllmIEvdk47EOhlw6VTjVHU1z8Lg13C7Cxb9Ri9RYe@Rp2nKN2oQUmT/9L1cVc0lC3Lf9W92/439bsnnMejJU9NSRDFZftEm2fAE)** Unnamed function taking a list, `a`, and testing the condition that each value, `v`, appears `in` the relevant slice to its right in a concatenation of `a` with itself, `(a+a)[i:i-~v]`, where the 1-based index of `v` in `a`, `i`, is provided by `enumerate(a,1)`. [Answer] ## Haskell, ~~60~~ ~~57~~ ~~56~~ 55 bytes ``` f(a:b)=b==[]||length(fst$span(/=a)b)<=a&&f b g x=f$x++x ``` Assumes that the input list contains at least one element. Usage example: `g [1]` -> `True`. [Try it online!](https://tio.run/nexus/haskell#bY7RCoMgFIbve4pzEVF0YFmaOeaTSBfGVguWi9VFF717U5GxwZCjfr/wfx59qs9dJjspVbvvj5sZ1nvaL2u8zNqkJ6mzLrtInSQ9dNEAm@zjLc@3Y9KjAQnXZwQwv0azQgyTnmEApUiLqkFh9xIrpPZkyOytwjpkDMtANXLPFXJLAim6hCKzRPCzigKJT4Slxg53KWnbf3pXHkTCFzkBddU/ehpeuB0RPsC8vnGawvV/K@ugPN4 "Haskell – TIO Nexus") Let `a` be the head of the list and `b` the tail. The result is `True` if `b` is empty or the number of elements at the beginning of `b` that are not equal to `a` is not greater than `a` and the recursive call of `f b` is also `True`, else `False`. Start with twice the input list. Edit: @Leo saved 3 bytes. Thanks! Edit 2: @Laikoni saved 1 byte. Thanks! [Answer] # JavaScript (ES6), ~~67 65 55 54 51~~ 49 bytes *Saved 3B thanks to @ETHproductions and 2B thanks to @Arnauld* ``` a=>!a.some((b,c)=>a.concat(a).indexOf(b,++c)>b+c) ``` # Explanation This defines a function that takes an array `a` as input. Then, the `.some` method iterates over that array, executing another function for every element. This inner function takes two arguments, `b` and `c`, the current value and its index. The function finds the index of the current value, starting from index `c + 1`. Then it checks if this index is greater than the current value plus the current index (the difference between two occurrences of the same value is greater than `b`). Note that this returns the exact opposite of what we want. If one of these return values is `true`, the `.some` function returns `true` as well. If none of the checks return `true`, the `.some` function returns `false`. Once again the opposite of the value we want to return, so this result is negated and then returned. # Test it Try all test cases here: ``` let f= a=>!a.some((b,c)=>a.concat(a).indexOf(b,++c)>b+c) let truthy = [[1], [8, 9], [2, 3, 4], [5, 5, 3, 3, 6], [2, 3, 5, 2, 3, 6], [6, 7, 3, 5, 3, 7], [9, 4, 6, 7, 4, 5], [1, 1, 1, 1, 1, 100, 1], [1, 9, 1, 8, 1, 7, 1, 11]]; let falsy = [[1, 2, 3], [2, 3, 9, 5], [3, 5, 4, 4, 6], [2, 3, 5, 2, 3, 4], [3, 5, 7, 5, 9, 3, 7], [5, 6, 7, 8, 9, 10, 11], [1, 9, 1, 8, 1, 6, 1, 11]]; console.log("Truthy test cases:"); for (let test of truthy) { console.log(`${test}: ${f(test)}`); } console.log("Falsy test cases:"); for (let test of falsy) { console.log(`${test}: ${f(test)}`); } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṣZL ;çЀ<‘P ``` [Try it online!](https://tio.run/nexus/jelly#bU45DgIxDOz3FX6Ai2TJKehpKKiJ8hdEQ0tJT0HDB6jzkt2PBGOzUZBWskb2zMgzdXo/TodhW57lNl9eu/l8P9ZypZVmX2tKSWccAFJAiLKNCBsEI4dFsHzTuF4nduxZh@AXgdALG@kRWVijxQqrEf5GKYImRSYDoxeDzgNkTD/DN7evEttjiTcSutrW9EbPGPvCdmkbpIji9LVqrlXL@QM "Jelly – TIO Nexus") ### How it works ``` ;çЀ<‘P Main link. Argument: A (array) ; Concatenate A with itself. çD€ For each n in A, call the helper with left arg. A + A and right arg. n. ‘ Increment all integers in A. < Perform element-wise comparison of the results to both sides. P Take the product of the resulting Booleans. ṣZL Helper link. Left argument: A. Right argument: n ṣ Split A at all occurrences of n. Z Zip to transpose rows and columns. L Length; yield the number of rows, which is equal to the number of columns of the input to Z. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ṙJḣ"‘Œpċ ``` Insipred by [@JonathanAllan's Python answer](https://codegolf.stackexchange.com/a/113880/12012). [Try it online!](https://tio.run/nexus/jelly#bU67DQIxDO1vCovaRXLkOwESK0TZgREQDQUdFdS0DAA1xyB3iwRjc1GQTrKe7Pee/F4Zn9ft@Litpv3lfd4Np/I6Toc7zaaUlJLO2AGkgBBl6xHWCEYOi2D5pnGtTmzfsg7BzwKhFzbSI7KwRosVViP8jVIEVYpMBkYvBp07yJh@hm9uWyXWxxJvJHSxrWmNnjG2he3cNkgRxelL1VytlvMH "Jelly – TIO Nexus") ### How it works ``` ṙJḣ"‘Œpċ Main link. Argument: A (array) J Yield the indicies of A, i.e., [1, ..., len(A)]. ṙ Rotate; yield A, rotated 1, ..., and len(A) units rotated to the left. ‘ Increment; add 1 to all elements of A. ḣ" Head zipwith; truncate the n-th rotation to length A[n]+1. Œp Take the Cartesian product of all resulting truncated rotations. ċ Count the number of times A appears in the result. ``` [Answer] # SWI-Prolog, 83 bytes ``` a(L,[H|R]):-nth0(X,R,H),H>=X,a(L,R);length(R,N),nth0(X,L,H),H>=N+X,a(L,R). a(_,[]). ``` The list should be entered twice: ``` a([1,2,3],[1,2,3]). ``` If this is not considered acceptable, you may add the predicate ``` a(L):-a(L,L). ``` which adds an extra 14 bytes. [Try it online](http://swish.swi-prolog.org/p/zXEqMJos.pl) nb: you may test for different false cases at once by separating your queries with ';' (or) and test for different true cases by separating with ',' (and) ie, using the OP examples : ``` a([1],[1]), a([8, 9],[8, 9]), a([2, 3, 4],[2, 3, 4]), a([5, 5, 3, 3, 6],[5, 5, 3, 3, 6]), a([2, 3, 5, 2, 3, 6],[2, 3, 5, 2, 3, 6]), a([6, 7, 3, 5, 3, 7],[6, 7, 3, 5, 3, 7]), a([9, 4, 6, 7, 4, 5],[9, 4, 6, 7, 4, 5]), a([1, 1, 1, 1, 1, 100, 1],[1, 1, 1, 1, 1, 100, 1]), a([1, 9, 1, 8, 1, 7, 1, 11],[1, 9, 1, 8, 1, 7, 1, 11]). ``` and ``` a([1, 2, 3],[1, 2, 3]); a([2, 3, 9, 5],[2, 3, 9, 5]); a([3, 5, 4, 4, 6],[3, 5, 4, 4, 6]); a([2, 3, 5, 2, 3, 4],[2, 3, 5, 2, 3, 4]); a([3, 5, 7, 5, 9, 3, 7],[3, 5, 7, 5, 9, 3, 7]); a([5, 6, 7, 8, 9, 10, 11],[5, 6, 7, 8, 9, 10, 11]); a([1, 9, 1, 8, 1, 6, 1, 11],[1, 9, 1, 8, 1, 6, 1, 11]). ``` [Answer] # PHP, 52 bytes ``` for(;$n=$argv[++$i];$$n=$i)!$$n|$i-$$n<$n+2?:die(1); ``` takes sequence from command line arguments; exits with code `1` for falsy, `0` for truthy. Run with `-nr`. * loop `$n` through arguments: + if there was no previous occurence or it was recent enough then do nothing, else exit with code `1` + remember previous occurence in `$$n` ([variable variables](http://php.net/manual/language.variables.variable.php)) * exit with code `0` (implicit) [Answer] ## [Retina](https://github.com/m-ender/retina), 50 bytes ``` $ ,$` M!&`\b(1+),.*?\b\1\b +%`(^1*)1,1+ $1 M`1, ^0 ``` Input as a list of comma-separate unary numbers. [Try it online!](https://tio.run/nexus/retina#TczbCcMwDAXQf21RcIoTX4oVv@KvTpANTDCh@6@QyiqBYoR1hXQm29vHkVkuQzCd9sezt9Oym/Fa3u1s3E5yU7cHLzODZZVp7ww6/HUxbai0IiBSQpI/IGtOWLXPKJoCClVEjByRSKj7eQ@WXKXfpMqYjYEASlVZH0Qc53941GmRqsonxbcB@Z9wk1nJLw "Retina – TIO Nexus") ### Explanation ``` $ ,$` ``` Duplicate the input so we can check steps that wrap around the end. ``` M!&`\b(1+),.*?\b\1\b ``` Match and return each (shortest) section between two identical values, e.g. `11,111,1,11`. ``` +%`(^1*)1,1+ $1 ``` Repeatedly remove a digit from the first number, together with an entire number after it. If the gap is small enough this will completely remove the first number. Otherwise, at least one digit will remain. ``` M`1, ``` Count how often `1,` appears in all the lines. If it appears anywhere, one of the steps was too wide. ``` ^0 ``` Try to match a number starting with `0` (i.e. only `0` itself). This is effectively a logical negation of the output. [Answer] ## JavaScript (ES6), 47 bytes ``` a=>![...a,...a].some((n,i)=>a[-n]-(a[-n]=i)<~n) ``` ### How it works We re-use the input array `a` to store the position of the last encountered occurrence of each integer in `a`. We use the key `-n` to store this position so that it does not interfere with the original indices of `a`. When `a[-n]` exists, the actual test occurs. When `a[-n]` doesn't exist, the expression `a[-n] - (a[-n] = i)` equals `undefined - i == NaN` and the comparison with `~n` is always falsy, which is the expected result. ### Test cases ``` f= a=>![...a,...a].some((n,i)=>a[-n]-(a[-n]=i)<~n) console.log('Truthy cases:'); console.log(f([1])); console.log(f([8, 9])); console.log(f([2, 3, 4])); console.log(f([5, 5, 3, 3, 6])); console.log(f([2, 3, 5, 2, 3, 6])); console.log(f([6, 7, 3, 5, 3, 7])); console.log(f([9, 4, 6, 7, 4, 5])); console.log(f([1, 1, 1, 1, 1, 100, 1])); console.log(f([1, 9, 1, 8, 1, 7, 1, 11])); console.log('Falsy cases:'); console.log(f([1, 2, 3])); console.log(f([2, 3, 9, 5])); console.log(f([3, 5, 4, 4, 6])); console.log(f([2, 3, 5, 2, 3, 4])); console.log(f([3, 5, 7, 5, 9, 3, 7])); console.log(f([5, 6, 7, 8, 9, 10, 11])); console.log(f([1, 9, 1, 8, 1, 6, 1, 11])); ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~41~~ 39 bytes *2 bytes golfed thanks to Martin Ender, which by the way introduced me to balancing groups with his [fantastic guide on SO](https://stackoverflow.com/a/17004406/7161497)* ``` $ ,$`, ((1)+,)(?=(?<-2>1+,)*(\1|$)) ^$ ``` Input is a comma-separated list of unary numbers. Output is `0` for false and `1` for true. [Try it online!](https://tio.run/nexus/retina#TcxrCgIxDATg/zlHhXZ3hL4foO5FiiziMbz7mkQUKaGZof1Odp/PlcxyGILZQfNhbXArnN2udruc4y1wWOwML@Mc0d0cR6COQREJmQoK3wlVc0HUvaJpSmg0kCE5o1DA73iPwHnw3nmadFIwoNTg50Jk@f6HZ20bz1C@KN4F8h/hS1Yl3w "Retina – TIO Nexus") (Test suite that automatically converts from decimal) I've recently learned about balancing groups, so I wanted to give them a try. They're not among the easiest tools to use, but sure they are powerful. ### Explanation ``` $ ,$`, ``` As many other submissions do, we duplicate the list to deal with wrapping. We also add a comma at the end, so every number is followed by a comma (this makes things a bit easier later) ``` ((1)+,)(?=(?<-2>1+,)*(\1|$)) ``` Here's where things get interesting. This is a replacement stage, we replace everything matched by the first line with the second line, in this case we are looking to remove all numbers `n` not followed by `n+1` other different numbers. To do so, we first match the number, capturing each `1` in a group (capturing group number 2 in this case). Then with a positive lookahead, in order to have a zero-width assertion, we repeatedly try to match in a balancing group `-2`, that will succeed no more than the number of captures made by group `2`, a number followed by a comma. After this sequence of numbers, we are satisfied if we reach either the first number again or the end of the line. Note: this expression could match just the final part of a number, if it doesn't manage to find a match with the full number. This is not a problem, because then the first part of the number will remain in the string and we will know that the replacement didn't completely succeed. ``` ^$ ``` Finally, the result should be truthy iff we have completely removed all numbers from the list. We try to match the empty string and return the number of matches found. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ẋ2ĠṢI_2<"QȦ ``` [Try it online!](https://tio.run/nexus/jelly#bU67DUIxDOzfFBa1iyTkK9EjSuooYhcaCpZAFFQsAC0UrPFYJBibFwXpSdbJvjv5ro73o3mextt5szOrxfZ1qY/De3@lWdeac9YFB4AcEZJsBmGJYOVwCI5vGt/rxJqe9QhhEgiDsIkekYU1WpywGuFvlCJoUmIyMgYx6DJAwfwzfHP7Kqk9lngrobNtbW8MjKkv7Ka2UYooTp@r5lu1Uj4 "Jelly – TIO Nexus") ``` ẋ2ĠṢI_2<"QȦ Main link. Argument: A (array) ẋ2 Repeat A twice to account for wrap-around. Ġ Group all indices of A + A by their respective values, sorting the index groups by the associated values. Ṣ Sort the groups lexicographically, i.e., by first appearance in A. I Increments; compute the forward differences of adjacent indices in each of the groups. _2 Subtract 2 from the differences. Q Unique; yield A, deduplicated. <" Compare all differences in the index group corresponding to the n-th unique value in A with the n-th unqiue value in A. Ȧ All; yield 1 if and only if none of the comparisons returned 0. ``` [Answer] # [Python 3](https://docs.python.org/3/), 101 bytes ``` lambda l:all(v>=(l[i+1:].index(v)if v in l[i+1:]else len(l[i+1:])+l.index(v))for i,v in enumerate(l)) ``` [Try it online!](https://tio.run/nexus/python3#jVDLbsMgELz7K1Y5gUIiO/ULS86PuD5QBVQkTCuHWImifLvDwy6t2kMRWpaZYXdY0b7Oig1vJwaqYUqh6dgi1clt1vR7qU/8iiYsBUwgNSw4V2cOiutVh7fqS4rFxwiSeDnXl4GPzHCkMJ7NeDHvN2ih67KeQFcToO48EHghkLu0IFD4m91l5Cx2iFhJoFphGyuHUVvA0p6xSeGwjMCPnaY2LAT1UO1jFeis7xPB1PkGwWLoGU3QpWxonIeGf3jMo6jykUabxeqxDhZS3/e3pfKbJTtO44YZxtckYNfnKLVBm/sDdke4PzZ7qxqYQYaAQAZjnAQFjs/91/75en4C "Python 3 – TIO Nexus") [Answer] # [Röda](https://github.com/fergusq/roda), 50 bytes ``` f a{seq 0,#a-1|[indexOf(a[_],a[_1+1:]..a)<=a[_1]]} ``` [Try it online!](https://tio.run/nexus/roda#TYxNasMwEIXX1ikGdWPTSbDi/1AfoBTqTXeuMSKWi8CRXcuLQpJe3ZVkGoKY0bw38761B37R4htCfOI7dq2l6sRP1fu8bhs0jT2zY7Pf8@CltKppbuuZSwUX4vXjDINUArqReJ6bfkugn4oiUGqsReilPXEt4FhCradBLr49Q9BiKinSAK4w8VmLV7WILzFD25iY7KH379lgw3vTLNUCtHqzZDFo8WC@Vx@wLbpRmYXrt5WRHAtywAhjkmBi/ghTpxM8uDnFzKkIM1JgjFbHmBCG9xeGyIwuzJybyqxnDQNwqMKcW0Rs4w/w2LmZqcLhEwfPLSjcCP/I1CH/AA "Röda – TIO Nexus") Finally! I have been [waiting](https://codegolf.stackexchange.com/a/112982/66323) [for](https://codegolf.stackexchange.com/a/113265/66323) this challenge... It's a function that returns a truthy or a falsy value. It takes one argument, the array. It iterates over a stream of indices and checks for each index `_1` that the distance of the current index and the next index of `a[_1]` is not more than `a[_1]`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ƛ?=T¯‹≤A;A ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGmz89VMKv4oC54omkQTtBIiwiIiwiWzEsIDksIDEsIDgsIDEsIDcsIDEsIDExXSJd) ``` ƛ ;A # Does every value have the property that... A # All of... ¯ # The differences between... ?=T # Indices of that value in the input ‹ # Minus 1 ≤ # Are at most that value? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` Dì©v®¦©yky›_P ``` [Try it online!](https://tio.run/nexus/05ab1e#@@9yeM2hlWWH1h1admhlZXblo4Zd8QH//0db6iiY6CiY6SiYgxmmsQA "05AB1E – TIO Nexus") or as a [Test suite](https://tio.run/nexus/05ab1e#qymrVKquVdJV0lFQOrQwNOK/y@E1h1aWHVp3aNmhlZXZlY8adsUH/K@NUDq830rh8H4lnf/VhrVc1RY6CpZAykhHwVhHwQTIMtVRMAVzgMgMLgMUMoILmekomMNEgaQ5UMgSqBkoCZYAMkyBQoY6CijIwABIQMQtwSIWYNIcIguVAVkCt9QSYhDEIhOIDZguMoErMQeTlnBHmcJcZAGx0gBhD7ILzGAuAAA) **Explanation** ``` Dì # duplicate input and prepend the copy to the original © # store a copy in the register v # for each element in the list ® # push the list from register ¦© # remove the first element and store a copy in the register yk # get the index of the current element in the list y›_ # check if it's less than or equal to the current element P # product of stack ``` ]
[Question] [ # Objective Given an input list of `6` distinct digits, find 3 numbers `a`, `b` and `c` such that `a × b = c`, with `a` having 2 digits, `b` having 1 digit and `c` having 3 digits. In a more visual way, your program must arrange those 6 digits in the boxes of this image: [![enter image description here](https://i.stack.imgur.com/3veFP.jpg)](https://i.stack.imgur.com/3veFP.jpg) If more than one solution exists, you may output any of them. # Input 6 distinct digits. You may take them in any reasonable way for your language. # Output The 3 numbers `a`, `b` and `c`. The output format is relatively free, as long as the 3 numbers are separated and are always printed in the same order (but not necessarily in the order `a, b, c`). # Test Cases ``` 1, 2, 3, 4, 5, 6 -> 54,3,162 2, 3, 4, 5, 6, 7 -> 57,6,342 or 52,7,364 ``` # Scoring The shortest code in bytes wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 10 bytes ``` p~c₃o.k×~t ``` [Try it online!](https://tio.run/nexus/brachylog2#@19Ql/yoqTlfL/vw9LqS///NjIz/RwEA "Brachylog – TIO Nexus") Far too slow to run in a reasonable length of time (the Brachylog interpreter spends a long time doing multiplications on empty strings, 4-digit numbers, negative numbers etc. using a very slow constraint solver). The TIO link uses an input with only 3 digits (this program can handle input with any number of digits). This is a function whose input is a number containing all the digits required (e.g. `234567`) – the lack of duplicates in the input means that you can always just put any `0` at the end to avoid a leading zero – and whose output is a list in the order `[b, a, c]` (e.g. `[6, 57, 342]`). ## Explanation ``` p~c₃o.k×~t p Permute the digits of the input ~c₃ Split them into three groups o Sort the three groups . to produce the output, which must have the following property: k all but the last group × when multiplied together ~t produces the last group ``` So where did the requirement on the groups to be 2, 1, and 3 digits go? Well, we know there are 6 digits in the input, and the groups are in sorted orders. The only possible sizes they can have, therefore, are [1, 1, 4], [1, 2, 3], or [2, 2, 2]. The first case is impossible (you can't multiply two 1-digit numbers to produce a 4-digit number, as 9×9 is only 81), as is the last case (you can't multiply two 2-digit numbers to produce a 2-digit number, as even 10×10 produces 100). Thus, the return values `[b, a, c]` must be 1, 2, and 3 digits long in that order, so `a` is 2 digits, `b` is 1 digit, and `c` is 3 digits, as requested. [Answer] ## JavaScript (ES6), ~~90~~ 88 bytes Takes input as an array of 6 digits. Returns a string describing a possible solution (such as `'54*3==162'`) or exits with a 'too much recursion' error if (and only if) there's no solution. ``` f=(a,k=1)=>eval(s='01*2==345'.replace(/\d/g,n=>a[n],a.sort(_=>(k=k*2%3779)&2)))?s:f(a,k) ``` ### How it works This is a deterministic algorithm. The primes `P=2` and `Q=3779` were chosen in such a way that the sort callback `(k = k * P % Q) & 2` is guaranteed to generate all 720 possible permutations of the input array over time. More precisely, all permutations are covered after 2798 sorts -- which should be within the recursion limit of all browsers. We inject each permutation in the expression `01*2==345` by mapping the digits to the corresponding entries in the array. We evaluate this expression and do recursive calls until it's true. ### Test ``` f=(a,k=1)=>eval(s='01*2==345'.replace(/\d/g,n=>a[n],a.sort(_=>(k=k*2%3779)&2)))?s:f(a,k) console.log(f([1,2,3,4,5,6])); // 54*3==162 console.log(f([2,3,4,5,6,7])); // 52*7==364 console.log(f([1,2,3,4,6,7])); // 73*2==146 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` p~c[Ċ,I,Ṫ]cᵐ.k×~t ``` [Try it online!](https://tio.run/nexus/brachylog2#@19Qlxx9pEvHU@fhzlWxyQ@3TtDLPjy9ruT//2gjHWMdEx1THTMd89j/UQA "Brachylog – TIO Nexus") ### Explanation ``` p Try a permutation of the Input ~c[Ċ,I,Ṫ] Deconcatenate it; the result must be a list of the form [[_,_],_,[_,_,_]] cᵐ. Output is the list of integers you get when mapping concatenate on the previous list k×~t The first two ints of the Output, when multiplied, result in the third int of the Output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 13 bytes Saved two bytes thanks to *Emigna*! ``` œJvy3L£Â`*Qi, ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@390sldZpbHPocWHmxK0AjN1/v@PNtJRMNZRMNFRMNVRMNNRMI8FAA "05AB1E – TIO Nexus") Explanation: ``` œ # Get all permutations of the input J # Join them to get the numbers vy # For each element in the list.. 3L # Push the list [1, 2, 3] £ # Pops a and pushes [a[0:1], a[1:3], a[3:6]] Â` # Bifurcate and flatten * # Multiply the top two elements in the stack Qi # If equal to the third element.. , # Print the array ``` [Answer] # Bash + coreutils, 70 ``` for((b=1;b;));{ a=`shuf -ze $@` b=${a:0:2}*${a:2:1}-${a:3:3} } echo $b ``` No particularly easy way to generate all the permutations. Instead randomly generate permutations and calculate until we find a good one. Output is in the form `A*B-C` - i.e. the expression that will evaluate to zero when we have the correct permutation. [Try it online](https://tio.run/nexus/bash#@5@WX6ShkWRraJ1kralpXc2VaJtQnFGapqBblaqg4pDAlWSrUp1oZWBlVKsFYhhZGdbqghjGVsa1XLVcqckZ@QoqSf///zdSMFYwUTBVMFMw/5qXr5ucmJyRCgA). [Answer] # [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` qm!{3/)2/+:i}%{(\:*=}=p ``` [Try it online!](https://tio.run/nexus/cjam#@1@Yq1htrK9ppK9tlVmrWq0RY6VlW2tb8P@/oZGxiakZAA "CJam – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 105 bytes ``` lambda s:[(x[0],x[1:3],x[3:])for x in permutations(s)if eval('%s*%s%s==%s%s%s'%x)] from itertools import* ``` [Try it online!](https://tio.run/nexus/python2#FcVLCsMgEADQfU8xG1FDF23TDwiexLqwNMJAdMSZFG@fks172b/3NZXPNwG7YEa4xPMIVzcfzS7aTB0GYIW29LJJEqTKhi1mWH5pNVrxpFix94eKtRo2nnKnAihLF6KVAUujLtPeOlYx2WBtmxhr7a5v8/3xfOk/ "Python 2 – TIO Nexus") # 88 bytes solution with a more *flexible* output ``` lambda s:[x for x in permutations(s)if eval('%s*%s%s==%s%s%s'%x)] from itertools import* ``` [Try it online!](https://tio.run/nexus/python2#FcRLCgMhDADQfU@RjWhm2S8UPEnbhaUKATWSZIq3t/QtXonPVVN7fxLo/TGhsMAE6jCytN2SEXcNilQgf1MN3unm1GmM/516N/F1KMINyLIYc1WgNlhsW0OoWyiB@tgtIOLyx9P5cr35Hw "Python 2 – TIO Nexus") where the output would be ['6', '5', '7', '3', '4', '2'] instead '6', '57', '342' [Answer] # PHP, 110 bytes It'll get there... eventually... ``` <?$v=$argv;unset($v[0]);do shuffle($v)&[$a,$b,$c,$d,$e,$f]=$v;while("$a$b"*$c!="$d$e$f");echo"$a$b $c $d$e$f"; ``` Ungolfed: ``` <? $v=$argv; unset($v[0]); do shuffle($v); [$a,$b,$c,$d,$e,$f]=$v; while("$a$b"*$c!="$d$e$f"); echo"$a$b $c $d$e$f"; ``` [Answer] # PHP, 77 bytes ``` for(;;)eval(strtr('0.*1-"428"||die("0.,1,428");',1/7,str_shuffle($argv[1]))); ``` Takes input as a string. [Answer] # [Pip](https://github.com/dloscutoff/pip), 18 bytes 17 bytes of code, +1 for `-S` flag. ``` $/_=1FI_^@3,5MPMa ``` Takes input as a string of digits via command-line argument. Output is in the order c, b, a. [Try it online!](https://tio.run/nexus/pip#@6@iH29r6OYZH@dgrGPqG@Cb@P//fyNjE1Mz8/@6wQA "Pip – TIO Nexus") This code outputs *all* solutions if multiple exist. If it is required to output only *one* solution, then add three bytes and wrap the program in `(...0)`. ### Explanation ``` a is 1st cmdline arg (implicit) PMa Compute all permutations of a M To each, map this function: 3,5 Range(3,5)--contains values 3 and 4 _^@ Split the function argument at those indices This transforms a string like 342657 into a list [342; 6; 57] FI Now filter the list of split permutations on this function: $/_ Fold on division: takes 1st element and divides it by the rest =1 Compare the quotient with 1 This keeps only the permutations where the first number is the product of the other two Autoprint the list (implicit), with each sublist on a separate line and space-separated (-S flag) ``` [Answer] ## Ruby, 60 bytes ``` ->x{x.permutation{|a|(eval a="%d%d*%d==%d%d%d"%a)&&puts(a)}} ``` Prints all solutions as "a\*b==c" ### Example: ``` ->x{x.permutation{|a|(eval a="%d%d*%d==%d%d%d"%a)&&puts(a)}}[[1,2,3,4,5,6]] 54*3==162 ->x{x.permutation{|a|(eval a="%d%d*%d==%d%d%d"%a)&&puts(a)}}[[2,3,4,5,6,7]] 52*7==364 57*6==342 ``` [Answer] # ES6 (Javascript), ~~85~~, ~~82~~, 79 bytes Accepts an array of digits (strings), returns a 3-element array `[A,B,C]` => `C=A*B` **Golfed** ``` R=(w,[a,b,c,d,e,f]=w)=>f*(d+=e)^(a+=b+c)?R(w.sort(_=>Math.random()-.5)):[a,d,f] ``` EDITS: * Saved 3 more bytes by reusing `d` and `a`, and getting rid of `==` (Thanks @Arnauld !) * Saved 3 bytes using destructuring assignment **Try It !** ``` R=(w,[a,b,c,d,e,f]=w)=>f*(d+=e)^(a+=b+c)?R(w.sort(_=>Math.random()-.5)):[a,d,f]; function generate(A) { console.log(R([...A])); } ``` ``` <input type="text" id="A" value="123456"/><button onclick="generate(A.value)">GENERATE</button> ``` [Answer] ## Batch, 305 bytes ``` @echo off set/pd= for /l %%i in (0,1,719)do set n=%%i&call:c exit/b :c set t=%d% set s= for /l %%j in (6,-1,1)do set/ap=n%%%%j,n/=%%j&call:l set s=%s:~0,2%*%s:~2,1%-%s:~3% set/an=%s% if %n%==0 echo %s% exit/b :l call set u=%%t:~%p%%% call set s=%%s%%%%u:~,1%% call set t=%%t:~,%p%%%%%u:~1%% ``` Takes input on STDIN as a string `[1-9]{6}` and outputs all solutions in `dd*d-ddd` format. Batch isn't very good at string manipulation so generating the 720 permutations is a little awkward. ]
[Question] [ ## Background Programmers these days can't seem to keep their buffers straight! A common source of error is trying to use an array index that is too large for the buffer. Your task is to implement a buffer where large indices are reduced to a size that the buffer can handle. Because I decide exactly what's best for everyone, you will implement this buffer to my precise specifications. ## Overview You have a insert-only buffer that grows in size as elements are added to it. The buffer is zero-indexed, and also indexed *modulo* its current size. The special rule for this challenge is this: * **To insert an item at index *i* means to compute *j*, `j = i % buffer.length()` and insert the new item after the *jth* item in the list.** The only special case is if the buffer is empty, as arithmetic modulo zero doesn't work. Thus, if the buffer is currently empty, the new item will be index *0*. If the buffer has only one item, then you are always inserting after the *0th* item. This is just one instance of the general case. If the buffer contains 6 items: `[4, 9, 14, 8, 5, 2]` and you are told to insert a new item `10` at index *15*, you find that `15 % 6 == 3`, and then insert the new `10` after the `8` at index *3* which gives a resulting buffer of `[4, 9, 14, 8, 10, 5, 2]` ## Problem Write a function or program that takes in an ordered list of positive integers, and positive integer indices at which to insert them. Start with an empty buffer, and add the specified integers to the buffer at the corresponding indices. Output the ordered list of integers that are in the buffer after all the specified insertions have been made. This is a code-golf challenge, so shortest code wins. ## Input guidelines You may take the input lists however you see fit. Examples: * List of pairs: `[ [1,1], [2,4], [3,9], [4,16], [5,25]...]` * Item list and index list: `[1, 2, 3, 4, 5...], [1, 4, 9, 16, 25]` * Flattened: `[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 ...]` * etc. You may assume the input always contains at least one item and corresponding index. ## Test cases Squares case from above: ``` [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64)] -> [1, 2, 8, 7, 6, 5, 4, 3] ``` I generated these randomly: ``` [(11, 9), (13, 14)] -> [11, 13] [(1, 18), (11, 7), (3, 35), (16, 22)] -> [1, 11, 16, 3] [(3, 16), (16, 37), (0, 28), (18, 24)] -> [3, 18, 0, 16] [(7, 26), (8, 20), (11, 39), (1, 23), (17, 27)] -> [7, 8, 11, 1, 17] [(15, 35), (17, 7), (16, 15), (1, 13), (2, 6), (11, 34)] -> [15, 17, 1, 2, 16, 11] [(2, 13), (1, 20), (16, 25), (8, 21), (5, 2), (16, 37), (3, 0)] -> [2, 3, 8, 1, 16, 5, 16] [(6, 20), (15, 15), (12, 26), (10, 27), (17, 13), (7, 18), (4, 16)] -> [6, 10, 17, 12, 7, 4, 15] [(18, 9), (5, 34), (15, 4), (12, 29), (2, 5), (7, 0), (7, 10), (16, 38)] -> [18, 7, 15, 2, 16, 5, 7, 12] [(0, 12), (12, 0), (4, 16), (15, 12), (6, 28), (8, 10), (11, 24), (0, 25)] -> [0, 11, 8, 6, 15, 0, 4, 12] [(6, 12), (14, 13), (10, 33), (11, 35), (1, 3), (0, 28), (15, 27), (8, 10), (1, 2)] -> [6, 14, 10, 1, 11, 8, 15, 0, 1] [(2, 29), (19, 30), (18, 17), (13, 3), (0, 21), (19, 19), (11, 13), (12, 31), (3, 25)] -> [2, 13, 3, 11, 0, 12, 19, 18, 19] ``` ## Python3 reference implementation ``` def f(inputs): # `inputs` is a list of pairs buff = [] for item, index in inputs: if len(buff) == 0: buff.insert(0, item) else: insert_after = index % len(buff) buff.insert(insert_after+1, item) return buff ``` [Answer] # Perl, 37 bytes 35 bytes of code + 2 bytes for `-lp` flags. ``` splice@F,1+<>%(@F||1),0,$_}{$_="@F" ``` [Try it online!](https://tio.run/nexus/perl#FclLCsIwFEbh@b@K24egGCE3QbSgklG2UUoNtDTYoO2gWNceGzij7xRZcG9PJx9Q0NgJWsaZmnaaG@8Xan3fDu5JU@fI968hi5@wkTNW8PH22O2NXVc@CCnK@vct63tubB6jgqrAFbQEX8EXsIaGhOKkKU7ECpq3oc74Aw "Perl – TIO Nexus") The implementation is quite straight forward, `splice` inserts in array `@F` at index `1+<>%(@F||1)` (note that `@F||1` handles the case of the array being empty). Just a few words about the (seemingly) unmatched braces `}{` (because I had a comment about it, and I think it's quite weird for people who don't know Perl), and it's a quite common trick in Perl golfings: `-p` flag surrounds the code with (roughly) `while(<>){ CODE } continue { print }`, (the `continue` is executed after each iteration). So with those *unmatched* `}{`, I change my code to `while(<>) { CODE}{ } continue { print }`. So it creates an empty block right after my code (but that's not a problem), and the `continue` is executed only once, after the `while` (ie. when the all the input has been read). [Answer] # ES6 (Javascript), ~~58~~,~~57~~,~~53~~, 50 bytes **Golfed** ``` a=>a.map((e,i)=>b.splice(1+e[1]%i,0,e[0]),b=[])&&b ``` Takes an array of index-value pairs, as input. EDITS * Use `&&` to return value, -1 byte * Removed `|0` (as splice apparently can handle NaN just well), -2 bytes * Made `b=[]` a second "argument" to *map()*, -2 bytes (Thx @ETHproductions !) * Replaced b.length with map() index (i), -3 bytes (Thx @Patrick Roberts !) **Test** ``` F=a=>a.map((e,i)=>b.splice(1+e[1]%i,0,e[0]),b=[])&&b F([[11, 9], [13, 14]]) [ 11, 13 ] F([[2, 29], [19, 30], [18, 17], [13, 3], [0, 21], [19, 19], [11, 13], [12, 31], [3, 25]]) [ 2, 13, 3, 11, 0, 12, 19, 18, 19 ] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~70~~ 69 bytes ``` b!(x,i)|b==[]=[x]|j<-1+i`mod`length b=take j b++x:drop j b foldl(!)[] ``` [Try it online!](https://tio.run/nexus/haskell#HYw7DoMwEER7TjFIKWyxFHwTovgkliWwIMSEnxAFBXcn61T79GZ2LhuKg5w8rVLaKH2Yc3jFSeTqaWnrsZv7/QOr9ubbYYCNouPZbsvqOejVexnbUYRSm2tq3AyFdXPzjht6aJEQEkkQKSH3NyNUEgw5B6U3BSEtPJSE7G/u3K08PAhlLg2COIbmJR5hxTFX@Y0nMnP9AA "Haskell – TIO Nexus") Usage: `foldl(!)[] [(1,5),(2,4),(3,7)]`. Saved one byte thanks to @nimi! Explanation: ``` b!(x,i) -- b!(x,i) inserts x into list b at position i+1 | b==[] = [x] -- if b is empty return the list with element x | j <- 1 + i `mod` length b -- otherwise compute the overflow-save insertion index j = take j b ++ x : drop j b -- and return the first j elements of b + x + the rest of b foldl(!)[] -- given a list [(1,2),(3,5),...], insert each element with function ! into the initially empty buffer ``` --- Solution without computing the modulus: (90 bytes) ``` f h t(x,-1)=h++x:t f h[]p=f[]h p f h(c:t)(x,i)=f(h++[c])t(x,i-1) g((x,_):r)=foldl(f[])[x]r ``` [Try it online!](https://tio.run/nexus/haskell#HYy9DoMwEIN3nsJDh5w4Bn5bkPIkUVRVVEAkShHKwNtTp9P5bH@@JiyI5tSiFLvk@TnEjJbzu52cX7Cnz4xDFHaC2Mmw5EYviQmEstlQPWU4GH7X92rIiTv9cX1eYYPFfoQt4oYZzpSKUhSmUjTp1opeQNEw6JLTKqo2iU5R/507u30SD0XXiEdWFHBc4ggtxqwS40Ttrx8) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~24~~ 22 bytes ``` "N?@2)yn\Q:&)@1)wv}@1) ``` Input is a matrix (with `;` as row separator) containing the values in the first row and the indices in the second. Output is a column array, displayed as numbers separated by newlines. [**Try it online!**](https://tio.run/nexus/matl#@6/kZ@9gpFmZFxNopabpYKhZXlYLJP//jzZSMLRUMLRQMDRWMAAzDRUMjRSMrRWMLBWMgSLmCsYKRoZgGWMFY0MFI9NYLgA) Or [**verify all test cases**](https://tio.run/nexus/matl#JVC7TsQwEOz5iuEKpHTeXceOcXFXUCMh0R2R@AJKEAXfHmY2imTFs/PY8edxeb3efPn9@nh7flputvx8//E89v3x5f24m8FiYsDq/nDnxRCwNmEbOmKFO3FBKMSmfqLDN7gEHZsk/PqEN3hBDHjAu@xW4lIYnLQpP96JBmgjA5e20WVN56kRTZzBEjGqkNVSRG6RYUedIhFTZJeG61pTZDol2SGqugxmocIHZ0UmsZFaRKoit7NFmUJKLuyqSKZTtp4b1IxX2YzmOPkMj1CzyFfpqTqbjVwrxB@pdDXkGpE9Qh01odwy5h8), with each result displayed on a single line. ### Explanation ``` " % Input matrix (implicit). For each column N % Number of elements in the stack ? % If nonzero (true for all iterations but the first) @2) % Push second element of current column: new index yn % Duplicate current buffer; push its number of elements \ % Modulo Q % Add 1 :&) % Split buffer at that point. This gives two pieces, one % of which may be empty @1) % Push first element of current column: new value wv % Swap; concatenate all stack. This places the new value % between the two pieces of the buffer } % Else (this is executed only in the first iteration) @1) % Push first element of current column: new value % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~64~~ ~~62~~ ~~58~~ 56 bytes ``` x=[] for n,i in input():x[i%(len(x)or 1)+1:0]=n, print x ``` *Thanks to @xnor for golfing off 2 bytes!* [Try it online!](https://tio.run/nexus/python2#HYpBCsIwFET3PcVshB@chWnTqIWeJGSpEJBvKRVy@/hTGJjHvGl1TXl4f3coC4patt8hbqmpXOTzUqnOpHdXv9zyqhy2veiB2loSTxOEjEToPRHP3sH22GEmxrlDJKZzudv1/DyIGFz@Aw "Python 2 – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 60 bytes Takes input as a list of pairs, prints the result. *[Edit: Outgolfed by Dennis](https://codegolf.stackexchange.com/a/107177/60919)* ``` b=[] for x,y in input():b.insert(1+y%(len(b)or 1),x) print b ``` [**Try it online!**](https://tio.run/nexus/python2#NYzBCoMwEETvfsVeCrt0ETehWIV@iXgJWAhIlBhBvz5dI4U5PGYek91nGKvvEuHgE3zQrHtC6l3twzbFhPI8HzhPAR2pJcQHVWv0IYHLeUDDYDpiQOkYbFPozSBtIavdBY1a8rfk9kWpjKIftqyqmxeNPw) This is quite simple - loop through the input, inserting the items into the correct place, and then print the result. Deciding which index to insert into is done with `1+y%(len(b)or 1)`. This is the standard way to do modular indexing, with the `or 1` to handle the edge case of an empty list. [Answer] # JavaScript (ES6), 60 bytes ``` f=([[q,r],...a],z=[])=>z.splice(r%z.length+1,0,q)+a?f(a,z):z ``` ### Test snippet ``` f=([[q,r],...a],z=[])=>z.splice(r%z.length+1,0,q)+a?f(a,z):z I.textContent = I.textContent.replace(/(.+) -> (.+)/g, (_,a,b) => _ + " (" + (f(eval(a.replace(/\(/g, "[").replace(/\)/g, "]"))) + "" == eval(b) + "") + ")") ``` ``` <pre id=I>[(11, 9), (13, 14)] -> [11, 13] [(1, 18), (11, 7), (3, 35), (16, 22)] -> [1, 11, 16, 3] [(3, 16), (16, 37), (0, 28), (18, 24)] -> [3, 18, 0, 16] [(7, 26), (8, 20), (11, 39), (1, 23), (17, 27)] -> [7, 8, 11, 1, 17] [(15, 35), (17, 7), (16, 15), (1, 13), (2, 6), (11, 34)] -> [15, 17, 1, 2, 16, 11] [(2, 13), (1, 20), (16, 25), (8, 21), (5, 2), (16, 37), (3, 0)] -> [2, 3, 8, 1, 16, 5, 16] [(6, 20), (15, 15), (12, 26), (10, 27), (17, 13), (7, 18), (4, 16)] -> [6, 10, 17, 12, 7, 4, 15] [(18, 9), (5, 34), (15, 4), (12, 29), (2, 5), (7, 0), (7, 10), (16, 38)] -> [18, 7, 15, 2, 16, 5, 7, 12] [(0, 12), (12, 0), (4, 16), (15, 12), (6, 28), (8, 10), (11, 24), (0, 25)] -> [0, 11, 8, 6, 15, 0, 4, 12] [(6, 12), (14, 13), (10, 33), (11, 35), (1, 3), (0, 28), (15, 27), (8, 10), (1, 2)] -> [6, 14, 10, 1, 11, 8, 15, 0, 1] [(2, 29), (19, 30), (18, 17), (13, 3), (0, 21), (19, 19), (11, 13), (12, 31), (3, 25)] -> [2, 13, 3, 11, 0, 12, 19, 18, 19]</pre> ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~38~~ ~~40~~ 35 bytes This answer bends the definition of list, and isn't normally a language you'd use for list manipulation, but I wanted to use `[count]/{regex}` which I recently added to V. The input is taken like `[index] [num] [index] [num] ...` and returned like `[num] [num] [num]`. ``` Í ¨ä«© ½/¯ÜdÜ+òhea ±^ Hdd2xdG@" X ``` [Try it online!](https://tio.run/nexus/v#@3@4V@HQisNLDq0@tFLh0F79Q@sPz0k5PEf78KaM1ESFQxvFpOO4PFJSjCpS3B2UuCL@/zc0UjAAQiBlaKZgAqZNFYwsFMwUDA0ULBSMgEKGCkamCgYA "V – TIO Nexus") Hexdump for 2 hidden characters: ``` 00000000: cd20 a8e4 aba9 20bd 2faf dc64 dc2b f268 . .... ./..d.+.h 00000010: 6561 20b1 161b 5e0a 4864 6432 7864 4740 ea ...^.Hdd2xdG@ 00000020: 220a 58 ".X ``` ### Explanation The code up to `dG@"` formats all `\d+ \d+` pairs so that a list 1 2 3 4 5 6 would end up like ``` a 2^[^3/\d\+ hea 4^[^5/\d\+ hea 6^[^ ``` and then the `dG@"` executes all of that as V code like the following: ``` a 2^[ | insert " 2" and return to command mode ^ | LOOP: go to the first number 3/\d\+ | find the 3rd number (0 indexed) h | move one character left e | go to the end of the next word a 4^[ | append " 4" and return to command mode ^5/\d\+ | basically the same as LOOP on, just with different numbers ``` [Answer] # PHP, ~~72~~ 92 bytes ``` for($b=[];++$i<$argc;)array_splice($b,$b?$argv[$i]%count($b)+1:0,0,$argv[++$i]);print_r($b); ``` takes input flattened from command line arguments. Run with `-nr`. [Answer] # Java 7, ~~125~~ 124 bytes ``` import java.util.*;List z(int[]a){List r=new Stack();for(int i=0,q=a.length/2;i<q;)r.add(i<1?0:a[i+q]%i+1,a[i++]);return r;} ``` Accepts a flat list of values followed by indexes. For the squares test case the input would be `new int[] {1, 2, 3, 4, 5, 6, 7, 8, 1, 4, 9, 16, 25, 36, 49, 64}` [Try it online!](https://tio.run/nexus/java-openjdk#lZPLctowFIb3PMXZdMYuGseSfMFxmL5Au2KZYaEASdQaA7ZIp2F4dnoumqzNyrr@/3f@I/v98TAE@O0@XHYOvsu@t7NN58YRfjnfw@X2048BPhPfh@e1Sy88HZb97i@sgtv8SdL29TDQNvhlrk5Ll3W7/i28P5jWP53adMjcdpv4J/0jf3TPfn5af/NzrWg4X6ftsAvnoYehvd6O55fOb2AMLuDn4@C3sEeGZBUG37@h@5DCZQYC5mAJBEETZMDl1b8x7PbZ4RyyI14IXZ@47DOhQwwPF63AKLAKCgWlgkpBrWChQPNKgwNcMrhj8VvgvCqu6VRtFNFWVO64hac1I5G1XjCRRQJjJmvEy7ncp6FFEYNjMx0kBqE5DE33KQrUtFiQQQtTTy@qFAkuiSPnGksujjcth2@n4xnhqpiyjFWKEEFSz0zsLnrkk3WrCET6uVDX/BhIlXY4hlqcJN7pMUTUqG9YOsbSUPVi1PCpXADsYrJ8LrKFOFRf/YvreczfyFMgcUN25V3ZFDEXeRc5iJn8MhwaxmKtNNfGR1dHt7ua28R4rZA30VN@V8rIxvZYRY3mA@Srv0q6zmbX238 "Java (OpenJDK) – TIO Nexus") [Answer] ## Mathematica, 62 bytes ``` Fold[Insert[#,#2[[1]],Mod[Last@#2,Tr[1^#]]+2/.0/0->-1]&,{},#]& ``` Pure function with first argument `#` expected to be a list of pairs. Starting with the empty list `{}`, left `Fold` the input list `#` with the following function: ``` Insert[ Insert #, into the first argument #2[[1]], the first element of the second argument Mod[ at the position given by the modulus of Last@#2, the second element of the second argument Tr[1^#] with respect to the length of the first argument ]+2 plus 2 (plus 1 to account for 1-indexing, plus 1 because we are inserting after that position) /. then replace 0/0 Indeterminate -> with -1 negative 1 ]& End of function ``` [Answer] # [Perl 6](http://perl6.org/), 51 bytes ``` {my @a;.map:{splice @a,(@a??$^b%@a+1!!0),0,$^a};@a} ``` Takes the flattened input. [Answer] ## Clojure, 87 bytes ``` #(reduce(fn[r[v i]](let[[b e](split-at(+(mod i(max(count r)1))1)r)](concat b[v]e)))[]%) ``` ]
[Question] [ # The Challenge Write a program or function that takes two input integers, `i` and `j`, and outputs their greatest common divisor; calculated by using the [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) (see below). --- # Input Input may be taken as a space-delimited string representation of `i` and `j` or as two separate integers. You can assume that integers will be less than or equal to 10,000. You can also assume that the input integers will not be prime to one another. --- # Euclidean Breakdown The larger number between `i` and `j` is divided by the smaller as many times as possible. Then, the remainder is added. This process is repeated with the remainder and the previous number, until the remainder becomes `0`. For example, if the input was `1599 650`: ``` 1599 = (650 * 2) + 299 650 = (299 * 2) + 52 299 = (52 * 5) + 39 52 = (39 * 1) + 13 39 = (13 * 3) + 0 ``` The final number, `13`, is the greatest common divisor of the two input integers. It can be visualized like this: ![](https://i.stack.imgur.com/jvDNw.gif) --- # Output Your output must be the breakdown in the form above, followed by a newline and the GCD. It can be output through any medium. --- # Examples ### Inputs ``` 18 27 50 20 447 501 9894 2628 ``` ### Outputs ``` 27 = (18 * 1) + 9 18 = (9 * 2) + 0 9 50 = (20 * 2) + 10 20 = (10 * 2) + 0 10 501 = (447 * 1) + 54 447 = (54 * 8) + 15 54 = (15 * 3) + 9 15 = (9 * 1) + 6 9 = (6 * 1) + 3 6 = (3 * 2) + 0 3 9894 = (2628 * 3) + 2010 2628 = (2010 * 1) + 618 2010 = (618 * 3) + 156 618 = (156 * 3) + 150 156 = (150 * 1) + 6 150 = (6 * 25) + 0 6 ``` Note: Outputs do not have to be spaced as they are above. The spacing is only for clarity. Parentheses are required. --- # Bonus If your output is spaced as above, you may add a -10% bonus to your score. [Answer] # CJam, ~~46~~ ~~43~~ 39 bytes ``` q~]$3*~\{N5$"=("3$:G'*3$Gmd")+"\}h]7>NG ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%5D%243*~%5C%7BN5%24%22%3D(%223%24%3AG'*3%24Gmd%22)%2B%22%5C%7Dh%5D7%3ENG&input=9894%202628). ### How it works ``` q~] e# Read all input, evaluate it and wrap the results in an array. $3* e# Sort the array and repeat it thrice. ~\ e# Dump the array and swap its last two elements. { e# Do: N e# Push a linefeed. 5$ e# Copy the sixth topmost element from the stack. "=(" e# Push that string. 3$:G e# Copy the fourth topmost element from the stack. Save it in G. '* e# Push that character. 3$ e# Copy the fourth topmost element from the stack. Gmd e# Push quotient and remainder of its division by G. ")+" e# Push that string. \ e# Swap the string with the remainder. }h e# If the remainder is positive, repeat the loop. ]7> e# Wrap the stack in an array and discard its first seven elements. NG e# Push a linefeed and G. ``` [Answer] ## Python 2, 70 ``` f=lambda a,b:b and'%d=(%d*%d)+%d\n'%(a,b,a/b,a%b)*(a>=b)+f(b,a%b)or`a` ``` A recursive function that returns a multiline string. The function creates the first line, then appends it to the recursive result with the next pair of numbers in the Euclidean algorithm. Once the second number is zero, we take the string of the other number as the base case, causing it to be printed on its own line at the end. The formatting is done via string substitution, using integer division to get the multiplicand. One hiccup is needing to start with the larger number being taken mod the smaller number. Conveniently, if the numbers are in the wrong order, the first step of the Euclidian algorithm flips them. To prevent this step from being displayed, only add the current line if the first number is at least the second (equality is needed for, say `f(9,9)`). [Answer] # Pyth, 33 bytes ``` ASQWGs[H\=\(G\*/HG\)\+K%HG)A,KG)H ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=ASQWGs%5BH%5C%3D%5C%28G%5C%2A/HG%5C%29%5C%2BK%25HG%29A%2CKG%29H&test_suite_input=18%2C%2027%0A50%2C%2020%0A447%2C%20501%0A9894%2C%202628&test_suite=0&input=18%2C%2027) or [Test Suite](http://pyth.herokuapp.com/?code=ASQWGs%5BH%5C%3D%5C%28G%5C%2A/HG%5C%29%5C%2BK%25HG%29A%2CKG%29H&test_suite_input=18%2C%2027%0A50%2C%2020%0A447%2C%20501%0A9894%2C%202628&test_suite=1&input=18%2C%2027) ### Explanation: ``` ASQWGs[H\=\(G\*/HG\)\+K%HG)A,KG)H Q read the two numbers from input S sort them A and assign them to G and H WG while G != 0: K%HG assign H mod G to K s[H\=\(G\*/HG\)\+K ) join the following list items and print: H=(G*(H/G))+K A,KG assign K, G to G, H ) end while H print H ``` [Answer] # awk, ~~78~~ 77 ``` x=$1{for(x<$2?x+=$2-(y=x):y=$2;t=y;x=t)print x"=("y"*"int(x/y)")+",y=x%y}$0=x ``` Sorting the input by size takes a lot of bytes :/ It comes down to this: ``` x=$1; if(x<$2) x+=$2-(y=x); # add $2 subtract $1 and set y to $1 else y=$2; # set y to $2 ``` ### Output ``` 650 1599 (input) 1599=(650*2)+ 299 650=(299*2)+ 52 299=(52*5)+ 39 52=(39*1)+ 13 39=(13*3)+ 0 13 ``` Just for the fun of it I made a properly spaced version too, giving me a score of 233 \* 0.9 == 209.7 bytes. *Update* I was able to shorten this from 285 bytes and now it works for arbitrarily long numbers if calling gawk4 with the `-M` option. ``` x=$1{x<$2?x+=$2-(y=x):y=$2;a=length(x);b=length(y);for(d=length(x%y);t=y;x=t){$++i=x;$++i=y;if(c<l=length($++i=int(x/y)))c=l;$++i=y=x%y}while(j<NF)printf "%"a"d = %"b-length($(j+2))"s(%d * %"c"d) + %"d"d\n",$++j,_,$++j,$++j,$++j}$0=x ``` But I still got a feeling I ran into some mental block there somewhere... ### Output (gawk4 called with `awk -M -f code.awk`) ``` 6837125332653632513763 18237983363879361 (input) 6837125332653632513763 = (18237983363879361 * 374883) + 15415252446024000 18237983363879361 = (15415252446024000 * 1) + 2822730917855361 15415252446024000 = (2822730917855361 * 5) + 1301597856747195 2822730917855361 = (1301597856747195 * 2) + 219535204360971 1301597856747195 = (219535204360971 * 5) + 203921834942340 219535204360971 = (203921834942340 * 1) + 15613369418631 203921834942340 = (15613369418631 * 13) + 948032500137 15613369418631 = (948032500137 * 16) + 444849416439 948032500137 = (444849416439 * 2) + 58333667259 444849416439 = (58333667259 * 7) + 36513745626 58333667259 = (36513745626 * 1) + 21819921633 36513745626 = (21819921633 * 1) + 14693823993 21819921633 = (14693823993 * 1) + 7126097640 14693823993 = (7126097640 * 2) + 441628713 7126097640 = (441628713 * 16) + 60038232 441628713 = (60038232 * 7) + 21361089 60038232 = (21361089 * 2) + 17316054 21361089 = (17316054 * 1) + 4045035 17316054 = (4045035 * 4) + 1135914 4045035 = (1135914 * 3) + 637293 1135914 = (637293 * 1) + 498621 637293 = (498621 * 1) + 138672 498621 = (138672 * 3) + 82605 138672 = (82605 * 1) + 56067 82605 = (56067 * 1) + 26538 56067 = (26538 * 2) + 2991 26538 = (2991 * 8) + 2610 2991 = (2610 * 1) + 381 2610 = (381 * 6) + 324 381 = (324 * 1) + 57 324 = (57 * 5) + 39 57 = (39 * 1) + 18 39 = (18 * 2) + 3 18 = (3 * 6) + 0 3 ``` ### Some newlines and tabs added ``` x=$1{ x<$2?x+=$2-(y=x):y=$2; a=length(x); b=length(y); for(d=length(x%y);t=y;x=t) { $++i=x; $++i=y; if(c<l=length($++i=int(x/y)))c=l; $++i=y=x%y } while(j<NF) printf "%"a"d = %"b-length($(j+2))"s(%d * %"c"d) + %"d"d\n", $++j,_,$++j,$++j,$++j }$0=x ``` I can save the lengths of the initial values for x, y and x%y in the beginning, because they can only get shorter each step. But for the factor I have to determine the maximum length before printing anything, because it's length can vary. I use `$i` as an array here, because it saves two characters compared to using a[i] every time. [Answer] # C++, GCC compiler, 171 bytes( -10%, so 154 bytes) okay so my first try.. ``` #include<iostream> using namespace std; int main() { int a,b,c; cin>>a>>b; if(a<b) swap(a,b); while(b>0) { c=a; cout<<a<<" = ("<<b<<" * "<<a/b<<") + "<<a%b<<endl; a=b; b=c%b; } cout<<a; } ``` tips to code golf appreciated. P.S. Is it necessary to count bytes of standard header files and int main while using c++? Excluding it reduces 50 bytes [Answer] # T-SQL (2012+), 268 bytes Implemented as an inline table function that executes a recursive CTE. Might be worthwhile trying to put formatting in for the 10% bonus, but that will have to wait. ``` CREATE FUNCTION E(@ INT,@B INT)RETURNS TABLE RETURN WITH M AS(SELECT IIF(@<@B,@B,@)A,IIF(@>@B,@B,@)B),R AS(SELECT A,B,A/B D,A%B R FROM M UNION ALL SELECT B,R,B/R,B%R FROM R WHERE 0<>R)SELECT CONCAT(A,'=(',B,'*',D,')+',R)R FROM R UNION ALL SELECT STR(B)FROM R WHERE R=0 ``` Explanation and usage: ``` --Create the function CREATE FUNCTION E(@ INT,@B INT)RETURNS TABLE RETURN WITH --Order the input correctly M AS ( SELECT IIF(@<@B,@B,@)A, IIF(@>@B,@B,@)B ) --Recursive selection ,R AS ( SELECT A,B,A/B D,A%B R FROM M -- Anchor query UNION ALL SELECT B,R,B/R,B%R FROM R -- Recurse until R = 0 WHERE 0<>R ) SELECT CONCAT(A,'=(',B,'*',D,')+',R)R -- Concat results into output string FROM R UNION ALL -- ALL required to maintain order SELECT STR(B) -- Add final number FROM R WHERE R=0 --Function Usage SELECT * FROM E(447,501) R ----------------------------------------------------- 501=(447*1)+54 447=(54*8)+15 54=(15*3)+9 15=(9*1)+6 9=(6*1)+3 6=(3*2)+0 3 ``` [Answer] # Rev 1: Ruby, 86 Recursive algorithm, thanks to tip from Doorknob. ``` f=->i,j{j>i&&(i,j=j,i) 0<j ?(print i," = (#{j} * #{i/j}) + #{i%j} ";f[j,i%j]):puts(i)} ``` # Rev 0: Ruby, 93 This really hasn't worked out well at all. The `while` loop takes up too many characters, especially with the `end`. I can't see a way of avoiding it. Recursion would require a named function instead of a lambda, which would also eat up a lot of characters. ``` ->i,j{j>i&&(i,j=j,i) while j>0 print(i," = (#{j} * #{i/j}) + #{i%j}\n") i,j=j,i%j end puts i} ``` Call it like this: ``` f=->i,j{j>i&&(i,j=j,i) while j>0 print(i," = (#{j} * #{i/j}) + #{i%j}\n") i,j=j,i%j end puts i} I=gets.to_i J=gets.to_i f.call(I,J) ``` [Answer] # PowerShell, 84 A recursive code block, stored in a variable. Invoke it with `& $e num1 num2`, e.g.: ``` $e={$s,$b=$args|Sort;if(!$s){$b}else{$r=$b%$s;"$b=($s*$(($b-$r)/$s))+$r";&$e $s $r}} PS D:\> & $e 9894 2628 9894=(2628*3)+2010 2628=(2010*1)+618 2010=(618*3)+156 618=(156*3)+150 156=(150*1)+6 150=(6*25)+0 6 ``` In a more readable form, it does the following (nb. for clearer code, I've put the full commandlet names, more spaces in the string, and made the pipeline output commands explicit): ``` function Euclid { $small, $big = $args|Sort-Object #Sort argument list, assign to two vars. if (!$small) { #Recursion end, emit the last Write-Output $big #number alone, for the last line. } else { #main recursive code $remainder = $big % $small Write-Output "$big = ( $small* $(($big-$remainder)/$small)) + $remainder" Euclid $small $remainder } } ``` One annoyance from a codegolf point of view; PoSh has no integer division, 10/3 returns a Double, but cast the result to an integer and it doesn't always round down, it [rounds N.5 to the nearest even number](http://c2.com/cgi/wiki?BankersRounding) - up or down. So `[int](99/2) == 50`. That leaves two awkward choices: ``` $remainder = $x % $y $quotient = [Math]::Floor($x/$y) # or, worse $remainder=$null $quotient = [Math]::DivRem($x, $y, [ref]$remainder) ``` Which is why I have to burn some characters doing: ``` $remainder = $big % $small ($big - $remainder)/$small ``` Apart from that, it's the number of $$$$ and the lack of ternary operator which really hurts. --- I also have an iterative version which, rather nicely, is also 84 characters: ``` {$r=1;while($r){$s,$b=$args|Sort;$r=$b%$s;"$b=($s*$(($b-$r)/$s))+$r";$args=$s,$r}$s} ``` Completely anonymous codeblock, so run it with ``` & {*codeblock*} 1599 650 ``` [Answer] # PHP, 118 Bytes ``` for(list(,$n,$m)=$argv,$g=max($n,$m),$l=min($n,$m);$g;$g=$l,$l=$m) echo$g,$l?"=($l*".($g/$l^0).")+".($m=$g%$l)." ":""; ``` [Try it online!](https://tio.run/nexus/php#LcqxCsIwFIXhPY9xuUKisUoRaY2hg3Rw0cVNtBSpaSFpyrWIk69eUxXO8v2cbdbVHauIPBVUdZ76pjX8nReH42m/y4ViWJJ56jPMQaZJupLxOk4uarh74rZ59FxiK9EJ/f1JNNqVL/5rEq12TfuXQhOm0Y45mFW32qMJykBztFOIOJoF2utSRCBmI51GM0EbzGADoIbhAw "PHP – TIO Nexus") # PHP, 131 Bytes ``` for(list(,$n,$m)=$argv,$r=[max($n,$m),min($n,$m)];$r[+$i];)echo$g=$r[+$i],($l=$r[++$i])?"=($l*".($g/$l^0).")+".($r[]=$g%$l)." ":""; ``` [Try it online!](https://tio.run/nexus/php#LcpBC4IwGMbxux9jvMGWyyIitDU8hIcudek2lkjYHEwnbxKd@uqm5u3/e3iOaVu1QYnoMcey9djZxtBvll@ut/MpYyKAAs1bKrIiPImTHd/ut7EW/dMjdfbVUQ4Nh5rJ6ccBpaqLD/2PvLbNnFoAqhCsFqx8VB6MnM0puKlHsJTIwUsSUTBrcPcNiwgLR6LSEswC3LAE5ECI6Psf "PHP – TIO Nexus") -4 Bytes replace `list(,$n,$m)=$argv` with `[,$n,$m]=$argv` needs PHP>=7.1 [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~43~~ ~~42~~ 41 bytes My newfound Japt "skills" seem to be getting worse, not better! ``` ?U>V?ßVU :[V'='(U'*V/U|0')'+V%=UR,ßVU]¬:V ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=P1U+Vj/fVlUgOltWJz0nKFUnKlYvVXwwJyknK1YlPVVSLN9WVV2sOlY=&input=OTg5NCwyNjI4) [Answer] # JavaScript (ES6), ~~74~~ ~~50~~ ~~62~~ ~~61~~ 55 bytes ``` f=(x,y)=>y?y>x?y:x+`=(${y}*${x/y|0})+${x%=y} `+f(y,x):x ``` * Sacrificed 12 bytes allowing the integers to be passed in any order, rather than largest first. --- ## Try It ``` f=(x,y)=>y?y>x?y:x+`=(${y}*${x/y|0})+${x%=y} `+f(y,x):x o.innerText=f(i.value=683712533265363251376,j.value=18237983363879361) i.oninput=j.oninput=_=>o.innerText=f(+i.value,+j.value) ``` ``` <input id=i type=number><input id=j type=number><pre id=o> ``` --- ## Explanation ``` f= :Assign the function to variable f ... (x,y)=> :And take the two integer inputs as arguments via parameters x and y. y? :If y is greater than 0 then y>x? : If y is greater than x then f(y,x) : Call f again, with the order of the integers reversed. : (This can only happen the first time the function is called.) : : Else x : Start building the string, beginning with the value of x. +`=( : Append "=(". ${y} : The value of y. * : "*" ${x/y|0} : The floored value of x divided by y )+ : ")+" ${x%=y} : The remainder of x divided by y, which is assigned to x : (x%=y is the same as x=x%y.) \n : A newline (a literal newline is used in the solution). `+f(y,x) : Append the value f returns when y and the new value of x : are passed as arguments. : :Else x : Return the current value of x, : which will be the greatest common divisor of the original two integers. ``` [Answer] # JS, 151 ``` a=prompt("g","");b=prompt("l","");c=0;l=[a,b];for(var i=0;i<=1;i++){t=c;o=c+1;r=c+2;n=l[t]%l[o];if(n!==0){l[r]=n;c=c+1;i=0;}else{p=l[o];alert(p);i=2;}} ``` [Answer] # C, 83 bytes ``` g(x,y,z){y&&(printf("%u=(%u*%u)+%u\n",x,y,x/y,z=x%y),z)?g(y,z,0):printf("%u\n",y);} ``` test and results ``` int main() {g(18,27,0); g(50,20,0); g(447,501,0); g(9894,2628,0); } 18=(27*0)+18 27=(18*1)+9 18=(9*2)+0 9 50=(20*2)+10 20=(10*2)+0 10 447=(501*0)+447 501=(447*1)+54 447=(54*8)+15 54=(15*3)+9 15=(9*1)+6 9=(6*1)+3 6=(3*2)+0 3 9894=(2628*3)+2010 2628=(2010*1)+618 2010=(618*3)+156 618=(156*3)+150 156=(150*1)+6 150=(6*25)+0 6 ``` [Answer] # Java 133 ``` public void z(int i,int j){for(int d=1;d!=0;i=j,j=d){d=i%j;System.out.println(i+"=("+j+"*"+((i-d)/j)+")+"+d);}System.out.println(i);} ``` It doesn't do the regular Euclidean algorithm. Instead, it uses modulus and then computes the 2nd number to multiply by when it's printed out. You can also make this shorter by turning it into a lambda expression, but I'm not sure how. ``` public void z(int i, int j) { for(int d=1;d!=0;i=j,j=d) { d=i%j; System.out.println(i+"=("+j+"*"+((i-d)/j)+")+"+d); } System.out.println(i); } ``` [Answer] # C# 115 First time on this forum ``` int g(int a,int b){(a,b)=a<b?(b,a):(a,b);Console.Write($"{a}=({b}*{a/b})+{a%b}\n");return a%b==0?b:g(b,a%b);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~32~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {R[D`‰«Â`"ÿ=(ÿ*ÿ)+ÿ",¤_#ιθ}1è, ``` Inputs as a pair `[i,j]`. Output is without spaces. [Try it online](https://tio.run/##AT4Awf9vc2FiaWX//3tSW0Rg4oCwwqvDgmAiw789KMO/KsO/KSvDvyIswqRfI865zrh9McOoLP//WzE1OTksNjUwXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLkFQO5OpX/q4OiXRIeNWw4tPpwU4LS4f22Gof3ax3er6l9eL@SzqEl8crndp7bUWt4eIXO/0Pb7P9HRxuaWlrqmJkaxOpEG1roGJkDaVMDHSMQ38TEXMfUwBDIsrSwNNExMjOyiI0FAA). The -10% bonus isn't worth it to output in the correct format, but here it is anyway: **48.6 bytes (54*†* [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 10% bonus)** ``` {R[D`‰«¤_#¤UDιθ})øε§Zgj}øεR`"ÿ = (ÿ * ÿ) + ÿ"}Xª»„( Â: ``` [Try it online](https://tio.run/##yy9OTMpM/f@/OijaJeFRw4ZDqw8tiVc@tCTU5dzOcztqNQ/vOLf10PKo9KxaECsoQenwfgVbBQ0gqaVweL@mgjaQVKqNOLTq0O5HDfM0FA43Wf3/H21oammpY2ZqEAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLkFQO5OpX/q4OiXRIeNWw4tPrQknjlQ0tCXc7tPLejVvPwjnNbDy2PSs@qBbGCEpQO71ewVdAAkloKh/drKmgDSaXaiEOrDu1@1DBPQ@Fwk9V/nUPb7P9HRxuaWlrqmJkaxOpEG1roGJkDaVMDHSMQ38TEXMfUwBDIsrSwNNExMjOyiI0FAA). **Explanation:** ``` { # Sort the (implicit) input-pair from lowest to highest R # Reverse it from highest to lowest [ # Start an infinite loop: D # Duplicate the current pair ` # Pop one and push both values separated to the stack ‰ # Divmod: a,b → [a//b,a%b] « # Merge the pairs together: [a,b,a//b,a%b]  # Bifurcate this quadruplet; short for Duplicate & Reverse copy ` # Pop and push the reversed items separated to the stack "ÿ=(ÿ*ÿ)+ÿ" # Push this string, where the `ÿ` are one by one filled with the values , # Pop and output it with trailing newline ¤ # Push the last value (`a%b`), without popping _ # If this is 0: # # Stop the infinite loop # (else) ι # Uninterleave it into two parts: [a,b,a//b,a%b] → [[a,a//b],[b,a%b]] θ # Pop and keep the last pair (`[b,a%b]`) } # After the infinite loop: 1è # Pop the final quadruplet, and leave its second item: `b` , # Pop and output it with trailing newline as well ``` ``` {R[D`‰« # Similar as above ¤_# # Similar as above as well ¤ # Push the last item without popping again U # Pop and store it in variable `X` D # Duplicate the quadruplet ιθ} # Similar as above as well ) # Wrap the quadruplets of the stack into a list ø # Zip/transpose; swapping rows/columns ε # Map over each inner list § # Cast every integer to a string (†bug work-around for builtin `j`) Z # Push the largest integer, without popping g # Pop and push its length j # Potentially add leading spaces so all values in the list are of this length }ø # After the map: zip/transpose back ε # Map over each inner list: R` # Push the items in reverse order to the stack "ÿ = (ÿ * ÿ) + ÿ" # Push this string, where the `ÿ` are one by one filled with the values }Xª # After the map: append value `X` » # Join this list by newlines „( # Push string "( "  # Bifurcate; short for Duplicate & Reverse copy: " (" : # Infinitely replace "( " to " (" # (after which the string is output implicitly as result) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/189537/edit). Closed 4 years ago. [Improve this question](/posts/189537/edit) We've all done it, well, maybe not, but making your own alien language and numbering system is a staple of especially fantasy writing, but is mostly just a fun activity. The task is simple, take two inputs: 1. An ordered list input of 10 [ten] unique 'numerals' (any printable ASCII character) and interpret them, in order, as the values 0, 1, 2, 3,...,9 +There are exceptions to what can be a numeral here. Arithmetic operators (+, -, \*, /), Parentheses, and spaces cannot be used as one of the numerals. 2. An arithmetic problem using only those 'numerals' And output the equivalent integer result in the given form. Here's an example: ``` INPUT abcdefghij bcd + efg + hij ``` ``` OUTPUT bdgi ``` In the example, the input list (you may choose which form the list comes in) of 'abcdefghij' corresponds to '0123456789' just as 'hjkloiwdfp' would also correspond 1 to 1 with '0123456789' where instead of 'a' associating with zero, 'h' does. The arithmetic following 'translates' to 123 + 456 + 789, which equals 1368. This must then be outputted in the form we gave it, so b (which represents 1) d (for 2) g (for 6) and i (for 8). **TEST CASES** ``` abcdefghij abc + def - ghij -gedc ``` ``` qwertyuiop qwerty / uiop e ``` ``` %y83l;[=9| (83l * 9) + 8% y9|8 ``` ***MORE RULES*** * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden! * This is code golf, so shortest answers in bytes wins. * Must be a full program or function taking the inputs and outputs in whatever format works best for you. (Just cannot add additioal information in the inputs, just 'numerals' and the expression. * Use any language you'd like (as long as it complies with other rules) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žh‡.Eò¹Åв ``` (Now) outputs as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//6L6MRw0L9VwPbzq083DrhU3//ycmJaekpqVnZGZxAVkK2gpADpAE8gE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC8aGV/4/uy3jUsFDP9fCmQ@sOt17Y9F/nf3S0UmJSckpqWnpGZpaSjhKQraCtAOQCSZBIrI4CmgogBygH5CvoKqTDlRSWpxaVVJZm5hcAlUA4CvoKYD5YXrXSwjjHOtrWsgYorwFkK2gpWGoCDbJQxWGHlgKI1FVIAdoQCwA). **Explanation:** ``` ‡ # Transliterate the second (implicit) input, replacing every character of # the first (implicit) input with: žh # The builtin "0123456789" .E # Then evaluate it as Elixir code ò # Round it to the nearest integer ¹Åв # And change it back by using a custom base-conversion with the first input as # base (which results in a character list) # (after which that result is output implicitly) ``` The new version of 05AB1E is build is build in [Elixir](https://elixir-lang.org/). The `.E` function will call `call_unary(fn x -> {result, _} = Code.eval_string(to_string(x)); result end, a)`, where the [`Code.eval_string` is an Elixir builtin](https://hexdocs.pm/elixir/Code.html#eval_string/3). Note that the legacy version of 05AB1E won't work for this, because it is build in Python. The numbers with leading 0s won't be evaluated: [See all test cases in the legacy version](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVC8aGV/4/uy3jUsFDP9fAmIOvQOiD7v87/6GilxKTklNS09IzMLCUdJSBbQVsByAWSIJFYHQU0FUAOUA7IV9BVSIcrKSxPLSqpLM3MLwAqgXAU9BXAfLC8aqWFcY51tK1lDVBeA8hW0FKw1AQaZKGKww4tBRCpq5ACtCEWAA) (which uses the 10-byte version because the `Åв` builtin is new). [Answer] # [R](https://www.r-project.org/), 58 bytes ``` function(d,s,`[`=chartr)'0-9'[d,eval(parse(t=d['0-9',s]))] ``` [Try it online!](https://tio.run/##HchLCoAgEADQqwxtVBqhbZAnESFztA9hodb17bN8L9UAg4QarujKekROmHHUo3KLTSUJ1smeaUJ/252fNmXPiyL9N2YjhKmBN3Zy5MO8rFuDH6CF1yDhL1Ef "R – Try It Online") Uses character translation `chartr` to swap the digits, `parse`s and `eval`s the expression, and then `chartr`s back to the original digits. If rounding to nearest integer is required, this is # [R](https://www.r-project.org/), 65 bytes ``` function(d,s,`[`=chartr)'0-9'[d,round(eval(parse(t=d['0-9',s])))] ``` [Try it online!](https://tio.run/##JYzvCoIwFEe/9xQXQdxqomV/HOWTDMHlNjVEbc5C6N3XWt/u@Z3D1VbBLQarlqE23TggQWZSsaqoW66NxlEa04gJosdlEEi@eI8mrmeJTCGYl2QuMcalVSjg91pI1bTdIyA/gB04hhj8hDcueb6lNuvSjZNL/gAJePY@XPOsv7KCfpxH7oYtUOwe5aEL0v0hO56S8yWn9gs "R – Try It Online") [Answer] # T-SQL, 117 bytes ``` DECLARE @ CHAR(99) SELECT @='SELECT TRANSLATE('+TRANSLATE(e,c,'0123456789')+',''0123456789'','''+c+''')'FROM t EXEC(@) ``` Line breaks are for readability only. Input is via a pre-existing table **t** with text columns **c** (characters) and **e** (equation), [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Uses the SQL 2017 function [`TRANSLATE`](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-2017) to switch between characters and generate a string that contains not only the equation, but the code to translate back to the original characters: ``` SELECT TRANSLATE(123 + 456 + 789,'0123456789','abcdefghij') ``` This string is then evaluated using `EXEC()`. There may be some characters (such as a single quote `'`) that would break this code; I haven't tested all possible ASCII characters. Per the challenge, I am evaluating the expression as given, subject to how my language interprets those operators. As such, the second test case returns 1 (`w`), and not 2 (`e`), due to integer division. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes ``` {*.trans($_=>^10).EVAL.trans(^10=>$_)} ``` [Try it online!](https://tio.run/##LYtBC4IwAEbP7Vd8hxmbpRVBKDGhQ7fOXYJi1laGqakRw/zta4i39x68StX5xr7MVEPYzg/bWhYNoxeRnFdLHu6Pu8PYnIuEXnhvdVmD5VmhGo4gAZVz0BQdmTTSQDMqOaMpJ72V6fWm9P2RPYlDzOAMAYbw/qq6NZ@srEbEAoN5Jlrn25OIf4Q5go@YuzXy/g "Perl 6 – Try It Online") I'm not sure how the rounding is supposed to work. If it rounds at the end then I can add `.round` for [+6 bytes](https://tio.run/##LYtBC4IwAEbP7Vd8hxmbpRVBKDGhQ7fOXYJippZhalOJYf72NcTbe@/jq1NV7MxbzzMI07t@q2TZMHoT0XWz5v7xfDj5qurKZFpsFRG98cFklQIr8jJtOLwIVC5BY/Rk1kiNjFHJGY05GYyM70maPZ75i1jEAtbgYQyfb6pa3eVVPSFWGM3RwbbYX0T4I8wSXITcXgPnDw). If the behaviour of `/` should be different then it may be longer. Takes input curried like `f(arithmetic)(numerals)(arithmetic)`. ### Explanation: ``` { } # Anonymous codeblock * # Returning a whatever lambda .trans($_=>^10) # That translates the numerals to digits .EVAL # Evaluates the result as code .trans(^10=>$_) # And translates it back again ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~74~~ ~~66~~ 65 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┼ö8Q#xóπcM~oÖ÷╦├mî☼yº─▐4ç≥e╘o▄ê‼ø_k╜ø8%N╫ ╗e<.╗P[─╛èA±!xêj«w╠°{B♪ ``` [Run and debug it](https://staxlang.xyz/#p=c59438512378a2e3634d7e6f99f6cbc36d8c0f79a7c4de3487f265d46fdc8813005f6bbd0038254ed720bb653c2ebb505bc4be8a41f12178886aae77ccf87b420d&i=abcdefghij%0Abcd+%2B+efg+%2B+hij%0A%0Aqwertyuiop%0Aqwerty+%2F+uiop%0A%0A%25y83l%3B[%3D9%7C%0A%2883l+*+9%29+%2B+8%25&a=1&m=1) Stax does not do well here, lacking a true "eval" instruction. It has one that's called "eval" in the docs, but it only works on literal values, not full expressions. [Answer] # Bash, 97 bytes ``` IFS='' read S read O A=`echo "$O"|tr "$S" 0-9` printf %0.f `bc<<<"(${A[@]##0})+0.5"`|tr 0-9 "$S" ``` Could be less if we could truncate, rather than round. Also tricky to handle leading zeroes (as in test case #2) since Bash interprets numbers starting with 0 as octal. [Answer] # [Bean](https://github.com/patrickroberts/bean), ~~94~~ 90 bytes ### Hexdump ``` 00000000: 53d0 80d6 d800 d3d0 80a0 1f20 8047 53a0 SÐ.ÖØ.ÓÐ. . .GS  00000010: 1753 d080 d3d0 80a0 5e20 800a a181 8100 .SÐ.ÓÐ. ^ ..¡... 00000020: 40a0 5f52 cac3 4da0 6580 53d0 80a0 5d20 @ _RÊÃM e.SÐ. ] 00000030: 8089 205f a065 205f 2080 0aa1 8181 0123 .. _ e _ ..¡...# 00000040: 0058 0020 800a a181 8102 40a0 6550 84a0 .X. ..¡...@ eP.  00000050: 5d20 652e dce2 b02b dc64 ] e.Üâ°+Üd ``` ### JavaScript ``` `${Math.round( eval( b.replace( /./g, c => ~(i = a.indexOf(c)) ? i : c ).replace( /\b0+/g, '' ) ) )}`.replace( /\d/g, i => a[i] ) ``` ## Explanation This program implicitly assigns the first and second lines of input as strings to the variables `a` and `b` respectively. Each character `c` on line `b` is replaced with the respective index `i` of the character found on line `a`, or itself if it is not found. Then it removes each sequence of one or more `0`s preceded by a boundary from the resulting string. This is to prevent `eval()` from evaluating any sequence of digits starting with `0` as an octal literal. After `eval()` and `Math.round()`, the result is coerced back into a string and each digit character `i` is replaced by the corresponding character from line `a` at index `i`. ## Test Cases [Demo](https://patrickroberts.github.io/bean/#h=U9CA1tgA09CAoB8ggEdToBdT0IDT0ICgXiCACqGBgQBAoF9SysNNoGWAU9CAoF0ggIkgX6BlIF8ggAqhgYEBIwBYACCACqGBgQJAoGVQhKBdIGUu3OKwK9xk&i=YWJjZGVmZ2hpagphYmNkICsgZWZnICsgaGlq) ``` abcdefghij abcd + efg + hij bdgi ``` [Demo](https://patrickroberts.github.io/bean#h=U9CA1tgA09CAoB8ggEdToBdT0IDT0ICgXiCACqGBgQBAoF9SysNNoGWAU9CAoF0ggIkgX6BlIF8ggAqhgYEBIwBYACCACqGBgQJAoGVQhKBdIGUu3OKwK9xk&i=YWJjZGVmZ2hpagphYmMgKyBkZWYgLSBnaGlq) ``` abcdefghij abc + def - ghij -gedc ``` [Demo](https://patrickroberts.github.io/bean#h=U9CA1tgA09CAoB8ggEdToBdT0IDT0ICgXiCACqGBgQBAoF9SysNNoGWAU9CAoF0ggIkgX6BlIF8ggAqhgYEBIwBYACCACqGBgQJAoGVQhKBdIGUu3OKwK9xk&i=cXdlcnR5dWlvcApxd2VydHkgLyB1aW9w) ``` qwertyuiop qwerty / uiop e ``` [Demo](https://patrickroberts.github.io/bean#h=U9CA1tgA09CAoB8ggEdToBdT0IDT0ICgXiCACqGBgQBAoF9SysNNoGWAU9CAoF0ggIkgX6BlIF8ggAqhgYEBIwBYACCACqGBgQJAoGVQhKBdIGUu3OKwK9xk&i=JXk4M2w7Wz05fAooODNsICogOSkgKyA4JQ) ``` %y83l;[=9| (83l * 9) + 8% y9|8 ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 63 bytes ``` $p=<>;eval"y/$p/0-9/";s/\b0+\B//g;$_=int.5+eval;eval"y/0-9/$p/" ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lwNbGzjq1LDFHqVJfpUDfQNdSX8m6WD8myUA7xklfP91aJd42M69Ez1QbpAimEqQMqFrp///C8tSikkoFfYXSzPwCLggPzNSwMM5R0FKw1FTQVrBQ5VKtBPKto20ta/7lF5Rk5ucV/9ctyAEA "Perl 5 – Try It Online") Takes the expression on the first line of input and the translation list on the second. [Answer] # [Perl 5](https://www.perl.org/), 130 bytes ``` sub f{eval sprintf"'%.0f'=~y/%s/%s/r",eval(eval(sprintf"\$_[1]=~y/%s/%s/r",@r=map"\Q$_",$_[0],'0123456789')=~s,\b0,,gr),reverse@r} ``` [Try it online!](https://tio.run/##VYxNb4JAEIbv@ysmFAJb14q1tiDFaNJrD028qSEgA24Dut1FDfHjr9MF00Mnk8kzeT8EymLcNOqQQHbGY1yAEpLvqsywrSc3s8NbPbBUu9Jgre5058@0MqPlcP3PNJNhGQtj9WVGBtOyu2a2O3wevYxf3zzfpuFNsVXiMpZLyiQeUSqcyWtzUAgLVNVk8rmXCJVGFU5HATlteYHO@8d8MZ/SMwE9Ze2YKTMFM2MaKlHwKoCHlOe8UiDkPimwhHinTig7O1cOZPcEZWDGQANyJVHUVkYRiZNNilm@5d@gsae53z39HNMN@dEtVX3gewF3HHSMxKq9UREsQ/8CjqZHn/Y8C2r/4jW/ "Perl 5 – Try It Online") Maybe that double eval somehow can be turned into `s/.../.../geer`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ⍘UV⭆η⎇№θι⌕θιιθ ``` [Try it online!](https://tio.run/##NYtBCsIwEEX3nmKWM5iewF1Fd0JBLzCmsRkJiY1poaefDoibz3sPvo9cfeGkOlTJDXv@hnsznHDYWiz5snJauAX81Rt/MDp4hJq5bngui51mB0IOrpLHPwuR7Ux0UuWnH8NrivI@GMERTKADc@3WtAM "Charcoal – Try It Online") Link is to verbose version of code. Note: Expression is evaluated according to Python 3 semantics, so for instance leading zeros on non-zero numbers are illegal. Explanation: ``` ⭆η Map over expression's characters and join ι Current character №θ Count matches in first input ⎇ If non-zero ⌕θι Replace with position in first input ι Otherwise keep character unchanged UV Evaluate as Python 3 ⍘ θ Convert to base using first input as digits ``` [Answer] # [Python 3](https://docs.python.org/3/), 137 bytes A non-regex approach using `str.translate` and `str.maketrans` to replace the characters. I lost a lot of characters on trimming the leading zeros... ``` lambda s,t,d='0123456789',e=str.translate,m=str.maketrans:e(str(round(eval(' '.join(c.lstrip('0')for c in e(t,m(s,d)).split())))),m(d,s)) ``` [Try it online!](https://tio.run/##RY3dTsMwDEbv9xSWqikOZGVQflpQnwRussbdMtKkJBmo0t69eJ0E35XP52N5nPIh@Gru24/Z6WFnNCSVlWnF9v6henx6fqkboahNOZY5ap@czqSGhQf9SUv3SsiMMZy8QfrWDgWI8hisx650vLIjiq2QfYjQgfVAmNWASRkpyzQ6m1Fewp1RScp5jNZn7FHoXWeo3x/sUagLwC0wwwaWSkooYLMn063@Lr5@KObpZMPIF1eAO1iYdU4B9G@vp7pyb@9tc2YbeYYbaCR/qddXvYCpOdfz6hc "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 167 bytes ``` import re a=[*enumerate(input())] e=input() for i,c in a:e=re.sub(c,str(i),e) e=str(round(eval(re.sub(r'\b0+(?!\b)','',e)))) for i,c in a:e=re.sub(str(i),c,e) print(e) ``` [Try it online!](https://tio.run/##dYxBDsIgEEX3nGJcMVg0Ju5MGg9iXQCdWowCmYKJp0eadOus3vy8vPTNcwznWv07Rc7AJEx/21Mob2KTCX1IJaNSd0H9xmKKDF478AHMhXqm41IsOr1kRq80qeauzLGEEeljXrg5LAd76vC6G6ySWsrmtvsT3HJuDSb2ISOpWo11I02P2T9FQ@igfXCAdfgB "Python 3 – Try It Online") Room for improvement... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 121 bytes I define a pure function with two arguments. Since some functions are repeated I save them in a variable to save a few characters. This code simply does some string replacements and then uses `ToExpression` to evaluate the expression with the Wolfram kernel. ``` (r=Thread[StringPartition[#,1]->(t=ToString)/@Range[0,9]];u[(u=StringReplace)[#2,r]//ToExpression//Round//t,Reverse/@r])& ``` [Try it online!](https://tio.run/##VY3LbsIwEEX3fIUFokqK0fSxIUJGbMoapdlZXrjJNDGCOJ1M2iL1312HSJW6vOeeO3Ox3ODFsittOKiQkCoaQlvpVybX1kdL7Nj5Vi/ko1nvElaFn6oU9rlta9QPMjNmO@hkUFOTY3e2JaZ68STJABT@5bsj7Pt4ByD3Q1sBsMzxE6lH2JNJ78IxLlkf9Ny@lRW@1407zaUYk1iJCMRa3Fh8NftzP76Q@Do4343ulASIG/gnLq@b5/NWq@xnFJMY7rN0tVmOVpiFXw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Lua](https://www.lua.org), ~~162~~ ~~151~~ 150 bytes * -11 bytes thanks to my idea of using `load` instead of `function(...) end` * -1 byte by omitting newline ``` l,p=...print(((math.ceil(load('return '..p:gsub('.',load'n=l:find(...,1,1)return n and n-1'))()-0.5)..''):gsub('%d',load'c=...+1 return l:sub(c,c)'))) ``` [Try it online!](https://tio.run/##LY1BbsMgEEX3OcVsrGEaoLWqSokrn6MLKwuCcUJFgWKsKlLv7oLr5f//vRm3qFUI@EgqRpNAzTAtXmcbPOQA2cz54IJWDqbeBTUOw@p47KWUMVmfGWNfKt@lNtaxujNMJi/JAxaiu83LlaFEXif0vesm60dWbN7ylnbUg/IjeNEiESPxIt9ISkTa9WbcfV3fHlvYNdfVWXNNxaP1cjlMDNVVj2a63e0ncqgJjlAKELB1VJnvH5PyY7EhVuY/wTNsxQY0j9Orex/6828FWAnwBGcqp04N0voH "Lua – Try It Online") Not shortest thing in the world (Lua forces you to be fancy quite hard, especially by huge keywords), but was pretty fun to create. Full program taking input as arguments and printing result. ## Explanation ### Introduction ``` l,p=... ``` Assign values from arguments to variables. Our dictionary is `l` and expression is `p`. Following expression is quite hard to understand because it have a weird order of execution, so I'll explain it step-by-step: ### Converting to normal numbers ``` p:gsub('.', load'n=l:find(...,1,1)return n and n-1') ``` Perform replacement on expression string: take each symbol and pass it to function (`load` proved itself to be shorted than normal declaration here). Function finds position of occurrence in dict string for passed symbol using `find`. `...` is first (and only) argument here as we're in vaarg function (any `load`ed one is) that is our current symbol. Following arguments are required to make `find` ignore special symbols (`1` is just short value which evaluates as `true` when converted to boolean): starting position (one is default here) and `plain`, which actually disables pattern handling. Without those program fails on third test case due to `%` being special. If match is found, subtract one as Lua strings (and arrays btw) are 1-based. If no match is found, it will return nothing, resulting in no replacement being done. ### Solving ``` math.ceil(load('return '..ABOVE)()-0.5) ``` Prepend `return` to our expression to let it return result, calculate it by compiling as Lua function and calling it, perform rounding ([this](https://stackoverflow.com/a/18313481/5697743) turned other way around to make it shorter). It the end we get a numerical solution to our problem, only converting it back remains. ### Making it crazy again ``` (ABOVE..'') :gsub('%d',load'c=...+1 return l:sub(c,c)') ``` First line is a short way to convert number to string, so now we can call string methods in a short way. Let's do so! Now `gsub` is called again to replace everything back to insanity. This time `%d` is used instead of `.` as replacement pattern as our function may and must process only numbers (`.` would result to error on negative numbers). This time function (`load`ed again to save bytes) first adds `1` to its first (and only) vaargument, converting it to position in dict string, then returns character from it at that position. Hooray, almost there! ### Dramatic finale, or Why Brackets Matter ``` print((ABOVE)) ``` Well… why two pairs of brackets anyways? It's time to talk about parall… eh, multiple return in Lua. Thing is that one function may return few values from one call (look at [this meta question](https://codegolf.meta.stackexchange.com/q/17950/59169) for more examples). Here, last `gsub` returned two values: answer string we need and amount of replacements done (count of digits actually, but who cares). If it wasn't for internal pair, both string and number would be printed, screwing us up. So here we sacrifice two bytes to omit second result and finally print product of this insanity factory. --- Well, I've enjoyed explaining almost as much as golfing in first place, hope you got what's going on here. ]
[Question] [ Given a positive integer `n >= 1`, output the first `n` rows of the following structure: ``` # # # ### # # # # # ## ## ##### # # # # # # # # # # ### # ## ## ## # ## ### ### ####### ``` The `n`-th 1-indexed row is the binary representation of `n`, mirrored without copying the last character, with `#` in place of 1 and `<space>` in place of 0. All rows are centered. You must output as ASCII-art but you may use any non-whitespace character in place of where I use `#` in the example. Trailing whitespace is allowed, and a trailing newline is allowed. The output must look like the example, and no extra leading whitespace or leading newlines. You can view the first 1023 rows of the fractal cathedral [here](https://gist.githubusercontent.com/hyper-neutrino/95a00814b4abb3b1bf6985affe65fb6d/raw/57b6ee5e7b0471b62aa441f4934c494f25a1c3d6/fractal-cathedral.txt). To generate larger test cases, here's an ungolfed reference implementation in [Python](https://tio.run/##XY9NCoMwEIXXySkGukhCrTSWboSeRFykGjVFExlTxNOniUUK3b033/y9efODs7cQzDQ79DApP1Da6g5aVCtHty6ipGQ1rR/gseO80Wbkuxpdv7fAGWQGhRCUdA4hlsBYQGV7zSM4WtIm8jRW4RZ3RZGGRVWU9V89ihz1PKpGc3ZlGTBgIsfXe/F8f0X8sEz4xOJpMqOxnn/nq/Ii63j0cMmKmCylkncRwgc) [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` :B2&Zv35*c ``` [Try it online!](https://tio.run/##y00syfn/38rJSC2qzNhUK/n/f0NTAA "MATL – Try It Online") ### Explanation ``` : % Implicitly input n. Push range [1 2 ... n] B % Convert to binary. Gives a matrix where each row corresponds to % a number. Rows have left-padding zeros if needed 2 % Push 2 &Zv % Symmetrize along sepecified dimension (2nd means horizontally), % without repeating the last element 35* % Multiply by 35 (ASCII code for '#') c % Convert to char. Char 0 is shown as space. Implicitly display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ### Code: ``` Lb€û.c0ð: ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/fJ@lR05rDu/WSDQ5vsPr/39AUAA "05AB1E – Try It Online") ### Explanation: ``` L # List [1, .., input] b # Convert each to binary €û # Palindromize each binary number .c # Join the array by newlines and centralize 0ð: # Replace zeroes by spaces ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` RBUz0ZUŒBo⁶Y ``` [Try it online!](https://tio.run/##y0rNyan8/z/IKbTKICr06CSn/EeN2yL///9vaAoA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 92 bytes ``` n=input() for x in range(n):s=bin(2**len(bin(n))/4+x+1)[3:].replace(*'0 ');print s+s[-2::-1] ``` [Try it online!](https://tio.run/##FcZBCoMwEAXQfU8xO2cSbDXtxognERdW0jYg35BE0NOn@FYvnPm3wZSCwSPsmeX22SId5EFxxtcxxKbh7cFGqdWBr0Lk8dKHbmV82ukeXVjnxbGqGqqkD9EjU9JprI21dTuV0v0B "Python 2 – Try It Online") In Python 3, `s=f'{x+1:0{len(bin(n))-2}b}'.replace(*'0 ')` is shorter, but `int(input())` and parens around the `print` argument push it up to 95 bytes. [Answer] # JavaScript (ES6), 106 bytes Uses `1` as the non-whitespace character. ``` f=(n,k=0)=>k++<n?[...Array(32-Math.clz32(n))].reduce((s,_,i)=>(c=k>>i&1||' ')+s+(i?c:''),'')+` `+f(n,k):'' ``` ### Demo ``` f=(n,k=0)=>k++<n?[...Array(32-Math.clz32(n))].reduce((s,_,i)=>(c=k>>i&1||' ')+s+(i?c:''),'')+` `+f(n,k):'' O.innerText = f(15) ``` ``` <pre id=O> ``` ### Alternate version (same size) Without `Math.clz32()`: ``` f=(n,a=[k=i=0])=>n>>i+1?f(n,a,a[++i]=i):k++<n?a.reduce((s,i)=>(c=k>>i&1||' ')+s+(i?c:''),'')+` `+f(n,a):'' ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21~~ ~~20~~ 18 bytes Thanks @Zgarb for golfing off 2 bytes! ``` S↑(tfS=↔ΠR" #"←DLḋ ``` [Try it online!](https://tio.run/##ASYA2f9odXNr//9T4oaRKHRmUz3ihpTOoFIiICMi4oaQREzhuIv///8xNQ "Husk – Try It Online") ### Ungolfed/Explanation To avoid lengthy padding, this determines the width of the fractal which is given as `2*len(bin(N))-1` and generates all sequences of that length with the symbols `#,_` ('\_' denotes a space). Since the Cartesian power is generated in order and the binary numbers are too, this is fine. All we need to do to get the fractal at this point, is filtering out all palindromes and that's basically it: ``` -- implicit input N S↑( -- take N from the following list ΠR" #" -- Cartesian power of [" #"] to Lḋ -- number of bits in bin(N) D -- 2* ← -- -1 fS=↔ -- filter out palindromes t -- drop the first line (all spaces) ``` [Answer] # Mathematica, 94 bytes ``` Column[Row/@Table[s=IntegerDigits[i,2];Join[s,Reverse@Most@s]/.{0->" ",1->"#"},{i,#}],Center]& ``` [Answer] # Mathematica, 98 bytes ``` Riffle[Nest[ArrayFlatten@{{0,#,0},{1,0,1},{1,#,1}}&,{1},⌊Log2@#⌋]~Take~#"#"/. 0->" "," "]<>""& ``` Try it at the [Wolfram sandbox](https://sandbox.open.wolframcloud.com/)! The `⌊` and `⌋` are three bytes each. It's a different approach from the other answers so far, using the fractal nature of the pattern. The key step is `ArrayFlatten@{{0,#,0},{1,0,1},{1,#,1}}&`, which does the fractally stuff, best explained in picture form: ``` [ ] [grid] [ ] [ ] [grid] ---> # # [ ] #[ ]# #[grid]# #[ ]# ``` The code repeats this step enough times to get at least *n* rows, then trims off the extra rows and displays it nicely. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 11 bytes ``` #”B¦ₔṫ¦€|ṣ ``` [Try it online!](https://tio.run/##S0/MTPz/X0H5UcNcp0PLHjVNebhzNYheU/Nw5@L//00NAA "Gaia – Try It Online") ### Explanation ``` ¦ₔ For each number 1..input: #”B Convert it to base 2 and use space as 0 and # as 1 ṫ¦ Palindromize each €| Centre the lines ṣ Join with newlines ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ ~~118~~ 107 bytes thanks @luismendo, @officialaimm, @halvard-hummel ``` def f(l): for a in range(1,l+1):print(bin(a)[2:]+bin(a)[-2:1:-1]).replace(*'0 ').center(len(bin(l+1))*2-4) ``` [Try it online!](https://tio.run/##LcwxDoMwDEDRvafwhg0NIlYnX6ViSKnTRopMFGXh9KmK2P7yfjnadzfu/a0RImaSG8S9QoBkUIN9FP09T56k1GQNX8kw0JNlna50LF6cX2muWnLYFMdhgYHmTa1pxax2qv@ERnYP6hH9wtR/ "Python 2 – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~192~~ ~~178 bytes~~ 168+23 thank you TheLethalCoder for the help. ``` x=>new int[x].Select((_,z)=>Convert.ToString(z+1,2).PadLeft((int)Math.Log(x,2)+2).Replace('0',' ')).Aggregate((y,z)=>y+"\n"+z+new string(z.Reverse().Skip(1).ToArray())) ``` [Try it online!](https://tio.run/##TVDfS8MwEH62f0XYS@9oDdvwrXYwBJ82ECv4MIeE7BaDbVKTbK4b/dtr3BR9vO@@X3fSX0vraNh5bRSrOh@o4QttPor/SJEY0ZBvhSTWOqucaE6JrIX3f6MPImjJ7ndG3moTch9cNJhty@FQzgx9sgiuDmteUU0yALzmRyxnd9bsyQX@ZKszH47ZJJ8ifxCbBW0jLapwKcIbX1gFh7jK4vaR2jp2gXSc5ilLEflcKUdKBALozsZdNnoxo@yYfUf7H@8ojGmeAHn1rluYYAyeOyc6QMSh@D1ib/WGLYU2cFGu1kw45fGUXMXC3tbEn50OFB9FsIXJeHqDWCR90vfDFw "C# (.NET Core) – Try It Online") pretty sure this can be reduced by a lot, most likely in the padding and reversing of the string. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` A…·¹NθW⌈θ«Eθ§ #κ↓⸿AEθ÷κ²θ»‖O ``` [Try it online!](https://tio.run/##NY27CoMwFEDn@hUXuyQQBwtd6lRwcegD5y423mowRs1LofTbUwt2PZzD4W2l@VDJEM7GiEaRQnHpjPBYVqpBkjIo1Ojs1fVP1IRSBhPNorkVEoFcqkX0ricTpfCOdnctlF3hSCYGZ1uoGhcSwz5m0FG6ZptxyodZMYgfOv7B7bx1hbK58KJG0jE4/IefqMSXRG5vHrVcTZqFkB5D4kNi5Bc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` A…·¹Nθ ``` Create a list of the first `n` natural numbers. ``` W⌈θ« ``` Repeat until all elements are zero. ``` Eθ§ #κ ``` Print the last binary digit of each element of the list as a or `#`. ``` ↓⸿ ``` Move to the previous column. ``` AEθ÷κ²θ ``` Divide all elements of the list by two. ``` »‖O ``` Once the left half has been drawn, reflect it. [Answer] # J, 29 bytes ``` ' #'{~(],}.@|.)"1@(#.^:_1)@i. ``` [Try it online!](https://tio.run/##y/r/P81WT0FdQVm9uk4jVqdWz6FGT1PJ0EFDWS/OKt5Q0yFTj4srNTkjXyFNwcjg/38A "J – Try It Online") ## explanation * `i.` integers up to n, the input * `(#.^:_1)` converted to base 2 * `(],}.@|.)` row by row (`"1` does that part), take the binary number (`]` is the identity fn), and cat it (`,`) with its reverse (`|.`), where the reverse is beheaded (`}.`). * `' #'{~` converts the `1`s and `0`s to hashes and spaces. [Answer] # [Proton](https://github.com/alexander-liao/proton), 95 bytes ``` r=>{for i:range(1,r)print(((bin(i)[2to]).rjust(len(bin(r))-2)[to-1,to by-1]).replace('0',' '))} ``` [Try it online!](https://tio.run/##HcpBCsIwEAXQq2SX@ZCI6cKFUC9SXLSSSKTMhHG6EPHskXb7eE3FhHsZu463bxF19aozPzOloGha2YhoqUwV02Byx0lf29tozXywAnHAZBJTMHHLJ6b95LbOj0z@7IN3Hvj1QumC/gc "Proton – Try It Online") There are too many bugs to not have too many brackets... I need to fix up the parser... [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` n=input()+1 w=' #' while len(w)<n:w=[s+l+s for s in' #'for l in w] print'\n'.join(w[1:n]) ``` [Try it online!](https://tio.run/##FctBCoAgEEbhvacYaGEiBAVtIk9SLosm5FfSGDq91e5bvJeeckQMtcIx0l1aY3slTlOjlRwcNgobWjEzJnFLtsFm2uNFmRh/9Dt8JvEqXYyiV@jujPxNSz/Bm1rHFw "Python 2 – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 11 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ∫2─0@ŗ}¹╬⁴╚ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjJCMiV1MjUwMDBAJXUwMTU3JTdEJUI5JXUyNTZDJXUyMDc0JXUyNTVB,inputs=MTY_) [Answer] # PHP, ~~98 97 95~~ 94+1 bytes ``` while($r++<$argn)echo$s=strtr(sprintf("%".-~log($argn,2).b,$r),0," "),substr(strrev(" $s"),1); ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/68d0b8006aac9915276447b94e6a63c890f07ac0). Uses `1` as non-whitespace. [Answer] # [K (ngn/k)](https://github.com/ngn/k), 19 bytes ``` {" #"@+a,1_|a:!x#2} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlpJQVnJQTtRxzC@JtFKsULZqPa/oYNSTJ6SfpqCifV/AA "K (ngn/k) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` n=input() for i in range(n):s=bin(2**n.bit_length()+i+1)[3:].replace(*'0 ');print s+s[-2::-1] ``` [Try it online!](https://tio.run/##BcFBCoMwEAXQfU8xOycJSpPSTcSTiBQtqQ7INyTTRU@fvpd/elwIrWES5K@yuX2uQkICKiv2xDCxTpuAg7UYNtHXmbDrwcaJ82Z@xGUoKZ/rO7Ht7tSZMReBUnV17kOMvV9a888/ "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 146 108 105 bytes ``` #define o putchar(33-!(c&(1<<n))) b;c;p(n){--n?o,p(n),o:o;}f(n){while(n>>++b);while(c++<n)p(b),puts("");} ``` [Try it online!](https://tio.run/##JY3NCsIwEITveYpYQXab5FB6M6U@iHhI1/4EdFNq1UPps8cE5zTzwcyQGYliPN77wXMvg5zfK01ugbo2B6ATVE3DiCg6S3YGxs0YvgSdrQ7nYPchw@/kHz1w2yrVof0nUipVZ@hQp9EXFAXaPXpe5dN5hmzcMpKW@U@WZQofFJuQSQO4NXjI6FrdEK3YY6yrHw "C (gcc) – Try It Online") This is a function `f(n)` called with the number of rows `n`, using an exclamation mark (`!`) as non-whitespace character. **Explanation**: ``` #define o putchar(33-!(c&(1<<n))) b;c; p(n) { // least significant bit not yet reached? --n? // print bit twice with recursive step between o, p(n), o // for least significant, just print this bit :o; } // the main "cathedral function": f(r) { // determine max number of bits to shift while(r>>++b); // iterate over rows while(c++<r) // print row recursively p(b), // newline puts(""); } /** * footer, just calling the function */ main(int argc, char **argv) { f(atoi(argv[1])); } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~156~~ 149 bytes **-7 bytes by @ConorO'Brien** ``` f=(n,w=n.toString(2).length,b=n.toString(2).replace(/0/g," "),s=" ".repeat(w-b.length))=>`${--n?f(n,w)+s+b+[...b].reverse().join``.substr(1):s+"1"} ` ``` [Try it online!](https://tio.run/##XYy9CsIwFEZ3n0KKQy75aRVchOhDOIqQpN7GlpCUJLaD@OyxBSenA4fzfYOedGpjP2buwwNL6STxbJZe5HDNsfeWHEA49DY/mfnTEUenWyR1U1tWbStgSS5YPepMZm5@SwB5Vrs35/7SrfdAEzX0JoQw96WeMCYkIIbQe6VEepmUI9nDKdFqX302qrTBp@BQuGBJR44NQPkC "JavaScript (Node.js) – Try It Online") Recursive function. Unfortunately JS does not support reversing a string, so 19 bytes are used on turning it into an array and back. [Answer] # [Perl 5](https://www.perl.org/), 77 + 1 (-n) = 78 bytes ``` $x=1+(log$_)/log 2;map{$_=sprintf"%0${x}b",$_;y/0/ /;say$_.chop.reverse}1..$_ ``` [Try it online!](https://tio.run/##DcVRCoMwDADQq4hk4Jim7UAQikfYGYJKtwmuDa2Minj1Zb6fxy4urQjk3tyqJbyAruqsuNvPwDtQnzjOfn2WFw17PsayBrKb0qpQNg0bEE7vwBjd18XkDoMIJNL9Aq9z8EmaR4vaaGn8Hw "Perl 5 – Try It Online") Using '1' instead of '#' because it saves a couple bytes. [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ç▼┼Ö☺Ç¬É ``` [Run and debug it](https://staxlang.xyz/#p=871fc5990180aa90&i=22&a=1) Shortest answer so far. Uses CP437 charcode 1 in place of `#`. ASCII equivalent: ``` {:B|pm|Cm ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õ_s*iS)êÃû ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9V9zKmlTKerD%2bw&input=MTU) ``` õ_s*iS)êÃû :Implicit input of integer U õ :Range [1,U] _ :Map s : Convert to string in base *i : "*" prepended with S : Space ) : End base conversion ê : Palindromise à :End map û :Centre pad each element with spaces to the length of the longest :Implicit output, joined with newlines ``` ]
[Question] [ ## Background I want to buy an plot of land and build my house on it. My house should be rectangular, and as large as possible; however, the available plots have lots of rocky areas that I cannot build on, and I'm having trouble fitting a potential house on the plots. I want you to write a program that analyzes the plots for me. ## Input and output Your input is a rectangular 2D array of bits, of size at least 1×1, in any reasonable format. The array represents a plot of land; `1`s are "good" areas where I could build my house, and `0`s are "rocky" areas where the house cannot be built. Your output shall be the maximal area of a solid rectangle of `1`s in the input array. It represents the area of the largest house I could build on the plot. Note that if there are no `1`s in the input, then the output is `0`. ## Example Consider the input ``` 101 011 111 ``` The largest rectangle of `1`s is the 2×2 rectangle in the lower right corner. This means that the correct output is `4`. ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. ## Test cases ``` 0 -> 0 1 -> 1 00 00 -> 0 01 10 -> 1 01 11 -> 2 111 010 111 -> 3 101 011 111 -> 4 0111 1110 1100 -> 4 1111111 1110111 1011101 -> 7 111011000 110111100 001111110 011111111 001111110 000111100 000011000 -> 20 000110000 110110010 110111110 110011100 010011111 111111111 111101110 -> 12 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~21~~ ~~20~~ ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṡṂ€€×" ‘×¥\ç"Ụ€FṀ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmh4bmC4oKs4oKsw5ciCuKAmMOXwqVcw6ci4buk4oKsRuG5gA&input=&args=W1sxLDEsMSwxLDEsMSwxXSwKIFsxLDEsMSwwLDEsMSwxXSwKIFsxLDAsMSwxLDEsMCwxXV0) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmh4bmC4oKs4oKsw5ciCuKAmMOXwqVcw6ci4buk4oKsRuG5gArDh-KCrEc&input=&args=WwogW1swXV0sCgogW1sxXV0sCgogW1swLDBdLAogIFswLDBdXSwKCiBbWzAsMV0sCiAgWzEsMF1dLAoKIFtbMCwxXSwKICBbMSwxXV0sCgogW1sxLDEsMV0sCiAgWzAsMSwwXSwKICBbMSwxLDFdXSwKCiBbWzEsMCwxXSwKICBbMCwxLDFdLAogIFsxLDEsMV1dLAoKIFtbMCwxLDEsMV0sCiAgWzEsMSwxLDBdLAogIFsxLDEsMCwwXV0sCgogW1sxLDEsMSwxLDEsMSwxXSwKICBbMSwxLDEsMCwxLDEsMV0sCiAgWzEsMCwxLDEsMSwwLDFdXSwKCiBbWzEsMSwxLDAsMSwxLDAsMCwwXSwKICBbMSwxLDAsMSwxLDEsMSwwLDBdLAogIFswLDAsMSwxLDEsMSwxLDEsMF0sCiAgWzAsMSwxLDEsMSwxLDEsMSwxXSwKICBbMCwwLDEsMSwxLDEsMSwxLDBdLAogIFswLDAsMCwxLDEsMSwxLDAsMF0sCiAgWzAsMCwwLDAsMSwxLDAsMCwwXV0sCgogW1swLDAsMCwxLDEsMCwwLDAsMF0sCiAgWzEsMSwwLDEsMSwwLDAsMSwwXSwKICBbMSwxLDAsMSwxLDEsMSwxLDBdLAogIFsxLDEsMCwwLDEsMSwxLDAsMF0sCiAgWzAsMSwwLDAsMSwxLDEsMSwxXSwKICBbMSwxLDEsMSwxLDEsMSwxLDFdLAogIFsxLDEsMSwxLDAsMSwxLDEsMF1dCl0). ### Background Let **M** be a matrix of bits such as ``` 0 0 0 1 1 0 0 0 0 1 1 0 1 1 0 0 1 0 1 1 0 1 1 1 1 1 0 1 1 0 0 1 1 1 0 0 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 ``` We start by counting the number of **1** bits in each column of **M**, resetting the count every time we encounter a **0** bit. For our example matrix, this gives ``` 0 0 0 1 1 0 0 0 0 1 1 0 2 2 0 0 1 0 2 2 0 3 3 1 1 2 0 3 3 0 0 4 2 2 0 0 0 4 0 0 5 3 3 1 1 1 5 1 1 6 4 4 2 2 2 6 2 2 0 5 5 3 0 ``` Next, we compute all contiguous sublists of each row. We achieve this by generating all slices of length **k**, where **k** varies between **1** and the number of entries in each row. For the penultimate row, this gives ``` [1], [5], [1], [1], [6], [4], [4], [2], [2] [1, 5], [5, 1], [1, 1], [1, 6], [6, 4], [4, 4], [4, 2], [2, 2] [1, 5, 1], [5, 1, 1], [1, 1, 6], [1, 6, 4], [6, 4, 4], [4, 4, 2], [4, 2, 2] [1, 5, 1, 1], [5, 1, 1, 6], [1, 1, 6, 4], [1, 6, 4, 4], [6, 4, 4, 2], [4, 4, 2, 2] [1, 5, 1, 1, 6], [5, 1, 1, 6, 4], [1, 1, 6, 4, 4], [1, 6, 4, 4, 2], [6, 4, 4, 2, 2] [1, 5, 1, 1, 6, 4], [5, 1, 1, 6, 4, 4], [1, 1, 6, 4, 4, 2], [1, 6, 4, 4, 2, 2] [1, 5, 1, 1, 6, 4, 4], [5, 1, 1, 6, 4, 4, 2], [1, 1, 6, 4, 4, 2, 2] [1, 5, 1, 1, 6, 4, 4, 2], [5, 1, 1, 6, 4, 4, 2, 2] [1, 5, 1, 1, 6, 4, 4, 2, 2] ``` Next, we map each slice to the product of its minimum and its length. For each slice, this computes the area of the rectangle of **1** bits of maximum height that has the given slice as bottom row. For the slices of length **3** of the penultimate row of our example matrix, this gives ``` 3 3 3 3 12 6 6 ``` All that's left to do is take the maximum across all slices of all rows. For our example matrix, this gives **12**. ### How it works ``` ‘×¥\ç"Ụ€FṀ Main link. Argument: M (2D list of bits) \ Reduce the columns of M by the link to the left. ¥ Combine the two atoms to the left into a dyadic chain. ‘ Increment the left argument. × Multiply the result with the right argument. Ụ€ Grade up each; yield the indices of each row of M, sorted by their values. The order is not important here; we just need the indices. ç" Apply the helper link to each element of the result to the left and the corresponding element of the result to the right. F Flatten the resulting, nested list. Ṁ Extract the maximum. ṡṂ€€×" Helper link. Arguments: R (row), X (indices of R) ṡ For each k in X, split R into overlapping slices of length k. Ṁ€€ Compute the minimum of each individual slice. ×" Multiply the minima of all slices of length k by k. ``` [Answer] # MATL, ~~32~~ ~~31~~ 27 bytes ``` n:"@:"@1M2$ltntG4$bZ+=a*vX> ``` This uses a brute-force 2D convolution-based approach. All possible rectangle sizes are created and convolved with the terrain. The maximum result of all convolutions is the maximal rectangle area. This is an extremely inefficient solution because in order to save bytes, I create kernels for all rectangles between `[1, 1]` and `[numel(input) numel(input)]` rather than actually determining the number of rows/columns in the input to determine the proper rectangle dimension ranges. *Thanks to @Luis for suggesting the usage of `M` and omitting the `]]`.* [**Try it Online!**](http://matl.tryitonline.net/#code=bjoiQDoiQDFNMiRsdG50RzQkYlorPWEqdlg-&input=WzEsMSwxLDEsMSwxLDE7MSwxLDEsMCwxLDEsMTsxLDAsMSwxLDEsMCwxXQ) **Explanation** ``` % Implicitly grab input as a 2D numeric array n % Compute the number of elements in the input (over estimation of max kernel size) : % Create array 1:n " % For each value @ % Current loop index : % Create an array from 1:(current_index) " % For each of these values @ % Push the current index onto the stack 1M % Grab the input to the previous function call (the outer index) 2$l % Create an array of 1's whose dimensions are specified by top two stack elements tn % Duplicate this array and compute number of elements t % Duplicate this number G % Explicitly grab input 4$b % Bubble up the 4th element from the stack (the kernel) Z+ % Perform 2D convolution of this kernel and the input =a % Determine if any convolution result (in each column) is equal to the area of the kernel. % This yields a row vector * % Multiply the logical result by the area v % Vertically concatenate all results (forces the row vectors above to be column vectors) X> % Compute the maximum yielding the largest area % Implicitly display the result. ``` [Answer] # Julia, ~~83~~ ~~60~~ ~~57~~ 53 bytes ``` !M=M⊆1?sum(M):maximum(t->!rotr90(M,t)[2:end,:],0:3) ``` [Try it online!](http://julia.tryitonline.net/#code=IU09TeKKhjE_c3VtKE0pOm1heGltdW0odC0-IXJvdHI5MChNLHQpWzI6ZW5kLDpdLDA6MykKCmZvciBNIGluCigKcmVzaGFwZShbMF0sKDEsMSkpCiwKcmVzaGFwZShbMV0sKDEsMSkpCiwKWzAgMAogMCAwXQosClswIDEKIDEgMF0KLApbMCAxCiAxIDFdCiwKWzEgMSAxCiAwIDEgMAogMSAxIDFdCiwKWzEgMCAxCiAwIDEgMQogMSAxIDFdCiwKWzAgMSAxIDEKIDEgMSAxIDAKIDEgMSAwIDBdCiwKWzEgMSAxIDEgMSAxIDEKIDEgMSAxIDAgMSAxIDEKIDEgMCAxIDEgMSAwIDFdCiwKWzEgMSAxIDAgMSAxIDAgMCAwCiAxIDEgMCAxIDEgMSAxIDAgMAogMCAwIDEgMSAxIDEgMSAxIDAKIDAgMSAxIDEgMSAxIDEgMSAxCiAwIDAgMSAxIDEgMSAxIDEgMAogMCAwIDAgMSAxIDEgMSAwIDAKIDAgMCAwIDAgMSAxIDAgMCAwXQopCiAgICBkaXNwbGF5KCFNKQogICAgcHJpbnQoIiAiKQplbmQ&input=) The last test case exceeds TIO's time limit, but I've verified it locally. ### How it works First, **!** checks if its matrix argument **M** consists entirely of **1**'s. * If so, **!** returns the sum of **M**'s entries, which is equal to its area. * If not, **!** does the following: 1. Rotate **M** by **0°**, **90°**, **180°** and **270°** clockwise. 2. Remove the first row of each of the four rotations, effectively removing one of top row, bottom row, leftmost column and rightmost column of **M**. 3. Call itself recursively on each of the submatrices. 4. Return the maximum of the return values from the recursive calls. [Answer] ## JavaScript (ES6), 97 bytes ``` a=>a.map((b,i)=>a.slice(i).map((c,j)=>c.map((d,k)=>(n=(b[k]&=d)&&n+j+1)>r?r=n:0,n=0),c=[]),r=0)|r ``` Turns out bit twiddling still wins. Accepts an array of array of integers. Ungolfed: ``` function rect(array) { var max = 0; for (var i = 0; i < array.length; i++) { var bits = array[i]; for (var j = 0; i + j < array.length;) { var row = array[i + j]; j++; var size = 0; for (var k = 0; k < row.length; k++) { if (!row[k]) bits[k] = 0; size = ones[k] ? size + j : 0; if (size > max) max = size; } } } return max; } ``` The array is sliced by rows as per the other answers, so each possible range of rows is looped over. Given a range of rows, the next step is to measure the available rectangles. This is achieved by ANDing the rows together bitwise; the result is a list of bits which were set in the entire range of rows. It then remains to find the maximal length of set bits in the row and multiply that by the height of the range. Test shamelessly stolen from @ed65: ``` f= a=>a.map((b,i)=>a.slice(i).map((c,j)=>c.map((d,k)=>(n=(b[k]&=d)&&n+j+1)>r?r=n:0,n=0),c=[]),r=0)|r // test cases as strings, converted to 2d arrays result.textContent = [ ['0', 0], ['1', 1], ['00 00', 0], ['01 10', 1], ['01 11', 2], ['111 010 111', 3], ['101 011 111', 4], ['0111 1110 1100', 4], ['1111111 1110111 1011101', 7], ['111011000 110111100 001111110 011111111 001111110 000111100 000011000', 20], ['000110000 110110010 110111110 110011100 010011111 111111111 111101110', 12] ].map(t => t[0].replace(/ /g, '\n') + '\n' + t[1] + '\n' + f(t[0].split` `.map(r => [...r]))).join`\n\n` ``` ``` <pre id=result></pre> ``` [Answer] # Python 2.7, ~~93~~ ~~91~~ ~~89~~ ~~81~~ 79 bytes ``` f=lambda M,t=1:max(f(M[1:]),f(zip(*M)[::-1],t+1))if`t/3`in`M`else`M`.count(`t`) ``` Input is a list of tuples. Verify the smaller test cases [here](http://ideone.com/lquBjI) and the larger test cases [here](http://ideone.com/zAzDzg). Without memoization, the last two test cases exceed Ideone's time limit, as they require, resp., **1,530,831,935** and **2,848,806,121** calls to **f**, which takes **39** and **72** minutes on my machine. ### Algorithm For a given matrix **M**, the general idea is to iterate over all submatrices of **M** by removing top rows and rotating quarter turns counterclockwise, keeping track of the sizes of encountered submatrices that consist entirely of **1** bits. Golfing a straightforward recursive implementation of the above idea lead to a function **f(M)** that does the following. 1. If **M** doesn't contain any **0** bits, return its number of **1** bits. 2. If we have rotated **M** two times already and it doesn't contain any **1** bits, return **0**. 3. If we have rotated **M** five times already, return **0**. 4. Recursively call **f** on **M** without its top row. 5. Recursively call **f** on **M** rotated a quarter turn counterclockwise. 6. Return the maximum of the return values from the recursive calls. ### Code In the implementation, we use an additional function argument **t** that defaults to **1** to keep track of how many times we have rotated this particular matrix already. This allows condensing steps 1 to 3 into a single step by testing `​`t/3`in`M`​` and returning `​`M`.count(`t`)​` if the test fails. 1. If **t = 1**, we haven't rotated this particular submatrix previously in this branch. **t / 3 = 0**, so `​`t/3`in`M`​` will return **True** iff the string representation of **M** contains the character **0**. If it doesn't, we return ​`​`M`.count(`t`)​`, the number of times the character **1** appears in the string representation of **M**. Note that a matrix without **0** bits can occur only if **t = 1**, since we do not recurse in this case. 2. If **3 ≤ t ≤ 5**, we've previously rotated this particular submatrix at least two times in this branch. **t / 3 = 1**, so `​`t/3`in`M`​` will return **True** iff the string representation of **M** contains the character **1**. If it doesn't, we return ​**0** computed as `​`M`.count(`t`)​`, the number of times the string representation of **t** (i.e., the character **3**, **4** or **5**) appears in the string representation of **M**. 3. If **t = 6**, we've previously rotated this particular submatrix five times in this branch. **t / 3 = 2**, so `​`t/3`in`M`​` will return **False**, because the string representation of **M** does not contain the character **2**. We return ​**0** computed as `​`M`.count(`t`)​`, the number of times the character **6** appears in the string representation of **M**. If **f** didn't return already, the remaining steps are executed. 4. `f(M[1:])` calls **f** on **M** without its top row. Since **t** isn't specified, it defaults to **1**, signaling that this is the first time **f** encounters this particular submatrix in this branch. 5. `f(zip(*M)[::-1],t+1)` calls **f** on **M** rotated a quarter turn counterclockwise, incrementing **t** to keep track of the time we've rotated this particular submatrix in this branch. The quarter turn is obtained by zipping the rows of **M** with each other, returning tuples of the corresponding elements of **M**'s rows, thus transposing **M**, then reversing the order of rows (i.e., placing the top row at the bottom and vice versa). 6. Finally `max` returns the maximum of the return values from the recursive calls. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~27~~ ~~23~~ 20 bytes *-3 bytes by Adám and ngn* ``` {⌈/∊(×/×⍵⍷⍨⍴∘1)¨⍳⍴⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pRT4f@o44ujcPT9Q9Pf9S79VHv9ke9Kx71bnnUMcNQ8xCQtRnE6d1a@z/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv@vACoxVjAH6jBUwIQGGCwgzZWmUAEA "APL (Dyalog Extended) – Try It Online") ``` {⌈/∊(×/×⍵⍷⍨⍴∘1)¨⍳⍴⍵} Monadic function taking an argument ⍵: ⍳⍴⍵ Indices: e.g. for a 3x7 array (1 1) (1 2) ... (1 7) (2 1) (2 2) ... (2 7) (3 1) (3 2) ... (3 7) (×/×⍵⍷⍨⍴∘1) Helper fn: Takes ⍵ and x (e.g. (2 2)) ⍴∘1 Make an array of 1s of shape x. Call it a. ⍵⍷⍨ All places where a exists in x ×/ Product of x's dims (size of a) × Size of a where a is in ⍵, and 0 elsewhere. (×/×⍵⍷⍨⍴∘1)¨ Call the helper function on x and each (¨) index. We now have a nested list containing sizes of blocks in ⍵ and many 0s. ∊ Flatten ⌈/ Find the maximum value. ``` [Answer] # JavaScript (ES6), 154 ~~176~~ *Edit* tried to shorten a bit, but cannot compete against @Neil's solution Try every possible rectangle, return the max size. Probably the same algorithm of the Matl answer, just 6 times longer. Input as a 2d array of integers ``` g=>g.map((r,i)=>r.map((x,j)=>v=s(r,j,(_,l)=>s(g,i,(_,k)=>!s(g,k,r=>s(r,l,x=>!x,l+j+1),k+i+1)))&(t=-~i*-~j)>v?t:v),s=(a,i,l,j)=>a.slice(i,j).some(l),v=0)|v ``` *Less golfed* This is the original algorithm, the golfed version abuse a lot of array traversing function istead of for loops ``` g=>{ v = 0 for(i = h = g.length; i; i--) for(j = w = g[0].length; j; j--) { p = true for(k=0; p && k <= h-i; k++) for(l=0; p && l <= w-j; j++) p = g.slice(k, k+i).some(r=>r.slice(l, l+j).some(x=>!x)); if (!p && i*j<v) v = i*j } return v } ``` **Test** ``` f=g=>g.map((r,i)=>r.map((x,j)=>v=s(r,j,(_,l)=>s(g,i,(_,k)=>!s(g,k,r=>s(r,l,x=>!x,l+j+1),k+i+1)))&(t=-~i*-~j)>v?t:v),s=(a,i,l,j)=>a.slice(i,j).some(l),v=0)|v console.log=(...x)=>O.textContent+=x+'\n' // test cases as strings, converted to 2d arrays ;[ ['0',0],['1',1],['00 00',0],['01 10',1],['01 11',2], ['111 010 111',3],['101 011 111',4], ['0111 1110 1100',4],['1111111 1110111 1011101',7], ['111011000 110111100 001111110 011111111 001111110 000111100 000011000',20], ['000110000 110110010 110111110 110011100 010011111 111111111 111101110',12] ].forEach(t=>{ var k=t[1] var p=t[0].split` `.map(r=>[...r].map(x=>+x)) var r=f(p) console.log((r==k?'OK':'KO')+' '+r+(r==k?'':' expected '+k)+'\n'+p.join`\n`+'\n') }) ``` ``` <pre id=O></pre> ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~20~~ ~~17~~ 15 bytes *Thanks to [Kroppeb](https://codegolf.stackexchange.com/users/81957/kroppeb) for 2 bytes* ``` {s\sc≡ᵛ¹l}ᶠ⌉|hh ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7o4pjj5UefCh1tnH9qZU/tw24JHPZ01GRn//0dHG@iAoCEQQlgGsTrREB5MzBBNDAIRYjBRiF4DFDEghKpDgUhicN2xsf8dAQ "Brachylog – Try It Online") ### Explanation ``` { }ᶠ Find all possible outputs of the following predicate: s Find a sublist of the array (i.e. remove 0 or more rows from the top and/or bottom) \ Transpose the array s Find a sublist again The result is some sub-rectangle of the array c Concatenate all the rows in that rectangle into one list ≡ᵛ¹ Verify that all the elements are 1 l Get the length (i.e. how many 1's make up the rectangle) Now we have a list of the sizes of all possible 1-rectangles ⌉ Take the maximum | If no 1-rectangles could be found: hh Take the head of the head of the array (i.e. the top left element) Since the array contains no 1's in this case, this will give 0 ``` [Answer] # [R](https://www.r-project.org/), ~~129~~ 122 bytes ``` function(M,D=dim(M),L=`for`){L(i,1:D,L(j,1:D[2],L(r,0:(D-i),L(c,0:(D[2]-j),F<-max(F,i*j*(i*j==sum(M[r+1:i,c+1:j]))))))) F} ``` [Try it online!](https://tio.run/##bVFBb4IwGD3bX9HEg8UV95WZLDFyM57wsqszERG2klIMrRuL8be7IsgKrIfSvu@9971@FLcxjnL5FRca688Yx2WYnUSssNIFlx8Kc6lzHEr8huGZ4Sw0cIl0vinx0sXJWUaa55LoUjsXhHHgx4IYqToJriuUTt7lxHFM6ZjPolAIUhy4PFIRnk7ihwS0tSidUM2O@fkgYnKWgittGRU8@1aGQifGzCx0RSjxb614Q1f@kWdk49DA3yd5sXcuAeGULVY0IGn13Xo7cywoLMjK5YZHovvZ4G7q0PXSzcKSrCmfplNiNt9XZ2O4LZ7YgtPI7OnOqRdaX28JqYZAJmAC4TEG9ABYDbAWADCvrxcM2MDaIoOB0io2th76a8QYGgEDNGKP6otVtcTAbKOGO0dWny4BrMsj8rzTmPUVnTvckVr32tFBZdixr5w6E6rNwQ7f6/cPB4Y@UPe6p/DAemxT6KUAYINcvUH0OrAmhz2H4WTqYTR/1rv9Ag "R – Try It Online") Plain and simple brute force approach. Unrolled code and explanation : ``` function(M){ # M is the matrix of 0/1 n = 0 # n is the biggest rectangle found R=nrow(M) C=ncol(M) for(i in 1:R) # for each possible num of rows of the rectangle for(j in 1:C) # for each possible num of cols of the rectangle for(r in 0:(R-i)) # for each possible position offset on the rows for(c in 0:(C-j){ # for each possible position offset on the cols subM = M[1:i+r,1:j+c] # sub-set the matrix given the size of rectangle and offsets if(sum(subM)==i*j) # if sub-matrix is full of 1's rec = i*j # (i.e. nrow*ncol == sum of values in sub-matrix) else # store the rectangle area rec = 0 # otherwise store 0 n = max(n,rec) # keep the maximum rectangle found } } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` π└ÿ§L▓═J║φ§╦╢9 ``` [Run and debug it](https://staxlang.xyz/#p=e3c098154cb2cd4abaed15cbb639&i=[%220%22]%0A[%221%22]%0A[%2200%22+%2200%22]%0A[%2201%22+%2210%22]%0A[%2201%22+%2211%22]%0A[%22111%22+%22010%22+%22111%22]%0A[%22101%22+%22011%22+%22111%22]%0A[%220111%22+%221110%22+%221100%22]%0A[%221111111%22+%221110111%22+%221011101%22]%0A[%22111011000%22+%22110111100%22+%22001111110%22+%22011111111%22+%22001111110%22+%22000111100%22+%22000011000%22]%0A[%22000110000%22+%22110110010%22+%22110111110%22+%22110011100%22+%22010011111%22+%22111111111%22+%22111101110%22]&a=1&m=2) [Answer] # Matlab 106 bytes ``` x=input('');[n,k]=size(x);r=0;for p=1:n;for m=1:k;r=max([p*m*(any(conv2(x,ones(p,m))==p*m)),r]);end;end;r ``` Ungolfed: ``` x=input(''); %//Take input [n,k]=size(x); %//Determine array size r=0; %//Variable for output. Initially zero for p=1:n; %// Loop through the columns for m=1:k; %// Loop through the rows r=max([p*m*(any(conv2(x,ones(p,m))==p*m)),r]);%//See explanation below end; end; r %//Display result ``` The operation in the loop starts with 2D convolution `conv2()` of input array with the `p*m` array of ones. `==p*m` checks if the resulting array contains an element equal to `p*m`. The corresponding element is turned to `1`, all other elements are turned to `0`. `any()` turns the array into vector. Columns containing at least one nonzero entry are turned to `1`, otherwise `0`. `p*m*()` multiplies the vector by `p*m` thereby turning all `1`-s into `p*m`. `[__,r]` square brackets concatenate the obtained result with the previous maximum area stored in `r`. Finally, `max()` finds the maximum value in the resulting vector. [Answer] ## Matlab ~~(222)~~(209) Actually ,this solution brings me shame for being double-sized the actual same-language solution but ... blimey, i had been thinking of it for 6 hours! and the trick is a slightly different build off from Dennis and Neil 's answers. ``` function p=g(x,a,u,i,j),i=i+~u;j=j+u;p=0;if(j*u+i*~u>=size(a,2-u))return;end,x=circshift(x,[0-u -1+u]),a=(x+a).*~~x.*~~a;for h=0+u:1,p=max([p,reshape(a(1:end-j,1:end-i),1,[]),g(~u*(a*h+x*~h)+u*x,a,h,i,j)]);end ``` * The function is called as ``` y=[1 1 1 0 1 1 0 0 0; 1 1 0 1 1 1 1 0 0; 0 0 1 1 1 1 1 1 0; 0 1 1 1 1 1 1 1 1; 0 0 1 1 1 1 1 1 0;]; t=g(y,y,[],0,0,0);t, ``` * I could save more bytes if introduced matrix length in function's dimentions, eventhough, more golfing is ongoing. * How does this proceed? This algorithm adds the actual matrix to itself shifted of it to left direction, with a bit twiddling (&). in any stage the resulted matrix is set as initial and added to itself shifted upward repeatedly,then reloop from the beginning with the new matrix. All sub-elements of all the matrices generated by this operation `(original_matrix+shifted_matrix)&shifted_and_original_matrices)` are maximized to the output. **example:** ``` 1 1 1 1 1 0 2 2 0 0 2 0 0 4 0 M0= 0 1 1 M0<<1= 1 1 0 M1=(M0+M0<<1)&both= 0 2 0 shift(M1,up)= 2 0 0 M2=(M1+sh(M1,u)&both= 0 0 0 1 1 0 1 0 0 2 0 0 0 0 0 0 0 0 2 0 0 4 0 0 M3=(M0<<1+M0<<2)&both= 2 0 0 , M4=(M3+shift(M3,up))&both= 0 0 0 0 0 0 0 0 0 3 0 0 M5=(M1+M0<<2)= 0 0 0 , M6=(M5+shift(M5,up))&both=zeros(3,3). 0 0 0 Max_of_all_values=Max(0,1,2,3,4)=4 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 30 bytes ``` ®åÏ*°X}ÃÕ®£ZãYÄÃm®rm *Zl}Ãc rw ``` [Try all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=ruXPKrBYfcPVrqNa41nEw22ucm0gKlpsfcNjIHJ3&input=WwpbWzBdXQoKW1sxXV0KCltbMCwwXSxbMCwwXV0KCltbMCwxXSxbMSwwXV0KCltbMCwxXSxbMSwxXV0KCltbMSwxLDFdLFswLDEsMF0sWzEsMSwxXV0KCltbMSwwLDFdLFswLDEsMV0sWzEsMSwxXV0KCltbMCwxLDEsMV0sWzEsMSwxLDBdLFsxLDEsMCwwXV0KCltbMSwxLDEsMSwxLDEsMV0sWzEsMSwxLDAsMSwxLDFdLFsxLDAsMSwxLDEsMCwxXV0KCltbMSwxLDEsMCwxLDEsMCwwLDBdLFsxLDEsMCwxLDEsMSwxLDAsMF0sWzAsMCwxLDEsMSwxLDEsMSwwXSxbMCwxLDEsMSwxLDEsMSwxLDFdLFswLDAsMSwxLDEsMSwxLDEsMF0sWzAsMCwwLDEsMSwxLDEsMCwwXSxbMCwwLDAsMCwxLDEsMCwwLDBdXQoKW1swLDAsMCwxLDEsMCwwLDAsMF0sWzEsMSwwLDEsMSwwLDAsMSwwXSxbMSwxLDAsMSwxLDEsMSwxLDBdLFsxLDEsMCwwLDEsMSwxLDAsMF0sWzAsMSwwLDAsMSwxLDEsMSwxXSxbMSwxLDEsMSwxLDEsMSwxLDFdLFsxLDEsMSwxLDAsMSwxLDEsMF1dCl0KLW1S) Approximately a port of Dennis's Jelly answer. The test cases are simply 2D arrays of numbers, converted from the question's format using [this](https://ethproductions.github.io/japt/?v=1.4.6&code=cVIgbXEgbV9tbg==&input=IjExMTExMTEKMTExMDExMQoxMDExMTAxIgotUQ==). Explanation: ``` ® à #For each row: å } # Replace each number with this running total: °X # Increment the previous total Ï* # Multiply it by the current number Õ #Transpose rows and columns ® à #For each column: £ à # Iterate over the range [0..length) as Y: ZãYÄ # Get the subsections of that column with length Y+1 m® } # For each subsection: rm # Get the minimum *Zl # Multiply it by the length c #Flatten everything to a single list of possible rectangle sizes rw #Get the maximum ``` [Answer] # [J](http://jsoftware.com/), 38 bytes ``` ,"0/&(1+i.)/@$>./@,@:((#**/)@,;._3"$)] ``` [Try it online!](https://tio.run/##fZDBCsIwDIbve4owi1tn7dJtMKxMCoInT97FgzjUi@9/qnWts12HhLEm/9fkT5865VkPnYQMGCBI86057E/Hg2YplstcrB6clorseKmYknm@KIqSKrbllzol9KxpcrveX@ZeBz0wiTYVLhW@WpkgEBCuZDLxFapIcE3qQahNEFse5ABpAsSTp0hjgvjiiKIJS7auWTvOEzO8f/r83RJ24xY2gVnbHqPrv6pfiwfGDM70wWCWe@7KMzRFcGJQRBZD1V9kzui/18Ik0W8 "J – Try It Online") ## how ``` ,"0/&(1 + i.)/@$ >./@,@:((# * */)@,;._3"$) ] @$ NB. pass the shape of NB. the input (rows, cols) NB. to... ,"0/&(1 + i.)/ NB. this verb, which will &(1 + i.)/ NB. will first create 2 NB. lists: 1...num rows NB. and 1...num cols. ,"0/ NB. and then creat a cross NB. of every possible NB. concatenation of the two, NB. giving us all possible NB. rectangle sizes. pass NB. that and... ] NB. the original input >./@,@:((# * */)@,;._3"$) NB. to this verb, which ;._3"$ NB. will take every NB. possible rectangle of NB. every size, @, NB. flatten it and... (# * */) NB. multiply the size of NB. the list by the list's NB. product, yielding the NB. size of the list if it's NB. all ones, zero otherwise. ,@: NB. Flatten all those results NB. into one big list >./@ NB. and take the max. ``` ]
[Question] [ **NOTE:** This challenge is currently dead, as I'm unable to install the languages needed to run a match. If someone else has the time and interest to do it, I'm not opposed. **See the bottom of the post for a leaderboard.** This is a semi-cooperative king-of-the-hill challenge, where the bots construct paths through a two-dimensional grid graph. The bot who controls the nodes with the most traffic is the winner. However, it takes more than one bot's resources to actually build a connecting path, so the bots will have to work together -- to some extent. # Gameplay In the following, let `N > 0` be the number of bots in play. ## The Grid The game is played on a two-dimensional integer grid of size `⌊4/3N2⌋ × ⌊4/3N2⌋`, whose bottom left coordinate is at `(0,0)`. Each coordinate `(x,y)` with `0 ≤ y < ⌊4/3N2⌋-1` has outgoing edges to the three coordinates `(x-1,y+1)`, `(x,y+1)`, and `(x+1,y+1)` above it, where the `x`-coordinates are taken modulo `⌊4/3N2⌋`. This means that the grid wraps around at the east and west edges. Every bottom coordinate `(x,0)` is a *source*, and every top coordinate `(x,⌊4/3N2⌋-1)` is a *sink*. The following picture shows an `8 × 8` grid. ![An 8x8 grid.](https://i.stack.imgur.com/9g2nj.png) Each vertex of the graph is either *inactive*, *active*, or *broken*. All vertices start inactive, and can be activated by bots, which will then be their owners. Also, bots can break vertices, and they cannot be repaired. ## Turn Order A turn consists of a *destruction phase* and an *activation phase*. In the destruction phase, each bot may break one inactive vertex. That vertex is broken from then on, and may not be activated by anyone. In the activation phase, each bot may activate one inactive vertex. From then on, they own that vertex, and it cannot be reactivated by anyone else. Several bots may own a single vertex, if they all activate it on the same turn. In each phase, the vertex selections are done simultaneously. ## Scoring One round lasts for exactly `N2` turns. After this, the round is scored as follows. From each active source vertex, we perform `N` times a randomized depth-first search along the active vertices (meaning that the children of each vertex are visited in a random order). If a path is found from the source to some sink, then for all vertices along that path, every owner of the vertex gets one point. The entire game lasts for 100 rounds, and the bot with the most points overall is the winner. I may increase this number, if the variance of the scores is too high. # Additional Rules * No messing with the controller or other submissions. * At most one submission per contestant. * No external resources, except one private text file, wiped clean at the beginning of the game. * Do not design your bot to beat or support specific opponents. * Provide commands to compile and run your bot. Any compiler/interpreter that's freely available for Debian Linux is acceptable. # The Controller The controller is written in Python 3, and can be found [in GitHub](https://github.com/iatorm/grid-routing-battle). See the README file for detailed instructions. Here's an API to get you started: * Bots are started at the beginning of each round, and persist until the end of the round. The communicate with the controller via STDIN and STDOUT, using newline-terminated messages. * `BEGIN [num-of-bots] [num-of-turns] [side-length]` is input at the beginning. * `DESTROY [turn]` is input at the beginning of each destruction phase. Your bot shall respond with either `VERTEX x,y` to choose a vertex, or `NONE`. * `BROKEN [turn] [your-choice] [other-choices]` is input at the end of each destruction phase. The order of the other bots is randomized at the beginning of each game, but stays fixed during it. The choices are presented as `x,y` or `N`. * `ACTIVATE [turn]` and `OWNED [turn] [your-choice] [other-choices]` are the equivalents of the above for the activation phase, and have the same semantics. * `SCORE [your-score] [other-scores]` is input at the end of the game. * Your bot has **1 second** to analyze the results of a phase and choose the next vertex, and **1 second** to quit after given the score. I will test the submissions on my relatively old laptop, so it's better to leave some margin here. **Please remember to flush your output buffer.** Not doing so may hang the controller in some environments. # Leaderboard *Updated 3/13/2015* Peacemaker is up and running, and Funnelweb received an update too. The scores jumped up by an order of magnitude. Connector exceeded the time limit in two games. ``` Funnelweb: 30911 Connector: 18431 Watermelon: 3488 Annoyance: 1552 Explorer: 735 Checkpoint: 720 Random Builder: 535 FaucetBot: 236 Peacemaker: 80 ``` The full log with ASCII art graphics can be found in the controller's repository, in `graphical_log.txt`. Some observations: * Connector can very easily be stopped by breaking a single vertex in front of it. I suspect Annoyance frequently does this. However, it currently makes little sense because only Connector can conceivably construct a path. * Watermelon can get a decent score by simply happening to be on a connecting path (since the DFS is very likely to use its vertices). * Explorer likes to grow vines from the watermelons. * The updated Funnelweb gets really good scores, since Connector usually latches onto it in the lower half of the grid. * The games are getting quite long, the average round taking about 25 seconds on my machine. [Answer] ## Connector (Java) Tries to create a path at a random position. Because it can't create a path on its own, it searches for active cells and uses them. Credit goes to Geobits, from whom I stole some code. Also, this submission isn't finished yet, as it simply stops doing anything as soon as the path is built. **Edit:** If a path is built, Connector tries to create multiple paths along the existing one. ``` import java.awt.Point; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Connector { private static final int INACTIVE = 0; private static final int ACTIVE = 1; private static final int BROKEN = 2; private static final int MINE = 3; private int size = 0; private int[][] grid = new int[size][size]; private Point previousCell = null; private final List<Point> path = new ArrayList<>(); public static void main(String[] args) { new Connector().start(); } private void start() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while(true) { try { String input = reader.readLine(); act(input); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } private void act(String input) throws Exception { String[] msg = input.split(" "); String output = ""; int turn; switch(msg[0]){ case "BEGIN": size = Integer.parseInt(msg[3]); grid = new int[size][size]; break; case "DESTROY": output = "NONE"; break; case "BROKEN": update(msg, true); break; case "ACTIVATE": turn = Integer.parseInt(msg[1]); output = activate(turn); break; case "OWNED": update(msg, false); break; case "SCORE": System.exit(0); break; } if (output.length() > 0) { System.out.println(output); } } private String activate(int turn) { if (turn == 0) { Random r = new Random(); previousCell = new Point(r.nextInt(size), 0); return "VERTEX " + previousCell.x + "," + 0; } Point lastCell = findLastPathCell(previousCell.x, previousCell.y); if (lastCell.y == size-1) { //path is done Point extendingPathPoint = findExtendingPathPoint(); if (extendingPathPoint == null) { return "NONE"; } return "VERTEX " + extendingPathPoint.x + "," + extendingPathPoint.y; } else { int x = findBestX(lastCell.x, lastCell.y); return "VERTEX " + x + "," + (lastCell.y + 1); } } private int findBestX(int x, int y) { int bestScore = Integer.MIN_VALUE; int bestX = 0; for (int i = -1; i <= 1; i++) { int newY = y + 1; int newX = (x + i + size) % size; int score = calcCellScore(newX, newY, 10); if (score > bestScore) { bestScore = score; bestX = newX; } else if (score == bestScore && Math.random() < 0.3) { bestX = newX; } } return bestX; } private int calcCellScore(int x, int y, int depth) { int newY = y + 1; if (depth < 0) { return 1; } if (newY >= size) return 100; int cellScore = 0; for (int i = -1; i <= 1; i++) { int newX = (x + i + size) % size; if (grid[newX][newY] == ACTIVE || grid[newX][newY] == MINE) { cellScore += 5; } else if (grid[newX][newY] == INACTIVE) { cellScore += 1; } else { cellScore -= 2; } cellScore += calcCellScore(newX, newY, depth -1); } return cellScore; } private Point findLastPathCell(int x, int y) { Point thisCell = new Point(x,y); int newY = y + 1; if (newY >= size) { return thisCell; } List<Point> endCells = new ArrayList<>(); endCells.add(thisCell); path.add(thisCell); for (int i = -1; i <= 1; i++) { int newX = (x + i + size) % size; if (grid[newX][newY] == ACTIVE || grid[newX][newY] == MINE) { endCells.add(findLastPathCell(newX, newY)); } } int bestY = -1; Point bestPoint = null; for (Point p : endCells) { if (p.y > bestY) { bestY = p.y; bestPoint = p; } } return bestPoint; } private Point findExtendingPathPoint() { if (path.size() == 0) return null; Random rand = new Random(); for (int i = 0; i < size; i++) { Point cell = path.get(rand.nextInt(path.size())); for (int j = -1; j <= 1; j += 2) { Point newCellX = new Point((cell.x + j + size) % size, cell.y); if (grid[newCellX.x][newCellX.y] == INACTIVE) return newCellX; Point newCellY = new Point(cell.x, cell.y + j); if (cell.y < 0 || cell.y >= size) continue; if (grid[newCellY.x][newCellY.y] == INACTIVE) return newCellY; } } return null; } private void update(String[] args, boolean destroyPhase) { for(int i = 2; i < args.length; i++) { String[] tokens = args[i].split(","); if(tokens.length > 1){ int x = Integer.parseInt(tokens[0]); int y = Integer.parseInt(tokens[1]); if (grid[x][y] == INACTIVE) { if (destroyPhase) { grid[x][y] = BROKEN; } else if (i == 2) { grid[x][y] = MINE; path.add(new Point(x,y)); previousCell = new Point(x,y); } else { grid[x][y] = ACTIVE; } } } } } } ``` [Answer] # Funnelweb, Python 2 version 1.2 - Better joining code, added new animation Named after one of Australia's less friendly spiders. This bot first builds a funnel-shaped nest in the top rows, then lures other bots into building paths for traffic to the nest. Here is a new animation of a 6 bot game on a 4/3N^2 board showing the funnelweb and some simpler bots: ![bots6.gif](https://i.stack.imgur.com/k66LL.gif) The funnelweb's Python code: ``` from random import * import sys ME = 0 def pt(x,y): return '%u,%u' % (x % side_len, y) while True: msg = raw_input().split() if msg[0] == 'BEGIN': turn = 0 numbots, turns, side_len = map(int, msg[1:]) R = range(side_len) top = side_len - 1 grid = dict((pt(x, y), []) for x in R for y in R) mynodes = set() deadnodes = set() freenodes = set(grid.keys()) mycol = choice(R) extra = sample([pt(x,top) for x in R], side_len) path = [(mycol, y) for y in range(top, top - side_len/6, -1)] moves = [] fence = [] for x,y in path: moves.append( [pt(x,y), pt(x+1,y), pt(x-1,y)] ) fence.extend( [pt(x+1,y), pt(x-1,y)] ) for dx in range(2, side_len): fence.extend( [pt(x+dx,y), pt(x-dx,y)] ) for x,y in [(mycol, y) for y in range(top - side_len/6, top - 3*side_len/4, -1)]: moves.append( [pt(x,y), pt(x+1,y), pt(x-1,y)] ) elif msg[0] == 'DESTROY': target = 'NONE' while fence: loc = fence.pop(0) if loc in freenodes: target = 'VERTEX ' + loc break print target sys.stdout.flush() elif msg[0] == 'BROKEN': for rid, loc in enumerate(msg[2:]): if loc != 'N': grid[loc] = None deadnodes.add(loc) freenodes.discard(loc) if loc in extra: extra.remove(loc) elif msg[0] == 'ACTIVATE': target = 'NONE' while moves: loclist = moves.pop(0) goodlocs = [loc for loc in loclist if loc in freenodes] if goodlocs: target = 'VERTEX ' + goodlocs[0] break if target == 'NONE': if extra: target = 'VERTEX ' + extra.pop(0) else: target = 'VERTEX ' + pt(choice(R), choice(R)) print target sys.stdout.flush() elif msg[0] == 'OWNED': for rid, loc in enumerate(msg[2:]): if loc != 'N': grid[loc].append(rid) if rid == ME: mynodes.add(loc) freenodes.discard(loc) if loc in extra: extra.remove(loc) turn += 1 elif msg[0] == 'SCORE': break ``` The spider is run with `python funnelweb.py`. [Answer] # Checkpoint, Java This bot tries to create checkpoints so that any valid path passes through one of my vertices. Since there are N2 turns and the board is 2N2 across, I can activate/break every node on a single horizontal line (assuming I'm there first). Do this in an alternating pattern (`x` is broken, `o` is mine): ``` xoxoxoxoxoxox... ``` If you want to make a path, you need to go through my checkpoints :) Now, there are several issues this might face. First, it's not going to do very well at all unless there are many paths. Since he doesn't make *any* productive paths himself, he really is totally reliant on there being some competitors. Even a couple competitors combining to make a single path won't help much, since he only scores one spot for each path found. What he needs to shine is probably quite a few bots making quite a few different paths. Even then, it might not score *very* highly, but it was an idea I had in chat, so... If one of the spaces on the line is blocked/claimed already, I just search for a nearby spot I can use (preferably on the same `x` line, just shifted vertically). --- ``` import java.io.BufferedReader; import java.io.InputStreamReader; public class Checkpoint { public static void main(String[] args) { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while(true) try { String input = reader.readLine(); act(input); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } static void act(String input) throws Exception{ String[] msg = input.split(" "); String output = ""; int turn; boolean found = false; switch(msg[0]){ case "BEGIN": size = Integer.parseInt(msg[3]); grid = new int[size][size]; target = size/2; break; case "DESTROY": turn = Integer.parseInt(msg[1]); for(int x=0;x<size;x+=2) for(int y=0;y<size&&!found;y++) if(grid[(x+turn*2)%size][(y+target)%size]==INACTIVE){ output = "VERTEX " + ((x+turn*2)%size) + "," + ((y+target)%size); found = true; } if(output.length() < 1) output = "NONE"; break; case "BROKEN": for(int i=2;i<msg.length;i++){ String[] tokens = msg[i].split(","); if(tokens.length>1){ int x = Integer.parseInt(tokens[0]); int y = Integer.parseInt(tokens[1]); if(grid[x][y]==INACTIVE) grid[x][y] = BROKEN; } } break; case "ACTIVATE": turn = Integer.parseInt(msg[1]); for(int x=1;x<size;x+=2) for(int y=0;y<size&&!found;y++) if(grid[(x+turn*2)%size][(y+target)%size]==INACTIVE){ output = "VERTEX " + ((x+turn*2)%size) + "," + ((y+target)%size); found = true; } if(output.length() < 1) output = "NONE"; break; case "OWNED": for(int i=2;i<msg.length;i++){ String[] tokens = msg[i].split(","); if(tokens.length>1){ int x = Integer.parseInt(tokens[0]); int y = Integer.parseInt(tokens[1]); if(i==2){ if(grid[x][y]==INACTIVE) grid[x][y] = MINE; }else{ if(grid[x][y]==INACTIVE) grid[x][y]=ACTIVE; } } } break; case "SCORE": System.exit(0); break; } if(output.length()>0) System.out.println(output); } static int size = 2; static int target = size/2; static int[][] grid = new int[size][size]; static final int INACTIVE = 0; static final int ACTIVE = 1; static final int BROKEN = 2; static final int MINE = 3; } ``` --- To compile, it's `javac Checkpoint.java`. To run, `java Checkpoint`. You'll want to add/change the path to reflect wherever it is. [Answer] # Watermelon, Java Attempts to draw watermelons on the grid. ``` import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Watermelon { private static int numberOfBots; private static int numberOfTurns; private static int sideLength; private static int turn = 0; private static int[][] theGrid; private static final int INACTIVE = -2; private static final int BROKEN = -1; private static final int MINE = 0; private static final int ACTIVE = 1; private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static PrintStream out = System.out; public static void main(String[] args) throws IOException { while (true){ String[] input = in.readLine().trim().split(" "); String instruction = input[0]; switch (instruction){ case "BEGIN": begin(input); break; case "DESTROY": destroy(input); break; case "BROKEN": broken(input); break; case "ACTIVATE": activate(input); break; case "OWNED": owned(input); break; default: return; } out.flush(); } } private static void begin(String[] input) { numberOfBots = Integer.parseInt(input[1]); numberOfTurns = Integer.parseInt(input[2]); sideLength = Integer.parseInt(input[3]); theGrid = new int[sideLength][sideLength]; for (int x = 0; x < sideLength; x++){ for (int y = 0; y < sideLength; y++){ theGrid[x][y] = INACTIVE; } } } private static void owned(String[] input) { turn = Integer.parseInt(input[1]); for (int i = input.length - 1; i >= 2; i--){ if (input[i].equals("N")){ continue; } String[] coordinates = input[i].split(","); int x = Integer.parseInt(coordinates[0]); int y = Integer.parseInt(coordinates[1]); int player = i - 2; if (player == 0){ theGrid[x][y] = MINE; } else { theGrid[x][y] = ACTIVE; } } } private static void activate(String[] input) { turn = Integer.parseInt(input[1]); double[][] values = new double[sideLength][sideLength]; List<Point> pointList = new ArrayList<>(); for (int x = 0; x < sideLength; x++){ for (int y = 0; y < sideLength; y++){ if (theGrid[x][y] == MINE || theGrid[x][y] == ACTIVE){ for (int x1 = 0; x1 < sideLength; x1++){ for (int y1 = 0; y1 < sideLength; y1++){ double distance = Math.pow(x - x1, 2) + Math.pow(y - y1, 2); values[x1][y1] += 1 / (distance + 1); } } } pointList.add(new Point(x, y)); } } pointList.sort(Comparator.comparingDouble((Point a) -> values[a.x][a.y]).reversed()); for (Point point : pointList){ if (theGrid[point.x][point.y] == INACTIVE){ out.println("VERTEX " + point.x + "," + point.y); return; } } out.println("NONE"); } private static void broken(String[] input) { turn = Integer.parseInt(input[1]); for (int i = 2; i < input.length; i++){ if (input[i].equals("N")){ continue; } String[] coordinates = input[i].split(","); int x = Integer.parseInt(coordinates[0]); int y = Integer.parseInt(coordinates[1]); theGrid[x][y] = BROKEN; } } private static void destroy(String[] input) { turn = Integer.parseInt(input[1]); double[][] values = new double[sideLength][sideLength]; List<Point> pointList = new ArrayList<>(); for (int x = 0; x < sideLength; x++){ for (int y = 0; y < sideLength; y++){ if (theGrid[x][y] == MINE){ for (int x1 = 0; x1 < sideLength; x1++){ for (int y1 = 0; y1 < sideLength; y1++){ double distance = Math.pow(x - x1, 2) + Math.pow(y - y1, 2); values[x1][y1] -= 1 / (distance + 1); } } } if (theGrid[x][y] == ACTIVE){ for (int x1 = 0; x1 < sideLength; x1++){ for (int y1 = 0; y1 < sideLength; y1++){ double distance = Math.pow(x - x1, 2) + Math.pow(y - y1, 2); values[x1][y1] += 1 / (distance + 1) / (numberOfBots - 1); } } } pointList.add(new Point(x, y)); } } pointList.sort(Comparator.comparingDouble((Point a) -> values[a.x][a.y]).reversed()); for (Point point : pointList){ if (theGrid[point.x][point.y] == INACTIVE){ out.println("VERTEX " + point.x + "," + point.y); return; } } out.println("NONE"); } } ``` [Answer] # FaucetBot (in R) Creates a bottleneck on the second line, and activate nodes on the path behind it. ``` infile <- file("stdin") open(infile) repeat{ input <- readLines(infile,1) args <- strsplit(input," ")[[1]] if(args[1]=="BEGIN"){ L <- as.integer(args[4]) M <- N <- matrix(0,nrow=L,ncol=L) x0 <- sample(2:(L-1),1) } if(args[1]=="DESTROY"){ if(args[2]==0){ X <- x0 Y <- 2 }else{ free <- which(M[,2] == 0) mine <- which(N[,2] == 1) X <- free[which.min(abs(free-mine))] Y <- 2 } if(length(X)){cat(sprintf("VERTEX %s,%s\n",X-1,Y-1))}else{cat("NONE\n")} flush(stdout()) } if(args[1]=="BROKEN"){ b <- strsplit(args[args!="N"][-(1:2)],",") o <- strsplit(args[3],",")[[1]] b <- lapply(b,as.integer) if(o[1]!="N") N[as.integer(o[1])+1,as.integer(o[2])+1] <- -1 for(i in seq_along(b)){M[b[[i]][1]+1,b[[i]][2]+1] <- -1} } if(args[1]=="ACTIVATE"){ if(args[2]==0){ broken <- which(M[,2] == -1) free <- which(M[,2] == 0) X <- free[which.min(abs(broken-free))] Y <- 2 }else{ y <- 3 X <- NULL while(length(X)<1){ lastrow <- which(N[,y-1]==1) newrow <- unlist(sapply(lastrow,function(x)which(M[,y]==0 & abs((1:L)-x)<2))) if(length(newrow)){ X <- sample(newrow,1) Y <- y } y <- y+1 if(y>L){X <- x0; Y <- 1} } } cat(sprintf("VERTEX %s,%s\n",X-1,Y-1)) flush(stdout()) } if(args[1]=="OWNED"){ b <- strsplit(args[args!="N"][-(1:2)],",") o <- strsplit(args[3],",")[[1]] b <- lapply(b,as.integer) if(o[1]!="N") N[as.integer(o[1])+1,as.integer(o[2])+1] <- 1 for(i in seq_along(b)){M[b[[i]][1]+1,b[[i]][2]+1] <- 1} } if(args[1]=="SCORE") q(save="no") } ``` If I didn't screw up, the final configuration should be something like: ``` ........ .a..aa.. ..aaa... ..aaa... .xxaxx.. xxxaxxx. etc. ........ ........ ``` Command is `Rscript FaucetBot.R`. [Answer] # Peacemaker, Java Based on Manu's code. Peacemaker search conflict zones (i.e. most BROKEN or ACTIVE vertex concentration) and activates a random vertex nearby. ``` import java.awt.Point; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.stream.IntStream; public class Peacemaker { private static final int INACTIVE = 0; private static final int ACTIVE = 1; private static final int BROKEN = 2; private static final int MINE = 3; private int size = 0; private int[][] grid = new int[size][size]; private int startingPoint = 0; public static void main(String[] args) { new Peacemaker().start(); } private void start() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while(true) { try { String input = reader.readLine(); act(input); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } } private void act(String input) throws Exception { String[] msg = input.split(" "); String output = ""; int turn; switch(msg[0]){ case "BEGIN": size = Integer.parseInt(msg[3]); grid = new int[size][size]; break; case "DESTROY": output = "NONE"; break; case "BROKEN": update(msg, true); break; case "ACTIVATE": turn = Integer.parseInt(msg[1]); output = activate(turn); break; case "OWNED": update(msg, false); break; case "SCORE": System.exit(0); break; } if (output.length() > 0) { System.out.println(output); } } private String activate(int turn) { Random r = new Random(); if (turn == 0) { startingPoint = r.nextInt(size); return "VERTEX " + startingPoint + "," + 0; } else { Point point = searchConflicts(); int posX = point.x; int posY = point.y; while (grid[posX][posY] != INACTIVE) { int previousX = (posX - 1 < 0 ? size - 1 : posX - 1); int nextX = (posX + 1 > size - 1 ? 0 : posX + 1); int previousY = (posY - 1 < 0 ? size - 1 : posY - 1); int nextY = (posY + 1 > size - 1 ? 0 : posY + 1); int choice = r.nextInt(4); switch (choice) { case 0: posX = previousX; break; case 1: posX = nextX; break; case 2: posY = previousY; break; case 3: posY = nextY; break; } } return "VERTEX " + posX + "," + posY; } } private Point searchConflicts() { int previousCellScore = 0; int cellX = 0; int cellY = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j ++) { if (previousCellScore < adjacentCellsScore(i, j)) { cellX = i; cellY = j; previousCellScore = adjacentCellsScore(i, j); } } } return new Point(cellX, cellY); } /* Format of adjacent cells : * * 0 1 2 * 3 . 4 * 5 6 7 */ private int adjacentCellsScore(int x, int y) { int[] scores = new int[8]; int previousX = (x - 1 < 0 ? size - 1 : x - 1); int nextX = (x + 1 > size - 1 ? 0 : x + 1); int previousY = (y - 1 < 0 ? size - 1 : y - 1); int nextY = (y + 1 > size - 1 ? 0 : y + 1); scores[0] = calcScore(previousX, nextY); scores[1] = calcScore(x, nextY); scores[2] = calcScore(nextX, nextY); scores[3] = calcScore(previousX, y); scores[4] = calcScore(nextX, y); scores[5] = calcScore(previousX, previousY); scores[6] = calcScore(x, previousY); scores[7] = calcScore(nextX, previousY); return IntStream.of(scores).reduce(0, (a, b) -> a + b); } private int calcScore(int x, int y) { int activeScore = 2; int mineScore = 1; int inactiveScore = 0; int brokenScore = 3; if (grid[x][y] == ACTIVE) return activeScore; else if (grid[x][y] == MINE) return mineScore; else if (grid[x][y] == INACTIVE) return inactiveScore; else if (grid[x][y] == BROKEN) return brokenScore; else return 0; } private void update(String[] args, boolean destroyPhase) { for(int i = 2; i < args.length; i++) { String[] tokens = args[i].split(","); if(tokens.length > 1){ int x = Integer.parseInt(tokens[0]); int y = Integer.parseInt(tokens[1]); if (grid[x][y] == INACTIVE) { if (destroyPhase) { grid[x][y] = BROKEN; } else if (i == 2) { grid[x][y] = MINE; } else { grid[x][y] = ACTIVE; } } } } } } ``` [Answer] # Random Builder, Python 3 This is a stupid example bot that never destroys anything, and tries to activate a random vertex every turn. Note that it doesn't need to check whether the vertex is inactive; the controller takes care of that. ``` import random as r while True: msg = input().split() if msg[0] == "BEGIN": side_len = int(msg[3]) elif msg[0] == "DESTROY": print("NONE") elif msg[0] == "ACTIVATE": print("VERTEX %d,%d"%(r.randrange(side_len), r.randrange(side_len)), flush=True) elif msg[0] == "SCORE": break ``` Run with the command ``` python3 random_builder.py ``` You may need to replace `python3` by `python` depending on your Python installation. To do this, just edit the `bots.txt` file. I updated the controller, and there's no need to mess with file paths anymore. [Answer] # Explorer, Python 3 Activation strategy: Creates a heatmap based on the state of every node (active/inactive/broken) and chooses the node which would have the biggest expected heatmap-value per person if it would choose that one. Destruction strategy: Never destroys anything as that doesn't help the bot much. ``` import sys class bd: def __init__(s, l): s.l=l s.b=[] s.v=[] s.m=[] s.bm=[] s.utd=False #up_to_date s.bmc=1 for i in range(s.l): s.b+=[[]] s.v+=[[]] s.m+=[[]] s.bm+=[[]] for k in range(s.l): s.b[i]+=[0] s.v[i]+=[0] s.m[i]+=[0] s.bm[i]+=[s.bmc] def update(s): s.utd=True vu=[] vd=[] for i in range(s.l): vu+=[[]] vd+=[[]] for k in range(s.l): vu[i]+=[1] vd[i]+=[1] #spread up for i in range(s.l): vu[i][0]*=s.bm[i][0] for k in range(1,s.l): for i in range(s.l): sumv=vu[(i-1)%s.l][k-1]+vu[(i)%s.l][k-1]+vu[(i+1)%s.l][k-1] vu[i][k]*=sumv*s.bm[i][k]/3 #spread down t=s.l-1 for i in range(s.l): vd[i][t]*=s.bm[i][t] for k in range(s.l-2,-1,-1): for i in range(s.l): sumv=vd[(i-1)%s.l][k+1]+vd[(i)%s.l][k+1]+vd[(i+1)%s.l][k+1] vd[i][k]*=sumv*s.bm[i][k]/3 #mult for i in range(s.l): for k in range(s.l): if s.b[i][k]==-1 or s.m[i][k]==1: s.v[i][k]=float(-1) else: s.v[i][k]=vu[i][k]*vd[i][k]/(s.b[i][k]+1) def add_act(s,al): s.utd=False for ind, ap in enumerate(al): i,k=ap s.b[i][k]+=1 s.bm[i][k]=2*s.bmc #doesn't work alone WHY??? if ind==0: s.m[i][k]=1 def add_ina(s,il): s.utd=False for ind, ip in enumerate(il): i,k=ip s.b[i][k]=-1 s.bm[i][k]=0 def get_newact(s): s.update() vm=-28 pm=None for i in range(s.l): for k in range(s.l): if s.v[i][k]>vm: vm=s.v[i][k] pm=(i,k) #doesn't work alone WHY??? s.m[pm[0]][pm[1]]=1 return pm b=None while True: inp=input() msg = inp.split() if msg[0] == "BEGIN": b = bd(int(msg[3])) elif msg[0] == "DESTROY": print("NONE") elif msg[0] == "BROKEN": pl=[] for m in msg[2:]: if m!='N': pl+=[tuple(map(int,m.split(',')))] b.add_ina(pl) elif msg[0] == "ACTIVATE": at=b.get_newact() print("VERTEX %d,%d"%(at[0], at[1])) elif msg[0] == "OWNED": pl=[] for m in msg[2:]: if m!='N': pl+=[tuple(map(int,m.split(',')))] b.add_act(pl) elif msg[0] == "SCORE": break sys.stdout.flush() ``` [Answer] # Annoyance, Bash ``` #!/bin/bash declare -A avail broken= owned= while read c p case "$c" in ACTIVATE|BROKEN) v=broken;; *) v=owned esac case "$c" in BEGIN) read b t n <<<"$p" list=$( eval "echo {0..$((n-1))},{0..$((n-1))}\$'\\n'" | shuf ) for i in $list; do avail[$i]=1 done;; DESTROY|ACTIVATE) for t in $( for i in ${!v}; do [ "$i" != N ] && if [ "$c" = ACTIVATE ]; then echo $(((${i%,*}+2)%n)),${i#*,} echo $(((${i%,*}-2+n)%n)),${i#*,} else echo ${i%,*},$(((${i#*,}+1)%n)) echo ${i%,*},$(((${i#*,}-1+n)%n)) fi done | shuf ) $list; do [ "${avail[$t]}" ] && echo VERTEX $t && break done || echo NONE;; BROKEN|OWNED) read x m $v <<<"$p"; for i in $m ${!v}; do unset avail[$i] done;; SCORE)! : esac do :;done ``` Tried to make the result looks more interesting. Run with `bash annoyance.sh`. [Answer] # Middle Man I saw that some bots built from the top, and some from the bottom. This is the first (I think) to start in the middle and work up and down. (it is not tested with the controller, so if it dose not work, let me know.) ``` class Node def self.set_size s @@grid = Array.new(s,Array.new(s,0)) end def initialize x,y @x=x @y=y end def offset dx,dy return Node.new @x+dx,@y+dy end def state return -1 if @x<0 || @y<0 || @x>=@@grid.length || @y>=@@grid.length @@grid[@x][@y] end def state= n return -1 if @x<0 || @y<0 || @x>=@@grid.length || @y>=@@grid.length @@grid[@x][@y]=n end def active? state > 0 end def open? state == 0 end attr_reader :x,:y def to_s "VERTEX #{@x},#{@y}" end def scan_down ans = nil [0,-1,1].each do|offset| n = Node.new @x+offset,@y-1 ans = (ans||n) if n.open? ans = (n.scan_down||ans) if n.active? end return ans end def scan_up ans = nil [0,-1,1].each do|offset| n = Node.new @x+offset,@y+1 ans = (ans||n) if n.open? ans = (n.scan_up||ans) if n.active? end return ans end end input = gets.split input.shift BotCount = input.shift.to_i Turns = input.shift.to_i GridSize = input.shift.to_i Node.set_size GridSize midRow = GridSize/2 toDestroy = (0...GridSize).map{|i|Node.new i,midRow} toDestroy.reject!{|n| n.x==midRow} chain = [] Turns.times do gets; toDestroy.each{|x| if x.active? toDestroy.push x.offset 0,1 toDestroy.push x.offset 1,1 toDestroy.push x.offset -1,1 end } toDestroy.reject!{|x|!x.open?} puts toDestroy.sample input = gets.split input.shift;input.shift input.each{|str| a,b = str.split ',' (Node.new a.to_i,b.to_i).state=1 } gets; if chain.length == 0 n = Node.new midRow,midRow until n.open? n = Node.new n.x+1,midRow end puts chain[0]=n elsif rand>0.5 n=nil loop do h=chain[0] n = h.scan_down break if !n chain.shift end h.unshift n puts n else loop do h=chain[-1] n = h.scan_up h.pop if !n brake if n end chain.push n puts n end input = gets.split input.shift;input.shift input.each{|str| a,b = str.split ',' (Node.new a,b).state=-1 } end gets exit ``` ]
[Question] [ Determine whether a given sequence could be a winning sequence for the game [shut the box](https://en.wikipedia.org/wiki/Shut_the_box). ## Background There are a few variants to this game, so I'll clarify the rules here. Play begins with 12 tiles (1 through 12) face up. Each turn the player rolls two six sided dice, and must then flip over one or more tile(s) which sum to the given roll. The game ends when you roll a number that cannot be summed to with tiles that remain face up. Your score then is the sum of the values of the remaining face up tiles. If one manages to flip over all tiles (obtaining a score of 0), this is referred to as "shutting the box". An example of a winning game may go as follows: ``` roll | sum | face up tiles remaining 4, 3 7 [1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12] 1, 4 5 [1, 2, 3, 4, 6, 8, 9, 10, 11, 12] 6, 6 12 [1, 2, 3, 4, 6, 8, 9, 10, 11] 2, 2 4 [1, 2, 3, 6, 8, 9, 10, 11] 5, 1 6 [6, 8, 9, 10, 11] 3, 6 9 [6, 8, 10, 11] 5, 3 8 [6, 10, 11] 6, 5 11 [6, 10] 4, 2 6 [10] 5, 5 10 [] ``` ## The challenge For this challenge you will take a sequence of roll sums (ie. `[7,5,12,4,6,9,8,11,6,10]`) as input, and output a truthy value which will denote whether or not this sequence of rolls could be used to "shut the box" exactly (no extra rolls either). Standard i/o rules apply, input can be taken in any reasonable form for a sequence, and output can be anything as long as truthy and falsy are distinct and consistent. You may assume that the input will consist only of integers 2-12. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. ## Test cases #### Truthy: ``` [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12] [3, 4, 5, 6, 7, 8, 9, 12, 12, 12] [12, 12, 12, 12, 12, 12, 6] [12, 12, 12, 12, 12, 11, 7] [7, 7, 7, 7, 8, 9, 10, 11, 12] [12, 4, 5, 7, 8, 9, 10, 11, 12] [2, 5, 7, 7, 7, 8, 9, 10, 11, 12] ``` #### Falsy: ``` [] [2] [12, 5, 6] [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] [3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12] [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8] [3, 3, 4, 5, 6, 8, 9, 12, 12, 12, 4] [2, 2, 5, 6, 6, 7, 8, 9, 10, 11, 12] [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12, 2, 2, 2] [8, 8, 8, 10, 10, 10, 12, 12] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` vṄΠ'fs12ɾ⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ24bmEzqAnZnM0yb7igbwiLCIiLCJbMiwgMywgNV0iXQ==) Outputs an empty list for falsy, a non-empty list for truthy. Link is for a much smaller version as this is \$O\left(\prod\_{i=0}{n\_i}^2\right)\$, that is, takes time proportional to the square of the product of the inputs. -1 by stealing some ideas from [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/253383/100664). ``` vṄ # Take the integer partitions of each number Π # Take the cartesian product of this ' # Filter all possible partitions by... fs # Flattened and sorted ⁼ # Is the result equal to... 12ɾ # range(1, 12)? ``` [Answer] # Python3, 230 bytes: ``` def C(d,n,c=[]): if(K:=sum(c))==n:yield{*c};return for j in d: if K+j<=n:yield from C(d-{j},n,c+[j]) def f(d): q=[({*range(1,13)},d)] while q: s,d=q.pop(0) if not s:return 1 if d: for r in C(s,d[0]):q+=[(s-r,d[1:])] ``` [Try it online!](https://tio.run/##jZHBcoIwEIbvPMXeTHTpEKlCaXPy6CMwHDqGVBgNEHA6DuOz00SmrSLazmQP2Xz7/3@S8thsC@WHpe46kUpYEYEKNzxOaORAJsk64vVhTzaUcq6iY5buRDvdnF512hy0ckAWGnLIFAjDmwFYz/K3bxKkLvZW023zk9WdxXlCHWskibAOFY9JO9Xv6iMlDJlPTyho4sDnNtulUFnNGgWvnsqiJB7tLVTRQB31CYD1vbP9OY22aVbEjMWeuUU1Mxa1q82WRQlNulJnqiGSxHMEH@EZYYGwRAgQQoQXBOaZmttKKHV@8HF2Psr@tq9r@TfFjPoVFZztgmFANmraJ3xITtzJ1Pcu5q5EbiUXw9gP343debd/45fXvV3hUPoyyfBLzJHBuy8) Outputs `1` for Truthy and `None` for Falsy. [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 62 bytes ``` (!12) []!0=1 (0:a)!n=a!n (a++b:c)!n|b>=n&&n>0=(a++b-n:c)!(n-1) ``` [Try it online!](https://tio.run/##HchBCoQwDEDRfU/RbqTFFBpRxxHiRcRFLAgiBnFwIXj3jrr7/8Vj30@/8RJ/KU1kDRZO9YMJhMqGlp0RYiPKcp6Pbbz3GjuSLJMu0IteHrbi0aWVZ9GkJ91/oAIsoIQavtAA4h0YhvQH "Curry (PAKCS) – Try It Online") Returns `1` for truthy, and nothing otherwise. It might return the same `1` multiple times for truthy result. [Answer] # JavaScript, ~~61~~ 57 bytes ``` f=(s,k=12)=>s.some((v,i)=>k?f(t=[...s],k-1,t[i]-=k):v)^!k ``` [Try it online!](https://tio.run/##PY3LCsIwEEX3fsW4SyAN9oGpSvRDQoRSE6mpjXRCfz/GSgP3Xs5hFvPqlg77efiEYvIPE6OVBJmTZUXlFTn6tyFkYUMyd7MkSMU5R81cUbKgBl1IR88Lve9dtH4GMpoAwWDoOzTgLaidEkKztO26p982Bwa1yNRmWq/VkcG/2cRmokmUsnKCOkXvNIXeT@hHw0f/JNt/BjYzpZf4BQ "JavaScript (Node.js) – Try It Online") Takes an `Array`. `k` counts down from 12 to 1. Each number is tried at each position in the array; each time, [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) is used to make a copy of the array, in which `k` is subtracted from that position and the function is recursively called. When `k` hits 0, the function passed to `some` instead returns each value in the array, and then `some` returns `true` if any of the values are nonzero and `false` otherwise. `^!k` inverts the result for `k`=0, to be 1 if all the values are zero. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Åœ.«âʒ˜ê12LQ ``` Outputs `[]` as falsey result; and a nested integer list as truthy result. Port of [*emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/253133/52210), so make sure to upvote him/her as well! [(Don't) try it online](https://tio.run/##ASUA2v9vc2FiaWX//8OFxZMuwqvDosqSy5zDqjRMUf//WzIsIDMsIDVd) (try it with a smaller example, which won't time out). **Explanation:** ``` Åœ # Map each integer in the (implicit) input-list to: all positive integer # lists that sum to that value .« # (Right-)reduce this list of lists by: â # Taking the cartesian power between two lists ʒ # Then filter this list of nested lists by: ˜ # Flatten the nested list ê # Sorted-uniquify the list Q # And check if it's now equal to 12L # a list in the range [1,12] # (after which the filtered result is output implicitly) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) (+cureutils+bc), 145 160 *fail* bytes ``` f(){ test `echo 0 $@|sed -e s/\ /+/g|bc` = 78||return 1 y=12 echo $@|fmt -w1|sort -rn|while read x&&test $y -ge 6 do [ $x -lt $y ]&&return 1 : $(( y-- )) done } ``` [Try it online!](https://tio.run/##jZDdboJAEIWv3ac42hWhDYGlKrYNqQ/Ru9pEgUVILBiWRon47HYFUSvadmcuJrPfmT93JsLdXdtwo9hwZUzILlC1Dcm4yDDlXpjABB0XgvvQOYQxgfFgzAvXm8KBPSqKlGdfaQxGcodZpFRIPvjMoK9YIZJUBmlcrMJowZHymY@1opTlaQ59zjEkfkLeQdfQF2XyQ1GORZ9BVRW5rkPTJBdzst2RN6lWNWwIXy@5lzmU4QUijIKMBOjQcYfME5l9JV6Spnsg56LaiFYKtB1QyUBRUDNxQpZpFGcBel0fex8IdMUk7h1VpYQeBLLRfYdsSTkN5DNRPQuP6GOAIWyM8ARmglnSG@AFZt3A6o@TD/9kGOwGYx@snondaLYf6oI6YuwU1ds2MrLE4GxE9stZfozAzs7yL9C@YqMr5eq@51dGv1qqZbasct/GZXbf "Bash Try It Online") Based on my observation above: > > Two necessary conditions that are sufficient to eliminate the Falsy examples: the sum of the sequence must be 78. For every n>=6 there must be at least 13-n entries in the sequence >= n. I don't know if we are just missing another Falsy sequence, or if this is enough. > > > And on my fondness for answers in bash, I decided to give it a try. Input is function parameters. The function exits with either 0=truthy or 1=falsy. The test harness prints expected, actual, if it matched, and the input. It works for all the current test cases. Previously I wrote > > I'm not quite sure why. > > > Well, the problem was the lack of a stopping condition. Adding test case `[2, 5, 7, 7, 7, 8, 9, 10, 11, 12]` revealed this, and added 15 bytes to my solution. And I haven't tried serious golfing yet. ## Second Edit: A couple more test cases: ``` [ 2, 5, 2, 5, 7, 7, 8, 9, 10, 11, 12] [ 2, 2, 2, 12, 12, 12, 12, 12, 12] ``` Since no possible Truthy sequence can have two 2s, or three 3s, and probably some other combinations, my answer current fails. And I'm not sure how it can be fixed... or even if. ## Third Edit: I generated some complete lists. There are 636 distinct valid sorted sequences. There are 220295 distinct sorted sequences totaling to 78. If we discard the sequences before "12 11 10 9 8 7 6 5 4 3 2", which would not be able to remove all the numbers, and discard any sequence of more than 11, we are left with 6638 sequences. My original 145 byte answer got 315 false negatives, and 124 false positives. My (first) 160 byte answer got no false negatives and 3075 false positives. My current 160 byte answer (`test $x -ge 6` changed to `test $y -ge 6`) gives no false negatives and 1600 false positives. (I had been hoping for some simple special cases.) [Answer] # [C (GCC)](https://gcc.gnu.org), ~~123~~ 117 bytes *-6 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` f(r,x,t,s,b,R)int*r;{for(R=0,t=8192;t--;R|=!x||s==*r&(t&x)==t&&f(r+1,x&~t))for(s=0,b=13;b--;)s+=t&1<<b?b:0;return R;} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=tZRLasMwEIY33dinmBpqpGQElvNyKovewdumhDqtSyBxgiyDwXEv0k02uUBv056mSkzANKFQ4oBmIaT_-2dGj4_dbPo2m223u1wnLPjKE6KwQI0ZxhjReao7SpTJSpFIeqhlwMe-0IyJaCNvi80mk7KjXKLdgkqpXdfIuxwL911TuldlRhVL3hOx0dCsa_bwMIwf4ntPqFedqxQiUdXm3zefxg-Wz_OU0NK2rf2sAAmEQxgC71FgwIVZKA9LarVYTLN8mT0-ydJH6CH0EQYIQ4QRQoAwRuCeCb8OrxK2Za2VESfEuXuBSeogmJSPIISCUgHVWYfzeL8tfJPUjOFVwPxQw2Xg0YEx-t1s3lY36m5fCLetda4z4jDGHGpEZ90uy7WVYgctnPSfb6CVY6nx13RoXqrTEbRQQLNFp4-4_6_LVdn113X8P38A) Note that it is exponentially slow; if you want it to run in a reasonable amount of time, add `if(R)return R;` after the `x&~t);` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~124~~ ~~108~~ 84 bytes ``` Max[Length/@Fold[Select[Join@@@Tuples@{##},0!=##&@@#&]&,IntegerPartitions/@#]]===12& ``` [Try it online!](https://tio.run/##Xcq7CoMwFIDhvU@REsh0QE3vQ@BMhZYWhHYTh6BRAxqLnkJBfPZUeoFS@L/tbzRVptFkM@0L5c/6kZyMK6kKcN/WeXIxtckoObbWIeL1fqtNjwPnI4RzxblA5CIVcHBkStPFuiNLtnV9gDxNlVKRFD7urCMscJDAVsA237bAdsCicBJN5Dj7PRfAlq9//T/Lt0@jfwI "Wolfram Language (Mathematica) – Try It Online") Thanks to @att!! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` ⊞υ⊕…¹²FA≔∧υΣEυEΦEX²LκΦκ&μX²π⁼ιΣμ⁻κμυ∧υ¬Συ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU_NbsIwDL7vKSx2cSQjUbQfECcmgYQ0pmo7Vj2EEtqINu2SeDzMLhw2bQ_EhbchAbaT_fn7sf35W1TSFq2s9_tv9pv-6HhI2VXIBAtTWNUo49UaX6UpFSZDIcTkZtNawIXp2KMQMHVOlwanZh1Nb9zgUnaxjWWua6_seZK2u9ANCZ6VKX2FWyEIrvyW4En7nXYqxjQE_-IuiGbvLGuH-pLeiGhcasMu-iIMmMNdqdXG_x3y0nqMco785MutCnf98Cfr9T_qXn68zbJHgnuCJCy6I3ggGBOMAk7OIBnk-cVyAg) Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for flipped, nothing if not. Explanation: ``` ⊞υ⊕…¹² ``` Start with a list of the numbers `1` to `12`. ``` FA ``` Loop through the input roll sums. ``` ≔∧υΣEυEΦEX²LκΦκ&μX²π⁼ιΣμ⁻κμυ ``` For each position found so far, find all the subsets of unflipped tiles that sum to the current sum, remove them from the position, and save all of the resulting positions for the next iteration. Note that `Sum` doesn't know what to do with an empty list (which happens when the previous move was impossible) so there's a short-circuit for that case. ``` ∧υ¬Συ ``` Check that we were able to flip over all of the tiles. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~13~~ ~~11~~ 13 bytes *Edit: +2 bytes to fix bug that failed to realise that incomplete 'shut the box' sequences can't themselves 'shut the box'.* ``` ¬€ṁö→½Ṗ∫Pḣ12∫ ``` [Try it online (using only 6 tiles to avoid timing out)](https://tio.run/##yygtzv6f@6ip8f@hNY@a1jzc2Xh426O2SYf2Ptw57VHH6oCHOxabAen///9HRxvqGOkY65jomOqYxepEG@uY6xgaAhmGBnAREDQ0AjIh8rGxAA "Husk – Try It Online") ``` € # first index (or 0 if not found) of ∫ # cumulative sum of the input # in ṁö # list conctructed by mapping over P # all permutations of ḣ12 # 1..12 Ṗ # and taking all ordered sublists of ∫ # the cumulative sum of each permutation # BUT: we need to include the last element # to avoid matching incomplete seqeunces, so ½ # split it in half (longer half comes first) ← # and take the second half, containing all the # sublists that contain the last element; ¬ # and finally return the logical NOT of this ``` [Answer] # [Haskell](https://www.haskell.org), 129 bytes ``` p[]=[[]] p(x:y)=[x:s|s<-p y]++p y t#[]=null t t#(r:q)=length t>0&&any(#q)[filter(`notElem`s)t|s<-p[1..12],sum s==r,all(`elem`t)s] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZPBToNAEIYTj_sUk9YYCNumoG2xEW8-gcd1k24TKo0LpewQS-LF5_DSi_FJfAh9GhcoulJFyQ6QmW9nhn-Hp5dIqLtQyt3uOcflwH97TBkPGOOcpNZ2VtgB287Ug7oYpFBwx9F3gn2NJLmUgPrdymYbO5BhcosR4OXo5EQkhdXf2Gy5khhm1jxZ45UM47mysUrE3OHQ9ThVeQwqCDIqpLTmYYmgrXjdyPvRK2Y5RgUEwAjoi3kUTimcURhTmFCYUvApnFNwR9q80jityZ8xr419eb7bpBNwdc4GmFb5p-1m3HaVupsOyGuAX3JxQpZCKkONz51mnbHRfKdc7qFc_yHN7z1cvpHQLN3WX4eMJr0G6y799-lXqcrVbPErxt8zI5MtBRVazFikYO0Hsm9DPXJkcRip1CckFqtEB9McrzGDY1DR-h4EOA70bpJe-aw8i8ZD6mlufq8P) [Answer] # [Scala](https://www.scala-lang.org/), 382 bytes It can be golfed more. Golfde version, [try it online!](https://tio.run/##jVJNb5wwEL3zK0Y52ZWxlk2TTUFG6qGHSqRStcdoVTlgumyM@bBpu1rx27c2NA0lJCliEJ558@bNA51yyc9FWVetAe0ONK2kFKkpKkXLzvB7KejXTnTC86r7gy3ALS8UiF9GqEzDx7qG09kcawFbthXm7rMyO284Jywp9J9EJnJIA5SFW6JCmyFpmLAvhcThgNnu2OkHl/AADFKquzIqcvTAmMKujFJqKsuNIyG1AFeKFbbd4zmzVQejueTmltfowGI3yz8QRQ5hmGIc9YOC3ApIsJs/jmvYsNkdQluSYLxDKABTQbDG40A/znD0c19IgRqqKvWprM0RD61Ik0xj1tBMNI4DYSdZ00KPoFaYrlUQuGymZ82tKK2HhfrOwNYMt5tYwY6R7gXPMM2rVvB0j1oWN1SocQLSvt@Sv73YrdV7q6g/AzhW03Zmf/xmhDba@jg454G9hrc1gUsC7wlcEbgmsCFwQ@ADgWBlY@0Ckyf0MnS9BH3K/hvXb4ICyz0FbYZZm7m4YGniqG4JaHEunCM5l/pFQ6aMz@ivZvpfdS9Ydu9/0dO1n983M@KpjPlnsaVxffuY/g2P/xOcwACLoW4LZaRCOTIYQ2/Rj5kL/wLeweXK0Uzce4ugP/8G) ``` type S=Set[Int] type L=List[Int] def c1(d:S,n:Int,c:L=Nil):List[S]={val k = c.sum;if(k==n)List(c.toSet);else if(k>n)Nil;else d.toList.flatMap(j=>c1(d-j,n,j::c));} def f(d:L):Int={val q=Queue[((S,L))]((1 to 12).toSet->d);while(q.nonEmpty){val (s,ds)=q.dequeue();if(s.isEmpty)return 1;if(ds.nonEmpty){val remaining= ds.tail;c1(s,ds.head).foreach(r=>q.enqueue((s--r,remaining)));}} 0;} ``` Ungolfed version ``` import scala.collection.mutable.Queue object Main extends App { def combinations(d: Set[Int], n: Int, c: List[Int] = Nil): List[Set[Int]] = { val k = c.sum if (k == n) List(c.toSet) else if (k > n) Nil else d.toList.flatMap(j => combinations(d - j, n, j :: c)) } def f(d: List[Int]): Int = { val q = Queue[((Set[Int], List[Int]))]((1 to 12).toSet -> d) while (q.nonEmpty) { val (s, ds) = q.dequeue() if (s.isEmpty) return 1 if (ds.nonEmpty) { val remaining = ds.tail combinations(s, ds.head).foreach(r => q.enqueue((s -- r, remaining))) } } 0 } val truthy_tests = List( List(2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12), List(3, 4, 5, 6, 7, 8, 9, 12, 12, 12), List(12, 12, 12, 12, 12, 12, 6), List(12, 12, 12, 12, 12, 11, 7), List(7, 7, 7, 7, 8, 9, 10, 11, 12), List(12, 4, 5, 7, 8, 9, 10, 11, 12) ) val falsy_tests = List( List(), List(2), List(12, 5, 6), List(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), List(3, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12), List(7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8), List(3, 3, 4, 5, 6, 8, 9, 12, 12, 12, 4) ) truthy_tests.foreach { t => println(f(t)) } println("-" * 30) falsy_tests.foreach { t => println(f(t)) } } ``` ]
[Question] [ Your task is to take an ASCII art image and output it rotated clockwise by 45 degrees and scaled by a factor of \$\sqrt 2\$. The scaling comes from using a lattice pattern which introduces space between the characters. To explain it visually, a \$3 \times 3\$ block would be processed like so: ``` 123 456 789 ``` becomes ``` 1 4 2 7 5 3 8 6 9 ``` Characters will not be transformed, so boxes will look strange after rotation: ``` +-+ | | +-+ ``` becomes ``` + | - + + - | + ``` To explain the process more explicitly, the output consists of a diamond lattice pattern where the top row corresponds to the top-left character of the input, the next row corresponds with the right and below neighbors, next row is those neighbors, and so forth until all of the characters have been placed on the lattice. ## Examples ``` FISHKISSFISHKIS SFISHKISSFISHKISSFISH F ISHK ISSFISHKISSFISHKISS FI SHKISS FISHKISSFISHKISSFISS FIS HKISSFISHKISSFISHKISSFISHKISSFISH KISS FISHKISSFISHKISSFISHKISSFISHKISS FISHK SSFISHKISSFISHKISSFISHKISSFISHKISSF ISHKISSFISHKISSFISHKISSFISHKISSF ISHKI SSFISHKISSFISHKISSFISHKISSFISHKIS SFIS HKISSFISHKISSFISHKISSFISHKISS FIS HKISSFISHKISSFISHKISSFISHK IS SFISHKISSFISHKISSFISH K ISSFISHKISSFISHK ``` [Source](https://www.asciiart.eu/animals/fish) Becomes ``` H K S I H I F S K S S I S I H S S I S F S K F F S H I S I H I H K S S F K S K S I H H I I H I S S K I K S H S K S F S I F S I H K S I S I F S I S S K I F S F S I S S F S I S I S I H S F H I F S S S S F S K H I K S I S F F H I H I K S I H S F I I K S K S I H S K H I I S S I H I S S K S I K S S H H S K S F S I F S I H S K K S I S I F S I S S K F I I F S F S I S S F S I I S S I S I H S F H I F S S S S S F S K H I K S I H F F H I H I K S I H S K I I K S K S I H S K H I S S I H I S S K S I S H H S K S F S I F S S K K S I S I F S I S F I I F S F S I S S I S S I S I H S F S S S S S F S K H I H F F H I H I K S K I I K S K S I H S S I H I S S H H S K S F S K S I S I S F S H F K F F F K I I I I I I S S S S S H S S H S K F K F F I I I S I S S K ``` --- ``` _,,ddF"""Ybb,,_ ,d@#@#@#@g, `"Yb, ,d#@#V``V@#@#b "b, d@#@#I I@#@8 "b d@#@#@#A..A@#@#P `b 8#@#@#@#@#@#@8" 8 8@#@#@#@#@#@J 8 8#@#@#@#@#P 8 Y@#@#@#@#P ,db, ,P Y@#@#@#@) @DWB aP "Y#@#@#b `69' aP" "Y@#@#g,, _,dP" `""YBBgggddP""' ``` [Source](https://www.asciiart.eu/religion/yin-and-yang) Becomes ``` d d , 8 @ @ d , 8 # # # # d _ 8 @ @ @ @ @ @ , Y # # # # # # # , @ @ @ @ @ I V @ d Y # # # # # ` # d @ @ @ @ @ A ` @ F " # # # # # . V # " Y @ @ @ @ @ . @ @ " # # # # # # A I # g " " @ @ @ @ @ @ @ @ @ , Y Y # # # # # # # # # b @ @ @ P P @ @ @ @ b b ` # # ) J 8 # 8 , " @ b " P ` , " # " _ Y g Y B , , b B , @ d , g ` D b " g 6 W , b g 9 B , d ' " d b P _ ` " , b " d 8 ' P a 8 " P a , 8 " P P ``` --- ``` ...,?77??!~~~~!???77?<~.... ..?7` `7!.. .,=` ..~7^` I ?1. ........ ..^ ?` ..?7!1 . ...??7 . .7` .,777.. .I. . .! .,7! .. .? .^ .l ?i. . .` .,^ b .! .= .?7???7~. .>r . .= .,.?4 , .^ 1 ` 4... J ^ , 5 ` ?<. .%.7; .` ., .; .=. .+^ ., .% MML F ., ?, P ,, J .MMN F 6 4. l d, , .MMM! .t .. ,, , JMa..` MMM` . .! .; r .M# .M# .% . .~ ., dMMMNJ..! .P7! .> . . ,, .WMMMMMm ?^.. ..,?! .. .. , Z7` `?^.. ,, ?THB3 ?77?! .Yr . .! ?, ?^C ?, .,^.` .% .^ 5. 7, .....?7 .^ ,` ?. `<. .= .`' 1 ....dn... ... ...,7..J=!7, ., ..= G.,7 ..,o.. .? J. F .J. .^ ,,,t ,^ ?^. .^ `?~. F r %J. $ 5r J ,r.1 .=. .% r .77=?4. ``, l ., 1 .. <. 4., .$.. .X.. .n.. ., J. r .` J. `' .?` .5 `` .% .% .' L.' t ,. ..1JL ., J .$.?` . 1. .=` ` .J7??7<.. .; JS.. ..^ L 7.: `> .. J. 4. + r `t r ~=..G. = $ ,. J 2 r t .; .,7! r t`7~.. j.. j 7~L...$=.?7r r ;?1. 8. .= j ..,^ .. r G . .,7, j, .>=. .J??, `T....... % .. ..^ <. ~. ,. .D .?` 1 L .7.........?Ti..l ,` L . .% .`! `j, .^ . .. .` .^ .?7!?7+. 1 .` . .`..`7. .^ ,` .i.; .7<..........~<<3?7!` 4. r ` G% J.` .! % JiJ .` .1. J ?1. .' 7<..% ``` [Source](https://www.asciiart.eu/video-games/sonic-the-hedgehog) Becomes ``` . . . . . . b . . . , . . J . . . % ? . + . 4 . . P ^ 7 ! ? . l ; ^ 7 . , . ` . d , ^ . . M r , , W M , = M M d ` . M N J , . ? M J . M ? T M . M a , . 7 H M . # . = . ` . ? B m ! . . . , . ^ . . , 3 ` , J % ` ^ . , . ? 7 , 7 ? 7 7 ? r . , ^ ? 7 7 . r J . . ? . ? 7 , ? . % . . ` . ? . ` . ? . ` $ . J = . < . 7 . . ? . 7 . . . . M , ~ l . ~ ! . . 7 . . ? . M M . I . 7 ~ . . = $ ^ . 7 M M L . . ^ ~ 1 5 ? d 7 M M N 1 ? ` ~ J 4 , n ? . M M ? 7 ~ L . , G . ! M M ! 5 i ! ! . , . . . # ` . . 1 ? . . 1 X 5 t , . . . ; . . I ? . ` ^ , . . . r 7 . , F > . . ? 7 ` ? . J . . . ? . F r . 7 < ` . S ` J , . . ! . . . t . ! 7 . ^ . . . ` ^ . . . P % . ` ? . J j , ` . ` , . ? . 7 ` < . ? . 7 > ` . , . 7 . . ! ` ~ . ? , r 8 ! + n o . , . . . . , 7 . = . . . . . ^ Y . . , 7 2 . . % . . , . r . . . . < ~ r . , 7 ` > , . . . ` L r . l . . . 6 4 . . 1 T . $ ^ . . . . = . . . . . . = . ` . . . r ` = . , . ? ? J ^ % . . . , 7 ~ L ~ . . t t ` J % , ^ = . . ! . ^ . ! < . . . . $ ` , J . ! ` . ~ , . < . L . G = = 7 . ` . . . 1 7 ' , . . , ? 7 . 3 . . . ~ t J $ ' , , ` ^ ! < ! . ? . . j ? . r . . . r r . J . . 7 . . . , 7 . J L J ? L . . ^ . Z . ? ! ` , r . ~ 7 ` . . . 1 7 . ? 1 ` . . % j ; = 4 ? ' ` ? ` = ? . . . . j . . ? < ` , . 7 ` . % 7 . . . 7 . ? 7 ` . . r . G < J ~ 5 ? . . , . . . . . . , 4 . ^ ; . t ? . . ? . . . 4 J . . . . 1 7 . = 1 . . r ^ ^ ` . . . ; . . , ` ! . . : , ` , J . . . . 4 F ? . i . ` , . . > . . F ^ ; J ! ` ? ? = ` , % . . . 7 T . ' . , 1 ! i . . , . ? . D . , 7 . ? , ? + ` l ^ , 1 . j C . . , i 1 . 7 G ; < % . . % . . J ` % ' ``` ## Rules and Notes * Input and output may be in any convenient format and character encoding as long as it supports all printable ASCII characters (U+0020 - U+007E, LF) * You may assume the input contains only printable ASCII characters (defined above) * You must support art up to \$100 \times 100\$ characters. * You may assume the input is right-padded, as to be a perfect rectangular grid of characters. + If it conveniences you, you may also assume the input is padded to be exactly \$100 \times 100\$ characters. * Use the ASCII space to align and space characters. * Characters may be overpadded (or even underpadded) in any direction as long as the result is properly aligned. Happy Golfing! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes ``` ↘A ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88LygzPaNER8Ezr6C0RENT0/r//@hoJQUEcPMM9vD2DA6G0ko6XAoKMPlgNEkwrYCsGaEcpAJMYWhCsgqmHC6BxYJghMMgyjFcgM1FIDbMdHxqIfaCWchexW8BmIYpJ6QOqgKinKC5sGCGmU7A4aghA@Lg1gAPd1JjFSVksMSpUmzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as either a single newline-delimited string literal or as an array of strings. Explanation: `A` reads the input and `↘` outputs it in the desired diagonal direction. Version which accepts a blank-line terminated list of lines from STDIN: ``` WS⊞υι↘υ ``` [Try it online!](https://tio.run/##lVFBDoMgELzvKzhCYj9Qr01T0ospLzCmERKCjYX6fASKaJRqymU2wzC7wza87puultYOXMgnwlS9jGa6F6rFhKDKvDk2BRKkhMqRGp8v3aAeouW6QIaU1qL5XCm73SljESHSbMUHRMt3QekvA2z0iwZOmbiMLZsngU3L3Ai@hqzVaoJQxUT7tgHhm2dPEhVw6Db9ofM8GDJl9/hbm/7zjx1N2TMbAnv6yBE "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` /⤢ *\⤢ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjBGJXUyOTIyJTIwJXVGRjBBJXVGRjNDJXUyOTIy,i=JTYwJTYwJTYwJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwRklTSEtJU1NGSVNIS0lTJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwU0ZJU0hLSVNTRklTSEtJU1NGSVNIJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwRiUwQSUyMCUyMCUyMCUyMElTSEslMjAlMjAlMjBJU1NGSVNIS0lTU0ZJU0hLSVNTJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwRkklMEElMjAlMjBTSEtJU1MlMjAlMjAlMjBGSVNIS0lTU0ZJU0hLSVNTRklTUyUyMCUyMCUyMCUyMCUyMCUyMCUyMEZJUyUwQUhLSVNTRklTSEtJU1NGSVNIS0lTU0ZJU0hLSVNTRklTSCUyMCUyMCUyMCUyMEtJU1MlMEElMjAlMjBGSVNIS0lTU0ZJU0hLSVNTRklTSEtJU1NGSVNIS0lTUyUyMCUyMEZJU0hLJTBBJTIwJTIwJTIwJTIwJTIwJTIwU1NGSVNIS0lTU0ZJU0hLSVNTRklTSEtJU1NGSVNIS0lTU0YlMEElMjAlMjBJU0hLSVNTRklTSEtJU1NGSVNIS0lTU0ZJU0hLSVNTRiUyMCUyMElTSEtJJTBBU1NGSVNIS0lTU0ZJU0hLSVNTRklTSEtJU1NGSVNIS0lTJTIwJTIwJTIwJTIwU0ZJUyUwQSUyMCUyMEhLSVNTRklTSEtJU1NGSVNIS0lTU0ZJU0hLSVNTJTIwJTIwJTIwJTIwJTIwJTIwJTIwRklTJTBBJTIwJTIwJTIwJTIwSEtJU1NGSVNIS0lTU0ZJU0hLSVNTRklTSEslMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBJUyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMFNGSVNIS0lTU0ZJU0hLSVNTRklTSCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMEslMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBJU1NGSVNIS0lTU0ZJU0hLJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIw,v=8) ``` / pad each line with one less space than the previous ⤢ transpose the object * place a space between every character \ pad each line with one more space than the previous ⤢ transpose the object back ``` Example: ``` 123 456 789 /: 123 456 789 ⤢: 7 48 159 26 3 *: 7 4 8 1 5 9 2 6 3 \: 7 4 8 1 5 9 2 6 3 ⤢: 1 4 2 7 5 3 8 6 9 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 104 bytes ``` lambda a:[" "*abs(l+~i)+" ".join(a[i-j][j]for j in range(i+1)if j<l>i-j)for i in range((l:=len(a))*2-1)] ``` [Try it online!](https://tio.run/##RU7NisIwED6bpxh6mjHbgnqRYn2Rbg@RtjohTUISWQTZV6@JHjzNfL98/pFuzh6OPqxz97satVxGBartK6i26hLRyH8mmVGjHVtUPdd66PUwuwAa2EJQ9johyx3xDPpkztlAReWviqbtzJTTRNt9vaNh5cW7kCA@ohBs/T1BV0AT08i2CZMakcQ18Jh5wzHhojyW5wfe9iZ6w8mwnSISkRDunj4tM5ZYZsqG4P7Kio/Yio0PbBNmllZZS/GEp8j3BQ "Python 3.8 (pre-release) – Try It Online") -5 bytes thanks to ovs (Python 3.8 things) [Answer] # [J](http://jsoftware.com/), ~~56~~ 45 bytes -11 bytes thanks to FrownyFrog! ``` -@}:@(i.@-@#,#\@{.)|."_1+/@${."1|.@,@,.&' '/. ``` [Try it online!](https://tio.run/##jZJND4IwDIbv/IoGjJU4C/gtCclORMJxVxMPxkW9ePAo/HaECQMFwV3arE/fdl1vmXwEBC744GYznvp8ciU@4xazDvxJdkLm0Zs6fPQk00uIM85ojIAOZbZhEqAMCIFB6oN8GMb5dLmDBPTmC2S4XK2R@bjZ7lBHoD5hJPZxJERp4fPk@aUnvkBlm2hYskVYmVZGo6Zi9W2HtKjby9lW4a5GCl/p9oHvisrTb@uXVlaxQ1BJ5OygYjVRpTvQbGMOhfeb1vPV7D//Fhfb0Uj9oVktRPYC "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` RāRú€Sζðýāú» ``` Port of [*@dzaima*'s Canvas answer](https://codegolf.stackexchange.com/a/182546/52210), so make sure to upvote him!! Input as a list of lines. [Try it online.](https://tio.run/##yy9OTMpM/f8/6Ehj0OFdj5rWBJ/bdnjD4b1HGg/vOrT7//9oJUMjYxMlHSVTM3MLIGVp4OgEpJxdXN2AlLuHpxeQ8vbx9QNS/gGBQUAqOCQ0DEiFR0RGKcUCAA) **Explanation:** ``` R # Reverse the (implicit) input-list ā # Push a list in the range [1, length of input-list], # without popping the list itself R # Reverse this list to [length, 1] ú # Pad the reversed input-list with that many leading spaces €S # Split each string on spaces ζ # Zip/transpose; swapping rows/columns, with space default as filler ðý # Join each inner character-list by spaces ā # Push a list in the range [1, length of this string-list], # without popping the list itself ú # Pad the list of strings with that many leading spaces » # Join the string-list by newlines (and output the result implicitly) ``` --- **Original ~~18~~ 17 bytes answer:** ``` €g2.ýIεNFR]JŽE5SΛ ``` Input as a list of lines. [Try it online.](https://tio.run/##yy9OTMpM/f//UdOadCO9w3s9z231cwuK9Tq619U0@Nzs//@jlQyNjE2UdJRMzcwtgJSlgaMTkHJ2cXUDUu4enl5AytvH1w9I@QcEBgGp4JDQMCAVHhEZpRQLAA) **Explanation:** ``` €g # Get the length of each line of the (implicit) input # (assumes they are all padded with spaces to make them of equal length) 2.ý # Intersperse this list with 2 (i.e. [3,3,3] becomes [3,2,3,2,3]) Iε # Map the strings in the input to: NF # Loop the 0-based index amount of times: R # And reverse the current string that many times ]J # After the loop and map: join the strings to a single string ŽE5S # Push compressed integer 3575, converted to a list of digits: [3,5,7,5] Λ # Use the canvas with these three options (which is output immediately by default) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽE5` is `3575`. [Some more info about the 05AB1E Canvas builtin can be found in this tip of mine.](https://codegolf.stackexchange.com/a/175520/52210) The Canvas builtin takes three parameters: * \$a\$ Length: The size(s) of the line(s). This can be a single integer, or a list of integers * \$b\$ String: The character(s) we want to display. This can be a single character, a string, a list of characters, or a list of strings (in the last three cases it will use all of them one-by-one including wrap-around) * \$c\$ Direction: The direction the character-lines should be drawn in. In general we have the digits `[0,7]` for the directions, for which we can use one or multiple. There are also some special options that require a certain character (`+`, `×`, `8`). In this challenge I use the following options: \$c\$: Let's start with the directions. For this I use \$[3,5,7,5]\$ which translates to \$[↘,↙,↖↙]\$. This means the string is printed in the following matter: ``` S ↘ ↙↖ ↘ ↘ ↖ ↘ ↙↖ ↘ ↖↙ ↘ ↖ ↘ . ↖ ↙ . ``` \$b\$: Since we print in this direction, this means the list of strings we input has to be modified slightly, which is what we do with the reverse on each 0-based odd-indexed string in the list. \$a\$: Finally, the lengths of how it is printed. This will be the length of each lines for the directions \$3\$ (\$↘\$) and \$7\$ (\$↖\$). The \$2\$ for the directions \$5\$ (\$↙\$), which means to print one character (with a character overlap of the trailing part of the previous line) in a south-west direction, and then we print the next line (with again one character overlap, hence the use of \$2\$ instead of \$1\$). This overlapping is better explained in the tip I linked earlier. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` JU’;ZJ$x@€⁶ðżµUŒDUṙLN‘ƊṚK€ ``` [Try it online!](https://tio.run/##y0rNyan8/98r9FHDTOsoL5UKh0dNax41bju84eieQ1tDj05yCX24c6aP36OGGce6Hu6c5Q2U/v9w95bD7ZH//ysggJtnsIe3Z3AwlFZABVxQOhhNGZhGVugGVgmSBFMY6pHsA6qEi2ExNhjhMC4MK7E5AcTmwmoUmgvALKiP8BsLprkg/sGnBKqCi6BpsDAEmknAkXC/g2jcauHhCVVJTBzB/I4lhtCiXQEA "Jelly – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` ỴṚµLḶṚŒḄ⁶ẋżŒDṙLK€ƲY ``` [Try it online!](https://tio.run/##hVbNbtNAEL7nKWyRKIeuRjJNWUTirgRVA8apKlEJysFaUDkkCkWycuESCcSNW2/wDJwQVC1wQirvkb5ImFnvr@2mKyX@m5md@Wbmm529mc/fr9er3z9Wl1///sxXF@d4c3W2uvh0/eF89evz1Z@rs73V5Zf86fXHb/@@H6/X636/H21aAMAE50LES1yxEPQwWuJr6NysI7jcYFPy@AZtYKn07Sx5Qc9PmpIisRZAL7orAhlZ@RInETTDwki0BfsRnNvAOOdoE55AJQKx7yaPjW6lDMJ91D7AnFyYAulKq1gYr1@rZ2sUUrTBCd6ltrhbGscgtaEyEAO7E4u8eBOLrvof@AnK8Fd4at7aCbQUaiOHbA/40AUmtQ/VZdiWv9TpbhVGlAxV18kkV9d9G0@YVGZdPiRHmXOfhCeTg0A7ulfbfuBCJvCjE@bHi/oTwhsWrgpqBphzQGllk1cADho0IP16CYpCvxm6wi7VpneCz@qR4DC5XbY0gTFxghseZNDcJYJDHlONRKE7LYHA8wmtt4huYeOlpo51@Oofo33pil9Woh4aqH30@OG2uUcOcJV7XFY7KzcFq/Vp8agTpri17QtEWaGiy3Snzg@cBc1LbW27jVnHRZNW5AhayhSL2ee9pNPCe3BySqyifwzZIEtj3w8vU0YpVdcxSiuQ3ylWUtyQ@W7s@3pAnzAOxhhWJiscdNV7TIfmhECvjHqo2FVolaZHTPpLSGxHUr0FesB5KgbKpJRMtwu2YqKKweI1CMKDri6XF@oKpyo0RnGVihpsgLJv1UBR8I7NRZVk@oN@lINKwcK1HAGdZLkPsGp/3FvoHDcTnICfWIlMBhkSKR9R3obNMZM9M3Wvkbb7cXjQNpXkriMKCnLQPru2FLZyoS7LFGDcLkcl0lXBRlmrwF1NHYuo6T9NHv1V4qRAG7PGKJ1RKMsca7abYpuUytzQG5hm3bfzpVLDgi0UMDXB0tyMa850aq7Z3pgFXbKbepKQCeIAeWSmdq/WQnawVumhcqzKn4WNDHsdW2JuBOZ6kJtDAYijKcCcRJl/Jsk1W1aTCaShMznDog@PERFoklSTgL7RmULwLUDegNpBh2QlzgwOITfBFHMJVJRmLUejbbQjq1YjkD1T417n5vNTRmTpz4RNwig@9ckB5EZhFPAaKrtFtjqIVWr922VVkyEEPTx1/gc "Jelly – Try It Online") [Answer] # JavaScript (ES6), 102 bytes ``` f= s=>(z=[...Array(100)],o=z.map(v=>z.map(_=>" ")),s.map((r,y)=>r.map((c,x)=>o[y+x][s.length+~y+x]=c)),o) ``` [Try it online!](https://tio.run/##jVJNb8IwDL3nV1Q9JaKL2Bkl0i5oaMccO7REXYGiLq6SCiiH/fUuTT9gpYP58uz45cWOvVcHZROTFeWThs@03rDaMo7PLKaUvhijKvw8n5N1BOxMv1SBD4y3zgfjYRASElkfYhNVhHHTBkl0cgHE1ey0ji3NU70td7PvJmSJuwOkXiCUgLaQpzSHLd5gGVxsuRKvbyshOgx@G@pQjGger4lLz2ySHm74V@855nA2ISsuhaGbJ6dKaHw0KTWqwHtdR/dlPaK2n3uUjoEeqvV/6DQfFDn03uDf3OE/O@Z/ZtT3PjGh0dgDSW2RZyUO33VI/KIZOLqdg2OfcPtInJ7PKcYV3UOmpSQtIkkW9Q8 "JavaScript (Babel Node) – Try It Online") Input and output as list of lists. **Explanation:** Creates a 100x100 grid of spaces. Then loops through the input, setting the appropriate entry in the grid. The index of the character to set is calculated as `x' = length of input - 1 + y + x` and `y' = y + x`. The returned result is a 100x100 list of lists, with the output in the upper left corner. [Answer] # [Ruby](https://www.ruby-lang.org/), 94 bytes ``` ->l{w=(2..y=l.size+b=l[z=0].size).map{' '*y};l.map{|r|b.times{|x|w[x+z][b+~z+x]=r[x]};z+=1};w} ``` [Try it online!](https://tio.run/##HclLCsIwFEDRrXT21Jhgq1YlPDcSMjDQQiGFkrTk79ajdHLhcM2mQh2x0rdODg8dYwE1s1MciEItIl7kriObP0uCBk6hcL0jm6zYOs2DTdlnJzyJUijyjcRLNMLLwiPBtnBX6rKtthmFgLa7whlu9/7fx/MFUvL9AaUU6g8 "Ruby – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 153 bytes ``` z=>{var m=new char[100,100];var s=z.Split('\n');var l=s[0].Length;for(int x=0;x<l-1;x++)for(int y=0;y<s.GetLength(0);y++)m[x+y,l+~y+x]=s[y][x];return m;} ``` [Try it online!](https://tio.run/##jZI9b8IwEIZn/CssFhIloDA7Rp1oUdkydEg9oMhApOBWtmltEP3r6cX5KIUUasm60/nR6zv7zdQ4U3k534ssVlrmYhNm25VMQzbDa1oe6Oz4sZJ4RwX/xO5kGkUhbEaquqKHSfJe5NobvYqR72oFVWnEJksuNnpL1m/Sy4XGhkbExMV4SkwQ@G3VQtXGavLIdc17kU8sALvUBDYsgi8bGAaClqWGEcn1Xgq8I6eSINQ0iiVX@0JjitfewxD/rPkieXpeJEkT8e@FmphcYC6eg3NHVocuXPFn9wHZ1Xpkk5/G0NWVfS1UOeqVuujAZc1Et2VdRPU8t5CGQHfV2jcEzTtNdrNX8W@2e8@G/M8ftbP3/NDFt@OhD9YB/@HalmCbiECIMZgaEvAeOqJBB9gasC1QmRMNgBi8yFxzrzZfakJsGSi3t5y6zGHLXHDv7Bidym8 "C# (Visual C# Interactive Compiler) – Try It Online") Asks for a string and returns a 2D char 100 x 100 array. I tried using LINQ/Collections, but I eventually give up. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 79 bytes ``` SparseArray[100+{#2+#,#2-#}&@@#&/@Range@100~Tuples~2->Flatten@#,{301,301}," "]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@4ILGoONWxqCixMtrQwEC7WtlIW1lH2UhXuVbNwUFZTd8hKDEvPdUBKFcXUlqQk1pcZ6Rr55aTWFKSmuegrFNtbGCoA8S1OkoKSrFq//8DAA "Wolfram Language (Mathematica) – Try It Online") The input should be padded as exactly 100x100. The output is an array of 301x301. The result of rotating sonic (with proper formatting): [![Sonic result](https://i.stack.imgur.com/DAH3X.png)](https://i.stack.imgur.com/DAH3X.png) ]
[Question] [ To increase data safety at our company, we are planning to start using Gray code numbers (where successive values differ by only one bit) instead of classical binary ones. Please help us to make a program that converts numbers to Gray code (single number to single number), but the program needs to be safe as well. This means that each successive byte of the program can differ at most by one bit. Here is a code from [Wikipedia](https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code) for conversion (ungolfed and "unsafe"): ``` uint BinaryToGray(uint num) { return num ^ (num >> 1); // The operator >> is shift right. The operator ^ is exclusive or. } ``` This code does following: Input number is bit shifted to the right by one bit and then there is performed exclusive or with original number. Example with input 123: Binary representation of 123 is 1111011b, after shift right the number is 0111101b. After performing exclusive or between those two numbers the result is 1000110b, which is 70 in decimal. Example inputs, outputs: ``` 0, 0 1, 1 123, 70 255, 128 11, 14 ``` Example of safe programs: ``` a bcbcbc !!! h() bcg ``` Example of unsafe programs: ``` abc OP ``` [Answer] # [Incident](https://esolangs.org/wiki/Incident), 100 bytes ``` @``aaqscbjnNFNLllnjnnfdlLDDdeEDLHJJBBbfd`bcCK[SCGGEGFFB@@HIIKCAIMM]UQAEMmikKJHXxzz{{kcCAackjzZ[[{sqq ``` [Try it online!](https://tio.run/##BcHrCsIgGADQV5uXTadzEBFEEnjbwEsfyPoR@vB2TgQfwwHfMSZjrK2Xdwn2Zd9KgQRwhrJRGo6ZblwIjN0ZjPNE6jthbGbLgqeJr6skaFXq/bihWX1iloI/f631nj1B1ufUXlr3q9Yx7B8 "Incident – Try It Online") I/O is done by character (actually byte) code, because Incident is a horrible low-level tarpit with no numeric I/O routines. The program can handle numbers greater than 255 by using multiple characters (enter the number you want in little-endian base 256). ## Explanation In Incident, the tokens are not fixed by the language but rather defined by the program – any substring of the program that appears exactly 3 times is a token, unless it's contained within another token or overlaps another token. Additionally, the actual bytes that make up a token don't matter – just how the copies of the tokens are arranged relative to the other tokens. In this program, I picked single-byte tokens to implement the program, choosing the bytes that represent them in order to get an approximate "only one bit changes from one byte to the next" property, and added extra bytes (that appear more or fewer than 3 times) as comments in order to make the property perfect. Thus, every occurrence of a byte in `]eimQSUxXZ` `fNs` `cCn` is a comment, because it appears 1, 2, or 4 times respectively. (I had to double one of the `n`s to "detokenise" `n`; other padding characters added to maintain the one-bit-at-a-time property naturally ended up being used 1, 2 or 4 times.) The actual choice of bytes to represent the tokens, and positions of the padding bytes, was mostly done via a computer search (and the algorithm wasn't optimal, so this is probably golfable, but I haven't found anything better so far). Removing the comments gives us the following 72-byte program, whose token arrangement was chosen by hand: ``` @``aaqbjFLlljdlLDDdEDLHJJBBbd`bK[GGEGFFB@@HIIKAIMMAEMkKJHzz{{kAakjz[[{qq ``` Incident programs are generally very hard to explain, so I'm going to attempt to explain this one by highlighting subsets of characters and explaining what they do. I think I've covered the whole program here, but in a program as unreadable as this one (and which was partially computer-generated, so I didn't entirely write it myself), it's quite possible that I've missed something. ### Starting the program, and the first two bits of input ``` @``aaqbjFLlljdlLDDdEDLHJJBBbd`bK[GGEGFFB@@HIIKAIMMAEMkKJHzz{{kAakjz[[{qq @ b HJJBBb b @@H k Hzz{{k k ``` Incident reads standard input a bit at a time (which is the only reason why writing this program is remotely viable in Incident – it's normally a horrible language for just about anything). If the three uses of a token are split as a lone token and a touching pair (e.g. `@` … `@@`), that represents a jump from the single token to the double token, so the program starts by jumping from the `@` at the start to `@@`. To do input (the usual way, at least), the program must run into the middle of the three occurrences of a token, without ever hitting the first or last use. `H` here therefore reads the first bit (the least significant bit of the input number), and jumps to the first or last `H` accordingly. In either case, we then cross over a couple of jump labels (`JJBB` or `zz{{`). For a *backwards* jump (which all of `JBz{` are), it's safe to do this; control just moves past the jump label, like you'd expect for a jump label. (This is not safe for a *forwards* jump – you're encountering the middle of three uses without ever hitting the first or last, which is interpreted as an attempt to read input rather than an attempt to move past a jump label.) This part of the program finishes by reading the second bit of input, using `b` or `k` based on whether the first bit read was a 0 or a 1 bit. Control flow is thus sent to one of four locations, based on the two most recent bits read. ### Output subroutines ``` @``aaqbjFLlljdlLDDdEDLHJJBBbd`bK[GGEGFFB@@HIIKAIMMAEMkKJHzz{{kAakjz[[{qq bj bK kK kj j lljdl j K IIKAI K d DDdED d A MMAEM A L L E L GGEG E ``` The outer uses (first and last) of any given token are basically subroutine calls, with the middle use being the entry and exit point from the subroutine (i.e. running the first or last token will jump to the middle, and then returning to the middle will return to just after the token you called it from). We want to output 0 if we read two 0s or two 1s. We want to output 1 if we read 01 or 10. Output in Incident is done by calling a subroutine using the token that's the centremost token in the entire program (which for this program is `E`; the `L` token is dead code, with none of its uses ever reached, and it exists only to push the centre of the program over an `E`); its left call point outputs a `0` bit as a side effect, and its right call point outputs a `1` bit as a side effect. So we have a `d` subroutine that outputs 0 bits, and an `A` subroutine that outputs 1 bits, both via calling `E`. Because subroutines have their entry and exit points in the same place, we wrap each of them in a backwards jump to allow control flow to return to the point from which they were called. Each Incident subroutine must be called from exactly 2 points in the program, but we have three locations that want to output `0` bits (and three locations that want to output `1` bits). The usual way to fix this is with helper/wrapper subroutines that contain nothing but a call to another subroutine, here `j` and `K`; `j` outputs `0` bits by calling `d`, and `K` outputs `1` bits by calling `A`. These wrapper subroutines use up one of the call points of the subroutine they're calling, but provide two (an increase of one call point), so this technique makes it possible to call `d` and `A` from three points each. In order to convert regular little-endian binary to Gray code, we basically need to output, for each bit, the XOR of that bit with the previous bit. The program has jumped to one of four locations based on whether the two bits we just read are `00`, `01`, `10`, or `11`; and each of these locations immediately calls an output subroutine to output `0`, `1`, `1`, or `0` respectively. ### Moving from one bit to the next ``` @``aaqbjFLlljdlLDDdEDLHJJBBbd`bK[GGEGFFB@@HIIKAIMMAEMkKJHzz{{kAakjz[[{qq jF BBb FFB K[ {{k [[{ JJ b KJ zz k jz ``` After we've produced our output, we need to move onto the next bit. The output of the binary-to-Gray conversion only ever depends on the most recent two bits, so we effectively just need to jump to the same location that the `H` which reads the first bit does – after producing output after a `0` bit, we need to jump to the `b` that handled input after a `0` bit is read, and after producing output after a `1` bit, we need to jump to the `k` that handled input after a `1` bit is read. This is almost very straightforward, just using jumps to return to the relevant part of the program. After reading `10` or `11`, we can do exactly that (using `J` and `z` respectively as the jump labels) – those are backward jumps, so control flow can safely pass over their jump labels. After reading `00` or `01`, though, we would need to jump forward in the program rather than backward jumps, and control flow can't pass over a forward jump label safely. So instead, we need to jump forwards to an arbitrary point in the code, and then backwards to the point we actually need, allowing the two control flows to merge safely. This is done with `F` then `B` after reading `00`, and `[` then `{` after reading `01`. This handles most of the program – the situation we're in after reading, say, `1110` is identical to the situation we're in after reading `10`, except that we've output two bits already (but there's no need to remember which two bits they were, because those never become relevant later). ### Ending the program ``` @``aaqbjFLlljdlLDDdEDLHJJBBbd`bK[GGEGFFB@@HIIKAIMMAEMkKJHzz{{kAakjz[[{qq `` bd` aa kAa q qq ``` Eventually, we reach the end of the input, causing an end-of-file condition. Incident handles end of file by not jumping at all – it just falls through from the input instruction to the next instruction. To convert binary to Gray codes, we need to handle this by outputting a copy of the most recently input bit (because the most significant bit of the input is output directly in addition to being XORed with the bit below), then quitting the program. If the most recently read bit was a `0` bit, so we're using `b` to read input, then we fall through to `d` (which outputs `0` bits), then use ``` to jump back to the start of the program. Likewise, if we read a `1` bit and thus used `k` to read input, we fall through to `A` to output a `1` bit and `a` to jump back to the start of the program. In either case, `q` jumps to the end of the program and exits. This code is a little inefficient – I was a little safer than I needed to be here. Normally in Incident, you have to jump backwards to reach the same point from two different places, because forward jump labels don't behave properly if encountered directly (they either try to read input or return from a subroutine, depending on whether they've been used before or not). You could save three bytes from this part of the code via using forward jumps to the end of the program, rather than needing a separate `q` – this would mean encountering a forward jump label, but because the corresponding jump would never have been used, it would try to read input, encounter the same end-of-file condition again, and fall through, so the "forbidden control merge" would actually work in this case. I'm not sure whether the program could be shortened like this, because a lot of it would have to be redone (e.g. the centre of the program would move so you'd need to place the output routine in a different place, and that means moving the padding elsewhere in the program). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ;3ss{Ƶ}]\\^ ``` [Try it online](https://tio.run/##yy9OTMpM/f/f2ri4uPrY1trYmJi4//8NjYwB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaWL0n9r4@Li6mNba2NjYuL@K@mF6fyPNtAx1DE0MtYxMjXVMTSMBQA). The core program without the [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") would have been 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage): ``` ;^ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fOu7/f0MjYwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf@u4/zr/ow10DHUMjYx1jExNdQwNYwE). **Explanation:** *Explanation of the core program:* ``` ; # Halve the (implicit) input ^ # Implicitly truncate it to an integer, and bitwise-XOR it with the # (implicit) input # (after which the result is output implicitly) ``` The idea is to add no-ops between them without changing the functionality. I started by [creating a generator to get all 05AB1E character-pairs that differ by a single bit](https://tio.run/##yy9OTMpM/X9035G2YCO9w22nJoGYldlJFoc2aD9qWnNoGZAITji8A0gd7o73rz207VHDvJg8q////wMA). Before the `^`, only `\` and `V` seemed reasonable candidates (`\` discards the top of the stack; and `V` pops the top of the stack and saves it in variable `Y`). From there it was kinda trial-and-error to see what characters I could use. Because the `;` and `^` differ by 4 bits, at least that many no-op bytes in between are necessary. Although I have the feeling the byte-count can still be improved perhaps, 9 no-op bytes to toggle 4 specific bits isn't too bad I guess. *Explanation of the new program:* ``` ; # Halve the (implicit) input-integer # No-ops: 3 # Push 3 s # Swap the two values on the stack s # Swap them back { # Sort the digit(s) of 3 Ƶ} # Push compressed integer 226 ] # Close all open if-statements and loops \ # Discard the top of the stack (the 226) \ # Discard the top again (the 3) ^ # Implicitly truncate the halved input to an integer, and bitwise-XOR # it with the (implicit) input # (after which the result is output implicitly) ``` ([See this 05AB1E tip (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ}` is `226`.) *The [bytes in 05AB1E's codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage) of `;3ss{Ƶ}]\\^` are:* ``` ; 00111011 v 3 00110011 v s 01110011 s 01110011 v { 01111011 v Ƶ 01111111 v } 01111101 v ] 01011101 v \ 01011100 \ 01011100 v ^ 01011110 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` HL\^ ``` A monadic Link that accepts an integer and yields a list of one integer. ...Or a full program that accepts an integer and prints the result. The code's bytes only change by one bit each time, as required: | Byte | Hex | Binary | | --- | --- | --- | | `H` | **48** | **01001000** | | `L` | **4C** | **01001100** | | `\` | **5C** | **01011100** | | `^` | **5E** | **01011110** | **[Try it online!](https://tio.run/##y0rNyan8/9/DJybu////hkbGAA "Jelly – Try It Online")** ### How? The shortest code that starts with `H` (halve) and ends with `^` (XOR the input) for which the code in between has no adverse effect while fulfilling the source-code restriction of only changing by at most one bit from byte to byte. ``` HL\^ - Link: integer, N H - halve N -> N/2 \ - cumulative reduce with: L - length -> [N/2] ^ - (floor to integer) XOR (N) -> [floor(N/2) XOR N] ``` --- ###### Note `:2` (integer divide by two) seems like a reasonable start as the bytes already only differ by one bit, but the next available bytes (`Ø"036:rḶ`) don't really help us advance. [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), ~~425~~ 421 bytes *-4 bytes thanks to [@Jiří](https://codegolf.stackexchange.com/users/101306/ji%c5%99%c3%ad)* ``` ,()9;{[YIMm-/?>?;+*:>?;+*(8<<=}]_^~>?;{[YIMm-/?>>?;+*(8<<=?;{[YIMm-/?>>?=-/?>?;+*(8<=}]_^~>>?;{[YIMm-/?>>>>?;+*(8<<=}]}|<<<<=}]_^~>>>?;{[YIMm-=<<<=?;+*:>>>?=}]}|>>>?;{[YIMm-=}]}|<<<<<<<=-/?;{[[Z^~>>>>>>?;{[Z^~>>>?=}]_OKk++;{[YIMm-=<<<=}]}|<<<=-=}]_^~>?=}]_^~>>>?;{[ZXx|<=}]_^~>?;{[[Z^~>?;{[Z^~>?=-=<=-=}]_^~>?;{[ZXx|<<<<<<=?;+*:>>>>>>?;{[YIMm-=}]]_^~>?=}]_OKk+;{[ZXx|<=?;{[ZXx|<<<=?;++*:>>>?=-=}]}|<<=}]_^~>>?=}]}|<<<=?/. ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuha3GJfqaGhaWldHR3r65urq29vZW2trWYFJDQsbG9va2Pi4OiAXoQAhhypqC9MNlINqQ9Vnh2xqbY2NDdx4JIW2NmCDQW4AmQlSiCIN0wlSBjQVKB4dBTYBqgrCAWmM9_fO1tZGMReq2VYX5i0U-6MiKmqQPQw2C2Ym0Hu2SBphyiEOgbkXzaUIO0BOgduApBmkE-ZVmN_gYQd3rr2-HiS2oJG2YGEmhAEA) Thanks to [this](https://codegolf.stackexchange.com/a/15291) answer for the XOR algorithm and to [this](https://codegolf.stackexchange.com/a/9184) answer for the division by 2. Expanded code: ``` , duplicate the input in two cells [->+>+<<] > divide n by two [ 0 - >>+ set marker 2 << 0 [->>->+<] dec marker inc n/2 >> 2 or 4 [->>>>+<<] <<<< ] >>> [-<<<+>>>] set temp cell to zero >>>[-] <<<<<<< xor -[[>>>>>>[>>>]++[-<<<]<<<-]>]>>>[<]>[[>[>-<-]>[<<<<<<+>>>>>>[-]]>]+[<[<<<++>>>-]<<]>>] <<<. ``` The code has been made safe with [this](https://ato.pxeger.com/run?1=ZVJLTsMwEJVY-hQjd2OraURhQRU1XCQKkpM41GqTGMf9QJWTsOkGjsIhOA1jux-g3iTz5vnNvPG8f-pXu-jaw-FjbevJ7PvmqzZdA1ob1VpQje6MPUWEVLIG1ftIFCvJdjwhgMdIuzYtrGTLjNSGlQuDOc4hTeGekAZS2DtM8QQy__PEpvM5UqDuDOxAtWBE-yzZAwf1t8aZmnuuunCnd7NrNoeBjI4ds4YT0rviAyndl84fx5MoznJKiBMrnVjZBxOV7zIBSgfigZe1XEsEszL38XahVjKg4YY7AgkeinWn2S0_JzQmqkzkZ8AVLFzBBtGLgDtoooC2sy5b_U35zrIiRzUNYxBXyd93T1b-n9Cg0Fq2FSt4sNejL2d5mcAmmyZhvMsINr6LWFnZ9MwPeBm0cSznyfYoQrbKLqBDUUZFXFAOooc6dGBRuY6NFBVDpouy3eWtrVPdBdU8PIWIwnDelGY2Aus6Om5XqFjTvRj2Pc4OpzHQCNBLSiknIe1cjY5Uy0lY5-NWn7b7Bw) program. **I invite anyone who's better at golfing in Brainkfuck than me to use it to make shorter solutions!** ]
[Question] [ This is a King of the Hill challenge in a round robin. It's a battle to find the best gunman of the west! To be able to compete in this contest you need to make two functions. The first one sets the attributes of your gunman and the second is the main logic function for the gunman. # Attribute Function ``` function () { var bot = { name: "testBot", numbOfBullets: 7, reloadSpeed: 1, shotsPerTurn: 1, moveSpeed: 2 } return bot } ``` The attribute function includes 5 variables that you will need to set according to some rules (with the exception of `name` that can be any string). You must spend a total of exactly 15 points on your gunman -- gunmen that do not spend all 15 points are not eligible. Here is how the attributes work: * **`numbOfBullets`** - defines how many bullets your gun holds. The initial and minimum value of `numbOfBullets` is 1. Each additional bullet costs 1 point with the maximum being 16 bullets with 15 points spent. * **`reloadSpeed`** - defines how many turns your gunman needs to reload his gun after he ran out of bullets. The base and maximum value is 4 with the minimum being 1. Decreasing this attribute by 1 costs 2 points. * **`shotsPerTurn`** - defines how many times your gunman can shoot in one turn. The base and minimum value is 1. Each increase by 1 costs 3 points so you can have a maximum of 6 shots per round with 15 points spent. Raising this attribute above `numbOfBullets` is counter productive since you can't shoot more bullets then your gun can hold. * **`moveSpeed`** - defines how many spaces your gunman can run in one turn. The base and minimum value is 1. Each increase by 1 costs 3 points with a maximum of 6 speed with 15 points spent. The gunman can run either left or right every turn up to a maximum of his move speed. He can also stand still which gives him a bonus (more on this later). The example function above has 6 points spend on bullets, 6 points spend on reload speed and 3 points spend on movement. # Main function ``` function main(bulletsLeft, yourShots, enemyShots, yourMovement, enemyMovement) { var shots = []; shots.push(Math.floor((Math.random() * 24) + 1)); var move = yourMovement[yourMovement.length - 1] + 2 var play = []; play.shots = shots; play.move = move; play.reload = false; return play; } ``` **Parameters:** * `bulletsLeft`, number of bullets left in your gun * `yourShots`, this is a array of arrays of all the past positions your gunman has fired at. Example for a gunman who can shoot 1 bullet per round: ``` [[12],[4],[22],...] ``` Example for a gunman who can shoot 3 bullets per round: ``` [[12,13,14],[11,15,16],[9,14],...] ``` * `enemyShots` - same as above but for your enemy * `yourMovement` - an array of all your past movement positions * `enemyMovement`, same as above but for your enemy **What you need to return:** You are required to return a variable which has 3 attributes: * `shots` - an array of numbers which determine at which space/s your gunman will shoot * `move` - a single number that determines to what space your gunman will try to move to * `reload` - a true/false value with which you can make your gunman reload # The Duel The contest follows a round robin 1 versus 1 system. Each gunman has 50 rounds against every other gunman. A round lasts until someone is hit by a bullet or until 66 turns have passed (a turn is when both players have shot). The gunman can earn 2 points by killing their opponent, 1 point if they both die in the same turn or 0 points if they reach the 66 turns limit. The shooting field is 24 spaces width (1-24 inclusive). To hit a player and win a round you need to shoot at the same space as he is currently standing on. Here is a step by step guide on how a duel works. This also covers all invalid commands and special rules: * At the start of each duel both players are put on space 12 and their revolvers are fully loaded * The main function is called and the gunman make their first move command and choose where they want to shoot * First the gunmen move to their new location. If any invalid input is made at the move command (positions lower then 1 or higher then 24 or they moved more spaces then they are allowed too) they stay at the same position. * Next reloading is checked, if you ran out of bullets the previous turn or you called reloading yourself your gunman goes into the reload cycle. He is reloading for as many turns as you set your `reloadSpeed` value. If you decided to stand still (returning the same space integer as you where standing on before or just returning a invalid value) you reload counter goes down for 2 turns instead of one. * Now comes checking your shooting values, every turn you can enter as many shooting location as you like they will always be cut off to the actual valid amount which is determined by: The number of shots per turn and the number of bullets in your revolver (whichever is lower). Your `shotsPerTurn` value is increased by 1 if you decide to stand still this turn, so you can make a extra shot if you decide to stand still. If you are in the reload cycle you have 0 shots. * Now comes the actual shooting, there are 2 ways this can go down. If both gunman have the same movespeed stat then they both shoot at the same time and can both kill each other at the same time. In the case that they have different movespeed stats the bot with the higher movespeed stat starts shooting first and if he kills his opponent he wins this round. If the gunman can shoot one or more bullets in one round then it follows the same rules as above except in more cycles as a example: Lets say that bot1 has 3 bullets and is faster and bot 2 has 2 bullets then it would go like this: ``` Bot1 shoots, Bot2 shoots cycle 1 Bot1 shoots, Bot2 shoots cycle 2 Bot1 shoots cycle 3 ``` This would look the same if they had the same movespeed only that if now Bot1 hit Bot2 in the same cycle Bot2 could also hit Bot1 and it would be a tie. # RULES First I am copying some rules from Calvin's Hobbies' entry that also apply here. **When declaring a new JavaScript variable, you must use the var keyword.** This is because a variable declared without var becomes global rather than local, so it would be easy to accidentally (or intentionally) mess with the controller or communicate freely with other players. It has to be clear that you aren't trying to cheat. When declaring functions it is best to use the var keyword as well, i.e. use `var f = function(...) {...}` instead of `function f(...) {...}.` I'm not entirely sure why, but sometimes it appears to make a difference. In your code you may not... * attempt to access or modify the controller or other player's code. * attempt to modify anything built into JavaScript. * make web queries. * do otherwise malicious things. My additional rules: * The users can create as many gunman as they want and change their functions for any period of time * I will remove any entry from the game that either takes a excessive amount of time or tries to cheat in any way that I see fit * The names of the attributes that your function need to return has to be the same as in the examples with the same structure! Your answer should be in this format, the first function being the attribute function and the second being the logic function. Notice that I used an exclamation mark because if you just make new lines between code blocks the parser wont see two different code blocks so you have to use any symbol(just use a exclamation mark) to seperate them: ``` var bot = { name: "testBot", numbOfBullets: 7, reloadSpeed: 1, shotsPerTurn: 1, moveSpeed: 2 } return bot ``` ``` var shots = [] var testBot_moveUp = true if(Math.random() * 2 > 1) testBot_moveUp = false shots.push(Math.floor((Math.random() * 24) + 1)) var move = 0 if (testBot_moveUp) move = yourMovement[yourMovement.length - 1] + 2 else move = yourMovement[yourMovement.length - 1] - 2 move = 12 var play = [] play.shots = shots play.move = move play.reload = false return play ``` And here is the controller: [GAME CONTROLLER](http://jsfiddle.net/sh4wr82r/30/). Just open the link and wait for the bots to load, then select which one you want in the fight (probably all) and press the start button. I also put in a testbot as my answer which will compete, it also serves as a example on how the structure of the answer should look like. As a note, if you make a small mistake and edit your answer stackexchanges algorithm might not pick it up right away and the site that the controller uses which is generated by stackexchange isnt updated(but will later or if you make bigger changes which i suggest doing, just add some text at the end). Here is the site: [codelink](https://api.stackexchange.com/2.2/questions/51698/answers?page=1&pagesize=100&order=asc&sort=creation&site=codegolf&filter=!JDuPcYJfXobC6I9Y-*EgYWAe3jP_HxmEee) [Answer] # Pandarus ``` var bot = { name:"Pandarus", numbOfBullets: 2, reloadSpeed: 3, shotsPerTurn: 1, moveSpeed: 5 } return bot ``` ``` var myPos; if(yourMovement.length > 0) { myPos = yourMovement[yourMovement.length - 1]; } else { myPos = 12; } var EnemyPos; if(enemyMovement.length>0) { EnemyPos = enemyMovement[enemyMovement.length - 1]; } else { EnemyPos = 12; } var play = { shots: [ ], reload: true, move: 12 }; if (bulletsLeft < 1) { //Reload play.reload = true; play.shots = [ ]; } else { //FIRE!!! play.reload = false; var enemyMoveSum = 0; for (var i = 0; i < enemyMovement.length; i++) { var MoveSinceLast; if (i == 0) { MoveSinceLast = enemyMovement[i] - 12; } else { MoveSinceLast =enemyMovement[i] - enemyMovement[i-1]; } enemyMoveSum += Math.abs(MoveSinceLast); } var enemyAvgMove; if (enemyMovement.length > 0) { enemyAvgMove = Math.round(enemyMoveSum / enemyMovement.length); } else { enemyAvgMove = 0; } var LeftShot = EnemyPos - enemyAvgMove; var RightShot = EnemyPos + enemyAvgMove; if (RightShot > 24 ||( (LeftShot>0) && (Math.random()*2 < 1))) { play.shots.push( LeftShot ); } else { play.shots.push( RightShot ); } } var MyMove = myPos; do { var move = Math.floor(Math.random() * 10) - 5; if(move == 0) { move = 5; } MyMove = myPos + move; } while (MyMove<1 || MyMove > 23) play.move = MyMove; return play; ``` Pandarus relies on his speed to get out the way of the bullets, and uses the enemies previous movements to guess where they are going to go. [Answer] ## A Simple Man Not perfect at anything, but quite good at everything through the power of less is more. ``` return { name: "A Simple Man", numbOfBullets: 7, /* 9 points */ shotsPerTurn: 2, /* 3 points */ reloadSpeed: 4, /* 0 points */ moveSpeed: 3 /* 3 points */ } ``` ``` var lastPos = yourMovement[ yourMovement.length - 1 ], lastEnemyPos = enemyMovement[ enemyMovement.length - 1 ], lastEnemyMove = enemyMovement.length > 1 ? ( function () { var i = 0, currentMove, minMove = Infinity; while ( i < enemyMovement.length ) { currentMove = Math.abs( enemyMovement[ enemyMovement.length - 1 ] - enemyMovement[ enemyMovement.length - 2 ] ); if ( currentMove < minMove ) { minMove = currentMove; } return minMove; } } )() : 1, needsToReload = bulletsLeft === 0; return { shots: [ yourMovement.length === 1 ? 12 : lastEnemyPos + lastEnemyMove, lastEnemyPos - lastEnemyMove ], move: needsToReload ? lastPos : lastPos + Math.floor( Math.random() * 3 + 1 ) * ( ( Math.random() > 0.5 ) ? -1 : 1 ), reload: needsToReload }; ``` [Answer] ``` var bot = { name: "testBot", numbOfBullets: 7, reloadSpeed: 1, shotsPerTurn: 1, moveSpeed: 2 } return bot ``` ``` var shots = [] var testBot_moveUp = true if(Math.random() * 3 > 1) testBot_moveUp = false shots.push(Math.floor((Math.random() * 24) + 1)) var move = 0 if (testBot_moveUp) move = yourMovement[yourMovement.length - 1] + 2 else move = yourMovement[yourMovement.length - 1] - 2 var play = [] play.shots = shots play.move = move play.reload = false return play ``` Test bot, this added as a control test. If anybody loses to this you should be ashamed :). Fixed bot behaviour, copy pasted the wrong test bot(it always stayed on field 12) [Answer] ``` var bot = { name: "Sniper", numbOfBullets: 4, /* 3 points */ reloadSpeed: 4, /* 0 points */ shotsPerTurn: 1, /* 0 points */ moveSpeed: 5 /* 12 points */ }; return bot; ``` ``` var play = {}; var my_speed = 5; var gatherStatistics = function(moves) { var enemyMoves = []; for (var m = 1; m < moves.length; ++m) { var diff = moves[m]-moves[m-1]; var found = false; for (var i = 0; i < enemyMoves.length; ++i) { if (enemyMoves[i][0] === diff) { ++enemyMoves[i][1]; found = true; break; } } if (!found) enemyMoves.push([diff,1]); } return enemyMoves; }; var calcOptimalTarget = function(moves, histogram) { var enemy_pos = moves[moves.length-1]; var optimalDiffs = []; var optimalScore = 0; for (var i = 0; i < histogram.length; ++i) { var diff = histogram[i][0]; var score = histogram[i][1]; if (score > optimalScore) { optimalScore = score; optimalDiffs = [diff]; } else if (score === optimalScore) { optimalDiffs.push(diff); } } var chosenDiff = optimalDiffs[Math.floor(Math.random() * optimalDiffs.length)]; return enemy_pos + chosenDiff; }; /* Never reload */ play.reloading = false; /* Run around like a mad man */ var my_pos = yourMovement[yourMovement.length-1]; var rand_sign = 2*Math.floor(2*Math.random())-1; /* Never run into walls */ if (my_pos <= my_speed+1) { rand_sign = 1; } else if (my_pos >= 24 - my_speed - 1) { rand_sign = -1; } if (yourMovement.length === 1) { /* Leap out of the way on first move */ play.move = yourMovement[yourMovement.length-1] + rand_sign*my_speed; } else { play.move = yourMovement[yourMovement.length-1] + rand_sign*((my_speed-1)*Math.floor(2*Math.random()) + 1); } /* Shoot all bullets by the end of the game */ var random_shot = (Math.random() > 0.15) ? true : false; if (enemyMovement[enemyMovement.length-1] === enemyMovement[enemyMovement.length-2]) { /* Enemy is standing still; now is our time to STRIKE! */ play.shots = [ enemyMovement[enemyMovement.length-1] ]; } else if (enemyMovement.length >= 2 && random_shot) { /* We take a random shot; best guess by enemies movement */ var histogram = gatherStatistics(enemyMovement); play.shots = [ calcOptimalTarget(enemyMovement, histogram) ]; } else { /* No default shooting */ play.shots = []; } return play; ``` [Answer] ## The Weaver More concerned with staying alive than killing, he weaves back and forth, increasing his distance every time. Picks a random spot within the enemies proven range to shoot at. ``` var bot = { name: "TheWeaver", numbOfBullets: 4, // 3 points reloadSpeed: 4, // 0 points shotsPerTurn: 1, // 0 points moveSpeed: 5 // 12 points } return bot; ``` ``` var play = {}; var moveSpeed = 2; //Guess the enemies speed var enSpeed = 1; var prev = 12; for(var move in enemyMovement){ if(Math.abs(move - prev) > enSpeed){ enSpeed = Math.abs(move - prev); } prev = move; } //Randomly shoot in his range var enemyPos = 12; if(enemyMovement.length > 0){ enemyPos = enemyMovement[enemyMovement.length - 1]; } var shots = []; //Shoot somewhere in his range var distance = Math.random()*enSpeed; var direction = 1; if(Math.random() < 0.5){ direction = -1;} if(enemyPos + enSpeed > 24){ direction = -1;} if(enemyPos - enSpeed <= 0){ direction = 1;} shots.push(enemyPos + distance*direction); var move = 12; //Start with a dash if(yourMovement.length == 0){ move = 12 + moveSpeed - 1; } //Quick switch else if(yourMovement.length == 1){ move = 11 } //Wave baby, weave else{ var lastPos = yourMovement[yourMovement.length - 1]; var lastMove = yourMovement[yourMovement.length - 1] - yourMovement[yourMovement.length - 2]; var distance = Math.abs(lastMove + 1); if(distance > moveSpeed) { distance = 0;} var direction = lastMove/Math.abs(lastMove)*(-1); move = lastPos + distance*direction; } //Correct move if(move > 24){ move = 24; } if(move < 1){ move = 1; } play.move = move; play.reload = false; play.shots = shots; return play; ``` [Answer] # Alexander Hamilton If he doesn't win in the first round, will probably die ``` var bot = { name: "Hamilton", numbOfBullets: 7, // 6 pts reloadSpeed: 4, // 0 pts shotsPerTurn: 4, // 9 pts moveSpeed: 1 // 0pts } return bot ``` ! ``` var shots = [] var move = yourMovement[yourMovement.length - 1] + 1 var play = [] play.shots = [12,11,10,13,14,9,15,8,16,7,17,6,18] play.move = move play.reload = false return play ``` [Answer] # Aaron Burr ``` var bot = { name: "Burr", numbOfBullets: 7, // 6 pts reloadSpeed: 4, // 0 pts shotsPerTurn: 3, // 6 pts moveSpeed: 2 // 3pts } return bot ``` ! ``` var shots = [] var move = yourMovement[yourMovement.length - 1] // Dodging dance switch (yourMovement.length % 4) { case 1: move += 2 break; case 2: move -= 1 break; case 3: move -= 2 break; case 0: move += 1 break; } var play = [] var elast = enemyMovement[enemyMovement.length - 1] play.shots = [elast + 1, elast -1, elast] play.move = move play.reload = false return play ``` [Answer] ``` var bot = { name: "Winger", numbOfBullets: 7, // 6 points reloadSpeed: 4, // 0 points shotsPerTurn: 3, // 6 points moveSpeed: 2 // 3 points } return bot; ``` ``` var play = {}; var moveSpeed = 2; //Guess the enemies speed var enSpeed = 5; // Assume they are fast on the first turn var prev = 12; for(var move in enemyMovement){ if(Math.abs(move - prev) > enSpeed){ enSpeed = Math.abs(move - prev); } prev = move; } var move = 12; if(Math.random() < 0.5){ moveSpeed = 1; } //Move against the enemies shots if(yourMovement.length == 0 || enemyShots.length == 0){ move = 12 + moveSpeed; } else if(enemyShots.length == 1){ if(enemyShots[0] <= 12){ move = yourMovement[yourMovement.length - 1] - moveSpeed; } else{ move = yourMovement[yourMovement.length - 1] + moveSpeed; } } else{ var dir = enemyShots[enemyShots.length - 1][0] - yourMovement[yourMovement.length - 1]; if(dir > 0){ move = yourMovement[yourMovement.length - 1] + moveSpeed; } else{ move = yourMovement[yourMovement.length - 1] - moveSpeed; } } //reload? var reload = false; if(bulletsLeft < 3){ reload=true; } var enemyPos = 12; if(enemyMovement.length > 0){ enemyPos = enemyMovement[enemyMovement.length - 1]; } var shots = []; if(reload == false){ //Shoot a spread around the opponent shots.push(enemyPos); if(enemyPos + enSpeed <= 24){ shots.push(enemyPos + enSpeed);} if(enemyPos - enSpeed > 0){ shots.push(enemyPos - enSpeed);} } //Correct move if(move > 24){ move = 24; } if(move < 1){ move = 1; } if(reload && (yourMovement[yourMovement.length - 1] - yourMovement[yourMovement.length - 2]) != 0){ move = yourMovement[yourMovement.length - 1]; } play.move = move; play.reload = reload; play.shots = shots; return play; ``` Winger fires a spread that bounds the enemies range. He also kind of runs towards the enemies shots. Just gonna leave this here to push the reset. [Answer] # SMG His gun is his cover. Unfortunately, it seems to block his view. He is also good at taking advantage of standing still to reload faster and get extra shots. ``` var bot = { name: "SMG", numbOfBullets: 12, //11pt reloadSpeed: 2, //4pt shotsPerTurn: 1, //0pt moveSpeed: 1 //0pt } return bot ``` ``` var shots = []; shots.push(Math.floor((Math.random() * 24) + 1)); shots.push(Math.floor((Math.random() * 24) + 1)); var play = []; if (bulletsLeft < 1) { play.reload = true; play.shots = []; } play.shots = shots; play.move = Math.floor((Math.random() * 24) + 1); play.reload = false; return play; ``` [Answer] ``` var bot = { name: "Random Evader", numbOfBullets: 7, reloadSpeed: 4, shotsPerTurn: 1, moveSpeed: 4 } return bot ``` ``` var getSpeed=function(Moves){ var m = 0; for(var i=1;i<Moves.length;i++){ var d = Math.abs(Moves[i]-Moves[i-1]); m = m>d?m:d; } return m; } var validMove=function(moves,speed){ speed = speed||getSpeed(moves); var m; do{ m=moves[moves.length-1]+Math.floor(Math.random()*(speed*2+1)-speed); }while(m>25 && m<0); return m; } var shots = []; shots.push(validMove(enemyMovement)); var move = validMove(yourMovement,4); return { shots:shots, move:move, reload:false }; ``` [Answer] ``` var bot = { name: "Gun and run", numbOfBullets: 4, /* 3 points */ reloadSpeed: 4, /* 0 points */ shotsPerTurn: 3, /* 6 points */ moveSpeed: 3 /* 6 points */ }; return bot; ``` ``` var play = {}; play.reload = false; if (yourShots.length === 1) { /* Opening move */ if (Math.random() < 0.5) { play.shots = [13,14,15,16]; } else { play.shots = [8,9,10,11]; } play.move = 12; } else { /* YOLO */ play.shots = []; switch (yourMovement[yourMovement.length - 1]) { case 12: play.move = 15; break; case 15: play.move = 18; break; case 18: play.move = 15; break; } } return play; ``` [Answer] # Diephobus ``` var bot = { name: 'Deiphobus', numbOfBullets: 5, reloadSpeed: 3, shotsPerTurn: 4, moveSpeed: 1 }; return bot ``` ``` var getSorted = function(list) { var modifiedList = [0,0,0,0,0,0,0,0,0,0,0,0,0]; modifiedList[0] = list[6]; modifiedList[1] = list[7]; modifiedList[2] = list[5]; modifiedList[3] = list[8]; modifiedList[4] = list[4]; modifiedList[5] = list[9]; modifiedList[6] = list[3]; modifiedList[7] = list[10]; modifiedList[8] = list[2]; modifiedList[9] = list[11]; modifiedList[10] = list[1]; modifiedList[11] = list[12]; modifiedList[12] = list[0]; var messedUpOrder = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]; for(var order = 0; order < 13; order++) { var currBest = -2; for (var i = 0; i < 13; i++) { if ((messedUpOrder.indexOf(i) < 0) && (modifiedList[i] > modifiedList[currBest] || currBest<0)) { currBest = i; } } messedUpOrder[order] = currBest; } var toRet = [0,0,0,0,0,0,0,0,0,0,0,0,0]; toRet[6] = messedUpOrder[0]; toRet[7] = messedUpOrder[1]; toRet[5] = messedUpOrder[2]; toRet[8] = messedUpOrder[3]; toRet[4] = messedUpOrder[4]; toRet[9] = messedUpOrder[5]; toRet[3] = messedUpOrder[6]; toRet[10] = messedUpOrder[7]; toRet[2] = messedUpOrder[8]; toRet[11] = messedUpOrder[9]; toRet[1] = messedUpOrder[10]; toRet[12] = messedUpOrder[11]; toRet[0] = messedUpOrder[12]; return toRet; }; var myPos; if(yourMovement.length>0) { myPos = yourMovement[yourMovement.length - 1]; } else{ myPos = 12; } var EnemyPos; var play = { shots: [ ], reload: true, move: 12 }; if(enemyMovement.length>0) { EnemyPos = enemyMovement[enemyMovement.length - 1]; } else { EnemyPos = 12; } if(bulletsLeft<4) { play.reload = true; } else { play.reload = false; var enemyChanges = [0,0,0,0,0,0,0,0,0,0,0,0,0]; for(var i = 0; i<enemyMovement.length; i++) { var enemyChange; if(i == 0) { enemyChange = enemyMovement[i] - 12; } else { enemyChange = enemyMovement[i] - enemyMovement[i-1]; } enemyChanges[enemyChange+6] = enemyChanges[enemyChange+6]+1; } var orderedEnemyChanges = getSorted(enemyChanges); var CurrentShot = 0; play.shots = [12,12,12,12]; for(var i = 0; i<orderedEnemyChanges.length && CurrentShot<4; i++) { var pos = orderedEnemyChanges[i] + EnemyPos - 6; if(pos<24 && pos>0) { play.shots[CurrentShot] = pos; CurrentShot ++; } } } if(myPos == 1) { play.move = 2; } else if (myPos == 23) { play.move = 22; } else { play.move = myPos + (Math.floor((Math.random() * 3)) %3) - 1; } return play; ``` Diephobus beleives in mercilessly firing bullets everywhere he thinks his enemy might be, but he's a bit slow. [Answer] # ASCIIGunInTheWest Fires 2 shots a turn, and guesses where the enemy can go based on how fast he moves. Forgive me if there's any errors, I haven't coded much in JavaScript. ``` var bot = { name: "ASCIIGunInTheWest", numbOfBullets: 4, reloadSpeed: 1, shotsPerTurn: 2, moveSpeed: 2 } return bot ``` ! ``` function main(bulletsLeft, yourShots, enemyShots, yourMovement, enemyMovement) { var randnum = function (min, max) { return Math.floor( Math.random() * (max - min + 1) ) + min } var getDiff = function (num1, num2) { return Math.abs( (num1 > num2) ? num1-num2 : num2-num1 ) } var shots = [] var enemyMaxMovement = 0 for (index = 0 index < enemyMovement.length ++index) { var moveDiff = getDiff(enemyMovement[index], enemyMovement[index - 1]) if (index != 0 && moveDiff > enemyMaxMovement) { enemyMaxMovement = moveDiff } } var enemyCurrentPosition = enemyMovement[enemyMovement.length - 1] var enemyMinMoveRange = enemyCurrentPosition - enemyMaxMovement var enemyMaxMoveRange = enemyCurrentPosition + enemyMaxMovement shots.push( randnum(enemyMinMoveRange, enemyMaxMoveRange) ) shots.push( randnum(enemyMinMoveRange, enemyMaxMoveRange) ) var move = yourMovement[yourMovement.length - 1] + randnum(-2, 2) var play = [] play.shots = shots play.move = move play.reload = false return play } ``` EDIT: Apparently my bot (just mine) can't be used in the JSFiddle. Does anyone know why this is? I'm using all my points for my gunman, so I don't think I've been disqualified. ]
[Question] [ The challenge - given a numeric list L and an integer N as inputs, write a function that: 1. finds the bucket sizes for L such that it is split into N *whole* buckets of equal or near-equal size, and 2. returns for each element in L the minimum of that element's bucket. Example - ``` L=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] N=5 ``` Compute the bucket sizes with the following: \$\left \lfloor \frac{| L |}{N} \right \rfloor + 1\$ elements go into \$|L| \bmod N\$ buckets, and \$\left \lfloor \frac{| L |}{N} \right \rfloor \$ go into the rest, where |L| is the length of L. For the above, we get `floor(12/5)+1` into `12 mod 5` buckets, and `floor(12/5)` in the rest: ``` [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9], [10, 11]] ``` Finally, we output a list where each element is the minimum of its bucket: ``` [0, 0, 0, 3, 3, 3, 6, 6, 8, 8, 10, 10] ``` Some test cases: ``` In -> Out [1, 2, 3, 4], 1 -> [1, 1, 1, 1] [1, 2, 3, 4], 2 -> [1, 1, 3, 3] [0, 2, 4, 6, 8], 3 -> [0, 0, 4, 4, 8] [9, 3, 0, 1, 5, 7, 4, 6, 8, 10, 12, 11, 2, 13], 5 -> [0, 0, 0, 1, 1, 1, 4, 4, 4, 10, 10, 10, 2, 2] [3, 0, -2, 0, -1], 2 -> [-2, -2, -2, -1, -1] ``` This is a code golf challenge. Shortest answer in bytes wins. Standard loopholes apply and such. Edit: 1. you may assume L is not empty 2. you do not have to handle the case where N>|L| 3. your answer should return a flat list [Sandbox](https://codegolf.meta.stackexchange.com/a/18458/88520) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous infix lambda. Takes \$N\$ as left argument and \$L\$ as right argument. ``` {p/⌊/¨(-p)↑¨↑∘⍵¨+\p←1+@(⍳⍺|l)⌊⍺⍴⍺÷⍨l←≢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7pA/1FPl/6hFRq6BZqP2iYeWgEkHnXMeNS79dAK7ZiCR20TDLUdNB71bn7Uu6smRxOoGMh41LsFSB7e/qh3RQ5QxaPORUD1tf/TQOzevkd9Uz39H3U1H1pvDDKsb2pwkDOQDPHwDP5vqpCmYKCjYKijYKSjYKyjYKKjYKqjYKajYK6jYKGjYAmUAkkbchkCFSJUcRmhco0hxhiBDQDqtuACGWwJloUYbwo2EioLNdUIZDJYl6ExWMOj3jUA "APL (Dyalog Unicode) – Try It Online") `{`…`}` \$⍺:=N,\ ⍵:=L\$  `l←≢⍵` \$l:=|L|\$  `⍺÷⍨` \$l\over N\$  `⍺⍴` \$(\underbrace{\frac{l}N,\frac{l}N,\frac{l}N,\cdots,\frac{l}N}\_{N\text{ elements}})\$  `⌊` \$(\underbrace{\left\lfloor\frac{l}N\right\rfloor,\left\lfloor\frac{l}N\right\rfloor,\left\lfloor\frac{l}N\right\rfloor,\cdots,\left\lfloor\frac{l}N\right\rfloor}\_{N\text{ elements}})\$  `1+@(`…`)` increment **at** the following indices:   `⍺|l` \$|L|\bmod N\$   `⍳` \$(1,2,3,…,|L|\bmod N)\$  `p←` \$p:=(\underbrace{\overbrace{1+\left\lfloor\frac{l}N\right\rfloor,1+\left\lfloor\frac{l}N\right\rfloor,\cdots,1+\left\lfloor\frac{l}N\right\rfloor}^{|L|\bmod N\text{ elements}},\left\lfloor\frac{l}N\right\rfloor,\left\lfloor\frac{l}N\right\rfloor,\cdots,\left\lfloor\frac{l}N\right\rfloor}\_{|n|\bmod N\text{ elements}})\$  `+\` cumulative sum of that list  `↑∘⍵¨` for each element, take that many elements from \$L\$  `(-p)↑¨` for each list, take as many trailing elements as the corresponding number in \$p\$  `⌊/¨` minimum of each list  `p/` replicate each minimum by the the corresponding number in \$p\$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` œsṂṁ$€F ``` A dyadic Link accepting `L` on the left and `N` on the right which yields a list as specified. **[Try it online!](https://tio.run/##y0rNyan8///o5OKHO5se7mxUedS0xu3////RljoKxjoKBjoKhjoKpjoK5joKJjoKZjoKFkARkKgREAOlQJRx7H9TAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///o5OKHO5se7mxUedS0xu3/0T2Hl@sDWSpHJz3cOQPIAKIsENUw59A2XTuFRw1zsx417ju07dC2//@jo6MNdRSMdBSMdRRMYnUUDGO5dNCEjMBCBmAhEx0FMx0FC6CoMVjUEqwKKAfUYaqjYA5XARQBiQK1GEIMMzQGajIFa4Lo0DWCUIYQK2IBE "Jelly – Try It Online"). (Also `œsµṂṁ)F` is the same.) ### How? ``` œsṂṁ$€F - Link: list of order-able items, L; positive integer, N œs - split L into N chucks, longer ones to the left € - for each chunk: $ - last two links as a monad - i.e. f(chunk): Ṃ - minimum of chunk ṁ - mould like chunk F - flatten ``` [Answer] # JavaScript (ES6), ~~101~~ 87 bytes Takes input as `(array)(n)`. ``` a=>n=>a.map(w=_=>--w?m:m=Math.min(...a.slice(p,p+=w=L/n+(i++<L%n)|0)),L=a.length,i=p=0) ``` [Try it online!](https://tio.run/##lZDdToQwEEbvfYq5MWnDUP5XduPgC@ATGGIaZHdroJCFyI3vjrSIq27U2Hy9auZ80/MsX2RfnlQ3uLp9qqY9TZIyTZkUjezYSI@Uue541@waupfDUTRKMyGEFH2tyop12Dk0Uu5phynHuc2vNX/1OcecpKgrfRiOqKgjn09lq/u2rkTdHtiePfgIAUKIECHECAnCBuEGIUXYzk/mOSg4SziH9XgemLEl0ZqNTWpjx/zi6lvXuWgmBp@IPx/TFdgVTX4nhv8kmr0viL4lxstnZmj0N/TsI7ZJL6BbW7aoTqzeeLVlVYXGsi0OonfZXyR/GIjXLIaXO4@FxfQG "JavaScript (Node.js) – Try It Online") ## How? ### Variables * \$L\$ is the length of the input array * \$i\$ is the ID of the current bucket * \$w\$ is the width of the current bucket * \$m\$ is the minimum value in the current bucket * \$p\$ is a pointer to the starting point of the next bucket ### Commented ``` a => n => // given the input array a[] and the integer n a.map(w = // initialize w to a non-numeric value _ => // for each value in a[]: --w ? // decrement w; if it's not equal to 0: m // append the current minimum : // else: m = // append the updated value of m Math.min( // which is the minimum value found in ...a.slice( // the slice of a[] p, // starting at p p += // and ending at the updated value of p (-1): w = // update w: L / n + // floor(L / n) is the base width (i++ < L % n) // add 1 if i is less than L mod n // (then increment i) | 0 // apply the floor() ) // end of slice() ), // end of Math.min() L = a.length, // initialize L i = p = 0 // start with i = p = 0 ) // end of map() ``` [Answer] # [J](http://jsoftware.com/), ~~52~~ ~~50~~ ~~47~~ ~~42~~ ~~39~~ ~~37~~ ~~35~~ ~~32~~ 27 bytes ``` ](]#(<.//.~I.))[:+/-@[]\]=] ``` [Try it online!](https://tio.run/##hU7LCsIwELz3KxY91KJNu0lb22BBEATBk9caPIhFvPgH/nqcTVsULzLJYXceOw8/U3FPraWYVpSTxU8V7U7HvXcLN19sVJap10ElSWeXWbrt3Nm1zifR7Xp/Ukk9DEyaDBWYKlpTTQ0xlhwNmjzABFRADQiPQ/ZPQPDzCKgZ6lH74SQXnP7l5GoB1MKacEdjRIHvXkN2ETC0YtHpqVwDq6hKFAvmINFoBw0bGrIuenosb6wjTuxyWUX@DQ "J – Try It Online") This solution doesn't use any of the arithmetic formulas. Instead it relies on geometric transformations. We'll use the example ``` 5 f 0 1 2 3 4 5 6 7 8 9 10 11 ``` to see how the transformations work: * `]=]` Does the input equal itself, elementwise? This converts the input to ones: ``` 1 1 1 1 1 1 1 1 1 1 1 1 ``` * `-@[]\` Split it into rows whose size is `5` (the left arg), filling the final partial row with zeros: ``` 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 ``` * `[:+/` Sum the rows: ``` 3 3 2 2 2 ``` * `] (...(...)) <above result>` Execute the verb in parens with that result (`3 3 2 2 2`) as the right arg, and the original list `]` as the left arg. Now we'll break down the verb in inner parens first... * `<.//.~I.` This is a dyadic hook which first transforms the right arg `3 3 2 2 2` using `I.`, which duplicates the indexes in place according to the multiplier at each index. Thus `I. 3 3 2 2 2` gives: ``` 0 0 0 1 1 1 2 2 3 3 4 4 ``` * `<.//.~` Use this mask to group `/.~` the implicit left arg (the original list): ``` 0 0 0 1 1 1 2 2 3 3 4 4 <-- Mask 0 1 2 3 4 5 6 7 8 9 10 11 <-- Original List ``` * `<./` Returning the min of each group: ``` 0 3 6 8 10 ``` * `]#( ... )` Returning to the verb in outer parens: Make right arg `]` (ie, `3 3 2 2 2`) copies of `#` the result of the verb in the inner parens. Thus: make 3 copies of the min of the first group, 3 copies of the min of the 2nd group, 2 copies of the min of the third group, etc: ``` 0 0 0 3 3 3 6 6 8 8 10 10 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` smLhSdcF ``` [Try it online!](https://tio.run/##K6gsyfj/vzjXJyM4Jdnt/39THYVoAx0FQx0FIx0FYx0FEx0FoJCZjoK5joKFjoIlUAokbRgLAA "Pyth – Try It Online") This answer is mostly straightforward in that `c` provides the appropriate splitting behaviour. After that, we map twice to each element of the inner list the element of that list which is minimal. The interesting part is performing this double map: `mLhSd` expands into `mmhSdd`. [Answer] # [R](https://www.r-project.org/), ~~52~~ 47 bytes ``` function(L,n)ave(L,sort(seq(0,a=L)%%n),FUN=min) ``` [Try it online!](https://tio.run/##NYy7CoNAFET7fMVthHvDCPsyxiW2qSRdPkDEBYusRE1@f7NbpBjmcAZmS4FuNaXwidOxrJEHRBm/c@593Q7e5zcrjP0gVRUF9@ejfy1RUmDltUYjp8DaO@g/mALKu7OBLThxB7IgBdKgBtSCHOgCumZTrMnJUykr@TH9AA "R – Try It Online") `ave` replaces each member of a group with the value provided by `FUN` applied to that group; the rest is just figuring out the groups. Thanks to Robin Ryder for -5 bytes. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 90 bytes ``` lambda L,N,x=0:sum([(w:=len(L)//N+(v<len(L)%N))*[min(L[x:(x:=x+w)])]for v in range(N)],[]) ``` **[Try it online!](https://tio.run/##XY9LDoIwEIb3nmI2JjM6Rgs@G7mB4QK1C4ygJFJJfeHpsYCaajed@b/5pmn5vB7PJlyWts6ibX1Kit0@gQ3HXEUTebkVqPAho1NqcEPjcTzE@7pr@jHRQBW5q1UlsZJRNXyQJp2dLdwhN2ATc0gxJs1KU93EiT1cGoI9eB9UgiFgCBmmmkHQh/AfCXwyacmUYc6wdDD04ap13IjzZwyL76BLmtSZolstQufOfLcTR0F3iZ93SbZVaXNzxeYn5PUZDtrIz6h@AQ "Python 3.8 – Try It Online")** [Answer] # [CJam](https://sourceforge.net/p/cjam), 25 bytes ``` q~\_,@d/m]/{_,\[:e<]*}%e_ ``` [Try it online!](https://tio.run/##S85KzP3/v7AuJl7HIUU/N1a/Ol4nJtoq1SZWq1Y1Nf5/wv9oAwUjBRMFMwWLWAVjAA "CJam – Try It Online") ## Explanation ``` q~ "Read whole input & eval"; \ "Swap the splitted-items down"; _ "Copy the list"; , "Find its length"; @ "Roll the 3rd-to-top on top"; d "Convert the number to double"; / "Divide them (resulting in a float)"; m] "Find the ceiling of that number"; / "Divide the list into that many chunks"; { }% "Map every item in that list"; _,\ "Preserve the length of the list"; :e< "e< doesn't take a single list, so"; "we have to reduce by minimum"; [ ] "Turn this result into a list"; * "Repeat the list that many times"; ] "Put the result into a list"; e_ "Flatten the list"; ``` [Answer] # Python, 118 bytes ``` def f(L,N):l=len(L);s=l//N;m=l%N;return sum([[min(L[s*i+i*(m>0):s*i+s+i*(m>0)+(i<m)])]*(s+(i<m))for i in range(N)],[]) ``` [Try it online!](https://tio.run/##bYpLDoIwFAD3nKIbk/fgJSD4BfEEpBdoujCx1SZtIS0sPH3FGHfuZjIzvebn6JuU7kozDQNxbG1vlYcBu9jbsuSd6@2Gd0HNS/AsLg6EcGYdRMxNYXJw1wrbD8efFWAuDiXKHOKXUY@BGWY8Czf/UMBRkpCYpmD8DJkGUdGWampoR3s60JFOdJbEasww@zOtqVlTegM) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` Fη⊞υE÷Lθ⁻ηι⊟θF⮌υIEι⌊ι ``` [Try it online!](https://tio.run/##HYzLCsIwEEX3fsUsJzCC9S0udSMoFLeli1BjM9CmNY/@fpx2ee/hnMZq3wy6y/k7eECroEzBYiJ46REfLt554o/Bp3FttPhTAtilgJaAlaxyGOVV6rpaAm8zGR8MJiUlzy7iTYeIc4wXlfvUo5hi5FxVG4KCYEuwI9gTHAiOBCeCM8FF0IyLWv46r6fuDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fη ``` Loop from `N` down to `1`. ``` ⊞υE÷Lθ⁻ηι⊟θ ``` Remove the last `|L|/N` elements of `L` and add them to a separate list. ``` F⮌υIEι⌊ι ``` Reverse the secondary list to restore the elements to their original order, but map each to their minimum before implicitly printing them on separate lines. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` äεWδ, ``` -2 bytes thanks to *@Grimmy*. Prints each of the integers on a separated line. [Try it online](https://tio.run/##yy9OTMpM/f//8JJzW8PPbdH5/9@UK9pSR8FYR8FAR8FQR8FUR8FcR8FER8FMR8ECKAISNQJioBSIMo79r6ubl6@bk1hVCQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/qpuSZV1BaUmyloGTv6WKvpJCYlwJjPmqbBGQWcyn5l5YA1QCV6Pw/vOTc1vBzW3T@1x7aZv/fkCvaUMdIx1jHJJbLCIltzBVtAGSb6JjpWMRymXJFW@ooGOsoGOgoGOoomOoomOsomOgomOkoWABFQKJGQAyUAlHGYA0QpUZgbSZgPWZgbUANllA9hrH/dXXz8nVzEqsqAQ). Outputting as a list would be **6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` äεWδ]˜ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8JJzW8PPbYk9Pef/f1OuaEsdBWMdBQMdBUMdBVMdBXMdBRMdBTMdBQugCEjUCIiBUiDKOPa/rm5evm5OYlUlAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/q5ulir6SQmJeioGQPZj5qmwRkFv8/vOTc1vBzW2prT8/5r/PfkCvaUMdIx1jHJJbLCIltzBVtAGSb6JjpWMRymXJFW@ooGOsoGOgoGOoomOoomOsomOgomOkoWABFQKJGQAyUAlHGYA0QpUZgbSZgPWZgbUANllA9hrH/dXXz8nVzEqsqAQ). **Explanation:** ``` ä # Split the (implicit) input-list into the (implicit) input-integer # amount of pieces, with smaller pieces at the left side if not all are equal ε # Map each inner integer-list to: W # Push the minimum (without popping the list itself) δ # Using this minimum, apply to each value in the list: , # Print (this minimum) with trailing newline ä # Split the (implicit) input-list into the (implicit) input-integer # amount of pieces, with smaller pieces at the left side if not all are equal ε # Map each inner integer-list to: W # Push the minimum (without popping the list itself) δ # Using this minimum, apply to each value in the list: ] # Close both this double-vectorized apply-each, as well as the map itself, # leaving the minimums in the inner lists after the apply-each is finished ˜ # Flatten this list of integer-lists # (after which the resulting list is output implicitly as result) ``` [Answer] # [~~Perl 6~~ Raku](https://github.com/nxadm/rakudo-pkg), ~~66 65 63~~ 59 bytes -4 bytes thanks to Jo King. ``` {flat map {.min xx$_},@^m.rotor((1,0 X+@m/$^n)Zxx@m%$n,$n)} ``` [Try it online!](https://tio.run/##bY7dTgIxFITv@xSTuCrEZmX5E0JMMNzwAF4YDZgiXWig7dp2Zclmn309rEQu9PLMzDdzMun2w1ofb9LHukz3IkCLDGWslUFRRO8Vny517GywrtVKeAcvd1N9Hy1N@7Uopvo6Mjwy7aqeMFayKzxvpZO3HgKrfAPqcGKXry3ClpozJ7@kCZ4u5ZHm5iMoa5A6q3GwbqfMhiyJVDkfEJSWMVXO7YEwx6FCk/IgxucrLz9zaoMIQeos@JilrbeEo8vR4@gvOJL2hM2enmdzlFjLVOT7gLJCxSrGvDiC8h1K/SIcA44hxwPHiGNM1slOFnxARWfgz8B/eveidxq93/SOyOpdrHGT//lg0KyeY@fh7mm8wZMekfRE/Q0 "Perl 6 – Try It Online") This function causes an exception when first executed, but subsequently works. In previous versions of Rakudo, it always worked, and I have [filed a Rakudo bug](https://github.com/rakudo/rakudo/issues/3444). Thanks for helping me find it. ## Explanation ``` { } # anonymous function with parameters @m (array) and $n (bucket size) @m/$^n # calculate bucket size: length(@m) / $n (1,0 X+ ) # make a list consisting of 1 + bucket-size, bucket-size # using the cross-product metaoperator X with operator + Zxx@m%$n,$n # repeat (1 + bucket-size) length(@m) % $n times # and repeat bucket-size $n times (* didn't work) # using the zip metaoperator Z with operator xx @^m.rotor( ) # take batches of those sizes from the list @m map {.min xx$_}, # replace each bucket with its minimum repeated by its length flat # flatten the list ``` # Previous version, ~~65~~ 61 bytes ``` {$/=$^m/$^n;flat map {.min xx$_},$m.rotor(1+$/xx$m%$n,$/xx*)} ``` [Try it online!](https://tio.run/##dY7BCoMwEETvfsUetkXbRU2iVhG/pGjJoULBqFgPivjtaUwtnnpb5s3sTP8cmkSr@VwXesGgwEoFWLV53cgRlOxh8dWrhWnCx0qo/KEbu8FlVwyMpE7Y0nZdvFXnjvOWM9TuPSRgBJxAEEQEMUFCcCNICTKDNsxKir38FzjcpWF/dH7oodUj@zc1SBwos/7vgti27ra9mG/lNs6ESZoR@gM "Perl 6 – Try It Online") ## Explanation ``` { } # anonymous function with params $m (array) and $n (bucket size) $/=$^m/$^n; # calculate minimum bucket size $/ 1+$/xx$m%$n # take (length of m)%n batches of size 1+$/ ,$/xx* # and then as many batches of size $/ as possible $m.rotor( ) # from the list $m map {.min xx$_}, # replace each bucket with its minimum repeated by its length flat # flatten the list ``` [Answer] # Haskell, ~~158~~ 145 bytes *Thank you @SirBogman and @PostRockGarfHunter for saving 13 bytes and for the great tip* Please feel free to improve it. ``` l%n=map(minimum.o)[0..t-1]where(t,w,v,g,a)=(length l,t`div`n,w+1,t`mod`n*v,map(l!!));n&b=div n b*b;o i|i<g=a[i&v..i&v+w]|b<-g+(i-g)&w=a[b..b+w-1] ``` ## Explanation ``` list % n= map (minimum . sublist) [0..listSize - 1] where (listSize, widthLastBlocks, widthFirstBlocks, lengthFirstBlocks, indecesToElem)= (length l -- t ,listSize`div`n -- w ,widthLastBlocks+1 -- v ,listSize`mod`n*widthFirstBlocks -- g ,map(list!!)) -- a n & b = div n b * b -- bigest multiple of b smaller than n sublist i -- o |i < lengthFirstBlocks = indecesToElem [i & widthFirstBlocks .. i&widthFirstBlocks + widthFirstBlocks - 1] |b <- lenghtFirstBlocks + (i - lengthFirstBlocks) & widthLastBlocks = indecesToElem [b..b + widthLastBlocks - 1] ``` [Answer] # [Haskell](https://www.haskell.org/), 116 bytes ``` p=replicate []&_=[] f&(x:xs)=(p x$minimum$take x f)++(drop x f)&xs f%n|(q,r)<-divMod(length f)n=f&((p r$q+1)++p n q) ``` [Try it online!](https://tio.run/##XY5LboMwEIb3nGIWgIyYIGwgL9VHyAmQVaFgEitgjKGVF707MV2kVRbz@kb/P3Nv5ofs@3U13ErTq2uzyKAW8SevRdDFxJ3dnHBiwIWD0mr4GsKleUhw0CVpSlo7mt8@dnPQRfqHTGiTj12rvi9jS3qpb8vdrzX3Xt7FhlNKvdCAhilZh0Zp4NCOARir9BLWeZZRKqLqBWiWlSKibzP7EyDDEvd4FFHxgieEAiFHoAgVwgGhRNgjHD3ZKPPhV1sp/h8rMMcd25L/ga1P "Haskell – Try It Online") The `%` operator is the bucket and minimize function, where `f` is the list and `n` is the bucket size. The `&` operator is a helper that repeats `x` times the minimum of the first `x` elements of the list `f`, where `x` is the head of the right parameter list. The sum of the right parameter list may be greater than the length of the left parameter list, but the left parameter list must be divided evenly. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~91~~ 77 bytes ``` ->l,n{(0..z=l.size).flat_map{|x|(k=l.slice!(0,z/n+(z%n>x ?1:0))).map{k.min}}} ``` [Try it online!](https://tio.run/##bY5bC4JAEIXf/RXTQ7DStO16ywLth8gSFQqSiXSBWvW3m3uRfAjOPsyZ78zZ@@v8GYpkWKcV1i1hlMqkoo9S5i4tqtPzeDs1bffuyFXZVXnJF4Sh3NQrIpd1@oYD3zPXdanirvRW1n3fDw0UWcYQOIKH4CMECCFChLBFiBF240qtucBQOJr@oQL5H8@zHtNeoI/FAn1r7zRnKkNdYxHb5Kk2HeW@Kh0yBRv5k6IpMqUYCCdTJ61mo0ro0dwItOKZw/AXDCaZq@aNf/FG/gs "Ruby – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~107~~ 105 bytes ``` Z,x,y,i,m;f(*a,z,n){for(x=z%n,Z=z/n;m=*a,y=Z,z;a+=y)for(z-=i=y+=x-->0;i--;)wmemset(a,m=a[i]<m?a[i]:m,y);} ``` [Try it online!](https://tio.run/##ZZJ9b4IwEMb/51NcSExAjsjrpqt130NClsaXpclAg7gJhs/Ori1TnKRNc/f091yPduNvvkT52fdrvGCDEgu2d6YCWyzd6/5QORfeTkpc83ZWsoKT0vA1tkx4vHGV3vpc8sbjF99fBUz6PnN/il1x2tWOwIKLTObL4l0tbwU2Luv674PcwrGSZe3QnIqqQlqhda@WSe/BsTOwXWaBqqBECRzIfdkyz5OuBfeNky3YSB5UQAHHc31ybMgV3VmWYgshS8cFclfRVtTiI8xyMrwGCCFChBAjJAgpwgvCK8IcYUGSksOOzWbpCI0MeufUBgjBX0EWaj81cmuExM8IEBONGMrGD0xyO2Gkz0YHmxss1hgJgRZozB/I1JALbWo6THVXg8vQWKSa0@5hbIzTkXFw6@SvSDJwwyQuyul@HPM/kfxSfWEmEWGC4SiOKY5GcYIpxqM4xTDRBsMTgLuvvtVRjqz/p@LnlHF7SKkaqgLVoK/a1eeqpEdldf0v "C (clang) – Try It Online") Thanks to @ceilingcat for saving 2 ]
[Question] [ This is a different type of compression challenge. In a normal [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge, you are required to recreate a list exactly. Here, you are allowed to round the values in any way you wish. What's the catch? Your score is penalized based on how wrong your output is. At the bottom of this question is a list of the first ionization energies for the first 108 elements. Your program, upon execution, should output a reasonably accurate copy of this list. There will be no input or arguments. For scoring purposes your output should be deterministic (same output every time). **Output format** Your program/function must output a list of 108 numbers, sorted in order of increasing atomic number. This list can be in any appropriate format. The source data below is provided in the correct order, from hydrogen to hassium. ## Scoring **Your score will be your program's length in bytes plus a rounding penalty.** A rounding penalty is calculated for each element and summed to give the total penalty. As an example, let's take the number `11.81381`. Let's say that your program outputs an incorrect value of `11.81299999`. 1. First, both numbers are multiplied by the same power of 10 such that there is no longer a decimal point in the true value: `1181381, 1181299.999`. Trailing zeros in the true value are considered significant. 2. Then, the absolute difference is taken to determine the absolute error: `81.001`. 3. Finally, we calculate this element's penalty as `max(0, log10(err * 4 - 1)) -> 2.50921`. This formula was chosen such that an error < 0.5 gives no penalty (since the answer is correct within rounding), while also giving an asymptotic 50% chance that rounding the number to any particular decimal place would provide a net benefit in score (assuming no other compression). Here is a [Try-It-Online](https://tio.run/##hZVhbxs3DIa/@1ccAn@wk04RJVGi6nQo9i@Gphhc9JIZc@zMvqAohvz2jHdHUm6BYQWCnmSJIl9R7/Pcn/b49nHYnh77ofvQ/f1ttej4H0SHlVJM3iPEPM2F5JBKpFJlAl2sUCCVDNO4uhhCrnUakAuVPFQ/xwMXsg913ggcKSaIelQG8pjmUXEpBArzieAwJ0xejoNYfcllGhWXUw4R5adKWDLJyYCQSaJ7lyhnyjqK2fs5XQiu5pJlHbqCNQPMJyfHpeccJavsACIgBi9DzJCqfFMg2ZVdSVxL0UHOCJLsKCWQDKoPKRcdEYHXZTlWKlpgCTmSV2lrglpViVprbPGo1iRKVFdIiuVPDLEGvQCCSKCSc4DspYTkoBQIJLFzZcWKlRqA85DvHGPV@YJEKAn4GlKUb4AaNTEWG70qgCR7ycWoN1Ic31uISX7gsigESaQQXwAGjZXGbpN12VOkKmV6X7Pdb0KQdPl@IYxNPBcdWSbOHjFpoQEg5yQDTqPqZyRt8FSiTgZU8ZE0w5xiAf0uPoog3C6pki7nKvTEKQFZ4gPYal@0Z8DyZeUxAWpSKfDjA2s59JIuC5gqFm0gysnrTVCMoh5x/1GIKjKnqvOVbzGKjiEgYns2saC39vfc5XZIYt1K1QsMhPze9BxI2rBQpPs5WEkiTXK@hJK8lhUKpaB3wN0erNeil5fOCupTg5pMv5CxSYmmcGliV7D0q7w23kagWkd@/fqe7WHruqz5WsN7U1/11Xeqj3ex3rx9fO4P2/2w689sp6v1ZrF4OJ661fLAQ7/p@P87FoTGr5ubdfcP710Op5eef17ONvxpefi8GacfX/rzGOXuV47C46eX/ejR4K@v9/3hcfhztTo/73fD6vbe3b6bw6zXn@DzemNRrz/M@y4Ctqlx7uvu4YGDbr@cV/OOX2TdFGT3wKlPS@4673DOl3dZkWOyU2U8/9r1@3P/X0v2x0cJdd0lPgXWt@MU@Omg18XrYrE8vzx1N5zeH90oWpOSU30@7Q5Dd/X78eXUDcdhu@/mX793u/P7@8O49f5wf7ja6MrfTv32r6/Hb4fuy3dOrH/qD8P7acH/38gcgsfwrrv6qZQpxOvi7e1nRv7Ax0s2GhcbExsPjYWNg8bAxr/GPuOeMc9411hnnDPGXfDtgm0XXFOmKc@MZcoxY1jjl7LLuGXMarxqrDJOCaOMT8amCy4Zky54pCxSDimDlD/KHuWOMkd5Y6wxzjTGGF@MLcoVY8oFTy5ZYhwRhgg/ZnYIN2ZmKC@MFcoJYYTyQdggXFAmGA@MBcYBY4D6v3q/@r56vvq9eX3z@ebxzd/N22dfV09XP29ebj5uHi7@PXm3@rZ4tvi1eLX4tHi0@LN48@TLkydPfjx58eTDoweX6W96EP8C) implementation of a penalty-calculating program. The input to this program is provided as a list of numbers, one per line. The output of this program is the total penalty and a per-element breakdown of scoring. ## Data The list of numbers below is the target data, in the correct order from atomic number 1 to 108. [Source](http://physics.nist.gov/cgi-bin/ASD/ie.pl?spectra=H-DS+i&units=1&at_num_out=on&el_name_out=on&shells_out=on&level_out=on&e_out=0&unc_out=on&biblio=on) ``` 13.598434005136 24.587387936 5.391714761 9.322699 8.2980190 11.260296 14.53413 13.618054 17.42282 21.564540 5.1390767 7.646235 5.985768 8.151683 10.486686 10.36001 12.96763 15.7596112 4.34066354 6.11315520 6.56149 6.82812 6.746187 6.76651 7.434018 7.9024678 7.88101 7.639877 7.726380 9.3941990 5.9993018 7.899435 9.7886 9.752392 11.81381 13.9996049 4.177128 5.69486720 6.21726 6.63390 6.75885 7.09243 7.11938 7.36050 7.45890 8.33686 7.576234 8.993822 5.7863552 7.343917 8.608389 9.00966 10.45126 12.1298431 3.893905548 5.211664 5.5769 5.5386 5.473 5.5250 5.582 5.64371 5.670385 6.14980 5.8638 5.93905 6.0215 6.1077 6.18431 6.254159 5.425871 6.825069 7.549571 7.86403 7.83352 8.43823 8.96702 8.95883 9.225553 10.437504 6.1082871 7.4166796 7.285516 8.414 9.31751 10.7485 4.0727409 5.278424 5.380226 6.3067 5.89 6.19405 6.2655 6.0258 5.9738 5.9914 6.1978 6.2817 6.3676 6.50 6.58 6.65 4.90 6.01 6.8 7.8 7.7 7.6 ``` ## Baselines & Tips The source data above is 906 bytes, with certain compression tools able to get it to sub-500 bytes. Interesting solutions are those that attempt to perform intelligent rounding, use algebraic formulas, or other techniques to output approximate values in fewer bytes than compression alone. It is difficult, however, to judge these tradeoffs across languages: for some languages compression alone might be optimal, while many other languages might lack compression tools altogether, so I expect a wide variation in score across languages. This is fine, as I'm going by the "competition within languages, not between them" philosophy. I anticipate that it might be useful to attempt to take advantage of trends in the periodic table. Below is a graph I found of ionization energies, so that you can see some of these trends. [![enter image description here](https://i.stack.imgur.com/5pJyF.png)](https://i.stack.imgur.com/5pJyF.png) [Answer] # [Clean](https://clean.cs.ru.nl), 540 bytes + 64.396 [Penalty](https://tio.run/##hVddbxU3EH33r1ihPCTQLp7xeDxuaIX6L6qCqiAuNGq4ocmNKlTx2@kZ73hDkaryAGtfe2Z85uMcPh7ubuqXl6eru/eH0/Lj8udf52nBHypr7SZFcq5UdOyxrNVasdZjo66lUyNpSmPd18KsvY@FrdwtU8@bPVpZM/ftIsFSESrTlZLlKtuqrcJsvHmktapUyeGOSs9N21i1VUW51PipW21q4ZkqqYX1vIqpms5V0Zy3cInXrk3jXF1b7Uq0eZYVT1ctEZWuRIVq5RzLqiQ9vo0tbunaBG9pc6FaKYJ1KMli0TOLtrkyozyPaenW5gMba7E8oe1CvU8keu/l0Z71LoFEX5vFY/FZuXSeCTAqRhNyGNAcT5CVWiO2sK0diLX9qUyII761lD73WzWrEUDuLCW@iXqZgQHsmicC1eKuraXMjLQVeeMi8QOeZcwRSDMkoPK0JV5tcU6zFevxzJy77vmVShEu8kvsRbw9ugAmRF@rzIcykarEAmH0@VlsFri0Mje5TvCrzQhVSqP53XIJQFAu0m0exyumxxFAHMlM@@ncZs3QHi@Qr0J1BiWM5qO95GqOcAGg9NpmAZlKnpmwUgI9Q/0ZlwkyQp37HVksgSNzrfWxbUqreS//jCrfnQhwa30mkK2i36Yfklmw1KL6YaxJQCNrbtwkz2dxM@GZA1Q777VWcnQ6EJytRl12/FjrI5R1R7g9gt1pD79Ht@Ga0cS6oPtnP@@NPc/pjHcv@LyjP/GdfTqbN11cfnn58XC8ujldH@4xTs8vLlN6d3u3nJ8dscyXC/59AUDMv549u1j@xt2z093DAT@fbWP417Pj60vffv9wuHcrL36CFaw/PNz4jKb89OnN4fj@9Pv5@f3Hm@vT@fNX6/PvNjMXF7/S64vL3erTH7d7Xxl83PK9t9fv3sHo1Zv78@3G93FuGLl@h9DHkRdLXusWL27tj/Rgx8uw/3k53Nwf/uvIze37MPV0EXihi@e@RXk4@pw@p3R2//BheYbwflsctEcoEerHu@vjaXnyy@3D3XK6PV3dLNuvn5br@x9eHf3qq@Or45PLefLnu8PVH29v/zoubz4hsMOHw/H0wzjw/xnZTGBN3y1PvnnKMPE5ffkyObJIl4p@SBtBgjKloAtRfEGQmGFaLWP4ToasopjG6KBgSRN0Xq6lpUmU1ti6cE@TKxlNjhFa0@RLZdQ6@iUFZVIndGwrnCZtchsjqaVgTljAoMnosEme8GDoKEsbgeLnzEU5e2CDRBXU6XFOGq2gFFMw3GRS6YTHgEQnm1asGwulyaiMUQ12ojQ5FYjlhpmVglXFwIC1ZEvBqyyCFaykIFeEZYJ29xODYX3KIXgZG2DZ3CsAwlta2qiWIVs6V8X4DLpFnOZMRikYl/AgQD6uDNpVn0T411JQLwNMJBBqZ9AvA2xsgHo8sxsD4y1VsZmChBWEgVBF0kbEuTRD8svI/aBjED8A9jwGIxOSSAZ8JivDDthXNG28XAiDFHvmeRzc3CsBlow5H@xMrRPj/Q7poGiYjIrbeFq6@4QYczicrKHESusZJZaCsbP4VPZaGLQtHQUBgldOg7rxuo4hjpdu7F07aiur10ZQuLKgkrV47Qwa9@pBNnsKJod9RI2ySpPMi6J/uLrNjdCtIvUEXgxSR2106i6VJrOzh6kYxTu7NwJ6JU16R@MBChB48DvSk0vUuHN8xp@6b4Dp0a4i0LQOL7KX0XyUETh8bKyfCWhkQRbS4H4YcKIcBRoSAOcLTkIshA7QrzIytADQkIZW8tIxx945G3quu9sROLsbwOVXXBsgjkYqrnmGQsDYMPfk1RY6wQcNUG/eBi4WEEVt0OfqXoZgQMFCdjXeWgmiwTr@Gs02hUMlAZDqhTDEAwaUVTSw98VQEFxAn45PqAjC8AIIUNshJZD3At8oldATyKW3fPbGGaJCMCKQuboNEhcWEBAVVc5pagvcEGHyMFxeoPnY52Lx1hoKwwjFnz3yoTI8jUS@V1KIDQxaVAJDpoTiyChUINq8lYbsoO4HgFsK5QH918iUvRiG@sDIMPhvngVXIJgTeMzoHNchnnsYqmhgSaFH4BsnMW/SJkoACIYknEvapAmyif9IwKaXhwsUlBRwHJW/yRR46c4SNPCAWPEORkc2Hkb96V3RQDjoGy5c0EuMCY3K9bHpVV0Khg1aw5seTuEEXjEfqteL@pHHQnZZ868Nlze@gYlZOh7s9ZJHpWNUgxCqV8O3Gy2PHVMCcj5adBjFTOuY2v8A) = 604.396 ***Note:*** *for the sake of readability, I've escaped every byte in the `[Char]` literal as most of them are non-printable. However, they are counted as only one byte per escape (except the null, quote, and newlines) as Clean naturally takes source files encoding-independently (except nulls).* ``` import StdEnv,GenLib c[h:t]=[(toInt h>>i)rem 2\\i<-[0..7]]++c t c[]=[] r[]=[] r l=[7<<29+2^62+sum[d<<p\\d<-l&p<-[32..53]]:r(drop 22l)] u::Maybe[Real] u=uncompress{e\\e<-[108:r(c['\145\062\353\227\045\336\021\131\341\224\212\225\230\140\121\241\231\027\321\306\361\254\075\154\161\041\144\255\346\110\371\126\172\155\361\127\152\023\350\222\117\116\341\222\155\357\351\072\341\153\315\025\171\317\141\367\076\232\377\323\206\301\257\235\103\154\157\274\035\010\347\167\142\370\355\074\172\320\347\036\165\262\210\364\177\025\144\176\303\223\143\116\340\270\012\172\062\377\257\141\265\320\342\261\225\347\215\165\044\152\017\011\133\251\027\347\243\307\231\304\165\351\325\035\036\053\010\341\344\131\363\207\072\045\327\012\130\347\167\023\312\023\210\013\347\244\236\020\172\153\362\370\142\123\276\116\226\341\211\245\105\136\145\146\130\367\123\026\312\244\225\347\152\225\145\142\207\164\227\145\360\105\140\201\041\271\141\273\274\230\020\101\166\101\133\171\063\155\302\062\036\061\335\147\130\365\175\201\203\035\357\341\272\172\270\067\047\002\200\223\342\156\230\253\152\347\105\322\335\117\203\220\242\342\316\137\311\247\004\155\164\124\131\205\325\203\116\306\365\170\325\032\143\337\017\331\232\006\266\122\176\305\334\137\214\312\130\035\110\306\206\227\001\000\150\353\121\132\146\246\226\231\071\365\050\140\063\063\333\314\314\307\314\354\231\231\171'])]} ``` [Try it online!](https://tio.run/##RVTbihNBFHzfr8iTuqy7nEt3jy5ZnxQRFMR9TI8Qk1k3kBvZRBDx141Vp0d8GGa6@1zqVNX0Yj3Mt@fNbnlaD5PNfLU9rzb73eE4uT8u321/vHw/bD@uvl0sZo@3x/5u9uK4@7A9Th7fvFldHobNxGpdTa9ncnPT9f3V1WJyRCji@ovD@Jqs72bddGqvr@xrsaun02a2nE73tS6n1@tneyS73dxk7/vbw4vlYbefmK0v@4vT7e2n@c9vw@zLMF9jeXfaLnab/WF4evo11DogUeUVchaz51VTrlKsevZq1lXB2r1UMa3qWj0p9lM1NbxzNRfk4MG58QwxgjzH2qVUL9jLqUqXq@KtWAviNKFGRu1UqqpU77Bn@O4McTnyFHU0G@o58Aj64Uyxp2XEMcZm9Muoi1zuK7C7Yg7gU9R15mDfC@bpCjAiriNGzEiMQowd9hEv3nBy3QE39oT4EmoU1mEu1ugrOCdet3Yu4EkLOAF/xpzC867hSPxmL/KKHsnHOTAX6gn4ZK3gHjnEQ8yGeq0@apJLy9HLMB97CeuSI8woSo1QP48aMA59XLrQxSVFDrly1InZqC34ajNS39R0LuSmC07DA/QCMfp/LkIXbfpwXlEfe0Lb8IyMemK/NN7InzK@KzG/2ail0j/kHw955De9wX7kHTnCWPqO9UceOLsFvzlqE7OWFN7lnhdpNcmzNO8ZvRZvD43p4cCKcy2lvcEjvSPFm8ekaRN8QQenV9g/8NFnOeob9CWv4cno0XQNjckZfSLEKeED6qq5BAbLHvPEXELOrfWBtha@QQz9x0fJDXoEb6yZAidnV2saWtTIkRtei/@RWGXU38KH7l34x5mDPUGckQf@X@FZ3gEp@pmm0IBzS2CTqMv/KO4LcozZNEvcIRr3hoWWlprecUfwv6R/c7s/yDMfd3oqtUe69s4pcvhAk@f9Zf/7fH@c4269m5zOfxYP6/n3p/P1h4/ntz@3881q0Ra4cYfDv8Xn9fz4sDtsYoErGXfxXw) This is the first challenge where I've been able to utilize Clean's generic compression ability (technically not actually compression, it's binary serialization) to gain an actual benefit. I started with a `[Real]` - a list of 64-bit floating-point numbers, those from the question. After serializing this list, I simplified the top 10 bits (which were the same for each number), and the optimal configuration of the bottom 32 bits into the constant `7<<29+2^62`. The remaining 22 bits per number were translated into 2.75 characters each, and encoded in a string. This leaves the entire compressed constant at **only 302 bytes**, including every escape! [Answer] # [Python 3](https://docs.python.org/3/), ~~355 + 202~~ 353 bytes + 198 penalty = 551 ``` for i in'趐￵㠡愍噢甹靍跄땠㖀侙㹐哜洫毙蛿ꐏⴰ㾤䑎䜕䘻䙱䵤剄刋侈偯懌㹴刼旧斆竼醽⭼㭉䂹䔏䙜䧕䨝䲠䶦囊仟嶡㰽䱴妝巋泍繆⢉㙁㨎㦨㣺㦄㨜㫀㬈䀅㴋㷔㺯㾕䁡䄛㡼䜍亘凞册埘嵙嵃怊沨㾗䴵䯘垗惿濥⩦㛳㠂䆧㵑䁻䄺㺻㸰㹟䂅䅥䉊䎫䒀䔺㌃㺑䛊儳倩伞':print(ord(i)/2665) ``` [Try it online!](https://tio.run/##FcjdTtpwGAfgW2nigbqELHGZWbydObeeFEPYwc5aKJVvYYLQtHw5LTXMgNKCLaXcC@/v/YNbsl0CxufwOf@R/pZUPuz2pMS7hPRF@Zw8lZWvJ9L39Fni09vtzpIpSZZkZX87q/1f@dQfCL3C5s2mEbx0Ktu5/rfZ/6ct6VpFbFJQ4ytbeCMxNrfW6k/tcu1NKL5FvQq7ifYC5iP8Wy7onC8hzrM2FhdlCjzOR6I1FNfGZhS9GMv1Q0QPBWQCNC5h2hg24Xbw1MfMYauIRY9nA5os8eix0@F5SUwrm8BY3xTI1MitkuPSr5AcnVybRir9zkPNkVeieYPCMcVNaAPoFg0i2BWEbb7oslHmXpt9k/2sUIviyaW4Bc/HuM3dlsiuxOpufe@QNaV@BsaQ/Dq0BfSQwgU9TyjoIZND7g6FIqoj/FTRCKmcpbAOq8j6lNV7RN39k/OUrKQPkqnTA/nw/dHx8cfD3e4V "Python 3 – Try It Online") I used `0xffff (65535)` as upper bound because it's the max value that can be stored in a single 3-bytes unicode character. Since the highest ionization energy is ~24.587, that gives a ratio of `2665`. To generate the string itself I used the snippet `''.join([chr(int(round(n*2665)))for n in ionization_energies])` (on python2 you need to use `unichr`), your console may or may not be able to print the characters. --- ### 4-bytes characters, 462 bytes + 99 penalty = 561 ``` for i in'򖛬􏿸𻩕񧈞񛳀񼤓򠲊򖩥󀯗󮣬𸶞񔥢񂍻񚋙񴀥񲦹򏝅򮕴𰁌񃨇񈥢񋢔񊨓񊶬񒏒񗚽񗋰񔡂񕞒񧻆񂗠񗘳񬒕񫸬򂬋򚷮𮍚𾿾񄱴񉘳񊱑񎝜񎰡񑛏񒠺񜎠񓳾񣟨񀀯񑏠񟎯񣪶񳧟򆋻𫄹𹩷𽬜𽑕𼢹𽇭𽰄𾛰𾮨񄂄񀷥񁬶񂧎񃤐񄚟񅋼𼁡񋠊񓡆񖿯񖪈񝖑񣌪񣆷񦃬񳝰񃤫񒃁񐦉񝅇񧄳񶹼𭃠𺙈𻡍񅱉񁊈񄡙񅓾񂪑񂅝񂑺񄤃񅟜񆜑񇺀񈲩񉤍𶍍񂟅񋎚񖒚񕋦񔄳':print(ord(i)/45312) ``` [Try it online!](https://tio.run/##FYvbbppgAMdfxWQXbZeYZeuWLH2ddW290ca4i90hB0UoWFBwogiIZ6miGBQVfKXvT3fv3O3v8Py79FTI354/ZLIfs5mf@R@F@1z@8S7zq/SQ/f6fnR8KxUwuk8tfpXrH@1s/7chhqmHM99AJKBwHjdReC6k@Hb5Ty9b7wvXILuyhOeyDlg4wxDY21BDrUZTWTS5daBvil1/ATKrgL43Yb0KYNCCEHtS6ipYRoyX6aDo0tJ6K8aECumWj9SeAp2qY77yU9sTU2C7IQjJIckrArjaoXbywUiCbXci@A6VTh2rv0ZVtNIIErjUBRS2h1G1Y8hLuLEQwttKKeCBzNiLRdEtir0tiRSPHfkTi6huJfZYkHZ8kiwlYmgW1HaLshaDHMpjBK1jDAiceybHsQLQFNJwK9NMS@oyHqStwX2ZwK1uMGA@B6V@eOVSmjNdRDSZXxZgNEEZH8sbYZN/mycGRwK1qKAs8WKcNrpGAnimgORO0sgc7YMBZXVS6Cqp7Cvx6itpAIqEkgbY4iLIBXTWgiSM02eDq7rmYy5euC8X769zNp6/fbj9/uTmf/wE "Python 3 – Try It Online") Same idea, but the max value is `0x110000` [Answer] # C, 49 bytes + 626.048 penalty = 675.048 ``` f(i){for(i=0;i<108;)printf("%f\n",5.5+i++/13%2);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPT1sA608bQwMJas6AoM68kTUNJNS0mT0nHVM9UO1NbW9/QWNVI07r2P1BOITcxM09Dk6uaSwEI0jQ0rblq/wMA) [Answer] ## CJam (389 bytes + 33.09 penalty => 422.09) xxd-encoded: ``` 0000000: 2256 3232 7c24 1bf9 7116 2f43 c82b 110e "V22|$..q./C.+.. 0000010: 6b93 4525 1cb3 4118 4afc 4d05 5c22 e15a k.E%..A.J.M.\".Z 0000020: 11bc 563c 38e4 626c 1efb 6b10 c229 0e35 ..V<8.bl..k..).5 0000030: 873d 15df 2f71 36ca 404d 54d9 4979 17ba .=../[[email protected]](/cdn-cgi/l/email-protection).. 0000040: 4938 a953 6fb6 5f04 75f0 5c22 5c6b 39e5 I8.So._.u.\"\k9. 0000050: 3073 6fbd 343e fb36 4fff 357c 8c36 10f3 0so.4>.6O.5|.6.. 0000060: 3b3c 37cd 3f1c 10a1 3f06 933d 0f1d fa3d ;<7.?...?..=...= 0000070: 67e8 4549 6a9c 2f7f 24be 3f99 4713 e147 g.EIj./.$.?.G..G 0000080: 011c e14f 20d5 577f 668d 2135 30c2 2d47 ...O .W.f.!50.-G 0000090: 45d1 315e bc35 8936 0987 385e d238 7a9f E.1^.5.6..8^.8z. 00000a0: 3af1 3b55 f441 2cbc 3c4e 8843 7ceb 2e25 :.;U.A,.<N.C|..% 00000b0: 1d93 3a60 15f1 4237 3fb0 4404 f949 e750 ..:`..B7?.D..I.P 00000c0: 423d b21e 265b 7cf6 2958 df2c 4edf 2c27 B=..&[|.)X.,N.,' 00000d0: c32b e42c 992c d32d 1394 2d2e 3cd9 3119 .+.,.,.-..-.<.1. 00000e0: b22e 74c3 2f41 cb30 9630 6ea4 313c dd32 ..t./A.0.0n.1<.2 00000f0: 04a1 2b34 0be1 364c 6fb8 3c32 61af 3e74 ..+4..6Lo.<2a.>t 0000100: e23e 55c3 4160 af43 6f8e 436a f544 733d .>U.A`.Co.Cj.Ds= 0000110: eb49 e030 6e71 b43b 2ad7 3a24 af41 d345 .I.0nq.;*.:$.A.E 0000120: 5c22 c84a 7f9d 204a 3ea5 2a1d 0dcb 2b05 \".J.. J>.*...+. 0000130: 2cfd 32ba af31 46da 320f ef30 1ab5 2fe5 ,.2..1F.2..0../. 0000140: 2ff7 314a c632 20ba 3278 b6b4 34d1 b5a7 /.1J.2 .2x..4... 0000150: b0b6 bebd bc22 7b69 3235 362b 3262 283b ....."{i256+2b(; 0000160: 287d 2531 6125 7b32 253a 2b5f 323e 315c (}%1a%{2%:+_2>1\ 0000170: 2b32 6232 405f 2c33 2d5c 323c 3262 2d23 +2b2@_,3-\2<2b-# 0000180: 642f 4e7d 2f d/N}/ ``` Basically this is ``` "MAGIC STRING"{i256+2b(;(}%1a%{2%:+_2>1\+2b2@_,3-\2<2b-#d/N}/ ``` This uses a custom variable-width floating point format to store the numbers. Two bits suffice for the exponent; the mantissa gets anywhere from 5 bits to 47 bits, in multiples of 7. The remaining bit per byte serves as the separator. There seems to be some corruption going on when I copy the magic string to make an [online demo](https://tio.run/##DZDtT1JxAEbXpm3Vpjhnr@qMoFQu3nt/CRJcQERysMS20loxUWu1sGRO2ypxbrolZbYZvYyW09tg1vwAvkCJaNvz/GHEh/PhnI/nUWz8RaViHBEiYbrEg@mzsp9JS0PdJFIBczP2fOdDLA/WRozUHzSgPKI5mJl43srDSQMXO@psWHY3cUOetvN97@BdpoOvz6EUdOD3nTiK0ZqXzEeMkckbzCozcRx1e3hoH@I/WwIf7AbuubQernqbDdC9J5Fy17ew5H7KX4FgDD/kBROOvUgPNFIfONFMfaiNX@4tPMHqZZvCRetAgGvqKMo2vLOfwrJjlJ8cb7Dh5I5rmPs@CWUtjKQ/we0ucwtSzrEm7vT1eJHvr@FBkFu3@9zYbb36MMFix31uSOEq17hkYUZCWmLK2ojP1i6NafUCdrtmuST7uKLgqzKFjKpxXdRAt3SfoW6/FcdfTYwj55nlT88wl3xjyPnj@OiPsdA/4@Z2kJvK1DT2XZ385jQh52MqUF2aDC1gvS3kQbaz5TRXLLUSjwRKyKk3@V3UM6dcREFmVuYfNcS3og0l8QpF7HdzDQVsIV@VYxyhbJx7Jmx2i5hod7XPm9Vx85wwOy1R4VEj1Sh6o9J1a0RoYsJ65bEcnpcrlf8), so that scores about 2 penalty points more. I'll have to figure out how to build the URL directly... --- Generation program: ``` e# Score calculation {1$`'.+'.%1=,10\#_@*@@*-z 4*1- 0e> ml10ml/0e>}:E; q~] e# Custom float format e# Exponent goes from 2^1 to 2^4, so 2 bits e# Each byte has 1 bit for continuation, so 7 bits available e# That means the options for the mantissa are 5 bits, 12 bits, 19 bits, 26 bits, 33 bits, 40 bits, 47 bits { :X 0\{2/\)\_2<!}g e# Stack: exponent mantissa 2 47#*i2b(; e# Stack: exponent mantissa-bits W%7/W%Wf%:M 7,{ )M<e_ 1_$+2b2@,#d/ }% 2 3$#f* X\f{E} _,,.+ _:e< #)< \(4+2b(;\+e_7/ _,,:!W%\.+2fb:c }% ""*` ``` [Online demo](https://tio.run/##fVJNbxtHDL3Pr5hEFhJL8njI4XwpbmGg8DGnFnAOapWVuord6iON1kVbw/3r7uPIvvay5HDJx/dIrn/rds/P/cj@uD586@26264ftt1wf9ibRzr7/M5N37kxfTcjvxgtryfX15OLf6xM6ML6/nu725LfbS/hPs1vPhjzx78/GwOwHx6Ow2FnN9tDN9jN4duuGzR889fXw77fD/bLoT/azTek8C9khwOMzOwR1q7uh2PL7dZ3dvX30Nu77mhJ44pk14f9cL9/aBRbSW4ltvuzu992q22vxT/doe@u7/ZHO9z19vBVs4@tXt@7DhjHY2c7SI6tfmaJX5364nB6cUJ4ccS/Oqeu5tFYO/@Ej1888uXifLHkqzdPXxDQkQ7d@ve57V9Vv7bFXwbCaHLPq/cf/j/3orWx9nacL2/Ht5vx/CNeeaaNrT3/eNUvm0fLsymv@Ho2@vUSgadxaxLORpsJvE@LzePNE5zlbOamauf9Fczo/MrALN7LVKkspv0yX57S5m9uxws35c1qvjaAe/t28tk8P1NwsRYJ4n2kkAyLiyWHkise0YVKmSQnMtUF5lSrKY5r8VS9IXKcPNdkCFVBKBjAJSo@iqHshLmwYXIxSRQPOArV55RNdkkSh4hQLTGnAlSKlAoQvJOSUknqheQ9GWJXU074F12ONRGxEQfKKQV0So4oUIzs4cZEUmELF2QllwV8sjopRUJjlUoFTvUsKatXCnn9lUItWcllTqF4lVyFalXmtdZwqiu1CphXlwtIwkQOlXUYhUIhHQGSkwcNcZQzcUF9qlCVG0Um4MOmgGkos1hKBLCvLAGWqAZtBPHRK@NYkFdcCDqV7DAvDoIAKBVmgOeCQUTWGtGN4V/yJZQKet7X1GYpkdAWsyTWhZMJkAIGMYoSZKKUBA7gq5pQ9AAkB31w1CHEot2ShExqsw8gjvELDgIBsFCkBoqwZ2p/fdb5U@sJ9VEoagNhHBq1VUWPlhAmNWZdREnidRIlBKgq2FnhoILRUt8VEwvQxhxjPJ1MyNG3U/DYfAMR6MlVB8Yl4rYUh0SXShmXgKIsoC/OZ87ilRLnIqwzwPa57Sh4XCuU6UlRlaaLUzzJi01tPomu1NpXXBRSCqnmgKvVm2yHqfGk/drSfVOuGvXe9Pj@Aw) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~379 361~~ 360 [bytes](https://github.com/DennisMitchell/jelly/bytes) + 0 [Penalty](https://tio.run/##hZVRbxs3DMff9SkOQR7spLuIkihRdToU@xZDUxQpekmNOU5mOyiKIZ894@lInS7D0HvxSUdR5J@kf0/DYYevH0@3h/vh1H3o/v6xMh0/4HvMFHywFsHHsudCj5Q8pSwb2PsMCUKKUNa5987FnMuCepfJQraTP@hdtC5PB4E9@QBer4pAFsO0Sn1wjtx0I/QYAwYr14HPNsVUVqmPITqP8ikTpkhyMyBEEu@2DxQjRV35aO0ULrg@xxTFDvuEOQJMN4eeU4/RS1SxB/CA6KwsMULI8k6O5FTsU@Bcki5iRJBgRymBZJGtCzHpigismkWfKWmCyUVPVqXNAXJWJXLOfvZHOQdRIveJJFl@Reez0wIQeAKVnB1EKymEHlICR@I7ZlYs1VQdcBzyHr3Pup@QCCUAm13w8g6QvQbGYqNVBZDkLPXea0VSz3VzPsgHTouck0AScQHQqa8wdpvYRUuesqRpbY61vgFBwuX6ghubeEras0wcPWLQRB1AjEEWHEbWV0/a4CF53XSo4iNphDH4BPqerBdBuF1CJjXnLPTGEoCYWAfV2ibtGajxsvIYADWo4Hj4oLYcWgmXBQwZkzYQxWC1EuS9qEfcf@S8isyh6n7mKnrR0TlEnMfGJ7S1/S13eb0ksG4pawEdIc@b3gNBGxaSdD87S0GkCb1NLgWrablEwWkNuNtd7TVvZdJZQR01yKHq5yLOUmJVOM1iZ6jhZ5k2PkagWnuefp3nOthqFzXe2vC2qq/66pzq8Jr15vXj07C/3Z22w5H/TlfrjTF3j4dudb7npd10/HvNgtD4dnm57v7hs@enw/PAn8@nv@FP5/vPm3H7/nk4jl6uf2cvvH543o3/0WAvLnbD/v70fbU6Pu22p9XVTX/1bnKzXn@Cz@tN9XrxYTrXOJy3xr1v27s7dnr79biaTvwmdsXJ9o5DLybXne1xipdP1STHYEtmvP/SDbvj8H8mu8d7cXXRBb4F1lfjFthy0Yt5Meb8@PzQXXJ4X7pRtFlKDvXpsN2furM/H58P3enxdLvrpq8/u@3x/c1@PHqzv9mfbdTyj8Nw@9e3xx/77utPDmx4GPan98Xg1xWZXPAa3nVnb1IpLl7M6@tbRrZ8tOPjTEvISkclo5mhqEC0@oBRLPqsj6lsFC7On5JROEbdQlMJKXRMs6eKSMUjNrcoI5WPNShnGko2hJzpKA8aIWSTj3KyMlL5WNmoXKxxGmFj40UIGXNjUzBplJBmhqOAMeRZE8FjRWPFYoPEisOKQiMUrIGUDAsMFxkWJC6incAoUGyPCxsXxoWQzY5wcmFTaOmbjCozZ14KK2Nb7wJMmneUmkrMtvOUm7Zat@ys3BRmTrxs456wWZBpJloKKWej8bQAU2C5OF@QKbhcKDxC0y7LUOAp4FzYCj4rOis2BZm2baLCzWWBCj4X5ZggKgBtxkIxWhGq@GyGd2ao8hOb6wtDsS3YCFKFqAJU4VnraASgzT1CUWxaRFhaOCoMXQo1klQoOhF0WY0RpG9FH4E6wXQ5AoWpPP2moLRglBFqCj25ALZ9Rin@u5PGIV/sWvwXQ "Perl 5 – Try It Online") = 360 -18 using an observation from Peter Taylor (order 10 values have leading 1 or 2, while order 1 values do not). ``` <3Ḣ‘_L⁵*×Ḍ “KẸ⁺dzⱮÑ2⁵İ2ṭ¬⁴²¬¶9°ß°øİẆGẊœ%X(¢ṆḢ/8¬Ɗ’b7µ18,-;_3+\⁺Ṭœṗ“SŒƥŻƭ°}MḋṘḥfyɼ{ṅĊLƝġœ⁺ḟ8ḶhỊDṭ&æ%*ɱ¬ =¦ẉ Qh"¶:ḌĊ€ĖṢė°ġṀƬmẓSṃ÷E⁴Ȥ⁼ḋ#ØĖḂ2øzẸżƈ¥Ȧƥ7¢®|ḳẊṆƙƲɦḟɼṖỊɲṁẉɗ6ẇSɗ⁴ẉİt]ẓeṆHṚƑ½>]ɦ~T¢~ẆẆA`/6ƭṡxṠKG£Ḅ+wḃḣỤw×ḌŻƲF>Ụ]5bJḤḟCḞİḶ|ȥ9Ỵ0ụKṗT⁴ƥƁṖı×ṄtTĊG©ṀḥṬƭʂd½ḊȦуŀṣ¹ʋṖẓYL²ṅṿ&ẏdDṬIɦỵ¹b,ḷṣƭ#P'µ{GTƇẹ¥L8SƥÑṆẈėẎßṀḷƓ⁷ðḳċ¿ḶM_ḲẈg9ḢĠi+LṭẹḲẎ¤g<ṘJJĿßæ⁺(ɲỴ3ɲgkSḃIƙṭ.Ỵ&_:cĿƝı’D¤Ç€ ``` **[Try it online!](https://tio.run/##HVJ9S1NRGP@/TyFZFmovJumcJkSWOScUG0GQLEzTSkFCWKbJru9dw9CBd0Y1nbsXgjuZ07lz7p0Mzjl72PVbPPeLrMfB@eccnuf8Xj9OTE/P1@t9ncgyfiIVC/tasVUayH5c8xO/RaYZne/Ic@hsf@6IzygdtNlQEHnGKwdhB3bBhk2w0eGQRGddHCNbQ3YqjYUbMiXTvsZeQapX5v3E/li3KHYE2u/0xjrb3viag9yuJpEbhBKp7oJZdSEn8t9GkG0hTyEz38975QXka0oPwx91WE1eLbF0ANn5FLr6ALFqkdbNVu9E2E2PhEVEm15OXRfnQSKvdH/ZVntEVBkirw6RJ8CeQScZQb4iS0997ayW9bUyoTXLFA2y5QeSfUWHVcuwKcyaBWa3yIjjRZKDjo58Hfah4FnEwCsj3yMGXgG5Rqie0YXORsQz6FO6qvzcKAFN0Mpz5L9gR1z0j3rWUlRklsgjOo/f3uuCHPLDL8gPhgfFEbLVtjiyFWRH6GbjDfvJj8KzfrqOPhwLIcsS8BNkf1We9C/WzB50z@6jaw6ThVECBhM0oqVOaJmvzkWVPij@kWoykpyG3OXyuLhAptcsSbFVE8iPBL/culLiJF@HBWlZQ15pQefnOFlrD5FUtyj4WDuyEg1DrvnFLVFcGIzCBsUtzHAgAqbcIZXobCqDCiLTDbwSUFIlSTxP1ZaoEN2RGLICTU32UMnUwYe2cKNRvPG6LbKTfZR4KKQqMi0tSvk2OeuedXqFyU8RcmUI9mn@Lj21xILvVIXacEKFGhBZuUEp1@v/AQ "Jelly – Try It Online")** ### How? Creates these two constants (AKA nilads): * (A) all the decimal digits used (i.e. the numbers all joined up ignoring where they join and their decimal place separators), and * (B) the number of significant figures used by each number Then uses those to reconstruct floating point representations of the numbers. The full program is of this form: ``` <3Ḣ‘_L⁵*×Ḍ “...’b7µ18,-;_3+\⁺Ṭœṗ“...’D¤Ç€ ``` (where `...` are encoded numbers for constructing B, and A) and works like this: ``` <3Ḣ‘_L⁵*×Ḍ - Link 1, conversion helper: list of digits e.g. [1,2,9,6,7,6,3] <3 - less than three? [1,1,0,0,0,0,0] Ḣ - head 1 ‘ - increment 2 L - length 7 _ - subtract -5 ⁵ - literal ten 10 * - exponentiate 0.00001 Ḍ - undecimal (convert from base 10) 1296763 × - multiply 12.96763 - i.e. go from digits to a number between 3 and 30 “...’b7µ18,-;_3+\⁺Ṭœṗ“...’D¤Ç€ - Main link: no arguments “...’ - base 250 literal = 16242329089425509505495393436399830365761075941410177200411131173280169129083782003564646 b7 - to base seven = [2,0,4,3,2,4,2,4,3,2,3,3,4,2,3,5,3,3,0,3,4,2,4,4,1,4,3,4,3,2,1,5,3,5,1,5,0,3,3,3,3,3,3,3,4,3,4,2,3,2,4,5,4,0,1,3,2,4,2,5,4,2,2,4,2,3,4,4,3,3,3,2,3,3,3,3,4,4,3,3,2,0,5,3,5,2,3,1,1,6,2,3,3,3,3,3,3,1,3,3,3,3,2,3,3] µ - start a new monadic chain, call that x 18,- - integer list literal = [18,-1] ; - concatenate with x = [18,-1,2,0,4,3,2,4,2,4,3,2,3,3,4,2,3,5,3,3,0,3,4,2,4,4,1,4,3,4,3,2,1,5,3,5,1,5,0,3,3,3,3,3,3,3,4,3,4,2,3,2,4,5,4,0,1,3,2,4,2,5,4,2,2,4,2,3,4,4,3,3,3,2,3,3,3,3,4,4,3,3,2,0,5,3,5,2,3,1,1,6,2,3,3,3,3,3,3,1,3,3,3,3,2,3,3] _3 - subtract three = [15,-4,-1,-3,1,0,-1,1,-1,1,0,-1,0,0,1,-1,0,2,0,0,-3,0,1,-1,1,1,-2,1,0,1,0,-1,-2,2,0,2,-2,2,-3,0,0,0,0,0,0,0,1,0,1,-1,0,-1,1,2,1,-3,-2,0,-1,1,-1,2,1,-1,-1,1,-1,0,1,1,0,0,0,-1,0,0,0,0,1,1,0,0,-1,-3,2,0,2,-1,0,-2,-2,3,-1,0,0,0,0,0,0,-2,0,0,0,0,-1,0,0] \ - cumulative reduce with: + - addition = [15,11,10,7,8,8,7,8,7,8,8,7,7,7,8,7,7,9,9,9,6,6,7,6,7,8,6,7,7,8,8,7,5,7,7,9,7,9,6,6,6,6,6,6,6,6,7,7,8,7,7,6,7,9,10,7,5,5,4,5,4,6,7,6,5,6,5,5,6,7,7,7,7,6,6,6,6,6,7,8,8,8,7,4,6,6,8,7,7,5,3,6,5,5,5,5,5,5,5,3,3,3,3,3,2,2,2] - ("B" significant figures, with 1 extra for the very first entry and a missing last entry) ⁺ - repeat (the cumulative addition to get - partition positions) = [15,26,36,43,51,59,66,74,81,89,97,104,111,118,126,133,140,149,158,167,173,179,186,192,199,207,213,220,227,235,243,250,255,262,269,278,285,294,300,306,312,318,324,330,336,342,349,356,364,371,378,384,391,400,410,417,422,427,431,436,440,446,453,459,464,470,475,480,486,493,500,507,514,520,526,532,538,544,551,559,567,575,582,586,592,598,606,613,620,625,628,634,639,644,649,654,659,664,669,672,675,678,681,684,686,688,690] Ṭ - untruth (1s at those indices) = [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,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0,1,0,1] ¤ - nilad followed by link(s) as a nilad: “...’ - base 250 literal = 1359843400513624587387936539171476193226998298019011260296145341313618054174228221564540513907677646235598576881516831048668610360011296763157596112434066354611315520656149682812674618767665174340187902467878810176398777726380939419905999301878994359788697523921181381139996049417712856948672062172666339067588570924371193873605074589083368675762348993822578635527343917860838990096610451261212984313893905548521166455769553865473552505582564371567038561498058638593905602156107761843162541595425871682506975495717864037833528438238967028958839225553104375046108287174166796728551684149317511074854072740952784245380226630675896194056265560258597385991461978628176367665065866549060168787776 D - decimal (to base 10) = [1,3,5,9,8,4,3,4,0,0,5,1,3,6,2,4,5,8,7,3,8,7,9,3,6,5,3,9,1,7,1,4,7,6,1,9,3,2,2,6,9,9,8,2,9,8,0,1,9,0,1,1,2,6,0,2,9,6,1,4,5,3,4,1,3,1,3,6,1,8,0,5,4,1,7,4,2,2,8,2,2,1,5,6,4,5,4,0,5,1,3,9,0,7,6,7,7,6,4,6,2,3,5,5,9,8,5,7,6,8,8,1,5,1,6,8,3,1,0,4,8,6,6,8,6,1,0,3,6,0,0,1,1,2,9,6,7,6,3,1,5,7,5,9,6,1,1,2,4,3,4,0,6,6,3,5,4,6,1,1,3,1,5,5,2,0,6,5,6,1,4,9,6,8,2,8,1,2,6,7,4,6,1,8,7,6,7,6,6,5,1,7,4,3,4,0,1,8,7,9,0,2,4,6,7,8,7,8,8,1,0,1,7,6,3,9,8,7,7,7,7,2,6,3,8,0,9,3,9,4,1,9,9,0,5,9,9,9,3,0,1,8,7,8,9,9,4,3,5,9,7,8,8,6,9,7,5,2,3,9,2,1,1,8,1,3,8,1,1,3,9,9,9,6,0,4,9,4,1,7,7,1,2,8,5,6,9,4,8,6,7,2,0,6,2,1,7,2,6,6,6,3,3,9,0,6,7,5,8,8,5,7,0,9,2,4,3,7,1,1,9,3,8,7,3,6,0,5,0,7,4,5,8,9,0,8,3,3,6,8,6,7,5,7,6,2,3,4,8,9,9,3,8,2,2,5,7,8,6,3,5,5,2,7,3,4,3,9,1,7,8,6,0,8,3,8,9,9,0,0,9,6,6,1,0,4,5,1,2,6,1,2,1,2,9,8,4,3,1,3,8,9,3,9,0,5,5,4,8,5,2,1,1,6,6,4,5,5,7,6,9,5,5,3,8,6,5,4,7,3,5,5,2,5,0,5,5,8,2,5,6,4,3,7,1,5,6,7,0,3,8,5,6,1,4,9,8,0,5,8,6,3,8,5,9,3,9,0,5,6,0,2,1,5,6,1,0,7,7,6,1,8,4,3,1,6,2,5,4,1,5,9,5,4,2,5,8,7,1,6,8,2,5,0,6,9,7,5,4,9,5,7,1,7,8,6,4,0,3,7,8,3,3,5,2,8,4,3,8,2,3,8,9,6,7,0,2,8,9,5,8,8,3,9,2,2,5,5,5,3,1,0,4,3,7,5,0,4,6,1,0,8,2,8,7,1,7,4,1,6,6,7,9,6,7,2,8,5,5,1,6,8,4,1,4,9,3,1,7,5,1,1,0,7,4,8,5,4,0,7,2,7,4,0,9,5,2,7,8,4,2,4,5,3,8,0,2,2,6,6,3,0,6,7,5,8,9,6,1,9,4,0,5,6,2,6,5,5,6,0,2,5,8,5,9,7,3,8,5,9,9,1,4,6,1,9,7,8,6,2,8,1,7,6,3,6,7,6,6,5,0,6,5,8,6,6,5,4,9,0,6,0,1,6,8,7,8,7,7,7,6] - ("A" all the required digits in order) œṗ - partition at truthy indices = [[1,3,5,9,8,4,3,4,0,0,5,1,3,6],[2,4,5,8,7,3,8,7,9,3,6],[5,3,9,1,7,1,4,7,6,1],[9,3,2,2,6,9,9],[8,2,9,8,0,1,9,0],[1,1,2,6,0,2,9,6],[1,4,5,3,4,1,3],[1,3,6,1,8,0,5,4],[1,7,4,2,2,8,2],[2,1,5,6,4,5,4,0],[5,1,3,9,0,7,6,7],[7,6,4,6,2,3,5],[5,9,8,5,7,6,8],[8,1,5,1,6,8,3],[1,0,4,8,6,6,8,6],[1,0,3,6,0,0,1],[1,2,9,6,7,6,3],[1,5,7,5,9,6,1,1,2],[4,3,4,0,6,6,3,5,4],[6,1,1,3,1,5,5,2,0],[6,5,6,1,4,9],[6,8,2,8,1,2],[6,7,4,6,1,8,7],[6,7,6,6,5,1],[7,4,3,4,0,1,8],[7,9,0,2,4,6,7,8],[7,8,8,1,0,1],[7,6,3,9,8,7,7],[7,7,2,6,3,8,0],[9,3,9,4,1,9,9,0],[5,9,9,9,3,0,1,8],[7,8,9,9,4,3,5],[9,7,8,8,6],[9,7,5,2,3,9,2],[1,1,8,1,3,8,1],[1,3,9,9,9,6,0,4,9],[4,1,7,7,1,2,8],[5,6,9,4,8,6,7,2,0],[6,2,1,7,2,6],[6,6,3,3,9,0],[6,7,5,8,8,5],[7,0,9,2,4,3],[7,1,1,9,3,8],[7,3,6,0,5,0],[7,4,5,8,9,0],[8,3,3,6,8,6],[7,5,7,6,2,3,4],[8,9,9,3,8,2,2],[5,7,8,6,3,5,5,2],[7,3,4,3,9,1,7],[8,6,0,8,3,8,9],[9,0,0,9,6,6],[1,0,4,5,1,2,6],[1,2,1,2,9,8,4,3,1],[3,8,9,3,9,0,5,5,4,8],[5,2,1,1,6,6,4],[5,5,7,6,9],[5,5,3,8,6],[5,4,7,3],[5,5,2,5,0],[5,5,8,2],[5,6,4,3,7,1],[5,6,7,0,3,8,5],[6,1,4,9,8,0],[5,8,6,3,8],[5,9,3,9,0,5],[6,0,2,1,5],[6,1,0,7,7],[6,1,8,4,3,1],[6,2,5,4,1,5,9],[5,4,2,5,8,7,1],[6,8,2,5,0,6,9],[7,5,4,9,5,7,1],[7,8,6,4,0,3],[7,8,3,3,5,2],[8,4,3,8,2,3],[8,9,6,7,0,2],[8,9,5,8,8,3],[9,2,2,5,5,5,3],[1,0,4,3,7,5,0,4],[6,1,0,8,2,8,7,1],[7,4,1,6,6,7,9,6],[7,2,8,5,5,1,6],[8,4,1,4],[9,3,1,7,5,1],[1,0,7,4,8,5],[4,0,7,2,7,4,0,9],[5,2,7,8,4,2,4],[5,3,8,0,2,2,6],[6,3,0,6,7],[5,8,9],[6,1,9,4,0,5],[6,2,6,5,5],[6,0,2,5,8],[5,9,7,3,8],[5,9,9,1,4],[6,1,9,7,8],[6,2,8,1,7],[6,3,6,7,6],[6,5,0],[6,5,8],[6,6,5],[4,9,0],[6,0,1],[6,8],[7,8],[7,7],[7,6]] Ç€ - call the last link (1) as a monad for €ach = [13.598434005136,24.587387936000002,5.391714761,9.322699,8.298019,11.260295999999999,14.534129999999998,13.618053999999999,17.422819999999998,21.56454,5.1390766999999995,7.646235,5.985767999999999,8.151683,10.486686,10.360009999999999,12.96763,15.759611200000002,4.34066354,6.1131552000000005,6.561490000000001,6.82812,6.746187,6.76651,7.434018,7.902467799999999,7.881010000000001,7.639876999999999,7.72638,9.394199,5.9993018,7.8994349999999995,9.7886,9.752392,11.81381,13.9996049,4.177128,5.6948672,6.2172600000000005,6.633900000000001,6.758850000000001,7.09243,7.1193800000000005,7.360500000000001,7.458900000000001,8.336860000000001,7.5762339999999995,8.993822,5.7863552,7.343916999999999,8.608388999999999,9.00966,10.45126,12.129843099999999,3.893905548,5.211664,5.5769,5.538600000000001,5.473,5.525,5.582,5.6437100000000004,5.670385,6.149800000000001,5.8638,5.939050000000001,6.0215000000000005,6.1077,6.184310000000001,6.254159,5.425871,6.825069,7.549570999999999,7.8640300000000005,7.833520000000001,8.43823,8.967020000000002,8.95883,9.225553,10.437504,6.1082871,7.416679599999999,7.285515999999999,8.414,9.31751,10.7485,4.072740899999999,5.278423999999999,5.3802259999999995,6.3067,5.89,6.194050000000001,6.2655,6.0258,5.973800000000001,5.9914000000000005,6.1978,6.281700000000001,6.3676,6.5,6.58,6.65,4.9,6.01,6.800000000000001,7.800000000000001,7.7,7.6000000000000005] ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 403 + 9.12 = 412.12 ``` 00000000: 1551 5116 c030 04fb 7718 af20 e2fe 17db .QQ..0..w.. .... 00000010: f2d1 454d 4322 cae7 d8d5 ef4d 142c db87 ..EMC".....M.,.. 00000020: 5bdc 2bd8 785d 6cf4 22ec bc32 7167 f43c [.+.x]l."..2qg.< 00000030: be38 8bf0 c4cb 8345 fb54 4759 9423 f8a6 .8.....E.TGY.#.. 00000040: 2dd6 3b93 6919 3ee8 691b 8fba b758 5b47 -.;.i.>.i....X[G 00000050: 236b 6cfc 380b 1a3d 26c0 b278 de04 0845 #kl.8..=&..x...E 00000060: 85f7 c222 fdb0 288b f19d 4344 5a7b f503 ..."..(...CDZ{.. 00000070: 6ada e011 1533 69f0 41f4 fdc8 64e8 be8d j....3i.A...d... 00000080: e02a 0026 6c5d 3a83 7f70 2f1b ab88 8ca7 .*.&l]:..p/..... 00000090: 5fa8 e36a b64d 1425 f73a ee0c aab9 eb1a _..j.M.%.:...... 000000a0: 3b5f 1282 c9ba 9401 8c62 58b4 b5c7 6e24 ;_.......bX...n$ 000000b0: 6d1c d7c4 aa7f c626 7e44 d569 8a21 c7d6 m......&~D.i.!.. 000000c0: df65 d78f 1157 b495 4ea5 7b28 77ab 4035 .e...W..N.{(w.@5 000000d0: 9d45 561b fdae 9869 e34b d44c ea45 6b31 .EV....i.K.L.Ek1 000000e0: 46c7 63f1 ecfc bd03 645a 4f24 645a a4f6 F.c.....dZO$dZ.. 000000f0: 1a56 ceab 7b33 ade1 3202 681b d19f a088 .V..{3..2.h..... 00000100: 1f7a 4b97 1c7d 9952 d1b5 21dc 571c d9dc .zK..}.R..!.W... 00000110: 2702 a204 a254 f665 08e2 ed0a d451 c2a7 '....T.e.....Q.. 00000120: 6344 df39 5c65 98f3 7092 d537 2bc3 897e cD.9\e..p..7+..~ 00000130: 25ac 9a34 7a17 b324 17fb 5238 64d9 79e6 %..4z..$..R8d.y. 00000140: cc94 a475 edbc 3675 6372 45d2 01ec c9ae ...u..6ucrE..... 00000150: e44c 403c d1da 5eec 841e 6d73 acfd 6d6e .L@<..^...ms..mn 00000160: 3f8d 94cb 4e39 507c 995a 4f3d ac94 9da8 ?...N9P|.ZO=.... 00000170: afa5 cb13 2378 3994 da2d 0a2e 5a35 b754 ....#x9..-..Z5.T 00000180: 0943 9a0b 2b92 d151 1a6a 77a6 9c96 abb3 .C..+..Q.jw..... 00000190: ffc1 07 ... ``` [Try it online!](https://tio.run/##hVTZclVVFHz3K1oZpESWex4YFItEHpiESgkGkdojBgKFWimQKL8eeyfXkDdP1bnn3Htr9e7VvVbXg1r3x4uD10dHanNdhfZew2sd0JRVUG5WxKgTyjQKw8wBHXsF5OFDESXyTgTC67MTBE2MabqG867DWWPQyojoqXuMyd@0Mw29pkgM2b5364tVLffk61MMQwxfe4OpPSEm3xHadDBmNNRmDaIOEdPZBjyVy/L@2b4Qxvz@Qq5vMCwx6rAJqU6F5lpFss5jVu/gos/IzljMVAJ5pGMO27Jz@2c5d8rDEcP0HmBrtghZZ9gx0noj2qwFNfpEqo69XJFrsiff8ub15OntDYZfGDbU1UGDTapCF9thQlOoJib0oRxUIjece7W/qNy4KPJ@8dlgBGIkPyOaoZyzVwWTUsXUeUnsHHyJ/OqVXZouKS7xcWtr9/C0l0iMUHrBUFrTZbsaojJOU9jZG7tybK2O1IGXqwe7J9/z0T95m4gxlCmgRYEN0RdbkkWckYwmRSk1UfFWlrdfycX9Z1dF3n4jZ@YjL29nSRg2UL9wMhD0JVpyG6qhlJoxqi7Ac5GXnIwLclXOYhRi2OontEkcr0wjslOaBwcDn6pD9S0iDOOAa89PaqU@4ceb8xuMuvTompMYm@OZcYLVAXFQzu5DRipGo0Xaj9cnCBc/btHez095NGL0GTwxEsloH1Fd9nCjeMRqOLuxVDhl6a0MIjwWuS@Hl97JTb/B6MTIneb7QP1mLwM58fRhXUV3rmEU/huq1cTY/mnx2JM7cle2X@kNxiCGC6tjOzXGGrTaOQvB@QI3qcLxW3GTvfwg7biZvvvgfN897WWu3S@eaz9IOVbOR@lDwxplEBK5dZ0niqLBENI4tFw4@e2ML/o4P2bkmTVHaGqHnL1hZfUwmgvt41I88w3y4Y7IP/JIKOjjTxgrP0zkmcVwLYrhts5AiVUaBqOrQlGYUM2sGftyHb5zrKzIw1OMlR9hrUWfNsM3luc0Oacqk4y3kcHSLFKOA2hbkn8hwluReFnk4wZj5YfxpSEX6xCLpreWSurIQPTGrn3pGTEPanpBxH0QOS/yKHX56z8eKz9ay2yDgUPylQEQ@BZsNMzHbqA0E61lmr729kAkHLQ/ts9quvJjrDHgFFE6zQ32g0XJ6cEBjrSpTeZjDwvj7s3rIr@y@vWfvN9sMFZ@2MnFzisG3ViiqNiWOWs@mEZlscyda4nvWH0///i37D64cYbHyo8yOdetastEY3DZzKJeTIcqZjCDOOYMRHfci5x7n0WuiOx62dlgrPxQ2Vlqyhg0dbmhaaYujAKuSkBuOTBE6sqxW8Jkp6sv353VY@XHnE1D0f//u1h2dPQv "Bubblegum – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 116 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) + 429.796016684433 [Penalty](https://tio.run/##jVXhbts4DP7vpzCK/kjanSpKIkUu3WG4tzisw6HD3F5wadpLUgzDoc/eo2zJaS0XnYO6IkWRHz@S1kO32@Dz58P17rY7tJ/af38smlYf8AaFgw/WInjqdS4Y5Og5Slag8QIRQiToZTHeORLpBTZO2ILYwR8YR9bJcBDUkw/gSygCthgGKZrgHLshIhikgMHmcODFRoq9FA0Fch7zljBG4hwZEIizd2sCEzEVyZO1A1xwRihStkMTUQhgiByMpk7kMyoyAB4Qnc0iEgTJa3acT5GJQXOJRSBCyGATlcBZEOsCxSIxgy1m5IVjSTA68mwLtRJApDAhIv7oj0VCZkJM5JysLtF5caUADJ6hUK4OyOYUgoEYwXH2TaKMxTFVB4ojr8l7KfqIzJgBWHHB5zWA@AJMyUZbGEDOZ9l4XyoSjdbN@ZA3NC12LgOJrAVAV3yF1G3Zjix7lpymtUJjfQNChqv1BZeaeEjaK02KHjGURB0AUciCwpCy9FwaPERflA4L@cgFIQUfoayj9ZkQbZcgXMw1ixKxB5BNrIPR2sbSMzDiVeYxABZQwenwwdhyaDNcJTAIxtJATMGWSrD3mT3W/mPnC8kKtehFq@gzj84h4nFsfEQ7tr/VLh@DBOUtSimgY9R5K3EglIaFmLtfncWQqQnGRheDLWm5yMGVGmi3u7HXvM2TrgyWUQMJI3@O8EgljgzHI9kCI3zJ06bHGArXXqe/zPM42MWOCt6x4e3IfuG3zGkZ3ma5ev780G2vN4d1t9fP6WK5apqb@127ON2qaFet/r9UQjitzs@X7X969vSwe@x0@3T4DH853X5dJfXtY7dPXi5/Vy8q3z1u0jca7NnZptveHv5eLPYPm/VhcXFlLj4MbpbLL/B1uRq9nn0azr1weFQl3ff1zY06vf62Xwwnfst2vZP1jULvTS5ba3DAq6fGJBPYPjPVP7XdZt@9ZbK5v82uztqgUWB5kVRg@0BPzVPTnO4f79pzhfdXm0g7UqlQH3br7aE9@fP@cdce7g/Xm3bY/dmu9x@vtuno1fZqe7Iqln/suut/vt//2Lbffiqw7q7bHj72Bu9XZHChMnxoTyap9C6emufndEfqiB2f0PRX5EuVa7CfluMTGx0N//oYV5p0X2KT7slmJgzEiVNu0lVZRX5lo5G1RSca0tivrajRccX0qjD5pr8lmzDZ8o0OB081WGm4OqXO@lesSNJL8hc0VCWozmTijDTL@rAMpvpKV@M01aBJTtnDmr1UJJpR9ylNKZnTTInUr/lMN8SKTGlwCDJ1wFWzSKrllJF0N07K7icU6QcQU35YBVfNy79ql36BuJrcaXdgVTKa7TOYK0o9dXX71azGGRuuCJ5yKenXj2vNM83UvG51h3Nu6wG0w/TZivE3MvbvUzpPHw2/NzZnxh9nB35a9jBb0vc5nxv0SbT/AQ) = 545.796016684433 ``` “tẏØA5X¶tɱḅÐ-ı3OMm⁾¦ȷ #""*00-.Bı0FF_y¤ß÷!"&&)+5,=æ)8=Nc¡ÑÞŒŒŒÞßßñçðıȷñ÷Ø#,//6==@Nȷ*(6AR£ÑØøðñ÷ıııñ÷øþ !€ı#/-,‘+47÷12 ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5ySh7v6D89wNI04tK3k5MaHO1oPT9A9stHY3zf3UeO@Q8tObFdQVlLSMjDQ1XM6stHAzS2@8tCSw/MPb1dUUlPT1DbVsT28TNPC1i/50MLDEw/POzoJBA/PA6qYf3jj4eWHNxzZeGI7kLX98AxlHX19M1tbB78T27U0zByDDi0G6phxeMfhDSD5IxtBEKxyx@F9CoqPmtYc2aisr6vzqGGGton54e2GRv//AwA "Jelly – Try It Online")** Nothing particularly spectacular, a code-page index list, `“...‘` (numbers between 0 and 249), to each of which we add **47**, `+47`, and then divide by **12**, `÷12`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 164 bytes + [409.846](https://tio.run/##hVXbbhtHDH3nVywMP0h2Oh7OlRM7RdC/KOKgcJC1K1SWXUlGEBT@dpdnd7gKAhQV4PVwLuThGc7h87jf5rePx7v9w3gcPgx/f1vRoD@OLjdJMXmfOZZpLiSXpUaprU9kFxtXTrXwZDcXQyitTYa40MRz87M/dqH40OaDrJ5i4mihCovPabaqSyFImCOyyyXl5Hs4js3XUierupJKiLkvNcm1SI/MmYt0794lKUWKWbF4P8Pl4Fqppe/LruZWmOfIyWnqpcSOqjjmyDkH381cOLU@liD9VHE1aS7VjFIyd7CgkqUbzYdUqlki7G1biU2qJVhDieKN2pa4NWOitRZP/qS11JlorkpPVoc5xBbsAoSjsFGuDorvKSTHtXKQ7rs0ZawuqQZWHH1cYmw2X7NI7gB8Cyn2MXOLBkzJzt4YyNLPiovRbqQ6vbcQU1/QtCSEDqSKXkAO5iuh2vq@4iVK62l638pyvylzh6v3ywFFPCcdlSZFn3OyRANzKakbCqPZMIoVeKrRJkM28rMYwpJiZRtXHzshWi6piW3XLCziBKBv8YGX3b5azfCCV5nPibOBSkEfHy8ll32HqwSmlqsVkJTk7SYkxs6eaP1JiEayQrX5prcYO48h5JxPzybW7Jfy91rlS5CkvNVmFxgk63uzOJysYLn26ldnNXVqkvM11OQtrVAlBbsDrfaw1Fr0/aUrg/bUuKWFv1Dyicq8MFxPZDde4Lf@2vSYsHEd9fXbe14etu0rhncpeL@wb/zaO7XHS@vrt4/P4@5ue9yMB5XT1fqa6P5pP6zOd2r660H/3yghgtHl5Xr4R8@eH/cvoy6fzzL86Xz3@RrTDy/jAV5uflUvaj@@bKHR7C8utuPu4fjnanV43m6Oq6tbd/VudrNef@LP6@vF68WH@dwPDk9TmPu6ub9Xp3dfDqv5xC993@Rkc6/Qpy03g3d5xqunliQBdspM51@HcXsY/2vL9umhu7oYkkbh9RWm2E@BXumV6Pzw8jhcKrw/BpB2olKhPu83u@Nw9vvTy344Ph3vtsO8@n3YHN7f7nD0dne7O7u2nb/tx7u/vj592w1fviuw8XHcHd9PG/7/RmYXavO74eynVCYXr/T2hh5JaIqERkjofoSuR2h2/scfEzoeodP9PK@PidDmCN2N0NQIzYzQxAivEJ9I6FWEHvXTefQpQnci9CSCMhC6ED6F0Hb00whNBs5h1QCoDWGmBSDX14FuQaz6ox9dRU8g9AJCByBIP3xmgtgTVJ4g7wiRCYJOUHKCghOUG6tJzUKK26mOMNxAgwnCSxBcfCJBZDEK@AhiggJ9@1BRgnwCKqJ75AYsChLqiKNhzhkqiGQASPUMegcsBZ9MkLYZBc5DvwiyhW0MMhiLlaBNQIdPRAiAEzDAEw1lxgCRmdmzhWkvVjNNCjKphyoHTaIBwajTX8Ud/As) = 573.846 ``` “?#4ß<Ʋƒ⁻µ`kḞÑ6{ɱ~.ṣ¬⁷Ḷlŀ⁸ẎṘ£ỌgfĖỌƒ⁻ḋN?ḤḞ{ị#qp⁵mp&WṘƙ=/rŻ-vn⁼ẊTị}W;!z€ȦMẊẇİ_D8ỴtṫQAẎḣṬr¥1J3Ƙ~ʋ$ĿẠ7þƭ8ṛM{ịḟƇỵ÷b?°6I@?Ȥ⁾d⁹DẈcȷv5ⱮAJb}øDȯRµ’Ds3Ḍ÷³×⁵$2R;6r⁵¤¤;15r18¤¤¦Y ``` [Try it online!](https://tio.run/##HY7fS8JQHMX/llB6q1imCSuWsJcEgySQngr7BbXCVgglircXI0Woh1KKDLZ8yUqrtbstDO6dY/VffO8/su56OofD53DO7painAQBq95JkRnamfPevCuGHGKs7wG@p5eJ0s@gMgmWRnoMmYA/lVGVIQx2E6wW0cBp7Gy711z@a4DrSxJgnVdL4NQjhwWGjP3CeI7DXnt@Sh05E8UDhr7AvljhQDknjp2ys57fzfAE7JrbX5OT4Hwcg/W0nApXsAZWTyWPQjrmtSq/9aj7DfbDLB16z0mwbjPhDuCOVwPHoGZeIv3E4oLk6wwNNxmyZLDPN3yzGGeDl1Q6X6ZY9l@zxGDVtnwUA9ygJnmnN/xmdDorJlRuiE50UYirQjJ0pLsaBH8 "Jelly – Try It Online") There is a compressed number in there that is the concatenation of the first three digits of each energy (including trailing zeroes). I get a list of these three digit numbers with `Ds3Ḍ` then divide each by 100 with `÷³`. Some of the numbers should only be divided by 10, so I multiply some of these by 10 to improve the score slightly (`×⁵$2R;6r⁵¤¤;15r18¤¤¦`). **Previous version**: [Jelly](https://github.com/DennisMitchell/jelly), 50 bytes + [571.482 penalty](https://tio.run/##hVRtb9tGDP6uXyEE/mAn7eV4R/LIOh2K/YuhKQYXVTKjjp3ZCopiyG/PKOkopyuK@WD7SPHl4UNSj91xRy8f@s3xvuvb9@3f35ZNax/IgVQwY4wEmUddwkBSshStCgpZoQAWhlHWkFNi1VGQkFQiaJziQUgck06OYJEyQvZUDBIJJ6kETEnSlBECMRLGmg6yxsJllEpg5JSpPlKhwlIzAwFLjR4DCrOwS5ljnOBCCsqFqx2FQsoAU2YMVjpzrqg4AGQgSrGKxIBa75KkenEoaLUUF5gJKtiBSpAqaEzIxSURiG7GWaV4gSVxlujUKoKqM6Gq@RxPVLEyoaFILdaulLImb4BAFnDKLQDHWgIGKAWS1NisxliZS01gOOqdc1bXFxKhCiBqwlzvAJodmJFN0Rkgqb4ScvaOlGB9SxnrAytLUqpAilgDKHksHKat2nGULFrLjFF57i8SVLjWX0jDEE9FZ6PJ0BOhF5oAmLEKBkP9msUHHEt2ZSInn8QRMuYCfi8xV0JsXFDFza0KzzgCqCYxwWwdi88MzHiNeUIgB4XJlg/mkaNY4RqBqFR8gIQxeick58qe2PxJyk6yQXW9Whdz5TElIjqvTS4U5/GPNuVzEjTeinoDk5Dtm@cB9IGFUqffghWs1GCIJRWMXlYqgsl7YNOe5lnLsW66MeirBoozf4npTCXNDJcz2QozfK3bZm4CznW27fd9nhfb7djxzgMfZ/adX99TX95mtX758NjtN7t@253sdbpcrZvm7nBsl4u9iXHd2v@NESLD7epq1f5jvov@@NTZ48X0Gv642H9aD@r7p@40RLn5zaKY/PC0G97REC8vd93@vv9ruTw97rb98vo2XL@ZwqxWH@HTaj1HvXw/@b0KeFYNui/buzsLuvl8Wk4eb6vdGGR7Z9BHk5s2Bprwmtdc5AB2rMz0z223O3W/Mtkd7muoyxYtC6yuBxXEMdFz89w0i9PTQ3tl8P5sB9LOVBrUx@N237cXfxyejm1/6De7dnr6vd2e3t3uB9fb/e3@Yu2Wvx@7zdcvh2/79vN3A9Y9dPv@3Wjw/x2ZQpgMb9qL/5QyhnhuXl600YbsK43Oh0ziVxo0qcxH6tGfbF5bldmmvLKh0Wr6/fnQD9GnwzWW@//Kd7Ci8X/0/xc) = 621.482 ``` “¡9;ẋkñ¬nƑḳ_gÐ.RḊụʠṁṬl⁾l>ɼXZĖSṠƈ;cḶ=ß³ṾAiʠʠɼZÞ⁹’DY ``` [Try it online!](https://tio.run/##AWQAm/9qZWxsef//4oCcwqE5O@G6i2vDscKsbsaR4bizX2fDkC5S4biK4bulyqDhuYHhuaxs4oG@bD7JvFhaxJZT4bmgxog7Y@G4tj3Dn8Kz4bm@QWnKoMqgybxaw57igbnigJlEWf// "Jelly – Try It Online") Rounded each energy to it's nearest single digit integer. Concatenated together this gives `995989999958689999467777788889689999466777777889679999456656666666666657888899996778994556666666666677567888`. `“¡9;ẋkñ¬nƑḳ_gÐ.RḊụʠṁṬl⁾l>ɼXZĖSṠƈ;cḶ=ß³ṾAiʠʠɼZÞ⁹’` is a base 250 number which yields this. `DY` joins the digits of this number with newlines. [Answer] # Java 8, 48 bytes + 625.173330827107 [Penalty](https://tio.run/##3VTBbhtHDL3rKxaGDpKdjIczJIeMnCDoXxRxECjI2hUqrxxphSAo/O0ud3e4KgIUvdc6eMjhPD4@kvvcHvf0@rHfHh/bvnnffP@xWjT2BzmQCmaMkSDz6EsYSEqWotVBISsUwMIw2hpySqw6GhKSSgSNEx6ExDHp9BAMKSNkT8UgkXCySsCUJE0ZIRAjYazpIGssXEarBEZOmeqVChWWmhkIWCp6DCjMwm5ljnGiCykoF65xFAopA0yZMVjpzLmy4gCQgSjFahIDaj1LkvqKQ0GrpbjBTFDJDlKCVENjQi5uiUD0MM4qxQssibNEl1YRVF0JVc0XPFHFqoSGIrVYO1LKmrwBAlnAJTcAjrUEDFAKJKnYrKZYmUtNYDzqmXNW9xcSoUogasJczwCanZiJTdEVIKlvJeTsHSnB@pYy1gsrS1KqRIpYAyg5Fg7TVuM4ShatZcaoPPcXCSpd6y@kYYinorPJZOyJ0AtNAMxYDaOhfsziA44luzORi0/iDBlzAT@XmKsgNi6o4uFWhWccCdSQmGCOjsVnBma@pjwhkJPCZMsH88hRrHRNQFQqPkDCGL0TknNVT2z@JGUX2ai6X62LueqYEhFd1iYXivP4R5vyOQmabkW9gUnI9s3zAPrAQqnTb2AFqzQYYkkFo5eVimDyHti0p3nWcqybbgr6qoHirF9iukhJs8LlIrbCTF/rttkzAdc62/b7Ps@L7XHsfOeBj7P6rq/vqS/vYr15/fjcdtt9v2tP9jldrTeLxcPh2KyWnZlx09j/OxNEhtPNzbr5y94u@@O5tevl9Bn@tOw@bwb347k9DSh3HwzF7KfzfvhGQ7y@3rfdY//HanV63u/61e19uH0zwazXn@DzejOjXr@f3v0D8OIafN92Dw8Guv16Wk0v3ta4EWT3YNTHkLsmBpr42qu5yIHsWJn5X5p2f2r/LWR/eKxQ1w1aFljfDi6IY6KXxctisTydn5obo/elGUS7SGlUn4@7rm@ufj@cj01/6Lf7Zrr92exO7@674el9d99dbTzyt2O7/fPb4UfXfP1pxNqntuvfjQH/3ZEJwmx401z9UsoI8bJ4feXF//L3Nw) = 673.173330827107 ``` v->{for(int i=108;i-->0;System.out.println(6));} ``` [Try it online.](https://tio.run/##LY5NCoMwEIX3PcUsk0XEbkoh6A3qRuimdJHGWGJjEkwMFPHs6ViFGYb5ed@8QSTBnFd26D5ZGhEC3IS2ywlA26imXkgFzdYCJKc7kOS@lUQ5zlZMjBBF1BIasFBBTqxeejcR1IOuzuWVa8bqkrffENVYuDkWfsKlseRCKV8z3yl@fhmkHLD/sxGtkDbi9fvxFHS3YQtJ7GzM4WDNPw) Initial version that prints 108 times `6`. Will try to improve from here. [Answer] # [J](http://jsoftware.com/), 390 bytes + 183.319 [Penalty](https://tio.run/##jVXbbhtHDH3nVywMP0h2uh7OlYycIuhfFHEQOIjsCpVlV5IRBIW/3eUOyZVboGj1ouEsh0Mecs55Wu@35fXj8XZ/vz4OH4Y/vi9gkB@msTDllEMomGrfi3ks1BI1to0yJsaGuVXsNo8pxsrcDRojU0AOGg/HWENkPYgSKWVMflVFCiWr1cYcI0W9EcdSc8nBrsPEodXWrTbWXGMq9omptEp2MxasZNHDmKlWqm6lGoKmi3Hk2qr5lbEVroh6cx6l9FqTZVVHxISlxGBmqZjZ1hTJTtWxZamluVFrQUt2ghLJDA4x1@YWEQZ3q4mpeYEt1kTBoeWMzI4EM6dTPGLOhgSPjaxYWZaYOHoDCBOhQy4BarAS8oitYSSLXVkQa3OpESUPW9eU2PdbISqWQOCYk60ROXliAnYJjkAhO0tjSt6RNkrfYsr2QcqiGC2RRtKAEj1WnqbN/GqgRGxlhsB17m8uaOlKfzFOQ6xFJ4FJsi8le6ERsdZshqTBvkzkA55b8s1YHPxCnmHNqaGvW0gGiIxLZnJ3qcJv7AmYS4g4e4fmM4NzvoJ8yVg8qRzl8eE8ciVYugJg5tJ8gKjm4J2glAw9kvmjmBxkSdX3WbqYDMcYSymnZ5NaCfP4B5ny@ZIsuDX2BkYq8t78Hsw@sNhs@iVYywZNHkOLLQcvKzbK0Xsg0x7nWUvBXrog6E8NOc/4xVpOUJYZ4XYCm3FOn@21yTFCxzrJ6/f3PD9s96ue7zzwYUbf8fV36o8XlqvXj0/r3e32uFkfhE4XyxXA3eN@WJzvxAyrQf6vBRCaVpeXy@FPOXt@3D@v5fO50vCn893n1bR9/7w@TFGuf5YoYj88byeOxnBxsV3v7o@/LRaHp@3muLi6Ga/eaZjl8hN@Xq7mqBcf9NybgKetae/b5u5Ogt5@PSz0xE/m14Ns7iT17nI9hLFovnJqLnJKtlcm@y/DentY/5vL9vHeQl0MWW7B5dW0haFf9AIvAOeH54fhUtL7MkygnaCUVJ/2m91xOPv18Xk/HB@Pt9tBv/4YNof3N7vp6M3uZne2cs9f9uvb3789ft8NX39IYuuH9e74vjv8d0c0hNj4bjj7Ryk9xAu8vppGguqijJrqIagOTkPRNRBU@xKY6oEKnvyr1IGpHKjAyZCptE0252keu6A1UCmb4nYZg0m/RHtBpUvu76Il37taRVCZKmASBSpPfX9SJjBZAhUktYn0/sR9X5g/g4qP5cMJTHBg1pouNBlMYqb6xK/nM@kKqKQwqJYkMB0B1RAG0w9Q7ej/k26AaQaoXnS/SSsmW@SOQBVC/XPqfiILPS9RhAwqBglUB2RfFQCU@RvMpD8zvvN9Z3uYqV55HpTjMyi9934rtXde7/gqpzuhK5uDMnmPIyTO2o/ScS49jtI2GGODsXWfH2mw1ksEytAVjJv1Hur9EEJuYFQMMw0rB8NMv8q9YKwLRrjwhmuVajvP9nqUY51gy4w79/jOq06qf2dUeMOnb@kU/ieZ/gU) = 573.319 ``` d=.'5@-103659=-/-02247,...../////1-/1135,-...////0/0-/0124+--------.--....-.///00012.//012,--.-...--......,..///' f=.'[ZG@=:U]JX-`~/PD~kB+XrjlKzx_hG~ynkq~1e5_k)+DMAY~nB\ M,y5YUOTZ`c.v}"*29JrVvsK~~6K*I<I?j'';F>y3:"~~3<DRZaz!ppf\' p=.'tj1;p#Iq<M{^Z1c l~''@/q^aH9*~`J}~v8F~gQiGy8~%ye^F`Gt~-~G1ev>R4E$~F{/mKJ[S~HCrfxXkscWHku;t"c IWZF.n1l',9$' ' echo,.(_40+a.i.d)+(100%~_32+a.i.f)+1e4%~_32+a.i.p ``` [Try it online!](https://tio.run/##RY1pT8JAEIa/8ysQIQu0u93tgdwiYssRoqIIFORIKUKLWA4JhTB/vbaExOfDZOZ9Mnktz5sWCFJKmFEppWQKWMBUFOU7ngQIAQwLjEkKj68BFSgWKBNlDl8hOHAEB5pSX/mLP/nABPnFEsJf/lFo5jf2da1UyLY/6108BuGlAnaZ626sZeN4GM01cFf2GpipjOwEV2k@9GBVHoSbvKv02s/v@tgg@3MkKWbqm4/9tgGQaiRr@dq9hVBOLbpSNgIg5SstfXK8cZzZAIUcv3JnsZxzW1vnm6ehzozwEhAqCevhpJpJwrh@hn1aha/XheamIeaaQ3Ws7QCDxsx9sSU/RUE9Cd@Nev8Nqo@b2aFrb41O1f7N7SJGuNbRVbJiS8RnoiiMQqYx/@FJfCRTbkIWZJrg4ozSGIwk8RLMEhwz5f/b8bw/ "J – Try It Online") I rounded the numbers to four decimal digits and split them into one list for integer parts, one list for the first 2 fraction digits and one for the second 2 fraction digits. I encoded each number with a printable character. For decoding I simpy extract the ingerer and fraction parts of a number from the associated character lists and assemble them back to float. # [J](http://jsoftware.com/), 602 bytes + 0 [Penalty](https://tio.run/##hZVhbxs3DIa/@1ccAn@wk04RJVGi6nQo9i@Gphhc9JIZc@zMvqAohvz2jHdHUm6BYQWCnmSJIl9R7/Pcn/b49nHYnh77ofvQ/f1ttej4H0SHlVJM3iPEPM2F5JBKpFJlAl2sUCCVDNO4uhhCrnUakAuVPFQ/xwMXsg913ggcKSaIelQG8pjmUXEpBArzieAwJ0xejoNYfcllGhWXUw4R5adKWDLJyYCQSaJ7lyhnyjqK2fs5XQiu5pJlHbqCNQPMJyfHpeccJavsACIgBi9DzJCqfFMg2ZVdSVxL0UHOCJLsKCWQDKoPKRcdEYHXZTlWKlpgCTmSV2lrglpViVprbPGo1iRKVFdIiuVPDLEGvQCCSKCSc4DspYTkoBQIJLFzZcWKlRqA85DvHGPV@YJEKAn4GlKUb4AaNTEWG70qgCR7ycWoN1Ic31uISX7gsigESaQQXwAGjZXGbpN12VOkKmV6X7Pdb0KQdPl@IYxNPBcdWSbOHjFpoQEg5yQDTqPqZyRt8FSiTgZU8ZE0w5xiAf0uPoog3C6pki7nKvTEKQFZ4gPYal@0Z8DyZeUxAWpSKfDjA2s59JIuC5gqFm0gysnrTVCMoh5x/1GIKjKnqvOVbzGKjiEgYns2saC39vfc5XZIYt1K1QsMhPze9BxI2rBQpPs5WEkiTXK@hJK8lhUKpaB3wN0erNeil5fOCupTg5pMv5CxSYmmcGliV7D0q7w23kagWkd@/fqe7WHruqz5WsN7U1/11Xeqj3ex3rx9fO4P2/2w689sp6v1ZrF4OJ661fLAQ7/p@P87FoTGr5ubdfcP710Op5eef17ONvxpefi8GacfX/rzGOXuV47C46eX/ejR4K@v9/3hcfhztTo/73fD6vbe3b6bw6zXn@DzemNRrz/M@y4Ctqlx7uvu4YGDbr@cV/OOX2TdFGT3wKlPS@4673DOl3dZkWOyU2U8/9r1@3P/X0v2x0cJdd0lPgXWt@MU@Omg18XrYrE8vzx1N5zeH90oWpOSU30@7Q5Dd/X78eXUDcdhu@/mX793u/P7@8O49f5wf7ja6MrfTv32r6/Hb4fuy3dOrH/qD8P7acH/38gcgsfwrrv6qZQpxOvi7e1nRv7Ax0s2GhcbExsPjYWNg8bAxr/GPuOeMc9411hnnDPGXfDtgm0XXFOmKc@MZcoxY1jjl7LLuGXMarxqrDJOCaOMT8amCy4Zky54pCxSDimDlD/KHuWOMkd5Y6wxzjTGGF@MLcoVY8oFTy5ZYhwRhgg/ZnYIN2ZmKC@MFcoJYYTyQdggXFAmGA@MBcYBY4D6v3q/@r56vvq9eX3z@ebxzd/N22dfV09XP29ebj5uHi7@PXm3@rZ4tvi1eLX4tHi0@LN48@TLkydPfjx58eTDoweX6W96EP8C) = 602 ``` q=.'qy7?JOZp@''T1}Ciz={3L/0rHp/r}`M{m^ZHZSy55MYPBaNcV+\?A%/{eyQxQPkDs8W''@m$\6wZsV%KjI''_9"o\XMCP+vU=S3''c3\IKD@ovEW''4LX2O=>n&dgNktY><Ru_TvNpArL?}Y642=}5Hb"yYsD19$<OP2<|Jo)!8S`^9N3w{Q]968P2VF`[(2HOa%XL*V|,[8PcL)}w8"*l%JNC{amnCNx\yH73(pmJGCDq?8@D$ww{X`t0[o.`$''RB&eXiP|_u#9WBFS%U:3|O.U+is5E$A[c{1MpJ@Dw&^rpM_N:M^:o&!HPX9?0i}{j?%2W20z>Q?AOw!fuTWC"Q{-Er' f=:3 :0 a=.0$0 while.*#y do.l=.1+{.y a=.a,<' '-.~":}.l{.y y=.l}.y end.a ) echo;(('.',~":"0)&.>_40+a.i.'5@-103659=-/-02247,...../////1-/1135,-...////0/0-/0124+--------.--....-.///00012.//012,--.-...--......,..///'),.(f 12,10#.inv 94x#._32+a.i.q),.<CR ``` [Try it online!](https://tio.run/##Lc7ZcqJAFAbge5/CDdsFmmZTcERUNGOMIu7rqMRlglFBjSJB5tUdsPJfdHf93zlVvX08jiIERzsj1ZpjswBAl3Jl/Vt0mDqJTlWTPLmLhrOfjavjjs1xjZFa0pRlPzWVihjprO3WraV@ls/8AIDCPjpNW@NzH3vbvgIwF8LGdNiQ1dS1J3YYAJbM9PWtXDCuFW@YrQ/pppg/xFZ/lc@vUT7Xvsy7V8UsnuqSO0qztOhy1fewPTqXKSGaa6p07l4zEiG@s5gJCmM5rT9Cmlfp/stiEqerTQ0b1pP9Oz7h1WU94Vp8OLnDaorsaPuDrNymdjXDxM197bdcPkp8oRy1LGe4@EITAy6iALRLsfVQV@/zS0QYlF46WC/L3Juwl9LPXCVanCwdqmHWCmUrNjuZjbmSbcyyRixUVYeChHTX2UoYPaDRd74lFZtWaHPpDuRwyyEqJxDYiFkmmEUBTYQoioLWh75bw2TEDq4MuBMhlXKg7aOG50AQEPBfOOvCnV/aIty53r0@rKAWSATWyw/jVzwOIMC9oTBKxGB@zqKUBnUIuAJBISbNCSJBEoim2QwO/ZB@KIKkKIbDiZ8CkYggEUWzKeInkPANEj4j5JH38E7cF79/KoT4cx8kcBjfBD2mUATqh2tQYG8ROGfo51@OHufk9uPxHw "J – Try It Online") This time I went for a slightly different approach. I split the numbers to 2 streams - the first one contains the integer parts which are simply encoded with a single printable character. The second stream contains the entire fractional parts. I removed all intervals between the digits and prepended each substring with its length 1-9 (I tweaked the first fraction, wich is 13 digits long). Then I encoded this list as a base 94 number, presented it as a list of characters. About 20 bytes can be saved if the verb is rewriten as tacit one. ]
[Question] [ ### Definition Let's call an (infinite) integer sequence universal if it contains every finite integer sequence as a contiguous subsequence. In other words, the integer sequence **(a1, a2, …)** is universal if and only if, for each finite integer sequence **(b1, …, bn)**, there is an offset **k** such that **(ak+1, …, ak+n) = (b1, …, bn)**. The sequence of positive prime numbers, for example, is not universal, among others for the following reasons. * It doesn't contain any negative integers, **1**, or composite numbers. * Although it contains **3**, it does not contain the contiguous subsequence **(3, 3, 3)**. * Although it contains **2** and **5**, it does not contain the contiguous subsequence **(2, 5)**. * Although it contains the contiguous subsequence **(7, 11, 13)**, it does not contain the contiguous subsequence **(13, 11, 7)**. ### Task Pick *any* single universal integer sequence **(a1, a2, …)** and implement it in a programming language of your choice, abiding to the following rules. * You can submit a full program or a function. * You have three options for I/O: 1. Take no input and print or return the entire sequence. 2. Take an index **n** as input and print or return **an**. 3. Take an index **n** as input and print or return **(a1, …, an)**. * For I/O options *2* and *3*, you may use **0**-based indexing if you prefer. * Your submission must be deterministic: if run multiple times with the same input, it must produce the same output. In addition, unless it's immediately obvious, please prove that the sequence you picked is universal. Your proof may not depend on unproven conjectures. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. May the shortest code in bytes win! [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes This prints an infinite list ``` ΣṖ…ݱ ``` [Try it online!](https://tio.run/##ARQA6/9odXNr///Oo@G5luKApsSwwrH//w "Husk – Try It Online") or [find the first index of your sequence](https://tio.run/##ASAA3/9odXNr///igqzOo@G5luKApsSwwrH///9bMywtMSwwXQ). (Takes a lot of memory for most sequences) ### Explanation: ``` ݱ Infinite list [1,-1,2,-2,3,-3,4,-4,5,-5...] … Rangify [1,0,-1,0,1,2,1,0,-1,-2,...] Ṗ Powerset Σ Concatenate ``` In Husk `Ṗ` behaves nicely for infinite lists. You can see it's behaviour [here](https://tio.run/##yygtzv7//1HbREMDA4OHO6f5/f8PAA) [Answer] # [Python 2](https://docs.python.org/2/), ~~49~~ ~~46~~ 43 bytes ``` def f(n):d=len(`n`);return n/d**(n%d)%d-d/2 ``` `f(n)` returns **an** only. This uses the smallest digit of `n` in base `d` to extract one of the higher digits. [Try it online!](https://tio.run/##hVBBbsIwEDzjV6yQEHZwRBygDak40msP7Y0iEdUORMAmcoxqXk83prSqWqmRvLZ2Z2Zn0pzdrsb0ctGmhJKjyPXiYJBvcCMerHEni4BjHUUcB1oMdKzHacBuuRc562lYgEogiuBYeN6dwN5vBIxAQVlb2EOF4IVk8OcX8F3x4koSrIekmjDW@6av8jxWa1oYZggRaMLu6ZAhxn50r364hhjSoEjzWxTG3nfVwcCLPRlSc/bcaXpiV9icHBefG7p4ROsVbWusAwIsKGHDSwm2wK3hKGnfCK7GRcA2tkKC0kBC/xX7X4GNfzONg@XT49La2ua//oQtqtbA87l15rj0leMJ@bixwlXVCEULnefPPcOyoCA6h6EE/7@iEpdVsmarRCqZygm9JjJWctqVmYzn1Izv5Iz66b2SWZpJlaUym3adZB3NQ1VJuKbzDw "Python 2 – Try It Online") This script (courtesy of Dennis) takes any finite sequence and gives you an `n` where that sequence begins. ## Explanation ``` n/d**(n%d)%d-d/2 (n%d) least significant digit of n n/d**( )%d get n%d-th digit of n -d/2 offset to get negative values ``` For example, for `n` in the range `3141592650` to `3141592659`, `d=10` and the last digit of `n` selects one of the other digits. Then we add `-d/2` to get negative values. ``` n%d: 0 1 2 3 4 5 6 7 8 9 f(n)+d/2: 0 5 6 2 9 5 1 4 1 3 f(n): -5 0 1 -3 4 0 -4 -1 -4 -2 ``` Standalone alternative, also 43 bytes: ``` n=input();d=len(`n`);print n/d**(n%d)%d-d/2 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) 2, 11 bytes ``` ≜~×-₂ᵐ~ȧᵐ≜∋ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sWHNr5qHEDHJX/f9Q5p@7wdN1HTU0Pt06oO7EcSAKFHnV0//8PAA "Brachylog – Try It Online") I also tried an algorithm using additive partitions on a list, but it wasn't any shorter. This is a generator that produces an infinite stream of integers as output; the TIO link has a header to print the first ten thousand of them. ## Explanation The program starts off by trying all possible integers in sequence (`≜` tries all remaining possibilities, for integers by default). That's 0, 1, -1, 2, -2, etc. (although the negative integers don't reach the end of the program). This is the only "infinite" step of the program; all the others are finite. `~×` then generates all possible factorisations of the integer, treating different orders as different, and using only values from 2 upwards (so there are only finitely many); note that composite numbers are allowed in the factorisation, not just primes. This means that all possible sequences of integers ≥ 2 will be generated by this step at some point in the execution of the function (as such a sequence necessarily has some product, and that product will be generated at some point by the initial `≜`). We then need to map the set of those sequences onto the set of all integer sequences, which is done in two steps: subtracting 2 (`-₂`) from each element (`ᵐ`), giving us the set of all nonnegative integer sequences, then taking plus or minus (`~ȧ`, i.e. "a value whose absolute value is") each element (`ᵐ`). The latter step is obviously nondeterministic, so Brachylog treats it as a generator, generating all possible lists whose elements are plus or minus the corresponding element of the input list. This means that we now have a generator for all possible integer sequences, and it generates them in an order that means they're all generated (specifically, the order that you get if you take the absolute value of each element, add 2 to each element, and then order by the product of the resulting elements). Unfortunately, the question wants a single sequence, not a sequence of sequences, so we need two more commands. First, `≜` requests Brachylog to explicitly *generate* the sequence of sequences strictly (as opposed to producing a data structure describing the concept of a sequence generated via this method, and not actually generating the sequences until necessary); this both happens to make the program faster in this case, and ensures that the output is produced in the requested order. Finally, `∋` causes the generator to output the elements of the individual sequences one at a time (moving onto the next sequence once it's output all elements of the previous one). The end result: each possible integer sequence gets generated and output, one element at a time, and all concatenated together into a single universal sequence. [Answer] # Pyth - 11 bytes `n`th power cartesian product of `[-n, n]`, for all `n`. ``` .V1js^}_bbb ``` [Try it online here](http://pyth.herokuapp.com/?code=VQjs%5E%7D_NNN&input=4&debug=0) (finitely). [Answer] # [Python 2](https://docs.python.org/2/), ~~100~~ 99 bytes * Saved one byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs); iterating over an `itertools` built-in to indefinitely loop. ``` from itertools import* for n in count(): for P in permutations(range(-n,n)*n): for p in P:print p ``` [Try it online!](https://tio.run/##FcqxDYAwDATAGqZwmSBoKJkiKyAUwBJ5W8YUTB9Iezp9/RTMte4mhdizuch1ExcV86HfxQjEoE0eeIhLT41SI81WHl@dBXewFUcOE0bEAX/rWtPW0qLGcNJaPw "Python 2 – Try It Online") Indefinitely prints all permutations of the `n`-times repeated integer range `[-n; n)` for all nonnegative integers `n`. You can search for the first offset `k` for any subsequence using [this modified version](https://tio.run/##bY8xb8MgEIVn8ytOmUxiItzR6Dp2zlzLg1XhBhkfFIiqLv7rDibJVokB3vve3cP/paujty3qn5umLw0IvWgbkOW0A4vGakoA2fgYbdRbxH5QFrNav0JczbhKNgW3gEk6JOdsBLN4F9JREUr2e81jVtmxanIBLmAIvA7LLY3JOIp1GOlb14Ia4kfiGSuc37nL/qrMBOQSPNp0Ppjcye9GPKFv1HzC9onFXthuQHyVK/H/8kUvt8MMeGjEOgurPndZ28yXH/J328Wzd76WnFWU12zbHQ). [Answer] # [Perl 6](https://perl6.org), 91 bytes ``` loop (my$i=1;;$i++){my@n=(-$i..$i);my@m=@n;loop (my$k=1;$k <$i;$k++){@m=@m X@n;};print @m;} ``` [Try it online!](https://tio.run/##K0gtyjH7/z8nP79AQSO3UiXT1tDaWiVTW1uzOrfSIc9WQ1clU09PJVPTGsjNtXXIs4YrzQYqVclWsFHJBFIgDSD5XIUIoJpa64KizLwSBYdc69r//wE "Perl 6 – Try It Online") This uses a similar method to some of the other answers. It uses Cartesian products to print the elements of `(-1,0,1)`, then all ordered pairs of the elements in `(-2,-1,0,1,2)`, then all ordered triplets of the elements in `(-3,-2,-1,0,1,2,3)`, etc. I'm new to Perl, so there might be more golfing that could be done. More readable version: ``` loop (my $i = 1; ; $i++) { my @n = (-$i..$i); my @m = @n; loop (my $k=1; $k <$i; $k++) { @m = @m X @n; } print @m; } ``` ]
[Question] [ Every number can be represented using an infinitely long remainder sequence. For example, if we take the number 7, and perform `7mod2`, then `7mod3`, then `7mod4`, and so on, we get `1,1,3,2,1,0,7,7,7,7,....`. However, we need the *shortest* possible remainder subsequence that can still be used to distinguish it from all lower numbers. Using 7 again, `[1,1,3]` is the shortest subsequence, because all of the previous subsequences don't start with `[1,1,3]`: ``` 0: 0,0,0,0... 1: 1,1,1,1... 2: 0,2,2,2... 3: 1,0,3,3... 4: 0,1,0,4... 5: 1,2,1,0... 6: 0,0,2,1... ``` Note that `[1,1]` *doesn't* work to represent 7, because it can also be used to represent 1. However, you should output `[1]` with an input of 1. # Input/Output Your input is a non-negative integer. You must output a sequence or list of the minimal-length sequence of remainders as defined above. # Test cases: ``` 0: 0 1: 1 2: 0,2 3: 1,0 4: 0,1 5: 1,2 6: 0,0,2 7: 1,1,3 8: 0,2,0 9: 1,0,1 10: 0,1,2 11: 1,2,3 12: 0,0,0,2 30: 0,0,2,0 42: 0,0,2,2 59: 1,2,3,4 60: 0,0,0,0,0,4 257: 1,2,1,2,5,5 566: 0,2,2,1,2,6,6 1000: 0,1,0,0,4,6,0,1 9998: 0,2,2,3,2,2,6,8,8,10 9999: 1,0,3,4,3,3,7,0,9,0 ``` Here are the [first 10,000 sequences](https://gist.github.com/nathanmerrill/6238c8eed102f15f794d96a481473567), in case you are interested (the line numbers are off by 1). This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make it as short as you can in your favorite language. Fake bonus points for any answers that are fast! [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘Ræl\>iṠ2»2r⁸% ``` This uses the fact a the solution (if any) of a system of linear congruences is unique modulo the LCM of the moduli. [Try it online!](http://jelly.tryitonline.net/#code=4oCYUsOmbFw-aeG5oDLCuzJy4oG4JQ&input=&args=OTk5OQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4oCYUsOmbFw-aeG5oDLCuzJy4oG4JQrDh-KCrEc&input=&args=MCwgMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTAsIDExLCAxMiwgMzAsIDQyLCA1OSwgNjAsIDI1NywgNTY2LCAxMDAwLCA5OTk4LCA5OTk5). ### How it works ``` ‘Ræl\>iṠ2»2r⁸% Main link. Argument: n ‘ Increment; yield n+1. R Range; yield [1, ..., n+1]. æl\ Cumulatively reduce by LCM. This yields [LCM(1), ..., LCM(1, ..., n+1)]. > Compare all LCMs with n. iṠ Find the first index of sign(n). This yields the first m such that LCM(2, ..., m) > n if n > 0, and 0 if n == 0. 2» Take the maximum of the previous result and 2, mapping 0 to 2. 2r Yield the range from 2 up to and including the maximum. ⁸% Compute n modulo each integer in that range. ``` [Answer] ## Mathematica, ~~60~~ 53 bytes ``` #~Mod~FirstCase[2~Range~#&/@Range[#+2],x_/;LCM@@x>#]& ``` *Somewhat* fast (it handles 10000 in ~0.1 second, but will likely run out of memory for 100000). The code throws an error but computes the result correctly. ### Explanation We've found earlier in chat that the required divisors can always be determined as the shortest list `{1, 2, ..., n}` whose least common multiple exceeds the input. A short argument for why that is: if the LCM is less than the input, then subtracting the LCM from the input would leave all the divisors unchanged, so the representation is not unique. However, for all inputs less than the LCM, the remainders will be unique, otherwise the difference between two numbers with equal remainders would be a smaller multiple of all divisors. As for the code... as usual the reading order of golfed Mathematica is a bit funny. ``` Range[#+2] ``` This gets us a list `[1, 2, 3, ..., n+2]` for input `n`. The `+2` is to ensure that it works correctly for `0` and `1`. ``` 2~Range~#&/@... ``` Map `2~Range~#` (syntactic sugar for `Range[2,#]`) over this list, so we get ``` {{}, {2}, {2,3}, ..., {2,3,...,n+2}} ``` These are candidate divisor lists (of course in general that's a lot more than we'll need). Now we find the first one of them whose LCM exceeds the input with: ``` FirstCase[...,x_/;LCM@@x>#] ``` More syntax: `x_` is a pattern which matches any of the lists and calls it `x`. The `/;` attaches a condition to that pattern. This condition is `LCM@@x>#` where `@@` *applies* the function to the list, i.e. `LCM@@{1,2,3}` means `LCM[1,2,3]`. Finally we simply get all the remainders, making use of the fact that `Mod` is `Listable`, i.e. it automatically maps over a list if one of the arguments is a list (or if both of them are lists of the same length): ``` #~Mod~... ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes *Thanks to @nimi for pointing out an error in a previous version of this answer (now corrected)* ``` Q:qtQ!\t0Z)tb=YpsSP2):Q) ``` This runs out of memory in the online compiler for the two largest test cases (but it works on a computer with 4 GB RAM). [**Try it online!**](http://matl.tryitonline.net/#code=UTpxdFEhXHQwWil0Yj1ZcHNTUDIpOlEp&input=MjU3) ### Explanation This applies the definition in a straightforward manner. For input `n` it computes a 2D array containing `mod(p,q)` with `p` from `0` to `n` and `q` from `1` to `n+1`. Each `p` is a column, and each `q` is a row. For example, with input `n=7` this array is ``` 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 1 2 0 1 2 0 1 0 1 2 3 0 1 2 3 0 1 2 3 4 0 1 2 0 1 2 3 4 5 0 1 0 1 2 3 4 5 6 0 0 1 2 3 4 5 6 7 ``` Now the last column, which contains the remainders of `n`, is element-wise compared with each column of this array. This yields ``` 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 ``` where `1` indicates equality. The last column is obviously equal to itself and thus contains all ones. We need to find the column that has the *largest number of initial ones*, other than the last column, and take note of that number of initial ones, `m`. (In this case it's the second column, which contains `m=3` initial ones). To this end, we compute the cumulative product of each column: ``` 1 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 ``` then the sum of each column ``` 1 3 1 2 1 2 1 8 ``` and then sort non-increasingly and take the second value, which is `3`. This is the desired `m`, which indicates how many remainders we need to pick. ``` Q:q % take input n implicitly. Generare row array [0 1 ... n] tQ! % duplicate. Transform into column array [1; 2; ...; n-1] \ % modulo, element-wise with broadcast. Gives the 2D array t0Z) % duplicate. Take last column tb % duplicate, bubble up = % test for equality, element-wise with broadcast Yp % cumumative product of each column s % sum of each column. This gives the number of initial coincidences SP2) % sort in decreasing order and take second value: m :Q % generate range [2 3 ... m+1] ) % apply as index into array of remainders of n. Implicitly display ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` r¬µ%€R‘$ḟ/Ṫ ``` This won't win any velocity brownie points... [Try it online!](http://jelly.tryitonline.net/#code=csKswrUl4oKsUuKAmCThuJ8v4bmq&input=&args=NjA) or [verify the smaller test cases](http://jelly.tryitonline.net/#code=csKswrUl4oKsUuKAmCThuJ8v4bmqCsOH4oKsRw&input=&args=MCwgMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTAsIDExLCAxMiwgMzAsIDQyLCA1OSwgNjAsIDI1Nw). ### How it works ``` r¬µ%€R‘$ḟ/Ṫ Main link. Argument: n r¬ Range from n to (not n). This yields [n, ..., 0] if n > 0 and [0, 1] otherwise. µ Begin a new, monadic chain. Argument: A (range) $ Combine the previous two links into a monadic chain: R Range; turn each k in A into [1, ..., k] or [] if k == 0. ‘ Increment to map k to [2, ..., k+1]. %€ Take each k in A modulo all the integers in the 2D list to the right. ḟ/ Reduce by filter-not; sequentially remove all remainder sequences of n-1, ..., (not n) from the remainder sequences of n. Ṫ Tail; take the last remainder sequence. This gives the shortest sequence for descending A and the longest one (i.e., [0]) for ascending A. ``` [Answer] # Python 3.5, 117 95 78 bytes ``` import sympy r=lambda n,m=2,M=1,*l:M>n and l or r(n,m+1,sympy.lcm(m,M),*l,n%m) ``` Requires Python 3.5 and sympy (`python3 -m pip install --user sympy`). Credit to @Dennis to notify me that Python 3.5 allows the `*l` trick with default arguments. [Answer] # Python 2, 73 70 69 65 bytes ``` i=l=1 n=input() while l<=n|1: i+=1;a=l;print n%i while l%i:l+=a ``` A full program. @Dennis saved 4 bytes by improving the way zero is handled. [Answer] ## Haskell, ~~66~~ ~~60~~ ~~51~~ 50 bytes ``` f i=mod i<$>[2..2+sum[1|l<-scanl1 lcm[2..i],l<=i]] ``` Usage example: `f 42`-> `[0,0,2,2]`. It's the algorithm described in [@Martin Büttner's answer](https://codegolf.stackexchange.com/a/77786/34531). I'll keep the previous version for reference, because it's pretty fast: ### Haskell, 51 bytes ``` f i=mod i<$>[[2..x]|x<-[2..],foldl1 lcm[2..x]>i]!!0 ``` It takes 0.03s for `f (10^100)` on my five year old laptop. Edit: @xnor found a byte to save. Thanks! [Answer] # Pyth, ~~51 Bytes~~ 66 Bytes ``` IqQZ[Z).q)IqQ1[1))IqQ2,0 1))FdhhQJu/*GHiGHtUd1I>JQVQ aY%QhN)<tYd.q ``` [Try it out!](http://pyth.herokuapp.com/?code=IqQZ[Z%29.q%29IqQ1[1%29%29IqQ2%2C0+1%29%29FdhhQJu%2F*GHiGHtUd1I%3EJQVQ+aY%25QhN%29%3CtYd.q&input=10&debug=0) **Much** higher speed 39 byte version (does not work for 0-2): ``` FdhhQJu/*GHiGHtUd1I>JQVtd aY%QhN)<tYd.q ``` It seems to work for absurdly large numbers like 10103 ~~Note: this answer does not work for 0, 1, and 2.~~ Fixed! [Answer] ## JavaScript (ES6), ~~81~~ 77 bytes ``` f=(n,r=[n%2],l=i=2,g=(j,k)=>j?g(k%j,j):k)=>l>n?r:f(n,[...r,n%++i],i/g(i,l)*l) ``` This recursively builds up the answer until the LCM exceeds the original number. The GCD is also calculated recursively, of course. Edit: Saved 4 bytes thanks to @user81655. [Answer] # Ruby, 52 bytes ``` ->n{m=t=1;a=[];(a<<n%m)until n<t=t.lcm(m+=1);a<<n%m} ``` This solution checks every possible `m` starting from 2 that be the remainder that makes the sequence unique. What makes the last `m` unique is not the remainder itself, but that the `m` is the last member of the smallest range `(2..m)` where the least common multiple (LCM) of that range is greater than `n`. This is due to the Chinese Remainder Theorem, where to uniquely determine what number `n` is with a number of remainders, the LCM of those remainders must be greater than `n` (if selecting `n` from `(1..n)`; if selecting `n` from `a..b`, the LCM needs only be greater than `b-a`) **Note:** I put `a<<n%m` at the end of the code because `until n<t=t.lcm(m+=1)` short-circuits before `a` has received the last element to make it unique. If anyone has any golfing suggestions, please let me know in the comments or in [PPCG chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte). **Ungolfing:** ``` def remainder_sequence(num) # starting with 1, as the statements in the until loop immediately increments divisor divisor = 1 # starts with 1 instead of 2, as the statements in the until loop # immediately change product to a new lcm product = 1 remainders = [] # this increments divisor first then checks the lcm of product and divisor # before checking if num is less than this lcm until num < (product = product.lcm(divisor = divisor + 1)) remainders << num % divisor end # until always short circuits before the last element is entered # so this enters the last element and returns return remainders << num % divisor end ``` [Answer] # Julia, ~~36~~ 33 bytes ``` \(n,k=2)=lcm(2:k)>n?n%(2:k):n\-~k ``` [Try it online!](http://julia.tryitonline.net/#code=XChuLGs9Mik9bGNtKDI6ayk-bj9uJSgyOmspOm5cLX5rCgpmb3Igbj1bMCAxIDIgMyA0IDUgNiA3IDggOSAxMCAxMSAxMiAzMCA0MiA1OSA2MCAyNTcgNTY2IDEwMDAgOTk5OCA5OTk5XQogICAgQHByaW50ZigiJTRkOiAlc1xuIixuLCBcKG4pKQplbmQ&input=) [Answer] # Python 3.5, 194 181 169 152 149 146 bytes: (*Thanks to @Sherlock9 for 2 bytes!*) ``` def r(o,c=0): y=[[j%i for i in range(2,100)]for j in range(o+1)] while 1: c+=1;z=y[-1][:c] if z not in[f[:c]for f in y[:-1]]:break print(z) ``` Works perfectly, and is also pretty quick. Calculating for the minimal remainder sequence of `100000` outputs `[0, 1, 0, 0, 4, 5, 0, 1, 0, 10, 4, 4]` and took only about 3 seconds. It was even able to calculate the sequence for the input `1000000` (1 million), output `[0, 1, 0, 0, 4, 1, 0, 1, 0, 1, 4, 1, 8, 10, 0, 9]`, and took about 60 seconds. # Explanation Basically what this function does is firstly create a list, `y`, with all `j mod i` where `j` is every integer in the range `0=>7` (including 7) and `i` is every integer in the range `0=>100`. The program then goes into an infinite `while` loop and compares the same number of contents of each sublist within the first through second-to-last sublists of `y` (`y[:-1:]`) with the same number of items in the last sublist (`y[-1]`) of list `y`. When sublist `y[-1]` is *different* than any other sublist, the loop is broken out of, and the correct minimal remainder sequence is returned. For instance, if the input is 3, `y` would be: ``` [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [1, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]] ``` Then, when it enters into the while loop, it compares each sublist in list `y[:-1:]` with the same number of items in sublist `y[-1]`. For example, it would first compare `[[0],[1],[0]]` and `[1]`. Since the last sublist is in the rest of `y`, it would continue on and then compare `[[0,0],[0,1],[0,2]]` and `[1,0]`. Since `[1,0]` is now NOT in the rest of `y` *in that specific order*, that is the minimal reminder sequence, and therefore, `[1,0]` would be correctly returned. [Answer] # C89, 105 bytes ``` g(a,b){return b?g(b,a%b):a;}main(n,m,M){scanf("%d",&n);for(m=M=1;(M=++m*M/g(m,M))<=n;)printf("%d ",n%m);} ``` Compiles (with warnings) using `gcc -std=c89`. Takes a single number on stdin, and outputs the sequence of remainders separated by spaces on stdout. [Answer] # C, 89 bytes ``` a,i=2;main(l,n){for(n=atoi(gets(n))?:!puts(n);n/l;printf("%d ",n%i++))for(a=l;l%i;l+=a);} ``` Compile with gcc. Try it online: [n=59](http://ideone.com/R3M78D), [n=0](http://ideone.com/tsEDOl). ]
[Question] [ A Caesar shift is probably something we're all familiar with. (You might be even doing it as a homework task. If so, please don't copy these answers, your teacher almost certainly doesn't want anything like the answers here.) Just in case you aren't, a Caesar shift is a very simple form of cipher. It takes a string to be ciphered and an integer. Then for every alphabetical character in the string, perform the following transformation: 1. Work out the character's position in the alphabet (0 based). 2. Add to that number the integer received at the beginning. 3. While the number is bigger than 25, subtract 26 from it. 4. Work out the position of the alphabet it is in. Leave the rest of the characters unshifted. Capital letters have to be respected because what is English without capital letters? Examples: ``` abcdefghijklmnopqrstuvwxyz 1 -> bcdefghijklmnopqrstuvwxyza Spam spam spam sausage and spam! 13 -> Fcnz fcnz fcnz fnhfntr naq fcnz! abcdefghijklmnopqrstuvwxyz 52 -> abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz -1 -> zabcdefghijklmnopqrstuvwxy ABCxyz 3 -> DEFabc ``` ## Assumptions * You may receive any printable ASCII character * The input number can be negative and will always be bigger than -128 and less then 128 (`-128<x<128`) * You must be able to encode capital letters and non-capital letters reversibly. * You must create a full program, not just a function or snippet * You will get your input from STDIN or closest alternate * You may choose the format for your input, please state this in your answer * The characters that need to be shifted are ASCII codepoints `0x41 - 0x5A` and `0x61-0x7A` - upper and lower case letters + Upper case letters should stay upper + Lower case letters should stay lower + Characters not in this range should be left as they are * Note for this challenge, you only have to cipher strings, you don't have to be able to solve them automatically (but giving `-x` will reverse the cipher) Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8). ## Catalog The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [<><](https://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 67044; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 32686; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # Pyth, 13 bytes ``` uXGH.<HQrBG1z ``` [Test suite](https://pyth.herokuapp.com/?code=uXGH.%3CHQrBG1z&input=abcdefghijklmnopqrstuvwxyz&test_suite=1&test_suite_input=abcdefghijklmnopqrstuvwxyz%0A1%0ASpam+spam+spam+sausage+and+spam%21%0A13%0Aabcdefghijklmnopqrstuvwxyz%0A52%0Aabcdefghijklmnopqrstuvwxyz%0A-1%0AABCxyz%0A3&debug=0&input_size=2) Basically, we start with the two strings we want to caesar shift, the lowercase and uppercase alphabets. The list containing both of these is generated by `rBG1`, bifurcate on uppercase. Then, we reduce over this list, starting with the input string and translating first lowercase, then uppercase letters by the appropriate shift. [Answer] # Pyth, 16 ``` XXzG.<GQJrG1.<JQ ``` [Try it online](http://pyth.herokuapp.com/?code=XXzG.%3CGQJrG1.%3CJQ&input=abc%2Cxyz%20123%0A3&debug=0) or run a [Test Suite](http://pyth.herokuapp.com/?code=XXzG.%3CGQJrG1.%3CJQ&input=abc%2Cxyz%20123%0A3&test_suite=1&test_suite_input=abcdefghijklmnopqrstuvwxyz%0A1%0Aabcdefghijklmnopqrstuvwxyz%0A52%0Aabcdefghijklmnopqrstuvwxyz%0A-1%0AABCxyz%0A3%0Aabc%20123%2C%3C%3E%21A%20more%20elegant%20weapon%2C%20from%20a%20more%20civilized%20age%21%40%23%0A999&debug=0&input_size=2) [Answer] # Bash + bsd-games package, 21 ``` caesar $[($1+130)%26] ``` Builtins FTW! Almost feels like Mathematica. Pyth answers are still shorter though. Input string read from STDIN and integer from command-line. e.g.: ``` $ ./caesar.sh 13 <<< "Spam spam spam sausage and spam!" Fcnz fcnz fcnz fnhfntr naq fcnz! $ ``` --- Or if you don't like the builtin: # Bash + coreutils, 63 ``` printf -va %s {a..z} t=${a:$1%26}${a:0:$1%26} tr A-Z$a ${t^^}$t ``` [Answer] # JavaScript (ES6), ~~122~~ ~~118~~ ~~114~~ 111 bytes ``` alert((p=prompt)().replace(/[a-z]/gi,c=>String.fromCharCode((x=c.charCodeAt(),a=x&96,x-a+n+129)%26-~a),n=+p())) ``` *Saved 4 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!* ## Explanation First prompt takes the input string. The second is the number to shift each letter by. ``` alert( (p=prompt)() // get input string .replace(/[a-z]/gi,c=> // for each letter String.fromCharCode(( x=c.charCodeAt(), // x = code of character a=x&96, // a = index of letter a (-1) in same capitalisation x-a+n+129)%26-~a // add N to the letter code and wrap at 26 ), // (+129 is needed to make the % work with negative numbers) n=+p() // get number to shift by ) ) ``` [Answer] ## CJam, ~~34~~ ~~22~~ ~~21~~ 20 bytes *Thanks to FryAmTheEggman for saving 1 byte.* ``` l'[,_el^_26/l~fm<ser ``` [Test it here.](http://cjam.aditsu.net/#code=l'%5B%2C_el%5E_26%2Fl~fm%3Cser&input=abcdefghijklmnopqrstuvwxyzABCDEF%3D-1231294810%20asd%20!%0A-3) Input is the string to be shifte on the first line and the shift on the second. ### Explanation ``` l e# Read the first line of input. '[, e# Push a string with all ASCII characters up to and including Z. _el e# Duplicate and convert to lower case. This only affects the letters. ^ e# Symmetric set-difference: except for the letters, each character appears in both e# sets and will be omitted from the difference, but all the letters will be included. e# This gives us "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz". _26/ e# Duplicate and split into chunks of 26 characters, separating lower and upper case. l~ e# Read the second line of input and evaluate. fm< e# Shift each of the two substrings by that many characters to the left. s e# Convert to a single string, joining both substrings back together. e# On the stack are now the input, the letters in alphabetical order and the letters e# in shifted order. er e# Character transliteration: replace each occurrence of a letter with the character e# at the corresponding position in the shifted string. ``` [Answer] # Java, 249 Bytes This is as short as I could get it. Reading from stdin eats a ton of bytes. A solution using command line args is noticeably shorter but, this task specified stdin for input. Input format is the String first followed by the shift number on a new line. ``` interface C{static void main(String[]a){java.util.Scanner r=new java.util.Scanner(System.in);String s=r.nextLine();int i=(r.nextInt()+26)%26;s.chars().forEach(c->System.out.print((char)(c>64&c<91|c>96&c<123?c<91?65+(c+i-65)%26:97+(c+i-97)%26:c)));}} ``` Using command line Arguments this solution is only 188 bytes. Input is the String as the first argument and the shift as the second. ``` interface C{static void main(String[]a){int i=(Integer.parseInt(a[1])+26)%26;a[0].chars().forEach(c->System.out.print((char)(c>64&c<91|c>96&c<123?c<91?65+(c+i-65)%26:97+(c+i-97)%26:c)));}} ``` [Answer] ## R, 111 bytes ### code ``` n=scan();s=scan(,"");for(l in as.numeric(sapply(s,charToRaw))){v=97;if(l<97)v=65;cat(intToUtf8((l+n-v)%%26+v))} ``` ### ungolfed ``` n <- scan() # input integer s <- scan(,"") # input string letter by letter z <- as.numeric(sapply(s,charToRaw)) # get ASCII index of character for (l in z){ # loop through chars v=97 # base index of not capitalized chars if(l<97)v=65 # base index of capitalized chars cat(intToUtf8((l+n-v)%%26+v)) # paste the char of the shifted index } ``` This program takes the user input from STDIN, first the integer shifter and then the string, character by character. [Answer] ## Perl, 81 bytes (+1 for the `-p` flag) ``` s/[^ ]+ //;$n=$&%26;eval"y/a-zA-Z/".($x=chr(97+$n)."-za-".chr$n+96).uc$x."/"if$n ``` Still working on golfing it down... Test: ``` llama@llama:...code/perl/ppcg67044caesar$ printf '1 abcdefghijklmnopqrstuvwxyz\n13 Spam spam spam sausage and spam!\n52 abcdefghijklmnopqrstuvwxyz\n-1 abcdefghijklmnopqrstuvwxyz\n3 ABCxyz' | perl -p caesar.pl; echo bcdefghijklmnopqrstuvwxyza Fcnz fcnz fcnz fnhfntr naq fcnz! abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxy DEFabc ``` [Answer] # Japt, ~~45~~ 43 bytes ``` Ur"[^\\W_]"_c +V+#¶-(A=Zc <#a?#A:#a)%26+A d ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VXIiW15cXFdfXSJfYyArVisjti0oQT1aYyA8I2E/I0E6I2EpJTI2K0EgZA==&input=IlVyeXliLCBKYmV5cSEiIDEz) [Answer] ## Python 2, ~~163~~ 160 bytes Not sure if I can still golf it down.. ``` import sys;k=sys.argv def f(x,n):r=chr((ord(x.lower())-97+n)%26+97);return(x,[r,r.upper()][x.isupper()]) print''.join(f(x,int(k[2]))[x.isalpha()] for x in k[1]) ``` Since it's pretty unreadable, here is an ungolfed version: ``` import sys def shift(x,n): # shift character x by n (all in lowercase) r = chr((ord(x.lower())-97+n)%26+97) if x.isalpha() and x.islower(): return r elif x.isalpha() and x.isupper(): return r.upper() else: return x # 'map' the function shift to each character of the input output = ''.join(shift(x,int(sys.argv[2])) for x in sys.argv[1]) print(output) ``` Concerning the input: It expects two arguments, the first must be a string and the second an integer (the shift amount). Examples (file is called `csr.py`): ``` $ python csr.py gnu 9 pwd $ python csr.py "Spam spam spam sausage and spam\!" 13 Fcnz fcnz fcnz fnhfntr naq fcnz! ``` Note: In the second example an escape character and `""` are needed [Answer] ## Python 2, ~~118~~ 116 bytes ``` s,n=input() print''.join([[c,chr((ord(c)-97+n)%26+97)]['`'<c<'{'],chr((ord(c)-65+n)%26+65)]['@'<c<'[']for c in s) ``` [Answer] ## Mathematica, 117 bytes ``` Echo[InputString[]~StringReplace~Thread[Join[a=Alphabet[],b=ToUpperCase@a]->(c=RotateLeft)[a,d=Input[]]~Join~c[b,d]]] ``` Takes the string, followed by a newline, followed by the shifting factor. Might still be golfable... [Answer] # [Perl 6](http://perl6.org), 73+1 = 74 bytes ``` $ perl6 -pe 's:g:i/<[a..z]>/{chr ((my$o=ord ~$/)-(my$a=$o+&96+1)+BEGIN get%26)%26+$a}/' # 73+1 ``` The first line of input is the number of characters to shift the letters up by. Usage: ``` $ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \ '1 abcdefghijklmnopqrstuvwxyz' bcdefghijklmnopqrstuvwxyza ``` ``` $ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \ '13 Spam spam spam sausage and spam!' Fcnz fcnz fcnz fnhfntr naq fcnz! ``` ``` $ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \ '52 abcdefghijklmnopqrstuvwxyz' abcdefghijklmnopqrstuvwxyz ``` ``` $ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \ '-1 abcdefghijklmnopqrstuvwxyz' zabcdefghijklmnopqrstuvwxy ``` ``` $ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \ '3 ABCxyz' DEFabc ``` ``` $ perl6 -pe 's:g:i/<[a..z]>/{...}/' <<< \ '1000000000000000000000000000000000000000 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ' mnopqrstuvwxyzabcdefghijkl MNOPQRSTUVWXYZABCDEFGHIJKL ``` [Answer] # C++, ~~163~~ ~~154~~ 152 bytes ``` #include<cstdio> #include<cstdlib> int main(int x,char**a){for(int c,b,s=atoi(a[1]);1+(c=getchar());putchar(c<b|c>b+26?c:(c+s-b+26)%26+b))b=c<97?65:97;} ``` Usage: ``` $ ./caesar -1 <<< "123 a A z Z aBcDeFgHiKlMnOpQrStUvWxYz" 123 z Z y Y zAbCdEfGhJkLmNoPqRsTuVwXy ``` [Answer] ## k4, 80 bytes The program accepts the shift number as a command-line argument and reads text from stdin. Due to a technical constraint, negative shifts must be encoded with an underscore instead of a hyphen-minus. (Without the parser for interpreting this encoding, the solution would be 64 bytes.) ``` % wc -c c.k 80 c.k % cat c.k c:{x;,/x{y!(x_y),x#y}'.Q`a`A} .z.pi:{1@x^c[.q.mod[.*{x^((!).$"_-")x}.z.x]26]x;} % ``` Here's the examples executed: ``` % echo abcdefghijklmnopqrstuvwxyz|q c.k 1 bcdefghijklmnopqrstuvwxyza % echo 'Spam spam spam sausage and spam!'|q c.k 13 Fcnz fcnz fcnz fnhfntr naq fcnz! % echo abcdefghijklmnopqrstuvwxyz|q c.k 52 abcdefghijklmnopqrstuvwxyz % echo abcdefghijklmnopqrstuvwxyz|q c.k _1 zabcdefghijklmnopqrstuvwxy % echo ABCxyz|q c.k 3 DEFabc % ``` And here's a silly little test harness that verifies both encode and decode. (This is `zsh`; for `bash` or `ksh`, change the `for` loop indexing to `((i=0;i<5;i++))`. One-based arrays, ugh....) ``` % a=(abcdefghijklmnopqrstuvwxyz 'Spam spam spam sausage and spam!' abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ABCxyz) % b=(1 13 52 _1 3) % c=(bcdefghijklmnopqrstuvwxyza 'Fcnz fcnz fcnz fnhfntr naq fcnz!' abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxy DEFabc) % for ((i=1;i<=5;i++)) for> do for> r=$(echo "${a[i]}"|q c.k "${b[i]}") for> s=$(echo "$r"|if [[ ${b[i]} == _* ]]; then q c.k "${b[i]/_}"; else q c.k "_${b[i]}"; fi) for> printf '%s\t%s\n' "$([[ ${c[i]} == $r ]] && echo good || echo bad)" "$([[ ${a[i]} == $s ]] && echo good || echo bad)" for> done good good good good good good good good good good % ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 2 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ç' ``` [Run and debug it](https://staxlang.xyz/#p=8727&i=%22abcdefghijklmnopqrstuvwxyz%22+1%0A%22Spam+spam+spam+sausage+and+spam%21%22+13&m=2) ]
[Question] [ Given a real number `t` in `(-10^9,13)` (not including `-10^9` or `13`) as input, output `Γ(t)`, also known as the [Gamma function](https://en.wikipedia.org/wiki/Gamma_function), which is defined as follows: [![gamma function definition](https://upload.wikimedia.org/math/6/0/3/603515ff4df2cb431387e92bb6419c66.png)](https://upload.wikimedia.org/math/6/0/3/603515ff4df2cb431387e92bb6419c66.png) You may not use a built-in Gamma function to solve this task, nor may you use built-in numeric or symbolic integration functions. Your output should be accurate to 6 significant figures or within `10^-6` of the actual value, whichever is less restrictive for the given value. Python's built-in Gamma function will be used for determining the actual value. You may assume `Γ(t)` is defined - that is, `t` is either a positive real number or a non-integer negative real number - and that `|Γ(t)| ≤ 10^9`. [Here](http://ideone.com/fork/cvDdYR) is a reference program that you may use to get the actual values, using Python's built-in Gamma function. ### Examples ``` 1 -> 1.000000 -2.5 -> -0.945309 3.14159265 -> 2.288038 -2.71828182846 -> -0.952682 12 -> 39916800.000000 0.5 -> 1.772454 8.675309 -> 20248.386956 -10.1 -> -0.000002 ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins. * Standard loopholes are forbidden. * Input and output may be performed in whatever manner is considered standard for your language. * You may write a full program, a function, or anything that is normally considered a valid answer for your language # Leaderboard The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` <style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 63887; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script> ``` [Answer] # C++14, ~~86~~ ~~85~~ 81 bytes ``` [](auto t){auto v=1.;for(int x=1;x<1e9;++x)v*=pow(1+1./x,t)/(1+t/x);return v/t;}; ``` I didn't spend much time on this one. I just looked an approximation that seemed the easiest to implement (in the manner of bytes). It will take some time to compute the value (since the loop is over all positive integers), but time limitation is not specified in the challenge. It is anonymous function (lambda), which takes any argument (convertible to `T` on which `pow(double, T)` and `operator/(T, int)` can be called) and returns `double`. Ungolfed with usage ``` #include <iostream> int main() { auto r = [](auto t) { auto v = 1.; for (int x = 1; x < 1e9; ++x) v *= pow(1 + 1. / x, t) / (1 + t / x); return v / t; }; std::cout << r(-2.71828182846); // outputs -0.952682 } ``` [Answer] ## [Minkolang 0.12](https://github.com/elendiastarman/Minkolang), ~~35~~ ~~34~~ 25 bytes ``` n$zl8;dz;z$:r[i1+dz+$:*]N ``` This does halt with an error (on trying to divide by 0), but that is allowed as per [Meta consensus](http://meta.codegolf.stackexchange.com/a/4781/12914). Add a `.` at the end for a program that halts normally. [Try all test cases at once.](http://play.starmaninnovations.com/minkolang/?code=%28n%24zl4%3Bdz%3Bz%24%3Ar%5Bi1%2Bdz%2B%24%3A*%5DNlO%24I%29%2E&input=1%0A-2%2E5%0A3.14159265%0A-2.71828182846%0A12%0A0.5%0A8.675309%0A-10.1) (The loop iterates only 1e4 times so it would finish sooner rather than later.) ### Explanation Zereges used one of the [alternative, infinite product definitions](https://en.wikipedia.org/wiki/Gamma_function#Alternative_definitions). As it turns out, the other is much more amenable to implement in Minkolang. [![Euler's alternative formulation of the gamma function](https://i.stack.imgur.com/8Kwcf.gif)](https://i.stack.imgur.com/8Kwcf.gif) This is a limit as `n` goes to infinity, which means that I can calculate both `n!` and `(t+n)` as I go. So I take out `1/t` (because `0!=1`) and `n^t` because that one cannot be calculated sequentially without knowing the ending value of `n`. As it happens, because `n` is the limit, I can use it twice. Once as a factor in the calculation and once as the number of times to run the loop. An sequential infinite product has to start with something, usually 1. In this case, it's `n^t/t`. In the body of the loop, I calculate `k/(t+k)` and multiply this with the product so far. At the end, the whole product has been calculated and output. This is essentially what my program does, with `n` high enough that the answer is precise enough. [![exploded version of the infinite product](https://i.stack.imgur.com/SMTIL.gif)](https://i.stack.imgur.com/SMTIL.gif) ``` n Take number from input $z Store it in the register (this is t; retrieved with z) l8; 10^8 (this is n, the limit) d n,n z; n,n^t z$: n,n^t/t r Reverse stack -> n^t/t,n [ For loop that runs n times i1+ k d k,k z+ k,t+k $: k/(t+k) * Multiply ]N Close for loop and output as integer ``` As there is no `.`, it wraps around and starts over. However, `n` now produces `-1` because the input is empty, which eventually leads to attempting to divide by 0, which halts the program. [Answer] # Julia, 141 bytes ``` z->(z-=1;a=90;c(k)=(k=big(k);(-1)^(k-1)/factorial(k-1)*(a-k)^(k-.5)*exp(a-k));(z+a)^(z+.5)*exp(-z-a)*(√(2π)+sum([c(k)/(z+k)for k=1:a-1]))) ``` This creates an unnamed lambda function that accepts a real number and returns a real number. It uses [Spounge's approximation](https://en.wikipedia.org/wiki/Spouge%27s_approximation) to compute Gamma. Ungolfed: ``` function Γ(z::Real) # Spounge's approxmation is for Γ(z+1), so subtract 1 z -= 1 # Choose a number for the constant a, which determines the # bound on the error a = 90 # Define a function for the sequence c_k function c(k::Integer) # Convert k to a BigInt k = big(k) return (-1)^(k-1) / factorial(k-1) * (a-k)^(k-1/2) * exp(a-k) end # Compute the approximation return (z+a)^(z+1/2) * exp(-z-a) * (√(2π) + sum([c(k)/(z+k) for k=1:a-1])) end ``` [Answer] # Pyth, 21 bytes As with my TI-BASIC answer, I haven't been able to test this with the full 8^10 iterations, but everything seems good with smaller cases. ``` cu*Gc^hc1HQhcQHS^8T1Q ``` Explanation: ``` [implicit: Q=input] ^8T 8**10 S^8T [1,2,3,...,8**10] *Gc^hc1HQhcQH lambda G,H:G*(1+1/H)**Q/(1+Q/H) 1 Base case u*Gc^hc1HQhcQHS^8T1 Reduce with base case 1 c Q Divide by Q ``` Try it [here](https://pyth.herokuapp.com/?code=cu%2aGc%5Ehc1HQhcQHS2000+1Q&input=1%0A-2.5%0A3.14159265%0A-2.71828182846%0A12%0A0.5%0A8.675309%0A-10.1&test_suite=1&test_suite_input=1%0A-2.5%0A3.14159265%0A-2.71828182846%0A12%0A0.5%0A8.675309%0A-10.1&debug=0) with 2000 iterations instead of 8^10. [Answer] # Japt, 45 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` $for(V=X=1;X<1e9;)$V*=(1+1/X pU /(1+U/X++;V/U ``` Of course, 1e9 = 1,000,000,000 iterations takes forever, so for testing, try replacing the `9` with a `6`. (1e6 is accurate to ~5 significant figures. Using 1e8 on an input of `12` is enough to get the first six.) Test-case results: (using 1e7 precision) ``` 1: 1 -2.5: -0.9453083... pi: 2.2880370... -e: -0.9526812... 12: 39916536.5... 0.5: 1.7724538... 8.675309: 20248.319... -10.1: -0.0000022... ``` ### How it works ``` // Implicit: U = input number $for( // Ordinary for loop. V=X=1; // Set V and X to 1. X<1e9;)$ // Repeat while X is less than 1e9. V*= // Multiply V by: (1+1/X // 1 plus (1 over X), pU / // to the power of U, divided by (1+U/X++ // 1 plus (U over X). Increment X by 1. ;V/U // Output the result of (V over U). ``` [Answer] # TI-BASIC, 35 bytes ``` Input Z 1 For(I,1,ᴇ9 Ans(1+I⁻¹)^Z/(1+Z/I End Ans/Z ``` This uses the same algorithm as Zereges. Caveat: I haven't actually tested this with the full 1e9 iterations; based on the time taken for smaller values, I expect the runtime to be on the order of *months*. However, it appears to converge, and there should be no problems with rounding errors. TI stores numbers as decimal floats with 14 digits of precision. [Answer] # Python 3, ~~74~~ ~~68~~ ~~78~~ 73 bytes Thanks @Mego and @xnor This is a translation of the C++ answer by Zereges. Basically, this is an alternate definition of the gamma function, hence more accurate (and what is great is that is uses less bytes!) I am sorry for all the mistakes! ``` def g(z,v=1): for i in range(1,10**9):v*=(1+1/i)**z/(1+z/i) return v/z ``` [Answer] # Python, ~~348~~ ~~448~~ ~~407~~ ~~390~~ 389 bytes Special thanks to @Mego! A crossed out 448 is (almost) still a 448! :p This is based on the Lanzcos approximation. Golfed from [here](http://web.archive.org/web/20150905222455/http://en.literateprograms.org/Gamma_function_with_the_Lanczos_approximation_(Python)) ``` from cmath import* C=[0.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-17‌6.6150291621406,12.507343278686905,-0.13857109526572012,9.984369578019572e-6,1.5‌​056327351493116e-7] def g(z): z-=1;if z.real<0.5:return pi/(sin(pi*z)*gamma(1-z)) else: x=C[0] for i in range(1,9):x+=C[i]/(z+i) t=z+7.5;return sqrt(2*pi)*t**(z+0.5)*exp(-t)*x ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 [bytes](https://github.com/abrudz/SBCS) ``` 1e8∘(*÷⊣!+)÷⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zDV/FHHDA2tw9sfdS1W1NYE0Yv@pz1qm/Cot@9RV/Oh9caP2iY@6psaHOQMJEM8PIP/qzvn5xaUlqSmKJQl5pSmFlup66QdWqFgqHBovZGeqYKxnqGJoamlkZkpWMDc0MLIAoRNzBQMjRQMgCos9MzMTY0NLIHyhgZ6hlwhRaWp7om5uYlAa6sVgYLaj3q31nKpByWWZOYDTdcAGX94uwJcnSb5lgEA "APL (Dyalog Unicode) – Try It Online") The above code uses the `!` function, but it is used as [generalized binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient#Generalization_and_connection_to_the_binomial_series), not factorial. A version without the `!` symbol altogether: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [bytes](https://github.com/abrudz/SBCS) ``` 1e8∘(*×(×/⊢÷+)∘⍳⍨)÷⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3zDV/FHHDA2tw9M1Dk/Xf9S16PB2bU2gyKPezY96V2ge3g4U@p/2qG3Co96@R13Nh9YbP2qb@KhvanCQM5AM8fAM/q/unJ9bUFqSmqJQlphTmlpspa6TdmiFgqHCofVGeqYKxnqGJoamlkZmpmABc0MLIwsQNjFTMDRSMACqsNAzMzc1NrAEyhsa6BlyhRSVpron5uYmAq2tVgQKaj/q3VrLpR6UWJKZDzRdA2T84e0KcHWa5Fv239cxIjzY1sgdAA "APL (Dyalog Unicode) – Try It Online") In both cases, `1e7` is used instead of `1e8` to show that the actual values calculated are close enough to the true values. ### How it works: the math Uses the formula used in [TanMath's Python answer](https://codegolf.stackexchange.com/a/63917/78410) and therefore [Zereges' C++ answer](https://codegolf.stackexchange.com/a/63893/78410). Basically, the solutions by TanMath/Zereges compute the following, which I developed further to suit better to APL: $$ \begin{align} \Gamma(x) &\approx \frac1x \prod\_{i=1}^{n}{\Bigl(1+\frac{1}{i}\Bigr)^x \div \Bigl(1+\frac{x}{i}\Bigr)} \\ &= \frac1x \prod\_{i=1}^{n}{\Bigl(\frac{i+1}{i}\Bigr)^x \times \Bigl(\frac{i}{x+i}\Bigr)} \\ &= \frac1x \Bigl(\prod\_{i=1}^{n}{\frac{i+1}{i}}\Bigr)^x \times \prod\_{i=1}^{n}{\Bigl(\frac{i}{x+i}\Bigr)} \\ &\approx \frac{n^x}x \times \prod\_{i=1}^{n}{\Bigl(\frac{i}{x+i}\Bigr)} \tag{1}\label{eq1}\\ &= \frac{n^x}x \div \binom{x+n}{n} \tag{2}\label{eq2}\\ \end{align} $$ The second solution uses equation \$\eqref{eq1}\$ while the first uses equation \$\eqref{eq2}\$, both using \$n=10^8\$ in order to get enough precision. ### How it works: the code ``` 1e8∘(*÷⊣!+)÷⊢ ⍝ Input←x; n←1e8 1e8∘( +) ⍝ n+x ⊣! ⍝ binom(n+x, n) *÷ ⍝ n^x ÷ binom(n+x, n) ÷⊢ ⍝ Divide by x 1e8∘(*×(×/⊢÷+)∘⍳⍨)÷⊢ ⍝ Input←x; n←1e8 1e8∘( ( )∘⍳⍨) ⍝ Generate 1..n; for each i in 1..n, ⊢÷+ ⍝ i÷(x+i) ×/ ⍝ Product over all i *× ⍝ Multiply n^x ÷⊢ ⍝ Divide by x ``` [Answer] # Julia, 41 bytes ``` x->prod([(1+1/i)^x/(1+x/i)for i=1:1E7])/x ``` This is a translation of Zereges' C++ answer. While my other Julia answer finishes instantaneously, this is rather slow. It computes the test cases in a couple seconds each on my computer. Ungolfed: ``` function f(x::Real) prod([(1 + 1/i)^x / (1 + x/i) for i = 1:1E7]) / x end ``` [Answer] # Mathematica, 40 bytes ``` NProduct[(1+1/n)^#/(1+#/n),{n,1,∞}]/#& ``` [Answer] # Prolog, 114 bytes This is a translation of Zereges' C++ answer. ``` q(F,F,V,Z):-X is V/Z,write(X). q(F,T,V,Z):-W is(1+1/F)**Z/(1+Z/F)*V,I is F+1,q(I,T,W,Z). p(N):-q(1.0,1e9,1,N),!. ``` Try it out online [here](http://swish.swi-prolog.org/) Run it with a query of the form: ``` p(12). ``` Running it with 1e9 recursions takes about 15 minutes. If you decrease it to 1e6 it takes about 1 second which makes for easier (but less acurate) testing. Running it in an interpreter on you computer/laptop is most likely faster for most people as well. ]
[Question] [ This challenge was inspired by [this non-challenge about the natural logarithm base \$e\$](https://codegolf.stackexchange.com/q/261002/110698) and the following pandigital approximation to \$e\$ appearing on a [Math Magic page](https://erich-friedman.github.io/mathmagic/0804.html): $$\left|(1+9^{-4^{7×6}})^{3^{2^{85}}}-e\right|$$ $$\approx2.01×10^{-18457734525360901453873570}$$ It is fairly well-known that $$e=\lim\_{n\to\infty}\left(1+\frac1n\right)^n$$ It is less well-known that the limit expression is strictly monotonically increasing over the positive real numbers. These facts together imply that for every nonnegative integer \$d\$ there is a **least** positive integer \$n=f(d)\$ such that the first \$d\$ decimal places of \$(1+1/n)^n\$ agree with those of \$e\$. \$f(d)\$ is [OEIS A105053](https://oeis.org/A105053). For example, \$(1+1/73)^{73}=2.69989\dots\$ and \$(1+1/74)^{74}=2.70013\dots\$, so \$f(1)=74\$. ## Task Given a nonnegative integer \$d\$, output \$n=f(d)\$ as described above. Your code must theoretically be able to give the correct answer for any value of \$d\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Test cases The corresponding digits of \$e\$ are given for reference. ``` d, n (2. 0, 1 (7) 1, 74 (1) 2, 164 (8) 3, 4822 (2) 4, 16609 (8) 5, 743325 (1) 6, 1640565 (8) 7, 47757783 (2) 8, 160673087 (8) 9, 2960799523 (4) 10, 23018638268 (5) 11, 150260425527 (9) 12, 30045984061852 (0) 13, 30045984061852 (4) 14, 259607904633050 (5) 15, 5774724907212535 ``` [Answer] # [Python](https://www.python.org), 126 bytes ``` f=lambda k,s=2,r=0:(P:=10**k*(t:=s+1)**t//s**s,p:=P//t,s%2*((x:=p<r)+s)or f(k,s+[s,x*(S:=s&-s)-S//2][r>0],r or(p==P//s)*p))[2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Nc5BCsIwEIXhvafIRpmZpqQGBAnGMxRcli4qGi3VNGQi6MaLuHGj1_Ac3saKuH_f4789wyXte3-_P07J5fP31dlDc1xvGtFJtlpGWxgojZ0WRB1BMpazKRIlpZiIZTC2VCpJHmsCOBsbFhEzxj4KB8NFVrE8E6wGN8kZ85VSuq7isqhlFH2EYL-ekQJipetfxcsN3IvWi9j43RZmaEYixNYncOARf6t_8wc) #### Previous [Python](https://www.python.org), 144 bytes ``` def f(k): o=p=0;P=n=1 while p<P//n:n*=2;m=n+1;P=10**k*m**m//n**n;p=P//m while n+~o:T=n+o>>1;o,n,*_=[o,T,n][10**k*(T+1)**T//T**T<p:] return n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY8xDoIwGIV3TvGP5QcDNTExlHIGhm6EGBOpEORv00CMi2dwd2HRa3gOb2MNYXnL-77kvefb3sbW0Dy_plFv9t_HqdGgWR9mARhpZSpKSZIHcG27SwM2L5OEMkK5FYOkiPuap4g9DoiDrxBJWOmhYVUouptMedYUBRcmphgPsjKxiqmuFpepiIeIKkmUz9xmdQCuGSdHQMuujzYOCDoCd6Rzw3b_fdZ1NDLNKAwXan3xAw) Not the golfiest, but should, in theory, give exact values for arbitrary inputs. In practice, times out for d>4 on ato. ### How? Takes advantage of Python's inbuilt bigints. Uses \$(1+1/n)^n<e<(1+1/n)^{n+1}\$ to compute the correct digits and an upper bound for n and then pinpoints n by bisection. As we always have to first compute the nth power of n+1 and only then can divide by the nth power of n this is still expensive. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~34~~ ~~33~~ 28 bytes (~~26~~ ~~25~~ 24 characters) ``` ⌊E/2/Mod[E,10^-#]+1/12⌋& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7/1FPl6u@kb5vfkq0q46hQZyucqy2ob6h0aOebrX/AUWZeSXRyrp2adHKsbFqCvoOCkGJeemp0aYGsf8B "Wolfram Language (Mathematica) – Try It Online") –5 bytes thanks to @CommandMaster The exact formula is $$ n(\zeta)=\left\lceil\frac{\zeta}{e^{-W\_{-1}\left(-\frac{\ln\zeta}{\zeta}\right)}-\zeta}\right\rceil=\left\lceil\frac{e}{2(e-\zeta)}-\frac{11}{12}+O(e-\zeta)\right\rceil \approx\left\lfloor\frac{e}{2(e-\zeta)}+\frac{1}{12}\right\rfloor $$ with $$ \zeta=10^{-d}\lfloor10^de\rfloor $$ being Euler's number rounded down to *d* digits, and *W* the [Lambert function](https://en.wikipedia.org/wiki/Lambert_W_function). The given series-expansion of *n(ζ)* seems to be good enough to evaluate the task. Note that we can freely replace the ceiling function `⌈…⌉` with the shifted floor function `⌊…⌋+1` because the argument cannot be an exact integer [because *e* is irrational](https://en.wikipedia.org/wiki/Proof_that_e_is_irrational). Here's the exact formula, golfed to 54 bytes (46 characters), to verify that the above series expansion gives correct results: ``` ⌈#/(E^(-LambertW[-1,-Log@#/#])-#)⌉&@⌊E,10^-#⌋& ``` [Try it online to verify up to *d*=2000](https://tio.run/##y00syUjNTSzJTE78/z9NwVbhUU@Xq76Rvm9@SrSrjqFBnK5yrLahvqHRo55uNWuudLCKDmV9Ddc4DV2fxNyk1KKS8GhdQx1dn/x0B2V95VhNXWXNRz2dag4gkyAmgPX@V/FNrHCtKClKDChKTc4szszPAxnWMc@aK6AoM68k2jEnJ6SoNDU6KDEvPTXayMDAIFZHIS1aOVbB1lYhHUSrxcb@BwA). For higher values of *d*, let's estimate the probability of failure. The series expansion of *n(ζ)* underestimates the true *n(ζ)* by about 5(*e*-*ζ*)/(72 *e*), which is the next term in the series-expansion of *n(ζ)*. But *e*-*ζ*<10^(-*d*), and so the probability of this underestimation crossing an integer (and thus fouling up the ceiling function) is less than 5×10^(-*d*)/(72 *e*). Summing these probabilities (assumed independent!) from *d*=2001 to infinity, we get a failure probability of around 3×10^(-2003). There were a lot of assumptions in this derivation (assuming independence, irrationality, ergodicity, etc.); but I think it indicates that we cannot expect any failures as *d* becomes large. NB: I've checked up to *d*=10000 and found no deviations, thus pushing the expected failure probability to 3×10^(-10003). PS: I've got [`°Džr*ïs/žrD;r-/TÌz+ï`](https://tio.run/##yy9OTMpM/f//0AaXo/uKtA6vL9YH0i7WRbr6IYd7qrQPr///3xwA) as a [05AB1E](https://github.com/Adriandmen/05AB1E) translation, but it does not seem very golfed (20 bytes). Help would be appreciated! [Answer] # [R](https://www.r-project.org), ~~59~~ 52 bytes ``` \(d){while(exp(1)%/%10^-d-(1+1/F)^F%/%10^-d)F=F+1;F} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3TWI0UjSryzMyc1I1UisKNAw1VfVVDQ3idFN0NQy1DfXdNOPcYCKabrZu2obWbrUQvTvT8os0MhUy8xQMrEw0FQqKMvNKNNI0MjU1IfILFkBoAA) Only works up to `d = 4` in practice, afterwards produces different results due to numerical precision issues. Credit for -7 bytes to Dominic van Essen. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes ``` (k=0;While[⌊10^#(1+1/++k)^k⌋!=⌊E*10^#⌋];k)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyPb1sA6PCMzJzX6UU@XoUGcsoahtqG@tna2Zlz2o55uRVugsKsWSALIi7XO1lT7H1CUmVeioO@Qru8QlJiXnhptoGMS@/8/AA "Wolfram Language (Mathematica) – Try It Online") -2 bytes from @Roman [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` n d=[n|n<-[1..],floor(10**d*(1+1/n)**n)==floor(10**d*exp 1)]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P08hxTY6rybPRjfaUE8vVictJz@/SMPQQEsrRUvDUNtQP09TSytP09YWWSK1okDBUDNWUdHgf25iZp5tQVFmXolKno2KHcgQ09j/AA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 204 bytes, fast ``` n d=b.(\(v,w)->(last v,head w)).break p$map(2^)[0..]where i=fromInteger f=floor.(*10**i d) e=f$exp 1 p n=e==f((1+1/i n)**i n) b(a,z)|let m=div(a+z)2=if m==a then z else if p m then b(a,m) else b(m,z) ``` [Try it online!](https://tio.run/##JYxBboMwEEX3nGIWLMaEunGk7jLZ9wxJKhkxLlbswTIWRKh3p0RZ/qf3/mCnB4ewbQI9dRpvOLeL@rhgsFOBuR3Y9rAopbvM9gGpjjbh6Uddj1rfl4EzV@DJ5TF@S@FfzhU4cmEcs8bGHJvGQ68qYHI1PxOYChIIMZFDNAfz6UHUS5Jd6tC2q/oLXCBS72e0h1WdyLt9koUysMAKHCaGnSWIb/TKonrzDuN@sUXrhVL2Umo515er0dp83bd/ "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 299 bytes, unlimited by `f64` ``` import Data.Ratio n d=b.(\(v,w)->(last v,head w)).break p$map(2^)[0..]where f=floor.(*10^d) e=f.sum.scanl1(*).map(1%)$1:[1..until(\i->product[1..i]>10^d)(1+)1] p n=(e==).f.sum.take(16+d)$scanl(*)1[(n-k+1)%(k*n)|k<-[1..n]] b(a,z)|let m=div(a+z)2=if m==a then z else if p m then b(a,m) else b(m,z) ``` [Try it online!](https://tio.run/##JY3BioMwFEX3fsVbWHiv1tB0YBZD42q@YLathWeNGExi0FSh9N8dbZf3wDm35bHT1i6LcaEfIvxyZPHH0fSJh1pVAq84HWbKC7Q8RpgOreYaZiJRDZo7CKnjgKcbXY5ClHOrB51Aoxrb94PAvTzeakpAq0aMDyfGO3srcU9is@SOUvlzkUI8fDQWryYvwtDXj3vcoCmLt44yI1kmEMAr1EqR@MQidxrld1ZT@u6uWXlBn3eZpB12e0@v7pxvJV@ueoV8eNLL6ghO1WZCzp50UqZZp2KIrfbwBG1HDSsL4D5o0xx9eIVuTSyOjVdhMD6m/pwW28PXqVz@AQ "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` NθP×ψ⁺²θ¤≕E≔¹ηW‹÷×XχθX⊕ηηXηηI⪫ΦKD⁺²θ→⊖λω≦⊕η⎚Iη ``` [Try it online!](https://tio.run/##TZBBT8MwDIXv/IpoJ0cqEtuRndAKqIihCiHuWWctFm7aJe4qfn1wS8W4@dnW957deBebznHOVegHeRvaA0Y42@3NfmChPlIQ@KAWE3wXpuYhwaYwZ2t144mY4Rnl00VyB0ZYPa6m/kNKdAqwLoxXNXpiNPCKKUEVpKQLHXFB1t2obuu7iaj0WVWhidhiEDyCtxPjb@QXtXNJ4KWjABpBdFAjfpUUsRHqAlxTFub@nU5etCjxiuUJMuoN1uxdv8T95/sbfMfoImhRz0@YTdV@m/Mm3174Bw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Brute force approach. ``` Nθ ``` Input `d`. ``` P×ψ⁺²θ¤≕E ``` Write `e` to `d` decimal places to the canvas. (I don't know a better way of extracting arbitrary numbers of decimal places of `e` in Charcoal.) ``` ≔¹η ``` Start with `n=1`. ``` W‹÷×XχθX⊕ηηXηηI⪫ΦKD⁺²θ→⊖λω ``` While `10ᵈ(1+⅟ₙ)ⁿ` is less than `10ᵈe`... ``` ≦⊕η ``` ... increment `n`. ``` ⎚Iη ``` Remove `e` from the canvas and output the final value of `n`. 73 bytes for a less inefficient version based on @loopywalt's original Python answer: ``` ≔XχNθ≔¹η≔⁰ζW↨÷÷×θX⊕η⊕ηXηη⟦⊕ηη⟧±¹≦⊗ηW∧⊖⁻ηζ÷⁺ηζ²¿↨E⟦ηι⟧÷×θX⊕κκXκκ±¹≔ιζ≔ιηIη ``` [Try it online!](https://tio.run/##fVCxjsIwDN3vKzI6Uk66sjLBdekA6sCGGELrI1bTFJoUJH4@JG1QK4Zbojz7@b1nV0r2VSe19xtr6WKg7B7YQ/YjWGGug9sP7TlgzgW78fVXImWCqRkF7jOghyKNDLbSIhTG5XSnevk7UIsWboJNFoWpemzROKxB8Wi3xNFw4qnoFdDxc0CdwrPHi3QIWRhgO3lNifJuOGusp5Qp18bUkOMssSMz2Kj@5KP7O2ap32XBVlGW/tJSQR@OoUOnJf@ftZog0cybNCP6CJ0S03hDhtriohTjlz0ZB7/SuniWtfcr/33XLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔XχNθ ``` Input `10ᵈ`. ``` ≔¹η≔⁰ζ ``` Start with bounds of `0` and `1`. ``` W↨÷÷×θX⊕η⊕ηXηη⟦⊕ηη⟧±¹≦⊗η ``` Double the bounds until the first `d` decimal places of `10ᵈ(1+⅟ₙ)ⁿ` are the same for both `n` and `n+1`. ``` W∧⊖⁻ηζ÷⁺ηζ²¿↨E⟦ηι⟧÷×θX⊕κκXκκ±¹≔ιζ≔ιη ``` Binary search to find the smallest value of `n` with the same first `d` decimal places. ``` Iη ``` Output the resulting `n`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 124 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 15.5 bytes ``` Ė›$eke"$↵vḞ?⇧vẎ≈)ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwixJbigLokZWtlXCIk4oa1duG4nj/ih6d24bqO4omIKeG5hSIsIiIsIjAiXQ==) Times out for all `d` except 0. Might be due to the fact that to even find the right number for `d > 0` a minimum of \$10^{74}\$ digits of \$e\$ and the approximation need to be calculated. ## Explained ``` Ė›$eke"n↵vḞ?⇧vẎ≈)ṅ )ṅ # find the first positive integer n where Ė›$e # (1 + 1/n) ^ n ke" # paired with the exact value of e ?n↵vḞ # both evaluated to 10 ** n decimal places - guarantees enough digits will be generated to avoid rounding errors ?⇧vẎ # each sliced to the first d + 2 characters (the 2, then the dot point, then d decimals) ≈ # are all the same ``` [Answer] # APL, 44 bytes ([SBCS](https://github.com/abrudz/SBCS)) ``` {1∘+⍣((⊢*⍨1+÷)⍤⊣=⍥((10*⍵)∘(÷⍤⊣×⌊⍤×))(*1⍨))1} ``` Explanation: ``` 1 Starting from 1, 1∘+ increment ⍣ until (⊢*⍨1+÷)⍤⊣ (1+1/n)^n = is equal to *1⍨ e ⍥ after both arguments to equal are processed by (10*⍵)∘(÷⍤⊣×⌊⍤×) rounding to input significant figures ``` Tested until d = 7, afterwards it gets too slow. Will probably eventually fail because of precision issues. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 (or 15) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞.Δz>ymþSžt‚I>δ£Ë ``` In theory works for an arbitrary value of \$n\$, but in practice times out for \$n\geq5\$ on TIO. [Try it online](https://tio.run/##ASYA2f9vc2FiaWX//@KIni7OlHo@eW3DvlPFvnTigJpJPs60wqPDi///NA) or [verify the first few test cases](https://tio.run/##ATYAyf9vc2FiaWX/NMaSTj8iIOKGkiAiP05V/@KIni7OlHo@eW3DvlPFvnTigJpYPs60wqPDi/99LP8). Here a 2 bytes shorter approach which works up to \$n=15\$ (in theory again, in practice it also times out at \$n\geq5\$): ``` ∞.Δz>ymžr‚IÌδ£Ë ``` [Try it online](https://tio.run/##ASQA2/9vc2FiaWX//@KIni7OlHo@eW3FvnLigJpJw4zOtMKjw4v//zQ) or [verify the first few test cases](https://tio.run/##ATQAy/9vc2FiaWX/NMaSTj8iIOKGkiAiP05V/@KIni7OlHo@eW3FvnLigJpYw4zOtMKjw4v/fSz/) **Explanation:** ``` ∞.Δ # Find the first positive integer `n` that's truthy for: z # Pop and push 1/n > # Increase it by 1 ym # Take that to the power n þ # Remove the dot by only leaving its digits S # Convert this integer to a list of digits ‚ # Pair it with žt # The infinite list of e: [2,7,1,...] δ # Map over the pair, I> # using the input+1 as argument: £ # Only leave that many digits from both lists Ë # Check if the lists in the pair are the same # (after which the found integer is output implicitly as result) ``` In the 15-bytes answer, `þS` are both removed; the infinite list of digits of \$e\$ `žt` is replaced with its decimal value `žr` (\$2.718281828459045\$); and the input+1 `I>` is replaced with the input+2 `IÌ` to account for the dot. [Answer] # [Scala](https://www.scala-lang.org/), 91 bytes Golfed version. [Try it online!](https://tio.run/##XY2xCsIwFEX3fMUb39MS28FFSMGhg4M4@AESm1Qr6UtIHyqI316ro8vlHricO7Y22KkfUswC4xf0YOWqT0rF8823AnvbM/ineHYjbFOCl1J3G4A3sGMx9RxgJmfqo2RvB93lOGBFuuvZIZu6CzFmTPGBVVk4WvzastLligsmMuZ/0BDpi5dDbsLosaRJAWAFEmE9W@N80l7Rgakh5Z4lMDI6IlJvNX0A) ``` d=>Stream.from(1).find(n=>floor(pow(10,d)*pow(1+1.0/n,n))==floor(pow(10,d)*E)).getOrElse(0) ``` Ungolfed version. [Try it online!](https://tio.run/##dU/BSsUwELznK@a40UdsD16ECh7ewYN48AMkNqmtpJuQLCpIv72mQcGLl4HZmdmdLaMNdt@XNcUsKAczq5XZPCsVX978KHiwC8N/imdXcJcSvhTg/AQmd4N7Ft0QQxOAJ8nermbKcaVem2lhR4zh9kcG3m1AmEsNTCHGTCl@UN@d4DQu0Mhlb7orPoG1/pPJ/2XOv662dTiMbbBp8@rlMZ9D8dQdpk1VoB4ScV2rxdp0nMkd7VJeWAJT/UrXs5va928) ``` import scala.math._ object Main extends App { def n(d: Int): Int = { Stream.from(1).find(n => { val lhs = floor(pow(10, d) * pow(1+1.0/n, n)) val rhs = floor(pow(10, d) * E) lhs == rhs }).getOrElse(0) } (1 to 5).foreach(d => println(n(d))) } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` (°žrDr%/;12z+ï ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f49CGo/uKXIpU9a0Njaq0D6///98cAA "05AB1E – Try It Online") Direct translation of [my Mathematica solution](https://codegolf.stackexchange.com/a/261684/87058), with help from @CommandMaster. Works only up to *d*=7 because of machine-precision issues. disassembly: ``` stack ---------------------------------- n ( -n ° 10^(-n) žr 10^(-n) e D 10^(-n) e e r e e 10^(-n) % e e%10^(-n) / e/(e%10^(-n)) ; e/(e%10^(-n))/2 12 e/(e%10^(-n))/2 12 z e/(e%10^(-n))/2 1/12 + e/(e%10^(-n))/2+1/12 ï floor(e/(e%10^(-n))/2+1/12) ``` ]
[Question] [ From the [Wikipedia article](https://en.wikipedia.org/wiki/Location_arithmetic): > > Location arithmetic (Latin arithmeticæ localis) is the additive (non-positional) binary numeral systems, which John Napier explored as a computation technique in his treatise Rabdology (1617), both symbolically and on a chessboard-like grid. > > > ## What? Location numerals is a way of writing numbers using letters of the alphabet. > > Binary notation had not yet been standardized, so Napier used what he called location numerals to represent binary numbers. Napier's system uses sign-value notation to represent numbers; it uses successive letters from the English alphabet to represent successive powers of two: **a = 2^0 = 1, b = 2^1 = 2, c = 2^2 = 4, d = 2^3 = 8, e = 2^4 = 16** and so on. > > > ## An example **`ab`** = 1+2 = 3 in base 10 **`aabb`** = 1+1+2+2 = 6 in base 10 Note that `aabb` can be shortened to `bc` by replacing any 2 instances of a letter by a higher one. ## Addition You just concatenate the two numbers and simplify. `acd` + `bde` = `acdbde` = `abcdde` = `acebe` = `abcf` = `39` in base 10 ## Subtraction Just remove all digits appearing equally in both parts of the subtraction. Expanding (converting `b` to `aa`) may be necessary `abde`- `ad` = `be` = 18 in base 10 ## Multiplication This is a bit harder. Lets say we want to multiply `acd` (13) by `def` (56). First you arrange `acd` vertically: ``` a c d ``` Then you add `def` after the first `a`: ``` a def c d ``` Now, c is 2 positions later in the alphabet than a, so we add 2 positions in the alphabet to `def` to make `fgh`. That is added to the second row. ``` a def c fgh d ``` Lastly, d is 1 position later in the alphabet than c, so we add 1 position in the alphabet to `fgh` to make `ghi`. That is added to the third row. ``` a def c fgh d ghi ``` Then you take the sum of the right: `def` + `fgh` + `ghi` = `deffgghhi` = `deggghhi` = `deghhhi` = `deghii` = `deghj` (728) ## Another example of multiplication Input: ``` bc * de ``` First: ``` b c ``` Then ``` b ef c ``` Then ``` b ef c fg ``` **Note that we wrote down `ef` on the first line. That's because `bc` starts with `b`, and `b` is the second letter in the alphabet, so we need to shift `de` by 1 letter, so it becomes `ef`.** Then ``` ef+fg ``` Output: ``` eh ``` ## Division This is not part of this challenge, because it can get very complex. # Your actual challenge Your program or function must take input as a string that looks like this: ``` a + b ``` And you must output: ``` ab ``` Of course, your program or function must support numbers of arbitrary length (up to the string or input limit of your language) with any of the operators `+`, `-`, or `*`. Some more examples: Input: ``` ab + bd ``` Output: ``` acd ``` Input: ``` d - ab ``` Output: ``` ac ``` Input: ``` ab * cd ``` Output: ``` cf ``` # Notes: * The order of letters in the output doesn't matter, but you can always assume that the order of letters in numbers in the input will be ascending (a before z). * You may take input with a trailing newline and output with a trailing newline. * You may *not* take input as a list of `ab`, `*` and `bd` for `ab * bd`. * The english alphabet is used (`abcdefghijklmnopqrstuvwxyz`) * Your output must be simplified (`aa` is not allowed, `b` is required) * The input will be simplified (`b` + `c`, not `aa` + `bb` or `aa` + `aaaa`) * You may require a space before and the operator (`+`, `-`, or `*`), or you may require there to be none. * There will only be one operator per input. * You may assume that the output and the input will never go over 2^27-1 (`abcdefghijklmnopqrstuvwxyz`) * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!** [Answer] ## Mathematica, 168 bytes ``` FixedPoint[StringReplace[x_~~x_:>FromCharacterCode[c@x+1]],Table["a",ToExpression@StringReplace[#,x:LetterCharacter..:>ToString@Tr[2^((c=ToCharacterCode)@x-97)]]]<>""]& ``` My initial solution (before the post was edited to clarify that the output must be simplified) was `64` bytes shorter: ``` Table["a",ToExpression@StringReplace[#,x:LetterCharacter..:>ToString@Tr[2^(ToCharacterCode@x-97)]]]<>"" ``` This just modified that solution to work. It's probably shorter to actually use the methods described in the challenge, but I wanted to put this up anyway. ## Explanation: Replaces each sequence of letters with its corresponding integer by character code arithmetic, then converts the resulting string to an expression (which will automatically simplify to an integer), then produces a string of `a` characters of length equal to that integer, and finally replaces adjacent identical characters with the next character code up until a fixed point is reached. [Answer] ## JavaScript (ES6), ~~136~~ ~~134~~ 133 bytes *Saved 1 byte thanks to Luke* ``` s=>[...a='abcdefghijklmnopqrstuvwxyz'].filter((c,i)=>eval(s.replace(/\w+/g,s=>[...s].reduce((p,c)=>p|1<<a.search(c),0)))&1<<i).join`` ``` ### Test cases ``` let f = s=>[...a='abcdefghijklmnopqrstuvwxyz'].filter((c,i)=>eval(s.replace(/\w+/g,s=>[...s].reduce((p,c)=>p|1<<a.search(c),0)))&1<<i).join`` console.log(f('ab + bd')); // acd console.log(f('d - ab')); // ac console.log(f('ab * cd')); // cf ``` [Answer] # [Perl 5](https://www.perl.org/), 95 bytes 94 bytes of code + `-p` flag. ``` s/\w/a x 2**(-97+ord$&)/ge;s/(.*)-\1|\+//;/\*/&&($_=$`x length$');1while s/(.)\1/chr 1+ord$1/e ``` [Try it online!](https://tio.run/nexus/perl5#JY7NbsMgEITvfoqtYvm3BNFLFVl9E6SWwGKQCDiA61Tqu7s4vcxqNd/s7OllweiALK46AXGgnZjBJoh4X21EBTpEuK0u28UhZEwZpEiYzgW3GrLBiAcfvPsp8o@8whLDt1XFybDZbMKaQVsvHHjcnPVY0t1hQIvSBCC@fRZZn7LwEvs9Ub5RAQ94G4aOXN7HEFXd9HTGKdHuPPSEs18@UjpRPtCm6erPj/rrAQ79nE3d9hPbjC0vH3TPGZUmAnteYRT3XUg1XhVWoggRqir7oFBXV1nGHw "Perl 5 – TIO Nexus") Three steps here: - `s/\w/a x 2**(-97+ord$&)/ge;` converts the input into a string of `a` only. - `s/(.*)-\1|+//;/*/&&($_=$`x length$')` will execute the operator (that are very simple on strings of `a`): `+` is the concatenation, `-` means removing from the first part as many `a` as there are in the second part, and `*` means duplicating the first part as many times as there are `a` in the second part. - `1while s/(.)\1/chr 1+ord$1/e` folds the consecutive same letters into the next letter in the alphabet. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes ``` ð¡À¬U¦v0yvAyko+}}X.VbRvyiANèJ ``` [Try it online!](https://tio.run/nexus/05ab1e#@394w6GFhxsOrQk9tKzMoLLMsTI7X7u2NkIvLCmorDLT0e/wCq///xOTUxS0FFJS0wA "05AB1E – TIO Nexus") or as a [Test suite](https://tio.run/nexus/05ab1e#qymrDKv8f3jDoYWHGw6tCT20rMygssyxMjtfu7Y2Qi8sKaisMtPR7/AKr/@1tZFKh/dbKRzer6TzPzE5RUFbISkllQvE0lJISU3jSgSJcCUmgSW4UhR0FRLBXC2F5BQA) **Explanation** ``` ð¡ # split input on string À # rotate left ¬U¦ # get the operator, store it in X and remove it from list v # for each side of the equation 0 # push 0 as an accumulator yv # for each letter in each side of the equation Ayk # get its index in the alphabet o # raise 2 to this power + # add to the accumulator }} # end loops X.V # apply the operator to the 2 numbers now on the stack bR # convert to binary and reverse v # for each binary digit yi # if it is true ANè # get the letter at that index in the alphabet J # join stack to a single string ``` [Answer] # C & x86 asm, 340 Bytes Compile with -O0 ``` #define G getchar() g(){int c,a=0;for(;islower(c=G);)a+=1<<(c-97);return a;} main(){short o[]={[43]=0x4403,[45]=0x442b,[42]=0x6cf7}; mprotect((long)&&l&~4095,4096,7); for(;;){int c,b=0,a=g();*(short*)&&l=o[G];G;g();asm("xchg %%eax,%0":"+m"(a)); l:asm("addl %1,%%eax":"=a"(c):"m"(a)); for(;a=c>>b;b++)if(a&=1)putchar(97+b);putchar(10);}} ``` **Explanation** Since C doesn't have `eval()`, I used a table of x86 instructions in its place. I had to choose instructions which were all the same length (or padded with nops), and which expected src and destination of the same types. Of particular annoyance was that MUL can only write to registers, and the 1-byte MUL opcodes can only write to EAX. Additionally, there seemed to be no register-writing SUB instruction which subtracted from memory, instead of the other way around, hence the XCHG. **edit** Since it was asked in the comments, a more traditional appraoch would look like this: ``` #define G getchar() #define return r #define int i g(){i c,a=0;for(;islower(c=G);)a+=1<<(c-97);r a;} a(i x,i y){r x+y;}s(i x,i y){r x-y;}m(i x,i y){r x*y;} main(){i(*o[])(i,i)={[43]=a,[45]=s,[42]=m}; for(;;){i c,b,a=g();b=G;G;g();c=o[b](a,g()); for(b=0;a=c>>b;b++)if(a&=1)putchar(97+b);putchar(10);}} ``` It's actually a bit shorter, at 301 chars, for a few reasons: 1. Because there need to be a lot of functions, the overhead of each can be chopped with some preprocessor rules. 2. Modern linux protects from execution on the stack, so the mprotect() call to disable this sacrificed 34 bytes. 3. The XCHG call is very sub-optimal, costing another 30 bytes. If not for those things, the x86 combo would win by about 10-20 bytes. Also chopped 2 bytes from both by improving the islower() call in g. [Answer] # GNU sed + coreutils, 329 bytes Yeah, I have no idea what got into me, but at least I know sed scripting a bit better now. Note that this solution requires GNU sed's `e` extension, which runs a shell command. ``` /\+/{s/\+// b S} /-/{:E /a+-a+/{s/(a*)(a*)-\2/\1/ b S} s/.*/echo &|tr b-z- A-Y-/ e s/([A-Z])/\L\1\1/g b E} /\*/{h :M /^\*/{x s/[^\n]*// s/\n//g b S} s/(.).*\*(.*)/echo \2|tr a-z \1-za-z/ e H g s/.(.*)/\1/ h s/\n.*// b M} :S s/^.*$/echo &|grep -o .|sort|tr -d '\n'/ e :L s/(.)\1/\u\1/g /^[a-z]*$/ q s/.*/echo &|tr A-Z b-za/;e b L ``` I assume that there will not be spaces around the operators. From my terminal: ``` $ sed -rf golf.sed <<< a+b ab $ sed -rf golf.sed <<< ab+bd acd $ sed -rf golf.sed <<< abc+b ad $ sed -rf golf.sed <<< d-ab ca $ sed -rf golf.sed <<< ab*cd cf $ sed -rf golf.sed <<< bc*de eh $ sed -rf golf.sed <<< acd*def deghj ``` And, for those saner than I: the commented version! ``` #!/bin/sed -rf /\+/ { s/\+// b simplify } /-/ { # expand pattern space; everything will now be 'a's :E /a+-a+/{ # Remove doubled 'a's on either side of the dash. For example, # for input d-ab, space is now 'aaaa-aaa'; substitute this to 'a' s/(a*)(a*)-\2/\1/ b simplify } # shift letters that aren't 'a' down and double them s/.*/echo &|tr b-z- A-Y-/;e s/([A-Z])/\L\1\1/g b E } /\*/ { # Hold space: line 1 is pattern, other lines are output h :M # if space starts with *, we've eaten entire arg0; sum and simplify /^\*/ { x s/[^\n]*// # remove first line, which is our pattern s/\n//g # remove newlines to add results together b simplify } # convert pattern into shifting command s/(.).*\*(.*)/echo \2|tr a-z \1-za-z/ # execute it, append result to hold space e H # restore pattern, with leading char and all output lines removed g s/.(.*)/\1/ h s/\n.*// b M } :simplify # reorder all letters so all 'a's are before all 'b's are before all 'c's # are before ... etc # See https://stackoverflow.com/questions/2373874 s/^.*$/echo &|grep -o .|sort|tr -d '\n'/ e :L # Replace repeated characters with themselves upper-cased, then translate # upper-cased characters to what they should be. s/(.)\1/\u\1/g /^[a-z]*$/ q s/.*/echo &|tr A-Z b-za/;e b L ``` [Answer] # PHP, 168 Output Ascending with use of eval ``` [$a,$o,$b]=explode(" ",$argn);function d($s){for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);return$n;}for(eval("\$k=d($a)$o d($b);");$i<26;)echo$k&2**$i++?chr(96+$i):""; ``` # PHP, 185 Bytes Output Ascending ``` [$a,$o,$b]=explode(" ",$argn);function d($s){for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);return$n;}for(;$i<26;)echo(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b))&2**$i++?chr(96+$i):""; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/ba38afb7a46b7e54297f3a6d929c464e4af90c4f) Expanded ``` [$a,$o,$b]=explode(" ",$argn); # part the input into variables function d($s){ # make decimal value for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97); return$n; } for(;$i<26;) echo(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b))&2**$i++?chr(96+$i):""; # Bitwise Compare and Output ``` ## PHP, 201 Bytes Output Decending ``` [$a,$o,$b]=explode(" ",$argn);function d($s){for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97);return$n;}for($r=(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b));$r;$r-=2**$l)$t.=chr(97+$l=log($r,2)^0);echo$t; ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/b11688e83798dedb2eb15acee83a80f5881eee6f) Expanded ``` [$a,$o,$b]=explode(" ",$argn); # part the input into variables function d($s){ # make decimal value for(;$i<strlen($s);)$n+=2**(ord($s[$i++])-97); return$n; } for( $r=(bc.[mul,add,0,sub][ord($o)-42])(d($a),d($b)) # result of the operation ;$r; $r-=2**$l) # subtract the letter value $t.=chr(97+$l=log($r,2)^0); # find greatest letter echo$t; # Output ``` [Answer] # [Python 3](https://docs.python.org/3/), 176 167 bytes ``` i=lambda a:str(sum(1<<ord(i)-97for i in a)) def f(a): a,b,c=a.split();m=eval(i(a)+b+i(c));r='' while m: t=0 while m>=2**t*2:t+=1 r+=chr(97+t);m-=2**t return r ``` [Try it online!](https://tio.run/nexus/python3#LYxJDoMwDEX3OYV32ASqwgYxpHdxGIQlJpnQHp9GVTd/8Z7ev8UtvPqBgZszKJ7XikXX7TqgUF5X064gIBswkRnGCSZkagxw5rPe8eM8FglI7erGNy8o0VpvBXuiVl2SGPjMsoywxgaCe8b9g5cr0zSkZROsKyJW6/pZsa5siHf5zxrQMVy6gd6HyhZwwoQ9WPBDQnR/AQ "Python 3 – TIO Nexus") * saved 9 bytes: Thanks to [tutleman](https://codegolf.stackexchange.com/users/64834/tutleman) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` i@€Øað’2*S;ḟ.Ḣ ḲÇ€VBṚTịØa ``` Uses Jelly's operators (`×` rather than `*` and `_` rather than `-`) in the input string as [allowed by the OP](https://codegolf.stackexchange.com/questions/116017/lets-do-some-location-arithmetic#comment283341_116017). (Requires spaces around the operators) **[Try it online!](https://tio.run/nexus/jelly#@5/p8KhpzeEZiYc3PGqYaaQVbP1wx3y9hzsWcT3cselwO1AuzOnhzlkhD3d3AxX9//8/MUnh8HSF5BQA)** or see the [test suite](https://tio.run/nexus/jelly#@5/p8KhpzeEZiYc3PGqYaaQVbP1wx3y9hzsWcT3cselwO1AuzOnhzlkhD3d3AxX9f7h7y6GtR/eAJbKA@FHDHAVbhUcNcyP//09MTlE4PF0hJTWNKykZwuJKVNBWSOJKTAJRKVwpCvEKiWAuUDY5BQA) ### How? ``` i@€Øað’2*S;ḟ.Ḣ - Link 1, transform from input sub-string to value or operator: sub-string i@€ - 1st index of, for €ach (or 0 if not found) [reversed @rguments] in: Øa - lowercase alphabet (i.e. a->1, b->2, ..., non-alpha->0) ð - dyadic chain separation i.e. f(result above, substring): ’ - decrement (i.e a->0, b->1, ..., non-alpha->-1) 2* - 2 raised to that power S - sum ; - concatenate with the substring ḟ - filter out: . - 0.5 (for an operator substring the evaluated 0.5 is removed) Ḣ - head (i.e. the evaluation for a location, and the operator otherwise) ḲÇ€VBṚTịØa - Main link: string e.g. 'ab × cd' Ḳ - split on spaces [['a','b'],['×'],['c','d']] Ç€ - last link (1) as a monadic function for €ach [3,'×',12] V - evaluate as Jelly code 36 B - convert to binary [1,0,0,1,0,0] Ṛ - reverse [0,0,1,0,0,1] T - truthy indexes [3,6] ị - index into: Øa - lowercase alphabet ['c','f'] (i.e. "cf", which is implicitly printed when run as a full program) ``` [Answer] # PHP, 130 ``` for($d=a;$e=$argn[$i++];)$e!=' '?$d!=b?$$d+=1<<ord($e)-97:$b=$e:++$d;eval("for(;\$j++<27;)echo($a$b$c>>\$j-1)&1?chr(96+\$j):'';"); ``` expanded version: ``` for($d=a;$e=$argn[$i++];) // for each char in the input $e!=' '? // if space $d!=b? // if not the operation $$d+=1<<ord($e)-97: // add 2^(char - 'a') $b=$e: // else save operation ++$d; // else increase "pointer" eval("for(;\$j++<27;) // for each bit in the output echo($a$b$c>>\$j-1)&1? // calulate the result and check the bit chr(96+\$j): // output corrosponding char ''; // output nothing "); ``` run with `php -R <code>`. [Answer] # AWK, 201 bytes ``` BEGIN{RS="(.)"}n=index(V="abcdefghijklmnopqrstuvwxyz",RT){s+=2^--n}index("+-*",RT){a=s RT s=0}END{RS="\n" "(awk '$0="a s"'<<<1)"|getline v for(j=26;j--;)if((s=v-2^j)>=0){v=s;c=substr(V,j+1,1)c}print c} ``` `"(awk '$0="a s"'<<<1)"|getline v` is the best way I could come up with to do an `evaluate` in `AWK`. I may be "cheating" a little to call this just `AWK`, since I am executing a command, but at least the command is also `AWK` :) I'm sure I'm missing some way to reduce the byte-count, but I sure can't see it. Usage is fairly standard, e.g. put the code in `FILE` and do: ``` awk -f FILE <<< "bc + ab" ``` Note that spaces are not required and any non-op/non[a-z] character will be silently ignored. Could be extended to work with numbers greater than "abcdefghijklmnopqrstuvwxyz" by changing the loop. To do division, simply add the `/` character to the operation string :). Also, will print a blank line if the `result <= 0`. ]
[Question] [ **The Challenge:** Consider the function `F(N) = 2^N + 1` where `N` is a positive integer less than `31`. The sequence defined by this function is: ``` 3, 5, 9, 17, 33, 65, 129, 257, 513, 1025, 2049, 4097, 8193, 16385, 32769, 65537, 131073, 262145, 524289, 1048577, 2097153, 4194305, 8388609, 16777217, 33554433, 67108865, 134217729, 268435457, 536870913, 1073741825 ``` An input will be generated as follows: * Take 5 *contiguous* integers from the above sequence. * Replace one of them with a different, positive integer (which may or may not be part of the above sequence). * Optionally reorder the the 5 resulting numbers. Given such a list of 5 integers, find the one that was swapped in and is therefore not part of the original 5 contiguous integers. Example: * Original sublist: `5, 9, 17, 33, 65`. * Replace one: `5, 7, 17, 33, 65`. * Reorder: `33, 17, 5, 7, 65`. The expected output would be `7`. The 5 values in the input will always be distinct and there will always be a unique solution. (For instance, you won't have to deal with inputs like `3, 9, 17, 33, 129` where either `3` or `129` might have been swapped in.) **Test Cases:** ``` 5,9,17,33,829 o/p: 829 9,5,17,829,33 o/p: 829 33, 17, 5, 7, 65 o/p: 7 5,9,177,33,65 o/p: 177 65,129,259,513,1025 o/p: 259 129,259,513,1025,65 o/p: 259 63,129,257,513,1025 o/p: 63 65,129,257,513,4097 o/p: 4097 5, 9, 2, 17, 33 o/p: 2 536870913, 67108865, 1073741825, 1, 268435457 o/p: 1 ``` [Answer] # Jelly, 15 bytes ``` ⁹R2*‘ṡ5ḟ@€µEÐfQ ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4oG5UjIq4oCY4bmhNeG4n0DigqzCtUXDkGZR&input=&args=WzUsOSwxNywzMyw4Mjld)** All test cases also at **[TryItOnline](http://jelly.tryitonline.net/#code=4oG5UjIq4oCY4bmhNeG4n0DigqzCtUXDkGZRCsW8w4dGJOKCrEvigqxH&input=&args=W1s1LDksMTcsMzMsODI5XSxbOSw1LDE3LDgyOSwzM10sWzUsOSwxNzcsMzMsNjVdLFs2NSwxMjksMjU5LDUxMywxMDI1XSxbMTI5LDI1OSw1MTMsMTAyNSw2NV0sWzYzLDEyOSwyNTcsNTEzLDEwMjVdLFs2NSwxMjksMjU3LDUxMyw0MDk3XV0)** Returns a list containing one list containing the odd one out. How? ``` ⁹R2*‘ṡ5ḟ@€µEÐfQ - Main link, a (list) ⁹ - literal 256 (saving a byte over literal 30) R - range, [1,2,3,...] 2* - 2 ** x, [2,4,8,...] ‘ - increment, [3,5,9,...] ṡ5 - all contiguous slices of length 5 ḟ@€ - filter with reversed arguments for each µ - monadic chain separation Ðf - filter on condition: E - all equal (those previously filtered lists with only one value) Q - unique (there can be two, but both will have the same odd-one-out) ``` [Answer] ## JavaScript (ES6), 62 bytes ``` a=>a.find(n=>--n&--n|!n)||a.sort((a,b)=>a-b)[a[0]*16>a[3]?4:0] ``` Completely new algorithm, since as @edc65 pointed out the previous one was broken. Explanation: We first deal with the easy case by looking for a 2 or a number that is not one greater than a power of 2. If none was found then there are two possible cases, depending on whether the extra value was below or above the original run of five, so we check whether the smallest and second largest value belong to the same run of five and if so blame the largest value otherwise the smallest value. [Answer] # Python, 84 bytes ``` def f(a,i=0):s=set(a)-{2**j+1for j in range(i,i+5)};return len(s)<2and s or f(a,i+1) ``` All test cases are at **[ideone](http://ideone.com/rNSr55)** For valid input returns a set containing only the odd-one-out. For invalid input the recursion limit will be reached and an error will be thrown. [Answer] ## Mathematica, 65 bytes ``` f[a___,x_,b___]/;NestList[2#-1&,a~Min~b/. 2->0,4]~SubsetQ~{a,b}=x ``` This defines a function `f` which should be called with 5 arguments, e.g. ``` f[5, 9, 17, 33, 829] ``` In principle the function can be called with any (non-zero) number of arguments, but you might get unexpected results... I think this is the first time, that I managed to put the entire solution to a non-trivial challenge into the left-hand side of a `=`. ### Explanation This solution really puts Mathematica's pattern matching capabilities to work for us. The basic feature we're using is that Mathematica can't just define simple functions like `f[x_] := (* some expression in x *)` but we can use arbitrarily complex patterns on the left-hand side, e.g. `f[{a_, b_}, x_?OddQ] := ...` would add a definition to `f` which is only used when it's called with a two-element list and an odd integer. Conveniently, we can already give names to elements arbitrarily far down the left-hand side expression (e.g. in the last example, we could immediately refer to the two list elements as `a` and `b`). The pattern we're using in this challenge is `f[a___,x_,b___]`. Here `a___` and `b___` are *sequences* of zero or more arguments and `x` is a single argument. Since the right-hand side of the definition is simply `x`, what we want is some magic that ensures that `x` is used for the input we're searching for and `a___` and `b___` are simply wildcards that cover the remaining elements. This is done by attaching a *condition* to the pattern with `/;`. The right-hand side of `/;` (everything up to the `=`) needs to return `True` for this pattern to match. The beauty is that Mathematica's pattern matcher will try every single assignment of `a`, `x` and `b` to the inputs for us, so the search for the correct element is done for us. This is essentially a declarative solution to the problem. As for the condition itself: ``` NestList[2#-1&,a~Min~b/. 2->0,4]~SubsetQ~{a,b} ``` Notice that this doesn't depend on `x` at all. Instead, this condition depends only on the remaining four elements. This is another convenient feature of the pattern matching solution: due to the sequence patterns, `a` and `b` together contain all other inputs. So this condition needs to check whether the remaining four elements are contiguous elements from our sequence with at most one gap. The basic idea for checking this is that we generate the next four elements from the minimum (via `xi+1 = 2xi - 1`) and check whether the four elements are a subset of this. The only inputs where that can cause trouble is those that contain a `2`, because this also generates valid sequence elements, so we need to handle that separately. Last part: let's go through the actual expression, because there's some more funny syntactic sugar here. ``` ...a~Min~b... ``` This infix notation is short for `Min[a,b]`. But remember that `a` and `b` are sequences, so this actually expands to the four elements `Min[i1, i2, i3, i4]` and gives us the smallest remaining element in the input. ``` .../. 2->0 ``` If this results in a 2, we replace it with a 0 (which will generate values which aren't in the sequence). The space is necessary because otherwise Mathematica parses the float literal `.2`. ``` NestList[...&,...,4] ``` We apply the unnamed function on the left 4 times to this value and collect the results in a list. ``` 2#-1& ``` This simply multiplies its input by 2 and decrements it. ``` ...~SubsetQ~{a,b} ``` And finally, we check that the list containing all elements from `a` and `b` is a subset of this. [Answer] ## Racket 198 bytes ``` (λ(m)(let((l(for/list((i(range 1 31)))(+ 1(expt 2 i))))(r 1)(n(length m)))(for((i(-(length l)n)))(let ((o(for/list((j m)#:unless(member j(take(drop l i)n)))j)))(when(eq?(length o)1)(set! r o))))r)) ``` Ungolfed version: ``` (define f (λ(m) (let ((l (for/list ((i (range 1 31))) (+ 1 (expt 2 i)))) (res 1) (n (length m))) (for ((i (- (length l) n))) (let ((o (for/list ((j m) #:unless (member j (take (drop l i) n))) j))) (when (eq? (length o) 1) (set! res o)))) res))) ``` Testing: ``` (f '(5 9 17 33 829)) (f '(9 5 17 829 33)) (f '(5 9 177 33 65)) (f '(65 129 259 513 1025)) (f '(129 259 513 1025 65)) (f '(63 129 257 513 1025)) (f '(65 129 257 513 4097)) ``` Output: ``` '(829) '(829) '(177) '(259) '(259) '(63) '(4097) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~32~~ ~~30~~ ~~26~~ ~~24~~ 20 bytes ``` 30Lo>Œ5ùv¹yvyK}Dgi`q ``` **Explanation** ``` 30Lo> # list containing the sequence [3 .. 1073741825] Œ5ù # all sequence sublists of length 5 v # for each such list ¹yvyK} # remove it's elements from input Dgi # if the remaining list has length 1 `q # end the program and print the final list flattened ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MzBMbz7FkjXDuXbCuXl2eUt9RGdpYCxx&input=WzUsIDksIDIsIDE3LCAzM10) [Answer] ## R, 97 bytes This turned out to be more difficult than I thought. I'm sure this can be golfed significantly though. ``` m=match(x<-sort(scan()),2^(1:31)+1);l=diff(m);ifelse(NA%in%m,x[is.na(m)],x[ifelse(l[4]>1,5,l>1)]) ``` ### Ungolfed and explained ``` x<-sort(scan()) # read input from stdin and sort, store as vector m=match(x, 2^(1:31)+1) # generate a vector of indices for which input matches the sequence l=diff(m) # vector of the difference of indices (will only contain 4 elements) ifelse(NA%in%m, # if m contains NA do: x[is.na(m)], # return x where no match has been found, else: x[ifelse(l[4]>1,5,l>1)]) # return x by index where diff>1 unless it's the last object, then return x[5] ``` The `match()` function will return `NA` if the any element of the input vector is not in the sequence and consequently we can just find the index where `NA`exist in the input and return this: `x[is.na(m)]` It gets a bit more complicated if input is part of the sequence but misplaced. Because input has been sorted, the distance between each pair of *indices* should be `1`. We can therefore find the misplaced element by investigating the `1st` difference of the matched indices `l=diff(m)` and select the index for which `l>1`. This would be just enough if it weren't for the fact that `l` contains `4` elements rather than `5`. This is only a problem if the last element in the sorted input is a member of the sequence BUT not a part of the subsequence (as in the final test case). Consequently, if the `4th` element `>1` fetch the `5th` entry in the sorted input else look for the index in the `4`-length vector: `x[ifelse(l[4]>1,5,l>1)]` [Answer] ## Haskell, ~~66~~ 64 bytes ``` g x=[s|n<-[1..],[s]<-[filter(`notElem`[2^m+1|m<-[n..n+4]])x]]!!0 ``` Usage example: `g [65,129,257,513,4097]` -> `4097`. Loops through all contiguous sublists of length 5 of `F(N)`, keeps the elements that are not in the input list `x` and pattern matches those of length 1 (-> `[s]`). Edit: @xnor saved two bytes by removing the upper bound of the outer loop. As a solution is guaranteed to exist, Haskell's laziness stops at the first number found. [Answer] # Perl, ~~64~~ 59 bytes Includes +2 for `-an` Give input list on STDIN: ``` perl -M5.010 oddout.pl <<< "5 9 2 17 33" ``` `oddout.pl`: ``` #!/usr/bin/perl -an @a=grep$_,@a{@F,map{2**$_+++1}($.++)x5}=@F while$#a;say@a ``` If you don't mind variable amount of space around the result this 58 byte verson works: ``` #!/usr/bin/perl -ap $_=join$",@a{@F,map{2**$_+++1}($.++)x5}=@F while/\b +\b/ ``` Both versions loop forever if the input has no solution. This is very sick code, but I can't think of anything elegant... The way I (ab)use `%a` is a new perlgolf trick as far as I know. [Answer] ## Python 2, 73 bytes ``` s=set(input());i,=d={1} while~-len(s-d):i*=2;d=d-{i/32+1}|{i+1} print s-d ``` Iterates through sets `d` of five consecutive sequence elements until it finds one that contains all but one of the input elements, and then prints the difference, which is the output in a singleton set. The sets `d` of five consecutive elements are built up from nothing by repeatedly adding a new element `i+1` and deleting any old element `i/32+1` that comes before the current window of 5. Here's what its progress looks like. ``` {1} {3} {3, 5} {3, 5, 9} {3, 5, 9, 17} {3, 5, 9, 17, 33} {5, 9, 17, 33, 65} {9, 17, 33, 65, 129} {17, 33, 65, 129, 257} {33, 65, 129, 257, 513} ``` There's a stray 1 at the start from initialization, but it's harmless because it's immediately removed. The smaller sets as it builds up to 5 elements are also harmless. [Answer] # PHP, ~~87~~ ~~76~~ 75 bytes ``` for(;count($b=array_diff($argv,$a?:[]))-2;)$a[$n%5]=1<<++$n|1;echo end($b); ``` run with `php -r '<code>' <value1> <value2> <value3> <value4> <value5>` [Answer] # C#, 69 bytes `int M(int[]a)=>a.Except(new int[30].Select((_,i)=>(1<<i+1)+1)).Sum();` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ¨²›5l¨VF~₃h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwqjCsuKAujVswqhWRn7igoNoIiwiIiwiWzUsOSwxNywzMyw4MjldXG5bOSw1LDE3LDgyOSwzM11cblszMywxNyw1LDcsNjVdXG5bNSw5LDE3NywzMyw2NV1cbls2NSwxMjksMjU5LDUxMywxMDI1XVxuWzEyOSwyNTksNTEzLDEwMjUsNjVdXG5bNjMsMTI5LDI1Nyw1MTMsMTAyNV1cbls2NSwxMjksMjU3LDUxMyw0MDk3XVxuWzUsIDksIDIsIDE3LCAzM11cbls1MzY4NzA5MTMsIDY3MTA4ODY1LCAxMDczNzQxODI1LCAxLCAyNjg0MzU0NTddIl0=) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~17~~ 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs a singleton array. ``` HÆÒ2pXÃã £kXÃl1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=SMbSMnBYw%2bMgo2tYw2wx&input=WzYzLDEyOSwyNTcsNTEzLDEwMjVdCi1R) ``` HÆÒ2pXÃã £kXÃl1 :Implicit input of array U H :32 Æ :Map each X in the range [0,32) Ò : Negate the bitwise NOT of 2pX : 2 raised to the power of X à :End map ã :Sub-arrays £ :Map each X kX : Remove the elements in X from U à :End map l1 :Filter elements of length 1 :Implicit output of first element ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 13 bytes (26 nibbles) ``` /+=~.;,30-_<5>$.@+^2$~, ``` [Try it at nibbles.onrender.com](https://nibbles.onrender.com/#WyIvKz1+LjssMzAtXzw1PiQuQCteMiR+LCIsIls2NSwxMjksMjU3LDUxMyw0MDk3XSJd) ``` . # each n of ,30 # 1..30 ; # (saving this range for later) # using function: -_ # get difference between input and <5 # first 5 elements >$ # after dropping n elements from @ # 1..30 . # each ^2$ # used as an exponent of 2 + # added to ~ # 1 =~ # now group & sort results by , # length + # flatten this list of lists / # and fold over this returning the leftmost element # (which is the single element in the smallest-length list) ``` [![enter image description here](https://i.stack.imgur.com/C75Vq.png)](https://i.stack.imgur.com/C75Vq.png) [Answer] # Java 7,85 bytes ``` int f(int[]a,int l){int i=1;for(;i<l;)if(a[i++-1]*2-1!=a[i])return a[i];return a[0];} ``` # Ungolfed ``` int f(int[]a,int l){ int i=1; for(;i<l;) if(a[i++-1]*2-1!=a[i]) return a[i]; return a[0]; } ``` [Answer] # PHP, 76 Bytes implemented Titus idea with the mod 5 ``` <?for(;count($x=array_diff($_GET[a],$r))-1;$r[++$i%5]=2**$i+1);echo end($x); ``` 126 Bytes before ``` <?for(;$x=array_diff($_GET[a],array_map(function($z){return 2**$z+1;},range(++$i,$i+4)));)if(count($x)<2){echo end($x);break;} ``` [Answer] # Pyth, 18 bytes ``` hhlD-LQ.:mh^2dSCd5 ``` Form the sequence, take sublists of length 5, Remove each sublist from Q, take the shortest result, output its only element. [Answer] # Kotlin, 55 bytes `fun f(a:IntArray)=a.find{it-1 !in(1..30).map{1 shl it}}` [Answer] # [Ruby](https://www.ruby-lang.org/), 70 bytes ``` ->a{(1..a.max).map{2**_1+1}.each_cons(5).map{b=a-_1 break b if !b[1]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY33XTtEqs1DPX0EvVyEys0gURBtZGWVryhtmGtXmpickZ8cn5esYYpRCbJNlE33pArqSg1MVshSSEzTUExKdowtrYWalpjgYJbdLSpjoKljoKhuY6CsbGOgoWRZWwsF1gCKGoKkQAKgmRhEiB1IGGgLJA0M4WJw0yCGoWQMAOZAzLDyBRkqCFIv4ERUBrikAULIDQA) ]
[Question] [ You must write a program or function that sorts a nested list. Here are the rules for sorting a nested list: Let's take this list as an example: ``` ((5, 2), 2, 7, (2, 1, (3, 4)), 9) ``` Each element in this list has a "priority". An element counts as a number or a sublist. First, get the priority of each element at the same depth. If an element is just a number, its priority is the same as the number itself. If an element is a sublist, its priority is the sum of all the *numbers* in it, not including any sub-sublists. So, the priorities of all the elements of depth **1** are: ``` ( 7 ) 2 7 ( 3 ) 9 ((5, 2), 2, 7, (2, 1, (3, 4)), 9) ``` Sort each element by priority. If there is a tie, you must keep the same order as the original list. ``` 2 ( 3 ) ( 7 ) 7 9 (2, (2, 1, (3, 4)), (5, 2), 7, 9) ``` Repeat for every sublist. So on this sublist ``` (2, 1, (3, 4)) ``` Our priorities look like: ``` 2 1 ( 7 ) (2, 1, (3, 4)) ``` So sorted, it looks like: ``` (1, 2, (3, 4)) ``` `(3, 4)` is already sorted, so we're done. Repeat for `(5, 2)` which results in `(2, 5)` and we're done! Our final list is: ``` (2, (1, 2, (3, 4)), (2, 5), 7, 9) ``` # Rules: * Highly doubtful, but just in case Mathematica has something for this, no nested list sorting builtins are allowed. Regular sorting functions *are* allowed. * I/O can be in any reasonable format. * Every sublist will contain at least one number or list. Also, sublists can be nested several levels deep. For example, in `(1, 2, (((3))))` the `(((3)))` has a priority of 0, since it has only sublists in it. * Invalid lists (unmatched parentheses, non-numbers, wrong bracket types, negative numbers, etc.) result in undefined behavior. # Test I/O: ``` (1, 2, 3) ---> (1, 2, 3) (1, 2, 6, 3, 9, 8) ---> (1, 2, 3, 6, 8, 9) (4, 3, (2), (1)) ---> ((1), (2), 3, 4) (4, 3, (2), ((1))) ---> (((1)), (2), 3, 4) (5, (1, 2, (9, 8))) ---> ((1, 2, (8, 9)), 5) (3, (1, 2), (2, 1)) ---> (3, (1, 2), (1, 2)) (3, (1, 2, (99)), (2, 1, (34))) ---> (3, (1, 2, (99)), (1, 2, (34))) (7, 2, (1, (9, 12)), (4, 3, 2, (1, 2))) ---> ((1, (9, 12)), 2, 7, (2, 3, (1, 2), 4)) ``` Shortest answer in bytes wins. [Answer] # Python 2, ~~114~~ ~~101~~ ~~78~~ ~~73~~ 62 bytes ``` k=lambda t:t*(t<[])or t.sort(key=k)or sum(z for z in t if[]>z) ``` I *knew* there was a better way to filter lists out. Sorts a python list (and its sublists) in-place. <https://eval.in/540457> thanks @tac for letting me know in-place solutions are acceptable, and @xnor + @feersum for further optimizations! [Answer] # Jelly, 13 bytes ``` fFSµ€Ụị߀µ¹<? ``` [Try it online!](http://jelly.tryitonline.net/#code=ZkZTwrXigqzhu6Thu4vDn-KCrMK1wrk8Pw&input=&args=W1s1LCAyXSwgMiwgNywgWzIsIDEsIFszLCA0XV0sIDld) or [verify all test cases](http://jelly.tryitonline.net/#code=ZkZTwrXigqzhu6Thu4vDn-KCrMK1wrk8PwrDh-KCrOG5hOKCrOG5m-KAnA&input=&args=WzEsIDIsIDNdLCBbMSwgMiwgNiwgMywgOSwgOF0sIFs0LCAzLCBbMl0sIFsxXV0sIFs0LCAzLCBbMl0sIFtbMV1dXSwgWzUsIFsxLCAyLCBbOSwgOF1dXSwgWzMsIFsxLCAyXSwgWzIsIDFdXSwgWzMsIFsxLCAyLCBbOTldXSwgWzIsIDEsIFszNF1dXSwgWzcsIDIsIFsxLCBbOSwgMTJdXSwgWzQsIDMsIDIsIFsxLCAyXV1d). ### How it works ``` fFSµ€Ụị߀µ¹<? Main link. Input: A (list) µ€ Apply the chain to the left to each item B in A. F Flatten B. f Filter; intersect B with flattened B, yielding a list. This returns the numbers in B if B is a list, [B] if B is a number. S Compute the sum of the resulting list. Ụ Sort the indices of A according to the computed sums. ߀ Recursively apply the main link to each B in A. ị Retrieve the items of the list (right) at those indices (left). µ Convert the preceding chain into a single link. ? If: < A compared with itself is truthy: Execute the link to the left. ¹ Else, apply the identity function to A. ``` Comparing (`<`) a number with itself yields **0** (falsy), but comparing a non-empty list with itself yields a list of **0**'s (truthy), so `<` can be used to distinguish numbers from lists. [Answer] # Lua, 172 bytes ``` function p(a)if type(a)~="table"then return a end s(a)local t=0 for i,v in next,a do t=t+p(v)end return t end function s(t)table.sort(t,function(a,b)return p(a)<p(b)end)end ``` The function `s` sorts a Lua table (a data structure that serves as a list among other things in Lua) in place according to the rules. [Answer] # Mathematica, 50 bytes ``` #0/@SortBy[#,Tr@Cases[#,_Integer,{0,1}]&]~Check~#& ``` Simple recursive method that uses `SortBy`. Ignore the messages. [Answer] **Haskell, ~~160~~ ~~151~~ 135 bytes** ``` import Data.List data T=N Int|T[T]deriving Show p(N x)=x p(T t)=sum$[x|N x<-t] f(N x)=N x f(T t)=T$sortBy((.p).compare.p)$map f$t ``` The first problem is nested lists. Haskell requires that all elements of a list have the same type; in particular, an integer and a list of integers aren't the same type. In other words, a variable-nested list *isn't a list, it's a rose tree!* So first, we have to define a data type for rose trees: ``` data T = N Int | T [T] ``` (Strictly, `deriving Show` is only necessary if you want to *see* the results. But that's a technicality.) With this definition in place, we can write a list such as `(1, 2, (3, 4))` as ``` T [N 1, N 2, T [N 3, N 4]] ``` which is considerably less readable. But whatever; it's a trivial, mechanical translation. Prefix every number with `N` and every subtree with `T`. Now we need to compute priorities. This would be easy if the priority of a subtree was simple the sum of *all* elements it contains. That would be a trivial recursive loop. But since it isn't, we need to define *two* functions: one which recurses, and one which does not. ``` p (N x) = x p (T t) = sum $ map q t q (N x) = x q _ = 0 ``` If we were to sum *all* subelements, then `q` would not need to exist, saving a huge number of characters. Oh well! Edit: Actually, several commentors point out that you can avoid `q` using a list comprehension: `[ x | N x <- t]`. Good call, guys! (In fact, `p` would not need to exist either; we could have the compiler auto-generate an `Ord` instance for us in a handful of characters, and this default implementation would match the spec.) Finally, we need to recursive over all sub-trees and sort them: ``` f (N x) = N x f (T t) = T $ sortBy (\ x y -> compare (p x) (p y)) $ map f $ t ``` That is, `f` sorts a tree by recursively applying itself to all elements (`map f`), and then calling the `sortBy` function to sort the top-level. The first line says that sorting a number does nothing, and is necessary to terminate the recursion. [Answer] # CLISP, 380 bytes ``` (defun q(L)(if(null L)L(append(append(q(car(s(cdr L)(car L))))(list(car L)))(q(cadr(s(cdr L)(car L))))))))(defun s(L E)(if(not(atom(car L)))(setq L(cons(q(car L))(cdr L))))(cond((null L)'(nil nil))((<(v(car L))E)(list(cons(car L)(car(s(cdr L)E)))(cadr(s(cdr L)E))))(T(list(car(s(cdr L)E))(cons(car L)(cadr(s(cdr L)E)))))))(defun v(L)(if(atom L)L(apply'+(remove-if-not #'atom L)))) ``` Call the function q with a list. I'm a lisp noob, please don't kill me^^ [Answer] # Pyth, 15 bytes ``` L?sIbbossI#NyMb ``` [Test suite](https://pyth.herokuapp.com/?code=L%3FsIbbossI%23NyMbyQ&input=%28%285%2C+2%29%2C+2%2C+7%2C+%282%2C+1%2C+%283%2C+4%29%29%2C+9%29&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%5D%0A%5B1%2C+2%2C+6%2C+3%2C+9%2C+8%5D%0A%5B4%2C+3%2C+%5B2%5D%2C+%5B1%5D%5D%0A%5B4%2C+3%2C+%5B2%5D%2C+%5B%5B1%5D%5D%5D%0A%5B5%2C+%5B1%2C+2%2C+%5B9%2C+8%5D%5D%5D%0A%5B3%2C+%5B1%2C+2%5D%2C+%5B2%2C+1%5D%5D%0A%5B3%2C+%5B1%2C+2%2C+%5B99%5D%5D%2C+%5B2%2C+1%2C+%5B34%5D%5D%5D%0A%5B7%2C+2%2C+%5B1%2C+%5B9%2C+12%5D%5D%2C+%5B4%2C+3%2C+2%2C+%5B1%2C+2%5D%5D%5D&debug=0) A recursive function, that works as follows: ``` L?sIbbossI#NyMb L define y(b): ?sIb If b is an integer: (invariant under the s function) b Return it. yMb Else, apply y recursively to all of the elements of b, o Then sort b by sI#N For each element, the elements of that list that are integers. This is luckily a nop on integers. s Summed. ``` [Answer] # Java, 219 bytes ``` import java.util.*;List f(List l){l.sort(Comparator.comparing(o->{if(o instanceof Integer)return(Integer)o;f((List)o);return((List) o).stream().filter(i->i instanceof Integer).mapToInt(i->(Integer)i).sum();}));return l;} ``` With line breaks: ``` import java.util.*; List f(List l){ l.sort(Comparator.comparing(o -> { if (o instanceof Integer) return (Integer) o; f((List) o); return ((List) o).stream().filter(i -> i instanceof Integer).mapToInt(i -> (Integer) i).sum(); })); return l; } ``` There's a lot of casting going on which really racks up the byte count. :P Integer values are fed into a Comparator, and nested lists are sorted first before the sum of only the integer values are given to the Comparator. These values are how the Comparator determines their position within the list when it is sorted. Try it [here](http://ideone.com/XlmRPt). [Answer] ## JavaScript (ES6), 86 bytes ``` f=a=>a.map?a.map(f).sort((a,b)=>p(a)-p(b),p=a=>a.map?a.map(a=>t+=a.map?0:a,t=0)|t:a):a ``` All that array checking :-( ]
[Question] [ # Challenge Given a list of integers, return the list of these integers after repeatedly removing all pairs of adjacent equal items. Note that if you have an odd-length run of equal numbers, one of them will remain, not being part of a pair. ### Example: ``` [0, 0, 0, 1, 2, 4, 4, 2, 1, 1, 0] ``` First, you should remove `0, 0`, `4, 4`, and `1, 1` to get: ``` [0, 1, 2, 2, 0] ``` Now, you should remove `2, 2`: ``` [0, 1, 0] ``` And this is the final result. # Test Cases ``` [] -> [] [1] -> [1] [1, 1] -> [] [1, 2] -> [1, 2] [11, 11, 11] -> [11] [1, 22, 1] -> [1, 22, 1] [-31, 46, -31, 46] -> [-31, 46, -31, 46] [1, 0, 0, 1] -> [] [5, 3, 10, 10, 5] -> [5, 3, 5] [5, 3, 3, 3, 5] -> [5, 3, 5] [0, -2, 4, 4, -2, 0] -> [] [0, 2, -14, -14, 2, 0, -1] -> [-1] [0, 0, 0, 1, 2, 4, 4, 2, 1, 1, 0] -> [0, 1, 0] [3, 5, 4, 4, 8, 26, 26, 8, 5] -> [3] [-89, 89, -87, -8, 8, 88] -> [-89, 89, -87, -8, 8, 88] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Œgœ^/€FµÐL ``` [Try it online!](https://tio.run/##y0rNyan8///opPSjk@P0HzWtcTu09fAEn/@H24Hso5Me7pwBpCP//4@OjtVRiDYEEzoKMNoITIMEwBgmagRVoWsM5JmY6ShAGVB5AzACqzDVUTAGMg0g2BQhBEFgAaCELtBEEzACsQygokCmrqEJlDACG6prCJWD2gEWh@g0AnMNodpBhsNkLICSZhBsAbIzFgA "Jelly – Try It Online") ### How it works ``` Œgœ^/€FµÐL Main link. Argument: A (array) µ Combine all links to the left into a chain. Œg Group all adjacent equal items. /€ Reduce each group by... œ^ symmetric multiset difference. In each step, this maps ([], n) to [n] and ([n], n) to [], so the group is left with a single item if its length is odd, and no items at all if its length if even. F Flatten the resulting array of singleton and empty arrays. ÐL Apply the chain until the results are no longer unique. Return the last unique result. ``` [Answer] # Mathematica 29 bytes This repeatedly removes pairs of equal adjacent elements, `a_,a_` until there are none left. ``` #//.{b___,a_,a_,c___}:>{b,c}& ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~17~~ 15 bytes ``` +m`^(.+)¶\1$¶? ``` [Try it online!](https://tio.run/##K0otycxL/P9fOzchTkNPW/PQthhDlUPb7Ln@/4@3sOQCongLcy5TIIw3AiMgL94CiCwA "Retina – Try It Online") Saved 2 bytes thanks to Neil and Martin! Replaces each pair of numbers with nothing. This process loops until no changes are made. [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` r=[] for x in input():r+=x,;r[-2:]*=r[-2:-1]!=[x] print r ``` [Try it online!](https://tio.run/##JcdNCoAgEEDhfaeYdv0oqLQy5iTDbCM3KoOBnd7E4IPHy2@5U3StCRJPVxKoEGKXn7KsXnas6hTSzvOGo9ryjFR5yhJiAWmNjIKfVeAUHIMb2xn@AA "Python 2 – Try It Online") Iteratively constructs the output list by appending the next element, then chopping off the end if the appending element equals the one before it. Checking the second-to-last element `r[-2:-1]!=[x]` turns out awkward because it's possible the list has length only 1. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` Œr;ṪḂ$$€x/€FµÐL ``` [Try it online!](https://tio.run/##y0rNyan8///opCLrhztXPdzRpKLyqGlNhT6QcDu09fAEn////0cb6hjpGOuYAKGRjqGOYSwA "Jelly – Try It Online") # Explanation ``` Œr;ṪḂ$$€x/€FµÐL Main Link Œr Run-length encode ; Concatenate (?) € For each element ṪḂ$$ Is the last element odd? € For each element // Non-breaking alternative x/ Reduce by repeating // for run-length decode F Flatten µ (New monadic link) ÐL Repeat until results are no longer unique ``` -1 byte thanks to miles, and fixed :) [Answer] ## JavaScript (ES6), ~~54~~ 53 bytes *Saved 1 byte thanks to @ThePirateBay* ``` f=a=>1/a.find(q=>q==a[++i],i=-2)?f(a,a.splice(i,2)):a ``` Naive recursive solution, may be improvable. [Answer] # [Python 2](https://docs.python.org/2/), 73 bytes Since I do not have enough reputation to comment: I just changed @officialaimm 's answer to use r!=[] instead of len(r) to save a byte. Very clever solution to you, @officialaimm ! ``` r=[] # create list that will hold final results. A new list is important because it needs to be removable. for i in input(): if r!=[]and r[-1]==i:r.pop() # Ensure that we have at least 1 char added to the list (r!=[])... or that the last character of our final result isn't the current character being scanned. If that is, well, remove it from the final list because we do not want it anymore else:r+=[i] # Shorthand for r.append(i). This adds i to the final result print r ``` [Try it online!](https://tio.run/##FYlBCoAgEEX3nmLaJWVQm0zwJOIiKGkgdJhs0elN4f0Hn0dfvlJcSmHrvAiJAQFjhd7cSyMAA3BX2x4PYKdmby0anihRLwWc93MaHqxDL4gxZuBSnNLbCG1Kr031VLT/AQ "Python 2 – Try It Online") It is, again, way too late... why am I even still up? [Answer] # Python, ~~60~~ 58 bytes ``` f=lambda a:a and(a[:1]+f(a[1:]))[2*(a[:1]==f(a[1:])[:1]):] ``` [Try it online!](https://tio.run/##VVDLCsMgELz3K5aeYqsQzaNWSH9EPFhCaKA1IeTSr7erJsHKjs7ODK44f9fX5Crvh@5tP8/eglUI1xdWK26uA55cGUK0uCSp63YtdEQZP0wLWBgd6BPg0oamkx@EQs7FwYMRkbsiS7MKlbqlsJEsV8Y6kg2FCtsyofmXUx0iBhhOqWMFVmYOtozX2ybiEMYzf5sbvXSDiC3PrgnDdldioE2Q2RuYvKOAYPIWtuhKibZRMTEvo1sLS@HMHmcK@OmE@B8 "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` t"Y'oY" ``` For some of the test cases where the result is empty the program exits with an error, but in any case it produces the correct (empty) output. [Try it online!](https://tio.run/##y00syfn/v0QpUj0/Uun//2gDHQUIMtRRMNJRMAEjIzAXiAxiFQA "MATL – Try It Online") Or [verify the test cases with non-empty output](https://tio.run/##PUw7DoAgDN09BWFxgYQiEg7gEVwIMdFd4@L98ZWiyXv0fUqv4znrXh@dxzvrui1rLbQNhYzyPDCFPfPQkHaCCdGoLhDNRk0onXD@EwF7xPhuKfQHxrGUSkAtDg2@WcBhg298RUIXhYlPvw). ### Explanation ``` t % Implicit input. Duplicate " % For each (i.e. do as many times as input size) Y' % Run-length encode. Gives array of values and array of run lengths o % Parity, element-wise. Reduces run-lengths to either 0 or 1 Y" % Run-length decode. Gives array of values appearing 0 or 1 times; % that is, removes pairs of consecutive values % Implicit end. Implicit display ``` Consider input ``` 0 0 0 1 2 4 4 2 1 1 0 ``` Each iteration removes pairs of consecutive pairs. The first iteration reduces the array to ``` 0 1 2 2 0 ``` The two values `2` that are now adjacent were not adjacent in the initial array. That's why a second iteration is needed, which gives: ``` 0 1 0 ``` Further iterations will leave this unchanged. The number of required iterations is upper-bounded by the input size. An empty intermediate result causes the run-length decoding function (`Y"`) to error in the current version of the language; but the ouput is empty as required. [Answer] # x86 Machine Code (32-bit protected mode), 36 bytes ``` 52 8B 12 8D 44 91 FC 8B F9 8D 71 04 3B F0 77 10 A7 75 F9 83 EF 04 4A 4A A5 3B F8 75 FB 97 EB E7 58 89 10 C3 ``` The above bytes of machine code define a function that takes an array as input, collapses adjacent duplicates in-place, and returns to the caller without returning a result. It follows the [`__fastcall` calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall), passing the two parameters in the `ECX` and `EDX` registers, respectively. The first parameter (`ECX`) is a pointer to the first element in the array of 32-bit integers (if the array is empty, it can point anywhere in memory). The second parameter (`EDX`) is a pointer to a 32-bit integer that contains the length of the array. The function will modify the elements of the array in-place, if necessary, and also update the length to indicate the new length of the collapsed array. This is a bit of an unusual method for taking input and returning output, but you really have no other choice in assembly language. [As in C, arrays are actually represented in the language as a pointer to the first element and a length](https://codegolf.meta.stackexchange.com/questions/13210/list-input-in-c-and-length-argument). The only thing a bit weird here is taking the length *by reference*, but if we didn't do that, there would be no way to shorten the array. The code would work fine, but the output would contain garbage, because the caller wouldn't know where to stop printing elements from the collapsed array. **Ungolfed assembly mnemonics:** ``` ; void __fastcall CollapseAdjacentDuplicates(int * ptrArray, int * ptrLength); ; ECX = ptrArray ; ECX = fixed ptr to first element ; EDX = ptrLength push edx ; save pointer to the length mov edx, [edx] ; EDX = actual length of the array lea eax, [ecx+edx*4-4] ; EAX = fixed ptr to last element FindAdjacentPairs: mov edi, ecx ; EDI = ptr to element A lea esi, [ecx+4] ; ESI = ptr to element B FindNext: cmp esi, eax ; is ptr to element B at end? ja Finished ; if we've reached the end, we're finished cmpsd ; compare DWORDs at ESI and EDI, set flags, and increment both by 4 jne FindNext ; keep looping if this is not a pair ; Found an adjacent pair, so remove it from the array. sub edi, 4 ; undo increment of EDI so it points at element A dec edx ; decrease length of the array by 2 dec edx ; (two 1-byte DECs are shorter than one 3-byte SUB) RemoveAdjacentPair: movsd ; move DWORD at ESI to EDI, and increment both by 4 cmp edi, eax ; have we reached the end? jne RemoveAdjacentPair ; keep going until we've reached the end xchg eax, edi ; set new end by updating fixed ptr to last element jmp FindAdjacentPairs ; restart search for adjacent pairs from beginning Finished: pop eax ; retrieve pointer to the length mov [eax], edx ; update length for caller ret ``` The implementation was inspired by [my C++11 answer](https://codegolf.stackexchange.com/a/135840/58518), but meticulously rewritten in assembly, optimizing for size. Assembly is a much better golfing language. :-) *Note:* Because this code uses the string instructions, is *does* assume that the direction flag is clear (`DF` == 0). This is a reasonable assumption in most operating environments, as the ABI typically requires that DF is clear. If this cannot be guaranteed, then a 1-byte `CLD` instruction (`0xFC`) needs to be inserted at the top of the code. It also, as noted, assumes 32-bit protected mode—specifically, a "flat" memory model, where the extra segment (`ES`) is the same as the data segment (`DS`). [Answer] ## Batch, 133 bytes ``` @set s=. :l @if "%1"=="%2" (shift/1)else set s=%s% %1 @shift/1 @if not "%1"=="" goto l @if not "%s:~2%"=="%*" %0%s:~1% @echo(%* ``` I set s to `.` because Batch gets confused if there are only duplicates. I also have to use `shift/1` so that I can use `%0%s:~1%` to set the argument list to the new array and loop. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒgṁLḂ$$€ẎµÐL ``` A monadic link taking and returning lists of numbers. **[Try it online!](https://tio.run/##y0rNyan8///opPSHOxt9Hu5oUlF51LTm4a6@Q1sPT/D5//@/sY6CqY6CCRhZ6CgYmUEwkGkKAA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##y0rNyan8///opPSHOxt9Hu5oUlF51LTm4a6@Q1sPT/D5f3TP4XYgPwuIQahhjo7Co4a5WQ5wfnQsiA9hK@jagWQj//@Pjo7VUYg2BBM6CjDaCEyDBMAYJmoEVaFrDOSZmOkoQBlQeQMwAqsw1VEwBjININgUIQRBYAGghC7QRBMwArEMoKJApq6hCZQwAhuqawiVg9oBFofoNAJzDaHaQYbDZCyAkmYQbAGyMxYA) ### How? ``` ŒgṁLḂ$$€ẎµÐL - Link: list µÐL - perform the chain to the left until no changes occur: Œg - group runs (yield a list of lists of non-zero-length equal runs) $€ - last two links as a monad for €ach run: $ - last two links as a monad: L - length (of the run) Ḃ - modulo 2 (1 if odd, 0 if even) ṁ - mould (the run) like (1 or 0) (yields a list of length 1 or 0 lists) Ẏ - tighten (make the list of lists into a single list) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 34 bytes ``` ó¥ k_l vîò k_l É}Ãc ó¥ l ¥Ul ?U:ß ``` Recursively removes pairs of equal numbers until none exist. [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=86Uga19sIHbDrvIga19sIMl9w2MK86UgbCClVWwgP1U63w==&input=WzAsIDAsIDAsIDEsIDIsIDQsIDQsIDIsIDEsIDEsIDBdCi1R) with the `-Q` flag to format the output array. [Run all test cases](https://codepen.io/justinm53/full/NvKjZr?code=86Uga19sIHbDrvIga19sIMl9w2MK86UgbCClVWwgP1U63w==&inputs=W10=,WzFd,WzEsIDFd,WzEsIDJd,WzExLCAxMSwgMTFd,WzEsIDIyLCAxXQ==,Wy0zMSwgNDYsIC0zMSwgNDZd,WzEsIDAsIDAsIDFd,WzUsIDMsIDEwLCAxMCwgNV0=,WzUsIDMsIDMsIDMsIDVd,WzAsIC0yLCA0LCA0LCAtMiwgMF0=,WzAsIDIsIC0xNCwgLTE0LCAyLCAwLCAtMV0=,WzAsIDAsIDAsIDEsIDIsIDQsIDQsIDIsIDEsIDEsIDBd,WzMsIDUsIDQsIDQsIDgsIDI2LCAyNiwgOCwgNV0=,Wy04OSwgODksIC04NywgLTgsIDgsIDg4XQ==&flags=LVE=) using my WIP CodePen. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` [γʒgÉ}€нÐγ‚€gË# ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@tzmU5PSD3fWPmpac2Hv4QnnNj9qmAVkpx/uVgbKGugoQJChjoKRjoIJGBmBuUBkEAsA "05AB1E – Try It Online") ### Explanation ``` [γʒgÉ}€нÐγ‚€gË# [ # Start infinite loop γ # Group Array into consecutive equal elements ʒgÉ} # Keep the subarrays with an uneven amount of elements €н # Keep only the first element of each subarray Ð # Triplicate the result on the stack γ # Group the top element into consecutive equal elements ‚ # Wrap the top two items of the stack in an array €g # Get the length of each subarray Ë# # Break if they are equal # Implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` [DγʒgÉ}€нDŠQ# ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/2uXc5lOT0g931j5qWnNhr8vRBYHKQFEDHQUIMtRRMNJRMAEjIzAXiAxiAQ "05AB1E – Try It Online") Explanation: ``` [DγʒgÉ}€нDŠQ# Implicit input [ Start infinite loop D Duplicate γ Split into chunks of equal elements ʒ } Filter by g Length É Odd? (0=falsy 1=truthy) € Foreach command н Head D Duplicate Š Push c, a, b Q Equal? (0=falsy 1=truthy) # Break if true (i.e. equal to 1) ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` a!(b:c)|a==b=c a!b=a:b foldr(!)[] ``` [Try it online!](https://tio.run/##VY3NDoIwEITvPMVgPECkCSBqNalPoCePSMyiEo34E3/ixXfHbaGpJrvt7HzbzoEep31dNw35QTnbhh9SqlRbj/xS0az0KlVd69098MO8aM50vEDhTLflBsGaIOa4vZ6r531xQR@Pw/UNwmCAniY9rYwXVKAw9IAcecFXhDyxd4QfmVqpbdM/LHWrYshGNo7QCbcVm7J7owhDnuK2R39uW9ZjLDggM6VV7ABPIsm6IzUBInG4izSofZ@aMXGf6CALJfNx29LlCznlmVvIiT4MlFLTovkC "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~74 70~~ 66 bytes * Thanks @SteamyRoot for 4 bytes: `r` instead of `len(r)` is enough to check emptiness of the list/stack. * Thanks @ovs for 4 bytes: better if condition `[i]==r[-1:]` # [Python 2](https://docs.python.org/2/), 66 bytes ``` r=[] for i in input(): if[i]==r[-1:]:r.pop() else:r+=[i] print r ``` [Try it online!](https://tio.run/##JclBCoAgEEDRvaeYZZKFSivBk4hLpYHQYbJFpzcxeJvPp7edtdje2YcocmVAwDLQ0xbpBGAOGL3nsBkXHe9UaZEC0nUnx6sfUxBjacC9B63gZxRYBcdkZw46fg "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ωoṁ?I↓2εg ``` [Try it online!](https://tio.run/##yygtzv7//3xn/sOdjfaej9omG53bmv7///9oAx0QNNQx0jEBQiMgy1DHIBYA "Husk – Try It Online") A bit shorter than Zgarb's existing answer. ## Explanation ``` ωoṁ?I↓2εg ωo apply the following till a fixed point: g group adjacent values ? ε if the group is a singleton list I leave as is ↓2 otherwise drop 2 elements ṁ concatenate the results of that ``` [Answer] ## Clojure, 100 bytes ``` #(loop[i % j[]](if(= i j)i(recur(mapcat(fn[p](repeat(mod(count p)2)(last p)))(partition-by + i))i))) ``` Not sure if this is the shortest possible. [Answer] ## Bash, 82 bytes ``` cat>b while cat b>a perl -pe 's/(\d+) \1( |$)//g' a>b ! diff a b>c do : done cat a ``` There's probably a way out of all those `cat`s, but I don't know it. [Answer] ## [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ωoṁS↑o%2Lg ``` [Try it online!](https://tio.run/##yygtzv7//3xn/sOdjcGP2ibmqxr5pP///z/aUscUDC11oKxYAA "Husk – Try It Online") ## Explanation ``` ωoṁS↑o%2Lg ω Repeat until fixed point o the following two functions: g a) group adjacent elements ṁ b) map over groups and concatenate: L length of group o%2 mod 2 S↑ take that many elements of group ``` [Answer] # PHP, 81 bytes ``` function f(&$a){for($i=count($a);--$i;)$a[$i]-$a[$i-1]||array_splice($a,$i-1,2);} ``` function, call by reference or [try it online](http://sandbox.onlinephpfunctions.com/code/2dd3555772e46e6cb63d54cfa31a3ee759d82fb2). fails for empty input; insert `$i&&` or `$a&&` before `--$i` to fix. [Answer] # [V](https://github.com/DJMcMayhem/V), 10 bytes ``` òͨ.«©î±î* ``` [Try it online!](https://tio.run/##K/v///Cmw72HVugdWn1o5eF1hzYeXqf1/78BFwgachlxmQChEZBlyGUAAA "V – Try It Online") Compressed Regex: `:%s/\(.\+\)\n\1\n*`. The optional newline is so that it works at the end of the file also. If I assume that there is a newline after the end it would be 8 bytes... but that seems like a stretch [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 84 78 bytes ``` [L.ly1-dsy0<A]sA[LtLtS.ly1+sy]sP[dStrdStr!=Pz1<O]sO[0syzdsz1<Oly0<Azlz>M]dsMxf ``` [Try it online!](https://tio.run/##FYuxCoAwDER/Jc6imFKhgwruLQodS3EwOHUyHWx/vhJ4N9w7ju5mDFwIGmYlaEBQSkDRMhrTgh1TwYG4TMseeQ822@zF9Vwin4F8fiXdelZcjshHmLhUYmlJXjXVzUVi9z2t/Q "dc – Try It Online") Unpacking it a bit, out of order in some attempt at clarity: * `[0syzdsz1<Olydsx0<Alx1+lz>M]dsMxf` The main macro `M` resets counter `y` to 0, retrieves the number of items on the stack, stores this in register `z`, then runs macro `O` if there are at least two items on the stack. Once `O` finishes, it loads counter `y` and copies it into register `x` before checking to make sure `y` is nonzero (meaning stack `.` has data). If this is the case, it runs macro `A`. Finally it checks whether the original stack size is larger than the current stack size and reruns itself if so. Once it has finished, it prints the stack with `f`. * `[dStrdStr!=Pz1<O]sO` Macro `O` temporarily stores the top two items on the stack into stack `t`. It then compares the top two items and runs macro `P` if they are not equal. Finally it checks whether or not there are at least two items on the stack, and runs itself if so. * `[LtLtS.ly1+sy]sP` Macro `P` takes the two items from stack `t`, pushes the top one back onto the main stack, and pushes the following one onto stack `.`. It then increments counter `y`. * `[L.ly1-dsy0<A]sA` Macro `A` takes stack `.` and turns it back into the primary stack. It does that, decrementing counter `y` until there's nothing left to push. Edited for explanation, and to golf off 6 bytes as I was needlessly storing the size of the stack. [Answer] # C++11, 161 bytes ``` #include<vector> #include<algorithm> using V=std::vector<int>;void f(V&v){V::iterator i;while((i=std::adjacent_find(v.begin(),v.end()))!=v.end())v.erase(i,i+2);} ``` The above code defines a function, `f`, that takes a `std::vector<int>` by reference, modifies it in place to collapse adjacent duplicates according to the specification, and then returns. **[Try it online!](https://tio.run/##tZPdbqMwEIWv8VNMU2mFtdAC@VkWCI@Rq0gVC07iVQoVGHoR8ezZ8ThOSLu9bILBPvPN8SFyyrc3f1@W5/OjrMtjX4lsEKVq2pxdheK4b1qpDq856ztZ72Gz7lSVJAbMZK3ydGhkBTt382Pgp02SSCXaAosg0/eDPArXlaanqP4WpajVy07WlTs8/RF7WbvcG54ErjnnD2s7xWdbdMKVnvwZ8XS8JoRMNp1qRYGBGO4Or4X2YCfmTHNtclCiUyV6dLBmDpadE4yeoz/Pz4BzUsI7LbSqdy1MWQ@iqWrWpqQ7aNwBE78o@uB50wjx5ygsVp6dGJTIzyVrGtD1n6hLD@ZYCMxYTsxMZXnHza32BYUWPkZd0KVnwQS9Iqj74eJyiyiZb6KZtwhv6CU3YcY1omV4saaGwK6pS8excIz8yoz4kps65va3jH9jBYcf/9I3wuJ4kuUrgDljypizw8PrFr1qYEhu54ibY0THrGx6BVkGsxPMUhRvHTKBgesYOO5ZSQ2eaRg/OY3beqvs1/fzrSJQm7sD17G@b@uZfpCGf78jQiNu1wrVtzUEKRvP/wA "C++ (gcc) – Try It Online")** Before I checked the byte count, I thought this was pretty svelte code. Over 150 bytes is, however, not so good! Either I'm not very good at golfing, or C++ is not a very good golfing language… **Ungolfed:** ``` #include <vector> #include <algorithm> using V = std::vector<int>; void f(V& v) { V::iterator i; // Use std::adjacent_find to search the entire vector for adjacent duplicate elements. // If an adjacent pair is found, this returns an iterator to the first element of the // pair so that we can erase it. Otherwise, it returns v.end(), and we stop. while ((i=std::adjacent_find(v.begin(), v.end())) != v.end()) { v.erase(i, i+2); // erase this adjacent pair } } ``` [Answer] # PHP, 74 bytes ``` function c(&$a){foreach($a as$k=>$v)$a[$k+1]===$v&&array_splice($a,$k,2);} ``` Function c calls by reference to reduce array. [Try it online](http://sandbox.onlinephpfunctions.com/code/81c4dc0f9acbd77d698e809255e64651d38562e5). Interestingly this works in Php5.6 but not 7. [Answer] # [R](https://www.r-project.org/), ~~57~~ 54 bytes ``` l=rle(scan());while(any(x<-!l$l%%2))l=rle(l$v[!x]);l$v ``` [Try it online!](https://tio.run/##K/r/P8e2KCdVozg5MU9DU9O6PCMTyEvMq9SosNFVzFHJUVU10tSEqMlRKYtWrIjVtAYy/hsogKChgpGCCRAaAVmGCgb/AQ "R – Try It Online") uses a run-length encoding to remove pairs. [Answer] # [J](http://jsoftware.com/), 38 bytes ``` ;@(<@($~2|#)/.~0+/\@,}.~:}:)^:(0<#)^:_ ``` [Try it online!](https://tio.run/##JUzRDoIwEPuVS/BhRAK3wXDu0OxDiIsxEuOLPwD79dlB2qbX5u6@OS@3liSoKahTMmtVd23iczeHZmuT33z98IqnChbz@/X5UbSrn0nJUoc7PX2jRVOREY2hsASDLvaahpEOQ8mAFks9aS60@1xghSkaGgAYIxmKetiFDBc@zunYwnuABad7dmTGQodX0V0JjO4CoXEu/wE) [Answer] # [GNU sed](https://www.gnu.org/software/sed/), 19 + 1 = 20 bytes +1 byte for `-r` flag. ``` : s/\b(\S+ )\1//g t ``` [Try it online!](https://tio.run/##LY3NCsIwEITveYo9KiLJpmldfQ2vgYAo4sWK7fM3ziQys38fm83yuNd6cYvPt12@HmSf1funW2t1KnBLEQltM8dIXAaVNMm/AAcIfJRBNNBjHyi0QUqUBKEEjlGKphYERcn6jb7HX3jV8TmBSZxo47liZ4GLnRBAZrLNn/U1v5d6/P4A "sed 4.2.2 – Try It Online") [Answer] # Pyth, 10 bytes Bit late to the party. ``` ueMf%hT2r8 ``` [Test Suite.](http://pyth.herokuapp.com/?code=ueMf%25hT2r8&input=%5B0%2C+0%2C+0%2C+1%2C+2%2C+4%2C+4%2C+2%2C+1%2C+1%2C+0%5D&test_suite=1&test_suite_input=%5B%5D%0A%5B1%5D%0A%5B1%2C+1%5D%0A%5B1%2C+2%5D%0A%5B11%2C+11%2C+11%5D%0A%5B1%2C+22%2C+1%5D%0A%5B-31%2C+46%2C+-31%2C+46%5D%0A%5B1%2C+0%2C+0%2C+1%5D%0A%5B5%2C+3%2C+10%2C+10%2C+5%5D%0A%5B5%2C+3%2C+3%2C+3%2C+5%5D%0A%5B0%2C+-2%2C+4%2C+4%2C+-2%2C+0%5D%0A%5B0%2C+2%2C+-14%2C+-14%2C+2%2C+0%2C+-1%5D%0A%5B0%2C+0%2C+0%2C+1%2C+2%2C+4%2C+4%2C+2%2C+1%2C+1%2C+0%5D%0A%5B3%2C+5%2C+4%2C+4%2C+8%2C+26%2C+26%2C+8%2C+5%5D%0A%5B-89%2C+89%2C+-87%2C+-8%2C+8%2C+88%5D&debug=0) ]
[Question] [ # The cool stuff The following rosace can help calculate numbers modulo 7. [![enter image description here](https://i.stack.imgur.com/6b7cR.png)](https://i.stack.imgur.com/6b7cR.png) In order to do that, you must start at 0 and turn clockwise a number of steps given by the first digit. Then, for each successive digit, follow the arrow and then turn clockwise the number of steps given by that digit. Here is how you proceed for number 294: 1. You start at circle 0. 2. You turn clockwise the number of steps given by the first digit (which is a 2, you end up at 2). 3. You follow the arrow there (you end up at 6). 4. You turn clockwise the number of steps given by the second digit (which is a 9, you end up at 1). 5. You follow the arrow there (you end up at 3). 6. You turn clockwise the number of steps given by the third number (which is 4, you end up at 0). 7. 294 mod 7 = 0 (meaning 294 is multiple of 7). ([Video explanation if you still didn't get it](https://www.youtube.com/watch?v=vxHrfIom-YA)) # The goal Figure out how that works (I know but I won't tell you). Create a program that takes a number `n` in parameter and that generates a rosace for `mod n`. The rosace can be displayed by any means you want (ASCII, generate PNG, generate SVG, ...) as long as it could be used by a 8 years old child (**so no list of rules, I want a picture**)! You can use strait lines, even if it's a bit less clear than what I made for the example, but you *must* show clearly the numbers that point to themselves with some kind of tail-biting arrow. ## Test cases (I only give the links between the numbers, feel free to edit my question once your program sucessfully generates them) mod 2: ``` 0 -> 0 1 -> 0 ``` mod 3: ``` 0 -> 0 1 -> 1 2 -> 2 ``` mod 4: ``` 0 -> 0 1 -> 2 2 -> 0 3 -> 2 ``` mod 5: ``` 0 -> 0 1 -> 0 2 -> 0 3 -> 0 4 -> 0 ``` mod 6: ``` 0 -> 0 1 -> 4 2 -> 2 3 -> 0 4 -> 4 5 -> 2 ``` mod 7: ``` 0 -> 0 1 -> 3 2 -> 6 3 -> 2 4 -> 5 5 -> 1 6 -> 4 ``` mod 8: ``` 0 -> 0 1 -> 2 2 -> 4 3 -> 6 4 -> 0 5 -> 2 6 -> 4 7 -> 6 ``` mod 9: ``` 0 -> 0 1 -> 1 2 -> 2 3 -> 3 4 -> 4 5 -> 5 6 -> 6 7 -> 7 8 -> 8 ``` mod 10: ``` 0 -> 0 1 -> 0 2 -> 0 3 -> 0 4 -> 0 5 -> 0 6 -> 0 7 -> 0 8 -> 0 9 -> 0 ``` # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. As usual, loopholes and cheats are forbidden. [Answer] # Mathematica, 192 bytes This type of challenge (nontrivial mathematical computation together with high-level graphics output) is what Mathematica is made for! ``` (d=#;r_~t~n_:=r{Sin[#],Cos[#]}&[6.3n/d];m=Mod[10#,d]&;Graphics@{Array[#~Text~t[9,#]&,d,0],Array[Arrow@{t[9,#+1/7],t[9,#+6/7]}&,d],Array[Arrow@BezierCurve@{t[8,#+1/9],{0,0},t[8,m@#-1/9]}&,d]})& ``` Expanded and explained: ``` [1] ( [2] d = #; r_~t~n_ := r {Sin[#], Cos[#]} &[6.3 n/d]; m = Mod[10 #, d] &; [3] Graphics@{ [4] Array[#~Text~t[9, #] &, d, 0], [5] Array[Arrow@{t[9, # + 1/7], t[9, # + 6/7]} &, d], [6] Array[Arrow@BezierCurve@{t[8, # + 1/9], {0, 0}, t[8, m@# - 1/9]} &, d] [7] } [8] ) & ``` Lines 1 and 8 delimit an unnamed function of one argument. Lines 3 and 7 delimit several commands that output graphics. Lines 2 stores the input as `d`; defines a binary function `t` giving the coordinates of a point `n/d` of the way around the circle of radius `r`, clockwise from the top (in the spirit of this site, I saved a byte by rounding 2π to `6.3`!); and defines a unary function `m` calculating the destination of the arrow starting at its argument. Line 4 renders the numbers `0` to `d–1` equally spaced around the circle of radius 9 (the exact radius unimportant, chosen to maximize aesthetics subject to fitting in one byte). Line 5 renders the clockwise straight arrows around the circumference of the circle. The `1/7` and `6/7` leave enough space to read the numbers. Line 6 renders the curved arrows from each number to (10 times the number modulo `d`). `BezierCurve` automatically draws a [Bézier curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve) using the given control points. Fortunately, using the origin as a single interior control point produces reasonable output. Sample output (note that the cases 9, 10, and 11 are trivial in different ways): ## d = 7 [![d=7](https://i.stack.imgur.com/BxtNw.png)](https://i.stack.imgur.com/BxtNw.png) ## d = 8 [![d=8](https://i.stack.imgur.com/tie4V.png)](https://i.stack.imgur.com/tie4V.png) ## d = 9 [![d=9](https://i.stack.imgur.com/qak4K.png)](https://i.stack.imgur.com/qak4K.png) ## d = 10 [![d=10](https://i.stack.imgur.com/InUpy.png)](https://i.stack.imgur.com/InUpy.png) ## d = 11 [![d=11](https://i.stack.imgur.com/ahIo6.png)](https://i.stack.imgur.com/ahIo6.png) ## d = 12 [![d=12](https://i.stack.imgur.com/ctUXZ.png)](https://i.stack.imgur.com/ctUXZ.png) ## d = 13 [![d=13](https://i.stack.imgur.com/QBVgn.png)](https://i.stack.imgur.com/QBVgn.png) ## d = 37 [![d=37](https://i.stack.imgur.com/aKAL3.png)](https://i.stack.imgur.com/aKAL3.png) This last input was chosen because 37 divides 10^3–1, and so the interior arrows (not counting the obligatory self-arrow from 0 to 0) form lots of triangular cycles. [Answer] # Python 2, 294 bytes ``` n=input() r,R="",range(n) for i in R:r+=[" ","__ "][10*i%n==i] r+="\n" for i in R:r+=[" ","|/ "][10*i%n==i] print r print">>".join(map(str,R)) for i in R: o,r=10*i%n,"" for j in R: r+="|" if i<=j<o:r+=">>" elif i>j>=o:r+="<<" else:r+=" " print r ``` Prints the diagram in this format: ``` __ |/ 0>>1>>2>>3>>4>>5>>6 | | | | | | | | |>>|>>| | | | | | |>>|>>|>>|>>| | | |<<| | | | | | | | |>>| | | |<<|<<|<<|<<| | | | | | |<<|<<| ``` I don't know if this format is okay, therefore I'll leave this answer as invalid for the time being. Yay, it's valid! [**Try it on repl.it!**](https://repl.it/EIlx/0) [Answer] # PHP+SVG, 500 Bytes little arrow for connections between same values ``` <svg viewBox=0,0,500,500><def><marker id=t viewBox=0,0,9,9 refX=1 refY=5 orient=auto><path d=M0,0L10,5L0,10z /></marker></def><circle cx=250 cy=250 r=150 fill=#ccc /><?for($i=0;$i<$n=$_GET[n];$i++){$w=deg2rad((($i*10%$n)-$i)*360/$n);echo"<g transform=rotate(".$i*360/$n.",250,250)><path d=M250,110L".(250+(sin($w)*135)).",".(250-cos($w)*145)." fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>$i</text></g>";}?></svg> ``` to see the arrows to the same values I use this color value `rgba(255,0,0,0.3)` . it is a possibility to short it down. expanded ``` <svg viewBox=0,0,500,500> <def> <marker id=t viewBox=0,0,10,10 refX=1 refY=5 markerWidth=5 markerHeight=5 orient=auto> <path d=M0,0L10,5L0,10z /> </marker> </def> <circle cx=250 cy=250 r=150 fill=#ccc stroke=#a00 /> <?php for($i=0;$i<$n=$_GET[n];$i++){ $w=deg2rad((($i*10%$n)-$i)*360/$n); echo"<g transform=rotate(".$i*360/$n.",250,250)> <path d=M250,110L".(250+(sin($w)*135)).",".(250-cos($w)*145)." fill=none stroke=#0f0 marker-end=url(#t) /> <circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /> <text x=250 y=105 text-anchor=middle>$i</text> </g>"; }?> </svg> ``` output for n=45 ``` <svg viewBox=0,0,500,500><def><marker id=t viewBox=0,0,10,10 refX=1 refY=5 markerWidth=5 markerHeight=5 orient=auto><path d=M0,0L10,5L0,10z /></marker></def><circle cx=250 cy=250 r=150 fill=#ccc stroke=#a00 /><g transform=rotate(0,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>0</text></g><g transform=rotate(8,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>1</text></g><g transform=rotate(16,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>2</text></g><g transform=rotate(24,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>3</text></g><g transform=rotate(32,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>4</text></g><g transform=rotate(40,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>5</text></g><g transform=rotate(48,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>6</text></g><g transform=rotate(56,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>7</text></g><g transform=rotate(64,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>8</text></g><g transform=rotate(72,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>9</text></g><g transform=rotate(80,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>10</text></g><g transform=rotate(88,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>11</text></g><g transform=rotate(96,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>12</text></g><g transform=rotate(104,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>13</text></g><g transform=rotate(112,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>14</text></g><g transform=rotate(120,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>15</text></g><g transform=rotate(128,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>16</text></g><g transform=rotate(136,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>17</text></g><g transform=rotate(144,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>18</text></g><g transform=rotate(152,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>19</text></g><g transform=rotate(160,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>20</text></g><g transform=rotate(168,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>21</text></g><g transform=rotate(176,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>22</text></g><g transform=rotate(184,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>23</text></g><g transform=rotate(192,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>24</text></g><g transform=rotate(200,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>25</text></g><g transform=rotate(208,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>26</text></g><g transform=rotate(216,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>27</text></g><g transform=rotate(224,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>28</text></g><g transform=rotate(232,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>29</text></g><g transform=rotate(240,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>30</text></g><g transform=rotate(248,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>31</text></g><g transform=rotate(256,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>32</text></g><g transform=rotate(264,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>33</text></g><g transform=rotate(272,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>34</text></g><g transform=rotate(280,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>35</text></g><g transform=rotate(288,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>36</text></g><g transform=rotate(296,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>37</text></g><g transform=rotate(304,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>38</text></g><g transform=rotate(312,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>39</text></g><g transform=rotate(320,250,250)><path d=M250,110L250,105 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>40</text></g><g transform=rotate(328,250,250)><path d=M250,110L378.39262969985,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>41</text></g><g transform=rotate(336,250,250)><path d=M250,110L329.35100905948,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>42</text></g><g transform=rotate(344,250,250)><path d=M250,110L170.64899094052,367.30746418437 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>43</text></g><g transform=rotate(352,250,250)><path d=M250,110L121.60737030015,205.19253581563 fill=none stroke=#0f0 marker-end=url(#t) /><circle cx=250 cy=100 r=10 fill=rgba(255,0,0,0.3) /><text x=250 y=105 text-anchor=middle>44</text></g></svg> ``` ## 320 Bytes working with rect ``` <svg viewBox=0,0,<?=$w=30+10*$n=$_GET[n]?>,<?=20*$n?>><?for($i=0;$i<$n;$i++)echo"<rect x=0 y=".($y=$i*20)." fill=none width=$w height=20 stroke=grey /><text x=5 y=".($y+17).">$i</text><path d=M".($x=$i*10+25).",".($y+17)."L$x,".($m=($i*10%$n)*20+5)." fill=none stroke=blue /><circle cx=$x cy=$m r=2 fill=#0f0 />"?></svg> ``` expanded ``` <svg viewBox=0,0,<?=$w=30+10*$n=$_GET[n]?>,<?=20*$n?>> <?for($i=0;$i<$n;$i++) echo"<rect x=0 y=".($y=$i*20)." fill=none width=$w height=20 stroke=grey /> <text x=5 y=".($y+17).">$i</text> <path d=M".($x=$i*10+25).",".($y+17)."L$x,".($m=($i*10%$n)*20+5)." fill=none stroke=blue /> <circle cx=$x cy=$m r=2 fill=#0f0 />"?> </svg> ``` output for n=72 ``` <svg viewBox=0,0,750,1440><rect x=0 y=0 fill=none width=750 height=20 stroke=grey /><text x=5 y=17>0</text><path d=M25,17L25,5 fill=none stroke=blue /><circle cx=25 cy=5 r=2 fill=#0f0 /><rect x=0 y=20 fill=none width=750 height=20 stroke=grey /><text x=5 y=37>1</text><path d=M35,37L35,205 fill=none stroke=blue /><circle cx=35 cy=205 r=2 fill=#0f0 /><rect x=0 y=40 fill=none width=750 height=20 stroke=grey /><text x=5 y=57>2</text><path d=M45,57L45,405 fill=none stroke=blue /><circle cx=45 cy=405 r=2 fill=#0f0 /><rect x=0 y=60 fill=none width=750 height=20 stroke=grey /><text x=5 y=77>3</text><path d=M55,77L55,605 fill=none stroke=blue /><circle cx=55 cy=605 r=2 fill=#0f0 /><rect x=0 y=80 fill=none width=750 height=20 stroke=grey /><text x=5 y=97>4</text><path d=M65,97L65,805 fill=none stroke=blue /><circle cx=65 cy=805 r=2 fill=#0f0 /><rect x=0 y=100 fill=none width=750 height=20 stroke=grey /><text x=5 y=117>5</text><path d=M75,117L75,1005 fill=none stroke=blue /><circle cx=75 cy=1005 r=2 fill=#0f0 /><rect x=0 y=120 fill=none width=750 height=20 stroke=grey /><text x=5 y=137>6</text><path d=M85,137L85,1205 fill=none stroke=blue /><circle cx=85 cy=1205 r=2 fill=#0f0 /><rect x=0 y=140 fill=none width=750 height=20 stroke=grey /><text x=5 y=157>7</text><path d=M95,157L95,1405 fill=none stroke=blue /><circle cx=95 cy=1405 r=2 fill=#0f0 /><rect x=0 y=160 fill=none width=750 height=20 stroke=grey /><text x=5 y=177>8</text><path d=M105,177L105,165 fill=none stroke=blue /><circle cx=105 cy=165 r=2 fill=#0f0 /><rect x=0 y=180 fill=none width=750 height=20 stroke=grey /><text x=5 y=197>9</text><path d=M115,197L115,365 fill=none stroke=blue /><circle cx=115 cy=365 r=2 fill=#0f0 /><rect x=0 y=200 fill=none width=750 height=20 stroke=grey /><text x=5 y=217>10</text><path d=M125,217L125,565 fill=none stroke=blue /><circle cx=125 cy=565 r=2 fill=#0f0 /><rect x=0 y=220 fill=none width=750 height=20 stroke=grey /><text x=5 y=237>11</text><path d=M135,237L135,765 fill=none stroke=blue /><circle cx=135 cy=765 r=2 fill=#0f0 /><rect x=0 y=240 fill=none width=750 height=20 stroke=grey /><text x=5 y=257>12</text><path d=M145,257L145,965 fill=none stroke=blue /><circle cx=145 cy=965 r=2 fill=#0f0 /><rect x=0 y=260 fill=none width=750 height=20 stroke=grey /><text x=5 y=277>13</text><path d=M155,277L155,1165 fill=none stroke=blue /><circle cx=155 cy=1165 r=2 fill=#0f0 /><rect x=0 y=280 fill=none width=750 height=20 stroke=grey /><text x=5 y=297>14</text><path d=M165,297L165,1365 fill=none stroke=blue /><circle cx=165 cy=1365 r=2 fill=#0f0 /><rect x=0 y=300 fill=none width=750 height=20 stroke=grey /><text x=5 y=317>15</text><path d=M175,317L175,125 fill=none stroke=blue /><circle cx=175 cy=125 r=2 fill=#0f0 /><rect x=0 y=320 fill=none width=750 height=20 stroke=grey /><text x=5 y=337>16</text><path d=M185,337L185,325 fill=none stroke=blue /><circle cx=185 cy=325 r=2 fill=#0f0 /><rect x=0 y=340 fill=none width=750 height=20 stroke=grey /><text x=5 y=357>17</text><path d=M195,357L195,525 fill=none stroke=blue /><circle cx=195 cy=525 r=2 fill=#0f0 /><rect x=0 y=360 fill=none width=750 height=20 stroke=grey /><text x=5 y=377>18</text><path d=M205,377L205,725 fill=none stroke=blue /><circle cx=205 cy=725 r=2 fill=#0f0 /><rect x=0 y=380 fill=none width=750 height=20 stroke=grey /><text x=5 y=397>19</text><path d=M215,397L215,925 fill=none stroke=blue /><circle cx=215 cy=925 r=2 fill=#0f0 /><rect x=0 y=400 fill=none width=750 height=20 stroke=grey /><text x=5 y=417>20</text><path d=M225,417L225,1125 fill=none stroke=blue /><circle cx=225 cy=1125 r=2 fill=#0f0 /><rect x=0 y=420 fill=none width=750 height=20 stroke=grey /><text x=5 y=437>21</text><path d=M235,437L235,1325 fill=none stroke=blue /><circle cx=235 cy=1325 r=2 fill=#0f0 /><rect x=0 y=440 fill=none width=750 height=20 stroke=grey /><text x=5 y=457>22</text><path d=M245,457L245,85 fill=none stroke=blue /><circle cx=245 cy=85 r=2 fill=#0f0 /><rect x=0 y=460 fill=none width=750 height=20 stroke=grey /><text x=5 y=477>23</text><path d=M255,477L255,285 fill=none stroke=blue /><circle cx=255 cy=285 r=2 fill=#0f0 /><rect x=0 y=480 fill=none width=750 height=20 stroke=grey /><text x=5 y=497>24</text><path d=M265,497L265,485 fill=none stroke=blue /><circle cx=265 cy=485 r=2 fill=#0f0 /><rect x=0 y=500 fill=none width=750 height=20 stroke=grey /><text x=5 y=517>25</text><path d=M275,517L275,685 fill=none stroke=blue /><circle cx=275 cy=685 r=2 fill=#0f0 /><rect x=0 y=520 fill=none width=750 height=20 stroke=grey /><text x=5 y=537>26</text><path d=M285,537L285,885 fill=none stroke=blue /><circle cx=285 cy=885 r=2 fill=#0f0 /><rect x=0 y=540 fill=none width=750 height=20 stroke=grey /><text x=5 y=557>27</text><path d=M295,557L295,1085 fill=none stroke=blue /><circle cx=295 cy=1085 r=2 fill=#0f0 /><rect x=0 y=560 fill=none width=750 height=20 stroke=grey /><text x=5 y=577>28</text><path d=M305,577L305,1285 fill=none stroke=blue /><circle cx=305 cy=1285 r=2 fill=#0f0 /><rect x=0 y=580 fill=none width=750 height=20 stroke=grey /><text x=5 y=597>29</text><path d=M315,597L315,45 fill=none stroke=blue /><circle cx=315 cy=45 r=2 fill=#0f0 /><rect x=0 y=600 fill=none width=750 height=20 stroke=grey /><text x=5 y=617>30</text><path d=M325,617L325,245 fill=none stroke=blue /><circle cx=325 cy=245 r=2 fill=#0f0 /><rect x=0 y=620 fill=none width=750 height=20 stroke=grey /><text x=5 y=637>31</text><path d=M335,637L335,445 fill=none stroke=blue /><circle cx=335 cy=445 r=2 fill=#0f0 /><rect x=0 y=640 fill=none width=750 height=20 stroke=grey /><text x=5 y=657>32</text><path d=M345,657L345,645 fill=none stroke=blue /><circle cx=345 cy=645 r=2 fill=#0f0 /><rect x=0 y=660 fill=none width=750 height=20 stroke=grey /><text x=5 y=677>33</text><path d=M355,677L355,845 fill=none stroke=blue /><circle cx=355 cy=845 r=2 fill=#0f0 /><rect x=0 y=680 fill=none width=750 height=20 stroke=grey /><text x=5 y=697>34</text><path d=M365,697L365,1045 fill=none stroke=blue /><circle cx=365 cy=1045 r=2 fill=#0f0 /><rect x=0 y=700 fill=none width=750 height=20 stroke=grey /><text x=5 y=717>35</text><path d=M375,717L375,1245 fill=none stroke=blue /><circle cx=375 cy=1245 r=2 fill=#0f0 /><rect x=0 y=720 fill=none width=750 height=20 stroke=grey /><text x=5 y=737>36</text><path d=M385,737L385,5 fill=none stroke=blue /><circle cx=385 cy=5 r=2 fill=#0f0 /><rect x=0 y=740 fill=none width=750 height=20 stroke=grey /><text x=5 y=757>37</text><path d=M395,757L395,205 fill=none stroke=blue /><circle cx=395 cy=205 r=2 fill=#0f0 /><rect x=0 y=760 fill=none width=750 height=20 stroke=grey /><text x=5 y=777>38</text><path d=M405,777L405,405 fill=none stroke=blue /><circle cx=405 cy=405 r=2 fill=#0f0 /><rect x=0 y=780 fill=none width=750 height=20 stroke=grey /><text x=5 y=797>39</text><path d=M415,797L415,605 fill=none stroke=blue /><circle cx=415 cy=605 r=2 fill=#0f0 /><rect x=0 y=800 fill=none width=750 height=20 stroke=grey /><text x=5 y=817>40</text><path d=M425,817L425,805 fill=none stroke=blue /><circle cx=425 cy=805 r=2 fill=#0f0 /><rect x=0 y=820 fill=none width=750 height=20 stroke=grey /><text x=5 y=837>41</text><path d=M435,837L435,1005 fill=none stroke=blue /><circle cx=435 cy=1005 r=2 fill=#0f0 /><rect x=0 y=840 fill=none width=750 height=20 stroke=grey /><text x=5 y=857>42</text><path d=M445,857L445,1205 fill=none stroke=blue /><circle cx=445 cy=1205 r=2 fill=#0f0 /><rect x=0 y=860 fill=none width=750 height=20 stroke=grey /><text x=5 y=877>43</text><path d=M455,877L455,1405 fill=none stroke=blue /><circle cx=455 cy=1405 r=2 fill=#0f0 /><rect x=0 y=880 fill=none width=750 height=20 stroke=grey /><text x=5 y=897>44</text><path d=M465,897L465,165 fill=none stroke=blue /><circle cx=465 cy=165 r=2 fill=#0f0 /><rect x=0 y=900 fill=none width=750 height=20 stroke=grey /><text x=5 y=917>45</text><path d=M475,917L475,365 fill=none stroke=blue /><circle cx=475 cy=365 r=2 fill=#0f0 /><rect x=0 y=920 fill=none width=750 height=20 stroke=grey /><text x=5 y=937>46</text><path d=M485,937L485,565 fill=none stroke=blue /><circle cx=485 cy=565 r=2 fill=#0f0 /><rect x=0 y=940 fill=none width=750 height=20 stroke=grey /><text x=5 y=957>47</text><path d=M495,957L495,765 fill=none stroke=blue /><circle cx=495 cy=765 r=2 fill=#0f0 /><rect x=0 y=960 fill=none width=750 height=20 stroke=grey /><text x=5 y=977>48</text><path d=M505,977L505,965 fill=none stroke=blue /><circle cx=505 cy=965 r=2 fill=#0f0 /><rect x=0 y=980 fill=none width=750 height=20 stroke=grey /><text x=5 y=997>49</text><path d=M515,997L515,1165 fill=none stroke=blue /><circle cx=515 cy=1165 r=2 fill=#0f0 /><rect x=0 y=1000 fill=none width=750 height=20 stroke=grey /><text x=5 y=1017>50</text><path d=M525,1017L525,1365 fill=none stroke=blue /><circle cx=525 cy=1365 r=2 fill=#0f0 /><rect x=0 y=1020 fill=none width=750 height=20 stroke=grey /><text x=5 y=1037>51</text><path d=M535,1037L535,125 fill=none stroke=blue /><circle cx=535 cy=125 r=2 fill=#0f0 /><rect x=0 y=1040 fill=none width=750 height=20 stroke=grey /><text x=5 y=1057>52</text><path d=M545,1057L545,325 fill=none stroke=blue /><circle cx=545 cy=325 r=2 fill=#0f0 /><rect x=0 y=1060 fill=none width=750 height=20 stroke=grey /><text x=5 y=1077>53</text><path d=M555,1077L555,525 fill=none stroke=blue /><circle cx=555 cy=525 r=2 fill=#0f0 /><rect x=0 y=1080 fill=none width=750 height=20 stroke=grey /><text x=5 y=1097>54</text><path d=M565,1097L565,725 fill=none stroke=blue /><circle cx=565 cy=725 r=2 fill=#0f0 /><rect x=0 y=1100 fill=none width=750 height=20 stroke=grey /><text x=5 y=1117>55</text><path d=M575,1117L575,925 fill=none stroke=blue /><circle cx=575 cy=925 r=2 fill=#0f0 /><rect x=0 y=1120 fill=none width=750 height=20 stroke=grey /><text x=5 y=1137>56</text><path d=M585,1137L585,1125 fill=none stroke=blue /><circle cx=585 cy=1125 r=2 fill=#0f0 /><rect x=0 y=1140 fill=none width=750 height=20 stroke=grey /><text x=5 y=1157>57</text><path d=M595,1157L595,1325 fill=none stroke=blue /><circle cx=595 cy=1325 r=2 fill=#0f0 /><rect x=0 y=1160 fill=none width=750 height=20 stroke=grey /><text x=5 y=1177>58</text><path d=M605,1177L605,85 fill=none stroke=blue /><circle cx=605 cy=85 r=2 fill=#0f0 /><rect x=0 y=1180 fill=none width=750 height=20 stroke=grey /><text x=5 y=1197>59</text><path d=M615,1197L615,285 fill=none stroke=blue /><circle cx=615 cy=285 r=2 fill=#0f0 /><rect x=0 y=1200 fill=none width=750 height=20 stroke=grey /><text x=5 y=1217>60</text><path d=M625,1217L625,485 fill=none stroke=blue /><circle cx=625 cy=485 r=2 fill=#0f0 /><rect x=0 y=1220 fill=none width=750 height=20 stroke=grey /><text x=5 y=1237>61</text><path d=M635,1237L635,685 fill=none stroke=blue /><circle cx=635 cy=685 r=2 fill=#0f0 /><rect x=0 y=1240 fill=none width=750 height=20 stroke=grey /><text x=5 y=1257>62</text><path d=M645,1257L645,885 fill=none stroke=blue /><circle cx=645 cy=885 r=2 fill=#0f0 /><rect x=0 y=1260 fill=none width=750 height=20 stroke=grey /><text x=5 y=1277>63</text><path d=M655,1277L655,1085 fill=none stroke=blue /><circle cx=655 cy=1085 r=2 fill=#0f0 /><rect x=0 y=1280 fill=none width=750 height=20 stroke=grey /><text x=5 y=1297>64</text><path d=M665,1297L665,1285 fill=none stroke=blue /><circle cx=665 cy=1285 r=2 fill=#0f0 /><rect x=0 y=1300 fill=none width=750 height=20 stroke=grey /><text x=5 y=1317>65</text><path d=M675,1317L675,45 fill=none stroke=blue /><circle cx=675 cy=45 r=2 fill=#0f0 /><rect x=0 y=1320 fill=none width=750 height=20 stroke=grey /><text x=5 y=1337>66</text><path d=M685,1337L685,245 fill=none stroke=blue /><circle cx=685 cy=245 r=2 fill=#0f0 /><rect x=0 y=1340 fill=none width=750 height=20 stroke=grey /><text x=5 y=1357>67</text><path d=M695,1357L695,445 fill=none stroke=blue /><circle cx=695 cy=445 r=2 fill=#0f0 /><rect x=0 y=1360 fill=none width=750 height=20 stroke=grey /><text x=5 y=1377>68</text><path d=M705,1377L705,645 fill=none stroke=blue /><circle cx=705 cy=645 r=2 fill=#0f0 /><rect x=0 y=1380 fill=none width=750 height=20 stroke=grey /><text x=5 y=1397>69</text><path d=M715,1397L715,845 fill=none stroke=blue /><circle cx=715 cy=845 r=2 fill=#0f0 /><rect x=0 y=1400 fill=none width=750 height=20 stroke=grey /><text x=5 y=1417>70</text><path d=M725,1417L725,1045 fill=none stroke=blue /><circle cx=725 cy=1045 r=2 fill=#0f0 /><rect x=0 y=1420 fill=none width=750 height=20 stroke=grey /><text x=5 y=1437>71</text><path d=M735,1437L735,1245 fill=none stroke=blue /><circle cx=735 cy=1245 r=2 fill=#0f0 /></svg> ``` [Answer] # Python 2, ~~540~~ ~~464~~ 431 bytes Some golfing like using shorter variable names, variable substitution, list comprehension and changing everything to white (except the text). Biggest save was changing precomputed positions to dynamically (see `L`). ``` from cv2 import* from numpy import* D=1024 G=zeros((D,D,3),uint8) n=7 w=(1,1,1) R=range(n) c=circle I=int L=lambda i,r=400:(I(sin(2*pi*i/n)*r+D/2),I(D/2-cos(2*pi*i/n)*r)) for i in R: p,q=L(i),L((i*10)%n) line(G,p,L((i+1)%n),w,5) line(G,p,q,w,5) f=lambda z:I(.15*p[z]+.85*q[z]) c(G,[(f(0),f(1)),L(i,450)][p==q],25,w,-1) for i in R: c(G,L(i),50,w,-1) putText(G,`i`,(L(i)[0]-30,L(i)[1]+30),0,2,(0,0,0),2) imwrite('m.png',G*255) ``` `L` calculates the positions of the circles by distance to origin for the big ones containing the numbers and the outer small ones that indicate self pointing. First loop draws the connections: 1st line is the circle around and 2nd line is in the interior, a small circle is added to show direction or self pointing. Second loop puts big circle and number. It is obviously not as nice as the Mathematica answers, but everything made from scratch. [![enter image description here](https://i.stack.imgur.com/IIr9x.png)](https://i.stack.imgur.com/IIr9x.png) [Answer] # Mathematica, ~~124~~ 121 bytes ``` Graph[Join@@Thread[{k->Mod[k+1,#],k->Mod[10k,#]}~Table~{k,0,#-1}],VertexLabels->"Name",GraphLayout->"CircularEmbedding"]& ``` Creates a figure as a graph with directed edges. The graph output now follows the same pattern except counter-clockwise. I prefer Greg Martin's [solution](https://codegolf.stackexchange.com/a/97901/6710) a lot more since the output is much more aesthetically pleasing. A less visually pleasant graph can be generated for **82 bytes** using ``` Graph[Join@@({k->Mod[k+1,#],k->Mod[10k,#]}~Table~{k,0,#-1}),VertexLabels->"Name"]& ``` For *d* = 8, ![figure8](https://i.stack.imgur.com/V5vLp.png) [Answer] ## Python 2 + graphviz, 147 bytes ``` from graphviz import* d=Digraph() k=input() p=d.edge for j in[d.node(`i`,`i`)or i for i in range(k)]: p(`j`,`-~j%k`);p(`j`,`10*j%k`) d.render("o") ``` Doesn't always draw a circle, outputs a pdf file called `o` [![Output for 7](https://i.stack.imgur.com/5BSpS.png)](https://i.stack.imgur.com/5BSpS.png) [Answer] # Haskell, 350 bytes Inspired by @Loovjo, I also use ASCII art. This works for numbers under 100000 (or something like that). ``` g k="\t"++(foldl (++) ""$map (\y->show y++"|") [0..k]) n k=length$g k r z x=(show x)++":\t"++(replicate f ' ')++(replicate d s)++"\n" where y=mod (x*10) z;(a,b)=(min x y,max x y);s=(case compare y x of LT->'<';EQ->'.';GT->'>');f=n (a-1)-1;d=n b-f-2 w z=(g (z-1))++"\n"++(foldl1 (++) (map (r z) [0..(z-1)])) main=do{n<-getLine;putStrLn (w$read n);} ``` Basically you point from x to (x\*10)%n. You can try this [here](http://codepad.org/ESX9bJB4). But since codepad doesn't support input, change **q** to the value of **n** you want, and resubmit. (Note that forking doesn't work, so copy and resubmit from main page). The code submitted there is a bit different, because the above version takes input from console. I hope the output is intuitive. Compression suggestions are welcome (particularly if that beats **294** ;)). [Answer] ## Batch, 394 bytes ``` @echo off set/an=%1-1 set s= for /l %%j in (0,1,%n%)do call:h %%j echo %s% for /l %%i in (0,1,%n%)do call:r %%i %1 exit/b :h set "s=%s%^>%1^>" exit/b :r set/ar=%1*10%%%2 set s= for /l %%j in (0,1,%n%)do call:l %%j %1 echo %s% exit/b :l if %1==%r% set "s=%s%^>%1^<"&exit/b if %2 geq %1 if %1 geq %r% set "s=%s%^<%1%^<"&exit/b if %2 leq %1 if %1 leq %r% goto h set "s=%s% %1 " ``` Escaping in Batch is ugly at the best of times. Example output for 7: ``` >0>>1>>2>>3>>4>>5>>6> >0< 1 2 3 4 5 6 0 >1>>2>>3< 4 5 6 0 1 >2>>3>>4>>5>>6< 0 1 >2<<3< 4 5 6 0 1 2 3 >4>>5< 6 0 >1<<2<<3<<4<<5< 6 0 1 2 3 >4<<5<<6< ``` ]
[Question] [ Generate the sequence *number of bases in which `n` is a palindrome* ([OEIS A126071](https://oeis.org/A126071)). Specifically, the sequence is defined as follows: given a number `n`, express it in base `a` for `a = 1,2, ..., n`, and count how many of those expressions are palindromic. "Palindromic" is understood in terms of reversing the base-`a` digits of the expression as atomic units (thanks, [@Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner)). As an example, consider `n = 5`: * `a=1`: the expression is `11111`: palindromic * `a=2`: the expression is `101`: palindromic * `a=3`: the expression is `12`: not palindromic * `a=4`: the expression is `11`: palindromic * `a=5`: the expression is `10`: not palindromic Therefore the result for `n=5` is `3`. Note that OEIS uses bases `2, ..., n+1` instead of `1, ..., n` (thanks, [@beaker](https://codegolf.stackexchange.com/users/42892/beaker)). It's equivalent, because the expressions in base `1` and `n+1` are always palindromic. The first values of the sequence are ``` 1, 1, 2, 2, 3, 2, 3, 3, 3, 4, 2, 3, 3, 3, 4, 4, 4, 4, 2, 4, 5, ... ``` Input is a positive integer `n`. Output is the first `n` terms of the sequence. The program should theoretically work (given enough time and memory) for any `n` up to limitations caused by your default data type in any internal computations. All functions allowed. Lowest number of bytes wins. [Answer] ## Pyth, 13 bytes ``` mlf_ITjLdSdSQ ``` The brevity of this is mostly due to the `I`nvaluable "`I`nvariant" command. ``` msf_ITjLdSdSQ implicit: Q=input m d map lambda d over SQ Inclusive range 1 to Q jLdSd Convert d to all the bases between 1 and d f filter lambda T: _IT is invariant under reverse l number that are invariant under reverse ``` If `True` is an acceptable output for `1`, `msm_IjdkSdSQ` (12 bytes) works. Try it [here](http://pyth.herokuapp.com/?code=mlf_ITjLdSdSQ&input=10&debug=1). [Answer] # Jelly, 12 bytes ``` bRµ=UP€S RÇ€ ``` [Try it online!](http://jelly.tryitonline.net/#code=YlLCtT1VUOKCrFPCtlLDh-KCrA&input=&args=MTA) An old 14-byte version (The Jelly interpreter had a bug that made converting to unary impossible) ``` bR‘$µ=UP€S RÇ€ ``` [Try it online!](http://jelly.tryitonline.net/#code=YlLigJgkwrU9VVDigqxTClLDh-KCrA&input=&args=MTA) ### How it works ``` bR‘$µ=UP€S Helper link. Argument: z R‘$ Apply range and increment, i.e., map z to [2, ..., z + 1]. In the non-competing version R simply maps z to [1, ... z]. b Convert z to each of the bases to the right. µ Begin a new, monadic chain. Argument: base conversions =U Compare the digits of each base with the reversed digits. = has depth 0, so [1,2,3]=[1,3,3] yields [1,0,1]. P€ Take the product of the innermost arrays. S Sum all resulting Booleans. RÇ€ Main link. Argument: n R Yield [1, ..., n]. Ç€ Apply the helper link to each. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 19 ~~20~~ bytes ``` :"0@XK:Q"K@:YAtP=A+ ``` Uses [current release (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0), which is earlier than this challenge. [**Try it online**!](http://matl.tryitonline.net/#code=OiIwQFhLOlEiS0A6WUF0UD1BKw&input=MTA) ### Explanation ``` : % vector [1,2,...,N], where "N" is implicit input " % for each number in that vector 0 % push 0 @ % push number 1,2,...N corresponding to current iteration, say "n" XK % copy n to clipboard :Q % vector [2,3,...,n+1] " % for each number "m" in that vector K % push n @: % vector [1,2,...,m] YA % express n in base m with symbols 1,2,...,m tP % duplicate and permute =A % 1 if all entries are equal (palindrome), 0 otherwise + % add that number % implicitly close the two loops and display stack contents ``` [Answer] ## ES6, 149 bytes ``` n=>[...Array(n)].map((_,i)=>[...Array(i)].reduce((c,_,j)=>c+(''+(a=q(i+1,j+2,[]))==''+a.reverse()),1),q=(n,b,d)=>n<b?[n,...d]:q(n/b|0,b,[n%b,...d])) ``` Works for bases > 36 too. [Answer] ## CJam, 20 bytes ``` ri{)_,f{)b_W%=}1bp}/ ``` [Test it here.](http://cjam.aditsu.net/#code=ri%7B)_%2Cf%7B)b_W%25%3D%7D1bp%7D%2F&input=20) [Answer] # Python 2, 97 bytes ``` c=1;n=int(input()) for b in range(2,n): a=[];z=n while z:a+=[z%b];z//=b c+=a[::-1]==a print c ``` My first Python post, actually my first Python code at all probably has some golfing potential. [Try it online!](https://tio.run/##DcyxCsMgEADQ2fuKWwpKWoIZDfcl4nBK2gjlImII9edt1je88mv7IcsYiewqlKXpLOVs2hh4HxUjZsHK8tn08hTjQDH5sHYSUNeevxt2xxP5/oi3zjNFUGki9s69bCBiKPVOMcEY9g8) [Answer] # Haskell, 88 bytes ``` a!b|a<b=[a]|1>0=mod a b:(div a b)!b f n=[1+sum[1|x<-[2..y],y!x==reverse(y!x)]|y<-[1..n]] ``` [Answer] # JavaScript (ES6), ~~105~~ 95 bytes ``` f=(n,b)=>b?b<2?1:f(n,b-1)+([...s=n.toString(b)].reverse().join``==s):n<2?[1]:[...f(n-1),f(n,n)] ``` ## Explanation Takes a number from 1 to 36 (the limitation of base conversion in JavaScript) and returns an array of the sequence. Recursive function that checks for palindromes when a base is passed, else returns the sequence if just `n` is passed. ``` f=(n,b)=> // Base palindrome checking b? b<3?1: // return 1 for base-1, since toString(2) f(n,b-1)+( // return the sum of all lower bases and check this [...s=n.toString(b)] // s = n in base b .reverse().join``==s // add 1 if it is a palindrome ) // Sequence generation : n<2?[1]: // return 1 for the first value of the sequence [...f(n-1),f(n,n)] // return the value for n after the previous values ``` ## Test ``` var solution = f=(n,b)=>b?b<2?1:f(n,b-1)+([...s=n.toString(b)].reverse().join``==s):n<2?[1]:[...f(n-1),f(n,n)] ``` ``` <input type="number" oninput="result.textContent=solution(+this.value)" /> <pre id="result"></pre> ``` [Answer] # PHP, 73+1 bytes ``` while(++$i<$argn)$c+=strrev($n=base_convert($argn,10,$i+1))==$n;echo$c+1; ``` works for bases `1` to `36`. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/85ba61651bf57830f7aa8ff228c0b77b5ec28447). [Answer] # PHP, 92+1 bytes: ``` for($b=$c=1;$b++<$n=$argn;$c+=$a==array_reverse($a))for($a=[];~~$n;$n/=$b)$a[]=$n%$b;echo$c; ``` works for all bases. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/0897aa4aa94a4bbad8b7402904ccf2f817d3906a). [Answer] # ><>, 197+2 Bytes +2 for -v flag ``` :1+0v ;n\ 1\ \$:@2(?/ :<~$/?)}:{:*}}@:{{ \ \~0${:} >$:@1(?\::4[:&r&r]:$&@@&%:&@&$@-$,5[1+{]$~{{:@}}$@,$ ~~1 \ \ ?\~0>$:@2(?\$1-:@3+[}]4[}1-]= \ /@@r/!?/ r@+1/)0:< /?/$-1$~< ~$/ \-1 ``` tio.run doesn't seem to return any output for n>1, but you can verify it on <https://fishlanguage.com>. Input goes in the "Initial stack" box. [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` õ_õ!ìZ èêS ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9V/1IexaIOjqUw==&input=OA==) --- ## Explanation ``` õ :Range [1,input] _ :Map each Z õ : Range [1,Z] (let's call each X) !ìZ : Convert Z to a base X digit array è : Count êS : Palindromes ``` [Answer] # [Python 2](https://docs.python.org/2/), 85 bytes ``` def f(a):b,c=2,0;exec'd,m=[],a\nwhile m:d+=[m%b];m/=b\nc+=d[::-1]==d;b+=1;'*a;print c ``` [Try it online!](https://tio.run/##BcFLDsIgFADAtZ6CjSkIRmEJeSehLPhaEnltSBPx9Dhz/M5tRzVnyoUU6pkOIoISL5NHjksSDawTfsXvVj@ZNJ042HYLzrQnhBUjh2S1fkgHkEzgIM1y9@boFU8SZ9k7GaQi6R7fmUqhJNPXS6GDzT8 "Python 2 – Try It Online") Expects an integer as an argument. Explanation: ``` # named function def f(a): # initialize variable to track base (b) and to track palindromes (c) b,c=2,0 # construct code ' # initialize variable to store remainders (m) and to track divisor (d) m,d=[],a # while d is not zero, # add the current remainder to the array # and divide d by the base and assign the result back to d while d:m+=[m%b];d/=b # False == 0 and True == 1, so add 1 to total if m == reversed(m) c+=m[::-1]==m; # increment base # terminate with ; so that next statement can be executed separately b+=1; ' # execute constructed statement (a) times exec'....................................................'*a # print result print c ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` mλṁoS=↔`B¹ḣ)ḣ ``` [Try it online!](https://tio.run/##yygtzv7/P/fc7oc7G/ODbR@1TUlwOrTz4Y7FmkD8//9/UwA "Husk – Try It Online") not sure if I can avoid using a lambda here. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` bRfU$Lµ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z8pKC1UxefQ1kdNa/7//28KAA "Jelly – Try It Online") Alternatively: ``` bRŒḂ€Sµ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z8p6OikhzuaHjWtCT60FUj@///fFAA "Jelly – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 80 bytes ``` n=>(h=(a,g=n=>n?[n%a,...g(n/a|0)]:[])=>--a<2||(g(n).reverse()+''==g(n))+h(a))(n) ``` [Try it online!](https://tio.run/##FYnLDsIgEAC/xnQ3PKw92m79kKaHTQWqNGDA9MS/I14mk5k3n5y39Pp8VYhPUy3VQDPsBCwdNQ2PJVxYaq0dhCuXHtf7siLNSvE0lAIto07mNCkbQNF1RP@EYgdGbFZtTOA93Ubvp6EfhfAetxhyPIw@omtPCtuIWH8 "JavaScript (Node.js) – Try It Online") Add 1 at last manually [Answer] # [Perl 5](https://www.perl.org/) `-Minteger -pa`, 81 bytes ``` map{@n=($t="@F")%$_;push@n,$t%$_ while$t/=$_;$\+="@n"eq"@{[reverse@n]}"}2..$_+1}{ ``` [Try it online!](https://tio.run/##DYpBCsIwEAC/ImEFpTa2SgWRQE7efIFK6WGxgbqNyaqHkK@75jQMMx7D1Ik8B58smRWwUfas1kvoT/4dR0sb4CKL7@gmBN6aEuBWlYsUvpRN14AfDBEt3bPKO62hr9qcRI77w2/27GaKUl863bRNoSPGBwap/fAH "Perl 5 – Try It Online") ]
[Question] [ The cumulative sum of a vector is calculated by simply taking the sum of all previous elements. For instance: ``` vec = [1 1 1 -1 -1 -1 -1 -1 1 1 1 1 -1] cum_vec = [1 2 3 2 1 0 -1 -2 -1 0 1 2 1] ``` Now, impose an upper and a lower limit, meaning that you stop increasing the cumulative sum if it's at the upper limit, and stop decreasing the cumulative sum if it's at the lower limit. A simple example: ``` upper_lim = 2 lower_lim = -1 vec = [1 1 1 -1 -1 -1 -1 -1 1 1 1 1 -1] cum_vec = [1 2 2 1 0 -1 -1 -1 0 1 2 2 1] ``` The input vector consists of integers, not necessarily only `1` and `-1`, both positive and negative. Assume that `upper_lim >= lower_lim`. If the first element of the vector is outside the boundary, jump directly to the boundary (see last example). Write a function that takes a vector of integers as input, and two integers that represent the upper and lower limits. Output the bounded cumulative vector, as defined above. The input can be as either function arguments or from STDIN. Standard code golf rules apply. Examples: ``` upper_lim = 6 lower_lim = -2 vec = [1 4 3 -10 3 2 2 5 -4] cum_vec = [1 5 6 -2 1 3 5 6 2] upper_lim = 100 lower_lim = -100 vec = [1 1 1 1 1 1] cum_vec = [1 2 3 4 5 6] upper_lim = 5 lower_lim = 0 vec = [10 -4 -3 2] cum_vec = [5 1 0 2] upper_lim = 0 lower_lim = 0 vec = [3 5 -2 1] cum_vec = [0 0 0 0] upper_lim = 10 lower_lim = 5 vec = [1 4 6] cum_vec = [5 9 10] | Note, jumped to 5, because 5 is the lower bound. ``` [Answer] # Pyth, 14 bytes ``` t.u@S+Q+NY1vwZ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=t.u%40S%2BQ%2BNY1vwZ&input=6%2C%20-2%0A%5B1%2C%20%204%2C%20%203%2C%20-10%2C%20%203%2C%20%202%2C%20%202%2C%20%205%2C%20-4%5D&input_size=2&test_suite=0&test_suite_input=6%2C%20-2%0A%5B1%2C%20%204%2C%20%203%2C%20-10%2C%20%203%2C%20%202%2C%20%202%2C%20%205%2C%20-4%5D%0A100%2C%20-100%0A%5B1%2C%20%201%2C%20%201%2C%20%201%2C%20%201%2C%20%201%5D%0A5%2C%200%0A%5B10%2C%20-4%2C%20-3%2C%20%202%5D%0A0%2C%200%0A%5B3%2C%205%2C%20-2%2C%201%5D%0A10%2C%205%0A%5B1%2C%204%2C%206%5D) or [Test Suite](http://pyth.herokuapp.com/?code=t.u%40S%2BQ%2BNY1vwZ&input=6%2C%20-2%0A%5B1%2C%20%204%2C%20%203%2C%20-10%2C%20%203%2C%20%202%2C%20%202%2C%20%205%2C%20-4%5D&input_size=2&test_suite=1&test_suite_input=6%2C%20-2%0A%5B1%2C%20%204%2C%20%203%2C%20-10%2C%20%203%2C%20%202%2C%20%202%2C%20%205%2C%20-4%5D%0A100%2C%20-100%0A%5B1%2C%20%201%2C%20%201%2C%20%201%2C%20%201%2C%20%201%5D%0A5%2C%200%0A%5B10%2C%20-4%2C%20-3%2C%20%202%5D%0A0%2C%200%0A%5B3%2C%205%2C%20-2%2C%201%5D%0A10%2C%205%0A%5B1%2C%204%2C%206%5D) ### Explanation ``` t.u@S+Q+NY1vwZ implicit: Q = first input list [upper_lim, lower_lim] .u vwZ for each number Y in the next input list, update N = 0 with: +NY N + Y +Q append this to Q S sort this list @ 1 take the middle element .u returns a list with all intermediate values of N t remove the first value, print the rest ``` [Answer] # CJam, ~~16~~ 15 bytes ``` l~f{\T++$1=:T}` ``` [Try it online](http://cjam.aditsu.net/#code=l~f%7B%5CT%2B%2B%241%3D%3AT%7D%60&input=%5B1%204%203%20-10%203%202%202%205%20-4%5D%20%5B6%20-2%5D) This takes the list as first argument, and the pair of upper/lower limit as a second 2-element list. Example input: ``` [1 4 3 -10 3 2 2 5 -4] [6 -2] ``` The latest version saves 1 byte by sorting the 3 values, and taking the middle value, instead of using a max and min operation. This was also used in Jakube's solution, as well as suggested by Martin. Explanation: ``` l~ Get and parse input. This leaves the value and bounds lists on the stack. f{ Apply block with value (the bounds list). \ Swap new value to top. T Get previous value from variable T (which is default initialized to 0). + Add new value and previous value. + Append new value to bounds list, producing a 3 value list. $ Sort it... 1= And take the middle value. :T Store in variable T for next iteration. } End of apply loop. ` Convert list to string. ``` [Answer] # JavaScript (ES6), 43 bytes ``` (l,u,v,p=0)=>v.map(c=>p=(p+=c)<l?l:p>u?u:p) ``` Defines an anonymous function that takes input in the format `lower bound, upper bound, vector (as JS Array)`. I don't know if it could be any shorter, but I'll try. Suggestions welcome! [Answer] # Haskell, 37 bytes ``` u#l=tail.scanl(((min u.max l).).(+))0 ``` Usage example: `6 # (-2) $ [1,4,3,-10,3,2,2,5,-4]` -> `[1,5,6,-2,1,3,5,6,2]`. Start the sum with `0` to fix initial values out of bounds. Take the `tail` to remove it from the final result. [Answer] ## R, 61 bytes ``` function(x,l,u,s=0)sapply(x,function(i)s<<-min(u,max(l,s+i))) ``` `sapply` is the function to apply a function to every element of a vector (here `x`) but it is usually done in a context where all the evaluations are independent and without side-effect. Here, however, I use the `<<-` operator to make an assignment in the parent/calling environment of `sapply` so that the cumulative sum `s` can be stored outside the iterative evaluations. This is very bad practice... [Answer] # Mathematica, 46 bytes ``` Rest@FoldList[{a,b}Min[a+b,#2]~Max~#3,0,#]& ``` The funny character is U+F4A1 for `\[Function]`. If the first element can be assumed to be in the range, I could save 7 bytes. [Answer] # Julia, ~~44~~ ~~42~~ 38 bytes ``` f(x,l,u,s=0)=[s=clamp(s+i,l,u)for i=x] ``` This creates a function `f` that accepts an array and two integers and returns an array. Ungolfed: ``` function f(v::Array, u::Int, l::Int, s::Int = 0) # The parameter s is the cumulative sum, which begins # at 0 # For each element i of v, define s to be s+i if # l ≤ s+i ≤ u, l if s+i < l, or u if s+i > u x = [s = clamp(s + i, l, u) for i = v] return x end ``` Saved 2 bytes by using ETHproductions' idea of including the cumulative sum as a function parameter and 1 bytes thanks to Glen O. [Answer] # Python 2, 67 Bytes ``` lambda u,l,v:reduce(lambda x,y:x+[max(min(x[-1]+y,u),l)],v,[0])[1:] ``` [Answer] ## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), 30 bytes ``` 0I3-[2g+d0c`,3&x0cd1c`3&x1cdN] ``` This, as a function, assumes the stack has been pre-initialized to `high, low, vector`. The full program is below (**37 bytes**) and takes input as `high, low, vector`. ``` (n$I$)0I4-[2g+d0c`,3&x0cd1c`3&x1cdN]. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%28n%24I%24%290I4-%5B2g%2Bd0c%60%2C3%26x0cd1c%603%26x1cdN%5D%2E&input=10%205%20%5B1%204%206%5D) ### Explanation ``` (n$I$) Read in integers from input until empty 0 Initialize cumulative sum I4-[ ] Loop over vector 2g+ Get the next partial sum d0c`,3&x0c If too high, replace with high d1c`3&x1cd If too low, replace with low N Output as integer . Stop ``` [Answer] ### C 98 bytes It's long, but it works ``` #define P printf( void c(*v,n,u,l,s,c){P"[");while(c++<n)s+=*v++,s=s<u?s>l?s:l:u,P"%d ",s);P"]");} ``` ### Usage example ``` #define P printf( void c(*v,n,u,l,s,c) { P"["); while(c++<n) s+=*v++,s=s<u?s>l?s:l:u,P"%d ",s); P"]"); } int main() { int vec[9] = {1, 4, 3, -10, 3, 2, 2, 5, -4}; int upper = 6, lower = -2, count = 9; c(vec, count, upper, lower, 0, 0); } ``` The output would be ``` [1 5 6 -2 1 3 5 6 2 ] ``` [Answer] # APL, ~~29~~ ~~27~~ 18 bytes As Dennis pointed out in chat, `\` (expand) works from left to right, but applies the function being expanded with from right to left. So we can't just do `1↓(⎕⌈⎕⌊+)\0,⎕`. We work around this by taking the `,\` of the array, and then processing each subarray separately using `/` (fold). ``` 1↓(⎕⌈⎕⌊+)/¨⌽¨,\0,⎕ ``` Input in the order `array, upper bound, lower bound`. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 12 bytes ``` {0(x&y|+)\z} ``` [Try it online!](https://tio.run/##PYs5DoAwDAS/shUkQkZ2Dgr8Feo0FLScbw8OBfLKK409K21rrWW@2O3dcQ9@OZ9axt65SSmoAAmIIOFWCF8yKHl1wqzUluAfw1mNsL2AIoIBNhCbFL67sCKbkzB5X18 "K (oK) – Try It Online") Similar to [lirtosiast's APL answer](https://codegolf.stackexchange.com/a/61715/98547), but with some simplifications. Uses `0` as the seed for a scan over `z`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ż+«⁴»⁵ʋ\Ḋ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//xbsrwqvigbTCu@KBtcqLXOG4iv///1sxLCA0LCA2Xf8xMP81 "Jelly – Try It Online") We can remove the first and last bytes if not for the `[1, 4, 6]` test case. This is a full program which takes the arguments on the command line in the order `vec upper_limit lower_limit` ## How it works ``` Ż+«⁴»⁵ʋ\Ḋ - Main link. Takes a list V on the left And integers U and L on the command line Ż - Prepend a 0 to V ʋ - Group the previous 4 links together into a dyad f(x, y): + - x + y ⁴ - U « - min(x+y, U) ⁵ - V » - max(min(x+y, U), L) \ - Cumulative reduce V by f(x, y) Ḋ - Remove the leading 0 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` å@VwWmX+Y}T ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5UBWd1dtWCtZfVQ&input=WzEgNCA2XQo1CjEw) ]
[Question] [ [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes?wprov=sfla1) is a method for finding prime numbers: take the sequence of all positive integer numbers starting from 2 then for each remaining number drop all its multiples. ``` 2 3 x 5 x 7 x 9 x 11 x 13 x 15 x 17 x ... 2 3 _ 5 _ 7 _ x _ 11 _ 13 _ x _ 17 x ... ``` **Task** Given a number \$n \ge 2\$, find the minimum amount of numbers you have to drop before you can determine whether *n* is a prime number or not using the Sieve of Eratosthenes. For example if you want to check if \$15\$ is prime you start dropping multiples of \$2\$: `2 3 x 5 x 7 x 9 x 11 x 13 x 15 ..` then \$3\$: `2 3 _ 5 _ 7 _ x _ 11 _ 13 _ X ..` Here we are! 15 was dropped so it's not prime. We dropped 8 numbers. Note that we don't need to check more numbers. That is, you don't have to find how many *not-primes* are there. Note also that if the number you are testing is prime then you have to try all numbers up to it( without considering optimizations) , and you have to drop all not primes actually in that case. **Test cases** Terms for *n* from 2 to 100 ``` 0, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 8, 7, 9, 8, 10, 9, 12, 10, 13, 11, 15, 12, 16, 13, 18, 14, 19, 15, 20, 16, 23, 17, 24, 18, 24, 19, 27, 20, 28, 21, 28, 22, 31, 23, 33, 24, 32, 25, 36, 26, 37, 27, 36, 28, 41, 29, 42, 30, 40, 31, 45, 32, 47, 33, 44, 34, 50, 35, 51, 36, 48, 37, 55, 38, 56, 39, 52, 40, 59, 41, 59, 42, 56, 43, 64, 44, 66, 45, 60, 46, 67, 47, 71, 48, 64, 49 ``` **Rules** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the aim is to have the shortest code(in bytes) possible within the respect of golfing rules. This is also [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") so as usual you can output: * *n-th* term. * First *n* terms. * The infinite sequence. Where *n* refers to the actual number you have to check so the sequence starts at \$n = 2\$. You can include 0 and 1, however those are considered undefined behaviour so the result doesn't matter. [Sandbox](https://codegolf.meta.stackexchange.com/a/24646/84844) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~40 68 ...~~ 60 bytes ``` ->n,*w{4.step(n,2){|x|w[-1]==n||w|=[*x.step(n,x/2)]};w.size} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PR6u82kSvuCS1QCNPx0izuqaipjxa1zDW1javpqa8xjZaqwImW6FvpBlba12uV5xZlVr7v0BBw0hPz9DAQFMvN7FAQy1N8z8A "Ruby – Try It Online") Reverse sieve: start with an empty set, add all multiples of numbers in the range (2..n) unless n is in the set. The result is the size of the final set. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅP©÷L€¦®*˜ÙIpigëIk> ``` Outputs the \$n^{th}\$ term. [Try it online](https://tio.run/##ASkA1v9vc2FiaWX//8OFUMKpw7dM4oKswqbCrirLnMOZSXBpZ8OrSWs@//8xNQ) or [verify the first 23 test cases](https://tio.run/##AT0Awv9vc2FiaWX/MjVMwqZ2eT8iIOKGkiAiP3nDkFX/w4VQwqnDt0zigqzCpsKuKsucw5lYcGlnw6tYaz7/fSz/) or [see this for a step-by-step outout](https://tio.run/##VZCxSsRAEIb7e4ohpdwVKWxO9BBBCCiIaCUWm8skGW6zu5fdRG0FH0KwFkSx1D5X@ha@SNxk9lDbne@b/9/RVqSEfR8lyjRuDtF0v/tYTKJDKcHUVKGFFKW@AV0DrhshwWlwJVmgrbB5OOte2EqUwwLrWUYtZeg5ZAzSO0CxLEHnw6PFsHvUP9m9qIWyua4rJkn5IAFX8bS9Bkl2jDph9Bwr3fJ6iSIjVUAMea1ZHcDv@7fumeHTRjoyMhTwRchZjh/A7n2HsWMpnEPFS0Pc1xPPLhWtG8oHdWz8yM9HJS5XQPmff/q7iN/liQlnyb3pZ3Mw2oBQGZjGlqG/Ktz2LmPw3oQCDkr7vALdOItnqbCY@aAMb7dCSP1fm4rNa7I6WPR9vPsD). **Explanation:** ``` ÅP # Get all prime numbers up to and including the (implicit) input © # Store this in variable `®` (without popping) ÷ # Integer-divide the (implicit) input by each of these primes L # Transform each value into a [1,v] ranged list €¦ # Remove the leading 1 from each to make the range [2,v] ®* # Multiply each list by its prime from variable `®` # (we now have a list of lists of prime-multiples up to the input) ˜ # Flatten this list of lists Ù # Uniquify it Ipi # If the input itself is a prime: g # Pop the list and push its length ë # Else: Ik> # Push the input's 1-based index instead # (after which the result is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/), 99 bytes Pretty straightforward implementation of the sieve which stops updating values as soon as `n` has been marked as composite. ``` def f(n): r=[0]*-~n for p in range(2,n):r[p*p::p]=[v>=r[p]|r[n]for v in r[p*p::p]] return sum(r) ``` [Try it online!](https://tio.run/##TcxBCgIxDIXh/Zwiy2ZQqLor1IuELARb7cJMiJ2BAfHqtSMILh/v49e13ic5tXZNGbITDANYJM/j/i0D5MlAoQjYRW7JHXcdGOmoIShHWs6xL34ZCW90@dLfzz2V6mwCz/nhDJtakeoou4KbLv9hOHiPjO0D "Python 3 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 53 bytes ``` .+ $*, $.`$* ^.. +1`(?=.*1$)(,(1+),.*?,)\2+\b $1# # ``` [Try it online!](https://tio.run/##K0otycxL/K@nzaWidWgbF5eKXgKXkWMCl6qGewJEVAcsqKLFFaenx8WlbZigYW@rp2Wooqmho2Goramjp2WvoxljpB2TxKViqMyl/P@/oSkA "Retina 0.8.2 – Try It Online") Link is to test suite that outputs all the values from `2` to `n`. Explanation: ``` .+ $*, $.`$* ^.. ``` List all the values from `2` to `n` in unary with leading commas. ``` 1`(?=.*1$)(,(1+),.*?,)\2+\b $1# ``` Unless `n` has been replaced with a `#`, replace the smallest composite number divisible by the smallest possible prime with a `#`. ``` +` ``` Repeat until either `n` or all the composite numbers have been replaced with a `#`. ``` # ``` Output the number of integers that were replaced with a `#`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḊÆfḢ$ÞẒÐḟ⁸0¦i ``` A monadic Link that accepts an integer, `n`, and yields an integer. **[Try it online!](https://tio.run/##AScA2P9qZWxsef//4biKw4Zm4biiJMOe4bqSw5DhuJ/igbgwwqZp////MTU "Jelly – Try It Online")** ### How? ``` ḊÆfḢ$ÞẒÐḟ⁸0¦i - Link: n Ḋ - dequeue n -> [2,3,4,...,n] Þ - sort by: $ - last two links as a monad: Æf - prime decomposition e.g. 63 -> [3,3,7] Ḣ - head -> minimum prime factor ^ Ðḟ - filter discard those for which: Ẓ - is prime? ¦ - sparse application... 0 - ...to indices: zero (rightmost) ⁸ - ...apply: chain's left argument, n ...(this makes the rightmost entry, if there is one, become n) i - first 1-indexed index of n (zero if n is not found) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 94 bytes ``` c;j;i;*s;f(n){s=calloc(n,4);for(c=j=i=1;++i<n&j!=n;)for(s[j=i]=1;j<n;j+=i)c+=!s[j]++;c-=j!=n;} ``` [Try it online!](https://tio.run/##VZJhb5swEIa/91e4kTpBIBo2NhQ53pdpv6LhA3JMB0udCiI1WpS/Pnbnc9M2Ooh5773nMD67ebZ2Wawe9aDXs@4Tn15mY7vD4WgTn8tU98cpsWY0g@E6y4at/zbeG69T1Ocn0FtIjFuvx8wMqc3MPahtlmm7McF5XQZ/Yi/d4JOUXe4Y/FBw51dnT27/1DLDLkXOIHgIEaLMmQyhQlQhHnNW56wJC16EFRe05FDAEaCiVkUNrYDhDeVEQTmBOYAJSR4RPaImj0CNx398H041ZUneEl8TeCWy4Cprqg3PUCPRDzyJtcCTBTGkolpZE0siC7eJedwrJ4Z8JKZCP6wV9gCeEsRSDfVQsQfmJfAqScyqol4V9savV1PPmhM7@JqrDgdij34@Mfu7m9Zwd/aPm@hcVrvzL7E7Nz/hUqucfX4uV7EaRoEleKaD37szlBU6LrdsHv66Y5@8n3b6PQrrm6IZjBW60wCjCXmfEg80QmVM6C@pDlI4r19VB@pttEJl@2F4ncDSJ6uHPdv8YHB/mHceduVz1uW3jXfGuPYTtp@cS@YoXO@uyz/bH7rnedm8/Qc "C (gcc) – Try It Online") Inputs an integer \$n\ge 2\$. Returns the \$n^{\text{th}}\$ term. [Answer] # [Python](https://www.python.org), 95 bytes ``` f=lambda n:(g:=lambda x:(g([i for i in x if i%min(x)])if n in x else n-len(x))-1)(range(2,n+1)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY349NscxJzk1ISFfKsNNKtYJwKIEcjOlMhLb9IIVMhM0-hQiEzTSFTNTczT6NCM1YTyMmDCKfmFKcq5OnmpIIkNHUNNTWKEvPSUzWMdPK0DTU1odYoFxRl5pVoRKdpZGrCzYQpVDA0MACaCVEKcxkA) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~38~~ 34 bytes -4 bytes by adapting @Kevin Cruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/245976/98547) ``` {(#r)^(0,r:?,/(x<)_'n*/:n:2+!x)?x} ``` [Try it online!](https://ngn.codeberg.page/k/#eJwtkd1unDAQhe/9FFO1UnZbCP4Z2xgq5SV6FyUN2kJYJYtboC2rKH32ztjIA7ZnzvnGhqF5O3ycj48HWczNXVEdtq/H7zfT56qZGv3lw3a8296FmBsJEhQNTcMA0rA0HI0aPAR6K0mT0jwrA4rENm1d2lIdQQVOaslJTUkPGrmkU0l7LmnaqvSmRoplxrDAUGcLhowOjGcxr2tA0gRAEktAyRa0LEbPRiQjHZXydFzFFqzZbklTgyVUAKvZaAOjbEJRHg04ZLtzDHQEp8t6xnrFEK4GIdbm7dP99d/cDACwtU/xpT08Dd35td3aazsfH97FenNPXzKEdn4QohLjuv5cmqo6xR/9c3wdbpe1O73022nspuf+9hQv1a/f/bKe47RUGm3wWI3xb3nppmu5nPs/fRmHsp+7NS7r2E/9Uo7ndRHiWz9fFhjiDBMMc7zQn1oj/Q4phCyAQqXQKUwBmMKmcCnqAnwBIS2UTCul81KRQTHA7jm351hKGBVyTctc01wjmMas0btG+6zRnFP7zOdR2WNM1ho+JvEMs+gxPnvTnjzIeuIhe4mHMjPQZi/6zEJm8TW5zndVmYF1ZlrW09pyD+JZnVk25B5278F1JJ7DzHQu93Lcm7+ezz29yuykC+I/kA6z1Q==) Outputs the *n-th* term (referred to within the code as `x`). * `(...)?x` find the 0-based index of `x` in the list generated by `(...)` (returning `0N`, the integer null, if `x` is not present) * `(...)` + `n:2+!x` generate the sequence `2..n+1`, storing in `n` + `n*/:n` calculate a multiplication table of these values + `(x<)_'` drop values larger than `x` from each row + `r:?,/` flatten, then uniquify the remaining values, storing in `r` + `0,` prepend a 0 (guaranteed to not already be present) to end up returning 1-based indices * `(#r)^` replace nulls (i.e. prime `x`s) with the count of the list (i.e. the number of non-prime numbers smaller than `x`) [Answer] # JavaScript (ES6), ~~67 61~~ 55 bytes *Saved 6 bytes thanks to @tsh* ``` n=>(g=j=>!g[j]*(j>i)+(n-j&&g(g[j]=j+i>n?++i:j+i)))(i=2) ``` [Try it online!](https://tio.run/##FcjBCoMwDADQX@kumqwzB28OUtl3iIzitCS4VHQM9vXddns8je94TLtsr8byYy4LF@MAiZXDKQ06nkGDoAdrtKoS/IvVS7Dee7n@hIgg3GKZsh15nWnNCQYiuu17/EDX4UjPuAHcL07QcXALiPOuRSTNYlC7GrF8AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = input g = // g is a recursive function taking: j => // j = current number being tested !g[j] * // increment the final result if g[j] is not set (j > i) + ( // and j is greater than i (i.e. when testing // multiples of i, we don't count i itself) n - j && // unless j is equal to n, g( // do a recursive call: g[j] = // mark j as dropped j + i > n ? // if j + i is beyond n: ++i // increment i and restart : // else: j + i // keep going with j + i ) // end of recursive call ) // )(i = 2) // initial call to g with i = j = 2 ``` [Answer] # [Python](https://www.python.org), 76 bytes ``` f=lambda n,*s,t=2:len({*s})if n in[*s,t]else f(n,*s,*range(t+t,n+1,t),t=t+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3fdJscxJzk1ISFfJ0tIp1SmyNrHJS8zSqtYprNTPTFPIUMvOiQeKxqTnFqQppGmBVWkWJeempGiXaJTp52oY6JZpAfSXahppQM5ULijLzSjSi0zQyNdPyixQygYYoQLQY6SgYGhhoxkKVwpwBAA) [Answer] # [Haskell](https://www.haskell.org/), 69 bytes ``` f n=n-n![2..n] n!(h:t)|n`elem`t=1+n![x|x<-t,x`mod`h>0]|1>0=2+length t ``` [Try it online!](https://tio.run/##LZBNboNADIX3PYUjddEqJBp7/kJVcpEKCaSSEhWmUTsLFtyd2mOkhzB@z59nGPu/72Gatu0GqUmndPig8zm1T@nwMr7l1zV1wzTMXW7wyN6yLu@nXC3d/PPZjVfTrng1DR2nIX3lEfI29/cEDTx@7ynDM8z9A25CRGPazVTAwiIqshW4Il8Uii4VxArqUqApFZKWyAMoAL/3wt6TKGOwVo@MeiQew8hphvYMRc2Q9HB/y3lQZ6zVrJVjMs8Kix8bdbZ884yTPPOczDLPGWU4r7MuKssJS64pvtwVleEuyvSS59rLDuZ5UpavdYffd4jvmBecMkPQXUF2y9@LujOiskuu/gc "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` Nθ≔…·²θη≔LηζW№ηθ«≔Φη﹪κ⌊ηη≦⊖ζ»I⁻ζLη ``` [Try it online!](https://tio.run/##RY7LCsIwEEXX9iuynEBdKLjqSipCwYr4B7EdmmCStnlUqPjtccSis7pczj1MI4VreqFTquwQwzmaGzoYeZHtvVedhco2Ono14VXYDmGbs5HnTP6BE9ouSJDUztQ@pNLIoOyjDSA/NGfPbLXAR6UD@amv@zbqHu6UlFUmGjLwxbyqxbAMDtg4NGgDtl//K7s4RepS@AA0jR7mnP2eoCtS2uzSetJv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔…·²θη ``` Start with the list of integers from `2` to `n`. ``` ≔Lηζ ``` Store its length as we need to adjust for each prime we remove. ``` W№ηθ« ``` Repeat while `n` is found in the list. ``` ≔Φη﹪κ⌊ηη ``` Remove all multiplies of the lowest prime remaining in the list from the list. ``` ≦⊕ζ ``` Since this also removes the prime, don't count it as one of the integers that was dropped. ``` »I⁻ζLη ``` Output the number of integers that were dropped. ]
[Question] [ # Introduction You can skip this part if you already know what a cyclic group is. A group is defined by a set and an associative binary operation \$\times\$ (that is, \$(a \times b) \times c = a \times (b \times c)\$. There exists exactly one element in the group \$e\$ where \$a \times e = a = e \times a\$ for all \$a\$ in the group (**identity**). For every element \$a\$ in the group there exists exactly one \$b\$ such that \$a \times b = e = b \times a\$ (**inverse**). For every two elements \$a, b\$ in the group, \$a \times b\$ is in the group (**closure**). We can write \$a^n\$ in place of \$\underbrace{a\times a\times a\times ...\times a}\_{n \text{ times}}\$. The cyclic subgroup generated by any element \$a\$ in the group is \$<a> = \{e, a, a^2, a^3, a^4, ..., a^{n-1}\}\$ where \$n\$ is the order (size) of the subgroup (unless the subgroup is infinite). A group is cyclic if it can be generated by one of its elements. # Challenge Given the Cayley table (product table) for a finite group, determine whether or not it's cyclic. # Example Let's take a look at the following Cayley table: ``` 1 2 3 4 5 6 2 3 1 6 4 5 3 1 2 5 6 4 4 5 6 1 2 3 5 6 4 3 1 2 6 4 5 2 3 1 ``` (This is the Cayley table for Dihedral Group 3, \$D\_3\$). This is 1-indexed, so if we want to find the value of \$5 \times 3\$, we look in the fifth column on the third row (note that the operator is not necessarily commutative, so \$5 \times 3\$ is not necessarily equal to \$3 \times 5\$. We see here that \$5 \times 3 = 6\$ (also that \$3 \times 5 = 4\$). We can find \$<3>\$ by starting with \$[3]\$, and then while the list is unique, append the product of the last element and the generator (\$3\$). We get \$[3, 3 \times 3 = 2, 2 \times 3 = 1, 1 \times 3 = 3]\$. We stop here with the subgroup \$\{3, 2, 1\}\$. If you compute \$<1>\$ through \$<6>\$ you'll see that none of the elements in the group generate the whole group. Thus, this group is not cyclic. # Test Cases Input will be given as a matrix, output as a truthy/falsy decision value. ``` [[1,2,3,4,5,6],[2,3,1,6,4,5],[3,1,2,5,6,4],[4,5,6,1,2,3],[5,6,4,3,1,2],[6,4,5,2,3,1]] -> False (D_3) [[1]] -> True ({e}) [[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]] -> True ({1, i, -1, -i}) [[3,2,4,1],[2,4,1,3],[4,1,3,2],[1,3,2,4]] -> True ({-1, i, -i, 1}) [[1,2],[2,1]] -> True ({e, a} with a^-1=a) [[1,2,3,4,5,6,7,8],[2,3,4,1,6,7,8,5],[3,4,1,2,7,8,5,6],[4,1,2,3,8,5,6,7],[5,8,7,6,1,4,3,2],[6,5,8,7,2,1,4,3],[7,6,5,8,3,2,1,4],[8,7,6,5,4,3,2,1]] -> False (D_4) [[1,2,3,4,5,6],[2,1,4,3,6,5],[3,4,5,6,1,2],[4,3,6,5,2,1],[5,‌​6,1,2,3,4],[6,5,2,1,‌​4,3]] -> True (product of cyclic subgroups of order 2 and 3, thanks to Zgarb) [[1,2,3,4],[2,1,4,3],[3,4,1,2],[4,3,1,2]] -> False (Abelian but not cyclic; thanks to xnor) ``` You will be guaranteed that the input is always a group. You may take input as 0-indexed values. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11 10~~ 9 bytes ``` VS≡`ȯU¡!1 ``` 1-based. Returns the index of a generator if one exists, 0 otherwise. [Try it online!](https://tio.run/##ZVC7DcJADO2ZAjqQ3Nwnl@yBoDmdRImEaIgYADrGyAR0DJCKObLIYT9bRIjmfO/Zfs/28dqf6vK87qf77bIZX3W/nR7D4f3cjcPK1VpzduQpUKSGUqEsf0dJMCP5e8lQZIQaMIERWFR7RuiAkitlwar6qrbpRs6JZrSeaFpSGfineUQ4IKISkXVME1U/DpispW52UmxbqBMwtjRnxdRim47zsl00z0TKeeWYkbxwQTlmtKfRnv@JdE5k03cSuyGmAI9Oved8L@PhXD4 "Husk – Try It Online") ## Explanation ``` V Does any row r of the input satisfy this: ¡! If you iterate indexing into r ` 1 starting with 1 ȯU until a repetition is encountered, S≡ the result has the same length as r. ``` [Answer] # [J](http://jsoftware.com/), 8 bytes ``` 1:e.#@C. ``` [Try it online!](https://tio.run/##hVBLCsIwEN33FA9dFEGK@TQNwYLgNRQXYhE3Lrr27DHJTNKoCxd56ft0ZjIPP80YHXYIxwt369aHY@c3zapDO42uxRYvh2lumtv1/sSEvcPF4HyCgISCRg@TvkS4I1PJ6RMjl5KkkEvJ9FddV6S6taLrToSCUTKqn7wq3pKOGqGu8zLXl5997fcLB9jSn1hf5iBm8jzMhoA2YHy/Tp0NK5KVgRXFimWF0uLPxqmG4TnynrMW/WX3umjB9/4N) ## Explanation ``` 1:e.#@C. Input: matrix M C. Convert each row from a permutation to a list of cycles #@ Number of cycles in each row 1: Constant function 1 e. Is 1 a member of the cycle lengths? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes ``` ị"⁸$ÐĿ«/E€Ẹ ``` [Try it online!](https://tio.run/##bVC7DcJADO2ZAiFKSyh3l88CTHG6kgZlAUpoKGjYAwaIoEAiLJIsctjPJkiIyn7P9nu2t5u23eU83E@Lcd8t@/Pr8bys1uPhOty63B85yTnGWJAjT4FKqhJFyQuqBDOS3EmFAiP0gPGMwKLbMcIElIqUaDZn3U9UfdMOXBfdYHPB9LTXc64diPBBRC8iK0266PvxwY41NV8/xXaP@gHjXvNXTDXuargudwbzrUg5pxwzUhfOK8eMzpQ6828n3RX1atrF/ok9wGNWf/v9m/HwTukN "Jelly – Try It Online") [Answer] ## JavaScript (ES6), 52 bytes ``` a=>a.some(b=>!a[new Set(a.map(_=>r=b[r],r=0)).size]) ``` [Answer] # [Python 2](https://docs.python.org/2/), 96 91 97 bytes ``` lambda x:any(g(r,r[i],i+1)==len(r)for i,r in enumerate(x)) g=lambda x,y,z:y==z or 1+g(x,x[y-1],z) ``` [Try it online!](https://tio.run/##XVHLboQwDDzDV3BMtO4hgX0IKV@SRhVtA0Xaza4ClYCfp7HNslIPyJnxzGDLj3n8uQe9tuZ9vTa3z@@mmOomzKITEaLtHfQHJY25@iCibO@x6CF9ofDh9@ZjM3oxSZl35mmGGZZ6NmYpklYdOjHBZOc35WCR6@iH8eOrGfxQmMLmmbUKNJRQwRFODiy@FZwQJ4RvjR2oEiINMWVCxJJaJ0QOSlLOAeU@K@dv2VXqY261@aotb9eS7p@X/nuGyyuD8TYjZxCmHbZMxnCmWS@pj7PjxDwvc5q5xGAfuZK5xLDnyJ59JnzzFlTJS5VyqSY3azXpcCuXZy7H4@0HwBO@rlHn2SP2YRSt2Ekp1z8) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` JŒ!ị@€µṂ⁼Jṙ'’$$ ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//SsWSIeG7i0DigqzCteG5guKBvErhuZkn4oCZJCT///9bWzEsMl0sWzIsMV1d "Jelly – Try It Online") First silly idea that came to mind: check for isomorphism to **Zn**. (This code is *O*(n!)…) ``` JŒ!ị@€ Generate all ways to denote this group. (by indexing into every permutation of 1…n) µṂ⁼ Is the smallest one equal to this? Jṙ'’$$ [[1 2 … n ] [2 3 … 1 ] (the group table for Z_n) [… … … … ] [n 1 … n-1]] ``` [Answer] # [R](https://www.r-project.org/), ~~101~~ 97 bytes ``` function(m)any(sapply(1:(n=nrow(m)),function(x)all(1:n%in%Reduce(`[`,rep(list(m[x,]),n),x,T,T)))) ``` [Verify all test cases](https://tio.run/##jVHLboMwELznKyJLkdbS9sAjJKqaT@gl4uYghaYQIRGDDLTk6@l67RBVatpyMTPrmZ1dm6kfjE6b/Wvem2pcvjwty0Gf@qrR0Mkeurxt6ysUH3kNbW66AvrduRveQBwOmUAhBd6gIlhXXQ8CO0kfDtpCKReLknyn2fcic329OQfPoHfaNJ9ES5zvjDKvayrqVaVX@@J9OBVwVEc0RQvc5KJGzCRqiSOmmNqGUwnfhgGhVIAhRhjjGpMMlf0PMLGYkP0PbQVjQnyHmYgQs3w7JMQKdgqyTNBEP3V6XHEZfP@YPGzv2HvHvucjdURVp@GT0/HJaj7J@5ferPwzHU@/we09pcN@Uy4lY96kT@0wbnhjW6rbDcY@W4KOCx1HjK1bLnIcMU6zdpr/pXTzsCKZ0/m342TMs5t7x/v@Pc9pbKfpCw "R – Try It Online") This simply computes `<g>` for each `g \in G` and then tests if `G \subseteq <g>`, then checks if any of those are true. However, since we're always applying `$g` on the right, we replicate `m[g,]` (the `g`th row) and then index into that row with the result of applying `$g`, accumulating the results rather than using `m[g,g$g]` every time, which saved about 4 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` JịƬ"ZẈiL ``` [Try it online!](https://tio.run/##bVKxTsMwEN37FSdYiHQZkrihEmJAQgyIkalRQE4a2kAUV04iqFAXFpDYmPiI/gAwIviP8iPBPrs0FIbIfs@@957vcpkVxaxtj5dvj5@LreHy9SE/ad/vv@4WH0/Ll@e2jXpR5KGPATLsYxhjpPcehhorpPe@PkGmEN0hJlCIWLrtK0QVpOTFMcI2HPGiymDn8DxwtIkhT2WjuNts7qyNrSlThdqQWUFmjbp1HkKO4KrFzUkiUFdMIa2Ui1aSoFUZdCVcq6E@b5WCyjcSIvA5XOf1BPiZ6@1z53encBcH6@AG246Z4ISpo/YhBuMudW6gznUnmU0aouF8wylGn2suMJxiTE3f1PzpMnP@GaUxCH@C2fFRKOJJyIxyPQ3LU5BOT6ZSjJq0BnEB6Swt8hSqJhlL0UwrzQk5yiT4wMsRBAj1hJdXFdQChmMuk815r57Znbf5lbrPOkiyIuclJE0Npait715H/KYU0unF3w "Jelly – Try It Online") Outputs `0` for False and a non-negative integer for True Jelly finally ties J! ## How it works ``` JịƬ"ZẈiL - Main link. Takes the Cayley matrix n×n M on the left Z - Transpose M J - Yield [1, 2, ..., n] Ƭ - Until reaching a fixed point, do the following and replace i with the result " - Pair each i (intially 1,2...,n) with each row, then do the following: ị - Take the i'th element of each row Ẉ - Get the length of each L - Yield n i - Index of n in the lengths, or 0 if not present ``` [Answer] ## Clojure, 68 bytes ``` #(seq(for[l % :when(apply distinct?(take(count l)(iterate l 0)))]l)) ``` [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` lambda A:len(A)in[len(set(reduce(lambda a,c:a+[A[a[-1]][n]],A,[n])))for n in A[0]] ``` [Try it online!](https://tio.run/##fVJNb4MwDD2PX@Ej0TypSWCVkHbIpX8iy4EV0JDatKL0sF/PEuIkRfs44Tw/Pz/bXL/mz4sVy/D2vpza80fXgmpOvS0VG632wa2fy6nv7se@JEKLx6Z91kq3@oUbo60xqNB9GGPDZQILowWld8YsXT/AwWk1xdN1Gu0MCmFw76I4lFrvEDiCQJAIFUJtEHQAXKYOsMcCwAPJwR6T8UUiHqtiFRV4rI7qJGwMC71TkEzk9tITQ2OZpWRuRrVifUY2j2yR2YJqKfRdHvpS1S9e4nSvCPutrwTn5SRjBNMqs98EOwotar@yw/5k9lmvvJDkKekzgR2SIiV9JklVSeqfmeLMkVtv5sg3pQlEVOa05c3VyUFmkN@/bvswz4/bxp/G1S7f "Python 2 – Try It Online") 0-indexed Cayley table is input; True/False output for cyclic/non-cyclic group. ]
[Question] [ # Challenge description You have a music library with many tracks recorded by many bands, each of which has a name, like `Queen`, `Aerosmith`, `Sunny Day Real Estate`, `The Strokes` . When an audio player displays your library alphabetically by band name, it usually skips the `The` part, as many band names start with `The`, making it easier to navigate through your media collection. In this challenge, given a list (array) of strings, you need to sort it that way (that is, omitting the `The` word at the beginning of the name). You can either write a method or a full working program. # Sample inputs / outputs ``` [Queen, Aerosmith, Sunny Day Real Estate, The Strokes] -> [Aerosmith, Queen, The Strokes, Sunny Day Real Estate] [The Ramones, The Cure, The Pixies, The Roots, The Animals, Enrique Iglesias] -> [The Animals, The Cure, Enrique Iglesias, The Pixies, The Ramones, The Roots] [The The, The They, Thermodynamics] -> [The The, Thermodynamics, The They] ``` # Notes / Edge cases * Sorting lexicographically is case insensitive, so `The Police`, `The police` and `the police` are all equivalent, * Your algorithm should only omit the first `the` word, so bands named `The The` or `The The Band` are sorted normally by the second `the`, * A band named `The` (a three letter word) is sorted normally (no skipping), * Order of two bands having the same name, one of which starts with `the` (like `The Police` and `Police`) is undefined, * You can assume that if a band's name consists of more than one word, they are separated by a single space character. You don't need to handle leading or trailing whitespaces, * All input strings match `[A-Za-z0-9 ]*`, that is they will consist only of lower- and uppercase letters of English alphabet, digits and space characters, * Remember that this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so make your code as short as possible! [Answer] ## Python, ~~56~~ ~~62~~ 64 bytes ``` lambda b:sorted(b,key=lambda x:(x,x[4:])[x.lower()[:4]=='the ']) ``` [Try it](https://repl.it/CilL/1) Thanks to @Chris H for pointing out that `lstrip()` was not handling `The The` correctly, since the strip was blasting all matching characters and sorting it as a blank string, and @manatwork for finding the flaw in using `replace()`. The new version should work. Old version: ``` lambda b:sorted(b,key=lambda x:x.lower().lstrip('the ')) ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~32~~ 28 bytes ``` ç^The /dwA_ :sort ç_/$xIThe ``` [Try it online!](http://v.tryitonline.net/#code=w6deVGhlIC9kd0FfCjpzb3J0CsOnXy8keElUaGUg&input=VGhlIFJhbW9uZXMKUmFkaW9oZWFkClRoZSBDdXJlClRoZSBQaXhpZXMKVGhlIFJvb3RzClRoZSBBbmltYWxzCkVucmlxdWUgSWdsZXNpYXM) *Note to self: Make an abbreviation for `:sort` so that I don't need 6 whole bytes for a single command!* Explanation: ``` ç^The / "On every line starting with 'The ', dw "Delete a word A_ "And (A)ppend an underscore '_' :sort "Sort all lines alphabetically ç_/ "On every line containing an underscore, $x "Delete the last character IThe "And prepened 'The ' ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 34 bytes The trailing linefeed is significant. ``` %`^ $'; T`L`l`.+; m`^the O` .+; ``` I/O is one band per line. [Try it online!](http://retina.tryitonline.net/#code=JWBeCiQnOwpUYExgbGAuKzsKbWBedGhlIAoKT2AKLis7Cg&input=UXVlZW4KQWVyb3NtaXRoClN1bm55IERheSBSZWFsIEVzdGF0ZQpUaGUgU3Ryb2tlcwpUaGUgUmFtb25lcwpUaGUgQ3VyZQpUaGUgUGl4aWVzClRoZSBSb290cwpUaGUgQW5pbWFscwpFbnJpcXVlIElnbGVzaWFzClRoZSBUaGUKVGhlIFRoZXkKVGhlcm1vZHluYW1pY3M) ### Explanation ``` %`^ $'; ``` Duplicate each line, using `;` as a separator. ``` T`L`l`.+; ``` Turn everything in front of a `;` to lower case. ``` m`^the ``` Remove any `the`s that appear at the beginning of a line. ``` O` ``` Sort the lines. ``` .+; ``` Remove the beginnings of the lines which we used for sorting. [Answer] ## Pyke, 16 bytes ``` .#l1D"the ".^4*> ``` [Try it here!](http://pyke.catbus.co.uk/?code=.%23l1D%22the+%22.%5E4%2a%3E&input=%5B%22Queen%22%2C+%22Aerosmith%22%2C+%22Sunny+Day+Real+Estate%22%2C+%22The+Strokes%22%5D) ``` .# - sort_by(V, input) l1 - i = i.lower() "the ".^ - i.startswith("the ") I - if ^: 4> - i[4:] ``` [Answer] # Perl, 52 bytes *-13 byte thanks to @manatwork* *-1 byte thanks to @msh210* ``` sub f{lc pop=~s/^the //ri}print sort{f($a)cmp f$b}<> ``` One band per line as input, and so is the output. The implementation is quite straight forward : the program prints the list of bands, sorted with the help of a custom function (`f`) which returns the lower case band name without the eventual leading `the` . [Answer] # Python, ~~66~~ ~~72~~ 69 bytes ``` lambda x:sorted(x,key=lambda a:a[4*(a.lower()[:4]=='the '):].lower()) ``` Uses Python's `sorted` method with the `key` keyword argument to sort by the name minus "The". This is a lambda; to call it, give it a name by putting `f=` in front. Now with extra case insensitivity! [Answer] # Ruby, 42 bytes ``` ->a{a.sort_by{|s|s.upcase.sub /^THE /,''}} ``` [Try it online!](https://repl.it/Ciq3) [Answer] # [Perl 6](http://perl6.org), 26 bytes ``` *.sort({fc S:i/^'the '//}) ``` ### Explanation: ``` # 「*」 is the input to this Whatever lambda *.sort( # sort based on the return value of this Block lambda { fc # foldcase the following # string replace but not in-place S :ignorecase / # at the start of the string ^ # match 「the 」 'the ' # replace with nothing // } ) ``` ### Test: ``` use v6.c; use Test; my @tests = ( « Queen Aerosmith 'Sunny Day Real Estate' 'The Strokes' » => « Aerosmith Queen 'The Strokes' 'Sunny Day Real Estate' », « 'The Ramones' 'The Cure' 'The Pixies' 'The Roots' 'The Animals' 'Enrique Iglesias' » => « 'The Animals' 'The Cure' 'Enrique Iglesias' 'The Pixies' 'The Ramones' 'The Roots' », « 'The The' 'The They' Thermodynamics » => « 'The The' Thermodynamics 'The They' », ); # give it a lexical name for clarity my &band-sort = *.sort({fc S:i/^'the '//}); plan +@tests; for @tests -> ( :key(@input), :value(@expected) ) { is-deeply band-sort(@input), @expected, @expected.perl; } ``` ``` 1..3 ok 1 - ("Aerosmith", "Queen", "The Strokes", "Sunny Day Real Estate") ok 2 - ("The Animals", "The Cure", "Enrique Iglesias", "The Pixies", "The Ramones", "The Roots") ok 3 - ("The The", "Thermodynamics", "The They") ``` [Answer] ## PowerShell v2+, ~~33~~ ~~32~~ 29 bytes ``` $args|sort{$_-replace'^the '} ``` *Saved 3 bytes thanks to @MathiasRJessen* Input is via command-line arguments. Sorts the original names based on the results of the script block `{...}` that performs a regex `-replace` to strip out the leading (case-insensitive) `"the "`. ### Examples ``` PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'the Ramones' 'The cure' 'The Pixies' 'The Roots' 'the Animals' 'Enrique Iglesias' the Animals The cure Enrique Iglesias The Pixies the Ramones The Roots PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'The The' 'The They' 'Thermodynamics' The The Thermodynamics The They PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'THE STOOGES' 'The Strokes' 'The The' 'the they' 'the band' 'STP' the band THE STOOGES STP The Strokes The The the they ``` [Answer] # JavaScript/ECMAScript 6 ~~93~~ 70 bytes **70** *Thanks to Neil and Downgoat for advice* ``` B=>B.sort((a,b)=>R(a).localeCompare(R(b)),R=s=>s.replace(/^the /i,'')) ``` *Readable Version for the 70-byte variant* ``` let sortBandNames = (bandNames) => { let stripThe = (name) => name.replace(/^the /i, ''); let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b)); return bandNames.sort(compareFunc) }; ``` **93** ``` f=B=>{R=s=>s.toLowerCase().replace(/the /,'');return B.sort((a,b)=>R(a).localeCompare(R(b)))} ``` *Readable Version for the 93-byte variant* ``` let sortBandNames = (bandNames) => { let stripThe = (name) => name.toLowerCase().replace(/the /, ''); let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b)); return bandNames.sort(compareFunc) }; ``` [Answer] ## Java 8, 178 bytes ``` void q(String[]s){java.util.Arrays.sort(s,(a,b)->(a.toLowerCase().startsWith("the ")?a.substring(4):a).compareToIgnoreCase(b.toLowerCase().startsWith("the ")?b.substring(4):b));} ``` Ungolfed version: ``` void sort(String[] bands) { java.util.Arrays.sort(bands, (a, b) -> (a.toLowerCase().startsWith("the ") ? a.substring(4) : a).compareToIgnoreCase( b.toLowerCase().startsWith("the ") ? b.substring(4) : b ) ); } ``` Call as such: ``` public static void main(String[] args) { String[] bands = {"The Strokes", "Queen", "AC/DC", "The Band", "Cage the Elephant", "cage the elephant"}; sort(bands); // or q(bands) in the golfed version System.out.println(java.util.Arrays.toString(bands)); } ``` [Answer] ## Bash + coreutils, 44 bytes ``` sed '/^the /I!s,^,@ ,'|sort -dk2|sed s,@\ ,, ``` **Explanation:** the input and output format is one band per line ``` sed '/^the /I!s,^,@ ,' # prepend '@ ' to each line not starting with 'the ', case #insensitive. This adds a temporary field needed by sort. sort -dk2 # sort in ascending dictionary order by 2nd field onward sed s,@\ ,, # remove the temporary field ``` **Test run (using a here-document with EOF as the end marker):** ``` ./sort_bands.sh << EOF > Queen > Aerosmith > Sunny Day Real Estate > The Strokes > EOF ``` **Output:** ``` Aerosmith Queen The Strokes Sunny Day Real Estate ``` [Answer] # Vim, 18 bytes Well now that I realized this is possible, I'm kinda embarrassed by my 26 byte V answer, especially since V is supposed to be shorter than vim. But this is pretty much a builtin. ``` :sor i/\(The \)*/<CR> ``` Explanation (straight from vim help): ``` *:sor* *:sort* :[range]sor[t][!] [b][f][i][n][o][r][u][x] [/{pattern}/] Sort lines in [range]. When no range is given all lines are sorted. With [i] case is ignored. When /{pattern}/ is specified and there is no [r] flag the text matched with {pattern} is skipped, so that you sort on what comes after the match. Instead of the slash any non-letter can be used. ``` [Answer] # C, ~~216~~ ~~212~~ 135 + 5 (`qsort`) = ~~221~~ ~~217~~ 140 bytes ``` M(void*a,void*b){char*A,*B;A=*(char**)a;B=*(char**)b;A=strcasestr(A,"The ")?A+4:A;B=strcasestr(B,"The ")?B+4:B;return strcasecmp(A,B);} ``` Well, I finally got around to finishing this in `C`. Golfing tips are very much appreciated. In this submission, `M` is the comparison function to be supplied to [`qsort`](https://www.gnu.org/software/libc/manual/html_node/Array-Sort-Function.html#Array-Sort-Function). Therefore, to invoke this, you must use `qsort` in the format `qsort(argv++,argc--,8,M)` where `argv` contains the command-line arguments and `argc` is the number of arguments provided. [Try It Online!](https://tio.run/##TU89T8MwEJ2bX2EFIcWJgxiYcAuyBWMHKBswuI6TODR2sZ1IpcrPZjZ2iqDT3fu4d3e8bDj3F1Lx3VAJsLSukvqqvUvOKSNVEzi/zkYtq5yhuWzhkbfM5ATlFJNVns0ohwzTf7ANSgjgzIpQMoLSl1aAFN6T4uaWBOeZSP9EGkSKjXCDUeDXwft9GKcQT14qB3omVRYbZhqOTttiP0JwTBafVhuXRVgUKDrKEln5JXR9OgyiNcTJotZmzuhW17hbRh/uimJOWOzD167O0kv7ptKYMb5273FoSibvnwYhlCfCaNtL1/rNoNQBPLADeBZsBx6tY074@M7GGf0h7LfSJWe8FT8) [Answer] # [Nim](http://nim-lang.org/), 96 bytes ``` import algorithm,strutils,future x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0] ``` Those `import`s take up so many bytes `:|` A translation of my [Python answer](https://codegolf.stackexchange.com/a/87456/56755). This is an anonymous procedure; to use it, it must be passed into a testing procedure. Here's a full program you can use for testing: ``` import algorithm,strutils,future proc test(x: seq[string] -> seq[string]) = echo x(@["The The", "The They", "Thermodynamics"]) # Substitute your input here test(x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0]) ``` [Answer] # Haskell, 84 bytes ``` import Data.List p(t:'h':'e':' ':s)|elem t"Tt"=s p s=s sortBy(\a b->p a`compare`p b) ``` Call with ``` sortBy(\a b->p a`compare`p b)["The The", "The They", "Thermodynamics"] ``` Testcase: ``` let s = sortBy(\a b->p a`compare`p b) and[s["Queen", "Aerosmith", "Sunny Day Real Estate", "The Strokes"]==["Aerosmith", "Queen", "The Strokes", "Sunny Day Real Estate"],s["The Ramones", "The Cure", "The Pixies", "The Roots", "The Animals", "Enrique Iglesias"]==["The Animals", "The Cure", "Enrique Iglesias", "The Pixies", "The Ramones", "The Roots"],s["The The", "The They", "Thermodynamics"]==["The The", "Thermodynamics", "The They"]] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` tk'^the '[]YX2$S ``` Input format is (each line corresponds to a test case) ``` {'Queen', 'Aerosmith', 'Sunny Day Real Estate', 'The Strokes'} {'The Ramones', 'The Cure', 'The Pixies', 'The Roots', 'The Animals', 'Enrique Iglesias'} {'The The', 'The They', 'Thermodynamics'} ``` [**Try it online!**](http://matl.tryitonline.net/#code=dGsnXnRoZSAnW11ZWDIkUw&input=eydRdWVlbicsICdBZXJvc21pdGgnLCAnU3VubnkgRGF5IFJlYWwgRXN0YXRlJywgJ1RoZSBTdHJva2VzJ30g) ### Explanation ``` t % Implicitly input cell array of strings. Push another copy k % Convert to lowercase '^the ' % String to be used as regex pattern: matches initial 'the ' [] % Empty array YX % Regex replacement: replace initial 'the ' in each string by empty array 2$S % Sort input according to the modified cell array. Implicitly display ``` [Answer] # C#, 139 Bytes ``` using System.Linq;System.Collections.IEnumerable S(string[] l)=> l.OrderBy(b=>(b.ToLower().StartsWith("the ")?b.Substring(4):b).ToLower()); ``` [Try online!](http://csharppad.com/gist/7f2a6e59f3525c4e81fe1068956400a4) Without counting the usings the answer would be 102 bytes. [Answer] **BASH, 64 Bytes** ``` sed 's/^the / /;s/^The / /'|sort -fb|sed 's/^ /the /;s/^ /The /' ``` Input: stdin, one band per line. Output: stdout Note: The second replacements (s/^The/ / and s/^ /The /) use the tab character, so they don't always copy/paste correctly. [Answer] # Groovy, 34 bytes ``` {it.sort{it.toLowerCase()-'the '}} ``` 41% my answer is `.toLowerCase()`, kill me now. --- # Output When running... ``` ({it.sort{it.toLowerCase()-'the '}})(['The ramones','The Cure','The Pixies','The Roots','The Animals','Enrique Iglesias']) ``` The result is... `[The Animals, The Cure, Enrique Iglesias, The Pixies, The ramones, The Roots]` With no debug or error output. [Answer] # q/kdb+, ~~36~~ 33 bytes **Solution:** ``` {x(<)@[x;(&)x like"[Tt]he *";4_]} ``` **Example:** ``` q){x(<)@[x;(&)x like"[Tt]he *";4_]}("Queen";"Aerosmith";"Sunny Day Real Estate";"The Strokes";"the Eagles") "Aerosmith" "the Eagles" "Queen" "The Strokes" "Sunny Day Real Estate" ``` **Explanation:** Strip out any "[Tt]he " from each input string, sort this list, then sort the original list based on the indexing of the sorted list. ``` {x iasc @[x;where x like "[Tt]he *";4_]} / ungolfed solution { } / lambda function @[x; ; ] / apply function to x at indices 4_ / 4 drop, remove first 4 items where x like "[Tt]he *" / where the input matches 'The ...' or 'the ...' iasc / returns sorted indices x / index into original list at these indices ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~11~~ 10 bytes ``` ñ_v r`^e ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8V92IHJgXpBlIA==&input=WyJUaGUgUmFtb25lcyIsIlRoZSBDdXJlIiwiVGhlIFBpeGllcyIsIlRoZSBSb290cyIsIlRoZSBBbmltYWxzIiwiRW5yaXF1ZSBJZ2xlc2lhcyIsIlF1ZWVuIiwiQWVyb3NtaXRoIiwiU3VubnkgRGF5IFJlYWwgRXN0YXRlIiwiVGhlIFN0cm9rZXMiLCJUaGUgVGhlIiwiVGhlIFRoZXkiLCJUaGVybW9keW5hbWljcyIsInRoZSBwQXBlciBjaEFzZV0=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes ``` vyð¡RD¤…TheQsgα£Rðý})‚øí{ø¤ ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/rPLwhkMLg1wOLXnUsCwkIzWwOP3cxkOLgw5vOLy3VvNRw6zDOw6vrT6849CS//@jlYAKFIBYSUcBxqyEsoty81Mq8xJzM5OLlWIB "05AB1E – Try It Online") ### Explanation ``` vyð¡RD¤…TheQsgα£Rðý})‚øí{ø¤ Argument l v } For each y in l, do: yð¡ Split y on space RD Reverse and duplicate ¤…TheQ Last element equals "The" (true = 1, false = 0) sgα Absolute difference with length of array £ Get elements from index 0 to calculated difference R Reverse ðý Join on space )‚øí Pair each element with original {ø¤ Sort and get the original band name ``` [Answer] # Java ~~176~~ 158 bytes ``` public String[]sort(String[]names){ for(int i=-1;++i<names.length;) if(names[i].startsWith("(The |the )")) names[i]=names[i].substring(4); return Arrays.sort(names,String.CASE_INSENSITIVE_ORDER); } ``` Main Function ``` public static void main(String[]args){ Scanner s = new Scanner(System.in); List<String> list= new ArrayList<>(); while(!(String h = s.nextLine).equalsIgnoreCase("~")){ list.add(h); } System.out.println(sort(list.toArray(newString[0])) ``` ); } Golfed sort function: ``` String[]s(String[]n){for(int i=-1;++i<n.length;)if(n[i].startsWith("(The |the )"))n[i]=n[i].substring(4);return Arrays.sort(n,String.CASE_INSENSITIVE_ORDER);} ``` > > Thanks to @raznagul for saving 18 bytes > > > ]
[Question] [ The [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_number) is a well know sequence in which each entry is the sum of the previous two and the first two entries are 1. If we take the modulo of each term by a constant the sequence will become periodic. For example if we took decided to compute the sequence mod 7 we would get the following: ``` 1 1 2 3 5 1 6 0 6 6 5 4 2 6 1 0 1 1 ... ``` This has a period of 16. A related sequence, called the [Pisano sequence](http://oeis.org/A001175), is defined such that `a(n)` is the period of the fibonacci sequence when calculated modulo n. ## Task You will should write a program or function that when given `n` will compute and output the period of the Fibonacci sequence mod `n`. That is the nth term in the Pisano sequence. You must only support integers on the range `0 < n < 2^30` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition so you should aim to minimize the size of your source code as scored by bytes. ### Test cases ``` 1 -> 1 2 -> 3 3 -> 8 4 -> 6 5 -> 20 6 -> 24 7 -> 16 8 -> 12 9 -> 24 10 -> 60 11 -> 10 12 -> 24 ``` [Answer] ## GolfScript (28 25 24 23 chars) ``` ~1.{(2$+}{.@+2$%}/+\-,) ``` Takes input in stdin, leaves it on stdout (or the stack, if you want to further process it...) This correctly handles the corner cases ([Demo](http://golfscript.apphb.com/?c=IyBUZXN0IG9uIDEsMiwzLDEwCiMgRXhwZWN0ZWQgb3V0cHV0IDEsMyw4LDYwCjsnMScKCn4xLnsoMiQrfXsuQCsyJCV9LytcLSwpCgpwJzInCgp%2BMS57KDIkK317LkArMiQlfS8rXC0sKQoKcCczJwoKfjEueygyJCt9ey5AKzIkJX0vK1wtLCkKCnAnMTAnCgp%2BMS57KDIkK317LkArMiQlfS8rXC0sKQ%3D%3D)). As a point of interest to GolfScript programmers, I think this is the first program I've written with an unfold which actually came out shorter than the other approaches I tried. [Answer] ### GolfScript, 24 characters ``` ~:&1.{.2$+&%.2$(|}do](-, ``` Next iteration of a GolfScript implementation. The second version now also handles 1 correctly. It became quite long but maybe someone can find a way to shorten this version. You can [try above version online](http://golfscript.apphb.com/?c=OycxMCcKCn46JjEuey4yJCsmJS4yJCh8fWRvXSgtLAoKcHJpbnQKCg%3D%3D). [Answer] # Python, ~~188~~ ~~132~~ ~~101~~ ~~95~~ 87 characters ``` n=input() s=[] a=k=0 b=1 while s[:k]!=s[k:]or k<1:s+=[a%n];k=len(s)/2;a,b=b,a+b print k ``` ## Usage ``` $ echo 10 | python pisano.py 60 ``` For example: ``` $ for i in {1..50}; do; echo $i | python pisano.py; done 1 3 8 6 20 24 16 12 24 60 10 24 28 48 40 24 36 24 18 60 16 30 48 24 100 84 72 48 14 120 30 48 40 36 80 24 76 18 56 60 40 48 88 30 120 48 32 24 112 300 ``` [Answer] # Python ~~90~~ ~~85~~ ~~96~~ ~~94~~ ~~90~~ 82 ``` n=input();c=[1,1];a=[] while(c in a)<1%n:a+=[c];c=[c[1],sum(c)%n] print len(a)or 1 ``` Edit: Implemented suggestions by beary and primo [Answer] # Mathematica 73 ``` p = {1, 0}; j = 0; q = p; While[j++; s = Mod[Plus @@ p, n]; p = RotateLeft@p; p[[2]] = s; p != q]; j ``` [Answer] ## PHP - ~~61~~ 57 bytes ``` <?for(;1<$a.$b=+$a+$a=!$i+++$b%$n+=fgets(STDIN););echo$i; ``` This script will erroneously report `2` for `n=1`, but all other values are correct. Sample I/O, a left-truncable series where π(n) = 2n + 2 : ``` $ echo 3 | php pisano.php 8 $ echo 13 | php pisano.php 28 $ echo 313 | php pisano.php 628 $ echo 3313 | php pisano.php 6628 $ echo 43313 | php pisano.php 86628 $ echo 543313 | php pisano.php 1086628 $ echo 4543313 | php pisano.php 9086628 $ echo 24543313 | php pisano.php 49086628 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` LU_2M`%İf ``` [Try it online!](https://tio.run/##yygtzv7/3yc03sg3QfXIhrT///9bAAA "Husk – Try It Online") # Explanation I'm not sure if I've ever used `U` with a negative argument before. ``` LU_2M`%İf Implicit input, say n=8. İf Infinite list of Fibonacci numbers: [1,1,2,3,5,8,13,21.. M Map `% modulo n: [1,1,2,3,5,0,5,5,2,7,1,0,1,1,2.. U_2 Cut at the start of first repeated sublist of length 2 (here [1,1]): [1,1,2,3,5,0,5,5,2,7,1,0] L Length: 12 ``` [Answer] ## PowerShell: 98 **Golfed code:** ``` for($a,$b=0,(1%($n=read-host))){$x++;if($a+$b-eq0-or("$a$b"-eq10)){$x;break}$a,$b=$b,(($a+$b)%$n)} ``` --- **Ungolfed, with comments:** ``` for ( # Start with $a as zero, and $b as 1%$n. # Setting $b like this at the start helps catch the exceptional case where $n=1. $a,$b=0,(1% ( # Grab user input for n. $n=read-host )) ) { # Increasing the counter ($x) and testing for the end of the period at the start ensures proper output for $n=1. $x++; # Test to see if we've found the end of the Pisano Period. if ( # The first part catches $n=1, since $a and $b will both be zero at this point. $a+$b-eq0-or ( # A shorter way of testing $a-eq1-and$b-eq0, which is the end of a "normal" Pisano Period. "$a$b"-eq10 ) ) { # Pisano Period has reached its end. Output $x and get out of the loop. $x;break } # Pisano Period still continues, perform operation to calculate next number. # Works pretty much like a Fibonacci sequence, but uses ($a+$b)%$n for the new $b instead. # This takes advantage of the fact we don't really need to track the actual Fibonacci numbers, just the Fibonacci pattern of %$n. $a,$b=$b,(($a+$b)%$n) } # Variable cleanup - not included in golfed code. rv n,a,b,x ``` --- **Notes:** I'm not sure exactly what the maximum reliable limit is for $n with this script. It's quite possibly less than 2^30, as $x could possibly overflow an int32 before $n gets there. Besides that, I haven't tested the upper limit myself because run times for the script already hit around 30 seconds on my system for $n=1e7 (which is only a bit over 2^23). For the same reason, I'm not quickly inclined to test and troubleshoot whatever additional syntax may be needed to upgrade the variables to uint32, int64, or uint64 where needed in order to expand this script's range. --- **Sample output:** I wrapped this in another for loop: ``` for($i=1;;$i++) ``` Then set `$n=$i` instead of `=read-host`, and changed the output to `"$i | $x"` to get an idea of the script's general reliability. Here's some of the output: ``` 1 | 1 2 | 3 3 | 8 4 | 6 5 | 20 6 | 24 7 | 16 8 | 12 9 | 24 10 | 60 11 | 10 12 | 24 13 | 28 14 | 48 15 | 40 16 | 24 17 | 36 18 | 24 19 | 18 20 | 60 ``` ... ``` 9990 | 6840 9991 | 10192 9992 | 624 9993 | 4440 9994 | 1584 9995 | 6660 9996 | 1008 9997 | 1344 9998 | 4998 9999 | 600 10000 | 15000 10001 | 10212 10002 | 3336 10003 | 5712 10004 | 120 10005 | 1680 10006 | 10008 10007 | 20016 10008 | 552 10009 | 3336 10010 | 1680 ``` --- **Sidenote:** I'm not really sure how some Pisano Periods are significantly shorter than $n. Is this normal, or is something wrong with my script? Nevermind - I just remembered that, after 5, Fibonacci numbers quickly become *much* larger than their place in the sequence. So, this makes total sense now. [Answer] # Perl, ~~75~~, ~~61~~, 62 + 1 = 63 ``` $k=1%$_;$a++,($m,$k)=($k,($m+$k)%$_)until$h{"$m,$k"}++;say$a-1 ``` ### Usage ``` $ echo 8 | perl -n -M5.010 ./pisano.pl 12 ``` ### Ungolfed ``` $k = 1 % $_; $a++, ($m, $k) = ($k, ($m + $k) % $_) until $h{"$m,$k"}++; say $a - 1 ``` +1 byte for `-n` flag. Shaved off 13 bytes thanks to Gabriel Benamy. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 21 bytes ``` {≢(⍵|1⌽+\)⌂traj⍵|1 1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR5yKNR71bawwf9ezVjtF81NNUUpSYBRZRMKz9n/aobcKj3r5HXc2H1hs/apv4qG9qcJAzkAzx8Az@n3ZoxaPezYZGAA "APL (Dyalog Extended) – Try It Online") An anonymous function (dfn) that takes n as its right argument. ### How it works ``` {≢(⍵|1⌽+\)⌂traj⍵|1 1} ⍝ Anonymous function; Input ⍵←n { 1 1} ⍝ Two ones (initial two values of Fibonacci) ⍵| ⍝ Modulo n (to handle special case) ( )⌂traj ⍝ Repeat and collect until the same value appears... 1⌽+\ ⍝ (a,b) → (a+b,a) ⍵| ⍝ Modulo n ≢ ⍝ Count the iterations before the same value appears ``` [Answer] **Clojure, 102 bytes** Not too exciting, iterates the formula until we reach back `[1 1]` (I hope this is always the case). Special handling of `(f 1)` as it converges to `[0 0]`. ``` #(if(< % 2)1(+(count(take-while(fn[v](not=[1 1]v))(rest(iterate(fn[[a b]][b(mod(+ a b)%)])[1 1]))))1)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞.Δ∞ÅfI%sô3£Ë ``` [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8vXNTgOTh1jRP1eLDW4wPLT7c/f@/GQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o5Opnr6TwqG2SgpK9X@j/Rx3z9M5NAZKHW9MiVIsPbzE@tPhw9/9anf9mAA). **Explanation:** ``` ∞.Δ # Find the first positive integer which is truthy for: ∞ # Push a positive infinite list Åf # Get the n'th Fibonacci number of each value `n` in this list I% # Take modulo the input on each Fibonacci number s # Swap so the current integer is at the top of the stack ô # Split the infinite modular Fibonacci list into parts of that size 3£ # Only leave the first 3 parts Ë # And check if all three sublist parts are the same # (after which the result is output implicitly) ``` ]
[Question] [ # Challenge Create a function or program that, when given an integer `size`, behaves the following way: If `size` is equal to 1, output ``` ┌┐ └┘ ``` If `size` is greater than 1, apply the following substitutions : | Source | Target | | --- | --- | | `┌` | `┌┐``└┌` | | `┐` | `┌┐``┐┘` | | `└` | `┌└``└┘` | | `┘` | `┘┐``└┘` | **Note:** this is basically a Unicode box-drawing version of the [T-Square fractal](https://www.wikiwand.com/en/T-square_(fractal)). If it makes things easier for you, you may make the base case correspond to `0`, as long as you specify in your answer. The program should output anything that is isomorphic to a grid, so a multiline string, an array of strings, an array of arrays of chars, whichever is more comfortable. You may use a different set of characters than `┌┐└┘` (such as 1234, ABCD, etc.) if you want. Leading and trailing spaces are allowed if you choose to work with strings. Please specify what output format your code is returning. # Test Cases `1` ``` ┌┐ └┘ ``` `2` ``` ┌┐┌┐ └┌┐┘ ┌└┘┐ └┘└┘ ``` `3` ``` ┌┐┌┐┌┐┌┐ └┌┐┘└┌┐┘ ┌└┌┐┌┐┘┐ └┘└┌┐┘└┘ ┌┐┌└┘┐┌┐ └┌└┘└┘┐┘ ┌└┘┐┌└┘┐ └┘└┘└┘└┘ ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count for each language wins! [Answer] # JavaScript (ES6), 108 bytes Returns an array of strings, with `0123` instead of `┌┐└┘`. ``` f=(n,a=[w="01","23"])=>n?f(n-1,[...a,...a].map((s,i)=>i<w|i/w/3?s+s:s.slice(0,w)+a[i-w]+s.slice(-w)),w*=2):a ``` [Try it online!](https://tio.run/##VY8xboQwEEV7TjFy5QnGsEsqst69Q5oUhMIiQLwitsWwcZHkBilSUOR8XIRApEjZZr70vubPn7N@1VQPxo@JdU/NsrSKW6FVGRTLdkywfc4qVEd7arlNdqKUUmqxjUq@aM85CbPa5hDeTRrS/EQxFSSpN3XDMxEw1qVJQhX/sSQginCj9ljopXaWXN/I3nWc3esA7jL6y1gwjP5bLc8RoyvEHu2DGZ/BOxoTP7i6ITK22zZbN3ALCrI7sHCA21XiGOEtArgOtfj7AoE6Asmh8b1eC6Yy7QTUG2Tz9DlPX/M0zdM3K@sKUZ6dsdt1tjb6WH4A "JavaScript (Node.js) – Try It Online") ### How? This is a rather straightforward recursive construction of the pattern and is probably not the shortest method. Below is an example for the 2nd iteration, with **w = 2**. ``` 0123 0123 4567 0123 4567 0 ABCD ABCD|ABCD ABCD|ABCD \__ i < w -> s + s 1 EFGH EFGH|EFGH EFGH|EFGH / 2 IJKL IJ..|..KL IJ**A****B**|**C****D**KL \ 3 MNOP MN..|..OP MN**E****F**|**G****H**OP \ ----+---- ----+---- }-- s.slice(0, w) + a[i - w] + s.slice(-w) 4 AB..|..CD AB**I****J**|**K****L**CD / 5 EF..|..GH EF**M****N**|**O****P**GH / 6 IJKL|IJKL IJKL|IJKL \__ i ≥ 3w -> s + s 7 MNOP|MNOP MNOP|MNOP / ``` ### Commented ``` f = ( // f is a recursive function taking: n, // n = number of iterations a = [ // a[] = output array initialized to: w = "01", // the pattern "01" (we also initialize w to "01") "23" // the pattern "23" ] // ) => // n ? // if n is not equal to 0: f( // do a recursive call: n - 1, // decrement n [...a, ...a] // repeat a[] twice .map((s, i) => // for each string s at index i in this array: i < w | // if i is less than w i / w / 3 ? // or i is greater than or equal to w * 3: s + s // just double the previous row : // else: s.slice(0, w) + // take the first half of s a[i - w] + // append the row i - w of the previous pattern s.slice(-w) // append the 2nd half of s ), // end of map() w *= 2 // double w ) // end of recursive call : // else: a // return a[] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~29~~ 21 bytes ``` ┌F÷X²…⁰N²«Cιι‖BO⌈⊗ι ``` [Try it online!](https://tio.run/##DcwxCsIwFIDhuT3Fo9N7EEEKLrpply5aeoO0fdVATEJIKkXcHTp6wl4kdv35@PuH9L2VOqXGKxOwWH9LQad8tB6wNqFSkxoYG/tij6WAVpo7415AbVwM1/jstk5EAkoieOfZxboZlQC1TbKWR819OMcQ2I96vk3stXR4XJevgMrGTvOAijb7SemQdpP@Aw "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation: ``` ┌ ``` Print a quarter of the initial box. This gets fixed up on the first loop iteration. Note that while this character is not in Charcoal's code page, Charcoal has an escape sequence that encodes this character using three bytes; this sequence is not shown although the deverbosifier does account for it correctly. ``` F÷X²…⁰N²« ``` Take the powers of two from `1` up to (but not including) `2ⁿ`, but then integer divide them by 2. ``` Cιι ``` Make a copy of the current figure, overwriting the bottom right quarter of the figure. (Except that `i` is zero on the first loop, so nothing happens.) ``` ‖BO⌈⊗ι ``` Reflect the (original three quarters of) the figure to complete the new iteration. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~103~~ 101 bytes (UTF 8) or ~~95~~ 93 bytes (ASCII) ``` ->n{n<1?%w{┌┐ └┘}:(q=f[n-1];(-k=1<<n)...k).map{|i|s=q[i]*2;(t=i+j=k/2)/2%k<j&&s[j,k]=q[t];s}} ``` A function which returns an array of strings. For `n=0` the output is as follows: ``` UTF 8 ┌┐ Or ASCII (my preferred pq └┘ character choice) bd ``` For higher values of `n` the function is called recursively to build up a square of double the proportions of the previous iteration (total 4 copies) line by line. For the middle rows, the lines are modified as necessary to overwrite a fifth copy of the previous iteration onto the centre of the pattern. [Try it online!](https://tio.run/##DcoxDsIgFADQq3RpAyo0xU34ehDCoAMJEEkrNMZQbuDgwOD5uAj65vdYb6@moZGzT15Ml/6ZannX8ulqKbV88wktoKUnk@KIOJiE8JhS6jC9X@e0mS3AIo3aMY4imL0FNzI8st4JOwxB2oNT/xAVDzm3eY2h0/Ko2g8 "Ruby – Try It Online") TIO link shows the UTF 8 version for easy verification. substituting the box characters with `pq bd` (or other ASCII characters) reduces the code to 93 bytes. [Answer] # [J](http://jsoftware.com/), ~~46~~ 42 bytes ``` ([`(<@;~@(-:+i.)@#@[)`]},~@,.~)@[&0 i.@2 2 ``` [Try it online!](https://tio.run/##VctBC4IwAIbh@37FR0Fu5IauiLCEUdApIrpKoJjaIpw4O4TkX1927PAensP7cBPhlYgjePARIBrjAvvL8eBoktKt2gyK8miuBVNTlbD0@vEH5YuBqWQWQAslIR0j5LQTOBvboWlNXlir6wrlq847bWqUpkWt8wI3bZtn9iZVLGi4QriGHP9lnwlW5Hejon4oCakQkB/hcc69keE/5T8X7gs "J – Try It Online") * `i.@2 2` returns: ``` 0 1 2 3 ``` * `(...)@[&0` Apply the verb (...) iteratively "input" number of times. * `(<replace logic> ,~@,.~)` - `,~@,.~` first zips the current input with itself `,.~`, so with the starting input that becomes: ``` 0 1 0 1 2 3 2 3 ``` and then appends that to itself `,~@`: ``` 0 1 0 1 2 3 2 3 0 1 0 1 2 3 2 3 ``` giving us the original input repeated 4 times in a square. * Next we replace the "center" with the original input. Imagine filling in a hole like so: ``` 0 1 0 1 0 1 0 1 2 3 + 0 1 = 2 0 1 3 0 1 2 3 0 2 3 1 2 3 2 3 2 3 2 3 ``` * Here we're using the gerund form of Amend `}`, and all the rest is mechanics to specify which coordinates we replace: * `(<@;~@(-:+i.)@#@[)` That entire phrase, verbosely, converts (in our example) the 2x2 original input matrix into the J double boxed: ``` ┌─────────┐ │┌───┬───┐│ ││1 2│1 2││ │└───┴───┘│ └─────────┘ ``` which is how we tell Amend: "Replace the intersection of rows 1 and 2, and columns 1 and 2 with..." [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ 55 bytes ``` Nest[Flatten[q/. 5-#->#&/@#&/@#,q]&,q={{1,3},{2,4}},#]& ``` [Try it online!](https://tio.run/##Hcw9CsJAFATgq8iupHoafxvREAUFG8UfsFgXWcIzLujGrC9FCPEEFhYpPJ8XiTHFfEwzc1N0wZsiHajyPClX@CCxuCoiNCJ2241hi7c87rh@HYilA/Eky7rQzyHrwSDPgUun3CQayZ9po2x6sJpQNNcJ3ROCHVltwn00Swmn1qpU8LHHjob9/6rGpHTE2Z8Hl8jnblufloYwRDvyMvYtXgwqi9p37YflQmhZrZ67QJnnVpkQRQeGsvwB "Wolfram Language (Mathematica) – Try It Online") Returns a matrix of integers - uses `1234` for `┌└┐┘`. [Answer] # [Python 3](https://docs.python.org/3/), ~~217~~ \$\cdots\$ ~~119~~ 102 bytes Saved ~~9~~ a whopping 35 bytes thanks to [Danis](https://codegolf.stackexchange.com/users/99104/danis)!!! Saved ~~2~~ 5 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!! ``` f=lambda n:n and[[(j,c)[j+c==3]for c in r for j in(i,i+1)]for r in f(n-1)for i in(0,2)]or[[0,1],[2,3]] ``` [Try it online!](https://tio.run/##jVTNboMwDL7zFLkl6dKpQKVJSLnuJTIODMIa1gaEmLQfbU@www4c9ny8CEug1UJb03KwTOzP9uc4rt6aTanDvs/5Ntk9ZgnSkUaJzoQgBUupKG5SzsM4L2uUIqVRjaxaGJUopm58Ophqa8qJXvrU/iprXrGAxmUtxIr5MRMBC@O4z2SOKrKjkYfMZ323FrqLqlrphmB8W5QGi7v2u2t/urbt2l8s5JBEWs8tpZ58rWTayAxxRGx4ZOIjkwCZDGw8YMg5Hg9C@2dU6@dAxoMjoCunQQb3k4Au5iS4izxgRu99Kcd5/ss6V7iLnJJw5QwhSMJEIR1uwKHI6xvjyNmGQQxmGwnxmG0wxGm28RCnKQ9XTobg8n0cD8eF@zgzNHP3cX6YrhtgiBM82BAneOAhHX4IkDQPhHrpRqbPsraLBD@8BHfrFDM0aH6IqTfsMjbsnXdVkTrRT5KsKTssoP0aG3dXju@Nu@Yf6jMyWGtoeE7UqFakoY7zPrFoOJexa8BLvAgWi@WXov0f "Python 3 – Try It Online") Uses integers \$0,1,2,3\$ instead of chars `┌`,`┐`,`└`,`┘`. Inputs a zero-base integer \$n\$ and returns the \$2^{n+1}\times 2^{n+1}\$ T-Square fractal as a list of strings. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~36~~ 31 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⊃⍪/,/{⍵@(⌽⍵=⊖)x}¨⍵}⍣⎕⊢x←2 2⍴⍳4 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@Vz/qan7Uu0pfR7/6Ue9WB41HPXuBtO2jrmmaFbWHVgDZtY96FwM1PepaVAHUZqRg9Kh3y6PezSb/gfr/p3EZcqVxGQGxMRCbALEpAA "APL (Dyalog Unicode) – Try It Online") A dfn submission which takes the number as left argument. Uses `⎕IO←0` (0-indexing). The box is represented as ``` 01 23 ``` which is then substituted exactly according to the question spec. -5 bytes from Adám. ## Explanation ``` {⊃⍪/,/{⍵@(⌽⍵=⊖)x}¨⍵}⍣⎕⊢x←2 2⍴⍳4 x←2 2⍴⍳4 store 0 1 in x 2 3 ⍣⎕⊢ apply the following n times to the value of x: { ¨⍵} substitute each number ⍵ with: {⍵@ x} replace the following with ⍵ in the value of x: (⌽⍵=⊖) position of ⍵, flipped diagonally ⍪/,/ join all the submatrices together ⊃ and remove boxing. ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 42 bytes ``` {⍵≡0:2 2⍴⍳4⋄m⊣@((2*⍵-1)+⍳,⍨2*⍵)⍪⍨,⍨m←∇⍵-1} ``` ``` {⍵≡0:2 2⍴⍳4⋄m⊣@((2*⍵-1)+⍳,⍨2*⍵)⍪⍨,⍨m←∇⍵-1} ⍵≡0:2 2⍴⍳4 ⍝ if ⍵ is 0 return the first result ⋄ ⍝ otherwise m←∇⍵-1 ⍝ assign the last result to m ⍪⍨,⍨ ⍝ duplicate in both directions ((2*⍵-1)+⍳,⍨2*⍵) ⍝ indices corresponding to the middle section m⊣@ ⍝ replace with m ``` Produces the fractal recursively using a pattern I spotted where you make 4 copies of the previous one and replace the middle. (I'm not sure if this works in general though, so if you have outputs for 4+ that would be great) [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qn/6O2CQb/qx/1bn3UudDAykjB6FHvlke9m00edbfkPupa7KChYaQFlNU11NQGCus86l0B5ms@6l0FZIP4uUAjHnW0gxXV/k8D8Xr7HnU1P@pdAzTr0HrjR20TgVYFBzkDyRAPz@D/j3rnKhSllpQW5RUrlBZn5qUrGCgYKhgpGOsoZOalpFYAyZJ8hZKMVIXkjMSixOSS1KJihbT8IoVEhaTUEiBPISWzuCAnsZJL/dGUnkdTJjyaMuXRlBnq0WkKBrGYYoZYxIywiBnHAgA "APL (Dyalog Classic) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3Ý2ô©IGNoTS-U2δиD«DÅsε®NèXǝ}Xǝ ``` Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/218673/52210), so make sure to upvote him as well! Outputs as a matrix, with `0123` for `┌┐└┘` respectively. [Try it online](https://tio.run/##AVcAqP9vc2FiaWX//zPDnTLDtMKpSUdOb1RTLVUyzrTQuETCq0TDhXPOtcKuTsOoWMedfVjHnf99SsK7M8OdIuKUjOKUkOKUlOKUmCLigKH/NP8tLW5vLWxhenk) or [verify the first input amount of test cases](https://tio.run/##yy9OTMpM/e/pquSZV1BaYqWgZO@nw6XkX1oC4en8Nz481@jwlkMr/dz98kOCdUONzm25sMPl0GqXw63F57YeWud3eEXE8bm1QPy/1uvQbqBypUdTeh5NmfBoypRHU2YoPWpYqHNom/1/s/@6unn5ujmJVZUA) (the footers transliterate it to the unicode boxes to pretty-print). **Explanation:** ``` 3Ý # Push list [0,1,2,3] 2ô # Split it into parts of size 2: [[0,1],[2,3]] © # Store this 2x2 matrix in variable `®` (without popping) IG # Loop `N` in the range [1,input): No # Push 2 to the power `N` TS- # Subtract [1,0] to create a pair: [2^N-1,2^N] U # Pop and store this pair in variable `X` δ # Map over each row of the matrix: 2 и # And repeat it # (i.e. [[0,1],[2,3]] becomes [[0,1,0,1],[2,3,2,3]]) D« # Merge a copy of itself: # [[0,1,0,1],[2,3,2,3],[0,1,0,1],[2,3,2,3]] D # Create a copy of the matrix Ås # Pop and push its middle two rows ε # Map over those two rows: ® # Push matrix [[0,1],[2,3]] from variable `®` Nè # Get the M'th row of this matrix based on the 0-based map-index `M` Xǝ # Insert those two values at indices `X` into the current row }Xǝ # After the map: insert the modified middle rows at indices `X` into # the matrix # (after the loop, the resulting matrix is output implicitly) ``` ]
[Question] [ Your task is to generate a graph with 54 vertices, each corresponds to a facet on a Rubik's cube. There is an edge between two vertices iff the corresponding facets share a side. ### Rules * You may choose to output an adjacency list, adjacency matrix, edge list, or any reasonable format to represent a graph in an algorithm. (A visual graph readable by a human is generally not a reasonable format in an algorithm in most cases.) * You may make either every vertex adjacent to itself, or none adjacent to itself. * You may either include both directions for each edge (count one or two times for self-loops), or output exactly one time for each edge, but not mix the ways. * You may renumber the vertices, skip some numbers, or even use non-number labels for the vertices in any way you want. You should also post the numbering if it isn't obvious, so others could check your answer in easier ways. * This is code-golf. Shortest code in bytes wins. ### Example output This is the numbering of vertices used in the example: ``` 0 1 2 3 4 5 6 7 8 9 10 11 18 19 20 27 28 29 36 37 38 12 13 14 21 22 23 30 31 32 39 40 41 15 16 17 24 25 26 33 34 35 42 43 44 45 46 47 48 49 50 51 52 53 ``` Output as an adjacency list (vertex number before each list is optional): ``` 0 [1 3 9 38] 1 [2 4 0 37] 2 [29 5 1 36] 3 [4 6 10 0] 4 [5 7 3 1] 5 [28 8 4 2] 6 [7 18 11 3] 7 [8 19 6 4] 8 [27 20 7 5] 9 [10 12 38 0] 10 [11 13 9 3] 11 [18 14 10 6] 12 [13 15 41 9] 13 [14 16 12 10] 14 [21 17 13 11] 15 [16 51 44 12] 16 [17 48 15 13] 17 [24 45 16 14] 18 [19 21 11 6] 19 [20 22 18 7] 20 [27 23 19 8] 21 [22 24 14 18] 22 [23 25 21 19] 23 [30 26 22 20] 24 [25 45 17 21] 25 [26 46 24 22] 26 [33 47 25 23] 27 [28 30 20 8] 28 [29 31 27 5] 29 [36 32 28 2] 30 [31 33 23 27] 31 [32 34 30 28] 32 [39 35 31 29] 33 [34 47 26 30] 34 [35 50 33 31] 35 [42 53 34 32] 36 [37 39 29 2] 37 [38 40 36 1] 38 [9 41 37 0] 39 [40 42 32 36] 40 [41 43 39 37] 41 [12 44 40 38] 42 [43 53 35 39] 43 [44 52 42 40] 44 [15 51 43 41] 45 [46 48 17 24] 46 [47 49 45 25] 47 [33 50 46 26] 48 [49 51 16 45] 49 [50 52 48 46] 50 [34 53 49 47] 51 [52 44 15 48] 52 [53 43 51 49] 53 [35 42 52 50] ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~34~~ 30 bytes -4 thanks to jimmy23013 ``` 4≥+/¨|∘.-⍨,(⍳3)∘.⌽7 ¯1∘.,○⍳3 3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/TR51LtXWP7Si5lHHDD3dR70rdDQe9W421gRxH/XsNVc4tN4QxNZ5NL0bJKFgDNIM1Pqot@9RV/Oh9caP2iYCRYqLkoFkSUZm8X8A "APL (Dyalog Classic) – Try It Online") outputs an adjacency matrix with each vertex adjacent to itself `⍳3 3` generate an array of `(0 0)(0 1)(0 2)(1 0)(1 1)(1 2)(2 0)(2 1)(2 2)` `○` multiply all by π `7 ¯1∘.,` prepend 7 or -1 in all possible ways `(⍳3)∘.⌽` rotate coord triples by 0 1 2 steps in all possible ways `+/¨|∘.-⍨,` compute manhattan distance between each pair `4≥` it must be no greater than 4 for neighbouring facets [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` i=0;("$$5$$1$Hu"*6).bytes{|j|p [(j/18+i+=1)%54,(j%18+i)%54]} ``` [Try it online!](https://tio.run/##KypNqvz/P9PWwFpDSUXFVEXFUMWjVEnLTFMvqbIktbi6JqumQCFaI0vf0EI7U9vWUFPV1ERHI0sVxAWxY2v//wcA "Ruby – Try It Online") Improved version of my original answer. We split the surface of the cube into squares of 9 (instead of rectangles of 18 as before) and use a magic string rather than a formula to generate the offsets. The output is a list of the nodes below and to the right of each node in the (revised) map below, as before. **Output map in base 10** as shown in the output (each node is linked to the nodes below and to the right) ``` 0 3 6 9 10 11 1 4 7 12 13 14 2 5 8 15 16 17 18 21 24 27 28 29 19 22 25 30 31 32 20 23 26 33 34 35 36 39 42 45 46 47 37 40 43 48 49 50 38 41 44 51 52 53 ``` **Output map in base 9** (to show more clearly how it works.) Note that each square of 9 has the same first digit. The last digits repeat 0,1,2 on the free edge and 0,3,6 on the attached edge (alternating between horizontal and vertical.) In one direction the next node is 3 higher (except when crossing to the next square, when it is 3,5 or 7 higher) and in the other direction it is 1 higher (except when crossing to the next square, when it is [base 10] `18, 14 or 10` higher = [base 9] `20, 16 or 12` higher.) This info is encoded into the magic string, where the ASCII code of each character is `18*[2,4 or 6]+[17,13,10 or 0]`. Incrementing `i` at the beginning of each iteration boosts these values by 1. ``` 00 03 06 10 11 12 01 04 07 13 14 15 02 05 08 16 17 18 20 23 26 30 31 32 21 24 27 33 34 35 22 25 28 36 37 38 40 43 46 50 51 52 41 44 47 53 54 55 42 45 48 56 57 59 ``` # [Ruby](https://www.ruby-lang.org/), 79 bytes ``` 54.times{|i|p [(i%6<5?i+1:i+18-i/6%3*7)%54,(i+=i%18<12?6:[18-i%6*7,3].max)%54]} ``` [Try it online!](https://tio.run/##KypNqvz/39REryQzN7W4uiazpkAhWiNT1czG1D5T29AKiC10M/XNVI21zDVVTU10NDK1bTNVDS1sDI3szayiQbKqZlrmOsaxermJFSAlsbX//wMA "Ruby – Try It Online") Prints a representation of a unidirectional graph, as a list of the vertices to the right of and below each vertex as shown in the map below. ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ``` [Answer] ## Python 2.7, 145 ``` def p(n):l=(3-n%2*6,n/6%3*2-2,n/18*2-2);k=n/2%3;return l[k:]+l[:k] r=range(54) x=[[sum((x-y)**2for x,y in zip(p(i),p(j)))<5for i in r]for j in r] ``` [Try it online!](https://tio.run/##JclLCoMwEADQvafIRphJFWmsUrQ5SXBRqLbxM4apQuzl04buHjx3bK@VVAiPfhAOCJtZQ5lTqmSdUVGnpVS5@ul8jcB20lSotGy533YmMZup6U6zaaYuYc13evZQXTDx2pj3vgD4/EAp1bCy8NkhLImPdeDAYuZgRMRbFc/G4S5y/DM4trQJH74 "Python 2 – Try It Online") Defines an adjacency matrix `x` as a list of lists of boolean values. Facets count as being adjacent to themselves. `p(n)` computes the coordinates of the center of the nth facet of a 3x3x3 cube whose facets are 2 units across. Adjacency is determined by testing if 2 facets have a square distance under 5 (adjacent facets have square distance at most 4, non-adjacent facets have square distance at least 6). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 48 bytes ``` F⁷F⁷F⁷⊞υ⟦ικλ⟧≔Φυ⁼Φ﹪ι⁶¬﹪λ²⟦⁰⟧υIEυΦLυ⁼²ΣE§υλ↔⁻ν§ιξ ``` [Try it online!](https://tio.run/##XY49C8IwEIZ3f8WNCUSQDjp0KqIgWCk4lg6xjW3wTDQf0n8fE2k7eMvBc8@9d@3ATas5hnDXBsiOwn@vvB2IZ1BLBg8G2NB8VVgre0WOEp0waXh4e452BqXuPGoSF7aUwUW7mSCDjNLI6k2Tmo9ZlZHKkT230eKvFDalnIXqXTxNl/iMwdU/f1rhTqoTY9IxCsXNavROkFIqb4mKZBLiEyNdKg8hrD/4BQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⁷F⁷F⁷⊞υ⟦ικλ⟧ ``` Generate all sets of 3-dimensional coordinates in the range `[0..6]` for each dimension. ``` ≔Φυ⁼Φ﹪ι⁶¬﹪λ²⟦⁰⟧υ ``` Keep only those coordinates that are centres of `2x2` squares on one of the faces `x=0`, `y=0`, `z=0`, `x=6`, `y=6`, `z=6`. ``` IEυΦLυ⁼²ΣE§υλ↔⁻ν§ιξ ``` For each coordinate, print the indices of those coordinates whose taxicab distance is 2. The vertices are numbered as follows: ``` 33 34 35 21 22 23 9 10 11 36 24 12 0 1 2 13 25 37 47 46 45 38 26 14 3 4 5 15 27 39 50 49 48 40 28 16 6 7 8 17 29 41 53 52 51 18 19 20 30 31 32 42 43 44 ``` [Answer] # Wolfram Language 190 bytes The following returns all of the graph edges in terms of the actual coordinates (assuming each mini-cube is 2 units at the edge and the Rubik's cube has its bottom left vertex at the origin). ``` t=Table;h[a_,b_,c_]:=t[{x,y,z},{a,1,5,2},{b,1,5,2},{c,0,6,6}];Partition[Sort[a=Cases[DeleteCases[Tuples[Flatten[{h[x,z,y],h[y,z,x],h[x,y,z]},3],{2}],{x_,x_}],x_/;ManhattanDistance@@x==2]],4] (* output *) {{{{0,1,1},{0,1,3}},{{0,1,1},{0,3,1}},{{0,1,1},{1,0,1}},{{0,1,1},{1,1,0}}},{{{0,1,3},{0,1,1}},{{0,1,3},{0,1,5}},{{0,1,3},{0,3,3}},{{0,1,3},{1,0,3}}},{{{0,1,5},{0,1,3}},{{0,1,5},{0,3,5}},{{0,1,5},{1,0,5}},{{0,1,5},{1,1,6}}},{{{0,3,1},{0,1,1}},{{0,3,1},{0,3,3}},{{0,3,1},{0,5,1}},{{0,3,1},{1,3,0}}},{{{0,3,3},{0,1,3}},{{0,3,3},{0,3,1}},{{0,3,3},{0,3,5}},{{0,3,3},{0,5,3}}},{{{0,3,5},{0,1,5}},{{0,3,5},{0,3,3}},{{0,3,5},{0,5,5}},{{0,3,5},{1,3,6}}},{{{0,5,1},{0,3,1}},{{0,5,1},{0,5,3}},{{0,5,1},{1,5,0}},{{0,5,1},{1,6,1}}},{{{0,5,3},{0,3,3}},{{0,5,3},{0,5,1}},{{0,5,3},{0,5,5}},{{0,5,3},{1,6,3}}},{{{0,5,5},{0,3,5}},{{0,5,5},{0,5,3}},{{0,5,5},{1,5,6}},{{0,5,5},{1,6,5}}},{{{1,0,1},{0,1,1}},{{1,0,1},{1,0,3}},{{1,0,1},{1,1,0}},{{1,0,1},{3,0,1}}},{{{1,0,3},{0,1,3}},{{1,0,3},{1,0,1}},{{1,0,3},{1,0,5}},{{1,0,3},{3,0,3}}},{{{1,0,5},{0,1,5}},{{1,0,5},{1,0,3}},{{1,0,5},{1,1,6}},{{1,0,5},{3,0,5}}},{{{1,1,0},{0,1,1}},{{1,1,0},{1,0,1}},{{1,1,0},{1,3,0}},{{1,1,0},{3,1,0}}},{{{1,1,6},{0,1,5}},{{1,1,6},{1,0,5}},{{1,1,6},{1,3,6}},{{1,1,6},{3,1,6}}},{{{1,3,0},{0,3,1}},{{1,3,0},{1,1,0}},{{1,3,0},{1,5,0}},{{1,3,0},{3,3,0}}},{{{1,3,6},{0,3,5}},{{1,3,6},{1,1,6}},{{1,3,6},{1,5,6}},{{1,3,6},{3,3,6}}},{{{1,5,0},{0,5,1}},{{1,5,0},{1,3,0}},{{1,5,0},{1,6,1}},{{1,5,0},{3,5,0}}},{{{1,5,6},{0,5,5}},{{1,5,6},{1,3,6}},{{1,5,6},{1,6,5}},{{1,5,6},{3,5,6}}},{{{1,6,1},{0,5,1}},{{1,6,1},{1,5,0}},{{1,6,1},{1,6,3}},{{1,6,1},{3,6,1}}},{{{1,6,3},{0,5,3}},{{1,6,3},{1,6,1}},{{1,6,3},{1,6,5}},{{1,6,3},{3,6,3}}},{{{1,6,5},{0,5,5}},{{1,6,5},{1,5,6}},{{1,6,5},{1,6,3}},{{1,6,5},{3,6,5}}},{{{3,0,1},{1,0,1}},{{3,0,1},{3,0,3}},{{3,0,1},{3,1,0}},{{3,0,1},{5,0,1}}},{{{3,0,3},{1,0,3}},{{3,0,3},{3,0,1}},{{3,0,3},{3,0,5}},{{3,0,3},{5,0,3}}},{{{3,0,5},{1,0,5}},{{3,0,5},{3,0,3}},{{3,0,5},{3,1,6}},{{3,0,5},{5,0,5}}},{{{3,1,0},{1,1,0}},{{3,1,0},{3,0,1}},{{3,1,0},{3,3,0}},{{3,1,0},{5,1,0}}},{{{3,1,6},{1,1,6}},{{3,1,6},{3,0,5}},{{3,1,6},{3,3,6}},{{3,1,6},{5,1,6}}},{{{3,3,0},{1,3,0}},{{3,3,0},{3,1,0}},{{3,3,0},{3,5,0}},{{3,3,0},{5,3,0}}},{{{3,3,6},{1,3,6}},{{3,3,6},{3,1,6}},{{3,3,6},{3,5,6}},{{3,3,6},{5,3,6}}},{{{3,5,0},{1,5,0}},{{3,5,0},{3,3,0}},{{3,5,0},{3,6,1}},{{3,5,0},{5,5,0}}},{{{3,5,6},{1,5,6}},{{3,5,6},{3,3,6}},{{3,5,6},{3,6,5}},{{3,5,6},{5,5,6}}},{{{3,6,1},{1,6,1}},{{3,6,1},{3,5,0}},{{3,6,1},{3,6,3}},{{3,6,1},{5,6,1}}},{{{3,6,3},{1,6,3}},{{3,6,3},{3,6,1}},{{3,6,3},{3,6,5}},{{3,6,3},{5,6,3}}},{{{3,6,5},{1,6,5}},{{3,6,5},{3,5,6}},{{3,6,5},{3,6,3}},{{3,6,5},{5,6,5}}},{{{5,0,1},{3,0,1}},{{5,0,1},{5,0,3}},{{5,0,1},{5,1,0}},{{5,0,1},{6,1,1}}},{{{5,0,3},{3,0,3}},{{5,0,3},{5,0,1}},{{5,0,3},{5,0,5}},{{5,0,3},{6,1,3}}},{{{5,0,5},{3,0,5}},{{5,0,5},{5,0,3}},{{5,0,5},{5,1,6}},{{5,0,5},{6,1,5}}},{{{5,1,0},{3,1,0}},{{5,1,0},{5,0,1}},{{5,1,0},{5,3,0}},{{5,1,0},{6,1,1}}},{{{5,1,6},{3,1,6}},{{5,1,6},{5,0,5}},{{5,1,6},{5,3,6}},{{5,1,6},{6,1,5}}},{{{5,3,0},{3,3,0}},{{5,3,0},{5,1,0}},{{5,3,0},{5,5,0}},{{5,3,0},{6,3,1}}},{{{5,3,6},{3,3,6}},{{5,3,6},{5,1,6}},{{5,3,6},{5,5,6}},{{5,3,6},{6,3,5}}},{{{5,5,0},{3,5,0}},{{5,5,0},{5,3,0}},{{5,5,0},{5,6,1}},{{5,5,0},{6,5,1}}},{{{5,5,6},{3,5,6}},{{5,5,6},{5,3,6}},{{5,5,6},{5,6,5}},{{5,5,6},{6,5,5}}},{{{5,6,1},{3,6,1}},{{5,6,1},{5,5,0}},{{5,6,1},{5,6,3}},{{5,6,1},{6,5,1}}},{{{5,6,3},{3,6,3}},{{5,6,3},{5,6,1}},{{5,6,3},{5,6,5}},{{5,6,3},{6,5,3}}},{{{5,6,5},{3,6,5}},{{5,6,5},{5,5,6}},{{5,6,5},{5,6,3}},{{5,6,5},{6,5,5}}},{{{6,1,1},{5,0,1}},{{6,1,1},{5,1,0}},{{6,1,1},{6,1,3}},{{6,1,1},{6,3,1}}},{{{6,1,3},{5,0,3}},{{6,1,3},{6,1,1}},{{6,1,3},{6,1,5}},{{6,1,3},{6,3,3}}},{{{6,1,5},{5,0,5}},{{6,1,5},{5,1,6}},{{6,1,5},{6,1,3}},{{6,1,5},{6,3,5}}},{{{6,3,1},{5,3,0}},{{6,3,1},{6,1,1}},{{6,3,1},{6,3,3}},{{6,3,1},{6,5,1}}},{{{6,3,3},{6,1,3}},{{6,3,3},{6,3,1}},{{6,3,3},{6,3,5}},{{6,3,3},{6,5,3}}},{{{6,3,5},{5,3,6}},{{6,3,5},{6,1,5}},{{6,3,5},{6,3,3}},{{6,3,5},{6,5,5}}},{{{6,5,1},{5,5,0}},{{6,5,1},{5,6,1}},{{6,5,1},{6,3,1}},{{6,5,1},{6,5,3}}},{{{6,5,3},{5,6,3}},{{6,5,3},{6,3,3}},{{6,5,3},{6,5,1}},{{6,5,3},{6,5,5}}},{{{6,5,5},{5,5,6}},{{6,5,5},{5,6,5}},{{6,5,5},{6,3,5}},{{6,5,5},{6,5,3}}}} ``` The work of generating the points on each external facet is done by the function, `h`. It has to be called 3 times to generate the points at x=0, x=6; y=0, y=6; and z=0,z=6. Each facet point that is a Manhattan distance of 2 units from another will be connected to the respective point. We can display the graph edges visually by the following; `a` is the list of graph edges that are represented below as arrows. ``` Graphics3D[{Arrowheads[.02],Arrow/@a},Boxed->False,Axes-> True] ``` [![pic1](https://i.stack.imgur.com/fBbvJ.png)](https://i.stack.imgur.com/fBbvJ.png) The following shows the Rubik's cube, the points on the external facets, and 8 graph edges. [![pic2](https://i.stack.imgur.com/rtGUK.png)](https://i.stack.imgur.com/rtGUK.png) Red dots are located on facets at y = 0 and y = 6; blue and gray dots are on facets at x = 6 and x = 0, respectively; black dots are on facets at z=6 and z=0. [Answer] # [Rust](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=309e94d8fe6a66c402a09901e9af5621) - 278 bytes ``` fn main(){let mut v=vec![];for x in vec![-2,0,2]{for y in vec![-2,0,2]{for z in vec![-2,2]{v.push([-1,z,x,y]);v.push([0,x,y,z]);v.push([1,x,z,y]);}}}for r in 0..54{print!("\n{} ",r);for s in 0..54{if (0..4).map(|n|v[r][n]-v[s][n]).map(|d|d*d).sum::<i32>()<5{print!("{} ",s)}}}} ``` [Try on play.rust-lang.org](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=309e94d8fe6a66c402a09901e9af5621) This is big, but the smallest code for a compiled language (so far). It creates an adjacency list. Its very similar to cardboard\_box 's python answer but I wanted to see if Quaternions could work. Step 1: Construct 54 Quaternions, each representing a single facet. Step 2: for each Quaternion, list all other Quaternions with Quadrance (aka squared distance, aka squared norm of the difference) <= 4. Quaternions are built like so: The imaginary vectors i j k are points on the shell of a grid, from -2,-2,-2 to 2,2,2, step 2. The real part w is always -1, 0, or 1, so that facets on opposite sides of the cube have the same real part, but adjacent sides have different real parts. The real part allows distinguishing different 'sides' of the cube through calculation. Quaternion numbering (pseudo isometric 3d view of a cube): ``` ->i ^j \k -2,+2,+2 +0,+2,+2 +2,+2,+2 -2,+0,+2 +0,+0,+2 +2,+0,+2 -2,-2,+2 +0,-2,+2 +2,-2,+2 w=0 -2,+2,+2 -2 +2 +2 +0 +2 +2 +2 +2 +2 +2,+2,+2 -2,+0,+2 +2,+0,+2 -2,-2,+2 -2 -2 +2 +0 -2 +2 +2 -2 +2 +2,-2,+2 -2,+2,+0 -2 +2 +0 +0 +2 +0 +2 +2 +0 +2,+2,+0 -2,+0,+0 +2,+0,+0 -2,-2,+0 -2 -2 +0 +0 -2 +0 +2 -2 +0 +2,-2,+0 -2,+2,-2 -2 +2 -2 +0 +2 -2 +2 +2 -2 +2,+2,-2 -2,+0,-2 w=1 +2,+0,-2 -2,-2,-2 -2 -2 -2 +0 -2 -2 +2 -2 -2 +2,-2,-2 w=-1 w=1 w=-1 -2,+2,-2 +0,+2,-2 +2,+2,-2 -2,+0,-2 +0,+0,-2 +2,+0,-2 -2,-2,-2 +0,-2,-2 +2,-2,-2 w=0 ``` Indexed numbering (unfolded cube): ``` 16 34 52 10 28 46 4 22 40 48 30 12 14 32 50 15 33 51 42 24 6 8 26 44 9 27 45 36 18 0 2 20 38 3 21 39 1 19 37 7 25 43 13 31 49 5 23 41 11 29 47 17 35 53 ``` [Answer] # JavaScript (ES6, Browser), 153 bytes ``` for(F=n=>(A=[n%9/3|0,n%3]).splice(n/18,0,(n/9&1)*3-.5)&&A,i=0;i<54;i++)for([a,b,c]=F(i),j=0;j<54;Math.hypot(a-d,b-e,c-f)>1||alert([i,j]),j++)[d,e,f]=F(j) ``` [Try it online!](https://tio.run/##HY7RCoMgGEafptD1a0ULFs2gm@72BNGFmS1FNCoGg97d2a6@i8N3OJp/@C42tR7Eukl6buR2MOHs7oykxr1rP7sNdcyyBrWst1GVFmcGNioGTPfVKCGRTfMHZBC2inN8KwgtcRy3oFhWq2d5r1WS4EvTcxhBDKxDCoMOVF/0xY@FLt/VHYiTCUYiQZAZN/l5/nNQr0AP4RAs/QQS5sugsfc/ "JavaScript (Node.js) – Try It Online") This is modified to reduce 5 bytes by making same points adjacent, i.e. \$||\mathbf{A-B}||\leq1\$. # JavaScript (ES6, Browser), 158 bytes ``` for(F=n=>(A=[n%9/3|0,n%3]).splice(n/18,0,(n/9&1)*3-.5)&&A,i=0;i<54;i++)for([a,b,c]=F(i),j=0;j<54;Math.hypot(a-d,b-e,c-f)>1||i-j&&alert([i,j]),j++)[d,e,f]=F(j) ``` [Try it online!](https://tio.run/##HY7RCoMgGEafJtH1a0ULFs2gm@72BNKFmS0lNCoGg9692a6@i8N3OFZ@5KZWs@zU@UGfctbrzpV3m581m/27Oke/4pY7XuOGCxeVSX6k4KK8I2xbZqM0dkn2gBTCligjt5yygiDUgOFpZZ7FvTJxTC6NkNCD6niLDQEbqL3oS@4Tm76L37GkA/RUg6IjqbPjMNQi9G/CwoDtwiuoxAAaxktjyXn@AA "JavaScript (Node.js) – Try It Online") (simulates `alert` with `console.log`) Maps the center of all 54 facets to the 3-d space and calculates whether \$0<||\mathbf{A-B}||\leq1\$ for every pair of points. Outputs all directed edges as pairs of numbers `[a, b]`. The vertex map is ``` 47 50 53 46 49 52 45 48 51 20 23 26 11 14 17 35 32 29 8 5 2 19 22 25 10 13 16 34 31 28 7 4 1 18 21 24 9 12 15 33 30 27 6 3 0 36 39 42 37 40 43 38 41 44 ``` ]
[Question] [ I did the IMC this year. Did anyone else here do it? In a UKMT Intermediate Maths Challenge paper, there are twenty-five questions. The first fifteen questions give you five marks if you get them right. For the other ten questions, you get six marks for getting them right. In the last ten questions, you lose marks if you get them wrong! For questions sixteen to twenty, you lose one marks and for the last five questions, you lose two marks. If you leave a question blank, no marks are awarded or deducted. No marks are deducted for getting any of the first fifteen questions wrong. The paper is multiple choice; you can choose any answer out of A, B, C, D and E for each question. There is always just one right answer for each question. Create a program/function that takes two strings and outputs a score. The first string will be your answers to the paper. If you skip a question, use a space, a null byte or an underscore. Otherwise, use the letter A, B, C, D or E for the answer. You can either have the inputs uppercase or lowercase. The second string will be the correct answers for each question in the paper. Your program/function will then output a score. Make your code short. Test cases: ``` DDDDDDDDDDDDDDDDDDDDDDDDD ABCDEABCDEABCDEABCDEABCDE 15 BDBEACCECEDDBDABBCBDAEBCD BDBEACCECEDDBDABBCBDAEBCD 135 DBACBDCDBAEDABCDBEECACDC_ DBADBDCDBAEDABCDBEEDACDCA 117 _________________________ DABDABDABDABDABDABDABDABD 0 DBADBDCDBAEDABCD_E__A__C_ DBADBDCDBAEDABCDBEEDACDCA 99 _______________BBBBBBBBBB AAAAAAAAAAAAAAAAAAAAAAAAA -15 ``` [Answer] # C, ~~88~~ ~~87~~ ~~86~~ 81 bytes ``` c,d;i(char*a,char*b){for(c=d=0;*b;c++,a++)d+=*a^*b++?*a?-c/15-c/20:0:5+c/15;d=d;} ``` [Try it online!](https://tio.run/nexus/c-gcc#lY7bSsQwEIbv9ymGiNAcxCjszYay5PQWQUibFnthlLjeuOyz10mRysouaA7/TDI/38xNGsYpD/DZ9CJReCtTPowNuX0Pebkp5JCJwKKYFgudURXmz7GwKJbQ0eP4Wpq@Ta1UrFM95yJyThNvWXxiHed7Fvd3/f3DFuVR7uRuy@tLpTap04w94SVOualJFFChwBh0FI4bAByOuGuLiOoAINpY5y8JoeobYpzx2lpvvXPGaWMsqkfPCrnuWCHOaPy0GLyrfOO91dbZIFcK1twvi6sWXSmICPK/@wetzeVzNuBZ9yB9Regqf54SDWU4fJQMUm1O8xc "C (gcc) – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ ~~23~~ 22 bytes ``` =s5ị"“HHHQP‘D¤_2Fæ.n⁶¥ ``` [Try it online!](https://tio.run/nexus/jelly#@29bbPpwd7fSo4Y5Hh4egQGPGma4HFoSb@R2eJle3qPGbYeW/n@4e8vh5UpAsjZS4eGO7UCVCr6JBcUKJRmpCsn5KakK@WWpRWBeSWpxiUJyYnFqsd7//y64AJeTi5Oro7Ozq7Ori4uTi6OTkzOQdHVyduFycXIEsp2BlCtQHEi7ujo7Ors4K3Ap4AIgPS7IehRcFRQcFRQw9TjBwX@QOldsBH63uaC5zQXkNkcuIBc7wqPHERcAAA "Jelly – TIO Nexus") ### How it works ``` =s5ị"“HHHQP‘D¤_2Fæ.n⁶¥ Main link. Argument: t (answer to test), s (answer sheet) = Test the characters of t and s for equality. s5 Split into chunks of length 5. ¤ Combine the two preceding links into a niladic chain. “HHHQP‘ Yield the code points, i.e., [72, 72, 72, 81, 80]. D Decimal; yield [[7, 2], [7, 2], [7, 2], [8, 1], [8, 0]]. ị" Index zipwith; use the Booleans in each chunk to index into the corresponding pair. Indexing is 1-based and modular, so 1 gives the first element and 0 the last. _2 Subtract 2 from each result. F Flatten the resulting 5x5 matrix. ¥ Combine the two preceding links into a dyadic chain. n⁶ Test the characters of t for inequality with space. æ. Take the dot product of the integers to the left and the Booleans to the right. ``` [Answer] ## JavaScript (ES6), ~~70~~ ~~68~~ 66 bytes *Saved 2 bytes thanks to Neil* *Saved 2 bytes thanks to ETHproductions* Takes applicant answers `a` and correct answers `c` in currying syntax `(a)(c)`. Expects skipped questions to be marked with a space. ``` a=>c=>a.replace(/\S/g,(a,i)=>s+=a==c[j=i>14,i]?5+j:-j^i>19,s=0)&&s ``` ### Test cases ``` let f = a=>c=>a.replace(/\S/g,(a,i)=>s+=a==c[j=i>14,i]?5+j:-j^i>19,s=0)&&s console.log(f ("DDDDDDDDDDDDDDDDDDDDDDDDD") ("ABCDEABCDEABCDEABCDEABCDE") ); console.log(f ("BDBEACCECEDDBDABBCBDAEBCD") ("BDBEACCECEDDBDABBCBDAEBCD") ); console.log(f ("DBACBDCDBAEDABCDBEECACDC ") ("DBADBDCDBAEDABCDBEEDACDCA") ); console.log(f (" ") ("DABDABDABDABDABDABDABDABD") ); console.log(f ("DBADBDCDBAEDABCD E A C ") ("DBADBDCDBAEDABCDBEEDACDCA") ); console.log(f (" BBBBBBBBBB") ("AAAAAAAAAAAAAAAAAAAAAAAAA") ); ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~86~~ ~~85~~ ~~83~~ 77 bytes ``` f=lambda t,s,i=24:~i and(i/10*-(14<i<t[i]<'_'),5+i/15)[t[i]==s[i]]+f(t,s,i-1) ``` [Try it online!](https://tio.run/nexus/python2#nZBNCoMwFIT3PUV2SarSWuym6CLv5xQiwSJCoJVSXffqNnEhVnTTIUxgJvnyyNgWj/p5b2oxxH3sikt2@zhRd41yp/R8TFSa5S4fSlfl0kodXyOfX3UZkqLovVdRq6a7SarH19t1g2iVpD3JWEgDSLxlUh9mAhCwQWRkIiADgN7ZnwqE/XJBIDA@Rr8xBTwwo0FCGwg@pVVJoTRLgt3TRDCwvVYz/Dxj2Vpj7f8zwKzpJ/ck9fgF "Python 2 – TIO Nexus") ### How it works This defines a recursive function **f** that takes two non-optimal arguments: **t** (the answers to the test) and **s** (the answer sheet). When called only with these two arguments, **f** initializes **i** to **24**, the last index of both **t** and **s**. Every time **f** is called, it first checks if **~i** (the bitwise NOT of **i**) is truthy/non-zero. Since **~(-1) = 0**, this happens once the **i** reaches the value **-1**. If **i = -1**, **~i = 0** is returned, but as **i** takes values from **24** to **0** (all indices of **t** and **s**), the code following `and` is executed and **f** returns the result. While **i** is non-negative, the following happens. First, ``` (i/10*-(14<i<t[i]<'_'),5+i/15) ``` creates a tuple of length **2**: * The quotient `i/10` is **0** if **0 ≤ i < 10**, **1** if **10 ≤ i < 20**, and **2** if **20 ≤ i < 25**. The chained comparison `14<i<t[i]<'_'` returns *True* if and only if all individual comparisons return *True*, i.e., if and only if **i ≥ 15** (the range of questions with penalty), **i** is smaller than **t[i]** (always true since all numbers are smaller than all iterables in Python 2), and **t[i]** is not an underscore. If the comparison returns *False*, the unary `-` returns **0** and the entire expression evaluates to **0**. However, if the comparison returns *True*, the unary `-` returns **-1**, so the entire expression evaluates to **0** if **0 ≤ i < 10**, **-1** if **10 ≤ i < 20**, and **-2** if **20 ≤ i < 25**; these are the net results for wrong or missing answers for all indices **i**. * `5+i/15` returns **5 + 0 = 5** if **0 ≤ i < 15** and **5 + 1 = 6** if **15 ≤ i < 25**. These are the net results for correct answers for all indices **i**. Finally, `[t[i]==s[i]]` selects the first element of the constructed tuple if **t[i]** and **s[i]** differ (wrong or missing answer) and the second one if they are equal (correct answer), then adds the return value of **f** called with decremented **i** to that result. Once **i** reaches **-1**, the final score has been computed and is returned by **f**. [Answer] # Mathematica, 114 bytes ``` Tr@(m=MapThread)[#/.True->#2/.False->-#3&,{Tr/@Partition[m[Equal,#/."_"->u]/.u==_->0,5],{5,5,5,6,6},{0,0,0,1,2}}]& ``` Pure function taking an ordered pair of lists of characters and returning an integer. `m[Equal,#/."_"->u]` returns a list of booleans, except for unevaluated entries of the form `u=="B"` in places where the answer equaled `"_"`; then right away, `u==_->0` turns those unevaluated entries into `0`s. `Tr/@Partition[...,5]` adds these entries up 5 at a time, resulting in a list like `{4False+True, 4False+True, 4False+True, 4False+True, 4False+True}` for the first test case or `{5True, 5True, 5True, 2True, 2True}` for the last test case. Then in each coordinate, `True` and `False` are mapped to the appropriate scores, and the results are added together. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 21 bytes ``` Zm0ṁ135µ;t€⁶E€’;E€ṫ⁹S ``` [Try it online!](https://tio.run/nexus/jelly#nZC9DQIxDIV7prBSXwFCVFf5bwI6ooxAxwCEhhmYAVqQ0nKTXBYJjkAg0KXhKfJT/PLZUspmOx9TXCxX92u/y4dLjjettj/11cd0zjGty3C0SyneO2nJdQ6JRaeKC90MvCMhRWZlFSFBIraq9sDYdvZkhdA6bKZSZ5IqIwuDsdaUn0xqhi8WWqos0vT57P2aDQqAAP/spbfqX7XkQngA "Jelly – TIO Nexus") I *thought* @Dennis's answer was probably beatable. And after trying out a huge number of different possibilities and benefitting from an amazing coincidence, I've finally managed it! This program takes a pair of [student's answers, correct answers] as input, and uses spaces to indicate a missing answer. ## Explanation This program uses some bizarre internal input formats to keep track of what's going on, so we'll take this a step at a time. 1. `Z` This transposes the input, so we'll end up with a list of 25 elements, one for each question; each element is of the form [student's answer, correct answer]. We'll indicate an element of this form with a capital letter; `A` for question 1, `B` for question 2, and so on. So the answers are currently being stored as ``` ABCDEFGHIJKLMNOPQRSTUVWXY ``` 2. `m0` This is a "greater palindrome" operation; we append the reverse of the current value to the value itself, yielding this: ``` ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA ``` 3. `ṁ135` The `ṁ` (mold) operator does a number of things, but in this context, it effectively takes the first 135 elements of the infinite list produced by appending the current value to itself repeatedly. That gives us the following (which I've broken into groups of 50 elements for convenience; this is just a list of 135 pairs internally): ``` ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP ``` 4. `µ;` `µ` sets the current value as the new default for missing operands. We then immediately see a builtin that's missing an operand; `;` appends, but we haven't specified what to append with. As a result, the current value is appended to the value as of the last `µ` (which is also the current value), giving us the following 270-element current value: ``` ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQPABCDEFGHIJKLMNO PQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNO PQRSTUVWXYYXWVUTSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNO PQRSTUVWXYYXWVUTSRQP ``` 5. `t€⁶` Remember that all the capital letters above represent pairs of [student's answer, correct answer]. The `t€⁶` operation operates on each (`€`) pair, and deletes (`t`) spaces (`⁶`) from either side of the pair (i.e. any space that appears in the pair). So we still have the same convoluted list of 270 questions with many repeats, but they're of the form [correct answer] (student didn't answer) or [student's answer, correct answer] (student did answer). 6. `E€’` The `E€’` operation also operates on each (`€`) element, and, due to the use of `E`, replaces the element with 1 if all the elements are equal (i.e. the student didn't answer or got the question right), or 0 if not all the elements are equal (i.e. the student answered but got the question wrong). The use of `’` here changes the numbering, meaning that we now use -1 or 0 respectively. I'll use lowercase letters for this new sort of element, which uses -1 for an answer which would be penalised if it were on a penalty-eligible question, or 0 for a missing or correct answer: ``` abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba abcdefghijklmnopqrstuvwxyyxwvutsrqpabcdefghijklmno pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno pqrstuvwxyyxwvutsrqp ``` 7. `;E€` We've seen both `E€` and `;` before; we're appending something to the current value, and we're using a format of 1 if all the elements are equal, or 0 if some are different (no `’` this time!). There's a missing operand here, so we use the value as of the last `µ` (i.e. the output of step 3). Back in step 3, we hadn't deleted spaces from the elements, so we'll have 1 for a correct answer, or 0 for an incorrect or missing answer (because a space won't match the correct answer). From now on, I'll use capital letters for this 1=correct, 0=incorrect/missing format, and continue to use lowercase letters for 0=correct/missing, -1=incorrect. The resulting value has 405 elements, and looks like this: ``` abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba abcdefghijklmnopqrstuvwxyyxwvutsrqpabcdefghijklmno pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno pqrstuvwxyyxwvutsrqponmlkjihgfedcbaabcdefghijklmno pqrstuvwxyyxwvutsrqpABCDEFGHIJKLMNOPQRSTUVWXYYXWVU TSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVU TSRQPONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVU TSRQP ``` 8. `ṫ⁹` Here comes the amazing coincidence I mentioned earlier. Before talking about this bit of the code, I want to take stock of where we've got to. Each capital letter represents +1 for a correct answer; the first 15 questions (`A` through `O`) appear 5 times each in the string, and the last 10 questions (`P` through `Y`) appear 6 times each. That bit isn't really magical; I designed it that way when I chose the number 135 earlier on in the program (which is 5 × 15 + 6 × 10), and the only stroke of luck here is that 5 happens to be an odd number (so it's the last 10 questions that end up appearing the extra times, rather than the first 10). The 15 letters immediately preceding this contain `p` through `t` (the -1 penalty questions) once, and `u` through `y` (the -2 penalty questions) twice. That also isn't much of a coincidence; because we used `m0` earlier, the extra copies of the questions are in the order `PQRSTUVWXYYXWVUTSRQP`, and the later questions will naturally occur near the middle of that string (so taking the last 15 of the "extra" questions will give fewer repeats to the ones near the edges; and of course, it's not a surprise that the "extra" questions come last). Because each lowercase letter subtracts 1 from the score for an incorrect, non-missing answer, and each uppercase letter adds 1 to the score for a correct answer, we therefore simply need to take the last 135 + 15 = 150 elements in order to get each sort of element the correct number of times. Jelly's command for getting a substring at the end of a list is `ṫ`; however, it doesn't specify the number of elements you want, but rather the index of the first element you want. We have 405 elements at this point, and want 150, so we need to start at index (405 - 150 + 1), or 256. In an amazing coincidence, 256 happens to be the number of distinct octets that exist, and thus has a short representation in Jelly (`⁹`). There was very little I could do in order to make this happen; step 4 added another 135 elements to the start of the list in order to hit the round number, but the fact that it was 135 elements I had to add (a value which was readily available at that point in the program) was really convenient, with basically any other number being completely unhelpful in this situation. Here's how the internal value looks now: ``` uvwxyyxwvutsrqpABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP ONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP ONMLKJIHGFEDCBAABCDEFGHIJKLMNOPQRSTUVWXYYXWVUTSRQP ``` 9. `S` Finally, now we've got a list of modifications to the score from questions, all we need to do is sum them using `S`, and we're done. [Answer] # [Python 2](https://docs.python.org/2/), ~~93~~ 91 bytes ``` f=lambda a,b,n=0:a>""and((a[0]==b[0])*(5+n/15)or-(n/15*n/10)*(a[0]<"^"))+f(a[1:],b[1:],n+1) ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCok6STZ2tglWinpJSYl6KhkRhtEGtrmwQkNbU0TLXz9A1NNfOLdDVADC0gYQAUBqmxUYpT0tTUTgNyDK1idZLAZJ62oeb//wA "Python 2 – TIO Nexus") -2 bytes thanks to @KritixiLithos --- ## Input: * `a` : Answers of the student as a string, `_` for skipped question * `b` : correct answers * `n` : the number of the current question `0`-based, defaults to `0` [Answer] # k, 52 bytes Function takes 2 strings, format per the test cases ``` {+/(~x="_")*(+,/'(15 5 5#'0 -1 -2;15 10#'5 6))@'x=y} ``` Example: ``` k){+/(~x="_")*(+,/'(15 5 5#'0 -1 -2;15 10#'5 6))@'x=y}["DBADBDCDBAEDABCD_E__A__C_";"DBADBDCDBAEDABCDBEEDACDCA"] 99 ``` [Answer] ## Haskell, 84 bytes ``` i x a b|a>'Z'=0|a==b=6-0^x|1<2= -x w x=x<$[1..5*3^0^x] (sum.).zipWith3 i(w=<<[0..2]) ``` Usage example: `((sum.).zipWith3 i(w=<<[0..2])) "DBADBDCDBAEDABCD_E__A__C_" "DBADBDCDBAEDABCDBEEDACDCA"` -> `99`. [Try it online!](https://tio.run/nexus/haskell#Zcm7CoMwFADQ3a@4BEEtePFBnXILefgNhYqGOEgzKNJaDMV/t9k7neGcDjxYGA97Sx4JFYclGqnJi8EfJa8Ich/t4MnzuCsRr5d6CNVHE6Xvz4wZft16d9uzBpfuxHlXIFZ9ds7WLUCwvtyyQQwTMC2FlloFWi2k0qY1RhijDPs/2QaVVoKdPw "Haskell – TIO Nexus"). How it works: `i x a b` calculates the score for a single answer `a` with correct result `b` and the penalty `x` for a wrong answer (a non-negative value). If you skip (`a>'Z'`), the score is `0`, if the answer is right (`a==b`), the score is `6-0^x`, else the score is `-x`. `w=<<[0..2]` makes a list of penalties for all 25 questions by applying `w` to `0`, `1` and `2`, i.e. making `5*3^0^x` copies of each number (-> 15 times `0`, 5 times `1` and 5 times `2`). `zipWith3` applies `i` to the list of penalties, list of answers and list of correct results. Finally all scores are added (`sum`). [Answer] # Octave, ~~61~~ 54 bytes ``` @(a,b)[a==b,-(a<95&a~=b)]*[(x=1:25>15)+5,(1:25>20)+x]' ``` [Try it online!](https://tio.run/nexus/octave#nZFNasMwEIXX1Sm8iqTGhdrgRZMoRPNzCmOETGIohrTUmwThXN2VUlraEnfRxzASevPNwGjaKZ@3uvbGtPmD8punauEvptXNfa1OpliV1bao9LLK1fVePurlqZFTZ/xxWIv@cB5MFkQQkuYkhbSAxLeSFOM6wUDAFpGRiYAsAMbMsUL@6X3ABDY@YTyYUldgRouETl49@uVR8uwn7OaUYAu349vkH90dO2ed@9dk@FJa2JwinPDu5S3rM5PV6QPCamzE3f55eFWd6kMx5n0oR63F4bif3gE "Octave – TIO Nexus") Previous answer: ``` @(a,b)(m=a==b)*(((f=kron(z=[0 0 0:2],z|1)')&1)+5)-(a<95&~m)*f ``` [Answer] # JavaScript (ES6), ~~105~~ ~~103~~ ~~101~~ ~~94~~ ~~89~~ ~~88~~ ~~85~~ ~~84~~ ~~78~~ 77 bytes My first solution in ES6, maybe even first in Javascript O.o ``` f=(s,a,i=24)=>i+1&&(s[i]>'Z'?0:s[i]==a[i]?5+(i>14):~(i>19)*(i>14))+f(s,a,i-1) ``` **s** is the submitted solution and **a** is the correct solution. Both will be taken as strings. Here's a non-recursive solution at 78 bytes: ``` s=>a=>eval([...s].map((c,i)=>c>'Z'?0:c==a[i]?5+(i>14):~(i>19)*(i>14)).join`+`) ``` Takes input through the currying syntax. Thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) for saving 9 bytes! `s[i]` to `c` and `(-1-(i>19|0))` to `~(i>19)`. Thanks to [@Kritixi Lithos](https://codegolf.stackexchange.com/users/41805/kritixi-lithos) for saving a byte! `c=='_'` to `c>'Z'`. [Try it online!](https://tio.run/nexus/javascript-node#hY7PCsIwDMbvPkYPW@umOJkHJ91o/ryEImWIk8Fwh9199dmyk6PFUL40@cIvmTstp7zNe30sla77rEgSOd36e51e0@ZQ@a/WrdPmlMm@LkpVfXw@q@1SqqxbCLtCzY/xPY3Dcz@ML9lJQbEQuTCAxCERSl02KxAQsEFkZCIgA4BO2U07UNwLgAiMs9ElJr8NmNEgoXUg16SVR94zIZCNhQcZCL/IRT9bLVtrrP1/0fwF) ]
[Question] [ Define the function *f(n)* for a positive integer *n* as follows: * *n / 2*, if *n* is even * *3 \* n + 1*, if *n* is odd If you repeatedly apply this function to any *n* greater than 0, the result always seems to converge to 1 (though nobody's been able to prove that yet). This property is known as the [Collatz Conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture). Define an integer's *stopping time* as the number of times you have to pass it through the Collatz function *f* before it reaches 1. Here are the stopping times of the first 15 integers: ``` 1 0 2 1 3 7 4 2 5 5 6 8 7 16 8 3 9 19 10 6 11 14 12 9 13 9 14 17 15 17 ``` Let's call any set of numbers with the same stopping time *Collatz cousins*. For example, 5 and 32 are Collatz cousins, with a stopping time of 5. Your task: write a program or function that takes a nonnegative integer and generates the set of Collatz cousins whose stopping time is equal to that integer. ## Input A nonnegative integer S, given via STDIN, ARGV, or function argument. ## Output A list of all numbers whose stopping time is S, **sorted** in **ascending** order. The list may be output by your program, or returned or output by your function. Output format is flexible: space-separated, newline-separated, or any standard list format of your language is fine, as long as the numbers are easily distinguishable from one another. ## Requirements Your submission must give correct results for any S ≤ 30. It should finish in seconds or minutes, not hours or days. ## Examples ``` 0 -> 1 1 -> 2 5 -> 5, 32 9 -> 12, 13, 80, 84, 85, 512 15 -> 22, 23, 136, 138, 140, 141, 150, 151, 768, 832, 848, 852, 853, 904, 906, 908, 909, 5120, 5376, 5440, 5456, 5460, 5461, 32768 ``` Here is a Gist of the output for [S = 30](https://gist.github.com/dloscutoff/2cea4ebd0cea81f0cf90). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): shortest program in bytes wins. Good luck! [Answer] # Mathematica, ~~98~~ ~~92~~ 89 bytes This solution solves `S = 30` immediately: ``` (p={0};l={1};Do[l=Complement[##&@@{2#,Mod[a=#-1,2]#~Mod~3~Mod~2a/3}&/@l,p=p⋃l],{#}];l)& ``` This is an unnamed function taking `S` as its only parameter and returning a list of the Collatz cousins. The algorithm is a simple breadth-first search. The Collatz cousins for a given `S` are all the integers that can be reached from the Collatz cousins for `S-1` via `2*n` or odd numbers that can be reached via `(n-1)/3`. We also need to ensure that we only produce those integers which were reached for the *first time* after `S` steps, so we keep track of all previous cousins in `p` and remove those from the result. Since we're doing that anyway, we can save a few bytes by computing the steps from *all* previous cousins (not just those from `S-1`) to save a few bytes (that makes it slightly slower, but not noticeably for the required `S`). Here is a slightly more readable version: ``` ( p = {0}; l = {1}; Do[ l = Complement[ ## & @@ {2 #, Mod[a = # - 1, 2] #~Mod~3~Mod~2 a/3} & /@ l, p = p ⋃ l ]~Cases~_Integer, {#} ]; l ) & ``` [Answer] # Pyth, ~~26~~ ~~24~~ 21 bytes ``` Su+yMG-/R3fq4%T6G1Q]1 ``` This code runs instantly for `S=30`. Try it out yourself: [Demonstration](https://pyth.herokuapp.com/?code=Su-%2ByMG%2FR3fq4%25T6G1Q%5D1&input=30&debug=0) Thanks to @isaacg for saving 5 bytes. ### Explanation My code starts with `1` and undos the Collatz function. It maps all numbers `d` of the `S-1` step to `2*d` and `(d-1)/3`. The last one in not always valid though. ``` implicit: Q = input number ]1 start with G = [1] u Q apply the following function Q-times to G: update G by yMG each number in G doubled + + fq4%T6G filter G for numbers T, which satisfy 4==T%6 /R3 and divide them by 3 - 1 and remove 1, if it is in the list (to avoid jumping from 4 to 1) S sort the result and print ``` [Answer] # Python 2, ~~86~~ ~~83~~ ~~75~~ ~~73~~ 71 bytes ``` f=lambda n,k=1:sorted([k][n:]or(k>4==k%6and f(n-1,k/3)or[])+f(n-1,k*2)) ``` Call like `f(30)`. `n = 30` is pretty much instant. *(Thanks to @DLosc for the idea of recursing by `k` being a number rather than a list of cousins, and a few bytes. Thank to @isaacg for dropping `~-`.)* This variant is much shorter, but unfortunately takes too long due to exponential branching: ``` f=lambda n,k=1:sorted([k][n:]or(k>4==k%6)*f(n-1,k/3)+f(n-1,k*2)) ``` [Answer] # CJam, ~~29~~ 26 bytes ``` Xari{{2*_Cmd8=*2*)}%1-}*$p ``` *Credit goes to @isaacg for his idea to remove 1's after each iteration, which saved me two bytes directly and another one indirectly.* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Xari%7B%7B2*_Cmd8%3D*2*)%7D%251-%7D*%24p&input=30) (should finish in less than a second). ### How it works ``` Xa e# Push A := [1]. ri{ e# Read an integer from STDIN and do the following that many times: { e# For each N in A: 2* e# Push I := (N * 2) twice. _Cmd e# Push (I / 12) and (I % 12). 8= e# Push K := (I % 12 == 8). e# (K == 1) if and only if the division ((N - 1) / 3) is exact and e# yields an odd integer. In this case we can compute the quotient e# as (I / 12) * 2 + 1. *2*) e# Push J := (I / 12) * K * 2 + 1. e# This yields ((N - 1) / 3) when appropriate and 1 otherwise. }% e# Replace N with I and J. 1- e# Remove all 1's from A. e# This serves three purposes: e# 1. Ones have been added as dummy values for inappropriate quotients. e# 2. Not allowing 1's in A avoids integers that have already stopped e# from beginning a new cycle. Since looping around has been prevented, e# A now contains all integers of a fixed stopping time. e# 3. If A does not contain duplicates, since the maps N -> I and N -> J e# are inyective (exluding image 1) and yield integers of different e# parities, the updated A won't contain duplicates either. }* e# $p e# print(sort(C)) ``` [Answer] # CJam, 35 bytes ``` 1]ri{_"(Z/Y*"3/m*:s:~\L+:L-_&0-}*$p ``` Explanation coming soon. This is a much faster version than the "pretty straight forward" approach (see it in edit history). [Try it online here](http://cjam.aditsu.net/#code=1%5Dri%7B_%22(Z%2FY*%223%2Fm*%3As%3A~%5CL%2B%3AL-_%260-%7D*%24p&input=25) for `N = 30` which runs in seconds on the online version and instantly in the [Java Compiler](http://sourceforge.net/p/cjam/wiki/) [Answer] # Java 8, 123 ``` x->java.util.stream.LongStream.range(1,(1<<x)+1).filter(i->{int n=0;for(;i>1;n++)i=i%2<1?i/2:3*i+1;return n==x;}).toArray() ``` When `x` is 30, the program takes 15 minutes and 29 seconds. ## Expanded ``` class Collatz { static IntFunction<long[]> f = x -> java.util.stream.LongStream.range(1, (1 << x) + 1).filter(i -> { int n = 0; for (; i > 1; n++) i = i % 2 < 1 ? i / 2 : 3 * i + 1; return n == x; }).toArray(); public static void main(String[] args) { System.out.println(Arrays.toString(f.apply(15))); } } ``` [Answer] # Python 2, 118 bytes Well, I figured that I wouldn't reach the best Python score after seeing @Sp3000's solution. But it looked like a fun little problem, so I wanted to try an independent solution anyway: ``` s={1} for k in range(input()): p,s=s,set() for t in p:s.add(2*t);t>4and(t-1)%6==3and s.add((t-1)/3) print sorted(s) ``` Same thing before stripping whitespace: ``` s={1} for k in range(input()): p,s=s,set() for t in p: s.add(2 * t) t > 4 and (t - 1) % 6 == 3 and s.add((t - 1) / 3) print sorted(s) ``` This is a very direct implementation of a breadth first search. In each step, we have the set with stopping time `k`, and derive the set with stopping time `k + 1` by adding the possible predecessors of each value `t` in the set from step `k`: * `2 * t` is always a possible predecessor. * If `t` can be written as `3 * u + 1`, where `u` is an odd number that is not `1`, then `u` is a predecessor as well. Takes about 0.02 seconds to run for `N = 30` on my MacBook Pro. [Answer] # PHP 5.4+, 178 bytes The function ``` function c($s,$v=1,$p=[],&$r=[]){$p[]=$v;if(!$s--){return$r[$v][]=$p;}c($s,$v*2,$p,$r);is_int($b=($v-1)/3)&!in_array($b,$p)&$b%2?c($s,$b,$p,$r):0;ksort($r);return array_keys($r);} ``` Test & Output ``` echo "0 - ".implode(',',c(0)).PHP_EOL; // 0 - 1 echo "1 - ".implode(',',c(1)).PHP_EOL; // 1 - 2 echo "5 - ".implode(',',c(5)).PHP_EOL; // 5 - 5,32 echo "9 - ".implode(',',c(9)).PHP_EOL; // 9 - 12,13,80,84,85,512 echo "15 - ".implode(',',c(15)).PHP_EOL; // 15 - 22,23,136,138,140,141,150,151,768,832,848,852,853,904,906,908,909,5120,5376,5440,5456,5460,5461,32768 ``` S(30) runs in **0.24 seconds\***, returns 732 elements. A couple are ``` 86,87,89,520,522,524,525,528, [ ... ] ,178956928,178956960,178956968,178956970,1073741824 ``` \*To save on bytes, I had to add `ksort` and `array_keys` at every step. The only other choice I had was to make a small wrapper function that calls `c()` and then calls `array_keys` and `ksort` on the result once. But due to the time still being decently snappy, I decided to take the performance hit for low byte count. Without the proper sorting & processing, the time is **0.07 seconds** on average for S(30). If anyone has any clever ways of getting the proper processing only once without too many additional bytes, please let me know! (I store my numbers as array keys, hence the use of `array_keys` and `ksort`) [Answer] # C Language ``` #include <stdio.h> #include <limits.h> const int s = 30; bool f(long i) { int r = 0; for(;;) if (i < 0 || r > s) return false; else if (i == 1) break; else{r ++;i = i % 2 ? 3*i + 1 : i/2;} return (r==s); } void main(){ for(long i = 1; i < LONG_MAX; i++) if (f(i)) printf("%ld ", i); } ``` ]
[Question] [ Given an input string of length `2` or longer consisting solely of alphabetical characters `[A-Z]` or `[a-z]` (your choice if they're all uppercase or all lowercase), output a continuous string of characters forming a double diamond pattern. The input string starts on the center line and extends down-and-right at a diagonal until the end of the input string is reached. Then, the pattern continues up-and-right at a diagonal until you're as far above the center line as the length of the input string minus 1. Continue down-and-right back to the center line, then down-and-left, then up-and-left (going "behind" the center character), and finally down-and-left back to the starting character. That's a little wordy, and it's better demonstrated by some examples: ``` "YOU" U Y Y O U O Y O U O Y U Y U O ^ ^ ↙ ↖ ↗ ↘ ↘ ↗ > ↘ ↗ ↖ ↙ V V ``` See how the `YOU` starts at the center line and follows down-and-right, then up-and-right, etc., until it loops back to the beginning. Note especially how the `Y` on the up-and-left portion is "behind" the `O` and therefore not shown. Some further examples: ``` "HI" I I H H H I I "TEST" E E S T T S T T T T T S T E E E E S T T S T T "HELLO" L L O L E L H E H O E H O H H L E E L L L L E L L L H E O O H ``` --- * Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * The input is guaranteed to be at least two letters long (i.e., you'll never receive `""` as input). * 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 (e.g., feel free to pad as a rectangle). * [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] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` GH<↗↘>↖↙LθθGH<Lθθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT/PIz8nJ79cw8pGR8EqtCAoMz2jBMhyyS/Pg7HtwDI@qWkwCQjTJzUvvSRDo1BTR6FQ05oL0zhUBf//e7j6@Pj/1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` GH ``` Draw along a path. ``` <↗↘>↖↙ ``` Draw in the directions ↘↗↗↘↙↖↖↙ (the `<` and `>` are shorthands for those two pairs, but the other pairs don't have shorthands.) ``` Lθ ``` Each path segment has the same length, including the ends, of the length of the input. ``` θ ``` Use the input as the text to be written along the path. ``` GH<Lθθ ``` Print the first two parts of the path again so that the middle character is correct. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` gIR7._•Íη•Λ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/3TPIXC/@UcOiw72H@w5tBzLOzf7/38XT0dffzwUA "05AB1E – Try It Online") ``` Λ use the canvas function g with the length of input for each segment IR7._ the input reversed and rotated left by 7 characters (we will draw this backwards to have the right center character) •Íη• and the directions 1, 3, 3, 1, 7, 5, 5, 7 as a compressed number. ``` [Answer] # JavaScript (ES6), ~~157 155~~ 154 bytes Returns a matrix of characters. ``` s=>(y=n=s.length,y+=i=X=Y=-1,m=[...Array(y+n)].map(_=>r=Array(4*n-3).fill` `),g=x=>x?g(x-=r[m[y][++i==6*n-6||+x]=s[i%n],y-=m[y-Y]?Y:Y=-Y,x-X]?X:X=-X):m)`` ``` [Try it online!](https://tio.run/##LY5Na4QwGITv/RW5lCTNB5SWPVhepQdhCwt76BaUNFSx6mbRZEmWYmD/u3VtT88wMzBzqn/q0Hhzvgjrvtu5gzlASiJYCHJobX858sjAQAEliEc@gpJSvnpfRxKZpVqO9Zl8Qerhz3x@sOKJys4MQ4UqynuYIJ2ynkwCvBpV1IoxA7BZepvrlU0agjL3VvMoYIlFqbMyWbZKPolCZ0VSgChoMtKqml8U3r5hjnC5/7jhkL8fbtzmu90e6zvZOZ/XzZEEBClqnA1uaOXgetKRQNeraxLkyRlLMKb0X31aTBFDK@n8Cw "JavaScript (Node.js) – Try It Online") ### How? Given the length \$n\$ of the input string, we build a matrix of size \$w\times h\$, with: * \$w = 4n-3\$ * \$h = 2n-1\$ We run a simulation of a 'ball' bouncing in this matrix, starting at \$(0,n-1)\$ and heading South-East, until it's back to its initial position. The 0-based index of the center character that must be skipped in the diamond shape is: $$p=6n-6$$ Example for \$n=4\$: [![enter image description here](https://i.stack.imgur.com/onMG0.png)](https://i.stack.imgur.com/onMG0.png) ### Commented ``` s => ( // s = input string y = n = s.length, // n = length of s y += i = X = Y = -1, // y = n - 1; i = X = Y = -1 m = // create a matrix m[]: [...Array(y + n)].map(_ => // - of height 2n-1 r = Array(4 * n - 3) // - of width 4n-3 (save one of these rows in r[]) .fill` ` // - initially filled with spaces ), // g = x => // g is a recursive function taking x x ? // if x is truthy: g( // do a recursive call: x -= r[ // update x: m[y][ // update m[y][x]: ++i == 6 * n - 6 // unless this is the 2nd pass through the || +x // center cell, set it to the next character ] = s[i % n], // in s (otherwise we write to m[y][true] // instead, which has no effect) y -= // update y: m[y - Y] ? Y // bounce vertically if m[y - Y] is undefined : Y = -Y, // x - X // bounce horizontally ] ? X // if r[x - X] is undefined : X = -X // ) // end of recursive call : // else: m // stop recursion and return m[] )`` // initial call to g with x = [''] (zero-ish but truthy) ``` [Answer] ## JavaScript (ES6), 136 bytes ``` f= (s,l=s.length-1,z=l*4,a=[...Array(l-~l)].map(_=>Array(z+1).fill` `),g=x=>x--?g(x,a[a[y=(x+l)%z]?y:z-y][x>z?z+z-x:x]=s[x%-~l]):a)=>g(z+z) ``` ``` <input oninput=o.textContent=f(this.value).map(c=&gt;c.join``).join`\n`><pre id=o> ``` Returns a two-dimensional array. Works by drawing the string into the array directly computing the destination co-ordinates working backwards from the end so that the centre cell is overwritten automatically. Explanation: ``` (s ``` Input string. ``` ,l=s.length-1 ``` Distance between "bounces", also half the last row index and one less than the length. ``` ,z=l*4 ``` Last column index, also half of the length of text to draw. ``` ,a=[...Array(l-~l)].map(_=>Array(z+1).fill` `) ``` Array of spaces. ``` ,g=x=>x-- ``` Count down from the last cell to the first. ``` ?g(x ``` Recursive call to process the remaining cells. ``` ,a[a[y=(x+l)%z]?y:z-y] ``` Calculate the row of this cell. ``` [x>z?z+z-x:x]=s[x%-~l]) ``` Calculate the column of this cell and the character that belongs there. ``` :a ``` Finish by returning the array. ``` )=>g(z+z) ``` Start at the end of the text. [Answer] # [J](http://jsoftware.com/), ~~79~~ ~~77~~ 75 bytes ``` (|.@$~8*])`([:;/(1,~<:@])+/\@,(_2{&1 _1\#:33495)}.@#~])`(' '$~1+2 4*])}<:@# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWr0HFTqLLRiNRM0oq2s9TUMdepsrBxiNbX1Yxx0NOKNqtUMFeINY5StjI1NLE01a/UclOtAitUV1FXqDLWNFEyAemuBWpT/a3JxpSZn5CukKah7eKpD2OrqcLEQ1@AQTFEPVx8ff3Uurv8A "J – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), [~~201~~](https://tio.run/##TY5Ra8IwFIXf@ytKxiBp791sdBtrjEVE1gdZYfZlqA@h6gzYdLRVquJv71J9WSC55zuce28yzPbK/LRtAyfQcIQcjNjSCs4s26nSq8TlVhUUCy1pI8/eADnz6MkqjgFbiW1RUiUroYWRuQxYsUDUK6kfm6jPw6AntGw8xPMteLSaIxdHRKF9C7lvbIfNdw/2edTV0O5T0vN9FamwAtMNGzXYjzAIDeRSPzeRvcMTBlEeWjMQv4e6ogUT1/ZBm2x/WG/cYVWvdfG0GzmONrWbK20ocy/OlpL4mwBnopPpdJ4SGNwhns5mCYGXOyVf48@PKYHX/zgn8HbnSZxMktk4tYl369x@QJZmadyNWRPrOK495aY@lMbtCefa/gE "C (clang) – Try It Online") [~~196~~](https://tio.run/##TY5Pa8JAEMXv@RRhS2E3mW1N0j806xpExBykgeqlqIcl0bpgJiWJkih@9nSNlw4M836PN8OkPD0o/Om6BlrQcIIcUOxoBWeW7lXpVOLSTyUrKFZa0laeHZ97zKGNbN2WbcSuKKnQAmUuPVasONcbqR@bKPBDbyC0bBzOz33qZLTPfXHiXGjXQO6i2TB5GfhRLxwVDkBJx3VVpMIK8HZq1PAg4l6IkEv93ESmhy33ojw0pid@j3VFCyau3YPG9HDMtvawqjNdPO1HlqWxtnOlkTL7Yu0oib8J@Ezc5HK6WBJ4uUM8nc8TAq93Sr7Gn7Mpgbf/uCDwfudJnEyS@XhpEh/G6T8ga1yjvcWMGMeyTZXb@liiPRDWtfsD "C (clang) – Try It Online") 188 bytes ``` x,y,i,v,m,n;f(s,z){char*a=s,o[i=(y=z*2-1)*(x=y+y)];for(v=x*2-2;i;n=m=1)o[--i]=i%x?32:10;for(i=x*--z;v--;i+=x*m+n)o[i]==32?o[i]=*a:0,a=*++a?a:s,n=i%x>x-3?-1:n,m=i/x?i/x<y-1?m:-1:1;puts(o);} ``` [Try it online!](https://tio.run/##TY5Na8JAEIbv@RVhS2E3mW1N7AfNugYR0YM0UL0U9bDEpC6YScmHJIq/PV3NpQMD7/PyMEzM46PCn65roAUNJ8gARUpLOLNLfFCFo2QJ@UZL2sqz43OPObSRrduynUjzgp5kY1pfaIEykx7LN5zrndSPTTj0A29wl7SROD@LE@dCuwYyF41pPDn0w3twVDAAJR3XVaEKSsDbiXHDhyH3AoRM6ucmNDtquRdmgSk98VtXJc2ZuHYPGuNjvU/sUVntdf50GFuWxsrOlEbK7IuVUrL4JuAzcYvr2WpN4KWHxWy5jAi89hR9TT7nMwJv/3FF4L3n6SKaRsvJ2hgfprl/QLa4RTvBPTGNZZspkqou0B4I69r9AQ "C (clang) – Try It Online") -13 @ceilingcat suggestions [Answer] # [Python 2](https://docs.python.org/2/), 137 bytes ``` s=input();n=len(s);m=2*n-2 for r in range(m+1):print''.join([s[[x,-8-x][(x<=m)==(m>2*r)]%n],' '][r!=(x+1-n)%m!=m-r]for x in range(4*n-3)) ``` [Try it online!](https://tio.run/##RY/BbsIwEETP8VeYA1obkkqkPVRQVyo0FZWQuPRm@UBTU9LiTbQJqvn61A5IXMZrjXfeuDl3hxrzvqy/rCIA6FtVYXPqhFygOloUrVw4lU8wy9m@Jk68Qk47/LbCTWdy3lCFHcDdT12h0K3WPs0eM2@08E/KSaWEe84nJM0YTQocjKaREn46y1CO3Ui5jEzM9bfchwC7l7IPbRiLEv02@hrW75DCy3J10ddwrIvNZgtmzpKhCm9Zsg@lr9dhn/0dqqPlH3Sy4VlH56CJ9bbk8dssjKVtOl5s3wqimqL7SXb320ccG3DsgmNX3D8 "Python 2 – Try It Online") A full program that takes a string as input as prints out the diamondized version. ]
[Question] [ Write a mathematical statement, using the symbols: * `There exists at least one non-negative integer` (written as `E`, existential quantifier) * `All non-negative integers`(written as `A`, universal quantifier) * `+` (addition) * `*` (multiplication) * `=` (equality) * `>`, `<` (comparison operators) * `&`(and), `|`(or), `!`(not) * `(`, `)` (for grouping) * variable names which is equivalent to the statement > > There exists a rational number a, such that π + e \* a is rational. > > > (of course, \$\pi =3.1415...\$ is the mathematical constant equal to the circumference divided by the diameter of a circle, and \$e=2.7182...\$ is [Euler's number](https://en.wikipedia.org/wiki/E_(mathematical_constant))) You must prove that your statement is indeed equivalent to the statement above. Obviously, the “shortest” way to go about this is to prove the statement true or false, and then answer with a trivially true or false statement, as all true statements are equivalent to one another, as are all false statements. However, the given statement’s truth value is an [unsolved problem in mathematics](https://math.stackexchange.com/questions/159350/why-is-it-hard-to-prove-whether-pie-is-an-irrational-number): we don't even know if \$\pi+e\$ is irrational! Therefore, barring groundbreaking mathematical research, the challenge is to find a “simple” equivalent statement, prove its equivalence, and describe it as briefly as possible. # Scoring `E` `A` `+` `*` `=` `>` `<` `&` `|` and `!` each add 1 to the score. `(` and `)` don't add anything to the score. Each variable name adds 1 to the score. E.g. `E x (A ba x+ba>x*(x+ba))` score 13 (`E` `x` `A` `ba` `x` `+` `ba` `>` `x` `*` `x` `+` `ba`) Lowest score wins. --- # Note: Disclaimer: This note was not written by the OP. * This is **not** a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. Answers are not required to contain code. * This is similar to, but not, a [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'") challenge, as you need to write a statement and prove it being equivalent to another statement. * You are allowed to submit a trivially-true (e.g., for all x, x = x `Ax x=x`) or a trivially-false statement (e.g., for all x, x > x `Ax x>x`) if you can prove the statement above is true/false. * You are allowed to use additional symbols (similar to lemma in proof-golf), but the score would be counted the same as you not using them. For example, if you define `a => b` to mean `(!a) | b`, each time you use `=>` in your proof, your score increases by 2. * Because constants are not listed in the allowed symbols, you must not use them. For example: The statement `1 > 0` can be written as ``` Forall zero: ( zero + zero = zero ) => Forall one: ( Forall x: x * one = x ) => one > zero ``` at the score of 23. (remember that `=>` costs 2 per use). # Hints * To use natural constants, you may do `E0, 0+0=0 & E1, At 1*t=t &` (so you don't need `=>` which is more expansive); for numbers larger than 1, just add some 1's [Answer] # 671 `E a (a+a>a*a & (E b (E c (E d (A e (A f (f<a | (E g (E h (E i ((A j ((!(j=(f+f+h)*(f+f+h)+h | j=(f+f+a+i)*(f+f+a+i)+i) | j+a<e & (E k ((A l (!(l>a & (E m k=l*m)) | (E m l=e*m))) & (E l (E m (m<k & g=(e*l+(j+a))*k+m)))))) & (A k (!(E l (l=(j+k)*(j+k)+k+a & l<e & (E m ((A n (!(n>a & (E o m=n*o)) | (E o n=e*o))) & (E n (E o (o<m & g=(e*n+l)*m+o))))))) | j<a+a & k=a | (E l (E m ((E n (n=(l+m)*(l+m)+m+a & n<e & (E o ((A p (!(p>a & (E q o=p*q)) | (E q p=e*q))) & (E p (E q (q<o & g=(e*p+n)*o+q))))))) & j=l+a+a & k=j*j*m))))))) & (E j (E k (E l ((E m (m=(k+l)*(k+l)+l & (E n (n=(f+m)*(f+m)+m+a & n<e & (E o ((A p (!(p>a & (E q o=p*q)) | (E q p=e*q))) & (E p (E q (q<o & j=(e*p+n)*o+q))))))))) & (A m (A n (A o (!(E p (p=(n+o)*(n+o)+o & (E q (q=(m+p)*(m+p)+p+a & q<e & (E r ((A s (!(s>a & (E t r=s*t)) | (E t s=e*t))) & (E s (E t (t<r & j=(e*s+q)*r+t))))))))) | m<a & n=a & o=f | (E p (E q (E r (!(E s (s=(q+r)*(q+r)+r & (E t (t=(p+s)*(p+s)+s+a & t<e & (E u ((A v (!(v>a & (E w u=v*w)) | (E w v=e*w))) & (E v (E w (w<u & j=(e*v+t)*u+w))))))))) | m=p+a & n=(f+a)*q & o=f*r)))))))) & (E m (m=b*(h*f)*l & (E n (n=b*(h*f+h)*l & (E o (o=c*(k*f)*i & (E p (p=c*(k*f+k)*i & (E q (q=d*i*l & (m+o<q & n+p>q | m<p+q & n>o+q | o<n+q & p>m+q))))))))))))))))))))))))))` ### How it works First, multiply through by the purported common denominators of a and (π + e·a) to rewrite the condition as: there exist a, b, c ∈ ℕ (not all zero) with a·π + b·e = c or a·π − b·e = c or −a·π + b·e = c. Three cases are necessary to deal with sign issues. Then we’ll need to rewrite this to talk about π and e via rational approximations: for all rational approximations π₀ < π < π₁ and e₀ < e < e₁, we have a·π₀ + b·e₀ < c < a·π₁ + b·e₁ or a·π₀ − b·e₁ < c < a·π₁ + b·e₀ or −a·π₁ + b·e₀ < c < −a·π₀ + b·e₁. (Note that we now get the “not all zero” condition for free.) Now for the hard part. How do we get these rational approximations? We want to use formulas like 2/1 · 2/3 · 4/3 · 4/5 ⋯ (2·k)/(2·k + 1) < π/2 < 2/1 · 2/3 · 4/3 · 4/5 ⋯ (2·k)/(2·k + 1) · (2·k + 2)/(2·k + 1), ((k + 1)/k)k < e < ((k + 1)/k)k + 1, but there’s no obvious way to write the iterative definitions of these products. So we build up a bit of machinery that I first described in [this Quora post](https://www.quora.com/How-is-power-of-10-represented-in-Hofstadters-Typographical-Number-Theory/answer/Anders-Kaseorg?srid=uXs). Define: divides(d, a) := ∃b, a = d·b, powerOfPrime(a, p) := ∀b, ((b > 1 and divides(b, a)) ⇒ divides(p, b)), which is satisfied iff a = 1, or p = 1, or p is prime and a is a power of it. Then isDigit(a, s, p) := a < p and ∃b, (powerOfPrime(b, p) and ∃q r, (r < b and s = (p·q + a)·b + r)) is satisfied iff a = 0, or a is a digit of the base-p number s. This lets us represent any finite set using the digits of some base-p number. Now we can translate iterative computations by writing, roughly, there exists a set of intermediate states such that the final state is in the set, and every state in the set is either the initial state or follows in one step from some other state in the set. Details are in the code below. ### Generating code in [Haskell](https://www.haskell.org/) ``` {-# LANGUAGE ImplicitParams, TypeFamilies, Rank2Types #-} -- Define an embedded domain-specific language for propositions. infixr 2 :| infixr 3 :& infix 4 := infix 4 :> infix 4 :< infixl 6 :+ infixl 7 :* data Nat v = Var v | Nat v :+ Nat v | Nat v :* Nat v instance Num (Nat v) where (+) = (:+) (*) = (:*) abs = id signum = error "signum Nat" fromInteger = error "fromInteger Nat" negate = error "negate Nat" data Prop v = Ex (v -> Prop v) | Al (v -> Prop v) | Nat v := Nat v | Nat v :> Nat v | Nat v :< Nat v | Prop v :& Prop v | Prop v :| Prop v | Not (Prop v) -- Display propositions in the given format. allVars :: [String] allVars = do s <- "" : allVars c <- ['a' .. 'z'] pure (s ++ [c]) showNat :: Int -> Nat String -> ShowS showNat _ (Var v) = showString v showNat prec (a :+ b) = showParen (prec > 6) $ showNat 6 a . showString "+" . showNat 7 b showNat prec (a :* b) = showParen (prec > 7) $ showNat 7 a . showString "*" . showNat 8 b showProp :: Int -> Prop String -> [String] -> ShowS showProp prec (Ex p) (v:free) = showParen (prec > 1) $ showString ("E " ++ v ++ " ") . showProp 4 (p v) free showProp prec (Al p) (v:free) = showParen (prec > 1) $ showString ("A " ++ v ++ " ") . showProp 4 (p v) free showProp prec (a := b) _ = showParen (prec > 4) $ showNat 5 a . showString "=" . showNat 5 b showProp prec (a :> b) _ = showParen (prec > 4) $ showNat 5 a . showString ">" . showNat 5 b showProp prec (a :< b) _ = showParen (prec > 4) $ showNat 5 a . showString "<" . showNat 5 b showProp prec (p :& q) free = showParen (prec > 3) $ showProp 4 p free . showString " & " . showProp 3 q free showProp prec (p :| q) free = showParen (prec > 2) $ showProp 3 p free . showString " | " . showProp 2 q free showProp _ (Not p) free = showString "!" . showProp 9 p free -- Compute the score. scoreNat :: Nat v -> Int scoreNat (Var _) = 1 scoreNat (a :+ b) = scoreNat a + 1 + scoreNat b scoreNat (a :* b) = scoreNat a + 1 + scoreNat b scoreProp :: Prop () -> Int scoreProp (Ex p) = 2 + scoreProp (p ()) scoreProp (Al p) = 2 + scoreProp (p ()) scoreProp (p := q) = scoreNat p + 1 + scoreNat q scoreProp (p :> q) = scoreNat p + 1 + scoreNat q scoreProp (p :< q) = scoreNat p + 1 + scoreNat q scoreProp (p :& q) = scoreProp p + 1 + scoreProp q scoreProp (p :| q) = scoreProp p + 1 + scoreProp q scoreProp (Not p) = 1 + scoreProp p -- Convenience wrappers for n-ary exists and forall. class OpenProp p where type OpenPropV p ex, al :: p -> Prop (OpenPropV p) instance OpenProp (Prop v) where type OpenPropV (Prop v) = v ex = id al = id instance (OpenProp p, a ~ Nat (OpenPropV p)) => OpenProp (a -> p) where type OpenPropV (a -> p) = OpenPropV p ex p = Ex (ex . p . Var) al p = Al (al . p . Var) -- Utility for common subexpression elimination. cse :: Int -> Nat v -> (Nat v -> Prop v) -> Prop v cse uses x cont | (scoreNat x - 1) * (uses - 1) > 6 = ex (\x' -> x' := x :& cont x') | otherwise = cont x -- p implies q. infixl 1 ==> p ==> q = Not p :| q -- Define one as the unique n with n+n>n*n. withOne :: ((?one :: Nat v) => Prop v) -> Prop v withOne p = ex (\one -> let ?one = one in one + one :> one * one :& p) -- a is a multiple of d. divides d a = ex (\b -> a := d * b) -- a is a power of p (assuming p is prime). powerOfPrime a p = al (\b -> b :> ?one :& divides b a ==> divides p b) -- a is 0 or a digit of the base-p number s (assuming p is prime). isDigit a s p = cse 2 a $ \a -> a :< p :& ex (\b -> powerOfPrime b p :& ex (\q r -> r :< b :& s := (p * q + a) * b + r)) -- An injection from ℕ² to ℕ, for representing tuples. pair a b = (a + b) ^ 2 + b -- πn₀/πd < π/4 < πn₁/πd, with both fractions approaching π/4 as k -- increases: -- πn₀ = 2²·4²·6²⋯(2·k)²·k -- πn₁ = 2²·4²·6²⋯(2·k)²·(k + 1) -- πd = 1²⋅3²·5²⋯(2·k + 1)² πBound p k cont = ex (\s x πd -> al (\i -> (i := pair (k + k) x :| i := pair (k + k + ?one) πd ==> isDigit (i + ?one) s p) :& al (\a -> isDigit (pair i a + ?one) s p ==> ((i :< ?one + ?one :& a := ?one) :| ex (\i' a' -> isDigit (pair i' a' + ?one) s p :& i := i' + ?one + ?one :& a := i ^ 2 * a')))) :& let πn₀ = x * k πn₁ = πn₀ + x in cont πn₀ πn₁ πd) -- en₀/ed < e < en₁/ed, with both fractions approaching e as k -- increases: -- en₀ = (k + 1)^k * k -- en₁ = (k + 1)^(k + 1) -- ed = k^(k + 1) eBound p k cont = ex (\s x ed -> cse 3 (pair x ed) (\y -> isDigit (pair k y + ?one) s p) :& al (\i a b -> cse 3 (pair a b) (\y -> isDigit (pair i y + ?one) s p) ==> (i :< ?one :& a := ?one :& b := k) :| ex (\i' a' b' -> cse 3 (pair a' b') (\y -> isDigit (pair i' y + ?one) s p) ==> i := i' + ?one :& a := (k + ?one) * a' :& b := k * b')) :& let en₀ = x * k en₁ = en₀ + x in cont en₀ en₁ ed) -- There exist a, b, c ∈ ℕ (not all zero) with a·π/4 + b·e = c or -- a·π/4 = b·e + c or b·e = a·π/4 + c. prop :: Prop v prop = withOne $ ex (\a b c -> al (\p k -> k :< ?one :| (πBound p k $ \πn₀ πn₁ πd -> eBound p k $ \en₀ en₁ ed -> cse 3 (a * πn₀ * ed) $ \x₀ -> cse 3 (a * πn₁ * ed) $ \x₁ -> cse 3 (b * en₀ * πd) $ \y₀ -> cse 3 (b * en₁ * πd) $ \y₁ -> cse 6 (c * πd * ed) $ \z -> (x₀ + y₀ :< z :& x₁ + y₁ :> z) :| (x₀ :< y₁ + z :& x₁ :> y₀ + z) :| (y₀ :< x₁ + z :& y₁ :> x₀ + z)))) main :: IO () main = do print (scoreProp prop) putStrLn (showProp 0 prop allVars "") ``` [Try it online!](https://tio.run/##pVhfbxvHEX/np5gyhnlHikwsyXJLiDSUxg0CBLZRJ3mxHWPvuJK2JO9Ot0eJVNXCKlogQJ/7OQr4xe/6Av4O/iLuzOzu3d6RlOpEgMjb@b@zv5md46nQUzmbffr01/4X8P3R029/PPr2CXw3z2YqVsVzkYu53oEfVpn8k5irmZK4@rNIprtE0vBF/2@tVr8P38hjlUgQCch5JCcTOYFJOhcq6etMxupYxTATyclCnEg4TnPI8jRLtSpUmuhBSyXHapnDLgyvWm6xB8P7dgH7MBx5z2Pv@dA@z@AAhr1y8QiG3VZrIgoBT0UB5y2AEfwkcn66MjSUL5klqWtJaEgXIoklPF3MIWBiCBenMpcoHvRCtBcMeyEtumbRpYWINC7UBB@1OklQdwQyz3HLbbtGU23kHufp/LukkCcyr0R8opVL5IkoZCVi18w1G3yOubQ7fLKE4Bz6Y0sLeWdHsw1Eu93RegbG66RDj2SM4OFUfivilU98mhYQOJ8MEqWzmVjVDh9UAsWphBN1LhOCxlwUg5aYzfCwNAyH8PJFkavk5HVJGyGyKLtw2Id2G4ZgGUiLifayIzowGEDnsvMaadkilxBo6PXgZfwaA9Gn6QVtB21jqikvtDJeaPUC@S9KqTcQMGzoiIlm5c5LgSyXMQSCwBShEEWGHCwc3E7AzDEchHAPnMIBCBj4ttq9tiUQ@xFE67a7220/8m0/WrPd9W3/Hm2zcT6VKgG8rDLgUl7PBguZiBBmWYigGh7nUm4L7IELzBoO2k@gTcdwTh9taIc2Mja8j3qUZbLYdIcA/jXujn6lO0Flgfl@s8XTvp/xh2sZH/kZf2hPs25@/BvMj@82f/gbzB/eYT6jyj8zidviYQ89OIbJdWbE657gPrT9I9mDs43HkVFbud3jbsPj3haPV3WPu2sesdqpa2XOW039dzXlP1gf3Nn@mM6zBXZl6mQ6TnM5aPGX7TOmjWI1Yb1VDG4sb6ixPPCIZSeBkiagBw/wvyREdfnu3fJGwZU9fwdhLSJDM5U9wtRYdUMm6dCXMyV5t1xGtXRWiy5rRnfWUBh/rsLh5yrc9xQM0nwNpjRVrj5TxcJo1JDJLFwSvO2UpPHiIhdZJvFeo7Eo6Yt8BXKpdKFxmJoQEa@3QSueCa3hWSYT69xNIgWOYSX9J7QPqL6DdyKdc1Y298ATCb3hprToLupthkv@iG93uXRTDnrip8pmUIWJgcDfGf61ANDK2HMtKMxsu2vHH61tFHdohh58HOBiQDNeaKIiFo0@@OixKP0/FjjIFivOeJzO52kCehHJJXYTrXEoATlTc5UIGlAw9Vo2ZgUu5aB8cpkpH1lloXE8XqJ9LDCahoISjUvo023VhYBleIEzAo14uJNXyw5Zwk@snCVhlUzg2sxtKbaY/EJpak6GwVvKQNHIjubOBm4GfgCjEY7KGX1hpxvxQGag7M/sKc3tmlvXIlFnCwkJXKjiFJJeMk66mAFaPUsoCxgC/gXB45SXYMdidAP2r5oxq3Q4/Yzbt1yycPCKbPRLzZksgM2OKCJHxemQaD3@xM5AX12zuM9Ixn0IUFgsMF/MCpXNcEPHMBm0JupcTTAfE2TZzEYUE9/uE6Ce6Wtn6QXO3KhKeNR6MaeWnxEvy9VchoMWSzw7fk5LUkCrCC1rNaLgHtu4nOuIXGPu3Tqr@fwKEH4CmSeqIMd0AJHQsp8BviZEGI3eForS37CWAG2TSojbxfU9eCVcUnkSoG7HK5t2cBHXthOxnMnSGeTEz3mOIKqmjGEP7CKIeiAIuRE@5KHZzFGCp/QXGVO18FsNfPznf27eQZHSww5XWS6ptmRS0FaKBZ4SvvVlQlECInp5oisLL7Gf@UKJ2O6Ht8nHf7z98sPbCRzi4st9/kLaNdF2DEYjrAd0KmLzMoGtNE9FfEpuWAWBPSVjKolzicnVw8o0XV83727e79PHwc27j//@b7B7834a0npayl3fKhdM6R4IjfSE@j0J/GuPeA8rWRa6edf68PbrdIF9PYOpKd9aRVDDICtVVYhZWVnIVx7HkBSdDSeSA5mG1DKuoEnGfwJnaGIc1Y2AgxNac3Ka@q1FDmyIxQYkmgHV7XEEiueR0uy6e9NSFOHtsSl2V0hcq0ZzeLWuVGG6GZfqgOhsjG1jhCztx9jYua9JISkn3YxVMYK7aC7EP88MdbcSdUuUmPoOSpxZkR4svQbIOLEcK4nHaIpPco1IKhFJ/1we8v@oDrmlNKSN0eL65ynHahnXHsMDviTcT0uKvAvi0kc4da49exDEwhe9VytqQPUzmsJqGzibNUItpXH0vhNBjWajD9X00YSqB1IfnbSIaDFdw@kaQh02o83wrAVKUttC7dwV6ya0uqCDqiEQVqv4qbV31oArt@HWYUJuQ61hGDFpIfsDTXlmxgWxA9EOxPDxl1/osoAgwREFB164lHkaGhCLm/fcyvFeuHnPYw9enHyLWsbIMHrMcEKVVow3jf/ec26WhEo3mNzzEUrwibe2YEJ14@CmFSjqhx/43R5v5rUa3gABWdOo5@82xAg8G2u/y1WE2ktabW6CTa3rmtb11tZp9SISt86oF5Hearu3DZrXdc3rWzSN7gEEsdGpQr28VQsPYGlwyaHhIV0S0nl/TLumoe1yy93SMILaK6NYGUHtlXFwtxEXwtIz4kJYOiMhjVT0qzm/cDzDl2mzsj954viHNRV4b5P4EfJvnMWLIv8@QZ77eeIrZrrfRqHdDj99@h8 "Haskell – Try It Online") [Answer] # 270 ``` E1 { Exist 1, defined when Any k introduced } Ec1 Ec2 Ec3 Ec4 Ec5 Ak k*1=k & c3>1 & ( En0 An n<n0 | { for large enough n, |(c1-c4)e+c3(4-pi)/8+(c2-c5)|<1/k } Ex Ep Ew Emult At (Eb ((b>1 & Eh b*h=t) &! Eh h*p=b)) | { x read in base-p, then each digit in base-w. t as a digit } Ee1 Ee2 Ehigher Elower e2<p & lower<t & ((higher*p+e1)*p+e2)*t+lower=x & { last digit e1, this digit e2 } { Can infer that e2=w+1 | e1<=e2 & u1<=u2 & i1<=i2 & s1<=s2 & t1<=t2, so some conditions omitted } Ei1 Es1 Et1 Eu1 (((u1*w)+i1)*w+t1)*w+s1=e1 & { (u,i,t,s) } Ei2 Es2 Et2 Eu2 i2<w & s2<w & t2<w & (((u2*w)+i2)*w+t2)*w+s2=e2 & { e2=1+w is initial state u=i=0, s=t=1 } (e2=w+1 | e1=e2 | i2=i1+1+1 & s2=s1*(n+1) & t2=t1*n & { i=2n, s=(n+1)^n, mult=t=n^n, s/mult=e } Eg1 Eg2 g1+1=(i2+i2)*(i2+i2) & g1*u1+mult=g1*u2+g2 & g2<g1) & { u/mult=sum[j=4,8,...,4n]1/(j*j-1)=(4-pi)/8. mult=g1*(u2-u1)+g2 } (t>1 | i2=n+n & t2=mult & Ediff Ediff2 { check at an end t=1 } c1*s2+c2*mult+c3*u2+diff=c4*s2+c5*mult+diff2 & k*(diff+diff2)<mult)) { |diff-diff2|<=diff+diff2<mult/k, so ...<1/k } ``` `a|b&c` is `a|(b&c)` since I think removing these parentheses makes it look better, anyway they're free. Used JavaScript `"(expr)".replace(/\{.*?\}/g,'').match(/[a-z0-9]+|[^a-z0-9\s\(\)]/g)` to count tokens. ]
[Question] [ Given a string, return whether the string is a substring of the program's source code. Standard quine rules apply, meaning you cannot read your own source code. The length of the input is guaranteed to be less than or equal to the length of the program. You may return any two distinct values, not necessarily truthy and falsey values. You may also submit a function, rather than a full program. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins! ### An example If your source code is `print(input() = False)`, it should return True for `nt(i` but False for `tupn`. [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` s="print input()in's=%r;exec s'%s";exec s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWqaAoM69EITOvoLREQzMzT73YVrXIOrUiNVmhWF21WAnK/P9fHaxQHQA "Python 2 – Try It Online") [Answer] # [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript), 25 bytes ``` f=s=>('f='+f).includes(s) ``` [Try it online!](https://tio.run/##DcnBDYAwCADAcYAYuwHu0rRgakgxoq6P3veO@tZo1zjvdXqXTOXgDUEZFqUyZrOnS2BQNp/hJsV8R0X4C4jyAw "JavaScript (Node.js) – Try It Online") I'm personally not a fan of this, but [it's allowed](https://codegolf.meta.stackexchange.com/a/13638/68615). ## Alternate (invalid?) solution, 19 bytes This takes input as a regex. ``` f=s=>s.test('f='+f) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbY1q5YryS1uERDPc1WXTtN839yfl5xfk6qXk5@ukaahj5QTl9T8z8A "JavaScript (Node.js) – Try It Online") [Answer] # Java 8, ~~124~~ 112 bytes (function) ``` p->{String s="p->{String s=%c%s%1$c;return s.format(s,34,s).contains(p);}";return s.format(s,34,s).contains(p);} ``` [Try it here.](https://tio.run/##jY9Bi8IwEIXv/RVD2UIKGlj0VvQf6MXj4mFMo0TbSchMBZH@9my624sLC14GHvNm3veueMelD5au7S2ZDplhh46eBYAjsfGMxsJ@kgAn7zuLBEYdJDq6QKibvBiLPFhQnIE9EGwgheX2OXt4U76oylRcfX6YJloZIgHrs489iuLFar3gWhtPkglY5e9j@Z4tNRNDGE5dZphR7t610GfLTPt1BKx/ixweLLbXfhAd8ko6UqSNKv8GlfVPwf8PIlLr@5w4BczusRhT@gY) --- Here is it as full program instead (to see one of the reasons why functions are allowed on PPCG, because some languages -like Java- require very verbose mandatory boilerplate code for full programs). # Java 8, ~~226~~ 214 bytes (full program) ``` interface M{static void main(String[]a){String s="interface M{static void main(String[]a){String s=%c%s%1$c;System.out.print(s.format(s,34,s).contains(a[0]));}}";System.out.print(s.format(s,34,s).contains(a[0]));}} ``` [Try it here.](https://tio.run/##ncxBCsIwEIXhq4RiIIEaFN0Vj9BVl6WLIU0llUxKZixI6dljQHCvux8e35thhWNcHM7jI2eP7NIE1ol2Iwb2VqzRjyKAR9Vx8njvB9DbJwXdqp@FtJLk@WCb7kXsgolPNkvZWJGZYgpQor5ca9LGRuRyQwr606B1s@/VXyrn/CVv) --- **Explanation:** * The `String s` contains the unformatted source code. * `%s` is used to input this String into itself with the `s.format(...)`. * `%c`, `%1$c` and the `34` are used to format the double-quotes. * `s.format(s,34,s)` puts it all together. And then `.contains(...)` is used to check if this source code contains the given input. [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` import Data.List;f s=isInfixOf s$(++)<*>show$"import Data.List;f s=isInfixOf s$(++)<*>show$" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuMQ6TaHYNrPYMy8ts8IfyFbR0NbWtNGyK87IL1dRIk31/9zEzDwFW4XMvJLUosTkEgUVBZCEgp5C2n@irQAA "Haskell – Try It Online") Obvious extension of the standard quine. Getting rid of the import would be nice, but I doubt `isInfixOf` can be computed in a shorter amount of bytes. [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` !StringFreeQ[ToString[#0], #1] & ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@18xuKQoMy/drSg1NTA6JB/Ci1Y2iNVRUDaMVVBT@B8AFClxSItWIqhUKfY/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Bash, ~~43~~, 28 bytes ``` [[ $BASH_COMMAND = *"$1"* ]] ``` [try it online](https://tio.run/##S0oszvifll@kUKyQmafg5BisoB4draACZHjEO/v7@jr6uSjYKmgpqRgqaSnExqrjl1ZQt1ZIyVcoTi1R0NVVUFIpVvqPT/n/1OSMfAUldRVDdSsFFQ0NRRV7TU0lrpT8vNT/AA) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 28 bytes ``` ?instr(B+B,;)#?instr(B+B,;)# ``` This prints 0 if the input is not a substring of the source, and X otherwise where X is the (first) index of the substring. ## Explanation ``` Latter part: #?instr(B+B,;)# Define a string literal B$ with a copy of the source First part: ? PRINT instr( , ) the index of ; the cmd line parameter A$ B+B in B$ concatenated with itself ``` `#` defines a string literal in QBIC, and assigns it to the first available string variable. That is `B$` in this program, because `A$` is already taken by `;` (read a string from cmd line). Then, everything up to the delimiter is fed into the literal; the delimiter is a backtick - which also makes it the only ASCII char not includable in string lits. In this case, QBIC doesn't need a backtick, because the literal is terminated at the end of the code by QBIC's auto-close feature. For more information on QBIC's literals, see [the Showcase thread](https://codegolf.stackexchange.com/questions/44680/showcase-of-languages/86385#86385). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` “;⁾vṾƓẇ”vṾ ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxzrR437yh7u3Hds8sNd7Y8a5oLY//@rQznqAA "Jelly – Try It Online") ### How it works ``` “;⁾vṾƓẇ”vṾ Main link. No arguments. “;⁾vṾƓẇ” Set the left argument and the return value to ';⁾vṾƓẇ'. Ṿ Uneval; yield '“;⁾vṾƓẇ”'. v Dyadic eval; eval ';⁾vṾƓẇ' with argument '“;⁾vṾƓẇ”'. ⁾vṾ Yield 'vṾ'. ; Append it to '“;⁾vṾƓẇ”', yielding the source code. Ɠ Read a string from STDIN. ẇ Check if it's a substring of the source code. ``` [Answer] # Julia, 72 bytes I now understand what people mean when they say that quine problems are just variations on the classic quine. ``` x="~y=contains\"x=\$(repr(x));\$x\",y)";~y=contains("x=$(repr(x));$x",y) ``` ## Explanation ``` #Defines x to be the next line of the source, with the help of escaping characters x="~y=contains\"x=\$(repr(x));\$x\",y)"; #Interpolates together a comparison string, including repr(x), the re-escaped from of x, and x itself, for comparison. ~y=contains("x=$(repr(x));$x",y) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 56 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7 bytes ``` `Iǎc`Iǎc ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJEPSIsIiIsImBJx45jYEnHjmMiLCIiLCJJx45jIl0=) ## Explained ``` `Iǎc`Iǎc­⁡​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­ ǎ # ‎⁡Does all substrings of `Iǎc` # ‎⁢ The string "Iǎc" I # ‎⁣ With a version surrounded in backticks prepended to itself c # ‎⁤Contain the input? 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # Perl 5, 60 + 2 (-pl) bytes ``` $_=(sprintf$a=q($_=(sprintf$a=q(%s),$a)=~/\Q$_/),$a)=~/\Q$_/ ``` [try it online](https://tio.run/##K0gtyjH9/18l3lajuKAoM68kTSXRtlADna9arKmjkqhpW6cfE6gSr4/CIaybC7dmLkpsJqhZQQG35n/5BSWZ@XnF/3ULcgA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0"D34çýIå"D34çýIå ``` Modification of the default [quine](/questions/tagged/quine "show questions tagged 'quine'") [`0"D34çý"D34çý`](https://codegolf.stackexchange.com/a/97899/52210) by adding `Iå`. [Try it online.](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7PQ8vRWL@/w/mAwA) **Explanation:** ``` 0 # Push 0 to the stack # STACK: [0] "D34çýIå" # Push the string 'D34çýIå' to the stack # STACK: [0, 'D34çýIå'] D # Duplicate this string # STACK: [0, 'D34çýIå', 'D34çýIå'] 34ç # Push '"' to the stack # STACK: [0, 'D34çýIå', 'D34çýIå', '"'] ý # Join the stack by this '"' delimiter # STACK: ['0"D34çýIå"D34çýIå'] I # Take the input # STACK: ['0"D34çýIå"D34çýIå', 'Iå"D'] å # Check if it's a substring of the source code # STACK [1] # (Output the top of the stack implicitly) ``` ]
[Question] [ The beloved fish who swims through the code of [><> (an esoteric programming language)](https://esolangs.org/wiki/Fish) has been taken out of its natural environment. This change has rendered it incapable of moving around in the way it's used to: what used to be toroidal movement has been restricted to simple left-to-right movement. But ><> programs are still written as if the fish were capable of moving through them. It is your task, dear programmer, to write a program to linearize a ><> program. And do it in as few bytes as possible; fish don't have very large memories. ## Movement in ><> In ><>, movement is toroidal and one character at a time. This means that the fish (the pointer) can "wrap" around from the end of a line back to the beginning. In ><>, the fish also is capable of moving top-to-bottom, bottom-to-top, and right-to-left, in contrast to the way most pointers move. So this movement pattern would be valid: ``` >>>^ >>>v >>>^ v ``` and it would end on an infinite loop (looping back to the top line once it gets past the bottom infinitely). The fish moves in a grid of length equal to max(row length) and height equal to the number of rows. How do you figure out which way the fish moves? These commands change the direction vector of movement (e.g. `(-1,0)` means right-to-left): ``` Command | Direction Change --------------------------- > | (1,0) (default) < | (-1,0) ^ | (0,1) v | (0,-1) / | (x,y) -> (y,x) \ | (x,y) -> (-y,-x) | | (x,y) -> (-x,y) _ | (x,y) -> (x,-y) # | (x,y) -> (-x,-y) ; | (0,0) ``` As noted, the fish starts moving left-to-right, i.e. with direction vector `(1,0)`. The fish starts parsing commands starting with the first command it sees and changes its direction if a command matches one of the aforementioned direction changers. The fish stops moving when it sees a `;` and terminates the program. ## Input Input will be a valid (e.g. not infinitely looping) program given through STDIN. You may also read a file if you wish. The lines of each program will *not* necessarily be of the same length. Input is given as a string, with newlines separating each line in the program. Programs will not loop, which also means they will always terminate with a `;`. ## Output Output will be the program linearized. That is, you should return all of the characters (including direction changers) that the fish would see if it ran the program "normally." This is all of the characters in its path to the `;`. If the input is has lines of unequal length and the fish ends up moving along a line shorter than the length of the longest line, you should treat that as if the fish were moving over a space (see test cases). Those familiar with ><> will know that direction changers are not the only way to do movement in it, but for simplicity's sake treat the input as if they are the *only* way to affect movement. ## Rules 1. Standard loopholes apply 2. You may write either a full program or function 3. Input is supplied through STDIN or a file as a string containing the program lines separated by newlines (`\n`) * You may take the input differently, within reason (feel free to ask me if you have a specific kind of input in mind). You may not pad the input with spaces so the line lengths match. * Refer to [this](https://codegolf.meta.stackexchange.com/q/11871/42833) meta post regarding flexible input. As it stands of posting, general consensus is to be as flexible as possible within reason. 4. Output is a single string through STDOUT or returned by the function (depending on what you choose to do, see Rule 2) ## Test Cases ``` v >v >abcv//; gfed<^ih v>abcv<defghi^//>v; v >v >abcv//; gfed<^ v>abcv<defg ^//>v; abcdef; abcdef; abcd|; abcd|dcba; abcd#; abcd#dcba; abcd\; _ abcd\_\dcba; ^; >abcde/ ^jihg< ^ >abcde/ <ghij^a; ; ; ``` [Answer] # [Röda](https://github.com/fergusq/roda), ~~405~~ ~~393~~ ~~392~~ ~~391~~ ~~371~~ ~~366~~ ~~361~~ ~~236~~ ~~234~~ ~~232~~ ~~230~~ ~~223~~ 200 bytes ``` F f{L=f()|[#_]|sort|tail c=""x=0 y=0 X=1 Y=0{l=f[y]l.=[" "]*(L-#l)c=l[x]a=X [c] C=indexOf(c,`><v^/\|_#`)X=[1,-1,0,0,-Y,Y,-X,X,-X,X][C]Y=[0,0,1,-1,-a,a,Y,-Y,-Y,Y][C]x+=X x=x%L y+=Y y=y%#f}until[c=";"]} ``` [Try it online!](https://tio.run/nexus/roda#dVDBjtsgFDwvX/GEtVKSxXVydshlpT1F6qUHW4RkqY0TKha3hrq24nx7Cqxi9VJj0NPMvHkD9zdornvaLJYTS058sm3nJieURhXFeKBrNPpd0A0q6fqqacNGrr9QhgHz1WKfJnpZUc0GLmiBWMXRK1WmlsPXZlGR9922P2aH6ZS8LwvKNiTdkLVfaUlKkhakiAdnr7ykLBBRkQoiAh//MrDDizcf6PC8R@MLLX2k8Tlpbr@NU5r5nDnmt/uHUAauCMBJ6yphpQUKDPcQvl2PduJ71WdZjs6NrLdHdcEE/ssGziO1bPJHOc1VMleHQ46CwSkAxzy61DJDcPyhLudtQKN2m4s4beclPebIN1n5C9YEkjltuoEJmrYDBXWLnp6y1beLBCMHB@5PC1oZf6OqNb3sPOIp6zplzhaUcW2QpLX6kMaq1ggNWpqzu3jPTxWIrhOjXWUx7mOmf6B5PFM8wweDo@Az3JwtRrtOanoAXvxPb2zFt5MP/TaD0eenn@0AB9O6NRKh2/0v "Röda – TIO Nexus") [Check outputs!](https://tio.run/nexus/roda#dZFNb6MwEIbP8a8YGVVKUijJGZxLpZwi9bKHIMcQCiZxRU0XHJYo5Ld3BydB3cPypZl3vh4P32soLhtWTGc9dxLRN1VtepOqkmSM0o4tyBnfLVuSiC0uJSv4WZQvjFOgYj7deE45y1jJO5GyLeGZIK9M6Vx2b8U0c/ersI39XZ84@9mW8aXrLd0F3l7kRq63dbf2I/iriBgfAjbDS910iNsnGqLdMzbvWPe0IednFiHS@ckpridtVMmRM6Di@v2ZKg0XAmBkY7K0kQ0w4LSF4Vq1ZJW@Z63vB@RQyDyM1ZG68N/oEEMll0XwMPvRckZrtwvI0CAZhDiwXXLpE4g/1PEQDqrNDYOUCkImWVXXMjNvJ/N1Mnc@OznESYejin1/1WLFTxVgVEeiG1CevacPx7k7e4uV7Ky7d2kMdyYIsf9HbAtuTGgiE/I38jcsXHDGxXlL6KGoalCQV2QyqSwv4lKKnj//dZSgZWfA/KmgVBpXnVW6lTUqGGpMrfShAaVNNaR4ufqUulGVTksopT6YI064ZUFa1@m5mft2jw8CHDXCcCV8utPUJtxQR1ILeulV/xAw@UetLaXXxJby9fShzwSW3Q/1wiDBQ/HxjP/@I2whiD@fTNZj1zvrF@KbYSOAS9KSkOv3Xw "Röda – TIO Nexus") ### Explanation (outdated) ``` F f{ /* Declares a function F with parameter f */ /* Takes a 2D array of single-char Strings as f */ L = /* L contains the value of the length of the longest line*/ f() /* Push the contents each element of f to the stream; this pushes each line*/ | [#_] /* Pull a line and push its length to the stream*/ |sort|tail /* Sort it and get the last value (the largest one) */ c="" /* c contains the value of the current char that is being processed */ x=0; y=0 /* x and y contain the position of the fish */ X=1; Y=0 /* X and Y contain the direction of the fish */ { ... }while [c != ";"] /* While c is not `;` do: */ l=f[y] /* l is the line (row) the fish is at */ c=" " if [x >= #l] /* If x is more than or equal to the line's length, set c to a space (so that we don't need to pad spaces to the array at the beginning)*/ else c = l[x] /* Else set c to the character a position x of l*/ [c] /* Push c to the output stream; ie prints c without a trailing newline*/ a = X /* a preserves the value of X before analysing c */ C = indexOf(c,`><v^/\|_#`) /* Simple enough */ X=[1,-1,0,0,-Y,Y,-X,X,-X,X][C]/* Map each value of C to their respective X-direction in the array */ /* If c cannot be found in `><v^/\|_#` then it will be given the value of -1, or in other words, the -1th element of an array its last element */ Y=[0,0,1,-1,-a,a,Y,-Y,-Y,Y][C]/* Do the same thing for Y */ x += X /* Change the x-pos by the X-direction */ x = x%L /* Wrap around the right edge */ y += Y /* Do the same for y */ y=y%#f /* But wrap around the bottom instead */ x+=L if[x<0] /* Wrap around the left */ y+=#f if[y<0] /* Wrap around the top */ } ``` ### Edits * 10 bytes saved thanks to @fergusq by using `%` instead of checking whether x or y is over the boundaries, which paved the way for 2 more! * Used ``\`` instead of `"\\"` * Moved `c=""` to the second line and then removed the newline following it * Moved the conversion of the lines to single-character array into the loops instead of at the beginning (inspired by the Python answer) * Used the brace syntax of `while` (thanks to @fergusq for spotting that) * Moved the `a=X` out of the if-statements * Thanks to @fergusq for finding a shorter way to find the length of the longest line * Used array syntax instead of if-statements (like the Python answer) to save tons of bytes * Removed the code that padded spaces, instead spaces are added as the ><> moves along * Fixed a bug thanks and golfed one character thanks to @fergusq * Removed the `+1` at the end of `indexOf` and restructured code to save 2 bytes * Saved 2 bytes by moving things around (thanks to @fergusq again) * Saved 1 byte thanks to @fergusq by using a different method of padding spaces * Saved 1 byte by using `until[c=";"]` instead of `while[c!=";"]` * Thanks to a hint from @fergusq, I removed the loop that pads spaces and replaced it with `l.=[" "]*L` * Saved over 20 bytes by removing the if-statements at the end that wrap the program around the left and top edges [Answer] # Python 2, ~~262~~ ~~243~~ ~~237~~ ~~235~~ ~~234~~ ~~233~~ ~~231~~ ~~221~~ ~~219~~ ~~218~~ 217 bytes Takes input as `['<line_1>', '<line_2>', ...]` ``` i=input() q=max(map(len,i)) i=[k+' '*q for k in i] x=y=k=0 j=1 o='' while';'not in o:r=[1,-1,-j,-k,0,0];o+=i[y][x];l='><#\\v^/|_'.find(o[-1]);a=(r+[k,-j,j])[l];k=([k,-k,k,j]+r)[~l];j=a;x=(x+j)%q;y=(y-k)%len(i) print o ``` [Try it Online!](https://tio.run/nexus/python2#LU7RTsMwDHzPVwRNyAlNWPtK5n1B/yBLUWHd5qRLqmlAKvHvJRR0tuXznaxbCClOH3chWYvjEBmhDRVweBLXPpeeRKtISt2KIOUp3XjgFDk5lnHGgDXz2LCEAOzrQuPAyc7OZveAYOAlVfjPzYiw33Wf28Ph@3UDzyeKR5Gsbpw0PdpG6UbVBUHpUl75dTg7OhPQ/iqrZT3/eYIKq@yxNxlFrrx8bAXZunycUcw6rFyy6UbxzlNVAi2Lhc6Agn3/9n4ctmXjnafLeQfuBw) -19 bytes thanks to @math\_junkie -6 bytes thanks to @ThisGuy -2 bytes by extracting `max(map(L,i))` to a variable (because it is theoretically used twice). -1 byte by reducing the number of times `i[y][x]` shows up. -1 byte by using `'\x00'` so I don't have to do the `[1:]` part of `o[1:]` in the output -2 bytes by using `\0` instead of `\x00` -10 bytes thanks to @KritixiLithos for realizing that I can pad as much as I want on the right side because the extra will be ignored (no byte change) fixed bug because extracted variable was outside of loop -2 bytes because now I only use `len` 2 times so reassigning it takes 2 additional bytes -2 byte by using `while';'not in o` instead of `while o[-1]!=';'`, and using `o=''` instead of `o='\0'`. This not only saves 2 bytes but also gets rid of the leading null byte which was technically not really valid. # Explanation ``` i = input() # Takes input as an array of strings q = max(map(len,i)) # Finds the width of the longest line i = [k + ' ' * q for k in i] # Makes sure everything is at least that width x = y = k = 0 # Set the point to (0, 0). Set the vertical motion to 0 j = 1 # Set the horizontal motion to 1 o = '\0' # Initialize the output to a null byte (this is output as nothing, so it doesn't actually affect output) while o[-1] != ';': # While the last character in the output is not ';' (this is why the output needs to be initialized with something, otherwise o[-1] gives an index error) r = [1,-1,-j,-k,0,0] # Some of the vertical and horizontal coordinates correspond in opposite order o += i[y][x] # Add the current character to the output l = '><#\\v^/|_'.find(o[-1]) # Find the index of the current character here (or -1 if it's just a regular character) a = (r + [k, -j, j])[l] # The fancy array contains the horizontal movement for each control character k = ([k, -k, k, j] + r)[~l] # The fancy array contains the vertical movement for each control character. Using ~l to get the right index, because r has the values backwards j = a # a was a placeholder because otherwise k would not be correct x = (x + j) % q # Adjust the pointer position y = (y - k) % len(i) # Adjust the pointer position print o # Print the output after the loop is finished ``` [Answer] ## Ruby, ~~274~~ ~~200~~ ~~187~~ 183 Shaved off just a few more characters by dropping the momentum array, `d`. I'm pretty proud of this one. This was fun! It takes in an array of strings and returns the proper string. ``` ->a{o,x,y='',-1,0 b,m=1,0 (o+=n=a[y=(y+m)%a.size][x=(x+b)%(a.map &:size).max]||' ' b,m=([1]+[0,-1,0]*2+[1,-m]+[-b,m,b]*2+[-m,-b,-m,b,m])[2*('><^v/\\|_#'.index(n)||9),2])until o[?;] o} ``` Commented below. ``` ->a{ o,x,y='',-1,0 # o is the output string, x and y are the positions in the array b,m=1,0 # b and m are the direction of momentum until o[?;] # until o contains a semicolon w=(a.map &:size).max # w is the max width of the arrays h=a.size # h is the height of arrays x=x+b % w # increment cursor position y=y+m % h o+=n=a[y][x]||' ' # add the new char (or " ") to o ix=2*('><^v/\\|_#'.index(n)||9) # find the index new char in the string b,m=([1]+[0,-1,0]*2+[1,-m]+[-b,m,b]*2+[-m,-b,-m,b,m])[ix,2] # set momentum to its new value end o # return output string } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~107~~ 106 [bytes](https://github.com/abrudz/SBCS) ``` {v←⍬⋄d←⍳2⋄v⊣⍵{v,←c←⍵⌷⍺⋄(⍴⍺)|⍵+d⊢←('^<v>/\|_#'⍳c)⊃⌽d(-d)(-@0⊢d)(-@1⊢d)(⌽d)(-⌽d),(⊢,-)(⊂,⊂∘⌽)⍳2}⍣{';'∊v}0 0} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6vLgNSj3jWPultSwKzNRkBm2aOuxY96t1aX6QDFksHiWx/1bH/UuwsoqfGodwuQpVkDFNROedS1CCivoR5nU2anH1MTr6wONCNZ81FX86OevSkauimaGroOBkBVYIYhhAGSAnLBlI4GUExHFyjY1aQDxI86ZgDFNUEuqX3Uu7ha3Vr9UUdXWa2BgkHt/zSwW/qAph9ab/yobSLQI8FBzkAyxMMz@H9uYglIvm2iepkCCNiVqSuo2yUmJZfp61sDmelpqSk2cepcaQpAHUCVQPVcurq6XHB9IPvVgepTaqyJUaWMTxVYRQzIWpBT4nGq7F2ljmoMAA "APL (Dyalog Unicode) – Try It Online") Takes a character matrix as input. The code uses the technique already used [here](https://codegolf.stackexchange.com/a/199608/78410) to select the next direction based on the current command. Direction change for `;` is not handled because we'll stop once it is reached anyway. ### How it works ``` { ⍝ Input: the ><> program as a matrix v←⍬ ⍝ List of commands walked over d←⍳2 ⍝ Initial direction (0 1); (vertical horizontal) v⊣⍵{ ⍝ Return the resulting v after running... ⍝ Extract the current command c and append to v v,←c←⍵⌷⍺ ⍝ Update the direction based on the command ⍝ (0 1) is east, (0 ¯1) west, (1 0) south, (¯1 0) north ⍝ - mirrors in each direction, ⌽ swaps the two (mirror by \) ⍝ @0 or @1 selects which element to apply the transformation ⍝ (⊢,-)(⊂,⊂∘⌽)⍳2 evaluates to (0 1)(1 0)(0 ¯1)(¯1 0), the directions for >v<^ d⊢←(⌽d(-d)(-@0⊢d)(-@1⊢d)(⌽d)(-⌽d),(⊢,-)(⊂,⊂∘⌽)⍳2)⊃⍨'^<v>/\|_#'⍳c ⍝ Add the step to the coordinates and handle wrapping (⍴⍺)|⍵+d }⍣{';'∊v}0 0 ⍝ Start at (0 0) and repeat until v contains ';' } ``` [Answer] # PHP 7, ~~291~~ 260 bytes ``` for($m=max(array_map(strlen,$z=explode(" ",$argv[1]))),$y=0,$r=count($z)-$v=1;';'!=$c;[$v,$w]=[[$v,1,-1,0,0,-$w,$w,-$v,$v,-$v][$o=strpos(' ><^v/\|_#',$c)],[$w,0,0,-1,1,-$v,$v,$w,-$w,-$w][$o]],$x+=$m+$v,$x%=$m,$y=0<=($y+=$w)?$r<$y?:$y:$r)echo$c=$z[$y][$x]??' '; ``` [Answer] # JavaScript, ~~242~~ ~~236~~ ~~235~~ ~~231~~ 220 bytes ``` a=>{n=a.length;m=x=y=p=0;a.map(g=>m=(w=g.length)<m?m:w);q=1,o="";while((t=a[y][x]||" ")!=";")o+=t,h=q,q=[q,1,0,p,-q][(s=">v\\| <^/_#".indexOf(t)+1)%5]*(r=s>5?-1:1),p=[p,0,1,h,p][s%5]*r,x=(x+q+m)%m,y=(y+p+n)%n;return o+t} ``` [Try it online!](https://tio.run/nexus/javascript-node#Vc1LboMwGATgfU5BXUWyawfCIpuYnxyhB@BRXGIwFX4AbgJqeuyu00TNprOdbzQNXGdIvwTM4eT6zlerihsQYS9N6xXXMMMCDrZchFo43EKqAZ@hfQCS6IPenwkfIGYWEOJn1fUSYw8iW4psLi4XFCDyBIgjYil4NkCmYGAx2zLHNkOR4QlQesrzS5CU0dszCjtzlPNrgz2hMVnvihc8wpTuDpt4HxPmIHO3bcwUc0U23fuRzYBnOlBN1potgBfqqCFrw0fpP0cTWOq/r7U1k@1l2NsWNxidgntuxyYV7/Upinhu2kYek7JTiJDVf16V/A8eZZSboPzoVJtUhFx/jN3UolbyFw) ]
[Question] [ [Hearts](http://en.wikipedia.org/wiki/Hearts) is a trick-taking card game for 4 players. Each trick is taken by the player who played the highest card of the leading suit. At the end of each hand, the players incur a penalty score depending on the penalty cards they have taken; the task is to determine the scores under [Microsoft Hearts](http://en.wikipedia.org/wiki/Microsoft_Hearts) rules. ## Input Input is 4 lists (or delimited string, array, etc.) showing the penalty cards taken by each of the 4 players. The penalty cards are ``` 2♥, 3♥, 4♥, 5♥, 6♥, 7♥, 8♥, 9♥, 10♥, J♥, Q♥, K♥, A♥, Q♠ ``` which we shall represent as ``` 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 0 ``` respectively. ## Output Output is the 4 penalty points incurred by the 4 players (list, string, array etc.). Scoring is as follows: * Each heart (`♥`, represented by integers `1` to `13` inclusive) incurs 1 point * The queen of spades (`Q♠`, represented by `0`) incurs 13 points * Exception: if a player has taken all of the penalty cards (called shooting the moon), then he incurs 0 points, while all other players incur 26 points. ## Test cases ``` [2, 8, 7, 1], [3, 4], [], [9, 5, 6, 0, 10, 11, 12, 13] --> 4, 2, 0, 20 [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1] --> 25, 0, 0, 1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], [], [], [] --> 0, 26, 26, 26 ``` **Shortest code in bytes wins.** [Answer] ## R, 85 77 74 bytes ``` function(x,z=sapply(x,function(x)sum(x>0)+any(x<1)*13))abs(z-any(z>25)*26) ``` Unnamed function that takes an R-list as input. Works by counting the number of elements `>0` and adds 13 if any element within each vector is `<1` (i.e. queen of spades) and store as `z`. If any element in `z` is `>25`, return `26-z`, else return `z`. [Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=gCETKMSR&version=2) [Answer] # C++14, 158 bytes As unnamed Lambda: ``` [](auto c){typename decltype(c)::value_type r;int b=0;for(auto d:c){int q=0;for(auto i:d)q+=i?1:13;r.push_back(q);b+=q==26;}if(b)for(int&x:r)x=26-x;return r;} ``` Requires a `vector<vector<int>>` and returns `vector<int>` Ungolfed: ``` [](auto c){ typename decltype(c)::value_type r; //result vector int b=0; //flag if one has all cards for(auto d:c){ //over all decks int q=0; //count points for(auto i:d) q+=i?1:13; //+13 for queen, +1 else r.push_back(q); //add to result b+=q==26; //possibly activate flag } if(b) for(int&x:r) x=26-x; //if flag is set, mirror the results return r; } ``` Few testcases for you: ``` auto r = std::vector<std::vector<int>>{{2,8,7,1},{3,4},{},{9,5,6,0,10,11,12,13}}; auto s = std::vector<std::vector<int>>{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0},{},{},{}}; auto t = std::vector<std::vector<int>>{{},{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0},{},{1}}; ``` [Answer] ## Python 2, ~~75~~ ~~72~~ 71 bytes ``` i=[len(a)+12*(0in a)for a in input()] print[[x,26-x][26in i]for x in i] ``` Takes input as `[2, 8, 7, 1], [3, 4], [], [9, 5, 6, 0, 10, 11, 12, 13]` [Answer] ## CJam, ~~22~~ 20 bytes *Thanks to jimmy23013 for saving 2 bytes.* ``` {{XD?}f%1fb_26&1bf^} ``` An unnamed block (function), which takes a list of 4 lists as input and returns the list of scores. [Try it online!](http://cjam.tryitonline.net/#code=cU4ve34KCnt7WEQ_fWYlMWZiXzI2JjFiZl59Cgp-cH0v&input=W1syIDggNyAxXSBbMyA0XSBbXSBbOSA1IDYgMCAxMCAxMSAxMiAxM11dCltbMCAyIDMgNCA1IDYgNyA4IDkgMTAgMTEgMTIgMTNdIFtdIFtdIFsxXV0KW1sxIDIgMyA0IDUgNiA3IDggOSAxMCAxMSAxMiAxMyAwXSBbXSBbXSBbXV0) ### Explanation ``` { e# For each card... XD? e# Choose 1 if it's positive and 13 if it's zero. }f% 1fb e# Sum each hand. _26& e# Get the set intersection of the scores with 26. This gives [26] e# if someone shot the moon, and [] otherwise. 1b e# Treat as base-1 digits, which gives 26 if someone shot the moon e# and zero otherwise. f^ e# XOR each result with this number. This swaps zeros and 26s when e# someone shot the moon and does nothing otherwise. ``` [Answer] # PHP, 113 bytes ``` function h($a){foreach($a as&$b)$b=count($b)+12*in_array(0,$b);if(max($a)>25)foreach($a as&$n)$n=26-$n;return$a;} ``` function takes an array of arrays, returns an array of values. --- Marvel the other array mapping in PHP: loops with referenced items. Waaay shorter than `array_map`. [Answer] # Haskell, ~~62~~ ~~59~~ 56 bytes ``` f x|all(<26)x=x|0<1=map(26-)x f.map(sum.map((13^).(0^))) ``` Usage: ``` > f.map(sum.map((13^).(0^))) $ [[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1]] [25,0,0,1] ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~26~~ ~~22~~ 21 bytes Trailing whitespace must be removed from input so that it is interpreted as an array. The ending was inspired of the other answers when using (26-x) when a player gathered all penalty cards. ``` vy0å12*yg+})D26©åi(®+ v For each array y Push array on the stack 0å Generate a boolean array indicating whether the queen of spades is at the same index in the original array 12* Multiply by 12 the value of the queen of spades yg+ Add the length of the array; the queen of spades gets her last point from this part } End for ) Push an array of all evaluated scores D26©å 1 if there is a 26, 0 otherwise i If there is a 26 (®+ Mirror the array: for each element yield 26-element Implicit end if Implicitly print the score array ``` [Try it online!](http://05ab1e.tryitonline.net/#code=dnkww6UxMip5Zyt9KUQyNsKpw6VpKMKuKw&input=WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTIsIDEzLCAwXSwgW10sIFtdLCBbXQ) It still looks pretty golfable, with duplicated constants and conditional statements. # Former version, 26 bytes (One byte for each point in maximal penalty value) I decided to keep it as its length fits best this challenge in my opinion :) . ``` vyD0å12*sg+})D26©QDOi_®*ë\ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=dnlEMMOlMTIqc2crfSlEMjbCqVFET2lfwq4qw6tc&input=WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTIsIDEzLCAwXSwgW10sIFtdLCBbXQ) [Answer] # Python 3, 101 bytes ``` def s(a):r=[sum([(1,13)[c==0]for c in h])for h in a];s=(r,[(26,0)[s==26]for s in r]);return s[26in r] ``` Full code: ``` def score(hands): result = [sum([(1, 13)[card == 0] for card in hand]) for hand in hands] results = (result, [(26, 0)[score == 26] for score in result]) return results[26 in result] ``` [Answer] ## JavaScript (ES6), ~~82~~ ~~80~~ ~~77~~ ~~72~~ ~~70~~ ~~69~~ 67 bytes *Saved 2 bytes thanks to @Neil* ``` f = s=>s.map(c=>c.map(t=>r+=t?1:13,r=0)|(b|=r>25,r),b=0).map(c=>b*26^c) console.log(f.toString().length) console.log(f([[2, 8, 7, 1], [3, 4], [], [9, 5, 6, 0, 10, 11, 12, 13]])); console.log(f([[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [], [1] ])); console.log(f([[0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [], [1], [] ])); console.log(f([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], [], [], []])); console.log(f([[],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0], [], []])); ``` ### Breakdown ``` s=>s.map( // for each hand c=>c.map( // for each card t=>r+=t?1:13, // add value of card r=0)|( b=b|r>25,r // set flag if any hand scores 26 points ), b=0) .map(c=>b? // for every card if a hand scored 26 c?0:26 // set every 0 hand to 26 and the 26 hand to 0 :c) // otherwise do nothing ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), 28 bytes 27 bytes of code, +1 for `-p` flag. ``` Y{$+1+12*!*a}M Va26Ny?26-yy ``` Takes input on the command-line as a string representing a nested list, like `"[[2 8 7 1] [3 4] [] [9 5 6 0 10 11 12 13]]"` (quotes not needed on TIO). [Try it online!](http://pip.tryitonline.net/#code=WXskKzErMTIqISphfU0gVmEyNk55PzI2LXl5&input=&args=LXA+W1tdIFsyIDggNyAxIDMgNCA1IDYgMCAxMCAxMSAxMiAxM10gW10gWzldXQ) [Answer] # Ruby, 59 bytes ``` ->a{a.map{|h|a.max.size>13?h.min||26:h.size+12*h.count(0)}} ``` Or, alternatively, ``` ->a{a.map{|h|a.count([])>2?h.min||26:h.size+12*h.count(0)}} ``` If only one hand has any cards, we want the empty hands to get a value of 26, and the hand with cards to get a value of 0. I do this by calling `min` on the hands - this returns `nil` for an empty array, and then I `||` it into 26. In other cases, I count the number of cards in a hand and then add 12 to the Queen of Spades. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` ƛ0c12*nL+;:26c[26꘍ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGmzBjMTIqbkwrOzoyNmNbMjbqmI0iLCIiLCJbW10sIFsxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMCwgMTEsIDEyLCAxMywgMF0sIFtdLCBbXV0iXQ==) or [run all the test cases](https://vyxal.pythonanywhere.com/#WyJQaiIsIjrGmyIsIsabMGMxMipuTCs7OjI2Y1syNuqYjSIsIl07WsabYCA9PiBgaiIsIltbWzIsIDgsIDcsIDFdLCBbMywgNF0sIFtdLCBbOSwgNSwgNiwgMCwgMTAsIDExLCAxMiwgMTNdXSwgW1swLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMCwgMTEsIDEyLCAxM10sIFtdLCBbXSwgWzFdXSwgW1swLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMCwgMTEsIDEyLCAxM10sIFtdLCBbMV0sIFtdXSwgW1sxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMCwgMTEsIDEyLCAxMywgMF0sIFtdLCBbXSwgW11dLCBbW10sWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTIsIDEzLCAwXSwgW10sIFtdXV0iXQ==). ## How? ``` ƛ0c12*nL+;:26c[26꘍ ƛ # For each inner list in the (implicit) input: 0c # Does it contain a zero (the queen of spades)? 12* # Multiply this by 12 (aka if it contains a zero, then 12, otherwise 0) nL+ # Add the length of the inner list to this ; # Close map lambda : # Duplicate 26c # Does it contain 26? (aka someone shot the moon) [26꘍ # Then bitwise XOR each with 26 (swapping 26 and 0) ``` [Answer] # Scala, 93 bytes ``` a=>{val% =a.map(_.map{case 0=>13;case _=>1}sum) if(%toSet 26)%map{case 0=>26;case _=>0}else%} ``` Usage: ``` val f:(Seq[Seq[Int]]=>Seq[Int])=... f(Seq(Seq(2, 8, 7, 1), Seq(3, 4), Seq(), Seq(9, 5, 6, 0, 10, 11, 12, 13))) ``` Explanation: ``` a=>{ //define an anonymou function with a parameter a val% = //define % as... a.map( //map each element of a... _.map{ //to each of the card case 0=>13 //replaced with its value case _=>1 } sum //and the sum of the values ) if( //if %toSet 26 //one player has all cards ) %map{ //return % with... case 0=>26 //each 0 replaced with 26 case _=>0 //and everything else (aka the 26) replaced 0 } else //else % //return % } ``` I could use `%toSet 26` instead of `% contains 26` because `Set`'s `apply` method is `contains` and not get-at-index like `Seq`'s ]
[Question] [ ## Task * Print 0 if an `n*m` maze cannot be solved * Print 1 if an `n*m` maze can be solved (in 1 or more ways) (so I'm not asking for paths but if it's possible to solve!!!) ## Example Input array(2d): ``` [[0,0,0,0,0,0,1],[0,0,0,0,0,1,0],[0,0,0,0,1,0,0],[1,0,0,0,0,0,0]] XXXXXXXXX XS XX X X X X X X XX FX XXXXXXXXX 0 = can pass through 1 = can not pass trough [0][n] is the last block of the first line [m][0] is the first block of the last line ``` **Rule** The start position is 0,0 and the end position is n,m You can only move horizontally and vertically Shortest code wins [Answer] # Dyalog APL, 27 characters [`⊃⌽∨.∧⍨⍣≡1≥+/¨|∘.-⍨,(~×⍳∘⍴)⎕`](http://tryapl.org/?a=%u2283%u233D%u2228.%u2227%u2368%u2363%u22611%u2265+/%A8%7C%u2218.-%u2368%2C%28%7E%D7%u2373%u2218%u2374%29%20%204%207%u23740%200%200%200%200%200%201%20%200%200%200%200%200%201%200%20%200%200%200%200%201%200%200%20%201%200%200%200%200%200%200&run) `⎕` evaluated input. APL distinguishes between a matrix and a vector of vectors. This program assumes that the input is a matrix. `(~×⍳∘⍴)A` is a fork equivalent to `(~A) × ⍳⍴A`. It's needed to avoid mentioning `⎕` twice or introducing a variable. `⍴A` is the shape of `A`. For a 4-by-7 matrix the shape is `4 7`. `⍳` is the index generator. `⍳4` is `1 2 3 4`. `⍳4 7` is the vectors `(1 1)(1 2)...(4 7)` arranged in a 4-by-7 matrix. `~A` flips the bits of `A`. `×` by multiplying `⍳⍴A` by the flipped bits, we preserve the coordinates of all free cells and turn all walls into `0 0`. `,` ravels the matrix of coordinate pairs, i.e. linearizes it into a vector. In this case the vector will consist of pairs. `∘.-⍨A` or `A∘.-A` subtracts elements of `A` pairwise. Note that here the elements of `A` are themselves pairs. `|` absolute value `+/¨` sum each pair of absolute values. This gives us the grid distances between every pair of cells in the maze, save for walls. `1≥` we are only intrested in neighbours at a distance no more than 1, this also excludes walls. Now we have a graph's adjacency matrix. `∨.∧⍨⍣≡` Floyd--Warshall's transitive closure algorithm `(f⍣n)A` (not used here) where `n` is an integer is the power operator. It applies `f` to `A` `n` times: `f f ... f A`. `(f⍣g)A` where `g` is a function, is the fixed point operator, a.k.a. "power limit". It keeps on computing the series `A`, `f A`, `f f A`, ... until `((f⍣i)A) g ((f⍣(i+1))A)` returns true for some `i`. In this case we use match (`≡`) as `g`. `∨.∧⍨A` or `A∨.∧A` is a step in Floyd's algorithm. `f.g` is a generalisation of matrix multiplication (`+.×`), here we use conjunction (`∧`) and disjunction (`∨`) in place of `+` and `×`. `⊃⌽` After `⍣≡` has applied the step enough times and reached a stable state, we must look up the top-right corner of the matrix to get the result, so we flip it (`⌽`) and take the first, top-left item (`⊃`). [Visualization of `⍣≡`'s steps](http://tryapl.org/?a=a%u21904%207%u23740%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%200%201%200%200%200%200%200%200%20%u22C4%20%7B%27.%23%27%5B1+%28%u2374a%29%u2374%u2228.%u2227%u2368%u2363%u2375%u22A21%u2265+/%A8%7C%u2218.-%u2368%2C%28%7E%D7%u2373%u2218%u2374%29a%5D%7D%A8%AF1+%u23736&run) [Answer] # CJam, 42 41 39 36 35 bytes ``` Wq3>~_s,{{[{_2$+0<{e<_}*}*]}%z}*sW= ``` Based on the ideas in [this answer](https://codegolf.stackexchange.com/a/40204/25180). 4 bytes thanks to Optimizer. Input format: ``` [[0 0 0 0 0 0 1] [0 0 0 0 0 1 0] [0 0 0 0 1 0 0] [1 0 0 0 0 0 0]] ``` [Answer] # Python, 164 bytes ``` def s(a): d=[(0,0)] while d:i,j=d.pop();a[i][j]=2;d+=[(x,y)for x,y in[(i-1,j),(i,j-1),(i+1,j),(i,j+1)]if len(a[0])>y>-1<x<len(a)and a[x][y]<1] return a[-1][-1]>1 ``` I was reluctant to post this because it's practically how I'd normally do flood fill, just lightly golfed. But here it is anyway. [Answer] ## Perl, 73 bytes 69 bytes of code + 4 bytes for `-n0E` (not sure how the tags where counted in 2014, so I counted them for 4 instead of 2, but it doesn't matter a lot). ``` /.*/;s/(^0|A)(.{@{+}})?0/A$2A/s||s/0(.{@{+}})?A/A$1A/s?redo:say/A$/+0 ``` [Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdPMMuEqLUxXSUhNLSotSFdSLEyvVrf/r62npWxfra8QZ1DhqauhVO1Rr19Zq2hvoO6oYOeoX19QU6xsghB2BwoZAYfui1JR8K6AJQL6@tsH//wZgYMgFoQy4DIHAwBDKNzAAAA "Perl 5 – Try It Online") (and if you replace the `1111011` line with `1111111`, the maze isn't solvable anymore, and the output will be `0` instead of `1` : [Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdPMMuEqLUxXSUhNLSotSFdSLEyvVrf/r62npWxfra8QZ1DhqauhVO1Rr19Zq2hvoO6oYOeoX19QU6xsghB2BwoZAYfui1JR8K6AJQL6@tsH//wZgYMgFoQy4DCEAwjcwAAA "Perl 5 – Try It Online")) **Explanations:** This code will find every reachable cell of the maze (and mark them with a `A`): if a cell touches a cell marked with a `A`, the it's reachable and we mark it with a `A` too; and we do that again (`redo`). That's done thanks to two regex: `s/(^0|A)(.{@{+}})?0/A$2A/s` checks if a space is on the right or the bottom of a `A`, while `s/0(.{@{+}})?A/A$1A/s` checks if a space is on the left or on top of a `A`. At the end, if the last cell contains a `A` it's reachable, otherwise it's not (that's what `say/A$/+0` checks; the `+0` is here to make sure the result will be `0` or `1` instead of *empty string* and `1`). Note that `/.*/` will match an entire line, thus setting `@+` to the index of the end of the first line, which happens to be the size of a line, which allow use to use `.{@{+}}` to match exactly as many character as there are on a line. (`@{+}` is equivalent to `@+`, but only the former can be used in regex) [Answer] # Ruby, ~~133~~ ~~130~~ 129 characters ``` a=eval gets f=->x,y{a[x][y]=1 [[-1,0],[1,0],[0,-1],[0,1]].map{|o|d,e=x+o[0],y+o[1] f[d,e]if a[d]&&a[d][e]==0}} f[0,0] p a[-1][-1] ``` Input on STDIN, outputs `1` or `0` on STDOUT. Annoyingly long. It simply does a flood-fill of `1`s from `(0, 0)`, and then checks to see whether the "end" square is a `1`. [Answer] ### Java, 418 bytes ``` import java.util.Scanner;public class Solvable{static int w,h;public static void main(String[] a){String[]i=new Scanner(System.in).nextLine().split(";");h=i.length+2;w=i[0].length()+2;int[]m=new int[w * h];for(int x=1;x<w-1;x++)for(int y=1;y<h-1;y++)m[y*w+x]=i[y-1].charAt(x-1)<'.'?0:1;f(m,w+1);System.out.println(m[w*h-w-2]>0?0:1);}static void f(int[]m,int i){if(m[i]>0){m[i]--;f(m,i-1);f(m,i+1);f(m,i-w);f(m,i+w);}}} ``` My first code golf. I don't know why I chose Java - it's so bad for golfing xD Example maze would be inputted via stdin like this: ``` ......#;.....#.;....#..;#...... ``` [Answer] ## Python 184 ~~188~~ ``` def f(a,x=0,y=0,h=[]):s=h+[[x,y]];X,Y=len(a[0]),len(a);return([x,y]in h)==(x>=X)==(y>=Y)==(x<0)==(y<0)==a[y][x]<(x==X-1and y==Y-1or f(a,x-1,y,s)|f(a,x+1,y,s)|f(a,x,y-1,s)|f(a,x,y+1,s)) ``` This got much longer than I thought it would be :( Anyway, I'll add an explanation once I can't golf it any longer. [Answer] ## J, 75 chars Powering of the adjacency matrix (very time and memory inefficient). *(Is it called powering in English?)* ``` ({.@{:@(+./ .*.^:_~)@(+:/~@,*2>(>@[+/@:|@:->@])"0/~@,@(i.@#<@,"0/i.@#@|:))) ``` Some test cases: ``` m1=. 0 0 0 0 0 0 1,. 0 0 0 0 0 1 0,. 0 0 0 0 1 0 0,. 1 0 0 0 0 0 0 m2=. 0 1 1 ,. 0 0 0 m3=. 0 1 0 ,. 1 1 0 m4=. 0 1 1 0 ,. 0 0 1 0 ({.@{:@(+./ .*.^:_~)@(+:/~@,*2>(>@[+/@:|@:->@])"0/~@,@(i.@#<@,"0/i.@#@|:))) every m1;m2;m3;m4 1 1 0 0 ``` [Answer] # [Python 3](https://docs.python.org/3/), 136 bytes ``` def f(g,x=0,*p):w=len(g[0])+1;l=w*len(g);return~x%w*(-1<x<l)*~-(x in p)and any(g[x//w][x%w]and f(g,x+a,*p,x)for a in(1,-1,w,-w))or-~x==l ``` [Try it online!](https://tio.run/##tY/NCoMwEITvPkUuhawmmNBba55Ecgj4U0GiBEvixVe3qUX7k4K9NHPa4cvsbD8Ol04f57koK1ThmjjBSNzDyYq21LjOmYSEn1th42WGsymHq9GTO9gYU565rIV4otihRqMelC6Q0qP/6NLUytxj8u4t0Yny0cRB1RmkPI85oZxYQi1AZ@jkhGjn3jR6wBXOc064JBFa3zJLgCh6Rdg@8p7CQoT9sugTYXtd2NeUTUHx1Q/LrH54yVP/XvXQtmq@AQ "Python 3 – Try It Online") Uses `0` for wall, `1` for free space. Port of my answer to [Find the shortest route on an ASCII road](https://codegolf.stackexchange.com/a/195042/87681). [Answer] # [Python 3](https://docs.python.org/3/), 184 bytes ``` f=lambda m,x=0,y=0,n=0:n<len(m)*len(m[0])and m[x][y]<1and((x,y)==(len(m)-1,len(m[0])-1)or any(0<=i<len(m)and 0<=j<len(m[0])and f(m,i,j,n+1)for i,j in[(x-1,y),(x,y-1),(x+1,y),(x,y+1)])) ``` [Try it online!](https://tio.run/##jZBBCsIwEEX3niLLiY6QwZ00JwlZVLRYMaOULpLT16m1NbYKUtLJhzfvQ@6pPd9413WVvZbhcCxVwGgNJjlszZ6L64kh6PVzOON1yUcVXPQu@YIkAERM2loYwC3hhG5J3xpVcgJT2Ppl6vclXooPYwUBa7wgb0hXsiR3VbODKL6kse8Qm8zNlIX0Wnf3puYWKnDO4Psjj1kmNFmm/i@ZMt54ca1mrnFnmktm6KG3b8HQzEMLhv7smjP0rSvvmbp/3ce36d/xAQ "Python 3 – Try It Online") ]
[Question] [ Your task is to find how many distinct Blackjack sequences can be found in an ordered list of 12 cards. A Blackjack sequence is defined as a sequence of consecutive cards whose sum of points is exactly 21. Points are counted according to the following table: ``` Symbol | Name | Points Symbol | Name | Points -------+-------+-------- -------+-------+-------- 2 | Two | 2 9 | Nine | 9 3 | Three | 3 T | Ten | 10 4 | Four | 4 J | Jack | 10 5 | Five | 5 Q | Queen | 10 6 | Six | 6 K | King | 10 7 | Seven | 7 A | Ace | 1 or 11 8 | Eight | 8 ``` ### Input A 12-character string, using the symbols described above. We do not care about the colors of the cards, so they are not provided. *Example:* `K6K6JA3Q4389` ### Output The number of distinct Blackjack sequences that can be found in the input string. *Example:* `K6K6JA3Q4389` includes two distinct Blackjack sequences: [![example](https://i.stack.imgur.com/ipA5L.png)](https://i.stack.imgur.com/ipA5L.png) * `JA`, with the Ace being counted as 11 points (10 + 11 = 21) * `A3Q43`, with the Ace being counted as 1 point (1 + 3 + 10 + 4 + 3 = 21) So the answer would be `2`. ### Rules * Two Blackjack sequences are considered distinct if they contain different cards or the same cards in different orders. If the exact same sequence appears at different positions in the input list, it must be counted only once. * The Blackjack sequences may overlap each other. * Each kind of card may appear up to 12 times in the sequence. (We assume that the cards are picked from at least 3 different decks.) * If no Blackjack sequence can be found in the input string, you must return `0` or any other falsy value. * This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden. ### Test cases The sequences are provided for information purposes, but you're only required to output the number of them. ``` Input | Output | Distinct sequences -------------+--------+-------------------------------------------------------- 3282486Q3362 | 0 | (none) 58A24JJ6TK67 | 1 | 8A2 Q745Q745Q745 | 1 | Q74 AAAAAAAAAAAA | 1 | AAAAAAAAAAA T5AQ26T39QK6 | 2 | AQ, 26T3 JQ4A4427464K | 3 | A442, 44274, 7464 Q74Q74Q74Q74 | 3 | Q74, 74Q, 4Q7 37AQKA3A4758 | 7 | 37A, 37AQ, AQ, AQK, QKA, KA, A3A475 TAQA2JA7AJQA | 10 | TA, TAQ, AQ, QA, A2JA7, 2JA7A, JA, AJ, AJQ, JQA TAJAQAKAT777 | 13 | TA, TAJ, AJ, JA, JAQ, AQ, QA, QAK, AK, KA, KAT, AT, 777 ``` [Answer] # Python 2, 215 bytes ``` def b(s,a=[],r=range): S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s) for i in r(12): for j in r(13): if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]and s[i:j]not in a:a+=s[i:j], return len(a) ``` Comments added: ``` def b(s,a=[],r=range): # Define the function b and a list, a, which holds all the blackjack sequences S=map(lambda x:":">x>"1"and int(x)or 10-(x=="A")*9,s) # Set S to the score of each card in b for i in r(12): # Loop with i from 0 to 11 for j in r(13): # Loop with j from 0 to 12 if 21in[x*10+sum(S[i:j])for x in r(S[i:j].count(1)+1)]\ # If 21 is included in all the possible sums that the scores between i and j in S can be and s[i:j]not in a: # And that sequence is not already included, a+=s[i:j], # Append that sequence to a return len(a) # Return the amount of elements in a ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1e×5,⁵Ḥ‘ O_48«26%⁴µSeÇ ẆÇÐfQL ``` **[Try It Online!](https://tio.run/nexus/jelly#AT8AwP//MWXDlzUs4oG14bik4oCYCk9fNDjCqzI2JeKBtMK1U2XDhwrhuobDh8OQZlFM////J1RBUUEySkE3QUpRQSc)** or check out the **[test suite](https://tio.run/nexus/jelly#TcyxCsIwEAbgve8hWbqYXHJxvDUR5LCLiDjV51AHu7rpA7jpaEHEqcEHaV8kporicf/wHfwXh2U46Lzb1O3t1K2P2WQJtjlLM@g216aelqHK2vsuVGG/4nF8PkLVbS@zPjHOhZJWgjWslJEiF9qSBOdM4Q0mMoL@JpH@JrHQxNIUasTeJDoGApAIBvyn@9tEhcSeFAFq23eJSTpCcvx@RS4dPBWIKBYv)** ### How? Note that, if we always value an ace as **1** then the only valid sums are **21** and **11**, the latter being acceptable iff an ace appears in the sequence. ``` ẆÇÐfQL - Main link: string Ẇ - all non-empty contiguous sublists Ðf - filter keep if... Ç - last link (2) as a monad ...is truthy Q - unique results L - length O_48«26%⁴µSeÇ - Link 2, isBlackjackSubtring: char array e.g. ['A','2','8','Q'] O - cast to ordinal values [ 65, 50, 56, 81] _48 - subtract 48 [ 17, 2, 8, 33] 26 - 26 « - minimum (vectorises) [ 17, 2, 8, 26] ⁴ - 16 % - modulo [ 1, 2, 8, 10] µ - monadic chain separation (call the result v) S - sum(v) 21 Ç - last link (1) as a monad link_1(v) [11,21] e - exists in? 1 1e×5,⁵Ḥ‘ - Link 1 validSums: value list (where A is 1, and {T,J,Q,K} are 10) 1e - 1 exists in? (are there any aces? Yields 1 or 0) ×5 - multiply by 5 (5 or 0) ⁵ - 10 , - pair ([5,10] or [0,10]) Ḥ - double ([10,20] or [0,20]) ‘ - increment ([11,21] or [1,21]) - ^ - note: if no ace is in the sequence it's sum can't be 1 anyway ``` [Answer] # [Python](https://docs.python.org), ~~134~~ 130 bytes ``` lambda x:len({x[i:j]for i in range(12)for j in range(13)if sum(min(26,ord(c)-48)%16for c in x[i:j])in([11,21][~('A'in x[i:j]):])}) ``` **[Try it online!](https://tio.run/nexus/python2#TY8/a8MwEMXn5lNoCZLAGSzJkmrIcKs8Cbw5HtzELgqxUmwXAqX96q7P6Z8IieP39N5x1@0P86XpX04NueWXNrKPWxXyc91dBxJIiGRo4mvLUsFROT8okoeOjO8960NkQifX4cSOfKcs36YazUc037vxxVKlaSLSuvpiFOj/T17zTz5P7TiNZE8qKoUVymovpRY0ITSzIJRzuiy0QfZGZb8PGR4OcpmBF7qUz77QyM4rUEoYpVXxk/@7yNKAL0CCMpld8@BBODDg/L0fuEUpoDTG0HqDi@GwuNs6dL55ehtCnFZKSMew8iV4iHT@Bg)** ### How? An unnamed function, taking the string of length 12 as `x`. `x[i:j]` is a slice of the string from the i+1th to the jth character. Slices are taken such that we have all sublists by traversing from `i=0` to `i=11` with `for i in range(12)`, for each of which we traverse from `j=0` to `j=12` with `for j in range(13)`. (We only need `j=i+1` and up, but slices with `j<=i` are just empty strings, so we can golf off 4 bytes from `for j in range(i+1,13)`) These are filtered for those with the correct sum... Valid sums are 11 and 21 if there is an ace in a slice, or just 21 if not. `'A'in x[i:j]` gives us this information and `~(v)` performs `-1-v`, which we use to slice `[11,21]` - thus if an ace is in the sequence we get `[11,21][-2:]` and if not we get `[11,21][-1:]`, resulting in `[11,21]` and `[21]` respectively. The sum itself needs to treat `A` as 1, digits as their values, and `T`, `J`, `Q`, and `K` as 10. This mapping is achieved by first casting to ordinals: `" 2 3 4 5 6 7 8 9 T J Q K A"` (without the spaces) becomes `[50, 51, 52, 53, 54, 55, 56, 57, 84, 74, 81, 75, 65]`, subtracting 48 to get `[ 2, 3, 4, 5, 6, 7, 8, 9, 36, 26, 33, 27, 17]`, taking the `min` with 26 yields `[ 2, 3, 4, 5, 6, 7, 8, 9, 26, 26, 26, 26, 17]`, and mod (`%`) sixteen those are `[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 1]`, as required for the sum, `sum(...)`. The filtered results are place into a set with `{...}`, so only the unique results remain and the length, `len(...)` is the count [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ ~~38~~ 37 bytes ``` 'A1:vTy‚ydè})ŒvyO¸y1åiDT+ì}21å})¹ŒÏÙg ``` [Try it online!](https://tio.run/nexus/05ab1e#@6/uaGhVFlL5qGFWZcrhFbWaRyeVVfof2lFpeHhppkuI9uE1tUZAZq3moZ1HJx3uPzwz/f9/Y3PHQG9HY0cTc1MLAA) **Explanation** ``` 'A1: # replace A with 1 in input v } # for each card Ty‚ # pair 10 and the card yd # check if the card is a digit è # use this to index into the pair, giving 10 for JQK ) # wrap in list # we now have a list of cards as numbers in range [1 ... 10] Œv } # for each sublist yO¸ # create a list with the sum of the sublist y1åi } # if the sublist contain 1 DT+ì # add sum+10 to the list 21å # check if 21 is in that list ) # wrap in list # we now have a list with 1 where the sublist sums to 21 and # 0 otherwise ¹Œ # get sublists of the input Ï # keep only those which sum to 21 Ù # remove duplicates g # count the number of lists ``` [Answer] ## JavaScript (ES6), 123 bytes ``` f= t=>eval("for(s=new Set,i=0;t[i];i++)for(a=0,b=21,j=i;c=t[j++];b&&b-a*10||s.add(t.slice(i,j)))b-=+c||(c>'A'?10:a=1);s.size") ``` ``` <input oninput=o.textContent=/[^2-9TJQKA]/.test(this.value)?'':f(this.value)><pre id=o> ``` [Answer] ## JavaScript (ES6), ~~144~~ ~~138~~ ~~129~~ ~~128~~ ~~126~~ 124 bytes ``` g=([c,...s],a=[],q=new Set)=>c?g(s,[...a,[,21]].map(([x,y,A])=>[x+=c,y-=+c||(c<'B'?A=1:10),A,y&&y^10*A||q.add(x)]),q):q.size ``` Old attempt at 128: ``` s=>(q=new Set,f=s=>s?f(s.slice(1))&f(s.slice(0,-1))&[...s].map(c=>t+=-c||~(c<'B'?A=0:9),t=A=21)|t&&t-10*!A?q:q.add(s):q)(s).size ``` [Answer] ## JavaScript (ES6), 112 bytes ``` f=(s,x=[k=0])=>s?f(s.slice(1),x,[...s].map(c=>x[t+=+c||10^(c<'B'?a=11:0),b+=c]||t-21&&t-a?0:x[b]=++k,a=b=t=0)):k ``` This code logic is quite similar to the one used in existing JS answers from [ETHproductions](https://codegolf.stackexchange.com/a/110148/58563) and [Neil](https://codegolf.stackexchange.com/a/110159/58563). But it's using a basic array to keep track of the encountered Blackjack sequences rather than a `Set`. ### Formatted and commented ``` f = ( // given: s, // - s = list of cards x = [k = 0] // - x = array of Blackjack sequences ) => // - k = number of distinct Blackjack sequences s ? // if s is not empty: f( // do a recursive call: s.slice(1), // starting at the next card in the list x, // without re-initializing x[] [...s].map( // for each card 'c' in the list: c => x[ // t+ = // update the total number of points: +c || // using the number of the card (for 2 ... 9) 10 ^ ( // or using 10 for all other cards c < 'B' ? // except the Ace which is a = 11 // counted as 1 point and sets 'a' to 11 : // (which means that a total number of points 0 // of 11 will be considered valid from now on) ), // b += c // update the current sequence 'b' ] || // if x[b] was previously stored as a Blackjack sequence t - 21 && // or the total number of points is not equal to 21 t - a ? // and not equal to 'a': 0 // do nothing : // else: x[b] = ++k, // store the current sequence in x[] and increment k a = b = t = 0 // initialization of all variables used in map() ) // ) // : // else: k // return k ``` ### Test cases ``` f=(s,x=[k=0])=>s?f(s.slice(1),x,[...s].map(c=>x[t+=+c||10^(c<'B'?a=11:0),b+=c]||t-21&&t-a?0:x[b]=++k,a=b=t=0)):k console.log(f('3282486Q3362')) // 0 console.log(f('58A24JJ6TK67')) // 1 console.log(f('Q745Q745Q745')) // 1 console.log(f('AAAAAAAAAAAA')) // 1 console.log(f('T5AQ26T39QK6')) // 2 console.log(f('JQ4A4427464K')) // 3 console.log(f('Q74Q74Q74Q74')) // 3 console.log(f('37AQKA3A4758')) // 7 console.log(f('TAQA2JA7AJQA')) // 10 console.log(f('TAJAQAKAT777')) // 13 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~40 39 38 37~~ 36 bytes -4 Thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) ``` Ç<çJŒÙ'@0:[Ž„èµJuS9:S>D1å2‚T*>sOå½]¾ ``` [Try it online!](https://tio.run/nexus/05ab1e#AUIAvf//w4c8w6dKxZLDmSdAMDpbxb3igJ7DqMK1SnVTOTpTPkQxw6Uy4oCaVCo@c0/DpcK9XcK@//9UQUpBUUFLQVQ3Nzc "05AB1E – TIO Nexus") ``` Ç<ç # decrement characters by 1 JŒÙ # get all unique substrings '@0: # replace @ (was A) with 0 [Ž ] # for everything on the stack „èµJuS9: # replace what was T,J,Q,K with 9 S>D # increment all values 1å2‚T*> # push [11,21] if there was an A, [1,21] otherwise sO # sum the values of the cards å½ # increment the counter_variable if the sum # is in the array ¾ # end loop and push (print) the counter_variable ``` We need to do the decrement -> substring -> increment thing so that face cards are represented by a single digit number. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~145~~ ~~142~~ 141 bytes ``` for n in {9..155} { echo ${1:n%12:n/12};}|sort -u|sed 's/\(.\)/+\1/g;s/A/{1,11}/g;s/[J-T]/10/g;s/^/eval echo $[0/;s/$/]/'|sh|grep -c '\<21\>' ``` [Try it online!](https://tio.run/nexus/bash#LcxBC4IwGIDhe7/iOxgrSj8/TSyNYNc6Bd2cQdjSIGa46rLtt6@Qjs97eP2tH0DBXYHZRBFlmZsYkE3XQ2CoUFNKCoWUuNJZ3Q8vCN9WyyswjWIWiTkuBGFbauRoaEnkRlT78FQjxSPOKD@Xx/9ZxfhLAdbIrO5sO8gnhA0wsU1I7Jj3Ps358cBTvsqz9Rc "Bash – TIO Nexus") Test runs: ``` for x in 3282486Q3362 58A24JJ6TK67 Q745Q745Q745 AAAAAAAAAAAA T5AQ26T39QK6 JQ4A4427464K Q74Q74Q74Q74 37AQKA3A4758 TAQA2JA7AJQA TAJAQAKAT777 do echo -n "$x " ./21 "$x" done 3282486Q3362 0 58A24JJ6TK67 1 Q745Q745Q745 1 AAAAAAAAAAAA 1 T5AQ26T39QK6 2 JQ4A4427464K 3 Q74Q74Q74Q74 3 37AQKA3A4758 7 TAQA2JA7AJQA 10 TAJAQAKAT777 13 ``` [Answer] # PHP, 240 bytes ``` $a=str_split($argv[1]);foreach($a as$k=>$v)$n[$k]=$v=='A'?1:($v==0?10:$v);for($i=0;$i<=$k;$i++){$s=$a[$i];$r=$n[$i];for($j=$i+1;$j<=$k;$j++){$s.=$a[$j];$r+=$n[$j];if ($r==21||($r==11&&stristr($s,'A')))$f[]=$s;}}echo count(array_unique($f)); ``` **Ungolfed :** ``` $a = str_split($argv[1]); foreach ($a as $k=>$v) $n[$k] = $v == 'A' ? 1 : ($v == 0 ? 10 : $v); for ($i=0; $i<=$k; $i++) { $s = $a[$i]; $r = $n[$i]; for ($j=$i+1; $j<=$k; $j++) { $s .= $a[$j]; $r += $n[$j]; if ($r == 21 || ($r == 11 && stristr($s,'A')) ) $f[] = $s; } } echo count(array_unique($f)); ``` [**Try it here!**](https://eval.in/740611) ]
[Question] [ [There's a question on this site](https://codegolf.stackexchange.com/questions/5891/josephus-problem-counting-out "There's a question on this site that is similar to this one") that is similar to this question, but I have added a twist. You have three inputs, the number of people in the circle *n*, the *k*-th person counted out at each step, and the *q*-th person that survives. The people in the circle are numbered 1 to *n*. For example, in a circle of 20 people, the 20th person to survive is the very first person removed, the 19th survivor is the second person removed and so on. Normally, the Josephus problem is to determine the *last* person removed, here called the *first* survivor. Write the shortest program or function that, with those three inputs, returns the number of the *q*-th person to survive. If there are any issues with clarity, please let me know. Some examples: ``` >>> josephus(20, 3, 9) 4 >>> josephus(4, 3, 1) 1 >>> josephus(100, 9, 12) 46 ``` **Edit:** Assume all inputs are valid. That is no one will ask for 0 or any negative numbers and no one will ask for the 20th survivor in a circle of 5 people (that is, 1 ≤ q ≤ n) **Edit:** I'll accept an answer at midnight UTC+7 at the start of December 2. [Answer] # Piet, ~~280~~ 273 codels [![enter image description here](https://i.stack.imgur.com/0CTFk.png)](https://i.stack.imgur.com/0CTFk.png) **Edit:** I have golfed this down some more, and I think I can golf it down even further, but that is still to come. For now, I'm just glad it works, and that I had room to sign it in the bottom left-hand corner. Two ideas I have to save more codels are a) to change the end instructions be `pop, push 1, add, out num` (pop n, output r+1) and b) to duplicate again at the bottom left corner to save codels in stack manipulation later on in the loop. The picture above is my code at 8 pixels per codel. In general, it's the same algorithm as my Python answer, but with the inputs in the order of **k**, **q**, **n**. In practice, there is a also a great deal of stack manipulation. You can [try it here](http://www.rapapaing.com/blog/?page_id=6) by opening the image there and running the code with it. **Explanation** This is a step-by-step ungolfing of the solution. ``` in num get k dup Stack: k k push 1 subtract Stack: k k-1 in num get q dup Stack: k k-1 q q dup Stack: k k-1 q q q push 4 push 2 roll Stack: k q q k-1 q mod Stack: k q q r in num get n # note: the loop will return to the following codel dup Stack: k q q r n n push 4 push 3 roll Stack: k q r n n q greater 1 or 0 pointer Here the loop begins. If q>n, the pointer moves clockwise. Else, it points straight ahead LOOP: Stack: k i r n (i=q at the start of the loop) push 4 push 2 roll Stack: r n k i push 1 add Stack: r n k i=i+1 push 2 push 1 roll Stack: r n i k dup Stack: r n i k k push 5 push 4 roll Stack: n i k k r add Stack: n i k m=r+k push 3 push 2 roll Stack: n k m i dup Stack: n k m i i push 3 # here it turns the corner push 1 roll Stack: n k i m i mod Stack: n k i r=m%i push 4 # here it turns the corner and avoids the black codels push 1 roll Stack: r n k i dup Stack: r n k i i push 5 push 3 roll Stack: k i i r n dup Stack: k i i r n n # and we meet up with the dark green codel once more push 4 push 3 roll Stack: k i r n n i greater Stack: k i r n (0 or 1) pointer if else again # else Stack: k i r n push 2 push 1 roll Stack: k i n r # and turn the corner push 1 add Stack: k i n r+1 out num print r+1 # turn the corner into the end pattern (the shape with the black edges) END ``` [Answer] # Pyth, 16 bytes ``` eu.<PGvzh-QvwShQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite=0&input=3%0A20%0A9&input_size=3&code=eu.%3CPGvzh-QvwShQ&test_suite_input=3%0A20%0A9%0A3%0A4%0A1%0A9%0A100%0A12) or [Test Suite](http://pyth.herokuapp.com/?test_suite=1&input=3%0A20%0A9&input_size=3&code=eu.%3CPGvzh-QvwShQ&test_suite_input=3%0A20%0A9%0A3%0A4%0A1%0A9%0A100%0A12) Input is of the form `k<newline>n<newline>q`. ### Explanation: ``` eu.<PGvzh-QvwShQ implicit: z = first input line (string) Q = second input line (integer) hQ Q + 1 S the range [1, 2, ..., Q+1] u h-Qvw apply the following statement (Q-input()+1) times to G=^ PG remove the last number of G .< vz and rotate eval(z) to the left e print the last number of the resulting list ``` [Answer] # CJam, ~~22~~ ~~20~~ 19 bytes ``` q~_,@a@*{m<)\}%\~=) ``` This reads the input as `q k n`. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~_%2C%40a%40*%7Bm%3C)%5C%7D%25%5C~%3D)&input=1%203%207). ### How it works ``` q~ Read and evaluate all input. This pushes q, k, and n. _, Push A := [0 ... n-1]. @a Rotate on top of the stack and wrap it in an array. @* Rotate the original n on top and repeat [k] n times. { }% For each of the n k's: m< Rotate A k units to the left. )\ Pop the last element and swap it with A. \~ Swap the resulting array with q and apply bitwise NOT. =) Select the corresponding element and add 1 to it. ``` [Answer] # JavaScript (ES6), 56 bytes ``` (n,k,q)=>{r=(k-1)%q;for(i=q;i<n;r=(r+k)%++i);return r+1} ``` ## Ungolfed Basically a JavaScript adaptation of [@Sherlock9](https://codegolf.stackexchange.com/users/47581/sherlock9)'s Python answer. ``` (n,k,q)=>{ r=(k-1)%q; for(i=q;i<n;r=(r+k)%++i); return r+1 } ``` ## Test ``` n = <input type="number" id="N" value="100" /><br /> k = <input type="number" id="K" value="9" /><br /> q = <input type="number" id="Q" value="12" /><br /> <button onclick="result.innerHTML=( (n,k,q)=>{r=(k-1)%q;for(i=q;i<n;r=(r+k)%++i);return r+1} )(+N.value,+K.value,+Q.value)">Go</button><br /> <pre id="result"></pre> ``` [Answer] ## Golfscript, ~~58~~ ~~56~~ ~~55~~ ~~35~~ ~~31~~ 30 bytes Assuming the three inputs are already in the stack, in the order **n**, **k**, **q** ``` ~1$(1$%3$),@),-{\2$+\%}%\)])\; ``` That solution assumes I need to get rid of everything but the final answer. ### How it works See `j(n,k,q)` in my Python 3 solution for more detail. ``` ~ Read the inputs n, k, q 1$( Duplicate k, decrement 1$ Duplicate q % (k-1)%q 3$), Create array [0..n+1] @), Create array [0..q+1] - Subtract the second array from the first, leaving only [q+1..n+1] { }% Map the following statement onto [q+1..n+1]. The numbers from this array will be denoted i. \ Swap i and r 2$+ Duplicate k, add to r \ Swap r and i % r mod i \) Swap the leftover array from map with r, increment ] Put the whole stack into an array ) Remove the last member of the array, r \; Pop the array, leaving only the result ``` **Edit 1:** Used @Doorknob's suggestion (Added a + to get all the inputs into the array) Formerly, ``` \.(2$2$*1$4$%-{.5$3$*>!}{~)2$*1$/~)}while 4$3$*\-)\;\;\;\; ``` **Edit 2:** Added ~, per the rules of the wiki, and shortened the code. Thanks @Dennis Formerly, ``` [\.(2$2$*1$4$%-{.5$3$*>!}{~)2$*1$/~)}while 4$3$*\-)]+)\; ``` **Edit 3:** Implemented a shorter algorithm. Formerly, ``` ~\.(2$2$*1$4$%-{.5$3$*>!}{~)2$*1$/~)}while 4$3$*\-)]-1= ``` **Edit 4:** Figured out that I could use `%` as map. Formerly, ``` ~1$(1$%{1$4$<}{\)\2$+1$%}while)])\; ``` **Edit 5:** Minor edit. Changed `2$` to `@` to make `[0..q-1]` and `3$` to `2$` to retrieve `k`. Saved a bite Formerly, ``` ~1$(1$%3$),2$),-{\3$+\%}%\)])\; ``` [Answer] # C, ~~81~~ 73 bytes Based off [@user81655](https://codegolf.stackexchange.com/users/46855/user81655)'s Javascript implementation of my Python answer. **Edit:** Removed i ``` int j(int n,int k,int q){int r=(k-1)%q;for(;q<n;r=(r+k)%++q);return r+1;} ``` ### Test ``` #include <stdio.h> int j(int n,int k,int q){int r=(k-1)%q;for(;q<n;r=(r+k)%++q);return r+1;} int main() { printf("%d\n", j(20,3,9)); return 0; } ``` [Answer] ## Python 3, ~~72~~ ~~66~~ 62 bytes A dynamic programming function in 62 bytes. Adapted from [the algorithm on Wikipedia.](https://en.wikipedia.org/wiki/Josephus_problem) There used to be a direct implementation of this algorithm when q=1 (i.e. i=1, r=0) on that page, but I see that has been removed now. **Edit 1:** I removed `i` to save 4 bytes. Explanation remains unchanged. **Edit 2:** Miscalculation in byte count. I was using `\r\n` for EOL and didn't notice when that added 3 bytes. I have lowered my byte count accordingly. ``` def j(n,k,q): r=(k-1)%q while q<n:q+=1;r=(r+k)%q return r+1 ``` ### How this works ``` def j(n,k,q): i=q;r=(k-1)%q We start with the smallest possible circle to have a q-th survivor, a circle of q people. while i<n:i+=1; Iterate from q to n r=(r+k)%i Every time you add people to the circle, r increases by k, modulo the current size of the circle i. return r+1 Return the result. ``` Thanks to @Dennis for reminding me that I should explain my code (if only implicitly, because he included one in his answer). If anything is unclear, please let me know. ### Edit: Formerly, An iterative function that is adapted from *Concrete Mathematics* by Graham, Knuth and Patashnik. Though this algorithm is longer, it is faster for large *n* and small *k*. ``` def t(n,k,q): m=k-1;z=q*k-m%q while z<=n*m:z=-(-z*k//m) return n*k-z+1 ``` [Answer] # Mathematica, 50 bytes ``` <<Combinatorica` Tr@Position[Josephus@##2,1+#2-#]& ``` An anonymous function. Takes inputs in the order `q,n,k`. [Answer] ## PHP, 71 bytes Based off of @Sherlock9's answers. See his Python answer for the algorithm. ``` function a($n,$k,$q){for($r=($k-1)%$q;$q<$n;$r=($r+$k)%++$q);echo$r+1;} ``` Alternatively, here is my original naive approach without the algorithm. This uses an array to mark which people are found. **91 bytes** ``` function a($n,$k,$q){for($r=--$i;$q<=$n;++$i%$k||$c[$r]=$q++)while($c[$r=++$r%$n]);echo$r;} ``` [Answer] # Haskell, ~~48~~ ~~47~~ 43 bytes ``` (n!k)q=1+foldl(mod.(k+))(mod(k-1)q)[q+1..n] ``` Based on a Haskell algorithm on [the Rosetta Code page](http://rosettacode.org/wiki/Josephus_problem#Haskell) of the Josephus function with two inputs. Golfing suggestions are welcome. **Edit:** My thanks to [nimi](https://codegolf.stackexchange.com/users/34531/nimi) for help with golfing the first algorithm via suggesting a pointfree version, and for help with golfing the second algorithm by letting me know that the `until` keyword exists. ``` (n#k)q|m<-k-1=1+n*k-until(>n*m)(\z-> -div(-z*k)m)(q*k-mod m q) ``` A version of the algorithm at the end of [my Python answer](https://codegolf.stackexchange.com/a/64668/47581) adapted from Concrete Mathematics by Graham, Knuth and Patashnik. Though this algorithm is longer at 62 bytes, and has not been golfed down as much as the first, it is faster for large `n` and small `k`. **Ungolfed:** First algorithm ``` jos_g num step q = 1 + foldl (\x -> mod (x + step) ) (mod (step-1) q) [q+1..num] ``` Second algorithm ``` jos_gkp num step q -- ceiling throws a type-related fit with ceiling(z*k/(k-1)) -- better to use - div (-z * k) (k - 1) | m <- step-1 = 1 + num*step - until (>num*m)(\z-> -div (-z*k) m) (q*step - mod m q) ``` [Answer] # GameMaker Language (GML), 88 bytes Based on @user81655's answer ``` r=argument0 k=argument1 q=argument2 r=(k-1)mod q;for(i=q;i<n;r=(r+k)mod ++i){}return r+1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Rµṙ⁴ṖµL>⁵µ¿⁴ị ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=UsK14bmZ4oG04bmWwrVMPuKBtcK1wr_igbThu4s&input=&args=MTAw+OQ+MTI)** ### How? ``` Rµṙ⁴ṖµL>⁵µ¿⁴ị - Main link: n, k, q µ - monadic chain separation R - range(n): [1,2,3,...,n] - the circle of people µ µ¿ - while L - length > - greater than ⁵ - 5th program argument (3rd input), i.e. q ṙ - rotate left by ⁴ - 4th program argument (2nd input) i.e. k Ṗ - pop - remove the rightmost person ị - get index ⁴ - 4th program argument (2nd input), i.e. k ``` [Answer] # Ruby, ~~53~~ 48 bytes A lambda. ``` ->n,k,q{r=(k-1)%q;(q+=1;r=(r+k)%q)while q<n;r+1} ``` ### How it works ``` def j(n,k,q) r=(k-1)%q # r starts at j[q,k,q] while q<n q+=1 r=(r+k)%q # Every time you add people to the circle, r increases by k, # modulo the current size of the circle q. end r+1 # Return the result. end ``` ]
[Question] [ **Overview:** From [Wikipedia](http://en.wikipedia.org/wiki/Egyptian_fraction): An Egyptian fraction is the sum of distinct unit fractions. That is, each fraction in the expression has a numerator equal to 1 and a denominator that is a positive integer, and all the denominators differ from each other. The value of an expression of this type is a positive rational number a/b. Every positive rational number can be represented by an Egyptian fraction. **Challenge:** Write the shortest function that will return the values of all the denominators for the *smallest set* of unit fractions that add up to a given fraction. **Rules/Constraints:** * Input will be two positive integer values. + This can be on `STDIN`, `argv`, comma separated, space delimited, or any other method you prefer. * The first input value shall be the numerator and the second input value the denominator. * The first input value shall be less than the second. * The output may include a value(s) that exceeds the memory limitations of your system/language (RAM, MAX\_INT, or whatever other code/system constraints exist). If this happens, simply truncate the result at the highest possible value and note that somehow (i.e. `...`). * The output should be able to handle a denominator value up to at least 2,147,483,647 (231-1, signed 32-bit `int`). + A higher value (`long`, etc.) is perfectly acceptable. * The output shall be a listing of all values of denominators of the smallest set of unit fractions found (or the fractions themselves, i.e. `1/2`). * The output shall be ordered ascending according to the value of the denominator (descending by the value of the fraction). * The output can be delimited any way you wish, but there must be some character between so as to differentiate one value from the next. * This is code golf, so the shortest solution wins. **Exmaples:** * Input 1: `43, 48` * Output 1: `2, 3, 16` * Input 2: `8/11` * Output 2: `1/2 1/6 1/22 1/66` * Input 3: `5 121` * Output 3: `33 121 363` [Answer] ## Python 2, ~~169~~ 167 chars ``` x,y=input() def R(n,a,b): if n<2:return[b/a][b%a:] for m in range((b+a-1)/a,b*n/a): L=R(n-1,a*m-b,m*b) if L:return[m]+L n=L=0 while not L:n+=1;L=R(n,x,y) print L ``` Takes comma-separated args on stdin and prints a python list on stdout. ``` $ echo 8,11 | ./egypt.py [2, 5, 37, 4070] ``` [Answer] ## Common Lisp, 137 chars ``` (defun z(n)(labels((i(n s r)(cond((= n 0)r)((< n(/ 1 s))(i n(ceiling(/ 1 n))r))(t(i(- n(/ 1 s))(1+ s)(cons s r))))))(reverse(i n 2'())))) ``` (z 43/48) -> (2 3 16) (z 8/11) -> (2 5 37 4070) (z 5/121) -> (25 757 763309 873960180913 1527612795642093418846225) No need to worry about huge numbers, or handling fractional notation! [Answer] ## PHP 82 bytes ``` <?for(fscanf(STDIN,"%d%d",$a,$b);$a;)++$i<$b/$a||printf("$i ",$a=$a*$i-$b,$b*=$i); ``` This could be made shorter, but the current numerator and denominator need to be keep as whole numbers to avoid floating point rounding error (instead of keeping the current fraction). Sample usage: ``` $ echo 43 48 | php egyptian-fraction.php 2 3 16 $ echo 8 11 | php egyptian-fraction.php 2 5 37 4070 ``` [Answer] ## C, 163 177 chars **6/6**: At last, the program now correctly handles truncation in all cases. It took a lot more chars than I was hoping for, but it was worth it. The program should 100% adhere to the problem requirements now. ``` d[99],c,z; r(p,q,n,i){for(c=n+q%p<2,i=q/p;c?d[c++]=i,0:++i<n*q/p;)q>~0U/2/i?c=2:r(i*p-q,i*q,n-1);} main(a,b){for(scanf("%d%d",&a,&b);!c;r(a,b,++z));while(--c)printf("%d\n",d[c]);} ``` The program takes the numerator and denominator on standard input. The denominators are printed to standard output, one per line. Truncated output is indicated by printing a zero denominator at the end of the list: ``` $ ./a.out 2020 2064 2 3 7 402 242004 $ ./a.out 6745 7604 2 3 19 937 1007747 0 ``` The denominators in the second example sum to 95485142815 / 107645519046, which differs from 6745 / 7604 by roughly 1e-14. [Answer] ## Python, 61 chars Input from STDIN, comma separated. Output to STDOUT, newline separated. Doesn't always return the shortest representation (e.g. for 5/121). ``` a,b=input() while a: i=(b+a-1)/a print"1/%d"%i a,b=a*i-b,i*b ``` Characters counted without unneeded newlines (i.e. joining all lines within the `while` using `;`). The fraction is `a/b`. `i` is `b/a` rounded up, so I know `1/i <= a/b`. After printing `1/i`, I replace `a/b` with `a/b - 1/i`, which is `(a*i-b)/(i*b)`. [Answer] # C, 94 bytes ``` n,d,i;main(){scanf("%i%i",&n,&d);for(i=1;n>0&++i>0;){if(n*i>=d)printf("%i ",i),n=n*i-d,d*=i;}} ``` [Try It Online](https://tio.run/##HctBCoQwDAXQq0jB0mgEuxsI7V2kofIXxkHdiWfvDK4fr0xrKa0ZK0O2BRboPstiNbgePRx7Y68kdT8CUhTLsx9H5FnoRg02ICel7wG73tI5BrGlP0zKOiTI87T26WL8AQ) edit: A shorter version of the code was posted in the comments so I replaced it. Thanks! [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é├WüsOΩ↨÷╬6H╒σw[▐â ``` [Run and debug it](https://staxlang.xyz/#p=82c35781734fea17f6ce3648d5e5775bde83&i=43%2F48%0A8%2F11%0A5%2F121%0A55%2F89&a=1&m=2) At each step, it tries to minimize the subsequent *numerator*. It seems to work, but I can't prove it. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 bytes ``` ⌂efract ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qW9CjtgmGRhbmXEBOQACQY2zy/1FPU2paUWJyyf80oMCj3r5HXc2Petc86t1yaL3xo7aJQKXBQc5AMsTDM/i/ibFCmoKJBZcFkDI05DIFUUaGAA "APL (Dyalog Extended) – Try It Online") From *some* reason, Dyalog APL has a builtin for this. Takes the numerator and denominator on the left and the right [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ḟo=⁰ΣṖİ\ ``` [Try it online!](https://tio.run/##AR4A4f9odXNr///huJ9vPeKBsM6j4bmWxLBc////NDMvNDg "Husk – Try It Online") Larger denominators take very long, as we are calculating the powerset of an infinite list. Takes input as a fraction `a/b`. ## Explanation ``` ḟo=⁰ΣṖİ\ İ\ Infinite list [1,1/2,1/3...] Ṗ Powerset ḟo first sublist which satisfies: Σ sum =⁰ equals input? ``` [Answer] # AXIOM, 753 bytes ``` L==>List FRAC INT macro M(q)==if c<m or(c=m and m<999 and reduce(max,map(denom,q))<xv)then(m:=c;a:=q;xv:=reduce(max,map(denom,a))) f(x,n)==(y:=x;a:L:=[];c:=0;q:=denom x;q:=q^4;for i in n.. repeat((c:=c+1)>50=>(a:=[];break);1/i>y=>1;member?(1/i,a)=>1;a:=concat(a,1/i);(y:=y-1/i)=0=>break;numer(y)=1 and ~member?(y,a)=>(a:=concat(a,y);break);(i:=floor(1/y))>q=>(a:=[];break));a) h(x:FRAC INT):L==(a:L:=[];x>1=>a;numer(x)=1=>[x];n:=max(2,floor(1/x));xv:=m:=999;d:=denom x;zd:=divisors d;z:=copy zd;for i in 2..30 repeat z:=concat(z,i*zd);d:=min(10*d,n+9*m);for i in n..d repeat((c:=maxIndex(b:=f(x,i)))=0=>1;c>m+1=>1;M(b);v:=reduce(+,delete(b,1));for j in z repeat((c:=1+maxIndex(q:=f(v,j)))=1=>1;member?(b.1,q)=>1;q:=concat(b.1,q);M(q)));reverse(sort a)) ``` The idea would be apply the "Greedy Algorithm" with different initial points, and save the list that has minimum length. But not always it would find the min solution with less difined: "array A will be less than array B if and only if A has few elements of B, or if the number of elements of A is the same of number of elements of B, than A it is less than B if the more little element of A is bigger as number, than the more little element of B". Ungolfed and test ``` -- this would be the "Greedy Algorithm" fracR(x,n)== y:=x;a:L:=[];c:=0;q:=denom x;q:=q^4 for i in n.. repeat (c:=c+1)>50 =>(a:=[];break) 1/i>y =>1 member?(1/i,a)=>1 a:=concat(a,1/i) (y:=y-1/i)=0 =>break numer(y)=1 and ~member?(y,a)=>(a:=concat(a,y);break) (i:=floor(1/y))>q =>(a:=[];break) a -- Return one List a=[1/x1,...,1/xn] with xn PI and x=r/s=reduce(+,a) or return [] for fail Frazione2SommaReciproci(x:FRAC INT):L== a:L:=[] x>1 =>a numer(x)=1=>[x] n:=max(2,floor(1/x));xv:=m:=999;d:=denom x;zd:=divisors d;z:=copy zd for i in 2..30 repeat z:=concat(z,i*zd) d:=min(10*d,n+9*m) for i in n..d repeat (c:=maxIndex(b:=fracR(x,i)))=0=>1 c>m+1 =>1 M(b) v:=reduce(+,delete(b,1)) for j in z repeat (c:=1+maxIndex(q:=fracR(v,j)))=1=>1 member?(b.1,q) =>1 q:=concat(b.1,q) M(q) reverse(sort a) (7) -> [[i,h(i)] for i in [1/23,2/23,43/48,8/11,5/121,2020/2064,6745/7604,77/79,732/733]] (7) 1 1 2 1 1 43 1 1 1 8 1 1 1 1 [[--,[--]], [--,[--,---]], [--,[-,-,--]], [--,[-,-,--,--]], 23 23 23 12 276 48 2 3 16 11 2 6 22 66 5 1 1 1 505 1 1 1 1 1 [---,[--,---,---]], [---,[-,-,-,---,----]], 121 33 121 363 516 2 3 7 602 1204 6745 1 1 1 1 1 1 77 1 1 1 1 1 1 [----,[-,-,--,---,-----,------]], [--,[-,-,-,--,---,---]], 7604 2 3 19 950 72238 570300 79 2 3 8 79 474 632 732 1 1 1 1 1 1 1 [---,[-,-,-,--,----,-----,-----]]] 733 2 3 7 45 7330 20524 26388 Type: List List Any Time: 0.07 (IN) + 200.50 (EV) + 0.03 (OT) + 9.28 (GC) = 209.88 sec (8) -> h(124547787/123456789456123456) (8) 1 1 1 [---------, ---------------, ---------------------------------, 991247326 140441667310032 613970685539400439432280360548704 1 -------------------------------------------------------------------] 3855153765004125533560441957890277453240310786542602992016409976384 Type: List Fraction Integer Time: 17.73 (EV) + 0.02 (OT) + 1.08 (GC) = 18.83 sec (9) -> h(27538/27539) 1 1 1 1 1 1 1 1 (9) [-,-,-,--,---,-----,------,----------] 2 3 7 52 225 10332 826170 1100871525 Type: List Fraction Integer Time: 0.02 (IN) + 28.08 (EV) + 1.28 (GC) = 29.38 sec ``` reference and numbers from: <http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.html> for add something, this below would be the one optimized for find min length fraction that has the max denominator less (and not optimized for lengh) ``` L==>List FRAC INT -- this would be the "Greedy Algorithm" fracR(x,n)== y:=x;a:L:=[];c:=0;q:=denom x;q:=q^20 for i in n.. repeat (c:=c+1)>1000 =>(a:=[];break) 1/i>y =>1 member?(1/i,a) =>1 a:=concat(a,1/i) (y:=y-1/i)=0 =>break numer(y)=1 and ~member?(y,a)=>(a:=concat(a,y);break) (i:=floor(1/y))>q =>(a:=[];break) a -- Return one List a=[1/x1,...,1/xn] with xn PI and x=r/s=reduce(+,a) or return [] for fail Frazione2SommaReciproci(x:FRAC INT):L== a:L:=[] x>1 =>a numer(x)=1=>[x] n:=max(2,floor(1/x));xv:=m:=999;d:=denom x;zd:=divisors d;z:=copy zd; w1:= if d>1.e10 then 1000 else 300; w2:= if d>1.e10 then 1000 else if d>1.e7 then 600 else if d>1.e5 then 500 else if d>1.e3 then 400 else 100; for i in 2..w1 repeat(mt:=(i*zd)::List PI;mv:=[yy for yy in mt|yy>=n];z:=sort(removeDuplicates(concat(z,mv)));#z>w2=>break) for i in z repeat (c:=maxIndex(b:=fracR(x,i)))=0=>1 c>m+1 =>1 if c<m or(c=m and m<999 and reduce(max,map(denom,b))<xv)then(m:=c;a:=b;xv:=reduce(max,map(denom,a))) v:=reduce(+,delete(b,1)) for j in z repeat (c:=1+maxIndex(q:=fracR(v,j)))=1=>1 member?(b.1,q) =>1 q:=concat(b.1,q) if c<m or(c=m and m<999 and reduce(max,map(denom,q))<xv)then(m:=c;a:=q;xv:=reduce(max,map(denom,a))) reverse(sort a) ``` the results: ``` (5) -> [[i,Frazione2SommaReciproci(i)] for i in [1/23,2/23,43/48,8/11,5/121,2020/2064,6745/7604,77/79,732/733]] (5) 1 1 2 1 1 43 1 1 1 8 1 1 1 1 [[--,[--]], [--,[--,---]], [--,[-,-,--]], [--,[-,-,--,--]], 23 23 23 12 276 48 2 3 16 11 2 6 22 66 5 1 1 1 505 1 1 1 1 1 [---,[--,---,---]], [---,[-,-,-,---,----]], 121 33 121 363 516 2 3 7 602 1204 6745 1 1 1 1 1 1 77 1 1 1 1 1 1 [----,[-,-,--,---,-----,------]], [--,[-,-,-,--,---,---]], 7604 2 3 19 950 72238 570300 79 2 3 8 79 474 632 732 1 1 1 1 1 1 1 [---,[-,-,-,--,----,-----,-----]]] 733 2 3 7 45 7330 20524 26388 Type: List List Any Time: 0.08 (IN) + 53.45 (EV) + 3.03 (GC) = 56.57 sec (6) -> Frazione2SommaReciproci(124547787/123456789456123456) (6) 1 1 1 1 [---------, ------------, ----------------, -------------------, 994074172 347757767307 2764751529594496 1142210063701888512 1 -------------------------------------] 2531144929865351036156388364636113408 Type: List Fraction Integer Time: 0.15 (IN) + 78.30 (EV) + 0.02 (OT) + 5.28 (GC) = 83.75 sec (7) -> Frazione2SommaReciproci(27538/27539) 1 1 1 1 1 1 1 1 (7) [-,-,-,--,----,-------,-------,-------] 2 3 7 43 1935 3717765 5204871 7105062 Type: List Fraction Integer Time: 0.05 (IN) + 45.43 (EV) + 2.42 (GC) = 47.90 sec ``` It seems many good denominators have as factor divisors of the input fraction denominator. [Answer] # APL(NARS), 2502 bytes ``` fdn←{1∧÷⍵}⋄fnm←{1∧⍵}⋄ffl←{m←⎕ct⋄⎕ct←0⋄r←⌊⍵⋄⎕ct←m⋄r}⋄divisori←{a[⍋a←{∪×/¨{0=≢⍵:⊂⍬⋄s,(⊂1⌷⍵),¨s←∇1↓⍵}π⍵}⍵]} r←frRF w;x;y;c;q;i;j (x i)←w⋄i-←1⋄y←x⋄r←⍬⋄c←0⋄q←fdn x⋄q←q*20 i+←1 →4×⍳∼1000<c+←1⋄→6 j←÷i⋄→2×⍳j>y⋄→2×⍳(⊂j)∊r⋄r←r,(⊂j)⋄y←y-j⋄→0×⍳y=0⋄→5×⍳1≠fnm y⋄→5×⍳(⊂y)∊r⋄r←r,⊂y⋄→0 →2×⍳∼q<i←ffl ÷y r←⍬ r←fr2SumF x;n;xv;m;d;zd;z;i;b;c;t;v;j;k;q;w1;w2;t;b1 z←r←⍬⋄→0×⍳1≤ffl x :if 1=fnm x⋄r←,⊂x⋄→0⋄:endif n←2⌈ffl÷x⋄xv←m←999⋄d←fdn x⋄zd←divisori d w1←1000⋄w2←50⋄:if d>1.e10⋄w2←700⋄:elseif d>1.e7⋄w2←600⋄:elseif d>1.e5⋄w2←500⋄:elseif d>1.e3⋄w2←400⋄:elseif d>1.e2⋄w2←100⋄:endif :for i :in ⍳w1⋄z←∪z∪k/⍨{⍵≥n}¨k←i×zd⋄:if w2<≢z⋄:leave⋄:endif⋄:endfor z←∪z∪zd⋄z←z[⍋z] :for i :in z :if 0=c←≢b←frRF x i ⋄:continue⋄:endif :if c>m+1 ⋄:continue⋄:endif :if c<m ⋄m←c⋄r←b⋄xv←⌈/fdn¨b :elseif (c=m)∧(m<999) :if xv>t←⌈/fdn¨b⋄m←c⋄r←b⋄xv←t⋄:endif :endif :if c≤2⋄:continue⋄:endif v←↑+/1↓b⋄b1←(⊂↑b) :for j :in z :if 1=c←1+≢q←frRF v j⋄:continue⋄:endif :if b1∊q ⋄:continue⋄:endif q←b1,q :if c<m⋄m←c⋄r←q ⋄xv←⌈/fdn¨q :elseif (c=m)∧(m<999) :if xv>t←⌈/fdn¨q⋄m←c⋄r←q⋄xv←t⋄:endif :endif :endfor :endfor →0×⍳1≥≢r⋄r←r[⍋fdn¨r] ``` Traslation from AXIOM code for this problem, to APL, using for the first time (for me) the fraction type (that is bignum...). 103r233 means the fraction 103/233. Test: ``` ⎕fmt fr2SumF 1r23 ┌1────┐ │ 1r23│ └~────┘ ⎕fmt fr2SumF 2r23 ┌2──────────┐ │ 1r12 1r276│ └~──────────┘ ⎕fmt fr2SumF 43r48 ┌3────────────┐ │ 1r2 1r3 1r16│ └~────────────┘ fr2SumF 8r11 1r2 1r6 1r22 1r66 fr2SumF 5r121 1r33 1r121 1r363 fr2SumF 2020r2064 1r2 1r3 1r7 1r602 1r1204 fr2SumF 6745r7604 1r2 1r3 1r19 1r950 1r72238 1r570300 fr2SumF 77r79 1r2 1r3 1r8 1r79 1r474 1r632 fr2SumF 732r733 1r2 1r3 1r7 1r45 1r7330 1r20524 1r26388 fr2SumF 27538r27539 1r2 1r3 1r7 1r43 1r1935 1r3717765 1r5204871 1r7105062 fr2SumF 124547787r123456789456123456 1r994074172 1r347757767307 1r2764751529594496 1r1142210063701888512 1r2531144929865351036156388364636113408 ``` [Answer] # [GAP](https://www.gap-system.org/), 340 bytes ``` f:=function(b,l)local x,R;if l=1 then if IsInt(b)then return[[b]];fi;return[];fi;R:=[];for x in[Int(b)+1..Int(l*b)]do UniteSet(R,List(Filtered(f(b*x/(x-b),l-1),d->not x in d),s->UnionSet([x],s)));od;return R;end;e:=function(n,d)local l,R;l:=0;repeat l:=l+1;R:=f(d/n,l);until R<>[];return Filtered(R,s->s[l]=Minimum(List(R,s->s[l])))[1];end; ``` [Try it online!](https://tio.run/##TY@xbsMgEIZ3PwUjJDgpW2Vij5UitQtVJ8RgB2iRLkdkY8lv74JrRd3@Q/x33/fdP9bVN62f8ZZCRDpwYBBvPZCFKxk8gVaQ9OOQ5HydrpjowMpcjS7NI2o9GCN9kPu4ZdW0JcSRLCSg/isdxelUEhwGZmysvjAk9@kSVfw9TIm@BUhudJZ6OhyWM13qgXGoBeO27jCmbRexjE91l7sRS1cvhk@MMRntTlAp6dBK988Jud2dIDtB077kvw/XJ5IzHEXh9dSeMbvLGVMAoi5dNtg3PslUuT1pMO1HwHCf73Qjfz5nEC3Mdn9dHX3lQjD5Cw "GAP – Try It Online") The entry function is `e`, which takes two parameters, the numerator and denominator in that order, as required. 2 characters could be golfed (replace `n,d` with `q` and `d/n` with `1/q`) if I may make `e` take the fraction `n/d` direct, and 2 more if I may make `e` take its reciprocal `d/n`. But this goes against the question. The helper function `f` returns a list of the ways to represent `1/b` in `l` distinct terms. ]
[Question] [ The barfoos, a hypothetical alien species, go about charity in an interesting way. Every morning, barfoo Specialists come up with an ordered list of causes to donate to, and for each cause they recommend what quantity of resources should be donated. That wasn't the weird part. Here's the weird part: A random civilian barfoo will donate the recommended quantity of resources to the first cause. Another one will likewise donate to the very next cause on the list, and keep going down the list until it has given at least as much as its compatriot, at which point it immediately stops. This continues, each civilian giving at least as much as *the one directly before*, until the remaining elements of the Great List of Charitable Causes can no longer satisfy this donation arms race, at which point the Specialists themselves just chip in. **How many civilian barfoos are involved?** **Input:** a sequence of \$1\leq n\leq100000\$ integers each of value \$1\leq i\leq1000\$, representing the recommended donation sizes for the Great List of Charitable Causes in the order in which it's given to the barfoos. **Output:** a single integer representing the number of civilian barfoos who donate something. ## Sample 1 Input: `5 2 3 1 3 4 2 5` Output: `3` This may be divided into the buckets `5`, `2 3` (sum 5), `1 3 4` (sum 8) and `2 5` (sum 7, cannot satisfy a fourth civilian barfoo). ## Sample 2 Input: `4 1 2 3 6 6` Output: `4` This may be divided into the buckets `4`, `1 2 3` (sum 6), `6` and `6`. (In this case, no Specialists need to involve themselves.) --- * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code in bytes wins. * [The](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/) [linked](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) [rules](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * Please explain your code. * Please link to Try It Online! or another online demo. --- Credit: ['Nomnomnom' (AIO 2009, Senior)](https://orac.amt.edu.au/cgi-bin/train/problem.pl?set=aio09sen&problemid=422) [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` d=p=t=0 for x in input(): d-=x if d<1:t+=1;p=d=p-d print t ``` [Try it online!](https://tio.run/##bYxBCsIwEEX3OcWQlWIKTmxdROckpSuT0oCkoUwxnj6OcSs8Psz7n8lvXtZk62uJzwDoQgkPrXX1lInprOZ1gwIxCXnnw9Ep8B0VBXEGf0fHJ8JbJpl3XuUtJgau3wfjYMAauBjAln07h0mNfVO/7iqIwqb@I7Vtc5w@ "Python 2 – Try It Online") The code is easier to understand in the below version, which is fairly natural: `t` tracks the number of barfoos who donate, `p` tracks the previous donation, and `s` tracks the sum of the current barfoo's donation. **61 bytes** ``` s=p=t=0 for x in input(): s+=x if s>=p:t+=1;p=s;s=0 print t ``` [Try it online!](https://tio.run/##bYxBCsIwEEX3OcWQldIsTGxdpIwXKV1JSgOSDs0U4@njGLfC48O8/xl687olV19rfAawPpTw0FrXjISMF7VsOxSISaCDT2evIHdYFMQF8h3Jc4d2JMxjljXtMTFw/X6YBgPOwNWAbdm3c5jV1Df1626CKNvUf6R2bW7nDw "Python 2 – Try It Online") The original replaces tracking `s` with tracking `d=p-s`, the amount the current barfoo needs to donate to catch up with the previous donation. This lets us replace `s>=p` with `d<1`, saving a byte. Note that `s/p` doesn't work because `p` starts at 0. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~59~~ ~~57~~ ~~59~~ 58 bytes Don't mind me, just abusing the walrus ``` lambda y,p=0,d=0:len([p:=(d:=p-d)for x in y if(d:=d-x)<1]) ``` [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum) shaved a byte using [xnor's idea](https://codegolf.stackexchange.com/a/203996/32604) to keep track of the remaining amount of donation needed instead of the current donation. [Try it online!](https://tio.run/##LY3RioMwEEXf8xWDfUlAS626LLLpj3T74DZKw8Y4TFK2In67O3GXIXDn3JME5/iYfPWOtA36c3Pd@GU6mHPUp9zoU@t6L6/YamlajYVRw0TwAuthBjskaIqX@ihvarMjThQhzEGIZDnr@yQyOIZorG8FwAGo7wxjfEZeQw6dD6Bh7FCGSCySxXy/ewzobJRZccmUYtex5myIMrnWxxzCv6L2/u8hLiQntf91f/T371T89MSAuB@kSx1SEodscSsUF1hohetCWrO73jK11YmWooEzVFDyqTk1CVaiZpDwGw@DWpQMOJz3sA9vzS8 "Python 3.8 (pre-release) – Try It Online") [Answer] # JavaScript (ES6), 50 bytes ``` f=([v,...a],p,s=0)=>v?(s+=v)<p?f(a,p,s):1+f(a,s):0 ``` [Try it online!](https://tio.run/##XYo7CoAwEAV7T7KLa/BfiNGDiEVQI4qYYCTXj5vW4sHwZk7llVuew77ZbdYtBC1h8iSEUDNZcjJHOfgRXCo99nbUoOKNXZFGZMjDYm5nrk1cZgcNU0MlVVTwaqZmRkx@Rc02Ni21bMMH "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: [ v, // v = next entry in the input array ...a ], // a[] = all remaining entries in the input array p, // p = previous donation, initially undefined s = 0 // s = current donation ) => // v ? // if v is defined: (s += v) // add v to s < p ? // if the result is less than the previous donation: f(a, p, s) // do a recursive call with the updated s : // else: 1 + // increment the final result f(a, s) // do a recursive call with p = s (and s = 0, implicitly) : // else: 0 // stop recursion ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖ§ṢƑƇḢL ``` A monadic Link accepting a list of numbers which yields a non-negative integer. **[Try it online!](https://tio.run/##y0rNyan8///opIc7px1a/nDnomMTj7U/3LHI5////9GmOgpGOgrGOgqGYNIEzDWNBQA "Jelly – Try It Online")** (not efficient) ### How? ``` ŒṖ§ṢƑƇḢL - Link: list ŒṖ - all partitions (order is such that those with shorter sublists at the left appear first) § - sums (sum each part of each partition) Ƈ - filter keep those for which: Ƒ - is invariant under: Ṣ - sort Ḣ - head L - length ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` lesDI#./ ``` [Try it online!](https://tio.run/##K6gsyfj/Pye12MVTWU////9oEx1DHSMdYx0zHbNYAA "Pyth – Try It Online") Form all ordered partitions `./`, then filter `#` for the partitions which are invariant `I` under sorting `D` by sum `s`. Take the last one the survived the filler `e`, which is also the longest due to the order that `./` outputs partitions, and return its length `l`. This is one of the longest string of prefix modifiers (`DI#`) I've ever used, it's a challenge that fits Pyth quite well. [Answer] # [Python 2](https://docs.python.org/2/), ~~64~~ 62 bytes ``` f=lambda l,p=1,c=0:c/p and-~f(l,c)or l>[]and f(l[1:],p,c+l[0]) ``` [Try it online!](https://tio.run/##LY/BjoMgFEX3fsWLs4GIndraWZjgjxgXDGpKikiApulmft25OBNC8jj3vAf4d7pv7rLvi7Rq/Z4UWeFlI7Q8d/rTk3JT/bMwKzTfAtl@GEEIYGi6UXihKzucR76b1W8hUXzHoliyadxMxmVwimkyriuIPijMagL2z4RjFBgfSdKqPIspQAzGi6P3FL01iZV1X3IO10KzJiaWXeOSoPiv8CP/G4SAoeLHXfo@60cOXnMACMjx7pz5ABEfpTxeUEAxlBVuZ0HK3F@VY7m3VPfUFDe60JUa7BbVLcNr0QJk/IUF0P4C "Python 2 – Try It Online") A recursive function that takes in a list of integers and returns the number of barfoos. **How**: `p` and `c` keeps track of the previous donation and the current donation. If the current donation is sufficient, moves to a new barfoo. Otherwise, adds another cause to the current donation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` .œ.ΔOD{Q}g ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f7@hkvXNT/F2qA2vT//@PNtVRMNJRMNZRMASTJmCuaSwA "05AB1E – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 56 bytes Similar to [my JS answer](https://codegolf.stackexchange.com/a/204009/58563), but with \$p\$ and \$s\$ declared in the global scope. They are reset to \$0\$ on the last iteration to make sure that the function is [reusable](https://codegolf.meta.stackexchange.com/a/4940/58563). Takes a zero-terminated array of integers as input. ``` p,s;f(int*a){a=!*a?p=s=0:!((s+=*a++)>=p?s-=p=s:1)+f(a);} ``` [Try it online!](https://tio.run/##Nc3BCsIwDAbgu0@RDQbN2kGr08NK3YOoh9CxMdBZrOhh7NWtpU4ICfn5SGw1WBuCE173bJyeJeFMJiupdcYb2WSMeW5K4hyPxrW@MjFvFPKeEeolvO5jBzcaJ4YwbwDiCSB5uoCBGfYCtgJ2AlTqdVpjKGHRf6tWWyf144dUq3KP6HqWF915KrpcQPwsMQ2FqDdL@Nj@SoMP1fsL "C (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 60 bytes Port of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [Python answer](https://codegolf.stackexchange.com/a/203996/9481). ``` n;m;s;f(int*l){for(n=m=s=0;*l;s=s<1?++n,m-=s:s)s-=*l++;s=n;} ``` [Try it online!](https://tio.run/##bYzLCsIwEEX3/YqhIORVamx14Tj4IepCKpFCM0rTXem3x5i6FIYLcy/ndNWz62Jk9BjQiZ4nNcjZvUbB5CnQFtWAgcLJnrVm4ysKxyBDRWrQOg2MS/T3noWciwTDdLkBwbw3sDPQGLA52/ymcrsg1AoaUHXxHhPgRLl5XLk04MQkJa4Su1razK@iQ74f3/7n7VewxA8 "C (gcc) – Try It Online") Inputs a zero-terminated integer array. [Answer] # [PHP](https://php.net/), 62 bytes ``` for(;$a=$argv[++$i];)if(($s+=$a)>=$t){$r++;$t=$s;$s=0;}echo$r; ``` [Try it online!](https://tio.run/##pY5NCsIwEIX3PUUoA21JEPvnwjF6geLOVdtFqakNaBPSIoJ49jj1CsLMe4/h8TF2tP5wsqSDcTFCJ6Fzt2fNOegWEz3EMcycjslRwpK8wXGOsEiYEWa5xY/qRwMO/eosbKZmUq/uYe@KZftmCjH48WQd9eaqNos2kWCFYKlgmWC5YDuallqakHIFO3m@VBUGf/7jS5/53Ke0BaXyCw "PHP – Try It Online") Pretty straightforward implementation, saying that "s" is for "sum", "t" for "total" and "r" for "result" should be enough ;) [Answer] # [C#], 108 bytes ``` f=(i,c,p,s,q)=>{y=c;if(i==L.Length)return;var t=L[i++];p=i==0?t:p;q=s+t>=p;f(i,q?++c:c,q?s+t:p,q?0:s+t,q);}; ``` [Try It online!](https://tio.run/##VY/BboMwDIbvPIWFdgCRItq1O5CFatpt4rbDDlUPXRTaSCgJSdiEEM/ODHRVK1n2H@v77Zi7FXdy/DlZkMq0fg0MlPg9HKGHHYENgWcC6zlv5@cOBhrc8M0dvp3BxfGC8QC6O3BZRP4nXLEOiYzCJEuUC0SDN@6lVq9S@cnwkL61rguopsltXdOxYpEknBjiSBOzou8Yp7KKJGNlWgp19pfYCt9aRaclnpUHmSRHahgS2d7nhjbMJb5ghqKLNPsk4TnHis3cYM1yVDibDrhMW3Hil2i@EP9zPTOGPoDlAIqiijICt6hOtRPx1H/XyulapF9WelFKJaKnsP/0Vqpz@qGlikISkjIeYFVA3w0hmobxDw) Very verbose recursion implementation, but I'm proud of this ugly baby. Call function with ever greater sum of donations until donation is equal to or greater then increment a counter, and set sum to 0. Increase index (to loop through donations). Return when index is equal to length of donations. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` ≔⁰ηWΦEθ…θ⊕묋Σκη«⊞υω≔Σ§ι⁰η≔✂θL§ι⁰Lθ¹θ»ILυ ``` [Try it online!](https://tio.run/##ZU5NC8IwDD27X5FjChX8PHkaA0GYMvAoO4wa1mLXubXzA/G3124OLwYSkryXvCdk0Yq60N7H1qrS4IyDZJvoLpUmwK3SjlrcF1dsOCRPoSmR9TDsjGipIuPojJoxxuFQO0zJWjx2FV5Y/ygEvKJJ1lmJHYd7@DwZhXpS7HbmTA9UHGaMfZV/uFaCeqGUTOnkH3dcN6Gdh2zC6TvKWmUcJoXtnQx4FyxsvD@d1hwWHJaBPdTVMK7z3E9v@gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁰η ``` Start off with no resources. ``` WΦEθ…θ⊕묋Σκη« ``` Find out which prefixes of the remaining list contain as least as many resources as the last donation. ``` ⊞υω ``` Keep track of how many times a donation was found. ``` ≔Σ§ι⁰η ``` Calculate the minimum donation for next time. ``` ≔✂θL§ι⁰Lθ¹θ ``` Remove the recommendations that were donated. ``` »ILυ ``` Print the count of donations. [Answer] # [Io](http://iolanguage.org/), 72 bytes Port of xnor's Python solution. ``` method(I,d :=p :=t :=0;I foreach(x,d=d-x;if(d<1,t=t+1;p=d=p-d))return t) ``` [Try it online!](https://tio.run/##bYzBCsIwEETvfsUeE9yCqa0HYz6g/@BF3IQGahrSFfr3MaQeRF1mBoZ9jJ@zg7OBa35YHmcSA1LpsZiLD3oANyd7u49iRTLUrNo7QReFbHivdDRkYkNSJsvPFIBldmLyC4seoUU4IqiaXa29lBCTDzyF3ZvrKrGhp6JCbPfFqcr91@9qWyc/HvkF "Io – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 35 + 1 bytes ``` $d-=$_;if($d<1){$\++;$p=$d=$p-$d}}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRddWJd46M01DJcXGULNaJUZb21qlwFYlxValQFclpba2@v9/Uy4jLmMuQyA2AbJMuf7lF5Rk5ucV/9ctAAA "Perl 5 – Try It Online") I counted one additional byte for replacing the standard command-line switch `-e` by `-pe`. This program reads the list of causes from its standard input, one amount per line. When there is nothing left to read, it prints the number of civilian barfoos who donated something. This is a port of xnor's Python2 solution with a few Perl golfing tricks thrown in. I use the following variables: `$\` tracks the number of barfoos who have successfully donated, `$p` tracks the previous donation, and `$d` tracks the amount that the current barfoo still needs to donate to catch up with the previous donation. ### Slightly more natural, 36 + 1 bytes ``` $s+=$_;if($s>=$p){$\++;$p=$s;$s=0}}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lWNtWJd46M01DpdjOVqVAs1olRlvbWqXAVqXYWqXY1qC2tvr/f1MuIy5jLkMgNgGyTLn@5ReUZObnFf/XLQAA "Perl 5 – Try It Online") In this version, `$s` counts the sum of what the current barfoo is trying to donate instead of tracking what is still missing (as done with `$d` above). ### Ungolfed and commented The implementation is simple but it uses a few [well-known](https://codegolf.stackexchange.com/questions/5105/tips-for-golfing-in-perl/32884#32884) Perl golfing tips: * The `-p` switch wraps `while (<>) { ... ; print }` around the program but it does so literally, in a way that allows unmatched curly braces in the code to match those that are added by the wrapper. So `perl -p 'foo}{bar'` becomes `while (<>) { foo } { bar ; print }`. In this codegolf entry, I have an empty `bar` (which is kind of sad, but this is another topic). * The special variable `$\` is the output record separator for the print operator. Using `print` without arguments would print `$_` followed by `$\`, but `$_` is undefined at the end of the `while` loop, so assigning a value to `$\` is a convenient way to print something at the end of the program. * Incrementing an undefined variable sets its value to 1. `$\` is undefined by default. To make the ungolfed code more readable and to make it easier to understand what is printed, here I use a variable `$t` for counting the number of successful donations instead of using the output record separator `$\`. The natural version of the code would look like this: ``` while (<>) { # Read all input lines (one amount per line). $s += $_; # Add the amount for the current cause to $s. if ($s >= $p) { # If we can match or exceed the last donation, $t++; # then count it and invite the next barfoo. $p = $s; $s = 0; } } # When we reach the end of the input, print $t; # print the number of barfoos who donated. ``` ...and the slightly optimized version would look like this: ``` while (<>) { # Read all input lines (one amount per line). $d -= $_; # Subtract the amount from what we need to catch up. if ($d < 1) { # If the difference from the last donation is 0 or lower, $t++; # then count it and invite the next barfoo. $d = $p - $d; $p = $d; } } # When we reach the end of the input, print $t; # print the number of barfoos who donated. ``` [Answer] # MMIX, 52 bytes (13 instrs) Takes pointer to sequence of 16-bit integers as sole argument, sequence terminated by a 0. (jelly xxd) ``` 00000000: e301 0000 e302 0000 e303 0000 87ff 0000 ẉ¢¡¡ẉ£¡¡ẉ¤¡¡⁷”¡¡ 00000010: 42ff 0008 e700 0002 2002 02ff 5102 fffc B”¡®ḃ¡¡£ ££”Q£”‘ 00000020: 2003 0302 3402 0003 e701 0001 f1ff fff8 ¤¤£4£¡¤ḃ¢¡¢ȯ””ẏ 00000030: f802 0000 ẏ£¡¡ ``` **Disassembly and explanation** ``` charity SETL $1,0 // ndonors = 0 SETL $2,0 // amtleft = 0 SETL $3,0 // prevdonor = 0 0H LDWU $255,$0,0 // loop: amt = *causes (causes is const uint16_t *) BZ $255,0F // if(!amt) goto end INCL $0,2 // causes++ ADD $2,$2,$255 // amtleft += amt PBN $2,0B // iflikely(amtleft < 0) goto loop ADD $3,$3,$2 // prevdonor += amtleft NEG $2,0,$3 // amtleft = -prevdonor INCL $1,1 // ndonors++ JMP 0B // goto loop 0H POP 2,0 // end: return ndonors ``` ]
[Question] [ This challenge is about the number of orderings which contain at most \$n\$ classes and at most \$k\$ of the \$k^{\text{th}}\$ class. One way to represent such an ordering is as a sequence of positive integers with these three restrictions: 1. A number may only appear after all lower numbers have appeared 2. All numbers which appear must be less than or equal to \$n\$ 3. Any number may only appear up to as many times as its own value As such the number of such sequences is itself a sequence, \$a(n)\$ where: \$a(0) = 1\$, since only the empty sequence, `[]`, works; \$a(1) = 2\$, since `[1]` now also works; \$a(2) = 4\$, since both `[1, 2]` and `[1, 2, 2]` also work\*; \$a(3) = 16\$: ``` [], [1], [1, 2], [1, 2, 2], [1, 2, 3], [1, 2, 2, 3], [1, 2, 3, 2], [1, 2, 3, 3], [1, 2, 2, 3, 3], [1, 2, 3, 2, 3], [1, 2, 3, 3, 2], [1, 2, 3, 3, 3], [1, 2, 2, 3, 3, 3], [1, 2, 3, 2, 3, 3], [1, 2, 3, 3, 2, 3], [1, 2, 3, 3, 3, 2] ``` \$a(4) = 409\$: ``` [], [1], [1, 2], [1, 2, 2], [1, 2, 3], [1, 2, 2, 3], [1, 2, 3, 2], [1, 2, 3, 3], [1, 2, 3, 4], [1, 2, 2, 3, 3], [1, 2, 2, 3, 4], [1, 2, 3, 2, 3], [1, 2, 3, 2, 4], [1, 2, 3, 3, 2], [1, 2, 3, 3, 3], [1, 2, 3, 3, 4], [1, 2, 3, 4, 2], [1, 2, 3, 4, 3], [1, 2, 3, 4, 4], [1, 2, 2, 3, 3, 3], [1, 2, 2, 3, 3, 4], [1, 2, 2, 3, 4, 3], [1, 2, 2, 3, 4, 4], [1, 2, 3, 2, 3, 3], [1, 2, 3, 2, 3, 4], [1, 2, 3, 2, 4, 3], [1, 2, 3, 2, 4, 4], [1, 2, 3, 3, 2, 3], [1, 2, 3, 3, 2, 4], [1, 2, 3, 3, 3, 2], [1, 2, 3, 3, 3, 4], [1, 2, 3, 3, 4, 2], [1, 2, 3, 3, 4, 3], [1, 2, 3, 3, 4, 4], [1, 2, 3, 4, 2, 3], [1, 2, 3, 4, 2, 4], [1, 2, 3, 4, 3, 2], [1, 2, 3, 4, 3, 3], [1, 2, 3, 4, 3, 4], [1, 2, 3, 4, 4, 2], [1, 2, 3, 4, 4, 3], [1, 2, 3, 4, 4, 4], [1, 2, 2, 3, 3, 3, 4], [1, 2, 2, 3, 3, 4, 3], [1, 2, 2, 3, 3, 4, 4], [1, 2, 2, 3, 4, 3, 3], [1, 2, 2, 3, 4, 3, 4], [1, 2, 2, 3, 4, 4, 3], [1, 2, 2, 3, 4, 4, 4], [1, 2, 3, 2, 3, 3, 4], [1, 2, 3, 2, 3, 4, 3], [1, 2, 3, 2, 3, 4, 4], [1, 2, 3, 2, 4, 3, 3], [1, 2, 3, 2, 4, 3, 4], [1, 2, 3, 2, 4, 4, 3], [1, 2, 3, 2, 4, 4, 4], [1, 2, 3, 3, 2, 3, 4], [1, 2, 3, 3, 2, 4, 3], [1, 2, 3, 3, 2, 4, 4], [1, 2, 3, 3, 3, 2, 4], [1, 2, 3, 3, 3, 4, 2], [1, 2, 3, 3, 3, 4, 4], [1, 2, 3, 3, 4, 2, 3], [1, 2, 3, 3, 4, 2, 4], [1, 2, 3, 3, 4, 3, 2], [1, 2, 3, 3, 4, 3, 4], [1, 2, 3, 3, 4, 4, 2], [1, 2, 3, 3, 4, 4, 3], [1, 2, 3, 3, 4, 4, 4], [1, 2, 3, 4, 2, 3, 3], [1, 2, 3, 4, 2, 3, 4], [1, 2, 3, 4, 2, 4, 3], [1, 2, 3, 4, 2, 4, 4], [1, 2, 3, 4, 3, 2, 3], [1, 2, 3, 4, 3, 2, 4], [1, 2, 3, 4, 3, 3, 2], [1, 2, 3, 4, 3, 3, 4], [1, 2, 3, 4, 3, 4, 2], [1, 2, 3, 4, 3, 4, 3], [1, 2, 3, 4, 3, 4, 4], [1, 2, 3, 4, 4, 2, 3], [1, 2, 3, 4, 4, 2, 4], [1, 2, 3, 4, 4, 3, 2], [1, 2, 3, 4, 4, 3, 3], [1, 2, 3, 4, 4, 3, 4], [1, 2, 3, 4, 4, 4, 2], [1, 2, 3, 4, 4, 4, 3], [1, 2, 3, 4, 4, 4, 4], [1, 2, 2, 3, 3, 3, 4, 4], [1, 2, 2, 3, 3, 4, 3, 4], [1, 2, 2, 3, 3, 4, 4, 3], [1, 2, 2, 3, 3, 4, 4, 4], [1, 2, 2, 3, 4, 3, 3, 4], [1, 2, 2, 3, 4, 3, 4, 3], [1, 2, 2, 3, 4, 3, 4, 4], [1, 2, 2, 3, 4, 4, 3, 3], [1, 2, 2, 3, 4, 4, 3, 4], [1, 2, 2, 3, 4, 4, 4, 3], [1, 2, 2, 3, 4, 4, 4, 4], [1, 2, 3, 2, 3, 3, 4, 4], [1, 2, 3, 2, 3, 4, 3, 4], [1, 2, 3, 2, 3, 4, 4, 3], [1, 2, 3, 2, 3, 4, 4, 4], [1, 2, 3, 2, 4, 3, 3, 4], [1, 2, 3, 2, 4, 3, 4, 3], [1, 2, 3, 2, 4, 3, 4, 4], [1, 2, 3, 2, 4, 4, 3, 3], [1, 2, 3, 2, 4, 4, 3, 4], [1, 2, 3, 2, 4, 4, 4, 3], [1, 2, 3, 2, 4, 4, 4, 4], [1, 2, 3, 3, 2, 3, 4, 4], [1, 2, 3, 3, 2, 4, 3, 4], [1, 2, 3, 3, 2, 4, 4, 3], [1, 2, 3, 3, 2, 4, 4, 4], [1, 2, 3, 3, 3, 2, 4, 4], [1, 2, 3, 3, 3, 4, 2, 4], [1, 2, 3, 3, 3, 4, 4, 2], [1, 2, 3, 3, 3, 4, 4, 4], [1, 2, 3, 3, 4, 2, 3, 4], [1, 2, 3, 3, 4, 2, 4, 3], [1, 2, 3, 3, 4, 2, 4, 4], [1, 2, 3, 3, 4, 3, 2, 4], [1, 2, 3, 3, 4, 3, 4, 2], [1, 2, 3, 3, 4, 3, 4, 4], [1, 2, 3, 3, 4, 4, 2, 3], [1, 2, 3, 3, 4, 4, 2, 4], [1, 2, 3, 3, 4, 4, 3, 2], [1, 2, 3, 3, 4, 4, 3, 4], [1, 2, 3, 3, 4, 4, 4, 2], [1, 2, 3, 3, 4, 4, 4, 3], [1, 2, 3, 3, 4, 4, 4, 4], [1, 2, 3, 4, 2, 3, 3, 4], [1, 2, 3, 4, 2, 3, 4, 3], [1, 2, 3, 4, 2, 3, 4, 4], [1, 2, 3, 4, 2, 4, 3, 3], [1, 2, 3, 4, 2, 4, 3, 4], [1, 2, 3, 4, 2, 4, 4, 3], [1, 2, 3, 4, 2, 4, 4, 4], [1, 2, 3, 4, 3, 2, 3, 4], [1, 2, 3, 4, 3, 2, 4, 3], [1, 2, 3, 4, 3, 2, 4, 4], [1, 2, 3, 4, 3, 3, 2, 4], [1, 2, 3, 4, 3, 3, 4, 2], [1, 2, 3, 4, 3, 3, 4, 4], [1, 2, 3, 4, 3, 4, 2, 3], [1, 2, 3, 4, 3, 4, 2, 4], [1, 2, 3, 4, 3, 4, 3, 2], [1, 2, 3, 4, 3, 4, 3, 4], [1, 2, 3, 4, 3, 4, 4, 2], [1, 2, 3, 4, 3, 4, 4, 3], [1, 2, 3, 4, 3, 4, 4, 4], [1, 2, 3, 4, 4, 2, 3, 3], [1, 2, 3, 4, 4, 2, 3, 4], [1, 2, 3, 4, 4, 2, 4, 3], [1, 2, 3, 4, 4, 2, 4, 4], [1, 2, 3, 4, 4, 3, 2, 3], [1, 2, 3, 4, 4, 3, 2, 4], [1, 2, 3, 4, 4, 3, 3, 2], [1, 2, 3, 4, 4, 3, 3, 4], [1, 2, 3, 4, 4, 3, 4, 2], [1, 2, 3, 4, 4, 3, 4, 3], [1, 2, 3, 4, 4, 3, 4, 4], [1, 2, 3, 4, 4, 4, 2, 3], [1, 2, 3, 4, 4, 4, 2, 4], [1, 2, 3, 4, 4, 4, 3, 2], [1, 2, 3, 4, 4, 4, 3, 3], [1, 2, 3, 4, 4, 4, 3, 4], [1, 2, 3, 4, 4, 4, 4, 2], [1, 2, 3, 4, 4, 4, 4, 3], [1, 2, 2, 3, 3, 3, 4, 4, 4], [1, 2, 2, 3, 3, 4, 3, 4, 4], [1, 2, 2, 3, 3, 4, 4, 3, 4], [1, 2, 2, 3, 3, 4, 4, 4, 3], [1, 2, 2, 3, 3, 4, 4, 4, 4], [1, 2, 2, 3, 4, 3, 3, 4, 4], [1, 2, 2, 3, 4, 3, 4, 3, 4], [1, 2, 2, 3, 4, 3, 4, 4, 3], [1, 2, 2, 3, 4, 3, 4, 4, 4], [1, 2, 2, 3, 4, 4, 3, 3, 4], [1, 2, 2, 3, 4, 4, 3, 4, 3], [1, 2, 2, 3, 4, 4, 3, 4, 4], [1, 2, 2, 3, 4, 4, 4, 3, 3], [1, 2, 2, 3, 4, 4, 4, 3, 4], [1, 2, 2, 3, 4, 4, 4, 4, 3], [1, 2, 3, 2, 3, 3, 4, 4, 4], [1, 2, 3, 2, 3, 4, 3, 4, 4], [1, 2, 3, 2, 3, 4, 4, 3, 4], [1, 2, 3, 2, 3, 4, 4, 4, 3], [1, 2, 3, 2, 3, 4, 4, 4, 4], [1, 2, 3, 2, 4, 3, 3, 4, 4], [1, 2, 3, 2, 4, 3, 4, 3, 4], [1, 2, 3, 2, 4, 3, 4, 4, 3], [1, 2, 3, 2, 4, 3, 4, 4, 4], [1, 2, 3, 2, 4, 4, 3, 3, 4], [1, 2, 3, 2, 4, 4, 3, 4, 3], [1, 2, 3, 2, 4, 4, 3, 4, 4], [1, 2, 3, 2, 4, 4, 4, 3, 3], [1, 2, 3, 2, 4, 4, 4, 3, 4], [1, 2, 3, 2, 4, 4, 4, 4, 3], [1, 2, 3, 3, 2, 3, 4, 4, 4], [1, 2, 3, 3, 2, 4, 3, 4, 4], [1, 2, 3, 3, 2, 4, 4, 3, 4], [1, 2, 3, 3, 2, 4, 4, 4, 3], [1, 2, 3, 3, 2, 4, 4, 4, 4], [1, 2, 3, 3, 3, 2, 4, 4, 4], [1, 2, 3, 3, 3, 4, 2, 4, 4], [1, 2, 3, 3, 3, 4, 4, 2, 4], [1, 2, 3, 3, 3, 4, 4, 4, 2], [1, 2, 3, 3, 3, 4, 4, 4, 4], [1, 2, 3, 3, 4, 2, 3, 4, 4], [1, 2, 3, 3, 4, 2, 4, 3, 4], [1, 2, 3, 3, 4, 2, 4, 4, 3], [1, 2, 3, 3, 4, 2, 4, 4, 4], [1, 2, 3, 3, 4, 3, 2, 4, 4], [1, 2, 3, 3, 4, 3, 4, 2, 4], [1, 2, 3, 3, 4, 3, 4, 4, 2], [1, 2, 3, 3, 4, 3, 4, 4, 4], [1, 2, 3, 3, 4, 4, 2, 3, 4], [1, 2, 3, 3, 4, 4, 2, 4, 3], [1, 2, 3, 3, 4, 4, 2, 4, 4], [1, 2, 3, 3, 4, 4, 3, 2, 4], [1, 2, 3, 3, 4, 4, 3, 4, 2], [1, 2, 3, 3, 4, 4, 3, 4, 4], [1, 2, 3, 3, 4, 4, 4, 2, 3], [1, 2, 3, 3, 4, 4, 4, 2, 4], [1, 2, 3, 3, 4, 4, 4, 3, 2], [1, 2, 3, 3, 4, 4, 4, 3, 4], [1, 2, 3, 3, 4, 4, 4, 4, 2], [1, 2, 3, 3, 4, 4, 4, 4, 3], [1, 2, 3, 4, 2, 3, 3, 4, 4], [1, 2, 3, 4, 2, 3, 4, 3, 4], [1, 2, 3, 4, 2, 3, 4, 4, 3], [1, 2, 3, 4, 2, 3, 4, 4, 4], [1, 2, 3, 4, 2, 4, 3, 3, 4], [1, 2, 3, 4, 2, 4, 3, 4, 3], [1, 2, 3, 4, 2, 4, 3, 4, 4], [1, 2, 3, 4, 2, 4, 4, 3, 3], [1, 2, 3, 4, 2, 4, 4, 3, 4], [1, 2, 3, 4, 2, 4, 4, 4, 3], [1, 2, 3, 4, 3, 2, 3, 4, 4], [1, 2, 3, 4, 3, 2, 4, 3, 4], [1, 2, 3, 4, 3, 2, 4, 4, 3], [1, 2, 3, 4, 3, 2, 4, 4, 4], [1, 2, 3, 4, 3, 3, 2, 4, 4], [1, 2, 3, 4, 3, 3, 4, 2, 4], [1, 2, 3, 4, 3, 3, 4, 4, 2], [1, 2, 3, 4, 3, 3, 4, 4, 4], [1, 2, 3, 4, 3, 4, 2, 3, 4], [1, 2, 3, 4, 3, 4, 2, 4, 3], [1, 2, 3, 4, 3, 4, 2, 4, 4], [1, 2, 3, 4, 3, 4, 3, 2, 4], [1, 2, 3, 4, 3, 4, 3, 4, 2], [1, 2, 3, 4, 3, 4, 3, 4, 4], [1, 2, 3, 4, 3, 4, 4, 2, 3], [1, 2, 3, 4, 3, 4, 4, 2, 4], [1, 2, 3, 4, 3, 4, 4, 3, 2], [1, 2, 3, 4, 3, 4, 4, 3, 4], [1, 2, 3, 4, 3, 4, 4, 4, 2], [1, 2, 3, 4, 3, 4, 4, 4, 3], [1, 2, 3, 4, 4, 2, 3, 3, 4], [1, 2, 3, 4, 4, 2, 3, 4, 3], [1, 2, 3, 4, 4, 2, 3, 4, 4], [1, 2, 3, 4, 4, 2, 4, 3, 3], [1, 2, 3, 4, 4, 2, 4, 3, 4], [1, 2, 3, 4, 4, 2, 4, 4, 3], [1, 2, 3, 4, 4, 3, 2, 3, 4], [1, 2, 3, 4, 4, 3, 2, 4, 3], [1, 2, 3, 4, 4, 3, 2, 4, 4], [1, 2, 3, 4, 4, 3, 3, 2, 4], [1, 2, 3, 4, 4, 3, 3, 4, 2], [1, 2, 3, 4, 4, 3, 3, 4, 4], [1, 2, 3, 4, 4, 3, 4, 2, 3], [1, 2, 3, 4, 4, 3, 4, 2, 4], [1, 2, 3, 4, 4, 3, 4, 3, 2], [1, 2, 3, 4, 4, 3, 4, 3, 4], [1, 2, 3, 4, 4, 3, 4, 4, 2], [1, 2, 3, 4, 4, 3, 4, 4, 3], [1, 2, 3, 4, 4, 4, 2, 3, 3], [1, 2, 3, 4, 4, 4, 2, 3, 4], [1, 2, 3, 4, 4, 4, 2, 4, 3], [1, 2, 3, 4, 4, 4, 3, 2, 3], [1, 2, 3, 4, 4, 4, 3, 2, 4], [1, 2, 3, 4, 4, 4, 3, 3, 2], [1, 2, 3, 4, 4, 4, 3, 3, 4], [1, 2, 3, 4, 4, 4, 3, 4, 2], [1, 2, 3, 4, 4, 4, 3, 4, 3], [1, 2, 3, 4, 4, 4, 4, 2, 3], [1, 2, 3, 4, 4, 4, 4, 3, 2], [1, 2, 3, 4, 4, 4, 4, 3, 3], [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], [1, 2, 2, 3, 3, 4, 3, 4, 4, 4], [1, 2, 2, 3, 3, 4, 4, 3, 4, 4], [1, 2, 2, 3, 3, 4, 4, 4, 3, 4], [1, 2, 2, 3, 3, 4, 4, 4, 4, 3], [1, 2, 2, 3, 4, 3, 3, 4, 4, 4], [1, 2, 2, 3, 4, 3, 4, 3, 4, 4], [1, 2, 2, 3, 4, 3, 4, 4, 3, 4], [1, 2, 2, 3, 4, 3, 4, 4, 4, 3], [1, 2, 2, 3, 4, 4, 3, 3, 4, 4], [1, 2, 2, 3, 4, 4, 3, 4, 3, 4], [1, 2, 2, 3, 4, 4, 3, 4, 4, 3], [1, 2, 2, 3, 4, 4, 4, 3, 3, 4], [1, 2, 2, 3, 4, 4, 4, 3, 4, 3], [1, 2, 2, 3, 4, 4, 4, 4, 3, 3], [1, 2, 3, 2, 3, 3, 4, 4, 4, 4], [1, 2, 3, 2, 3, 4, 3, 4, 4, 4], [1, 2, 3, 2, 3, 4, 4, 3, 4, 4], [1, 2, 3, 2, 3, 4, 4, 4, 3, 4], [1, 2, 3, 2, 3, 4, 4, 4, 4, 3], [1, 2, 3, 2, 4, 3, 3, 4, 4, 4], [1, 2, 3, 2, 4, 3, 4, 3, 4, 4], [1, 2, 3, 2, 4, 3, 4, 4, 3, 4], [1, 2, 3, 2, 4, 3, 4, 4, 4, 3], [1, 2, 3, 2, 4, 4, 3, 3, 4, 4], [1, 2, 3, 2, 4, 4, 3, 4, 3, 4], [1, 2, 3, 2, 4, 4, 3, 4, 4, 3], [1, 2, 3, 2, 4, 4, 4, 3, 3, 4], [1, 2, 3, 2, 4, 4, 4, 3, 4, 3], [1, 2, 3, 2, 4, 4, 4, 4, 3, 3], [1, 2, 3, 3, 2, 3, 4, 4, 4, 4], [1, 2, 3, 3, 2, 4, 3, 4, 4, 4], [1, 2, 3, 3, 2, 4, 4, 3, 4, 4], [1, 2, 3, 3, 2, 4, 4, 4, 3, 4], [1, 2, 3, 3, 2, 4, 4, 4, 4, 3], [1, 2, 3, 3, 3, 2, 4, 4, 4, 4], [1, 2, 3, 3, 3, 4, 2, 4, 4, 4], [1, 2, 3, 3, 3, 4, 4, 2, 4, 4], [1, 2, 3, 3, 3, 4, 4, 4, 2, 4], [1, 2, 3, 3, 3, 4, 4, 4, 4, 2], [1, 2, 3, 3, 4, 2, 3, 4, 4, 4], [1, 2, 3, 3, 4, 2, 4, 3, 4, 4], [1, 2, 3, 3, 4, 2, 4, 4, 3, 4], [1, 2, 3, 3, 4, 2, 4, 4, 4, 3], [1, 2, 3, 3, 4, 3, 2, 4, 4, 4], [1, 2, 3, 3, 4, 3, 4, 2, 4, 4], [1, 2, 3, 3, 4, 3, 4, 4, 2, 4], [1, 2, 3, 3, 4, 3, 4, 4, 4, 2], [1, 2, 3, 3, 4, 4, 2, 3, 4, 4], [1, 2, 3, 3, 4, 4, 2, 4, 3, 4], [1, 2, 3, 3, 4, 4, 2, 4, 4, 3], [1, 2, 3, 3, 4, 4, 3, 2, 4, 4], [1, 2, 3, 3, 4, 4, 3, 4, 2, 4], [1, 2, 3, 3, 4, 4, 3, 4, 4, 2], [1, 2, 3, 3, 4, 4, 4, 2, 3, 4], [1, 2, 3, 3, 4, 4, 4, 2, 4, 3], [1, 2, 3, 3, 4, 4, 4, 3, 2, 4], [1, 2, 3, 3, 4, 4, 4, 3, 4, 2], [1, 2, 3, 3, 4, 4, 4, 4, 2, 3], [1, 2, 3, 3, 4, 4, 4, 4, 3, 2], [1, 2, 3, 4, 2, 3, 3, 4, 4, 4], [1, 2, 3, 4, 2, 3, 4, 3, 4, 4], [1, 2, 3, 4, 2, 3, 4, 4, 3, 4], [1, 2, 3, 4, 2, 3, 4, 4, 4, 3], [1, 2, 3, 4, 2, 4, 3, 3, 4, 4], [1, 2, 3, 4, 2, 4, 3, 4, 3, 4], [1, 2, 3, 4, 2, 4, 3, 4, 4, 3], [1, 2, 3, 4, 2, 4, 4, 3, 3, 4], [1, 2, 3, 4, 2, 4, 4, 3, 4, 3], [1, 2, 3, 4, 2, 4, 4, 4, 3, 3], [1, 2, 3, 4, 3, 2, 3, 4, 4, 4], [1, 2, 3, 4, 3, 2, 4, 3, 4, 4], [1, 2, 3, 4, 3, 2, 4, 4, 3, 4], [1, 2, 3, 4, 3, 2, 4, 4, 4, 3], [1, 2, 3, 4, 3, 3, 2, 4, 4, 4], [1, 2, 3, 4, 3, 3, 4, 2, 4, 4], [1, 2, 3, 4, 3, 3, 4, 4, 2, 4], [1, 2, 3, 4, 3, 3, 4, 4, 4, 2], [1, 2, 3, 4, 3, 4, 2, 3, 4, 4], [1, 2, 3, 4, 3, 4, 2, 4, 3, 4], [1, 2, 3, 4, 3, 4, 2, 4, 4, 3], [1, 2, 3, 4, 3, 4, 3, 2, 4, 4], [1, 2, 3, 4, 3, 4, 3, 4, 2, 4], [1, 2, 3, 4, 3, 4, 3, 4, 4, 2], [1, 2, 3, 4, 3, 4, 4, 2, 3, 4], [1, 2, 3, 4, 3, 4, 4, 2, 4, 3], [1, 2, 3, 4, 3, 4, 4, 3, 2, 4], [1, 2, 3, 4, 3, 4, 4, 3, 4, 2], [1, 2, 3, 4, 3, 4, 4, 4, 2, 3], [1, 2, 3, 4, 3, 4, 4, 4, 3, 2], [1, 2, 3, 4, 4, 2, 3, 3, 4, 4], [1, 2, 3, 4, 4, 2, 3, 4, 3, 4], [1, 2, 3, 4, 4, 2, 3, 4, 4, 3], [1, 2, 3, 4, 4, 2, 4, 3, 3, 4], [1, 2, 3, 4, 4, 2, 4, 3, 4, 3], [1, 2, 3, 4, 4, 2, 4, 4, 3, 3], [1, 2, 3, 4, 4, 3, 2, 3, 4, 4], [1, 2, 3, 4, 4, 3, 2, 4, 3, 4], [1, 2, 3, 4, 4, 3, 2, 4, 4, 3], [1, 2, 3, 4, 4, 3, 3, 2, 4, 4], [1, 2, 3, 4, 4, 3, 3, 4, 2, 4], [1, 2, 3, 4, 4, 3, 3, 4, 4, 2], [1, 2, 3, 4, 4, 3, 4, 2, 3, 4], [1, 2, 3, 4, 4, 3, 4, 2, 4, 3], [1, 2, 3, 4, 4, 3, 4, 3, 2, 4], [1, 2, 3, 4, 4, 3, 4, 3, 4, 2], [1, 2, 3, 4, 4, 3, 4, 4, 2, 3], [1, 2, 3, 4, 4, 3, 4, 4, 3, 2], [1, 2, 3, 4, 4, 4, 2, 3, 3, 4], [1, 2, 3, 4, 4, 4, 2, 3, 4, 3], [1, 2, 3, 4, 4, 4, 2, 4, 3, 3], [1, 2, 3, 4, 4, 4, 3, 2, 3, 4], [1, 2, 3, 4, 4, 4, 3, 2, 4, 3], [1, 2, 3, 4, 4, 4, 3, 3, 2, 4], [1, 2, 3, 4, 4, 4, 3, 3, 4, 2], [1, 2, 3, 4, 4, 4, 3, 4, 2, 3], [1, 2, 3, 4, 4, 4, 3, 4, 3, 2], [1, 2, 3, 4, 4, 4, 4, 2, 3, 3], [1, 2, 3, 4, 4, 4, 4, 3, 2, 3], [1, 2, 3, 4, 4, 4, 4, 3, 3, 2] ``` \$a(5) = 128458\$; \$a(6) = 612887198\$; ...and so on. \* Note, for example, that `[2, 1, 2]` violates (1) while `[1, 1, 2]` violates (3). (Other interpretations of the underlying objects being counted no doubt exist too, feel free to comment regarding these, or, even better, explain them as part of an answer.) ### The Challenge Write a program or function which does any of the following: * Takes a non-negative integer, \$n\$ and outputs either: + \$a(n)\$ + \$[a(0),\cdots ,a(n)]\$ * Takes a positive integer, \$n\$ and outputs either: + \$a(n-1)\$ + \$[a(0),\cdots ,a(n-1)]\$ * Takes no input and outputs the sequence \$a\$ forever --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so try to achieve the shortest solution in your chosen language. Also insightful answers that are not necessarily the shortest, so long as they are still well golfed, will probably be received well! --- This sequence is not currently in the [OEIS](https://oeis.org/), and as far as I can tell neither is any trivially related sequence (e.g. `[1,1,2,11,393,12442,...]`) - if you spot any do comment. [Answer] # JavaScript (ES6), ~~91 ... 76~~ 74 bytes A recursive approach. This is very fast up to \$n=5\$. Computing \$a(6)\$ takes approximately 2 minutes on my laptop. ``` n=>(g=a=>1+(h=i=>i&&h(i-1)+(a[i]^i&&a[i-1]?g(b=[...a,0],b[i]++):0))(n))`1` ``` [Try it online!](https://tio.run/##DYvLCoMwEEX3fsUsiswQDWbRTe3YDxFLovWRIknR0o347emsDod77tv93D5s/vMtQ3yNaeIUuMGZHTdG4cKeG5/nC/rSkELX@u4pLixN95ix51Zr7YqqK3rZlKJbRYSByBqbprhhAIaqhgB3hqtQEjgygCGGPa6jXuOM1uHlCCdJejkmeZ@W6uxMfw "JavaScript (Node.js) – Try It Online") ### How? Instead of explicitly building the sequences, we just keep track of how many times each value appears. This gives us enough information to decide which values are allowed to be added at any given time, assuming they're always added at the end of the sequence. ### Commented ``` n => ( // n = input g = a => // g is a recursive function taking an array a[] holding // how many times each value appears in the sequence 1 + ( // increment the final result h = i => // h is a recursive function taking i = next value to try i && // stop if i = 0 h(i - 1) + ( // otherwise, do a recursive call to h with i - 1 a[i] ^ i && // if i does not appear i times (rule #3) a[i - 1] ? // and i - 1 appears at least once (rule #1): g( // add the result of a recursive call to g: b = [...a, 0], // define b[] as a copy of a[] with an extra '0' // so that b[i] is guaranteed to be defined // (at this point, we know that a[0] to a[i-1] exist) b[i]++ // increment b[i] ) // end of recursive call to g : // else: 0 // add nothing ) // )(n) // initial call to h with the maximum value i = n (rule #2) )`1` // initial call to g with a[0] = '1', which is required to // to allow i = 1 to be added as per rule #1 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` lfUI{T{.ysmRh ``` [Try it online!](https://tio.run/##K6gsyfj/Pyct1LM6pFqvsjg3CMg1BgA "Pyth – Try It Online") Let's go through this step by step, starting at the end: * `mRh`: This autoexpands to `mRhdQ`. This means "Map the function `m` with right input `hd` over the input `Q`." + `Q` is an integer (e.g. 3) so it gets automatically cast to a range (e.g. [0, 1, 2]). + The `m` function is the map function. + `d` is defined to be the input to the map function. + `h` is the `+ 1` function (head). + `m` with two numeric inputs just replicates the left input a number of times equal to the right input. + As a result, `mRh` outputs a list like this: `[[0], [1, 1], [2, 2, 2]]`. * `s`: Flatten (sum). Now we have a list like `[0, 1, 1, 2, 2, 2]`. * `.y`: All permuted subsets. * `{`: Uniquify (remove duplicates). Now we have a list like `[[], [0], [1], [2], [0, 1], ... ]` * `fUI{T`: Filter that list on the function `UI{T`. + `T` is the input to the filter. + `{`: Uniquify the list to be filtered. Uniquify orders the unique elements in the order they first appear. + `UI`: Invariant under the function `U`: - `U`: Cast to range. So the unique elements must be `[]`, or `[0]`, or `[0, 1]`, etc. to pass this test. * `l`: Length. The result is implicitly printed. To see the orderings, just remove the `l`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` x`€FŒ!QJƑ$Ƈ¹Ƥ€ẎQL‘ ``` [Try it online!](https://tio.run/##y0rNyan8/78i4VHTGrejkxQDvY5NVDnWfmjnsSVAkYe7@gJ9HjXM@P//vzEA "Jelly – Try It Online") An initial attempt at a Jelly answer. A monadic link taking an integer and returning an integer. Too slow for n>3 on TIO. ## Explanation ``` x`€ | Repeat each of 1..n itself times F | Flatten Œ! | Permutations $Ƈ | Keep those where the following is true: Q | - Uniquify JƑ | - Check whether invariant when a sequence along the list is generated ¹Ƥ€ | Prefixes of each Ẏ | Join outer lists Q | Uniquify L | Length ‘ | Add one (to account for the empty list) ``` # Longer but handles \$n=5\$ in under 25 seconds on TIO ## [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ċⱮṀ$;0ḣ³<J$T;€)Ẏ “”WÇƬẈS ``` [Try it online!](https://tio.run/##ATcAyP9qZWxsef//xIvisa7huYAkOzDhuKPCszxKJFQ74oKsKeG6jgrigJzigJ1Xw4fGrOG6iFP///81 "Jelly – Try It Online") Thanks to @JonathanAllan for improving the final bit of the faster version! [Answer] # [R](https://www.r-project.org/), ~~113~~ ~~106~~ 98 bytes ``` g=function(n,N=1:n,B=N*0){for(e in N[c(1,B)[-n-1]>0&(F=all(B<=N))])F=F+g(n,,'[<-'(B,e,B[e]+1));+F} ``` [Try it online!](https://tio.run/##FcuxCsIwEADQ3a/oZO/MBRK1i/YcMmTMD4QMUtJQKFcoOonfHs3ytrfXWnh@y/RaNgGhwPYm5DicDH7mbYfcLdKFOIElh1GLtulhjuD5ua7gRg6ICT17Vf6b@jjqHhxlcjEnZRHvyn9rAYOHArZxblwa18aA9Qc "R – Try It Online") * -9 bytes thanks to @RobinRyder * -2 bytes using @Arnauld idea of storing occurrences table only (I just noticed that basically I was using the same approach, but creating the actual list too) [Answer] # [Ruby](https://www.ruby-lang.org/), 100 bytes Relatively simple answer similar to the Jelly solution, but it's able to calculate for n=4 without timing out on TIO (albeit taking 30 seconds to do so), which Jelly can't at time of writing. ``` ->n{r=(1..n).flat_map{|j|[j]*j};i=0;r.sum{r.permutation(i+=1).uniq.count{|a|a.uniq==[*1..a.max]}}+1} ``` [Try it online!](https://tio.run/##HcxLCsIwEADQq7jsBwcD7sp4kRDKKI0kmI/pBCpJzh7F5du8lO@frrGfb74kHASAH0G/iFdHsVRbpVWTbYvBy5Jgz64kiFtymYlN8IOZUYyQvXnDI2TPpVKlvxHl9OsIHB2qtVm0Hk9aPjfegcNqVL9@AQ "Ruby – Try It Online") [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 94 bytes ``` {1+set map ~*,grep {all .unique Z==^$_},.permutations>>[[\,] ^$_][*;*]}o{(^$_ Zxx 1..$_)[*;*]} ``` [Try it online!](https://tio.run/##JY1LCsMgAAWv8hahtFaEQOkmmIPEmuDClIAm1g8kSHp1K3Q5M4tx2ptnsQcuMzhKbu9BR1jl8CX07bVDVsaApXX5JI2B87GZTsqc9jZFFZdtDX0vxItK1CIF6Yg8t3ytgGHf0TLWTLe/LkEdYPU0bx7joys/ "Perl 6 – Try It Online") Times out for \$n>3\$, mostly since it is running the same filter for all prefixes of all permutations of the largest list (i.e. `[1,2,2,3,3,3,...n]`). This results in a lot of duplicates that have to filtered out later. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÝDÅΓœ€Œ€`ÙʒÙāQ}g> ``` Pretty slow (\$n=3\$ in about ~~5.5~~ 0.5 seconds on TIO), but it works. Inspired by [*@isaacg*'s Pyth answer](https://codegolf.stackexchange.com/a/198584/52210). I have the feeling this can definitely be golfed by at least a few bytes, though. -1 byte thanks to *@ExpiredData*. -1 byte and sped up by changing the order of some operations thanks to *@Grimmy*. [Try it online](https://tio.run/##yy9OTMpM/f//8FyXw63nJh@dfGrS4ZlHGgNrHzWtObcdSCQcnplu9/@/MQA) or [verify a few more test cases](https://tio.run/##ATcAyP9vc2FiaWX/M8aSTj8iIOKGkiAiP07/w51Ew4XOk8WTypLDmcSBUX3igqzOt@KCrGDDmWc@/yz/). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input] # (NOTE: `L` cannot be used here, because input=0 would become [1,0]) D # Duplicate this list ÅΓ # Run-length encode the lists, to have each value repeat itself that # many times (i.e. [1,2,3,4] → [1,2,2,3,3,3,4,4,4,4]) œ # Take all permutations of this list ʒ # Filter this list of lists by: Ù # Uniquify it ā # Push a list in the range [1, length] (without popping the list itself) Q # Check if both lists are equal }€η # After the filter: take the prefixes of each remaining permutation €` # Flatten one level Ù # Uniquify the list of lists g # After the filter: get the amount of remaining lists by taking the length > # + 1 for the missing `[]` # (after which this is output implicitly) ``` Minor (but even slower) alternative: `$ÝDÅΓœ€Œ€`ÙvyÙāQO`: [Try it online](https://tio.run/##yy9OTMpM/f9f5fBcl8Ot5yYfnfyoac3RSUAi4fDMssrDM480Bvr//28EAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/W90bJKfvZLCo7ZJCkr2/w39Ds91Odx6bvLRyY@a1hydBCQSDs8sqzw880hjoP//Wp3/AA). ``` $ # Push 1 and the input ÝDÅΓœ # Same as above €Œ # Get all sublists of each permutation €`Ù # Same as above v # Loop over each inner list `y` y # Push list `y` ÙāQ # Same as above O # Take the sum of the stack # (after the loop, the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` Nθ⊞υυFυFθF∧∨¬κ№ι⊖κ‹№ικ⊕κ⊞υ⁺ι⟦κ⟧ILυ ``` [Try it online!](https://tio.run/##VY4xC8IwEIV3f8WNF4ijUyepS6HU7uIQ09OWpkmb5Pz7MREVnN7B9x3v6VF57ZRJqbErx46XG3ncRLXrOYzIEjjfd@cBWcA7t08e7YBnj52LOAsJtWMbcZJwIu1pIRtpyEBk1FII@ONFbuy/I@Bb1xsOxbrMV1FW@Cl/1SpEbMk@YnayXaV0SPuneQE "Charcoal – Try It Online") Link is to verbose version of code. Builds up all `a(n)` lists in memory, so TIO will only go up to `n=5`. Explanation: ``` Nθ ``` Input `n`. ``` ⊞υυ ``` Start with a sequence with no digits. (Alternatively, I could start with a list containing `-1`; this would cost 3 bytes here and then save 3 bytes because I don't need to special case the first digit below.) ``` Fυ ``` Loop through each sequence as it is discovered. ``` Fθ ``` Loop through each available digit. (These are 0-indexed, so each digit `i` must be less than `n` and can be added if there are no more than `i` digits `i` so far.) ``` F∧∨¬κ№ι⊖κ‹№ικ⊕κ ``` Check that the digit is legal. ``` ⊞υ⁺ι⟦κ⟧ ``` If so then append this sequence to the list. ``` ILυ ``` Output the total number of sequences found. [Answer] # [Perl 5](https://www.perl.org/), 150 bytes ``` sub f{my$n=pop;$n?do{my%e;@f=f($n-1);push@f,map{$f=$_;grep!$e{$_}++,map$f=~s/.{$_}/$&$n/r,$n==1?0:index($f,$n-1)+1||9e9..length$f}@f for 1..$n;@f}:''} ``` [Try it online!](https://tio.run/##Nc5RT4NADAfw932KSqoHActI5GGcF/geahaXXTcMlAuwxIXhV8fDxb71l/7bOts3@bIMlwPw1F5RjOucRimPnW8fra7YcIjynEXaXYZzxUn76SZkg3t96q17QDvhfo7j1T3/DCmtkOITStonfqPJym1Ry9F@h8jJ3644u912dkfUWDmNZ@S5YuCuh4wIxR@dC6XmZZX2CigQbonyaNqALy9@2sD6V6T/CZt6GL2ivOZQgnpT9NXVEqpEJRVHpD4UFKDUPeD6WkYIUAoIqGIK7vl3CfRmXl5@AQ "Perl 5 – Try It Online") Produces the correct output in about two seconds for up to n=5. Out of memory for n=6. And would not work anyway for n>9 (two digit numbers). Thought about using a permutation solution like @Value Ink's Ruby answer, but could'nt find a core perl function or module that generated perm's and including a permutation function would probably add just way too many bytes. With indentation, comments and test run: ``` sub f { my $n = pop; $n == 0 ? ('') : $n == 1 ? ('',1) : do { my %e; #keep track of existing elements (strings) @f = f($n-1); #start with f(n-1) array push @f, map{ #expand f array n times $f = $_; #f = current @f element grep !$e{$_}++, #don't add if already exists map $f =~ s/.{$_}/$&$n/r, #insert n char at current position index($f,$n-1)+1||9e9 .. length$f #loop positions from first occurence of n-1 to end } @f for 1..$n; @f #return expanded @f array (string sequences) } } # test: for my $n (0..5){ my @f = f($n); my $list = $n<5 ? '['.join(',',map"'$_'",@f).']' : ''; print "$n: ".@f." $list\n"; } ``` Output: ``` 0: 1 [''] 1: 2 ['','1'] 2: 4 ['','1','12','122'] 3: 16 ['','1','12','122','123','1232','1223','1233','12332','12323','12233','12333','123332','123323','123233','122333'] 4: 409 ['','1','12','122','123','1232','1223','1233','12332','12323','12233','12333','123332','123323','123233','122333','1234','12342','12324','12234','12343','12334','123432','123342','123324','123423','123243','123234','122343','122334','123433','123343','123334','1234332','1233432','1233342','1233324','1234323','1233423','1233243','1233234','1234233','1232433','1232343','1232334','1223433','1223343','1223334','12344','123442','123424','123244','122344','123443','123434','123344','1234432','1234342','1234324','1233442','1233424','1233244','1234423','1234243','1234234','1232443','1232434','1232344','1223443','1223434','1223344','1234433','1234343','1234334','1233443','1233434','1233344','12344332','12343432','12343342','12343324','12334432','12334342','12334324','12333442','12333424','12333244','12344323','12343423','12343243','12343234','12334423','12334243','12334234','12332443','12332434','12332344','12344233','12342433','12342343','12342334','12324433','12324343','12324334','12323443','12323434','12323344','12234433','12234343','12234334','12233443','12233434','12233344','123444','1234442','1234424','1234244','1232444','1223444','1234443','1234434','1234344','1233444','12344432','12344342','12344324','12343442','12343424','12343244','12334442','12334424','12334244','12332444','12344423','12344243','12344234','12342443','12342434','12342344','12324443','12324434','12324344','12323444','12234443','12234434','12234344','12233444','12344433','12344343','12344334','12343443','12343434','12343344','12334443','12334434','12334344','12333444','123444332','123443432','123443342','123443324','123434432','123434342','123434324','123433442','123433424','123433244','123344432','123344342','123344324','123343442','123343424','123343244','123334442','123334424','123334244','123332444','123444323','123443423','123443243','123443234','123434423','123434243','123434234','123432443','123432434','123432344','123344423','123344243','123344234','123342443','123342434','123342344','123324443','123324434','123324344','123323444','123444233','123442433','123442343','123442334','123424433','123424343','123424334','123423443','123423434','123423344','123244433','123244343','123244334','123243443','123243434','123243344','123234443','123234434','123234344','123233444','122344433','122344343','122344334','122343443','122343434','122343344','122334443','122334434','122334344','122333444','1234444','12344442','12344424','12344244','12342444','12324444','12234444','12344443','12344434','12344344','12343444','12334444','123444432','123444342','123444324','123443442','123443424','123443244','123434442','123434424','123434244','123432444','123344442','123344424','123344244','123342444','123324444','123444423','123444243','123444234','123442443','123442434','123442344','123424443','123424434','123424344','123423444','123244443','123244434','123244344','123243444','123234444','122344443','122344434','122344344','122343444','122334444','123444433','123444343','123444334','123443443','123443434','123443344','123434443','123434434','123434344','123433444','123344443','123344434','123344344','123343444','123334444','1234444332','1234443432','1234443342','1234443324','1234434432','1234434342','1234434324','1234433442','1234433424','1234433244','1234344432','1234344342','1234344324','1234343442','1234343424','1234343244','1234334442','1234334424','1234334244','1234332444','1233444432','1233444342','1233444324','1233443442','1233443424','1233443244','1233434442','1233434424','1233434244','1233432444','1233344442','1233344424','1233344244','1233342444','1233324444','1234444323','1234443423','1234443243','1234443234','1234434423','1234434243','1234434234','1234432443','1234432434','1234432344','1234344423','1234344243','1234344234','1234342443','1234342434','1234342344','1234324443','1234324434','1234324344','1234323444','1233444423','1233444243','1233444234','1233442443','1233442434','1233442344','1233424443','1233424434','1233424344','1233423444','1233244443','1233244434','1233244344','1233243444','1233234444','1234444233','1234442433','1234442343','1234442334','1234424433','1234424343','1234424334','1234423443','1234423434','1234423344','1234244433','1234244343','1234244334','1234243443','1234243434','1234243344','1234234443','1234234434','1234234344','1234233444','1232444433','1232444343','1232444334','1232443443','1232443434','1232443344','1232434443','1232434434','1232434344','1232433444','1232344443','1232344434','1232344344','1232343444','1232334444','1223444433','1223444343','1223444334','1223443443','1223443434','1223443344','1223434443','1223434434','1223434344','1223433444','1223344443','1223344434','1223344344','1223343444','1223334444'] 5: 128458 ``` ]
[Question] [ Most square numbers have at least 1 different square number with which their [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is exactly 1. For a given square \$x\$, each square that meets this condition is called a *Levenshtein neighbour* of \$x\$. For example, \$36\$ is a Levenshtein neighbour of \$16\$, as only 1 edit (\$1 \to 3\$) is required. However, \$64\$ is not a Levenshtein neighbour of \$16\$, as it requires a minimum of 2 edits. Numbers that have leading 0s (\$2025 \to 025\$) are *not* Levenshtein neighbours. Your task is to take a square number as input and to output, in any reasonable format, the complete list of it's Levenshtein neighbours. You may include repeat neighbours in the list, if you wish, but you may not include the original input, as it isn't a Levenshtein neighbour of itself. Any reasonable format should include some sort of separator between the outputs, such as `,` or a newline, and can output characters with the corresponding Unicode value (i.e. brainfuck) rather than the numbers themselves. The order of the output doesn't matter. This input will always be a square number, greater than \$0\$. Your program should have no *theoretical* limit, but if it fails for large numbers for practical reasons (e.g. beyond 32-bit numbers), that's completely fine. If the input does not have any Levenshtein neighbours, the output must clearly reflect this, such as outputting nothing, an empty array/string, a negative integer, \$0\$, etc. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases These are the results for the squares of \$1\$ through to \$20\$: ``` 1: 4, 9, 16, 81 4: 1, 9, 49, 64 9: 1, 4, 49 16: 1, 36, 169, 196 25: 225, 256, 625 36: 16, 361 49: 4, 9 64: 4 81: 1, 841 100: 400, 900, 1600, 8100 121: 1521 144: 1444 169: 16, 1369 196: 16, 1296, 1936 225: 25, 625, 1225, 2025, 4225, 7225 256: 25 289: 2809 324: 3249 361: 36, 961 400: 100, 900, 4900, 6400 ``` In addition, `1024` does not have any neighbours, so is a good test case. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11 10~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) -4 thanks to Grimy !! (square first rather than looking for squares saves 3; use 10^n saves 1) ``` °Lnʒ.L ``` Takes an integer, outputs a, possibly empty, list **[Try it online!](https://tio.run/##yy9OTMpM/f//0AafvFOT9Hz@/zcBAA "05AB1E – Try It Online")** - This is crazy-slow due to the `°`, so no point trying it even for `9`. Or **[Try a slightly faster version](https://tio.run/##yy9OTMpM/f/fQtsn79QkPZ///40MjEwB "05AB1E – Try It Online")** - This one adds eight instead with `8+` then uses the same approach. ### How? ``` °Lnʒ.L - f(integer) stack = n ° - push 10^n 10^n L - range [1,2,3,...,10^n] n - square [1,4,9,...,10^2n] ʒ - filter keep if == 1: .L - Levenshtein distance ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~142~~ 138 bytes ``` .? $'¶$`#$&$'¶$`#$'¶$`$& # 0$%'¶$%`1$%'¶$%`2$%'¶$%`3$%'¶$%`4$%'¶$%`5$%'¶$%`6$%'¶$%`7$%'¶$%`8$%'¶$%`9 A`^0 Dr` \d+ $* -2G`(\b1|11\1)+\b %`1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fz55LRf3QNpUEZRU1GANMqahxKXMZqKiCOKoJhjCGEYxhDGOYwBimMIYZjGEOY1jAGJZcjglxBlwuRQlcMSnaXCpaXLpG7gkaMUmGNYaGMYaa2jFJXEDb/v83MjAyBQA "Retina 0.8.2 – Try It Online") Explanation: ``` .? $'¶$`#$&$'¶$`#$'¶$`$& ``` For each digit, try a) removing it b) preceding it with a different digit c) changing it to a different digit. For now, the different digit is marked with a `#`. ``` # 0$%'¶$%`1$%'¶$%`2$%'¶$%`3$%'¶$%`4$%'¶$%`5$%'¶$%`6$%'¶$%`7$%'¶$%`8$%'¶$%`9 ``` For each potential different digit, substitute each possible digit. ``` A`^0 ``` Remove numbers that now begin with zero. ``` Dr` ``` Remove all duplicated numbers. (This just leaves the lines blank.) ``` \d+ $* ``` Convert to unary. ``` -2G`(\b1|11\1)+\b ``` Keep all square numbers except the last (which is always the input number). ``` %`1 ``` Convert the remaining numbers back to decimal. [Answer] # [R](https://www.r-project.org/), ~~42~~ 41 bytes -1 byte with the bound \$(9n)^2\$. ``` function(n,y=(1:(9*n))^2)y[adist(n,y)==1] ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6fSVsPQSsNSK09TM85IszI6MSWzuAQkrmlraxj7P03DUJMrTcPEEkQaGhiZgGgjUzPN/wA "R – Try It Online") All Levenshtein neighbours of \$n\$ are smaller than \$91n\$ (That bound is attained, for example, by \$1\to 91\$ or \$100\to9100\$). Here, I am using instead the bound \$(9n)^2=81n^2\$. For \$n>1\$, \$81n^2>91n\$ so we are fine. For \$n=1\$, this bound misses one Levenshtein neighbour: \$1\to91\$; since \$91\$ is not a square, we are fine. Lists all square numbers between \$1\$ and \$(9n)^2\$, and keeps those with Levenshtein distance equal to 1. [Answer] # [Python 2](https://docs.python.org/2/), ~~173~~ ~~167~~ ~~149~~ ~~148~~ ~~147~~ ~~144~~ ~~139~~ 138 bytes ``` lambda n,I=int:{(I(I(v)**.5)**2==I(v))*I(v)for v in[`n`[:i]+`j-1`[:j]+`n`[i+k:]or 0for j in range(11)for i in range(n)for k in 0,1]}-{0,n} ``` [Try it online!](https://tio.run/##XY5RCoNADES/6yny6epaXFspLOwBPINd0NLaRm0UEaGIZ99m/SmUwGQyvMCMn/k1UOYac3V9/b7dayBZGKRZr2HBs4goOuYsmTH@EpHXZphgAaSyoqrUaOOqTRS7lh0nGHfaMpJ6rmUOppqej1Cp/RN/Ce1B54NUKrslayppc3@UkqeLiMtzbnVwGCduBygBuZSEJvRbBO4L "Python 2 – Try It Online") 19+3+5+1=28! bytes thx to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # Oracle SQL, 93 bytes ``` select level*level from t where utl_match.edit_distance(x,level*level)=1connect by level<10*x ``` Test in SQL\*PLus. ``` SQL> set heading off SQL> with t(x) as (select 225 from dual) 2 select level*level from t where utl_match.edit_distance(x,level*level)=1connect by level<10*x 3 / 25 625 1225 2025 4225 7225 6 rows selected. ``` [Answer] # [PHP](https://php.net/), 62 bytes ``` for(;$argn*92>$n=++$i**2;levenshtein($argn,$n)==1&&print$n._); ``` [Try it online!](https://tio.run/##VVLbToQwEH3nK5pNswEWXVpKpSL65gf4qsZsDArJpksW1hfjr4udC6uS0HbmzMw5pzB0w3xzN3RDFMmpHadRNOIxEvioTGy3wmTCZULZTFSKAYOAQsCE1xoG3AIYACgJnZQsLMyBYc4SpkvENOy6DLDVJSEFd1loY17jzoIoYUkIs1dqIaoMdag8pwLYHSzKwloFgAo095SaOwx7M4amol4WogpLxEH/b1JDoFxBlvRiqUQzgKO5HFaD5yvNJtEx1lJYEZWucqIpNIkJOycsyYXLcXwrhj2qs0eDqzWLxzyMIQIQET3XUfR2OLa71y7mT74bBZ6ST6wbjr2fxOqhHU/7gIZigq/FqsYCuTu@@/CjYLaeQ0FcYy51@lb6ZrORfZrqet9@tH7sprb3MeKZ9EnTqPUaKaS/fEnq@Q/lk2eGkx/bKZZ98i/0Ifyawcb3YZj6gx/ni/sf "PHP – Try It Online") This script prints Levenshtein neighbors of input separated by `_` with a trailing separator, and if no neighbors are found, prints nothing. Happily PHP has a built-in for [Levenshtein distance](https://www.php.net/manual/en/function.levenshtein.php)! This script loops over all square numbers from 1 to `input * 91`, since all valid Levenshtein neighbors (distance of 1) are in that range. Then prints every number in that range which has a Levenshtein distance of 1 with the input. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~129 125~~ 123 bytes Takes input as a string. Prints the Levenshtein neighbours to STDOUT. ``` s=>{for(t=9+s;t;t--)(t+='')**.5%1||(g=m=>m*n?1+g(m,--n)*(g(--m)-(s[m]==t[n++]))*g(m):m+n)(s.length,n=t.length)-1||print(t)} ``` [Try it online!](https://tio.run/##Xc/BboMwDAbge58il4mYOIjQgGDI7LTrXgBxQFWhnUioSNRL22dnnrTTTrb8f7bk7/E@htN2vUV9r/eJ9kDdY1o3GalRoY1t1BpkVJQkkKZZ@WaeTzmTo86l/sOoWTrU2kMqZ6m1Ay1D7wai2HulBoCUAbw75UGGbDn7OV7QU/xrQfO523b1UUZ47W1v0GKDpsKixGOFtsHKYm3Q5Dmagqu1nLJomLApSq51g8fCsuftX5cXdjhk/MTneLpIL6gTj4MQp9WHdTlnyzrL5EuQSIQSHlqOJlZK8IvtP8eDF@w/ "JavaScript (V8) – Try It Online") ### Commented ``` s => { // s = input for( // loop: t = 9 + s; // start with t = '9' + s t; // repeat while t > 0 t-- // decrement t after each iteration ) // (t += '') // coerce t to a string ** .5 % 1 || // abort if t is not a square ( g = // g is a recursive function to test whether the // Levenshtein distance between s and t is exactly 1 m => // m = pointer into s (explicit parameter) // n = pointer into t (defined in the global scope) m * n ? // if both m and n are greater than 0: 1 + // add 1 to the final result and add the product of: g(m, --n) * ( // - a recursive call with m and n - 1 g(--m) - // - a recursive call with m - 1 and n - 1 (s[m] == t[n++]) // minus 1 if s[m - 1] = t[n - 1] ) * // g(m) // - a recursive call with m - 1 and n : // else: m + n // stop recursion and return m + n )(s.length, n = t.length) // initial call to g with m = s.length, n = t.length - 1 || // abort if the final result is not 1 print(t) // otherwise, print t } // ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~53~~ 38 bytes ``` D;Ɱ⁵ṭJœP,œṖjþ⁵Ẏṭ@ḢF${ʋʋ€$ƲẎ%⁵1ị$ƇḌƲƇḟ ``` [Try it online!](https://tio.run/##y0rNyan8/9/F@tHGdY8atz7cudbr6OQAnaOTH@6clnV4H0hoVx9Q1OHhjkVuKtWnuk91P2pao3JsE1BYFShr@HB3t8qx9oc7eg63HdoEYsz/b/2oYY6Crp3Co4a51ofbj056uHOGCpeJQdChTYfbgZoj/wMA "Jelly – Try It Online") There’s no built-in for Levenshtein distance so generates all possible 1-distance edits and then excludes those with leading zero and keeps only perfect squares. Doesn’t filter duplicates (as permitted). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~62~~ 59 bytes ``` f@n_:=Select[Range[9n]^2,EditDistance@@ToString/@{n,#}==1&] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NIS/eyjY4NSc1uSQ6KDEvPTXaMi82zkjHNSWzxCWzuCQxLznVwSEkP7ikKDMvXd@hOk9HudbW1lAt9n8AUKQkWlnXLi1aOTZWTUHfQUEDYoSxEdAIzf8A "Wolfram Language (Mathematica) – Try It Online") Using the bound from the [R answer](https://codegolf.stackexchange.com/a/190221/87058). ]
[Question] [ Given a sequence of bytes, output the SHA-256 hash value of the sequence. ## The SHA-256 Algorithm The following pseudocode is taken from the [Wikipedia page for SHA-2](https://en.wikipedia.org/wiki/SHA-2#Pseudocode). ``` Note 1: All variables are 32 bit unsigned integers and addition is calculated modulo 2^32 Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63 Note 3: The compression function uses 8 working variables, a through h Note 4: Big-endian convention is used when expressing the constants in this pseudocode, and when parsing message block data from bytes to words, for example, the first word of the input message "abc" after padding is 0x61626380 Initialize hash values: (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): h0 := 0x6a09e667 h1 := 0xbb67ae85 h2 := 0x3c6ef372 h3 := 0xa54ff53a h4 := 0x510e527f h5 := 0x9b05688c h6 := 0x1f83d9ab h7 := 0x5be0cd19 Initialize array of round constants: (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311): k[0..63] := 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 Pre-processing: append the bit '1' to the message append k bits '0', where k is the minimum number >= 0 such that the resulting message length (modulo 512 in bits) is 448. append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer (this will make the entire post-processed length a multiple of 512 bits) Process the message in successive 512-bit chunks: break message into 512-bit chunks for each chunk create a 64-entry message schedule array w[0..63] of 32-bit words (The initial values in w[0..63] don't matter, so many implementations zero them here) copy chunk into first 16 words w[0..15] of the message schedule array Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array: for i from 16 to 63 s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3) s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19) xor (w[i-2] rightshift 10) w[i] := w[i-16] + s0 + w[i-7] + s1 Initialize working variables to current hash value: a := h0 b := h1 c := h2 d := h3 e := h4 f := h5 g := h6 h := h7 Compression function main loop: for i from 0 to 63 S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25) ch := (e and f) xor ((not e) and g) temp1 := h + S1 + ch + k[i] + w[i] S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22) maj := (a and b) xor (a and c) xor (b and c) temp2 := S0 + maj h := g g := f f := e e := d + temp1 d := c c := b b := a a := temp1 + temp2 Add the compressed chunk to the current hash value: h0 := h0 + a h1 := h1 + b h2 := h2 + c h3 := h3 + d h4 := h4 + e h5 := h5 + f h6 := h6 + g h7 := h7 + h Produce the final hash value (big-endian): digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7 ``` ## Reference implementation Here is a reference implementation, in Python 3: ``` #!/usr/bin/env python3 import sys # ror function modified from http://stackoverflow.com/a/27229191/2508324 def ror(val, r_bits): return (val >> r_bits) | (val << (32-r_bits)) % 2**32 h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] s = sys.stdin.read().encode() msg = [int(x,2) for c in s for x in '{:08b}'.format(c)] msg.append(1) while len(msg) % 512 != 448: msg.append(0) msg.extend([int(x,2) for x in '{:064b}'.format(len(s) * 8)]) for i in range(len(msg)//512): chunk = msg[512*i:512*(i+1)] # sloth love chunk w = [0 for _ in range(64)] for j in range(16): w[j] = int(''.join(str(x) for x in chunk[32*j:32*(j+1)]),2) for j in range(16, 64): s0 = ror(w[j-15], 7) ^ ror(w[j-15], 18) ^ (w[j-15] >> 3) s1 = ror(w[j-2], 17) ^ ror(w[j-2], 19) ^ (w[j-2] >> 10) w[j] = (w[j-16] + s0 + w[j-7] + s1) % 2**32 work = h[:] for j in range(64): S1 = ror(work[4], 6) ^ ror(work[4], 11) ^ ror(work[4], 25) ch = (work[4] & work[5]) ^ (~work[4] & work[6]) temp1 = (work[7] + S1 + ch + k[j] + w[j]) % 2**32 S0 = ror(work[0], 2) ^ ror(work[0], 13) ^ ror(work[0], 22) maj = (work[0] & work[1]) ^ (work[0] & work[2]) ^ (work[1] & work[2]) temp2 = (S0 + maj) % 2**32 work = [(temp1 + temp2) % 2**32] + work[:-1] work[4] = (work[4] + temp1) % 2**32 h = [(H+W)%2**32 for H,W in zip(h,work)] print(''.join('{:08x}'.format(H) for H in h)) ``` ## Restrictions * The usage of builtins which compute SHA-256 hashes or otherwise trivialize the challenge is forbidden * The input and output may be in any reasonable format (encoded in a single-byte encoding, base64, hexadecimal, etc.) ## Test cases ``` <empty string> -> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 abc -> ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad Hello, World! -> c98c24b677eff44860afea6f493bbaec5bb1c4cbb209c6fc2bbb47f66ff2ad31 1234 -> 03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4 ``` [Answer] ## Python 2, 633 bytes ``` n=range f=2**32 q=512 r=lambda v,b:v%f>>b|(v<<32-b)%f t=int g=lambda e:[t(x**e%1*f)for x in n(2,312)if 383**~-x%x==1] h=g(.5) k=g(1/3.) m=map(t,input()) l=len(m) m+=[1]+[0]*((447-l)%q)+map(t,'{:064b}'.format(l)) for i in n(l/q+1): c=m[q*i:][:q];w=[t(`c[j*32:][:32]`[1::3],2) for j in n(16)];x=h[:8] for j in n(48):a,o=w[j+1],w[j+14];w+=[(w[j]+(r(a,7)^r(a,18)^(a>>3))+w[j+9]+(r(o,17)^r(o,19)^(o>>10)))%f] for j in n(64):a,o=x[::4];d=x[7]+(r(o,6)^r(o,11)^r(o,25))+(o&x[5]^~o&x[6])+k[j]+w[j];e=(r(a,2)^r(a,13)^r(a,22))+(x[1]&a|x[2]&a|x[1]&x[2]);x=[d+e]+x[:7];x[4]+=d h=[(H+W)%f for H,W in zip(h,x)] print''.join('%08x'%H for H in h) ``` This solution is the result of a collaboration between myself, Leaky Nun, and Mars Ultor. As such, I've made it community wiki out of fairness. It takes input as a binary string wrapped in quotes (e.g. `'011000010110001001100011'` for `abc`) and outputs a hex string. [Answer] ## Python 2, 519 bytes ``` Q=2**32 G=lambda e:[int(x**e%1*Q)for x in range(2,312)if 383**~-x%x<2] H=G(.5)[:8] r=lambda v,b:v>>b|v<<32-b M=input() l=len(M) M+=bin(l|1<<(447-l)%512+64)[2:] while M:j=0;a,b,c,d,e,f,g,h=H;exec"H+=int(M[:32],2),;M=M[32:];"*16+"x=H[-15];y=H[-2];H+=(H[-16]+H[-7]+(r(y,17)^r(y,19)^y>>10)+(r(x,7)^r(x,18)^x/8))%Q,;"*48+"u=(r(e,6)^r(e,11)^r(e,25))+(e&f^~e&g)+h+G(1/3.)[j]+H[j+8];X=a,b,c,d,e,f,g,h=(u+(r(a,2)^r(a,13)^r(a,22))+(a&b^a&c^b&c))%Q,a,b,c,(d+u)%Q,e,f,g;j+=1;"*64;H=tuple(a+b&Q-1for a,b in zip(H,X)) print"%08x"*8%H ``` I was working off the pseudocode, but some parts just ended up being the same as the golfed reference Mego posted since there's not much to golf (e.g. the constant tables, for which the only real golf was a `<2` instead of `==1`). Over 100 bytes down though, but I'm sure there's still more to be gotten. Input/output is also string of bits to hex string. [Answer] # [J](http://jsoftware.com/), ~~458~~ ~~445~~ ~~443~~ ~~438~~ ~~435~~ ~~430~~ 421 bytes ``` 3 :0 B=.32#2 A=.B&#: P=.+&#. 'H K'=.A<.32*&2(-<.)2 3%:/p:i.64 for_m._512]\(,(1{.~512|448-#),(,~B)#:#)y do.w=.(,B#:(15&|.~:13&|.~:_10|.!.0])@(_2&{)P/@,(25&|.~:14&|.~:_3|.!.0])@(_15&{),_7 _16&{)^:48]_32]\m 'a b c d e f g h'=.H=.8{.H for_t.i.64 do.u=.A]P/((e<g)~:e*f),h,(~:/26 21 7|."{e),t{&>K;w v=.A(a*b)P(c*a~:b)P~:/30 19 10|."{a h=.g g=.f f=.e e=.A]d P u d=.c c=.b b=.a a=.A]u P v end. H=.A]H P a,b,c,d,e,f,g,:h end. ,H ) ``` [Try it online!](https://tio.run/##RZHLbtswEEX38xWTEJVIdzK2KNlxWbNIvBKQjXbdxBX0oCQXTlQkdoJChn7dpZ0AXfEO7iHmEPx9Or12hZ4v0BqM0cxgbTnWQsO95XUgDGSWvwaCIUzxIbR8v/L1JNDyZsVKY/zFTP@YLS8SaPqX/InzeaQ3j5JkNPDo8zFJljdCkaRxrYQR6i/UPb9blrQWRkbz4MijieLLkUezI1/xbKPuZK6DQWXTO5L6k0k@mPg/4m8PivJbzKOFT79Mstzksd//BGGBJVZYo8MGW@y8emp5OXB6Ed3zxdmrHPybNtlUSrdq1WjcpFHUkRzNVC9QR3h75OvBKdoPwY@H7@/w5nlZTEqVyWpSjMYHz8YzjL7hWf96KKCz3EJruYHGsgN3XlFjhgeoLVdQWS6htFxAcW4OvnkD91wzpOc59XNBJVVUk6OGWjLdR00pKABXdT0Sdk2NeYKCH/HzCwnlEgVqhcJgwbhlfN3X22cMw9MpdbtdT/izf9nVV/AP) This is a monadic verb that takes a list of bits as input and outputs a list of bits. On TIO, conversion from string to list of bits for the input and list of bits to hexadecimal is implemented for convenience. To test other input, just modify the text in the `input` field. [Answer] ## C, ~~1913~~ 1822 bytes (just for fun) ``` #define q unsigned #define D(a,c)x->b[1]+=a>1<<33-1-c;a+=c; #define R(a,b)(a>>b|a<<32-b) #define S(x,a,b,c)(R(x,a)^R(x,b)^x>>c) #define W(i,a)i=x->s[a]; #define Y(i,a)x->s[a]+=i; #define Z(_,a)h[i+a*4]=x->s[a]>>(24-i*8); #define J(a)x->d[a] #define T(_,a)x->d[63-a]=x->b[a/4]>>8*(a%4); #define Q(_,a)x->s[a]=v[a]; #define A(F)F(a,0)F(b,1)F(c,2)F(d,3)F(e,4)F(f,5)F(g,6)F(h,7) #define G(a,b)for(i=a;i<b;++i) typedef struct{q char d[64];q l,b[2],s[8];}X;q k[]={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2},v[]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19};a(X*x){q a,b,c,d,e,f,g,h,i,t,z,m[64];G(z=0,16)m[i]=J(z++)<<24|J(z++)<<16|J(z++)<<8|J(z++);G(i,64)m[i]=S(m[i-2],17,19,10)+m[i-7]+S(m[i-15],7,18,3)+m[i-16];A(W);G(0,64){t=h+(R(e,6)^R(e,11)^R(e,25))+(e&f^~e&g)+k[i]+m[i];z=(R(a,2)^R(a,13)^R(a,22))+(a&b^a&c^b&c);h=g;g=f;f=e;e=d+t;d=c;c=b;b=a;a=t+z;}A(Y)}i(X*x){x->l=*x->b=x->b[1]=0;A(Q)}p(X*x,char*w,q l){q t,i;G(0,l){J(x->l)=w[i];if(++x->l==64){a(x);D(*x->b,512)x->l=0;}}}f(X*x,char*h){q i=x->l;if(i<56){J(i++)=128;G(i,56)J(i)=0;}else{J(i++)=128;G(i,64)J(i)=0;a(x);G(0,56)J(i)=0;}D(*x->b,x->l*8)A(T)a(x);G(0,4){A(Z)}} ``` I took the reference implementation and started golfing, my target was under 2k. Can be improved if somebody knows how to generate the constants (cube root of primes, I can't think of any golf-friendly way). Usage: ``` X ctx; unsigned char hash[32]; i(&ctx); // initialize context p(&ctx,text,strlen(text)); // hash string f(&ctx,hash); // get hash ``` ]
[Question] [ # Task Given an input list of integers **x1…xn**, compute a list of ranks **r1…rn** (a permutation of **{1…n}**) so that **xr1 ≤ xr2 ≤ … ≤ xrn**. Then, for each **xi**, replace its rank by the arithmetic mean of the ranks of all values in **x** that are equal to **xi**. (That is, whenever there is a tie between equal values in **x**, fairly redistribute the ranks among all of them.) Output the modified list of ranks **r’1…r’n**. (For statistics geeks: such a ranking of observations is used in the [Mann–Whitney *U* test](https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test#Calculations) (method two, step 1.)) # Example Given an input list **[3, -6, 3, 3, 14, 3]**, the first list of ranks would be **[2, 1, 3, 4, 6, 5]**, which would sort the list into **[-6, 3, 3, 3, 3, 14]**. Then, the ranks for all **3**s in the input list are evened out into **(2 + 3 + 4 + 5) ÷ 4 = 3.5**. The final output is **[3.5, 1, 3.5, 3.5, 6, 3.5]**. # Test cases ``` [4, 1, 4] -> [2.5, 1.0, 2.5] [5, 14, 14, 14, 14, 5, 14] -> [1.5, 5.0, 5.0, 5.0, 5.0, 1.5, 5.0] [9, 9, -5, -5, 13, -5, 13, 9, 9, 13] -> [5.5, 5.5, 2.0, 2.0, 9.0, 2.0, 9.0, 5.5, 5.5, 9.0] [13, 16, 2, -5, -5, -5, 13, 16, -5, -5] -> [7.5, 9.5, 6.0, 3.0, 3.0, 3.0, 7.5, 9.5, 3.0, 3.0] ``` # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ð_'Ṡ‘S‘H ``` *Saved 2 bytes by using the `cmp` trick from [@xnor's answer](https://codegolf.stackexchange.com/a/81100).* [Try it online!](http://jelly.tryitonline.net/#code=w7BfJ-G5oOKAmFPigJhI&input=&args=WzMsIC02LCAzLCAzLCAxNCwgM10) or [verify all test cases](http://jelly.tryitonline.net/#code=w7BfJ-G5oOKAmFPigJhICsOH4oKsRw&input=&args=WzQsIDEsIDRdLCBbNSwgMTQsIDE0LCAxNCwgMTQsIDUsIDE0XSwgWzksIDksIC01LCAtNSwgMTMsIC01LCAxMywgOSwgOSwgMTNdLCBbMTMsIDE2LCAyLCAtNSwgLTUsIC01LCAxMywgMTYsIC01LCAtNV0). ### How it works ``` ð_'Ṡ‘S‘H Main link. Left argument: A (list of values) ð Make the chain dyadic, setting the right argument to A. _' Spawned subtraction; compute the matrix of differences. Ṡ Apply the sign function to each difference. ‘ Increment. S Sum across columns. ‘ Increment. H Halve. ``` [Answer] # Pyth, 12 ``` m+l<#dQ.OS/Q ``` [Test Suite](http://pyth.herokuapp.com/?code=m%2Bl%3C%23dQ.OS%2FQ&input=%5B5%2C+14%2C+14%2C+14%2C+14%2C+5%2C+14%5D&test_suite=1&test_suite_input=%5B4%2C+1%2C+4%5D%0A%5B5%2C+14%2C+14%2C+14%2C+14%2C+5%2C+14%5D%0A%5B9%2C+9%2C+-5%2C+-5%2C+13%2C+-5%2C+13%2C+9%2C+9%2C+13%5D%0A%5B13%2C+16%2C+2%2C+-5%2C+-5%2C+-5%2C+13%2C+16%2C+-5%2C+-5%5D&debug=0) For each value this computes the arithmetic mean of `[1..frequency]` and adds the count of values less than the current one. This works because for each value we would compute: ``` (1 / frequency) * sum (i = 1..frequency) i + count_less ``` which we can simplify to: ``` (1 / frequency) * [ frequency * (frequency + 1) / 2 + count_less * frequency ] ``` and again to: ``` (frequency + 1) / 2 + count_less ``` However, in Pyth it was golfier to compute the first summand by using the mean builtin, rather than this other formula. [Answer] ## Python 2, 51 bytes ``` lambda l:[-~sum(1+cmp(y,x)for x in l)/2.for y in l] ``` For each element `y`, the `cmp` expression gives 2 points for each smaller `x` and 1 point for each equal `x`. This sum is rescaled into the right range by adding 1 and halving. The `2.` is needed to avoid integer division. **Python 3, 52 bytes** Python 3 lacks `cmp`, requiring a Boolean expression (+2 bytes), but it has float division (-1 byte). ``` lambda l:[-~sum((y>x)+(y>=x)for x in l)/2for y in l] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` 7#utG&S&S2XQw) ``` [Try it online!](http://matl.tryitonline.net/#code=NyN1dEcmUyZTMlhRdyk&input=WzEzLCAxNiwgMiwgLTUsIC01LCAtNSwgMTMsIDE2LCAtNSwgLTVd) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhJCjcjdXRJJlMmUzJYUXcpCiFEVAo&input=WzMsIC02LCAzLCAzLCAxNCwgM10KWzQsIDEsIDRdCls1LCAxNCwgMTQsIDE0LCAxNCwgNSwgMTRdCls5LCA5LCAtNSwgLTUsIDEzLCAtNSwgMTMsIDksIDksIDEzXQpbMTMsIDE2LCAyLCAtNSwgLTUsIC01LCAxMywgMTYsIC01LCAtNV0) (slightly modified version of the code; each result is on a different line). ``` % Implicit input. Example: [5 14 14 14 14 5 14] 7#u % Replace each value by a unique, integer label. Example: [1; 2; 2; 2; 2; 1; 2] t % Duplicate G&S % Push input again. Sort and get indices of the sorting. Example: [1 6 2 3 4 5 7] &S % Sort and get the indices, again. This gives the ranks. Example: [1 3 4 5 6 2 7] 2XQ % Compute mean of ranks for equal values of the integer label. Example: [1.5; 5] w % Swap top two elements in stack ) % Index the means with the integer labels. Example: [1.5; 5; 5; 5; 5; 1.5; 5] % Implicit display ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes Code: ``` v¹y‹O¹yQO>;+ˆ ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=dsK5eeKAuU_CuXlRTz47K8uG&input=WzEzLCAxNiwgMiwgLTUsIC01LCAtNSwgMTMsIDE2LCAtNSwgLTVd). [Answer] # R, ~~17~~ 12 bytes Takes the input from STDIN outputs to STDOUT. If the output is flexible then we can ditch the `cat()`. ``` rank(scan()) ``` Fairly simple, uses the builtin rank that defaults to average for a tie breaker. In use: ``` > rank(scan()) 1: 5 14 14 14 14 5 14 8: Read 7 items [1] 1.5 5.0 5.0 5.0 5.0 1.5 5.0 > rank(scan()) 1: 3 -6 3 3 14 3 7: Read 6 items [1] 3.5 1.0 3.5 3.5 6.0 3.5 > ``` [Answer] # J, 18 bytes ``` 1-:@+1+/"1@:+*@-/~ ``` Based on Dennis' [solution](https://codegolf.stackexchange.com/a/81089) using xnor's [method](https://codegolf.stackexchange.com/a/81100). Using a straight-forward approach requires **24 bytes** for me. ``` (i.~~.){](+/%#)/.1+/:@/: ``` ## Usage ``` f =: 1-:@+1+/"1@:+*@-/~ f 3 _6 3 3 14 3 3.5 1 3.5 3.5 6 3.5 f 4 1 4 2.5 1 2.5 f 5 14 14 14 14 5 14 1.5 5 5 5 5 1.5 5 f 9 9 _5 _5 13 _5 13 9 9 13 5.5 5.5 2 2 9 2 9 5.5 5.5 9 f 13 16 2 _5 _5 _5 13 16 _5 _5 7.5 9.5 6 3 3 3 7.5 9.5 3 3 ``` [Answer] ## Actually, 18 bytes ``` ;╗`╝╜"╛-su"£MΣu½`M ``` [Try it online!](http://actually.tryitonline.net/#code=O-KVl2DilZ3ilZwi4pWbLXN1IsKjTc6jdcK9YE0&input=WzMsIC02LCAzLCAzLCAxNCwgM10) This is essentially a port of [xnor's Python solution](https://codegolf.stackexchange.com/a/81100/45941). Explanation: ``` ;╗`╝╜"╛-su"£MΣu½`M ;╗ push a copy of input to reg0 ` `M for x in input: ╝ push x to reg1 ╜ push input from reg0 " "£M for y in input: ╛ push x from reg0 -s cmp(y,x) (sgn(y-x)) u add 1 Σu½ sum, add 1, half ``` [Answer] # Julia, 30 bytes ``` !x=-~sum((x.>x')+(x.>=x'),2)/2 ``` This uses an approach from [@xnor's answer](https://codegolf.stackexchange.com/a/81100). Julia has `cmp`, but it doesn't vectorize. [Try it online!](http://julia.tryitonline.net/#code=IXg9LX5zdW0oKHguPngnKSsoeC4-PXgnKSwyKS8yCgpmb3IgeCBpbiAoWzQsIDEsIDRdLCBbNSwgMTQsIDE0LCAxNCwgMTQsIDUsIDE0XSwgWzksIDksIC01LCAtNSwgMTMsIC01LCAxMywgOSwgOSwgMTNdLCBbMTMsIDE2LCAyLCAtNSwgLTUsIC01LCAxMywgMTYsIC01LCAtNV0pCiAgICBkaXNwbGF5KCF4KQogICAgcHJpbnRsbigpCmVuZA&input=) [Answer] # APL, 17 chars ``` (y+.×⍋X)÷+/y←∘.=⍨X ``` Assuming the list is stored in `X`. ## Explanation: Note that APL evaluates expressions from right to left. Then: * `∘.=⍨X` = `X∘.=X` where `∘.=` is the outer product using `=` as dyadic function. (Where you normally would multiply. So the mathematical outer product may be written as `∘.×`.) * The resulting matrix is stored in `y` and `y` is directly folded using `+` to give a vector of the number of equal objects for each rank (lets call it `z←+/y`). * `⍋X` returns the ranks of `X` * `y+.×⍋X` gives the inner product of our matrix y with this vector. * The result is divided (component wise) by `z`. [Answer] ## JavaScript (ES6), ~~49~~ 48 bytes ``` a=>a.map(n=>a.reduce((r,m)=>r+(n>m)+(n>=m),1)/2) ``` Edit: Saved 1 byte by reformulating the expression so it now looks like @xnor's Python 3 answer. ]
[Question] [ **[Liar's Dice](http://en.wikipedia.org/wiki/Liar%27s_dice)** is a fairly simple dice game. I've seen a few different variations of the rules, but here is the version I'm most familiar with: * Each player starts with 5d6 * Except when tallying the dice at the end of a round, each player may see their own dice, but not those of any opponent * At the start of any given round, all players roll whatever dice they currently have * Then, one player (usually, this is either the winner of the previous round OR the player to the left of the player who started last time; we'll be using the former for this KotH; with a random player starting the first round) makes a guess about how many of a particular number are on the table **(ONES ARE WILD)** * Bidding continues to the right, going higher each time (for instance; 3 fives, 3 sixes and 4 twos are all higher than 3 fours, but 3 threes is not; 4 ones is also higher but bidding on ones will probably put you at a disadvantage); until any player calls the player preceding them a liar * At this point, all players reveal their dice and count the number of the last number bid on on the table altogether * If the total is lower than the bid, the player who made the bid must give a die to the player who called them a liar, otherwise, the player who called the bidder a liar must give a die to the bidder (so the bidder wins if their are *at least* as many of that number as he had bid, there don't have to be the exact number) * When you run out of dice, you lose * The last player standing wins For example: ``` Player one has 1,1,2,4,6 Player two has 1,2,2,3,5 Player three has 1,3,3,4,6 Player one: three sixes. Player two: four twos. Player three: four threes. Player one: five twos. Player two: six twos. Player three: six threes. Player one: six fours. Player two: Liar! They reveal their dice and count up the ones (because ones are wild) and the fours. It turns out that there are, in fact, exactly six fours. So player two gives player one a die. They reroll and player one starts the next round. ``` You must write a bot to play this game. It must implement the following abstract java class: ``` public abstract class Player { public Player() {} public String toString() { return this.getClass().getSimpleName(); } public abstract String bid(int yourId, int[] diceEachPlayerHas, int[] yourDice, String[] bids); } ``` * You must implement the bid method + The first argument is your bot's current position in the turn order, the second is an array showing how many dice each player (including yourself) currently has, the third is an array showing the values currently shown on your own dice, and the fourth is an array of all bids made since the start of the current round - will have length 0 if you are making the first bid of the round + The output should be either a string of the form "number face", or the string "Liar!" to call the previous bidder a liar. + If your output is formatted illegally, you will be eliminated. * You may override the toString method, but are not required to. However, you may not edit it in any way that interferes with the readability of the controller's output. * You are permitted to call any other public methods of the controller, but *not* its main method. * You may read and edit only files in the running directory prefixed with your bot's own name * You are not permitted to take input from any other source * Instance variables are reset at the start of each new game, but static variables are not. **Scoring** * One set of 1,000 games, with 3-5 players in each, will be simulated each time a bot is added (as soon as three or more bots have been submitted), scored as shown in the controller source (in any given game, you get 1 at the start of each of your turns, 10 each time you capture a die, and 1,000 bonus if you win); enforcing a limit of 5,000 TURNS (not rounds) each game. * Your bot will be scored by its score from the latest set of games; plus ten times its vote score, if nonnegative. (The latter is unlikely to have a significant effect on the score) The controller source can be found [here.](http://pastebin.com/raw.php?i=Rud0rR1R) # Scores as of 2015-06-19: ``` Badnomial: 434,924 + 6x10 = 424,984 Nobody: 282,329 + 6x10 = 282,389 StraightShooter: 265,205 + 5x10 = 265,255 MostlyHonestAbe: 158,958 + 4x10 = 158,998 The Pirate: 157,005 + 1x10 = 157,015 Statistician: 144,012 + 2x10 = 144,032 Fidelio: 49,973 + 2x10 = 49,993 Absurd Bot: 6,831 DrHouse: 2,638 + 3x10 = 2,668 ``` [Answer] # Nobody Tries to guess the dice from other players. Calls other bots liars if it doesn't know what to do. **Edit:** Fixed a problem where Nobody would bid forever, never calling Liar. ``` public class Nobody extends Player{ @Override public String bid(int myId, int[] diceEachPlayerHas, int[] myDice, String[] bids) { if (bids.length == 0) return "1 2"; int wilds = 0; int players = Controller.numPlayers(); double myKnowledge = (double)diceEachPlayerHas[myId]/Controller.diceInPlay(); double previousKnowledge = (double)diceEachPlayerHas[(myId-1+players)%players] / Controller.diceInPlay(); int[] dice = new int[5]; for (int i = 0; i < myDice.length; i++) { if (myDice[i] == 1) { wilds++; } else { dice[myDice[i]-2]++; } } wilds = (int) (1/myKnowledge+wilds-1)+1; for (int i = 2; i <= 6; i++) { dice[i-2] += wilds; } String best = "0 0"; for (int i = 2; i <= 6; i++) { if (Controller.isGreaterThan(dice[i-2] + " " + i, best)) { best = dice[i-2] + " " + i; } } if (Controller.isGreaterThan(best, bids[bids.length - 1])) { return best; } if (previousKnowledge > 0.4) { int prev = Integer.valueOf(bids[bids.length - 1].split(" ")[0]); int prevFace = Integer.valueOf(bids[bids.length - 1].split(" ")[1]); if (dice[prevFace - 2] +2 >= prev) return (prev+1) + " " + bids[bids.length - 1].split(" ")[1]; } return "Liar!"; } } ``` [Answer] **Badnomial, the bot that makes bad decisions based on binomial distributions:** Edit: Fixed a stupid mistake in the probability calculations, now accounts for next Bidder as well as previous. ``` public class Badnomial extends Player{ public String toString() {return "Badnomial";} public String bid(int myId, int[] diceEachPlayerHas, int[] myDice, String[] bids) { int[] dieCounts = new int[7]; for(int i:myDice) dieCounts[i]++; for(int i=2; i<7; i++) dieCounts[i] += dieCounts[1]; if(bids.length > 0) { String[] lastBid = bids[bids.length - 1].split(" "); int bidCount = Integer.valueOf(lastBid[0]); int bidDie = Integer.valueOf(lastBid[1]); // Check if I hold a better bid boolean betterBid = false; int myBidDie; int myBidCount; int myHighestCount = 0; int myHighDie = bidDie +1; for(int i = 2; i < 7; i++) { if(dieCounts[i] >= myHighestCount) { myHighestCount = dieCounts[i]; myHighDie = i; } } if((myHighestCount > bidCount) || ((myHighestCount == bidCount) && (myHighDie > bidDie))) { betterBid = true; myBidDie = myHighDie; myBidCount = myHighestCount; } if(betterBid == false) { int unknownDice = Controller.diceInPlay() - myDice.length; int myDiceNeeded = bidCount - myHighestCount; if(myHighDie <= bidDie) myDiceNeeded++; int previousBidder = myId - 1; if(previousBidder < 0) previousBidder = Controller.numPlayers() -1; int bidderDiceNeeded = bidCount - dieCounts[bidDie] - (int)(diceEachPlayerHas[previousBidder]/3 +1); int bidderUnknown = Controller.diceInPlay() - diceEachPlayerHas[previousBidder] -myDice.length; int nextBidder = myId + 1; if(nextBidder == Controller.numPlayers()) nextBidder = 0; int nbDiceNeeded = myDiceNeeded - (int)(diceEachPlayerHas[nextBidder]/3 +1); int nbUnknown = Controller.diceInPlay() - diceEachPlayerHas[nextBidder]; //float myChances = (unknownDice/3 - myDiceNeeded)/((float)unknownDice/9); //float bidderChances = (bidderUnknown/3 - bidderDiceNeeded)/((float)bidderUnknown/9); double myChances = 1 - cumBinomialProbability(unknownDice, myDiceNeeded -1); double bidderChances; if(bidderDiceNeeded > 0) bidderChances = 1- cumBinomialProbability(bidderUnknown, bidderDiceNeeded -1); else bidderChances = 1.0; double nbChances; if(nbDiceNeeded > 0) nbChances = 1- cumBinomialProbability(nbUnknown, nbDiceNeeded -1 ); else nbChances = 1.0; if(((myChances < .5) && (nbChances <.5)) || (bidderChances < .2)) return "Liar!"; } return (bidCount+1) + " " + myHighDie; } return 2 + " " + 2; } private double cumBinomialProbability(int n, int k) { double sum = 0; for(int i = 0; i <=k; i++) sum += binomialProbability(n, i); return sum; } private double binomialProbability(int n, int k) { double nfact = 1; double dfact = 1; int greater; int lesser; if((n-k) > k) { greater = n - k; lesser = k; } else { greater = k; lesser = n-k; } for(int i = greater+1; i <= n; i++) nfact = nfact * i; for(int i = 2; i <= lesser; i++) dfact = dfact * i; return (nfact/dfact)*(Math.pow((1.0/3), k))*Math.pow(2.0/3, (n-k)); } } ``` It tries to determine whether it should bluff or call Liar based on estimated cumulative binomial distributions for itself and the previous and next bidders' chances of having their needed dice present. Basically, it calls Liar if the previous Bidder is very likely to be a Liar or if it feels it that both it and the next Bidder are more likely lying than not. [Answer] # Straight Shooter He plays it straight and doesn't bluff. He's also naive enough to think that others do, too, so he never calls liar unless the bid goes over the total number of dice in play (minus his own dice that don't match the bid). To be a bit more conservative than the exact expected number for each die, he doesn't count his own wilds, but assumes others have a uniform distribution. With the current four players, either he or MostlyHonestAbe came up first each time, with fairly close scores. I'm assuming the minimum bid is `2 2`. If a bid of one die (or bidding ones) is allowed, let me know so I can make that change. ``` public class StraightShooter extends Player{ public String toString(){return "Straight Shooter";} public String bid(int me, int[] numDices, int[] dice, String[] bids){ int[] counts = new int[7]; double[] expected = new double[7]; int unknown = Controller.diceInPlay() - dice.length; for(int i:dice) counts[i]++; for(int i=2;i<7;i++) expected[i] = counts[i] + unknown / 3d; int bidCount = 2; int bidDie = 2; if(bids.length > 0){ String[] lastBid = bids[bids.length-1].split(" "); bidCount = Integer.valueOf(lastBid[0]); bidDie = Integer.valueOf(lastBid[1])+1; int possible = Controller.diceInPlay(); for(int i=2;i<7;i++) if(i != bidDie) possible -= counts[i]; if(bidCount > possible) return "Liar!"; if(bidDie > 6){ bidDie = 2; bidCount++; } } double best = Double.MAX_VALUE; int bestCount = bidCount; int bestDie = bidDie; for(int count=bidCount;count<=Controller.diceInPlay();count++){ for(int die=bidDie;die<7;die++){ double score = Math.abs(expected[die]-bidCount); if(score < best){ best = score; bestCount = count; bestDie = die; } } bidDie = 2; } return bestCount + " " + bestDie; } } ``` [Answer] ## MostlyHonestAbe Abe makes conservative guesses about the rest of opponents die, and then then stays honest until he doesn't think there are enough dice to beat the current bid. At this point he bluffs once, then calls liar the next time. ``` import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; public class MostlyHonestAbe extends Player{ final boolean debug = false; boolean bluffedOnce = false; PrintStream out; @Override public String bid(int myId, int[] diceEachPlayerHas, int[] myDice, String[] bids) { try { File f = new File("abe.log.txt"); out = new PrintStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); } if(debug){ out = System.out; } //reset bluff counter on the first round if(bids.length < diceEachPlayerHas.length){ bluffedOnce = false; } //Is it the first bid? if(bids.length == 0){ out.println("I go first"); return lowestViableBid(1,1, myDice, diceEachPlayerHas, true); } out.println("Last bid = " + bids[bids.length - 1]); out.print("My Dice = "); for(int d : myDice){ out.print(d + ", "); } out.println(); //What was the last bid? String[] lastBid = bids[bids.length -1].split(" "); return lowestViableBid(Integer.parseInt(lastBid[1]), Integer.parseInt(lastBid[0]), myDice, diceEachPlayerHas, false); } //Lowest honest bid, or liar private String lowestViableBid(int highestVal, int highestCount, int[] myDice, int[] otherDice, boolean firstTurn){ //Make a better array for the dice //Include what the other players probably have int wilds = numDie(1, myDice); int[] diceCount = new int[6]; diceCount[0] = wilds; int otherPlayerExpectedValue = 0; for(int d : otherDice){ otherPlayerExpectedValue += d; } otherPlayerExpectedValue -= myDice.length; out.println("Number of other dice = " + otherPlayerExpectedValue); otherPlayerExpectedValue = otherPlayerExpectedValue / 4; //Note: Other player expected value is biased low, counting wilds the number should be divided by 3. out.println("playerExpectedVal = " + otherPlayerExpectedValue); for(int i = 1; i < 6; i++){ diceCount[i] = numDie(i + 1, myDice) + wilds + otherPlayerExpectedValue; } //What's my array look like? for(int i = 0; i < diceCount.length; i++){ out.println("diceVal = " + (i + 1) + ", diceCount = " + diceCount[i]); } //Can I bid the same number, but higher dice val? for(int diceVal = highestVal + 1; diceVal <= 6; diceVal++){ if(diceCount[diceVal - 1] >= highestCount){ out.println("1.Returning " + highestCount + " " + diceVal); return highestCount + " " + diceVal; } } //What about more dice? for(int diceNum = highestCount + 1; diceNum <= myDice.length; diceNum++){ for(int diceVal = highestVal + 1; diceVal <= 6; diceVal++){ if(diceCount[diceVal - 1] == diceNum){ out.println("2.Returning " + (diceNum) + " " + diceVal); return (diceNum) + " " + diceVal; } } } if(firstTurn){ return "1 2"; } //If this is the first time I'm out of my league, bluff a round before calling liar. if(!bluffedOnce){ out.println("bluffing " + (highestCount + 1) + " " + highestVal); bluffedOnce = true; return (highestCount + 1) + " " + highestVal; } out.println("Returning Liar!"); //Well, wouldn't want to lie return "Liar!"; } private int numDie(int i, int[] myDice){ int result = 0; for(int j : myDice){ if(i == j){ result++; } } return result; } } ``` [Answer] # Dr. House Everybody Lies! ``` public class DrHouse extends Player { public String bid(int yourId, int[] diceEachPlayerHas, int[] yourDice, String[] bids) { return "Liar!"; } } ``` [Answer] # Fidelio This bot know that only his most recurrent value will lead him to victory, so he stick with it. He assume there's a portion of everyone's dice that is the same as his, if anyone bid more than that portion, he assume he's a liar. ``` public class Fidelio extends Player { final String LIAR ="Liar!"; @Override public String bid(int yourId, int[] diceEachPlayerHas, int[] yourDice, String[] bids) { int[] myDices = new int[6]; int valueToBid=1; for(int i : yourDice) myDices[i-1]++; for(int i=2;i<myDices.length;i++) if(myDices[i]>=myDices[valueToBid]) valueToBid=i; if(bids.length==0) return 2+" "+valueToBid; int sum=0; String[] lastBidString=bids[bids.length-1].split(" "); int[] lastBid = new int[2]; lastBid[0] = Integer.parseInt(lastBidString[0]); lastBid[1] = Integer.parseInt(lastBidString[1])-1; for(int i : diceEachPlayerHas) sum+=i; sum-=yourDice.length; if(lastBid[0]>sum/3+myDices[lastBid[1]]+myDices[0]) return LIAR; if(lastBid[1]>= valueToBid) { if(lastBid[0]>=myDices[0]+myDices[valueToBid]+sum*2/5) return LIAR; return (lastBid[0]+1)+" "+myDices[valueToBid]; } return lastBid[0]+" "+valueToBid; } } ``` I hope he will do some good work :). [Answer] # Statistician You have 1/3 chance of having any number other than aces. One guy once tell me that not checking your dices and juste knowing the odds can make you win this game. EDIT : It was bidding too high. But it doesn't improve the score a lot. ``` public class Statistician extends Player{ public String toString(){return "Statistician";} public String bid(int me, int[] numDices, int[] dice, String[] bids){ int totalDices = 0; int currentBid, max; for (int i : numDices) totalDices += i; max = totalDices/3; if(bids.length>0){ currentBid = Integer.valueOf(bids[bids.length-1].split(" ")[0]); if(currentBid>max) return "Liar!"; } return max+" 6"; } } ``` [Answer] # Absurd Bot Makes the claim that all of the dice are 6's unless it can't. If the bot can't do that, it means that this is an impossible situation or nearly impossible situation. Because of this, it calls liar. I am curious as to how effective this bot will be. ``` public class AbsurdBot extends Player { @Override public String bid(int yourId, int[] diceEachPlayerHas,int[] yourDice,String[] bids) { String[] lastbid; int a, b, d; d = 0; for (int dice : diceEachPlayerHas) d += dice; if (bids.length != 0) { lastbid = bids[bids.length-1].split(" "); a = Integer.parseInt(lastbid[0]); b = Integer.parseInt(lastbid[1]); if (a > d || a == d && b == 6) return "Liar!"; } return d + " 6"; } } ``` [Answer] # The Pirate I made a few simple bots while testing the controller, and this is the only one that's really any good. Will likely be improved upon later. ``` import java.util.Arrays; import java.util.Scanner; public class Pirate extends Player{ public Pirate() { } public String toString(){ return "The Pirate"; } private String bid(int[] t,int tol){ int[]z=t.clone(); Arrays.sort(z); int j=0; for(int i=0;i<6;i++){ if(t[i]==z[5]){j=i;break ;} } return (tol+t[j])+" "+(j+1); } @Override public String bid(int yourId, int[] diceEachPlayerHas, int[] yourDice, String[] bids) { int[] t=new int[6]; for(int i=0;i<yourDice.length;i++){ t[yourDice[i]-1]++; } for(int i=1;i<t.length;i++)t[i]+=t[0]; int tol=(Controller.diceInPlay()-yourDice.length)/4; if(bids.length==0)return bid(t,1); Scanner i=new Scanner(bids[bids.length-1]); int x=i.nextInt(),y=i.nextInt(); i.close(); if(t[y-1]>x)return (t[y-1]+2)+" "+y; int nd=Controller.diceInPlay(); if(x>nd+t[y-1]-yourDice.length)return "Liar!"; if(Controller.isGreaterThan(bid(t,tol), bids[bids.length-1])){ int z=Controller.valueOf(bids[bids.length-1]); for(int j=1;j<=tol;j++)if(Controller.valueOf(bid(t,j))>z)return bid(t,j); } return "Liar!"; } } ``` ]
[Question] [ # Background In Bejeweled and similar games, the player must swap any two adjacent gems (no diagonals) in an 8x8 grid of gems in order to match three of the same color in a row. The gems can be matched horizontally or vertically. Gameplay continues until there no move exists that can be made resulting in three in a row, at which point the game is over. # Task The goal is to write a program that determines whether a game of Bejeweled is not over yet. In other words, it must check to see if there is a possible move that makes at least three in a row. There can be more than three gems in a row and it is still a valid move. # Input Your program must accept via standard input an 8x8 representation of a Bejeweled grid. Each of the seven gem colors will be represented by a digit from 1 to 7. Each line will contain one row, and 8 lines, each consisting of 8 digits, will be input. See the examples. You can assume that the input will always follow this format, and will never already contain three in a row. # Output The program must then output (to standard output) `yes` or `no` depending on whether or not at least one valid move exists that would result in three or more gems in a row. Your program must not output anything other than a single instance of either `yes` or `no`. # Rules Your program must not use any external files or resources, command-line arguments, or require a certain file name. The program with the least number of bytes in its source code wins. # Examples **Input:** ``` 12314131 13224145 54762673 61716653 61341144 23453774 27645426 75575656 ``` **Output:** `yes` **Input:** ``` 35261546 76421754 15743271 62135642 35617653 64565476 54427254 15635465 ``` **Output:** `no` See [MT0's answer below](https://codegolf.stackexchange.com/questions/26505/determine-if-a-move-exists-in-a-bejeweled-match-3-game/26512#26512) for additional test cases. [Answer] # Original Solution: JavaScript - ~~261~~ ~~255~~ ~~228~~ ~~227~~ ~~179~~ 153 Characters ``` /(\d)(\1(\d|.{6}|.{9})|(\d|.{6}|.{9})\1|.{7}\1(.|.{9})|(.|.{9})\1.{7}|(.{7,9}|.{17})\1.{8}|.{8}\1(.{7,9}|.{17}))\1/.test(s.replace(/\n/g,'A'))?'yes':'no' ``` Assuming that the string to test is in the variable `s` (to make it a function `f` then add `f=s=>` to the beginning of the code or, otherwise, to take input from a prompt then replace `s` with `prompt()`). Outputs is to the console. # 3rd Solution: JavaScript (ECMAScript 6) - 178 Characters ``` p=x=>parseInt(x,36);for(t="2313ab1b8a2a78188h9haj9j8iaiir9r",i=v=0;s[i];i++)for(j=0;t[j];v|=s[i]==s[i+a]&s[i]==s[i+b]&i%9<8&(b>3|(i+b-a)%9<8))a=p(t[j++]),b=p(t[j++]);v?'yes':'no' ``` I took the 2nd solution, below, (which uses regular expressions to check for characters in certain configurations) and reworked it to just check the string for identical characters in the same configurations without using regular expressions. The Base-36 string `"2313ab1b8a2a78188h9haj9j8iaiir9r"` gives pairs of offsets to check - i.e. the pair `23` results in the check if ith character is identical to the (i+2)th character and the (i+3)th character (the equivalent of the regular expression `(.).\1\1` - with some additional checks to ensure that the non-identical character is not a newline). # 2nd Solution: JavaScript (ECMAScript 6) - 204 Characters ``` p=x=>parseInt(x,18);g=a=>a?a>1?"(.|\\n){"+a+"}":".":"";f=(x,a,b)=>RegExp("(.)"+g(a)+"\\1"+g(b)+"\\1").test(x);for(t="10907160789879h8",i=v=0;t[i];v|=f(s,x,y)||f(s,y,x))x=p(t[i++]),y=p(t[i++]);v?'yes':'no' ``` Builds multiple regular expressions (see below for more details) using pairs of values taken from the Base-18 string `10907160789879h8` and takes the `OR` of all the tests. To reduce it further you can note that the regular expressions come in pairs where one is the "reverse" of the other (ignoring the Regular Expressions for 3-in-a-row horizontally and vertically as the OP states they will never be present - if you want to add those tests back in the append `0088` to the Base-18 string). **Explanation** Start with 16 regular expressions covering all the possible configurations of valid moves: ``` REs=[ /(\d)\1\1/, // 3-in-a-row horizontally /(\d).\1\1/, // 3-in-a-row horizontally after left-most shifts right /(\d)\1.\1/, // 3-in-a-row horizontally after right-most shifts left /(\d)(?:.|\n){9}\1\1/, // 3-in-a-row horizontally after left-most shifts down /(\d)(?:.|\n){7}\1.\1/, // 3-in-a-row horizontally after middle shifts down /(\d)(?:.|\n){6}\1\1/, // 3-in-a-row horizontally after right-most shifts down /(\d)\1(?:.|\n){6}\1/, // 3-in-a-row horizontally after left-most shifts up /(\d).\1(?:.|\n){7}\1/, // 3-in-a-row horizontally after middle shifts up /(\d)\1(?:.|\n){9}\1/, // 3-in-a-row horizontally after right-most shifts up /(\d)(?:.|\n){7,9}\1(?:.|\n){8}\1/, // 3-in-a-row vertically (with optional top shifting left or right) /(\d)(?:.|\n){7}\1(?:.|\n){9}\1/, // 3-in-a-row vertically after middle shifts right /(\d)(?:.|\n){9}\1(?:.|\n){7}\1/, // 3-in-a-row vertically after middle shifts left /(\d)(?:.|\n){8}\1(?:.|\n){7}\1/, // 3-in-a-row vertically after bottom shifts right /(\d)(?:.|\n){8}\1(?:.|\n){9}\1/, // 3-in-a-row vertically after bottom shifts left /(\d)(?:.|\n){17}\1(?:.|\n){8}\1/, // 3-in-a-row vertically after top shifts down /(\d)(?:.|\n){8}\1(?:.|\n){17}\1/, // 3-in-a-row vertically after bottom shifts up ]; ``` (*Note: the regexs for 3-in-a-row horizontally (0th) and vertically (part of the 9th) are irrelevant as the OP states that inputs matching these will never be present.*) Testing each of those against the input will determine if a valid move of that configuration can be found. However, the regular expressions can be combined to give these 6: ``` /(\d)(?:.|(?:.|\n){9}|(?:.|\n){6})?\1\1/ // Tests 0,1,3,5 /(\d)\1(?:.|(?:.|\n){9}|(?:.|\n){6})?\1/ // Tests 0,2,6,8 /(\d)(?:.|\n){7}\1(?:.|(?:.|\n){9})\1/ // Tests 4,10 /(\d)(?:.|(?:.|\n){9})\1(?:.|\n){7}\1/ // Tests 7,11 /(\d)(?:(?:.|\n){7,9}|(?:.|\n){17})\1(?:.|\n){8}\1/ // Tests 9,14 /(\d)(?:.|\n){8}\1(?:(?:.|\n){7,9}|(?:.|\n){17})\1/ // Tests 9a,12,13,15 ``` These can then be combined into a single regular expression: ``` /(\d)(?:.|(?:.|\n){9}|(?:.|\n){6})?\1\1|(\d)\2(?:.|(?:.|\n){9}|(?:.|\n){6})?\2|(\d)(?:.|\n){7}\3(?:.|(?:.|\n){9})\3|(\d)(?:.|(?:.|\n){9})\4(?:.|\n){7}\4|(\d)(?:(?:.|\n){7,9}|(?:.|\n){17})\5(?:.|\n){8}\5|(\d)(?:.|\n){8}\6(?:(?:.|\n){7,9}|(?:.|\n){17})\6/ ``` Which just needs to be tested against the input. **Test Cases** Some test cases which other people might find useful (doesn't comply with the input format of using only digits 1-7 but that's easily corrected and is only an 8x4 grid - since that is the minimum required for a test of all the valid inputs). In the format of a map from input string to which of the 16 regular expressions above it matches. ``` Tests={ "12345678\n34567812\n56781234\n78123456": -1, // No Match "12345678\n34969912\n56781234\n78123456": 1, // 3-in-a-row horizontally after left-most shifts right "12345678\n34567812\n59989234\n78123456": 2, // 3-in-a-row horizontally after right-most shifts left "12345978\n34567899\n56781234\n78123456": 3, // 3-in-a-row horizontally after left-most shifts down "12345978\n34569892\n56781234\n78123456": 4, // 3-in-a-row horizontally after middle shifts down "12345678\n34967812\n99781234\n78123456": 5, // 3-in-a-row horizontally after right-most shifts down "12399678\n34967812\n56781234\n78123456": 6, // 3-in-a-row horizontally after left-most shifts up "12345678\n34597912\n56789234\n78123456": 7, // 3-in-a-row horizontally after middle shifts up "12345998\n34567819\n56781234\n78123456": 8, // 3-in-a-row horizontally after right-most shifts up "12945678\n34597812\n56791234\n78123456": 9, // 3-in-a-row vertically after top shifts right "12349678\n34597812\n56791234\n78123456": 9, // 3-in-a-row vertically after top shifts left "12345978\n34569812\n56781934\n78123456": 10, // 3-in-a-row vertically after middle shifts right "92345678\n39567812\n96781234\n78123456": 11, // 3-in-a-row vertically after middle shifts left "12945678\n34967812\n59781234\n78123456": 12, // 3-in-a-row vertically after bottom shifts right "12349678\n34569812\n56781934\n78123456": 13, // 3-in-a-row vertically after bottom shifts left "12395678\n34567812\n56791234\n78193456": 14, // 3-in-a-row vertically after top shifts down "12345698\n34567892\n56781234\n78123496": 15, // 3-in-a-row vertically after bottom shifts up "12345678\n34567899\n96781234\n78123456": -1, // No match - Matches (.)\1.\1 but not 3 in a row "12345679\n99567812\n56781234\n78123456": -1, // No match - Matches (.).\1\1 but not 3 in a row }; ``` **Edit 1** Replace `\d`s with `.` - saves 6 characters. **Edit 2** Replace `(?:.|\n)` with `[\s\S]` and removed extra non-capturing groups and updated back references (as suggested by [m-buettner](https://codegolf.stackexchange.com/users/8478/m-buettner)) and added in yes/no output. **Edit 3** * Added ECMAScript 6 solution to build the individual Regular Expressions from a Base-18 string. * Removed the tests for 3-in-a-row horizontally (as suggested by [m-buettner](https://codegolf.stackexchange.com/users/8478/m-buettner)). **Edit 4** Added another (shorter) solution and two more non-matching tests cases. **Edit 5** * Shortened original solution by replacing newlines with a non-numeric character (as suggested by [VadimR](https://codegolf.stackexchange.com/users/15846/vadimr)). **Edit 6** * Shortened original solution by combining bits of the regular expression (as suggested by [VadimR](https://codegolf.stackexchange.com/users/15846/vadimr)). [Answer] # Python 383 Just a single\* line of Python! ``` a=[list(l)for l in raw_input().split('\n')];z=any;e=enumerate;c=lambda b:z(all(p==b[y+v][x+u]for(u,v)in o)for y,r in e(b[:-2])for x,p in e(r[:-2])for o in [[(0,1),(0,2)],[(1,0),(2,0)]]);print z(c([[q if(i,j)==(m,n)else a[m][n]if(i,j)==(y+1,x+1)else p for j,p in e(r)]for i,r in e(a)])for y,t in e(a[1:-1])for x,q in e(t[1:-1])for n,m in((x+u,y+v)for u,v in[(1,0),(1,2),(0,1),(2,1)])) ``` \*Well, with semicolons, but that's still non-trivial in python (python one-liners are [fun!](https://wiki.python.org/moin/Powerful%20Python%20One-Liners)) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 71 [bytes](https://github.com/abrudz/SBCS) ``` 'no' 'yes'⊃⍨{∨/∊{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}¨⍵(⍉⍵)}↑{⍞}¨⍳8 ``` [Try it online!](https://tio.run/##HY49TsNAEIVr9hTp7EhAmH8aDkDFGSJBaCKCRBVZqZCCY8UICiQqCn6Ee5SGBilHmYuY8Ta7b95@781Ob@dHl8vpfHHd@@PL@YWvn06S1w@zvrhZFKNieXVXeHPvbVd53U28bqqyJN98gjdf8XDmzft43/HhxNvduBwg3/55/Z3PrNud16/HAX4MzMq3vziiiA2B1b6Lq/R2kydfP1fevmX357SPf/QHswRIwECQgBAZWJKwKapRUjBQlUEQAzAnJBYyC2HKwqjJRExUNEUVCSoIh6mMYMIJxJjQICkCSbjBRGvu5IjFpljHaJhhpUjLPw "APL (Dyalog Unicode) – Try It Online") Nice challenge to show off some extreme array-processing capabilities of APL. Without the I/O restriction, it is **~~55~~ 52 bytes** as a function taking a 8-by-8 matrix of chars and returning a boolean (therefore without 7-bytes pre-processing `↑{⍞}¨⍳8` and 12-bytes post-processing `'no' 'yes'⊃⍨`): ``` {∨/∊{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}¨⍵(⍉⍵)} ``` [Try it online!](https://tio.run/##bY27SgNREIZrz1Ok3ICazN3GysZUgvEFAhKbQGxlSSWEzZINWghWFl5wOxvT2Aj7KPMi6@zWNnPmDN//f7PbxdH13WyxvGl99zS58PXDuM29qEdelHmWkW/ewcsPL@9PvXwdNjUfjrzaD7MO8u2vF5/97Pdq78XzcYBvHbPy7Q8OKGJdYNXU8WRebfpfOw@VV7sobr7I14@hn16exbw6n0zbg/kgbrlXL5E78ep7nAAJGAgSECIDSxI2RTVKCgaq0i3EAMwJiYXMYjFlYdRkIiYqmv6pJkEF4YCUEUw4gRgTGiRFIIlrMGHpHRw1YQ49o2EPK0Va/gA "APL (Dyalog Unicode) – Try It Online") The basic idea is that we can test for 1x4 and 2x3 sub-boxes if each sub-box has a valid Bejeweled move: ``` (1x4 box) OxOO OOxO (2x3 box) OOx OxO xOO xxO xOx Oxx Oxx xOx xxO xOO OxO OOx ``` For 1x4 boxes, we can check if the first item appears at least 3 times. For 2x3 boxes, we can check if at least one item in the first column appears in every column. For 4x1 and 3x2 boxes, we can check for 1x4 and 2x3 on the board transposed. ### How it works: the code ``` 'no' 'yes'⊃⍨{∨/∊{((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)}¨⍵(⍉⍵)}↑{⍞}¨⍳8 ↑{⍞}¨⍳8 ⍝ Take 8 lines of input and form a 8x8 matrix ⍳8 ⍝ A dummy length-8 vector {⍞}¨ ⍝ Map "take a line of input" over the dummy vector ↑ ⍝ Promote a vector of vectors to a matrix (M) {∨/∊{...}¨⍵(⍉⍵)} ⍝ Pass the matrix onto the inline function ⍵(⍉⍵) ⍝ M and transpose of M {...}¨ ⍝ Test over M and transposed M for Bejeweled moves ⍝ (explained below) ∨/∊ ⍝ Enlist all booleans and check if any is true {((3≤1⊥⊃=⊢)¨4,/⍵)({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵)} ⍝ Test over all possible sub-boxes ((3≤1⊥⊃=⊢)¨4,/⍵) ⍝ Test over 1x4 boxes 4,/⍵ ⍝ Extract 1x4 boxes ( ⊃=⊢)¨ ⍝ For each box, test if each item equals first item 3≤1⊥ ⍝ Is the count at least 3? ({∨⌿∧⌿∨⌿⍵∘.=⊣/⍵}⌺2 3⊢⍵) ⍝ Test over 2x3 boxes { }⌺2 3⊢⍵ ⍝ Ditto ⍵∘.=⊣/⍵ ⍝ Compare each item with the first column ∨⌿ ⍝ Does there exist an item from the first column ∧⌿ ⍝ that appears on every column ∨⌿ ⍝ at least once? 'no' 'yes'⊃⍨ ⍝ Map 0/1 to no/yes respectively ``` [Answer] # Perl, ~~114~~ ~~96~~ ~~95~~ ~~93~~ ~~92~~ ~~87~~ ~~86~~ 85 bytes Includes + for `-a0p` Run with the input on STDIN: ``` bejeweled.pl 12314131 13224145 54762673 61716653 61341144 23453774 27645426 75575656 ^D ``` `bejeweled.pl`: ``` #!/usr/bin/perl -a0p $i/s%.%chop$F[$i++&7]%eg>3|/(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/||redo;$_=$1?yes:n.o ``` This combines a single direction horizontal regex solution with rotations ## Explanation: In this solution I will repeatedly rotate and do the following 4 tests: ``` /(.).\1\1/, // 3-in-a-row horizontally after left-most shifts right /(.)\C{9}\1\1/, // 3-in-a-row horizontally after left-most shifts down /(.)\C{7}\1.\1/, // 3-in-a-row horizontally after middle shifts down /(.)\C{6}\1\1/, // 3-in-a-row horizontally after right-most shifts down ``` Where `\C` is "any character" (unlike `.` this includes newline). Except that `\C` is deprecated and leads to warnings, so I use `\H` (non-horizontal space) instead which is good enough to capture all digits and newline. After 4 rotation this will have done all 16 tests that are needed ``` -p Read lines from STDIN, print $_ at the end -0 No line ending => slurp ALL of STDIN -a Split $_ into @F. Since there are no spaces on the rows this means each element of @F is 1 row s%.%chop$F[$i++&7]%eg Replace each row by the removed last column This is therefore a left rotation. Very short but at the cost of using @F. To make sure that @F gets refilled from $_ each time I won't be able to use while, until, eval or do$0 for the loops but have to use redo. That costs a few bytes but less than having to do my own split $i/ >3 The previous regex replacement always returns 64 and each time through the loop $i is increased by 64. So if this division reaches 4 all rotations have been done /(.)((.|\H{6}|\H{9})\1|\H{7}\1.)\1/ This is the 4 regexes mentioned above ||redo Stop the loop if the regex matches or we rotated 4 times $_=$1?yes:n.o If the regex matched $1 will be one of the color digits (which cannot be 0) and this will assign "yes" to $_. If the regex didn't match in 4 times $1 will get its value from the last succesful regex in scope which will be the one from the rotation, but that one doesn't have any () so $1 will be unset. So in case there is no move $_ will be set to "no" (which needs to be constructed because "no" is a keyword) ``` [Answer] # Node.js - Naive solution - 905 bytes Well, no answers yet so I'll post a really naive solution in Node.js It goes through every possible move and then tests the resulting board to see if there's 3 in a row. Golfed (with google closure compiler) (some hacky stuff in there like !0 and !1; I'm not even sure what it did with my XOR swap) ``` Array.prototype.a=function(){for(var f=[],d=0;d<this.length;d++)f[d]=this[d].a?this[d].a():this[d];return f};for(var a=[],b=0;8>b;b++)a[b]=[];for(b=2;b<process.argv.length;b++)for(var c=process.argv[b].split(""),e=0;e<c.length;e++)a[b-2][e]=parseInt(c[e],10);function h(){for(var d=l,f=0;f<d.length-2;f++)for(var g=0;g<d[f].length-2;g++){var k=d[f][g];if(k==d[f+1][g]&&k==d[f+2][g]||k==d[f][g+1]&&k==d[f][g+2])return!0}return!1}function m(){console.log("yes");process.exit()}for(b=0;b<a.length;b++)for(e=0;e<a[b].length;e++){var l=a.a();0!=b&&(l[b-1][e]^=l[b][e],l[b][e]^=l[b-1][e],l[b-1][e]^=l[b][e],h()&&m(),l=a.a());b!=a.length-1&&(l[b+1][e]^=l[b][e],l[b][e]^=l[b+1][e],l[b+1][e]^=l[b][e],h()&&m(),l=a.a());0!=e&&(l[b][e-1]^=l[b][e],l[b][e]^=l[b][e-1],l[b][e-1]^=l[b][e],h()&&m(),l=a.a());e!=a[b].length-1&&(l[b][e+1]^=l[b][e],l[b][e]^=l[b][e+1],l[b][e+1]^=l[b][e],h()&&m(),l=a.a())}console.log("no"); ``` Note that I wrote this *all* on my mobile and don't have time to test it or anything. Comment if you see any bugs, I'll check it myself later. The pre-golfed human readable version ``` // set it up Array.prototype.clone = function() { var arr = []; for( var i = 0; i < this.length; i++ ) { if( this[i].clone ) { arr[i] = this[i].clone(); } else { arr[i] = this[i]; } } }; var board=[]; for(var i=0;i<8;i++)board[i]=[]; for(var i=2;i<process.argv.length;i++){ var row=process.argv[i].split(""); for(var j=0;j<row.length;j++)board[i-2][j]=parseInt(row[j], 10); } // function to test function testBoard(arr){ for(var i=0;i<arr.length-2;i++){ for(var j=0;j<arr[i].length-2;j++){ var val=arr[i][j]; if(val==arr[i+1][j] && val==arr[i+2][j])return true; if(val==arr[i][j+1] && val==arr[i][j+2])return true; } } return false; } // functions to exit function yay(){console.log("yes");process.exit();} function nay(){console.log("no");} // super slow naive solution time for(var i=0;i<board.length;i++){ for(var j=0;j<board[i].length;j++){ var newboard=board.clone(); if(i!=0){ newboard[i-1][j]=newboard[i-1][j]^newboard[i][j];// whoa, it's a newboard[i][j]=newboard[i-1][j]^newboard[i][j]; // cool algorithm newboard[i-1][j]=newboard[i-1][j]^newboard[i][j];// at least this // isn't all naive if(testBoard(newboard))yay(); newboard=board.clone(); } if(i!=board.length-1){ newboard[i+1][j]=newboard[i+1][j]^newboard[i][j]; newboard[i][j]=newboard[i+1][j]^newboard[i][j]; newboard[i+1][j]=newboard[i+1][j]^newboard[i][j]; if(testBoard(newboard))yay(); newboard=board.clone(); } if(j!=0){ newboard[i][j-1]=newboard[i][j-1]^newboard[i][j]; newboard[i][j]=newboard[i][j-1]^newboard[i][j]; newboard[i][j-1]=newboard[i][j-1]^newboard[i][j]; if(testBoard(newboard))yay(); newboard=board.clone(); } if(j!=board[i].length-1){ newboard[i][j+1]=newboard[i][j+1]^newboard[i][j]; newboard[i][j]=newboard[i][j+1]^newboard[i][j]; newboard[i][j+1]=newboard[i][j+1]^newboard[i][j]; if(testBoard(newboard))yay(); newboard=board.clone(); } } } nay(); ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 51 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „€¸…Ü#|€S2FЀü3ø€ü2s€ü4«sø}\«€`ʒÐg;iøćδåøPàë¢3å]gĀè ``` Port of the approach used by [*@Bubbler* in his APL answer](https://codegolf.stackexchange.com/a/205227/52210), so make sure to upvote him!! [Try it online.](https://tio.run/##HcetCsJQGIDhfm7DK/h@T7CbBauCCjKWDKsKw2IdZhERJsKMhhNM51syeBG7keNcep93W6zW@Salrrx0h2cMXXm382jXe4YTq/ramywMxWIIx6awsJ/Hpt/l52RVNs4ttMfvy2oLU7taE29k9SJrS3ukBEjAQOCAEBlYnLBXVE9OwYOq/EEMwOyQWMj7Hl5ZGNV5ES8q@gM) **Explanation:** ``` „€¸…Ü # Push dictionary string "no yes" # # Split it on spaces: ["no","yes"] | # Push all input-lines as list €S # Convert each line to a list of digits 2F # Loop 2 times: Ð # Triplicate the matrix € # For each row: ü3 # Create overlapping triplets ø # Zip/transpose; swapping rows/columns € # For each overlapping 3-sized column: ü2 # Create overlapping pairs s # Swap to get the initial matrix again € # For each row: ü4 # Create overlapping quadruplets « # Merge this list of 4x1 blocks to the list of 2x3 blocks s # Swap again to get the initial matrix ø # Zip/transpose; swapping rows/columns }\ # After the loop: discard the top item « # Merge the two lists together €` # Flatten it one level down ʒ # Filter this list of 4x1 and 2x3 blocks by: Ð # Triplicate the block g # Get its length (either 4 or 2) ;i # If this length is 2: ø # Zip/transpose; swapping rows/columns, # to make the 2x3 block a 3x2 block ć # Extract head; pop and push the remainder 2x2 columns and # first 2x1 column separated to the stack δ # Apply double-vectorized: å # Check if the value is in the list ø # Zip/transpose; swapping rows/columns, # so the checks per value are in the same inner list P # Check for both lists whether all checks were truthy à # And check if either of the two checks is truthy ë # Else (the length is 4 instead): ¢ # Count how many times each value occurs in the 4x1 block 3å # And check if the counts contain a 3 ] # Close both the if-else statement and filter g # Get the amount of remaining blocks Ā # Check that at least one block is remaining # (1 if truthy; 0 if falsey) è # And use that to index into the ["no","yes"] list # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„€¸…Ü` is `"no yes"`. [Answer] # Python3, 314B ``` import itertools as T,copy r=[] K=range(8) J=[list(input())for w in K] P=T.product f=lambda A:["yes"for b in[A[m][n:]for m,n in P(K,K[:6])]if b[0]==b[1]==b[2]] for i,j,x in P(K,K,[0,1]): t=j+1-x if i+x<8and t<8:B=copy.deepcopy(J);B[i][j],B[i+x][t]=B[i+x][t],B[i][j];r+=f(B)+f(list(zip(*B))) r+=["no"] print(r[0]) ``` Change the 8, the 5 on line 6, and the 8s on line 9 to handle arbitrarily large input sizes; also doesn't care what each value is, so you can feed it: ``` absdefgh sdkljahs lsdfjasd fjdhsdas dkjhfasd sdfhaskd sdkfhkas weriuwqe ``` and it will return `yes`. ### Annotations ``` import itertools as T,copy # itertools.product is going to save us lots of for loops r=[] # result K=range(8) # we can use range(8) everywhere, so this saves more than the usual R=range J=[list(input())for w in K] # input handling: keep everything as a length-1 string to avoid map(int,input()) P=T.product f=lambda A:["yes"for b in[A[m][n:]for m,n in P(K,K[:6])]if b[0]==b[1]==b[2]] # check the condition horiontally only. K[:6] is the same as range(5) # A[m][n:n+3] would be neater, but not actually needed for i,j,x in P(K,K,[0,1]): # <3 itertools.product! 3 for-loops without it. # NB we're only going right and downwards t=j+1-x if i+x<8and t<8: # don't want out-of-bounds errors at the edges B=copy.deepcopy(J) # preserve the reference array B[i][j],B[i+x][t]=B[i+x][t],B[i][j] # do the switch r+=f(B)+f(list(zip(*B))) # do the test. you could end up with lots of 'yes's in r. # zip(*B) takes the transpose, so that f checks the columns too r+=["no"] # happens to ensure that r is nonempty print(r[0]) # only prints no if r was empty before the last line ``` [Answer] # GNU sed 255+2 = 257B I thought this wasn't going to be as good as python but it is now :-/ I've been without internet access today so I occupied myself with solving this in sed :). Needs to be called with the -r flag, i.e. `sed -rf command.sed < input` so I added 2 to my score. ``` :a $!N s/\n/ /g ta :b /^((\w)(\w\2\2|\2\w\2|\w\2\w* \w\2|\2\w* \w\w\2|\w* (\2\w* \w* \2|\w* \2\w* \2|\w\2\2|\w\2\w* \2|\2\w* \w\2|\w\2\w* \w\2))|\w((\w)(\w* \6\w\6|\6\w* \6|\w* (\6\w \w\6|\w\6\w* \6|\6\w* \6))|\w(\w)\w* \9\9))/c\yes s/\w(\w*)/\1/g tb c\no ``` How it works: 1. Read the grid into a single line of space-separated characters 2. Use the motherload regex to find out whether there's a match in the first column\* - if yes, swap the entire line for 'yes' (ending the program) 3. Strip the first character from each column and goto 2 if we did 4. If we didn't (the line is empty) replace the whole line with 'no' [Answer] # Ruby, 201 bytes I was disappointed not to see any solutions to this great challenge that don't use a regex or brute force (although those are great), so I wrote one. It takes input on STDIN. The core bitwise arithmetic algorithm is derived from [this fantastic answer on Game Development Stack Exchange](https://gamedev.stackexchange.com/questions/2607/match-three-puzzle-games-algorithm) by @leander. ``` s=$<.read $><<(?1..?9).any?{|n|a=[0]*19 s.scan(n){i=$`.size a[i/9+1]+=2**(i%9) a[i%9+10]+=2**(i/9)} a.each_cons(3).any?{|x,y,z|q=y&y<<1 l=q<<1 q>>=2 y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}?"yes":"no" ``` ## Ruby lambda, 181 bytes Here it is as a lambda that takes a string and returns `true` or `false`: ``` ->s{(?1..?9).any?{|n|a=[0]*19 s.scan(n){i=$`.size a[i/9+1]+=2**(i%9) a[i%9+10]+=2**(i/9)} a.each_cons(3).any?{|x,y,z|q=y&y<<1 l=q<<1 q>>=2 y&(l<<1|q>>1)|(q|l|(y&y<<2)>>1)&(x|z)>0}}} ``` See it on repl.it: <https://repl.it/ColJ/2> ## Ungolfed & explanation ``` ->s{ (?1..?9).any? {|n| a = [0] * 19 s.scan(n) { i = $`.size a[i/9+1] += 2**(i%9) a[i%9+10] += 2**(i/9) } a.each_cons(3).any? {|x,y,z| q = y & y << 1 l = q << 1 q >>= 2 y & (l << 1 | q >> 1) | (q | l | (y & y << 2) >> 1) & (x | z) > 0 } } } ``` The code iterates over the digits "1" to "9." Each iteration has two discrete steps: The first step is board transformation, which you can see in the `s.scan(n)` block in the ungolfed code. It transforms the board into an array of 8 integers, one for each row, by treating matching digits as 1s and all others as 0s in a binary string. For example, take the row `12231123`. In the first iteration, this will become the binary string `10001100` (all 1s become—er, stay—1s and all other digits become 0s), which is the decimal number 140. In the second iteration the same row becomes `01100010` (all 2s become 2s and all other digits become 0s), or decimal 98. It simultaneously performs a second transformation, which is the same as the first but with the board rotated 90 degrees. This lets us use the same logic for making horizontal matches as vertical ones. For simplicity, it concatenates the two boards into a single long one with a zero at the beginning, middle (to separate the two boards), and end for padding. The second step is searching for possible matches, which you can see in the `each_cons(3).any?` block. The transformed rows (which are now 8-bit integers) are checked in (overlapping) groups of three rows (*x*, *y*, *z*) using bitwise arithmetic. Each group is checked to see if a match can be made in row *y*, either by shifting a piece in row *y* or by shifting a piece into *y* from *x* or *z*. Since there is a zero "row" before and after both the original and rotated boards' rows, we don't have to check if we're on the first or last row of a board. If no matches were found, it continues to the next iteration. ]
[Question] [ Imagine a two-dimensional array of boolean values, where the 0s represent squares of grass on a rectangular plot of land and the 1s represent fences. Write a function that accepts the 2D array as an input and determines whether you can travel from any one area of grass to any other area of grass, using only north/east/west/south movements, without running into a fence. If any area of grass in the array is fully enclosed by fences (meaning you can't travel N/E/W/S to reach every other area of grass in the array) the function should return false; otherwise, it should return true. Below are two sample arrays you can use as inputs, although your function should be able to handle not just these but any 2D array of boolean values: ``` 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 (should return true) 0 1 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 0 (should return false, since the middle 0 in the top row is fully enclosed) ``` Shortest working code wins. I'll pick the winner after either a week has passed or there have been no new submissions within 24 hours. [Answer] ## APL (39) ``` {∧/,⊃{⍺∨⊖⍵}/{⍵∨(∧\~⍵)∨⌽∧\⌽~⍵}¨s,⊖¨s←⊂⍵} ``` Usage: ``` board1 board2 0 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0 1 1 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 0 {∧/,⊃{⍺∨⊖⍵}/{⍵∨(∧\~⍵)∨⌽∧\⌽~⍵}¨s,⊖¨s←⊂⍵} ¨ board1 board2 1 0 ``` [Answer] # Mathematica, ~~60~~ 58 chars ``` f=Max@MorphologicalComponents[1-#,CornerNeighbors->1>2]<2& ``` --- Usage: ``` f[{{0, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 1}}] ``` > > True > > > ``` f[{{0, 1, 0, 1, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 1, 1, 0}}] ``` > > False > > > [Answer] ## Excel VBA, ~~305~~ 215 Bytes Yes, *haha VBA*, but the matrix nature of the problem suggets a practical solution in Excel might be interesting (Plus someone has already submitted an answer in my other languages!). Obviously VBA is not going to be the most succinct, but I think it's reasonable. This flood fills from an arbitrary starting point then checks if any "grass" left R is a worksheet range with 1's and 0's representing the fences and grass as defined in the problem. Bonus, the playing field doesn't have to be rectangular or even contiguous. ``` 0 1 1 1 1 0 0 0 0 0 0 1 1 1 1 ``` For example, would return False. The zeros on the right can't be reached from the zeros on the left. The irregular field doesn't break it. ``` Function F(R) L R, R.Find(0) F = Not IsNumeric(R.Find(0)) End Function Sub L(R, S As Range) If S Or IsEmpty(S) Then Exit Sub S = 1 L R, S.Offset(1, 0) L R, S.Offset(-1, 0) L R, S.Offset(0, 1) L R, S.Offset(0, -1) End Sub ``` **Some notes on the golfing.** I think some chars could be trimmed if the requirement was inverted in regards to 1 and 0, but not enough to make it worth inverting. VBA insists on a bunch a whitespace (a = b vs a=b), which doesn't help the char count. S needs to be explicitly declared as a range. If it's left a variant, it turns into a range value rather than a range. Maybe a better way to branch the flood? I couldn't come up with a loop that saved any chars to send it N/E/S/W Edit: rethougt the base case on the flood fill, managed to trim quite a bit off by checking if it's at a base case after recursion rather than preventing the recursion. [Answer] # Ruby, ~~202~~ ~~198~~ 193 ``` a=$<.read.split(' ').map(&:split) f=->x,y{a[x][y]=1 [[-1,0],[1,0],[0,-1],[0,1]].map{|o|d,e=x+o[0],y+o[1] f[d,e]if a[d]&&a[d][e]==?0}} f[i=a.index{|x|x.index ?0},a[i].index(?0)] p !(a.join=~/0/) ``` Does a flood-fill, then checks to see if there are any 0s left. [Answer] ## PHP 147 202 177 165 149 bytes **EDIT** I beat my gzip hack with a real php solution. A little long.... input as a text string, no spaces, rows delimited by newlines. It flood fills with `c`s and then checks to see if there are any zeros left. In the loop I use `exp` as a crude upper bound on the number of iterations required. I take advantage of the symmetry to handle the duplicate cases in less code ``` function f($s){$r=strpos;$n=$r($s,' ');$s[$r($s,'0')]=c;for(;$i++<1<<$n;)$s=strrev(ereg_replace('0(.{'.$n.'})?c','c\1c',$s));return!1==$r($s,'0');} ``` Here is an ungolfed test case: ``` <?php $s1="00000 01000 01111 00000 00011"; $s2="01010 01100 00000 00010 11110"; function f($s){ $n=strpos($s,"\n"); $s[strpos($s,'0')]=c; for(;$i<strlen($s);++$i) $s=strrev(ereg_replace( '0(.{'.$n.'})?c', 'c\1c' ,$s)); return!1===strpos($s,'0'); } var_dump(f($s1)); var_dump(f($s2)); ``` [Answer] # Python (219 bytes) Definitely not the shortest, but it's my first try here, so I'm proud of it: ``` def f(n): m=[int(c) for c in n if c!='\n'] for i in range(len(m)): if m[i]<1:m[i]=2;break g(m,n.find('\n'),i);return not 0in m def g(n,w,i): for x in i-w,i-1,i+1,i+w: if 0<=x<len(n): if n[x]<1:n[x]=2;g(n,w,x) ``` It's input should be a String of 0s & 1s where rows are delimited by a newline (\n) character. Example usage: ``` >>> f("00000\n01000\n01111\n00000\n00011") True >>> f("01010\n01100\n00000\n00010\n11110") False ``` [Answer] ## Python (196) Standard flood filling. ``` g=raw_input() m=g.find(' ') g=g.replace(' ','') V={} def D(V,x): if V.get(x,0)or g[x]=='1':return V[x]=1;[D(V,x+i)for i in 1,-1,m,-m if 0<=x+i<len(g)] D(V,g.find('0')) print len(V)==g.count('0') ``` Takes the matrix through STDIN with each row separated by a single space. For example "01010 01100 00000 00010 11110". [Answer] # Mathematica 53 ``` f=Max@(Symbol@@Names@"I*`i*B*l")[Image[1-#],0,1>2]<2& ``` It calls the internal function `Image`MorphologicalOperationsDump`imageBinaryLabel`, which is similar to `MorphologicalComponents`. ``` f[{{0, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 1}}] f[{{0, 1, 0, 1, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 1, 1, 0}}] ``` > > True > > > False > > > [Answer] # Matlab 45 ``` input('');c=bwconncomp(~ans,4);c.NumObjects<2 ``` [Answer] # PHP (286 chars) Way too long, I probably went the long long way. ``` function D($a){$x=count($a);$y=count($a[0]);for($i=0;$i<$x;$i++)$a[$i][-1]=$a[$i][$y]=1;for($j=0;$j<$y;$j++)$a[-1][$j]=$a[$x][$j]=1;for($i=0;$i<$x;$i++){for($j=0;$j<$y;$j++){if($a[$i][$j]!=1){if($a[$i][$j-1]==1&&$a[$i][$j+1]==1&&$a[$i-1][$j]==1&&$a[$i+1][$j]==1)return 0;}}}return 1;} ``` Non-golfed: ``` function D($a) { $x=count($a); $y=count($a[0]); for ($i=0;$i<$x;$i++) $a[$i][-1]=$a[$i][$y]=1; for ($j=0;$j<$y;$j++) $a[-1][$j]=$a[$x][$j]=1; for ($i=0;$i<$x;$i++) { for ($j=0;$j<$y;$j++) { if ($a[$i][$j] != 1) { if ($a[$i][$j-1] == 1 && $a[$i][$j+1] == 1 && $a[$i-1][$j] == 1 && $a[$i+1][$j] == 1) return 0; } } } return 1; } ``` [Answer] # C#, 235 Bytes ``` int[][]D;int w,h,n;bool Q(int x,int y){var r=x>=0&&x<w&&y>=0&&y<h&&(D[x][y]++==0);if(r){Q(x-1,y);Q(x+1,y);Q(x,y+1);Q(x,y-1);}return r;} bool P(int[][]B){D=B;w=D[0].Length;h=D.Length; for(int i=0;i<w*h;i++)if(Q(i%w,i/w))n++;return n==1;} ``` It tries to flood fill every cell in the board, it it makes only one flood fill returns true. ``` bool R( int x, int y) { var r = (x >= 0 && x < w && y >= 0 && y < h && D[x, y]++ == 0); if (r) { R(x-1, y); R(x+1, y); R(x, y+1); R(x, y-1); } return r; } public bool Do() { D = Board1; w = D.GetLength(0); h = D.GetLength(1); for (int x = 0; x < w; x++) for (int y = 0; y< h; y++) if (R(x, y)) n++; return n == 1; } ``` [Answer] # Python 2.X + 3.X: 335 chararcters Golfed: ``` def f(n): x,y=0,0 z=lambda x,y:y<len(n)and x<len(n[0])and n[x][y]!=1 while not z(x,y): y+=1 if y==len(n): y=0 x+=1 if x==len(n[0]): return False t=set([(x,y)]) v=set() while t: (x,y)=t.pop() v|=set([(x,y)]) if z(x+1,y): t|=set([(x+1, y)]) if z(x,y+1): t|=set([(x, y+1)]) return len(v)+sum(map(sum,n))==len(n)*len(n[0]) ``` Ungolfed: ``` def f(n): """In the following filed, starting from a 0: is it possible to get to every other 0? >>> f([[0,0,0,0,0],\ [0,1,0,0,0],\ [0,1,1,1,1],\ [0,0,0,0,0],\ [0,0,0,1,1]]) True >>> f([[0,1,0,1,0],\ [0,1,1,0,0],\ [0,0,0,0,0],\ [0,0,0,1,0],\ [1,1,1,1,0]]) False >>> f([[1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,1]]) False >>> f([[1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,1],\ [1,0,1,1,1],\ [1,1,1,1,1]]) True >>> f([[1,1,1,1,1],\ [1,1,1,1,1],\ [0,1,1,1,1],\ [1,0,1,1,1],\ [1,1,0,1,1]]) False >>> f([[1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,1],\ [1,1,1,1,0]]) True """ x, y = 0,0 isValid = lambda x,y: y<len(n) and x<len(n[0]) and n[x][y] != 1 for i in range(len(n)*len(n[0])): x = i%len(n) y = i/len(n) if isValid(x,y): break while not isValid(x,y): y += 1 if y == len(n): y = 0 x += 1 if x == len(n[0]): return False # Problem is not clearly defined here toGo=set([(x,y)]) visited=set() while toGo: (x,y) = toGo.pop() visited |= set([(x,y)]) if isValid(x+1,y): toGo |= set([(x+1, y)]) if isValid(x,y+1): toGo |= set([(x, y+1)]) return len(visited)+sum(map(sum,n)) == len(n)*len(n[0]) if __name__ == "__main__": import doctest doctest.testmod() ``` ]
[Question] [ Create a program that prints the MD5 sum of its source in the form: ``` MD5 sum of my source is: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` No cheating - you can't just read the source file and compute its sum. The program must not read any external information. Of course you can use a MD5 library available for your language. [Answer] ## Python 2, 91 bytes ``` s="import md5;print'MD5 sum of my source is: '+md5.new('s=%r;exec s'%s).hexdigest()";exec s ``` Using the Python quine variant which doesn't require repeating everything twice. Tested on [ideone](http://ideone.com/XAoU9K). [Answer] ## Python 157 149 ``` r='r=%r;import md5;print "MD5 sum of my source is: "+md5.new(r%%r).hexdigest()';import md5;print "MD5 sum of my source is: "+md5.new(r%r).hexdigest() ``` ### Output: ``` MD5 sum of my source is: bb74dfc895c13ab991c4336e75865426 ``` Verification at [ideone](http://ideone.com/QKmFGW) [Answer] # Perl + Digest::MD5, 89 bytes ``` $_=q(use Digest::MD5 md5_hex;say"MD5 sum of my source is: ",md5_hex"\$_=q($_);eval");eval ``` No TIO link because Digest::MD5 is not installed on TIO. Note that this requires the language conformance level to be set to 5.10 or higher (`-M5.010`; this doesn't carry a byte penalty according to PPCG rules. ## Explanation This is yet another "print a function of the source code" challenge, meaning that it can be trivially solved via a universal quine constructor. ### Universal quine constructor ``` $_=q(…"\$_=q($_);eval");eval ``` We use the `q()` string notation (which nests) to initialize `$_`, the "default" variable that Perl uses for missing arguments. Then we `eval` with a missing argument, so that the string inside the `q()` gets evaluated. The string inside the `q()` is a description of how to create the entire program; we specify the rest of the program literally, then use an unescaped `$_` to substitute the whole string in for the inside. The technique thus creates a string with identical contents to the entire program's source; we could print it to produce a quine. We can also do other things to it first, though, making a universal quine constructor. ### The rest of the program ``` use Digest::MD5 md5_hex;say"MD5 sum of my source is: ",md5_hex ``` Very simple: import an MD5 builtin, then print the fixed string specified in the question (it's not worth compressing it, I believe that in Perl the decompressor would take up more space than just stating the string literally), and use the MD5 builtin on the string we got via the universal quine constructor. [Answer] # Node.js REPL (version 0.9.3), ~~96~~ 94 bytes Using the last version of Node.js that existed when this challenge was posted. I've tracked down the [November 9, 2012 documentation](https://github.com/nodejs/node/blob/f3621359f4866c8ed732a48ece4049cc6e9a8b91/doc/api/crypto.markdown) for Node.js' crypto module, and it did support all the functions I've used here back in the day. ``` function x(s){return require("crypto").createHash("md5").update(s+";x(x)").digest("hex")};x(x) ``` If you don't feel like [installing](https://nodejs.org/download/release/v0.9.3/) an antique version of Node.js just to test this code, rest assured it also works in the most recent version. ## Node.js REPL (version 7.0.0), 81 bytes And here is a version using ES6's arrow functions. ``` x=s=>require("crypto").createHash("md5").update(`x=${s};x(x)`).digest("hex");x(x) ``` **Edit**: thanks to [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg) for pointing out an error in my Node.js 0.9.3 version, fixing which saved two bytes. ]
[Question] [ Given a rod of length n inches and a list of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) ``` length | 1 2 3 4 5 6 7 8 ------------------------------------------- price | 1 5 8 9 10 17 17 20 ``` And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1) ``` length | 1 2 3 4 5 6 7 8 -------------------------------------------- price | 3 5 8 9 10 17 17 20 ``` The input will be given in this form: The prices will be in ascending order, index starting at 1 to n separated by a space. `{price of length 1} {price of length 2}.... {price of length N}` The output should be the maximum Obtainable Value `{maxVal}` a Non-Golfed solution to this, in Python is: ``` INT_MIN = -32767 def cutRod(price, n): val = [0 for x in range(n+1)] val[0] = 0 for i in range(1, n+1): max_val = INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i-j-1]) val[i] = max_val return val[n] arr = [1,2,3,4,5,6,7,8,9,10] size = len(arr) print(cutRod(arr, size)) ``` Test cases: ``` | Input | Output | |:------------------------------------------------------------------------------:|:------:| | `1 5 8 9 10 17 17 20` | `22` | | `1 3 2 5 6 7 4 8` | `12` | | `5 6 3 2 4 6 8 7 3 4 6 2 12 4 5 7 4 3` | `90` | | `23 2 3 45 34 23 3143 13 13 213 1321 3123 12 312 312 31 3 213 432 41 3 123 43` | `9475` | ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` LŒṗịµ§Ṁ L length Œṗ integer partitions ị index §Ṁ sum each and take the maximum ``` My first jelly answer, so there can probably be improvements made. [Try it online!](https://tio.run/##y0rNyan8/9/n6KSHO6c/3N19aOuh5Q93Nvz//z/ayFjHSMdYx8RUx9hEB8gxNjQx1jEEIyMwZWQIFANKGBqBaCjWgciaGBvpmIA4IAUmxrEA "Jelly – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 57 bytes ``` a=>a.map((v,i)=>a[i]=w=a.map(u=>v=(u+=a[--i])>v?u:v)|v)|w ``` [Try it online!](https://tio.run/##rZNNb4JAEIbv/Iq5uSgfLgtVaRZPPfTUQ4/WZAlFuw0CkQVNxN9uZ1Ga9NDioZslsx8zzzvZvHzGTVwle1kqOy/e08uGX2Iexc4uLglpLGniZiXX/MCvZzWPGk7qCY9Xti3XZtQs67AxW5yHi0orlcRVChw2dZ4oWeRATDiBOzZauGs852Wt7sps4aVWOrk12tD@1xH2wLAd6ltQCGAOC6BToDM9vakY6BuE52FOO/wmSGfgocIDzMCHuRh8Eyz5iy00SiN9jHOEsm7lAdVHQafCxK/sxfTGFp6GYHEAzAfcMOozoN30uuBh6xQvEMy@P7je@gzV9EYn@KiHwIU/C3BhjF04O6p4VXuZb4npYNxhqMpMKjJ6y0e4zmSSEmaBTc1Hozedsyn2T3HyQTKZowMjOBlZqmAltaMsSI9lmqg1WlPfo5cVprrCGS@Fu0WMzi2uhkL3kq7qpkQ7pb4FwA70n3DUGpOjibVJkVdFljpZsSU9g3OYXDV/UKybCFad8bt8AQ "JavaScript (Node.js) – Try It Online") As the question is a [knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem). Let \$ val\left[i\right] \$ be the price of segment of length \$i\$. We have: $$ dp\left[0\right] = 0$$ $$ dp\left[i\right] = \max\_{j=1..i} \left\{ val\left[j\right] + dp\left[i-j\right] \right\} $$ And \$dp\left[len\right]\$ is the answer. To golf more bytes, we slightly modify the transition equation into $$ dp\left[i\right] = \max\left\{val\left[i\right], \max\_{j=1..i-1} \left\{ dp\left[j\right] + dp\left[i-j\right] \right\} \right\} $$ We use \$a\$ for both \$val\$ and \$dp\$ during iteration. When try to calculate \$a\left[i\right]\$, all values \$a\left[0..i-1\right]\$ equals to \$dp\$ and all other values equals to \$val\$. Also, our array is 0-indexed instead of 1-indexed. So we modify the equation into $$ a\left[i\right] = \max\left\{a\left[i\right], \max\_{j=0..i-1} \left\{ a\left[j\right] + a\left[i-j-1\right] \right\} \right\} $$ Use the feature that when access values out of array range, `undefined` is returned. And mathematics operation on `undefined` results `NaN`. `NaN>v` will also be `false`. We can ignore \$j=0..i-1\$ part from \$\max\$. And the code is shown above. Ungolfed C program as reference: ``` int f(int* a) { int i, j, val; // before loop: a[i] = price of length (i+1) segement // after loop: a[i] = max sum price of cutted length (i+1) segment for (i = 0; a[i]; i++) { // before loop j // a[i] = price of length (i+1) segment // = price if do not cut the segment for (j = 0; j < i; j++) { // price when cut the segment into two parts with length (j+1), (i-j) val = a[j] + a[i - j - 1]; // we prefer higher price if we can if (a[i] < val) { a[i] = val; } } // j } // i return a[i - 1]; } ``` [Try it online!](https://tio.run/##hVPbcpswEH3vV5xJJjNQyw0YkqbB7Y@4flBAGDG25MFy3ZkM357uShDl8lBmdGH37NnDkaiXu7p@udam3p8bhfXJNdp@6369aOPQJjR/hUzx/AXgiBboBf7IfUWB21s8qdYOCntrj4@QG73FTxwHXSvYFntldq5Dohd5ipPaqYMyLtTJ1qnhfdlB/sXpfIjl9dk51XximUioL8WoLqs8QwW9WAShH5Whn4P/Uzhxe6x/Zqxu0VgY61gVXKfeob2WPmjpsYamJYrxbIHm0inzkYF9tXAXi6Mc3AkXTYpmYT0JE6Rv2acTF3lPjeSm32LB34MltVwi31ax2UVRP9WSw53edbS8fgRlamkmJL0n3pE1s0a5mH2azpmf0a8js7ObfqNpMyh3HswkhEWM/uYcpDZJvDZms93kWcacockzcoE7gQeBHwJ5RuN7GKsMo4iYgiIeeS9A2ZJKYj6EA6T0@wePKuZXiuchdzeXF7F8FSoZTemCkhwp8pLmfBqrsFmxlJzTzFe8mUJ/RpUFtwoBD2WezDs3Vq83lg883BRNvpfztZ2dn@ymAzOuTa5umt/mStCPaOhE0pRpxuh6xnb/Aw "C (gcc) – Try It Online") Above C code may golf to [81 bytes](https://tio.run/##TVFtT4MwEP7Or7jMuFBbTEuZzhT8I9gPBIaWaGeQ8YXhX8c7umWS3Ovz3HNw1Ml7XS@LE50YTRs7PzxUbGqPfeyKrpCmS5LzuSq7gnNnTVU6m4/bbUxJMTI2FohZjiX/7ayh0iXKmnm5c77@PDUHyH@Gxh0fP16jCNXhq3I@ZjBFAFT60pZKSgvF2gKYQAnYCdgLeBGgJNpzsFTCLG4cjZ2V@SQA0QxHbnhoB0q25vuVpa8l9lXAdtdxfRtPwySxEdYIUkerDL26WBqSlF5FEUx6@p8L@4mVaVoVGiuVdPBrcNts0OG5gU4PDs8gDYYcMgyc46Hg8kQhfPdIbOPNffPmNwLa2OOvYIxkSK8/DKfeo0g0R8sf), but still longer than JavaScript implementation. :( --- * -5 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) [Answer] # JavaScript (ES6), 78 bytes *Saved 1 byte thanks to @Davide* ``` a=>(m=F=(n,i=0,s=0)=>n?i>n||F(n+~i,i,s+a[i])|F(n,i+1,s):m=s<m?m:s)(a.length)&m ``` [Try it online!](https://tio.run/##bY3NisIwFIX3PsiQ0KM0P9Uqpu58CXERtGqkSYeJuJJ59XpvBTcKN9yf852Tq7/7fPgLv7dp6o/tcHKDd42IbutEQnAlsiula9ImNOnx2IpU/AcE5MLvwl7yAaFQyHIVXV7HTVxlKfysa9P5dpE/cTj0KfddO@v6sziJnUKFGkuoEmrBpcu9lJMPykATOccCFvUXgjVmLPWaKDNOGopP1WgzX2yaPcRWMBa0GGUN1Fh6bJq@ViRQjnk/vFRrKJwXBizHD08 "JavaScript (Node.js) – Try It Online") ### Commented ``` a => ( // a[] = input array m = // initialize m to a non-numeric value F = ( // F is a recursive function taking: n, // n = integer to be partitioned i = 0, // i = integer to be subtracted from n (-1) s = 0 // s = price sum ) => // n ? // if n is not equal to 0: i > n // abort if i is greater than n || // otherwise: F( // first recursive call with: n + ~i, // n - i - 1 i, // i unchanged s + a[i] // s + i-th price ) | // F( // second recursive call with: n, // n unchanged i + 1, // i + 1 s // s unchanged ) // : // else: m = s < m ? m // update m to max(m, s) : s // )(a.length) // initial call to F with n = length of a[] & m // return m ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~98~~ 89 bytes -9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` m;*n;l;g(N,L)int*N;{n=N;l=L;f(0,m=0);}f(t,s,i){m<t?m=t:0;for(i=0;++i<l-s;f(t+n[i],s+i));} ``` [Try it online!](https://tio.run/##ZZDhbsIgEMe/@xTEZQnYc6GAU0e7vYDxBbQflmodSYtLi5@aPnt3h4tdMgIc3P/HHXfl8lKW45PzZX07nVnWhZO7vny9j41deFvbC9/DTjgfFnvb@3xv63xnKy6hyaWwQ8UDdOBE32Tho8nDm7TVteUulzZJXFYvO4RD4g@ugC5xAp@MGIw1n85zwfrZjOEgjz@Y4qBMwXL0kjNuvYQUVrCBLaR4XNNUcoBJ1KAQeIU1GNhMArlIMmg3KOp4UpCSaxVpPdGKUERWoA1ddGo0pHGqaBQmSlHA5/qx4K4ajTHpQoDRQww62KkIKq8@U4FU3JZq2YIyf5HYNMQcEtKiyZhBkyTitxsPksaFx4ZSTFcI@x/4bjFYxefPp6OfA2uQuf9qytiew631mGw2jD8 "C (gcc) – Try It Online") ### Explanation That's the explanation of a previous [illegal version](https://tio.run/##ZZDdToQwEIXveYpmjQnIrCltccGCPghyYfjRJtA1wF4Rnh1nioKJTcu053xMO1OdP6pqvTO26m51w7Jxqs318fNl7XXrW@hggjEwdnqweu6z6bXPp2eu2@vgo8hMznUYmqw7j794aAtTwhiaINDLSlD/bqwfsNnzGA5SbKHKQqiS5aiS6D4zhwhiSCCFCLcXmoIvcJgSBAJPcAEFyWGQRJbCmKAp3U5ARFLsaHnQglBEYpCKDjJSEiI3hQsCL4rQwN/lvmBzlcScdCBAycUlXfRRBJXXNVQgFZdSLSkI9RfZm4cE1xgypjCEYfDTjZ10tO8aSjkxcOCB/g99DZiw9U/39Zs9AeuR2b1@u2Z76fGKoZlug0XHW9Zv "C (gcc) – Try It Online"), but not so much has changed, so the explanation is still valid. The function `f()` call itself recursively and into a loop, so that for each index of the loop it starts a whole new loop, and for each index of this other loop it launches a whole new loop and so on. Each branch stops when the sum of the lengths of the pieces of that particular branch reaches the length of the rod. Every time, before to enter a new branch-generating loop, the current maximum value possible is compared with that of the branch and eventually updated to a greater value. ``` m; // variable used to store the maximum value possible f( // this is a recursive function creating all the possible combinations of the pieces n, // it takes: an array of integers l, // the length of the array t, // the total price of the current branch s) // the sum of the inches virtually sold till now int*n;{ m<t?m=t:0; // if the maximum value is less than the total of a branch, update it for(int i=0; // `i` represents the inches of a particular piece ++i<l-s; // untill `i` is less than the maximum length minus the current sum of the inches f( // f() calls itself with: n, // the same array l, // the same length t+n[i], // the current total price plus the price of this one more piece s+i) // the current sum of the inches plus the length of this one more piece ); // end of for() loop } // end of function ``` [Ported to JavaScript](https://codegolf.stackexchange.com/a/218622/100356) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` Max[Range@#~FrobeniusSolve~#.#2]& ``` [Try it online!](https://tio.run/##PYxPC4JAEMXvfo0FT1O4O2vaofDUqSDyKB42Wf9ArmAWgehXtxmDYIaZ93tvpjVDbVszNIVZysNyMZ/sZlxlEzGf@u5uXfN6pt3jbWexFSr3l2vfuCETm2OZna2rhjoRIPLcn9PCuHn0RgkhxLAHGYCMuFQwAWMERdYOItAQM2LBUNOMCeO6KZCMwjWHnFMcIjME1EACpUaQa6l1KHouyaBD/Df8XI30jQUHNE7etHwB "Wolfram Language (Mathematica) – Try It Online") Input the length and list of prices. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 51 bytes ``` f=lambda l,n:n and max(x+f(l,n:=n-1)for x in l[:n]) ``` [Try it online!](https://tio.run/##hVHNboMwDL7zFL6RaKnU/HS0ldiLMDQxCGo1mkbAJDbEszM7KVJvOziyvx87cfzPeLk7ffT9urZ5V90@mwo64c4OKtfArZrY9NIyQnK3k7y99zDB1UFXnF3J19EO44fvr7UdIAeWABRSwEHAUcBJgNxjZDHUvhTE63949KNEBdWrAGQMyiMXoUibkB@DQm8l4jJyh82qo1VFFymR0kgQoqXBUz5CxUTRFSTR1Es/HXE2qYymMREIUkNzeGInb@vRNrQNhRJlYpcTvvRksgNP6outv2xPgvT9W2WmTgWETOqUJ7RhLyzt@Pfq2dOCBWzN@RlfBOCwR2cd8zyU9AMt88LFEk1uZG06@0XA7BbYvcE8LDA/LlDYPB/KJeXrHw "Python 3.8 (pre-release) – Try It Online") Same length: **51 bytes** ``` f=lambda l,n:max([0]+[x+f(l,n:=n-1)for x in l[:n]]) ``` [Try it online!](https://tio.run/##hVHNboMwDL7zFL6RqKnU/DBoJfYiDE0dDSoqTSNgEhvi2ZlNitTbDo7s78dOHP8zXB9OZ75bljpvz/evyxla4U7388iKQ7krxl3NCMjdXvL60cEIjYO2OLmy5Mtg@@HTd01le8iBRQCFFJAIyAQcBcgDRhpCHUpBvP6HRz9K1Kp6E4CMQXngAhRos@bZqtBbibgMXLJZdbCq4CIlUhoJQrQ0eMpnqJAouoIkmnrplyPMJpXRNCYAq9TQHB7Z0dtqsBfahkKJMqHLEV96NGnCo@pqq5vtSBB/fKvUVLGANZM65hGt2AtLS/5tPHtZsICtOT/hiwAc9mitY56vJf1AzbxwoUSTG1gdT34WMLkZ9u8w9TNMzwsUNs/7co758gc "Python 3.8 (pre-release) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~82~~ 79 bytes ``` (n,m=0)=>(g=(t,s,i=0)=>{m<t?m=t:0;while(i<n.length-s)g(t+n[i],s-~i++);})(0,0)|m ``` [Try it online!](https://tio.run/##bY3djsIgFITv90kgnRr@utZV1gcxXhitFdPSjRC9cPXV6wETbzQ55DDMN8Nxc96E7cn9xdIPu2bc25F59FZw@8tayyICXFbXfhGXvY0/Yn45uK5hbuEnXePbeCgDb1ks/MqtEcq7Kwo@v3EmIPh/P24HH4aumXRDy/ZsJVGhxgxSQE7TKLHm/OuN0lBEfmMKg/oDkbzEGNo1UTrfFGR6qnJMf4iplCG2gjYgoaXRkHlUXoq@lmRQj34dPF2jqTyJBJhUPz4A "JavaScript (Node.js) – Try It Online") ### That's my first JavaScript answer!! Made translating [my C answer](https://codegolf.stackexchange.com/a/218559/100356). The algorithm is the same (you can read the explanation from there if interested). [Answer] # [Wenyan Language](https://wy-lang.org), 2178 bytes I know what you're going to say -- **WHAT ON EARTH IS THIS?!** ``` 吾有一術名之曰「獲取」欲行是術必先得一物曰「對象」一物曰「域」乃行是術曰乃得對象[域]是謂「獲取」之術也吾有一術名之曰「賦值」欲行是術必先得一物曰「對象」一物曰「域」一物曰「值」乃行是術曰乃得對象[域]=值是謂「賦值」之術也減零以三萬二千七百六十七名之曰「極小」吾有一術名之曰「分桿」欲行是術必先得一物曰「物價」一物曰「桿數」乃行是術曰吾有一列名之曰「遞歸」昔之「索引」者今零是矣恆為是吾有一爻名之曰「甲丙」若「索引」不大於「桿數」者昔之「甲丙」者今陽是矣云云若「甲丙」等於零者乃止云云充「遞歸」以零加「索引」以一昔之「索引」者今其是矣云云昔之「索引」者今一是矣恆為是加「桿數」以一吾有一爻名之曰「甲申」若「索引」小於其者昔之「甲申」者今陽是矣云云若「甲申」等於零者乃止云云吾有一物曰「極小」名之曰「最大」昔之「索引其二」者今零是矣恆為是吾有一爻名之曰「亥卯」若「索引其二」小於「索引」者昔之「亥卯」者今陽是矣云云若「亥卯」等於零者乃止云云吾有一術名之曰「丁戊」欲行是術必先得一物曰「a」一物曰「b」乃行是術曰乃得Math.max(a,b)是謂「丁戊」之術也施「獲取」於「物價」於「索引其二」名之曰「子甲」減「索引」以「索引其二」夫「遞歸」之其加「子甲」以其名之曰「午申」施「丁戊」於「最大」於「午申」昔之「最大」者今其是矣加「索引其二」以一昔之「索引其二」者今其是矣云云施「賦值」於「遞歸」於「索引」於「最大」噫加「索引」以一昔之「索引」者今其是矣云云施「獲取」於「遞歸」於「桿數」。名之曰「支子」乃得 「支子」是謂「分桿」之術也噫吾有一列名之曰「桿長」吾有一數名之曰「桿數」夫「桿長」之長昔之「桿數」者今其是矣施「分桿」於「桿長」於「桿數」名之曰「卯地」吾有一物曰「卯地」書之 ``` Expect an input at char 678: ``` ... 吾有一列名之曰「桿長」(INPUT GOES HERE!)吾有一數 ... ``` Using the format: ``` 充「桿長」以(some number)以(some number)以(some number)以...... ``` Well I know it's difficult for those who don't understand Chinese. Fortunately the language compiles into equivalent JavaScript. I'll show it below for you to understand: ``` var 獲取 = () => 0 獲取 = function(對象) { return function(域) { return 對象[域] } } var 賦值 = () => 0 賦值 = function(對象) { return function(域) { return function(值) { return (對象[域] = 值) } } } // Notice that functions above are only for convenience, because all function calls in this language is curry. var 極小 = 0 - 32767 // The main function var 分桿 = () => 0 分桿 = function(物價) { return function(桿數) { // The above two lines is to make the function a curry. var 遞歸 = [] 索引 = 0 while (true) { // In this language we only have while-loops, but we can use 'if' and 'break' to control it. var 甲丙 = false if (索引 <= 杆數) { 甲丙 = true } if (甲丙 == 0) { break } 遞歸.push(0) 索引 = 索引 + 1 } 索引 = 1 while (true) { var 甲申 = false if (索引 < 杆數 + 1) { 甲申 = true } if (甲申 == 0) { break } var 最大 = 極小 索引其二 = 0 while (true) { var 亥卯 = false if (索引其二 < 索引) { 亥卯 = true } if (亥卯 == 0) { break } var 丁戊 = () => 0 丁戊 = function(a) { return function(b) { return Math.max(a, b) } } var 子甲 = 獲取(物價)(索引其二) var _ans5 = 索引 - 索引其二 var _ans6 = 遞歸[_ans5 - 1] var _ans7 = 子甲 + _ans6 var 午申 = _ans7 最大 = 丁戊(最大)(午申) 索引其二 = 索引其二 + 1 } var _ans10 = 賦值(遞歸)(索引)(最大) 索引 = 索引 + 1 } var 支子 = 獲取(遞歸)(杆數) return 支子 } } var 桿長 = [] // There should be some input... 杆數 = 桿長.length var 卯地 = 分桿() console.log(卯地) // Program complete ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gÅœ<èOà ``` [Try it online](https://tio.run/##yy9OTMpM/f8//XDr0ck2h1f4H17w/3@0oY6pjoWOpY6hgY6hOQgZGcQCAA) or [verify all test cases](https://tio.run/##PY5BCgIxDEWvMsz6L5qmdSoIs3HvAYYuFERcuRCEOYAeQC/g0nsUL@JF6k8FISXJ@79JTuft7rivl3nsu8/t3vXjvK6Hcn0/VuW1Kc@KOk2CiIQlxEEGC@8ySBWeygIDAhKJ1cYCcyLVVnmIodhsSps3D7UIDWCjEhTSwrfkOVoo8J/@H35qUA6zxgxB2x2tddwgttUucSQRLucv). **Explanation:** ``` g # Get the length of the (implicit) input-list Åœ # Get all lists of positive integers that sum to this length < # Decrease each by 1 to make it a 0-based index è # Index those into the (implicit) input-list O # Sum each inner list à # Pop and push the maximum # (after which it is output implicitly as result) ``` [Try it online with step-by-step output.](https://tio.run/##NY9NSgMxFMf3nuIxK4UIHUH8QCkFNwWhm@7ERTp9nXmaSYZ5b9p6AE/gBVx6Ag@geK7xJWkhgcD/65fAdkU4jsXcd4PcQmHuf76nJ8Uj@loaCBuQBoGOYp3VmXPgiIWjoQtMQtvoEqyxZ41YAR5akKBvYnCpLRb8vv995I4HrHq0jIC2amD1BmXU77I492vcZ0VbQ4ZoO0cVSaY5j/up8StHlvYVky8OK9Yh7LGHo3VxoPdrJbJK/DKwpExr99TmXAbWBJzuGood@suh1ys6e5YmP804PpXm0lybG1NOTHkVz8Xk@R8) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` FA⊞υ⌈⊞OE⮌υ⁺κ§υλιI⊟υ ``` [Try it online!](https://tio.run/##PUs5DsIwEOx5hcu1ZAofVFSIKkWERRulsIJRInLJR5Tfm7WDKHZ2zq43rlvMmNJ7cQSqeY0BKCU6@h4iI7XZhylOkPVjtc6ExUFtVnjazTpvIVJG9Bg9fBi5hWp@2T3vRkoxGBCvJ@2GOcDd@AB6WXGBZkpNIyQjghFEdcGnUCGXXCHy34mDCJ6DHHNR2B/KvrSUREMdRqkq2bbpvI1f "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @tsh's approach. ``` FA ``` Loop over each input element. ``` ⊞υ⌈⊞OE⮌υ⁺κ§υλι ``` The value of each length is the maximum of the current input element and the array sum of the array of values so far with its reverse. This is pushed to the array of values. ``` I⊟υ ``` Output the last value. [Answer] # [Python 3](https://docs.python.org/3/), 103 bytes ``` lambda p,n:max(map(sum,d(p,n))) d=lambda p,n:[[p[n-1]]]+[m+[p[i]]for i in range(n-1)for m in d(p,n+~i)] ``` [Try it online!](https://tio.run/##hVJNb4MwDL3zKzztAFFTqRC6fkjsvtMuu1E0UQgragkRpFo7xP46s5NW6m0HB/u95w/Z6Ks5tEpMVbKbTnmzL3PQXG2b/BI0uQ76c8PLABHGmFcmD4o01amah1mWzdJmhkGdZVXbQQ21gi5XXzJAmhHUEGSrzH5rlk1G9uZTd3Uhe0gg8ADSkMOSw5rDhkO4QFs5ixYZJ178w2M@SiKreuGATIxyxznI0bH111Yh7iHioeOW91ThUiOXRUqkBBKEiDDGN7xZ5JyIRgiJplri4XG9SRULauMAK42pD/PkRcvCyJK2EaEkil2VzYLBM37i1ZLBx9s7mLrBnbVnA60Cc5BwynvyJewRqw18t92xJ7K5IqdNq5@84iCLo@youL87R6u48DlYLxQ@8@hCmku60U@tg4fjcLgPxra4DQCFNU5SBZrZkK5X2Z/DhpikTFD5gx45DGqE@SsM/QjDbYBUJkmfjT6b/gA "Python 3 – Try It Online") Inputs the prices as a list of integers along with the length of the rod. Returns the maximum price you can get. Uses a variation of the integer partition function I wrote for my [Landau logarithm](https://codegolf.stackexchange.com/q/217536/9481) [answer](https://codegolf.stackexchange.com/a/217602/9481). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` eSmsm@Qtkd./l ``` [Try it online!](https://tio.run/##K6gsyfj/PzU4tzjXIbAkO0VPP@f//2gjYx0FIx0FIGliCqRMgDwg29jQBEgaQrERhGFkCJIASRsagVlwAqwfrMrEGChgAhEAKzUxjgUA "Pyth – Try It Online") The obvious approach: try all integer partitions, compute their value, and take the maximum. I spent a while trying to use the `M` or `L` builtins, but they didn't end up being shorter. [Answer] # [Julia 1.0](http://julialang.org/), ~~47~~ 36 bytes port of [xnor's answer](https://codegolf.stackexchange.com/a/218595/98541) ``` n*l=max(0,(1:n.|>x->l[x]+(n-x)l)...) ``` [Try it online!](https://tio.run/##hVHbboMwDH3nK6wKiaR1EbkwyiT4EYamimYrG8sQUAlN@3fmECr1bQ@O7HOxneTj1rVnMS@L3XfF13lmCTLxbOPfcj6WXTXXB2aPM@94HMd8mcw4vfZD25gRCmABQCUQUoQTQo4gEorMh0xqdLz6hyc/SeSqekIgRpPccx7ytF7z06pQ95Jw4bn0blXeKr3LKYlSRDhECU2n2EL6RLoVhKNdL/Vw@NlOpZUb44FVqt0cHpi5N81kLu41JEmk9l1yummus5QHzdU0n2ZwgujlJjPdRAhrJlTEg7fvAViPhkNr4aft2cMTI9zbc7oSgKUmnbHv05X1HnG/sGcWt5Jsduos24U9hqQuIRxhh7DtUDFTFCM/iJoWt5flDw "Julia 1.0 – Try It Online") # [Julia 0.4](http://julialang.org/), 42 bytes or with Julia 1.0+ and Combinatorics.jl ``` f(p,n)=maximum(x->sum(p[x]),partitions(n)) ``` [Try it online!](https://tio.run/##hVHbbsIwDH3vV1gIiUTLJHLpoA/lRxiaqhIgG4SoSaVqP985MUi87cGJ7XOO7Tjf49V183xiQXje3rrJ3cYbm953Ea@wnw5chG5ILrm7j8xzPicb01cYXG8jtMAqgL0UUAvYCmgEyDXahkytDyLj@h8c9UhRhfUhABGDdMIoRbAp/rYw9DPEvCSsfko1SRWpMhMhjUDOaGnwlA9T5Kg8gsxwrqVfDuqdWUbnNpQoVJP78MpOwfbJHvM2FFKUoSoNvrQxm5pX/cX2P3bIhNXnqDamXwkontQrXp3uA@D@LQfn4dcF9rJiAc/yHJ8E4LHI1fpzurBAmfwL9H0lRJlPV88WyyCWyN7BMsJCwGOGPbNtG/mbPODg/jj/AQ "Julia 0.4 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 98 bytes Port of [@tsh's Javascript answer](https://codegolf.stackexchange.com/a/218557/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##ZZHBTsMwDIbvfQpzi7UMNU0HY10mceTACXFCO4SuHYlKhrqqCFV99uIkG5pGJTuO/dn@lR5L3ejp8G6rsoNnbRwMSdLrBuoVe2xb/fP25Lqt2pBHUJNWm6HXLRhuea/S4vvDNBXTzOCNSnGwfym7Njj0SjOLMyrP7VxgYeqArnv0h@oLO1NiLEzwnhI4TgC7qoZPksJ0uz@uIMp46Vrj9ltcwaszHSjSCfR5qY5uAWIhBaeL4LDgsOTwwEGkZPfRMopT5NespErouONAVB5ar7lYjmge4mWg5flKeRFri/MY@X9MFif4LsIkQT4jRU5enCyLQealCV/2c@WFizo8lUu/MiYCmoedYSUm4agPLTAD6zm4W@N2pqyOeHpCgC962q5xrGaO/gvGxjHxNk6/) ``` a=>{var i,j,v=0;while(a(i)!=0){j=0;while(j<i){v=a(j)+a(i-j-1);if(a(i)<v)a(i)=v;j+=1};i+=1};a(i-1)} ``` Ungolfed version. Try it online! ``` object Main { def f(a: Array[Int]): Int = { var i = 0 var j = 0 var val_ = 0 while (a(i) != 0) { j = 0 while (j < i) { val_ = a(j) + a(i - j - 1) if (a(i) < val_) { a(i) = val_ } j += 1 } i += 1 } a(i - 1) } def main(args: Array[String]): Unit = { val n = Array( Array(1, 5, 8, 9, 10, 17, 17, 20, 0), Array(1, 3, 2, 5, 6, 7, 4, 8, 0), Array(5, 6, 3, 2, 4, 6, 8, 7, 3, 4, 6, 2, 12, 4, 5, 7, 4, 3, 0), Array(23, 2, 3, 45, 34, 23, 3143, 13, 13, 213, 1321, 3123, 12, 312, 312, 31, 3, 213, 432, 41, 3, 123, 43, 0) ) for (i <- n.indices) { println(f(n(i))) } } } ``` ]