text
stringlengths
180
608k
[Question] [ A [**powerful number**](https://en.wikipedia.org/wiki/Powerful_number) is a positive integer \$n\$ such that for every prime \$p\$ that divides \$n\$, \$p^2\$ also divides \$n\$. Or equivalently, \$n\$ is powerful if and only if it can be written in the form \$n = a^2b^3\$, where \$a\$ and \$b\$ are positive integers. For example, \$972 = 2^2 \times 3^5\$ is powerful, because \$2^2\$ and \$3^2\$ both divide \$972\$. And we have \$972 = 6^2 \times 3^3\$. \$961 = 31^2\$ is also powerful, because \$31^2\$ divides \$961\$. And we have \$961 = 31^2 \times 1^3\$. On the other hand, \$1001 = 7 \times 11 \times 13\$ is not powerful, because \$7^2\$ does not divide \$1001\$. It is not possible to write \$1001\$ in the form \$a^2b^3\$. Here is a list of all the powerful numbers less than 1000: ``` 1, 4, 8, 9, 16, 25, 27, 32, 36, 49, 64, 72, 81, 100, 108, 121, 125, 128, 144, 169, 196, 200, 216, 225, 243, 256, 288, 289, 324, 343, 361, 392, 400, 432, 441, 484, 500, 512, 529, 576, 625, 648, 675, 676, 729, 784, 800, 841, 864, 900, 961, 968, 972 ``` This is sequence [A001694](https://oeis.org/A001694) in the OEIS. ## Task Given a positive integer \$n\$, determine whether or not it is a powerful number. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. This is also a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") so you may use your language's convention for truthy/falsy (swapping truthy and falsy is allowed), or use two distinct, fixed values to represent true or false. [Answer] # [Python 3](https://docs.python.org/3/), 43 bytes Returns `False` for a powerful number, and `True` otherwise. ``` f=lambda n,i=1:i>n or(n/i)**.5%i>0<f(n,i+1) ``` [Try it online!](https://tio.run/##JZDNbsMgEITveYrtoZJxUWow5ietI@VR3NZukWJsYXrI07s77gHE7M58C6yP8rOkdo/zuuRC22N7w3bexpLHz9@8xSXd4xxLpZq6tmKf@vswf3wNlGTs1SVeEy25Sq9R1PW5e47X5n2quPeixH6jnpQkI8lLCpKUlaQ7Xk5Sq3mxNly37HCsPZtV02DjgNKQ8CsNaQwIwARw4NMH8UCaFmxI77EFjOBEi0ZrGdUGHmEQMxhuDK7m2dKh1imudZpjnWOKBdQaRlmHE2oOXYeER8ID4HH3ABkwI1i81OnTaVoyJYqJ8pC@x@r/ZY24nChOxD8k6KmnKlFaClw3dGjNMRX@vcMg9j8 "Python 3 – Try It Online") Checks the condition that `n` is in the form `a^2*b^3` by asserting that `n/a^3` is a perfect square. In Python this would look something like `(n/a**3)**.5%1==0`. This condition can be rearranged so that it is slightly golfier: ``` (n/a**3)**.5%1==0 n**.5/a**1.5%1==0 n**.5/a**.5/a%1==0 (n/a)**.5/a%1==0 (n/a)**.5%a==0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ÆE1e ``` [Try it online!](https://tio.run/##HY@xFcIwDERX8QAuIluW5AEYJQ0vC9BBAy0tFWNAQZeGNcgi5i6F/HzS3Zd9nJflNMZ6Pcg8vq/t/Fhv6/33fm6XzxiSk@YUOfWcxHIqDeU51YKCVvQNDocOmGWaeCAghZJ@KZSqJBDTyaGv7MQdqZVsyggenSuQqBxUA6p2rFDGlMtV@bSApbHXBL1WEGsOihFqCpQ5b@w5p85EMBEEBN/eKTt3dONPvfwB "Jelly – Try It Online") Inverted native truthy/falsy semantics: 0 for powerful numbers, 1 otherwise. ``` 1e Is 1 an element of ÆE the array of the input's prime exponents? ``` [Answer] # [R](https://www.r-project.org), 24 bytes ``` \(n)all((n/1:n)^.5%%1:n) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY7YjTyNBNzcjQ08vQNrfI04_RMVVVBDIj0TYM0DUNNrjQNIxBhDCJMQISpJld5RmZyhoZicWJBQU6lhqGVoYGBTpomVN-CBRAaAA) Port of [@dingledooper's approach](https://codegolf.stackexchange.com/a/263443/55372). --- ### [R](https://www.r-project.org), 26 bytes ``` \(n,i=1:n)n%in%(i^2%o%i^3) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuha7YjTydDJtDa3yNPNUM_NUNTLjjFTzVTPjjDUhCm7qp2kYanKlaRiBCGMQYQIiTDW5yjMykzM0ihMLCnIqNQytLC0tddI0odoWLIDQAA) Uses the alternative characterization from the question. [Answer] # [Python](https://docs.python.org/3.8/), 43 bytes ``` f=lambda n,c=1:f(n,c+1)if c**n%n else n/c%c ``` [Try it online!](https://tio.run/##DYtBCoAgFAXXdYq/CbKC@rQJwcOYaQn1FHPT6c3VzGImfvkKWLeYSnHq1s9@aMJkFEvXV44svCMzDOhA9n4tYTadKS4kAnlQ0jhtzxMvLGTb1BghU32FjMkjVyk/ "Python 3.8 (pre-release) – Try It Online") Outputs Truthy/Falsey reversed. A different method than [dingledooper's solution](https://codegolf.stackexchange.com/a/263443/20260), without using square roots. The idea is to find the square-free part `c` of `n`, that is, the product of the distinct prime factors of `n`. We do this by counting up to the smallest `c` where `c**n%n` is 0, which checks that the prime factors of `c`, if copied many times, cover those of `n`. Having found `c`, we check whether `n/c%c` is zero, which is equivalent to `n` being divisible by `c**2`. This confirms that `n` includes each of its prime factors at least twice. This also works in Python 2 where `/` is integer division rather than float division, since `n` is divisible by `c`, for a solution with only exact integer arithmetic. Rather than finding the smallest `c` with `c**n%n`, we could instead check all values of `c` from `1` to `n` for one where `c**n%n` and `n/c%c` are both 0. This could look like: **44 bytes** ``` f=lambda n,c=1:c>n or(c**n%n+n/c%c)*f(n,c+1) ``` [Try it online!](https://tio.run/##DcpBCsMgEEbhdXqK2QTUBNKhmyCkdzGT2gjprwxuenrj7sH3yr@eGa@1aGtxu8JvPwJhlo29vEFZjTiHERMWGcW6aDpObFvMSqAE0oDvx/DMT7b@MaRIyJX6Z33RhNqj3Q "Python 3.8 (pre-release) – Try It Online") **39 bytes with exit code** ``` def f(n,c=1):c**n%n+n/c%c>0!=f(n,-~c%n) ``` [Try it online!](https://tio.run/##FYwxDoMwEARreMVRWMKECCyayBH8BV1soFlOh4vQ5OsOdCONZuRM647hJZrzJ0SKNVoenfXcNDB4oGPDU1@Nt3j@2MDmuCuBNpDOWELtWtdfQVkkPf09sG/RDemCsghfDpI8yXwc@Q8 "Python 3.8 (pre-release) – Try It Online") From *@loopy walt* ## [Python 2](https://docs.python.org/2/), 42 bytes ``` d=n=input() while n%d**2:d-=1 print d**n%n ``` [Try it online!](https://tio.run/##JcpBCsIwEEDR/ZxiCBTa2kKmy8BcIRcQF9FEG6jTEFLU08egy/956VPWXZZ63zNajILZySP0NJHWNBhoKx2FN/e8emcsYMpRCtoJMLzDTSlVPQv/VD/Aa41bQOn8OC7Gz0zw962lk9r42cx0OaFi1grrFw "Python 2 – Try It Online") Finds the largest value `d` where `n` is divisible by `d**2`, then checks that it includes each distinct prime factor of `n` via `d**n%n` being zero. [Answer] # TI-BASIC (TI-84 Plus/Plus CE), ~~35~~ 27 Bytes -8 bytes thanks to Bbrk24 ``` Prompt A:For(B,1,A:If not(fPart(√(A/B:Stop:End:Disp 0 ``` The thing right after `A/B` is a cube (3). The thing right before the `A/B` is a sqrt symbol. Does nothing and terminates if your number is powerful and prints `0` and terminates if your number is not powerful. **Ungolfed** ``` Prompt A For(B,1,A If not(fPart(√(A/B Stop End Disp 0 ``` **Explained** ``` Prompt A Asks user for input A For(B,1,A For loop: increase B by 1 from 1 until it reaches A If If... √( square root of... A/B A/B^3... not(fPart( is a whole number... Stop then stop execution. End End of while loop, go back to While A>B Disp 0 If, eventually, B does exceed A, then A is not a powerful number. ``` TI-BASIC programs are scored by tokens bytes, not characters. TI-BASIC also completes parentheses for you. ### Edit: Test cases **Truthy**: [![1](https://i.stack.imgur.com/A1ApC.png)](https://i.stack.imgur.com/A1ApC.png)[![2](https://i.stack.imgur.com/hZBqj.png)](https://i.stack.imgur.com/hZBqj.png)[![3](https://i.stack.imgur.com/o873j.png)](https://i.stack.imgur.com/o873j.png) **Falsy**: [![4](https://i.stack.imgur.com/nr7Mf.png)](https://i.stack.imgur.com/nr7Mf.png)[![5](https://i.stack.imgur.com/ErSyE.png)](https://i.stack.imgur.com/ErSyE.png)[![6](https://i.stack.imgur.com/TiOfH.png)](https://i.stack.imgur.com/TiOfH.png) [Answer] # Excel, 42 bytes ``` =LET(a,SEQUENCE(A1),OR(a^2*TOROW(a^3)=A1)) ``` Input in cell `A1`. [Answer] # [J](http://jsoftware.com/), ~~12 10~~ 8 bytes ``` 1 e._&q: ``` [Try it online!](https://tio.run/##HY/NTgMxDITvPMWoSLSrZlfrxPnxSpyQOHHiBTigVoUL4gV49WWmB0cZZ@az870fluMVzxuOSFixseYFL@9vr7vhsnw8/W779HD5vP3gdHr8s/l6OE@w89cSERPmDZbgCSMhEqwl5MrqCSWzqJ39RkenHjTbuupgwLKk/JYl3UUQJsSRL9@Jd6QXsSXH0BEawUTRQ2lEleAIV8w13F2rDVqqetXYq5mx2klpgjYnqnXd1Ot67UoMJYYAQ7uHZGhGNP205/0f "J – Try It Online") *-2 by using Unrelated String's approach of checking for 1 instead of verifying that every exponents was 2 or more* *-2 thanks to Bubbler for a shorter way to get prime exponents* * `_&q:` shows the number's prime exponents * `1 e.` checks if all exponents are greater than 1, by checking if 1 is an element and using 0 for truthy and 1 for falsy [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes ``` {|/~1!%x%/3#,1+!x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxlkFluwzAMRP99ChmFE1sVIGuxNiDoRYIG9kdyBSGLz94ZJy3Q9kOCyOE8kjqX212vpu1qp92bMu9tfTTNpdz6U+2WoV1kWYq879Z+lnNp69DuXwWfvdKL1GWWS6FG6/AB8UKkroe/IhUIB216KNqc5PHZsQzHH9Nv5Zv2b8BrEUYJr0RSIithghJ2wolKOIuD2CMfUBERJxSbceQFg7EMWW8sQ+9JICaTwzq7ETekd2QzTIlXZgs4HAUXgHIZLTxtns2952gJJRNzk0FusrBNEZRAaPBAhcgXc5FqpCPRkQhInD0zzOyRAzflLthjbK6r4KfuznuBH9lS8xfCsWJT) Works more like [dingledooper's Python solution](https://codegolf.stackexchange.com/a/263443/78410). ``` {|/~1!%x%/3#,1+!x} 1+!x 1..x x%/3#, starting from x, divide by above three times % square root of each |/~1! test if any of them has zero fractional part ``` --- # [K (ngn/k)](https://codeberg.org/ngn/k), 22 bytes ``` {|//x=*/:/1_*\3#,1+!x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxlT1uKAjEQ/J9TJCyrMzGQyfsBsheRlcmHXmFQ17NbJSLs7keaVNeju0/tejNm3SvTjD2qg//QdifXn2E4t+t4XD/7JLtqvanb5j4uamlyneT2JfgetemwLqo3crROXyDPr9i/JBkQe2PH3xPbdHib/u9yacJqEbQoWlQtbNLCRbyshXd4wAH9BEUGLhDbeWaBwTpC6q0jDIEJjKnMoc49E5+RwTObsBSWyhFweBI+IcpXjAi0BQ4PgasVSCJ70aIXHWwxIyUxNAVEpcwfe5lspqPQURhQuHslrJxREy/lLbhjHi53YXeb0xZVsvEATeNcwg==) A bit of a convoluted way to check if the given number `x` is `a^2 * b^3`. Returns 1 if `x` is a powerful number, 0 otherwise. ``` {|//x=*/:/1_*\3#,1+!x} 1+!x 1..x inclusive -> A 3#, an array that contains three copies of A *\ cumulative product (A; A^2; A^3) 1_ drop first */:/ reduce by cartesian product by multiplication x= boolean matrix indicating each number is equal to input |// max of all booleans ``` [Answer] # Dyalog APL, 21 bytes ``` ⊢(⊣|*⍨)0⌈/∘⍸⍤=⊢|⍨2*⍨⍳ ``` port of xnor's [Python](https://codegolf.stackexchange.com/a/263481) answer. Outputs inverse truthy value ``` ⊢(⊣|*⍨)0⌈/∘⍸⍤=⊢|⍨2*⍨⍳ ⍝ implicit n ⍳ ⍝ list values 1..n 2*⍨ ⍝ square each value ⊢|⍨ ⍝ mod by n 0 = ⍝ find where index is 0 ⌈/∘⍸⍤ ⍝ Get max index divisible (d) ⊢(⊣|*⍨) ⍝ then check d^n mod n ``` [Answer] # C, ~~69~~ 63 bytes -6 bytes thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c) suggesting to reverse the loops and pointing out that I'd managed to leave in an unused variable. ``` i,j;f(n){for(i=n;i;i--)for(j=n;j;j--)n*=i*i*j*j*j!=n;return!n;} ``` [Try it online!](https://tio.run/##bU5BCsMgELz7ik2goCaCOW99TDG1rNBNkTSX4NutQkMO7exhZ3aGYb15eF8KjRGDZLWHJUlyjIRkjGoqVhUxVsXakSYd23T1mu7rO3HHmAvxCs8bsdwWmpXYBXxRG0A2l8HBhHVdYbLWIgwDKziDByiAbJ/88w68Um0Msr/M0I/ACn@SWZwslw8) [Answer] # [Factor](https://factorcode.org) + `math.primes.factors math.unicode`, ~~30~~ 29 bytes ``` [ group-factors unzip 1 ∋ ] ``` [Try it online!](https://tio.run/##NYwxDsIwEAT7vGIfAFFCCQ9ANDSIKkphzCVYJGdzZxfwAiR@yUdMIKLb1YymMzZ6ycfDbr9dYzTxUgZxI2nZ/YjCqHqruJIwDbOR2Fl/pvmI4Z4USrdEbKcVhGK8TxWO2BTFqqrQ1ItTmxv04lNY/suJHy6gxvv5wpeyj2hh/Ri8Ejo3RBKUsAMZyR8 "Factor – Try It Online") Port of Unrelated String's [Jelly answer](https://codegolf.stackexchange.com/a/263440/97916). -1 by using `unzip` instead of `values` to get at the exponents * `group-factors` get an associative array of a number's prime factors and exponents * `unzip` get just the exponents * `1 ∋` is 1 in this? [Answer] # [Octave](https://www.gnu.org/software/octave/), 22 bytes ``` @(n)n-(t=1:n).^2'*t.^3 ``` * The output for powerful input is a matrix containing at least one entry equal to 0, which is falsy in Octave. * The output for a non-powerful input is a non-empty matrix with all entries different than zero, which is truthy. [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08zT1ejxNbQKk9TL85IXatEL874f6WCrUKahqW5kaY1V2aaRqUml4KCQkpmcYGGul9@iUJBfnlqUVppjromV2pOcSpCMgBJIi/lPwA "Octave – Try It Online") The footer code contains truthiness/falsihood test. Or [verify all test cases](https://tio.run/##y08uSSxL/Z9mq6en999BI08zT1ejxNbQKk9TL85IXatEL874f1p@kUKegq2CoZWlpSWXAhBUAnlpQMXWYF5mmkalJpgFBCmZxQUa6rq66hCR1JziVBSpPKh4XgoXEP8HAA). The footer code displays the input number if powerful (falsy output), or `--` otherwise (truthy output). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ǏΠ²Ḋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwix4/OoMKy4biKIiwiIiwiMVxuMlxuM1xuNFxuNVxuNlxuN1xuOFxuOVxuMTBcbjExXG4xMlxuMTNcbjE0XG4xNVxuMTYiXQ==) Uses [Command Master's insight](https://codegolf.stackexchange.com/questions/263438/is-this-a-powerful-number#comment576718_263438) that these are numbers where the product of the distinct prime factors of the input is divisible by the input. ``` ǏΠ²Ḋ # implicit input of integer Ǐ # distinct prime factors Π # the product of this list ² # squared Ḋ # is divisible by the (implicit) input ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 3 bytes ``` ƒ1> ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBVktLS4WYosS89FRDhZi0zJyS1CKF6qWlJWm6FkuOTTK0W1KclFy8ACKwAEoDAA) ``` ƒ1> ƒ Factor 1> Check if all exponents are greater than 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ó1å ``` Outputs an inverted 05AB1E boolean: \$1\$ if it's NOT a powerful numbers; \$0\$ if it is a powerful number (only `1` is truthy in 05AB1E). Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/263440/52210), so make sure to upvote that answer as well! [Try it online](https://tio.run/##yy9OTMpM/f//8GTDw0v//7c0NwIA) or [verify all test cases](https://tio.run/##ATQAy/9vc2FiaWX/4oKER04/IiDihpIgIj9O/8OTMcOl/0Q/acO1w6siIChwb3dlcmZ1bCkifSz/). **Explanation:** ``` Ó # Get a list of exponents of the (implicit) input's prime factorization 1å # Does this list contain a 1? # (after which the result is output implicitly) ``` [Answer] # [Arturo](https://arturo-lang.io), ~~33~~  30 bytes ``` $=>[in? 1tally factors.prime&] ``` [Try it!](http://arturo-lang.io/playground?XIEcmv) Port of Unrelated String's [Jelly answer](https://codegolf.stackexchange.com/a/263440/97916). ``` $=>[ ; a function where input is assigned to & in? 1 ; is 1 in tally ; counts of factors.prime& ; input's prime factors ] ; end function ``` [Answer] # [Racket](https://racket-lang.org/), 101 bytes ``` (define(f n)((λ(D ?)(=(count(λ(p)(and(? p n)(?(sqr p)n)))D)(length D)))(prime-divisors n)divides?)) ``` [Try it online!](https://tio.run/##XVBLboMwEN1zihFRpZkFKmyRKjY5QNQuqy5cGBKrZkxsSJQNF@sdeiU6RmrU1rtnv6@DaT94WnfOyBHCBjIMfJ5tYEAv7lZYgcFMJ@jsxXYcGxiDHbhIMPoQiVbsuLfC2IMQ4tcn7qEhfMLWzzIlPBIa6VClidFgPAcYSYhoT@hYjmq/V4R/rZX8E7ql2Dg6c3MC2PugnSB/5ji7qYbFLA@5XoN2N506UZb94ucvuoilZfA9HPyVQz87kHl4Z03pgx@gKqqyLAGttG6O9sJU53T3yABwMVvuo7NxAnzVFkE/jaECVVb0ppx/Z1dfT5za6hC6P6fZa5J8Aw "Racket – Try It Online") --- ## Explanation We create a function `f` that takes one input `n`. We find the list of prime divisors of `n` and call it `D`. We then iterate through the list and check whether `n` is divisable by each element and `n` is divisable by each element squared. If both conditions are satisfied, we increment a counter. After iterating through list, we retrieve the total count and test whether the count is the same as the length of the list of divisors. If it is, then the number is a Powerful Number. The ungolfed version is simpler to understand: ``` (define (f n) (let ([D (prime-divisors n)]) (= (count (lambda (p) (and (divides? p n) (divides? (sqr p) n))) D) (length D)))) ``` *Have a wonderful weekend ahead!* [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` k e@vX² ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ayBlQHZYsg&input=OTcy) [Answer] # JavaScript, 32 bytes A port of [xnor's solution](https://codegolf.stackexchange.com/a/263481) to JavaScript: ``` f=(n,c=1)=>c**n%n?f(n,c+1):n/c%c ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `G`, 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ḟḅ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOCU5RiVFMSVCOCU4NSZmb290ZXI9JmlucHV0PTk3MiZmbGFncz1H) or [verify the first few powerful numbers](https://Not-Thonnu.github.io/run#aGVhZGVyPSVDMyVBNiZjb2RlPSVFMSVCOCU5RiVFMSVCOCU4NSZmb290ZXI9R34maW5wdXQ9MTAwJmZsYWdzPU4=) Port of Unrelated String's Jelly answer. Output with inverted booleans. Add the `!` flag to take the logical NOT. #### Explanation ``` # Implicit input ḟ # Get the list of prime factor exponents ḅ # Check for each if it equals one # Take the maximum of this list # Implicit output ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` Ċ^₂ʰ^₃ᵗ× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//0hX3KOmplMbgGTzw63TD0////@/pbkRAA "Brachylog – Try It Online") Takes input as the Output variable. Outputs `true.` or `false.` as you would expect. ### Explanation It’s just a description of the alternative definition. ``` Ċ Take a couple of 2 variables ^₂ʰ Square the first one ^₃ᵗ Cube the last one × Multiply them: it must be equal to the given input Brachylog will implicitly check if such a couple of variables Ċ exists ``` [Answer] # APL(NARS), 8 chars ``` 1∊≢¨⊂⍨π⎕ ``` It return `0` if the number is as question ask, `1` otherwise. It is read in reverse `⎕π⍨⊂¨≢∊1` `⎕`Call for input,`π` return the list of factors of input, `⍨⊂` doing partition as input`⊂`input,`¨≢` for each element list, of partition return the lenght,`∊1` see if in the last list there is 1 test: ``` 1∊≢¨⊂⍨π⎕ ⎕: 36 0 ~ a/⍨∼{1∊≢¨⊂⍨π⍵}¨a←⍳100 ┌14─────────────────────────────────────┐ │ 1 4 8 9 16 25 27 32 36 49 64 72 81 100│ └~──────────────────────────────────────┘ ``` [Answer] # Mathematica, ~~40~~ ~~39~~ ~~38~~ ~~36~~ 27 bytes ``` FactorInteger@#1∨#==1& ``` The first `` is `\[VectorGreater]`, the second `∨` is `\[Or\]`. Assuming UTF-8 encoding, they both occupy 3 bytes. [Try this online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0xuSS/yDOvJDU9tShaOfb9hC2GjzpWKNvaGqr9DyjKzCuJDkrMS091MDQwMKgLTs1JTS6pS4v9DwA) [Answer] # Regex (ECMAScript or better), 50 bytes ``` ^((?=(xx+?)\2+$)((?=\2+$)(?=(x+)(\4+$))\5){2,})*x$ ``` [Try it online!](https://tio.run/##TY/NbsIwEIRfhUYIdgkJSQQ94BpOPXDh0B5LK1mwOG6NY9kGUn6ePU1UVeptZr6RRvMpTsJvnbIh8VbtyB0q80XfjeOGzr0Xks@1BbjwxWTUfAAsOdR1vMRNEfexs7@ii2OEzbQ1uJnhtRjfcVT3m9HkgmmoXoNTRgKmXqstweM4mSIyzzN2LpUmAM0diZ1WhgDxgZuj1niVXKfeahVgmAyRqT2A4TLVZGQocVHcbsqvxRoUt8J5WpkA8i17R/wD9B@YRb7M5x3GULrqHK3MSWi16zlhJM17UazZvnLA1BMnpuIY28GojlJHlkQAhelBhG0JDvHqBwPbXgrQvciZPQYfXFth93uTJ8Usy34A "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##RY7LasMwEEV/ZQgi1tQ2flBvIit2IN121V2diLTEIFASV3JBRai/7spOoJthzp3HvcNZq2q6/ADRDJy6fZ4UkIwF5PV@97bbeuhvmhLDc1ZvGTqQfSB0g5bXEVbddcU8tIqbQcmRRmmUmO8PM4YTkaRFUuD5a15q/tU86LghAtn8ywTHk25VXaJr1Xtx4KHmB/bwlQ8ksubLOHRxjE72QGlkI7AQlhCB/0JGdIaOmPV6CbdkC8ELds9KJPPeC/HyuhdiOlLacGpt3GBXxgRnvDezHCPtngNgV6ErE49PlkxTkZZVnv8B "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDpGSVE2C9WWqUWzDBgxot6F9TDJAseVErUx7kty4DfLbM8rxPgrULxTJ81F34r16VGf3@cPBlHXlAtxTLkwlhhL@rzTB2FdrTq91S52TullZk0FmlfdwowzCDvqaDypQeKxMDiV12F1wBteg3NrPlxzCxlVbD5/bTNfBVPTnCcAXYzUUKeptd2SJyKpcC@onXH5sikI7nd9qlWsHqw72ssj@/NmnBeeyn@vHQW43kZ8xn65Ig8qvDWrG@ZsUG2u5KZgX@lejrGfJ@XA4TDjfvYQeGRgLrxLsiCH8ZSCCc2JYEe5B@lE6WOAgxiD3x9r@hwpBOwSX9idSW9ZxgOeS3FhVldUK4TktiFFLuMsUIkk3WDcBUohq@xq7e/JBl8Igl9Dr7GBio/w33Qa6ZmcxQG@IpbsTxxGEhOgl9v35Eiy1I0r42prAkjN6BMIHwAl1vmKgNXCiVs5rSpidT5Z8DDh9tSmsxnXYXM7gCiIS3lOYLokx2yg3X7a9ni7D6VLCB@fUkxeFsZa140E76EwBKCoXtdE1UpxIwMsUpxRGIxJ4o0K2IYdKYnOiPGas21ykBf9E5MeNEVunataPyKr66Xtxq3CtadJkjJxHpQWwksZjTt7Ft33mvckVObZ1JmgWH5XL5zS4Jr7Pv3ZNHoaCJW99QpZwuY/fSdyqw0/GrlLWtqMrvpiNTnlMj4dYHnG2eEcJX1zw3Wy858P29BB36TA9m11MJr8B "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##NY5NasMwEIX3PsUgspiJZSO57caOyEFsF0KrNCqKbEYqdSg9u2sldPd@@B5vvqXLFJ5Wd50nThBvUbKVn3EKHbBhIcT6ing0uCzlkYam3FG2D5HjknB43gwNL/TTyF/aL7t1w3rdVnrswBlVnCcGDy7k@TqmdxfaArzxdZy9SygqQQW4M3gb0NOhacH3ejS@V2MBGQ4Z5lP4sOhCwlyQfCg9Uqlp28sDbOtoT/x2QZYgFrEP9yZXroWZM0L3wOju/830lepvdsliTIyBaNWVVkr9AQ "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##PY5RS8MwFIXf/RXXMliyriEp@rIaRnFFfJmw@dbOoCzrAiEracYion@9JpvuIZec755z77XHj8/BAoeVbKXviJEnWJSvJbHyfTu9wNns@Wn5sqoey3VVgOK0gNNeaQmat9L1NwBqB7rO2IbzpDFJERq6poRk@aYAabbBEQjpO60cGmdj/BchWprW7RF@yEOmDvkQu0Z2BwsGlIEIiTsIhRjFhETjVQbfeRZKfDIxGPgP2CICdRvv7I6uP8@Ld7OgrTIOzP@KWOMTolouhBjeEJpz5H06x02ejnCUl0/EKUbNXRC4ucdf@fQbT/xoGFjGKKW/ "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##XVDBasMwDL33K4wxxGrcNgntRnFDL9tgMHbYdms6k2ZuE5Y6xnEhUPrtndzttIOFnqT3nixb2@tqbWtLmCM5oTNKpsQ6fVBO27asNI9m0/Faqbpsvaq6o21a7QpegCzeZn0kSIRvj0V10GHAeG18z5V6en55VAoESQElUViOGtOoXntObeX0dFdW395hUG1zbDwVhM6z5Xx5d58tFxTkaN85zpo8kazN96je8/ePh@dXkHAmzZ6zdtN712qDGUzSbZ7TwlDA4f60ww6WRSImKQS@HmzbfWlOJ1TguER@1Z2MD9xVhqQNCmBMtnJEyM3Z/GFmVvmtj1kcA1oTfrvQsfRVzZkTaBbOpUvPoyESzAAAOYcVG9BV3YW9JMGvpJIETJiRF7S5/DsrB3n95Hyd82GI11BkMYMAf5NQjoEXcwRQLOCciQuMB3a9ppNskSQ/ "PHP – Try It Online") - PCRE [Try it online!](https://tio.run/##RY/RioMwEEV/RWTATNMUle1LJbSwz/0CdUHcaQ1kE4kpSiXfbnXLsm9zDpfLnd6O5IaOtF7AydLRnab6dDI0skuyfDF2lmya@BmrnANu@D42zZFVHytgdcQ53wfcTbAkl338aX96pek7xgKeMi1u1lHTdgx0pEwEyvQPjzM0ErQYeq18LOJC3Rg0h9Y@jBfaR/kW4BKaMq3DWsDAyFIZX/@aAozQ9MfZxpzjvHW4w7XxbUcDS6ZkBwbf@onz6JQn0dnBh3VWVvxzJIxdX9bKUAQmhLBkIj@m6Qs "PowerShell – Try It Online") - .NET I adapted this on 2018-12-26, as a slight modification to the regex that [matches numbers of the form \$n^k\$](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power/21951#21951), where \$k\$ is a constant. In its implementation, that regex actually matches numbers that are either \$0\$ or of the form \$n^k=\prod\_{i=0}^{q} p\_i^{k\_i}=p\_0^{k\_0}p\_1^{k\_1}p\_2^{k\_2}...p\_q^{k\_q}\$ where all \$p\_m\$ are distinct primes, all \$k\_m=k\$, and \$q\ge 0\$. The only changes here, to match powerful numbers instead, are to make \$k\_m\ge 2\$ (which takes 1 extra byte), and not to match \$0\$ (which saves 1 byte). In other words, this regex works by dividing away each prime factor, from smallest to largest, asserting along the way that each distinct prime is divided away at least twice, with an end result of \$1\$. ``` ^ # N = input number (initial value of tail) ( # Loop/iterate the following: (?=(xx+?)\2+$) # \2 = smallest prime factor of tail ( # Loop/iterate the following: (?=\2+$) # Assert tail is still divisible by \2 (?=(x+)(\4+$)) # \4 = largest proper divisor of tail = tail / \2 (implicitly); # \5 = tail - \4 (a tool to make tail = \4) \5 # tail -= \5, i.e. tail = \4 ){2,} # Iterate the above at least 2 times )* # Iterate the above any number of times, minimum 0 x$ # Assert tail == 1 ``` # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes ``` .+ $* ^((?=(11+?)\2+$)((?=\2+$)(?=(1+)(\4+$))\5){2,})*1$ ``` [Try it online!](https://tio.run/##JY09DsIwGEP3d44iJRShfD9pkwF15BIVgoGBhQGxIc4eUjHZfrLs1/39eN7aLpyv7Tgy7LmEsJyCyLjEVcchbvFvNjzGsHoPcc3xo4dv3MvQmuAUKjKhGZ0xxSa80pXMxIwkRBBFDHEkIx0WpJcSKqiihjraVwpasYQJZphjGeu7Bat4wvul4oY7nvF@NuPlBw "Retina 0.8.2 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 64 bytes ``` .+ $* ^((.){2,})(?<!^\3+(..+))\1*$(?<!^\4*(?(2)$)(((?<-2>)\1)+)) ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLK05DQ0@z2kinVlPD3kYxLsZYW0NPT1tTM8ZQSwUiYqKlYa9hpKmiqaEBFNA1sgPKaQJV/P9vyGXEZcxlwmXKZcZlzmXBZQkA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for a powerful number, `1` if not. Explanation: ``` .+ $* ``` Convert to unary. ``` ^((.){2,}) ``` Search for a nontrival integer... ``` (?<!^\3+(..+)) ``` ... that is not composite... ``` \1*$ ``` ... and is a factor of the input... ``` (?<!^\4*(?(2)$)(((?<-2>)\1)+)) ``` ... and whose square is not a factor of the input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` Nθ⊙…·²θ∧∧¬﹪θι﹪θ×ιι⬤…²ι﹪ιλ ``` [Try it online!](https://tio.run/##RUy9CsIwEN59iowXiEsXkU4dO1hEfIE0DXpwvZg0Kfj018bBfvAN36972@SCJZGePyUPZR59gqjb0z0hZ@j4Cz07Kguu/mH55aExKmqjOp6gcggZbmEqFCAahXqPDvnE2S@AP79uiOB/gkdzL5CuaEWul0bOK20 "Charcoal – Try It Online") Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. `-` if the input is not a powerful number, nothing if it is. Explanation: ``` Nθ Input as an integer …· Inclusive range from ² Literal integer `2` to θ Input integer ⊙ Any value satisfies θ Input integer ¬﹪ Is divisible by ι Current value ∧ Logical And θ Input integer ﹪ Is not divisible by ×ιι Current value squared ∧ Logical And … Range from ² Literal integer `2` to ι Current value ⬤ All satisfy ι Outer value ﹪ Is not divisible by λ Inner value Implicitly print ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, 32 bytes `Prime.prime_division` returns a number's prime factors \$\prod\_{k=1}^\infty {p\_k}^{e\_k}\$ in the form `[ [p1, e1], [p2, e2], ... ]` so this function checks whether every exponent is 2 or more. ``` ->n{n.prime_division.all?{_2>1}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7OI025ilpSVpuhY3FXTt8qrz9MAS8SmZZZnFmfl5eok5OfbV8UZ2hrW1EHVbChQ0DPX0LC0tNfWKU3NSk0sU1NIgUgsWQGgA) [Answer] # [Desmos](https://desmos.com/calculator), 47 bytes ``` f(k)=0^{∏_{n=1}^{k^{.5}}mod((k/n^2)^{1/3},1)} ``` In case it bothers anyone, `k/n^2` can't be shortened to `k/nn` because `k/nn` is parsed as `k/n * n` when we actually want `k/(n*n)`. [Try It On Desmos!](https://www.desmos.com/calculator/mnbfsa7ujf) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/4wfmwybazs) [Answer] # [Perl 5](https://www.perl.org/) `-ap`, 43 bytes ``` //&map$\+=$_**2*$'**3=="@F",@;for@;=1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/19fXy03sUAlRttWJV5Ly0hLRV1Ly9jWVsnBTUnHwTotv8jB2tZQT08lvrb6/38jU8t/@QUlmfl5xf91fU31DAwN/usWJAIA "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `g`, 23 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 2.875 bytes ``` ∆Ǐċ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBZz0iLCIiLCLiiIbHj8SLIiwiIiwiMVxuMlxuM1xuNFxuNVxuNlxuN1xuOFxuOVxuMTBcbjExXG4xMlxuMTNcbjE0XG4xNVxuMTYiXQ==) Bitstring: ``` 00010101110001100111100 ``` Prime exponents, check if not equal to one, minimum of that list (will always be greater than one for a powerful number) ]
[Question] [ ### Your task Given a integer input, \$ n \$ (such that \$ n > 1 \$), decide whether it can be written as the sum of (at least 2) consecutive square numbers. ### Test cases **Truthy:** ``` Input Explanation 5 1 + 4 13 4 + 9 14 1 + 4 + 9 25 9 + 16 29 4 + 9 + 16 30 1 + 4 + 9 + 16 41 16 + 25 50 9 + 16 + 25 ``` **Falsy:** (Any number from 2 to 50 that's not in the truthy test cases) ### Clarifications and notes * For reference, [here](https://ato.pxeger.com/run?1=TZBdTsQgFIXfu4rzVuiPsU2Mk8a6kaYP2FKlQ2GkkIxr8aUx0T3NbgQH07kvwM35zrmXz5_Th33Tart8re-OGb6ihWTLy8igGnTHLKsxaYMjhIJh6pWTqvB3S1SW3T3QvKJ9Mmi18uEGlV7S1p6X3dzMuej_PObdQ3JFJC1FwJGDCDzh2gNTI6IhCT5eAg93Pf12dioPl2XkE1YtnRVakTNtEvgKAUMI-GfjPl4QFaGEJ91CBoq2xXnvhzLcOuP55OaRpjH0MfiLfYG6QHVfReeTCR8iCqTlc1rsswkaZ9626_kL) is an ungolfed Python program which will get all the truthy values up to 100. * This is [OEIS A174069](https://oeis.org/A174069) * [Default [decision-problem] rules](https://codegolf.meta.stackexchange.com/questions/19202/default-policy-for-output-in-decision-problems) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ẇḋ`ṫċ ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bqG4biLYOG5q8SL/@G4isOH4oKsVOKAmP//MTAw "Jelly – Try It Online") ``` Ẇḋ`ṫċ – link, we call the argument n Ẇ – all contiguous sublists of [1, ..., n] ḋ – dot product (vectorized) with... ` ... itself (` makes a monad from a dyad by repeating the argument) ṫ – discard the first n-1 (for n>1, n^2 ≠ n, so it's ok) ċ – count the occurences of n in this list ``` [Answer] # [R](https://www.r-project.org), ~~57~~ ~~52~~ ~~49~~ 48 bytes ``` \(n)n%in%apply(array(1:n,1:0+n)^2,2,cumsum)[-1,] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3DWI08jTzVDPzVBMLCnIqNRKLihIrNQyt8nQMrQy08zTjjHSMdJJLc4tLczWjdQ11YiH69qdpmGpypWmYaHKVZ2QmZ2gUQ7QbWpka6KRpakJULVgAoQE) ### Explanation outline: 1. Construct a matrix with `n+1` rows: filling up columns with `1:n` (with recycling). For `n=5`: ``` 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4 1 2 3 4 5 ``` 2. Square values in the matrix. 3. Take cumulative sum of the columns. We don't care about the additional values in the bottom-right triangle of the matrix, as those are bigger than `n^2` (which is bigger than `n`). ``` 1 4 9 16 25 5 13 25 41 26 14 29 50 42 30 30 54 51 46 39 55 55 55 55 55 56 59 64 71 80 ``` 4. Discard the first row, as it contains squares (not constructed as sums of squares). 5. Check if `n` is in the matrix. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ÞS~Ḣ²Ṡc ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnlN+4biiwrLhuaBjIiwiIiwiMTQiXQ==) **How it works** ``` ÞS~Ḣ²Ṡc ÞS Sublists of range 1-n ~Ḣ Keep lists with length >= 2 ²Ṡ Square and sum each sublist c Does it contain n? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Unrelated String (square after getting sublists of `[1..n]` avoiding `€`). ``` Ẇ²ḊƇ§ċ ``` A monadic Link that accepts an integer and yields the count of ways it is partitionable into consecutive (positive) squares (`0` is falsey while non-zero integers are truthy). **[Try it online!](https://tio.run/##ARsA5P9qZWxsef//4bqGwrLhuIrGh8KnxIv///8zNjU "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ASAA3/9qZWxsef//4bqGwrLhuIrGh8KnxIv/w4figqxU//81MA "Jelly – Try It Online"). ### How? ``` Ẇ²ḊƇ§ċ - Link: integer, n Ẇ - all contiguous sublists of [1..n] ² - square (vectorises) Ƈ - filter keep those for which: Ḋ - dequeue (i.e. remove the singleton lists) § - sums ċ - count occurrence of (n) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 58 bytes ``` n=>(g=i=>(s+=++i*i)-n?s>n?q<n&&g(++q,s=q*q):g(i):1)(s=q=1) ``` [Try it online!](https://tio.run/##FYzBDoIwEAXvfkVPZJeKsQcvlIVvIUibZ8jWUuPv13qZZOYwr/W7lu3E@zNoeu41SFWZKQoaixVr0YMHXcqsS5606yJZm69Fcp95jAQeHVNTcVz9JaSTAHHeANPj7k0bgA0ChdaZzZa0pGO/HSn@g68/ "JavaScript (Node.js) – Try It Online") By definition [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` §õ²ãx aU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=p/Wy43ggYVU&input=NTA) ``` §õ²ãx aU :Implicit input of integer U § :Less than or equal to õ : Range [1,U] ² : Square each ã : Sub arrays x : Reduced by addition aU : Last 0-based index of U ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~22~~ 21 bytes ``` {|//x=1_+\|+':3+\/=x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0devsDWM146p0Va3MtaO0betqOXi0lcoz0gtSlVIyU8tVkhTKEotKS3KUzBUyMxTiDbSUTA0MNC05zLSVktTN4pXBPIAGIYUCw==) **Comments**: ``` =x / Generate identity matrix of size x 3+\/ / Three times cumulative sum; / This puts triangular numbers on the columns, starting with 1 at the diagonal +': / Sum adjacent values; This gives square numbers | / Reverse the matrix +\ / Cumulative sums; Now matrix has all sums of ranges of sqaures 1_ / Remove first row; This correspond to the sums of a single square |//x= / Is any of the values equal to x? ``` [Try it](https://ngn.codeberg.page/k#eJxLs6qu0devsFWIMYxXiNGOUYipAVLqVgoxxtox+goxthW1XFxpDqYA5zcKvA==) with output of intermediate values. [Answer] # [Python](https://www.python.org), 71 bytes ``` lambda n,k=0:(z:={k:=k+j*j for j in range(n)if j*j<n})&{l+n for l in z} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY33XMSc5NSEhXydLJtDaw0qqxsq7OtbLO1s7SyFNLyixSyFDLzFIoS89JTNfI0M9MUgOI2ebWaatU52nlgBTkgBVW1UONUQEKZCD2GOqaGmlZcnAVFmXklGpk6aRqZmpoQtQsWQGgA) # [Python](https://www.python.org) NumPy, 68 bytes ``` lambda n:{*(z:=cumsum(x:=r_[:n]**2)[x<n])}&{*z+n} from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3XXISc5NSEhXyrKq1NKqsbJNLc4tLczUqrGyL4qOt8mK1tIw0oyts8mI1a9Wqtaq082q50orycxXySnMLKhUycwvyi0q0oGappOUXKWQqZOYpFCXmpadqGOqYGmpacXEWFGXmlWhk6qRpZGpqQtQuWAChAQ) Returns the empty set for False and a nonempty set for True. ### How? Compares (i.e. intersects) the sets {0,1,1+4,1+4+9,...,1+4+...+j^2} and {n,n+1,n+1+4,n+1+4+9,...,n+1+4+...+j^2} where j is the largest number such that j^2<n. [Answer] # [Python](https://www.python.org), 73 bytes ``` lambda n:n in[-~(r:=i//n+1)*(r*(r/3+i%n+1/6)+i%n*i%n)for i in range(n*n)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3PXMSc5NSEhXyrPIUMvOides0iqxsM_X187QNNbU0ioBI31g7UxXI1TfTBDG0gFgzLb9IIROoXqEoMS89VSNPK08zFmqgCpqckY6poaYVF2dBUWZeiUamTppGpqYmRO2CBRAaAA) Formula for \$\sum\_{i=x}^{x+r}i^2\$ found using [Wolfram Alpha](https://www.wolframalpha.com/input?i=sum+from+i%3Dx+to+%28x%2Br%29+of+i%5E2), then golfed as hard as I could. [Answer] # JavaScript (ES6), 50 bytes Returns \$0\$ or \$1\$. ``` f=(n,p=0,q)=>n?++p<n&&f(n-p*p,p,q?1:f)|!q*f(n,p):q ``` [Try it online!](https://tio.run/##FYpBDoIwEADvvGK9NF1aTPEIVN5CsGs0zXYLxIv69lpPM5nMc3kt@7o95Og43UIp5DVb8c5m9FeejZGJlSLNnbRixea5Hwg/p9zSf8QhF0qbjuEABg@XsWKC3rkqxiC8G4B6IigFa@I9xXCO6V7L2HzLDw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input p = 0, // p = counter used to generate squares q // q = flag telling that we've started to subtract // squares from n, initially undefined, then ) => // set to f, then set to 1 n ? // if n is not 0: ++p < n // increment p and abort if it's greater than && // or equal to n f( // otherwise, do a 1st recursive call: n - p * p, // subtract p² from n p, // pass p unchanged q ? 1 : f // set q to 1 if it's already defined or // to f (truthy but NaN'ish) otherwise ) | // end of recursive call !q * // if q is defined, ignore the result of ... f(n, p) // ... the 2nd recursive call where n and p are // left unchanged and q is undefined : // else: q // return q, which is coerced to 1 by the bitwise // OR if and only if it's equal to 1, meaning // that n is the sum of at least 2 squares ``` [Answer] # [Factor](https://factorcode.org/) + `grouping.extras`, ~~60~~ 58 bytes ``` [ dup [1,b] 2 v^n tail-clump [ cum-sum rest ] gather in? ] ``` [Try it online!](https://tio.run/##NY27CsJAEEV7v@J@gAkmPkAtLMXGRqwkwrqOcTG7rjOzoojfHiPirQ6HA/dkrF653W5W6@UMF@JADbzRc84m1CQ/vtO3EtR8TdGFOqeHshEI3RIF@89EjTpRZwWRSfUZ2QXtKhXMe70XxiiGKEYoxyinGA7w3QhF5yd4tzscU8Su6B8qlLjvA9S4JrNN8p2GTT6T5MEkigp1d0kMFxaoWm8i8vYD "Factor – Try It Online") ``` dup ! duplicate input [1,b] ! range from 1 to input inclusive 2 v^n ! square each tail-clump ! suffixes [ ! begin gather cum-sum ! cumulative sum rest ! sans the first element ] gather ! map, flatten, and uniqueify in? ! is the input we duped at the beginning in the sequence? ``` [Answer] # [Python](https://docs.python.org/3.8/), 55 bytes ``` f=lambda n,z=0,j=0:j*j<n and f(n,z<<j*j|1,j+1)or z&z>>n ``` [Try it online!](https://tio.run/##FctBCoAgFEXReav4o8hykEQQoe3FKCupl4iTpL2bzS4HrnvCfqMbnE/JqFNf86IJPKqWW9WOtrYSpLGQqbJKmeEV3DaC3Z5iGacJyeQEHSCvsa2V4L1gY0HOHwj5@lfG0gc "Python 3.8 (pre-release) – Try It Online") Outputs 0 for falsey, nonzero for truthy. Based on [loopy walt's method](https://codegolf.stackexchange.com/a/257475/20260) of making a set of the cumulative sums of squares, then intersecting it with a copy that's shifted by `n`. This answer represents the set as a bit field stored as a positive number, which lets us shift it with `>>` and intersect with bitwise `&`. **53 bytes** ``` f=lambda n,z=0,j=0:z&z>>n|(j*j<n>0<f(n,z<<j*j|1,j+1)) ``` [Try it online!](https://tio.run/##DYtBCoAgEADvvWJPoeVBiSBC/YtRVlKbiJekv9seh5mJbz4eHKaYavXmcveyOkBRjBTByLm0xVr8WOiCRiu1Z@S0JvyUCL3ivPonAcKJkBzuG1NiVHxuIKYTM9VAC1U/ "Python 3.8 (pre-release) – Try It Online") [Answer] # [J](http://jsoftware.com/), 19 bytes ``` e.[:,@(>:+/\*:)1+i. ``` [Try it online!](https://tio.run/##FYwxDsIwEAR7v2ITCsf4OOIkjuWTQAgkKkRBC1QoEdDwA75ujmK0u1Psu@RKwn2sJFtrarYzNgILQgtRVozD5XQsE1@Fds1W/Pq2FBf8i4sz5z0jEkKvDIROe5cJfUsYAiFqRvVR/ag7JTM9nh80i@9ce4f/S0rlBw "J – Try It Online") Brute force: tries every possible infix of all the squares up to n. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` Nθ⊙θ⊙ι⁼θΣX…·λι² ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfDPPMKSkv8SnOTUos0CjWtuQKKMvNKNBzzKjUKdRRAVKaOgmthaWJOMUgguDRXIyC_HKjWMy85p7Q4syw1KDEvPVUjR0chU1NHwUgTDKyXFCclF0PtWB6tpFuWoxS7yNQAIgAA) Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if `n` can be written as a sum of at least `2` consecutive squares, nothing if not. Explanation: ``` Nθ Input `n` as a number θ Input `n` ⊙ Any of implicit range satisfies ι Current value ⊙ Any of implicit range satisfies …· Inclusive range from λ Inner value to ι Outer value X Raised to power ² Literal integer `2` Σ Take the sum ⁼ Equals θ Input `n` Implicitly print ``` Although the program includes `0²` the only relevant sum is `0²+1²` but when the input is `1` the outer loop only goes up to `0` so that sum is never constructed. [Answer] # [R](https://www.r-project.org), 41 bytes ``` \(n)n%in%diffinv(array(1:n,1:0+n)^2)[-2,] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3NWM08jTzVDPzVFMy09Iy88o0EouKEis1DK3ydAytDLTzNOOMNKN1jXRiIRr2p2mYanKlaZhocpVnZCZnaBQnFhTkgNSbGuikaWpCVC1YAKEB) This is mostly a golf of [pajonk's answer](https://codegolf.stackexchange.com/a/257472/67312) that uses `diffinv(X)` rather than `apply(X,2,cumsum)` to calculate the cumulative sums. ### Changes from pajonk's answer: 3. Take the [discrete integral](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/diffinv) of the columns. We don't care about the additional values in the bottom-right triangle of the matrix, as those are bigger than `n^2` (which is bigger than `n`), nor do we care about the additional row of zeros at the beginning (since they are smaller than `n`). ``` 0 0 0 0 0 1 4 9 16 25 5 13 25 41 26 14 29 50 42 30 30 54 51 46 39 55 55 55 55 55 56 59 64 71 80 ``` 4. Discard the second row, as it contains squares (not constructed as sums of squares). [Answer] # [Python](https://www.python.org), 111 102 95 90 87 bytes This uses `p` (positive) and `a` (antipositive?) to track the the beginning and end of a series of consecutive squares, only storing the sum (`s`) of squares between them. If the sum is less then `n`, the square of `p` is added to the sum and `p` is incremented. If the sum is greater than `n`, the square of `a` is subtracted from the sum and `a` is incremented. When `p` is greater than `n`, the number has failed the test. `p-a` is checked to see that at least 2 squares are included in the sum. 102 thanks to l4m2 90 thanks to gsitcia ``` f=lambda n,s=0,p=1,a=1:s!=n>p and f(n,s+[-a*a,p*p][x:=s<n],p+x,a+(x<1))or(s==n)&(p-a>1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY4xCsJAEABrfcUJInvJBnKFICGbb1gEi5V4eqCb5S5CfItNGv2Tv9Ei1jMM83zrY7j0Mk2v--CL3Wfv6cq3Y8dGMFGJSg6ZXJVWJI0als54-KG8LThj1EwP7VhRquWAmo_IOYy1s7aPkIjEbkALbpyd82vfRxNMEBNZzidwuC1ttVxoDDJAQA_Bzu5_6Qs) [Answer] # Haskell, 51 bytes ``` f x=elem x[sum$map(^2)[z..w]|z<-[1..x],w<-[z+1..x]] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` !FreeQ[Tr/@Subsequences[Range@#^2,{2,#}],#]& ``` function that returns true-false [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X9GtKDU1MDqkSN8huDSpOLWwNDUvObU4OigxLz3VQTnOSKfaSEe5NlZHOVbtf0BRZl6JQ3BqTmpyCURFtKGOoYFBrI5CerRyrK1tSFFpqoJa7P//AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~48~~ 38 bytes ``` .+ $* ((^1|11\2)+)(?<1>\1(?<2>11\2))+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS0MjzrDG0DDGSFNbU8PextAuxhBIGdmBhTS1Vf7/NzTiMjTmMjThMjTlMrLgMrLkMjbgMjYEAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Vaguely based on my Retina 0.8.2 answer to [Sum of two squares](https://codegolf.stackexchange.com/questions/242459). ``` .+ $* ``` Convert to unary. ``` ((^1|11\2)+) ``` Match a square number. ``` (?<1>\1(?<2>11\2))+ ``` Match at least one additional consecutive square number; "named" capturing groups are used to reuse the captures from the previous square number. ``` $ ``` Check whether the squares are able to sum to the input. [Answer] # [Desmos](https://desmos.com/calculator), 54 bytes ``` f(N)=∑_{n=1}^N∑_{k=1}^N0^{(N-∑_{a=n}^{n+k}aa)^2} ``` [Try It On Desmos!](https://www.desmos.com/calculator/ueblkbthmg) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/nuve8w4bla) [Answer] # [Desmos](https://www.desmos.com), ~~76~~ ~~60~~ 58 bytes ``` l=[1...n] f(n)=[0^{([a...a+b]^2.total-n)^2}fora=l,b=l].max ``` [Try it on Desmos!](https://www.desmos.com/calculator/8ppdolt62d) Outputs 0 or 1. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ⟦sṀ^₂ᵐ+? ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZcUPdzbEPWpqerh1grb9///GBv8B "Brachylog – Try It Online") Tried a more declarative approach instead of this one but the constraint solver is not strong enough for anti-sums, it falls into infinite loops for falsy cases. ### Explanation ``` ⟦ Range [0, …, N] sṀ Sublist of Ṁany (i.e. at least 2) consecutive elements ^₂ᵐ Map square +? The sum is N ``` [Answer] # Java 8, 84 bytes ``` n->{int i,j,c,r=c=i=0;for(;i<n;c=i*i)for(j=++i;j<n;r+=c==n?1:0)c+=j*j++;return r>0;} ``` [Try it online!](https://tio.run/##NU/LbsMgEDzbX7FHExzLrdRLCekPpKccqx4IsaOlBCLAkSqLb3fXj@4F7cwwO2PUU@3N9Wd6DBeLGrRVMcKnQgdjWQINutSFXukOTgTBNhfvbacc9BXx4JhYmLx@iUkl8jqBBTm5/XGcNVibWtdBaomyFb0PlcCDE7TukM2rkZyjMIQFTirpPl7eW6a5NDvDuQhdGoKDcGxFntZzW@bt3NPjFe6UvDqngO729Q0q3CIby2K2XzLIVwF4kG8tPZwzKlQsHfvKNlSFLUhx/o2puzd@SM2DnJJ1RIlVmssi/3fN0x8 "Java (JDK) – Try It Online") --- For the science : inline solution using only Streams : ``` n->java.util.stream.IntStream.range(1,n).anyMatch(i->java.util.stream.IntStream.range(i+1,n).anyMatch(j->n==java.util.stream.IntStream.range(i,j+1).reduce(0,(a,b)->a+b*b))) ``` [Answer] # SWI-Prolog, 64 bytes ``` \X:-X/_. X/Y:-between(2,X,Y),Z is Y-1,W is X-Y*Y,(W is Z*Z;W/Z). ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LnIKŒOIå ``` [Try it online](https://tio.run/##yy9OTMpM/f/fJ8/T@@gkf8/DS///NzQBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/R9panB0R1mlvZLCo7ZJCkr2lf998iq9j07yrzy89L/OfwA). Minor alternative: ``` <tLnŒOIå ``` [Try it online](https://tio.run/##yy9OTMpM/f/fpsQn7@gkf8/DS///NzQBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/R9panB0R1mlvZLCo7ZJCkr2lf9tSnzyjk7yrzy89L/OfwA). More original, but longer (and slower) program (**9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**): ``` Åœ¨t€¥PΘà ``` [Try it online](https://tio.run/##AR0A4v9vc2FiaWX//8OFxZPCqHTigqzCpVDOmMOg//8xNA) or [verify all test cases](https://tio.run/##AS0A0v9vc2FiaWX/WTUwxbh2eT8iIOKGkiAiP3n/w4XFk8KodOKCrMKlUM6Yw6D/LP8). **Explanation:** ``` L # Push a list in the range [1, (implicit) input] n # Square each inner integer IK # Remove the input-integer from the list Œ # Get all sublists O # Sum each sublist Iå # Check if the input-integer is in this list of sums # (after which the result is output implicitly) < # Decrease the (implicit) input-integer by 1 t # Pop and take the square root of this input-1 L # Pop and push a list in the range [1, floor(sqrt(input-1))] n # Square each inner integer ŒOIå # Same as above Åœ # Get all lists of positive integers that sum to the (implicit) input ¨ # Remove the last [...,[input]] sub-list t # Get the square root of each inner integer € # Map over each inner list of decimals: ¥ # Pop and push its deltas / forward-differences P # Get the product of each inner list of forward-differences Θ # Check for each product if it's equal to 1 (with a 05AB1E-truthify) à # Check if any is truthy # (after which the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 82 bytes ``` i;j;s;t;f(n){for(s=i=0;s-n&&++i<n;)for(s=i*i,t=j=i;!t*s-n&&++j<n;t=0)s+=j*j;s-=n;} ``` [Try it online!](https://tio.run/##lVDLTsMwELz3K7aRWjkvkRZxQK65IL6C5BA5dnEAp7KNiIjy64TNE1rBAWu9Ws/MrrzD4yPnXadoSS11VBLtN7IyxDLFEmpjvd2GoTpo6k9ooCLHSqbo2gUTXSLtWOLbkJUBzomZpm2ntIPXXGniQ7MCPD0g6pPgThSPGTBokgjG2M3FRez@pn7t/a/@kmrp8FNeaeuAP@UmwCz4szDjh720ftin9e093hsvgp/va2/qRqOA9MsqXYga2xI6lQew6kNUksw2@FcTECwIBfS7V8@2zdY5nDSOCWFPzyiL1FoS55/DAuHF8KE1@xacDEok8TYFxHeAeWNTjSu5CGy0bG0ZE9k0th2yEe7NaNxp1XafXL7kR9vF718 "C (gcc) – Try It Online") Inputs \$n\$. Returns a falsey value if \$n\$ is the sum of consecutive squares or a truthy value otherwise. [Answer] # [///](https://esolangs.org/wiki////), 39 bytes ``` /13///14///25///29///30///41///50///5// ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X9/QWF9f39AESBiZgghLIGFsACRMDIGEKYgFFP9vbPofAA "/// – Try It Online") *Sigh.* I thought there was some light at the end of the tunnel with [this idea](https://tio.run/##nYs7koMwEAVznYJYidBfhDb2QTZw1Qabcf9iG9gPNggkK9C86dczfH0Mn49hHJXMPXVRm1JdV0z1y6JuTHVX6nLtidPgX3J/u89kBvPON7Gx0Y0UjWkkv@VnuGkw/TwJYQmk@JOI6TeSu78shW7/Fza92ljNemW3TzvAPQOIfyGg8IpgccOAaQuh3Q6VwrR7GK53OYXZL2hspqFyuYrOZzvKkC9p40FLnY5q@u6wl8K2xwKGPjFQzJmCY08dJHcuYfkCCy2UaHixyENMZSJmV2hK4dpSFVcXu8imXMa2FTa6q9HxfZXPQag74CJWXnCSak@46apv3juS4zc), but it turns out the simple greedy approach fails for a few of the inputs. Plus, hardcoding it is a third of the length. ]
[Question] [ What general tips do you have for golfing in sed? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to sed (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] If you need to use [labels](https://www.gnu.org/software/sed/manual/sed.html#Programming-Commands) then for sure you'll want your label names to be as short as possible. In fact taken to the extreme, you may even use the empty string as a label name: ``` : # define label "" p # print pattern space b # infinite loop! - branch to label "" ``` [Answer] The [GNU sed documentation](https://www.gnu.org/software/sed/manual/sed.html) describes the `s` command as *"sed's Swiss Army Knife"*. But if all you want to do is replace all instances of one character with another, then the `y` command is what you need: ``` y/a/b/ ``` is one char shorter than: ``` s/a/b/g ``` [Answer] When repeatedly replacing in a loop: ``` loop: s/foo/bar/g tloop ``` it's usually unnecessary to replace globally, as the loop will eventually replace all occurrences: ``` # GNU sed : s/foo/bar/ t ``` Note also the GNU extension above: a label can have an empty name, saving more precious bytes. In other implementations, a label cannot be empty, and jumping without a label transfers flow to the end of script (i.e. same as `n`). [Answer] Consider using extended regex syntax (in GNU sed). The `-r` option costs one byte in scoring, but using it just once to eliminate the backslashes from a pair of `\(...\)` has already paid for itself. [Answer] As mentioned in `man sed` (GNU), you can use any character as a delimiter for regular expressions by using the syntax ``` \%regexp% ``` where `%` is a placeholder for any character. This is useful for commands like ``` /^http:\/\// ``` which are shorter as ``` \%^http://% ``` What is mentioned in the [GNU sed manual](https://www.gnu.org/software/sed/manual/sed.html#Regular-Expressions) but **not** in `man sed` is that you can change the delimiters of `s///` and `y///` as well. For example, the command ``` ss/ssg ``` removes all slashes from the pattern space. [Answer] # Read the whole input at once with `-z` Often you need to operate on the whole input at once instead of one line at a time. The `N` command is useful for that: ``` : $!{N;b} ``` ...but usually you can skip it and use the `-z` flag instead. The `-z` flag makes sed use NUL (`\0`) as its input line separator instead of `\n`, so if you know your input won’t contain `\0`, it will read all of the input at once as a single “line”: ``` $ echo 'foo > bar > baz' | sed -z '1y/ao/eu/' fuu ber bez ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I19BPS0/nyspsQiIq9QVahSKU1MUdKsU1A0r9RPz9VNL9dX//wcA "Bash – Try It Online") [Answer] There's no built-in arithmetic, but calculations can be done in unary or in unary-coded decimal. The following code converts decimal to UCD, with x as the unit and 0 as the digits separator: ``` s/[1-9]/0&/g s/[5-9]/4&/g y/8/4/ s/9/4&/g s/4/22/g s/[37]/2x/g s/[26]/xx/g s/[1-9]/x/g ``` and here's the conversion back to decimal: ``` s/0x/-x/g s/xx/2/g y/x/1/ s/22/4/g s/44/8/g s/81/9/g s/42/6/g s/21/3/g s/61/7/g s/41/5/g s/-//g ``` These are both taken from [an answer to "Multiply two numbers without using any numbers"](/a/49442). Plain old unary can be converted using this pair of loops from [this answer to "{Curly Numbers};"](/a/58007), where the unit is `;`. I've used `v` and `x` to match Roman for `5` and `10`; `b` comes from "bis". ``` # unary to decimal :d /;/{ s/;;;;;/v/g s/vv/x/g /[;v]/!s/x\+/&0/ s/;;/b/g s/bb/4/ s/b;/3/ s/v;/6/ s/vb/7/ s/v3/8/ s/v4/9/ y/;bvx/125;/ td } # Decimal to unary :u s/\b9/;8/ s/\b8/;7/ s/\b7/;6/ s/\b6/;5/ s/\b5/;4/ s/\b4/;3/ s/\b3/;2/ s/\b2/;1/ s/\b1/;0/ s/\b0// /[^;]/s/;/&&&&&&&&&&/g tu ``` [Answer] # Append a newline in one byte The `G` command appends a newline and the contents of the hold space to the pattern space, so if your hold space is empty, instead of this: ``` s/$/\n/ ``` You can do this: ``` G ``` # Prepend a newline in three bytes The `H` command appends a newline and the contents of the pattern space to the hold space, and `x` swaps the two, so if your hold space is empty, instead of this: ``` s/^/\n/ ``` You can do this: ``` H;x ``` This will pollute your hold space, so it only works once. For two more bytes, though, you could clear your pattern space before swapping, which is still a savings of two bytes: ``` H;z;x ``` [Answer] If not explicitly banned by the question, the consensus for [this meta question](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) is that numerical input may be in unary. This saves you the 86 bytes of decimal to unary as per [this answer](https://codegolf.stackexchange.com/a/51329/11259). [Answer] I know this is an old thread, but I just found those clumsy decimal to UCD converters, with almost a hundred bytes, some even messing the hold space or requiring special faulty `sed` versions. For **decimal to UCD** I use (68 bytes; former best posted here 87 bytes) ``` s/$/\n9876543210/ :a s/\([1-9]\)\(.*\n.*\)\1\(.\)/\3x\2\1\3/ ta P;d ``` **UCD to decimal** is (also 66 bytes; former best posted here 96) ``` s/$/\n0123456789/ :a s/\([0-8]\)x\(.*\n.*\)\1\(.\)/\3\2\1\3/ ta P;d ``` * `\n` in the replacement is not portable. You can use a different character instead and save two bytes, but you'll need more bytes to remove the appendix instead of `P;d`; see next remark. Or, if your hold space is empty, do `G;s/$/9876543210/` without byte penalty. * If you need further processing, you'll need some more bytes for `s/\n.*//` instead of `P;d`. * You could save two bytes each for those buggy old GNU `sed` versions * No, you can't save those six backslashes as extended regular expressions don't do backreferences [Answer] ## Empty regexes are equivalent to the previously encountered regex (thanks to [Riley](https://codegolf.stackexchange.com/users/57100/riley) for discovering this from an [anagol submission](http://golf.shinh.org/reveal.rb?ASCII+Pylon/mitchs+%28tails%29_1524733941&sed)) Here is an example where we are tasked with creating 100 `@`s in an empty buffer. ``` s/$/@@@@@@@@@@/;s/.*/&&&&&&&&&&/ # 31 bytes s/.*/@@@@@@@@@@/;s//&&&&&&&&&&/ # 30 bytes ``` The second solution is 1 byte shorter and uses the fact that empty regexes are filled in with the last encountered regex. Here, for the second substitution, the last regex was `.*`, so the empty regex here will be filled with `.*`. This also works with regexes in `/conditionals/`. Note that it is the previously *encountered* regex, so the following would also work. ``` s/.*/@@@@@@@@@@/;/@*/!s/$/@/;s//&&&&&&&&&&/ ``` The empty regex gets filled with `@*` instead of `$` because `s/$/@/` is never reached. [Answer] # Unary-UCD-Decimal conversions The programs below are adapted from solutions in [anarchy golf](http://golf.shinh.org/). The solutions below work on GNU sed 4.2.2, where empty labels are allowed. It is possible I've missed better solutions on anarchy golf. ## Unary to Decimal, `sed -r` at 47 bytes From solutions by [%20](http://golf.shinh.org/reveal.rb?Collatz+Problem/%2520_1480130793&sed) and [tails](http://golf.shinh.org/reveal.rb?Bijective+base+10+add/tails_1536134169&sed). Works only for integers greater than 0. The chosen unary digit (`-` in the below program) occurs 3 times in the program. ``` : s/-/<<123456789-01>/ s/(.)<.*\1(-*.).*>/\2/ t ``` [Try it online!](https://tio.run/##K05N@f/fiqtYX1ffxsbQyNjE1MzcwlLXwNBOHyiooadpo6cVY6ihq6Wnqadlpx9jpM9V8v@/LtHgX35BSWZ@XvF/3SIA "sed 4.2.2 – Try It Online") and [(bash wrapper for easier testing)](https://tio.run/##FcgxCoQwEEDR3lNMsaAGJuPEddeV4EnSKAloo2LSCLn7uFb/8ecpLnKFmJcwecAX53QCenBue3QBZtqPRDF4mtftKeAJpQxFJCRr2bTv7vPtf9jwSP9Z6dpq5bhCpWutRnKGiiSlSNsYvgE "Bash – Try It Online") ## Decimal to UCD, `sed` at 39 bytes From a solution by [%20](http://golf.shinh.org/reveal.rb?Collatz+Problem/%2520_1480130793&sed). Works on all integers, including negative ones. ``` : s/[1-9]/&;/g y/123456789/012345678/ t ``` [Try it online!](https://tio.run/##K05N@f/fiqtYP9pQ1zJWX81aP52rUt/QyNjE1MzcwlLfAMbU5yr5/9/QwNLsX35BSWZ@XvF/3SIA "sed 4.2.2 – Try It Online") ## Decimal to Unary (via UCD), `sed` 55 bytes From a solution by [tails](http://golf.shinh.org/reveal.rb?Boxception/tails_1626672646&sed). Works on all integers, including negative ones. ``` : s/[1-9]/&;/g y/123456789/012345678/ s/;0/9;/ t s/0//g ``` [Try it online!](https://tio.run/##K05N@f/fiqtYP9pQ1zJWX81aP52rUt/QyNjE1MzcwlLfAMbUB6qxNtC3tNbnKgEyDfT10///NzKwBAA "sed 4.2.2 – Try It Online") and [(bash wrapper)](https://tio.run/##S0oszvivn19Qol@cmqKflJkHohXU/1txFetHG@paxuqrWeunc1XqGxoZm5iamVtY6hvAmPpANdYG@pbW@lwlQKaBvn76f/WatPycFAVdw5rSvMxCBd3k/7pGBpYA "Bash – Try It Online") [Answer] Instead of clearing the pattern space with `s/.*//`, use the `z` command (lowercase) if you go with GNU sed. Besides the lower bytes count, it has the advantage that it won't start the next cycle as the command `d` does, which can be useful in certain situations. [Answer] Let's talk about the `t` and `T` commands, that although they are explained in the man page, it's easy to forget about it and introduce bugs accidently, especially when the code gets complicated. **Man page statement for `t`:** > > If a `s///` has done a successful substitution since the last input line was read and since the last t or T command, then branch to label. > > > **Example showing what I mean:** Let's say you have a list of numbers and you want to count how many negatives there are. Partial code below: ``` 1{x;s/.*/0/;x} # initialize the counter to 0 in hold space s/-/&/ # check if number is negative t increment_counter # if so, jump to 'increment_counter' code block b # else, do nothing (start a next cycle) :increment_counter #function code here ``` Looks ok, but it's not. If the first number is positive, that code will still think it was negative, because the jump done via `t` for the first line of input is performed regardless, since there was a successful `s` substitution when we initialized the counter! Correct is: `/-/b increment_counter`. If this seemed easy, you could still be fooled when doing multiple jumps back and forth to simulate functions. In our example the `increment_counter` block of code for sure would use a lot of `s` commands. Returning back with `b main` might cause another check in "main" to fall in the same trap. That is why I usually return from code blocks with `s/.*/&/;t label`. It's ugly, but useful. [Answer] Expanding upon this [tip answer](https://codegolf.stackexchange.com/a/51329/59010), regarding the conversions between decimal and plain unary number formats, I present the following alternative methods, with their advantages and disadvantages. **Decimal to plain unary:** 102 + 1(r flag) = 103 bytes. I counted `\t` as a literal tab, as 1 byte. ``` h : s:\w::2g y:9876543210:87654321\t : / /!s:$:@: /\s/!t x;s:-?.::;x G;s:\s::g /\w/{s:@:&&&&&&&&&&:g;t} ``` [**Try it online!**](https://tio.run/nexus/sed#@5/BZcVVbBVTbmVllM5VaWVpYW5mamJsZGhgBWPFlChYcekr6CsWW6lYOQCZMcX6iiVcFdbFVrr2elZW1hVc7kB2TLGVVTpQsly/uhioTA0OrNKtS2r//zc0@pdfUJKZn1f8X7cIAA) Advantage: it is 22 bytes shorter and as extra, it works with negative integers as input Disadvantage: it overwrites the hold space. However, since it's more likely that you'd need to convert the input integer right at the start of the program, this limitation is rarely felt. **Plain unary to decimal:** 102 + 1(r flag) = 103 bytes ``` s:-?:&0: /@/{: s:\b9+:0&: s:.9*@:/&: h;s:.*/:: y:0123456789:1234567890: x;s:/.*:: G;s:\n:: s:@:: /@/t} ``` [**Try it online!**](https://tio.run/nexus/sed#PYy7EkAwFET7fIgihhtvWYV0fkKlosGIgjF@XdwobHV25uw6i6hFoCDI0AVh0Q86hAo8xloaEOPYcJEEiBMqSbO8KKta4yeeH6xQLFnpmPoZ/sDg@91v54zPs6z7tMzWRdsL) Advantage: it is 14 bytes shorter. This time both tip versions work for negative integers as input. Disadvantage: it overwrites the hold space For a complicated challenge, you'll have to adapt these snippets to work with other information that may exist in the pattern space or hold space, besides the number to convert. The code can be golfed more, if you know you only work with positive numbers or that zero alone is not going to be a valid input / output. An example of such challenge answer, where I created and used these snippets, is the [Reciprocal of a number (1/x)](https://codegolf.stackexchange.com/a/115528/59010). [Answer] # Make use of sed's line-handling ability With flexible challenge I/O, it can pay to have input/output separated by newlines instead of any other character by taking advantage of sed's commands for handling lines (like `D`, `N`, `n`, `G`, `H`, `P`, `s`'s `m` flag) instead of only being limited to `s` substitutions. This can also open the opportunity for using `D` for looping instead of labels and goto, especially in sed versions that don't permit empty labels. [Answer] # The `L` command in old GNU sed versions Used, for example, in the second solution in <https://codegolf.stackexchange.com/a/220633/>. Older versions of GNU sed like GNU sed 4.2.2 have the `L` command, which was later removed in newer versions. From [the archived docs](https://web.archive.org/web/20161224125356/https://www.gnu.org/software/sed/manual/sed.html#Extended-Commands), > > `L` *n* > > > This GNU `sed` extension fills and joins lines in pattern space to produce output lines of (at most) *n* characters, like `fmt` does; if *n* is omitted, the default as specified on the command line is used. This command is considered a failed experiment and unless there is enough request (which seems unlikely) will be removed in future versions. > > > [Answer] # `#n` at first to imply `-n` > > The "#" and the remainder of the line are ignored (treated as a comment), with the single exception that if the first two characters in the file are #n, the default output is suppressed; this is the equivalent of specifying -n on the command line. > > > [Source: sed (from SUSv2)](https://pubs.opengroup.org/onlinepubs/7908799/xcu/sed.html) This is useful if you prefer NOT to output something by default. ...But is it really useful? `-n` adds either 1 or 2 bytes but `#n` and LF adds 3. [Answer] # `i`, `a`, and `c` (The answer focuses on GNU sed because GNU sed's invocation of these commands is slightly shorter than that of POSIX, but otherwise I think the functionality should be the same). These insert to, append to, and change the pattern space respectively. The lines they add are printed and so are not edited into the pattern space, meaning that the program will not be able to manipulate these lines. But they are shorter than `s`, if you want to insert some unchanging lines. Compare the following two lines: ``` s/^/text\n/ # 11 bytes itext # 5 bytes ``` Now I want to focus on `c`. `c text` replaces the pattern space with `text`. This text will be printed immediately, since the `c` makes sed move on to the next line. This means that the commands follows a call to `c` are effectively ignored. This behaviour of `c` can be useful in challenges where there are only few possible outputs, particularly when combined with the conditional `/.../`. An example is the ['Hello, World!'](https://codegolf.stackexchange.com/q/55422) challenge, where `c` is shorter than `s`: ``` s/^/Hello, World!/ # 18 bytes cHello, World! # 14 bytes ``` Another example is [this challenge](https://codegolf.stackexchange.com/q/187816) ([sed answer](https://codegolf.stackexchange.com/a/190946)) to swap the strings `Good` and `Bad`. The outputs are restricted to being `Good` (when the input is `Bad`) or `Bad` (when the input is `Good`). `s` gives 21 bytes: ``` s/Goo/Ba/;t;s/Ba/Goo/ ``` Using `c` (in combination with `/.../`) gives 13 instead: ``` /B/cGood cBad ``` If the input matches `/B/`, i.e. it the input is `Bad`, `Good` is printed and the program skips processing this input line. So the program only ever reaches the second line if the input doesn't match `B`, i.e. if the input is `Good`. Then in this case the output is set to `Bad`. [Answer] In sed, the closest thing to a function that you can have is a label. A function is useful because you can execute its code multiple times, thus saving a lot of bytes. In sed however you would need to specify the return label and as such you can't simply call this "function" multiple times throughout your code the way you would do it in other languages. The workaround I use is to add in one of the two memories a flag, which is used to select the return label. This works best when the function code only needs a single memory space (the other one). **Example showing what I mean:** taken from a project of mine to write a small game in sed ``` # after applying the player's move, I overwrite the pattern space with the flag "P" s/.*/P/ b check_game_status :continue_turn_from_player #code ``` --- ``` b calculate_bot_move :return_bot_move # here I call the same function 'check_game_status', but with a different flag: "B" s/.*/B/ b check_game_status :continue_turn_from_bot #code (like say 'b update_screen') ``` --- ``` :check_game_status # this needs just the hold space to run #code /^P$/b continue_turn_from_player /^B$/b continue_turn_from_bot ``` The labels should be golfed of course to just one letter, I used full names for a better explanation. [Answer] Mostly useless step: ``` y|A-y|B-z| ``` This will only translate `A` to `B` and `y` to `z` (... and `-` to `-` ;), but nothing else, so ``` sed -e 'y|A-y|B-z|' <<<'Hello world!' ``` will just return: ``` Hello world! ``` You could ensure this will be useless, for sample by using this on lower-case hexadecimal values (containing only `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `a`, `b`, `c`, `d`, `e` or `f`.) A little worst: ``` sed '; ;/s/b;y|A-y|B-z|;s ;s/ //; ; ;' <<<'Hello world' Hello world ``` Why did this **not** suppress the space? [Answer] # Combine `s` substitutions The `s` command takes many bytes (4 + 1 for the statement separator), so combining them can save bytes. [An example](https://codegolf.stackexchange.com/a/221378): the following is at 17 bytes ``` s/\S+ // s/\S+$// ``` while combining the two substitutions gives 15 bytes ``` s/^\S+ |\S+$//g ``` [Answer] # Use back references Most people know that you can mark some parts of your regex with `\(\)` and later refer to it as `\1` (or `\2` for the second and so on) in your substitution. But you hardly ever see *back references*, using `\1` in the regex itself. For extended regular expressions (option `-E` to `sed`), this has been removed from the standard, but GNU `sed` supports it anyhow, so it works at tio.run, for example. For example, this ERE `(.)\1` matches a double character or this one `(.).*\1` appearing twice in the pattern space. [See here](https://codegolf.stackexchange.com/a/266985/72726) for an example, how this makes things easier (and much shorter!). Complicated task like [this one](https://codegolf.stackexchange.com/questions/266951/get-the-bible-verse/266969#266969) looking for matches in a file or [this one](https://codegolf.stackexchange.com/questions/266223/find-the-conflict-free-sitting-arrangement/266251#266251) or [this one](https://codegolf.stackexchange.com/questions/265307/play-a-game-of-memory/265363#265363) would almost be impossible without this feature. # Math with back references And it's great for teaching `sed` to count. I know you can solve some of those problems using `y`, but as soon as you have more than one thing to increment or decrement, this is the way to go. See examples [here](https://codegolf.stackexchange.com/questions/264903/order-by-earliest-lower-digit/265011#265011) or [here](https://codegolf.stackexchange.com/questions/38325/minimum-excluded-number/265157#265157) or [try the 151-byte decimal add online](https://tio.run/##XcyxDsIgFIXhnae4Boe2CT1woRbs7FsQpxrj0jYBX1@UbjY505ecPz1m9VzepSTcobRh64bL6IOEuBqR0DR9@1vftdEqRBM54J9ZVra6MkmQ0ZhyvUoNWbHvJAHbBMJpPiRpT9Ixed6TENmUYskJp4kFs/WaxuCt@6xbfq1LKur2BQ "sed – Try It Online") to examine how it works. [Answer] Okay, here's a weird functioning of (GNU) sed's regex. For example, if the pattern space is only `qqq`, then the extended regex `s/^|q|$/<&>/g` gives `<q><q><q>`. [Try it online!](https://tio.run/##K05N@f@/WD@uprBGRd9GzU4//f//wsLCf/kFJZn5ecX/dYsA "sed 4.2.2 – Try It Online") I'm not sure, but I think it is because if a character matches, then do the empty strings surrounding it. So because the terminal `q` matches, the match also includes the end of the pattern space, so `$` by itself doesn't get matched because otherwise it would overlap with the previous match (and likewise for `^` and even I think for word boundaries and the like). An example where this is useful is in the following (rather contrived) task: * an input of `a` should give `ab`, * and inputs matching `/a(c+)/` should give `ab\1b`, for example, an input of `accc` should give `abcccb` Without the trick I can get 11 bytes (with the `-E` flag) ``` s/a|c+/&b/g ``` but using it gives 10 bytes ``` s/a|$/&b/g ``` [Try it online!](https://tio.run/##K05N@f@/WD@xRkVfLUk//f//RK7EZCACYwiR/C@/oCQzP6/4v24RAA "sed 4.2.2 – Try It Online") (Do let me know if there is a better example that uses this behaviour). ]
[Question] [ This is an adaption of [Core War](http://en.wikipedia.org/wiki/Core_War), a programming KOTH dating back to the 20th century. To be more specific, it is using an incredibly simplified instruction set primarily based off of the [original proposal](http://corewar.co.uk/cwg.txt). ## Background In Core War, there are two programs battling for control over the computer. The goal of each program is to win by locating and terminating the opposing program. The battle takes place within the main memory of the computer. This memory is called the Core, and it contains 8192 addresses. When the battle starts, the code for each competitor (called a warrior) is placed in a random chunk of memory. Program execution alternates between warriors, performing one instruction of each. Each instruction is capable of modifying a part of the Core, leading to the possibility of self-modifying programs. The goal is to terminate the opposing program. A program terminates when it attempts to execute an invalid instruction, which is any `DAT` instruction. # The Instruction Set Each program consists of a series of low-level instructions, each of which takes two fields, called the A and B fields. This instruction set draws heavily from the original spec. The main changes are 1) clarification on adding/subtracting commands, and 2) a change of the `#` addressing mode to allow it to be used anywhere. Most full versions of Core Wars have over 20 opcodes, 8 addressing modes, and a set of "instruction modifiers." ## Opcodes Each instruction must have one of seven different opcodes. * **`DAT A B`** - (data) - This simply holds the numbers `A` and `B`. Importantly, a process dies when it attempts to execute a DAT instruction. * **`MOV A B`** - (move) - This moves the contents of memory location `A` to memory location `B`. Here is a demonstration of before-and-after: ``` MOV 2 1 ADD @4 #5 JMP #1 -1 ``` ``` MOV 2 1 JMP #1 -1 JMP #1 -1 ``` * **`ADD A B`** - (add) - This adds the contents of memory location `A` to memory location `B`. The two first fields of both are added, and the second fields are added. ``` ADD 2 1 MOV @4 #5 JMP #1 -1 ``` ``` ADD 2 1 MOV @5 #4 JMP #1 -1 ``` * **`SUB A B`** - (subtract) - This subtracts the contents of memory location `A` from (and stores the result into) memory location `B`. ``` SUB 2 1 MOV @4 #5 JMP #1 -1 ``` ``` SUB 2 1 MOV @3 #6 JMP #1 -1 ``` * **`JMP A B`** - (jump) - Jump to location `A`, which will be executed next cycle. `B` must be a number but does nothing (you can use it to store information, though). ``` JMP 2 1337 ADD 1 2 ADD 2 3 ``` The jump means that `ADD 2 3` will be executed next cycle. * **`JMZ A B`** - (jump if zero) - If both fields of line `B` are 0, then the program jumps to location `A`. ``` JMZ 2 1 SUB 0 @0 DAT 23 45 ``` Since the two fields of instruction 1 are 0, the DAT command will be executed next turn, leading to imminent death. * **`CMP A B`** - (compare and skip if not equal) - If the fields in instructions `A` and `B` are not equal, skip the next instruction. ``` CMP #1 2 ADD 2 #3 SUB @2 3 ``` Since the two fields of instructions 1 and 2 are equal in value, the ADD command is *not* skipped and is executed next turn. When two instructions are added/subtracted, the two fields (A and B) are added/subtracted pair-wise. The addressing mode and opcode are not changed. ## Addressing Modes There are three kinds of addressing modes. Each of the two fields of an instruction has one of these three addressing modes. * **Immediate `#X`** - `X` is the line to be used directly in computation. For example, `#0` is the first line of the program. Negative lines refer to lines in the core before the start of program. ``` ... //just a space-filler ... ADD #3 #4 DAT 0 1 DAT 2 4 ``` This will add the first of the two DAT lines to the second, since those are in lines 3 and 4, respectively. You would not want to use this code, however, because the DAT will kill your bot on the next cycle. * **Relative `X`** - The number `X` represents the location of a target memory address, relative to the current address. The number at this location is used in computation. If line `#35` is being executed and contains `-5`, then line `#30` is used. ``` ... //just a space-filler ... ADD 2 1 DAT 0 1 DAT 2 4 ``` This will add the second DAT line to the first. * **Indirect `@X`** - The number `X` represent a relative address. The contents at that location are temporarily added to the number X to form a new relative address, from which the number is retrieved. If line `#35` is being executed, and its second field is `@4`, and the second field of line `#39` contains the number `-7`, then line `#32` is used. ``` ... //just a space-filler ... ADD @1 @1 DAT 0 1 DAT 2 4 ``` This will add the first DAT to the second, but in a more convoluted way. The first field is @1, which gets the data from that relative address, which is the first field of the first DAT, a 0. This is interpreted as a second relative address from that location, so 1+0=1 gives the total offset from the original instruction. For the second field, @1 gets the value from that relative address (the 1 in the second field of the first DAT) and adds it to itself in the same way. The total offset is then 1+1=2. So, this instruction is executed similarly to `ADD 1 2`. Each program can contain up to 64 instructions. When a round starts, the two programs are placed randomly in a memory bank with 8192 locations. The instruction pointer for each program starts at the beginning of the program and is incremented after each execution cycle. The program dies once its instruction pointer attempts to execute a `DAT` instruction. ## Parameters of the Core The core size is 8192, with a timeout of 8192\*8 = 65536 ticks. The core is cyclic, so writing to address 8195 is the same as writing to address 3. All unused addresses are initialized to `DAT #0 #0`. Each competitor must not be longer than 64 lines. Integers will be stored as 32-bit signed integers. ## Parsing In order to make programming easier for competitors, I will add a line-label feature to the parser. Any words that occur on a line before an opcode will be interpreted as line labels. For example, `tree mov 4 6` has the line label `tree`. If, anywhere in the program, there is a field that contains `tree` `#tree` or `@tree`, a number will be substituted. Also, capitalization is ignored. Here is a example of how line labels are substituted: ``` labelA add labelB @labelC labelB add #labelC labelC labelC sub labelA @labelB ``` Here, labels A, B, and C are on lines 0, 1, and 2. Instances of `#label` will be substituted with the line number of the label. Instances of `label` or `@label` are substituted with the relative location of the label. Addressing modes are preserved. ``` ADD 1 @2 ADD #2 1 SUB -2 @-1 ``` # Scoring For each pair of contestants, every possible battle is performed. Since the outcome of a battle depends on the relative offsets of the two programs, every possible offset (about 8000 of them) is tried. Furthermore, each program has a chance to move first in each offset. The program that wins the majority of these offsets is the winner of the pair. For each pair-up that a warrior wins, it is awarded 2 points. For each tie, a warrior is awarded 1 point. You are allowed to submit more than one warrior. The typical rules for multiple submissions apply, such as no tag-teaming, no cooperating, no king-making, etc. There's not really any room for this in Core War anyways, so it shouldn't be a big deal. # The Controller The code for the controller, along with two easy example bots, [is located here](https://github.com/PhiNotPi/NanoCoreWar). Since this competition (when run using the official settings) is completely deterministic, the leaderboard you create will be the exact same as the official leaderboard. ## Example Bot Here is an example bot that demonstrates some features of the language. ``` main mov bomb #-1 add @main main jmp #main 0 bomb dat 0 -1 ``` This bot operates by slowly erasing all other memory in the core by replacing it with a "bomb." Since the bomb is a `DAT` instruction, any program which reaches a bomb will be destroyed. There are two line labels, "main" and "bomb" which serve to replace numbers. After preprocessing, the program looks like this: ``` MOV 3 #-1 ADD @-1 -1 JMP #0 0 DAT 0 -1 ``` The first line copies the bomb to the line immediately above the program. The next line adds the value of the bomb (`0 -1`) to the move command, and it also demonstrates a use of the `@` addressing mode. This addition causes the move command to point to a new target. The next command unconditionally jumps back to the start of the program. --- # Current Leaderboard > > 24 - Turbo > > 22 - DwarvenEngineer > > 20 - HanShotFirst > > 18 - Dwarf > > 14 - ScanBomber > > 10 - Paranoid > > 10 - FirstTimer > > 10 - Janitor > > 10 - Evolved > > 6 - EasterBunny > > 6 - CopyPasta > > 4 - Imp > > 2 - Slug > > > Pairwise Results: ``` Dwarf > Imp CopyPasta > Imp Evolved > Imp FirstTimer > Imp Imp > Janitor Imp > ScanBomber Slug > Imp DwarvenEngineer > Imp HanShotFirst > Imp Turbo > Imp EasterBunny > Imp Paranoid > Imp Dwarf > CopyPasta Dwarf > Evolved Dwarf > FirstTimer Dwarf > Janitor Dwarf > ScanBomber Dwarf > Slug DwarvenEngineer > Dwarf HanShotFirst > Dwarf Turbo > Dwarf Dwarf > EasterBunny Dwarf > Paranoid Evolved > CopyPasta FirstTimer > CopyPasta Janitor > CopyPasta ScanBomber > CopyPasta CopyPasta > Slug DwarvenEngineer > CopyPasta HanShotFirst > CopyPasta Turbo > CopyPasta CopyPasta > EasterBunny Paranoid > CopyPasta Evolved > FirstTimer Evolved > Janitor ScanBomber > Evolved Evolved > Slug DwarvenEngineer > Evolved HanShotFirst > Evolved Turbo > Evolved EasterBunny > Evolved Paranoid > Evolved Janitor > FirstTimer ScanBomber > FirstTimer FirstTimer > Slug DwarvenEngineer > FirstTimer HanShotFirst > FirstTimer Turbo > FirstTimer FirstTimer > EasterBunny FirstTimer > Paranoid ScanBomber > Janitor Janitor > Slug DwarvenEngineer > Janitor HanShotFirst > Janitor Turbo > Janitor Janitor > EasterBunny Janitor > Paranoid ScanBomber > Slug DwarvenEngineer > ScanBomber HanShotFirst > ScanBomber Turbo > ScanBomber ScanBomber > EasterBunny ScanBomber > Paranoid DwarvenEngineer > Slug HanShotFirst > Slug Turbo > Slug EasterBunny > Slug Paranoid > Slug DwarvenEngineer > HanShotFirst Turbo > DwarvenEngineer DwarvenEngineer > EasterBunny DwarvenEngineer > Paranoid Turbo > HanShotFirst HanShotFirst > EasterBunny HanShotFirst > Paranoid Turbo > EasterBunny Turbo > Paranoid Paranoid > EasterBunny ``` The latest update (new versions of Turbo and Paranoid) took about 5 minutes to run on an old laptop. I would like to thank Ilmari Karonen for his improvements to [the controller](https://github.com/PhiNotPi/NanoCoreWar). If you have a local copy of the controller, you should update your files. [Answer] # Dwarven Engineer A new and improved Dwarf. Wins against everything else submitted so far. The fancy [corestep](http://www.infionline.net/~wtnewton/corewar/corestep.c)-optimized step size is probably overkill here. ``` MOV bomb @aim aim MOV bomb @-6326 SUB step aim step JMZ #0 6328 MOV 0 1 bomb DAT 0 3164 ``` Notable features include the fast bombing loop that throws two bombs in four cycles, for an average bombing speed of 0.5c in old Core War jargon, and the use of `JMZ` to detect when the bombing run is complete and it's time to switch to plan B (here, an Imp). --- I used to play Core War back in the 90's (some of you may have seen the basic [guidebook](http://vyznev.net/corewar/guide.html) I wrote back in '97), so I thought it would be interesting to see which old strategies from the RedCode '88 / '94 world might be useful in this variant. My first thoughts were: * There's no `SPL`, thus no replicators (and no imp rings/spirals). This should make bombers strong. (Also, all those fancy bombing strategies designed to deal with replicators and imp spirals? Totally needless and useless here. Just bomb with any `DAT`s.) * Then again, `CMP` scanning is still potentially faster than bombing, so a fast scanner *could* have a chance. * The absence of in/decrements makes core clears very slow. In fact, a core clear in this variant is pretty much just a bomber with a (suboptimal) step size of ±1. Again, this also hurts scanners; a one-shot scanner → bomber strategy *might* work, though. * Quickscanners / quickbombers (an early-game strategy using an unrolled scanning / bombing loop, for those not so familar with Core War jargon) are still potentially useful, but only against long programs (which they themselves are, so there's a kind of a feedback effect here). Hard to say if it's really worth the trouble. * The scoring system is interesting. Ties score half as much points as a win (rather than 1/3, as in traditional Core War), making them more attractive. Then again, about the only program likely to score lots of ties under these rules is an imp. (Also, the absence of de/increments makes imp gates hard, so even simple imps actually *do* have a chance of scoring a tie if they reach their opponent alive.) * Also, because the final rankings only depend on which programs you beat, and not how *much* you beat them by, it tends to favor generalist entries. It's better to just barely beat *all* of your opponents, than to totally destroy half of them and just barely lose to the rest. * Because the code is public, it's *always* possible to find a program that can beat any given earlier submission — possibly even several of them — no matter how good they are in general. Such tricks (like tuning your step size to hit your opponent just before they hit you) can easily seem cheap, though. And, of course, the target player could always just submit a new version with different constants. Anyway, the upshot of all this is that I decided that I should try to write either a fast bomber or a *very* fast scanner, and *maybe* tack a quickscanner/bomber onto it. Out of those options, a fast bomber seemed the simplest and most likely to work. At that point, I spent way too much time tweaking and optimizing PhiNotPi's interpreter code, because I figured I'd probably be running lots of brute force trials to optimize the constants. As it happens, I never had to do that — the code above is pretty much the first version that actually worked (after a couple of failed attempts that just committed suicide due to silly bugs). --- The trick that makes my bomber fast is using indirect addressing to throw two bombs for each `ADD`. Here's how it work: 1. On the first cycle, we execute `MOV bomb @aim`. This copies the `bomb` instruction to whereever in the core the B-field of `aim` points to (initially, exactly 6326 instructions before `aim`, or 6328 instructions before `step`; you'll see why those numbers matter later). 2. On the next step, we execute the `aim` instruction itself! On the first pass, it looks like this: `MOV bomb @-6326`. Thus, it copies `bomb` to the location that the B-field of the instruction at 6326 lines before itself points to. So, what is there at 6326 lines before `aim`? Why, it's the copy of `bomb` we just placed there one cycle earlier! And we just happened to arrange things so that the B-field of `bomb` has a non-zero value, so the new bomb will not be copied on top of the old one, but some distance away (in fact, here the distance is 3164, which is half of our nominal step size 6328; but other offsets could work, perhaps even better). 3. On the next cycle, we adjust our aim with `SUB step aim`, which subtracts the values of the `step` instruction (which also happens to be the jump we're going to execute next, although it *could've* been just a simple `DAT` somewhere) from `aim`. (One detail to note here is that we *kind of* want the A-value of `step` to be zero, so that we'll still throw the same bombs on the next iteration. Even that isn't strictly necessary, though; only the bombs thrown by the *first* instruction need to have their B-field equal to 3164, the rest can be anything.) 4. Next, the `JMZ` check that the instruction 6328 steps away from it is still zero, and if so, jumps back to the top of the code. Now, 6328 is the step size of our bomber, and is divisible by 8 (but not 16); thus, if we just kept throwing bombs every 6328 steps, we'd eventually get back to where we started, having bombed every eighth instruction in the core (and with the extra bombs offset by 3163 = 6328/2 ≡ 4 (mod 8), we would've hit every *fourth* instruction). But we started our bombing run at 6328 instructions *before* the `JMZ`, and stepped backwards by -6328 at every iteration, so we're going to bomb the location 6328 steps *after* the `JMZ` just one iteration before we would hit the `JMZ` itself. So when the `JMZ` detects a bomb at 6328 instructions after it, that's a sign that we've covered as much of the core as we can without hitting ourself, and should switch to a backup strategy before we kill ourself. 5. As for the backup strategy, it's just a plain old `MOV 0 1` imp, because I couldn't think of anything better for now. The way I see it, if we've bombed every fourth location of the core and still haven't won, we're probably fighting something very small or very defensive, and might as well just try to survive and settle for a tie. It's OK, because such small or defensive programs generally aren't very good at killing anything else, and so even if we only win a few fights by chance, we'll probably still come out ahead. --- **Ps.** ~~In case anyone else wants it, here's my [slightly improved fork of PhiNotPi's tournament code](https://github.com/vyznev/NanoCoreWar). It's about twice as fast, saves old battle results so that you don't need to re-run them, and fixes what I believe to be [a minor bug in the battle results calculation.](https://github.com/PhiNotPi/NanoCoreWar/pull/2)~~ The changes have been merged into the [mainline version](https://github.com/PhiNotPi/NanoCoreWar) by PhiNotPi. Thanks! [Answer] # Turbo ``` main add three target test jmz -1 @target bomb mov three @target sub j1 target mov jump @target sub j1 target mov copy @target sub j1 target two mov decr @target j1 jmp @target 1 target dat -8 -8 decr sub #two 3 copy mov 2 @2 jump jmp -2 0 three dat -9 -9 ``` My 2nd ever CoreWar attempt. Designed to beat Dwarf. Scans by 3's for data, then puts a bomb every 2. Each stage runs in only 3 instructions, in a hope that Dwarf's bombs miss it. **NEW Turbo++**: Now enhanced. It scans backward until it finds data, then moves itself there, then bombs backward. The hope is that the move either clobbers the opponent, or is to a place already bombed and therefore safe(ish). ...And an edit to make it scan more sparsely makes it beat everyone! [Answer] # Dwarf A common and simple program that represents a dwarf throwing stones. It places a `DAT` instruction every four addresses. ``` add 2 3 mov 2 @2 jmp -2 #4 dat #0 #4 ``` EDIT: Fixes addressing. Apparently the addressing modes are different from the spec the OP linked to. [Answer] # Graph View This can be used as a debugging tool. It displays the core and shows the location of the player. To use it you have to call it from code. I have also provided a modifed `Game.java` that automatically displays the GraphView. PhiNotPi and Ilmari Karonen recently changed the Controller. Ilmari Karonen has been kind enough to provide an updated GameView at [this location](https://github.com/vyznev/NanoCoreWar/tree/graphics). ``` import javax.swing.*; import java.awt.*; public class GameView extends JComponent{ final static Color[] commandColors = new Color[]{ Color.black, //DAT Color.blue, //MOV Color.blue, //ADD Color.blue, //SUB Color.blue, //JMP Color.blue, //JMZ Color.blue, //CMP }; final static Color[] specialColors = new Color[]{ new Color(0,0,0), new Color(190, 255, 152), Color.yellow, new Color(0, 93, 14), new Color(96, 92, 4), new Color(0, 93, 14), new Color(96, 92, 4), new Color(0, 93, 14), new Color(96, 92, 4) }; final static Color playerOneColor = Color.green; final static Color playerTwoColor = Color.white; final Game game; int playerOneLocation; int playerTwoLocation; final static int width = 128; final static int height = 64; public GameView(Game game) { this.game = game; } @Override public void paint(Graphics g) { int pixelWidth = getSize().width; int pixelHeight = getSize().height; if (width > pixelWidth){ pixelWidth = width; setSize(width, pixelHeight); } if (height > pixelHeight){ pixelHeight = height; setSize(pixelWidth, height); } int squareWidth = Math.min(pixelWidth / width, pixelHeight / height); for (int x = 0; x < squareWidth * width; x += squareWidth){ for (int y = 0; y < squareWidth * height; y += squareWidth){ int index = (y / squareWidth) * width + (x / squareWidth); Color color = commandColors[game.core[index][0]]; if (game.coreData[index] != 0){ color = specialColors[game.coreData[index]]; } if (index == playerOneLocation){ color = playerOneColor; } if (index == playerTwoLocation){ color = playerTwoColor; } g.setColor(color); g.fillRect(x, y, squareWidth, squareWidth); } } } public void setLocations(int p1loc, int p2loc){ this.playerOneLocation = p1loc; this.playerTwoLocation = p2loc; } } ``` Modified Game.java: ``` import javax.swing.*; import java.util.Random; import java.util.ArrayList; import java.util.Arrays; /** * This runs a game of Core Wars between two players. It can be called mutiple times. * * @author PhiNotPi * @version 3/10/15 */ public class Game { final Player p1; final Player p2; final int coreSize; final int coreSizeM1; final int maxTime; final int debug; public int[][] core; public int[] coreData; //Used in debugging. int offset1; int offset2; Random rand; ArrayList<int[]> p1code; ArrayList<int[]> p2code; int p1size; int p2size; GameView gameView; int time = 1000000; //Time in nanoseconds between frames public Game(Player A, Player B, int coreSize, int maxTime, int debug) { p1 = A; p2 = B; coreSize--; coreSize |= coreSize >> 1; coreSize |= coreSize >> 2; coreSize |= coreSize >> 4; coreSize |= coreSize >> 8; coreSize |= coreSize >> 16; coreSize++; this.coreSize = coreSize; this.coreSizeM1 = coreSize - 1; this.maxTime = maxTime / 2; this.debug = debug; core = new int[coreSize][5]; rand = new Random(); p1code = p1.getCode(); p1size = p1code.size(); p2code = p2.getCode(); p2size = p2code.size(); if (debug == 1){ gameView = new GameView(this); JFrame frame = new JFrame("Game"); frame.add(gameView); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.setSize(128, 64); coreData = new int[coreSize]; } } public int runAll() { int sum = 0; for(int i = 0; i < coreSize - p1size - p2size; i++) { sum += run(i) - 1; } if(sum > 0) { return 1; } if(sum < 0) { return -1; } return 0; } public int run() { return run(rand.nextInt(coreSize - p1size - p2size + 1)); } public int run(int deltaOffset) { core = new int[coreSize][5]; //offset1 = rand.nextInt(coreSize); offset1 = 0; for(int i = 0; i != p1size; i++) { //System.arraycopy(p1.getCode().get(i), 0, core[(offset1 + i) % coreSize], 0, 5 ); int[] line = p1code.get(i); int loc = (offset1 + i) & coreSizeM1; core[loc][0] = line[0]; core[loc][1] = line[1]; core[loc][2] = line[2]; core[loc][3] = line[3]; core[loc][4] = line[4]; if (debug != 0){ coreData[loc] = 1; } } offset2 = offset1 + p1size + deltaOffset; for(int i = 0; i != p2size; i++) { //System.arraycopy(p2.getCode().get(i), 0, core[(offset2 + i) % coreSize], 0, 5 ); int[] line = p2code.get(i); int loc = (offset2 + i) & coreSizeM1; core[loc][0] = line[0]; core[loc][1] = line[1]; core[loc][2] = line[2]; core[loc][3] = line[3]; core[loc][4] = line[4]; if (debug != 0){ coreData[loc] = 2; } } int p1loc = offset1 & coreSizeM1; int p2loc = offset2 & coreSizeM1; for(int time = 0; time != maxTime; time++) { if(debug != 0) { //printCore(p1loc,p2loc); //System.out.println("p1loc " + p1loc); //System.out.println("offset " + offset1); gameView.setLocations(p1loc, p2loc); gameView.repaint(); try { Thread.sleep(time / 1000000, time % 1000000); } catch (InterruptedException e) { e.printStackTrace(); } } if(core[p1loc][0] == 0) { return 0; } p1loc = execute(p1loc, offset1, 1); if(debug != 0) { //printCore(p1loc,p2loc); //System.out.println("p2loc " + p2loc); //System.out.println("offset " + offset2); gameView.setLocations(p1loc, p2loc); gameView.repaint(); /*try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); }*/ } if(core[p2loc][0] == 0) { return 2; } p2loc = execute(p2loc, offset2, 2); } return 1; } public int execute(int ploc, int offset, int player) { int line1 = offset + core[ploc][3]; if(core[ploc][1] != 0) { line1 += ploc - offset; } if(core[ploc][1] == 2) { line1 += core[line1 & coreSizeM1][3]; } int line2 = offset + core[ploc][4]; if(core[ploc][2] != 0) { line2 += ploc - offset; } if(core[ploc][2] == 2) { line2 += core[line2 & coreSizeM1][4]; } line1 = line1 & coreSizeM1; line2 = line2 & coreSizeM1; int opcode = core[ploc][0]; ploc = (ploc + 1) & coreSizeM1; //String opDescription = ""; if(opcode == 1) { core[line2][0] = core[line1][0]; core[line2][1] = core[line1][1]; core[line2][2] = core[line1][2]; core[line2][3] = core[line1][3]; core[line2][4] = core[line1][4]; if (debug != 0) { coreData[line2] = player + 2; } return ploc; //opDescription = "Moved from " + line1 + " to " + line2; } if(opcode == 2) { core[line2][3] += core[line1][3]; core[line2][4] += core[line1][4]; if (debug != 0) { coreData[line2] = player + 4; } return ploc; //opDescription = "Added " + line1 + " to " + line2; } if(opcode == 3) { core[line2][3] -= core[line1][3]; core[line2][4] -= core[line1][4]; if (debug != 0) { coreData[line2] = player + 6; } return ploc; //opDescription = "Subtracted " + line1 + " to " + line2; } if(opcode == 4) { ploc = line1; return ploc; //opDescription = "Jumped to " + line1; } if(opcode == 5) { if(core[line2][3] == 0 && core[line2][4] == 0) { ploc = line1; //opDescription = "Jumped to " + line1; } else { //opDescription = "Did not jump to " + line1; } return ploc; } if(opcode == 6) { if(core[line1][3] == core[line2][3] && core[line1][4] == core[line2][4]) { //opDescription = "Did not skip because " + line1 + " and " + line2 + " were equal."; } else { ploc = (ploc + 1) & coreSizeM1; //opDescription = "Skipped because " + line1 + " and " + line2 + " were not equal."; } return ploc; } if(debug != 0) { //System.out.println(opDescription); } return ploc; } /*public void printCore(int p1loc, int p2loc) { int dupCount = 0; int[] dupLine = new int[]{0,0,0,0,0}; for(int i = 0; i < core.length; i++) { int[] line = core[i]; if(Arrays.equals(line, dupLine) && i != p1loc && i != p2loc) { if(dupCount == 0) { System.out.println(Player.toString(line)); } dupCount++; } else { if(dupCount == 2) { System.out.println(Player.toString(dupLine)); } else if(dupCount > 2) { System.out.println(" " + (dupCount - 1) + " lines skipped."); } System.out.println(Player.toString(line)); if(i == p1loc) { System.out.print(" <- 1"); } if(i == p2loc) { System.out.print(" <- 2"); } dupLine = line; dupCount = 1; } } if(dupCount == 2) { System.out.println(Player.toString(dupLine)); } else if(dupCount > 2) { System.out.println(" " + (dupCount - 1) + " lines skipped."); } }*/ } ``` [Answer] # Evolved ~~I honestly don't get how it works. It seems to construct its source code before doing anything. I would love it if someone gave me an explanation for how it works.~~ After studying it, I found that it is simply a modified dwarf with an imp guard. Instead of bombing the enemies with `DAT` instructions, it shuffles the enemies code. It also bombs every two registers instead of every four registers. Given enough time, it would undoubtedly destroy itself. ``` MOV -2 #-1 MOV #4 -9 SUB -5 #6 MOV #1 1 MOV #-6 #4 SUB @8 @7 JMP -3 @4 DAT #-4 8 JMP -1 9 JMP 5 #-10 CMP @-1 #0 SUB 3 #-10 JMP @10 #-9 JMZ #1 10 MOV #3 2 ADD @9 @-3 CMP #-3 @7 DAT @0 @-2 JMP @-7 #6 DAT @-8 -6 MOV @0 #9 MOV #2 1 DAT @6882 #-10 JMP @3 4 CMP @8 2 ADD -7 @11 ADD @1 #-9 JMZ @-5 7 CMP 11 5526 MOV @8 6 SUB -6 @0 JMP 1 11 ADD @-3 #-8 JMZ @-14 @-5 ADD 0 @-8 SUB #3 @9 JMP #-1 5 JMP #9 @1 CMP -9 @0 SUB #4 #-2 JMP #-8 5 DAT -1 @-10 MOV 6 #2 CMP @-11 #-14 ADD @4 @-3 MOV @5 #-6 SUB -3 -2 DAT @-10 #-1 MOV #-13 #-6 MOV #1 5 ADD 5 #-5 MOV -8 @-1 DAT 0 10 DAT #5 #7 JMZ 6 -5 JMZ -12 -11 JMP 5 @-7 MOV #7 -3 SUB #-7 @-3 JMP -4 @-11 CMP @-5 #-2 JMZ @-1 #0 ADD #3 #2 MOV #5 @-6 ``` [Answer] # CopyPasta Never participated to a CoreWar, this simple program is just trying to copy-paste himself and then execute the copy. It may not have the correct behavior, please tell me if it is the case. It is too pacifist and can't win in fact. ``` MOV 6 0 MOV @-1 @-1 CMP @-2 3 JMP 4242 0 SUB -3 -4 JMP -4 0 DAT 0 4244 ``` [Answer] # FirstTimer If it does work, it should try to take position at the start of the core and create a defens ``` main MOV 5 #0 ADD #data #main CMP #main #max JMP #0 0 JMP #main 0 MOV #data #100 ADD #data -1 JMP -2 0 data DAT 1 1 max DAT 8 3 ``` [Answer] # Janitor It should check if the following addresses are empty and if not it cleans them (thus, hopefully, erasing the opponent bot). **Edit:** This new version should be quicker (now that I understood the `JMZ` command and the `@` reference correctly). ``` JMZ 2 6 MOV 4 @-1 ADD 2 -2 JMP -3 0 DAT 0 1 DAT 0 0 ``` [Answer] # ScanBomber Remove my comments before compiling. Scans for a while, then bombs when it finds a program. It probably will still lose to my Dwarf, though. ``` scan add #eight #range ; scan jmz #scan @range sub #six #range fire mov #zero @range ; bombs away! (-6) add #two #range mov #zero @range add #two #range mov #zero @range add #two #range mov #zero @range ; (+0) add #two #range mov #zero @range add #two #range mov #zero @range add #two #range mov #zero @range add #two #range mov #zero @range ; (+8) range jmp #scan 6 two dat 0 2 six dat 0 6 zero dat 0 0 eight dat 0 8 ``` [Answer] # Han Shot First (v2) I figured the competition could use some more diversity, so here's my second entry: a one-shot `CMP` scanner. This is **version 2**, with improved anti-Imp defenses — it can now beat Imp, if only by just one point. It still loses to Dwarven Engineer, but beats everything else so far, putting it currently in tied first place. ``` scan ADD bomb aim aim CMP 17 12 JMZ scan #-3 loop MOV bomb @aim ADD step aim step JMP loop #2 bomb DAT 10 10 ``` It works by comparing adjacent core locations 5 steps apart, at 10-step intervals, until it finds a difference. When it does, it starts throwing bombs at 2-step intervals until it kills its opponent or loops all the way around the core to reach itself. If the scan does *not* find anything else, it will eventually loop around and find its own code and attack it. This would be suicidal, but for the fortunate coincidence that the first bomb lands squarely on the `aim` line, causing the next bomb to be thrown 12 positions (rather than the usual 2) down the core, conveniently skipping the code. (This also happens with 50% probability if the scan does find something, but fails to kill the opponent.) Since the core size is a multiple of two, this will also keep happening if the bombing run loops around, eliminating the need for a further backup strategy. (This self-bombing trick was originally a pure coincidence — I had planned for a completely different way to switch from scanning to bombing mode if nothing was found, but when I first tested the code, the constants just happened to be right to make it work this way, and I decided to stick with it.) [Answer] # Imp ``` MOV 0 1 ``` Simply inches through the program. [Answer] # Slug ``` mov ones @-1024 mov from -3 mov here -3 loop mov @-5 @-4 add ones -5 jmz -17 -6 add ones -8 jmp loop 42 ones dat 1 1 from dat 2 2 here dat -11 -11 ``` Crawls through memory space backwards. Occasionally throws a bomb far away. [Answer] # Paranoid Kind of a copy-pasta but it will check if the code have been modified by bombing. If so it copy past a dwarf and execute it. If I manage to make the GameView again I'll try to change some of the constants. ``` copy MOV data copy loop MOV @-1 @-1 CMP @copy end out JMP check 0 SUB loop copy JMP loop 0 data DAT 0 4109 check MOV data copy loop2 CMP @copy @copy JMP ok 0 MOV aah 2 ok CMP @copy end JMP 4098 0 SUB loop copy JMP loop2 0 panic MOV end copy MOV jump out JMP loop 0 jump JMP 4124 0 dwarf ADD 2 bomb MOV bomb @bomb JMP dwarf 4 bomb DAT 0 4 aah JMP 3 0 end DAT 19 4127 ``` [Answer] # Easter Bunny He enjoys hopping backwards :) ``` loop mov 0 -10 add data loop cmp -7 data jmp -13 0 jmp loop 0 data dat 1 1 ``` ]
[Question] [ Consider the array `[5, 6, 8, 3, 9, 4, 2, 1, 7]`. If we list how far each number has moved from it's (1-indexed\*) index, we have (considering absolute distance): ``` Array: [5, 6, 8, 3, 9, 4, 2, 1, 7] Index: [1, 2, 3, 4, 5, 6, 7, 8, 9] Dists: 4 4 5 1 4 2 5 7 2 ``` We can then group the elements of the array based on their distance away from their indices: ``` [[3], [4, 7], [5, 6, 9], [8, 2], [1]] ``` Additionally, we can optionally include empty lists to indicate distances not there (e.g. `0`): ``` [[], [3], [4, 7], [], [5, 6, 9], [8, 2], [], [1], []] ``` Note that the maximum distance an element can be from its index is `len(list) - 1` and the minimum is `0`, so the list (including empty lists) will always be the same length or less as the original list. \*: Note that it doesn't matter if we use 1 or 0 indexing --- Given a list of `n` positive integers, group the elements of the list by their absolute distance from their indices. The input is guaranteed to be a permutation of `[1, 2, 3, ..., n]` and will have a minimum of `3` elements. You may choose to include empty lists in the output, but only if the length of the output is the same length as the input. The elements of the groups can be separated with any clear, consistent, non-digit separator, and the groups themselves should be separated in the same way, but with a separator that's different from that used to separate the elements of the groups. For example, spaces and newlines, or nested lists. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. ## Test cases ``` [1, 3, 2] -> [[1], [3, 2]] [3, 2, 4, 1] -> [[2], [4], [3], [1]] [1, 2, 3, 4] -> [[1, 2, 3, 4]] [2, 5, 3, 1, 4, 6] -> [[3, 6], [2, 4], [5, 1]] [2, 1, 3, 6, 5, 7, 4] -> [[3, 5], [2, 1, 7], [6], [4]] [1, 7, 4, 2, 8, 6, 3, 5] -> [[1, 6], [4], [2], [8, 5], [3], [7]] [2, 6, 8, 3, 1, 7, 9, 5, 4] -> [[2, 3, 7], [9], [5], [6, 1], [8, 4]] [5, 6, 8, 3, 9, 4, 2, 1, 7] -> [[3], [4, 7], [5, 6, 9], [8, 2], [1]] [1, 7, 5, 10, 8, 9, 6, 3, 4, 2] -> [[1], [6], [5], [8, 9], [7, 3, 4], [10], [2]] [10, 8, 5, 9, 2, 3, 4, 7, 6, 1, 11, 12] -> [[11, 12], [7], [5], [2, 3, 4, 6], [9], [8], [10, 1]] [3, 5, 10, 11, 6, 7, 12, 14, 8, 2, 9, 13, 1, 4] -> [[6, 7, 8, 13], [3, 9], [5], [12], [14], [10, 11], [2], [4], [1]] [6, 14, 8, 9, 12, 4, 13, 7, 5, 15, 10, 11, 3, 1, 2] -> [[7, 10, 11], [4], [5], [6, 8, 9, 15], [13], [12], [3], [14], [1, 2]] [8, 12, 13, 7, 16, 5, 14, 15, 3, 10, 2, 4, 1, 9, 11, 6] -> [[10], [5], [7], [11], [9], [3], [8, 14, 15], [4], [2], [12, 13, 6], [16], [1]] [14, 5, 10, 1, 2, 4, 13, 9, 7, 12, 8, 11, 3, 15, 16, 6] -> [[9, 11, 15, 16], [4, 7, 12], [5, 1, 2, 8], [13], [10], [3, 6], [14]] [19, 8, 16, 15, 2, 6, 11, 18, 12, 9, 3, 14, 4, 1, 7, 5, 17, 13, 10] -> [[6, 17], [9], [14], [2, 12], [11], [13], [8], [3, 7], [4, 10], [18], [15, 5], [16, 1], [19]] [19, 11, 7, 5, 3, 1, 20, 16, 17, 15, 10, 13, 6, 18, 2, 12, 9, 4, 14, 8] -> [[5, 10, 13], [3], [7, 18, 12], [1, 15, 14], [6], [16, 17, 9], [11], [8], [20, 2], [4], [19]] ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` </.~]|@-#\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bfT16mJrHHSVY/5rcqUmZ@QrpCmY6iiY6ShY6CgY6yhY6iiY6CgY6SgY6iiYwxQYKhgrGME4QKaCiYIhjAtUagrWaQjWafYfAA "J – Try It Online") * `</.~` Group by... * `]|@-#\` Absolute value of `|@` input minus all length prefixes (ie, 1 2 3... n) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ạJĠị ``` A monadic Link that accepts the list of integers and yields a list of lists of integers. Does not perform the optional empty list insertions. **[Try it online!](https://tio.run/##y0rNyan8///hroVeRxY83N39////aFMdBTMdBQsdBWMdBUsdBRMdBSMdBUMdBfNYAA "Jelly – Try It Online")** ### How? Pretty simple for Jelly this one... ``` ạJĠị - Link: list of integers, A J - range of length of A -> [1,2,...,length(A)] ạ - A absolute difference that (vectorises) Ġ - group indices of that by their values ị - use those to index back into A ``` [Answer] # JavaScript, 151 ``` x=>x.map((y,i)=>[y,Math.abs(y-i-1)]).sort((a,b)=>a[1]-b[1]).reduce((g,z)=>d-z[1]?(d=z[1],[...g,[z[0]]]):[...g.slice(0,-1),[...g.at(-1),z[0]]],[[]],d=0) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ż-ȧZ⁽tṡfyĠ• ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvC3Ip1rigb104bmhZnnEoOKAoiIsIiIsIls1LCA2LCA4LCAzLCA5LCA0LCAyLCAxLCA3XSJd) The pains of not having tons of array focused built-ins ## Explained ``` ż-ȧZ⁽tṡfyĠ• ż # The range [1, len(input)] -ȧ # and the absolute difference with the input Z # Zip those together ⁽tṡ # and sort that by tail - this is a work around way to group one list by the results of a function applied to it fy # flatten and uninterleave this - this pushes the original list and the absolute differences but sorted Ġ # group the indexes on consecutive items • # and mold the other list to the shape of that. ``` [Answer] # [Factor](https://factorcode.org/), 52 bytes ``` [ dup '[ dup _ index 1 + - abs ] collect-by values ] ``` The `collect-by` word postdates build 1525, the one TIO uses, so here's a screenshot of running the above code in build 2101's listener: [![enter image description here](https://i.stack.imgur.com/JlFLe.png)](https://i.stack.imgur.com/JlFLe.png) `collect-by` is a combinator that collects values in an associative array by a given quotation. The quotation calculates the difference between an element and its index. Then we take only the values from the associative array, discarding the keys. [Answer] # [R](https://www.r-project.org/), 32 bytes ``` function(x)split(x,(x-seq(x))^2) ``` [Try it online!](https://tio.run/##jZTdbtswDIXv9xQGdmMDLmA6sn4u2hcJsmLLsiFAl3ZtCmRPn4k81I@xTdlFmlQSeT4eUnq9fn99fn95/PLr8evx7eXp8/7w43A631@/vZ/25@Pzqb8Mcfl47i9jf7l7O/yMC8Onefh7XL/vaew2YzcPQ/exu3votlvajd2Wl3a7D/8K4u2xM2NHJW7mOCPB/Ica4SThMYmpZPNaIzCeWOQQibot4XHNsixj8Xc8Ru1EKNxKRrdCicuL5oqHHP@0KK5ZkhOmGOQlLWdZlWezQWKVVxVxy7VZrSRF3VEmCHRFDOeENEj1wswWQKhFvlTpQyqBdSpDhFwFcD5o5vk/eu0ElyZRCckc8@fU2czuVcHpSLDIBOsaUlBYRGROIk4EIwbxp5aU/@F@0s1RNnvpId6ep00ukbNaUSX20QjSLEikg1sQcNDzlt660j6gkcnylEfH3DLdZuUADgN17USFCqTKFZf2slAaJs0GuE1B3FSc7WfDqykgIdw9BiW91VN@V6BFqzuOCVhyx8AYMoNPydYXLUlKS8neHFhTeplxcDe0qb5Yt6CMClKxsZPuTRq0JeX0lYmTtt6qjw20AHGL/HgYRE2dDaAyyUPtt9PZm1aTR@W9QPfmhAljgeeVzmktwCUUsOgbRumtoXADnzKVTt6k9bhqLvEuEy6O1mV0pEsJ@XR5RZMTOouS0OSXJemEUqOUwQzVveISrr8B "R – Try It Online") ([51 bytes](https://tio.run/##K/qfXpRfWhCfVBmfkllckJOYnJqbmldi@z@tNC@5JDM/T6NC0zexQAPOzdOsiE5MKtao0C3WtLXNi9UpttEtTi0EKtPEbpRGsoapjoKZjoKFjoKxjoKljoKJjoKRjoKhjoI5UA8A) if we want to include the empty lists for displacements that don't occur: `function(x)Map(function(n)x[abs(x-s)==n],s<-seq(x))`, painfully long because of the double "`function`" keyword, although this could be replaced by "`\`" in [R](https://www.r-project.org/)≥4.1 for 37 bytes) [Answer] # [Python 2](https://docs.python.org/2/), 111 bytes ``` o={} for a,b in[[abs(x+1-y),y]for x,y in enumerate(input())]:o.setdefault(a,[]).append(b) print[o[p]for p in o] ``` [Try it online!](https://tio.run/##JY5BDoIwEEX3PcXsaHUkAoJiwkmaLgqMkUTbBkpCYzw7Qt1N/sv7f1zwT2vytbM9QQNJkqy2@XzZw46gsYXBSKnbiS/H7BQEBrWDBcMGgMz8plF74oNxs@dCqLtNJ/I9PfT88lyjVCLVzpHpeSuYGwfjpZUutri9w6p122S0UMf3HwQcoFhliVAh3BAKhBrhgpAjZAhXxeR2lRFkEVRbtJOYZudo1VEv/qL6AQ "Python 2 – Try It Online") Not particularly short or clever but it was fun. Unbelievably `o.setdefault(a,[]).append(b)` is shorter than any way I could find of using a comparison. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .¡Nα ``` Input and index-comparison are both 0-based. [Try it online](https://tio.run/##yy9OTMpM/f9f79BCv3Mb//@PNtFRMNVRMNdRMNJRsNBRMNZRMNRRMNBRMIsFAA) or [verify all test cases](https://tio.run/##NVCxDcJADFwlSm2hd/4/@VRswAJRCpAoqCiQkFLQMgAbMAIrMABDsEi4sx8pUuzz3fn858v@cDqu12XbNt/7o2m3y7p5P3ef13qTdZqCdKKzNBN@EiWwDCg7iSxVEsqASfaW/Ayw93lgAfoAsJPknIyWol4KmMZLFSzGxugvTjJiUEwePQmBBMhCgJLBV3w1JhVoMyaqohFsJdtikpIdLBxH4tyiVUaWGQ2m5lB5DyTKU0d/BqpDvTnayiDVrfjiwd0ggt6JhWA2CPEY2ZYU0qK5WpKeLmNVqIMWazR1X7PynWngFtGOmucf). The groups are sorted based on their first occurrence, rather than their index-difference, which is allowed in the comments. If this wouldn't have been the case, it would be this 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) monstrosity instead (with 1-based input/comparison), since 05AB1E lacks a sort + group-by builtin in one, and doing them one at a time when comparing it to their index isn't exactly ideal.. ``` āøΣÆÄ}.¡ÆÄ}€€н ``` [Try it online](https://tio.run/##yy9OTMpM/f//SOPhHecWH2473FKrd2ghmH7UtAaILuz9/z/aVEfBTEfBQkfBWEfBUkfBREfBSEfBUEfBPBYA) or [verify all test cases](https://tio.run/##NVA7TsQwEL1KtPUIZTa2E1d7kCgFSBRUFEhIW1CA0B6AG6xoOQANDaFGnGEvEt57k0iWPPM@4ze@f7i@ubtdHo@HXXM5vTW7w3H5eZ4/f9/n0/z6dPV91n15@cD5@1psGUe3zvaTNSMuS@YsHWVnieXeMkoHU6KlvgDsg3cWkA8AO8uhKWhp6q1CKV1ewSo1qM2czVswVf4UUYRkYIoBUYHDcdag8qAvoBzTEuR7yF1JqSkBVtKJuB7afJRp1CA7WedO8LjWbeMv6PdYHFS4bR1Y4@1hnZc5IZSVYCHEn2BsPVMpSxqrML3itqvFA1WyVvZ@y8v/di6oIUmbTdM/). **Explanation:** ``` .¡ # Group the (implicit) input-list by: N # Push the 0-based index α # Get the absolute difference of this index and the number # (after which the list of lists is output implicitly as result) ā # Push a list in the range [1,input-length] ø # Create pairs with the input-list Σ # Sort this list of pairs by: Æ # Reduce the pair by subtracting Ä # And take the absolute value of that }.¡ÆÄ # After the sort-by, do the same with a group-by }€ # After the group-by, map over each list of pairs: € # Map over each inner pair: н # Only leave the first value # (after which the list of lists is output implicitly as result) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` GatherBy[#,i=0;Abs[#-++i]&]& ``` [Try it online!](https://tio.run/##XZRda9swFIbv/SuMO8pGFbAcWbYIKdlYGYNejGV3whdZcDdD6wRbhY7S357pfEjydpFEts553@ccHeXp4H73Twc3HA@Xh@3lCzxOn/7YKzFsy83Hn7O9Wt3cDN11d31x/ezmfJvv3TSMv@5e3HQ4Ovtuf5yGs/s6np8d7YgiK1a3m40o8tVtjssu@3yy2eswitOze/MaP053L@epn@fhNO4o7Xt/fjwce1tYn1LcD7OzRbd7HMZ@k33zAc4O4@r2YedFivx9Ifanye3gcbvFpVcWxYeiy8QrJAnEfesuVop8LfKqAxprZSdyi89dhr8iVyKXvFvBrsIQ@JIQJDHIh6ogkV74bb@s8UmikuagNSy9BOjDbw0mFE5AGvOaJOvf1ZzhIxpYasIhiAb1/W6LyRgegXQExxJa1sIqGvbVmEqkXswgQHCnitDVIC/6AzTJIUW9EDEBB2G5BKRgGQo2nF8t@9mgtSxRy4Ry1H@npCNHyzoNtx2kSioWBEmnRqkqSDUo680kfKIwPWBXgnpM0bH6liz4zNYRF9I1akuoXKFxhcaSR4CNKKqF9zxxqa0EIFU0kfHgVGyTjvqG3BR5cO8WQGQcKmzCRpQLR8lShLBOIOsFDV@MlgskP0mzCjiSZ72MN4dEZZp8Opk69phITHRqg9K/Ixv88BCkTuOiUvejKc0fH0Ob2lATbEBhMnodZjMMQB0E20VDSj4szT0BAEMWmoToIqEsd8mQtwr94BNqeCbKNBEy3S/qdxVgqEkE0TJDw8QEJQmz5pstw92UJkDK6M0TUTJ1s5gX@ueRNLZMr3jUGDSGpn@QUCzPCKqpeEeDiUmVICwALKbag/4F "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-Q`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` üÈaY ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&header=bV8tMQ&code=/MhhWQ&input=WzUsIDYsIDgsIDMsIDksIDQsIDIsIDEsIDdd) * saved 1 by 0-indexing ``` ü - sort and group by: È - f(value,index) aY - distance(value,index) ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~13~~ 11 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Saved 2 bytes thanks to Razetime ``` {𝕩⊔˜|𝕩-↕≠𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniipTLnHzwnZWpLeKGleKJoPCdlal9CgpGIDXigL824oC/OOKAvzPigL854oC/NOKAvzLigL8x4oC/Nw==) Outputs with empty lists (the first group is at the back though) The best train I could get was `⊢⊔˜(|⊢-↕∘≠)` (also ~~13~~ 11 bytes). Razetime found two even smaller trains: [`⊢⊔˜·|⊒˜⊸-`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqi4oqUy5zCt3ziipLLnOKKuC0KCkYgNeKAvzbigL844oC/M+KAvznigL804oC/MuKAvzHigL83) and [`(|⊒˜⊸-)⊸⊔`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKHziipLLnOKKuC0p4oq44oqUCgpGIDXigL824oC/OOKAvzPigL854oC/NOKAvzLigL8x4oC/Nw==), both 9 bytes! ``` {𝕩⊔˜|𝕩-↕≠𝕩} ⊔˜ # Group the elements of 𝕩 # the input by |𝕩-↕≠𝕩 # the displacements ↕≠𝕩 # Indices of the input: range (↕) to length (≠) 𝕩- # Distance from each element to its corresponding index | # Absolute value ``` [Answer] # JavaScript (ES6), 48 bytes The output includes empty lists. ``` a=>a.map((_,i)=>a.filter((v,j)=>(v+=~j)*v==i*i)) ``` [Try it online!](https://tio.run/##dZFBboMwEEX3PYWXduomMgETFs5FkFVZKVQgGqIkYpmrU8@3S2khLADbM4/3h9YN7na6Npf727n/qMbajM4c3fbLXTh/l42gRd109@rK@SBbv@bDq3m0YjMY02waIcZTf771XbXt@k9e81JJtpcssWxxCcF2O1aWykpWosa@/GumXclSyZR90pxQcwoC3dSSocDwpPQZY1ax6PYHGc4UPLRddO9p13@aROmZke0aJ0xCA5j/6sw4WeT4ypxedQi3FimHjq89AInmv5H0NBnM6BDxGFO@KqhBC1k9v4BpaqdR4wxiBYJCkdIG/IpoNoMWP8ZIN6WGZcSG8iLykvhDx28 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://python.org/) + [pandas](https://pandas.pydata.org/), 48 bytes ``` lambda s:s.groupby(abs(s-s.index-1)).apply(list) ``` Input `pd.Series[int]`, output `pd.Series[List[int]]`. Could be 46 bytes if we use 0-indexed. TIO didn't have pandas installed (although it installed NumPy). So no TIO link available. [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->a{r=0;a.group_by{|x|(x-r+=1)**8}.values} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6xusjWwDpRL70ov7QgPqmyuqaiRqNCt0jb1lBTS8uiVq8sMac0tbj2f4FCWnS0oY6xjlFs7H8A "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` kS≠€¹ ``` [Try it online!](https://tio.run/##yygtzv7/Pzv4UeeCR01rDu38//9/tKmOmY6FjrGOpY6JjpGOoY55LAA "Husk – Try It Online") ``` k # group each x in input by S≠ # difference between x and € # index of x in ¹ # input ``` [Answer] # [Haskell](https://www.haskell.org/), 83 bytes ``` g a=(\l->map(\k->[fst m|m<-zip a$map(\n->abs$1+n-a!!n)l,snd m==k])l)[0..length a-1] ``` [Try it online!](https://tio.run/##HchNDoIwEAbQq3wkLCBOifUHNbG9SOlijAgN7YRYVsa718S3fDPnZYyxlAlsmiEqm3hthkVZ98ob0jfd1Ses4Pr/oiw/cq13oriqpI2U5YlkzOLb2Lp918VRpm0GK@1L4iBmfQfZ6smdCT3hSjgSboQT4UDQhIsvPw "Haskell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~91~~ ~~86~~ 84 bytes ``` j;i;f(a,n)int*a;{for(i=n*n;i--;j||puts(""))abs(a[j=i%n]-j)-i/n||printf("%d ",a[j]);} ``` [Try it online!](https://tio.run/##XZLtboMgFIb/9ypOSJqAPaTzY5/M7UI6szitDWajS3HZstZbn0OwVeQHyHneF17Agu@KoutqIUVFc1RMqibIxbHaH6hMVaCE5FzUp9PnV6MpIYzlb5rmmzqVS5XxmnG5VoYejK@iZFkCQUMzJtrOlOAjl4oyOC7AtL7QbHUTbjJI4XiNcINwhxAj3CMkCBFCiHDbCk8eOXlohdEMxg7G1myWCGc8uZgj609GHliBdgKbC91@bojdkMwWfFXOoOXvdl9R62PrYRa4KcKERj6NfBr7NPZp4tOEDWHM8wDtE0lVbn9MnCsxfD5O7dq3ayZgtbK685OMV2EWcddheSamGNRAzeHneIwyxDARlN1nukffmo3MeBoKr3j5c/SyJAjy2XTkgZi@l7NR3C7mFuBPL4pMJObQCGpSOCvTeRt97aLt/orqPd/pjn//Aw "C (gcc) – Try It Online") *Saved 5 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!* *Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a pointer to an array of integers and its length (because pointers in C carry no length info). Outputs the \$0\$-indexed numbers (separated by spaces) in displacements groups on separate lines for each possible displacement (so there may be empty lines). [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` (\a->[[y|(j,y)<-a,abs(j-y)==i]|(i,_)<-a]).zip[0..] ``` [Try it online!](https://tio.run/##FchLDsIgFAXQrdyBA4gPYv2biBuhxDwbUSptiDjBdO2iDs7k3Dk/rjFWb9oqWlYna8skeiryqJj4kkWvijQmuEkEOv/XSf0OyS60dnXgMMIgPcP4wgz@Z@AEoZq5hN0QtoQ9YUU4ENaEJaEh7Fz9dD7yLVfVpfQF "Haskell – Try It Online") Uses 0-indexing [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` l=input() d=[[]for _ in l] n=1 for x in l:d[abs(x-n)]+=x,;n+=1 print d ``` [Try it online!](https://tio.run/##HclBCoMwFAXAfU7xlorPhbZVq@QkIZSWUAzIN9gI8fRp7XKYcMR5lTbnRXsJeyxK5bQx9r1ueMALFqtEN@p0@nt05vn6FKmW0lY6cZLq92HzEuFyNjeiIwbiQtyJK9ESDdHbLw "Python 2 – Try It Online") Full program. Output includes empty lists. -11 thanks to @loopywalt [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` f x=[[b|(a,b)<-zip[0..]x,abs(a-b)==y]|y<-x] ``` [Try it online!](https://tio.run/##BcFLCoAgFAXQrTRoYHCN/jXQlYiDJyRJJlENNNq7nbPRva/e52yLKJUyHyOYSvDXnaqpax1B5mbETSVl0l8SPOp8kAvyvFx4SqsWzJgwYkCPDi0anX8 "Haskell – Try It Online") *Zero indexing. Outputs with empty lists*. Nothing really clever here. I'm quite surprised that this is the shortest of *3* Haskell answers. ## Explanation We have a first list comprehension ``` f x=[...|y<-x] ``` From `x` it takes all the possible distances we are looking for. Since `x` is a permutation every number we want appears and it appears exactly once. Inside we have a second comprehension. ``` f x=[[...|(a,b)<-zip[0..]x,...]|y<-x] ``` Here we take an index and a value from `x`. Using `zip` to get the indexes. ``` f x=[[...|(a,b)<-zip[0..]x,abs(a-b)==y]|y<-x] ``` We filter only the ones such that their absolute difference is the desired distance. ``` f x=[[b|(a,b)<-zip[0..]x,abs(a-b)==y]|y<-x] ``` Then we return the value. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` IEθΦθ⁼κ↔⁻λμ ``` [Try it online!](https://tio.run/##JYvLCsJADEV/JcsIERxfVVxJ0V3BfeliLAUHYx/z8PfHOxhy4OaE27@s7yerOT@8GyPXNkRu7MyL0N1pHHxJtyVZDfwWuj7DpCkO3LgxBVahz@o/l5zb1pyEzEboKLQX2gohmzM4AEgDW058iqkAFqC3QwJV1@X1V38 "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Output includes empty lists. Lists are double-spaced from each other. Explanation: ``` θ Input array E Map over elements θ Input array Φ Filtered where λ Inner value μ Inner index ↔⁻ Absolute difference ⁼ Equal to κ Outer index I Cast to string Implicitly print ``` [Answer] # Python3, 96 bytes: ``` f=lambda x,i=1,d={}:f(x[1:],i+1,{**d,(j:=abs(x[0]-i)):d.get(j,[])+[x[0]]})if x else[*d.values()] ``` [Try it online!](https://tio.run/##XVTbbuIwEH3efoUfE@qtMonjSyS@JMpDELCbilIEbEVV9dvZeC526APIl5lzzswc5/R5/ft@bPzpfL/v14fxbbMd1U1Pa9Db9dd3ty9uPXSDnp5Bf61WW128dutxc5mPq@H3VJbd9uXP7lq86n4on/t4OnyX017d1O5w2fWr7cvHePi3uxTlcN@/n9Wo1UZNR9X3PWjVaFUPet5A/MfdgPu41MpohRc9BhmMiX/AUYBRc6z5uaX7edfiASCWFWhc1JzWRpIUT6IsJjoBnk9aTpnvXVxaUpR0OGSYAzxmS0a8skk8luH5CitxmdliLomd0QJKMHLbMG9AyaiAm@Nzve0CJYggUUyEhncUGhig/tFVh@RQIViQiszDtGxS4hnI5VlARfUyIgG1iFULlkPcmQ3ij5HT0iX4lGBTAzxx5Mk1SXBEsAgOsXiDzDUyAzsBMyjGx1P2Xm4tKQCTWCBNzyw7ZRNBIDpDJNy@hSJiphqdHCc8mScDkYYmK2kWcvIb8VwiEQJ5NuoBNn2VHhHhihd5Om1qM0kJicoLzqNzhQ1BwD54xuQBJFZyIU/C50a0pJa0sDA6FIeKCVqB84uWVDwvy11hBYE4LGHRg0Jk7lMgciMd4SE59kWVJprfGbW8FjXUJlLhWYRjyZQPpLPlJw7yRiEsVEIiZ1dULNstPEMfISDvsnzDdpO3ToH5WyK1sk8Qy6SnKhQhl4JIkX5h7ah06J5@nc7T8Vrsi7Esn@7/AQ) [Answer] # Scala 3, 64 bytes ``` l=>l.indices.map(d=>l.indices.filter(i=>(i+1-l(i)).abs==d)map l) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZXBjpswEIZvPeQpLJoDqCTCxBioRLSXHir11iOJKppAi8SSFNiqUtUn6SWX9in6IrtP0_HM2NC99JAA9vj_P4_H9s_f46nqqt3t8eXXqhPNa_GuHafybT8dRbEX7-svpfmZb2j49TA1m-zxriv23bbtz-2pHrf31dU_LxuatpvqwW-Lvd--kpvOb4NgW30ci-IcQLDoAtJ5evHHeJ6qsR5FITzPK2UodqGIj2KzF2Upj6Eo8fu4wmcoVCgk98amV2GI-ZMmSGIQhCorMTdAN7wm-CVRSXPQzryChNE3z8SYUDgBaRyXzrLQlvAIiEjNqyYcgkhRH3ozHIzhDkg7cJxCxlo4i5R9NQ4lUhDLEcC604zQNUde9DfQJIcUyUIktzgIy1NACpah4JzHx8t8pmgtI9TK7XTUs1XSjiNjnZTTbqQimqwRJJ0EpWIrlaIsmEnzc8L0gVmx6m6IdrPPyILXbOdwzXCN2tLMXKFxjMaSS4CNKCoz7Vxxc1oJQCpnIt3CKZcm7fRzclPkwblbAJGxnWFqO5ycXUqWIoTdDLJb0PDGyHiC5CepVg2O5FqP3M4hUTlXPq1M4nJMJLlzyqzSvyVr_XARpJ7LRc3Zd6ZUf7wM2ZyGhGAtCpNRs61NWwCJFcwWCYl4sTTnxADkZKFJiDYSynKWcvJWNh-8QinXRDRXhJz3F-U7tjCUJILImCFlYoKShJnwzpZ2b8rcQkrnzRURMXW6qBc6eSSVLdMrLjUGdaHzCWInyzWCasrtUWuSzzNBWAOwqGoAhfN4tbq7r9penOtG4EuxEnReb8dr106-d-i9YNtchro6fRbfoZf6xeiV67ZnyPXlAa4PDy4UDBDCHPvVMMCh3_ZWKRSgNF3M9YNXygf4gGsnWAwZ8J4AMed-ANjDoXw-8j-SS81Plwk0Gx9wbPN1aPup6_3Re_PtWp-m-izWYB1i7Br-PBP5gy6x242efwE) Includes empty lists. [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 18 bytes ``` cr<<<bgB(Uc aD)<eu ``` *0 indexed* # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 21 bytes ``` cr<<<bgB(Uc aD)<zp nN ``` *1 indexed* ## Explanation The main crux of this is `bgB` which groups a list into chunks using a conversion function. This function was inspired by [this answer](https://codegolf.stackexchange.com/a/240388/56656). The first thing we do in each answer is pair every element with it's index. For zero indexed that's `eu`, but for one indexed it's a little more expensive `zp nN`. Then we do the grouping. We use `bgB` and our conversion function is the absolute difference `aD`. Since we need to operate on a tuple we have to uncurry `aD` with `Uc`. Once we've made the groups we need to go remove the indexes, `cr` gets the second element of a tuple so we triple map `cr` to get the second element of every tuple. ## Reflection This feels very big for what it's doing. It's nice we have the `bgB` to work with, but it doesn't quite fit here. The issue is that `bgB` is a very local function but index is a non-local property. So we need to put the indexes in, and then take them out. Not to mention this adds the currying necessary. It's possible to imagine a version of `bgB` that doesn't have this issue, but it seems like it would be very specific to this problem. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 24 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⍵∘{⍺[⍸⍵=1+|⍺-⍳≢⍺]}¨⍳≢⍵} ``` Outputs with empty lists. [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu/VRx4zqR727oh/17gDybA21a4A83Ue9mx91LgKyYmsPrYBxttYCAA&f=NVDtEcUgCPv/pmAEU5GWhbr/CC@J9q5nMR8QfAMx4/q9OiMDrMBqRrK6YrEC8fJN2iJ2m4X@RB9iM5YVxds009RJtQ7W1pI5zhUYJNrmdAQDi5DnU1NUgt/OZwevRQZslVRfVMMRKamNtdgU7CmfTSo1emwWCe1CC7zl2A8gO7wvme2N06734Od0W2pgYQsrIXoBJfaQlird1EluRx3bgQ061bD7/rLqkaHd3CO91R8&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Idk how to convert this to tacit lol, I'm sure it's possible though. ``` {⍵∘{⍺[⍸⍵=1+|⍺-⍳≢⍺]}¨⍳≢⍵} { } ⍝ a dfn in which... ¨ ⍝ for each element in... ⍳≢⍵ ⍝ the range 1 to the length of the input... ⍵∘{⍺[⍸⍵=1+|⍺-⍳≢⍺]} ⍝ apply the following function, with original the input passed in as the left argument: { 1+|⍺-⍳≢⍺ } ⍝ calculate the distance between the original list and its indices + 1... ⍸⍵= ⍝ and keep the ones that are equal to the right argument (which is an element from the range we are looping over) ⍺[ ] ⍝ then index the input (left argument) with the filtered list of indices ``` [Answer] # Python/NumPy, 47 bytes (@tsh) ``` lambda a:[[*a[abs(a-sorted(a))==i]]for i in~-a] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVVLrtowFJ1VKt2EZy88BTUOjj9PYiVpBo4gaiQgKPAGTLqRTpCqdk_tamrfjx3egBDb955z7s_5-edyv32fzo9fw-7b7_fbsLF_vx79qd974d_a9tW3vr8WfnOd5tthX_j1ercbu26YZjGK8fxj4zt0-_fpyzBPJ3F-P13uYjxdgoPw8-zvq1W09qXog4No21aWYluKuivDQsYnrDpYx9dSqFLAQQtGCmziQ5KVBKtgqz4u8TysGtiQgKUZGl5qcmsiSbJHURocDQOHnYZcwrmJrxoVJR0GGIKBBW_2iEc6iYcwLB1BJCYza_BFsQHNgQTFp1vidSAZFFBybI63WaA4FsSKkVDRCk0dAdQfsmqAXFYA5jgi9VQtnZRYAjK5FrLCeAkRgRrAqhnLAG5gk_FHyOnVJPjkoFMCLHLkym2T4IigAVzG4BUw18AsqRPAA21s3KXey6lFBVIlFpmqp5aZ0onAIZ1CEkrfQhEyY4yGtxMe15OAUMM2K9ku5OQZsRQiEkrs2ahHUtNXaYgQl3uRqtOkNKMUl6gs4zx3LrMBiNRPPaNyARIrdiFVwuZENKgWtZAw3OQO5SZoGM4uUlJRvTRlhRQ45NCIhQMFyJQnh-SKM0JFMtQXVaponjNMec1qME2owpIIQ5LRX6LOhkZc8oxKt1ApEzl1RUWyzaJn8BKS2LskX1G78ayjYb5LOFbqE8BSaVSZwuVQACnSL1o7Ku3eVp_99XoIVzdd-O3rMB5vh7nop-lYDgXc6PEzsO7Cl4CM-vXqMo_nW_Fyid77lzV-Ex4P_P8P) #### Python/NumPy, 49 bytes ``` lambda a:[[*a[(a-sorted(a))**2==i*i]]for i in~-a] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVXLjtowFN1VKv0J74agIMXB8WMkviTNwgiiiQQEBWbBpj8yG6RR-0_t19S-DzvMghDb955z7sv5-HO5397G8-Oz3_78_X7r1_avPPrTbu-Ff23blW-Xfn0dp9thv_RFsVrV2-2wGrquHycxiOH8a-07dPz37Uc_jSdxfj9d7mI4XYKX8NPk74tFtPal2AUH0batLMWmFHVXhoWMT1h1sI6vpVClgIMWjBTYxIckKwlWwVZ9XeJ5WDWwIQFLMzS81OTWRJJkj6I0OBoGDjsNuYRzE181Kko6DDAEAwve7BGPdBIPYVg6gkhMZtbgi2IDmgMJik83xOtAMiig5NgcbzNDcSyIFSOhohWaOgKov2TVALmsAMxxROqpWjopsQRkci1khfESIgI1gFUzlgHcwCbjj5DTq0nwyUGnBFjkyJXbJMERQQO4jMErYK6BWVIngAfa2LhLvZdTiwqkSiwyVU_NM6UTgUM6hSSUvpkiZMYYDW8nPK4nAaGGTVaymcnJM2IpRCSU2LNRj6Smr9IQIS73IlWnSWlGKS5RWcZ57lxmAxCpn3pG5QIkVuxCqoTNiWhQLWohYbjJHcpN0DCcnaWkonppygopcMihEQsHCpApTw7JFWeEimSoL6pU0TxnmPKa1WCaUIUlEYYko79EnQ2NuOQZlW6mUiZy6oqKZJtZz-AlJLF3Sb6iduNZR8N8l3Cs1CeApdKoMoXLoQBSpJ-1dlTavS6---v1EK5uuvXbVT8cb4dpuRvHY9kv4UaP34KiK7ZbMtoVi8s0nG_Ll0v03r8U-E14PPD_Pw) Avoiding explicit numpy import saves 15. #### Python/NumPy, 64 bytes ``` lambda a:[[*a[abs(a-sort(a))==i]]for i in~-a] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVVLrtowFB11UFbh2QsoSHFw_HkSUveRZmAEUSMBQSFvwKQb6QSpavfULqMrqH0_dt4bALF97znn3nscfvy-PeZv4_X5s99__fU291v758vZXw5HL_xr22586w_3wm_v4zQXfr3e74eu68dJDGK4ft_6btVP40Vc3y63hxgutxC2QZy_n_7FOF-KQwgVbdvKUuxKUXdlWMj4DasO1vGxFKoUcNBCkIKY-CUpSkJUiFUfl3geVg1sSMDSDA0PNaU1kSTFoygNiYaBw05DKeHcxEeNipIOAwwhwEI2Z8QjncRDGZaOoBKTmTXkotiA5kCC4tMd8TqQDAqoOTbX2yxQHAtixUioaIWhjgDqD101QC4rAHNckXo3LZ2UWAIyeRaywnoJEYEawKoZywBuYJPxQ8jp0ST4lKBTAyxy5MntkuCIoAFcxuIVMNfALMkJkIExNu6S93JrUYFUiUWm6allp3QicEinkITat1CEzFij4e2Ex_MkINSwy0p2Czn5jlgqEQklejbqkWT6Kl0ixGUv0nSa1GaU4hKVZZz3zmU2AJH6nWdUHkBiRRfSJGxuRINqUQsJw012KJugYTi7aElF89LUFVLgkEMjFl4oQKY-OSRX3BEakiFfVGmi-Z5hy2tWg21CFZZEGJKM-RJ1NnTFJd9R6RYqZSInV1Qk2yw8gy8hid4l-YrsxncdA_O7hGslnwCWSleVKVwuBZAi_cLaUWn3uvrs7_fTNIv4oj8di3bTD-f5NBWHcTyXfeGnyT_iH8C6C_8BFHRYr27TcJ2Ll1vMPr6s8dX_fOLvfw) This version exploits that OP doesn't care for order. #### Python/NumPy, 71 bytes ``` lambda a:[[*a[abs(a-sort(a))==i]]for i in sort(a)-1] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVU7jtswEK1SxKdgt7YhAxqZ4mcB1zmEooLGrrACbMuQtYXPksZAkNwpKXOSiPMhtVvYFsmZ997MPMo_fl_v09twefzsDt9_vU_dzv35dgrn40tQ4blptqEJx9s67G7DOK3DZnM49G3bDaPqVX9RvLuDdtWNw1ld3s_Xu-rP13l_S3B_v_yL4aFQx5jRNA0Ual-oqi3mBcRvXLW4jo-F0oXCgwaDNMbEL-AowKg5Vn9e0vm8qnEDEMsIND5UnFZHkhRPogwmWgGed2pOmc9tfDSkKOmwyDAHOMyWjHhkkngsw_ERVmIzs8FcEjujeZSg5XTPvB4lowJujsv11gsUL4JEMRFqXlGoZ4DqU1ctkkOJYF4q0h-mZZISx0A2zwJKqpcRCahGrEqwLOLObBA_jJwebYJPCSY1wBFHntw-CY4IBsEhFq-RuUJmYCdgBsW4uMvey60lBaATC6Tp6WWnTCLwRKeJhNu3UETMVKOV7YQn82Qg0rDPSvYLOfmOOC6RCIE8G_UAm75Ml4hwxYs8nTq1maT4ROUE56NzhQ1BwHzwjM4DSKzkQp6Ey42oSS1pYWG0KQ4VE9QC5xYtKXlehrvCCjxxGMKiC4XI3CdP5Fo6wkOy7IsyTTTfM2p5JWqoTaTCsQjLkikfSGfNVxzkjoJfqIREzq4oWbZdeIZeQkDeZfma7SZ3nQLzu0RqZZ8glk5XVSh8LgWRIv3C2lFp-7z6Gm6313FSzbbrT9PruD4Ow6no1mEcwz3-AWzaw-G4uo79ZVo_XWP0y9OGXvWPB_3-Bw) Expects a numpy array but outputs a plain list of lists instead of a list of arrays which would be 3 bytes shorter but looks rather ugly. [Answer] # [Arturo](https://arturo-lang.io), 34 bytes ``` $=>[0gather&=>[abs&-dup+1]|values] ``` [Try it](http://arturo-lang.io/playground?rtSwmo) ]
[Question] [ I define the n-th ternary as a ternary that returns n and has the form: ``` 1 ? 2 ? 3 ? n - 1 ? n : 0 : 0 : 0 # n - 1 zeroes ``` Write a function or complete program that given an input n will output or return the n-th ternary. Code-Golf. **Testcases** ``` 0 #=> undefined behaviour 1 #=> 1 2 #=> 1 ? 2 : 0 3 #=> 1 ? 2 ? 3 : 0 : 0 10 #=> 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? 10 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 ``` [The 1000-th ternary](http://pastebin.com/0hh0ZE8g) I think there is some kind of zen harmony to it. [Answer] # CJam, 18 18 bytes ``` ri,:)":?0"*2/ze_S* ``` [Try it online](http://cjam.aditsu.net/#code=ri%2C%3A%29%22%3A%3F0%22*2%2Fze_S*&input=10). ### Explanation ``` ri,:) e# Generate the list 1..n. ":?0"* e# Insert ":?0" between every two numbers. 2/ e# Split into pairs, e.g. 1:, ?0, 2:, ?0, ..., ?0, n. z e# First items in every pair before second items in every pair. e_ e# Concatenate the two parts. S* e# Insert spaces. ``` [Answer] # Pyth - 19 18 17 bytes The spaces are killing me, thinking of a better way to handle them. ``` +j" ? "SQ*tQ" : 0 ``` It just joins the numbers by a `" ? "` and then concatenates the second part on. ``` + String concatenation j" ? " Join by the string SQ 1-indexed inclusive range to input * String repetition tQ Input - 1 " : 0 String implicitly closed by end of program ``` [Try it online here](http://pyth.herokuapp.com/?code=%2Bj%22+%3F+%22SQ*tQ%22+%3A+0&input=10&debug=1). [Answer] # Ruby, 31 bytes ``` f=->n{[*1..n]*' ? '+' : 0'*~-n} ``` Test: ``` > f[1] => "1" > f[7] => "1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 : 0 : 0 : 0 : 0 : 0 : 0" ``` [Answer] # CJam, 19 bytes Just a start... ``` ri_,:)'?*\(":0"*+S* ``` **How it works** ``` ri_ e# Read the number as integer and make a copy of it on stack ,:) e# Convert the copy to array [1 .. n] '?* e# Join the numbers with a '?'. So we have [1 '? 2 '? ... '? n] \( e# Swap the stack to get original integer on top. Decrement it by 1 ":0"* e# Get n-1 repeated ":0" string +S* e# Join the two strings and fill it with spaces. ``` [Try it online here](http://cjam.aditsu.net/#code=ri_%2C%3A)'%3F*%5C(%22%3A0%22*%2BS*&input=5) [Answer] # Brainfuck, 305 (Without input number from STDIN, see edit at the bottom) ``` -[->+>+<<]>>>++++[>++++++++<-]>[<+>-]+++++++[>+++++++++<-]>[<+>-]++++++[>++++++++ <-]>[<+>-]++<<<<>>>+.-<<<[>.>.<.>>>>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<< ]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<< +>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<+<<< <-]>>-----<<<[->>.>.<.>>.<<<<] ``` I used [this](http://esolangs.org/wiki/brainfuck_algorithms#Print_value_of_cell_x_as_number_for_ANY_sized_cell_.28ie_8bit.2C_16bit.2C_etc.29) lovely algorithm to print a number, which takes up 155 bytes of the whole program. It works for inputs up to 32768 (16-bit limitation of the algorithm). It doesn't produce trailing spaces and works for input `1` as well: ``` input output 0 [infinite loop (til underflow)] 1 "1" 2 "1 ? 2 : 0" 4 "1 ? 2 ? 3 ? 4 : 0 : 0 : 0" etc. ``` ## Quick walk-through: ### Setup (97 bytes) ``` - Decrease input (position 0) [->+>+<<] >>> Copy input twice to the right and shift 3 positions to the right ++++[>++++++++<-]> [<+>-] Precalculate number 32 (=" ") at position 3 +++++++[>+++++++++<-]> [<+>-] Precalculate number 63 (="?") at position 4 ++++++[>++++++++<-]> [<+>-] Precalculate number 48 (="0") at position 5 ++<<<< Precalculate number 2 for later use. This number will be printed in each iteration. (position 6) ``` ### First part (181 bytes) ``` >>>+.-<<< Go to the char "0" we saved, increase it, print it, decrease it and go back (this prints "1" everytime) [ While our second copy of the number isn't zero >.>.<.>>> Move to " ", print, move to "?", print, move to " " again, print, move to our number at the end which is initially 2 [>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-] ++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]< [.[-]<]< Algorithm to print the number at current position +<<<< Increase our number at the end and return to the beginning -] Decrease the loop variable ``` ### Second part (27 bytes) ``` >>-----<<< Move to our "?" char and decrease it by 5 to get ":" [- While our first copy of the number isn't zero decrease it >>.>.<.>>.<<<< Print " ", print ":", print " ", print "0" ] ``` If it would be allowed to map the 8 Brainfuck commands to 3 bits, then this program would take up **114** bytes and another 3 bits # Unary, ~4.08\*10^275 bytes It would be too long for here, but it's just 408452257862560239329948606295286361112603208650130608525040044700379331457759667646985586658469601803889628246410788572492437928714867190270708935427798983714797786123292750743771225096145575210320040188155473030775033228313350778616384531426430459309802833775612506568528463 zeros and works the same as the Brainfuck program. **EDIT**: I messed up, this program doesn't take user input really, it just uses the current pointer value as input. For being able to parse a number a whole lot more would be required and I can't be bothered to do that. So it works with a value directly entered into the program (by appending n times "+" before the program) but not with STDIN [Answer] # JavaScript (ES6), ~~42~~ 39 bytes ``` f=m=>(g=k=>k-m?k+` ? ${g(k+1)} : 0`:m)(1) ``` The outer function `f` takes the input value and then calls the inner function `g` recursively to build the string from the middle out, using the input value as a maximum to test for the base case. Ungolfed: ``` function f(max) { function g(count) { if(count==max) { // base case: return max for the center return max; } else { // recursive case: build outer shell around center return count + " ? " + g(count+1) + " : 0"; } } return g(1); } ``` [Answer] # Python 56 55 ``` t=lambda n:' ? '.join(map(str,range(1,n+1)))+' : 0'*~-n ``` [Answer] # C# - 76 ``` Func<int,string>F=k=>{var r="";for(;k>1;)r=" ? "+k--+r+" : 0";return"1"+r;}; ``` [Answer] # Haskell, 53 bytes ``` g n='1':foldr(\x s->" ? "++show x++s++" : 0")""[2..n] ``` How it works: build the string from inside out by starting with an empty string and looping from `n` down to `2` with prepending the current number and a `?` and appending a `: 0`. Finally put a `1` in front of all. A different approach (thanks to @Mauris now 9 bytes shorter): # Haskell, ~~60~~ 51 bytes ``` f n='1':((=<<[2..n])=<<[(" ? "++).show,\x->" : 0"]) ``` How it works: a literal `1` followed by `? <x>` for each `<x>` in `[2..n]` followed by a constant `: 0` for each `<x>` in `[2..n]`. [Answer] # Pyth, 17 bytes ``` jd.iSQs*RtQ,\?":0 ``` [Demonstration.](https://pyth.herokuapp.com/?code=jd.iSQs*RtQ%2C%5C%3F%22%3A0&input=10&debug=0) [Answer] # Julia, ~~44~~ 31 bytes ``` n->join(1:n," ? ")*" : 0"^(n-1) ``` This creates an unnamed function that accepts an integer as input and returns a string. To call it, give it a name, e.g. `f=n->...`. First we join together the integers 1 to *n*, separating each with `?` and spaces into a single string. Then we append to this the string `" : 0"` repeated *n*-1 times. Examples: ``` julia> f(1) "1" julia> f(3) "1 ? 2 ? 3 : 0 : 0" julia> f(0) can't repeat a string -1 times ``` [Answer] # Perl, 36 bytes ``` say join(" ? ",1..$_)." : 0"x($_-1) ``` `35` characters `+1` for `-n`. Run with: ``` echo 10 | perl -nE'say join(" ? ",1..$_)." : 0"x($_-1)' ``` [Answer] # JavaScript ES7, 62 bytes ``` n=>[for(i of Array(n).keys())i+1].join` ? `+' : 0'.repeat(n-1) ``` I don't know if I can golf this more. But it's a pretty straightforward solution Firefox only: ``` var f=n=>[for(i of Array(n).keys())i+1].join` ? `+' : 0'.repeat(n-1) alert(f(+prompt('Input: '))); ``` ES5 equivalent: ``` // Most browsers now support .repeat String.prototype.repeat = String.prototype.repeat || function(n){var _n = '', i = 0; for (;i < n; i += 1){_n+=this};return _n} //Function function f(n){a=[];for(i of Array(n).keys()){a.push(i+1)};return a.join(' ? ')+' : 0'.repeat(n-1)} alert(f(+prompt('Input: '))) ``` [Answer] ## CoffeeScript, 52 bytes ``` f=(n)->s='';s=' ? '+n--+s+' : 0'while n;s.slice 3,-4 ``` ### Explanation ``` f=(n)-> s = '' # initialize string s = ' ? ' + n-- + s + ' : 0' while n # prepend and append in decrementing loop s.slice 3,-4 # chop off leading ?, trailing 0 and whitespace ``` [Answer] # SWI-Prolog, 90 bytes ``` a(X):-Y is X-1,\+ (between(1,Y,L),\+writef('%w ? ',[L])),write(X),writef('%r',[' : 0',Y]). ``` Definitely not going to win, but the `\+ (between(1,TopBound,N),\+do_something(N))` construction is pretty interesting to repeat something on a sequence of integers. [Answer] # Swift 145 (135 w/o whitespace) ``` func t(n:Int) -> String { let a = (1..<n).reverse().reduce("") {" ? \($1)\($0) : 0"} return a.substringFromIndex(advance(a.startIndex, 3)) } ``` Can you believe the part to substring is actually longer than the part to produce the expression. [Answer] # Java, 71 I couldn't help myself after commenting on [RCB's answer](https://codegolf.stackexchange.com/questions/52867/the-n-th-ternary/53037#53037). So here's another Java (71 like wow when is Java not the longest!) ``` String t(int n){String s=""+n;for(;--n>0;)s=n+" ? "+s+" : 0";return s;} ``` [Answer] ## Java, ~~125~~ 88 bytes **Original** ``` String f(int n){if(n==1)return"1";String s="",e="";for(int i=1;i<n;i++){s+=i+" ? ";e+=i==n-1?": 0":": 0 ";}return s+n+" "+e;} ``` With nicer formatting and variable names: ``` String nAry(int n) { if (n == 1) { return "1"; } String start = "", end = ""; for (int i = 1; i < n; i++) { start += i + " ? "; end += (i == n - 1) ? ": 0" : ": 0 "; } return start + n + " " + end; } ``` **Improved -** Thanks to Jack Ammo's comments below: ``` String f(int n){String s="",e=s;for(int i=1;i<n;){s+=i+++" ? ";e+=" : 0";}return s+n+e;} ``` [Answer] ## JavaScript (ES6), 59 bytes Same approach as my CoffeeScript answer, using template strings help. [`String.prototype.repeat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat) costs too many characters. ``` f=n=>{for(s=``;n;)s=` ? ${n--+s} : 0`;return s.slice(3,-4)} ``` ### Demo Firefox only for now, as it is ES6. ``` f=n=>{for(s=``;n;)s=` ? ${n--+s} : 0`;return s.slice(3,-4)} // DEMO console.log = x => document.body.innerHTML += '<p>' + x console.log(f(1)); console.log(f(3)); console.log(f(10)); ``` [Answer] # K, 36 bytes ``` {(3_,/(" ? ",)'$!x),(4*-1+x)#" : 0"} ``` [Answer] # Python 2, ~~63~~ ~~60~~ ~~58~~ 56 [**Try it here**](http://ideone.com/0TlIpQ) Easy solution: (63) ``` n=input() for i in range(n-1):print-~i,'?', print`n`+' : 0'*~-n ``` **Edit**: I really wanted to try a recursive function. Here it is: (56) ``` f=lambda n,c=1:`c`+(' ? '+f(n,c+1)if c<n else~-n*' : 0') ``` **Edit**: Anyone know why this isn't working? I tried a list with an index of `c<n`, but that didn't work because of a stack overflow error. Same with this: ``` f=lambda n,c=1:`c`+((c<n)*(' ? '+f(n,c+1))or~-n*' : 0') ``` [Answer] # [rs](https://github.com/kirbyfan64/rs), 77 bytes ``` (\d+)/(_)^^(\1) +^_(_+)/\1 _\1 _(_+)$/_\1( : 0)^^((^^\1)) (__+)/? (^^\1) ^./1 ``` [Live demo and test cases.](http://kirbyfan64.github.io/rs/index.html?script=(%5Cd%2B)%2F(_)%5E%5E(%5C1)%0A%2B%5E_(_%2B)%2F%5C1%20_%5C1%0A_(_%2B)%24%2F_%5C1(%20%3A%200)%5E%5E((%5E%5E%5C1))%0A(__%2B)%2F%3F%20(%5E%5E%5C1)%0A%5E.%2F1&input=0%0A1%0A2%0A3%0A10) ## Explanation: ``` (\d+)/(_)^^(\1) ``` Expand the number into a series of N underscores. ``` +^_(_+)/\1 _\1 ``` Repeatedly create a range of underscores, separated by spaces. e.g. This would turn `___` into `_ __ ___`. ``` _(_+)$/_\1( : 0)^^((^^\1)) ``` Append to the last set of underscores (of length N) N-1 instances of `: 0`. ``` (__+)/? (^^\1) ``` Replace each group of underscores by it's length, preceded by `?`, EXCEPT for the first one. ``` ^./1 ``` Replace the first one with the number 1. Because of the format, this also handles `0` well: it just prints the empty string. [Answer] # Swift, 79 75 bytes ``` let f={{$0+$1}((1..<$0).reduce(("1","")){($0.0+" ? \($1+1)",$0.1+" : 0")})} ``` `f` is implicitly declared as a function with one `Int` parameter which returns a `String` Works with `n >= 1` and crashes at runtime when `n == 0`. There are no trailing whitespaces Edit: Managed to remove 2\*2 characters, because string interpolation isn't always the shortest Note to edit: This code takes forever (it doesn't stop) to compile, but it definitely would if the compiler would be able to handle it. Take a look at the version before this edit to get one that compiles [Answer] # [><>](http://esolangs.org/wiki/Fish), 32 + 3 = 35 bytes ``` :l(?vln" ? "ooo0$ "ooo>nl?!;" : ``` Note that there is a trailing space on the second line. The +3 is for the `-v` flag, e.g. run like ``` $ py -3 fish.py ternary.py -v 2 1 ? 2 : 0 ``` Taking input [as a code point](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values) like ``` i:l(?vln" ? "ooo0$! "ooo>nl?!;" : ``` is 34 bytes, but I prefer the above version since it's easier to test and it won't win anyway. ## Explanation There's quite a bit of pseudo-recursion and abuse going on, so let's take a look. The first line prints the `"1 ? 2 ? ... n-1 ? "` part. The stack starts off with just the input `n`, thanks to the `-v` flag, and we do the following: ``` :l(?v If (length of stack + 1 > n), go to the second line ln Print the length of the stack " ? "ooo Print the reverse of " ? " (but hey, palindromes) 0$ Push 0 and swap, keeping n on top and increasing the length of the stack by 1 ``` ><> is toroidal, so the above executes in a loop until the stack consists of `n` at the top with `n-1` zeroes below, at which point it moves to the second line. The first time the second line is executed, the `n` instruction is run, printing the `n` at the top of the stack. This leaves just the `n-1` zeroes, and we do the following, also in a loop: ``` l?!; If the stack is empty, terminate " : "ooo Print the reverse of " : " (but hey, palin...) n Print one of the 0s, decreasing the stack's length by 1 This reuses the same n instruction from before ``` [Answer] ## Scala, ~~78~~ ~~71~~ ~~52~~ 50 bytes ``` def f(n:Int)=(1 to n).mkString(" ? ")+" : 0"*(n-1) ``` [Answer] # Objective-C, 346 bytes ``` -(void)printTernaryOfInt:(int)ternary{NSMutableString *outString=@"".mutableCopy; for (int i=1;i<=ternary;i++) {[outString appendString:[NSString stringWithFormat:@" ? %i",i]];}[outString deleteCharactersInRange:NSMakeRange(0, 2)];for (int i=1;i<ternary;i++) {[outString appendString:[NSString stringWithFormat:@" : 0"]];}NSLog(@"%@",outString);} ``` Putting in `0` for the `int` or anything negative raises an `NSRangeException` due to `outString` containing `nil`. This should run on iOS 2.0 and later and many of the latest versions of Mac OS X. ### A breakdown of the code: ``` -(void)printTernaryOfInt:(int)ternary{ ... } ``` Standard function declaration in Objective-C. ``` NSMutableString *outString=@"".mutableCopy; ``` Makes a string for output to go to, `outString`, and makes it mutable. (In other words, it can be read and written to. ``` for (int i=1;i<=ternary;i++) {[outString appendString:[NSString stringWithFormat:@" ? %i",i]];} ``` Adds the first part of the string to output. ``` [outString deleteCharactersInRange:NSMakeRange(0, 2)]; ``` Cleans up the beginning of the string to make sure `? 1` is replaced with `1`. Note: if `0` was given, this is where the `NSRangeException` would occur, due to there not being an index `1`. ``` for (int i=1;i<ternary;i++) {[outString appendString:[NSString stringWithFormat:@" : 0"]];} ``` Adds the second part of the string to the string. ``` NSLog(@"%@",outString);} ``` Spits the string back out using `NSLog` and closes off the function. ### Output: Inputting `0` gives this crash log: ``` 2015-07-11 05:15:28.036 Example App[41665:2134488] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString deleteCharactersInRange:]: Range or index out of bounds' *** First throw call stack: ( 0 CoreFoundation 0x009b5746 __exceptionPreprocess + 182 1 libobjc.A.dylib 0x0063ea97 objc_exception_throw + 44 2 CoreFoundation 0x009b566d +[NSException raise:format:] + 141 3 CoreFoundation 0x00981813 mutateError + 259 4 CoreFoundation 0x009818c1 -[__NSCFString deleteCharactersInRange:] + 65 5 Example App 0x000e3785 -[ViewController printTernaryOfInt:] + 277 6 Example App 0x000e3645 -[ViewController placeOrder:] + 133 7 libobjc.A.dylib 0x006547cd -[NSObject performSelector:withObject:withObject:] + 84 8 UIKit 0x00d75a40 -[UIApplication sendAction:to:from:forEvent:] + 99 9 UIKit 0x00d759d2 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 64 10 UIKit 0x00eb613a -[UIControl sendAction:to:forEvent:] + 69 11 UIKit 0x00eb6557 -[UIControl _sendActionsForEvents:withEvent:] + 598 12 UIKit 0x00eb57c1 -[UIControl touchesEnded:withEvent:] + 660 13 UIKit 0x00dcdcaa -[UIWindow _sendTouchesForEvent:] + 874 14 UIKit 0x00dce786 -[UIWindow sendEvent:] + 792 15 UIKit 0x00d8c681 -[UIApplication sendEvent:] + 242 16 UIKit 0x00d9cab8 _UIApplicationHandleEventFromQueueEvent + 21484 17 UIKit 0x00d702e7 _UIApplicationHandleEventQueue + 2300 18 CoreFoundation 0x008d706f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15 19 CoreFoundation 0x008ccb7d __CFRunLoopDoSources0 + 253 20 CoreFoundation 0x008cc0d8 __CFRunLoopRun + 952 21 CoreFoundation 0x008cba5b CFRunLoopRunSpecific + 443 22 CoreFoundation 0x008cb88b CFRunLoopRunInMode + 123 23 GraphicsServices 0x029e42c9 GSEventRunModal + 192 24 GraphicsServices 0x029e4106 GSEventRun + 104 25 UIKit 0x00d740b6 UIApplicationMain + 1526 26 Example App 0x000e3cfa main + 138 27 libdyld.dylib 0x02d76ac9 start + 1 28 ??? 0x00000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException ``` `1` gives this: ``` 2015-07-11 05:06:02.360 Example App[41665:2134488] 1 ``` `2` gives this: ``` 2015-07-11 05:06:07.613 Example App[41665:2134488] 1 ? 2 : 0 ``` `7` gives this: ``` 2015-07-11 05:06:12.147 Example App[41665:2134488] 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 : 0 : 0 : 0 : 0 : 0 : 0 ``` `200` gives this: ``` 2015-07-11 05:06:35.552 Example App[41665:2134488] 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? 10 ? 11 ? 12 ? 13 ? 14 ? 15 ? 16 ? 17 ? 18 ? 19 ? 20 ? 21 ? 22 ? 23 ? 24 ? 25 ? 26 ? 27 ? 28 ? 29 ? 30 ? 31 ? 32 ? 33 ? 34 ? 35 ? 36 ? 37 ? 38 ? 39 ? 40 ? 41 ? 42 ? 43 ? 44 ? 45 ? 46 ? 47 ? 48 ? 49 ? 50 ? 51 ? 52 ? 53 ? 54 ? 55 ? 56 ? 57 ? 58 ? 59 ? 60 ? 61 ? 62 ? 63 ? 64 ? 65 ? 66 ? 67 ? 68 ? 69 ? 70 ? 71 ? 72 ? 73 ? 74 ? 75 ? 76 ? 77 ? 78 ? 79 ? 80 ? 81 ? 82 ? 83 ? 84 ? 85 ? 86 ? 87 ? 88 ? 89 ? 90 ? 91 ? 92 ? 93 ? 94 ? 95 ? 96 ? 97 ? 98 ? 99 ? 100 ? 101 ? 102 ? 103 ? 104 ? 105 ? 106 ? 107 ? 108 ? 109 ? 110 ? 111 ? 112 ? 113 ? 114 ? 115 ? 116 ? 117 ? 118 ? 119 ? 120 ? 121 ? 122 ? 123 ? 124 ? 125 ? 126 ? 127 ? 128 ? 129 ? 130 ? 131 ? 132 ? 133 ? 134 ? 135 ? 136 ? 137 ? 138 ? 139 ? 140 ? 141 ? 142 ? 143 ? 144 ? 145 ? 146 ? 147 ? 148 ? 149 ? 150 ? 151 ? 152 ? 153 ? 154 ? 155 ? 156 ? 157 ? 158 ? 159 ? 160 ? 161 ? 162 ? 163 ? 164 ? 165 ? 166 ? 167 ? 168 ? 169 ? 170 ? 171 ? 172 ? 173 ? 174 ? 175 ? 176 ? 177 ? 178 ? 179 ? 180 ? 181 ? 182 ? 183 ? 184 ? 185 ? 186 ? 187 ? 188 ? 189 ? 190 ? 191 ? 192 ? 193 ? 194 ? 195 ? 196 ? 197 ? 198 ? 199 ? 200 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 : 0 ``` [Answer] # C, ~~84~~ 78 bytes C, even though it is not the shortest, as a function: ``` i;f(n){while(++i<n)printf("%i ? ",i);printf("%i",n);while(--i)printf(" : 0");} ``` In the name of golfing, the `int` type specifier is left off of `i`, `f`, and `n` because it is the default. `i` can be uninitialized because it is a global variable and defaults to zero. `f` does not return a value, but that only causes a warning. `printf` is not `#include`'d. To run, here is a full program version: ``` #include <stdio.h> i;f(n){while(++i<n)printf("%i ? ",i);printf("%i",n);while(--i)printf(" : 0");} int main(int argc, char *argv[]){ if(argc != 2){ return 1; } f(atoi(argv[1])); puts(""); } ``` [Answer] # C, 63 bytes Reusable function, takes n as an argument. ``` i;f(n){for(i=1;i<2*n;i++)printf(i-1?n/i?" ? %d":" : 0":"1",i);} ``` Ungolfed and commented (pretty straightforward): ``` int f(int n) { int i; // 1 ... n, n+1 ... 2n-1 for(i = 1; i < 2*n; i++) { // If i == 1, prints "1" // If i <= n, prints " ? %d", i (i = 2 ... n) // Else, prints " : 0" (i = n+1 ... 2n-1) printf( i-1 ? n/i ? " ? %d" : " : 0" : "1", i); } } ``` [Answer] # Common Lisp, 84 ``` (format t "~{~A ? ~}~@*~{~[~;~:;0~^ ? ~]~}" (loop for i from 1 to (read) collect i)) ``` First, `(loop for i from 1 to (read) collect i)` generates a list of integers from 1 to whatever is put in, which is used as the only argument to the function. But the real magic of it is in the control string that looks like line noise. `"~{~A ? ~}"` iterates over the entire list stored within the first argument, outputting each number with the `?` for the first half. `~@*` resets the argument list to the first argument. `~{~[~;~:;0~^ ? ~]~}` reiterates over the list, outputting `0 ?` for each argument consumed, but outputting nothing if the argument is 0 or 1. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~52~~ 38 bytes ``` param($a)(1..$a-join' ? ')+' : 0'*--$a ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9vyCxKDFXQyVRU8NQT08lUTcrPzNPXcFeQV1TW13BSsFAXUtXVyXxfy2XmkqagiGYNAKTxmDSDCJuwPX/PwA "PowerShell Core – Try It Online") Save 14 bytes thanks to *mazzy*! ]
[Question] [ A doubling sequence is an array of numbers where each subsequent number is at least twice the previous number. Given an ordered list of numbers, determine if the numbers in the list (\$n\_{x}\$) have the property that: \$n\_1 \times 2 \le n\_2\$ \$n\_2 \times 2 \le n\_3\ ...\$ and so on until reaching the end of the list. # Input A list of two or more numbers. # Output Any distinct True or False value. # Examples: ``` [10,20,30] -> False [10,20,40] -> True [1,2,3] -> False [1,2,4] -> True [1,2,10] -> True [1,1] -> False [10,1] -> False ``` [Answer] # [R](https://www.r-project.org/), ~~27~~ 26 bytes ``` all(diff(log2(scan()))>=1) ``` [Try it online!](https://tio.run/##K/r/PzEnRyMlMy1NIyc/3UijODkxT0NTU9PO1lDzv6GCkYKhwX8A "R – Try It Online") 1 byte saved by Giuseppe. [Answer] # Jelly, 4 (5?) bytes Monadic link taking the list as input. ``` I<ṖẸ ``` If I am allowed to output 0 for Truthy and 1 for Falsy... Otherwise, ``` I<ṖẸ¬ ``` You can [try all test cases](https://tio.run/##y0rNyan8/9/T5uHOaQ937Ti05v/h9kdNa/7/j442NNAxMtAxNojV4YKyTSBsHSMdYxjDBMYwhMoZQpUbxsYCAA)! Notice that \$x\_{i+1} \geq 2x\_i \iff x\_{i+1} - x\_i \geq x\_i\$. ``` < Compare I the forward differences Ṗ with the original list without the last item. Ẹ Check if any comparison returned true ¬ and negate that ``` # Jelly, 6 bytes We can instead take pairwise quotients and check directly if they satisfy the inequality with this monadic link: ``` ÷Ɲ>.Ẹ¬ ``` You can [verify all test cases](https://tio.run/##y0rNyan8///w9mNz7fQe7tpxaM3/w@2Pmtb8/x8dbWigY2SgY2wQq8MFZZtA2DpGOsYwhgmMYQiVM4QqN4yNBQA)! ``` ÷Ɲ Compute the quotient for all pairs of elements in the input list. >. See if the elements are greater than 0.5 Ẹ and take the "OR" of that list, ¬ finishing off with the negation of that. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ä÷ e§½ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=5PcgZae9&input=WzEsMiwxMF0) ``` ä÷ e§½ :Implicit input of array ä :Consecutive pairs ÷ : Reduced by division e :All §½ : Less than or equal to 0.5 ``` [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` f(x:s)=any(<2)$zipWith(/)s$x:s ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02jwqpY0zYxr1LDxkhTpSqzIDyzJENDX7NYBSjxPzcxM0/BVqGgKDOvREFFITexQCFNITra0EDHyEDH2CBWB8o0ATN1jHSMobQJlDaESBhCVBrGxv4HAA "Haskell – Try It Online") `True` for false and `False` for true. [Answer] # [Python 3](https://docs.python.org/3/), ~~37~~ 29 bytes -8 bytes thanks to xnor. Fails for doubling sequences, completes otherwise. ``` f=lambda a,*b:2*a<=b[0]>f(*b) ``` [Try it online!](https://tio.run/##nY89C4NADIb3@xVZxFNS8GuSnlsL3buJw1lPKliVuwj66@1pKaV1a4YkPLz5eIeZ7n0XL0stWvkoKwkS/TKNfHkUZR4UWc390ltIGTIggDPgeRhgFGAcFAhn2Rrl4YcmK73q8Q0xwvhHZ1GyE4W/c@Fu@4d48EcwVvcaCBU0HWx@UgZAel4LgPVJ3tZpZcaWrNntmEVquqmB4NJVajpp3ev0W7e@zSwadNMRdx0DhwxsFsJm1@GELynaz5cn "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 40 bytes ``` f=lambda a,*b:b==()or 2*a<=b[0]and f(*b) ``` [Try it online!](https://tio.run/##nY@/CoMwHIR3n@LolMivEP9M0nTsE3QThwQTKtgomkKL@OypLRRBt974cXfw9S9/61wWgpWtuutaQVGsCy0l492ANFYnqUtRKVfDsljz4M3oR0iwCKxMBKWCMlERLqodDaeV5h96HR4/SCllm96C8l0p2e6S3ftKOP5IFNnFzZNB4/D1KSL0Q@M8s4fJzzieMS22ns8wzx6TmQ88vAE "Python 3 – Try It Online") Test suite by Noodle9. [Answer] # JavaScript (ES6), ~~26~~ 24 bytes *Saved 2 bytes thanks to @Grimmy* ``` a=>!a.some(n=>2*a>(a=n)) ``` [Try it online!](https://tio.run/##fc2xDsIgEIDh3ac4NzDYHrQrjD6Bm2G4VGo0yJmivj5qotFEZf/y/we6Uh6m/em8TLwNZbSFrJtTk/kYRLLOLMgJsknKMnDKHEMTeSdGsdGoDKoOvZTQtrCimMPsp@lfZj1dvokyqvMAUMvcTf82/zIafZ3oR6N@wif6MOUG "JavaScript (Node.js) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` Λ·≤D ``` [Try it online!](https://tio.run/##yygtzv7//9zsQ9sfdS5x@f//f7ShjpGOoUEsAA "Husk – Try It Online") Returns 0 if False, a positive number if True. ``` Λ Check if adjacent pairs of elements satisfy the predicate · D by doubling the first number ≤ and checking if the second number is less than it ``` [Answer] # [Dyalog APL](https://www.dyalog.com/), 8 bytes ``` ∧/2≤2÷/÷ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhEcdy/WNHnUuMTq8Xf/wdqCYgqGBgpGBgrEBF4xpAmYqGCkYQ2kTKG0IkTCEqDQEAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 18 bytes ``` @(e)istril(e<2*e') ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1Uzs7ikKDNHI9XGSCtVXfN/mka0oYGOkYGOsUGsJhecZwLk/QcA "Octave – Try It Online") Octave has a nice feature known as broadcasting. Here, we take broadcast less-than of the input and the input doubled, by transposing the input. This creates a matrix of ones and zeroes. Iff this matrix is lower triangular (no nonzero entries above the diagonal), the sequence is a doubling sequence. [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes ``` ->l{x,*l=l;l.all?{|y|x*2<=x=y}} ``` [Try it online!](https://tio.run/##NcqxCoAgEIDhV2mOS9Tc6upB5AYbmi6IIDhRn92GdPvg/5/3iPXEOm2cBEZGXlgF5j3lmGW0KwrGUqr3RoPVMGuCodn9Bgtzh@swrZm2GyJ1hTtlyffgBU4vRKV@ "Ruby – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-rR`, ~~15~~ 13 bytes ``` 1&÷{!;|":'½≤⑾ ``` [Try it online!](https://tio.run/##y05N///fUO3w9mpF6xolK/VDex91Lnk0cd///9GGOgpGOgrGsf91i4IA "Keg – Try It Online") *-2 bytes thanks to @a'\_'* ## Answer History ### 15 Bytes ``` 1&÷^{!;|":'2*≥⑾ ``` [Try it online!](https://tio.run/##y05N///fUO3w9rhqResaJSt1I61HnUsfTdz3/3@0oY6CkY6Ccex/3aIgAA "Keg – Try It Online") I'm quite happy with this answer, and I'm quite happy with the explanation. **Explained** ``` 1& ``` First, we store the number 1 in the register. This will end up being the means by which the result is shown. ``` ÷^ ``` We then item split the input list and reverse it, so that things are in descending order. ``` {!;| ``` Now, we start a while loop that will run while the length of the stack - 1 is not zero. ``` ":' ``` This bit of the algorithm took me a while to visualise and write... I had to resort to move playing cards around my living room floor to understand which stack shifting mechanics to use. Lets say the input stack (after item splitting and reversal) is `[4, 2, 1]`. Right shifting the stack (`"`) gives `[1, 4, 2]`, duplicating the top gives `[1, 4, 2, 2]` and then left shifting the stack (`'`) gives `[4, 2, 2, 1]`. We do this so that we can compare the top of the stack with the next item and preserve that second item (in other words, circumnavigate the side effects of operators consuming stack items). ``` 2*≥ ``` We then multiply the top item by two and see if the result is greater than or equal to the next item in the series. ``` ⑾ ``` The result is then augmented multiplied into the register and the while loop continues. `-rR` prints the value of the register at the end of execution as an integer. [Answer] # [Python 3](https://docs.python.org/3/), ~~57~~ \$\cdots\$ ~~44~~ 43 bytes Saved a byte thanks to [kaya3](https://codegolf.stackexchange.com/users/91685/kaya3)!!! ``` lambda l:all(b>=a*2for a,b in zip(l,l[1:])) ``` [Try it online!](https://tio.run/##nY/BCoJAFEX38xWPVjPxAkddCbrsC9qZi5FmSHjpoC@oxG@fMghBd93l4d4Lxz/52rVJcPk5kLnVFwOUGSJZF7nZx67rwWANTQuvxktCKnVWKRXYDjxADlKALHWEcYRJVCEcDQ1W4ULTmZ76@w9ijMmq90HppqTXO715X4iCPyLEbMdoZ7uvTybA903L0u1GnuBQwOgkqwnsw8Nop50Kbw "Python 3 – Try It Online") [Answer] # [PHP](https://php.net/), ~~53~~ ~~49~~ ~~47~~ 43 bytes ``` for(;$argv[$i++]*2<=$k=$argv[$i];);echo!$k; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVEovSy6JVMrW1Y7WMbGxVsm1hIrHWmtapyRn5iirZ1v///zf8b/Tf0OC/kQEA "PHP – Try It Online") -4 bytes thanks to @Kaddath. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~46~~ ~~33~~ 31 bytes ``` @(n)all(2*n(1:end-1)<=n(2:end)) ``` [Try it online!](https://tio.run/##y08uSSxL/f8/zdZBI08zMSdHw0grT8PQKjUvRddQ08Y2T8MIxNbU/J@mEW1ooGNkoGNiEKv5HwA "Octave – Try It Online") Thanks to Luis Mendo for `all`. Much shorter! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~4~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) [Crossed out 4 is still regular 4 ;(](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44) ``` ¥›à ``` Outputs `0` for truthy and `1` for falsey. Port of [*@RGS*' first Jelly answer](https://codegolf.stackexchange.com/a/199416/52210), so make sure to upvote him! -1 byte thanks for *@Grimmy* for mentioning any two distinct truthy/falsey values are allowed, so I can drop the invert at the end [Try it online](https://tio.run/##yy9OTMpM/f//0NJHDbsOL/j/P9rQQMfIQMfEIBYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf6fL/0NJHDbsOL/iv8z862tBAx8hAx9ggVgfKNAEzdYx0jKG0CZQ2hEgYQlQaxsYCAA). **Explanation:** ``` ¥ # Get the deltas (forward differences) of the (implicit) input-list › # Check for each whether it's larger than value at the same position in the (implicit) # input-list, which automatically ignores the trailing item of the input à # Get the maximum of this, to check if any are truthy # (after which it is output implicitly as result) ``` [Answer] # [Clojure](https://clojure.org/), ~~42~~ 40 bytes ``` (fn[s](every? #(<= 2%)(map /(rest s)s))) ``` [Try it online!](https://tio.run/##TcwxCoAwEETRPqcYEGG3EBO11oOIhWhSiEZJYuHpo53bzYPhL/u53cFmWq2Dy@T8GCfyZ6pm/wwoqEeDkumYL9QUbEyIHJk5s6IreAVyGI1Go9HqiaW731@klegkjPgZkfg25xc "Clojure – Try It Online") Basically the obvious pairwise thing, with a fun way to generate consecutive pairs of a sequence. [Answer] # [Lua](https://www.lua.org/), 54 bytes ``` for i=2,#arg do b=b or arg[i-1]*2>0+arg[i]end print(b) ``` [Try it online!](https://tio.run/##yylN/P8/Lb9IIdPWSEc5sShdISVfIck2SQEoBORFZ@oaxmoZ2RlogzmxqXkpCgVFmXklGkma////NzT4b2Tw38QAAA "Lua – Try It Online") `true` and `false` are swapped. [Answer] # Desmos, 41 Bytes ``` f(n)=1-l(n[2n[0...l(n)]>n]) l(n)=n.length ``` [Try It Over Here](https://www.desmos.com/calculator/u24c7rpumy?nographpaper) [Answer] # [J](http://jsoftware.com/), 14 bytes ``` [:*/0.5>:2%/\] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209A30TO2sjFT1Y2L/a3IpcKUmZ@QrpCkYGigYGSgYG6DyTRB8BSMFY2SOCTLHEEmdIZIRhv8B "J – Try It Online") [Answer] # x86-16 machine code, 11 bytes ``` 49 DEC CX ; adjust to loop N-1 times N_LOOP: AD LODSW ; load N1 into AX D1 E0 SHL AX, 1 ; double AX 39 04 CMP WORD PTR[SI], AX ; compare to N2 7C 02 JL DONE ; if less, return E2 F7 LOOP N_LOOP ; keep looping DONE: C3 RET ; return to caller ``` Input array at `[SI]`, length in `CX`. Returns `ZF` if `truthy`, `NZ` if `falsey`. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 28 bytes GolfScript has its clunky zip function (I need a lot of code to convert the string to a list of codepoints). ``` .1>]zip);{1/~0=\0=2*<!}%{&}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPkfbWigYGSgYGwQ@1/P0C62KrNA07raUL/OwDbGwNZIy0axVrVarVbrf2zCfwA "GolfScript – Try It Online") # Explanation ``` .1>]zip # Zip itself with itself without the first item ); # Discard the extra trailing item {1/~0=\0=2*<!}% # Is the first item * 2 greater than or equal to the next item? {&}* # All of them? ``` # [GolfScript](http://www.golfscript.com/golfscript/), 31 bytes ``` .(+{2/}%]zip);{1/{0=}%~>!}%{&}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPkfbahgpGBoEPtfT0O72ki/VjW2KrNA07raUL/awLZWtc5OsVa1Wq1W639swn8A "GolfScript – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` <1hS/MP.T,t ``` [Try it online!](https://tio.run/##K6gsyfj/38YwI1jfN0AvRKfk//9oQx1jHTMdQxMdY2MdQwMDHRMDo1gA "Pyth – Try It Online") ### Explanation ``` <1hS/MP.T,tQQ # full program, last two Q (=input) are implicit ,tQQ # [Q[1:], Q] .T # Transpose -> [[Q[1],Q[0]], [Q[2],Q[1]], ..., [Q[-1]]] P # all but last element (gets rid of lone Q[-1]) /M # Map all pairs by division S # Sort quotients h # first element (minimum quotient) <1 # is 1 smaller than this? ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 15 bytes ``` raJ0{2.*>=}LO== ``` [Try it online!](https://tio.run/##SyotykktLixN/Z@TV/2/KNHLoNpIT8vOttbH39b2f21u9P9oQwMdIwMdY4NYLijTBMzUMdIxhtImUNoQImEIUWkYCwA "Burlesque – Try It Online") Finally got an answer where using `LO` is advantageous. ``` ra # Read as array J # Duplicate 0 # 0 (start of loop) {2.* # Double >= # Greater than or equal to previous elem }LO # Loop through array performing op on each pair # Push to array if true == # Arrays are the same ``` # Burlesque, 16 bytes Alternative (but longer) solutions using 2-grams and map-reduce ``` ra2CO{./2>=}m^r& ra2CO{p^./2>=}al ``` [Try it online!](https://tio.run/##SyotykktLixN/Z@TV/2/KNHI2b9aT9/IzrY2N65I7X9tbvT/aEMDHSMDHWODWC4o0wTM1DHSMYbSJlDaECJhCFFpGAsA "Burlesque – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 49 bytes ``` param($n)($n|?{$_-ge2*$l;$l=$_}).count-eq$n.count ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPE4hr7KtV4nXTU420VHKsVXJsVeJrNfWS80vzSnRTC1XyIMz///87aBjqGOmYaAIA "PowerShell – Try It Online") Takes input `$n` then uses a `Where-Object` to pull out those elements that are `-g`reaterthanor`e`qual to `2` times the `$l`ast element. Those are left on the pipeline, and we set our `$l`ast element for the next iteration. We then take the `.count` of that collection and make sure it's `-eq`ual to the `.count` of our input array. That Boolean value is left on the pipeline and output is implicit. --- If we don't need to worry about negative numbers, we can use the following instead, thanks to mazzy: # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 27 bytes ``` !($args|?{$_-lt2*$l;$l=$_}) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X1FDJbEovbjGvlolXjenxEhLJcdaJcdWJb5W8////4b/jf6bAAA "PowerShell – Try It Online") This again takes input `$args`, and pulls out those items where they're `-l`ess`t`han `2` times the `$l`ast element (i.e., they're not "big enough" to make the doubling sequence). If there are any left, then the Boolean-not surrounding the collection results in `False`, otherwise if the collection is empty we get `True`. That's left on the pipeline and output is implicit. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-r`, 11 bytes ``` $&2*_<=BMPg ``` [Try it online!](https://tio.run/##K8gs@P9fRc1IK97G1sk3IP3/f0MDLiMDLmOD/7pFAA "Pip – Try It Online") Takes input numbers separater by newlines. (`-r` flag) ## Explanation ``` $&2*_<=BMPg g → input MP pass pairs from g to function on the left 2*_<=B a ≤ b? for pair (a, b) $& Fold with & operator ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~25~~ 15 bytes ``` Min@Ratios@#<2& ``` Returns `True` for false and `False` for true. -10 bytes thanks to @att [Try it online!](https://tio.run/##y00syUjNTSzJTE7876Zg@983M88hCMjNL3ZQtjFS@x9QlJlXEq2soGun4BatHBuroKag76BQXW1ooKNgBMTGBrU6CnCeCYQH5ABlEEwTBNMQpsIQps@wtvY/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 41 bytes ``` a=>all([a[x+1]/a[x]>=2for x:0..len(a)-1]) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/R1i4xJ0cjOjG6QtswVh9IxdrZGqXlFylUWBno6eWk5mkkauoaxmr@LyjKzCvRSNOINtRRMNJRMNVRMASxjGI1Nf8DAA "Proton – Try It Online") This isn't very efficient because Proton is too buggy to do this right. [Answer] # [Arturo](https://arturo-lang.io), ~~29~~ 28 bytes ``` $=>[l:0every?&'x[x>=l*2l:x]] ``` [Try it](http://arturo-lang.io/playground?FlfhwT) [Answer] # [Pyt](https://github.com/mudkip201/pyt), 6 bytes ``` ↔ʁ/2≥Π ``` [Try it online!](https://tio.run/##K6gs@f//UduUU436Ro86l55b8P9/tLGOmY6haSwA "Pyt – Try It Online") Outputs 1 if doubling array, 0 otherwise ``` ↔ implicit input; flip array ʁ/ ʁeduce by division 2≥ is each element greater than or equal to 2? Π take product of list; implicit print ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 27 bytes ``` rl1)?v1n;n0< @:$+:<|.!:0^?) ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoicmwxKT92MW47bjA8XG5AOiQrOjx8LiE6MF4/KSIsImlucHV0IjoiIiwic3RhY2siOiIxIDIgNCA4IDEwMCIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) * `r` reverse * `l1)?` is the length greater than 1? * `v` then go down * `1n;` otherwise, output 1 (true) * `<` go left * `:+` double * `$:@` duplicate NOS * `)?` is NOS greater than TOS? * `^<0n;` then output 0 (false) * `0:!.|` go back to start after inverting direction ]
[Question] [ This challenge takes place on the [snub square tiling](https://en.wikipedia.org/wiki/Snub_square_tiling). Start by choosing any triangle, and color it \$c\_1\$. Next, find all tiles which touch this triangle at any vertex, and color them \$c\_2\$. Next, find all tiles which share a vertex with any \$c\_2\$-colored tile, and color these \$c\_3\$. Continue this process ad infinitum. # Illustration [![Concentric tiling on snub square tiling](https://i.stack.imgur.com/Sst1X.png)](https://i.stack.imgur.com/Sst1X.png) # Initial terms The sequence begins ``` a(1) = 1 a(2) = 9 a(3) = 21 a(4) = 35 ``` Notice: * `a(1) = 1` corresponds to the red triangle; * `a(2) = 9` corresponds to the number of tiles in the second, orange layer; * `a(3) = 21` corresponds to the number of tiles in the third, green layer; and so on. (Note, this [sequence is now in the OEIS](https://oeis.org/A332019); OEIS sequence [A296368](https://oeis.org/A296368) is closely related.) # Challenge Your goal is to write a program that takes in a positive integer `n` and returns the number of tiles that are colored \$c\_n\$, (i.e. the number of tiles in the \$n\$-th layer.) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in bytes wins. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` ->n{~-n*12-496/4**n%4+1/n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vuk43T8vQSNfE0kzfREsrT9VE21A/r/a/hqGenqGBpl5uYkF1TWZNgUJ0pk5adGZsbO1/AA "Ruby – Try It Online") Revised version adding `1/n` and subtracting `496/4**n%4` to get the `+1,-3,-3,-1` offset for the first 4 terms. # [Ruby](https://www.ruby-lang.org/), 32 bytes ``` ->n{n>4?~-n*12:[0,1,9,21,35][n]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOs/OxL5ON0/L0Mgq2kDHUMdSx8hQx9g0Njovtva/hqGenqGBpl5uYkF1TWZNgUJ0pk5adGYsUAoA "Ruby – Try It Online") After 4, the sequence settles down to `(n-1)*12`. See diagram below (the equilateral triangles have been distorted into 45 degree isosceles triangles and the entire diagram rotated 45 degrees, but it remains topologically equivalent.) [![enter image description here](https://i.stack.imgur.com/QYnJD.png)](https://i.stack.imgur.com/QYnJD.png) [Answer] # JavaScript (ES6), 23 bytes Based on [Level River St's answer](https://codegolf.stackexchange.com/a/198953/58563). ``` n=>[1,5,13,7][--n]^n*12 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7aUMdUx9BYxzw2Wlc3LzYuT8vQ6H9afpFGnoKtgqG1Qp6CDZA2ADK0tTUVqrkUFJLz84rzc1L1cvLTNRISNVSq82o1gWpVqtM08jRrEzStuWr/AwA "JavaScript (Node.js) – Try It Online") ### How? We compute \$(n-1)\times12\$ and adjust the first 4 values with a XOR. $$\begin{array}{c|c} n&1&2&3&4&5&6&7&8&9&10\\ \hline (n-1)\times12&0&12&24&36&48&60&72&84&96&108\\ \hline \text{XOR}&1&5&13&7&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0&\color{grey}0\\ \hline a(n)&1&9&21&35&48&60&72&84&96&108 \end{array}$$ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` <©12*3®cα ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5tBKQyMt40Prks9t/P/fGAA "05AB1E – Try It Online") or [try a test suite](https://tio.run/##yy9OTMpM/R/i7mevpKBrp6Bk7/ff5tBKQyMt40Prks9t/K/zHwA). ``` < # input - 1 © # save to register 12* # multiply by 12 ® # push the register 3 c # binomial coefficient(3, input - 1) α # absolute difference ``` With 0-indexing, this would be 7 bytes: ``` 12*3Icα ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’3cạ×ʋ12 ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw0zj5Ie7Fh6efqrb0Oj///@mAA "Jelly – Try It Online")** ### How? ``` ’3cạ×ʋ12 - Link: integer, n ’ - decrement (n-1) 1 2 3 4 5 6 7 ... 12 - twelve 12 12 12 12 12 12 12 12 ... ʋ - dyad: 3 - three 3 3 3 3 3 3 3 3 ... c - choose 3C(n-1) 1 3 3 1 0 0 0 ... × - multiply (n-1)*12 0 12 24 36 48 60 72 ... ạ - absolute difference |3C(n-1)-(n-1)*12| 1 9 21 35 48 60 72 ... ``` [Answer] # [Python](https://docs.python.org/3/), 31 bytes ``` lambda n:n*12-11-(n>4or 5%-n%5) ``` [Try it online!](https://tio.run/##DcrNCkBAFAbQV/lSakZmcf1sFC@CxYjhFtc02UiefTjr4@9rO6WMDi2GuNtjmi2kkYwKQ2SUdNUZUKdG0lrH3geWS7nk4Remw@MU6zfRcH9isCBYWRdFeUF6jB8 "Python 3 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytesSBCS ``` 12(|×-3!⍨⊢)-∘1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///39BIo@bwdF1jxUe9Kx51LdLUfdQxw/B/2qO2CY96@x71TfX0f9TVfGi98aO2iUBecJAzkAzx8Az@n3ZoxaPezYYGAA "APL (Dyalog Unicode) – Try It Online") Direct translation of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/198961/78410). Even the code structure is the same. Jelly is a golfy descendant of APL; if you want to learn Jelly, learn APL first! ### How it works ``` 12(|×-3!⍨⊢)-∘1 ⍝ Monadic train, input: n 12( )-∘1 ⍝ Pass on to the inner function with left←12 and right←n-1 × ⍝ left × right - ⍝ minus 3!⍨⊢ ⍝ binomial(3, right) | ⍝ absolute value of the above ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 9 bytes ``` ’3cạ×12$Ʋ ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//4oCZM2PhuqHDlzEyJMay/zvigJwgLT4g4oCdO8OHCjEww4figqxZ/w "Jelly – Try It Online") A monadic link taking \$n\$ as its argument and returning \$a(n)\$. Based on [@LevelRiverSt’s clever Ruby answer](https://codegolf.stackexchange.com/a/198953/58563) so be sure to upvote that one too! Thanks to @Grimmy for saving 6 bytes! ## Explanation ``` ’ | Subtract 1 Ʋ | Following as a monad 3c | - Number of ways of picking (n-1) items from 3 ạ $ | - Absolute difference from: ×12 | - Multiply (n-1) × 12 ``` [Answer] # brainfuck, 50 bytes ``` >>>>>>+<++<<----<+<,-[>++++++++++++[[>+<-]<]>>-]>. ``` Does i/o as raw byte values, like the others here. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes ``` {$_*12-[-1,3,3,1][$_]}o*-1 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXsvQSDda11DHGAgNY6NV4mNr87V0Df9bcxUnViroAdWl5RcpGOrpGRr8BwA "Perl 6 – Try It Online") If this could be zero-indexed the `o*-1` at the end can be removed. Returns `(n-1)*12`, offsetting the first 4 values. [Answer] # [Python 3](https://docs.python.org/3/), 40 36 bytes ``` lambda n:~-n*12-(*n*[0],1,3,3,-1)[4] ``` [Try it online!](https://tio.run/##DcJBCoMwEAXQq3xcJSGBjnYl2IukWUQ0dkBHCW5E9OqxvLcd@2@VpiR0@JY5Lv0QIe3txFDtlBHjX8GSbf4caf8OxW@ZZVepOvmC@@BMivVVaaQ1g8GCHGUaFVkiHcoD "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` lambda n:n>4and~-n*12or[1,9,21,35][n-1] ``` [Try it online!](https://tio.run/##BcFBCoMwEAXQqwyukhIXk9RFBb2IuphiYwfaHwluRPTq8b11374JocRuLD/5v2chtOifgvmq8WCf8sDu5Ty70EwDap5KTJmUFJQFy8ewY7btmhWbiZWYQ09LHR3RqD0rW24 "Python 3 – Try It Online") Total rip of [Level River St](https://codegolf.stackexchange.com/users/15599/level-river-st)'s answer so upvote him. [Answer] # [Python](https://docs.python.org/3/), 38 bytes ``` lambda n:n*12-11-([1]*n+[2,4,4,0])[-n] ``` **[Try it online!](https://tio.run/##HYlLCoAgFAD3neLt0lLoVRAEdRFzYZQV1DPMTae3z8xqmPMOq6Mq2m6IuznGyQC1lGEpESVTqDPKVSnq10JzJUlH6zyE@QqwEXhDy8xQADa8TeDl9BsF9n0BqexTAfYvzuMD "Python 3 – Try It Online")** [Answer] # [J](http://jsoftware.com/), 14 bytes ``` 12(*|@-3!~])<: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DY00tGocdI0V62I1baz@a3IpcKUmZ@QraFinaSqo2SkYamfqGRr8BwA "J – Try It Online") A [J](http://jsoftware.com/) port of [Bubbler's APL answer](https://codegolf.stackexchange.com/a/198966/75681), so it's also a port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/198961/78410). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~34~~ ~~33~~ 32 bytes Saved a byte thanks to [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy)!!! ``` f(n){n=--n<4?"!)5C"[n]-32:n*12;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs9WVzfPxsReSVHT1FkpOi9W19jIKk/L0Mi69n9uYmaehmZ1Wn6RRmZeiUKmrYG1tnamjZGhdUERUCBNQ0k1RUHXTkE1JSZPSSdTJ00jU1NTE6gRAA "C (gcc) – Try It Online") [Answer] # brainfuck, 78 bytes ``` ++++[->+++<]>>>+>--->--->-<<<<<<,-[->>>[+]<[->+<]<[->+>+<<]<[->+<]>]>>[->+<]>. ``` You can try it online over at [TIO](https://tio.run/##SypKzMxLK03O/p@bmptfVGnFlZlXoFCjYGgEJBKTk0FMIM5LTVcwRqNB4gZQnFqSnFqSWpT4XxsIonXtgKRNrJ2dnbadrq4uBNuAgY4uUNbOLlo71gakzAZCARk2MAE7oD4oS@//fy4A) (the input is a line-feed (ascii 10) and the output is an `l` (ascii 108)) You can also try the verbose code at [this](https://copy.sh/brainfuck/?c=KysrK1stPisrKzxdIHNldCB1cCAxMgo-Pj4rPi0tLT4tLS0-LSBzZXQgdXAgdGhlIHNoaWZ0cwo8PDw8PDwgYmFjayBhdCAwCiwKbWVtb3J5IGF0IHRoaXMgcG9pbnQgKHBvaW50ZXIgaXMgYXQgdGhlIGxlZnQpCmlucCB8IDEyIHwgMCAoYWNjdW11bGF0b3IpIHwgMSB8IG5lZyAzIHwgbmVnIDMgfCBuZWcgMSB8IDAgfCAwIHwgZXRjZXRlcmEKLSBzdWJ0cmFjdCAxIGZyb20gbiBmaXJzdApbIHdoaWxlIHRoZXJlIGlzIHNvbWUgaW5wdXQKLSBkZWNyZW1lbnQgaXQuCj4-PlsrXSB6ZXJvIG91dCB0aGUgbmV4dCBzaGlmdAo8Wy0-KzxdIG1vdmUgdGhlIG91dHB1dCBvbmUgY2VsbCBmb3J3YXJkCjxbLT4rPis8PF0gbW92ZSB0aGUgMTIgZm9yd2FyZCBhbmQgYWxzbyBhZGQgaXQgdG8gdGhlIG91dHB1dAo8Wy0-KzxdPiBtb3ZlIHRoZSBpbnB1dCBvbmUgY2VsbCBmb3J3YXJkCl0KPj4KWy0-KzxdIGFkZCBvdXRwdXQgdG8gb2Zmc2V0Cj4uIHByaW50IG91dHB1dA$$) online interpreter where input can be inserted as decimals, e.g. `\6` gives 6 as input. After running, you can hit the "view memory" button and check the value of the output cell in bold, to ensure the result is right. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 61 bytes ``` ,-[>++<-[>+++<-[>+++>++<<-[>+++>+<<-[>+++<-]]]]]>[>++++<-]>+. ``` Input/output as character codes ([meta](https://codegolf.meta.stackexchange.com/a/18027/6484)). [Try it online!](https://tio.run/##SypKzMxLK03O/v9fRzfaTlvbBkzCKJAAnGkDl4sFATswB8Sz09b7/58LAA "brainfuck – Try It Online") or [try it with decimal I/O](https://tio.run/##dVBBCsMwDHuQl152FfqI8aEbDMagh8Hen8pum22wCeLEtiwluTzn@3J7XR@d5t6CWic3b2941qzg2EpsoRPgjbQBICguYGQoRAQCXQLqVTy2LIwjRi8SrCQzWv@Wl50xydJnXjJNKkOh7BU@hzTzfyI2vu8D2d4hwpQPsWQEvHRwfEMbDpKYioGfEmrltdMV/bwC). [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ų@8Ω@╩vä3 ``` [Run and debug it](https://staxlang.xyz/#p=8ffd4038ea40ca768433&i=1%0A2%0A3%0A4&m=2) [Answer] # Rust - 52 bytes ``` let m=|n|(match n{1=>1,2=>9,3=>21,4=>35,_=>n}-1)*12; ``` oh gosh.. it loses even to Brainf\*\*\* ]
[Question] [ # Challenge Given a list, determine if grouping the list into runs of increasing and decreasing elements will result in a list of equal-sized lists. In other words, "turning points" of the list are spaced out evenly. # Example Here's an example: `0, 3, 7, 5, 2, 3, 6` `0, 3, 7` increases, `7, 5, 2` decreases, and `2, 3, 6` increases. Therefore this is truthy. Another example: `1, 4, 6, 8, 5, 3, 5, 7, 9` `1, 4, 6, 8` increases, `8, 5, 3` decreases, and `3, 5, 7, 9` increases. Therefore this is falsy. # Rules and Specifications * No adjacent elements will be equal * All numbers can be assumed to be within your language's reasonable number range * You may assume that all numbers are integers, if it helps you golf your submission * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins * Input as a list in any reasonable representation and output as any truthy/falsy value. The two values must be consistent. # Test Cases ``` Input -> Output 1, 3, 5, 8, 6, 4, 2, 3, 5, 7, 6, 4, 2, 5, 7, 9, 6, 4, 2 -> True 1, 3, 5, 7, 6, 4, 5, 7, 9, 8, 6, 4, 2, 3, 5 -> False 2, 3, 6, 4, 2, 3, 7, 5, 3, 4, 6 -> True 3, 6, 4, 8, 5, 7, 3, 5, 2 -> True 8 -> True 1, 3, 5, 7 -> True 4, 5, 7, 6, 8, 9 -> False 6, 4, 2, 3, 5, 4, 2 -> True 8, 5, 3, 2, 4, 6, 5, 3, 2, 5, 7 -> False ``` **Note**: You may not assume that all numbers are single digits (unless that is all your language is capable of handling); the test cases reflect that just because it's easier for me to type the cases this way :P Here are a few test cases with numbers outside of that range: ``` 1, 5, 10, 19, 15, 13, 8, 13, 18, 23, 19, 18, 14 -> True 15, 14, 17, 16, 19, 18 -> True 12, 16, 19, 15, 18, 19 -> False ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 bytes ``` dZS&Y'da~ ``` [Try it online!](https://tio.run/##y00syfn/PyUqWC1SPSWx7v//aCMdBWMdBTMdBRMdBQjbXEfBFMwAipjFAgA "MATL – Try It Online") Saved one byte thanks to Luis Mendo! ### Explanation: Assume the input is: `[0, 3, 7, 5, 2, 3, 6]`: ``` % Implicit input: [0, 3, 7, 5, 2, 3, 6] d % Difference between adjacent elements: [3, 4, -2, -3, 1, 3] ZS % Sign of the differences: [1, 1, -1, -1, 1, 1] &Y' % Length of runs of consecutive elements: [2, 2, 2] d % Difference between the lengths: [0, 0] a % Any non-zero elements: False ~ % Negate, to get a truthy value if all are zero: True ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` IṠŒgAE ``` [Try it online!](https://tio.run/##y0rNyan8/9/z4c4FRyelO7r@//8/2lBHwUhHwVhHAcgw0FEw1VGw0FEwA4sg2LEA "Jelly – Try It Online") Saved 1 byte thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)! ## How it works ``` IṠŒgAE - Full program. I - Increments (Deltas). Ṡ - Sign of each. -1 if negative, 0 if null, 1 if positive. Œg - Group runs of adjacent elements. A - Absolute value. Vectorizes. This maps -1 and 1 to the same value. E - Are all equal? ``` While golfing, I discovered some cool, longer alternatives: `IṠŒgL€E`, `IṠŒrṪ€E` (uses run-length-encode instead). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes ``` Equal@@(1^Differences@#~SplitBy~Sign)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d@1sDQxx8FBwzDOJTMtLbUoNS85tdhBuS64ICezxKmyLjgzPU9T7b@mNVdAUWZeiUOaQ7WhjoKpjoKhARBbAjGIbayjYAGhDIG0kTFUCiRmUvsfAA "Wolfram Language (Mathematica) – Try It Online") ### Explanation ``` Equal@@(1^Differences@#~SplitBy~Sign)& (* Input: {3, 6, 4, 8, 5, 7, 3, 5, 2} *) Differences@# (* Take differences: {3, -2, 4, -3, 2, -4, 2, -3} *) ~SplitBy~Sign (* Split by sign: {{3}, {-2}, {4}, {-3}, {2}, {-4}, {2}, {-3}} *) 1^ (* Raise to power of 1: {{1}, {1}, {1}, {1}, {1}, {1}, {1}, {1}} *) Equal@@ (* Check equal: True *) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~54~~ 50 bytes ``` @(x)nnz(unique(diff(find([diff(diff(x)>0) 1]))))<2 ``` [**Try it online!**](https://tio.run/##XY9NCsIwEIX3PcUsExiK/bFN0Yr3KF1Im0CgRMVGiuLZY0xojM4izHzz5j1yHubTnRvRpmlqjmShSj2IVvKqORmlEERINZLOte5Z6GFDIeuprX1upLro@QYtPLsMoUDYIjCECqFEyFdSR8SPTSB98r0MuiD697Jq38W0dgeFI5VVhDVbnbz9J4v95NmhjJKtvulfu2Tg0yS0IgLBf5CaNw) ### Explanation ``` @(x)nnz(unique(diff(find([diff(diff(x)>0) 1]))))<2 @(x) % Define anonymous function diff(x) % Deltas (consecutive differences) >0 % Positive? Gives signs diff( ) % Deltas between signs [ 1] % Append 1 to "close" last group find( ) % Indices of nonzeros diff( ) % Deltas. Gives group lengths unique( ) % Remove duplicates nnz( ) % Number of nonzeros. Gives length <2 % If 1 or 0: input is periodic ``` [Answer] ## R, 36 bytes ``` function(n)!sd(rle(sign(diff(n)))$l) ``` `diff` computes the successive differences, then `sign` squishes those down to ±1. `rle` then run-length encodes them. All the elements of this `rle` should be the same, i.e. the vector has standard deviation zero. `!` then produces the correct logical output. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes ``` ¥0.SγaË ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0FIDveBzmxMPd///H22oo2Cqo2BoAMSWQAxiG@soWEAoQyBtZAyVAomZxwIA "05AB1E – Try It Online") -1 thanks to Adnan. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~143~~ ~~140~~ ~~138~~ ~~136~~ ~~135~~ 132 bytes * Saved three bytes; using a variable `r` to store the function's return boolean instead of terminating using `return`. * Saved two bytes; golfing `int A[]` to `int*A` (using a pointer instead of an array). * Saved two bytes thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox); golfing `f(int*A,int a)` to `f(A,a)int*A;`. * Saved a byte; golfing `if(d!=...` to `if(d-...`. * Saved three bytes; golfing `;j++...j+1` to `;...++j`. ``` j,d,e,l,m,r;f(A,a)int*A;{for(d=A[0]>A[1],r=1,j=m=l=0;j-~-a;){l++;if(d-(e=A[j]>A[++j]))d=e,j--,r*=l>=(m=!m?l:m),l=0;}r*=-~l==m||m<1;} ``` [Try it online!](https://tio.run/##nZRNc5swEIbPza/Y@gS2SJD4DlUyPviaU2@MDxobt2bA7gC9xHH@urtCXoY6NONaF2Al7aN3Wb0r58dqdToVbM1yVrKK1enGmjNlb3ftdJ4eNvvaWst55i6f5hlfslpyVshKltJNC@fdUal9KGezdLux1o6V48pCr5zNiqVtr2XOCsdh9VSWT9Kq5NfquXysbKZ3HzHqvJdSVm9v1TeeHk@V2u4s@3D3BdnwChJ4at7nbsaTJQYOnIHHIGAQMwgZ@AwERaJBxHwmfeSYgs6jXJ0Uw233ksLDdPqApKkEFO0yXGCDlDhNYJ7x4G9wj@kZl0eBwSAw1zzc0eoX9wKMuRU34F6xyDjvwCbpEBB1bK@LhPCPQWChwQhoxYhizKeEAQsCexmYUvfUmLSaAgj4dBDYwxy6Oq03AsZMyjNgj8B@BkZxDDcNAvsarBX7I2CUo3wD9gkcZOBf/OObwIEGI6ANRsCYVQUGHBA4zCDswP6gs7DayX@CQw3GrW040lwYV6EBhwSOMu6RYgRz7Hx9K3SDcq87gn5wfArvPKVj/iU40kJxRRuNKEY5KjLgiMAxKe5QKJvjKh4S42rFMSmOR8B4VBUbcEzgpAeLATA4C0uuBicETkZKjSlVYsDJGbxwB81lrq@4pbly99xcjfsRvMD/lxvnasi5FjyDqANf2KR/5QkIrA1Lt2bDP5Z6gaJy41wNOdeid66YfEoYqxp8fnbHCEzO1YgRxZgjN87VaOf6VeOWjfX6PHnZQ17X@7qBzf73bn0/eZx8/5nXOWwbUDszdz@xcc/d8fQH "C (gcc) – Try It Online") Defines a function `f` which looks at every element in the list but the last and determines this element's relation to the next element in the list. The number of consecutive equal comparisons is stored the first time the relation flips, any runs after the initial run that differ in length to the stored length result in a falsy output. At the end, the second-to-last element's relation to the last element's is looked at so that it matches the rest of the list. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` qFlM.g._k.+ ``` [Try it here.](http://pyth.herokuapp.com/?code=qFlM.g._k.%2B&input=%5B1%2C+5%2C+10%2C+19%2C+15%2C+13%2C+8%2C+13%2C+18%2C+23%2C+19%2C+18%2C+14%5D&debug=00) [Answer] # [Python 2](https://docs.python.org/2/), ~~107~~ ~~105~~ ~~103~~ ~~97~~ ~~96~~ ~~94~~ 91 bytes ``` lambda l:len({sum(g)**2for k,g in groupby(map(cmp,l[:-1],l[1:]))})<2 from itertools import* ``` [Try it online!](https://tio.run/##bU5LDoIwEN17ilm2pCa2ICLRkygL/IDElja1Lozx7DiAkKIumum83zzzcBddi6bY7huZq8MpB5nKc02et7siJQ0CUWgLV1ZCVUNp9d0cHkTlhhyVYXKXznmGg6cZpS@6EbPCagWVO1untbxBpYy2LmiMrWoHBdlxBiGDJYOEQcwgYiAGZOUh/boekYzOfiNGw6j@DvVtPeTTq84ZdkjsS0ddMmT3Byc1kv@dfDTyamLU@suBHF/gw@K8/Yedqh0cpwg/VItFE2srxmyOyTweVBOF8JjlJwPPN28 "Python 2 – Try It Online") # [Python 3](https://docs.python.org/3/), ~~102~~ ~~100~~ 97 bytes ``` lambda l:len({len([*g])for k,g in groupby(x>y for x,y in zip(l,l[1:]))})<2 from itertools import* ``` [Try it online!](https://tio.run/##dY7NDoIwEITvPsUei9mDpYhg1BdBDxoFGwttak1E47NjC0KoxkP/vp2ZjqrNWVasydfbRuzLw3EPYilOFXm6LZsWuyCXGi5YAK@g0PKmDjW5b2pw@I61ww@uiECR0eUuCF7BKpzkWpbAzUkbKcUVeKmkNtNGaV4ZkpOMIjCEOUKCECNECGFPFiPSPdOB2PjJb8bgGOTfqZ6vY@P5orWylsSedhAmfXr3pd8k@dPLw9Goq01Lvz12SGd22frU3Vkrcwe1Z8g@I8ci3@vUNp3abBr3Ml8SjkbzT4pr0LwB "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` EmLġ±Ẋ- ``` [Try it online!](https://tio.run/##yygtzv7/3zXX58jCQxsf7urS/f//f7ShjrGOqY6FjpmOiY4RmG0OZYNYlhB2LAA "Husk – Try It Online") ## How this works ``` EmLġ±Ẋ- ~ Full program. Ẋ ~ Map over pairs of adjacent elements. - ~ With subtraction (this computes the deltas) ġ ~ Group using equality predicate. ± ~ Sign. mL ~ Get the lengths. E ~ Are all equal? ``` Some cute alternatives: ``` εġLġ±Ẋ- εüLġ±Ẋ- ``` [Answer] # [Python 2](https://docs.python.org/2/), 96 bytes ``` import re def f(x):exec"x=map(cmp,x[1:],x[:-1]);"*2;re.match('.([^1]*)(-?1, \\1)*9',`x+[9]`)<0<_ ``` [Try it online!](https://tio.run/##XY1NU4MwEIbv/IodLk1o2hH6AYQ6nvToyRuNlsHFMiOQWdOZ9NdjWiyil0z23WffR5/NsWujvq8b3ZEBQu8dK6iY5RItlr69bwrNykYLm4dSuVcuQsUzP4gywmVTmPLIZkuWv4Yq4GzxEArY70MepDNxsPM8VQe@u9u99VVHUEPdAhXtB7KYSw/A0FnCxQN@xepWnwzjrjsDTXVr4IVO6Ci0JWoDz0WDj0QdyZ/1U/H5hV6fO@VKwEZAImArYC0guiXxJBnGdEyU93s5ciP0v8vRw2@axteD1TXZOmJcJ7emof7iSv743LCemB2fqm8 "Python 2 – Try It Online") Output via exit code: crash (1) is falsey, clean exit (0) is truthy. ### [Python 2](https://docs.python.org/2/), 106 bytes ``` def f(x):d=map(cmp,x[1:],x[:-1]);l=len(d);s=(d+[0])[0];k=(d+[-s]).index(-s);print((k*[s]+k*[-s])*l)[:l]==d ``` [Try it online!](https://tio.run/##XY3BDoIwEETvfsWG0y4WI6CCNP2SpgdDSyRibQQT/HqsEBE9dNOZfTvjnt35ZpNh0KaCCnsqtLieHJZXx3oZF8rPIooV8UY0xqIm3grUa7lV5B@/jCJqFW1qq02PUUvc3WvbIV5C2aq1n@912JAsGiWEHkxvSggqrK17dEjEAwghWw0yZpAy2DPIGRwY7BgkHydbOJM8zo5afS9nbob@szw9/ZZuNh6ko3PwxLzOP0lT/Lsr/@nzYrdo9vxRvQA "Python 2 – Try It Online") [Answer] # [Desmos](https://desmos.com/calculator), 82 bytes ``` f(l)=0^{mod(k/k[1],1).total} L=D(D(l)) k=[1...L.length][LL=1] D(l)=sign(l[2...]-l) ``` [Try It On Desmos!](https://www.desmos.com/calculator/9jddrzflvt) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/cgoifst858) ### Explanation `D(l)=sign(l[2...]-l)`: Takes the consecutive differences of the input list `l`, and takes the `sign` of the resulting differences. `L=D(D(l))`: Applies the function `D` described above 2 times on `l`. The first difference will output a list (which I will denote as `A`) that, for each value of the original list `l[i]` for some `i` in the range `[1,l.length-1]`, does the following: * If `l[i]<l[i+1]`, `A[i]` will be 1. In other words, if `l` increases from `l[i]` to the next element, then it is denoted in the new list as 1. * If `l[i]>l[i+1]`, `A[i]` will be -1. In other words, if `l` decreases from `l[i]` to the next element, then it is denoted in the new list as -1. Note that we don't have to consider the case where `l[i]=l[i+1]`, because that is guaranteed not to happen as per the specs: > > * No adjacent elements will be equal > > > The second difference outputs a list (denoted as `B` below) that does the following for each value in `A`, `A[i]`, for some `i` in the range `[1,A.length-1]` (remember that the first difference is denoted as `A`): * If `A[i]=A[i+1]`, then `B[i]` will be 0. In terms of `l`, what this checks for is if `l[i]`, `l[i+1]`, and `l[i+2]` are all either increasing or decreasing. * If `A[i]<A[i+1]`, then `B[i]` will be 1. In terms of `l`, what this checks for is if it decreases from `l[i]` to `l[i+1]`, but increases from `l[i+1]` to `l[i+2]`. In other words, this will check for transitions from a decreasing run to an increasing run. * Similarly, if `A[i]>A[i+1]`, then `B[i]` will be -1. In terms of `l`, what this checks for is if it increases from `l[i]` to `l[i+1]`, but decreases from `l[i+1]` to `l[i+2]`. In other words, this will check for transitions from an increasing run to a decreasing run. `k=[1...L.length][LL=1]`: Filters the range `[1...L.length]` based on whether `L*L` is 1. This essentially obtains a list of indices at which `L` is either 1 or -1, and removes the indices where it is 0. What this achieves is that it will find the indices of the "turning points". `f(l)=0^{mod(k/k[1],1).total}`: Divides each element of `k` by the first element `k[1]`, and then takes the fractional part of the resulting quotients. If the "turning points" are spaced out evenly, then this will result in a list of all 0's. Otherwise, at least one element will be a decimal number. The `total` of this list is 0 only if the list only contains 0's, and nothing else. Otherwise, the `total` will be some number greater than 0. In other words, the `total` is 0 only if the elements are spaced out equally. The last part is that, `0^0` is 1, will `0^n` for some positive number `n` is 0. We can take advantage of this by using the `total` we obtained, and raising 0 to the power of the `total`. Recall that if the "turning points" are all spaced out evenly, then the `total` will be 0. This will cause `0^{mod(k/k[1],1).total}` to be 1. Otherwise, if they aren't spaced out equally, the `total` is greater than 0, so `0^{mod(k/k[1],1).total}` will be 0. [Answer] # JavaScript (ES6), 81 bytes This seems too long. I'm probably missing something here... Returns either `true` or `undefined`. ``` f=(a,p=1)=>a.every((n,i)=>!i|!(1/(y=a[i+1]))|!(i%p)^y>n^a[i-1]>n)||a[p]&&f(a,p+1) ``` Looks for a period ***0 < p < a.length*** such that all direction changes occur every ***p*** elements. ### Test cases ``` f=(a,p=1)=>a.every((n,i)=>!i|!(1/(y=a[i+1]))|!(i%p)^y>n^a[i-1]>n)||a[p]&&f(a,p+1) console.log(f([1, 3, 5, 8, 6, 4, 2, 3, 5, 7, 6, 4, 2, 5, 7, 9, 6, 4, 2])) // -> True console.log(f([1, 3, 5, 7, 6, 4, 5, 7, 9, 8, 6, 4, 2, 3, 5])) // -> False console.log(f([2, 3, 6, 4, 2, 3, 7, 5, 3, 4, 6])) // -> True console.log(f([3, 6, 4, 8, 5, 7, 3, 5, 2])) // -> True console.log(f([8])) // -> True console.log(f([1, 3, 5, 7])) // -> True console.log(f([4, 5, 7, 6, 8, 9])) // -> False console.log(f([15, 14, 17, 16, 19, 18])) // -> True console.log(f([19, 15, 14, 17, 18, 17, 16, 19, 20])) // -> True ``` [Answer] # [Haskell](https://www.haskell.org/), ~~79~~ ~~78~~ 77 bytes ``` import Data.List g s|h:t<-(1<$)<$>group(zipWith(<)s$tail s)=all(==h)t g _=1<3 ``` [Try it online!](https://tio.run/##dY9NC4JAEIbv/opBPLiwBab5EbudOnrr0CEkFgpdWj9wx0v03y0VRaWO8/A@78xkQj8fSrWtzKuyRjgJFNtYajRS0O/sgGxjO8wizDqmddlU9ktWF4mZzYi2UEgFmnChlM15Rjrpxh3mtrmQBXC4lwZUtSwQLEjh6lBwKewphBR8Ch6F3UiCGRnGaCLJomRQ5nrQK25P/GV4SoZj7bBu1Rkmv@8MOt7gGeu4MM0/mXHFdPb6u2W5N7O@yShpPw "Haskell – Try It Online") Given a list `s`, `zipWith(<)s$tail s`tests for each element whether it is smaller than its successor, e.g. `s=[2,3,6,4,2,3,7,5,3]` yields `[True,True,False,False,True,True,False,False]`. Then `group` runs of the same elements together: `[[True,True],[False,False],[True,True],[False,False]]`. To check whether all those lists have the same length, replace their elements with `1` ([see this tip](https://codegolf.stackexchange.com/a/146634/56433)) yielding `[[1,1],[1,1],[1,1],[1,1]]` and check if all elements in the tail `t` of this list equal the head `h`: `all(==h)t`. This approach does not work for singleton lists, but because those are always true, we can handle them in their own case: `g[_]=1<3`. [Answer] # [R](https://www.r-project.org/), 57 bytes ``` function(x){d=diff sum(rle(d(which(!!d(d(x)>0))))$v^0)<2} ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrM6xTYlMy2Nq7g0V6MoJ1UjRaM8IzM5Q0NRMQXIrtC0M9AEApWyOANNG6Pa/8mJJRppGskahjoKxjoKpjoK5joKZjoKJjC2pY6CBUzECKIGqP0/AA "R – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 bytes ``` ä- mg ò¦ mÊä¥ e ``` [Try it online!](https://tio.run/##y0osKPn///ASXYXcdIXDmw4tU8g93HV4yaGlCqn//0cb6igY6yiY6ihY6CiY6SiY6CgYwUTMkUQgXEu4SCwA "Japt – Try It Online") ## Explanation ``` ä- mg ò¦ mÊä¥ e [0,3,7,5,2,3,6] ä- // Difference between neighboring elements [-3,-4,2,3,-1,-3] mg // Get the sign of each element [-1,-1,1,1,-1,-1] ò¦ // Partition between different elements [[-1,-1],[1,1],[-1,-1]] mÊ // Get the length of each element [2,2,2] ä¥ // Check for uniqueness [true,true] e // Return true if all elements are truthy true ``` [Answer] # Haskell (Lambdabot), 59 bytes ``` g(map(1<$).group.ap(zipWith(<))tail->h:t)=all(==h)t;g _=1<3 ``` Based on @Laikoni's answer [Answer] ## Clojure, ~~70~~ 63 bytes ``` #(<(count(set(map count(partition-by pos?(map -(rest %)%)))))2) ``` Returns true or false. The original answer was a bit silly. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~437~~ ~~302~~ ~~256~~ 188 bytes ``` a->{int i=0,g=0,x=0,l=0;String d="";for(;i<~-a.length;d+=a[0].compare(a[i+1],a[i++])+1);for(String s:d.split("(?<=(.))(?!\\1)"))if(g++<1)x=s.length();else if(s.length()!=x)l++;return l<1;} ``` [Try it online!](https://tio.run/##TZBNT8MgGIDP7le86wksI6vfSrslHkw8eNqx6wFbVpkUCKVzyzL/esXZqSRvCM/7FZ413/CJsUKvq/deNtY4D@vAaOeloqtOl14aTc/ZyHavSpZQKt628MKlhv3orPXcB/g01KXP2otauLwg8GiMElzPwAonTRWqMuj5ZLaX2oPMpqQOsQ2hsilbeCd1DVUWRWxlHGIy/ZxwqoSu/Rur4ozn04KWprHcCcRzGScF@b7iAscJPvYMM9qHirZWSY8iNE8zRDFG8/FymeAIY7lCdRynCd5m7TAdYSZUKyCk/tA422IVx8wJ3zkNKk3YoWeDguHTGyMraIKIYXNeAMdBCgxnsWu9aKjpPLUh79FJBOXWqh3S4gN@fe0TApcErgncEbghcEXg4kRu/5Gf5/0vOWDMjhsPo0P/BQ "Java (OpenJDK 8) – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 135 bytes ``` a->{Integer i=0,c,d=0,p=0,r=0;for(;++i<a.length;)d+=(i<2|(c=i.signum(a[i-1]-a[i]))<0?d<0:d>0)?c:p==0|p==-d?c-(p=d):1-(r=1);return r<1;} ``` [Try it online!](https://tio.run/##bVLBbuIwEL3zFaNKSPbiRDFQSpMYtMc9rLRSj4iDGztZs@BEtlOpovl21kkgZLc9jMd@8@bNWDMH/saDspL6IP5c1KkqjYODx8LaqWP4LZlU9etRZZAdubXwkysN5wnAFbWOO@/eSiXg5GPoxRmli90euCks7qgw0strnTlV6vCXkUJl3MlUabfbbyAHduHB5vxDO1lIA4pFJCPCn5U3w6IkLw1KZjOV8vAodeF@J1jMGFLp/ANlTIVWFbo@Ib5TAd0H3u0xTqOtSKNYbCK8zeKKsejDH4HYZgGqmMAxDZBhFCdGutpoMClNmkvSdd015n/ipHUW2PUvAGdKYEHgkcCawIrAksD8hjyNkP75PCAN@SQw0Afu/5L3pB4YB5@6vEWHrO7EgbW@6fbFRg2sv@rlji1HzXmR53/YPkIjb75Z2t4XHad11Pv54hpqseUosaV6XepV6erGGcXnI/zxmn8r3PQDaRegG0o3krgfDB7m8vJunTyFZe3Cyi@hy9HD1MYwfZ3qBwLfjeHvNnRlv6GoTcYE8rC99C/cl2kmrTWXvw "Java (OpenJDK 8) – Try It Online") # Explanations ``` a->{ // int array Integer i=0,c,d=0,p=0,r=0; // variable definitions, use Integer to abuse static calls for(;++i<a.length;) // Loop from 1 till length - 1 d+= // Change d (i<2 // First iteration? |(c=i.signum(a[i-1]-a[i]))<0?d<0:d>0 ) // Or do c and d have the same sign? ?c // then increase the magnitude of d. :p==0|p==-d // else we're in a u-turn. Is it the first? Or is the magnitude the same as previously? ?c-(p=d) // assign the new magnitude with sign to p and reset d to -1 (if was positive) or 1 (if was negative) :1-(r=1); // else just do r=1 (technically: "add 1-1=0 to d" as well) return r<1; // return whether there were wrong amplitudes. } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~110~~ 99 bytes *-11 bytes thanks to @Lynn* ``` d=input() exec"d=map(cmp,d[:-1],d[1:]);"*2 x=[i+1for i,e in enumerate(d)if e] for i in x:i%x[0]>0<q ``` [Try it online!](https://tio.run/##XY5BT4QwEIXv/RUTEhPQmlBgWUDxpkdP3ggHhNls4wK1lsj@emzLwrIemum87828EWd17LtgqvsGc8dxpibnnRiU6xEcsXaavK2EW7eCNkX2yEpdWFZ6T859QMa84A/s0EvgFIF3gN3QoqwUuo3HD4AlsdCgMeN3Y@GXL/7z96RzyO@RnxA@5IAZAVDybAqACQVzjO2E5J2yJmJQjULBe9Xiq5S9zDaWt@r0c/XM5FNi9TUVjEJIYUchoRBTiCgEi7LfKHObrkpJrpOrbzX936Xd82@r7u1AaJVYO1acLJvm9SYrucnTTbRJ1v505lpivn76BGb@oYWmMF2D8IKMFpkJ49GbmN7D4gUaEGyE3WUiLf8A "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->a{!a.each_cons(2).chunk{|x,y|x>y}.uniq{|*,x|x.size}[1]} ``` [Try it online!](https://tio.run/##fZHdCoJAEIXvfYqJICymBc1KL/SyJ@hOJDYxkmqzbEFTn91sxWW1n73bwzkfZ2bufJ/XB@bWc48WI0oiGh534ZWlujkl4ZGzU1FmmJeZl1eEs/hWlDPMyoyk8TOqfCOo6pgl/AEu@BqAbyAsEJYINsIKwUIwO2WtKO3XkUqAMIa5B9s7j3oYGZKJIbiJqk9gNvScCk7rUf1rgVoIZTXIfnC6OpJhd0Xadu/efaf9B/lrxC@RntNSNtEUcHp@Zd5A05pLpCAOQi400ScHNq1f "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs `false` for truthy and `true` for falsey. ``` äÎòÎmÊäÎd ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5M7yzm3K5M5k&footer=IVU&input=WzAgMyA3IDUgMiAzIDZd) (footer negates the output) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=5M7yzm3K5M5k&footer=IVU&input=WwpbMCAzIDcgNSAyIDMgNl0gICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0%2bIHRydWUKWzEgNCA2IDggNSAzIDUgNyA5XSAgICAgICAgICAgICAgICAgICAgICAgICAtPiBmYWxzZQpbMSAzIDUgOCA2IDQgMiAzIDUgNyA2IDQgMiA1IDcgOSA2IDQgMl0gICAgIC0%2bIHRydWUKWzEgMyA1IDcgNiA0IDUgNyA5IDggNiA0IDIgMyA1XSAgICAgICAgICAgICAtPiBmYWxzZQpbMiAzIDYgNCAyIDMgNyA1IDMgNCA2XSAgICAgICAgICAgICAgICAgICAgIC0%2bIHRydWUKWzMgNiA0IDggNSA3IDMgNSAyXSAgICAgICAgICAgICAgICAgICAgICAgICAtPiB0cnVlCls4XSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLT4gdHJ1ZQpbMSAzIDUgN10gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0%2bIHRydWUKWzQgNSA3IDYgOCA5XSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAtPiBmYWxzZQpbNiA0IDIgMyA1IDQgMl0gICAgICAgICAgICAgICAgICAgICAgICAgICAgIC0%2bIHRydWUKWzggNSAzIDIgNCA2IDUgMyAyIDUgN10gICAgICAgICAgICAgICAgICAgICAtPiBmYWxzZQpbMSA1IDEwIDE5IDE1IDEzIDggMTMgMTggMjMgMTkgMTggMTRdICAgICAgIC0%2bIHRydWUKWzE1IDE0IDE3IDE2IDE5IDE4XSAgICAgICAgICAgICAgICAgICAgICAgICAtPiB0cnVlClsxMiAxNiAxOSAxNSAxOCAxOV0gICAgICAgICAgICAgICAgICAgICAgICAgLT4gZmFsc2UKXS1tUg) ``` äÎòÎmÊäÎd :Implicit input of array > [0,3,7,5,2,3,6] ä :Consecutive pairs > [[0,3],[3,7],[7,5],[5,2],[2,3],[3,6]] Î : Reduced by the sign of their differences (1 or -1) > [-1,-1,1,1,-1,-1] ò :Partition between elements that return true (not zero) Î : Get the sign of their difference > [[-1,-1],[1,1],[-1,-1]] m :Map Ê : Length > [2,2,2] ä :Consecutive pairs > [[2,2],[2,2]] Î : Reduced by the sign of their differences > [0,0] d :Any truthy? > false ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` Λ≡gẊo±- ``` [Try it online!](https://tio.run/##yygtzv7//9zsR50L0x/u6so/tFH3////0QY6xjrmOqY6RkDaLBYA "Husk – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ¯±Ġȧ≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwixpsiLCLCr8KxxKDIp+KJiCIsIjtaxptgID0+IGBqO+KBiyIsIltbMSwgMywgNSwgOCwgNiwgNCwgMiwgMywgNSwgNywgNiwgNCwgMiwgNSwgNywgOSwgNiwgNCwgMl0sIFsxLCAzLCA1LCA3LCA2LCA0LCA1LCA3LCA5LCA4LCA2LCA0LCAyLCAzLCA1XSwgWzIsIDMsIDYsIDQsIDIsIDMsIDcsIDUsIDMsIDQsIDZdLCBbMywgNiwgNCwgOCwgNSwgNywgMywgNSwgMl0sIFs4XSwgWzEsIDMsIDUsIDddLCBbNCwgNSwgNywgNiwgOCwgOV0sIFsxLCA1LCAxMCwgMTksIDE1LCAxMywgOCwgMTMsIDE4LCAyMywgMTksIDE4LCAxNF0sIFsxNSwgMTQsIDE3LCAxNiwgMTksIDE4XSwgWzEyLCAxNiwgMTksIDE1LCAxOCwgMTldXSJd) Port of Jelly answer. ## How? ``` ¯±Ġȧ≈ ¯ # Get the deltas (consecutive differences) of input ± # Get the sign (implicit vectorization) Ġ # Group consecutive identical items ȧ # Absolute value (implicit double-vectorization) ≈ # All equal? ``` [Answer] # [Factor](https://factorcode.org/), 49 bytes ``` [ [ trends check-lengths t ] [ tuple? ] recover ] ``` [Try it online!](https://tio.run/##dZHBTsMwEETv/YrhAxqJNrQBJHor4sIFOFU9RGZpLZy1sTdIqOq3BzsOUCK4Pc3Ojkfrl1qJ9d3Tw9397RWCM1pE865oLFuxrBWUbZw25AvxRIXak3olH1WOvrYWbTkgKkwGzpPIh/OaBYHeWmJFAdeTw@SAc8xxgQoLlJj1vBw40eXAR5xheoNH39L3TvZl1@n@4F3XJiRzEr@GyzieR16MArOj6sNSxPjB6p8Cv9VyKFXFQqMSP@3KP8JTqVlfK9NJdA44dhtsEA/NzwH9qaeGeCf7AME2jVpnaBXRk7Lv8R@2XVM7FFCGat99Ag "Factor – Try It Online") There is a lot to unpack here. First, Factor (nearly!) has the perfect word for this problem, `trends`, which splits a sequence into its rising, falling, and stable parts. This question guarantees no two adjacent elements will be equal, so we don't need to worry about receiving any stable trends in the result. The problem is, for some unfathomable reason, if the sequence has only one trend, `trends` returns a single trend object instead of a sequence with a single trend object in it. Thus when we attempt to see if the lengths of the trends are all equal, we'll get an error that `length` can't be applied to a non-sequence if there is only a single trend. Next, instead of saying something like `[ length ] map all-eq?`, Factor has a word in its (exposed) compiler named `check-lengths` that throws an error if the lengths of a sequence are not all equal. So `check-lengths` is capable of failing in two different ways: either it'll end up calling `length` on a non-sequence, or it'll throw an error if the lengths of its input are not all the same. Enter `recover`, one of Factor's exception handling words. It calls the first quotation (which will simply return `t` if no errors are encountered) and calls the second quotation with the error on top of the stack if the first quotation encounters an error. Inside this quotation, all we need to do is check whether the error is a tuple or not, because calling `length` on a non-sequence produces an actual error tuple while `check-lengths` throws a simple string error if the lengths are unequal. ]
[Question] [ ### Intro We have had [histograms](https://codegolf.stackexchange.com/questions/48216/n-gram-histogram) and [counting](https://codegolf.stackexchange.com/questions/45257/counting-k-mers), but not listing all of them. Every year, [Dyalog Ltd.](http://www.dyalog.com/) holds a student competition. [The challenge there](http://www.dyalog.com/student-competition.htm) is to write *good* APL code. This is a language agnostic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") edition of this year's sixth problem. I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the [provided link](http://www.dyalog.com/student-competition.htm) and contacting the author. ### Problem The term k-mer typically refers to all the possible substrings of length *k* that are contained in a string. In computational genomics, k-mers refer to all the possible subsequences (of length *k*) from a read obtained through DNA Sequencing. Write a function/program that takes a string and *k* (the substring length) and returns/outputs a vector of the k-mers of the original string. ### Examples `[4,"ATCGAAGGTCGT"]` → `["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]` *k* > string length? Return nothing/any empty result: `[4,"AC"]` → `[]` or `""` or `[""]` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṡ ``` Jelly has a single byte dyadic atom for this very operation **[Try it online!](https://tio.run/nexus/jelly#@/9w58L/h5dH/v@v5Bji7O7o6O4OpEKU/psAAA "Jelly – TIO Nexus")** (the footer splits the resulting list with newlines, to avoid a mushed representation being printed.) [Answer] # Octave, 28 bytes ``` @(N,s)s((1:N)+(0:nnz(s)-N)') ``` [Try it online!](https://tio.run/nexus/octave#@@@g4adTrFmsoWFo5aeprWFglZdXpVGsqeunqa75nysxr1jDREfJMcTZ3dHR3R1IhShpcv0HAA "Octave – TIO Nexus") For k > string length works in Octave 4.2.1-windows but in tio (Octave 4.0.3) doesn't work. Creates numeric indexes of consecutive elements and index the string by it. ``` s= "ATCGAAGGTCGT" N = 4 idx = (1:N)+(0:nnz(s)-N)' = 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 6 7 8 9 7 8 9 10 8 9 10 11 9 10 11 12 s(idx) = ATCG TCGA CGAA GAAG AAGG AGGT GGTC GTCG TCGT ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes Code: ``` Œù ``` Explanation: ``` Œ # Get all substrings of the input ù # Only keep the substrings of length the second input ``` Uses the [**05AB1E** encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md). [Try it online!](https://tio.run/nexus/05ab1e#@3900uGd//87Ojm7uLq5cxkDAA "05AB1E – TIO Nexus") [Answer] # C (GCC on POSIX), ~~67~~ ~~66~~ 63 bytes *-3 bytes thanks to @LeakyNun!* ``` f(i,s,j)char*s;{for(;j+i<=strlen(s);puts(""))write(1,s+j++,i);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@mkalTrJOlmZyRWKRVbF2dll@kYZ2lnWljW1xSlJOap1GsaV1QWlKsoaSkqVlelFmSqmGoU6ydpa2tk6lpXfs/NzEzTyNZpwxigFYZ0ASNxJL8TI2yaMNYTZ2yaKNYkLL/Jv8dQ5zdHR3d3YFUCAA "C (gcc) – TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), ~~47 45~~ 42 bytes -3 bytes thanks to ovs (use Python 3's unpacking to reuse `a[n-1:]` at the tail.) ``` f=lambda a,n:a[n-1:]and[a[:n],*f(a[1:],n)] ``` A recursive function taking the string, `a`, and the slice length, `n`, and returning a list of the slices or an empty string. `a[n-1:]` takes a slice of the current string from the n-1th (0-indexed) element onward to test whether there are enough elements remaining (an empty string is falsey in Python) - this is shorter than the equivalent `len(a)>=n`. * If there are enough elements a list is constructed, `[...]`, with the first `n` elements of the string, `a[:n]`, and the unpacked result of calling the function again, `*f(...)`, with a dequeued version of the current input (without the first element), `a[1:]`. * If there are not enough elements the tail of the recursion is reached when `a[n-1:]` is returned (in this case an empty string). **[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCok2eVGJ2na2gVm5iXEp0YbZUXq6OVppEYDRTRydOM/V9QlJlXopGmoeSRmpOT71KZmJOfrqRjrKn5HwA)** --- **45** for Python 2 or 3 with: ``` f=lambda a,n:a[n-1:]and[a[:n]]+f(a[1:],n)or[] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` s₎ᶠ ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/8qKnv4bYF//9HKzmGOLs7Orq7A6kQJR2T2P9RAA "Brachylog – TIO Nexus") ## Specs: * Input: `["ATCGAAGGTCGT",4]` * Argument: `Z` * Output: `Z = ["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]` ## How it works ``` s₎ᶠ s Output is a substring of first element of input, ₎ with length specified by second element of input. ᶠ Find all solutions. ``` [Answer] # [J](http://jsoftware.com/), 2 bytes ``` ,\ ``` It is not a complete program, but a function with an operator. Call it as such: ``` echo 4 ,\ 'ATCGAAGGTCGT' ``` [Try it online!](https://tio.run/nexus/j#@5@anJGvYKKgE6Og7hji7O7o6O4OpELU//8HAA) ## How it works The operator (called "conjunction") `\` (named "[infix](http://code.jsoftware.com/wiki/Vocabulary/bslash#dyadic)") is used as such: > > `(x u\ y)` applies verb `u` to successive parts of list `y` (called infixes). > > > The function (called "verb") `u` in this case is the function `,` which is a simple "[append](http://code.jsoftware.com/wiki/Vocabulary/comma#dyadic)" function: > > Creates an array containing the items of `x` followed by the items of `y`. > > > [Answer] # Mathematica, 21 bytes ``` ##~StringPartition~1& ``` Anonymous function. Takes a string and a number (in that order) as input and returns a list of strings as output. [Answer] # R, ~~65~~ 61 bytes *-2 bytes thanks to MickyT* *-2 bytes by changing the indexing* returns an anonymous function. ``` function(s,n,x=nchar(s))`if`(n>x,'',substring(s,x:n-n+1,n:x)) ``` `substring` cycles through the indices (as opposed to `substr` which does not), and if the starting index is less than 1, it defaults to `1` instead, so it checks and returns the empty string. `x:n-n+1` is equivalent to `1:(x-n+1)` since `:` takes precedence over sums/differences [Try it online!](https://tio.run/nexus/r#Fco7CoAwDADQ4yTBOAhOQj1LP5raJUJjobevdHrLEzekafrKq2is3J2mJ1Q0Il/Eo56dAdhatK8WzTMdfdVlmxINQQgxXbdk4J3GDw) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 2 bytes ``` .: ``` It is not a complete program, but a built-in function. Call it as such: ``` .:"ATCGAAGGTCGT"4 ``` [Try it online!](http://pyth.herokuapp.com/?code=.%3A%22ATCGAAGGTCGT%224&debug=0) Full program: ``` .:.* ``` [Try it online!](http://pyth.herokuapp.com/?code=.%3A.%2a&input=%22ATCGAAGGTCGT%22%2C4&debug=0) (The `.*` is splat.) [Answer] # [Jellyfish](https://github.com/iatorm/jellyfish), 7 bytes ``` p _I \i ``` [Try it online!](https://tio.run/nexus/jellyfish#@1/AFe/JFZP5/79jiLO7o6O7O5AK4TIBAA "Jellyfish – TIO Nexus") ## How it works In linear: `p(\(I,i))`, where `p` is print and `\` gets the required substrings. `I` is the raw first input while `i` is the evaluated second input. In Jellyfish, every function and operator gets two arguments, one from the right, and one from the bottom. Here, the function `p` gets the argument from the output of `_`, which is required if we are to use the operator `\` to get substrings. [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` lambda x,n:map(''.join,zip(*[x[b:]for b in range(n)])) ``` [Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqFChk2eVm1igoa6ul5WfmadTlVmgoRVdEZ1kFZuWX6SQpJCZp1CUmJeeqpGnGaup@b@gKDOvRCFNQ8nRydnF1c3dQ0lHwUTzPwA "Python 2 – TIO Nexus") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 92 bytes ``` void f(String s,int n){for(int i=n;i<=s.length();)System.out.println(s.substring(i-n,i++));} ``` [Try it online!](https://tio.run/nexus/java-openjdk#LY6xDoJAEERr@YoL1W3Eq@xOCmJBZQWdsQAE3ORYCLtoDOHb8USrN83Mm2EqHVaqcgWzuhRI8/rs8a4ancmI1CqOkEQRzE0/6m/EmCyeYjauplYeGixkb5a6M/0kZvAlcaTZ8FTyNqHxQBHu9wB2WYefj6UQj03Veevfdr2pYmwZ5mBH9Wv7o8E0Okzyc5okaeqRh9ERbLAEy/oB "Java (OpenJDK 8) – TIO Nexus") [Answer] ## Clojure, 19 bytes Well [this](https://clojuredocs.org/clojure.core/partition) is handy: ``` #(partition % 1 %2) ``` Examples: ``` (def f #(partition % 1 %2)) (println [(f 4 "ATCGAAGGTCGT") (f 4 "abc")]) [((A T C G) (T C G A) (C G A A) (G A A G) (A A G G) (A G G T) (G G T C) (G T C G) (T C G T)) ()] ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` {ew} ``` Anonymous block that expects the arguments on the stack and leaves the result on the stack after. [Try it online!](https://tio.run/nexus/cjam#K6z7X51aXvu/ruC/iYKSY4izu6OjuzuQClECAA "CJam – TIO Nexus") `ew` is a built-in that does exactly what is required. [Answer] # [Retina](https://github.com/m-ender/retina), ~~41~~ 38 bytes ``` .*$ $* !&`(.)+(?=.*¶(?<-1>.)+(?(1)¶)$) ``` [Try it online!](https://tio.run/nexus/retina#@6@npcKlosWlqJagoaeprWFvq6d1aJuGvY2uoR2Yr2GoeWibporm//@OIc7ujo7u7kAqhMsEAA "Retina – TIO Nexus") Takes the string and count on separate lines. The first two lines are used to convert the count from decimal to unary, so if unary input is acceptable then the byte count would be reduced to ~~34~~ 31. Edit: Saved 3 bytes thanks to @FryAmTheEggman. Or, if you prefer, a 48-byte version that handles newlines in the string, although that does produce confusing output: ``` .*$ $* !&`(\S|\s)+(?=[\S\s]*¶(?<-1>.)+(?(1)$.)$) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) with Image Package, 29 bytes ``` @(s,n)[im2col(+s, [1 n])' ''] ``` [Try it online!](https://tio.run/nexus/octave#@@@gUayTpxmdmWuUnJ@joV2soxBtqJAXq6muoK4e@z8xr1hDPTEpOSU1LV1dR8FY8z8A "Octave – TIO Nexus") ### Explanation The function `im2col(m,b)` takes a matrix `m`, extracts blocks of size `b` from it, and arranges them as columns. By default blocks are sliding (as opposed to distinct). Here the matrix `m` is a row vector of the ASCII codes of the input string `s` (this is done as `+s`, which is shorter than the standard `double(s)`), and the size `b` is `[1 n]` to obtain horizontally sliding blocks of `n` elements. The result is transposed (using complex-conjugate transpose `'`, which is shorter than transpose `.'`) to turn the columns into rows, and then it is converted back to char (`[... '']`, which is shorter than the standard `char(...)`). [Answer] # oK, 2 bytes ``` ': ``` oK has a [sliding window](https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual.md#window) operator! [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` f=lambda a,n:[a[i:i+n]for i in range(len(a)-n+1)] ``` [Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCok2cVnRidaZWpnRebll@kkKmQmadQlJiXnqqRk5qnkaipm6dtqBn7v6AoM69EI01DySM1JyffpTIxJz9dScdYU/P/fwA "Python 3 – TIO Nexus") A non-recursive solution, albeit not shorter. Compatible with Python 2. [Answer] # PHP, 75 Bytes [Online Version](http://sandbox.onlinephpfunctions.com/code/41ec5bfef257284cf51c44b118c18f73b0449e10) ``` for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[]=substr($s,$i++,$n);print_r($r); ``` 80 Bytes without double values ``` for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[$p=substr($s,$i++,$n)]=$p;print_r($r); ``` [Answer] ## Haskell, 39 bytes ``` n#s|length s<n=[]|1<2=take n s:n#tail s ``` Usage example: `4 # "ABCDEF"` -> `["ABCD","BCDE","CDEF"]`. [Try it online!](https://tio.run/nexus/haskell#@5@nXFyTk5qXXpKhUGyTZxsdW2NoY2RbkpidqpCnUGyVp1ySmJmjUPw/NzEzT8FWISWfS0GhoCgzr0RBRcFYQVlBydHJ2cXVzc3D00sJU0rpPwA "Haskell – TIO Nexus") A simple recursion that keeps the first `n` chars of the input string an continues with the tail of the string as long as its length is not less than `n`. [Answer] **Microsoft Sql Server, 199 bytes** ``` create function dbo.f(@s nvarchar(max),@ int)returns table as return with v as(select 2 p,left(@s,@)g where len(@s)>=@ union all select p+1,substring(@s,p,@)from v where len(@s)>p-2+@)select g from v ``` [Check it.](http://rextester.com/NNQ87039) [Answer] **PowerShell, 70 bytes** ``` $b={$c,$s=$args;[regex]::matches($s,"(?=(.{$c}))")|%{''+$_.groups[1]}} ``` [Try it online!](https://tio.run/nexus/powershell#DYtBCsMgEAC/EmSbVSqBQk8JUqQHP@BNRJJg7aWkuC0UUt9uPA0MMxUWtcMqgRTMOdHkckzx58fxNX/WZyQOJBm/KT60rAjBxP@0I54hDClv3ze5iy@lwvYghRIn1PZutDamwTahLbaBQVAOeA9Ld@0gCM9KPQA "PowerShell – TIO Nexus") [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 7 bytes ``` infixes ``` [Try it online!](https://tio.run/nexus/stacked#U3cMcXZ3dHR3B1Ih6gom/zPz0jIrUov/55eW/AcA "Stacked – TIO Nexus") Pretty standard. Without this builtin, it becomes 20 bytes: ``` {%x#'y-#+:>y#-#>x\#} ``` Which is: ``` {%x#'y-#+:>y#-#>x\#} {% } dyad; first arg: x, second arg: y x#' length of x (the array) y- minus y (the skew) #+ plus 1 :> range [x, y] y#- y minus 1 #> range from [[x, y], [x, y] + y] x\# get indices from x ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` YC! ``` [Try it online!](https://tio.run/nexus/matl#@x/prPj/v7pjiLO7o6O7O5AKUecyAQA "MATL – TIO Nexus") ### Explanation ``` YC % Sliding blocks of input string with input size, arranged as columns ! % Transpose ``` [Answer] # C# 89 bytes ``` void a(string s,int n){for(int i=n;i<=s.Length;)Console.WriteLine(s.Substring(i++-n,n));} ``` [Try it online!](https://tio.run/nexus/cs-mono#Lc4xD4IwEAXguf0VDVMbkMmtMhAGFpwgcTAOBSteglfDFRND@O0IwnRveC/fDQTYivJL3r405@@h7qARTWeIRMpHzsgbD838cXAXRpLv1z5FgF6gGh@ul2uEBDWcEooLi61/apU5JNfZ@NKDtwWglRSXQ73tJYThASNUSk8z280NEn/obAB363oTpm9JcbY8w4wM0irL0zTPl1MF0VFpziY@zT8 "C# (Mono) – TIO Nexus") Best method I could find in C# is basically the same as [Java](https://codegolf.stackexchange.com/a/118227/44998) [Answer] # Ruby, ~~48~~ 46 bytes ``` ->(s,k){0.upto(s.size-k).map{|i|s[i..i+k-1]}} ``` No particular tricks, just a stabby-lambda defining a function that pulls the required substring from each valid starting point. Saved two bytes, since there doesn't seem to be a need to store the lambda. [Answer] # [V](https://github.com/DJMcMayhem/V), 16 bytes ``` òÀ|ly0Ïp "_xòkVp ``` Not terribly well golfed I'm afraid, struggling with "delete the string if k > len(str)". Input is in the file, k is an argument. Golfing before explanation [Try it online!](https://tio.run/nexus/v#@3940@GGmpxKg8P9BVxK8RWHN2WHFfz/n5iUnJL63wgA "V – TIO Nexus") [Answer] # Standard ML (mosml), ~~109~~ ~~65~~ 61 bytes ``` fun f(n,x)=if n>length(x)then[]else List.take(x,n)::f(n,tl x) ``` Takes a number and a character list (quite a common alternative to strings in the SML world). (Really works on all lists of course.) Usage: ``` - f(3,explode("ABCDEFGH")); > val it = [[#"A", #"B", #"C"], [#"B", #"C", #"D"], [#"C", #"D", #"E"], [#"D", #"E", #"F"], [#"E", #"F", #"G"], [#"F", #"G", #"H"]] : char list list - f(7, explode("ABCD")); > val it = [] : char list list ``` Changelog: * Right, there is a standard library.. (-44 bytes) * Change comparison and nil to [] as suggested (-4 bytes) [Answer] ## JavaScript (Firefox 30-57), 51 bytes ``` (s,n,t='')=>[for(c of s)if((t+=c)[n-1])t.slice(-n)] ``` 64 bytes in ES6: ``` (s,n,t=s.slice(0,--n))=>[...s.slice(n)].map(c=>(t+=c).slice(~n)) ``` ]
[Question] [ Take a unit circle centered on the origin. In any two neighboring [quadrants](http://en.wikipedia.org/wiki/Quadrant_%28plane_geometry%29), mirror the curve of the circle across the lines connecting the circle's x and y intercepts. With the resulting shape, you can tile the plane: [![circle tessellation](https://i.stack.imgur.com/TmwIX.png)](https://i.stack.imgur.com/TmwIX.png) I made this image with the awesome 2D physics sandbox [Algodoo](http://www.algodoo.com/)! Write a program that outputs an image similar to this one in some common lossless image file format. You may save the image as a file with the name of your choice or you may simply display it. No input should be taken. **Rules:** * The *entire* image must be tessellated with the modified-circle tiles using any two visually distinct RGB colors: one for the vertically pointing tiles, one for the horizontally pointing tiles. * The radius of the circle tiles should be at least 32 pixels. (The radius in the image above is about 110 pixels.) * The image should be at least 4 tiles wide and 4 tiles tall. This, combined with the rule above, means that images can have a minimum size of 256×256 pixels. (The image above is 4 tiles by 4 tiles.) * The tessellation may be translated by any amount. For example, the top left corner of the image does not need to be the vertex where tiles meet. (The tessellation should not be rotated, however.) * You may use external graphics libraries that have commands for drawing circles and outputting images and the like. * The curves really should approximate circles, as can done with the [midpoint circle algorithm](http://en.wikipedia.org/wiki/Midpoint_circle_algorithm), which most graphics libraries will do for you. * Anti-aliasing around the edges of the tiles is allowed but not required. **The shortest submission in bytes wins.** [Answer] # POV-Ray, ~~199~~ 163 ``` Old version camera{location -9*z}light_source{-9*z}#declare L=union{#for(X,-9,9,2)#for(Y,-9,9,2)cylinder{X*x+x+Y*y,<.001*pow(-1,(X+Y)/2),0,.1>+X*x+x+Y*y,1}#end#end}object{L pigment{color x}}object{L rotate z*90} Same output, but golfed down further by using default light/camera, so I dont even need to specify them #declare L=union{#for(X,-9,9,2)#for(Y,-9,9,2)cylinder{<X+1,Y,9>,<.001*pow(-1,(X+Y)/2),0,.1>+<X+1,Y,9>,1}#end#end}object{L pigment{color rgb x}rotate z*90}object{L} ``` ![enter image description here](https://i.stack.imgur.com/5mkX9.png) I am using as many default parameters for camera and lightsource as possible, thats why it is a little dark. Lets ungolf it first ``` camera{location 9*z look_at 0} light_source{9*z color 1} #declare L=union{ #for(X,-9,9,2) #for(Y,-9,9,2) cylinder{<1+X,Y,0>, //central axis, start <1+X,Y,0> + <.001*pow(-1,(X+Y)/2), 0, .1>, //central axis, end 1} //radius #end #end } object{L pigment{color x}} // x is the <1,0,0> vector, here interpreted as RGB object{L rotate<0,0,90>} ``` It is obvious what is happening once we increase the offset of the cylinder axis and change the perspective ![enter image description here](https://i.stack.imgur.com/x7kqK.png) [Answer] # Gnuplot, 182 I noticed that the boundaries between the cells look very sinusoidal, so i went for an analytical solution with a very simple core equation ![enter image description here](https://i.stack.imgur.com/K0eXz.png) ``` set view map set isosamples 900 f(x,y)=.3*sin(x*3.14)+y splot(ceil(f(x,y))+ceil(f(y,x)))%2?1:NaN #can only modulo integers ``` ![enter image description here](https://i.stack.imgur.com/1fI7a.jpg) While it looks similar, the circles are way too square. With the same idea, I replace `sin` by a curve made from concatenated quartercircle-arcs and rotate it 45° by replacing `x` and `y` with `x+y` and `x-y` ``` set view map set samples 800 set isosamples 800 d=.5**.5 c(x,k)=(-1)**k*sqrt(1-(x-d*(1+2*k))**2)-(-1)**k*d # k-th circle arc # s(x)=c(x,floor(x/d/2)) # circlified sinus # f(x,y)=d*s(x/d)+y f(x,y)=d*c(x/d,floor(x))+y # combined commented functions splot(ceil(f(x+y,x-y))+ceil(f(x-y,x+y)))%2?1:NaN ``` ![enter image description here](https://i.stack.imgur.com/vThnp.jpg) [Answer] ## Context Free, 99 bytes ``` startshape d CF::Tile=[s 4]CF::Symmetry=CF::pmg,0,1,0path d{ARCTO(-1,1,1)ARCTO(1,1,-1)ARCTO(0,0,1)} ``` You can see the result at the [Context Free Gallery](http://www.contextfreeart.org/gallery/view.php?id=3571). [Answer] # HTML+JavaScript, 277 ``` <canvas id=C></canvas><script>r=50,C.width=C.height=9*r,T=C.getContext('2d'); for(f=1,P=Math.PI,i=0;i<45;f=-f,i+=i&7?1:2)x=2*r*(i%8-2),y=2*r*(i>>3),T.moveTo(x,y+f*r), T.arc(x+r,y+f*r,r,P,-f*P/2,f<0),T.arc(x,y,r,0,P,f>0),T.arc(x-r,y+f*r,r,-f*P/2,0,f<0); T.fill()</script> ``` To test, save as html file and open with a browser. Or else, run the snippet ``` r=50,C.width=C.height=9*r,T=C.getContext('2d') for(f=1,P=Math.PI,i=0;i<45;f=-f,i+=i&7?1:2) x=2*r*(i%8-2),y=2*r*(i>>3), T.moveTo(x,y+f*r), T.arc(x+r,y+f*r,r,P,-f*P/2,f<0), T.arc(x,y,r,0,P,f>0), T.arc(x-r,y+f*r,r,-f*P/2,0,f<0) T.fill() ``` ``` <canvas id=C></canvas> ``` Due to popular demand, here is the output image. Not so exciting after all... ![Tiles](https://i.stack.imgur.com/o4me7.png) [Answer] # IDL 8.3, ~~201~~ ~~193~~ 183 bytes The image is output into an IDL graphics window; I took a screenshot, below. EDIT: thanks to @AlexA. and @Sp3000 for helping me shave some bytes ``` p=!pi/99*[0:99] q=p[49:0:-1] o=p[99:50:-1] window,xs=(ys=400) for i=0,24 do cgpolygon,i mod 5*100+50*[cos(p),cos(q)-1,cos(o)+1],i/5*100+(-1)^i*50*[sin(p),sin(q)-1,sin(o)-1],/d,/fi end ``` ![enter image description here](https://i.stack.imgur.com/MB1Vo.png) [Answer] # Mathematica: 86 bytes (or 82 bytes) Thanks to the infinite [@alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha) for a clever array-based method: ``` Image@ArrayFlatten@Array[DiskMatrix@32~RotateLeft~32/.a_/;OddQ@+##:>1-Thread@a&,{5,5}] ``` Inside the array is an anonymous function, which uses a clever trick to add its arguments (`+##`) and determine whether the sum is odd. That boolean is used as the conditional to a pattern that replaces the whole 'white' tile with the transformed, 'black' tile. From there, `ArrayFlatten` joins together the tiles and `Image` displays them. Note the use of the shorter `Thread` to replace `Transpose`. We can still save 4 bytes by using the transpose symbol instead. ## Previous: 97 bytes (or 90 bytes) ``` Image@ArrayFlatten@Partition[ Join@@Table[{#,1-Transpose@#}&@RotateLeft[DiskMatrix@32,32],{13}],5] ``` You can reduce the number of bytes by replacing `Transpose@#` with the superscript-t symbol (codepoint U+F3C7, shortcut `ESC``tr``ESC`). In UTF-8 that brings the total to [90 bytes in 88 characters](https://mothereff.in/byte-counter#Image@ArrayFlatten@Partition[Join@@Table[%7B#,1-#%EF%8F%87%7D&@RotateLeft[DiskMatrix@32,32],%7B13%7D],5]). ![enter image description here](https://i.stack.imgur.com/Zm1Vu.png) We start with `DiskMatrix`, which generates a binary matrix: ``` DiskMatrix@32 // Image ``` ![enter image description here](https://i.stack.imgur.com/FoFTs.png) We then circular-shift the rows of the matrix to produce the unit cell for the tiling: ``` RotateLeft[DiskMatrix@32, 32] // Image ``` ![enter image description here](https://i.stack.imgur.com/tikfp.png) If the plane is a chessboard, these are the 'white' squares. For the 'black' squares, we need to invert the colors and rotate by 90 degrees. We can invert by subtracting from 1 (`1 - 1 -> 0` and `1 - 0 -> 1`), and rotate by taking the transpose: ``` Image /@ {#, 1 - Transpose@#} &@RotateLeft[DiskMatrix@32, 32] ``` ![enter image description here](https://i.stack.imgur.com/N0Nzv.png) If the dimensions of the image are even (like the minimum size, 4), then a tile on the right edge will be the same as the next one on the left edge. However, adding one tile to get an odd size (5) then concatenating the rows produces a regular alternating pattern. This suggests that we can get the full image by wrapping a single row of alternating tiles with `Partition`. We use `Table` to make a list of `13` black/white tile pairs, and `Join` to flatten the list of pairs to a list of 26 tiles. Then we `Partition` the list into a `5` by `5` matrix of tiles (`Partition` discards the trailing 26th tile): ``` Map[Image] /@ Partition[ Join @@ Table[{#, 1 - #\[Transpose]} &@ RotateLeft[DiskMatrix@32, 32], {13}], 5] // MatrixForm ``` ![enter image description here](https://i.stack.imgur.com/T7KaA.png) Finally `ArrayFlatten` turns the matrix of tile matrices into a flat matrix, and `Image` displays the result. ## Previous: 111 bytes ``` Image[ArrayFlatten[{{#, #}, {#, #}}] &[ Join[#, Reverse@#, 2] &[ Join[1 - Transpose@#, #] &@RotateLeft[DiskMatrix[32], 32]]]] ``` ![enter image description here](https://i.stack.imgur.com/mpsXc.png) [Answer] # gs2, 49 bytes ``` 50 31 05 0d 1f 2a 48 0a 1e 2e 40 83 2c e8 64 2d 1e 73 ed 1e 33 40 20 30 9a a2 22 e8 e9 40 20 30 9a 30 40 20 30 ee 40 20 30 12 32 e9 12 32 55 e8 2b ``` Generates a PBM image: ![output](https://i.stack.imgur.com/b11Ux.png) Mnemonics: ``` # Print header "P1" space 256 double 2dup new-line # Make 1/4 circle 64 range dup cartesian-product square m1 sum sqrt 64 >= m6 64 / # Make tile dup reverse + transpose @2 not m1 m2 dup reverse + transpose + # Make quarter of image dup reverse + z1 dup reverse + # Loop 2 * m2 2 * # Format show-words m1 unlines ``` [Answer] # Java, ~~550~~ ~~540~~ ~~508~~ 504 bytes This is a java applet. ``` import java.awt.*;public class T extends java.applet.Applet{int a=98,b=49,x,y;public void paint(Graphics g){for(x=0;x<5;x++)for(y=0;y<5;y++)a(g.create(x*a,y*a,a,a),x%2^y%2);}void a(Graphics g,int c){if(c>0){g.translate(a,0);((Graphics2D)g).scale(-1,1);}g.setColor(Color.red);g.fillRect(0,0,b,b);g.fillRect(b,b,b,b);g.setColor(Color.blue);g.fillRect(b,0,b,b);g.fillRect(0,b,b,b);g.fillArc(0,-b,a,a,180,90);g.fillArc(0,b,a,a,0,90);g.setColor(Color.red);g.fillArc(-b,0,a,a,0,-90);g.fillArc(b,0,a,a,90,90);}} ``` Expanded with boilerplate: ``` import java.awt.*; public class T extends java.applet.Applet{ int a = 98, b = 49, x, y; //Make these larger for better quality pictures. a = b * 2 public void paint(Graphics g) { for (x=0; x < 5; x++) //Make these larger for more tiles. for (y=0; y < 5; y++) // a(g.create(x * a, y * a, a, a), x % 2 ^ y % 2); } void a(Graphics g, int c) { if (c > 0) { g.translate(a, 0); ((Graphics2D) g).scale(-1, 1); } g.setColor(Color.red); //Change colors for nicer looking colors. g.fillRect(0, 0, b, b); g.fillRect(b, b, b, b); g.setColor(Color.blue); g.fillRect(b, 0, b, b); g.fillRect(0, b, b, b); g.fillArc(0, -b, a, a, 180, 90); g.fillArc(0, b, a, a, 0, 90); g.setColor(Color.red); g.fillArc(-b, 0, a, a, 0, -90); g.fillArc(b, 0, a, a, 90, 90); } } ``` **Applet:** A small application program that can be called up for use while working in another application. Example image: ![enter image description here](https://i.gyazo.com/06cec720b3368bfbcb0623b96e724462.png) **Explanation:** This works by using a method to print each tile. Before the method is created, it is given a graphics object that uses a coordinate system centered on the upper left corner of each tile: ![](https://i.gyazo.com/777ae72d1c19c2b4bad54a9694943b80.png) To create a tile, we use the following method: ``` void a(Graphics g, int c) { g.setColor(Color.red); g.fillRect(0, 0, b, b); g.fillRect(b, b, b, b); g.setColor(Color.blue); g.fillRect(b, 0, b, b); g.fillRect(0, b, b, b); g.fillArc(0, -b, a, a, 180, 90); g.fillArc(0, b, a, a, 0, 90); g.setColor(Color.red); g.fillArc(-b, 0, a, a, 270, 90); g.fillArc(b, 0, a, a, 90, 90); } ``` However, every other tile must be reflected horizontally in order to produce the correct image. To reflect a tile, we simply modify the supplied `graphics` object with this code: ``` g.translate(a, 0); ((Graphics2D) g).scale(-1, 1); ``` Thanks @CoolGuy for 4 bytes. [Answer] # Mathematica ~~299~~ 256 Wordy but it was nice to figure out. The basic tile is r (shown below),which is a region displayed by RegionPlot. A left-right reflection of the tile is made and joined with r. The two tile assembled figure is then repeated to tile the space. ![r](https://i.stack.imgur.com/bPE4h.png) ``` a_~f~b_ := (x + a)^2 + (y + b)^2 <= 1; a = ImageAssemble; r = RegionPlot[(0~f~0 && y <= 0 && ! f[-1, 1]) \[Or] (0~f~2 && y >= -2 && ! f[1, 1]), {x, -1, 1}, {y, -2, 0}, Frame -> False, BoundaryStyle -> None]; s = ImageCrop@Rasterize@r; t = s~ImageReflect~Right; i = a@{s, t}; j = a@{t, s}; a@{k = {i, i, i, i}, m = {j, j, j, j}, k, m, k, m} ``` ![tile](https://i.stack.imgur.com/7VWmq.png) [Answer] ## C, ~~237~~ ~~209~~ 180 bytes 180 bytes. This version includes changes suggested by edc65 in a comment. It gives 9 compiler warnings when building on a Mac with clang and default options: ``` a,b,c,d,x,y;main(){for(puts("P1 256 256");b=a+32&64,a<256;++a){for(c=0;d=c+32&64,x=(a&64)-d?31-a&31:a&31,y=(c&64)-b?c&31:31-c&31,c++<256;)putchar(48+(x*x+y*y<962^b==d));puts("");}} ``` 209 bytes, using some suggestions from comments by Martin. Compiles without warnings with clang: ``` #include <stdio.h> int a,b,c,d,x,y;int main(){puts("P1 256 256");for(;b=a+32&64,a<256;++a){for(c=0;d=c+32&64,x=(a&64)-d?31-a&31:a&31,y=(c&64)-b?c&31:31-c&31,c<256;++c)putchar(48+(x*x+y*y<962^b==d));puts("");}} ``` Original version, 237 bytes: ``` #include <stdio.h> int main(){puts("P1 256 256");for(int a=0;a<256;++a){int b=a+32&64;for(int c=0;c<256;++c){int d=c+32&64;int x=(a&64)-d?31-a&31:a&31;int y=(c&64)-b?c&31:31-c&31;putchar(48+(x*x+y*y<962^b==d));}puts("");}} ``` Result (256x256): ![enter image description here](https://i.stack.imgur.com/dDDT2.png) Original code with whitespace for better readability: ``` #include <stdio.h> int main() { puts("P1 256 256"); for (int a = 0; a < 256; ++a) { int b = a + 32 & 64; for (int c = 0; c < 256; ++c) { int d = c + 32 & 64; int x = (a & 64) - d ? 31 - a & 31 : a & 31; int y = (c & 64) - b ? c & 31 : 31 - c & 31; putchar(48 + (x * x + y * y < 962 ^ b == d)); } puts(""); } } ``` This does not use any graphics library, the rendering is completely contained in the code. The basic idea is to simply loop over all 256x256 pixels, and see if they are inside/outside the circular arc of the 32x32 sub-square they are in. The bottom 5 bits of the overall pixel coordinates define the relative coordinates of the pixel within the sub-square. The inside/outside test of `(x, y)` being inside the arc with radius `r` is then the standard: ``` x * x + y * y < r * r ``` Most of the logic is for placing the center of the arc in the correct corner of the sub-square, and determining which color is inside/outside. Some comments on the solution: * The code generates the image in the PBM ASCII format. I loaded the result into GIMP, and did a copy&paste into Paint to generate the actual file I posted here. So the format was converted, but the content is exactly as the original output. * If you look closely, you may notice that the quality is not great. This is because the inside/outside calculation is done for the corner of the pixel, instead of the pixel center, causing the whole thing to be 1/2 pixel off. I don't think it would be very difficult to do better, but it would make the code somewhat longer. And since there were not specific quality requirements, I believe this is sufficient. * Code was compiled using clang on a Mac. Latest version gives warnings, initial version did not. * This is the first time I ever attempted one of these, so I probably missed a few tricks to save the last byte possible. ]
[Question] [ This was inspired by [this question](https://codegolf.stackexchange.com/questions/235446/neural-processing-lattice-checker). Given an \$m\times n\$ matrix of \$0\$'s and \$1\$'s, apply "gravity" to it. This means to drop down all the \$1\$'s as if they were affected by gravity. For example ``` [[1,0,1,1,0,1,0] [0,0,0,1,0,0,0] [1,0,1,1,1,1,1] [0,1,1,0,1,1,0] [1,1,0,1,0,0,1]] ``` Should result in ``` [[0,0,0,0,0,0,0] [0,0,0,1,0,0,0] [1,0,1,1,0,1,0] [1,1,1,1,1,1,1] [1,1,1,1,1,1,1]] ``` As all \$1\$'s have been dropped down. ## input Input will be atleast \$1\times 1\$. You may take input in all reasonable forms (Bitsets, arrays, Lists) and either output the result, return a new Bitset, array or list or simply modify the input. This is code golf, so the answer with the fewest bytes wins! ## test-cases More test-cases: ``` [[1,0] [[0,0] [0,0] -> [1,0] [1,0]] [1,0]] [[1,1,1,1,1] [[1,0,1,1,0] [1,0,1,1,0] -> [1,1,1,1,0] [1,1,1,1,0]] [1,1,1,1,1]] [[1]] -> [[1]] ``` The brackets are just there to visualize arrays, they are *not* required in your output! [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Transposes, sorts each row and automatically transposes back. ``` yn ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=eW4&input=W1sxLDAsMSwxLDAsMSwwXQogWzAsMCwwLDEsMCwwLDBdCiBbMSwwLDEsMSwxLDEsMV0KIFswLDEsMSwwLDEsMSwwXQogWzEsMSwwLDEsMCwwLDFdXQotUg) ## [Japt](https://github.com/ETHproductions/japt), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Transpose, sort rows, transpose. ``` yÍy ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ec15&input=W1sxLDAsMSwxLDAsMSwwXQogWzAsMCwwLDEsMCwwLDBdCiBbMSwwLDEsMSwxLDEsMV0KIFswLDEsMSwwLDEsMSwwXQogWzEsMSwwLDEsMCwwLDFdXQotUg) [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` import Data.List t=transpose t.map sort.t ``` [Try it online!](https://tio.run/##Rcs9CsQgEAXg3lNMkXIQPYDdlskJJMUUkZWNRpy5v/kRszwYeMP3vsS/bd9bi6kcVeBDQnqOLEqcVMpcDt5UcKITFeCLaGmJYnZXX6DUmGUKCjx4iwYt9mtWBQjeoOn1Tn8N9WSoMbN/Zd/hrdZ2Ag "Haskell – Try It Online") This is the same boring answer you've already seen in this thread. Unfortunately it's quite short. Here's a fun answer that doesn't import anything: # No imports, ~~53~~ 49 bytes ``` q=foldr.zipWith e=[]:e q(:)e.q([(0:),(++[1])]!!)e ``` [Try it online!](https://tio.run/##RYtBCsMgFET3nsJAFko@QbeCR@i6i89fCFEiNammWfXyllRsGRiY4b3VvR4@pVqLDc@0HPM75ns8V@YtkvEs2CKM9HMRKJSRIKYJNUkaBunr5uJuN5dvPB9xP8fAOHLUoEBDa0WMA0cFqs0r7erUN53qmv5T@ideFNUP "Haskell – Try It Online") This answer is a little odd. # Explanation Let's first solve an easier problem. Instead of having gravity acting down it will act to the right. Here each row acts independently so we can just solve it on 1 row and map it across the whole thing. We start by making a function ``` 0#x=0:x 1#x=x++[1] ``` This takes a list and a value, adds it to the front if it is `0` and the end if it's `1`. This will always insert new values to the proper place in the row, so to build the row we can just do: ``` foldr(#)[] ``` and to make the complete thing we just add the `map` ``` f=map$foldr(#)[] ``` --- Ok, now we want to solve the original problem. How can we make this act on the columns? The idea is to use `zipWith`. `zipWith` acts independently on the columns of two lists to combine them. So `zipWith(#)` will take a list of columns and a list of values and add each value to the corresponding column. To do this repeatedly we use `foldr` ``` e=[]:e foldr(zipWith(#))e ``` The issue however arises that because we are treating the columns as lists the output is transposed. So we need to transpose it back. If we take a look at the short way to transpose in Haskell [here](https://codegolf.stackexchange.com/a/111362/56656) ``` e=[]:e foldr(zipWith(:))e ``` we instantly notice that this is extremely similar to the code we have already written, so we can abstract it. When we do that and add in our transpose we get nearly the final answer ``` 0#x=0:x 1#x=x++[1] q=foldr.zipWith e=[]:e f=q(:)e.q(#)e ``` The last change is that we can express our original function `(#)` in pointfree as `([(0:),(++[1])]!!)` and substitute it where `(#)` goes. ``` q=foldr.zipWith e=[]:e f=q(:)e.q([(0:),(++[1])]!!)e ``` [Answer] # [R](https://www.r-project.org/), 26 bytes Or **[R](https://www.r-project.org/)>=4.1, 19 bytes** by replacing the word `function` with `\`. ``` function(m)apply(m,2,sort) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jVzOxoCCnUiNXx0inOL@oRPN/mkZuYklRZoVGsoahjoGOoQ6ENNDhUjDQMYCyDcB8mDwEguRhqg2h8oZw9YaaOqY6OiGamlxoFkCN1NQxxiKNgMhmG2LXABTW1PwPAA "R – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~80 79 73~~ 64 bytes ``` i;f(*a,w,h){for(i=w;i<w*h;)i=a[i-w]>a[i]?a[i-w]---a[i]+++w:i+1;} ``` [Try it online!](https://tio.run/##pZHRCsIgFIbv9xQiBDoV2qKb3OpBwgtZrITaYhUuYs@@jtuKWtSizkF@f/38vTiJSLY6W9e1kSnxNbd8Qy9pXhATW2ki628kNbFeGmHVHEQt2r0QwjnGmJ0ZFsiqNtkR7bTJCEUXD0G5A71UKO68qzH/3MFAvw3qg0P3L0H9h9/6p6Ab8Is@BAX8j9XkVLKRlGg@CfmUdjYvEHFjOcNQxhIkQlMQxujDjO5U2VIlUJMQFLA75GpfAJUSPFohzGHUJWIQ6QOsug8b6nQ8EIy7k8qr6is) This is essentially a strided sort looped over all columns except instead of swapping out of order elements, ~~both elements are xor'ed by one~~ out of order elements are decremented and incremented until they are in order. Thanks to @jdt for the -9! Slightly less golfed ``` x,*u; f(*a,w,h){ for(x=w*h*--h;x--;) w[u=a+x%h*w-x/h/~h]<*u? u[w]^=1, *u^=1 : 0; } ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 [bytes](https://github.com/abrudz/SBCS) ``` ∧⍤1⍢⍉ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HH8ke9Swwf9S561Nv5P@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/69QAKpRMFUwV3jUu0XBUMEAiCGkARQaItGGcGiAlQSr46rgUte1U@dKU6gAAA "APL (Dyalog Extended) – Try It Online") Sort `∧` each row `⍤1` while transposed `⍢⍉` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [bytes](https://github.com/abrudz/SBCS) ``` ⊖⍳∘≢∘.≤+⌿ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXtEe9mx91zHjUuQhI6j3qXKL9qGf//7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/L9CAahGwVTBXOFR7xYFQwUDIIaQBlBoiEQbwqEBVhKsjquCS/1R2yR1rjSFCgA "APL (Dyalog Unicode) – Try It Online") `+⌿` sum of each column `⍳∘≢` indices from 1 to the number of rows `∘.≤` `≤`-table between these two vectors `⊖` vertically reverse the resulting matrix [Answer] # [Python 3](https://docs.python.org/3/), 34 bytes ``` lambda a:zip(*map(sorted,zip(*a))) ``` [Try it online!](https://tio.run/##PY3BCsMgEETvfsUe3bAHl94C@RLrYUsiFRIV66X9eUNMEwYGZnjD5G99p/hofnq2VbbXLCDjL2Q9bJL1J5W6zNSzIGLzqcAa4gIhgtfKWiZDTKcbRwqsIXOmQ725mK4/c234ZvhesXMKR8glxKqPN2w7 "Python 3 – Try It Online") *-3 bytes thanks to pxeger* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ÞTvsÞT ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%9ETvs%C3%9ET&inputs=%5B%5B1%2C0%2C1%2C1%2C0%2C1%2C0%5D%2C%5B0%2C0%2C0%2C1%2C0%2C0%2C0%5D%2C%5B1%2C0%2C1%2C1%2C1%2C1%2C1%5D%2C%5B0%2C1%2C1%2C0%2C1%2C1%2C0%5D%2C%5B1%2C1%2C0%2C1%2C0%2C0%2C1%5D%5D&header=&footer=) There's probably something cleverer / shorter. ``` ÞT # Transpose vs # Sort each ÞT # Transpose ``` [Answer] # MATLAB / [Octave](https://www.gnu.org/software/octave/), 13 bytes ``` @(M)sort(M,1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bw1ezOL@oRMNXx1Dzf5pGtKGOgY6hDoQ0sOZSUFAw0DGA8EAQLAJTA4ZQNTA9hnA1hnBdhrGa/wE "Octave – Try It Online") ### How it works Anonymous function that `sort`s along the `1`st dimension, i.e. vertically. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ZṢ€Z ``` [Try it online!](https://tio.run/##y0rNyan8/z/q4c5Fj5rWRP0/uSDscPv/6GhDHQMdQx0IaRCrE22gYwBhgyCQD5MHQ7A8TLUhVN4Qrt4wNhYA "Jelly – Try It Online") A monadic link which takes a 2d array of booleans. ``` Z # Transpose € # For each Ṣ # Sort Z # Transpose back ``` [Answer] # [Factor](https://factorcode.org/), 34 bytes ``` [ flip [ natural-sort ] map flip ] ``` [Try it online!](https://tio.run/##bZBNDsIgEIX3PcW7gKYkrvQAxo0b46rpAptpQ6SAQBe18ex1tPZHYyYw5M33HoFSFtH6/nw6HPdbBLo1ZAoKCNZHZSo4TzG2zisTcSVvSENZVGTIS63uMiprAnZJ0qGDQMpr2FM8ErCWvkt8@qCN3FAjJxb@kROTlzlWp2vm8DlyAXxn/8sVvxY@9hlKrRwyGBkbfuDq9Q3IUUs3THJGgqqdplWUF01rGM3zwtbOBsKGjc7ptn8C "Factor – Try It Online") Transpose (flip), sort each row, transpose. [Answer] # [Python 3](https://docs.python.org/3/) + [NumPy](https://numpy.org/), 18 bytes ``` lambda a:a.sort(0) ``` [Try it online!](https://tio.run/##RYuxCsMwDER3fYVGG0SQ6VbIl6QZVEpooHaE4w7@eteuccuBdHe805yeR7iUbb6Vl/j7Q1CuMp1HTIZt2b1Wh@HtNaOcGBRAcK5/khglmwUQF0dMjvrllVrFxD029WpQXw1qzNyfcr9ho1YLsBmxoHEPqZryAQ "Python 3 – Try It Online") Input a `np.array`, output by modify it in-place. [Answer] # JavaScript (ES6), 53 bytes Suggested by [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2): counting the number of 1's on each column, using `.filter()`. Returns a matrix of Boolean values. ``` m=>m.map((r,y)=>r.map((_,x)=>!m.filter(r=>!r[x])[y])) ``` [Try it online!](https://tio.run/##XY9RCsMgEET/c4rtn4IVPYAeoRcQKTbVkhJj2KQlOb21DbQ2sCwzDPuYvbunm1rsxvk4pKvPQeWodOTRjYQgW6nSuJkzW4o5RB66fvZIsBg0i6VmtZTmNg1T6j3v040EYhoAA5KBYO/9FQIsqyLBfmIXyXqqqKbtgPIfWK4aSz/lEZSG7Y/TI1480tL4BQ "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 55 bytes Sorting the columns. ``` m=>m.map((r,y)=>r.map((_,x)=>m.map(r=>r[x]).sort()[y])) ``` [Try it online!](https://tio.run/##VY5hCoMwDIX/e4r@bCAr7QHqRUoZxenYsEZSGXr6TjeVCo/wksf3yDt8Qmr4NU63gR5t7myOto4qhlFKxgVszf/ljjMcCa9XN3tQiXiS4BYPkBsaEvWt6ukpO@kqIZwwKDRu8zRaePxFGneZw5xRSe0qqLLNXClzLVypavvsCw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 57 bytes Counting the number of 1's on each column, using `.some()`. Returns a matrix of Boolean values. ``` m=>m.map((r,y)=>r.map((_,x)=>m.some(r=>!m[n+=r[x]],n=y))) ``` [Try it online!](https://tio.run/##VY9dCsIwEITfe4r1LcG1NAfYHMELhCC1pqI0SdmotKev9sfSwrDsMnzDzrP8lKniR/s6hXhzQ02DJ@1zX7ZCMPaSNM/HBTs5Oil6J5j0wZtwJDadtRiol1IOVQwpNi5v4l3UwmQABhRCgeNclwIsTlaBi9R/Wa0ttWhDbdPUnlL7wB@VWTkVYCANc5fz218djx9/AQ "JavaScript (Node.js) – Try It Online") [Answer] # [MY](https://bitbucket.org/zacharyjtaylor/my-language), 11 bytes ``` ⎕⍉86ǵ'ƒ⇹(⍉← ``` [Try it online!](https://tio.run/##y638//9R39RHvZ0WZse3qh@b9Kh9pwaQ96htwv//0dGGOlAYqxNtAKQNQBDIhoiC2LEA "MY – Try It Online") ``` ⎕⍉86ǵ'ƒ⇹(⍉← ⎕ - Input ⍉ - Transpose 86ǵ'ƒ⇹( - Sort each ⍉ - Transpose again ← - Output ``` [Answer] # [RAD](https://bitbucket.org/zacharyjtaylor/rad), 4 bytes ``` ⍉<⍉⍵ ``` [Try it online!](https://tio.run/##K0pM@f//UW@nDRA/6t36//9/DQ1DBSjUVNAwANIGIAhkQ0RBbE0A "RAD – Try It Online") Transpose the input (`⍉⍵`), sort each (`<`), then retranspose `⍉`. [Answer] # [jq](https://stedolan.github.io/jq/), 28 bytes ``` [transpose[]|sort]|transpose ``` [Try it online!](https://tio.run/##yyr8/z@6pCgxr7ggvzg1OramOL@oJLYGLvK/JjexQMOhOEMzOvZ/dLShjoGOoQ6ENIjV4VKINtAxgPBAECwCUwOGUDUwPYZwNYZwXYaxsf/yC0oy8/OK/@sWAQA "jq – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 92 bytes ``` c,x,y,*p;f(*a,w,h){for(x=0;x<w;x++)for(c=y=0;y<h*2;y++)p=a+x+y%h*w,y<h?c+=*p:(*p=y-h>=h-c);} ``` [Try it online!](https://tio.run/##VY9va8MgEIff91NIoOCfC5hBCcy4fZDRF@KwFto0pB1RSr763JmkITvBH/fwcJ62tBfTnlKyECAC75Sj3MAAnj3dradBSxWaQQUhWO6tjkhi4/mbisg6bUQQce/5AEg/rdC8e6e807H0H9qXlqkxndsHuZpzSxl57ghWBubrSPTS56pAQgXzLWHFEuSC5Ba/7Pls7NeI6r9drUOqiY5qCkcN1HBgS3frCc27RdxMKoyGHDDwo5tFVyvMVkCrxkBrdXJ1PUqOFvtvUgB@NxCBEzmpj8tzk/TzuNOiWMi4G9OvdRdzuqdy@AM "C (clang) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes ``` ->l{l.transpose.map(&:sort).transpose} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevpCgxr7ggvzhVLzexQEPNqji/qEQTIVr7v0AhLTo62lDHQMdQB0IaxOpwKUQb6BhAeCAIFoGpAUOoGpgeQ7gaQ7guw9jY2P8A "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø€{ø ``` Similar as some of the other answers. [Try it online](https://tio.run/##yy9OTMpM/f//8I5HTWuqD@/4/z862lDHQMdQB0IaxOpEG@gYQNggCOTD5MEQLA9TbQiVN4SrN4yNBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2l7aLcOl5J/aQlM4P/hHY@a1lQf3vEfJHVom/3/6OhoQx0DHUMdCGkQqxNtoGMAYYMgkA@TB0OwPEy1IVTeEK7eMDZWRwFsJMQgiHaYIMIMdP0QNkRZbGwsAA). **Explanation:** ``` ø # Zip/transpose the (implicit) input-matrix, swapping rows/columns €{ # Sort each inner list ø # Zip/transpose back # (after which the result is output implicitly) ``` [Answer] # JavaScript, 142 Bytes ``` for(j=0,l=a.length,w=a[0].length,c=new Array(l),e=1;j<w;j++){for(i=0;i<l;i++){if(a[i][j]){p=l-e++;!c[p]&&(c[p]=new Array(w));c[p][j]=1}}e=1;} ``` Where `a` is the input array and `c` is the output array. Might be cheating since I am pulling a vacuum on all the 0s rather then applying gravity to all the 1s. It works similar to the rest of the solutions where you need to rotate the array and sort it but it does it all in one go and without using any of the built in sort/rotate functions. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 bytes ``` a->vecsort(a~)~ ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P1HXriw1uTi/qEQjsU6z7n9iQUFOpUaigq6dQkFRZh5QVEEJxFFSSNNI1NTUiY421DHQMdSBkAbWBjoGEBYIWsPkwNAaoc4QLGcIV2kYqxMN1Q3SA@bBdKHqALNA8rGxmv8B "Pari/GP – Try It Online") [Answer] # TI-Basic, 54 bytes ``` Input [A] dim([A] For(I,1,Ans(2 Matr►list([A],I,A SortA(ʟA For(J,1,dim(ʟA ʟA(J→[A](J,I End End ``` Output is stored in `[A]`, which was the inputted matrix. [Answer] # [Swift 5.5/Xcode 13.0](https://developer.apple.com/swift/), 215 bytes ``` var c=[Int:Int]();let d=m.count;let e=m[0].count;for i in 0..<e{for j in 0..<d{c[i,default:0]+=m[j][i]}};var r=Array(repeating:Array(repeating:1,count:e),count:d);for k in c{for i in 0..<d-k.1{r[i][k.0]=0}};return r ``` [Try it online!](https://tio.run/##fZDdaoQwEIXvfYq5VJqVBHrlNgu9Kn2GkIsQY8m6RknHbUV8dmv82e5aaAbCnMNMvkM@v2yBz2PROg2qaS7dm1dXi12MNVQZCPHuUMoEDqeth368Kg@aB5kFK06OF4OQ8yrVdetwVoZXgsrVKGoPFqwDmqYvpg/yvMm818KS3BSqvWBG5dO0eJbCymE4BpDnr96rLvamMQqt@8j2mpGZkplkbfJkJpYBofsHeH4oU9b76XlRplRyOlG8wdY78OMQRSG6dU2LwPf/kYkIpiMYoYSR5aaSLCYldDFCbeY2Odfv5LbM7ifZbT1MymSJYr4bo9HkUxpxD6KPoH/pdA/6E2lvyihqvHUYrz/BbzmS8Qc "Swift – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes ``` +`(?<=(.)*)1(.*¶(?<-1>.)*(?(1)^))0 0$+1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fO0HD3sZWQ09TS9NQQ0/r0DYgV9fQDsjXsNcw1IzT1DTgMlDRNvz/31DHQMdQB0ICxXQMICwQ5ILJgSEXQp0hWM4QrtIQAA "Retina 0.8.2 – Try It Online") Takes input as a list of digit strings although commas can be redundantly included as per the example link. Explanation: .NET's balancing groups are used to ensure that the regular expression matches a `1` directly above a `0`; the digits are thus exchanged. `$+` is used instead of `$2` due to the following digit which would otherwise be interpreted as part of the substitution name. The `+` modifier repeats the substitutions until all of the gravity has been applied. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~35~~ 20 bytes ``` WS⊞υι↑Eθ⭆²Φ⭆υ§νκ⁻Iνλ ``` [Try it online!](https://tio.run/##RYvLCgIxDEX3/YosU6iQunRWIgizEAbEDyhjscVSxz7Uv6/puPASAuckd3YmzQ8TWns7HyzgGJdaziX5eEMpYarZYVXg5SAmlgV3l0XBySz4VPD767BVcPSh2IR/x7V9GePVfjAquEvJPR9rxoPJBSNjkD1Da5o0Dwki3kSiM0esmv16JS3a5hW@ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of digit strings. Explanation: ``` WS⊞υι ``` Read the input. ``` ↑Eθ⭆²Φ⭆υ§νκ⁻Iνλ ``` Map over each column, taking the transpose and filtering out the `0`s and `1`s each time, so that the `1`s are effectively sorted to the front, but then print the whole lot vertically which rotates the result so that the mapped rows turn back into columns but also the `1`s end up at the bottom as desired. Previous 35-byte canvas-based version: ``` WS⟦ι⟧↑WKK«WKK«F⁼⪫KD²↓ω10↓01↑»↓WKK↓↗ ``` [Try it online!](https://tio.run/##ZY29CsIwFIXn5ClCpxQiJI7tWgcFoShO4lBKbIMhqTVtB@mzxzT9USmXhHPPdy4nL7M615m0tiuF5AjvVdWYs6mFKnAYotQJg6/iFsbwqFuOo0vl5BROOX8MqTcEawfcdY3w7tlk8oUPWigPE1Hz3Ait8JagKNGdCgnq3AsYDZZCD5xHWeDaAPipBj2cVn8cr6r/4Xx5EkVpnNFbywgljIw/hZTQUQ0DZ@YHfnPMM7YkGbSbVn4A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of digit strings although commas can be redundantly included as per the example link. Explanation: ``` WS⟦ι⟧ ``` Copy the input to the canvas. ``` ↑ ``` Start at the bottom of the first column. ``` WKK« ``` Repeat while there are still columns to process. ``` WKK« ``` Repeat until this column has been processed. ``` F⁼⪫KD²↓ω10 ``` If this column contains a `1` above a `0`, then... ``` ↓01 ``` ... switch the characters, moving down so that the `1` gets considered for gravity again on the next pass. ``` ↑ ``` Try the next digit. ``` »↓WKK↓↗ ``` Locate the bottom of the next column. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` CSMC ``` [Try it online!](https://tio.run/##K6gsyfj/3znY1/n//@hoQx0FAx0FQzCCMAxidRSiDcA8A5iwAVQYWTUUQVUjm2CIUG2IaohhbCwA "Pyth – Try It Online") ``` CSMC C # transpose the matrix SM # sort each row C # transpose again ``` ]
[Question] [ Consider a grid from \$(0,0)\$ in the bottom-left corner to \$(m,n)\$ in the top-right corner. You begin at \$(0,0)\$, and can only move in one of these three ways: * Directly north \$(+0, +1)\$, * Directly east \$(+1, +0)\$, or * Directly north-east \$(+1, +1)\$ How many different paths are there from your start at \$(0,0)\$ to \$(m, n)\$? For example, if you're trying to reach \$(3, 3)\$, there are 63 different paths: [![enter image description here](https://i.stack.imgur.com/uFhat.png)](https://i.stack.imgur.com/uFhat.png) This value is given by \$D(m,n)\$, the [Delannoy numbers](https://en.wikipedia.org/wiki/Delannoy_number). One formula for these numbers is $$D(m,n) = \begin{cases} 1, & \text{if } m = 0 \text{ or } n = 0 \\ D(m-1, n) + D(m-1, n-1) + D(m, n-1), & \text{otherwise} \end{cases}$$ Others can be found on the Wikipedia page --- You are to take two non-negative integers \$n\$ and \$m\$ and output \$D(m,n)\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins You may input and output in [any convenient manner](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you may assume that no part of the calculation exceeds your language's integer maximum. ## Test cases ``` [m, n] -> D(m, n) [5, 8] -> 13073 [5, 7] -> 7183 [3, 9] -> 1159 [8, 6] -> 40081 [8, 8] -> 265729 [1, 7] -> 15 [7, 0] -> 1 [11, 6] -> 227305 [0, 4] -> 1 ``` And all possible outputs for \$0 \le n, m \le 7\$: ``` [m, n] -> D(m, n) [0, 0] -> 1 [0, 1] -> 1 [0, 2] -> 1 [0, 3] -> 1 [0, 4] -> 1 [0, 5] -> 1 [0, 6] -> 1 [0, 7] -> 1 [0, 8] -> 1 [1, 0] -> 1 [1, 1] -> 3 [1, 2] -> 5 [1, 3] -> 7 [1, 4] -> 9 [1, 5] -> 11 [1, 6] -> 13 [1, 7] -> 15 [1, 8] -> 17 [2, 0] -> 1 [2, 1] -> 5 [2, 2] -> 13 [2, 3] -> 25 [2, 4] -> 41 [2, 5] -> 61 [2, 6] -> 85 [2, 7] -> 113 [2, 8] -> 145 [3, 0] -> 1 [3, 1] -> 7 [3, 2] -> 25 [3, 3] -> 63 [3, 4] -> 129 [3, 5] -> 231 [3, 6] -> 377 [3, 7] -> 575 [3, 8] -> 833 [4, 0] -> 1 [4, 1] -> 9 [4, 2] -> 41 [4, 3] -> 129 [4, 4] -> 321 [4, 5] -> 681 [4, 6] -> 1289 [4, 7] -> 2241 [4, 8] -> 3649 [5, 0] -> 1 [5, 1] -> 11 [5, 2] -> 61 [5, 3] -> 231 [5, 4] -> 681 [5, 5] -> 1683 [5, 6] -> 3653 [5, 7] -> 7183 [5, 8] -> 13073 [6, 0] -> 1 [6, 1] -> 13 [6, 2] -> 85 [6, 3] -> 377 [6, 4] -> 1289 [6, 5] -> 3653 [6, 6] -> 8989 [6, 7] -> 19825 [6, 8] -> 40081 [7, 0] -> 1 [7, 1] -> 15 [7, 2] -> 113 [7, 3] -> 575 [7, 4] -> 2241 [7, 5] -> 7183 [7, 6] -> 19825 [7, 7] -> 48639 [7, 8] -> 108545 [8, 0] -> 1 [8, 1] -> 17 [8, 2] -> 145 [8, 3] -> 833 [8, 4] -> 3649 [8, 5] -> 13073 [8, 6] -> 40081 [8, 7] -> 108545 [8, 8] -> 265729 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Żc@Ɱ,PṚḄ ``` [Try it online!](https://tio.run/##y0rNyan8///o7mSHRxvX6QQ83Dnr4Y4WIP/w8sP7Etz//zcFAA "Jelly – Try It Online") Because I couldn't tolerate Jelly being tied with APL. Again uses the formula $$D(m,n) = \sum\_{k=0}^{\min(m,n)} \binom{m}{k} \binom{n}{k} 2^k$$ but takes `m` and `n` as two separate arguments. This is essentially a port of [my own Dyalog Extended answer](https://codegolf.stackexchange.com/a/225208/78410). ``` Żc@Ɱ,PṚḄ Dyadic link. Left arg: m, Right arg: n Ż Inclusive range 0..m (if m > n, the extra nCk terms will be zero) , [m, n] c@Ɱ A table containing [[mC0 .. mCk], [nC0 .. nCk]] P Vectorized product; [mC0 * nC0 .. mCk * nCk] ṚḄ Reverse and unbinary; effectively sum mCk * nCk * 2^k for k = 0..m ``` Alternative 8 bytes, taking a single argument `[m, n]`: ``` c€ṂŻ$PṚḄ ``` [Try it online!](https://tio.run/##y0rNyan8/z/5UdOahzubju5WCXi4c9bDHS3/j@7WObwv4XA7UAKI3P//NwUA "Jelly – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 [bytes](https://github.com/abrudz/SBCS) ``` ⊢/(1,2+/+\)⍣⎕⊢1,⎕⍴1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@f9qhtQvX/R12L9DUMdYy09bVjNB/1Ln7UuwsoZKjzqHfro94thv9r/z/qmKGX9qh3hYIBUHCzBQA "APL (Dyalog Unicode) – Try It Online") A full program that takes `n` and `m` on two separate lines. TIO link has an equivalent dfn for demonstration purposes. ### How it works It goes through the table of Delannoy numbers row by row. Start with the zeroth row of `m + 1` ones, and calculate the next row n times: ``` Previous row: 1 a b c d e ... Next row: 1 A B C D E ... ``` From the recurrence relation, we can observe the following: ``` A = 1 + 1 + a = 2 + a = (1) + (1 + a) B = A + a + b = 2 + 2a + b = (1 + a) + (1 + a + b) C = B + b + c = 2 + 2a + 2b + c = (1 + a + b) + (1 + a + b + c) ... ``` Therefore, we can compute the next row by taking the cumulative sum `+\`, then pairwise sum `2+/`, then prepending a 1. The desired value of `D(m,n)` is at the end of the row, so we apply `⊢/` at the end. --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes ``` ⊥⍤⌽(×/…⍤⌊!\,) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HX0ke9Sx717NU4PF3/UcMyMKdLMUZH83/ao7YJj3r7HnU1H1pv/Kht4qO@qcFBzkAyxMMz@P@jjhl6aY96VygY6Dzq3WwBAA "APL (Dyalog Extended) – Try It Online") A straightforward implementation of the Wikipedia formula, also used by multiple other answers. ``` ⊥⍤⌽(×/…⍤⌊!\,) ⍝ Input: left arg = m, right arg = n !\ ⍝ Outer product by nCk function... …⍤⌊ ⍝ k = 0..min(n,m) , ⍝ [m, n] ×/ ⍝ Row-wise product; mCk * nCk for each k ⊥⍤⌽ ⍝ Reverse and evaluate in base 2; sum of mCk * nCk * 2^k ``` [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` m#n|m*n<1=1|i<-m-1,j<-n-1=i#n+m#j+i#j ``` [Try it online!](https://tio.run/##NY1BroIwEED3PcUkmAjfaewUsZjfegJvQFyQ0Gj5tBBkQ@Ld@RXibl7evJln/fqzXbcsPglv/xM0GXo7zT0nbDUPnIxLwsEn7cEl7eJrF0zTM0gd9pnmr6EO6dHs@T7Tu@vDTjcXLIPOTpXHcDejrRtwv/M67JqxH0BCzIfRhSmNP42ZMW7inDH4HF@qAqG8A78C5ULl7MNqZUVlxBzhsmkqLqwqEc4rnoQoaeWtludCybhA35wKVikEsUEU9E2lVLmIViCcNvsP "Haskell – Try It Online") Straightforward recursive implementation. # [Haskell](https://www.haskell.org/), 41 bytes ``` 0#n=1 m#n|j<-m-1=2*sum(map(j#)[0..n])-j#n ``` [Try it online!](https://tio.run/##NY3BisMgFEX3fsUDC9VBO2qamtLYL5g/kCyEyIyZaEKSLgrz7xmb0M3jHc693B83//q@X1eBk5Eo4vTX1TxyadTH/IgkupF0mFpxOqWG8g6nNbqQTDsgIIENtObz6BL5NEd@pPXh/u2Xr5A8gt4vNrLUmMm7FsLtuT2HdhpGUJDr4xTSQvKiMU@WkyxfnCiC18BqSwZVA/wOshC6QC/WG2tZZSwYXHctyyuyFYPLhmchKrnx3laXUqsckO@6LJHVDMQOWch3VSldiGwFg/Nu/wE "Haskell – Try It Online") Based on a curious formula I found, but not quite short enough. $$ D(m,n)=2\sum\_{k=0}^{n-1}D(m-1,k)+D(m-1,n). $$ [Answer] # [J](http://jsoftware.com/), 24 21 19 bytes ``` 2#.[:*/,!~/],i.@-@] ``` [Try it online!](https://tio.run/##TcyxCsIwEAbg3ac4dShKmt4lTS8JFAqCk5OrdBKLuvgGvno8TYodAvd//PmfaaOrCfoIFShAiPJqDYfz6ZjMVl/ivlHrdzOqhx7qYUy71e16f4GDCXw@ySJb6JfE5GfhUiIXRKxIyNIiehLyQl0m0zk2odi87iTTYkgiS8TyxbDFX4X@O98OSmzTBw "J – Try It Online") -3 thanks to the base 2 trick from [Bubbler's APL answer](https://codegolf.stackexchange.com/a/225208/15469). -2 thanks to Bubbler. Just this formula translated into J: $$ D(m,n) = \sum ^ {\min(m, n)} \_ {k=0} \binom m k \binom n k 2^k $$ [Answer] # [R](https://www.r-project.org/), 45 bytes ``` function(m,n,o=0:m,`$`=choose)m$o%*%(n$o*2^o) ``` [Try it online!](https://tio.run/##K/rvkpqTmJeXX2n7P600L7kkMz9PI1cnTyff1sAqVydBJcE2OSM/vzhVM1clX1VLVSNPJV/LKC5fE65Pw1THQlNBWUHXTsHQ2MDc@D8A "R – Try It Online") Similar but independently-derived approach to pajonk's answer (version 2) - [check it out](https://codegolf.stackexchange.com/a/225223/95126) - but here maximizing [R](https://www.r-project.org/)'s vectorization & vector operators to avoid needing any loop. [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` D=lambda m,n:m*n<1or D(m-1,n)+D(m-1,n-1)+D(m,n-1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/38U2JzE3KSVRIVcnzypXK8/GML9IwUUjV9dQJ09TG8rQNQQzwYz/BUWZeSUaLhoGOgaamv8B "Python 3 – Try It Online") Uses the formula specified in question, and looks like `m*n` works instead of `m and n` -1 byte saved thanks to @CommandMaster forgot that we could use short-circuit evaluation -4 again for @DingleDooper, genius one line short circuit [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 65 bytes ``` [| m n | m n min [0,b] [| k | m k nCk n k nCk k 2^ * * ] map Σ ] ``` [Try it online!](https://tio.run/##PY@7DsIgGIV3n@LMxph6rZfExcG4uBgnUxNEVNICFehgap/G9/GVEEttCPDxncPwXwm1SrvDfrvbLCCIvfepEmcuidecGmSKkszUSYiVvjAdsJCcqgsLD03kjRkQY5T/lmtm7TPXXFoY9iiYpD5cdsoOUGKCGaqG4oZGmDc0w7Slf2/Q9mJEfzdoixHGnip3fEFAIpyCSxyj3jmB12ktU8i1382dYnhC16/Ej5Dj80biSlRhhtVPGUto2ndf "Factor – Try It Online") Inputs are re-used so often it's one of the odd times local variables are the terse way to go. Since recursion is generally verbose in Factor, I've gone with the formula $$D(m,n) = \sum\_{k=0}^{\min(m,n)} \binom{m}{k} \binom{n}{k} 2^k$$ [Answer] # [JavaScript (Node.js)](https://nodejs.org), 38 bytes ``` m=>g=n=>m*n?g(n--,m--)+g(n)+g(n,m++):1 ``` [Try it online!](https://tio.run/##HcbBCoAgDADQ39nSBdGpYHbxR8JECt0io9@36PJ4x/qsNVz7eZPoFpvnVtglFnalkyWBENlChObrjy3G4Dy0oFI1xz5rAg8jwoTYXg "JavaScript (Node.js) – Try It Online") Uses the specified formula, so will reach recursion limit on larger testcases. -1 byte thanks to @dingledooper -3 bytes thanks to @Arnauld [Answer] # [R](https://www.r-project.org/), 52 bytes ``` D=function(x)"if"(all(x),D(x-1:0)+D(x-1)+D(x-0:1),1) ``` [Try it online!](https://tio.run/##RcxNCoNADIbhfU8R7GZCIyQzjhmFduVFiiAIYqG04O2nZX5wlfDw8r1jnO7Ld58/62s3Bzbr0pjntv1fmszRysh4S08@PAqSYJzMbDxBQLxC@wBxrO5SUAuqhGyOYKih@CFZIOiLdcxBKtZF23u1OZVzUnwSJeAqOZFzzlp1nDsm6GoXfw "R – Try It Online") Using the recursive formula and taking input as a tuple (thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)). Taking input as two arguments: ### [R](https://www.r-project.org/), 55 bytes ``` D=function(m,n)"if"(m*n,D(m-1,n)+D(m-1,n-1)+D(m,n-1),1) ``` [Try it online!](https://tio.run/##PYw7CsMwEET7nGJxGilZwa5keeUiqXSTgMGFFQjJ@RX9cDfz5jGfnONj@6XXd38ndWDS075N6rgljOowXMB9BMMttoCsc1QeIegrmCewI3GXRqQT4VCBQ1iHwn4tICAsHcxEgTsZL3bxYqvE5w37UgWBRq0jnxfWiqNqEMI8jPwH "R – Try It Online") Using the closed-form expression from [Wikipedia](https://en.wikipedia.org/wiki/Delannoy_number#Delannoy_numbers) results in 56 bytes with a loop, but take a look at [@Dominic's 45 byte approach](https://codegolf.stackexchange.com/a/225244/55372)! ### [R](https://www.r-project.org/), ~~68~~ ~~61~~ ~~58~~ 56 bytes ``` function(m,n,`$`=choose){for(k in 0:m)F=F+m$k*n$k*2^k;F} ``` [Try it online!](https://tio.run/##RYzBCoJAEIbvPcVAHrQmmNl13bWwk/gYIUiSiLtgdYqefXNT9DCH/5uPb/Rl4du3bV6ds/GAFuuoLpqHc8978mndGPfQWaDzkFRFdRyi/mCnE7f@Un19GSsEk@zhdAWWpOXuT/RMNJsAJEK@KKzyCRiEbAYpkeGZLBWRKS2CxGuG1TQ1Ai0zPHlNCKElBYMQ0s2gzfc/ "R – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes ``` Total//@DiamondMatrix@Table@##& ``` [Try it online!](https://tio.run/##TZJPa9tAEMXv@hRGCaUFmUizf0Vi40Jy6KFQiG@qDqrrNAuyZBQFDCGf3ZX27a729kajmd@bmT014@vx1Izm0FxfNtd9Pzbt3d3u0TSnvvv7sxkHc9ntmz/tcXdz8@X62FfJh8n6z01ruuN9YjbpS/qwNffJr8F0Y2XW233/dDkPx7c303eVqbN09TXN@iz9ltZJ9jGXZc9T1@7f02UcmsNY3T4fBnMef3Tn9xGZLP3dpevt97adqtfbFXT9WV@rPFvl9fytSGZdRJoizSLNIy0iLSOtIq29LiJW4VnMarCE1WApq8EqrXYsFDsYqh0N5Q431VPEI88TVlMoJw8kZEDkKAFSIgBS4zeHdB0ck085FkGZhyqrKXCYh0pmA7dSKm0EKjF0AJYp9ABXKDQBV7OpC4@43HNLqymMxMMlCSmAGSHnxtWI3IpJ41eQiVwfoJnkU1ZEbBEeEQIKKxRh0wwRX3AinFdqZkM3thQIQVeFy7qFs1xNsYzwMuCRoHA06fF2lXJZ@jyf9HwAZbh26bLu3qUmtIIBnuezexUZUMGAsAEtD0V5B/Z8yjvASpV3gBlV2D@QylvgWrLSxm4HuRbzu9ORBx08KBvQ8jy192AfjQ4vwN5RhytgsdqbcHPqsIcFChckhaLyPw "Wolfram Language (Mathematica) – Try It Online") Returns `{1}` instead of `1` when the second argument is 0. To fix this, ~~+4~~ +3 bytes: [Try it online!](https://tio.run/##TZJPa9tAEMXv/hRGKaUFmUizf0Vqo4Jz6KFQiG@qDqrjpAuyZBQVDCGf3ZX27a729kajmd@bmT0349/TuRnNsbm9bG/7sjz0Y9Pe35d705z77vlnMw7mWh6aP@2pvLv7fNv31erdpP3HtjXd6WFltslL8m1nHla/BtONldnsDv3j9TKc3t5M31WmTpP1lyTt0@RrUq/S97ksfZq6dq@P13FojmP16ek4mMv4o7v8G5FJk99dstl9b9uperNbQ9cf9a3K0nVWz9/y1azzSFOkWaR5pEWkZaRVpLXXecTKPYtZDZawGixlNViF1Y6FYgdDtaOh3OGmeop45HnCagrl5IGEDIgcJUBKBEBq/OaQroNj8inHIijzUGU1BQ7zUMls4FZKhY1AJYYOwDKFHuAKhSbgajZ14RGXe25hNYWReLgkIQUwI@TcuBqRWzFp/AoykesDNJN8yoqILcIjQkBhhSJsmiHiC06E80rNbOjGlgIh6Cp3WbdwlqkplhFeBjwSFI4mPd6uUi5Ln@eTng@gDNcuXNbdu9CEVjDAs2x2ryIDKhgQNqDloSjvwJ5PeQdYqfIOMKMK@wdSeQtcS1bY2O0g02J@dzryoIMHZQNanqf2Huyj0eEF2DvqcAUsVnsTbk4d9rBA4YKkUFT8Bw "Wolfram Language (Mathematica) – Try It Online") From Wikipedia: > > The Delannoy number \$D(m,n)\$ also counts... the number of cells in an *m*-dimensional von Neumann neighborhood of radius *n*... > > > Generates a matrix representing a radius-`m` dimension-`n` von Neumann neighborhood, and counts the number of cells. --- Some other approaches: **Multinomial formula, ~~38~~ 36 bytes** ``` Multinomial[k,#-k,#2-k]~Sum~{k,0,#}& ``` [Try it online!](https://tio.run/##bZRNi9swEIbv/hXGW0oLMtgj68NsEyh0Dz0UCtmb64MJ2VYksUPWgYWQ/euprVdSRNpD4J2MZp7RzMj7bvyz2XejWXfXl8X1x2k3mn7Ym27XbNlDPv0o37bvq9P@/bxlBXu4fLx@G5rkbNhwWexMv3lMzCJ7yb4szWPy82j6sTH58nl4ejscN6@vZugb07Is/ZSxgWWfszZh5zmMrcbp8O@nt/HYrcfmw2p9NIfxe384jfCw7Fef5cuvu90UnS9T6PbSXhvBUt3O/5W8UDyZbWVtVerJ5Cyt4S5FnTSapdKaVVHo0tqIJikUTQdKH16KpFEsLWBMjtKHEileTN6CpZX3FtHJSZeRpkjzSMexItIy0irSOlQSV@VZ3GqwhNVgKavBwvUcC8EOxu8uXgbcFE8RjzxPWE0hnDyQ4AGxQgiQEgaQGscc0mVwzErYuQUo91BlNQUO91CJSbuWznPknkocGYDlCjnAFQpJwNV8ylJF3Mpza6spXKkKkyS4AOYEn7uuhuVaTBpHldshlwdoLqvarm5gi7BEMCi0UIROc1jVDSfCeKXGW3DXluLfp3H/cmSElwEPB4WhSY@3rZS3ps/3k54PoAzTrp3XzbvWhFQ6fozxc1OhALxDui2K8hXY8SlfAVqqfAW4owr9B1L5EioteW1t14NCi3nvdFSDDjUoa9BtPbWvwS6NDhtg56jDFNDY/3x01D00/gr9BQ "Wolfram Language (Mathematica) – Try It Online") **Direct recursion, 46 bytes** ``` f=If[1##>0,f[#-1,#2]+f[#-1,#2-1]+f[#,#2-1],1]& ``` [Try it online!](https://tio.run/##bZRNi9swEIbv/hXGKaWlMlijT7NNoNA97K2we3N9CCFpBVk7ZF1YWPa3p7ZeSRFpb@94NHrmS37eTr/3z9vJ7baXy2H9cOj4arVp2KFb1ZytqP8SVc29hmK8/3j5PnbFm2Pj@/rohv1d4dbVofq6cXfFj7Mbps7Vm6fx/vV03r@8uHHoXM@q8lPFRlZ9rvqCvS1h7HGaD/@6f53O293UfXjcnd1pehhOfyZ4WPVzqOrNt@Nxjq43JXT/3l86xUrbL9@4aIwoFtt423A7m4KVLdxctUVnWam9KZvGcm8jmrQyNB/gMZyrojOsbGDMDh5DiYxoZm/DShm9TXZy1jzTlGmR6TxWZVpn2mTapkzyrCJLeA2W8hos4zVYKC@wEBxg4qZwnnBzPGU8ijzlNaVwikCCB0SJECA1DCAtjgVkuCEwpfJzS1ARocZrShwRoRqTDi1d5igilQRuAFYY3AGuMrgEXCvmW2TGlZHbek2pJJkmSXABLAi@UK6FFVpMFkdN2KFwD9BCy9avbmKrtEQwKLVQpU4LWPKKU2m82uIthLK1@vdp3L4cneF1wsNBaWg64n0r9bXpS3068gHUadpt8IZ5t5Zwlc0fY/7cTEoA75Cui2JiBn58JmaAlpqYAWo0qf9AmpiCtFq03g49aKxa9s5mOdiUg/EGXdfTxhz80ti0AX6ONk0Bjf3PT8fcQvO/0F8 "Wolfram Language (Mathematica) – Try It Online") **Generating function, 46 bytes** ``` SeriesCoefficient[1/(2-x y),{x,1,#},{y,1,#2}]& ``` [Try it online!](https://tio.run/##bZRNi9swEIbv/hXGW8ouKNQaWR9mm0Bp99BbIb25PoTgbAXZOCQuZAn57amtV1JE2lPeyWjmGc2M/LYafndvq8GuV9fN/LrsDrY7fu27zcaubbcbGv7pkWan/P2JnU@Ms4cLO79Pv3RpP16/9U12tqy/zLd21z1ndl5sis8L@5z9ONgx2M4WP/uX0/7QHY@23zW2ZUX@WLCeFU9Fm7HzFMaWw3j49eU0HFbrofmwXB/sfvi@2/8Z4GHFr10xW3zZbsfo2SKHbi/ttZEsN@30HxelFtlka2drbkZTsLyGm8s6awzLlTOrsjTc2YgmJTWNB3gI5zJrNMtLGKODh1AiLcrRW7K8Ct4yOTlqnmhKtEh0GisTrRKtE21iJWlVgSWcBks6DZZ2Gixcz7MQ7GHi7uI84sZ4SngUeNJpiuEUgAQPiBVCgFQwgDQ45pE@g2dW0s0tQkWAaqcpckSAKkzat3SaowhUEsgArNDIAa7USAKuEWOWKuFWgVs7TfFKVZwkwQWwIPj8dQ0s32IyOKr9Dvk8QAtV1W51I1vGJYJBsYUydlrAqm44GcerDN6Cv7aS/z6N@5ejEryKeDgoDk0FvGulujV9up8KfABVnHbtvX7etSGkMuljTJ@bjgXgHdJtUXSowI1PhwrQUh0qwB117D@QOpRQGSVqZ/selEZOe2eSGkysQTuDbutpQg1uaUzcADdHE6eAxv7no6PvoelX6C8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes ``` WÝ€cPR2β ``` [Try it online!](https://tio.run/##yy9OTMpM/f8//PDcR01rkgOCjM5t@v8/2lTHPBYA "05AB1E – Try It Online") -2 thanks to the base 2 trick from Bubbler's APL answer. Uses the direct formula from wikipedia. ``` W push the minimum of m,n Ý push the range [0,min(n,m)] € and map each number to c the input choose that number, vectorizes P product R reverse 2β convert from base 2 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ≔E⊕N¹θFNUMθ⁺κ⊗↨…θλ¹I⊟θ ``` [Try it online!](https://tio.run/##XUw5DsIwEOzzCpdryRSICqUC01CA/IWNY0jE@ogPJF5vbEpGGmk0l14wao9U6yml9enghgGuTkdjjctmbjqUfC92MhE4F2zfuPFxePjI/kLWttJbi26GTTBFJcFLsIsvE7WnMyYD8qPJyMWH3qDfX8M4qLi6DBJTBtXDbtZ6YMe6e9MX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @Delfad0r's curious formula. ``` ≔E⊕N¹θ ``` Input `n` and create an array of `1`s representing `D(0,k)` for `0<=k<=n`. ``` FN ``` Repeat `m` times. ``` UMθ⁺κ⊗↨…θλ¹ ``` Add twice the cumulative sum to each element. (I have to use base `1` conversion because `Sum` returns `None` for an empty list. It was still shorter than adding the inclusive and exclusive cumulative sums.) ``` I⊟θ ``` Output `D(m,n)`. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~79~~ 67 bytes ``` filter f($a){if($a*$_){(--$a|f $_)+(--$_|f $a)+($a+1|f $_)}else{1}} ``` [Try it online!](https://tio.run/##RY1bC4JAEIXf/RXzsIHmCol0AQmEnruQjxFhNpKxXnKVAt3fbjsaBbvsd86eOVMWL6zkHYVw4qLCvk9SUWMFickiq03pmbKL1ZqOw6IuAc028YU40swi2x19hUJi6yrVB6bBA9PjoM/Cs0jMOaw4uN5sqbVhQQcTaA0AlnFgub74LjGu8QZr3eXTT4WyETXpjBbk2jsdwk0j6yLbXx86fQ6oAiBs4hilpOh3yMHnv9IfQtuhaeQdcT7y8bdmnCVXGar/AA "PowerShell Core – Try It Online") * Saved 1 byte by using a filter * Saved 3 bytes replacing the `-and` by a `*` * Saved a whopping 12 bytes thanks to [Zaelin Goodman](https://codegolf.stackexchange.com/users/99902/zaelin-goodman) [Answer] # [Julia 1.0](http://julialang.org/), ~~47~~ 30 bytes ``` m%n=m*n<1||~-m%n+~-m%~-n+m%~-n ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P1c1zzZXK8/GsKamThfI0QaRdbp52mDyf1p@kUKmQmaegoGVuY5CFpTFxVlQlJlXkpOnoaSSqaOgkmWloKKRqZqlqaTJlZqX8h8A "Julia 1.0 – Try It Online") Boring port of the formula. * -12 bytes thanks to @Sisyphus! * -5 bytes thanks to @MarcMush! [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 18 bytes ``` {0/x(+':+\)/1,y#1} ``` [Try it online!](https://ngn.codeberg.page/k#eJxVkEsOwjAMRPc5RRALQCA1juvYyVlYc4QKhLg7GRuQkJpP3eeZcW/jWZb78XwY5+tpoctjT6+UtpF3PW35tozryFtKlPN8fiu2v/13gOV5kbkUle7laONgJA4FK1GuqK1ONd9Nos9baBWwGlybNarQrQyW1Y1EvcWYwXaXc4wrqGaYopr3VbfitvbJItw0dbGgmjG+CsyV8EJcFLrIM6PBMrSCso47dUO+tRTDf5hzIj9yhaFLfSFr3DMVE5+NFEMivKcKv1D6QLk20drfXT9KOA==) Port of [my APL answer](https://codegolf.stackexchange.com/a/225208/78410) that does not use the binomial coefficient built-in. See the linked answer for the explanation of how it computes Delannoy numbers using just cumulative sum `+\` and windowed sums `+':`. ``` {0/x(+':+\)/1,y#1} x, y: two input integers 1,y#1 (y+1) copies of 1; the 0th row of the grid of Delannoy numbers x( )/ do x times: +':+\ calculate the next row 0/ base 0 = extract the last item ``` [Answer] # Java, 62 bytes ``` int f(int m,int n){return n*m<1?1:f(m--,n-1)+f(m,n)+f(m,n-1);} ``` [Try it online!](https://tio.run/##dUzLDoIwEDzDV@yx1ZaEg9GIxi/wxNF4qLwC0oW0BWMI314XwtU5zO7O7EyjRiWb/O374dXWGWStshbuqkaYQiBsunXK0Ri7OgdNLkudqbF6PEGZyvIpDNaMhitg8VkLGE/WhgXp17pCR93gop5yrkWmo5IdxInTV/DXPvKtZPYkQ8kW1mJh5JMp3GAQcKcv8S0@l0xLKVDGfE@rwG3Qncx@9j8) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes ``` d(m,n)=if(m*n,d(m-1,n)+d(m-1,n-1)+d(m,n-1),1) ``` [Try it online!](https://tio.run/##LYtBCsMwDATvfUncyqC148g5@DGF0pJDQuj/IdWK3mY02vP53fLnvK7XtMuRxvae9vshbhnujz9kBAYIEt@b9DQGqlq90czN0ClVVia01aXL4jKrdoRxVZZmhRExQ3M0USKPiEkpVpVFZWb5AQ "Pari/GP – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes ``` f=->m,n{m*n<1?1:f[m-1,n]+f[m-1,n-=1]+f[m,n]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5XJ686VyvPxtDe0CotOlfXUCcvVhvK0LU1BLOBQrX/CxTSoo11jGP/AwA "Ruby – Try It Online") Using the formula in the question [Answer] # [Desmos](https://desmos.com/calculator), 38 bytes ``` D(m,n)=\sum_{k=0}^mnCr(m,k)nCr(n,k)2^k ``` [Try It On Desmos!](https://www.desmos.com/calculator/kxgyyd9zi2) [Try It On Desmos! (Prettified)](https://www.desmos.com/calculator/6tppbob2vv) Implements the formula$$D(m,n)=\sum\_{k=0}^{\min(m,n)}\binom mk\binom nk2^k$$with the observation that \$\min(m,n)\$ can be replaced with \$m\$(or \$n\$). [Answer] # [J](http://jsoftware.com/), 17 bytes ``` ]{(2&+/\@[&0>:$#) ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6Wuo2CgYAXEunoKzkE@bv9jqzWM1LT1Yxyi1QzsrFSUNf9rcqUmZ@QrpClp69cpZOpZ/gcA "J – Try It Online") Uses the same algorithm as my [19-byte APL solution](https://codegolf.stackexchange.com/a/225208/78410). I randomly came across the problem again and realized J has multiple tricks to shorten the code, so it is actually shorter than APL. Also beats [Jonah's J solution](https://codegolf.stackexchange.com/a/225212/78410) which uses the direct formula. Takes `m` and `n` as left and right argument respectively. `2&+/` part comes from [here](https://codegolf.stackexchange.com/a/206979/78410). ``` ]{(2&+/\@[&0>:$#) NB. left arg = m; right arg = n xxxxxxxxxyyyy NB. This part is a hook, so it evaluates as m x (y n) >:$# NB. n+1 copies of 1 xxxxx@[&0 NB. A trick idiom for "repeat x m times to (y n)" 2&+/\ NB. Evaluate next row of Delannoy matrix: \ NB. For each prefix, 2&+/ NB. Convert [a, b, ..., m, n] to 2a+2b+...+2m+n ]{ NB. Extract the last element, which is at index n (0-based) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ṂŻc@ⱮµPæ«J$SH ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//4bmCxbtjQOKxrsK1UMOmwqtKJFNI////WzMsIDld "Jelly – Try It Online") Using the direct formula from Wikipedia. ``` Ṃ Minimum Ż [0, 1, ..., min(m, n)] Ɱ For each in the input c@ swapped args: input choose k P product (vectorizes) æ«J$ bitshift by [1, 2, 3, ...] S sum H halve (since J starts at 1) ``` # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` _45Bs2¤ß€Sµ1Ȧ? ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//XzQ1QnMywqTDn@KCrFPCtTHIpj////9bMywgOV0 "Jelly – Try It Online") Could use some work, probably. ``` ? If Ȧ all (m != 0, n != 0) S take the sum of ß this link € applied to each of _ (m, n) - 45Bs2¤ [1, 0], [1, 1], [0, 1] 45B 45 as binary: [1, 0, 1, 1, 0, 1] s2 sliced into size 2 chunks 1 Otherwise, 1 ``` [Answer] # [Red](http://www.red-lang.org), 73 bytes ``` f: func[m n][either(m * n)= 0[1][(f m - 1 n)+(f m - 1 n - 1)+ f m n - 1]] ``` [Try it online!](https://tio.run/##RY7BCoMwDIbvPsWPJ53ILNvUDbaH2DX0IDZFwVYp@vxO7brlEL6Ej@R3rNY3K5KrfkAvtiUDK4n7uWOXGJxg0ycKEpISDYMcYttkf957mmGfD5bbpdFx03bwpyLsdUMdoPJwwd1DjTLA1xHBqVAcIERwClwjSZPr7QyaGnUeWM8w46DgWC0tH09RIs5fMX6Cj1dt4T4 "Red – Try It Online") Uses the formula from the problem description. [Answer] # MMIX, 64 bytes (16 instrs) Recursive, so takes forever. ``` 00000000: dc020001 52020003 e3020001 f8030000 ṇ£¡¢R£¡¤ẉ£¡¢ẏ¤¡¡ 00000010: fe020004 c1040000 27050101 f303fff9 “£¡¥Ḋ¥¡¡'¦¢¢ṙ¤”ż 00000020: 27060001 f304fff7 c1050100 22030304 '©¡¢ṙ¥”ẋḊ¦¢¡"¤¤¥ 00000030: f304fff4 22030304 f6040002 f8040000 ṙ¥”ṡ"¤¤¥ẇ¥¡£ẏ¥¡¡ ``` Disassembled: ``` delannoy MOR $2,$0,$1 PBNZ $2,0F SETL $2,1 POP 3,0 // if(!(m && n)) return(1,m,n) 0H GET $2,rJ SET $4,$0 SUBU $5,$1,1 PUSHJ $3,delannoy // $3,$4,$5 = delannoy(m,n-1) = f(m,n-1),m,n-1 SUBU $6,$0,1 // $6 = m - 1 PUSHJ $4,delannoy // $4,$5,$6 = delannoy(n-1,m-1) SET $5,$1 ADDU $3,$3,$4 // $3 += $4 PUSHJ $4,delannoy // $4,$5,$6 = delannoy(n-1,m) ADDU $3,$3,$4 PUT rJ,$2 POP 4,0 // return(f(m,n), m, n) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~45~~ 43 bytes ``` D(m,n){m=m*n?D(m-1,n)+D(m-1,--n)+D(m,n):1;} ``` [Try it online!](https://tio.run/##bVFhT4MwEP2@X3EhIQFWYoExmIh@UH@FWwwpZRJtt1CixIW/Ll4LI5uRlOPdvXuv7cH8PWPD8OQIIt2TyIUnHzDxA0yXI/D9EWLlNsj6oZYtiKKWjgZFs2cE2FvReJ5OPt3FaQH4aLLlqn0VLzvI4RQTwBURSM0KCCQY8UP77FogR0FqOjYE1kaAmBq8uujn3ZGzlpejIohoghskQRpp6xi1K0pT3CNcx0mIaRCbncMwiaiGk5U5PkbO3nmDXqDdrG33HG67zSO@sUXgMo@sSVkdGjBzqGXJO5TRbIJ3oOpvfqic8xndm6ngzZUMlkvT7cI4tPO9BDpNwzP8Lrui5ZmW/9IK6fF/Xdc51ueJ/RUeG2ypHMsuCdgl@Pc62mor8eqCgCSgyDwiled8N7n3i374YdVHsVeD//UL "C (gcc) – Try It Online") *Saved 2 bytes thanks to [mousetail](https://codegolf.stackexchange.com/users/91213/mousetail)!!!* [Answer] # [Pyt](https://github.com/mudkip201/pyt), 19 bytes ``` Đ↓0⇹ŘĐ1⇹«04Ș⇹ɐćÁ*·+ ``` [Try it online!](https://tio.run/##K6gs@f//yIRHbZMNHrXvPDrjyARDIH1otYHJiRlAxskJR9oPN2od2q79/3@0kY5JLAA "Pyt – Try It Online") Direct implementation of the formula on Wikipedia ``` Đ↓ implicit input; Đuplicate on stack; get minimum of inputs (k) 0⇹Ř create Řange [0,1,...,k] Đ1⇹« 2^k 04Ș⇹ stack manipulation to have the range on top, then the input ɐć for ɐll pairs of values in the two arrays, nćr Á* multiply the two nCr lists element-wise · dot-product with the powers of 2 + remove that pesky 0; implicit print ``` [Answer] # [Arturo](https://arturo-lang.io), ~~50~~ ~~48~~ 47 bytes ``` f:$[m,n][(0=m*n)?->1[+ +f m-1n-1f m n-1f m-1n]] ``` [Try it](http://arturo-lang.io/playground?cRSQyZ) ]
[Question] [ You must take two lists of positive integers as input, let's call these **n** and **m**. You may assume that: * All integers in **n** are part of **m** * All integers in **m** are unique * The lists are non-empty ### Challenge: Return the indices of where you find the values in **n**, in **m**. That might be confusing, but I think the test cases will make the task pretty clear. The examples are 1-indexed, you may choose 0-indexed if you want to (please specify). ``` n = 5 3 4 1 m = 6 8 4 1 2 5 3 100 output: 6 7 3 4 // 5 is in the 6th position of m // 3 is in the 7th position of m // 4 is in the 3rd position of m // 1 is in the 4th position of m n = 5 3 4 9 7 5 7 m = 3 4 5 7 9 output: 3 1 2 5 4 3 4 n = 1 2 3 4 5 6 m = 1 2 3 4 5 6 output: 1 2 3 4 5 6 n = 16 27 18 12 6 26 11 24 26 20 2 8 7 12 5 22 22 2 17 4 m = 15 18 11 16 14 20 37 38 6 36 8 32 21 2 31 22 33 4 1 35 3 25 9 30 26 39 5 23 29 10 13 12 7 19 24 17 34 27 40 28 output: 4 38 2 32 9 25 3 35 25 6 14 11 33 32 27 16 16 14 36 18 n = 54 m = 54 output: 1 ``` **The winners will be the shortest solutions in each language.** --- [This](https://codegolf.meta.stackexchange.com/a/10132/31516) is a very nice meta-post by the way! [Answer] # [V](https://github.com/DJMcMayhem/V), 26 bytes ``` jòdf kÄ/- DÓÓ ÒC1@"Gòdk ``` [Try it online!](https://tio.run/nexus/v#@591eFNKmkL24RZ9IV0ul8OTD0/mOjyJ0dlQ2kHJHSiV/f@/mYGChYKJgqGCkYKpgrGCoYGBAheIARICAA "V – TIO Nexus") This is a very strange and hacky solution, because V has little to no concept of numbers. Input comes in this format: ``` 6 8 4 1 2 5 3 100 5 3 4 1 ``` With a trailing space on each line. Hexdump: ``` 00000000: 6af2 6466 206b c42f 122d 0a44 d3d3 0ad2 j.df k./.-.D.... 00000010: 0143 311b 4022 47f2 646b .C1.@"G.dk ``` Explanation: ``` j " Move down one line (to N) (1) ò " Recursively: df " (d)elete until you (f)ind a space. This will be saved into " register '-' (2) k " Move up one line (to M) Ä " Duplicate line M (3) /<C-r>- " Move the cursor forward until the next occurence of register '-' " (the number we deleted from N) " (4) D " Delete every character *after* the cursor (5) ÓÓ " Remove everything on this line except for whitespace Ò<C-a> " Replace every character on this line with `<C-a>`, which is the " command for incrementing a number (6) C " Delete this line into register '"', and enter insert mode 1<esc> " Enter a '1' and return to normal mode @" " Run register '"' as V code (7) G " Go to the last line (1) ò " End recursion dk " Delete the last two lines (m and n) ``` If this doesn't make it clearer, here are examples of the buffer during the various stages the loop goes through: Stage 1 (`|` is the cursor) ``` 6 8 4 1 2 5 3 100 |5 3 4 1 ``` Stage 2: ``` 6 8 4 1 2 5 3 100 |3 4 1 ``` Stage 3: ``` |6 8 4 1 2 5 3 100 6 8 4 1 2 5 3 100 3 4 1 ``` Stage 4: ``` 6 8 4 1 2 |5 3 100 6 8 4 1 2 5 3 100 3 4 1 ``` Stage 5: ``` 6 8 4 1 2 | 6 8 4 1 2 5 3 100 3 4 1 ``` Stage 6: ``` |<C-a><C-a><C-a><C-a><C-a> 6 8 4 1 2 5 3 100 3 4 1 ``` Stage 7: ``` |6 6 8 4 1 2 5 3 100 3 4 1 ``` Back to stage 1: ``` 6 6 8 4 1 2 5 3 100 |3 4 1 ``` [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes ``` lambda a,b:map(a.index,b) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQqJNklZtYoJGol5mXklqhk6T5v6AoM69EI00j2kzHQsdEx1DHSMdUx1jH0MAgVicaxAKKxWpq/gcA "Python 2 – TIO Nexus") Note that this uses 0-indexing. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 1 byte ``` ⍳ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG3Co97N//@bKVgomCgYKhgpmCoYKxgaGCg4gllAMQA "APL (Dyalog Unicode) – TIO Nexus") Note: the `⍳` function does **not** take scalars as its left argument, so to give it a left argument like `54`, you have to make it into an array using `,` like so `(,54)`. [Answer] ## Mathematica, 25 bytes ``` #&@@@PositionIndex@#/@#2& ``` Takes two inputs `m` and `n`, and returns the 1-based indices of `n` in `m`. [Answer] # [Retina](https://github.com/m-ender/retina), ~~32~~ ~~31~~ 30 bytes 1 byte saved thanks to Kritixi Lithos and 1 byte thanks to Martin Ender ``` (\d+)(?=.*¶(\d+ )*\1 ) $#2 G1` ``` Uses 0-indexing. Input has a trailing space on each line. [Try it online!](https://tio.run/nexus/retina#HY49DsJQDIP3nsISDH1FQs/x@x0QI5fowMAZOQAXK0mlDFbiz86x7p9bWp@P@/b7hkbadiIt14stL76Pgw3WwQEaXDaQsBLCMgwDPS4VZueAHQUL64kQjrOEVR0anqDmjNzpMRADkhwhVCFYxYRy5GtGrK8mmEFFj5fNqPcWlXisuHXgDw "Retina – TIO Nexus") **Explanation** ``` (\d+)(?=.*¶(\d+ )*\1 ) $#2 ``` Here we replace every number on the first line by the number of numbers before the same number on the second line. ``` G1` ``` Then, we delete the second line, leaving only the new first line as the output. [Answer] # [Java](http://openjdk.java.net/), ~~104~~ 81 bytes 1 byte thanks to Business cat. ``` void f(int[]a,int[]b){for(int i=0,j=0;i<b.length;)j=a[j++]==b[i]?0*(b[i++]=j):j;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#VY9NbsMgEIXXzSlYQjNCpD9RVBdVPUBWWVpeQGo7IIItGCeKLJ/dBbubrp7mzZv5ZvpBO3MmZ6diJEdl/DjfOvNDGmo8lpWCRTQbmy5kixgpwEpRmE/NXe1bvBTMSlXa7baSUpem@hLPNGmuLfuwxTT3KySiwiTL/mtC0RMG49tECW1k4@ZpRRJJfH0nSzHu4QBvsIMXeIdX2AkxFX85/S@XuymXu9nMn1DGG6pAs@SdHhHrK@8G5H1iovPUqpviAxrHv0NQj8ixW@@hmqWRaTPNvw "Java (OpenJDK 8) – TIO Nexus") [Answer] # C#, 32 Bytes ``` (n,m)=>n.Select(i=>m.IndexOf(i)) ``` This is the code as a lambda expression, so it should be valid. The solution is with a 0 based index. I think it's pretty straigt forward how it works - it simply takes the items of n and selects the indices of the items in m. [Answer] # Octave, 25 bytes ``` @(n,m)([x,~]=find(n==m')) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaeTq6kRXaFTF2ublpmXopFna5urrqn5P802Ma/YmitPwVYh2lTBWMFEwVLBXMFUwTzWmisXJAgSAnIVLIECaWBj/gMA "Octave – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` a%b=[length$fst$span(/=x)b|x<-a] ``` [Try it online!](https://tio.run/nexus/haskell#@5@ommQbnZOal16SoZJWXKJSXJCYp6FvW6GZVFNho5sY@z83MTNPwVahoCgzr0RBRSHaVMdYx0THMFY12kzHAsTSMdIBiRkaGMT@BwA "Haskell – TIO Nexus") One-indexed. Other attempts: ``` q(h:t)x|x==h=0|1>0=1+q t x;map.q f b=map$length.fst.($b).span.(/=) a%b=[until((==x).(b!!))(+1)0|x<-a] a%b=[until(\y->x==b!!y)(+1)0|x<-a] import Data.List;map.flip elemIndex ``` [Answer] # k, 1 This is a built-in operator in `k` and uses zero-based indexing. ``` ? ``` Example: ``` k)6 8 4 1 2 5 3 100 ? 5 3 4 1 5 6 2 3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` v²yk, ``` [Try it online!](https://tio.run/nexus/05ab1e#@192aFNlts7//9GmOgrGOgomOgqGsVzRZjoKFhCOjoKRjgJEzkAnFgA "05AB1E – TIO Nexus") ``` v # For each value in n (call it y) ² # Push m y # Push y k, # Print the 0-indexed index of y in m ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` iЀ ``` [Try it online!](https://tio.run/nexus/jelly#@595eMKjpjX///@PNtOx0DHRMdQx0jHVMdYxNDCI/R8NYgHFYgE "Jelly – TIO Nexus") ## Specs * Input: two arguments, the first being **m**, and the second being **n**. * Output: one array [Answer] ## JavaScript (ES6), 28 bytes Takes the arrays in currying syntax `(n)(m)`. 0-indexed. ``` let f = n=>m=>n.map(v=>m.indexOf(v)) console.log(JSON.stringify(f([5,3,4,1])([6,8,4,1,2,5,3,100]))) console.log(JSON.stringify(f([5,3,4,9,7,5,7])([3,4,5,7,9]))) console.log(JSON.stringify(f([1,2,3,4,5,6])([1,2,3,4,5,6]))) console.log(JSON.stringify(f([16,27,18,12,6,26,11,24,26,20,2,8,7,12,5,22,22,2,17,4])([15,18,11,16,14,20,37,38,6,36,8,32,21,2,31,22,33,4,1,35,3,25,9,30,26,39,5,23,29,10,13,12,7,19,24,17,34,27,40,28]))) console.log(JSON.stringify(f([54])([54]))) ``` [Answer] # [Perl 6](https://perl6.org), 31 bytes ``` ->\n,\m{n.map:{m.first($_,:k)}} ``` [Try it](https://tio.run/nexus/perl6#TVBdTsJAEH7fU8yDMa2UsrtT@kMD8RA@NjFaFkNk26Y/RkPwQh7BNy6GMwsUkyadmf3@ZobOwEcclrmwX3Bf1msDy9N0VVRBYfdVaF@axd6Gm23b9d7dc7B49w@HE0Efe9P1sITJ8We3rUzn@eFbaxrv@8E//oZlbV@9WbGezPywrfu69dDPxUBeT0TLRbN7qWDiNHKxqduL3HQFnnMOCvPZmLI3ax/2AmDbAUfzqsD6AVzfcnE4VZRhDggRKGGpjiHlGrSbKilFPfTN0C@oj2mKQtwoGSRUJY7IPdWQjQQNkoQiehlprHsGxo70v7/S5G16IZFvAioFpTlCDIoAERdaEjIlU8VxtXYfqASis/rcsRQrqIjRmACmJIK8JhLYWSnmobsBIG@m57QaSrbAjJVplNExQCFbkV/GCcgII84WETQdF0C2USybupwOxDsyW7ItO8YunhuSp0oudz0np994jj8 "Perl 6 – TIO Nexus") ## Expanded: ``` -> \n, \m { # pointy block lambda n.map: { # map over the values in 「n」 m.first( $_, :k ) # return the key 「:k」 of the first occurrence } } ``` 0 indexed [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` m!bV ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=bSFiVg==&input=WzUgMyA0IDFdCls2IDggNCAxIDIgNSAzIDEwMF0=) ### Explanation There's not much to explain here, but it shows off an interesting feature of Japt. Normally, you would pass a function to `m`, like so: ``` mX{VbX} ``` This is basically `U.map(X => V.indexOf(X))` (the `U` is implicit). However, when you're just performing one operation between two values (`b` here, on `V` and `X`), you can just give the operator and the other value and Japt will make a function out of it. This means `mX{X+2}` can be golfed to `m+2`. However, this doesn't work when the values are in the wrong order (`mbV` would be short for `mX{XbV}`). To get around this, you can prepend an exclamation mark to the operator, which tells Japt to swap the operands. This costs an extra byte, but it's still a couple bytes shorter than the alternative. And now you know a little more about Japt. [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` &m ``` This uses 1-indexing. [Try it online!](https://tio.run/nexus/matl#HY6xDcQwDAP7n@Kqr03Rju1Zgozw@5d@KYAKQiJ5Ot/fObcuYqKFgpQXEtFLRCNYzLoMIt5Bk/58bo03IzKvXl5PvLLCV4ac1uzBqpRNR3hgYrBxK4B39eZqo4ZcoKTt4ifGvT7raV3PHw "MATL – TIO Nexus") ### Explanation The meta-function `&` indicates that the next function will use a (function-specific) secondary default in/out specification. For function `m` (`ismember`), `&` specifies that its second output will be produced. This contains the index of (the first occurrence of) each entry of the first input in the second input. [Answer] ## Haskell, 34 bytes ``` n#m=[i|a<-n,(i,e)<-zip[1..]m,e==a] ``` Usage example: `[5,3,4,9,7,5,7] # [3,4,5,7,9]` -> `[3,1,2,5,4,3,4]` The built-in `elemIndex` is in `Data.List` and therefore longer than the version above. The outer loop goes through `n` and the inner loop through pairs of `(i,e)` where `i` is the index of `e` in `m`. Keep the `i` where `e` equals the current element of `n`. [Answer] # R, ~~20~~ 5 bytes 1-indexed; `match` is the builtin function that finds the indices in the second input of the elements of the first, i.e., `match(n,m)` gives the desired answer ``` match ``` thanks to @flodel for pointing out that returning a function is perfectly acceptable as an answer! [Try it online!](https://tio.run/nexus/r#HY4xDsMgEAT7vIIyljZS9gBDpHwmcpPGrvJ/Z84Spxv2GOA83o/t7lUx5CmHwFW2oiXEU6GpkZOuiGvJQ2257ZfaL88qXovcCkpRHdQsIqoUVIOJKTBb9lrEeXa1U4RdLwA/UoTJIwegiQ0bk9tNFGnnS/kqvaU5@djnt33vh/blPP8) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` xLQE ``` [Try it online!](http://pyth.herokuapp.com/?code=xLQE&input=%5B6%2C8%2C4%2C1%2C2%2C5%2C3%2C100%5D%0A%5B5%2C3%2C4%2C1%5D&debug=0) Note that this uses 0-indexing. [Answer] # [J](http://jsoftware.com/), 2 bytes ``` i. ``` This is not a complete program, but a built-in function. Use it as such: ``` echo 6 8 4 1 2 5 3 100 i. 5 3 4 1 ``` [Try it online!](https://tio.run/nexus/j#@5@anJGvYKZgoWCiYKhgpGCqYKxgaGCgkKkHZgIF//8HAA) Note that this uses 0-indexing. [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` {f#} ``` Anonymous block that expects arguments on the stack and leaves the result on the stack. Uses 0-indexing. [Try it online!](https://tio.run/nexus/cjam#K6z7X52mXPu/ruB/tKmCsYKJgqWCuYKpgnmsQjSIB2QpWMYCAA "CJam – TIO Nexus") [Answer] ## Haskell, 43 bytes ``` a*b=[[fst x|x<-zip[0..]b,y==snd x]!!0|y<-a] ``` ``` a*b= -- define function * with 2 args [ |y<-a] -- for each elt in first arg zip[0..]b -- match elts in second arg w/ idxs -- [a,b,c] -> [[0,a],[1,b],[2,c]] [fst x|x<- ] -- take first element in each pair ,y==snd x -- if the index matches !!0 -- first element (always only 1) ``` [Answer] ## Clojure, 25 bytes ``` #(map(zipmap %2(range))%) ``` 0-indexed. [Answer] # Perl 5, ~~38~~ 34 bytes 4 bytes saved thanks to Dada ``` sub{map$x{$_}//($x{$_}=++$x)x0,@_} ``` 1-indexed. Takes the lists **m** and **n** as a single list, like `f(@m,@n)`. The `x0` is just to keep the output from starting with `1,2,3,4,5`, etc. [Answer] # PHP, 56 Bytes [Online Versions](http://sandbox.onlinephpfunctions.com/code/177bee277201e7015aeb5bb84f69db6805bddde4) 0 Indexing output as String ``` <?foreach($_GET[0]as$v)echo" ".array_flip($_GET[1])[$v]; ``` ## PHP, 65 Bytes Output as array ``` <?foreach($_GET[0]as$v)$r[]=array_flip($_GET[1])[$v];print_r($r); ``` PHP, 78 Bytes workaround with `array_map` ``` <?print_r(array_map(function($v){return array_flip($_GET[1])[$v];},$_GET[0])); ``` for not unique arrays replace with `array_flip($_GET[1])[$v]` `array_search($v,$_GET[1])` [Answer] # [Uiua](https://uiua.org), 1 [byte](https://codegolf.stackexchange.com/a/265917/97916) ``` ⊗ ``` [Try it!](https://uiua.org/pad?src=0_2_0__4oqXWzUgMyA0IDFdWzYgOCA0IDEgMiA1IDMgMTAwXQriipdbNSAzIDQgOSA3IDUgN11bMyA0IDUgNyA5XQriipdbNTRdWzU0XQo=) 0-indexed. [Answer] # Bash + coreutils, 51 ``` for n in $1 do grep -wn $n <<<"$2" done|cut -d: -f1 ``` [Try it online](https://tio.run/nexus/bash#bVHLboMwELzzFSOXKCESEmubl5v8SS5VAmkOmAioekjz7XTXSaWowkLyMp7Z8XjbTXKb236Ax8UjpujU4zw0V6Tf/Oux2@1UrBXDvvk5fk1ITw5pS/M9ikQ2NeN0/BgbUascBhbkClSyQ0MQyjKFQ4R/68muUTKrdFLzjnqRK70ejMK91MvcAroEVSANLgsQK6wUOmNpxSYkN9M6fKAS1lEeFARWkxWmKWEqbmAkjWFi8CXRmBATRhLonCOYTNqbWroyVHNmkBEb9qrFnU2MlXtZplbL72FdbtU7Tn0483sV3/6ed@W2dxXg7hV@27on3Bw/e5bwxLp93AWohYo31@Hipxbr1Xjwax5oohbQLnkMeP4F). --- Previous answer: ``` s()(sort -$1k2) nl|s|join -j2 - <(nl<<<"$1"|s)|s n|cut -d\ -f3 ``` [Try it online](https://tio.run/nexus/bash#bZDNbsIwEITveYqRG0SCFClrO39u@iZcKkgEFJwKpyfCs9PdlEoIYVnyavzNjtd9kl5uIUmTMJxHZDF96TTyxylMh2HvkR00MrSJP7Ztq2JSU0inAD9tfpjeroGsN7drFPXDGWMXxs1n6MBGVcDAglyJWk5oiEJ5rrCO8LTudIOKqcpJzSeal6z0@iNK91C/ZkvoClSDNLgsQeywUuicrTWHkLxM63mDKlhHxewgsJuskKaCqbmBkWkMg3MuicfMY8LIBLrgEUwu7U0jXVlqeGaQkRjOaiSdQ4yVd1lG69f/YV1h1Tu2w3znP1R8@f/ehVtd1SyfHuW3lbvL3WY3sCX2DMSnWfo@7/3YY7kIa78E30zooeLkST@lKtoOvrv9Ag). [Answer] # Java 7, 80 bytes ``` void c(int[]a,java.util.List b){for(int i=0;i<a.length;a[i]=b.indexOf(a[i++]));} ``` 0-indexed **Explanation:** ``` void c(int[]a,java.util.List b){ // Method with integer-array and List parameters for(int i=0;i<a.length; // Loop over the integer-array a[i]=b.indexOf(a[i++]) // And change every value to the index of the List ); // End of loop (no body) } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#rZLBb4IwFMbv/hXvCLFpKAWFMA@7b9nBo@FQEV0XLAaqwxj@dtf24ZYsjmTLDiW0vPd9v68PuT/UjYY3cRL0qGVFH5tGnNtsUlSibeH5MgFotdCygOuplhsoPKn0Khfkq@VJthrW/mVbN/YjyEWQyQdBq1Lt9GsmVjJfrKlUm7J72XpmO53mvp/1V4DDcV0Z6cHBGeyFVN5SN1LtVjkI3xIAOFPoYAGqfMfdBWICnEBEgEGfubLC6whgBCpaC@bNCCRYRCAkQw8LAkPgWpbnVpd7Wh81PRhTXSlvENA1YnjdrdY9foJICcyd/nyEBktjV5r@FuGePab6lJ2NeH8v/dMN3GUwdxyaQMxcNDMWdmsWs4YRvoeBM09ccIZzCMNhmRNzGo2hx4O6kbRuLEJJbvp44hw5DppbwSEpQ33Ob/PnOKwwdtPiAbLxFHHsl9T@G2ZxpLSwKaawiDzCoJHtTP7t/uKx6HH0e59@0l8/AA) ``` import java.util.Arrays; class M{ static void c(int[]a,java.util.List b){for(int i=0;i<a.length;a[i]=b.indexOf(a[i++]));} public static void main(String[] a){ int[] x = new int[]{ 5, 3, 4, 1 }; c(x, Arrays.asList(6, 8, 4, 1, 2, 5, 3, 100)); System.out.println(Arrays.toString(x)); x = new int[]{ 5, 3, 4, 9, 7, 5, 7 }; c(x, Arrays.asList(3, 4, 5, 7, 9)); System.out.println(Arrays.toString(x)); x = new int[]{ 1, 2, 3, 4, 5, 6 }; c(x, Arrays.asList(1, 2, 3, 4, 5, 6)); System.out.println(Arrays.toString(x)); x = new int[]{ 16, 27, 18, 12, 6, 26, 11, 24, 26, 20, 2, 8, 7, 12, 5, 22, 22, 2, 17, 4 }; c(x, Arrays.asList(15, 18, 11, 16, 14, 20, 37, 38, 6, 36, 8, 32, 21, 2, 31, 22, 33, 4, 1, 35, 3, 25, 9, 30, 26, 39, 5, 23, 29, 10, 13, 12, 7, 19, 24, 17, 34, 27, 40, 28)); System.out.println(Arrays.toString(x)); x = new int[]{ 54 }; c(x, Arrays.asList(54)); System.out.println(Arrays.toString(x)); } } ``` **Output:** ``` [5, 6, 2, 3] [2, 0, 1, 4, 3, 2, 3] [0, 1, 2, 3, 4, 5] [3, 37, 1, 31, 8, 24, 2, 34, 24, 5, 13, 10, 32, 31, 26, 15, 15, 13, 35, 17] [0] ``` ]
[Question] [ There seems not to be a contest for this one yet. The task is simple. Add the first `n` numbers of the Fibonacci sequence that are even and output the result. This is given by [OEIS A099919](https://oeis.org/A099919), except that sequence is shifted by one, starting with `fib(1) = 0` instead of `fib(1) = 1`. This is code golf. Lowest byte count wins. # Examples ``` n sum 1 0 2 2 3 10 4 44 5 188 6 798 7 3382 8 14328 9 60696 ``` --- [Related](https://codereview.stackexchange.com/questions/35322/project-euler-question-2-sum-of-even-fibonacci-numbers-under-4-million) [Answer] ## Python, 33 bytes ``` c=2+5**.5 lambda n:(7-c)*c**n//20 ``` [Try it online](https://tio.run/nexus/python2#@59sa6RtqqWlZ8qVZpuTmJuUkqiQZ6VhrpusqZWspZWnr29k8D8tv0ghTyEzT6EoMS89VcNQR8HQQNOKi7OgKDOvRCFNI0/zPwA) Magic formula! [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), ~~8~~ ~~7~~ 5 bytes *1 byte saved thanks to @ETHProductions and 2 more saved thanks to @Adnan!* ``` zc»+U ``` [Try it online!](https://tio.run/nexus/oasis#@1@VfGi3duj///8tAQ "Oasis – TIO Nexus") ### Explanation: This uses the same recurrence formula as my MATL answer. [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` f=lambda n:n/2and 4*f(n-1)+f(n-2)+2 ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJBnladvlJiXomCilaaRp2uoqQ2ijDS1jf6n5Rcp5Clk5ikUJealp2oY6igYGmhacXEWFGXmlSgAlWn@BwA "Python 2 – TIO Nexus") [Answer] # [Actually](https://github.com/Mego/Seriously), 6 bytes ``` r3*♂FΣ ``` [Try it online!](https://tio.run/nexus/actually#@19krPVoZpPbucX//5sCAA "Actually – TIO Nexus") Explanation: Every third Fibonacci number (starting from `F_0 = 0`) is even. Thus, the first `n` even Fibonacci numbers are `F_{i*3}` for `i` in `[0, n)`. ``` r3*♂FΣ r [0, n) 3* multiply each element by 3 ♂F retrieve the corresponding element in the Fibonacci sequence Σ sum ``` [Answer] ## JavaScript (ES6), 27 bytes ``` f=x=>x>1&&4*f(x-1)+f(x-2)+2 ``` Recursion to the rescue! This uses one of the formulas on the OEIS page: > > f(n < 1) = 0, f(n) = 4\*a(n+1)+a(n)+2 > > > (but shifted by one because the challenge shifts it by one) [Answer] ## Pyke, 6 bytes ``` 3m*.bs ``` [Try it here!](http://pyke.catbus.co.uk/?code=3m%2a.bs&input=4&warnings=0) ``` 3m* - map(i*3, range(input)) .b - map(nth_fib, ^) s - sum(^) ``` [Answer] # [Perl 6](https://perl6.org), ~~38 35~~ 32 bytes ``` {[+] grep(*%%2,(1,&[+]...*))[^($_-1)]} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V8drR2rkF6UWqChpapqpKNhqKMGFNHT09PS1IyO01CJ1zXUjK39X5xYqaCkEq@gEq8H1qmhqaSQll@kYKinZ/kfAA "Perl 6 – TIO Nexus") ``` {[+] grep(*%%2,(0,1,*+*...*))[^$_]} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V8drR2rkF6UWqChpapqpKNhoGOoo6Wtpaenp6WpGR2nEh9b@784sVJBSSVeQSVeD6xNQ1NJIS2/SMFQT8/yPwA "Perl 6 – TIO Nexus") ``` {[+] (0,1,*+*...*)[3,6...^$_*3]} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V8drR2roGGgY6ijpa2lp6enpRltrGMGZMSpxGsZx9b@L06sVFBSiVdQidcD69HQVFJIyy9SMNTTs/wPAA "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 [+] # reduce with 「&infix:<+>」 ( 0, 1, * + * ... * )\ # fibonacci sequence with leading 0 [ 3, 6 ...^ $_ * 3 ] # every 3rd value up to # and excluding the value indexed by # the input times 3 } ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~36~~ ~~35~~ 33 bytes ``` @(n)filter(2,'FAD'-69,(1:n)>1)(n) ``` [Try it online!](https://tio.run/nexus/octave#@@@gkaeZlplTklqkYaSj7ubooq5rZqmjYWiVp2lnqAmU/J@YV6xhqfkfAA "Octave – TIO Nexus") ### Explanation This anonymous function implements the difference equation `a(n) = 4*a(n-1)+a(n-2)+2` as a [recursive filter](https://en.wikipedia.org/wiki/Infinite_impulse_response): > > `Y = filter(B,A,X)` filters the data in vector `X` with the > filter described by vectors `A` and `B` to create the filtered > data `Y`. The filter is a "Direct Form II Transposed" > implementation of the standard difference equation: > > > `a(1)*y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb) - a(2)*y(n-1) - ... - a(na+1)*y(n-na)` > > > In our case `A = [1 -4 -1]`, `B = 2`, and the input `x` should be a vector of ones, with the result appearing as the last entry of the output `y`. However, we set to `0` the first value of the input so that an initial `0` appears in the output, as required. `'FAD'-69` is just a shorter way to produce the coefficient vector `A = [1 -4 -1]`; and `(1:n)>1` produces the input vector `x = [0 1 1 ... 1]`. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~25~~ 22 bytes ``` 9k5v1+2/3?*1-^5v/0k2/p ``` [Try it online!](https://tio.run/nexus/dc#@2@ZbVpmqG2kb2yvZagbZ1qmb5BtpF/w/78pAA "dc – TIO Nexus") Or save the program in a file and run it by typing ``` dc -f *filename* ``` The program accepts a non-negative integer *n* on stdin, and it outputs the sum of the first *n* even Fibonacci numbers on stdout. (The Fibonacci sequence is taken to start with 0, as per the OP's examples.) --- This program uses the formula (F(3n-1)-1)/2 for the sum of the first n even Fibonacci numbers, where F is the usual Fibonacci function, given by F(0) = 0, F(1) = 1, F(n) = F(n-2) + F(n-1) for n >= 2. --- dc is a stack-based calculator. Here's a detailed explanation: ``` 9k # Sets the precision to 9 decimal places (which is more than sufficient). 5v # Push the square root of 5 1+ # Add 1 to the number at the top of the stack. 2/ # Divide the number at the top of the stack by 2. ``` At this point, the number (1+sqrt(5))/2 is at the top of the stack. ``` 3 # Push 3 on top of the stack. ? # Read a number from stdin, and push it. \* # Pop two numbers from the stack, multiply them, and push the product 1- # Subtract 1 from the number at the top of the stack. ``` At this point, 3n-1 is at the top of the stack (where n is the input), and (1+sqrt(5))/2 is second from the top. ``` ^ # Pop two numbers from the stack (x, then y), compute the power y^x, and push that back on the stack. 5v/ # Divide the top of the stack by sqrt(5). ``` At this point, the number at the top of the stack is (((1+sqrt(5))/2)^(3n-1))/sqrt(5). The closest integer to this number is F(3n-1). Note that F(3n-1) is always an odd number. ``` 0k # Change precision to 0 decimal places. 2/ # Divide the top of the stack by 2, truncating to an integer. p # Print the top of the stack on stdout. ``` [Answer] ## Mathematica, 27 21 bytes *Thanks to xnor for pointing out an alternate formula, alephalpha for correcting for starting index* ``` Fibonacci[3#-1]/2-.5& ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 38 bytes ``` : f 1 1 rot 1 ?do tuck 4 * + loop 2/ ; ``` [Try it online!](https://tio.run/##FYxBCoMwFET3PcUjK2sxRbGbiniQkEUxpC0t/BDi@eMPAzOzmHlRcvkM79ii1ieRUZWlqG9BKMf@Y6bnxl8kMd1ZdJYIR8IaXp1hwubWr6wYJVj2zHIZH8pwQTzu6/XhGsDXEw "Forth (gforth) – Try It Online") Wins over [existing Forth answer](https://codegolf.stackexchange.com/a/199388/78410) by porting [this formula](https://codegolf.stackexchange.com/a/199432/78410): $$ G(0)=G(1)=1, G(n+2)=4G(n+1)+G(n) \\ a(n) = \left\lfloor \frac{G(n)}2 \right\rfloor $$ ``` : f ( n -- a_n ) \ Take single number n and return a_n 1 1 rot 1 \ g0 g1 n 1 ?do \ loop n-1 times tuck 4 * + \ gn-1 gn -> gn gn+1=4gn+gn-1 loop \ end loop; top is gn 2/ \ an = gn/2 (floor division) ; ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ 14 bytes ``` OOi:"t4*b+2+]x ``` [Try it online!](https://tio.run/nexus/matl#@@/vn2mlVGKilaRtpB1b8f@/JQA "MATL – TIO Nexus") ### Explanation This uses one of the recurrence formulas from OEIS: > > a(n) = 4\*a(n-1)+a(n-2)+2 > > > For input *N* the code iterates *N* times, which is 2 more times than necessary. This is compensated for by setting `0`, `0` (instead of `0`, `2`) as initial values, and by deleting the last obtained value and displaying the previous one. ``` OO % Push two zeros as initial values of a(n-2), a(n-1) i % Input N :" % Do this N times t % Duplicate a(n-1) 4* % Multiply by 4 b+ % Bubble up a(n-2) and add to 4*a(n-1) 2+ % Add 2. Now we have 4*a(n-1)+a(n-2)+2 as a(n), on top of a(n-1) ] % End x % Delete last value, a(n). Implicitly display the remaining value, a(n-1) ``` [Answer] ## Batch, 80 bytes ``` @set/at=x=0,y=1 @for /l %%i in (2,1,%1)do @set/az=x+y,y=z+x,t+=x=y+z @echo %t% ``` Uses the fact that every third Fibonacci number is even, and just calculates them three at a time (calculating more than one at a time is actually easier as you don't have to swap values around). I tried the `(Fibonacci(3*n+2)-1)/2` formulation but it's actually a few bytes longer (`t+=` turns out to be quite efficient in terms of code size). [Answer] # C, 82 38 36 bytes *2 bytes saved thanks to @BrainSteel* The formulas at the OEIS page made it much shorter: ``` a(n){return--n<1?0:4*a(n)+a(n-1)+2;} ``` [Try it online!](http://ideone.com/bbQN0T) 82 bytes: ``` x,s,p,n,c;f(N){s=0;p=n=1;c=2;while(n<N){if(~c&1)s+=c,n++;x=p+c;p=c;c=x;}return s;} ``` The first version is 75 bytes but the function is not reusable, unless you always call `f` with greater `N` than the previous call :-) ``` x,s,p=1,n=1,c=2;f(N){while(n<N){if(~c&1)s+=c,n++;x=p+c;p=c;c=x;}return s;} ``` My first answer here. Didn't check any other answers nor the OEIS. I guess there are a few tricks that I can apply to make it shorter :-) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 21 bytes -1 byte thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m) ``` (2+5*.5)∘(⌊20÷⍨*×7-⊣) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X8NI21RLz1TzUccMjUc9XUYGh7c/6l2hdXi6ue6jrsWa/9MetU141Nv3qG@qp/@jruZD640ftU0E8oKDnIFkiIdn8P@0Qyse9W62BAA "APL (Dyalog Unicode) – Try It Online") Uses [xnor's magic formula](https://codegolf.stackexchange.com/a/105530/91097) ``` (2+5*.5)∘(⌊20÷⍨*×7-⊣) (2+5*.5) ⍝ constant c ∘( ) ⍝ joined to 7-⊣ ⍝ 7-c × ⍝ multiplied by * ⍝ input^c 20÷⍨ ⍝ all over 20 ⌊ ⍝ floor ``` # Or with [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 19 bytes (Thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)) ``` (2+√5)∘(⌊20÷⍨*×7-⊣) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X8NI@1HHLFPNRx0zNB71dBkZHN7@qHeF1uHp5rqPuhZr/k971DbhUW/fo76pnv6PupoPrTd@1DYRyAsOcgaSIR6ewf/TDq141LvZEgA "APL (Dyalog Extended) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytesSBCS ``` ⌊⊃⌽(4∘⊥,⊃)⍣⎕÷2 2 ``` [Try it online!](https://tio.run/##Fco9DoJAGIThfk4xpSaasD8sC70mHoOEQEPAWGltISFgZ2JjZTyBhZWVN/kugksxxbx58n29Lk553VaTdJdykqGX/izDd2Glu0v/WoW7lPEp19vvo6lnhrAK2bY98Mhs11DGt4pAlsg2TRH6LKYKChoGFjEcEnikCEzGByNqqojWUnnPJPU0xodkjfZ0kUsddZwoZf8 "APL (Dyalog Unicode) – Try It Online") A full program. ### How it works: the math Uses `a(n) = (Fibonacci(3*n + 2) - 1)/2` from the OEIS page, but we have offset 1 in `a(n)`, so the actual formula is: $$ a(n) = \frac{F(3 n - 1) - 1}{2} = \Bigl\lfloor \frac{F(3 n - 1)}{2} \Bigr\rfloor $$ And using \$ F(2) = F(-1) = 1 \$ and \$ F(n+3) = 4F(n) + F(n-3) \$, we define a derived sequence \$ G(n) \$ such that $$ G(0)=G(1)=\frac12, G(n+2)=4G(n+1)+G(n) $$ Then the desired value is \$ a(n) = \lfloor G(n) \rfloor \$. ### How it works: the code ``` ⌊⊃⌽(4∘⊥,⊃)⍣⎕÷2 2 ⍝ Input: n ÷2 2 ⍝ 2-element vector [.5 .5] i.e. [G(1) G(0)] (4∘⊥,⊃)⍣⎕ ⍝ Derive [G(x+2) G(x+1)] from [G(x+1) G(x)] n times: 4∘⊥ ⍝ G(x+2) = 4×G(x+1) + G(x) ⊃ ⍝ G(x+1) as first element of the vector , ⍝ Concatenate ⊃⌽ ⍝ Get the last element of the result vector, i.e. G(n) ⌊ ⍝ Floor ``` [Answer] ## Haskell (~~32~~ 31 bytes) Saved one byte thanks to @ChristianSievers. Using the formula given in OEIS: `a(n) = 4*a(n-1)+a(n-2)+2, n>1` by Gary Detlefs `a n|n>1=4*a(n-1)+a(n-2)+2|n<2=0` [Answer] ## Mathematica, ~~32~~ 27 bytes ``` Fibonacci[3Input[]-1]/2-1/2 ``` *Credit to **xnor**. Saved 5 bytes thanks to JungHwan Min.* [Answer] # R, 42 bytes Non-recursive solution, as contrast to the earlier solution by @rtrunbull [here](https://codegolf.stackexchange.com/a/105705/59530). ``` for(i in 1:scan())F=F+gmp::fibnum(3*i-3);F ``` Uses the property that each third value of the Fibonacci sequence is even. Also abuses the fact that `F` is by default defined as `FALSE=0`, allowing it as a basis to add the values to. [Answer] # R, ~~42~~ 41 bytes ``` sum(DescTools::Fibonacci(3*(scan():2-1))) ``` > > `scan()` : take `n` from stdin. > > > `scan():2-1` : generate integers from `n` to `2`, decrement by `1`, yielding `n-1` through `1`. > > > `3*(scan():2-1)` : multiply by 3, as every third fibonacci number is even. > > > `DescTools::Fibonacci(3*(scan():2-1))` : Return these fibonacci numbers (i.e. `3` through `(n-1)*3`). > > > `sum(DescTools::Fibonacci(3*(scan():2-1)))` : Sum the result. > > > Previously, I had this uninteresting solution using one of the formulae from OEIS: ``` a=function(n)`if`(n<2,0,4*a(n-1)+a(n-2)+2) ``` [Answer] ## [Japt](http://ethproductions.github.io/japt/), 10 bytes ``` Uo@MgX*3Ãx ``` [Try it online!](https://tio.run/nexus/japt#@x@a7@CbHqFlXKtZ8f@/JQA) Thanks ETHproductions :) [Answer] # PHP, ~~73~~ 70 bytes ``` for(${0}=1;$i++<$argv[1];$$x=${0}+${1})${$x^=1}&1?$i--:$s+=$$x;echo$s; ``` showcasing [variable variables](http://php.net/variables.variable). O(n). Run with `-nr`. **breakdown** ``` for(${0}=1; # init first two fibonaccis (${1}=NULL evaluates to 0 in addition) # the loop will switch between $0 and $1 as target. $i++<$argv[1]; # loop until $i reaches input $$x=${0}+${1} # 3. generate next Fibonacci ) ${$x^=1} # 1. toggle index (NULL => 1 => 0 => 1 ...) &1?$i-- # 2. if current Fibonacci is odd, undo increment :$s+=$$x; # else add Fibonacci to sum echo$s; # print result ``` Numbers are perfectly valid variable names in PHP. But, for the literals, they require braces; i.e. `${0}`, not `$0`. **36 bytes, O(1)** ``` <?=(7-$c=2+5**.5)*$c**$argv[1]/20|0; ``` port of [xnor´s answer](https://codegolf.stackexchange.com/a/105530#105530) [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 47 bytes ``` : f 3 * 1- 0 1 rot 0 do tuck + loop d>s 1- 2/ ; ``` [Try it online!](https://tio.run/##JcvBDoIwEIThu0/xhyNapHpSEp7ECykWiJU1tSa8fd2G0@xkvvUS02wmXyLnO54rNdbQYomSNEch/dyLI0Hkw9h/y34506nfsEWqWWhoKjA9lRav1cX9peOxHz7KW3USbifcEMKyTipl5Tm4@bDlPw "Forth (gforth) – Try It Online") Uses the first formula for OEIS `a(n) = (Fibonacci(3*n + 2) - 1)/2`, since the code for Fibonacci is relatively small in forth. ``` : f \ start a new word definition 3 * 1- \ multiply by 3 and subtract 1 (simplified form of 3*(n-1) + 2 ) 0 1 rot 0 \ create starting Fibonacci values and set up loop parameters do tuck + loop \ Fibonacci code - iteratively copy top value add top 2 stack values d>s \ drop the top stack value 1- 2/ \ subtract 1 and divide result by 2 ; \ end word definition ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` Σ↑Θnİ0İf ``` [Try it online!](https://tio.run/##ARgA5/9odXNr///Oo@KGkc6YbsSwMMSwZv///zI "Husk – Try It Online") painfully slow due to intersecting two infinite lists. [Answer] # PARI/GP, 21 bytes ``` n->fibonacci(3*n-1)\2 ``` `\` is the integer quotient. [Answer] # Excel (Version 1911), 119 Bytes Using iterative calculations (Maximum iteration 1024) ``` A1 'Input B1 =IF(B1=4^5,1,B1+1) C1 =SEQUENCE(A1*3-1)-1 D1 =IF(B1=1,N(C1#>0),IF(C1#=B1,SUM(INDEX(D1#,B1-{0,1})),D1#)) E1 =SUM(D1#*(MOD(D1#,2)=0)) 'Output ``` Tests [![Test tables](https://i.stack.imgur.com/1ESnr.png)](https://i.stack.imgur.com/1ESnr.png) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 46 bytes ``` (:m;5 2 -1??:i 3*5\- 2i-m?*3i*5+2i+m?*+-10+20/ ``` Ignore the floating point, TIO isn't perfect. Yeah, yeah. I cheated. This is just a fancy arithmetic equation to calculate the result. Works in O(1) time, though, assuming a^n can be calculated in O(1) time, which might not be true. ``` (:m;5 2 -1??:i 3*5\- 2i-m?*3i*5+2i+m?*+-10+20/ #Sum the first n even F (:m; #Set m to our input minus one, pop the value from the list. 5 2 -1??:i #Set i to sqrt(5), but don't pop it since we're gonna use it (saves 1 byte) 3*5\- #5-3sqrt(5) 2i-m? #[2-sqrt(5)]^m * #Multiply those two together 3i*5+2i+m?* #Same as the above lines, but + instead of -. + #Add the left part with the right part -10+ #Add -10 (-10+20/ and 10- 20/ are the same size) 20/ #Divide by twenty. ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlv@V/DKtfaVMFIQdfQ3t4qU8FYyzRGV8EoUzfXXss4U8tU2yhTG8jU1jU00DYy0P//HwA "GolfScript – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` L<3*ÅfO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx8ZY63Brmv///5YA "05AB1E – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 15 bytes ``` 0.@{.4*@2++}\*; ``` This one actually does the "operation" using a neat little trick I found. The sum is actually just a 0, 0 leading sequence, with a(n) = 4a(n-1) + a(n-2) + 2. So I do that. ``` 0.@{.4*@2++}\*; #Print the sum of the first n even F 0. #Add two 0s to the stack. [n 0 0] @ #Bring the n up front. [0 0 n] { } #A block of "do something" [0 0 n {}] { }\ #Bring n to the front again [0 0 {} n] { } * #Perform the block n times on the stack below it [0 0] {. } #Duplicate our top element (a[n-1] a[n-1]) { 4* } #Multiply the dupe by 4 (a[n-1] 4a[n-1]) { @ } #Bring up our bottom element (a[n-1] 4a[n-1] a[n-2]) { 2++} #4a[n-1]+a[n-2]+2 = a[n] { } #Stack is now a[n-1] a[n], so we dop the loop until our n is right! ; #The stack has a[n-1] a[n], but our "n" in question is 1 too high #So we pop the top element, leaving a[n-1], W5. ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlv@d9Az6Faz0TLwUhbuzZGy/r/fwA "GolfScript – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Ḷ×3ÆḞS ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//4bi2w5czw4bhuJ5T/zk7w4ck4oKsR/8 "Jelly – Try It Online") Uses the formula $$a(n) = \sum\_{i=0}^{n-1}f(3i)$$ where \$f(n)\$ is the \$n\$-th Fibonacci number ## How it works ``` Ḷ×3ÆḞS - Main link. Take n on the left Ḷ - [0, 1, 2, ..., n-1] ×3 - [0, 3, 6, ..., 3n-3] ÆḞ - n'th Fibonacci number for each S - Sum ``` ]
[Question] [ Use any programming language to display numbers between 1 and 99 (including both) in such a way, so that: * the numbers are separated by single space, * if a number is divisible by 3, it should be in parentheses, * if a number is divisible by 4, it should be in square brackets, * if a number is divisible by both 3 and 4, it should be in both parentheses and square brackets (with square brackets closer to the number). Your program should display exactly: ``` 1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes -1 byte thanks to Kevin Cruijssen ``` тGND4Öi…[ÿ]}N3Öi…(ÿ)]ðý ``` [Try it online!](https://tio.run/##yy9OTMpM/f//YpO7n4vJ4WmZjxqWRR/eH1vrZwzhaBzerxl7eMPhvf//AwA "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~68~~ ~~65~~ 60 bytes ``` i=0 exec"i+=1;print'('[i%3:]+`[i][i%4:]or i`+')'[i%3:],;"*99 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgCu1IjVZKVPb1tC6oCgzr0RdQz06U9XYKlY7ITozFsg0sYrNL1LITNBW14TK6FgraVla/v8PAA "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 61 bytes ``` "+"=c r=""+"" cat(paste0(r+"(",r+""+"[",1:99,r+""+"]",r+")")) ``` [Try it online!](https://tio.run/##K/r/X0lbyTaZq8hWCchQ4kpOLNEoSCwuSTXQKNJW0lDSAZJAiWglHUMrS0soLxYsrKmkqfn/PwA "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 20 bytes ``` ³Ṗµ3,4ṚƬḍד([“])”j)K ``` [Try it online!](https://tio.run/##y0rNyan8///Q5oc7px3aaqxj8nDnrGNrHu7oPTz9UcMcjWggEav5qGFulqb3//8A "Jelly – Try It Online") ### How it works ``` ³Ṗµ3,4ṚƬḍד([“])”j)K Main link. No arguments. ³ Set the return value to 100. Ṗ Pop; yield [1, ..., 99]. µ ) Map the chain in between over [1, ..., 9]; for each integer k: 3,4 Set the return value to [3, 4]. ṚƬ Reverse until a loop is reached. Yields [[3, 4], [4, 3]]. ḍ Test k for divisibility by [[3, 4], [4, 3]], yielding a matrix of Booleans. ד([“])” Repeat the characters of [['(', '['], [']', ')']] as many times as the Booleans indicate. j Join the resulting pair of strings, separated by k. K Join the resulting array of strings, separated by spaces. ``` [Answer] # [D](https://dlang.org/), 110 bytes ``` import std.stdio;void f(){for(int i;i<99;)write(++i%3?"":"(",i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");} ``` [Try it online!](https://tio.run/##S/n/PzO3IL@oRKG4JEUPiDPzrcvyM1MU0jQ0q9PyizQy80oUMq0zbSwtrTXLizJLUjW0tTNVje2VlKyUNJR0MlVNwMxoIBPOiQWJQ5RogpiWlvZKCkCOkqZ17X@w6bmJmXkamgrVXJxAe6y5av8DAA "D – Try It Online") Ported from @HatsuPointerKun's C++ answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ⪫EEE⁹⁹I⊕ι⎇﹪⊕κ⁴ι⪫[]ι⎇﹪⊕κ³ι⪫()ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPwzexAI4tLXUUnBOLSzQ885KLUnNT80pSUzQyNTU1dRRCUovyEosqNXzzU0pz8lEUZAOlTYA4U0cBbKJSdKwSkEeELmNkXRqaEF1AMSUFJU1N6////@uW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⁹⁹ Literal 99 E Map over implicit range ι Current value ⊕ Incrementd I Cast to string E Map over list of strings κ Current index ⊕ Incremented ⁴ Literal 4 ﹪ Modulo ι Current value [] Literal string `[]` ι Current value ⪫ Join i.e wrap value in `[]` ⎇ Ternary E Map over list of strings κ Current index ⊕ Incremented ³ Literal 3 ﹪ Modulo ι Current value () Literal string `()` ι Current value ⪫ Join i.e wrap value in `()` ⎇ Ternary Literal space ⪫ Join list Implicitly print ``` [Answer] # [J](http://jsoftware.com/), ~~54~~ 53 bytes *1 byte less thanks to @Jonah* ``` (*stdout(3|.0=4 3 1 3 4&|,1=":)#3|.']) ([',":)@>i.100 ``` [Try it online!](https://tio.run/##y/r/X0OruCQlv7REw7hGz8DWRMFYwRCITdRqdAxtlaw0lYHC6rGaChrR6jpAroNdpp6hgcH//wA) [Answer] ## C, C++, ~~136~~ ~~133~~ ~~131~~ ~~129~~ ~~128~~ 124 bytes -5 bytes thanks to Zacharý and inspired by write() function in D language ( see Zacharý answer ) -2 bytes thanks to mriklojn -12 bytes for the C version thanks to mriklojn -4 bytes thanks to ceilingcat ``` #include<cstdio> void f(){for(int i=0;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");} ``` ### C Specific Optimization : 115 bytes ``` #include<stdio.h> i;f(){for(;i++<99;)printf("(%s%d%s%s%s"+!!(i%3),i%4?"":"[",i,i%4?"":"]",i%3?"":")",i%99?" ":"");} ``` [Answer] # Powershell, 60 bytes ``` "$(1..99|%{($_,"($_)","[$_]","([$_])")[!($_%3)+2*!($_%4)]})" ``` Explanation: * the array with 4 elements: `$_, "($_)", "[$_]", "([$_])"` * and the index: `[!($_%3)+2*!($_%4)]` * repeat for each number * convert the result to a string Less golfed Test script: ``` $f = { $r = 1..99|%{ ($_, "($_)", "[$_]", "([$_])") [!($_%3)+2*!($_%4)] } "$($r)" } $expected = '1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99)' $result = &$f $result-eq$expected $result ``` Output: ``` True 1 2 (3) [4] 5 (6) 7 [8] (9) 10 11 ([12]) 13 14 (15) [16] 17 (18) 19 [20] (21) 22 23 ([24]) 25 26 (27) [28] 29 (30) 31 [32] (33) 34 35 ([36]) 37 38 (39) [40] 41 (42) 43 [44] (45) 46 47 ([48]) 49 50 (51) [52] 53 (54) 55 [56] (57) 58 59 ([60]) 61 62 (63) [64] 65 (66) 67 [68] (69) 70 71 ([72]) 73 74 (75) [76] 77 (78) 79 [80] (81) 82 83 ([84]) 85 86 (87) [88] 89 (90) 91 [92] (93) 94 95 ([96]) 97 98 (99) ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), ~~41~~ ~~40~~ ~~34~~ 29 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ♀({îû)(î+╫îa_'(\')ßyΓî34α÷ä§ ``` NOTE: It has a trailing space Only my second MathGolf answer.. -5 bytes thanks to *@JoKing*. [Try it online.](https://tio.run/##y00syUjPz0n7///RzAaN6sPr1DUOr3s0baK65uH5lYfXJcara8SA2ecmH15nbOJ0eP7h7YeXHFpeqFD4/z8A) **Explanation:** ``` ♀( # Push 99 (100 decreased by 1) { # Start a loop, which implicitly loops down to (and excluding) 0 û)( # Push string ")(" î+ # Append the 1-indexed index ╫ # Rotate the string once towards the right îa # Push the 1-indexed index of the loop, wrap in a list _ # Duplicate it '( '# Push string "(" \ # Swap the top two items of the stack ') '# Push string ")" ßy # Wrap all three into a list, and join them Γ # Wrap all four into a list # (We now have a list [N, "(N)", "[N]", "([N])"], where N is the index) î # Push the 1-indexed index of the loop 34 # Push 3 and 4 to the stack α # Wrap all three into a list ÷ # Check for each if the index is divisible by it # (resulting in either [0,0], [0,1], [1,0], or [1,1] ä # Convert from binary to integer # (resulting in either 0, 1, 2, or 3 § # Push the string at that index from the array # Push a space # (After the loop, output the entire stack joined together implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` unwords[f"()"3$f"[]"4$show n|n<-[1..99],let f(x:r)m s|mod n m<1=x:s++r|1<3=s] ``` [Try it online!](https://tio.run/##BcFBCoQgFADQfaf4iIuiJpBmU@gNZjdLcRGUNKTf8BsF45zdeW@baV@dK9/Kzx8EBceZ3im@EDiUE68QF9KW1Q0buGXasCenLVyAGeVDi74fR9O5NYGt7yk2Hij7sACCl0LdE7VtzEIOikz5lT8 "Haskell – Try It Online") I wonder if `show[n]` can be used to shorten things up, so far to [no avail](https://tio.run/##jdDNisIwEADgu08xhoYmxBZLelEan2BvHocsKFqUbdKlqShsffZu/6CuruhpGGbmG2YOG/e1z7L6Z2I2RwsKvk/luiw@LHhQB8HJnvNi51BSwogQMSXYBHfIz2C7VDdpU@SkskmAURguFnqW7Usw1Ck0@Q4smDCc69XK6ckIpp2HvTRrA1qtp1M2/@yHYi5E@o@bKjawsmf5LYs@86utfimjz9u@e3yrBjqJHtSx8p4@9t9suXsBJ9JLCWoSe734cC27LAtuwA2cSSJ1WTohiipKpPrz0paj0ms5@sRjHUcNf@rV1/oX). [Answer] ## Lua, ~~161~~ 123 bytes ``` b=""for i=1,99 do;c,d=i%3==0,i%4==0;b=b..(c and"("or"")..(d and"["or"")..i..(d and"]"or"")..(c and")"or"").." "end;print(b) ``` [Try it online!](https://tio.run/##PctRCoAgEATQq8hCoCBR1E/IniT6SLdgITSkzr9JkV/DG2aOexXxCLCnrBh7O02KkguWkJsBsbPcjCWcR9@2Oqg1EmhIGcAU0@v5N9dqqZPvYn6Dgi2SOzPHS3sj8gA "Lua – Try It Online") Ungolfed: ``` b = "" for i = 1, 99 do c = 1 % 3 == 0 d = 1 % 4 == 0 a = "" if c then a = a .. "(" end if d then a = a .. "[" end a = a .. i if d then a = a .. "]" end if c then a = a .. ")" end b = b .. a .. " " end print(b) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ ~~97~~ ~~88~~ ~~86~~ ~~85~~ 84 bytes ``` x=1 while x<100:print((('%s','(%s)')[x%3<1],'[%s]')[x%4<1],'([%s])')[x%12<1]%x,;x+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8LWkKs8IzMnVaHCxtDAwKqgKDOvRENDQ121WF1HXUO1WFNdM7pC1djGMFZHPVq1OBbMNQFzNUB8iLyhEVBEtULHukLb1vD/fwA "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 84 bytes ``` main(i){while(99/i++)printf("%s%s%d%s%s ","("+i%3,"["+i%4,i-1,"]"+i%4,")"+i%3);} ``` There's a null byte at the beginning of each "bracket string". [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzujwjMydVw9JSP1NbW7OgKDOvJE1DSbUYCFNApIKSjhKDhpJ2pqoxkBENYpjoZOoaAjmxEI4SgyZYWtO69v9/AA "C (gcc) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~67~~ 62 bytes ``` "$(1..99|%{'('*!($x=$_%3)+'['*!($y=$_%4)+$_+']'*!$y+')'*!$x})" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lFw1BPz9KyRrVaXUNdS1FDpcJWJV7VWFNbPRrMrQRxTTS1VeK11WOBIiqV2uqaILqiVlPp/38A "PowerShell – Try It Online") Basically a [FizzBuzz](https://codegolf.stackexchange.com/a/58624/42963) using string multiplication times Boolean variables (implicitly cast to 1 or 0). Those strings are left on the pipeline and gathered within a script block inside quotes. Since the default `$OutputFieldSeparator` for an array is spaces, this implicitly gives us space-delimited array elements. [Answer] ## C#, ~~124~~ ~~117~~ 123 bytes -5 bytes thanks to Kevin Cruijssen ``` x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));} ``` Test with : ``` Action<int> t = x=>{for(int i=0;i++<99;)System.Console.Write((i%3<1?"(":"")+(i%4<1?"[":"")+i+(i%4<1?"]":"")+(i%3<1?")":"")+(i>98?"":" "));} t.Invoke(0); Console.ReadKey(); ``` [Answer] # [Red](http://www.red-lang.org), 99 97 bytes ``` repeat n 99[a: b: c: d:""if n% 3 = 0[a:"("c:")"]if n% 4 = 0[b:"["d:"]"]prin rejoin[a b n d c" "]] ``` [Try it online!](https://tio.run/##JYwxCsMwEAS/siwE7C4QNz7wJ9yKKyTdGeRCNiL/V0TczgzT3PruFrQ3vz1@UbGuIQqSIAtMyHKgvvDBhvcQnJiFM/XByx8nYeBolXq3UtH8vEoNEWn8DJmgau8/ "Red – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org), ~~72~~ 66 bytes ``` p [*1..99].map{|x|a=x a="[#{x}]"if x%4<1 a="(#{a})"if x%3<1 a}*' ' ``` Thanks to @jonathan-frech and @conor-obrien for additional trimming. [Answer] # PowerShell, 98 82 74 ~~67~~ ~~63~~ 62 bytes A whopping -31 bytes thanks to @Veskah -5 bytes thanks to @ASCII-only ``` (1..99|%{(($a=($_,"[$_]")[!($_%4)]),"($a)")[!($_%3)]})-join' ' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8NQT8/Sska1WkNDJdFWQyVeRylaJT5WSTNaEchRNdGM1dRRAkppwkSMNWNrNXWz8jPz/v8HAA "PowerShell – Try It Online") I'm still not quite sure what I've done here. [Answer] # perl -E, 60 bytes ``` $,=$";say map$_%12?$_%3?$_%4?$_:"[$_]":"($_)":"([$_])",1..99 ``` Some bytes can be saved if we can use newlines between the numbers: in that case, we can remove the `$,=$";`, change the `map` into a `for` loop, while moving the `say` into the loop. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~51~~ 48 bytes ``` put {$_%3??$^a!!"($a)"}(++$_%4??$_!!"[$_]")xx 99 ``` [Try it online!](https://tio.run/##K0gtyjH7/7@gtEShWiVe1djeXiUuUVFRSUMlUVOpVkNbGyhoAhSMB4pFq8THKmlWVChYWv7/DwA "Perl 6 – Try It Online") [Answer] ## Batch, 145 bytes ``` @set s= @for /l %%i in (1,1,99)do @set/an=%%i,b=n%%4,p=n%%3&call:c @echo%s% :c @if %b%==0 set n=[%n%] @if %p%==0 set n=(%n%) @set s=%s% %n% ``` The code falls through into the subroutine but the string has already been printed by this point so the code executes harmlessly. [Answer] # PHP 103 `for(;$i<1e2;$i++)$a.=$i%12==0?"([$i]) ":($i%3==0?"($i) ":($i%4==0?"[$i] ":"$i "));echo substr($a,5,-1);` <https://www.ideone.com/SBAuWp> [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 100 bytes ``` import StdEnv,Text ``` # ``` join" "[if(n/3*3<n)m("("+m+")")\\n<-[1..99],m<-[if(n/4*4<n)(""<+n)("["<+n<+"]")]] ``` [Try it online!](https://tio.run/##JYyxDoIwFEV3vqJ5Lq0FjIGFpGw6mDiY4AYdGqCmpn01WI3@vBV0OucmJ7e3o8Lo/PCwI3HKYDTu5qdAmjDs8Zmex1eITVBTSFZEk5pcvUEg0BpNcVOsC4HMUaDAHQcGrOtQZO02z6tKpm7WX1euy7mjAIIvaBcKDhKYlEk9/8ZPr6263GN2OMbdG5Uz/X@crAraT@4L "Clean – Try It Online") [Answer] # [sfk](http://stahlworks.com/dev/swiss-file-knife.html), 225 bytes ``` for n from 1 to 99 +calc -var #(n)/3+1/3 -dig=0 +calc -var #text*3-#(n) +setvar t +calc -var #(n)/4 -dig=0 +calc -var #text*4-#(n) +xed -var _0_#(t)\[#(n)\]_ _*_#(t)#(n)_ +xed _0*_([part2])_ _?*_[part2]_ +xed "_\n_ _" +endfor ``` [Try it online!](https://tio.run/##dY9BDoIwEEWvMoFNaUMowoYF8SCUTAi0xqitKRPD7WsrbIxx@d@8t5jV3EIwzoMF490DaiAHXQdinu4zlK/JQ85sUTWirhool@ull19H0hvxpkwSiFVTgvSTt3/T9kg3vewYJeaMCjUkrkYE5B@QJu4eSo5seE6eTmNkeOZ4rEPIUNnIMxDaLvG7EN4 "sfk – Try It Online") [Answer] # Bash, 61 bytes *-14 bytes, thanks to Dennis* ``` seq 99|awk '{ORS=" ";x=$1%4?$1:"["$1"]";print$1%3?x:"("x")"}' ``` # explanation Pretty straightforward: * `seq` produces 1..99 * we pipe that into `awk` with the output record separator (`ORS`) set to space so the output is a single line. * the main awk body just adds "[]" when the number is divisible by 4, and then adds, on top of that, "()" when divisible by 3. [Try it online!](https://tio.run/##S0oszvj/vzi1UMHSsiaxPFtBvdo/KNhWSUHJusJWxVDVxF7F0EopWknFUClWybqgKDOvBChqbF9hpaShVKGkqVSr/v8/AA "Bash – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 57 bytes ``` f=(n=99)=>n&&f(n-1)+(s=n%4?n:`[${n}]`,n%3?s:`(${s})`)+' ' ``` [Try it online!](https://tio.run/##BcHbCkBAFAXQX/Hgck4uJV5MDR8iNcKItEeOvMi3j7X28RllurbzzuHmxXurCbppWLeIY0vIS05JNKK6gzJ9@OIbTIao6kQZCl/52HCaBImfHMQdS3G4lSwx@x8 "JavaScript (Node.js) – Try It Online") Changed to community cuz the optimize rely too much on it [Answer] # PHP, 65 bytes ``` while($i++<99)echo$i%4?$i%3?$i:"($i)":($i%3?"[$i]":"([$i])")," "; ``` or ``` while($i++<99)echo"("[$i%3],"["[$i%4],$i,"]"[$i%4],")"[$i%3]," "; ``` (requires PHP 5.5 or later) Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/7ea8b8e434dfb5609faba67eefc6b9f680441ae2). [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` i=0 exec"i+=1;u=i%3/-2*(i%4/-3-1);print'([%0d])'[u:7-u:1+(i%3<1<=i%4)]%i,;"*99 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgCu1IjVZKVPb1tC61DZT1Vhf10hLI1PVRF/XWNdQ07qgKDOvRF0jWtUgJVZTPbrUyly31MpQG6jC2MbQBqjBRDNWNVPHWknL0vL/fwA "Python 2 – Try It Online") I envisioned this cool approach slicing `'([%0d])'` but I can't get the expressions any shorter. [Answer] # Java 8, ~~92~~ 91 bytes *-1 byte thanks to @Dana* `i->{for(;i++<99;)out.printf((i>1?" ":"")+(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i),i);}` [Try it online!](https://tio.run/##LY/NqsIwEIX3eYohUEjotaj3bmr8wQdw5VJcxP4xvW1TkihI6bPXSXAWA9@cmZyTVr/0yozV0Jb/C/ajsR6c1x4LaEnKOj002fXtfNVn5ukVY0WnnYOLxoFNDAAHX9laFxWcYQIaUL0MlkDbgkRAqcJ4ZtS@L58B4bDg6jjVxgqFabrPcyXpIhst3dRC4HFz4sB3nMtUYLLZ7onFLSnvku8w@Y2YlBH@AgSJQP6Q37yo4DY@Hx25fU1jqJ5ii6snk@Z2B20bJ2lxirExfFCspYpp5@UD) Alternative solution, 82 bytes (with trailing space in the output - not sure if that's allowed): `i->{for(;i++<99;)out.printf((i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i)+" ",i);}` Explanation: `for(;i++<99;)` - a for loop that goes from the value of `i` (reused as input, taken to be 0 in this case) to 99 `out.printf(<part1>+<part2>,i);` - formats the string before immediately printing it to stdout with the value of `i` where `<part1>` is `(i>1?" ":"")` - prints the space *before* printing the number *unless* that number is 1, in which case it omits the space and `<part2>` is `(i%12<1?"([%d])":i%3<1?"(%d)":i%4<1?"[%d]":i)` - if `i` is divisible by both 3 and 4, `i` has both square and round brackets around it; else if `i` is divisible by 3, `i` has round brackets; else if `i` is divisible by 4, `i` has square brackets; else, `i` has no brackets. ]
[Question] [ Let \$n=42\$ (Input) Then divisors are : 1, 2, 3, 6, 7, 14, 21, 42 Squaring each divisor : 1, 4, 9, 36, 49, 196, 441, 1764 Taking sum (adding) : 2500 Since \$50\times 50=2500\$ therefore we return a truthy value. If it is not a perfect square, return a falsy value. # Examples : ``` 42 ---> true 1 ---> true 246 ---> true 10 ---> false 16 ---> false ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each language wins Thanks to @Arnauld for pointing out the sequence : [A046655](https://oeis.org/A046655) [Answer] # [R](https://www.r-project.org/), ~~39~~ 37 bytes ``` !sum((y=1:(x=scan()))[!x%%y]^2)^.5%%1 ``` [Try it online!](https://tio.run/##K/r/X7G4NFdDo9LW0EqjwrY4OTFPQ1NTM1qxQlW1MjbOSDNOz1RV1fC/kYnZfwA "R – Try It Online") Uses the classic "test if perfect square" approach, taking the non-integral part of the square root `S^.5%%1` and taking the logical negation of it, as it maps zero (perfect square) to `TRUE` and nonzero to `FALSE`. Thanks to [Robert S](https://codegolf.stackexchange.com/users/81727/robert-s) for saving a couple of bytes! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÑnOŲ ``` **[Try it online!](https://tio.run/##yy9OTMpM/f//8MQ8/8Othzb9/29iBAA "05AB1E – Try It Online")** ### How? ``` ÑnOŲ Ñ - divisors n - square O - sum Ų - is square? ``` [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~434~~ ~~428~~ 415 bytes ``` ,.Ajax,.Ford,.Puck,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy.Scene V:.Ajax:You be the sum ofyou a cat.Ford:Is the remainder of the quotient betweenyou I worse a cat?[Exit Ajax][Enter Puck]Ford:If soyou be the sum ofyou the square ofI.[Exit Puck][Enter Ajax]Ford:Be you nicer I?If solet usScene V.[Exit Ford][Enter Puck]Puck:Is the square ofthe square root ofI worse I?You zero.If notyou cat.Open heart ``` [Try it online!](https://tio.run/##bVDNasMwDH4VPUDwoezkS9igA8Ngg8JglB68RCHeWqu1Zdr05TPL8UYOuwjrs74fKZ6P89yoxy97a9Qzhb5Rb6n7zkjHYLTadehRHvutZwwgg2B9DzJ7kKJfXGT0wMTjVOffdVHUH5TgE4FHhJhOQMOUAQud5eKlTSx/AU/W@T7L01CASyJ26DmT@YrohWbgSiHiQm/325vjkuZQk0nsJZAZINL0n3XpLskGzIBRi0ghrtZbRJ4QhOFdl2HTFs0jMqRYV6zscod1BCm/i/15rZpAxOJe1zGtHOmOgVT28MTiKgd6PeejjmgDz/PD5gc) *-13 bytes thanks to Jo King!* Outputs `1` for true result, outputs `0` for false result. [Answer] # JavaScript (ES7), ~~ 46 44 ~~ 42 bytes *Saved 1 byte thanks to @Hedi* ``` n=>!((g=d=>d&&d*d*!(n%d)+g(d-1))(n)**.5%1) ``` [Try it online!](https://tio.run/##dczRCoIwGIbh865iHSj/P3M2Mc8mdB0RMdwm5tpkWtDVL4NOJPxOH773Ll9yakM/zrnzSkcjohPNHqATSjQqTRVVdA8uUZh1oHKOCA4pZaeEY2y9m7zVzPoODFQlIiFFQebw1Lu18S9tWFnVi278jr@mkXb6w3qFK70wxs4hyPeSWIZX9pAjwO1ABiSiIQPJCEdmejvrAAYxfgA "JavaScript (Node.js) – Try It Online") ## Commented ``` n => // n = input !( // we will eventually convert the result to a Boolean (g = d => // g is a recursive function taking the current divisor d d && // if d is equal to 0, stop recursion d * d // otherwise, compute d² * !(n % d) // add it to the result if d is a divisor of n + g(d - 1) // add the result of a recursive call with the next divisor )(n) // initial call to g with d = n ** .5 % 1 // test whether the output of g is a perfect square ) // return true if it is or false otherwise ``` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` lambda n:sum(i*i*(n%i<1)for i in range(1,n+1))**.5%1==0 ``` [Try it online!](https://tio.run/##FckxDsIwDAXQGU7hpVKSWqiOSoeKnAQYgiBgif5WoQyc3qhvfctvfc2IVtLF3nm63TNh/Hwnp0GDQ6Mn8WWupKSgmvF8OGG04n0Ih2MjKXW2PbY/95GFYz@wdCzDddzvlqpYqTh4sz8 "Python 2 – Try It Online") [Answer] # [Neim](https://github.com/okx-code/Neim), 5 bytes ``` 𝐅ᛦ𝐬q𝕚 ``` Explanation: ``` 𝐅 Factors ᛦ Squared 𝐬 Summed 𝕚 is in? q infinite list of square numbers ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCa0PZy8DUmsKP8ydOuv/f0MzAA "Neim – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~67~~ ~~63~~ ~~60~~ 59 bytes *-1 bytes* thanks to @JonathanFrech ``` i,s;f(n){for(s=i=0;i++<n;)s+=n%i?0:i*i;n=sqrt(s);n=n*n==s;} ``` [Try it online!](https://tio.run/##dctBCsIwEIXhfU8hhcJM00CMxYUxeBE3JZIy0I6a6a706sbi2rzVg48/6DGEnKkTF4Fxjc8E4skbR0pd2aEozw3dzIVacuzlnRYQ3B@37L24Lc8DMWC1Vod9r0S8RKibx53rLkJvEd1fOZbA9udiY4rya7b8CXEaRsl6Ptmsp/kL "C (gcc) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~12~~ 8 bytes ``` f^₂ᵐ+~^₂ ``` -4 bytes thanks to Fatelize cause i didn't realize brachylog has a factors functions # explanation ``` f^₂ᵐ+~^₂ # full code f # get divisors ^₂ᵐ # square each one + # added together ~^₂ # is the result of squaring a number ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koKtrp6BUrvaobcOjpqZHHcuVSopKU5Ue7uqsAXHSEnOKwbzah1sn/E@LA6oBMrTrQIz//6NNjHQUDHUUjEzMgLQBEJvFAgA "Brachylog – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes ``` ─²Σ° ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RlIZDm84tPrTh/38TIwA "MathGolf – Try It Online") ## Explanation ``` ─ Get all divisors as list (implicit input) ² Square (implicit map) Σ Sum ° Is perfect square? ``` Very similar to other answers, compared to 05AB1E I gain one byte for my "is perfect square" operator. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` Z\UsX^tk= ``` [Try it online!](https://tio.run/##y00syfmf8D8qJrQ4Iq4k2/a/S1RFSOx/EyMuQy4jEzMuQwMuQzMA "MATL – Try It Online") As simple as it gets ``` Z\ % Divisors of (implicit) input U % Square s % Sum X^ % Square root t % Duplicate this value k= % Is it equal to its rounded value? ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` F²SƲ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPUYlQzIlQjJTJUMzJTg2JUMyJUIyJmZvb3Rlcj0maW5wdXQ9NDIlMjAlMjAtJTNFJTIwVHJ1ZSUwQTElMjAlMjAlMjAtJTNFJTIwVHJ1ZSUwQTI0NiUyMC0lM0UlMjBUcnVlJTBBMTAlMjAlMjAtJTNFJTIwRmFsc2UlMEExNiUyMCUyMC0lM0UlMjBGYWxzZSZmbGFncz1DZQ==) #### Explanation ``` F²SƲ # Implicit input F # Factors ² # Square S # Sum Ʋ # Perfect square # Implicit output ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~68~~ 56 bytes ``` param($n)1..$n|%{$a+=$_*$_*!($n%$_)};1..$a|?{$_*$_-eq$a} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVP01BPTyWvRrVaJVHbViVeC4gUgcKqKvGatdYgucQa@2qwuG5qoUpi7f///02MAA "PowerShell – Try It Online") ~~Seems long ...~~ *-12 bytes thanks to mazzy* Does exactly what it says on the tin. Takes the range from `1` to input `$n` and multiplies out the square `$_*$_` times whether it's a divisor or not `!($n%$_)`. This makes divisors equal to a nonzero number and non-divisors equal to zero. We then take the sum of them with our accumulator `$a`. Next, we loop again from `1` up to `$a` and pull out those numbers where `|?{...}` it squared is `-eq`ual to `$a`. That is left on the pipeline and output is implicit. Outputs a positive integer for truthy, and nothing for falsey. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ ~~9~~ 7 bytes *-2 bytes from @Giuseppe and another -2 from @Shaggy* ``` â x²¬v1 ``` --- ``` â x²¬v1 Full program. Implicity input U â get all integer divisors of U x² square each element and sum ¬ square root result v1 return true if divisible by 1 ``` [Try it online!](https://tio.run/##y0osKPn///AihYpDmw6tKTP8/9/ECAA "Japt – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes ``` 0=1|.5*⍨2+.*⍨∘∪⍳∨⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///38DWsEbPVOtR7wojbT0Q9ahjxqOOVY96Nz/qWPGoa9H/tEdtEx719j3qm@rp/6ir@dB640dtE4G84CBnIBni4Rn8/1HvqupHvVttDa3UQ4pKU9UfdbeouyXmFKeq1x5akXZohYmRgqGCkYmZgqGBgqEZAA "APL (Dyalog Unicode) – Try It Online") Anonymous lambda. Returns 1 for truthy and 0 for falsy (test cases in TIO are prettified). Shoutouts to @H.PWiz for 4 bytes! ### How: ``` 0=1|.5*⍨2+.*⍨∘∪⍳∨⊢ ⍝ Main function, argument ⍵ → 42 ∨⊢ ⍝ Greatest common divisor (∨) between ⍵ (⊢) ⍳ ⍝ and the range (⍳) [1..⍵] ∪ ⍝ Get the unique items (all the divisors of 42; 1 2 3 6 7 14 21 42) ∘ ⍝ Then ⍨ ⍝ Swap arguments of 2+.* ⍝ dot product (.) of sum (+) and power (*) between the list and 2 ⍝ (sums the result of each element in the vector squared) ⍨ ⍝ Use the result vector as base .5* ⍝ Take the square root 1| ⍝ Modulo 1 0= ⍝ Equals 0 ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~26~~ ~~25~~ 22 bytes **Solution:** ``` {~1!%+/x*x*~1!x%:1+!x} ``` [Try it online!](https://tio.run/##y9bNz/7/v7rOUFFVW79Cq0LLqsI2vkLVylBbsaLWQd3ESMFQwcjETMHQQMHQ7P9/AA "K (oK) – Try It Online") **Explanation:** ``` {~1!%+/x*x*~1!x%:1+!x} / the solution { } / lambda taking x as input !x / range 0..x-1 \ 1+ / add 1 | x%: / x divided by and save result into x | 1! / modulo 1 | get divisors ~ / not | x* / multiply by x / x* / multiply by x (aka square) > square +/ / sum up > sum up % / square root \ 1! / modulo 1 | check if a square ~ / not / ``` **Notes:** * -1 bytes taking inspiration from the [PowerShell](https://codegolf.stackexchange.com/a/171955/69200) solution * -3 bytes taking inspiration from the [APL](https://codegolf.stackexchange.com/a/171960/69200) solution [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 23 bytes ``` n->issquare(sigma(n,2)) ``` [Try it online!](https://tio.run/##FYdBCoAgEAC/snjaBYUS8ZYfiQ4eUoRaNq1Drzc7DDMjsRaTpSdYoLMJpbXriXXHVvIZkbUl6lHkeJHBBJBa@B6p/lGQkIk0rM5qmDVY54engd@ofw "Pari/GP – Try It Online") [Answer] ## Matlab, 39 37 bytes ``` @(v)~mod(sqrt(sum(divisors(v).^2)),1) ``` Unfortunately, it doesn't work on Octave (on tio) so no tio link. **Note** As @LuisMendo stated, `divisors()` belongs to Symbolic Toolbox. [Answer] # [Haskell](https://www.haskell.org/), ~~78~~ ~~64~~ 53 bytes *-14 bytes thanks to [Ørjan Johansen](/u/66041). -11 bytes thanks to [ovs](/u/64121).* ``` f x=sum[i^2|i<-[1..x],x`mod`i<1]`elem`map(^2)[1..x^2] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwra4NDc6M86oJtNGN9pQT68iVqciITc/JSHTxjA2ITUnNTchN7FAI85IEywbZxT7PzcxM0/BVgEo7BuvoFFQlJlXopemqRBtYqRjqGNkYqZjaKBjaBb7HwA "Haskell – Try It Online") Hey, it's been a while since I've... written *any* code, so my Haskell and golfing might a bit rusty. I forgot the troublesome Haskell numeric types. :P [Answer] # [Pyt](https://github.com/mudkip201/pyt), 7 bytes ``` ð²ƩĐř²∈ ``` [Try it online!](https://tio.run/##ARgA5/9weXT//8OwwrLGqcSQxZnCsuKIiP//NDI "Pyt – Try It Online") ### Explanation ``` Implicit input ð Get list of divisors ² Square each element Ʃ Sum the list [n] Đ Duplicate the top of the stack ř² Push the first n square numbers ∈ Is n in the list of square numbers? Implicit output ``` --- ``` ð²Ʃ√ĐƖ= ``` [Try it online!](https://tio.run/##ARcA6P9weXT//8OwwrLGqeKImsSQxpY9//80MQ "Pyt – Try It Online") ### Explanation ``` Implicit input ð Get list of divisors ² Square each element Ʃ Sum the list [n] √ Take the square root of n Đ Duplicate the top of the stack Ɩ Cast to an integer = Are the top two elements on the stack equal to each other? Implicit output ``` --- [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), ~~4430~~ 4305 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Cyclone.0 is waiting at Starchild Numerology.0 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 2 l.Pickup a passenger going to Rob's Rest.Pickup a passenger going to Addition Alley.Go to Rob's Rest:w 1 r 2 l 1 r.Go to Cyclone:s 1 l 1 l 2 l.[B]Pickup a passenger going to Divide and Conquer.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 r 3 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:w 1 r 3 r 1 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Cyclone.Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l.Go to Zoom Zoom:n 1 r.Go to Cyclone:w.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Trunkers.Go to Sunny Skies Park:n 1 r.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan C if no one is waiting.Pickup a passenger going to Riverview Bridge.Go to Sunny Skies Park:n.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Cyclone.Go to Riverview Bridge:n 1 r 1 r.Go to Cyclone:w 2 l.Pickup a passenger going to Cyclone.Go to Sunny Skies Park:n 1 r.Go to Cyclone:n 1 l.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to Addition Alley.Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r.Pickup a passenger going to Addition Alley.Go to Addition Alley:s 1 l 1 l 2 r 1 r 1 r.Pickup a passenger going to Rob's Rest.Go to Rob's Rest:n 1 l 1 l 1 l 2 r 1 r.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Magic Eight.Go to Sunny Skies Park:n 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Magic Eight.Go to Magic Eight:s 1 l 2 r.Switch to plan D if no one is waiting.Pickup a passenger going to Addition Alley.Go to Cyclone:n 1 l 2 r.Switch to plan B.[C]Go to Sunny Skies Park:n.Pickup a passenger going to Cyclone.Pickup a passenger going to Addition Alley.Go to Cyclone:n 1 l.Switch to plan B.[D]Go to Cyclone:n 1 l 2 r.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 r.Go to Rob's Rest:s 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:s 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Cyclone.Go to Zoom Zoom:n.Go to Cyclone:w.[E]Pickup a passenger going to Joyless Park.Pickup a passenger going to Divide and Conquer.Go to Joyless Park:n 2 r 2 r 2 l.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 2 r 2 r 2 l.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Magic Eight.1 is waiting at Starchild Numerology.Go to Starchild Numerology:e 1 r 3 r 1 l 1 l 2 l.Pickup a passenger going to Magic Eight.Go to Magic Eight:w 1 r 2 r 1 r.Switch to plan F if no one is waiting.Pickup a passenger going to Riverview Bridge.Go to Joyless Park:e 2 l 4 r.Pickup a passenger going to Cyclone.Pickup a passenger going to The Underground.Go to The Underground:w 1 l.Pickup a passenger going to Cyclone.Go to Fueler Up:s.Go to Riverview Bridge:n 3 l.Go to Cyclone:w 2 l.Switch to plan E.[F]Go to Joyless Park:e 2 l 4 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 2 l 2 l.Pickup a passenger going to Multiplication Station.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 2 l 1 r 3 l.Pickup a passenger going to Knots Landing.Go to Knots Landing:e 4 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:w 1 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r. ``` [Try it online!](https://tio.run/##zVjJbtswEP2VufUmNLLRg2/xFqCrEScoUMMHRhrJhBnSISW7/npXEr1QiyVaUYseZAPc5s2bmceRIvKbHg4PAiIBM6Ei@BEE1MPBDu6AJY9M/50Z9dbxBghsiFLIQ5QQCsrDdNfTCmFIXpAFVK1Q7h19WHF4oE4n1p422ntMcHQ@AlWwIzRKx0kE84hIb0WZD9/jV5SCiXBvt0jDqZoa8CMk/bgNjj6Klw8KHlFFtcvufT8BJDjcM4Yn85e9GbMyNZZxoaePXp850mAWw2WdoTHdUh@BcB9Ggr/FKJ27DgiR0GsgotLD/ODRy16WP9I66nk2zuGp3TuPOd/DfE1RwYzItXMjZ9pmeSIx72aBuhV@EdAAzahm/uiFv4R4zX407wXvd915PXmLCUvybyQkx3pXnmTM1yjVNV9MpKe1Om1vQaD35we15DjzHY28VTq9YYTDCGgAXEDCiJHb9XVKtyi3FHcwlNQPr4aFd0dwPgGKAI5lVRHiRs1pyKyqvOGNwfgWs4huGPVIVrCJEqT/bbZoy9WTRzFL66ffRlAMyVSGZDIrQbGRKFNs7WTKuAFKGIt3iWyU91q@SUg9mNBwFdXHvqWqWu27DaAxcgl9sZzHt5dzZSjzV0SFoaGzGC1bFb6N982YKvCMl9ewd6ZDpcUWupGrM7f1ZW2f2zYE520YF2XpklxMapukz2LPUL2nMzBPMHoC93yNX9T8pFJdMJAD/teQVHj979snU0ve28Gi0Xe2lVpTyU5Uai8KRT3trDnJhRaz0PUty7Dp3eyZ@yhDKWLuG69mxuix8bIvx2mMLJl93gzU9Y6nV5GVblkXJ85iumzNwc8ViRLxSh0a0yBAidzDFuJlXzD/Xe9UTYE@vHIuK0xm9aL3hYtIwdekqtO01mfmxpIw9Tv8RNCciMYnCqf80YKfPzEcDm7/0x8 "Taxi – Try It Online") I went to a lot of places in Townsburg that I've never visited before for this program. Because this program is HUGE (mainly due to the fact that there isn't a one-stop way to take square roots; I still don't actually do that, though), I'm going to attempt to sketch out an explanation of this program. ``` Go to Post Office:w 1 l 1 r 1 l. [Take an input line from STDIN.] Pickup a passenger going to The Babelfishery. Go to The Babelfishery:s 1 l 1 r. [Take it to The Babelfishery, which converts the string to a double.] [If you were to give it a double, it gives back a string.] Pickup a passenger going to Cyclone. [We're going to clone this number by sending it to the Cyclone.] 0 is waiting at Starchild Numerology. [In Taxi, numeric passengers are introduced once they wait at Starchild Numerology.] [This passenger will be our running squares total.] 0 is waiting at Starchild Numerology. [This passenger will be our counter, going from 1 to the inputted number.] [Yes, it's starting at 0 here, but it is incremented at the start of our loop.] Go to Starchild Numerology:n 1 l 1 l 1 l 2 l. Pickup a passenger going to Rob's Rest. Pickup a passenger going to Addition Alley. Go to Rob's Rest:w 1 r 2 l 1 r. Go to Cyclone:s 1 l 1 l 2 l. [Drop off the squares total at Rob's Rest. We'll pick it back up later when we need it.] [Also, do the actual cloning of the inputted number.] [At the start of each loop, our only passenger is the counter, going to Addition Alley.] [B] Pickup a passenger going to Divide and Conquer. [Pick up one of the clones of the inputted number.] [We will leave the other clone here for later.] 1 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 r 3 l. Pickup a passenger going to Addition Alley. Go to Addition Alley:w 1 r 3 r 1 r 1 r. Pickup a passenger going to Cyclone. [Pick up the number 1, and add it to the counter, then pick up the result.] [This new passenger is our new counter.] Go to Cyclone:n 1 l 1 l. Pickup a passenger going to Sunny Skies Park. Pickup a passenger going to Divide and Conquer. [First we pick up the other clone of the inputted number, going to Sunny Skies Park.] [Sunny Skies Park is basically a First-In-First-Out queue, where we will stick it for later.] [Then we pick up a clone of the counter which we just dropped off, so we can divide the input by it.] [We will leave the other clone here for later.] Go to Divide and Conquer:n 2 r 2 r 1 r. Pickup a passenger going to Cyclone. [Divide the inputted number by the counter, and prepare to clone it.] Go to Sunny Skies Park:e 1 l 1 l 2 l 1 l. [Drop off our clone of the inputted number at Sunny Skies Park.] Go to Zoom Zoom:n 1 r. [Can't forget to get gas!] [Zoom Zoom is a close gas station, and we have so many credits that one stop here every iteration fills us up completely.] Go to Cyclone:w. Pickup a passenger going to Sunny Skies Park. Pickup a passenger going to Equal's Corner. Pickup a passenger going to Trunkers. [First we pick up the other clone of the counter, going to Sunny Skies Park for later.] [Then we pick up a clone of the division result, going to Equal's Corner.] [Equal's Corner takes multiple numeric passengers, and returns the value of one of them if they are equal, but otherwise it returns no one.] [Finally we pick up the other clone of the division result, going to Trunkers.] [Dropping off a passenger at Trunkers is equivalent to the floor function. We need it here because division results are "exact".] [(Well, as exact as double precision arithmetic can be.)] [We will compare the result of this to the exact result of the division.] Go to Sunny Skies Park:n 1 r. [Drop off our clone of the counter at Sunny Skies Park.] Go to Trunkers:s 1 l. Pickup a passenger going to Equal's Corner. Go to Equal's Corner:w 1 l. [Compare the exact division result with the floored division result.] [If they are equal, then the value of one of them will be waiting.] [This also means that the counter is a divisor of the input, and we should add the square of the counter to our running squares total.] [If they are not equal, no one will be waiting, the counter is not a divisor of the input, and nothing should happen.] Switch to plan C if no one is waiting. [This is Taxi's only conditional operator.] [It jumps to a bracketed label (in this case, C) if there is no one waiting at this stop.] [Of course, there is an unconditional version of this, too.] [If we are on this path, we are adding the square of the counter to our running squares total.] Pickup a passenger going to Riverview Bridge. [We don't actually need the passenger that's waiting here (and leaving it there will not work at all).] [So what do you do when you have a pesky passenger you don't want? You take them to Riverview Bridge!] [Riverview Bridge has a lovely view, but passengers dropped off there always seem to fall in the river.] [This means you don't collect your fare for bringing them there, but at least the pesky passenger is gone.] Go to Sunny Skies Park:n. Pickup a passenger going to Sunny Skies Park. Pickup a passenger going to Cyclone. [We want to pick up the counter (so we can multiply it by itself). That dang input is in the way, but we still need it.] [So what do we do? We just take it back to where it was waiting!] [Yup, even though one would never do this in real life, a passenger's current location is a perfectly legal destination in Taxi.] Go to Riverview Bridge:n 1 r 1 r. [So long, Equal's Corner result!] Go to Cyclone:w 2 l. Pickup a passenger going to Cyclone. Go to Sunny Skies Park:n 1 r. [We clone the counter so we can still use it, then we drop the inputted number back at Sunny Side Park.] [Again, we will leave the other clone here for later.] Go to Cyclone:n 1 l. Pickup a passenger going to Multiplication Station. Pickup a passenger going to Multiplication Station. Go to Multiplication Station:s 1 l 2 r 4 l. [Square the counter.] Pickup a passenger going to Addition Alley. Go to Rob's Rest:s 1 r 2 l 1 l 1 r 1 r. Pickup a passenger going to Addition Alley. Go to Addition Alley:s 1 l 1 l 2 r 1 r 1 r. Pickup a passenger going to Rob's Rest. Go to Rob's Rest:n 1 l 1 l 1 l 2 r 1 r. [Pick up the running squares total from Rob's Rest, add it to the square of the counter, then bring it back.] Go to Cyclone:s 1 l 1 l 2 l. Pickup a passenger going to Magic Eight. [Pick up the counter, going to Magic Eight.] [Magic Eight takes two numeric passengers, and returns the first passenger if it is less than the second, but otherwise it returns no one.] [We will compare the counter to the inputted number...] Go to Sunny Skies Park:n 1 r. Pickup a passenger going to Cyclone. Go to Cyclone:n 1 l. Pickup a passenger going to Cyclone. Pickup a passenger going to Magic Eight. [...who we take now, so we can make a clone of it and compare it to the counter.] Go to Magic Eight:s 1 l 2 r. Switch to plan D if no one is waiting. [Compare.] [If the counter is waiting here, the loop is to continue.] [If not, switch to plan D, end the loop, and start detecting whether or not the running squares total is a square itself.] Pickup a passenger going to Addition Alley. Go to Cyclone:n 1 l 2 r. Switch to plan B. [Reset everything, and loop back to the start of plan B.] [C] [If we are on this path, the counter is not a divisor of the inputted number, but the loop should continue anyways.] Go to Sunny Skies Park:n. Pickup a passenger going to Cyclone. Pickup a passenger going to Addition Alley. Go to Cyclone:n 1 l. Switch to plan B. [Reset everything, and loop back to the start of plan B.] [D] [We are finally out of the loop. Now it's time for the real fun.] Go to Cyclone:n 1 l 2 r. Pickup a passenger going to Sunny Skies Park. Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park:n 1 r. [We don't need the inputted number anymore, but we can't change its destination from the Cyclone.] [So we go to the Cyclone, so we can take the two clones and bring them to Sunny Skies Park forever.] [We could send them to Riverview Bridge, but that will take more bytes.] Go to Rob's Rest:s 2 r 1 r. [Pick up our running squares total from Rob's Rest, so it can go out and see the town.] Pickup a passenger going to Cyclone. Go to Cyclone:s 1 l 1 l 2 l. Pickup a passenger going to Cyclone. Pickup a passenger going to Cyclone. Go to Zoom Zoom:n. Go to Cyclone:w. [We need to end up with 4 clones of the total.] [Two of them will actually be used as the counter in this loop.] [At the start of each loop, we have no passengers.] [E] Pickup a passenger going to Joyless Park. Pickup a passenger going to Divide and Conquer. Go to Joyless Park:n 2 r 2 r 2 l. [We will leave one clone of the total at Joyless Park (like Sunny Side Park, but on the opposite side of town).] [The other clone will be used in a division.] Go to Cyclone:w 1 r 2 l 2 l. Pickup a passenger going to Cyclone. Pickup a passenger going to Joyless Park. Go to Joyless Park:n 2 r 2 r 2 l. [We will leave one clone of the counter at Joyless Park.] [We will clone the other clone (clone-ception?).] Go to Cyclone:w 1 r 2 l 2 l. Pickup a passenger going to Divide and Conquer. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer:n 2 r 2 r 1 r. [We will use both clones of the counter in a division.] [Divide and Conquer can take 3 arguments, and the result here will be equivalent to total / counter^2 .] [If the square of the counter is equal to the total, the result will be 1.] [If the square of the counter is less than the total, the result will be greater than 1.] [If the square of the counter is greater than the total, the result will be less than 1.] Pickup a passenger going to Magic Eight. 1 is waiting at Starchild Numerology. Go to Starchild Numerology:e 1 r 3 r 1 l 1 l 2 l. Pickup a passenger going to Magic Eight. Go to Magic Eight:w 1 r 2 r 1 r. Switch to plan F if no one is waiting. [We compare the result of the division against 1 to decide our next course of action.] [If it is greater or equal, the loop should end, and the counter is equal to the floor of the square root.] [If it is less, the loop should continue.] Pickup a passenger going to Riverview Bridge. [Whoops, we don't actually need this anymore.] Go to Joyless Park:e 2 l 4 r. Pickup a passenger going to Cyclone. [We will clone the total later, so we can reuse it in the next loop iteration.] Pickup a passenger going to The Underground. Go to The Underground:w 1 l. [Instead of taking the number 1 and subtracting it from the counter, we can do an optimization here.] [The Underground is a destination that takes 1 passenger, and subtracts 1 from it.] [If the result is positive, it returns the result. Otherwise, it returns no one.] [The latter result will not happen for us, however.] Pickup a passenger going to Cyclone. [We will clone the counter later, so we can reuse it in the next loop iteration.] Go to Fueler Up:s. [Gotta remember to stop for gas!] Go to Riverview Bridge:n 3 l. [So long, Magic Eight result!] Go to Cyclone:w 2 l. Switch to plan E. [Reset everything, and loop back to the start of plan E.] [F] Go to Joyless Park:e 2 l 4 r. Pickup a passenger going to What's The Difference. Pickup a passenger going to Cyclone. [Once we've figured out the square root of the total, we're still not done.] Go to Cyclone:w 1 r 2 l 2 l. Pickup a passenger going to Multiplication Station. Pickup a passenger going to Multiplication Station. Go to Multiplication Station:s 1 l 2 r 4 l. [We actually square the square root...] Pickup a passenger going to What's The Difference. Go to What's The Difference:n 2 l 1 r 3 l. [...and subtract it from the total at What's The Difference (which subtracts dropped-off passengers).] Pickup a passenger going to Knots Landing. Go to Knots Landing:e 4 r 1 l. [If the result is 0, the total is a perfect square, and a truthy value should be output.] [If the result is nonzero, the total is not a perfect square, and a falsy value should be output.] [Luckily, Knots Landing does our work for us.] [Knots Landing inverts the boolean logic of numeric passengers (i.e. 0 becomes 1, nonzero becomes 0).] Pickup a passenger going to The Babelfishery. Go to The Babelfishery:w 1 l. [Convert it to a string...] Pickup a passenger going to Post Office. Go to Post Office:n 1 l 1 r. [...and output it.] [We would exit the program by going to the Taxi Garage, but that takes bytes.] [The boss fires us because we didn't bring the taxi back to the garage, but that gets output to STDERR, so that's OK.] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` K²∑∆² ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJLwrLiiJHiiIbCsiIsIiIsIjQyIl0=) ``` ∆² # Is ∑ # The sum of ² # The squares of K # The factors of the input ∆² # A perfect square? ``` [Answer] # Vyxal, 14 bytes ([Test cases](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLGm8m+4biKVOKAusabOio7xpIr4oiaOuG5mT0iLCIiLCIxLDQyLDI0NiwxMCwxNiJd)) ``` ɾḊT›ƛ:*;ƒ+√:ṙ= ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` £İ□ṁ□Ḋ ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpKBrp6B0Yn3xo6bGokPb/h9afGTDo2kLH@5sBJE7uv7//29ixGXIZWRixmVowGVoBgA "Husk – Try It Online") ### Explanation ``` £İ□ṁ□Ḋ -- example input 12 Ḋ -- divisors: [1,2,3,4,6,12] ṁ -- map the following .. □ -- | square: [1,4,9,16,36,144] -- .. and sum: 210 £ -- is it element of (assumes sorted) İ□ -- | list of squares: [1,4,9,16..196,225,.. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆD²SƲ ``` **[Try it online!](https://tio.run/##y0rNyan8//9wm8uhTcGH2w5t@v//v4kRAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9wm8uhTcGH2w5t@n90z@H2R01r3P//NzHSUTDUUTAyMQPSBkBsBgA "Jelly – Try It Online"). ### How? ``` ÆD²SƲ - Main Link: integer ÆD - divisors ² - square S - sum Ʋ - is square? ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 5 bytes ``` ds¦Σụ ``` [Try it online!](https://tio.run/##AScA2P9nYWlh//9kc8KmzqPhu6X/ZeKGkcKm/1s0MiAxIDI0NiAxMCAxNl0 "Gaia – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 41 bytes ``` a=>sum(q*q for q:1..a+1if a%q<1)**.5%1==0 ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/R1q64NFejUKtQIS2/SKHQylBPL1HbMDNNIVG10MZQU0tLz1TV0NbW4H9BUWZeiUaahomRpiYXjGOIxDYyMUOWMUDmAGX@AwA "Proton – Try It Online") Similar approach to the Python answer. [Answer] # Mathematica, 32 bytes ``` IntegerQ@Sqrt[2~DivisorSigma~#]& ``` Pure function. Takes a number as input and returns `True` or `False` as output. Not entirely sure if there's a shorter method for checking perfect squares. [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 43 bytes ``` @(n)~mod(sqrt(sum(find(~mod(n,1:n)).^2)),1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zLjc/RaO4sKhEo7g0VyMtMy9FAyyUp2NolaepqRdnpKmpY6j5P03DxEiTK03DEEQYmZiB2QZg0kzzPwA "Octave – Try It Online") [Answer] # [Red](http://www.red-lang.org), 67 bytes ``` func[n][s: 0 repeat d n[if n % d = 0[s: d * d + s]](sqrt s)% 1 = 0] ``` [Try it online!](https://tio.run/##Rcm9CoAgGIXhvas4S9DPohINQTfRKt8QqeDyUWrXbzpUw4GH8wZr8maNpsYt2d18aCYdFwgEe9o9wYC1d2C0hStEjQZD2YhI1MUrJMS@hayV8hk8JzhMqnkpP6lp/l/xc84P "Red – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), ~~68~~ 67 bytes ``` def j(s:Int)=Math.sqrt((1 to s).filter(s%_<1).map(a=>a*a).sum)%1==0 ``` [Try it online!](https://tio.run/##JcqxCoMwEADQvV@RRbgrIRgRh9IIjh2c@gHlqpEqGqN3BaH029Ohb37c0UxpfU6@E9XSGJQ/xIeeVRPjJ/V@UBPw5RYEXUvyMrztAmCVrIrRDOMsfgfOHleLZqEI5Go6Exp@L5hZ5/J09xuUhba6KCttc22r/zxcHfcxyBxgggMRT9@Ufg "Scala – Try It Online") ]
[Question] [ In this task your code will be given an integer \$n\$ as input. Your code should then output the greatest number of multiples of \$3\$ that can be concatenated (in base \$10\$) to form \$3n\$ (with no leading zeros). For example if you were given \$26042\$ as input, \$26042\times3=78126\$ and \$78126\$ can be made by concatenating \$78\$, \$12\$ and \$6\$, so you output \$3\$. Any standard forms of IO are permitted. Answers should aim to minimize the number of bytes in their code. --- Here are the first \$6562\$ entries in this sequence starting with zero: ``` 1,1,1,1,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,4,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,2,2,2,2,2,2,3,3,3,3,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2 ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 11 bytes of Latin-1 ``` v`.3*[012¶] ``` [Try it online!](https://tio.run/##K0otycxLNPz/vyxBz1gr2sDQ6NC22P//jcwMTIy4AA "Retina – Try It Online") Retina works on strings rather than integers, so I'm taking the number as it'd appear in a file (digits followed by a newline). (Note: as pointed out in the comments, `v`.3*[¶-2]` works for 10 bytes, but I didn't come up with it myself.) ## Algorithm Almost all the solutions here have a multiplication by 3, but I thought it'd be interesting to try to solve the problem without it. We already know from the algorithm most people are using that we need to identify the number of suffixes of 3*n* that are divisible by 3. Now, given a suffix of *n* (say *s*), 3*s* will appear as a suffix of 3*n* if the multiplication *s*×3 does not carry into the digit before the suffix. Meanwhile, if the multiplication *s*×3 *does* carry, then the corresponding suffix of 3*n* will not be divisible by 3 (as the digital root of 3*s* is divisible by 3 – 3 divides (10-1) and we're working in base 10 – and the corresponding suffix of 3*n* will be equal to 3*s* but without a leading `1` or `2`, neither of which is divisible by 3). We do need to adjust for the possibility that 3*n* has more digits than *n*, thus meaning that 3*n* has an extra suffix that doesn't correspond to any suffix of *n*. This suffix is trivially the whole number 3*n*, and will always be divisible by 3 (for obvious reasons). Thus, if the multiplication *n*×3 carries, we have to add 1 to the result. We can note that if *n*×3 doesn't carry, it will contribute 1 to the result using a naive algorithm, whereas if it does, it won't; and thus we can do this adjustment simply by counting the "suffix that represents the whole number *n*" unconditionally, rather than checking for a carry. Equivalently (and slightly more tersely), we can unconditionally *not* count this suffix, and count some other suffix instead (the empty suffix is convenient), as it'll come to the same total. How do we determine if a multiplication by 3 would carry? Well, if the first digit of the number is greater than 3, it must; if it's less than 3, it can't. If it's 3, whether it carries or not will depend on the next digit of the number in the same way. If the number consists *entirely* of 3s, the multiplication won't carry (it'll stop just short at a number consisting entirely of 9s). Thus, the algorithm we want is "count the number of proper suffixes that start with 0 or more 3s, followed by 0, 1, 2, or the end of the string; plus one extra suffix". ## Explanation This algorithm ends up longer than the consensus algorithm in most languages, so I'm submitting it in Retina, a language where it turns out to be shorter than the more usual method (and a similar length to golfing languages). ``` v`.3*[012¶] v` {Count the number of} points within the input from which you can . ignore one character, 3* and skip past any number (including zero) of 3s, [012¶] to find 0, 1, 2, or the newline at the end of the input. ``` The requirement to ignore one character before we start looking means that the improper suffix consisting of the whole number cannot be counted (as the suffixes that we actually look at will be the ones starting one character to the right of where Retina starts, and thus not at the first character). However, the improper suffix consisting only of the newline at the end of the number will always be counted, thus giving us the one extra suffix we need. [Answer] # [Haskell](https://www.haskell.org/), 51 bytes ``` f n=sum[1|x<-scanr(:)"0".show$3*n,read x`mod`3<1]-1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDfasKbCRrc4OTGvSMNKU8lASa84I79cxVgrT6coNTFFoSIhNz8lwdjGMFbX8H9uYmaebW5igW@8RkFRZl6JXppmtIGenpGhhXnsfwA "Haskell – Try It Online") The key idea is the following: given a multiple of 3 (call it \$3n\$), the best way to write it as the juxtaposition of multiples of 3 is to start from the end (or the beginning) and select multiples of 3 greedily. For instance, if \$3n=78126\$, then we get (starting from the end) a \$6\$, then a \$12\$, and finally a \$78\$: \$78|12|6\$. Note that this is possible because a number is a multiple of 3 iff the sum of its digits is a multiple of 3. Also note that if we concatenate two multiples of 3, we get another multiple of 3, so \$6,12|6,78|12|6\$ are all multiples of 3. Thus the answer can be found by considering the list of suffixes of \$3n\$ (e.g. \$[78126,8126,126,26,6]\$) and counting the multiples of 3. [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` #o¦3dṫd*3 ``` [Try it online](https://tio.run/##yygtzv7/Xzn/0DLjlIc7V6doGf///9/QwBAA "Husk – Try It Online") or [verify the first 2188 terms!](https://tio.run/##yygtzv6f@6ip8WjDf@X8Q8uMUx7uXJ2iZfz//38jQwsLAA "Husk – Try It Online") ### Explanation ``` #(¦3d)ṫd*3 -- example: 42 *3 -- times 3: 126 d -- digits: [1,2,6] ṫ -- tails: [[1,2,6],[2,6],[6]] #( ) -- count values that are truthy when d -- | undigits: [126,26,6] ¦3 -- | divisible by 3: [42,0,2] -- : 2 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 bytes ``` +/0=3|+\⍎¨⍕3×⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@2voGtcY12zKPevkMrHvVONT48/VHfVJDc/zQuIzMDEyMA "APL (Dyalog Unicode) – Try It Online") or [verify the first 1000](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/9OAZLW2voGtcY12zKPevkMrHvVONT48/VHv1tr//zXSQPzNhgYGBpqPOhcaKmBCIygcSmLGUGiEBEkVG/XHqD9G/THqj1F/jPpjiPoDAA) ### Explanaition ``` +/0=3|+\⍎¨⍕3×⎕ ⎕ ⍝ prompt for input 3× ⍝ multiply by 3 ⍎¨⍕ ⍝ convert the number to a vector of digits +\ ⍝ take the cumulative sum 3| ⍝ find each term modulo 3 +/0= ⍝ count those that equal 0 ``` This works because a number is divisible by three if and only if the sum of its digits is divisible by three [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~12~~ ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3*η3ÖO ``` -5 bytes creating a port of [*@BMO*'s Husk answer](https://codegolf.stackexchange.com/a/172930/52210). -1 byte thanks to *@Nitrodon* by changing suffixes to prefixes. [Try it online](https://tio.run/##yy9OTMpM/f/fWOvcduPD0/z//zcyMzAxAgA) or [verify the first 1000 items](https://tio.run/##yy9OTMpM/f@oqcXN77@x1rntxoen@f9/1DDv8H4d@/8A). **Explanation:** ``` 3* # Multiply the (implicit) input by 3 # i.e. 26042 → 78126 η # List of prefixes # i.e. 78126 → ["7","78","781","7812","78126"] 3Ö # Check for each if its divisible by 3 # i.e. ["7","78","781","7812","78126"] → [0,1,0,1,1] O # And take the sum (which is implicitly output) # i.e. [0,1,0,1,1] → 3 ``` --- **Old 12-bytes answer:** ``` 3*.œʒ3ÖP}€gà ``` Or alternatively `€gà` can be `éθg`. [Try it online](https://tio.run/##yy9OTMpM/f/fWEvv6ORTk4wPTwuofdS0Jv3wgv//jcwMTIwA) or [verify the first 1000 items](https://tio.run/##ASgA1/9vc2FiaWX/4oKERk7/MyouxZPKkjPDllB94oKsZ8Og/@KAnsO/LD//) **Explanation:** ``` 3* # Multiply the (implicit) input by 3 # i.e. 26042 → 78126 .œ # Take all possible partitions of this number # i.e. 78126 → [["7","8","1","2","6"],["7","8","1","26"],["7","8","12","6"], # ...,["781","26"],["7812","6"],["78126"]] ʒ } # Filter these partitions by: 3ÖP # Only keep partitions where every number is divisible by 3 # i.e. ["7","8","1","2","6"] → [0,0,0,0,1] → 0 # i.e. ["78","12","6"] → [1,1,1] → 1 #(option 1:) €g # Take the length of each remaining partition # i.e. [["78","12","6"],["78","126"],["7812","6"],["78126"]] → [3,2,2,1] à # And take the max (which we output implicitly) # i.e. [3,2,2,1] → 3 #(option 2:) é # Sort the remaining partitions by length # i.e. [["78","12","6"],["78","126"],["7812","6"],["78126"]] # → [["78126"],["78","126"],["7812","6"],["78","12","6"]] θ # Take the last one (the longest) # i.e. [["78126"],["78","126"],["7812","6"],["78","12","6"]] # → ["78","12","6"] g # And take its length (which we output implicitly) # i.e. ["78","12","6"] → 3 ``` [Answer] # ~~[Perl 6](https://github.com/Raku/problem-solving/issues/81)~~ [Raku](https://github.com/nxadm/rakudo-pkg), ~~54 28~~ 26 bytes *-14 bytes thanks to nwellnhof!* ``` {sum [\+](.comb)X%%3}o*×3 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/urg0VyE6pi5WQy85PzdJM0JV1bg2X@vwdOP/1lzFiZUKekBlaflFCkZmBiZGOgo1cUYG1v8B) This counts how many prefixes of the number times three are divisible by 3. ### Explanation: ``` { }o*×3 # Pass the input times 3 into the code block [\~](.comb) # Get all the prefixes of the number X%%3 # Map each to whether they are divisible by 3 sum # And get the sum ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~99~~ 88 bytes ``` lambda n:g(`3*n`) g=lambda n:int(n)%3<1and 1+max([g(n[i:])for i in range(1,len(n))]+[0]) ``` [Try it online!](https://tio.run/##7Y/BCoMwEETvfkUuhU31YGLpQeqXpAFTTNKArhKstF9vI0op9NSjEOayzMwOvOE13nvks6muc6u6W6MIlhbq4og1TWz18RyOgPRQXJjChrC0U08QFlC4UlLTe@KIQ@IVWg0sazWGNpWpyCWdlxiXmGUsz/g5P/EyIYMPm8SEXpKst2pbAAOOVtW0bmbT8qbx0WmvRg0iLPyIb9qTV2ziX/rXixyRI3JEjsgROXbKISmd3w "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 41 bytes ``` f=(n,i=10)=>!(n*3%i%3)+(n*3>i&&f(n,i*10)) ``` [Try it online!](https://tio.run/##FctBCoMwEEDRq6QLdcamQ8R1Aj1HKSVYLSN2RmIRPH0adx8ef4573IbE6@8m@h5znjyIZd859OEC0vYVVz1ezwpc19OpbVHMg8qmy0iLfuBBRPeU4gGdcw6f9I0rwMsaQeODKRcizcoCjW3K@wc "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 44 bytes ``` g.(*3).max 1 g 0=0 g n=0^mod n 3+g(div n 10) ``` [Try it online!](https://tio.run/##DcZLCoAgEADQfaeYRYs@JCOtPUkfGCxNUpOK6PRNbh5vo2tfvWejRraiavpaBHpBFhZQYTYqnMOxQIS@tdXinjyJNQdyUaXTxRtKCJTAwIBCSMSJP2082Ys7ndIP "Haskell – Try It Online") Uses [Delfad0r's observation](https://codegolf.stackexchange.com/a/172921/20260) that the output is the number of suffixes (equivalently, prefixes) of 3n that are multiples of 3. This method finds the prefixes arithmetically by repeatedly floor-dividing by 10 rather than using the string representation. The `0^` is a short arithmetic way to produce `1` if the exponent `mod n 3` is zero, and produce `0` otherwise. The first line is the main function, which triples the input before passing it to the helper function `g` which is defined recursively. The `max 1` is a hack to make `f(0)` equal 1, since we're required to handle zero like the string `'0'` rather than the empty string. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~15~~ 14 bytes ``` 3*▒0\Ƨ_3÷\;]Σ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/99Y69G0SQYxh9sOLY83Prw9xjr23OL//43MDEyMAA "MathGolf – Try It Online") -1 byte thanks to JoKing ## Explanation ``` 3* Multiply the input by 3 ▒ Convert to a list of digits 0\ Push a zero and swap the top two elements Æ Execute the next 5 characters for each block § Concatenate _ Duplicate 3÷ Check divisibility by 3 (returns 0 or 1) \ Swap top two elements ; Discard TOS (the last swap ]Σ Wrap the entire stack in an array and output its sum ``` I don't know if this is the correct solution to the problem but it mimics the JS solution by Arnauld. If I'm incorrect, I'll try to fix it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ×3DÄ3ḍS ``` [Try it online!](https://tio.run/##7dWhDcJAFIDhhWq4g07ABp0B03QBHCEkKHQVG6BJ/U3SLnKYE01QDQhKvjz33HfJu789dN0x59THfbrEcbg1ud7VYRye6TqdH@10uld5U71PKLOmXSwTZrN0x8HBwcHBsVbHtkyczdLdJ2/wrR3H/zncOQcHB4eec@i5O@fg4NBzHeTQc/8VBweHnusgh577rzg4OPRcBzn0nIODg0PPOfTcnf@I4wU "Jelly – Try It Online") ### How it works ``` ×3DÄ3ḍS Main link. Argument: n ×3 Compute 3n. D Decimal; convert 3n to the array of its digits in base 10. Ä Accumulate; take the cumulative sum. Note that an integer and its digit sum are congruent modulo 3. 3ḍ Test each partial digit sum for divisibility by 3. S Take the sum of the Booleans, counting the multiples of 3. ``` [Answer] # Pyth, ~~16~~ 15 bytes ``` lef!.E%vT3./`*3 ``` Try it online [here](https://pyth.herokuapp.com/?code=lef%21.E%25vT3.%2F%60%2A3&input=26042&debug=0). ``` lef!.E%vT3./`*3Q Implicit: Q=eval(input()) Trailing Q inferred `*3Q Input * 3 ` Convert to string ./ Take divisions into disjoint substrings f Filter the above using: vT Convert each back to integer % 3 Mod 3 .E Are any non-0? ! Logical NOT le Take the length of the last value As the substring sets are generated in order of number of substrings, the last value is guaranteed to be the longest ``` [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 376 bytes ``` T.Ajax,.Page,.Act I:x.Scene I:x[Enter Ajax and Page]Ajax:Listen tothy!You be the sum ofthe sum ofyou you you!Scene V:x.Page:You be the sum ofyou the quotient betweena cat the sum ofa cat the remainder of the quotient betweenI the sum ofa big cat a cat!Ajax:You be the quotient betweenyou twice the sum ofa big big cat a cat!Be you nicer zero?If solet usscene V.Page:Open heart ``` [Try it online!](https://tio.run/##bVBBCsIwEPzK9l6KiHjoRRQ8FAQFRRDxEOu2jbSJJhts/XxNUkFrPQR22JnZmehb2ba7aH5ldRhtWI5hNE8JkriOtikKdNNxKQgVOA4wcQFHOzkUr7gmFECSiiY4SANnBCoQtKlAZp@psav3CzrbvT3gfOKByvEcuhtJHAXZLT0QBYOU0RfvgxVWjIuLjSizv9KkJzvz3Eu9QeB7fIX41fo4D57iwKPvs0DfUFimgicqOUsy0LJEAqN117lrvL7ZLyuQKWrb8XQ0Gb8A "Shakespeare Programming Language – Try It Online") I wonder if the `1/(1+I/3)` trick is better than a control flow. [Answer] # Java 10, 66 bytes ``` n->{int m=1,r=n<1?1:0;for(n*=3;m<n;m*=10)r+=n%m%3<1?1:0;return r;} ``` [Try it online.](https://tio.run/##bVCxasMwEN3zFYchIMWOkeLSwbLardChWTKWDqqiBKXWOchyoAR/uyu53trljnv3eO/dXdRNbS/Hr0m3qu/hTVm8rwAsBuNPShvYp3EGQJPXCJ@NB6QiouMqlj6oYDXsAUHChNune6I6yQsrWeElNvyZ10ycOk9wIyvhGhRuIzmjPpe4dutqYXgTBo/gxTiJpHwdPtuovBjcOnsEF@ORQ/AWz@8foOhvtsN3H4wruyGU17gKLZJs98gedjVkOZaazAOdM//PfrG@D8AZY3W20FLedEm8QoBtuKliy3M6L/@qkORjaZ4V2fKbcfoB) **Explanation:** Uses a combination of [*@BMO*'s Husk answer](https://codegolf.stackexchange.com/a/172930/52210) (checking how many prefixex are divisible by 3) and [*@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/172911/52210) (multiplying an integer by 10 every iteration, and get the prefixes with a modulo of this integer). ``` n->{ // Method with integer as both parameter and return-type int m=1, // Modulo-integer, starting at 1 r= // Result-integer, starting at: n<1? // If the input is the edge-case 0: 1 // Start it at 1 : // Else: 0; // Start it at 0 for(n*=3; // Multiply the input by 3 m<n; // Loop as long as `m` is still smaller than `n` m*=10) // After every iteration: Multiply `m` by 10 r+=n%m // If `n` modulo-`m` (to get a suffix), %3<1? // is divisible by 3: 1 // Increase the result-sum by 1 : // Else: 0; // Leave the result-sum the same by adding 0 return r;} // Return the result-sum ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~35~~ 32 bytes ``` .+ $.(*3* Lv$`.+ <$&*-> <(---)*> ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0VPQ8tYi8unTCUByLNRUdPSteOy0dDV1dXUsvv/38jQwgAA "Retina – Try It Online") Explanation: ``` .+ $.(*3* ``` Multiply the input by 3. ``` Lv$`.+ <$&*-> ``` Convert each suffix to unary. ``` <(---)*> ``` Count the multiples of three. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes ``` {+/~3!+\.:'$3*x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/dqlpbv85YUTtGz0pdxVirovZ/iVW1SnRlXZFVmkKFdUJ@trVGQlpiZo51hXWldZFmbC0XV7GVkiEcGAEBbVjGQGAEBrhYA2GHEleaVbWOvkq6umJFrXVJtHKxdXGsgn5ZalFmWqVCWmZRcYmCkakBF0iZtj5MlZmpmZE10DZLC4Ta4tJchfw0qBaQgv8A "K (ngn/k) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` n=input()*3;p=n<1 while n:p+=n%3<1;n/=10 print p ``` [Try it online!](https://tio.run/##LYw7DsIwEAX7PcXKEhKfAjtBFElchpaGC0BYKRbRerVyBDm9iQXVe8XMyJLGyFUe4pPQozEmsw8sc9ru9nUrnjsH7zFMhNzIwfOm7lzLR@8siAZOKHmV4M/cdKYGEJMuZRDpQwOWOJQ/kCTsr5deNeoPeCjdX9mCg7VYne2p@gI "Python 2 – Try It Online") Similar to [ovs's answer](https://codegolf.stackexchange.com/a/173009/20260), but takes the whole prefix mod 3 without accumulating rather than the last digit. Outputs `True` as 1 on input of 0. --- # [Python 3](https://docs.python.org/3/), 42 bytes ``` f=lambda n:n>=1and(n%1<1/3)+f(n/10)or n==0 ``` [Try it online!](https://tio.run/##DcHBCoQgFAXQvV/hJnjSovcqWkTOvziYJNhNwoq@3plz8lu2A0OtwSa3f73TmPGx4uAJjSzSDaYNhE7YHKeGtVyfLaZVy5zPiEKB1tslishXIfNXWYkSVv3EY/8D "Python 3 – Try It Online") Uses ideas from [ais523's very nice solution](https://codegolf.stackexchange.com/a/172973/20260). Repeatedly floor-divides the input by 10 until it's zero, and counts how many times the fractional part is less than 1/3. On very large inputs float precision will eventually be a problem. The `n=0` case is handled with `or n==0` making it return True for 1. The code can work in Python 2 if the input is a float, if we rewrite `n%1<1/3` as `n%1*3<1` which is the same length. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` #¦3∫d*3 ``` [Try it online!](https://tio.run/##yygtzv7/X/nQMuNHHatTtIz///9vaGAIAA "Husk – Try It Online") Same as the other answer, except it uses cumulative sum. [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` αNΘ╠╠1d} ``` [Run and debug it](https://staxlang.xyz/#p=e04ee9cccc31647d&i=26042&a=1) Unpacked, ungolfed, and commented, it looks like this. ``` 3* triple input E convert to array of decimal digits :+ get all prefix sums F for each prefix sum 3%! is it a multiple of 3? + add to running total ``` [Run this one](https://staxlang.xyz/#p=e04ee9cccc31647d&i=26042&a=1) [Answer] # Japt `-x`, 12 bytes ``` *3 s å+ ®°v3 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=KjMgcyDlKyCusHYz&input=MjYwNDIKLXg=) or [view results for`0-1000`](https://ethproductions.github.io/japt/?v=1.4.6&code=KjMgcyDlKyCusHYzCng=&input=MTAwMQotbQ==) [Answer] # [J](http://jsoftware.com/), 20 bytes ``` 1#.0=[:(3|".)\3":@*] ``` [Try it online!](https://tio.run/##LcmxDkAwFEbhvU/xp4YicnOLGG7SxOQlMIkGi0SNPHtJGM93tuiDIzAEHG1C7HpJq0tTNlRa2nyMmdIE4x0ZFLgFPig1T8sOj7LhuvzCdOsRTlhmMf/WjJVegIoP "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` n=input()*3;k=p=0 while n:k+=n%10;n/=10;p+=k%3<1 print p ``` [Try it online!](https://tio.run/##LY2xDoJAEET7/YoNCYlK4R0YC3BLbG38AcVNIEeWzeaI8vUnRJt5U7zJ6BL7ScrUTS9GwizLktAgOsfd/lA1gZQcvPthZJQ6FCS5d40caU0tKOTVxYPaIBE1rWP4u3ebuQbEaMsGRP5wh9sJbL1jjdjerq3ZZD/hafwIyYN3UJ7dqfwC "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 32 bytes ``` $_*=3;s/./$\+=!(($t+=$&)%3)/ge}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXsvW2LpYX09fJUbbVlFDQ6VE21ZFTVPVWFM/PbW2@v9/QwNDg3/5BSWZ@XnF/3V9TfWA/P@6BQA "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `s`, ~~6~~ ~~5~~ 4 bytes ``` 3*¦₃ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=3*%C2%A6%E2%82%83&inputs=26042&header=&footer=) ;) ## Explained ``` 3*¦₃ 3* # multiply the input by 3 ¦ # take cumulative sums of that number, treating it as a list ₃ # get the divisibility of 3 of each number and then # the `-s` flag sums the top of the stack before outputting ``` [Answer] # [Desmos](https://desmos.com/calculator), 61 bytes ``` f(n)=total(0^{mod(floor(3n/10^{[0...floor(log(0^n+n))]}),3)}) ``` Essentially does the prefix trick that some of the other answers are using. Pretty straightforward, though quite interesting to implement in Desmos. [Try It On Desmos!](https://www.desmos.com/calculator/pugd698blv) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/d35v1oscrp) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/): (53) 43 Bytes ``` If[#<1,1-Sign@#,Boole[3#~Mod~1<1]+#0[.1#]]& ``` *-10 bytes from att* Pretty long, but I figured it was worth posting anyways because it was difficult enough to golf. [Try It Online](https://tio.run/##y00syUjNTSzJTE78n2b73zMtWtnGUMdQNzgzPc9BWccpPz8nNdpYuc43P6XO0MYwVlvZIFrPUDk2Vu1/QFFmXkl0mr5DUGJeemq0gY6hkUFs7H8A) --- ## Explanation: `If[#<1, 1-Sign@#`: If our input was 0, return 1. `Boole[3#~Mod~1<1]`: Otherwise, check if the fractional part of 3n is less than 1, and return 1 if so. `+#0`: Then, add this same expression to this total `[.1#]]&` but with a tenth of the input. I also tried using the other algorithm, but I couldn't get anything below around 75 bytes with it. Probably possible to get much lower than 75 (I'm not great at golfing), but 43 certainly seems better. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` T¦v₃∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJUwqZ24oKD4oiRIiwiIiwiMjYwNDIiXQ==) ## How? ``` T¦v₃∑ T # Triple the (implicit) input ¦ # Cumulative sum v₃ # Is each element divisible by three? ∑ # Sum ``` ]
[Question] [ ## Introduction According to [Rand Al'Thor's post](https://puzzling.stackexchange.com/questions/42209/what-is-a-close-knit-word) in the Puzzling SE, a close-knit word is any word that contains three alphabetically consecutive letters (in any order). Words like **education**, **foghorn** and **cabaret** are all considered close-knit words whereas words like **learning**, **klaxon** and **perform** are not close-knit words. ## Challenge The challenge is to code-golf a program capable of taking a single word as input (assumed lower case, for all intents and purposes) and to return output that (if available) lists all consecutive letter sets (also in lower case) if it is a close-knit word, and empty output if it is not a close-knit word. ## Examples ``` Input: education Output: cde Input: foghorn Output: fgh Input: cabaret Output: abc Input: hijacking Output: ghi, hij, ijk Input: pneumonia Output: mno, nop Input: klaxon Output: <<no output>> Input: perform Output: <<no output>> Input: learning Output: <<no output>> ``` ## Rules 1. Whereas input is to be assumed to be a single lower-case word and output must be lower-case, the nature of the output will vary according to the choice of your coding language. Please select a form of output that will best suit the nature of the challenge, whether it be STDOUT, file output, array, etc. 2. Because this is code-golf, it will be a case of lowest number of bytes being the clear winner. 3. [No silly loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny). 4. I will not accept answers that have the consecutive letters in non-alphabetical order... So `cab` will not be deemed a suitable output for `cabaret`, for example. 5. Special note, while the "triplets" don't necessarily have to be in alphabetical order, but the characters within the triplets must be... so in the case of the word "performance", for example, the output `mno,nop` will be accepted, as will `nop,mno`. In the case of the word "hijacking", there are six ways that the triplets of `ghi`, `hij` and `ijk` could be arranged in a list, and all six permutations are acceptable as output. Other than that, on your marks, get set, golf! [Answer] ## Python 3.5, 68 bytes ``` w=input() a=0 while 1:s='%c'*3%(a,a+1,a+2);a+=1;{*s}-{*w}or print(s) ``` Prints output strings, and terminates with error when the character value gets too large. Generates all strings of three consecutive and prints those that are a subset of the input word. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~7~~ ~~6~~ 5 bytes Code: ``` 3ãAŒÃ ``` Explanation: ``` 3ã # Cartesian product × 3 with input AŒ # All substrings of the alphabet à # Setwise intersection ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=M8OjQcWSw4M&input=aGlqYWNraW5n) [Answer] # Pyth - ~~11~~ ~~10~~ ~~8~~ 7 bytes Super brute force method. ``` @^z3.:G ``` [Test Suite](http://pyth.herokuapp.com/?code=%40%5Ez3.%3AG&test_suite=1&test_suite_input=education%0Afoghorn%0Acabaret%0Ahijacking%0Apneumonia%0Aklaxon%0Aperformance%0Alearning&debug=0). ``` @ Setwise intersection, finds common strings between the two lists ^ Cartesian product z Input 3 Of length 3 .: Substrings. Without second input finds all substrings which is ok G Lowercase aphabet ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØaẆfṗ3$ ``` This is a monadic link. [Try it online!](http://jelly.tryitonline.net/#code=w5hh4bqGZuG5lzMkCuG4ssOH4oKsRw&input=&args=ZWR1Y2F0aW9uIGZvZ2hvcm4gY2FiYXJldCBoaWphY2tpbmcgcG5ldW1vbmlhIGtsYXhvbiBwZXJmb3JtIGxlYXJuaW5n) ### How it works ``` ØaẆfṗ3$ Monadic link. Argument: s (string) Øa Yield the lowercase alphabet, i.e., a := "abcdefghijklmnopqrstuvwxyz". Ẇ Window; yields all substrings of a. $ Combine the two links to the left into a monadic chain. ṗ3 Take the third Cartesian power of s, yielding all combinations of three characters that can be formed from the letters in s. f Filter; keep only those substrings of a that appear in the Cart. power. ``` [Answer] ## JavaScript (ES6), ~~95~~ 90 bytes ``` f= s=>[...s].map(c=>a[parseInt(c,36)]=c,a=[])&&a.map((c,i)=>c+a[i+1]+a[i+2]).filter(c=>!c[3]) ; ``` ``` <input oninput="o.textContent=f(this.value).join`, `"><div id=o> ``` Missing values concatenate as `undefined`, so the resulting string contains greater than 3 characters. I borrowed the `!c[3]` trick from @ETHproductions to save 5 bytes. [Answer] ## Haskell, 48 bytes ``` f w=filter(all(`elem`w))[take 3[c..]|c<-['a'..]] ``` Generates all triples of three consecutive characters, takes those that use only letters in the input. --- **53 bytes:** ``` f w=filter(all(`elem`w))[[pred$pred c..c]|c<-['c'..]] ``` The list `['c'..]` contains all unicode characters from `'c'` onward. The list comprehension `[[pred$pred c..c]|c<-['c'..]]` turns them into all strings of 3 consecutive characters from `"abc"` onward. We step backwards with `[pred$pred c..c]` instead of forwards with `[c..succ$succ c]` to avoid an error when taking the successor of the highest unicode character. These triples are filtered for those that only use letters in the input. [Answer] # Python 3.5, 78 bytes ``` s={*input()} for c in s:o=ord(c);a=chr(o-2);b=chr(o-1);s>{a,b}and print(a+b+c) ``` [Answer] # PHP, 100 bytes ``` for($a="abc",$i=98;$i<123;$a=substr($a,1).chr(++$i))if(strstr(count_chars($argv[1],3),$a))echo"$a,"; ``` takes input as command line argument; prints a trailing comma. run with `-r`. [Answer] # C, ~~175~~ 174 bytes ``` main(_,a,m,n)char**a;{char*s=a[1],*t=s;while(*++s)while(s>t&&(n=s[-1])>=*s){m=(*s^n)?*s:0;*s=n;*--s=m;!*t&&++t;}for(;t[1]&t[2];++t)*t==t[1]-1&&*t==t[2]-2&&printf("%.3s ",t);} ``` indented: ``` main(_,a,m,n)char**a; { char*s=a[1],*t=s; while(*++s) while(s>t&&(n=s[-1])>=*s){ m=(*s^n)?*s:0; *s=n; *--s=m; !*t&&++t; } for(;t[1]&t[2];++t) *t==t[1]-1&&*t==t[2]-2&&printf("%.3s ",t); } ``` While doing the sort it replaces duplicate values with 0s, these 0s get sorted to the beginning of the word. Looking for the consecutive values is then trivial. [Answer] # [MATL](http://github.com/lmendo/MATL), 13 bytes ``` 2Y23YCtjmAZ)! ``` [Try it online!](http://matl.tryitonline.net/#code=MlkyM1lDdGptQVopIQ&input=aGlqYWNraW5n) ``` 2Y2 % Push string of lowercase alphabet 3YC % 2D char array with sliding blocks of size 3, each on a column t % Duplicate j % Take input m % Member function: true for elements of the 2D array that are in the input A % All: true for columns that consist of all true values Z) % Use as logical index into the columns of the 2D char array ! % Transpose. Implicitly display ``` [Answer] # Perl, 36 bytes Includes +1 for `-n` Give input on STDIN: ``` perl -nE 'join("",a..z)=~/[$_]{3}(?{say$&})^/' <<< "hijacking" ``` Just the code: ``` join("",a..z)=~/[$_]{3}(?{say$&})^/ ``` [Answer] # T-SQL, 153 bytes Had to react on the comment from WallyWest, about it being long time since last TSQL answer. Answer was partly inspired by Brian J's answer **Golfed:** ``` USE MASTER DECLARE @ varchar(max)='hijacking' ;WITH C as(SELECT distinct ascii(substring(@,number,1))z FROM spt_values)SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)FROM C,C D,C E WHERE c.z+1=d.z and d.z=e.z-1 ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/542452/close-knit-words)** **Ungolfed:** ``` USE MASTER -- can be left out if the master database is already being used DECLARE @ varchar(max)='hijacking' ;WITH C as ( SELECT distinct ascii(substring(@,number,1))z FROM spt_values ) SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z) FROM C,C D,C E WHERE c.z+1=d.z and d.z=e.z-1 ``` [Answer] ## Haskell, ~~63~~ ~~60~~ 52 bytes ``` f w=[x|x<-take 3<$>scanr(:)"_"['a'..],all(`elem`w)x] ``` Usage example: `f "hijacking"` -> `["ghi","hij","ijk"]`. `scanr(:)"_"['a'..]` builds a list with the tails of the list of all unicode chars starting with `'a'` and lets it end with a `'_'`, i.e. `["abcde...\1114111_", "bcde...\1114111_", "cde...\1114111_", ..., "\1114109\1114110\1114111_", "\1114110\1114111_", "\1114111_", "_"]`. Then we take up to three chars of each string and bind it to `x`. Keep all `x` where every letter of it is in the input parameter `w`. Edit: @xnor saved ~~3~~ 7 bytes. Thanks! [Answer] # T-SQL (SQL Server 2014), 217 bytes ## Golfed ``` declare @ table(a char)declare @i int=1while @i<=len(@a)begin insert into @ values(SUBSTRING(@a,@i,1))set @i+=1 end select distinct t.a+u.a+v.a from @ t,@ u,@ v where ASCII(t.a)+1=ASCII(u.a)and ASCII(u.a)+1=ASCII(v.a) ``` ## Usage First declare the variable @a as a char of some sort and assign the input like so ``` declare @a varchar(max) = 'pneumoultramicroscopicsilicovolcanoconiosis' ``` I didn't count the declare as part of my code, but I didn't find a sql standard for input, so I'm willing to change my counting Output will either be one row for each triple, or no rows if the word is not close knit ## Ungolfed ``` declare @temp table ( letter char(1) ) -- table to hold each letter of the word declare @i int = 1 while @i <= len(@input) -- split each letter, and each row in @temp will have one letter begin insert into @temp values (SUBSTRING(@input, @i, 1)) set @i = @i + 1 end -- join the letters table to itself to get three letter triples, where the three are in adjacent increasing order -- use distinct because there might be duplicates in the word select distinct t1.letter + t2.letter + t3.letter from @temp t1 cross apply @temp t2 cross apply @temp t3 where ASCII(t1.letter) + 1 = ASCII(t2.letter) and ASCII(t2.letter) + 1 = ASCII(t3.letter) ``` [Answer] ## **R, 220 bytes** My solution is pretty straightforward. It loops through the possible three letter combinations, loops through and checks the characters of the entered string against the three consecutive letters, and adds them to a string. The string is then only printed when three letters are found (c==4). ``` f<-function(w){if(nchar(w)>2){for(i in 1:24){ c<-1 t<-"" for(k in 1:3){for(j in 1:nchar(w)){if(substr(w,j,j)==intToUtf8(95+k+i)&c<4){ t<-paste(t,substr(w,j,j),sep="") c<-c+1 break }}} if(c==4){print(paste(t))}}}} ``` ## input/output ``` > f("education") > [1] "cde" > > f("foghorn") > [1] "fgh" > > f("cabaret") > [1] "abc" > > f("hijacking") > [1] "ghi" > [1] "hij" > [1] "ijk" > > f("pneumonia") > [1] "mno" > [1] "nop" > > f("klaxon") > > f("perform") > > f("learning") > > ``` [Answer] # Python 3.5, ~~114~~ ~~111~~ ~~88~~ ~~80~~ 79 bytes: ``` lambda X,W=[*map(chr,range(65,91))]:[i*({*X}>={*i})for i in zip(W,W[1:],W[2:])] ``` An anonymous lambda function. Takes input as an *uppercase* string and outputs an array of tuples, with the ones filled with three *uppercase* characters representing all sets of `3` consecutive letters that appear in the input. For example, ``` [(), (), (), (), (), (), ('G', 'H', 'I'), ('H', 'I', 'J'), ('I', 'J', 'K'), (), (), (), (), (), (), (), (), (), (), (), (), (), ()] ``` would be the output for input `HIJACKING`. This output format has been [confirmed](https://codegolf.stackexchange.com/questions/93831/close-knit-words/93839#comment228857_93831) to be okay by OP. [So has](https://codegolf.stackexchange.com/questions/93831/close-knit-words/93839#comment228862_93831) the only uppercase input format. However, if you want to input in *only* lowercase, simply replace `range(65,91)` with `range(97,123)`, adding one more byte. [Repl.it with all Test Cases!](https://www.repl.it/DdNm/3) ## Explanation: Basically what is happening here is: 1. A list, `W`, is created using `W=[*map(chr,range(65,91))]`, which contains all the uppercase letters in the English alphabet. Because of this, an uppercase input is *always* required. 2. For each tuple, `i`, in a list, which we will call `U`, containing *all* three consecutive letter tuples, i.e.: ``` U=[('A','B','C'),('B','C','D'),('C','D','E'),...] ``` created by `zip(W,W[1:],W[2:])`, each `i` is fully added to the output list as long as all elements in the set version of `i` (`{*i}`) are in the set version of input `X` (`{*X}`), i.e. `{*X}>={*i}`, i.e. `X` is a *superset* of `i`. Otherwise, the empty version of `i` (`()`) is added to the list. 3. Once all the tuples have been gone through with the matches fully added, the list is returned as the final output. [Answer] # Scala, 59 bytes ``` (s:Set[Char])=>'a'to'z'sliding 3 filter{_.toSet subsetOf s} ``` Ungolfed: ``` (s:Set[Char]) => ('a' to 'z').sliding(3).filter{threeChars => threeChars.toSet.subsetOf(s)} ``` ## Explanation: ``` (s:Set[Char])=> //define a function with a Set of Chars called s as an argument 'a' to 'z' //create a Range of characters 'a' to 'z' sliding 3 //create an Iterator(Seq(a, b, c), Seq(b, c, d), Seq(c, d, e), ... , Seq(x, y, z)) filter{_.toSet subSetOf s} //keep only the triplets which are a subset of s ``` [Answer] # Actually, 13 bytes Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=UzNA4pWnYM61amBNM8O6VuKIqQ&input=ImhpamFja2luZyI) ``` S3@╧`εj`M3úV∩ ``` **Ungolfing** ``` Implicit input string s. S sorted(s). 3@╧ Push all length-3 combinations of s. `εj`M Join all of those combinations into single strings. 3úV Push all slices of the lowercase alphabet of length 1 <= n <= b ∩ Push the intersection of the combinations and slices. Implicit return. ``` [Answer] # Java 7, 230 bytes ``` String c(char[]q){java.util.Arrays.sort(q);char a[]=new String(q).replaceAll("(.)\\1","$1").toCharArray(),c=97,i=2;String r="",z="",s;for(;c<'z';z+=c++);while(i<a.length)if(z.contains(s=""+a[i-2]+a[i-1]+a[i++]))r+=s+" ";return r;} ``` This can most likely be golfed, but the challenge was a lot tougher than I originally thought in Java.. **Ungolfed & test cases:** [Try it here.](https://ideone.com/14ITbf) ``` class M{ static String c(char[] q){ java.util.Arrays.sort(q); char a[] = new String(q).replaceAll("(.)\\1", "$1").toCharArray(), c = 97, i = 2; String r = "", z = "", s; for(; c < 'z'; z += c++); while(i < a.length){ if(z.contains(s = "" + a[i-2] + a[i-1] + a[i++])){ r += s+" "; } } return r; } public static void main(String[] a){ System.out.println(c("education".toCharArray())); System.out.println(c("foghorn".toCharArray())); System.out.println(c("cabaret".toCharArray())); System.out.println(c("hijacking".toCharArray())); System.out.println(c("pneumonia".toCharArray())); System.out.println(c("klaxon".toCharArray())); System.out.println(c("perform".toCharArray())); System.out.println(c("learning".toCharArray())); System.out.println(c("dblacghmeifjk".toCharArray())); } } ``` **Output:** ``` cde fgh abc ghi hij ijk mno nop abc bcd cde def efg fgh ghi hij ijk jkl klm ``` [Answer] ## PowerShell v2+, 93 bytes ``` param($n)97..120|%{-join[char[]]($_,++$_,++$_)}|?{(-join([char[]]$n|sort|select -u))-match$_} ``` Feels much longer than required, but I can't seem to golf it any further. Takes input `$n`. Loops from `97` to `120`, constructing contiguous three-letter strings -- that is, up to the `|?`, we'll have `abc`, `bcd`, `cde`, etc. on the pipeline. Then that's fed through a `Where-Object` (the `|?`) to pull out only those items where the clause is true. Here, the clause is 1) the input string `$n`, cast as a `char`-array, `sort`ed and `select -u`nique'd, then `-join`ed back into a string, 2) `-match`ed against the three-letter strings (i.e., regex matching). If it's a match, then the three-letter string is in the word, and so it filters through the `|?`. The results are left on the pipeline and output is implicit. ### Examples (Note that here the output is space-separated, since we're stringifying the output by concatenation.) ``` PS C:\Tools\Scripts\golfing> 'education','foghorn','cabaret','hijacking','pneumonia','klaxon','perform','learning'|%{"$_ -> "+(.\close-knit-words.ps1 $_)} education -> cde foghorn -> fgh cabaret -> abc hijacking -> ghi hij ijk pneumonia -> mno nop klaxon -> perform -> learning -> ``` [Answer] # Retina, ~~106~~ 56 bytes ``` D`. O`. ^ abc¶ {`^(.*)¶.*\1.* $0¶$1 }T`_l`l;`^.* 2`.*¶? ``` Deduplicate, Sort. Add `abc`. Find if the substring is found and append if so. Translate to next substring. Repeat. Then remove first two lines. [**Try it online**](http://retina.tryitonline.net/#code=RGAuCk9gLgpeCmFiY8K2CntgXiguKinCti4qXDEuKgokMMK2JDEKfVRgX2xgbDtgXi4qCjJgLirCtj8K&input=aGlqYWNraW5n) --- Naive solution: ``` D`. O`. !&`abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz ``` Deduplicate, Sort, then output overlapping matches of 3 sequential letters. [**Try it online**](http://retina.tryitonline.net/#code=RGAuCk9gLgohJmBhYmN8YmNkfGNkZXxkZWZ8ZWZnfGZnaHxnaGl8aGlqfGlqa3xqa2x8a2xtfGxtbnxtbm98bm9wfG9wcXxwcXJ8cXJzfHJzdHxzdHV8dHV2fHV2d3x2d3h8d3h5fHh5eg&input=aGlqYWNraW5n) [Answer] # JavaScript (Firefox 48), 93 bytes ``` x=>[for(c of a=[...new Set(x,i=0)].sort())if(parseInt(d=c+a[++i]+a[i+1],36)%1333==38&!d[3])d] ``` This lends itself to a **96-byte ES6 version**: ``` x=>[...new Set(x)].sort().map((c,i,a)=>c+a[i+1]+a[i+2]).filter(x=>!x[3]&parseInt(x,36)%1333==38) ``` ### How it works The first major chunk of the function is this: ``` [...new Set(x)].sort() ``` `new Set(string)` creates a Set object that contains one of each unique character in the string. For example, `new Set("foghorn")` will return `Set ["f", "o", "g", "h", "r", "n"]`. We can convert this into an array with `[... ]`, then sort it with the built-in `.sort()`. This turns `"foghorn"` into `["f", "g", "h", "n", "o", "r"]`. The next step is this: ``` .map((c,i,a)=>c+a[i+1]+a[i+2]) ``` This maps each `c`haracter in the `a`rray to the character concatenated with the two items after it. For example, `["f", "g", "h", "n", "o", "r"] => ["fgh", "ghn", "hno", "nor", "orundefined", "rundefinedundefined"]`. (The `undefined`s pop up when you try to access a non-existent member of the array. The final step is filtering: ``` .filter(x=>!c[3]&parseInt(x,36)%1333==38) ``` First, the `!c[3]&` is to rule out any strings that contain `undefined`. This is necessary because a bug causes the following algorithm to count e.g. `gmundefined` as a consecutive triplet. All three-consecutive-char strings, when interpreted as base-36 numbers, are 38 modulo 1333. I figured this out by the following calculation: * 012 (base 36) = 38 * 123 (base 36) = 1371 * 1371 - 38 = 1333 * 1371 mod 1333 ≡ 38 mod 1333 ≡ 38 Therefore, if a three-char string is 38 mod 1333 in base-36, the three characters are consecutive in the alphabet. ### Test snippet ``` function test(x){O.innerHTML=/[^a-z]/.test(x)?"Invalid input":f(x);} f=x=>[...new Set(x)].sort().map((c,i,a)=>c+a[i+1]+a[i+2]).filter(x=>!x[3]&parseInt(x,36)%1333==38) ``` ``` <input id=I value="hijacked"> <button onclick="test(I.value)">Run</button> <pre id=O>cde,hij,ijk</pre> ``` [Answer] ## Racket 237 bytes ``` (define(f s)(let((lr(λ(l i)(list-ref l i)))(l(sort(map char->integer(string->list s))<)))(for((i(-(length l)2))) (when(=(-(lr l(+ i 2))(lr l(+ i 1)))1(-(lr l(+ i 1))(lr l i)))(for((j 3))(display(string(integer->char(lr l(+ i j)))))))))) ``` Testing: ``` (f "education") ``` Output: ``` cde ``` Detailed version: ``` (define(f2 s) (let ((lr (λ(l i)(list-ref l i))) (l (sort (map char->integer (string->list s)) <))) (for ((i (-(length l)2))) (when (= (- (lr l (+ i 2)) (lr l (+ i 1))) 1 (- (lr l (+ i 1)) (lr l i))) (for((j 3)) (display (string(integer->char (lr l (+ i j)))))))))) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 50 bytes `each_cons(3)` gets all consecutive sublists of length 3 from the alphabet `?a..?z`, then use `e&s.chars==e` to select only the ones that have all characters in the target string by using setwise intersection. Returns a list of lists. ``` ->s{(?a..?z).each_cons(3).select{|e|e&s.chars==e}} ``` [Try it online!](https://tio.run/##DYxLCoMwFAD3OUUQEaVtNt0J1oOUIs/4NPHzEpJIP@rZbVazmGHc2n7PvjpvD7/lNQhR/wqBIFUjDfn8XgiPM8qw7bhj5oVU4HxV4XGcb6Vn5AMGz7hdg@dpE7VZLL/wpORJRP9Mm5dYwOZZqcnbOCrEaDTlyZUnBUPqTuxWCUEbYr0ZlHHEJLTgMDClR5CTpoFZwnUxpIFNM3xiatH1xi1sRnAUiz8 "Ruby – Try It Online") [Answer] # [R], 110 bytes ``` f=function(b){a=combn(sort(utf8ToInt(b)),3);apply(unique(t(a[,which(apply(diff(a),2,prod)==1)])),1,intToUtf8)} ``` I'm sure its still golfable [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~10~~ 9 bytes ``` ;Cã3 fUá3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0PjMyBmVeEz&input=ImVkdWNhdGlvbiI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O0PjMyBmVeEz&input=WwoiZWR1Y2F0aW9uIiAgLT4gIGNkZQoiZm9naG9ybiIgICAgLT4gIGZnaAoiY2FiYXJldCIgICAgLT4gIGFiYwoiaGlqYWNraW5nIiAgLT4gIGdoaSwgaGlqLCBpamsKInBuZXVtb25pYSIgIC0%2bICBtbm8sIG5vcAoia2xheG9uIiAgICAgLT4KInBlcmZvcm0iICAgIC0%2bCiJsZWFybmluZyIgICAtPgpdCi1tUg) ``` ;Cã3 fUá3 :Implicit input of string U ;C :Lowercase alphabet ã3 :Substrings of length 3 f :Filter elements contained in Uá3 :Permutations of U of length 3 ``` ]
[Question] [ Write a program or a function to print the following cube (if you allow me to call it so) in different sizes: ``` ^L^L^L^L^L^L^L^L^L^L^L //^L^L^L^L^L^L^L^L^L^L^L ////^L^L^L^L^L^L^L^L^L^L^L //////^L^L^L^L^L^L^L^L^L^L^L ////////^L^L^L^L^L^L^L^L^L^L^L //////////^L^L^L^L^L^L^L^L^L^L^L ////////////^L^L^L^L^L^L^L^L^L^L^L //////////////^L^L^L^L^L^L^L^L^L^L^L ////////////////^L^L^L^L^L^L^L^L^L^L^L //////////////////^L^L^L^L^L^L^L^L^L^L^L ////////////////////^L^L^L^L^L^L^L^L^L^L^L \\\\\\\\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\\\ " " " " " " " " " " " \\\\\\\\\\ " " " " " " " " " " " \\\\\\\\ " " " " " " " " " " " \\\\\\ " " " " " " " " " " " \\\\ " " " " " " " " " " " \\ " " " " " " " " " " " " " " " " " " " " " " ``` The shape is made of pairs of characters: `^L`, `"`, `\\`, `//` ### Input: An integer greater than 1, representing the size of the shape. The one showed above has a size of 11 because each side of each face is made of 11 pairs of characters. Note that only two faces are fully displayed. ### Output: A cube of the given size. Here's another example, with a size of 5: ``` ^L^L^L^L^L //^L^L^L^L^L ////^L^L^L^L^L //////^L^L^L^L^L ////////^L^L^L^L^L \\\\\\\\ " " " " " \\\\\\ " " " " " \\\\ " " " " " \\ " " " " " " " " " " ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest in bytes wins. Even though you are not required to do so, it would be nice if you could provide an easy way to check the output of your code [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` k=n=input() while 1:k-=1;i=k^k/n;print' '*i+(n+~i)*2*'\/'[k/n-1]+'^ L"'[k<0::2]*n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9s2zzYzr6C0REOTqzwjMydVwdAqW9fW0DrTNjsuWz/PuqAoM69EXUFdK1NbI0@7LlNTy0hLPUZfPRooqWsYq60ep@CjBOTZGFhZGcVq5f3/b2gIAA "Python 2 – Try It Online") Reuses some ideas from my answer on [Draw an ASCII hexagon of side length n](https://codegolf.stackexchange.com/a/217375/20260), including using the index `k/n-1` both to select between `/` and `\` in an order where the `\` doesn't need escaping, as well as to terminate the loop with error at the end. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~27~~ 22 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` {╷2×/×^L⁸×+]:↕vL∙ "╋∔r ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJXUyNTc3JXVGRjEyJUQ3LyVENyU1RUwldTIwNzglRDcldUZGMEIldUZGM0QldUZGMUEldTIxOTV2TCV1MjIxOSUyMCUyMiV1MjU0QiV1MjIxNCV1RkY1Mg__,i=NQ__,v=8) ## Explanation ``` {|2×/×^L⁸×+]:↕vL∙ "╋∔r { ] map each i from 1 to n: |2× decrement and double i /× repeat "/" that many times ^L⁸× repeat "^L" n times + add that to get one line : copy the top half ↕ mirror vertically (mirrors characters) vL∙" ╋ replace 'vL' with '" ' ∔ and add vertically r center the whole art ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` ->n{puts (0...n).map{|i|puts ' '*(j=n+~i)+?/*i*2+'^L'*n;' '*i+?\\*j*2+' "'*n}} ``` Builds an array for the bottom half while printing the top half, then dumps the bottom half at the end. I also tried recursion but it was longer. [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vuqC0pFhBw0BPTy9PUy83saC6JrMGLKauoK6lkWWbp12Xqaltr6@VqWWkrR7no66VZw2SytS2j4nRygIJKigBBWtr/6dFm8b@BwA "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 121 bytes ``` s=>(j=n=>' '[b="repeat"]((a=n>=s)?n-s:s+~n)+(a?"//":"\\\\")[b](a?s*2-n:n+1)+(a?"^L":' "')[b](s)+'\n'+(~n?j(--n):''))(s*2) ``` [Try it online!](https://tio.run/##JYtBCoMwEEWvUrLJjCHaugxEL9CeQC0kGlrFTsSRLr16KvWvHu/xJ/d13K/jsmmKQ0jeJrYVTJZsJS@y8VasYQluEx2As1RZxpo0G1Y7oQJXi6IQRrTHBDa@OwxnpSZD6nb2510YeRHyXxmVbEkq2KmeQGtCIyUiHB9MfSSOc8jn@AIPD7e98z6M80mroyF@ALPyiojpBw "JavaScript (Node.js) – Try It Online") [Answer] # [K (ngn/k)](https://git.sr.ht/%7Engn/k), 69 bytes ``` {` 0:,/',/$(`" "`"//"`"^L";`" "`"\\\\"`" \"")@'&''(t;|t:+(|!x;!x;x))} ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6pOUDCw0tFX19FX0UhQUlBKUNLXBxJxPkrWEG4MEAAphRglJU0HdTV1dY0S65oSK22NGsUKayCq0NSs5eJKUzA0BAC+2xJX) Not a great fit for the language, but an interesting exercise... * `(t;|t:+(|!x;!x;x))` build a nested list containing the number of copies of each type of symbol to take. (i.e. spaces from x..0,0..x, slashes from 0..x,x..0, and x copies of `^L` and `"`). * `&''` convert to indices, e.g. `3 1 5` => `0 0 0 1 2 2 2 2 2` * `(`" "`"//"`"^L";`" "`"\\\\"`" \"")` build another nested list (of the same shape), this time containing symbol versions of the output characters. This avoids having to enlist the individual strings and simplifies the list notation a bit. Since they contain special characters (as opposed to being alphanumeric), the contents need to be enclosed in `"`'s, with `"` and `\` also needing to be escaped. * `(...)@'(...)` retrieve the correct number of copies of each type of symbol * `,/',/$` stringify the symbols, and raze them into the lines of the output * `` 0:` print them (this elides the wrapping `"`s and `\` escapes otherwise present) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ 26 bytes -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! Without [this bug](https://github.com/Adriandmen/05AB1E/issues/181), `»∊¶¡` could be just `∊`. ``` L<·'/×»∊¶¡„^L„ "‚I×Iδи˜ø.c ``` [Try it online!](https://tio.run/##ATgAx/9vc2FiaWX//0w8wrcnL8OXwrviiIrCtsKh4oCeXkzigJ4gIuKAmknDl0nOtNC4y5zDuC5j//8xMQ "05AB1E – Try It Online") **Commented**: ``` L<·'/×»∊¶¡ # generate the left part L # push the range [1..n] < # decrement to get [0..n-1] · # double each value: [0, 2, ..., 2*(n-1)] '/ # push the string '/' × # for each number in the list, repeat the string this many times »∊¶¡ # vertically mirror to get lower left half „^L„ "‚I×Iδи˜ # generate the right part „^L # push the string '^L' „ " # push the string ' "' ‚ # pair into a list: ['^L', ' "'] I× # repeat each string input times Iδи # for each string create a list containing the string input times ˜ # flatten into a single list ø # zip both parts to get the rows .c # join each row, centralize and join by newlines ``` [Try it with step-by-step output!](https://tio.run/##bVJNSsNAGN17io9uqhJTq7uiBxB6g2Jhkn5tRiYzYeZLS7vqUryAIiJ4B38K7tqlIJ6hF4mTZIJTaTYhmffe9977RhkWcSyKPthnu3zIcpMAJQiayQnCoBuG8rpXngSXm7fg4MLhRhhrTFESkIIJEgxOLfKk62PXHw1Y5ZFAQBYnMGUix56FB3AWQBiG9n18aJlHPrXd@WfHkOZyAu1O20Nt7t2AsdK1uszTCDVwWZEENxSAxgwZ@SqUcAMpk3MgnqLxLX9ub@/W7@uX8tcUNfGYCTGHlGttZ7isQs3sEIFjgoSJscffLp@H/f3Oh/32LhBa@4HQ2gU@NqthvExmPbAqmS2xFA0qhl/eVdWL/XTJq2acOpdZTnVs8Cnfrz@r3Sodwa6ZEbqRECtJjMu6RNwj6ml@PTXbEYwIZePdWIpAF@FvlyuHXvAMIkUJZEyTaSqvrqSa@fphXBNulF13ZdkCAojtpdRM8IU1LUdQnUZzkDgTXPoGi@L8Fw) Some slightly longer alternatives: ``` L<·'/×»∊¶¡εNI@i„ "ë„^L}I׫}.c L<·'/×»∊¶¡ε„^LNI@i„ "}I×yì}.c L<·Â«εNI@i'\ׄ "ë'/ׄ^L}I׫}.c ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 88 bytes ``` param($n)$n..1|%{($l=' '*--$_)+'//'*($j=$n-$_-1)+'^L'*$n $b=,($l+'\\'*$j+' "'*$n)+$b} $b ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyVPT8@wRrVaQyXHVl1BXUtXVyVeU1tdX19dS0Mly1YlD8jXNQSKxPmoa6nkcakk2eoA1Wqrx8QA@Vna6gpKIHFNbZWkWqDk////TQE "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~104~~ ~~102~~ 92 bytes, Alternative ``` param($n),{$l='//';'^L';$i++}*$n+,{$l='\\';--$i;' "'}*$n|%{.$_}|%{' '*($n-$i-1)+$l*$i+$_*$n} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPU6daJcdWXV9f3Vo9zkfdWiVTW7tWSyVPGyIeE6NuraurkmmtrqCkDhKvUa3WU4mvBVLqCupaQAOAkrqGmtoqOVpArSrxQCW1////NwUA "PowerShell – Try It Online") The script generates the array of scriptblocks and executes its in the same context. Less golfed: ``` param($n)filter g{' '*($n-$i-1)+$l*$i+$_*$n} ,{$l='//';'^L'|g;$i++}*$n+,{$l='\\';--$i;' "'|g}*$n|%{.$_} ``` [Answer] # Java 11, ~~148~~ 136 bytes ``` n->{String r="",t=r;for(int i=n;i-->0;t+=" ")r=t+"//".repeat(i)+"^L".repeat(n)+"\n"+r+t+"\\\\".repeat(i)+" \"".repeat(n)+"\n";return r;} ``` -12 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##hZDBasMwEETv@YpFJwnVTtPSk1C@oMklx7oFVVGCUmdt1utACf52d5OaQgslexDMzluY0SGcQnHYfoyxDl0Hq5DxPAPIyIl2ISZYXyTAhinjHqIWB9A4WQ4zeToOnCOsAcGPWCzPE0heqTv25HYNXW@yR5eLYnnv2HoFypBnq@ZzVVJqU2CdjVVvzz8SRVaoLFnBKplfIFTqL@kocU8I5IbRXaK1/Xst0aaEpyZv4Sj19HfCl1cIZur22XE6lk3PZSsW16ixjPrJXGv@6z/e8BeLG8CDmf5xGL8A) **Explanation:** ``` n->{ // Method with integer parameter and String return-type String r="", // Result-String, starting empty t=r; // Temp-string, starting empty as well for(int i=n;i-->0 // Loop `i` in the range [input, 0): ; // After every iteration: t+=" ") // Append a space to `t` r=...+r+...; // Change the result-String to: // Prepend to the result-String: t // The spaces `t` +"//".repeat(i) // plus '//' repeated `i-1` amount of times +"^L".repeat(n) // plus '^L' repeated the input amount of times +"\n" // plus a newline // Append to the result-String: t // The spaces `t` again +"\\\\".repeat(i) // plus '\\' repeated `i-1` amount of times +" \"".repeat(n) // plus ' "' repeated the input amount of times +"\n"; // plus a newline again return r;} // After the loop, return the result-String ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~42~~ 32 bytes ``` NθG⌈⊖θ\↓‖C‖M↑Fθ«P×^Lθ↘»Fθ«P×" θ↙ ``` [Try it online!](https://tio.run/##fYyxDoIwFEVn@IqmU0lwdMFRFhMxhuhGTBAf0KT0lWfBEOPu4Ff6I7VxYTGO995zbtWWVGGpnNtoM9jd0J2BRB@twj2qqUEtkvfrGbMUKoIOtIWLX2PGi4J7KMMRRJLiTfuQQ62gsms0k5hjJomQRHI0vquRmPfZPQyyQVlpSGorDrKDq@CnLY9ZH3ksmH9z2bTWV4//bsHZD3kL9dd1bukWo/oA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the size. ``` G⌈⊖θ\↓ ``` Print a small triangle of `\`s. ``` ‖C‖M↑ ``` Reflect it twice, once horizontally to complete the bottom left block of `\`s, once vertically with mirroring to produce the top left block of `/`s. ``` Fθ«P×^Lθ↘» ``` Print the top right block of `^`s and `L`s. ``` Fθ«P×" θ↙ ``` Print the bottom right block of `"`s and spaces. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~97 93~~ 92 bytes ``` lambda a:sum(zip(*((' '*(x:=a+~i)+'//'*i+'^L'*a,' '*i+r'\\'*x+' "'*a)for i in range(a))),()) ``` [Try it online!](https://tio.run/##FclBCsIwEIXhqwxuZiYpdCGCFHoDjxCEEY0OpGmIKVQXXj0mi7f4v5c@5bXG4znl6mdXgyy3u4BM722hryYyRAhoaJ9msT9li@OIRi1eL2hk6J/ajM6h2S3CoSH7NYOCRsgSnw8SZh6IuXYP3T1pLG1pK815Srl34Hr6Aw "Python 3.8 (pre-release) – Try It Online") Output is a [tuple of lines](https://codegolf.meta.stackexchange.com/a/17095). *-4 by @Seb* *-1 by @Danis* [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~160~~ ~~135~~ 130 bytes Saved 5 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` p(n,c){for(;n--;)printf(L"\n//\\\\L^ \" "+c+n%2);}i;t;f(n){for(t=i=1;i;i+=t,t=i>n?i=n,-1:t)p(n-i,9),p(!p(2*n,6-t),p(2*~-i,2-t));} ``` [Try it online!](https://tio.run/##PU7RCsIwDHzfV8SB0K4tYwMVjdUf8BOGMAqTgsaxFXwY89OtKRPvJdzlcjlnbs7F2AvSTk7dcxBIxqDsB0@hE5e8obJsGJcrNDlArpyidS1x9hiwE7QcBetthR69skEzOdHZW9KmOgTJ2cbrvdS9WPWiLkhvTUisLt68qJlwXOR/8Gg9CZlNGTA4F0RSCSxskMfRwg5BKZKwWBKSY2RH6oJ/9def6@c/dc7mLH5cd29vYzSvLw "C (gcc) – Try It Online") ### Explanation (before some golfs) ``` d;p(n,c){ // p is a helper function that prints // n/2 pairs of chars for(d=0;n--;d^=1) // loop n times, flipping d between // 0 and 1 each time printf(L" // print one char of a pair of // chars based on c (then select the // other one on the next loop as d // flips between 0 and 1): // // c==0: '//' \\\\ // c==2: '\\' ^L // c==4: '^L' \" // c==6: '" ' // c==7: any number of spaces \n" // c==9: p(1,9) prints a newline +c+d); // use c and d to select char } // returns 0 i;t;f(n){ // f is the main function for(t=i=1; // main loop i goes from 1 to n and // back down to 1 again i; // loop until i is 0 i+=t, // bump i up for 1st half and then // bump i down for 2nd half t=i>n?i=n,-1:t) // flip t from 1 to -1 half way thru p(n-i,7), // print leading spaces p(2*~-i,1-t), // print left side slashes p(2*n,5-t), // print right side of cube p(1,9); // print newline } // ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḶṚżḤƊØ.xⱮ;€3,5ẋ$;ṚḤ$$ị“/\^"L ” ``` A monadic Link accepting a positive integer which yields a list of lists of characters (a list of lines). **[Try it online!](https://tio.run/##AUUAuv9qZWxsef//4bi24bmaxbzhuKTGisOYLnjisa474oKsMyw14bqLJDvhuZrhuKQkJOG7i@KAnC9cXiJMIOKAnf/Dh1n//zQ "Jelly – Try It Online")** (The footer calls the Link and joins the resulting lines with newline characters.) ### How? ``` ḶṚżḤƊØ.xⱮ;€3,5ẋ$;ṚḤ$$ị“/\^"L ” - Link: integer, n e.g. 3 Ḷ - lowered range [0,1,2] Ɗ - last three links as a monad - f(that): Ṛ - reverse [2,1,0] Ḥ - double [0,2,4] ż - zip together [[2,0],[1,2],[0,4]] Ɱ - map with: Ø. - bits [0,1] x - repeat elements [[0,0],[0,1,1],[1,1,1,1]] $ - last two links as a monad - f(n): 3,5 - three pair five [3,5] ẋ - repeat (n times) [3,5,3,5,3,5] ;€ - concatenate each = x [[0,0,3,5,3,5,3,5],[0,1,1,3,5,3,5,3,5],[1,1,1,1,3,5,3,5,3,5]] $ - last two links as a monad - f(x): $ - last two links as a monad - f(x): Ṛ - reverse [[1,1,1,1,3,5,3,5,3,5],[0,1,1,3,5,3,5,3,5],[0,0,3,5,3,5,3,5]] Ḥ - double [[2,2,2,2,6,10,6,10,6,10],[0,2,2,6,10,6,10,6,10],[0,0,6,10,6,10,6,10]] ; - concatenate [[0,0,3,5,3,5,3,5],[0,1,1,3,5,3,5,3,5],[1,1,1,1,3,5,3,5,3,5],[2,2,2,2,6,10,6,10,6,10],[0,2,2,6,10,6,10,6,10],[0,0,6,10,6,10,6,10]] “/\^"L ” - list of characters = '/\^"L ' ị - index into (1-indexed & modular, i.e. 10->") -> [' ^L^L^L', ' //^L^L^L', '////^L^L^L', '\\\\ " " "', ' \\ " " "', ' " " "', ] ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 27 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╚lTà╨ú%Ñ►F↔33j♦ü♂D▄P;L.⌂î↑ ``` [Run and debug it](https://staxlang.xyz/#p=81c86c5485d0a325a510461d33336a04810b44dc503b4c2e7f8c18&i=5%0A10&a=1&m=2) [Answer] # [PHP](https://php.net/), ~~134~~ 116 bytes ``` for($f=str_repeat;$i<$n=$argn;)$s=($t=$f(" ",$i++).$f("//",$n-$i).$f("^L",$n)." ").$s.strtr($t,'/^L','\\ "');echo$s; ``` [Try it online!](https://tio.run/##JcyxCsMgFIXhvU8R5IJKjE6djHTrlEcICaFo46IXvc9fa8hy4DvDjye2@YV9Qy4CgqtU9uLRH2QhzpAcHOWbrITqBJCDINjAFMRxlPqCMV1pgnhzWy5KzR6sH1X3HPUuKW62hSu@rgPj0vrPmaHa1p6/jBRzqm16/wE "PHP – Try It Online") Yes, much shorter to build the string.. **EDIT:** a huge 18 bytes saved thanks to optimization from Dom Hastings **Old version kept just for the fun:** # 157 bytes ``` for($f=str_repeat;$i<2*$n=$argn;$s.='//')$i++<$n?printf("%".($n-2+$i)."s%s",$s,$f("^L",$n)." "):printf("%".(5*$n-$i)."s",$f('\\',4*$n-2*$i).$f(' "',$n)." "); ``` [Try it online!](https://tio.run/##TY3LCsIwEEX3foUMU5KYPqDYjU3pzpWfUJQuGs1mEpJ8v3GKIG6G4cy5d8IrFDMHntZHiXZKOT7iFrY1j@hMf0KacI1PGjG1k@g6odBpbZDmEB1lK6GCViI1vUanWkhVghpTjXy533glhgdQl3994Nrmq8NuimUR9XmH/JDxjo4gfuGxlOHtQ3aeUmmuHw "PHP – Try It Online") Here is an infamous PHP answer based on `printf`. Couldn't think of an uglier looking piece of code for now, but I'll work on it (starting to think it would be better to build the whole string)! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 172 bytes ``` (m=MapThread[Join,{DiamondMatrix[#][[1;;#+1,1;;#]],2BoxMatrix[#][[1;;#+1,1;;#+1]]}];Print/@StringJoin@@@(Join[m,4Reverse[m]]/.{0->" ",1->"//",2->"^L",4->"\\\\",8->" \""}))& ``` [Try it online!](https://tio.run/##bcxBC4IwHAXwrxILQnE1NQ@BGCM6RUJYt/kPRk7dYTPWCEH87Lbde5ff4T2e4rYXilv54ktbLIEqSv5@9Ebwhl0GqfF0llwNuim5NXJka2AsyfN1lGAPAE5Pw/i/jBKAGfKbkdoSencT3flPSmngZQpnlfgK8xFMAZDdFG@PaIVw4iAE4dT5vCKcOWsXhA9@UCM0h@FmaQmtuO4E28ew/AA "Wolfram Language (Mathematica) – Try It Online") **Brief explanation**: Construct the upper part `m` with [DiamondMatrix](https://reference.wolfram.com/language/ref/DiamondMatrix.html) and [BoxMatrix](https://reference.wolfram.com/language/ref/BoxMatrix.html): ``` m = MapThread[Join, {DiamondMatrix[n][[1 ;; n + 1, 1 ;; n]], 2BoxMatrix[n][[1 ;; n + 1, 1 ;; n + 1]]}] ``` Derive the whole matrix `M` from `m`: ``` M = Join[m, 4*Reverse@m] ``` you can visualize it with: ``` MatrixPlot[M, Frame -> None] ``` when n = 10, it's like this: [![when n = 10](https://i.stack.imgur.com/ftFhG.png)](https://i.stack.imgur.com/ftFhG.png) Replace each number from the matrix with corresponding string: ``` M/.{0->" ",1->"//",2->"^L",4->"\\\\",8->" \""} ``` Convert each row to string and print it: ``` Print/@StringJoin@@@% ``` [Answer] # [Zsh](https://www.zsh.org/) [commit 2a96748](https://github.com/zsh-users/zsh/commit/2a9674862ecaf9b7b1b66178782d47e8445df325), ~~123~~ ~~121~~ 119 bytes ``` alias R=repeat R "i=a=$1" {s=${(l:--i:)};R b++ s+=//;R a s+=^L;<<<$s} R a {s=${(l:i++:)};R a-i s+='\\';R a s+=' "';<<<$s} ``` [Try it online!](https://tio.run/##qyrO@P8/MSczsVghyLYotSA1sYQrSEEp0zbRVsVQSaG62FalWiPHSlc300qz1jpIIUlbW6FY21ZfH8hOBLHifKxtbGxUimu5QAIw9Zna2hD1ibqZIFXqMTHqMB3qCkrqUD3///83BQA "Zsh – Try It Online") This specific version fixes a bug that would otherwise require `i=a=$1` to be in quotes. TIO doesn't have that version obviously, so the linked one is two bytes longer. [Answer] # batch ~~317~~ ~~309~~ ~~301~~ ~~291~~ ~~284 bytes~~ 276 bytes ``` Cls&@Set $=@Set %$%/Ah=%1*2,z=0 %$%F=@For /L %%a in (1 1 &%$%P=@^<nul set/p&%$%C= @If ,%%y LEQ %1 %f:a=y%!h!)Do @(%$%/Aw=%1-z %F%!w!)Do %P%=ESCC %F%!z!)Do%C%(%P%=//)Else %P%=\\ %F%%1)Do%C%(%P%=^^L)Else %P%^"=ESCC"" %C:EQ=SS%(%$%/A z+=1)Else%C:,=not %%$%/Az-=1 Echo() ``` **Cube.bat** Notes: * *must be run from the command line using:* `Echo(cube.bat n|Cmd /V:on` *where `n` is an integer representing cube size and cube.bat is the filename of the file* * lines `1` and`3` end wth trailing spaces * **requires windows 10 with virtual terminal support** * `ESC` is a stand in for the ANSI escape character, [As it can't be pasted here, the scripts raw paste data can be found here](https://pastebin.com/AaNxX84B). + Or it can be generated by opening the command prompt and typing: - `>"%TEMP%\escape.chr" Echo(``ALT`+`027` then pressing `ENTER` + Or output using a for loop with `Echo off`: - `(For /F "skip=4 DELIMS=" %a in ('Echo(prompt $E^|cmd')Do Echo(%a) >"%TEMP%\escape.chr"` Vt sequence `ESCC` *('cursor right')* is used to get around `<nul set /p`'s inability to output leading spaces. example output: [![enter image description here](https://i.stack.imgur.com/wNmR3.png)](https://i.stack.imgur.com/wNmR3.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` Ḷ,Ṛ$ạ’;,ʋ³ẋ@"ɗ€"“ “//“^L”,“ “\\“ "”ẎY ``` [Try it online!](https://tio.run/##y0rNyan8///hjm06D3fOUnm4a@GjhpnWOqe6D21@uKvbQenk9EdNa5QeNcxRAGJ9fSAR5/OoYa4OVCQmBsQAys99uKsv8v///5YA "Jelly – Try It Online") [Answer] # [Lua (LuaJIT)](https://luajit.org/), 122 bytes ``` r=n.rep;for i=1,n*2 do print(i<=n+0 and r(' ',n-i)..r("/",i*2-2)..r('^L',n)or r(' ',i-1-n)..r("\\\\",n*2-i)..r(' "',n))end ``` [Try it online!](https://tio.run/##LYxBCsMgFET3OcXHjZr6bRW6ar1Bj1AKUiP8Er5BkvNb03RgFsO8mXmLOG/xQ2vLG79XKgxZsW41sK3TcsulAgVnePSQCiyVeFV0D3y6QOQEVUmQhpG0tVWJszA0evS/JF@PXun@cFCEDvngnl1iP/0PJYgd1ROn1j0gOu@HrKy1urXrFw "Lua (LuaJIT) – Try It Online") (Above code abuses the TIO's input string-type to save 1 byte, see [Not abused version](https://tio.run/##LYzBCsIwEETv/Yoll2xKNtKcBO0f@AkiVNvASt2UkHx/TK0DcxjmzaxlorVMb841FHlljgIBxdQ0otbGpWW7hJiAx8FK72GOsCWWjHwdBSaZIaEGbYXYOJdQnZTl3pP/Jf24tcq0/UExDSQHd29S@@V/qEHtqFlkrs0d0eB9FzBHKZ/nktA5Z0yt5y8)) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 68 bytes ``` ~:i,.-1%]zip.-1%]{{~" "*\["//""\\\\"]0=*+["^L"' "']0=i*+}%1:0;n*}%n* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v84qU0dP11A1tiqzAExXV9cpKShpxUQr6esrKcUAgVKsga2WdrRSnI@SuoKSOpCXqaVdq2poZWCdp1Wrmqf1/78lAA "GolfScript – Try It Online") Its really messy, but it works and I don't really know a better way to do it. [Answer] # Excel, 114 bytes ``` =LET(x,A1,q,SEQUENCE(2*x),b,q>x,r,IF(b,q-x-1,x-q),REPT(" ",r)&REPT(IF(b,"\\","//"),x-r)&REPT(IF(b,"""""","^L"),x)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnB_Q6r1yxIKXAP04?e=DC5Wq8) [Answer] # [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 84 bytes ``` (( {#2-1}| {$~1-1})(//$3|)(^L){$~1}\n){$~1}(( $6|)(\\{#7-2}|\\{#3})( "){$~1}\n){$~1} ``` Takes the size as a command-line input. [Try it here!](https://replit.com/@dloscutoff/regenerate) ### Explanation Spaces are replaced with underscores for improved visibility. Top half: ``` (( {#2-1}| {$~1-1})(//$3|)(^L){$~1}\n){$~1} ( ) Group 1: one row of the top half ( ) Group 2: leading spaces _{#2-1} Either one less space than the previous row |_{$~1-1} or (input-1) spaces if this is the first row ( ) Group 3: slashes //$3 Either the previous row's slashes plus two more | or empty string if this is the first row (^L) Group 4: ^L {$~1} Repeat group 4 (input) times \n Newline {$~1} Repeat group 1 (input) times ``` Bottom half: ``` (( $6|)(\\{#7-2}|\\{#3})( "){$~1}\n){$~1} ( ) Group 5: one row of the bottom half ( ) Group 6: leading spaces _$6 Either the previous row's spaces plus two more | or empty string if this is the first row ( ) Group 7: backslashes \\{#7-2} Either two fewer slashes than the previous row |\\{#3} or the same number of slashes as in the last match of group 3 if this is the first row (_") Group 8: space-quote {$~1} Repeat group 8 (input) times \n Newline {$~1} Repeat group 5 (input) times ``` [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0 -pa`, 71 bytes ``` say,$\=y'/^L'\ "'r.$/.$\for map$"x("@F"-$_--)."//"x$_."^L"x"@F",1..$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJHJca2Ul0/zkc9RkFJvUhPRV9PJSYtv0ghN7FARalCQ8nBTUlXJV5XV1NPSV9fqUIlXk8pzkepAiSuY6inpxJfW/3/v@W//IKSzPy84v@6BYn/dX1N9QwN9AwA "Perl 5 – Try It Online") [Answer] # [Julia](http://julialang.org/), ~~79~~ ~~73~~ 69 bytes output is a list of lines ``` f(N,a=-N+1:0,b=0:N-1)=@.[" "^-a*"//"^b*"^L"^N;" "^b*"\\"^-2a*" \""^N] ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P03DTyfRVtdP29DKQCfJ1sDKT9dQ09ZBL1pJQSlON1FLSV9fKS5JSynORynOzxokCOTExADljICSCjFKQOHY/wVFmXklOXl6GmkappqaXEhcQ0NUvhGCC@H9BwA "Julia 1.0 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 26 bytes ``` ʁd\/*m‛^L‛ ""?*ƛw?ẋ;fZvṅøĊ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%CA%81d%5C%2F*m%E2%80%9B%5EL%E2%80%9B%20%22%22%3F*%C6%9Bw%3F%E1%BA%8B%3BfZv%E1%B9%85%C3%B8%C4%8A&inputs=10&header=&footer=) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 31 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Æç'Li^)i'/pXÑÃû c¡Xd`/\\^ L"`Ãw ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=xucnTGleKWknL3BY0cP7CmOhWGRgL1xcXiBMImDDdw&input=NQ) ``` Æç'Li^)i'/pXÑÃû\nc¡Xd`...`Ãw :Implicit input of integer U Æ :Map each X in the range [0,U) ç : U times repeat 'Li^ : "L" prepended with "^" ) : End repeat i : Prepend '/p : "/" repeated XÑ : X*2 times à :End map û :centre pad each element with spaces to the length of the longest \n :Reassign to U c :Concatenate ¡ : Map each X in U Xd`...` : For each pair of characters in the string, replace all occurrences of the first in X with the second à : End map w : Reverse :Implicit output joined with newlines ``` ]
[Question] [ ## Challenge: Take a list, **L** containing positive integers as input: ``` 3 5 2 1 6 ``` and create a matrix where the n'th column contains the vector **1:L(n)**, where shorter rows are padded with zeros. ### Test cases: ``` 3 5 2 1 6 ----------------- 1 1 1 1 1 2 2 2 0 2 3 3 0 0 3 0 4 0 0 4 0 5 0 0 5 0 0 0 0 6 1 - 1 1 2 3 4 3 2 1 ------------------------- 1 1 1 1 1 1 1 0 2 2 2 2 2 0 0 0 3 3 3 0 0 0 0 0 4 0 0 0 ``` ### Rules: * Optional input and output formats + List of lists is an acceptable output format * The matrix must be as small as possible (you may not pad it with more zeros than needed) * Shortest code in each language wins * Explanations are highly encouraged [Answer] # [R](https://www.r-project.org/), ~~40~~ 38 bytes ``` function(l)outer(m<-1:max(l),l,"<=")*m ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNHM7@0JLVII9dG19AqN7ECKKCTo6NkY6ukqZX7P00jWcNYx1THSMdQx0xT8z8A "R – Try It Online") Explanation: `outer` applies its third argument (the function) to all combinations of elements of its first two arguments, generating a matrix of `TRUE` and `FALSE` where each column has `TRUE` where `1:max(l)` is less than or equal to the corresponding element of `l`, for the example where `l=c(3,5,2,1,6)`: ``` [,1] [,2] [,3] [,4] [,5] [1,] TRUE TRUE TRUE TRUE TRUE [2,] TRUE TRUE TRUE FALSE TRUE [3,] TRUE TRUE FALSE FALSE TRUE [4,] FALSE TRUE FALSE FALSE TRUE [5,] FALSE TRUE FALSE FALSE TRUE [6,] FALSE FALSE FALSE FALSE TRUE ``` Then supposing the resultant matrix is `A`, then `A*m` -> `A[i,j]=A[i,j]*i` which coerces `TRUE` to 1 and `FALSE` to 0, producing the desired result. [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` "@:]Xho! ``` [Try it online!](https://tio.run/##y00syfn/X8nBKjYiI1/x//9oQwUjBWMFEyA2UjCMBQA "MATL – Try It Online") ### Explanation ``` " % Implicit input, L. For each k in L @ % Push k : % Range [1 2 ... k] ] % End Xh % Collect all stack contents in a cell array o % Convert to double matrix. The content of each cell is % right-padded with zeros if needed ! % Transpose. Implicitly display ``` [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` lambda x:[[-~i*(i<a)for a in x]for i in range(max(x))] ``` [Try it online!](https://tio.run/##FcYxDoMwDADAr0RMNjIDRTAgeEnI4AoClsBEgSEs/Xoqbrrw3NupTfbjlHc@vjOb1Ftb/aQEGRj9GQ0bUZPcW3kbWdcFDk6QEF0OUfSG0oNtqKUP1dQ5pGsJYzFpgfkP) [Answer] # Mathematica, 20 bytes ``` PadRight@Range@#& ``` Contains U+F3C7 (Mathematica's builtin `Transpose` function) [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) ### Usage ``` PadRight@Range@#&[{3, 5, 2, 1, 6}] ``` > > > ``` > { > {1, 1, 1, 1, 1}, > {2, 2, 2, 0, 2}, > {3, 3, 0, 0, 3}, > {0, 4, 0, 0, 4}, > {0, 5, 0, 0, 5}, > {0, 0, 0, 0, 6} > } > > ``` > > ### Explanation ``` PadRight@Range@#& Range@# (* Generate {1..n} for all elements of input *) PadRight@ (* Right-pad 0s so that all lists are equal length *)  (* Transpose the result *) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 26 bytes ``` @(x)((y=1:max(x))'<=x).*y' ``` Anonymous function that inputs a row vector and outputs a matrix. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTQ6PS1tAqN7ECyNZUt7Gt0NTTqlT/n6YRbaxgqmCkYKhgFqv5HwA "Octave – Try It Online") ### Explanation Consider input `x = [3 5 2 1 6]`. This is a row vector of size 1×5. `1:max(x)` gives the row vector `[1 2 3 4 5 6]`, which is assigned to variable `y`. The transpose of that, i.e. the column vector `[1; 2; 3; 4; 5; 6]`, is `<=`-compared (element-wise with broadcast) with the input `[3 5 2 1 6]`. The result is the 6×5 matrix ``` [1 1 1 1 1; 1 1 1 0 1; 1 1 0 0 1; 0 1 0 0 1; 0 1 0 0 1; 0 0 0 0 1] ``` Finally, multiplying (element-wise with broadcast) by the column vector `[1; 2; 3; 4; 5; 6]`, obtained as `y` transposed, gives the desired result: ``` [1 1 1 1 1; 2 2 2 0 2; 3 3 0 0 3; 0 4 0 0 4; 0 5 0 0 5; 0 0 0 0 6] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` €L0ζ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UdMaH4Nz2/7/jzbWMdUx0jHUMYsFAA "05AB1E – Try It Online") or as a [nicely formatted test suite](https://tio.run/##MzBNTDJM/V9TVvn/UdMaH4Nz2/4f2q1zeKvO/2hjHVMdIx1DHbNYrmhDIMtYxwSIgSJIfFMdMx1zHQsdy1gA) ``` €L # For each: get the range 1..input 0ζ # zip, padding with 0s ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes Returns a list of lists ``` T0mḣ ``` [Try it online!](https://tio.run/##yygtzv6vkJtb/Kip8X@IQe7DHYv///8fbaxjqmOkY6hjFgsA "Husk – Try It Online") ### Explanation ``` m Map over the input ḣ Range from 1 to n T0 Transpose, padding with 0s ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` .tSMQZ ``` **[Try it here!](https://pyth.herokuapp.com/?code=.tSMQZ&input=%5B1%2C1%2C2%2C3%2C3%2C1%2C1%2C1%5D&debug=0)** or **[Verify all the test cases (with pretty-print)!](https://pyth.herokuapp.com/?code=j.tSMQZ&input=%5B1%2C1%2C2%2C3%2C4%2C3%2C1%2C1%2C1%5D&test_suite=1&test_suite_input=%5B3%2C5%2C2%2C1%2C6%5D%0A%5B1%5D%0A%5B1%2C2%2C3%2C4%2C3%2C2%2C1%5D&debug=0)** --- # Explanation ``` .tSMQZ - Full program. SMQ - Get the inclusive unary ranges for each. .t - Transpose, padding with copies of... Z - ... Zero. - Implicit print. ``` A non-built-in transpose version [would be](https://pyth.herokuapp.com/?code=jmm%2ahd%3CdkQeS&input=%5B1%2C1%2C2%2C3%2C4%2C3%2C1%2C1%2C1%5D&test_suite=1&test_suite_input=%5B3%2C5%2C2%2C1%2C6%5D%0A%5B1%5D%0A%5B1%2C2%2C3%2C4%2C3%2C2%2C1%5D&debug=0): ``` mm*hd<dkQeS ``` This works as follows: ``` mm*hd<dkQeS - Full program. m eS - Map over [0, max(input)) with a variable d. m Q - Map over the input with a variable k. hd - d + 1. * - Multiplied by 1 if... <dk - ... d is smaller than k, else 0. - Output implicitly. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` Rz0 ``` [Try it online!](https://tio.run/##y0rNyan8/z@oyuD/4Xb3//8NdYx0jHVMgNhIxxAA "Jelly – Try It Online") ## Explanation ``` Rz0 Input: array A R Range, vectorizes to each integer z0 Transpose and fill with 0 ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 17 bytes ``` ;M╗♂R⌠╜;0@α(+H⌡M┬ ``` [Try it online!](https://tio.run/##ATkAxv9hY3R1YWxsef//O03ilZfimYJS4oyg4pWcOzBAzrEoK0jijKFN4pSs//9bMywgNSwgMiwgMSwgNl0 "Actually – Try It Online") Explanation: ``` ;M╗♂R⌠╜;0@α(+H⌡M┬ ;M╗ store the maximal element (M) of the input in register 0 ♂R range(1, n+1) for each n in input ⌠╜;0@α(+H⌡M for each range: ╜;0@α push a list containing M 0s (+ append to range H take first M elements ┬ transpose ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 3 bytes This uses the new feature of Pyke, hex encodings... The best part is that we tie Jelly! Raw bytes: ``` 4D 53 AC ``` [Try it here!](http://pyke.catbus.co.uk/?code=4D+53+AC&input=%5B1%2C2%2C3%2C4%2C3%2C2%2C1%5D&warnings=0&hex=1) The ASCII-Pyke equivalent would be [4 bytes](http://pyke.catbus.co.uk/?code=MS.%2C&input=%5B1%2C2%2C3%2C4%2C3%2C2%2C1%5D&warnings=0&hex=0): ``` MS., ``` # How? ``` 4D 53 AC - Full program. 4D - Map. 53 - Inclusive range. AC - Transpose with zeroes. - Output implicitly. ------------------------------------- MS., - Full program. M - Map. S - Inclusive range. ., - Transpose with zeroes. - Output implicitly. ``` [Here](http://pyke.catbus.co.uk/?code=MS.%2CJ&input=%5B1%2C2%2C3%2C4%2C3%2C2%2C1%5D&warnings=0&hex=0) is a pretty-print version with ASCII, and [here](http://pyke.catbus.co.uk/?code=4D+53+AC+4A&input=%5B1%2C2%2C3%2C4%2C3%2C2%2C1%5D&warnings=0&hex=1) is one with hex encodings. [Answer] # [Perl 6](https://perl6.org), 39 bytes ``` {zip (1 X..$_).map:{|@_,|(0 xx.max-1)}} ``` [Try it](https://tio.run/##PY7NDoIwEITvPMUcjJREGusPBwmGq2/gwcQYrQkJQtOCosCTefPFcGuJh8lm55vMrpI6j4baSNwjfo692xPTc3mRSIb2lSkwgT3nk2PAbye1abv0OOvYHE1DexOKoO@Ha6mRZ4U0LPi8@aPUF0NzV1QIt0izQtUVWg@g6oOWps4rJLA3mINBTNCGfJf1Z87nin77s7KuHHQVf8ita19w/phnVNoPSwBr0oIkSJEnPDHulq3G@eNf "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 zip (1 X.. $_) # turn each input into a Range that starts with 1 .map: # map each of those Ranges using the following code { # bare block lambda with implicit parameter 「@_」 # (「@_」 takes precedence over 「$_」 when it is seen) |@_, # slip the input into a new list |( # slip this into the list 0 # a 「0」 xx # list repeated by .max # the max of 「$_」 (implicit method call) - 1 # minus 1 (so that zip doesn't add an extra row) ) } } ``` Note that [`zip`](https://docs.perl6.org/routine/zip.html) terminates once the shortest input list is exhausted. [Answer] ## [C#](http://csharppad.com/gist/c8eefd5e0d7cd1078cf157bd0a2d61ab), 136 bytes --- ### Data * **Input** `Int32[]` `i` An array of ints * **Output** `Int32[,]` A bidimentional array. --- ### Golfed ``` i=>{int m=System.Linq.Enumerable.Max(i),l=i.Length,x,y;var o=new int[m,l];for(y=0;y<m;y++)for(x=0;x<l;)o[y,x]=i[x++]>y?y+1:0;return o;}; ``` --- ### Ungolfed ``` i => { int m = System.Linq.Enumerable.Max( i ), l = i.Length, x, y; var o = new int[ m, l ]; for( y = 0; y < m; y++ ) for( x = 0; x < l; ) o[ y, x ] = i[ x++ ] > y ? y + 1 : 0; return o; }; ``` --- ### Ungolfed readable ``` // Take an array of Int32 i => { // Store the max value of the array, the length and declare some vars to save some bytes int m = System.Linq.Enumerable.Max( i ), l = i.Length, x, y; // Create the bidimensional array to output var o = new int[ m, l ]; // Cycle line by line... for( y = 0; y < m; y++ ) // ... and column by column... for( x = 0; x < l; ) // And set the value of the line in the array if it's lower than the the value at the index of the input array o[ y, x ] = i[ x++ ] > y ? y + 1 : 0; // Return the bidimentional array. return o; }; ``` --- ### Full code ``` using System; using System.Collections.Generic; namespace TestBench { public class Program { // Methods static void Main( string[] args ) { Func<Int32[], Int32[,]> f = i => { int m = System.Linq.Enumerable.Max( i ), l = i.Length, x, y; var o = new int[ m, l ]; for( y = 0; y < m; y++ ) for( x = 0; x < l; ) o[ y, x ] = i[ x++ ] > y ? y + 1 : 0; return o; }; List<Int32[]> testCases = new List<Int32[]>() { new[] { 1, 2, 5, 6, 4 }, new[] { 3, 5, 2, 1, 6 }, new[] { 1, 2, 3, 4, 3, 2, 1 }, }; foreach( Int32[] testCase in testCases ) { Console.WriteLine( " INPUT: " ); PrintArray( testCase ); Console.WriteLine( "OUTPUT: " ); PrintMatrix( f( testCase ) ); } Console.ReadLine(); } public static void PrintArray<TSource>( TSource[] array ) { PrintArray( array, o => o.ToString() ); } public static void PrintArray<TSource>( TSource[] array, Func<TSource, String> valueFetcher ) { List<String> output = new List<String>(); for( Int32 index = 0; index < array.Length; index++ ) { output.Add( valueFetcher( array[ index ] ) ); } Console.WriteLine( $"[ {String.Join( ", ", output )} ]" ); } public static void PrintMatrix<TSource>( TSource[,] array ) { PrintMatrix( array, o => o.ToString() ); } public static void PrintMatrix<TSource>( TSource[,] array, Func<TSource, String> valueFetcher ) { List<String> output = new List<String>(); for( Int32 xIndex = 0; xIndex < array.GetLength( 0 ); xIndex++ ) { List<String> inner = new List<String>(); for( Int32 yIndex = 0; yIndex < array.GetLength( 1 ); yIndex++ ) { inner.Add( valueFetcher( array[ xIndex, yIndex ] ) ); } output.Add( $"[ {String.Join( ", ", inner )} ]" ); } Console.WriteLine( $"[\n {String.Join( ",\n ", output )}\n]" ); } } } ``` --- ### Releases * **v1.0** - `136 bytes` - Initial solution. --- ### Notes * None [Answer] # [Perl 5](https://www.perl.org/), ~~62~~ 57 + 1 (`-a`) = 58 bytes ``` $,=$";say map$i*($_-->0),@F while++$i&&(sort{$b-$a}@F)[0] ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx1ZFybo4sVIhN7FAJVNLQyVeV9fOQFPHwU2hPCMzJ1VbWyVTTU2jOL@opFolSVclsdbBTTPaIPb/f0MFIwVjBRMgtlAw/JdfUJKZn1f8X9fXVM/A0OC/biIA "Perl 5 – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 17 bytes ``` {a*~x</:a:1+!|/x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6pO1KqrsNG3SrQy1Fas0a+o5eJKczBWMFUwUjBUMAOyDYEsYwUTIAaKAAA2CAsF) [Answer] # [C (gcc)](https://gcc.gnu.org/), 142 bytes ``` i,j,k;main(c,v)char**v;{for(;++i<c;k=k<*v[i]?*v[i]:k)printf("%c ",*v[i]);for(i=48;puts(""),i++<k;)for(j=1;j<c;)printf("%c ",i<=*v[j++]?i:48);} ``` [Try it online!](https://tio.run/##VYzNCoMwEIRfpQQKiYkHfw7iJvggxYMsaDepVqL1Uvrq3aq3HmYO8/ENpgMiMxlvAowdTRLNpvDexSTZ4N0/owStySIEF2yy3ahtzq6DmiNNay/FFS/CnKOCQyBXVjC/1kUKoQxpbQOoA3iXgd@v/k2ybpe91m1DdVkp@DBzxjkXXO7JOfti/@iGhdOxyH8 "C (gcc) – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 38 bytes ``` a=>[[i<j?-~i:0for j:a]for i:0..max(a)] ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@z/R1i46OtMmy163LtPKIC2/SCHLKjEWRAO5enq5iRUaiZqx/wuKMvNKNNRj8tT1svIz8zRyEwvAuLikSFNBW0FdQUEBIqOjkKYRbaxjqmOkY6hjFqsJBP8B "Proton – Try It Online") [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 37 bytes ``` D,g,@@*,bL_1+0XA$p$+bUp L~*,€RAbM€gBc ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HwUFLJ8kn3lDbIMJRpUBFOym0gMunTkvnUdOaIMckXyCV7pQMVJmVn5mn41Cnw6UABMZGzllcXEDtRZkpOg4QMcPYpFAwA6ilGqS6Nu///2hjBVMFIwVDBbPYf/kFJZn5ecX/dXUzcwtyMpMzS4DM4oLU5My0SluQSQA "Add++ – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` x=>f=(t=1,s,e=x.map(y=>y<t?0:s|=t))=>s?[e,...f(++t)]:[] ``` [Try it online!](https://tio.run/##ZcqxCsIwEIDh3Se5o2cwVh2ql259iZAh1FSU2hRzSAu@eww4OvzT9z/826f@dZ9lO8VryB3nhc3AIKwpUeBFPf0MK5v1Iu2uSR8WRDaptYGUUgNUlaBrrMvnTR@nFMegxniDDmxNR9qTppNDQPxjXbCmQ6lMvyV/AQ "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 63 bytes ``` x=>[...Array(Math.max(...x,t=0))].map(_=>x.map(y=>y<t?0:t,++t)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1i5aT0/PsagosVLDN7EkQy83sUIDKFKhU2JroKkZC@QXaMTb2lWAGZW2dpU2JfYGViU62tolmpr/rbmS8/OK83NS9XLy0zXSNKKNdUx1jHQMdcxiNTUxJA2BUsY6JkAMVAJS8B8A "JavaScript (Node.js) – Try It Online") [Answer] # Java 10, 115 bytes ``` a->{int l=a.length,m=0;for(int j:a)m=j>m?j:m;var r=new int[m][l];for(;l-->0;)for(m=0;m<a[l];r[m][l]=++m);return r;} ``` **Explanation:** [Try it online.](https://tio.run/##dVHBTsMwDL3zFT42WhttDDg0dIgPYJcdqx5Ml42UJJ1Sd2ia@u0lScsBMaRYcmy/@L2XBs@YNfvPsdbYdfCGyl7vAJQl6Q5YS9iGayyUVVlBncQMkAlfH3z40xGSqmELFgoYMdtc/RDoArmW9kgfqSmW4tC6gIUmR2aKZmNemtyIMzpwhZVfcYOpSl3FSaGzbLMULOQBbZ4xtNw0UiwWhgknqXcWnBhGMRE59e/aE5n5nFu1B@MVJTtyyh7LCtmkhmRHyc/S6rpOH9P7dJU@DVHVn/7qv7pHrdMHHx493HAkMoigyTVlTz2x344675nlwdfQm/bMXgWfIQfHYhFgd@lIGt72xE9eEGmbNP7/eE9K81fn8NJxaiexCbL5sRuomeowfgM) ``` a->{ // Method with integer-array parameter and integer-matrix return-type int l=a.length, // Length of the array m=0; // Largest integer in the array, 0 for now for(int j:a) // Loop over the array m=j>m? // If the current item is larger than `m`: j // Set `m` to this item as new max : // Else: m; // Leave `m` the same var r=new int[m][l];// Result-matrix of size `m` by `l`, filled with zeroes by default for(;l-->0;) // Loop over the columns for(m=0;m<a[l]; // Inner loop over the rows r[m][l]=++m); // Set the cell at position `m,l` to `m+1` return r;} // Return the result-matrix ``` [Answer] # [Uiua](https://uiua.org), 8 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` +1⍉⬚¯1∵⇡ ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAgKzHijYnirJrCrzHiiLXih6EKCmYgWzMgNSAyIDEgNl0KZiBbMV0KZiBbMSAyIDMgNCAzIDIgMV0K) ``` +1⍉⬚¯1∵⇡ ∵⇡ # range of each ⬚¯1 # filling with -1 ⍉ # transpose +1 # increment ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Would be 4 if Japt's transpose padded with `0` instead of `null`. ``` mõ zÔÕ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bfUgetTV&input=WzMgNSAyIDEgNl0KLVI) [Answer] # TI-Basic, 48 bytes ``` Ans→A List►matr(1 or Ans,[A] [A] For(I,2,max(ʟA List►matr(I(I≤ʟA),[B] augment(Ans,[B] End Ansᵀ ``` Takes input in `Ans`. Similar method to [this answer](https://codegolf.stackexchange.com/a/142065/91262). [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 20 bytes ``` {+(1+!'x),'&'-x-|/x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6rW1jDUVlSv0NRRV1PXrdCt0a+o5eJKczBWMFUwUjBUMAOyDYEsYwUTIAaKAAAxkQrR) [Answer] # [Scala](http://www.scala-lang.org/), 76 bytes Golfed version. [Try it online!](https://tio.run/##PY5Ba8JAEIXv@RXvOAMh1BY9hG6gx0I9FU@Sw6i7YWXdhM00VMTfHlcR5zDMe3wM37iXIHO/O9q9Yi0@4lIUwCQBrgb9@FG331Fb0zzOV24ZZg6mCZULomsZaDINLaA9QnWSf85rIG8a78h/mok9bBgt3pirLvV/gz3QE9T@/nUGDtbhlBVIUjfW@EpJzttfTT52LdfYRK8w2Q95htxqiOQeivRRYlnivcSixIqZM3MtrvMN) ``` l=>l.flatMap(v=>(1 to l.max).map(i=>if(i<=v)i else 0)).grouped(l.max).toList ``` Ungolfed version. [Try it online!](https://tio.run/##TY9BSwMxEIXv/RXvmMASrNIeiit4FOxJPJUexjZZIkl2SaaiLfvbt0lcqqeZee/jDS8dyNE09R@f@sDYkg24LICjNjDCbfBqE@9eAu/lvN@EPdqKAl/k4PMlluAeTnn6lor7QlbfKeOItzTgUtiTRvtUDcBnuMj2TwKsgbB4bH9hmU3tksbdDIx1jqqL/WnQR@FVsmf97@O4mBv4XEdQ7NIGzzHSz@6Now1d6fIeLN8KDFllF4QRJUE8NFg1uG@wbLCWUtbIcZqu) ``` object Main { def f(l: List[Int]): List[List[Int]] = { val m = (1 to l.max).toList l.flatMap { value => m.map { i => if (i <= value) i else 0 } }.grouped(m.size).toList } def main(args: Array[String]): Unit = { println(f(List(3, 5, 2, 1, 6))) } } ``` [Answer] # [J](https://www.jsoftware.com), 10 bytes ``` 0|:>:@i."0 ``` No surprises [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxyqDGys7KIVNPyQAicFNPkys1OSNfIU3BWMFUwUjBUMEMLKCuDhM3BIoaK5gAMVAWomvBAggNAA) ``` 0|:>:@i."0 i."0 NB. create 0..n-1 range for each atom >:@ NB. then increment 0|: NB. transpose ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 8 bytes ``` ṀR$ᵒ{≤0I ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fuse7mwIUnm4dVL1o84lBp5LipOSi6FSC_ZHG-uY6hjpGOqYxXJFG4IwkGesYwLEQNFYiDIA) Longer than other answers, because Nekomata doesn't have a padding builtin yet. I'll add one in some future version. ``` ṀR$ᵒ{≤0I Ṁ Maximum R Range from 1 to that $ Swap ᵒ{ Make a 2D array by the following function ≤ If left <= right, return left 0I Otherwise, return 0 ``` --- # [Nekomata](https://github.com/AlephAlpha/Nekomata), 8 bytes ``` R:∑0*ᵚ+Ť ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FmuDrB51TDTQerh1lvbRJUuKk5KLoTIL9kcb65jqGOkY6pjFckUbgjCQZ6xjAsRA0ViIMgA) ``` R:∑0*ᵚ+Ť R Range from 1 to input : Duplicate ∑ Sum 0* Multiply by 0 ᵚ+ Add this to each element of the other array Ť Transpose ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 5 bytes ``` ⍉∘↑⍳¨ ``` Anonymous tacit function. Did you know that APL's Mix function automatically pads with zeros? [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/TeFR2wSFR72djzpmPGqb@Kh386EV//@XpBaXFINlNIwVTBWMFAwVzDQ1DIEIyDZWMAFioJgmF1idTrSBnmls2qEVYB4A "APL (Dyalog Classic) – Try It Online") ]
[Question] [ [Fibonacci coding](https://en.wikipedia.org/wiki/Fibonacci_coding) is a universal code, which can encode positive integers of any size in an unambiguous stream of bits. To encode an integer \$ n \$: * Find the largest Fibonacci number less than or equal to \$ n \$; subtract this number from \$ n \$, keeping track of the remainder * If the number subtracted was the \$ i \$th Fibonacci number \$ F(i) \$, put a \$ 1 \$ at index \$ i−2 \$ in the code word (counting the left most digit as index \$ 0 \$) * Repeat the previous steps, substituting the remainder for \$ n \$, until a remainder of \$ 0 \$ is reached * Append a final \$ 1 \$ Alternately explained: * Find the [Zeckendorf representation](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem) of \$ n \$ (the list of unique non-consecutive Fibonacci numbers which sum to it) * For all the Fibonacci numbers up to and including \$ n \$, excluding \$ 0 \$ and the first \$ 1 \$, append a bit \$ 0 \$ or \$ 1 \$ according to whether or not they appear in \$ n \$'s Zeckendorf representation * Strip any trailing \$ 0 \$s and append a final \$ 1 \$ Your task is to, given a positive integer, output the bits of its Fibonacci coding. ## Test Cases ``` Input Output ------------------------------------------- 1 11 2 011 3 0011 4 1011 11 001011 12 101011 13 0000011 14 1000011 65 0100100011 610 000000000000011 8967 00001010101010010011 8039213 0010010010100010001001001000001011 ``` (if your code cannot compute this high in reasonable time, that is fine) ## Rules * Output should be as a string or array of \$ 1 \$s-and-\$ 0 \$s or booleans (but not just any truthy or falsey value) * You may output the bits in reverse if that is more convenient (although this behaviour must be consistent) * You may use [any sensible I/O format](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] # [Japt](https://github.com/ETHproductions/japt), 13 bytes ``` @!X¤øB}iU ¤ÔÄ ``` Explanation: ``` @!X¤øB}iU @ }iU // Get the U-th (input) number ! // which doesn't have øB // "11" in its X¤ // binary representation ¤ÔÄ ¤ // Take that number's binary representation, Ô // reverse it Ä // and add one to the end. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=QCFYpPhCfWlVCqTUxA==&input=NjU=) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~51~~ 50 bytes ``` k;f(n){for(k=0;n-=!(++k&k/2););n=log2(k);k+=2<<n;} ``` [Try it online!](https://tio.run/##XVHdboIwFL73Kc5IXIqUKJXfVHaz7CmmFwaLI2g1lGRkhlcf@1AkOpIW@v2dnkPm7rOs60qZM21f8lPFynQhtZu@MMcpX8u5sKUtdXo47QUrbVk6qVittGy747bQzJ5cJoSn0DXVytTmc9MfU7p4nASnJSefU8Ap5BRxijklnLwFFngPAg8KD5Kw1/REnIRRK8dQ1ZxVVqsdchG6vAbdfQI@AZ8A5iPaR3aAiAB8AD4BnqBqFIe9OIjwioUfBuFQIPvaVjPsKitVdatgrZsPsW6Sd6zA4vR4XlqDD2Mi1t@u0DvVwLaQw@eKTPGjTjm739ueD8BsRCQ5zlVt02149141km5DvNIb@cQasP1PekYV0HFG/23nCpKcWdMduW@EfWrWGk1pToaPfZs0VZshtp203W@WH7Z707mHY@d@/wE "C (gcc) – Try It Online") Uses the formula from [Etheryte](https://codegolf.stackexchange.com/users/16484/etheryte)'s [Japt answer](https://codegolf.stackexchange.com/a/222687/9481). Returns the Fibonacci code word for input \$n\$ in reversed binary. ### Explanation ``` k;f(n){ // function taking an integer n > 0 for(k=0; ;); // loop over values of integer k // starting at 1 (because of the bump) n // until n is zero -=!( ) // subtracting 1 from n when... ++ // (bump k at the start of each loop) k&k/2 // ...there's no 2 consecutive 1 bits in k // k is now the nth integer without // any 2 consecutive 1 bits n=log2(k); // get the number of bits in k by // converting its log2 to an int k+=2<<n; // add a 1 bit just above k's most // significant bit and return k } ``` [Answer] # [Haskell](https://www.haskell.org/), 76 bytes ``` 1#2 (u#v)x|x<v=["11"|x==u]|z<-u+v=map('0':)(v#z$x)++map("10"++)(z#(z+v)$x-u) ``` [Try it online!](https://tio.run/##FcrRCoIwFADQ9z7DCW7sGrubmYb7hL7AJIZkSSqSbQzx21v4ejgvs7wfwxA6fQtI5IFa4pjffOV0HSFGm9faNttapZY7PZqZJiK5MOrIGnvG@S4RiohzRldCV@5Y7FPLwmj6af/XO50//fQ9dqxGkKAgA0RACagAM8hPkKOAoszPUAhVSlRN@LXdYJ5LSNt5/gM "Haskell – Try It Online") Outputs a string of `0`'s and `1`'s wrapped in a singleton list (e.g. `["001011"]`). ## How? * `(u#v)x`: we want this function to return a list of all the possible Fibonacci encodings for `x` using only Fibonacci numbers greater or equal than `u`; we further assume that `u` and `v` are consecutive fibonacci numbers (with `u<v`). It is well known that, if such an encoding exists, than it is unique (this follows from the uniqueness of the Zeckendorff representation), so the length of the list `(u#v)x` will be at most 1. For instance, `(3#5)11==["1011"]`, since `11=3+8`. * `|x<v=["11"|x==u]`: if `x<v` then the encoding only exists if `x==u`. If this is the case we return `["11"]`, otherwise we return the empty list. * `|z<-u+v=`: otherwise, let `z=u+v` be the next Fibonacci number. We have two choices. + `map('0':)(v#z$x)`: we try to encode `x` without using `u`. In this case, the encoding will be contained in `(v#z)x`, and we prepend a `'0'` to denote the fact that we didn't take `u`. + `++map("10"++)(z#(z+v)$x-u)`: we try to encode `x` using `u`. In this case, `"10"` denotes that we take `u` and we don't take `v`. For this choice to be valid, we must also find an encoding of `x-u` using only Fibonacci numbers from `z` onwards (notice that `z+v` is the Fibonacci number after `z`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ 12 bytes Using [Etheryte](https://codegolf.stackexchange.com/users/16484/etheryte)'s observation from their [Japt](https://codegolf.stackexchange.com/a/222687/53748) answer is much terser and more efficient to boot (it may be possible in even less, let's see...) ``` 1BSƝỊẠƲ#ṪB1; ``` A monadic Link accepting a positive integer that yields a list of `1`s and `0`s (in reversed order as allowed in the rules). **[Try it online!](https://tio.run/##ASEA3v9qZWxsef//MUJTxp3hu4rhuqDGsiPhuapCMTv///82MTA "Jelly – Try It Online")** --- A faster 12 byter: ``` 1Ḥ^:3ƲƑ#ṪB1; ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//MeG4pF46M8ayxpEj4bmqQjE7////NjEw) ### How? ``` 1Ḥ^:3ƲƑ#ṪB1; - Link: positive integer, n 1 # - set k=1 and increment to collect the first n ks for which: Ƒ - (k) is invariant under?: Ʋ - last four links as a monad, f(k): Ḥ - double (k) ^ - (2k) bitwise-XOR with k -> x 3 - three : - (x) integer divide (3) Ṫ - tail B - to binary 1 - one ; - (1) concatenate with (the binary list) ``` --- Original 21: This is (a) extremely inefficient and (b) almost certainly not the right way to get the tersest code, so I~~'ll~~ was planning to come back to it after work... ``` ‘ÆḞ€ḊðŒPS⁼¥Ƈ⁹Ḣ⁸iⱮðṬ;1 ``` A monadic Link accepting a positive integer that yields a list of `1`s and `0`s. [Try it online!](https://tio.run/##ATsAxP9qZWxsef//4oCYw4bhuJ7igqzhuIrDsMWSUFPigbzCpcaH4oG54bii4oG4aeKxrsOw4bmsOzH///8xNA "Jelly – Try It Online") [Answer] # JavaScript (ES6), ~~46~~ 44 bytes *Based on [@Etheryte's insight](https://codegolf.stackexchange.com/a/222687/58563).* Returns a string of bits in reverse order. ``` f=(n,k)=>k&k/2||n--?f(n,-~k):1+k.toString(2) ``` [Try it online!](https://tio.run/##bc/BDoIwDAbgu0@xk9miY@tADyboQ/gEBBnBks3Awonw6lMPDM3WY7/@bfqspmqsh@7luLGPxntdUnNEVl5xj0LNs@H8pj8tviC7wAEzZ@9u6ExLFfO1NaPtm6y3LdUUCGGMCEEAdv@iVpER5YFiK8LC2AC2XELVlkxoHrIycRaKEE7x@RSe@d5OTYD82b8WgH8D "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input k // k = counter, initially undefined (coerced ) => // to 0 for bitwise operations) k & k / 2 || // yield a truthy value right away if there are // at least 2 consecutive bits set in k n-- // otherwise, yield n and decrement it afterwards ? // if either statement above is truthy: f(n, -~k) // do a recursive call with k + 1 : // else: 1 + // stop and return a leading '1' k.toString(2) // followed by the binary representation of k ``` --- # [JavaScript (Node.js)](https://nodejs.org), ~~109~~ 105 bytes *Based on the challenge description.* Expects a BigInt. Returns a string of bits in reverse order. ``` f=(n,k=m=0n)=>n?(g=(i,x=0n,y=1n)=>i?g(~-i,z=y,x+y):y)(k)>n?f(n-z,0n,m|=1n<<k-2n):f(n,-~k):1+m.toString(2) ``` [Try it online!](https://tio.run/##bZBBbsIwEEX3PUWWM8IGj0NpiXA5RE@AKIlMyBhBhAiquHpqUgpybXs2M//5@9vb1Wl1XB/svpXsvjZ9XxpgUZvGKEbzwUuoDFhx9q3oDN1mdlnBVVpxMZ04jzosOoQaPVoCy4vwYPPtycWilpqx8FMhrzUWNGrGrftsD5Yr0NivHR/dbjPeuQpKIM6GhZhNJhnRSyjrQFaRnod6DExD/xige4KHQwLRHHokkDx0UYkoNA1tUszsNfChW54URor/Xfe3IvZ9PnvjgKXHHio6oPK59g96/shvDUnUs79bUf8D "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 51 bytes Another based on [Etheryte](https://codegolf.stackexchange.com/users/16484/etheryte)'s [Japt answer](https://codegolf.stackexchange.com/a/222687/53748) ``` f=lambda n,k=0:-n*f'1{k-1:b}'or f(n-(k&k//2<1),k+1) ``` **[Try it online!](https://tio.run/##PY9hboMwDIX/c4onTVpJF1bcboyicRjoQhMREpSYVdW0s7OwSbP0ZH227GfPd9beneo5rOvQ2m7qPzo4ObZlU7j9sKOvsaCm/975gCF3RT4@jofD8Z2EHJ9IrGaafWDEe8ySnqPioC5LiMY7aybDeU3nSgAPYG0iOmv9LYJV5LaiEuxx8dNsFSuJfuG/Tl2d33Az1iKq69AtlqFVUFCfyqU6a2hz1VDOLyn9G@LXMcuGdOu2B8YhJ4mjxEniRYISUCJKSImr1yQqRZMhxRyM43wblOnVLQux/gA "Python 3.8 (pre-release) – Try It Online")** [Answer] # Scala, 69 bytes Based on [Etheryte's amazing answer](https://codegolf.stackexchange.com/a/222687/95792) ``` "1"+Stream.from(0).map(_.toBinaryString).filter(!_.contains("11"))(_) ``` [Try it online!](https://scastie.scala-lang.org/96OmivWtTEqg7FrcpfKpRw) Outputs a String (reversed) ## Original answer, 123 bytes ``` n=>(f.takeWhile(n>=_):\(n,1::Nil)){case(x,n->c)=>if(x>n)(n,0::c)else(n-x,1::c)}._2 def f:Stream[Int]=1#::f.scanLeft(2)(_+_) ``` [Try it online!](https://scastie.scala-lang.org/gewTQsoiTVGaI1vrTKLfMg) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ∞ʒb11å>}s<èb1ì ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5OSDA0PL7WrLbY5vCLJ8PCa///NDA0A "05AB1E – Try It Online") ``` ∞ʒb11å>}s<èb1ì # full program <è # push the... s # implicit input... <è # -th... ∞ # natural number... ʒ } # which... > # does not... å # contain... 11 # literal... b # in binary... b # converted to binary... 1 # with literal... ì # prepended # implicit output ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âî}g♥▼«zΩ╥;QbB]╔ ``` [Run and debug it](https://staxlang.xyz/#p=838c7d67031fae7aead23b5162425dc9&i=1%0A2%0A3%0A4%0A11%0A12%0A13%0A14%0A65%0A610%0A8967%0A8039213%0A&m=2) Based on Etheryte's observation, which shaved a off a ton of bytes. [Check out their answer!](https://codegolf.stackexchange.com/a/222687/80214) ## Explanation ``` Z{|B.11#!}{ge|B'1s+ Z push 0 under the input(counter) ge generator: find the first n elements, return the last { empty block: get the next element by incrementing { } filter: |B base2 string .11#! has 0 occurrences of "11"? '1s+ prepend a 1 to it(r'1+ also works for valid output) ``` # [Stax](https://github.com/tomtheisen/stax), 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` 齯½┼≥╦◘½}○└╩►à«ôæ→¢ûU«½*≈ø»▀ ``` [Run and debug it](https://staxlang.xyz/#p=82ab92abc5f2cb08ab7d09c0ca1085ae93911a9b9655aeab2af700afdf&i=1%0A2%0A3%0A4%0A11%0A12%0A13%0A14%0A65%0A610%0A8967%0A8039213%0A&m=2) Pretty big. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 43 bytes ``` n=>(g=p=>n<p||2*g(p+q,q=p)+(n>(n%=p)))(q=1) ``` [Try it online!](https://tio.run/##jU49b8IwEN39K7xUOTdg4oTSIupsHTp1YAQkotSkQcE2iWEp/e3pJYBB6tKzZb2Pu3feZsesyevSuqE2n6rdyFbLFAppZapf7ekUPxZgw/1gLy0LQaegHxAxBnspWOuopGvyru3BUayPg0NEhv8vIuilhCDxFUdIEk86NvZtHRPi5vU8vrk9T7wf9eNi7BvOwuTJr@oyzpqI7qauhcbLdPLsDeFPf9GNkmncbYyu2jkwuvHLnCBr7upyB4w3tiodBEsdIK7KXEHM@C6zUFGZ0gqhy79gtJyHo4KxGXF8Y@q3DDVYlAOqVqzr@yaU5kY3plK8MgWEaG3wZdyZOW7SBcYO6IJz/kde8VodVd0o/M3WlBqCADMlVbjth83aXw "JavaScript (Node.js) – Try It Online") It returns an integer whose binary form is reversed Fibonacci Encoding. ``` // I have a code for base 2 convention n=>(g=p=>n<p 2*g( )+(n>(n%=p)))( ) // I have a code for Fibonacci sequence n=>(g=p=> g(p+q,q=p) )(q=1) // Boom, Fibonacci base convention n=>(g=p=>n<p||2*g(p+q,q=p)+(n>(n%=p)))(q=1) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Based off Etheryte's solution, posted with permission. ``` _øB ªU´}f¤ÔÄ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X/hCIKpVtH1mpNTE&input=NjU) [Answer] # [jq](https://stedolan.github.io/jq/) (74 bytes) Since shortness is the goal ... ``` def f:def i:.,(i|[0]+.,[1]+.);nth(.-1;[1]|i|select(index([1,1])|not))+[1]; ``` Example: ``` 65|f #=> [0,1,0,0,1,0,0,0,1,1] ``` [Try it online](https://jqplay.org/s/q8bwV3z8nOW) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 127 bytes ``` (f@n_:=(k=1;While[(F=Fibonacci)[++k]<=n];k-1);s=Table[0,f[t=#]];(s[[#]]=1)&/@(f/@NestWhileList[#-F@f@#&,t,#>0&]);RotateLeft@s)& ``` [Try it online!](https://tio.run/##Hcy9CsIwFEDhVxEKJcEr7W21/sRIpk4iIoJDCBJLoqFawdxNfPYoTmf5OA9LN/ewFDqbrjIxr4bzSrJeojjdwt1p1so2XJ6D7brA9Xjcm7UcjOgnyEWUR3v5mRK8JpkZI1jU@leJPC8U84XauUj/0TZE0tmkVV5lORBkmzI3XByeZMltnScVeZ72rzDQqFDXQr0RKqhhCoiAFWANOIVmBg2WsFg2c1iU9bLC@pPSFw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Haskell (GHC)](https://www.haskell.org), ~~118~~ 104 bytes ``` x@(_:v)=1:scanl(+)1x f n=snd(foldr(\v(x,l)->if v<=x then(x-v,1:l)else(x,0:l))(n,[])$fst$span(<=n)v)++[1] ``` [Try it online!](https://tio.run/##RVFba4MwFH73VxxCoQmNYNqtW6WRwZ4Kuzz0aVgpwcZVlsbSZM5/76JRm@Thu5zvBM45C/MjlWrb5gUf45pwFptcaIUXhDVBAZobfcJFpU43fKhxQxUJk7KAessbsGepcRPWlMWKSGWk8yMHCdY0zcisMHZmrkLjLdekJotFyrLWSmNfhZEG4hhSvNOWwt7eSv1NsuBucucxihhDhOIlRZFHK4cG@ODcATLWyyNb9s7I@kg0plgfm@j6sWvdZSeFRUNgPF5/3qyfvMGm2z/vRqvN0n81yL5ldOdD1JVnQXARpe4GsPsETDzjcBHX9yPgAy4pVATCBJS0UM2dVUAJScLBnKs/cMXXX@uG9qZhBnmlc2EhdVvpSjlU/WIAfQGCbiuAPgC5jnPqBOd3OCMwzbr9Bw) ## Original: Outputs a list of reversed bits. ``` import Data.List x@(_:v)=1:scanl(+)1x f n=1:snd(mapAccumL(\a b->if b<=a then(a-b,1)else(a,0))n$reverse$fst$span(<=n)v) ``` [Try it online!](https://tio.run/##RVFbT8IwGH3frzhZltDGYlZQlIUtGn0hQX3wyQAhZXayuHXLWpB/P7sLo@vDufR8S853EPpXZlldp3lZVAavwojbVaqNc34iu@BEQx7oWKiM3FB@dhKoRlDfJBflcxwf8xXZCOzHUZpgvwgFzEEqIsZ7xqnMtCSC@ZQqr5InWWnpJdp4uhSKLEJFT7Q2UpsXoaVGEGBNlsowfJoqVT9061zN0HqcuZy7lJEJc/0OTS3q4Z11e8h5K1/YpHUurI34lxRvYwOd3Tejm@ygcL8PXE6nP85nD53Bh6@9netP55PuV73cjfSvvI/a51vHyUWqmgKWHyC0YyFsw287kA1JGQqKcYRMGhQja/VtgiRIKaIohD4Uf7Cx8mhsfSsFD3GhYmGwtptpQiGKdjlwv@Ci2Q3cd7h29ohZwfoN3lIMrdf/) [Answer] # [Red](http://www.red-lang.org), ~~135~~ 124 bytes ``` func[n][i: k: 0 until[i: i + 1 unless find do b:[enbase/base to#{01}i 2]"11"[k: k + 1]n = k]reverse rejoin["1"find do b"1"]] ``` [Try it online!](https://tio.run/##LYyxDoJAEET7@4oJlhayqKgk/oTtZgvw9uKJWcyBNsZvxyNxism84k1SP1/Us7jQzOFlVzbh2KBvUOJlU3wsFLEGZXzoOCJE8/CD6xpW69pRN0thGlafkr4RlRREBeeHftHEcEYvSd@aRnVJ70M0Lqj4/6DLW2QOQ9L2eoOBCRW22IEIVIG2oB3qPWoqcTzVB2GHnGeKNvGz9VnZI8DEyfwD "Red – Try It Online") Uses [@Etheryte's method](https://codegolf.stackexchange.com/a/222687/75681) ### As an excercise - the step by step method: ## [Red](http://www.red-lang.org), 153 bytes ``` func[n][c: charset 1 until[k: 0 a: 0 b: 1 until[k: k + 1 t: a a: b b: t + b b > n]c/(k - 2): 1 0 = n: n - a]replace enbase/base to#{01}c 2[any"0"end]"1"] ``` [Try it online!](https://tio.run/##TY7BasMwEETv@orBvbSUEq2cOo4g@YhehQ6yvCbBYWMU5RBCvt2Rbt3DMLzhwSYe1z8enVeTXae7RCfeRYt4CunGGYS75PPFzRYaocZg/8MZ3yCVLUJdh7rmgkrBEeLj5nPGD8xXlTQOEAspIPjEyyVEVixDuPGmBvL146npFWFckEejG5bRN9T4dbomDvFUXEcwaLEFEciAWtAW3S860uj33Q69bveGWu8Uyi3pLNktYSxqj6m8pPz6Bg "Red – Try It Online") More readable: ``` f: func[n][ c: charset 1 until [ k: 0 set [a b] [0 1] until [ k: k + 1 set [a b] reduce [b a + b] b > n ] c/(k - 2): 1 0 = n: n - a ] replace enbase/base to binary! c 2 [any "0" end] "1" ] ``` `charset` is short for `make bitset!` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 12 bytes *Edit: -2 bytes thanks to Leo* ``` ↔:1!fo¬V&mḋN ``` [Try it online!](https://tio.run/##yygtzv7//1HbFCtDxbT8Q2vC1HIf7uj2@///v5kpAA "Husk – Try It Online") Based on [Etheryte's approach](https://codegolf.stackexchange.com/a/222687/95126): upvote that! [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 63 bytes ``` .+ $* (\G1|(?>\2?)(\1))*1 $#1$*01¶ +`^(.*).(.*¶)(\1.)¶ $3$2 ¶ 1 ``` [Try it online!](https://tio.run/##FYkxDsIwEAT7/QaOdHYky3sXTNKQMp@wUCgoaCgQZd6VB@RjxmlmpJnv6/f@PGsny1pjDxcgZeEm873o7KXQ@0C4C11IPHb060Ni8LHh2M8ffavOnKKZtRIKwwASVNDAAfmKzIRxyjeMySal/QE "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` (\G1|(?>\2?)(\1))*1 ``` Use a tweaked version of @MartinEnder's answer to [Am I a Fibonacci Number?](https://codegolf.stackexchange.com/questions/126373) to match Fibonacci numbers that sum to the input. ``` $#1$*01¶ ``` For each match, generate the bit in the appropriate column. ``` +`^(.*).(.*¶)(\1.)¶ $3$2 ``` Fold all of the bits together. ``` ¶ 1 ``` Replace the final delimiter with a final 1 bit. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` NθF²⊞υ⊕ιW‹⌈υθ⊞υΣ…⮌υ²←1FΦ⮌υκ«←I¬›ιθ≧﹪ιθ ``` [Try it online!](https://tio.run/##VY7LCsIwEEXX9iuCqwnUhS58rqSgFKyIfkGsUxNMkzYPH4jfHtuCqNvhnHMn58zkmskQUlV5t/XlEQ3UdBEV2hAYUbLzloOPSapygyUqhycQtAFuXEgksEFrIWN3UfoSPI1JTb/Sobklj1xiwnUFe7yisdhRI9o2dkYoB/MNFi4m/WH/s7sS0jV//AqXJvuMen9GwqyDrXawNshaQXTzbbmXsWpprTirvThzB5k@ealj0hGL6BXCdDaehMFVvgE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Outputs digits in reverse order, but this is the least of Charcoal's problems because it can simply print them backwards. ``` Nθ ``` Input `n`. ``` F²⊞υ⊕ι ``` Start with `1` and `2` from the Fibonacci sequence. ``` W‹⌈υθ⊞υΣ…⮌υ² ``` Keep pushing terms until one exceeds `n`. ``` ←1 ``` Print the final `1`. ``` FΦ⮌υκ« ``` Loop through all the terms except the last in reverse order. ``` ←I¬›ιθ ``` Print `0` or `1` depending on whether this term is larger than `n`. ``` ≧﹪ιθ ``` Subtract the term from `n` if it is smaller. [Answer] # [Mini-Flak (BrainHack)](https://github.com/Flakheads/BrainHack), 104 bytes ``` ([{}]((()))){({}(())({{}[()](({}({}))){(()[{}]){(({}{}[()]))}}{}}{}(())){[({})]({}[()](()[()]))}{}{})}{} ``` [Try it online!](https://tio.run/##NYs5DoBADAO/Yxe0HG9ZbbHQgBAUtFbeHhKOFNEkHs9X2861Lbs7iqwCYIwgS4JkBYx33LInAVNMkL0paUH2VqiSZsXf5Kekndvdu8PHqR9u "Brain-Flak (BrainHack) – Try It Online") Starts at `11` and iteratively computes the encoding of the next number `n-1` times. ``` # Create 11 while computing 1-n. ([{}]((()))) # Repeat { # Add 1 to counter (going up to zero) and allow loop to start ({}(()) # Eventually push number of iterations to reach 00 or 11 ( { # Remove 1 from stack {}[()] # Compute sum of two digits, keeping second, and push twice (({}({}))) # If not 00: { # Subtract value from 1; this makes iteration evaluate to 1 (()[{}]) # If top of stack still isn't zero (i.e., digits were 11): { # Push two zeros: one to exit loop and the other to exit conditional (({}{}[()])) }}{} # Repeat until 00 or 11 found }{} # Push 1 at position (()) # Push number of leading zeroes to use, plus one ) # That many times: { # Compute -k: this will make each iteration evaluate to -1 [({})] # Subtract 1 from k... ({}[()] # while pushing 0 below it (()[()]) ) }{} # Since the push evaluates to a number of iterations, and # those iterations all evaluate to -1, this main part of the main # loop evaluates to zero. # Remove extraneous zero: this is shorter than subtracting 1 earlier {} # Repeat until counter reaches zero, and pop zero )}{} ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` λbṅ11c¬;ȯtbṘ1J ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BBb%E1%B9%8511c%C2%AC%3B%C8%AFtb%E1%B9%981J&inputs=65&header=&footer=) Port of Ethertyte's answer. ``` λ ;ȯt # Nth integer where... bṅ # Binary 11c¬ # Doesn't contain 11 bṘ # Get the binary of that, reversed 1J # Append a 1 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes Based on [tsh's JavaScript answer](https://codegolf.stackexchange.com/a/222719/9288). -4 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att). ``` n1~If[#>n,k=n;1,2#0[+##,#]+If[k<#,0,k-=#;1]]&~1 ``` [Try it online!](https://tio.run/##DctBCsIwFATQq3z44Ka/mEm0WmqKW3fuQxZBLJbSLKQ7sYfwBp7QI8S/mIE3MHNaHvc5LeMtlcGX/Pt8sV6GwH2WyecOYtmEilk4VrpPJxYjU@25Q4ybFeX6HPMSmOqe9KYbbc/0gpAVckI7ISigghLqZq@BETq2zUHbuNbCvcsf "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ You're given a non-empty list of positive integers, e.g. ``` [6 2 9 7 2 6 5 3 3 4] ``` You should rank these numbers by their value, but as is usual in leaderboards, if there is a tie then all the tied numbers get the same rank, and an appropriate number of ranks is skipped. The expected output for the above list would therefore be ``` [3 9 1 2 9 3 5 7 7 6] ``` For example, the highest value in the input was `9`, so this becomes a `1` (first rank). The third highest value is `6`, so both `6`s become `3`, and the rank `4` is skipped entirely. ## Rules You can use any convenient, unambiguous, flat list format for input and output. The first/smallest rank in the output should always be **1**. You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases ``` [8] -> [1] [1 15] -> [2 1] [18 14 11] -> [1 2 3] [11 16 14 8] -> [3 1 2 4] [15 15 15 15 15] -> [1 1 1 1 1] [10 2 5 4 15 5] -> [2 6 3 5 1 3] [5 5 10 10 5 11 18] -> [5 5 3 3 5 2 1] [2 4 9 4 17 9 17 16] -> [8 6 4 6 1 4 1 3] [11 17 19 17 10 10 15 3 18] -> [6 3 1 3 7 7 5 9 2] [2 11 4 8 3 3 12 20 4 18] -> [10 4 6 5 8 8 3 1 6 2] [12 6 10 2 19 19 6 19 8 6 18] -> [5 8 6 11 1 1 8 1 7 8 4] [5 6 14 19 13 5 19 9 19 9 9 19] -> [11 10 5 1 6 11 1 7 1 7 7 1] [9 2 12 3 7 11 15 11 6 8 11 17 11] -> [8 13 3 12 10 4 2 4 11 9 4 1 4] [3 5 15 7 18 5 3 9 11 2 18 1 10 19] -> [11 9 4 8 2 9 11 7 5 13 2 14 6 1] [6 11 4 19 14 7 13 16 10 12 7 9 7 10 10] -> [14 6 15 1 3 11 4 2 7 5 11 10 11 7 7] [11 20 11 1 20 16 11 11 4 8 9 7 11 14 10 14] -> [6 1 6 16 1 3 6 6 15 13 12 14 6 4 11 4] [4 7 15 2 3 2 3 1 14 2 10 4 7 6 11 2 18] -> [9 6 2 13 11 13 11 17 3 13 5 9 6 8 4 13 1] [5 1 17 7 1 9 3 6 9 7 6 3 2 18 14 4 18 16] -> [12 17 3 8 17 6 14 10 6 8 10 14 16 1 5 13 1 4] [5 6 8 10 18 13 20 10 7 1 8 19 20 10 10 18 7 2 1] -> [16 15 11 7 4 6 1 7 13 18 11 3 1 7 7 4 13 17 18] [12 17 8 2 9 7 15 6 19 5 13 16 14 20 10 11 18 4 3 1] -> [9 4 13 19 12 14 6 15 2 16 8 5 7 1 11 10 3 17 18 20] ``` [Answer] # [Workaround in Excel for silly Rules Regarding Mouse Inputs on Code Golf Stack Exchange: (WESRRMICGSE)](https://drive.google.com/file/d/0B7siA0B5wdc1TDZQaEFIMU1fMUU/view?usp=sharing) 28 bytes `rank(RC[1],r1c1:r1024:c1024)` Input list as csv (`10,23,34,2,`) into the compiler after entering the source. no quotes, no brackets, trailing comma. WESRRMICGSE is exactly like programming in excel, except you can omit the initial '=' sign to save a byte. The difference in functionality comes from the fact that WESRRMICGSE will either drag the formula down to copy the code automatically and provide different outputs provided with a single integer input. provided a list as input, that list goes into the B column (input column), and the formula is drug down automatically to match the number of inputs. (eg: the input 34,21,45, would 'drag' the formula down 2 cells, for a total of 3 cells with the formula). Edit: I never expected this answer to be popular. Wow! [Answer] # [MATL](http://github.com/lmendo/MATL), 4 bytes ``` &<sQ ``` [Try it online!](http://matl.tryitonline.net/#code=JjxzUQ&input=WzEyIDE3IDggMiA5IDcgMTUgNiAxOSA1IDEzIDE2IDE0IDIwIDEwIDExIDE4IDQgMyAxXQ) Or [verify all test cases](http://matl.tryitonline.net/#code=YAomPHNRCkRU&input=WzhdClsxIDE1XQpbMTggMTQgMTFdClsxMSAxNiAxNCA4XQpbMTUgMTUgMTUgMTUgMTVdClsxMCAyIDUgNCAxNSA1XQpbNSA1IDEwIDEwIDUgMTEgMThdClsyIDQgOSA0IDE3IDkgMTcgMTZdClsxMSAxNyAxOSAxNyAxMCAxMCAxNSAzIDE4XQpbMiAxMSA0IDggMyAzIDEyIDIwIDQgMThdClsxMiA2IDEwIDIgMTkgMTkgNiAxOSA4IDYgMThdCls1IDYgMTQgMTkgMTMgNSAxOSA5IDE5IDkgOSAxOV0KWzkgMiAxMiAzIDcgMTEgMTUgMTEgNiA4IDExIDE3IDExXQpbMyA1IDE1IDcgMTggNSAzIDkgMTEgMiAxOCAxIDEwIDE5XQpbNiAxMSA0IDE5IDE0IDcgMTMgMTYgMTAgMTIgNyA5IDcgMTAgMTBdClsxMSAyMCAxMSAxIDIwIDE2IDExIDExIDQgOCA5IDcgMTEgMTQgMTAgMTRdCls0IDcgMTUgMiAzIDIgMyAxIDE0IDIgMTAgNCA3IDYgMTEgMiAxOF0KWzUgMSAxNyA3IDEgOSAzIDYgOSA3IDYgMyAyIDE4IDE0IDQgMTggMTZdCls1IDYgOCAxMCAxOCAxMyAyMCAxMCA3IDEgOCAxOSAyMCAxMCAxMCAxOCA3IDIgMV0KWzEyIDE3IDggMiA5IDcgMTUgNiAxOSA1IDEzIDE2IDE0IDIwIDEwIDExIDE4IDQgMyAxXQ). ### Explanation ``` &< % Input array implicitly. Matrix of all pairwise "less than" comparisons s % Sum of each column Q % Add 1. Display implicitly ``` [Answer] ## Python 2, 41 bytes ``` lambda l:map(sorted(l+[l])[::-1].index,l) ``` For each value, find its index in the list sorted by decreasing order. To make the largest value give 1 instead of 0, we use an extra "infinity" element of the list itself, since Python 2 treats lists as bigger than numbers. A more direct solution is 42 bytes and also works in Python 3. ``` lambda l:[1+sum(y<x for x in l)for y in l] ``` For each element, counts the number of smaller elements, adding 1 to shift to 1-indexed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ṢṚiЀ ``` [Try it online!](https://tio.run/nexus/jelly#@/9w56KHO2dlHp7wqGnN////o810FIx0FCx1FMzBDCDXVEfBGIxMYgE "Jelly – TIO Nexus") ### How it works ``` ṢṚiЀ Main link. Argument: A (array) ṢṚ Sort and reverse A. iЀ Find the index of each n in A in the previous result. ``` [Answer] # R, 24 ~~25~~ ~~20~~ bytes Uses the standard rank function with the "min" ties method over the negated vector. `cat` added to output it to STDOUT. Saved one thanks to @Guiseppe ``` cat(rank(-scan(),,"mi")) ``` Example ``` > cat(rank(-scan(),,"mi")) 1: 9 2 12 3 7 11 15 11 6 8 11 17 11 14: Read 13 items 8 13 3 12 10 4 2 4 11 9 4 1 4 > ``` [Answer] ## PowerShell v2+, ~~43~~ 41 bytes ``` ($a=$args)|%{@($a|sort -d).indexof($_)+1} ``` Developed independently, but I see that this is the same algorithm as @xnor's [Python solution](https://codegolf.stackexchange.com/a/102567/42963), so /shrug. Takes input as individual command-line arguments (i.e., a space separated list). Output (default formatting) is a newline between elements. For each element in the input list, it `sort`s the input list in `-d`escending order, takes the `.indexOf()` the current element, and adds `1`. Note the explicit array cast `@(...)` in order to account for a single-digit input. The resulting numbers are left on the pipeline and output is implicit. Saved 2 bytes thanks to @Matt! ### Example ``` PS C:\Tools\Scripts\golfing> .\rank-the-integers.ps1 6 2 9 7 2 6 5 3 3 4 3 9 1 2 9 3 5 7 7 6 ``` [Answer] # Octave, 15 bytes ``` @(x)sum(x<x')+1 ``` Port of my MATL answer to Octave. It also works in Matlab R2016b. The code defines an anonymous function. To call it, assign it to a variable. [Try it at Ideone](http://ideone.com/8CeOoQ). [Answer] ## JavaScript (ES6), ~~38~~ 36 bytes ``` a=>a.map(e=>a.map(d=>r+=e<d,r=1)&&r) ``` Edit: Saved 2 bytes thanks to @ETHproductions. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` <S‘ð€ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=PFPigJjDsOKCrA&input=&args=WzYsIDIsIDksIDcsIDIsIDYsIDUsIDMsIDMsIDRd)** ### How? ``` <S‘ð€ - Main link: listOfValues ð - dyadic chain separation € - for each < - less than (vectorises) - yields a list of 1s and 0s S - sum - yields number of values the current value is less than (those that beat it) ‘ - increment - the place of a value is the number that beat it plus 1. ``` [Answer] # [Perl 6](https://perl6.org), ~~42~~ 26 bytes Find the first index `:k` in a reversed `[R,]` sorted list ``` {map {[R,](.sort).first(*==$^a,:k)+1},@$_} ``` Count the values that are larger, and add one ``` {map {1+.grep(*>$^a)},@$_} ``` [Answer] # JavaScript, ~~87~~ 49 bytes ~~`f=a=>a.slice().map(function(v){return a.sort(function(a,b){return b-a}).indexOf(v)+1 })`~~ `a=>[...a].map(v=>a.sort((a,b)=>b-a).indexOf(v)+1)` Thanks Conor O'Brien and ETHproductions! [Answer] ## Mathematica, 44 bytes 42 bytes 40 bytes ``` xPosition[SortBy[x,-#&],#][[1,1]]&/@x ``` `` is the 3 byte private use character [`U+F4A1`](https://unicode-table.com/en/F4A1/) ([Wolfram docs page](https://reference.wolfram.com/language/ref/character/Function.html)) Edit: Thanks to [JHM](https://codegolf.stackexchange.com/users/60043/jhm) for the byte savings. [Answer] ## Pyke, 6 bytes ``` FQS_@h ``` [Try it here!](http://pyke.catbus.co.uk/?code=FQS_%40h&input=%5B10%2C+2%2C+5%2C+4%2C+15%2C+5%5D) ``` F - for i in input(): QS - sorted(input()) _ - reversed(^) @ - i.find(^) h - ^+1 (not required if allowed to start from 0) ``` [Answer] # [J](http://www.jsoftware.com/), ~~14~~ 8 bytes ``` 1+1#.</~ ``` ### How? ``` 1+1#.</~ - Consumes and returns a list of integers ~ - Use the same list for both inputs </ - Create a table of less-than comparisons 1#. - Treat each row like digits of a base-one number, returning a list of integers 1+ - Increment the results ``` ### Previous solution ``` 1+(+/@:<)"0 1~ ``` [Answer] ## Haskell, 28 bytes ``` f l=[1+sum[1|y<-l,y>x]|x<-l] ``` Just some list comprehensions. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 28 bytes ``` @(->@+1:0iO#0rev sort#I#1)#0 ``` Usage: ``` (@(->@+1:0iO#0rev sort#I#1)#0)[6 2 9 7 2 6 5 3 3 4] ``` Map over input array with a function that adds 1 to the first index of the item in a descending-sorted version of the input. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 7 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⊢⍳⍨⍒⊃¨⊂ ``` `⊢` arguments' `⍳⍨` indices in `⍒` the indices which would sort the argument descending `⊃¨` each picked from `⊂` the entire argument [TryAPL online!](http://tryapl.org/?a=f%u2190%u22A2%u2373%u2368%u2352%u2283%A8%u2282%20%u22C4%20f%206%202%209%207%202%206%205%203%203%204&run) [Answer] # Mathematica, 37 bytes ``` Min@Position[-Sort@-#,i]~Table~{i,#}& ``` A pure function which will rank it's input, as per the rules of the problem. Ex: ``` Min@Position[-Sort@-#, i]~Table~{i, #} &[{6, 2, 9, 7, 2, 6, 5, 3, 3, 4}] (*{3, 9, 1, 2, 9, 3, 5, 7, 7, 6}*) ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 15 bytes ``` p`&& ~i >/+`< ``` [Try it online!](https://tio.run/nexus/jellyfish#@1@QoKamUJfJpaBgp6@dYPP/f7ShkYKZgqGBgpGCoSUImYEICxBlEQsA "Jellyfish – TIO Nexus") ### Explanation There doesn't seem to be a good way to find the index of a value in a list in Jellyfish yet, so this uses the approach of counting how many values are bigger than current one and incrementing the result. This is largely done by constructing a unary function which computes this value for a given element. ``` `< ``` This creates a threaded version of the comparison operator, so if you give this an integer and a list, it will return a list of comparison results between that integer and each element in the list. ``` ~i `< ``` This curries the right-hand argument of the previous function with the input list. So the result is a unary function which takes an integer and gives you the list of comparison results with the input of the program. ``` & ~i /+`< ``` Here, `/+` is reduction by addition, which means it's simply a "sum this list" function. `&` composes this onto the previous function, so we now have a unary function which *counts* how many values in the input are bigger than that integer. ``` && ~i >/+`< ``` We also compose the increment function onto this. ``` `&& ~i >/+`< ``` Finally, we thread this function as well, so that it's automatically applied to each integer of a list passed to it. Due to the layout of the code, `i` happens to be taken as the input of this function as well, so that this computes the desired output. ``` p`&& ~i >/+`< ``` Finally, this prints the result. [Answer] ## brainfuck, 124 bytes ``` ->,[>>>+>,]<[-<+]+[-->[<[<<<<]>>>+>[>[>>]<[[<<+<<]>+>[->>>>]]<+>>>]+[-<<+]->]<[< <<<]>+.,>>[>[>->+>>]<<[-<<<<]>-]+[->+]+>>>>] ``` Formatted: ``` -> ,[>>>+>,] <[-<+] + [ --> [ <[<<<<] >>>+> [ >[>>] < [ [<<+<<] >+>[->>>>] ] <+> >> ] +[-<<+] -> ] <[<<<<] >+.,>> [ >[>->+>>] <<[-<<<<] >- ] +[->+] +>>>> ] ``` This is designed for 8-bit brainfuck implementations. Input and output are via [byte values](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719). [Try it online.](http://brainfuck.tryitonline.net/#code=LT4sWz4-Pis-LF08Wy08K10rWy0tPls8Wzw8PDxdPj4-Kz5bPls-Pl08W1s8PCs8PF0-Kz5bLT4-Pj5dXTwrPj4-XStbLTw8K10tPl08Wzw8PDxdPisuLD4-Wz5bPi0-Kz4-XTw8Wy08PDw8XT4tXStbLT4rXSs-Pj4-XQ&input=NjI5NzI2NTMzNA&debug=on) For each element, this counts the number of elements greater than it, then prints the result plus one. This is accomplished by incrementing all elements until the current element equals zero, updating the result whenever another element becomes zero before the current element. The tape is broken into 4-cell nodes, `b c 0 0` where `c` is the element and `b` is a navigation flag that is negative one for the current element, otherwise one. The result and a copy of the current element are kept to the left of the array. [Answer] # Java, 215 bytes ``` public class G{public static void L(int[]A){int[]r=new int[A.length];for(int i=0;i<A.length;i++){int c=1;for(int j=0;j<A.length;j++){if(A[j]>A[i])c++;}r[i]=c;}for(int i=0;i<r.length;i++)System.out.print(r[i]+",");}} ``` Explanation: Very self explanatory. Basically for each integer in the array it checks how many are larger than it, then prints the new array with the rankings. I'm sorry this isn't very concise but it's my first try at one of these and I didn't see an entry for java. I'm sure it can be golfed down more. It can be run just by making reference to the static method and passing an array. I didn't think it was necessary to write the main function but if it is I'll do that in the future. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` m€↔O¹ ``` [Try it online!](https://tio.run/##yygtzv7/P/dR05pHbVP8D@38//9/tJmOkY6ljjmQNNMx1TEGQpNYAA "Husk – Try It Online") ## Explanation ``` m€↔O¹ O¹ sort the input in ascending order ↔ reverse it m ¹ map the input to: € it's index in that list ``` [Answer] # PHP, 101 bytes There must be some shorter way. ``` function f(&$a){for($r=1;$v++<max($a);$r+=$n,$n=0)foreach($a as$k=>$w)if($w===$v){$a[$k]="$r";$n++;}} ``` function takes input as array of integers, overwrites input variable with ranks as numeric strings. Usage: `$a=[1,2,4,2,2,3];f($a);print_r($a);` [Answer] # Ruby, ~~45~~ 40 bytes ``` ->a{a.map{|x|a.sort.reverse.index(x)+1}} ``` [Answer] # [Tcl](http://tcl.tk/), 54 bytes ``` proc R L {lmap x $L {lsearch .\ [lsort -r -de $L] $x}} ``` [Try it online!](https://tio.run/##TVJBboMwELzzijnkmgob2@A/9JRr2kNEI/VAFUSoFAnxdjqzBqkSYb07M@vZJXM/bNs4PXpc8I5l@LmNeOGk4/N@m/pvvH3gOjwf04zzhPPXneAnTq913YxMZrV0a7U4uKjQwQU4pyNLSZnBEf8eFWp4RAQV4opqYQCLfBgp7VT0JGSRWga@XNob81gKpmCPRgoJiPJK5qx4@Fpqc@CRYLdKmZVk8lJBI8yqoEYGMnJ5KRDP0nn2bM2cWUyU7140r@miCB3kJwv0ypx5VJtU7OmaIGZjK6rVWhPu85QZaV3dLZpunyzvHoKRA8nWKkL29DPMCxWQDhs2pdklm10aQtkIzW4z2K7KkmMZr7ZCYyZqE3ZyX9KCtlKXBbN3xywXP7bheAwZDpG@LS9ilV94xTL@zk9cL/pjrdsf "Tcl – Try It Online") [Answer] # PHP, 84 bytes ``` function r($l){$s=$l;rsort($s);foreach($l as$n)$r[]=array_search($n,$s)+1;return$r;} ``` Usage: Pass the function r your array of integers and it will return the corresponding array of ranked integers. [Passing tests here.](http://sandbox.onlinephpfunctions.com/code/f25a46c15cf3bda0e7b0ec4ec9655f72c664430f) [Answer] # Perl 5, 23 +2 (-ap) ``` s/\d+/1+grep$&<$_,@F/ge ``` [Try it online](https://tio.run/##K0gtyjH9/79YPyZFW99QO70otUBFzUYlXsfBTT899f9/Q0MFQ3MFQ0swaQBGpgrGCoYW//ILSjLz84r/6yYWAAA) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 11 bytes **Solution:** ``` 1+(x@>x)?x: ``` [Try it online!](https://tio.run/##Dcg7CoAwEAbhq0ypiOC/JuZRqPdJYbu3XwNTfMzYvxGhbfH39vXxLkOFitEoKHOhRkYnmkzYgWZClcS8ET8 "K (oK) – Try It Online") **Examples:** ``` 1+(x@>x)?x:6 2 9 7 2 6 5 3 3 4 3 9 1 2 9 3 5 7 7 6 1+(x@>x)?x:5 6 14 19 13 5 19 9 19 9 9 19 11 10 5 1 6 11 1 7 1 7 7 1 ``` **Explanation:** Lookup position of original list in sorted list, then add one. ``` 1+(x@>x)?x: / the solution x: / save input as x ( >x) / return indices of x sorted in descending order x@ / apply these indices to x (thus sort x) ? / lookup right in left 1+ / add one ``` [Answer] # Clojure, ~~48~~ 44 bytes Update: using `for` instead of `map` ``` #(for[i %](+(count(filter(partial < i)%))1)) ``` Simply filters each value smaller than the current one, counts the length of the list and increments by one. ]
[Question] [ ## Display a Digital Clock (I see there are many clock challenges, I have tried to read them all, I'm pretty sure this is unique) Write some code that continuously updates a digital clock displayed in the format `h:m:s` where `h`, `m`, and `s` can occupy 1 or 2 characters each. The restrictions in simple terms as @BlueEyedBeast put it, I basically want it to replace the time shown. * Newlines are not allowed * Trailing spaces are allowed * Other trailing characters are not allowed * No seconds should be missed (57 -> 59 is not allowed) * Numbers beginning with "0" are allowed, as long as they don't occupy more than 2 characters * The code must not accept any input * If your language can't get the current time without input, you may use for input up to 8 bytes in a standardly allowed way * Output must be to stdout * This is codegolf so the shortest answer wins! **Example** ~~I'm working on a language named \*><> (starfish) because programs like this aren't possible in ><> (just wait for file i/o) . Here's a working digital clock program in it (ungolfed).~~ This program is written in [\*><>](http://esolangs.org/wiki/Starfish): ``` s":"m":"hnonon" "ooo88888888888ooooooooooo1S ``` Note: Everything is identical to ><> in this except, s = second, m = minute, h = hour, S = sleep(100ms\*x) This outputs: ``` 14:44:31 ``` Updating every 100ms until terminated. **Disallowed Examples** The following are not allowed: 1: ``` 14:44:3114:44:32 ``` 2: ``` 14:44:31 14:44:32 ``` 3: ``` 14:44:31 14:44:32 ``` The time must remain on the first line it was outputted with no visible trailing characters. Clearing the terminal though, would be allowed as that still wouldn't have any trailing characters. [Answer] # HTML + JS (ES6), 8 + 60 = 68 bytes Tested in Chrome. ``` setInterval`a.innerHTML=new Date().toLocaleTimeString('fr')` ``` ``` <a id=a> ``` -1 byte (@ETHProductions): Use French time format instead of `.toTimeString().slice(0,8)` --- # HTML + JS (ES6), 8 + 62 = 70 bytes This will work in FireFox. ``` setInterval('a.innerHTML=new Date().toLocaleTimeString`fr`',0) ``` ``` <a id=a> ``` -3 bytes (@ETHProductions): Use French time format instead of `.toTimeString().slice(0,8)` [Answer] # Python 2, 50 bytes (Python 2.1+ for `ctime` with no argument) ``` import time while 1:print'\r'+time.ctime()[11:19], ``` `time.ctime()` yields a formatted string, from which the hh:mm:ss may be sliced using `[11:19]` (it remains in the same location whatever the date and time). `print`ing the carriage return `'\r'` before the text and making the text the first item of a tuple with `,` effectively suppresses the implicit trailing `'\n'` and overwrites the previously written output. `while 1` loops forever. [Answer] # Mathematica, ~~48~~ ~~41~~ ~~37~~ 28 bytes ``` Do[s=Now[[2]],∞]~Monitor~s ``` The output will be a `TimeObject`, refreshing continuously. Looks like this: [![enter image description here](https://i.stack.imgur.com/B6qZf.jpg)](https://i.stack.imgur.com/B6qZf.jpg) **Alternative versions** 48 bytes: ``` Dynamic@Refresh[TimeObject[],UpdateInterval->.1] ``` 53 bytes: ``` Dynamic@Refresh[DateString@"Time",UpdateInterval->.1] ``` [Answer] ## Pyke, 6 bytes ``` Ctr\ J ``` [Try it here!](http://pyke.catbus.co.uk/?code=Ctr%5C+J) I think this is valid. Replace the space character with carriage return for valid output (does not work online) [Answer] I see that the requirement for a non-signal UI input to stop the program has been removed. So now we can do: # Bash + coreutils, 28 ``` yes now|date -f- +$'\e[2J'%T ``` `yes` continuously outputs the string "now", once per line, into a pipe. `date -f-` reads interprets each "now" as the current time, then outputs in the required format. The format string includes the ANSI escape sequence to clear the screen. `date` *does* output a newline after the date - I'm not sure if this disqualifies, since the screen is cleared every time anyway. If it disqualifies, then we can use `tr` instead: # Bash + coreutils, 31 ``` yes now|date -f- +%T|tr \\n \\r ``` --- Previous Answers: # Bash + X, 32 ``` xclock -d -update 1 -strftime %T ``` Unfortunately this can only update every second. If that disqualifies, then we can do this instead: # Bash + coreutils, 43 ``` until read -t0 do printf `date +%T`\\r done ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 6 bytes ``` {_C?_d { Starts a DO-loop _C CLS ? PRINT _d TIME$ ``` Constantly clears the screen and prints the system time in the format `22:03:41`. [Answer] # PHP, 28 bytes ``` for(;;)echo date("\rH:i:s"); ``` The `date` function prints everything literally that it doesn´t recognize. `\r` is the carriage return, sets the cursor to the first column. Run with `-r`. [Answer] # Clojure, ~~150~~ ~~136~~ 141 bytes ## V3: 141 bytes :( +5 bytes to fix a bug. Since the times aren't zero padded, the clock can "shrink" and expand when the time changes. It was "smearing" when it shrunk because the last digit was no longer being cleared. Fixed it by adding some spaces at the end to ensure everything is being overwritten. ``` #(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))" "))(Thread/sleep 99)) ``` ## V2: 136 bytes ``` #(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))))(Thread/sleep 99)) ``` -14 bytes by switching to using `SimpleDateFormat` to format the date. Still huge. ## V1: 150 bytes ``` #(while true(let[d(java.util.Date.)](flush)(print(str(apply str(repeat 9 "\b"))(.getHours d)":"(.getMinutes d)":"(.getSeconds d)))(Thread/sleep 100))) ``` I realized I'm probably using the worst way possible to get the date. Definitely room for improvement here. Ungolfed: ``` (defn -main [] (while true (let [d (java.util.Date.)] (flush) (print (str (apply str (repeat 9 "\b")) (.getHours d)":"(.getMinutes d)":"(.getSeconds d))) (Thread/sleep 100)))) ``` [Answer] # SmileBASIC 3.3.2, 38 bytes ``` @L?TIME$;" "; GOTO@L ``` UTF-16 sucks :( Anyway, this repeatedly prints the local time in HH:MM:SS with a space after it, no newline afterward. It doesn't update every second though, it just repeatedly prints forever. [Answer] ## C, ~~134~~ ~~116~~ ~~89~~ ~~80~~ ~~76~~ ~~75~~ 73 bytes ``` main(n){for(;time(&n);)printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);} ---- Old versions: main(n){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);} n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);} ---- n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",n/3600%24,n/60%60,n%60);} ---- Saved 9 more bytes thanks to @nmjcman101 again: n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",(n/3600)%24,(n/60)%60,n%60);} ---- Saved 27 bytes thanks to @nmjcman101 n,b[9];main(){for(;;){n=time(0);strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}} ---- I figured out I don't need to put `#include<stdio.h>` into the file :) #include<time.h> main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}} ---- #include<time.h> #include<stdio.h> main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}} ``` [Answer] # Bash + watch, 19 bytes *watch* is not a part of *coreutils*, but is available out of the box on virtually every Linux distro. **Golfed** ``` watch -tn1 date +%T ``` [Try it online !](https://goo.gl/5Ayb7t) [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` `XxZ'13XODT ``` Infinite loop that clears the screen and prints the time in the specified format. You can try it at [MATL Online!](https://matl.io/?code=%60XxZ%2713XODT&inputs=&version=19.5.1). This compiler is experimental; if it doesn't work refresh the page and press "Run" again. [Answer] # WinDbg, 73 bytes ``` .do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1 ``` It continually updates a line with the current time until the user presses Ctrl+Break. How it works: ``` .do * Start do-while loop { r$t0 = 0; * Set $t0 = 0 .foreach(p {.echotime}) * Foreach space-delimited word in a sentence like "Debugger (not { * debuggee) time: Mon Dec 5 14:08:10.138 2016 (UTC - 8:00)" r$t0 = @$t0+1; * Increment $t0 j 8==@$t0 * If $t0 is 8 (ie- p is the current time) ' .printf"p \r" * Print p (current time) and \r so the next print overwrites ' } } 1 * Do-while condition: 1, loop forever ``` Sample output (well, you get the idea): ``` 0:000> .do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1 14:10:12.329 ``` [Answer] # C#, 82 bytes ``` ()=>{for(;;)Console.Write(new string('\b',8)+DateTime.Now.ToString("HH:mm:ss"));}; ``` Anonymous method which constantly overwrites 8 characters with new output. Can be made 1 byte shorter if modifying to accept a dummy parameter (`z=>...`). Full program: ``` using System; public class Program { public static void Main() { Action a = () => { for (;;) Console.Write(new string('\b', 8) + DateTime.Now.ToString("HH:mm:ss")); }; a(); } } ``` [Answer] ## C#, 65 bytes ``` ()=>{for(;;)Console.Write("\r"+DateTime.Now.ToLongTimeString());}; ``` Works by overwriting the same line within an endless loop [Answer] # Powershell, 39 bytes ``` for(){write-host -n(date -F h:m:s`0`r)} ``` Because I dislike using cls in Powershell. From briantist's post @<https://codegolf.stackexchange.com/a/102450/63383> [Answer] # Pascal, 61 bytes ``` uses sysutils;begin while 1=1do write(#13,timetostr(now))end. ``` Free pascal has nice time routines in SysUtils unit. Ungolfed: ``` uses sysutils; begin while 1=1 do write(#13, timetostr(now)); end. ``` [Answer] # Commodore BASIC (CBM/PET, C64, C128, VIC-20, C16/+4), 64 ~62 BASIC bytes (tokens), 64 62 PETSCII characters with keyword abbreviations ``` ?"{CLEAR}":FORI=0TO1:?"{HOME}"LEFT$(TI$,2)":"MID$(TI$,3,2)":"RIGHT$(TI$,2):I=0:NEXT ``` **Edit** I realised that this is what I would call a *zero liner*, or in other words, it does not require a line number to run, so I've taken this out. Once you break it though, you need to type it in again. **Changes** Line numbers in Commodore BASIC take up I think at least two bytes (though I need to check), so by actual byte count is an estimation, however, removing the line number and using the `LEFT$` command for the first two digits, rather than the `MID$` command, has shaved off two whole characters from this. Some notes: if you are entering this on a Commodore C64 then you will need to use keyword abbreviations (see the screen shot below). Some other Commodore 8-bits, like the C128 and VIC-20, accept more than 80 characters entered per line, but to be sure, use the keyword abbreviations anyway. To set the time first, use `TI$="112233"` as `HHMMSS` format as 24 hours (`000000` being midnight). ## How it works `TI$` is a system variable which fairly accurately keeps time. 8 BIT Show and Tell explores this in some depth in [this YouTube video](https://youtu.be/VkabHdR15xs) and is well worth a watch if you are interested. An unbroken loop is set with resetting the `I` variable per iteration by setting it to `0`. We then use the `MID$` and `RIGHT$` function to print out each relevant time segment, being `HH:MM:SS`. A list of BASIC keywords can be found [here](https://www.c64-wiki.com/wiki/BASIC). [![Display a Digital Clock, Commodore C64](https://i.stack.imgur.com/zBhRD.png)](https://i.stack.imgur.com/zBhRD.png) [Answer] # Vim, 26 bytes ``` qqS<C-r>=strftime("%T")<CR><esc>@qq@q ``` This creates a recursive macro (e.g. an eternal loop) that deletes all the text on the current line and replaces it with the current time. [Answer] # Pyth - 28 bytes Kinda longish, because pyth has no strftime. ``` #p+"\r"j\:m.[`02`dP>4.d2.d.1 ``` [Answer] # Groovy, 45 characters ``` for(;;)print(new Date().format("\rHH:mm:ss")) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` 13Ọ7ŒTȮß 13Ọ chr(13), carriage return 7ŒT time string, which extends the previous character Ȯ print ß call the whole link again ``` [Try it online!](http://jelly.tryitonline.net/#code=MTPhu4w3xZJUyK7Dnw) The carriage return doesn't work online, and I can't get the interpreter to work, so its kinda untested, but it works as expected when I use printable characters in place of the CR. [Answer] # ForceLang, 123 bytes ``` def s set s d datetime s z string.char 8 s z z.repeat 16 label 1 io.write z io.write d.toTimeString d.now() d.wait 9 goto 1 ``` `datetime.toTimeString` is backed in the reference implementation by Java's `DateFormat.getTimeInstance()`, which is locale-dependent, so you can set your default system locale to one that uses 24-hour time. [Answer] # PowerShell, ~~30~~ ~~28~~ ~~24~~ 20 bytes Changed my computer's region to Germany based on [raznagul](https://codegolf.stackexchange.com/users/42502/raznagul)'s comment to save 4 bytes. :) ``` for(){date -F T;cls} ``` ### Previous version that works in all locales. ``` for(){date -F h:m:s;cls} ``` [Answer] # Java, 67 bytes ``` for(;;)System.out.print("\r"+java.time.LocalTime.now()+"\b\b\b\b"); ``` We loop infinitely, grabbing the current time and outputting to screen. The quad backspace is for easy formatting, because otherwise we'd have to do something like this: ``` for(;;)System.out.print("\r" + java.time.LocalTime.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS)); ``` [Answer] # tcl, 69 bytes ``` while 1 {puts -nonewline \r[clock format [clock seconds] -format %T]} ``` [Try it here!](http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMUkdTRkhVUDRFbkU) [Answer] ## C 65 (prev 64) bytes Guaranteed to work on Linux machine. :) @Marco Thanks! ``` f(){while(1){system("date +%T");usleep(100000);system("clear");}} ``` [Answer] # SmileBASIC, 14 bytes ``` CLS?TIME$EXEC. ``` `CLS` clears the screen, `? TIME$` prints the current time, and `EXEC 0` runs the code that's in slot 0. It's a bit flickery, but there's nothing in the reqirements about that, so it should be fine. Format is `HH:MM:SS` 24 hour time :( [Answer] # x86-16 machine code, IBM PC DOS, ~~71~~ 69 bytes Binary: ``` 00000000: b81c 35cd 2153 06ba 1901 e806 00b4 08cd ..5.!S.......... 00000010: 211f 5ab8 1c25 cd21 c3b4 2ccd 218a c5e8 !.Z..%.!..,.!... 00000020: 0800 91e8 0400 8ac6 b2ff d40a 0d30 3086 .............00. 00000030: e0cd 2986 e0cd 2984 d27c 05b0 3acd 29c3 ..)...)..|..:.). 00000040: b00d cd29 cf ...). ``` Listing: ``` B8 351C MOV AX, 0351CH ; AL = 1CH, AH = 35H CD 21 INT 21H ; get interrupt vector for 1CH into ES:BX 53 PUSH BX ; save old vector 06 PUSH ES ; save old segment BA 011D R MOV DX, OFFSET GET_TIME ; DX = interrupt vector of time proc E8 0117 R CALL SET_VECT ; setup new vector B4 08 MOV AH, 8 ; DOS read char from stdin without echo CD 21 INT 21H ; wait for user to press the "any key" 1F POP DS ; restore old segment 5A POP DX ; restore old vector SET_VECT: B8 251C MOV AX, 0251CH ; AL = 1CH, AH = 25H CD 21 INT 21H ; set interrupt vector from DS:DX C3 RET ; return to DOS GET_TIME: B4 2C MOV AH, 2CH ; get DOS time CD 21 INT 21H ; CH = hour CL = minute DH = second 8A C5 MOV AL, CH ; display hour: AL = CH E8 012E R CALL OUT_TIME ; write time 91 XCHG AX, CX ; display minute: AL = CL E8 012E R CALL OUT_TIME ; write time 8A C6 MOV AL, DH ; display second: AL = DH B2 FF MOV DL, -1 ; set DL to -1 so doesn't display ':' OUT_TIME: D4 0A AAM ; BCD convert: AL = AL % 10, AH = AL / 10 0D 3030 OR AX, '00' ; ASCII convert 86 E0 XCHG AH, AL ; endian convert CD 29 INT 29H ; write tens 86 E0 XCHG AH, AL ; swap digits CD 29 INT 29H ; write ones 84 D2 TEST DL, DL ; when DL = -1, it is seconds digit 7C 05 JL DONE_TIME ; if last number, write CR not ':' B0 3A MOV AL, ':' ; write ':' CD 29 INT 29H C3 RET ; return from near call DONE_TIME: B0 0D MOV AL, 0DH ; carriage return CD 29 INT 29H ; move cursor back to beginning of line CF IRET ; return from interrupt ``` A standalone PC DOS executable COM program. Uses DOS to hook the hardware timer interrupt which calls the program every 18.2ms to update the clock on the screen. Exits when any key is pressed. Runtime: [![enter image description here](https://i.stack.imgur.com/GkdLi.gif)](https://i.stack.imgur.com/GkdLi.gif) (A key was hit after 5 seconds, exiting the program) [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` i@OqK¤¯8 ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=aUBPcUukrzg) ``` i@OqK¤¯8 i :Every 0 milliseconds @ :Run the following function Oq :Replace the output with K :Date object ¤ :Convert to time string ¯8 :Slice to the 8th character ``` ]
[Question] [ July 1st is Canada day (yay Canada)! Or is it? It seems that the [Wikipedia](https://en.wikipedia.org/wiki/July_1) page for this day has a lot of Canada related content, but is there another day which is more Canadian? Your task is to write a program or function which takes a date (month and day) as input and returns or outputs the number of mentions of "Canada" on the Wikipedia page for the inputed date. Some rules: * Dates may be input in any reasonable format of your choice * Your submission must pull data from the url `en.wikipedia.org/wiki/Month_Day`. * Only `"Canada"` must be searched for and counted included substrings, and only in title case. `"Canadian"` does not count, however `"Canada's"` does count. As long as the exact, case-senstitive text `"Canada"` exists within a string, it is a match * Contents of the page are considered anything within the corresponding `.html` file (i.e. what shows up if you download as page as a `.html` and open it in Notepad) * Result may be output to STDOUT, returned, or displayed in any other reasonable manner Test Cases: ``` July 1 => 34 May 14 => 1 Oct 31 => 2 July 4 => 2 ``` This is code golf, so shortest submission wins (As an unrewarded bonus, I'm interested to see what the day with the highest count is) [Answer] # Bash, 43 42 40 bytes ``` curl -L enwp.org/$@|grep -o Canada|wc -l ``` Uses `curl`, `grep`, and `wc` to count occurrences of "Canada" in specified webpage. Like the other answers, input is given in the format `July_1`. This is my first time posting on the Code Golf SE and I'm not quite familiar with all of the rules. Any feedback would be most welcome. *Didn't realize that output to* `STDERR` *is traditionally ignored. Thanks for the 3 bytes, [Dennis](//codegolf.stackexchange.com/users/12012/dennis)!* [Answer] # Perl 5, 39 bytes 38 bytes, plus 1 for `-pe` instead of `-e` ``` $_=()=`curl -L enwp.org/$_`=~/Canada/g ``` Takes input like `July_1`. Thanks to [busukxuan](/users/49362/busukxuan) for saving me seven bytes. [Answer] # Python 3.5, ~~117~~ ~~111~~ ~~98~~ 90 bytes (*-8 bytes (`98 -> 90`) thanks to [alexwlchan](https://codegolf.stackexchange.com/users/13285/alexwlchan)*) ``` from urllib.request import* lambda i:urlopen('http://enwp.org/'+i).read().count(b"Canada") ``` Simply uses Python's built-in "urllib" library to fetch HTML data and then counts the occurrences of the word "Canada" in that data. Will try and golf more over time where and when I can. Call it by renaming the `lambda` function to anything and then calling that name like a normal function wrapped in `print()`. For instance, if the function were named `H`, then you would call it like `print(H(Month_Day))`. [Answer] # Mathematica, 60 bytes ``` Import["http://enwp.org/"<>#,"Source"]~StringCount~"Canada"& ``` Anonymous function. Similarly to the Perl 5 solution, takes input like `July_1`. [Answer] # PowerShell, 52 bytes ``` ((iwr enwp.org/$($args[0]))-csplit"Canada").length-1 ``` * Input as `July_1`. * `iwr` is short for `Invoke-WebRequest`. * `$($args[0])` is first command line argument. Start script as `OhCanada.ps1 July_1`. * `-csplit` is case sensitive split. [Answer] # C#, 85 bytes ``` return Regex.Matches(new WebClient().DownloadString("http://enwp.org/"+d),"Canada").Count; ``` Takes input `d` like `July_1`. And `July_1` *is* truly Canada Day, having the most references. With `February_1` and `April_23` sharing 2nd place with 18 `"Canada"`s each. # Find `"Canada"` day (in parallel), 207 bytes: ``` return Enumerable.Range(0,366).Select(i=>new DateTime(8,1,1).AddDays(i).ToString("MMMM_d")).AsParallel().OrderBy(d=>Regex.Matches(new WebClient().DownloadString("http://enwp.org/"+d),"Canada").Count).Last(); ``` (Year 8 is the leap year with the shortest representation). Potentially inefficient, in that the `OrderBy` probably generates >366 web calls, but just going for shorter and appears to complete in not much more time. [Answer] # Pyth, 31 bytes ``` /jk'+"http://enwp.org/"z"Canada ``` Does not work on the online implementation, the server disables Internet access. I wanted to use <http://wki.pe/July_1> but sadly it's a client-side redirect so it fetches the wrong page. The input format is `July_1`. The code is basically just: ``` "".join(open("http://enwp.org/"+input())).count("Canada") ``` [Answer] # R, 99 96 bytes x=function(d){p=readLines(paste0("<http://enwp.org/>",d));sum(nchar(p)-nchar(gsub("Canada","",p)))/6} ``` d=scan(,"");p=readLines(paste0("http://enwp.org/",d));sum(nchar(p)-nchar(gsub("Canada","",p)))/6 ``` This takes input d in the form "July\_1" and returns the count of Canadas. It counts the words by counting the number of characters on the page, then removes the word Canada from the page and counts the characters again. The number of times Canada shows up is the difference in these counts divided by the number of letters in Canada, 6. edit: I appreciate the tip below about replacing my function with scan. [Answer] # ES6, 89 bytes ``` d=>fetch('http://enwp.org/'+d).then(r=>r.text().then(t=>alert(t.split`Canada`.length-1))) ``` Sadly Unwrapping all the promises penalises the size :/ [Answer] # Clojure, 71 bytes ``` #(count(re-seq #"Canada"(slurp(str"https://en.wikipedia.org/wiki/"%)))) ``` Yeah, it would be nice to use `http://enwp.org` but I guess `slurp` does not handle redirects(?). Anonymous function which take day in the format "July\_1". [Answer] # Ruby + curl, 44 bytes ``` p`curl -L enwp.org/#$_`.scan(/Canada/).size ``` `ruby -n` + 43 bytes. Takes input like `July_1`. [Answer] # PHP, 65 bytes ``` echo substr_count(file_get_contents('http://enwp.org'),'Canada'); ``` ]
[Question] [ A pleasing number (according to this definition) is a number that can be passed through the following process (let's use `41802000` as an example): * Separate the trailing identical numbers (`41802000 => [41802, 000]`) * Sort the first half of the digits and take the maximum (`[41802, 000] => [8, 000]`) * Take the length of the final element. Call the resultant elements *A* and *B* (`[8, 000] => A=8, B=3`) * Is NB = A for any integer `N`? (`True` in this example; 23 = 8) If the input results in `True` from the following process, it is considered pleasing. Your task is to take an integer `x`, and output whether `x` is a pleasing number. You can output any two distinct values for truthy and falsey, but please state what you're using in your answer. `x` is guaranteed to have at least two distinct digits (e.g. `111` is an invalid input). As with most challenges, you may take `x` as a string, or a list of digits. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in *bytes* wins. ## Test cases ``` Input Output 41802000 1 100 1 123456788 0 451111111 0 234543454545444 0 12 1 41902000 0 92599 1 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 36 bytes ``` {(⊢≡⌊)(⌈/⍎¨⍵/⍨~o)*÷≢⍵/⍨o←⌽⌊\1,2=/⌽⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUddix51LnzU06Wp8ainQ/9Rb9@hFY96twIZK@ryNbUOb3/UuQjKzwdqeNSzF6g2xlDHyFYfxO7dWgs0SeFR71QFE0MLAyMDAwMuCNcQwTIyNjE1M7ewgPJNTA0hAMhXB8mZgDAImpiow/UAAA "APL (Dyalog Unicode) – Try It Online") **How?** *Almost a poem.* `⌽⍵` - reverse the input once, `1,2=/` - get the differences list. `⌊\` - keep only the first group of ones, `⌽` - and flip it over to complete. --- `o←` - assign to `o`, `~o` - switch ones and zero(s), `⍵/⍨` - filter the input with it, `⍎¨` - turn the result into list of each digit, * `⌈/` - and get the maximum. (that's A) --- `⍵/⍨o` - filter the input with `o` unalt(ered), `≢` - and take the length, that would be B. `÷` - get one divided by this result, `*` - and take A to that power thee. --- `⊢≡⌊` - integer? [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` γRćgUZXzm.ï ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3OagI@3poVERVbl6h9f//29iaGFgZGBgAAA "05AB1E – Try It Online") ## Explanation ``` γRćgUZXzm.ï ~ Full program. γ ~ Split into runs of digits. R ~ Reverse. ć ~ Push a[1:], a[0] to the stack. g ~ Length (of a[0]). U ~ Assign this to the integer variable X. ZX ~ Get the maximum, without popping, and push X. zm ~ A1/B. .ï ~ Is it an integer? ``` [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) saved 1 byte. Relies on the fact that if **A** is a positive integer **N** raised to the power of **B**, then **N=A1/B**, hence it must be an integer. [Answer] # [Haskell](https://www.haskell.org/), ~~85~~ ~~75~~ ~~72~~ 71 bytes ***Edit**: -10 bytes by taking a list of digits instead of a string. Thanks to [WhatToDo](https://codegolf.stackexchange.com/users/76292/whattodo) for pointing out that this is allowed. -3 bytes thanks to [Ourous' solution in Clean](https://codegolf.stackexchange.com/a/150964/56433). -1 byte thanks to [user28667](https://codegolf.stackexchange.com/users/75762/user28667).* ``` f s|(b,a)<-span(==last s)$reverse s=or[n^length b==maximum a|n<-[1..9]] ``` [Try it online!](https://tio.run/##dU5RasMwDP3PKfSxjwSUYLtK60B9hJ3AZOCCu4bGXoizMVh39sxZlrJ2y3sIIT09SScTzrZtx/EI4ZIe0GT7PHTGp0q1JgwQsofevtk@WAjqpdf@qbX@eTjBQSln3hv36sBc/D7XvCiquh6daTwocKZ7hLTrGz9AAccMtCbkKJGhiBFZo@bXLHCDhCVucRdnZOxNFf/N2Fum6JqXiJz3fDs5Vnd3pp118pEnMIO4ZIIxBrfgyU21qnOxoXK7k/JOZz86lXzGH30y0hQTiVb8yzmx9h/x6r//WZJ/jl8 "Haskell – Try It Online") Takes input as a list of digits. Example usage: `f [4,1,8,0,2,0,0,0]` yields `True`. ### Explanation: Given an input `s=[4,1,8,0,2,0,0,0]`, we `reverse` the list and separate the leading elements with `span(==last s)`: `([0,0,0],[2,0,8,1,4])`. The pattern matching on `(b,a)` yields `b=[0,0,0]` and `a=[2,0,8,1,4]`. The list comprehension `or[n^length b==maximum a|n<-[1..a]]` checks whether any integer `n` in the range from `1` to `9` satisfies `n^length b==maximum a`, that is `n^3=8`. [Answer] # [Haskell](https://www.haskell.org/), ~~104~~ 89 bytes @Laikoni found a [shorter solution](https://codegolf.stackexchange.com/a/150960/24877), but this is the best I could do. Thanks @Laikoni for letting me know that we can also accept lists of digits as input. ``` import Data.List (g.length.last<*>maximum.concat.init).group g b a=any(==a)$(^b)<$>[1..a] ``` ### Explanation: ![](https://i.stack.imgur.com/tHLV7.jpg) [Try it online!](https://tio.run/##fZHNToQwEMfvPMUcOLQGGopdRbP05NE3IJgMaxca@Qp0oz49UlhAV9dpOpl2fvOfaVpg/6bKchh01TadgSc0yJ51b5xjTHJWqjo3BSuxN/sbWeGHrk4VOzT1AQ3TtTaU5V1zap0cMsAY608Sx0hd8pLRvSsTzhimQ4W6hhjaTtcGXDjCmAIgpFP4yshjklqWsr5o3umUSwSPgjAIAo/bHd6K3d19FHlix2fz7JWw2y4hRsYT/GGqSR3fh9kWGfhpfCPm8z/E2vyCCFZiHeoP4mLMqxpL2/D6pMvzfmlYRIEvAa3LrCPKl0iXKKMAIzN@oEXJjJ2zU923eGHdmd10piq1lapzsxGSMqbDFw "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org/), 80 bytes ``` function(x)any((0:(m=max((d=rle(rev(utf8ToInt(c(x,''))-48)))$v[-1])))^d$l[1]==m) ``` [Try it online!](https://tio.run/##LYzBCoMwEETv/Q7BWaiQ2LWNhXxA772JBVEDBRNBoqRfnzbVXYbZYR67RKOjWV3v37NDoM59AHGH1bYLwKCXacQybli9Uc/54Tx6hHOeExWsiCjbmkK2v@M1ZFMjW60tRQOWSpRCCDoZyMPKC1fXm1IpcCX3SSEVnJSWeYf/lKyPL/EL "R – Try It Online") Uses `utf8ToInt - 48` to split the number into digits. This throws a warning from the conversion to a string. Using rle get the count of the trailing digits and the max value of the first digits. Return true if the any of the range 0 to max value to the power of trailing count equals max value. I think there are further golfing opportunities, but that can wait until tomorrow. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ŒgµṪL9*€fṀL ``` Takes input as a list of digits. [Try it online!](https://tio.run/##y0rNyan8///opPRDWx/uXOVjqfWoaU3aw50NPv@P7nE53A7kqbj//29iaGFgZGBgoKNgCCaMjE1MzcwtLHQUTEwNIUBHASRoAsIgaGICUgaUN7QE6wQA "Jelly – Try It Online") ### How it works ``` ŒgµṪL9*€fṀL Main link. Argument: D (digit array) Œg Group runs of digits, yielding a run array R. µ Begin a new chain with argument D. Ṫ Tail; remove and yield the last element of D. L Take the length. Let's call it b. 9*€ Compute [1**b, ..., 9**b]. Ṁ Take the maximum run in R, yileding [a, ..., a]. f Filter, yielding either [a] (if a = n**b for some n) or []. L Take the length. ``` [Answer] # R, 66 bytes This answer is more or less a medley of [MickyT](https://codegolf.stackexchange.com/a/150989/6741) and [NofP](https://codegolf.stackexchange.com/a/150980/6741)'s answers, and on their request, here it is: ``` function(x,R=rle(rev(utf8ToInt(x)-48)))!max(R$v[-1])^(1/R$l[1])%%1 ``` It takes x as a string. ``` > f=function(x,R=rle(rev(utf8ToInt(x)-48)))!max(R$v[-1])^(1/R$l[1])%%1 > f("41802000") [1] TRUE > f("100") [1] TRUE > f("123456788") [1] FALSE > f("451111111") [1] FALSE > f("234543454545444") [1] FALSE > f("12") [1] TRUE > f("41902000") [1] FALSE ``` [Answer] # JavaScript (ES7), 66 bytes Takes input as either a string or an array of characters. Returns a boolean. ``` f=([c,...s],m)=>s.some(n=>n-c)?f(s,c<m?m:c):!(m**(1/-~s.length)%1) ``` ### Test cases ``` f=([c,...s],m)=>s.some(n=>n-c)?f(s,c<m?m:c):!(m**(1/-~s.length)%1) console.log(f( '41802000')) // 1 console.log(f( '100')) // 1 console.log(f( '123456788')) // 0 console.log(f( '451111111')) // 0 console.log(f('234543454545444')) // 0 console.log(f( '12')) // 1 ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~130~~ ~~128~~ ~~118~~ 93 bytes ``` import StdEnv @l#(b,a)=span((==)(last l))(reverse l) =or[n^length b==last(sort a)\\n<-[0..9]] ``` Defines the function `@`, taking a list of integer digits. [Try it online!](https://tio.run/##TZDBasMwDIbveQqRXhxo2qRLt3TU0MN2KOyWY5KBG3upwZFDrBb28svsZofZSPow/y8Jd0YJnAcrb0bBIDTOehjtRFCRfMd7dDIrdlmLhLtRIGOcJ8wIR2CShE3qrianPEfcTjV@GoU9XeHCedAwF/qIpGnwmNbZZnNo27kiMVG00jjeyAGHOi7yMttlWRav43zJu6di//xSlp6Lfb4cz@G5CBFuUTyUQZIfFn8bbbfQWfRLEZAFqXvtF9WO3P@BNdkzEjCyFU0ae5AJNA1IOKavoNvA2jMsjkdTuioEaUP14T0R9381wulPNP90X0b0bk7PH/PbN4pBd@4X "Clean – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~95~~ 78 bytes * Saved seventeen bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod). ``` def f(s,i=~0): while s[i]==s[~0]:i-=1 return int(max(s[:-~i]))**(1./~i)%1==0 ``` [Try it online!](https://tio.run/##bY/BCoMwDIbP9imKMLAyXdPVzQl9hb2AeBBWsbC10jq2XfrqTpExh0vIJd@f/En36luj2TBcZIObyG2V8JQUKHi06iqxK1UlhCs9rQqVCECBlf3daqx0H93qZ@TKIvGqIiSOI0h3XpENCEGH2jlp@3FjyCGnjFIaEiwEBvQl8LfJ9jw7HPN8RnSBeAZzrNE0xKeakvO1ANjaisNpcdmP@mMPqLPjqzg8GzxjZTSW1hrr0nB4Aw "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), 93 bytes ``` function(x){n=nchar(x) d=x%/%10^(n:1-1)%%10 i=max(which(d!=d[n])) max(d[1:i])^(1/(n-i))%%1>0} ``` [Try it online!](https://tio.run/##NYtNCsIwEIX3uYWLwMyidKZGkEK8SGmhJIRk4SihYkA8e0wW8njw8X5yDbaGl7gjPQQKfsSKi3tuqLwtetRMG8jMA6NurJK97wXeMbkI/mT9Iiui6plfeE4rbsAjyJCw72/0rc@c5IAA09lcTHeXMe31bwxfaSIixPoD "R – Try It Online") The code takes an integer as input and returns FALSE if the number is pleasing, and TRUE otherwise. [Answer] # [Python 3](https://docs.python.org/3/), ~~88~~ 85 bytes ``` def f(n):p=n.rstrip(n[-1]);a=int(max(p));b=len(n)-len(p);return round(a**(1/b))**b==a ``` ### Ungolfed: ``` def is_pleasing_number( n ): prefix = n.rstrip(n[-1]) a = int(max(prefix)) b = len(n) - len(prefix) return round(a ** (1 / b)) ** b == a ``` * The input argument is expected to be a digit string * The output is either `True` or `False`. * Similar to yet developed independently of [Halvard’s answer](/a/150947/68800) but uses floating point arithmetic in a way that doesn't suffer from rounding errors until `a ** (1 / b)` is off by at least 0.5 from b√a which requires a value above 253 (or whatever floating point radix and mantissa length Python happens to use, see `sys.float_info`). * Can be modified trivially to still work with arbitrary number bases between 2 and 36. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~144~~ ~~126~~ 117 bytes * Saved eighteen bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). * Saved nine bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` j,k,m;f(char*N){N+=j=strlen(N);k=~j;for(j=-1;m=N[j--]==N[j];);for(;k++<j;)m=fmax(N[k],m);j=!fmod(pow(m-48,1./~j),1);} ``` [Try it online!](https://tio.run/##jY9RTsMwDIaf4RSl0qSEJpCUDIqMr5ALjD5UKRlL63bqJoE0bUcnLCDxBsWWZVn@/l@2k2vnYgyiEwSeuddmurb8YAsMuNtP/cvALIcOTwH8OLGAUgOhXQUpa0y9Bv61ga4ongJwQk/NO7OrrhbEIeCVp7Fl2/GNkTSV0De3p8CF5nCM1GwGxg@XF9tpM@w9yxdthpgt2uchF@fR6EqVSqmci@ws@JXT/0DKO7O8f6iqBKo/QLPU3zEHJkOTKqUxc7gu5040@vHn2@R0jB/O9816F2VPnw "C (gcc) – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 106 bytes ``` fun String.p()=split(Regex("(?=(.)\\1*$)")).let{Math.pow((it[0].max()?:'0')-'0'+.0,1.0/(it.size-1))}%1==.0 ``` Output: true/false [Try it online!](https://tio.run/##bU5dr8FAEH3vr2gaYsbHmGVRosQP8MIjHvahaqNW0@7NdYnfXt14cIOZzGRyTuacczzbVJuy3P8Yf21zbRLKAKMiS7WFVZzEFwhgHgHhdiuaNQwQKY3tbansgbLzL4C2G97RSV0A55MGN7BTrRZxWxB3K5YKfY07AvFeF1FE7HnO66S0AZUnxcRf5Ln6mz7NZ@jfvKy6bGogkCLkHjMHLhO@cPEF6vXlYDgKw3dCDsSz3gn3IN24lvJT8ENJjP@nuZflAw "Kotlin – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~26~~ 18 bytes ``` ó¶ o l ñ o n qV v1 ``` [Try it online!](https://tio.run/##y0osKPn///DmQ9u48hVyuA5vVMhXyFMoDFMoM/z/X8nE0MLAyMDAQAkA) --- Takes input as a string, returns `1` for pleasing numbers, `0` otherwise. Short explanation: ``` ó¶ ``` Take the first input and split it by values where `(x,y) => x===y` is true. For example `'41802000'` to `['4','1','8','0','2','000']`. ``` o l ``` Take the array from the first step, remove the last element and get its length, yielding **B**. ``` ñ o n qV v1 ``` Find the largest element in the remaining array, yielding **A**, take it to the power `1/B` and then return if the result is divisible by one. --- First time working with Japt, very open to any recommendations. Shaved off 8 bytes thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). [Answer] # [Ruby](https://www.ruby-lang.org/), 64 bytes ``` ->a{!([a[/(\d)\1*$/].size,$`.chars.max]*?x!~/x1$|^2x[49]|^3x8/)} ``` Input as a string, returns true if: * B==1 (no need to check A) * A==4 and B==2 * A==9 and B==2 * A==8 and B==3 [Try it online!](https://tio.run/##JYxLDoIwFACvItgFkNofRetCPUh5xPohujAhEJOnbb16xTiZ2c74PL1Sv0urvfNZYZ3lRXspW1kRDmy6v6@UHNn55saJPRxCdcDsw1GS0Cm0eguhq9HwMiarpRFKCEHlLzVb62a9MYbqRv6B@TH4gGFYWKS9zZceYw4Q0xc "Ruby – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 55 bytes ``` {m/(\d+?)((\d)$0*)$/;so any(^10)**$1.comb==$0.comb.max} ``` [Try it online!](https://tio.run/##JUtbDoIwELzKhjSmrQns4oIoohcxmvrolxUDPzaEs9cWZzKPbHY@z@FVB@dhZaELkyvk@bE@KRlDCdRKFO3Yg3l7eSFUWgvK7727dZ3ApeTOfOfQwmg8ZJMFcZ330TKw/QAHpgZLRARKKjdc1dumAa7oD0gnTkpkjj/AtFs2xzb8AA "Perl 6 – Try It Online") After the evaluation of the initial regex--which can only succeed if the input is a positive integer--`$0` contains the initial part of the number, and `$1` contains the trailing repeated digits. The `comb` method without arguments, applied to a string, returns a list of the characters, which in numeric context evaluates to the length of the list. So `$0.comb.max` is the largest of the digits in the prefix, and `$1.comb` is the length of the suffix. We then check whether `any(^10)` (ie, the or-junction of the numbers from 0-9), when raised to the power of the length of the suffix, is equal to the largest digit in the prefix. The `so` forces boolean evaluation of the resulting junction, which would otherwise be just fine on its own as a truthy value, but the challenge calls for just two distinct values to be returned. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 21 bytes ``` L,BGubLV@¦+bMG1$/^1%! ``` [Try it online!](https://tio.run/##S0xJKSj4/99Hx8m9NMknzOHQMu0kX3dDFf04Q1XF/yo5iblJKYkKhnb2XP5cRPP@/482UTBUsFAwUDACYiCM/R9tpGCsYKJgCsQwGoaBEChvqGAUC9JnCtSJBGMB "Add++ – Try It Online") It's been 3 and a half months, I hope I'm not ninja'ing anyone. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 132 bytes ``` n=>{int A=0,B=1,s=1,i=n.Length-1;for(;i-->0;)if(n[i]==n[i+1]&s>0)B++;else{A=n[i]>A?n[i]:A;s=0;}return System.Math.Pow(A,1d/B)%1==0;} ``` [Try it online!](https://tio.run/##lZBBS8QwEIXP9lfkojR0Wpu16mpMpRU87ULBg4fSQ@1mdwM1gSZ1kdLfXlOxIp5aHm8GMvOYj1Tar1TDh1YLeUAvn9rwd@pUdak1yjpHm9KICj23snoQ0uQFoDel6hhlNS@/IwwNksWdHaKEhZAyAtpaMBlsuDyYo0/oXjUuFb4fhxSLvStzUTBmq0eKCx2HOPU8ymvNu2R8LeLkcWz3CdUspH3DTdvIH7ZgW5pjkKmTmwDZXab4nLBxaaDOBPuhxA5tSyFd7HTO2ZOSWtU8eG2E4RshuTuxu5Kf8gJ1KAICawhhZW2FeozprCBZur6CK4jgGm7g1l5cz4@OIfJX86PTzei3T7ZaBL8El8Dd/x/tnX74Ag "C# (.NET Core) – Try It Online") ### Acknowledgements -12 bytes thanks to @KevinCruijssen ### DeGolfed ``` n=>{ int A=0, // maximum digit B=1, // count of trailing identical numbers s=1, // 1 if dealing with trailing numbers, 0 otherwise i=n.Length-1; for(; i-- > 0;) if(n[i] == n[i+1] & s > 0) B++; else { A = n[i] > A? n[i] : A; s = 0; } return Math.Pow(A, 1d/B) % 1 == 0; } ``` [Answer] ## Clojure, 168 bytes ``` (fn[x](let[y(reverse(vec x))z(count(take-while #(= %(first y))y))a(apply max(map #(-(int %)48)(drop z y)))b(Math/pow a(/ 1 z))](<(Math/abs(- b(Math/round b)))0.00001))) ``` [Try it online!](https://tio.run/##1VRRbsIwDP3fKSwQ0vNHoWFhFAmOsBMgPtISRFloozQtbS/fpWI7RJ5jyYmeEz/FcmHqR@v0NMG6svKmIuBWnfsLjPbnAU532jUanS6oZx5R1G3l4dWPTl730mha4kQr3ErXeBqYw1JQ1pqBnqrHU9nASBDuphXLjHF1taVxpnKOb@XvG1u/SGFDgkbmC47vU5U3SOiP4sKrV8pDTrpOA0SIaCFFlm7DbsH8EWP9IuLSt59y97XPslgFyJ14I1YB8wfI2WeTMt5GiraDxOF/@kzTLw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes ``` ≔ESιθ⊞υ⊟θW⁼§υ⁰§θ±¹⊞υ⊟θ¬﹪XI⌈θ∕¹Lυ¹ ``` [Try it online!](https://tio.run/##ZY2xCsMgEIb3PoXjCRZM6VDIFNoOgSYIfQJpJBGMxqhJ3t6eQ6ce3HAf/33/Z5Lrx0mTcxOCHi10coHWLim@46rtCJQRjetpfRIpTJAYEW4BTxHskzaKwNMnaQI0sbWDOkqC48fv9Iz0apRRQUVxyJ9FYE@E3kXo3JCMA@F2tcJdBiTy0HOaS5CRh970gBpGXsqOES204KKtc75WN37hnOfzZr4 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a `-` for pleasing numbers. Explanation: ``` ≔ESιθ ``` Split the input `q` into characters. ``` ⊞υ⊟θ ``` Remove the last character from `q` and push it to `u` (predefined to an empty list). ``` W⁼§υ⁰§θ±¹⊞υ⊟θ ``` Repeatly pop and push while the last character of `q` is the first character of `u`. ``` ¬﹪XI⌈θ∕¹Lυ¹ ``` Take the maximum digit of `q` and raise it to the power of the reciprocal of the length of `u`, then check whether the result is an integer. [Answer] # [Python 2](https://docs.python.org/2/), ~~91~~ 85 bytes ``` s=`input()`;d=0 p=s.rstrip(s[-1]) exec"`d**(len(s)-len(p))`==max(p)>exit(1);d+=1;"*10 ``` [Try it online!](https://tio.run/##FcbBCsIwDADQ@z5jp6QySYaHQYk/IkJlLazgalgq1K@venpPP3V7lbl3k5CLvitg8FFoULHzYfXICnab@I5DamkdQ3QOnqmA4fRHEYPI/mi/XVPLFRh9PAn70TH1fuGFZiL6Ag "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 73 + 1 (`-p`) = 74 bytes ``` s/(.)\1*$//;$/=length$&;$_=(sort/./g)[-1];$q=$"++**$/while$q<$a;$_=$q==$a ``` [Try it online!](https://tio.run/##FcpNCoUgFAbQvTw@Hv2gVweNzCW0gopoIBVIWgrtvluNz4nu9A1zokKWg65AZEDWu33JK/4Gky1SODNJWspe6NHgsPjVdfXWa928w9Fi/t4LFjOzVuoOMW9hTyy6RiqtWMQH "Perl 5 – Try It Online") [Answer] # Java 8, 125 bytes ``` a->{int A=0,B=1,f=1,i=a.length-1;for(;i-->0;)if(a[i]==a[i+1]&f>0)B++;else{A=a[i]>A?a[i]:A;f=0;}return Math.pow(A,1d/B)%1==0;} ``` Port of [*@Ayb4btu*'s C# .NET answer](https://codegolf.stackexchange.com/a/152068/52210). [Try it online.](https://tio.run/##lVDBbsIwDL33K3zZlAq3axjb2KJ0Kvdx4Yh6CCWFsJKiNoCmqt/euTCmSbuArGcrtp/8XjbqoILN8rPLClXX8KGMbTwAY52ucpVpmPZPgEVZFlpZyBiN5ikoX1C/9SjVTjmTwRQsSOhUEDe0AomMcCI55gQjVVhou3LrgIu8rJgwQRBHwjc5U3OTSkl5wNP7PI78yWAgdFHrJum7aZy89@UtEbmMRFtpt68s6XTrcFceWYJ8@TDx77jsp53oBe32i4IE/eg6lGYJW/LFZq4ydjVPlX/2NPuqnd6G5d6FO5q4wjIbZszqI5xMNiPkOMYIhwSK1j@ZvoLIb10f4iOO8Amf8YUujq@n9iT@N66nXm6OfusFFDeJv0Uux9d/P9p6bfcN) **Explanation:** ``` a->{ // Method with digit-array parameter and boolean return-type int A=0, // Maximum digit `A` as specified in the challenge description B=1, // `B` as specified in the challenge description f=1, // Flag-integer, starting at 1 i=a.length-1; // Index integer `i` for(;i-->0;) // Loop `i` backwards over the digits (excluding the last) if(a[i]==a[i+1] // If the current and next digits are the same, &f>0) // and the flag is still 1 B++; // Increase `B` by 1 else{ // Else: A=a[i]>A? // If the current digit is larger than `A` a[i] // Replace `A` with the current digit : // Else: A; // Leave `A` the same f=0;} // Set the flag-integer to 0 return Math.pow(A,1d/B) // Return if `A` ^ (1/`B`) %1==0;} // is an exact integer ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~32~~ ~~22~~ 21 bytes ``` '.N(#a-#Ya<|a@v)RTMXy ``` Uses `1` for *falsey* and `0` for *truthy*, saving a byte. [Try it online!](https://tio.run/##K8gs@P9fXc9PQzlRVzky0aYm0aFMMyjEN6Ly////JoYWBkYGBgYA "Pip – Try It Online") [Answer] ## Pyth, 29 bytes ``` JezWqezJ=Pz=hZ)[[email protected]](/cdn-cgi/l/email-protection) ``` [**Test suite**](https://pyth.herokuapp.com/?code=JezWqezJ%3DPz%3DhZ%29K%40sh.MsZzZqKsK&test_suite=1&test_suite_input=41802000%0A100%0A123456788%0A451111111%0A234543454545444%0A12%0A41902000&debug=0) Python 3 translation: ``` Z=0 z=input() J=z[-1] while z[-1]==J: z=z[:-1] Z+=1 K=max(map(int,z))**(1/Z) print(K==int(K)) ``` ]
[Question] [ I came across [this question on SO](https://stackoverflow.com/questions/8886475/simple-way-to-compare-a-character-in-a-position-in-a-line-to-rest-of-lines-at-sa) and thought it'd make a nice golf challenge. So here it is: ### Challenge: Write a program that reads a sequence of character strings, one per line, and outputs a list of all positions where each string has the same character. ### Input and output: The input consists of one or more lines of printable non-whitespace ASCII characters, each followed by a newline. You *may* assume that all input lines have the same length. The newline is *not* to be considered part of the input (i.e. you should not output it as a matching character). Example input (shamelessly stolen from the SO question): ``` abcdefg avcddeg acbdeeg ``` After reading the input, your program should print the positions of each matching column and the characters they contain. (Your program may, but need not, stop reading further input if it can determine early that there are no matching columns.) Any reasonable output format is permitted; in particular, you may use either 0-based or 1-based indexing for the positions. Example output for the above input (using 0-based indexing): ``` 0: a 3: d 6: g ``` ### Scoring: This is code golf, so shortest answer wins. In the event of a tie, fractional tie-breaker chars may be awarded for additional features: * −½ chars for correctly handling input lines of unequal length. (Output should not contain positions past the end of the shortest input line.) * −¼ chars for correctly handling input consisting of arbitrary UTF-8 encoded Unicode characters. For inspiration, you may find some ungolfed solutions at the SO question (see above). ### Clarifications: * Simply concatenating the positions and characters, as in `0a3d6g`, does *not* count as "reasonable output". You should provide some kind of separator (such as a space) between each element of the output so that it can be parsed unambiguously. * The input will be provided on the standard input stream (`stdin`), or using whatever text file input mechanism is most natural to your language of choice. (If your chosen language doesn't *have* a natural mechanism for file input, do whatever seems closest in spirit.) * The input ends when there is no more data to be read (i.e. when an end-of-file condition occurs). If you wish, you *may* require that the input be terminated by a blank line (which you then should not count as part of the input, obviously). If you do so, please mention it in your answer so that others can provide correct input for testing. * Every input line, *including* the last one, ends with a newline character. Your answer must not report this newline as a matching column. (It's fine if your solution can also handle input where the last line doesn't end in a newline, but that's not required.) [Answer] ## APL, 25 characters ``` ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞ ``` I used Dyalog APL (version 13) as my interpreter. It handles both inputs of unequal length and Unicode (UTF-8) characters. Examples: ``` ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞ abcdefg avcddeg acbdeeg 1 a 4 d 7 g ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞ test日本 blat日本国foo 4 t 5 日 6 本 ``` Explanation, somewhat from right to left: * The main chunk of this answer is the direct function (basically, anonymous function), defined within the curly braces. Its right argument is specified by `⍵`. + `0=⍴⍵:⍬` is our first expression, and it checks if we've gotten an empty line (i.e., we are done). It uses a guard (a familiar construct to many functional programmers) to conditionally execute the expression to the right of the colon. In this case, if 0 is equal to the shape/length (`⍴`) of the right argument, we return the empty set (`⍬`). + `⋄` separates the two expressions within the function. If the previous expression didn't get evaluated (and thus didn't return anything), we move to the next expression. + We recursively call the function using the self-reference function (`∇`). The argument to the function is a line of non-evaluated user input, given by quote-quad (`⍞`). + `⊂⍵,⍨¨⍳⍴⍵` creates pairs for each character in the string, where each pair's first element is its position in the string, and its second element is the character. + `⍳⍴⍵` gives a vector from 1 to `⍴⍵`, or the length of the input string. + `⍵,⍨¨` applies the commuted concatenation function (`,⍨`) to each (`¨`) element to its left (`⍵`, in this case the user's input) and right. Commuting the concatenation function causes its left and right arguments to be swapped. + Finally, we enclose the result using `⊂`, so that we can differentiate between lines of input. * We initially feed our function with user input (`⍞`). * Finally, we reduce (`/`) our resulting vector of vectors of pairs using the intersection function (`∩`), yielding the pairs that are found in all of the sub-vectors. [Answer] ## Golfscript (28 chars) ``` n/zip:^,,{.^=.&.,1>{;;}*}%n* ``` There are character set issues when piping Unicode through, so no quarter-point bonus. [Answer] ## J, 57 51 44 40 characters ``` ,.&.>y;y{{.z[y=.I.*/2=/\]z=.];._2]1!:1]3 ``` I'm getting there slowly but surely. This is still far from ideal though I think. I felt sure that using a hook would be the answer but unfortunately not (44 chars): ``` ,.&.>((];({{.)~)([:I.[:*/2=/\]))];._2]1!:1]3 ``` I may need a completely different method to get any shorter. [Answer] ## Python 2, score 81.5 (116 94 86 83 82 bytes minus bonus) ``` import sys i=0 for x in zip(*sys.stdin)[:-1]: i+=1 if len(set(x))<2:print i,x[0] ``` [Answer] ## Haskell, 64 characters ``` main=interact$show.foldl1(filter.flip elem).map(zip[0..]).lines ``` Handles lines of unequal length. Unicode support depends on the current locale settings. **Example output:** ``` [(0,'a'),(3,'d'),(6,'g')] ``` [Answer] ## (Bash) Shell Scripting, 105 characters If anyone has some more tricks for this, please fill free to comment! ``` for((i=1;i<`tail -1 $1|wc -c`;i++))do x="cut -c$i $1";y=`$x`;[ `$x|uniq|wc -l` = 1 ]&& echo $i ${y:3};done ``` Result: ``` 1 a 4 d 7 g ``` [Answer] ## Perl, 87 characters (−½ char tie-break bonus) Here's a golfed version of [my own solution from the SO thread](https://stackoverflow.com/a/8887504): ``` chomp($a=$b=<>);$a&=$_,$b|=$_ for<>;@$_=$$_=~/./sgfor a,b;$b[$i++]eq$_&&say"$i:$_"for@a ``` Unlike the SO version, this one uses 1-based indexes for the output. It uses the Perl 5.10 `say` feature, so needs to be run with `perl -M5.010` (or with `perl -E`). Like the SO version, this code handles variable-length lines, and *would* handle arbitrary Unicode input if the standard input and output were in UTF-8 mode. Alas, by default they're not, unless one specifies the [non-free](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions) `-CS` command line switch. Thus, it earns the −½ char bonus, but not the −¼ one. **Edit:** +1 char to fix a bug: just because the input strings don't contain line feeds doesn't mean they can't end up in `$a` (e.g. `"+" & "J" eq "\n"`). [Answer] ## T-SQL ``` SELECT N.number, letter = MIN(SUBSTRING(L.line, N.number, 1)) FROM Lines AS L INNER JOIN master.dbo.spt_values AS N ON N.type = 'P' WHERE N.number BETWEEN 1 AND (SELECT MAX(LEN(L2.line)) FROM Lines AS L2) GROUP BY N.number HAVING COUNT(DISTINCT SUBSTRING(L.line, N.number, 1)) = 1 ORDER BY N.number ``` [Answer] # Q, 32 ``` {a!((*:)x)a:(&)1=(#:')(?:')(+)x} ``` usage ``` q){a!((*:)x)a:(&)1=(#:')(?:')(+)x}[("abcdefg";"avcddeg";"acbdeeg")] 0| a 3| d 6| g ``` # K, 22 The above solution can be reduced to 22 by writing it completely in K rather than passing K functions to a Q interpreter, reducing the number of parentheses required. ``` {a!@[*x]a:&1=#:'?:'+x} ``` [Answer] ### Scala 115107: (−¼ for handling UTF-8) ``` io.Source.stdin.getLines.map(_.zipWithIndex).toList.flatten.groupBy(_._2).map(_._2.toSet).filter(_.size==1) ``` ungolfed, and `Source.fromFile ("f")` instead of `stdin` for better testability: ``` io.Source.fromFile ("f"). getLines.map (_.zipWithIndex). toList.flatten.groupBy (_._2). map (_._2.toSet). filter (_.size==1) ``` Result: ``` List(Set((a,0)), Set((g,6)), Set((d,3))) ``` Thanks to Gareth for the reduction of size 8 for using `stdin`. [Answer] ## VBA (307.25 284 - 0.75 bonus = 283.25) I know this has already been won, but here's my shot (not reading a file, just a string - needs to have the io added). I like that I got to use `l()` recursively. I usually don't have a need for recursion my real-life programming. I only did so much testing, but I believe this covers the unicode bonus point stipulation. It also assumes `vbCr` is the line terminator. This may not translate to all systems because of that. **Code:** ``` Function a(i) b=Split(Left(i,Len(i)-1),vbCr):c=UBound(b):For q=1 To Len(b(c)):d=Mid(b(c),q,1):If l(b,c,q,d) Then a=a & q & ": " & d & vbCr:Next End Function Function l(m, n, o, p) If n+1 Then l=IIf(o<=Len(m(n)),Mid(m(n),o,1)=p,0) And l(m,n-1,o,p) Else l=Mid(m(n+1),o,1)=p End Function ``` --- **Example input/output:** ``` Debug.Print a("abcdefghijklmnop" & vbCr & "abcdefg" & vbCr & "abcabcghijkl" & vbCr) ``` --- ``` 1: a 2: b 3: c 7: g ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), score: \$9\frac{1}{4}\$ (10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - \$\frac{3}{4}\$ for both bonuses) ``` |ø€Ù₸ʒнg ``` Outputs with 1-based indexing. [Try it online.](https://tio.run/##MzBNTDJM/f@/5vCOR01rDs880vioYdbhHacmXdib/v9/SWpxybPpS5/NWVOcn5uqkJtflMqVlJpaABHLSC1KVUgsVihPzcl5OnsvbhkA) Uses the legacy version, because `ø` worked with a list of strings whereas the new version would need an explicit `€S` to convert each inner string to a list of characters first. It does mean I can't use the builtin `.ā` of the new version though, which pairs each item with its 0-based index. As alternative I use `₸` to pair with its 1-based index. In the [new 05AB1E version](https://github.com/Adriandmen/05AB1E/wiki/Commands) this would therefore have been **11 bytes**: `|€Sø€Ù.āʒнg` - [Try it online](https://tio.run/##yy9OTMpM/f@/5lHTmuDDO4Dk4Zl6RxpPTbqwN/3//5LU4pJn05c@m7OmOD83VSE3vyiVKyk1tQAilpFalKqQWKxQnpqT83T2XtwyAA) (with 0-based indexing instead). **Explanation:** ``` | # Push all input-lines as a list ø # Zip/transpose; swapping rows/columns, # which implicitly discards any trailing characters for the 1/2 bonus €Ù # Uniquify each inner string/character-list ā # Push a list in the range [1, length] (without popping the list of strings) ‚ # Pair it with the list of strings ø # Zip/transpose again, which pairs each string with its 1-based index ʒ # Filter this list of string-index pairs by: н # Where the first item (the string) g # Has a length equal to 1 (note: only 1 is truthy in 05AB1E) # (after which the result is output implicitly) ``` [Answer] ## PHP, 123 127 :( I'm not happy with it (there's bound to be improvements to be had), but here goes: ``` <?$a=$b=trim(fgets(STDIN));while($l=fgets(STDIN)){$a&=$l;$b|=$l;}$n=-1;while(@$a[++$n]){echo$a[$n]!=$b[$n]?'':"$n:{$a[$n]}\n";} ``` [Proof it works.](http://ideone.com/wxSJr) If anyone can think of a more clever way of initializing $a and $b, please let me know. Originally I had `$a=$b=$n=''` and $b eventually was correct, but `[empty] & [anything] == [empty]`, so $a never had content. --- Edit: Had to fix newline handling (+6) but dropped closing tag (-2). [Answer] ## JavaScript (125 134 140) ``` for(i=s=[];I=s[++i]=prompt(o='');S=I);for(c=-1;w=r=++c<S.length;o+=r?c+':'+C+'\n':'')for(C=S[c];w<i;)r&=s[w++][c]==C;alert(o) ``` Demo: <http://jsfiddle.net/Fv7kY/4/> **Edit 1**: Rearrange loops to avoid braces. Initialize i with `[]` to combine with `s`. Move `w` increment into expression. **Edit 2**: Set `S=I` to capture last entered word and save using `s[1]`. Combine `r=1` and `++c<S.length`. Set `C=s[c]` in inner loop and compare to `C` instead of previous and next words to shorten expression `s[w][c]==s[w++][c]` to just `s[w++][c]==C`. Saved a total of 9 characters. Also set `w=r=...` because when that's true `w=1` which is what we need to initialize `w` with. [Answer] # Ruby (71) ``` a,*s=*$<.lines (a.size-1).times{|i|s.all?{|t|t[i]==a[i]}&&p([i,a[i]])} ``` output: ``` [0, "a"] [3, "d"] [6, "g"] ``` [Answer] ## Common Lisp, 183 165 characters ``` (let((l(loop for m =(read-line)until(equal m "")collect m)))(loop for c across(car l)for i from 0 if(null(remove c(mapcar(lambda(y)(char y i))l)))collect(list i c))) ``` Readable format: ``` (let ((l (loop for m = (read-line) until (equal m "") collect m))) (loop for c across (car l) for i from 0 if (null (remove c (mapcar (lambda(y) (char y i))l))) collect(list i c))) ``` Enter this directly into the REPL and enter lines, terminating with an empty line. [Answer] ## C, 126 chars ``` char a[999],b[999];main(i){for(gets(a);gets(b);)for(i=0;b[i];++i)a[i]^b[i]?a[i]=0:0; while(i--)a[i]&&printf("%d:%c\n",i,a[i]);} ``` I've been staring at this but I just can't make it smaller. A new approach may be needed. (No bonus points; it only handles differently-sized lines if the first line is the shorter one.) [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 16 bytes ``` ln)XXtpzif{[~sm} ``` [Try it online!](https://tio.run/##SyotykktLixN/f8/J08zIqKkoCozrTq6rji39v//xKTklNS0dK7EsuSUlFQgnZyUkpqaDgA "Burlesque – Try It Online") ``` ln # Split to lines )XX # Split each line to chars tp # Transpose zi # Zip with indices f{ # Filter for [~ # Tail (i.e. chars) sm # All the same } ``` [Answer] # T-SQL, 134 bytes This can handle input lines of unequal length Using 0-based indexing ``` SELECT n,max(z)FROM(SELECT substring(x,number+1,1)z,abs(number)n,*FROM spt_values,@)t GROUP BY n HAVING max(z)=min(z)and n<max(len(x)) ``` **[Try it online](https://rextester.com/BPHX15145)** [Answer] ## [JavaScript (Node.js)](https://nodejs.org), 67 bytes (Anonymous function) ``` a=>[...a[0]].reduce((p,c,i)=>p+(a.every(s=>s[i]==c)?i+c+" ":""),"") ``` [Try it online!](https://tio.run/##JcZBCgIhFADQ/Zwi/krRpHWgHURcmH7NGkZRm/L0NtDiwXva3TZXU@nnLXucQU4rlRZCWH0xRlT0b4eEFO54olIVRqzAHesgTaqmk5HS0VtijsEJrgCUH6bLW8srijVHEohewPoQH1g78OOvFPv9838fMY1vh8VQOn8 "JavaScript (Node.js) – Try It Online") Input as array of lines, output in form `"0a 2g 5p "` etc [Answer] # C# with .NET 4 (280) ``` using c=System.Console;class P{static void Main(){char[]a=c.ReadLine().ToCharArray();int r,i,l=a.Length;m:i=0;n:r=c.Read();if(r>0&&r!=10&&r!=13){if((int)a[i]!=r)a[i]='\0';i++;goto n;}for(;i>0&&i<l;)a[i++]='\0';if(r>0)goto m;for(i=0;i<l;i++)if(a[i]!='\0')c.WriteLine(i+":"+a[i]);}} ``` * 1 line, 280 characters * Includes all necessary using statements and Main method. * Program **does not require** an empty line at the end, but will accept it * Empty lines are ignored * Handles input strings of any length. * Reserves output until the end (whereas the original answer provided incremental output) ### Readable version ``` char[]a=c.ReadLine().ToCharArray(); int r,i,l=a.Length; m: i=0; n: r=c.Read(); if(r>0&&r!=10&&r!=13){ if((int)a[i]!=r) a[i]='\0'; i++; goto n; } for(;i>0&&i<l;) a[i++]='\0'; if(r>0) goto m; for(i=0;i<l;i++) if(a[i]!='\0') c.WriteLine(i+":"+a[i]); ``` --- ### Original answer ~~using c=System.Console;class P{static void Main(){char[]a;var b=c.ReadLine();a=b.ToCharArray();while(b!=""){for(int i=0;i * 1 line * 207 characters * Includes all necessary using statements and Main method. * Program ends when an empty line is entered. * Does not handle input strings that are shorter than the first. --- Readable version: ``` static void Readable() { char[]a; string b=System.Console.ReadLine(); a=b.ToCharArray(); while(b.Length>0) { for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { a[i] = '\0'; } else { System.Console.WriteLine(i+": "+a[i]); } } b=System.Console.ReadLine(); } } ```~~ [Answer] **python 122 characters**: ``` print("\n".join([str(i)+':'+str(x[0]) for i,x in enumerate(zip(*[tuple(x) for x in input().split()])) if len(set(x))<2])) ``` [Answer] ## Ruby (242) ``` s = %w{ abcdefg avcddeg acbdeeg aejdjeggd } cols = [] s.sort{ |a, b| b.size <=> a.size }[0].size.times do |i| uneq=true l = s[0][i] s.each { |w| uneq = false if l != w[i] } cols << [l, i] if uneq end cols.each { |c| puts c.join('|') } ``` [Answer] ## C# ``` List<string> strings = new List<string> { "abcdefg", "avcddeg", "acbdeeg", "aejdjeggd" }; var transposes = from index in Enumerable.Range(0, strings.First().Length) select new string((from s in strings select s[index]).ToArray()); int i = 0; foreach(string transpose in transposes) { if (transpose.Distinct().Count() == 1) Console.WriteLine("{0}: {1}", i , transpose[0]); i++; } ``` ]
[Question] [ Just because the [reverse](https://codegolf.stackexchange.com/q/193315/78410) and [palindrome](https://codegolf.stackexchange.com/q/221209/78410) were not too challenging individually :) Write a program (full program or function) that satisfies the following: given a string input, * the program *as-is* outputs the input string unchanged. * the program *reversed* outputs the input string reversed. * the program *palindromized* outputs the input string palindromized. * the program *reversed and then palindromized* outputs the input string reversed and then palindromized. In this challenge, *palindromize* is defined as "concatenate the reverse on the right" (`lambda s: s + s[::-1]` in Python). For example, if your code is `abc`, when given `"xyz"` as input, * `abc` should output `"xyz"`. * `cba` should output `"zyx"`. * `abccba` should output `"xyzzyx"`. * `cbaabc` should output `"zyxxyz"`. You may assume that the input string is nonempty and entirely consists of printable ASCII (32-126, no newlines). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ?R\ ``` * `?R\` - [Try it online.](https://tio.run/##yy9OTMpM/f/fPijm//@KyioA) * `\R?` - [.enilno ti yrT](https://tio.run/##yy9OTMpM/f8/Jsj@//@KyioA) * `?R\\R?` - [Try it online..enilno ti yrT](https://tio.run/##yy9OTMpM/f/fPigmJsj@//@KyioA) * `\R??R\` - [.enilno ti yrTTry it online.](https://tio.run/##yy9OTMpM/f8/JsjePijm//@KyioA) **Explanation:** ``` ? # Output the (implicit) input-string (without trailing newline) R # Reverse the (implicit) input-string \ # Discard it from the stack # (don't output anything implicitly, since we already had an explicit print) ``` ``` \ # No-op to discard the top of the stack R # Reverse the (implicit) input-string ? # Pop and output this reversed input # (don't output anything implicitly, since we already had an explicit print) ``` ``` ?R\ # Same as the first program above, outputting the input as is \R? # Same as the second program above, outputting the input reversed ``` ``` \R? # Outputs the input reversed ?R\ # Outputs the input as is ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes ``` θ⮌ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5///cjkfres53whkA "Charcoal – Try It Online") Reversed: ``` ω⮌θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9856N1Ped2/P9/bgeQcb4TAA "Charcoal – Try It Online") Palindromised: ``` θ⮌ωω⮌θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///cjkfres53nu8EUud2wPkA "Charcoal – Try It Online") Palindomised Reversed: ``` ω⮌θθ⮌ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9856N1Ped2nNsBpM53/v8PZQAA "Charcoal – Try It Online") Explanation: ``` θ ``` Print the input. ``` ⮌ω ``` Print the reverse of the empty string. Reversed explanation: ``` ω ``` Print the empty string. ``` ⮌θ ``` Print the reverse of the input. Palindromised and reversed palindromised follow trivially. [Answer] # JavaScript, 70 bytes ``` (x=>x.at?x:y=>y+z(y))//)y+)y(z>=y:``nioj.)(esrever.]x...[?ta.x>=x=z( ``` [Try it online!](https://tio.run/##XVDLbsIwELznK1b0wJqUjbhSOaivL@iRImGlBjmN7Mh2ohjEt6dOk6gqe/KMZ3dmtxStcIVVtV9r8yX7D2@VPlNtjTc@1JKEBw6nRhdeGQ3I4HqDLIOTKL5hFD8InySF0c6DM40t5H0DZKs@wY7nXZy267aB5yG9YGAsy1hIWcBLzsP2eNTKlMRQOitbaenQEdF@5wV1Oe/4BZN@lcGNvBmNkZGrK@Vx@amX8V2pQuLmEdYbRqVReuSf5nC20TGZA57DNYFYA20qSZU5o4u6e062ooofuHh@eX17X7Aouf1NGyK6Ydd9TDkufqCJxTnAr300xlEQ0QAm1YSmo6Xwn54NUph7@x8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python](https://www.python.org), 51 bytes *-2 bytes, thanks to tsh* *-2 bytes, thanks to Jakque* ``` s=input()#)]1-::[s=dne(tnirp print(end=s)#)(tupni=s ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYrUioIiWyUlpaWlJWm6FjeNi20z8wpKSzQ0lTVjDXWtrKKLbVPyUjVK8jKLCrgKijLzSjRS81Jsi4HyGiWlBXmZtsVQrROBpkQbWukaxnJxgc1QsFXIScxNSklUiAfaYKWgFBEZpcTFlVqRmqwBslYTap4mkli0FcgAbDLa-KUhMtoo5kIctmABhAYA) --- # [Python](https://www.python.org), 55 bytes ``` def f(s):# print(end=s)#)]1-::[s=dne(tnirp #:)s(f fed ``` *function accepting string as argument* [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYrUioIiWyUlpaWlJWm6FjfNU1LTFNI0ijWtlLkUCooy80o0UvNSbIs1lTVjDXWtrKKLbVPyUjVK8jKLChS4lK00izWA6lNToNqnAU2KNrTSNYzl4kqtSE3WABmvyZWmoRQRGaWkyQUxURMhF20FUoxPhTZxyiAqtLHbB3HdggUQGgA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` ₴Ḃ_ ``` [Try!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLigrThuIJfIiwiIiwiYWJjIl0=) [!yrT](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJf4biC4oK0IiwiIiwiYWJjIl0=) [Try!!yrT](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLigrThuIJfX+G4guKCtCIsIiIsImFiYyJd) [!yrTTry!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJf4biC4oK04oK04biCXyIsIiIsImFiYyJd) > > +1 very hard > > > You uh sure about that? ## Explained ``` ₴Ḃ_­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‏​⁢⁠⁡‌­ ₴ # ‎⁡Print without newline # ‎⁢The rest has no impact 💎 ``` ``` _Ḃ₴­⁡​‎⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌­ Ḃ₴ # ‎⁡Print the reverse of the input 💎 ``` ``` ₴Ḃ__Ḃ₴­⁡​‎‎⁡⁠⁡‏⁠⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­ ₴ # ‎⁡Print the normal input Ḃ₴ # ‎⁢Print the reverse 💎 ``` ``` _Ḃ₴₴Ḃ_­⁡​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌­ Ḃ₴ # ‎⁡Print reversed input ₴ # ‎⁢And then normal input 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [R](https://www.r-project.org), ~~92~~ ~~88~~ 86 bytes *Edit: -2 bytes thanks to [Jakque's comment](https://codegolf.stackexchange.com/questions/265514/i-revpal-the-source-code-you-revpal-the-input#comment579581_265522)* ``` x=utf8ToInt(scan(,''))#)))x(ver(8ftUoTtni(tac cat(intToUtf8(x))#))'',(nacs(tnIoT8ftu=x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nZGxasMwEIbpqsdwB9-BDKWTofUDZHcyZTmE0hpUyUgXIzL0RbK4Qx8qfZrKcnALSSntpB_p_-6_Ox3f_HiqAvvOPjU9BdZ3EBRZkEUh7QvF5h6lcsZQH3RTbG2B73veVfVpE5sk6tatLJ-RskS8RcQIg_ZQ73jtWrYdMCmhiKGz3Lp1giBmY1lKsKQCsF25Nvn3TZyrf9y8ej2c2_rC0h18C83PKU_0ZC68Cg6P1YVZTiUOE5PEdSw7rqAoEyeEHshATz5oYB15WVo2ybwhxIdp3KzFszbG_YgtU_6ZXJr_T-av8PwN4zifnw) Full program that reads input from and outputs to the R console. Note that the program(s) should be saved to a file & run in R using `source("myprog.r")`: copy-pasting into a REPL environment will result in incorrect parsing of the input (the program will try to read it's own lines!). The header/footer in the "Attempt This Online" link mimic this behaviour, instead of the default of running code in a REPL setting. --- # [R](https://www.r-project.org), ~~118~~ 115 bytes ``` if(!exists('f'))f=\(x)c();body(f)[T<-T+1]=parse(t='x')#)')x(ver'=t(esrap=]1+T-<T[)f(ydob;)(c)x(\=f))'f'(stsixe!(fi ``` [Attempt This Online!](https://ato.pxeger.com/run?1=zZOxTsMwEIYHNj-Fq0j4Tk2Gbkit3yJb0yFNztRS6li2g1JehSUMvAYPwQZPg9WIIgZQlSLBZOl0_-_7_rMfHt3wrI3tgqQGfHDeNjqA2FHTtCIVAvGpCyq7efVawYx67YMHoWJdyQJ6rACX27Y-gMJ1vsry-WIjbek8QZCiF5igwB7uyAkZgLwrrdws5nm2yteo4FC32yVCFVsKqRCjcRzC655moDQbr367ekl4Z6pdaW6p5lVbE69JaUOeq1gPujVccckdhc4ZfsT5FLCqDKDgWMVUFEaknqyMaIwlURNn8-fbfvQzt4_IbEIo0SG2HJPpp4TyI44tG21q1-71_flMX0TTwS7d9n_L8vQ0JoV6Ul__Vr6Xwv7BSr_Pd_zawzCe7w) Code that defines a function, `f`, that accepts an input of a vector of characters and returns it unchanged. Reversed code defines `f` to return its input reversed, palindromized code defines `f` to return it palindromized, and reverse-palindromized code defines `f` to return it reverse-palindromized. It's not completely straightforward to amend an already-complete R function definition, but it can be achieved (as here) by assigning directly into the function `body` if the function already `exists`. [Answer] # [Bash](https://www.gnu.org/software/bash/), 17 bytes ``` rev $1 # 1$ tac ``` [Try it online!](https://tio.run/##S0oszvifmpyRr6Cbp6CemJScoq5gp1Dxn6sotUxBxVBBWcFQRaEkMZkLrIgrObEELlqWWoSp6n8FAA "Bash – Try It Online") [Answer] # C# Interactive Compiler, ~~80~~ 77 bytes Based on [*@bsoelch*'s Python answer](https://codegolf.stackexchange.com/a/265522/52210). -3 bytes implicitly thanks to [the suggested golf of *@Jakque* on the ported Python answer](https://codegolf.stackexchange.com/questions/265514/i-revpal-the-source-code-you-revpal-the-input/265518#comment579581_265522). ``` var s=ReadLine();//;))(yarrAoT.)(esreveR.s(etirW Write(s);//;)(eniLdaeR=s rav ``` [Try it online.](https://tio.run/##JcohDoAwDAVQzykmO8E4AEHgpxaS6WZ8UQNJuyyMyw/B06/YXEzGaKzOtgQ@o1wgvy7L6j11Vt3vI3iCKRpSMEIVzVNWqSD7I@GSeDLSZk65jfH09wM) ``` var s=ReadLine();//;)s(etirW Write(s.Reverse().ToArray());//;)(eniLdaeR=s rav ``` [.enilno ti yrT](https://tio.run/##JcoxCoAwDAXQ3VN0TAf1AMXBvVMRnIP9QxaFRIp6@Sg4v7dZv5m4N9ZgUwHXLDsopnFM0Qin6NqtKifIhoIGtU@H5ZhV@ab4R8IuuTLKZEG5uV/38wI) ``` var s=ReadLine();//;))(yarrAoT.)(esreveR.s(etirW Write(s);//;)(eniLdaeR=s ravvar s=ReadLine();//;)s(etirW Write(s.Reverse().ToArray());//;)(eniLdaeR=s rav ``` [Try it online..enilno ti yrT](https://tio.run/##bcwxCoBADETR3lNYJoXrAcTC3moRrIOmSKMwkcX18qtgJ9bz5y3eLG6lJEHtfVRZR9uUuGvbjpmyAMM@BSZ1aNIYnPQwzNUMO5T8DUk3G1fR2HsNSb/Y5xjiw8GfNUz7AEgm/sVKOfN1Aw) ``` var s=ReadLine();//;)s(etirW Write(s.Reverse().ToArray());//;)(eniLdaeR=s ravvar s=ReadLine();//;))(yarrAoT.)(esreveR.s(etirW Write(s);//;)(eniLdaeR=s rav ``` [.enilno ti yrTTry it online.](https://tio.run/##bc0xCoAwEETR3lNYbgrjAcTC3ioI1kvcYhuFWQnGy8eAnVjP5020LpqWkhitjUF4m3UXckPfD85ITsXarNBTyHyQJLC6@uWYAM7k3pBk13ljCaO14PSLOcoMTMfia26oVPCfg1@slCvfDw) **Explanation:** `//` is a single-line comment and everything after it are no-ops. So if we'll ignore those comments, all four of the REPL-programs will: 1. Start with `var s=ReadLine();`: Read the input as string into variable `s` 2. 1. `Write(s);`: Write string `s` to the output-buffer 2. `Write(s.Reverse().ToArray());`: Reverse string `s` to a reversed character-iteratator (`Enumerable.ReverseIterator<char>`); then convert it to a character-array (`char[]`); then write all characters in this character-array separately to the output-buffer 3. `Write(s);Write(s.Reverse().ToArray());`: 1 and 2 combined 4. `Write(s.Reverse().ToArray());Write(s);`: 2 and 1 combined 3. After which the output-buffer is output implicitly as single string without trailing newline [Answer] # [Pip](https://github.com/dloscutoff/pip), 11 10 bytes ``` .:a aR. ``` This answer exploits the fact that `.a` does nothing significant, whereas `a.b` is concatenation. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuharuPSsEhUUEoP0uCACUPHl0UqJSclKsVAuAA) ``` [\n].:a aR.[\n]­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­ [\n] [\n] # ‎⁡Newlines for Palindormize/Reverse Palindromize .:a # -, Push input (`:` lowers precedence for Reverse Palindromize) # ‎⁣Comment (" "), ignore the following characters aR. # 💎 ``` [Reversed:](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuharuPSCEhUUEq30uCACUPHl0UqJSclKsVAuAA) ``` [\n].Ra a:.[\n]­⁡​‎‎­⁡​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌­ .Ra # ‎⁡-, Push input reversed a:. # ‎⁢Comment 💎 ``` [Palindromized:](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZbuPSsEhUUEoP0uLj0gkAsKz0uiBRUxfJopcSkZKVYKBcA) ``` [\n].:a aR.[\n][\n].Ra a:.[\n]­⁡​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏‏​⁡⁠⁡‌­ .:a # ‎⁡-, Push input .Ra # ‎⁢Concatenate with input reversed aR. a:. # ‎⁣Comment 💎 ``` [Reverse Palindromized](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZbuPSCEhUUEq30uLj0rECsID0uiBRUxfJopcSkZKVYKBcA) ``` [\n\.Ra a:.[\n][\n].:a aR.[\n]­⁡​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏‏​⁡⁠⁡‌­ .Ra # ‎⁡-, Push input reversed .:a # ‎⁢Concatenate with input, ":" groups it as .(Ra).a rather than .R(a.a) a:. aR. # ‎⁣Comment 💎 ``` [Answer] # [PHP](https://php.net/) -F, 31 bytes ``` echo$argn;#;)ngra$(verrts ohce ``` [Try it online!](https://tio.run/##K8go@G9jXwAkU5Mz8lUSi9LzrJWtNfPSixJVNMpSi4pKihXyM5JTuf7/r6is@pdfUJKZn1f8X9cNAA "PHP – Try It Online") ``` echo strrev($argn);#;ngra$ohce ``` [Reversed version](https://tio.run/##K8go@G9jXwAkuVKTM/IVikuKilLLNFQSi9LzNK2VrfPSixJV8jOSU///r6is@pdfUJKZn1f8X9cNAA) ``` echo$argn;#;)ngra$(verrts ohce echo strrev($argn);#;ngra$ohce ``` [Palindromed version](https://tio.run/##K8go@G9jXwAkU5Mz8lUSi9LzrJWtNfPSixJVNMpSi4pKihXyM5JTubi4QAoUikuKilLLNMAKNYEqwQpBCv7/r6is@pdfUJKZn1f8X9cNAA) ``` echo strrev($argn);#;ngra$ohce echo$argn;#;)ngra$(verrts ohce ``` [Reversed and Palindromed version](https://tio.run/##K8go@G9jXwAkuVKTM/IVikuKilLLNFQSi9LzNK2VrfPSixJV8jOSU8HSYGGgqCZYWKMstaiopFgBLP3/f0Vl1b/8gpLM/Lzi/7puAA) Actually, [my answer to the palindrome question](https://codegolf.stackexchange.com/a/221251/90841) will work here too, because it uses 2 separate `echo` for the palindrome parts ;) Notice the new line at the end which is necessary because of the comment trick. Actually saved one byte here using `#` as comment ]
[Question] [ ## Challenge Given a whole number divisible by 9 and one missing digit, find the missing digit. The missing digit may be represented by any character other than the digits 0-9 as long as it is consistent. If the missing digit could be 0 or 9, output something to signify so. Assume the user is intelligent enough to put only one missing digit and one number etc. ## Test Cases In the test cases the missing digit is represented by a question mark ``` 123? -> 3 ?999 -> 0 or 9 ?0023 -> 4 000?1 -> 8 ``` [Answer] # [Python](https://docs.python.org/2/), 21 bytes ``` lambda s:-int(s,19)%9 ``` [Try it online!](https://tio.run/##HYtBCoAgEAC/spdYA4PVThvU3T90MUoKSiW99HorTzMMTHzyHrwubpzLaa9ltZCG7vBZJKm4bbi4cEPeUobDAyrdG5SAhpkriXT/CxEZVQsO8f7@@kjsJpRO/N6WFw "Python 2 – Try It Online") I used `I` to represent a missing digit. [Answer] ## [Alice](https://github.com/m-ender/alice), 12 bytes ``` /o& \i@/+R9% ``` [Try it online!](https://tio.run/##S8zJTE79/18/X40rJtNBXzvIUvX/f3sDAyNjAA "Alice – Try It Online") Outputs `0` if the result can be either 0 or 9. ### Explanation ``` / Switch to Ordinal mode. i Read all input as a string. & Fold the next operation over the characters of this strings. / Switch to Cardinal mode (not an operation). + Add. Implicitly converts each character to the integer value it represents and adds it to the top of the stack. The top of the stack is initially, implicitly zero. When the character is "?", it is simply discarded, which adds the top of the stack to another implicit zero beneath, so the "?" is effectively skipped. R Negate. Multiplies the sum by -1. 9% Modulo 9. This gives the result. \ Switch to Ordinal mode. o Implicitly convert the result to a string and print it. @ Terminate the program. ``` [Answer] # JavaScript (ES6), 40 bytes Outputs 9 if could be 0 or 9. ``` f=_=>9-([..._].reduce((a,b)=>a+~~b,0)%9) ``` [Answer] # Japt, 7 bytes Tried a few solutions but the shortest was similar to most others except we don't need to replace the `?` at the start. Can take any non-numeric character as the missing digit. Outputs `0` when the solution can be that or `9`. ``` ¬x*J u9 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=rHgqSiB1OQ==&input=IjAwMD8xIg==) --- ## Explanation Implicit input of string `U`. `¬` splits to an array of individual characters, `x` reduces the array by addition ignoring any non-numeric elements, `*J` multiplies each element by -1 and `u9` gets the positive modulus of the result. [Answer] # JavaScript (ES6), 18 bytes Expects a `+` as the missing digit. Returns `9` for *0 or 9*. ``` s=>9-eval(9+s+9)%9 ``` ### Test cases ``` let f = s=>9-eval(9+s+9)%9 console.log(f('123+')) // -> 3 console.log(f('+999')) // -> 0 or 9 console.log(f('+0023')) // -> 4 console.log(f('000+1')) // -> 8 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes An output of `0` means the result could be either **0** or **9**. ``` þSO(9% ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8L5gfw1L1f//7Q0MjIwB "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVvn/8L5gfw1L1f@VSof3Wykc3q@k89/QyNiey97S0pLL3sDAyJjLwMDA3hAA) **Explanation** ``` þ # remove non-digits from input S # split to list of digits O # sum list ( # negate 9% # mod by 9 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~44~~ ~~41~~ 35 bytes -6 bytes thanks to RiaD ``` lambda n:-sum(ord(c)-3for c in n)%9 ``` [Try it online!](https://tio.run/##HYrBCoUgEEV/ZTaPUVCYdGVQX5KLXj0pqDHUFn29D1udcy73esoW2dQwTPWYz@86A/c636eIaRWL1DbEBAvsDCw/rrYqv1zagJ2xHhWgd869JDK2CRH5Dvsr7Vzeu0I9ogqiuax/ "Python 2 – Try It Online") Users `]` for missing digit. Outputs `0` if the missing digit could be 0 or 9. [Answer] # Pyth, ~~9~~ 7 bytes ``` %_s-Qd9 ``` Uses space as the delimiter and returns 0 if the result could be 0 or 9. [Try it online](http://pyth.herokuapp.com/?code=%25_ssMcQd9&input=%22123%2033%22&debug=0) ### Explanation ``` %_s-Qd9 -Qd Remove the space from the input. s Convert it to an integer. %_ 9 Negate mod 9. ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 59 bytes ``` 0*[]. X*[H|T]:-between(0,9,H),U is mod(X+H,9),U*T. +X:-0*X. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30ArOlaPK0Ir2qMmJNZKNym1pDw1NU/DQMdSx0NTJ1Qhs1ghNz9FI0LbQ8cSyNcK0ePSjrDSNdCK0Pv/XzvaUMdIJ0LHLFYPAA "Prolog (SWI) – Try It Online") Yay for Logical programming! ## Explanation First we make a predicate `*`, which holds when applied to zero and the empty list. Our predicate also holds when the front of the list is between 0 and 9 and when we add the leading digit mod 9 the predicate holds. We then define `+` to just be this predicate with `0` as the first argument. That is we want the digital sum to be a multiple of 9. Prolog does all the grunt work of actually finding solutions for us. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~9~~ 6 bytes ``` |0SN%9 ``` ### Explanation ``` |0 # Read input while removing non-digits (question marks) and removing leading zeros S # Sum the digits N # Negate %9 # Mod by 9 ``` An output of 0 means the result could be either 0 or 9. [Try it online!](https://tio.run/##y0rNyan8/7/GINhP1fL////2BgZGxgA "Jelly – Try It Online") Saved 2 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). When using the Each quick (`€`) during evaluation, splitting the number into digits was redundant. Saved 3 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). Can bitwise OR the input with 0 instead of manually parsing the input as a number while removing leading zeros and non-digits. [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), 16 bytes ``` 1+!_#@3#.--9%~:# ``` [Try it online!](https://tio.run/##S0pNK81LT/3/31BbMV7ZwVhZT1fXUrXOShkoYmSsBQA "Befunge-93 – Try It Online\" \"Befunge-93 – Try It Online") A one line version of [James Holderness’ Befunge answer](https://codegolf.stackexchange.com/a/151536/76162) that manages to shave off two bytes. This essentially compresses the code down to one line, reverses the direction and takes advantage of the fact that Befunge doesn’t skip at the end of the line. He suggested I post a separate answer with an explanation. The code takes an \* as representing the missing digit and outputs a 9 for either 0 or 9. ### How It Works ``` 1+!_ 3 --9% Initialises the pointer going right and initialises the digitsum with 3 1+!_ ~: Gets input and checks whether it is end of input (-1) 3 - Subtract three from the input. This turns the ASCII values of digits into their mod 9 equivalent ("0"(48)=>45(mod 9)=>0) -9% Subtract the value from the digitsum and mod it with 9 This keeps the digitsum as a negative digit greater than -9 Repeat this until the input ends Now this is where it gets tricky. At the end of input, the stack looks like this: -(Digitsum%9), Copy of EOF input (-1) The pointer is moving left from the _ +!_ Invert the -1 to get 0 and add it to the digitsum (does nothing but get rid of the -1) 1 %~ Adds 1 mod -1 (no input) = 0 to the stack --9 Subtracts 9 from 0, yielding -9 and subtracts that from the digitsum. This makes the digitsum positive and equal to 9-(digitsum%9), our desired value @ . Finally, print and exit ``` `*` (ASCII value 42) was chosen as the missing character because it counteracts the initial value of the digitsum, 3. [Answer] ## LaTeX, many bytes (~~1000~~ ~~628~~ 614) ``` \RequirePackage{expl3} \ExplSyntaxOn \tl_new:N \l_divnine_input_tl \int_new:N \l_divnine_sum_int \def \getnum { \typein [ \l_divnine_input_tl ] { Input\space a\space number } \tl_map_function:NN \l_divnine_input_tl \divnine_sum:n \int_set:Nn \l_tmpa_int { 9 - \int_mod:nn { \l_divnine_sum_int } { 9 } } \typeout { The\space missing\space digit\space is:\space \int_use:N \l_tmpa_int \int_compare:nNnT { \l_tmpa_int } = { 0 } { \space or\space 9 } } } \cs_new:Nn \divnine_sum:n { \regex_match:nnT { \d } { #1 } { \int_add:Nn \l_divnine_sum_int { #1 } } } \ExplSyntaxOff \getnum \stop ``` ## LaTeX, illegible (~~348~~ 334 bytes) ``` \RequirePackage{expl3}\ExplSyntaxOn\int_new:N\1\tl_new:N\2\def\3{\typein[\2]{Input\space a\space number}\tl_map_function:NN\2\4\int_set:Nn\1{9-\int_mod:nn{\1}{9}}\typeout{The\space missing\space digit\space is:\space\int_use:N\1\int_compare:nNnT{\1}={0}{\space or\space9}}}\def\4#1{\regex_match:nnT{\d}{#1}{\int_add:Nn\1{#1}}}\3\stop ``` ## LaTeX, 132 bytes ``` \RequirePackage{expl3}\typein[\1].\newcount\2{\ExplSyntaxOn\int_gset:Nn\2{9-\int_mod:nn\19}}\typeout{\the\2 \ifnum\2=9or 0\fi}\stop ``` Only space is allowed as unknown digit in this code. [Answer] # [J](http://jsoftware.com/), ~~14~~ 12 bytes -2 bytes thanks to @BolceBussiere ``` 9|9-[:+/"."0 ``` I honestly don't know why `"."0` interprets `?` as 0 but it does so on my interpreter and on TIO so I'm not going to question it. (Update: see comments for an explanation why). This approach very simply takes the sum of the digits, negates it by subtracting from 9, and takes it modulo 9. [Try it online!](https://tio.run/##y/r/P81Wz7LGUjfaSltfSU/J4H9qcka@QppCallqUaWCuqGRsb26grWCur2lpSWEYWBgZAxmGRgY2Buq/wcA "J – Try It Online") [Answer] # [Swift](https://swift.org), 51 bytes ``` {9-Int("0"+$0.filter{"?" != $0})!%9}as(String)->Int ``` [Try it online!](https://tio.run/##Ky7PTCsx@Z@TWqKQpmD7v9pS1zOvREPJQElbxUAvLTOnJLWoWsleSUHRVkHFoFZTUdWyNrFYI7ikKDMvXVPXDqj4fwGQXaKRpqFkaGRsr6SpyQUXsLe0tEQVMDAwMkYRMTAwsDdEVQPi/QcA) [Answer] # [Befunge-93 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~22~~ 21 bytes I realized that I don't need to use `?` to represent the absent digit, so I used one that is a multiple of 9 after subtracting 48: `x` This let me golf off the `3+`, but it only saved me 1 byte because of the length of the first line before the conditional :( --- A port of my Befunge-98 answer: 5 more bytes in order to check if we've reached EOF, 1 more byte to push 48 (`"0"` vs `'0`), 1 more byte to print the answer with `.@`, and 1 more byte, because the second line has a space for a total of 8 more bytes. ``` ~:0`!#|_"0"-+ @.%9-< ``` [Try it online!](https://tio.run/##S0pNK81LT9W1NNYtqAQz//@vszJIUFSuiVcyUNLV5lJw0FO11LX5/9/QyLgCAA "Befunge-93 (PyFunge) – Try It Online") Outputs `0` if the missing digit could be 0 or 9. This only works in the PyFunge interpreter for reasons explained below. ### Explanation Much of this explanation is copy-pasted from my [Befunge-98 explanation](https://codegolf.stackexchange.com/a/151583/62574), as that program is very similar to this one. shameless plug In the first line of the program, we sum the digits, including the x, which is treated like a 72 because of it's ASCII value. However, the sum will be the same once we've modded by 9, so this is irrelevant. ``` ~:0`!#|_"0"-+ THE FIRST LINE ~ Gets a character from input - If it is negative, we've reached EOF :0`! Pushes 0 if the character is positive, 0 otherwise #|_ Goes to the next line if the value if 0 This also gets the negative value off the stack by using a | "0"- Subtracts 48 to account for taking in ASCII values + Adds this adjusted value to the sum ``` If we just modded by 9, we would be left with the wrong digit, because we want `9 - (sum % 9)`. However, we can do better than `9\-`, which would subtract the remainder from 9: if we make the sum negative before modding by 9, we will get a positive result, equivalent to `9 - (sum % 9)` in some interpreters. This is what requires us to use the PyFunge interpreters for both Befunge 93 and 98, as it is the only one on TIO that does this. The others give us a value between -8 and 8 instead of 0 and 8 ``` @.%9-< THE SECOND LINE < Redirects the IP onto this line - Subtracts the sum from an implicit 0, making it negative %9 Mods the sum by 9 @. Prints the digit and exits ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~15~~ 13 bytes I realized that I don't need to use `?` to represent the absent digit, so I used one that is a multiple of 9 after subtracting 48: `x` This let me golf off the `3+`. ``` #v~'0-+ q>-9% ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XLqtTN9DV5iq007VU/f/f0Mi4AgA "Befunge-98 (PyFunge) – Try It Online") Uses an `x` as the missing digit, because it's ASCII value is divisible by 9 after subtracting 48 (and it's nice because its commonly used as a variable in math). Outputs via exit code (because `q` is one byte shorter than `.@`) Outputs `0` if the missing digit could be 0 or 9. This only works in the PyFunge interpreter for reasons explained below. ### Explanation In the first line of the program, we sum the digits, including the `x`, which is treated like a 72 because of it's ASCII value. However, the sum will be the same once we've modded by 9, so this is irrelevant. ``` #v~'0-+ THE FIRST LINE #v~ Pushes the next character from input, and goes to the second line on EOF '0- Subtracts 48 to account for taking in ASCII values + Adds this adjusted value to the sum ``` If we just modded by 9, we would be left with the wrong digit, because we want `9 - (sum % 9)`. However, we can do better than `9\-`, which would subtract the remainder from 9: if we make the sum negative before modding by 9, we will get a positive result, equivalent to `9 - (sum % 9)` *in some interpreters*. This is what requires us to use the PyFunge interpreters for both Befunge 93 and 98, as it is the only one on TIO that does this. The others give us a value between -8 and 8 instead of 0 and 8. ``` q>-9% THE SECOND LINE > Redirects the IP onto this line - Subtracts the sum from an implicit 0, making it negative 9% Mods the sum by 9 q Outputs via exit code, ending the program ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 22 bytes Uses `'` (any char that has a distance to `0` that is divisible by "0" will do, including `0` itself). An output of `0` signifies either `0` or `9`. ``` p -(gets.sum+6*~/$/)%9 ``` [Try it online!](https://tio.run/##KypNqvz/v0BBVyM9taRYr7g0V9tMq05fRV9T1fL/f3UDAyNjAA "Ruby – Try It Online") ## Explanation ``` p # print after inspecting -( # unary negative, for reversing result of modulus (a-b%a) gets.sum # ascii value of string + 6*~/$/ # add six for each size (in chars) of input, so "0" translates to 0 )%9 # mod 9 # find remainder after dividing 9 # except it's inverted so it's remainder to add to divide 9 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 13 bytes ``` {9-9|+/,↑⍎¨⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqS13LGm19nUdtEx/19h1a8ah3ay1QRkHd0Mj4Ue8adS4gE0hbWlrCmAYGRsZgtoGBAZBrqA4A "APL (Dyalog Unicode) – Try It Online") The missing digit is `⍬`. [Answer] # [Ruby](https://www.ruby-lang.org/), 46, 41 bytes *-5 thanks to @Unihedron* ``` ->s{-s.chars.sum{|i|?<>i ? i.to_i : 0}%9} ``` [Try it online!](https://tio.run/##JYpBCoMwFAX3OcVDEXSREHWVUs1FCsWqoQGrxR8pJebsqdJZDcOs2@MbTXOLvCXPSfTPbiVB28vvdtfX1kLDCrfcLS6QIVMhupEcoUH2ycuq1tBKKWgpqxpSSl0WzCwrzgt2xv8eFoaD93Z4kvozBvAWqTei76YpP0sREjbOA@IP "Ruby – Try It Online") [Answer] # Befunge-93, ~~28~~ ~~27~~ ~~19~~ 18 bytes Credit must go to [Mistah Figgins](/users/62574/mistah-figgins), whose [PyFunge answer](/a/151584/62101) showed me that you didn't need a special check for the missing digit character, if you just made sure the ASCII value was a multiple of nine. Additional thanks to [Jo King](/users/76162/jo-king) who showed that you didn't need to fully convert the characters to their numeric equivalent, and could simply subtract 3 to get a value that is relative to base 9 (ASCII `0` minus 3 is 45, a multiple of 9). ``` 3_v#`0:~-- %9_@.+9 ``` [Try it online!](http://befunge.tryitonline.net/#code=M192I2AwOn4tLQolOV9ALis5&input=KjAwMjM) For this to work, you should use the character `*` for the missing digit (there are others that could also work, but that's the nicest). Outputs `9` if the missing digit could be 0 or 9. **Explanation** ``` 3 Push 3 onto the stack. _ Since this is non-zero, drop the 3 and branch left. 3 Now executing right to left, push 3 again. -- Negate twice, leaving the value unchanged as our starting sum. ~ Now we start the main loop, reading a character from stdin. `0: Duplicate and check if it's > 0, i.e. not end-of-stream. _ # If so, continue to the left. 3 - Subtract 3 to make the number relative to base 9. - Then subtract it from the total, and repeat the loop. v Once we reach the end of the input, we go down. _ Drop the EOF character from the stack and go left. %9 +9 Mod the total with 9, and add 9. @. Output the result and exit. ``` Essentially we are calculating the sum of all digits, plus 45 per digit (which will ultimately be cancelled out when we mod with 9). This sum is subtracted from 3 (our starting total), and an additional 39 is subtracted by the missing digit (ASCII `*` minus three). Again that 3 minus 39 is a multiple of 9, so it's cancelled out when we mod with 9. So in the end we're calculating the negative sum of all the digits, mod 9, plus 9, i.e. ``` 9 - (digitsum % 9) ``` And that's gives us the missing digit. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 50 bytes ``` +>,[---[<-[<<]>[<+++++++++<]>>-],]-[<+>-----]<---. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9f204nWldXN9oGiGxi7aJttGEAyLPTjdWJBUpo2@mCQKwNkND7/9/QyNgKAA "brainfuck – Try It Online") Prints a 9 for either 0 or 9. Missing character is represented by : ### How It Works ``` Tape Format: 0 Total Input 0 The total is represented as 9-digitSum%9 +>,[ Start loop with 1 as the total --- Subtract 3 from the inputted byte to make the value%9 equal to the digit [ While the input byte exists <- Decrement the total [<<]>[<+++++++++<] If the total is 0, reset it to 9 >>- Decrement the input byte ] ,] Continue loop until there is no input -[<+>-----]<---. Add 48 to the total to convert the digit to the ascii value and output it ``` The missing character needs to be a character that has a mod 9 of 4, +3 because we subtract 3 from the normal digits and +1 for the initialisation of the total as 1. As a side note, there is a *lot* of inefficiency in the code for the sake of golfing, as each digit will reset the total 5 times each, rather than just once sometimes if I subtracted 48 instead of 3. [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 8 bytes ``` #q~3--9% ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XLqwz1tW1VP3/39DIuAIA "Befunge-98 (PyFunge) – Try It Online") Outputs via exit code. As with [Mistah Figgin's answer](https://codegolf.stackexchange.com/a/151583/76162), it only works with Pyfunge, where a negative number mod 9 becomes positive. Uses an x as the missing digit. [Answer] # Java 8, ~~36~~ 34 bytes ``` s->9-s.map(c->c>57?0:c-48).sum()%9 ``` Returns `9` when both `0` and `9` are valid. **Explanation:** [Try it online.](https://tio.run/##jY5Na8MwDIbv/RWiMLAPNu7HWL2y5LxDe@mx7KC53uYsdkKkFMrIb8@8dKfBoGCBJT0Peis8o2pan6rT5@hqJIIdhvQ1AwiJffeGzsP@p50G4ESVDd1zqDVx5zHq58SH6QcktxkccuVHjBwc7CHBE4ykCqtIR2yFU4Ur7h9K8@jUeiM19VHIOztur17bv9bZ@9XPTThBzIlEvhHS@/EF5TXN4ULso2561m3ecJ1E0k7MF8tVOdfuAzsSUk6J/odLa@3tsDHL1c20MaZc/KGH2TB@Aw) ``` s-> // Method with IntStream parameter and int return-type 9- // Return 9, minus: s.map(c->c>57?0:c-48).sum() // The sum of the digits (ignoring the question mark) %9 // modulo-9 ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 7 bytes ``` 19βN9%‹ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=19%CE%B2N9%25%E2%80%B9&inputs=%3F0023&header=&footer=) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 40 bytes ``` param($a)0..9|?{!(($a-replace'x',$_)%9)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVR00BPz7LGvlpRA8jRLUotyElMTlWvUNdRiddUtdSs/f//v7qBgUGFoToA "PowerShell – Try It Online") or [Verify all test cases](https://tio.run/##FcrRCsIgFIDh@57ChkOlNs62q3NTDxIxZGgFbhNXJDif/WRXHz/8fv2asD2Nc2Q/y/R@rQuzibwOepZcK2hb3K/pKEs0wXinJyOiOPNR1agy5QPX4bHd4L7XqeIjay6sOknLypCJRNcP5RYREf8A9EMRAGInfg "PowerShell – Try It Online") Takes input like `'123x'` into `$a`. Constructs a range `0` to `9` and uses `Where-Object` (here abbreviated as `|?`) to pull out those integers that match the clause. The clause takes `$a`, performs a regex `-replace` to replace the `x` with the current digit `$_` and gets the mod 9 with `%9`. Thus if 9 evenly divides, this will be zero. We take the Boolean-not thereof, which turns the zeros truthy and everything else falsey, so that satisfies the Where-Object clause. Those result(s) are left on the pipeline and output is implicit. [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` f s=9-sum[read[i]|i<-s,i<':']`mod`9 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2NZSt7g0N7ooNTElOjO2JtNGt1gn00bdSj02ITc/JcHyf25iZp6CrUJBUWZeiYKKQpqCkr2lpaXSfwA "Haskell – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~35~~ ~~34~~ 25 bytes If the `?` can be `0 or 9`, the result is shown as `9`. ``` . $* 1{9} ^ 9$*; +`;1 . ``` [**Try it online**](https://tio.run/##K0otycxL/K@q4Z7wX49LRYvLsNqylosrjstSRcuaSzvB2pCLS@//f0MjY3sue0tLSy57AwMjYy4DAwN7QwA) ### Explanation ``` . Sum of the digits in unary + 1 $* 1{9} Modulo 9 ^ Prepend 9 semicolons, for subtracting 9$*; +`;1 Subtract from 9 . Back to decimal ``` [Answer] # [Perl 5](https://www.perl.org/), 23 bytes ``` $_=- s/\D//r%9;s/0/0|9/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZXoVg/xkVfv0jV0rpY30DfoMZS//9/A3sDAyPjf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") Doesn't care what character signifies the missing digit as long as it isn't a digit. [Answer] # Tcl, 53 bytes ``` puts [expr 9-([regsub -all (\\d)\\D? 0$argv +\\1])%9] ``` As with other answers, this is made shorter by not explicitly saying “0 or 9”. Instead, a result of “9” means either 0 or 9. [Try it online!](https://tio.run/##K0nO@f@/oLSkWCE6taKgSMFSVyO6KDW9uDRJQTcxJ0dBIyYmRTMmxsVewUAlsSi9TEE7JsYwVlPVMvb///@GRsb2AA) **Explanation** It works pretty simply. It employs a regular expression to: * split the argument into individual digits * eliminate any ~~question mark(s)~~ non-digit(s) * interleave the digits with plus signs It then evaluates 9 - (sum\_of\_digits mod 9) to arrive at a final value in 1..9, which it then `puts`. The leading 0 (in `0$argv`) is required just in case the question mark comes first in the input; a leading plus sign in the transformed sequence is not a problem for `expr`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` %_iz19 9 ``` [Try it online!](https://tio.run/##K6gsyfj/XzU@s8rQUsHy/39PAwMjYwA "Pyth – Try It Online") Uses `I` instead of `?`. * Convert to base 19. * Negate. * Modulo 9. ]
[Question] [ Given an image, either as input (possibly in RGB triplets) or with the filename as input (you may assume the image has a specific filename, possibly without an extension), output an image representing a single color channel of the image. You will also take another input, representing which channel to output. The input can be one of any 3 distinct symbols. However, the symbols must be either a string or a number. You cannot take a matrice to apply to the array as input however. (such as `{1, 0, 0}`, or `{0, 1, 0}`). You will output the `<input>` channel of the input image. You may either save it to a file or output a set of RGB pairs. Your program should have no limits on the size of the image (in px), and must support either `.png`, `.jpg`/`.jpeg`/`.JPG`, or RGB triplets as image formats. (it can support as many as you want however) Test case: [![violet original](https://i.stack.imgur.com/Rwp0c.png)](https://i.stack.imgur.com/Rwp0c.png) Red channel: [![violet red](https://i.stack.imgur.com/O7j1r.png)](https://i.stack.imgur.com/O7j1r.png) Green channel: [![violet green](https://i.stack.imgur.com/Qsvo7.png)](https://i.stack.imgur.com/Qsvo7.png) Blue channel: [![violet blue](https://i.stack.imgur.com/ZZSiR.png)](https://i.stack.imgur.com/ZZSiR.png) And another test case, entirely of red. [Original photo](https://i.stack.imgur.com/7rl5Tm.png), [red](https://i.stack.imgur.com/3zvrHm.png), [green](https://i.stack.imgur.com/tHlbjm.png), and [blue](https://i.stack.imgur.com/OSeOWm.png). (warning: the plain and red channel hurt to look at for too long) 2 more test cases: [Original](https://i.stack.imgur.com/S5CuU.png), [red](https://i.stack.imgur.com/eGP3p.png), [green](https://i.stack.imgur.com/69ivJ.png), [blue](https://i.stack.imgur.com/i4Kup.png). [Original](https://i.stack.imgur.com/Ov3Gm.png), [red](https://i.stack.imgur.com/ncJux.png), [green](https://i.stack.imgur.com/l6YeK.png), [blue](https://i.stack.imgur.com/Wspfm.png). The latter two test cases are from [Images with all colors](https://codegolf.stackexchange.com/questions/22144/images-with-all-colors). [Answer] # JavaScript (ES6), 29 bytes ``` a=>n=>a.map(b=>b.map(c=>c&n)) ``` Input is a 2D array of 24-bit integers (e.g. `[[0x0000ff,0x00ff00],[0xff0000,0xffffff]]`) and `16711680` for red, `65280` for green, `255` for blue. If this isn't valid, try this instead: ## JavaScript (ES6), 48 bytes ``` a=>n=>a.map(b=>b.map(c=>c.map((d,i)=>i==n?d:0))) ``` Input is a 3D array of color values and `0` for red, `1` for green, `2` for blue. [Answer] ## Mathematica, 13 bytes ``` ImageMultiply ``` This should be the legitimate version of JungHwan Min's answer. This function takes the image and one of `Red`, `Green`, `Blue` as input. For example: [![enter image description here](https://i.stack.imgur.com/CU0td.png)](https://i.stack.imgur.com/CU0td.png) As a fun-fact, there's also `ColorSeparate` which gives you individual channels, but it returns them as single-channel/greyscale images, so you'd need to multiply them by the colour afterwards anyway. [Answer] # [Spectrum](https://github.com/ConorOBrien-Foxx/Spectrum), noncompeting, 1 byte (Non-competing because this challenge inspired this language.) In reality, Spectrum is an npm library with a language interface for the commands. ``` I ``` Takes input as: ``` <filename> channel ``` Call the program as: ``` cat input.txt | node spectrum.js "I" ``` Alternatively, you may supply information to the prompts: ``` λ node spectrum.js "I" input> Ov3Gm.png input> r [ Image { 512x512 } ] ``` This leaves the image on the stack. To view it, add `O` at the end, like so: ``` λ node spectrum.js "IO" input> Ov3Gm.png input> r [] ``` --- For some extra fun, try `echo filename | node spectrum.js "wO"`. It performs all three channel isolations at once: [![warhol](https://i.stack.imgur.com/pWVsZ.png)](https://i.stack.imgur.com/pWVsZ.png) [Answer] # Bash + ImageMagick, ~~35~~ ~~32~~ 27 bytes ``` mogrify -channel $1 -fx 0 i ``` Assumes the image is in the file `i` and the script takes one of `RG`, `BG`, `BR` for blue, red, and green respectively; outputs to the file `i`. [Answer] ## JavaScript (ES6), 29 bytes ``` a=>b=>a.map((v,i)=>i%3^b?0:v) ``` A lot like [ETHproductions' answer](https://codegolf.stackexchange.com/a/114418/67501 "ETHproductions") but with more flexible input than the first method and smaller than the second one. This defines a function which accepts the image as a 1-dimensional array of numerical colour intensities. This function then returns another function which accepts an integer value representing the desired colour channel. Colours can be represented by any numerical range as long as 0 indicates a complete absence of colour. E.g. `0.0 - 1.0` or `0 - 255` **Examples:** If image data is in the format RGB then calling the function with arguments `(imageData)(0)` will return the image with only the red channel. If image data is in the format BGR then calling the function with arguments `(imageData)(2)` will also return the image with only the red channel. [Answer] # Python 2, 69 bytes ``` from cv2 import* def f(s,i):k=imread(s);k[:,:,[i,i-1]]=0;imwrite(s,k) ``` Still golfing. Takes input as `filename, n` (where `n` is 0, 1, or 2). Saves the new image over the old one. `0` is green, `1` is red, and `2` is blue. Thanks to @ovs, @Mikhail and @Rod for bytes off. [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` {3,f=f{f.*}} ``` An anonymous block that expects a 3D array of RGB triplets and a number between 0 and 2 inclusive on the stack. Leaves the extracted array on the stack afterward. ``` Red -> 0 Green -> 1 Blue -> 2 ``` Could possibly be golfed by using a bizarre input format, but I feel like that's cheating a bit. [Try it online!](https://tio.run/nexus/cjam#K6z7X22sk2abVp2mp1Vb@7@u4H90dLShgpGCcWy0iYKpgllstLmChYJlbKwCieKxCgYA "CJam – TIO Nexus") The test case is made up just to demonstrate, using the triplets from an actual image would be way too big. **Explanation** ``` 3, e# The range [0 1 2] f= e# Check each for equality with the RGB indicator, gives the indicator array: e# [1 0 0] for 0, [0 1 0] for 1, [0 0 1] for 2 f{ e# Map on each row of the array using the indicator array as an extra parameter f.* e# Perform vectorized multiplication of the indicator array with each triplet. e# For red, multiplies red by 1, and green and blue by 0. Does similarly e# for green and blue. } e# (end of block) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 282 bytes ``` $x,$y=$args;1..($a=New-Object System.Drawing.Bitmap $x).Height|%{$h=--$_;1..$a.Width|%{$i=("$($a.GetPixel(--$_,$h)|select R,G,B)"|iex)[$y];$r,$g,$b=(((0,0,$i),(0,$i,0))[$y-eq'G'],($i,0,0))[$y-eq'R'];$a.SetPixel($_,$h,[system.drawing.color]::fromargb($r,$g,$b))}};$a.save("$x$y.png") ``` None of this fancy "golfing the input" or "using built-ins." Phooey on that. ;-) This here takes the full path of an input PNG (though, strictly speaking, it doesn't *need* to be a PNG, since JPG, BMP, etc. are supported by .NET, but I've only tried it on PNGs), and one of `(R, G, B)` for the color channel, then stores those into `$x` and `$y`. We then create a `New-Object` of type [`System.Drawing.Bitmap`](https://msdn.microsoft.com/en-us/library/system.drawing.bitmap(v=vs.110).aspx) of `$x` and store that into `$a`. Then we do a double loop over all pixels. First from `1` up to `$a`'s `.Height`, setting `$h` each iteration (it's zero-indexed, so that's why we `--$_`, which saves bytes over `( .height-1)`. Inside, we loop from `1` up to `$a`'s `.Width`. Each iteration, we're performing a `.GetPixel` on the particular `w,h` coordinates, which returns a [`System.Drawing.Color`](https://msdn.microsoft.com/en-us/library/system.drawing.color(v=vs.110).aspx) object. We `select` out the `R G B` values thereof. The `iex` here is a neat trick that turns this into a hashtable (e.g., something like `@{R=34; G=177; B=76}`) so we can index into that directly with the desired color channel `[$y]`. That value is stored into `$i`. Next, we set three values `$r, $g, $b` to be the result of some [pseudo-ternary operators](https://codegolf.stackexchange.com/a/79895/42963) based on the letter value of `$y`. So, for example, if `$y` is `R`, then the result here is `$r=$i, $g=0, $b=0`. Then, we do a `.SetPixel` back onto that particular `w,h` coordinate, constructing a new `System.Drawing.Color` using the static `FromARGB` (which assumes the alpha to be fully opaque). Once we've finished looping, we then simply `.Save` the PNG to a new file. *Note: This does take a long while, since it's completely independently looping through every pixel and performing a bunch of calculations and calls each iteration.* Tests: [![AdmBorkBork Red](https://i.stack.imgur.com/t2CXX.png)](https://i.stack.imgur.com/t2CXX.png) [![AdmBorkBork Green](https://i.stack.imgur.com/LloJf.png)](https://i.stack.imgur.com/LloJf.png) [![AdmBorkBork Blue](https://i.stack.imgur.com/VQd6U.png)](https://i.stack.imgur.com/VQd6U.png) [Answer] # Bash + ImageMagick, 41 bytes ``` C="RGB" mogrify -channel ${C//$1} -fx 0 x ``` Input is a file named `x`, command line parameter one of `R` or `G` or `B` Output overwrites the input file Differs from betseg's answer in taking more natural single-letter channel parameter. Also overwriting instead of outputting a new file which betseg is free to steal :) [Answer] # [Chip](https://github.com/Phlarx/chip), 78 bytes ``` ~Z~vS f/F,^-. e/E|,-Z. d/D|>zz^. a/AMx-x-]. b/BMx-]v-' c/CM]v-' >--v' G/gh/H ``` [Try it online!](https://tio.run/nexus/chip#@69QF1VXFsyVpu@mE6erx5Wq71qjoxulx5Wi71JjV1UVp8eVqO/oW6FboRurx5Wk7wRkxpbpqnMl6zv7ghkKdrq6Zepc7vrpGfoe//@bGhoZm5iamVtYAgA "Chip – TIO Nexus") Chip is a 2D language that operates on the component bits of each byte in a byte stream. ### Overview This particular solution expects the first byte of input to be the control character--to define which channel(s) to keep--and following is the bytes of image data. The image data must be RGB triplets, one byte per channel, 24 bits per pixel: ``` | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ... | 3n-2 | 3n | 3n+1 | | | First Pixel | Second Pixel | ... | nth Pixel | | Ctl | Red | Grn | Blu | Red | Grn | Blu | ... | Red | Grn | Blu | ``` The control character is interpreted as a bit field, though only the three lowest bits have meaning: ``` 0x1 keep Red channel 0x2 keep Green channel 0x4 keep Blue channel ``` This means we can use ASCII characters to select which channel we want: `1` means red `2` means blue `4` means green Or do something fancier: `5` keep red and blue, but not green `7` keep all channels (image is unchanged) `0` drop all channels (image is black) ### How it works This solution is rather jumbled up due to golfing, but here goes: 1. Read the three low bits of the first byte with `C`, `B`, and `A`, and store those bits in their corresponding `M`emory cells. Also, `S`uppress output for the first cycle. 2. Loop over those three bits repeatedly. If the current bit it is on, close the `/` switches to output the current input byte, if it is off, open the switches so that we output a zero byte. 3. Continue until input is exhausted. ### Viewing the results Sure, you could use hexdump or something boring, but it turns out this is (almost) an actual valid image format: [binary Portable PixMap](https://en.wikipedia.org/wiki/Netpbm_format). Just plop the image data from above (minus the control byte, of course) into the file below, adjust the width/height to be valid, and you can view the image in a proper viewer like IrfanView, though simpler ones (like most browser built-ins) can't handle it. ``` P6 {width as ASCII} {height as ASCII} 255 {binary image data here} ``` For example (using escapes for the raw data): ``` P6 3 1 255 \xff\x00\x00\x00\xff\x00\x00\x00\xff ``` [Answer] # MATL, ~~21~~ 13 bytes ``` Yi3:iml&!*3YG ``` The color channel should be specified using the following mapping: `1:red`, `2:green`, `3:blue` The Online interpreters are unable to use `imread` to read images so [here is a slightly modified version where I have hard-coded a random image into the source](https://matl.suever.net/?code=%5B10+15+3%5Dl%24r+255%2a+%27uint8%27Y%25+%25+Create+some+bogus+image+data%0A%0A3%3Aiml%26%21%2a3YG&inputs=2&version=19.8.0). **Explanation** ``` % Implicitly grab first input as a string (filename) Yi % Read the image in from a filename or URL 3: % Push the string literal 'rgb' to the stack i % Grab the second input as a number m % Check for membership. So for example 2 will yield [false, true, false] l&! % Permute the dimensions to turn this 1 x 3 array into a 1 x 1 x 3 array * % Multiply this with the input RGB image. It will maintain the channel which % corresponds with the TRUE values and zero-out the channels that corresponded to % the FALSE values 3YG % Display the image ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 7 bytes I/O: array of RGB triplets ``` ⎕×⊂⎕=⍳3 ``` [Try it online!](https://tio.run/nexus/apl-dyalog#PY@xSgNBEIb7fYopTXFw5Lh0QaxECARMWou9u1mzsJkNu5dwQdKkSIJwYiNWvoGdvoFvMu9gfc4ZtJp/Zr6ff4ZPR9Px08vXKz/upY65/cg6Ph07bt@gXiAQNrWIgAjOEkZA0oXD886WCIVvsILKxpXTWzUo/WoLUbtaPezO6OxqMld3fHgWEjxBYsaelJK024lMuX2HPuwaawiaKr8EWi8LDBFMkGY669GbqaDpL5gmhY4SaanCxtI9XBgf/qwb7dZyZJoM83yglOm94rzM/gXk3H7Kt5mUYT76Jp@UulzgDw "APL (Dyalog Unicode) – TIO Nexus") `⍳3` first three integers `⎕=` compare numeric input (the chosen channel) to that `⊂` enclose (so each image triplet pairs up this entire triplet) `⎕×` multiply numeric input (the array of triplets) with that [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` vyvy2ô²è}})¹0ègô ``` [Try it online!](https://tio.run/nexus/05ab1e#@19WWVZpdHjLoU2HV9TWah7aaXB4RfrhLf//R0eru4GBug6Y4eoKZQBFYnXIlozlMgQA "05AB1E – TIO Nexus") Uses hex colors in a 2D array format and [0,1,2] for each channel. [Answer] # Clojure, ~~421~~ 332 bytes **-89 bytes** by aggressively inlining everything, changing from my ridiculous old method of stripping the channels, and getting rid of an unnecessary accidental import. ``` (import '(java.awt.image BufferedImage)'(clojure.lang Keyword)'(javax.imageio ImageIO)'(java.io File)'(java.awt Color))(fn[p i](doseq[y(range(.getHeight p))x(range(.getWidth p))](.setRGB p x y(.getRGB(apply #(Color. % %2 %3)(#(let[c(Color. %)](assoc [0 0 0]i(([(.getRed c)(.getGreen c)(.getBlue c)]%)i)))(.getRGB p x y))))))(ImageIO/write p"jpg"(File."./o.jpg"))) ``` Smacked this out half an hour before my shift started with no idea what I was doing. I have little experience with `BufferedImage`, so there may be a better way of going about this. I'm also abusing `Color` to convert back-and-forth between integer and individual channel representations of colors. This is comically huge compared to the other answers for a couple reasons (besides the obvious that Clojure isn't a golfing language): * Instead of just manipulating a byte array, this actually takes as input a picture, alters it, and outputs it. * I'm using Java-interop, which while handy can be quite verbose at times. The imports alone are larger than many answers. See the code below for a break down. ``` (ns bits.restrict-channel (:import (java.awt.image BufferedImage) (clojure.lang Keyword) (javax.imageio ImageIO) (java.io File) (java.awt Color))) (defn restrict-channel "Accepts a BufferedImage and a index between 0 and 2 (inclusive). Removes color from all channels EXCEPT the channel indicated by color-i. color-i of 0 = keep red color-i of 1 = keep green color-i of 2 = keep blue" [^BufferedImage image ^long color-i] (let [; Turn a number representing RGB into a triplet representing [R G B] channels #(let [c (Color. %)] [(.getRed c) (.getGreen c) (.getBlue c)]) ; Create a new triplet that only contains color in the color-i channel zero-channels #(assoc [0 0 0] color-i ((channels %) color-i))] ; Loop over each pixel (doseq [y (range (.getHeight image)) x (range (.getWidth image))] ; Grab the current color... (let [cur-color (.getRGB image x y)] ; ... setting it to stripped color triplet returned by zero-channels (.setRGB image x y ; This "apply" part is just applying the stripped triplet to the Color constructor ; This is needed to convert the separate channels into the integer representation that `BufferedImage` uses. (.getRGB (apply #(Color. % %2 %3) (zero-channels cur-color)))))) ; Save the result to file (ImageIO/write image "jpg" (File. "./o.jpg")))) ``` [Answer] # Lua (love2d Framework), 498 bytes I did this more as a exercise for myself, so it's not as short as it could be (though I did try to golf), but I wanted to add it to here cause I think I did good. Even if I'm too late. Here the golfed code, under it is the explained and untangled version. ``` l=love g,p,rm,bm,gm,s=l.graphics,0,1,1,1,[[uniform float m[4];vec4 effect(vec4 co,Image t,vec2 c,vec2 s){vec4 p=Texel(t,c);p.r=p.r*m[0];p.b=p.b*m[1];p.g=p.g*m[2];return p;}]]t=g.setShader h=g.newShader(s)function l.draw()h:send("m",rm,gm,bm)if p~=0 then t(h)g.draw(p)t()end end function l.filedropped(f)a=f:getFilename()p=g.newImage(f)end function l.keypressed(k)if k=="0"then rm,gm,bm=1,1,1 end if k=="1"then rm,gm,bm=1,0,0 end if k=="2"then rm,gm,bm=0,1,0 end if k=="3"then rm,gm,bm=0,0,1 end end ``` Here is the code which has to get a \*.jpg file dropped into it. After the image was inserted you can press the number buttons for red(1) green(2) or blue(3) channels. Also to see the default picture again press 0. Actually it just shows the picture in the window. ``` l=love g=l.graphics p=0 rm,bm,gm=1,1,1 s = [[uniform float m[4]; vec4 effect(vec4 co,Image t,vec2 c,vec2 s){vec4 p=Texel(t,c);p.r = p.r * m[0];p.b = p.b * m[1]; p.g = p.g * m[2]; return p;} ]] sh=g.newShader(s) function l.draw() sh:send("m",rm,gm,bm) if p~=0 then g.setShader(sh) g.draw(p) g.setShader() end end function l.filedropped(f) a=f:getFilename() p=g.newImage(f) end function l.keypressed(k) if k=="0"then rm,gm,bm=1,1,1 end if k=="1"then rm,gm,bm=1,0,0 end if k=="2"then rm,gm,bm=0,1,0 end if k=="3"then rm,gm,bm=0,0,1 end end ``` The important part which does all the work is the shader which is the small string declaration at the beginning or untangled: ``` uniform float m[4]; vec4 effect(vec4 co,Image t,vec2 c,vec2 s) { vec4 p=Texel(t,c); p.r = p.r * m[0]; p.b = p.b * m[1]; p.g = p.g * m[2]; return p; } ``` which gets the actual pixel of the image and just shows the channels as needed. My test image and the different outputs for the channels (also for sure the other ones) [![default image and channel images merged](https://i.stack.imgur.com/wVWJA.png)](https://i.stack.imgur.com/wVWJA.png) [Answer] # C, ~~60~~ 58 bytes ``` main(a,b)char**b;{while(scanf(b[1],&a)>0)printf("%d ",a);} ``` Image input is a list of numbers (in decimal) between 0 and 255 on `stdin`, e.g. ``` 255 0 0 192 192 192 31 41 59 ... ``` The channel is specified as the first argument to the program, and is one of ``` red -> "%d%*d%*d" green -> "%*d%d%*d" blue -> "%*d%*d%d" ``` Example: ``` $ echo "255 0 0" | ./extract "%d%*d%*d" 255 ``` ]
[Question] [ **Task:** Given an input consisting of exactly one of the characters `<>^v`, output a second input consisting of the printable ASCII characters (from space to tilde), oriented with the arrow. Let's assume the second input to the program is `ABC`. This is what it should do: * Input `>`: print `ABC`. * Input `<`: print `CBA`. * Input `^`: print `C\nB\nA`, or the input rotated -90°. * Input `v`: print `A\nB\nC`, or the input rotated 90°. ## Test cases ``` input => \n output --- ">", "thanks!" => thanks! --- "<", "Hello, World!" => !dlroW ,olleH --- "^", "This is text." => . t x e t s i s i h T --- "v", "Tokyo" => T o k y o --- "<", ">>>" => >>> ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~10~~ 6 bytes *4 bytes saved thanks to Martin!* ``` 19\qX! ``` [**Try it online!**](http://matl.tryitonline.net/#code=MTlccVgh&input=J14nCidUaGlzIGlzIHRleHQn) ``` 19\ % implicitly take input (a character) and compute mod-19 of its ASCII code q % subtract 1. Gives 17, 2, 3, 4 for the characters '^<v>' respectively. % These numbers correspond to 1, 2, 3, 4 modulo 4, and so are the numbers % of 90-degree rotations required by each character X! % implicitly take input (string). Rotate the computed number of times % in steps of 90 degrees. Implicitly display ``` --- Old version, without modulo operations: 10 bytes ``` '^<v>'=fX! ``` [Try it online!](http://matl.tryitonline.net/#code=J148dj4nPWZYIQ&input=J14nCidUaGlzIGlzIHRleHQn) ``` '^<v>' % push string = % implicitly take input (a char) and test for equality f % find index of matching character X! % implicitly take input (string). Rotate that number of times % in steps of 90 degrees. Implicitly display ``` [Answer] ## Python 3, ~~64~~ ~~51~~ 48 bytes Saved 6 bytes thanks to xnor. Saved 7 bytes thanks to Lynn. Saved 3 bytes thanks to DSM and Morgan from **so**python. ``` lambda c,s:'\n'[c<'?':].join(s[::1|-(c in'<^')]) ``` The function accepts one of the characters from `<>^v` as the first argument and the string that needs to be rotated as the second argument. --- Here's a more readable version: ``` lambda c, s: ('\n' if c in '^v' else '').join(s[::-1 if c in'<^' else 1]) ``` [Answer] ## Haskell, 57 bytes ``` f">"=id f"<"=reverse f"v"=init.((:"\n")=<<) f _=f"<".f"v" ``` Usage example: `f "v" "ABC"` -> `"A\nB\nC"`. Direction `>` is the idendity function, `<` reverses it's argument, `v` appends a newline to each character in the string and drops the last one and `^` is `v` followed by `<`. [Answer] # Japt, 9 bytes ``` VzUc %B+1 ``` Inspired by @DonMuesli's answer, although I just noticed the CJam one uses exactly the same technique. [Test it online!](http://ethproductions.github.io/japt?v=master&code=VnpVYyAlQisx&input=Il4iICJBQkMi) ### How it works ``` // Implicit: U = arrow char, V = text Uc %B // Take the char code of U, mod 11. // This converts ">", "v", "<", and "^" to 7, 8, 5, and 6, respectively. Vz +1 // Add one and rotate V by 90° clockwise that many times. ``` [Answer] ## CJam, 13 bytes ``` l(iB%{W%z}*N* ``` Input is the orientation character followed directly by the string to be rotated. [Test it here.](http://cjam.aditsu.net/#code=l(iB%25%7BW%25z%7D*N*&input=%3EABC) ### Explanation Yay for modulo magic. Taking the four characters modulo 11 maps them to: ``` > 7 v 8 < 5 ^ 6 ``` These are all distinct modulo 4 and more importantly they are neatly increasing: `3, 0, 1, 2`. That means we can just use the result of the `mod 11` to determine how often to rotate (without needing an explicit `mod 4`, since four rotations are a no-op anyway). We'd normally have to offset these numbers by 1, such that `>` actually yields `8` and becomes a no-op, but the way I'm rotating them, actually reverses the string on the first application such that we always get one rotation for free. ``` l e# Read input. (i e# Pull off the first character and convert to its character code. B% e# Modulo 11. { e# That many times... W% e# Reverse... on the first iteration this reverses the string. Afterwards e# we'll have an Nx1 or 1xN grid of characters on the stack, where e# this reverses the rows instead. z e# Transpose. On the first iteration, this simply wraps the string in e# array, turning it into a grid without changing its orientation further e# beyond the reversal that just happened. On subsequent iterations, a e# transpose combined with reversing the rows rotates the grid 90 degrees e# clockwise. }* N* e# Join with linefeeds. ``` [Answer] # Pyth, ~~17~~ 15 ``` jWgz\^_W}z"<^"w ``` [Try it here](https://pyth.herokuapp.com/?code=jWgz%5C%5E_W%7Dz%22%3C%5E%22w&input=%5E%0AHello%2C+World%21&debug=0) or run the [Test Suite](https://pyth.herokuapp.com/?code=jWgz%5C%5E_W%7Dz%22%3C%5E%22w&input=%5E%0AHello%2C+World%21&test_suite=1&test_suite_input=%3C%0AHello%2C+World%21%0A%5E%0AThis+is+text.%0Av%0ATokyo%0A%3C%0A%3E%3E%3E&debug=0&input_size=2) 2 bytes saved thanks to Jakube! Alternatively using mod tricks: ``` @s_MBjBz)h%Cw11 ``` [Try it here](https://pyth.herokuapp.com/?code=%40s_MBjBz%29h%25Cw11&input=Hello%2C%20World%21%0A%3C&debug=0). [Answer] # Julia, 51 bytes ``` f(d,s)=join(d∈"<^"?reverse(s):s,d∈"^v"?"\n":"") ``` This is a function that accepts a `Char` and a string and returns a string. Let `d` be the character denoting the direction and `s` be the string. If `d` is left or up, we use the reverse of `s`, otherwise we use `s` as given. We construct a separator as the empty string if `d` is left or right, or a newline if `d` is up or down. The pass the string and the separator to `join`, which will insert the separator between each character of the string and return a string. [Verify all test cases online](http://goo.gl/50zYRB) [Answer] # Bash + GNU Utilities, 67 ``` (egrep -q '>|v'<<<$1&&cat||rev)|(egrep -q '<|>'<<<$1&&cat||fold -1) ``` [Answer] ## JavaScript (ES6), ~~76~~ ~~67~~ 65 bytes ``` (a,b)=>(/v|>/.test(a)?[...b]:[...b].reverse()).join(a>`>`?` `:``) ``` Port of @Alex A.'s Julia answer. Edit: Saved 9 bytes thanks to @ETHproductions. Saved two bytes separately thanks to @edc65. [Answer] # Perl, ~~54~~ 51 + 1 = 52 bytes ``` @.=<>=~/./g;@[[email protected]](/cdn-cgi/l/email-protection)/[<^]/;$,=$/x/[v^]/;say@. ``` Requires the `-n` flag and the free `-M5.010`|`-E`. Takes input as the following: `direction\nline`: ``` $ perl -nE'@.=<>=~/./g;@[[email protected]](/cdn-cgi/l/email-protection)/[<^]/;$,=$/x/[v^]/;say@.' <<< $'^\nhello' o l l e h ``` I like that `$/x/[v^]/` looks like a substitution. How it works: ``` # -n read first line into $_ @.=<>=~/./g; # Read next line and split @[[email protected]](/cdn-cgi/l/email-protection)/[<^]/; # Reverse `@.` if matches # `<` or `^` $,= # An array will be concatena- # ted with the value of # `$,` when printed. $/ # Contains a newline /[v^]/ # boolean x # "\n" x 1 -> "\n" # "\n" x 0 -> "" say@. # Print the array ``` [Answer] ## PowerShell, 84 bytes ``` param([char]$a,$b)($b[($c=$b.length)..0],$b[0..$c])[$a%7-eq6]-join("","`n")[90-lt$a] ``` This is going to be complete gibberish to people not familiar with PowerShell. Let's go through it. Takes input `param([char]$a,$b)`, with an explicit cast to character for `$a`. The rest of the program is one statement. We'll start with the first half, up to the `-join`. We're creating a new dynamic array `(...,...)` and indexing into it with `$a%7-eq6`. The ASCII values for `v` and `>` are `116` and `62`, respectively, and `116%7 = 62%7 = 6`, and those are the two directions that "increase" down and to the right. So, if that `-eq` is `$true`, we'll take the second value, which is `$b[0..$c]`, or *an array of the characters of `$b` up to the end*. We get the value `$c` from the first value, `$b[($c=$b.length)..0]`, which gets selected if the input char is `^` or `<` (i.e., so it goes through the string backwards). Important to note is that even if the second value is selected, the `$c` value is still calculated and stored, so we can re-use it as a shortcut like this. So, we've now got an array of characters either going forwards or backwards. We then `-join` those characters together with the result of another dynamic array index. This time we're selecting based on whether the ASCII value for `$a` is below `90` (really lots of values would work, I selected this one just because). Since `>` and `<` both have a value below `90`, the `-lt` is `$false`, so we select the empty string `""`, and thus the char-array is simply concatenated. Otherwise, we select the newline character `"`n"` to join the char-array together with newlines. This resultant string is left on the pipeline, and output is implicit. **Example** ``` PS C:\Tools\Scripts\golfing> .\orthogonal-orientation.ps1 "^" "TimmyD" D y m m i T ``` [Answer] # C, ~~123~~ ~~119~~ ~~117~~ 114 bytes Golfed: ``` f(char*d,char*a){char*b=a,c=*d%21,s[3]={0,c&8?10:0};while(*++b);while(*s=c&4?*a++:*--b)printf(s);if(c&16)puts(b);} ``` Test program, with explanations & somewhat ungolfed code: ``` #include <stdio.h> #include <stdlib.h> // c c%21 // < 10010 => if(c&8), vertical; if(c&16), horizontal // > 10100 => if(c&4), backwards // ^ 01010 // v 01101 int f(char*d,char*a){ char *b=a,c=*d%21,s[3]={0,c&8?10:0}; while(*++b); // b = a + strlen(a) - 1; this is shorter while(*s=c&4?*a++:*--b)printf(s); if(c&16)puts(b); // single trailing newline if horizontal } int main() { char *c="<>^v"; for(;*c;c++) { printf("--- %c ---\n", *c); f(c,"hello world!"); } return 0; } ``` Tips welcome! [Answer] # [Retina](https://github.com/mbuettner/retina), 60 bytes Needs golfing... ``` $ ¶ +`^([<^].*)(.)(¶.*) $1$3$2 ¶ . $&¶ +`([<>].*)¶ $1 ^.¶? ``` Input is all as one string, e.g. `^ABC`. * If `^` or `<`, reverse the string * Insert newlines after every character * If `<` or `>`, remove the newlines [Try it online.](http://retina.tryitonline.net/#code=JArCtgorYF4oWzxeXS4qKSguKSjCti4qKQokMSQzJDIKwrYKCi4KJCbCtgorYChbPD5dLiopwrYKJDEKXi7Ctj8K&input=XkFCQw) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 15 bytes ``` ⌽∘⍉⍣(11|⎕UCS⍞)⍪ ``` `⍪` make string into 1-column table `⍣(‍`…`)` repeat (*n*) times `⍞` get string input `⎕UCS` convert to UCS code point `11|` division rest when divided by 11 `⌽∘⍉` rotate -90° (flip-transpose) Alternate method (same length): ``` ⌽∘⍉⍣('<^>v'⍳⎕)⍪ ``` `⎕` get evaluated input (so one must input, e.g. '^' or the name of a program/variable that returns the desired character) `'<^>v'⍳` index into the string [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` zVc %BÄ ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=elZjICVCxA&input=IkFCQyIKIl4i) [Answer] # Jolf, 22 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=LuKAmElfSc6zwp9HSUVfzrPigJkgaSI-PHZeImk) You should replace `ƒ` with `\x9f`. Takes the sting, then the directional character. ``` .‘I_IγƒGIE_γ’ i"><v^"i ‘ golfy array I the input _I input reversed ƒGIE split by "" and join by newlines γ γ = that _γ gamma reversed . _i"><v^"i get the respective index ``` [Answer] # JavaScript ES6, ~~91~~ ~~83~~ 84 bytes ``` (a,b)=>[b,(c=[...b].reverse()).join``,[...b].join` `,c.join` `]["><v^".indexOf‌​(a)] ``` Constructs the necessary strings and obtains the index of which `a` lies in. `indexOf` is used because `^` is a regex token. Thanks to ETHproductions for the bug fix and shaved bytes! [Answer] # JavaScript (ES6) 71 ``` (a,b)=>([...b].map(c=>(a>'A'?c+=` `:0,r=/v|>/.test(a)?r+c:c+r),r=''),r) ``` **Test** ``` F=(a,b)=>([...b].map(c=>(a>'A'?c+=` `:0,r=/v|>/.test(a)?r+c:c+r),r=''),r) console.log=x=>O.textContent+=x+'\n'; for(d of '<>^v') console.log(d+'\n'+F(d,'ABCDE')+'\n') ``` ``` <pre id=O></pre> ``` [Answer] # Perl 5, 67 bytes 66 plus one for `-p` ``` $_=reverse if/^[<^]/;$&?s/.$//:s/.//;$&=~/[v^]/&&s/(.)(?=.)/$1\n/g ``` The input is a single string whose first character defines the orientation. [Answer] # [DUP](https://esolangs.org/wiki/DUP), 48 bytes ``` [`5/%$$a:4<&[1$][1_]?\1-[$;$][,^+a;2>[' ,][]?]#] ``` `[Try it here.](http://www.quirkster.com/iano/js/dup.html)` Anonymous lambda that takes both argument and STDIN input. Usage: ``` 0"asdf"[`5/%$$a:4<&[1$][1_]?\1-[$;$][,^+a;2>[' ,][]?]#]! {make sure to put one of <>^v in STDIN} ``` # Explanation ``` [ ] {lambda} `5/%$$a: {store STDIN char (mod 5) to a} 4<& {is 0<a<4?} [ ][ ]? {conditional} 1$ {if so, push 2 1's} 1_ {otherwise, push -1} {determines whether to output in reverse or not} \1- {swap, -1} [ ][ ]# {while loop} $;$ {if there is a char at index} , {output that char} ^+ {increment/decrement index} a;2> {check if a>2} [ ][]? {conditional} '\n, {if so, output newline} ``` [Answer] ## Seriously, 41 bytes ``` ,' 9uc#;+"? R #'{}j #R'{}j"fs,"><v^"í@E£ƒ ``` Takes the string as the first input and the direction (`><v^`) as the second input. [Try it online!](http://seriously.tryitonline.net/#code=LCcgOXVjIzsrIj8gUiAjJ3t9aiAjUid7fWoiZnMsIj48dl4iw61ARcKjxpI&input=IkFCQyIKPA) [Answer] # D, 198 bytes ``` import std.stdio,std.array,std.algorithm;void main(string[]a){auto x=a[2].split("");char[]y;if(canFind(["^","<"],a[1]))x.reverse;if(canFind(["v","^"],a[1]))y=x.join("\n");else y=x.join("");y.write;} ``` :c --- Less golfed: ``` import std.stdio; import std.array; import std.algorithm; void main(string[]a) { auto x=a[2].split(""); string y; if(canFind(["^","<"],a[1])) x.reverse; if(canFind(["v","^"], a[1])) y=join(x,"\n"); else y=join(x,""); y.write; } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` C:½›₃[√⌈₂ßṘ⁋|₃ßṘ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C%3A%C2%BD%E2%80%BA%E2%82%83%5B%E2%88%9A%E2%8C%88%E2%82%82%C3%9F%E1%B9%98%E2%81%8B%7C%E2%82%83%C3%9F%E1%B9%98&inputs=%3E%0AHello&header=&footer=) ``` C: # Get charcode, dupe for later use ½›₃[ # If C/2 + 1 % 3 == 0 (`^v`)... √⌈₂ # Is ceil(√C) is even? ßṘ # If so, reverse ⁋ # Join by newlines | # Else... ₃ # Is C divisible by 3? ßṘ # If so, reverse ``` ]
[Question] [ This challenge is inspired by the AoC 2020, [Day 14 - Part II](https://adventofcode.com/2020/day/14#part2), created by [Eric Wastl](https://twitter.com/ericwastl) and [his team](https://adventofcode.com/2020/about), which asks to output the possible binary values from a bitmask. Let's say we've a bitmask like `"10X0X0"`, then we've to find the possible binary values that can be generated by replacing an `X` with either `0` or `1`. Here I've taken `X`, but you could take anything except `0` and `1`, of course. So, the possible binaries are `["100000", "100010", "101000", "101010"]`. When each of them are converted in decimal, then these are `[32, 34, 40, 42]` respectively. And, finally the sum is `148`. # Test cases ``` INPUT: "X" ["0", "1"] [0, 1] OUTPUT: 1 INPUT: "0" OUTPUT: 0 INPUT: "1" OUTPUT: 1 INPUT: "1X0" ["100", "110"] [4, 6] OUTPUT: 10 INPUT: "1X0X1" ["10001", "10011", "11001", "11011"] [17, 19, 25, 27] OUTPUT: 88 INPUT: "X0X0X0X" ["0000000", "0000001", "0000100", "0000101", "0010000", "0010001", "0010100", "0010101", "1000000", "1000001", "1000100", "1000101", "1010000", "1010001", "1010100", "1010101"] [0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85] OUTPUT: 680 INPUT: "1X1X1X1X1X1X1X1X1X1X1" OUTPUT: 1789569024 INPUT: "1X01X01X01X01X01X01X01X01X01X01X01X0" OUTPUT: 201053554790400 INPUT: "X000X000X000X000X000X000X000X000X000X000X000X000" OUTPUT: 307445734561824768 INPUT: "101" ["101"] [5] OUTPUT: 5 INPUT: "XXX" ["000", "001", "010", "011", "100", "101", "110", "111"] [0, 1, 2, 3, 4, 5, 6, 7] OUTPUT: 28 ``` # Rules * It is guaranteed that \$ 0 \leq \text{count}(X) \leq 12 \$ and \$ 1 \leq \text{length(mask)} \leq 48 \$. * Input can be either a string, or an array of chars (non-empty). * I have chosen `X` in bitmask, however you can replace it with any other character of your choice. * Output will be the sum of the binaries in decimal. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes will win! --- [Sandbox link](https://codegolf.meta.stackexchange.com/a/20552/83605). [Answer] # [Python 2](https://docs.python.org/2/), 61 bytes ``` k=n=0 for c in input():n=n*2+-ord(c)%3;k+=c>"1" print(n<<k)/2 ``` [Try it online!](https://tio.run/##lYzNCsIwEITv@xRhQUisP0m91cbnyK3ENGJp3YZQqT59TcSjIDIzC7vsfOE5XUcql47CfdKDvZ1bW0U7N@8DF7vow2Cd52hwgw0KmK/d4Jmq/MM7RFx6TVrCZYzMsY7Yp1eRpnVZbMfYcidWh2NfaHdChRBiRxOnuu7FvlwywYAEBcrIHKMgjay0fVH@@WlQMmGMSSgp/8kL "Python 2 – Try It Online") Implements this algorithm: 1. Convert the input from binary, treating X as \$\frac{1}{2}\$. 2. Double the result for each X in the input. Why does this work? If X appears \$k\$ times in the input, we're adding up \$2^k\$ near-copies of its binary value. Among these near-copies, each X in any position appears as 0 half the time and 1 half the time for an average of \$\frac{1}{2}\$, so we can treat X as the digit \$\frac{1}{2}\$. In the code, we actually convert `0,X,1` to doubled values `0,1,2`, then halve the result before doubling for `X`'s. And, we use `_` for `X`, since we're allowed to use a different character -- anything with the same ASCII code modulo 3 would work, such as the digit `2`. **63 bytes** ``` lambda s:(reduce(lambda n,c:2*n+-ord(c)%3,s,0)<<s.count('_'))/2 ``` [Try it online!](https://tio.run/##lYxBCsMgFET3niKborY21XQn6T1cFII1hghGRQ2hp7emdFkoZWY@/GF44Zln77oy3e7FyuUxyiZxFPW4Ko0@hSOKd0d3Ovs4IoUPV5IIxX2fWuVXlxEcIMaXrmyzsbphPETjcjOhKLfBuLBmhNuog5UVCQUk730RgAIGmKB7BAP17KrfF@2bnwaMVowQFUXpP3kB "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~[56](https://codegolf.stackexchange.com/revisions/216384/1)~~ 55 bytes ``` n!(a:x)|a<'X'=(2*n+read[a])!x|m<-4*n=m!x+1!x n!x=n (0!) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P09RI9GqQrMm0UY9Qt1Ww0grT7soNTElOjFWU7GiJtdG10QrzzZXsULbULGCK0@xwjaPK81Ww0BR839uYmaebUFRZl6JSpqSYYSh0n8A "Haskell – Try It Online") ## Explanation Start with a simple recursive algorithm to convert binary to an integer: ``` n!(a:x)=(2*n+read[a])!x n!x=n (0!) ``` From here we add an extra rule if we hit an `X` which just adds the results for the X being 0 and 1 together: ``` n!('X':x)=n!('0':x)+n!('1':x) n!(a:x)=(2*n+read[a])!x n!x=n (0!) ``` We can unroll the applications in that: ``` n!('X':x)=(2*n)!x+(2*n+1)!x n!(a:x)=(2*n+read[a])!x n!x=n (0!) ``` We can move a `2*n` over to the other side since `(!x)` is affine ``` n!('X':x)=(4*n)!x+1!x n!(a:x)=(2*n+read[a])!x n!x=n (0!) ``` From here we combine the pattern matches to save bytes. [Answer] # JavaScript (ES6), 55 bytes ``` f=(s,g=d=>f(s.replace('X',d)))=>1/s?+('0b'+s):g(0)+g(1) ``` [Try it online!](https://tio.run/##pZExb4MwEIX3/AorC7Yg4Qw2NpVIJ4buHVhdMISKYIRJlX9PQe0ESKGqzyfLkr97T8@f6kvZvK@74dSaQo9jmWDrVUmRXEpsz73uGpVr7GSOVxBCkgv17auLHfhwXEteKgzErTAlY25aaxp9bkyFS3zMjoSgHcv3ET0sWNjPwpKl/9Cl2T7lmYUNONsjPsFSLuGJnespPsGR3JDeqI1Zs28hYx7FELAN/0/3PHMaEgAFHnLORAwM1naA7o2Rr4LIsr1sIA@H6Xi/1haZVqNeD/e@tUi1SHVdbx71TQ21aT2kLBquGtn7DelHrnXxc@96ndd2eoFMid7SND0JztY/A/CX/o0oBMEYFyHjEZUBE5EcvwE "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function s, // taking the input string s g = d => // g is a helper function taking a digit d f( // and doing a recursive call to f s.replace('X', d) // with the first 'X' in s replaced with d ) // ) => // 1 / s ? // if s looks like a number (i.e. does not contain any 'X'): +('0b' + s) // convert it from binary to decimal : // else: g(0) + // invoke g a 1st time to replace the first 'X' with '0' g(1) // invoke g a 2nd time to replace the first 'X' with '1' ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 38 ``` echo $[`eval echo +2\#${1//X/{0,1\}}`] ``` [Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYYq2Qks@loFCcWqKgq6ugEuQa4BP5PzU5I19BJTohtSwxRwHM0TaKUVapNtTXj9CvNtAxjKmtTYj9n5Kfl/o/gsuAy5DLMMIAhCMMuYAECAJ5WCBIDUEENMLAgBTMZWgAtDciggsA "Bash – Try It Online") [Answer] # [J](http://jsoftware.com/), 47 bytes ``` 1#.#.@(]`(_ I.@E.[)`[}"#.[:#:@i.@(**2&^)1#._&=) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1lPUcNGITNOIVPPUcXPWiNROia5WU9aKtlK0cMoFSWlpGanGaQHXxaraa/zW5/Jz0FEjUhV@PEURLHEwxV2pyRr6CoYKtQppCPIRjAOYYQDgWFmCeoUI8UDxewRAiagQRjQdBqAnmFpamZpYGRiYQ9RUgxcTg/wA "J – Try It Online") Not super happy with this one... [Answer] # [R](https://www.r-project.org/about.html), ~~156~~ ~~142~~ ~~78~~ ~~61~~ ~~56~~ ~~52~~ ~~51~~ 50 bytes In the entry of the bitmask, `2` replaces `X`. Thanks to [Giuseppe](https://tio.run/##JYzBasMwEETv@gpBMeymMtndY4j6HQVjg2xLjeJGEYoNhdJvdxUyh3kzMEzZ37aH16LDvehPFewetjSt8Z7Amdmm6eIKOMTfbPk0t6xG65pjwzTkprpa7LdPX@sFruc2d@MH9@@MytubW0v8gdHMRoYFVb2HqGPSdFrQd9cu9qa3E4RzW3wGrqt4FDR0CKge2w38QYaMf3sAFpL6@QwvED0hVa8qwixCxMS4/wM "R – Try It Online"), came a reduction in [unnecessary brackets in an earlier version](https://tio.run/##JY3RioMwEEXf8xWBRZgpEWfmsZj9jgWxEDXZprappAqFst/upvS@nHvhwsn71/bwWnS4Z/2jgt3DlsY13hM4M9k0nl0Gh/haLB8nNVhXVXBta6bTglVTesOEarZXn37XM1zaeumGb@5ReXtza45PGMxk5DSjigFmLCKIOibNxxl9d@lib3o7Qmjr7Bfgco2NoKFDQPXYbuAPIEWGjfztAVhIGNW7fED0hpR8pgizCBET4/4P "R – Try It Online") recreating the binary duplications. However, a more condensed version can be found by realising that the sum is the sum of the inverse of the non-zero digits, times 2 to the power of the number of 2's, ie                                         [![enter image description here](https://i.stack.imgur.com/tNR31.gif)](https://i.stack.imgur.com/tNR31.gif) which actually happens to be [the solution earlier worked out](https://codegolf.stackexchange.com/a/216371/85958) by [xnor](https://codegolf.stackexchange.com/users/20260/xnor). With improvements [from Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) achieving the same score as this earlier solution and more from [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)! ``` function(x)2^sum(a<-x>1)*rev(x/4^a)%*%2^(seq(x)-1) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQtMorrg0VyPRRrfCzlBTqyi1TKNC3yQuUVNVS9UoTqM4tRCoRtdQ83@aRrKGoY6BjhEEa2pygUSMdMAQyoPIg1QYQkUMgGwDuCwcamr@BwA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Y1ÝI2¢ãδ.;CO ``` Uses `2` instead of `X`. [Try it online.](https://tio.run/##yy9OTMpM/f8/0vDwXE@jQ4sOLz63Rc/a2f//f0MDIyAEAA) **Explanation:** ``` 1Ý # Push the list [0,1] I2¢ # Count the amount of 2s in the input-string ã # Take the cartesian product of [0,1] with this count δ # Map over each inner list of 0s and 1s: Y .; # Replace every 2 in the (implicit) input-string one by one with the 0s # and 1s in the current list C # Convert each binary string to a base-10 integer O # Sum the list together # (after which the result is output implicitly) ``` --- Fun alternative that's unfortunately a byte longer (**13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**): ``` TIgãʒøþ€ËP}CO ``` Uses `X`. [Try it online.](https://tio.run/##yy9OTMpM/f8/xDP98OJTkw7vOLzvUdOaw90Btc7@//8bGkQAIQA) **Explanation:** ``` T # Push 10 Ig # Push the length of the input-string ã # Take the cartesian product of "10" with this count ʒ # Filter this list of binary strings by: ø # Zip/transpose it with the (implicit) input, creating pairs þ # Remove all "X" from each pair by only leaving digits €Ë # Check for each if all digits are the same # (this checks if the 1s and 0s are at the same positions between the # current binary string and input; and since we've removed all "X" those # single digits are truthy by default) P # Check if this is truthy for all of them with the product }C # After the filter: convert any remaining binary string to a base-10 integer O # Sum the list together # (after which the result is output implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), 53 bytes ``` sum.foldl(%)[0] l%c=[2*a+1-read[b]|a<-l,b<-"01",b/=c] ``` [Try it online!](https://tio.run/##lUzLCsIwELz7FSFY8NHo1nPzCd4DMYdt2mjppoZWb367sa@jIDKzM8wyzA37piKKTl5i//QHd6eSNslWg1lRYqU@7XCfia7CUhfmhbmgtMgFh4ynxVFaEz3WrfQYzix0dftgazYE5pjmiqeMwyjZJAoWU1MefMT8@4Kl/JNTD@ZJpeZlgH@Om/i2jvDaR2FD@AA "Haskell – Try It Online") Implements the spec somewhat directly, using a modified from-binary conversion that works on lists of digits to produce lists of possible outcomes. Any character can be used for `X` except of course for `0` and `1`. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` *ΠfI¹ḋm?I\ε ``` [Try it online!](https://tio.run/##yygtzv7/X@vcgjTPQzsf7ujOtfeMObf1////0YY6RjpE4VgA "Husk – Try It Online") Port of [xnor's approach](https://codegolf.stackexchange.com/a/216371/95126). Input is list of binary digits (`0` or `1`), with `2` to represent the bitmask. [13 bytes](https://tio.run/##yygtzv7//9By/fxzC9I8H@7ozrX3jDm3NeX///@GRlggAA) to accept input as an integer instead of a list. ``` * # multiply Π # product of fI¹ # non-zero elements of input ḋ # by binary number with digits given by m # mapping over all digits of input ? ε # if digit is equal to at most 1 I # leave it alone \ # otherwise take reciprocal ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 35 bytes ``` s/X/{0,1}/g;map$\+=oct"0b$_",glob}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/79YP0K/2kDHsFY/3To3sUAlRts2P7lEySBJJV5JJz0nP6m2@v//CAMw/JdfUJKZn1f8X9fXJ7O4xMoqtCQzx7a4NPe/bkEOAA "Perl 5 – Try It Online") [Answer] # [MATLAB](https://www.mathworks.com/products/matlab.html), 55 46 bytes ``` @(x)2.^(nnz(x):-1:1)*mod(x'*2,3)/4*2^nnz(x>49) ``` Inspired by [the Python solution of xnor](https://codegolf.stackexchange.com/a/216371/91877). But here we don't use a loop, we work with array operators. Thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) for replacing the sum of element-wise products by the dot product (-5 bytes). Instead of `X`, it expects `_` as input: ``` ans('1_0_1') ans = 88 ``` etc. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 67 bytes ``` Distribute@StringReplace[#,"X"->"0"+"1"]/.s_String:>s~FromDigits~2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yWzuKQoM6m0JNUhGMjISw9KLchJTE6NVtZRilDStVMyUNJWMlSK1dcrjocosLIrrnMrys91yUzPLCmuM1L7HwAULolW1rVLc1COVasLTk7Mq6vmAmrX4QJqBxKGYCLCAEpFgPlAGgQhYlggVDFBBDHLwIAUDDbbAOKMiAglrtr/AA "Wolfram Language (Mathematica) – Try It Online") -1,2,...50...61 bytes from @att [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 37 bytes ``` {(*/(+/t)#2)*{y+2*x}/x-48+1.5*t:x=50} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWkNLX0Nbv0RT2UhTq7pS20irola/QtfEQttQz1SrxKrC1tSg9n@1RoW1QppChWatuoaSkZK1gpIBiDAEE0YGUMoIzAfSIAgRwwKhigkiiFkGBqRgsNkGEGcYGSlp/gcA "K (oK) – Try It Online") Inspired by [xnor's Python solution](https://codegolf.stackexchange.com/a/216371/75681). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (9?) 12 bytes 9 if we may accept a list of integers (e.g. `"0X1X0"` as `[0,2,1,2,0]`) - remove the leading `V€µ`. ``` V€µẹ2ŒPṬạḂḄS ``` A monadic Link accepting a list of characters from `"012"` (`'2'` representing an unknown bit) which yields the sum. **[Try it online!](https://tio.run/##y0rNyan8/z/sUdOaQ1sf7tppdHRSwMOdax7uWvhwR9PDHS3B////VzI0wgKVAA "Jelly – Try It Online")** ### How? ``` V€µẹ2ŒPṬạḂḄS - Link: list of characters, S e.g. "022001" V€ - convert (S) to a list of integers [0,2,2,0,0,1] µ - start a new monadic chain, f(A=that) ẹ2 - indices of 2 [2,3] ŒP - power-set [[],[2],[3],[2,3]] Ṭ - un-truth [[],[0,1],[0,0,1],[0,1,1]] Ḃ - mod-2 (A) [0,0,0,0,0,1] ạ - absolute difference [[0,0,0,0,0,1],[0,1,0,0,0,1],[0,0,1,0,0,1],[0,1,1,0,0,1]] Ḅ - convert from binary [1,17,9,25] S - sum 52 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 71 bytes ``` c,s;f(char*m){for(c=1,s=0;*m;88-*m++||(s++,c*=2))s+=s+=*m==49;c=c*s/2;} ``` [Try it online!](https://tio.run/##dY5NCoMwEIX3nkKEQn4UE1EbCbmHi25krFZoYjHtSj27lZqdKTOLGd775g0kPcD2MXbozb0Nn6Ppww1iKzsEj2YiGs/dOCFQPLaKSaKlEAnRlC4LspTGQFSGsaVqb6KVyisJCohNM7lug3mHuhlMiPAcvKZ97VB0aW8mivehjjCWacrPCjsUdlb4X4bXjuLMK9YOFcLzCfvVYSiF94CnXN5VVEVZsSz3YMyZCk9o7QIzEazbFw "C (gcc) – Try It Online") * Saved 2 bytes thanks to @Ceilingcat * Works only for small numbers (int) added unsigned long in header to test 1X1X1X1X1X1X1X1X1X1X1 We iterate a char array: `s` is sum `c` is number of masks, initially 1 ``` s+=*m==49 - we add 1 if we have '1' s*=2 - then we multiply by 2 88-*m++|| - if we have a 'X' (s++,c*=2) - we add 1 and we double number of possible masks. c=c*s/2 - finally we multiply sum by c and divide by 2 because we multiplied sum one time more than needed. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~27~~ 20 bytes ``` {_2/0.5^x,&+/^x:.'x} ``` [Try it online!](https://ngn.codeberg.page/k#eJyVU1FP2zAQfvevsKyJbVpo7pzYceJfsJdtDyBVqsooJYWI0rCmSEFo++27JDY2WyVEHMvnz+cvd/ddNtXzT5nCTF30ycmX9KKvZh/734wdqucPi6c/+2rDOe/tZXtnP11uVs3W9vbJ7j8vB59FIriwuBwtEBYmCx0mkBOI4G1OB8aMO9oMQ1ht/PGRQZcLUypdgsw9yZuvsBIQVKZUXpSQA7gPArxnCptBkeeqyHKl0ci80FPkCBSWmjg5JSAJZixlt4fDQ1el6bq9rm/a7WbWHVbru7pf3652N/Vs3d6nvx7r7tC0uy6VqDNdpg9t1zVX2/r0qtmt9k3dnXaP9yljX7/9OD+ruJgLtqC6JpxKumQLSDjV9fv52XiKwQ/ECwoBRXHMF+cwsCJMvAgDc55wHTHDK/c5uguU+XCFVnR3wRs4BogFRVgmXCqaRSA0JsoJxjFmNj0DxWShNzGg6FEMvhh8Mfii82VjrM4ZAzEGYgzEGIgRoiQx+E7EToCEU7EoP9Q0KV9JoCRUDzUkXBuaVANDuCHcEG5UqAU1fFzdIyOS7aX7Xwny5hsY/vkVYhkA3jMD5f//RRQcuF4ZyxVlraIvz734TrZxwWmHXilXed+j4xJpIBOeeSVIiKjXJIXD/gJO3gp4) Modeled after [@Galen Ivanov's oK answer](https://codegolf.stackexchange.com/a/216428/98547). Uses `" "` in place of `"X"` in the input. * `x:.'x` convert input string to a list of integer digits, updating variable `x` (spaces in the input become `(::)`s, i.e. null functions) * `&+/^` generate n 0's, where n is the number of blanks in the input * `x,` append these 0's to the end of the digit-ified input * `0.5^` fill nulls with 0.5's * `_2/` convert from base-2 and take the floor [Answer] # [Stax](https://github.com/tomtheisen/stax), 20 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` år╢T>∩E%>►ΣD"╬@☼≡ ╫^ ``` [Run and debug it](https://staxlang.xyz/#p=8672b6543eef45253e10e44422ce400ff020d75e&i=X%0A0%0A1%0A1X0%0A1X0X1%0AX0X0X0X%0A1X1X1X1X1X1X1X1X1X1X1%0A1X01X01X01X01X01X01X01X01X01X01X01X0%0AX000X000X000X000X000X000X000X000X000X000X000X000%0A101%0AXXX&a=1&m=2) Shortened from 32 by borrowing the idea from Kevin Cruijssen's answer. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~66~~ 59 bytes ``` @(x)(t=0:2^nnz(x)-1)*all(abs(dec2bin(t)*2-mod(2*x,99))<2,2) ``` Uses character `b` instead of `X`. Runs out of memory for the two longest test cases. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTo8TWwMooLi@vCsjRNdTUSszJ0UhMKtZISU02SsrM0yjR1DLSzc1P0TDSqtCxtNTUtDHSMdL8n5ZflJtYopCTn5fOlaahnqSuCaIMIJQhlEoygDOSoGJAFgjCxLFAqJQBTEMSUPF/AA "Octave – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes ``` d[c=0;d/@#/. 2:>++c^0/2,2]2^c& d=FromDigits ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyU62dbAOkXfQVlfT8HIyk5bOznOQN9IxyjWKC5ZjSvF1q0oP9clMz2zpPh/QFFmXkm0sq5dmoNzRmJRYnJJalGxg3KsWl1wcmJeXTWXkpGSDpeSAYgwBBNGBlDKCMwH0iAIEcMCoYoJIohZBgakYLDZBhBnGBkpcdX@BwA "Wolfram Language (Mathematica) – Try It Online") Input a list of characters. Uses `2` instead of `X`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~41~~ 29 bytes ``` +%1`X 0$'¶$`1 1 01 +`10 011 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX1vVMCGCy0BF/dA2lQRDLkMuA0Mu7QRDAyAN5P3/D5QDChpGGIBwhCEXkABBLkOguoiICAA "Retina 0.8.2 – Try It Online") Link includes smaller test cases (code uses unary arithmetic so large numbers won't work on TIO). Explanation: ``` +%1`X 0$'¶$`1 ``` Repeatedly replace each line containing an `X` with two copies of that line, one with a `0` and one with a `1` in place of the first `X`. ``` 1 01 +`10 011 ``` Convert each line from binary to unary. ``` 1 ``` Take the sum and convert to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` I÷×↨Eθ⌕0X1ι²X²№θX² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzOvxCWzLDMlVSMkMze1WMMpsThVwzexQKNQR8EtMy9FQ8kgwlBJRyFTU1NHwQiIA/LLU4s0jHQUnPNLgYYAlSlFKEEkNTWt//83jABq@K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @xnor's algorithm. ``` θ Input string E Map over characters ⌕ Find index of ι Current character 0X1 In literal string `0X1` ↨ ² Convert from "binary" × Multiply by ² Literal `2` X Raised to power № Count of X Literal string `X` θ In input string ÷ Integer divide by ² Literal `2` I Cast to string Implicitly print ``` [Answer] # Scala, 61 bytes ``` _./:(Set(0)){(a,c)=>for(s<-a;d<-Set(c%2,c%3))yield s*2+d}.sum ``` [Try it online!](https://scastie.scala-lang.org/1UJUJrApT4mIcBYpBMOOtQ) Turns out `X`'s value of 88 is perfect for this algorithm. A simple binary-to-decimal conversion would look like this in Scala. `/:` is the fold operator. Starting with `0`, you multiply 0 by 2 and add the first digit. Then you multiply that by 2 again and add the next digit, and so on. ``` (0 /: listOfInts)((a, c) => 2 * a + c) ``` This is very similar, except now we're folding with multiple integers, and we're taking the sum at the end. In the lambda used for folding, `a` is all the accumulated sums, and `c` is the next character. For every sum `s` in `a` (`for(s<-a`), for every possible digit `d` that `c` could represent `d<-Set(c%2,c%3)`, we do the same thing as above - double the accumulator and add the next digit (`d`) to it, doubling the size of our set of accumulators each time. `Set(c%2,c%3)` works because `'0'%2` and `'0'%3` both return `0` and `'1'%2` and `'1'%3` both return `1`. Even though there's two of them, since we're using a `Set`, the duplicate is automatically removed. If, however, `c` is `'X'` (88), then `'X'%2` is `0` and `'X'%3` is `1`, giving us two different possible values, which is pretty nice. [Answer] # [Icon](https://github.com/gtownsend/icon), ~~85~~ 77 bytes ``` procedure f(s) b:=n:=0 c:=!s&{c=2&{c:=.5;n+:=1};b:=2*b+c}&\z return b*2^n end ``` [Try it online!](https://tio.run/##lVDbCsIwDH3vV8Q9jFandAVBKvVHvIDr4ixoJ12nqPjt2nU@@CCIOckJCYdDiNG1fT5PrtZYtg5hRxtGCqmsVJxoqQZNetdKBJJqMp3bkVT5Yx4EYliM9CNd3YhD3zoLxVBsLEFbfrgdt8ZSRiAEntFdoQmOy0QkGSS8ozyS4O8m4hx6h373BW/xz@y9OP@nojfvzxAiWUNZQ7w/BL0445EecOdpk8GUs6AaLyCInan2nhrrsUJHuyeyLJ8xxuJDXg "Icon – Try It Online") Uses `2` instead of `X`. Inspired by [xnor's Python solution](https://codegolf.stackexchange.com/a/216371/75681). [Answer] # [Factor](https://factorcode.org/), 46 bytes ``` [ [ 48 - >bin ] map [ bin> ] product-map sum ] ``` [Try it online!](https://tio.run/##bU6xCoMwFNzzFYe7YkOHYsG1uLiUTuKQpilKa4wvcZDSb09jLJ3Kwb1797jj3YV0I/nLuapPBR6KtHpiEK7LjCCrCIaUc4uhXjtYNc1KS2XZT2WGxtssHQSRWGyM4siquoCVJJzs2IsBSZ6svIvMOd9mHrFd@B8k7M0alLEabeg2vkGD/QEpymuvNy84QZdh@f6SrqadB7R@VZn/AA "Factor – Try It Online") Takes an array of charcodes (the character `2` is used for X) and returns the sum. Uses the built-in that generates the Cartesian product of multiple sequences. (I think it's already done in many answers.) ``` [ [ 48 - >bin ] map ! map '0', '1', '2' to "0", "1", "10" respectively [ bin> ] product-map ! compute cartesian product of all strings, ! and convert from binary to integer sum ! sum ] ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` 1#.2#.[:>@,@{#:@".&.> ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1jJT1oq3sHHQcqpWtHJT01PTs/mtycaUmZ@QrGCrYKqQpqBupQ7gGEK4BlGthAeEbGhkYGULFjKBiRkYwTYbmFpamZpYGRiYw1Vig@n8A "J – Try It Online") Exact same algorithm as [my Factor answer](https://codegolf.stackexchange.com/a/216552/78410). Takes a string, with `2` in the place of X. If a plain integer vector is allowed, remove `@".` to get 18 bytes. ``` 1#.2#.[:>@,@{#:@".&.> &.> NB. Apply to each character and enclose... #:@". NB. Eval and convert to binary (0 -> 0, 1 -> 1, 2 -> 1 0) @{ NB. Take cartesian product of all boxed vectors @, NB. Remove unnecessary outer array shape [:> NB. Unbox the result vectors 2#. NB. Convert from binary to integer for each row 1#. NB. Sum ``` ]
[Question] [ ### Challenge Given an [ASCII](http://en.wikipedia.org/wiki/ASCII) operator from the list below and a number n, draw an ASCII representation of the operator using that operator as the character with the line segments of the operator having length *n*. ### Input An ASCII character from the list `= + - x /` and an integer `n` where `n >= 1`. (I'm using `x` instead of `*` and `/` instead of `÷`, but you could use either one, whichever is easier). For `+` and `x`, you only have to handle odd numbers to avoid issues with alignment. ### Output An ASCII drawing of the operator composed of the character with segments of length n. Horizontal portions should have spaces between the characters to offset vertical/horizontal distance differences. ### Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Standard loopholes are forbidden. ### Examples Input: `+ 3` ``` + + + + + ``` Input: `= 4` ``` = = = = = = = = ``` Input: `= 10` ``` = = = = = = = = = = = = = = = = = = = = ``` Input: `- 2` ``` - - ``` Input: `/ 10` ``` / / / / / / / / / / ``` Input: `x 7` ``` x x x x x x x x x x x x x ``` [Answer] # [V](http://github.com/DJMcMayhem/V), ~~78, 72, 71, 68, 65, 63, 62~~, 61 bytes ``` Ç=ü-/Àé X ç^Ó/é Àä$ ç+/ÀÄM|ÀR+ ç=/Ä ç¯/lòhYpX çx/rxòl3Äjxlrx ``` [Try it online!](http://v.tryitonline.net/#code=w4c9w7wtL8OAw6kgWArDp17Dky_DqSDDgMOkJArDpysvw4DDhE18w4BSKyAKw6c9L8OECsOnwq8vbMOyaFlwWArDp3gvcnjDsmwzw4RqeGxyeA&input=PQ&args=NQ) As always, the neck-and-neck battle with 05AB1E is really fun! Since this contains non-ASCII characters, here is a hexdump: ``` 0000000: c73d fc2d 2fc0 e920 580a e75e d32f e920 .=.-/.. X..^./. 0000010: c0e4 240a e72b 2fc0 c44d 7cc0 522b 200a ..$..+/..M|.R+ . 0000020: e73d 2fc4 0ae7 af2f 6cf2 6859 7058 0ae7 .=/..../l.hYpX.. 0000030: 782f 7278 f26c 33c4 6a78 6c72 78 x/rx.l3.jxlrx ``` This does create leading spaces in the output for `=` and `-`, but [this seems to be allowed](https://codegolf.stackexchange.com/questions/98890/operator-ascii-art/98902#comment240335_98890). If this is not allowed, feel free to comment and I'll roll it back. # Explanation The "global command" (e.g. `ç`) applies a certain set of commands to every line that matches a certain regex. The syntax is ``` ç<compressed regex>/<commands> ``` This is the easiest way of simulating a conditional/switch statement. In my original answer, I simply created the entire ASCII-art on the right-hand side for each different character we need to search for. However, a lot of these outputs require similar commands. So I combined them. The first command ('Ç') is actually the inverse of the global command, it applies the command to every line *not* matching the regex. So the first command is: ``` Ç=ü- " On every line not containing an '=' or an '-' (e.g. inputs '/', '+', and 'x'): /Àé " Insert *n* spaces X " Delete one of them ``` The following command is for inputs '=' and '-'. These two are conveniently easy and similar. After this command, we need no more processing for `-`. ``` ç^Ó " On every line that starts with non-whitespace (e.g. every line not affected by our previous command): /é " Insert one space " Move back a character À " Make *n* copies ä$ " Of every character on this line ``` From here we just do some extra commands for each individual possible input. For `+`: ``` ç+/ " On every line containing a '+': ÀÄ " Make *n* copies of this line M| " Move to the first character of the middle line À " *n* times: R+ " Replace the next two characters with '+ ' ``` The command for equals is very straightforward. We just duplicate it with `Ä`. For `/`: ``` ç¯ " On every line containing a '/': /l " Move one character to the right ò " Recursively: h " Move one character to the left Yp " Make a copy of this line X " Delete one character ò " End loop (implicit) ``` The last one is the most complicated. It is basically a port of [this answer](https://codegolf.stackexchange.com/a/97402/31716). ``` çx " On every line containing a 'x': /rx " Replace the first character with an 'x' ò " Recursively: l " Move one char to the right 3Ä " Make 3 copies of this line j " Move down one line x " Delete one char l " Move one char to the right rx " Replace this char with an 'x' ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~81~~ ~~76~~ ~~74~~ ~~73~~ ~~70~~ ~~69~~ ~~68~~ ~~65~~ ~~64~~ ~~62~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes Currently **in war** with the [*V answer*](https://codegolf.stackexchange.com/a/98902/34388). I'm coming for you Dr. McMoylex :p. Also **in war** with the [*Pip answer*](https://codegolf.stackexchange.com/a/99231/34388). I'll be watching you Mr. DLosc. --- Code: ``` Ç6&"¹s<ú.s.Bívy¹'xQiÂðñ}, ¹×S)»¹'=Qƒ= ;ƒ¹})D¦»»Rû.c"#è.V ``` Or in a more readable form: ``` Ç6& "¹s<ú.s.Bívy¹'xQiÂðñ}, ¹×S)»¹'=Qƒ= ;ƒ¹})D¦»»Rû.c" #è.V ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w4c2JiLCuXM8w7oucy5Cw612ecK5J3hRacOCw7DDsX0sIMK5w5dTKcK7wrknPVHGkj0gO8aSwrl9KUTCpsK7wrtSw7suYyIjw6guVg&input=eAo3) [Answer] # Python 3, ~~304~~ ~~283~~ 278 bytes Simple enough, just makes a matrix of chars and applies the different operations based on which one it is. The `=` and `-` have trailing spaces if that's not too bad. EDIT: Thanks to @Shebang and @Rod for their suggestions which ended up saving 21 bytes! EDIT2: Thanks to @Artyer for saving 5 bytes! ``` t,s=input().split() s=int(s) r=range(s) b=[[' ']*s for x in r] exec(['for x in r:b[s//2][x]=b[x][s//2]=t','b=[t*s]'+'*2'*(t=='='),'for x in r:b[x][s-x-1]='+'b[x][x]='*(t=='x')+'t'][(t>'+')+(t in'x/')]) if t in'-=+':b=[[x+' 'for x in l]for l in b] print(*map(''.join,b),sep='\n') ``` [Answer] # JavaScript (ES6), ~~238~~ ~~225~~ ~~215~~ ~~202~~ 196 bytes ``` (c,n)=>[...Array(i=n*(c=="="?4:c+1-1?2:c<"-"?n+n:n+1))].map(_=>--i%(n+(c=='/'|c>'w'||n))?c>'w'?i%n&&~-i%(n+2)?" ":c:c<'-'?i%(n*2)-n&&(~i&1|(n/2^i/n/2))?" ":c:c=="/"?i%n?" ":c:i%2?c:" ":` `).join`` ``` Could probably be golfed, but it's a start. [Answer] # Scala, 275 bytes ``` (i,c)=>if(c<44){val b=(" "*(i-1)+"+\n")*((i-1)/2) b+"+ "*i+"\n"+b}else if(c<46)"- "*i else if(c<48)i-1 to(0,-1)map(" "*_+"/\n")mkString else if(c<62)"= "*i+"\n"+"= "*i else{val a=0 to i/2-1 map(x=>" "*x+"x"+" "*((i/2-x)*2-1)+"x"+" "*x+"\n")mkString;a+" "*(i/2)+"x"+a.reverse} ``` Usage: ``` val f:((Int,Char)=>String)=... print(f(10, '/')) ``` Explanation: The code tests for the ascii value of the char to choose the right way of generating the image. The ascii values of the operators in question are: `('+' -> 43), ('-' ->45), ('/' -> 47), ('=' -> 61), ('x' -> 120)` ``` (i,c)=> //define a function if(c<44){ //if c is a plus val b=(" "*(i-1)+"+\n")*((i-1)/2) //define the top/bottom part b as (i-1)/2 times (i-1) spaces, a plus sign and a newlineine b+"+ "*i+"\n"+b //return b, i times a plus and a space, a newline and b }else if(c<46) //if c is a '-' "- "*i //return "- " repeated i times else if(c<48) //if c is a '/' i-1 to(0,-1) //create a range from i-1 to 0 in steps of -1 map(" "*_+"/\n") //map each number to that number of spaces plus a "/" and a newline mkString //join them together else if(c<62) //if c is '=' "= "*i+"\n"+"= "*i //return "= " repeated i times, a newline and "= " repeated i times again else{ //if c if 'x' val a= //define a, which will be the top part, as... 0 to i/2-1 //a range from 0 to i/2-1 map(n=> //map each number n to " "*n //n spaces +"x" //plus an "x" +" "*((i/2-n)*2-1) //plus ((i/2)-n)*2-1 spaces +"x" //plus an "x" +" "*n //plus n spaces +"\n" //and a newline )mkString; //join them a+" "*(i/2)+"x"+a.reverse //return a, i/2 spaces, "x" and the reverse of a } ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), ~~62~~ ~~59~~ 56 bytes 55 bytes of code, +1 for `-S` flag. ``` [sXbRA_AEv-_aM,b(Y^aWR_Xb/2s)MyRVsX,b.aYaXbJsxyRL2x]@Aa ``` Note that this solution works with input of `÷` for division and `*` for multiplication, though it uses those characters to draw ASCII-art `/` and `x`, respectively. OP has [clarified](https://codegolf.stackexchange.com/questions/98890/operator-ascii-art#comment240883_98890) that this is okay. [Try it online!](http://pip.tryitonline.net/#code=W3NYYlJBX0FFdi1fYU0sYihZXmFXUl9YYi8ycylNeVJWc1gsYi5hWWFYYkpzeHlSTDJ4XUBBYQ&input=&args=w7c+NQ+LVM) ### How? Here's a [partially spaced and commented version](http://pip.tryitonline.net/#code=WyAgICAgICAgICAgICAgICAgQnVpbGQgYSBsaXN0IG9mIGFsbCBwb3NzaWJsZSBmaWd1cmVzOgogc1hiUkFfQUV2LV9hTSxiICAgMCAtIE11bHRpcGxpY2F0aW9uCiAoWV5hV1JfWGIvMnMpTXkgICAxIC0gQWRkaXRpb24KIFJWc1gsYi5hICAgICAgICAgIDIgLSBEaXZpc2lvbgogWWFYYkpzICAgICAgICAgICAgMyAtIFN1YnRyYWN0aW9uCiB4ICAgICAgICAgICAgICAgICA0IC0gRW1wdHkKIHlSTDIgICAgICAgICAgICAgIDUgLSBFcXVhbHMKIHggICAgICAgICAgICAgICAgIDYgLSBFbXB0eQpdIEAgQWEgICAgICAgICAgICBJbmRleCwgbW9kIDcsIHdpdGggQVNDSUkgdmFsdWUgb2YgYQ&input=&args=w7c+NQ+LVM). Note that `a` and `b` are the command-line args, i.e. the operator and the size respectively. The `-S` flag controls how lists are output: it joins on newlines first, but joins any nested lists on spaces. ``` [ Build a list of all possible figures: sXbRA_AEv-_aM,b 0 - Multiplication (Y^aWR_Xb/2s)My 1 - Addition RVsX,b.a 2 - Division YaXbJs 3 - Subtraction x 4 - Empty yRL2 5 - Equals x 6 - Empty ] @ Aa Index, mod 7, with ASCII value of a ``` And here are the individual sections: **Multiplication** For each row in the figure, we generate a string of spaces and then replace two of them with the input character. For row `i`, we want to replace the spaces at index `i` and `b-1-i`; but note that the latter can use the negative index `-1-i`. (It's even shorter because the variable `v` is preinitialized to negati**v**e 1.) ``` sXbRA_AEv-_aM,b M,b Map this function to range(b): sXb Space, repeated b times _ Function arg AE (Implicitly) convert to list and append element... v-_ -1 minus function arg RA Replace the characters at those indices... a ... with input character The resulting list is output with one item per line ``` **Addition** Using the strategy from my [Draw a hollow square](https://codegolf.stackexchange.com/a/98936/16766) answer, we define a function that wraps a `+` in `b/2` copies of its argument and returns the result as a list of characters. (Integer division `//` isn't necessary because the string repetition operator `X` automatically truncates to integer.) First, we call this function on a space, giving `[" ";" ";"+";" ";" "]`; then, we map the same function to that result, giving `[" ";" ";"+";" ";" "]` on most lines but `["+";"+";"+";"+";"+"]` on the center line. This nested list is then output, because of the `-S` flag, with spaces between all characters on a row and newlines between rows. ``` (Y^aWR_Xb/2s)My Anonymous function: _Xb/2 Function arg, repeated b/2 times (implicitly rounded down) aWR Wrap a in two copies of the above ^ Split resulting string into list of chars Y Yank that function into y ( s) Apply function y to space My Map y to that result ``` **Division** Each row has between `b-1` and `0` spaces, followed by the input character `a`. ``` RVsX,b.a ,b Range(b) sX Space, repeated that many times (works itemwise) .a Concatenate a (itemwise) RV Reverse (puts the larger number of spaces at the beginning) Outputs newline-separated ``` **Subtraction** Make a space-separated row of the input character. Save a copy for later. ``` YaXbJs aXb b copies of a Js Join on space Y Yank into y (overwrites the function from earlier, but we're done using it anyway) This is a string, so it just gets output ``` **Equals** The subtraction step stored half of what we need in `y`--just double it. ``` yRL2 (Implicitly) convert y to list and repeat it twice Outputs newline-separated ``` The dummy `x` values are there to pad the main list so that the modular indexing gives a unique index for each input character in `+-*÷=`. [Answer] ## JavaScript (ES6), 156 bytes ``` (c,n)=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>({'/':a=i+j-n,x:a&&i-j,'-':a=i+i-n,'+':a&&j+j-n,'=':a+2&&a-2}[c]?' ':c)).join(c=='='|c<'/'?' ':'')).join`\n` ``` Where `\n` represents the literal newline character. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~91~~ 86 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Needs `⎕IO←0`, which is default on many systems. Takes **n** as left argument, and one of **+ - × ÷ =** as right argument. ``` {s←⌈⍎⍕3⍵2 t←' '⍵ d←⌽∘.=⍨⍺ s∊2 6:t[d∨⌽d∧6=s] 5=s:t[↑,/2↑¨∨/¨(⌊⍺÷2)=⍳⍺ ⍺] (2-s)(2×⍺)⍴t} ``` ### Explanation ``` { s ← ⌈ ⍎ ⍕ 3 ⍵ 2 ⍝ calculate ceil(3 f 2), where f is the given symbol t ← ' '⍵ ⍝ create a string with a space before the symbol d ← ⌽ ∘.=⍨ ⍺ ⍝ Boolean \ diagonal s ∊ 2 6: t[d ∨ ⌽ d ∧ 6 = s] ⍝ if ÷ or × index t with one or both diagonals ⍝ find coordinates that are in the middle of at least one dimension ⍝ pad with zeros for spacing ⍝ use that to index into t 5 = s: t[ ↑ ,/ 2↑¨ ∨/¨ (⌊ ⍺ ÷ 2) = ⍳ ⍺ ⍺] ⍝ - or =: (2 - s) (2 × ⍺) ⍴ t ⍝ one or two rows of double-spaced symbols } ``` [Answer] # Mathematica, 191 bytes ``` e=#~Mod~2==1&;StringRiffle[Normal@SparseArray[{a_,b_}/;(a+b==d+1||a==b)[e@b&&a<3,,e@b&&(a==⌈d/2⌉||b==d),,e@b&&a<2,,a+b==d+1][[Last@ToCharacterCode@#~Mod~10]]:>#,{d=#2,2d-1}," "]," "," "]& ``` Anonymous function. Takes a string and a number as input, and returns a string as output. Not the shortest by far, but still fun to write. [Answer] # C, 396 bytes ``` #define p(x) printf(x); i,j,k,m;f(char s,int n){i=k=0;if(s==45)for(;i<n;++i)p("- ")m=n/2;if(s==43)for(;i<n;++i)for(j=0;j<=m;++j)if(i-m)p(j-m?" ":"+\n")else{for(;k<n;++k)p("+ ")p("\n")j+=m;}if(s==61)for(;i<2;++i){for(k=0;k<n;++k)p("= ")p("\n")}j=n;if(s==47)for(;i<n;++i){--j;for(k=0;k<j;++k)p(" ")p("/\n")}if(s==120)for(;i<n;++i){k=m-abs(m-i);for(j=0;j<n-k;++j)p(j-k?" ":"x")p(i-m?"\bx\n":"\n")}} ``` Call with: ``` int main() { f('x', 5); return 0; } ``` [Answer] # [SOML](https://github.com/dzaima/SOML), ~~104~~ 100 [bytes](https://github.com/dzaima/SOML/blob/master/chartable.md) (non-competing) ``` Cd³³b»E +=?ce*d+e{t}bd*Oe{t}} ==?b*tt} -=?b*t} /=?bc*b{j:d+p}} x=?"”cb*e{jj⁴⁴d;d+++tGG;c+;}XOdoe{O ``` This is kind-of competing as I'm pretty sure that everything I used here has docs on github before this questions posting date but the parser doesn't have support for some functions I used so idk. [Answer] # PHP, ~~306~~ ~~292~~ ~~281~~ ~~282~~ ~~281~~ ~~275~~ 270 bytes ``` $r=str_pad("",2*$n=$argv[2],($c=$argv[1])." ")."\n";if(",">$c)$r=($m=str_repeat(str_pad($c,$n," ",0)."\n",$n/2))."$r$m";if(9<$c)$r.=$r;if(w<$c)for($r=$c;$i<$n;$r[$i*(2+$n)]=$r[++$i*$n-1]=x)$r[$i*$n+$i+$n]="\n";if("/"==$c)for($r=$s="";$i++<$n;$s.=" ")$r="$s/\n$r";echo$r; ``` Ooh this is bulky ... needs further golfing. I could save 4 bytes with physical linebreaks or one byte with putting "\n" into a variable. [Answer] # C#, 744 Bytes *It's like 1 million characters long, I think, but I don't care, I am just so happy that I solved this...* Golfed: ``` string A(string s,int n){string O="";Func<string,int,string>R=(a,b)=>{return string.Join("",Enumerable.Repeat(a,b))+"\r\n";};switch(s){case"+":for(int i=0;i<n;i++){if(i==n/2){O+=R("+",n);}else{O+="+".PadLeft(n-n/2,' ').PadRight(n-n/2,' ')+"\r\n";}}return O;case"=":return R("=",n)+R("=",n);case "-":return R("-",n);case "/":for(int i=n;i>0;i--){O+="/".PadLeft(i)+"\r\n";}return O;case "x":int x=0;string[]r=new string[n];for(int i=n;i>0;i--){if(n-x-x<0){O+="x".PadLeft(x+1)+"\r\n";break;}string row=string.Join("",Enumerable.Repeat(" ",x))+"x"+string.Join("",Enumerable.Repeat(" ",n-x-x))+"x"+"\r\n";O+=row;x++;r[x]=row;if(i==n/2)break;}for(int i=r.Length-1;i>0;i--){if(string.IsNullOrEmpty(r[i]))continue;O+=r[i];}return O;default:return "";}} ``` Ungolfed: ``` public string A(string s, int n) { string O = ""; Func<string, int, string> R = (a, b) => { return string.Join("", Enumerable.Repeat(a, b)) + "\r\n"; }; switch (s) { case "+": for (int i = 0; i < n; i++) { if (i == n / 2) { O += R("+", n); } else { O += "+".PadLeft(n - n / 2, ' ').PadRight(n - n / 2, ' ') + "\r\n"; } } return O; case "=": return R("=", n) + R("=", n); case "-": return R("-", n); case "/": for (int i = n; i > 0; i--) { O += "/".PadLeft(i) + "\r\n"; } return O; case "x": int x = 0; string[] r = new string[n]; for (int i = n; i > 0; i--) { if (n - x - x < 0) { O += "x".PadLeft(x + 1) + "\r\n"; break; } string row = string.Join("", Enumerable.Repeat(" ", x)) + "x" + string.Join("", Enumerable.Repeat(" ", n - x - x)) + "x" + "\r\n"; O += row; x++; r[x] = row; if (i == n / 2) break; } for (int i = r.Length - 1; i > 0; i--) { if (string.IsNullOrEmpty(r[i])) continue; O += r[i]; } return O; default: return ""; } } ``` Testing: ``` +: 3, 5, 7, 9, 11 /: 7, 8, 9, 10 -: 3, 4, 5, 6 =: 3, 4, 5, 6, 7 x: 5, 7, 9, 11 ``` Too much to paste and format here, I created a pastebin: [Pastebin](http://pastebin.com/iSeSAPmm) [Answer] ## C, 331 Bytes ``` i,j;f(o,n){if(47==o)for(i=n;i;puts("")){for(j=i--;j--;putchar(j?32:o)){}} if(43==o)for(i=n;i--;puts("")){for(j=n;j--;printf(i==n/2||!j?"+ ":" ")){}} if(45==o)for(i=n;i--;putchar(o)){} if(61==o)for(i=3;i--;puts("")){for(j=n;j--;putchar(i&1?32:o)){}} if(120==o)for(i=n;i;puts("")){for(j=0;j++<n;putchar(j==i||j==n-i+1?o:32)){}i--;}} ``` The operator is passed as ASCII code into `o` and the character count into `n`. I only added spaces between horizontally consecutive characters into the plus sign, since this was the only one where the output would have been distorted if I hadn't and in the task it only said "should". I use two nested loops counting down (except for `-` where I only need one line). `=` Three Lines, one of them empty, straight forward `+` using `printf` because of the spaces `-` straight forward `/` have the inner loop print at zero and start at the outer loop's counter `x` have the inner loop print at the outer loop's counter and its "inverse" `n-i`. Still need to look at why I'am off-by-one here. Sample call: ``` #include <stdio.h> /* = 61 + 43 - 45 / 47 Space 32 x 120 */ int main(int argc, char **argv){ printf("%s\n%s\n",argv[1], argv[2]); f(*argv[1],strtol(argv[2],NULL,10)); } ``` [Answer] # Lua, ~~402~~ ~~344~~ 312 bytes 312: ``` r,p,b,x=string.rep,print,' ','x'function d(s,n)h,l=(n+1)/2,s..b;e=r(l,n)if s=='-'then p(e)elseif s=='='then p(e)p(e)else for f=1,n do p(s=='/'and(r(b,n-f)..s)or s=='+'and(f~=h and r(' ',n-1)..'+'or r('+ ',n))or f<h and r(b,f-1)..x..r(b,n-2*f)..x or f>h and r(b,n-f)..x..r(b,2*f-2-n)..x or r(b,f-1)..x)end end end ``` 344: ``` r,p,b,x=string.rep,print,' ','x'function d(s,n)h,l=(n+1)/2,s..b;e=r(l,n)if s=='-'then p(e)elseif s=='='then p(e)p(e)else for f=1,n do if s=='/'then p(r(b,n-f)..s)elseif s=='+'then p(f~=h and r(' ',n-1)..'+'or r('+ ',n))elseif s=='x'then p(f<h and r(b,f-1)..x..r(b,n-2*f)..x or f>h and r(b,n-f)..x..r(b,2*f-2-n)..x or r(b,f-1)..x)end end end end ``` 402: ``` r,p,b,x=string.rep,print,' ','x'function d(s,n)h=(n+1)/2;if s=='-'then p(r(s..b,n))end;if s=='='then p(r(s..b,n))p(r(s..b,n))end;if s=='/'then for i=1,n do p(r(b,n-i)..s)end end;if s=='+'then for i=1,n do p(i~=h and r(' ',n-1)..'+'or r('+ ',n))end end;if s=='x'then for i=1,n do if i<h then p(r(b,i-1)..x..r(b,n-2*i)..x)elseif i>h then p(r(b,n-i)..x..r(b,-n+2*i-2)..x)else p(r(b,i-1)..x)end end end end ``` 90 characters reduced and it's now painful to look at even when expanded. :| ]
[Question] [ You're given a **n-by-m** matrix of integers, where **n,m > 3**. Your task is to find the **3-by-3** sub-matrix that has the lowest mean, and output this value. **Rules and clarifications:** * The integers will be non-negative * Optional input and output format * The output must be accurate up to at least 2 decimal poins (if it's non-integer) * The submatrices must be made up of consecutive rows and columns **Test cases:** ``` 35 1 6 26 19 24 3 32 7 21 23 25 31 9 2 22 27 20 8 28 33 17 10 15 30 5 34 12 14 16 4 36 29 13 18 11 Minimum mean: 14 ``` --- ``` 100 65 2 93 3 11 31 89 93 15 95 65 77 96 72 34 Minimum mean: 46.111 ``` --- ``` 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 Minimum mean: 1 ``` --- ``` 4 0 0 5 4 4 5 8 4 1 1 4 9 3 1 0 0 1 3 9 0 3 2 4 8 4 9 5 9 6 1 8 7 2 7 2 1 3 7 9 Minimum mean: 2.2222 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins. I encourage people to post answers in languages that are already used, even if it's not shorter than the first one. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes ``` +3\⁺€F÷9Ṃ ``` Saved 2 bytes thanks to @[Dennis](https://codegolf.stackexchange.com/users/12012/dennis). [Try it online!](https://tio.run/nexus/jelly#rVGxEcIwDOyZwj0uLMtxogVYwngY0rAMPQdtJoFFwr/jHHfU3Em29HrprWQ96vl9eb7n22m52@sxr8sVybqWUnTwTrzL3kW4GO5UvSvqnUbvRuQoR6RxaDgykmB01gPxCQFcQRSAEuBbAyJoaAKADuGdWUCglMU0YRe6RWr1B1eKBHTloemY9vcIpCk/GQEjAoYNZBIZoWuYOEbK7ZPaer9G@h8rmxQWCs3wotQ3RIi90rc9tc@nHdj40gDrgLatwZv6DGtjcOY@Y9r@C04CcR/A9WutHw) ## Explanation ``` +3\⁺€F÷9Ṃ Main link. Input: 2d matrix +3\ Reduce overlapping sublists of size 3 by addition ⁺€ Repeat previous except over each row F Flatten ÷9 Divide by 9 Ṃ Minimum ``` [Answer] # Octave, 30 bytes ``` @(A)min(mean(im2col(A,[3,3]))) ``` [Try it online!](https://tio.run/nexus/octave#JY5LCoAwDET3OUWWLUixRq1FBHsOcSGiINi68P7UJmbxyEw@TJ5V0PFKKh5bUlds9udWoVqoolVrnc9pS@8IASdcjDFg6xpL9R0TG4YnQCTurGWScPBQJuLKru/@O0DnRPdMJx@oXUc4S5D8AQ "Octave – TIO Nexus") [Answer] # Octave, 38 bytes ``` @(M)min(conv2(M,ones(3)/9,'valid')(:)) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 9 bytes ``` 3thYCYmX< ``` Port of [@rahnema1's answer](https://codegolf.stackexchange.com/a/109100/36398). [Try it online!](https://tio.run/nexus/matl#DcmxDYAwDADBVX6EOCYxlulYgiiip6Fjf5PydKnfM87xXkfmlFLoDSqugSKCCrvHMtLwtjowwztW0e3@AQ "MATL – TIO Nexus") ### How it works Consider input ``` [100 65 2 93; 3 11 31 89; 93 15 95 65; 77 96 72 34] ``` as an example. ``` 3th % Push [3 3] % STACK: [3 3] YC % Input matrix implicitly. Convert 3x3 sliding blocks into columns % STACK: [100 3 65 11; 3 93 11 15; 93 77 15 96; 65 11 2 31; 11 15 31 95; 15 96 95 72; 2 31 93 89; 31 95 89 65; 95 72 65 34] Ym % Mean of each column % STACK: [46.1111 54.7778 51.7778 56.4444] X< % Minimum of vector. Display implicitly % STACK: [46.1111] ``` [Answer] # Mathematica, ~~37~~ 35 bytes Thanks @MartinEnder for 2 bytes! ``` Min@BlockMap[Mean@*Mean,#,{3,3},1]& ``` **Explanation** ``` Min@BlockMap[Mean@*Mean,#,{3,3},1]& BlockMap[ ]& (* BlockMap function *) # (* Divide the input *) {3,3} (* Into 3x3 matrices *) 1 (* With offset 1 *) Mean@*Mean (* And apply the Mean function twice to each submatrix *) Min (* Find the minimum value *) ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` [:<./@,9%~3+/\3+/\"1] ``` [Try it online!](https://tio.run/nexus/j#FYxNCsJAFIP3nuJDcKXYyXvt9EcF72GLC7G4GbyBVx9fIcniS0hduU08puu5uZ/Gw8@Pzbx5r6WWrXpmlhnvEBnLaMRaHDd6TJhjHS6CY6GgiQEbcEc9SigGiYgWGYrMxEf8jShGA9Lu/fp8KZeVUv8) The proper way to operate on subarrays in J is to use the third (`_3`) form of cut `;.` where `x (u;._3) y` means to apply verb `u` on each full subarray of size `x` of array `y`. A solution using that requires only 1 more byte but will be much more efficient on larger arrays. ``` [:<./@,9%~3 3+/@,;._3] ``` [Try it online!](https://tio.run/nexus/j#FYxBCsJAFEP3nuJtXCl18n877bQK3kNLF2JxM3iDXr1@IYSQPLKv3EYe47W53M/luDl@ijQ1i897/W9LZn7iHSJjGRWsJTijx4Q51uEieiwUbWLABtxRjxIKIBHWIkPhmfiIv4ICGpAO79fnS51W6v4D) ## Explanation ``` [:<./@,9%~3+/\3+/\"1] Input: 2d array M ] Identity. Get M "1 For each row 3 \ For each overlapping sublist of size 3 +/ Reduce by addition 3 \ For each overlapping 2d array of height 3 +/ Reduce by addition 9%~ Divide by 9 [: , Flatten it <./@ Reduce by minimum ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~93~~ ~~81~~ ~~80~~ 79 bytes ``` f=lambda M:M[2:]and min(sum(sum(zip(*M[:3])[:3],()))/9,f(M[1:]),f(zip(*M)[1:])) ``` [Try it online!](https://tio.run/nexus/python2#xVM7boQwFKzhFK9ZrR0h4g9gjJQjcAJEsdEKCSmQ1SZpcnkC89ZGpEmZgpHfb2YemGV4ebtMr9cLtU3bmaa/zFeaxll8fE14vsebeGq7xvZyg0xIKZ99Noi2000v1wN3SIRyGd7v1NI4k0iTTtgyVxmRBlYbGqD2OBe5klmakCC7xdagz6GGGYO8KUOfZSZME7oNI8@oyFcjBlpwaHRoBdz5EBNc2gI18Gk@V5EPseUNoK6ZFQp6dSX7bFtYKzBW5e7Q28jCa2oswavUPha9Dd7WmTKwPIoO9j0MOBPsBlEM/gXM9M@9bBhvU0XAsvEuFDFVP/K/ZZDCV7CH4s6oY9EfinydIkd90PRRGKfqoAkvLo67UDRHORc0e9mkye0@zp90Prm8GM50ovWvkcsP "Python 2 – TIO Nexus") ### How it works **f** is a recursive function that takes a list of tuples (or any other indexable 2D iterable that represents a matrix **M**) and recursively computes the minimum of the mean of the **3×3** submatrix in the upper left corner and **f** applied recursively to **M** without its first row and **M** without its first column. `f(M)` does the following. * If **M** has less than three rows, `M[2:]` is an empty list, which **f** returns. Note that, since **n > 3** in the first run, the initial cannot cannot return an empty list. * If **M** has three rows or more, `M[2:]` is non-empty and thus truthy, so the code to the right of `and` gets executed, returning the minimum of the three following values. ``` min(sum(sum(zip(*M[:3])[:3],()))/9 ``` `M[:3]` yields the first three rows of **M**, `zip(*...)` transposes rows and columns (yielding a list of tuples), `sum(...,())` concatenates all tuples (this works because `+` is concatenation), and `sum(...)/9` computes the mean of the resulting list of nine integers. ``` f(M[1:]) ``` recursively applies **f** to **M** with its first row removed. ``` f(zip(*M)[1:]) ``` transposes rows and columns, removes the first row of the result (so the first column of **M**, and recursively applies **f** to the result. Note that the previously removed layer in a recursive call will always be a row, so testing if **M** has enough rows will always be sufficient.. Finally, one may expect that some recursive calls returning `[]` would be a problem. However, in Python *2*, whenever **n** is a number and **A** is an iterable, the comparison `n < A` returns *True*, so computing the minimum of one or more numbers and one or more iterables will always return the lowest number. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *Missed the trick, as used by miles in their [answer](https://codegolf.stackexchange.com/a/109096/53748), of using an n-wise cumulative reduce of addition - the whole first line can be replaced with `+3\` for 11.* ``` ẆµL=3µÐfS€ ÇÇ€FṂ÷9 ``` [Try it online!](https://tio.run/nexus/jelly#HYsxEkAwFER7Z9lCJCS/0Kp0SqN1EAWtg2iNoZSTcJFYf7bYN7Nv03PN997W9t7jOnbvtGVxiQu7ec4pHpJS6nuHnCnhBpBLBDgYsmELrPJvGLIoWxTcgvrCh6BSP8Bz8eRCbU9/@AA "Jelly – TIO Nexus") Traverses all contiguous sublists, filters to keep only those of length 3 and sums (which vectorises) then repeats for each resulting list, to get the sums of all 3 by 3 sub-matrices and finally flattens those into one list, takes the minimum and divides by 9 (the number of elements making this minimal sum). [Answer] # Pyth, 19 bytes ``` chSsMsMs.:R3C.:R3Q9 ``` A program that takes input of a list of lists and prints the result. [Test suite](http://pyth.herokuapp.com/?code=chSsMsMs.%3AR3C.%3AR3Q9&test_suite=1&test_suite_input=%5B%5B35%2C+1%2C+6%2C+26%2C+19%2C+24%5D%2C+%5B3%2C+32%2C+7%2C+21%2C+23%2C+25%5D%2C+%5B31%2C+9%2C+2%2C+22%2C+27%2C+20%5D%2C+%5B8%2C+28%2C+33%2C+17%2C+10%2C+15%5D%2C+%5B30%2C+5%2C+34%2C+12%2C+14%2C+16%5D%2C+%5B4%2C+36%2C+29%2C+13%2C+18%2C+11%5D%5D%0A%5B%5B100%2C+65%2C+2%2C+93%5D%2C+%5B3%2C+11%2C+31%2C+89%5D%2C+%5B93%2C+15%2C+95%2C+65%5D%2C+%5B77%2C+96%2C+72%2C+34%5D%5D%0A%5B%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%2C+%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%2C+%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%2C+%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%5D%0A%5B%5B4%2C+0%2C+0%2C+5%2C+4%5D%2C+%5B4%2C+5%2C+8%2C+4%2C+1%5D%2C+%5B1%2C+4%2C+9%2C+3%2C+1%5D%2C+%5B0%2C+0%2C+1%2C+3%2C+9%5D%2C+%5B0%2C+3%2C+2%2C+4%2C+8%5D%2C+%5B4%2C+9%2C+5%2C+9%2C+6%5D%2C+%5B1%2C+8%2C+7%2C+2%2C+7%5D%2C+%5B2%2C+1%2C+3%2C+7%2C+9%5D%5D&debug=0) **How it works** *[Explanation coming later]* [Answer] # [Haskell](https://www.haskell.org/), 87 bytes ``` import Data.List t(a:b:c:d)=a+b+c:t(b:c:d);t _=[] s=(/9).minimum.(t=<<).transpose.map t ``` [Try it online!](https://tio.run/nexus/haskell#JckxDoMgFADQ3VM4dMD4Q0WqFipbx96AkOarHRhAIr/ntyQdX97pQ9oPqp9IyF8@U0UM9aJXvTUG26VdNbE/H1S/jXVVNuyqGh589OEbOCMzzw2nA2NOe/7wgKmmM6CPJh0@0iVbK7oOxgF6UNKBlSAESAF3VaCKBlBD@aJpAjXC1IO8OXf@AA "Haskell – TIO Nexus") [Answer] # [Uiua](https://uiua.org), 14 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ÷9/↧♭⍥(/+⍉◫3)2 ``` [Try it!](https://uiua.org/pad?src=0_3_0__ZiDihpAgw7c5L-KGp-KZreKNpSgvK-KNieKXqzMpMgoKZltbMzUgMSA2IDI2IDE5IDI0XQogIFszIDMyIDcgMjEgMjMgMjVdCiAgWzMxIDkgMiAyMiAyNyAyMF0KICBbOCAyOCAzMyAxNyAxMCAxNV0KICBbMzAgNSAzNCAxMiAxNCAxNl0KICBbNCAzNiAyOSAxMyAxOCAxMV1dCgpmW1sxMDAgNjUgMiA5M10KICBbMyAxMSAzMSA4OV0KICBbOTMgMTUgOTUgNjVdCiAgWzc3IDk2IDcyIDM0XV0KCmZbWzEgMSAxIDEgMSAxIDEgMV0KICBbMSAxIDEgMSAxIDEgMSAxXQogIFsxIDEgMSAxIDEgMSAxIDFdCiAgWzEgMSAxIDEgMSAxIDEgMV1dCgpmW1s0IDAgMCA1IDRdCiAgWzQgNSA4IDQgMV0KICBbMSA0IDkgMyAxXQogIFswIDAgMSAzIDldCiAgWzAgMyAyIDQgOF0KICBbNCA5IDUgOSA2XQogIFsxIDggNyAyIDddCiAgWzIgMSAzIDcgOV1dCg==) ``` ÷9/↧♭⍥(/+⍉◫3)2 input: a matrix of shape RxC ⍥( )2 repeat twice: ◫3 windows of 3; shape (R-2)x3xC ⍉ transpose (rotate axes once); shape 3xCx(R-2) /+ sum over the length-3 axis; shape Cx(R-2) ◫3 windows of 3; shape (C-2)x3x(R-2) ⍉ transpose (rotate axes once); shape 3x(R-2)x(C-2) /+ sum over the length-3 axis; shape (R-2)x(C-2) ÷9/↧♭ minimum of all elements divided by 9 ``` # [Uiua](https://uiua.org), 14 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ÷9/↧♭/+/+◫-2△. ``` [Try it!](https://uiua.org/pad?src=0_3_0__ZiDihpAgw7c5L-KGp-KZrS8rLyvil6stMuKWsy4KCmZbWzM1IDEgNiAyNiAxOSAyNF0KICBbMyAzMiA3IDIxIDIzIDI1XQogIFszMSA5IDIgMjIgMjcgMjBdCiAgWzggMjggMzMgMTcgMTAgMTVdCiAgWzMwIDUgMzQgMTIgMTQgMTZdCiAgWzQgMzYgMjkgMTMgMTggMTFdXQoKZltbMTAwIDY1IDIgOTNdCiAgWzMgMTEgMzEgODldCiAgWzkzIDE1IDk1IDY1XQogIFs3NyA5NiA3MiAzNF1dCgpmW1sxIDEgMSAxIDEgMSAxIDFdCiAgWzEgMSAxIDEgMSAxIDEgMV0KICBbMSAxIDEgMSAxIDEgMSAxXQogIFsxIDEgMSAxIDEgMSAxIDFdXQoKZltbNCAwIDAgNSA0XQogIFs0IDUgOCA0IDFdCiAgWzEgNCA5IDMgMV0KICBbMCAwIDEgMyA5XQogIFswIDMgMiA0IDhdCiAgWzQgOSA1IDkgNl0KICBbMSA4IDcgMiA3XQogIFsyIDEgMyA3IDldXQo=) ``` ÷9/↧♭/+/+◫-2△. input: a matrix of shape RxC -2△ subtract 2 from the shape; [R-2, C-2] ◫ . 2D windows of that size; gives 3x3x(R-2)x(C-2) array /+/+ sum over the first two axes ÷9/↧♭ minimum of all elements divided by 9 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~111~~ 103 bytes ``` lambda m,r=range:min(sum(sum(m[y+i][x:x+3])for i in r(3))/9for x in r(len(m[0])-3)for y in r(len(m)-3)) ``` [Try it online!](https://tio.run/nexus/python3#nVBdS8QwEHz3V/Sx4UbMZpM2ObhfUvpQ8SqFa5Wq0Pv1dRIFPR8lH@zMTmazu4@nyzA/Pg3VjPW0Dsvz@ThPS/32MZczd9fD1HfbcTtob8aXtZqqaanWWo15SBlvX/hyXii2vbnXIrv@ojNn9td1Wt7rse46DRA0cA0kwfkenUIdWjiBU7iQGQFzcNzkLZkIF6EKaSEWUkQWAeohDsK7IeWhdE4QCiNE@t6Yu5/SYi2aQOOkpawIWCkmgkQUkALzRG2L1KB1tP9rgZtF7X@YW08Pi9yLLx0ERPjvV55j0BJnBX@LVGKOiblY9IkvEpqij3mMaBm7omYbudb@CQ "Python 3 – TIO Nexus") [Answer] # Python 2, 96 bytes ``` h=lambda a:[map(sum,zip(*s))for s in zip(a,a[1:],a[2:])] lambda a:min(map(min,h(zip(*h(a)))))/9. ``` Test cases at **[Repl.it](https://repl.it/F7Oc)** An unnamed function taking a list of lists, `a` - the rows of the matrix. The helper function `h` zips through three adjacent slices, and maps the sum function across the transpose, `zip(*s)`, of each. This results in summing all height three slices of single columns. The unnamed function calls the helper function, transposes and calls the helper function again on the result, then finds the minimum of each and the minimum of the result, which it then divides by `9.` to yield the average. [Answer] ## JavaScript (ES6), ~~107~~ ~~98~~ 96 bytes A function that computes the sums of triplets over the rows and then calls itself to do the same thing over the columns, keeping track of the minimum value `M`. ``` f=m=>m.map((r,y)=>r.map((v,x)=>M=(z[x<<9|y]=v+=r[x+1]+r[x+2])<M?v:M),z=[M=1/0])&&m[1]?f([z]):M/9 ``` JS is a bit verbose for that kind of stuff and lacks a native `zip()` method. It took me quite a lot of time to save just a dozen bytes over a more naive approach. (Yet, a shorter method probably exists.) ### Non-recursive version, 103 bytes *Saved 2 bytes with the help of Neil* ``` m=>m.map((r,y)=>y>1?r.map((v,x)=>[..."12345678"].map(i=>v+=m[y-i%3][x+i/3|0])&&(M=v<M?v:M)):M=1/0)&&M/9 ``` ### Test cases ``` f=m=>m.map((r,y)=>r.map((v,x)=>M=(z[x<<9|y]=v+=r[x+1]+r[x+2])<M?v:M),z=[M=1/0])&&m[1]?f([z]):M/9 console.log(f([ [ 35, 1, 6, 26, 19, 24 ], [ 3, 32, 7, 21, 23, 25 ], [ 31, 9, 2, 22, 27, 20 ], [ 8, 28, 33, 17, 10, 15 ], [ 30, 5, 34, 12, 14, 16 ], [ 4, 36, 29, 13, 18, 11 ] ])); console.log(f([ [ 100, 65, 2, 93 ], [ 3, 11, 31, 89 ], [ 93, 15, 95, 65 ], [ 77, 96, 72, 34 ] ])); console.log(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, 1, 1, 1, 1, 1, 1, 1 ] ])); console.log(f([ [ 4, 0, 0, 5, 4 ], [ 4, 5, 8, 4, 1 ], [ 1, 4, 9, 3, 1 ], [ 0, 0, 1, 3, 9 ], [ 0, 3, 2, 4, 8 ], [ 4, 9, 5, 9, 6 ], [ 1, 8, 7, 2, 7 ], [ 2, 1, 3, 7, 9 ] ])); ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 16 bytes ``` 2FvyŒ3ùO})ø}˜9/W ``` [Try it online!](https://tio.run/nexus/05ab1e#HYyxDQIxEATrQRoJ397bbzdASkhguQ0kgm@CmEIgfhFRlDmQVhvMrHbqdL29776/ztthf26fRzte5uzdM0ZBBWtoGXTHxYoMOco/YoRDkeApSEUVd2zFEvYfJTK@YMKiS6AFj@eGxbCGGOML "05AB1E – TIO Nexus") **Explanation** ``` 2F } # 2 times do: v } # for each row in the matrix yŒ3ù # get all sublists of size 3 O # reduce by addition )ø # transpose matrix ˜ # flatten the matrix to a list 9/ # divide each by 9 W # get the minimum ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes ``` 2ᵑ{q3Lµ}aṁ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nVA7TkMxEBQtx0g9kby7_t6BNpXl4oGgQQGhJBWi4AipaVIAoqNKQcsx6HITxk4aWmTL2p0Zj8f78nF3fXu_nNbTe53Nl7O2e9usb-b5Uw_77eODXXzvn6bD1_Pr6vJqdeJ2P2eLWi1AEKERUqC-oRpMkaACNWjoiIAclJu4I5KhGWaQBHGQIXIIMA9RCM9IyMPoXCAUZoi0dl6rOIcYaFdsPCYC-ufCprALKIE8u5RQIpLS9HgRfxYV_0G6k4dDT-tHxoAMf9J6ftRG3RVMhjJqDoJcHvrCGwVx6HMfFBJrHWpGbu043l8) ``` 2ᵑ{q3Lµ}aṁ 2ᵑ{ } Apply the following function twice q Choose a contiguous subsequence 3L of length 3 µ Take its mean aṁ Minimum of all possible results ``` [Answer] # [Uiua](https://uiua.org), ~~17~~ 16 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ÷9/↧♭≡≡(/+♭)◫3_3 ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAgw7c5L-KGp-KZreKJoeKJoSgvK-KZrSnil6szXzMKCmZbWzM1IDEgNiAyNiAxOSAyNF0KICBbMyAzMiA3IDIxIDIzIDI1XQogIFszMSA5IDIgMjIgMjcgMjBdCiAgWzggMjggMzMgMTcgMTAgMTVdCiAgWzMwIDUgMzQgMTIgMTQgMTZdCiAgWzQgMzYgMjkgMTMgMTggMTFdXQoKZltbMTAwIDY1IDIgOTNdCiAgWzMgMTEgMzEgODldCiAgWzkzIDE1IDk1IDY1XQogIFs3NyA5NiA3MiAzNF1dCgpmW1sxIDEgMSAxIDEgMSAxIDFdCiAgWzEgMSAxIDEgMSAxIDEgMV0KICBbMSAxIDEgMSAxIDEgMSAxXQogIFsxIDEgMSAxIDEgMSAxIDFdXQoKZltbNCAwIDAgNSA0XQogIFs0IDUgOCA0IDFdCiAgWzEgNCA5IDMgMV0KICBbMCAwIDEgMyA5XQogIFswIDMgMiA0IDhdCiAgWzQgOSA1IDkgNl0KICBbMSA4IDcgMiA3XQogIFsyIDEgMyA3IDldXQo=) -1 thanks to alephalpha ``` ÷9/↧♭≡≡(/+♭)◫3_3 ◫3_3 # 3x3 windows ≡≡( ) # map function to each matrix in 4D array ♭ # deshape /+ # sum ♭ # deshape /↧ # minimum ÷9 # divide by 9 ``` [Answer] # [R](https://www.r-project.org/), 78 bytes ``` \(m,l=nrow(m))min(mapply(\(x,y)mean(m[x-0:2,y-0:2]),3:l,y=rep(3:ncol(m),l-2))) ``` [Try it online!](https://tio.run/##ZY/RioQwDEXf/Yo@tnCFJrXVuuuXLPsg7giCVRGH1a9348swO1NCIDnJze16Tp95ard12HWnyVoED0Z0cCCCI1Txqsgj@ouVJWJAyXCFQYHCZOkh8NNurWpUpp5ep50HIYADKIKLf1QpueMYJZjADuzfMEG2wBIyZF9xBa7gxF8JsuLybd3Ci1UQgySHV17AibUIEolKfmzwNBEQlMn65uzvU7cN86QTxmZa51@djEmD1O2yjId@8B2HSbdWwNee25pxXPnbwNUjjma9LdrVUzePIoAxZ2PM2evJfPTSOP8A "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` 2(3lvṁ∩)fg ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCIyKDNsduG5geKIqSlmZyIsIiIsIltbMzUsIDEsIDYsIDI2LCAxOSwgMjRdLCBbMywgMzIsIDcsIDIxLCAyMywgMjVdLCBbMzEsIDksIDIsIDIyLCAyNywgMjBdLCBbOCwgMjgsIDMzLCAxNywgMTAsIDE1XSwgWzMwLCA1LCAzNCwgMTIsIDE0LCAxNl0sIFs0LCAzNiwgMjksIDEzLCAxOCwgMTFdXSJd) ``` 2( ) # Twice 3l # Take sliding windows of length 3 vṁ # Take the mean of each window ∩ # Transpose fg # Flatten and take the minimum ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~21~~ ~~20~~ 17 bytes Port of @miles' J solution -3 thanks to @Bubbler ``` 1%9%&//2(+3+/':)/ ``` [Try it online!](https://ngn.codeberg.page/k#eJwdj0uOQzEIBPc+RUmjzCTK4hnwjxwo9z/CNE+2bLCLbvh+7JGP3+vy5zve19/ndbX2fcYEg4UvLPHRgCAcNm544FNvISjBcW399OIOfojANtaxm+swiYE5pnMVNwgZJCb0YPaSsfXOmqWYUYxMzcrmZKWpdJJTTKV7k4vtUlaxBM+PSWTQtSbV9dB9dFqriYa6jTsuQsLkHWucqr75VEWybv7UuOxWDRUtv1f7B71yMd8=) [Answer] # [Scala](http://www.scala-lang.org/), 142 bytes Golfed version. [Try it online!](https://tio.run/##PY9Nb4MwDIbv/AofEyliUNYy0ECatMuk5TRtl4qD24UqKAREwrSP9rczA@sixYqf2H5fuyManLpDo44eJGoLP0HwgQbqnD1r5/dLeLK@qorysRsPRnEoJlmUumYydPpb3Sfns2QR/0v4WhVK/HxDMypQximYxzAWge9gw8PaoJfYM12U/6ylvClKyTRnDec0bmxvsjASs45Hbfj6GtC6vnNqZdSn7QTwrmpoyT7D4eRyeBgG/Nq/@EHbU8VzeLXaQ0G7AZ15PUnZ4mkJcRQJ2G0FbARkCRfrVyIgjgUkdO@yK8xmSpXZdu640jQlshOQ0oDklvNFpyd1bywj2wu5BJfpFw) ``` M=>if(M.size<3||M(0).size<3)Double.MaxValue else List((0 to 2).flatMap(i=>(0 to 2).map(j=>M(i)(j))).sum/9.0,f(M.tail),f(M.transpose.tail)).min ``` Ungolfed version. [Try it online!](https://tio.run/##VZBBbwIhEIXv@yvmCAmha7dq19QmTXppUk6mvRgPo7KKYdEsbGNT/e3bga7GkkDgg/ceM36FFrtuv9zpVQCFxsFPlgGsdQUVUxN4Nz7M0/LmwmLBJ/C6b5dWw5QeAg1TAVPSarcJW3iCAk4nUHKrcX0Dea@SCo@faFudpNp63bsAfKGF2rhZu1QYGnOkAJZD64KxpJeVxaDwwAxMn/9d1AR3ESpmONtxzqVva7iDUua9dfw@u/UWsTYZ0Fjebxt0/rD3@g@Sq3FJfM7i7BtSU3sYNhs/gZemwe/5jMzcJjblw5lwbUksRdEp5aZlkOcCRkMB9wLKgkITLQQMBgIKmo/lBZaR0styGBUXOh4TGQkYk0HxwHnKOVB6sI5RBYmcs3PX/QI) ``` object Main { def f(M: List[List[Int]]): Double = { if (M.length < 3 || M.head.length < 3) Double.MaxValue else { val minSubMatrix = (0 until 3).flatMap(i => (0 until 3).map(j => M(i)(j))).sum / 9.0 List(minSubMatrix, f(M.tail), f(M.transpose.tail)).min } } def main(args: Array[String]): Unit = { val M = List(List(100, 65, 2, 93), List(3, 11, 31, 89), List(93, 15, 95, 65), List(77, 96, 72, 34)) println(f(M)) } } ``` ]
[Question] [ ## Background **[Gödel numbers](https://en.wikipedia.org/wiki/G%C3%B6del_numbering)** are a way of encoding any string with a unique positive integer, using prime factorisations: First, each symbol in the alphabet is assigned a predetermined integer code. Then, to encode a string \$ x\_1 x\_2 x\_3 \ldots x\_n \$, where each \$ x\_i \$ represents an symbol's integer code, the resultant number is $$ \prod\_{i=1}^n p\_i^{x\_i} = 2^{x\_1} \cdot 3^{x\_2} \cdot 5^{x\_3} \cdot \ldots \cdot p\_n^{x\_n} $$ where \$ p\_i \$ represents the \$ i \$th prime number. By the fundamental theorem of arithmetic, this is guaranteed to produce a unique representation. For this challenge, we will only consider strings made of the symbols Gödel originally used for his formulae and use their values, which are: * `0`: 1 * `s`: 3 * `¬`: 5 * `∨`: 7 * `∀`: 9 * `(`: 11 * `)`: 13 ...although for simplicity the symbols `¬`, `∨`, and `∀` can be replaced by the ASCII symbols `~`, `|`, and `A` respectively. (I don't know why Gödel used only odd numbers for these, but they're what he assigned so we're sticking with it) ## Challenge Given a string consisting only of the symbols above, output its Gödel encoding as an integer. You may assume the input will consist only of character in the set `0s~|A()`. ## Example For the string `~s0`: * start with \$ 1 \$, the multiplicative identity * the first character `~` has code \$ 5 \$; the 1st prime is \$ 2 \$, so multiply by \$ 2 ^ 5 \$; the running product is \$ 32 \$ * the 2nd character `s` has code \$ 3 \$; the 2nd prime is \$ 3 \$, so multiply by \$ 3 ^ 3 \$; the running product is \$ 864 \$ * the 3rd character `0` has code \$ 1 \$; the 3rd prime is \$ 5 \$, so multiply by \$ 5 ^ 1 \$; the running product is \$ 4320 \$ * so the final answer is \$ 4320 \$ ## Test-cases ``` Input Output "" 1 "A" 512 "~s0" 4320 "0A0" 196830 ")(" 1451188224 "sssss0" 160243083000 "~(~0|~s0)" 42214303957706770300186902604046689348928700000 "0s~|A()" 5816705571109335207673649552794052292778133868750 ``` ## Rules * Your program does not have to work for strings that would produce larger integers than your programming language can handle, but it must work in theory * You can accept input as a string, list of characters, or list of code-points * You may use [any reasonable 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] # JavaScript (ES7), ~~75~~ 72 bytes Expects an array of ASCII codes. ``` a=>a.map(g=k=>--d-1?g(k,d=n%d?d:++n):p*=n**(17088/k%75%14|1),d=p=n=1)&&p ``` [Try it online!](https://tio.run/##LY/NCoMwEITvPoUIysaf1EBLxbIWKX2K0kNI1LbaJJjSk/jqVqtz2Bl2v8Psi3@5Ff3TfBKlZTXVOHEsOH1zAw22WCSJTNi5gTaWqHx5lnkUKZKbEFUYAjumWbZr/ePBZ/uBkRkyqJCRIDDT6ea4rufFyyxXG226hrTcAoHV7aJtN8KYDjNKNtaOQwnEc@4OrXV/5eIB1sXCFVpZ3VW00w3UcKOU2vu/ufhfqXjw/jJ/VX6ALJp@ "JavaScript (Node.js) – Try It Online") ### Magic formula The formula `17088/k%75%14|1` was found by injecting random values into several handcrafted templates. More specifically, the template for this one was ``${p}/k%${m0}%${m1}|1`` with \$0<p<10^5\$, \$0<m\_0<10^3\$ and \$12\le m\_1 \le 15\$. ``` char. | k | floor(17088 / k) | mod 75 | mod 14 | OR 1 -------+-----+------------------+--------+--------+------ '(' | 40 | 427 | 52 | 10 | 11 ')' | 41 | 416 | 41 | 13 | 13 '0' | 48 | 356 | 56 | 0 | 1 'A' | 65 | 262 | 37 | 9 | 9 's' | 115 | 148 | 73 | 3 | 3 '|' | 124 | 137 | 62 | 6 | 7 '~' | 126 | 135 | 60 | 4 | 5 ``` ### Commented ``` a => // a[] = input a.map(g = k => // for each ASCII code k in a[]: --d - 1 ? // decrement d; if d is not equal to 1: g( // do a recursive call to the callback function: k, // pass k unchanged d = // update d: n % d ? d // if d is not a divisor of n, leave d unchanged : ++n // otherwise, increment n and set d = n ) // end of recursive call : // else (n is now the next prime): p *= // multiply p by n ** ( // n raised to the power of 17088 / k // the odd positive integer <= 13 which is obtained % 75 % 14 // by applying our magic formula to k | 1 // ), // d = p = n = 1 // start with d = p = n = 1 ) && p // end of map(); return p ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)! (I had a bug in my Python search code so failed to find the hash for a domain of `[1..7]`.) ``` ⁽=ȧ,7ḥⱮḤ’ÆẸ ``` A monadic Link accepting a list of characters that yields the Gödel number. **[Try it online!](https://tio.run/##y0rNyan8//9R417bE8t1zB/uWPpo47qHO5Y8aph5uO3hrh3/D7c/alrz/3@0kpKOgpIjiKgrNgBRBo5gSlMDRBaDAJhfp1FnUANUoglWU1xX46ihqRQLAA "Jelly – Try It Online")** ### How? ``` ⁽=ȧ,7ḥⱮḤ’ÆẸ - Link: list of characters, S ⁽=ȧ - 16481 7 - 7 , - literal pair -> [16481, 7] Ɱ - map across (c in S) with: ḥ - (c) hash (salt=16481, domain=[1..7]) Ḥ - double ’ - decrement ÆẸ - prime-index-exponentiate ([a,b,c,...]->2^a*3^b*5^c*...) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes ``` "0s~|A()"sk·>.Ó ``` [Try it online!](https://tio.run/##yy9OTMpM/X9u638lg@K6GkcNTaXi7EPb7fQOT/7/Pzo6VkchWslRCUzVKekoKBWDCAOIgAGI7YgkoAlia0DYxXDVaIQBkmkaIKIOIgokauDcYriYJpJdxXD5GrjVGlBFsQA "05AB1E – Try It Online") Link includes test suite. Takes input as a list of characters (test suite expects a list of lists) saving 1 byte thanks to @ovs. Explanation: ``` "0s~|A()" Literal string of symbols s Swap with implicit input k·> Get the incremented doubled indices .Ó Decode as list of prime exponents ``` Previous version took input as a string, which is easier to use: [Try it online!](https://tio.run/##yy9OTMpM/f9fyaC4rsZRQ1NJ5fCW7EPb7fQOT/7/HyoGAA "05AB1E – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~21 20~~ 19 bytes * Saved 1 byte thanks to caird coinheringaahing * Saved 1 byte thanks to Dominic Van Essen ``` Πz`^İpmȯ←D€"0s~|A() ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@5BVUJcUc2FOSeWP@obYLLo6Y1SgbFdTWOGpr///@PVlLSUXIE4rpiAyBp4AgiNTWARDEIgHh1GnUGNUBpTZA8RKNSLAA "Husk – Try It Online") ``` Πz`^İpmȯ←D€"0s~|A() m For each character in the input €"0s~|A() Find its index in the string "0s~|A()" D Double ← and decrement to get the corresponding code z Zip this with İp the list of prime numbers `^ by raising the prime numbers to the powers of the codes Π Get the product of that ``` [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes Takes input as a list of characters. ``` s=input() P=k=r=1 while s:r*=P%k<1or k**(3+2*'s~|A()'.find(s.pop(0)));P*=k*k;k+=1 print r ``` [Try it online!](https://tio.run/##LYu9CsIwFEb3PkUWuT@V0tbN9g6@QXZxU2mIJCGJiFD66jFCh8N3vuGEb168G0tJYlx4Z6RGi5UoQ/NZzOuh0jmy6IOdBx@VZcZTOzKkbb0gQfc07o6pCz5gT0STZrFsJ9vWPkTjsoqlXGGDI2Dlv31l3T3tn@D2Aw "Python 2 – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~109~~ 102 bytes -7 bytes; thank you, @ovs! Pretty naïve. ``` a=1{for(p=2;i++<length;)for(a*=p++**(index("0s~|A()",substr($0,i,1))*(j=2)-1);j<p;)p%j++||p++<j=2}$0=a ``` [Try it online!](https://tio.run/##LczBCsIwEATQ@35GqbCbVNj2muaQT4lYNVFqaFoUjPn1mIIDc3kwY1/34jQrX1us7j@X54JBD8pJOT6m@breFO1mhQ5SCoFuPk9vbDjmZJCaLm6nuC7Ycue6nkig1wMde1J@DIrCwUuZUp2O1b8ta1sKGMiRgQ0DIcQ9DBkzp8oE/@sf "AWK – Try It Online") ## Ungolfed ``` { # accumulator and currently seeing prime number a=1;p=2; for(i=1;i<=length($0);i++){ # multiply p_i^(x_i) a*=p**(index("0s~|A()",substr($0,i,1))*2-1); # get next prime p++; for(j=2;j<p;) if(p%j!=0) j++; else{ p++;j=2;}} # finally $0=a ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~26~~ ~~24~~ 23 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Ew! Don't think I've ever been more jealous of languages with built-ins for lists of primes and exponents and what-not :\ Input is an array of codepoints. Saved a byte by borrowing [Arnauld's formula](https://codegolf.stackexchange.com/a/226313/58974). ``` £_j}iY p#ª88÷X%75%E|1Ã× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&header=bWM&code=o19qfWlZIHAjqjg491glNzUlRXwxw9c&input=WyIwIiwiQSIsIjAiXQ) ``` £_j}iY p#ª88÷X%75%E|1Ã× :Implicit input of codepoint array £ :Map each X at index Y _ : Function taking an integer as argument j : Is prime? } : End function iY : Get the Yth integer that returns true p : Raise to the power of #ª88 : 17088 ÷X : Divide by X %75 : Mod 75 %E : Mod 14 |1 : Bitwise OR with 1 à :End map × :Reduce by multiplication ``` [Answer] # Japt, 24 bytes Japt is fairly verbose when it comes to primes, taking 6 bytes to get the Nth prime. Takes input as an array of letters. ``` £Èj}iY p"0s~|A()"aX ÑÄÃ× £ // Map the input with X as values, Y as indexes. Èj}iY // Get the Y-th prime p aX // to the power of the index of X in "0s~|A()" // string constant, ÑÄ // times two plus one to map to correct values. Ã× // Finally, reduce with multiplication, return result. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=o8hqfWlZIHAiMHN+fEEoKSJhWCDRxMPX&input=WycwJywnQScsJzAnXQ==) [Answer] # [Mathematica](https://www.wolfram.com/mathematica/), ~~120~~ ~~106~~ ~~102~~ 99 bytes -14 bytes, thank you pxeger! ``` 1##&@@(Prime[Range@Length@#]^#&@((Tr@StringPosition["0s~|A()",#]*2-1)&/@Characters@InputString[])) ``` First golfing, and would welcome feedback! [Answer] # [J](http://jsoftware.com/), 28 bytes ``` [:*/p:@i.@#^1+2*'0s~|A()'&i. ``` [Try it online!](https://tio.run/##PZBLS8RQDIX3/oqg4G1HrXncPG5hYIrgypVbwY04OG4Uuh361@uVthPIIt/JCYd8z9ddOsK@hwT3gNDXfujg6fXleX7rd4@//eHUHW7e6Y53CcfpPDRtuj11c3v1@fH1AwR7OEJKy6TEyzysIAvjQqYRV0bFQlaKw4VmJYpgzovSNptgyFmwWnA1jf@1@TIzVVmKuqPVrnsUVpANM2azKJKjcDji5cLUTHiuidotd5A5qjoRFhFldHOxXFTZS0ZlLuweJBIWrlv69R/zHw "J – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.primes math.unicode`, 64 bytes ``` [ dup length nprimes swap [ "0s~|A()"index 2 * 1 + ] map v^ Π ] ``` [Try it online!](https://tio.run/##TZHPTsMwDMbvfQrT0wbS5Dj/4bQT4sIFcZqGVHUZVNuy0rQDxOiz8ES8UklpxWYpUvz77M@Ks87yel91jw9397fXsMvql1lZFTsXYOMq77YQ3GvjfB5BLw4V68bndbH3A5s1vsj3KzckB9cbBigrV9cf0cvXcJMknwnESFM4xQWwAc7TcygZDbgNmJ6w4IQDx/k5Z1YZPirTSXruLiRjxhCJQQ19jK1RVUiCY@zFsbudtHiMQ6fp3zwiFnVupdao4omFzCiLpFCgUMpYLowloxH/LTC0x/lkmo4vMUxplFIzhpZzSaiV5kpYKUlbgZLIktaGcW6U0RKTr24Bq6aErfPPcdl@/IrwlpWwONkXfuXegeASGFzBMi6@hMMT/HzDsuvvoc7yzaz7BQ "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a string from the data stack as input and leaves an integer on the data stack as output. Assuming `"~s0"` is on the data stack when this quotation is called... * `dup` Duplicate the object on top of the data stack (TOS). **Stack:** `"~s0" "~s0"` * `length` Take the length of a sequence. **Stack:** `"~s0" 3` * `nprimes` Obtain a list of the first number of primes indicated by TOS. **Stack:** `"~s0" { 2 3 5 }` * `swap` Swap the top two objects on the data stack. **Stack:** `{ 2 3 5 } "~s0"` * `[ "0s~|A()"index 2 * 1 + ]` Push a quotation for `map` to use later. This is a function that maps letters of our alphabet to numeric values. **Stack:** `{ 2 3 5 } "~s0" [ "0s~|A()"index 2 * 1 + ]` * `map` Apply a quotation to each element of a sequence, collecting the results into a sequence of the same length. Inside the quotation now during the first iteration... **Stack:** `{ 2 3 5 } 126` * `"0s~|A()"` Push our alphabet string to the stack. **Stack:** `{ 2 3 5 } 126 "0s~|A()"` * `index` Find the index of NOS (next on stack) in TOS. **Stack:** `{ 2 3 5 } 2` * `2 * 1 +` Multiply by 2, then add 1. **Stack:** `{ 2 3 5 } 5` * Now `map` will collect `5` into the sequence it's building and move on to the rest of the elements in our input string... **Stack** `{ 2 3 5 } "\x05\x03\x01"` * As a side note, strings in Factor are just arrays of code points. Often when we map over a string, we'll get a string result, but we can still do vector math and such with them. This string is equivalent to `{ 5 3 1 }`. * `v^` Component-wise exponentiation. **Stack:** `{ 32 27 5 }` * `Π` Product. **Stack:** `4320` [Answer] # [R](https://www.r-project.org/), ~~98~~ 97 bytes *Edit: -1 byte thanks to pajonk* ``` function(x,p=1){for(y in x){while(sum(!(T=T+1)%%2:T)>1)1;p=p*T^(regexpr(y,"0s~|A()",f=T)*2-1)};p} ``` [Try it online!](https://tio.run/##XY7RCoIwGEZfxQbC/9uCzctkge@w66Js2mDOsSkppq9u8yrowHfuPjh@azr1VOZmh/ahvLaN2OrBVr3uLIzUCY5z3XmYEm2TEef3SxsFYWjhAFLII8c0zc8SLxx54YTL5BW8atTo4ocSFtZPCUhoLSRm@YnjUrhlC3fnzAQVEEJJGbcGFs3K3QhRYYcRpL8Y/C8FZSD0Pjij@9hKCEa2Lw "R – Try It Online") Input is a vector of characters. ``` goedel_numbering= function(x){ # x is the input character vector; p=1 # initialize p to 1 (one less than the first prime); for(y in x){ # now cycle through each character y in x: while(sum(!(p=p+1)%%2:p)>1)1 # update p to the next prime T=T* # multiply T (initially 1) by p^ # p to the power of (regexpr(y,"0s~|A()",f=T) # the position of y in the string "0s~|A()" *2-1) # times 2, minus 1; } +T # finally, output T. } ``` [Answer] # MATLAB/Octave, ~~102~~ 97 bytes ``` @(x)prod(table(primes(intmax)).Var1(1:nnz(x)).^int32(2*arrayfun(@(y)find('0s~|A()'==y),x)-1),'n') ``` [Try it on Octave Online!](https://octave-online.net/)\* - TIO has some problems with function and execution exceeds 60 seconds and is terminated. Anonymous function. In theory could work forever but maxes out at `int32` limit. Explaination: ``` % anonymous function - take product of first argument... @(x)prod( primes(intmax) % all prime numbers < than limit of int32 table( ).Var1( )% take elements of array 1:nnz(x) % vector 1 to length of input .^ % element-wise power int32( )% casting to int32 arrayfun( ,x) % for each character in input @(y)find('0s~|A()'==y) % find index in '0s~|A()' 2* -1 % indices to symbol values ,'n') % shorthand 'native', return product of elements in same type as input ``` --- Alternative solution as full function, **103 bytes** long. ``` function r=g(x) p=primes(intmax);r=int64(1);for n=1:nnz(x) r=r*p(n)^(2*find('0s~|A()'==x(n))-1);end end ``` [Try it online!](https://tio.run/##LYzRCoMwDEXf/QrfmghjrYwxJnnwRwaiVfpglLYOGdJf7yo2kNyby0mW3ndfHeO4ce/NwqWlCXYsVlqtmbUDw37u9ruqX9hYStvzAQqbcbElk3oz/07ckq1WYPxAXY2GBxDShaMFFER7yvGWbjQPReo4gRBYpNleEpy8jGyzQbjUnZWzAEEeCcXM5v8Y/w "Octave – Try It Online")\* This one on the other hand maxes out at `int64` limit. Ungolfed: ``` function result = g(x) primeNumbers = primes(intmax); result = int64(1); for n=1:length(x) result = result * primeNumbers(n) ^ (2*find('0s~|A()'==x(n))-1); end end ``` --- It is possible to write a function that doesn't max out (...so easily) but it outputs symbolic numbers instead of integers (and has **105 bytes**). Very similar to first function: ``` @(x)prod(sym(table(primes(intmax)).Var1(1:nnz(x))).^sym(2*arrayfun(@(y)find('0s~|A()'==y),x)-1),'native') ``` --- \*it is adviced for testing to replace `primes(intmax)` with something like `primes(intmax/128)` to calculate fewer prime numbers and thus reduce the execution time (and it was done for TIO example). The result will max out much faster than you'll use up all prime numbers, so no worries about that. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` εNØ"0s~|A()"yk·>m}P ``` [Try it online!](https://tio.run/##yy9OTMpM/V9WGWSZFaR0eL@Crp2Ckn3l/3Nb/Q7PUDIorqtx1NBUqsw@tN0utzbgv87/aCUlHQUlRxBRV2wAogwcwZSmBogsBgEwv06jzqAGqEQTrAZqUCwA "05AB1E – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 81 bytes ``` s=>s.map(c=>q*=(g=v=>p%v--?g(v):v?g(p++):p*p)``**'0s~|A()'.indexOf(c)*p,q=p=1)&&q ``` [Try it online!](https://tio.run/##hZBBDoIwEEX3nsI0EWaKNLjFFMMJPIAxgVQgGKSDNY0LwtUrStyJ/M1sXv5/mWtuc6PuNT3CVl8KV0pnZGLELSdQMum4hEpamdDGhuGhAouxHQ8FAcbECbOMcz8yQ58C@qJuL8XzWIJCTttOktyh53VO6dbophCNrqCEkxCCsfU3Z8T96geRsiViMBH7T0TpEoHAFlbMO5@aWQ8Yon6UQTbrMT2ITR3uBQ "JavaScript (Node.js) – Try It Online") Input as array of characters, output a number. Saved 1 byte by Shaggy. --- # [JavaScript (Node.js)](https://nodejs.org), 79 bytes ``` s=>s.map(c=>q*=(g=v=>p%v--?g(v):v?g(p++):p*p)``**'056 3421'[c%30%9]*p,q=p=1)&&q ``` [Try it online!](https://tio.run/##nY/BCoJAFEX3fYUMqG/GHMasIOMZ0meIkExlhenoxKzCXzcr2gWRd3NXh3PvJTe5lu1Z3fyq3h/6I/YaY82vuQKJccMQCjQYK9v4/qYAQyMzlPI8Gimm6G7HmCsWSyuczwI3lXYo7FXG1LRBhQF1nKaXdaXr8sDLuoAjpJxzQqxPsrfJwtiSXJ7ydjusSG5Ah6wnX9CEjEY7LchIVCSjUQpk7GD9zEv8/1foxH04TMn/X3V3T4CSH9b@AQ "JavaScript (Node.js) – Try It Online") Input an array of codepoints, output a number. Saved 1 byte by Shaggy. I believe [someone](https://codegolf.stackexchange.com/users/58563/arnauld) may find out better hash functions. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~103...~~ 94 bytes ``` n=>n.map(g=b=>(eval("for(j=++i;i%--j;);"),j)<2?l*=i*(i*i)**'0s~|A()'.indexOf(b):g(b),i=l=1)&&l ``` [Try it online!](https://tio.run/##DcRBDoMgEADAv5hUdlGJ7bF2bXxB34AKZgmCEWN6aPp12jmM06dO087b0YQ4m2wpB@qDWvUGC43Ugzm1h8LGHRxVFXd8aRrXYVdg7fBxe3pJLIElo5SiTd/PACgUh9m8XxZGvC//aiZPVyxLn6cYUvRG@biABdEOrVBp83yAEIiYfw "JavaScript (Node.js) – Try It Online") Takes input as an array of characters. A naïve implementation. ## How it works For each character, multiplies counter `l` by the exponential expression if incremented `i` is prime. If not, recall `g` until we get a prime number. Then logical-ANDs (short-circuit) with `l`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 bytes ``` *F.b^Nhyx"0s~|A()"Y.fP_ZlQ)Q ``` [Test suite](http://pythtemp.herokuapp.com/?code=%2aF.b%5ENhyx%220s%7E%7CA%28%29%22Y.fP_ZlQ%29Q&test_suite=1&test_suite_input=%22%22%0A%22A%22%0A%22%7Es0%22%0A%220A0%22%0A%22%29%28%22%0A%22sssss0%22%0A%22%7E%28%7E0%7C%7Es0%29%22%0A%220s%7E%7CA%28%29%22&debug=0) Naïve solution. Will attempt to find another solution... eventually. [Answer] # [PHP], 175 bytes My first try here, so obviously this will suck… ``` <?php $G="0s~∨A()";$p=[0,2,3,5,7,11,13,17,19,23,29,31,37,41];$i="~s0";$t=1;for($k=0;$k<strlen($i);$k++){$r=strpos($G,$i[$k]);$r2=$r*2+1;$m=pow($p[$k+1],$r2);$t*=$m;}echo $t;?> ``` I couldn’t think of a formula to generate primes, so I entered them all in an array. One can obviously do better. Also, my server doesn’t accept just <? as PHP marker, so I’m stuck with <?php. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~116~~ ~~110~~ 106 bytes Saved 3 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` d;g;p;r;f(char*s){for(p=r=1;*s;r*=pow(p,17088/ *s++%75%14|1))for(g=0;!g;)for(g=d=p++;d>1;)g=g&&p%d--;d=r;} ``` [Try it online!](https://tio.run/##XVHbbtswDH3PV2gGXEi@INRdhuoCwbCvWPIQ@NZgbWJYBho0cT59nuykQToBEsnDQ1Iki7QpinEsbWNb29kaF6/bLnLkVB863OZdTm3kbBfl7eEDtwnVYMwSRS6OQy1DKs6UkIna5GB/NPaml3kbx7Z8oZY0efP01IZlmtoy7@ww7vY9et/u9pgsTgvkz1wR9ZXr3e8NytEpCBIUrKbn4mASsJoFwdPrpjPbF3yBs6eQmeMu5xUmwWDnpFOV6thWRV@V16w0QZKyBAnOIEE0U4ZPUkhKjWFMDBYtIw8oYIKDd4J3C8aot3gmtQblr4epURkwBQKEUibjwmTMaIA5QBqqNEipKYWMc8lAK82VyKRkOhMgGcuY1oZybpTREgYbLR/GULxWxZ@q819G8yjWx19sfcx@@iunNh9s/tWrnznCU8O7fVkdfRjYm/qM3O6zOtT4axRkeQOiO2JRHM9sgq77eNiJz3Xdy0zY2Lt/qua8t8Y9@Y5WHr0P/v@wtvOUGgfrIHTrAKUvKCyRV/e@tT5BLrn3X@W529xSD4th/FvUb9vGjenHmL69/wM "C (gcc) – Try It Online") Inputs a string and returns its Gödel number. Uses the Magic ASCII to Gödel value mapping formula from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/226313/9481). ### Commented Code (before some golfs) ``` d;g;p;r;f(char*s){ // declare variables and function r=1 // init return value r to 1 p= // init prime number p to 1 for( ;*s;++s){ // loop over chars in s for(g=0;!g;) // loop until we find the next prime p++ // start by bumping p d= // init divisor d to p-1 g= // set g to non-zero p-1 as well for( ;d>1;) // loop over d until its 2 g=g&&p%d--; // g with only remain non-zero if // p is the next prime number r*=pow(p, ); // multiply r by p to the power of 17088/ *s%75%14|1 // the Gödel value for the ASCII // code, need the space so it's not } // interpreted as start of comment d=r; // return r } // ``` [Answer] # [Python 3](https://docs.python.org/3/), 190 bytes ``` def f(x): P,p=[2],3 while len(P)<len(x): P.append(p) while 1: p+=1 for i in P: if p%i==0:break else:break i=1 for d,n in zip(x,P):i*=n**(2*"0s~|A()".find(d)+1) return i ``` [Try it online!](https://tio.run/##NY1LCsIwFEXH6SpCQUjSUvqZFTNwB5mLg0pe6MOShrRiFXHrMak4utzP4brnOs62C0GDoYZtvM@IKp08t5eyy8hjxAnoBJYpfkyyD4iqBufAauZ4dL9RkwriCtkkNbOnSNFStccEDXUHlLLurx6GW8pgWuDvMFGJ0aVN1Asd20rFexTSCsFakdfL531iPK8MxmPNiyZ@e1jvPhIhfAE) Generates enough primes to form the Gödel number, then finds the product. [Answer] # [Haskell](https://www.haskell.org/), 95 bytes ``` e=(product.zipWith(^)[p|p<-[2..],all((>0).mod p)[2..p-1]]<$>).mapM(`lookup`zip"0s~|A()"[1,3..]) ``` [Try it online!](https://tio.run/##FcuxCoMwEADQXzmkwwU0xHbVgHs7dxCLoYYajMmhcSkhv57a9cGb1b5oa3PWLdLmp@Md@NfQ04QZX6ynSE3VXzkfSmUtohSMr34CYn@kqh6G5iJPU/TA0Xq/HDSevxB7ih2yoq/L27lZXpVx7UeHu3EapGyBNuMCcNCQEyYR0y7YDw "Haskell – Try It Online") ]
[Question] [ (we won't be finding a `Find` or catching a `tryCatch`, though) This is part two of a multi-part series of implementing some interesting R functions. Part one can be found [here](https://codegolf.stackexchange.com/q/188078/67312). # The task: You are to implement [R's `match` function](https://stat.ethz.ch/R-manual/R-devel/library/base/html/match.html) in as few bytes as possible. ## Input: * `x`, a possibly empty list/array of integers * `table`, a possibly empty list/array of integers * `nomatch`, a single integer value * `incomparables`, a possibly empty list/array of integers ## Output: * a single array/list of integers `O` of equal length to `x`, where each value `O[i]` represents either: + The index `j` of the **first** value in `table` where `table[j]==x[i]` + `nomatch`, indicating that no value in `table` is equal to `x[i]` **OR** that `x[i]` is in the list of `incomparables`. # Test Cases ``` All in the form x, table, nomatch, incomparables -> output outputs [], [1,2,3], 0, [5] -> [] [1, 2, 3], [], 0, [5] -> [0, 0, 0] [9, 4, 3, 6, 3], [9, 8, 7, 6, 5, 4, 3, 2, 1], -1, [4] -> [1, -1, 7, 4, 7] [8, 6, 7, 5, 3, 0, 9], [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6], 1000, [1] -> [12, 8, 14, 5, 1, 1000, 6] ``` More test cases can be generated as needed. ## Additional rules: * R has 1-based indices, but a consistent alternative-based indices are acceptable. So you can use indices that start at 3 or 17 or whatever, but this must be consistent, and you must indicate this in your answer. * If you chosen language has a builtin that does this, please also implement your own solution. * Explanations are appreciated. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest solution in bytes wins! [Answer] # [R](https://www.r-project.org/), 83 bytes ``` function(x,t,n,i)sapply(x,function(a)c(which(a==t/!rowSums(outer(t,i,`==`))),n)[1]) ``` [Try it online!](https://tio.run/##PYrLCsIwEEV/ZdzNwBWNj1oX@QqXIrQEQwOalDSh@vUxFnR37zknFquLzd4kFzy/kODhZOrH8fGu9296MTwPzgzca502qxjmS35OHHK6R05w6LTuRAReruomxbLhM@gA2oMa0LYOAS2wBZ0WePwFO5Cqdq2@RUWNSPkA "R – Try It Online") Avoids `match`, `%in%` and `setdiff`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024) ``` ,⁷y⁵iⱮ⁶o ``` A full program accepting four command line arguments, `incomparables nomatch table x` which prints a Jelly representation\* of the list of R's `match` function results. **[Try it online!](https://tio.run/##NYy7DYAwDERX8QAuEgwkzBKlpABFok6ZhZAogH28iBGHaJ7s@61zKdWMtd1V27nosWu7NjNLPpt3zlkSJs/UgwPTxNQxjbgFjBADKHAFYo/YF36nsqWIJ/xlhw68Bw "Jelly – Try It Online")** ### How? e.g. with `incomparables nomatch table x` = `[1,4], 2, [2,4], [4,3,2,1,0]`: ``` ,⁷y⁵iⱮ⁶o - Main Link: list, incomparables; list, nomatch ⁷ - newline character '\n' , - pair (incompararables) with (right) [[1,4],'\n'] ⁵ - 5th argument (3rd input = table) [2,4] y - translate (right) with lookup (left) [2,'\n'] ⁶ - 6th argument (4th input = x) [4,3,2,1,0] Ɱ - map with: i - first index of (right) in (left) [0,0,1,0,0] o - logical OR [2,2,1,2,2] ``` --- \* An empty list is represented as nothing, a list of lenth one is represented as just the item, while other lists are enclosed in `[]` and delimited by `,` [Answer] # [R](https://www.r-project.org/), 55 bytes In this case, the code doesn't use `match` with its full functionality, it is just used as an `index` function. First R answer, so probably incredibly inefficient byte-wise! **Note** (thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for the info)**:** `%in%` and `setdiff` are also both *internally* implemented using `match`, so completely getting rid of this surprisingly useful function will result in a *mess*. Therefore, there is a [150-rep bounty](https://codegolf.meta.stackexchange.com/questions/5243/list-of-bounties-with-no-deadline/17875#17875) with no deadline for this! (note that `setdiff` is allowed, though) ``` function(x,t,n,i)ifelse(x%in%setdiff(t,i),match(x,t),n) ``` [Try it online!](https://tio.run/##dZBdCsMgEITfewqhBBQ2EGP@hOYwxUYiNLYklub2dl2QUkre1tlvZ2TWuLBLyaJ9eRPcw/MdAnhwwtnpvk18L5wvtincnLU8oA7LNZg5YQK8iM/V@cAXbrgAZriEGhROVXq0QojTF5DAamCKuANEA2sQAdZlEJUBWE9Km7doI3FbykQ0vxYDoT3RilI0GeEs6V7SSpNLl7GWYjQd6pyhSGwISzD6yKqif8sUev4rjR@29p4dthbGcU@1ifgB "R – Try It Online") or... # [R](https://www.r-project.org/), 5 bytes ``` match ``` [Try it online!](https://tio.run/##dY7dCsIwDIXvfYqCDBLIYF33V3API3VjBVdlq7i3r22giBfeJed8OSdbWMWlFGG9erOE52adhxUMIAkDkmpScarS0iLi6QtIEjUJxdwfRJNoIkKiy2BUBhI9K212Y4yMbikT0fxGDIz2TCtu0RwUZ8n3ki3NKV3GWq7RfKhzh2KxYSzBMUdWFf8tU@l5fjnj7cPBQZ4cWQQ7T/d9gqOwrtgnf7PzDD4a9F6sWcCP44HkEMMH "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ṣK¥ƒiⱮo⁶ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsXeh5Yem5T5aOO6/EeN2/7//x9trKNgqKNgAiZNdRQsdRSMdBTMwGxjMGkBFjQHk8ZgWWOwoAlYGUhxLFDz/2gLMN8cptMArMEw9r@hgYEBAA "Jelly – Try It Online") A full program that takes three arguments: `[[table], incomparables]`, `x`, `nomatch` in that order. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 60 bytes ``` (a,b,c,d)=>a.Select(x=>d.Contains(x)|(x=b.IndexOf(x))<0?c:x) ``` [Try it online!](https://tio.run/##pU9Na4NAEL37K/aoMMquq1lt1R5KC0KhhR7Fg58gpFuIhgqtv92OEyUJ6a2X4c2bN@/NVL1d9d38fNRVlL50/RB1ekjgAmK5bNMnffxoDkW5b4hI2ng2CyihgtqKk8J5b/ZNNZhjnNTO46ceik735mj9IFM6qa6b8bXF3or4Q3U3WvO98XZAI7M1dfPFEGU8B4RZ/i3ABTkBh/PEsq70Z9HFMl/X/elWHYIHEnbrBhEBKCR8GrggJrDFOvP@MAhQq1AtMSbcTCQIYB4wrD6wEJgLbEdYUg2IVFQlTSWRHskW8QSC8@1wseTOWQ4so@8QcMR@zuyEZblhIE0mi@J6yKnjiyYkf0kRpAwpU22nedstAof4M8u8k4c4tYokarEKaEdtH2FCuBhK@vhff6MNPY6p@S8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes Zero-indexed. ``` ->x,t,n,i{x.map{|e|i-[e]==i&&t.index(e)||n}} ``` [Try it online!](https://tio.run/##XY5BDoIwEEX3nGIWxqgZCBVQusCLNMRUbLQJEIOoGODsOJ3Axt3kvf9/27wu36nSbXGHbPJPHbZYo@27oNKPfjCD9ZXJs8yu121g66vpNmY7DPU4Tp@7LQ3cTPv0AB660RVkYN66hNXZEeDVoNBludmx33qmvk4KVI6gBO4xoiOkO8kh95RjsEdwVP0ZiRCTQTjMnkCKcGSQLJLKgqRPOyqemylHjpyKeFS6Pp2Ca4KN5PJhSSW8Lrknl@mIYcwxF6YZEYbul4Le@gE "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 79 bytes ``` function(x,t,n,i)sapply(x,function(y)`if`(any(z<-y==t)&all(y-i),which(z)[1],n)) ``` [Try it online!](https://tio.run/##dY7NCoNADITvfYo9lQQiGP/qQn2SUlAEcUG2Yi3t@vI2Bmzpobdk5stMprWr1u7h29ndPLxoJk8O7804DkHWjxOwdl0NjQ@wnKNQVTMem2GAEDmkZ@/aHha88JU84jpOzs/QQQtIpgWmhFKZ4m3JEfHwBZhMQiZV7g9iyWSCkCl2UJSSzEmVfHclhsWNeCOy34hS0ZPSqbZYDZKZ9Z7VsppS7FiuNVYP7d6RqpgptsGSw3Gsf7OUrm8 "R – Try It Online") # [R](https://www.r-project.org/), 66 bytes ``` function(x,t,n,i)sapply(x,function(y)c(which(y==t&all(y-i)),n)[1]) ``` Combining my solution with parts of [Nick's solution](https://codegolf.stackexchange.com/a/188182/59530). [Try it online!](https://tio.run/##dY7NCsJADITvPsWeZAMpNN3@LdgnEQ9lQbrQrqVWdJ@@poFVPHhLZr7MZNkmdcrUdn0Et/pb0C9cMaCHez/PY@T140Rw@jl4N@jYdeuxH0cdMw@AAc50gW1efFj1pJ0GVE4TFmh4yvelAoDDFyBUBSoj3B/EoioZQVUnkJUWVSNKlVyOIXYz2onyN6IVtBHaSIuVIJ5J7kksKyl1wiqpsXJoU4cRsRRshzmH8lz@Ji7d3g "R – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` Ë!XøD ©ÒVbD ªW ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yyFY%2bEQgqdJWYkQgqlc&input=WzgsIDYsIDcsIDUsIDMsIDAsIDldClszLCAxLCA0LCAxLCA1LCA5LCAyLCA2LCA1LCAzLCA1LCA4LCA5LCA3LCA5LCAzLCAyLCAzLCA4LCA0LCA2LCAyLCA2XQoxMDAwClsxXQ) [Answer] # [Python 3](https://docs.python.org/3.8/), 60 bytes ``` lambda x,t,n,i:[v in{*t}-{*i}and-~t.index(v)or n for v in x] ``` [Try it online!](https://tio.run/##bY7dCoJAEEbve4q5VBnD9SfdoCfZvDAsWshVZBFD7NW32SGDoJtlmHPm@3Z42ntvsmoYXQcnOLtH013aBma0aFAf1QTaLJFd4yXSa2Pa@GX32rTXOZjCfgQDN3q9BHPthlEbG3SBqhGUwBQzGhKaizoMd18qEFIEz9RfLhFy4giHj0WLCqHkRbFBihAEY0pT@c99xWLJbsYF0qfQKPhYMJEccdisgjsk38mtIONlzpqXKUYkif@xoEb3Bg "Python 3.8 (pre-release) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes ``` param($x,$t,$n,$o)$x|%{($n,$t.indexof($_))[$_-in$t*!($_-in$o)]} ``` [Try it online!](https://tio.run/##TY/hCsIwDIT/7ykiRm0kk9Vtzv5QfA8REdxQ0E104EB99plGh0ILae@7u/ZS3fPr7ZCfTi0Wi0d72V13Z4MNY81YMlaEzXPwMH6uJ8dynzdVYXBLtMZteCyxHvfMZ6po82pfQTDEAlaGZFueckwQyZhSMBp9JcswZYhJqY8I/XAJ64jBr80PdQyJoAwzNfjznCHTc9ppEmZFC61PTL5ZUhJaRQXK/iLnas7UH2uhE7NMVlGrgtPUWQelWuvU5rrOWC8TxTxMYKPIf0fe0b4B "PowerShell – Try It Online") 0-indexed [Answer] # JavaScript (ES6), 53 bytes ``` (x,t,n,i)=>x.map(v=>!~i.indexOf(v)*-~t.indexOf(v)||n) ``` [Try it online!](https://tio.run/##bY9NboNADIX3PYW7m6kMGfObWcAVcoARC5RARZQOUYMQiyhXJ8YtEmq68zx/7z3PuR7r2/G7uw6B70/N3BazmnBAj50uyin8qq9qLMr3Rxd2/tRMh1aN@iN4DJvn/e71fOz9rb804aX/VK1yFYIjjDDmwfCcVlrDbgdBCa56@wMTQoSwoO4f3IhkXlwWIWEXQvbrZWGPkIuQrksOJl4G3OGSTSr9aLlw@Uv4XlJyCYrlALtU8EjiINlYyc9WKpUDrPjs2h6LmAi2wBxDxiyfpO05kWCUSAqtTFbNTw "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 45 bytes ``` ->\b,\c,\d{*>>.&{$_∉d&&~b.first($_,:k)||c}} ``` [Try it online!](https://tio.run/##VY67boNAEEV7f8XIQngXLetdniZRiFKkS@0GVpZfSCg4QeDGwqROfjM/QoaxKUI1e@@ZM9THpoqG0wXsAp4GN813It@L/NA5aSrtztr8fv8cbPtrJ4uyac/M2oiHd3697vt@KD4bYFX5cWy5PG1r5si2rsozW4CbLnimDIduBvgtmXSec8OlxIEvHylstxdg84JZmjNL8TmXr@uXt1k/ZEZApoUnfBwUzqFBIWRmhil4AsY8@98peilEEgEBIgKiO4jBSkBMQTiVaNFYuijMgptC354xITGaVrQS05ZP/mT04aiJ0dQkJIsmKqRrCe0l0ymfwoCwEUaNVmr8fX2/7RGhAxLoqY7MHw "Perl 6 – Try It Online") Anonymous code block that takes input curried, like `f(table, nomatch, incomparables)(x)` and returns the matches 0 indexed. ### Explanation: ``` ->\b,\c,\d{ } # Anonymous code block taking 3 inputs * # Return an anonymous Whatever lambda >>.&{ } # Mapping input to $_∉d # If the element is not an uncomparable && b.first($_,:k) # Return the first index in the table ~ # Stringified so Nils are false ||c # Else the nomatch element ~~ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` IEθ∨∧¬№ει⊕⌕ηιζ ``` [Try it online!](https://tio.run/##Nco9C4MwEMbxr3LjBc7Bqn2hUxEKHfqyS4YQAwZsomnaoV/@vApdnuH/e@xgko1mZH4kHzK25pXxaiacCe4JT6HHW5Qc34KOwCtFcAk2uacL2fV49nIZVhD5yqojc9cdCGqCimArqwl@YU@wW0Pzxw1BKViUcqi15uIzLg "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation: ``` θ First input (x) E Map over elements ε Fourth input (incomparables) № Count occurrences of ι Current element ¬ Is zero ∧ Logical And η Second input (table) ⌕ Find 0-based index of ι Current element ⊕ Convert to 1-indexed ∨ Logical Or ζ Third input (nomatch) I Cast to string Implicitly print on separate lines ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 125 bytes 1-indexed. Given that I can't use a sentinel value in the passed arrays, I need to give the array bounds for each array. ``` f(x,c,t,d,n,i,e,j,f)int*x,*t,*i;{for(;f=0,c-->0;x[c]=--f?n:j){for(j=e;!f&j;x[c]-i[--j]||--f);for(;!f&j<d;x[c]-t[j++]||++f);}} ``` [Try it online!](https://tio.run/##pVLJbtswEL3rKxgXCbQMC8pbotJyfyDorSdBB4eSEhK2FDh0IcDRt7tDanFdK7kEBgz6vXkLhxb0WYjTqXBrEKAhgxIk5KCg8GSp/Rp8Db7kx6Lau7yIGQhK14zXiUhjSouf5Q/lWVLFOb8p7pSlqEwoVen7O4543GoNt8paVicqCJANAmSb5vRNlmJ7yHKyetOZrL6/rJ0LaCufDOZgI7LbyNL9U8nMI0eHEITwmxC/TtL4aI@E/Pr9@Ajd2cWJJPWOIUxh1vyPRjCHGSxHmAdE72GBLIOosWQ34@vN0zb/J248YqxEBA9oukRbEzuF8Cp2BiFyIU5EyC9tgQWqItRFVjPDX3NkkL2oVVa7jRYvphfDzjSEkDHWd8Z1VrvXkdKLqwrXyPwKCS@iRd2mmqr3mNzDw6LsEmHaL0ec22BL82m4g4z5o5g3ljHjxlSmaxpyIoOgfWxCXvfIF@6kjpOJxy3Ui5QRqZWV4cFouum7Cdxmk@RGpUAMm6i00/Z2SNiuH7u2V/nMuZ8Yde8eJ77NgLSXx6gBRtUHsd2iPssdRkaCCV0Te6XW3DW3B7sh6OvCcDU4t4HBFM4VBpuvLPyg37BXu@XG@O1zfdiXhHGnOf0F "C (gcc) – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 39 bytes ``` ${{[_,y][nil=_or x@_in z]}=>x&Index@_4} ``` [Try it online!](https://tio.run/##hY9Ba8JAEIXv@RVzEE8jZE2ijaAWeuqlFNrbMoRtXGtAN2L2EBV/ezo7NaCUtrlk8ua9702M96bc2G65hLej86adwVp787G1CK7eGV9uECpX1ru9OQS5QYAWKOLA7dNe38cb7dQPRRqtYTbvBuezLvBI2lXbeVEfoH0sKgcnuswX7fDZrSwL6aV7sXbV6MF@X35SFK139Uq3CH9eRcyPQte/17eMfD1Uzr/bxj@ZxjZ6GCoQtAC0Jh4VjjHhIeY5I0JZ8T@PFqBJPq5mhTBGCFb9iz0WOb5L5QgppxAm1ywLDwhTEbJ@yWDFyxF36PQnNeiTb8od/EHkqYASKc9DBY9KyEo2ufAnvSuTA3LJ5X17ImIqtmBmjIrj8JOK6PYapSSoEnHHvS2jiKj7Ag "Attache – Try It Online") Pretty simple verification. Note that the argument order differs from that of match; specifically, `x` is the last argument rather than the first, and corresponds to `_4` in the above snippet. ## Explanation ``` ${{[_,y][nil=_or x@_in z]}=>x&Index@_4} ${ } named lambda, taking parameters x, y, z, and _4 x&Index@_4 short for Index[x, _4]; calculates where each element in _4 occurs in x returns `nil` for no match { }=> over each index: [_,y][ ] choose y (`nomatch`) if nil=_ the index is nil or x@_in z or the element is in `incomparables` _ otherwise, choose the index ``` [Answer] ## Haskell, ~~57~~ 56 bytes ``` (t#n)i=map$maybe n id.($zip i[n,n..]++zip t[1..]).lookup ``` Argument order is: `table`, `nomatch`, `incomparables`, `x`. [Try it online!](https://tio.run/##ZY7NDsIgEITvPsUm7YGmKwHp76FPQjhg2kTSlhKtB315XDTx0sMmzH4zs9zsY56WJUa2Z75ww2pDvtrXdQIPbuQsf7sATnv0nJuyTGrXkt4FX7Ztfoa4WudhgHE7AUC4O79DDiwrQEu8oDIgQNcGtDnwP/oZD7zHDltssMYKFVmkAXaWBCqTYFo26cAhqFASlRTsKZYKFE1HqqVJVYpURYSoASkEfYTadUer9msX2Jv4AQ "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` õ:Ik®I: ``` 0-indexed. Inputs are in the order: `incomparables, table, x, nomatch`. [Try it online.](https://tio.run/##yy9OTMpM/f//8FYrz@xD6zyt/v@PNonlirbUUbDQUTDXUTDTUTDVUTDRUTDWUTDSUTCEyEH4QDnjWC5dS0sA) **Explanation:** ``` õ: # Replace all values of the (implicit) first incomparables-list in # the (implicit) second table-list with an empty string # i.e. incomparables=[4] and table=[9,8,7,6,5,4,3,2,1] → [9,8,7,6,5,"",3,2,1] Ik # Get the index of each value in the third x-list in this list (-1 if not found) # i.e. x=[9,4,3,6,3] → [0,-1,6,3,6] ®I: # Replace all -1 with the fourth input-integer # i.e. nomatch=-99 → [0,-99,6,3,6] # (and output the mapped list implicitly as result) ``` ]
[Question] [ Your task is to write a function that takes an even-digit integer and compares the 2 halves of the integer. If the sum of the digits in the first half is greater than the sum of the digits in the second half, output a truthy value, otherwise, output falsey. For example: ``` 12345678 1234 5678 (1+2+3+4)>(5+6+7+8) 10>26 Output falsey ``` ### Input A single integer. * This must be passed as a single whole integer in base 10, a single string, an array of integers, or an array of characters. Please specify which format your answer accepts * The input can be passed via Command Line Arguments, STDIN, or any other standard method of input supported by your language * Assume the input will always have an even digit count * Assume the input will always be positive and greater than 0 * Assume the input will be within feasible number handling capacities for your language * The input will not contain leading zeroes ### Output A truthy value if the sum of the digits in the first half is greater than the sum of the digits in the second half. A falsey value if the sum of the digits in the first half is less than **or equal** to the sum of the digits in the second half. ### Test cases ``` Input > Output 12345678 > False 87654321 > True 12344321 > False 12 > False 214758392639543385 > False 1001 > False 100000 > True ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ḍ+ᵐ>₁ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wR6/2w60T7B41Nf7/b2hkbGJqZm4BAA "Brachylog – TIO Nexus") ## How it works ``` ḍ+ᵐ>₁ example input: 12345678 ḍ split in half [[1,2,3,4],[5,6,7,8]] +ᵐ sum each half [10,26] >₁ results in a decreasing list false ``` [Answer] # Octave, ~~39~~ ~~35~~ 28 bytes ``` @(x)sum(x)/2<sum(x(1:end/2)) ``` Input integers as a string `'12345678'`. Takes the `sum` of all the digits (as ASCII-values), and divides it by two, to get the mean of the two sides. Compares this to the sum of the first half of the integer, to check if it's smaller or not. [Answer] # [Retina](https://github.com/m-ender/retina), 34 bytes ``` \d $*1; +`;(.*);(.) $1$2 1(1*);\1; ``` [Try it online!](https://tio.run/nexus/retina#LYnBDcAgDAP/mYNKQKWqTggEMUCX4MGj@69AQaoflu98@GfM/pKLaHSO5q8YVgVycEzwWNjR5gRL0lyMrGRNwqBt/kGMVNSkcpa6XjHdFvfOBw "Retina – TIO Nexus") Works by inserting `;`s after each digit as they are converted to unary. The `;`s are then deleted in pairs until only the middle and final `;`s remain and the numbers can then be compared. [Answer] # Regex, 226 bytes ``` ^(9(){9}|8(?<2>){8}|7(?<2>){7}|6(?<2>){6}|5(?<2>){5}|4(?<2>){4}|3(?<2>){3}|2(?<2>){2}|1(?<2>)|0)+(?<-1>9(?<-2>){9}|8(?<-2>){8}|7(?<-2>){7}|6(?<-2>){6}|5(?<-2>){5}|4(?<-2>){4}|3(?<-2>){3}|2(?<-2>){2}|1(?<-2>)|0)+(?<-2>)(?(1)^)$ ``` [Try it online!](https://tio.run/nexus/retina#Tc1LCgMxCIDh/ZyjhYQijJonlJllbzH0HqNnTxPqQjd@6OJ/hs93XKGHeHeVFs43HfFuKtVYVYqxqGRjVknGpMJGViEjqeCfssfXFODR11pPK4FLgWuBi4GrgcuB64ELgitOhjNgvOJjDCROudS2tVpyYsJtXQwbYaq5cafCfX655XXFfc0P "Retina – TIO Nexus") (uses Retina to check) [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` g(h:t)=h-g(reverse t) g _=0 (>0).g ``` [Try it online!](https://tio.run/nexus/haskell#bU3NCsIwDL73KXLw0EKUdbXrFOqLlCIDu26H/VCLr1/DhuLBBJLw/eQrkQ/XLOxwjDyFV0jPAFmwCHdbsd7yWyVOsUzdOIOFx8KAak3jnOEAU7dCD861aLBBjWdUWKP06CRWn/b@r0eSUpFDk9Ngu3l25PdLTZNuwgwpW2IuxDXb3vMUofqbKL0vbw "Haskell – TIO Nexus") Take list as input. Computes the sum of the first half minus that of the second half by recursively taking the first element and subtracting the recursive result on the reverse. For example: ``` g [1,2,3,4] = 1-g[4,3,2] = 1-(4-g[2,3]) = 1-(4-(2-g[3])) = 1-(4-(2-3)) = 1-4+2-3 = (1+2)-(3+4) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` 2äO`› ``` [Try it online!](https://tio.run/nexus/05ab1e#qymrDP5vdHiJf8Kjhl3/K5UO77dSOLxfSee/oZGxiamZuQWXhbmZqYmxkSEXSATK4DIyNDE3tTC2NDIztgTKGluYchkaGBiCCCAAAA "05AB1E – TIO Nexus") **Explanation** Takes input as list of digits. ``` 2ä # split in half O # sum each part `› # is the first half greater than the second ``` To take input as an integer you could just add `S` for ``` S2äO`› ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~60~~ 40 bytes *Saved some bytes thanks to @MartinEnder* ``` ^(.)+?(?=(?<-1>.)+$) $&; \d $* .(1*);\1$ ``` [Try it online!](https://tio.run/nexus/retina#LYlLDoAgDAX3PQeagpFYyjeoLL0EMS68/xUQEt9qZt6E19Nu1HIpWA4s@0pnFyFBzBnqC0KBRlIyVxKtkWHrfIgQg3eWDcEoP4AhG1zkZDyn/nJ0o9I29gE "Retina – TIO Nexus") [Answer] # PHP, 54 bytes ``` for($n=$argn;~$n[2*$i];)$s+=$n[$i]-$n[-++$i];echo$s>0; ``` takes input from STDIN; empty output for falsy. Requires PHP 7.1. Run with `-nR`. **breakdown** ``` for($n=$argn; # import input ~$n[2*$i]; # loop while there is a 2*$i-th digit (0-indexed) ) $s+=$n[$i] # 1. add $i-th digit -$n[-++$i]; # 2. subtract -1-$i-th digit echo$s>0; # if $s>0, print "1" , else print nothing ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~78~~ ~~62~~ ~~44~~ 35 bytes Crossed out 44 is still regular 44. :c *-16 bytes thanks to LeakyNun. -18 bytes on allowance of integer array input. -9 bytes thanks to Dennis.* Takes input as an array of integers and returns True/False. Note that it relies on Python 2's integer division. ``` lambda s:sum(s[:len(s)/2])*2>sum(s) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbFVcmqtRHG2Vk5qnUaypbxSrqWVkBxbT/F9QlJlXopGmEW2oo2Cko2Cso2Cio2Cqo2Cmo2Cuo2ARq6nJBVdiARYzA8ubgNUCdRiiKEE2BY8SFAGQCrBqc7DJFmBtlmCdZjA23EZjsAJTdBMNYMgQpwwIASX/AwA "Python 2 – TIO Nexus") ### Explanation: *I know this (or anything in Python) doesn't need an explanation but I'm doing it anyways for good practise. :P* ``` s[:len(s)/2] # Gets first half of array sum(s[:len(s)/2]) # Calculates the sum of the values sum(s[:len(s)/2])*2 # Multiplies it by 2 (explanations...) sum(s) # Total sum of the digits sum(s[:len(s)/2])*2>sum(s) # Compares the two sums ``` [Answer] # Python 3, ~~68~~ 62 bytes ``` i=input() print(sum(map(int,i))>2*sum(map(int,i[len(i)//2:]))) ``` ### Short explanation: * `input()` reads a string from `stdin`. * `i[len(i)//2:]` takes the second half of the string. * The `map` functions turn the string to an integer list. * `sum`, `>`, `*2` and `print` do what they say. [Answer] # Python 2, 52 Bytes thanks to help in comments ``` lambda x:sum(x[i]-x[~i] for i in range(len(x)//2))>0 ``` The idea was to substract the first digit from the last, second from second last... and check if the sum of all substractions is greater then 0. [Try it online!](https://tio.run/nexus/python2#fY3NCsIwEITvPsUeE9hi098o6IvEHCK2EmhTiQp5@9iutFhBYQ7LzDez7eEUO9OfLwbC/v7smQrK6iSornEs8MQmQreDBwvWgTfu2rB3ss245sc03rx1D9YyJRAyhByhQCgRKoQaQWrONwsiyasoL4gdG2KFfK78QVbGRBBd07Kk2o6a1XwvH3MCyu/FdJb4mUwaw/gC "Python 2 – TIO Nexus") [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes ``` 2,╡♂Σi> ``` Input is taken as a list of digits. [Try it online!](https://tio.run/nexus/actually#@2@k82jqwkczm84tzrT7/z/aUMdIx1jHRMdUx0zHXMciFgA "Actually – TIO Nexus") Explanation: ``` 2,╡♂Σi> 2,╡ split input into two equal sublists ♂Σ sum each sublist i> is first sum greater than second sum? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 7 bytes ``` œs2S€>/ ``` Saved a byte by changing the input to a list of digits. Saved several more thanks to Leaky Nun! [Try it online!](https://tio.run/nexus/jelly#AR4A4f//RMWTczJT4oKswrXhuKI84bmq////NTY3ODEyMzQ "Jelly – TIO Nexus") Explanation: ``` œs2 Split that list into 2 chunks S€ Sum each chunk individually >/ Reduce the resulting list by relative compare. Prepend this to work with integer input instead of a list: D Turn the integer into a list of digits ``` [Answer] ## JavaScript (ES6), 44 bytes ``` f=([n,...a],d=0)=>1/n?f(a,d-=n-=a.pop()):d<0 ``` ``` <input oninput=o.textContent=this.value.length%2?``:f(this.value)><pre id=o> ``` Takes input as a string or array of digits as characters or integers. [Answer] # C#, 148 bytes ``` void q(){var a=Console.ReadLine();int b=0,c=0,i=0,d=a.Length/2;for(;i<d;i++){b+=int.Parse(a[i]+"");c+=int.Parse(a[i+d]+"");}Console.WriteLine(b>c);} ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` F<mΣ½ ``` [Try it online!](https://tio.run/##yygtzv7/qKkx5b@bTe65xYf2/v//39DI2MTUzNwCAA "Husk – Try It Online") Input as an array of integers. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 13 bytes ``` .,2//{{+}*}/> ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0/HSF@/ulq7VqtW3@7/f0MjYxNTM3MLAA "GolfScript – Try It Online") ``` ., # Get the length of the input "12345678" 8 2/ # Half it "12345678" 4 / # Divide the string in groups of that many digits ["1234" "5678"] { }/ # For each string {+}* # Add the ascii values 202 218 > # Is the first bigger than the second? 0 ``` It actually adds the ascii values of the numbers, but both groups of digits have `d` digits, so both results are `48*d` more than the actual value. This would only be a problem if the groups had different lengths. [Answer] # [C (gcc)](https://gcc.gnu.org/), 79 or 75, 74 better version (80 char -> 79 thanks to titus ) ``` f(char*s){int i=0,n=strlen(s--)/2;for(;*(++s+n);)i-=*s-s[n];putchar(48+(i<0));} ``` [Try it online!](https://tio.run/nexus/c-gcc#VYzLCoMwFET3foW4utcYzFMjqV9SupBSaaBNi7Er8dttUuhrVucwzGwjHM/DVAZcnJ9z17PK92GeLicPgVKshR1vE9gSCAnEo0VH@zLQsPcHe3/MaQzKEHA7hmjXLb1cB@cBsyXLRyi4kEo3rSnQvty0jVZS8Len/t8T1XVkVrGq@DaCq1Yb2YlGdvFCGv3ZMMZ/OCbZuj0B "C (gcc) – TIO Nexus") next, 75 bytes if we rely on constant undefined behaviour, ``` f(char*s){int i=0,n=strlen(s)/2;for(;s[n];)i-=*s-s++[n];putchar(48+(i<0);} ``` [Try it online!](https://tio.run/nexus/c-gcc#VYzLCoMwFET3foW4utcYzFMjqV9SupBSaaBNi7Er8dttUuhrVucwzGwjHM/DVAZcnJ9z17PK92GeLicPgVKshR1vE9gSCAnEo0VH@zLQsPcHe3/MaQzKEHA7hmjXLb1cB@cBsyXLRyi4kEo3rSnQvty0jVZS8Len/t8T1XVkVrGq@DaCq1Yb2YlGdvFCGv3ZMMZ/OCbZuj0B "C (gcc) – TIO Nexus") input valid string in C (a zero terminated array of char) output 1 for true, 0 for false ungolfed version ``` f(char*s) { int i=0; int n=strlen(s)/2; /* n is the length of each strings so we have the start of the first string at *s or s[0], and the start of the second sequence at s[n] */ for(;s[n];) /* until we get 0, all string in C are terminated by 0 */ i-=*s-s++[n]; /* i is the difference between the two characters *s and s[n], then we move the cursor to the next character (s++) :) on the string 12345678, after the first iteration we have i == -4 and 234,678 the proceed */ putchar(48+(i<0)); /* put char '0' if i<0, char '0'+1 otherwise (the char '1') } ``` and now 74 thanks to "a stone arachnid" # [C (gcc)](https://gcc.gnu.org/), 74 bytes ``` f(char*s){int i=0,n=strlen(s)/2;for(;s[n];)i-=*s-s++[n];printf("%d",i<0);} ``` [Try it online!](https://tio.run/##VYxLDoMgFEXnrsKQNAHFyEcUQ11J04Gh1ZK0tAFnxrVTaNLfG92Tc9/V1ax1CBPUl9EVHq3GLrkZCLaDX9z1bKFHNVPT3UHlD/aokKmGwle@LBM9XOxPEOxOAJs9QWoLaeA2GgtRtmZ5dJTxRrSdBEi9WHataDijb07@n1Oq65gJJhh8DaNNJyTvWcv7OMGl@PwQQn9yvERbeAI "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~8~~ ~~7~~ 6 bytes *Thanks to @Razetime for saving 1 byte due to the `⌊` command auto-vectorising.* ``` ½⌊v∑>t ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%BD%E2%8C%8Av%E2%88%91%3Et&inputs=%2212345678%22&header=&footer=) Takes input in the form of `"12345678"`. Alternatively, the quotes can be left out if the `Ṡ` flag is used. I’m gonna be honest, I’m not really sure what the `>` is doing since `(a:string, b:list)` isn’t documented for that command, but I was messing with it and found that in this case it returns `<1|0>` or `<1|1>`, so I take the last value of the list and that’s the answer. Explanation: ``` # Implicit input ½ # Split the input into two chunks ⌊ # Convert both chunks to integers v∑ # Sum the digits of each chunk > # Some sort of a>b thing? t # Tail; last item # Implicit output ``` [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 20 bytes ``` dl2/2->[+]>l3->[+],- ``` [Try it online!](https://tio.run/nexus/python3#xVlLc9s2EL7rVyBuU5GNpEh2TpLtdqaTzPTUHjq9KKqHIUEJDU2yAOnY007/ursLgHiQkCxNpvbFFheLfXz7ILB8zHl1S8SDIOy2rnhDEr69W40kNW/LtKmqwqxxmrUp1atpVRQ0bVhVmvWM/tXCsn6qxKxOmp19rilPmoobAmsol/JXo1FaJEIQISVE8m@8HBGQmJObmy1tgPf25iYStMgnhJUZvZfrhLCcMMFK0SRlSiO5MiGiYCnVDATMblpekuahplJAHBnNMyZZXbkzEMUb@1DV9jet43jkiJSGzvYZOBqh@WhdEwlpTcMftNWS5Ir6jbcUnul9SuuG/J4ULX3PecWXLtOHpBBUiVVo0qhDdUJyxgXYLWhalZlUp3d1LJHPsVKCwHbwOP18lxSR/DEhNaeC8js6AQl3UhKg3BE9g@SG9XyDDMBLKNinidPFZoUOAWW4ZVZXdUHzJoqHO3EtClgnDppX0FKtx@SaLExu@FYTgkrJ1RF2S4vZdme5F0Huc81t/fSVHONpQNtx26zS/a76Tsz3mzvQr3TosEXINVFMXXDqhAsapVWmaq3mmNbjX4HKyi15LcbkNZGrKEeKRfGqxiVNxw17DobtQlmkON9cyV60vlhuVoEQzxWv1vlzWbfNUqtcI4nFJK84YVBqWiB2io2CrczAEFlMK2m3As6lQYXcQY9wSRAECv66JNFw9NShUJEmtcdz2xYNk2Z6Oz@z2n1muWeSYOCstyEv5AZsE/hYVJW3f8spzR5cCnLIVgbE@aoLT1q1Uu7ZmbEt3SXcUO477i87MAEeLyXsJsaADHDg4/pep9I9hmoBKYEPiPkDYs6Tckuj@cQGzfRjCIRKxgeoKEHKqsF@2K0Su3il@qR@jLUK3A7oOdLApCsy/mdMQLn6vRw74npQd9uyPhFi3rAS8e30IIYDPRtHtnEFWonJSdcLoE8lOnYBITbBsQtuRcqq7EXYk2vbg10amm9Tz3FCvY/S2OpyEgMimYYkhkzsUgnFWRGxakVGomxbCxd3GXCV4K6/upLHsz8rVkbrdMcjJu2FFFwsFu8Wi3MlbN6v7LXNsalUutxs4glW@dV4HA9U9/ukbTldk1z2BW6skHA5dy4MG4mWP6jnAfSqAk2Gy84yyL2zMUmgeaEbqtO4VdPvRa5rENh1xTOvLZrq77vndQQVeGPBx49@@odMcdpg16@G6WM12aRTelTr7ThVvid1DfGM0IU0jp2K7Xdpz9ilhQvq3Uj87LVSb8fZ2OrVeAb5bsZObFC@asDLY/P8qVMXvmlCOXxqivmY@3XjWrXX3K8x2MHryuClxIXf0Zvhxh@fAtoryP3phuH0cvoQGpIZ0/JAE1oN0Qt1lsHBZ73xtu4PqAIKTXE2DN/zHlrfGLRsaQTz99@xvR11x5og47e2ILoEC/JNjiiI0BldhwJvJsOzp4FQ3lgOrLs9Qsrav2xuP@Es8WKlscm6E8zA6@@M1yYwQXRm42A7MzeOoeS/zQ5zaVQXx1q@cuG4G/mvNqB5iOJZaIfZ3VsIddRdHO8/iHjs04VFTl1V3//ywbmo7t/g@FaE0XCOioMtmdkCDQgQOKodrUaHayxwovehg@KLQEO8xzd5kNoFrP3ha6yVsWykXnJ55R4qBy8ue5B1aSe561i9Nlbrs6cr1L1O3A@2vnmq@vH@7gMhnkain6q9kccsybJJh5WA@3nsPM03cXzEe/Ng@a9Fe6szcnN8D377IljkECCesbv/FxA1AQxpPRmm718EJjgtPC9CUuHJ4ExfBBzRfnpecKTCk8H540XAqasvzwuOVHgyOK9fpqyq7JnLChWeAE5/6jF8jwde46@cS4sxOni@u@ydaHjVID6hw891mDXAuTKcamCpNI@Co53ThzHBG19oCHPUuCX2hPYvQr3xijdU2TdQCefJ8JbbzSDKzJ0IOxeF4ehY4SCvqSNvBH2pRtBmqAz5yzIcQ4tX6k6rV36qOKdpQ1qRbCmOncllXiTba3Ipqpan9Jqs1Q@5d/OxRMM0y5K8Z82OcjLNcV45TWf4i5UZSyEPBGl2SWPlMEESuB0VlDQV@UShMJOM4Pe3iZ7QTtNDez/xhJXbqsjlyLaT0ZYznJPL8fpcj8TvmbxQjG6RT4/e8UuI9kNT8GsHQqa48EWVj13EiNhVbZGhCjCGKq0Mf4Mx6EY3o1dipWokl8kt6lBUHVX9/XDGBHJEHZsu4S8AIn7ZgrgqUSQBDSbhOqvzGSLWXZXUBwtHt2062oMPiOlrNZTOIUuzV2it0a1rtANLFqvFIj2ABfiPYAT87xnVmdRLQkwenYRa/ePj4zR9zIrzt@fT6/WbzXVxIf9Ppo@L84t37y4Wi/8A "Python 3 – TIO Nexus") Figured nobody else is likely to post a braingolf answer, so here's mine. Takes input as an integer, Prints a positive number for truthy, and a negative number or zero for falsey Explanation: ``` dl2/2->[+]>l3->[+],- d Split last item on stack into digits, push each digit to stack l Push length of stack to stack 2/ Halve last item on stack 2- Subtract 2 from last item on stack > Move last item on stack to start of stack [+] Sum last 2 items of stack 3 times (last 4 items) > Move last item on stack to start of stack l Push length of stack to stack 3- Subtract 3 from last item on stack [+] Sum last 2 items of stack 3 times (last 4 items) ,- Subtract last item (sum of first half) from 2nd to last (sum of 2nd half) Implicit: Print last item on stack ``` [Answer] ## Batch, 122 bytes ``` @set/al=r=0 @set/ps= :l @set/al+=%s:~,1%,r+=%s:~-1% @set s=%s:~1,-1% @if not "%s%"=="" goto l @if %l% gtr %r% echo 1 ``` Takes input on STDIN and outputs `1` if the value is significant. [Answer] # [Java](http://openjdk.java.net/), ~~95~~ 94 bytes ``` boolean f(long n){int x=10,a=x,s=0;for(;a<n;n/=x,a*=x)s+=n%x;for(;n>0;n/=x)s-=n%x;return s<0;} ``` [Try it online!](https://tio.run/nexus/java-openjdk#ZU/LboMwEDzjr/Clkt2mLm@ICP2CtheOVQ8ONcSVs0bYJFQo307tJLfuSuvVjGdGO0x7JVvcKm4MfucSlnWvtRIccEeUhh4DXSRYPNdRuOH1vDF1WHV6JBXfQQUvDuGP9UzNUw0P842B1/DKUPN8BUdhpxGw2YXVZR1uicZy656Tlt/46HJJY0cJ/ecX5mNv6IKCH37ibLJSsablAGLEpsU1BnHG/yjS/BorjkwCrVBwPkgliGnZgZsPMds3CYJQ7xnc/@nJssHlWQXEG/rLCWWdF4FXuMudwptdkOs1ipM0y4sSlUWepUkcIY/cFxRHaZGVyTbOk61jkzJDURhGfrj6Aw "Java (OpenJDK 8) – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), ~~40~~ 38 bytes ``` f s=sum s<2*sum(take(div(length s)2)s) ``` [Try it online!](https://tio.run/nexus/haskell#bU3NDsIgDL77FD14ANODgAxM3JMQDiTblCi4CPr62GzReLBN@jXfT9smKH15JignuSNkNVxHNsQXu435XC9QuOSFtxRihh6G@wao5kfMFbaQwgwTOGfRYIcaD6hQovDoBO4/7f3fjCCnooSmpEG7ZFbm94qkSTtxhpyWlCNp3YLrP0Ws/n4U3rc3 "Haskell – TIO Nexus") Takes the integer as list of digits and returns either `True` or `False`. Example usage: `f [1,2,3,4]`. ``` f s= -- function f takes a list s sum s -- return whether the sum of s <2*sum( ) -- is smaller than two times the sum of take(div(length s)2)s -- the first (length s/2) elements of s ``` **Edit:** Thanks to @nimi for -2 bytes. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~29~~ 17 bytes *Saved 12 bytes thanks to ETHproductions and obarakon* ``` ¯½*Ul)x >Us½*Ul)x ``` [Try it online!](https://tio.run/nexus/japt#@39o/aG9WqE5mhUKdqHFUOb//9GGOmY6xjrmsQA) [Answer] ## Mathematica 36 Bytes ``` #>#2&@@BlockMap[Total,#,Length@#/2]& ``` [Answer] ## Lua, 65 bytes `s=...load("x="..s:gsub(".","+%0"):gsub("+","-",#s/2))()print(x<0)` Steps of conversion: ``` 1234 +1+2+3+4 -1-2+3+4 x=-1-2+3+4 eval the last string print(x<0) ``` Usage: ``` $ lua program.lua 1234 false ``` [Answer] # JavaScript (ES6), ~~67~~ 65 bytes I think it might be too early in the morning for golf; this seems much longer than it needs to be! Takes input as an array of individual digits. ``` n=>(g=(a,b)=>eval(n.slice(a,b).join`+`))(0,l=n.length/2)>g(l,l+l) ``` --- ## Try it ``` f= n=>(g=(a,b)=>eval(n.slice(a,b).join`+`))(0,l=n.length/2)>g(l,l+l) console.log(f([1,2,3,4,5,6,7,8])) // false console.log(f([8,7,6,5,4,3,2,1])) // true console.log(f([1,2,3,4,4,3,2,1])) // false console.log(f([1,2])) // false console.log(f([2,1,4,7,5,8,3,9,2,6,3,9,5,4,3,3,8,5])) // false console.log(f([1,0,0,1])) // false console.log(f([1,0,0,0,0,0])) // true ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~13~~ ~~10~~ 9 bytes -4 bytes by making tacit ``` >/+/0N 2# ``` [Try it online!](https://tio.run/##PUrLCYAwFLs7RamHKqJ9n/4FR3CMXnpwA1evLYoJJCFJWa9Sa06HXrQiAedYQaCAj3hntSWlJonExjof5C6Dd9YwYYu9/WMTQuNt4EiOY/twsH0BwNca5DzUBw "K (oK) – Try It Online") Takes a list of integers as the input. * `0N 2#` split input into pairs * `+/` sum the pairs column-wise * `>/` is the sum of the first chunk larger than the sum of the second? [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 20 bytes ``` [ halves v- Σ 0 > ] ``` [Try it online!](https://tio.run/##ZY/NCoJQEIX3PsV5gSTzJytoG23aRKtocblNKOrVrlchxKfpfXql26gQhAzMzzfnDMxDSFNqezkfT4ctano2pCTVKIRJxuS2NCgm4jYqleWdUGky5lXpVBlkpBXl2DmdA3TwsIKPACEirBGjH2nMfcQs4N2KNf2fdk6nbmABO0P2@9jwHI11uuMzDWceD8tf9E5vr0hE3vJL7QKfN8M9brYQFWojZObaLw "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a sequence of integers from the data stack as input and leaves a boolean value on the data stack as output. Assuming `{ 1 2 3 4 5 6 7 8 }` is on top of the data stack when this quotation is called... * `halves` Split a sequence in half. **Stack:** `{ 1 2 3 4 } { 5 6 7 8 }` * `v-` Element-wise subtraction of two vectors. (This is shorter than summing each sequence individually.) **Stack:** `{ -4 -4 -4 -4 }` * `Σ` Sum. **Stack:** `-16` * `0 >` Is it greater than zero? **Stack:** `f` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` 2ẆʂØv ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPWQmY29kZT0yJUUxJUJBJTg2JUNBJTgyJUMzJTk4diZmb290ZXI9JmlucHV0PTEyMzQ1Njc4JTIwLSUzRSUyMEZhbHNlJTBBODc2NTQzMjElMjAtJTNFJTIwVHJ1ZSUwQTEyMzQ0MzIxJTIwLSUzRSUyMEZhbHNlJTBBMTIlMjAtJTNFJTIwRmFsc2UlMEEyMTQ3NTgzOTI2Mzk1NDMzODUlMjAtJTNFJTIwRmFsc2UlMEExMDAxJTIwLSUzRSUyMEZhbHNlJTBBMTAwMDAwJTIwLSUzRSUyMFRydWUmZmxhZ3M9Qw==) #### Explanation ``` 2ẆʂØv # Implicit input 2Ẇ # Split into 2 pieces ʂ # Sum each inner list Øv # Strictly decreasing? # Implicit output ``` ]
[Question] [ **This question already has answers here**: [Pseudofactorial](/questions/82494/pseudofactorial) (44 answers) Closed 7 years ago. The question's pretty much described by the title: write a program or function that takes a positive integer *n* as input, and returns the smallest positive output which has all integers from 1 to *n* as factors. (Another way of looking at this is that you're looking for the [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) of the integers from 1 to *n*.) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest entry in bytes wins. Inspired by [this challenge](https://codegolf.stackexchange.com/q/105412/62131). (This challenge is basically the inverse of that one.) ## Test cases * **Input:** 1; **Output**: 1 * **Input:** 6; **Output**: 60 * **Input:** 19; **Output**: 232792560 * **Input:** 22; **Output**: 232792560 You don't need to worry about integer precision issues (unless your language has integers so small that this would trivialise the problem). If your language does have bignums, though, you might also want to test your program on this case, just for fun: * **Input:** 128; **Output**: 13353756090997411579403749204440236542538872688049072000 [Answer] ## Python, 46 bytes ``` g=lambda n,c=0:n<1or(c%n<1)*c or g(n,c+g(n-1)) ``` Take that, past xnor! --- **50 bytes:** ``` g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1) ``` I apparently golfed this problem 5 months ago, and I don't remember how this code works or why I golfed it. I think I have a golfing problem. (Edit: It's from [this answer](https://codegolf.stackexchange.com/a/82534/20260). Thanks to Dennis for inspiring the solution and saving 4 bytes.) Apparently, this code recursively finds `lcm(1..n)` as `lcm(lcm(1..n-1),n)`. So, the function `g` expresses `g(n)` as the smallest positive multiple `i*n` of `n` that's also a multiple of `g(n-1)`. (It could instead search multiples of `g(n-1)` for multiples of `n`, but this is golfier because `g(n-1)` only needs to be referenced once. Thanks to Dennis for this improvement.) Here's the rest of the file, full of other golfing attempts: ``` f=lambda a,b:a and f(b%a,a)or b g=lambda n:reduce(lambda a,b:a*b/f(a,b),range(1,n+1)) f=lambda a,b:a and f(b%a,a)or b g=lambda n:n==1 or n*g(n-1)/f(n,g(n-1)) import math g=lambda n:n==1 or n*g(n-1)/math.gcd(n,g(n-1)) g=lambda n,k=1:k*all(k%~i==0for i in range(n))or g(n,k+1) g=lambda n,k=1:min(k%~i for i in range(n))and g(n,k+1)or k l=lambda a,b:a%b and l(b,a%b)*a/(a%b)or a g=lambda n:n<1or l(n,g(n-1)) g=lambda n,i=1:n==0 or (g(n-1)*i if g(n-1)*i%n==0 else g(n,i+1)) g=lambda n,i=1:n<1or g(n-1)*i*(g(n-1)*i%n<1)or g(n,i+1) g=lambda n,i=1:n<1or(i*g(n-1)%n<1)*i*g(n-1)or g(n,i+1) g=lambda n,r=1,c=1:r if n<2 else (g(n-1,r,r)if r%n==0 else g(n,r+c,c)) g=lambda n,r=1,c=1:r*(n<1)or r%n and g(n,r+c,c)or g(n-1,r,r) g=lambda n,i=1:n<1or(i*g(n-1)%n or i)*g(n-1)or g(n,i+1) def g(n): if n==0:return 1 a=b=g(n-1) while b%n:b+=a return b g=lambda n,i=1:n<1or g(n-1)*i%n and g(n,i+1)or g(n-1)*i g=lambda n:n<1or min(range(n,3**n,n),key=g(n-1).__rmod__) g=lambda n,i=1:n<1or(i*n%g(n-1)<1)*i*n or g(n,i+1) r=n=input() while n: c=r while r%n:r+=c n-=1 print r r=n=input() while n: c=r while r%n:r+=c n-=1 print r r=1 for n in range(input()): c=r while r%~n:r+=c print r r=n=input() while n: exec"r+=c*(r%n>0);"*n n-=1;c=r print r r=n=input();exec("r+=r%n and c;"*n+"n-=1;c=r;")*n;print r ``` It's eerie looking at my own past work. In trying to golf it, I keep thinking "maybe I can save some bytes by ..." and then seeing there's already a piece of code that attempted to do just that. You think you've thought of everything, past xnor? Well, I'll show you! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` L.¿ ``` [Try it online!](https://tio.run/nexus/05ab1e#@@@jd2j///@GRhYA "05AB1E – TIO Nexus") **Explanation** ``` L # range [1 ... input] .¿ # least common multiple ``` [Answer] # julia, 11 bytes ``` n->lcm(1:n) ``` [Answer] # Wolfram Language, ~~20~~ 13 bytes ``` LCM@@Range@#& ``` Applies a range from 1 to x, then applies it to LCM. To run this, append `[<input>]`. 7 bytes (!) shaved off by Martin. [Answer] ## JavaScript (ES6), ~~54~~ 50 bytes ``` f=(n,L=1,a=L,b=n)=>n?b?f(n,L,b,a%b):f(n-1,n*L/a):L ``` ### Test cases ``` f=(n,L=1,a=L,b=n)=>n?b?f(n,L,b,a%b):f(n-1,n*L/a):L console.log( 1, f( 1)); console.log( 6, f( 6)); console.log(19, f(19)); console.log(22, f(22)); ``` [Answer] # PHP, ~~61~~ ~~52~~ 48 bytes saved 9 bytes thanks to @user59178, 4 bytes by merging the loops to one. Recursion in PHP is bulky due to the `function` key word; so I use iteration. And with a "small" trick, I now even beat JS. ``` while(++$k%++$i?$i>$argv[1]?0:$i=1:$k--);echo$k; ``` takes input from command line argument. Run with `-r`. **breakdown** ``` while(++$k%++$i? # loop $i up; if it does not divide $k $i>$argv[1]?0 # break when $i is larger than input :$i=1 # while not, reset $i and continue loop with incremented $k :$k--); # undo increment while $i divides $k echo$k; # print $k ``` **ungolfed** That´s actually two loops in one: ``` while($i<=$argv[1]) # break when $i (the lowest non-divisor of $k) is >input for($k++, # loop $k up from 1 $i=0;$k%++$i<1;); # loop $i up from 1 while it divides $k echo$k; # print $k ``` [Answer] # [Perl 6](https://perl6.org), 13 bytes ``` {[lcm] 1..$_} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25uLKrVRQS85PSVWw/V8dnZOcG6tgqKenEl/7vzixUkFJJV4vLbdEQ13VLEVdUwHIA6vV0FRSSMsvUsjJzEst/m/IZcZlaMllZMRlaGQBAA "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 [lcm] # reduce using 「&infix:<lcm>」 1 .. $_ # a Range from 1 to the input ( inclusive ) } ``` [Answer] ## Perl, 32 bytes 31 bytes of code + `-p` flag. ``` $.++while grep$.%$_,2..$_;$_=$. ``` [Try it online!](https://tio.run/#ZzFbz) The code test every number (starting from 1 and incrementing by 1 each time) to find a common multiple. So it's rather slow even for not so large numbers. `grep$.%$_,2..$_` returns an array of the elements of the range `2..$_` (where `$_` is the input) that satisfy `$.%$_!=0` (`$.` is the number we're trying), ie. an array of the elements that aren't a divisor of `$.`. While this array isn't empty, `$.++` is incremented. At the end, `$_` is set tp `$.` and implicitly print thanks to `-p` flag. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ræl/ ``` [Try it online!](https://tio.run/nexus/jelly#@x90eFmO/v///w2NLAA "Jelly – TIO Nexus") When I posted the question, I thought Jelly didn't have a built-in for this. We were discussing the problem in chat, though, and someone pointed out that it does, so I decided I might as well write the obvious solution using it. (That said, 4 bytes is quite a lot for a challenge that's mostly solved via a built-in! It may well be possible to beat this in some other language, or even in Jelly itself. **Update:** I see 05AB1E beat this while I was writing out the entry.) Ideally, this answer shouldn't be voted on either way, in order to let answers which require more skill shine; it's not wrong, but it's also not all that interesting. As the community advert says: **Know how to vote** — **Byte count isn't everything** — **Support clever golfing!** ## Explanation ``` Ræl/ R All numbers from 1 to the input / Reduce by æl lowest common multiple ``` [Answer] ## [GAP](http://www.gap-system.org), 14 bytes ``` n->Lcm([1..n]) ``` Checking the test cases: ``` gap> List([1,6,19,22,128], n->Lcm([1..n]) ); [ 1, 60, 232792560, 232792560, 13353756090997411579403749204440236542538872688049072000 ] ``` [Answer] ## Sage, ~~33~~ 28 bytes No golfing tricks here, but somehow I had an urge to post this xP ``` l=lambda n:lcm(range(2,n+1)) ``` ~~Too bad Sage's `lcm` only takes 2 arguments, unlike Octave's variadic one.~~ *It can actually take a list as input.* [Answer] # Octave, 25 bytes ``` @(n)lcm(num2cell(1:n){:}) ``` [Answer] # Maxima, 29 bytes ``` f(n):=lcm(makelist(x,x,1,n)); ``` [Answer] ## Ruby, 22 bytes ``` ->n{(1..n).reduce:lcm} ``` [Answer] # REXX, 61 bytes ``` arg a do m=1 until a<n do n=1 to a until m//n>0 end end say m ``` (Indented for readability) ]
[Question] [ # Challenge description Let's take a positive integer `n`, reverse its digits to get `rev(n)` and get the absolute value of the difference of these two numbers: `|n - rev(n)|` (or `abs(n - rev(n))`). Example: ``` n = 5067 rev(n) = 7605 |n - rev(n)| = |5067 - 7605| = |-2538| = 2538 ``` After repeating this operation sufficiently many times, most numbers will become `0` (thus terminating the loop)... ``` 5067 -> 2538 -> 5814 -> 1629 -> 7632 -> 5265 -> 360 -> 297 -> 495 -> 99 -> 0 ``` ...though some numbers (like `1584`) get stuck in an infinite loop: ``` 1584 -> 3267 -> 4356 -> 2178 -> 6534 -> 2178 -> 6534 -> 2178 -> 6534 -> ... ^ infinite loop starts here ``` Your job is to determine if a given integer gets stuck in an infinite loop. # Input description A positive integer. # Output description A truthy value (`True`, `1`) if the number gets stuck in an infinite loop, a falsy value (`False`, `0`) otherwise. # Notes * Trailing zeroes should be ommited. i.e. `rev(5020) = 205`. * Remember that this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as short as possible! * Relevant sequence: [A072140](https://oeis.org/A072140) [Answer] # Pyth, 5 bytes 4 bytes thanks to FryAmTheEggman ``` uas_` ``` [Test suite.](http://pyth.herokuapp.com/?code=uas_%60&test_suite=1&test_suite_input=5067%0A1584&debug=0) The truthy value is one of the numbers in the loop. The falsey value is `0`. ## Explanation ``` uas_` Input:Q uas_`GGQ Implicit filling of variables. u Q Set G as Q: do this repeatedly until result seen before: Set G as a the absolute difference of G G ` convert to string _ reverse s convert to integer G and G ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṚḌạµ¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bma4biM4bqhwrXCoQ&input=&args=NTA2Nw) ### Background This uses [@MartinEnder's upper bound](https://codegolf.stackexchange.com/a/84125) of **10n** iterations and the following observations. 1. There are **9 × 10k - 1** positive integers **n** with **k** digits. 2. The difference of a number and its reverse is always a multiple of **9**, so only **10k - 1** of them can occur after the first iteration. 3. Of the multiples, more than **1 / 10** will lose a digit in the next iteration (for starters, all that start and end with the same digits, and roughly twice as many if the first digit is neither a **1** nor a **9**), so it takes at most **9 × 10k - 2** to either enter a loop or lose a digit. 4. Applying the same reasoning to the eventual resulting integer of **k - 1** digits and so on, it takes at most **9 × 10k - 2 + 9 × 10k - 2 + … ≤ 10k - 1 ≤ n** iterations to enter a loop or reach **0**. ### How it works ``` ṚḌạµ¡ Main link. Argument: n µ¡ Iteratively apply the chain to the left n times. Ṛ Reverse n (casts to digits). Ḍ Undecimal; convert from base 10 to integer. ạ Take the absolute difference of the result and the argument. ``` [Answer] ## Mathematica, ~~39~~ 37 bytes ``` Nest[Abs[#-IntegerReverse@#]&,#,#]<1& ``` Simply applies the reverse/subtract transformation `n` times to the input `n` and then checks whether the result is `0`. It can never take more than `10n` steps to reach a loop, because the transformation cannot increase the number of digits, and there are less than `10n` numbers with no more digits than `n`. [See Dennis's proof for how to reduce this bound to `n`.](https://codegolf.stackexchange.com/a/84126/8478) [Answer] # Oracle SQL 11.2, 136 bytes ``` WITH v(n)AS(SELECT :1 FROM DUAL UNION ALL SELECT ABS(n-REVERSE(n||''))FROM v WHERE n>0)CYCLE n SET c TO 0 DEFAULT 1 SELECT MIN(c)FROM v; ``` Un-golfed ``` WITH v(n) AS ( SELECT :1 FROM DUAL UNION ALL SELECT ABS(n-REVERSE(n||''))FROM v WHERE n>0 ) CYCLE n SET c TO 0 DEFAULT 1 SELECT MIN(c)FROM v ``` [Answer] ## APL, 26 chars ``` 0∘{⍵∊⍺:×⍵⋄(⍺,⍵)∇|⍵-⍎⌽⍕⍵} ``` We use the left argument as the accumulator of the values we've seen already. We initialise it to "0", which is one of the two termination conditions. The guard `⍵∊⍺:×⍵` is read: "is the right argument something we've seen already (and that includes zero)? If so return the sign of the number, that is 1 or 0". Otherwise let's recurse by calling ourselves with the absolute value of the subtraction after having catenated the current value to the left argument. A recast of the Mathematica solution by Martin Ender would clock at **21 chars**: ``` {×{|⍵-⍎⌽⍕⍵}⍣(10×⍵)⊣⍵} ``` It reads: "what is the sign of the result after applying the wanted 10n times"? [Answer] # Python 2, 50 bytes ``` n=input() exec'n=abs(n-int(`n`[::-1]));'*n print n ``` Test it on [Ideone](http://ideone.com/W9Bb1e). ### Background This uses [@MartinEnder's upper bound](https://codegolf.stackexchange.com/a/84125) of **10n** iterations and the following observations. 1. There are **9 × 10k - 1** positive integers **n** with **k** digits. 2. The difference of a number and its reverse is always a multiple of **9**, so only **10k - 1** of them can occur after the first iteration. 3. Of the multiples, more than **1 / 10** will lose a digit in the next iteration (for starters, all that start and end with the same digits, and roughly twice as many if the first digit is neither a **1** nor a **9**), so it takes at most **9 × 10k - 2** to either enter a loop or lose a digit. 4. Applying the same reasoning to the eventual resulting integer of **k - 1** digits and so on, it takes at most **9 × 10k - 2 + 9 × 10k - 2 + … ≤ 10k - 1 ≤ n** iterations to enter a loop or reach **0**. [Answer] ## CJam, ~~15~~ 13 bytes ``` ri_{_sW%i-z}* ``` [Test it here.](http://cjam.aditsu.net/#code=ri_%7B_sW%25i-z%7D*&input=5067) Same as my Mathematica answer. [Answer] ## Python, ~~129~~ ~~120~~ 96 bytes If a exception is caught (normally the only exception that can be throwed with this function is a RuntimeError, due to the infinite recursion), print 1. Otherwise, print the result, 0. ``` def r(n):a=abs(n-int(str(n)[::-1]));return a and r(a) try:print(r(int(input()))) except:print(1) ``` Thanks to @LeakyNun Thanks to @shooqie [Answer] # Python, ~~101~~ 98 bytes Tortoise and hare algorithm. Truthy is any value in loop, falsey is `0`. ``` g=lambda n:abs(n-int(str(n)[::-1])) def r(n): t=g(n);h=g(t) while t-h:h=g(g(h));t=g(t) return h ``` [Ideone it!](http://ideone.com/fzXmzU) [Answer] ## Python 2, ~~85~~ ~~84~~ 83 bytes ``` L=[] def f(n,L=L): if n<1or n in L:print n<1 else:L+=[n];f(abs(n-int(`n`[::-1]))) ``` Another Python answer. It adds n to a list for every iteration, and if n is already in the list, it outputs `False`. Otherwise, it works down to 0. *Thanks @NonlinearFruit for one byte.* [Answer] ## 05AB1E, ~~11~~ ~~8~~ 6 bytes ``` DFÂï-Ä ``` **Explained** ``` DF # input number of times do  # push current number and its reverse ï- # convert reverse to int and subtract Ä # absolute value # implicitly print after loop ends ``` Truthy value is a number from the loop. Falsy value is 0. [Try it online](http://05ab1e.tryitonline.net/#code=REbDgsOvLcOE&input=NTA2Nw) Uses the upper bound explained in [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/84126/47066) Saved 2 bytes thanks to @Adnan In [version 7.9](https://github.com/Adriandmen/05AB1E/tree/7f7df2e8c4575ab0669f2129a48a7c2cc623b86b) of 05AB1E the following 5-byte solutions works as noted by @Adnan ``` DFÂ-Ä ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~49~~ ~~32~~ 23 bytes ``` :10*N,?:N:{r:?-+.}itT'0 ``` Returns `true` for infinite loops and `false` otherwise. This is a shameless adaptation of Martin Ender's algorithm. ### Previous answer, 32 bytes ``` g{tTr:T-+U(0!\;?:ImU;?:[U]c:1&)} ``` ### Explanation of the previous answer ``` g{ } Call predicate with [Input] as input tT T is the last element of Input r:T- Subtract T from the reverse of T +U U is the absolute value of T (0!\ If U is 0, return false ; Or ?:ImU If U is in Input, return true ; Or ?:[U]c:1&) Recursive call with U concatenated to the Input ``` [Answer] # Java 7, 161 bytes This requires an import but I wrote it as a function. Yell at me in the comments if a full program is preferred in this scenario. Outputs 1 if there's an infinite loop and 0 if the value gets to 0. ``` import java.util.*;int z(int a){int o,r,c=a;Set s=new HashSet();while(c!=0){for(r=0,o=c;o!=0;r=r*10+o%10,o/=10);c=Math.abs(c-r);if(!s.add(c))return 1;}return 0;} ``` [Answer] ## PowerShell v2+, 94 bytes ``` param($n)for($a=,0;){if(($n=[math]::Abs($n-(-join"$n"["$n".length..0])))-in$a){$n;exit}$a+=$n} ``` Takes input `$n`, starts an infinite `for` loop, with `$a=,0` as the initial condition (this uses the comma operator to set `$a` to an array of one element, `0`). This `$a` is our array of already-seen values. Each loop iteration we check an `if`. The condition first sets the next value of `$n` using string-reversing and the `[math]::Abs` .NET call, and checks whether that value is already `-in` `$a`. If so, we output `$n` and `exit`. Otherwise, we add that value to the array and continue the loop. Outputs `0` for input values where it does not go into an infinite loop (which is falsey in PowerShell) and outputs the value where the loop was encountered otherwise (non-zero integers are truthy). For example, outputs `2178` for input `1584`. [Answer] ## Haskell, 65 bytes ``` _#0=0 a#n|elem n a=1|1<2=(n:a)#abs(n-(read$reverse$show n)) ([]#) ``` Returns `0` for False and `1` for True. Usage example: `([]#) 1584` -> `1`. The obvious approach: keep a list with all results seen so far. Calculate the next number until `0` or it's in the list. [Answer] ## JavaScript (ES6), 75 bytes ``` f=(n,...a)=>a.includes(n=n<0?-n:n)?n:f([...n+``].reverse().join``-n,n,...a) ``` `n<0?n=-n:n` and `n*=n>0||-1` also work. Algorithm somewhat resembles the PowerShell answer, although this is a recursive formulation. [Answer] # Ruby, 57 bytes ``` ->n,*h{h[n]=n=(n-"#{n}".reverse.to_i).abs until h[n];n>0} ``` The initially empty array `h` tracks previously hit values. We iterate the number until we hit a previous value, then check the value on the last iteration. Since 0 is a cycle of 1, it'll be 0 if and only if there's no larger cycle. I take an extra 2 bytes to convert this to a Boolean because 0 is truthy in Ruby. [Answer] # [Perl 6](http://perl6.org) ~~58 53 33~~ 30 bytes ``` ~~sub {$/=%;$^a,{return ?1 if $/{$\_}++;abs $\_-.flip}...0;?0} {$/=%;?($\_,{last if $/{$\_}++;abs $\_-.flip}...0)[\*-1]} {?($\_,{abs $\_-.flip}...0)[10\*\*$\_]}~~ {?($_,{abs $_-.flip}...0)[$_]} ``` ### Explanation: ``` { # block lambda with implicit parameter $_ # coerce the following to Bool # ( False for Nil or 0, True otherwise ) ? ( $_, # start a sequence with the input # block lambda with implicit parameter $_ # subtracts the previous value in the sequence and its reverse # ( .flip is short for $_.flip where a term is expected ) { abs $_ - .flip } ... # repeat that lambda 0 # until you get 0 # get the element indexed with the block's input # may be 0, Nil, or a number that is part of a repeating sequence )[ $_ ] } ``` ( relies on the previous observation that you only need to do this transformation at most `n` times ) [Answer] ## Matlab, ~~89~~ 84 bytes ``` n=input('');z=n;while n z=abs(z-str2num(fliplr(num2str(z))));n=[n z]*all(n~=z);end z ``` Simple approach - stacks all numbers and checks if a number appeared before. **Explanation** ``` n=input('');z=n; -- take input, initiate z while n -- n is said to be positive z=abs(z-str2num(fliplr(num2str(z)))) -- calculate the "reverse and substract" n=[n z] -- put the value at the end of the vector *all(n~=z) -- make the n all zeroes if z is previously in the vector (break the loop) end z -- print z (0 when not entered loop, >0 otherwise) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 25 bytes ``` eval'$_=abs$_-reverse'x$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHXSXeNjGpWCVetyi1LLWoOFW9QiX@/39TAzNzLkNTC5N/@QUlmfl5xf91C/7r5gAA "Perl 5 – Try It Online") It iterates `n=|n-rev(n)|` n times, so output is 0 if there is no loop, >0 otherwise. Dennis already proved this is enough. ]
[Question] [ What general tips do you have for golfing in Prolog? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Prolog (e.g. one letter variables is not specific to Prolog to reduce the size of programs). Please indicate in your tips if it is specific to an implementation of Prolog (e.g. SWI-Prolog specific built-ins) Please post only one tip per answer, or a list of tips that are all closely related to the same main idea. [Answer] # Use Operators for Predicate Names It is possible to give predicates operators as names so long as the operator is one of the predefined operators (listed [here](http://www.swi-prolog.org/pldoc/man?section=operators)) and is not already defined as a predicate. This saves a few bytes both when defining and calling the predicate since operator predicates do not need to be written in the normal `name(arg1,arg2,etc..)` form and can be called as one might expect with operators. For one and two argument predicates, they can be give the names of unary and binary operators, respectively. For higher arity predicates, we can still avoid parentheses using pattern matching. For example if we have a predicate `A+B+C:-...`, Prolog will use its [operator precedence and associativity rules](http://www.swi-prolog.org/pldoc/man?section=operators) to transform it into `(A+B)+C:-...` which is a operator predicate where the first argument is pattern matched to `A+B`. Or `A-B+C*D:-...` which becomes `(A-B)+(C*D)` so its first argument is pattern matched to `A-B` and its second is pattern matched to `C*D`. ### Examples ``` _+_+_. A-B+C*D:-between(A,B,C),C+D. \X:-X>1,X<10. X+Y:-length(Y,X),member(X,Y). 5+[10,5,3,2,5],a+b+c,0-20+X*[2,4,6,5,40],\9. ``` The output will be `X = 5.` [Try it Online!](https://tio.run/##DclZCoMwFAXQ/6xEfTchplpoKAWHRbygUqoEW3AoVnD5qZzP893WaR3l7/iE8KSTEoUsqUpqK3u/H94vUYESVYyKaiVatpIfKfieaiWYnJWTX8b9HTlwjNnPvd8ihotVCDk1qUaOCwzyDi/qaYCWRhMnjUGG65mZ7tDelBB/) ## Corollary Since [DCGs](http://www.swi-prolog.org/pldoc/man?section=DCG) are syntactic sugar for predicates they too can be given operators for names. This works as expected when calling them as DCGs either from a DCG or using the `phrase` predicates or others that are designed to work with DCGs. When calling them as predicates parentheses are required (eg `A+B-->...` must be called like `+(A,B,...)`) since DCG predicates take an additional two arguments for their difference lists. For operator named DCGs with more than two arguments using operator pattern matching then it is important to make sure when calling it as a predicate that the pattern matched operators are distributed correctly. Giving operator names to DCGs that take no additional arguments can be useful if you need to call them within your program since then you can do so without using parentheses. Caution is required because it can be the case that what you save in parentheses you can lose to added spacing required to parse adjacent operators. ### Examples ``` / -->a+b+X,X+d+e. A+B+C-->[A],[B],[C]. X/[],member(c,X),phrase(f+o+o,Y),+(b+a,r,Z,[]). ``` Output will be ``` X = [a, b, c, c, d, e], Y = [f, o, o], Z = [b, a, r]. ``` [Try it online!](https://tio.run/##DcgxDoMgAAXQnVN0hPwP3sAEvASVMICl1aQGA0OPTx3e8q5Wv/Wj@@8YY3poPSdkeHq8UIywcFjuDDYyuNsSzRh@CpFnOXNpcqNXvPaWepFvVFQ@FSEzEhtXhqiMEH8 "Prolog (SWI) – Try It Online") ## Caveats With the unary operators `+` and `-`, Prolog will interpret `+20` or `-20` as numbers instead of a call to a `+/1` or `-/1` predicate. Predicates given unary `+` or `-` as names can still be called on number by using parentheses (`+(20)`, `-(20)`). If avoiding the extra bytes from parentheses is desirable other unary operators such as `\`, `$`, etc can be used as names instead. The combination of pattern matching and operator named predicates is not entirely without flaws. If you have two predicates that have the same operator as their name and with pattern matching one is strictly more general than the other then the more general one may get called first or if the less general one fails (depending on their ordering in the source). For instance in the example above if `A-B+C*D` fails to match its input then Prolog will try calling `X+Y`. This will result in an error because `length/2` require `Y` to be an integer which it will not be since it will be in the form `C*D`. This can be avoided simply by making sure no two predicates have the same operator as their name or if that fails then using cuts and careful ordering of the source. [Answer] # Try to put every possible case into a single rule The clean way to program in Prolog is to declare multiple rules for the same predicate. For example, a predicate to reverse a list with an accumulator would look like this: ``` r([],Z,Z). r([H|T],Z,R):-r(T,[H|Z],R). ``` In Code-golf, we can remove the first rule, and add a `;` at the end of the second rule to code the recursion end: ``` r([H|T],Z,R):-r(T,[H|Z],R);R=[H|Z]. ``` We know that the first condition `r(T,[H|Z],R)` will fail if T is empty, i.e. if the recursion need to end and thus we can add our termination as an or clause after it. The same principle works in a lot of situations. Note however that sometimes it is actually shorter to declare another rule rather than doing this. [Answer] One trick that is frequently useful: Use **CLP(FD) constraints** for integer arithmetic to obtain predicates that can be automatically used in several directions, thus avoiding conditions and dedicated branches and variants. Use B-Prolog or GNU Prolog, where such constraints are available out of the box, without needing to load any libraries. [Answer] # Use arithmetic operators as tuple constructors and cons pairs If you need to pass a single structure consisting of two or more values, the most obvious thing to use is a list, e.g. `[A,B]`. That's really verbose, though. There's an alternative. Prolog values can store a pretty much arbitrary nested structure, which isn't evaluated. Here's an example showing how that works: ``` | ?- member(member(A,B),C). C = [member(A,B)|_] ? ; C = [_,member(A,B)|_] ? ; (etc.) ``` `member(A,B)` is just a named tuple in this situation, and the outside `member` (which is a function call) is treating it as such. Although named tuples are fairly useful in non-golfed Prolog programming, they might seem even more verbose than the list approach. However, we can use pretty much arbitrary characters in the name of the tuple constructor (assuming they're properly quoted); instead of something cute like `member` or a single character like `a`, we can do something like this: ``` | ?- A = '-'('/'(1,2), '/'(3,4)). A = 1/2-3/4 ``` Here, our tuple constructors are `'-'` and `'/'`. And it's interesting to note what the pretty-printer did with them; it's using *infix* notation for the tuples. This is really terse, and parses the same way that the comparable arithmetic operation would. (This also explains why arithmetic uses `is` not `=`; `A = 1+2` would unify `A` with the *tuple* `'+'(1,2)`, so separate syntax is needed to actually evaluate the unevaluated arithmetic expression.) Because a tuple constructor has to be called *something*, you may as well use a character that has a terse syntax (and as a bonus, `-` and `/` are some of the most common choices in non-golfed code too when they want a quick throwaway tuple constructor rather than something meaningful, in much the same way that `i` is often used as a loop variable, so they're entirely reasonable to use in your input and output if you happen to want a tuple there for some reason). `'-'` and `'/'` are good choices for tuple constructors because they have well-behaved and useful precedence, allowing you to write tuple literals tersely. However, note that you don't need to worry about precedence when intermediate values are produced inside the program. Prolog keeps the tuples stored as a tree rather than as source code, and pretty-printers can output it unambiguously: ``` | ?- A = '-'('-'(1,2), '-'(3,4)). A = 1-2-(3-4) ``` Because the tuple syntax is so terse (`f(A,B)` is no shorter than `f(A-B)`), you can replace multiple prediccate arguments with tuples at no cost, meaning that if a predicate needs to pass two or more of its arguments to another predicate, you can often form them into a tuple and just pass the tuple (although this will require changing all calls to the predicate, in addition to the predicate itself, to use an appropriate mix of tuple constructors and commas). Another advantage of this syntax is if you need to use lists internally (rather than to interoperate with standard predicates); a list is basically just a set of nested cons cells, and a cons cell is just a tuple with constructor `'.'`, as can be seen here: ``` | ?- Q = '.'('.'(A,B),'.'(C,D)). Q = [[A|B],C|D] ``` If your code uses lists "manually", it can make a lot of sense to use a less bulky tuple constructor than `'.'`. A common choice for me is to represent a cons cell as `'/'(Tail,Head)` (because it's about the most readable you can get in debug output without wasting characters). Note that you'll probably want your own `[]` equivalent too; you *could* use `[]` but it's two bytes long, and there are plenty of one-byte atoms (all the lowercase letters) that you can use instead. So for example, the following list: ``` [1,2,3] ``` could be converted into a manual representation in the same number of characters like this: ``` x/3/2/1 ``` whilst gaining the advantage that `[H|T]`-style pattern matches can now be written more tersely as `T/H`, and a test against the empty list as just `x` rather than the longer `[]`. (Of course, this comes with the obvious disadvantage that `member`, `append`, etc., won't work on this representation.) [Answer] # Shorter syntax for lists of lists and a way to declare maps You can save bytes on lists of lists. If you have a list `[[1,2],[3,4]]`, you can actually declare it as `[1:2,3:4]`, which saves 4 brackets = 4 bytes. Note that you can use something else than `:` (for example, `^`). `1:2` isn't actually a list in that case (whereas `[1,2]` was), it is represented internally as `:(1,2)`. Therefore you cannot use predicates that work on lists on those sublists that use colons. This trick is mainly used to declare maps, i.e. a list of keys with values attached to them. For example, if you want to declare a map `M` that contains the spelling of a digit in both English and French, you could do something like this: ``` M=[0:'Zero':'Zéro',1:'One':'Un',2:'Two':'Deux', ... ] ``` You can then for example retrieve elements of the map with a built-in predicate like `member/2`. For example, if you want the digit and English word corresponding to `'Quatre'` in `M`, you could do: ``` member(Digit:Name:'Quatre',M). ``` [Answer] One neat trick: When you need to **fail**, use something that is equivalent to **false/0**, but shorter, such as: ``` ?- repeat, writeln(hi), **0=1**. ``` [Answer] # Shorter stdlib alternatives These may not apply exactly based on what you are using the predicates for. * `numlist/3` is better to generate numeric range lists than `between/3` with `bagof`. * `bagof/3` is a substitute for `findall/3` if you can guarantee the result to be a non-empty list. * Many string related predicates also use atoms. eg: `format(atom(X),Y,R)` can be done instead of `string(X)`, saving 2 bytes * some predicates are good aliases for many uses of `foldl`: + `sumlist` in place of `foldl(plus,...)` + similarly for `max_list`, `min_list`, etc. * In `aggregate_all(X,Y,_)` + `X=count,Y=member(...)` case can be replaced with `occurrences_of_term(E,S,O)` [Answer] ## Reuse a predicate with different calling modes For example, you can parse and print a structure with the same predicate, once with a variable argument and another time with a ground term. I used this approach in [Make the Stretchy Snakes Kiss](https://codegolf.stackexchange.com/a/53887/903). This is not possible in all challenges, of course. [Answer] ### Print as a side effect which cannot be undone by backtracking, using backtracking to loop. Goals like "print the first 1000 integers" can be: ``` :-findall(X,(between(0,999,X)),Nums),maplist(writeln,Nums). ``` That can be shortened to: ``` :-findall(X,(between(0,999,X),writeln(X)),_). ``` Backtracking can be used to get rid of the findall loop: ``` :-between(0,999,X),writeln(X),false. ``` Use a shorter `false` as per another tip in these answers: ``` :-between(0,999,X),\+writeln(X). ``` [Answer] `findall/3` will evaluate arithmetic expressions. I expected to have to use `is/2` and another variable for that, but no: ``` ?- findall(X,(between(1,10,X),Y is X^2,Y>20),Xs). Xs = [5, 6, 7, 8, 9, 10]. ?- findall(X,(between(1,10,X),X^2>20),Xs). Xs = [5, 6, 7, 8, 9, 10]. ``` ``` ]
[Question] [ A simple golf to start the week! You're given three arrays: the *base array* `B`, the *value array* `V` and the *index array* `I`. You should produce another array where the values from `V` are inserted into `B` at the indices specified by `I`. Here is an example: ``` Base: [5, 1, 4, 1, 3] Values: [0, 0, 7] Indices: [5, 0, 3] ``` The indices point at the following positions in the base array: ``` [ 5, 1, 4, 1, 3 ] ^ ^ ^ 0 3 5 ``` So inserting the corresponding elements from the value array, the result should be: ``` [0, 5, 1, 4, 7, 1, 3, 0] ``` ## Rules You may write a program or function, taking input via STDIN (or closest alternative), command-line arguments or function arguments and output the result via STDOUT (or closest alternative), function return value, or by modifying the array given as the `B` parameter. If your submission is a function, `I` and `V` can be modified in any way, as well as `B` if it isn't used for output. You may make the following assumptions about the input: * All elements of the base and value array will be non-negative integers. * The value array will have at most one more element than the base array. * The value array and index array will have the same number of elements. * The index array will not contain repeated indices, and all indices will be in range. * The base and value arrays *may* contain repeated elements. * Any or all of the arrays may be empty. * You must not assume that the indices are given in any particular order. * You may receive input and produce output in any convenient, unambiguous string or list format. You may also choose to receive the three arrays in a different order. * You may choose between 0-based and 1-based indexing. This is code golf, so the shortest answer (in bytes) wins. ## Test Cases Given in the format `B V I => Result` for 0-based indexing. If you're using 1-based indexing, increment the elements of the third array by 1. ``` [] [] [] => [] [] [1] [0] => [1] [1,2] [] [] => [1,2] [1,2] [3] [0] => [3,1,2] [1,2] [3] [1] => [1,3,2] [1,2] [3] [2] => [1,2,3] [0,0,0] [1,1,1,1] [0,1,2,3] => [1,0,1,0,1,0,1] [5,1,4,1,3] [0,0,7] [5,0,3] => [0,5,1,4,7,1,3,0] [1,2,3,4] [4,3,2,1] [4,0,3,1] => [3,1,1,2,3,2,4,4] ``` Let me know if you come across other interesting edge cases, and I'll add them. ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. 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 ``` ``` var QUESTION_ID=50369;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table> ``` [Answer] # Python 2, 54 ``` lambda B,*X:map(B.insert,*zip(*sorted(zip(*X))[::-1])) ``` Takes input as `B,I,V`. Modifies the input `B` when called (thanks to Martin Büttner for reminding me this is possible). Uses `map` to call `B.insert` on each index/element pair. To avoid the issue of the list indices shifting as elements are inserted, sorts the pairs in decreasing order of index by an ugly zip/sort/unzip. If not for the shifting issue, we could just do `map(B.insert,*X)`. **Old method (65):** ``` B,V,I=input() for i,v in sorted(zip(I,V))[::-1]:B[i:i]=v, print B ``` [Answer] # Pyth, 14 bytes ``` s.icFPQmedSCtQ ``` [Demonstration.](https://pyth.herokuapp.com/?code=s.icFPQmedSCtQ&input=%5B1%2C2%2C3%2C4%5D%2C%20%5B4%2C0%2C3%2C1%5D%2C%20%5B4%2C3%2C2%2C1%5D&debug=0) This program takes the inputs as a 3-tuple of lists in the order Base, Indices, Values. Explanation on the example `[5, 1, 4, 1, 3], [5, 0, 3], [0, 0, 7]`: 1. Take the input: implicit, Q is the input. 2. Make the index, value pairs: `CtQ` = `[(5, 0), (0, 0), (3, 7)]` 3. Sort the pairs into increasing index order: `SCtQ` = `[(0, 0), (3, 7), (5, 0)]` 4. Take the value out of each pair: `medSCtQ` = `[0, 7, 0]` 5. Split the base list at the location of the indicies: `cFPQ` = `[[], [5, 1, 4], [1, 3], []]` 6. Interleave 3 and 4: `.icFPQmedSCtQ` = `[[], 0, [5, 1, 4], 7, [1, 3], 0, []]` 7. Combine into one list: `s.icFPQmedSCtQ` = `[0, 5, 1, 4, 7, 1, 3, 0]` [Answer] # Haskell, 62 bytes ``` import Data.List f b v i=map snd$sort$zip[0.5,1.5..]b++zip i v ``` Usage example: `f [5,1,4,1,3] [0,0,7] [5,0,3]` -> `[0,5,1,4,7,1,3,0]`. How it works: augment the base list with "and-a-half" indices starting at `0.5` (e.g. `[(0.5,5),(1.5,1),(2.5,4),(3.5,1),(4.5,3)]`) and concatenate it with the index-value pairs. Sort and discard the index. **Remark**: don't know if I'm cheating here. From a mathematical point of view it's fine, but a programmer might argue that the list of indices `[5,0,3]` is not a list of `Integers` as requested, but a list of `Fractionals` (to be exact, the type is polymorphic, but must belong to the `Fractional` class, e.g. `Float` or `Double`). [Answer] # Ruby, ~~60~~ ~~59~~ 53 bytes ``` ->a,b,c{c.zip(b).sort.reverse.map{|i,v|a.insert i,v}} ``` And the ungolfed version ``` def riffle(array, values, indices) indices.zip(values).sort.reverse.each do |index, value| array.insert(index, value) end end ``` [Answer] # CJam, ~~34~~ ~~23~~ 18 bytes ``` {.\2/\ee+{0=}$1f=} ``` My first CJam submission. Advices are welcome, I'm sure there is a lot to golf. 16 bytes saved with the help of @MartinBüttner and @Dennis. Function expecting input on the stack in order `B V I` (I is the topmost). Example usage: ``` [5 1 4 1 3] [0 0 7] [5 0 3] {.\2/\ee+{0=}$1f=}~ ``` Method: * pair the array's `i`th element with `i+0.5` * pair insert values with insert positions * merge the resulting two arrays * sort array based on position elements * keep value elements [Answer] # K, ~~22~~ 21 bytes ``` {,//+(y@<z;(z@<z)_ x)} ``` We define a 3 argument function `{…}` with the implicit variables `x`, `y` and `z` representing the starting list, the value list and the index list, respectively. The "cut" operator (`_`) is used to split the starting list apart at the sorted list of given indices (`(z@<z)`). We interleave values (after sorting them correspondingly) with the split up chunks of the original array by forming a list (`(a;b)`), taking its transpose (`+`) and flattening the result (`,//`). Usage example: ``` f:{,//+(y@<z;(z@<z)_ x)} {,//+(y@<z;(z@<z)_ x)} f[1 2 3 4;4 3 2 1;4 0 3 1] 3 1 1 2 3 2 4 4 f[5 1 4 1 3;0 0 7;5 0 3] 0 5 1 4 7 1 3 0 ``` Spaces around the underscore are necessary because K allows underscores in identifiers. K5 removes this potential ambiguity. If we could count on the indices coming in ascending order and underscores were not valid identifiers, we could use the much nicer 13 byte program: ``` {,//+(y;z_x)} ``` (sigh.) ## edit: ``` {,//+(y@<z;(z@<z)_ x)} / before {,//+(y@<z;z[<z]_ x)} / after ``` Breaks symmetry, but we can save a byte by using bracket-indexing (`[…]`) instead of the infix `@` indexing operator. Usually this makes programs longer, but in this case we needed parens anyway to sort `z` before performing the cut. [Answer] # Pyth, 17 bytes ``` ssC,cFPQamedSCtQ] ``` @isaacg beat my solution already. But since I had my documentation finished, I'm just gonna post it anyways. This takes the input in the format `B, I, V`. You can try it here: [Demonstration](https://pyth.herokuapp.com/?code=ssC%2CcFPQamedSCtQ%5D&input=%5B5%2C1%2C4%2C1%2C3%5D%2C+%5B5%2C0%2C3%5D%2C+%5B0%2C0%2C7%5D&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=QFQ.Qp%22+%3D%3E+%22jdQ%0AssC%2CcFPQamedSCtQ%5D&input=%22Test+Cases%22%0A%5B%5D%2C+%5B%5D%2C+%5B%5D%0A%5B%5D%2C+%5B0%5D%2C+%5B1%5D%0A%5B1%2C2%5D%2C+%5B%5D%2C+%5B%5D%0A%5B1%2C2%5D%2C+%5B0%5D%2C+%5B3%5D%0A%5B1%2C2%5D%2C+%5B1%5D%2C+%5B3%5D%0A%5B1%2C2%5D%2C+%5B2%5D%2C+%5B3%5D%0A%5B0%2C0%2C0%5D%2C+%5B0%2C1%2C2%2C3%5D%2C+%5B1%2C1%2C1%2C1%5D%0A%5B5%2C1%2C4%2C1%2C3%5D%2C+%5B5%2C0%2C3%5D%2C+%5B0%2C0%2C7%5D%0A%5B1%2C2%2C3%2C4%5D%2C+%5B4%2C0%2C3%2C1%5D%2C+%5B4%2C3%2C2%2C1%5D&debug=0) ### Explanation: I'm using the example `B = [5,1,4,1,3], I = [5,0,3], V = [0,0,7]` from the OP. ``` implicit: Q = input() PQ all elements but last of Q => [[5,1,4,1,3], [5,0,3]] cF split B it the indices in I => [[], [5,1,4], [1,3], []] tQ all elements but first of Q => [[5,0,3], [0,0,7]] C zip => [(5,0), (0,0), (3,7)] S sort => [(0,0), (3,7), (5,0)] med extract the end of each pair => [0,7,0] a ] append an empty list => [0,7,0,[]] , create a pair => ([[], [5,1,4], [1,3], []], [0,7,0,[]]) C zip => [([],0), ([5,1,4],7), ([1,3],0), ([],[])] s sum => ([],0,[5,1,4],7,[1,3],0,[],[]) s sum => [0,5,1,4,7,1,3,0] ``` [Answer] # JavaScript (ES6), 75 A function with 3 array parameters, returnning an array. Weirdly, this function modifies its `i` parameter (as kindly allowed by OP) Test running the snippet, Firefox only as usual. ``` f=(b,v,i,j=0)=>b.concat(v).map(p=>(p=i.indexOf(j))<0?b[j++]:(i[p]=-1,v[p])) // TEST out=x=>O.innerHTML+=x+'\n' test=[ { b:[], v:[], i:[], k:[] }, { b:[], v:[1], i:[0], k:[1] }, { b:[1,2], v:[], i:[], k:[1,2] }, { b:[1,2], v:[3], i:[0], k:[3,1,2] }, { b:[1,2], v:[3], i:[1], k:[1,3,2] }, { b:[1,2], v:[3], i:[2], k:[1,2,3] }, { b:[0,0,0], v:[1,1,1,1], i:[0,1,2,3], k:[1,0,1,0,1,0,1] }, { b:[5,1,4,1,3], v:[0,0,7], i:[5,0,3], k:[0,5,1,4,7,1,3,0] }, { b:[1,2,3,4], v:[4,3,2,1], i:[4,0,3,1], k:[3,1,1,2,3,2,4,4] } ]; test.forEach(x=>{ r = f(x.b,x.v,x.i.slice(0)) // pass a copy of i, as the function will alter it ok = ''+r==''+x.k s='Test ' + (ok?'OK':'FAIL') +'\n B ['+x.b +']\n V ['+x.v +']\n I ['+x.i +']\n Result ['+r +']\n Check ['+x.k +']\n' out(s) }) ``` ``` <pre id=O></pre> ``` [Answer] # Mathematica, ~~52~~ 51 bytes ``` Last/@(Tr@#2->#&~MapIndexed~#⋃Thread[#3+.5->#2])& ``` ### Example: ``` In[1]:= f = Last/@(Tr@#2->#&~MapIndexed~#⋃Thread[#3+.5->#2])&; In[2]:= f[{5, 1, 4, 1, 3}, {0, 0, 7}, {5, 0, 3}] Out[2]= {0, 5, 1, 4, 7, 1, 3, 0} ``` ### Explanation: Using the example above. * `Tr@#2->#&~MapIndexed~#` => `{1 -> 5, 2 -> 1, 3 -> 4, 4 -> 1, 5 -> 3}` * `Thread[#3+.5->#2]` => `{5.5 -> 0, 0.5 -> 0, 3.5 -> 7}` * Then take the (sorted) union of these two lists. (=> `{0.5 -> 0, 1 -> 5, 2 -> 1, 3 -> 4, 3.5 -> 7, 4 -> 1, 5 -> 3, 5.5 -> 0}`) * And then take the last element of each pair. (=> `{0, 5, 1, 4, 7, 1, 3, 0}`) [Answer] # CJam, ~~30~~ 29 bytes ``` q~.\2/$z~0@+2ew@f{\~@<>}.\e_p ``` This is tooo long. I feel like this is not a golfing language submission :| [Try it online here](http://cjam.aditsu.net/#code=q%7E.%5C2%2F%24z%7E0%40%2B2ew%40f%7B%5C%7E%40%3C%3E%7D.%5Ce_p&input=%5B1%202%203%204%5D%20%5B4%203%202%201%5D%20%5B4%200%203%201%5D) [Answer] # R, 75 bytes ``` function(b,v,i){n=b;j=0;for(g in v)n=append(n,g,i[j<-j+1]+sum(i<i[j])-1);n} ``` This creates an unnamed function. To call it, give it a name, e.g. `f=function...`. Note that the arrays must be 1-indexed because that's just how R rolls. Ungolfed + explanation: ``` f <- function(b, v, i) { # Initialize the output vector to b n <- b # Initialize an index over the indices j <- 0 # Loop over the values to insert for(g in v) { # Get the index of the next given insertion index j <- j + 1 # Insert g into n. # The position at which to insert the value is determined by # adding the number of indices less than the current one and # subtracting 1. The subtraction is because we're using the # `after` argument in the `append` function. n <- append(n, g, i[j] + sum(i < i[j]) - 1) } # Return n n } ``` Examples: ``` > f(c(), c(), c()) [1] NULL > f(c(0, 0, 0), c(1, 1, 1, 1), c(1, 2, 3, 4)) [1] 1 0 1 0 1 0 1 > f(c(5, 1, 4, 1, 3), c(0, 0, 7), c(6, 1, 4)) [1] 0 5 1 4 7 1 3 0 ``` Suggestions are welcome as always! [Answer] # CJam, 19 bytes ``` l~_,)N*q~.{t}~.\N-p ``` This is a full program that the reads the arrays **B**, **I** and **V** (one per line, in that order) from STDIN. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l~_%2C)N*q~.%7Bt%7D~.%5CN-p&input=%5B5%201%204%201%203%5D%0A%5B5%200%203%5D%0A%5B0%200%207%5D). ### How it works ``` l~ e# Evaluate the first line of input. _,) e# Compute the array length and add 1. N* e# Push a string of that many linefeeds. q~ e# Evaluate the remaining input. .{t}~ e# Vectorized array set: for each index in the array from line 2, replace the e# LF at that index by the corresponding element of the array from line 3. .\ e# Interleave the two arrays on the stack. N- e# Remove the linefeeds. p e# Print. ``` --- # CJam, 20 bytes ``` {Qa+@@.{a2$2$=+t}e_} ``` This is an anonymous function that pops **B**, **V** and **I** (top to bottom) from the stack and leaves a single array on the stack in return. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%5B5%200%203%5D%20%5B0%200%207%5D%20%5B5%201%204%201%203%5D%20e%23%20Push%20input.%0A%7BQa%2B%40%40.%7Ba2%242%24%3D%2Bt%7De_%7D%20%20%20%20%20%20%20%20e%23%20Push%20function.%0A~%20p%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Eexecute%20function%20and%20print.). ### How it works ``` Qa+ e# Append [[]] to B. @@ e# Rotate V and I on top of B. .{ e# For each v in V and the corresponding i in I: a e# Push [v]. 2$2$= e# Retrieve b := B[i]. + e# Append to push [v b]. e# The stack now consists of: B i [v b] t e# Set B[i] := [v b]. } e# e_ e# Flatten B. ``` [Answer] # Ruby, 48 bytes I think this complies with the rules, but please check. ``` ->b,v,i{l=-1;i.map{|j|b[j]=[v[l+=1],b[j]]};b*?:} ``` Unnamed function taking the three arrays as input. Outputs a string that can be parsed unambiguously into an array of numbers with the ruby expression `x.split(/:+/).map(&:to_i)`. Test cases on [ideone](https://ideone.com/vrz1Lt). I could save 3 more bytes, but the output format `[1,2,[nil,5]]` is stretching the rules a bit too mych imo, although it is unambiguous. [Answer] # R, 60 As an unnamed function that takes b, v and i ``` function(b,v,i){e=c(NA,rbind(b,NA));e[i*2+1]=v;e[!is.na(e)]} ``` Expands b with NAs Fills the gaps where required with v Returns the vector without NAs ``` > f=function(b,v,i){e=c(NA,rbind(b,NA));e[i*2+1]=v;e[!is.na(e)]} > f(c(), c(), c()) logical(0) > f(c(0, 0, 0), c(1, 1, 1, 1), c(0, 1, 2, 3)) [1] 1 0 1 0 1 0 1 > f(c(5, 1, 4, 1, 3), c(0, 0, 7), c(5, 0, 3)) [1] 0 5 1 4 7 1 3 0 ``` [Answer] # Java, ~~253, 226, 219,~~ 209 not exactly a winner, but oh well. Assuming that B, V, and I are not null. v (lowercase v) is the length of the Values/Indicies arrays. R is the returned array. r is the length of the returned array. x, y, and i are all temporary ints. ``` int[]f(int[]B,int[]V,int[]I){int v=V.length,r=B.length+v,x,y,i;int[]R=java.utils.Arrays.copyOf(B,r);for(x=0;x<v;x++){i=I[x];for(y=0;y<x;y++)if(I[x]>I[y])i++;for(y=r-2;y>=i;y--)R[y+1]=R[y];R[i]=V[x];}return R;} ``` expanded: ``` int[]f( int[] B, int[] V, int[] I ) { int v = V.length, //length of Values r = B.length + v, //length of the result x, y, i; //temps int[] R = java.utils.Arrays.copyOf( B, r ); for( x = 0; x < v; x++ ) { i = I[x]; for( y = 0; y < x; y++ ) if( I[x] > I[y] ) i++; for( y = r - 2; y >= i; y-- ) R[y+1] = R[y]; R[i] = V[x]; } return R; } ``` [Answer] ## APL, 22 bytes ``` {(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]} ``` In ⎕IO←0 to match the test cases. It's a standard algorithm: the index vector of the first argument is appended to the given indexes (3rd argument). `⍋` computes the permutation that would sort the indexes in ascending order. Since APL's sorting algorithm is stable by definition, the permutation computed puts the element of the catenation of the second and first argument in the right place. [For instance](http://tryapl.org/?a=%7B%28%u220A%u233D2%u2191%u2375%29%5B%u234B%282%u2283%u2375%29%2C%u2373%u2262%u2283%u2375%5D%7D%285%201%204%201%203%29%280%200%207%29%285%200%203%29&run): ``` {(∊⌽2↑⍵)[⍋(2⊃⍵),⍳≢⊃⍵]}(5 1 4 1 3)(0 0 7)(5 0 3) 0 5 1 4 7 1 3 0 ``` ]
[Question] [ > > Given a string, you've to split it into groups of three characters (by padding `_` at the end). > > > [Related](https://codegolf.stackexchange.com/questions/77310/split-string-into-n-pieces-or-pieces-of-length-n), but still it's different. > > > --- **Sample I/O:** * `'abcde' -> 'abc', 'de_'` * `'1234' -> '123', '4__'` * `'' -> [] or falsey value` * `'Three spree!' -> 'Thr', 'ee ', 'spr', 'ee!'` * [6 MB string](https://www.dropbox.com/s/aruy7r9on8z4xst/ThreeSpreeText.txt?raw=1) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes will win! **Edit:** Finally, output is *unrestricted*. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes ``` …___«3ô¨ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcOy@Pj4Q6uND285tOL/f0MjYxMA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##yy9OTMpM/W/i9v9Rw7L4@PhDq40Pbzm04r/O/8Sk5JRULkMjYxMuJTDgCskoSk1VKC4AkooA) **Explanation** ``` …___« # append "___" to input 3ô # split into groups of 3 ¨ # discard the last group ``` [Answer] # Python 3, ~~58 47~~ 34 bytes ~~I'm sure someone else can do better~~ Someone else did better. Thanks Jo King for ~~-11~~ -24 bytes! Output is unrestricted, welcome to tuple hell. Returns empty list ([falsy](https://tio.run/##K6gsycjPM/7/v6AoM69EIy@/RAGIo2M1//8HAA)) on empty input ``` lambda x:[*zip(*[iter(x+"__")]*3)] ``` [TIO](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKlqrKrNAQys6syS1SKNCWyk@XkkzVstYM/Z/QVFmXolGmoaSoZGxiamSpuZ/AA) [Answer] # JavaScript, 25 bytes ``` s=>`${s}__`.match(/.../g) ``` [Try it](https://tio.run/##y0osSyxOLsosKNFNSkxKzdHNy09J/Z9m@7/Y1i5Bpbq4Nj4@QS83sSQ5Q0NfT09PP13zf3J@XnF@TqpeTn66RnSCoZGxSYJOQkIsUFWBRpqm5n8A) [Answer] # APL+WIN ~~36 24~~ 22 bytes 12 bytes saved as a result of output now being de-restricted and using the code in @Adám's first comment modified to work in APL+WIN and a further 2 with his second comment. Thanks. ``` (⌈(↑⍴s)÷3)3⍴(s←⎕),'__' ``` Prompts for input of the string and outputs the result as a nx3 array [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rPOrp0HjUNvFR75ZizcPbjTWNgSyNYqACoEJNHfX4ePX/QIX/07jUDY2MTdS5gIzEpOSUVDArJKMoNVWhuABIKqoDAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~16~~ 15 bytes ``` "@_\__"=~/.../g ``` [Try it online!](https://tio.run/##RY7BjsIgEIbvPMVImgCRra7bvdjQ9AW8eVsNWXVc2dS2KTXGGPfV62CtywGY7/9moMam@OxOHmGJvp3PF1WD0NLVmyxJ2fECeaiMZADie7PdoYDnMhl8BSQ0iB1asdbBeZ99JC@ldwgFJ7GD858PTs@XhwYRfE37SPS9hEIv4XBQ1FcjsWYqZeeDK1A@fqiuNOF4kZHTUaWMrwu3xUeip3qWUui8hN/KlVKMhd6TqFR4NawXzqmXahX8unFlCzxyAG8ZAIf46cEYhgHE@KrkKbsxf9rA/trx3K6s5eZvEsfx5Ke7dXc "Perl 5 – Try It Online") [Answer] # JavaScript, ~~51 50 48 27~~ 25 ``` b=>(b+"__").match(/.../g) ``` [Try it online!](https://tio.run/##bcnLDkAwEEDRva@gqzZixGPLT7BvZmq8Uioqfr@sxeYuzl3xRm/O5bgyQmKb7W7gMDaBmlZSKrQWCja8zCxzAMgnFYzbvbMM1k1ylALJDCyUij5elFX9wz/Uzydz3B1vk3eHBw "JavaScript (Babel Node) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes ``` {$_~"__"~~m:g/.../} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WiW@Tik@XqmuLtcqXV9PT0@/9r81V1p@kYJGTmZearGmQjWXgkJxYqWCnloaV@3/xKTklFQuQyNjEy6ukIyi1FSF4gIgqQgA "Perl 6 – Try It Online") Pads the string by two underscores then splits the string into chunks of three characters. Returns as an array of Match objects. [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes +1 byte to special case the empty string. Can save 2 if we can choose our padding character. ``` ©ò3 ú'_3 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qfIzIPonXzM&input=IjEyMzQi) ``` ©ò3 ú'_3 :Implicit input of string © :Logical AND with ò3 :Split into chunks of 3 ú'_3 :Right pad each with "_" to length 3 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é☻εgP▀╪ ``` [Run and debug it](https://staxlang.xyz/#p=8202ee6750dfd8&i=%22abcde%22%0A%221234%22%0A%22%22%0A%22Three+spree%21%22&a=1&m=2) For an empty string input, the result is an empty array, which is a falsey value in stax. [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` q'_3*+3/);p ``` [Try it online!](https://tio.run/##S85KzP3/v1A93lhL21hf07rg///EpOSUVAA "CJam – Try It Online") For empty input this gives an empty string, which is falsy. ### How it works ``` q e# Read input as a string '_ e# Push char '_' 3* e# String formed by that char repeated 3 times + e# Concatenate to input string 3/ e# Split in groups of 3, the last of which may be shorter. Gives array of strings ); e# Detach last string from the array and delete it p e# Print string representation of the array ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 10 bytes ``` $ __ !`... ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX4UrPp5LMUFPT@///8Sk5JRULkMjYxMurpCMotRUheICIKkIAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` $ __ ``` Append two `_`s, in case the last group needs to be padded. ``` !`... ``` Match as many groups of three as possible, outputting the matches themselves rather than the count. (In Retina 1 this would be `L` instead of `!`.) [Answer] # [C (gcc)](https://gcc.gnu.org/), 67 bytes ``` i;f(char*_){for(;*_;puts(""))for(i=3;i--;)putchar(*_?*_++:95);_=0;} ``` [Try it online!](https://tio.run/##JY3NDoIwEITvPMXaxKTlJ1HBg67El/CmpMFShBKRlHIifXZs4TKZnZl8K5KPEMvSYk1FU@qQs7n@aYohx2EyIyWEMR@0eYptkiBzqR/SkN9DHkXXy5khzw9ol2/Z9pTNAawgI0czPovc3UDKt6gkib09ntJsc5s@Gi0ljIPTHQnAYgDrv96Aclh1y1BFkceCzzrIoaYbXBXMrWHQrqgpoVqaSfcM9tWrJ3HnSxvY5Q8 "C (gcc) – Try It Online") Always returns a falsey value (0). [Answer] # **Ruby, 73 42 bytes** ``` a=gets a.length!=0?a.scan(/.{1,3}/).map{|s|(s+'_'*3)[0,3]}:'falsey value' ``` Edit: As falsey value looks like it's not required: ``` gets.scan(/.{1,3}/).map{|s|(s+'_'*3)[0,3]} ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~28~~ 21 bytes -7: No longer requires falsy (`False`) value on empty input ``` Partition[#,3,1,1,_]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyCxqCSzJDM/L1pZx1jHEAjjY9X@BxRl5pVEK@vapTk4ZyQWJSaXpBYVOyjHquk7VHMpJSYlp6Qq6XApGRoZm4BoEA7JKEpNVSguAJKKSly1/wE "Wolfram Language (Mathematica) – Try It Online") Takes a list of characters as input. Returns a list of 3-tuples of characters padded with `Blank`s (`_`). --- ### ~~34~~ 27 bytes ``` StringPartition[#<>"__",3]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ikKDMvPSCxqCSzJDM/L1rZxk4pPl5JxzhW7X8AUKokWlnXLs1BOVZN36GaSykxKTklVUmHS8nQyNgERINwSEZRaqpCcQGQVFTiqv0PAA "Wolfram Language (Mathematica) – Try It Online") String input, list of strings output [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s3o€“___” ``` A monadic Link accepting a list of characters which yields a list of lists of characters (an empty input yields empty output). **[Try it online!](https://tio.run/##AS0A0v9qZWxsef//czNv4oKs4oCcX19f4oCd/8OHxZLhuZj//2FiY2RlZmdoaWprbG0 "Jelly – Try It Online")** ### How? ``` s3o€“___” - Link: list of characters s3 - split into chunks of three € - for each chunk: o - OR (vectorises): “___” - list of characters = ['_', '_', '_'] ``` Notes: The `€` is only necessary to handle the edge case of an empty input. A full program can drop a trailing `”`, but here we can't do that as the printing behaviour of a full program smashes everything together. --- Equivalent 9: ``` o3ÐƤ“___” ``` [Try it](https://tio.run/##AS0A0v9qZWxsef//bzPDkMak4oCcX19f4oCd/8OHxZLhuZj//2FiY2RlZmdoaWprbG0 "Jelly – Try It Online") --- [Answer] # [J](http://jsoftware.com/), 16 bytes ``` [:}:_3]\'___',~] ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8D/aqtYq3jg2Rj0@Pl5dpy72vyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagnpiUnJKqjqca2hkbILghWQUpaYqFBcASUWEqPp/AA "J – Try It Online") # [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ 17 bytes -2 bytes thanks to ngn! ``` {-1_0N 3#x,"___"} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWtcw3sBPwVi5QkcpPj5eqfZ/mrqGUmJSckqqkrWSoZGxCZACopCMotRUheICIKmopPkfAA "K (oK) – Try It Online") [Answer] # Java 10, ~~116~~ 113 bytes ``` s->{s+="__";int l=s.length()/3,i=l;var r=new String[l];for(;i-->0;)r[i]=s.substring(i*3,i*3+3);return l<1?0>1:r;} ``` [Try it online.](https://tio.run/##rVDNUoMwEL7zFCunpJVYxJMRHB/Aeqg3humEkLbBNDBJwOl0eHZMoXr0oped2Z/vb2vWs6iuPkaumLXwyqQ@BwBSO2F2jAtYX1qAt7IW3AFHG2ek3oPF1M@HwBfrmJMc1qAhhdFG2dku03C7DalnAZVaooTeuwPCd8mtTBXtmQGTavEJM1muCrprDKIyirIVxSaXhUfZrrTTHsmFBy6SZYKpEa4zGtRT/LzK4kdDh5FeTLRdqbyJq5e@kRUcfZar3bwAhucgm5N14kiazpHWr5zSqPY/IJ2TirwYw06WuGaGoR841oSjkJW8EiHGU/a/UcX3ycOvTNNV@B9S7wcjBNjW15tvySEYxi8) Or **~~104~~ 101 bytes** if an empty array instead of `false` is allowed as output.. ``` s->{s+="__";int l=s.length()/3;var r=new String[l];for(;l-->0;)r[l]=s.substring(l*3,l*3+3);return r;} ``` [Try it online.](https://tio.run/##pU9JbsMwDLz7FaxPUlOri3sTHKAPaC7trQgCWVYSuYpskJKLIPDbXWXrA5oDCZKDmeG0alBF23xP2ikieFfWHzIA64PBtdIGFscV4COg9ZuvJWh2HoG4TMiYpUZBBathAR4qmKiYH2hW5atVLpMOuIqEM34Ttow/lnJQCFh583PVdEu57pBJVxTzJ8kxHRKDYk0nnLn78iHVrOQSTYjoAeU4yaNxH2uXjC/@Q2cb2KUE7O9bxS/v7ymYnehiEH2CgvOsTclFDNaJN0S1JxG6M415oVmuat2YnPNTyv8IPL@Ur7fwb@F@btEYoD71u6vOmI3TLw) **Explanation:** ``` s->{ // Method with String as both parameter and return-type s+="__"; // Append two "_" to the input-String int l=s.length()/3; // Get the length, integer-divided by 3 var r=new String[l]; // Create a string-array with that many parts for(;l-->0;) // Loop `l` in the range (l, 0]: r[l]= // Set the `l`'th value of the array to: s.substring(l*3,l*3+3); // Get the substring of size 3 from index `l*3` from `s` return r;} // Return the array ``` [Answer] ## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 74 bytes Just append two underscores '\_' at the end of the input to make sure they get printed if the length of the input isn't a factor of 3. ``` s=>Enumerable.Range(0,(s.Length+2)/3).Select(i=>(s+"__").Substring(i*3,3)) ``` [Try it online!](https://tio.run/##jcxBC4JAEAXgu79i29NsmpV2M/emEHgqoaPoNuqCbbG7gv/epARv4RwezHvwCbMTRo5pr8TZWC1V410S1T9Rl1WHc8U5qUk8mpgvk38tVYNw8MD4GarGtm7A9iHzb9ihsCBjDsalRUGnqq9@EMht6IWMjZFTAy0r8cBpzl@ZNBaYn750UooWBhJzctfSYiYVwsBY5Cwv3c1H2Zc5BuFppUL@MHmrEYl5T7lZyY0f) [Answer] # [Kotlin](https://kotlinlang.org), 34 bytes ``` {"${it}__".chunked(3).dropLast(1)} ``` [Try it online!](https://tio.run/##JcuxDsIgEIDhvU9xIQ53g02MW6P1Bdh8gIYU0EvxSih1ITw7NvHfvuFf1hxY2tcE8APgMyeWF8F5BM1bvv09wr0VdSqc6zSpfn7vsjiLV@ptWqM2W8YL1eZ3gY9hQYLSwVE85hwEPSZnrGZxSI9BKaKuQnOR5x8 "Kotlin – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 55 bytes ``` i;f(char*s){for(;i%4|*s;)putchar(++i%4?*s?*s++:95:10);} ``` [Try it online!](https://tio.run/##JU3LDoIwELzzFWsTkpZiAooHqcSf8KYcsLTyiJW05YR8e20l2UxmZ3Zm@f7FuXM9k5h3jU4MWeRHY9bHxTcxjEyzDTqm1CvXxPihtDyfyjwjbHXvpleYLBH8w1YYa@515XdAzZO3AqWB5odjsbENb50WAszkcYciWFkE4WmvLAxVxoZLwQZKQy0EbYQKJN7Kh5r4a5i0NyRGWAs7a0Ugbh8KpWMw12h1Pw "C (gcc) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 90 bytes This uses Bash features rather than a combination of more traditional Bourne shell plus \*nix commands (which one version I created ended up at 205 bytes). I cheated by using the dodge of adding two \_ characters to the string. ``` c=;read a;a=${a}__;while (($(echo ${#a})>2));do b=${a:0:3};c=$c\ $b;a=${a#$b};done;echo $c ``` [Try it online!](https://tio.run/##JcuxCoQwDADQXwmYod1EN0P9EkGSNFpFTrgbHKTf3lO6vyf8S6VooK9xBCYOeHOeZ7rSdhg4h840nYB3w9mPnfcUT5BXDe3QZ9KAOgFKnQ1KfsDHqC4thUWjLWva9j8 "Bash – Try It Online") [Answer] # [PowerShell](https://docs.microsoft.com/en-us/powershell/), ~~58~~ 35 bytes ``` $args-split'(...)'-ne''|% *ht 3 '_' ``` -23 bytes thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy). [Try it online!](https://tio.run/##NY7BDoIwDIbve4pKimVmkCicTHgL7wRkiskCc8NoAjw7FtAe1v7f1yy13Vs732hjZqwgh2HG0t197K159BQlSSIpbjXRGMKh6SEFKmiehMDu5nNSJCIqq2utScEyqFoXJBXT4ynNFshdZcUPMsD2Zcy2seq/ujROa/CW390iOCsGiolakIQRwkEAF1r@5sPXYrFlx/Oe70e75gAj1rF@spFnwMFNgZjmLw) [Answer] ## [GNU sed](https://www.gnu.org/software/sed/), 27 bytes ``` s:$:__: s:...:& :g s: _*$:: ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v9hKxSo@3oqr2EpPT89KTcEqHchUiNdSsbL6/7@SKz@by9HJmcvQyNiEKzEpOSWVKySjKDVVobgASCoCAA) It gets a bit tricky regarding the empty string input, since sed has no meaning of a falsy value. So to deal with this, I provide you with two possible interpretations of the rules to validate my submission: --- **A.** You essentially provide nothing as input, not even a trailing newline (as it is the case with all the examples, including that 6 Mb file). **Usage:** ``` echo -n ""|sed -f script ``` **Output:** nothing is printed, because sed doesn't even run the script without input. --- **B.** One could consider as falsy value for sed to be an unique string, i.e., returned only when the input is an empty string. **Usage:** ``` echo ""|sed -f script ``` **Output:** ``` __ ``` --- I prefer the first interpretation so much more, as I believe it to be the closest to the intended rule, but the last one helps if you run the script using that TIO link. [Answer] # APL(NARS), 30 chars, 60 bytes ``` {(3/⍳3÷⍨≢v)⊂v←⍵,'_'⍴⍨3∣3-3∣≢⍵} ``` test: ``` f←{(3/⍳3÷⍨≢v)⊂v←⍵,'_'⍴⍨3∣3-3∣≢⍵} ⎕fmt f 'abcde' ┌2────────────┐ │┌3───┐ ┌3───┐│ ││ abc│ │ de_││ │└────┘ └────┘2 └∊────────────┘ ⎕fmt f '1234' ┌2────────────┐ │┌3───┐ ┌3───┐│ ││ 123│ │ 4__││ │└────┘ └────┘2 └∊────────────┘ ⎕fmt f '' ┌0──┐ │┌0┐│ ││ ││ │└¯┘2 └∊──┘ ⎕fmt f 'Three spree!' ┌4──────────────────────────┐ │┌3───┐ ┌3───┐ ┌3───┐ ┌3───┐│ ││ Thr│ │ ee │ │ spr│ │ ee!││ │└────┘ └────┘ └────┘ └────┘2 └∊──────────────────────────┘ ``` [Answer] # [C (clang)](http://clang.llvm.org/), 128 126 94 67 63 bytes *63 bytes thanks to @ceilingcat.* ``` f(char*k){for(;*k;k++)printf("%c%c%c\n",*k,*++k?:95,*++k?:95);} ``` [Try it online!](https://tio.run/##S9ZNzknMS///P00jOSOxSCtbszotv0jDWivbOltbW7OgKDOvJE1DSTUZBGPylHS0snW0tLWz7a0sTeEMTeva/7mJmXkaiTplmmBjtMqsq7kUgACoNzEpOSVVSdNaQV9foSS1uEQhObE4lav2PwA "C (clang) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` s3Zz”_ ``` [Try it online!](https://tio.run/##y0rNyan8/7/YOKrqUcPc@P@H27X1HzWtOTrp4c4ZmpH//yslJiWnpCrpKCgZGhmbgGgQDskoSk1VKC4AkopKAA "Jelly – Try It Online") ## How it works ``` s3Zz”_ - Main link. Takes a string S on the left s3 - Split into chunks of 3 Z - Transpose z”_ - Transpose, using "_" as a filler ``` [Answer] # [Factor](https://factorcode.org/) + `grouping.extras`, 27 bytes ``` [ 3 95 pad-groups 3 group ] ``` [![enter image description here](https://i.stack.imgur.com/ZVtEZ.gif)](https://i.stack.imgur.com/ZVtEZ.gif) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` 3ẇ∩\_ÞṪ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIz4bqH4oipXFxfw57huaoiLCIiLCJUaHJlZSBzcHJlZSEiXQ==) ## How? ``` 3ẇ∩\_ÞṪ 3ẇ # Split into chunks of three ∩ # Transpose \_ÞṪ # Transpose with "_" as filler ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ³'_3Ŀ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCMydfMyVDNCVCRiZmb290ZXI9JmlucHV0PWFiY2RlJmZsYWdzPQ==) ``` ³'_ƬṬ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCMyUyMCdfJTIwdHJhbnNwb3NlX3dpdGhfZmlsbGVyJTIwdHJhbnNwb3NlJmZvb3Rlcj0maW5wdXQ9YWJjZGUmZmxhZ3M9dg==) #### Explanation ``` ³'_3Ŀ '# Implicit input ³ # Split into threes Ŀ # Left-justify each, '_ '# padding with "_"s 3 # to length 3 # Implicit output ``` ``` ³'_ƬṬ '# Implicit input ³ # Split into threes Ƭ # Transpose with '_ '# filler "_" Ṭ # Tranpose again # Implicit output ``` [Answer] # [Haskell](https://haskell.org/), 40 bytes ``` f(a:b:c:t)=[a,b,c]:f t f _=[] f.(++"__") ``` ]
[Question] [ # The challenge Quite simple, given an input `x`, calculate it's infinite power tower! ``` x^x^x^x^x^x... ``` *For you math-lovers out there, this is `x`'s infinite [tetration](https://en.wikipedia.org/wiki/Tetration).* Keep in mind the following: ``` x^x^x^x^x^x... = x^(x^(x^(x^(x...)))) != (((((x)^x)^x)^x)^x...) ``` Surprised we haven't had a "simple" math challenge involving this!\* # Assumptions * `x` will **always** converge. * **Negative and complex** numbers should be able to be handled * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **lowest bytes** wins! * Your answers should be correct to at least **5** decimal places # Examples ``` Input >> Output 1.4 >> 1.8866633062463325 1.414 >> 1.9980364085457847 [Square root of 2] >> 2 -1 >> -1 i >> 0.4382829367270323 + 0.3605924718713857i 1 >> 1 0.5 >> 0.641185744504986 0.333... >> 0.5478086216540975 1 + i >> 0.6410264788204891 + 0.5236284612571633i -i >> 0.4382829367270323 -0.3605924718713857i [4th root of 2] >> 1.239627729522762 ``` --- *\*(Other than a more complicated challenge [here](https://codegolf.stackexchange.com/questions/124391/evaluate-modular-power-towers))* [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 4 bytes ``` *⍣≡⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wStR72LH3UufNS7AshXMNQzAWFDEwUNI63D2400FQ6tN1Qw8DJUAJJ6pgoah7cbayoYeoHEQDJgVSaaAA "APL (Dyalog Unicode) – Try It Online") `*` power `⍣` until `≡` stable `⍨` selfie [Answer] # Pyth, ~~4~~ 3 bytes [crossed out 4 is still regular 4 ;(](https://codegolf.stackexchange.com/a/133541/39242) ``` u^Q ``` [Try it online](https://pyth.herokuapp.com/?code=u%5EQG&input=1.414&test_suite=1&test_suite_input=1.4%0A1.414%0A1.4142135623730951%0A-1%0A1j%0A1%0A0.5%0A0.3333333333333333%0A1%2B1j%0A-1j%0A1.189207115002721) ### How it works ``` u first repeated value under repeated application of G ↦ ^QG input ** G Q starting at input ``` [Answer] # [Haskell](https://www.haskell.org/), ~~100~~ 63 bytes For inputs that don't converge (eg. `-2`) this won't terminate: ``` import Data.Complex f x=until(\a->magnitude(a-x**a)<1e-6)(x**)x ``` Thanks a lot @ØrjanJohansen for teaching me about `until` and saving me `37` bytes! [Try it online!](https://tio.run/##LY3NDsIgEITvPsUePEAtKP4djPWiV59AjdlEqkSg2NKEt8fVcJlvMpPJvHB4a2tzNi50fYQTRpTHzgWr06SF1Iw@GsuuKA4On97E8aEZilRVyPdKiy1n5HnKDo2HBhyG8x1Y6I2PsuVwUXJdA4kiDB96WNYgVA0L2M2A@LNyQ5yvSEr4L5lQvGymZXrLXw "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~40 39~~ 35 bytes * Thanks @Ørjan Johansen for a byte: `d>99` instead of `d==99`: 1 more iteration for a lesser byte-count * Thanks @Uriel for 4 bytes: wise utilization of the fact that `x**True` evaluates to x in `x**(d>99or g(x,d+1))`. The expression in the term evaluates to True for depth greater than 99 and thus returns the passed value. Recursive lambda with a max-depth 100 i.e. for a depth 100 returns the same value. Actually is convergency-agnostic, so expect the unexpected for numbers with non-converging values for the function. ``` g=lambda x,d=0:x**(d>99or g(x,d+1)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P902JzE3KSVRoUInxdbAqkJLSyPFztIyv0ghXQMopG2oqfm/oCgzr0QjXcNQzwTIAwA "Python 3 – Try It Online") [Answer] # Python 3, ~~37~~ ~~30~~ 27 bytes -7 bytes from @FelipeNardiBatista. -3 bytes from from @xnor I don't remember much of Python anymore, but I managed to port my Ruby answer and beat the other Python 3 answer :D ``` lambda x:eval('x**'*99+'1') ``` [Try it online!](https://tio.run/##K6gsycjPM/6fbhvzPycxNyklUaHCKrUsMUdDvUJLS13L0lJb3VBd839BUWZeiUa6hqGeiaYmF4yna4jEMczS1PwPAA "Python 3 – Try It Online") [Answer] # Mathematica, 12 bytes ``` #//.x_:>#^x& ``` Takes a floating‐point number as input. [Answer] # [J](http://jsoftware.com/), 5 bytes ``` ^^:_~ ``` [Try it online!](https://tio.run/##y/r/P03B1kohLs4qvo6LKzU5I19BQ0cvTclAU8FQzwSEDU0UdBQ0VK0UjDSBjHhDBYMsQwUgqWcKFlcwBgkbZoHEgZJAIRMFsOL//wE "J – Try It Online") ## Explanation First, I'll show what command is being executed after parsing the `~` at the end, and the walk-through will be for the new verb. ``` (^^:_~) x = ((x&^)^:_) x ((x&^)^:_) x | Input: x ^:_ | Execute starting with y = x until the result converges x&^ | Compute y = x^y ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 79 78 bytes ``` x=>{var a=x;for(int i=0;i++<999;)a=System.Numerics.Complex.Pow(x,a);return a;} ``` [Try it online!](https://tio.run/##rVFNTwIxEL3zK3rcDbj0a9tuluVC4kkMiQcPxkOzFmzCttoWWEP47euyEjFRBBPfoZ3MdN7rmyn9VWmdakCLcim9BzNnF05WvX1m2517@CCDLsHa6icwldpEPjhtFg@PQLqFjz/fHTv2uHvzQVXJ9cqUo0N8u6qU06VPJrZ6Wap6AE4UxmAOih5o6mK8XUsHZFHnc@sibQLQBcx1vz/KsiyPZXGCIZnZTVQPZJw7FVbOAJnvmrz30w8n1ni7VMm900HdaKOieYQSGsc5@BXDIUCJEIwxQiDDtL1w@gcBdE6iE8gyAQmjUKQ05YLySwUOpakMz8ndqwsRjr/JtQL4Uj6jNqe2FcEB6shbPphQIrDAGWEcc0gwAf02SRhMM0w5EhwRkXJ98ZzOruFjTv9hA321wSiCmFEuBIZUZKizkWLCsKAM4ZSjdt9HG7su2jXv "C# (.NET Core) – Try It Online") I chose to iterate until `i`=999 because if I iterated until 99 some examples did not reach the required precision. Example: ``` Input: (0, 1) Expected output: (0.4382829367270323, 0.3605924718713857) Output after 99 iterations: (0.438288569331222, 0.360588154553794) Output after 999 iter.: (0.438282936727032, 0.360592471871385) ``` As you can see, after 99 iterations the imaginary part failed in the 5th decimal place. ``` Input: (1, 1) Expected output: (0.6410264788204891, 0.5236284612571633) Output after 99 iterations: (0.64102647882049, 0.523628461257164) Output after 999 iter.: (0.641026478820489, 0.523628461257163) ``` In this case after 99 iterations we get the expected precision. In fact, I could iterate until `i`=1e9 with the same byte count, but that would make the code considerably slower * 1 byte saved thanks to an anonymous user. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ³*$ÐL ``` [Try it online!](https://tio.run/##y0rNyan8///QZi2VwxN8/v//b6htmAUA "Jelly – Try It Online") [Answer] # Ruby, ~~21~~ 20 bytes ``` ->n{eval'n**'*99+?1} ``` ~~**Disclaimer**: It [seems](https://en.wikibooks.org/wiki/Mathematics_with_Python_and_Ruby/Complex_numbers_in_Ruby#Exponentiation) that Ruby returns some weird values when raising a complex number to a power. I assume it's out of scope for this challenge to fix Ruby's entire math module, but otherwise the results of this function should be correct.~~ **Edit**: Applied the latest changes from my [Python 3 answer](https://codegolf.stackexchange.com/a/135656/4372) and suddenly it somehow gives the same, expected results :) [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOrUsMUc9T0tLXcvSUtvesPZ/gUJatKGeSSwXlGEIZfomlmToFRcWlWgYaUJEdA2hiiCUc35uQU5qhYaBjqFm7H8A "Ruby – Try It Online") [Answer] # TI-BASIC, 16 bytes The input and output are stored in `Ans`. ``` Ans→X While Ans≠X^Ans X^Ans End ``` [Answer] # [R](https://www.r-project.org/), ~~36~~ 33 bytes -*3 bytes thanks to Jarko Dubbeldam* ``` Reduce(`^`,rep(scan(,1i),999),,T) ``` Reads from stdin. `Reduce`s from the right to get the exponents applied in the correct order. [Try it (function)](https://tio.run/##K/qfX1CSmZ9XrKGekpmeWVKsbmtoqsmVZvs/rTQvGSSjUaEZlJpSmpyqkRCXoFOUWqBRoWNpaampoxOi@T9No7iwqETDSFPzPwA) [Try it (stdin)](https://tio.run/##K/qfX1CSmZ9XrKGekpmeWVKsbmtoqvk/KDWlNDlVIyEuQacotUCjODkxT0PHMFNTx9LSUlNHJ0Tzv6G2YeZ/AA "R – Try It Online") [Answer] # Javascript, 33 bytes ``` f=(x,y=x)=>(x**y===y)?y:f(x,x**y) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~20~~ 10 bytes cut down to half thanks to @LuisMendo ``` t^`Gw^t5M- ``` [Try it online!](https://tio.run/##y00syfn/vyQuwb08rsTUV/f/f0M9EwA "MATL – Try It Online") This is my first [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and my first time using MATL so i'm sure it could be easily outgolfed. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 4 bytes ``` ‡?eẊ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%E2%80%A1%3Fe%E1%BA%8A&inputs=1.4&header=&footer=) [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~165~~ 140 bytes ``` param($a)$u=1;for($r=$a;$u-join'+'|iex){$r=[Numerics.Complex]::Pow($a,($p=$r)) $u=($p.Real,($p|% I*),-$r.Real,-($r|% I*))|% *g '.0000000'}$r ``` [Try it online!](https://tio.run/##nVRbb9owFH7nV/jBW@IuyXyL7RQhISFN6sO2qvQNoSlLzaUihDqJaAX8dmaTwvaAtKR58fF3Lt@5xZtiq0250KtVmBVGH@FssDtuUpPmPkwRrAekPyuMD80Apn1Yh8/Fcu198fZL/Yp2Fp38qHNtllkZjYp8s9Kv09vb@2JrnQMfbgbQINSzUawcPeh05cD9J3B3g4IQmgYKbfQGQ/a4mQMvws3nHaA5Hnq9od8DIABDfzJ@KyudR1dI13rrk4gHAKMA/NdOKSEEY1hQbg8aOzfUmoS0pUkShZngWMU8lorLDjST72m1sPL4xVQ@Ra0IaYf4IWkV0pmFOGrfnXad6ZAojuJWMXEkOCEqlpzHmCdKfKDZbnNtEwn4CjhqOWPKEkGlpElMqRRdRmCdsWViEUYtK4y5VFgJSkTMcSI7ra0tq2UTMRWWR1HMVeImFcWUCaq4IDSWxP4vrUdnd6cVKWeKKpowIanEjLLTzjGB44RySZQkzM61A@sHSa9yIrAH3@zTmGaL8OfvZ51VYGcTgZUuq1Fa6gBA/bqxsH4CAwB/OZ3RZb2q7PUznP21dJragv67vnn@ztbRXZ7Ol@vUvP0T8WxyuV@MrqVl2aPHYlyZ5Xrue7h5Rj0EDpZ5cj8e1WVV5I3xdOiKAGBcZ5kuS@BSryd4CkL94iRqpXT95ERyAdm0f3J6fC/IOZ2LazQPTeGncE1ZDj/0Dr3j8Q8 "PowerShell Core – Try It Online") *-7 bytes* thanks to [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)! [55 bytes without complex numbers](https://tio.run/##VZBfa8IwFMWf208RXBgNtDVJ869KQRjb25jMvYmMrovIUFrTigPnZ@9uVyvuKbn3nPu7h1uVR@vqjd1uo6J0tsXr7NRWuct3Ac7JunQBdhnOp9hFuCInKJbPebNZTSbz8giWMMBVhh0hZ@zas@/PAt8LZwGLRYhYbIxSKkmo4gIeLskgsj85TQ1NlKBGCqmN0L08LFjsXRNwEqIRH/VKxEIUsQsEAP2PxjJENFaCMSO1EJKK1Kj/rC4sh4mxIN1inqSKa81TyblWHLx3YIZgdJzElHQ4KbShRnGmpKCphugE/aAnuFFebKKXjy9bNOjke7ixdfOQ1zZE2H5X0LWfKEP4HSRn68O2geoer9HV6HvL@eLhUDflrsesZsDxFoeisHXdzV45kd2jC2UKlrcLofMMtK7/Ouy58T7eZBl40D/757b9BQ) [Answer] # [Perl 6](http://perl6.org/), 17 bytes ``` {[R**] $_ xx 999} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjpISytWQSVeoaJCwdLSsva/tUJxYqWCElDE1k6hOg0oVaukkJZfpGCoZ6KjkKmjYKBnCiKMQUBHwVA70/o/AA "Perl 6 – Try It Online") `R**` is the reverse-exponentiation operator; `x R** y` is equal to `y ** x`. `[R**]` reduces a list of 999 copies of the input argument with reverse exponentiation. ]
[Question] [ # Background The [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight) of an integer is the number of ones in its binary representation. For this challenge, integers are represented with 32 bits, and they are unsigned. # Challenge Given an integer between 0 and 2^32-1 (non-inclusive), output a *different* integer within the same range, and also with the same Hamming weight. # Examples ``` Input (Decimal) | Input (Binary) | Hamming weight | Possible output (Decimal) 46 | 0b0010 1110 | 4 | 15 12 | 0b0000 1100 | 2 | 3 1 | 0b0000 0001 | 1 | 2 3 | 0b0000 0011 | 2 | 6 2^31 | 0b1000....0 | 1 | 1 2^31+2 | 0b1000...10 | 2 | 3 2^32-5 | 0b1111..011 | 31 | 2^31-1 2^32-2 | 0b1111....0 | 31 | 2^31-1 0 | 0b0000 0000 | 0 | None (This case need not be handled) 2^32-1 | 0b1111....1 | 32 | None (This case need not be handled) ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution in the fewest bytes in each language wins. [Answer] # x86-64 assembly, ~~5~~ 4 bytes ``` 0: 97 xchg %eax,%edi 1: d1 c0 rol %eax 3: c3 retq ``` A function using the C calling convention that bitwise rotates its argument left by 1 bit. [Answer] # Python, 20 bytes ``` lambda x:x*2%~-2**32 ``` Bitwise rotation left by 1 bit. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` 32&B1YSXB ``` Circularly shifts the 32-digit binary representation one step to the right. [Try it online!](https://tio.run/##y00syfn/39hIzckwMjjC6f9/QwA "MATL – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 8 bytes ``` ‘&~^^N&$ ``` Swaps the least significant set and unset bit. [Try it online!](https://tio.run/##y0rNyan8//9Rwwy1urg4PzWV/0f3HG5/1LRG4eGO7Y8a5ihEZRYoZOYVlJYoJOalKJRkpCoUpRaX5pQUK@Sngbk5mXnZegqPGuYqHNqqYK3kFAzUrIJkgGNBQSpUp0dibm5mXrpCeWpmekZJMUSX@///JmY6CoZGOgpGWlrGRrpAhqGOgjGEawgA "Jelly – Try It Online") ### How it works ``` ‘&~^^N&$ Main link. Argument: n ‘ Increment; yield n+1, toggling all trailing set bits and the rightmost unset bit. ~ Bitwise NOT; yield ~n, toggling ALL bits of n. & Bitwise AND; yield (n+1)&~n, keeping the only bit that differs in n+1 and ~n, i.e., the rightmost unset bit. ^ Perform bitwise XOR with n, toggling the rightmost unset bit. $ Combine the two links to the left into a monadic chain. N Negate; yield -n. Since ~n = -(n+1) in 2's complement, -n = ~n+1. & Take the bitwise AND of n and -n. Since -n = ~n + 1 and n = ~~n, the same reasoning that applied for (n+1)&~n applies to -n&n; it yields the rightmost unset bit of ~n, i.e., the rightmost set bit of n. ^ XOR the result to the left with the result to the right, toggling the rightmost set bit of the left one. ``` [Answer] ## JavaScript (ES6), ~~35~~ 31 bytes Looks for the first bit transition (0 → 1 or 1 → 0) and inverts it. ``` f=(n,k=3)=>(n&k)%k?n^k:f(n,k*2) ``` ### Demo ``` f=(n,k=3)=>(n&k)%k?n^k:f(n,k*2) ;[ 46, 12, 255, 2**32-2 ] .map(n => { r = f(n); console.log((n >>> 0), '=', (n >>> 0).toString(2), '-->', (r >>> 0), '=', (r >>> 0).toString(2)); }) ``` ## Bit rotation, 14 bytes Much shorter but less fun. ``` n=>n>>>31|n<<1 ``` ### Demo ``` let f = n=>n>>>31|n<<1 ;[ 46, 12, 255, 2**32-2 ] .map(n => { r = f(n); console.log((n >>> 0), '=', (n >>> 0).toString(2), '-->', (r >>> 0), '=', (r >>> 0).toString(2)); }) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 78 bytes ``` (([()()])[[]()]){((){}<({({})({}())}{})>)}{}([(({}(({}){})())<>)]){({}())<>}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0MjWkNTQzNWMzo6FkRVa2hoVtfaaFRrVNdqArGGpmYtkGUHIoFKQSIgGZCkpqaNHVgHWJWNHVDF//9GhibmJhbGZiYWAA "Brain-Flak – Try It Online") Returns 2n if n < 2^31, and 2n+1-2^32 otherwise. Unfortunately, because Brain-Flak doesn't have any fast way to determine the sign of a number, the program times out on TIO if the input differs from 2^31 by more than about 500000. ### Explanation First, push -2^32 onto the stack: ``` (([()()])[[]()]) push (initial value) -2 and (iterator) -5 {((){}< >)} do 5 times: ({({})({}())}{}) replace the current (negative) value with the negation of its square {} pop the (now zero) iterator ``` Then, compute the desired output: ``` (({}){}) replace n by 2n on left stack ({} ()) push 2n+1-2^32 on left stack ( <>) push again on right stack ([ ]) push its negation on right stack {({}())<>} add 1 to the top value of each stack until one of them reaches zero {} pop this zero, and implicitly print the number below it on the stack ``` [Answer] # dc, 10 ``` ?2~z31^*+p ``` [Try it online](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnYGKmYGikYGJkaWJpZg4kFaoN9fQMDWqtFVLyuRSAoKAoM68kTUFJtVhB105BSUEFphssm5qckY8QUqhRSElW0E1VUP9vb1RXZWwYp6Vd8F@dKyU/L/U/AA). This is an arithmetic implementation of a 32bit right-rotate: ``` ? # input 2~ # divmod by 2 - quotient pushed first, then the remainder z # z pushes the size of the stack which will be 2 (quotient and remainder) ... 31^ # ... and take that 2 to the 31st power * # multiply the remainder by 2^31 + # add p # output ``` [Answer] # APL, 12 bytes ``` (2⊥32⍴1)|2×⊢ ``` **How?** ``` ⊢ ⍝ monadic argument 2× ⍝ shift left (×2) (2⊥32⍴1)| ⍝ modulo 2^32 - 1 ``` [Answer] # Java 8, ~~117~~ ~~17~~ 29 bytes ``` n->n*2%~-(long)Math.pow(2,32) ``` +12 bytes by changing `int` to `long`, because `int`'s max size is `2³¹-1` ~~100~~ 89 bytes saved by creating a port of [*@AndersKaseorg*'s amazing Python answer](https://codegolf.stackexchange.com/a/124087/52210). [Try it here.](https://tio.run/##zZO9TsMwFIX3PMVRJCSbEos6bfmJYGBup25FDMYNxSW9jhK3qEXh1YNNOiABc@rBV74@555PlrxWO5XYMqf18q3VhaprzJShjwgw5PLqRekci3AECksraDYNhXjme03kt9opZzQWOOAOLSX3dC7PPhMW5Hym3Kso7TuTF6nkbRYM5fa58Iajb2fNEhufyeauMrR6fILiPwKNnzqaTLPvznxfu3wj7NaJ0otdQcxggBgs9iWQCWcfDKlq301jhod7fosgOAh9bPxv6DSdK@ZdbGAYyhNg6B8hPYFXuPSrf4yb66vJeNQ/x6@PhnTI@6f6A0t6XQLZI1sTNe0X) Outputs: ``` 46 (101110): 92 (1011100) 12 (1100): 24 (11000) 1 (1): 2 (10) 3 (11): 6 (110) 10000 (10011100010000): 20000 (100111000100000) 987654 (11110001001000000110): 1975308 (111100010010000001100) 2147483648 (10000000000000000000000000000000): 1 (1) 4294967294 (11111111111111111111111111111110): 4294967293 (11111111111111111111111111111101) ``` **Old answer (~~117~~ 118 bytes):** ``` n->{long r=0;for(;!n.toBinaryString(++r).replace("0","").equals(n.toBinaryString(n).replace("0",""))|r==n;);return r;} ``` +1 byte by changing `int` to `long`, because `int`'s max size is `2³¹-1` [Try it here.](https://tio.run/##zZPBUsIwEIbvPMWaUzLQAAVRydSDZzjhCcdDLAEDJalpigPYZ69J24Mjei457E7@/Lv5NjPZ8gMPdCrUdrUr44RnGcy5VOcOgFRWmDWPBSz9FiDRagMxnvmkCHNa0XEhs9zKGJZwgghKFTyeK6OJBmytDWY3ilr9JBU3x4U1Um1wt2sINSJNXHOMBqiHEKHiI@dJhi/M6sJKvkwUKUaYETY3CgwrSuZJ0vwtcSQN0EHLFezdMLju9PIKnPyYRDrc8WTGKmVxzKzYU51bmjqzTRSW0AUEGLnkR/7NJYk/J1PwhhONG@H/gtpTVyFSX@sZhuEVMLSPMLqCVxi41T7Gw/3d5HbcPgf234TMuX2nqf7EYQ9GQ9IqVRX6fXjmO5GB1br6ydNGrpj/gA5dlwBC1thaYS86RfkN) Outputs: ``` 46 (101110): 15 (1111) 12 (1100): 3 (11) 1 (1): 2 (10) 3 (11): 5 (101) 10000 (10011100010000): 31 (11111) 987654 (11110001001000000110): 255 (11111111) 2147483648 (10000000000000000000000000000000): 1 (1) ``` [Answer] ## Mathematica, 29 bytes ``` Mod@##+Quotient@##&[2#,2^32]& ``` [Try it at the Wolfram sandbox](https://sandbox.open.wolframcloud.com/) Rotates left arithmetically: first multiply by 2, which possibly shifts the number out of range, then cut off the out-of-range digit with `Mod[...,2^32]` and add it back on the right with `+Quotient[...,2^32]`. (Mathematica does have a single builtin that gives the modulus and the quotient in one go, but it's `QuotientRemainder`, which is a bit of a golfing handicap…) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ·žJ<% ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0Paj@7xsVP//NzGyNLE0MzeyNAYA "05AB1E – Try It Online") **Explanation** Uses the trick to rotate the binary representation left by 1 bit from [Anders Kaseorg's python answer](https://codegolf.stackexchange.com/a/124087/47066). ``` · # input * 2 % # modulus žJ< # 2^32-1 ``` [Answer] ## R, ~~42~~ 63 bytes ``` function(x){s=x;while(s==x){sample(binaryLogic::as.binary(x))}} ``` Shuffles the bits around randomly, but checks to make sure it didn't return the same number by chance. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~81~~ 80 bytes (1 byte saved thanks to @Ørjan Johansen reminding me dup is shorter than push 0) ``` ``` [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIAgIgxanACRQCczkVoACsDkFxgoWgSkAagIYocP7/b2RoYm5iYWxmYg4A "Whitespace – Try It Online") Basically implements a cyclic right bitshift using integer arithmetic. Pushing a large constant is expensive in Whitespace so we save some bytes by pushing 2^8 and squaring it twice. (Saves 1 byte over (2^16)^2 and 10 bytes over pushing 2^32 directly.) ## Explanation ``` sssn ; push 0 sns ; dup tntt ; getnum from stdio ttt ; retrieve n from heap and put it on the stack sns ; dup ssstsn ; push 2 tstt ; mod - check if divisible by 2 (i.e. even) ntsn ; jez "even" ssstssssssssn ; push 2^8 sns ; dup tssn ; mul - square it to get 2^16 sns ; dup tssn ; mul - square it to get 2^32 tsss ; add 2^32 so MSB ends up set after the divide nssn ; even: ssstsn ; push 2 tsts ; divide by 2, aka shift right tnst ; putnum - display result ``` [Answer] # Python 2.7, 89 bytes Full Program: ``` from random import*;a=list(bin(input())[2:].zfill(32));shuffle(a);print int(''.join(a),2) ``` [Try it online!](https://tio.run/##DcsxDsIwDEDRq3SrjaBDQAxEnKRiMKVRjFI7St2B3rtzyPD1pp9/FlVcraHo0hWST4OXrMVOnp6JV4M3C7DkzQBxdI/XsAdOCa4O0a9xCyHNQOhzYbGuBX0/fLVNhGeHtd7uh@hloinOfw) Suggestions welcome! :) [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 bytes ``` n->2*n%(2^32-1) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P185IK09VwyjO2EjXUPN/QVFmXolGmoaRpuZ/AA "Pari/GP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` Ñ%3pH ``` Bitwise rotation, like most answers here. [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0SUzcEg&input=MTI) [Answer] # [Perl 5](https://www.perl.org/) `-p`, 39 bytes ``` $_=sprintf'0b%b',$_;$_=oct$_.int s/10// ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ra4oCgzryRN3SBJNUldRyXeGiiWn1yiEq8HFFYo1jc00Nf//9/8X35BSWZ@XvF/XV9TPQNDAyCdlJkOVPJftwAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 45 bytes ``` lambda i:int(f'{i:32b}'[1:]+f'{i:32b}'[:1],2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZRvzPycxNyklUSHTKjOvRCNNvTrTytgoqVY92tAqVhuJa2UYq2Ok@b@gCKRMw9DGxthQU9tQRyELwdHU/A8A "Python 3 – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~45~~ 39 bytes *-6 bytes thanx to ceilingcat* ``` auto h(unsigned x){return x%2<<31|x/2;} ``` [Try it online!](https://tio.run/##RY1dC4IwGEav2694UQYbGOmMPlD6Jd3INnVQrzI3GJi/fVlE3p3ncOCR47jvpIyx8W6AnnmcTIdaQeCz1c5bhEBFXZfFKxxEtcTUoHx4pWs5OWWGGyGp0q1BDU5PjgUOozXoWpZQD9TfMclC1q@eE7J6eDYGGScz2X37nFc/Kjb63P2XyLfmehHn8nRc9xLf "C++ (gcc) – Try It Online") ]
[Question] [ This is inspired by a real world problem I had. I'm curious to see if there is any clever way to go about this. You are given two unsorted arrays, A and B, each containing an arbitrary number of floats. A and B don't necessarily have the same lengths. Write a function that takes the elements of A sequentially and finds the nearest value in array B. The result has to be contained in a new array. **Win condition** Shortest code wins (as usual). [Answer] # APL, 13 ~~17~~ (21 byte in UTF-8) ``` B[{↑⍋|⍵-B}¨A] ``` If you want true lambda (A as left argument and B as right): ``` {⍵[⍺{↑⍋|⍺-⍵}¨⊂⍵]} ``` ## How it works: `{...}¨A` invokes lambda function `{...}` with every A value (instead of invoking with A as array), gathering results to array of same shape `|⍵-B` computes absolute values of difference between argument ⍵ and all in B (- is subtraction, | is abs). `↑⍋` takes index of least element (⍋ sorts array returning indices, ↑ get first element) `B[...]` is just fetching element(s) by index(es). The solution is quite strightforward, altough it uses wonderful feature of APL's sorting function returning permutation vector (sorted element's indices in original array) rather than sorted array itself. [Answer] ## Mathematica - 17 ``` #&@@@Nearest@A/@B ``` How does it work? Yes, I admit that there's a bit of cheating here because Mathematica has built-in [nearest](http://reference.wolfram.com/language/ref/Nearest.html) functionality. The rest is straightforward and is concerned with arranging the result in a 1D array. It looks ugly only because of the extra effort to make it short. [Answer] # C# - 103 97 87 Bytes I'm not quite sure if I understood this question correctly but here is my solution anyway. I used Lists instead of arrays, because it allows me to write shorter code. A integer array is shorter than a integer list. **Input:** ``` t(new int[] { 0, 25, 10, 38 }, new int[] { 3, 22, 15, 49, 2 }); ``` **Method:** ``` void t(int[]a,int[]b){var e=a.Select(c=>b.OrderBy(i=>Math.Abs(c-i)).First()).ToArray(); ``` **Output:** ``` 2, 22, 15, 49 ``` If my answer isn't correct, please leave a comment below it. **EDIT:** AS @grax pointed out, the question is now about floats. Therefore I'd like to include his answer too. # 95 Bytes(Grax's answer) ``` float[]t(float[]a,float[]b){return a.Select(d=>b.OrderBy(e=>Math.Abs(e-d)).First()).ToArray();} ``` [Answer] ## R, 41 chars ``` B[apply(abs(outer(A,B,`-`)),1,which.min)] ``` Explanation: `outer(A,B,`-`)` computes for each element x of A the difference `x-B` and outputs the result as a matrix (of dimension length(A) x length(B)). `which.min` picks the index of the minimal number. `apply(x, 1, f)` applies function `f` on each row of matrix `x`. So `apply(abs(outer(A,B,`-`)),1,which.min)` returns the indices of the minimal absolute difference between each element of A and the elements of vector B. Usage: ``` > A <- runif(10,0,50) > B <- runif(10,0,50) > A [1] 10.0394987 23.4564467 19.6667152 36.7101256 47.4567670 49.8315028 2.1321263 19.2866901 0.7668489 22.5539178 > B [1] 44.010174 32.743469 1.908891 48.222695 16.966245 23.092239 24.762485 30.793543 48.703640 6.935354 > B[apply(abs(outer(A,B,`-`)),1,which.min)] [1] 6.935354 23.092239 16.966245 32.743469 48.222695 48.703640 1.908891 16.966245 1.908891 23.092239 ``` [Answer] # CJam - 14 ``` q~ f{{1$-z}$0=\;} p ``` The main code is on the second line, the rest is for using the standard input and pretty output. Try it at <http://cjam.aditsu.net/> **Explanation:** `q~` reads and evaluates the input `f{...}` executes the block for each element of the first array and the next object (which is the second array), collecting the results in an array `{...}$` sorts the second array using the block to calculate a key for each item `1$` copies the current item from the first array `-z` subtracts then takes the absolute value `0=` takes the first value of the sorted array (the one with the minimum key) `\;` discards the item from the first array `p` prints the string representation of the result **Examples** (inspired from other answers): Input: `[10.1 11.2 12.3 13.4 9.5] [10 12 14]` Output: `[10 12 12 14 10]` Input: `[0 25 10 38] [3 22 15 49 2]` Output: `[2 22 15 49]` [Answer] # Javascript (E6) 54 ~~56 59~~ Minimize distance. Using square instead of abs just so save chars. **Edit** algebra ... **Edit** fix useless assignment (a remainder of a test w/o the function definition) ``` F=(A,B)=>A.map(a=>B.sort((x,y)=>x*x-y*y+2*a*(y-x))[0]) ``` Was `F=(A,B)=>D=A.map(a=>B.sort((x,y)=>((x-=a,y-=a,x*x-y*y))[0])` **Test** ``` F([10.1, 11.2, 12.3, 13.4, 9.5],[10, 12, 14]) ``` Result: `[10, 12, 12, 14, 10]` [Answer] # Python 3.x - 55 chars ``` f=lambda a,b:[min((abs(x-n),x)for x in b)[1]for n in a] ``` `a` and `b` are the input arrays, and the desired array is the expression's result. [Answer] # Haskell, 55 ``` c a b=[[y|y<-b,(y-x)^2==minimum[(z-x)^2|z<-b]]!!0|x<-a] ``` At first, I thought to use `minimumBy` and `comparing`, but since those aren't in Prelude, it took a ton of characters to qualify them. Also stole the squaring idea from some other answers to shave off a character. [Answer] ## PowerShell - 44 ``` $a|%{$n=$_;($b|sort{[math]::abs($n-$_)})[0]} ``` **Example** With `$a` and `$b` set to: ``` $a = @(36.3, 9, 50, 12, 18.7, 30) $b = @(30, 10, 40.5, 20) ``` Output is ``` 40.5, 10, 40.5, 10, 20, 30 ``` [Answer] # Ruby, 40 ``` f=->a,b{a.map{|x|b.min_by{|y|(x-y)**2}}} ``` Same as the Python answer, but squaring is a little terser than any way I could think of to take absolute value. [Answer] # Pyth - 12 11 bytes ## Note: Pyth is much younger than this challenge, so this answer is not eligible to win. Simple method, uses `o` order function to get minimal distance and `m`aps it over list `a`. ``` mho.a-dNQvz m vz Map over evaled first input and implicitly print ho Q Minimal mapped over evaled second input .a- Absolute difference d Lambda param 1 b Lambda param 2 ``` [Try it online here](http://pyth.herokuapp.com/?code=mho.a-dNQvz&input=%5B0%2C+25%2C+10%2C+38%5D%0A%5B3%2C+22%2C+15%2C+49%2C+2%5D&debug=1). [Answer] # TI-BASIC, 24 ``` ∟A+seq(min(∟B+i²∟A(N)),N,1,dim(∟A ``` Doesn't come close to APL, but uses less powerful functions-- this uses no "sorted by" or "index of least" function. The disadvantage of TI-BASIC here is its lack of those functions and multidimensional arrays. Ungolfed: ``` seq( ,N,1,dim(∟A #Sequence depending on the Nth element of list A ∟A(N)+min( +0i) #Number with minimum absolute value, add to ∟A(N) ∟B-∟A(N) #Subtracts Nth element of ∟A from all elements of B ``` The min( function has two behaviors: when used with real numbers or lists, it gives the smallest value; however, when used with complex numbers or lists, it gives the value with the smallest absolute value. Adding `0i` or multiplying by `i^2` causes the interpreter to use the second behavior, so `min(1,-2)` returns `-2` whereas `min(1+0i,-2+0i)` returns `1`. [Answer] # Fortran 90: 88 ``` function f();integer::f(size(a));f(:)=[(b(minloc(abs(a(i)-b))),i=1,size(a))];endfunction ``` This requires it to be `contain`ed within a full program: ``` program main real :: a(5), b(3) integer :: i(size(a)) a = [10.1, 11.2, 12.3, 13.4, 9.5] b = [10, 12, 14] i = f() print*,i contains function f() integer :: f(size(a)) f(:)=[(b(minloc(abs(a(i)-b))),i=1,size(a))] end function end program main ``` The square braces declare an array while `(...,i=)` represents an implied `do` loop; I then return the value of `b` for which element `a(i)-b` is minimized. [Answer] # Matlab: 48 ``` f=@(a)B(abs(B-a)==min(abs(B-a)));C=arrayfun(f,A) ``` Assumes that `A` and `B` are 1D matrices in the workspace, Final result is `C` in the workspace. This would likely also work in Octave as well. Conditional indexing makes doing this fairly trivial. [Answer] # C 144 163 ``` #define f float f T, *C, m; f *q(f *A, f *B, int S, f s) { if(m) return abs(T - *A) - abs(T - *B); for ( C = malloc(S * 4); m = S--; C[S] = *B ) T = A[S], qsort(B, s, 4, q); return C; } ``` Okay... I think this little code needs explanation. At first i tried to do the job with two level of for loop finding the min difference and set the current value to min of B's value. That's very basic. The same thing can be reached with [qsort](http://www.cplusplus.com/reference/cstdlib/qsort/) and a comparator function. I make it sort B by the difference instead of B's elements. Too many functions for such a little algorithm. So the function q now serves two purposes. At first, it's the algorithm itself, secondly (when qsort calls it) a comparator. For communication between the two states, I had to declare globals. **m** stands for whether it's in comparator state or the *main* one. **example:** ``` float A[] = {1.5, 5.6, 8.9, -33.1}; float B[] = {-20.1, 2.2, 10.3}; float *C; C = q(A, B, sizeof(A)/sizeof(*A), sizeof(B)/sizeof(*B)); // C holds 2.2,2.2,10.3,-20.1 ``` [Answer] # GolfScript, 49 bytes *Note: this is a partial solution. I'm working on making it a complete solution* ``` {{\.@\.[.,,\]zip@{[\~@-abs]}+%{~\;}$0=0==}%\;}:f; ``` Yes. [GolfScript does support floating point.](https://codegolf.stackexchange.com/a/26553/9498) Try it out [here](http://golfscript.apphb.com/?c=e3tcLkBcLlsuLCxcXXppcEB7W1x%2bQC1hYnNdfSsle35cO30kMD0wPT19JVw7fTpmOw==). Example: ``` # B is [-20.1 2.2 10.3] [-201 10 -1?* 22 10 -1?* 103 10 -1?*] # A. No floating point numbers allowed here. # This is because 1.5{}+ (where the 1.5 is a # single floating point number, not 1.5, # which would be 1 1 5) results in the block # {1.5 }, which leads to 1 1 5 when executed [1 5 9 -30] ``` Output: ``` [2.2 2.2 10.3 -20.1] ``` [Answer] ## C# 262 Program finds min differences and saves closest value from Array B. I'll work on the golfing shortly. ``` List<float> F(List<float> a, List<float> b) { List<float> c = new List<float>(); float diff,min; int k; for(int i=0; i<a.Count;i++) { diff=0; min=1e6F; k = 0; for(int j=0; j<b.Count;j++) { diff = Math.Abs(a[i] - b[j]); if (diff < min) { min = diff; k = j; } } c.Add(b[k]); } return c; } ``` Full program with test code ``` using System; using System.Collections.Generic; public class JGolf { static List<float> NearestValues(List<float> a, List<float> b) { List<float> c = new List<float>(); float diff,min; int k; for(int i=0; i<a.Count;i++) { diff=0; min=1e6F; k = 0; for(int j=0; j<b.Count;j++) { diff = Math.Abs(a[i] - b[j]); if (diff < min) { min = diff; k = j; } } c.Add(b[k]); } return c; } public static void Main(string[] args) { List<float> A = RandF(8413); Console.WriteLine("A"); Print(A); List<float> B = RandF(9448); Console.WriteLine("B"); Print(B); List<float> d = JGolf.NearestValues(A, B); Console.WriteLine("d"); Print(d); Console.ReadLine(); } private static List<float> RandF(int seed) { Random r = new Random(seed); int n = r.Next(9) + 1; List<float> c = new List<float>(); while (n-- > 0) { c.Add((float)r.NextDouble() * 100); } return c; } private static void Print(List<float> d) { foreach(float f in d) { Console.Write(f.ToString()+", "); } } } ``` [Answer] # C#: 120 Linq is awesome: ``` float[] t(float[] A, float[] B){return A.Select(a => B.First(b => Math.Abs(b-a) == B.Min(c=>Math.Abs(c-a)))).ToArray();} ``` ]
[Question] [ # Setting the Scene: It is an average afternoon, as you unwind after a long day by engaging in your favorite pastime: answering the plethora of captivating questions on PPCG. It hasn't been a good day for you; those damned Pyth programmers keep getting best answer and it's killing your vibe. Suddenly, you notice a new question has been posted! You make up your mind; not this time CJammers. Furiously, you begin to type, birthing a stream of characters; a fetus of the glorious BrainFuck loop that your end product will be. You type and type. Faster! Faster still! You're so focused you don't even notice the lights on your screen start to flicker on and off. Suddenly, the monitor glows green, an alien like symbol branded upon the desktop. Using your impeccable skills you `cat ~/Desktop/aliensymbol` and get presented with a bunch of numbers, a message! Being the shrewd PPCG programmer that you are, you notice that it looks like ASCII. No matter for you, you `print(chr(i) for i in file)` and decipher the message. Your first thought: "I need to share this with the community!". ... Who would've thought it? That the first people to make contact with aliens would be the humble programmers of PPCG. Why us? Maybe it is because we are the epitome of human intelligence. Or maybe because BrainFuck is about as close as we have to an alien language. Nevertheless, the aliens - being the ultra-intelligent life forms that they are - want to test whether they should classify the human race as intelligent or not. As a test of our mental prowess, the aliens have asked us to send them a few computer programs to demonstrate that we are technologically cultured. The issue is, the only human language they understand is numerical ASCII! Help humankind show those creatures who the real intellectual alpha is. We need to send them a script that will convert our text based source codes into their numerical ASCII versions. Unfortunately, due to our underdeveloped technology (thanks Obama), we must send as small a translating program as possible. Good thing they chose to contact PPCG! # The Challenge: The premise of this challenge is simple: you are to write a program that will take any program's source code (or any general text file for that matter), and output a space separated version of it with an ASCII translation below each line. That is, given an input of a text file, you need to output each line of that file followed by a line containing the ASCII representation of each character in the line above it (with each number lining up with the character it represents). An example will greatly clarify this. Taking the source code of the infamous `hello world` as the input: ``` #include <stdio.h> int main() { printf("hello, world\n"); return 0; } ``` your program should output: ``` # i n c l u d e < s t d i o . h > 35 105 110 99 108 117 100 101 32 60 115 116 100 105 111 46 104 62 10 10 i n t m a i n ( ) { 105 110 116 32 109 97 105 110 40 41 32 123 10 p r i n t f ( " h e l l o , w o r l d \ n " ) ; 32 32 32 32 112 114 105 110 116 102 40 34 104 101 108 108 111 44 32 119 111 114 108 100 92 110 34 41 59 10 r e t u r n 0 ; 32 32 32 32 114 101 116 117 114 110 32 48 59 10 } 125 10 ``` # Implementation Details: You may choose to take the input in whatever form you wish (opening file, command line pipe, function parameter etc.) and you should output to stdout or return the output from a function. Things to note * Each character in the output is separated by a '\t' to allow for the space of 3 digits in the line below to line up (we are going to assume your tab is set to 4 spaces or more). * The newlines are displayed on the line that the return key was pressed (notice the 10's in the example) * The '\t' and '\n' printing requirements are lax. Your output must, in the general sense, look pleasing to the eye (need to show those aliens we have aesthetic sense as well), and if you can bend the previous two points while maintaining visual integrity, you will be forgiven. * You can choose to assume whether or not there is a newline at the end of the last line. # Scoring This is code-golf so shortest program wins. Note, even if your program isn't the shortest, but uses really neat tricks relative to the language you are using, many +1's to you! Good luck. The intergalactic intelligence ranking of humanity rests on your shoulders. Note: Please forgive the plot holes. [I'm not a writer](https://www.youtube.com/watch?v=MeB3eYk1Ze0&feature=youtu.be&t=1m55s) :D [Answer] # Pyth, ~~17~~ 13 bytes Another one of those Pyth programmers. *Sorry.* The new code requires each line to be wrapped in quotes and escaped (including newlines if you desire them to be printed), but puts an extra newline between the line and the ASCII. ``` jjLC9smCMBd.Q ``` [Try it online!](http://pyth.herokuapp.com/?code=jjLC9smCMBd.Q&input=%22hello%5Cn%22%0A%22world%5Cn%22%0A%22%5Cn%22%0A%22Testing%5Cn%22&debug=0) Explanation: ``` .Q Evaluate all input lines m For each of those lines: Bd Return the line and CM the line mapped to ASCII characters s Sum all these together to begin alternating between line and mapped line jLC9 Join all the characters and numbers in the lines and mapped lines on tabs j And join all of those on newlines ``` I'm keeping the old code and its' explanation below. ``` #Jw jKC9J jK+CMJT ``` [Try it online!](http://pyth.herokuapp.com/?code=%23Jw%0AjKC9J%0AjK%2BCMJT&input=%23include+%3Cstdio.h%3E%0A%0Aint+maint%28%29+%7B%0A++++printf%28%22hello%2C+world%5Cn%22%29%3B%0A++++return+0%3B%0A%7D&debug=0) or use an [easier-to-read test case](http://pyth.herokuapp.com/?code=%23Jw%0AjKC9J%0AjK%2BCMJT&input=%5C%2F%5C%2F%0ATesting+123%0A%0A%0ATest&debug=0). Explanation: ``` # Until we run into an error: Jw Read in the next line of input and call it J. (When there is no line of input, error is thrown that ends program.) j Join: J all characters in input line KC9 and insert tab characters (C9), which we can refer to later as K. (Setting it to a variable doesn't save or lose bytes.) Implicit print that join with trailing newline. j Join: CMJ the mapping of ASCII numbers to characters in the input, K inserting tab characters in between every number + T And with a trailing 10 for the newline at the end. ``` [Answer] # Python 2, 105 bytes This uses a slightly different approach than the OP's answer. Note that SO messes up my literal tabs with spaces. ``` def f(s): o=x='' for c in s: o+=c+" ";x+="%s "%ord(c) if"\n"==c:print o[:-1],x;o=x='' print o+"\n"+x ``` [**Try it online**](https://repl.it/DLjw) [Answer] # Vim, ~~86,~~ 77 keystrokes ``` :g/^/norm A<C-v><C-v>10<C-v><esc>Yp:s/./\=char2nr(submatch(0))."\t"/g<C-v><cr>k:s/./&\t/g<C-v><cr> :%s/<C-v><cr>0<cr> ``` This is way too long, but that's what you get when you use vim's `eval` feature (`\=`). [Answer] # Perl, ~~>33~~ 31 bytes Includes +3 for `-F` (cannot be combined with `-e` and the code has `'` too, so space and `-` are counted too). Run with the input on STDIN or give one or more filenames as argument ``` perl -M5.010 asciidump.pl <<< "Hoi" ``` `asciidump.pl` ``` #!/usr/bin/perl -F $"=v9;say"@F@{[unpack'W*']}" ``` Output is not aesthetic if the text contains a tab or there is no final newline [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Takes list of strings that include newline sequences (10 or 13 10 etc.) ``` ↑(⊢,[.5]⎕UCS)¨ ``` `↑` matrify the list of lists consisting of `(`...`)¨` for each line return...  `⊢` the text itself  `,[.5]` followed in a new dimension before the first dimension by  `⎕UCS` the **U**nicode **C**haracter **S**et code points [TryAPL online!](http://tryapl.org/?a=f%u2190%u2191%28%u22A2%2C%5B.5%5D%u2395UCS%29%A8%20%u22C4%20f%20%28%27include%20%3Cstdio.h%3E%27%2C%u2395ucs%2010%29%28%2C%u2395UCS%2010%29%28%27int%20main%28%29%20%7B%27%2C%u2395ucs%2010%29%28%27%20%20%20%20printf%28%22hello%2C%20world%5Cn%22%29%3B%27%2C%u2395ucs%2010%29%28%27%20%20%20%20return%200%3B%27%2C%u2395ucs%2010%29%28%27%7D%27%2C%u2395ucs%2010%29&run) [Answer] # Pyth, 21 bytes ``` j.imjC9d.zmjC9+CMdT.z ``` Here's an entry from one of *"those damned Pyth programmers"* ;) A program that takes input of an unquoted multiline string on STDIN and prints the result. This assumes that all input has a trailing newline. If you want it to deal with no trailing newline, add `<` at the beginning of the program and `)_3` at the end. [Try it online](https://pyth.herokuapp.com/?code=j.imjC9d.zmjC9%2BCMdT.z&input=%23include+%3Cstdio.h%3E%0A%0Aint+maint%28%29+%7B%0A++++printf%28%22hello%2C+world%5Cn%22%29%3B%0A++++return+0%3B%0A%7D&debug=0) The output for the test case is difficult to see in the online interpreter, so I've included it here: ``` # i n c l u d e < s t d i o . h > 35 105 110 99 108 117 100 101 32 60 115 116 100 105 111 46 104 62 10 10 i n t m a i n t ( ) { 105 110 116 32 109 97 105 110 116 40 41 32 123 10 p r i n t f ( " h e l l o , w o r l d \ n " ) ; 32 32 32 32 112 114 105 110 116 102 40 34 104 101 108 108 111 44 32 119 111 114 108 100 92 110 34 41 59 10 r e t u r n 0 ; 32 32 32 32 114 101 116 117 114 110 32 48 59 10 } 125 10 ``` **How it works** ``` j.imjC9d.zmjC9+CMdT.z Program. Input: .z (All of STDIN split on newlines) C9 Yield tab character by taking chr(9) j Join on tab m d.z Map that over .z CM Map ord() + T Append 10 jC9 Join on tab m d .z Map that over .z .i Interleave the results of the two mappings j Join on newlines Implicitly print ``` [Answer] ## C, ~~136~~ ~~117~~ 114 Bytes ``` #define p(s)while(l[i])printf(s,l[i++]);i=0;puts("") char l[99];i;f(f){while(fgets(l,99,f)){p("%c\t");p("%d\t");}} ``` ~~`char l[99];i;f(f){while(fgets(l,256,f)){i=0;while(l[i])printf("%c\t",l[i++]);i=0;puts("");while(l[i])printf("%d\t",l[i++]);puts("");}}`~~ Can be tested like this ``` infile; main(c,v)char**v; { infile=fopen(v[1],"r"); f(infile); } ``` [Answer] ## PowerShell v2+, 85 bytes ``` gc $args|%{$a=$b='';$_-split'(.)'-ne''|%{$a+="$_`t";$b+="$(+[char]$_)`t"};$a;$b+"10"} ``` Input is via a path to a file. We then `Get-Content` (alias `gc`) on that file, which automatically splits on newlines. We loop over each of those `|%{...}`. Start by setting `$a` and `$b` to an empty string -- these are our ASCII characters and code points respectively. We then `-split` the input line on every character, keeping it `(.)`, and removing the empty values `-ne''` (it's due to how .NET regex parses), then send those into another loop. Each inner loop, we string concatenate the current character with a tab ``t` and add that onto `$a`. Similarly for `$b`, excepting we're explicitly casting as a `char` and then as an int `+`. Outside the inner loop, we place the resulting `$a` and `$b` (with a linefeed designator, since that'll never come up in our looping) on the pipeline. Those are gathered up with an implicit `Write-Output` at program completion. ### Example (with the understanding that I've got a trailing linefeed and Markdown mangles the tab character) ``` PS C:\Tools\Scripts\golfing> .\aliens-only-understand-ascii.ps1 '.\aliens-only-understand-ascii.txt' # i n c l u d e < s t d i o . h > 35 105 110 99 108 117 100 101 32 60 115 116 100 105 111 46 104 62 10 10 i n t m a i n t ( ) { 105 110 116 32 109 97 105 110 116 40 41 32 123 10 p r i n t f ( " h e l l o w , w o r l d \ n " ) ; 32 32 32 32 112 114 105 110 116 102 40 34 104 101 108 108 111 119 44 32 119 111 114 108 100 92 110 34 41 59 10 r e t u r n 0 ; 32 32 32 32 114 101 116 117 114 110 32 48 59 10 } 125 10 ``` [Answer] # ><> (Fish), 48 Bytes ``` >i:0(?v::oa=?v9o 2';'oa<.20r <~p3 o9nv?=0l voa< ``` A task the language shines at! I'm sure I could probably have golfed out a little bit more, but it's been a long week. Might take a look at it later though. [Try it online!](http://fish.tryitonline.net/#code=Pmk6MCg_djo6b2E9P3Y5bwoyJzsnb2E8LjIwciAgPH5wMwpvOW52Pz0wbAp2b2E8&input=I2luY2x1ZGUgPHN0ZGlvLmg-CgppbnQgbWFpbnQoKSB7CiAgICBwcmludGYoImhlbGxvLCB3b3JsZFxuIik7CiAgICByZXR1cm4gMDsKfQ) [Alternate](https://fishlanguage.com/playground/Ft8ZT6j34fPzpYA4S) try it online that looks nicer in my opinion, but the text wrapping messes up a bit for input with long lines like the test case. [Answer] # PHP, ~~131~~ 115 bytes Just a FGITW, maybe I can improve upon it more. Turns out, I can! First version at 131 bytes: ``` <?$s=file($argv[1]);foreach($s as$l){$a=str_split(trim($l));echo join(' ',$a).' ';$i=0;while($c=ord($l{$i++}))echo$c.' ';echo' ';}; ``` The filename is supplied as the first argument after the script name: `php aliens.php helloworld.c` Second version at 115 bytes: ``` function($s){foreach($s as$l){$a=str_split($l);echo join(' ',$a);$i=0;while($c=ord($a[$i++]))echo$c.' ';echo' ';}}; ``` The first version accounts for missing newlines at the end of the line, but after the additional clarification, we can leave that code out and put everything in a function to save 16 bytes. The whitespace characters in `join(' ',$a)` as well as in `echo$c.' '` are tab characters = `\t`. The newlines in the code are on purpose. [Answer] # Python 3, ~~89~~ 77 bytes more golfed version based on the same idea: ``` def f(s): for a in s:print(*map('{:>4}'.format,[*a,*a.encode()]),end='\n\n') ``` If there are '\t's in the input, then change the `4` to a `9`. ### Prior version: ``` def f(s): for l in s: print(*l,sep='\t',end='');print(*l.encode(),sep='\t',end='\n\n') ``` Takes a list of strings, each ending with a '\n'. [Answer] # Powershell, 56 Bytes ``` gc $args|%{($a=[char[]]$_)-join" ";[int[]]$a+10-join" "} ``` Script accepts a filepath as input. Get-Content automatically splits input into an array of strings split on newlines in the source. From there I enter a foreach, cast to an array of characters and set that to $a, join that with tabs and print it. Next but still within the foreach I cast the character array to an integer array, append a linefeed and join again with a tab. Call looks like this: ``` PS C:\PretendFolder> .\aoua.ps1 ".\aoua.txt" ``` and here is an output sample ``` # i n c l u d e < s t d i o . h > 35 105 110 99 108 117 100 101 32 60 115 116 100 105 111 46 104 62 10 10 i n t m a i n ( ) { 105 110 116 32 109 97 105 110 40 41 32 123 10 p r i n t f ( " h e l l o , w o r l d \ n " ) ; 32 32 32 32 112 114 105 110 116 102 40 34 104 101 108 108 111 44 32 119 111 114 108 100 92 110 34 41 59 10 r e t u r n 0 ; 32 32 32 32 114 101 116 117 114 110 32 48 59 10 } 125 10 ``` [Answer] ## JavaScript (ES6), 94 bytes ``` s=>s.replace(/(.*)\n?/g,(s,n)=>n&&[...s].join`␉`+` ${[...n].map(c=>c.charCodeAt()).join`␉`} `) ``` Where ␉ represents the literal tab character. Works as long as the input doesn't contain tab characters. 81-byte version that also requires the input to have a trailing newline: ``` s=>s.replace(/.*\n/g,s=>[...s].join`␉`+[...s].map(c=>c.charCodeAt()).join`␉`+` `) ``` [Answer] # C#, ~~64~~ 63 bytes ``` s=>{foreach(int c in s+(s=""))s+=c+(10==c?"\n":" ");return s;}; ``` *-1 byte by using actual tab character instead of `\t`. Note: renders as 4 spaces above and 2 spaces in the ungolfed version below.* Ungolfed: ``` /*Func<string, string> Lambda =*/ s => { // Enumerate the ascii (int) values of the chars in s, // but at the same time set input s to "" to use at the output var. // +(s="") is 2 bytes less than var o=""; foreach (int c in s + (s="")) // Append the string representation of the ascii value, // Append new line if c was new line, otherwise append tab. s += c + (10==c ? "\n" : " "); return s; }; ``` Results: (Note: Visual Studio has used `\r\n` for the new lines when I pasted the input in, hence the `13 10` line endings in output) ``` Input: #include <stdio.h> int maint() { printf("hello, world\n"); return 0; } Output: 35 105 110 99 108 117 100 101 32 60 115 116 100 105 111 46 104 62 13 10 13 10 105 110 116 32 109 97 105 110 116 40 41 32 123 13 10 32 32 32 32 112 114 105 110 116 102 40 34 104 101 108 108 111 44 32 119 111 114 108 100 92 110 34 41 59 13 10 32 32 32 32 114 101 116 117 114 110 32 48 59 13 10 125 ``` [Answer] # CJam, 27 bytes ``` qN/{_1/9c*N+\{is9c}%+}%AN+* ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4ve18xLzljKk4rXHtpczljfSUrfSVBTisq&input=aGVsbG8Kd29ybGQ) **Explanation** ``` q e# Take the whole input N/ e# Split on newlines { e# Map this block to every line: _ e# Duplicate 1/ e# Split into characters 9c* e# Join with tabs (ASCII code 9) N+ e# Append a newline \ e# Swap top elements {is9c}% e# Map each character to its ASCII code plus a tab character + e# Concatenate the two lines }% e# (end of block) AN+* e# Join with "10" plus a newline ``` [Answer] # PowerShell, ~~61~~ 59 bytes ``` gc m|%{$b="$_ "[0..$_.Length] $b-join' ' [int[]]$b-join' '} ``` Things to note: * Reads the input from a file named `m` in the current directory. * All line breaks, (including the one embedded in the string after the first `$_`) are literal linefeeds only (0xA), so one byte each. * The contents of the strings directly after the `-join` operators are each a single tab character (regardless of how it's rendered here). ### Ungolfed ``` Get-Content m | ForEach-Object -Process { # Read the file line by line $b = "$_`n"[0..$_.Length] # Line by line processing strips line endings, so add a newline # Index operator on a [string] returns a [char], or given a [range], a [char[]] # Using $_.Length automatically accounts for the extra linebreak (0 based index) $b -join "`t" # PowerShell displays [char] as the printable character by default, so join the array with a tab [int[]]$b -join "`t" # We need to convert the [char]s to an [int]s so we can display it as a number # So cast the [char[]] as [int[]], then join with tab again } ``` [Answer] # Java, 202 bytes ``` s->{for(String g : s.split("\n")){g.chars().forEach(c->System.out.print((char)c+" "));System.out.println();g.chars().forEach(c->System.out.print(c+(c<10?" ":c<100?" ":" ")));System.out.println();}}; ``` I can't even be bothered making this shorter.. [Answer] # Haskell - 71 bytes ``` f q=unlines[(x>>=(++"\t").show.ord)++'\n':intersperse '\t'x|x<-lines q] ``` [Answer] # **Python 3, ~~92 97~~ 107 bytes** ~~for i in list(open(input()).read().split("\n")): for j in i: print(i+"\n"+ord(j))~~ ``` p=print for i in list(open(input()).read().split("\n")) s=t='' for j in i: r=str(ord(j)) s+=j+' '*len(r) t+=r+' ' p(s) p(t) ``` This is untested, but should work. Thanks @gowrath for pointing out that the code isn't doing as the question specifies. ]
[Question] [ You must write a program to evaluate a string that would be entered into a calculator. The program must accept input and output the correct answer. For languages that do not have standard input/output functions, you may assume the functions `readLine` and `print`. **Requirements** * Does not use any kind of "eval" functions * Can handle floating point and negative numbers * Supports at least the +, -, \*, and / operators * Can handle input containing one **or more** spaces between the operators and numbers * Evaluates the expression from left to right The program that is the shortest wins. In the event of a tie, the program that was submitted first wins. **You can assume that the input is valid and follows the correct format** ## Test Cases Input ``` -4 + 5 ``` Output ``` 1 ``` --- Input ``` -7.5 / 2.5 ``` Output ``` -3 ``` --- Input ``` -2 + 6 / 2 * 8 - 1 / 2.5 - 18 ``` Output ``` -12 ``` [Answer] ## Befunge - 37 x 5 = 185 38 x 3 = 114 characters This is limited to integer numbers as Befunge has no floating point support. ``` &v /& _ #`&# "-"$# -#< v >~:0`!#v_:" "`! #v_:","`#^_"*"`#v_&*> ^ ># $ .# @#< >&+ ``` ### Explanation The biggest distinguishing feature of [Befunge](http://en.wikipedia.org/wiki/Befunge) is that instead of being a linear set of instructions like most languages; it is a 2d grid of single character instructions, where control can flow in any direction. The first `&` simply inputs the first number. The `v` and `>` then redirect control to the main path on the second row. ``` ~:0`!#v_ ``` This inputs a character (`~`), duplicates it (`:`), pushes zero onto the stack (`0`), pops the top two elements and determines if the second is greater than the first (``` *I'm surprised you can't use ``` to get code backticks.*), inverts the truthiness of the top element (`!`), then goes right if it is zero, down otherwise (`#v_`). Basically it's checking whether the input is `-1` representing no more input. ``` ># $ .# @ ``` If the input was `-1` then the duplicated input value is discarded (`$`), the top of the stack is output as an integer (`.`) and the program is halted (`@`). ``` :" "`! #v_ ``` Otherwise a similar process is repeated to determine if the input is less than or equal to a space. If it is a space then control goes down, otherwise control heads right. ``` ^ ># $ .# @#< ``` If it is a space then it's redirected left (`<`); the program halt (`@`), output (`.`) and right redirection (`>`) are all skipped using `#`; but the discard is executed to remove the space from the stack. Finally it's redirected up to begin the next execution (`^`). ``` :","`#^_ ``` If it wasn't a space the same process is used to split on if it is in `[+, *]` or in `[-, \]` going right and up respectively. ``` >~ "*"`#v_&*> ^ >&+ ``` For `[+, *]` it is again split to determine whether it is a `+` or a `*`. If `+` it is directed down then the next number is input (`&`) and they are added (`+`), the control then wraps around and is redirected up to the main path for the next character. If `*` then it inputs (`&`) and multiplies (`*`) then directly wraps around. ``` /& _ #`&# "-"$# -#< ``` For `[-, \]` it starts on the right heading left. The `#`'s skip the character after them so the initial path is `"-"`_` which simply determines if it is `-` or `/`. If it is `/` then it continues left to input (`&`) and divide (`/`). If it is `-` then it heads right, again skipping characters so that it executes `&"-"$-` resulting in the number being input (`&`) the `-` character being pushed onto the stack then discarded (`"-"$`) and then the subtraction being calculated (`-`). The control is then redirected back to the main path. [Answer] # Ruby - ~~74~~ ~~69~~ ~~67~~ 65 characters ``` a=0 ("+ "+$<.read).split.each_slice 2{|b,c|a=a.send b,c.to_f} p a ``` [Answer] # Python 3, 105 bytes Manages the four basic operations, but it only costs 5 characters each to add `^` or `%`. ``` f=float x,*l=input().split() while l:o,y,*l=l;x,y=f(x),f(y);x=[x+y,x-y,x*y,x/y]['+-*/'.find(o)] print(x) ``` Precedence of operations is left to right. [Answer] ## Python (156) ``` from operator import* while 1: l=raw_input().split();f=float while len(l)>2:l[:3]=({'*':mul,'/':div,'+':add,'-':sub}[l[1]](f(l[0]),f(l[2])),) print l[0] ``` [Answer] # C - ~~168~~ 126 characters ``` main(c){float a,b;scanf("%f",&a);while(scanf("%s%f",&c,&b)!=-1)c=='+'?a+=b:c=='-'?(a-=b):c=='*'?(a*=b):(a/=b);printf("%f",a);} ``` [Answer] # Tcl 8.6, ~~57~~ 48 chars. * Input from arguments: ``` lm o\ b [las $argv a] {set a [exp $a$o$b]};pu $a ``` * From Stdin (~~64~~ **53**) ``` lm o\ b [las [ge stdin] a] {set a [exp $a$o$b]};pu $a ``` **You have to use the interactive shell for both solutions.** I treat the input as list (Tcl uses spaces as delimiter) take the first element and assign it to `a`, then I walk over the rest, taking 2 elements each time, the operator and a second number, apply the operator on `$a` and `$b` and assign the result to `a`. At the end the result is in `a`. [Answer] ### C++0x 205 203 198 194 chars ``` #include<iostream> #define P [](F l,F r){return l int main(){typedef float F;F r,v,(*a[])(F,F)={P*r;},P+r;},0,P-r;},0,P/r;}};std::cin>>r;for(char o;std::cin>>o>>v;)r=a[o-42](r,v);std::cout<<r;} ``` Nicely formatted: ``` #include<iostream> int main() { float r,v; float (*a[])(float,float) ={ [](float l,float r){return l*r;}, [](float l,float r){return l+r;}, 0, [](float l,float r){return l-r;}, 0, [](float l,float r){return l/r;} }; std::cin>>r; for(char o;std::cin>>o>>v;) r=a[o-42](r,v); std::cout<<r; } ``` [Answer] # Haskell: 124 114 characters ``` j[o]=o j(u:m:b:o)=j$show((case m of{"+"->(+);"-"->(-);"*"->(*);"/"->(/)})(read u)(read b)):o main=interact$j.words ``` A rather straight-forward answer, using pattern matching and a simple case statement for the heavy lifting. Usage: ``` > ./calc <<< "123 - 12 + -12 / 12.124 * 9.99 - 1" 80.57456285054437 ``` [Answer] # C: 111 108 characters ``` main(c){float a,b;for(scanf("%f ",&a);~scanf("%c%f ",&c,&b);a=c^43?c%5?c%2?a/b:a*b:a-b:a+b);printf("%f",a);} ``` It fulfills all the requirements, usage: ``` > ./calc <<< "-43 - 56 + 14.123 / -13.22" 6.420348 ``` [Answer] # Perl (97) ``` $b=shift;eval"\$b$r=$s"while($r=shift,$s=shift);print$b ``` read from arguments ``` $b=shift;$b=($r eq'+'?$b+$s:$r eq'-'?$b-$s:$r eq'*'?$b*$s:$b/$s)while($r=shift,$s=shift);print$b; ``` read from input ``` @_=split/ /,<>;$b=shift@_;$b=($r eq'+'?$b+$s:$r eq'-'?$b-$s:$r eq'*'?$b*$s:$b/$s)while($r=shift@_,$s=shift@_);print$b ``` [Answer] **PostScript (145)** Another PostScript entry (thanks to luser droog for digging the golfs interesting for PostScript!): ``` [/+{add}/-{sub}/*{mul}/{div}>>begin(%stdin)(r)file 999 string readline pop{token not{exit}if count 4 eq{3 1 roll 4 1 roll cvx exec}if exch}loop = ``` Un-golfed: ``` [/+{add}/-{sub}/*{mul}/ {div}>>begin % Read the input (%stdin)(r)file 999 string readline pop { % .. string token not{exit}if % .. string token % If we have 4 objects on the stack, we have two operands, one operator % and the input string. This means, we can calculate now. count 4 eq{ % a op string b % perform operation a op b = c (where op can be +,-,*,/) 3 1 roll % a b op string 4 1 roll % string a b op cvx exec % string c }if % string token (or c) exch % token string }loop = ``` [Answer] # Python - 308 ``` import sys;i=sys.argv[1].split();o=[];s=[];a=o.append;b=s.pop;c=s.append for t in i: if t in"+-*/": if s!=[]:a(b()) c(t) else:a(t) if s!=[]:a(b()) for t in o: if t=="+":c(b()+b()) elif t=="-":m=b();c(b()-m) elif t=="*":c(b()*b()) elif t=="/":m=b();c(b()/m) else:c(float(t)) print(b()) ``` Readable version: ``` # Infix expression calc import sys # Shunting-yard algorithm input = sys.argv[1].split() output = [] stack = [] for tkn in input: if tkn in "+-*/": while stack != []: output.append(stack.pop()) stack.append(tkn) else: output.append(tkn) while stack != []: output.append(stack.pop()) # Eval postfix notation for tkn in output: if tkn == "+": stack.append(stack.pop() + stack.pop()) elif tkn == "-": tmp = stack.pop() stack.append(stack.pop() - tmp) elif tkn == "*": stack.append(stack.pop() * stack.pop()) elif tkn == "/": tmp = stack.pop() stack.append(stack.pop()/tmp) else: stack.append(float(tkn)) print(stack.pop()) ``` Takes expression as command-line argument, output on standard output. [Answer] **Postscript (340)** ``` /D<</+{add}/-{sub}/*{mul}/ {div}>>def/eval{/P null def{token not{exit}if exch/rem exch def dup D exch known{/P load null ne{D/P load get exch/P exch def exec}{/P exch def}ifelse}if rem}loop/P load null ne{D/P load get exec}if}def {(> )print flush{(%lineedit)(r)file dup bytesavailable string readline pop eval == flush}stopped{quit}if}loop ``` And a little more readable: ``` %! /oper<</+{add}/-{sub}/*{mul}/ {div}>>def /eval{ /op null def { token not {exit} if exch /rem exch def dup oper exch known { /op load null ne { oper /op load get exch /op exch def exec }{ /op exch def } ifelse } if rem } loop /op load null ne { oper /op load get exec } if } def { (> )print flush { (%lineedit)(r)file dup bytesavailable string readline pop eval == flush } stopped { quit } if } loop ``` [Answer] ## JavaScript (208 characters compacted) For clarity, this is the code *before* I compacted it down ([JS-Fiddle of it](http://jsfiddle.net/IQAndreas/Td83k/1/)): ``` function math(match, leftDigit, operator, rightDigit, offset, string) { var L = parseFloat(leftDigit) var R = parseFloat(rightDigit) switch (operator) { case '*': return L*R; case '/': return L/R; case '+': return L+R; case '-': return L-R; } }; str = prompt("Enter some math:", "-2 + 6 / 2 * 8 - 1 / 2.5 - 18").replace(/ /g, ""); var mathRegex = /(\-?\d+\.?\d*)([\*\/\+\-])(\-?\d+\.?\d*)/; while(mathRegex.test(str)) { str = str.replace(mathRegex, math); } alert(str) ``` Here it is compacted down to 208 characters ([JS-Fiddle of it](http://jsfiddle.net/IQAndreas/Td83k/3/)): ``` function m(x,l,o,r){ L=(f=parseFloat)(l); R=f(r); return o=='*'?L*R:o=='/'?L/R:o=='+'?L+R:L-R; }; M=/(\-?\d+\.?\d*)([\*\/\+\-])(\-?\d+\.?\d*)/; for(s=prompt().replace(/ /g, "");M.test(s);s=s.replace(M,m)){}; alert(s) ``` Since I'm ending lines with semi-colons, all *removable* whitespace was ignored for character counting, but left in for clarity. [Answer] # Haskell - 124 ``` let p=let f[x]=Just$read x;f(x:o:r)=lookup o[("-",(-)),("+",(+)),("*",(*)),("/",(/))]<*>f r<*>Just(read x)in f.reverse.words ``` The result will be wrapped in `Maybe` monad ``` λ: p"-2 + 6 / 2 * 8 - 1 / 2.5 - 18" Just (-12.0) ``` Also it requires importing `<*>` from `Control.Applicative`, but imports can be done outside the code, so I hope it's allowed. [Answer] ## C# ~~(234)~~ ~~(231)~~ ~~(229)~~ ~~(223)~~ (214) ``` class A{void Main(string[]s){var n=1;var o="";var r=0F;foreach(var t in s){if(n>0){var v=float.Parse(t);if(o=="")r=v;if(o=="+")r+=v;if(o=="-")r-=v;if(o=="*")r*=v;if(o=="/")r/=v;}o=t;n=-n;}System.Console.Write(r);}} ``` --- ``` class A{ void Main(string[] s) { var n = 1; var o = ""; var r = 0F; foreach (var t in s) { if (n > 0) { var v = float.Parse(t); if (o == "") r = v; if (o == "+") r += v; if (o == "-") r -= v; if (o == "*") r *= v; if (o == "/") r /= v; } o = t; n = -n; } System.Console.Write(r); } } ``` [Answer] # JavaScript (87 characters) ``` alert(prompt().split(/ +/).reduce((a,b,i)=>i%2?(o=b,a):o+1-0?a-b*-(o+1):o<'/'?a*b:a/b)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` #ćs2ôívy`…+-*sk©i-ë®>i+ë®<i*ë/ ``` [Try it online](https://tio.run/##yy9OTMpM/f9f@Uh7sdHhLYfXllUmPGpYpq2rVZx9aGWm7uHVh9bZZWqDKJtMrcOr9f//1zVS0FYwU9BXMFLQUrBQ0FUwBLH1TEEsCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/5SPtxUaHtxxeW1aZ8KhhmbauVnH2oZWZuodXH1pnl6kNomwytQ6v1v9fCwQ6/6OVdE0UtBVMlXQUlHTN9UwV9BWM9CA8I6C4GYivoKVgoaCrYAiRA7EslGIB). **Explanation:** ``` # # Split the (implicit) input-string by spaces ć # Pop the list, and push the remainder and first item separated to the stack s # Swap so the remainder is at the top of the stack 2ô # Split it into parts of size 2 (operator + number pairs) í # Reverse each pair so the numbers are before the operators v # Loop over each of the pairs: y` # Push the number and operator separated to the stack …+-* # Push a string "+-*" sk # Get the index of the operator in this string © # Store this index in the register (without popping) i # If the index is 1 (the "-"): - # Subtract the numbers from each other ë®>i # Else-if the index is 0 (the "+"): + # Add the numbers together ë®<i # Else-if the index is 2 (the "*"): * # Multiply the numbers with each other ë # Else (the index is -1, so "/"): / # Divide the numbers from each other # (and output the result implicitly) ``` --- If an `eval` builtin was allowed, this could be an alternative approach (**16 bytes**): ``` #ćs2ôJv…(ÿ)y«}.E ``` [Try it online](https://tio.run/##MzBNTDJM/f9f@Uh7sdHhLV5ljxqWaRzer1l5aHWtnuv//7pGCtoKZgr6CkYKWgoWCroKhiC2nimIZQEA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeV/5SPtxUaHt3iVPWpYpnF4v2blodW1eq7/df5HK@maKGgrmCrpKCjpmuuZKugrGOlBeEZAcTMQX0FLwUJBV8EQIgdiWSjFAgA). **Explanation:** ``` #ćs2ô # Same as above J # Join each operator+number pair together to a single string v # Loop over the operator+number strings: …(ÿ) # Surround the top of the stack in parenthesis y« # And append the operator+number string }.E # After the loop: evaluate the string using a Python-eval ``` This would change `"-2 + 6 / 2 * 8 - 1 / 2.5 - 18"` to `"((((((-2)+6)/2)*8)-1)/2.5)-18"` before using the `eval` builtin (using `.E` directly would give operator precedence of `*/` over `+-`, hence the conversion with parenthesis first). [Answer] # Java 10, ~~151~~ 145 (as lambda function) ``` s->{float r=0,t,o=0,q;for(var x:s.split(" ")){if(x.length()>1|(q=x.charAt(0)-43)>4){t=new Float(x);r=o<0?r*t:o<1?r+t:o<3?r-t:r/t;}o=q;}return r;} ``` -6 bytes thanks to *@ceilingcat*. Lambda function taking a String input and outputting a float. [Try it online.](https://tio.run/##jU@7csIwEOz9FTdUEmCBeSQMwjBp0oWGkkmhGBtEjASnw3HG8bc78uA6k@aeuzu7Z1Wo8Hz4bJJcOQdvSpsqANCGUsxUksK2XQGy3CqChO0ItTmC49Kf68AXR4p0AlswEEPjwnX1wGI8HtLQ@nqTmUVWKIRy6YS75ppYD3qcVzpjpchTc6QT4@voh93iUiQnhS/ExjycTfl6xiuKTfoFr60qK7nE2K7GG@zT0q6iDQ7aPt1gSEsckaxtfJM1pnRHAyjrRrYmr/eP3JvsvBZWH@Dio3Zx9u@g@CPn7ttRehH2TuLqX5QbZkTCeuEMBjD3nuXfsGcxhxFMxD@gE6/41IKhDwsIIXoQ22nRseugbn4B) # Java 10, ~~241~~ 235 bytes (as full program with asked I/O) ``` interface M{static void main(String[]a){float r=0,t;int o=43,q;for(var x:new java.util.Scanner(System.in).nextLine().split(" ")){if(x.length()>1|(q=x.charAt(0))>47){t=new Float(x);r=o<43?r*t:o<44?r+t:o<46?r-t:r/t;}o=q;}System.out.print(r);}} ``` Full program taking a String-line through STDIN and outputting to STDOUT. [Try it online.](https://tio.run/##LY/BboJAFEV/5cXVPHVGUNsYEEk3XbUrlk0XExx0KM7I40lpKN9OIenm3rs6J7fUrZbl@WscrWNDhc4NvPcNa7Y5tN6e4aatExmTdZePT419UXnNQEmw5rWfso4LT6LVBF3kzDeUE1E92FYqy7VzhkT207C5KetQOdPxm3VGoGrulWWxgAVibwvRqcq4C18FnsJfUSedyq@aXlgEKPc7PO2x52Tmv85@0WFMiT8GKS058scwpdXcu5QkR7ThePBJHQ//av9gdZ8esCCMh2Ec5RZW8Awb2MISDiAhnLd6mtfhDw) **Explanation:** ``` interface M{ // Class static void main(String[]a){// Mandatory main-method float r=0, // Result float, starting at 0 t, // Temp float o=0, // Operator flag, starting at '+' q; // Temp operator flag for(var x:new java.util.Scanner(System.in) // Create an STDIN-reader .nextLine() // Get the user input .split(" ")){ // Split it on spaces, and loop over it: if(x.length()>1 // If the current String length is larger than 1 // (work-around for negative values) |(q=x.charAt(0)-43)>4){ // Or the first character is an operator // (and set `q` to this first character at the same time) t=new Float(x); // Convert the String to a float, and set it to `t` r= // Change `r` to: o<0? // If `o` is a '*': r*t // Multiply `r` by `t` :o<1? // Else-if `o` is a '+': r+t // Add `r` and `t` together :o<3? // Else-if `o` is a '-': r-t // Subtract `t` from `r` : // Else (`o` is a '/'): r/t;} // Divide `r` by `t` o=q;} // And at the end of every iteration: set `o` to `q` System.out.print(r);}} // Print the result `r` to STDOUT ``` [Answer] # ZX81 BASIC (might be cheating, so just for fun/non-competing), ~14 Tokenised BASIC bytes, 6 key entries without *new line* (ZX81 speak for enter) ``` 1 INPUT A 2 PRINT A ``` Whilst this does not explicitly use any kind of "eval" functions, ZX81 BASIC evaluates any mathematical expressions in its ROM *if you are inputing to a floating point variable* of which `A` would be (like most 8-bit BASIC variants, string variables will have a `$` at the end of the variable name). So when you enter the program and `RUN` it, you can type like `12+10*6` and this will output `72` (note the ZX81 keyboard has some odd key placements for +, /, - and \* etc). The byte count is as follows: as I recall, each line number is stored as 4 bytes, and `INPUT` is a single token, as is `PRINT` (you cannot free type in ZX81 BASIC to enter BASIC commands, so to enter the `INPUT` command, press I, and to enter the `PRINT` command, press P). I don't recall how many bytes are stored at the end of each BASIC line entered, but let's assume that it is a single byte, hence my estimate of 14 tokenised BASIC bytes. I'll find out the exact number at a later time (if this is not cheating). You may try this online with the [JtyOne Online ZX81 Emulator](http://www.zx81stuff.org.uk/zx81/jtyone.html) which helpfully has an interactive keyboard below the running emulator. ]
[Question] [ Euclidean distance between two lattice points \$(x\_1, y\_1)\$ and \$(x\_2, y\_2)\$ on a plane is: \$\sqrt{(x\_1 - x\_2)^2 + (y\_1 - y\_2)^2}\$. Imagine now a lattice `N x N` replicated infinitely many times next to itself. The two points \$(x\_1, y\_1)\$ and \$(x\_2, y\_2)\$ also get replicated. Euclidean distance on a torus is then the minimal distance between all these points. Input: `x1, y1, x2, y2` and `N`. Arrange these in any convenient order or way (e.g. represent \$(3,4)\$, \$(5,6)\$ as 4 arguments `3, 4, 5, 6`, two complex numbers \$3+4j\$, \$5+6j\$, a list `[[3,4],[5,6]]`, a list `[3,4,5,6]` or anything that's not too bizarre). Coordinates must be integers in the range `0..N-1` or `1..N`. The size of the torus (`N`) must be an integer (you can assume `1 < N < 100`). Output: a real number, with precision better than \$1\%\$. Test cases: | x1 | y1 | x2 | y2 | N | Result | | --- | --- | --- | --- | --- | --- | | 1 | 0 | 1 | 1 | 2 | 1.00 | | 2 | 3 | 2 | 3 | 4 | 0.00 | | 0 | 0 | 2 | 2 | 4 | 2.83 | | 0 | 9 | 1 | 1 | 10 | 2.24 | | 9 | 0 | 9 | 8 | 10 | 2.00 | | 12 | 34 | 56 | 78 | 99 | 62.23 | | 0 | 0 | 98 | 98 | 99 | 1.41 | [Answer] # [R](https://www.r-project.org), 40 bytes ``` \(a,b,N)sum(pmin((d=a-b)%%N,-d%%N)^2)^.5 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bdBLCsIwEIBh3HqKghQSmJYkfZgscoWcQCqpQShYK32cxk1duPU-ehrbhkqL2SSz-Pgz5P6o-1db1VVh9OVoiqaVz649B_yNDkhDDgo3XYluZXFFyEgd5Nj3FQRmOHHGcBYm1n82ySqDtDwhCgRDPg0Ug5IMezuPbv8hg8jCaVAyHiFxQDIXGbAfZCGPnFasXqfEYhY7sJjDAvgCOyQddoytTVLYT1qIUadD273I3OYgFp6GMbW_1_f2_gI) Input the two points as vectors `a` and `b`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~18~~ 16 bytes -2 bytes thanks to @ngn. Function taking input as `f[N;(x1,y1;x2,y2)]`. ``` {%+/&/x*x!:y-|y} ``` [Try it online!](https://ngn.codeberg.page/k#eJxFjcEOgjAQRM/0K9ZGBTSWtiDS9h84eAUSLsLFeBGTNui/u60Qk+1k83ZmOuh5d8z2mT3YjXant/sQMuq5scI4Yaw0TpraXG/P133qCAxNbSBJwjU1SbinaYehSVMBEYdIhJGojHMCALjmAaAWaFkwD24ZBrFkVb5gtZYIb2Cy8FwFO2q18l+N8MWYP5cQXfCm0FJiKP//oarl+WJWCEp6rrcji1kc03aiLeoDly82wDIm) `y-|y` Subtract the reversed list of points from the list of points. This results in component-wise distances in both directions. `x!:` Take all values mod *N*. Updates x. `x*` Square each value. `&/` take the element-wise minimum between positive and negative difference. `%+/` Sum, then take the square root. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 8 ~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ạ/«ạ¥ÆḊ ``` A dyadic Link that accepts the coordinates as a pair of pairs\* of integers\*\* on the left and the size as an integer\*\* on the right and yields the Euclidean toroidal distance. \* I guess this will work in any integer number of dimensions too. \*\* Will work with floats too (up to floating point inaccuracies, of course). **[Try it online!](https://tio.run/##y0rNyan8///hroX6h1YDyUNLD7c93NH1////aAMdy1idaEMdw9j/hgYA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hroX6h1YDyUNLD7c93NH1//By/UdNa/7/jwYCBUMdBQWDWB0FCMswFshUMIrV4VIASRoBOcZgSQgLJGkCkzSA6zQC68GQtEQ11tAAJmkJ1wliWaBIGgINMzYBSZqa6SiYgyUtLTHstLQACiMkYwE "Jelly – Try It Online"). ### How? \$\text{Distance} = \sqrt{\left (|x\_1-x\_2| \land ||x\_1-x\_2|-N| \right )^2 + \left (|y\_1-y\_2| \land ||y\_1-y\_2|-N| \right )^2}\$ ``` ạ/«ạ¥ÆḊ - Link: Coordinates=[[x1, y1], [x2, y2]]; Size=N / - reduce (Coordinates) by: ạ - ([x1, y1]) absolute difference ([x2, y2]) -> D = [|x1-x2|, |y1-y2|] ¥ - last two links as a dyad - f(D, N): ạ - (D) absolute difference (N) (vectorises) -> D2 = [||x1-x2|-N|, ||y1-y2|-N|] « - (D) minimum (D2) (vectorises) -> M = [min(|x1-x2|, ||x1-x2|-N|), min(|y1-y2|, ||y1-y2|-N|)] ÆḊ - norm = vector_length = square_root(sum(squared_values))) -> (min(|x1-x2|, ||x1-x2|-N|)^2 + min(|y1-y2|, ||y1-y2|-N|)^2)^(1/2) ``` [Answer] # [julia](https://julialang.org/), 43 bytes Notice that for any point \$x\$, the \$N\$-toroidal distance from \$x\$ to \$(N/2, N/2)\$ is the Euclidean distance from \$\mathrm{mod}(x, N)\$ to \$(N/2, N/2)\$. Hence, we can find the \$N\$-toroidal distance between \$a\$ and \$b\$ by computing the Euclidean distance from \$\mathrm{mod}(a-b+(N/2, N/2), N)\$ to \$(N/2, N/2)\$. ``` d(a,b,N)=sum(@. (mod1(a-b+N/2,N)-N/2)^2)^.5 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XdDRCoIwFAZggq56ikE3E-famdO2i6An8AWiwJDAUIvSp-nGGx-qnqYzXTGEwQ_j23_GeQ3Xrirzvh-69hLpd1jQnJ1ZFuyeXU33nND6VgDNo3OYbSTeRxjBCQ9PpiefxfL-KJu2amhBD8CIODJiEzBlEJA1gZUnJCOxFS7VKIQvhOtAIf9Cch3PkPEGgXBKKl8ZV4WpPeUTsB9RFiUpI1vLjBlZim3zmVObRuNB4AqmZfz2-AU) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~38~~ 33 bytes ``` nNorm[Min[#,n-#]&/@Abs[#-#2]]& ``` Thanks to @att! Where `` stands for `\[Function]` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@/9pIV@@UW50b6ZedHKOnm6yrFq@g6OScXRyrrKRrGxav8DijLzShzSog0NYqOrDXQsa3UUqg11DGtjuWAylpZgGQOQjKWFjqVFbex/AA "Wolfram Language (Mathematica) – Try It Online") Input: `[N][{x1,y1}, {x2,y2}]` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` αDŠ-ø€ßnOt ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3EaXowt0D@941LTm8Pw8/5L//6MNjXSMTWK5ok3NdMwtYrksLQE "05AB1E – Try It Online") -1 thanks to *@KevinCruijssen* #### Explanation ``` αDŠ-ø€ßnOt # Implicit input α # Absolute difference between the first two inputs D # Duplicate this pair Š # Triple swap so the input is second - # Subtract the absolute difference between the # first two inputs from the third input ø # Zip this with the absolute difference €ß # Minimum of each inner pair n # Square each O # Sum the list t # Square root the sum # Implicit output ``` [Answer] # JavaScript (ES7), 64 bytes Expects `(x1,y1,x2,y2,N)`. ``` (x,y,X,Y,n)=>((g=d=>(d*=d)<(q=n-d**.5)*q?d:q*q)(X-x)+g(Y-y))**.5 ``` [Try it online!](https://tio.run/##ddBBDoIwEAXQvafoslNbaAsqNVavAUtCgWgMiBgDp8cSajSIi5@/mJfppJf0mbbZ/Xx7sKo2@VDoAXe0pzFNaAX6iHGpjS1DtIEDbnTFDCHeBkhzMvuGNIBj1sG6xAnrAcbRkNVVW19z71qXuMBIUIS4jXCRAMj3kfA4X82otONgJK7DifIFyt1W6eKo9KJgiarPAYK/qQznVLmtY0ff9OcAYR8NQoo2W4p2lio10a1dG/w5VkUu6v0FoRhe "JavaScript (Node.js) – Try It Online") ### Commented ``` ( x, y, // (x, y) = coordinates of the 1st point X, Y, // (X, Y) = coordinates of the 2nd point n // n = size of the torus ) => ( // ( g = d => // g is a helper function taking d (d *= d) // square d < // and compare it with ( q = // q defined as: n - // the difference between n and d ** .5 // the square root of d (which is the // absolute value of the original d) ) * q // multiplied by itself ? // if d is less than q²: d // return d : // else: q * q // return q² )(X - x) + // 1st call to g with d = X - x g(Y - y) // 2nd call to g with d = Y - y ) ** .5 // square root of the sum ``` [Answer] # [Factor](https://factorcode.org/), 52 bytes ``` [ v- 2dup n-v rot '[ [ _ rem ] map ] bi@ vmin norm ] ``` [Try it online!](https://tio.run/##bdA9b8IwEAbgPb/i3TqBkkABtwsb6tKl6hQhlKYXNSqxzdmJFKH89vRigooE/jrpHp9PcpkX3vDw@fH2vntBnfufeUtjyuGXWNMRJXchD0enhnRBDrlzpnCwTN53livt8RpF5wgyzkhlJ4jRh5hI7CdZBl0EucRbiaeaVOa/JHEg9eC5QGqqUtjckFKjS49lwOcV1nd87ac24xqxHzK0M6TfjYWetWDj8ZQhwwFMNfbyD1bOr2qLtq40tGHJSlFZsfMLIfkSaxyFi/PhDw "Factor – Try It Online") Takes input as `N { x1 y1 } { x2 y2 }`. ``` ! 10 { 9 0 } { 9 8 } v- ! 10 { 0 -8 } 2dup ! 10 { 0 -8 } 10 { 0 -8 } n-v ! 10 { 0 -8 } { 10 18 } rot ! { 0 -8 } { 10 18 } 10 '[ [ _ rem ] map ] ! { 0 -8 } { 10 18 } [ [ 10 rem ] map ] bi@ ! { 0 2 } { 0 8 } (apply quot to both points) vmin ! { 0 2 } norm ! 2.0 ``` [Answer] # [Python](https://www.python.org), ~~63~~ ~~59~~ 57 bytes *Edit: -4 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) and -2 thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor).* ``` lambda x,y,X,Y,N:abs((x-X+(k:=N/2))%N-k+((y-Y+k)%N-k)*1j) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXMSc5NSEhUqdCp1InQidfysEpOKNTQqdCO0NbKtbP30jTQ1Vf10s7U1NCp1I7WzwRxNLcMsTagBUwuKMvNKNNI0DHUMdAyBEKiBCyZmpGOsA8ImSGIGQHVGQIgqZgnWa2iAJGipAxK2QBU0BBpnomNqpmNuoWNpiWaspQUYAYUhjluwAEIDAA) Port of [Damian Pavlyshyn's comment](https://codegolf.stackexchange.com/questions/260743/calculate-euclidean-distance-on-a-torus#comment573669_260757). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~60~~ 56 bytes ``` ->a,b,n{(-4..4).map{|c|(a-b-n*(c%3-1+1i*c/=3)).abs}.min} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0knr1pD10RPz0RTLzexoLomuUYjUTdJN09LI1nVWNdQ2zBTK1nf1lhTUy8xqbhWLzczr/Z/gUJatKEOSE7HKJYLxDPSNgayQYQJRMAAyDOC8ywzIaoNDaB8HUttCwTXEKjTJFPH1EzbHChqaQkzwtJC2xIi8B8A "Ruby – Try It Online") ## How? Input as complex numbers. `(a-b).abs` is the distance between a and b on the complex plane. We have to move b into the 8 adjacent spaces, and calculate distance between the original a and the new b, then take the minimum. Iterating from -4 to +4 we get the offset table using `c%3-1` for the real part, and `c/3` for the imaginary part: ``` +-----+-----+-----+ | -4 | -3 | -2 | |-1-i | -i | 1-i | +-----+-----+-----+ | -1 | 0 | 1 | | -1 | 0 | 1 | +-----+-----+-----+ | 2 | 3 | 4 | |-1+i | i | 1+i | +-----+-----+-----+ ``` [Answer] # Python3, 79 bytes: ``` lambda x,y,X,Y,n:(min(abs(x-X),n-abs(x-X))**2+min(abs(y-Y),n-abs(y-Y))**2)**0.5 ``` [Try it online!](https://tio.run/##XYzBCoMwEETv/YoeEzspSdQ2KfQ/FHqJFKlQ02A9mK9PEyGgZXdgeLM7zs@vjy2Vm0J/f4S3GbunOS7waNDC3sg4WGK6L1lYQ2FZtrQo5ClnnrU5SzZlUfxcBzcNdiY9EeAQcSSlh8wkSiRVG8bjnYyzZ3r9FXwDNRJWeyhiXYX6gquC1n@1Wq0bcfgB) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` -AD⁶_Ọ²Sƭ ``` #### Explanation ``` -AD⁶_Ọ²Sƭ # Implicit input -A # Absolute difference between first two inputs D # Duplicate the pair ⁶_ # Subtract from the third input Ọ # Elementwise dyadic minimum ² # Square each S # Sum the list ƭ # Square root the sum # Implicit output ``` #### Screenshot [![Screenshot](https://i.stack.imgur.com/qy84Am.png)](https://i.stack.imgur.com/qy84A.png) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, ~~10~~ 9 bytes ``` ε:?$-Þ∵∆/ ``` Thanks @TheThonnu! [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyLhuIsiLCIiLCLOtTo/JC3DnuKIteKIhi8iLCIiLCJbMTIsMzRdXG5bNTYsNzhdXG45OSJd) Input: `[x1, y1] \n [x2, y2] \n N` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` I₂ΣEθ⌊X⁻↔⁻ι§ηκ⟦⁰ζ⟧² ``` [Try it online!](https://tio.run/##LcnLCsIwEIXhV5nlBEbQei2uiisXhaLLkEWsgYamic1FxZePAT2r7@f0g/S9kybnzmsb8SRDxOucpFcX5wrThK184EzQaqunkp17KY@lUsDmFpxJUf1TEzTxbO/qjQPByBgj4EuCjyio2G/HnDlfVQTrjSj3dkewPxTVtciLp/kC "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two pairs of coordinates and a number. Explanation: ``` θ First input E Map over coordinates ι Corrent coordinate ⁻ Subtract η Second input § Indexed by κ Current index ↔ Absolute value ⁻ Vectorised subtract ⟦ ⟧ List of ⁰ Literal integer `0` and ζ Third input X Vectorised raise to power ² Literal integer `2` ⌊ Take the minimum Σ Take the sum ₂ Take the square root I Cast to string Implicitly print ``` [Answer] # SAS 4GL, 71 bytes (or 57) 1. *The answer (in short, just "the point"):* ``` data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run; ``` --- 2. *The answer and all details [with details ;-)]:* Input: ``` data input; /* x1 y1 x2 y2 N Result */ input x y p q n r; cards; 1 0 1 1 2 1.00 2 3 2 3 4 0.00 0 0 2 2 4 2.83 0 9 1 1 10 2.24 9 0 9 8 10 2.00 12 34 56 78 99 62.23 0 0 98 98 99 1.41 ; run; /* to print input data */ proc print data=input; run; ``` Immediately after "input code" run: Code: ``` data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run; ``` The: ``` data;set;...run; ``` part is mandatory for every SAS 4GL code so if we select only the "calculation" part: ``` a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2); ``` it is 57 bytes ;-) Code formatted: ``` data; set; a = abs(x - p); b = abs(y - q); d = sqrt( (a >< (N - a))**2 + (b >< (N - b))**2 ); run; ``` Comments: * `i><j` is minimum of i and j, `i**j` is i to power j * `sqrt(expression)` is the same number of bytes as `(expression)**.5`, * brackets arounf `N-b` are necessary because `><` takes precedence over substraction, * result dataset is named `DataX` where X is the first integer not yet used for naming default dataset. Log: ``` 1 data;set;a=abs(x-p);b=abs(y-q);d=sqrt((a><(N-a))**2+(b><(N-b))**2);run; NOTE: There were 7 observations read from the data set WORK.INPUT. NOTE: The data set WORK.DATA4 has 7 observations and 9 variables. NOTE: DATA statement used (Total process time): real time 0.00 seconds cpu time 0.00 seconds ``` --- [Answer] # [Scala](http://www.scala-lang.org/), ~~137~~ 96 bytes Saved 41 bytes thanks to the comment of @corvus\_192 --- [Try it online!](https://tio.run/##dY5RS8MwEMff8ynuMcGrtHXqUqgg@OKDTyJsiEg62y2jTWsadWX0s9drtCDbDHfHcb//3T/tSpVqqLNtvnLwoLSBPftUJRQJvzcOD1KkN3f1R1bm6X7QVVNbB5Vym/NXxnfY4QKXaEjTvlvHm/qLV9pwlbV8FywEmmBqBcbi7C/vguXEx3bkYugZwFtekMOosus2gVtrVff86Kw26xeRwJPRDlL6MtBraOpKwwseIYQIkQ@6dEBjhAua@zo7oqHfjX2cpHK6HIVHWPplqvOTOBpNZwiXVwjXJJHyH3s5/80fQc96NnwD) ``` import math._ (x,y,X,Y,n)=>sqrt(pow(min(abs(x-X),n-abs(x-X)),2)+pow(min(abs(y-Y),n-abs(y-Y)),2)) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` íaV ËmDaWÃx²¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7WFWIMttRGFXw3iyrA&input=WzEyIDM0XQpbNTYgNzhdCjk5) ``` íaV ËmDaWÃx²¬ :Implicit input of arrays U=[x1,y1] & V=[x2,y2] and integer W=N í V :Interleave U & V a : Reducing each pair by absolute difference Ë :Map each D m : Minimum with DaW : Absolute difference of D & W à :End map x :Reduce by addition after ² : Squaring each ¬ :Square root ``` [Answer] # [Arturo](https://arturo-lang.io), 57 bytes ``` $=>[x:abs&-&y:abs&-&n:&sqrt+^min@[x,n-x]2(min@[y,n-y])^2] ``` [Try it](http://arturo-lang.io/playground?N0wy1v) Takes input as `x1 x2 y1 y2 N`. ``` $=>[ ; a function x:abs&-& ; assign absolute value of first arg minus second arg to x y:abs&-& ; assign absolute value of third arg minus fourth arg to y n:& ; assign fifth arg to n (min@[y,n-y])^2 ; minimum of y and n-y squared ^min@[x,n-x]2 ; minimum of x and n-x squared + ; add sqrt ; square root ] ; end function ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 17 bytes ``` {√+´×˜⌊´𝕨|-⊸⋈-´𝕩} ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=VG9yb2lkYWxfZGlzdCDihpAge+KImivCtMOXy5zijIrCtPCdlah8LeKKuOKLiC3CtPCdlal9CgoxMCBUb3JvaWRhbF9kaXN0IOKfqOKfqDAsOeKfqSzin6gxLDHin6nin6k=) ``` {√+´×˜⌊´𝕨|-⊸⋈-´𝕩} # function taking N as left arg (𝕨) # and [[x1,y1],[x2,y2]] as right arg (𝕩): -´𝕩 # vectorized fold-subtract: [x1-x2,y1-y2] -⊸⋈ # joined to negative of itself: [[x1-x2,y1-y2],[x2-x1],[y2-y1]] 𝕨| # all modulo N ⌊´ # vectorized fold-minimum ט # vectorized multiply each element by itself +´ # sum (fold-addition) √ # square-root ``` [Answer] # [Scala](https://www.scala-lang.org/), 104 bytes Golfed version. [Try it online!](https://tio.run/##lZJNT4QwEIbv@yvmYtLGLsuXK2DYxMSLB7kYT5uNKR@uGD5LV6OE345TJIT1gvbQ9J32fabtTBPxjPdl@JZEEh54WkC7WgHEyQvkqAgXx8aDWyH45/5RirQ4HqgHT0UqwcejgKPCqMwKIktRpjHPnuO0kWSwEIOBThlMwkBhUqpsmw0Yi36TgTX5R2FPfn3Rr8/zmyr33G9qjvUXhPv7CYY@MAaEaS8i3PktUDjniOVfVC@3J8LVlsG1YrguMpCwxVtY//sL10H7nGFotipHh9VXxT8DePCD2N8X8jASxjXO1N/dlacwS7AjesJZyAIMte88g9jn2ldakZBqOa/aiDcJqViN26Ra15cBvQi6m5zLV62phSSxOkWEvxtCVflBhkWOfShYsBaUYe9ozSmnXd/13w) ``` (a,b,N)=>{val d=a.zip(b).map{case(p,q)=>(p-q+N)%N};math.sqrt(d.map(r=>math.pow(math.min(r,N-r),2)).sum)} ``` Ungolfed version. [Try it online!](https://tio.run/##lZLNToQwFIX38xRnY9JGZIDBEUjGxMSNC9kYV2ZiyhTHGv6EjkYn8@x4iw4BN2hX9zQ9X@9tT7MRmWjbMnlJNxq3QhXYz2aATJ@Qk2Ki3jYRrupafDzc6VoV2zWPcF8ojRUdBa2KdnVWMF3WpZIie5Sq0ayzMNeCwy30wiXhcW5s8zncSb9nYdH7f4Tf@51JvzO83zN3D/2eHSz@ggh/j@A6HaNDeP4kIhx2QSIYI6Zf0Uzu94TzpYULwwhDYhBhSV0s/vcWYUD2IcO1ffMdh@PvjwnimIGbQq8tJGMZR6CCcnFd7pIs7ZPxJjJIUsL@VBVLuJ2LCntsRJOCCUUcxbG6NDXOSOAUMccJYmrD@HOhn@3mtdZMGiuTypzudqvynXVFTiGVhIqJINV3vOxml/NumMOsbb8A) ``` object Main { def main(args: Array[String]): Unit = { println(toroidal_dist(Array(1, 0), Array(1, 1), 2)) // 1 println(toroidal_dist(Array(2, 3), Array(2, 3), 4)) // 0 println(toroidal_dist(Array(0, 0), Array(2, 2), 4)) // 2.83 println(toroidal_dist(Array(0, 9), Array(1, 1), 10)) // 2.24 println(toroidal_dist(Array(9, 0), Array(9, 8), 10)) // 2 println(toroidal_dist(Array(12, 34), Array(56, 78), 99)) // 62.23 println(toroidal_dist(Array(0, 0), Array(98, 98), 99)) // 1.41 } def toroidal_dist(a: Array[Int], b: Array[Int], N: Int): Double = { val d = a.zip(b).map { case (ai, bi) => (ai - bi + N) % N } math.sqrt(d.map(di => math.pow(math.min(di, N - di), 2)).sum) } } ``` ]
[Question] [ Given a ragged list of positive integers find the size of the largest list contained somewhere in it. For example: ``` [1,[1,[8,2,[1,2],5,4,9]],2,[],3] ``` Here the answer is 6 because one of the lists has 6 elements and all other lists have fewer. ``` [1,[1,[8,2,[1,2],5,4,9]],2,[],3] ^ ^ ^ ^ ^ ^ ``` The length doesn't care in any way about the *value* of the elements, so a list can be longer than the list that contains it. ## Task Given a ragged list of positive integers output the size of the largest list contained somewhere in it. You may take input in any reasonable format. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with the goal being to minimize the size of your source-code. ## Testcases ``` [] -> 0 [[]] -> 1 [1,2,3] -> 3 [[1,2,3]] -> 3 [1,2,[],1] -> 4 [1,[1,[8,2,[1,2],5,4,9]],2,[],3] -> 6 ``` [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` f=lambda a:a>[]and max(len(a),*map(f,a)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNzXSbHMSc5NSEhUSrRLtomMT81IUchMrNHJS8zQSNXW0chMLNNJ0EjU1oeo1C4oy80oU0jSiDXVAyELHCEQbxeqY6pjoWMbGgvixOsaxUA0wiwA) Uses Python 2's global ordering: lists are all considered greater than ints. We can also use `>` instead of `>=`, because `[]>[]` is `False` which is the same as `0`, which would be the result anyway from the `max(len(a),*map(f,a))`. This also uses the var-args version of `max` which is shorter than constructing a list. Normally we wouldn't be able to do this, because the var-args form of `max` only works with 2 or more arguments, but if we know `a>[]` then `a` is non-empty, so `*map(f,a)` always adds at least one more argument to the call. # [Whython](https://github.com/pxeger/whython), 34 bytes ``` f=lambda a:max(len(a),*map(f,a))?0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWN5XSbHMSc5NSEhUSrXITKzRyUvM0EjV1tHITCzTSdBI1Ne0NoCq1Cooy80o00jSiDXVAyELHCEQbxeqY6pjoWMbGgvixOsaxmpoQHTA7AA) When a member is an integer, the `len` call fails; we just catch this and replace the result with `0`. When `a` is an empty list, this also fails because `max` gets only one argument, but catching and returning `0` conveniently fixes this too. [Answer] # [R](https://www.r-project.org/), 58 bytes ``` f=function(x)max(l<-length(x),if(l&is.list(x))sapply(x,f)) ``` [Try it online!](https://tio.run/##K/qfk5@XnlpcEp@TWVxi@z/NNq00L7kkMz9Po0IzN7FCI8dGNyc1L70kA8jXyUzTyFHLLNYDqQXyNYsTCwpyKjUqdNI0NVEM0gATmpoKygq6dgoGXJhyhjpGOsYwBcZYFCCrwqMMpAJimY4hTJ0JVnXIlAVMF1C7po6pjomOpaYmwiS4w8z@AwA "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#t:Free), ~~[40](https://codegolf.stackexchange.com/revisions/240685/1)~~ 37 bytes *3 bytes saved by Lynn* Haskell doesn't have a built in ragged list type so we need to build one out of free monads from the [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html#t:Free) package. ``` iter(maximum.((:)=<<length)).fmap(*0) ``` [Try it online!](https://tio.run/##bZBBT4QwEIXv/Io5kNga2ahHApzMJp704M1szLi0y0RaCBTlsP8dpy2smngo6fvmzcwrDY4fqm2XLIMzPChNluwJXEMjNGpQMJI9KtYK9KAUmK6eWgU02isH@InU4jvrzsLL41NSo0PYe58GTABKeJ54hr@eIxcaxGaQMknIjg55AzsE7Cd7dN0AmpXkwwOqC1zbPP/yyUJdG@x5lAhrZglloBDXplyZ/9jCiF@2oNNYFtEkuSUhpwbI859APghHR8gqzu2/2yMCiQ1vaw42lBvrG1rXGk@DvBSKtGK86NITYXAmM5mdELksi6JV9uQaKXc@l7i@lYtBsmXdcfZ@IOvC@@Ls14P8j4Y0dzfxb9wf5PIN "Haskell – Try It Online") ## Explanation First we replace every number with `0` because that is their length, or at least it's the length they should be to make the math work out. Then from there we make a function `maximum.((:)=<<length`. This looks complicated, but really all it does is take the length of a list of integers, put it on the front of the list and take the maximum of that. So it gives the max of the list or the length of the list whichever is larger. With this we use `iter` to "tear down" the list. `iter` will start first with the lists containing only integers and run this on them then replace them with their results, and then it will do that again, and again until we've reduced the entire structure down to a single element. We can visualize the entire process as: ``` [1,[1,[8,2,[1,2],5,4,9]],2,[],3] [0,[0,[0,0,[0,0],0,0,0]],0,[],0] -- Replace everything with 0 [0,[0,[0,0,2,0,0,0]],0,0,0] [0,[0,6],0,0,0] [0,6,0,0,0] 6 ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~15~~ 13 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) -2 bytes thanks to Razetime! ``` {(≠⌈´𝕊⍟=¨)×𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiaDijIjCtPCdlYrijZ89wqgpw5fwnZWpfQoKPuKLiOKfnEbCqCDigKJKc8Ko4p+oIltdIgoiWzEsMiwzXSIKIltbMSwyLDNdXSIKIlsxLDIsW10sMV0iCiJbMSxbMSxbOCwyLFsxLDJdLDUsNCw5XV0sMixbXSwzXSLin6k=) ``` {(≠⌈´𝕊⍟=¨)×𝕩} # Anonymous function taking the list as right argument 𝕩 ×𝕩 # Sign of each number, converts all numbers to 1 =𝕩 ¨ # For each value in the list 𝕊⍟= # do a recursive call if it is a list (rank 1) # and return integers unchanged (rank 0) ≠⌈´ # Maximum reduction of the results starting with the length of 𝕩 ``` or questionable 12 bytes: ``` {(≠⌈´𝕊⎊0¨)𝕩} ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgeyjiiaDijIjCtPCdlYrijoowwqgp8J2VqX0KCj7ii4jin5xGwqgg4oCiSnPCqOKfqCJbXSIKIlsxLDIsM10iCiJbWzEsMiwzXV0iCiJbMSwyLFtdLDFdIgoiWzEsWzEsWzgsMixbMSwyXSw1LDQsOV1dLDIsW10sM10i4p+p) This relies on exceeding the maximum call stack size, which means this only works if such a limit exists and is larger than the maximum depth of the ragged list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔDgˆʒ˜gĀ}€`}¯à ``` [Try it online](https://tio.run/##yy9OTMpM/f//3BSX9NNtpyadnpN@pKH2UdOahNpD6w8v@P8/2lAHhCx0jEC0UayOqY6JjmVsLIgfq2NsYmpmbmFpEAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1Nc0k@3nZp0ek76kYbaR01rEmoPrT@84L/OoS3/o6NjdRSiDXWMdIxBDCgLJgaUNISwQcgCJAIUjtUx1THRsQSqAqswNjE1M7ewNIiNBQA). **Explanation:** ``` Δ # Loop until the result no longer changes: D # Duplicate the current list g # Pop and push its length ˆ # Pop and add this to the global array ʒ # Filter the items within the list: ˜ # Flatten it g # Pop and push the length Ā # Check that this is not 0 } # After the filter: €` # Flatten the list one level down } # After the loop: ¯ # Push the global array with lengths à # Pop and push its maximum # (which is output implicitly as result) ``` Bug-abuses the fact that [`˜` gives an error on integers](https://tio.run/##yy9OTMpM/f//9Jz//41NTM3MLSwNAA), causing them to be removed after the filter. Most errors in 05AB1E are simply ignored, which would be incorrect in this case, since the `gĀ` would result in a truthy result. --- Could have been **13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** in the [legacy version of 05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) if all integers were guaranteed to contain less digits than the intended result: ``` ˜g'ε׿'g«€.VZ ``` [Try it online](https://tio.run/##MzBNTDJM/f//9Jx09XNbD08/vEw9/dDqR01r9MKi/v@PNtRRAGMLHQUjCNMoVkfBVEfBREfBMjYWIgqkjGMB) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeWhlf9Pz0lXP7f18PTDy9TTD60@t/XQumK9sNqo/zr/o6NjdRSiDXWMdIxBDCgLJgaUNISwQcgCJAIUjtUx1THRsQSqAqsAKgcA). ``` ˜ # Flatten the (implicit) input-list g # Pop and push its length 'ε× '# Push a string of that many "ε" æ # Pop and push the powerset of this string # (the prefixes would be enough, but that builtin doesn't include # an empty string which the powerset builtin does) 'g« '# Append a trailing "g" to each € # Map over each string .V # Execute it as 05AB1E code with the (implicit) input-list # (where `ε` is a map, and `g` pushes the length) Z # Push the flattened maximum of this list # (which is output implicitly as result) ``` This unfortunately doesn't work if the integers are too big, because the `εg` would include the lengths of each inner integer in the resulting list of lists, which could potentially be larger than the intended result. [See that it fails if an input-number contains too many digits.](https://tio.run/##MzBNTDJM/f//9Jx09XNbD08/vEw9/dDqR01r9MKi/v@PNtQBIQsdIxBtFKtjqmOiYxkbC@LH6hibmJqZW1gaxAIA) Minor note: Luckily the `'ε×` isn't a dictionary word. If we would use `€` instead of `ε` it wouldn't work, because [`'€×` is the dictionary word for `"view"`](https://tio.run/##MzBNTDJM/f9f/VHTmsPT//8HAA). [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ ~~13~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ˶ԩßDÃrwUl ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=y7bUqd9Ew3J3VWw&input=WwpbXQpbMSwyLDNdCltbMSwyLDNdXQpbMSwyLFtdLDFdClsxLFsxLFs4LDIsWzEsMl0sNSw0LDldXSwyLFtdLDNdCl0KLW0) (includes all test cases) ``` ˶ԩßDÃrwUl :Implicit input of array U Ë :Map each D ¶ : Test for strict equality with Ô : Max with nothing if an integer (which, for some reason, returns an object) Ô : Itself reversed if an array (which works because reversing mutates the array) © : Logical AND with ßD : Recursive call with argument D à :End map r :Reduce by w : Maximum Ul : With initial value of length of U ``` [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes ``` f=lambda x:x*-1or max([len(x),*map(f,x)]) ``` [Try it online!](https://tio.run/##FcdBCoAgEEDRq7SckWmRFlTQSWQWRkmBmkiL6fSG8OHx8/deTzK1@i24uB@uk1VUPzyli07AhjOBIKnoMngSZKy53OkFD3ag1ky6qZkmGmlhbs9kGLH@ "Python 3 – Try It Online") -10 bytes thanks to loopy walt with a better way of typechecking [Answer] # [Factor](https://factorcode.org/), 41 bytes ``` [ [ array? ] deep-filter longest length ] ``` [Try it online!](https://tio.run/##VY5NC8IwDIbv/RXvH3AwP8CPg0fx4kU8jR3KzOZgdrWNhzH62@vqitRAyJs8b0JqWXFv/O16vpz2kMbIwcLS602qokRldyINbYh50KZVjIMQo8AUI1ysk/rpHEusEhL7Px78eTKZc/slgTtssMYubEV3uOiEL1DMvx5RIny2qNuOyaDrVUOW0ZFq@IHSP6VG5j8 "Factor – Try It Online") Get a list of every list (no matter the depth), then find the length of the longest one. `deep-filter` is like `filter` except instead of traversing elements in a linear fashion, it traverses nested sequences using a depth-first search algorithm. (`deep-reduce` is also an approach that works, but it offers atoms and so it's verbose to check for and ignore them.) ``` ! { 1 { 1 { 8 2 { 1 2 } 5 4 9 } } 2 { } 3 } [ array? ] deep-filter ! { ! { 1 { 1 { 8 2 { 1 2 } 5 4 9 } } 2 { } 3 } ! { 1 { 8 2 { 1 2 } 5 4 9 } } ! { 8 2 { 1 2 } 5 4 9 } ! { 1 2 } ! { } ! } longest ! { 8 2 { 1 2 } 5 4 9 } length ! 6 ``` [Answer] # [R](https://www.r-project.org/), ~~66~~ 64 bytes ``` f=function(x)"if"(is.list(x)&(l=length(x)),max(l,sapply(x,f)),0) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jQlMpM01JI7NYLyezuATIVdPIsc1JzUsvyQByNHVyEys0cnSKEwsKcio1KnTSgEIGmv/TNMCqNTUVlBV07RQMuKAChjpGOsYwUWOYKLIUuhxIGGKWjiFM0gQhiUxZwJQC9WjqmOqY6FgCXQPXDrfX7D8A "R – Try It Online") Currently being out-golfed by [Dominic van Essen](https://codegolf.stackexchange.com/a/240683/67312). [Answer] # JavaScript, 40 bytes ``` f=a=>a/a||Math.max(a.length,...a.map(f)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P8020dYuUT@xpsY3sSRDLzexQiNRLyc1L70kQ0dPTy8RKFKgkaap@b@gKDOvRCNNIzpWU5MLzomOReEa6hjpGKMqgAhhqIqO1TFEEwQhC5AUUD5Wx1THRMcyNhaiFGTmfwA) # JavaScript, 43 bytes ``` f=a=>Math.max(~~a.length,...a.map?.(f)??[]) ``` ``` f=a=>Math.max(~~a.length,...a.map?.(f)??[]) console.log(f([])) console.log(f([1,2,3])) console.log(f([[1,2,3]])) console.log(f([1,2,[],1])) console.log(f([1,[1,[8,2,[1,2],5,4,9]],2,[],3])) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` -λ[vxnLJG ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCItzrtbdnhuTEpHIiwiIiwiWzEsMixbMyw0LFs0LDVdLDUsWzYsNyw4XSw5LDEwXSw2XSJd) ``` - # Subtract from self to generate a list with the same shape but only zeroes λ # A recursive lambda, which automatically gets called with ^ [ # If it's truthy (a list) vx # Do a recursive call on each item nLJ # Append the length of the list G # Get the maximum ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 25 bytes Full program. ``` l←⍬ {1<|≡l,∘≢←⍵:∇¨⍵}⎕ ⌈/l ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94H/Oo7YJj3rXcFUb2tQ86lyYo/OoY8ajzkVg0a1WQCWHVgAZtY/6pnI96unQzwHp@q8ABgVcQFGvYH8/9WhDHSMd41h1LgwJqAw2KZBMdKyOIXY5ELIAqQAqi9Ux1THRsYyNhegAWgQA "APL (Dyalog Unicode) – Try It Online") `l←⍬` initiate `l` to an empty list `⎕` get evaluated console input `{`…`}` apply the following anonymous lambda to that; the argument is `⍵`:  `⍵` the length of the argument  `l,∘≢←⍵` append `l` with the argument length, giving the argument as pass-through value  `≡` the depth (nesting level — negative if ragged) of the argument  `|` absolute value of that  `1<`…`:` if that is greater than 1:   `∇¨` recurse on each element of the argument `⌈/l` [implicitly print] the largest value of `l` (lit. max-reduce) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 13 bytes ``` {⌈´≠⊸∾𝕊¨⍟=×𝕩} ``` Anonymous function that takes a list and returns an integer. [Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+4oiY4oaTwqgKCkYg4p+oImNhdCIsICJoZWxsbyLin6k=) Found independently of [ovs's solution](https://codegolf.stackexchange.com/a/240678/16766), but takes advantage of a 1-byte savings proposed in a comment on that solution by [Razetime](https://codegolf.stackexchange.com/users/80214). ### Explanation ``` {⌈´≠⊸∾𝕊¨⍟=×𝕩} 𝕩 Start with the argument, which is either a list or an integer × Get its sign (applies itemwise over lists): converts all integers to 1 ⍟= Apply this function 0 times to an integer or 1 time to a list: 𝕊¨ Map a recursive call over each element ≠⊸∾ Prepend the length of the list (or 1 if it's an integer) ⌈´ Take the maximum ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ⊞υAFυFιF⁼κ⁺κ⟦⟧⊞υκI⌈EυLι ``` [Try it online!](https://tio.run/##NczBCsIwDAbgu0/RYwPx4FRQdhQPgkLvJYcy1I513Wwb8e1rOzQEPn7Cn86a0E3G5aw4WskoLn7mJAHa1WMKQjKIxf7n@cXGRTmgUI4XNQGA@NeHUlSh90meTEzyZj79yGNxrtfr3T@TLc/qtDlrvcG6B2yqDeEed3gkqplwS5TXb/cF "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υA ``` Collect the input list into the list of lists. ``` Fυ ``` Loop over each list. ``` Fι ``` Loop over each element. ``` F⁼κ⁺κ⟦⟧ ``` If adding the empty list to the element results in a copy of the element, ... ``` ⊞υκ ``` ...then push the element to the list of lists. (Adding the empty list to a scalar results in an empty list, not the scalar.) ``` I⌈EυLι ``` Output the maximum of all the lengths of the lists. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` Max[Length@#,#0/@(0#)]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@983sSLaJzUvvSTDQVlH2UDfQcNAWTNW7X9AUWZeSbSygq6dQlq0cmysgpqCvoNCdXWtjkK1oY6CkY6CMYgJZyPEQUoMoVwwtoAIg2SBwqY6CuY6CpYgDVDFQM3/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` {ċl|ċ∋↰}ᶠ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pId07Nke5HHd2P2jbUPty24FFP5///0YY6IGShYwSijWJ1THVMdCxjY0H8WB3j2P9RAA "Brachylog – Try It Online") ### Explanation ``` { }ᶠ Find all possible outputs of the following predicate: ċ The input is a list l Output its length | OR ċ The input is a list ∋ Take an element of that list (creates choice points for each element) ↰ Recursively call this predicate ⌉ Final output is the maximum value of the resulting list of possible outputs ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 7 ~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ¬ß€»LṀ ``` **[Try it online!](https://tio.run/##y0rNyan8///QmsPzHzWtObTb5@HOhv@H24Hs//@jo2O5dIAEiDTUMdIxBnMhLJhYdKyOIYQNQhYgEaBwrI6pjomOZWwsRAVQYywA "Jelly – Try It Online")** A monadic Link accepting a list containing any strictly positive integers or nested, similar, lists that yields the maximal length list. ### How? ``` ¬ß€»LṀ - Link, call this "f": list, A ¬ - logical NOT (vectorises) - convert all positive integers to zeros so that we wont implicitly treat them as ranges € - for each element, E, in A (...if the current A isn't now a zero): ß - call this Link (i.e. f(A=E)) L - length of A - Note that zero has length one. » - maximum (vectorises) Ṁ - maximum (of the resulting list) ``` [Answer] # [Perl 5](https://www.perl.org/), 34 bytes ``` sub f{max@_+0,map ref?f(@$_):0,@_} ``` [Try it online!](https://tio.run/##hZFJT8MwEIXP5FeMKqMkYNKEbuDINIfeQPQCp9SKAjiRRZNYWaSitvz1YMeI7YLlw5vvvRl5kbzezvqu4XAnmpaQx1ZswS7SnR1amq7SNiVk1RWS16GVVbVjxQAxA3oDPgDDQxmzAQRfIMCXeDKwyXfIwD9Uw5jhYMDTH1jvK22qBMMzPMXXjJmwmTz/J6wKz1v87lkMPe7eArWKNwcJjLhLI5SEnwjlNHMiJFwDkKDm8irq0vdm7J3Rw6Y5hONxXpuIrEXZZqPTi3kDwHeSP7f8hQDiysurVqlcKVHKTmuh9KYcYesEcUqVtQS7erWBgH2/foD1rXr4Y990T5Dt1TdEybmPi1RCzbOlPljiEh9HybHvPwA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~44~~ 39 bytes ``` f=->d{d*0==0?0:[d.size,*d.map(&f)].max} ``` [Try it online!](https://tio.run/##RYvhCoJAEIT/31MsBVGyyZkWFVw9yLk/LE8SSkRPuFKf/brLIlh2v5mdabrL09pCrE95nwdcCH7mR5mHbflSGOThI6uXi2JFDsxopZSEwAkZeHQcTRzhBmMn4@9r0n/Da1d1aUh@jp@9992TcIsJHlzjk4sJEHbEKFTZ9dYPWrUaG9V2dz0wMKKQ3iEGNXjw17jVlJWG2bw3QkzhMa3SasaAsZHZNw "Ruby – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-m32` and `-lm`, ~~94~~ ~~88~~ 87 bytes * -6 thanks to ceilingcat 32-bit mode used to make bit-twiddling of pointers easier. As C doesn't have any list primitive, I implemented a tagged value list (lists stored as an item have the least significant bit set.) The function simply gets the total length of the current list and checks to see if any sublist has a longer length. ``` f(l,m,i)int*l,*m;{for(m=l,i=0;l;l=l[1])i++;for(;m;m=m[1])*m&1?i=fmax(f(*m^1),i):0;l=i;} ``` [Try it online!](https://tio.run/##rVXbbptAFHznK45cxWLJusmC0yahpD@Q9q1PhEYUQ7LSLkSA3aip@@l19wJ4MYZUaiUL4z0zZ@ZcwMniIUl2u8xmmGOKaF47DDvcf8mK0uYBwzQ495nPAhaSCNHTU18GfO7zgMsTh8/JRxpkPH62M9vhXwkSaa4FJ6D@dveG5glbr1L4UNUrWrx9vLF6R4x@G5wJD/LMqupyndTAaFXDC2wKugJnE7N16oMZcvL0ufZh61uWYAKt7uWx3eCRoJZpvS5zsEX4qS7va7SBORBBsTSoLjSll7XH1Dhkmyl@AkEyR4@VlQUf1e8h@8nm8OtINnm9VyWb6fqQIIkZKxK7oj/SQkyAISwzscWNIgYbv9Vnx/MPS2eGacNC2yaGUNc7FY5XqwbST4PBcP39kbLUFrbkuBCIhdK3yqq8Ccxqjygc8YlhOLIDRwLT@t5o3zptVqbpSOkW9NNysVkAau1lD1nANQiAZna7bm2/EVIRMAT2O7EH@QrFuyZYLUV0V/7YWq3Rp1KsybhTaUtBMnsWwgw1Frs@v27UEBh3mrIqNfFC7WQ1w@DIJRbL3OH9Vq9z0OKxdKdK2@eASJ61pdZpNVGp4VP36GldV/ZMJjAyfoqfKV9zYGn@UD9ew8nqLr/LhXim9tYyB8O0tqyAxzRXz5jWUi@SMApegGD5ucTgqhtxvcCwxHCl7j352jlYFxYuI2Xp7AzCSHzvy/r85fYWdbEwklEWnkfB/kFsICZLIlpWSLCLvQgWN@D1yHrb51RjYfAYiHMMIuxNh0lDH1Fv5A198rf6ZFqfmPrDtqh/n1faEkaYKGfL/9KZTgRDN5TRtk2ZA@FOfi6lR2E0whd4ia@iSHv29BZ4h3aXI3Y9LXnRNco9ZLojTHeyUBllo/NpuO@mw@@nw5ed58HakOOmiDLlDpZidKjG1Ngg6cHUrv5l4mMPynb3O8lY/FDtFtxzdwvG/wA "C (gcc) – Try It Online") Ungolfed: ``` f(l,m,i)int*l,*m;{ for(m=l,i=0;l;l=l[1]) i++; // Get length of current list for(;m;m=m[1]) *m&1? // Is this a sublist? i=fmax(f(*m^1),i): // Is the sublist longer? 0; l=i; } ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~65~~ 56 bytes ``` (load library (d M(q((x)(i(v x)1(max(c(length x)(map M x ``` [Try it online!](https://tio.run/##PYpRDoIwEET/OcV8zn62aKKH6CEqGGyyVkBiyunrCsHsJjvv7Swpr5reY63UV@yh6TbHeW3YI3AiizDxgyKOz1jYUe95WB4mjEcElMqAnLSxww4UW9lgooNHu2dwJ5Hji01Y3/3rNhf4n5czTriKeEpbvw "tinylisp – Try It Online") -9 bytes thanks to DLosc's suggestion for type abuse. [Answer] # [Julia 1.0](http://julialang.org/), ~~39~~ 34 bytes ``` ~a::Int=1 ~a=max(length(a),.~a...) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/vy7Rysozr8TWkKsu0TY3sUIjJzUvvSRDI1FTR68uUU9PT/M/l0NxRn65Ql10LJwVHYtgG@oY6RgjSUH4qPLRsTqGyCIgZAESB0rG6pjqmOhYxsZC1AGN@g8A "Julia 1.0 – Try It Online") Pretty easy to get a general idea of how this works. The `.~(a)` is way of recursively mapping our function (which we've called `~`) on the elements of a. (-5 bytes thanks to @MarcMush - making use of dispatch instead of the `isa` check.) ]
[Question] [ I don't like curry. Help me reverse the effects of this evil question - [Make me some curry](https://codegolf.stackexchange.com/q/162231/95792) - by uncurrying functions. # Task * Given a [blackbox](https://codegolf.meta.stackexchange.com/a/13706/95792) curried function, output its uncurried equivalent. * The curried function will take a single argument and output either another curried function or a value of another type. * The uncurried function you create will take the same number of arguments as the curried function, but all at once. # Rules * In languages without first-class functions, you can use an object with a method in place of a curried function - but please specify this. * The curried function may also output a function pointer instead. * If your language does not allow function pointers or makes passing around functions hard to work with, but allows evaluating strings to make functions (e.g. APL), you can use strings to represent both curried functions and your uncurried output function. * You can also take the number of arguments of the functions as an input to help you determine the depth of currying. * You may choose to return a function that takes a tuple, list, or other single value containing all the arguments. * You may constrain the arguments **and return type** to a data type of your choosing, but that type should have more than 1 possible value. * If `f` is the inputted curried function and `g` is your uncurried function, `f(a1)(a2)...(aN)` must always equal `g(a1, a2, ..., aN)`. * The order of arguments in the uncurried function should be the same as in the original curried function. For example, given the function `a -> b -> c -> a + b + c`, you can return a function that looks like `(a, b, c) -> a + b + c` or `arr -> arr[0] + arr[1] + arr[2] -> ...` but not `(c, b, a) -> ...` (wrong order). If you also take the number of arguments of the function as input, then `(a, b) -> c -> ...` would be an acceptable output given the input 2 (2 arguments are curried). # Bounty Since Rust is the language of the month, I will be offering a 50 rep bounty on Rust answer to this question if you haven't used Rust before. [Answer] # [Haskell](https://www.haskell.org/), ~~129~~ 127 bytes, thanks to Wheat Wizard ``` {-#Language GADTs#-} data N c u o where Z::N o()o;S::N c u o->N(i->c)(i,u)o (!)::N c u o->c->u->o (Z!o)_=o (S n!g)(i,u)=n!g i$u ``` [Try it online!](https://tio.run/##hY9Ra4MwFIXf/RXHtpSELvsBDoVBoS/FPtgnX0aqqYbZXNGEMsZ@u4tuFKEduw/hcO853yG17N9V0wzDp1jupamcrBR2r9tjvxRfgb601FlspZXPx49WyVOjIAROnTYVbK1g/fZwxtmZwmoycL0qoQ0u0j/aWEJfUKuC0iOQooAD4VqrTiGPohTEOL1ko5pOIkmZFknBmX5ynAIW8tmtEIkTid/mIfG32IsMJqx@zLFX0Cs3TNUxSgrgp3U2s93eYIWFIYvZRBEW2GzQ13QF@/2J9/C7YIYcIW7xh0F2M/F7AFuv@X/No@dR9Qjmnjwx/qqemzgfvgE) An unobfuscated version looks like this: ``` {-# Language GADTs #-} data Natural curried uncurriedArguments output where Zero :: Natural output () output Successor :: Natural curried uncurriedArguments output -> Natural (input -> curried) (input, uncurriedArguments) output deepUncurry :: Natural curried uncurriedArguments output -> curried -> uncurriedArguments -> output deepUncurry Zero output () = output deepUncurry (Successor n) g (input, uncurriedArguments) = deepUncurry n (g input) uncurriedArguments ``` The caller must specify the number of arguments they want uncurried as a natural number, where `Z` represents 0 and `S` adds one to a number. For example, to uncurry two arguments, you would use `S (S Z)`: ``` > :t S (S Z) ! (+) S (S Z) ! (+) :: Num o => (o, (o, ())) -> o ``` [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ``` lambda g,i:lambda*l,g=g:eval(f'g{"(%a)"*i%l}') ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFdJ9MKwtTK0Um3TbdKLUvM0UhTT69W0lBN1FTSylTNqVXX/F9QlJlXopGmAdWWCNWkkARjJFslaidpJ@soGGtqGOooGIEYmv8B "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 48 bytes ``` f=lambda g:lambda x,*a:f(g(x))(*a)if a else g(x) ``` [Try it online!](https://tio.run/##NYsxDoAgDAC/0rEVFnUj8TEFKZooEmXA12NMYLtc7tKbtyvOtcpy8GlXhmAaFD2wEQxYiHBg2gUY/PF4@FVN9x4zCraa@2Y7OMPKKkc4apg0zET1Aw "Python 3 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 34 bytes ``` g=>(...a)=>a.reduce((h,x)=>h(x),g) ``` [Try it online!](https://tio.run/##DcpLDkAwEADQvVNYzlCzwUqmd5mOaomo@MXty/Ilb5FHTj3m/Wq2NPo8cQ5sgYgE2QodfrzVA0Tz/o7wogmYI08gbB1b/VPtKsWh0LSdafW0pgARWlN2puwR8wc "JavaScript (Node.js) – Try It Online") -1 byte, thanks to ASCII-only. --- # [JavaScript (Node.js)](https://nodejs.org), 31 bytes ``` g=>(...a)=>(a.map(x=>g=g(x)),g) ``` [Try it online!](https://tio.run/##DcVBEkAwDADAu1c4JlQuOJnkL1EEgxo1xu/LXnbVR6O/lvOujjCMaeJkLEBEiv9Ku57wshgbvIjOMM08gbL0LJ5Fy77w2GU@HDFsI23BYIba5Y3LW8T0AQ "JavaScript (Node.js) – Try It Online") This 31 byte version, the returned function is not reusable. I'm not sure if this is allowed in this question... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` Fold[#@#2&]~Curry~2 ``` [Try it online!](https://tio.run/##nY47C4MwFIV3/0bA6QptUseWlFKnDg5u4QqptRjqMyZDEf3rVvuSrp3u4Rw@7ldIk6WFNCqRo92OQZVfBOGEujgcrNb3gY6hVqURxNtZQZAfk6zikbylYp/XmTynRiAQiuhyzjune1IizG0LDIH18KlOqjXQ@UCBwRo2PYI/j4EtE6OqUtTwjc0SNdRxE2uPaV67iDiBf0B00YhUkbbg/6i9OvY2oi6s5nudfjn9@AA "Wolfram Language (Mathematica) – Try It Online") Returns a function of a list of arguments, i.e. `u[f][{a,b,...}]=f[a][b]...`. Ironically, a short uncurrying involves `Curry`. Then again, functions curried with Mathematica's [`Curry`](https://reference.wolfram.com/language/ref/Curry.html) built-in can accept arguments in uncurried form - per the docs, "the structure of brackets is not relevant, only the number of arguments." --- To accept a sequence of arguments, i.e. `u[f][a,b,...]=f[a][b]...`, **20 bytes**: ``` f#@#2&~Fold~f?##& ``` [Try it online!](https://tio.run/##nY5LCsIwGIT3XiOQ1V/QxC7ViNiVCxfdhV@ItaXBvkyThZR6CG/gCT1CVHzh1tUMMwzzlcrmaamsTpR3E59dzxciCKOnqC52p2xGCPVroysrSTB1kqAQyySvRaz2qZwXTa62qZUIhCFSIUQ36BbOmKNcF64FjsB7eEcr3VroQmDAYQTjHiF8lJGrEqvrSjbwsYevNdBsDhsTcCMaioj34R8j9sWIdZm2EP6gPTP@ImIUhg/N7l@D3t8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Underload](https://github.com/catseye/stringie), 11 bytes ``` ((^)~^~a~*) ``` [Try it online!](https://tio.run/##K81LSS3KyU9M@a@RqKEFRJogyKVRoVkXp1EJIqqAhEKwgoaCZvB/DY04IK8usU5LE0V9nYaVlZYWSKEVRCUXSBtIP9ggmHYA "Underload – Try It Online") Function submission (because Underload full programs can't take input). The TIO link shows a curried function `a(*a(*)*)*` that concatenates its three arguments in reverse order (calling it three times by using the `(argument)~^` function call syntax that calls a function with one literal argument). Then it uses the program above, calling it with arguments 3 (`(::**)`) and the same curried function, producing the output `(a(*a(*)*)*)^^^`. The final line runs this input on the same three literal arguments (`(arg3)~(arg2)~(arg1)~^`), demonstrating that it produces the same result. ## Explanation ``` ((^)~^~a~*) ( ) define function literal: ~^ call {argument 1} with argument (^) lambda f, x: f(x) {replacing argument 1 with the return value} ~ ~ replace argument 2 with a uneval(argument 2) * compose argument 1 and argument 2 {and return the function newly created} ``` The basic idea here is to exploit the fact that Underload is generally very polymorphic with respect to how many arguments a function takes. In particular, we can take a function which takes two arguments and produces one return value, and call it in a loop in order to create a function that takes more than two arguments; each iteration will steal an additional argument from the argument stack. Numbers in Underload are basically curried loops with a specific number of iterations; you can think of the number 3 as having an effect similar to `lambda f: lambda x: f(f(f(x)))` (except with the number of arguments being more flexible than this). So by executing the first argument on `lambda f, x: f(x)`, we effectively end up creating a loop that uncurries a function via simply just calling it repeatedly, consuming an extra argument each time. This could have been just 8 bytes if not for an off-by-one error: if a function takes 1 argument, it's the same curried and uncurried; if it takes 2 arguments, we have to call it one more time; if it takes 3 arguments, we have to call it twice more, etc.. Arithmetic (other than multiplication and exponentiation) is very verbose in Underload, so instead of fixing the off-by-one error with subtraction, we uneval the function we're uncurrying. The uneval'ed function will consume no arguments and output the original function, so this neatly cancels out one level of uncurrying and thus fixes the off-by-one error. [Answer] # [R](https://www.r-project.org/), ~~68~~ ~~67~~ 71 bytes *Edit: -1 byte thanks to Giuseppe, but then +4 bytes to fix a bug spotted by ASCII-only* ``` function(f)function(...,g=f)el(rev(sapply(c(...),function(a)g<<-g(a)))) ``` [Try it online!](https://tio.run/##dZDdCoMwDIWv7VMUvElmJ6i7En2WUWv9YbJJNzdk@OxdtZ3KYIXQfMnhJK3Sw1UMSo25rkz2aG9XqHBNwzBkdV6h7EDJJ9x533cjiLmObFVxrLPsWJvbHO1TTmfLVpb0K1kKY8Xoq5FKOjJ6KBAEQok0p8CDAg8gghKJFeS7CW/irVTMtKFYcOPSsrc3NDiRJSYyEZ@KRopL6uZAhBAjJAgnJKbpvsStmRLL5j1nt5cTgEXc/H6VELGYJczY/u/oDw "R – Try It Online") This is a horrible bit of [R](https://www.r-project.org/) code, but my attempts using `for` or `while` have so far failed. Creates a function that uses `sapply` to loop over all its arguments, updating the passed function `f` in each iteration using the `<<-` assignment operator to assign in the 'parent' scope. This generates a list of all the intermediate values (all except the last one are partially-uncurried versions of `f`), so we `rev`erse it and return the new first element (so, effectively the last element), which is the result of the fully uncurried function call. ``` uncurry= # define 'uncurry' as function(f) # a function taking argument f, a curried function, function(...){ # that returns an anonymous function # with an undefined number of arguments, denoted as '...'. x= # define x as sapply( # the results of applying a function (see below) to each element of c(...), # the concatenation of all the elements of '...' (so: the arguments) function(a) # this is the function to apply, taking argument 'a' as each element: f<<-f(a)) # the value of f(a) # while updating 'f' to this value, in the parent scope # (so the next iteration will use this new version of 'f') rev(x)[[1]] # now, output the last element of x # (which is the value final, uncurried output; # the earlier elements of x are all the partially-uncurried # versions of f) } ``` Note that since we use `c()` to concatenate the argument list `...` into a vector (rather than into a list), the arguments are constrained to be all of the same type (as allowed by the challenge rules). For a more-general version that can accept argments of different types, exchange `c` for `list` (at the cost of an [extra 3 bytes](https://tio.run/##XZDRbsMgDEWfy1egVJpwxTIt2lPbfElVTYRAi9qyCMiWaMq3Zw5hybQHsI@5urZxY2tl61xfjhqzYD4s07CkeZ6DU5/Mi6a59@xufIg1vigE6OPxWWMEOJ1ez@dxSwWdLI2q6a8sFnpNv0y40ofp8MkHZ@yFPlHbPpQzkgp3wcwGT2Zx@afHN9ksVE20ooy4cj3zpiuLXXXo8a4jN8IHxbCrUw0TvHspgCeSvEeCSTaQeAYykC2VVyVv@zQOy0QGrACWVRjfgKAg/V3abk9mxsXf0wpJwGaE1fO/cnLnBUdvjtbjDw)). --- # [R](https://www.r-project.org/), ~~65~~ 61 bytes *Edit: -5 bytes thanks to Giuseppe* ``` g=function(f)function(a,...)`if`(nargs()>1,g(f(a))(...),f(a)) ``` [Try it online!](https://tio.run/##dZDRCoMgGIWv8ymEbs6/JKh2NWivssyyYtDALUaMnt1ZuRqDXQjn8z8ejxo79GowZsxtk2unH92th6ZNShHHMRWdLtBL09xB50Q00JBEmEdikTbkks9BXV3xz@FlY9SCP9va1J6cGyVBESriOYeMSjpARRWx1bDXkPRiwUblTDuqBXeuVg6@Ax1ObFkTm1jIVVur68nfg4SQEjLCkZgb@o/wNU9sZfeei@/lDViR9rxfJxKRiky42L8T@wY "R – Try It Online") Alternative recursive version: shorter, easier to understand, and without horrible scoping hacks. Heavily based on comment by ASCII-only, and made nicer (as well as even shorter) by Giuseppe. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` f=g=>(x,...a)=>a.length?f(g(x))(...a):g(x) ``` [Try it online!](https://tio.run/##HctNDkAwEEDhq1jORM0GGzJ1llFtkaYVRNy@fnYvX/JWueQw@7KdVUyTzdmxZw23IiJB1kLBRn/OgwMPNyL83n2dTYpHCpZC8uBAWI@szbuUY2kQalU0qmgR@/wA "JavaScript (Node.js) – Try It Online") Resulting function assumes that you give it the correct number of arguments. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~27~~ ~~25~~ 24 bytes -3 bytes thanks to [vrintle](https://codegolf.stackexchange.com/users/83605/vrintle) ``` ->f{->a{a.inject f,:[]}} ``` [Try it online!](https://tio.run/##bYq7CoQwEEV7vyKlWRPBR6UkPzJMkcQNaBFEnEJCvj0723vhwH1d5J9Kpmobs7Yuu35PxzfcIqoFsJQaKZn/oK1nArPl1nVeftrQbbKwmlPwCwaEEWFCmHFtKAVDwDX7U3ACGNSoJjXjW1N/ "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~60~~ ~~58~~ 51 bytes -2 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen). Nicer form thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) ``` function(f)function(a)Reduce(function(f,a)f(a),a,f) ``` [Try it online!](https://tio.run/##fY9NCsMgEIXX8RRCNjONm/ysArlEL1DMqDQUUpBKKSVntybaGLroQpjvzfPNjPVu8MbN9JjuMxjcS4lnrRxpyE0h0QRdSGHQl1xyctZOWvGvZRNeRvDnVVudKPyAEYEQFPKBg6xGPAFVClk0DIeZb1bsNK6UkTbMrCIXx8CAC9vewhZWcrpquvVpDtQIDUKL0CELzRC06mnNnkUO91zSXg5igTnp1wMEtWhEKzrE/03/AQ "R – Try It Online") [Answer] # [Common Lisp](http://www.clisp.org/), ~~54~~ 48 bytes ``` (lambda(f)(lambda(a)(reduce'funcall(cons f a)))) ``` [Try it online!](https://tio.run/##lY5NCoMwEIX3nuIhFGfqSu0FepQxMVCI2hqz9eoxqVrctNDZzAfzfkbZh3sGct38gg9kpW@1kOGDhGnqtFddYfygxFpS4@BgIBwncLZZ4/Hk2Kll7AhSJ9aRr6ASgiQpoaB5m4zMOPUyo5iRL/flkoOO4i87daNi1IyGcePjpXj9eOGT6mf8W19QhRpNSvlLG1Y "Common Lisp – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [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 taking the name of a Curried function as right argument, and returning the source of the un-Curried function. ``` ⎕NR⊃⍨4-2⍳⍨183⌶ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qsKteqLOvi/qjtglJ@RUK@Xnqj7oWp@YlJuWkBjv6hAA5QEXOkerFiTkl6iANfkGPupof9a4w0TV61LsZyDC0MH7Us@1/GtCER719YMk1j3q3HFpv/KhtIsiGIGcgGeLhGfw/HajG9FHHjOpHvbu0H/VureVKU09X58oACmtoP@rZf3j7o85FmkAFhkCJDHWuRx3tCkVAyQqFkKLEFLc8hUouBbCAkXbF4emG2pUgFVyZQAETI6AuiCKg1kx1AA "APL (Dyalog Unicode) – Try It Online") For example, with the function `f ← (~,∩)∘' '`, which consists of the function `~,∩` with a space character as curried right-argument, passing the name `"f"` gives: `183⌶` explain representation; a structure identical to the structure of the target function, but with integers indicating the name class of the components  `[[3,3,3],4,2]` (3 is function, 4 is higher-order function, 2 is array) `2⍳⍨` index of `2`  `3` `4-` subtract that from 4  `1` …`⊃⍨` use that index to pick from:  `⎕NR` the Nested Representation, `["~,∩","∘"," "]` This picks out our result, `"~,∩"`. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 11 bytes ``` Fold&:`!##V ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBlq/DfLT8nRc0qQVFZOex/cmlRUWVIanEJSCa6IlZB106hWiG6EsqoUNBWMFLQUqhUqFWo5eIKKMrMK4mG64k2jo02jY1VgAJ7ewVDY5iiNIQyHQVjHQWYOqCixJzifKDK/wA "Attache – Try It Online") Anonymous function that takes input like `f[curried, a1, a2, ..., aN]`. ## Explanation With some more whitespace: ``` (Fold&:`!) ## V ``` `V` is a function that converts its arguments into a list. `V[1, 2, 3]` yields `[1, 2, 3]`. `Fold` is given the execute operation `!` as a function (``!`) for its first argument, via `f&:n`. `##` composes these two functions. [Answer] # [Java (JDK)](http://jdk.java.net/), 81 bytes (-9 bytes thanks to user. -2 bytes after removing curly braces from for loop.) ``` f->a->{var g=f;for(int i:a)g=((java.util.function.Function)g).apply(i);return g;} ``` [Try it online!](https://tio.run/##jZCxboQwDIbn4yk8kh4gtd1KQepSqUPV4bqdbjAQ0tAQUDCcEOLZabiGtkOH8@DEvyz7@13hgGFVfC6ybhtDUNk66kmqqOx1TrLR0U3sebnCroNXlBomD2x0hCRzeHZNj29ZxXMKfgWp6XgK4FtPU7B6b8wIyVKGKYbpNKABkZRx2RjfNoN8QCYS3/@HYBvKBIuwbdXoSxYbTr3RIOJ52VnCXdtnyhI5sKGRBdSW1z@QkVocT5fqyYiOAX2Y5tzB@/pgprjztMWPhxdNXHATXKW4T2q9YlFAAghhCtma8jUh7G21h9zC/t12GDviddT0FLWWlJT23a2cVztts635GS6HnW4DuAvgfmYs9nazNy9f "Java (JDK) – Try It Online") Accepts an arbitrary depth `Function<Integer, ?>` where `?` is either `Integer` or `Function<Integer, ?>`, and returns a `Function<int[], Object>`. I can't really find rules on Java submissions. I tried to mostly follow the format for what counts as the header and what the code body has to look like from an answer on the [inspiration](https://codegolf.stackexchange.com/questions/162231/make-me-some-curry) for this question. Let me know if I got anything wrong [Answer] # [R](https://www.r-project.org/), 56 bytes ``` g=function(f)function(a,...)`if`(nargs(),g(f(a))(...),f) ``` [Try it online!](https://tio.run/##dZDNCoMwEITP5ikCXmZqEPpzEnyWNkZjpWAhrZRSfHYbNdVS6CGwX2Z2dhM3dK3pnHvmQ51bX9@bawvLpdQqTVOeGntCq119A1UNC01iFJTlEEstx4ymKuWnb7p4WiUf58pVgXwXCsIQJWUuoZOCG5ikpJgN6waaLxEtVIy0oplw5XLm6DvQYy@m04texNKcK3PJwhxsiR2xJw4UXgx/ENbMxMz@PcewVzBgRq55v05s1U7tlY/9qwxv "R – Try It Online") Credit to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) and [ASCII-only](https://codegolf.stackexchange.com/a/216960/67312) for a decent part of this, so please upvote their submissions as well. The `...` aka [dots](https://stat.ethz.ch/R-manual/R-devel/library/base/html/dots.html) is a special R construct for functions with arbitrary number of inputs. [Answer] # [Julia](http://julialang.org/), 22 bytes ``` !f=x->foldl(map,[f;x]) ``` `g = !f` will expect an array [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHNtkLXLi0/JyVHIzexQCc6zboiVvN/moKtAlC8UteuStdOoULb0KASiA2quNKBEoppXFwOxRn55QppGoaaGkaaGsaaUIF0jWhDHSMd41hNrv8A "Julia 1.0 – Try It Online") [Answer] # [PHP](https://php.net/), 84 bytes ``` function u($f){return function($a,...$b)use($f){return$b?u($f($a))(...$b):$f($a);};} ``` [Try it online!](https://tio.run/##jY5BCoMwEEX3nkIk4EwNAbUr0@JFuqlWqZs0pMmqeHY7g1oLdlECIZn3/mfs3U6n2tLdB9P64WHiAKLHl@t8cCZepyCuUiklGgzP7ksQTc0@YUSYhWr@6lGPWyk9eLivXQp/oXZBkqQ9vW1UkroKNMnIP1A8I4e34BMJCp4DpFSQoo6sG4wH3ipHKBBKhCOq5GKSD@QE5LKQpfwHTW8 "PHP – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 54 bytes ``` sub f($n,$g){--$n?sub($p,@p){&{f($n,&$g($p))}(@p)}:$g} ``` [Try it online!](https://tio.run/##XY1BCsIwEEX3niLIEDKYYEW6sRR7AW8gSFvatKBpaNqFhFzdOLag4GKG@f8//thmvKcxurlirQAjQaNXCsyZHAFWFhY990vEQZODGASZ4QQ6ROhy4vzjyQSUmBe3jH119afrVUOpoNpDHULINnbszcQ4feDQiUOSUHm6LGRyezXbH9KKo4SOIqIkSz@DKxJfg536wbioLm1TTvPY7FyvzXK5Nw "Perl 5 – Try It Online") Parameter `$n` is the number of arguments to uncurry, `$g` is the input function which has to be uncurried. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 189 bytes ``` #define T template T<class F>struct U{F f;auto operator()(){return f;}T<class A,class...B>auto operator()(A a,B...b){return U<decltype(f(a))>{f(a)}(b...);}};T<class F>U<F>u(F f){return{f};} ``` [Try it online!](https://tio.run/##fY5BasMwEEX3OsVAFpFa15RkF6mGZOETxKu0FFmWi8CWjTxaFKOzu3IaN3UXBcGg/98MT/X904dS07SpdG2shjOgbvtGoiZnoRo5DJBnAzqvEIoxh5pLjx10vXYSO0cZZaPT6J2NVVhWjsl1pml6yv7yR5DJKTblz2IhKq0a/Ow1ralkLBvnEWgZKcZD4HeTQuSZp1FjWR7rwMO0MVY1vtIgTBdltWwzQoxFaKWxlMFIAK4eyjtndPVeW3iByxudGRl7uKlc5HdW/srk4@6h5BDmt9zxdnXJ0/uXzdCA1eGgOo8gxAqmuwT2bE63r3b7P7pPYLdCb0LPnAQyfQE "C++ (gcc) – Try It Online") Function `u` takes in a curried callable object, and returns another callable object which is uncurried. (I don't see any allowance for a restriction on the return type of the curried function, just on the argument types. If it were allowed, we could save two bytes by replacing both instances of `auto` with `int`.) ]
[Question] [ # Code Golf Measurer © 2019 Hexdumps used with `xxd` look something like this: ``` 00000000: 666f 6f20 6261 7220 7370 616d 2065 6767 foo bar spam egg 00000010: 730a s. ``` Your task is to convert a hexdump in this form in to the number of bytes used. ## Rules: * Usual loopholes forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest valid answer in bytes wins. * You may or may not include the newline at the end of text (`0a`). This means that if the hexdump ends in a newline (`0a`), that input may have it's output reduced by one. * An empty input (literally nothing: empty list/string/etc.) must output 0. * Input can be taken in any form * Input will be valid ASCII with no control characters * The input must contain the whole hexdump ## Test cases: ``` 00000000: 4865 6c6c 6f2c 2077 6f72 6c64 2120 4865 Hello, world! He 00000010: 6c6c 6f2c 2077 6f72 6c64 210a llo, world!. ``` returns 28 or 27 ``` 00000000: 0a . ``` returns 1 or 0 ``` 00000000: 6368 616c 6c65 6e67 650a challenge. ``` returns 10 or 9 ``` 00000000: 4865 6c6c 6f2c 2077 6f72 6c64 21 Hello, world! ``` returns 13 ``` ``` returns 0 *(This is literally nothing: empty list/string/etc.)* Explanations would be nice for non-standard languages. [Answer] # [tcsh](http://www.tcsh.org/), 12 bytes ``` xxd -r|wc -c ``` [Try it online!](https://tio.run/##K0kuzvj/v6IiRUG3qKY8WUE3@f9/AyiwUjAzNrNQMDM0S1YwSzYzVTBLNTNXMDM1SFRAB8kZiTk5qXnpqXoA "tcsh – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 8 bytes ``` .{51} . ``` [Try it online!](https://tio.run/##K0otycxL/P9fr9rUsJaLS@//fwMosFIwsTAzVTBLNktWMEszSlYwMjA3B7LMjUBiJgpGhkYGECUKHqk5Ofk6CuX5RTkpikAeF8QEQ6AZeLQbJCogASQT9AA "Retina 0.8.2 – Try It Online") Explanation: ``` .{51} ``` Delete the first 51 characters of each line. (Lines can only have between 52 and 67 characters, so this always matches once per line.) ``` . ``` Count the remaining non-newline characters. 7 bytes if empty input did not have to be supported: ``` .{52} ``` [Try it online!](https://tio.run/##K0otycxL/P9fr9rUqJaL6/9/AyiwUjCxMDNVMEs2S1YwSzNKVjAyMDcHssyNQGImCkaGRgYQJQoeqTk5@ToK5flFOSmKQB4XxARDoBl4tBskKiABJBP0AA "Retina 0.8.2 – Try It Online") Explanation: ``` .{52} ``` Delete the first 52 characters of each line. (Lines can only have between 52 and 67 characters, so this always matches once per line.) ``` ``` Count 1 more than the number of remaining characters (including newlines). [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 7 bytes ``` Î51x Ø. ``` [Try it online!](https://tio.run/##K/v//3CfqWEF1@EZev//G0CBlYKJhZmpglmyWbKCWZpRsoKRgbk5kGVuBBIzUTAyNDKAKFHwSM3JyddRKM8vyklRBPK4ICYYAs3Ao90gUQEJIJmgBwA "V (vim) – Try It Online") Explanation: ``` Î " On every line... 51x " Delete the first 51 characters Ø. " Count the number of remaining characters on any line ``` Hexdump: ``` 00000000: ce35 3178 0dd8 2e .51x... ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 7 bytes This counts the total number of single-line strings of length 52. It might be possible to do something similar to `%52,`.`, but I failed to find a way to fix that. ``` w`.{52} ``` [Try it online!](https://tio.run/##K0otycxLNPz/vzxBr9rUqPb/fwMosFIwsTAzVTBLNktWMEszSlYwMjA3B7LMjUBiJgpGhgow4JGak5Ovo1CeX5STosgFAA "Retina – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 18 bytes Full program. Prompts for list of strings (i.e. of lists of characters). ``` 2÷⍨≢∊(1↓≠⊆⊢)¨49↑¨⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L/R4e2Pelc86lz0qKNLw/BR2@RHnQsedbU96lqkeWiFieWjtomHVjzqmwpS/F8BDAq41A2gwErBxMLMVMEs2SxZwSzNKFnByMDcHMgyNwKJmSgYGRoZQJQoeKTm5OTrKJTnF@WkKAJ56gpQUwyBpuAxwCBRAQkgmaGnzgVzz6OuJiQnoerAA3CaYGZsZqFgZghyUzLIe6lmQDeZYjE3OSMxJyc1Lz0Vp1GEwgduFEr4IEwzeNS7BWSiOgA "APL (Dyalog Extended) – Try It Online") `⎕` prompt `49↑¨` take the first 49 characters from each `(`…`)¨` apply the following tacit function to each:  `⊢` the argument  `⊆` chop into runs of characters that are  `≠` different from the padding character (space)  `1↓` drop the first "word" `∊` **ϵ**nlist (flatten) `≢` tally `2÷⍨` divide by two [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~64~~ ~~55~~ ~~45~~ 39 bytes ``` s[];f(l){l=gets(s)?strlen(s)-51+f():0;} ``` [Try it online!](https://tio.run/##fYy9DoIwHMRn@xR/MSZtBFIaKAb8WH0HdSCFYpNaDK1xIDw71uDg5E13l7ufiFohpsmer6XEmgx63zbOYkuO1vW6Md5FWbKRmBS0HKeVMkI/6wZ21tWqi28HhJRxcK@UwQQGtHj0PkscrOuLCULwR1KicaJfFZBueQZccAFcMgGM5rl3Oft0KbCE0XkCp0brLoRX1@t66ROaCYln/LnTCn70Q4jf "C (gcc) – Try It Online") 9 bytes shaved off thanks to YSC, 10 thanks to jdt, and 6 thanks to c--! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ẉ_51S ``` A monadic Link accepting a list of lines which yield the integer byte count. **[Try it online!](https://tio.run/##y0rNyan8///hro54U8Pg////R6sbQIGVgpmZWZqCWZqRgYKZkZmhgrkRkGVubA7kGpqlKBgZmJkqmJmbmSsopOXnKyQlFikUFyTmKqSmp6tz6UCNMQQaY25skKhADCjWU48FAA "Jelly – Try It Online")** ### How? ``` Ẉ_51S - Link: list of lists of characters, H Ẉ - length of each (line in H) 51 - literal fifty-one _ - subtract (vectorises) S - sum ``` [Answer] # Python 3, 48 46 bytes ``` lambda s:(len(s)or 51)+1-52*len(s.split('\n')) ``` Input is passed as a string to the function. The function increments the length of the input (including newlines), then subtracts 52 for each line. [Try it online](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSiMnNU@jWDO/SMHUUFPbUNfUSAssoldckJNZoqEek6euqfm/oCgzr0QjTUMdDIACAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Input as an array of lines. ``` ®Ê-51 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=rsotNTE&input=WyIwMDAwMDAwMDogNDg2NSA2YzZjIDZmMmMgMjA3NyA2ZjcyIDZjNjQgMjEyMCA0ODY1ICBIZWxsbywgd29ybGQhIEhlIiwiMDAwMDAwMTA6IDZjNmMgNmYyYyAyMDc3IDZmNzIgNmM2NCAyMTBhICAgICAgICAgICAgbGxvLCB3b3JsZCEuIl0) ``` ®Ê-51 :Implicit input of array ® :Map Ê : Length -51 : Subtract 51 :Implicit output of sum of resulting array ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes ``` {.join.comb-51*$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wi8rPzNPLzk/N0nX1FBLJb72vzVXcWKlQpqCg0ZOZl5qseZ/AyiwUjCxMDNVMEs2S1YwSzNKVjAyMDcHssyNQGImCkaGRgYQJQoeqTk5@ToK5flFOSmKQB4XxARDoBl4tBskKiABJBP0AA "Perl 6 – Try It Online") Anonymous Whatever lambda that takes a list of lines and returns the sum of the number of characters, subtracting 51 for each line [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes ``` €g51-O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UdOadFNDXf///6OVDKDASsHEwsxUwSzZLFnBLM0oWcHIwNwcyDI3AomZKBgZGhlAlCh4pObk5OsolOcX5aQoAnlKOlBTDIGm4DHAIFEBCSCZoacUCwA "05AB1E – Try It Online") Input as a list of strings. ``` €g get lengths of each line 51- subtract 51 from each O push the sum of the resulting list implicitly print ``` [Answer] # IBM/Lotus Notes Formula Language, 53 bytes ``` @Sum(@Length(@Explode(@Right(@Left(i;" ");": ")))/2) ``` There is no TIO for Formula so here are screenshots of the test cases: [![enter image description here](https://i.stack.imgur.com/aWsyt.png)](https://i.stack.imgur.com/aWsyt.png) [![enter image description here](https://i.stack.imgur.com/GDpSY.png)](https://i.stack.imgur.com/GDpSY.png) [![enter image description here](https://i.stack.imgur.com/lt6DE.png)](https://i.stack.imgur.com/lt6DE.png) [![enter image description here](https://i.stack.imgur.com/NhurB.png)](https://i.stack.imgur.com/NhurB.png) [![enter image description here](https://i.stack.imgur.com/MFXe0.png)](https://i.stack.imgur.com/MFXe0.png) The formula is in the computed field that provides the value after "Returns". **Explanation** This is a good demonstration of the way that Formula will recursively apply a function to a list without needing a loop. The formula is in a computed field on the same form as editable input field `i'. 1. Start in the middle. `@Left` and `@Right` allow a string delimiter or a number of characters to be used. We therefore search to the right of `:` and then to the left of the first occurrence of two spaces. Since Formula sees the newline as a list separator it will apply this to each line in the input. 2. `@Explode` is Formula's equivalent of a `split` function and defaults to space, `,` or `;`. Again it is applied to each line in the field but this time the results are combined into a single list. 3. `@Length` will then be applied to each member of the list. In each case we divide it's return value by 2. 4. `@Sum` the whole list and output the result. [Answer] # JavaScript (ES6), 34 bytes ``` s=>(n=s.length)&&(n/68<<4)+n%68-51 ``` [Try it online!](https://tio.run/##hZDBDoIwEETvfMV6EEoQhApLY8CzH@GF1AKapjVA9PORRqOQKMypnbRvZ@da3IuWN5db5yt9Fn2Z921@ICpvAylU1dWubRO1RZZlseupNTI/iXquVaulCKSuSEksACd8aw8xwwSQIwcsKQcapulwSqnxYqARDV9P4Cik1Bt46EaeV8PtpBzwvqxoYM1gwgJGGpECx3Jday7h9OuMllG4QwYYmZTcrC1wSJn8GMDrQppCxTJzqcAPc1LgH6yx@yc "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string (n = s.length) && // n = length of s; return 0 right away if n = 0 (special case) (n / 68 << 4) + // otherwise compute the number of full lines and multiply it by 16 n % 68 - 51 // add the length of the last line minus 51 ``` [Answer] # [Red](http://www.red-lang.org), ~~81~~ 55 bytes ``` func[s][n: 0 foreach l s[n: n - 51 + length? l]max 0 n] ``` [Try it online!](https://tio.run/##nZA/D4IwEMV3PsWT1T8pFQphcXV2bTo0pRWTWgxg9NtjG4mBRBl8093l7pd3r9XVcNIVF5EpMZi7U7wT3JUgME2rpaph0YWBwxZZgjWsdue@PsCKq3z6PSeGW3txPQx4TEaVSAuWgSmmwAxVoCTPfZXTMEtBE0reKzhqa5sNHk1rq5XvYoyUxFMWAERiogljF4vom6P5wYJ@AdieFWBJcKTCc5p5R9kXrKqlDTFpT0L0Tzof1Cydma9YDC8 "Red – Try It Online") Takes the input as a list of strings. [Answer] # JavaScript, ~~33~~ 32 bytes ``` a=>a.map(x=>a=~~a+x.length-51)|a ``` [Try it Online!](https://tio.run/##fYxBDoIwFESv8mVVIjSlgdaY1LV3MC5@SkFJbQkQZWG4eq2RBStn9WYyeR0@cdTDvZ9y52sTGhVQnZA@sCdzBLUsuJ@pNa6dbnlVpG8M2rvRW0Otb0lDLglbc4TyICoQWmgQDdfAmZSRJP9uJfCCs98FzsZan8HLD7bexZZkq6WIlj8ChrDJxkGTa5qGDw) Saved 1 byte thanks to Arnauld. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~39~~ ~~29~~ 28 bytes -10 bytes thanks to [south](https://codegolf.stackexchange.com/users/110888/south) -1 byte thanks to [Sʨɠɠan](https://codegolf.stackexchange.com/users/92689/s%ca%a8%c9%a0%c9%a0an) ``` p$<.sum{_1=~/.{52}/;$'.size} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6OUuyCpaUlaboWewpUbPSKS3Or4w1t6_T1qk2NavWtVdT1ijOrUmshSqAqF9xsNoACKwUTCzNTBbNks2QFszSjZAUjA3NzIMvcCCRmomBkaGQAUaLgkZqTk6-jUJ5flJOiCORxQUwwBJqBR7tBogISQDJBD-IWAA) [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 16 bytes ``` "c- cw|r- dxx"=@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/XylZVyG5vKZIVyGlokLJ1uH/fwMosFIwMzazUDAzNEtWMEs2M1UwSzUzVzAzNUhUQAfJGYk5OalAI/UA "Befunge-98 (FBBI) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ôφß→ê ``` [Run and debug it](https://staxlang.xyz/#p=93ede11a88&i=00000000%3A+4865+6c6c+6f2c+2077+6f72+6c64+2120+4865++Hello,+world%21+He%0A00000010%3A+6c6c+6f2c+2077+6f72+6c64+210a++++++++++++llo,+world%21.%0A%0A00000000%3A+0a+++++++++++++++++++++++++++++++++++++++.%0A%0A00000000%3A+6368+616c+6c65+6e67+650a+++++++++++++++++challenge.%0A%0A00000000%3A+4865+6c6c+6f2c+2077+6f72+6c64+21+++++++++Hello,+world%21&a=1&m=1) [Answer] # [Zsh](https://www.zsh.org/), 36 bytes With zsh's default flags: ``` for l (${(f)1})((c+=$#l-52)) <<<$[c] ``` [Try it online!](https://tio.run/##fY/BCsIwDIbvfYqIg7Woo61bNmTefQfxMGq7HYKDeRAUn722THCK7D@EJPz5@HO/dt5xwb3rByDgyYM7oZ6Cc7PaJ0vaFFoIVtd1cjQnLxhzkMq3dpBXWAAaNIBOG9CyLENX6rjLQSstRwscLFG/hls/0HkRJjYSVGDMnMsGJpoQMpbGIGP9xPn2zyj7vcQtVoAqJjHxJYshSfGHZ7qGyF5aGxD@BQ "Zsh – Try It Online") `${(f)1}` splits `$1` on newlines, and discards empty lines. The `$[ arithmetic expansion ]` guards against the empty case, when the loop never sets `$c`. # [Zsh](https://www.zsh.org/), 28 bytes With `-o extendedglob`: ``` <<<${#${(F)${(f)1}#?(#c52)}} ``` [Try it online!](https://tio.run/##fY/RCoIwFIbv9xQnFNwgZFs5JYTuotewuenFcJFCkfjsa8Mgi/C/@DnncM7Hf5596zQm2JVlGY9RPOIT8aYJm6IjjmTGyTQ5gno12OsA6jGorlZ1Y@wFIQ0JfesA@0JkIKSQIDSXwGme@yrnYbYHzjidV@CsjLFbuNubqTe@QzOBecbKOa1goQUhRUkIMvsnzvf@itLfS7ETBQgWksjwkhI@SfaHJ9vKGNU1yiPcCw "Zsh – Try It Online") `(f)` Split on newlines, `${ #?(#c52)}` remove leading 52 characters, `(F)` join on newlines so that counting is characterwise instead of listwise, `${# }` count characters. [Answer] # [asm2bf](https://github.com/KrzysztofSzewczyk/asmbf), 135 bytes Golfed version: ``` lbl 3 mov r2,51 lbl 1 in_ r1 dec r2 jz_ r1,4 jnz r2,1 lbl 2 in_ r1 jz_ r1,4 sub r1,10 jz_ r1,3 inc r3 jmp 2 lbl 4 out r3 ``` Commented version: ``` lbl 3 ; Main loop - the kinda entry point mov r2, 51 ; Loop 51 times. lbl 1 ; Loop start. in_ r1 ; Read character dec r2 ; Decrement the loop accumulator. jz_ r1, 4 ; If zero was read, end. jnz r2, 1 ; If we still loop, loop again. lbl 2 ; Second loop, accumulating the result. in_ r1 ; Read a character. jz_ r1, 4 ; If character is zero, end the loop and print result. sub r1, 10 ; Decrement r1 by 10 for next check. jz_ r1, 3 ; If the character - 10 (the newline) is zero, jump to 3 inc r3 ; Increment character read amount. jmp 2 lbl 4 out r3 ; Print out the result as an ASCII character. ``` [Answer] # [PHP](https://www.php.net), 22 bytes ``` fn()=>strlen(`xxd -r`) ``` Doesn't work on ATO unfortunatly ]
[Question] [ [Desmos](https://desmos.com/calculator) is mainly used as an online graphing calculator, but its graphical and mathematical functionalities can also be applied in certain coding challenges. I know not that many people use Desmos on this site, but for the people that do, what are some tips for golfing in Desmos? As usual, please keep the tips somewhat specific to Desmos, and one tip per answer. [Answer] (This is mainly a \$\LaTeX\$ trick that can save some bytes. This tip can likely apply to other languages that use \$\LaTeX\$.) When dealing with exponents(e.g. `x^{2}`) or other operators that require the usage of brackets(e.g. `\sqrt{5}`), you can take out the brackets that are automatically there if there is only one digit/character in the exponent. So, `x^{2}` can be written as `x^2`. Likewise, `\sqrt{5}` can be shortened to `\sqrt5`. Note that you cannot take out these brackets if there is more than one digit. For example, `x^{10}` is not the same as `x^10`. --- This exponent trick can even work in summations, where it uses the same notation when indicating the stopping value. For example, instead of writing... ``` \sum_{k=0}^{n}k^{3} ``` ...it can be written as: ``` \sum_{k=0}^nk^3 ``` --- Because if this trick, it is better if you can find a way to maximize the amount of one digit exponential terms in your code, to eliminate the brackets. For example, it is actually more byte efficient to write `a^xa^y` (6 bytes) instead of `a^{x+y}` (7 bytes). [Answer] # You can use / Pasting in `x/5` or `8/3` will give the same result as typing it, just not properly formatted - so in some cases, you don't need the bulky `\frac{x}{y}`. [Answer] ## Parentheses are not always required for trig functions For example, `tan35.6x=0` is valid and treated as `tan(35.6x)=0`. Similarly, `tan^23x` is treated as `tan^{2}(3x)`. [Answer] ### Edit #2: (Referring to the example in the first edit) Apparently you can add a `\` at the beginning of the function to make it work(see [this comment](https://codegolf.stackexchange.com/questions/230100/tips-for-code-golfing-in-desmos#comment528244_230101)), which I did not know as well. I guess that invalidates this tip, again. ### Edit: In [fireflame241's comment](https://codegolf.stackexchange.com/questions/230100/tips-for-code-golfing-in-desmos/230101#comment528123_230101), he brought to my attention that it is not required to have the `\left` and `\right` accompanying the bracket pairs. This is true for most cases. But after some testing, there are some cases where taking out the `\left` and `\right` does break the code. Specifically, if you are using any function(e.g. `total` or `max`) in addition to these brackets, the function will not work(see example below). Example: Suppose you want to compare the corresponding elements of two lists, `a` and `b`, and see how many of those corresponding elements are the same. That is, something like `a=[1,2,3,4]` and `b=[2,2,3,5]` will output `2`(the second and third elements of each list are the same). Here's what someone might do, after learning that you can take out the `\left` and `\right`: ``` total(\{a=b:1,0\}) ``` In theory, this should work perfectly fine, but in reality, Desmos gives an error and it doesn't work. I'm pretty sure it's because it considers `l` to be a function, and `t`, `o`, and `a` to be variables in this situation. `l`, `o`, and `t` are not defined, so it gives an error saying so. In cases like this, it would be better to do: ``` total(1-sign(a-b)^2) ``` as suggested by the tip below. --- First tip to start it off. When doing comparisons in your code, most of the times, it is better to try not to use brackets `{ }` in your code, because they always require a `\left` and a `\right` to go with them, which increases byte count unnecessarily. Instead, we can utilize the `sign` function. Consider a naive implementation that returns `0` if `a=b`, and returns `1` otherwise: (22 bytes) ``` \left\{a=b:0,1\right\} ``` Instead of doing this, we can save 9 bytes by doing a little math instead: (11 bytes) ``` sign(a-b)^2 ``` This works because `sign(x)` returns `-1` if `x` is negative, `0` if `x=0`, and `1` otherwise. `a-b` is `0` only when `a=b`, so `sign(a-b)` would be `0` only when `a=b`. If `a` does not equal `b`, it returns either `-1` or `1`. The `^2` is just to convert the `-1` to a `1`. Even if we wanted to return `1` if `a=b` and `0` otherwise, we can still save 9 bytes by doing `1-sign(a-b)^2` instead of `\left\{a=b:1,0\right\}`. [Answer] ### Change `\prod` to `∏` and `\sum` to `∑` `\prod` can be replaced with `∏`, saving 2 bytes, and `\sum` with `∑` to save 1 byte. Important to note that these are not capital pi `Π` or capital sigma `Σ`, but their own distinct characters. Similarly, `\to` can be replaced with `→`, but this loses a byte to `->`. in either case (`→` or `->`), you can omit the next `\` from a function. Example: `x\to\join(x,y)` => `x->join(x,y)` saves 2 bytes. (special thanks to [@Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow) for the correction about `->`) [Answer] # Logical negation If you want to swap numbers that represent falsy and truthy values, you can use `0^x`, where `x` is the value that needs to be logically negated. To make it work for negative numbers, you can use the absolute value (`0^{abs(x)}`), suggested by Aiden Chow. [Answer] You can use function parameters to assign variable values outside of that function, even though it throws an error. Using this, we can save bytes when we repeat expressions inside of functions. For example, look at this code: (45 bytes) ``` f(a)=sort(a)[1]+sort(a)[length(a)]-sort(a)[2] ``` There is a lot of `sort(a)`'s in that code, maybe we can shorten it? Here is what many people might try to do to shorten this: (49 bytes) ``` b(a)=sort(a) f(a)=b(a)[1]+b(a)[length(a)]-b(a)[2] ``` It seems like making a function just for `sort(a)` should have helped, but in reality this is actually 4 bytes longer than the initial code. What can we do then? Well, the following code will do it: (37 bytes) ``` b=sort(a) f(a)=b[1]+b[length(a)]-b[2] ``` `b` is using a function parameter `a` in declaring it, and Desmos is throwing an error because it seemingly doesn't understand this, but at the end, it still works somehow, so it is valid. [Answer] Here's a cool piecewise trick. When writing piecewise expressions in the form `\{(condition):1,n\}` for some value `n`, you can actually replace them with `\{(condition),n\}`, saving 2 bytes. I'm not aware of the full details on why this works, but the premise is that with any piecewise in the form `\{(condition)\}`, like `\{x>0\}`, if the `(condition)` is true, then it will return 1, otherwise, it will return `undefined` (if you are wondering why these values, it is because piecewise expressions are also used in domain/range restrictions). Notice how there is no `true` or `false` output in these type of piecewise experssions. This is because 1 and `undefined` are the "default" values when the `true` and/or `false` output is omitted. When writing `\{(condition),n\}`, you are omitting the `true` output, which means that it will default to 1, so it is essentially the same as `\{(condition):1,n\}`. [Answer] For functions that use `\operatorname{(function name)}`, you can simply take out the entire `\operatorname` part and use the `(function name)`. For example, instead of `\operatorname{total}`, you can simply write `total`. [Answer] # Use the dot calls of built-in functions For most list built-ins that don't require any arguments, they can be called using dot calls instead. Let's say that the built-in function is called `f`, and the list is `L`. You can then use a dot call to use the function like `L.f` (3 bytes) instead of `f(L)` (4 bytes), which saves 1 byte. For example, instead of using `mean(L)`, you can instead use `L.mean` for -1 bytes. Here is some [examples](https://www.desmos.com/calculator/9pgqulab1u) of dot calls being used on a list, and you can find a full list of the built-in functions that allow for dot calls [here](https://www.desmos.com/calculator/rlr1sstwye) (Find the folder that is named "Functions that allow dot call"). Note that the full list does put parentheses `()` after the dot call (like `L.mean()`), but that can be taken out (`L.mean` works). [Answer] # Regressions A regression can be used to solve an equation and can be shorter than explicitly typing out the expression for its solution. For example, the golden ratio can be calculated in 6 bytes, `aa-a~1`, with the result being stored in `a`, which is shorter than the 11-byte equivalent `5^{.5}.5+.5`. [Answer] When constructing a list with `...`, commas can usually be eliminated. For example, one might write `[0,...,9]` if they did not know about this, but you can actually save 2 bytes by writing `[0...9]` instead. In cases where you want to specify the second element(to set your own common difference), the comma is only required between the first and second element. For example, instead of `[0,2,...,50]`, you can write `[0,2...50]` instead. Basically, you can replace `,...,` with `...` to save 2 bytes. [Answer] ### List comprehension tips If you are unaware, a new feature has been released in Desmos a few months ago: [list comprehensions](https://twitter.com/Desmos/status/1451211022115561476) They are similar to Python list comprehensions, where you can essentially use loops to construct lists. This functionality now allows us to be able to emulate nested for loops in Desmos, which was previously much harder to do. List comprehensions follow the below form: ``` [(expression in terms of var1, ... ,varN) for var1 = (list1), var2 = (list2), ... , varN = (listN)] ``` This will construct a list by looping through each `var1, var2, ... , varN` in a nested fashion. There are some golfs you can do to save bytes in list comprehensions. Let's take a simple list comprehension below: ``` \left[\left(a,b\right)\operatorname{for}a=\left[1...10\right],b=\left[1...10\right]\right] ``` Like any other function, you can simply take out the `\operatorname` from the `for` and it will still work. So all in all, you have something like this: ``` [(a,b)fora=[1...10],b=[1...10]] ``` Even though the `for` and `a` are together, Desmos will still be able to distinguish between them. --- A quirk with list comprehensions (and nested for loops in general) is that you will actually get different lists based on the order of each list. Here's an example to illustrate my point (obviously not golfed completely for readability): ``` [a+b for a = [1,2,3], b = [2,4,6]] --> [3,4,5,5,6,7,7,8,9] [a+b for a = [2,4,6], b = [1,2,3]] --> [3,5,7,4,6,8,5,7,9] ``` ([Graph](https://www.desmos.com/calculator/er964mmn4n)) Generally, a list comprehension is generated following the pseudocode below (using the general list comprehension form that I mentioned earlier): ``` SET result to empty list FOR each varN in (listN) . . . FOR each var2 in (list2) FOR each var1 in (list1) ADD (expression in terms of var1, ... , varN) to the end of result END FOR END FOR . . . END FOR PRINT result ``` A certain ordering of the lists can potentially save a few bytes over another if a code golf challenge requires the list output to be ordered in a certain way. [Answer] # Removing `\left`'s and `\right`'s from piecewise expressions (A clarification of this [tip](https://codegolf.stackexchange.com/a/230101/96039) that's been edited to oblivion) When using a piecewise expression, you may have noticed that if you took out the `\left` and `\right` from a piecewise expression, it doesn't work. So, for example, the following doesn't work when directly pasted into Desmos: ``` \{x<0:x,x^3\} ``` But if you include the `\left` and `\right`, it does work: ``` \left\{x<0:x,x^3\right\} ``` To fix this issue, you can add a newline in front of the expression that includes the piecewise. In our case, the code to paste into Desmos is: ``` \{x<0:x,x^3\} ``` Even though the actual expression doesn't render properly, the graph of the piecewise expression should still show. Note that the piecewise expression will be fragile, which means that while you have selected the expression, most button presses (including buttons like `Ctrl`) will break the code. --- The downside of doing this trick is that every built-in function with the expression that includes the piecewise is not recognized by the Desmos parser. That means that you have to add a `\` in front of every built-in function to force Desmos to recognize it as a built-in function, adding one byte per built-in. For example, the following code won't work: ``` f(l)=min(\{l=0:l.max,l\}) ``` But the following code does work: ``` f(l)=\min(\{l=0:l.\max,l\}) ``` As a result, if you use too many built-in functions in the same expression as a piecewise expression, you should consider another approach that doesn't involve any piecewise expressions. For example, consider the following code (it doesn't do anything useful, but it has a whole bunch of built-in functions): (64 bytes) ``` f(l)=\{\sort([1...l.\max+1],\join(l,2,3,l.\mean))=l.\median,0\} ``` It can be shortened by doing the following: (60 bytes) ``` f(l)=0^{(sort([1...l.max+1],join(l,2,3,l.mean))-l.median)^2} ``` --- Overall, code in the form: ``` \{a=b,0\} ``` which includes \$k\$ built-in functions, can be shortened to: ``` 0^{(a-b)^2} ``` given that \$k\ge2\$. It will save \$k-1\$ bytes. Similarly, code in the form: ``` \{a=b:0,1\} ``` which includes \$k\$ built-in functions, can be shortened to: ``` 1-0^{(a-b)^2} ``` given that \$k\ge2\$. It will save \$k-1\$ bytes. These are just two common examples. Techniques will vary based on what you are trying to do. --- Because of this, code that includes piecewise expressions usually will have to be pasted in one expression at a time. This is because if you paste the entire code at once, expressions that don't have a piecewise expression in them will still have to include `\`'s in front of every built-in function in order to work. If you instead paste in the expressions that include piecewise expressions separately, you can avoid this issue. For example, consider the following code: ``` L=l.length f(l)=\{\sort([1...L],l)<L/2,0\} ``` If you paste this entire code into Desmos all at once, it will not work, because it expects a `\` in front of `length`. But if you first paste in: ``` L=l.length ``` Then paste in: ``` f(l)=\{\sort([1...L],l)<L/2,0\} ``` The code will work. [Answer] # Counting the number of digits of a number The number of digits of a non-negative integer `n` is: (19 bytes) ``` floor(log(n+0^n))+1 ``` This works because when Desmos calculates a number to the power of zero, it will automatically convert the entire exponential term to 1. We use this to our advantage with `0^n`, which returns 1 for `n=0` (because any number to the power of 0 is calculated as 1, even though the base is 0), and returns 0 for any positive integer. If `n` is guaranteed to be a positive integer (`n` can't be zero), then the formula becomes: (13 bytes) ``` floor(logn)+1 ``` If you need to find the number of digits of any integer `n`, then the formula is: (28 bytes) ``` k=abs(n) floor(log(k+0^k))+1 ``` ^ (Could probably be shorter but I can't see it at the moment) ]
[Question] [ Suppose we have an array \$\texttt{ps}\$ of length \$n\$ with pointers pointing to some location in the array: The process of "[*pointer jumping*](https://en.wikipedia.org/wiki/Pointer_jumping)" will set every pointer to the location the pointer it points to points to. For the purpose of this challenge a pointer is the (zero-based) index of an element of the array, this implies that every element in the array will be greater or equal to \$0\$ and less than \$n\$. Using this notation the process can be formulated as follows: ``` for i = 0..(n-1) { ps[i] = ps[ps[i]] } ``` This means (for this challenge) that the pointers are updated in-place in sequential order (ie. lower indices first). ## Example Let's work through an example, \$\texttt{ps = [2,1,4,1,3,2]}\$: $$ \texttt{i = 0}: \text{the element at position }\texttt{ps[0] = 2}\text{ points to }\texttt{4} \\ \to \texttt{ps = [4,1,4,1,3,2]} \\ \texttt{i = 1}: \text{the element at position }\texttt{ps[1] = 1}\text{ points to }\texttt{1} \\ \to \texttt{ps = [4,1,4,1,3,2]} \\ \texttt{i = 2}: \text{the element at position }\texttt{ps[2] = 4}\text{ points to }\texttt{3} \\ \to \texttt{ps = [4,1,3,1,3,2]} \\ \texttt{i = 3}: \text{the element at position }\texttt{ps[3] = 1}\text{ points to }\texttt{1} \\ \to \texttt{ps = [4,1,3,1,3,2]} \\ \texttt{i = 4}: \text{the element at position }\texttt{ps[4] = 3}\text{ points to }\texttt{1} \\ \to \texttt{ps = [4,1,3,1,1,2]} \\ \texttt{i = 5}: \text{the element at position }\texttt{ps[5] = 2}\text{ points to }\texttt{3} \\ \to \texttt{ps = [4,1,3,1,1,3]} $$ So after **one iteration** of "*pointer jumping*" we get the array \$\texttt{[4,1,3,1,1,3]}\$. ## Challenge Given an array with indices output the array obtained by iterating the above described pointer jumping until the array does not change anymore. ## Rules Your program/function will take and return/output the same type, a list/vector/array etc. which * is guaranteed to be non-empty and * is guaranteed to only contain entries \$0 \leq p < n\$. **Variants:** You may choose * to use 1-based indexing or * use actual pointers, however you should mention this in your submission. ## Test cases ``` [0] → [0] [1,0] → [0,0] [1,2,3,4,0] → [2,2,2,2,2] [0,1,1,1,0,3] → [0,1,1,1,0,1] [4,1,3,0,3,2] → [3,1,3,3,3,3] [5,1,2,0,4,5,6] → [5,1,2,5,4,5,6] [9,9,9,2,5,4,4,5,8,1,0,0] → [1,1,1,1,4,4,4,4,8,1,1,1] ``` [Answer] # JavaScript, 36 bytes Modifies the original input array. ``` a=>a.map(_=>a.map((x,y)=>a[y]=a[x])) ``` [Try it online](https://tio.run/##NY7BDsIgEETvfEgDydpQoEYP@CNI7Ka2pk0LjTWm/XoE1Mxh501mkxnxjWv7HJbXwfl7F3odUF@wnHGht7@hG@wsgtmtRrNZxkLr3eqnrpz8gxpiuAViKvgdARLUFzhUWRxkQhWtTAAiYQ2pzGO5hmMKzpAkIqocnvIrt8TmIXFaT5EVBbJy9INrrq5h4QM) [Answer] ## Haskell, 56 bytes ``` foldr(\_->([]#))=<<id x#a@(b:c)=(x++[(x++a)!!b])#c x#_=x ``` Haskell and in-place updates are a bad match. [Try it online!](https://tio.run/##PUtZDoIwEP3nFCX8tGEwZTNqqPECngAaUoooEbABPzi9ta1LXuZN3nYTy/0yDLpjle4eQzvjqo6OuOQBIawo@tZbA3HCzUEShtcwLC0J4vsNJ4E0Yc1WPYp@QgyNQp1rhNXcT0@0QR1BpYfKBGLIzKWQcDCaOo7h9xOTZF9FTc@CQur0Z0f/2xxsn5p@Dlvn7MEiMTpz7s6tKef6JbtBXBcdSaXe "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` def f(l):L=len(l);i=0;exec'l[i]=l[l[i]];i=-~i%L;'*L*L ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0fTysc2JzUPyLDOtDWwTq1ITVbPic6Mtc2JBlGxQFHdukxVH2t1LR8tn/@JCrYKmXkFpSUamlxcaRqJQLKgKDOvRCHxf7SlDgga6ZjqmAChqY6FjqGOgY5BLAA "Python 2 – Try It Online") -6 thanks to [HyperNeutrino](https://codegolf.stackexchange.com/users/68942/hyperneutrino). Alters `l` to the result in place. [Answer] # [C++14 (gcc)](https://gcc.gnu.org/), 61 bytes As unnamed generic lambda. Requires sequential containers like `std::vector`. ``` [](auto&c){auto d=c;do{d=c;for(auto&x:c)x=c[x];}while(d!=c);} ``` [Try it online!](https://tio.run/##RU1LCoMwEN3nFFMLxUAK/a2M8SLiQibaBtSIxjQQcnbrD7qZN/N@g31/fSPOZ9VhM8kKUqVHM1Rlm5E/Zys0esgIKSejoQYx50W87hekfuOkQC61X6HWw665BKkTmLuCh@9HNVUsTwIpDzMnRHUG2lJ1MQVPAEYjk2R/ky5SBtb7O3uwJ3uxWwh8sdSxpRse/eASS5f7CKOeDKQpuHVEDCJOwvwD "C++ (gcc) – Try It Online") [Answer] ## [Swift](https://swift.org), ~~68~~ 53 bytes ``` {a in for _ in a{var i=0;a.forEach{a[i]=a[$0];i+=1}}} ``` [Try it online!](https://tio.run/##TY7LasMwEEX3/opZlGLTaZD1sNsEdddFfiAbY4JIYioodlHVdmH87a7GiRwxmzP3SFf6/rOdl/PnxUO3hdz2w4@HZt/7tnh@Owz2DHoeDdgeusHBkcCMv8aB1WxnNiF8N6eP0TS21aZ5YO3OPulymqaZDhnnStDQsDa7rZzWEu@BuAYcBcoklss1LJdhKFahSMgQCoqRr6IioZCqWKhSWK2qJvWKNDwIueiXpTi8mHX5I320uAGPICLICCpCFaEusuzL2d7n14qVecIiYZmwSrhKuC7mfw) -15 thanks to BMO [Answer] # JavaScript (ES6), 41 bytes ``` f=a=>a+''==a.map((x,i)=>a[i]=a[x])?a:f(a) ``` [Try it online!](https://tio.run/##dc9NDoIwEAXgvadgRxtHaPkxaFI9COligmIwSIkYw@1rW3Ah1L5V5/HBcMc3DtWz6V@7Tl2uWtcCxQm3YSgERg/sCRmhoWZUNlJgOUp6xmNNkOpKdYNqr1GrbqQmJZOUBv4Tx4GpNwvA4S9xAHwkgRQyH7QkgTkryIC7MEiXdPrWt@Yrmpl5aqF5rYemrnZZ0RzswswsnMP@F1s61flcL/EBbKbePlG4/dyfW8znlbM5xXSX@gM "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 8 bytes ``` ΔDvDyèNǝ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3BSXMpfKwyv8js/9/z/aUgcEjXRMdUyA0FTHQsdQx0DHIBYA "05AB1E (legacy) – Try It Online") **Explanation** ``` Δ # apply until the top of the stack stops changing D # duplicate current list v # for each (element y, index N) in the list Dyè # get the element at index y Nǝ # and insert it at index N ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` [D©vDyèNǝ}D®Q# ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/2uXQyjKXysMr/I7PrXU5tC5QGShmqQOCRjqmOiZAaKpjoWOoY6BjEAsA "05AB1E – Try It Online") [Answer] # Japt, ~~15~~ ~~13~~ 7 bytes Modifies the original input array. ``` ££hYXgU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=o6NoWVhnVcPDVQ==&input=WzksOSw5LDIsNSw0LDQsNSw4LDEsMCwwXQ==) (additional bytes are to write the modified input to the console) ``` ££hYXgU £ :Map £ : Map each X at index Y hY : Replace the element at index Y XgU : With the element at index X ``` [Answer] # Java 8, ~~105~~ 54 bytes ``` a->{for(int l=a.length,i=0;i<l*l;)a[i%l]=a[a[i++%l]];} ``` Modifies the input-array instead of returning a new one to save bytes. -51 bytes by just modifying the array \$length^2\$ times, instead of until it no longer changes. [Try it online.](https://tio.run/##fVFBasMwELznFXspOI0iFMcpLa4LfUBzydHksHWUVK4iB0tOCcZvd1eyC4XiIiSk3dHMMFviFZfl4bMvNFoLb6hMOwNQxsn6iIWErX8CXCt1gCKier4HnKdU7GZ0WIdOFbAFAxn0uHxpj1XtYaAz5Fqak/tgKhOpetb3Op1jru70PsOcLosFXfdp16ee6dK8a2IaCYPemdxEO1crcwqqgxUnrYuM/IJgpo3ZiiW01yzugq8/CDFRX7HpTkx8yWRfkJ5fgq0nEIMj8Y@rDfMqglQ27GEC88T8igmRBNxj0Bxd/c4/xBU@/0xoyMrwIsKRe3ezTp551Th@oUidNlFJ0@eNU5q/1jXeLHfVEDd9GjW6/hs) **Explanation:** ``` a->{ // Method with integer-array parameter and no return-type int l=a.length, // Length of the input-array i=0;i<l*l;) // Loop `i` in the range [0, length squared): a[i%l]= // Set the (`i` modulo-length)'th item in the array to: a[ // The `p`'th value of the input-array, a[i++%l]];} // where `p` is the (`i` modulo-length)'th value of the array ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 bytes ``` ® £hYUgX eV ?U:ß ``` [Try all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=Cq4Ko2hZVWdYCmVWID9VOt8=&input=W1swXQpbMSwwXQpbMSwyLDMsNCwwXQpbMCwxLDEsMSwwLDNdCls0LDEsMywwLDMsMl0KWzUsMSwyLDAsNCw1LDZdCls5LDksOSwyLDUsNCw0LDUsOCwxLDAsMF1dCi1tUQ==) This feels like it should be shorter, but unfortunately my initial thought of `UmgU` doesn't work because each `g` accesses the original `U` rather than modifying it at each step. Preserving different components appropriately cost a handful of bytes as well. Explanation: ``` #Blank line preserves input in U long enough for the next line ® #Copy U into V to preserve its original value £hY #Modify U in-place by replacing each element X with... UgX #The value from the current U at the index X eV ?U #If the modified U is identical to the copy V, output it :ß #Otherwise start again with the modified U as the new input ``` [Answer] # [C (clang)](http://clang.llvm.org/), 32-bit, ~~49~~ 44 bytes ``` i;f(**p,n){for(i=0;i<n*n;)p[i++%n]=*p[i%n];} ``` [Try it online!](https://tio.run/##fY/RToQwEEWf4SsmmDVtKYYFdtWw@CPIAwFZm7AFdtEXwq@LMwUSg8akaad3zr3TFl5R5/o8TSqumBCt1HyomitTiR@rkxY65m2qXHens0RghWc8TndKF/VH@QanW1@q5uH9xf5sVAk9U7oHTAE6NYfBtozSpeizLUwGg1A8YD5urstty@pSlUFimoLfdymOyoyDdRKD/vW2V5Qr5uxKcOQcITgFeh0Z1/ardvA62pRxyZVm5nk9I0Oa8QF8GCXsyfJD3MtZD37rgYRQQrQAhw3gS2LmhXVIzHHDRKYbzgAG/sUc5DLLN7PweiTscYM9y2UFholW@Gl9wPw7@sY4fRVVnZ9vk3cJg28 "C (clang) – Try It Online") Uses pointers. **~~50~~ 45 bytes** with integers: ``` i;f(*p,n){for(i=0;i<n*n;)p[i++%n]=p[p[i%n]];} ``` [Try it online!](https://tio.run/##bY/RboMwDEWf4SsspkpJySYKtN2Udj/CeKigbJZagxjbC@LbmR1AmtgkK7Fvjq/j4rG4Xeh9HNFWatsY0n1VtwrPkcUTbcnqJsMw3FB@bjJOOcntMD4gFbev8gqnz67E@unj1f@usYROIXXAPiA3aeh9r1Jckrac1S04QOyB/fkIQ@17XtOyXKlgU0JggOfkwi/qGwVcDr603i9Iyvl2SryyXPcQwWBgJy2/xJ2Z9PivHhtIDKQzsF8BkRFmCs4TYQ4rJnWvyQSw4X/M3syzIjeLy4NgxxX2YuaIHZMu8PPygWk7WWMYfwA "C (clang) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~37~~ 34 bytes ``` ->a{a.size.times{a.map!{|x|a[x]}}} ``` [Try it online!](https://tio.run/##NY7NDsIgEITvPEWN17WBQk2N0RchHNDQ2EOTxmJSLTw7Ln@ZA8w3uwPvz@Mbxls43fWu23X6mdZOs1nRzHo57G5zWm7Kex8kkVQ1cGzwIJJBNZBtBxxEhR0UYUSBJVHgdaMChrHAG48hDqeYJ5CEcQ@xmmJ1D@c8kFFfEJEXiMoksiF1l5@w8pgoGrJXRLVGP1@7s26UVl2XxvrwBw "Ruby – Try It Online") Returns by modifying the input array in-place. [Answer] # [Red](http://www.red-lang.org), 63 bytes ``` func[b][loop(l: length? b)* l[repeat i l[b/:i: b/(1 + b/:i)]]b] ``` [Try it online!](https://tio.run/##ZY3NDsIgEITvfYo5tnoo9MdYLr6DV8JBLGgTQhuCz48rHgw2m012vtmdDWZOVzNLVVmR7MvfpVbSretWOwFn/CM@L9DNAU4Gs5lbxEKjbsUioNua44iPaJTSKm1h8REWEh04BuqeJlX9OCsU3@mOLoY/yojzvNsX/JvPdj/GnMPIH3EqnClXR3zI7jmn0rf0Bg "Red – Try It Online") Modifies the array in place [Answer] # [R](https://www.r-project.org/), ~~60~~ 58 bytes -2 bytes thanks to @digEmAll for reading the rules. ``` function(x,n=sum(x|1)){for(i in rep(1:n,n))x[i]=x[x[i]];x} ``` [Try it online!](https://tio.run/##VY5NCsIwEIX3niLgJsERnCatvz1J6aoYyMIo1UJA3XoAj@hF4jQNJvICQ2a@efN6r9lh6fVgu5s5W@7A1tfhxN0Dhbjrc88NM5b1xwvHnQUrhGtMW7tmLO3ePb3mKNicfV5v1qxatmA407zjBZDBrw9/EwkKynxeQFSiMLYQVO6DQVQTWRKlRg5kIiU15KREVjDeRrpdwTqxFIUGZQhVZQnoSniS8DIsbUOgLDjGQCpqM/2Dif8C "R – Try It Online") 1-indexed. `n` is the length of the input array. `rep(1:n,n)` replicates `1:n` `n` times (e.g. `n=3 => 1,2,3,1,2,3,1,2,3`) Loop through the array `n` times. Steady state will be acheived by then for sure, in fact by the end of the n-1st time through I think. The proof is left to the reader. [Answer] # Common Lisp, ~~59~~ 58 bytes ``` (lambda(a)(dolist(j a)(map-into a(lambda(x)(elt a x))a))a) ``` [Try it online!](https://tio.run/##NY7LCsJADEV/5VIQM4vC9CW6UOinxLZCpW1GO4u66a@PmRFJCOeGm0c3jasLNIk4POSNDeOCI5E1oAK/WqJCndiiSGFRqaqVqsgoVTWITqvOBifVF8QoVdWpd05z1hj0AtJbM3t4ZHuL6w17ux8yUCfuk6/DC5tu0Ld4vvdMbKgXfdTTE8ozu3xcvID/hs3QMHmwjhmOGRRM@AI) [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 80 bytes ``` import StdEnv ``` # ``` limit o iterate\b=foldl(\l i=updateAt i(l!!(l!!i))l)b(indexList b) ``` [Try it online!](https://tio.run/##pc69DoIwFAXgvU9x2SjB4N/KYKKDCRujOJS26E1uWwIXoy9vRQcTZ4eznJN8OZqs8tEFM5EFp9CLogCleVIExnbokTF4uNrBCnR9GBhqNgd/E93k9WcrgdAhQwBkOyi2TVt2gQylDQGWU2/mbseAKSXJOyglyTZFb@y9wpGhlaLI4i//vxmzQtSsZrKE79nTKl/nm3ybL8/xqTtSlzEujlXcP7xyqMcX "Clean – Try It Online") [Answer] # [Clojure](https://clojure.org/), 136 bytes ``` (defn j[a](let[f(fn[a](loop[i 0 a a](if(= i(count a))a(recur(inc i)(assoc a i(a(a i)))))))](loop[p nil a a](if(= p a)a(recur a(f a)))))) ``` [Try it online!](https://tio.run/##bY1NCsMgEEb3PcUsR5iF@SvtoieRLMQqGETFJOe3arNoSWZA9HvjG@XCsiedM7618bAIOaPTmzBofLuHEIUFDhLKyxp8gUUVdr@BZExi0mpPaL0Cy1Cua1Bl0qLEcrJvHZII3rofTSyC4z9INFVXK2NM1m/OAy4g@MzY7S/p6CrraaDxgnDqWnMaTmws@VAJ9Sc2UXXy4pzofqJPqt0XNraJR9tQt@cP "Clojure – Try It Online") [Answer] # Perl 5, ~~35~~ ~~34~~ 26 bytes using the fact that convergence is reach at most for the size number of iterations ``` $_=$F[$_]for@F x@F;$_="@F" ``` [26 bytes](https://tio.run/##K0gtyjH9/18l3lbFLVolPjYtv8jBTaHCwc0aKKTk4Kb0/78Bl6ECCBspGCuYAFkGCoZgaKBgzGUCpI1BLAUjLlMFkBoDoBpTBTMuSwUQNAKyTcAiFmAdBv/yC0oy8/OK/@smFuQAAA) ``` $_=$F[$_]for@F;/@F/ or$_="@F",redo ``` [34 bytes](https://tio.run/##HYvNCsIwEITveYqh5Gjt5k8UEXLKzScQKYIVhNIN0ed3TcIwzMcwk5eyBhE9X3S66fn@4hLTeYppApfaDjENu7I8WYSUQbOFg69EMF0Ep3xN1whWBbQN1U3AQZ3QZCv73hz7g36cv2/ePjJew56MjI@8/gE) ``` $_=$F[$_]for@F;$_="@F",redo if!/@F/ ``` [35 bytes](https://tio.run/##HYvNCsIwEITveYqx5Gjt5k8UKeSUW59ApAi2UCgmRJ/fNQnDsN8sM2nJu2OW8yjDXc6PNWYfbiV2PnTHvLwitvUw@DAwk1Co1jCwhQiqiWCELddUghYOtUOl43AWV1TpwrZ9Lm1Bv5i@W3x/uJ/ciRT3z7T/AQ) [Answer] # [Clojure](https://clojure.org/), 88 bytes ``` #(reduce(fn[x i](assoc x i(get x(get x i))))%(flatten(repeat(count %)(range(count %))))) ``` [Try it online!](https://tio.run/##ZY3RCoMwDEXf9xWFIaSQh1p1bN8iPpSaikOq1Bb8@67tYDBNIOTeQ270sr6DowgjGWbiHRyNQRMY2x9sHkDt@6pZWmEiz47vZDNPVYFZlPdk081GyoNeg/Ws4uCUnegnc0V@g83N1i8WTC8G/qdrvDoSG2wvvsC6tMDmRNrkNtlHeSId5jSR0jp8nNgLc8tE2sKfJTt/jR8 "Clojure – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` FθFLθ§≔θκ§θ§θκIθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BTAUz7pOall2QAuZoKjsXFmel5jiWeeSmpFRqFOgrZOgpIPGQJTU1Na66Aosy8Eg3nxOISkHbr//@joy11QNBIx1THBAhNdSx0DHUMdAxiY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Sadly all the usual mapping functions only operate on a copy of the array with the result being that they just permute the elements rather than jumping them, so the code has to do everything manually. Explanation: ``` Fθ ``` Repeat the inner loop once for each element. This just ensures that the result stabilises. ``` FLθ ``` Loop over the array indices. ``` §≔θκ§θ§θκ ``` Get the array element at the current index, use that to index into the array, and replace the current element with that value. ``` Iθ ``` Cast the elements to string and implicitly print each on their own line. [Answer] # F#, ~~74~~ 73 bytes ``` fun(c:'a[])->let l=c.Length in(for i in 0..l*l do c.[i%l]<-c.[c.[i%l]]);c ``` Nothing special. Uses the modulus idea seen in other answers. [Answer] ## K, 27 Bytes ``` {{@[x;y;:;x x y]}/[x;!#x]}/ ``` * `{..}/` applies lambda {..} over arg (until convergence) * inside outer lambda: + `{..}/[x;y]` applies lambda iteratively over x (updated at each iteration) and an item of y (y is a list of values, and uses an item at each iteration). In this case arg y is `!#x`(til count x, that is, indexes of the array) + `@[x;y;:;x x y]` amend array x (at index y assign x[x[y]]) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 [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") Requires `⎕IO←0` ``` {m⊣{m[⍵]←m[m[⍵]]}¨⍳≢m←⍵}⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6tzH3Utrs6NftS7NRYokBsNYcbWHlrxqHfzo85FuUBRoEjto97FjzoX/k8Dc/sgBnQ1H1pv/KhtIpAXHOQMJEM8PIP/pynoGHClKRhCSSMdYx0TMNtAxxAMDXSMgTwTIMsYxNYxAvJMdUAqDYAqTXXMgHxLHRA0AvJMwGIWYH0GAA "APL (Dyalog Unicode) – Try It Online") ]
[Question] [ Given an array of numbers with `length >=3` and `length % 3 == 0` `[1, 2, 3, 4, ...]` You will split it in sub-arrays of length 3 `[[1, 2, 3], [4, 5, ...], [...` And return an array with * [0] => The amount of cases in the sub-array where **all numbers are equal** * [1] => In case all numbers in sub-array are not equal, the amount of cases in the sub-array where **only 2 numbers are equal** **Example and test cases:** * Input: `[2, 4, 2, 5, 5, 5, 4, 2, 1, 3, 3, 1]` output `[1, 2]` This is because ``` [[2, 4, 2], [5, 5, 5], [4, 2, 1], [3, 3, 1]] ^ ^ ^ ^ ^ ^ ^ equal all equal equal ``` so 2 `equal` and 1 `all equal` * `[3,5,6,5,5,7,6,6,8,7,7,7,3,4,2,4,4,3] => [1, 3]` * `[3,3,3,4,4,4,5,5,5,6,6,6,5,4,3] => [4, 0]` * `[3,4,5,6,7,8,9,8,7,6,5,4,3,2,1] => [0, 0]` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win. --- PD: Apologies for my English. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~60~~ ~~52~~ 50 bytes ``` @(x)sum(sum(~diff(sort(reshape(x,3,[]))))'==[2 1]) ``` [Try it online!](https://tio.run/##ZY7NCsIwEITvPsVexASW0vy1eoj4HiGHog16kEpbpSdfPW7SKoo7DLOH/ZjtjmPzaGOwRVHEA5v4cL@y5OfpEgIbun5kfTucm1vLJlToPKfZWOskCM9jYE6hwYpssKascEuZpFCjJGtUngPAGsDuwQkE5VeZU/kmyWRVWeZDzLNwGqFcOJ1va2ra5baFoTbxz5VvTuZ/5qa0idz/Tfxw9Kf08QU "Octave – Try It Online") Saved 8 bytes thanks to Luis! ### Explanation: Reshapes the input into a matrix with 3 rows, and the appropriate amount of columns. It then sorts each of the columns, and calculates the difference between the elements on different rows. This gives a matrix with two rows, where identical numbers will have a zero, and different numbers will have a positive number. This is negated, so that all equal elements are `1`, and all unequal are `0`. We then sum each of those columns, giving us one of the three alternatives: `0 = All elements are unequal`, `1 = Two elements are equal` and `2 = All elements are equal`. We then check how many are `>1`, and how many are exactly `==1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Dennis (use a new alias for `L€`, `Ẉ`) ``` Q3ÐƤẈċⱮ2 ``` **[Try it online!](https://tio.run/##y0rNyan8/z/Q@PCEY0se7uo40v1o4zqj////RxvrmOiY6pjpmOtY6FgCsTmQbQoUM9Yx0jGMBQA "Jelly – Try It Online")** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` 3ôεÙg}12S¢ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f@PCWc1sPz0yvNTQKPrTo//9oYx1THTMgNtUxB9JmOhZAGgSNdUx0jIDYRMc4FgA "05AB1E – Try It Online") **Explanation** ``` 3ô # split input into groups of 3 ε } # for each triple Ù # remove duplicates g # and get the length 12S¢ # count the number of 1s and 2s in the result ``` [Answer] # JavaScript (ES6), 70 bytes ``` f=([a,b,c,...d],t=p=0)=>1/a?f(d,t+!(a-b&&a-c?b-c||++p:b-c&&++p)):[t,p] ``` [Try it online!](https://tio.run/##bY1BDoIwFET3ngI3TRs@BWwBJUEOQliUAkZDaCPEFXevbdWF0T@ZzCz@y9zEQyzyftVrNKt@MGascCOgAwmU0r6FtdJVQqpzGot6xD2s4R6LqENIRLLuIrltYahLWxCyhZCyWUG3Rqp5UdNAJ3XBI24YZJBbZ1DYzOFo04kBh4M1B9YSEsRx0KQQsHb3wzP/65R55V7Zh3yd4zkEyR@ee6awyye//mbtevrNJ443Tw "JavaScript (Node.js) – Try It Online") ### How? We recursively extract each triplet **[a,b,c]** from the input array and update two counters **t** (three-of-a-kind) and **p** (pair), using the following formula: ``` t = t + !(a - b && a - c ? b - c || ++p : b - c && ++p) ``` There are 5 possible cases which are detailed below, from 'all equal' to 'all distinct'. ``` a b c | a-b && a-c | b-c | b-c || ++p | b-c && ++p | t += ------+------------+-----+------------+------------+------------ 4 4 4 | false | 0 | n/a | 0 | !0 --> 1 4 4 5 | false | ≠0 | n/a | ++p | !++p --> 0 4 5 4 | false | ≠0 | n/a | ++p | !++p --> 0 5 4 4 | true | 0 | ++p | n/a | !++p --> 0 4 5 6 | true | ≠0 | ≠0 | n/a | !(≠0) --> 0 ``` [Answer] # Pyth, ~~13~~ ~~14~~ ~~12~~ 11 bytes ``` /Lml{kcQ3S2 ``` [Try it here](http://pyth.herokuapp.com/?code=%2FLml%7BkcQ3S2&input=%5B3%2C4%2C5%2C6%2C7%2C8%2C9%2C8%2C7%2C6%2C5%2C4%2C3%2C2%2C1%5D&debug=0) ### Explanation ``` /Lml{kcQ3S2 cQ3 Split the input into groups of 3. ml{k Deduplicate and get the length of each. /L Count the number... S2 ... of 1s and 2s. ``` [Answer] # [oK](https://github.com/johnearnest/ok), ~~17~~ 16 bytes ``` +/(1 2=#=:)'0N3# ``` [Try it online!](https://tio.run/##LY09DoAgDIV3TtGEAYgxCi2gJFzBY7AweP8JSyXf8Nr3@tP3t4/RynZYD6HqWpw5H9SjGRuAIEAUZuUBGa@Q@yRuZk1wsU5QpohBhTJLwn8hCXGlJE7m3Vv2VzK/uPEB "K (oK) – Try It Online") ``` 0N3# /reshape into groups of 3 (see ngn's comment) ( )' /for each group: =: / make a map from number -> indices # / count number of keys/values 1 2= / check if the count is equal to 1 or 2 +/ /sum together the columns ``` For [k](https://en.wikipedia.org/wiki/K_(programming_language)), the 17 byte version is: `+/(1 2=#=:)'0N 3#`. [Answer] # [R](https://www.r-project.org/), 70 bytes ``` function(v,x=lengths(by(v,seq(0,a=v)%/%3,table)))c(sum(x<2),sum(x==2)) ``` [Try it online!](https://tio.run/##dVBBTsQwDDyTV/iyii0ZAU3bBWnDJzgCh2zVLpVKCk12tQjx9uJYHODAjKxJ5LEnyrIOfh2OscvjHPHEZz/18ZBfEu4/5Jr6d7zm4E@0udo4zmE/9UTUYTq@4nlXEevB@4pozX3KCXaXMI0powHBBSg6dNxwK9XwVrTlW9FCxzVXUjU7YgN/UKacOgobZats/vXX6tnK/jvN@PFKxg2RGeYFA4wR9Kn0WRZ0IaN9tJznh7yM8YCB2D5btuDvQeR3a5Bm6T5FK1/z5q0l86XZZv0G "R – Try It Online") ***Previous versions :*** # [R](https://www.r-project.org/), 82 bytes ``` function(v,a=!1:2){for(i in lengths(by(v,seq(0,a=v)%/%3,table)))a[i]=a[i]+1;a[-3]} ``` [Try it online!](https://tio.run/##dVDLTsMwEDzjr1gOlb1iK0idpOVhfoJjyMGNktZS5JTYVEJVvz2sLQ5wYEbrOcx41@t5GcwyfPouusmrM1lzWzxt8DJMs3LgPIy9P8RjUPsvdkP/oR44c8bV/UpTtPuxR0TbuNak4654ts1at9cl9iEGeFnD6EJUAhg3kNEpTRXVXBVtWWvasSZqKmnDVZJGEvAH6ZbOicQqs86s/s2XObPl/o95xk@WZxSIIm1o04b5qXhJDToblWwkxektzs4flEWSrSQJ5hVYflsDm8l995L/5WSkRHHNs8XyDQ "R – Try It Online") --- # [R](https://www.r-project.org/), 93 bytes ``` function(v,a=table(lengths(by(v,0:(length(v)-1)%/%3,unique)))[c('1','2')])`[<-`(a,is.na(a),0) ``` [Try it online!](https://tio.run/##dU/LasMwEDxXX6FL0C6s0zh@pA1xf6JHNxDFyInAyK0lB0rpt7srkUN76AzLIO1oRzstfbP0s@uCHR3cSDdBnwcDg3GXcPVw/uTLzf5@hhtmOa4eVwXNzn7MBhHbDlSuSG0VHvHUHrITaLJ@7TRopA0uwfjg5SGTg/UBhGQ8yIQOCqqo5qpox1rTE2tkQSVtuUoqkIT8g/iqSI7IKrFOrP71l8mz4/nPKePu5YwcUfTjBFpaJ9NX8SsO6HQA1SoK42uYrLvEZdSR95TNi2T53eq5GbtvTpE3741SKL5Ttlh@AA "R – Try It Online") [Answer] # [Java (JDK 10)](http://jdk.java.net/), 116 bytes ``` l->{int r[]={0,0,0},i=0,a,b,c;for(;i<l.length;b=l[i++],c=l[i++],r[a==b?b==c?0:1:b==c|a==c?1:2]++)a=l[i++];return r;} ``` [Try it online!](https://tio.run/##bVFRT4MwEH7fr7gsWQLuJGOMqWBdfPHNpz0SHgrC7OyAtMeSZfLbZynMGDXX9nr9Pq7fR/f8yG/3bx8XcWhqRbA3tdeSkN5NPPlzVrZVTqKu/gU1qYIfeiiXXGt45aKC8wSgaTMpctDEyaRjLd7gYDBnS0pUuyQFrnbatVSAl/GKR1FRkqJdn6BkF3n7dDYVqCRl5wWa6FCwBXLMMI/LWjmxeJSeLKodvccZk4mYz1PMrxuVcMayTcZYvllEftRvPnlf@dEync9dPjJjVVCrKlBxd4mtJivC6KRCkwY2KgU4LxFWCGYNr2MofYTADr/DKzfAENdmhnhn8hrvTe4jwBUuzVxh8JMcWKCP0MbaRvibtrLQnen2YDuOFNPR7yyrGyyY/wOO9WFdRIMX99vKAKlCt5KMw9LjTSNPTs9y45GzPWkqDl7dkteYl6PSmc50BDM9q6YIz0rxk/aoHp51@PTv8XCFOzbtNXaT7vIF "Java (JDK 10) – Try It Online") Note: returns a 3-elements array with `[0]` and `[1]` returning th appropriate values, and `[2]` returning a dummy value (the number of 3-lists without any elements in common) . This is totally valid according to the current rules. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 106 bytes ``` param($a)for(;$a){$x,$y,$z,$a=$a;if($x-eq$y-and$y-eq$z){$i++}else{$j+=$x-eq$y-or$y-eq$z-or$z-eq$x}}+$i,+$j ``` [Try it online!](https://tio.run/##NYpBCsIwFEQv8xcpmS601iql4FU@mGJKNDVdmKbk7PEXdDEzj@HN/mPC8jDOlTJz4KcirkYfVC@7UQStoATigbi3o6JYmzetNb/u0oJJLKt1Nm4xG016@Bs@/ISd0k4xZ00WmqZSyk01OKHFGR0uuEo64Va@Bkccqi8 "PowerShell – Try It Online") Exactly what it says on the tin. Loops over input `$a`. Each iteration, peels off `$x,$y,$z` as the next three elements. Tests `if` they're all equal and if so, increments `$i`. `Else`, increments `$j` if at least one pair is equal. Once the loop is complete, output `$i` and `$j` as integers. *So ... many ... dollars ...* [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` (.+)¶(.+)¶(.+) ;$1;$2;$3;$1; %M`(;\d+)(?=\1;) s`((1)|(3)|.)+ $#3 $#2 ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZwQ46L9X0NPW/PQNgTJZa1iaK1iZK1iDGJwqfomaFjHpGhratjbxhhaa3IVJ2hoGGrWaBhr1uhpanOpKBsrqCgb/f9vpGOiY6RjCoYglqGOMRAachkD@WZgUXMgbaZjAaRB0BisygQIjbmMwWpNwBBighkYmkJlTcAi5kC9lmD9UBmQLQA "Retina 0.8.2 – Try It Online") Link includes test cases with header to convert to desired format of one value per line. Explanation: ``` (.+)¶(.+)¶(.+) ;$1;$2;$3;$1; ``` Collect three values onto each line with separators and duplicate the first one at the end. ``` %M`(;\d+)(?=\1;) ``` Count the number of pairs of duplicates. ``` s`((1)|(3)|.)+ $#3 $#2 ``` Count the number of `3`s and `1`s. [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` íUÖ←#"ë╕ ``` [Run and debug it](https://staxlang.xyz/#p=a155991b232289b8&i=[3,5,6,5,5,7,6,6,8,7,7,7,3,4,2,4,4,3]%0A[3,3,3,4,4,4,5,5,5,6,6,6,5,4,3]%0A[3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]&a=1&m=2) [Answer] # Common Lisp, 113 bytes ``` (lambda(l &aux(a 0)(b 0))(loop for(x y z)on l by #'cdddr do(if(= x y z)(incf a)(if(/= x y z)()(incf b))))`(,a,b)) ``` [Try it online!](https://tio.run/##PY9NCsJADIX3nuKhqAkI/kytutCzmHYoFGqn1BbURa9eM7E4D5LwJbxk8qp8NiNVITQoQouybvpOI9ZEByQ44GiK1R5OtecZOSWp8ZPmFGfNUc7mEpVjxDFnKOpnk5qONhD7ibGTGlzMZOrFZczwAaRHPaRDh/kgwPUGDDIs59OhpKfLI/NCFVbSv0iwY8o08P9P9MIbHw41KmRvLNa5975VcyoLuuLXpbLOCwhHtv3DCWes704b2Wg12mYF4xc) Used the fact that in Common Lisp `(= x y z)` gives true if all the three elements are equal, and `(/= x y z)` gives true if no pair of numbers is equal. [Answer] # Japt, ~~14~~ 13 bytes ``` 2õ@ò3 x_â ʶX ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=MvVA8jMgeF/iIMq2WA==&input=WzIsIDQsIDIsIDUsIDUsIDUsIDQsIDIsIDEsIDMsIDMsIDFdCi1R) --- ## Explanation ``` 2õ :Range [1,2] @ :Pass each X through a function ò3 : Split input to arrays of length 3 _ : Pass each through a function â : Remove duplicates Ê : Get length ¶X : Test for equality with X x : Reduce by addition ``` [Answer] # [Haskell](https://www.haskell.org/), 90 bytes ``` g[]=[] g(a:b:c:x)=(sum$map fromEnum[a==b,a==c,b==c]):g x f x=[sum[1|y<-g x,y==n]|n<-[3,1]] ``` [Try it online!](https://tio.run/##dUzBDoIwDL3zFT14wKQcxhgocUe/YtlhoCCRDQOSQMK/Y516MdrXvqbt67uY4Xpu23WtlZZKB3Vo8iIv82krw2G0G2tuUPWdPbrRKiNlgUQlFkR6m9cwBRVMUpFUsWU@RLTBWUqnF3eIFEem9WpN40DCqQuA4tY37g4bqEDFCAkCsfjka2QI3CfT3y8cBaZUAjPqKe6oP8ExwZgqQf7jh/v7E8Ij9RB/1IlXZOS99/5vJfkzvT4A "Haskell – Try It Online") Looks a bit awkward... [Answer] # [Python 2](https://docs.python.org/2/), ~~77~~ ~~72~~ 65 bytes ``` lambda a:map([len(set(t))for t in zip(*[iter(a)]*3)].count,(1,2)) ``` [Try it online!](https://tio.run/##RY7RCsIwDEWf9Sv6tlaC0HbddDB/pPah6oaFrSuzPujP17QKcgkJNzeHhFe8L16ksT@nyc6XmyW2m22geho8fQyRRsbGZSWROE/eLtCddnFYqWVmJ5nZX5enj0A5CMZSDtoc1FqCggZLQYu9gQP2LAk1CKwapAGCMVmsLFXUFKl/oC5mi4RjofyWSOEGtCi872meeAFyY7rtJqzOR2Kh6k8VjPhy@gA "Python 2 – Try It Online") 7 bytes saved via a clever trick from [xnor](https://codegolf.stackexchange.com/users/20260/xnor) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 23 bytes ``` S2,3,` %Cq`\S+ *\C`1 2 ``` [Try it online!](https://tio.run/##K0otycxLNPyvp6p0aNuhbUp2Gu4J/4ONdIx1EhS4VJ0LE2KCtbm0YpwTDLmM/v83UjBRMFIwBUMQy1DBGAgNuYyBfDOwqDmQNlOwANIgaAxWZQKExlzGYLUmYAgxwQwMTaGyJmARc6BeS7B@qAzIFgA "Retina – Try It Online") ### Explanation ``` S2,3,` ``` Split the input at every 3rd space starting at the (0-based) 2nd, i.e. split the input into groups of three. ``` %Cq`\S+ ``` On each line (`%`) count the number (`C`) of unique (`q`) values (`\S+`). ``` *\C`1 ``` Count the number of `1`s and print them with a trailing linefeed (`\`), but do so in a dry-run (`*`) so that we don't lose the previous result. ``` 2 ``` Count the number of `2`s (and print them automatically). [Answer] # [J](http://jsoftware.com/), 16 15 bytes -1 byte thanks to cole! ``` 1#.1 2=/_3#@=\] ``` [Try it online!](https://tio.run/##RY3BCoNADETv@xWDHkSQrWvWtQoL/ZCWHoqLePHg2W/fJrFFHiFhZpisOe3RosWENrvSOnTx9qbyEZ@vXJvCokrRVmhwTEi7MfNn2ZDQwfP0ilwOxLi/TSwHNQfeAXfeAmnYM4QrS6oLZ2FQpJiukFdj4KpR634B@Z2/ "J – Try It Online") Pretty much the same approach as the majority of solutions. ## Explanation: ``` _3 \] - split the input into sublists of lenght 3 #@~. - for each triplet remove duplicates and take the length 1 2=/ - compare with 1 and 2 1#. - add up ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes Saved two bytes thanks to Martin Ender. ``` {#~Count~{_},#~Count~{_,_}}&@BlockMap[Union,#,3]& ``` [Try it online!](https://tio.run/##RY3NCsIwEIRfZSHQ04q06Y8elKJnwYunEEooFoM2FYmnkL56TLZC@Q6zzAyzo7KP@6is7lUY4ADBsfk8fY2dXedxvbHzPmtPr6l/XtRb3IyeDDLkMgvXjzZWMNgcYRBMSshg24JzBZZYYEWkK0ceyT2C49GqKWii1riLmuBULCN8qXGyEstOTVRroSSziQt7WvmH6Z334Qc "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Elixir](https://elixir-lang.org/), 92 bytes ``` fn a->import Enum;c=map chunk(a,3),&(length uniq&1);{count(c,&(&1==1)),count(c,&(&1==2))}end ``` First, chunks the list into size length 3 `chunk(a,3)` Secondly, it converts finds the length of each element, uniqified; `map chunk(a,3),&(length uniq&1)`. Finally, it returns an array consisting of the number of times the resulting list is equal to one `count(c,&(&1==1))` and the number of times the resulting list is equal to two `count(c,&(&1==2))`. [Try it online!](https://tio.run/##VY3NCoJAFIX3PsXFhcyFSRitVYybaNGqB4iQYZx0SK82jhGYz25WtAg@DpwfOKa2D@vmUTnHIZ9Awq4tTGzuqs577yyV7HCMS@N7FoaIwbILnhmw@UKgVpltutZ52NPQbLVsVAe6GujKFE@RR6w2VPoKBrK3SOB21O1AnumliYSUApH/JwniZKiYMWb4vlmuLfWd0Z7hfEo4rDksuvnxtYJD@kGcXw "Elixir – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 59 bytes ``` ->a{[1,2].map{|x|a.each_slice(3).count{|y|x==y.uniq.size}}} ``` [Try it online!](https://tio.run/##VY3NCsIwEITvPoVHhRhItj96iC8SgsSQYkHbai00Jn32mKyCyHeYZWaYfUxnFxsRd0ftJSNc0ZsefJiDplaby2m8tsZuYEtNP3VPH1yYhXB06to7HduXXZYlDutGSk4KwkmJ5IsRSDClVhhDsisM66QV2SfNAJaLBPyqgHbms1ch5X@pwKBOSwdc@xbya6XiGw "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~24~~ 19 bytes ``` ò3 ®â l [Uè¥1 Uè¥2] ``` [Try it online!](https://tio.run/##y0osKPn///AmY4VD6w4vUsjhig49vOLQUkMFMGUU@/9/tLEOCJqAoSkYmoGhKZBvHKugAAA "Japt – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü┬─*HTÜ╫\Ä╢qm♥ ``` [Run and debug it](https://staxlang.xyz/#p=81c2c42a48549ad75c8eb6716d03&i=[2,+4,+2,+5,+5,+5,+4,+2,+1,+3,+3,+1]%0A[3,5,6,5,5,7,6,6,8,7,7,7,3,4,2,4,4,3]%0A[1,1,1]&m=2) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 80 bytes ``` [A,B,C|T]-X/Y:-T-M/N,(A=B,B=C,X is M+1,Y=N;X=M,(A\=B,B\=C,Y=N;Y is N+1)). _-0/0. ``` [Try it online!](https://tio.run/##hU7LCoMwELz3K3KsuGu0MdoHoRjPevKgqPRUiiC1aMFL/z3dpD0WyjAs7Mzs7GOexumGyzoY02agIX9VPda8OWKFBS9hmykNWuVQs2FhhR9Bo8pTrQpSOit1pNlVY/XSjzwv2Fww5GFgzshaARISooSUZgJ7mhYCYtgRYxA9ZlwDW@fheR3vW/tGT0c@aeGcFtIhcZB/c7HzptR3cJ3fDHVGv3PmDQ "Prolog (SWI) – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `pair-rocket`, 58 bytes ``` [ 3 group 1 => 2 [ '[ cardinality _ = ] count ] with map ] ``` [Try it online!](https://tio.run/##XVDBSgMxEL3vV7ybJwtttlu11Kt48SKelkVCTNuwNYmTWWQp/fZ1dlQQ80he8t5jwszeOk40vTw/Pj3c4UBpyCEeUDwX7GnEu@XjorDlUDi4AltKEgoJvafoT5L8GHx0viCTZx4zhcjINtA1Jdd7xraqzhVknbFCLXutmG9LGMESlx/fiN6ouxFucCM8w2i6Fpg/WaP6jO@KjWL9L1Wrs5Fat1rvN7HSfy/V1MpDGxdhdy96i6sWztJbiPYUeMQrdujg0iCddfgMfJS5ZHTTfMpwXL@YvgA "Factor – Try It Online") [Answer] # Desmos, 84 bytes ``` l(r)=r.length b=[l(k[3x-2...3x].unique)forx=[1...l(k)/3]] f(k)=[l(b[b=1]),l(b[b=2])] ``` [Try it on Desmos!](https://www.desmos.com/calculator/gc3b94ydvy) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) ~~14~~ 13 bytes ``` 3ẇƛ∪L;:1O$2Ox ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIz4bqHxpviiKpMOzoxTyQyT1csIiwiIiwiMSwxLDEsMiwzLDQsMSwxLDEsMiwyLDEiXQ==) #### Explanation: ``` 3ẇ # 3-partition ƛ # Open lambda map ∪L # Length of sublist union ; # Close lambda map : # Duplicate for next operation 1O # Count 1 $ # Swap 2O # Count 2 x # Print stack as list ``` [Answer] # C (GCC), ~~135~~ ~~128~~ 117 bytes *-7 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* *-11 more, again thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* This is basically [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)'s answer now, since he's improved it by more than 13 percent. ``` #define E(k)v[k-~i]==v[i a;b;i;f(v,l)int*v;{for(a=b=i=0;i<l;i+=3)E()]&E(1)]?++a:E()]|E(1)]|E(1)+1]&&++b;*v=a;v[1]=b;} ``` [Try It Online!](https://tio.run/##VU/RTsMwDHzvV0RDVMniiZVuAy1EiId@RclDmiXIWkhhjCBRyq@XdEwq2LJPZ/nOslk8GTMMFzvrMFhS0T2L9X7xjUrKWGOmRSNQOBrBMwzHeRSdaw9Uy0aiXAq88wK5LFlFmcorWjB1z7nejvTrRE@dFyrPOW/EPEotYl0o2Yh@eNYYKMu6jJwjXSDRmloRSboS1rBJtYabhBu4TThmCSu4TrWCshf/pN6GJHzDT9u60Ydc/SH1Uk3b6SFrYBSwafhySCaOzh68J/b1XfstudwBOX60E30MMzi7/WKhkkM//AA) Unfortunately, I'm too lazy to write a new explanation for the most recent answer, but it's quite similar to the previous 128-byte one: ``` #define E(j,k)v[j+i]==v[k-~i] a;b;i;f(v,l)int*v;{for(a=b=i=0;i<l;i+=3)E(,)&&E(,1)&&++a||(E(,)||E(,1)||E(1,1))&&++b;*v=a;v[1]=b;} ``` [Try It Online!](https://tio.run/##VY/RTsMgFIbv@xRkxgXWs7jabRqRCy/2FMgF7cCwIdU5MbGtr14P25Iq5PDl/If/J9Tzl7oehqutsS4YsqE72LMod7lTQkS5n/84lWleccctjeCZC8dZ5K1tDlSLSjix4O7Rc5eLkm0osOkUzwKR57rraJK67iQlFMjTrOKzKDSPslCi4v3wql2gLGszcln4DommlooI0pawgjXWCu6Qa7hHpl3CEm6xllD2/J/Vm4DGD/dtGptyyM2fRi7UeBu/ZWpIBjaKbwcMsXTy5D0x75/aP5DrLZDjVzO2z2ECl7QzC4UJ/fAL) `f` takes a vector (`v`) and its length (`l`) as arguments, and return its values in the first two elements of that vector. Explanation: ``` #define E(j,k)v[j+i]==v[k-~i] // k-~i == k-(-i-1) == k+i+1. an empty first argument equals +i, and an empty second argument equals -~i == i+1 a;b;i; f(v,l)int*v; { for(a=b=i=0;i<l;i+=3) E(,)&&E(,1)&&++a // if element i, i+1 and i+2 are all equal, increment a ||(E(,)||E(,1)||E(1,1))&&++b; // otherwise, if any two elements are equal, increment b *v=a; // set the first element in v to a v[1]=b; // set the second one to b } ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 9 bytes ``` .,2,`?.`/3@,`$$@ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWG_R0jHQS7PUS9I0ddBJUVBwgwlDZm5rRStHGOqY6ZkBsqmMOpM10LIA0CBrrmAD1mgChcaxSLFQHAA) ## Explanation ``` . Map ,2 [1,2] , length of `? find indices in . map `/ 3 split into chunks of 3 @ input , length of `$ deduplicate $ the chunk @ of the number (1 or 2) ``` [Answer] # [Elm](https://elm-lang.org/), ~~108~~ 106 bytes ``` import List.Extra as E m=List.map f x=m(\j->E.count((==)j)<|m(List.length<<E.unique)<|E.groupsOf 3 x)[1,2] ``` [Try it on Ellie](https://ellie-app.com/kR8yPsRw22Ha1) [Answer] # [Raku](https://raku.org/), 30 bytes ``` (+«*.rotor(3)».Set).Bag{1,2} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ/vQai29ovyS/CINY81Du/WCU0s09ZwS06sNdYxq/1srFCdWKiipxCvY2ilUpymoxNcqKaTlFynYGCmYKBgpmIIhiGWoYAyEhnY6CjbGQCEzsIQ5kDZTsADSIGgMVmgChMYQZcZgIRCEmGMGhqYIBSZgQXOgCZZgU6CSIOvs/gMA "Perl 6 – Try It Online") * `*.rotor(3)` breaks up the input list into groups of three elements. * `».Set` converts each of those groups into a `Set`. * `+«` converts each of those sets into its size. * `.Bag` makes a `Bag` (a set with multiplicity) out of those sizes. * `{1, 2}` looks up in that `Bag` the number of times sets with sizes of 1 and 2 were present. ]
[Question] [ # Intro Find the result of number cannibalism. Why was 6 scared of 7? Becase 7 `8` 9. Your program will have to find the result of applying the `8` operation(defined below) on a number, repeatedly. [Related](https://codegolf.stackexchange.com/questions/66603/why-was-6-afraid-of-7), [Sandbox](https://codegolf.meta.stackexchange.com/a/19390/80214) # Challenge Your input will be a single positive integer, n. You need to find each `8` in the integer, and substitute it for `+` or `-` based on the following conditions. * remove all `8`s at the beginning or end of the string. * If there are multiple `8`s, then collapse them into a single `8`. * \$a\$ and \$b\$ are the chunks to the left and right of the `8` respectively. Since `8` is an operator, the numbers are delimited by `8`. * If \$ a ≥ b,\$ `8` becomes `+`. * else, it becomes `-`. Then evaluate the expression from left to right, and take the absolute value. If the result has any `8`s in it, the repeat the above steps again till there are none. For example, `12384568789` becomes: ``` 123 456 7 9 123 < 456: 123 - 456 7 9 456 ≥ 7 : 123 - 456 + 7 9 7 < 9 : 123 - 456 + 7 - 9 = -335 = abs(-335) = 335 ``` Hence 335 is the final answer. # Example Input and Output ``` 789 → 2 180 → 1 42312348 → 4231234 2389687 → 66 12384568789 → 335 13749547874394873104972349 → 7309154 808 → 0 7800482 → 13 14458883442 → 1997 88888 → indeterminate 388182 → 2 08182 → 3 ``` Here are the testcases as an array: `[789,180,42312348,2389687,12384568789,13749547874394873104972349,808,7800482,14458883442,88888]` ## Scoring Criteria This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ8¡þDü@1š·<*OÄ ``` [Try it online](https://tio.run/##AToAxf9vc2FiaWX//86UOMKhw75Ew7xAMcWhwrc8Kk/DhP//ODEzNzQ5NTQ3ODc0Mzk0ODczMTA0OTcyMzQ5) or [verify all test cases](https://tio.run/##FYoxCsJAFAWvElLKL3b3v/W/BSEW9h5ALBQsrCwEIYWd5ADiBXIKG7HIYushvMiaTDUDczrv9sdDubRNXf26e1U3bfk@OPT5vcqvpf/0w3MxW@dbuUrZGJN4OkFQHxSUoExzmoxFxNGmQQ0pwmjQBJp6h2TjnoSOYnQODOKBSFKBIJwQJT3D9g8). **Explanation:** ``` Δ # Loop until it no longer changes: 8¡ # Split the integer on 8s # (which will use the implicit input-integer in the first iteration) þ # Remove all empty strings by only leaving digits D # Duplicate this list ü # For each overlapping pair [a,b]: @ # Check if a>=b (1 if truthy; 0 if falsey) 1š # Prepend a 1 to this list · # Double each value < # Decrease each by 1 (0 has become -1; 1 is still 1) * # Multiply the values at the same positions in the two lists O # Sum the list Ä # And take the absolute value of this sum # (after which the result is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 18 bytes ``` IŻṠo-× ṣ8LƇḌÇSAµÐL ``` [Try it online!](https://tio.run/##FcohDgIxFEVRz1o@Sdv/yn@VSJJxKBaAIZOgsZgaBA5LgsVOwgRHA/sYNlKKuzc5u23fH2pdvZ/TeN3Py2U2jTd2nzw9TiWvl6@hnLta8vd439RqTOLpBEF9UFCCMi1o0o6Irf5ADSnCaNAEmnqHZI0noaMYnQODeCCSVCD8AA "Jelly – Try It Online") Went through 5 or 6 other approaches before eval turned out to be the only one I could get to work... and then I tried a different spin on my second approach and it's 2 bytes shorter. Old version: `ṣ8LƇḌ<Ɲị⁾_+ż@ƲFVAµÐL` ``` IŻṠo-× Monadic helper link: Ṡ signs of I deltas Ż with prepended 0, o- replace all 0s with -1s, × pairwise multiply with argument. ṣ8LƇḌÇSAµÐL Main link: ṣ8 split (implicitly converted digit list) on 8s, LƇ remove empty slices, Ḍ convert digit lists from decimal, Ç apply helper link, S sum, A abs. µÐL Loop that whole thing until it doesn't change. ``` [Answer] # JavaScript (ES6), 76 bytes ``` f=n=>n.replace(p=/[^8]+/g,x=>t-=p<(p=+x)?x:-x,t=0)&&n-(t=t<0?-t:t)?f(t+''):t ``` [Try it online!](https://tio.run/##fdHBioMwEAbge59CPLQGm5pkRjORpj7IsgviatkiKm0ovr0rdPditDmGfMz/T27ls3xU95/B8a7/rqepsZ29dKd7PbRlVUeDTT6@6DNOrsfRXhy3w3m@i0dWjDkfj84Ktt93PHLWnUXBXe5Y0UQuPhxY7qaq7x59W5/a/ho1UajJhMH6YSxIkkDtFkKSeC/kUqACqQAp3BJ/D5ZOAZmMdLg5Kcu8cLPBdEZ@rRcBSD0DGk2KmjSCQdIgBRo95zHhy2gQRqZePBL0fhFi5y1bCCS1XUiCFw4xJSJAVOuFpDF6iYBIro/5/9TpFw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => // f is a recursive function taking n as a string n.replace( // we look for ... p = /[^8]+/g, // ... all groups of consecutive non-eight digits x => // for each group x: t -= // update t: p < (p = +x) ? // if the previous value is less than x: x // subtract x from t : // else: -x, // add x to t t = 0 // start with t = 0 ) && // end of replace() n - ( // if n is not equal to t, t = t < 0 ? -t : t // where t is first updated to its absolute value: ) ? // f(t + '') // do a recursive call with t (coerced back to a string) : // else: t // success: return t ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~27~~ ~~26~~ 25 bytes *Edit: -1 byte by using `S` combinator to recycle function argument, and moving helper function in-line, and then -1 more byte by a bit of rearrangement to be able to use `o` combinator instead of `()`* ``` ω(aΣSz*o:1Ẋȯ`^_1¬<mdfIx8d ``` [Try it online!](https://tio.run/##yygtzv7//3ynRuK5xcFVWvlWhg93dZ1YnxAXb3hojU1uSppnhUXK////DY2MLUxMzSzMLSwB "Husk – Try It Online") A *slightly* different approach to [Unrelated String's Husk answer](https://codegolf.stackexchange.com/a/213721/95126), ~~also 27 bytes~~. I'd held-off posting this for a bit, to give any new Husker a clean slate from which to try out this challenge... but now the Husketition is open... **How?**\* ``` mdfIx8d # helper function: splits input on 8s d # get digits of input x8 # split on 8 f # remove elements that are falsy for I # the identity function (so, remove empty elements) m # map over each element of the list d # combining digits as decimal number ωλaΣz*₁¹m`^_1ΘẊo¬<₁ # main program ω # repeatedly apply function until results are constant λ # lambda function taking one argument: a # get the absolute value of Σ # the sum of all elements of z* # element-wise multiplication of ₁¹ # (1) helper function applied to input # (so: the input split on 8s) m # (2) map this function to all elements of ₁ # helper function applied to input Θ # (with 0 prepended at the start) `^_1 # minus one to the power of Ẋ # the results for each pair of elements o # combine 2 functions ¬ # NOT < # second is greater than first ``` [Answer] # [R](https://www.r-project.org/), ~~89~~ 122 bytes *Edit: +33 bytes to convert to recursive function when I realized that it should repeat the `8` operation on its own output until there are no more `8`s. Doh!* ``` f=function(s)`if`(grepl(8,a<-abs(sum(c(1,-sign(diff(n<-sapply((n=el(strsplit(s,8)))[n>-1],as.double))))*n))),f(c(a,'')),a) ``` [Try it online!](https://tio.run/##fY9BbsIwEEX3OUUEC8Yoqex4gscS6UWqShhwkKVgIjss2gP0AD1iL0KN1AZCpXphWfO///sTLjvjvduazr3b5tI27dnvBnfyENnGtRs4BNt3QIVZl2YbIZ6PsANRlNEdPOxd24Jfl9H0ffcG4BvbQRxC7Ds3QCyIMfbin0vxWpj4tD@dt51NI7b06SralGSKxSI9DbvvATNRScJ6RYr0jOXzXMo6mxh@ha@Pz7yaSoL4KImphJVMyUij/jOYuhJbJ/RoWq2yf8tdPX8KCqlQ16hIodRISgqOWiXW7Y@SXIv6AU781o4/7sw5UnVbTj4gEWsikoh3Hq1VNs@niOsZHc7v7WDD0Xkz2LzJbQinMA2WROKOW2WXbw "R – Try It Online") Accepts argument `n` as a string. Errors for `n`s containing no non-8 digits/characters. [Answer] # [Python 3](https://docs.python.org/3/), ~~158~~ ~~148~~ ~~145~~ 138 bytes ``` x=input() while'8'in x: y=[int(f)for f in x.split('8')if f];x=str(sum([-1,1][y[i-1]<y[i]]*y[i]for i in range(len(y)))) print(abs(int(x))) ``` [Try it online!](https://tio.run/##FYzBDsIgGIPvewpuA@OMCIah7kkIh5kM9yeTEWARnh6hhzb50tbluO6WlZImsO6ImHS/FbalH3uwKD06lCcFNmJDzO6RQY1egtsg4tohYJDRzzSF6HE4vlgN9Ey1ygoGql81tD41b2NoYz/bz4K3xeJMqjrn2/v8DrhlqqgUygSXdy5GwZnko2D0yqW4MS7/ "Python 3 – Try It Online") *-10 bytes thanks to @pavi2410 and to me not being an idiot and accidentally leaving an extra space from the golfing suggestion* *and another -3 thanks to @pavi2410* *and another -7 thanks to @pavi2410* [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~149~~ \$\cdots\$ ~~139~~ 137 bytes Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved 8 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! ``` R;t=10;m;s;p;c;f(n){R=n;for(s=p=0;n;){for(m=1,c=0;n&&n%t-8;n/=t,m*=t)c+=n%t*m;s+=c>p?p:-p;for(p=c;n%t==8;)n/=t;}p=abs(s+c);R=p-R?f(p):p;} ``` [Try it online!](https://tio.run/##bVJNb@MgEL3nV4wipTI2Vuw4TUhnaQ@rlfaca5ODS3AbKSbIsJV3I//27GC7UbtaJASP9zEwQqWvSl2vW/Qyz7BGhxYVVpFhl600WJ2byEkrMzTILgHVMucq4Ls7M/OpQDOXntex9Ewlko5iCkmkerRP9iG1fYKVComRUiALcuysLF9c5BLFcCttun2qIsseLHbXo/FQl0cTscllAjTmMfws3zX4M@hWnX4dNLhzTVg7D6UD/6Z/Q9loOJXNq24IlwZCSjzv/WEbtO55DxIua7HhkIuMw3JR5ItiKTgsCrFZiTUHkRFaiyxbigWhMDgUQuQBrkXe4S1St1Yrrw9DKtH5LZHDasWBKuRFvxCZjU71VjYxNINpumt/LHbt5jvN@ymHz7iYjg7qH0Sh4NEcdEu2DMftN3DHP/pcRf3r2HxE8QARkqTXMRj6@HFxMBQyNKTn9/iV1kTfHvevwjakqaLp7ADpI9CdDftqb7R/L08UEb7Qf30ztzNkHIS0Pn9YqOx@tHST7voX "C (gcc) – Try It Online") ### Explanation (before some golfs) ``` t=10; // golf by storing 10 in t g(n){ // helper function takes int n for( ;n;){ // loops until n is zero s=p=0 // init sum s and previous p to 0 for( // inner loop calculates next rh value m=1, // init multiplier m to 1 c=0; // and current c to 0 n&& // loop until n is 0 n%t-8; // or most rh digit is 8 n/=t, // knock most rh digit off n m*=t) // and bump m by 10 each loop c+=n%t*m; // add next digit to current // building up number after // most right-hand 8 s+=c>p?p:-p; // after that's done update sum s for( // loop to strip off all rh 8's p=c; // also make previous = current n%t==8;) // loop until most rh digit isn't an 8 n/=t; // knock most rh 8 off n } // p=abs(s+c); // return abs value of sum with // positive most lh value } // f(n){ // recursive main function x=g(n); // calc first iteration x=x-g(x)? // is it different to next iteration? f(x): // if so iterate x; // else return value } // ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 59 bytes ``` y/8/ /;s/\d+/$&<$'?"$&-":"$&+"/ge;$_=abs eval$_.0;/8/&&redo ``` [Try it online!](https://tio.run/##LY1taoRADIb/zykGGSx02Z2PZEymtvQihcXiUASrorKwF@gBesQepNOpmh8h70OeZIpz79Oi5eVR6zrdNWup60W/tSetymf18Fqo8lw85X4q9Ees1fWleV9kvDW9ul5MnYWynGM7pkQc5M/Xt3TCstkmK9CBdYC8xSMIBxwqpo1VlciM0Wdw@ABeWCAMHokJISATWIOBsryvEJhgPQo2@2UjiI1BdvtbEBbRMzMgHigEEvxfW@yGNq5x/uyGZo0CmO2hut9xWrtxWNJ56v8A "Perl 5 – Try It Online") [Answer] # [J](http://jsoftware.com/), 53 bytes ``` |@('8'+/@(*_1x^0,2</\])@(,(*@#;._1#".;._1)~[=,)":)^:_ ``` [Try it online!](https://tio.run/##VY8xT8NADIV3foWVDsmVND2ffbF9UCkSEhMTK9AMVSvEwtoB8ddDkI@BwbLe96xn@2NphvYChwIt9BChrLUb4OH56XH5mrpW29v91G1nvB5jn@73r29h6vpuO23uhhk3zfDbwvfLoQ9NCccyL@HmfHr/hAS7AhcQNdfoGjW65kSYiJ1WoW6No9NEaqOKQ6JcE1bMeeVq4JZQNMw1CknYMosKk7EKYWSTNdyuPh19TmPdhvR3aYysqUIzqXnMWVWJOcG/z0gVNS0/ "J – Try It Online") ### How it works * `f^:_`: until the result does not change, do f. * `'8'…(,g[=,)":`: convert the input to a string, prepend `,` the character `8`, and execute `g` with this as the left argument, and a bit mask of `8` characters as the right argument. * `(…".;._1)~`: split the string into groups `u;._1`, which start with 1 in the bit mask and convert them back to numbers `".` (excluding the `8`). * `*@#;._1#`: because we could have empty groups (`888`), take `#` only those, whose length's `#` signum `*` is 1. (There might be a nicer approach.) * `2</\]`: compare `<` each group with its following, resulting a bit-mask. * `*_1x^0,`: prepend a 0 to the bit mask, and calculate `x*(-1)^y` for each group `x` with `y` being the result of the comparing. So we get `3 1 2 -> 3 1 _2`. * `|@…+/`: sum `+/` the result and take the absolute value `|`. [Answer] # [Scala](http://www.scala-lang.org/), ~~94~~ 90 bytes ``` i=>"[^8]+".r.findAllIn(""+i).map(_.toInt).scanRight(0){(a,b)=>if(a<b.abs)a else-a}.sum.abs ``` [Try it online!](https://tio.run/##lczBT4MwFAbwO3/Fk1MbXAujuLIICccl8@LV6PJgZXbpCqHVaJb97YhZMrn6nV6@9@XnGjQ4dvVRNR6eUFtQX17ZvYOq7@EcfKKBdg3bzh6gKKGy31AEnO9YRMKQMtcb7Ukoo@lutfFqmOq7grIT9mTHfLexflo1aJ/14d2TmJ4J3te0KHVL8LFmWDu6QFDGKcALcx@n32rURRm@vMnXKGTDBNt9ZczGTnak/2df6cWM7gdtvbGkJckylSJ7kCuZbymFazhP0yz4G8lY3n63cB7PJokQmZQyFWI5d5I8XwWX8Qc "Scala – Try It Online") -4 bytes by not using Java's cursed `split` method. ``` i=> //The input "[^8]+".r //Regex for operands .findAllIn(""+i) //Get all separate numbers in the input .map(_.toInt) //Turn them into integers .scanRight(0){(a,b)=> //Starting at the right, if(a<b.abs)a else-a} //Replace a with -a if a >= b.abs (this is different from the challenge, but it works because we call abs again later) .sum //Sum them up .abs //Take the absolute value ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 27 bytes ``` ω(aΣSz*(Ẋȯ`^_1±>Ṡ:←)mdfIx8d ``` [Try it online!](https://tio.run/##yygtzv5/aFvuo6bG/@c7NRLPLQ6u0tJ4uKvrxPqEuHjDQxvtHu5cYPWobYJmbkqaZ4VFyv///6PNLSx1DC0MdEyMjA2NjE0sdIyMLSzNLMx1gDwLE1MgC6TA2NzE0tTE3MLcxNjSxMLc2NDAxNIcqNxSx8LAQsfcwsDAxMJIx9DExNTCwsLYxMQoFgA "Husk – Try It Online") This isn't quite my first Husk answer, but it's a pretty clumsy direct translation of one of my attempted Jelly answers, so it could at least serve as a serviceable starting point for someone to swoop in and earn the bounty. ``` ω( Iterate until periodic: a absolute value of Σ sum of z* zipwith multiplication on: d decimal digits x8 split on 8s fI with empty slices removed md and converted back from decimal, S and the result of that ( Ṡ:←) with its first element duplicated Ẋ and with neighboring pairs mapped to `^_1 -1 to the power of ȯ ±> if the first is less than the second. ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 177 bytes ``` A=($(sed s/8/\ /g<<<$1));B=;while [ ${#A[@]} -ge 2 ];do [ ${A[0]} -ge ${A[1]} ]&&C=+||C=-;B=$B${A[0]}$C;A=(${A[@]:1});done;R=$(bc<<<$B$A|tr -d -);grep -cq 8 <<<$R&&f $R||echo $R ``` It has to be stored as function `f` or in file `f` in the current working directory. [Try it online!](https://tio.run/##LU/LbsIwEDw3XzGiVhSriojjpd7UpGrgxBVxAw4lD0CqkhaoeiB8e2oj9jS7O5rH7vN8GJrftrwcuxZNJHEdijwS0bmucB7zeIPxfjqdCiWlneX273D8qrGGuD4X64/tDfG@Roqtrbr7tVgnj6PHyuFtGM7zl76f57ETELMHR8yt97l6lTd1k06gre0yF9Gu9H4zUfSXE@IKsbT7U/2NuPwBw/@WYdhALPu@Lg@dA8MtCFZ5BMMZFCegVKtUEyPVnL2ygduYJg55gjaUTciwIZ0RG60SyoyjZ@CEnUaSEKdQRBNm1kQp2A9k0HQnLHBsXbeVL29RdcHTPcRILBC/Q0Qu2EKObODrDP8 "Bash – Try It Online") [Answer] # PHP, 290 bytes (Guess you shouldn't golf in php. :) ) ``` <?php $n=$_SERVER["argv"][1];while(false!==strpos($n,'8')){$n=abs(array_reduce(str_split(preg_replace('|8+|','8',trim($n,'8')).'8'),function($c,$i){if($i!=8){$c[1]*=10;$c[1]+=$i;}else{$c[2]+=$c[1]*((!isset($c[0])||$c[0]>=$c[1])?1:-1);$c[0]=$c[1];$c[1]=0;}return$c;},[null,0,0])[2]);}echo$n; ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/d624e56da25e682d5cb6e4e2516977583918ba9f) ## Ungolfed: ``` <?php $n = $_SERVER["argv"][1]; $f=function($c, $i){ if($i!=8) { $c[1]*=10; $c[1]+=$i; } else { $c[2] += $c[1] * ( (!isset($c[0]) || $c[0]>=$c[1])?1:-1); $c[0]=$c[1]; $c[1]=0; } return $c; }; while(false!==strpos($n,'8')) { $n = trim($n, '8'); $n = preg_replace('|8+|', '8', $n); $a = str_split($n.'8'); $n = abs(array_reduce($a, $f, [null, 0, 0])[2]); } echo $n; ``` ## Explanation: I use array\_reduce to walk over every digit, and use an array as carry to have 3 datapoints carried on: the variables $a, $b and $sum, though they are unnamed as the elements of $c. If the current digit is a non-8, I "add" it to my "$b", otherwise I first compare $b to $a, add/subtract $b from $sum, and move the content of $b to $a. [Answer] # [Red](http://www.red-lang.org), 142 bytes ``` func[n][while[find to""n"8"][b: to[]load form split to""n"8"forall b[if b/2[b/1: reduce[b/1 pick[- +]b/1 < b/2]]]n: absolute do form b]to 1 n] ``` [Try it online!](https://tio.run/##PY/dbsMgDIXv8xQWt1PU/NDVzaY9xLQ75AsIpEWlEBGiPX5GSDXf@HzW8ZEdjd6@jRZUTQNs0@pH4Un83q0zYrJeQwqMeYaMhBoyCHJBaphCfMIyO5v@DXkknQMl7ATq1Al1aocqGr2OZtcw2/EhanijHT53CxH5AaRagluTAR2OWEUpQAuetiqzkeMdPIgKcl3wWnqLTem869uu51ig6/H6jpfDkIGfM70WsMFXQNNw7A4P52dE7Dk/@ANwr6Ly5yaZ@LRe5stq@In2djNxAenBxBhi2egR2xxGAuZofRLlfA@s/mIwZUG0/QE "Red – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 32 bytes ``` .,{8`%(~:x\{~.x\:x<2*(*-}/abs`}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0@n2iJBVaPOqiKmuk6vIsaqwsZIS0NLt1Y/Mak4oVbr/39DY3MTS1MTcwtzE2NLEwtzY0MDE0tzI2MTSwA "GolfScript – Try It Online") Every time the algorithm is executed, the number either stays the same or it gets at least 1 digit shorter. This means we can execute the algorithm once for every byte instead of testing if it has an 8. ``` ., # Get the number of bytes in the input { }* # Execute this block that many times 8`% # Split the string around the 8s and remove the empty strings # This simultaneously executes the first 3 steps (~ # Get the first number :x # Store it in the variable x \{~ }/ # For each number left in the array .x # Copy it and push x \:x # Store the current number in x < # Compare the two numbers 2*( # 1 if previous<current and -1 if previous>=curret *- # Multiply and subtract abs` # Parse the absolute value to a string ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 37 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @=q8 f;=äÈn ¨Y?Y:-Y}Ug)x a s ,Uø8}f U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QD1xOCBmOz3kyG4gqFk/WTotWX1VZyl4IGEgcyAsVfg4fWYgVQ&input=LW0KWyI3ODkiLCIxODAiLCI0MjMxMjM0OCIsIjIzODk2ODciLCIxMjM4NDU2ODc4OSIsIjEzNzQ5NTQ3ODc0Mzk0ODczMTA0OTcyMzQ5IiwiODA4IiwiNzgwMDQ4MiIsIjE0NDU4ODgzNDQyIiwiODg4ODgiLCIzODgxODIiXQoiNzg5IFx1MjE5MiAyCjE4MCBcdTIxOTIgMQo0MjMxMjM0OCBcdTIxOTIgNDIzMTIzNAoyMzg5Njg3IFx1MjE5MiA2NgoxMjM4NDU2ODc4OSBcdTIxOTIgMzM1CjEzNzQ5NTQ3ODc0Mzk0ODczMTA0OTcyMzQ5IFx1MjE5MiA3MzA5MTU0CjgwOCBcdTIxOTIgMAo3ODAwNDgyIFx1MjE5MiAxMwoxNDQ1ODg4MzQ0MiBcdTIxOTIgMTk5Nwo4ODg4OCBcdTIxOTIgaW5kZXRlcm1pbmF0ZQozODgxODIgXHUyMTkyIDIi) * takes input as a string, it can be easily modified to take input as a number but it won't work with big numbers ''' ``` @=q8 f;=äÈn ¨Y?Y:-Y}Ug)x a s ,Uø8}f U @....}f - return first number which return false when passed through @... =q8 f; - input splitted on 8 and empties removed =äÈ...}Ug) - pass each consecutive values through È , but prepend first value before so that they are >= n ¨Y?Y:-Y - 1st to number compared to 2nd: return 2nd (negated eventually) x a s - reduce->abs->to string The above is assigned to U while the funxtion returns.. Uø8 - contains 8? => repeat Finally we return U ``` ''' [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~60~~ ~~43~~ 38 bytes -22 bytes thanks to Traws ``` {a|-a:+/{x*1-2*>':x}.:'(~^.)#"8"\$:x}/ ``` [Try it online!](https://tio.run/##FYo7DoMwEAWvsoJIBiKD90N4uMhJokg0NBS0SJBc3dlM9eZptrhvpaz5XK645PtwHh1H6Z4hH58@h@b77tu6QvW6@TGUNdCEmRiJTJRFDSSK@YGJ3GCjLw@Q4GFKBiE2GwGomRD@kAIMKT8 "K (oK) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` {`8+ - ^-|-$ \d+ $* (?=-(1*))(?<=\1)- + O`\D1* \+ 1>`- (1+)-\1 1 ``` [Try it online!](https://tio.run/##FYgxCgIxFAX7d44Vkg0f8pOseQuu2wiWXiBIBC22sRA7vXuMU83M6/Henre2M@faPpUOgqt8ZQDK3WEYYdZFjI7WmvWwFLUCh0stJx1RHKDHKoBRZ6Voz9YyZyg9QuS8Z4Z2SVO3/umJTO8TAzSliWRMKYB/EEll@AE "Retina 0.8.2 – Try It Online") Link includes smaller test cases (Retina has to do subtraction in unary, which is too slow for the larger cases). Explanation: ``` {` ``` Repeat until there are no `8`s left. ``` 8+ - ``` Convert each runs of `8`s to a `-`. ``` ^-|-$ ``` Delete leading and trailing `-`s. ``` \d+ $* ``` Convert the remaining numbers to unary. ``` (?=-(1*))(?<=\1)- + ``` Replace each `-` with a `+` unless the following number is greater. ``` O`\D1* ``` Sort the numbers to be added to the beginning and the numbers to be subtracted to the end. ``` \+ ``` Add all the numbers to be added together. ``` 1>`- ``` Add all the numbers to be subtracted together. ``` (1+)-\1 ``` Take the absolute value of the difference. ``` 1 ``` Convert it to decimal. ]
[Question] [ Write code that when given a positive number \$x\$ as input, outputs the largest positive divisor of \$x\$ less than or equal to the square root of \$x\$. In other words find the largest \$n > 0\$ such that \$\exists m\geq n:m\cdot n=x\$ (Exists \$m\$ greater than or equal to \$n\$ such that \$m\$ times \$n\$ is \$x\$) --- For example if the input were \$12\$ the divisors are \$1\$, \$2\$, \$3\$, \$4\$, \$6\$, and \$12\$. \$1\$, \$2\$ and \$3\$ all multiply by larger numbers to get \$12\$, but \$3\$ is the largest so we return \$3\$. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being considered a better score. ## Test Cases ``` (1,1) (2,1) (3,1) (4,2) (5,1) (6,2) (7,1) (8,2) (9,3) (10,2) (11,1) (12,3) (13,1) (14,2) (15,3) (16,4) (17,1) (18,3) (19,1) (20,4) (21,3) (22,2) (23,1) (24,4) (25,5) (26,2) (27,3) (28,4) (29,1) (30,5) (31,1) (32,4) (33,3) (34,2) (35,5) (36,6) (37,1) (38,2) (39,3) (40,5) (41,1) (42,6) (43,1) (44,4) (45,5) (46,2) (47,1) (48,6) (49,7) (50,5) ``` [OEIS A033676](http://oeis.org/A033676) [Answer] # [Python3](https://www.python.org/), 49 47 bytes ``` def f(x): l=x**.5//1 while x%l:l-=1 return l ``` # Explanation * `l=x**.5//1` → Assign `l` the largest integer less than equal to the square root of `x` * `while x%l:l-=1` → While `l` does not evenly divide `x`, decrement `l`. ### Edits * Mention Python3, not Python2 * Use `...//1` to save two bytes. (Decimals are okay! Thanks @Rod) [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` Z\tn2/) ``` [Try it online!](https://tio.run/##y00syfn/PyqmJM9IX/P/f0MLAA "MATL – Try It Online") For this explanation, we will use '12' as a sample input. Explanation: ``` Z\ % Divisors. % Stack: % [1 2 3 4 6 12] t % Duplicate. % Stack: % [1 2 3 4 6 12] % [1 2 3 4 6 12] n % Number of elements. % Stack: % 6 % [1 2 3 4 6 12] 2/ % Divide by 2 % Stack: % 3 % [1 2 3 4 6 12] ) % Index (grab the 3rd element) % 3 ``` This works because of a lot of lucky coincidences. 1. MATL uses 1 indexing 2. If we index with a non-integer (this will happen for any perfect square input), then `<n>)` will index \$\lceil n \rceil\$ [Answer] # [C (gcc)](https://gcc.gnu.org/) `-lm`, 35 bytes ``` i;f(n){for(i=sqrt(n);n%i;i--);n=i;} ``` [Try it online!](https://tio.run/##HYvBCoMwEETv@YogBHYxOUihl61/4kUikQFN2@hN/PWmq3N6M8yLYY6xVkiizEd6F0K/fcuuTbKDIASFHnLWdUQmNoexGuTdQszNalnVOsHr8RS0Ld/zlU/RY6KG3OTdxENuPHwiMIs56y@mZZy3Gpb1Dw "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` Ñ2äнθ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8ESjw0su7D234/9/QyMA "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##ASUA2v8wNWFiMWX/NTBMdnn/w5Eyw6TQvc64/3kiKMO/LMO/KSIs/zEy) **Explanation** ``` Ñ # push the list of divisors 2ä # split it into 2 parts н # take the first haft θ # take the last element of that ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~16~~ ~~14~~ 12 bytes I'm glad I was able to write some answer in APL since I only just learned it. Many, many thanks to Adám for help with golfing. Golfing suggestions very much welcome. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPh371o97Nj3q6HvVu1Tq83aj2UceKR12L/qc9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P9pCkYGXAA "APL (Dyalog Unicode) – Try It Online") To learn more about APL, take a look at [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard). **EDIT:** -2 bytes to fixing a problem with my code. Thanks to H.PWiz for pointing out that problem. -2 bytes from shortening everything again. ``` ⌈/{⍳⌊⍵*÷2}∨⊢ ``` **Ungolfing** ``` ⌈/{⍳⌊⍵*÷2}∨⊢ ∨ GCD of the following... ⊢ The right argument, our input. {⍳⌊⍵*÷2} ⍵ Our input. *÷2 To the power of 1/2, i.e. square root. ⌊ Floor. ⍳ Indices up to floor(sqrt(input)). In total, range from 1 to floor(sqrt(input)). ⌈/ The maximum of the GCDs of our input with the above range. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` →←½Ḋ ``` [Try it online!](https://tio.run/##yygtzv7//1HbpEdtEw7tfbij6////8amAA "Husk – Try It Online") ### Explanation ``` →←½Ḋ Ḋ Divisors of (implicit) input. ½ Bisect. →← Take the last element of the first half. ``` [Answer] # [R](https://www.r-project.org/), ~~45~~ 33 bytes ``` function(x,y=1:x^.5)max(y[!x%%y]) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqfS1tCqIk7PVDM3sUKjMlqxQlW1Mlbzf3FiQUFOpYahlamBTprmfwA "R – Try It Online") Original: ``` function(x,y=x/1:x^.5)max(which(y==floor(y))) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQqfStkLf0KoiTs9UMzexQqM8IzM5Q6PS1jYtJz@/SKNSU1Pzf3FiQUFOpYahlamBTprmfwA "R – Try It Online") [Answer] # x86 32-bit (IA32) machine code: ~~18~~ 16 bytes changelog: handle the `n=1` test case correctly, save 2 bytes, and return in EAX. **Count up until `n/i <= i` (i.e. when we reach the sqrt), and use the first exact divisor after that.** A 64-bit version of this is callable from C with the x86-64 System V calling convention, as `int squarish_root_countup(int edi)`. `nasm -felf32 -l/dev/stdout squarish-root.asm`: ``` 58 DEF(squarish_root_countup) 59 ; input: n in EDI 60 ; output: EAX 61 ; clobbers: eax,ecx,edx 62 .start: 63 00000025 31C9 xor ecx, ecx 64 .loop: ; do{ 65 66 00000027 41 inc ecx ; ++i 67 00000028 89F8 mov eax, edi 68 0000002A 99 cdq 69 0000002B F7F9 idiv ecx ; edx=n%i eax=n/i 70 71 0000002D 39C1 cmp ecx, eax 72 0000002F 7CF6 jl .loop ; }while(i < n/i 73 ; || n%i != 0); // checked below 74 ; falls through for i >= sqrt(n) 75 ; so quotient <= sqrt(n) if we get here 76 77 ; test edx,edx / jnz .loop 78 00000031 4A dec edx ; edx-1 is negative only if edx was zero to start with 79 00000032 7DF3 jge .loop ; }while(n%i >= 1); 80 ; falls through for exact divisors 81 82 ; return value = quotient in EAX 83 84 00000034 C3 ret 0x10 bytes = 16 bytes. 85 00000035 10 .size: db $ - .start ``` [Try it online!](https://tio.run/##5Vbfb9NIEH73XzGHGiVWSFsXrkBMKgUoKA9cTxDuToLKWtvjZDln191dJ24P/vbe7Np1kssF@sQLlqx4Zmdn58f3zYZpjYs4vx4Iphe3t50UMy4QXp2/7mWlSARboA93X0OY5TJmeavwPC8MIXgC8bVBDZlU8OhkEHPzEIJnTjx9bMVDgN6f3Mzho0p5P7gEmUEiS6XR9@xR@qpkiut5pKQ0Ea0Ik8qV8D2gJwQuitIMQdAHnL@aNFpZGqc@f/lXo0kouhiVHgKy6iEm9KaVd6gNU2bobHJk9scuwUesY3EnjEQ/sCtaQsaVNsANKma4FJBKSk3AEb1GwpyJNEcwcwQxCiBhGr3DXMpiCP/zhLT7H88dnWLSHL1rNBhwZ7OQS2dD0QNF53RJeuV@ecqX@/ZTmiPR4c3ekTji9ZnJomjTpQWn@zxzm1zMmz6@ruY8xx6HM7D7Ye8Trj@/fAF77C8jOPZJfXQEyRyTvzGFGHO5atqSsTzXVDEly9ncoYLD8xHoK2V61ONvHkWwMjY920lqwWdx04S@VdO02qnHIABObcMZNXGJIEV@DTxzpium4QaVtO102IAVYbMpDu7WZl0cm@zZCAI/3JsaViwxQL3iWirtNXZVMp@1jXUdDEGhKVWN6QbBpCG08hsiWhrDAQygxq6lGQSn2/x6ssEv6Ln8Apj89nIvo8rinnwa359PFYXQAiyp7scELvYzod//gUzIv8OE5z@CCWdrJtRGNIKuSmk4CrNBEwveFcIMDcxR4U/BmoYhS5aXCKN1VSxsx9@ljNfhGU8FRNHFh@nvH6bR64t3b8fTKCIE5NmjEy98MZm@J0J5d7ceXU4ObK2sSdYbMqsceFo5JjnekAmRlgVrf5Ut3Ya/gvwVrTx@9@aPwGr6T70O5nSTbK@QfT84pSWR8owSYjmfCRoELnPL8sjl6m9RMoTp5MJdWqJroFByyVOEg@6nMugClfrBQa9QXJgMup24C91PVfeA@w/A9YGpma691ASkitBF6aK5bPU3lUMPrdhr393pl94Ga93Sya9ualnqUbfpYt0aSMvgDiN1j7Xr6ftJvaNxE1uuUvn3u2n/KfzXEw3UHU/UGO@bjspiJ6IGZZtuWLXO1Y6noK6LnYTWwOKhHnIGjqunx02a@lpHWHHTDuYe9/1mmMP4xeT29l8 "Assembly (nasm, x64, Linux) – Try It Online") with an asm caller that uses the first byte of argv[1] as an integer directly, and uses the result as process exit status. ``` $ asm-link -m32 -Gd squarish-root.asm && for i in {0..2}{{0..9},{a..f}};do printf "%d " "0x$i"; ./squarish-root "$(printf '%b' '\x'$i)"; echo $?; done 0 0 # bash: warning: command substitution: ignored null byte in input 1 1 2 1 3 1 4 2 5 1 6 2 7 1 8 2 9 3 10 0 # this is a testing glitch: bash ate the newline so we got an empty string. Actual result is 2 for n=10 11 1 12 3 13 1 14 2 15 3 16 4 ... ``` [Answer] # Japt `-h`, ~~8~~ 6 bytes ``` â f§U¬ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=4iBmp1Ws&input=MjAKLWg=) 2 bytes saved thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) --- ## Explanation ``` :Implicit input of integer U â :Divisors of U f :Filter § : Less than or equal to U¬ : Square root of U :Implicitly get the last element in the array and output it ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ọⱮ½TṪ ``` [Try it online!](https://tio.run/##ASoA1f9qZWxsef//4buN4rGuwr1U4bmq/8OH4oKs//9bMTAwMCwyNiwyNSw0OV0 "Jelly – Try It Online") [Answer] # JavaScript ES7, ~~33~~ 31 bytes ``` n=>(g=x=>n%x?g(x-1):x)(n**.5|0) ``` [Try it online](https://tio.run/##BcFLCoMwEADQq3RTmNE66MJNYVJ6jlIwaAzxMyNJKRF69/S9xX5tGmM4Po3o5MrMRdiA58xGrvnhITcd3jOCVBX1vxbLqJJ0c7SphxcRPWO0J/Qt0urOBPim3R4Q2MxQ1wGRFg0y3C4Dlj8) [Answer] # [Snowman](https://github.com/KeyboardFire/snowman-lang), 38 bytes ``` ((}1vn2nD`#nPnF|:|NdE|;:,#NMo*|,;bW*)) ``` [Try it online!](https://tio.run/##NYw9D4IwGIT3/oo3UlMgCELiwoeTuklIHFwFWkIH3xJodLD41xFIvOVyl7unKod2qhUXGbXrUkOasiWxybbH8IURnh4WFngxscn52SSxZ@VX5Rovqe6u46xX4pBG9SBBInxC3z/sR8IVgVldL1E3wLYRh@wIDKhc@0B1OhhQvZ8l/h12AjZfKl26QC19G4rNOhZ1q2YgiukH) ``` (( } activate variables b, e, and g 1vn2nD` e=1/2 # retrieve the input into b nP set b=b^e, which is sqrt(input) nF floor the square root | move b into g so there's space for a while loop : body of the loop |NdE| decrement the value in g ;: loop condition ,# assign b=input, e=current value NMo store the modulo in g *| discard the input value and place the modulo in the condition slot , put the current value back into g ;bW continue looping while the modulo is nonzero * return the result )) ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 24 ``` ?dsnv1+[1-dlnr%0<m]dsmxp ``` [Try it online!](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnUG2gp2dqUKtgZmluaa2Qks9VUJSZV5KmoKSaoqBrp6CkoAJTzZWanJGP4CrUKKQkK@imqv@3TynOKzPUjjbUTcnJK1I1sMmNTSnOrSj4r86Vkp@X@h8A "Bash – Try It Online") ### Explanation: ``` ? # read input d # duplicate sn # store copy 1 in register n v # take the square root of copy 2 1+ # add 1 [ ] # define macro to: 1- # subtract 1 d # duplicate ln # load from register n r # reverse top 2 stack members % # calculate modulo 0<m # if not 0, recursively call macro m again d # duplicate macro sm # store copy 1 in register m x # execute copy 2 p # print final value ``` [Answer] # J, 24 19 bytes *-5 bytes thanks to Sherlock's GCD idea* ``` ([:>./+.)1+i.@<.@%: ``` [Try it online!](https://tio.run/##HU/LCsJADLz3K4IgtT623SR9olIQPHnyWsWDKOrF/z@tM7KEbDIzmeSTZiF/ym6QXNZSyYDYBDmcT8e0mIZ9KFehiKt3GLdhnA@pyLLH/fWVZSk3lcVznHbXorxIxFOEIRy/GrlBbpE75J5IRQqZUVmSG0mONcsGwkh@7Fj2nFhxGKeqgqdUqLNXw0FpoC3Rjj0qrAJg9DBFzwyo0cOosAZLGT2MSxm3ciqcCleg/r@AHk6F08Op8I5oj4tqKLKYpR8 "J – Try It Online") # original answer ``` ([:{:]#~0=]|[)1+i.@<.@%: ``` [Try it online!](https://tio.run/##HU9BasNADLz7FSKhOE4ae1eS7fUSg6HQU065uqaHUtP20gek9OvuTFmEVpoZjfS17epylTFLKY8SJCPOtTzdrs/bYc73vOx/w7j8zFU8fdbTpZ4e8lYVxfvbx7ccG3lVOazTPC5V8yIRTxGGcPxa5A65R07IA5FACplRWZIbSY4tyw7CSH5MLAdODBzGqargKRXq7LVwUBpoTzSxR4UFAEYPU/TMgBo9jArrsJTRw7iUcSunwqlwBer/F9DDqXB6OBWeiA64qIWiiMX2Bw "J – Try It Online") ## parsed ``` ┌───────────────────────────────┬──────────────────────┐ │┌──┬──┬───────────────────────┐│┌─┬─┬────────────────┐│ ││[:│{:│┌─┬─────┬─────────────┐│││1│+│┌─────────┬─┬──┐││ ││ │ ││]│┌─┬─┐│┌─┬─┬───────┐││││ │ ││┌──┬─┬──┐│@│%:│││ ││ │ ││ ││#│~│││0│=│┌─┬─┬─┐│││││ │ │││i.│@│<.││ │ │││ ││ │ ││ │└─┴─┘││ │ ││]│|│[││││││ │ ││└──┴─┴──┘│ │ │││ ││ │ ││ │ ││ │ │└─┴─┴─┘│││││ │ │└─────────┴─┴──┘││ ││ │ ││ │ │└─┴─┴───────┘│││└─┴─┴────────────────┘│ ││ │ │└─┴─────┴─────────────┘││ │ │└──┴──┴───────────────────────┘│ │ └───────────────────────────────┴──────────────────────┘ ``` ## explanation * `1 + i.@<.@%:` gives the range `1 .. floor(sqrt)`. * the entire verb `(A) B` forms a hook, with the above range passed as the right arg `]` to A and the original number passed as its left arg `[`. Thus... * `] | [` gives the remainer of each item in the range divided into the original arg. * and `0 = ] | [` gives the divisors with no remainder. * `] #~ ...` then filters the range, leaving only those. * and `{:` gives the last item in the list, ie, the largest one. [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` n=k=input() while(k*k>n)+n%k:k-=1 print k ``` [Try it online!](https://tio.run/##K6gsycjPM/pfnpGZk6pgaJVakZqspKT0P8822zYzr6C0REOTCyynka2VbZenqZ2nmm2VrWtryFVQlJlXopD9H6TaxJzLxILLxJLL1AAA "Python 2 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 5 bytes ``` K'?√≤ ``` [Try it online](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiSyc/4oia4omkIiwiIiwiMTAiXQ==), or see [a flagless MATL port](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJL4oKFwr1pLyIsIiIsIjI4Il0=). Explanation: ``` K # Factors ' # Filter by: √ # Square root of ? # The input ≤ # Is less than or equal to the input # Get the greatest item with the G flag ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ½ḍƇµṪ ``` [Try it online!](https://tio.run/##ARwA4/9qZWxsef//wr3huI3Gh8K14bmq/zUww4figqz/ "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 36 bytes ``` f x=[z|y<-[1..],z<-[1..y],y*z==x]!!0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwja6qqbSRjfaUE8vVqcKwqiM1anUqrK1rYhVVDT4n5uYmWdbUJSZV6KSpmBo8B8A "Haskell – Try It Online") Well this is my answer to this challenge. This uses a particular list comprehension to find the answer. In our list comprehension we pick \$y\$ from the infinite list `[1..]` that is the positive integers, and we pick \$z\$ from the list `[1..y]`. This means that \$(y,z)\$ is all the ordered pairs such that \$y \geq z\$. We then select only those pairs such that \$y\cdot z=x\$, meaning that we make the list of all pairs of numbers that multiply to \$x\$. Now since our comprehension is based first on \$y\$ and then \$z\$ this means that our pairs are in ascending order of \$y\$, or more usefully in descending order of \$z\$. So to get the largest \$z\$ we take the \$z\$ belonging to the first element. This is our result. [Answer] ## QBasic (4.5), 52 bytes ``` INPUT x FOR i=1TO sqr(x) if x/i=x\i then m=i next ?m ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 53 bytes The shortest way seems to be using the floating point stack and `fsqrt`, the shortest I could get without it was 62 bytes using `/mod` and checking if the quotient was greater than the divisor. ``` : f dup s>f fsqrt f>s 1+ begin 1- 2dup mod 0= until ; ``` [Try it online!](https://tio.run/##HYxBDoMgAATvfcXEawMpJr1o6l8siCWlQgETf0@xpz3MzNqQykus9pxaByxmj@TJYvM3FeyUUVeey@o2lKA/8ScYbg/2rTjP2Kr4r3pkQnYgJrr2JNGJ8TJwcFcoTMA1VftlTrnM@o0PITbjqD8 "Forth (gforth) – Try It Online") ### Explanation 1. Calculate the square root 2. Starting at the square root, decrement by 1 until we find a factor of the original number ### Code Explanation ``` : f \ Start a word definition dup \ duplicate the input s>f fsqrt \ move the number to the float stack and get the square root f>s \ truncate result and move to integer stack 1+ \ add 1 to the square root begin \ start indefinite loop 1- 2dup \ decrement divisor and duplicate input and divisor mod \ calculate n % divisor 0= until \ if result equals 0 (no remainder) end the loop ; \ end the word definition ``` [Answer] # F#, 55 49 bytes ``` let f x=Seq.findBack(fun i->x%i=0.0){1.0..x**0.5} ``` [Try it online!](https://tio.run/##LY7NCsIwEITveYqlUGiKDfHQm81B8C54FA@hJrLYphrbUtE@e8yPp11mZ78Z/arawSrnOjWChqU5qSfTaK572d4LPRnASiw5Npxx@tkyzthSlpzVa/x4WDSjsjDLblLQEI9I61eAv5Awo0cbyIocN5AjzaDwSjJSQs67gxnt@zh4UVxIwPYSDUh7mwMypda@wBp5oSGG0H84Ae5@) `Seq.findBack`: Returns the last element for which the given function returns `True`. The function in this case checks to see if a number is a factor of the value. [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 144 bytes ``` {({}{}<<>({}<>)<>([({})()]<>({}(<>)())){(<{}({}[()]{}<({}())>)>)}{}((({}<>)<>(({})))[({}[{}])])>[({<({}[()])><>({})<>}{}<><{}>)])}{}{}<>{}({}<>) ``` [Try it online!](https://tio.run/##PY2xDoBACEN/h44mNxJ@5HKDumhMHFwJ347lYgxDodDH9qznfaz7leni4aFqVDVQOzsIxrSEngBwUQ4enQse1gYwFsMif7aiQBG6x8CAsdcvB5tI3tVHI9Boxvxvk05IZi6tvQ "Brain-Flak (BrainHack) – Try It Online") I'm not really sure this answer is very good. I feel like there may be a nice way to solve this task however I'm just not clever enough. ## Explanation I tried to do an exploded view of the answer but there are so many moving parts it was not very enlightening, so here is an explanation of what the code does. The first important bit is this ``` ({}<>)<>([({})()]<>({}(<>)())){(<{}({}[()]{}<({}())>)>)}{} ``` This takes the two numbers on top of the stack and if they are unequal increments the second one, if they are equal it increments the first one and replaces the second one with zero. If we repeat this code a bunch we will get all the pairs \$(x,y)\$ such that \$x \geq y\$. The next part is multiplication, taken with modification from [the wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki/Basic-Arithmetic-Operations). This multiplication is special because it preserves the existing values without destroying them. It goes like: ``` ((({}<>)<>(({})))[({}[{}])])({<({}[()])><>({})<>}{}<><{}>) ``` So we are multiplying all these ordered pairs. For each result we check if it is equal to the input. If so we terminate and return the smaller item in the pair. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ÆDŒHḢṪ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm8vRSR4Pdyx6uHPV////TQ0A "Jelly – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 26 bytes ``` $\=0|sqrt;$\--while$_%$\}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxtagpriwqMRaJUZXtzwjMydVJV5VJaa2@v9/I5N/@QUlmfl5xf91CwA "Perl 5 – Try It Online") [Answer] # Rust, 71 70 bytes ``` fn f(x:u64)->u64{let mut l=(x as f64).sqrt()as u64;while x%l>0{l-=1}l} ``` ## Pre-uglified version ``` fn f(x: u64) -> u64 { // function takes u64, gives u64 let mut l = (x as f64).sqrt() as u64; // l takes integer'ed root value while x % l > 0 { // loop while l leaves remainder l -= 1 // decrement } l // return the found value } ``` ### Edits * Save a byte with `> 0` over `!= 0`. (Thanks to @CatWizard) [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` â w æ§Uq ``` [Try it online!](https://tio.run/##y0osKPn///AihXKFw8sOLQ8t/P/f2AwA "Japt – Try It Online") [Answer] # [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 49 bytes ``` ....).... ...@_)... ..IEdF).. .2)1/)IE. ^>{m..... ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8INEEEFxA7xGtCWJ6uKW6aIJaRpqG@pqerHlecXXUuSJne//@GRgA "Triangularity – Try It Online") [Answer] # [Pyret](http://www.pyret.org), 93 bytes ``` {(z):rec f={(i,x):if num-modulo(i, x) == 0:x else:f(i,x - 1)end} f(z,num-floor(num-sqrt(z)))} ``` You can try this online by copying it into [the online Pyret editor](https://code.pyret.org/editor)! The above evaluates to an anonymous function. When it is applied to an integer, it returns a result according to the specification. [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes Based on [my APL answer here](https://codegolf.stackexchange.com/a/167182/47581). Golfing suggestions welcome! [Try it online!](https://tio.run/##S0wuKU3Myan8/9/6Uccsn6BHMxvSff//NzIAAA "Actually – Try It Online") ``` ;√LR♀gM ``` **Ungolfing** ``` ;√LR♀gM Implicit input n ; Duplicate n √ sqrt(n) L floor(sqrt(n)) R 1..floor(sqrt(n)) ♀g gcd(n, foreach(1..floor(sqrt(n))) M The maximum of the GCDs. Return this maximum. ``` [Answer] A port of [this Mathematica answer](https://codegolf.stackexchange.com/a/18355). # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ½ðḞ³÷Ċ³÷µÐL ``` [Try it online!](https://tio.run/##y0rNyan8///Q3sMbHu6Yd2jz4e1HukDkoa2HJ/j8///fyAwA "Jelly – Try It Online") This (11 bytes) also works, and don't depend on `³`: ``` ½Ḟ÷@Ċ÷@ʋƬµṪ ``` Unfortunately `½Ḟ÷@Ċ÷@ʋÐL` (10 bytes) doesn't work. And apparently `Ƭ` and `ÐĿ` is not exactly the same (when the link is dyadic) --- Method: (let \$n\$ be the input) * Start with an upper bound \$i = \sqrt n\$ of the answer \$a\$. * At each step: + If \$i\$ is not an integer, then the upper bound can be made \$\lfloor i\rfloor\$ (because the result must be an integer) + If \$n\over i\$ is not an integer, then \$a \le i \Rightarrow \frac n a \ge \frac n i \Rightarrow \frac n a \ge \lceil \frac n i \rceil \Rightarrow a \le n \div \lceil \frac n i \rceil \$. * So we repeatedly replace \$i\$ with \$n \div \lceil \frac n {\lfloor i\rfloor} \rceil\$ until it's fixed. ]
[Question] [ Given a positive integer, find its smallest positive integer multiple which is a run of 9 followed by an optional run of 0. In other words, find its smallest positive integer multiple which is matched by the regex `/^9+0*$/`. For example, if the given positive integer is 2, then return 90, since 90 is a positive integer multiple of 2 and is the smallest which is matched by the regex `/^9+0*$/`. Test cases: ``` n f(n) 1 9 2 90 3 9 4 900 5 90 6 90 7 999999 8 9000 9 9 10 90 11 99 12 900 13 999999 14 9999990 15 90 16 90000 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes ``` ṚḌ‘DS=ḍ@ð1# ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//4bma4biM4oCYRFM94biNQMOwMSP/MTJS4bifNzsxNcK1OyLDh@KCrEf/ "Jelly – Try It Online") ### How it works ``` ṚḌ‘DS=ḍ@ð1# Main link. Argument: n ð Start a dyadic chain with arguments n and n. 1# Execute the chain to the left with left argument k = n, n+1, n+2, ... and right argument n until 1 match has been found. Return the match. Ṛ Get the decimal digits of k, reversed. Ḍ Convert from base 10 to integer. This essentially removes trailing zeroes. As a side effect, it reverses the digits, which doesn't matter to us. ‘ Increment the resulting integer. If and only if it consisted entirely of 9's, the result is a power of 10. DS Compute the sum of the digits. The sum is 1 if and only if the integer is a power of 10. Note that the sum cannot be 0. ḍ@ Test k for divisibility by n. = Compare the results. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~55~~ 54 bytes ``` n=r=input() while int(`10*r`.lstrip('9')):r+=n print r ``` [Try it online!](https://tio.run/##JYy9DoIwGEVn7lN0K2hi@PhTSDri6uIDoKQJDaQ0nyXK09cal7Pcc4/b/bTaIrwns2hx5013SDzvkYn@6FFIKYNVrIx1m08z/EVjfTpQfuDhtLw8G5fKVmZZx0dl4TjOgkO8IkZG7bzob9eeeeVf98n6MQdCgRIVajQ444IWlIMIVIBKUAWqQc0X "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` f=lambda n,r=9:r%n and f(n,10*r-10**n*r%-n/n*9)or r ``` [Try it online!](https://tio.run/##FcyxDoIwFAXQWb/iLi/Qpo0tGyT4LyVYJdELeYGBr69lOePZzv2zsislj9/0m@YEOh37QYVInJFbuhis@oqlVfF80PZmVWjJVWIhNPH9aqNDDMEM99umC3c00h3wT8jRQFCjazOm/AE "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~47~~ ~~43~~ 42 bytes *-4 bytes thanks to @Arnauld* *-1 byte thanks to @Luke* ``` n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n') ``` ## Tests ``` let f= n=>eval('for(i=0;!/^9+0*$/.test(i);)i+=n') for(let i=1;i<=16;i++)console.log(`f(${i}) = `+f(i)) ``` ### Recursive solution (fails for 7, 13, and 14), 38 bytes ``` n=>g=(i=0)=>/^9+0*$/.test(i+=n)?i:g(i) ``` Called like `f(5)()`. Reaches the max call stack size in Chrome and Firefox for `n=7`, `n=13`, and `n=14`. ``` f= n=>g=(i=0)=>/^9+0*$/.test(i+=n)?i:g(i) for(let i=1;i<=16;i++){ try { console.log(`f(${i}) = `+f(i)()) } catch(e) { console.log(`f(${i}) = FAILED`) } } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 36 bytes ``` ->x{r=0;1until"#{r+=x}"=~/^9+0*$/;r} ``` Brute-forcing - takes forever for x=17. [Try it online!](https://tio.run/##KypNqvyfZvtf166iusjWwNqwNK8kM0dJubpI27aiVsm2Tj/OUttAS0Xfuqj2v6FeaUFJvoahmWZ1TUVNQWlJsYKSaoqCaoqSanSFTlp0RWxs7X8A "Ruby – Try It Online") [Answer] # Java 8, ~~61~~ 57 bytes ``` n->{int r=0;for(;!(""+r).matches("9+0*");r+=n);return r;} ``` -4 bytes (and faster execution) thanks to *@JollyJoker*. **Explanation:** [Try it here.](https://tio.run/##LY7BbsIwDIbvPIXXU7KIqj1NU@jeAC4cpx1CCBDWupXjIiHUZy8ORXIs5Y/95bu6m1v3Q8Dr8X/2rUsJti7iYwUQkQOdnA@wy9dXAF7ljtpKMsmRSuw4etgBQgMzrn8eeYSayp56UvZDFYUhXXaO/SUkVXyb6rPQlkwjGAo8EgLZabYLbhgPreDe1Fsfj9CJkdozRTz//oHTi06m559iU1uIm/pLujHvR4D9PXHoyn7kcpBNblFhKfr65b7YT6tpfgI) ``` n->{ // Method with integer as parameter and return-type int r=0; // Result-integer for(;!(""+r).matches("9+0*"); // Loop as long as `r` doesn't match the regex r+=n // And increase `r` by the input every iteration ); // End of loop return r; // Return the result-integer } // End of method ``` [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` f=lambda n,r=0:{*str(r).strip('0')}!={'9'}and n+f(n,n+r) ``` [Try it online!](https://tio.run/##VYvBCoJAFEXX@RWvlTM2hNIiklxEEAyVi3LTSkzHGsg38mZaRPjtJraIVpdzuKd9ubvBRV@TaYCUNU8qFeimNeQg8EZtX/ZnPKscPXSjHTsd5FFm@TnbbPcCRsxlupOpzC4C/pDzsVPlk6w2@O0jWK9hEfK@Th5Fc60KQEFJGL8D64gRnw@jW@aHPu@mydtf@V2BFeCsZihwRkNoCBA0AhV4UywSEC157E1a0ujYcOO8/wA "Python 3 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` ;I×≜.ẹḅhᵐc~a₀90∧ ``` [Try it online!](https://tio.run/##AS8A0P9icmFjaHlsb2cy//87ScOX4omcLuG6ueG4hWjhtZBjfmHigoA5MOKIp///MTL/Wg "Brachylog – Try It Online") This is pretty slow ### Explanation ``` ;I×≜. Output = Input × I .ẹḅ Deconcatenate into runs of consecutive equal digits hᵐ Take the head of each run c Concatenate into a number ~a₀90∧ That number is a prefix of 90 (i.e. it's 9 or 90) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` 0[+D9Û0«_# ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fIFrbxfLwbINDq@OV//@3BAA "05AB1E – Try It Online") It just keeps adding the input to 0, until the result minus leading 9's equals 0. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 18 bytes ``` x={x*'^9+0*$'E}éx* ``` ## Explained ``` x={x*'^9+0*$'E}éx* x= # Set the value of "x" to the input. { }é # Find the first positive integer in which passing it to the defined function returns truthy. x* # Multiply the index by x, this essentially searches multiples now. '^9+0*$' # A Regex defined by a literal string. E # Does the multiple match the regex? x* # Multiple the outputted index by x, giving the result. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/7/CtrpCSz3OUttAS0Xdtfbwygqt////mwIA "RProgN 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 38 + 1 = 39 bytes Uses `-p` flag. ``` $_=y=eval$_ 1until"#{$_+=y}"=~/^9+0*$/ ``` `-p` surrounds the program with: ``` while gets ... end puts $_ ``` `gets` stores its result in `$_`. `eval` is used to convert it to a number, as it's shorter than `.to_i`, then brute force is used, incrementing $\_ until it matches the regex. `"#{}"` is sttring interpolation, it's shorter than a `.to_s` call as that would require parantheses around `$_+=y`. Finally, `$_` is printed. [Try it online!](https://tio.run/##KypNqvz/XyXettI2tSwxRyWey7A0ryQzR0m5WiVe27ayVsm2Tj/OUttAS0X//3@Tf/kFJZn5ecX/dQsA "Ruby – Try It Online\"ine") [Try all test cases!](https://tio.run/##BcFLCoMwFAXQ@V1F0TeqFL3@WgfZiqGCA0Gi1EQIRZfu85xfGKKqWBPNuH9nsWBwfpqT9C82M/FIzJn3XVY8Jdc1@O0hVokSFWo0aPHGBx1YgARLsAJrsAHba1n9tLhNX@4G) [Answer] # [Mathics](http://mathics.github.io/), 71 bytes ``` (x=#;While[!StringMatchQ[ToString@x,RegularExpression@"9+0*"],x+=#];x)& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo8JW2To8IzMnNVoxuKQoMy/dN7EkOSMwOiQfwnWo0AlKTS/NSSxyrSgoSi0uzszPc1Cy1DbQUorVqdC2VY61rtBU@x8AVFvikOZg8h8A "Mathics – Try It Online") Not very intresting brute force solution, but it beats the other Mathematica answer, which uses some clever tricks. The one redeeming quality Mathematica has in regards to this challenge is the fact that `StringMatchQ` requires a full match, so I can do `9+0*` rather than `^9+0*$`. [Answer] ## Batch, 175 bytes ``` @set/pn= @set s= :g @set/ag=-~!(n%%2)*(!(n%%5)*4+1) @if not %g%==1 set s=0%s%&set/an/=g&goto g @set r=1 :r @set s=9%s% @set/ar=r*10%%n @if %r% gtr 1 goto r @echo %s% ``` Takes input on STDIN. Not a brute force solution but in fact based on my answer to [Fraction to exact decimal](https://codegolf.stackexchange.com/questions/89215) so it will work for 17, 19, etc. which would otherwise exceed its integer limit anyway. [Answer] # Mathematica, 127 bytes ``` Select[FromDigits/@Select[Tuples[{0,9},c=#],Count[#,9]==1||Union@Differences@Flatten@Position[#,9]=={1}&],IntegerQ[#/c]&][[1]]& ``` **Input** > > [17] > > > **Output** > > 9999999999999999 > > > ***here are the first 20 terms*** > > {9, 90, 9, 900, 90, 90, 999999, 9000, 9, 90, 99, 900, 999999, > 9999990, 90, 90000, 9999999999999999, 90, 999999999999999999, 900} > > > [Answer] # [Haskell](https://www.haskell.org/), 53 bytes `f` takes and returns an integer. ``` f n=filter(all(<'1').snd.span(>'8').show)[n,n+n..]!!0 ``` [Try it online!](https://tio.run/##FcvdCoJAEIbhW/mEwJVicPzLILuR6GDIFZfWUVzDy9/s8IXnHSV8rPdxEqed082u8t5OX/VObaBJFhPGeaeBVit9Rvu89iEO0G5w/sBGvDf3lNOMgvYUFlHzSNt/Hlv21IueleiVJHmMjAIlKtRocEWLGzgHM7gAl@AKXIObHw "Haskell – Try It Online") This times out for 17, which conveniently is just beyond the test cases. A faster version in 56 bytes: ``` f n=[x|a<-[1..],b<-[0..a-1],x<-[10^a-10^b],mod x n<1]!!0 ``` [Try it online!](https://tio.run/##FchLCoMwFAXQrVyhgxb0kedf0JVIhFgjSjUpxqKD7j21s8OZlHvpZfGrmk0zm11v6rnfPmaZjXa0qvfdTfagkTathgcddhucH2Ga9vyqOmqZSIb9BUGkIpbh@U/RXRZdL8PVDjhhapZBILxnxEiQIkOOAiUqsAAzOAYn4BScgXNwAS7BFWLxAw "Haskell – Try It Online") # How it works * `f` generates all multiples of `n`, converts each to a string, filters out those with the right format, then takes the first one. * The faster version instead uses that the required numbers are of the form `10^a-10^b`, `a>=1`, `a>b>=0`. For golfing purposes it also uses the fact that for the minimal `a`, only *one* `b` can work, which allows it to generate the `b`s in the slightly shorter "wrong" order. [Answer] # [Perl 5](https://www.perl.org/), 23 + 2 (-pa) = 25 bytes **Brute Force Method** ``` $_+=$F[0]while!/^9+0*$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lXttWxS3aILY8IzMnVVE/zlLbQEtF//9/o3/5BSWZ@XnF/3V9TfUMDA3@6xYkAgA "Perl 5 – Try It Online") It's slow, but it's tiny. ## More Efficient Method: 41 + 2 (-pa) = 43 bytes ``` $_=9;s/0/9/||($_=9 .y/9/0/r)while$_%$F[0] ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tbSuljfQN9Sv6ZGA8RT0KsEcgz0izTLMzJzUlXiVVXcog1i//83NPmXX1CSmZ9X/F/X11TPwNDgv25BIgA "Perl 5 – Try It Online") It works well for any input, but it's longer code. [Answer] # Dyalog APL, 34 bytes ``` {∧/'0'=('^9+'⎕R'')⊢⍕⍵:⍵⋄∇⍵+r}n←r←⎕ ``` Recursive dfns, based on [Dennis' Python solution](https://codegolf.stackexchange.com/a/130113/65326). [Answer] **C++, 106 bytes** ``` int main(){long N,T=9,j=10,M;cin>>N;while(T%N){if(T/j){T+=(M/j);j*=10;}else{T=(T+1)*9;j=10;M=T;}}cout<<T;} ``` Detailed Form: ``` int main() { long N,T=9,j=10,M; cin >> N; while (T%N) { if (T/j) { T += (M/j); j *= 10; } else { T = (T+1)*9; j = 10; M = T; } } cout << T; } ``` [TRY it online!](https://tio.run/##RYtLDoMgFEXnroKkaQLVfkxH5gk70BEbIEj1GUBTMB0Y107pqLOTe@7R63odtU4n9NpugyEtLiG@jXKi@G9Oxek2iWIL6EfilTNhVdqQEAdI6CNxCj1lu12y7ivJm2rm9aPqQKMXoofPhNZQee7Zji8q7zPbZclplwHmS77CYWwwu@RUljW7NPDroeMSjkMvW2zbTCnVzy8) [Answer] # [Python 2](https://docs.python.org/2/), 79 bytes ``` x=input();n=10;y=9 while y%x: b=n while(b-1)*(y%x):b/=10;y=n-b n*=10 print y ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8I2M6@gtERD0zrP1tDAutLWkqs8IzMnVaFStcKKSyHJNo9LASygkaRrqKmlARTWtErSh6jN003iUsjTAnK4Cooy80oUKv//NzQFAA "Python 2 – Try It Online") **Some explanations** It finds the smallest natural of form `10**n-10**b` with `n>b>=0` that divides the input. **Some IO** ``` f(1) = 9 f(2) = 90 f(3) = 9 f(4) = 900 f(5) = 90 f(6) = 90 f(7) = 999999 f(8) = 9000 f(9) = 9 f(10) = 90 f(11) = 99 f(12) = 900 f(13) = 999999 f(14) = 9999990 f(15) = 90 f(16) = 90000 f(17) = 9999999999999999 f(18) = 90 f(19) = 999999999999999999 ``` [Answer] # [PHP](https://php.net/), 39 bytes ``` for(;ltrim($r=$argn*++$i,9)>0;);echo$r; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZGiiZP0/Lb9IwzqnpCgzV0OlyBYso6WtrZKpY6lpZ2CtaZ2anJGvUmT9/z8A "PHP – Try It Online") # [PHP](https://php.net/), 52 bytes ``` for(;!preg_match("#^9+0*$#",$r=$argn*++$i););echo$r; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZGiiZP0/Lb9Iw1qxoCg1PT43sSQ5Q0NJOc5S20BLRVlJR6XIFqxUS1tbJVPTWtM6NTkjX6XI@v9/AA "PHP – Try It Online") [Answer] ## Swift 3.0, Bytes:121 ``` var i=2,m=1,n="" while(i>0){n=String(i*m) if let r=n.range(of:"^9+0*$",options:.regularExpression){print(n) break};m=m+1} ``` [Try it online!](https://iswift.org/playground) [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes This function takes an integer `n` and initializes `m` to zero. Then it removes all zeros from the ends of `m` and checks if the result only contains 9's, returning `m` if it does. If not, it adds `n` to `m` and checks again, etc. ``` def f(n,m=0): while{*str(m).strip('0')}!={'9'}:m+=n return m ``` [Try it online!](https://tio.run/##FcxBCoMwEEDRvaeYrjJTQ1G6KBVyGKGJBswYphEj4tnT9G/@7sUjzSs/S/lYBw5ZB9PR0MA@@8We928SDPSo8xFVp@i6mVO91TWE1nADYtMmDKG4VSCDZ5CRJ4u9hv71d2pRPCfMuvKZqPwA "Python 3 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 66 bytes, doesn't choke on 17 ``` n->{long a=10,b=1;for(;(a-b)%n>0;b=(b<10?a*=10:b)/10);return a-b;} ``` [Try it online!](https://tio.run/##LU/BbsIwDL3zFe8yKYG1tOy2UPYF48Jx2sEpAYUVp0pTpAn124tLkWxLtp@f37vQjbLQOr4c/8a6oa7DN3m@LwDPycUT1Q77qQWawGfUSuZgbWQ0SEp0iZKvsQejwsjZ7v5EUlUW77YqzSlEZRRlVr/xrjC2UnZbFl@0FMCn1euy0Ca61EeGgMwwmpm37W0jvC/6W/BHXEWbOqTo@fzzC9KzsOnBpMrLM/jt5kPqavVaAof/LrlrHvqUt3KZGlaciw/9NDHbGBbD@AA "Java (OpenJDK 8) – Try It Online") Longer than @KevinCruijssen's [solution](https://codegolf.stackexchange.com/a/130105/58251) but can handle slightly larger numbers. It calculates the candidate numbers like 10^6 - 10^3 = 999000. 64-bit longs are still the limit, breaking for n=23. Can probably be golfed a bit but already took too long to make it work... [Answer] # [><>](https://esolangs.org/wiki/Fish), 35 bytes ``` &a:v ;n-< :,a/?(1:^!?%&:&-}:{ a*:\~ ``` [Try it online](https://tio.run/##S8sszvj/Xy3RqkzBOk/XhstKJ1HfXsPQKk7RXlXNSk231qqaK1HLKqbu////umUKRpYA "><> – Try It Online"), or watch it at the [fish playground](https://fishlanguage.com/playground)! Assumes the input is already on the stack. Works by looking for numbers of the form 10a − 10b, with a < b (yes, that's a less than sign — it takes fewer bytes!) until that's divisible by the input, then printing 10b − 10a. This is much faster than the brute force method (which would be difficult in ><> anyway). [Answer] # [V](https://github.com/DJMcMayhem/V), ~~19~~ 14 bytes ``` é0òÀ/[1-8]ü09 ``` [Try it online!](https://tio.run/##K/v///BKg8ObDjcw6kcb6lrEHt5jYPn//39LAA "V – Try It Online") ## Explanation ``` é0 ' &ltm-i>nsert a 0 ò ' &ltm-r>ecursively À ' &ltm-@>rgument times  ' &ltC-A> increment the number (eventually gives all multiples) /[1-8]ü09 ' find ([1-8]|09) if this errors, the number is of the form ' (9+0*) (because there won't ever be just zeros) ' implicitly end the recursion which breaks on the above error ``` [Answer] ## JavaScript (ES6), ~~51~~ 49 bytes ``` let f=(n,x=1,y=1)=>(x-y)%n?f(n,x,y*10):x-y||f(n,x*10) ``` ``` <input type=number value=1 step=1 min=1 oninput=O.value=f(value)> <input type=number value=9 id=O disabled> ``` Not the shortest approach, but it is wicked fast. [Answer] ## Mathematica, 82 bytes Using the pattern of submission from [@Jenny\_mathy 's answer](https://codegolf.stackexchange.com/a/130112/42612)... ``` (d=x=1;y=0;f:=(10^x-1)10^y;n:=If[y>0,y--;x++,y=d;d++;x=1];While[Mod[f,#]!=0,n];f)& ``` Input: ``` [17] ``` Output: ``` 9999999999999999 ``` And relative to the argument in comments at @Jenny\_mathy's answer with [@Phoenix](https://codegolf.stackexchange.com/users/60042/phoenix) ... `RepeatedTiming[]` of application to the input `[17]` gives ``` {0.000518, 9999999999999999} ``` so half a millisecond. Going to a slightly larger input, `[2003]` : ``` {3.78, 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999} ``` a bit under 4 seconds. Test table: On the first 30 positive integers, the results are ``` {9, 90, 9, 900, 90, 90, 999999, 9000, 9, 90, 99, 900, 999999, 9999990, 90, 90000, 9999999999999999, 90, 999999999999999999, 900, 999999, 990, 9999999999999999999999, 9000, 900, 9999990, 999, 99999900, 9999999999999999999999999999, 90} ``` Explanation: The only magic here is the custom iterator ("iterator" in the CS sense, not the M'ma sense) ``` n := If[ y>0 , y-- ; x++ , y=d ; d++ ; x=1] ``` which acts on the global variables `x`, the number of leading "9"s, `y`, the number of trailing "0"s, and `d`, the total number of digits. We wish to iterate through the number of digits, and, for each choice of number of digits, start with the most "0"s and the least "9"s. Thus the first thing the code does is initialize `d` to 1, forcing `x` to 1 and `y` to 0. The custom iterator checks that the string of "0"s can be shortened. If so, it shortens the string of "0"s by one and increases the string of "1"s by one. If not, it increments the number of digits, sets the number of "0"s to one less than the number of digits, and sets the number of "9"s to 1. (This is actually done in a slightly different order to shave a few characters, since the old value of `d` is the desired value of `y`.) [Answer] # Ti-Basic (TI-84 Plus CE), ~~48~~ 41 bytes ``` Prompt X For(K,1,0 For(M,-K+1,0 10^(K)-10^(-M If 0=remainder(Ans,X Return End End ``` Input is `Prompt`-ed during the program; output is stored in `Ans`. Explanation: Tries numbers of the form (10n)(10m-1) = 10k-10m, where m+n=k starts at 1 and increases, and for each value of k, it tries m=1,n=k-1; m=2,n=k-2; ... m=k,n=0; until it finds a multiple of `X`. This works up to 16; 17 gives a domain error because `remainder(` can only accept dividends up to 9999999999999 (13 nines), and 17 should output 9999999999999999 (16 nines). ``` Prompt X # 3 bytes, input number For(K,1,0 # 7 bytes, k in the description above; until a match is found For(M,-K+1,0 # 10 bytes, start with n=1, m=(k-n)=k-1; # then n=2, m=(k-n)=k-2, up to n=k, m=(k-n)=0 # (M=-m because it saved one byte) 10^(K)-10^(-M # 8 bytes, n=(k-m) nines followed by m zeroes → Ans If not(remainder(Ans,X # 8 bytes, If X is a factor of Ans (remainder = 0) Return # 2 bytes, End program, with Ans still there End # 2 bytes, End # 1 byte (no newline) ``` [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 53 bytes ``` {p=p+1┘o=p*9_F!o$|┘n=!A!~(_l!n$|=_l!n+1$|)-(o%:)|\_Xo ``` ## Explanation ``` { infinitely DO p=p+1 raise p (starts out as 0) ┘o=p*9 Get the mext multiple of 9 off of p _F!o$| Flip a string representation of p*9 ┘n=!A! and set 'n' to be an int version of the flipped p*9 (this effectively drops trailing 0's) ~ This IF will subtract two values: the first is either 0 for n=x^10, or -1 and the second bit does (p*9) modulo 'a' (input number): also 0 for the numbers we want ( _l!n$| the length of n's string representation = is equal to _l!n+1$| the length of (n+1)'s string rep (81 + 1 = 82, both are 2 long; 99 + 1 = 100, there's a difference) ) The above yields -1 (Qbasic's TRUE value) for non-9 runs, 0 for n=x^10 - Subtract from that (o%:) (p*9) modulo a 0 for p*9 = a*y | THEN (do nothing, since we want 0+0=0 in the conditionals above, execution of the right path jumps to ELSE \_Xo ELSE quit, printing (p*9) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 126 bytes ``` #include<stdio.h> main(x,n,y,b){n=10;y=9;scanf("%d",&x);while(y%x){b=n;while((b-1)*(y%x)){b/=10;y=n-b;}n*=10;}printf("%d",y);} ``` [Try it online!](https://tio.run/##LYxLDsIgFAD3HqOmBhpQWbgwiHeBRz8k@GqkppCGq4u/LmeSGeA9QClbh@Cftr2EybpxP1w3N@2QRIYsMUMXVOIokzrLABo7UtW2YrtI5Tw435JUR7oYhSsSwwVtfvajD/8UuZEZmy/k@8PhtF4SlbkUcXpB53UfCp/f "C (gcc) – Try It Online") **Some explanations** It finds the smallest natural of form `10**n-10**b` with `n>b>=0` that divides the input. **Some IO** ``` f(1) = 9 f(2) = 90 f(3) = 9 f(4) = 900 f(5) = 90 f(6) = 90 f(7) = 999999 f(8) = 9000 f(9) = 9 f(10) = 90 f(11) = 99 f(12) = 900 f(13) = 999999 f(14) = 9999990 f(15) = 90 f(16) = 90000 ``` ]
[Question] [ Given a number 1≤n≤365, output the nth day of the year in "Day-numberth Month" format. For example, given 1, you should output "1st January", without "of". The Gregorian calendar will be used and the program should not account for leap years, so your program should never output "29th February" in any circumstance. Any method can be used, as long as it follows the "Day-numberth Month" format mentioned before. Your program should also output ordinals correctly, meaning it should always output 1st, 2nd, 3rd, should 1, 2 or 3 respectively be the day numbers for any input. Leading spaces or other indentation are allowed. This is code golf, so the shortest solution by characters wins. Test cases: ``` 1 gives 1st January 2 gives 2nd January 3 gives 3rd January 365 gives 31st December 60 gives 1st March 11 gives 11th January ``` [Answer] # [PHP](https://php.net/), ~~38~~ ~~40~~ ~~30~~ 28 bytes ``` <?=date("jS F",86399*$argn); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoKCSWJSep2CrYGZgrWBvBxS0TUksSdVQygpWcFPSsTAztrTUAqvRtP7/HwA "PHP – Try It Online") Run with `php -nF` input is from `STDIN`. Example (above script named `y.php`): ``` $ echo 1|php -nF y.php 1st January $ echo 2| php -nF y.php 2nd January $ echo 3| php -nF y.php 3rd January $ echo 11|php -nF y.php 11th January $ echo 21|php -nF y.php 21st January $ echo 60|php -nF y.php 1st March $ echo 365|php -nF y.php 31st December ``` **Explanation** Construct an epoch timestamp for the desired day in 1970 (conveniently not a leap year) by multiplying the `day number * number of seconds per day` (86400). However, this would yield one day higher so instead multiply by `number of seconds in a day - 1` (86399) which for the range of input numbers (1≤n≤365) will result with the timestamp of the end of each correct day. Then just use PHP's built-in date formatting for output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~79 78~~ 77 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 fixing a bug :) (shouldn't pre-transpose to find index, should post-reverse, but then we can tail rather than head) -1 using reflection (`⁽©ṅB+30_2¦2` -> `⁽0ṗb4+28m0`) ``` ⁽0ṗb4+28m0SRṁRƲœiµṪȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤$K ``` A full program which prints the result **[Try it online!](https://tio.run/##AZkAZv9qZWxsef//4oG9MOG5l2I0KzI4bTBTUuG5gVLGssWTacK14bmqyK4lMzAlMjDCqzThu4vigJxu4biExrJm4oG3wrtzM8Kk4bmWLOG7i@KAnMKj4bmidOG6kuKBveG6ucK9TeG4injJssinxJdB4bmFIMmTYeG5vsKlRMK54bmA4bqPRDjDt@G5rMOYwrvhuLLCpCRL////NDU "Jelly – Try It Online")** ### How? *will update this later...* ``` ⁽©ṅB+30_2¦2SRṁRƲZœiµḢȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“...»Ḳ¤$K - Main Link: integer, n ⁽©ṅB+30_2¦2SRṁRƲZœi - f(n) to get list of integers, [day, month] ⁽©ṅ - compressed literal 2741 B - to a list of binary digits -> [ 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1] +30 - add thirty [31,30,31,30,31,30,31,31,30,31,30,31] ¦ - sparse application... 2 - ...to indices: [2] _ 2 - ...action: subtract two [31,28,31,30,31,30,31,31,30,31,30,31] Ʋ - last four links as a monad - i.e. f(x): S - sum x 365 R - range [1..365] R - range x (vectorises) [[1..31],[1..28],...] ṁ - mould like [[1..31],[32..59],...] Z - transpose [[1,32,...],[2,33,...],...] œi - 1st multi-dimensional index of n -> [day, month] µḢȮ%30%20«4ị“nḄƲf⁷»s3¤Ṗ,ị“...»Ḳ¤$K - given [day, month] format and print µ - start a new monadic chain - i.e. f(x=[day, month]) Ḣ - head -- get the day leaving x as [month]) Ȯ - print it (with no newline) and yield it %30 - modulo by thirty %20 - modulo by twenty «4 - minimum of that and four ¤ - nilad followed by link(s) as a nilad: “nḄƲf⁷» - dictionary words "standard"+" the" = "standard the" s3 - split into threes = ["sta","nda","rd ","the"] ị - index into Ṗ - remove rightmost character ¤ - nilad followed by link(s) as a nilad: “...» - dictionary words "January"+" February"+... Ḳ - split at spaces = ["January","February",...] ị - index into (vectorises across [month]) , - pair e.g. ["th", ["February"]] K - join with spaces ["th ", "February"] - print (implicitly smashes) th February ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~115~~ ~~113~~ ~~109~~ 98 bytes ``` g=>$"{f=(g=p.AddDays(g-1)).Day}{"tsnr"[f=f%30%20<4?f%10:0]}{"htdd"[f]} {g:MMMM}";DateTime p;int f; ``` Thanks to @someone for saving 9 bytes [Try it online!](https://tio.run/##FY6xCoMwFEX3foWECglWiW1xMMZSkE7tVuhQHMSY9A2mkqSDiN@exjsd7llOb9Pegr/9dF@JWXcj9AfrDGhVy/Bxr3i9R4vkWPEpuwrRdLPFKs0JyQKuC3JWG/SWXMYnGh9pdb7IOKclbYP7OCGCa9doUeUjbEWs6dzwhHGIJgbaRZJ5@TV4Q@A5g@pUFAyShOxeBtxwBz3grQQDIcz/AQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 112 bytes ``` lambda x:str(d:=(t:=gmtime(x*86399)).tm_mday)+'tsnrhtdd'[d%5*(d%30%20<4)::4]+strftime(' %B',t) from time import* ``` [Try it online!](https://tio.run/##HYxLDoIwFAD3nqIb0lcwBEQNNLLxGmpMzWuFhH5SXgycvqKznGQmrDR417QhJtPf06TsCxVb5EwRUPZAsn9bGq2GJW/PTdcJUZJ9WlSrKDjNLg6EyG@YnXLArKmyQ3U5CimPj2J7mH/KWXblexI7E71lP8VGG3ykPIU4OgID@qMm8EE7qEQZtUIQG6muvw "Python 3.8 (pre-release) – Try It Online") Weirdly enough, I don't have to parenthesize `d:=(t:=gmtime(~-x*86400)`, probably because the interpreter only checks if there are `()` characters around the assignment expression and not that the expression itself is parenthesized. -2 thanks to [gwaugh](https://codegolf.stackexchange.com/users/84624/gwaugh). -5 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~166~~ 161 bytes ``` {~(.day~(<th st nd rd>[.day%30%20]||'th'),<January February March April May June July August September October November December>[.month-1])}o*+Date.new(1,1,1)-1 ``` [Try it online!](https://tio.run/##JY1BC4JAFITv/Yp3sbRMXCUvmSBIB6E6dAwPqz4z0FW2tVgy/7qtxoN538xhpkVeeWMtYVnAYfwMupVTOei@KOEpgOXA8@A2ZZpra46d9P1KlCvD9GPKOsolHDHlM5woz0oIW/6oFEuIO4ZKKglhd@9U2RVbgXWKHC6ZaKZ/bl7/IMJsBjVVN0yUW5IY32a9iahAi@FbJ6Y6Y0vG/cIn4IALrrcDzwainB0EgbUslDypHH8 "Perl 6 – Try It Online") Hardcodes all the month names, which takes up most of the space. Man, Perl 6 really needs a proper date formatter. [Answer] # Hack, ~~115~~ ~~59~~ 39 bytes ``` $x==>date("jS F",mktime(0,0,0,1,$x)); ``` Since @gwaugh got to the same solution as mine while I was golfing, I'm posting this in Hack instead :). [Answer] # JavaScript (ES6), ~~117~~ 113 bytes *Saved 4 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` d=>(n=(d=new Date(1,0,d)).getDate())+([,'st','nd','rd'][n%30%20]||'th')+' '+d.toLocaleString('en',{month:'long'}) ``` [Try it online!](https://tio.run/##Hcu9bsIwFIbhvVfhAWRbfEQ@x/mBVmFqt24dERJRbBKq1K6C1Q4h156iLo/0Du9n89Pc2vH6nbYhOr9c6sXVBxVq5ergf8Vrk7wiGDits86n/9Z6o46QtyQhg3swOnk6hrU1azan@12mXuqNFHLjshTfY9sM/iON19Ap6YPE9BVD6p/lEEMnZ728HAkMixwFSlTYYQ8yIAIxyIJyUAEqQRVoB9qDDfjxMNiCc3ABLsEVeAfewxpYQvmwLE5P2SWOb03bKyfqg2hjuMXBZ0Ps1Hk1uVlsD2I1XZTT81nr5Q8 "JavaScript (Node.js) – Try It Online") ### Commented ``` d => // d = input day ( n = // ( d = // convert d to new Date(1, 0, d) // a Date object for the non leap year 1901 ).getDate() // save the corresponding day of month into n ) + ( // [, 'st', 'nd', 'rd'] // ordinal suffixes [n % 30 % 20] // map { 1, 2, 3, 21, 22, 23, 31 } to { 'st', 'nd', 'rd' } || 'th' // or use 'th' for everything else ) + ' ' + // append a space d.toLocaleString( // convert d to ... 'en', // ... the English ... { month: 'long' } // ... month name ) // ``` --- # Without date built-ins, 188 bytes ``` f=(d,m=0)=>d>(k=31-(1115212>>m*2&3))?f(d-k,m+1):d+([,'st','nd','rd'][d%30%20]||'th')+' '+`JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember`.match(/.[a-z]*/g)[m] ``` [Try it online!](https://tio.run/##HZBLb4JAGEX3/RUstMPIBflmBLUNNCZtFya2iy4JCSODj8rD8DCx6m@3tJtzchc3N7nf6qSatN4fW7usdHa/bwJTowhcHoQ6NA@BJNskIk@QCMNiJB4l5y8bU9sHFBbxJ22ZEVjTMrBS96g1iyM9lO5QuPH1ytod4xYzmJUsVdmp@vyeres/r1Sd7hbHep@v1HnZldmyy8@Lbts17Vd2bLNindWfaVv1@qhO//E1S/@dOIVq0505diJl/8Sj8ZZHRXx/jggCEhN48DHFDHOQCyKQAEnQBOSBfNAUNAPNIVyIviMgJMQEwoPwIaYQM4g5pAtJ8Hv6XvzgbKr6TfWr2ghCI63KpsozJ6@2ZjK46Jthh8bg0h/Dbwnn918 "JavaScript (Node.js) – Try It Online") [Answer] # Smalltalk, 126 bytes ``` d:=Date year:1day:n.k:=m:=d dayOfMonth.10<k&(k<14)and:[k:=0].o:={#st.#nd.#rd}at:k\\10ifAbsent:#th.m asString,o,' ',d monthName ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~141~~ ~~139~~ ~~133~~ ~~124~~ 122 bytes ``` a=>{var d=s.AddDays(a-1);int x=d.Day,m=x%30%20;return x+"thstndrd".Substring(m<4?m*2:0,2)+d.ToString(" MMMM");};DateTime s ``` Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for faster method of removing 11,12,13th saving 4 bytes [Try it online!](https://tio.run/##JY3LCsIwFET3fsWlUEjsg7Y@FqapCMWVrhRcxybVu2gKSSqV4rfHirM8zJlpbNJY9MdBNyVqF1tnUD8qaLkXvJpewoDkNj1IWYu3JSLJKZt7MHKZziTu@BiusrDImFFuMBrGKHBP67Q0Mkgvw/0/SLpyve@WxS6LCxrJ9Npf/jyA85yAsg@rhVNX7BRYzxZtb8jvB3nOEEpYbTcMMIrodDPo1Am1Ii1BOov@Cw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [R](https://www.r-project.org/), 158 134 bytes -24 bytes @Nick Kennedy for golfing the 'st', 'nd', 'rd', & 'th'. Thanks! ``` f=format;paste0(a<-as.double(f(d<-as.Date(scan(,''),'%j'),'%e')),`if`((a-1)%%10>2|a%/%10==1,'th',c("st","nd","rd")[a%%10]),f(d,' %B')) ``` [Try it online!](https://tio.run/##HYxBCsIwEEWvIoEwMzDVRldi40K8hQgdmwQV20oSd949xm4e/8PjxVKCDXMcJR/ekrJvUbpG0trNn9vLY0C33LNkj2mQCRmAGPRzoQci7h@hR5TGkNamPW6/ojd1WGsY8h14QJWyYjW5iugUXeQvXolrnWGlT7VS9rvyAw "R – Try It Online") [Answer] # MySQL, ~~47~~ ~~45~~ 42 bytes ``` SELECT DATE_FORMAT(MAKEDATE(1,n),"%D %M") ``` 1901 can be replaced with any year that was/is not a leap year. Edit: saved two bytes by removing spaces and another three bytes by changing the year to 1, thanks to [@Embodyment of Ignorance](https://codegolf.stackexchange.com/users/84206/embodiment-of-ignorance). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~81~~ ~~79~~ ~~78~~ ~~76~~ ~~75~~ ~~74~~ ~~73~~ ~~71~~ ~~70~~ 69 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •ΘÏF•ºS₂+.¥-D0›©ÏθDT‰ć≠*4šß„—ÊØ3ôsè¨ð”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”#®OèJ ``` -9 bytes thanks to *@Grimy*. -1 byte thanks to @JonathanAllan's `standard the` trick for `th,st,nd,rd`, which he used in [his Jelly answer](https://codegolf.stackexchange.com/a/181524/52210). [Try it online](https://tio.run/##yy9OTMpM/f//UcOiczMO97sB6UO7gh81NWnrHVqq62LwqGHXoZWH@8/tcAl51LDhSPujzgVaJkcXHp7/qGHeo4Yph5uPLjg8w/jwluLDKw6tOLzhUcPcRw3LwGjWYSCxEKgJyDu85FHDgsPrHzWtObQfxO0GEatAYi0gFkjD4R4Q0Qs0QPnQOv/DK7z@/zc3BAA) or [verify all possible test cases](https://tio.run/##yy9OTMpM/W9sZurqZ6@k8KhtkoKSvd//Rw2Lzs043O8GpA/tCn7U1KStd2iprovBo4Zdh1Ye7j@3wyXkUcOGI@2POhdomRxdeHj@o4Z5jxqmHG4@uuDwDOPDW4oPrzi04vCGRw1zHzUsA6NZh4HEQqAmIO/wkkcNCw6vf9S05tB@ELcbRKwCibWAWCANh3tARC/QAOVD6/wPr/D6r/MfAA). **Explanation:** ``` •ΘÏF• # Push compressed integer 5254545 º # Mirror it vertically: 52545455454525 S # Converted to a list of digits: [5,2,5,4,5,4,5,5,4,5,4,5,2,5] ₂+ # And 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31] # (the additional trailing 28,31 won't cause any issues) .¥ # Undelta this list (with automatic leading 0): # [0,31,59,90,120,151,181,212,243,273,304,334,365,393,424] - # Subtract each from the (implicit) input-integer D0› # Duplicate the list, and check for each if it's positive (> 0) © # Store the resulting list in the register (without popping) Ï # Only leave the values at those truthy indices θ # And get the last value from the list, which is our day D # Duplicate this day T‰ # Take the divmod-10 of this day: [day//10, day%10] ć # Extract the head; pop and push the remainder-list and head: [day%10], day//10 ≠ # Check whether the day//10 is NOT 1 (0 if day//10 == 1; 1 otherwise) * # Multiply that by the [day%10] value 4š # Prepend a 4 to this list ß # Pop and push the minimum of the two (so the result is one of [0,1,2,3,4], # where the values are mapped like this: 1..3→1..3; 4..9→4; 10..19→0; 20..23→0..3; 24..29→4; 30,31→0,1) …thŠØ # Push dictionary string "th standards" 3ô # Split it into parts of size 3: ["th ","sta","nda","rds"] sè # Swap and index the integer into this list (4 wraps around to index 0) ¨ # And remove the trailing character from this string ð # Push a space " " ”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í” # Push dictionary string "December January February March April May June July August September October November" # # Split on spaces ® # Push the list of truthy/falsey values from the register again O # Get the amount of truthy values by taking the sum è # Use that to index into the string-list of months (12 wraps around to index 0) J # Join everything on the stack together to a single string # (and output the result implicitly) ``` [See this 05AB1E tip of mine](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * (section *How to use the dictionary?*) `”……‚應…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í”` is `"December January February March April May June July August September October November"` * (section *How to use the dictionary?*) `…thŠØ` is `"th standards"` * (section *How to compress large integers?*) `•ΘÏF•` is `5254545` [Answer] # bash, ~~82~~ 80 bytes -2 bytes thanks to @ASCII-only ``` a=(th st nd rd);set `printf "%(%e %B)T" $[$1*86399]`;echo $1${a[$1%30%20]-th} $2 ``` [TIO](https://tio.run/##HclNCsMgEAXgfU8xBAUNFPwhEgnZ9AzdlUBso5hNWqK7kLNbJ4v3eN/M26VYAuNHcSPLEVKGbYF94UPyGebfvm45QEMZ9UAf/NkAeRHZ9kZbO82D/8QvEEkOV69UC6rEdM/xBKLKeQsga1SNxo2QKIlU1w@prq/FJWp1PRbSILXpyh8) # bash +GNU date, 77 bytes ``` a=(th st nd rd);set `date -d@$[$1*86399] +%e\ %B`;echo $1${a[$1%30%20]-th} $2 ``` [Answer] # Shell + coreutils, ~~112~~ 90 bytes ``` date -d0-12-31\ $1day +%-dth\ %B|sed 's/1th/1st/;s/2th/2nd/;s/3th/3rd/;s/\(1.\).. /\1th /' ``` [Try it online!](https://tio.run/##HcqxCsMgFEbh3af4h4S0FDVXaZZsfY2YwXIFCyGBKJSC725tt4/DefoU6zu@toAzeMaGUrAs6Das6ww@kEKGlC1U9jlA8ijJSEsOHbH/4NZLztGhf5QUGEPSlKOmlPWctGk0O/9oG@35p7uQcleloF17oYfKxx4qCSOssNNdTKMg@gI "Bash – Try It Online") Link includes test cases. Edit: Saved 22 bytes thanks to @NahuelFouilleul. Explanation: ``` date -d0-12-31\ $1day ``` Calculate the number of day(s) after the first day preceding a non-leap year. (Sadly you can't do relative date calculations from `@-1`.) ``` +%-dth\ %B|sed ``` Output the day of month (without leading zero), `th`, and the full month name. ``` 's/1th/1st/;s/2th/2nd/;s/3th/3rd/; ``` Fix up `1st`, `2nd`, `3rd`, `21st`, `22nd`, `23rd` and `31st`. ``` s/\(1.\).. /\1th /' ``` Restore `11th` to `13th`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~115~~ ~~114~~ ~~101~~ 97 bytes ``` %30%20¹0<?4Ḥ+ؽị“thstndrd”ṭ “5<Ḟ’b4+28ÄŻ_@µ>0T,>0$ƇZṪµ1ịị“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»Ḳ¤,2ịÇƊṚK ``` [Try it online!](https://tio.run/##y0rNyan8/1/V2EDVyODQTgMbe5OHO5ZoH55xaO/D3d2PGuaUZBSX5KUUpTxqmPtw51ouoIipzcMd8x41zEwy0TayONxydHe8w6GtdgYhOnYGKsfaox7uXHVoqyFQM0T/ocUPdy4qebhr0qPGvQ937Ty01/fhjq6Kk5tOLD8y3fHhzlaFk5MTH@7cd2ipy6GdD3c2PNzV72JxePvDnWuATtj9cMemQ0t0jIAmHW4/1vVw5yzv/8ZmpkE6QHN17YAu0gEKb3rUtCbyPwA "Jelly – Try It Online") Long by Jelly standards, but done from first principles. Thanks to @JonathanAllan for saving 13 bytes through better understanding of string compression. [Answer] # Google Sheets, ~~118~~ ~~103~~ 86 bytes ``` =day(A1+1)&mid("stndrdth",min(7,1+2*mod(mod(day(A1+1)-1,30),20)),2)&text(A1+1," mmmm") ``` I can't edit [my comment](https://codegolf.stackexchange.com/a/181469/30134) so, here's a working version of the Google Sheets code. [Try it Online!](https://docs.google.com/spreadsheets/d/161NlGfTcky849Ye0A3qLxoaSF8ic2UvBiBQ9yX-ahsg/edit?usp=sharing) [Answer] # [Red](http://www.red-lang.org), 124 bytes ``` func[n][d: 1-1-1 + n - 1[rejoin[d/4 either 5 > t: d/4 % 30 % 20[pick[th st nd rd]t + 1]['th]]pick system/locale/months d/3]] ``` [Try it online!](https://tio.run/##Tcy/DoIwEAbwnaf4FuNgCC0IA4MP4drcYGhJq1BIew4@fS2DYC65/HJ/vmB0uhutqBj7NL79oDwp3UOWuXCBRwmpgnkuzitdXWEcWxPQ4gbusU1OaERutVCrG16KLSLDawRNnBMkqTNbom2J@Ils5mpahsdkqnnxbGMOaYjSGpxnjJDFT/Wu5lDX7u7ETnl8tX/HIn0B "Red – Try It Online") Adds `n` - 1 days to 1-1-1 (1-Jan-2001) to form a date, than uses Arnauld's method to index into month suffixes. Too bad [Red](http://www.red-lang.org) is 1-indexed, this requires additional tweaking. The good thing is that [Red](http://www.red-lang.org) knows the names of the months :) [Answer] # APL(NARS), 235 chars, 470 bytes ``` {k←↑⍸0<w←+\v←(1-⍵),(12⍴28)+13561787⊤⍨12⍴4⋄k<2:¯1⋄d←1+v[k]-w[k]⋄(⍕d),({d∊11..13:'th'⋄1=10∣d:'st'⋄2=10∣d:'nd'⋄3=10∣d:'rd'⋄'th'}),' ',(k-1)⊃(m≠' ')⊂m←'January February March April May June July August September October November December'} ``` 13561787 is the number that in base 4 can be summed to (12⍴28) for obtain the lenght of each month... test: ``` f←{k←↑⍸0<w←+\v←(1-⍵),(12⍴28)+13561787⊤⍨12⍴4⋄k<2:¯1⋄d←1+v[k]-w[k]⋄(⍕d),({d∊11..13:'th'⋄1=10∣d:'st'⋄2=10∣d:'nd'⋄3=10∣d:'rd'⋄'th'}),' ',(k-1)⊃(m≠' ')⊂m←'January February March April May June July August September October November December'} ⊃f¨1 2 3 365 60 11 1st January 2nd January 3rd January 31st December 1st March 11th January ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~174~~ 155 bytes ``` i;char a[99],*b="thstndrd";f(long x){x--;x*=86400;strftime(a,98,"%d %B\0",gmtime(&x));i=*a==49?0:a[1]-48;a[2]=b[i=i>3?0:i*2];a[3]=b[++i];x=*a==48?a+1:a;} ``` [Try it online!](https://tio.run/##JY7dioMwFITv8xQHly5R46LVLdo0FvY1bC5Sfw/UtMQUhNJnt9G9m/mYga@O@rpevlDXt2fTniyO7c9QLsjrQRlQVVFIFlyFZ4fJ6sY0Hu/o7a57mP3XHEV8DkR@yOKYT9Z065sqVuTM2zUAsPu7xB7rx41/z77PUQRKiKw4x0dVJTLKcq6qvRTXCgWWqcMY7KVj6crCECWf/y/5WYXJUfH3QlBbGBVq6sNrK8gJ6e6Gokg4IJwEpIdfl8JwXcDDuFFHNydROq3poj0GyKCj6KTImxDT2qfREG9l@QA "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ṡ`, 81 bytes ``` kṁ¦Ṫ0p-'0>;:L`ƛǓ ⟇∩ ∨₄ ∨⋏ λ√ ∨ɾ ∨∑ ⟇τ ∨₆ ∨Þ ∨∞ ⟑√`⌈$i$t:t:4<[` ∨ǐ`3/vḢȮ‹i|‛th]$_+ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=%E1%B9%A1&code=k%E1%B9%81%C2%A6%E1%B9%AA0p-%270%3E%3B%3AL%60%C6%9B%C7%93%20%E2%9F%87%E2%88%A9%20%E2%88%A8%E2%82%84%20%E2%88%A8%E2%8B%8F%20%CE%BB%E2%88%9A%20%E2%88%A8%C9%BE%20%E2%88%A8%E2%88%91%20%E2%9F%87%CF%84%20%E2%88%A8%E2%82%86%20%E2%88%A8%C3%9E%20%E2%88%A8%E2%88%9E%20%E2%9F%91%E2%88%9A%60%E2%8C%88%24i%24t%3At%3A4%3C%5B%60%20%E2%88%A8%C7%90%603%2Fv%E1%B8%A2%C8%AE%E2%80%B9i%7C%E2%80%9Bth%5D%24_%2B&inputs=144&header=&footer=) What a mess. ``` kṁ # List of month lengths ¦ # Cumulative sums Ṫ0p # Pop off the last and prepend a 0 - # Subtract from input '0>; # Filter by positive :L # Duplicate and get length `...`⌈$i # Index into list of month names $t:t # Get the last digit :4<[ # If it's less than 4 then... `...` # Push ' standard' 3/ # Split into 3 vḢ # Lop off the first char of each Ȯ‹i # Index the number into this | ] # Else ‛th # Push 'th' $_+ # Swap, pop and concatenate # (ṡ flag) join stack by spaces ``` ]
[Question] [ Given an integer \$ n \ge 1 \$, your task is to output an array \$ a \$ consisting of \$ n^2 + 1 \$ integers, such that all possible pairs of integers \$ (x, y) \$ satisfying \$ 1 \le x, y \le n \$ exist as a contiguous subarray in \$ a \$, exactly once. For example, if \$ n = 2 \$, a valid output would be \$ (1, 1, 2, 2, 1) \$. We can check all possible pairs to verify that this is indeed correct: $$ \begin{align} (1, 1) \to (\color{red}{1, 1}, 2, 2, 1) \\ (1, 2) \to (1, \color{red}{1, 2}, 2, 1) \\ (2, 1) \to (1, 1, 2, \color{red}{2, 1}) \\ (2, 2) \to (1, 1, \color{red}{2, 2}, 1) \\ \end{align} $$ ### Notes * It can be shown that a construction exists for all \$ n \$. * \$ a \$ may be outputted in any reasonable form (e.g. a delimiter-separated string). * It is recommended, but not required, to prove that your construction works for all \$ n \$. * This problem is closely related to asking for the [de Bruijn sequence](https://en.wikipedia.org/wiki/De_Bruijn_sequence) of order \$ n \$. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` :1ṁSJṫṫ ``` [Try it online!](https://tio.run/##yygtzv7/38rw4c7GYK@HO1cD0f///00B "Husk – Try It Online") This is OEIS [A349526](https://oeis.org/A349526) reversed. ``` :1ṁSJṫṫ ṫ Let i range from the input down to 1 For each i ṫ Range from i down to 1 SJ Insert an i between every two elements ṁ Concatenate :1 Prepend 1 to the result ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` §+oṘ2ḣoṁSJoḣ←ṫ ``` [Try it online!](https://tio.run/##yygtzv7//9By7fyHO2cYPdyxGEg3BnvlA1mP2iY83Ln6////pgA "Husk – Try It Online") ### How? First, observe that this challenge is equivalent to the following: * Create a [complete digraph](https://en.wikipedia.org/wiki/Complete_graph) consisting of \$n\$ nodes, labeled \$1\$ through \$n\$ * Add a loop edge from each node to itself * Construct a traversal of the graph which follows each (directed) edge exactly once This solution generates a sequence like this (example for input `5`): ``` 1,1,2,2,3,3,4,4,5,5,1,5,2,5,3,5,4,1,4,2,4,3,1,3,2,1 ``` which can be divided into sections: ``` 1,1,2,2,3,3,4,4,5,5 1,5,2,5,3,5,4 1,4,2,4,3 1,3,2 1 ``` * In the first section, we go from node \$1\$ to node \$n\$ in order, taking the loop edge at each node as we reach it. * In the second section, we take the edge from node \$n\$ to each node other than \$n-1\$ and immediately return to node \$n\$. Finally, we go to node \$n-1\$. * In the next section, we do the same for node \$n-1\$, visiting each node except for \$n-2\$. * We continue this pattern all the way back to node \$1\$. This approach visits every directed edge exactly once: the edges \$i \to i\$ and \$i \to i+1\$ in the first section, and in \$i\$'s return section the edges \$i \to j\$ and \$j \to i\$ for all \$j < i-1\$, as well as \$i \to i-1\$. ### Explanation We construct the first section and the remaining sections separately and then concatenate them. First section: ``` oṘ2ḣ ḣ Range from 1 to argument, inclusive o Compose with Ṙ2 Repeat each element of a list twice ``` (Credit to [Razetime](https://codegolf.stackexchange.com/questions/188988/ddoouubbllee-ssppeeaakk/189056#comment522032_189056) for the `Ṙ2` code.) Remaining sections: ``` oṁSJoḣ←ṫ ṫ Range from argument down to 1, inclusive o Compose with ṁ Map this function and concatenate the resulting lists: ← Decrement o Compose with ḣ Range from 1 to argument, inclusive J Insert a value between all elements S using the argument as that value ``` Putting it all together: ``` §+oṘ2ḣoṁSJoḣ←ṫ § Apply each of these functions to the argument: oṘ2ḣ First section function oṁSJoḣ←ṫ Remaining sections function and combine the results using this function: + Concatenate lists ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ 15 bytes ``` ₌ɾ²›↔'2l?:Ẋ⊍¬;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwi4oKMyb7CsuKAuuKGlCcybD864bqK4oqNwqw7aCIsIiIsIjIiXQ==) So remember the last time I solved an array challenge with a brute force algorithm and it timed out for anything larger that a 2x2 matrix? Well I've made an improvement! This algorithm times out for anything larger than `n=3`. ## Explained ``` ₌ɾ²›↔'2l?:Ẋ⊍¬;h ₌ɾ²›↔ # From the range [1, input], choose all combinations with repetition of length (input**2) + 1 ' ;h # And get the first combination where: 2l # A list of all windows of length 2 ?:Ẋ⊍¬ # set xor'd with the cartesian product of the range [1, input] with itself is empty ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Rj)F;1 ``` A monadic Link that accepts a positive integer and yields a list of positive integers. **[Try it online!](https://tio.run/##y0rNyan8/z8oS9PN2vD////GAA "Jelly – Try It Online")** ### How? Much like alephalpha's [Husk answer](https://codegolf.stackexchange.com/a/253324/53748)... ``` Rj)F;1 - Link: integer, N ) - for each (n in [1..N]): R - range (n) j - join with (n) F - flatten ;1 - concatenate a one ``` [Answer] # Python3, 173 bytes: ``` lambda n:next(F({(x,y)for x in R(1,n+1)for y in R(1,n+1)})) def F(k,c=[]): if not k:yield c for i in k: if[]==c or c[-1]==i[0]:yield from F(k-{i},c+[*i][c!=[]:]) R=range ``` [Try it online!](https://tio.run/##TY2xDoIwEIZneYpza6Ukogtp0pUHYK0dsFC9AIU0DDSEZ6@FGON29/33fzf5@T3aezG5YMQj9PXwbGqw3LbLTEqykoV5akYHC6CFiuTMpvkB/D/YKE2a1kBJOqaFVJQngAbsOEPHPbZ9AzqBvYZ7rYtxzKUSQkOEWmZ5nFFe1ffauHHYbdmKG9OpvKCS@hzNXNGkEq62rzb8fMdKbqyIf0@TQzsTQ5DS8AE) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes -3 bytes thanks to [@hakr14](https://codegolf.stackexchange.com/users/78186/hakr14). ``` #~DeBruijnSequence~2~Append~0+1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@1@5ziXVqag0MysvOLWwNDUvObXOqM6xoCA1L6XOQNtQ7b9LfnRAUWZeSXSegq6dQlp0XmysjkJ1no6CIRAZ1Mb@BwA "Wolfram Language (Mathematica) – Try It Online") Using the built-in [`DeBruijnSequence`](http://reference.wolfram.com/language/ref/DeBruijnSequence.html). --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes ``` ##~Join~{1}&@@Range@i~Riffle~i~Table~{i,#}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19Zuc4rPzOvrtqwVs3BISgxLz3VIbMuKDMtLSe1LrMuJDEJSFdn6ijXqv13yY8OKMrMK4nOU9C1U0iLzouN1VGoztNRMAQig9rY/wA "Wolfram Language (Mathematica) – Try It Online") This is OEIS [A349526](https://oeis.org/A349526). [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes (15 nibbles) ``` +.:,$1>>+.,$:@ ``` A [Nibbles](http://golfscript.com/nibbles/index.html) port of the generator for [A349526](https://oeis.org/A349526), thanks to [alephalpha's Husk answer](https://codegolf.stackexchange.com/a/253324/95126) (upvote that!). ``` ,$ # range 1..input : 1 # append 1 . # map each i over this: .,$ # map over 1..i :@ # prepend i + # flatten >> # and remove first element + # and flatten the list-of-lists ``` [![enter image description here](https://i.stack.imgur.com/Dx6xs.png)](https://i.stack.imgur.com/Dx6xs.png) [Answer] # [R](https://www.r-project.org/), 50 bytes ``` f=function(x)if(x)c(1,rbind(x,x:1)[-x],f(x-1)[-1]) ``` [Try it online!](https://tio.run/##K/qfklmWWlScmlhUlFhp@z/NNq00L7kkMz9Po0IzMw1IJGsY6hQlZealaFToVFgZakbrVsTqACV0QUzDWE0UAzSMNf8DAA "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 39 bytes ``` f n=n:do x<-[1..n];init$(:[x])=<<[x..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzbPKiVfocJGN9pQTy8v1jozL7NERcMquiJW09bGJroCJPg/NzEzT8FWITexwDdeQaOgKDOvRC9NUwGkxSz2PwA "Haskell – Try It Online") * saved 10 Bytes thanks to @xnor [Answer] # JavaScript (ES6), 47 bytes Returns a comma-separated string. This generates the same results as [alephalpha's answer](https://codegolf.stackexchange.com/a/253324/58563), with a recursive algorithm. ``` f=n=>n?1+[,(g=k=>k>1?[k,n,g(k-1)]:f(n-1))(n)]:1 ``` [Try it online!](https://tio.run/##ZchNCoAgEEDhfSeZIQ3sbxFoB5EWYSpljFHR9a1tuHqPb5uf@TLnetyc4mJTcpKkolGUmoGXQaqgxKgDI@YhcIHT4IC@ItD3IplIV9xttUcPDmrE4i9NJm0mXSY9YnoB "JavaScript (Node.js) – Try It Online") ### How? By using `[1,` instead of `1+[,` ([like that](https://tio.run/##DcyxDsIgFEDRvV/xxkdKm@DgYIXuDjo4Ng5NBYKQRwPExBi/HZnOne5rfa95S24vA8WnrtVIkormRXC00kvllZgXz4lb9INgj5NBajKk1qKamDDoAgQSDlPjLOHY7HsG3w5gi5Rj0GOIFi/323XMJTmyznywjRhjU/erfw)), we can see that it actually builds the following structure (here for \$n=3\$): ``` +------ first call to f | +-- first call to g | | v v [1, [3, 3, [2, 3, [1, [2, 2, [1, 1]]]]]] ^ | +-- second call to f ``` The purpose of `1+[,` is to force the result to be coerced to a string *and* implicitly flattened. [Answer] # Rust, ~~84~~ 74 bytes -10 bytes thanks to [alepalpha](https://codegolf.stackexchange.com/users/9288/alephalpha) ``` use itertools::*;|n|chain((1..=n).flat_map(|m|(1..=m).intersperse(m)),[1]) ``` [Plauground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f25108422ba6282e2fd9611ad2dca433) Takes a `usize` and returns an iterator of usizes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` FNF⊕ι«I⊕✂⟦ικ⟧¬κ»1 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTASqWXJSam5pXkpqikQkUrFYIKMrMK9FwTiwuQZEMzslMTtWIztRRyI7VUfDLL9HI1gQBa4VaLogWJUMlTev//03/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @DominicvanEssen's Nibbles answer. ``` FN ``` Input `n` and loop `i` from `0` until `n`. ``` F⊕ι« ``` Loop `k` from `0` until `i` inclusive. ``` I⊕✂⟦ικ⟧¬κ ``` If `k` is `0` then just output `k+1` otherwise output both `i+1` and `k+1`. ``` »1 ``` Output a trailing `1`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LLεZ.ý}˜Ć ``` Port of [*@alephalpha*'s Husk answer](https://codegolf.stackexchange.com/a/253324/52210), but reversed. [Try it online](https://tio.run/##yy9OTMpM/f/fx@fc1ii9w3trT8850vb/vzEA) or [verify the first 5 test cases](https://tio.run/##yy9OTMpM/W/q6mevpPCobZKCkr3ffx@fc1uj9A7vrT0950jbf53/AA). **Explanation:** ``` L # Push a list in the range [1, (implicit) input] L # Convert each value in this list to a list in the range [1,value] ε # Map over each inner list: Z # Push the list's maximum (without popping the list itself) .ý # Intersperse the list with this maximum as delimiter }˜ # After the map: flatten it to a single list Ć # Enclose; appending its own head (which is always 1) # (after which the result is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` f=lambda n,i=1:n*[1]and f(n-i//n,i%n+1)+[n,i][i-n:] ``` [Try it online!](https://tio.run/##DcixCoAgFEbhvae4S6BlhDQEgk8iDkZZF@pPxKWnN8/0cdJXrhdLrdHe4dn2QFBstcHgtA/YKQpMPM/t9hi1HF2TdzzB@BrfTEwMygHnIbSiVZqOWikzioiCpaw/ "Python 3 – Try It Online") This uses a similar method as [alephalpha's answer](https://codegolf.stackexchange.com/a/253324/95116), except it orders segments in reverse. Using `n=4` as an example, the list is built recursively, as a sum of segments `[1,1] + [2,2,1] + [3,3,2,3,1] + [4,4,3,4,2,4,1]`, where the last segment is concatenated to `f(n-1)`. The segments are also built recursively, as `[4,4]+[4,3]+[4,2]+[4,1]` with the `[i-n:]` to slice off the beginning of the second term (`[4,3] => [3]`). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` <~l.&⟦₁gjẋ~sᵛ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/36YuR0/t0fxlj5oa07Me7uquK364dfb//8b/owA "Brachylog – Try It Online") ### Explanation ``` <~l. length(output) > input &⟦₁ Take the range [1, …, input] gj Juxtapose to itself [[1, …, input], [1, …, input]] ẋ Cartesian product ~sᵛ Each sublist of the cartesian product is a connex sublist of the output (the output gets filled in with the right values to match this constraint) ``` ]
[Question] [ The 3Blue1Brown Youtube channel released a video a year ago called "[Why do colliding blocks compute pi?](https://www.youtube.com/watch?v=jsYwFizhncE)" which describes a model where a block `A` of mass \$a\$ slides into a block `B` of mass \$b\$, which then pushes block `B` into a wall, causing it to bounce off the wall and then collide again with block `A`. The miracle of this process is that if \$a/b = 10^{2n-2}\$ the number of total collisions (both between `A` and `B` and between `B` with the wall) is given by the first \$n\$ digits of \$\pi\$. --- # Example output ``` +-------+---+--------+ | a | b | output | +-------+---+--------+ | 1 | 1 | 3 | | 2 | 1 | 5 | | 3 | 1 | 5 | | 4 | 1 | 6 | | 5 | 1 | 7 | | 10 | 3 | 6 | | 7 | 2 | 6 | | 9 | 2 | 7 | | 1 | 2 | 3 | | 1 | 5 | 2 | | 100 | 1 | 31 | | 10000 | 1 | 314 | +-------+---+--------+ ``` (These values were calculated using [this web applet](https://editor.p5js.org/KyleCow/full/SJbg0W6z4) from Reddit user [KyleCow1](https://www.reddit.com/r/3Blue1Brown/comments/agpnl3/i_made_the_collisions_demo_in_p5_js/). Please let me know if I've made any mistakes.) --- # Challenge Your challenge is to take two positive integers \$a, b \in \mathbb N\_{>0}\$, and output the number of collisions in this scenario. Your program should be able to handle all \$a, b \leq 10\,000\$. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest program wins. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~18~~ 16 bytes ``` ¯1+⌈○÷¯3○.5*⍨⎕÷⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOpD6w21H/V0PJrefXj7ofXGQFrPVOtR74pHvVsPb3/Uu6v2//8QkDog/1HnoiIg81FXc5o@UMZKPS0xM0cdyALKFT3qblHPz1av5TJUAAFDhRAFYy4jONuUyxiJbQJnm3GZwtnmXIYGILYxWNwcLG4EZlvC2eZQ843A5kPYpkC2EVCvAcxeQxAHyIVwTAA "APL (Dyalog Classic) – Try It Online") rendered as the equivalent `{¯1+⌈○÷¯3○.5*⍨⍵÷⍺}` in the tio link, to facilitate testing; `⎕` means evaluated input; `⍺` and `⍵` are the arguments to an anonymous function $$\left\lceil\frac\pi{\textrm{arctg}\sqrt\frac ba}\right\rceil-1$$ (that's the formula from [the video](https://www.youtube.com/watch?v=jsYwFizhncE). i recommend watching it. it's well explained and the animations are great for building intuition.) [Answer] # Jelly, ~~10~~ 9 bytes My first Jelly submission :') ``` ÷½ÆṬØP÷Ċ’ ``` *-1 byte* thanks to Mr.Xcoder Uses the formula as in the video. Receives the input flipped; OP gave permission. It probably has room for further golfing, so be sure to give me feedback! ``` ÷½ divide b by a and take square root ÆṬ take the ArcTan of that; then ÷ divide ØP pi by the number we had. Ċ Round up ’ and subtract one ``` [Try it online](https://tio.run/##y0rNyan8///w9kN7D7c93Lnm8IyAw9uPdD1qmPn///9oQx0FZGSso2AEQ6YQwViQIiMdYx0THVMdQwMdcx1LHUMQNDAAYQODWAA) [Answer] # JavaScript (ES7), ~~41~~ 39 bytes Takes input as `(a)(b)`. ``` a=>b=>3.14159265/Math.atan((b/a)**.5)|0 ``` [Try it online!](https://tio.run/##fdBLDoIwFAXQuavosCWx/0IYwA5cxAPBT0hrpHHk3quRCf3EOz25Ly/3Di9Yx@ft4Y/WnacwdwG6fuh6RYUWppW1YSfwVwoeLMYDA1JV1JA3D6Ozq1smurgLnrFA3xAsCEGMIXWIVUZqElV/VUdaJ2oibRIV/Keq3G22rixrG2l2OVJVVrOpzL7i@61EzpzvWIcP "JavaScript (Node.js) – Try It Online") ### How? Instead of using a *ceil* function and subtracting \$1\$, we deliberately use a slightly underestimated approximation of \$\pi\$ and *floor* the result with a bitwise OR. For \$a,b\le 10000\$, it was empirically proven to give the same results as this safer 44-byte version: ``` with(Math)f=a=>b=>ceil(PI/atan((b/a)**.5))-1 ``` [Try it online!](https://tio.run/##fdBBDoIwEAXQvadgOUMCbSmVuIC9CxOvMCAIhFAjjR6/GtnQlvi3L38y@SO9aGmew8Mks7611r4H08OFTI9dSWVVl1XTDhNcz4wMzQA1I4zjVCEmwjZ6XvTUppO@Qwci@gZBIEaMRfLgauao8lT@1dzRo6fK0cJTwX8q97vF2s329eRocNlRua9q1Sz4im@3EiFzvuHcfgA "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` a#b=ceiling(pi/atan(sqrt$b/a))-1 ``` [Try it online!](https://tio.run/##bdBRC8IgEAfw932Kg/ag4NicW6MH@yLVwy2kJGdr2uc3cRRMEl/8ecefuzu6hzImBNyN8qq00fZGZl2jR0vca/HlWCOlFQ9eOe9AwolwBvEKygr4HtIm6zcm/liXbL@xPtmwMd7EhLxwYNDmdkiWNScTucWcNgtp1lF4zr@Pjl6KYkJt4@Tzoq2HEtAYIGeCDEYGz7enUB0h7g@kXJ9pVeED "Haskell – Try It Online") [Answer] # Mathematica, ~~30~~ 29 bytes, 25 characters ``` ⌈Pi/ArcTan@Sqrt[#2/#]⌉-1& ``` [Try it online](https://tio.run/##y00syUjNTSzJTE78n2b7/1FPR0CmvmNRckhinkNwYVFJtLKRvrJh7KOeTl1Dtf9p0YY6hrEK@voKAUWZeSVcadFGaHxjNL4JGt8UjW9ooGOMImCuY4TCt0TjG2LwTdEMNMCwwgBV7D8A) *-1 byte* thanks to ExpiredData Uses the formula explained in the video. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~49~~ 43 bytes ``` ->a,b{(-1.arg/((a*b)**0.5+b.i).arg).ceil-1} ``` [Try it online!](https://tio.run/##Tc7BjoIwFAXQvV9xUzaApVIQzZigq1nNwoQtYdEizpiY0aAsDPTbmUeJzSRNm3N7@9K206/xnI/RXnHd@5EUqv1e@b4KdRCGsciWWlyCKQxE3VyukTRjuQBKyUErrfiExCKbkf7H2mIzI7PYzpAxPXdXW47E4cPi3bNIHWhI8p4Qz5@Qzi5ZU1SJRtU/ON0wKA7NceueAxVb5DiXU1SR7t3zAeb1lOZTAwew4xfDDuyzKI4FMxjg9cpw2rVBvqezNfC9ntomYIvm9zT@AQ "Ruby – Try It Online") -5 thans to G B, nicely done -1 replacing `1i*b` with `b.i` [Answer] # Excel, 35 ~~37~~ bytes -2 bytes thanks to @Chronocidal ``` =CEILING(PI()/(ATAN((B1/A1)^.5)),1)-1 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~63~~ \$\cdots\$ ~~47~~ 46 bytes ``` f(a,b){a=ceil(acos(-1)/atan(sqrt(b*1./a)))-1;} ``` [Try it online!](https://tio.run/##bVFta4MwEP7eX3EIQmLj1Fo7inNfxn7FlBFj7GRWOxOYTPzrc/EVLQuX43LPPU8uF2ZeGOu6FFES44YGjGc5oqwUyHSwRSUtkPiqJIoN58GiGGPT8dsuKyRcaVYgDM0O1OoTkgv5Tt8iCKBxCBwIuASOBDwCjk3gkcBZRaPZ9uBsu/W3/Hjhr80d5EbzxuSKyOsbZ5InI9UdSpSdhjtPczBquL2ac5zYrCyEBPZBK0N5zj55NYpoYf16COvzi9qeRmB9drWJnZYVoL6BrEh4rWi2P4VPILIfXqZobg1bU8JYMj7s90P1PMP5OVQpTbMc8MjfwPEMx//CQsH9b0KMtwBXwDKpe@atUiUp0vSEgJ6A@dx7XYSFenuvRUCQZUIiCHg0qbe7tvtlaU4vojO/OzO//gE "C (gcc) – Try It Online") *Saved ~~11~~ 12 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Uses the formula from the video as [ngn](https://codegolf.stackexchange.com/users/24908/ngn) recommended. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes ``` /t©ažq;‚Δ{ÐO;ż®‹èsO;‚}нžqs/î< ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fv@TQysSj@wqtHzXMOjel@vAEf@vDrYf2HFr3qGHn4RXF/iDx2gt7gSqK9Q@vs/n/39AACLgMAQ "05AB1E – Try It Online") Almost definitely golfable.. Implements the formula but because 05AB1E doesn't have arctan we have to calculate it, this does it by bisection. --- # Explanation ``` /t - sqrt(a/b) © - store this value ažq;‚ - the array [0, pi/2] Δ - repeat until the array passed in does not change {Ð - sort then triplicate array O;ż - arctan of the average of the array (bisection) ®‹ - is this greater than the sqrt(a/b)? 0 if so 1 if not èsO;‚ - Take the index from the current two guesses and combine with their average }н - Stop looping and get the first value - (this should be close enough to arctan(sqrt(a/b)) žqs/ - push pi then divide it by the atan(sqrt(a/b)) guess î< - ceil and decrement ``` [Answer] # [Rust](https://www.rust-lang.org/), 59 bytes ``` |a:f64,b:f64|(f64::acos(-1.)/(b/a).sqrt().atan()).ceil()-1. ``` [Try it online!](https://tio.run/##hZBNboMwEEb3OcUXFpEtuRB@kqignKCLHgChykRGQqKmwc6KcHZqOxRCNrWsGfvNzJPl7qb0WEl881oSin4DsxqhUeE83nlaHRNW2ngnJqQpv7SKvIU@DUgZcOqra6cJ9bnmZpz6F1E3hJr6aD3ZZtZpobTCGbkjQB4ymB0X7A9EDhwWEL@CxIHjAg4OnBYQ7o1y1XJiiFbg3YHnGQfiFTDi6Nm6fzw2XLGZJhMuMpdcqNoOu5wzlAztTReoJXaPT@gnB8CVEp3@EtctqQg3V9jvRjmdqBudsddK8BT9YDps8hisn2azLwhelLbsJP9NDy7@dLXUjdwS7/PDM5Vh/AU "Rust – Try It Online") [Answer] # J, 19 bytes ``` _1+1p1>.@%_3 o.2%:% ``` Try in Jconsole as the TIO seems to be quite weird. Usage: `f=:_1+1p1>.@%_3 o.2%:%` # Example `f 10000` => `314` [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` lambda a,b:ceil(pi/atan((b/a)**.5)-1) from math import* ``` [Try it online!](https://tio.run/##fdDfCoIwFAbwe5/iQDebrHSuJQk9iXkxK3Hg/jB209MvjaSp1Ln98X18HPv0vdEsdJdrGIRq7wIEaavbQw7Iykx4oRFqM4HT9MDxnuKkc0aBEr4HqaxxPg2dcVMIpIa6poQ2BN63A5ZAdHURG18a@2PH2E5L47GVS6M5YR/c5EpS/Ow8x7bujI2tjX@tWG/J56Vjjm5w5gmPozYVWCe1Rx0af4txeAE "Python 3 – Try It Online") [Answer] # AWK, ~~56~~ 55 bytes ``` {x=atan2(0,-1)/atan2(($2/$1)^.5,1);$0=int(x);$0-=$0~x}1 ``` [Try it online!](https://tio.run/##JclBCoAgFATQvadw4UJB839NIsKrBC4jcCUkRF3dvrZ4zDCTrrO1u8ZUUnYStEFl/y6FswLVPgWNahMQj1xk7c1EAW99sDXkyBzxZCaBIHDPFu7YSnAINMK4oOcH "AWK – Try It Online") I know I can save a few bytes by hardcoding Pi to some arbitrary precision, but I'm not sure how accurate it is outside of the provided test cases. [Answer] # [PHP](https://php.net/), 46 bytes ``` <?=ceil(pi()/atan(($argv[2]/$argv[1])**.5))-1; ``` [Try it online!](https://tio.run/##hdLNCoMwDADgu08RZIdWpm2qRZz7eYQ9wPQgIlMQJ875@p1O2GEj9hYSviSE9HVvzPFyKqumZX3DuCjGomNsVwz36aZysQaYc88LNOc@pqYq6we4WZd117GuBpiK9lU9D0vCTR1nLeMeABD8M7gBg9/2KPDbEHjgfuQKlQUqCoYWGFIwssCIgtoCNQVRzjKkYChQUjJeRipKKhFTMLHAhNzVAnETagrqDSjn82y9jvw/jzFzVkqDbw "PHP – Try It Online") Not very original I guess, applying the formula from the video.. ]
[Question] [ Given an integer `n >= 2`, output the largest exponent in its prime factorization. This is OEIS sequence [A051903](https://oeis.org/A051903). ## Example Let `n = 144`. Its prime factorization is `2^4 * 3^2`. The largest exponent is `4`. ## Test Cases ``` 2 -> 1 3 -> 1 4 -> 2 5 -> 1 6 -> 1 7 -> 1 8 -> 3 9 -> 2 10 -> 1 11 -> 1 12 -> 2 144 -> 4 200 -> 3 500 -> 3 1024 -> 10 3257832488 -> 3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ÓZ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8OSo//8NDYxMAA "05AB1E – Try It Online") **How?** ``` Ó exponents of prime factors Z maximum ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ ~~57~~ 56 bytes ``` lambda n:max(k%n-n%(k/n+2)**(k%n)*n for k in range(n*n)) ``` [Try it online!](https://tio.run/##RYyxDoIwGAZnfYpvaWhLifS3LiT6IupQo1WCfBACiT49ppPLJXfDjd/5NVDWhCMu6zv2t3sEmz5@dKdYUelux1KMtdmNJdIwoUNLTJHPh6alMWuO/Edx8HuDEmcfgoPUtcMhw9cSrs12M04tZxQqLKhOULIUUNB0SDrvfg "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆEṀ ``` **[Try it online!](https://tio.run/##y0rNyan8//9wm@vDnQ3///83NDAyAQA "Jelly – Try It Online")** ``` ÆEṀ - Full program / Monadic link. ÆE - Array of exponents of prime factorization. Ṁ - Maximum. ``` This also works in [M](https://github.com/DennisMitchell/m). [Try it online!](https://tio.run/##y/3//3Cb68OdDf///zc0MDIBAA "M – Try It Online") [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 2 bytes ``` n↑ ``` [Try it online!](https://tio.run/##y8/INfr/P@9R28T//w1NTAA "Ohm v2 – Try It Online") ## Explanation? No. [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` n=input() e=m=0 f=2 while~-n:q=n%f<1;f+=1-q;e=q*-~e;m=max(m,e);n/=f**q print m ``` [Try it online!](https://tio.run/##BcFBDoMgEAXQPafopolQiUK6Ev9hXAyBpDMFg7HdeHV8r/xb@orvXZClHG3QisCYVYRXZ8ofuqwsFfKMqwvxBWdrIFRjLwoM3n4Dj6SDTIjGVFX2LO3BvbvZv28 "Python 2 – Try It Online") -5 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs). This answer doesn't do prime checks. Instead, it takes advantage of the fact that the highest exponent of a prime factor will be greater than or equal to the exponent of any other factor in any factorization of a number. [Answer] # [Haskell](https://www.haskell.org/), ~~61~~ ~~60~~ ~~50~~ ~~48~~ 46 bytes -2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) ``` f n=maximum[a|k<-[2..n],a<-[1..n],n`mod`k^a<1] ``` [Try it online!](https://tio.run/##HcZNCsIwEAbQq2Sp8BkyMVUL7RE8QYh2QIshnbH4Ay68eywuHrwbP8t1mmodjfbCnyxvifwt3SZ6azWBl9F/Osj9MpQTd5SqcFbTG@H5eDar@ZH1Zce1iR5bBDTYYY8DWpADEciDQoB3Ds2CnA@p/gA "Haskell – Try It Online") ### 45 bytes with an import: ``` import NumberTheory maximum.map snd.factorize ``` [Try it Online!](https://tio.run/##DcmxDoIwFAXQ3a/oqMlN0z5aqQOfoJObMaZqCQ08IKUk6s9XhjOdzi99GIZSIs9TyuKy8jOkaxem9N21DftP5JUl@1ks41u2/pWnFH@hsI@jaMQW54fYzymOWbYHcSNUMLA4oobDCVpBa2iCNgakFOxGKzKoyNauIuPcvfwB) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~9~~ 7 bytes ``` k ü mÊn ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg=&code=ayD8IG3Kbg==&input=MTQ0) ``` k ü mÊn :Implicit input of integer k :Prime factors ü :Group by value m :Map Ê : Length n :Sort :Implicit output of last element ``` [Answer] # Mathematica, 27 bytes ``` Max[Last/@FactorInteger@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfN7Ei2iexuETfwS0xuSS/yDOvJDU9tchBOVbtf0BRZl6JgkNatLGRqbmFsZGJhUXsfwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` YFX> ``` [Try it online!](https://tio.run/##y00syfn/P9Itwu7/f0MTEwA "MATL – Try It Online") ``` % implicit input YF % Exponents of prime factors X> % maximum % implicit output ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ḋḅlᵐ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7oc7WnMebp3wqKfz/39jI1NzC2MjEwuL/1EA "Brachylog – Try It Online") ### Explanation ``` ḋ Prime decomposition ḅ Group consecutive equal values lᵐ Map length ⌉ Maximum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ▲mLgp ``` [Try it online!](https://tio.run/##yygtzv7//9G0Tbk@6QX///83NDAyAQA "Husk – Try It Online") * `p` – Gets the prime factors. * `g` – Groups adjacent values. * `mL` – Gets the lengths of each group. * `▲` – Maximum. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 19 bytes ``` ⎕CY'dfns' ⌈/1↓2pco⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqnOkeopaXnF6lyPejr0DR@1TTYqSM4HioMU/E/jsuDiSuMyNTAAUYYGRiYA "APL (Dyalog Unicode) – Try It Online") **How?** `2pco⎕` - 2D array of prime factors and exponents `1↓` - drop the factors `⌈/` - maximum [Answer] # Javascript 54 bytes \*assuming infinite stack (as do in code-golf challenges) ``` P=(n,i=2,k)=>i>n?k:n%i?k>(K=P(n,i+1))?k:K:P(n/i,i,-~k) console.log(P(2 )== 1) console.log(P(3 )== 1) console.log(P(4 )== 2) console.log(P(5 )== 1) console.log(P(6 )== 1) console.log(P(7 )== 1) console.log(P(8 )== 3) console.log(P(9 )== 2) console.log(P(10 )== 1) console.log(P(11 )== 1) console.log(P(12 )== 2) console.log(P(144 )== 4) console.log(P(200 )== 3) console.log(P(500 )== 3) console.log(P(1024 )== 10) //console.log(P(3257832488 )== 3) ``` [Answer] # PARI/GP, 24 bytes ``` n->vecmax(factor(n)[,2]) ``` If I do not count the `n->` part, it is 21 bytes. [Answer] # [Octave](https://www.gnu.org/software/octave/), 25 bytes ``` @(n)[~,m]=mode(factor(n)) ``` [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI08zuk4nN9Y2Nz8lVSMtMbkkvwgopvk/TcNYkytNwwREWIAIQxMw29DAyETzPwA "Octave – Try It Online") ### Explanation `factor` produces the array of (possibly repeated) prime exponents The second output of `mode` gives the number of times that the mode (i.e. the most repeated entry) appears. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` eShMr8P ``` [Try it here.](http://pyth.herokuapp.com/?code=eShMr8P&input=1024&debug=0) [Answer] # [Python 2](https://docs.python.org/2/), ~~90~~ 84 bytes ``` f=lambda n,i=2,l=[0]:(n<2)*max(map(l.count,l))or n%i and f(n,i+1,l)or f(n/i,2,l+[i]) ``` [Try it online!](https://tio.run/##DctBDsIgEIXhvaeYjQnYiQK2m0ZO0rBAa3USGBqCiZ4eZ/EW70@@/dfehV3vm08x39cIjOQdJr@YMCu@OX3K8aty3FU6P8qHGyatSwU@EkReYVMiBitVopwLofBhoaD7JomAGGrk11M5tFc9LHYc0RmDk8waN4b5ALBX4iaedP8D "Python 2 – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 4 bytes ``` ḋ)⌠) ``` **[Try it online!](https://tio.run/##S0/MTPz//@GObs1HPQs0//83NgMA "Gaia – Try It Online")** * `ḋ` - Computes the prime factorization as **[prime, exponent]** pairs. + `⌠` - Map and collect the result with the maximal value. + `)` - Last element (exponent). + `)` - Last element (maximal exponent) # [Gaia](https://github.com/splcurran/Gaia), 4 bytes ``` ḋ)¦⌉ ``` [Try it online!](https://tio.run/##S0/MTPz//@GObs1Dyx71dP7/b2wGAA "Gaia – Try It Online") * `ḋ` - Computes the prime factorization as **[prime, exponent]** pairs. + `)¦` - Map with the last element (exponent). + `⌉` - Gets the maximum element. [Answer] # [MY](https://bitbucket.org/zacharyjtaylor/my-language), 4 bytes ``` ωĖ⍐← ``` [Try it online!](https://tio.run/##y638//9855Fpj3onPGqb8P//fyMA "MY – Try It Online") ## Explanation? ``` ωĖ⍐← ω = argument Ė = prime exponents ⍐ = maximum ← = output without a newline ``` [Answer] # [Octave](https://www.gnu.org/software/octave/): 30 bytes ``` @(x)max(histc(a=factor(x),a)); ``` 1. `a=factor(x)` returns a vector containing the prime factors of `x`. This is a vector sorted in ascending order where the multiplication of all numbers in `factor(x)` yields `x` itself such that each number in the vector is prime. 2. `histc(...,a)` calculates a histogram on the prime factor vector where the bins are the prime factors. The histogram counts up how many times we have seen each prime number thus yielding the exponent of each prime number. We can cheat here a bit because even though `factor(x)` will return duplicate numbers or bins, only one of the bins will capture the total amount of times we see a prime number. 3. `max(...)` thus returns the largest exponent. ## [Try it online!](https://tio.run/##DczLCsMgFIThV5nlEbLwlsZWAn2P0sXBGCo0CokpeXvrbv5vMSVU/sWWMeOlYWAx4oYJDncoCaWgNJS10LKX1BZGj5Mz2jr39u1Jl9j4ok86aiCeVw617B0HFsK3texI/VrhgXxu8UtZDFgoiY6cD8p9Co@Yl87tDw "Octave – Try It Online") [Answer] # [Racket](https://racket-lang.org/), ~~83~~ 79 bytes ``` (λ(n)(cadr(argmax cadr((let()(local-require math/number-theory)factorize)n)))) ``` [Try it online!](https://tio.run/##HYxLDsIwDAX3PYUlNvai4iMuZFKnjUgcsByJcjXuwJVC6VvNzOIZh7t4P2TWGWyXASeJSQViU@j4/aASBp4M2ebCL9gZszgS5ho4jybPlkygsC9HbeUmNvoi1VaKHLxaegspbes04MOSOuD//ny6XLf4Aw "Racket – Try It Online") (I'm not sure if there's a consensus on what constitutes a complete Racket solution, so I'm going with the Mathematica convention that a pure function counts.) ### How it works `factorize` gives the factorization as a list of pairs: `(factorize 108)` gives `'((2 2) (3 3))`. The second element of a pair is given by `cadr`, a shorthand for the composition of `car` (head of a list) with `cdr` (tail of a list). I feel silly doing `(cadr (argmax cadr list))` to find the maximum of the second elements, but `max` doesn't work on lists: `(max (map cadr list))` doesn't do what we want. I'm not an expert in Racket, so maybe there's a standard better way to do this. # Racket, 93 bytes ``` (λ(n)(define(p d m)(if(=(gcd m d)d)(+(p d(/ m d))1)0))(p(argmax(λ(d)(p d n))(range 2 n))n)) ``` [Try it online!](https://tio.run/##LY1LCsNADEP3OYWhG5kumoRse5gh82FoYgaTQu/WO/RKEzsUvJCeLKRhfaWj37YghfQyA2LKVRLlt1DH7wvhP0KjSDujZjxRVtMUOTLuHuBxWZ54ZEZD0LKHj/ftw4tiWG0n0ezarvOAplUOgo9N47wYPAE "Racket – Try It Online") ### How it works An alternative version that doesn't import `factorize` and instead does everything from scratch, more or less. The function `(p m d)` finds the highest power of `d` that divides `m` and then we just find highest value of `(p n d)` for `d` between `2` and `n`. (We don't need to restrict this to primes, since there will not be a composite power that works better than prime powers.) [Answer] ## [Alice](https://github.com/m-ender/alice), 17 bytes ``` /o \i@/w].D:.t$Kq ``` [Try it online!](https://tio.run/##S8zJTE79/18/nysm00G/PFbPxUqvRMW78P9/QxMTAA "Alice – Try It Online") ### Explanation ``` /o \i@/... ``` This is just a framework for simple-ish arithmetic programs with decimal I/O. The `...` is the actual program, which already has the input on the stack and leaves the output on top of the stack. Alice actually has built-ins to get the prime factorisation of an integer (even with prime-exponent pairs), but the shortest I've come up with using those is 10 bytes longer than this. Instead the idea is that we repeatedly divide one copy of each distinct prime factor out of the input, until we reach **1**. The number of steps this takes is equal to the largest prime exponent. We'll be abusing the tape head as the counter variable. ``` w Remember the current IP position. Effectively starts a loop. ] Move the tape head to the right, which increments our counter. .D Duplicate the current value, and deduplicate its prime factors. That means, we'll get a number which is the product of the value's unique prime factors. For example 144 = 2^4 * 3^2 would become 6 = 2 * 3. : Divide the value by its deduplicated version, which decrements the exponents of its prime factors. .t Duplicate the result and decrement it. This value becomes 0 once we reach a result of 1, which is when we want to terminate the loop. $K Jump back to the beginning of the loop if the previous value wasn't 0. q Retrieve the tape head's position, i.e. the number of steps we've taken through the above loop. ``` [Answer] # Julia, 60 52 40 bytes ``` f(x)=maximum(collect(values(factor(x)))) ``` -12 +correction thanks to [Steadybox](https://codegolf.stackexchange.com/users/61405/steadybox) [Answer] # [Actually](https://github.com/Mego/Seriously), 4 bytes ``` w♂NM ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/7/80cwmP9///w0NjEwA "Actually – Try It Online") ``` w♂NM - Full program. w - Pushes the prime factorization as [prime, exponent] pairs. ♂N - Get the last element of each (the exponents). M - Maximum. ``` [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes *-4 bytes thanks to H.PWiz.* ``` lambda n:max(a*(n%k**a<1)for a in range(n)for k in range(2,-~n)) ``` [Try it online!](https://tio.run/##RYzLDoIwFET3fMVsTFpyTdqKLyJfoi6uEbRBLgS60I2/XgsbJ5nNmckZPuHZi4tNdYkv7m53hpQdvxXnSlZtnvPJ6qYfwfCCkeVRK1lA@weO1l/ROoZ6ChMqnB1hQygIW8KOsCccCEeCNak2NR1skXZnEtkac82y2eln52IpM6QMo5eARnkdfw "Python 2 – Try It Online") Port of [H.PWiz's Haskell answer](https://codegolf.stackexchange.com/a/145941/68615). I'm only sharing this because I'm proud that I was able to understand this piece of Haskell code and translate it. :P [Answer] # Axiom, 61 bytes ``` f n==(a:=factors n;reduce(max,[a.i.exponent for i in 1..#a])) ``` This is the first time i find it is possible define the function without the use of () parenthesis. Instead of "f(n)==" "f n==" one character less... [Answer] # J, 9 bytes ``` [:>./_&q: ``` Max of `<./` all prime exponents `_&q:` [Try it online!](https://tio.run/##Xc@/DsIgEAbwnaf44mBtYurdARZJ8EUcHIzEuBjT2WdHWxOaY2D4wf35eJY8IUUQfqdc4nk4XLfvWHqzGdDlFDvs8YnIkzHmfnu8sMuQHglcaTXdTKn0@vWoOWqGmbbypEcx6WrmxtLUuyWLW4MT6QW@vWCSpYdp/Z74MVhx4R@ufAE "J – Try It Online") [Answer] # APL(NARS), 15 chars, 30 bytes ``` {⌈/+/¨v∘=¨v←π⍵} ``` test: ``` f←{⌈/+/¨v∘=¨v←π⍵} f¨2..12 1 1 2 1 1 1 3 2 1 1 2 f¨144 200 500 1024 3257832488 4 3 3 10 3 ``` comment: ``` {⌈/+/¨v∘=¨v←π⍵} v←π⍵ π12 return 2 2 3; assign to v the array of prime divisors of argument ⍵ v∘=¨ for each element of v, build one binary array, show with 1 where are in v array, else puts 0 return one big array I call B, where each element is the binary array above +/¨ sum each binary element array of B ⌈/ get the max of all element of B (that should be the max exponet) ``` ]
[Question] [ A [superpermutation](https://en.wikipedia.org/wiki/Superpermutation) on n symbols is a string which contains every permutation of n symbols in its body. For instance, `123121321` is a superpermutation on three symbols because it contains `123`, `132`, `213`, `231`, `312` and `321` as substrings. # The Challenge Given a string composed of n unique symbols (and, optionally, n), output whether it is a superpermutation on n symbols. # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. * Assume only valid input will be given. * Assume n is greater than 0 * Input and output can assume whatever form is most convenient, e.g. the series of symbols can be a string, a list, an integer, a set of n bitmasks, etc, so long as it is indicated in the answer. Additionally, anything may be used as a symbol provided it is distinct from all the other symbols. # Test Cases ``` In: 1234 Out: False In: 1 Out: True In: 11 Out: True In: 123121321 Out: True In: 12312131 Out: False ``` See also: [this question](https://codegolf.stackexchange.com/questions/179607/) about generating superpermutations [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÙœåP ``` Only takes input \$J\$ (I don't need \$n\$ with this approach). [Try it online](https://tio.run/##yy9OTMpM/f//8Myjkw8vDfj/39DI2NDI0NjIEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8Mzj04@vDTgv87/aEMjYxMdQx1DIDIyNjQyNDaCswxjAQ). **Explanation:** ``` Ù # Uniquify the digits of (implicit) input-integer œ # Get all permutations of this uniquified integer å # Check for each if it's a substring of the (implicit) input-integer P # And check if this is truthy for all of them # (after which the result is output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 20 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) ``` {(!⍺)=+/⍺=⍴∘∪¨∪⍺,/⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pD8VHvLk1bbX0gZfuod8ujjhmPOlYdWgEkgCI6QOGttf/THrVNeNTb96ir@VHvGqCiQ@uNH7VNfNQ3NTjIGUiGeHgG/zdRSFMAsoEq1Q2NjE3UuQzhAoZAxeqGCshC6oaG6lzGKFoMjQyNjbCKGqoDAA "APL (Dyalog Unicode) – Try It Online") Takes `n` on the left and `J` on the right ### How? ``` ⍺,/⍵ ⍝ Overlapping sublists of length n in J ∪ ⍝ Unique sublists ⍴∘∪¨ ⍝ Length of the unique elements of each unique sublist +/⍺= ⍝ How many are equal to n? (!⍺)= ⍝ Is this equal to the number of permutations of n symbols? ``` [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` lambda s:all(''.join(p)in s for p in permutations({*s})) from itertools import* ``` [Try it online!](https://tio.run/##TYwxDsIwEAT7vOKa6JwoIGxTReInNEbEwsj2Wb5LgRBvNwkVxa5mit3ykgdl2/zl2qJLt7sDnl2MCvH4pJBVGUIGBk8VCmxYlppWcRIos3qP/BmGzldKEGSpQhQZQipUZWz7ZrOM2tgzTqj3/MpYbbQ1f6xx7qDUkEVhf9Anxp4nr3h7b18 "Python 3 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 81 bytes ``` lambda s:all(''.join(p)in s for p in permutations(set(s))) from itertools import* ``` [Try it online!](https://tio.run/##TYyxDgIhEER7vmKby4I5jYDVJf6JDcYjYoAl7Fr49XhnZTGT94qZ9pEnVTfi9TZyKPdHAF5Czhrx9KJUdTOpAkOkDg02bGsvbwmSqLLmVTQbY1TsVCDJ2oUoM6TSqMth7KvNKlrnLzij3fMr562z3v2xxUVB66kK4HS0Z8aJ57jdq/EF "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~83 82~~ 81 bytes Returns `0` if the input string is a superpermutation, or `1` if it's not. ``` f=(s,a=[...new Set(s)],p)=>!s.match(p)|a.some((c,n)=>f(s,a.filter(_=>n--),[p]+c)) ``` [Try it online!](https://tio.run/##fcuxDsIgFEDR3a/QTu9FeAngSn/CsWkMQdAaCqQQXfx3tKtpXO/JfZinKXaZcuUxXV1rXkNhRg9EFN1rf3YVCo4so@4PhWZT7R0yvg2VNDsAy@JX/PqQn0J1C1x0HzlHNuTxaBGbTbGk4CikG3johFSnDnH3m7faZpRKSKHkH1upfQA "JavaScript (Node.js) – Try It Online") ### How? If all permutations of the \$N\$ symbols are present in the input string \$s\$, so are all prefixes of said permutations. Therefore, it's safe to test that all \$p\$ are found in \$s\$ even when \$p\$ is an incomplete permutation whose size is less than \$N\$. That's why we can use a function that recursively builds each permutation \$p\$ of the symbols and tests whether \$p\$ exists in \$s\$ at each iteration, even when \$p\$ is still incomplete. ### Commented ``` f = ( // f is a recursive function taking: s, // s = input string a = [...new Set(s)], // a[] = list of unique characters in s p // p = current permutation, initially undefined ) => // !s.match(p) | // force the result to 1 if p is not found in s // NB: s.match(undefined) is truthy because it's equivalent // to looking for an empty string in s a.some((c, n) => // for each character c at position n in a[]: f( // do a recursive call: s, // pass s unchanged a.filter(_ => n--), // remove the n-th character in a[] (0-indexed) [p] + c // coerce p to a string and append c to p ) // end of recursive call ) // end of some() ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~10~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Saved 2 bytes with the clarification that the string can only contain the digits in `[1,n]`. ``` â á e!øU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=4iDhIGUh%2bFU&input=IjEyMzEyMTMyMSI) ``` â á e!øU :Implicit input of string U â :Deduplicate á :Permutations e :All !øU : Contained in U ``` [Answer] # [Io](http://iolanguage.org/), 104 bytes ``` method(x,n,K :=Range 1 to(n)asList;x map(i,v,x slice(i,i+n))unique select(x,x sort==K)size==K reduce(*)) ``` [Try it online!](https://tio.run/##jYyxDoJAEER7v2LLW93mgErDF2BlbUNg0U2OO@AOQ/z58wKxMMbEal5mXkZc7OBYwjX2HO6uVQtZqlJzqe2NQUNwymLtz@LDaYG@HpTQgxbwRhpOLAeLOFsZZwbPhpuQLtLsplCWFXp5ckqYuJ2Tv0eMnTLpTGmCjCAnKJAKhGESG4zdvVck/V0S/Oq3qw30ytkq5//JH2Z8AQ "Io – Try It Online") ## Explanation (Ungolfed) ``` method(x,n, // Take the string and the num of uniquified integers K := Range 1 to(n)asList // K = [1..n] x map(i,v,x slice(i,i+n)) // All slices of x of length n unique // Uniquify these slices select(x, // Filter: (x : current item) x sort==K // sort(x) == [1..n]? ) size // Number of items that satisfy this == K reduce(*) // == factorial(n)? ) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` dpᶠ~sᵛ? ``` Same algorithm as [@Kevin Cruijssen](https://codegolf.stackexchange.com/a/207466/95594), so upvote that. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P6Xg4bYFdcUPt862//9fydDI2NDI0NjIUOk/AA "Brachylog – Try It Online") ### How it works ``` dpᶠ~sᵛ? d deduplicate input pᶠ find all permutations ~sᵛ all of them must be substrings of ? the input ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Union[##~Partition~1]~Count~{a__/;0!=a}<#2!& ``` [Try it online!](https://tio.run/##TYyxCoMwFEV3/8IEnCxtkm6t8sC1g1A6SZCHaJPBCOnrFMyvp2IXl3M5HLgzkhlnJDtgmqr0cnZxHeexRU@WNolCx2b5OooB@/58u@QVrncu8yI9B3Rd662jjp/qCYDrAkJj0ONAo/8ALx@je5OB/RaOZS00hIwJqa6s3HbHn1IJKZQ8imDZmn4 "Wolfram Language (Mathematica) – Try It Online") Takes a list of characters and \$n\$ as input. Returns `False` if the string is a superpermutation, and `True` otherwise. Verifies that the number of unique sequences of \$n\$ distinct characters is (un)equal to \$n!\$. [Answer] # [R](https://www.r-project.org/) + gtools, 79 bytes ``` function(x,n)all(sapply(apply(permutations(n,n),1,paste0,collapse=""),grepl,x)) ``` [Try it online!](https://tio.run/##Zc29CsMgFAXgPU8R7KJwh6pzhg7plKk/D2CDDYFbvXgVkqe3KV1KCofDGT44qeL8SC6tcsoxIquGC/m05VWyy3MMXX2WMH6WXCAohyjZEeEqv/1DWYZNgAZynP0RxojoiH0nhIIpeUJYlKr7Bym0sdpoa7QAq9pDe7vc@@af7dT5NFz7@gY "R – Try It Online") An example of some awfully-verbose names for R functions and mandatory arguments! Generates all permutations of digits 1..n, pastes them together as strings, and checks that all are present in the input string. An alternative **66 byte** solution using the R "combinat" library would be: `function(x,n,`[`=sapply)all(permn(n)[paste0,collapse=""][grepl,x])`, but unfortunately this library isn't installed on TIO. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!ẇ€Ạ ``` A dyadic Link accepting \$n\$ on the left and the candidate as a list of integers on the right which yields `1` (is) or `0` (is not) as appropriate. **[Try it online!](https://tio.run/##y0rNyan8///oJMWHu9ofNa15uGvB////jf9HG@oY6RjrgEhDEB0LAA "Jelly – Try It Online")** ### How? ``` Œ!ẇ€Ạ - Link: n, L Œ! - all permutations of [1..n] € - for each (permutation, p): ẇ - is (p) a sublist of (L)? Ạ - all? ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Subsequences@#~SubsetQ~Permutations@Union@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P7g0qTi1sDQ1Lzm12EG5DswtCawLSC3KLS0BqsrPK3YIzQNSDspq/wOKMvNKFPQd0h20nDMSixKTS1KLivUdqpUMjYxNlHSUDEEYTBgZGxoZGhshsQ2Vav//BwA "Wolfram Language (Mathematica) – Try It Online") @att saved 31 bytes [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` import Data.List s p=all(`isInfixOf`p)$permutations$nub$p ``` [Try it online!](https://tio.run/##BcExCoAwDADA3Vc4dFAQoe5uLoLgA0RohBaDbRqaCP6@3t0gj4@xVkyci7YLKIwbijbS8gwxdg5lpYDfHhz3hn1Jr4JiJjH0XoZrAqSZC5IaOewwDfasPw "Haskell – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` Λ€¹Pu ``` [Try it online!](https://tio.run/##yygtzv7//9zsR01rDu0MKP3//7@SoZGxoZGhsZGhEgA "Husk – Try It Online") Same as the Jelly answer. [Answer] # Scala `-deprecation -encoding=UTF-8 -feature -unchecked -language:postfixOps -language:implicitConversions -language:higherKinds -language:existentials -language:postfixOps -Xfuture -Yno-adapted-args -Ywarn-dead-code -Ywarn-numeric-widen -Ywarn-value-discard -Ywarn-unused`, 44 bytes ``` s=>s.distinct.permutations forall s.contains ``` Pretty straightforward. Finds all the distinct symbols, generates all their permutations, and then checks if each permutation is in the input string. [Try it online](https://scastie.scala-lang.org/T5tiM4TESvmq3Y3fyPUTkA) # Scala, ~~56~~ 54 bytes ``` (s,>)=>(1 to>).mkString.permutations forall s.contains ``` As you can tell, the superpermutation string is ~~`|`~~ `s`(lot less readable now) and `n` is `>`. It basically just generates every permutation in the range `1 to n` and checks if each of those are in the input string. [Try it online!](https://scastie.scala-lang.org/YqSl0SDJQHyPn2tc8s0Hqw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` Nθ⁼ΠEθ⊕ιLΦEη✂ηκ⁺κθ¹∧⁼κ⌕ηι⁼θLΦι⁼μ⌕ιλ ``` [Try it online!](https://tio.run/##XYzBDoIwEETvfEWP26QeCkdOHiQhEUPiF9TSSONSaGn9/boY1MS97M7svNGjCnpWmHPrlhQvabqZAJ7XRR@si3DySeEKfZiHpCN0agEvWOt0MJNx0QxgORfsbNw9jtBYjIRvqVGwK1pttuMhWI9pBdqewnIjjm74lJPdWJKUfJfttv@vtd/XtBPkIP9NnXNVyLKSpaxKmQ9PfAE "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a superpermutation, nothing if not. Explanation: ``` Nθ ``` Input `n` as a number. ``` ⁼ΠEθ⊕ι ``` `n!` must equal... ``` LΦEη✂ηκ⁺κθ¹ ``` ... the number of truncated suffixes of the string... ``` ∧⁼κ⌕ηι ``` ... that have not already been seen earlier in the string, and... ``` ⁼θLΦι⁼μ⌕ιλ ``` ... contain `n` distinct characters. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` .Am}dz.p{z ``` [Try it online!](https://tio.run/##K6gsyfj/X88xtzalSq@guur/f0MjY0MjQ2MjQwA "Pyth – Try It Online") --- Explanation: ``` .Am}dz.p{z {z Deduplicate, yielding the distinct digits .p Permutate m Map with d as variable }dz Check if d is a substring of z .A Verify that all elements are truthy ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` UṖƛ∑⁰$c;A ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=U%E1%B9%96%C6%9B%E2%88%91%E2%81%B0%24c%3BA&inputs=%27123121321%27&header=&footer=) A mess. [Answer] # Java 10, ~~291~~ ~~287~~ ~~233~~ 229 bytes ``` n->{var t="";for(var d:n.split(t))t+=t.contains(d)?"":d;return p(n,"",t);}boolean p(String n,String p,String s){int l=s.length(),i=0;var r=n.contains(p);for(;i<l;)r&=p(n,p+s.charAt(i),s.substring(0,i)+s.substring(++i));return r;} ``` -4 bytes by taking inspiration from what [*@Arnauld* mentioned in his JavaScript answer](https://codegolf.stackexchange.com/a/207483/52210): > > If all permutations of the \$N\$ symbols are present in the input string \$s\$, so are all prefixes of said permutations. Therefore, it's safe to test that all \$p\$ are found in \$s\$ even when \$p\$ is an incomplete permutation whose size is less than \$N\$. > > > That's why we can use a recursive function that recursively builds each permutation \$p\$ of the symbols and tests whether \$p\$ exists in \$s\$ at each iteration, even when \$p\$ is still incomplete. > > > Takes the integer-input as String. [Try it online.](https://tio.run/##TZHBboMwDIbvfQorhykWFJV2JzI2TTuvlx6nHVJI23RpQInpNCGenQUGXQ9x7Dj6vz/OWV7l8lx@9YWR3sO71LZdAGhLyh1koWA7lAD7qjJKWij4jpy2R7AoQqNbhLAFCzn0dvncXqUDyhkTh8rxoSgzm/jaaOKESFFOSVFZChTPS3xhLCuFU9Q4CzW3MWMxoejETKtvtHhK6jnx2AaTYHKfGGWPdOIY63wlBqjL7T@mxtGM0E9GoHvIB04d@aQ4SfdKXGPsE9/s/SjLV7HG6P4gijTi7NGJrg8Prpu90QV4khS2a6VLuATWZPbjEyT@TW0AT35JeXqTXmVWfcN8sWXpevPIYpYOawzrTbpON@u7PGUdjmoAux9P6pJUDSV1UCBj@awbsQxYNIgPf8gxCSO4NXH6rK7/BQ) **Explanation:** ``` n->{ // Method with String as parameter and boolean return-type var t=""; // Temp String, starting empty for(var d:n.split(t)) // Loop over the digits of the input: t+= // Append to String `t`: t.contains(d)? // If `t` contains this digit already: "" // Append nothing : // Else (it doesn't contain this digit yet): d; // Append this digit return p(n,"",t);} // Call the separated recursive method to check if each // permutation of `t` is a substring of `n` and return it as // Separated recursive method to get all permutations of String `t`, and check for each // if it's a substring of String `n` boolean p(String n,String p,String s){ int l=s.length(), // Get the length of the input-String `s` i=0; // Set the index `i` to 0 var r= // Result-boolean, starting at: n.contains(p); // Check that String `n` contains part `p` as substring instead // (this doesn't necessary have to be the full permutation, // but it doesn't matter if the part is smaller) for(;i<l;) // Loop `i` in the range [0, length): r&= // Add the following to the boolean-return (bitwise-AND style): p( // Do a recursive call with: n,p // The current part, +s.charAt(i),// appended with the `i`'th character as new part s.substring(0,i)+s.substring(++i)); // And the String minus this `i`'th character as new String // (and increment `i` for the next iteration in the process) return r;} // And return the resulting boolean ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, 44 bytes ``` p$_.chars.uniq.permutation.all?{|x|$_[x*'']} ``` [Try it online!](https://tio.run/##KypNqvz/v0AlXi85I7GoWK80L7NQryC1KLe0JLEkMz9PLzEnx766pqJGJT66QktdPbb2/39DI2MTLkMuQyAyMjY0MjQ2grMM/@UXgLQV/9fNywEA "Ruby – Try It Online") [Answer] # T-SQL, 186 bytes Returns 1 for true, 0 for false. This struggles with more than 6 unique characters ``` WITH B as(SELECT distinct substring(@,number,1)a FROM spt_values),C as(SELECT a y FROM b UNION ALL SELECT y+a FROM B,C WHERE y like'%'+a+'%')SELECT 1/sum(1)FROM C WHERE replace(@,y,'')=@ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1268288/verify-a-superpermutation)** ungolfed ]
[Question] [ **The Challenge:** Draw a rectangle of ASCII boxes: [] **The Rules:** Takes a width and a height input You can assume both of these are numbers Must produce a string with newline characters, \n **Examples:** 2, 2: ``` [][] [][] ``` 2, 3: ``` [][] [][] [][] ``` Fewest Bytes wins. [Answer] # [SOGL](https://github.com/dzaima/SOGL), 5 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Ƨ[]*∙ ``` Simple: ``` Ƨ[] push "[]" * multiply horizontally (repeating width times) ∙ get an array with input (height) items of that implicitly output the array joined with newlines ``` [Answer] # Mathematica, 26 bytes ``` Grid@Table["[]",{#2},{#}]& ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` v&DiiX" ``` [Try it online!](https://tio.run/##y00syfn/v0zNJTMzQun/f2MuIwA "MATL – Try It Online") ### Explanation ``` v % Concatenate the (non-existing) stack contents: gives [] &D % String representation: gives '[]' ii % Take two inputs X" % Repeat those numbers of times vertically and horizontally. Implicit display ``` [Answer] # Pyth - ~~7~~ 5 bytes -2 bytes by a clever trick thanks to insert\_name\_here ``` VE*`Y ``` [Try it here](https://pyth.herokuapp.com/?code=VE%2a%60Y&input=8%0A4&debug=0) Explanation: ``` VE*`Y V # Loop E # <input> number of times `Y # String representation of empty list (used to be "[]", but insert_name_here pointed out this shorter alternative) * # repeat string implicit input number of times # implicit print ``` [Answer] # C, ~~47~~ 46 bytes ``` f(w,h){for(h*=w;h--;)printf(h%w?"[]":"[]\n");} ``` or ``` f(w,h){for(h*=w;h--;)printf("[]%c",h%w?0:10);} ``` My first code golf attempt, did I miss anything obvious? [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` F„[]×, ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f7VHDvOjYw9N1/v834TIGAA "05AB1E – Try It Online") **Explanation** Input takes as `height, width` ``` F # height times do „[] # push "[]" × # repeat width times , # print with newline ``` [Answer] # [;#+](https://github.com/ConorOBrien-Foxx/shp), 197 bytes ``` >;;;;;;~++++++++:>~;;;;:>~*(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)-::<-::::>-::(;)::>-::*(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)-:<~<;;;;;-+>-:<-:-(-:::~<-:::(~<#<-;;-#~;)-:<#-::<;>-:-) ``` [Try it online!](https://tio.run/##lY4xDsAgDAP5C0sgytJuIeI9HSt199dpEtEHNBJE9lmG57rXmiMHvEcnQvvqJAoDi@r0owaTL8VII1jC3vyyUClptO3/7HCe3xF2x/uEgiKbCVZNnFWMiNZ4cnhO2lpnOcoL ";#+ – Try It Online") Requires a zero byte after each input number. I kinda don't know how this works. What I can tell you is that this part of the code: ``` *(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*)-::<-::::>-::(;)::>-::*(-:~<~+-::>-:::<~<-+++++++++~:::<~+-:::>-::*) ``` is parsing the input numbers. [Answer] # brainfuck, 145 bytes ``` +++++++++[>++++++++++<-]>+[>+>+<<-]>>++>,>+++++++++[<----->-]<--->>>,>+++++++++[<----->-]<--->++++++++++<[<<<[>+>+<<-]>[<<<.>.>>-]>[<<+>>-]>>.<-] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwai7eBMbRvdWDuQgJ22DYgJlLHTQUhH2@iCgJ1uLIhhZ4dHDsnIaBsbG4SRIJ6enZ6dHYStDWbY6QGluP7/NzUFAA) My first ever code golf! Yay! The input is in ascii + 48, so in order to do 50, 50 you must input b, b (the ascii letters for 98) ## Explanation ``` +++++++++[>++++++++++<-]>+ Get the opening square bracket into first position [>+>+<<-] Get it into the second and third position >>++ Get the third position to be the closing bracket > ,>+++++++++[<----->-]<--- Get first number into fourth cell >>> ,>+++++++++[<----->-]<--- Get second number into seventh cell >++++++++++ get newline into 8th position < [ Start our height loop <<<[>+>+<<-] Get the width into the fifth and sixth positions >[ Start our width loop at the fifth position <<<.>. Print the second and third positions >>-] Decrement the fifth position > [<<+>>-] copy the sixth position into the fourth position >>. print newline <-] ``` [Answer] # [J](http://jsoftware.com/), 12 bytes ``` '[]'$~],+:@[ ``` [Try it online!](https://tio.run/##LcoxC8IwFATgPb/iECEWY0yjLimCKDiJg2vpEEJKq8UWEx396/G1yHGP4/Hd00zyGnsDLqBgqCuJ001czomXFZ9/K7E0hzJlLLqRaUpB3dBVlAL59NliN26FnF2PEu1zeEdoAW2Yd02Pek14aN0D0U2i//gXbNch@hDhbPDhTxdCEvfWNRnh9AM "J – Try It Online") ## Explanation ``` '[]'$~],+:@[ input: y, x +:@[ double y ], pair with x this gives (x, 2y) $~ shape the left argument into the right argument's shape '[]' 2-length character string ``` This gives us an `x` by `2y` string of repeating `[]` characters. [Answer] # Python 2.7, 32 bytes Full program: ``` n,m=input() exec"print'[]'*n;"*m ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P08n1zYzr6C0REOTK7UiNVmpoCgzr0Q9OlZdK89aSSv3/38jHWMA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẋ⁾[]ẋ$Y ``` A dyadic link returning a list of characters (or a full program printing the result). **[Try it online!](https://tio.run/##y0rNyan8///hru5HjfuiY4G0SuT///@N/hsDAA)** ### How? ``` ẋ⁾[]ẋ$Y - Main link: number w, number h e.g. 2, 3 ẋ - repeat w h times [2,2,2] $ - last two links as a monad: ⁾[] - literal ['[',']'], "[]" ẋ - repeat list (vectorises) ["[][]","[][]","[][]"] Y - join with newlines "[][]\n[][]\n[][]" - if a full program, implicit print ``` [Answer] # [Retina](https://github.com/m-ender/retina), 32 bytes ``` .+ $* 1(?=1*(¶1+))|. $1 G`1 1 [] ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLUMPe1lBL49A2Q21NzRo9LhVDLvcEQy5DrujY//@NuYwA "Retina – Try It Online") Takes height and width input on separate lines. [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` lambda n,m:('[]'*n+'\n')*m ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFPJ9dKQz06Vl0rT1s9Jk9dUyv3f0FRZl6JRpqGkY6xpuZ/dWVlBSAEkepcxgA "Python 3 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), 7 bytes ``` Ài[]<esc>ÀÄ ``` where `<esc>` is `0x1b`. [Try it online!](https://tio.run/##K/v//3BDZnSs9OGGwy3///83@W8KAA "V – Try It Online") ### Explanation ``` Ài[]<esc> " arg1 times insert [] ÀÄ " arg2 times duplicate this line ``` [Answer] # [Ohm](https://github.com/nickbclifford/Ohm), 9 bytes ``` M"[]"┘ÄJ, ``` [Try it online!](https://tio.run/##y8/I/f/fVyk6VunRlBmHW7x0/v834jIGAA "Ohm – Try It Online") ### Explanation ``` M"[]"┘ÄJ, M //Executes code input1 times "[]" //Pushes [] ┘Ä //Duplicates [] input2 times J //Joins the stack , //Prints with a trailing newline ``` [Answer] # PowerShell, 25 Bytes ``` param($w,$h),("[]"*$w)*$h ``` -3 thanks to Mathias! [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~13~~ 12+1= ~~14~~ 13 bytes +1 for the `-R` flag. ``` "[]"pN× òU*2 ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=IltdInBO1yDyVSoy&input=NSw2Ci1S) * 1 byte saved thanks to obarakon. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 11 bytes ``` '[]'⍴⍨⊢,2×⊣ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@lR2wT16Fj1R71bHvWueNS1SMfo8PRHXYv//zdSSFIw4jIGkQA "APL (Dyalog Unicode) – Try It Online") `'[]'` the string `⍴⍨` cyclically repeated to fill the shape `⊢` right argument (rows) `,` and `2×` twice `⊣` the left argument (columns) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~8~~ 7 bytes ``` EN×[]Iη ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDM6@gtMSvNDcptUhDU0chJDM3tVhDKTpWSUfBObG4RCNDU1PT@v9/Iy7j/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order height, width. Charcoal's drawing primitives aren't suited to this, so this just takes the easy way out and repeats the `[]` string appropriately. Explanation: ``` N First input as a number E Map over implcit range η Second input I Cast to number [] Literal string × Repeat Implicitly print on separate lines ``` [Answer] # [R](https://www.r-project.org/), 70 bytes ``` p=paste function(w,h)p(rep(p(rep('[]',w),collapse=''),h),collapse=' ') ``` [Try it online!](https://tio.run/##K/r/v8C2ILG4JJUrzTatNC@5JDM/T6NcJ0OzQKMotUADQqpHx6rrlGvqJOfn5CQWFKfaqqtrApUg8WPy1DX/p2kY65hocqVpGOkYaf4HAA "R – Try It Online") Returns an anonymous function that constructs and returns the string. ## 45 bytes, non-conforming ``` function(w,h)write(matrix('[]',w,h),'',w,,'') ``` An anonymous function that prints out the string in the desired format. [Try this online](https://tio.run/##K/qfZvs/rTQvuSQzP0@jXCdDs7wosyRVIzexpCizQkM9OlZdBySqow6igaTm/zQNYx0TTa40DSMdI83/AA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes 6 bytes of code, +1 for the `-R` flag. ``` VÆç"[] ``` Doesn't work in the latest version due to a bug with `ç`, but it does work in [commit `f619c52`](https://github.com/ETHproductions/japt/tree/f619c52d28277eaf279903146e832360384acb02). [Test it online!](http://ethproductions.github.io/japt/?v=f619c52d28277eaf279903146e832360384acb02&code=VsbnIltd&input=MiAzIC1S) ### Explanation ``` VÆ ç"[] VoX{Uç"[]"} // Ungolfed // Implicit: U, V = input integers VoX{ } // Create the range [0...V) and replace each item X with Uç"[]" // U copies of the string "[]". -R // Join the result with newlines. // Implicit: output result of last expression ``` [Answer] # [Go](https://golang.org/), 74 bytes ``` import."strings" func(x,y int)string{return Repeat(Repeat("[]",x)+"\n",y)} ``` [Try it online!](https://tio.run/##nZDBasQwDETv/orBp3gbNrC9FfoPpde2B69jB9NYDrYMG5b99qyTlFJoTxUCwQyMnjTEZdLmUw8WQXsSojvAxN7C5zpDsMS2x9kaXXIVedU11Y40h1gyXCHDPtLiwxQTH2Xm5GnIUqxOc2lneGK1q9dkuSTCq52s5uZryLcP2V7Ug3wn2c7qthw6IfY4SBdYoutAkVER@poGbbjoceNsEWmc4WIC28x1h/gFspFs5zUKV4FaDk/P@DfgypN1sN/Hg2P90c73E2XfFfj4UsN5pMY1pxYnpf42HqtxW@4 "Go – Try It Online") [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 14 bytes ``` [:|?[:|?@[]`'; ``` Explanation: ``` [:| FOR a = 1 to (read input from cmd line) ? PRINT a newlne [:| FOR c = 1 to (read input from cmd line) ?@[]` PRINT A$ (containing the box) '; and inject a semicolon in the compiled QBasic code to suppress newlines ``` This takes its arguments in the order of #rows, #cols. Output starts with a newline. [Answer] ## Pyke, 8 bytes ``` }A;**"[] ``` [Try it here!](http://pyke.catbus.co.uk/?code=%7DA%3B%2a%2a%22%5B%5D&input=5%0A3) Also 8 bytes: ``` F2K*"[] ``` [Try it here!](http://pyke.catbus.co.uk/?code=+F2K%2a%22%5B%5D&input=5%0A3) [Answer] # [Bash](https://www.gnu.org/software/bash/), 55 bytes ``` seq $(($1*$2))|sed s/.*/[]/|tr -d " "|fold -w $(($1*2)) ``` [Try it online!](https://tio.run/##S0oszvj/vzi1UEFFQ0PFUEvFSFOzpjg1RaFYX09LPzpWv6akSEE3RUGJS6kmLT8nRUG3HKoSqPD////G/00A "Bash – Try It Online") Uses the TIO flavor of bash, since I run windows. [Answer] ## C#, 78 bytes ``` (w,h)=>"".PadLeft(h).Replace(" ","".PadLeft(w).Replace(" ","[]")+'\n').Trim(); ``` [Run in C# Pad](http://csharppad.com/gist/333b511ae47260be12c20bea40d4981c) This is shorter than with for-loops and I'm not aware of any function in C# which can repeat with less code. [Answer] ## CJam, 10 bytes ``` l~"[]"*N+* ```   [Answer] # JavaScript (ES6), ~~43~~ 36 bytes From the comments, a trailing newline is now permitted. ``` w=>h=>("[]".repeat(w)+` `).repeat(h) ``` --- ## Try it ``` f= w=>h=>("[]".repeat(w)+` `).repeat(h) oninput=_=>o.innerText=f(+i.value)(+j.value);o.innerText=f(i.value=2)(j.value=2) ``` ``` *{font-family:sans-serif;} input{margin:0 5px 0 0;width:50px;} ``` ``` <label for=i>w: </label><input id=i type=number><label for=j>h: </label><input id=j type=number><pre id=o> ``` [Answer] # [J](http://jsoftware.com/), 11 bytes ``` ,./@$'[]'"0 ``` [Try it online!](https://tio.run/##y/r/P81WT0FHT99BRT06Vl3J4H9qcka@QpqCqYIhF5RppGAMYxoqmPwHAA) [Answer] # [Canvas](https://github.com/dzaima/Canvas), 4 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` []×* ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JTVCJTVEJUQ3JXVGRjBB,i=MiUwQTM_,v=7) ]
[Question] [ ## Challenge: Create a function or program that will take an input N (a number from 0 - 24) which represents the HOUR. Output should draw an analog clock out of asterisks showing the hour N. # 🕛🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛 --- ## Notes: •The minute hand must be longer than the hour hand (in terms of number of asterisks used) •The minute hand must be at least 2 asterisks. •Noon, 3pm, 6pm, and 9pm will always be orthogonal. Your output for intermediary hours, when arranged by degrees, should be in the same order as the hours of the day. What I mean is at noon the hour hand is 0º and at 3pm the hour hand is 90º so for your output cases of 1pm and 2pm the following must be true: `0pm_deg < 1pm_deg < 2pm_deg < 3pm_deg`. Apart from this rule the actual degree amount can be whatever you decide, obviously it will change depending on font and other native factors. •The connecting joint between the hour hand and minute hand is a circular/oval unicode character of any kind. `o, O, •, 0, etc.` --- ## Example Input / Output (May vary depending on drawing styles) ``` N = 3; * * * O  *  * ``` --- ``` N = 4; * * * O     *        * ``` --- ``` N = 5; * * * 0   *    * ``` --- ``` N = 6; * * o * ``` --- ``` N = 7; * * * • * * ``` --- ``` N = 0,12,24; * * * o ``` --- Example of Differentiating Outputs: ``` N = 4 VS   N = 5 VS   N = 6 *             *             * *             *             * O             O             O *        *           * ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the shortest bytecount wins! [Answer] # Javascript (ES6), 105 76 65 bytes ``` F=N=>` * ab*12 9@3 87654`.replace(/\w/g,y=>'0x'+y^N%12?' ':'*') ``` ``` <!-- Snippet Demo: --> N = <input type="number" min="0" max="24" value="2" id="I" /> <button onclick="console.log(F(I.value))">Run</button> ``` * **-29 bytes:** + Reduced size of minute and hour hand to 2 and 1 asterisks respectively. Smaller clock = less bytes :-P * **-11 bytes:** + Changed string comparison to numeric comparison. + `y==(N%12).toString(16)?'*':' '` -> `'0x'+y^N%12?' ':'*'` ## Original with longer hands: (105 94 bytes) ``` F=N=>` * a b * 1 2 ab*12 99@33 87654 8 7 6 5 4`.replace(/\w/g,y=>'0x'+y^N%12?' ':'*') ``` ``` <!-- Snippet Demo: --> N = <input type="number" min="0" max="24" value="2" id="I" /> <button onclick="console.log(F(I.value))">Run</button> ``` [Answer] ## CSS/HTML(JavaScript), 62 + 106 = ~~180~~ 168 bytes ``` pre{position:absolute;left:99px;bottom:99px;transform-origin:50% 80%} ``` ``` <input oninput=h.style.transform=`rotate(${this.value*30}deg)`><pre>* * o</pre><pre id=h>* </pre> ``` Edit: Saved 9 bytes thanks to @nderscore. [Answer] # [Python 2](https://docs.python.org/2/), ~~148~~ ~~140~~ 135 bytes -8 by deleting some leftover spaces and an unneeded newline. -5 by changing `(' ','*')` to `' *'` ``` a=input() b=''' * a b * 1 2 ab*12 9 9 o 3 3 87654 8 7 6 5 4''' for x in range(1,12):b=b.replace(hex(x)[2],' *'[x==a%12]) print b ``` [Try it online!](https://tio.run/nexus/python2#DctLCsMgFEbh@V3FPyk@CIVr3gVXEjLQYttAMSIpuHvrGX5wqrNHTL9LKvJWCIGWJgcPDYYhwHnNhlasONGjb7LM0zjQghkTRgztoteZUXBEZBffQXLHRj289fcc0tc9g/yEIovazN4JaLEVa92Nza4o5SNe8LUy/wE "Python 2 – TIO Nexus") [Answer] # [C (gcc)](https://gcc.gnu.org/), 144 bytes ``` #define v ,t h;t(i){putchar(i>12?i-9:h^i?32:42);}n(i){h=i%12;puts(" *")v(10)v(11)v(h)v(1)v(2)v(19)v(12)v(9)v(57)v(3)v(19)v(8)v(7)v(6)v(5)v(4);} ``` [Try it online!](https://tio.run/nexus/c-gcc#NU7LDoIwELzzFRsMoUVMoOCLqvwIMUGBtAcrqasX4rfjrgmHmZ3s7GPmVdcP1vXwgRQDo1FYOY1vvJvWC3vJVW03x8pcbV2oqlRSfx1PmLONcqVp8CVCgCSUH5FnTDmRYUFQXI9MrFhs90TF0j4QuLFjh1DS@dk6hEdr6Q2JNgVOAkkCNwlTAADD0/8tPGcaT6rUS9q4cbGUoydzEGHUVY0LU5SpE7heS827vse3d5Dp4Dv/AA "C (gcc) – TIO Nexus") [Answer] # SmileBASIC, ~~90~~ ~~88~~ 74 bytes ``` INPUT H?(" *"+" "*47)*2;" o R=H/1.9LOCATE 2.5+SIN(R)*2,3.5-COS(R)*2?"* ``` Example output: ``` ? 5 * * o * ? 3 * * o * ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~86~~ 85 bytes -1 byte, better clockface (credit DuctrTape, as used in my Jelly answer) ``` def f(h):print(*([c,' *'[h%12+64==ord(c)]][c>'@']for c in''' K*A J*B I0C HFD G E''')) ``` **[Try it online!](https://tio.run/nexus/python3#@5@SmqaQppGhaVVQlJlXoqGlEZ2so66gpR6doWpopG1mYmubX5SikawZGxudbKfuoB6bll@kkKyQmaeurs7lreXI5aXlxOVp4Mzl4ebC5a7gChTW1PwPUpQBVKRQlJiXnqphZKppxcUJsSFDk4szDUxC@Jr/AQ)** [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35 34~~ 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ị“ tI©’Œ?Ḋ¤µ⁶ẋ13”*⁸¦Ṗ;“**o”ṙ7s5ZY ``` **[Try it online!](https://tio.run/nexus/jelly#AUQAu///4buL4oCcIHRJwqnigJnFkj/huIrCpMK14oG24bqLMTPigJ0q4oG4wqbhuZY74oCcKipv4oCd4bmZN3M1Wln///8yMQ)** (`tI©`!) or see all **[(0 - 24)](https://tio.run/nexus/jelly#@/9wd/ejhjkKJZ6HVj5qmHl0kv3DHV2Hlhza@qhx28Nd3YbGjxrmaj1q3HFo2cOd06yBKrW08oFCD3fONC82jYr8b2T6cMe2Q1uP7jnc/qhpTSQI/wcA)**. ### How? ``` ị“ tI©’Œ?Ḋ¤µ⁶ẋ13”*⁸¦Ṗ;“**o”ṙ7s5ZY - Main link: h ¤ - nilad followed by link(s) as a nilad: “ tI©’ - base 250 number: 522956007 Œ? - shortest permutation of [1,N] that would be at that index in a lexicographically sorted list: [2,3,4,5,6,7,1,12,11,10,9,8,13] Ḋ - dequeue: [3,4,5,6,7,1,12,11,10,9,8,13] ị - index into (1-based and modular, so h=2 picks 4, as does h=14 [as do h=26, h=-10, etc.]) µ - monadic chain separation (call the result j) ⁶ - space character ẋ13 - repeat 13 times ¦ - apply to index... ⁸ - ...left argument (j) ”* - an asterisk character (replacemes the space at index j with an asterisk) Ṗ - pop the last character off the list † ;“**o” - concatenate "**o" ṙ7 - rotate left by 7 ‡ s5 - split into chunks of length 5 (columns) Z - transpose (get the rows of the clock) Y - join with line feeds - implicit print ``` Note that `“ tI©’Œ?Ḋ` (permutation at index, dequeued) is a byte save over `“9ȧỤ_ÑḶ’b⁴` (base 16 of), which is a byte save over `“¦þxṙ<ȥ’ḃ13` (bijective base 13 of). `†` Regarding the pop - we have an extra space in the string, which is where the asterisk for 0, 12, 24 will go to to allow mod-12 indexing of the list of indexes, popping the last character off there is byte-cheaper than doing the concatenation of `“**o”` beforehand and overwriting one of those asterisks. `‡` Regarding the rotation - this is a byte save over constructing a string with the `“\*\*o” in the middle (either with it before or after the asterisk placement). [Answer] ## Haskell, 148 bytes ``` c n=mapM_ putStrLn$(t(n-3)!(t n!(\_->'*')))(map(\x->(2!(\_->x))" ")"**O ") n!f=(\(x,a:y)->x++f a:y).splitAt n t n=2+truncate(2.5*sin(n*pi/6)) ``` Function c is the one that solves the given task [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 57 bytes ``` tr `dc -e12o$1O%p` \*<<<'B*1 A*2 9O3 864 7 5'|tr 1-9AB \ ``` (There's a space after the final backslash.) [Try it online!](https://tio.run/nexus/bash#@19SpJCQkqygm2polK9i6K9akKAQo2VjY6PupGXI5ahlxGXpb8xlYWbCZa5gql4DVG2oa@nopBCj8P//f2MA "Bash – TIO Nexus") Not a very pretty clock, but it meets all the requirements. [Answer] # PHP, 71 bytes 1 asterisk hours hand, 2 asterisk minutes hand. ``` $s=" * * O ";$s[ord(BGHNTSRQPJDE[$argv[1]%12])&31]="*";echo$s; ``` takes input from command line argument; run with `-nr`. 1. define template 2. map hour to position (decode from letter) and set character at position to asterisk 3. print [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 41 bytes This is too slow for TIO. ``` 14Ýœ•2!&ô÷‰•èv… *@y_2L11+¹12%0‚ìyå+èJ}3ô» ``` For similar code working on TIO try [this](https://tio.run/nexus/05ab1e#AUgAt///4oCiR8OOw6bCruKAmsW@asKx4oCiMTVCUzE1w7Z24oCmICpAeV8yTDExK8K5MTIlMOKAmsOsecOlK8OoSn0zw7TCu///MTk) Pretty sure this can still be both golfed and sped up. Explanation coming later. [Answer] ## [Logicode](http://esolangs.org/wiki/Logicode) 634 bytes Couldn't figure out how to input so there is a var a=... for the input at the top of tio link ``` circ v(a)->cond((a&1000)+0)&a->0/a circ n(a)->cond a&10000->((a&100)+0)|!(a&100)&((a&011)|100)/a circ y(a)->cond((a&100)+0)&a->a&10011/a var s=@100000 var m=@101010 var x=y(n(v(a))) var e=x&1000 var f=(x&100)+0 var t=(x&10)+00 var o=(x&1)+000 circ r(a,b)->cond(a)->b/@a out s+s+s+s+m out r(e&t&!o,m)+s+r(o&e&t,m)+s+m+s+r(o&!e&!f&!t,m)+s+r(t&!o&!f&!e,m) out s+s+r(e&t&!o,m)+r(e&t&o,m)+m+r(o&!t&!f&!e,m)+r(t&!o&!f&!e,m) out r(e&o&!t,m)+s+r(e&o&!t,m)+s+@110000+s+r(t&o&!f&!e,m)+s+r(t&o&!f&!e,m) out s+s+r(e&!t&!o,m)+r((f&t&o),m)+r(f&t&!o,m)+r(f&!t&o,m)+r(f&!t&!o,m) out r(e&!t&!o,m)+s+r(f&t&o,m)+s+r(f&t&!o,m)+s+r(f&o&!t,m)+s+r(f&!t&!o,m) ``` Have given up on golfing this. Could make it shorter at the cost of making the clock look horrible though. [Try it Online](https://tio.run/nexus/logicode#bZFNboMwEIX3OYWtStZYSRtTZUvFDXoGQ0FCLXZkHApS7k49Y34cpfJmvsebmWczaMd0nmVKKXZ4ac315llrWNka7aY39ml@JvZr3XfPblfmLXu/zFXrKjaAlq8flTVfAKAF9sujkgJVddYHMpndFC0q4GJH950vtSAxk3eEtXt6WrFtIMqy4BxC/j4vaLgi6pDwEI35BAYwrZQk1PlIUQiaHMZlMLGPHDCyJUZUMZMDfSq3O4WiPBf6YMOj9cd4OiIHtfCC21Mng@bAisARukXgteCN4H61oJ2UOijbyHRQrKns4gi/Nfw7ABtssiKlgv65WlbvjU/CQxS@Z4EGw8gITRISLyXSmj5sgXj6Ls16of5hSKQ0@j5onv8A) ]
[Question] [ ## Background As far as we can tell from trying everything (besides cheating with ZWSPs), you can't type ``\` in [Stack Exchange chat](https://chat.stackexchange.com/). However, you can type `\`` by doing ``\\```. So, if you want to tell someone in chat how to type backslash-backtick, you'd need to type out ``\`\\`\``` to format ``\\``` into a codeblock. ## Challenge Your challenge will be to take a string of backticks and backslashes and output a string of backticks and backslashes that will format into that (as a code block) when you type it into SE chat. You can test this in [the chat sandbox](https://chat.stackexchange.com/transcript/1). One important thing to note is that a backslash prevents the next backtick from starting or ending a code block, but a backslash will not actually make the next backslash *not* escape - basically, three backslashes and a backtick will become two literal backslashes and a literal backtick, the latter of which will not function as a code block delimiter anymore. Thus, one way to solve this challenge is to take each block of backslashes (including the zero-length ones between consecutive backticks) and add a backslash to each, then surround the string in backticks. You may assume it is possible; that is, the input will not end with a backslash. You also do not need to handle empty input. ## Input / Output Input and output will be taken and provided as a string of backticks and backslashes. For this challenge, you must use these characters specifically. You can input or output as a flat list of characters instead, and input and output do not have to use the same format. ## Test Cases These test cases follow my example solution. I don't actually know if another solution exists, but if you can find an alternative that works in SE chat and isn't just the aforementioned approach, I may offer a bounty. ``` \` => `\\`` `\\`\`\\`` => `\`\\\`\\`\\\`\`` `\`\\\`\\`\\\`\`` => `\`\\`\\\\`\\\`\\\\`\\`\`` `````` => `\`\`\`\`\`\`` \\\\\\\\\` => `\\\\\\\\\\`` ` => `\`` `\`\`\`\`\`\`\` => `\`\\`\\`\\`\\`\\`\\`\\`` ``` [Reference Implementation](https://tio.run/##ZY0xDsMgDEVn@xSIKWmWVt0q9RYdGSARESiIIELU5vTUbhSpVQdj8/3/c9qKm@O11qfzwYpHXu0NoeSNXgg@WnEXPqa1NC2CfQ02Fd702ZoJoTfDtASzOLuQ74wwr4W8NEuJMM5ZDM5kAghGcdCPu3Qni5asHJmOFKWkOIlvareLHbvZ/HcRbFg@5J8VwS4IKftYGkpS/rjCoLZWrbRSXHvTGpVGzSp/3g) in Python; you can input as many lines as you want and it will print a valid answer to each using my approach. [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed as usual. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in bytes per language wins in its language category. Happy golfing! [Answer] # [Pip](https://github.com/dloscutoff/pip), 6 bytes ``` RP``.q ``` [Try it online!](https://tio.run/##K8gs@P8/KCAhQa/w//@YBAA "Pip – Try It Online") ### Explanation Um... well, this is interesting. It just so happens that Pip's Pattern type (used for regex) is delimited with backticks. And that backticks can be escaped within a Pattern using backslashes. ... And furthermore, that the code for generating the Pip [repr](https://docs.python.org/3/library/functions.html#repr) of a Pattern is apparently [incorrect](https://tio.run/##K8gs@P8/ISYmIeH/fwA), because it should escape the backslashes too, but in fact it only escapes the backticks. Which is exactly the behavior this question asks for. "It's not a bug, it's a feature"? ¯\\_(ツ)\_/¯ ``` q Read a line of stdin ``. Cast it to a Pattern by concatenating an empty Pattern to it RP Get the repr ``` --- Okay, I've looked at this again and I think it's **not actually a bug**. The reason why I thought it was a bug was because some of the inputs are not possible to enter as Pattern literals. Since they are "impossible" Patterns, it makes sense that their reprs are not correctly formed representations of Pattern literals. ``` Input Repr Comment ` `\`` Properly formed: backtick is escaped with a backslash \\` `\\\`` Properly formed: backslash is also escaped with a backslash \` `\\`` Improperly formed: first backtick is not escaped ``` You can't enter a regex for `\`` in Pip because `\`` is not a properly formed regex. (If you want a regex that matches the string `\``, you should use `\\``, which is entered as ``\\\```. Clear as mud? Great.) In summary, inputs with only even-length runs of backslashes output well-formed reprs, but if there is an odd run of backslashes, all bets are off. [Answer] # [Python 3](https://docs.python.org/3/), 35 bytes ``` lambda s:'`%s`'%s.replace('`','\`') ``` [Try it online!](https://tio.run/##bU7RCoMwDHz3K/IibUGEsTeh@5LA4raKha4Wq4x9fVeLbuq8hCbcHc2599B29hwaicHUz9ujBl8xyj2x3Je9cqa@K86IFQyJifBqtVFwqjIAXcC1gA4kaOvGgYvSO6PjjJrrtR14w7UAKaETAQl2kBcgRKJsejGtGykyiU0j2XbM1zYRizg7Jn/C38VVUYYLtqd/dPwGDoPPgVa1yn3Q9AE "Python 3 – Try It Online") -1 thanks to dingledooper. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ṣ”`j⁾\`⁾``j ``` [Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYmZD1q3BeTACQSErL@P9yx6eGORYfbuR7u3nK4/VHTmsj//2MSFNCArZ1CQkxMQgIXiIwBM1GkgCJgUTAFVoYmAlcGEoBJQlWA1IMBho1IMIErBgZQrUYIA41RwOpwqIOQIJK7saAEAA "Jelly – Try It Online") Jelly version of [Lynn's approach](https://codegolf.stackexchange.com/a/230316/66833), found independently ## How it works ``` ṣ”`j⁾\`⁾``j - Main link. Takes a string S on the left ṣ”` - Split S on backtick j⁾\` - Join with "\`", essentially replacing backticks with "\`" ⁾``j - Surround with backticks ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 32 bytes ``` n=>'`'+n.replace(/`/g,'\\`')+'`' ``` [Try it online!](https://tio.run/##PYtBDoAgDASfUwgKL8CXcChBIBrSEjB@HwkH9zBzmOztX99Du@qzE59xJDvIHoCgSLdYiw9RGDR5A@cQpJplBKbOJerCWSQBOItbwx9LOA9yfA "JavaScript (Node.js) – Try It Online") Self-explanatory trivial solution. [Answer] # [Trilangle](https://github.com/bbrk24/Trilangle), 52 bytes ``` "`oo,.<|...,>~i\"<..._".#.,oo`"<>..+...._#..,@.....^ ``` Try it on [the online interpreter](https://bbrk24.github.io/Trilangle/#%22%60oo%2C.%3C%7C...%2C%3E%7Ei%5C%22%3C..._%22.%23.%2Coo%60%22%3C%3E..%2B...._%23..%2C%40.....%5E)! I'm not a huge fan of how un-dense this is (`.` is NOP) but I couldn't make it any smaller. Unfolds to this: ``` " ` o o , . < | . . . , > ~ i \ " < . . . _ " . # . , o o ` " < > . . + . . . . _ # . . , @ . . . . . ^ . . . ``` [![](https://i.stack.imgur.com/5CVhI.png)](https://i.stack.imgur.com/5CVhI.png) On the red path, it prints the opening ```, and gets input. If there's no input left, it follows the green path, which prints the closing ``` and exits. Otherwise, it follows the blue path, which prints `\` and then compares the inputted character against `_` (0x5f). If it's less, it takes the yellow path to close the loop. Otherwise, it takes the magenta path to print ```, waste a lot of time/space, and *then* close the loop. As I said above, there's so many NOPs I can't help but think I can contract this, but I have yet to find a smaller way to do this. [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Look, Ma, no escape characters! ``` "`{r'`_i'\}` ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ImB7cidgX2knXH1g&input=ImBcYFxgXGBcYFxgXGBcYCI) [Answer] # [Vyxal 2.3](https://github.com/Lyxal/Vyxal/releases/tag/v2.3.0), 7 bytes ``` \`‛\`Vq ``` Up until recently, q (uneval) simply surrounded the string in backticks. Now it escapes backslashes and backticks, which we don't want. Also up until recently, strings in the input couldn't be delimited by backticks, but now they can so input is misparsed. The rest is just replacing backticks with a backtick and a backslash. So no TIO, but feel free to download the interpreter from the above link and try it out. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 11 bytes ``` ^|$ ` ` \\` ``` [Try it online!](https://tio.run/##KyxNTCn6/z@uRoUrAQhjYhL@/48BsoCMGBABYgJpMBtMgUTAAKgWCkAaE2JQIAA "QuadR – Try It Online") Simply replaces (i.e. inserts at) the beginning/end with a backtick, and any backtick with a backslash and a backtick. Equivalent to the Dyalog APL function `'^|$' '`'⎕R'`' '\`'` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Z„\`.:Z.ø ``` Assumes the input will always contain a backtick. [Try it online](https://tio.run/##MzBNTDJM/f8/6lHDvJgEPasovcM7/v@PSQAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3l/6hHDfNiEvSsovQO7/iv8z8mgSshJiYhBkSAmEAazAZTIBEw4IqBAaAIWBUSBAA). **Explanation:** ``` Z # Get the maximum character of the (implicit) input-string (the backtick `) .: # Replace all backticks in the input „\` # with "\`" Z # Then get the backtick again with the maximum (without popping the string) .ø # Surround the string with this backtick as leading/trailing character # (after which the result is output implicitly) ``` Uses the legacy version of 05AB1E, because the newer 05AB1E version's min/max won't work on characters (it will return the first character, instead of the lowest/highest unicode character). [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 9 bytes ``` ;"`":<<*$.`%_$:"\\" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWm62VEpSsbGy0VPQSVONVrJRiYpQgMlAFC246xyRwJcTEJMSACBATSIPZYAokAgZcMTAAFAGrQoIQswA) ``` ;"`":<<*$.`%_$:"\\" ; Output b := "`" backtick : Join << remove last character from * join by $ b . for each s in `% split _ input $ by b : join "\\" backslash s b ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 31 bytes ``` '`'+$args.replace('`','\`')+'`' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Xz1BXVslsSi9WK8otSAnMTlVAyiiox6ToK6pDWT9B6mIiUmIAREJ6gA "PowerShell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-pl140`, 16 bytes ``` $_=$\.s/`/\\`/gr ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYlRq9YP0E/JiZBP73o//@EmISYGBCGUAkJ//ILSjLz84r/6xbkGJoYAAA "Perl 5 – Try It Online") ## Explanation A relatively standard solution, this uses the `-l140` flag to set `$\` to ``` which is automatically output after every call to `print`. Since we're also using the `-p` flag, `$_` will be automatically `print`ed so we set it to `$\` concatenated with the `/r`esult of `s/`ubsitituing ``` with `\`` in the (implicit) input stored in `$_`. --- # [Perl 5](https://www.perl.org/) + `-p0140l`, 19 bytes ``` $\.="$_\\`"}{$\.=$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRs9WSSU@JiZBqbYaxFHR//8/ISYhJgaEIVRCwr/8gpLM/Lzi/7oFBoYmBjkA "Perl 5 – Try It Online") ## Explanation Slightly more interesting but longer, this answer uses the `-0140` flag to split input on ``` instead of newlines which means the first part of the code (before the `}{`) will be called for each part of the string (up to, but excluding ```), appending the string itself concatenated with `\\`` to `$\` which is pre-initialised to `$/` (```) via `-l`. Once all the input has been parsed (`}{`), `$/` is appended to `$\` which is implicitly output due to `-p`. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 15 \log\_{256}(96) \approx \$ 12.35 bytes ``` '`"\`"Ar'`+'`s+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbr1ROUYhKUHIvUE7TVE4q1IaJQyQXrE2JQIEQYAA) Port of Lynn's Python answer #### Explanation ``` '`"\`"Ar'`+'`s+ # Implicit input '` # Push ` "\`" # Push \` Ar # Replace ` with \` '`+ # Append a backtick '`s+ # Prepend a backtick # Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ 7 bytes ``` q\\d\\V ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwicVxcXFxkXFxcXFYiLCIiLCJcXGBcbmBcXFxcYFxcYFxcXFxgYFxuYFxcYFxcXFxcXGBcXFxcYFxcXFxcXGBcXGBgXG5gYGBgYGBcblxcXFxcXFxcXFxcXFxcXFxcXGBcbmBcbmBcXGBcXGBcXGBcXGBcXGBcXGBcXGAiXQ==) *-5 thanks to @lyxal* #### Explanation ``` q\\d\\V # Implicit input q # Repr (Vyxal strings are # delimited by backticks) \\d # Double a backslash to get \\ \\V # Replace with one backslash # Implicit output ``` Old: ``` \`\\\`+V\`ø. # Implicit input \` # Push the character ` \\ # Push the character \ \`+ # Add it to ` to get \` # This is one byte shorter than # using a string literal, `\\\``, # since strings in Vyxal are # delimited by backticks V # Replace ` with \` \`ø. # Surround with backticks # Implicit output ``` [Answer] # [Red](http://www.red-lang.org), 42 bytes ``` func[s][rejoin[t:"`"replace/all s t"\`"t]] ``` [Try it online!](https://tio.run/##ZVBbDsIgEPznFBsu4H@NHsJfIKFpl1hDaAN4foQt2IqzJEtmZh/gcU4PnIViZkjm7SYRlPD4Whcn4sA197jZccLLaC0EiFxqHpVKZvU4Tk@IGCIIVugrdLjdQUupNeMlSbofLlIzRzyl3dlRuaA5C9Xk6qESwu/4WvKNbJMN/Q6HUJr9P6M2q8udgqyn5fqjmWJi84uLYOijVPoA "Red – Try It Online") ]
[Question] [ # Introduction * Note that I learned it from a [Numberphile Video](https://www.youtube.com/watch?v=KNjPPFyEeLo), where [Neil Sloane](https://www.youtube.com/playlist?list=PLt5AfwLFPxWJXQqPe_llzWmTHMPb9QvV2) explains it better. I recommend you to watch his Video. But for a quick Introduction: The [Levine Sequence](https://oeis.org/A011784) is made from the Levine's Triangle, which is made as follows: First you have \$0\$ ones, and \$1\$ twos. Then you read the list backwards (right to left) and you have the same number of ones, as the \$0\$\$th\$ element of the list. Then you have the same number of twos, as the \$1\$\$th\$ element of the list. That goes on and on, till the list ends. These are the first few rows: ``` ln[0]: 2 ln[1]: 11 ln[2]: 12 ln[3]: 112 ln[4]: 1123 ln[5]: 1112234 ln[6]: 11112223344567 ``` Really, I don't think I've explained it good, so check out [Neil's Video](https://www.youtube.com/watch?v=KNjPPFyEeLo) to learn more about it. So, now, the Levine's Sequence. The \$n\$\$th\$ Term of the sequence (starting at \$0\$), is just the sum of the \$n\$\$th\$ row of the Levine's Triangle. These are the first few terms: 2, 2, 3, 4, 7, 14. Then it just blows up. Disclaimer: In the Numberphile video, also when you follow the steps I told, the \$0\$\$th\$ term is \$2\$. But in [OEIS](https://oeis.org/A011784) the first term is \$1\$. So I will accept both sequences. # Rules * The output must be printed to the program's output. * The output must be in base 10 (outputting them in any other base is not allowed). * Your program must *can* take input, the nth term. * Outputting the integers with trailing / leading spaces is allowed. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest (original) code in each language wins! I'm a bit free about this, so you can output just the \$n\$\$th\$ term, up to the \$n\$\$th\$ term, or even the whole sequence! # Leaderboard I liked the leaderboard thingy, so here it is again: This uses uses [@manatwork's layout](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet/7742#7742). ``` /* Configuration */ var QUESTION_ID = 222856; // 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 = 96037; // 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 = '<i>' + lang + '</i>'; lang = jQuery(lang).text().toLowerCase(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.uniq > b.uniq) return 1; if (a.uniq < b.uniq) 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/Sites/codegolf/all.css?v=617d0685f6f3"> <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><a href="{{LINK}}">{{SIZE}}</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr> </tbody> </table> ``` [Answer] # [J](http://jsoftware.com/), 17 15 bytes ``` 1#.0&(]|.##\)&2 ``` [Try it online!](https://tio.run/##DcPNCkBAFIDRvaf4milMmOb6p6yUlZU1K5FsvIB3H06d2ysbnQw9ESmO/p9ZxmWevGjrwnh7rdarCXNvgmO/Hk6VIOQUlFTUNLR0iEPEfw "J – Try It Online") -2 thanks to FrownyFrog! On TIO, handles up to the 11th term `6837625106787` (where term 1 is `2`). ## how J's ["Copy" verb `#`](https://code.jsoftware.com/wiki/Vocabulary/number#dyadic) is tailor made for this challenge: ``` 1 2 3 # 'abc' abbccc ``` The rest is just mechanics needed to reverse and iterate: * `0&(...)&2` Iterate `...` as many times as the input. This occurs as a result of a special rule J has for the bond `&` conjunction. The `&2` on the right hand side also sets the starting value of the iteration. * `]...` Ignores the left argument of `0` (resulting from `0&`), and returns the result of `...`, which is processed as a single argument verb, because this entire phrase is a dyadic hook. + `|.##\` Reverse current list `|.`, and use it as a mask to duplicate `#` the numbers `1...<length of current list>`. * `1#.` Sum the result of that iteration. [Answer] # [Python 3](https://docs.python.org/3/), ~~91~~ ~~87~~ 85 bytes ``` f=lambda n,l=[2]:n and f(n-1,[n+1for n,e in enumerate(l[::-1])for _ in[0]*e])or l[-1] ``` [Try it online!](https://tio.run/##NU/baoRADH33KwJ90GlHcLzuCvZHplKmbtRldRTNQov47TYjbQjkXAjJmX@on2xyHG01mPHrZsDKodJxXVow9gZtYEMltX1T7bSwh3C3gPY54mIIg0GXZahq4cxPtnRUv2ItmA2a9QO/Z2wIb1BBoCTEZycSUgmFBMUjdZpiKb4kTiqyNIt4Jtciu@YRw5yNPM5UlBeXQgC8AJkHrkDTBMNkOwbQTTCblUBF1AMOOKIlr@mxeeDibvsfz7hIG1/CiVTiC8/9TC7OYmyH7j2lROkB18o7bUDiJMjkP4cmTnWq83K3FLT@RjuE77CtO2x/BzVW1Vrvvjh@AQ "Python 3 – Try It Online") Inputs \$1\$-based index \$n\$ and returns the \$n^{\text{th}}\$ element of the Levine Sequence starting at \$1\$. ### Explanation Starts at `[2]` and successively computes the next row in Levine's Triangle. The last element in the \$(n+2)^{\text{th}}\$ row is equal to the sum of the \$n^{\text{th}}\$ row or the \$n^{\text{th}}\$ term of the Levine Sequence starting at \$2\$. By using a \$1\$-based index and starting the sequence at \$1\$ we simply return the last element in the \$(n+1)^{\text{th}}\$ row. [Answer] # [R](https://www.r-project.org/), ~~49~~ 48 bytes *Edit: -1 byte thanks to Giuseppe* ``` i=1:0;repeat{i=rep(seq(!i),rev(i));show(sum(i))} ``` [Try it online!](https://tio.run/##K/r/P9PW0MrAuii1IDWxpDrTFsjQKE4t1FDM1NQpSi3TyNTUtC7OyC/XKC7NBXFq//8HAA "R – Try It Online") Prints the infinite sequence (well, until it fails to allocate vector of size 25472.1 Gb at the 12th iteration...) [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes *-3 bytes thanks to @xnor* Outputs the Levine sequence indefinitely, starting at `1`. ``` a=[2] while 1:i=len(a);print i;exec'a+=a.pop(i-1)*[i];i-=1;'*i ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9E22iiWqzwjMydVwdAq0zYnNU8jUdO6oCgzr0Qh0zq1IjVZPVHbNlGvIL9AI1PXUFMrOjPWOlPX1tBaXSvz/38A "Python 2 – Try It Online") [Answer] # [Scratch](https://scratch.mit.edu/), ~~734~~ 715 Bytes -19 thanks to Lyxal! [Try it online!](https://scratch.mit.edu/projects/513149982/) [Previously discussed](https://codegolf.meta.stackexchange.com/questions/673/golfing-in-scratch/), there doesn't seem to be a consensus on how to score Scratch code. I converted the code to scratchblocks4 and counted the characters: ``` when gf clicked delete all of[B v delete all of[E v delete all of[T v ask[]and wait add(2)to[E v add(1)to[T v set[D v]to(1 repeat(answer set[C v]to(0 A repeat((item(length of [T v])of[T v])-(1 A if<not<(R)=(item((length of[B v])-(1))of[B v])>>then change[C v]by(()-(length of(D change[D v]by(-1 delete(length of[B v])of[B v A end end set[D v]to(length of[B v set[S v]to( set[V v]to(1 set[t v]to(0 repeat(length of[B v repeat(item(1)of[B v set[S v]to(join(S)(V end change[V v]by(1 change[t v]by(item(1)of[B v delete(1)of[B v end add(S)to[E v add(t)to[T v define A set[R v]to( repeat(length of(D set[l v]to(item(length of[E v])of[E v set[R v]to(join(letter((length of(l))-(C))of(l))(R change[C v]by(1 end add(R)to[B v ``` Alternatively, the program is 73 blocks: [![enter image description here](https://i.stack.imgur.com/HsaGc.png)](https://i.stack.imgur.com/HsaGc.png) Obviously, Scratch isn't the first choice for any serious program, but I enjoyed making this! Lyxal substituted `(item(length of[E v])of(E v` for a variable, saving 19 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` 2JxṚƊ¡S ``` [Try it online!](https://tio.run/##y0rNyan8/9/Iq@LhzlnHug4tDP7//78pAA "Jelly – Try It Online") Outputs the \$n\$th term. ## Explanation ``` 2JxṚƊ¡S Main monadic link 2 Start with 2 ¡ Repeat n times Ɗ ( J Indices (range [1..length]) x Repeat each item a number of times given by the corresponding item in Ṛ The list reversed Ɗ ) S Sum ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes prints the `n`th 0-indexed term ``` Tr@Nest[Join@@MapThread[Table,{Range@Length[a=#],Reverse@a}]&,{1,0},#]& ``` [Try it online!](https://tio.run/##HcuxCsIwEAbgVxEKnQ7auhduFhUp2UKGU3@SgI2SHl1Kn/2Efvs3iybMovklFkdzle9Y1F@@uTDf5OdShby9k@cHtE1SIviKEjV5GZtAE1bUBSx7aGkbqN@pCa09ai566jh2fBzf03AOZn8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` mΣ¡o`ṘN↔;2 ``` [Try it online!](https://tio.run/##yygtzv7/P/fc4kML8xMe7pzh96htirXR//8A "Husk – Try It Online") Prints the infinite sequence. If you let it time out, you can see upto 11 terms. ## Explanation ``` mΣ¡o`ṘN↔;2 ;2 start with [2] ¡o create the next iteration by ↔ reversing it `Ṙ and replicating each element(flipped arg) N times each element in the natural numbers mΣ map each list to its sum ``` [Answer] # JavaScript (Node.js), 110 bytes ``` n=6;a=[2];for(;n-->0;a=a.reverse().reduce((v,e,i)=>v.concat(Array(e*1).fill(i+1)),[]));console.log(a.join("")) ``` [Try it online!](https://tio.run/##DcpBCsMgEEDRu2Q10xppuuhGDOQcIYvBTIpBnDKmQk9v3X0e/6RKJWj8XGOWnVvL/uXIr8/NHaLg8jjOjw5klStrYcBe@zcwQDVsIvq52iA50AWLKv2AbxPaI6YE8T4hmnVDdP0oktgmeQPZU2KGYUBs7Q8 "JavaScript (Node.js) – Try It Online") Set `n` at the start to change which element of the sequence is calculated. Unfortunately, this is a rather long answer, due to JavaScript's wordy array operator functions. [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` x=[2] exec'x=sum([v*[i]for i,v in enumerate(x[::-1],1)],[]);'*input() print sum(x) ``` Prints the nth, 0-indexed, term. **[Try it online!](https://tio.run/##FcsxCoAwDADA3Vd0s5U61EVQfEnIIBIxg7HUVuLrK95@8c3HJUOtusCADSltrS53OS08HTDuVzLsH8NiSMpJac1kFaapD@iDQw/o5rZjiSVb18TEks3f1dU6fg "Python 2 – Try It Online")** --- Others at 82: ``` x=[2] exec'i=1;x=x[::-1];exec"x+=x.pop(0)*[i];i+=1;"*len(x);'*input() print sum(x) ``` ``` x=[2] exec'i=1;exec"x=x.pop()*[i]+x;i+=1;"*len(x);x=x[::-1];'*input() print sum(x) ``` ``` x=2, exec'x=sum([v*(i,)for i,v in enumerate(x[::-1],1)],());'*input() print sum(x) ``` [Answer] # JavaScript (ES6), 81 bytes Returns the \$n\$-th term, 0-indexed. ``` f=(n,a=[2])=>a.map(k=>A=n?[...Array(k).fill(++i),...A]:+A+k,i=A=[])&&n?f(n-1,A):A ``` [Try it online!](https://tio.run/##FYtBCoMwEADvfUUOIlkSQ@1Ru0reIYLBmpKabiSWQhHfnuppYJh5ma9Zx@iWT0HhMaVkkZM02N16wMaot1n4jI1GajullI7R/PgMyjrvuRAO5Gn7SmgxS4caux7ynFrLqSilhkonGyInhuxaM2J3Vp4UAth2YWwMtAY/KR@efDA822iHI82244d9gPqypz8 "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input a = [2] // a[] = Levine sequence ) => // a.map(k => // for each value k in a[]: A = // compute A, which is either the updated Levine sequence // or the sum of the terms of the last sequence if this is // the last iteration: n ? // if n is not equal to 0: [ ...Array(k) // build an array consisting of k entries .fill(++i), // equal to i (which is first incremented) ...A // followed by the existing entries in A[] ] // : // else: +A + k, // coerce A to a number and add k i = A = [] // start with i = A = [] ) // end of map() && n ? // if n is not equal to 0: f(n - 1, A) // do a recursive call with n - 1 and a[] = A[] : // else: A // we're done: return A ``` [Answer] # [Haskell](https://www.haskell.org/), ~~57~~ 55 bytes * -2 bytes thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops). ``` sum<$>iterate(!1)[2] (x:y)!n=y!(n+1)++(n<$[1..x]) e!_=e ``` [Try it online!](https://tio.run/##BcFBCsMgEADAe16h4EGRBjbHEvuDviANYQmbVqKLRAvJ57ud@WDdKSVJ4SX1m0fziI0ObGQ1uGmYO3veL6c5XNqyB@e95dFM0Pfn7DrSSyDJGDlkLM9FlSNyMw13UgAqyW/dEr6r3NZS/g "Haskell – Try It Online") The whole Levine sequence. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 2̶3̶ 2̶2̶ 21 bytes -1 thanks to @Razetime -1 thanks to @User ``` +/{×⍵:/∘⍳∘⍴⍨⌽∇⍵-1⋄,2} +/ ⍝ summation ×⍵: ⍝ conditional /∘⍳∘⍴⍨ ⍝ expand range 0 to length of L(n-1) inclusive ⌽∇⍵-1 ⍝ reverse L(n-1) ⋄ ⍝ statement separator (effectively an else clause) ,2 ⍝ return value ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRt/erD0x/1brXSf9Qx41HvZjC55VHvikc9ex91tANldA0fdbfoGNUC1SsYcKUpGAKxERAbA7EJEJsCsRkQmwOxBRBbgtQYAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` 1‚¸λRεN>yи}˜}εθ ``` [Try it online!](https://tio.run/##ASIA3f9vc2FiaWX//zHigJrCuM67Us61Tj550Lh9y5x9zrXOuP// "05AB1E – Try It Online") prints the whole sequence forever ``` 1 pushes 1 to the stack ‚ because there is no input, pairs 1 with itself, pushing [1, 1] ¸ listify, pushing [[1,1]] λ recursive environment, with [1, 1] as the base case R reverse the implicit last value ε and map each element to N> index + 1 y that element и repeated, pushes index + 1 repeated the element } ˜ flatten, to a flat list } ε and for each such list θ take the last element ``` [Answer] # [Factor](https://factorcode.org/), 68 bytes ``` [ { 2 } swap [ reverse [ 1 + <array> ] map-index concat ] times Σ ] ``` [Try it online!](https://tio.run/##JY0xCsJAEEV7T/F7MaiIhYqt2NiIVUixbEZcNLPr7EQNIafxPl5pXbR7vA/vn41VL@l03B92K1xJmG6IdG@JLUU0Ri8wIqb7c9Gys74mBCHVLohjxXrUY4o5FlhiSCX6zAPi0wSUEHqQRMo0wxibX2uLKtfCxHFNL1jP1mhW6pp8@XmjSnlFkb4 "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes an integer from the data stack as input and puts an integer (the nth term of the Levine sequence) on the data stack as output. Assuming `4` is on top of the stack when this quotation is called... * `{ 2 }` Push a sequence to the stack containing one element, `2`. **Stack:** `4 { 2 }` * `swap` Swap two objects (because `times` needs access to the `4` later). **Stack:** `{ 2 } 4` * `[ reverse [ 1 + <array> ] map-index concat ]` Push a quotation for `times` to use later. This is a quotation that produces the next row of the Levine's Triangle from the previous one. **Stack:** `{ 2 } 4 [ reverse [ 1 + <array> ] map-index concat ]` * `times` Call a quotation a certain number of times. Inside the quotation now for the first iteration... **Stack:** `{ 2 }` * `reverse` Reverse a sequence. **Stack:** `{ 2 }` * `[ 1 + <array> ]` Push a quotation for `map-index` to use later. **Stack:** `{ 2 } [ 1 + <array> ]` * `map-index` Take a sequence and a quotation and apply the quotation to each element of the sequence, collecting the results into a new sequence of the same length. However, it also places the index of the element on top of the stack. Inside the quotation now for the first iteration... **Stack:** `2 0` * `1` Push `1`. **Stack:** `2 0 1` * `+` Add. **Stack:** `2 1` * `<array>` Create an array from a count and an element. **Stack:** `{ 1 1 }` * Now `map-index` has exhausted its elements. Since we are mapping numbers to arrays, the result will be an array of arrays. **Stack:** `{ { 1 1 } }` * `concat` Concatenate a sequence of sequences together into one sequence. **Stack:** `{ 1 1 }` * Now we have produced the second row of Levine's Triangle. `times` will run the quotation three more times... **Stack:** `{ 1 1 2 3 }` * `Σ` Sum a sequence. **Stack:** `7` [Answer] # [Python 3](https://docs.python.org/3/), 316 bytes ``` print(*[11,12,112,1123],sep="\n");n="11|2|3";x=2;t="";j=0 while 1: for y,z in enumerate(''.join([str(w)[::-1] for w in n.split("|")[1:][::-1]])): t+=str(y+1)*int(z) if j==0:t+="|" j+=1;k=y+2 n=t+''.join(map(lambda z:'|'+str(z),list(range(k,k+(len(n)-len(n.lstrip('1'))))))) print(n.replace("|",""));t="";j=0 ``` [Try it online!](https://tio.run/##PVDRboQgEHz3KwgvwMGZw3vD8CXWB9pyPRRXgjRW479bPNNustlkZnZ2smFJzxHu@x6ig0QvjZRCVkKefW/FZIPGb4BZDRpLuVXbHdc/uqqTxrju9K2Yn85bJFWBHmNEi1iRA2The7DRJEsJKbvRAW2mFOnMGqWusn1J50MI5RS8SxRvmDVStSffMpb9UOL62Fq4ZJcj3soy6B6o0/qmMpmXMtBxLeteL7wqEOjE/y4OJlBvhvdPg1ZFNsIPr5UJ76ZEo4EvS3vRc@otUGDX1yh9FrlAiSTsrAKdr4Ey2uDNhz2iCowZ@3/Bvv8C "Python 3 – Try It Online") In one word, horrible [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ⊞υ²FN«≔⟦⟧θFLυF§⮌υκ⊞θ⊕κ≔θυ»IΣυ ``` [Try it online!](https://tio.run/##PYw/D4IwEEdn@BQdr0lN1LUTcSIxhOhoHBBOINJD@oeYGD97PTs4/u69e@3Q2HZuphjr4AYISuylzu@zFVDSM/gqmBtakFK886xwbuwJLlclFraypB2Res@frKRd@JI6fMEJV7QOGSjxYJj6ixIltRYNkscO@K7/WWaB5yev7UgeDo3zcA7mV5Y6xt02btbpCw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed, I think? Explanation: ``` ⊞υ² ``` Start with `[2]`. ``` FN« ``` Repeat `n` times. ``` ≔⟦⟧θ ``` Start a new list. ``` FLυ ``` Iterate up to the length of the previous list. ``` F§⮌υκ ``` Repeat according to the value in the reversed list. ``` ⊞θ⊕κ ``` Push the next integer to the list. ``` ≔θυ ``` Copy the new list to the previous list. ``` »IΣυ ``` Print the final sum. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 76 bytes function that take n and output A[n] ``` f=(n,a=[2],q=a.length)=>n?f(n-1,a.flatMap(n=>Array(a[--q]).fill(++i),i=0)):q ``` [Try it online!](https://tio.run/##Dc1NCoMwEEDhvafIwsUM@UG7rI2lB@gJRHCwxlrCRKMUinj21NXbfPA@9KW1j9O8aQ6vISVngRXZ5tKqxZLxA4/bG23NdwesS0XGedqeNAPb@hEj/YAarZcWjZu8ByknVJMtEK9LciECCyuKSrC4ibI8KyWKPROiD7wGPxgfRugI8p0PPGm@nx88OqyyI/0B "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 77 bytes output all A[i] ``` for(a=[2];;a=a.flatMap(n=>Array(a[--q]).fill(i++)))i=!console.log(q=a.length) ``` [Try it online!](https://tio.run/##DctBCsMgEAXQs3Q3Q9BFt2KhB@gJQhYfq4llcIyRQE5v8/bvhxNHaLl2U/Qbx0jaCH5@Ls7BwyZB/6BS8a93a7gIszH7wjZlEcrTxMzZP4KWQyVa0ZX2u0ksa994jD8 "JavaScript (Node.js) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 bytes ``` J[2)W1K_JsK=JYFklK=+J*@Kk[hk ``` [Try it online!](https://tio.run/##K6gsyfj/3yvaSDPc0Dveq9jb1ivSLTvH21bbS8vBOzs6I/v/fwA "Pyth – Try It Online") Prints the infinite sequence. # Explanation ``` J[2) # Initialize J to [2] W1 # While 1... K_J # Initialize K to reverse of J sK # Print the sum of elements of K =JY # Y is an empty list by default. Set J to it. FklK # For loop from 0 till length of K, with iterator as k @Kk # k'th element of K [hK # A list containing only k+1 * # Repeats the sequence specified number of times. =+J # Append that to J. ``` [Answer] # Scala 3, 84 bytes ``` Seq.iterate(Seq(2),_){s=>s.reverse.zip(1 to s.sum)flatMap(Seq.fill(_)(_))}map(_.sum) ``` [Try it in Scastie!](https://scastie.scala-lang.org/r8kyBmirTRSRIpJN02aYYw) Outputs the first n items. ## Infinite list + nth element, 85 bytes ``` Stream.iterate(Seq(2)){s=>s.reverse.zip(1 to s.sum)flatMap(Seq.fill(_)(_))}map(_.sum) ``` [Try it in Scastie!](https://scastie.scala-lang.org/LL2mFC06SNi79QmItJiD2w) Here is an infinite Stream that also acts as a function giving the nth element, but it's a byte longer. ]
[Question] [ A while ago, I had a look at the prime factorization of 27000: > > 27000 = 23 × 33 × 53 > > > There are two special things about that: * **consecutive-prime**: The primes are consecutive: 2 is the 1st prime, 3 is the 2nd prime, 5 is the 3rd prime. * **constant-exponent**: The exponent is the same for every prime (always 3) Mathematically expressed: > > An integer *x* is a consecutive-prime/constant-exponent number if there exist strictly positive integers *n*, *k*, *m* such that *x* = *p**n**m* × *p**n*+1*m* × ... × *p**n*+*k**m*, where *p**j* is the *j*-th prime > > > Your task is to test if a positive integer fulfills these conditions. ## Input: A positive integer > 1, in any reasonable form. ## Output: One of two values, at least one of which has to be constant, indicating whether the input is a consecutive-prime/constant-exponent number. ## Edge cases: * primes are truthy, as the factorization for prime *p* is *p*1 * other numbers that can be written as *p**m* where *p* is a prime are also truthy. ## Rules: * Standard loopholes apply. * No worries about integer overflow, but numbers up to 255 must work. * Shortest code in bytes wins. ## Test cases: Truthy: ``` 2 3 4 5 6 7 8 9 11 13 15 27000 456533 ``` Falsy: ``` 10 12 14 72 10000000 ``` [Here](https://tio.run/##fVLBboMwDD0nX@FVqkRahoCpm4rGdcedduuqComwRoIQQdDar2cOSTO2tTtAEuf5@T3H6qyPrUzHUTSq7TR0hSzbhlLdDVzzXkMOuz2tirqfHVUnGt6bfRrCQwibEJ5CSBL88JSY/TaEFPfpdk9p1XYgQEg4IfsHD4RUgw4YyyjBMvp4RiZbN7JLwOAZ4mhDyVTpIIfmJ8TyYL1HRknH@6E2yhJKRAWWErkJP6lWcqlv5G4wl1Si668C4hBqLgNrld17IetkSkNLyliy97uJJpv@aw/dZ@C0rXJEr1ZwUUQJx4Y6jVj9FaN4GHpeHnxznaS@aFTNnZAQPDv7mRD1@HzB3JKLC1nyUzBD7uK9gfnW/2sB8hxmuXPrs7BxQiT/PFg7N7tt3sdA8GJa73JwWRl4PS9m2AzYkjmACfzt5vzF4TKzUaEUl2Vg4cw1G/wQ/76nlmO6y6aZw5lZvFnWBSV@fk2LeRlcsCwDh33Xy3IBSxCGytf55posXeXy4Ctk45jGXw "Python 2 – Try It Online") is a python script generating some test cases. ### The fact that I accepted an answer does not mean that the challenge is over; the winner can still change! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` Ó0ÛË ``` [Try it online!](https://tio.run/##DcexCYAwEAXQ/k8RrBXuX3KJNu6i4ApCwA0sLR0mxQ0Wfd0T23Ye/Tpr90f89bvXwVuY1uBtGDuhiEgwZBTMWECCETRoEREkyxb/C6hgQtEP "05AB1E – Try It Online") **Explanation** ``` Ó # get a list of prime exponents 0Û # remove leading zeroes Ë # all remaining elements are equal ``` [Answer] # Regex (ECMAScript), ~~276~~ ~~205~~ ~~201~~ ~~193~~ ~~189~~ ~~177~~ 174 bytes Comparing the multiplicities (exponents) of different prime factors is an interesting problem for solving with ECMAScript regex – the lack of backreferences that persist through iterations of a loop makes it a challenge to count anything. Even if counting the numerical trait in question is possible, often a more indirect approach makes for better golf. As with my other ECMA regex posts, I'll give a **spoiler warning:** I highly recommend learning how to solve unary mathematical problems in ECMAScript regex. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. [See this earlier post](https://codegolf.stackexchange.com/a/178889/17216) for a list of consecutively spoiler-tagged recommended problems to solve one by one. So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above. The main payload from a regex I previously developed turned out to be very applicable to this challenge. That is the [regex that finds the prime(s) of highest multiplicity](https://gist.github.com/Davidebyzero/9735222#gistcomment-1197451). My first solution for that was very long, and I later golfed it way down in stages, first [rewriting it to use molecular lookahead](https://gist.github.com/Davidebyzero/9735222#gistcomment-1209588), and then [porting it back to plain ECMAScript](https://gist.github.com/Davidebyzero/9735222#gistcomment-1211502) using an advanced technique to [work around the lack of molecular lookahead](https://gist.github.com/Davidebyzero/9735222#gistcomment-1207638), and subsequently golfing it down to be much smaller than the original plain ECMAScript solution. The part from that regex that applies to this problem is the first step, which finds Q, the smallest factor of N that shares all of its prime factors. Once we have this number, all we have to do to show that N is a "constant-exponent number" is divide N by Q until we can't any longer; if the result is 1, all primes are of equal multiplicity. After submitting an answer using my previously developed algorithm for finding Q, I realized that it could be calculated in an entirely different way: Find the largest square-free factor of N (using the same algorithm as my [Carmichael number regex](https://codegolf.stackexchange.com/a/179024/17216)). As it turns out, this poses no difficulty at all in terms of stepping around the lack of molecular lookahead and variable-length lookbehind (no need to pull in the advanced technique previously used), and is 64 bytes shorter! [Note, at the time, molecular lookahead still offered a slight benefit, but thanks to later golfs, it no longer does at all.] Additionally it eliminates the complexity of treating square-free N and prime N as different special cases, dropping another 7 bytes from this solution. (There still remain other problems that require the advanced technique formerly used here to golf down the calculation of Q, but currently none of them are represented by my PPCG posts.) I put the multiplicity test before the consecutive-primes test because the latter is much slower; putting tests that can fail more quickly first makes the regex faster for uniformly distributed input. It's also better golf to put it first, because it uses more backreferences (which would cost more if they were double-digit). [The multiplicity test is now split in two for golf, with the consecutive-primes test sandwiched inside.] I was able to drop 4 bytes from this regex (193 → 189) using a trick found by [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy) that can futher shorten the form of division in which the assertion that \$dividend-quotient\$ is divisible by \$divisor-1\$ can be skipped. (Skipping this assertion was already saving 4 bytes, so now it's saving 8 bytes.) This algorithm (in both its 4 byte longer form and the currently used one) is guaranteed to match the correct quotient when at least one of these constraints is met (along with satisfying the assertion that \$dividend\$ is divisible by \$divisor\$): * \$divisor^2+2(divisor)+1 < 4(dividend)\$ * \$quotient=1\$  or equivalently  \$divisor=dividend\$ * \$divisor\$ is a prime power + One of the cases in which this must be true is when \$dividend\$ is semi-prime and neither of the two other conditions are met. It also must be true if \$dividend\$ is a prime power. We're actually not guaranteed in this context that any of those constraints will be met. Most notably, we're not even asserting that \$quotient\$ (which will become the next \$dividend\$) is still divisible by \$divisor\$ after each iteration of the loop. But an additional fact comes to the rescue: if the division algorithm matches an incorrect quotient (which it doesn't always do even when none of the above constraints are met), the incorrect answer is guaranteed to be less than \$divisor\$ but greater than \$1\$. So if this happens when repeatedly dividing N by Q, the loop will terminate, and the final result will not be 1, thus guaranteeing no false positives. If N is actually a constant-exponent number, the correct quotient will always be greater than or equal to Q, so this doesn't cause any false negatives either. Further golfs: * -3 bytes by dividing by N just like any other largest square-free factor, instead of treating N being square-free as a special case ([inspired by H.PWiz](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#comment441526_179412) but goes farther then what he did, saving 1 extra byte – he made it so the regex attempted to divide by 0 in the case that Q=N, and then asserted that the end result of the repeated division was Q rather than 1) * -6 bytes by changing `(?=A)(?!B)` to `(?!B)A` (some of this is from multiple uses of backrefs changing from double to single digit, with less of the opposite occurring) – [thanks to H.PWiz](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#comment441526_179412) * -2 bytes by capturing the smallest prime as \$\ge 2\$ instead of augmenting the non-composite test to be a full prime test – [thanks to H.PWiz](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#comment441526_179412) * -2 bytes by removing an extraneous pair of parentheses – [thanks to H.PWiz](https://codegolf.stackexchange.com/questions/164911/is-this-a-consecutive-prime-constant-exponent-number/179412#comment441526_179412) * -2 bytes by changing an outermost `(|(x+)\2*(?=\2$))` to `(|x*)\1*(?=\1\b)`, similarly to what I did [in the alternate answer here](https://codegolf.stackexchange.com/questions/144561/golf-the-pseudoprimes/179024#179024); one of these bytes is from a backref changing from double to single digit And the regex: `^(?=(|x*)\1*(?=\1\b)(((?=(xx+?)\4*$)(?=(x+)(\5+$))\6(?!\4*$))*x$))(?!(((xx+)(?=\9+$)(x+))(?!\8+$)(x+))\7*(?=\7$)(?!(\11\10?)?(xx+)\13+$))((?=((x*)(?=\2\16*$)x)(\15*$))\17)*x$` [Try it online!](https://tio.run/##TU9LU8IwEP4rwDCw20ppkIdSQ08euHDQo9GZCKFEQ@gkQSqP345JZ5jxksn32m/3i/9wuzSydD1bypUw253@Fr9XQ7U4NF5E8VyVAEc660fXD8gpnKsIGYn8lxH2iQCBrKo4RzaM2lijGIGN4jYiG0PerHmMKv945ANVMPj8o7cEc6DZww2wST180q7djBBG0hzzOsXIfRhbd4JfJBgHjIx9QeU7ySg0MTIJbdeof8TE7V6dkboATKySSwHju94QMbM0zQ4bqQSAokbwlZJaAGKT6r1SeCqoSmyppINur4uZXANoWiRK6MJtcDY4n6Vd8AVIWnJjxVw7KN7Sd8SbIP4LekZyMg0yuo3ZHVpz/cOVXDUM14WYNlqxytY7A5l8oiKTcYy@sFW1EiNKwR1ITLbcLTdgEE@20yn9SQ7CFSQr98464y3Z5XJNe8M0/QM "JavaScript (SpiderMonkey) – Try It Online") ``` ^ # tail = N = input number # Assert that all of N's prime factors are of equal multiplicity. There are two stages # to this, which we will call Step 1 and Step 2. For golf reasons, a negative assertion # is inserted between them. # Step 1: Find Q, the largest square-free factor of N (which will also be the smallest # factor of N that has all the same prime factors as N). (?= (|x*)\1*(?=\1\b) # cycle tail through all of the divisors of N, including N, # from largest to smallest; # \1 = the divisor, or zero if the divisor is N itself # Assert that tail is square-free (its prime factors all have single multiplicity) ( # \2 = tail = the divisor ( (?=(xx+?)\4*$) # \4 = smallest prime factor of tail (?=(x+)(\5+$)) # \5 = tail / \4 (implicitly); \6 = tool to make tail = \5 \6 # tail = \5 (?!\4*$) # Assert that tail is no longer divisible by \4, i.e. that # that prime factor was of exactly single multiplicity. )*x$ ) ) # Assert that there exists no trio of prime numbers such that N is divisible by the # smallest and largest prime but not the middle prime. (?! ( # \7 = a factor of N ( # \8 = a non-factor of N between \7 and \9 (xx+)(?=\9+$) # \9 = a factor of N smaller than \7 and greater than 1 (x+) # \10 = tool (with \11) to make tail = \9 ) (?!\8+$) (x+) # \11 = tool to make tail = \8 ) \7*(?=\7$) # tail = \7 # Assert that \7, \8, and \9 are all prime (?! (\11\10?)? # tail = either \7, \8, or \9 (xx+)\13+$ # Assert tail is not composite; no need to test against # 0 and 1, because we captured \9 > 1 ) ) # Step 2: Require that the result of repeatedly dividing N by \2 is 1. ( # In this division calculation \15 = N / \2, we can skip the test for N-\15 being # divisible by \2-1. (Actually doing that test would make the regex 8 bytes larger.) # The quotient matched by this abbreviated algorithm is guaranteed to be correct if # the real quotient is 1 or is not less than the divisor, or if the divisor is a # prime power. Our input here is not guaranteed to satisfy any of those constraints. # But if none of those constraints are met, and the quotient matched by the algorithm # is incorrect, the incorrect quotient is guaranteed to be less than the divisor and # greater than 1. And once that happens, this loop will terminate, as the current # value will no longer be divisible by our divisor \2. (?= ( # \15 = tail / \2 (x*) # \16 = \15-1 (?=\2\16*$) x ) (\15*$) # \17 = tool to make tail = \15 ) \17 # tail = \15 )* x$ # Require that the end result is 1 ``` ## Regex (ECMAScript+`(?*)`, ~~195~~ ~~187~~ ~~183~~ bytes Obsoleted by no longer treating N being square-free as a special case (i.e. is now identical to the above). ## Regex (ECMAScript 2018), ~~198~~ ~~195~~ ~~194~~ ~~186~~ ~~182~~ bytes Obsoleted by no longer treating N being square-free as a special case and changing `(?=A)(?!B)` to `(?!B)A` (i.e. is now identical to the above). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~6~~ 5 bytes ``` ÆEt0E ``` [Try it online!](https://tio.run/##y0rNyan8//9wm2uJgev/h7u3hD1qWnO4HUj8/6@urm7EZcxlwmXKZcZlzmXBZcllaMhlaMxlaMplZG5gYMBlYmpmagzkG3AZGnEZmnCZA0kDCABqBgA "Jelly – Try It Online") Still outgolfed... (thanks Erik for -1 byte) --- **Explanation** ``` ÆE # get a list of prime exponents (noooo long builtin name) t0 # remove zeroes on both sides (leading or trailing) E # all remaining elements are equal ``` [Answer] # JavaScript (ES6), 87 bytes Returns **0** for truthy or a non-zero integer for falsy. ``` f=(n,k=2,j,i)=>n%k?j*(P=d=>k%--d?P(d):d==!i)(k)|j-i|(n>1&&f(n,k+1,j||i)):f(n/k,k,j,-~i) ``` [Try it online!](https://tio.run/##bdCxDoIwEAbgnbdwAHvaKkUBNSluzgxuxoFQ0bakGFETE@Kro8RFPbr1y93lz6@ze1bnF3W@MlvJQ9sWglhqREA1VSAS65q1HpFUSJEYlzG5TomElRRioIAYaDRTDbEJ97yiWxxzqptGAaze36mh5n2HPRW0eWXrqjxMyupIhrvt5XY9PfZDcL69IAH8ywzJHEmIJEISI1kgWSLhHBNOxHGAIPZ9H0cPo3DW7Tu/dWyysu5pg@MLHDfEcSFxz5T/eQDtCw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f() = recursive function taking: n, // n = input k = 2, // k = current factor j, // j = reference exponent, initially undefined i // i = current exponent, undefined each time we start testing ) => // the next factor n % k ? // if k is not a divisor of n: j * ( // ignore the primality of k if j is still undefined P = d => // P() = function testing if k is prime: k % --d ? // decrement d; if d is not a divisor of k: P(d) // do a recursive call until it is : // else: d == !i // unless i is already defined: d must not be equal to 1 // (if it is: k is the next prime but does not divide n) )(k) | // initial call to P() with d = k j - i | ( // if both i and j are defined, they must be equal n > 1 && // if n is not yet equal to 1, f(n, k + 1, j || i) // go on with k + 1; if j is undefined, set it to i ) // (otherwise, stop recursion and return what we have) : // else: f(n / k, k, j, -~i) // increment the current exponent and go on with n / k ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~30~~ 29 bytes ``` {mFz~)-!\__W=,\0=>\-:mp1#W=&} ``` [Try it online!](https://tio.run/##S85KzP3/vzrXrapOU1cxJj4@3FYnxsDWLkbXKrfAUDncVq32f2Gdqp/W/2gjLmMuEy5TLjMucy4LLksuQ0MuQ2MuQ1MuI3MDAwMuE1MzU2Mg34DL0IjL0ITLHEgaQEAsAA "CJam – Try It Online") My first answer after a nearly 2(!)-year break, so it can probably be golfed more. This is a block that takes input as an integer (can also be mapped over for arrays of integers). ## Explanation ``` { e# Begin block mF e# Factor input, giving an array of primes and their powers z~ e# Transpose and dump, giving an array of primes and an array of powers )- e# Check that the powers are the same: subtract each power from the last element ! e# Negate to make sure they're all 0 \__W=, e# Get the range from 0 to the largest prime minus one \0=> e# Slice that array so it only includes everything larger than the smallest prime \- e# Remove the original primes from the range array :mp e# Check each element for primality. If the input's primes are consecutive, e# this will contain no primes 1#W= e# Make sure a "1" is not found & e# If the powers are the same AND primes are consecutive, return 1. Otherwise, 0. } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~5~~ 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╣♥qJ╬c ``` [Run and debug it](https://staxlang.xyz/#p=b903714ace63&i=2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A11%0A13%0A15%0A512%0A27000%0A456533%0A10%0A12%0A14%0A72%0A10000000&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` |n get the exponents of the prime factorization 0:D trim leading zeroes :u array has exactly a single distinct element ``` **Edit:** ~~This doesn't work on `512`. I'll give it some thought and hopefully a fix later.~~ It works now. [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) 1 is truthy, 0 is falsy ``` αAG<└\{┬⌠ ``` [Run and debug it](http://stax.tomtheisen.com/#p=e041473cc05c7bc2f4&i=2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A11%0A13%0A15%0A27000%0A456533%0A%0A10%0A12%0A14%0A72%0A10000000%0A%0A108%0A2250&m=2) **Explanation** ``` |nX0-u%x:^= # Full Program, unpacked, implicit input |n # Exponents of sequential primes in factorization. (eg. 20 -> [2 0 1]) X # Save to X register 0- # Remove all '0' from array u% # Get unique numbers and get length of array x # Copy back the array saved to X :^ # Is it ascending = # Are the two comparisons equal? implicit output ``` Can probably be golfed more, but it covers the cases I was missing in the last solution. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` Λ§*≈¤≈oṗ←gp ``` [Try it online!](https://tio.run/##yygtzv6fq@GlpKBrp6AUnKpR/KipsUhT89C2/@dmH1qu9aiz49ASIJH/cOf0R20T0gv@//9vxGXMZcJlymXGZc5lwWXJZWjIZWjMZWjKZWRuYGDAZWJqZmoM5BtwGRpxGZpwmQNJAwgAAA "Husk – Try It Online") Outputs 0 if not a consecutive-prime/constant-exponent number. [Answer] # Java 10, ~~223~~ ~~191~~ ~~178~~ ~~176~~ 168 bytes ``` n->{var s=new java.util.HashSet();for(int f=1,i=1,x,j;n>1;){for(x=++i,j=2;j<x;)x=x%j++<1?1:x;if(x>1){for(j=0;n%i<1&&n>(f=0);n/=i)j++;if(f<1)s.add(j);}}return s.size();} ``` Returns `1` as truthy, and `>=2` as falsey. [Try it online.](https://tio.run/##bVJdT8MgFH33V9w0cYGwdWWfOsp8M764l/mmPuBGFeyYKXRWl/72ST@WrIkECOfey8m5B7Q4iIHefp42qbAWHoUyxysAZZzMErGRsKpgHYANqnaDmY@UfvlpnXBqAyswwOFkBsvjQWRguZHfoD11mDuVhg/CfqylQ5gl@6wmSTjtK7@KvmZmSRk@VpmCE6L6mo@YjguGC15ca0JiekcXBVMJKpa0KdQ8YuZaxbTXM0uU8AgzM@QK@@qqLokptqHYbpHGrCwz6fLMgA2t@pVeRHlijfqv/C316tsmDnu1hZ03AK1dpsz78ysI3HQ/HMJTlruPn0UNz10orxRUzG/9TgiucwBOWodU7VILKO2gcQdNL9FoHkXRZWAynU3H5wvrH@vkLtznLvzyCl1qUJs5q7wXqZWtyoa@w0ZHHTS5RPNu7nY0v@kEomb88/q1cU3XlSmtZ/@IVSRYvLiAIP9ycnYX@PMiCDAxof9auGUuT38) **Explanation:** ``` n->{ // Method with integer parameter and boolean return-type var s=new java.util.HashSet(); // Set to keep track of the prime exponents for(int f=1, // Prime-flag, starting at 1 i=1,x,j; // Index and temp integers n>1;){ // Loop as long as `n` is still larger than 1 for(x=++i, // Set `x` to `i`, after we've increased `i` by 1 first with `++i` j=2; // Set `j` to 2 (first prime) j<x;) // Inner loop as long as `j` is still smaller than `x` x=x%j++<1? // If `x` is divisible by `j`: 1 // Set `x` to 1 : // Else: x; // Leave `x` unchanged if(x>1){ // If `x` is larger than 1 (if `i` is a prime): for(j=0; // Use `j` as counter, and set it to 0 n%i<1 // If `n` is divisible by `i`: // And loop as long as `n` is still divisible by `i`, &&n> // and `n` is larger than 0 (f=0); // (and set `f` to 0 at the same time) n/=i) // Divide `n` by `i` j++; // And increase `j` by 1 if(f<1) // If the flag `f` is now/still 0: s.add(j);}} // Add counter `j` to the Set return s.size();} // Return the amount of items in the Set // (1 being true, >=2 being false) ``` **Some example inputs:** `n=15`: * Flag remains `1` for the first prime 2 (because 15 is not divisible by 2). * Flag goes from `1` to `0` as soon as we're at the prime 3. Since 15 is divisible by 3, `n` becomes 5 (15/31), and the Set becomes `[] → [1]`. * Then we check the next prime 5. Since 5 is divisible by 5, `n` becomes 1 (5/51), and the Set remains the same (`[1] → [1]`). * Now `n=1`, so we stop the outer loop. The Set (`[1]`) only contains one item, the `1` from both adjacent primes 3 and 5, so we return true. `n=14`: * Flag goes from `1` to `0` for the first prime 2 (because 14 is divisible by 2). `n` becomes 7 (14/21), and the Set becomes `[] → [1]`. * Then we check the next prime 3. Since 7 is not divisible by 3, `n` remains the same, and the Set becomes `[1] → [1,0]`. * Then we check the next prime 5. Since 7 is also not divisible by 5, `n` remains the same, and the Set remains the same as well (`[1,0] → [1,0]`). * Then we check the next prime 7. Since 7 is divisible by 7, `n` becomes 1 (7/71), and the Set remains the same (`[1,0] → [1,0]`). * Now `n=1`, so we stop the outer loop. The Set (`[1,0]`) contains two items, the `1` from the non-adjacent primes 2 and 7, and the `0` from the primes 3 and 5, so we return false. `n=72`: * Flag goes from `1` to `0` for the first prime 2, because 72 is divisible by 2 (multiple times). So `n` becomes 9 (72/23), and the Set becomes `[] → [3]`. * Then we check the next prime 3. Since 9 is divisible by 3 (multiple times), `n` becomes 1 (9/32), and the Set becomes `[3] → [3,2]`. * Now `n=1`, so we stop the outer loop. The Set (`[3,2]`) contains two items, the `3` from prime 2, and the `2` from prime 3, so we return false. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12 11~~ 10 bytes ``` YFtgYsg)Zs ``` [Try it at MATL Online!](https://matl.io/?code=YFtgYsg%29Zs&inputs=27000&version=20.9.1) Thanks to Luis Mendo for the remove-leading-zeroes part. He also pointed out that swapping truth values is allowed, so this returns **0** for numbers that satisfy the challenge requirements and any positive value otherwise. Grosso Modo, this generates the exponents of the sequential prime factorization, removes leading zeroes and calculates the standard deviation. [Answer] # [J](http://jsoftware.com/), 16 bytes Big thanks to FrownyFrog for -8 bytes! ``` (=&#+/\=@#])_&q: ``` [Try it online!](https://tio.run/##Rc7BCsIwDAbge58ibLBuzNZkM6sWCj6IYwexDC8iO@/Z60ETc/oIP3/yLHlLHhAiYGlTU/fHW7rWc7c071g6U3mwOXkLB9gj5M2Yx319QYZBMApOAhZMgiA4Cy4CIpU2kTYMARH1AE88/kLWOWc1rxHSt0jfCf8dfkfbmcsH "J – Try It Online") ## My old solution: # [J](http://jsoftware.com/), 24 bytes ``` [:(1=[:#@~.{.@I.}.])_&q: ``` [Try it online!](https://tio.run/##Rc7BCsIwDAbge58iKFgHNiSbXTVQ2NVnGOJBLMOLyI4yX70eNDGnj/DzJ/da5oxAIEB1lC3nUdbDG184nHDBc3PZPKU2boXgS0YPO1gEyuzc7To9oECr6BR7RVT0iqQ4KI4KZpM1sTW0iYjsQOxj9wv5EIK3vEXY3mJ7J/139J36AQ "J – Try It Online") ## Explanation: `_&q:` prime exponents `{.@I.}.]` removes the leading zeros by finding the first non-zero element: ``` }. drop ] from the list of exponents {.@ as much items as the first of the I. indices of non-zero elements ``` `1=[:#@~.` tests if all remaining numbers are equal: ``` [:#@~. finds the length of the list after removing the duplicates 1= is it 1? ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` 0iYFhdz ``` The result is `1` iff input satisfies the requirement. [Try it online!](https://tio.run/##y00syfn/3yAz0i0jper/fyNzAwMDAA) Or [verify all test cases](https://tio.run/##JccxCoAwDEDR/Z8maZpWd/EELm4VHBR0c/LyseAfHvx7e65oIec6H/sb0xIJI@MUKgMjqqihTqoiQvbi1l/QhGZqV/4@) ### Explanation ``` 0 % Push 0 i % Push input number YF % Exponents of consecutive prime factors h % Concatenate horizontally d % Consecutive differences z % Number of nonzeros. Implicitly display ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 67 bytes ``` @(x)~any(diff(find(h=histc(factor(x),primes(x))))-1)&h(h>0)==max(h) ``` [Try it online!](https://tio.run/##TYzhCoIwAIT/31P4Kzcw2dRpEYteZahjA52hM5SoV7eRBN2P4@C7u6H26tFuWqZput3IQt/KraSxWhNtXUOMNHbyNdGq9sMYeHIfbd9OIQUdOT0YYq6MStmrhRi6@XH2Zo1k9MyQo4BAiQonnME5eA4ukFWMMRSiFHn@ukCrbmq/C87AM/ACVXC2KxRQt12nZ0d0sr8n8ezihNE/sJ/8wPYB "Octave – Try It Online") I believe this is the only solution that uses a histogram. ### Explanation: This makes a histogram, where the variable to be counted are the factors of the input, and placed in the bins `primes(x)`, which is all primes less than the input. We then find the location of the prime factors, takes the difference between each of the indices and subtract one. If there are any elements that aren't zero (i.e. the difference of the indices of prime numbers is not 1), then this will result in a falsy value, otherwise it will return a truthy value. We then chech that all non-zero elements in the histogram are equal to the maximum element. If there are values that aren't equal then this will result in a falsy value, otherwise it will return a truthy value. If both those blocks are truthy then our input is a consecutive prime constant exponent number! [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 28 bytes ``` {f p←`↓⍭⍵⋄(1=≢∪p)∧∨/f⍷⍸1⍭⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/Py3vUduE6jSFAiCV8Kht8qPetY96tz7qbtEwtH3UuehRx6oCzUcdyx91rNBPe9S7/VHvDkOwks1AVbX//6uHFJWWZFRaqXOl5SkYgQhjEGECIkxBhBmIMAcRFiDCEkQYGoJJsEpDsCojcwMDA7BGUzNTY2MuQ9NHvVvUddW51N0Sc4qhxhuCVRiCbTEE22AOYRuAND/qnatQkpmbWqyQX1qiABMGAgA "APL (Dyalog Extended) – Try It Online") ### How: ``` {f p←`↓⍭⍵⋄(1=≢∪p)∧∨/f⍷⍸1⍭⍳⍵} ⍝ Monadic function, takes an argument ⍵ ⍭⍵ ⍝ Prime factors and exponents of ⍵ `↓ ⍝ split the resulting matrix in 2 vectors f p← ⍝ assign the factors to f and the powers to p ⋄ ⍝ then ⍳⍵ ⍝ range [1..⍵] 1⍭ ⍝ primality check for each element in the vector ⍸ ⍝ where; returns the indices of truthy values f⍷ ⍝ find the factors; returns a boolean vector ∨/ ⍝ logical OR reduction ∧ ⍝ logical AND ( ∪p) ⍝ unique members of the powers ≢ ⍝ tally; returns the number of elements in the vector 1= ⍝ check if there's only one element ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes ``` Differences[{PrimePi@#,#2}&@@@FactorInteger@#]~MatchQ~{{1,0}...}& ``` [Try it online!](https://tio.run/##JYuxCoMwEIZf5SDgdLWJVm2Hlgyl0KFgZ3EIIdEMWkizhfjq6Ul/OP7ju/sWFWazqOC0yhau@e6sNd6s2nyH2Hu3mN5JhqxKhZTyoXT4@OcazGS8ZOP2UkHP7y1GgTyVZZmKTNIaBgaHG9iBjSMUcJQQK4Qa4YTQILQIHcIZ4YIgBA1dBPGq45zTU9M29Y5oF@QJsrq9@T8p/wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 63 bytes ``` n->#Set(vector(#(a=factor(n)~),i,[primepi(a[1,i])-i,a[2,i]]))<2 ``` [Try it online!](https://tio.run/##JYzRCsIwDEV/5bK9NJBCu7lNwe0nfBx9KLJJQWsZRfDFX6@ZBkJObu5N8lvQt1RWjCXqqb4sWb2Wa35uqlZ@XP0PI32IA89pC48lBeVny8GRDuznRsgRnZviU7q/VYSeIMaYBat9qbDKB2KIFy3jwOgYPWNgHBknhrXScrGiN4MxRkxd37W7JGwlZyU17NP8y1H5Ag "Pari/GP – Try It Online") [Answer] # [J](http://jsoftware.com/), 14 bytes ``` 1#.2~:/\0,_&q: ``` 1 in the output indicates consecutive constant exponent. [Try it online!](https://tio.run/##Rc7BCsIwDAbge58iOLAIa5d0ZnWFvYngQSziRWRnffV6cPnN6SP8/Mmj1XWJxFSIm3Qxfcpw5v6yf5V2cLtIvi7RU0/vQnV17na9P6lSMoyGo0ENkyEbTobZIAKhSdCQMjPjgE46biEfQvDIIyJ4S/BO/u/4N2hXbV8 "J – Try It Online") ``` 0,_&q: zero followed by the prime exponents of input 2~:/\ for every two consecutive values, 1 if they are different 1#. convert from base-1, just add them up ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 127 bytes ``` import StdEnv @n=[]== $n ?n#j= $n = @n||j==filter@[hd j..last j]&&any(\p=(prod j)^p==n)[1..n] $n=[i\\i<-[2..n-1]|n/i*i==n&& @i] ``` [Try it online!](https://tio.run/##PY5PC4JAFMTvfooHhVSgYdCtRx7qEHTzqBts/qknu09Z10Dws7ctBd3mNzMMU6pastNdNaoatCR2pPvOWMhsdeZXkDLmAhGWHBx50X4FQsrz3CI2pGxt0vxZQRvHSg4WWhGGkqdV0eOqN50P1rcekdd5EscsgqXfo6KgQ5TvvBElYuYtbchXwhBSEi6z0thgATzqe20AYZ/sPDYjl5Y69sbRP/jjr@beZaPkY3DR5epOE0tN5fAB "Clean – Try It Online") Defines the function `? :: Int -> Bool` using `$ :: Int -> [Int]` to factorize and `@ :: Int -> Bool` to check primality. [Answer] # APL(NARS) 41 chars, 82 bytes ``` {(1=≢∪+/¨{v=⍵⊃v}¨⍳≢v)∧(1↓w)≡¯1↓1πw←∪v←π⍵} ``` {π⍵} is the function factorization of argument ⍵ in the list of prime factors (repeat if one prime appear more time); {1π⍵} is the function next prime (note that in this case its argument is not a scalar but one array of integers). test: ``` h←{(1=≢∪+/¨{v=⍵⊃v}¨⍳≢v)∧(1↓w)≡¯1↓1πw←∪v←π⍵} (2..30)/⍨h¨2..30 2 3 4 5 6 7 8 9 11 13 15 16 17 19 23 25 27 29 30 h¨27000 456533 72 10000000 1 1 0 0 ``` ]
[Question] [ In this challenge, you receive a string as input containing a string of X's, Y's and Z's eg. "XYZZ". X, Y and Z represent a particular character. This pattern is then compared with a second string input. If the pattern exists as a substring in the second input, return `True`, otherwise, return `False`. Once a pattern is found in the word, the program stops searching and returns `True`. ## Examples Pattern: "XXYY" ``` succeed ---> True (pattern found: ccee) success ---> False (pattern not matched) balloon ---> True (pattern found: lloo) ``` Pattern: "XYXYZ" ``` bananas ---> True (pattern found: nanas) banana ---> False (pattern not found) ``` * Note: This is not the actual input. This is an example of how the program should work. Your program should output `True` or `False`, or other Truthy/Falsy values. ## Other important/useful information * The pattern does not need to contain an X, Y and a Z, it could contain X's and Y's or even (although somewhat pointless) just X's. * The pattern cannot be empty, but this will not be used as a test case. * The search string will not be empty, and will be lowercase. * The alphabetic order of X, Y and Z in the pattern does not matter. * X, Y and Z *must* be unique characters. * You may use any library you wish. * The score is determined by the **code size**, in bytes. Lowest score wins. Good luck! [Answer] # [Perl 5](https://www.perl.org/), 85 bytes *Saved 40 bytes thanks to Peter Taylor's suggestion! (see my older version bellow to see the differences)* 83 bytes of code + `-pl` flag. ``` s/./$h{$&}?"\\$h{$&}":($h{$&}=$.,join("",map"(?!\\$_)",1..$.++)."(.)")/ge;$_=<>=~$_ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAtyPlfrK@nr5JRraJWa68UEwNhKVlpQBi2Kno6WfmZeRpKSjq5iQVKGvaKQDXxmko6hnp6Knra2pp6Shp6mkqa@ump1irxtjZ2tnUq8f//R0RGREZxJSXmAWExAA "Perl 5 – TIO Nexus") XYXYZ is transformed into `((?!\1).)((?!\1)(?!\2).)\1\2((?!\1)(?!\2)(?!\3).)` (yup, some of the tests can't be true, but it's shorter that way), and the second input is then checked against that regex. (see the explanations of my older version to get more intuition of how it works) --- My older version: *Thanks to Arnauld for pointing out a mistake I made in my first version.* 113 bytes of code + `-pl` flags, and `-Mre=eval`. ``` s/./$h{$&}?"\\$h{$&}":($h{$&}=++$i,"(.)")/ge;$_.='(?{++$c;$\=1if!grep$v{$c}{${$_}}++,1..'.(keys%h).'})^';<>=~$_}{ ``` [Try it online!](https://tio.run/nexus/perl5#JYndCoIwGEDvfQpdX21j9om3reVraEhi8vlDEuJIiLFe3QQ5N4dzDtFE8xiepzH4WApnCjkt9cj1ahNMoHdw8hkry93YRexilIIhZgIlk0lHGio0XGRuy42G0qRDG3UzTbA4aLwDB5X3SsUpIkfxoq899hK5lw@urzfz27Zb17zIi3vwrN8b9g8 "Perl 5 – TIO Nexus") On the example XYXYZ: the first regex will convert the pattern to (.)(.)\1\2(.), and add at the end a test to check if `$1`, `$2` and `$3` are different: if so, `$\` is set to one. Then, the second input is testes against this regex, and `$\` is implicitely printed at the end. The regex generated for XYXYZ is `(.)(.)\1\2(.)(?{++$c;$\=1if!grep{$v{$c}{${$_}}++}1..3})^`. *(I'll to add a bit more details to the explanations when I have a moment)* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` =þ ẆÇ€ċÇ} ``` Returns the number of times the pattern was found, non-zero being truthy and zero being falsy. [Try it online!](https://tio.run/nexus/jelly#@297eB/Xw11th9sfNa050n24vfb/wx2bDi9XApK17v//F5cmJ6empiiA6eJihaTEnJz8/DwgnQeExVD6f0REZKQCEhEZERkFIQE "Jelly – TIO Nexus") ### How it works ``` ẆÇ€ċÇ} Main link. Left argument: s (string). Right argument: p (pattern) Ẇ Window; generate all substrings of s. Ç€ Map the helper link over the substrings. Ç} Apply the helper link to p. ċ Count the number of times the right result appears in the left result. =þ Helper link. Argument: t (string) =þ Compare all characters of t for equality with all characters of t, yielding a square matrix of Booleans. ``` [Answer] ## JavaScript (ES6), 94 bytes ``` f= (p,s)=>s.match(p.replace(/./g,c=>m[c]||(t=r,r=`(?!\\${++g})`+r,m[c]=`\\`+g,t),g=m=[],r=`(.)`)) ``` ``` <div oninput=o.textContent=!!f(p.value,s.value)><input id=p placeholder=Pattern><input id=s placeholder=String><span id=o> ``` Works by transforming the pattern into a regexp, e.g. for `XYXYZ` it generates `/(.)(?!\1)(.)\1\2(?!\2)(?!\1)(.)/`. I notice an interesting distinction between PCRE and JavaScript regexp: in PCRE, `\<n>` fails (and therefore `(?!\<n>)` succeeds) before the capture group is defined, while JavaScript it succesfully matches the empty string (and therefore `(?!\<n>)` fails). [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` f=lambda p,s:s>''and(map(s.find,s[:len(p)])==map(p.find,p))|f(p,s[1:]) ``` [Try it online!](https://tio.run/nexus/python2#dYtBCsIwEEX3nqJk0wwEwW0gniOxdDFtEiik08GpO@8eo66E@v/uPV7NruA6RezYiJVr3yNFvSJrOeeFopHBlkSaYQTn3py/nAGeWbdouNgRKt8X2ruslfchKKPkMc8pRQWnQyNyYCYsZdvowGDbDw4@3D4Ftct/paC@AA "Python 2 – TIO Nexus") Checks if a string matches a pattern using the method in [this answer](https://codegolf.stackexchange.com/a/50612/20260). Uses a prefix of the search string whose length equals the pattern. Chops off the first character of the string string until a match is found, or `False` if it becomes empty --- **73 bytes:** ``` f=lambda p,s:s>''and(map(s.find,s)==map(p.find,p))|f(p,s[1:])|f(p,s[:-1]) ``` [Try it online](https://tio.run/nexus/python2#@59mm5OYm5SSqFCgU2xVbKeunpiXopGbWKBRrJeWmZeiU6xpawviFkC4BZqaNWkaQLXRhlaxMKaVrmGs5v@Cosy8EoU0DaWIiMhIJR2l4tLk5NTUFCVNLqwyxcVYZJISc3Ly8/OwyCQCAYpwZERkFFhHHhAW45ZS0vwPAA "Python 2 – TIO Nexus") Checks if a string matches a pattern using the method in [this answer](https://codegolf.stackexchange.com/a/50612/20260). Recursively checks all substrings by branching into removing the first or last character until the string is empty. [Answer] # [Python 3](https://docs.python.org/3/), 100 bytes ``` l=len f=lambda p,s:l(p)<=l(s)and(l({*zip(p,s)})==l({*p})==l({s for _,s in{*zip(p,s)}})or f(p,s[1:])) ``` [Try it online!](https://tio.run/nexus/python3#bY7LCsIwEEXXzVcMWWUkCC5ECOY/GkuR9AWFNA2durH022taFURlYLhz5i7O4rSr) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 16 bytes ``` ÙœJv¹y…XYZ‡²åi1q ``` [Try it online!](https://tio.run/nexus/05ab1e#@3945tHJXmWHdlY@algWERn1qGHhoU2Hl2YaFv7/n5SYB4RcEZERkQA "05AB1E – TIO Nexus") --- ``` ÙœJ # Get powerset of all unique characters in string. v # Loop through each... ¹ # Push input word. y # Push current set of letters in powerset. …XYZ‡ # Replace each of the 3 letters in the original word with XYZ. ²å # Check if second input is in this string, push 1 if it is. i1q # If 1, push 1 and quit. ``` Will return 1 if true, null if not true. --- This can be 14 bytes if returning the possible values of XYZ is allowed: # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ÙœJv¹y…XYZ‡²å— ``` [Try it online 2!](https://tio.run/nexus/05ab1e#@3945tHJXmWHdlY@algWERn1qGHhoU2Hlz5qmPL/f1JiHhByRURGRAIA "05AB1E – TIO Nexus") [Answer] # Java 7, ~~177~~ ~~176~~ 173 bytes ``` Object c(String p,String s){int i=p.length();if(s.length()<i)return 0>1;for(;i-->0;)if(p.indexOf(p.charAt(i))!=s.indexOf(s.charAt(i)))return c(p,s.substring(1));return 1>0;} ``` **Explanation:** ``` Object c(String p, String s){ // Method with two String parameters and Object return-type int i = p.length(); // Index that starts at the length of the pattern if(s.length() < i) // If the length of the input is smaller than the length of the pattern return 0>1;//false // Simply return false for(;i-->0;) // Loop from 0 to length_of_pattern if(p.indexOf(p.charAt(i)) != s.indexOf(s.charAt(i))) // If the index of the characters of the pattern and input aren't matching return c(p, s.substring(1)); // Return the recursive-call of pattern and input minus the first character // End of loop (implicit / single-line body) return 1>0;//true // If every index of the characters are matching: return true } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#jY@/TsMwEIf3PMWRyZbSqJlNK/EAqEOXBMTgOG57yHUs3wWBqjx7cEuoYIHqlvvz6efPk3GaCB5PGQCxZjSwaV@tYTBiyxH9HkIxNyRP6BlwFUpn/Z4PQircCbpO9yij5SF6WK4rteujULhYrJdKJiyU6Dv7vjl35qDjAwuU8m5F1z392H8HGREKKmlo6eIgKinVfKpS8Jgl7zC0LnnP@m89dnDU6Gf/5xfQ8vw9gO0HsT2W/cBlSCd2XhiR13XT5AXkNBhjbZenF26liW6kW@1c3/sL/Rfe1M3TF@9T/Zv@G5/pMRun6RM) ``` class M{ static Object c(String p,String s){int i=p.length();if(s.length()<i)return 0>1;for(;i-->0;)if(p.indexOf(p.charAt(i))!=s.indexOf(s.charAt(i)))return c(p,s.substring(1));return 1>0;} public static void main(String[] a){ System.out.println(c("XXYY", "succeed")); System.out.println(c("XXYY", "success")); System.out.println(c("XXYY", "balloon")); System.out.println(c("XYXYZ", "bananas")); System.out.println(c("XYXYZ", "banana")); } } ``` **Output:** ``` true false true true false ``` [Answer] # PHP, 89 Bytes A Gift from [@Christoph](https://codegolf.stackexchange.com/users/29637/christoph) and [@Titus](https://codegolf.stackexchange.com/users/55735/titus) ``` for(;$v=$argv[1][$i++];)$r.=$$v?"\\".$$v:"(.)".!$$v=++$j;echo preg_match("#$r#",$argv[2]); ``` # PHP, 105 Bytes [A Gift from @Christoph](https://codegolf.stackexchange.com/users/29637/christoph) ``` foreach(str_split($argv[1])as$v)$r.=$x[$v]?"\\$x[$v]":"(.)".!$x[$v]=++$y;echo preg_match("#$r#",$argv[2]); ``` # PHP, 167 Bytes ``` [,$a,$b]=$argv;foreach($s=str_split($a)as$v)$r[]=$k++>strpos($a,$v)?"\\".(1+array_search($v,array_keys(array_count_values($s)))):"(.)";echo preg_match(_.join($r)._,$b); ``` [Answer] ## C#, 184 165 155 bytes thanks aloisdg! ``` bool c(string p,string n){for(int l=p.Length,i=0,j;i<l;i++)for(j=i;j>=0;)if(p[i]==p[j]==(n[i]!=n[j--]))return l!=n.Length&&c(p,n.Substring(1));return 2>1;} ``` backtracking solution, as a bonus it works with a pattern with any characters! ``` public static bool c(string p,string n) { for (int l = p.Length, i = 0, j; i < l; i++) for (j = i; j >= 0;) if (p[i]==p[j]==(n[i]!=n[j--])) return l != n.Length && c(p,n.Substring(1)); return 2>1; } ``` [Answer] # Ruby, ~~63~~ 61 bytes ``` ->a,b{a.chars.permutation.any?{|w|a.tr((w|[])*'','XYZW')[b]}} ``` Instead of searching for a regex pattern, just try substituting 'X','Y' and 'Z' in all possible ways, and find a literal match. (Actually the same concept as carusocomputing's 05AB1E answer) [Answer] ## JavaScript (ES6), ~~92~~ ~~89~~ ~~87~~ 86 bytes Takes input `p` (pattern) and `s` (string) in currying syntax `(p)(s)`. Returns `0` / `1`. ``` p=>g=s=>s&&g(s.slice(1))|[...p].every((C,i,x)=>C==(x[c=s[i]]=x[c]||'XYZ'[c&&j++]),j=0) ``` ### Formatted and commented ``` p => // main function: takes pattern p as input, returns g g = s => // g = recursive function: takes string s as input s && // if s is not empty: g(s.slice(1)) // do a recursive call, starting at the next character | // merge the result with this iteration [...p].every((C, i, x) => // for each character C at position i in p: C == // check whether C is matching the next expected ( // character, which is either: x[c = s[i]] = x[c] || // - a substitution character already associated to s[i] 'XYZ'[c && j++] // - the next substitution character ('X', 'Y' or 'Z') ), // - undefined if c = s[i] doesn't exist or j > 2 j = 0 // initialize j = pointer in 'XYZ' ) // ``` ### Test cases ``` let f = p=>g=s=>s&&g(s.slice(1))|[...p].every((C,i,x)=>C==(x[c=s[i]]=x[c]||'XYZ'[c&&j++]),j=0) console.log(f("XXYY")("succeed")) // 1 console.log(f("XXYY")("success")) // 0 console.log(f("XXYY")("balloon")) // 1 console.log(f("XYXYZ")("bananas")) // 1 console.log(f("XYXYZ")("banana")) // 0 ``` [Answer] # Mathematica 18 characters (not counting string & pattern) ``` StringContainsQ[string,pattern] ``` Examples: ``` StringContainsQ["succeed", x_ ~~ x_ ~~ y_ ~~ y_] ``` `True` ``` StringContainsQ["bananas", x_ ~~ y_ ~~ x_ ~~ y_ ~~ z_] ``` `True` ]
[Question] [ **Final results are here !** # Introduction The game takes is strongly inspired by [Manu's Game of Town](https://codegolf.stackexchange.com/questions/44491/the-game-of-towns/44531). It takes place in a world of swords and magic. The king who ruled the whole continent just died, and the lords of the many city-states are now fighting over territory. You are one of these lords and your goal is to conquer and rule every single town. # Principle People are divided into **8 classes** : ``` Warlocks : Fighter (magic) Crusaders : Fighter (melee) Amazons : Fighter (range) Corsairs : Utility (steal, guard, transport) Bishops : Utility (convert, exorcize) Necromancers : Utility (resurrect) Architects : Utility (build) Peons : Resource (income, recruits) ``` When the game begins, you rule over one town. In each town, there are **100 people**. You have to split them up between those 8 categories. Then the actual game begins, which is turn-based. A turn consists of **12 phases**, 7 of which are interactive (asking bots for a command). Next phase begins when previous phase has been executed by every town (Phase 1 : Town 1, Town 2, Town 3... ; Phase 2 : Town 1, Town 2, Town 3...) : ``` 1. Raise Taxes - AUTOMATED 2. Steal Money - INTERACTIVE 3. Recruit Troops - INTERACTIVE 4. Pay Wages - AUTOMATED 5. Try Revolt - AUTOMATED 6. Convert Soldiers - INTERACTIVE 7. Attack Town - INTERACTIVE 8. Raise Corpses - INTERACTIVE 9. Move Army or Tribute - INTERACTIVE 10. Defend against Threats - AUTOMATED 11. Construct Buildings - INTERACTIVE 12. Make Children - AUTOMATED ``` The controller provides you with input via command arguments, your program has to output via stdout. # Syntax **Output (preparation)** Before the game starts, the controller invokes you submission without arguments. This means you have to distribute your 100 people into into the 8 categories. You need to output : `Warlocks Crusaders Amazons Corsairs Bishops Necromancers Architects Peons` For example : `15 10 12 10 7 5 1 40`. Each town also starts with 500 gold and 5 corpses. **Input** Each time your program is called, it will receive arguments in this format : `Round;Phase;YourPlayerId;YourTownId;PlayerId_TownId_Gold_Corpses_Warlocks_Crusaders_Amazons_Corsairs_Bishops_Necromances_Architects_Peons_Temples_Barracks_Estates_Palaces;PlayerId_TownId_Gold_Corpses_Warlocks_Crusaders_Amazons_Corsairs_Bishops_Necromances_Architects_Peons_Temples_Barracks_Estates_Palaces;...` **Example input** `1;2;1;1;0_0_600_5_15_10_12_10_7_5_1_40_0_0_0_0;1_1_700_5_15_10_12_10_7_5_1_40_0_1_0_2;...` Here, you see it is the 1st round, 2nd phase, you are player 1 in town 1. You have 700 gold, 5 corpses, 15 warlocks, 10 crusaders, 12 amazons, 10 corsairs, 7 bishops, 5 necromancers, 1 architect, 40 peons, 0 temples, 1 barracks, 0 estates and 2 palaces. **Output** See gameplay. # Gameplay **All phases** *Command* `W` = WAIT *Invalid command* = WAIT **Phase 1 : Raise Taxes** Income is generated according to your population and your completed buildings : ``` +5 gold * Peons +2 gold * (Warlocks + Bishops + Necromancers) * TEMPLES +2 gold * (Crusaders + Amazons) * BARRACKS +2 gold * (Corsairs + Peons) * ESTATES +10 gold * PALACES ``` **Phase 2 : Steal Money** During this phase, you can steal money from one town by sending Corsairs. Each Corsair can steal up to **10 gold** (i.e. 12 Corsairs can steal up to 120 gold). If the target town doesn't have enough gold, your corsairs will steal everything, up to the maximum debt amount : **200 gold**. If you try to send more Corsairs than you own, the program will use all your available Corsairs. *Command syntax* : `S DestinationId Corsairs` **Phase 3 : Recruit Troops** Here you can train your peons by spending some gold. You can recruit as much units as you want, as long as you have enough peons and gold available. If you try to recruit more than you actually can, the game will recruit randomly till everything has been spent. The program respects your maximum quotas (if you try to recruits 10 crusaders and 5 amazons with only 8 peons, it will for example recruit 6 crusaders and 2 amazons, and not 8 amazons or 8 warlocks). ``` Warlock : 10 gold Crusader : 10 gold Amazon : 10 gold Corsair : 12 gold Bishop : 20 gold Necromancer : 20 gold Architect : 15 gold ``` *Command syntax* : `R Warlocks Crusaders Amazons Corsairs Bishops Necromancers Architects` **Phase 4 : Pay Wages** Salaries are debited according to your population : ``` -1 gold * (Warlock + Crusaders + Amazons) -2 gold * (Corsairs + Bishops + Necromancers + Architects) ``` **Phase 5 : Try Revolt** If your balance is negative, you loose the control of your town to the **Outlaws**. After a revolt, the gold of the town is resetted to start value : **500 gold**. The population is maintained at its current levels. **Phase 6 : Convert Soldiers** Each of your Bishops can convert 1 enemy soldier (Warlock, Crusader or Amazon) from a choosen Town for a fee of 50 gold per unit. The converted units join the forces stationned in your town. As with the recruitment, if you don't have enough gold or bishops available, the program will convert randomly while respecting the quotas. *Command syntax* : `C DestinationId Warlocks Crusaders Amazons` **Phase 7 : Attack Town** You can send an army of Warlocks, Crusaders and Amazons to conquer a Town. If you try to send more than you have, the program will send everyone. The soldiers have a **1.5 fighting bonus** following this pattern : `Mage > Range > Melee > Mage` (ie. A Warlock fighting an Amazon gains 1.5 power). Only the units in excess get this bonus (ie. A Warlock fighting a Warlock and an Amazon doesn't get this bonus). The bonus is attributed to both offense and defense. Losses are distributed randomly between the units of the victor according to looser total power (ie. Offense power: 12 vs. Defense power: 14, Defense wins and looses 12 units). The looser looses all his units. Every dead unit is added to the corpses count of the town attacked. If the offense wins, the town is captured and is now owned by the attacker. He also keeps the gold, corpses and peons that were in this town. Corsairs, Bishops, Necromancers and Architects flee in front of potential oppression. The defense gets nothing. *Command syntax* : `A DestinationId Warlocks Crusaders Amazons` **Phase 8 : Raise Corpses** Each of your necromancers can resurrect up to 5 peons by consuming corpses and spending gold. Each resurrected Peons cost 1 corpse and 20 gold. If you try to resurrect more than you can, the program will spend everything you have. *Command syntax* : `R Corpses` **Phase 9 : Move Army or Tribute** You can send units to another town. If you try to send more than you have, the program will send everyone. *Command syntax* : `M DestinationId Warlocks Crusaders Amazons Corsairs Bishops Necromancers Architects` Or, you can send gold by chartering Corsairs's ships. Each corsair can transport up to **200 gold**. If you try to send more than you have, the program will send what you have. *Command syntax* : `T DestinationId Gold` **Phase 10 : Defend against Threats** Several menaces threats to harm your town : > > * Zombies : The dead are not always as dead as they look. 10% (floored) of the corpses in your town will awake and eat brains. Each zombie will eat 1 Peon and then wander into the nothingness (Corpses of both Zombies and eaten Peons are consumed). > * Demons : Your peons need to hear sermons or they will start to invoke Dark Spirits. Each of your Bishop cover the needs of up to 50 Peons. 10% (floored) of your Heretics (Peons in excess) will spawn Demons. Demons kill 1 Peon each and return to hell (Corpses of Peons are added to town count). > * Bandits : Outlaws are dwelling in the neighbourhood. The total Outlaws population is divided equitably between towns and sent to steal wealth. Your only defense is your Corsairs patrols. Each corsair can stop up to 5 outlaws. Each outlaw not stopped steals 10 gold from your town (maximum town debt is 200 gold) > > > At least 1 town of Outlaws (100 population) is generated at the start of the game, then 1 more for each 5 players (ie. 1-4 Players : 1 Outlaws, 5-9 Players : 2 Outlaws...). Outlaws can be recognized with `id = -1` **Phase 11 : Construct Building** When reaching this phase, the construction of the buildings in your town progress according to the number of Architects. Each Architect increases the completion of a single Building by 8%. When a Building reaches 100%, it is completed and start to generate revenues in the next "Taxes" Phase. The construction queue is auto-managed (first come, first served). You can then also start the construction of other Buildings (BuildingId = Letter in parenthesis) : ``` TEMPLE (T) : 200 Gold BARRACKS (B) : 200 Gold ESTATE (E) : 200 Gold PALACE (P) : 500 Gold ``` You can start the construction of as many Building as you want, and if you don't have enough gold, Building will be ignored. The construction of your new Buildings will only start next round. *Command syntax* : `B BuildingId BuildingId BuildingId ...` **Phase 12 : Make Children** Every five round (round 5, 10, 15...), new Peons will be born and ready to fight. Each pair of Peons will make 1 Peon (ie. 23 Peons generate 11 new Peons). # Rules * Bots should not be written to beat or support specific other bots. * Writing to files is allowed. Please write to "yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed. * Your submission has 1 second to respond (per town). * Provide commands to compile and run your submissions. # Winning Winner is the one with the most towns after 100 rounds. If a player captures all towns, the game stops and he wins. If multiple players have the same amount of towns, the total population will count, then the amount of gold. # Controller [You can find the controller on github.](https://github.com/Thrax37/koth-master/) It also contains 2 samplebots, written in Java. Open it in Eclipse, place the compiled bots in the root folder and add a class to the control program (just like the samplebots). # Fights The fighting formula is something like this : For each soldier class (Warlock, Crusader, Amazon) : * Calculate balance between offense and defense (ie. Who has more of each class and how many more?) * For the excess soldiers (ie. value of positive balance), see how many "weak targets" (see Phase 7 diagram) there is. * Multiply the eligible soldiers' (ie. "weak targets" compared to "excess soldiers") fighting strength by the bonus and add the rest with a fighting strength of 1. You can try a simulator here : <http://ideone.com/ArJosE> (just change the values of the soldiers, you'll get bonuses and total strengths) Here are a few test cases : ``` Attack Defense A. Bonus D. Bonus A. Str D. Str Winner 20/10/0 12/12/12 8/0/0 0/2/10 34.0 42.0 Defense 40/0/5 12/12/12 12/0/0 0/12/0 51.0 42.0 Attack 0/60/8 10/30/2 0/10/6 8/0/0 76.0 46.0 Attack 20/20/40 90/5/5 0/15/5 40/0/0 90.0 120.0 Defense ``` # Final Results Average of 10 games. Syntax : `Player(Towns, Population, Gold)` ``` 1. Opportunist(6.4, 4165, 2895626) 2. Politician(6.4, 1048, 42542) 3. Outlaw(2.8, 1575, 349073) 4. YoungEarl(0.4, 3424, 941624) 5. Aegis(0, 0, 0) . Butter(0, 0, 0) . Commander(0, 0, 0) . Lannister(0, 0, 0) . Machiaveli(0, 0, 0) . Monarch(0, 0, 0) . Serenity(0, 0, 0) . Sehtimianer(0, 0, 0) . Sleeper(0, 0, 0) . Zealots(0, 0, 0) ``` Results of 10 games : <http://pastebin.com/GdufEYjm> Complete logs of 2 games : <http://pastebin.com/GQDZ0JdY> & <http://pastebin.com/m3UBTDuC> Well played everyone, the fight has been really close between Politician and Oppotunist. [Answer] # Opportunist, Java v2 He tries to take opportunities as they present themselves... but if none present themselves (and he is still in contention) at the end of the game then he will go all out. UDPATE: Incorporated some of durron597's ideas. Now stops recruiting bishops when able to fully convert the strongest opponent's force and instead focuses on purchasing soldiers. Also v1 had an initial handicap where the starting population spread did not add up to 100... only 98! ``` package moogiesoft; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.stream.Collectors; public class Opportunist { private static final float FIGHTING_BONUS = 1.5f; public static final int GOLD_PER_PEON = 5; public static final int GOLD_PER_TEMPLE = 2; public static final int GOLD_PER_BARRACKS = 2; public static final int GOLD_PER_ESTATE = 2; public static final int GOLD_PER_PALACE = 10; private static final int CONVERSION_COST = 50; private static final int GOLD_PER_STEAL = 10; private static final int GOLD_MAX_DEBT = 200; private static final int CORSAIR_COST = 12; private static final int BISHOP_COST = 20; private static final int ARCHITECT_COST = 15; private static final int BARRACKS_COST = 200; private static final int MILITARY_COST = 10; int round; int phase; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; List<Town> otherNonOutlawTowns; List<Town> otherOutlawTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0) { System.out.println("8 8 9 22 8 0 13 32"); } else { new Opportunist().respond(args[0].split(";")); } } private void respond(String[] args) { round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); playerID = Integer.parseInt(args[2]); thisTownID = Integer.parseInt(args[3]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); otherNonOutlawTowns= new ArrayList<>(); otherOutlawTowns= new ArrayList<>(); for (int i = 4; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); if (town.getOwnerId()!=-1) { otherNonOutlawTowns.add(town); } else { otherOutlawTowns.add(town); } } } switch (phase) { case 2: steal(); break; case 3: recruit(); break; case 6: convert(); break; case 7: attack(); break; case 8: resurrect(); break; case 9: move(); break; case 11: build(); break; default: System.out.println("W"); break; } } private void steal() { ArrayList<Town> architectSoldierSortedNonOutlawTowns = new ArrayList<>(otherNonOutlawTowns); architectSoldierSortedNonOutlawTowns.sort((a,b)->b.getArchitects()-a.getArchitects()==0?a.getSoldiers()-b.getSoldiers():b.getArchitects()-a.getArchitects()); Town targetTown =null; int targetTownStolenGold = 0; // Try to steal from the towns that have the most architects as they are the long term threat. for (Town town : architectSoldierSortedNonOutlawTowns) { if (estimateProceedsOfTheft(town,thisTown)>thisTown.calculateTaxes()) { targetTown=town; break; } } // see if we can cause revolution in any non outlaw towns or if the target proceeds of theft is not sufficent to support this town... if (targetTown==null || estimateProceedsOfTheft(targetTown,thisTown)+thisTown.calculateTaxes()<thisTown.calculateSalary()*2) { for (Town town : otherNonOutlawTowns) { if (town.getGold()-town.calculateSalary()-thisTown.getCorsairs()*GOLD_PER_STEAL<0) { int stolenGold = estimateProceedsOfTheft(town,thisTown); if (stolenGold>targetTownStolenGold) { targetTownStolenGold=stolenGold; targetTown=town; } } } } // just pick the strongest opponent if (targetTown==null && round<5) { targetTown = otherNonOutlawTowns.stream().max((a,b) -> a.getSoldiers() - b.getSoldiers()).orElse(null); } // or if the target proceeds of theft is not sufficent to support this town... select the non outlaw town with the most gold! if (targetTown==null || estimateProceedsOfTheft(targetTown,thisTown)+thisTown.calculateTaxes()<thisTown.calculateSalary()*2) { targetTown = otherNonOutlawTowns.stream().max((a,b) -> a.gold - b.gold).orElse(null); } // otherwise just pick the outlaw town with the most gold. if (targetTown==null) { targetTown = otherTowns.stream().max((a,b) -> a.gold - b.gold).orElse(null); } System.out.println("S " + targetTown.getId() + " " + thisTown.getCorsairs()); } private void recruit() { Town strongestTown=otherTowns.stream().max((a,b)->a.getSoldiers()-b.getSoldiers()).orElse(null); Town mostRepoductiveTown=otherTowns.stream().max((a,b)->a.getPeons()-b.getPeons()).orElse(null); int originalNoOfPeonsAvailableToConvert = 0; boolean recruitSoldiers=true; // last round... no point in keeping any peons... make them soldiers. if (round==100) { originalNoOfPeonsAvailableToConvert = thisTown.getPeons(); } // looks like our bishops can recruit the full force of the strongest enemy... so lets just recruit soldiers. else if (strongestTown!=null && strongestTown.getSoldiers()<thisTown.getBishops()) { originalNoOfPeonsAvailableToConvert = thisTown.getPeons()-mostRepoductiveTown.getPeons(); } // ok so we need more bishops... else if (round>5) { recruitSoldiers=false; originalNoOfPeonsAvailableToConvert = thisTown.getPeons()/10; } int amazonRecruit = 0; int crusaderRecruit = 0; int warlockRecruit = 0; int bishopRecruit = 0; int corsairRecruit = 0; int architectRecruit = 0; while (originalNoOfPeonsAvailableToConvert>0) { int noOfPeonsAvailableToConvert=originalNoOfPeonsAvailableToConvert; int recruitsLeft; do { recruitsLeft=noOfPeonsAvailableToConvert; if (recruitSoldiers) { if (noOfPeonsAvailableToConvert-->0) amazonRecruit++; if (noOfPeonsAvailableToConvert-->0) crusaderRecruit++; if (noOfPeonsAvailableToConvert-->0) warlockRecruit++; } // see if we want to recruit more bishops... else if (thisTown.getBishops()<(round<30?Math.pow(2,round/4):thisTown.getPeons()-50)) { if (noOfPeonsAvailableToConvert-->0) bishopRecruit++; } } while (noOfPeonsAvailableToConvert>0 && noOfPeonsAvailableToConvert!=recruitsLeft); noOfPeonsAvailableToConvert = noOfPeonsAvailableToConvert<0?0:noOfPeonsAvailableToConvert; Town simulatedTown = new Town(thisTown); simulatedTown.setPeons(thisTown.getPeons()-(originalNoOfPeonsAvailableToConvert-noOfPeonsAvailableToConvert)); simulatedTown.setAmazons(simulatedTown.getAmazons()+amazonRecruit); simulatedTown.setCrusaders(simulatedTown.getCrusaders()+crusaderRecruit); simulatedTown.setWarlocks(simulatedTown.getWarlocks()+warlockRecruit); simulatedTown.setBishops(simulatedTown.getWarlocks()+bishopRecruit); simulatedTown.setCorsairs(simulatedTown.getWarlocks()+corsairRecruit); simulatedTown.setArchitects(simulatedTown.getWarlocks()+architectRecruit); simulatedTown.setGold(simulatedTown.getGold()-amazonRecruit*MILITARY_COST -crusaderRecruit*MILITARY_COST -warlockRecruit*MILITARY_COST -bishopRecruit*BISHOP_COST -corsairRecruit*CORSAIR_COST -architectRecruit*ARCHITECT_COST -BARRACKS_COST // aways have enough to build a building! ); // ensure that we can afford (both now and in the future) to recruit this number of bishops... if (estimateProceedsOfTheft(thisTown) + simulatedTown.calculateTaxes()-simulatedTown.calculateSalary()>0 && simulatedTown.getGold()>simulatedTown.calculateSalary()) break; originalNoOfPeonsAvailableToConvert--; } System.out.println("R " + warlockRecruit + " " + crusaderRecruit + " " + amazonRecruit + " " + corsairRecruit + " " + bishopRecruit + " 0 " + architectRecruit); } private void convert() { int currentGold = thisTown.getGold(); int futureTaxGeneration = thisTown.calculateTaxes(); int futureSalaryCost = thisTown.calculateSalary(); int futureProceedsOfCrime = estimateProceedsOfTheft(thisTown); int futureCashFlow = futureTaxGeneration+futureProceedsOfCrime-futureSalaryCost; int goldAvailableToSpend = currentGold-=BARRACKS_COST; if (goldAvailableToSpend>CONVERSION_COST && futureCashFlow>0) { Town strongestTown = null; // sort towns by architects and then soldiers... ArrayList<Town> architectSoldierSortedNonOutlawTowns = new ArrayList<>(otherNonOutlawTowns); architectSoldierSortedNonOutlawTowns.sort((a,b)->b.getArchitects()-a.getArchitects()==0?a.getSoldiers()-b.getSoldiers():b.getArchitects()-a.getArchitects()); for (Town town :architectSoldierSortedNonOutlawTowns) { // if we could use all our bishops...then we shall target this town... if (town.getSoldiers()-thisTown.getBishops()>0) { strongestTown =town; break; } } // no town targeted... select the town with the most soldiers then. if (strongestTown == null) { strongestTown = findStrongestTownThatCanDefeatGivenTown(thisTown); } if (strongestTown == null) { // this town is already surpreme! lets see if we can be fivolous and attempt to convert anyway... if (thisTown.getGold()>thisTown.calculateSalary()*2) { strongestTown=otherNonOutlawTowns.stream().max((a,b)->a.getSoldiers()-b.getSoldiers()).orElse(null); } } // no town targeted... select the town with the most soldiers then. if (strongestTown == null) { strongestTown=otherTowns.stream().max((a,b)->a.getSoldiers()-b.getSoldiers()).orElse(null); } // we have selected a town... try to convert from it... if (strongestTown != null) { Town simulatedThisTown = new Town(thisTown); int amazonConversionCount=0; int warlockConversionCount=0; int crusaderConversionCount=0; // iterate until we are unable to pay for conversion or unable to support converted forces while(true) { futureTaxGeneration = simulatedThisTown.calculateTaxes(); futureSalaryCost = simulatedThisTown.calculateSalary(); futureCashFlow = futureTaxGeneration+futureProceedsOfCrime-futureSalaryCost; goldAvailableToSpend-=CONVERSION_COST; // see if we can afford to convert another military unit or have run out of bishops to use... if (amazonConversionCount+warlockConversionCount+crusaderConversionCount==thisTown.getBishops() || goldAvailableToSpend < 0 || futureCashFlow<0) break; // convert a amazon... if any... if (strongestTown.getAmazons()>0) { amazonConversionCount++; simulatedThisTown.setAmazons(simulatedThisTown.getAmazons()+1); strongestTown.setAmazons(strongestTown.getAmazons()-1); } // convert a crusader... if any... else if (strongestTown.getCrusaders()>0) { crusaderConversionCount++; simulatedThisTown.setCrusaders(simulatedThisTown.getCrusaders()+1); strongestTown.setCrusaders(strongestTown.getCrusaders()-1); } // convert a warlock... if any... else if (strongestTown.getWarlocks()>0) { warlockConversionCount++; simulatedThisTown.setWarlocks(simulatedThisTown.getWarlocks()+1); strongestTown.setWarlocks(strongestTown.getWarlocks()-1); } // no more units to convert from the targeted town... else { break; } } System.out.println("C " + strongestTown.getId() + " " + warlockConversionCount + " " + crusaderConversionCount + " " + amazonConversionCount); return; } } System.out.println("W"); } private void attack() { // nearing end game.. lets just attack every thing blindly :P if (round>=99) { for (Town town : towns) { if (!town.isMine()) { Town simulatedThisTown = new Town(thisTown); Town simulatedOtherTown = new Town(town); // attempt to attack the opponent with all our soldiers. if (battle(simulatedThisTown,simulatedOtherTown,thisTown.getWarlocks(),thisTown.getCrusaders(),thisTown.getAmazons())) { System.out.println("A "+ town.getId()+ " " + thisTown.getWarlocks()+ " " + thisTown.getCrusaders()+ " " + thisTown.getAmazons() ); return; } } } } // we should be in a good position... lets try to take over strongest opponent... if (round>32) { Town strongestTown = otherTowns.stream().max((a,b)->a.getSoldiers()-b.getSoldiers()).orElse(null); Town simulatedThisTown = new Town(thisTown); Town simulatedStrongestTown = new Town(strongestTown); int warlockRegiment = thisTown.getWarlocks(); int crusaderRegiment = thisTown.getCrusaders(); int amazonRegiment = thisTown.getAmazons(); List<Town> remainderNonOutLawTowns = new ArrayList<Town>(otherNonOutlawTowns); remainderNonOutLawTowns.remove(strongestTown); Town nextStrongestTown = remainderNonOutLawTowns.stream().max((a,b)->a.getSoldiers()-b.getSoldiers()).orElse(null); boolean firstLoop=true; // attempt to attack the strongest opponent with the least number of soldiers possible and still be in a position to likely not succumb to the next strongest opponent. while (nextStrongestTown!=null && warlockRegiment+crusaderRegiment+amazonRegiment>0 && battle(simulatedThisTown,simulatedStrongestTown,warlockRegiment,crusaderRegiment,amazonRegiment)) { Town simulatedThisTownAfterWinning = new Town(simulatedThisTown); Town simulatedNextStrongestTown = new Town(nextStrongestTown); if (nextStrongestTown==null || battle(simulatedNextStrongestTown,simulatedThisTownAfterWinning, simulatedNextStrongestTown.getWarlocks()*2/3, simulatedNextStrongestTown.getCrusaders()*2/3, simulatedNextStrongestTown.getAmazons()*2/3)) { if (firstLoop) break; System.out.println("A "+ strongestTown.getId()+ " " + warlockRegiment+ " " + crusaderRegiment+ " " + amazonRegiment ); return; } firstLoop=false; warlockRegiment-=warlockRegiment>0?1:0; crusaderRegiment-=crusaderRegiment>0?1:0; amazonRegiment-=amazonRegiment>0?1:0; simulatedThisTown = new Town(thisTown); simulatedStrongestTown = new Town(strongestTown); } // it looks like we are in a power deadlock with one other town... lets see if going all out will make us the victor.... if (otherNonOutlawTowns.size()==1) { simulatedThisTown = new Town(thisTown); Town simulatedRemainingTown = new Town(otherNonOutlawTowns.get(0)); if (battle(simulatedThisTown,simulatedRemainingTown,thisTown.getWarlocks(),thisTown.getCrusaders(),thisTown.getAmazons())) { System.out.println("A "+ simulatedRemainingTown.getId()+ " " + thisTown.getWarlocks()+ " " + thisTown.getCrusaders()+ " " + thisTown.getAmazons() ); return; } } } System.out.println("W"); } private void move() { // give half our funds to the most needy town... List<Town> poorMyTowns = myTowns.stream().filter(a->a.calculateTaxes()-a.calculateSalary()<0).collect(Collectors.toList()); if (poorMyTowns.size()>0) { Town poorTown = poorMyTowns.get(new Random().nextInt(poorMyTowns.size())); if (poorTown.getId() != thisTownID) { System.out.println("T "+poorTown.getId()+ " "+ thisTown.getGold()/2); return; } } System.out.println("W"); } private void resurrect() { // zombie shmozies! System.out.println("W"); } private void build() { // endevour to always build a barracks or estate (which ever is more lucrative) int currentGold = thisTown.getGold(); int futureTaxGeneration = thisTown.calculateTaxes(); int futureSalaryCost = thisTown.calculateSalary(); int futureProceedsOfCrime = estimateProceedsOfTheft(thisTown); int futureCashFlow = futureTaxGeneration+futureProceedsOfCrime-futureSalaryCost; int goldAvailableToSpend = currentGold; if (goldAvailableToSpend>BARRACKS_COST && futureCashFlow>0) { if (thisTown.getAmazons()+thisTown.getCrusaders()>thisTown.getCorsairs()+thisTown.getPeons()) { System.out.println("B B"); return; } else { System.out.println("B E"); return; } } System.out.println("W"); } private class Town { private int ownerId =-1; private int id = -1; private int gold; private int corpses; private int warlocks; private int crusaders; private int amazons; private int corsairs; private int bishops; private int necromancers; private int architects; private int peons; private int temples; private int barracks; private int estates; private int palaces; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); warlocks = Integer.parseInt(args[4]); crusaders = Integer.parseInt(args[5]); amazons = Integer.parseInt(args[6]); corsairs = Integer.parseInt(args[7]); bishops = Integer.parseInt(args[8]); necromancers = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); peons = Integer.parseInt(args[11]); temples = Integer.parseInt(args[12]); barracks = Integer.parseInt(args[13]); estates = Integer.parseInt(args[14]); palaces = Integer.parseInt(args[15]); } //Copy constructor public Town(Town source) { this.ownerId=source.ownerId; this.id=source.id; this.gold=source.gold; this.corpses=source.corpses; this.warlocks=source.warlocks; this.crusaders=source.crusaders; this.amazons=source.amazons; this.corsairs=source.corsairs; this.bishops=source.bishops; this.necromancers=source.necromancers; this.architects=source.architects; this.peons=source.peons; this.temples = source.temples; this.barracks = source.barracks; this.estates = source.estates; this.palaces = source.palaces; } public void setOwnerId(int ownerId) { this.ownerId = ownerId; } public void setGold(int gold) { this.gold = gold; } public void setCorpses(int corpses) { this.corpses = corpses; } public void setWarlocks(int warlocks) { this.warlocks = warlocks; } public void setCrusaders(int crusaders) { this.crusaders = crusaders; } public void setAmazons(int amazons) { this.amazons = amazons; } public void setCorsairs(int corsairs) { this.corsairs = corsairs; } public void setBishops(int bishops) { this.bishops = bishops; } public void setNecromancers(int necromancers) { this.necromancers = necromancers; } public void setArchitects(int architects) { this.architects = architects; } public void setPeons(int peons) { this.peons = peons; } public int getTemples() { return temples; } public int getBarracks() { return barracks; } public int getEstates() { return estates; } public int getPalaces() { return palaces; } public int getOwnerId() { return ownerId; } public int getId() { return id; } public int getGold() { return gold; } public int getCorpses() { return corpses; } public int getWarlocks() { return warlocks; } public int getCrusaders() { return crusaders; } public int getAmazons() { return amazons; } public int getCorsairs() { return corsairs; } public int getBishops() { return bishops; } public int getNecromancers() { return necromancers; } public int getArchitects() { return architects; } public int getPeons() { return peons; } public int getSoldiers() { return getWarlocks() + getCrusaders() + getAmazons(); } public boolean isMine(){ return getOwnerId() == playerID; } public boolean isThisTown(){ return id == thisTownID; } public int calculateSalary() { return (getWarlocks() + getCrusaders() + getAmazons()) + 2*(getCorsairs()+getBishops()+ getArchitects()+ getNecromancers()); } // algorithm taken from Game.java public int calculateTaxes() { int taxes = 0; taxes += (getPeons() * GOLD_PER_PEON); taxes += ((getWarlocks() + getBishops() + getNecromancers()) * (getTemples() * GOLD_PER_TEMPLE)); taxes += ((getCrusaders() + getAmazons()) * (getBarracks() * GOLD_PER_BARRACKS)); taxes += ((getPeons() + getCorsairs()) * (getEstates() * GOLD_PER_ESTATE)); taxes += (getPalaces() * GOLD_PER_PALACE); return taxes; } } // algorithm taken from Game.java private boolean battle(Town attackingTown, Town defendingTown, int attackingWarlocks, int attackingCrusaders, int attackingAmazons) { int sourceWarlocks = Math.min(attackingTown.getWarlocks(), Math.max(0, attackingWarlocks)); int sourceCrusaders = Math.min(attackingTown.getCrusaders(), Math.max(0, attackingCrusaders)); int sourceAmazons = Math.min(attackingTown.getAmazons(), Math.max(0, attackingAmazons)); int destinationWarlocks = defendingTown.getWarlocks(); int destinationCrusaders = defendingTown.getCrusaders(); int destinationAmazons = defendingTown.getAmazons(); int sourceWarlocksBalance = Math.max(0, sourceWarlocks - destinationWarlocks); int sourceWarlocksBonus = Math.min(sourceWarlocksBalance, destinationAmazons); float sourceWarlocksStrength = (sourceWarlocks - sourceWarlocksBonus + (sourceWarlocksBonus * FIGHTING_BONUS)); int sourceCrusadersBalance = Math.max(0, sourceCrusaders - destinationCrusaders); int sourceCrusadersBonus = Math.min(sourceCrusadersBalance, destinationWarlocks); float sourceCrusadersStrength = (sourceCrusaders - sourceCrusadersBonus + (sourceCrusadersBonus * FIGHTING_BONUS)); int sourceAmazonsBalance = Math.max(0, sourceAmazons - destinationAmazons); int sourceAmazonsBonus = Math.min(sourceAmazonsBalance, destinationCrusaders); float sourceAmazonsStrength = (sourceAmazons - sourceAmazonsBonus + (sourceAmazonsBonus * FIGHTING_BONUS)); float sourceTotalStrength = sourceWarlocksStrength + sourceCrusadersStrength + sourceAmazonsStrength; int destinationWarlocksBalance = Math.max(0, destinationWarlocks - sourceWarlocks); int destinationWarlocksBonus = Math.min(destinationWarlocksBalance, sourceAmazons); float destinationWarlocksStrength = (destinationWarlocks - destinationWarlocksBonus + (destinationWarlocksBonus * FIGHTING_BONUS)); int destinationCrusadersBalance = Math.max(0, destinationCrusaders - sourceCrusaders); int destinationCrusadersBonus = Math.min(destinationCrusadersBalance, sourceWarlocks); float destinationCrusadersStrength = (destinationCrusaders - destinationCrusadersBonus + (destinationCrusadersBonus * FIGHTING_BONUS)); int destinationAmazonsBalance = Math.max(0, destinationAmazons - sourceAmazons); int destinationAmazonsBonus = Math.min(destinationAmazonsBalance, sourceCrusaders); float destinationAmazonsStrength = (destinationAmazons - destinationAmazonsBonus + (destinationAmazonsBonus * FIGHTING_BONUS)); float destinationTotalStrength = destinationWarlocksStrength + destinationCrusadersStrength + destinationAmazonsStrength; if (sourceTotalStrength > destinationTotalStrength) { RandomNumberGenerator rand = new RandomNumberGenerator(); int[] limits = new int[3]; limits[0] = sourceWarlocks; limits[1] = sourceCrusaders; limits[2] = sourceAmazons; int[] losses = rand.genNumberWithLimits((int) Math.ceil(destinationTotalStrength), limits); attackingTown.setWarlocks(attackingTown.getWarlocks() - sourceWarlocks); attackingTown.setCrusaders(attackingTown.getCrusaders() - sourceCrusaders); attackingTown.setAmazons(attackingTown.getAmazons() - sourceAmazons); defendingTown.setWarlocks(sourceWarlocks - losses[0]); defendingTown.setCrusaders(sourceCrusaders - losses[1]); defendingTown.setAmazons(sourceAmazons - losses[2]); defendingTown.setCorsairs(0); defendingTown.setBishops(0); defendingTown.setNecromancers(0); defendingTown.setArchitects(0); defendingTown.setCorpses(defendingTown.getCorpses() + destinationWarlocks + destinationCrusaders + destinationAmazons + losses[0] + losses[1] + losses[2]); defendingTown.setOwnerId(attackingTown.getOwnerId()); return true; } else if (sourceTotalStrength <= destinationTotalStrength) { RandomNumberGenerator rand = new RandomNumberGenerator(); int[] limits = new int[3]; limits[0] = destinationWarlocks; limits[1] = destinationCrusaders; limits[2] = destinationAmazons; int[] losses = rand.genNumberWithLimits((int) Math.ceil(sourceTotalStrength), limits); attackingTown.setWarlocks(attackingTown.getWarlocks() - sourceWarlocks); attackingTown.setCrusaders(attackingTown.getCrusaders() - sourceCrusaders); attackingTown.setAmazons(attackingTown.getAmazons() - sourceAmazons); defendingTown.setWarlocks(destinationWarlocks - losses[0]); defendingTown.setCrusaders(destinationCrusaders - losses[1]); defendingTown.setAmazons(destinationAmazons - losses[2]); defendingTown.setCorpses(defendingTown.getCorpses() + sourceWarlocks + sourceCrusaders + sourceAmazons + losses[0] + losses[1] + losses[2]); } return false; } /** * Taken from Game.java * * Generate N random numbers when their SUM is known * * @author Deepak Azad */ public class RandomNumberGenerator { public int[] genNumbers(int n, int sum){ int[] nums = new int[n]; int upperbound = Long.valueOf(Math.round(sum*1.0/n)).intValue(); int offset = Long.valueOf(Math.round(0.5*upperbound)).intValue(); int cursum = 0; Random random = new Random(new Random().nextInt()); for(int i=0 ; i < n ; i++){ int rand = random.nextInt(upperbound) + offset; if( cursum + rand > sum || i == n - 1) { rand = sum - cursum; } cursum += rand; nums[i]=rand; if(cursum == sum){ break; } } return nums; } public int[] genNumberWithLimits(int sum, int[] limits) { int n = limits.length; int[] nums = new int[n]; int total = 0; for (int l : limits) { total += l; } if (total <= sum) return limits; Random random = new Random(new Random().nextInt()); while (sum > 0) { int x = random.nextInt(n); if (nums[x] < limits[x]) { nums[x] += 1; sum--; } } return nums; } } // algorithm taken from Game.java private int estimateProceedsOfTheft(Town theivingTown) { int bestTownToTheiveProceedsAmount = -1; for (Town town : towns) { int goldStolen = estimateProceedsOfTheft(town,theivingTown); if (goldStolen > bestTownToTheiveProceedsAmount) { bestTownToTheiveProceedsAmount=goldStolen; } } return bestTownToTheiveProceedsAmount; } // algorithm taken from Game.java private int estimateProceedsOfTheft(Town victimTown,Town theivingTown) { int goldStolen = 0; if (victimTown.getOwnerId()!= theivingTown.getOwnerId()) { int goldReserve = victimTown.getGold() + GOLD_MAX_DEBT > 0 ? victimTown.getGold() + GOLD_MAX_DEBT : GOLD_MAX_DEBT - Math.abs(victimTown.getGold()); int goldToSteal = theivingTown.getCorsairs() * GOLD_PER_STEAL; goldStolen = Math.min(goldReserve, goldToSteal); } return goldStolen; } // exactly as the method name states :) private Town findStrongestTownThatCanDefeatGivenTown(Town defendingTown) { int strongestSurvivingForce=-1; Town strongestTown=null; for (Town town : towns) { if (town.getOwnerId()!=defendingTown.getOwnerId() && town.getOwnerId()!=-1) { Town simulatedThisTown = new Town(defendingTown); Town simulatedOtherTown = new Town(town); // check to see if the other town could defeat this town if (battle(simulatedOtherTown,simulatedThisTown,simulatedOtherTown.getWarlocks(), simulatedOtherTown.getCrusaders(), simulatedOtherTown.getAmazons())) { //and if so, if it is the most overwhelming win, then that town is the target of conversion. int survivingForce=simulatedOtherTown.getAmazons()+simulatedOtherTown.getCrusaders()+simulatedOtherTown.getWarlocks()+ simulatedThisTown.getAmazons()+simulatedThisTown.getCrusaders()+simulatedThisTown.getWarlocks(); if (survivingForce>strongestSurvivingForce) { strongestSurvivingForce=survivingForce; strongestTown = town; } } } } return strongestTown; } } ``` To run: 1. Place into moogiesoft directory 2. In parent directory: java moogiesoft.Opportunist [Answer] # Aegis, Java Aegis tries to play it safe and wait for other players to fight among themselves while building a nice residential block, full of luxurious estates. Since gold is a precious resource, Aegis recruits enough Corsairs to steal from its neighbours and protect its hard-earned money. ``` import java.util.ArrayList; import java.util.List; public class Aegis { int round; int phase; int playerID; int thisTownID; final int PEONS_PER_BISHOPS = 50; final int GOLD_STOLEN_PER_CORSAIR = 10; final int AVERAGE_COST_PER_UNIT = 2; final int GOLD_SAFETY = 100; final int PEONS_SAFETY = 20; final int COST_CORSAIR = 12; final int COST_SOLDIER = 10; final int COST_ESTATE = 200; final int MAX_CORSAIRS = 30; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0) { System.out.println("10 10 10 10 1 1 3 55"); } else { new Aegis().protect(args[0].split(";")); } } private void protect(String[] args) { round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); playerID = Integer.parseInt(args[2]); thisTownID = Integer.parseInt(args[3]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 4; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } switch (phase) { case 2: steal(); break; case 3: recruit(); break; case 6: convert(); break; case 7: attack(); break; case 8: move(); break; case 9: resurrect(); break; case 11: build(); break; } } private void steal() { Town richestTown = otherTowns.stream().max((a,b) -> a.gold - b.gold).get(); System.out.println("S " + richestTown.getId() + " " + thisTown.getCorsairs()); } private void recruit() { Town richestTown = otherTowns.stream().max((a,b) -> a.gold - b.gold).get(); Town soldierTown = otherTowns.stream().max((a,b) -> (a.amazons + a.warlocks + a.crusaders) - (b.amazons + b.warlocks + b.crusaders)).get(); int requiredBishops = Math.max(0, Math.floorDiv(thisTown.getPeons(), PEONS_PER_BISHOPS) - thisTown.getBishops()); int requiredNecromancers = Math.max(0, 1 - thisTown.getNecromancers()); int requiredArchitects = Math.max(0, 5 - thisTown.getArchitects()); int requiredCorsairs = Math.max(0, Math.min(MAX_CORSAIRS - thisTown.getCorsairs(), Math.floorDiv(richestTown.getGold(), GOLD_STOLEN_PER_CORSAIR))); int goldAvailable = thisTown.getGold() - (AVERAGE_COST_PER_UNIT * thisTown.getUnits()) - GOLD_SAFETY; int peonsAvailable = Math.max(0, thisTown.getPeons() - PEONS_SAFETY); int recruitedCorsairs = 0; int[] recruits = new int[3]; int i = 0; while (peonsAvailable >= 5 && goldAvailable >= 50 && recruitedCorsairs < requiredCorsairs) { recruitedCorsairs++; peonsAvailable--; goldAvailable-=COST_CORSAIR; } while (peonsAvailable >= 5 && goldAvailable >= 50) { if (soldierTown.getSoldiers() > thisTown.getSoldiers()) { i = (i >= recruits.length - 1 ? 0 : i+1); recruits[i]++; peonsAvailable--; goldAvailable-=COST_SOLDIER; } else { break; } } if (recruits[0] + recruits[1] + recruits[2] + recruitedCorsairs + requiredBishops + requiredNecromancers + requiredArchitects > 0) { System.out.println("R " + recruits[0] + " " + recruits[1] + " " + recruits[2] + " " + recruitedCorsairs + " " + requiredBishops + " " + requiredNecromancers + " " + requiredArchitects); } else { System.out.println("W"); } } private void convert() { System.out.print("W"); } private void attack() { if (this.countOtherPlayers() <= 1) { Town richestTown = otherTowns.stream().max((a,b) -> a.getGold() - b.getGold()).get(); int neededWarlocks = thisTown.getWarlocks() - richestTown.getWarlocks(); int neededCrusaders = thisTown.getCrusaders() - richestTown.getCrusaders(); int neededAmazons = thisTown.getAmazons() - richestTown.getAmazons() ; if (neededWarlocks > 0 && neededCrusaders > 0 && neededAmazons > 0) { System.out.println("A " + richestTown.getId() + " " + (richestTown.getWarlocks() + 1) + " " + (richestTown.getCrusaders() + 1) + " " + (richestTown.getAmazons() + 1)); } else { System.out.println("W"); } } else { System.out.println("W"); } } private void move() { for (Town town : myTowns) { int goldBalance = town.getGold() - (AVERAGE_COST_PER_UNIT * thisTown.getUnits()) + GOLD_SAFETY; if (goldBalance <= 0) { System.out.println("T " + town.getId() + " " + (-goldBalance + GOLD_SAFETY)); break; } } System.out.println("W"); } private void resurrect() { if (thisTown.getCorpses() > 0) { int corpses = Math.min(5, thisTown.getCorpses()); System.out.print("R " + corpses); } else { System.out.print("W"); } } private void build() { int goldAvailable = thisTown.getGold() - (AVERAGE_COST_PER_UNIT * thisTown.getUnits()) - GOLD_SAFETY; if (goldAvailable >= (COST_ESTATE + 50)) { System.out.println("B E"); } else { System.out.println("W"); } } public int countOtherPlayers() { List<Integer>players = new ArrayList<>(); for (Town town : otherTowns) { if (!players.contains(town.getOwnerId()) && town.getOwnerId() >= 0) players.add(town.getOwnerId()); } return players.size(); } private class Town { private final int ownerId; private final int id; private final int gold; private final int corpses; private final int warlocks; private final int crusaders; private final int amazons; private final int corsairs; private final int bishops; private final int necromancers; private final int architects; private final int peons; private final int temples; private final int barracks; private final int estates; private final int palaces; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); warlocks = Integer.parseInt(args[4]); crusaders = Integer.parseInt(args[5]); amazons = Integer.parseInt(args[6]); corsairs = Integer.parseInt(args[7]); bishops = Integer.parseInt(args[8]); necromancers = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); peons = Integer.parseInt(args[11]); String[] args2 = args[12].split("-"); temples = Integer.parseInt(args2[0]); barracks = Integer.parseInt(args2[1]); estates = Integer.parseInt(args2[2]); palaces = Integer.parseInt(args2[3]); } public int getOwnerId() { return ownerId; } public int getId() { return id; } public int getGold() { return gold; } public int getCorpses() { return corpses; } public int getWarlocks() { return warlocks; } public int getCrusaders() { return crusaders; } public int getAmazons() { return amazons; } public int getCorsairs() { return corsairs; } public int getBishops() { return bishops; } public int getNecromancers() { return necromancers; } public int getArchitects() { return architects; } public int getPeons() { return peons; } public int getTemples() { return temples; } public int getBarracks() { return barracks; } public int getEstates() { return estates; } public int getPalaces() { return palaces; } public int getBuildings() { return getTemples() + getBarracks() + getEstates() + getPalaces(); } public int getSoldiers() { return getWarlocks() + getCrusaders() + getAmazons(); } public int getUnits() { return getSoldiers() + getCorsairs() + getBishops() + getNecromancers() + getArchitects(); } public int getCitizens() { return getUnits() + getPeons(); } public boolean isMine(){ return getOwnerId() == playerID; } public boolean isThisTown(){ return id == thisTownID; } } } ``` Compile with `javac Aegis.java` Run with `java Aegis` [Answer] # The Young Earl, Python 2 version 3.1 ### Update: The Young Earl's mother will put up with his war mongering no longer. He is to engage in town building instead. The Earl now has economic advisors and a lot of spreadsheets. He wishes for a simpler life were he can just chase the chamber maids. ``` import sys, re from random import * from operator import itemgetter (PLAYER, TOWN, GOLD, CORPSES, WARLOCKS, CRUSADERS, AMAZONS, CORSAIRS, BISHOPS, NECROMANCERS, ARCHITECTS, PEONS, TEMPLES, BARRACKS, ESTATES, PALACES) = range(16) OUTLAW = -1 def seqalloc(seq, num): outseq = [] totalw = float(sum(seq)) for weight in seq: share = int(round(num * weight / totalw)) if weight else 0 outseq.append(share) totalw -= weight num -= share return outseq def getstrength(t): return sum(t[WARLOCKS:AMAZONS+1]) def calcprofit(t): return t[GOLD] + 20*t[PEONS] + 200*t[ESTATES] def getincome(t): return 5*t[PEONS] + 2*(t[PEONS]+t[CORSAIRS])*t[ESTATES] if len(sys.argv) < 2: print 5,20,5, 12,4,1,13, 40 else: try: output = 'W' parts = sys.argv[1].split(';') turn, phase, me, thistown = [int(parts.pop(0)) for i in range(4)] # Catagorize towns: towns = [map(int, re.split(r'_', town)) for town in parts] outlaws = [t for t in towns if t[PLAYER] == OUTLAW] mytowns = [t for t in towns if t[PLAYER] == me] enemy = [t for t in towns if t[PLAYER] not in (me, OUTLAW)] # Situation: here = [t for t in mytowns if t[TOWN] == thistown][0] strength = sorted(enemy, key=getstrength) strengthoutlaw = sorted(outlaws, key=getstrength) profenemy = sorted(enemy, key=calcprofit) profoutlaw = sorted(outlaws, key=calcprofit) rich = outlaws + sorted(enemy, key=itemgetter(GOLD)) bandits = sum(sum(t[4:12]) for t in outlaws) # Planning: siblings = [t for t in mytowns if t != here] bodytowns = [t for t in mytowns if t[CORPSES] > 0] myincome = getincome(here) isrich = all(t[GOLD] < here[GOLD]*1.5 for t in enemy) wages = getstrength(here) + sum(here[CORSAIRS:ARCHITECTS+1]) * 2 newpeons = (turn % 5 == 1) if turn > 1 else 0 theft = 10 * max(0, bandits/len(enemy+mytowns) - here[CORSAIRS]*5) if phase == 2: output = 'S %u %u' % (rich[-1][TOWN], here[CORSAIRS]) elif phase == 3: cash = max(0, here[GOLD] - wages) if theft < myincome: if here[ARCHITECTS] and cash > 200: cash -= 200 cash = max(0, cash - 150) # must haves: cors = (bandits/len(mytowns+enemy)) / 5 + 1 cors = cors if cors < 25 else 0 bish = here[PEONS]/50 + 1 necro = here[CORPSES]/20 + 1 require = [cors, bish, necro, 0] need = [0]*3 + [max(0, p-q) for p,q in zip(require, here[7:11])] if sum(need)*22 < cash: train = need else: train = seqalloc(need, cash/22) now = [p+q for p,q in zip(here[4:11], train)] cash -= sum(p*q for p,q in zip(train[3:], [12,20,20,15])) cash -= sum(train)*2 # new wages # nice to have: raises = min(here[CORPSES]/4+1, now[5]*5, cash/20) cash -= raises * 20 archreq = max(0, 13 - here[ARCHITECTS]) if theft < myincome and archreq * 17 < cash: train[6] += archreq cash -= archreq * 17 if cash > 200: cash -= 200 newbish = max(0, cash/50 - now[4]) if newpeons: bishreq = (myincome - 200 - wages)/50 * 12/10 newbish += max(0, bishreq - (now[4]+newbish)) newbish = min(newbish, cash/22) train[4] += newbish cash -= newbish * 22 if sum(train) > 0: output = 'R %u %u %u %u %u %u %u' % tuple(train) elif phase == 6: cash = here[GOLD] if theft < myincome: if here[ARCHITECTS] and cash > 200: cash -= 200 cash = max(0, cash - 150) raises = min(here[CORPSES]/4+1, here[NECROMANCERS]*5, cash/20) cash -= raises * 20 count = min(cash/50, here[BISHOPS]) if count > 0: target = (strengthoutlaw + strength)[-1] count = min(count, sum(target[4:7])) ftrs = seqalloc(target[4:7], count) output = 'C %u %u %u %u' % tuple([target[TOWN]] + ftrs) elif phase == 7: force = getstrength(here) target = None if not enemy or force > getstrength(strength[-1])*2: for town in profenemy[::-1]+profoutlaw[::-1]: if force > getstrength(town)*4: target = town break if target: raiders = seqalloc(here[4:7], force/2) output = 'A %u %u %u %u' % tuple([target[TOWN]] + raiders) elif phase == 8: cash = here[GOLD] if theft < myincome: if here[ARCHITECTS] and cash > 200: cash -= 200 cash = max(0, cash - 150) raises = min(here[CORPSES]/4+1, here[NECROMANCERS]*5, cash/20) if raises > 0: output = 'R %s' % raises elif phase == 9: if here[CORPSES] == 0 and bodytowns: dest = max(bodytowns, key=itemgetter(CORPSES)) necro = min(here[NECROMANCERS], dest[CORPSES]/20+1) output = 'M %u 0 0 0 0 0 %u 0' % (dest[TOWN], necro) elif siblings and theft < 100 and isrich: given = min(here[GOLD]/33, here[CORSAIRS]*200) dest = max(siblings, key=getincome) output = 'T %u %u' % (dest[TOWN], given) elif phase == 11: if here[ARCHITECTS] and here[GOLD] >= 200: output = 'B E' except: pass print output ``` ### Performance Analysis In the game competition, the latest Earl did well. In 2 games of the 10, he managed to win against the player towns but then froze up when it was time to conquer the bandit towns. I have fixed that bug - I never thought he would get that far ;-). In hindsight, I should have downloaded the controller and tested the Earl. Congratulations to @Moogie and @TheBestOne for the best entries. It is a shame only one can win. They are both very good. If there are more games, I would like to see how the repaired Earl survives against the two champions. I hope @Thrax will have some time free for this. [Answer] ## TheLannisters (Java) I choose this name because this submission gets rich as hell. Also, the sentence `TheLannisters gave birth to 30 children` sounds funny :D **Edit:** It now waits with attacks for a long time and annoys players by stealing away their soldiers. It can also recruit every type of unit. ``` import java.util.ArrayList; import java.util.List; public class TheLannisters { private static final int COST_PER_SOLDIER = 11; private static final int COST_PER_CORSAIR = 14; private static final int COST_PER_BISHOP = 22; private static final int COST_PER_CONVERTION = 50; private final int MIN_PEONS; private final int phase; private final int myId; private final int round; private final List<Town> myTowns = new ArrayList<>(); private final List<Town> enemyTowns = new ArrayList<>(); private final List<Town> enemyPlayerTowns = new ArrayList<>(); private final List<Town> outlawTowns = new ArrayList<>(); private Town thisTown = null; public static void main(String[] args){ if (args.length == 0) { System.out.println("12 14 10 11 3 5 5 40"); } else { new TheLannisters(args[0].split(";")).command(); } } public TheLannisters(String[] args) { round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); myId = Integer.parseInt(args[2]); MIN_PEONS = 40 + round/2; int thisTownId = Integer.parseInt(args[3]); boolean hasAlreadyCommanded = false; for (int i = 4; i < args.length; i++){ Town town = new Town(args[i], hasAlreadyCommanded); if (town.isMine()){ myTowns.add(town); if (town.id == thisTownId){ thisTown = town; hasAlreadyCommanded = true; } } else { enemyTowns.add(town); if (town.isOutlawTown()) { outlawTowns.add(town); } else { enemyPlayerTowns.add(town); } } } } private void command() { switch (phase) { case 2: steal(); break; case 3: recruit(); break; case 6: convert(); break; case 7: attack(); break; case 8: resurrect(); break; case 9: move(); break; case 11: build(); break; } } private void steal() { int goldToSteal = thisTown.corsairs * 10; int mostSoldiers = -1; Town richestTown = null; for (Town town : enemyPlayerTowns) { if (town.getSoldiers() > mostSoldiers && town.gold >= goldToSteal) { richestTown = town; mostSoldiers = town.getSoldiers(); } } if (richestTown != null) { printCommand("S " + richestTown.id + " " + thisTown.corsairs); } // player with most gold (could be an outlaw) int mostGold = -1; for (Town town : enemyTowns) { if (town.gold > mostGold) { richestTown = town; mostGold = town.gold; } } printCommand("S " + richestTown.id + " " + thisTown.corsairs); } private void recruit() { int freePeons = (thisTown.peons - MIN_PEONS); if (!thisTown.isWeak()) { freePeons /= 2; } int freeGold = thisTown.gold - thisTown.getSoldiers() - thisTown.getCitizens() * 2; if (freePeons <= 0 || freeGold < COST_PER_SOLDIER) { printCommand("W"); } int bishops = 0; if ((thisTown.bishops * 50 < thisTown.peons || thisTown.gold > 500) && freeGold >= COST_PER_BISHOP) { bishops = 1; freeGold -= COST_PER_BISHOP; freePeons--; } int necromancers = 0; if (thisTown.necromancers == 0 && freeGold >= COST_PER_BISHOP) { necromancers = 1; freeGold -= COST_PER_BISHOP; freePeons--; } int corsairs = 0; if (thisTown.getsRobbed() && freeGold >= COST_PER_CORSAIR) { corsairs = 1; freeGold -= COST_PER_CORSAIR; freePeons--; } int architects = 0; if (thisTown.architects == 0 && freeGold > 500) { architects = 1; freeGold -= COST_PER_BISHOP; freePeons--; } int producableSoldiers = Math.min(freePeons, freeGold / COST_PER_SOLDIER); int soldierPerType = producableSoldiers / 3; int crusaders = soldierPerType + (producableSoldiers % 3); printCommand("R " + soldierPerType + " " + crusaders + " " + soldierPerType + " " + corsairs + " " + bishops + " " + necromancers + " " + architects); } private void convert() { int freeGold = 0; if (thisTown.isWeak() || thisTown.corpses <= 0) { freeGold = thisTown.gold - 300; } if (freeGold < COST_PER_CONVERTION || thisTown.bishops == 0 || (round < 2 && thisTown.getSoldiers() > 35)) { printCommand("W"); } int soldiersToConvert = freeGold / COST_PER_CONVERTION; int soldiersPerType = soldiersToConvert / 3; int amazons = soldiersPerType + (soldiersToConvert % 3); Town destination = null; int mostSoldiers = -1; if (destination == null) { for (Town town : enemyPlayerTowns) { if (town.getSoldiers() > mostSoldiers) { destination = town; mostSoldiers = town.getSoldiers(); } } } if (destination == null) { destination = outlawTowns.get(0); } printCommand("C " + destination.id + " " + soldiersPerType + " " + soldiersPerType + " " + amazons); } private void attack() { int leastSoldiers = Integer.MAX_VALUE; Town destination = null; if (thisTown.isWeak() || round < 21) { printCommand("W"); } for (Town town : enemyTowns) { if (town.getSoldiers() < leastSoldiers) { destination = town; leastSoldiers = town.getSoldiers(); } } boolean attackTogether = false; for (Town town : myTowns) { if (!town.hasAlreadyCommanded && !town.isWeak() && !town.equals(thisTown)) { attackTogether = true; } } if (thisTown.getSoldiers() / 3.5 > destination.getSoldiers() || (attackTogether && thisTown.getSoldiers() / 2 >= destination.getSoldiers())) { int warlocks = thisTown.warlocks/2; int crusaders = thisTown.crusaders/2; int amazons = thisTown.amazons/2; while (warlocks + crusaders + amazons > (destination.getSoldiers() + 3) * 3) { warlocks = Math.max(0, --warlocks); crusaders = Math.max(0, --crusaders); amazons = Math.max(0, --amazons); } if (enemyPlayerTowns.size() == 0) { // dont send too many soldiers => otherwise they revolt printCommand("A " + destination.id + " " + (destination.warlocks + 2) + " " + (destination.crusaders + 2) + " " + (destination.amazons + 2)); } printCommand("A " + destination.id + " " + warlocks + " " + crusaders + " " + amazons); } else { printCommand("W"); } } private void resurrect() { printCommand("R 999"); } private void move() { if (myTowns.size() == 1 || thisTown.corpses > 10) { printCommand("W"); } int leastGold = thisTown.gold; Town destination = null; for (Town town : myTowns) { if (town.gold < leastGold) { leastGold = town.gold; destination = town; } } if (destination != null && (thisTown.hasMostGold() || (thisTown.gold > 100 && destination.gold - destination.getSoldiers() - destination.getCitizens() * 2 < 300) || (thisTown.gold > 300 && destination.getsRobbed()))) { printCommand("T " + destination.id + " " + Math.max(thisTown.gold / 10, 30)); } for (Town town : myTowns) { if (town.isWeak()) { printCommand("M " + town.id + " " + (thisTown.warlocks / 4) + " " + (thisTown.crusaders / 4) + " " + (thisTown.amazons / 4) + " 0 0 0 0"); } } printCommand("W"); } private void build() { if (thisTown.gold >= 500) { printCommand("B P"); } else if (thisTown.gold > 300) { if (round % 2 == 0) { printCommand("B E"); } printCommand("B B"); } } private class Town { private final int ownerId; private final int id; private final int gold; private final int corpses; private final int warlocks; private final int crusaders; private final int amazons; private final int corsairs; private final int bishops; private final int necromancers; private final int architects; private final int peons; private final boolean hasAlreadyCommanded; public Town(String string, boolean hasAlreadyCommanded){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); warlocks = Integer.parseInt(args[4]); crusaders = Integer.parseInt(args[5]); amazons = Integer.parseInt(args[6]); corsairs = Integer.parseInt(args[7]); bishops = Integer.parseInt(args[8]); necromancers = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); peons = Integer.parseInt(args[11]); this.hasAlreadyCommanded = hasAlreadyCommanded; } public int getSoldiers() { return warlocks + crusaders + amazons; } public int getCitizens() { return corsairs + bishops + necromancers + architects; } public boolean isMine(){ return ownerId == myId; } public boolean isOutlawTown() { return ownerId == -1; } public boolean isWeak() { return willBeWeak(1); } public boolean willBeWeak(double divisor) { if (enemyPlayerTowns.size() == 0) { return false; } int mySoldiers = (int) (getSoldiers() * divisor); int weakerTowns = 0; for (Town town : enemyTowns) { if (town.getSoldiers() < mySoldiers) { weakerTowns++; } } for (Town town : myTowns) { if (town.getSoldiers() < mySoldiers) { weakerTowns++; } } return weakerTowns <= 2; } public boolean getsRobbed() { int outlaws = 0; for (Town town : outlawTowns) { outlaws += town.getSoldiers() + town.getCitizens() + town.peons; } int notOutlawTowns = enemyTowns.size() + myTowns.size() - outlawTowns.size(); int outlawsPerTown = outlaws / notOutlawTowns; return outlawsPerTown - corsairs * 5 > 0; } public boolean hasMostGold() { for (Town town : enemyTowns) { if (gold < town.gold) { return false; } } return true; } } private void printCommand(String command) { System.out.println(command); System.exit(0); } } ``` [Answer] # Politician, Java v3 **Update:** Added annoying commentary and better planning. **Update:** Recruits much less trains(corsairs) and focuses on building up the economy(peons). **Update:** Tweaked a couple of parameters. **Update:** Attacks much more often. Listens to scientists more. He has two goals. 1. Unlimited gold. 2. Unlimited armies. ``` import java.util.ArrayList; import java.util.List; public class Politician { private static final int SOLDIER_COST = 11; private static final int AMBASSADOR_COST = 22; private static final int SCIENTIST_COST = 22; private static final int TRAIN_COST = 14; private static final int ARCHITECT_COST = 17; private static final int CONVERSION_COST = 50; private static final double MIN_SOLDIER_RATIO = .75; private static final int MIN_PEOPLE = 30; private static final int MIN_ARCHITECTS = 13; private static final int MAX_PEOPLE = 200; int round; int phase; int playerID; int thisTownID; List<State> states; List<State> myStates; List<State> otherStates; State thisState; public Politician(String... args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); playerID = Integer.parseInt(args[2]); thisTownID = Integer.parseInt(args[3]); states = new ArrayList<>(); myStates = new ArrayList<>(); otherStates = new ArrayList<>(); for (int i = 4; i < args.length; i++){ states.add(new State(args[i])); } for (State state : states){ if (state.isMine()){ myStates.add(state); if (state.isThisTown()){ thisState = state; } } else { otherStates.add(state); } } } public static void main(String[] args){ if (args.length == 0) { System.out.println("8 8 8 26 4 1 13 32"); } else { try { System.out.println(new Politician(args).conquer()); } catch (Exception e){ System.out.println("We, the enslaved people, declare Politician the winner."); } } } private String conquer() { switch (phase){ case 2: return steal(); case 3: return conscript(); case 6: return bribe(); case 7: return orderAttack(); case 8: return topSecret(); case 9: return handouts(); case 11: return roadConstruction(); default: throw new IllegalStateException();//Civil war!!! } } private String steal() { State bestState = otherStates.stream().max((a, b) -> a.profit() - b.profit()).get(); return "S " + bestState.getId() + " " + thisState.getTrains(); } private String conscript() { int gold = thisState.getFreeGold(); int neededTrains = Math.max(neededTrains() - thisState.getTrains(), 0); neededTrains = Math.min(neededTrains, thisState.getRegularPeople()); neededTrains = Math.min(neededTrains, gold / TRAIN_COST); thisState.regularPeople -= neededTrains; gold -= neededTrains * TRAIN_COST; int neededSoldiers = soldiersNeeded(); neededSoldiers = Math.min(gold / SOLDIER_COST, neededSoldiers); int neededAmbassadors = Math.min(neededSoldiers, (gold - 200 - 10 * thisState.getCorpses() - CONVERSION_COST * thisState.getAmbassadors()) / (CONVERSION_COST + AMBASSADOR_COST)); neededAmbassadors = Math.min(maxSoldiers() - thisState.getAmbassadors(), neededAmbassadors); neededSoldiers -= neededAmbassadors; thisState.regularPeople -= neededSoldiers; gold -= neededSoldiers * SOLDIER_COST; neededAmbassadors += (int) Math.max(Math.round(Math.ceil(thisState.getRegularPeople() / 50.0) - thisState.getAmbassadors() - neededAmbassadors), 0); neededAmbassadors = Math.min(gold / AMBASSADOR_COST, neededAmbassadors); thisState.regularPeople -= neededAmbassadors; gold -= neededAmbassadors * AMBASSADOR_COST; int neededScientists = (int) Math.max(Math.round(Math.ceil(thisState.getCorpses() / 10.0) - thisState.getScientists()), 0); neededScientists = Math.min(gold / SCIENTIST_COST, neededScientists); thisState.regularPeople -= neededScientists; gold -= neededScientists * SCIENTIST_COST; int neededArchitects = 0; if (thisState.getRegularPeople() > MIN_PEOPLE){ int freePeople = thisState.getRegularPeople() - MIN_PEOPLE; neededArchitects = Math.max(MIN_ARCHITECTS - thisState.getArchitects(), 0); neededArchitects = Math.min(neededArchitects, freePeople); neededArchitects = Math.min(neededArchitects, gold / ARCHITECT_COST); freePeople -= neededArchitects; gold -= neededArchitects * ARCHITECT_COST; if (freePeople + MIN_PEOPLE > MAX_PEOPLE){ if (freePeople + MIN_PEOPLE > MAX_PEOPLE){ freePeople = freePeople + MIN_PEOPLE - MAX_PEOPLE; } neededAmbassadors += Math.min(gold / AMBASSADOR_COST, freePeople); neededAmbassadors = Math.min(neededAmbassadors, maxSoldiers() - thisState.getAmbassadors()); gold -= neededAmbassadors * AMBASSADOR_COST; freePeople -= neededAmbassadors; neededSoldiers += Math.min(gold / SOLDIER_COST, freePeople); } } int neededAirmen = neededSoldiers / 3; int neededSailors = neededSoldiers / 3; int neededPrivates = neededSoldiers / 3; return "R " + neededAirmen + " " + neededSailors + " " + neededPrivates + " " + neededTrains + " " + neededAmbassadors + " " + neededScientists + " " + neededArchitects; } private int neededTrains() { int totalOutlaws = 0; int totalStates = myStates.size(); for (State state : otherStates){ if (state.isOutlaw()){ totalOutlaws += state.getTotalCitizens(); } else { totalStates++; } } return (int) Math.round(Math.ceil(.2 * totalOutlaws / totalStates)); } private int soldiersNeeded(){ int soldiers = (int) ((MIN_SOLDIER_RATIO * thisState.getRegularPeople() - thisState.getTotalSoldiers()) / (MIN_SOLDIER_RATIO + 1)); soldiers = Math.max(soldiers, minSoldiers() + 5 - thisState.getTotalSoldiers()); soldiers = Math.max(soldiers, maxSoldiers() / 2 - thisState.getTotalSoldiers()); soldiers = Math.max(soldiers, 0); return soldiers; } private String bribe() { int soldiersToConvert = Math.min(thisState.ambassadors, (thisState.getGold() - 200 - 10 * thisState.getCorpses()) / CONVERSION_COST); soldiersToConvert = Math.max(soldiersToConvert, 0); State toughest = otherStates.stream().max((a,b) -> a.getTotalSoldiers() - b.getTotalSoldiers()).get(); soldiersToConvert = Math.min(soldiersToConvert, toughest.getTotalSoldiers()); int airmen = (int) ((1.0 * toughest.getAirmen() / toughest.getTotalSoldiers()) * soldiersToConvert); soldiersToConvert -= airmen; int sailors = (int) ((1.0 * toughest.getSailors() / toughest.getTotalSoldiers()) * soldiersToConvert) * 3 / 2; soldiersToConvert -= sailors; int privates = soldiersToConvert; return "C " + toughest.getId() + " " + airmen + " " + sailors + " " + privates; } private String orderAttack() { if (round < 99 && otherTowns.size() < 2){ return "W"; } int soldiers = thisState.getFreeSoldiers(); otherStates.sort((a,b) -> b.getRegularPeople() / Math.max(b.getTotalSoldiers(), 1) - a.getRegularPeople() / Math.max(a.getTotalSoldiers(), 1)); if (otherStates.get(0).getTotalSoldiers() < soldiers){//Attack!!!! int airmen = (int) (((thisState.getAirmen()*1.0) / thisState.getTotalSoldiers()) * soldiers); int sailors = (int) (((thisState.getSailors()*1.0) / thisState.getTotalSoldiers()) * soldiers); int privates = (int) (((thisState.getPrivates()*1.0) / thisState.getTotalSoldiers()) * soldiers); return "A " + otherStates.get(0).getId() + " " + airmen + " " + sailors + " " + privates; } return getWaitString(); } private String handouts() { State poorestState = null; int goldOfPoorestTown = Integer.MAX_VALUE; for (State state : myStates){ if (state.getGold() < goldOfPoorestTown){ poorestState = state; goldOfPoorestTown = state.getGold(); } } if (thisState.getGold() <= goldOfPoorestTown){ return getWaitString(); } return "T " + poorestState.getId() + " " + (thisState.getGold() - poorestState.getGold()) / 2; } private String topSecret() { return "R " + thisState.getCorpses(); } private String roadConstruction() { int airportPriority = thisState.getAirmen() + thisState.getAmbassadors() + thisState.getScientists(); int highwayPriority = thisState.getSailors() + thisState.getPrivates(); int railroadPriority = thisState.getTrains() + thisState.getRegularPeople(); int palacePriority = 5;//Why would we build a palace??? if (airportPriority > highwayPriority && airportPriority > railroadPriority && airportPriority > palacePriority && thisState.getGold() > 200){ return "B T"; } else if (highwayPriority > railroadPriority && highwayPriority > palacePriority && thisState.getGold() > 200){ return "B B"; } else if (railroadPriority > palacePriority && thisState.getGold() > 200){ return "B E"; } else if (thisState.getGold() > 500){ return "B P"; } else { return getWaitString(); } } private int maxSoldiers(){ int max = 0; for (State state : otherStates){ if (state.getTotalSoldiers() > max){ max = state.getTotalSoldiers(); } } return max; } private int minSoldiers(){ int min = Integer.MAX_VALUE; for (State state : otherStates){ if (state.getTotalSoldiers() < min){ min = state.getTotalSoldiers(); } } return min; } private class State { private final int ownerId; private final int id; private final int gold; private final int corpses; private final int airmen; private final int sailors; private final int privates; private final int trains; private final int ambassadors; private final int scientists; private final int architects; private int regularPeople; private final int airports; private final int highways; private final int railroads; private final int palaces; public State(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); airmen = Integer.parseInt(args[4]); sailors = Integer.parseInt(args[5]); privates = Integer.parseInt(args[6]); trains = Integer.parseInt(args[7]); ambassadors = Integer.parseInt(args[8]); scientists = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); regularPeople = Integer.parseInt(args[11]); airports = Integer.parseInt(args[12]); highways = Integer.parseInt(args[13]); railroads = Integer.parseInt(args[14]); palaces = Integer.parseInt(args[15]); } public int getOwnerId() { return ownerId; } public int getId() { return id; } public int getGold() { return gold; } public int getCorpses() { return corpses; } public int getAirmen() { return airmen; } public int getSailors() { return sailors; } public int getPrivates() { return privates; } public int getTrains() { return trains; } public int getAmbassadors() { return ambassadors; } public int getScientists() { return scientists; } public int getArchitects() { return architects; } public int getRegularPeople() { return regularPeople; } public int getAirports() { return airports; } public int getHighways() { return highways; } public int getRailroads() { return railroads; } public int getPalaces() { return palaces; } public int getTotalBuildings() { return getAirports() + getHighways() + getRailroads() + getPalaces(); } public int getTotalSoldiers() { return getAirmen() + getSailors() + getPrivates(); } public int getTotalUnits() { return getTotalSoldiers() + getTrains() + getAmbassadors() + getScientists() + getArchitects(); } public int getTotalCitizens() { return getTotalUnits() + getRegularPeople(); } public boolean isMine(){ return getOwnerId() == playerID; } public boolean isThisTown(){ return id == thisTownID; } public int neededGold(){ return 2 * getTotalUnits() - getTotalSoldiers(); } public int getFreeGold(){ return gold - neededGold(); } public int getFreeSoldiers() { int soldiers = Math.max((int) (getTotalSoldiers() - regularPeople * MIN_SOLDIER_RATIO), 0); soldiers = Math.min(soldiers, getTotalSoldiers() - minSoldiers() - 5); soldiers = Math.min(soldiers, getTotalSoldiers() - maxSoldiers() / 2); soldiers = Math.max(soldiers, 0); return soldiers; } public boolean isOutlaw() { return ownerId == -1; } public int income() { return 5 * regularPeople + 10 * trains + 2 * (airmen + ambassadors + scientists) * airports + 2 * (sailors + privates) * highways + 2 * (trains + regularPeople) * railroads + 10 * palaces; } public int wages() { return airmen + sailors + privates + 2 * (trains + ambassadors + scientists + architects); } public int profit() { return income() - wages(); } } private static String getWaitString(){ switch ((int) (Math.random() * 7)){ case 0: return "We will win!"; case 1: return "Winny the Pooh, Winny the Pooh"; case 2: return "Who washed Washington's white woolen underwear when Washington's laundry woman, went west?"; case 3: return "What's up doc?"; case 4: return "Why is this taking so long?"; case 5: return "Wool is better than cotton."; case 6: return "Will I win?"; case 7: return "What's your favorite color?"; default: return "What! This message should not be being printed."; } } } ``` # Explanation He has two goals. 1. Unlimited gold. 2. Unlimited armies. **How to get gold:** Politician merely hires architects to build airports, highways, and railroads. Piles of money start pouring in rather quickly. After increasing taxes, Politician has unlimited money. **How to get armies:** This is a little harder. With limited people, you can only attain a small army. With ambassadors, he can hire even bigger armies, but they still aren't quite big enough. After some contemplation Politician figured out that conquering other nations and then enslaving the people gives him fairly large armies. But they are still not nearly big enough. After hiring some scientists, they tell him they have discovered the secret to raise the dead, unfortunately, they are no longer soldiers after resurrection. After deep contemplation Politician figures out that this is to his advantage, and hires the risen dead as ambassadors that hire even more soldiers, ad infinitum. [Answer] # Serenity, Lua Focuses on reaching Serenity through religion. Tries to convert the infidels and wait for towns to reach a critical state before expading its faith by building new temples. ``` function explode(d,p) local t, ll; t={}; ll=0 if(#p == 1) then return {p} end while true do l=string.find(p,d,ll,true) if l~=nil then table.insert(t, string.sub(p,ll,l-1)); ll=l+1 else table.insert(t, string.sub(p,ll)); break end end return t end function soldiers(t) local s s = t["WARLOCKS"] + t["CRUSADERS"] + t["AMAZONS"] return s end function reserve(t) local s s = t["GOLD"] - (3 * soldiers(t)) return s end parameters = {"PLAYER", "TOWN", "GOLD", "CORPSES", "WARLOCKS", "CRUSADERS", "AMAZONS", "CORSAIRS", "BISHOPS", "NECROMANCERS", "ARCHITECTS", "PEONS", "TEMPLES", "BARRACKS", "ESTATES", "PALACES"} if (#arg < 1) then print("5 5 5 10 10 1 3 59") else args = explode(";", arg[1]) local round = tonumber(args[1]) local phase = tonumber(args[2]) local playerID = tonumber(args[3]) local thisTownID = tonumber(args[4]) local thisTown = {} local towns = {} local enemyTowns = {} local myTowns = {} local output = "W" local stock = 200 local peons = 33 local bishops = 20 for i=5,#args,1 do local town = explode("_", args[i]) towns[town[2]] = {} for key, value in pairs(town) do towns[town[2]][parameters[key]] = tonumber(value) end end for i, town in pairs(towns) do if town["PLAYER"] == playerID then if town["TOWN"] == thisTownID then thisTown = town end table.insert(myTowns, town) else table.insert(enemyTowns, town) end end if phase == 2 then local richestTown for i, town in pairs(myTowns) do if richestTown == nil then richestTown = town end if richestTown["GOLD"] > town["GOLD"] then richestTown = town end end if thisTown["CORSAIRS"] > 0 then output = "S "..richestTown["TOWN"].." "..thisTown["CORSAIRS"] end elseif phase == 3 then local necromancers = 0 local architects = 0 if thisTown["NECROMANCERS"] < 1 then necromancers = 1 end if thisTown["ARCHITECTS"] < 1 then architects = 1 end if reserve(thisTown) > stock and thisTown["PEONS"] > peons then output = "R 0 0 0 0 "..math.max(0, math.min(thisTown["BISHOPS"] - bishops, math.min(thisTown["PEONS"] - peons, math.floor((reserve(thisTown) - stock) / 20)))).." "..necromancers.." "..architects end elseif phase == 6 then local biggestTown for i, town in pairs(enemyTowns) do if biggestTown == nil then biggestTown = town end if soldiers(biggestTown) > soldiers(town) then biggestTown = town end end local units = math.min(thisTown["BISHOPS"], math.floor((reserve(thisTown) - stock) / 50)) if (reserve(thisTown) > stock) then output = "C "..biggestTown["TOWN"].." "..math.floor(units/3).." "..math.floor(units/3).." "..math.floor(units/3) end elseif phase == 7 then for i, town in pairs(enemyTowns) do if soldiers(town) <= 3 and soldiers(thisTown) >= 9 then output = "A "..town["TOWN"].." 3 3 3"; break end end elseif phase == 8 then if thisTown["CORPSES"] > 0 and thisTown["NECROMANCERS"] > 0 then output = "R "..math.min(thisTown["NECROMANCERS"] * 5, thisTown["CORPSES"]) end elseif phase == 9 then local smallestTown, poorestTown for i, town in pairs(myTowns) do if smallestTown == nil then smallestTown = town end if poorestTown == nil then poorestTown = town end if soldiers(smallestTown) < soldiers(town) then smallestTown = town end if poorestTown["GOLD"] < town["GOLD"] then poorestTown = town end if (soldiers(thisTown) - soldiers(smallestTown) >= 18) then output = "M "..thisTown["TOWN"].." 3 3 3" break end if (thisTown["GOLD"] - poorestTown["GOLD"] >= 600) then output = "T "..thisTown["TOWN"].." 300" break end end elseif phase == 11 then if reserve(thisTown) > (stock + 200) then output = "B T" end end print(output) end ``` Run with `lua Serenity.lua` (requires Lua 5.2) [Answer] # The Zealots (Python) (Based on CarpetPython's code.) Build as meany temples as possible! Raise the dead! Convert the infidel! ``` import sys from random import * from operator import itemgetter (PLAYER, TOWN, GOLD, CORPSES, WARLOCKS, CRUSADERS, AMAZONS, CORSAIRS, BISHOPS, NECROMANCERS, ARCHITECTS, PEONS, TEMPLES, BARRACKS, ESTATES, PALACES) = range(16) def getstrength(t): return t[WARLOCKS]+t[CRUSADERS]*1.5+t[AMAZONS]/1.5 if len(sys.argv) < 2: print 20, 5, 5, 10, 8, 5, 7, 40 else: parts = sys.argv[1].split(';') turn, phase, me, thistown = [int(parts.pop(0)) for i in range(4)] towns = [[int(v) for v in town.split('_')] for town in parts] enemy = [t for t in towns if t[PLAYER] != me] mytowns = [t for t in towns if t[PLAYER] == me] here = [t for t in mytowns if t[TOWN] == thistown][0] otherids = [t[TOWN] for t in enemy] strength = sorted(enemy, key=getstrength) rich = sorted(enemy, key=itemgetter(GOLD)) output = '' if phase == 2: output = 'S %s %s' % (rich[-1][TOWN], here[CORSAIRS]) elif phase == 3: Warlocks=Crusaders=Amazons=Corsairs=Bishops=Necromancers=Architects=0 if here[CORPSES] > 5*here[NECROMANCERS]: Necromancers = 1 if here[PEONS] > 50*here[BISHOPS]: Bishops = 1 if here[WARLOCKS] < strength[0][CRUSADERS]: Warlocks = 2 Amazons = 2 if here[WARLOCKS] < here[AMAZONS]: Warlocks += 1 if here[GOLD] > 200: Architects = 1 if rich[-1][GOLD] > 100+2*here[GOLD]: Corsairs = 1 output = 'R %s %s %s %s %s %s %s' % (Warlocks,Crusaders,Amazons,Corsairs,Bishops,Necromancers,Architects) elif phase == 6: if here[GOLD] > 300: output = 'C %s %s %s %s' % (strength[0][TOWN],here[GOLD]/300,here[GOLD]/300,here[GOLD]/300) elif phase == 7: target = strength[0] if getstrength(target) < getstrength(here)*3/5: output = 'A %s %s %s 0' % (target[TOWN],here[WARLOCKS]*3/4,target[AMAZONS]) elif phase == 8: if here[CORPSES] > 10: output = 'R %s' % (here[NECROMANCERS]*5) elif phase == 9: pass # move people or gold here elif phase == 11 and here[GOLD] > 300: output = 'B T' # Build a temple! print output if output else 'W' ``` [Answer] # Commander, Java Commander is one of the 2 default bots I created along with the controller (the other one being Sleeper who does nothing). Commander is a conqueror and he'll try to use every last of his resources to reach complete domination. ``` import java.util.ArrayList; import java.util.List; public class Commander { int round; int phase; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public static void main(String[] args){ if (args.length == 0) { System.out.println("15 10 12 10 7 5 1 40"); } else { new Commander().conquer(args[0].split(";")); } } private void conquer(String[] args) { round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); playerID = Integer.parseInt(args[2]); thisTownID = Integer.parseInt(args[3]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 4; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } if (phase == 2) { // Steal //Command : S destinationId corsairs steal(); } else if (phase == 3) { // Recruit //Command : R warlocks crusaders amazons corsairs bishops necromancers architects recruit() ; } else if (phase == 6) { // Convert //Command : C destinationId warlocks crusaders amazons convert(); } else if (phase == 7) { // Attack //Command : A destinationId warlocks crusaders amazons attack(); } else if (phase == 8) { // Resurrect //Command : R corpses resurrect(); } else if (phase == 9) { // Move //Command : M destinationId warlocks crusaders amazons corsairs bishops necromancers architects move(); } else if (phase == 11) { // Build //Command : B building building building... (T: Temple, B: Barracks, E: Estate, P: Palace) build(); } } private void steal() { Town richestTown = otherTowns.stream().max((a,b) -> a.gold - b.gold).get(); System.out.println("S " + richestTown.getId() + " " + thisTown.getCorsairs()); } private void recruit() { int maxUnitsToRecruits = Math.floorDiv(thisTown.getPeons() - thisTown.getUnits(), 2); int goldAvailable = thisTown.getGold() - (thisTown.getUnits() * 5); int unitsRecruited = 0; int cost = 10; int[] recruits = new int[3]; int i = 0; int necromancers = Math.max(0, 5 - thisTown.getNecromancers()); while (goldAvailable >= 0 && unitsRecruited <= maxUnitsToRecruits) { i = (i >= recruits.length - 1 ? 0 : i+1); recruits[i]++; unitsRecruited++; goldAvailable-=cost; } if (unitsRecruited > 0) { System.out.println("R " + recruits[0] + " " + recruits[1] + " " + recruits[2] + " 0 0 " + necromancers + " 0"); } else { System.out.println("W"); } } private void convert() { Town biggestTown = otherTowns.stream().max((a,b) -> a.getCitizens() - b.getCitizens()).get(); int goldAvailable = thisTown.getGold() - (thisTown.getUnits() * 5); int bishopsAvailable = thisTown.getBishops(); int unitsConverted = 0; int cost = 50; int[] converts = new int[3]; int i = 0; while (goldAvailable >= 0 && unitsConverted <= bishopsAvailable) { i = (i >= converts.length - 1 ? 0 : i+1); converts[i]++; goldAvailable-=cost; } System.out.println("C " + biggestTown.getId() + " " + converts[0] + " " + converts[1] + " " + converts[2]); } private void attack() { Town lessDefendedTown = otherTowns.stream().max((a,b) -> a.getSoldiers() - b.getSoldiers()).get(); int neededWarlocks = thisTown.getWarlocks() - lessDefendedTown.getWarlocks(); int neededCrusaders = thisTown.getCrusaders() - lessDefendedTown.getCrusaders(); int neededAmazons = thisTown.getAmazons() - lessDefendedTown.getAmazons() ; if (neededWarlocks > 0 && neededCrusaders > 0 && neededAmazons > 0) { System.out.println("A " + lessDefendedTown.getId() + " " + (lessDefendedTown.getWarlocks() + 1) + " " + (lessDefendedTown.getCrusaders() + 1) + " " + (lessDefendedTown.getAmazons() + 1)); } else { System.out.println("W"); } } private void move() { System.out.println("W"); } private void resurrect() { int goldAvailable = thisTown.getGold() - (thisTown.getUnits() * 5); int corpsesAvailable = thisTown.getCorpses(); int availableNecromancers = thisTown.getNecromancers(); int raiseCapacity = availableNecromancers * 5; int raisedCorpses = 0; while (corpsesAvailable >= 0 && raiseCapacity >= 0 && goldAvailable >= 0) { raisedCorpses++; corpsesAvailable--; goldAvailable -= 20; raiseCapacity--; } if (raisedCorpses > 0) { System.out.println("R " + raisedCorpses); } else { System.out.println("W"); } } private void build() { int goldAvailable = thisTown.getGold() - (thisTown.getUnits() * 5); if (goldAvailable >= 400) { System.out.println("B B"); } else { System.out.println("W"); } } private class Town { private final int ownerId; private final int id; private final int gold; private final int corpses; private final int warlocks; private final int crusaders; private final int amazons; private final int corsairs; private final int bishops; private final int necromancers; private final int architects; private final int peons; private final int temples; private final int barracks; private final int estates; private final int palaces; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); warlocks = Integer.parseInt(args[4]); crusaders = Integer.parseInt(args[5]); amazons = Integer.parseInt(args[6]); corsairs = Integer.parseInt(args[7]); bishops = Integer.parseInt(args[8]); necromancers = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); peons = Integer.parseInt(args[11]); temples = Integer.parseInt(args[12]); barracks = Integer.parseInt(args[13]); estates = Integer.parseInt(args[14]); palaces = Integer.parseInt(args[15]); } public int getOwnerId() { return ownerId; } public int getId() { return id; } public int getGold() { return gold; } public int getCorpses() { return corpses; } public int getWarlocks() { return warlocks; } public int getCrusaders() { return crusaders; } public int getAmazons() { return amazons; } public int getCorsairs() { return corsairs; } public int getBishops() { return bishops; } public int getNecromancers() { return necromancers; } public int getArchitects() { return architects; } public int getPeons() { return peons; } public int getTemples() { return temples; } public int getBarracks() { return barracks; } public int getEstates() { return estates; } public int getPalaces() { return palaces; } public int getBuildings() { return getTemples() + getBarracks() + getEstates() + getPalaces(); } public int getSoldiers() { return getWarlocks() + getCrusaders() + getAmazons(); } public int getUnits() { return getSoldiers() + getCorsairs() + getBishops() + getNecromancers() + getArchitects(); } public int getCitizens() { return getUnits() + getPeons(); } public boolean isMine(){ return getOwnerId() == playerID; } public boolean isThisTown(){ return id == thisTownID; } } } ``` [Answer] # Butter This butter acts much the same as the previous butter. Unlike the previous butter, this gets rich uncommonly fast. Unfortunately, the Young Earls, along with the Lannisters, like butter on their waffles. Therefore, butter is quickly consumed. ``` import java.util.ArrayList; import java.util.List; public class Butter { int round; int phase; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> otherTowns; Town thisTown; public Butter(String... args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); playerID = Integer.parseInt(args[2]); thisTownID = Integer.parseInt(args[3]); towns = new ArrayList<>(); myTowns = new ArrayList<>(); otherTowns = new ArrayList<>(); for (int i = 4; i < args.length; i++){ towns.add(new Town(args[i])); } for (Town town : towns){ if (town.isMine()){ myTowns.add(town); if (town.isThisTown()){ thisTown = town; } } else { otherTowns.add(town); } } } public static void main(String[] args){ if (args.length == 0) { System.out.println("12 12 12 12 13 13 13 13"); } else { System.out.println(new Butter(args[0]).spread()); } } private String spread() { if (phase == 2) { // Steal //Command : S destinationId corsairs return steal(); } else if (phase == 3) { // Recruit //Command : R warlocks crusaders amazons corsairs bishops necromancers architects return recruit() ; } else if (phase == 6) { // Convert //Command : C destinationId warlocks crusaders amazons return convert(); } else if (phase == 7) { // Attack //Command : A destinationId warlocks crusaders amazons return attack(); } else if (phase == 8) { // Resurrect //Command : R corpses return resurrect(); } else if (phase == 9) { // Move //Command : M destinationId warlocks crusaders amazons corsairs bishops necromancers architects return move(); } else if (phase == 11) { // Build //Command : B building building building... (T: Temple, B: Barracks, E: Estate, P: Palace) return build(); } throw new IllegalStateException(phase + ""); } private String steal() { if (thisTown.getCorsairs() <= 0){ return "W"; } int mostGold = Integer.MIN_VALUE; Town richestTown = null; for (Town town : otherTowns){ if (town.getGold() > mostGold){ mostGold = town.getGold(); richestTown = town; } } return "S " + richestTown.getId() + " " + thisTown.getCorsairs(); } private String recruit() { int gold = thisTown.getFreeGold(); int peons = thisTown.getPeons(); int warlocks = thisTown.getWarlocks(); int crusaders = thisTown.getCrusaders(); int amazons = thisTown.getAmazons(); int corsairs = thisTown.getCorsairs(); int bishops = thisTown.getBishops(); int necromancers = thisTown.getNecromancers(); int architects = thisTown.getArchitects(); int totalPeople = peons+warlocks+crusaders+amazons+corsairs+bishops+necromancers+architects; int averagePeople = totalPeople / 8; int extraPeons = peons - averagePeople; if (extraPeons <= 0 || gold <= 0){ return "W"; } int warlocksToAdd = warlocks < averagePeople ? 0 : warlocks - averagePeople; int crusadersToAdd = crusaders < averagePeople ? 0 : crusaders - averagePeople; int amazonsToAdd = amazons < averagePeople ? 0 : amazons - averagePeople; int corsairsToAdd = corsairs < averagePeople ? 0 : corsairs - averagePeople; int bishopsToAdd = bishops < averagePeople ? 0 : bishops - averagePeople; int necromancersToAdd = necromancers < averagePeople ? 0 : necromancers - averagePeople; int architectsToAdd = architects < averagePeople ? 0 : architects - averagePeople; warlocksToAdd = warlocksToAdd * 11 > gold ? gold / 11 : warlocksToAdd; gold -= warlocksToAdd * 11; crusadersToAdd = crusadersToAdd * 11 > gold ? gold / 11 : crusadersToAdd; gold -= crusadersToAdd * 11; amazonsToAdd = amazonsToAdd * 11 > gold ? gold / 11 : amazonsToAdd; gold -= amazonsToAdd * 11; corsairsToAdd = corsairsToAdd * 14 > gold ? gold / 14 : corsairsToAdd; gold -= corsairsToAdd * 14; bishopsToAdd = bishopsToAdd * 22 > gold ? gold / 22 : bishopsToAdd; gold -= bishopsToAdd * 22; necromancersToAdd = necromancersToAdd * 22 > gold ? gold / 22: necromancersToAdd; gold -= necromancersToAdd * 22; architectsToAdd = architectsToAdd * 17 > gold ? gold / 17 : architectsToAdd; gold -= architectsToAdd * 17; warlocksToAdd = warlocksToAdd > extraPeons ? extraPeons : warlocksToAdd; extraPeons -= warlocksToAdd; crusadersToAdd = crusadersToAdd > extraPeons ? extraPeons : crusadersToAdd; extraPeons -= crusadersToAdd; amazonsToAdd = amazonsToAdd > extraPeons ? extraPeons : amazonsToAdd; extraPeons -= amazonsToAdd; corsairsToAdd = corsairsToAdd > extraPeons ? extraPeons : corsairsToAdd; extraPeons -= corsairsToAdd; bishopsToAdd = bishopsToAdd > extraPeons ? extraPeons : bishopsToAdd; extraPeons -= bishopsToAdd; necromancersToAdd = necromancersToAdd > extraPeons ? extraPeons : necromancersToAdd; extraPeons -= necromancersToAdd; architectsToAdd = architectsToAdd > extraPeons ? extraPeons : architectsToAdd; return "R " + warlocksToAdd + " " + crusadersToAdd + " " + amazonsToAdd + " " + corsairsToAdd + " " + bishopsToAdd + " " + necromancersToAdd + " " + architectsToAdd; } private String convert() { return "W"; } private String attack() { for (Town town : otherTowns){ if (town.getSoldiers() * 4 < thisTown.getSoldiers()){ return "A " + town.getId() + " " + thisTown.getWarlocks() / 2 + " " + thisTown.getCrusaders() / 2 + " " + thisTown.getAmazons() / 2; } } return "W"; } private String move() { int totalWarlocks = 0; int totalCrusaders = 0; int totalAmazons = 0; int totalCorsairs = 0; int totalBishops = 0; int totalNecromancers = 0; int totalArchitects = 0; for (Town town : myTowns){ totalWarlocks += town.getWarlocks(); totalCrusaders += town.getCrusaders(); totalAmazons += town.getAmazons(); totalCorsairs += town.getCorsairs(); totalBishops += town.getBishops(); totalNecromancers += town.getNecromancers(); totalArchitects += town.getArchitects(); } int averageWarlocks = totalWarlocks / myTowns.size(); int averageCrusaders = totalCrusaders / myTowns.size(); int averageAmazons = totalAmazons / myTowns.size(); int averageCorsairs = totalCorsairs / myTowns.size(); int averageBishops = totalBishops / myTowns.size(); int averageNecromancers = totalNecromancers / myTowns.size(); int averageArchitects = totalArchitects / myTowns.size(); Town worstTown = null; int biggestDifference = Integer.MIN_VALUE; for (Town town : myTowns){ int difference = 0; difference += town.getWarlocks() < averageWarlocks ? averageWarlocks - town.getWarlocks() : 0; difference += town.getCrusaders() < averageCrusaders ? averageCrusaders - town.getCrusaders() : 0; difference += town.getAmazons() < averageAmazons ? averageAmazons - town.getAmazons() : 0; difference += town.getCorsairs() < averageCorsairs ? averageCorsairs - town.getCorsairs() : 0; difference += town.getBishops() < averageBishops ? averageBishops - town.getBishops() : 0; difference += town.getNecromancers() < averageNecromancers ? averageNecromancers - town.getNecromancers() : 0; difference += town.getArchitects() < averageArchitects ? averageArchitects - town.getArchitects() : 0; if (difference > biggestDifference){ worstTown = town; biggestDifference = difference; } } int neededWarlocks = worstTown.getWarlocks() < averageWarlocks ? averageWarlocks - worstTown.getWarlocks() : 0; int neededCrusaders = worstTown.getCrusaders() < averageCrusaders ? averageCrusaders - worstTown.getCrusaders() : 0; int neededAmazons = worstTown.getAmazons() < averageAmazons ? averageAmazons - worstTown.getAmazons() : 0; int neededCorsairs = worstTown.getCorsairs() < averageCorsairs ? averageCorsairs - worstTown.getCorsairs() : 0; int neededBishops = worstTown.getBishops() < averageBishops ? averageBishops - worstTown.getBishops() : 0; int neededNecromancers = worstTown.getNecromancers() < averageNecromancers ? averageNecromancers - worstTown. getNecromancers() : 0; int neededArchitects = worstTown.getArchitects() < averageArchitects ? averageArchitects - worstTown. getArchitects() : 0; return "M " + worstTown.getId() + " " + neededWarlocks + " " + neededCrusaders + " " + neededAmazons + " " + neededCorsairs + " " + neededBishops + " " + neededNecromancers + " " + neededArchitects; } private String resurrect() { return "R " + thisTown.getCorpses(); } private String build() { if (thisTown.getGold() > 500){ return "B P"; } if (thisTown.getGold() > 200){ return "B T"; } return "W"; } private class Town { private final int ownerId; private final int id; private final int gold; private final int corpses; private final int warlocks; private final int crusaders; private final int amazons; private final int corsairs; private final int bishops; private final int necromancers; private final int architects; private final int peons; private final int temples; private final int barracks; private final int estates; private final int palaces; public Town(String string){ String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); warlocks = Integer.parseInt(args[4]); crusaders = Integer.parseInt(args[5]); amazons = Integer.parseInt(args[6]); corsairs = Integer.parseInt(args[7]); bishops = Integer.parseInt(args[8]); necromancers = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); peons = Integer.parseInt(args[11]); temples = Integer.parseInt(args[12]); barracks = Integer.parseInt(args[13]); estates = Integer.parseInt(args[14]); palaces = Integer.parseInt(args[15]); } public int getOwnerId() { return ownerId; } public int getId() { return id; } public int getGold() { return gold; } public int getCorpses() { return corpses; } public int getWarlocks() { return warlocks; } public int getCrusaders() { return crusaders; } public int getAmazons() { return amazons; } public int getCorsairs() { return corsairs; } public int getBishops() { return bishops; } public int getNecromancers() { return necromancers; } public int getArchitects() { return architects; } public int getPeons() { return peons; } public int getTemples() { return temples; } public int getBarracks() { return barracks; } public int getEstates() { return estates; } public int getPalaces() { return palaces; } public int getBuildings() { return getTemples() + getBarracks() + getEstates() + getPalaces(); } public int getSoldiers() { return getWarlocks() + getCrusaders() + getAmazons(); } public int getUnits() { return getSoldiers() + getCorsairs() + getBishops() + getNecromancers() + getArchitects(); } public int getCitizens() { return getUnits() + getPeons(); } public boolean isMine(){ return getOwnerId() == playerID; } public boolean isThisTown(){ return id == thisTownID; } public int neededGold(){ return 2 * getUnits() - getSoldiers(); } public int getFreeGold(){ return gold - neededGold(); } } } ``` [Answer] # Sehtimianer, Java ``` import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; public class Sehtimianer { private static final int GOLD_MAX_DEBT = 200; private static final int BIRTH_ROUND = 5; private static final int ZOMBIE_WAKING_CHANCE = 10; private static final int NECRO_RAISE_CAPACITY = 5; private static final int DEMON_SUMMON_CHANCE = 10; private static final int BISHOP_PRAYER_CAPACITY = 50; private static final int CORSAIR_SURVEILLANCE_RATIO = 5; public static final int GOLD_PER_WARLOCK = -1; public static final int GOLD_PER_CRUSADER = -1; public static final int GOLD_PER_AMAZON = -1; public static final int GOLD_PER_CORSAIR = -2; public static final int GOLD_PER_BISHOP = -2; public static final int GOLD_PER_NECRO = -2; public static final int GOLD_PER_ARCHITECT = -2; public static final int GOLD_PER_PEON = 5; public static final int GOLD_PER_RESURRECTION = 20; public static final int GOLD_PER_CONVERSION = 50; public static final int GOLD_PER_STEAL = 10; public static final int GOLD_RECRUIT_WARLOCK = 10; public static final int GOLD_RECRUIT_CRUSADER = 10; public static final int GOLD_RECRUIT_AMAZON = 10; public static final int GOLD_RECRUIT_CORSAIR = 12; public static final int GOLD_RECRUIT_BISHOP = 20; public static final int GOLD_RECRUIT_NECRO = 20; public static final int GOLD_RECRUIT_ARCHITECT = 15; public static final int GOLD_RECRUIT_DEFAULT = 20; public static final int GOLD_PER_TEMPLE = 2; public static final int GOLD_PER_BARRACKS = 2; public static final int GOLD_PER_ESTATE = 2; public static final int GOLD_PER_PALACE = 10; public static final int GOLD_COST_BUILDING = 200; public static final int COMPLETION_PER_ARCHITECT = 8; public static final int COMPLETION_NEEDED = 100; public static final int ARCHITECTS = (int) Math.ceil(1.0 * COMPLETION_NEEDED / COMPLETION_PER_ARCHITECT); int round; int phase; int playerID; int thisTownID; List<Town> towns; List<Town> myTowns; List<Town> playerTowns; List<Town> outlawTowns; Town thisTown; public static void main(String[] args) { if (args.length == 0) { System.out.println("9 9 9 24 5 2 13 29"); } else { new Sehtimianer().actions(args[0].split(";")); } } private void actions(String[] args) { round = Integer.parseInt(args[0]); phase = Integer.parseInt(args[1]); playerID = Integer.parseInt(args[2]); thisTownID = Integer.parseInt(args[3]); towns = new ArrayList<Town>(); myTowns = new ArrayList<Town>(); playerTowns = new ArrayList<Town>(); outlawTowns = new ArrayList<Town>(); for (int i = 4; i < args.length; i++) { towns.add(new Town(args[i])); } for (Town town : towns) { if (town.isMine()) { myTowns.add(town); if (town.isThisTown()) { thisTown = town; } } else { if (town.getOwnerId() == -1) { outlawTowns.add(town); } else { playerTowns.add(town); } } } if (outlawTowns.size() == 0 && playerTowns.size() == 0) { System.out.print("WIN : D"); return; } if (phase == 2) { steal(); } else if (phase == 3) { recruit(); } else if (phase == 6) { convert(); } else if (phase == 7) { attack(); } else if (phase == 8) { resurrect(); } else if (phase == 9) { move(); } else if (phase == 11) { build(); } } private List<Town> calcStrongestPlayers() { if (playerTowns.size() == 0) { return outlawTowns; } Map<Integer, Integer> playerTownCount = new HashMap<Integer, Integer>(); Integer count; int maxCount = 0; for (Town town : playerTowns) { count = playerTownCount.get(town.getOwnerId()); if (count == null) { count = Integer.valueOf(1); } else { count = Integer.valueOf(count + 1); } playerTownCount.put(town.getOwnerId(), count); if (count > maxCount) { maxCount = count; } } Set<Integer> strongestPlayers = new HashSet<Integer>(); for (Entry<Integer, Integer> entry : playerTownCount.entrySet()) { if (entry.getValue() == maxCount) { strongestPlayers.add(entry.getKey()); } } return playerTowns.stream().filter(a -> strongestPlayers.contains(a.getOwnerId())).collect(Collectors.toList()); } private void steal() { // S destinationId corsairs List<Town> afterFilter = calcStrongestPlayers().stream().filter(a -> a.getGold() > 0).collect(Collectors.toList()); if (afterFilter.size() == 0) { afterFilter = calcStrongestPlayers(); } Town poorestTown = afterFilter.stream().min((a, b) -> a.gold - b.gold).get(); System.out.println("S " + poorestTown.getId() + " " + thisTown.getCorsairs()); } private boolean willAttackSoon() { Town strongestTown; if (playerTowns.size() > 0) { strongestTown = playerTowns.stream().max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); if ((thisTown.getSoldiers() + thisTown.getBishops()) / 3 <= strongestTown.getSoldiers()) { return false; } } strongestTown = calcStrongestPlayers().stream().max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); int deltaWarlocks = thisTown.getWarlocks() - (strongestTown.getWarlocks() + strongestTown.getAmazons()); int deltaCrusaders = thisTown.getCrusaders() - (strongestTown.getCrusaders() + strongestTown.getWarlocks()); int deltaAmazons = thisTown.getAmazons() - (strongestTown.getAmazons() + strongestTown.getCrusaders()); return (deltaWarlocks + deltaCrusaders + deltaAmazons) > 0; } private void recruit() { // R warlocks crusaders amazons corsairs bishops necros architects int peonsAvailable = Math.max(0, thisTown.getPeons() - round); int corsairNeed = calcCorsairsNeeded(thisTown); int goldForNecros = Math.min(thisTown.getCorpses(), thisTown.getNecros() * NECRO_RAISE_CAPACITY) * GOLD_PER_RESURRECTION; int goldAvailable = thisTown.getGold() - thisTown.getBishops() * GOLD_PER_CONVERSION - goldForNecros - GOLD_COST_BUILDING + calcWages(thisTown) - (calcCashflow(thisTown) < GOLD_MAX_DEBT ? (corsairNeed * CORSAIR_SURVEILLANCE_RATIO * GOLD_PER_STEAL) : 0); int corsairGoldAvailable = thisTown.getGold() + calcWages(thisTown) - goldForNecros; boolean onlyCorsair = false; if (goldAvailable < 0) { if (corsairGoldAvailable > 0) { onlyCorsair = true; goldAvailable = corsairGoldAvailable; } else { System.out.println("W"); return; } } int necroNeed = Math.max(0, (int) Math.ceil(1.0 * thisTown.getCorpses() / NECRO_RAISE_CAPACITY) - thisTown.getNecros()); necroNeed = Math.max(necroNeed, Math.min(peonsAvailable, calcOtherNecrosNeeded() / 3)); int architectNeed = Math.max(0, ARCHITECTS - thisTown.getArchitects()); int necros = 0; if (!onlyCorsair) { int necroCost = GOLD_RECRUIT_NECRO + GOLD_PER_RESURRECTION * NECRO_RAISE_CAPACITY - GOLD_PER_NECRO; necros = Math.min(necroNeed, goldAvailable / necroCost); goldAvailable -= necros * necroCost; peonsAvailable -= necros; } if (willAttackSoon()) { corsairNeed = calcCorsairSpread(thisTown) * 2 - thisTown.getCorsairs(); } corsairNeed = (int) Math.max(corsairNeed, calcOtherCorsairsNeeded()); int corsairCost = GOLD_RECRUIT_CORSAIR - GOLD_PER_CORSAIR; int corsairs = Math.min(corsairNeed, peonsAvailable); corsairs = Math.min(corsairs, goldAvailable / corsairCost); goldAvailable -= corsairs * corsairCost; peonsAvailable -= corsairs; int architects = 0; if (!onlyCorsair) { int architectCost = GOLD_RECRUIT_ARCHITECT - GOLD_PER_ARCHITECT; architects = Math.min(architectNeed, peonsAvailable); architects = Math.min(architects, goldAvailable / architectCost); goldAvailable -= architects * architectCost; peonsAvailable -= architects; } int bishops = 0; if (!onlyCorsair) { int peonParts; if (round <= 50) { peonParts = 20; } else if (round <= 70) { peonParts = 15; } else if (round <= 90) { peonParts = 10; } else if (round <= 95) { peonParts = 5; } else { peonParts = 3; } int peonsLeft = Math.max(0, thisTown.getPeons() - (necros + corsairs + architects)); bishops = (int) Math.min(Math.min(peonsAvailable, peonsLeft / peonParts), goldAvailable / (GOLD_RECRUIT_BISHOP + GOLD_PER_CONVERSION - GOLD_PER_BISHOP)); } if (corsairs > 0 || bishops > 0 || necros > 0 || architects > 0) { System.out.println("R 0 0 0 " + corsairs + " " + bishops + " " + necros + " " + architects); } else { System.out.println("W"); } } private int calcCashflow(Town town) { int taxes = (town.getSurvivingPeons() * GOLD_PER_PEON); taxes += ((town.getWarlocks() + town.getBishops() + town.getNecros()) * (town.getTemple() * GOLD_PER_TEMPLE)); taxes += ((town.getCrusaders() + town.getAmazons()) * (town.getBarracks() * GOLD_PER_BARRACKS)); taxes += ((town.getSurvivingPeons() + town.getCorsairs()) * (town.getEstate() * GOLD_PER_ESTATE)); taxes += (town.getPalace() * GOLD_PER_PALACE); int wages = calcWages(town); return taxes + wages; } private int calcWages(Town town) { int wages = (town.getWarlocks() * GOLD_PER_WARLOCK); wages += (town.getCrusaders() * GOLD_PER_CRUSADER); wages += (town.getAmazons() * GOLD_PER_AMAZON); wages += (town.getCorsairs() * GOLD_PER_CORSAIR); wages += (town.getBishops() * GOLD_PER_BISHOP); wages += (town.getNecros() * GOLD_PER_NECRO); wages += (town.getArchitects() * GOLD_PER_ARCHITECT); return wages; } private int calcCorsairSpread(Town calcTown) { int outlaws = 0; for (Town town : outlawTowns) { outlaws += town.getPopulation(); } return (int) Math.ceil(1.0 * Math.floorDiv(outlaws, (playerTowns.size() + myTowns.size())) / CORSAIR_SURVEILLANCE_RATIO); } private int calcCorsairsNeeded(Town town) { return Math.max(0, calcCorsairSpread(town) - town.getCorsairs()); } private int calcFreeCorsairs(Town town) { return Math.max(0, town.getCorsairs() - calcCorsairSpread(town)); } private int calcOtherNecrosNeeded() { int necrosNeed = 0; for (Town town : myTowns) { if (town == thisTown) { continue; } necrosNeed += Math.max(0, (int) Math.ceil(1.0 * town.getCorpses() / NECRO_RAISE_CAPACITY) - town.getNecros()); } int necrosAvailable = Math.max(0, thisTown.getNecros() - (int) Math.ceil(1.0 * thisTown.getCorpses() / NECRO_RAISE_CAPACITY)); return Math.max(0, necrosNeed - necrosAvailable); } private int calcOtherCorsairsNeeded() { int corsairsNeed = 0; for (Town town : myTowns) { if (town == thisTown) { continue; } corsairsNeed += calcCorsairsNeeded(town); } return Math.max(0, corsairsNeed - calcFreeCorsairs(thisTown)); } private void convert() { // C destinationId warlocks crusaders amazons final int MIN_CONVERT_PERCENTAGE = 10; int goldAvailable = thisTown.getGold() - thisTown.getCorpses() * GOLD_PER_RESURRECTION - GOLD_COST_BUILDING - (calcCashflow(thisTown) < GOLD_MAX_DEBT ? (calcCorsairsNeeded(thisTown) * CORSAIR_SURVEILLANCE_RATIO * GOLD_PER_STEAL) : 0); if (goldAvailable < 0) { System.out.println("W"); return; } final int canConvert = Math.min(thisTown.getBishops(), goldAvailable / GOLD_PER_CONVERSION); if (canConvert == 0) { System.out.println("W"); return; } List<Town> useTowns = calcStrongestPlayers(); List<Town> afterFilter = useTowns.stream().filter(a -> a.getSoldiers() > canConvert / MIN_CONVERT_PERCENTAGE).collect(Collectors.toList()); if (afterFilter.size() == 0) { if (playerTowns.size() > 0) { useTowns = playerTowns; } else { useTowns = outlawTowns; } } afterFilter = useTowns.stream().filter(a -> a.getSoldiers() > canConvert).collect(Collectors.toList()); float getNear = 1.0f; while (afterFilter.size() == 0) { getNear -= 0.1f; final float toLower = getNear; afterFilter = useTowns.stream().filter(a -> a.getSoldiers() > canConvert * toLower).collect(Collectors.toList()); } Town smallestTown = afterFilter.stream().min((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); Town convertTown; if (smallestTown.getSoldiers() < canConvert / MIN_CONVERT_PERCENTAGE) { convertTown = useTowns.stream().max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); } else { convertTown = smallestTown; } int leftToConvert = canConvert; int warlocks = Math.min(leftToConvert, convertTown.getWarlocks()); leftToConvert -= warlocks; int crusaders = Math.min(leftToConvert, convertTown.getCrusaders()); leftToConvert -= crusaders; int amazons = Math.min(leftToConvert, convertTown.getAmazons()); leftToConvert -= amazons; System.out.println("C " + convertTown.getId() + " " + warlocks + " " + crusaders + " " + amazons); } private void attack() { // A destinationId warlocks crusaders amazons Town strongestTown; if (playerTowns.size() > 0) { strongestTown = playerTowns.stream().max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); if (thisTown.getSoldiers() / 3 <= strongestTown.getSoldiers()) { System.out.println("W"); return; } } strongestTown = calcStrongestPlayers().stream().max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); int warlockNeed = strongestTown.getWarlocks() + strongestTown.getAmazons(); int crusaderNeed = strongestTown.getCrusaders() + strongestTown.getWarlocks(); int amazonNeed = strongestTown.getAmazons() + strongestTown.getCrusaders(); int deltaWarlocks = thisTown.getWarlocks() - warlockNeed; int deltaCrusaders = thisTown.getCrusaders() - crusaderNeed; int deltaAmazons = thisTown.getAmazons() - amazonNeed; if ((deltaWarlocks + deltaCrusaders + deltaAmazons) > 0) { // calc Needed Troops int warlocks = Math.min(thisTown.getWarlocks(), warlockNeed); int crusaders = Math.min(thisTown.getCrusaders(), crusaderNeed); int amazons = Math.min(thisTown.getAmazons(), amazonNeed); if ((warlocks + crusaders + amazons) == 0) { warlocks = 1; crusaders = 1; amazons = 1; } else { while (deltaWarlocks < 0 || deltaCrusaders < 0 || deltaAmazons < 0) { if (deltaWarlocks < 0) { deltaCrusaders += deltaWarlocks; crusaders -= deltaWarlocks; deltaWarlocks = 0; } if (deltaCrusaders < 0) { deltaAmazons += deltaCrusaders; amazons -= deltaCrusaders; deltaCrusaders = 0; } if (deltaAmazons < 0) { deltaWarlocks += deltaAmazons; warlocks -= deltaAmazons; deltaAmazons = 0; } } } System.out.println("A " + strongestTown.getId() + " " + warlocks + " " + crusaders + " " + amazons); } else { System.out.println("W"); } } private void resurrect() { // R corpses int goldAvailable = thisTown.getGold(); if (goldAvailable < 0) { System.out.println("W"); return; } int raise = Math.min(thisTown.getCorpses(), goldAvailable / GOLD_PER_RESURRECTION); if (raise > 0) { System.out.println("R " + raise); } else { System.out.println("W"); } } private void move() { if (myTowns.size() == 1) { System.out.println("W"); return; } // M destinationId warlocks crusaders amazons corsairs bishops necros architects // T DestinationId Gold int thisStolenGold = calcCorsairsNeeded(thisTown) * CORSAIR_SURVEILLANCE_RATIO * GOLD_PER_STEAL; int thisGoldAvailable = Math.max(-GOLD_MAX_DEBT, thisTown.getGold() - thisStolenGold); int thisCashFlow = calcCashflow(thisTown); if (thisGoldAvailable + thisCashFlow <= 0) { // Give up the town Town sendToTown = myTowns.stream().filter(a -> a.getId() != thisTown.getId()).max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); System.out.print("M " + sendToTown.getId() + " " + thisTown.getWarlocks() + " " + thisTown.getCrusaders() + " " + thisTown.getAmazons() + " " + thisTown.getCorsairs() + " " + thisTown.getBishops() + " " + thisTown.getNecros() + " " + thisTown.getArchitects()); return; } thisGoldAvailable += thisCashFlow; int thisCostOfBishop = thisTown.getTemple() * GOLD_PER_TEMPLE + GOLD_PER_BISHOP; int thisCostOfNecro = thisTown.getTemple() * GOLD_PER_TEMPLE + GOLD_PER_NECRO; int thisCostOfWarlock = thisTown.getTemple() * GOLD_PER_TEMPLE + GOLD_PER_WARLOCK; int thisCostOfCrusader = thisTown.getBarracks() * GOLD_PER_BARRACKS + GOLD_PER_CRUSADER; int thisCostOfAmazon = thisTown.getBarracks() * GOLD_PER_BARRACKS + GOLD_PER_AMAZON; int thisCostOfCorsair = thisTown.getEstate() * GOLD_PER_ESTATE + GOLD_PER_CORSAIR; int thisCorsairsAvailable = calcFreeCorsairs(thisTown); int thisNecrosAvailable = Math.max(0, thisTown.getNecros() - (int) Math.ceil(1.0 * thisTown.getCorpses() / NECRO_RAISE_CAPACITY)); int thisBishopsAvailable = Math.max(0, thisTown.getBishops() - (int) Math.ceil(1.0 * thisTown.getPeons() / BISHOP_PRAYER_CAPACITY)); int thisArchitectsAvailable = Math.max(0, thisTown.getArchitects() - ARCHITECTS); int strongestTownSoldiers = 0; if (playerTowns.size() > 0) { Town strongestTown = playerTowns.stream().max((a, b) -> a.getSoldiers() - b.getSoldiers()).get(); strongestTownSoldiers = strongestTown.getSoldiers(); } int thisSoldiersAvailable = Math.max(0, thisTown.getSoldiers() - strongestTownSoldiers); int thisWarlocksAvailable = thisSoldiersAvailable / 3; thisSoldiersAvailable -= thisWarlocksAvailable; int thisCrusadersAvailable = thisSoldiersAvailable / 2; thisSoldiersAvailable -= thisCrusadersAvailable; int thisAmazonsAvailable = thisSoldiersAvailable; int warlockDelta = thisWarlocksAvailable - thisTown.getWarlocks(); int crusaderDelta = thisCrusadersAvailable - thisTown.getCrusaders(); int amazonDelta = thisAmazonsAvailable - thisTown.getAmazons(); while (warlockDelta > 0 || crusaderDelta > 0 || amazonDelta > 0) { if (warlockDelta > 0) { thisWarlocksAvailable -= warlockDelta; thisCrusadersAvailable += warlockDelta; crusaderDelta += warlockDelta; warlockDelta = 0; } if (crusaderDelta > 0) { thisCrusadersAvailable -= crusaderDelta; thisAmazonsAvailable += crusaderDelta; amazonDelta += crusaderDelta; crusaderDelta = 0; } if (amazonDelta > 0) { thisAmazonsAvailable -= amazonDelta; thisWarlocksAvailable += amazonDelta; warlockDelta += amazonDelta; amazonDelta = 0; } } // Calc loosing income for each x the town sends int tempThisGoldAvailable = thisGoldAvailable; if (thisCostOfCorsair > 0) { thisCorsairsAvailable = Math.min(thisCorsairsAvailable, tempThisGoldAvailable / thisCostOfCorsair); tempThisGoldAvailable -= thisCorsairsAvailable * thisCostOfCorsair; } // else dont plus the gold - would get too complicated if (thisCostOfWarlock > 0) { thisWarlocksAvailable = Math.min(thisWarlocksAvailable, tempThisGoldAvailable / thisCostOfWarlock); tempThisGoldAvailable -= thisWarlocksAvailable * thisCostOfWarlock; } if (thisCostOfCrusader > 0) { thisCrusadersAvailable = Math.min(thisCrusadersAvailable, tempThisGoldAvailable / thisCostOfCrusader); tempThisGoldAvailable -= thisCrusadersAvailable * thisCostOfCrusader; } if (thisCostOfAmazon > 0) { thisAmazonsAvailable = Math.min(thisAmazonsAvailable, tempThisGoldAvailable / thisCostOfAmazon); tempThisGoldAvailable -= thisAmazonsAvailable * thisCostOfAmazon; } if (thisCostOfNecro > 0) { thisNecrosAvailable = Math.min(thisNecrosAvailable, tempThisGoldAvailable / thisCostOfNecro); tempThisGoldAvailable -= thisNecrosAvailable * thisCostOfNecro; } if (thisCostOfBishop > 0) { thisBishopsAvailable = Math.min(thisBishopsAvailable, tempThisGoldAvailable / thisCostOfBishop); tempThisGoldAvailable -= thisBishopsAvailable * thisCostOfBishop; } boolean checkGoldNeed; boolean needsGold; for (int i = 0; i < 2; i++) { checkGoldNeed = i == 0; for (Town town : myTowns) { if (town == thisTown) { continue; } needsGold = false; int costOfBishop = town.getTemple() * GOLD_PER_TEMPLE + GOLD_PER_BISHOP; int costOfNecro = town.getTemple() * GOLD_PER_TEMPLE + GOLD_PER_NECRO; int costOfWarlock = town.getTemple() * GOLD_PER_TEMPLE + GOLD_PER_WARLOCK; int costOfCrusader = town.getBarracks() * GOLD_PER_BARRACKS + GOLD_PER_CRUSADER; int costOfAmazon = town.getBarracks() * GOLD_PER_BARRACKS + GOLD_PER_AMAZON; int costOfCorsair = town.getEstate() * GOLD_PER_ESTATE + GOLD_PER_CORSAIR; int corsairsNeed = calcCorsairsNeeded(town); int sendCorsairs = Math.min(corsairsNeed, thisCorsairsAvailable); int goldStolen = corsairsNeed * CORSAIR_SURVEILLANCE_RATIO * GOLD_PER_STEAL; int goldAvailable = town.getGold() - goldStolen; int goldAvailableWithCorsairs = Math.max(-GOLD_MAX_DEBT, goldAvailable + sendCorsairs * CORSAIR_SURVEILLANCE_RATIO * GOLD_PER_STEAL); goldAvailable = Math.max(-GOLD_MAX_DEBT, goldAvailable); int cashflow = calcCashflow(town); if (goldAvailable + cashflow < 0) { needsGold = true; } tryToSwim: if (goldAvailableWithCorsairs < 0) { int potentialCashflow = cashflow + sendCorsairs * costOfCorsair; if (goldAvailableWithCorsairs + potentialCashflow >= 0) { break tryToSwim; } else { int potentialGoldAvailable = goldAvailableWithCorsairs + potentialCashflow; if (costOfWarlock > 0) { potentialGoldAvailable += thisWarlocksAvailable * costOfWarlock; } if (costOfCrusader > 0) { potentialGoldAvailable += thisCrusadersAvailable * costOfCrusader; } if (costOfAmazon > 0) { potentialGoldAvailable += thisAmazonsAvailable * costOfAmazon; } if (costOfNecro > 0) { potentialGoldAvailable += thisNecrosAvailable * costOfNecro; } if (costOfBishop > 0) { potentialGoldAvailable += thisBishopsAvailable * costOfBishop; } if (potentialGoldAvailable >= 0) { System.out.print("M " + town.getId() + " " + thisWarlocksAvailable + " " + thisCrusadersAvailable + " " + thisAmazonsAvailable + " " + sendCorsairs + " " + thisBishopsAvailable + " " + thisNecrosAvailable + " 0"); return; } } // Last hope, check if enough gold can rescue the town from revolt int goldNeeded = -(town.getGold() - goldStolen + cashflow); if (thisGoldAvailable >= goldNeeded) { System.out.println("T " + town.getId() + " " + goldNeeded); return; } System.out.println("W"); continue; } if (checkGoldNeed && !needsGold) { continue; } goldAvailable = goldAvailableWithCorsairs; goldAvailable += cashflow + sendCorsairs * costOfCorsair; int sendNecros = 0; int sendBishops = 0; int sendWarlocks = 0; int sendCrusaders = 0; int sendAmazons = 0; int sendArchitects = 0; int soldiersNeed = Math.max(0, strongestTownSoldiers - town.getSoldiers()); int lastNeededSoldiers = 0; while (soldiersNeed > 0 && (thisWarlocksAvailable > 0 || thisCrusadersAvailable > 0 || thisAmazonsAvailable > 0) && soldiersNeed != lastNeededSoldiers) { lastNeededSoldiers = soldiersNeed; if (thisWarlocksAvailable > 0) { goldAvailable += costOfWarlock; if (goldAvailable < 0) { goldAvailable -= costOfWarlock; } else { soldiersNeed--; thisWarlocksAvailable--; sendWarlocks++; } } if (thisCrusadersAvailable > 0) { goldAvailable += costOfCrusader; if (goldAvailable < 0) { goldAvailable -= costOfCrusader; } else { soldiersNeed--; thisCrusadersAvailable--; sendCrusaders++; } } if (thisAmazonsAvailable > 0) { goldAvailable += costOfAmazon; if (goldAvailable < 0) { goldAvailable -= costOfAmazon; } else { soldiersNeed--; thisAmazonsAvailable--; sendAmazons++; } } } int necrosNeed = Math.max(0, (int) Math.ceil(1.0 * town.getCorpses() / NECRO_RAISE_CAPACITY) - town.getNecros()); int necrosCanAfford = costOfNecro < 0 ? Math.min(necrosNeed, goldAvailable / -costOfNecro) : necrosNeed; if (necrosCanAfford > 0) { sendNecros = Math.min(necrosCanAfford, thisNecrosAvailable); goldAvailable += sendNecros * costOfNecro; } int bishopsNeed = Math.max(0, (int) Math.ceil(1.0 * town.getPeons() / BISHOP_PRAYER_CAPACITY) - town.getBishops()); int bishopsCanAfford = costOfBishop < 0 ? Math.min(bishopsNeed, goldAvailable / -costOfBishop) : bishopsNeed; if (bishopsCanAfford > 0) { sendBishops = Math.min(bishopsCanAfford, thisBishopsAvailable); goldAvailable += sendBishops * costOfBishop; } int architectsNeed = Math.max(0, (int) Math.ceil(1.0 * COMPLETION_NEEDED / COMPLETION_PER_ARCHITECT) - thisTown.getArchitects()); int architectsCanAfford = Math.min(architectsNeed, goldAvailable / Math.abs(GOLD_PER_ARCHITECT)); sendArchitects = Math.min(architectsCanAfford, thisArchitectsAvailable); if (sendWarlocks > 0 || sendCrusaders > 0 || sendAmazons > 0 || sendCorsairs > 0 || sendBishops > 0 || sendNecros > 0 || sendArchitects > 0) { System.out.print("M " + town.getId() + " " + sendWarlocks + " " + sendCrusaders + " " + sendAmazons + " " + sendCorsairs + " " + sendBishops + " " + sendNecros + " " + sendArchitects); return; } } } System.out.println("W"); } private void build() { // B building building building... // (T: Temple, B: Barracks, E: Estate, P: Palace) int goldAvailable = thisTown.getGold() - (calcCashflow(thisTown) < GOLD_MAX_DEBT ? (calcCorsairsNeeded(thisTown) * CORSAIR_SURVEILLANCE_RATIO * GOLD_PER_STEAL) : 0); if (goldAvailable >= GOLD_COST_BUILDING) { char building = 'E'; int templeUnits = thisTown.getWarlocks() + thisTown.getBishops() + thisTown.getNecros(); int barracksUnits = thisTown.getCrusaders() + thisTown.getAmazons(); int estateUnits = thisTown.getCorsairs() + thisTown.getPeons(); if (templeUnits > barracksUnits) { if (templeUnits > estateUnits) { building = 'T'; } } else { if (barracksUnits > estateUnits) { building = 'B'; } } System.out.println("B " + building); } else { System.out.println("W"); } } private class Town { private final int ownerId; private final int id; private final int gold; private final int corpses; private final int warlocks; private final int crusaders; private final int amazons; private final int corsairs; private final int bishops; private final int necros; private final int architects; private final int peons; private final int temple; private final int barracks; private final int estate; private final int palace; public Town(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); id = Integer.parseInt(args[1]); gold = Integer.parseInt(args[2]); corpses = Integer.parseInt(args[3]); warlocks = Integer.parseInt(args[4]); crusaders = Integer.parseInt(args[5]); amazons = Integer.parseInt(args[6]); corsairs = Integer.parseInt(args[7]); bishops = Integer.parseInt(args[8]); necros = Integer.parseInt(args[9]); architects = Integer.parseInt(args[10]); peons = Integer.parseInt(args[11]); temple = Integer.parseInt(args[12]); barracks = Integer.parseInt(args[13]); estate = Integer.parseInt(args[14]); palace = Integer.parseInt(args[15]); } public int getOwnerId() { return ownerId; } public int getId() { return id; } public int getGold() { return gold; } public int getCorpses() { return corpses; } public int getWarlocks() { return warlocks; } public int getCrusaders() { return crusaders; } public int getAmazons() { return amazons; } public int getCorsairs() { return corsairs; } public int getBishops() { return bishops; } public int getNecros() { return necros; } public int getArchitects() { return architects; } public int getPeons() { return peons; } public int getSurvivingPeons() { int peons = this.peons; int zombies = Math.floorDiv(corpses, ZOMBIE_WAKING_CHANCE); peons = Math.max(0, peons - zombies); int demons = Math.floorDiv(peons - (bishops * BISHOP_PRAYER_CAPACITY), DEMON_SUMMON_CHANCE); peons = Math.max(0, peons - demons); if (round % BIRTH_ROUND == 0) { peons += Math.floorDiv(peons, 2); } return peons; } public int getTemple() { return temple; } public int getBarracks() { return barracks; } public int getEstate() { return estate; } public int getPalace() { return palace; } public int getSoldiers() { return getWarlocks() + getCrusaders() + getAmazons(); } public int getUnits() { return getSoldiers() + getCorsairs() + getBishops() + getNecros() + getArchitects(); } public int getPopulation() { return getUnits() + getPeons(); } public boolean isMine() { return getOwnerId() == playerID; } public boolean isThisTown() { return id == thisTownID; } } } ``` [Answer] # Machiavelli, Python 2 Lord Machiavelli is experienced in the politics and military domains required to succeed. He has developed a complex logic that directs his cunning strategy, now he watches from the shadows as his plan unfolds... ``` import sys, re from random import * from operator import itemgetter import cPickle (PLAYER, TOWN, GOLD, CORPSES, WARLOCKS, CRUSADERS, AMAZONS, CORSAIRS, BISHOPS, NECROMANCERS, ARCHITECTS, PEONS, TEMPLES, BARRACKS, ESTATES, PALACES) = range(16) def getfighters(t): return sum(t[WARLOCKS:WARLOCKS+3]) def threat(t): return t[2] + sum(t[4:12])*12 + sum(t[12:16])*200 def spyon(t): return ( t[2] + min(30,t[3])*5 + t[11]*10 + sum(t[12:16])*200 - getfighters(t)*20 ) def needs(t): return [bandits/5+1, t[PEONS]/50+1, t[CORPSES]/5+1, 7] def wants(t): return [max(0, g-h) for g,h in zip(needs(t), t[7:11])] def helpcheck(t): return sum(wants(t)) def choose(frequency, picks, span): 'Return <picks> counts using samples from <frequency> in list <span>' choices = [choice(frequency) for i in range(picks)] return [choices.count(i) for i in range(span)] if len(sys.argv) < 2: print 5, 15, 10, 20, 3, 4, 7, 36 else: parts = sys.argv[1].split(';') turn, phase, me, thistown = [int(parts.pop(0)) for i in range(4)] towns = [map(int, re.split(r'_', town)) for town in parts] # Analysis: enemy = [t for t in towns if t[PLAYER] != me] mytowns = [t for t in towns if t[PLAYER] == me] here = [t for t in mytowns if t[TOWN] == thistown][0] otherids = [t[TOWN] for t in enemy] fighters = sorted(enemy, key=getfighters) rich = sorted(enemy, key=itemgetter(GOLD)) threats = sorted(enemy, key=threat) attractive = sorted(enemy, key=spyon) # Useful numbers: avgfighters = sum(map(getfighters, enemy)) / len(enemy) wages = getfighters(here) + sum(here[CORSAIRS:CORSAIRS+4]) * 2 outlaws = sum(sum(t[4:12]) for t in towns if t[PLAYER] == -1) freetowns = len([t for t in towns if t[PLAYER] != -1]) bandits = outlaws / freetowns # Depends on above needhelp = sorted(mytowns, key=helpcheck) needhelp.remove(here) try: plans = cPickle.load(open('Machiavelli.txt', 'rb')) except: plans = {} bribes, raises, gobuild = plans.get(thistown, (0,0,'')) output = 'W' if phase == 2: output = 'S %s 100' % rich[-1][TOWN] # take from the rich ... elif phase == 3: # Decide strategy here: cash = here[GOLD] - wages forces = getfighters(here) raises = min(here[NECROMANCERS]*5, here[CORPSES], cash/20) cash -= raises * 20 bribes = trainftr = trainextra = 0 gobuild = '' if forces < avgfighters: bribes = min(here[BISHOPS], cash/50) cash -= bribes * 50 trainftr = min(max(0, here[PEONS]-30), cash/10) cash -= trainftr * 10 if cash > 200 and turn % 2 == 0: gobuild = choice('EEB') cash -= 200 bribes2 = min(here[BISHOPS] - bribes, cash/50) cash -= bribes2 * 50 bribes += bribes2 trainextra = min(max(0, here[PEONS]-30), cash/50) # Write plan to file: plans[thistown] = (bribes, raises, gobuild) cPickle.dump(plans, open('Machiavelli.txt', 'wb'), -1) # Output recruitment decision: if trainftr + trainextra: getutil = wants(here) if sum(getutil) > trainextra: utilbias = ( [0]*getutil[0]*3 + [1]*getutil[1]*3 + [2]*(getutil[2]) + [3]*(getutil[3]) ) getutil = choose(utilbias, trainextra, 4) getftr = choose([0,1,1,2], trainftr, 3) getpers = getftr + getutil if sum(getutil) < trainextra: othernum = trainextra - sum(getutil) others = choose([0,1,1,2,3,4,6], othernum, 7) getpers = [p+q for p,q in zip(getpers, others)] output = 'R %u %u %u %u %u %u %u' % tuple(getpers) elif phase == 6: if bribes: soldiers = choose([0,1,2], bribes, 3) target = fighters[-1][TOWN] output = 'C %s %s %s %s' % tuple([target] + soldiers) elif phase == 7: if getfighters(here) > avgfighters * 1.3: myarmy = here[WARLOCKS : WARLOCKS+3] raiders = sum(myarmy) / 2 for n in range(raiders): force = [min(myarmy[i], n) for i in (0,1,2)] if sum(force) >= raiders: break for target in attractive[::-1]: if raiders > getfighters(target) * 2.5: output = 'A %s %s %s %s' % tuple([target[TOWN]] + force) break elif phase == 8: if raises: output = 'R %s' % raises elif phase == 9: if needhelp: town = needhelp[-1] excess = [max(0, g-h) for g,h in zip(here[7:11], needs(here))] send = [min(g, h) for g,h in zip(excess, wants(town))] if sum(send) > 0: output = 'M %u 0 0 0 %u %u %u %u' % tuple([town[TOWN]] + send) elif phase == 11: if gobuild: output = 'B %s' % gobuild print output ``` [Answer] # Monarch (Ruby) Monarch is more than a mere King, so he'll not fight others until he's sure that his army can crush his opponents and show his overwhelming power. Meanwhile, he gets cozy in his base and asks for tributes from the insignificant insects. Anf of course, he likes Ruby and rubies. ``` $BONUS = 1.5 class Town attr_accessor :player, :town, :gold, :corpses, :warlocks, :crusaders, :amazons, :corsairs, :bishops, :necromancers, :architects, :peons, :temples, :barracks, :estates, :palaces def initialize(arg) args = arg.split("_") @player = args[0].to_i @town = args[1].to_i @gold = args[2].to_i @corpses = args[3].to_i @warlocks = args[4].to_i @crusaders = args[5].to_i @amazons = args[6].to_i @corsairs = args[7].to_i @bishops = args[8].to_i @necromancers = args[9].to_i @architects = args[10].to_i @peons = args[11].to_i @temples = args[12].to_i @barracks = args[13].to_i @estates = args[14].to_i @palaces = args[15].to_i end def soldiers @warlocks + @crusaders + @amazons end def units self.soldiers + @corsairs + @bishops + @necromancers + @architects end def citizens self.units + @peons end def buildings @temples + @barracks + @estates + @palaces end def cash @gold - (self.units * 2) - 50 end def flesh @peons - (self.units * 2 / 5) end end def stronger(aW, aC, aA, dW, dC, dA) aW - [[0, aW - dW].max, dA].min + ([[0, aW - dW].max, dA].min * $BONUS) + aC - [[0, aC - dC].max, dW].min + ([[0, aC - dC].max, dW].min * $BONUS) + aA - [[0, aA - dA].max, dC].min + ([[0, aA - dA].max, dC].min * $BONUS) > dW - [[0, dW - aW].max, aA].min + ([[0, dW - aW].max, aA].min * $BONUS) + dC - [[0, dC - aC].max, aW].min + ([[0, dC - aC].max, aW].min * $BONUS) + dA - [[0, dA - aA].max, aC].min + ([[0, dA - aA].max, aC].min * $BONUS) end if ARGV.size < 1 puts "12 12 12 8 2 2 2 50" else args = ARGV[0].split(";") round = args[0].to_i phase = args[1].to_i thisPlayer = args[2].to_i thisTownId = args[3].to_i towns, myTowns, enemyTowns = Array.new, Array.new, Array.new args[4..-1].each {|arg|arg.split(";").each {|t|towns.push(Town.new(t))}} towns.each {|town|town.player == thisPlayer ? myTowns.push(town) : enemyTowns.push(town)} thisTown = towns[towns.index{|t|t.town == thisTownId}] strongestTown = enemyTowns.sort{|x,y|y.soldiers<=>x.soldiers}.fetch(0) weakestTown = enemyTowns.sort{|x,y|x.soldiers<=>y.soldiers}.fetch(0) baseTown = myTowns.sort{|x,y|y.peons<=>x.peons}.fetch(0) case phase when 2 puts "S " + strongestTown.town.to_s + " " + thisTown.corsairs.to_s when 3 if (thisTown.cash > 90) recruits = [[(thisTown.cash - 90) / 10, thisTown.flesh].min / 5, 0].max puts "R " + recruits.to_s + " " + recruits.to_s + " " + (recruits*3).to_s + " " + [0, 2 - thisTown.corsairs].max.to_s + " " + [0, 2 - thisTown.bishops].max.to_s + " " + [0, 2 - thisTown.necromancers].max.to_s + " " + [0, 2 - thisTown.architects].max.to_s else puts "W" end when 6 converts = [[thisTown.cash / 50, thisTown.bishops].min / 5, 0].max puts "C " + strongestTown.town.to_s + " " + (converts*3).to_s + " " + converts.to_s + " " + converts.to_s when 7 if round > 10 if stronger(thisTown.warlocks / 6, thisTown.crusaders / 6, thisTown.amazons / 6, strongestTown.warlocks, strongestTown.crusaders, strongestTown.amazons) puts "A " + strongestTown.town.to_s + " " + (thisTown.warlocks/4).to_s + " " + (thisTown.crusaders/4).to_s + " " + (thisTown.amazons/4).to_s elsif stronger(thisTown.warlocks / 6, thisTown.crusaders / 6, thisTown.amazons / 6, weakestTown.warlocks, weakestTown.crusaders, weakestTown.amazons) puts "A " + weakestTown.town.to_s + " " + (thisTown.warlocks/4).to_s + " " + (thisTown.crusaders/4).to_s + " " + (thisTown.amazons/4).to_s else puts "W" end else puts "W" end when 8 puts "R 10" when 9 if thisTown.town != baseTown.town if thisTown.soldiers > 0 puts "M " + baseTown.town.to_s + " " + thisTown.warlocks.to_s + " " + thisTown.crusaders.to_s + " " + thisTown.amazons.to_s else puts "T " + baseTown.town.to_s + " " + thisTown.cash end else puts "W" end when 11 if thisTown.town == baseTown.town and thisTown.cash > 200 puts "B B" else puts "W" end else puts "W" end end ``` To run this script, you need a Ruby 1.9.3 interpreter. Run with : `ruby Monarch.rb` [Answer] I only can write 30000 signs in one answer xD So here are my bugs that i found: Moogie already reported this one: `int totalConvertible = (warlocksConvertible + crusadersConvertible + amazonsConvertible);` executeMovement: `if (source.getCorsairs() >= corsairsCount) {` executeTheft: used Source instead of Destination. But could you check, if the calculation is correct then? My recommendation would be: `int goldReserve = destination.getGold() + GOLD_MAX_DEBT > 0 ? destination.getGold() + GOLD_MAX_DEBT : GOLD_MAX_DEBT - Math.abs(destination.getGold());` And executeRecruitment had an bug, that if the town had not enough peons, they could recruit more than they had peons, if they could afford the recruitment. So I rewrote the method that it concerns peons and gold available: ``` private void executeRecruitment(Command support) { Town source = support.getSource(); try { String[] args = support.getArgs(); if (support.getCommand().equals("R") && args.length == 7) { int goldAvailable = source.getGold(); if (goldAvailable <= 0) { return; } int warlocksCount = Math.max(0, Integer.parseInt(args[0])); int crusadersCount = Math.max(0, Integer.parseInt(args[1])); int amazonsCount = Math.max(0, Integer.parseInt(args[2])); int corsairsCount = Math.max(0, Integer.parseInt(args[3])); int bishopsCount = Math.max(0, Integer.parseInt(args[4])); int necromancersCount = Math.max(0, Integer.parseInt(args[5])); int architectsCount = Math.max(0, Integer.parseInt(args[6])); int originalWarlocksCount = warlocksCount; int originalCrusadersCount = crusadersCount; int originalAmazonsCount = amazonsCount; int originalCorsairsCount = corsairsCount; int originalBishopsCount = bishopsCount; int originalNecromancersCount = necromancersCount; int originalArchitectsCount = architectsCount; int unitsToRecruits = warlocksCount + crusadersCount + amazonsCount + corsairsCount + bishopsCount + necromancersCount + architectsCount; int peonsAvailable = source.getPeons(); int recruitableUnits = Math.min(unitsToRecruits, peonsAvailable); if (recruitableUnits != unitsToRecruits) { RandomNumberGenerator random = new RandomNumberGenerator(); int[] recruits = random.genNumberWithLimits(recruitableUnits, new int[] { warlocksCount, crusadersCount, amazonsCount, corsairsCount, bishopsCount, necromancersCount, architectsCount }); warlocksCount = recruits[0]; crusadersCount = recruits[1]; amazonsCount = recruits[2]; corsairsCount = recruits[3]; bishopsCount = recruits[4]; necromancersCount = recruits[5]; architectsCount = recruits[6]; } int wouldCost; int index = 1; boolean tooExpensive = true; do { wouldCost = warlocksCount * GOLD_RECRUIT_WARLOCK + crusadersCount * GOLD_RECRUIT_CRUSADER + amazonsCount * GOLD_RECRUIT_AMAZON + corsairsCount * GOLD_RECRUIT_CORSAIR + bishopsCount * GOLD_PER_BISHOP + necromancersCount * GOLD_RECRUIT_NECROMANCER + architectsCount * GOLD_RECRUIT_ARCHITECT; if (goldAvailable < wouldCost) { RandomNumberGenerator random = new RandomNumberGenerator(); int[] recruits = random.genNumberWithLimits(recruitableUnits - index, new int[] { originalWarlocksCount, originalCrusadersCount, originalAmazonsCount, originalCorsairsCount, originalBishopsCount, originalNecromancersCount, originalArchitectsCount }); warlocksCount = recruits[0]; crusadersCount = recruits[1]; amazonsCount = recruits[2]; corsairsCount = recruits[3]; bishopsCount = recruits[4]; necromancersCount = recruits[5]; architectsCount = recruits[6]; } else { tooExpensive = false; } index++; } while (tooExpensive); int recruted = warlocksCount + crusadersCount + amazonsCount + corsairsCount + bishopsCount + necromancersCount + architectsCount; if (recruted > 0) { source.setWarlocks(source.getWarlocks() + warlocksCount); source.setCrusaders(source.getCrusaders() + crusadersCount); source.setAmazons(source.getAmazons() + amazonsCount); source.setCorsairs(source.getCorsairs() + corsairsCount); source.setBishops(source.getBishops() + bishopsCount); source.setNecromancers(source.getNecromancers() + necromancersCount); source.setArchitects(source.getArchitects() + architectsCount); source.setPeons(source.getPeons() - recruted); source.setGold(source.getGold() - wouldCost); if (GAME_MESSAGES) System.out.println(source.getOwner().getDisplayName() + " recruted " + recruted + " units (" + warlocksCount + " Wa / " + crusadersCount + " Cr / " + amazonsCount + " Am / " + corsairsCount + " Co / " + bishopsCount + " Bi / " + necromancersCount + " Ne / " + architectsCount + " Ar)"); } } else if (support.getCommand().equals("W")) { // Do nothing } else { if (DEBUG) System.out.println("Phase " + phase + " (Recruitment) : Invalid command by " + source.getOwner().getDisplayName() + "{" + source.getId() + "}"); } } catch (Exception e) { if (DEBUG) { System.out.println("Exception in executeRecruitment() by " + source.getOwner().getDisplayName()); e.printStackTrace(); } } } ``` ]
[Question] [ A simple regex is either: * `_` (which matches the empty string) * Any lowercase letter `a` to `z` (which matches that letter) * `r*`, where `r` is a regex (which matches `r` any number of times) * `(r|s)`, where `r` and `s` are regexes (which matches either `r` or `s`) * `(r+s)`, where `r` and `s` are regexes (which matches `r` followed by `s`) Note that due to the recursive definition, `*` can occur multiple times in a row. Here are some examples of regexes and their matches: * `(a+b)` matches only `ab` * `((a|_)+b*)` matches , `a`, `b`, `ab`, `bb`, `abb`, but not `baaa`, `aab` * `(c+(o+((l+(o+(u|_)))+r)))` matches only `color` and `colour` * `(a|b)*` matches only strings containing letters `a` and `b` (so , `ab`, `bab`, but not `abc`) * `(_***|(a+b***))` matches only the empty string or `a` followed by any number of `b`s. Your task is to write a program that takes such a regex and a string of lowercase letters, and outputs whether or not the regex matches the entire string (output should be [as described here](https://codegolf.meta.stackexchange.com/a/12308/84442)). The shortest code in bytes wins. [Answer] # [Haskell](https://www.haskell.org/), 203 bytes Nobody had done this by implementing a small regex engine yet, and I felt like it had to be done. This obviously won't win. but I'm hoping it will inspire someone to write an even more golfed regex engine. I've rewritten my solution to avoid directly parsing the regular expression into its AST. Instead, the parsing process constructs a function that is used to match a string against the input regex. The main function is `(&) :: String -> String -> Bool` which takes a string representation of a regex and a string to test, returning a boolean value. This calls to the next function which handles most of the work in parsing the regex and matching the string. Function `p :: String -> ([String] -> [String], String)` takes a string representation of a regex and returns as the first element of a tuple a function that returns a list of all possible unmatched suffixes of strings in the input list after satisfying the regex parsed from the input string. The regex fully matches the string if the empty string is contained in the list of possible unmatched suffixes. ``` r&s=elem""$fst(p r)[s] p(c:t)|c>'`'=t% \s->[t|h:t<-s,c==h]|c>'^'=t%id|(l,o:t)<-p t,(r,_:u)<-p t=u%last(r.l:[\s->r s++l s|o>'+']) m#s=s++filter(`notElem`s)(m s) ('*':t)%m=t%until(\s->s==m#s)(m#) s%m=(m,s) ``` [Try it online!](https://tio.run/##nZhRb5swEMff8yksui4GkvUdlTxMWqVJkyate@s6eqZug0ZChB21D2hfPbNJSKDBd@6iRgn5//y37zgflCWoP7Isd7v6o0plKVdB8OFJab5hdXin7icbnic6bPLF9GGa6kv2S80Xd7pZJvp6rmZ5mi7vrfjbisVjw8tZZfjr@YbpGa9nWbLdH6TbyxKMb/2pTO6sSc1UHJdMNdViGk/vw8nqQqXmp6ei1LLmD@tKfzHLeVAhXzEVTvg0mhrny5WZaLvWRcmti0pTM84gF@FEGY2vZircraBYsyRhX78zboztUcoeqwkzr81W3@r625oFtxpqXayfmZZKq6BV7dcf8lm@sgCC9v2z3soxSQTsBko1qnXSWy1rtTHHrO/4VuQQi9CuRowPPuqOJXW6IHQQOUHkQHrkFOGOsumiGA@y6YLAZGSBDRlkQwbZkEE2eJAGyMJYRKGzFAYIeDDCx8cHEn5OXlYAzmocuIFA6yEiCqLVScCuBoQHJdzRdRghk@MhB6x29gHlFJKf0nvWStyrzCL7QuR@EzmfO4oB3aCdTgMU4Qz/oAsKAACa8XAR7jzzrEHTcZBx1bmEzhzbHhneLrPe9I5NCHSPwU9pj8G3O5HxHuTFuM@KwQxjshe3F5xjk3Etv8UH8JEeuYLhKY8ztHgPo5GKijO0ZFD1uDZXQQ31saLf5wLff0cGvCBkp/cgTwrcJwbQ5nyQkRskIC4lR8DDA1kn3jKgwbtfA8MCcgCC0ikDtOucRelCCJkcD/0XzYo@7A4vOtyd@NMDWGB3doaPuWhEr16drWzA@nL@jl4RjgwS7x8l/neuQVZd/Xk4lScH/qDwXrAA8Y6UCGelAHYPdhABVykZ3zUHjD7VZ37CAxQDx/GreGTfxH9AHQNekCdFtJMB7bcVxtyFP09kK4vNH0RhhKVrCIEf5YsRGRviHilz@Yt3DBBnM5ye6twU60It5WP3VGcyOZklCTOUfeQzX/S@fa6q0n7uHxed8FoypWtmZ2gYr@VHcxSyNGWSpUbU23ptB1i10ktZvxRKjjxo4lwtqxfWDo5jFrC/7Cqw34y/Pb5i8nUjc23W3P68x2UYtjbHeXb/AA "Haskell – Try It Online") To get rid of one byte, I replaced `import Data.List; m#s=nub$s++m s` with `m#s=s++filter(`notElem`s)(m s)`. These functions aren't equivalent if there are duplicate elements in either `s` of `m s`. The new function does, however, remove all elements from `m s` that already exist in `s`, so `until` still terminates once no new suffixes are discovered by the application of `m`. # Ungolfed Code ``` import Data.List match :: String -> String -> Bool match r s =elem ""$(fst $ parseRegex r)[s] parseRegex :: String -> ([String] -> [String], String) parseRegex ('_':t) = parseKleene id t parseRegex (c:t) | c >= 'a' = parseKleene (>>=p) t where p (c':t')| c==c' = [t'] p _ = [] parseRegex ('(':t) = let (l, (o:t')) = parseRegex t in let (r, (_:t'')) = parseRegex t' in parseKleene (if o=='+' then (r.l) else (\ss-> (r ss)++(l ss))) t'' parseKleene :: ([String] -> [String]) -> String -> ([String] -> [String], String) parseKleene p ('*':t) = parseKleene p' t where p' ss | ss' <- nub$ p ss, ss /= ss' = ss ++ (p' ss') | otherwise = ss parseKleene p s = (p,s) ``` --- # [GolfScript](http://www.golfscript.com/golfscript/), 198 bytes I was able to beat my Haskell solution by implementing the first algorithm I tried in GolfScript instead of Haskell. I don't think it's interesting enough for a separate answer, so I'll just leave it here. There are likely some golfing opportunities since I learned GolfScript just for this. This solution is in the form of a block that expects the test string on the top of the stack followed by the regex string. ``` {[.;]\1+{(.96>{0[\]}{2%0{r\(\r\:s;[@]s(;\}i}{if}:i~\{(.3%}{;\2[\]\}until[.;]\+\}:r~\;{.{(.{.4%{2%{)@\m\)\;m}{)\;{.@.@m 1$|.@={\;}{\o}i}:o~}i}{;)@.@m@@\)\;m|}i}{;(:c;;{,},{(\;c=},{(;}%}i}{;}i}:m~""?} ``` [Try it online!](https://tio.run/##nZhtb5swEMff8ykstkg8dFnTTZMGapdX@wR7V1foTEmLlicBkToZ8tUzmwQCqu/MhhIR/P/d@e44G5SX3XpVpkW@r04n@TiPn/gilN78@7cHefvInxp5N7uVBfd4waMyflw@lV7Mm7yR@aqJ8iNX7JdZI2N@p2jeHLZVvm7dhLyJiiOP5Vwhcv51pjxJf8k33OfxppG@lpbz5YYtPtbz5b3kcSP5TrmOdkc9Qexrdbls@bod8aI0juVNcyM9Hqf3@hw3s1bSdpuj6/5oTtEGqvQ1dj6wKiurpMhesjd1kW/zKod1UlaQ/o5Y9rbP0ip7PkNlVbAW1L8UvMq3A3Szr/6wfMXKQ5pmZXnD0gLKVz2ygnztSIexqPMX64vOZ3vR@9VX/cV13jZcJX1aPFyjulcDjMnmfHL1PNlzxLjrdnYud9mRfXZ7j@5nN1TH/lCV2ixfOU10rUDsOLfRT1iXWewsol/FQZ0dV2VYVG0opasN1RC4TH81MSxgOy5c1rp4JxjGHTdphXeOEsSR43oQCl9PLwxmvWiKoRMFJYJIKTkF2jolZbNWdyEb0qm7iFENC6im06npdGo6nRpLR4lKTfxQBL75zo50sAHC6sFKiAk@7E4AzD018gNYy6p6BdQ9bkVa1RGAsCECyaVjKI22hBTQXjiHn5J6aiygWulIWEmgD0xD1rieLwgBX0@daFFJ2ZzmRRSkCgAWwGYvkDJ6SY2nfdEIyTxt5xNt64TYuRLzlP2aAcsGQNyoAUAsSqqgA8IOIBVXjAJUicJ2f@93AGO8LTsiTWj7qCCKGiZ4A17ssPYIE7wFcKkPxtgdqHhu2XPOxIrpAbAT2JIcEFMQQIoO@PZ40bB3CqB27161WWOBEasaamI7qgHthl4VpEia4lsCldBVpzTaEoaHBRRDEkkmuDzdJ6IjUqBvQAoOPVGLQduZN5kROAma6MueksFC/KOJ@K9ZRgU07pbjSaZAMJES04IUIKYWQJi7ANC3l4sChERqRPNfGMttfOdJ2CiB@eqelIH@Ui/8HQB2YgpCbQAjdEJHm/yKiTBVmCRUHwj8AK3MmIAJyCSGKs6YtVUH8yym0kR9nnfbbPivwukv "GolfScript – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 39 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ***Edit:*** now works with runs of `*` even after `_` Full program. Prompts stdin for string and then for regex. Returns a list consisting of an empty list (by default, this prints as two spaces) for matches and an empty list (empty line) for non-matches. ``` (1⌽'$^','\*+' '_'⎕R'*' '()'⊢⍞~'+')⎕S⍬⊢⍞ ``` [Try it online!](https://tio.run/##hZGxTsMwEEB3f0UHpLuz6cBHdGGAqhlYUKO7UKFKUR2ltFJFYASECGJhZWDmC5D4Gf9IuBQhSOuCB5/97tknn7nI@2crzv15Ex6fk4FOJwkMlpPZBfQQksl8PvWzYTlt93CYHB8BmTaEm6dLlTXovAb1@5UJd7dFgwfh4QP2xrAPp9bpsRTUGYHVJRKE@9dQv1yDA2pLhvrtizR6uOmtR2FYDLITMt/AIHKVkhP7wzgGJWpGqexw4zJztB7H78587kuDmUPvMHeoYUGVJ1cSda3F/5r2ohKyvx/eBbJlbBGJOMwRmG0ig6m1tmr/QyN1OiV/JHemRHgz9wk "APL (Dyalog Unicode) – Try It Online") (output made easier to read by converting all output to JSON) `⍞` prompt stdin (for string) `⊢` on that, apply the following: `(`…`)⎕S⍬` PCRE **S**earch for the following, returning an empty list for each match  `~'+'` remove all plusses from the following:  `⍞` prompt stdin (for regex) `⊢` on that, apply the following:  `'\*+' '_'⎕R'*' '()'` PCRE **R**eplace runs of `*` with `*` and `_` with `()`  `'$^',` prepend dollar sign and caret (indicating end and start)  `1⌽` rotate the first character (`$`) to the end [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~295~~ 277 bytes ``` a←819⌶⎕A E←{⍵{(⍺⊆⍨~⍵),⍺[⍸⍵]}(⍵∊'|+')∧0=+\-⌿'()'∘.=⍵}1↓¯1↓⊢ M←{c←⊃⌽⍵⋄c∊'0',a:0⋄c∊'_*':1⋄r s o←E⍵⋄o='|':∨/∇¨r s⋄∧/∇¨r s} D←{c←⊃⌽⍵⋄c∊'0_':'0'⋄c=⍺:'_'⋄c∊a:'0'⋄c='*':1⌽∊')('(⍺∇¯1↓⍵)'+'⍵⋄r s o←E⍵⋄o='|':1⌽∊')('(⍺∇r)'|',⍺∇s⋄M r:1⌽∊')(('(⍺∇r)'+'s')|',⍺∇s⋄1⌽∊')('(⍺∇r)'+'s} {M⊃D/(⌽⍵),⊂⍺} ``` [Try it online!](https://tio.run/##hVFLb9NAEL77V/g2u96U2uIClnJAtBI9REiUG1TWrvNqFcnIVQ8oaw6AgjFxBUJIXOFCbj0VoUoIKT9l/kiY9au2WojtzOw3883jy8oXs53hSzmLJpuNxMXHe959XP7E8y8PrH2Cc8wv5wzzK8wWmK9eEeQ9gs8w/0Xno4Ryl5hmoAVwTH@4ffF8B5d/gHHA9OudPqUTDxef1xfGYvbdGpi2IRnM3uDyt6n/8DY0PVzoSd@tUeCA7xGI7VM7Ivp@yYz6oMHHdLWL6bv1irIUpMkNTKy9f08IwKcxBtJmVz4EUKVkE4diLpURnzMoxFPrcn@SDwLKjrcudrMy5hTvlWez68COW6w2TcAp8A731m5ES6z5gMTt7bJSH91J9poIyWZsZOfndIEHj4mxvriLi0@EDp88JPv00cHhxrNdG99/s4FJoYprGq9XNkgFZEKwPPv6dRsukzrgQjnXBWCzHkjgxilyZQdVtCmsklIaQHGr2ywULBKMzQp3Ro05FzGZpncYzaIYSn9WH8iV0KqXq2RoxZ3WWtUipSBVKOqocMyv5nc0tJiBoE863NlKDRzzdOeHteJqrBk85JpN9AknR0@ox1wfc9HJOAYrPeJ6yiteDbcUVRluzjdmVS3@V1agGm4pahbkrb9dhcPReDI9PjFXPpQjNYVWUMFf "APL (Dyalog Unicode) – Try It Online") -18 bytes thanks to @ngn. This is a proof of concept that we can do a "simple regex matching" without any backtracking, thus avoiding possible infinite loops due to `_*` or `r**`. This is also a showcase that APL is a general-purpose programming language. The anonymous function at the last line does the regex matching; use it as `(regex) f (input string)`. The return value is 1 if the match is successful, 0 otherwise. ### Concept Given a simple regex `R` and the first character `c` of input string, we can construct (or *derive*) another simple regex `R'` that matches exactly the strings `s` where the original `R` matches `c+s`. $$ \forall R \in \text{simple regex}, c \in \text{[a-z]}, s \in \text{[a-z]\*}, \\ \exists R' \in \text{simple regex}, R' =\sim s \iff R =\sim c+s $$ Combine this with a tester which checks if `r` matches an empty string (epsilon), and we get a fully working simple regex matcher: given a regex \$ R\_0 \$ and string \$ s = c\_1 c\_2 \cdots c\_n \$, sequentially derive \$ R\_0, c\_1 \rightarrow R\_1, c\_2 \rightarrow R\_2 \cdots \rightarrow R\_n \$ and then test if \$ R\_n \$ matches epsilon. My code uses the following algorithm for testing epsilon match (`MatchEps`) and computing `R'` from `R` and `c` (`Derive`). ``` T = True, F = False 0 = null regex (never matches) _ = "empty string" regex a = single-char regex r, s = any (sub-)regex MatchEps :: regex -> bool MatchEps 0 = F # Null regex can't match empty string MatchEps _ = T # Empty-string regex trivially matches empty string MatchEps a = F # Single-char can't match MatchEps r* = T # Kleene matches as zero iteration MatchEps (r|s) = MatchEps r or MatchEps s MatchEps (r+s) = MatchEps r and MatchEps s Derive :: char -> regex -> regex # No matching string at all Derive c 0 = 0 # _ can't match any string that starts with c Derive c _ = 0 # Single-char regex only matches itself followed by empty string Derive c a = if c == 'a' then _ else 0 # r* matches either _ or (r+r*); # _ can't start with c, so it must be first `r` of (r+r*) that starts with c Derive c r* = ([Derive c r]+r*) # r or s; simply derive from r or derive from s Derive c (r|s) = ([Derive c r]|[Derive c s]) # r followed by s; it matters if r can match _ Derive c (r+s) = # if r matches _, either [r starts with c] or [r matches _ and s starts with c] if MatchEps r then (([Derive c r]+s)|[Derive c s]) # otherwise, r always starts with c else ([Derive c r]+s) ``` ### Ungolfed, with comments ``` ⍝ Unwrap single layer of (...) and extract (r, s, op) from (r|s) or (r+s) ExtractRS←{⍵{(⍺⊆⍨~⍵),⍺[⍸⍵]}(⍵∊'|+')∧0=+\-⌿'()'∘.=⍵}1↓¯1↓⊢ ⍝ 1↓¯1↓⊢ Drop the outermost () ⍝ {...} Pass the result to the function as ⍵... ⍝ +\-⌿'()'∘.=⍵ Compute the layers of nested ()s ⍝ (⍵∊'|+')∧0= Locate the operator (`|` or `+`) as bool vector ⍝ ⍵{...} Pass to inner function again ⍵ as ⍺, above as ⍵ ⍝ ⍺[⍸⍵] Extract the operator ⍝ (⍺⊆⍨~⍵), Prepend the left and right regexes ⍝ Tests if the given regex matches an empty string (epsilon, eps) MatchEps←{ c←⊃⌽⍵ ⍝ Classify the regex by last char c∊'0',819⌶⎕A:0 ⍝ 0(no match) or lowercase: false c∊'_*':1 ⍝ _(empty) or Kleene: true r s op←ExtractRS ⍵ ⍝ The rest is (r|s) or (r+s); extract it op='|': ∨/∇¨r s ⍝ (r|s): r =~ eps or s =~ eps ∧/∇¨r s ⍝ (r+s): r =~ eps and s =~ eps } ⍝ Derives regex `R'` from original regex `R` and first char `c` Derive←{ c←⊃⌽⍵ ⍝ Classify the regex by last char c∊'0_':,'0' ⍝ 0 or _ doesn't start with any c c=⍺:,'_' ⍝ Single char that matches c∊819⌶⎕A:'0' ⍝ Single char that doesn't match c='*': '(',(⍺∇¯1↓⍵),'+',⍵,')' ⍝ One char from Kleene: (R*)' = (R'+R*) r s op←ExtractRS ⍵ ⍝ Extract (r|s) or (r+s) op='|': '(',(⍺∇r),'|',(⍺∇s),')' ⍝ (r|s): one char from either branch MatchEps r: '((',(⍺∇r),'+',s,')|',(⍺∇s),')' ⍝ (r+s) and r =~ eps: ((r'+s)|s') '(',(⍺∇r),'+',s,')' ⍝ (r+s) but not r =~ eps: (r'+s) } ⍝ Main function: Fold the string by Derive with initial regex, ⍝ and then test if the result matches eps f←{MatchEps⊃Derive/(⌽⍵),⊂⍺} ``` ### Final note This is not an original idea of mine; it is part of [a series of exercises on a theorem proving textbook](https://softwarefoundations.cis.upenn.edu/lf-current/IndProp.html#lab245). I can claim that the algorithm is proven to work (because I did complete the correctness proofs), though I can't open the entire proof to public. [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda r,s:re.match(re.sub('(?<=[_*])\*+|[_+]','',r)+'$',s) import re ``` [Try it online!](https://tio.run/##nZDNasMwEITvfootFFYrmfTQW2jIKxR6TIJZOXIjkC0jyYSC391V/koCSQ7VYTWHmW@l6X/SznfvU7NYT45bvWUIZZwHM2s51TuRRRy0QLH8WKwquaG1VOOqUhssEctACl@xjFTYtvchQTBTMHFwKcICVpui8QEs2A5EdgPyYeijOk591hppXkA@5/CM@950W9HkxYLHipSWlK2W6BqpmY9E5keAzifQ3rt7JCrubKuV8Eo4JfI10OhJhew8LKm98wH/kxoexFhKeXo@3v7rr6rcjH5aTpURo@D8KSnpTkNXVfMzDo@a5Dn@rMKLL0NrPFRomwvuxO6D7ZLAT47RbIGdg2Riii9IhXHR3Ji@fGvSznbfsDddgn3wWc7fkKZf "Python 3 – Try It Online") Simple - just convert it to ordinary regex, using ordinary regex! [Answer] # JavaScript (ES6), 45 bytes Takes input as `(regex)(string)`. Returns a Boolean value. Applies the straightforward method of removing `[_+]` from the simple regex to turn it into a standard regex. ``` r=>s=>!!s.match(`^${r.replace(/[_+]/g,"")}$`) ``` [Try it online!](https://tio.run/##fY9BDoIwEEX3ngIbFjMU4QRwEYIwrYCaSkkLbsSzI2A3YnQ1P5l5L3@udCcrzaXrD60@VVOdTCZJbZLu9za6US/PUB79h4lM1SmSFcRZwfO4CRnDp1/iJHVrtaoipRvIGAkWekwQy2e4A@slqVcDA@ICGYJFxN0nsdzTCq3pzbvsZLTuad5trEBjgVwEP9RSK20WdAmD2dKSg@agOMxjwFEjN7PjT0tXx5WTXz@OAgOHTy8 "JavaScript (Node.js) – Try It Online") Or [43 bytes](https://tio.run/##fY9BDoIwEEX3ngIaFjMU4QR4EaIyrYCaSkmrbsSz14LdGNRkkvnJ5L38OdOdrDSn4bru9aFxbelMubF@8gtd5RHqXfIwuWkGRbKBotrzbdFljOEzqdFJ3VutmlzpDipGgmURE8S2Hh7ARuUmiuMWGBAXyBAsIq4@mYmgGZvT2xBy0NF8J39beIHGPXKR/pBLrbSZ4CnczJKXHDQHxcGvG44aufGWP01DpVBQfvl0FJgGgXsB) by returning either `null` or an object. [Answer] # [R](https://www.r-project.org/), ~~55~~ 75 bytes ``` function(x,y)grepl(paste0("^",gsub("([+_]|(?<=\\*))\\**","",x,pe=T),"$"),y) ``` [Try it online!](https://tio.run/##LYtBCsIwEEX3HmNwMZPMwgNYvIQ7qyUT2iKEpqQNVOjd40Q7i3mfz3@pDE0Z8uTXd5xw4w@NqZ8Dzm5Z@wvCC3hcsiDgw3bPHW/Xpm0NkT4DDMAbz31zJ4YzkNpl0Km3GC0Gi4pMeySbiAjYI/gYYk5q1nDQJSA6VbEz9XZ0Vmo4HF05J1Ih8uevUqt8AQ "R – Try It Online") A function that takes a simple regex `x` and a vector of strings `y` and returns a vector of logical values the same length as `y` indicating whether `x` matches. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~38~~ 35 bytes ``` *1A` 1G` ^ a` _ () \*+ * "$-5"~`\+ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X8vQMYHL0D2BK44rMYErnktDkytGS5tLi0tJRddUqS4hRpvr/3@NZG2NfG2NHG0NIFWqWZOvqV2kqanJlZyfk19aBAA "Retina – Try It Online") Takes the simple regex on the first line and the string to match on the second. Explanation: ``` *1A` ``` Delete the first line, but don't actually change the working string. The string to match still gets stored in the history, which allows us to refer to it later. ``` 1G` ``` Keep only the first line. ``` ^ a` ``` Prefix the `a` modifier to anchor the pattern to the whole string. ``` _ () ``` Turn the `_`s into `()`s to match an empty string that can be "repeated" with `*`. ``` \*+ * ``` Reduces runs of `*` to a single `*`. ``` \+ ``` Delete any `+`s. ``` "$-5"~` ``` Execute that as a stage, using the history as the working string. [Answer] # Java 8, 55 bytes ``` r->s->s.matches(r.replaceAll("\\+|(_|(\\*))\\**","$2")) ``` [Try it online.](https://tio.run/##lVKxTsMwEN37FacTUu04zcBYoBILG2LoSFB1dp2S4iaR4xSqpt8enNRVhSgSlRz7fO/53js7a9rSZL386JShuoZnyov9CKB25HIFa48mjctNkjWFcnlZJE8huJ87mxer@F@cF7nWys1mkMFDZyez2o9kQ06965rZxOrKkNKPxjBMU9GyRcvSNOLcTxHGeHOLnHd3I2@saqTxxoK/bZkvYeM9s6PS6xsQ7/0DOF07hiQxBmQkJEd@NwBZaQPbV7EwhUJ/wun4Hr0c@U/2az/JYzSERD1EPn/gQ62TDGPULriQEfdyvmqQCqASrBTMCOaXhrclF5bznomqNKXFa9iNvaKPo@ljA@qXZ2oljy74XUT9pQPixeziZ5pkFAB/R/JvjAJ2GJ3/ruH1Bmrow@qV/orh3FV4y/mudnqTlI1LKg85U7AxjoUnCEwRqFhCiiiG431mCiiyhKrK7NiQ5GHTlww2Dt03) Removes all `+`; all `_` with zero or more trailing `*`; and changes all sequences of more than one subsequent `*` with a single `*`. Then it check if the String matches this modified regex. Note that in Java, the [`String#matches`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#matches-java.lang.String-) method implicitly adds a leading and trailing `^...$` to check the entire String. [Answer] # [PHP](https://php.net/), ~~983~~ ~~976~~ ~~954~~ ~~930~~ ~~910~~ ~~892~~ 838 bytes ``` <?php list(,$s,$i)=$argv;$p=0;$u=[2,[3,[2,[1,'('],$o=[2,[4,[2,&$u,[1,'|+']]],&$u],[1,')']],[1,'_'.join(range('a','z'))]],[5,[1,'*']]];m($o,$a);$s=$i;$p=0;echo m(o($a))&&$p==strlen($s);function m($m,&$a=[]){global$p,$s;$r=$p;$n=array_shift($m);foreach($m as$t){$b=[];if($n==1)if(($c=$s[$p]??0)&&strpos($t,$c)!==!1){$a[]=$c;$p++;return 1;}if($n==2){if(!m($t,$b)){$p=$r;return!1;}$a[]=$b;}if($n==3){if(m($t,$b)){$a[]=$b;return 1;}}if($n==4){k:$b=[];$r=$p;if(!m($t,$b)){$p=$r;return 1;}$a[]=$b;goto k;}if($n==5){if(m($t,$b))$a[]=$b;else{$a[]=[];$p=$r;}return 1;}if($n==6)return 1;}return $n==2?:$p!=$p=$r;}function o($a){$e=$b=u($a[1]);if($a[0]){$e=[2];foreach($a[0]as$u){$e[]=u($u[0]);$e[0]=$u[1][0]=='+'?2:3;}$e[]=$b;}return$e;}function u($u){$w=$u[0][0];$v=$w[0][0];$t=$v!='('?($v=='_'?[6,0]:[1,$v]):o($w[1]);return$u[1][0]==[]?$t:[4,$t];} ``` [Try it online!](https://tio.run/##dVPbjpswEP0VkEbBLqhKspcH3BEfgqzIQSShS7BlTLJtNt9Ox4ZcqqoSoLmcM2fGY8zBjOOPwhxM1Da9Yxn0GTQcQdn9SYDBpYABy3VWvmT@u8oSlsgMdIi9@tgChhD/ShMppXdl8Dm5wdgk33/qpmNWdfuaJSrJkt8J5z77FgDfPFEcGegMFBfQIzSTdl0ddHRkmlGcLxYUw97Ztu4Y9Fzshq5yje4IAUcSVlhKftm3eqtaMDSKAItgBHSorFW/Nv2h2TnCElXbWlUHsiPVg@MX2BJZNDtGYFxxMhhUCH0JRhbFksRJ2Oiegcug4jFivCKWKiVCRc2mqbC1G2wXrcR1LrPmF7LiY@BsOcENgp1xMeEm@vZOeAmEJ/ycf1S@IV/55SOfep5m/L9Q9CS0105HH3e9t7/1bqi67etJ25cPpa7/DPfOH6HZCjMXOZgYZ9Z9Q2GDF6ipPA5klyvJw2mrcilDolzLx1Z8lPYy@Ay1QYzB4wR5S2pxILo3MEmTYp2/0ID1fJJTK1A/aXs2FTpjKEKPgBPC@WY7hFOMdK0LRnGk61qU79lS5nQ14SR5Tr2fQ79z7bt6KQtwOf0F4KS4juP4mVapTlt62fC14akdPyvd6sH@AQ "PHP – Try It Online") ## Ungolfed ``` <?php list($dummy,$string,$user_test)=$argv; $pointer = 0; //production rules $unit = []; $char = ['char','_abcdefghijklmnopqrstuvwxyz']; $separator = ['char','|+']; $unit_and_separator = ['and',&$unit,$separator]; $operators_list = ['list',$unit_and_separator]; $operators = ['and',$operators_list,&$unit]; $open_bracket = ['char','(']; $close_bracket = ['char',')']; $brackets = ['and',$open_bracket,$operators,$close_bracket]; $atom = ['or',$brackets,$char]; $star = ['opt',['char','*']]; $unit = ['and',$atom,$star]; $ast = []; match($operators, $ast); $user_regex = buildoperators($ast); $user_ast = []; $string = $user_test; $pointer = 0; // answer here 1=matched blank=not matched echo match($user_regex, $user_ast)&&($pointer==strlen($string)); // recursive descent parser function match($test_match, &$ast) { global $pointer,$string; $original_pointer = $pointer; foreach (array_slice($test_match,1) as $test) { switch ($test_match[0]) { case 'and': $sub_match = []; $pass = match($test,$sub_match); if (!$pass) {$pointer = $original_pointer;return false;} $ast[] = $sub_match; break; case 'or': $sub_match = []; $pass = match($test, $sub_match); if ($pass) { $ast[] = $sub_match; return true; } break; case 'list': do { $sub_match = []; $original_pointer=$pointer; $pass = match($test, $sub_match); if (!$pass) { $pointer = $original_pointer; return true; } $ast[] = $sub_match; } while (true); break; case 'char': $char = substr($string,$pointer,1); if ($char && @strpos($test,$char)!==false) { $ast[]=substr($string,$pointer,1); $pointer++; return true; } break; case 'emptystring': return true; break; case 'opt': $pass = match($test, $sub_match); if ($pass) {$ast[] = $sub_match;} else {$ast[] = []; $pointer = $original_pointer;} return true; break; } } if ($test_match[0] == 'and') { return true; } else { $pointer = $original_pointer; return false; } } // build user production rules function buildoperators($ast) { if ($ast[0]) { $engine = ['and']; foreach ($ast[0] as $unit_and_separator) { $engine[] = buildunit($unit_and_separator[0]); switch ($unit_and_separator[1][0]) { case '+': $engine[0]='and'; break; case '|': $engine[0]='or'; break; } } $engine[] = buildunit($ast[1]); } else { $engine = buildunit($ast[1]); } return $engine; } function buildunit($unit) { $star = !empty($unit[1][0]); if ($star) { return ['list',buildatom($unit[0][0])]; } else { return buildatom($unit[0][0]); } } function buildatom($atom) { if ($atom[0][0]=='(') { return buildoperators($atom[1]); } elseif ($atom[0][0]=='_') { return ['emptystring','']; } else { return ['char',$atom[0][0]]; } } ``` [Answer] # [Perl 5](https://www.perl.org/), 34 + `-p` flag = 35 bytes Full program. Takes the simple regex pattern, followed by string to match against, from stdin as two separate lines, then loops and does it again, until EOF is encountered. Prints `1` for a match or nothing for a non-match (with no newline in either case). @ankh-morpork [has pointed out](https://codegolf.stackexchange.com/questions/197061/check-if-simple-regex-matches-string/197828#comment470601_197168) that technically, given the question's description of simple regexes, any number of `*` in a row makes a valid simple regex. @Bubbler [has pointed out](https://codegolf.stackexchange.com/questions/197061/check-if-simple-regex-matches-string/197828#comment470621_197061) that `_*` also needs to work (and be equivalent to `_`). The other answers haven't taken these things into account yet, but I will do so: ``` s/[_+]/()/g;s/\*+/*/g;$_=<>=~/^$_/ ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPzpeO1ZfQ1M/3bpYP0ZLW18LyFKJt7Wxs63Tj1OJ1///X0MjWVsjX1tDIwdMldbEa2lqamoXgYhCLS0tTa7k/Jz80qLCQq5/@QUlmfl5xf91CwA "Perl 5 – Try It Online") To allow simple regexes such as `(_***+a)` to work, `_` is changed to `()` instead of . For golf reasons, `+` is also changed to `()`, although changing it to  would work. This solution exploits the fact that valid input won't contain newlines, input can be assumed to be valid, and both the implicit `<>` (from `-p`) and the explicit `<>` include the terminating newline read from stdin, thus `$` doesn't need to be added at the end of the regex (as both the pattern and the string ), only `^` needs to be inserted at the beginning. --- ## [Perl 5](https://www.perl.org/), 20 + `-p` flag = 21 bytes (looser, obsolete interpretation of question) ``` y/_+//d;$_=<>=~/^$_/ ``` [Try it online!](https://tio.run/##K0gtyjH9/79SP15bXz/FWiXe1sbOtk4/TiVe//9/jWRtjXxtDY0cMFVaE6@pqaldBCS4kvNz8kuLuP7lF5Rk5ucV/9ctAAA "Perl 5 – Try It Online") Like most of the other solutions, deletes the `_` and `+` characters to turn the simple regex into a standard regex. This means that the simple regex `(_*+a)` will not work, as it becomes `(*a)` after the deletion. Anything containing `**` won't work either; in standard regex, an already-quantified expression cannot be quantified again. [Answer] # Perl 5, 47 + `-alp` flag = 50 bytes ``` $_=$F[0];s/[_+]/()/g;s/\*+/*/g;$_=$F[1]=~/^$_$/ ``` [Try it online!](https://tio.run/##hY69DsIwDIT3PkWHDI4tFBiYUFdeopTIjiqEFJEqpVvFoxPMnwRTl7v7dDfc0Oe4LcX4xuzbdbcbXeupc2DdSfMByaGmd73pmps7Gm9cKR4RK2ASW7NUADx7S4JKvyDMf8zPbSBIBBBfNmllLWWVOqSY8kI/LQ1yr7dmsfgx/SDfyBKqexqu53QZy4rj8AA "Perl 5 – Try It Online") --- # Perl 5, 41 + `-alp` flag = 44 bytes Obsolete: it not supports `_***`-like regexes ``` $_=eval'$F[1]=~/^'.($F[0]=~y/_+//rd).'$/' ``` [Try it online!](https://tio.run/##hY6xCgIxEET7@4orAtnc4kULy2v9CdGwG1MIwYScJwjipxtXUdDqmp15zMBODiWua1VuCBeKWm22q91wt3vdg/il@Kt1aG05mF4rq2sFQjYtcQNAN2eQO6FfYKI/plfXIyQEiG@ZJDIGi5zWp5jKTD7NFUpo5B@b7iOygb@W2DePlM/HdBrrgmJ@Ag "Perl 5 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 522 bytes ``` a=>b=>{int y=0,e=a.Length,k=0,o,q;var z=new int[e];for(;k<e;k++)if(a[k]<41){for(o=q=1;o>0;q++)o+=a[q+k]<41?1:a[q+k]>41?0:-1;z[k+--q]=k+1;z[k]=k+q+2;}void t(string s,int j){for(;j<e;){var l=a[j++];var w=j<e&&a[j]==42;if(j>1&&a[j-2]<41)for(int r=j,d=0;r<z[j-2]-1;)if(a[r++]>123&z.Take(r).Skip(j-2).Count(x=>x>0)%2>0)t(s,r);if(l>96&l<124)do{if(w)t(s,j+1);if(s==""||s[0]!=l)return;s=s[1..];}while(w);if(l==42&&a[j-2]==41||l<41&z[j-1]<=e&&a[z[j-1]-1]==42)t(s,z[j-1]);j=l>123?a.IndexOf(')',j)+1:j;}y=s==""?1:y;}t(b,0);return y;} ``` Saved 6 bytes thanks to ceilingcat [Try it online!](https://tio.run/##bVPbjpswEH1evoIiNeuJCYJ0ValxzD5UqlRppZXaSn1AdGWIk3ApNIZsbvDt6dikaVQVJWY8Z86ZMwbSZpI22fnTtkrnTauyauXexotDJX5maRgu@VnwMOHhKata@8B9V3LhPclq1a7dAre1u2GvQtlHXsmdjUWRjNmyVoQVc8kKSiFbEhEV8fwhgJMGar7hAatDn20QrSkX0YYa/DGYDXGIsT@bBOwYFXQy2cS8oGajgw2dsv61zhZ2Swa7duNqd/mgz3JsDCdtqkTtnNLYONxxBEYjzMScP0wZ@srDwCQmU2NPs7WQ4rm74D5T86PB0MgwhUKtMJi@Gx29b6KQRIH3tch@ESwC72O9rVqy5@E@9OHtFBf05yrQjcrww/tROQ@mD7CoT5jYGTCngYEbzh2n65rIj9/wEpRst6piDW@iwPNi1u/WWSmRY6S0@T@uMQ66rkTzI201iOfcjDhs8KeLTashAyznpZ7gUXifq4XcPy/JPdy7OdBglrP@wI0VfBAH1rckcX1ggxsbE2dm6YNsZdPa3MbnHcUn6444RNAEHPeScUTi9OAagIjuBWgyvkExcoReEhOZNbnEw0YIg4sbnZSSmhJSmtsWNQGowuWvbFqXtdI0HWzVlSm6BMb/dL@0uTRNr7Uv4/G408PgHeB/JHF1qr1ZPbPwnZEiXRN9METJldy7Nr6VDeC3YE4KbDyj7ypr5VNWSeJ80TUz@@T3qGQIwKy7Wxmka/KgguRbNtKQG2gu4q69HHqC/hJAC/W3zTDRnwmOiH/o0oUE64e@LAvPWOc7ATjKkLxeFmZMhR7zNw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-¡`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` è^+'$iVr"_|%+ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LaE&code=6F4rJyRpVnIiX3wlKw&input=ImNvbG91ciIKIihjKyhvKyhsKygobyt1KXxvKStyKSkpIg) ``` true ``` ]
[Question] [ Think of a road as a number line, starting at `0` and continuing indefinitely: ``` ................................................................. ``` There are two cars on the road: `C` and `R`. `C` is the cop who is trying to catch `R`, the robber. `C` starts at `0`, and `R` starts somewhere on the road: ``` C.............................R.................................. ``` The cop is already moving - he's chasing the robber. He has a constant speed. The robber just hopped into his car. He's accelerating. Each tick, the robber's speed increases by his acceleration. Say the cop's speed is `7` and the robber's acceleration is `1`. If the robber starts at `30`, this is what the road would look like each tick: ``` C.............................R.................................. .......C.......................R................................. ..............C..................R............................... .....................C..............R............................ ............................C...........R........................ ...................................C.........R................... ..........................................C........R............. .................................................C........R...... ``` After the last tick above, the robber's speed is equal to the cop's, and he's still ahead. Since the cop is moving at a constant speed and the robber is still speeding up, the robber escapes, so you output a truthy value. However, if the cop's speed had been `9`... ``` C.............................R.................................. .........C.....................R................................. ..................C..............R............................... ...........................C........R............................ ....................................C...R........................ .............................................X................... ``` ... then the cop catches up to the robber before the robber can get away (marked by the `X`), so you output a falsey value. # Your Task Given three inputs - the cop's speed, the robber's position, and the robber's acceleration - determine whether or not the robber will get away. # Rules * The cop always starts at `0`. * All inputs will be positive integers. * The cop catches the robber if, after any tick, the cop's position is greater than or equal to the robber's position. * The robber gets away when he hasn't been caught yet and his speed is greater than the cop's. * Your program must terminate after output. * The robber accelerates before he moves each tick. # Test Cases ``` Cop Speed, Robber Position, Robber Acceleration -> Output ``` ``` 7, 30, 1 -> truthy 9, 30, 1 -> falsey 2, 1, 3 -> truthy 100, 100, 50 -> truthy 60, 60, 20 -> falsey 10, 1, 1 -> falsey 10, 50, 2 -> truthy 11, 50, 2 -> truthy 12, 50, 2 -> truthy 13, 50, 2 -> truthy 14, 50, 2 -> truthy 15, 50, 2 -> truthy 16, 50, 2 -> falsey 17, 50, 2 -> falsey 18, 50, 2 -> falsey 100, 451, 10 -> truthy ``` Reference Python 3 implementation that creates a visual also: [Try it online!](https://tio.run/##bVBNS8QwEL3PrxhySlwpXaUXoXsR/AHiQShliTW7rWaTkqZ@/Po600RhFw@ByZs3772Z8Tv23t0uS7cf/YQ1ltDtT/7DUDm4KAc3zlEqBSH3L8BMLanUXWfsJcPPkaCmhc9@sAafwmzuAJPZpsbkBZiFCMk6DGVO6gEgaRV6HI17lXJVuE4ksgEcDll1VyeUbDCYabYc4EHbiWzwJRj9Dmgs0bPn7jfF2QAH/eODNe4Ye4JP@kvyoyhK4QYrgIMPaHTX096ckFTs4PgmjShEi1eYhteEzGvKlj3XctuyKfOb/G9pUDwLjjiZ82aZmvfiv5FHQsfApxeiePODk0yhyyRwikGm3ZRalm0FVQk3Pw "Python 3 – Try It Online") This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), 29 bytes ``` lambda s,p,a:(a-2*s)**2<8*a*p ``` [Try it online!](https://tio.run/##PchNDsIgEAXgPadgSQkm/Iitjd7CpZsx0pQEKWmpxtMjbcxMMm@@N@mbxymaMlzvJcDr8QS6iCSgZ3DQfGk415eOA0/lM/rg6G1eXU9omn3MbGDcvSEwH9OaWVOntMJIochZ0HqpIrpGNVFyq1tYWcv@VTtsXU2UQmmUQR1RFnVCtajurx8 "Python 3 – Try It Online") ### Explanation The cop's position at time `t` is `st`. The robber's position at time `t` is `a(t)(t+1)/2 + p`. The signed distance from the cop to the robber is `(a/2)t^2 + (a/2-s)t + p`. It never reaches zero if the discriminant is negative, the discriminant being `(a/2 - s)^2 - 4(a/2)(p) = [(a-2s)^2-8ap]/4`, which has the same sign as `(a-2s)^2-8ap`. [Answer] # [Cubically](https://github.com/aaronryank/cubically), 61 bytes ``` $:7(U1R3U1F3D2*1-1/1)6+7$-77*6$(-77777777D2F1U3R1U3!0{<0%6&}) ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P9fxcpcI9QwyDjU0M3YxUjLUNdQ31DTTNtcRdfcXMtMRQNIQYCLkZthqHEQECsaVNsYqJqp1Wr@/2@oYK5gbAAA) For this to work in TIO, you may need to replace `&` with `&1` due to a bug in the interpreter. This is a shameless port of [Leaky Nun's answer](https://codegolf.stackexchange.com/a/138645/72489). Input is in the form `a s p`, where `a` is robber's acceleration, `s` is cop's speed, and `p` is robber's position. If the acceleration is too high, this will fail. I don't know how high of an acceleration this program will support, [but I know it isn't any higher than 1260](https://www.reddit.com/r/askscience/comments/3w23fk/on_a_rubiks_cube_can_any_sequence_of_moves_if/cxtucf1/). The limiting factor is that it stores the acceleration in the cube and checks if the cube is solved by checking only if the top face's sum is 0 (an incomplete check). It seems to work for acceleration = 50, but I haven't tested to see how high it can get. ### How it works ``` $:7(U1R3U1F3D2*1-1/1)6 $:7 Store the first number in the notepad ( )6 Loop until notepad is 0 U1R3U1F3D2 Rotate the cube a certain way *1-1/1 Subtract 1 from the notepad +7$-77*6 +7 Add first input to the notepad $-77 Subtract second input from the notepad twice *6 Multiply the notepad by itself (square it) $(-77777777D2F1U3R1U3!0{<0%6&}) $ Get next input ( ) Loop indefinitely -77777777 Subtract third input 8 times D2F1U3R1U3 "Unrotate" the cube !0{ } If the top face is 0 <0 Check if notepad < 0, store in notepad %6 Output notepad as number & End the program ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 bytes ``` ²/W-V-U<o0W x ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=si9XLVYtVTxvMFcgeA==&input=MTYsIDUwLCAy) ### Explanation `U`, `V`, and `W` are the implicit inputs. First, with `Uo0W` we create the range **[0, W, 2\*W, ...]** until it reaches `U`. `x` then sums this, which gives how far the robber travels before reaching cop speed. We'll call this **r**. Now, how far does the cop travel in this time? We can calculate this using **U \* (U // W - 1)**, which can be rearranged to **(U \* U) // W - U**. We'll call this **c**. Now for the final step: does the robber get away? All we need to do here is check if **c < r + V**, or rearranged, **c - V < r**. [Answer] # [Pyth](https://pyth.readthedocs.io), 11 bytes This takes them in this order: `Robber Acceleration, Cop Speed, Robber Position` separated by a newline (as shown in the test suite). ``` <^-QyE2*8*E ``` **[Test Suite](http://pyth.herokuapp.com/?code=%3C%5E-QyE2%2a8%2aE&input=1%0A7%0A30&test_suite=1&test_suite_input=1%0A7%0A30%0A%0A1%0A9%0A30%0A%0A3%0A2%0A1%0A%0A50%0A100%0A100%0A%0A1%0A10%0A1%0A%0A2%0A10%0A50%0A%0A2%0A11%0A50%0A%0A2%0A12%0A50%0A%0A2%0A13%0A50%0A%0A2%0A14%0A50%0A%0A2%0A15%0A50%0A%0A2%0A16%0A50%0A%0A2%0A17%0A50%0A%0A2%0A18%0A50%0A&debug=0&input_size=4)** or **[Try it online!](http://pyth.herokuapp.com/?code=%3C%5E-QyE2%2a8%2aE&input=1%0A7%0A30&test_suite_input=1%0A7%0A30%0A%0A1%0A9%0A30%0A%0A3%0A2%0A1%0A%0A50%0A100%0A100%0A%0A1%0A10%0A1%0A%0A2%0A10%0A50%0A%0A2%0A11%0A50%0A%0A2%0A12%0A50%0A%0A2%0A13%0A50%0A%0A2%0A14%0A50%0A%0A2%0A15%0A50%0A%0A2%0A16%0A50%0A%0A2%0A17%0A50%0A%0A2%0A18%0A50%0A&debug=0&input_size=4)** [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 14 bytes Port of [totallyhuman's Python answer](https://codegolf.stackexchange.com/a/138647/59487). Returns `1` for truthy and `0` for falsy. ``` hQee-XQ1@Qe*}< ``` **[Try it here!](http://pyke.catbus.co.uk/?code=hQee-XQ1%40Qe%2a%7D%3C&input=2%2C+1%2C+3&warnings=0)** --- # Explanation ``` hQee-XQ1@Qe*}< - Full program with implicit input added in the beginning (which automatically splits the components) h - First input Qee - Last Input halved (through integer division) - - Subtact the above X - Square. < - Is smaller than? Q1@ - The second input Qe* - Multiplied by the last input } - Doubled ``` # [Pyke](https://github.com/muddyfish/PYKE), 15 bytes My very first Pyke answer! Port of [my Pyth solution](https://codegolf.stackexchange.com/a/138649/59487), which is inspired by [Leaky's Python submission](https://codegolf.stackexchange.com/a/138645/59487). Returns `1` for truthy and `0` for falsy. ``` eQh}-XQe8*Q1@*< ``` **[Try it here!](http://pyke.catbus.co.uk/?code=eQh%7D-XQe8%2aQ1%40%2a%3C&input=7%2C+30%2C+1&warnings=0)** --- # Explanation ``` eQh}-XQe8*Q1@*< - Full program with implicit input added in the beginning (which automatically splits the components) e - End; last input in this case Qh - The first input } - Double - - Subtact the above X - Square. < - Is less than? Qe - Last Input 8* - Times 8 * - Multiplied by Q1@ - The second input. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` _⁵Ḥ¤²÷÷8< ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//X@KBteG4pMKkwrLDt8O3ODz///8x/zMw/zk "Jelly – Try It Online") Port of Leaky Nun's Python 3 answer. (full program) Takes arguments in order `acceleration, position, speed`. [Answer] # [Ruby](https://www.ruby-lang.org/), 29 27 25 bytes ``` ->c,p,a{(a-c-c)**2<8*p*a} ``` [Try it online!](https://tio.run/##Rco9D4IwEAbgnV9xcYKmNKXIh4k6ubi46EhiaiWBBLWBkmCA315bDXa4u@fu3ra/vXW1K3S4F1hiPvo8FKEIEGLbHEnEZ32@HI4n0pb8TjrZ1MpfFc9VQEouKhhhaiaQveqgIj5qlgQ2gQeX9j9MMJBOtbUk6nWtYQ5g1hmGmGKIwNv8xUw3C3gRtQfbEgpeaqYtRu3nm4l@SuzVMHJkjrHj2jFxTB0zx3zhBw "Ruby – Try It Online") Got from 29 to 27 by stealing the idea of multipliying both sides by 4. (Leaky Nun's python answer) Got from 27 to 25 by removing parens around lambda parameters (thanks totallyhuman) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 33 bytes ``` (v,p,a)=>v/a*v<p+v/a*(1+v/a)*.5*a ``` [Try it online!](https://tio.run/##fZFNT8QgEIbv/Io5QsXa7tpdTT8um@hlPXnwjIhK0gVSWIxp9rdXaK3hZMjwvg8zmWQGbq@5HsR0tlJ9wPO3deJUo5Tyg@57wZ3UyuaPQolB8hopdhLWMC5AjYj3zFowI7KOOcnh4ax4I5Wja7xq3XfAQyNpQ592wp4aykjb@RuW@cZcRcVlFJLlVcamem3mtXyDJyYVJiM6SusaHFqCpxDFLMJIB05YZ6EFJb7gvzo0IrynsC0olIQifJ/4TdCA0ZZFfIxXVUTeBRdjUyzZubJcfRUzM5QpbFLYpnCbQpXCLoV9CncroEuN0Hv4N8Y/sWfDPHsYcNlB2NMhfJbuRf4ySCeOUgn8t3wca/KwllnNrzJCanRZzvQD "C# (.NET Core) – Try It Online") I feel like this is off by one somewhere, but it passes for all test cases so it's possible that there simply aren't any test cases where the cop overtakes the robber for a single tick, or it might just work despite my reservations. [Answer] # [JavaScript (V8)](https://v8.dev/), 25 bytes ``` (c,r,a)=>(a-c*2)**2<8*r*a ``` [Try it Online!](https://tio.run/##fc/BCsMgDAbg@57Co4oFtbN1MPcuQSZ0jFGs6@s7HQxkczkkh3z8CbnBDpuPy5qG3ebgMvUiCmDuQmHwXDPO9dnyyCGvcXkkGugsyCgFUYw4R1J8XtnhQ6eWAty3xnSZF@6klKyZ2ozs8FSglpa9tUq@96p/Zmqyd1QhphEbETsiZhCbWvt@YsbQ/mJ@AQ) [Answer] # [Python 2](https://docs.python.org/2/), 62 bytes ``` P=s=0;S,p,a=input() while(s<S)*(P<p):s+=a;p+=s;P+=S print s>=S ``` [Try it online!](https://tio.run/##PczBDoIwDAbge59i4QSywzZEFKjPQDJfgOASSAgsDKI@/Rxoemj7tWl@@1n7eVK@m58GoyjyDToUleaWtzhMdlvjBF79MJrY1To5xU1tk9Kl2FY2RVc1KWqwyzCtzN1R@xABv3/2WDZTAjNv07E93hc8E1zCjbMwmQQVWjBIsa97y0VYjqs8kIdSICVJkTLSmZSTLqSCdP3rCw "Python 2 – Try It Online") [Answer] # [Swift 3](https://www.swift.org), 55 bytes Note that I declared the variable `t` because the expression would be too complex to be solved in reasonable time otherwise (Swift's fault!). ``` func f(a:Int,b:Int,c:Int){let t=c-2*a;print(t*t<8*c*b)} ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598e29d7cb3d25200b1533ad)** **or 55 bytes**, exact closure equivalent (I need the last part because it is a complex construct): ``` {let t=$2-2*$0;return t*t<8*$2*$1}as(Int,Int,Int)->Bool ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598e2ba1cb3d25200b1533af)** # [Swift 3](https://www.swift.org), 57 bytes ``` func f(a:[Int]){let t=a[2]-2*a[0];print(t*t<8*a[2]*a[1])} ``` **[Test Suite.](http://swift.sandbox.bluemix.net/#/repl/598e2877cb3d25200b1533ab)** [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` lambda c,p,a:c/a*(c-a+c%a)/2<p ``` [Try it online!](https://tio.run/##Rcq9DoIwEADgvU9xiwlgDW0VUKIjri6OLrWWQILQlBLl6Wsr0V5yd9/9qNk0Q89sfbrZjj/vDw4CK8xLkfIkEhu@Fisep@yorNFzicDFq2k7CVc9yWX2oXTbG6ijpO3VZKI4RvItpDJQXc6V1oNeXhUfR1tg2BIMFNDhL@aqGwBR4he@ZARQ7rpPRvzl@0MXZX7rSANZ4DZwF5gF5oFF4P7HDw "Python 2 – Try It Online") The cop has `c/a` ticks in which to catch the robber, after which it has out-accelerated the cop. At the first tick the cop gains `c-a` on the robber while on the last tick he only gains `c%a`. Thus the total that the cop can gain is the product of the number of ticks and the average distance per tick. This is simply compared to the initial lead the robber has. [Answer] # TI BASIC (TI-83/84 series), 18 [bytes](http://tibasicdev.wikidot.com/tokens) ``` Prompt C,R,A (A-2C)²<8RA ``` Yet another port of *itdoesntwork*'s influential [Ruby solution](https://codegolf.stackexchange.com/a/138646/44945). ## Execution Input order is cop speed, robber position, robber acceleration. ``` C=?7 R=?30 A=?1 1 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 79 bytes ``` \d+ $* $ ; {`(1+); $1;$1 ,(1+;(1+)) $2,$1 1`(1+),\1 $1, .*,,.* ^(1+),.*;\1.* 1 ``` [Try it online!](https://tio.run/##LcxBCsIwEAXQ/T9HhDYdSn7StEoO4CWCVNCFGxfiroeP0zqQ8PL/hPk8v6/3vZ2669rqY4DzcCjY1o5DX@BYHCEayl70cFG04DGWSv0gGL3I6IHbUY6@VGpka4ukIMTlTxRKAoO@9eaAOYieGLTTEXeyZpBmNJM5mdmczcU8m7p@yrox/AA "Retina – Try It Online") Explanation: ``` \d+ $* ``` Convert input to unary. ``` $ ; ``` Make room for the robber's speed. ``` {`(1+); $1;$1 ``` Accelerate the robber on each pass. ``` ,(1+;(1+)) $2,$1 ``` Move the robber away from the cop. ``` 1`(1+),\1 $1, ``` Move the cop towards the robber. ``` .*,,.* ``` Has the cop caught the robber? ``` ^(1+),.*;\1.* 1 ``` Does the robber out-speed the cop? [Answer] # [Recursiva](https://github.com/officialaimm/recursiva), ~~19~~ 16 bytes ``` >b*I/acIH+-ac%ac ``` [Try it online!](https://tio.run/##K0pNLi0qzixL/P/fLknLUz8x2dNDWzcxWTUx@f9/QwMDBRNTQwVDAwA "Recursiva – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~31~~ ~~30~~ 29 bytes *-1 byte thanks to Mr. Xcoder.* Started off as a port of the [Ruby answer](https://codegolf.stackexchange.com/a/138646). ``` lambda c,p,a:(c-a/2)**2<2*p*a ``` [Try it online!](https://tio.run/##Rcq9DoIwEADgvU9xIzQ1tkVAiY64uji6VCyhCUJTSpSnr61Ee8ndffejF9uNA3ft6eZ68bw/BDREE1ElzUZseYoxP3KssXDWLBUCH69O9RKuZpbrHEIbNVhoE6wGPdskTZF8N1JbqC/n2pjRrK9aTJMrCWSUAAN0@Iv76gdAjIZFKDkFVPgektNw@f6wVXnYerJIHplF7iLzyCKyjNz/@AE "Python 2 – Try It Online") ]
[Question] [ To neutralize data, recursively replace all numbers (not digits!) with zeros and all characters (not strings!) with spaces. You must accept any single number, character, or string, or possibly recursive array\* of mixed numeric/character data that your language can handle. For example, you must accept actual strings (and not restrict your input to lists of single characters) if your language can handle such. If your language contains a built-in which does all or most of this task, I would appreciate an additional alternative version without it. The shortest submission in each language is a winner, and will receive an upvote from me. **Sample cases** 1. `""` → `""` 2. `7` → `0` 3. `123.456` → `0` 4. `"X"` → `" "` 5. `" "` → `" "` 6. `"Yo!"` → `" "` 7. `[]` → `[]` 8. `[-1.2E3]` → `[0]` 9. `["Hey"]` → `[" "]` 10. `["H","e","y"]` → `[" "," "," "]` 11. `["R",2,"D",2]` → `[" ",0," ",0]` 12. `["C","3","P",0]` → `[" "," "," ",0]` 13. `["THX",[1138]]` → `[" ",[0]]` 14. `["T","H","X",[1138]]` → `[" "," "," ",[0]]` 15. `[[["H"],"e",1,1,0],[[-3],"arth"]]` → `[[[" "]," ",0,0,0],[[0]," "]]` \* If your language has several types which can equally well represent arrays like the above examples, you may chose to support only one. Two entries can both win, even though they are using the same language, by each going with a different data type. [Answer] ## JavaScript (ES6), ~~53~~ 47 bytes ``` f=o=>o.big?o.replace(/./g,' '):o.map?o.map(f):0 ``` ### Test cases ``` f=o=>o.big?o.replace(/./g,' '):o.map?o.map(f):0 test = [ "", 7, 123.456, "X", " ", "Yo!", [], [-1.2E3], ["Hey"], ["H","e","y"], ["R",2,"D",2], ["C","3","P",0], ["THX",[1138]], ["T","H","X",[1138]], [[["H"],"e",1,1,0],[[-3],"arth"]] ]; test.map(o => { console.log(JSON.stringify(o), '=>', JSON.stringify(f(o))); }); ``` [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` f=lambda x:1-(x<{})and map(f,x)if x<''else' '*len(x) ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqFBhZairUWFTXauZmJeikJtYoJGmU6GZmaZQYaOunppTnKquoK6Vk5qnUaH5v6AoM69EIU0jOjpa3UM9VkdBPVVdR8EQjAyA3OhoXWOQaGJRSYZ6bKzmfwA "Python 2 – TIO Nexus") ### How it works Python lets you compare different types. Numeric types are always smaller than iterables, and iterables are sorted by their type names, so ``` 0 < {} < [] < '' < () ``` This way, **f** does the following. * If **x** is numeric `x<{}` returns *True* and `1-(x<{})` returns **0**. The code after `and` does not get executed. * If **x** is iterable, `1-(x<{})` returns **1** (truthy), so the code after `and` gets executed. + If **x** is a list, `x<''` is true and **f** gets mapped over its items. + If **x** is a string, `x<''` is false and **x** is replaced with a string of spaces of the same length. [Answer] ## Ruby, ~~54 53~~ 49 bytes ``` f=->a{a*0==0?0:a*0==[]?a.map{|x|f[x]}:" "*a.size} ``` Maybe there is a better way, but: * x\*0 == 0 for integers * x\*0 == "" for strings * x\*0 == [] for arrays [Answer] ## Mathematica, 51 bytes I've currently got two solutions at this byte count: ``` #/._?NumberQ->0/.x_String:>StringReplace[x,_->" "]& StringReplace[#,_->" "]~Check~#&//@#/._?NumberQ->0& ``` The second one throws a bunch of warnings which can be ignored. ### Explanation In either case, we start by turning numbers into zeros with ``` #/._?NumberQ->0 ``` Then to process the string, there are two options. Either, we use another substitution that only applies to strings: ``` .../.x_String:>StringReplace[x,_->" "] ``` Or, we use the `MapAll` operator `//@` which maps a function over every single element in a nested list. The catch here is that we'll be trying to use `StringReplace` on zeros as well as the symbol `List` (since `//@` also goes through the heads of expressions), so we need to use `Check` (sort of like a `catch` statement in other languages) to avoid wreaking havoc with those values: ``` StringReplace[#,_->" "]~Check~#&//@... ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` nOa⁶ ``` This is a monadic link. Jelly's implicit printing does a lot of splatting; to verify that the output is what it should be, you can view the internal representation with `ŒṘ`. Note that this exposes strings as lists of characters, which is how the Jelly interpreter implements them. [Try it online!](https://tio.run/nexus/jelly#@5/nn/iocdt/ncPtRyc93DnjUdOaSIWHO7Y/apgTUJSZV1KsUJKRqgBkpBblJeYoFKUWFKUWp@aVJJZk5ucp5KdBpQtKSxQS81LAvPzSEiBX7///6OhoJQ@lWB0FpVQlHQVDMDIAcqOjdY1BoolFJRlKsbEA "Jelly – TIO Nexus") ### How it works ``` nOa⁶ Monadic link. Argument: z O Ordinal; replace all characters with the code points. This does not affect numbers. n Vectorizing not-equal; compare z with the result to the right, replacing characters with 1 and numbers with 0. a⁶ Logical AND space; replace all 1's with spaces. ``` [Answer] # Perl 6, ~~34~~ 48 bytes ``` {.deepmap:{$_~~Str??" "x.comb!!0}} ``` ``` {$_~~List??$_».&?BLOCK!!$_~~Str??" "x .comb!!0} ``` Expanded: ``` { # block-based lambda $_ ~~ List # if argument is a list/array ?? $_».&?BLOCK # then recurse for each element (&?BLOCK is a compile-time var) !! $_ ~~ Str # else if argument is a string ?? " "x .comb # then use space repeated by the string's length, !! 0 # else use the number 0 } ``` [Answer] ## [GAP](http://gap-system.org), 91 bytes GAP has a method `Zero` that returns the neutral additive element corresponding to an element of an additive structure. That handles numbers and even lists of numbers which are considered vectors, but not arbitrary lists. So let's add these and Chars and use that Strings are lists of Chars: ``` InstallOtherMethod(Zero,[IsChar],c->' '); InstallOtherMethod(Zero,[IsList],l->List(l,Zero)); ``` (I'm not counting the newline as it isn't needed.) Of course this is far away from the intended use of `Zero`, and GAP would complain if I hadn't used `Install`*Other*`Method`. Now I can do: ``` gap> Zero([[["H"],"e",1,1,0],[[-3],"arth"]]); [ [ [ " " ], " ", 0, 0, 0 ], [ [ 0 ], " " ] ] ``` I wouldn't say that the builtin does most of the job, one might rather suspect that writing a normal function should be shorter, but my best try doing that was 92 bytes long: ``` f:=function(x)if IsInt(x)then return 0;elif IsList(x)then return List(x,f);fi;return' ';end; ``` [Answer] ## Haskell, 115 bytes My language cannot handle any mix of numbers and strings in lists (but of course you can define a sum type and put that in a list), and its standard lists cannot handle differently nested lists. So I'm just doing what it can handle. I think that is not unfair because it is still long, and I mainly do it to show features of haskell that are rarely seen in haskell golfing solutions. Note that Strings are lists of Chars. ``` class N a where n::a->a instance N Double where n _=0 instance N Char where n _=' ' instance N a=>N[a]where n=map n ``` This handles any number as Double: ``` *Main> n 42 0.0 *Main> n 123.456 0.0 *Main> n "hi" " " *Main> n [[1,2],[3,4,5]] [[0.0,0.0],[0.0,0.0,0.0]] *Main> n ["hello","world!"] [" "," "] ``` [Answer] # PHP, 91 bytes ``` function f($a){return!is_array($a)?is_string($a)?str_pad("",strlen($a)):0:array_map(f,$a);} ``` if parameter is array: recurse using `array_map`. else if parameter is string: generate a strings of spaces with the same length. else `0`. `is_string` saves one byte over `is_numeric`; negating `is_array()` renders parentheses obsolete. Altogether it´s 17 bytes shorter than `if()recursion-loop;else x?string:number` with a call by reference. [Answer] ## Python 2, 59 bytes ``` g=lambda d:0if d*0==0else " "*len(d)if d*0==""else map(g,d) ``` uses G B's way to determine types [Answer] ##  Common Lisp, 87 ``` (defun c(e)(typecase e(list(mapcar'c e))(number 0)(string(map'string(lambda(u)#\ )e)))) ``` Ungolfed ``` (defun c(e) (typecase e (list (mapcar #'c e)) (number 0) (string (map 'string (lambda(u) #\space) e)))) ``` Example ``` > (c '((("H") "e" 1 1 0) ((-3) "arth"))) (((" ") " " 0 0 0) ((0) " ")) ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/) 13.2 and earlier, 1 byte Until and including version 13.2, monadic `∊` did exactly this. The old behaviour can be activated by setting `⎕ML` (**M**igration **L**evel) to zero. ``` ∊ ``` [Try it online!](https://tio.run/nexus/apl-dyalog-classic#e9Q31dfnUdsEg/9pQPJRR9d/t6L8XK9gfz8g19zQ1PJRzzaukHy4gJkBUOA/REAhTQGmWEFdSUmdC4uwOVZRQyNjPRNTM6xyShHYTVJSUMAhEZmviF0mOha7sK6hnpGrMQ5JJY/USiWccko6SqlAjFtFkJKOkY6SC5DEpcIZqN8YiAOUdAxwqQnxiFDSiTY0NLaIxakEaATIOYQURoNcHQt2tiEQGsTqREfrGgMFEotKMpSAugA "APL (Dyalog Classic) – TIO Nexus") Without using old behaviour it is 4 bytes: ``` ⊃0⍴⊂ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@5/2qG3Co65mg0e9Wx51Nf13K8rP9Qr29wOKmhuaWj7q2cYVkg8XMDMACvyHCCikKcAUK6grKalzYRE2xypqaGSsZ2JqhlVOKQK7SUoKCjgkIvMVsctEx2IX1jXUM3I1xiGp5JFaqYRTTklHKRWIcasIUtIx0lFyAZK4VDgD9RsDcYCSjgEuNSEeEUo60YaGxhaxOJUAjQA5h5DCaJCrY8HONgRCg1id6GhdY6BAYlFJhhJQFwA "APL (Dyalog Unicode) – TIO Nexus") `⊂` enclose `0⍴` make a length-zero list of copies of the entire input (preserves only structure and type info) `⊃` coerce one element from that (creates a prototypical array) [Answer] ## Groovy, 53 bytes ``` {[it].collectNested{it in String?" "*it.size():0}[0]} ``` This is an unnamed closure. [Try it here!](http://ideone.com/dxHel6) **Explanation**: Groovy has this method [`.collectNested`](http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html#collectNested(groovy.lang.Closure)) which helps to iterate through a list as if it was flattened. To handle special cases where only an integer or a string is passed without a list, simply wrap every input into a list and output the first element. [Answer] ## Pyke, 8 bytes [(Old version)](https://github.com/muddyfish/PYKE/commit/add0053688a23382f727a646f56fe657f61af8c2) ``` .FZ*0+d& ``` Explanation: ``` .FZ*0+d& - for i in deep_for(input): Z* - i*0 0+ - ^ + 0 d& - ^ and " " ``` This no longer works as an update made it so falsies of other types where there are truthies automatically convert to the falsey of the truthy type. [Answer] ## C#, ~~197~~ 195 Bytes ``` a=>{if(a is string||a is char)return new string(' ',(a as string)?.Length??1);try{System.Convert.ToDecimal(a);return 0;}catch{}var b=(object[])a;for(int i=0;i<b.Length;)b[i]=n(b[i++]);return b;}; ``` This function handles `char`, `string`, any builtin number type and recursive arrays. Full program, ungolfed whit output helper: ``` using System.Linq; class Class { public static void Main() { System.Func<object, object> n = null; n = a => { if (a is string || a is char) return new string(' ', (a as string)?.Length ?? 1); try { System.Convert.ToDecimal(a); return 0; } catch { } var b = (object[])a; for (int i = 0; i < b.Length;) b[i] = n(b[i++]); return b; }; var result = n(new object[] { new object[] { new object[] { "H" }, 'e', 1.5, 1, 0 }, new object[] { new object[] { -3 }, "arth" } }); System.Console.WriteLine(Output(result)); System.Console.Read(); } static string Output(object x) { var arr = x as object[]; if (arr != null) return "[" + string.Join(",", arr.Select(Output)) + "]"; else return x.ToString(); } }; ``` The `using` statement is only needed for the output helper, not for the actual function. [Try Online](http://csharppad.com/gist/5feca8f2e9f5f46525e4d561c76393fa) [Answer] # Javascript ES6, 81 chars ``` f=(x,t)=>(t=g=>eval(`try{x.${g}}catch(e){}`))`replace(/./g,' ')`||t`map(f)`||x&&0 ``` Test: ``` f=(x,t)=>(t=g=>eval(`try{x.${g}}catch(e){}`))`replace(/./g,' ')`||t`map(f)`||x&&0 console.log( `"" → "" 7 → 0 123.456 → 0 "X" → " " " " → " " "Yo!" → " " [] → [] [-1.2E3] → [0] ["Hey"] → [" "] ["H","e","y"] → [" "," "," "] ["R",2,"D",2] → [" ",0," ",0] ["C","3","P",0] → [" "," "," ",0] ["THX",[1138]] → [" ",[0]] ["T","H","X",[1138]] → [" "," "," ",[0]] [[["H"],"e",1,1,0],[[-3],"arth"]] → [[[" "]," ",0,0,0],[[0]," "]]` .split` `.map(s => s.split` → `.map(eval)) .every(([s,k]) => JSON.stringify(f(s))==JSON.stringify(k))) ``` [Answer] # Java 7, 262 (268) bytes ``` import java.util.*;Object c(Object o){if(o instanceof List){List r=new ArrayList();for(Object x:(List)o)r.add(c(x));return r;}if(o instanceof String){String r="\"";for(int i=((String)o).length();i-->0;r+=" ");return r+"\"";}return o instanceof Number?0:o instanceof Character?"' '":"";} ``` 282 + 6 for the added `\"` and `'` to pretty-print the String and characters. **Explanation:** ``` import java.util.*; // Required import for List and ArrayList Object c(Object o){ // Method with Object parameter and Object return-type if(o instanceof List){ // If the input is a List List r=new ArrayList(); // Create a result-list for(Object x:(List)o) // Loop over the items of the input-list r.add(c(x)); // And add all items with a recursive-call to this method // End of loop (implicit / single-line body) return r; // Return result-list }if(o instanceof String){ // If the input is a String instead String r="\""; // Create a result-String (starting with `"` for(int i=((String)o).length();i-->0;r+=" "); // Replace all characters in the String with a space return r+"\""; // Return the result within double-quotes } return o instanceof Number? // If the input is an integer or decimal instead: 0 // Return 0 :o instanceof Character? // If the input is a character instead: "' '" // Return ' ' : // Else: ""; // Return an empty String } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#tVHLT8IwGL/zV3z20lXCwpivsKAxeuDgIxEOGPVQRoGS0ZKuQ8myvx27MSQjusASL22//h7fi88XUmmY0SW1I80D@9Sr@QENQ3ikXMQ1gFBTzX1YPw9nzNfgW/lDkpiPLQlcGIbwmRzDAw81idMTVEewT7hViq7S2CLeWKqt9KttZVRJlE1HI8u3vgjxFNOREqC8ZN@3pxUXExJvbuON3hHKDLnQwDuWlTMksQMmJnpq8vFG47rpqXoHAdqZ1zNpkoeFLE/RfMjUTbNd@L2bUkV9bQCEAaN2ql4DLKJhYKaSD2cp@QjmZmB5IW8fQEk6PIDeKtRsbstI2wsD6UCYdhEy/f4NX5aiTsu1z84vSjl4gEtxBFBeAnqVJ@WMvf0ew43jdOsNx24xl3hJcrwWddkKVZPiLiZe9mDbxwpXtHrJHVq50f0urtRVvztAG4dfccdxrzLnatX2t/3@TGCA/y3b4Z9ZOWmawlKcwtXcMQ43brg7FaJKT1GxnaSWrL8B) ``` import java.util.*; class M{ static Object c(Object o){if(o instanceof List){List r=new ArrayList();for(Object x:(List)o)r.add(c(x));return r;}if(o instanceof String){String r="\"";for(int i=((String)o).length();i-->0;r+=" ");return r+"\"";}return o instanceof Number?0:o instanceof Character?"' '":"";} public static void main(String[] a){ System.out.println(c("")); System.out.println(c(7)); System.out.println(c(123.456)); System.out.println(c('X')); System.out.println(c(" ")); System.out.println(c("Yo!")); System.out.println(c(new ArrayList())); System.out.println(c(new ArrayList(){{add(-1.2e3);}})); System.out.println(c(new ArrayList(){{add("Hey");}})); System.out.println(c(new ArrayList(){{add('H');add('e');add('y');}})); System.out.println(c(new ArrayList(){{add('R');add(2);add('D');add(2);}})); System.out.println(c(new ArrayList(){{add("THX");add(new ArrayList(){{add(1138);}});}})); System.out.println(c(new ArrayList(){{add('T');add('H');add('X');add(new ArrayList(){{add(1138);}});}})); System.out.println(c(new ArrayList(){{add(new ArrayList(){{add(new ArrayList(){{add('H');}});add('e');add(1);add(1);add(0);}});add(new ArrayList(){{add(new ArrayList(){{add(-3);}});add("arth");}});}})); } } ``` **Output:** ``` "" 0 0 ' ' " " " " [] [0] [" "] [' ', ' ', ' '] [' ', 0, ' ', 0] [" ", [0]] [' ', ' ', ' ', [0]] [[[' '], ' ', 0, 0, 0], [[0], " "]] ``` ]
[Question] [ Given an integer ***n > 2***, print or return the smallest non-negative integer ***k*** such that ***a(n, k) = 9***, where ***a(n, k)*** is defined by: * ***a(n, 0) = n*** * ***a(n, k+1) =*** + ***a(n, k) / 2 + 1*** if ***a(n, k)*** is even + the sum of the digits of ***a(n, k)²*** (in base 10) if ***a(n, k)*** is odd ## Examples For ***n = 5***, the expected output is ***k = 4***: ``` a(5, 0) = 5 a(5, 1) = 7 (5² = 25 and 2 + 5 = 7) a(5, 2) = 13 (7² = 49 and 4 + 9 = 13) a(5, 3) = 16 (13² = 169 and 1 + 6 + 9 = 16) a(5, 4) = 9 (16 / 2 + 1) ``` For ***n = 40***, the expected output is ***k = 2***: ``` a(40, 0) = 40 a(40, 1) = 21 (40 / 2 + 1) a(40, 2) = 9 (21² = 441 and 4 + 4 + 1 = 9) ``` ## Clarifications and rules * The input is guaranteed to be greater than 2. * Your program should theoretically work for any value of ***n***. (In practice, it may be limited by the maximum integer size supported by your language.) * ***k*** may be either 0-indexed or 1-indexed. Please state it in your answer. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## First values Below are the first values from ***n = 3*** to ***n = 422***, with ***k*** 0-indexed. (For 1-indexing, just add `1` to these values.) ``` 1 2 4 3 3 5 0 4 3 4 2 6 1 1 6 5 5 4 1 5 2 3 3 7 6 2 3 2 2 7 6 6 5 6 6 5 1 2 2 6 6 3 1 4 3 4 4 8 1 7 6 3 5 4 6 3 2 3 3 8 7 7 3 7 4 6 6 7 5 7 6 6 6 2 4 3 3 3 6 7 3 7 2 4 7 2 6 5 6 4 7 5 2 5 6 9 6 2 3 8 2 7 1 4 6 6 6 5 1 7 4 4 3 3 7 4 3 4 2 9 6 8 6 8 6 4 6 8 2 5 3 7 6 7 3 8 2 6 7 8 6 7 5 7 6 7 4 3 3 5 6 4 3 4 4 4 6 7 6 8 3 4 6 8 7 3 6 5 6 8 3 3 2 7 6 6 5 7 6 5 7 8 2 6 3 3 6 6 6 7 4 10 6 7 3 3 6 4 1 9 2 3 3 8 7 2 6 5 2 7 7 7 6 7 3 6 7 2 4 8 3 5 6 5 6 4 2 4 6 8 3 5 6 4 7 5 2 3 6 10 7 7 3 9 2 7 1 9 5 7 6 5 6 7 4 9 6 3 6 6 3 4 2 8 7 7 6 8 6 4 7 9 4 3 3 7 7 8 3 9 4 7 6 8 3 6 6 8 7 7 7 8 6 5 7 4 6 4 2 6 7 7 6 5 3 4 7 5 4 5 3 5 7 7 6 8 2 7 1 9 6 4 6 5 7 7 2 9 6 8 7 4 3 7 4 6 6 7 6 9 3 4 6 4 2 3 3 8 1 7 6 7 2 6 7 8 3 7 5 6 7 8 2 9 3 3 6 7 6 4 4 4 6 7 6 7 6 7 6 8 7 5 6 11 7 7 3 8 4 4 7 4 6 7 3 5 6 2 2 10 6 3 6 4 3 4 4 9 7 8 3 3 6 7 7 6 4 3 6 8 ``` [Answer] # [Perl 6](https://perl6.org), 41 bytes (40 chars) ``` {+($_,{$_%2??[+] $_².comb!!$_/2+1}...9)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwv1pbQyVep1olXtXI3j5aO1ZBJf7QJr3k/NwkRUWVeH0jbcNaPT09S83a/9ZcxYkgXRomBprW/wE "Perl 6 – Try It Online") This uses 1-indexing of k's, so it gives 1 higher answers than the examples in OP. If this is not what the 1-indexing means, I'll have to add 1 byte more. **Explanation**: It's an anonymous function. We just use the Perl 6's facility for generating lists using recursion :—). It looks like this: `(first element),(block that takes the previous element and gives the next)...(end condition)`. In this case, the first element is `$_` (argument of the main function) and the end condition is `9` (fulfilled when we generate a 9). In the middle block, we use `$_` to refer to its argument ( = the previous element of the sequence). The `?? !!` is the old ternary operator (better known as `? :`). Finally, we take the length of this list by forcing numerical context by `+(...)`. The last weird thing here is the sum of digits. Numbers are `Cool` (behave both like strings and numbers), so we use a string method `.comb` on `$_²` (give list of characters = digits), then adding the characters up (that converts them back to numbers). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` ²DSµH‘$Ḃ?ßµ-n9$?‘ ``` [Try it online!](https://tio.run/##y0rNyan8///QJpfgQ1s9HjXMUHm4o8n@8PxDW3XzLFXsgQL///83MQAA "Jelly – Try It Online") Straight-forward approach. Uses 0-based indexing. ## Explanation ``` ²DSµH‘$Ḃ?ßµ-n9$?‘ Input: n ? If n9$ n != 9 µ Then ? If Ḃ n % 2 == 1 µ Then ² Square D Decimal digits S Sum $ Else H Halve ‘ Increment ß Call recursively Else - The constant -1 ‘ Increment ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~129~~ ~~126~~ ~~76~~ ~~68~~ ~~67~~ ~~64~~ ~~54~~ 53 bytes *-3 bytes thanks to Jonathan Frech. -8 bytes thanks to Maltysen. -7 bytes thanks to Jonathan Allan. -1 byte thanks to Mr. Xcoder.* ``` f=lambda n:n-9and-~f(n%2*sum(map(int,`n*n`))or 1+n/2) ``` [Try it online!](https://tio.run/##VVBBboMwELzzihFSFQimKeaUSOm1v6hi6gUcYEG2aZVLv04NqpJ2Tzuzs7OrmW6@HVkucRxHb@aTGIxXSIHJGvYYLSz52TJ8S3CD6ntyHjxyztQoHzYQdNSQRQc3f7RBqDxUwgJdijOOAl8tWbpTxkFTbZg0qtspQqht9LKq@YG7rAjMhh9cigMkMhQw9V9HCp/fpdur84Cx3lptGuPdin4X3iUSw6iUIxTh7H@rUesopLHU514NlVbgE@dHxTr/rhN@kvtgnQxqChZeXHjPlzQNMRUZH2S6bLElO@yer6PhTee8FVibWsAqbigpBcoyXWv5AQ "Python 2 – Try It Online") From somebody who probably doesn't know enough math, this seems completely arbitrary. :P [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` €9¡?o→½ȯΣd□¦2 ``` This is 1-indexed. [Try it online!](https://tio.run/##ASMA3P9odXNr///igqw5wqE/b@KGksK9yK/Oo2TilqHCpjL///80MA "Husk – Try It Online") ## Explanation Nothing too fancy here. ``` €9¡?o→½ȯΣd□¦2 Implicit input, say n = 5 ¡ Iterate the following function: ? ¦2 If divisible by 2, o→½ then halve and increment, ȯΣd□ else square, take digits and get their sum. This gives an infinite sequence: [5,7,13,16,9,9,9,9,9.. €9 1-based index of 9; print implicitly. ``` [Answer] # Mathematica, 58 bytes 1-indexed ``` If[#!=9,#0@If[OddQ@#,Total@IntegerDigits[#^2],#/2+1]+1,0]& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfMy1aWdHWUkfZwAHI9E9JCXRQ1gnJL0nMcfDMK0lNTy1yyUzPLCmOVo4zitVR1jfSNozVNtQxiFX7H1CUmVeioO@Qpu8QlJiXnhptrGNsEPv/PwA "Mathics – Try It Online") (in order to work on Mathics, `Tr` is replaced with `Total`) here is -1 byte version *by @JungHwanMin* (but it doesn't work on mathics so I kept both) # Mathematica, 57 bytes ``` If[#!=9,#0@If[2∣#,#/2+1,Total@IntegerDigits[#^2]]+1,0]& ``` [Answer] # JavaScript (ES6), ~~59~~ 50 bytes 0-indexed. ``` f=n=>n-9&&f(n%2?eval([...""+n*n].join`+`):n/2+1)+1 ``` --- ## Try it ``` o.innerText=( f=n=>n-9&&f(n%2?eval([...""+n*n].join`+`):n/2+1)+1 )(i.value=5);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i min=3 type=number><pre id=o> ``` --- ## Explanation The first thing we do is calculate `n-9`. If `n==9` then that, obviously, gives `0` and things stop there. If `n!=9` then `n-9` will give a non-zero value which, being truthy, means we can continue on through the logical AND. We call the function again, passing a new `n` to it, calculated as follows: ``` n%2? ``` If `n` modulo `2` is truthy - i.e., `n` is odd. ``` [...""+n*n] ``` Multiply `n` by itself, convert it to a string and destructure that string to an array of individual characters (digits). ``` .join`+` ``` Rejoin the characters to a string using `+`, giving us a mathematical expression. ``` eval( ) ``` Evaluate that expression, giving us the sum of the digits of `n*n`. ``` :n/2+1 ``` If `n%2` is falsey (i.e., `n` is even) then we simply divide `n` by `2` and add `1`. To the result of calling the function again, we then add `1`. So, using an initial input of `5`, the process goes as follows: ``` f(5) = -4&&f(7)+1 = -2&&(f(13)+1)+1 = 4&&((f(16)+1)+1)+1 = 7&&(((f(9)+1)+1)+1)+1 = (((0+1)+1)+1)+1 = 4 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles) (use of ternary if) ``` ²DSµH‘µḂ?_9$пL ``` A monadic link taking and returning numbers. **1-indexed** **[Try it online!](https://tio.run/##ASUA2v9qZWxsef//wrJEU8K1SOKAmMK14biCP185JMOQwr9M////MTk0 "Jelly – Try It Online")** or see a [test-suite](https://tio.run/##ATIAzf9qZWxsef//wrJEU8K1SOKAmMK14biCP185JMOQwr9M/zNyNDIyw4figqzigJlzMzBH/w "Jelly – Try It Online") (coerces results to be 0-indexed and formats like OP code-block) ### How? ``` ²DSµH‘µḂ?_9$пL - Link: number, n п - collect results in a list while: $ - last two links as a monad: _9 - subtract nine ? - if: Ḃ - bit - current loop input modulo by 2 (1 if odd, 0 if even) µ - ...then: ² - square the current loop input D - cast to a list of its decimal digits S - sum µ - ...else: H - halve current loop input ‘ - increment L - length (get the number of results collected - - this includes the 9, so is 1-indexed w.r.t. k) ``` [Answer] ## Haskell, ~~62~~ 59 bytes ``` f 9=0 f a=1+f(cycle[div a 2+1,sum[read[d]|d<-show$a^2]]!!a) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03B0taAK00h0dZQO00juTI5JzU6JbNMIVHBSNtQp7g0N7ooNTElOiW2JsVGtzgjv1wlMc4oNlZRMVHzf25iZp6CrUJKPpeCgkJBUWZeiYKKQpqCKSrXxOA/AA "Haskell – Try It Online") Edit: -3 bytes thanks to @Ørjan Johansen. [Answer] # [Perl 5](https://www.perl.org/), 56 + 1 (-n) = 57 bytes ``` $|++,$_=$_%2?eval$_**2=~s/./+$&/gr:1+$_/2while$_-9;say$| ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lRltbRyXeViVe1cg@tSwxRyVeS8vItq5YX09fW0VNP73IylBbJV7fqDwjMydVJV7X0ro4sVKl5v9/y3/5BSWZ@XnF/3V9TfUMDA3@6@YBAA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` [Ð9Q#Èi2÷>ënSO]N ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@vAEy0Dlwx2ZRoe32x1enRfsH@v3/7@JkREA "05AB1E – Try It Online") **Explanation** ``` [ # start a loop Ð # triplicate current number 9Q# # if it equals 9, break Èi # if even 2÷> # divide by 2 and increment ë # else n # square SO # sum digits ] # end loop N # push the iteration counter N ``` [Answer] # VB.NET (.NET 4.5.2), 107 + 20 (imports) = 117 bytes Requires `Imports System.Linq` ``` Function A(n) While n<>9 n=If(n Mod 2=0,n/2+1,CStr(n^2).Sum(Function(c)Val(c))) A+=1 End While End Function ``` Function which takes `n` as an integer input and returns a 0-based `k`. Ungolfed: ``` Function A(n) ' input/output types are Object, but we will be casting to integer 'A = 0 ' VB will create an implicit variable with the same name as the function ' loop until a(n, k) = 9 ' using n as the variable to store a(n, k) While n <> 9 n = If(n Mod 2 = 0, ' equivalent to c# ternary ?: operator n / 2 + 1, ' even case CStr(n ^ 2).Sum(Function(c) Val(c))) ' odd case ' cast number to string ' then convert each char to the number it represents ' and do a linq sum A += 1 ' Object + Integer will coerce to an integer End While ' Where's the return? ' That implicit variable with the matching name will get returned if there's no explicit return End Function ``` [Answer] # Golfscript, 34 bytes [Try it online!](http://golfscript.apphb.com/?c=OyI0MCIKfns5LX17LjIley4qYHsrNDgtfSo0OC19ezIvKX1pZn0vLA%3D%3D) I really need a better way than I have to add up the digits of a number. ``` ~{9-}{.2%{.*`{+48-}*48-}{2/)}if}/, ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~23~~ 22 bytes For now, this is a recursive function ~~but I'll try to switch to `.W` (functional while) to save bytes instead~~. ``` L&-b9hy|*%b2sj^b2Th/b2 ``` **[Try it here!](https://pyth.herokuapp.com/?code=L%26-b9hy%7C%2a%25b2sj%5Eb2Th%2Fb2%3B%2B%225+-%3E+%22%60y5%2B%2240+-%3E+%22%60y40%3B&input=%22Test%22%0A2&test_suite=1&debug=0)** (with additional code to call the function - use **`y`**`<your_number>` - without spaces) [Answer] # Java 8, ~~110~~ 98 bytes ``` n->{int k=0,s;for(;n!=9;k++){s=0;for(int c:(n*n+"").getBytes())s+=c-48;n=n%2<1?n/2+1:s;}return k;} ``` 0-indexed **Explanation:** [Try it here.](https://tio.run/##dU/BasMwDL33K7TCwJ6XLC0dbPW8we7rpcfRg@e6xU2qBEsplJBvz5ys14Ek0HtC772Tvdisbjye9uXgKksEXzZgNwMIyD4erPOwGdcJACfGiVInpE@dithycLABBAMDZu/deFKa4pH0oY5C45151aVSsiNTTND0aS3wAdV8LvOj588rexJSkjIuW71oNHi/fFt84NNSLdak@@i5jQil7gc9S6pN@1Ml1Zv4pQ57OCfjYssx4PF7B1b@ud5eif05r1vOm0RxhQJzJ57llOFfflXIW8h@@AU) ``` n-> // Method with integer as both input and return-type int k=0, // Result-integer `k` starting at 0 s; // Sum-integer for(;n!=9; // Loop (1) as long as `n` is not 9 k++){ // And increase `k` by 1 after every iteration s=0; // Reset sum `s` to 0 for(int c:(n*n+"").getBytes()) // Do `n*n` and inner loop (2) over the digits as characters s+=c-48; // And increase the sum `s` with these digits // End of inner loop (2) (implicit / single-line body) n=n%2<1? // If `n` is even: n/2+1 // Change `n` to `n/2+1` : // Else: s; // Change `n` to sum `s` } // End of loop (1) return k; // Return the result `k` } // End of separated method (2) ``` [Answer] # [Clojure](https://clojure.org/) v1.8, ~~124~~ ~~113~~ 112 bytes 0-indexed ``` (fn[n](loop[a n k 0](if(= a 9)k(recur(if(even? a)(+(/ a 2)1)(apply +(map #(-(int %)48)(str(* a a)))))(inc k))))) ``` [Try it online!](https://repl.it/languages/clojure) # Explanation ``` (loop[a n k 0](if(= a 9)...)) Loop until a=9 (if(even? a)(+(/ a 2)1)...) If even, a(n, k) / 2 + 1 if a(n, k) (if(even? a)...(apply +(map #(-(int %)48)(str(* a a))))) If odd, calculate the sum of digits of a(n, k)² #(-(int %)48) Convert character to number ``` [Answer] # Pyth, 18 bytes ``` tl.u?%N2sj*NNTh/N2 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=tl.u%3F%25N2sj%2aNNTh%2FN2&input=5&test_suite_input=3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25&debug=0) ### Explanation: ``` tl.u?%N2sj*NNTh/N2 .u apply the following function to the input, until it runs into a fixed point ?%N2 if value % 2 == 1: *NN value * value j T convert to digits s sum else: /N2 value / 2 h + 1 l get the length of all visited values t - 1 ``` [Answer] # Japt, ~~22~~ 21 bytes 0-indexed. ``` NcUÆ=v ?U/2Ä:U²ìxà b9 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=TmNVxj12ID9VLzLEOlWy7HjDIGI5&input=NDIy) --- ## Explanation Implicit input of integer `U`. ``` UÆ Ã ``` Generate an array of integers from `0` to `U-1` and pass each through a function. ``` = ``` Set the value of `U`. ``` v ? ``` If `U` is divisible by 2. ``` U/2Ä ``` `U` divided by 2, plus 1 (`Ä`). ``` :U²ìx ``` Else: `U` to the power of 2 (`²`), split to an array of digits (`ì`) and reduced by addition (`x`). ``` Nc ``` Append the resulting array to the array of inputs. ``` b9 ``` Find the index of the first occurrence of `9` in the array. Implicitly output the result. ]
[Question] [ When you convert a fraction to a decimal number and you want to store that number, you often have to round it, because you only want to use a certain amount of memory. Let's say you can only store 5 decimal digits, then 5/3 becomes 1.6667. If you can store only 2 decimal digits it will be 1.7 (now assuming that it is always between 0 and 9.99...). If you now try to reverse that process with 1.7 and you want to get your fraction back, that can be difficult, since you know that 1.7 is only a rounded number. Of course you can try 17/10 but that is rather an 'ugly' fraction compared to the 'elegant' 5/3. So the goal is now finding the fraction a/b with the least denominator b, that results in the rounded decimal number when correctly rounded. ## Details The input contains a string with a number of 1 up to 5 digits that is between 0 (including) and 10 (not including) with a '.' after the first digit. Let's say `n` denotes the number of digits. The output must be a list/array of two integers `[numerator, denominator]` or a rational datatype (you can create your own or use built-in) where the numerator is non-negative and the denominator is positive. The fraction numerator/denominator must be equal to the input when correctly rounded to `n` digits (which means `n-1` digits after the decimal point). **Restriction: only one loop statement allowed.** This means that you can use only one single looping statement (like `for` or `while` or `goto` etc. as well as functional loops like `map` or `fold` that apply code to every element of a list/array) in your whole code, but you are free to 'abuse' it or use recursion etc. You should write a function. If your language does not have functions (or even if it does), you can alternatively assume that the input is stored in a variable (or input via stdin) and print the result or write it to a file. The lowest number of bytes wins. ### Rounding The rounding should follow the 'conventional' rounding rules, i.e. if the last digit that will be cut off is 5 or greater, you will round up, and you will round down for any other cases, so e.g: 4.5494 will result when rounding to * 1 digit: 5 * 2 digits: 4.5 * 3 digits: 4.55 * 4 digits: 4.549 ## Examples Please include following test cases and other 'interesting' ones: ``` Input 1.7 Output 5/3 Input 0. Output 0/1 Input 0.001 Output 1/667 Input 3.1416 Output 355/113 ``` [Answer] ## T-SQL 254 While T-SQL isn't really suited to this sort of thing, it wa fun to try. The performance gets real bad the higher the denominator. It is limited to a denominator of 1000. Input is a float variable @ ``` WITH e AS(SELECT *FROM(VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(0))n(n)),t AS(SELECT ROW_NUMBER()OVER(ORDER BY(SELECT \))N FROM e a,e b,e c,e d)SELECT TOP 1concat(n.n,'/',d.n)FROM t d,t n WHERE round(n.n/(d.n+.0),len(parsename(@,1)))=@ ORDER BY d.n,n.n ``` A breakdown of the query ``` WITH -- Start CTE(Common Table Expression) e AS( --Create a set of 10 rows SELECT * FROM(VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(0))n(n) ), t AS( SELECT ROW_NUMBER()OVER(ORDER BY(SELECT \))N FROM e a,e b,e c,e d --Cross join e to produce 1000 numbered rows ) SELECT TOP 1 --Grab first result concat(n.n,'/',d.n) --Build output FROM t d,t n --Cross join t against itself for denominator and numerator WHERE round( n.n/(d.n+.0), --Force float division with +.0 len(parsename(@,1)) --Get rounding length )=@ --Filter where the rounded result = input ORDER BY d.n,n.n --Order by denominator then numerator ``` [Answer] # Haskell, ~~62~~ 59 if only the names weren't so long... ``` import Data.Ratio f s=approxRational(read s)$50/10^length s ``` this is a function returning a `Rational` value. **explanation:** the function `approxRational` is a function which takes a float number and a float epsilon and returns the most simple rational which is in distance epsilon of the input. basically, returns the most simple approximation of the float to a rational in a "forgivable error" distance. let's exploit this function for our use. for this we will need to figure out what is the area of the floats that round up to the given number. then getting this into the `approxRational` function will get us the answer. let's try 1.7, for example. the lowest float that rounds to 1.7 is 1.65. any lower will not round to 1.7. similarly, the upper bound of the floats that round to 1.7 is 1.75. both limits are the bounds are the input number +/- 0.05. it can be easily shown that this distance is always `5 * 10 ^ -(the length of the input - 1)` (the -1 is because there is always a '.' in the input). from here the code is quite simple. **test cases:** ``` *Main> map f ["1.7", "0.001", "3.1416"] [5 % 3,1 % 667,355 % 113] ``` unfortunately it doesn't work on "0." because Haskell's parser function doesn't recognize a `.` at the end of a float. this can be fixed for 5 bytes by replacing `read s` by `read$s++"0"`. [Answer] ## Ruby, ~~127~~ 125 bytes ``` f=->n{b=q=r=(m=n.sub(?.,'').to_r)/d=10**p=n.count('0-9')-1 b=r if(r=(q*d-=1).round.to_r/d).round(p).to_f.to_s==n while d>1 b} ``` Defines a function `f` which returns the result as a `Rational`. E.g. if you append this code ``` p f["1.7"] p f["0."] p f["0.001"] p f["3.1416"] ``` You get ``` (5/3) (0/1) (1/667) (355/113) ``` The loop is over denominators. I'm starting with the full fraction, e.g. `31416/10000` for the last example. Then I'm decrementing the denominator, proportionally decrement the numerator (and round it). If the resulting rational rounds to the same as the input number, I'm remembering a new best fraction. [Answer] # Python 2.7+, 111 characters Proof that you can write horrible code in any language: ``` def f(s): t,e,y=float(s),50*10**-len(s),1;n=d=x=0 while x|y:n,d=n+x,d+y;a=1.*n/d;x,y=a<t-e,a>t+e return n,d ``` ## Output ``` >>> [f(s) for s in ("1.7", "0.", "0.001", "3.1416")] [(5, 3), (0, 1), (1, 667), (355, 113)] ``` [Answer] # CJam, ~~41~~ ~~40~~ 36 bytes ``` Q'./1=,:L0\{;)_Qd*mo_d2$/LmOQd-}g'/@ ``` Asuumes the input string is stored in Q, which is explicitly allowed by the question. [Try it online.](http://cjam.aditsu.net "CJam interpreter") ### Test cases ``` $ for d in 1.7 0. 0.001 3.1416; do cjam <(echo "\"$d\":Q; > Q'./1=,:L0\{;)_Qd*mo_d2$/LmOQd-}g'/@ > "); echo; done 5/3 0/1 1/667 355/113 ``` ### How it works ``` Q'./1=,:L " Count the number of characters after the dot and store it in L. "; 0\ " Push 0 (denominator) and swap it with L (dummy value). "; { " "; ; " Discard the topmost item from the stack (numerator or dummy value). "; ) " Increment the denominator. "; _Qd*mo " Multiply a copy by Double(Q) and round. "; _d2$/ " Cast a copy to Double and it divide it by the denominator. "; LmO " Round to L digits. "; Qd " If the result is not Double(Q), "; }g " repeat the loop. "; ./@ " Push a slash and rotate the denominator on top of it. "; ``` [Answer] ## Mathematica, 49 53 characters ``` Rationalize[ToExpression@#,5 10^(1-StringLength@#)]&@ ``` Usage: ``` Rationalize[ToExpression@#,5 10^(1-StringLength@#)]&@"1.7" ``` Output: ``` 5/3 ``` Test cases: ``` input: 1.7 output: 5/3 input: 0. output: 0 input: 0.001 output: 1/999 input: 3.1416 output: 355/113 ``` The 0.001 case strikes me as odd; as the rationalize function didn't work according to its description, when it didn't find the 1/667 case. It should output the number with the smallest denominator that is within specified bounds. [Answer] ## APL, 50 ``` 2↑⍎⍕(⍎x←⍞){50>|(10*⍴x)×⍺-⍵÷⍨n←⌊.5+⍺×⍵:n ⍵⋄''}¨⍳1e5 ``` As long as you don't count `eval` and `toString` as loops **Explanation** The approach is to iterate over 1 to 10000 as denominator and calculate the numerator that most closely match the float, then check if the error is within bounds. Lastly, select the smallest pair from all the fractions found. `(⍎x←⍞)` Take string input from screen, assign to `x`, and eval `⍳1e5` Generate array from 1 to 10000 `{...}¨` For each element of the array, call function with it and `(⍎x←⍞)` and arguments **(loop)** `⍺×⍵` Multiply the arguments `⌊.5+` Round off (by adding 0.5 then rounding down) `n←` Assign to `n` `⍺-⍵÷⍨` Divide by right argument, then subtract from left argument `(10*⍴x)×` Multiply by 10 to the power of "length of `x`" `|` Take absolute value `50>` Check if less than 50 (length of `x` is 2 more than the no. of d.p., so use 50 here instead of 0.5) `:n ⍵⋄''` If the previous check returns true, then return the array of `n` and the right argument, else return empty string. `⍎⍕` `toString` and then `eval` to get an array of all the numbers in the array `2↑` Select only the first 2 elements, which is the first numerator-denominator pair found [Answer] # GNU dc, 72 bytes No loops - dc doesn't even have them. Instead the control comes from a single tail-recursive macro - idiomatic for dc. ``` ?dXAr^d2*sf*sq1sd0[ld1+sd]sD[r1+r]sN[dlf*ld/1+2/dlq>Ndlq<Dlq!=m]dsmxpldp ``` ## Output: ``` $ for n in 1.7 0. 0.001 3.1416; do echo " n = $n:"; dc unround.dc <<< $n; done n = 1.7: 5 3 n = 0.: 0 1 n = 0.001: 1 667 n = 3.1416: 355 113 $ ``` Phew. Partial explanation in [this answer](https://codegolf.stackexchange.com/a/38152/11259). [Answer] # Mathematica, 111 characters ``` f=Module[{a=0,b=1,k},While[Round[a/b,10^-(StringLength[#]-2)]!=(k=ToExpression)@#,If[N[a/b]>k@#,b++,a++]];a/b]& ``` Pretty simple really, and I don't think it converges anywhere as fast as the other solutions, since the numerator and denominator only increment by one. I mostly wanted to find the simple solution to this. I'll have to see the other answers and see what clever stuff happens there. ## Output ``` f/@{"1.7","0.0","0.001","3.1416","3.14"} {5/3, 0, 1/667, 355/113, 22/7} ``` Does anyone here celebrate [Pi Approximation Day](http://www.qwantz.com/index.php?comic=955)? [Answer] # Applescript, >300 bytes I wanted to do this in a language that natively does the type of rounding required. Turns out Applescript fits the bill. Then I saw the enum [`rounding as taught in school`](https://developer.apple.com/library/mac/documentation/applescript/conceptual/applescriptlangguide/reference/aslr_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW43), and couldn't resist the using it, despite the blatant uncompetitiveness of Applescript for golfing purposes: ``` on u(q) set n to 0 set d to 1 set x to 0 set AppleScript's text item delimiters to "." set f to 10 ^ (q's text item 2's length) repeat until x = q as real set x to (round n * f / d rounding as taught in school) / f if x < q then set n to n + 1 if x > q then set d to d + 1 end repeat return {n, d} end u log my u("1.7") log my u("0.") log my u("0.001") log my u("3.1416") ``` This can be golfed a bit more, but probably not worth it. ### Output: ``` (*5, 3*) (*0, 1*) (*1, 667*) (*355, 113*) ``` [Answer] # BC, ~~151~~ 148 bytes # Edit - faster and shorter version ``` define f(v){s=scale(x=v);for(i=r=1;i<=10^s;i+=1){t=v*i+1/2;scale=0;p=t/=1;scale=s+1;t=t/i+10^-s/2;scale=s;t=t/1-v;if((t*=-1^(t<0))<r){r=t;n=p;d=i}}} ``` same test case. A lot is similar to the previous version, but instead of trying all possible n / d combinations, we hill-climb over the residues of v and backward quotients of multiples m==v\*d and denominators d. Again the precision of the computation is the same. Here is it untangled: ``` define f(v) { s= scale(x=v) for( i=r=1; i <= 10^s; i+=1 ){ t= v * i +1/2 scale=0 m=t/=1 # this rounded multiple becomes nominator if # backward quotient is first closest to an integer scale=s+1 t= t / i +10^-s/2 # divide multiple back by denominator, start rounding again... scale=s t= t/1 - v # ...rounding done. Signed residue of backward quotient if( (t*= -1^(t < 0)) < r ){ r=t n=m d=i } } } ``` This version really has a mere single loop and does only $\Theta\left(\operatorname{fractional\_decimals}(v)\right)$ arithmetic operations. # Original - slow version This functions computes the smallest nominator n and denominator d such that the fraction n / d rounded to fractional\_decimals(v) digits is equal to a given decimal value v. ``` define f(v){s=scale(v);j=0;for(i=r=1;j<=v*10^s;){scale=s+1;t=j/i+10^-s/2;scale=s;t=t/1-v;if((t*=-1^(t<0))<r){r=t;n=j;d=i};if((i+=1)>10^s){i=1;j+=1}};v} ``` test case: ``` define o(){ print "Input ",x,"\tOutput ",n,"/",d,"\n" } f(1.7); o() > 0 > Input 1.7 Output 5/3 > 0 f(0.); o() > 0 > Input 0 Output 0/1 > 0 f(0.001); o() > 0 > Input .001 Output 1/667 > 0 f(3.1416); o() > 0 > Input 3.1416 Output 355/113 > 0 ``` And here is it untangled: ``` define f(v) { s=scale(x=v) # save in global for later print j=0 # do a full sequential hill-climb over the residues r of v and all possible # fractions n / d with fractional_decimals(v) == s precision. for( i=r=1; j <= v * 10^s; ){ scale=s+1 t= j / i +10^-s/2 # start rounding... scale=s t= t/1 - v # ...rounding done. New residue, but still signed if( (t*= -1^(t < 0)) < r ){ # absolute residue better? # climb hill r=t n=j d=i } if( (i+=1) > 10^s ){ # next inner step. End? # next outer step i=1 j+=1 } } v } ``` I admit, I cheated a little by emulating a second inner loop inside a single outer loop, but without using any further loop statements. And that's why it actually does $\Theta\left(v \operatorname{fractional\_decimals}(v)^2\right)$ arithmetic operations. [Answer] # C, 233 This works by calling a rationalization function r() with a starting denominator of 1. The function begins incrementing a numerator, and checking at every increment whether the resulting number, when rounded to the same number of digits as the original, has the same string representation as the original. Once the numerator has been incremented so much that the result is greater than the original, the function increments the denominator and calls itself. This of course uses much more code, but I think the spirit of the problem exonerates this bare-bones approach; for all we know, the internal rationalize() functions of modern languages have lots of internal loops. Note that this doesn't work for an input of "0." because that is not a standard way to write a float, so when it re-writes the float to string, the result will never be a "0.". The specs want a function that returns values instead of just printing to screen, hence the argument-passing. Code (ungolfed): ``` void r(char* x, int* a, int* b) { int i = -1; char z[32]; double v =atof(x); while(1) { i++; double y = ((double)i)/((double)(*b)); double w; sprintf(z, "%.*f", strlen(strchr(x,'.'))-1, y); if(strcmp(x, z)==0) { *a = i; return; } w = atof(z); if(w > v) { (*b)++; r(x, a, b); return; } } } ``` Usage: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { int num; int denom = 1; // start with a denominator of 1 r(argv[1], &num, &denom); printf("%d/%d\n", num, denom); return 0; } ``` Golfed code: ``` typedef double D; void r(char*x,int*a,int*b){int i=-1;char z[32];D v=atof(x);while(1){i++;D y=((D)i)/((D)(*b));D w;sprintf(z,"%.*f",strlen(strchr(x,'.'))-1,y);if(!strcmp(x,z)){*a=i;return;}w=atof(z);if(w>v){(*b)++;r(x,a,b);return;}}} ``` [Answer] # Pure Bash, 92 bytes As a partial explanation for [this answer](https://codegolf.stackexchange.com/a/38148/11259), here it is ported to bash: ``` f=${1#*.} q=${1//.} for((n=0,d=1;x-q;x=2*10**${#f}*n/d+1>>1,n+=x<q,d+=x>q));{ :;} echo $n/$d ``` Notably: * bash has integer-only arithmetic. So we appropriately scale everything up by 2\*10^(number of fractional digits). * bash rounds *down* to nearest integer; the 2 in the expression above is so we can instead round to nearest integer (*up or down*). * Just one loop * we check if the rational overshoots or undershoots the decimal and increment the denominator or numerator accordingly. ### Output: ``` $ for n in 1.7 0. 0.001 3.1416; do echo " n = $n:"; ./unround.sh $n; done n = 1.7: 5/3 n = 0.: 0/1 n = 0.001: 1/667 n = 3.1416: 355/113 $ ``` [Answer] # JavaScript (E6) 85 ``` F=r=>(l=>{for(n=r,d=1;l&&r!=((n=r*d+1/2|0)/d).toFixed(l);d++);})(r.length-2)||[n|0,d] ``` **Ungolfed** ``` F=r=>{ l = r.length-2; // decimal digits if (l==0) return [r|0, 1] // if no decimal return the same (conv to number) with denominator 1 // loop for increasing denominator for(d = 2; r != ( // loop until find an equal result // given R=N/D ==> N=R*D (n=r*d+1/2|0) // find possible numerator, rounding (+0.5 and trunc) /d).toFixed(l); // calc result to given decimals d++); return [n,d] } ``` **Test** In FireFox/FireBug console ``` ;["1.7","0.","0.001","3.1416","9.9999"].forEach(v => console.log(v,F(v))) ``` *Output* ``` 1.7 [5, 3] 0. [0, 1] 0.001 [1, 667] 3.1416 [355, 113] 9.9999 [66669, 6667] ``` ]
[Question] [ > > **Thanks for all the entries, the deadline has now passed and the final scores are at the end of the question.** > > **Congratulations to [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi) on a fairly comprehensive victory.** > > > This is a [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge, the aim of which is to create a program which wins more often than any of its opponents in a lowest unique bid auction. ## Input As input the program will receive all the previous rounds' bidding, one round per line, all bids separated by spaces as follows: ``` 10 4 12 11 12 4 7 3 3 1 2 9 15 1 15 15 9 3 3 21 6 4 3 8 6 13 1 ``` Each column of the input represents the bidding of one bot. The first column is the receiving program's bids, while the rest are in a randomly generated order. Thanks to [hammar](https://codegolf.meta.stackexchange.com/users/1811/hammar) and [Peter Taylor](https://codegolf.meta.stackexchange.com/users/194/peter-taylor) for their input. Input is provided as the one and only command-line (multi-line) argument to your program: ``` ./test1 '1 2 3 4 5 6 1 2' ``` This means that your program will need to be runnable from the command-line. Please give an example of invocation as part of your answer. **In the first round only** as a means of letting you know how many bots you're up against, the input will be a line of `0`s - one for each bot. ## Output Your program should output its bid as an integer in the range 1 to 100 (inclusive). ## Scorer Program This is my scoring program - any suggestions for additions, improvements or bug fixes would be welcomed. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define NUMROUNDS 10 #define NUMBOTS 4 #define MAXINPUTSIZE 10000 #define MAXFILENAMESIZE 100 int main() { int i,j,a,b,winner; FILE *fp; char bots[NUMBOTS][MAXFILENAMESIZE]={"onesconfident","random100","random20","random5"}; char openstring[MAXFILENAMESIZE+MAXINPUTSIZE+3]; char input[MAXINPUTSIZE]; char buff[5]; int shuffle[NUMBOTS],auction[100],lowestbid[NUMBOTS]={[0 ... NUMBOTS-1]=101}; static int guesses[NUMBOTS][NUMROUNDS]; static int scores[NUMBOTS],totalwinbids[NUMBOTS]; srand(time(NULL)); for(i=0;i<NUMROUNDS;i++) { /*blank the auction bids for the next round */ for(a=0;a<100;a++) { auction[a]=9999; } /*loop through the bots sending the input and storing their output */ for(j=0;j<NUMBOTS;j++) { /*Fisher-Yates shuffle */ for(b=0;b<NUMBOTS;b++) { shuffle[b]=(b+j)%NUMBOTS;/*put current bot at index 0 */ } for(b=NUMBOTS-1;b>1;b--) { int z=rand()%(b-1)+1;/*make sure shuffle leaves index 0 alone */ int t=shuffle[b]; shuffle[b]=shuffle[z]; shuffle[z]=t; } /*generate the input for the bots */ strcpy(input,"'"); if(i==0) { for(b=0;b<NUMBOTS;b++) { if(b!=0) sprintf(input,"%s 0",input); else sprintf(input,"%s0",input); } } else { for(a=0;a<i;a++) { for(b=0;b<NUMBOTS;b++) { if(b!=0) sprintf(input,"%s %d",input,guesses[shuffle[b]][a]); else sprintf(input,"%s%d",input,guesses[shuffle[b]][a]); } if(a!=i-1) strcat(input,"\n"); } } strcat(input,"'"); sprintf(openstring,"%s %s",bots[j],input); fp=popen(openstring,"r"); fgets(buff,3,fp); fflush(NULL); pclose(fp); guesses[j][i]=atoi(buff); /*add the bid to the auction, eliminating any duplicates */ if(auction[atoi(buff)-1]!=9999) auction[atoi(buff)-1]=9998; else auction[atoi(buff)-1]=j; } winner=9999; /*add one to the score of the winning bot */ for(a=0;a<100;a++) { if(auction[a]!=9998 && auction[a]!=9999) { winner=auction[a]; scores[winner]+=1; totalwinbids[winner]+=guesses[winner][i]; if(guesses[winner][i]<lowestbid[winner]) lowestbid[winner]=guesses[winner][i]; break; } } /*output this round's bids and the winning bot's name */ strcpy(input,""); for(b=0;b<NUMBOTS;b++) { if(strcmp(input,"")!=0) sprintf(input,"%s %d",input,guesses[b][i]); else sprintf(input,"%d",guesses[b][i]); } if(winner!=9999) printf("%s %s\n",input,bots[winner]); else printf("%s No winner\n",input); } /*output final scores */ printf("\nResults:\n"); printf("Bot\tScore\tTotal\tLowest\n"); for(a=0;a<NUMBOTS;a++) { printf("%s\t%d\t%d\t%d\n",bots[a],scores[a],totalwinbids[a],lowestbid[a]); } return 0; } ``` ## Test players **One's confident** Always bids 1. ``` #include <stdio.h> int main() { printf("1"); return 0; } ``` **Random100** Bids at random over the entire range ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(getpid()); printf("%d",rand()%100+1); return 0; } ``` **Random20** Bids at random between 1 and 20 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(getpid()); printf("%d",rand()%20+1); return 0; } ``` **Random5** Bids at random between 1 and 5 ``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(getpid()); printf("%d",rand()%5+1); return 0; } ``` Example run-through: ``` 1 38 5 2 onesconfident 1 66 13 5 onesconfident 1 94 1 3 random5 1 22 9 1 random20 1 50 17 4 onesconfident 1 78 5 2 onesconfident 1 6 13 5 onesconfident 1 34 1 3 random5 1 62 9 1 random20 1 90 17 4 onesconfident Results: Bot Score Total Lowest onesconfident 6 6 1 random100 0 0 101 random20 2 18 9 random5 2 6 3 ``` These players are for testing purposes only. They will NOT be included in the competition. You can enter as many bots as you wish, so if anyone does enter a bot that only guesses `1`, you can enter another that does the same to render it useless. ## Winner The winning bot in each round is the one which gives the lowest *unique* bid. So given a round in which the following bids are made: `1 1 3 5 2 3 6 3 2 8 7` the winner would be the bot that bid `5` because the `1`s, `2`s and `3`s are not unique. The winner of the competition will be the program which wins the most times after 100 rounds. In case of a tie the total of the winning bids will be used as a tie-breaker, and in the event of that also being a tie, the lowest winning bid will be used as a further tie-breaker. These scoring factors are all output by the scoring program. I will run the scoring program on all working programs that have been entered 2 weeks from today (18th February **now extended to 11pm(GMT) on the 20th of February**). I'll upvote all working entries and accept the winner of my scoring run. **Final scoring run** ``` 1 9 3 2 1 6 4 3 6 8 7 10 26 6 10 5 26 2 5 8 8 5 7 6 42 1 ./phinotpi2 1 11 4 2 1 4 9 20 6 8 7 6 26 4 8 4 26 2 5 8 8 5 7 7 42 1 ./phinotpi2 1 7 9 2 1 4 3 20 6 8 7 6 7 4 8 9 26 2 5 8 8 5 4 9 42 3 node minitech1.js 1 13 20 2 1 3 3 20 6 8 7 7 9 6 8 20 26 2 5 8 8 5 9 9 42 3 ./dirichlet 1 12 13 2 1 1 3 20 6 8 7 7 9 6 9 13 26 2 5 8 8 5 20 9 42 3 ./dirichlet 1 2 4 2 1 1 3 20 6 8 7 7 9 6 9 12 26 2 5 8 8 5 13 9 42 3 python blazer1.py 1 11 4 2 1 4 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 12 9 42 3 ./celtschk 1 3 4 2 1 1 3 20 6 8 7 6 7 4 8 9 26 2 5 8 8 5 4 9 42 3 node minitech1.js 1 7 4 2 1 1 3 20 6 8 7 9 26 6 7 20 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 9 9 2 1 3 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 20 9 42 10 ./phinotpi2 1 13 4 2 1 3 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 12 20 2 1 1 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 1 10 3 2 1 2 4 20 6 8 7 6 9 3 9 3 26 2 5 8 8 5 7 9 42 10 ./phinotpi2 1 6 9 2 1 4 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 8 4 2 1 3 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./celtschk 1 2 13 2 1 3 3 20 6 8 7 9 20 6 8 9 26 2 5 8 8 5 7 9 42 10 ruby1.9 strategist.rb 1 2 4 2 1 3 3 20 6 8 7 7 10 6 9 10 26 2 5 8 8 5 9 9 42 10 python blazer1.py 1 3 13 2 1 4 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 10 9 42 10 ./celtschk 1 4 4 2 1 3 3 20 6 8 7 6 7 4 8 9 26 2 5 8 8 5 4 9 42 10 ruby1.9 strategist.rb 1 4 9 2 1 4 3 20 6 8 7 7 9 6 8 10 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 11 7 2 1 1 4 20 6 8 7 6 7 3 8 3 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 6 4 2 1 3 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 13 7 2 1 1 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 1 7 4 2 1 4 4 20 6 8 7 6 20 3 8 3 26 2 5 8 8 5 7 9 42 10 ./celtschk 1 13 3 2 1 1 4 20 6 8 7 6 7 3 8 9 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 3 4 2 1 3 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 9 9 42 10 ruby1.9 strategist.rb 1 5 4 2 1 2 3 20 6 8 7 6 7 4 8 10 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 1 6 3 2 1 3 4 20 6 8 7 6 7 3 8 3 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 10 20 2 1 1 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 10 3 2 1 4 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./celtschk 1 12 4 2 1 1 3 20 6 8 7 9 20 6 8 9 26 2 5 8 8 5 7 9 42 10 ./phinotpi2 1 5 3 2 1 1 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 13 3 2 1 4 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 6 9 2 1 4 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 1 5 4 2 1 2 4 20 6 8 7 6 20 3 8 3 26 2 5 8 8 5 7 9 42 10 ./celtschk 1 12 3 2 1 3 4 20 6 8 7 6 7 3 8 9 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 10 7 2 1 2 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 9 10 2 1 4 9 20 6 8 7 4 6 3 8 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 9 20 2 1 4 4 20 6 8 7 6 20 3 8 7 26 2 5 8 8 5 3 9 42 10 ruby1.9 strategist.rb 1 6 3 2 1 3 3 20 6 8 7 9 10 6 9 10 26 2 5 8 8 5 7 9 42 10 node minitech1.js 1 13 3 2 1 3 3 20 6 8 7 7 10 6 8 20 26 2 5 8 8 5 10 9 42 11 ./celtschk 1 3 3 2 1 1 3 20 6 8 7 7 26 6 9 9 26 2 5 8 8 5 20 9 42 11 ruby1.9 strategist.rb 1 5 20 2 1 2 3 20 6 8 7 7 11 6 9 11 26 2 5 8 8 5 9 9 42 11 ./phinotpi2 1 7 3 2 1 4 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 11 9 42 11 node minitech1.js 1 7 3 2 1 1 4 20 6 8 7 6 7 3 8 20 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 8 4 2 1 4 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 20 9 42 10 ./phinotpi2 1 2 3 2 1 3 9 20 6 8 7 4 6 3 8 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 4 13 2 1 3 4 20 6 8 7 6 20 3 7 7 26 2 5 8 8 5 3 9 42 10 ./celtschk 1 8 3 2 1 3 3 20 6 8 7 9 20 6 8 9 26 2 5 8 8 5 7 9 42 10 ruby1.9 strategist.rb 1 9 10 2 1 2 3 20 6 8 7 7 10 6 9 10 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 10 20 2 1 1 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 9 4 2 1 1 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 11 20 2 1 4 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 1 4 9 2 1 3 4 20 6 8 7 6 9 3 9 3 26 2 5 8 8 5 7 9 42 10 ruby1.9 strategist.rb 1 5 3 2 1 4 4 20 6 8 7 6 7 3 8 10 26 2 5 8 8 5 3 9 42 10 ./celtschk 1 7 4 2 1 3 3 20 6 8 7 7 9 6 8 9 26 2 5 8 8 5 10 9 42 10 python blazer1.py 1 4 9 2 1 1 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 8 4 2 1 3 9 20 6 8 7 4 6 3 8 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 10 9 2 1 3 4 20 6 8 7 6 20 3 8 7 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 4 20 2 1 1 3 20 6 8 7 6 20 4 8 4 26 2 5 8 8 5 7 9 42 10 ./phinotpi2 1 5 3 2 1 2 9 20 6 8 7 4 6 3 9 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 2 4 2 1 1 4 20 6 8 7 6 20 3 8 7 26 2 5 8 8 5 3 9 42 10 ./celtschk 1 10 12 2 1 1 3 20 6 8 7 9 20 6 8 9 26 2 5 8 8 5 7 9 42 10 ./phinotpi2 1 9 4 2 1 4 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 9 9 42 10 ruby1.9 strategist.rb 1 11 3 2 1 3 4 20 6 8 7 6 7 3 8 10 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 8 4 2 1 1 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 13 9 2 1 4 9 20 6 8 7 4 6 3 8 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 2 9 2 1 3 4 20 6 8 7 6 20 3 8 7 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 8 3 2 1 2 3 20 6 8 7 6 20 4 8 4 26 2 5 8 8 5 7 9 42 10 ./celtschk 1 3 3 2 1 4 3 20 6 8 7 6 7 4 8 9 26 2 5 8 8 5 4 9 42 10 ruby1.9 strategist.rb 1 10 4 2 1 1 3 20 6 8 7 7 9 6 8 10 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 3 9 2 1 4 4 20 6 8 7 6 7 3 8 3 26 2 5 8 8 5 10 9 42 10 node minitech1.js 1 7 11 2 1 4 4 20 6 8 7 6 7 3 8 20 26 2 5 8 8 5 3 9 42 10 ./celtschk 1 8 3 2 1 2 3 20 6 8 7 7 9 6 8 9 26 2 5 8 8 5 20 9 42 10 ruby1.9 strategist.rb 1 3 10 2 1 3 3 20 6 8 7 7 10 6 9 10 26 2 5 8 8 5 9 9 42 10 node minitech1.js 1 8 4 2 1 1 3 20 6 8 7 7 10 6 8 20 26 2 5 8 8 5 10 9 42 11 ./phinotpi2 1 2 4 2 1 2 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 20 9 42 11 ruby1.9 strategist.rb 1 4 9 2 1 4 4 20 6 8 7 6 7 3 8 11 26 2 5 8 8 5 3 9 42 11 node minitech1.js 1 4 9 2 1 1 3 20 6 8 7 7 11 6 8 20 26 2 5 8 8 5 11 9 42 10 ./phinotpi2 1 2 7 2 1 1 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 20 9 42 10 ./phinotpi2 1 9 3 2 1 1 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 3 9 2 1 2 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ruby1.9 strategist.rb 1 5 7 2 1 3 3 20 6 8 7 10 20 6 8 10 26 2 5 8 8 5 7 9 42 10 ./celtschk 1 8 10 2 1 4 3 20 6 8 7 7 10 6 9 9 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 5 4 2 1 4 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 9 9 42 10 ruby1.9 strategist.rb 1 5 20 2 1 3 4 20 6 8 7 6 7 3 8 10 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 11 20 2 1 2 3 20 6 8 7 6 7 4 8 4 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 12 10 2 1 1 9 20 6 8 7 4 6 3 9 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 10 3 2 1 1 4 20 6 8 7 6 20 3 8 7 26 2 5 8 8 5 3 9 42 10 ./phinotpi2 1 9 4 2 1 4 3 20 6 8 7 6 20 4 8 4 26 2 5 8 8 5 7 9 42 10 ./phinotpi2 1 5 3 2 1 1 9 20 6 8 7 4 6 3 8 3 26 2 5 8 8 5 4 9 42 10 scala Schwarzenbeck 1 7 4 2 1 1 4 20 6 8 7 6 20 3 7 7 26 2 5 8 8 5 3 9 42 10 ./celtschk 1 11 7 2 1 3 3 20 6 8 7 9 20 6 8 9 26 2 5 8 8 5 7 9 42 10 ruby1.9 strategist.rb 1 13 10 2 1 1 3 20 6 8 7 7 10 6 9 10 26 2 5 8 8 5 9 9 42 10 ./phinotpi2 1 9 9 2 1 1 4 20 6 8 7 6 7 3 9 3 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 7 9 2 1 3 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 ruby1.9 strategist.rb 1 13 7 2 1 4 3 20 6 8 7 6 7 4 8 10 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 1 8 7 2 1 1 4 20 6 8 7 6 7 3 8 3 26 2 5 8 8 5 10 9 42 10 ./phinotpi2 1 12 3 2 1 1 9 20 6 8 7 4 6 3 8 4 26 2 5 8 8 5 3 9 42 10 scala Schwarzenbeck 1 13 7 2 1 2 3 20 6 8 7 6 20 4 8 7 26 2 5 8 8 5 4 9 42 10 ./phinotpi2 Results: Bot Score Total Lowest perl phinotpi1.pl 0 0 101 ./dirichlet 2 25 12 python blazer1.py 3 12 4 perl chef.pl ilmari2.chef 0 0 101 ./brainfuck ilmari1.bf 0 0 101 ./christophe1 0 0 101 ./phinotpi2 44 156 3 node minitech1.js 7 140 20 scala Mueller 0 0 101 scala Beckenbauer 0 0 101 scala Schwarzenbeck 15 105 7 ./alice 0 0 101 ./bob 0 0 101 ./eve 0 0 101 python joe.py 0 0 101 python copycat.py 0 0 101 python totalbots.py 0 0 101 perl healthinspector.pl 0 0 101 ./mellamokb1 0 0 101 ./mellamokb2 0 0 101 php eightscancel.php 0 0 101 php fivescancel.php 0 0 101 python copycat2.py 0 0 101 ./celtschk 14 126 9 ./deepthought 0 0 101 ruby1.9 strategist.rb 15 152 10 ``` [Answer] ## Perl I tried a little harder this time. It's a really simple complex strategy, but I've set up the framework for expansion. Edit: Complete redo. This thing is in it for the win. ``` sub prob{ $_[0]+$_[1]-$_[0]*$_[1] } $_=<>; INPUT:{ tr/ /,/; @in = eval; for(1..$#in){ $bids[$rnum][$in[$_]]++ } for(0..$#in){ $tbids[$rnum][$in[$_]]++ } $rnum++; $_=<>; if($_ ne"\n"){redo INPUT} } for(0..100){$pre[$_]=0} dirichlet: for(2..$#in/2+2){ #rough approximation, $pre[$_]=prob($pre[$_], 1/int($#in/2+1)) } CDP:{ @cdps1=(1,1,1,2,2,3,3,4); @cdps2=(-2,-1,0,1,1,2,2,3,3); for($a=0;$a<8;$a++){ for($b=0;$b<9;$b++){ $sum=$cdps1[$a]+$cdps2[$b]; if($sum<1){$sum=1}; $pre[$sum] = prob($pre[$sum], 1/72); } } } blazer: { for($r=1;$r<$rnum;$r++){ winner: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$r][$pnt] == 1){ if($pnt > 2){ $winnum[$pnt]++; $wins++; } last winner } } } if($wins==0){ $pre[3]=prob($pre[3], 1);last blazer } for(1..100){ $pre[$_]=prob($pre[$_], $winnum[$_]/$wins); } } CC1: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$rnum-1][$pnt] == 1){ $pre[$pnt] = prob($pre[$pnt], 1);last CC1 } if($pnt==100){ for($pnt2=1;$pnt2<100;$pnt2++){ $pre[$pnt2] = prob($pre[$pnt2], $tbids[$rnum-1][$pnt2]/($#in+1)); } } } CC2: for($pnt=1;$pnt<101;$pnt++){ if($rnum-2<0){$pre[7] = prob($pre[7], 1);last CC2} if($tbids[$rnum-2][$pnt] == 1){ $pre[$pnt] = prob($pre[$pnt], 1);last CC2 } if($pnt==100){ $pre[7] = prob($pre[7], 1);last CC2 } } one: { $pre[1] = prob($pre[1], 1); } two: { $pre[2] = prob($pre[2], 1); } five: { $pre[5] = prob($pre[5], 1); } eight: { $pre[8] = prob($pre[8], 1); } fortytwo: { $pre[42] = prob($pre[42], 1); } mueller: { $a=($#in+2)/4; $pre[int$a]=prob($pre[int$a], 1) } schwarzenbeck: { $a=($#in+2)/4+1; $pre[int$a]=prob($pre[int$a], 1) } beckenbauer: { $a=($#in+2)/4+2; $pre[int$a]=prob($pre[int$a], 1) } totalbots: { $pre[$#in+1]=prob($pre[$#in+1], 1) } joe: { $sum=0; for(1..100){ $sum+=$tbids[$rnum-1][$_]; } $average=$sum/($#in+1); if($average==0){$average=10}; $pre[$average]=prob($pre[$average], 1); } node: { $max=0;$maxloc=0; for(1..100){ if($tbids[$rnum-1][$_]>$max){$max=$tbids[$rnum-1][$_];$maxloc=$_} } $maxloc--; #if($maxloc==0){ $maxloc=20; #} if($rnum==1){$maxloc=3} $pre[$maxloc]=prob($pre[$maxloc], 1); } #print"\n@pre\n\n"; decide: for(1..100){if($pre[$_]<0.5){print; last decide}} ``` This program takes input one line at a time, followed by two newlines: ``` perl PhiNotPi2.plx 1 2 3 3 2 2 1 3 1 3 2 1 1 1 3 [empty line] ``` [Answer] ## Chef Since [always betting 1](https://codegolf.stackexchange.com/a/4843) is now a [losing strategy](https://codegolf.stackexchange.com/a/4848), the obvious thing to do is to always bet *2* instead. So let me do that. To make this otherwise boring entry a little more interesting, I decided to write it in [Chef](http://en.wikipedia.org/wiki/Chef_%28programming_language%29): ``` Shirred Eggs. This recipe prints the number 2 and, in doing so, yields two delicious shirred eggs. Ingredients. 2 eggs Cooking time: 12 minutes. Pre-heat oven to 175 degrees Celsius. Method. Put eggs into mixing bowl. Pour contents of the mixing bowl into the baking dish. Shirr the eggs. Bake the eggs until shirred. Serves 1. ``` As a bonus, the program actually more or less works as a real — if trivial — recipe, even if it does kind of read as if the writer was a bit, um, baked. The Chef grammar seems to make it pretty hard to write anything that involves something more complicated than mixing stuff in a bowl and baking it and still have it work both as a program and as a recipe, especially if any of the verbs one wants to use are even slightly irregular (like "fry" → "fried"). **Edit:** Changed the recipe from fried to [shirred](http://en.wiktionary.org/wiki/shirr) eggs — thanks to Blazer for the suggestion! The cooking time and temperature should be considered advisory only; I haven't actually tried the recipe yet myself, so I can't vouch for their accuracy. [Answer] ## Python (2.6) Extremely simple, but still I'm curious how it will perform compared to the other approaches. ``` import sys, random try: s = sys.stdin.readlines()[-2] m = min(int(x) for x in s.split()) except IndexError: m = random.choice([1,1,1,2,2,3,3,4]) a = random.choice([-2,-1,0,1,1,2,2,3,3]) print max(m + a, 1) ``` Just pipe in the bids via stdin, e.g. `python testbid.py < bids.txt`. *EDIT*: changed for the 'first round all zeros' *EDIT*: changed the 'magic numbers' a bit (a second time) [Answer] ## Python (Blazer) This bot analyzes the previous rounds and records the numbers that win. Winning numbers that appear more often will therefore have a better chance of getting picked. It will then randomly choose numbers from winning numbers (other than 1 or 2). it will choose ~~2~~ 3 instead if it is the first round. ~~Input is read one line at a time. simply enter an empty line to stop accepting input~~ A trick is to just paste (it automatically accepts each line with \n within the paste) and hit enter twice You may now just runt the script with a filename in the command line: ``` python bidding.py bidding.txt ``` file should look like this: ``` 10 4 12 11 12 4 7 3 3 1 2 9 15 1 15 15 9 3 3 21 6 4 3 8 6 13 1 ``` - ``` import random import sys winning = [] # record the winning numbers content = sys.argv[1].split('\n') for each in content: x = map(int, each.split()) if len(x)+sum(x) == 0: continue y = [] for each in x: if x.count(each) == 1: y.append(each) if len(y) > 0: if min(y) not in [1,2]: #never choose 1 or 2 winning.append(min(y)) # choose an output if len(winning) == 0: print 3 else: print random.choice(winning) ``` ~~edit: added `or sum(rounds) == 0` to compensate for the recent first-round-all-zeros change~~ edit: problems in comments fixed, also made it able to receive input from a filename, and never chooses '2' anymore since competition has weeded that out as well. works with either all-0's as the starting input or no data in the file at all edit2: forgot a min() edit3: changed input to suit question's input needs [Answer] ### Schwarzenbeck (Scala) ``` object Schwarzenbeck extends App { println ((args(0).split('\n')(0).split(' ').length+1)/4+1) } ``` Schwarzenbeck isn't supposed to score the goals. He is the cleanup for Beckenbauer, which follows soon. :) To use it, you need a compiler and compile it ``` scalac Schwarzenbeck.scala ``` Then you can run it: ``` scala Schwarzenbeck 'your ar- gu- ment' ``` Edit: Further adjustments. [Answer] **Strategist (Ruby )** Implements hundreds of simple strategies: for each round, picks the one which would have won the most previous rounds: ``` require 'Matrix' def winner guesses g=guesses.sort while g[0]&&g[0]==g[1] g.shift while g[0]==g[1] g.shift end g[0] end def prob g prob=[0]*100;best=0;n=g.size*(g[0].size-1) g.each{|r|r[1..-1].each{|v|prob[v-1]+=1.0/n}}; prob.map!{|v|v/n} end def regression x, y, degree return y if x.size==1 x_data = x.map {|xi| (0..degree).map{|pow| (xi**pow.to_f) }} mx = Matrix[*x_data] my = Matrix.column_vector y begin r = ((mx.t * mx).inv * mx.t * my).transpose.to_a[0] rescue Exception => e r=[0]*degree;r[-1]=y[-1].to_f/(x[-1]**degree) end r end brains=((1..50).map{|w|[proc{|g|w}, proc{|g|best=0;(p=prob g).each_with_index{|v,i| best=i if(v+i/100.0/w)<p[best]};best+1}]}+ (1..7).map{|w|[proc{|g|p=1; if (g[1]) then h=g[1..-1];x=(1..h.size).to_a p=0;regression(x,h.map{|r|winner r},w).each_with_index{|v,i| p+=v*(g.size**i)};end;p.to_i}, proc{|g|b=g[0].size/4;if g[1] then pred=[];h=g[1..-1] x=(1..h.size).to_a;h[0].size.times{|i|p=0 regression(x,h.map{|r|r[i]},w).each_with_index{|v,i|p+=v*((x[-1]+1)**i)} pred<<[[p.to_i,1].max,100].min} (1..100).each{|i|if !pred.include?(i) then b=i;break;end};end;b}]}+ (-1..1).map{|w|[proc{|g|r=g[0].size; if g.size>1 then f=g[1..-1].flatten;r=(f.inject{|s,v|s+v}/f.size.to_f+w).to_i;end;r}, proc{|g|r=g[0].size/2; if g.size>1 then r=(g[1..-1].inject(0){|s,v|s+winner(v)}/(g.size.to_f-1)+w).to_i;end;r}, proc{|g|(winner(g[-1])||9)+w} ]}+ [proc{|g|b=0;(p=prob g).each_with_index{|v,i|b=i if v<p[b]};b+1}]).flatten games = ARGV[0].split("\n").map{|l|l.split.map{|v|v.to_i}} winpct=[0]*brains.size (games.size-1).times{|round| entries=games[round+1].dup brains.each_with_index{|b,i| entries[0]=pick=[b[games[0..round]],1].max winpct[i]+= 1.0/games.size if winner(entries)==pick } } best=0; winpct.each_index{|i|best = i if (winpct[i]>winpct[best])} puts brains[best][games] ``` I'm not sure I've got the input format right - I'm not sure how to generate multi-line command line arguments for testing it on windows. *(This method seems to work on IDEone.)* [Answer] ## Perl I figured that I might as well enter the inevitable. More serious entries coming soon. As a bonus, this entry will never lose in one-on-one competition. ``` print 1 ``` [Answer] ## JavaScript (node.js) Counts what was most popular last round and bids one less than that, wrapping to 20 and bidding 3 on the first round. ``` var lastRound = /[^\n]+$/.exec(process.argv[2]); var numbers = {}; var re = /\d+/g; var match; while(match = re.exec(lastRound)) { numbers[match] = numbers[match] >>> 0 + 1; } var maxKey = -1; for(var i in numbers) { if(maxKey === -1 || numbers[i] > numbers[maxKey]) { maxKey = i; } } if(maxKey == 0) { // First round. Bid 3. console.log(3); } else if(maxKey == 1) { // Bid 20. console.log(20); } else { // Bid one less. console.log(maxKey - 1); } ``` How to invoke: ``` node script.js 'the argument' ``` [Answer] ## Python (CopyCat) Yet another, this time it copies the exact answer the last winner had, if there was one. It's dsigned to both try to win and block other bidders. bids `5` if first round, bids a random number from the previous round if there was somehow no winner ``` content = sys.argv[1].split('\n') x = map(int, content[-1].split()) y = [] for each in x: if x.count(each) == 1: y.append(each) print min(y) if sum(y) > 0 else random.choice(x) if sum(x) > 0 else 5 ``` [Answer] ## Python (Joe) This is by no means designed to win, but I'm throwing it out there anyway to add some color to the crowd :) It bids the average of the last round (Average Joe). Invoked the same as my [original answer](https://codegolf.stackexchange.com/a/4847/3421) (which I will now name because it seems like that's what all the cool kids are doing, and it helps to distinguish the two). if starting round, it bids `10`. ``` content = sys.argv[1].split('\n') x = map(int, content[-1].split()) print sum(x)/len(x) if sum(x) != 0 else 10 ``` edit: changed method of input to suit question's input method [Answer] ## Python (TotalBots) I think this one will be my last, but we'll see. It takes advantange of knowing how many bots there are by simply outputting the number of competing bots, so if there are 17 bots (current number of bots, plus this one), it will output `17` ``` content = sys.argv[1].split('\n') print len(content[-1].split()) ``` [Answer] ## Perl (Health Inspector) ``` print ((((((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))))*(rand(2)))) ``` I bet you can guess what it does. [Answer] # C++ (Educated Guess) I already thought I would have missed the deadline, but thanks to the extension I can still add my entry. This program compiles with g++. The program tries to guess the statistics of the other entries, and to choose the smallest one not likely to be chosen by any other one. ``` #include <iostream> #include <sstream> #include <string> #include <vector> #include <deque> #include <cstdlib> #include <ctime> #include <exception> #include <stdexcept> typedef std::vector<int> botvec; typedef std::vector<botvec> scorevec; // read all the scores from the given string // note that this only does minimal error checking // the result is a vector of vector, each entry of which // represents one round. That is, the vectors in the vector // correspond to the lines of the command line argument. scorevec read_past_scores(char const* scoretext) { scorevec past_scores; std::istringstream is(scoretext); std::string line; scorevec::size_type size = 0; while (std::getline(is, line)) { past_scores.push_back(botvec()); std::istringstream ils(line); int i; while (ils >> i) past_scores.back().push_back(i); if (size == 0) size = past_scores.back().size(); else if (past_scores.back().size() != size) throw std::runtime_error("invalid score format"); } return past_scores; } struct counts { int count[100]; }; struct prob { double p[100]; }; int generate_answer(scorevec& past_scores) { int const number_of_players = past_scores.front().size(); if (past_scores.front().front() == 0) // initial round past_scores.pop_back(); // Pre-fill the counts to get reasonable probabilities also for // insufficient statistics (and the statistics *will* be // insufficient!). Bias in favour of small numbers. counts initial; for (int i = 0; i < 100; ++i) initial.count[i] = i < number_of_players? 100*(number_of_players-i) : 1; std::deque<counts> playercounts(number_of_players, initial); // add the actual guesses (with a high factor, to give them high // weight against the initial counts) for (int i = 0; i < past_scores.size(); ++i) for (int j = 0; j < number_of_players; ++j) playercounts[j].count[past_scores[i][j]-1]+=5000; // drop the own guesses playercounts.pop_front(); // calculate the probabilities corresponding to the counts std::vector<prob> playerprobabilities(playercounts.size()); for (int i = 0; i < playercounts.size(); ++i) { double sum = 0; for (int k = 0; k < 100; ++k) sum += playercounts[i].count[k]; for (int k = 0; k < 100; ++k) playerprobabilities[i].p[k] = playercounts[i].count[k]/sum; } // for each selection, estimate the expected number of other players // who will bet on it. Return the first one with an expectation // below 1.5. for (int i = 0; i < 100; ++i) { double estimate = 0; for (int j = 0; j < number_of_players; ++j) estimate += playerprobabilities[j].p[i]; if (estimate < 1.5) return i+1; } // in the unlikely case that such a choice doesn't exist (meaning // there are far more than 100 players), just return 100. return 100; } int main(int argc, char* argv[]) { if (argc < 2) { std::cerr << "Missing score argument!\n"; return EXIT_FAILURE; } try { scorevec past_scores = read_past_scores(argv[1]); std::srand(std::time(0)); std::cout << generate_answer(past_scores) << std::endl; return EXIT_SUCCESS; } catch(std::exception& e) { std::cerr << e.what() << "\n"; return EXIT_FAILURE; } catch(...) { std::cerr << "Unknown error\n"; return EXIT_FAILURE; } } ``` [Answer] ## Perl (Bob) ``` $_=<>; INPUT:{ tr/ /,/; @in = eval; for(1..$#in){ $bids[$rnum][$in[$_]]++ } for(0..$#in){ $tbids[$rnum][$in[$_]]++ } $rnum++; $_=<>; if($_ ne"\n"){redo INPUT} } for(0..100){$pre[$_]=0} blazer: { for($r=1;$r<$rnum;$r++){ winner: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$r][$pnt] == 1){ if($pnt > 2){ $winnum[$pnt]++; $wins++; } last winner } } } if($wins==0){ $pre[3]++;last blazer } } CC1: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$rnum-1][$pnt] == 1){ $pre[$pnt]++;last CC1 } } CC2: for($pnt=1;$pnt<101;$pnt++){ if($rnum-2<0){$pre[7]++;last CC2} if($tbids[$rnum-2][$pnt] == 1){ $pre[$pnt]++;last CC2 } if($pnt==100){ $pre[7]++;last CC2 } } one: { $pre[1]+=2; } two: { $pre[2]+=2; } five: { $pre[5]+=2; } eight: { $pre[8]+=2; } fortytwo: { $pre[42]++; } mueller: { $a=($#in+2)/4; $pre[int$a]++; } schwarzenbeck: { $a=($#in+2)/4+1; $pre[int$a]++; } beckenbauer: { $a=($#in+2)/4+2; $pre[int$a]++; } totalbots: { $pre[$#in+1]++; } joe: { $sum=0; for(1..100){ $sum+=$_*$tbids[$rnum-1][$_]; } $average=$sum/($#in+1); if($average==0){$average=10}; $pre[$average]++; } node: { $max=0;$maxloc=0; for(1..100){ if($tbids[$rnum-1][$_]>$max){$max=$tbids[$rnum-1][$_];$maxloc=$_} } $maxloc--; #if($maxloc==0){ $maxloc=20; #} if($rnum==1){$maxloc=3} $pre[$maxloc]++; } choice: for(1..100){ if($pre[$_]==1){ $count++; if($count==3){print; last choice} } if($_==100){print"98"} } ``` See "Bob" for how to invoke. [Answer] ## Perl (Alice) ``` $_=<>; INPUT:{ tr/ /,/; @in = eval; for(1..$#in){ $bids[$rnum][$in[$_]]++ } for(0..$#in){ $tbids[$rnum][$in[$_]]++ } $rnum++; $_=<>; if($_ ne"\n"){redo INPUT} } for(0..100){$pre[$_]=0} blazer: { for($r=1;$r<$rnum;$r++){ winner: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$r][$pnt] == 1){ if($pnt > 2){ $winnum[$pnt]++; $wins++; } last winner } } } if($wins==0){ $pre[3]++;last blazer } } CC1: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$rnum-1][$pnt] == 1){ $pre[$pnt]++;last CC1 } } CC2: for($pnt=1;$pnt<101;$pnt++){ if($rnum-2<0){$pre[7]++;last CC2} if($tbids[$rnum-2][$pnt] == 1){ $pre[$pnt]++;last CC2 } if($pnt==100){ $pre[7]++;last CC2 } } one: { $pre[1]+=2; } two: { $pre[2]+=2; } five: { $pre[5]+=2; } eight: { $pre[8]+=2; } fortytwo: { $pre[42]++; } mueller: { $a=($#in+2)/4; $pre[int$a]++; } schwarzenbeck: { $a=($#in+2)/4+1; $pre[int$a]++; } beckenbauer: { $a=($#in+2)/4+2; $pre[int$a]++; } totalbots: { $pre[$#in+1]++; } joe: { $sum=0; for(1..100){ $sum+=$_*$tbids[$rnum-1][$_]; } $average=$sum/($#in+1); if($average==0){$average=10}; $pre[$average]++; } node: { $max=0;$maxloc=0; for(1..100){ if($tbids[$rnum-1][$_]>$max){$max=$tbids[$rnum-1][$_];$maxloc=$_} } $maxloc--; #if($maxloc==0){ $maxloc=20; #} if($rnum==1){$maxloc=3} $pre[$maxloc]++; } choice: for(1..100){ if($pre[$_]==1){ $count++; if($count==2){print; last choice} } if($_==100){print"99"} } ``` Takes input similar to my other bots. ``` perl Alice.plx 1 4 3 12 3 2 4 11 [blank line] ``` [Answer] ## Perl (Eve) I completely redid this entry to help pave the way for my other bots. ``` $_=<>; INPUT:{ tr/ /,/; @in = eval; for(1..$#in){ $bids[$rnum][$in[$_]]++ } for(0..$#in){ $tbids[$rnum][$in[$_]]++ } $rnum++; $_=<>; if($_ ne"\n"){redo INPUT} } for(0..100){$pre[$_]=0} blazer: { for($r=1;$r<$rnum;$r++){ winner: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$r][$pnt] == 1){ if($pnt > 2){ $winnum[$pnt]++; $wins++; } last winner } } } if($wins==0){ $pre[3]++;last blazer } } CC1: for($pnt=1;$pnt<101;$pnt++){ if($tbids[$rnum-1][$pnt] == 1){ $pre[$pnt]++;last CC1 } } CC2: for($pnt=1;$pnt<101;$pnt++){ if($rnum-2<0){$pre[7]++;last CC2} if($tbids[$rnum-2][$pnt] == 1){ $pre[$pnt]++;last CC2 } if($pnt==100){ $pre[7]++;last CC2 } } one: { $pre[1]+=2; } two: { $pre[2]+=2; } five: { $pre[5]+=2; } eight: { $pre[8]+=2; } fortytwo: { $pre[42]++; } mueller: { $a=($#in+2)/4; $pre[int$a]++; } schwarzenbeck: { $a=($#in+2)/4+1; $pre[int$a]++; } beckenbauer: { $a=($#in+2)/4+2; $pre[int$a]++; } totalbots: { $pre[$#in+1]++; } joe: { $sum=0; for(1..100){ $sum+=$_*$tbids[$rnum-1][$_]; } $average=$sum/($#in+1); if($average==0){$average=10}; $pre[$average]++; } node: { $max=0;$maxloc=0; for(1..100){ if($tbids[$rnum-1][$_]>$max){$max=$tbids[$rnum-1][$_];$maxloc=$_} } $maxloc--; #if($maxloc==0){ $maxloc=20; #} if($rnum==1){$maxloc=3} $pre[$maxloc]++; } choice: for(1..100){ if($pre[$_]==1){ $count++; if($count==1){print; last choice} } if($_==100){print"100"} } ``` Takes one input format: the same as "Bob" and "Alice". [Answer] ## Brainfuck To quote from the challenge: > > "You can enter as many bots as you wish, so if anyone does enter a bot that only guesses `1`, you can enter another that does the same to render it useless." > > > Well, since [PhiNotPi did enter one](https://codegolf.stackexchange.com/a/4843), let me enter another. Just to be different, I'll do it in Brainfuck: ``` +++[->++++<]>[-<++++>]<+. ``` Of course, now that betting 1 is no longer a feasible strategy, the obvious thing to do now is to [bet 2 instead](https://codegolf.stackexchange.com/a/4850)... **Edit:** Split answer into two per comments, rewrote both programs in more interesting languages. [Answer] ### Mueller (Scala) ``` object Mueller extends App { println ((args(0).split('\n')(0).split(' ').length+1)/4) } ``` If you know Schwarzenbeck and Beckenbauer, you surely expected Mueller. Here he is. He will benefit much from Beckenbauer and Schwarzenbeck and is supposed to win. Details about running and compilation: See [Schwarzenbeck](https://codegolf.stackexchange.com/a/4868/373) Closer to the goal, now. [Answer] ### Beckenbauer (Scala) ``` object Beckenbauer extends App { println ((args(0).split('\n')(0).split(' ').length+1)/4+2) } ``` With the help of Schwarzenbeck, Beckenbauer is supposed to score some goals. Without Schwarzenbeck, he's nothing. Details about running and compilation: See [Schwarzenbeck][1] Edit: Playing deeper in the room now, too. [Answer] ## Batch Scripting ``` echo 5 ``` My submission, gives 5 as its answer every time ;-) [Answer] Eight.bat ``` echo 8 ``` Another simple answer, gives 8 every time. [Answer] ## FivesCancel (PHP) Cancels mellamokb's "always 5" solution. ``` 5 ``` [Answer] ## EightsCancel (PHP) Cancels mellamokb's "always 8" solution. Sorry, mellamokb! ``` 8 ``` [Answer] ## Python 2.7 - Copycat2 Copies the *second* last round's winner. Oh no! otherwise outputs 7. ``` import sys content = sys.argv[1].split('\n') x = map(int, content[-2].split()) if len(content) > 1 else [7] y = [] for each in x: if x.count(each) == 1: y.append(each) print min(y) if sum(y) > 0 else random.choice(x) if sum(x) > 0 else 7 ``` [Answer] # Shell script (Deep Thought) OK, so that I get a slight second chance, here's another entry, this time a shell script (should work with any shell). This always gives the answer to the question of life, the universe and everything. ``` echo 42 ``` Actually this algorithm is not entirely correct because I omitted the 7.5 million year delay. :-) [Answer] ## dirichlet.c ``` #include <fcntl.h> #include <stdint.h> #include <stdio.h> main(int argc, char* argv[]) { int handle; char *str; int32_t bits, val, n = 0; if (argc) { for (str = argv[1]; *str; str++) if (*str == 32) n++; else if (*str == 10) break; } n /= 2; if (n > 99) n = 99; handle = open("/dev/urandom", O_RDONLY); do { read(handle, &bits, sizeof bits); bits &= 0x7fffffff; val = bits % n; } while (bits - val + (n-1) < 0); close(handle); printf("%d", 2 + val); } ``` I think this goes through random bits too fast to use `/dev/random`, however much I'd prefer to. If anyone wants to test it on Windows you'll have to port it yourself, because I don't have access to a Windows box with a C compiler. ### Rationale I didn't want to explain the logic behind this before the tournament was over, but now that the winner has been announced, I think it's time. By the pigeon-hole principle (aka Dirichlet's principle, hence the name of the bot), if there are *N* competing bots then there is a number *w* in [1..1+*N*/2] which either won or would have won if selected. I therefore conclude that the optimal strategy will not select numbers greater than 1+*N*/2. But if *N* is even, selecting 1+*N*/2 creates a smaller winning slot. Therefore the slots which are worth selecting are [1..(*N*+1)/2]. That leaves the question of how to select a slot. For small numbers of bots I verified that there's a Nash equilibrium when each bot selects uniformly among the candidates, and I strongly suspect that this will continue to hold true. The minor deviation in this bot's strategy from the theoretical one is simply metagaming. ]
[Question] [ In this challenge you will be tasked with implementing a sequence of natural numbers such that: * Each number appears a natural number of times * No two numbers appear the same number of times * No two numbers appear in the sequence next to each other more than once. For some examples, the sequence ``` 1,2,3,1,4,5,1,6,7,1,8,9,1,10,11,1,... ``` Is not valid because `1` appears an infinite number of times. The sequence: ``` 1,2,3,4,5,6,7,8,9,10,11,12,13,14,... ``` Is also not valid because every number appears exactly once, but different numbers must appear a distinct number of times. The sequence: ``` 1,1,2,2,3,2,4,3,5,3,6,3,7,4,8,4,9,4,10,4,11,5,... ``` meets the first two criteria but `2` occurs next to `3` two different times (`2,3,2`). One sequence that meets all the criteria is: ``` 1,1,2,2,3,4,2,5,6,3,7,8,3,9,10,3,11,12,4,13,14,4,15,16,4,17,18,4,19,20,5,21,22,5,23,24,5,25,26,5,... ``` You may use any option available in the default [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules. You should assume natural numbers include 0. You may assume they don't, but it won't do you any help. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. [Answer] # [JavaScript (V8)](https://v8.dev/), 37 bytes ``` for(i=0;;print(i**.5>>i%2))print(++i) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPT1sDauqAoM69EI1NLS8/Uzi5T1UhTEyKirZ2p@f8/AA "JavaScript (V8) – Try It Online") # [JavaScript (V8)](https://v8.dev/), ~~41~~ 40 bytes ``` for(i=0;;i%2||print(i**.5>>1))print(++i) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPT1sDaOlPVqKamoCgzr0QjU0tLz9TOzlBTE8LX1s7U/P8fAA "JavaScript (V8) – Try It Online") I don't know how it works but it seems fine and \$i\$ appears \$4i+3\$ times except 0 which appears 1 time [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~8~~ ~~5~~ 3 bytes ``` ₅[L ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigoVbTCIsIiIsIiJd) Modified Kevin Cruijssen's 05AB1E answer. Equivalent python code: `lambda n: n if n%5 != 0 else len(str(n))` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), 4 bytes ``` √ℕl| ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pvaGBg8Gj@skdNjY/aNgDJh1snlP9/1DHrUcvUnJr//wE "Brachylog – Try It Online") A function submission, which takes the 1-based index of the position within the sequence as an argument, and returns the value of the sequence at that index, one of the allowed default I/O formats for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'"). (The header in the TIO link calls the function with all indexes from 1 to 1000, printing the results, and therefore displays the first 1000 elements of the sequence.) ## Algorithm This solution's algorithm is pretty similar to the other short entries: if the input is not a square number, it's returned unchanged; if it is a square number, the program returns the number of digits in its square root. As such, each natural number \$n\$ appears \$9\times 10^n\$ times, plus one time more if the number isn't square, meaning that there are no duplicate numbers-of-occurrences; and because the difference between any two positive square numbers is at least 3, there can't be any repeated pairs. ## Explanation ``` √ℕl| √ {if} the square root of {the input} ℕ is a natural number l {then} {return} {the square root's} length {in digits} | otherwise, {return the input unchanged} ``` (In explanations, I use the `{}` notation for things that are implied by rather than explicitly stated in the program, such as tacit variables and default behaviours of the language – I can't remember ever having needed to use it quite so much before!) Contrary to what might be expected (given that `√` is normally a floating-point operation), `√ℕ` [does correctly work on arbitrarily large integers](https://tio.run/##SypKTM6ozMlPN/r/39DI2MTUzNzC0gA/y/Hw9EdtMx0f7up81NT0qGPWo5apEPb//wA) without having to worry about floating-point overflow and without having to worry about non-integral floats being approximated to integers (there's a special case in the Brachylog interpreter). [Answer] # x86 32-bit machine code, 9 bytes ``` A8 03 75 04 0F BD C0 48 C3 ``` [Try it online!](https://tio.run/##XZDBTsMwDIbPyVOYIrRk7dDYBIdt5cKZCyckhqosTdugNpvSFFKmvTrFGQMBFyf@HX/@YzkppRyGc21k3eUKVq3L9fayuqV/pFpv/mtWmzJoNMuEw2zTOZVljFlV7oRt2BXnHLRxULAQBV9S0TbA4CFitFgQp1pU6wTmlLyYd1CUbFoLSvgkBEpyJY8XtSBWOcojQAQNrEZo8wW1pUxAVsLCeIzJK6d7SkLFQwrTBPpwLCl5q3StgMWxh1UKs@sbTgnZ4RdcwaILDVGCNj3HAT/q2twLWWmjQG5ztYhCzZ9w@Rb23@/gYjp7xP4@ZawzrS6Nyo@WxrzgTz6On/nyACcDPZwhwd/Nf08Chg42PS6Erw2S/LHYuQBho7UZhRxX0FkTph/oMHzIohZlO0ya@QwDLjZFlqo/AQ "C (gcc) – Try It Online") Following the `regparm(1)` calling convention, this takes a 1-index in EAX and returns a number in EAX. This produces the sequence 1, 2, 3, **1**, 5, 6, 7, **2**, 9, 10, 11, **2**, 13, 14, 15, **3**, 17, 18, 19, **3**, 21, 22, 23, **3**, 25, 26, 27, **3**, ..., with each *n* appearing 2*n*-1 times among the bolded terms, and if not divisible by 4, appearing one more time among the unbolded terms. In assembly: ``` f: test al, 3 # Check the low two bits of the number. jnz e # If they're not both zero, jump to the end to return the number unchanged. bsr eax, eax # Find the highest position of a 1 bit in the number... dec eax # and decrease that by 1. e: ret # Return. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~59~~ 8 bytes ``` .*0$ $.& ``` [Try it online!](https://tio.run/##FcsxEkAwFEXR/q4DYxSZ/34SkRXYBoVCozD2H5z@3MdzXnvrx3VrYbKOLgytCSeSyMwUFioyJOQoooQymlFBC6q44d9xPOIJz9S/fMf0Ag "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs the nᵗʰ term of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2... where n appears ⌊9∙10ⁿ⁻²⌋ times if n is a multiple of 10 and an additional time if it is not. Explanation: ``` .*0$ ``` Match any multiple of 10. ``` $.& ``` Replace it with its length. It might even be possible to remove the `$` but then I'm not sure what behaviour the sequence would have. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes ``` ɾ:ẋfṖλ2lvsÞu;c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvjrhuotm4bmWzrsybHZzw551O2MiLCIiLCIzIl0=) Takes an integer as input. Takes a long time to calculate for larger integers. (Each element \$x\$ appears \$x\$ times.) ## Explanation ``` ɾ # Make range from input [1,2,...,r] :ẋ # Repeat each element x times [[1],[2,2],[3,3,3],...] f # Flatten [1,2,2,3,3,3,...,r] Ṗ # Get all permutations of input λ # Opening a lambda function 2l # Get all adjacent pairs of items vs # Sort each pair (so, e.g. (1,2) and (2,1) become the same) Þu # Check if there are any duplicates ;c # Take first item from list of permutations which satisfies the lambda above ``` [Answer] # [Python](https://www.python.org), ~~52~~ 46 bytes ``` i=2 while[*map(print,(i,i+1,int(i**.4)))]:i+=2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY39TJtjbjKMzJzUqO1chMLNAqKMvNKdDQydTK1DXWATI1MLS09E01NzVirTG1bI4guqGaYIQA) * -6 thanks to loopy walt [Answer] # [JavaScript (V8)](https://v8.dev/), 30 bytes ``` for(n=.3;;)print(++n**(n%4)|0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPPVs/Y2lqzoCgzr0RDWztPS0sjT9VEs8ZA8/9/AA "JavaScript (V8) – Try It Online") A messier but also shorter version of @Arnauld's answer. Was meant as a golf but they suggested I post it separately. [Answer] # [bc](https://www.gnu.org/software/bc/), 28 bytes ``` while(1){++x;++x;sqrt(x)-1} ``` [Try it online!](https://tio.run/##S0r@/788IzMnVcNQs1pbu8IahIsLi0o0KjR1DWu5/v8HAA) ~ Corrected per comments. ~~[Try it online!](https://tio.run/##qyrO@J@UrKCrW5ZaVJyZn8eVmpyRr6D0vzwjMydVw1CzWlu7whqEiwuLSjQqNGv/K9UkJddkpCamKOhaWlr@BwA) Note, this calls `bc` via Zsh. TIO's `bc` interpreter seems to be having problems.~~ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` ⎇﹪N⁹θILθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMktSgvsahSwzc/pTQnX8Mzr6C0xK80Nym1SENTR8ESiAt1FJwTi0s0fFLz0ksyNAo1gcD6/39DY9P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the nᵗʰ term of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 1, 10, 11, 12, 13, 14, 15, 16, 17, 2, 19, 20, 21, 22, 23, 24, 25, 26, 2, 28, 29, 30... where n appears 10ⁿ⁻¹ times if n is a multiple of 9 and an additional time if it is not. Explanation: ``` N First input as a number ﹪ Modulo ⁹ Literal integer `9` ⎇ If not divisible then θ First input as a string else θ First input as a string L Take the length I Cast to string Implicitly print ``` [Answer] # TI-Basic, 25 bytes ``` Input N N-int(N/3 If not(fPart(N/3 int(.5√(Ans Disp Ans ``` Outputs the nth term (1-indexed) of the sequence used in [l4m2's JavaScript answer](https://codegolf.stackexchange.com/a/257407). --- ### 64 bytes ``` {3,1 While 1 Disp 1+2Ans(1),2+2Ans(1 For(I,1,dim(Ans Disp Ans(I End Ans+1 If 1+2dim(Ans)=Ans(dim(Ans augment(Ans,{dim(Ans End ``` Outputs indefinitely. This is definitely not the simplest approach, but it uses an interesting sequence: ``` 7, 8, 3, 1, 9, 10, 4, 2, 11, 12, 5, 3, 13, 14, 6, 4, 15, 16, 7, 5, 2, 17, 18, 8, 6, 3, 19, 20, 9, 7, 4... ``` When arranged like this, the pattern becomes apparent: ``` 7 8 | 3 1 9 10 | 4 2 11 12 | 5 3 13 14 | 6 4 15 16 | 7 5 2 17 18 | 8 6 3 19 20 | 9 7 4 21 22 | 10 8 5 23 24 | 11 9 6 25 26 | 12 10 7 3 27 28 | 13 11 8 4 29 30 | 14 12 9 5 31 32 | 15 13 10 6 33 34 | 16 14 11 7 35 36 | 17 15 12 8 37 38 | 18 16 13 9 4 39 40 | 19 17 14 10 5 41 42 | 20 18 15 11 6 43 44 | 21 19 16 12 7 45 46 | 22 20 17 13 8 47 48 | 23 21 18 14 9 49 50 | 24 22 19 15 10 51 52 | 25 23 20 16 11 5 53 54 | 26 24 21 17 12 6 55 56 | 27 25 22 18 13 7 57 58 | 28 26 23 19 14 8 59 60 | 29 27 24 20 15 9 61 62 | 30 28 25 21 16 10 63 64 | 31 29 26 22 17 11 65 66 | 32 30 27 23 18 12... ``` For all natural numbers \$n\$, \$n\$ appears \$n\$ times if \$n < 3\$, \$n+1\$ times if \$2 < n < 7\$, and otherwise \$n+2\$ times. [Answer] # [JavaScript (V8)](https://v8.dev/), 32 bytes ``` for(n=0;;)print(n++%3?n:n**.4|0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sDaWrOgKDOvRCNPW1vV2D7PKk9LS8@kxkDz/38A "JavaScript (V8) – Try It Online") ### How? This is similar (but not identical) to the sequence [used by The Thonnu](https://codegolf.stackexchange.com/a/257408/58563). Two distinct sequences are interleaved. For any \$n\ge0\$, we use the sequence \$s\_0(n)=n+1\$ if \$n\not\equiv 0 \pmod 3\$ and the sequence \$s\_1(n)=\lfloor (n+1)^{2/5}\rfloor\$ if \$n\equiv 0 \pmod 3\$. | \$n\$ | \$s\_0(n)\$ | \$s\_1(n)\$ | | --- | --- | --- | | 0 | | 1 | | 1 | 2 | | | 2 | 3 | | | 3 | | 1 | | 4 | 5 | | | 5 | 6 | | | 6 | | 2 | | 7 | 8 | | | 8 | 9 | | | 9 | | 2 | | 10 | 11 | | | 11 | 12 | | | 12 | | 2 | | 13 | 14 | | | 14 | 15 | | | 15 | | 3 | | ⋮ | ⋮ | ⋮ | [Answer] # [Zsh](https://www.zsh.org/), 39 bytes ``` while echo $[++i] $[++i] $[(i**.5-1)^0] ``` [Try it online!](https://tio.run/##qyrO@K@hWf2/PCMzJ1UhNTkjX0ElWls7MxZBaWRqaemZ6hpqxhnE/q@tKSlSiInJU4hR@A8A)   ~~[42 bytes](https://tio.run/##qyrO@P@/PCMzJ1WhoCgzr0RBN0dBJVpbOzMWQWlkamkZ6JlqxhnE/v8PAA "Zsh – Try It Online")~~ Similar to the [@l4m2](https://codegolf.stackexchange.com/a/257407/15940) solution. Thanks to @pxeger for -2 bytes. Corrected per comment from @m90. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes A port of [ais523's Brachylog answer](https://codegolf.stackexchange.com/a/257442/53748) - do upvote that. ``` ẈƲ¡Ṫ ``` A monadic Link that accepts \$n\$ and yields: $$a(n) = \begin{cases} \lfloor n \log\_{10} \rfloor + 1 & \text{if $n$ is a perfect square} \\ n & \text{otherwise} \end{cases}$$ **[Try it online!](https://tio.run/##AR8A4P9qZWxsef//4bqIw4bCssKh4bmq/8OH4oKs//8xMDI1//8xMDI1 "Jelly – Try It Online")** ### How? A byte saved over the naive `DL$Ʋ¡`. ``` ẈƲ¡Ṫ - Link: integer, n ¡ - repeat... Ʋ - ...times: is square? (using integer only arithmetic) Ẉ - ...action: length of each (implicit range [1..n], implicit cast to digits) Ṫ - tail (for the list this is the length of digits of n, otherwise it's just n) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞TÅ€g ``` Slightly modified port of *@Neil*'s [Retina](https://codegolf.stackexchange.com/a/257420/52210) and [Charcoal](https://codegolf.stackexchange.com/a/257432/52210) answers, so make sure to upvote him as well! Outputs the sequence `1,2,3,4,5,6,7,8,9,10,2,12,13,14,15,16,17,18,19,20,2,22,...`. A.k.a.: $$a(n) = \begin{cases} \text{length}(n) & \text{if $(n-1)$ is divisible by 10} \\ n & \text{otherwise} \end{cases}$$ [Try it online.](https://tio.run/##yy9OTMpM/f//Uce8kMOtj5rWpP//DwA) **Explanation:** ``` ∞ # Push the infinite positive sequence: [1,2,3,...] TÅ€ # Map every 10th item to: # (where the 0-based index is visible by 10) g # The length of the current integer # (after which the infinite sequence is output implicitly as result) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞Ðtï.ι¦.ι ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8wxNKDq/XO7fz0DIg8f8/AA "05AB1E – Try It Online") Port of AndrovT's Vyxal answer. #### Explanation ``` ∞ # Infinite list of positive integers Ð # Triplicate tï # Square root and floor .ι # Interleave ¦ # Remove first item .ι # Interleave ``` [Answer] # [Scala](http://www.scala-lang.org/), 97 bytes Golfed version. [Try it online!](https://tio.run/##K05OzEn8/z8/KSs1uUTBVyG1oiQ1L6VYwbGgoDq4pCg1MVchrSg/V8FAIS0fyEvO0Mi0tasuKMrMK8nJ08hNLMnQK8gv18jU0TPV1CvJ98wrsbPLVDXStIYpydQ21KzVrP3/HwA) ``` object M extends App{Stream from 0 foreach(i=>{println(math.pow(i,.5).toInt>>i%2);println(i+1)})} ``` ]
[Question] [ Given an input of an integer \$n ≥ 2\$, output a list of its divisors sorted by the exponents in their prime factorizations, in ascending order, ordering first by the largest prime, then by the second largest, and so on. As an example, take the integer \$72\$, which is \$2^3\cdot3^2\$. It has the divisors ``` 1 3^0 · 2^0 2 3^0 · 2^1 3 3^1 · 2^0 4 3^0 · 2^2 6 3^1 · 2^1 8 3^0 · 2^3 9 3^2 · 2^0 12 3^1 · 2^2 18 3^2 · 2^1 24 3^1 · 2^3 36 3^2 · 2^2 72 3^2 · 2^3 ``` When sorted in ascending order by the exponents on the prime factors, with larger primes taking priority, this becomes ``` 1 3^0 · 2^0 2 3^0 · 2^1 4 3^0 · 2^2 8 3^0 · 2^3 3 3^1 · 2^0 6 3^1 · 2^1 12 3^1 · 2^2 24 3^1 · 2^3 9 3^2 · 2^0 18 3^2 · 2^1 36 3^2 · 2^2 72 3^2 · 2^3 ``` Note that the list is sorted first by the order of the exponent of 3, and then by the exponent of 2. You can also think of this as reading from left to right and top to bottom across the following grid: ``` 2^0 2^1 2^2 2^3 3^0 1 2 4 8 3^1 3 6 12 24 3^2 9 18 36 72 ``` Test cases: ``` 2 => 1 2 72 => 1 2 4 8 3 6 12 24 9 18 36 72 101 => 1 101 360 => 1 2 4 8 3 6 12 24 9 18 36 72 5 10 20 40 15 30 60 120 45 90 180 360 3780 => 1 2 4 3 6 12 9 18 36 27 54 108 5 10 20 15 30 60 45 90 180 135 270 540 7 14 28 21 42 84 63 126 252 189 378 756 35 70 140 105 210 420 315 630 1260 945 1890 3780 30030 => 1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210 11 22 33 66 55 110 165 330 77 154 231 462 385 770 1155 2310 13 26 39 78 65 130 195 390 91 182 273 546 455 910 1365 2730 143 286 429 858 715 1430 2145 4290 1001 2002 3003 6006 5005 10010 15015 30030 65536 => 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 74088 => 1 2 4 8 3 6 12 24 9 18 36 72 27 54 108 216 7 14 28 56 21 42 84 168 63 126 252 504 189 378 756 1512 49 98 196 392 147 294 588 1176 441 882 1764 3528 1323 2646 5292 10584 343 686 1372 2744 1029 2058 4116 8232 3087 6174 12348 24696 9261 18522 37044 74088 ``` Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes Code: ``` ÑÒí{€P ``` Explanation: ``` Ñ # Get the divisors of input. Ò # Factorize each. í # Reverse each. { # Sort the array. €P # Product each. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w5HDksOte-KCrFA&input=NzI). [Answer] ## [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆDÆfU$Þ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZEw4ZmVSTDng&input=&args=NzI) Thanks to @Dennis for -1 byte. ``` ÆD Array of divisors, e.g. 24 -> [1, 2, 4, 8, 3, 6, 12, 24] Þ Sort by... $ Combine previous two links... Æf Factorise each, e.g. ['', [2], [3], [2, 2], [2, 3], [2, 2, 2], [2, 2, 3], [2, 2, 2, 3]] U Upend/reverse each sublist ``` [Answer] # Pyth, 10 bytes ``` +1{*Mt_DyP ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=%2B1%7B%2AMt_DyP&input=74088&debug=0) Sadly the product over an empty list is not defined as 1 in Pyth. This costs three extra bytes. ### Explanation: ``` +1{*Mt_DyPQ implicit Q (=input number) at the end PQ prime factorization of input y powerset _D order by reversed subsets t remove the empy subset *M compute the product of each subsets { remove duplicates +1 prepend 1 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) **2 bytes thanks to @Sp3000.** ``` ~~ÆE‘ḶUṚŒpUṚÆẸ~~ ÆEU‘ḶŒpUÆẸ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZFVeKAmOG4tsWScFXDhuG6uA&input=&args=NzI) [Test suite.](http://jelly.tryitonline.net/#code=w4ZFVeKAmOG4tsWScFXDhuG6uArDh-KCrMWS4bmY4oKsauKBtw&input=&args=Miw3MiwxMDEsMzYwLDM3ODAsMzAwMzAsNjU1MzYsNzQwODg) ``` ÆE Array of exponents, e.g. 24 -> [3, 1] since 24 = 2^3*3^1 U Upend/reverse, e.g. [1, 3] ‘Ḷ Range of each, from 0, e.g. [[0, 1], [0, 1, 2, 3]] Œp Cartesian product, e.g. [[0, 0], [0, 1], ..., [1, 3]] U Upend, reversing the innermost lists ÆẸ Inverse of ÆE, converting exponents back into a number ``` **Credits to @Sp3000 for coming up with the format of the explanation.** [Answer] ## Python 2, 85 bytes ``` n=input() p,=L=[1] while~-n: l=L;p+=1 while n%p<1:L=l+[x*p for x in L];n/=p print L ``` No factorization, no sorting. Same-length recursive implementation: ``` f=lambda n,p=2:1/n*[1]or n%p and f(n,p+1)or[x*c for x in f(n/p)for c in[1,p][x%p<1:]] ``` [Answer] ## Actually, 19 bytes ``` ;÷#o♂w♂RS`"iⁿ"£Mπ`M ``` [Try it online!](http://actually.tryitonline.net/#code=O8O3I2_imYJ34pmCUlNgImnigb8iwqNNz4BgTQ&input=NzI) Explanation: ``` ;÷#o♂w♂RS`"iⁿ"£Mπ`M ; duplicate input ÷ divisors #o include input in divisors list (note to self: fix this bug) ♂w factor each integer into a list of [prime, exponent] pairs ♂R reverse each list, so that the largest prime comes first S sort the list `"iⁿ"£Mπ`M for each factorization: "iⁿ"£M for each [prime, exponent] pair: iⁿ push prime**exponent π product ``` [Answer] ## JavaScript, 78 bytes ``` f=(n,p=2,a=[1],b=a)=>n<2?a:n%p?f(n,p+1,a):f(n/p,p,a.concat(b=b.map(m=>m*p)),b) ``` Based on @xnor's idea, although I didn't understand his code so I had to reimplement it from scratch. The basic algorithm is that you start with [1] and multiply by [1,...,pᵏ] for each pᵏ in the prime factorisation of n, although as I don't have prime factorisation or cartesian product I have to do it all recursively. Example: ``` n=72 p=2 a=[1] b=[1] n=36 p=2 a=[1,2] b=[2] n=18 p=2 a=[1,2,4] b=[4] n=9 p=2 a=[1,2,4,8] b=[8] n=9 p=3 a=[1,2,4,8] b=[1,2,4,8] n=3 p=3 a=[1,2,4,8,3,6,12,24] b=[3,6,12,24] n=1 p=3 a=[1,2,4,8,3,6,12,24,9,18,36,72] b=[9,18,36,72] ``` [Answer] ## R, 196 bytes ``` n=scan() if(n<4)c(1,n)else{ r=2:n d=NULL while(n>1){i=r[min(which(n%%r==0))];d=c(d,i);n=n/i} m=unique(d) b=table(d) l=list() for(i in 1:length(m))l[[i]]=m[i]^(0:b[i]) apply(expand.grid(l),1,prod)} ``` This is going to be inefficient as heck because I hardly resisted the temptation of using `library(primes)`. It creates a vector `d` of all prime factors of the input, computes their frequency (number of occurreces), and then computes the cartesian product of all possible powers (from 0 to the respective frequency `b[i]`), to which the `prod` function is applied. Dang it, special cases of 2 and 3! Otherwise, this is a nice showcase of R dataframe handling and vector functions / by-row operations (and even the purely statistical `table` function!). Of course, its efficiency can be improved at the cost of 15 bytes using `r=2:ceiling(sqrt(n))`, if someone cares. Here is a nicer ungolfed version: ``` factorise <- function(n){ if (n<4) c(1,n) else { # Now that all special cases have been handled r=2:ceiling(sqrt(n)) # We check all divisors smaller than the square root d=NULL # Initiate the variable for divisors while (n>1) { i=r[min(which(n%%r==0))] # Check the first divisor with a zero remainder d=c(d,i) # Append it to the list of divisors n=n/i # Divide by it and check again } m=unique(d) # Get unique divisors, and they are already sorted b=table(d) # Count their frequencies l=list() # Initiate a list of all possible powers of unique factors for(i in 1:length(m)) l[[i]]=m[i]^(0:b[i]) # Calculate powers apply(expand.grid(l),1,prod) # Make a cartesian dataframe and row-multiply } } ``` [Answer] # Mathematica 150 bytes ``` f[t_]:=Thread@{#,IntegerExponent[t,#]&/@#}&@Prime@Range@PrimePi@Max@FactorInteger[t][[All,1]];Times@@@(#^#2&@@@#&/@Sort[Reverse/@(f@#&/@Divisors@#)])& ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` fḋᵒ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG04vK/6c93NH9cOuk//@jjXTMjXQMDQx1jM0MdIzNLYCEgYGxgY6ZqamxmY65iYGFRSwA "Brachylog – Try It Online") The code reads more or less just as the title of the challenge: "the factors of the input, sorted by their prime decompositions". Making sure that this 3-byte beauty actually passed the test cases using only Brachylog's built-in sense of how to sort lists ended up requiring me to copy and paste all those many numbers into the Clojure REPL, where list elements are separated by whitespace and commas are whitespace, but it turned out that it does indeed work. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 bytes Many thanks to ngn and Adám for their help in golfing both of these APL programs in [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard), a great place to learn APL and get APL help. ``` ∊×⍀/⌽{⊂×\1,⍵}⌸⍨⍭⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdoQBIdh2e/qi3Qf9Rz97qR11Nh6fHGOo86t1a@6hnx6PeFY961z7qmwpS@18BDAq4zI0A "APL (Dyalog Extended) – Try It Online") **Ungolfing** ``` ∊×⍀/⌽{⊂×\1,⍵}⌸⍨⍭⎕ ⎕ Gets evaluated input from stdin. ⍭ Gives us a list of the prime factors of our input. Example for 720: 2 2 2 2 3 3 5 { }⌸⍨ ⌸ groups our prime factors by the keys in the left argument, and ⍨ passes the prime factors as both arguments, grouping all the identical primes together before running a {} dfn on them ⊂×\1,⍵ We append 1 to each group, get a list of powers of each prime, and enclose the groups to remove 0s from uneven rows. ⌽ This reverses the prime power groups. ×⍀/ This multiplies all the powers together into a matrix of the divisors of our input. (Same as ∘.×/ in Dyalog Unicode) ∊ And this turns the matrix into a list of divisors sorted by prime factorization. We print implicitly, and we're done. ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 [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") ``` {∊∘.×/⌽{⊂×\1,⍵}⌸⍨¯2÷/∪∧\⍵∨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRR9ejjhl6h6frP@rZW/2oq@nw9BhDnUe9W2sf9ex41Lvi0Hqjw9v1H3WsetSxPAYo/KhjxaPezSD5/2mP2iY86u171DfV0/9RV/Oh9caP2iYCecFBzkAyxMMz@H@agrkRAA "APL (Dyalog Unicode) – Try It Online") **Ungolfing** ``` {∊∘.×/⌽{⊂×\1,⍵}⌸⍨¯2÷/∪∧\⍵∨⍳⍵} { } A dfn, a function in brackets. ⍵∨⍳⍵ We take the GCD of our input with all the numbers in range(1, input). ∪∧\ This returns all the unique LCMs of every prefix of our list of GCDs. Example for 72: 1 2 6 12 24 72. ¯2÷/ We divide pairwise (and in reverse) by using a filter window of negative two (¯2). Example for 72: 2 3 2 2 3, our prime factors. { }⌸⍨ ⌸ groups our prime factors by the keys in the left argument, and ⍨ passes the prime factors as both arguments, grouping all the identical primes together before running a {} dfn on them 1,⍵ We append 1 to each group. ⊂×\ Then we get a list of powers of each prime, and enclose the groups to remove 0s from uneven rows. ⌽ This reverses the prime power groups. ∘.×/ This multiplies all the powers together into a matrix of the divisors of our input. ∊ And this turns the matrix into a list of divisors sorted by prime factorization. We return implicitly, and we're done. ``` [Answer] # J, ~~32~~ 31 bytes ``` [:(*/@#~>:#:[:i.[:*/>:)&|./2&p: ``` Grabs the lists of primes and exponents of the input integer, reverse each, and build up the divisors from that. ### Usage ``` f =: [:(*/@#~>:#:[:i.[:*/>:)&|./2&p: f 2 1 2 f 72 1 2 4 8 3 6 12 24 9 18 36 72 f 101 1 101 ``` ### Explanation ``` [:(*/@#~>:#:[:i.[:*/>:)&|./2&p: Input: n 2&p: Factor n as a list where the first row are the primes and the second are their exponents [: &|./ Reverse each list >: Increment each exponent by 1 [:*/ Reduce it using multiplication [:i. Construct a range from 0 to that product exclusive >: The list of each exponent incremented #: Reduce each number in the previous range as a mixed base using the incremented exponents #~ For each mixed base value in that range, copy from the list of primes that many times */@ Reduce the copied primes using multiplication Return this list of products as the result ``` [Answer] # Ruby, 71 bytes This answer is based on xnor's Python 2 answer. ``` ->n{a,=t=[1];(s=t;a+=1;(t=s+t.map{|z|z*a};n/=a)while n%a<1)while n>1;t} ``` A same-length alternative is: ``` ->n{a,=t=[1];(a+=1;(t+=t.map{|z|z*a};n/=a)while n%a<1)while n>1;t.uniq} ``` **Ungolfing:** ``` def f(num) factor = 1 list = [1] while num != 1 s = list factor += 1 while num % factor == 0 list = s + list.map{|z| z*factor} num /= factor end end return list end def g(num) factor = 1 list = [1] while num != 1 factor += 1 while num % factor == 0 list += list.map{|z| z*factor} num /= factor end end return list.uniq end ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 9 bytes ``` â mk ñÔ®× ``` *-3 bytes thanks to @Shaggy* [Try it online!](https://tio.run/##y0osKPn///AihdxshcMbD085tO7w9P//zY24dAMB "Japt – Try It Online") [Answer] # Japt, 7 bytes ``` â ñ_k w ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=4iDxX2sgdw==&input=NzIKCi1R) [Answer] # Mathematica, 56 bytes ``` 1##&@@@Tuples@Reverse[#^Range[0,#2]&@@@FactorInteger@#]& ``` ]
[Question] [ ## Context When I was a little kid, I watched a Disney movie where [Goofy](https://en.m.wikipedia.org/wiki/Goofy) told his son "Boy, even a broken clock is right two or three times a day." ([see this youtube clip](https://youtu.be/pMw_oy-2wZY), courtesy of [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)). ## Rationale Given the previous statement, we wish to look at a clock that is *stopped* and answer the following question: *is this clock telling the correct time?*, [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'")-style. But we will also do it [*Goofy*](https://en.m.wikipedia.org/wiki/Goofy) style, assuming a stopped clock gets the correct time 3 times a day. # Task Pick some time of the morning with at least minute precision. Call it \$t\$. The function/full program/etc you submit must satisfy the following requirements: 1. if executed at \$t\text{ am}\$ and at \$t\text{ pm}\$, your code produces an observable output `a` (think *Truthy* in [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") challenges). 2. for every calendar day, there is a third time \$t\_1\$ distinct from \$t\text{ am}\$ and \$t\text{ pm}\$ such that, if your code is ran at that time, your code also deterministically produces the observable output `a`. This means \$t\_1\$ may be constant or it may be a function of the day the code is ran at. 3. if ran at any other time of the day, your code produces an observable output `b` that must be distinct from `a` (think *Falsy* in [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") challenges). Recall that your code should be precise at least to the minute. This means that you may decide that seconds don't matter for your answer, but you might also want to decide that your answer checks up to nanoseconds in order to decide if it is *that* time of the day. # Input Either your code takes no input or it takes the "current" time. For the time, acceptable formats include, but are not limited to: * Any ISO format for date/time strings where time is given at least to the minute; * An integer list with `[hours, minutes]` or `[hours, minutes, seconds]` or any similar list with further subdivisions of the second; (this order may be reversed but may *not* be shuffled) * Different arguments, each representing one element from the lists above. # Output A single, well-defined, observable output `a` if your code is run at \$t\text{ am}\$, at \$t\text{ pm}\$, or at \$t\_1\$, as specified in your answer. If ran at any other time, your code produces the observable output `b`, distinct from `a`. # Bonus imaginary internet points Bonus imaginary internet points will be awarded to the shortest answer for which \$t\_1\$ isn't constant. If this question turns out to receive enough attention, this will turn into an actual rep bounty. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing! [Answer] # JavaScript (ES6), 13 bytes Takes input as `(h)(m)`. Returns *true* for `01:00`, `02:00` and `13:00`, or *false* for anything else. ``` h=>m=>26%h<!m ``` [Try it online!](https://tio.run/##fcw9CoMwAIbh3VN8BQsJ2iC2OLTGS3gBg39RjJEYukjOnqZ17/QOD7yzeIu9NdNmb6vuej9wL3mleJUXV1lelB@0IRIc2QsSJfJHaJJQHBHwNXWaClb8mnDcs9OBVq@7Xnq26JE08SGZ1bU10zoSyjbR1VYYS/IUGXXP@FB/uEkxEEmJojScXeT8Bw "JavaScript (Node.js) – Try It Online") ### How? Testing \$26\bmod h<\delta\_m\$ is equivalent to test that we have \$m=0\$ and \$26\equiv 0\pmod h\$. For \$0<h\le23\$, we have \$26\equiv 0\pmod h\$ iff \$h\$ divides \$26\$, i.e. \$h\in\{1,2,13\}\$. For the edge case \$h=0\$, `26%h` results in `NaN` which is neither greater nor lower than any other value, so the test returns *false* as expected, no matter the value of \$m\$. ### Other possible values This program generates all possible values \$n<1000\$ for the expression \$n\bmod h\$. ``` for(n = 1; n < 1000; n++) { A = [...Array(24)].map((_, x) => x).filter(x => n % x == 0); if(A.length == 3 && A.some(x => A.includes(x + 12))) { console.log(n, A); } } ``` [Try it online!](https://tio.run/##JY1NDoIwFIT3nmI2kjbgC6A7xKTnMMY0UBBTWlLQYAxnr0U2k2/m/cxTvuVYuW6YDsbWyvvGOmZQIitgcEaWpmmgOOb47gARJlciEs7JD8tP/Ea9HBi7J5g5yktQajo9Kcfm1RrsEaBEyotw3jVMkFamnR5reEQUQdBoe7WtC@pMpV@1GoOPkeWcb71AZc1otSJtW2YSiP@/Zbd4/wM "JavaScript (Node.js) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/) + Core utilities, ~~26~~ 25 bytes + Bonus imaginary Internet points! ``` egrep '(.)T(11|23|0\1)00' ``` [Try it online!](https://tio.run/##S0oszvj/PzW9KLVAQV1DTzNEw9Cwxsi4xiDGUNPAQP3/fyMDIwMDY0PLEEMDQwtdA3MDAwA "Bash – Try It Online") *Thanks to @mypronounismonicareinstate for pointing out that the ISO 8601 allows omitting the colon in the time part, which saves a byte in the code. (ISO 8601 also allows omitting the hyphens in the date, but that doesn't affect the regex.)* This accepts input on stdin in a format like `20200319T1018-0700` which is a basic ISO 8601 format with precision to the minute. The result is in the exit code: `0` for truthy (one of the three Goofy times), `1` for falsey (everything else). The three times it outputs `0` are at: * 11:00 am * 11:00 pm * d:00 am where d is the last digit of the date. So, today, March 19, it would output truthy (exit code 0) for 9 am (because 9 is the last digit of the date 19), 11 am, and 11 pm. [Answer] # [R](https://www.r-project.org/), 23 bytes ``` function(h,m)26%%h|m|!h ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jQydX08hMVTWjJrdGMeN/moahjoEmV5qGEYQyNIbQBlCujqHmfwA "R – Try It Online") Port of [Arnauld's solution](https://codegolf.stackexchange.com/a/201380/86301), go upvote his! Outputs `FALSE` at 1:00, 13:00 and 2:00, and `TRUE` otherwise. --- Previous version: # [R](https://www.r-project.org/), 26 bytes ``` function(h,m)!h|m|(h/6)%%1 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jQydXUzGjJrdGI0PfTFNV1fB/moaZjoEmV5qGoRGUtoDQBhDKTMdQ8z8A "R – Try It Online") Outputs `FALSE` at the three times: \$t\_{am}\$ = `6:00` \$t\_{pm}\$ = `18:00` \$t\_1\$ = `12:00` and `TRUE` at any other time. Indeed, for the output to be `FALSE`, we need `h≠0`, `m=0`, and `h` to be a multiple of 6. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~22~~ \$\cdots\$ ~~20~~ 19 bytes Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f(h,m){h=26%~h<!m;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0MnV7M6w9bITLUuw0Yx17r2f25iZp6GZjVXWn6RRmZeiUKGrYF1ho2RibW2doYmTDAXKJhrY2YAFMzVzEzTgBikWVAElEzTUFI1MEqxAhExeUo6IBlrrtr/AA "C (gcc) – Try It Online") Returns `1` for noon, midnight and 1am, `0` otherwise. Adaptation of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [formula](https://codegolf.stackexchange.com/a/201380/9481). [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-!`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Inspired by [Kevin's choice of times](https://codegolf.stackexchange.com/a/201367/58974). Input as 2 integers in the order `h, m`. Outputs `true` at `00:00`, `01:01` and `13:01` and `false` otherwise. ``` %C*VÉ©Nx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=JUMqVsmpTng&input=MTIKMTI) ``` %C*VÉ©Nx :Implicit input of integers U=h and V=m %C :U modulo 12 (=1 if U=1 or U=13) *V :Multiplied by V (=1 if above and V=1) É :Subtract 1 (=0 if all above) © :Logical AND with N :Array of inputs (i.e., [U,V]) x :Reduced by addition (=0 if U=V=0) :Implicit output of boolean negation of result ``` --- A port of [Arnauld's solution](https://codegolf.stackexchange.com/a/201380/58974) would be 1 byte shorter. ``` 26%U<!V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MjYlVTwhVg&input=OAo4) [Answer] # [Ruby](https://www.ruby-lang.org), ~~48~~ 44 bytes *-4 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink)!* Differs from other answers so far in that it (i) takes no input and (ii) has a unique \$t\_1\$ for every day of the year. ``` p (t=*Time.now)[2]%12+t[1]<1||t[1,2]==t[3,2] ``` [Try it online!](https://tio.run/##KypNqvz/v0BBo8RWKyQzN1UvL79cM9ooVtXQSLsk2jDWxrCmBkjrGMXa2pZEGwPp//8B "Ruby – Try It Online") (actual code) [Try it online!](https://tio.run/##TY7BCsIwEETv/YqlEEg0hmSLB8X4Fd5iDrVNaaGtoikixm@PiScPM8u83YW5L5dX7PQ5bo605xODN9wW/4CSSGz32Upi0sLC0AH1enUaJidm96QoUfKKo@L5jxm0ROHaG2UPKoQ0OVqtvUknFj6RSiGwYsLVTQ/tFUIfCoBMt7s/OmUK0ImmHsdfo5Td3BZJ8Qs "Ruby – Try It Online") (demo version showing the three times that will return `true` on a given date) Outputs `true` at 00:00, 12:00, and *month*:*day* (03:20 for today, 20 March); `false` otherwise. `*Time.now` yields an array of the form `[sec, min, hour, day, month, year, wday, yday, isdst, zone]`, of which the first 8 elements are integers (but only *min*, *hour*, *day*, and *month* are used here). Then print `true` if *hour* (mod 12) and *min* are both 0, or if *hour* = *month* and *min* = *day*. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Taking input in the format `[minutes, hours]`: ``` `12%*ΘIO_~ ``` [Try it online.](https://tio.run/##yy9OTMpM/f8/wdBIVevcDE//@Lr//6MNDHUMjWMB) Without input and using the current time builtins: ``` ža12%žb*Θžažb+_~ ``` [Try it online](https://tio.run/##yy9OTMpM/f//6L5EQyPVo/uStM7NALKBDO34uv//AQ) (not very useful right now..) or [try it online with emulated hours/minutes](https://tio.run/##yy9OTMpM/a8UWpyqUJyfm6qQkV9aVKyQmJeikJuZV1qSWqxQCRJJzUlTyEgtSrVSUIrhMjRWUFDyAAmDuKFcBoZAvi9EOUgk7H@EoZFqpNa5GRGR2vF1//8DAA). Both programs use the three times: \$t\_{am}\$ = `1:01` \$t\_{pm}\$ = `13:01` \$t\_1\$ = `00:00` And will output `1` on any of those three times above, and `0` on any other time. **Explanation:** ``` ` # Push the values in the (implicit) input-pair separated to the stack 12% # Take modulo-12 on the hours, to make the 24-hour a 12-hour clock * # Multiply it with the minutes Θ # And check if it's exactly 1 (1 if truhy; 0 if falsey) I # Push the input-pair again O # Sum them together _ # Check if it's exactly 0 (1 if truhy; 0 if falsey) ~ # And then check if either of the two checks is 1 # (after which the result is output implicitly) ža # Push the current hours 12% # Modulo 12, to make the 24-hour a 12-hour clock žb # Push the current minutes * # Multiply them together Θ # And check if it's exactly 1 (1 if truthy; 0 if falsey) žažb # Push the current hours and minutes again + # Add them together _ # Check if it's exactly 0 (1 if truthy; 0 if falsey) ~ # And then check if either of the two checks is 1 # (after which the result is output implicitly) ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` _₂I%› ``` Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/201380/52210), so make sure to upvote him!! Takes two loose inputs, in the order `minutes`, `hours`. Will also output `1` for any of these three times below, and `0` on any other time: \$t\_{am}\$ = `01:00` \$t\_{pm}\$ = `13:00` [Try it online](https://tio.run/##MzBNTDJM/f8//lFTk6fqo4Zd//8bGHAZGgMA) or [verify some more test cases](https://tio.run/##MzBNTDJM/W9k4uYXemifscGjhllllSGPGjZ4RYBJpcP7rQ7vV3jUNklByb7yf/yjpqYI1UcNu/7r/AcA). **Explanation:** ``` _ # Check if the (implicit) input-integer (minutes) is 0 (1 if truthy; 0 if falsey) ₂ # Push 26 I # Push the second input-integer (hours) % # Take 26 modulo-hours (will result in 26 if the hours are 0 in the legacy version) › # Check if the first value is larger than the second # (after which it is output implicitly as result) ``` [Answer] # [Python 3](https://docs.python.org/3/), 21 bytes ``` lambda h,m:26%-~h<m<2 ``` [Try it online!](https://tio.run/##RY7BCsIwEETv/Yo1ICQQoY3SQ2luXvwHL7EmpmCSsuQior8eN1Xwssu8nR1meWSf4r44fS53Ey5XA16GQfXb3duPYVQlg4Ynb2UnJO@@U9F6NS4heJgjoIk3y9VBDA1UGP6wbysEpAzHKViQmB3pjQa@gurNqwkWnGPm7BSnhGinzCR1Afr5HY4pWibKBw "Python 3 – Try It Online") **Input**: hour and minute, as integers **Output**: `True` if the time is `00:01`,`01:01`,`12:01`, otherwise `False`. [Answer] # [Python 3](https://docs.python.org/3/), ~~35~~ \$\cdots\$ ~~22~~ 19 bytes Saved a byte thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved 3 bytes thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!! ``` lambda h,m:26%~h==m ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFDJ9fKyEy1LsPWNvd/Wn6RQoZCZp5CUWJeeqqGkYmmFZcCSDAXIWhmABJUyExTSNMAata0KijKzCvRSFOqzrAyMKq1qs4FUUqa/wE "Python 3 – Try It Online") Returns `True` for noon, midnight and 1am, `False` otherwise. Adaptation of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [formula](https://codegolf.stackexchange.com/a/201380/9481). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes ``` ^. $&$&$&$& \G\d $* ^1{8}:18 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP06PS0UNArli3GNSuFS0uOIMqy1qrQwt/v83sLAyNOcCkRZg0pLL0AQkAiItwKQll5EBSAREWoBJSwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^. $&$&$&$& ``` Repeat the hour tens digit four times. ``` \G\d $* ``` Convert the hour digits to unary. ``` ^1{8}:18 ``` They must sum to 8 and the minutes must be 18 (arbitrarily chosen to reuse the same digits). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` ⁼²№⟦↨S⁴N⟧⁹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDSEfBOb8UyI92SixO1fDMKygtCS4BqkjX0NRRMAFisJBfaW5SapGGZqyOgqWmpqb1//@GpgoGlv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as hour and minute separated by a space, on separate lines, or as a JSON list i.e. `[22, 10]`, and outputs `-` for `09 09`, `15 09` and `21 09` only. Explanation: ``` ⟦ ⟧ List of S Hours as a string ↨ ⁴ Interpreted as base 4 N Minutes № ⁹ Count `9`s ⁼² Must be 2 of them. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 19 bytes Returns true at 6:00, 12:00, 18:00. ``` ->h,m{h>0&&m|h%6<1} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cuQye3OsPOQE0ttyZD1czGsPZ/tJaBnp6RcaxeQVF@SmlyiUa0gY6hqY6xgY6JaaymQkq@Qg1QUw2XgkJBaUmxgpKqgVGKFYhQsFVQrk6LBkrG1iqpgmmu1LyU/wA "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Turns out porting [Arnauld's answer](https://codegolf.stackexchange.com/a/201380/53748) is a byte shorter than my original answer (which I've kept below) ``` 26%<¬} ``` A dyadic Link accepting the hour (an integer in `[0,23]`) on the left and the minute (an integer in `[0,59]`) on the right which yields 1 at three times (not varying by day), `2,0` (02:00), `1,0` (01:00), and `13,0` (13:00). **[Try it online!](https://tio.run/##y0rNyan8/9/ITNXm0Jra////Gxr/NwAA "Jelly – Try It Online")** --- **My 7** ``` æle1,98 ``` A dyadic Link accepting the hour (an integer in `[0,23]`) on the left and the minute (an integer in `[0,59]`) on the right which yields 1 at three times (not varying by day), `1,1` (01:01), `2,49` (02:49), and `14,49` (14:49). **[Try it online!](https://tio.run/##y0rNyan8///wspxUQx1Li////xua/DexBAA "Jelly – Try It Online")** [Answer] # perl -ple, 18 bytes ``` $_=/(2[01]|08):00/ ``` Reads a time in `HH:MM` format from `STDIN` (optionally preceded by a date in `YYYY-MM-DD` format (or anything else which doesn't like a time)). Print `1` followed by a newline if the time is `08:00`, `20:00` or `21:00`; otherwise, it prints a single newline. [Answer] # [W](https://github.com/A-ee/w), 5 [bytes](https://github.com/A-ee/w/wiki/Code-Page) ... With True and False swapped around; they're distinctive anyway. ``` ♥─y¥• ``` Uncompressed: ``` !26bm> ``` # Explanation ``` ! % Check whether the input is equal to 0 b % Push the second input 26 m % Push 26 % b > % Is input == 0 larger than the above value? ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~18~~ 17 bytes + Bonus imaginary Internet points ``` (.)T(11|23|0\1)00 ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0NPM0TD0LDGyLjGIMZQ08Dg/38jAyMDXQNjXUPLEANLAyDT3MrAAAA "Retina – Try It Online") *Note that TIO is having technical issues at the moment, so the link that it gave me above may or may not work.* --- *Thanks to @mypronounismonicareinstate for pointing out that the ISO 8601 allows omitting the colon in the time part, which saves a byte in the code. (ISO 8601 also allows omitting the hyphens in the date, but that doesn't affect the regex.)* --- I don't really know Retina, but this port of my bash answer appears to be right :) . The program accepts input on stdin in a format like 20200319T1018-0700 which is a basic ISO 8601 format with precision to the minute. Like my bash answer, it outputs truthy (0) for 11:00 am, 11:00 pm, and d:00 am where d is the last digit of the current date. It outputs falsey (1) otherwise. [Answer] # [Perl 5](https://www.perl.org/) -lF: , 34 bytes ``` say$F[0]%12&&$F[0]!=1||$F[1]>0?0:1 ``` [Try it online!](https://tio.run/##NcaxDkAwFAXQvX8hwVa5r1hegs3mC6RDB4OkQbBI@u2eklhOzjbtvhY53JX2I2xGJs@/JQ2FEEe2RQcmEYABBXol858U4o1CySgVKkZ1r9s5r8sheqgLEEQvzvf8AA "Perl 5 – Try It Online") Reads current time input from stdin in hh:mm format. Outputs 1 at 00:00, 01:00, and 12:00; 0 at all other times. [Answer] # [Io](http://iolanguage.org/), 19 bytes Port of @Arnauld's answer... ``` method(U,V,26%U>=V) ``` [Try it online!](https://tio.run/##y8z/n5yTn5ytYGWrEPM/N7UkIz9FI1QnTMfITDXUzjZMEyKtYahjoKlQUJSZV5KTxwURMsYUMtUxggv9BwA "Io – Try It Online") ]
[Question] [ ## Task Given an integer, `n`, where `3 <= n < 2^32`, calculate the area of a regular `n`-gon, with an apothem of 1, using the formula `A = n * tan(π / n)`. > > [The apothem of a regular polygon is a line segment from the center to the midpoint of one of its sides.](https://en.wikipedia.org/wiki/Apothem) > > > Output the area of this regular polygon as a floating point value showing no fewer than eight decimal places (i.e. `1.24217000`, `3.14159265`). ## Tests ``` In: 3 Out: 5.1961524227 In: 6 Out: 3.4641016151 In: 10 Out: 3.2491969623 In: 20 Out: 3.1676888065 In: 99 Out: 3.1426476062 In: 1697 Out: 3.1415962425 In: 15000 Out: 3.1415926995 ``` Note: The output values in the sample cases above each show ten decimal places -- two more than required. [Answer] # Mathematica, 16 bytes ``` N[Tan[Pi/#]#,9]& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfLzokMS86IFNfOVZZxzJW7X9AUWZeiYJDWrShqYGBQez//wA "Mathics – Try It Online") of course mathematica has built-ins for this ``` Area@*RegularPolygon ``` [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 24 bytes ``` i->i*Math.tan(Math.PI/i) ``` [Try it online!](https://tio.run/##ZY5BS8NAEIXP3V@xFAK7JR2rolBiexKhh4qQX7Amm2ZiMlmyk9RS@tvjWtOTpzfzPd7Mq8xglq2zVOVf6xEb13YsqwChZ6xhkYh/rOgpY2zp1xSu/6wxk1ltvJd7g3S@Ic@Ggwwt5rIJhkq5QzoAgOkOXp/F23Tn5bUNCRv/yVYWmxGXW1zsDZfAhtR1@NjdoR4TkWaGyHbSy40ke5TTrtKTZ9sAkk7EscTaKg@l8e/2m3fESoeHMySWQ8h5oBtOxGxKtj2DCw25UPMojyiCdRHRPB7iAoxz9Ump/NpQDzrELuJyGR/Fk3gW9yvxsPoB "Java (OpenJDK 9) – Try It Online") [Answer] # [Actually](https://github.com/Mego/Seriously), 5 bytes ``` ╦/Tß* ``` [Try it online!](https://tio.run/##S0wuKU3Myan8///R1GX6IYfna/3/bwwA "Actually – Try It Online") --- # How? ``` ╦/Tß* Full program. ╦ Push Pi. / Divide ^ by the input. T Tangent. ß* Multiply by the input. Output implicitly. ``` Alternative: `ß╦/T*`. o\_O Actually actually beats [Jelly](https://codegolf.stackexchange.com/a/141528/59487)!!! [Answer] # x87 Machine Code, 11 bytes ``` D9 EB DA 31 D9 F2 DD D8 DA 09 C3 ``` The above bytes of code define a function that calculates the area of a regular n-gon with an apothem of 1. It uses [x87 FPU instructions](https://en.wikipedia.org/wiki/X87) (the classic floating-point unit on the x86 processors) to do this computation. Following a standard x86 register-based calling convention (in this case, [`__fastcall`](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall)), the function's argument is a pointer to the integer, passed in the `ECX` register. The function's result is a floating-point value, returned at the top of the x87 floating-point stack (register `ST0`). **[Try it online!](https://tio.run/##nY7vaoMwFMU/m6e4ODoS0WKVuYpbYWvXl1iGpPFPAzaOGIcw9upzV9wL6IdwOTfnd8@RQS3lOMpWdxbkVRgY9smxLcr3D3gGlw@nlA9vrzhf@BDvZn2OcJ7w7ed9iLtj7Gaks8IqCUXbX5oS8lxYa9Slt2WeU1qJzkrRNIwB9TDlPGhGlbYew6T/1Gy8U1o2fVHCU2cL1W6vB4IeuAmlJzMIU0t/bup5KL4Y@SbO9KPxTJwR59Ogqqi7KbgNDtxutruw4tr1Qfsw59J7zRhaJyRZjuzC5Uy0gknTFd2S9HEF9RCGCwsSx5S2NxqQ@xl/ZdWIuhuDWxz9AQ)** **Ungolfed assembly mnemonics:** ``` D9 EB fldpi ; load constant PI at top of FPU stack DA 31 fidiv DWORD PTR [ecx] ; divide PI by integer input (loaded from pointer ; in ECX), leaving result at top of FPU stack D9 F2 fptan ; compute tangent of value at top of FPU stack DD D8 fstp st0 ; pop junk value (FPTAN pushes 1.0 onto stack) DA 09 fimul DWORD PTR [ecx] ; multiply by integer input (again, loaded via ECX) C3 ret ; return control to caller ``` As you can see, this is basically just a straightforward computation of the given formula,      *result = n \* tan(π / n)* Only a couple of interesting things bear pointing out: * The x87 FPU has a dedicated instruction for loading the constant value PI ([`FLDPI`](http://www.felixcloutier.com/x86/FLD1:FLDL2T:FLDL2E:FLDPI:FLDLG2:FLDLN2:FLDZ.html)). This was rarely used, even back in the day (and obviously much less so now), but it's shorter in size than embedding a constant into your binary and loading that. * The x87 FPU instruction to calculate tangent, [`FPTAN`](http://www.felixcloutier.com/x86/FPTAN.html), replaces the value of the input register (the top of the FPU stack) with the result, but *also* pushes a constant 1.0 onto the top of the FPU stack. This is done for backwards compatibility with the 8087 (I have no idea why this was done on the 8087; probably a bug). That means we need to pop this unneeded value off of the stack. The fastest and shortest way to do that is a simple [`FSTP st0`](http://www.felixcloutier.com/x86/FST:FSTP.html), like we use here. We could have also done a [multiply-and-pop](http://x86.renejeschke.de/html/file_module_x86_id_104.html), since multiplying by 1.0 won't change the result, but this is also 2 bytes (so no win in code size), will probably execute more slowly, and may introduce unnecessary indeterminacy into the result. Although a modern programmer or compiler would use the SSE (and later) instruction set, rather than the aging x87, this would require more code to implement, as there's no single instruction to compute a tangent in these newer ISAs. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ØP÷ÆT× ``` [Try it online!](https://tio.run/##y0rNyan8///wjIDD2w@3hRye/v//f0NTAwMDAA "Jelly – Try It Online") Jelly's π builtin has >8 decimal places. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` ;π/₍*₄;?× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/p8g/6jpl6tR00t1vaHp///b2hqYGDwPwoA "Brachylog – Try It Online") [Answer] ## [Sakura](https://github.com/tuxcrafting/sakura), 4 bytes ``` *ij/π ``` This is expanded to `*ij/π⓪⓪`, which is ``` * * ij tan( ) / / π π ⓪ n ⓪ n ``` [Answer] # [R](https://www.r-project.org/), 25 bytes ``` cat((n=scan())*tan(pi/n)) ``` Input from stdin, output to stdout. [Try it online!](https://tio.run/##K/qfX1CSmZ9XrJGSmZ5ZUmxrZKT5PzmxREMjz7Y4OTFPQ1NTqwRIFWTq52lq/jc0@A8A "R – Try It Online") [Answer] # JavaScript (ES6), 24 bytes ``` x=>x*Math.tan(Math.PI/x) ``` --- ## Try it ``` o.innerText=(f= x=>x*Math.tan(Math.PI/x) )(+i.value);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i min=3 type=number value=3><pre id=o> ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` YPy/Z,* ``` [Try it online!](https://tio.run/##y00syfn/PzKgUj9KR@v/f0MDAA "MATL – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), 7 bytes ``` *MtMP/U ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=Kk10TVAvVQ==&input=Mw==) --- ## Explanation Just implements the forumla, where `Mt` is tan, `MP` is pi and `U` is the input. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 7 bytes ``` απ/ÆT³* ``` **[Try it online!](https://tio.run/##y8/INfr//9zG8w36h9tCDm3W@v/fGAA "Ohm v2 – Try It Online")** --- # How? ``` απ/ÆT³* Full Program απ Push Pi. / Divided by the input. ÆT Tangent. ³* Multiplied by the input. Implicitly output. ``` [Answer] # Perl, 14 + 16 = 30 ``` perl -MMath::Trig -ple'$_*=tan(pi/$_)' ``` 14 bytes for the program proper, and 16 for the command line switches [Answer] # [var'aq](http://esolangs.org/wiki/Var%27aq), 51 bytes ``` 'Ij latlh HeHmI' tam boqHa''egh qojmI' boq'egh cha' ``` ## Explanation ``` 'Ij - read from STDIN latlh - duplicate top of stack HeHmI' - push PI onto stack tam - swap first 2 elements on stack boqHa''egh - divide qojmI' - take tangent boq'egh - multiply cha' - print ``` [Answer] # Common Lisp, 29 bytes ``` (lambda(n)(* n(tan(/ pi n)))) ``` [Try it online!](https://tio.run/##S87JLC74r5GWX5SbWKJQoqBUp2NokKakoPFfIycxNyklUSNPU0NLIU@jJDFPQ1@hIFMhTxMI/psBMQA) [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` from math import* n=input() print n*tan(pi/n) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1chN7EkQyEztyC/qESLK882M6@gtERDk6ugKDOvRCFPqyQxT6MgUz9P8/9/Q1MDAwMA "Python 2 – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes ``` *.tc.n0Q2 ``` **[Test suite.](https://pyth.herokuapp.com/?code=%2a.tc.n0Q2&test_suite=1&test_suite_input=3%0A6%0A10%0A20%0A99%0A1697%0A15000&debug=0)** --- # How? ``` *.tc.n0Q2 Full program. Q means input. .n0 Pi. c Divided by: Q The input. .t 2 Tangent. * Q Multiply by the input. Output implicitly. ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 5 bytes ``` ₵P÷ṫ× ``` [Try it online!](https://tio.run/##S0/MTPz//1HT1oDD2x/uXH14@v//xgA "Gaia – Try It Online") --- # How? ``` ₵P÷ṫ× Full program. ₵P Push Pi. ÷ Divided by the input. ṫ Tangent. × Multiply by the input. ``` [Answer] # [Swift](https://swift.org), 35 bytes With compiler warnings: ``` import Foundation {tan(M_PI/$0)*$0} ``` **[Try it here!](http://swift.sandbox.bluemix.net/#/repl/59ad330edd73eb75289a5491)** Without compiler warnings, [**40 bytes**](http://swift.sandbox.bluemix.net/#/repl/59ad3360dd73eb75289a5492): ``` import Foundation {tan(Double.pi/$0)*$0} ``` [Answer] # Excel, 16 bytes ``` =A1*TAN(PI()/A1) ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 25 bytes ``` f(X,Y):-X is Y*tan(pi/Y). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P00jQidS00o3QiGzWCFSqyQxT6MgUz9SUw8ipWCsqccFZpjBGIYGMJYRnGVpCZc1szSHs00NDIBKAA "Prolog (SWI) – Try It Online") This is my first submission to codegolf, hope I'm doing alright. Written as a function. [Answer] # IBM/Lotus Notes Formula Language, 13 bytes ``` a*@Tan(@Pi/a) ``` Input taken via a field named a on the same form as the field containing the formula. No TIO available so screenshot of all test cases shown below: [![enter image description here](https://i.stack.imgur.com/3RS6S.png)](https://i.stack.imgur.com/3RS6S.png) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes ``` param($n)$n*[math]::tan([math]::pi/$n) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyVPKzo3sSQj1sqqJDFPA8YuyNQHSv7//9/QzNIcAA "PowerShell – Try It Online") Does exactly what it says on the tin, just takes a little longer due to the lengthy `[math]::` .NET calls. [Answer] # [Ruby](https://www.ruby-lang.org/), 27 bytes ``` ->n{n*Math.tan(Math::PI/n)} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk/LN7EkQ68kMU8DxLCyCvDUz9Os/R9trKNgpqNgaKCjYATElpZAtpmlOZA0NTAwiNVLTUzOUKiuyatRKCgtKVZQUq7Oq43JU65Oi86LBTJi8pRq/wMA "Ruby – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 14 bytes ``` n->tan(Pi/n)*n ``` [Try it online!](https://tio.run/##FYexCoAgGAZf5cNJQ8mKDId8hvZocDGE@PkRl57ebLjjjmPJ5uaWsKORCTWSPPJIaqAWmZ9XEkwAl0y1p/hHIElSSuNcNJzGZDXmjve9nd@6V2vtpdoH "Pari/GP – Try It Online") [Answer] # [C# (Mono C# compiler)](http://www.mono-project.com/docs/about-mono/languages/csharp/), 24 bytes ``` =>n*Math.Tan(Math.PI/n) ``` [Try it online!](https://tio.run/##XY9PTwIxEMXPzqcot67RumjEkHVJDIIhASRC4sF4qN0Kjd0ptl3@hPDZ1@4CCfHWN/PevF@Fu84NmrJwCudkunVe5gmcKzZU@Ptv1DVaS@GVQcdeJEqrRAJCc@fIxJq55TnZATjPvRJkZVRGRlwhdd6GIx@fhNu5i4JlqJx/zEzxpWWHKFwW3pGUoFyT8w2NEpjWUeISyAzsgJDK2A39Rkv2JnkWKGUwXoD6po2Dmw3cuND61fbypd9SF0Uhd2hhT1lGQ3wlrWcz81wXVY4E9rBeqEo0UgzpMOkXKI4sVydYwbWoUIMj/PwoSkg7eDnifsFmHGn9mAxuMCoTOPb2je1xsaCbtHOif7fKyxq/usMGuDI/km6iA8y@vIMWNGO4jaHdhmar/QDN@ziO/wA "C# (Mono C# compiler) – Try It Online") [Answer] # [RPNGolf 0.6/0.7](http://github.com/pizzapants184/rpngolf), 12 bytes ``` tbp-1mBsdmcc ``` My first post using RPNGolf, my new stack-based language! This is a full program that reads an integer from standard input and prints the output to standard output (without a trailing newline). Explanation: ``` tb # push user input from STDIN as int p # duplicate top of stack -1 # push -1 mB # pop i, push inverse cosine of i s # swap top two items on the stack d # pop b, pop a, push a/b mc # pop i, push tangent of i c # pop b, pop a, push a*b # RPNGolf implicity prints the stack upon normal exit ``` [Answer] # [Factor](https://factorcode.org/), 19 bytes ``` [ pi over / tan * ] ``` [Try it online!](https://tio.run/##JY2xCsIwFEX3fMWdHWqiWIl@gLh0KU7iEMIrBu1LTF4FEb89Fh3POcMZnJeY66k/docdRifXxkcu4ljKD/9umNhLmANulJnuSJlEXikHFhR6TMSeCvZKvbFGC6Ox0rAWprVbmI3WGh9Vz0gB8UkZS8wLLHCpo0to6hc "Factor – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žqI/ż* ``` [Try it online](https://tio.run/##yy9OTMpM/f//6L5CT/3DrYf2aP3/bwYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o/sKK/UPtx7ao/Vf53@0sY6ZjqGBjpGBjqWljqGZpbmOoamBgUEsAA). **Explanation:** ``` žq # Push PI (3.141592653589793) I/ # Divide it by the input ż # Get the tangent of this * # Multiply it by the (implicit) input # (after which the result is output implicitly) ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 6 bytes ``` Đπ/⅟ť* ``` [Try it online!](https://tio.run/##K6gs@f//yITzDfqPWucfXar1/7@hAQA "Pyt – Try It Online") ``` Đ implicit input (n); duplicate on stack π push pi / divide n by pi ⅟ take the reciprocal ť tan(pi/n) * multiply by n; implicit print ``` ]
[Question] [ Inspired by [Find the “unwrapped size” of a list](https://codegolf.stackexchange.com/questions/99304/find-the-unwrapped-size-of-a-list). Define the Recursive Size, `RS`, of a list containing no lists as its length (number of items contained) and the Recursive Size of a list containing any lists as the sum of its length and the Recursive Size of those lists. ### Challenge Write a program or function that outputs the Recursive Size of any given list in as few bytes as possible. The input is a list and may contain numbers, strings (if your language has them), and similar lists. --- For example: ``` RS([]) = 0 RS([[]]) = 1 RS([4, 5, 6]) = 3 RS(["four", "five", "six"]) = 3 RS(["[[[[]]]]", "[][][][][]", "][][[[]]][]["]) = 3 RS([[4, 5, 6]]) = 4 RS([["four", "five", "six"]]) = 4 RS([["[[[[]]]]", "[][][][][]", "][][[[]]][]["]]) = 4 RS([[4], [5], [6]]) = 6 RS([["four"], ["five"], ["six"]]) = 6 RS([["[[[[]]]]"], ["[][][][][]"], ["][][[[]]][]["]]) = 6 RS([[[[[[[[[]]]]]]]]]) = 8 RS([[],[],[],[],[],[],[],[]]) = 8 RS([[],[],[[]],[[[[]]]]]) = 8 RS([0,[-1],[2.3,-4.3],[5,[6]],[7,[8,9,[10,11,[12,13,14]]]]]) = 22 ``` Note that if your language has no strings but does have lists of characters, the examples containing `"strings"` above could actually be lists of characters and have larger results. As an example: ``` RS([['f','o','u','r'], ['f','i','v','e'], ['s','i','x']]) = 14 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins; no funny-business, as always. A non-list input may produce any output. I/O is as [flexible as usual](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top). [Answer] ## Python, 42 bytes ``` f=lambda x:x*0==[]and len(x)+sum(map(f,x)) ``` For a non-list, output 0. For a list, output its length plus the sum of the recursive outputs for its elements. Lists fall above numbers and below strings in the Python 2 ordering, requiring `[]<=x<''`. Instead, we check `x*0==[]`, whereas the result of `0` for a number or `''` for a string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ߀-ŒḊ?‘S ``` [Try it online!](http://jelly.tryitonline.net/#code=w5_igqwtxZLhuIo_4oCYUw&input=&args=WzAsWy0xXSxbMi4zLC00LjNdLFs1LFs2XV0sWzcsWzgsOSxbMTAsMTEsWzEyLDEzLDE0XV1dXV0) ### How it works ``` ߀-ŒḊ?‘S Main link. Argument: x ŒḊ? If x has non-zero depth: ߀ Recursively map the main link over its elements. - Else, yield -1. ‘ Increment all integers in the result. S Compute the sum of the result. If x is an array, incrementing before adding is equivalent to computing the sum of the elements and the length. If x is an integer/character, incrementing -1 yields 0, as desired. ``` [Answer] # JavaScript (ES6), ~~39~~ 37 bytes *Saved 2 bytes thanks to @edc65* ``` f=a=>a.map&&a.map(x=>a-=~f(x),a=0)&&a ``` [Answer] # Mathematica, 20 bytes ``` Length@Level[#,∞]& ``` Anonymous function. Takes an expression as input and returns a number as output. The Unicode character is U+221E INFINITY for `\[Infinity]`. `Level[#,∞]` gives a list of the input's subexpressions, and `Length@` counts them. [Answer] ## Mathematica, 14 bytes ``` LeafCount@#-1& ``` Minor modification of my [previous answer](https://codegolf.stackexchange.com/a/99311/8478). As I explained there, `LeafCount` already takes care of nested atomic values, but it also counts the outermost list, which we need to subtract from the result. [Answer] ## Perl, 34 bytes A recursive function! Yep, Perl doesn't only have regex but also have functions! ``` sub f{@_+f(map ref?@$_:(),@_)if@_} ``` If you want to test it, you can run something like : ``` perl -pE 'sub f{@_+f(map ref?@$_:(),@_)if@_}$_=f@{+eval}' <<< '[["four"], ["five"], ["six"]]' ``` [Answer] # Mathematica, 32 bytes ``` Length@#+Tr[#0/@#~Select~ListQ]& ``` Unnamed recursive function. The excerpt `#0/@#~Select~ListQ` calls the function again on each element of the input that's a list, and `Tr` sums those values up. Fortunately Mathematica is fine taking the length of the empty list and searching for qualifying elements from the empty list, so no base case is needed. [Answer] ## Haskell, 52 bytes ``` data L a=E a|N[L a] r(N n)=1+sum(r<$>n) r _=1 pred.r ``` Usage example: ``` *Main> pred.r $ N[E 0,N[E(-1)],N[E 2.3,E(-4.3)],N[E 5,N[E 6]],N[E 7,N[E 8,E 9,N[E 10,E 11,N[E 12,E 13,E 14]]]]] 22 ``` Haskell doesn't support mixed lists (e.g. Int and list of Int), so I go with a custom list type `L` which is either an element of some type a (-> `E a`) or a list of other Ls (-> `N[L a]`). Calculating the RS is a simple recursion where an `E` counts `1` and a `N` one plus the sum of the recursive sizes of its elements. The whole sum is off by 1, so I subtract it via `pred`. Side note: the exact types and values of the elements are not important for the algorithm, so we could remove the polymorphism an deal with abstract elements only and go with `data L=E|N[L]`. [Answer] # Factor, 105 bytes Recursive function g. ``` : g ( o -- l ) [ dup [ sequence? ] [ string? not ] bi and [ [ g ] map sum 1 + ] [ drop 1 ] if ] map sum ; ``` Ungolfed (kinda): ``` : g ( o -- l ) [ dup [ sequence? ] [ string? not ] bi and [ [ g ] map sum 1 + ] [ drop 1 ] if ] map sum ; ``` You'll find there are no calls to `length` because instead of using the length builtin, it's implemented through `drop 1` on strings and non-sequences. [Answer] ## Mathematica, 18 bytes ``` (c=-1;++c&//@#;c)& ``` Yet another Mathematica approach. Not as short as using the built-in `LeafCount` but still fairly concise. This makes use of the `MapAll` operator `//@` which calls a function on every node of an expression, and we use that function to increment a counter `c`. As in the `LeafCount` case, this gives one more than we need, because it counts the outer list head as well, so we start the counter from `-1`. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 50 bytes ``` int f(Array a)=>a.Length+a.OfType<Array>().Sum(f); ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/M69EIU3DsagosVIhUdPWLlHPJzUvvSRDO1HPPy2ksiDVBixnp6GpF1yaq5Gmaf0/oAioSSNNIy@1XCE/KSs1uSQ6trpWU9OaC6sMqjKwOuwKTXRMdcxwm6OUll9apKSjlJZZlgqkijMrlPAojgaCWCAAqoyOhUEgB0SDZYC0Eh7HYHEZkV7E5k5itRLnaoiziTCPhpxaGCAy3nXoxQU56D8A "C# (Visual C# Interactive Compiler) – Try It Online") Uses the same technique as the previously submitted [Java answer](https://codegolf.stackexchange.com/a/178769/8340), but leverages LINQ to reduce the answer length. Explanation: ``` // f is a method that a accepts // an array of any underlying type int f(Array a)=> // include the length of the // current array in the total a.Length+ // filter the current list to elements // that are also arrays a.OfType<Array>() // recursively call f on each child // array and add to cumulative total .Sum(f); ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (legacy), ~~22~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "ε¼D¸D˜Êi®.V"©.V¾ ``` [Try it online](https://tio.run/##MzBNTDJM/f9f6dzWQ3tcDu1wOT3ncFfmoXV6YUqHVuqFHdr3/3@0gU60rmGsTrSRnrGOromeMZBpqhNtFgukzXWiLXQsdaINDXQMDYGUkY6hsY6hSSwIAAA) or [verify all test cases](https://tio.run/##jZA7CsJAEIavEqaehGwePqqg5gqKMGyhoJBKUBS9gIWltRewsRMsxGItBQ/hReLMJhGFFG42O/P/M/vtJn48GqtJvtqkCTiv7d6BxNz6OTzP5pqaS/o43HeZOXkDMEdvYG750MWcSKPDi6wRxtiQBKaz5RwQptlqwmGRrcHaRNKpNXukq4eFRFvhaDtLlE3rYEXhP1zB00gxvz9M1gVVkjqu@F9kkTXscuhq2P@BdfOrJOKzi20fyVVsBV6IbuSFct/iutREamEbSfmoFIcAVYgqqnZCB5gEXf7wHpTHKwwsPmQpjW8). **Explanation:** This challenge poses multiple challenges to overcome in 05AB1E: 1. Although 05AB1E does have a recursive function since the Elixir rewrite (`λ`), it's only useful for integer sequences. [Here is an answer of mine as example of the 05AB1E recursive function.](https://codegolf.stackexchange.com/a/171306/52210) Because of that, I had to find an alternative to do recursive calls, which I did by putting part of the code in a string, and execute that string as 05AB1E code recursively. 2. There also isn't an `isList` command in 05AB1E, so I had to use some workarounds to check this by utilizing wrapping into a list, deep flattening, and check for equality. 3. And third, there isn't a flatten for just one level of a multi-dimensional list. The flatten function `˜` is a deep flatten that removes all layers and makes a multi-dimensional list a single list with all inner-most values. (i.e. `[[1,2],[[[3]],4]]` becomes `[1,2,3,4]`). I ended up with the code at the top to overcome all three of the above issues. It's split into three major parts. First we have the following: ``` "..." # Create a string with 05AB1E code © # Save this string in the register (without popping) .V # Execute the string as 05AB1E code ``` The string contains the following code: ``` ε # Map each value in the given list by: # (this uses the input-list implicitly with the initial call) ¼ # Increase the counter_variable by 1 D # Duplicate the map-value # i.e. STACK "A" becomes "A","A" # i.e. STACK [["B","C"]] becomes [["B","C"]],[["B","C"]] ¸ # Wrap it into a list # i.e. "A" → ["A"] # i.e. [["B","C"]] → [[["B","C"]]] D # Duplicate that again # i.e. STACK "A",["A"] becomes "A",["A"],["A"] # i.e. STACK [["B","C"]],[[["B","C"]]] # becomes [["B","C"]],[[["B","C"]]],[[["B","C"]]] ˜ # Flatten it # i.e. ["A"] → ["A"] # i.e. [[["B","C"]]] → ["B","C"] Ê # Check if the wrapped and wrapped+flattened lists are NOT equal # i.e. ["A"] and ["A"] → 0 (falsey) # i.e. [[["B","C"]]] and ["B","C"] → 1 (truthy) i # If they are: ® # Push the string from the register .V # Execute it as 05AB1E code # (this is basically our recursive call, mapping the current value # we duplicated initially again) ``` A map is used instead of a foreach-loop, because the map has an implicit `y`, and a foreach-loop need an explicit `y`. We only care about the `counter_variable`, though. And finally, after all the maps and inner maps are done, we'll: ``` ¾ # Push the counter_variable (which is output implicitly as result) ``` [Answer] # [R](https://www.r-project.org/), 65 bytes ``` R=function(L,`*`=sapply)"if"(any(L*is.list),sum(1+L*R),length(L)) ``` [Try it online!](https://tio.run/##K/r/P8g2rTQvuSQzP0/DRydBK8G2OLGgIKdSUykzTUkjMa9Sw0crs1gvJ7O4RFOnuDRXw1DbRytIUycnNS@9JEPDR1Pzf5AGSFZDU5MLyoJy4XwTHVMdMwRXKS2/tEhJRyktsywVSBVnViih6cWqQvM/AA "R – Try It Online") Obvious recursive implementation of the spec. [Answer] # C, ~~174~~ ~~167~~ 152 bytes Recursive function `f`, which leaks memory (**152**): ``` #include"object.h" size_t f(array_t*a){size_t t=0,i=0;for(;i<array_length(a);i++){object_t*o=array_get_copy(a,i,0);t+=o->type==6?f(o->ary):1;}return t;} ``` Recursive `f` which doesn't leak, using references, at **167**: ``` #include"object.h" size_t f(array_t*a){size_t t=0,i=0;for(;i<array_length(a);i++){object_t**o=array_get_ref(a,i,0);t+=*o->type==t_array?f(*o->ary):1;}return t;} ``` Ungolfed: ``` size_t get_recursize (const array_t* const a) { pfn(); object_failnull(a); size_t out = 0; for (size_t i = 0; i < array_length(a); i++) { object_t** o = array_get_ref(a, i, NULL); if ( (*o)->type == t_array ) { out += get_recursize((*o)->ary); } else { ++out; } } return out; } ``` "But how," you ask, "can this be answered in C? Surely, there are no managed arrays in C, and you can't really have heterogeneous arrays...?" "Aha," I reply, "for I have been working on a simple system of "objects" for (GNU-ish) C11 and ISO C++11". The full demo program for this function is: ``` #include "../calc/object/object.h" size_t get_recursize (const array_t* const a); define_array_new_fromctype(ssize_t); int main (void) { size_t len = 6; static const ssize_t h[6] = { -1, 3, -5, 7, -9, 11 }; array_t* a = array_new_from_ssize_t_lit(h, len, t_realint); size_t rsize = get_recursize(a); printf("Recursive size of a: %zu\n", rsize); object_t* asobj = object_new(t_array, a); array_destruct(a); array_t* b = array_new(NULL, -1); for (size_t j = 0; j < 10; j++) { array_append(b, asobj); } object_destruct(asobj); rsize = get_recursize(b); printf("Recursive size of b: %zu\n", rsize); asobj = object_new(t_array, b); array_destruct(b); array_t* c = array_new(NULL, -1); for (size_t i = 0; i < 100; i++) { array_append(c, asobj); } object_destruct(asobj); rsize = get_recursize(c); printf("Recursive size of c: %zu\n", rsize); array_destruct(c); return EXIT_SUCCESS; } size_t get_recursize (const array_t* const a) { pfn(); object_failnull(a); size_t out = 0; for (size_t i = 0; i < array_length(a); i++) { object_t** o = array_get_ref(a, i, NULL); if ( (*o)->type == t_array ) { out += get_recursize((*o)->ary); } else { ++out; } } return out; } ``` Right now, it lives [here](https://github.com/catb0t/c-projects/tree/8c1f34fc95ce8f26b83cc30d1db56191f0b6418e) and you'll need that repo to use this. You'll also need the Fowler-Noll-Vo hash library, `libfnv`, compiled for your platform. It's in that repository and you can also grab it [here](https://github.com/catb0t/fnv-hash). Then you can do `cc -DNODEBUG size.c path/to/libfnv.a -o size`. The implementation isn't necessarily efficient: ``` $ valgrind --leak-check=full --track-origins=yes --show-leak-kinds=all ./size ==24127== Memcheck, a memory error detector ==24127== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. ==24127== Using Valgrind-3.12.0.SVN and LibVEX; rerun with -h for copyright info ==24127== Command: ./size ==24127== Recursive size of a: 6 Recursive size of b: 60 Recursive size of c: 6000 ==24127== ==24127== HEAP SUMMARY: ==24127== in use at exit: 0 bytes in 0 blocks ==24127== total heap usage: 22,900 allocs, 22,900 frees, 615,584 bytes allocated ==24127== ==24127== All heap blocks were freed -- no leaks are possible ==24127== ==24127== For counts of detected and suppressed errors, rerun with: -v ==24127== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) ``` But it does work! The last commit to master (which this program compiled on) was 2 days ago, which means this submission is valid. [Answer] **Axiom 118 bytes** ``` RS(a:Union(List(Any),Any)):INT==(a case List(Any)=>(g:List(Any):=a;leaf? g=>0;r:=#g;for i in g repeat r:=r+RS(i);r);0) ``` ungolfed ``` RS(a:Union(List(Any),Any)):INT== a case List(Any)=> g:List(Any):=a leaf? g=>0 r:=#g for i in g repeat r:=r+RS(i) r 0 ``` results ``` (25) -> RS([])=0 (25) 0= 0 Type: Equation NonNegativeInteger (26) -> RS([[]]) = 1 (26) 1= 1 Type: Equation PositiveInteger (27) -> RS([4, 5, 6]) = 3 (27) 3= 3 Type: Equation PositiveInteger (28) -> RS(["four", "five", "six"]) = 3 (28) 3= 3 Type: Equation PositiveInteger (29) -> RS(["[[[[]]]]", "[][][][][]", "][][[[]]][]["]) = 3 (29) 3= 3 Type: Equation PositiveInteger (30) -> RS([[4, 5, 6]]) = 4 (30) 4= 4 Type: Equation PositiveInteger (31) -> RS([["four", "five", "six"]]) = 4 (31) 4= 4 Type: Equation PositiveInteger (32) -> RS([["[[[[]]]]", "[][][][][]", "][][[[]]][]["]]) = 4 (32) 4= 4 Type: Equation PositiveInteger (33) -> RS([[4], [5], [6]]) = 6 (33) 6= 6 Type: Equation PositiveInteger (34) -> RS([["four"], ["five"], ["six"]]) = 6 (34) 6= 6 Type: Equation PositiveInteger (35) -> RS([["[[[[]]]]"], ["[][][][][]"], ["][][[[]]][]["]]) = 6 (35) 6= 6 Type: Equation PositiveInteger (36) -> RS([[[[[[[[[]]]]]]]]]) = 8 (36) 8= 8 Type: Equation PositiveInteger (37) -> RS([[],[],[],[],[],[],[],[]]) = 8 (37) 8= 8 Type: Equation PositiveInteger (38) -> RS([[],[],[[]],[[[[]]]]]) = 8 (38) 8= 8 Type: Equation PositiveInteger (39) -> RS([0,[-1],[2.3,-4.3],[5,[6]],[7,[8,9,[10,11,[12,13,14]]]]]) = 22 (39) 22= 22 Type: Equation PositiveInteger (40) -> RS([['f','o','u','r'], ['f','i','v','e'], ['s','i','x']]) = 14 (40) 14= 14 Type: Equation PositiveInteger ``` [Answer] # APL(NARS), 24 chars, 48 bytes ``` {⍬≡⍵:0⋄×≡⍵:(≢⍵)++/∇¨⍵⋄0} ``` This would be the litteral traslation of 'my' Axiom answer here... In APL the void list would be ´⍬´ Zilde, that you indicate with ´[]´, ´⊂⍬´ is ´[[]]´, ´1 2 3´ is ´[1,2,3]´ ecc Some test: ``` RS←{⍬≡⍵:0⋄×≡⍵:(≢⍵)++/∇¨⍵⋄0} RS ⍬ 0 RS ⊂⍬ 1 RS 4 5 6 3 RS ("four")("five")("six") 14 RS ('f' 'o' 'u' 'r') ('f' 'i' 'v' 'e') ('s' 'i' 'x') 14 RS ("(((())))")("()()()()()")(")()((()))()(") 33 RS (⊂4 5 6) 4 RS (⊂("four")("five")("six")) 15 RS (⊂("(((())))")("()()()()()")(")()((()))()(") ) 34 RS (,4) (,5) (,6) 6 RS ⊂¨("four")("five")("six") 17 RS ⊂¨("(((())))")("()()()()()")(")()((()))()(") 36 RS ⊂⊂⊂⊂⊂⊂⊂⊂⍬ 8 RS ⍬⍬⍬⍬⍬⍬⍬⍬ 8 RS ⍬⍬(⊂⍬)(⊂(⊂(⊂⍬))) 8 RS 0(,¯1)(2.3 ¯4.3)(5 (,6))(7 (8 9 (10 11 (12 13 14)))) 22 ``` for print the other type of results the exercise propose we need one other function (both functions RS and Rs should be ok for the exercise) ``` Rs←{⍬≡⍵:0⋄(''≡0↑⍵)∨0=≡⍵:0⋄(≢⍵)++/∇¨⍵} Rs ("four")("five")("six") 3 Rs ("(((())))")("()()()()()")(")()((()))()(") 3 Rs (⊂("four")("five")("six")) 4 Rs (⊂("(((())))")("()()()()()")(")()((()))()(") ) 4 Rs ⊂¨("four")("five")("six") 6 Rs ⊂¨("(((())))")("()()()()()")(")()((()))()(") 6 Rs 0(,¯1)(2.3 ¯4.3)(5 (,6))(7 (8 9 (10 11 (12 13 14)))) 22 Rs ('f' 'o' 'u' 'r') ('f' 'i' 'v' 'e') ('s' 'i' 'x') 3 ``` for see how appear some input we use the o function: ``` o←⎕fmt o 0(,¯1)(2.3 ¯4.3)(5 (,6))(7 (8 9 (10 11 (12 13 14)))) ┌5─────────────────────────────────────────────────────────┐ │ ┌1──┐ ┌2────────┐ ┌2─────┐ ┌2──────────────────────────┐│ │0 │ ¯1│ │ 2.3 ¯4.3│ │ ┌1─┐│ │ ┌3──────────────────────┐││ │~ └~──┘ └~────────┘ │5 │ 6││ │7 │ ┌3────────────────┐│││ │ │~ └~─┘2 │~ │8 9 │ ┌3────────┐││││ │ └∊─────┘ │ │~ ~ │10 11 │ 12 13 14│││││ │ │ │ │~~ ~~ └~────────┘2│││ │ │ │ └∊────────────────┘3││ │ │ └∊──────────────────────┘4│ │ └∊──────────────────────────┘5 └∊─────────────────────────────────────────────────────────┘ ``` this print Zilde, and one 8 Zilde list: ``` o ⍬ ┌0─┐ │ 0│ └~─┘ o ⍬⍬⍬⍬⍬⍬⍬⍬ ┌8──────────────────────────────────────┐ │┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐ ┌0─┐│ ││ 0│ │ 0│ │ 0│ │ 0│ │ 0│ │ 0│ │ 0│ │ 0││ │└~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘ └~─┘2 └∊──────────────────────────────────────┘ ``` [Answer] # Java, 96 bytes ``` int c(Object[]a){int r=a.length;for(var i:a)r+=i instanceof Object[]?c((Object[])i):0;return r;} ``` [Try it online.](https://tio.run/##tVPJTsMwEL33K6ycEuFGcReWRhVfgDj0GPnguk5xSZ3KcQKo8reHKVBKTEFNKLal0SxvnmfsWbGK9VeLx5pnrCjQHZNq20OoMMxIjmqpDOL@/XwluEkoC7Y7g56yMBNqaR7iNNd@xTSSExboi6lEUgFUcZGnaI@65f5nhkAGkyjWwpRaIR3bOu4B26acZ8D2QVrlcoHWcBF/ZrRUy4QiIIYwhGYvhRHrMC9NuAGXyZTPfSWe9lwRDYL4pEhCWwTT7QiP8aU9Pd5L81J72EtlJUAU8tlrg05gUVgATeh@g7KTbx6QbRIeqaUr@lhlnXOdVmfnQi1u6GNH/2sTnHTvLXGNZ2qQm/ZLu1xXx@bBRBw9bcakMYr43zV79ps5gRb//Da/oGybB4@aHH3ikA7CIe6PwqH7mb/95abhqqle45umgUSYEMc0wGSIycgeCrA9W78C) **Explanation:** ``` int c(Object[]a){ // Recursive method with Object-array parameter and integer return-type int r=a.length; // Result-sum, starting at the size of the input-array for(var i:a) // Loop over the input-array: r+= // Increase the result-sum by: i instanceof Object[]? // If the current item is an array: c((Object[])i) // A recursive call with this item : // Else: 0; // 0 (so leave the result-sum the same) return r;} // Return the result-sum ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 21 bytes ``` {#_+Sum!$=>IsArray\_} ``` [Try it online!](https://tio.run/##jY/Pb4IwFIDv/BW18@bTUAF1JposnnZZlszb2wshWpTDlFAwW5b97awtgrqh8UH6fnylH43yPFptZRlPZ@X3Q9h7Kz463dn8WT1lWfT1Hv6UL1KuFXbTdLUh5zVLdvlSqnwRKakwBoYO04EEVUY6VlXrAwuAjWrK432RcWA8Tg7SZJV88gYims@JDECqH9OZwjKd@YWgMTQ/0O444XstfzSkrxqY5Z/KDCuZra7pLDwT2v6W8hhUxwUkaHvb9phpc845dwH7QrPhwIO@P/B0GYC9Ho4BJ/AIKFwQQqchCA@Eb49wiMpf "Attache – Try It Online") Turns out the [C# approach](https://codegolf.stackexchange.com/a/178770/31957) is pretty short in Attache. ## Alternatives **25 bytes** `f[x]:=#x+Sum!f=>IsArray\x` **26 bytes** `f[x]:=#x+Sum[f=>IsArray\x]` **35 bytes** `f:=Sum##{If[IsArray@_,1+f@_,1]}=>Id` **35 bytes** `f:=Sum@Map[{If[IsArray@_,1+f@_,1]}]` **37 bytes** `f[x]:=Sum[{If[IsArray@_,1+f@_,1]}=>x]` [Answer] **Clojure, ~~79~~ ~~77~~ 51 bytes** Input has to be a list, not vector. Both would be supported by using `sequential?`. ``` (defn f[i](if(seq? i)(apply +(count i)(map f i))0)) ``` Previous: ``` (defn f[i](if(seq? i)(if(some seq? i)(apply +(count i)(map f i))(count i))0)) ``` [Answer] # Python, 72 bytes ``` l=lambda a:0if len(a)==0else len(a)+sum(l(i)for i in a if type(i)==list) ``` ]
[Question] [ Given a positive integer as input, output the smallest positive integer such that appending its digits (in base 10) to the end of the input number will form a prime number. ## Examples ``` 1 --> 1 2 --> 3 8 --> 3 9 --> 7 11 --> 3 20 --> 11 43 --> 1 134 --> 11 3492 --> 11 3493 --> 9 65595 --> 19 ``` ## Rules and Scoring * This is code golf, so shortest code wins * Standard rules and loopholes apply * Use any convenient I/O format * The largest concatenated number (which is larger than both the input and output) your solution supports must be at least \$2^{53} - 1\$. (This is the largest odd integer that can be represented with double precision floats) * Leading zeros should not be added to numbers before appending them to the input number * Primality tests must be exact [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` 1ṭVẒɗ1# ``` [Try it online!](https://tio.run/##y0rNyan8/9/w4c61YQ93TTo53VD5v/XhdpVHTWvcgcI6RjoWOpY6hkCGgY6JsY6hsYmOsYmlEYgw1jEzNbU0BQA "Jelly – Try It Online") ## How it works ``` 1ṭVẒɗ1# - Main link. Takes n on the left ɗ - Define a dyad f(k, n) from the previous 3 links: ṭ - Tack; Yield [n, k] V - Eval; Smash together into a single integer Ẓ - Is prime? 1 1# - Starting from k = 1, find the first k such that f(k, n) is true ``` [Answer] # JavaScript (ES6), ~~51~~ 50 bytes *Saved 1 byte thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects the input number as a string. ``` f=(n,k)=>eval('for(d=x=n+k;x%--d;)d')<3?k:f(n,-~k) ``` [Try it online!](https://tio.run/##fc9BDoIwEAXQvafoxkwbrVgKasXqWQilREtaA4aw8uqVGI2kBmb75mf@3PIub4vmen9Q61TpvZbYrg2R57LLawzaNVjJXtqVyfolpSojCsiJX8xRD4v0aYgvnG1dXW5qV2GNgQEahhAURQixRaDxWHmoh1kVY92Hyt6Hp7Lx9qfsr1XCYaYz4wlMZ3kihqdmlH8ViVB3aSpS@GSFfwE "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes 05AB1E treating strings and integers equal helps again. ``` ∞.Δ«p ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTDq0u@P/f2MTSGAA "05AB1E – Try It Online") or [Try all cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/2/1HHPL1zUw6tLvgP5HFxlWdk5qQqFKUmpihk5nGl5HMpKBQUZeaVpCkoqZqmKOjaKSgpqABlFBT08wtK9CFmQSk0423AClPy81L/G3IZcVlwWXIZAhkGXCbGXIbGJlzGJpZGIMKYy8zU1NKUCwA) ``` ∞ # in the list of positive integers .Δ # find the first one « # that, when concatenated to the input, p # is a prime number ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ;.cṗ> ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w31ov@eHO6Xb//0cb6hjpWOhY6hgCGQY6JsY6hsYmOsYmlkYgwljHzNTU0jQWAA "Brachylog – Try It Online") `,.ṗ>` seems like it should work, but `,` seems to be somewhat bugged with unbound variables. [It's a bit hard to tell why](https://github.com/JCumin/Brachylog/blob/2efca3d804ee8a30c231bf5974d1e9d6dfae267c/src/transpile.pl#L482). ``` ;.c The input's concatenation with the output ṗ is a prime number > greater than the output. ``` Uses `>` rather than `∧` so as to force the output to be an integer--otherwise, it would be an empty list for prime inputs. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes Saved 1 byte thanks to Leo ``` ḟöṗr+⁰s1 ``` [Try it online!](https://tio.run/##ARsA5P9odXNr///huJ/DtuG5l3Ir4oGwczH///8iMiI "Husk – Try It Online") Explanation: ``` ḟöṗr+⁰s ḟ Find first number at least 1 1 such that s when it's converted to a string, +⁰ and appended to the input r and read as an integer, ṗ the result is prime ``` [Answer] # [R](https://www.r-project.org/), ~~64~~ ~~62~~ ~~61~~ 60 bytes ``` function(n){while(sum(!(x=n*10^nchar(+F)+F)%%1:x)>2)F=F+1;F} ``` [Try it online!](https://tio.run/##Zc5NCsIwEAXgvaeoSGFiKXTyo0ZJlzmGIMXQQo1QLRbEs8ekim1wGGbx8XhM54xyprfVvblasOT5qJv2DLf@AksYlF1jcbRVfeog08RvmuJ@ICUlWukMD/rlDCBZJWHyvPQXFwZoJMzL7k9kJFsv@C2aMrSYCYZmzuaZIMj4SFOGcTk@EAn7SSK9bISQwtMnI90b "R – Try It Online") *-1 byte thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)'s idea and then another one (in both versions).* ### [R](https://www.r-project.org/), ~~60~~ 59 bytes ``` function(n){while(sum(!(x=n*10^nchar(F)+F)%%1:x)>2)F=F+1;F} ``` [Try it online!](https://tio.run/##Zc5LCsIwEIDhvaeoSGFiKXTyUKOkyxxDkGJooUaoFgvi2WNSxTY4i1l8/AzTOaOc6W11b64WLHk@6qY9w62/wBIGZddYHG1VnzrQJNMkTXE/kJISrXSGB/1yBpCskjB5XvqNCwM0EuZl9ycykq0X/B6aGlrMBMNlzuZNEGR8pKlhXI4PRMJ@kkgvGyGk8PRppHsD "R – Try It Online") Slower version from [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen). Abuses the fact that `n*10^5` will never be prime (but checks it in the first iteration, that's why it's so slow). [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` É3º╩(\╝░ ``` [Run and debug it](https://staxlang.xyz/#p=9033a7ca285cbcb0&i=1%0A2%0A8%0A9%0A11%0A20%0A43%0A134%0A3492%0A3493%0A65595&m=2) ## Explanation ``` wi;i\$e|p! w while |p! end result is not prime, do: i push index ;i push input and index again \$ stringify e convert to int final index is implicitly output ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÈsiU j}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yHNpVSBqfWE&input=NjU1OTU) ``` ÈsiU j}a :Implicit input of integer U È :Function taking an integer as an argument s : Convert to string iU : Prepend U and convert back j : Is prime? } :End function a :Get the first integer >=0 that returns true ``` [Answer] # [Python 3](https://docs.python.org/3/), 82 bytes ``` def x(n,i=1):k=int(f"{n}{i}");return all(k%j for j in range(2,k))and i or x(n,i+1) ``` [Try it online!](https://tio.run/##HY7RCoMwDEXf9xVhMGhYHlar23T0S4YPgrpVJUrpxE389q6VcC@BnHvJ9HXvkZX3ddPCIpiMllj02rAT7XHlbTXbER@2cR/LUA2D6E8dtKOFDgyDrfjViIR6xIprMBAOe8tZoo/UTC5yPzOJp6SE7pSTDMuFUkVSpaTSPImm6JpleVZSwFSYW1AA5W4ypvISiwNMNr4WamkRM2rt0P8B "Python 3 – Try It Online") -30 bytes thanks to @Manish Kundu, @MarcMush and @ophact [Answer] # [J](http://jsoftware.com/), 22 bytes ``` >:@]^:(0 p:,&.":)^:_&1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7awcYuOsNAwUCqx01PSUrDTjrOLVDP9rcnGlJmfkKxgq2CqkKRhCOMZgjhEyxwLCMQdzLJFlDKGaDCFGGBkgG2hijCJpaGyCwjc2sYTaYgnjwzRABMxMTS1N/wMA "J – Try It Online") Increment counter `>:@]` while `^:_` original number catted with counter `,&.":` is not prime `0 p:`, with counter starting at 1 `&1`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` fP_s+z ``` [Test suite](http://pythtemp.herokuapp.com/?code=fP_s%2Bz&test_suite=1&test_suite_input=1%0A2%0A8%0A9%0A11%0A20%0A43%0A134%0A3492%0A3493%0A65595&debug=0) Fairly different approach to the existing Pyth answer. Explanation: ``` fP_s+z | Full code fP_s+zT | with implicit variables --------+----------------------------------- f | first positive integer T such that +zT | input and T concatenated s | as an integer P_ | is prime ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes ``` ->n,r=1{(2...x=([n,r]*'').to_i).any?{|c|x%c<1}?f[n,r+1]:r} ``` [Try it online!](https://tio.run/##FYlLCsIwFACv4kba6vPhy0eMGHuQEKQWAl1YS2ghJcnZY7sZZhi/fNbidLm8RvCaYs0QMejabGlPVdXg/HsPDXbj2sbUp3Dsn5Rbt/8z2YfPxRAwuIMC2uQKggNxAVwotoPDTUolLX67KaaQpoMzwebyBw "Ruby – Try It Online") [Answer] # [Lyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ≬?pæṅJṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%89%AC%3Fp%C3%A6%E1%B9%85J%E1%B9%85&inputs=10&header=&footer=) Uses magic. -1 thanks to @vyxal. [Answer] # [Julia 0.4](http://julialang.org/), 39 bytes with julia 0.4 for `isprime` and `parse` ``` >(x,n=1)=isprime(parse("$x$n"))?n:x>n+1 ``` [Try it online!](https://tio.run/##JY3BCgIxDETv@Yqw7KFFD3bbFSu0foh4WLBCZY1LW6F/X2vM4YVJmJnnZ41La17UPTklXcxbiq8gtiXlIIaxjjRIeaFz9bRTrYRcMjq8gsI@MCGvE9P@hVL8ObAwmk/adGpjJ6aG4zzbGW7weCcsGAk5GH6W3k9lJVHQefSiSAmB7u0L "Julia 0.4 – Try It Online") [Answer] # JavaScript, 65 bytes ``` f=(n,x=1)=>[...Array((i=n+x)-2)].every((_,e)=>i%(e+2))?x:f(n,x+1) ``` Feel like this is way too long for some reason. I'm not very good at primality testing, so that takes up the vast majority of my code. Basically checks if every number between 2 and `n+[x]` [the number with x appended at the end] yields a nonzero remainder when it divides `i` [`n+[x]`]. If so, return `x`, otherwise call `f` again. *-4 bytes thanks to @Arnauld.* *saved 2 more bytes by taking the input number as a string.* [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` W!P_s+z=+Z1;Z ``` [Try it online!](https://tio.run/##K6gsyfj/P1wxIL5Yu8pWO8rQOur/fzNTU0tTAA "Pyth – Try It Online") # Explanation ``` Z # Set to 0 by default z # Input, taken as a string =Z+Z1 # Increment Z by 1 and assign Z to it s+z # Concatenate z with and convert to integer W!P_ # While it is not prime ;Z # Print Z after the while loop finishes ``` *thanks Citty for -1 byte* [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes ``` (k=0;While[!PrimeQ[10^⌊Log10@++k+1⌋#+k]];k)& ``` Increasing k until n\*floor(10^(Log10(k)+1)+k) is prime [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyPb1sA6PCMzJzVaMaAoMzc1MNrQIO5RT5dPfrqhgYO2dra24aOebmXt7NhY62xNtf9ARXklCvoO6foO1YY6RjoWOpY6hkCGgY6JsY6hsYmOsYmlEYgw1jEzNbU0rf3/HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 80 bytes ``` f=lambda n,a=0:math.perm(p:=int(n+str(a)))**2%-~p<1and f(n,a+1)or-~a import math ``` [Try it online!](https://tio.run/##NU/hToQwDP7PUzQxhvVumBsD7yDOF1F/TNgCORnLmIlKuFdHNrFp2n7N1/ar/fbdaPjFunXV4kMO760EQ6U41YP03YNVbiC2Fr3xxBwn74hExMMhv89u9olJ04ImG//IcHTZTSb9YEfnIQyvXk1@AgGEUcgpXChUFFgAJwoF32peINxR4EWVx7j1HsuyKjFRX1Y1XrX7OI9@jjFsYHtifzsrTJpONVflAj99/czPRZNSiBXjKSZ6dOCpgt7AT2/JIC3ZvqFRIlL4P4d1ApsF1Zp4jMC68L1OZ79A9gzztMC8X3tRQkxvS4rrLw "Python 3.8 (pre-release) – Try It Online") Inputs \$n\$ as a string and returns the smallest positive integer that makes a prime when appended to \$n\$. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 53 bytes ``` .+ _;$&;_10** +`((.+;).+);(__+)\3+$ _$1;$($1$.2)* \G_ ``` [Try it online!](https://tio.run/##DcYxCoAwDAXQ/Z8jStJAMdZByQF6iUJ0cHBxEO9ffdN7zve6D@sD171nRTiNHjalBN2Zs7pkFecIlVaUEGROTEZ5loRWo3fDjBUb7M@EpcDK8gE "Retina – Try It Online") Link includes less slower test cases. Explanation: ``` .+ _;$&;_10** ``` Create a working area with the suffix in unary (initially 1), the input prefix, and the current resulting integer in unary (initially one more than ten times the input). ``` ((.+;).+);(__+)\3+$ ``` Match the suffix and prefix, the prefix, and a factor of the resulting integer. ``` _$1;$($1$.2)* ``` Increment the suffix, keeping the prefix, and calculate the new integer. `$1` actually contains the unary suffix as well as the prefix, but Retina's `*` operator only considers the numeric portion of the parameter. Additionally, the separator is included in the capture of the suffix, thus automatically incrementing it when its length is taken. ``` +` ``` Repeatedly increment the suffix until a prime number is found. ``` \G_ ``` Convert the suffix to decimal. [Answer] # [Perl 5](https://www.perl.org/), 54 bytes ``` sub{$i=pop;$n=1;$n++while(1x"$i$n")=~/^(11+?)\1+$/;$n} ``` [Try it online!](https://tio.run/##ZZDdTsIwGIbPdxWf41PWrILdmDpmg/chSoJ22ABrHSVAAA@5AC/RG5kdW5yLPVj6Pu9P0mmRL6JiucOUF6v1dI@Sa6UTzDizH9/fvMuF8NjWRYmZS/hn/8VjzB@RMfOxbyPHInFsEdK9h5KiIfxxklygORy8WS502TPuJU4eGA16PZQ9NNeMjNIq7TMyRHN0UpV7DtjzBIwCg2daq4BC2Kj7loop3DWKsZYZ3NidP0ODsLXLwkHbDwdx8I/YTlyCTkVuoyiObKhk0Fkt1IbCdG1go/L5yiH7c3G5s0/L9NpQFFstXo14s/8EJ0nt4kwZfoVpnSJn3ql5m9o0oFTcrSB8n77gd9StIjqXmYGyDOKjcWEEXTXvwhC6mbXslYJbjo0zWzwWPw "Perl 5 – Try It Online") # [Perl 5](https://www.perl.org/), 65 bytes A slightly different approach, but 11 bytes longer: ``` sub f{($i,$t)=@_;!$t||(grep"$i$t"%$_<1,2..$i.$t-1)?f($i,$t+1):$t} ``` [Try it online!](https://tio.run/##ZZDdToMwGIbPdxWf3WegsRLLj8ommfehhmSzLM0mraVkmm2nXoCX6I1gERTJetT3eX@SVguzTZqmqpdQ7H2UDC3N7vP5GdrDwV8boQlKtOQc8zvOwiBAGaC95HRRdOkLTmdoj02hjD8Bdx6AM@DwxHoVMogGdTtSKYObQXE@MsMrt/NvKI5GuzyKx34Up@EJcZ20BdOOXCdJmrhQy2BabdWOwbK2sFNmU03o/qf48u6eVuraMhRvWqyseHZ/gvm8d3GtbFb0GfpLAaXKSAfh6@MT/sqki2gjSwttGcTr4MICPLXxYAZe6Sx3ZUDascfSFY/NNw "Perl 5 – Try It Online") [Answer] # Python 2, 73 bytes ``` def f(n,x=1):k=int(n+`x`);return all(k%i for i in range(2,k))or-~f(n,x+1) ``` Takes input as a string (e.g. `f("65595")`) Thanks to `ovs` [Answer] # [Raku](http://raku.org/), 28 bytes ``` {first ($_~*).is-prime,1..*} ``` [Try it online!](https://tio.run/##FcbRCoMgAEDRX7mERIslmRoTVr8ie0gQFgvdS0T7dbe9HM62pOdY1p06MJUjxJTfNMJ/2ouMudtSXJerkrI9S37sVMIzzRwB4c@K8ErcFQM3HOqXHqNR2qCNG/5oRmudncsX "Perl 6 – Try It Online") ]
[Question] [ [Sandbox](https://codegolf.meta.stackexchange.com/a/18345/82007) # Background (not necessary for the challenge) A standard number theory result using the pigeonhole principle is the fact that given any natural number k, there is a Fibonacci number that is a multiple of k. We can see this by considering modular pairs (F(n-1) % k, F(n) % k), and noting that there are only a finite number of possibilities of the pairs, while there are infinitely many pairs, so by the pigeonhole principle, there are naturals n, m such that (F(m-1) % k, F(m) % k) = (F(n-1) % k, F(n) % k). But, this implies that F(m-2) % k = F(n-2) % k, and more generally, F(m-i) % k = F(n-i) % k. Notably, if m < n, F(0) % k = F(n-m) % k. But, F(0)=0, so this means that F(n-m) is a multiple of k. # Challenge You must provide a program that takes in a natural k as an input and return m, the smallest Fibonacci number that is a multiple of k. This program must be irreducible in the sense that one can't remove any bytes and maintain the same functionality. This challenge is a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), as your score will be the smallest Fibonacci multiple of (the number of bytes in your program + 1). To find your program's score, use this TIO link: [Try it online!](https://tio.run/##hVCxCsIwEN3zFUdBSOhicROyutnJXS71agNpGtIE6dfHtmqJg/imd49773HnptAN9pDSNER/dX64e@xBQuEMNgQfoSNPBWM3amHs0Rgaw0mrwWLT6HM0QTtDvBZHBjN0C7wGKaF6Cws8hegtVKuAc8OLqY09Om0I@MVHymwIpQS1jUs0wg7W@H22l1XgJqrFjF9m9cesGHNe28B/n2nI8vxboqyESOkJ) The lowest score for a valid response in each language wins! # Test Cases ``` 1: 1 2: 2 3: 3 4: 8 5: 5 6: 144 7: 21 8: 8 9: 144 10: 610 11: 55 12: 144 13: 13 14: 46368 15: 6765 16: 144 17: 34 18: 144 19: 2584 20: 832040 21: 21 22: 832040 23: 46368 24: 144 25: 75025 26: 10946 27: 14930352 28: 46368 29: 377 30: 1548008755920 31: 832040 32: 46368 33: 6765 34: 34 35: 102334155 36: 144 37: 4181 38: 2584 39: 317811 40: 832040 41: 6765 42: 46368 43: 701408733 44: 832040 45: 1548008755920 46: 46368 47: 987 48: 144 49: 225851433717 50: 2111485077978050 51: 14930352 52: 267914296 53: 196418 54: 14930352 55: 55 56: 46368 57: 14930352 58: 267914296 59: 591286729879 60: 1548008755920 61: 610 62: 832040 63: 46368 64: 4807526976 65: 9227465 66: 1548008755920 67: 72723460248141 68: 2584 69: 46368 70: 5358359254990966640871840 71: 190392490709135 72: 144 73: 24157817 74: 365435296162 75: 354224848179261915075 76: 2584 77: 102334155 78: 160500643816367088 79: 8944394323791464 80: 1548008755920 81: 16641027750620563662096 82: 1548008755920 83: 160500643816367088 84: 46368 85: 1134903170 86: 1725375039079340637797070384 87: 317811 88: 832040 89: 89 90: 1548008755920 91: 225851433717 92: 46368 93: 1548008755920 94: 4807526976 95: 2880067194370816120 96: 46368 97: 7778742049 98: 57602132235424755886206198685365216 99: 1548008755920 ``` You can use the TIO link above to generate more test cases if needed. **EDIT**: As there seems to be some confusion on the scoring, here is how to generate your score: Take the number of bytes in your function, add 1, and take the result of this addition, and find the smallest Fibonacci multiple of this result. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 33 bytes, score: 34 Expects a BigInt as input. ``` f=(n,x=0n,y=1n)=>y%n?f(n,y,x+y):y ``` [Try it online!](https://tio.run/##FctBCoMwEEbhvaf4NwWHpJJs2449i1gjFpkpKuJQevaY7h4Pvne3d2u/TJ/tKvoack5ciz84iDeOQtzaRZ6pPPOHM7pZTrrUAkaUOwQPxBD@5RzhWwG9yqrz0Mw6FoVCiapfPgE "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 33 bytes, score 34 ``` n=scan();while(T%%n)F={T=T+F}-F;T ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMydVI0RVNU/TzbY6xDZE261W18065L@xyX8A "R – Try It Online") I thought I was going to have to resort to a 54 byte solution for a score of 55 (and had fun making an irreducible one), but eventually found this 33 byte solution. When coerced to integers, `F` and `T` are initially worth 0 and 1; they go through the Fibonacci sequence until `T` is divisible by `n`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes, Score: 34 ``` ->$a {(1,1,*+*...*).first(*%%$a)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX9dOJVGhWsNQx1BHS1tLT09PS1MvLbOouERDS1VVJVGz9n9xYqWCHlBxWn6RgqGenqGBwX8A "Perl 6 – Try It Online") There's no specifically redundant parts, even if it would pretty easy to golf. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes score = 13 ``` ÆḞ 1Çḍ@¥1#ÆḞ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Md87gMD7c/3NHrcGipoTJY4P///4bGAA "Jelly – Try It Online") A full program that takes an integer and returns an integer. [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes; score 55 ``` def f(n): a,b=0,1 while b/n*n!=b:a,b=b,a+b return b ``` [Try it online!](https://tio.run/##JY1BDoIwEEXXzinGVVupSl2S4CU8AYVBJjFTMtaop68g2//y3p@/eUpyKX0aqDXGlIFGHK24BrDzsa19AHxP/CCMZznIvo3NukffVRFQKb9UMJZFPT2z8mwdAH2ox7UIs7JkNLc@KRm/hB8kdiWuCm6jMCZFRhbUTu5kgw91vdzvNpc9muP177IrPw "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), Score: 13 ``` @XvU}a@MgX+1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hQE1nWCsx&input=MTM) ## Explanation The shortest possible solution (below) for this is 9 bytes, which means we're looking for the lowest possible score greater than or equal to `f(10)=610`. ``` _©vU}a!gM ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X6l2VX1hIWdN&input=MTM) That gives a target length of 12 bytes as `f(13)=13`, which can easily be achieved with some ungolfing/code bowling, giving: ``` @XvU}a@MgX+1 :Implicit input of integer U @ :Left function, taking an integer X as argument XvU : Is X divisible by U? } :End function a :Starting at 0, pass each integer through the right function and return the first result that returns true when passed through the left function @ :Right function, taking an integer X as argument MgX+1 : X+1th Fibonacci number ``` ## Proofs Hopefully, showing that no one character can be removed should also suffice to show that 2 or more characters can't be removed. I'll try to add a few words of explanation to the rest of these tomorrow. ``` *{box-sizing:border-box;}html{background:#fff;}body{background:#fff;color:#000;margin:0 auto;padding:20px;max-width:600px;}p{font-family:Arial,Helvetica Neue,Helvetica,sans-serif;font-size:14px;line-height:20px;margin:0 0 15px;}p.link{background:#eff0f1;border-radius:3px 0 0 3px;display:inline-block;margin:0 0 10px;width:32px;}a{display:block;padding:4px;}svg{fill:#212121;height:24px;width:24px;vertical-align:middle;}svg.warning{fill:#b00020;}pre{background:#eff0f1;border-radius:0 3px 3px 0;display:inline-block;line-height:16px;margin:0 0 10px 2px;padding:8px;width:calc(100% - 34px);}code{font-family:Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,sans-serif;font-size:13px;}p>code{background:#eee;padding:1px 5px;} ``` ``` <p>Click the play icon next to each programme to test it. Note that all programmes will auto-run and some, highlighted in red with a circle, may freeze or crash the tab they're running in so proceed with cautiond.</p><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=WHZVfWFATWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>XvU}a@MgX+1</code></pre><p>Without the first <code>@</code> to open the left function the, now unmatched, closing <code>}</code> causes the programme to throw an error.</p><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QHZVfWFATWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@vU}a@MgX+1</code></pre><p>Removing the first <code>X</code> results in <code>U</code> being auto-inserted between the <code>@</code> and the <code>v</code> and, therefore, the left function instead testing whether <code>U</code> is divisible by itself, which, of course, it is. So, no matter the input, the programme will exit after the first iteration and always return <code>1</code>.</p><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFhVfWFATWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XU}a@MgX+1</code></pre><p>If the <code>v</code> is removed then the <code>X</code> is ignored and the left function now tests whether <code>U</code> is truthy, which, for all non-zero inputs, it always will be. So, as above, the programme will exit after the first iteration and always return <code>1</code>.</p><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2fWFATWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@Xv}a@MgX+1</code></pre><p>The default agrument for the <code>v</code> method when applied to an integer is <code>2</code> so, by checking if <code>X</code> is divisible by 2, this version will always return the first even Fibonacci number: <code>2</code>.<p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VWFATWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XvUa@MgX+1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1ATWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XvU}@MgX+1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hTWdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XvU}aMgX+1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hQGdYKzE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XvU}a@gX+1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hQE1YKzE&input=MTM" target="_blank"><svg class="warning" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M10,16.5L16,12L10,7.5V16.5Z"/></svg></a></p><pre><code>@XvU}a@MX+1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hQE1nKzE&input=MTM" target="_blank"><svg class="warning" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M10,16.5L16,12L10,7.5V16.5Z"/></svg></a></p><pre><code>@XvU}a@Mg+1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hQE1nWDE&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XvU}a@MgX1</code></pre><p class="link"><a href="https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFh2VX1hQE1nWCs&input=MTM" target="_blank"><svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Try it</title><path d="M8,5.14V19.14L19,12.14L8,5.14Z"/></svg></a></p><pre><code>@XvU}a@MgX+</code></pre> ``` --- ## Alternative, 12 bytes, score: 13 Unlike the original solution above, this one can't be golfed any further. ``` °õ!gM ævN ªß ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sPUhZ00g5nZOIKrf&input=MTM) [Answer] # [C++ (clang)](http://clang.llvm.org/), 54 bytes, score : 55 ``` int F(int m,int a=1,int b=1){return a%m?F(m,a+b,a):a;} ``` [Try it online!](https://tio.run/##HY7BDoMgEETvfMWmTaNEm5QeAdubX9HLirQlETSI6cH47RSYw7w9zGxGLctVTeg@8WycmrZRgzTzGrxG@4jGBejr7LbNjh0rHDpGd6/D5h3gxT772rbYDC1SjuKIpDTQuJqSnUDSe/ZQ/hjogIkECfdbYtPQEshaw8i5mrcAUuaEhBMAh@TpTDNoZvVylSiV39dMGmpGBTlI/AM "C++ (clang) – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 20 bytes, Score 21 ``` U;;O01I%!^;u.@|W$p+q ``` [Try it online!](https://tio.run/##Sy5Nyqz4/z/U2trfwNBTVTHOulTPoSZcpUC78P9/I0MA "Cubix – Try It Online") Maps onto the cube as follows ``` U ; ; O 0 1 I % ! ^ ; u . @ | W $ p + q . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=VTs7TzAxSSUhXjt1LkB8VyRwK3E=&input=MjA=&speed=10) Fairly basic, builds the sequence on the stack checking the % for each iteration until it is zero then outputs and exits. * `01I` seed the stack with start of the sequence and input. `11I` would also work. * `%!` take modulus of TOS and test for 0. Also start of the loop * `^;U;O!$@` if 0 pop TOS, u-Turn, pop TOS and output number, a couple of no affecting commands and halt * `;uq+p` otherwise, pop TOS, u-turn, push TOS to bottom (input), add TOS and pull BOS to top * `$W|W` some trickery to keep the score nice while keeping it irreducible. skip the next command(W), reflect back onto the W, change the lane up onto the beginning of the loop [Answer] # [C (clang)](http://clang.llvm.org/), 54 bytes, score 55 ``` f(n){int a=0,b=1;while(b%n){b+=a;a-=b;a=-a;}return b;} ``` [Try it online!](https://tio.run/##FcvBCoMwDADQXylCIaUtuMN2WJY/2SVVuwVcNoqyg/jttV4fvCEOM@ur1gzqNtHFMPUh0QX/b5knSLZx8sTIkRIyRca9TMta1CTc64dFwW35W@DMQj16L4/rDd2vNMnQ2fFu7PjULkjIIM61dgA "C (clang) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 8 (7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` ∞Åf.ΔIÖ ``` [Try it online](https://tio.run/##yy9OTMpM/f//Uce8w61peuemeB6e9v@/BQA) or [verify the first \$n\$ outputs](https://tio.run/##ASkA1v9vc2FiaWX/RU7CqT8iIOKGkiAiP//iiJ7DhWYuzpTCrsOW/30s/zEwMA). **Explanation:** ``` ∞ # Push an infinite list: [1,2,3,...] Åf # Get the n'th Fibonacci number for each value in this list .Δ # Leave the first value of this list which is truthy for: Ö # Is it divisible by I # The input # (after which this is output implicitly as result) ``` These are all the possible builtins after removing one or multiple characters of the program, none of which are able to have the same functionality as the full program above: ``` ∞ # Push an infinite list: [1,2,3,...] Åf # Get the `a`'th Fibonacci number f # Get the prime factors of the given number(s) `a` .Δ # Leave the first value of the given list `a` which is truthy for Δ # Repeat the inner code until the result no longer changes ÅΔ # Get the (0-based) index of the first element of list `a` which is truthy for Ö # Check if integer `a` is divisible by `b` I # Push the input .I # Get the `a`'th permutation of `b` Å # No-op . # No-op ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 71 bytes, score 144 ``` N =INPUT T =1 F F =(T =F + T) - F OUTPUT =T EQ(REMDR(T,N)) :F(F) END ``` [Try it online!](https://tio.run/##DcoxDoAgDAXQuZzijxB1wDiZdIMmDqKScgFnI4P3D7K94X1vveuztEYJvKWzqCEFeyMkYNspGKAOE8TQUbQPsCJeNsc9ZKtjco5WseJMTKE1P/8 "SNOBOL4 (CSNOBOL4) – Try It Online") This might also be the most golfed version of this program, which would be interesting; I also learned that inline assignment works... [Answer] # [Red](http://www.red-lang.org), 54 bytes, score 55 ``` func[n][a: 0 b: 1 until[t: a a: b(b: t + b)// n = 0]b] ``` [Try it online!](https://tio.run/##JchBCsIwEEDRfU/x6UoRaRW6MKCHcDvMIrEJFGQoYXr@GHD5Xs1re@dVdCihlcM@YioxMJMCNw7z7SseiPRMp57OhXSeJownsyZtNe85ejf3B7LXzRwxxutrpGCqw/8Ky9J@ "Red – Try It Online") In fact it doesn't work in Red console after removing the space in front of `n`: ``` >> f: func[n][a: 0 b: 1 until[t: a a: b(b: t + b)//n = 0]b] == func [n][a: 0 b: 1 until [t: a a: b (b: t + b) / /n = 0] b] >> f 55 *** Script Error: / does not allow refinement! for its value2 argument *** Where: / *** Stack: f ``` so I thiink it's a valid submission. I suppose there are some subtle differences in [Red](http://www.red-lang.org) for Win and Linux ## Alternative: # [Red](http://www.red-lang.org), 67 bytes, score 2584 ``` func[n][set[a b][0 1]until[set[t a]reduce[a b]zero?(b: t + b)% n]b] ``` [Try it online!](https://tio.run/##JcoxCsJAEEbhPqf4CQgRETSQIin0DrbDFLvZWQiEMUxmGy@/Smy/90xSfUkibvJUc9GZlGkXp4DIdMOdi/qyHuQIbJLKLEf9iL2fXZzguCCeT1COXE02CQ4F@hG02aIOUrTXR4v8W7j5W8Yw1C8 "Red – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), (12 bytes), score 13 ``` Ol`tb+tG\]wx ``` [Try it online!](https://tio.run/##y00syfn/3z8noSRJu8Q9Jra84v9/QxMA) ## Explanation ``` O % Push 0 l % Push 1 ` % Do...while. The stack contains F(k), F(k+1) tb+ % Duplicate, bubble up, add. The stack contains F(k+1), F(k+2) t % Duplicate G % Push input \ % Modulo ] % End. If top of the stack is nonzero the loop continues wx % Swap, delete. This leaves only the latest Fibonacci number % Implicitly display ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes, score 21 ``` ⊞υ¬υW⌊﹪υIθ⊞υΣ…⮌υ²I⊟υ ``` [Try it online!](https://tio.run/##NYwxDsIwDEV3TpHRkcrCwMKYuSiCE0SppURya0jiIk5vkkr88eu9F1MokQOpeqkJZDJ3biDW3k6flAkNzHnLq6ww8yLEg3ChNnjbPvOXnh1w30joEr/ggTuWij0zmYsdLV/y1uAQfQdknKpXPe/0Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ¬υ ``` Take the logical not of the predefined empty list and push that to the list. (Using a literal 1 would increase my score of course.) ``` W⌊﹪υIθ ``` Divide each member of the list by the input and repeat while the minimum remainder is nonzero. ``` ⊞υΣ…⮌υ² ``` Reverse the list, take the first (originally last) two elements (duplicates the single element in the first pass), take the sum, and push that to the list. ``` I⊟υ ``` Cast the last element of the list to string for implicit print. [Answer] # **C++, 60 bytes, score : 610** ``` long f(int m){long a=0,b=1;while(b%m){b+=a;a=b-a;}return b;} ``` If I had used `int` all the way, I would have had a score of `591286729879`! [Try it online!](https://tio.run/##XYtBCoMwFAX3OcXHUoi0gl0VjHHbZc/wE6MGTAwmaSni2dPUZXczw3vSuWqUMp20lXPsFbR68WFVaDoSvbYjWDTKO5QKfOhZmpfcBqptAFNuhyGvr4Lf2HvSs6LinLu4cGTIRYVsX1WIqwXB9nS8UFtawkYADmUZ5BIDtC0UD/1SEKYPCPQKmoKB1Ba67m/2jMFlbKD46UBNychO0r3@Ag "C++ (gcc) – Try It Online") [Answer] # APL(NARS), chars 44, bytes 88, score 89 ``` r←u w a←1⋄⎕ct←0⋄r←1x →0×⍳0=w∣r⋄r+←a⋄a←r-a⋄→2 ``` The above has the problem change the global variable ⎕ct, and not define the variable 'a' as local (so if there is one extern global variable name 'a' and a extern function use 'a' or ⎕ct even trhu some operation, that extern function could return the wrong result...). test: ``` (1..8),¨u¨1..8 1 1 2 2 3 3 4 8 5 5 6 144 7 21 8 8 u 70 5358359254990966640871840 u 89 89 u 7373 1895175617433302745829870137958720928499852361085393597796453313487 4796286293483889267053950822315526092023966574765828063258184 5381860131060934476214808351544411531275197835352771384243811 1374862903608742278191775434865737602577844700159135211456619 9731096037977185178018629433653291613989743478589685505639564 4857727724829027387848536067017682345714489064874396569806069 164055864141425 ``` I copy "r+←a⋄a←r-a" from <https://codegolf.stackexchange.com/a/196929/58988> [Answer] # [Ruby](https://www.ruby-lang.org/), 33 bytes, score 34 ``` ->n{a=b=1;a=b+b=a until b%n==0;b} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtE2ydbQGkhqJ9kmKpTmlWTmKCSp5tnaGlgn1f4vUEiLNjaJ/Q8A "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 28 bytes, score 377 ``` for(a=o=1;o%i;t=a,a+=o,o=t); ``` **Edit:** -2 bytes [Try it online!](https://tio.run/##BcFhCoAgDAbQ0wRKFtS/GDvMMIuF@IWOrr/ee@STkbu@tjScxZX3wy/0IAzeCJOSsSSZGQlskTyjDdSyVtwB0X8 "JavaScript (Node.js) – Try It Online") Input goes in `i`, output goes in `o` 😅 [Answer] # [C (gcc)](https://gcc.gnu.org/), 33 bytes, Score:34 Based off xibu's answer. ``` int F(m,a,b){m=a%m?F(m,a+b,a):a;} ``` [Try it online!](https://tio.run/##HYpBDoIwEEX3PcUE06STjkZcWtAdp3BTWtFJaDGIK8LZa8vbvPyf544v59KBoxt//gnNd/E8nd63xHGBTgWy1OMaWivDfZ@6J4tXa7YkShIsR4ViFZAZphlUeRlaqE1WA5dztta4B4XPnItBVdKD9I9YEVOnmGqqEY3YRPoD "C (gcc) – Try It Online") ]
[Question] [ Given a natural number \$n\$, return the \$n\$-th [cuban prime](https://en.wikipedia.org/wiki/Cuban_prime). ### Cuban Primes A cuban prime is a prime number of the form $$p = \frac{x^3-y^3}{x-y}$$ where \$y>0\$ and \$x = 1+y\$ or \$x = 2+y\$ ### Details * You may use 0 or 1 based indexing, whatever suits you best. * You can return the \$n\$-th prime given the index \$n\$ or the first \$n\$ primes in increasing order, or alternatively you can return an infinite list/generator that produces the primes in increasing order. ### Test cases The first few terms are following: ``` (#1-13) 7, 13, 19, 37, 61, 109, 127, 193, 271, 331, 397, 433, 547, (#14-24) 631, 769, 919, 1201, 1453, 1657, 1801, 1951, 2029, 2269, 2437, (#25-34) 2791, 3169, 3469, 3571, 3889, 4219, 4447, 4801, 5167, 5419, (#35-43) 6211, 7057, 7351, 8269, 9241, 10093, 10267, 11719, 12097, (#44-52) 12289, 13267, 13669, 13873, 16651, 18253, 19441, 19927, 20173 ``` More terms can be found on OEIS: They are split up in two sequences, depending on wheter \$x = 1+y \$ or \$x = 2+y\$: [A002407](https://oeis.org/A002407) and [A002648](https://oeis.org/A002648) [Answer] # [JavaScript (V8)](https://v8.dev/), 54 bytes A full program that prints cuban primes forever. ``` for(x=0;;){for(k=N=~(3/4*++x*x);N%++k;);~k||print(-N)} ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SKPC1sDaWrMaxMy29bOt0zDWN9HS1q7QqtC09lPV1s621rSuy66pKSjKzCvR0PXTrP3/HwA "JavaScript (V8) – Try It Online") *NB: Unless you have infinite paper in your printer, **do not attempt to run this in your browser console**, where `print()` may have a different meaning.* --- # JavaScript (ES6), ~~63 61 60~~ 59 bytes Returns the \$n\$-th cuban prime, 1-indexed. ``` f=(n,x)=>(p=k=>N%++k?p(k):n-=!~k)(N=~(3/4*x*x))?f(n,-~x):-N ``` [Try it online!](https://tio.run/##DcxBCoMwEEDRvaeYgoUZ07QUXdmO3sAzKFZLjUyClhIQvXqa3V88/tT9urVfPu6rxb6GEEZGuXjiCh0brpqzUqZ2aKgUzafDEDZ8YH4rMp95onqMXB@eSt2E0S4owHB/gMCTochjKEWwJQC9ldXOw3W2b2w7TDfZKdp0iwfaW0r28Ac "JavaScript (Node.js) – Try It Online") ### How? This is based on the fact that cuban primes are primes of the form: $$p\_n=\left\lfloor\frac{3n^2}{4}\right\rfloor+1,\;n\ge3$$ The above formula can be written as: $$p\_n=\begin{cases} \dfrac{3n^2+1}{4}\;\text{ if }n\text{ is odd}\\ \dfrac{3n^2+4}{4}\;\text{ if }n\text{ is even} \end{cases} $$ or for any \$y>0\$: $$p\_{2y+1}=\dfrac{3(2y+1)^2+1}{4}=3y^2+3y+1$$ $$p\_{2y+2}=\dfrac{3(2y+2)^2+4}{4}=3y^2+6y+4$$ which is \$\dfrac{x^3-y^3}{x-y}\$ for \$x=y+1\$ and \$x=y+2\$ respectively. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~12~~ 9 bytes Generates an infinite list. Saved 4 bytes with *Kevin Cruijssen's* [port of Arnaulds formula](https://codegolf.stackexchange.com/a/185568/47066). Saved another 3 bytes thanks to *Grimy* ``` ∞n3*4÷>ʒp ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8PGMtk8Pb7U5NKvj/HwA "05AB1E – Try It Online") **Explanation** ``` ∞ # on the list of infinite positive integers n3*4÷> # calculate (3*N^2)//4+1 for each ʒp # and filter to only keep primes ``` [Answer] # [R](https://www.r-project.org/), ~~75~~ 73 bytes ``` n=scan() while(F<n)F=F+any(!(((T<-T+1)*1:4-1)/3)^.5%%1)*all(T%%(3:T-1)) T ``` [Try it online!](https://tio.run/##K/qfZptWmpdckpmfp1Gho1CcnJiHENCs0Kz@n2cLEtTQ5CrPyMxJ1XCzydN0s3XTTsyr1FDU0NAIsdEN0TbU1DK0MtE11NQ31ozTM1VVBQok5uRohKiqahhbhQAlNLlC/tdypWkYGmj@BwA "R – Try It Online") -2 bytes by noticing that I can remove brackets if I use `*` instead of `&` (different precedence). Outputs the `n`th Cuban prime (1-indexed). It uses the fact (given in OEIS) that Cuban primes are of the form \$p=1+3n^2\$ or \$4p=1+3n^2\$ for some \$n\$, i.e. \$n=\sqrt{\frac{a\cdot p-1}{3}}\$ is an integer for \$a=1\$ or \$a=4\$. The trick is that no prime can be of the form \$2p=1+3n^2\$ or \$3p=1+3n^2\$ (\*), so we can save 2 bytes by checking the formula for \$a\in\{1, 2, 3, 4\}\$ (`1:4`) instead of \$a\in\{1, 4\}\$ (`c(1,4)`). Slightly ungolfed version of the code: ``` # F and T are implicitly initialized at 0 and 1 # F is number of Cuban primes found so far # T is number currently being tested for being a Cuban prime n = scan() # input while(F<n){ T = T+1 # increment T F = F + # increment F if (!all(((T*1:4-1)/3)^.5 %% 1) # there is an integer of the form sqrt(((T*a)-1)/3) & all(T%%(3:T-1))) # and T is prime (not divisible by any number between 2 and T-1) } T # output T ``` (\*) No prime can be of the form \$3p=1+3n^2\$, else \$1=3(p-n^2)\$ would be divisible by \$3\$. No prime other than \$p=2\$ (which isn't a Cuban prime) can of the form \$2p=1+3n^2\$: \$n\$ would need to be odd, i.e. \$n=2k+1\$. Expanding gives \$2p=4+12k(k+1)\$, hence \$p=2+6k(k+1)\$ and \$p\$ would be even. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), [66](https://tio.run/##y00syUjNTSzJTE78X2D7XyPN1lDbLSc/vyjaWDnOSN8kVs06z9bIOtNW2To8IzMnNTrTzkAnU9fWKT8/J9UhoCgzNzXQIc1BWzsv1jrNIU9T7T9QLK8kuiDa1Cg29v9/AA "(f=1+Floor[3#^2/4]&;n=2;i=#;While[i>0,i-=Boole@PrimeQ@f@++n];f@n)&") [65](https://tio.run/##y00syUjNTSzJTE78X2D7XyPN1lD7UU@XsXKckb7Jo55uNes8WyPrTFtl6/CMzJzU6Ew7A51MXVun/PycVIeAoszc1ECHNAdt7bxY6zSHPE21/0CxvJLogmhTo9jY//8B "(f=1+⌊3#^2/4⌋&;n=2;i=#;While[i>0,i-=Boole@PrimeQ@f@++n];f@n)&") [56 bytes](https://tio.run/##y00syUjNTSzJTE78X2D7XyPN1lD7UU@XsbK@ifKjnm41a7f8oug820xbA51MG2WdgKLM3NRAhzQHbe08NbVMbe1Y6zSHPE21/0CJvJLogmhTo9jY//8B) ``` (f=1+⌊3#/4#⌋&;For[n=i=0,i<#,PrimeQ@f@++n&&i++];f@n)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78X2D7XyPN1lD7UU@XsbK@ifKjnm41a7f8oug820xbA51MG2WdgKLM3NRAhzQHbe08NbVMbe1Y6zSHPE21/0CJvJLogmhTo9jY//8B) * [J42161217](https://codegolf.stackexchange.com/posts/comments/444852) **-1** by using `⌊ ⌋` instead of `Floor[ ]` * [attinat](https://codegolf.stackexchange.com/posts/comments/444860) + **-1** by using `⌊3#/4#⌋` instead of `⌊3#^2/4⌋` + **-8** for `For[n=i=0,i<#,PrimeQ@f@++n&&i++]` instead of `n=2;i=#;While[i>0,i-=Boole@PrimeQ@f@++n]` [Answer] # Java 8, ~~94~~ ~~88~~ ~~86~~ 84 bytes ``` v->{for(int i=3,n,x;;System.out.print(x<1?++n+" ":""))for(x=n=i*i++*3/4;~n%x--<0;);} ``` -6 bytes by using [the Java prime-checker of *@SaraJ*](https://codegolf.stackexchange.com/a/181611/52210), so make sure to upvote her! -2 bytes thanks to *@OlivierGrégoire*. Since the first number we check is `7`, we can drop the trailing `%n` from Sara's prime-checker, which is to terminate the loop for `n=1`. -2 bytes thanks to *@OlivierGrégoire* by porting *@Arnauld*'s answer. Outputs space-delimited indefinitely. [Try it online.](https://tio.run/##LY7BDoIwDIbvPEVDYrIxQA2eHOgTyIXEi/EwJ5ohFAKDYAi@Og7l0qZt/n5fJjrhZffXJHPRNHASCgcLQKFO64eQKcTzCNCV6g6SnOfWUW52o2VKo4VWEmJAiGDqvMPwKGti0qCiwEW35zx5Nzot/LLVflWbC@nD7ZExZDbYe9umdE70EUbKUYw5wXrHP7jqPS/ccMrHic@cqr3lhrPgfjKFUSWJNi@flysI@vdEXxJs83xRHKcv) **Explanation (of the old 86 bytes version):** *TODO: Update explanation* Uses the formula of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/185568/52210): \$p\_n=\left\lfloor\frac{3n^2}{4}\right\rfloor+1,\;n\ge3\$. ``` v->{ // Method with empty unused parameter and no return-type for(int i=3, // Loop-integer, starting at 3 n,x // Temp integers ; // Loop indefinitely: ; // After every iteration: System.out.print( // Print: n==x? // If `n` equals `x`, which means `n` is a prime: n+" " // Print `n` with a space delimiter : // Else: "")) // Print nothing for(n=i*i++*3/4+1, // Set `n` to `(3*i^2)//4+1 // (and increase `i` by 1 afterwards with `i++`) x=1; // Set `x` to 1 n%++x // Loop as long as `n` modulo `x+1` // (after we've first increased `x` by 1 with `++x`) >0;);} // is not 0 yet // (if `n` is equal to `x`, it means it's a prime) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 83 bytes ``` (t=1;While[Length[l=Select[Join@@Array[{(v=3#^2+1)+3#,v}&,t++],PrimeQ]]<#];Sort@l)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PE1tA6PCMzJzXaJzUvvSQjOsc2ODUnNbkk2is/M8/BwbGoKLEyulqjzNZYOc5I21BT21hZp6xWTadEWztWJ6AoMzc1MDbWRjnWOji/qMQhR1PtP1Awr0TBIT3a1Cj2/38A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ²×3:4‘ ÇẒ$#Ç ``` [Try it online!](https://tio.run/##AR4A4f9qZWxsef//wrLDlzM6NOKAmArDh@G6kiQjw4f//zU "Jelly – Try It Online") Based on [@Arnauld’s method](https://codegolf.stackexchange.com/a/185568/42248). Takes n on stdin and returns that many Cuban primes. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 83 bytes This solution will output the n-th Cuban prime with the added benefits of being fast and remembering all previous results in the symbol f. ``` (d:=1+3y(c=1+y)+3b c;e:=If[PrimeQ@d,n++;f@n=d];For[n=y=b=0,n<#,e;b=1-b;e,y++];f@#)& ``` [Try it online!](https://tio.run/##XcsxC8IwFATg3V8hFKQlEa3Fpc@HmQQ3FbeQIUmTNEOeULrk18c61ungu7uk59ElPUerS8BSDz22rMu1XSI3rDNbC67Hu5ePKSb3FAMnxsALwkHB7TNJwowGj5wuFXdgsN0bcDwzppZV1ezKcqRZvmOKFGQ4iJem4OT5pJSCzboUP/1Dv8KrV1C@ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 180 bytes ``` [S S S T S N _Push_2][S N S _Duplicate][N S S N _Create_Label_OUTER_LOOP][S N N _Discard_top_stack][S S S T N _Push_1][T S S S _Add][S N S _Duplicate][S N S _Duplicate][T S S N _Multiply][S S S T T N _Push_3][T S S N _Multiply][S S S T S S N _Push_4][T S T S _Integer_divide][S S S T N _Push_1][T S S S _Add][S S S T N _Push_1][S N S _Duplicate_1][N S S S N _Create_Label_INNER_LOOP][S N N _Discard_top_stack][S S S T N _Push_1][T S S S _Add][S N S _Duplicate][S N S _Duplicate][S T S S T T N _Copy_0-based_3rd][T S S T _Subtract][N T S T N _Jump_to_Label_PRINT_if_0][S T S S T S N _Copy_0-based_2nd][S N T _Swap_top_two][T S T T _Modulo][S N S _Duplicate][N T S S S N _Jump_to_Label_FALSE_if_0][N S N S N _Jump_to_Label_INNER_LOOP][N S S T N _Create_Label_PRINT][T N S T _Print_as_integer][S S S T S T S N _Push_10_(newline)][T N S S _Print_as_character][S N S _Duplicate][N S S S S N _Create_Label_FALSE][S N N _Discard_top_stack][S N N _Discard_top_stack][N S N N _Jump_to_Label_OUTER_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Outputs newline-delimited indefinitely. [Try it online](https://tio.run/##bU3RCoBACHueX7Ffiziot6Cgzzc3fYzj5tRtvsf5rPva9pVJEgw/QagPFPYAroRnZlVAC0Yn0v6/AEnbLYATfRDVNZE0xlsiS6gb4pzo3od/5gc) (with raw spaces, tabs, and new-lines only). **Explanation in pseudo-code:** Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/185595/52210), which also uses the formula from [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/185568/52210): \$p\_n=\left\lfloor\frac{3n^2}{4}\right\rfloor+1,\;n\ge3\$. ``` Integer i = 2 Start OUTER_LOOP: i = i + 1 Integer n = i*i*3//4+1 Integer x = 1 Start INNER_LOOP: x = x + 1 If(x == n): Call function PRINT If(n % x == 0): Go to next iteration of OUTER_LOOP Go to next iteration of INNER_LOOP function PRINT: Print integer n Print character '\n' Go to next iteration of OUTER_LOOP ``` [Answer] # [Python 3](https://docs.python.org/3/), [110](https://tio.run/##RcuxDsIgEADQ3a@4xQSwSVOqi4n@iNNpodLAHTkxwa/H1sX9vfwpT6axNS@cIBQnhTm@IKTMUsxuvqgKngUqBIKEWUVM9wmBzsNhNGSM7ftj9@A3FaU1BA8Yo6r75beWbQnS7JTtqtZIE9TroNstS1gHuVrUvL4Nhz8@Wd3aFw "g= ...") [108](https://tio.run/##RcuxDsIgEADQ3a@4xQSwSVOqi4n@iNNpodLAHTkxwa/H1sX9vfwpT6axNS@cIBQnhTm@IKTMUsxuvqgKngUqBIKEWUVM9wmBzsNhNGSM7ftj9@A3FaU1BA8Yo6r75beWbQnS7JTtqtZIE9TroNstS1gHuVrUvL4Nhz8@Wd3aFw "(x for x in map(lambda n:1+3*n**2//4,count()) if all(x%j for j in range(2,x))and x>1)") [102 bytes](https://tio.run/##RcuxDsIgEADQ3a@4xYTDJo1UFxO/xDigAl4DdwQxwa/H1sX9vfypT@Gpd18kAVVXqkh8AaUspepNOKsGXgo0IIZks4o23R4W@LTfTZq1NuN4GO7y5qoMIpAHG6Nq2/nX5rUVy8EpMzRE7JdcaLHsWlVhCauivzoavPb@BQ "Try it online!") Similar method to my [Mathematica answer](https://codegolf.stackexchange.com/a/185580/82115) (i.e. `isPrime(1+⌊¾n²⌋) else n++`) using [this golfed prime checker](https://codegolf.stackexchange.com/a/143305/82115) and returning an anonymous infinite generator ``` from itertools import* (x for x in map(lambda n:1+3*n**2//4,count(2)) if all(x%j for j in range(2,x))) ``` [Try it online!](https://tio.run/##RcuxDsIgEADQ3a@4xYTDJo1UFxO/xDigAl4DdwQxwa/H1sX9vfypT@Gpd18kAVVXqkh8AaUspepNOKsGXgo0IIZks4o23R4W@LTfTZq1NuN4GO7y5qoMIpAHG6Nq2/nX5rUVy8EpMzRE7JdcaLHsWlVhCauivzoavPb@BQ "Try it online!") * [mypetlion](https://codegolf.stackexchange.com/posts/comments/444863?noredirect=1) **-2** because arguably anonymous generators are more allowed than named ones * **-6** by starting `count` at 2 +1 so that the `and x>1` in the prime checker I borrowed is unnecessary -7 [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes Adapted from [Arnauld's formula](https://codegolf.stackexchange.com/a/185568/58974). 1-indexed. ``` @µXj}f@Ò(X²*¾ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLVYan1mQNIoWLIqvg&input=OA) 1 byte saved thanks to EmbodimentOfIgnorance. [Answer] # [Racket](https://racket-lang.org/), 124 bytes ``` (require math)(define(f n[i 3])(let([t(+(exact-floor(* 3/4 i i))1)][k(+ 1 i)])(if(prime? t)(if(= 0 n)t(f(- n 1)k))(f n k)))) ``` [Try it online!](https://tio.run/##JY7BCsJAEEN/JeAlYylaq0fxQ0oPi87q0HZblxH8@7rqKbzwCMnhOqivmzGkO/IfmPX5sqyYgj@EN42WlBGpM7S9cFRn56yo73D1Oo7znLlFuzvCYCKN9N3ACk2Bolvkkm3SC/wHZ@yRxBlZI6GRQeQ7jpIiK6ewIIK5HFKcDqX6AA "Racket – Try It Online") Returns the n-th cuban prime, 0-indexed. Uses the formula of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/185568/52210) [Answer] # [Python 3](https://docs.python.org/3/), 83 bytes prints the cuban primes forever. ``` P=k=1 while 1:P*=k*k;x=k;k+=1;P%k>0==((x/3)**.5%1)*((x/3+.25)**.5%1-.5)and print(k) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8A229aQqzwjMydVwdAqQMs2WyvbusI22zpb29bQOkA1287A1lZDo0LfWFNLS89U1VBTC8zT1jMyhYro6plqJualKBQUZeaVaGRr/v8PAA "Python 3 – Try It Online") Based on [this](https://codegolf.stackexchange.com/a/70027/64121) prime generator. For every prime it checks whether an integer y exists that fulfills the equation for either \$x = 1+y\$ or \$x=2+y\$. $$ p=\frac{(1+y)^3-y^3}{(1+y)-y} = 1 + 3y +3y^2 \Leftrightarrow y = -\frac{1}{2}\pm\sqrt{\frac{1}{4}+\frac{p-1}{3}}$$ $$ p=\frac{(2+y)^3-y^3}{(1+y)-y} = 4 + 6y +3y^2 \Leftrightarrow y = -1 \pm\sqrt{\frac{p-1}{3}}$$ As we only care whether \$y\$ has an integer solution, we can ignore the \$\pm\$ and \$-1\$. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 31 bytes *-2 bytes thanks to Grimy* ``` {grep &is-prime,1+|¾*$++²xx*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7vzq9KLVAQS2zWLegKDM3VcdQu@bQPi0Vbe1DmyoqtGr/FydWKqRpaEbHGRnEWv8HAA "Perl 6 – Try It Online") Anonymous code block that returns a lazy infinite list of Cuban primes. This uses [Arnauld's formula](https://codegolf.stackexchange.com/a/185568/76162) to generate possible cuban primes, then `&is-prime` to filter them. ### Explanation: ``` { } # Anonymous code block grep &is-prime, # Filter the primes from xx* # The infinite list ¾* # Of three quarters $++² # Of an increasing number squared 1+| # Add one by ORing with 1 ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 51 bytes Using [Arnauld's formula](https://codegolf.stackexchange.com/a/185568/9288). ``` n->a=0;for(i=1,n,until(isprime(p=3*a^2\4+1),a++));p ``` [Try it online!](https://tio.run/##DYsxCsMwDAC/IjJZsQxx2k5GeUkIeIiDIFWN677f1XLDcVdzk3DVUYCHhi3zksqnOeFISj/tcjv51ibv01V@zPlY96ePSNl7xGSfxQoMkeC1EFip3cQEYTMUp4g4/g "Pari/GP – Try It Online") [Answer] # APL(NARS), 98 chars, 196 bytes ``` r←h w;y;c;v r←c←y←0⋄→4 →3×⍳∼0πv←1+3×y×1+y+←1⋄r←v⋄→0×⍳w≤c+←1 →2×⍳∼0πv+←3×y+1⋄c+←1⋄r←v →2×⍳w>c ``` indented : ``` r←h w;y;c;v r←c←y←0⋄→4 →3×⍳∼0πv←1+3×y×1+y+←1⋄r←v⋄→0×⍳w≤c+←1 →2×⍳∼0πv+←3×y+1⋄c+←1⋄r←v →2×⍳w>c ``` test: ``` h ¨1..20 7 13 19 37 61 109 127 193 271 331 397 433 547 631 769 919 1201 1453 1657 1801 h 1000 25789873 h 10000 4765143511 ``` it is based on: if y in N, one possible Cuban Prime is ``` S1=1+3y(y+1) ``` the the next possible Cuban Prime will be ``` S2=3(y+1)+S1 ``` ]
[Question] [ Last challenge ([Pixel-art, episode 1: display Super Mario](https://codegolf.stackexchange.com/questions/39915/pixel-art-display-super-mario/)) was just a training... (and you completed it in amazing ways, thanks!) This time, you have to work a little bit more. You have to display all the first overworld map of Super Mario bros on NES, without enemies, and without Mario. Your program or function must display all the pixels of the following image OR produce an image file similar to it (BMP, PNG, or GIF). Your program must not access the internet in any way. The output can be zoomed if you want, and the pixels can be ASCII or HTML elements if you want, as long as they have the right color. Here's the model you have to follow: * The whole image: <https://i.stack.imgur.com/2kfVc.png> ![image](https://i.stack.imgur.com/2kfVc.png) * The tileset (if you need it): <http://img.ctrlv.in/img/14/10/19/5443f44c7eb78.png> ![tileset](https://i.stack.imgur.com/u3GdU.png) You can produce your own tileset, subset or superset of this one. You can use your tileset as a separate image file or include it in your code (for example, in base64). If it's separate, add its size in bytes to your score. * The map with coordinates: <http://goo.gl/c8xJIx> or <http://img.ctrlv.in/img/14/10/19/544373adc9f64.png> ![map](https://i.stack.imgur.com/wYWTx.png) * The colors: ``` Sky blue: #5C94FC Black: #000000 Pink: #FCBCB0 (for the blocks and the castle) Brown: #C84C0C (for the blocks and the castle) Orange: #FC9838 (for the "?" block) Light green: #80D010 (for bushes, mountains, flagpole, warp) Dark green: #00A800 (for bushes, mountains, flagpole, warp) White: #FCFCFC (clouds) Light blue: #3CBCFC (clouds) ``` Shortest answer wins. EDIT: There will be two score boards, one where scores are counted in bytes and one where they are counted in characters. Good luck! P.S: Here are some notes that could help you optimizing your program: * Clouds, bushes and mountains have a repeating pattern (every 48 columns) * Flying blocks are only present on lines 4 and 8 * Each tile or sprite of the map uses at most 4 colors (including blue or transparent, depending on how you see it) * Bushes are just "top of clouds" with a diferent color palette * Single, double and triple bushes/clouds can easily be formed using the same mini set of 16x16px pieces. This is also true for the single and triple mountains [Answer] # x86 Machine Code, 1729 1619 1468 1382 Bytes How it works: Tiles are generated by a combination of RLE compression, 2bit images, and procedural code. Once the tiles are generated in memory, the program then creates a matrix of tile indexes. This is first loaded with the repeating background. After that, the pipes, floating blocks, pyramids, and the flag pole are drawn procedurally. The pipes, hills, bushes, and pyramids can extend below the ground, but are covered up when the rock tiles get written next. Finally, the castle tile values are simply copied into the correct location. To generate the image file, the BMP header and palette is stored in the file as data, and is written first. The program then runs through the matrix, writing the appropriate row from the corresponding tile for each position. Usage: Run mario.com, it will generate "m.bmp", a standard BMP image file. The file is created as a hidden file, since that ended up being less bytes. [Download a ZIP file containing the source code and binary, plus output.](http://lags.leetcode.net/mario.zip) ![enter image description here](https://i.stack.imgur.com/3rGNF.png) Assembly code to generate the executable file: ``` org 100h code_start: ;xor cx,cx mov cx,12+14+256*3 mov dx,filename mov ah,0x3c int 21h mov bx,ax push ax ;mov dx,BITMAPFILEHEADER inc dx inc dx mov ah,0x40 int 21h mov di,tiles xor ax,ax mov ch,48 rep stosw cwd ; load the cloud sprite mov si,cloud call DrawSprite call DrawHill mov dx,14*256+12*16 PipeTileLoop: ;Pipe mov si,pipe0 call DrawSprite sub dh,2 jns PipeTileLoop mov dx,32+12*16 call DrawSprite mov dh,13 ;mov si,pipe2 call DrawSprite cwd xor ax,ax ; move to the tile array mov cl,6 MoveTileLoop: call MoveTile loop MoveTileLoop mov word [BITMAPFILEHEADER+5+2],0x607 ; bushes sub dl,3*16 mov cl,13 jnc MoveTileLoop mov dx,0x1004 mov si,ball call DrawSprite mov dl,0 call MoveTile xor bx,bx ; pole pole: mov word[bx+tiles+22*256+7],0x707 add bl,16; jnc pole mov word [BITMAPFILEHEADER+5+2],0x805 ; qbrick mov si,qbrick call DrawSprite call MoveTile mov byte[BITMAPFILEHEADER+5+3],4 mov al,1 ; bricks & castle call Clear mov al,23 call MoveTile ; black door mov dx,0x800+64 BrickLoop: xor dh,8 mov si,bricks call DrawSprite sub dl,dh jg BrickLoop cwd call MoveTile ; left window call MoveTile ; castle brick mov al,3 mov di,image+15*256+16 mov cl,16 rep stosb mov al,26 mov dl,16 call MoveTile ; reg brick ;mov dl,32 ;mov si,door call DrawSprite ;mov dl,32 call MoveTile ; door top mov dx,48 +8*256 ;mov si,cren call DrawSprite push si mov dh,0 call MoveTile ; crenulation 1 mov si,image+48+256 +4 mov di,image+48+256*9+4 mov bl,7 CrenLoop: mov cl,7 rep movsb mov dl,256-7 add si,dx add di,dx dec bx jnz CrenLoop mov dl,3*16 call MoveTile ; crenulation 2 pop si mov cl,3 jmp skip LastLoop: ;call MoveTile ; right window ; block ; rocks call DrawSprite skip: call MoveTile loop LastLoop xor ax,ax ; Begin drawing world using the tiles call Clear mov bl,48*4 BackgroundLoop: lea di,[bx+image+2*256] SmallHill: mov al,10 mov cl,5 HillRow0: stosb inc ax loop HillRow0 mov dword [di+256-4],10+11*256+256*256*14 mov byte [di+512-3],15 sub di,256-10 cmp di,image +256 ja SmallHill mov si,fluff ; draw clouds, bushes FluffDrawLoop: lodsw add ax,bx add ax,image xchg ax,di lodsb aam mov cl,ah ;call DrawFluff; mov ah,1 FluffLayer2: stosb inc ax push cx rep stosb inc ax stosb pop cx add di,256-2 sub di,cx inc ax dec ah jns FluffLayer2 cmp si,pa jl FluffDrawLoop sub bl,48 jnc BackgroundLoop ;mov si,pa mov cl,6 PipePlace: lodsw xchg bx,ax mov di,image mov word [bx+di],18+19*256 PipeLoop: dec bh mov word[bx+di],16+17*256 jnz PipeLoop loop PipePlace ;mov si,dba ; draw the various floating blocks mov cl,4 DrawBlockLoop: lodsw xchg ax,bx mov ah,bl cwd lodsb BlockLoop: mov bl,al mov byte [bx+di],ah lodsb cmp al,dh mov dh,al ja BlockLoop dec si loop DrawBlockLoop mov bx,198+256*12 FlagPole: ; Draw flag pole mov byte [bx+di],22 dec bh jg FlagPole inc si ;mov si,pyr ; pyramid blocks mov cl,8 PyrMainLoop: lodsw shr ah,1 cwd inc dx jnc NoNeg neg dx NoNeg: mov bx,ax PyrDrawLoop: mov byte [bx+di],32 dec bh jnz PyrDrawLoop add ax,dx dec ah jnz NoNeg loop PyrMainLoop ;mov si,ground ; ground blocks ;mov di,image mov bl,4 push di GroundLoop: lodsb xchg ax,cx mov al,33 rep stosb lodsb add di,ax dec bx jnz GroundLoop push si inc ch mov si,di sub si,cx rep movsb pop si pop di ;push di ;mov si,copy ; Draw Castle, flag ball mov dl,6 CopyLoop: lodsw mov cx,ax shr cx,12 and ah,15 xchg bx,ax CopyRun: lodsb mov [bx+di],al inc bx loop CopyRun dec dx jnz CopyLoop; xor ax,ax xor bx,bx ; image y ; write the image to file pop dx WriteTileStep: WriteRowStep: mov bl,0 ; image x WriteStep: pusha mov ah,[bx+di] mov bx,dx add ax,tiles xchg ax,dx mov cl,16 mov ah,0x40 int 21h popa inc bx cmp bl,212 jb WriteStep add al,16 jnz WriteRowStep inc bh cmp bh,14 jl WriteTileStep ;pop bx ;mov ah,0x3e ;int 21h ;ret DrawSprite: ; dx=x,y, si=data pusha mov bp,dx ;cwd mov di,temp push di lodsw ; w, h*2+flag mov dl,al shr ah,1 pushf mul ah xchg bx,ax popf jc BitMapped RunLoop: lodsb mov cl,al shr cx,2 sub bx,cx rep stosb jnz RunLoop jmp MoveData BitMapped: BitMappedLoop: lodsb mov cl,4 BitMappedQuad: stosb shr ax,2 loop BitMappedQuad sub bx,4 jg BitMappedLoop MoveData: mov bx,sp mov [bx+4],si pop si mov bx,di lea di,[bp+image] mov dh,-1 MoveLoop: mov cl,dl rep movsb sub di,dx cmp si,bx jl MoveLoop popa ret MoveTile: ; dx =x,y, bx=y,ax=t-1 inc ax pusha mov si,dx xchg al,ah xchg di,ax mov ax,16 TileLoop: mov cl,16 TileTrans: mov bx,[si+image] inc si and bx,3 mov bl,[bx+BITMAPFILEHEADER+5] mov [di+tiles],bl inc di loop TileTrans add si,256-16 dec ax jnz TileLoop popa add dl,16 ret Clear: ; al = value mov di,image mov ch,48 rep stosb ret; DrawHill: pusha xor bx,bx mov al,3 HillLoop: lea di,[bx+image+6*16] inc byte [di] inc di mov cl,16*5-2 sub cl,bl sub cl,bl rep stosb inc byte [di] inc bx inc bh cmp bl,16 jl HillLoop mov si,spot push si mov dx,32-7+256*8 + 6*16 call DrawSprite mov dl,32+17 + 6*16 pop si call DrawSprite mov dx,5*16 + 6*16 call DrawSprite popa ret filename: db 'm','.' BITMAPFILEHEADER: db 66,77,'P',0,12,0,1,2,3,0,26,3,0,0 BITMAPCOREHEADER: db 12,0,0,0,64,13,224,0,1,0,8,0 colors: db 252,148,92,0,0,0,252,252,252,252,188,60,176,188,252,12,76,200,0,168,0,16,208,128,56,152,252 ;pal: db 0,1,2,3 cloud: db 88,32,224,5,114,5,228,5,122,5,224,5,122,5,228,9,106,5,6,5,240,102,5,4,5,240,5,86,5,10,5,252,5,78,5,4,5,6,5,252,4,13,66,5,8,5,92,13,16,17,136,5,14,7,42,5,100,9,14,5,4,9,18,9,4,9,120,5,14,11,14,7,18,5,96,5,26,5,34,5,10,9,116,5,26,7,22,5,84,13,18,11,18,15,34,9,108,5,38,5,6,5,84,5,22,27,6,23,38,108,5,34,5,4,5,88,5,10,19,14,19,18,7,34,5,108,9,26,5,92,5,10,7,10,7,26,7,54,5,120,5,18,5,92,5,10,7,46,7,46,5,128,17,56 spot: db 6,17,245,95,255,245,93,87,127,245,87,127,245,223 hilltop: db 16,3*2,0x9, 0x33, 0x9, 0x8, 0xD, 0x1B, 0xD, 0x1C, 0x19, 0x14 ball: db 8,17,80,5,244,31,253,127,253,127,249,127,249,127,228,31,80,5 pipe0: db 64,5,0x90,0xFA,0xAA,0xAE,0xFF,0xFF,0xBB,0x06,0xA9,0xAF,0xAA,0xEB,0xFF,0xFF,0xBB,0x6B,0x90,0xFA,0xAA,0xAE,0xFF,0xFF,0xAE,0x06,0xA9,0xAF,0xAA,0xEB,0xFF,0xFF,0xEF,0x6A pipe1:db 32,4,8,113,8,129 pipe2:db 32,12,5,23,26,79,9,122,133 qbrick: db 16,33,85,85,85,85,254,255,255,127,222,255,245,119,254,191,246,127,254,191,254,127,254,255,245,127,254,191,246,127,254,191,86,127,254,215,106,127,254,218,107,127,254,218,107,127,254,90,233,127,254,171,250,127,222,255,255,119,254,255,255,127,168,170,170,42 bricks: db 8,16,33,14,5,30,5,30,5,18,33,30,5,30,5,30,5 door: db 16,32,0xFD, 0xFD, 0x89, 0x6, 0x39, 0xA, 0x39, 0x6, 0x41, 0xA, 0x31, 0x6, 0x5, 0xE, 0x29, 0xA, 0x5, 0x16, 0x19, 0x12, 0x5 cren: db 16,17,213,255,255,85,234,0,192,170,234,0,192,170,234,0,192,170,234,0,192,170,234,0,192,170,234,0,192,170,255,0,192,255 block: db 16,32,61,6,7,53,6,5,11,45,6,9,15,37,6,13,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,19,34,17,15,6,35,17,11,6,43,13,7,6,51,9,6,59,5 rocks: db 16,33,86,149,87,149,171,106,171,90,171,127,171,106,251,85,171,106,95,170,173,106,165,170,173,106,171,170,182,106,171,170,182,106,171,170,182,106,171,170,246,127,171,170,102,149,171,170,118,106,171,170,182,106,171,170,182,106,171,170,182,106,254,255,231,191 fluff: db 8,10,11, 19,11,11, 27,10,31, 36,11,21, 11,1,34, 23,1,14, 41,1,24 pa: db 28,3,38,4,46,5,57,5,163,3,179,3 dba:db 21,5 qb: db 16,21,23,78,106,109,112,170, 21,9 qb2: db 22,94,109,129,130, 27,5 ba: db 20,22,24,77,79,94,100,101,118,129,130,168,169,171 , 27,9 ba2: db 80,81,82,83,84,85,86,87,91,92,93,121,122,123,128,131,0 pyr: db 137,5*2+1,140,5*2,151,5*2+1,152,5*2+1,155,5*2,188,9*2+1,189,9*2+1,198,4 ground: db 69,2,86-69-2,3,153-86-3,2,256-153-2,0 copy: db 202,2+5*16,26,26,24,26,26, 202,3+5*16,26,26,28,26,26, 202,4+5*16,29,30,30,30,29, 203,5+3*16,31,26,25, 203,6+3*16,29,29,29, 198,12+16,20 temp: rb 256*48 tiles: rb 34*16*16 image: ``` [Answer] # Javascript minified (\*): 1285 1258 1253 1205 1186 1171 characters (\*) Minified using Closure, RegPack and ObfuscaTweet, as suggested by xem Unicode version is 4549 bytes in size, without ObfuscaTweet (Closure and Regpack only), size is 2251 bytes. History: 1285 -> 1258: variable `A` for 48 (thx @hsl), merged some of the `for` loops, merged `mt()` and `mu()`, using tile indices instead of tile strings, optimized png with [PNGOUT](http://advsys.net/ken/utils.htm) 1258 -> 1253: merged some more `for` loops; renamed `mt()` to `r()`; removed unnecessary braces; variable `B` for 16; defining 16 unused CSS sprites (replaces 32 with `A`); showing 1 unused row (replaces 14 with `B`); removed function `e()`; shortened `t()`, `g()`, `c()`; using `for(i=0;i<n;)f(i++)` instead of `for(i=0;i<n;i++)f(i)` where possible 1253 -> 1205: moved body style to CSS part instead of `<body style=...>`; replaced some `for` loops with `f` calls; optimized functions `r`,`q`; `</head><body>` seems to be unnecessary, `<html><head>` too; function `t(i)` for CSS mapping removed; CSS names `b0`..`b31` instead of `a`..`z`,`aa`..`ff` 1205 -> 1186: function `n` renamed to `N`; new function `n` that operates on an array with delta coding 1186 -> 1171: hills and warps can be drawn "big" anytime, the lower parts get overdrawn by stone blocks; use `d` for both clouds and bushes; removed some unnecessary semicolons This is a procedural attempt. There are patterns everywhere, one of the magic numbers is 48 (tile gap between clouds, bushes and mountains). The tileset is encoded as Base64 data url string and used as a CSS stylesheet. In Javascript, the 212x14 array `m` is filled with tile indices. See the commented unminified version for more details. Works in Chrome 38 (Ctrl+T for new tab, Ctrl+Shift+J for javascript console, paste code there) and Firefox 33 (if wrapped with HTML javascript tags). There's a [JS bin version](http://jsbin.com/bafabaneja/edit), too. There's still some room for optimizations, I'll post updates and it would be nice if some JS/CSS/HTML people could suggest optimizations/corrections. Minified: ``` eval(unescape(escape('𩡯𬠨𧰽𙰠𨱬𨑳𬰽𠁹𚰫𚡗𚱸𙠩𞰣𘱦𘐽𜀻𨁦𫱲𚁟𘱟𪑠𧠣𫠨𦰟𛀴𗠩𮰝𝐳𗀬𝰛𚁡𖡦𭑮𨱴𪑯𫠠𖐨𜠘𘱧𖀗𖠬𨠖𛁥𕐮𭁯𤱴𬡩𫡧𚀔𚀱𔰣𬠓𞀒𘱎𔐚𚰐𮱢𨑣𪱧𬡯𭑮𩀏𛀳𓠞𚐬𩀌𭰨𘠼𒰬𜀣𒐫𚰩𒀟𨐫𜠱𑱁𠑁𠐆𚱩𚡁𑐬𜐄𕠕𗐃𛀲𐠩𯐙𐑗🐲𜐲𞱁🐴𞀻𠠽𜐶𞱭👛𧐻𖑷𖠝𩁯𨱵𫑥𫡴𛡷𬡩𭁥𖠁𣠖𗑭𦱡𧐽𘡢𘠫𨠔𐑮𕠝𮡠𧰤𘁩𫠠𨐩𮠫👡𦰤𧐬𣠨𮠬𨠁𩠃𧱫👡𞱫🀽𨐫𨠻𚑎𚁫𚰫𕐁𩰃𧱸👡𙑗𞱸🀽𨠥𥰻𮀈𧱹👡𛱗𯀰𞱹🁢𛱗𯀰𞰩𣠨𙠕𐑣𐱎𖠕𘐐𜐬𨠭𜐕𚰱𔐐𨠫𜐕𚰲𐑤𐱣𕠕𘱣𔁗𛁢𕐫𜐶𐑰𖠝𣠐𜠬𞀇𜰂𜐱𧐂𜰇𝀂𜐱𐡝𐠴𑰵𐠱𜱝𐠵𔐐𝀲𝠬𞐁𬐚𗑎𖠄𜀑𔀱𑀱𘱬𔁗𓠂𝠣𫀐𜠱𜰎𐠷𐑲𕠝𧱪𨀴🡪𞱪𒁦𔁢𚠨𜰭𪠩𚱪𚡗𛁪𛀰𐑬𐱟𪱠𪰼𨠻𪰈𣠐𪰪𥰕𚑽𩠨𜀂𞐶𝰛𧠴🡩𞱩𒁤𖀳𜐅𑀌𖀴𞀅𐠌𚀴𝐱𑐎𓀨𝀳𜠅𑀌𖀳𝀳𑐎𑀷𚐬𩀘𜰵𝐅𑀄𝰩𛁤𖀳𝰳𑐂𑀷𘱤𚀶𜠴𑀞𔐘𗀹𑀹𗰸𝰰𖰲𑀵𐠰𑀛𜰴𛀵𐠬𝐵𐠸𓠎𛀵𞁝𓠡𚀹𜠸𖰂𘐨𞐳𞐂𐠡𚀹𝠹𐠂𗰹𝰶𓠛𜰷𐠂𛀜𐠄𝐬𝠄𞀄𜐄𓠸𑀂𧐂𔐓𞐰𜀬𠠗𜰲𜠂𗀵𛁂𕰳𜠵𐠜𞀬𠠡𔰶𞀷𐠄𜰑𔰸𞐹𐠹𔐓𞐰𜐎𜐡𖀱𜐰𗠄𜰡𖀱𜐱𐠄𝐑𖀳𜠴𑀴𔐘𗀶𓠰𧠵🡩𞱩𒁰𔰹𜀸𑐩𛁰𖀱𜰵𑐣𬐓𝰴𜠣𬐓𝰜𘱱𔰹𝀶𘱱𖀱𝀸𘱱𖀲𞀳𘱱𖀲𞐹𔠳𜀄𔠴𝀄𔠷𝰄𘱲𔰰𜰳𑀒𜰶𒑲𔰸𝐱𒑧𔰸𞀱𐠵𜠰𒑬𔰰𜰷𗠉𫀓𞀴𞀞𒑬𔰸𞀵𗠉𣠨𝀱𜀄𜠣𫀨𝠲𜠬𞐂𞀑𖀜𜀉𩠘𝐴𝀞𜠳𑀗𝠱𜰂𞀲𝠛𕰶𜰰𐠸𝀴𖰗𝠹𝰂𞐱𜀛𘰋𬱴𮑬𩐾𨡯𩁹𮱷𪑤𭁨𞠳𝀰𜁰𮁽𩁩𭠏𞡵𬡬𚁤𨑴𨐺𪑭𨑧𩐯𬁮𩰻𨡡𬱥𝠴𛁩𥡂𣱒𭰰𢱇𩱯𑡎𤱕𪁅𥑧𠑁𠑑𑡁𩱂𠑍𑡐𪀷𭡘𑡇𜑂𣑖𡑖𨱬𤁷𑡁𬑁𡁉𥁁𮑁𜁂𡀸𛱐𮠸𭡌𡀸𫑄𩰸𭡐𮑑𥱌𣁕𠑁𠑃𭱫𫁅𤑖𤠴𦁲𥱗𤰴𬡪𣑂𠱇𦁣𮁪𬡦𢱪𩐲𜱨𠐴𭱒𢡎𭁊𞁁𡑭𪐴𢡳𥁕𡀷𬁨𩀹𩱫𠱏𤁓𥱎𝑏𪑒𭁴𬱸𞁸𡱊𜡃𢱰𪠹𞑓𢡣𥡏𥰸𨡤𭠫𫑩𢁤𚱕𝑖𩡸𤡡𤑄𡐯𮐶𜑪𮠹𜑆𬑰𢁲𡡓𤁢𛱲𡡒𨱴𦁅𥰸𢱆𝠶𞁅𜰱𨠫𭰯𣁇𚱂𠑏𢑘𠡏𫱨𝁵𡁘𜑣𝁉𫑃𣁉𥡆𮁣𫑡𡑋𨡓𣑙𨰴𡡘𥱺𞁑𠑃𢱸𣁆𠡋𮑑𣁓𜀲𦑃𨑁𪱅𨡁𤐴𠱡𠡪𛰯𡱵𥡊𩱁𣡅𤱮𬡹𤡧𠡌𬑪𦡌𬑵𮑸𢡁𪀹𬡸𞑇𢑅𭁇𢱣𭱋𪀶𫠸𢀫𤐲𡰱𡁷𤑡𦑧𡡙𢡓𠱐𚱓𤁯𜁖𢱚𚱈𪱫𠑪𜑗𩱣𡁲𩐵𞁉𥑃𣰲𢡌𠑳𫱐𥐴𢠳𡁭𡁌𦑭𩱉𝑍𢑎𞁄𨠶𞁱𡑁𠐶𦀫𫁋𬀲𨱔𭱂𩡎𝁉𤰯𡁧𤱹𦐯𪡥𝀱𜡧𝁥𬠰𤡁𣀫𚱐𬡶𤡙𩐯𫡨𩑙𥁧𡑧𣱑𤱳𥁑𠱏𥑩𭱌𥱋𥑘𡡔𨱩𫡁𤑡𞁯𪁇𬡅𮑧𣡴𜑧𥱕𠑪𠱷𤱇𢡯𡰹𡡷𠱡𣱊𡡙𫁙𠑘𭱅𞁯𞑉𪁍𪡸𩡢𪡉𢐫𡑄𝡃𢁸𤑧𮁌𫱅𤱩𭡧𬰰𥱈𭡹𝀰𡱩𫱵𬡳𩁉𩱆𬱸𭑬𦑍𡁑𥱣𪱯𜁉𪑇𢑭𩱓𥱂𡑓𜀹𡡺𩁪𥱧𪀯𪡂𬑋𪑁𦁑𡡍𠱚𦀰𣱑𥑳𭱉𭑏𭑱𝑺𢁹𭱉𤑬𠑘𤠱𬁡𤁉𤀲𝑮𛱉𤡰𩀰𨑚𪑩𤡫𪑧𪁘𤑖𬁡𣱤𜠰𮠫𠐴𠡉𜱷𚰲𛱘𠡺𡁂𜱈𬱫𥑐𤁮𦑰𫱺𡱣𝐵𠑋𥑌𫱇𭱦𠱈𥁤𥑷𣁉𫑹𪑌𝁇𫱕𬡬𪱃𢑌𜡁𡡅𞁭𩱉𝐷𬱙𡑒𢑯𜱧𩁱𦁢𪡒𜱩𠱍𬐷𤑄𭑦𠑈𝱃𭁄𭁪𩱣𣑨𡑓𠑵𩡺𭑺𠑶𣑮𜡷𡑬𬱯𫑙𥁓𠐸𠑥𡡊𩑃𮡑𬁑𞁂𪱁𜰴𦡑𣑑𨑑𠡴𜡚𬀵𢡯𡑖𠑪𨡃𫱸𢁉𣑪𩱒𜁷𥀱𤑘𫱂𨑒𡁐𢡊𡁴𠑗𠠷𢡨𣱁𪁧𤑓𢑑𤑌𦡓𮡑𬡴𞁄𩑒𛱁𩑶𫰯𫡓𩱁𬁮𛱍𤑓𨑉𝱘𜁁𠡳𞁂𜡈𝡥𥑩𨐰𜠯𭁁𤁕𮡕𤱷𢑧𣐸𥁭𤁪𠑅𢁇𠡤𠑅𮐷𭁑𛱧𡑆𢱌𩁑𡑷𦑬𬱦𩱃𡡇𬡁𭑁𨑚𣑅𛱱𣑁𮑉𩑉𨡘𜡧𪡧𤑏𨑷𣡧𜡲𥠷𝁃𞑋𤐫𮁹𣡄𤑯𬱷𑡂𢡒𥐵𡑲𪱊𩱧𩰽🐩𯐢𧡩🁁𞱩𒁪👩𙑂𚠭𠠬𪰽𜐵🁩🰭𠠺𜀬𭰨𘠮𨠢𚱩𕀩𚰢𓰭𬁯𬱩𭁩𫱮𞠢𚱪𚰢𬁸𘀢𚱫𚰢𬁸𞱷𪑤𭁨𞠱𝡰𮀻𪁥𪑧𪁴𞠱𝡰𮀻𩡬𫱡𭀺𫁥𩡴𞱽𘠣𒰯𬱴𮑬𩐾𘠣𧱸𨁸🁗𞱸𒁻𒱳𬁡𫡀𨠰🠢𘱟𮑠𮐼𠠻𚐋𩁩𭡀𘠫𫑛𙡝𚰢🠼𛱤𪑶🠢𘰋𛱳𬁡𫠾𘠩𯐻𙰻𩰽𛱛𐐭𗱞𛑠𘐣𙡀𧐯𛡥𮁥𨰨𧰩𞰩𭱩𭁨𚁟𛡳𬁬𪑴𚁧𚐩𧰽𪡯𪑮𚁳𪁩𩡴𚀩𚐻𩑶𨑬𚁟𚐠').replace(/uD./g,''))) ``` Unminified and commented: ``` // map width W=212; // helper constants A=48;B=16; // array containing the map, generated at runtime m=[]; function w(s){document.write(s)} // set a map tile function N(i,s){m[i]="b"+s.toString()} function n(i,s){z=0;for($ in i){z+=i[$];N(z,s)}} // set a row of map tiles (index a..a+b) function f(a,b,s){for(k=a;k<=a+b;)N(k++,s);} // set a block of map tiles (index a and b define upper left and lower right corner) function g(i,j,s){for(x=i%W;x<=j%W;x++)for(y=i/W|0;y<j/W|0;)N(y++*W+x,s)} // helper for clouds and bushes - j=1..3 sets map tiles to XYZ, XYYZ or XYYYZ function c(i,j,a){N(i,a);f(i+1,j-1,a+1);N(i+j+1,a+2)} // clouds/bushes function d(i,j,a){c(i,j,a);c(i+W,j,a+16)} // hill function p(i){N(i+2,8);n([i+213,211],23);n([i+214,211,2],24);n([i+215,213],25);N(i+426,9)} // warps function q(i){N(i,10);N(i+1,11);l(i+W,3,26);l(i+213,3,27)} // stairs - d=1 for upwards, d=0 for downwards function r(i,d){for(j=0;j<4;j++)f(i+d*(3-j)+j*W,j,0);} // set a column of map tiles (index i, height j) function l(i,j,s){for(k=0;k<j;k++)N(i+k*W,s);} // fill map with sky tiles f(0,2967,7); // clouds and bushes - some of the bushes will be overdrawn by blocks and the castle, so draw them first for(i=0;i<4;i++){d(231+i*A,1,4);d(248+i*A,2,4);d(451+i*A,3,4);d(432+i*A,1,4);d(2343+i*A,3,17);d(2355+i*A,1,17);d(2373+i*A,2,17)}d(624,1,4);N(2539,19) // '?' blocks n([870,72,15,20,1,734,5,2,55,28,3,3,58],3) // brick blocks and castle f(928,7,2);f(939,2,2);f(969,2,2);n([976,3,737,2,2,53,2,15,6,18,11,1,38,1,2],2);N(1900,B);g(2322,2535,B);g(2325,2538,B);f(1687,2,13);N(1899,29);N(1901,31);f(2110,4,13);f(2111,2,15);N(2324,14);N(2536,30) // big and small hills - one of the big hills will be overdrawn by the stairs, the small hills are big hills overdrawn by stone blocks for(i=0;i<5;i++){p(1908+i*A);p(2135+i*A)} // warps (often overdrawn by stone blocks), stairs and block below pole q(1742);q(1753);q(1946);q(2148);q(2283);q(2299);r(1830,1);r(1844,1);r(1877,1);r(1033,1);r(1836,0);r(1851,0);g(1881,2520,0);l(1037,4,0);l(1848,4,0);l(1885,4,0) // pole N(410,12);l(622,9,28);N(2530,0) // lower row of stone blocks f(2544,423,1); // gaps in stone blocks g(2613,2826,7);g(2630,2844,7);g(2697,2910,7) // HTML start and CSS spritesheet base (tileset PNG encoded as base64) w("<style>body{width:3400px}div{background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAgBAMAAAAPh7vXAAAAG1BMVEVclPwAAAAAqADITAyA0BD8/Pz8vLD8mDg8vPyQWLLUAAACwklEQVR4XrWWS4rjMBCGXcxjrfKje23hA4wRJNtJ8AEmi4JsTUD7phd9gkCOPSWN5OiRttsx8xGJ2CKpj99SJcVOW8bdv+miHd+U5VfxRaQDE/y61jz91FqpHrFSPb/rFRctXEW8KF668E31b+w/LG+BAOIXBOoh4uDX1c4ImCLIVFxcmaEKbSMYc4FXWz8QACKxLFBKyQLS02YCaAkEbAQ4CaBj//GuVJgANESnryRgBLqjZLquyxJAh9rx9GIEtGKcwKh6n8H+Q2G1DwQaYgFYJSCP+SPo0VKZ+HkkAj1WgcDre58IUCO2JLAsoPU4J3DmDLYmgI5MIN8Db68qEAA6X+lKp2cTwBfN4IS/DgSyY/je412g4er0RAL++PrvRYe/nheYTgEgOQSsTQCOUiwLWKUXFTcinAQa8ohGrEygNt1gWUAjCwSGJoG9FwCaOJFYlYAXwE8o9IhMjxfbjII+ED6CHxQgxLoESivgs0WHvy40GioursdIgFsxulYMDQWcko0IiGImgSWBES09FzdjWgh/jBqKiAXQFMCZX0OQUswIuOuq5zHywIQlAXR1paPIP25n/IRpd0aZiiRkighXQVpaOd20z+A4BI3w+2/XBzDB3HskUPPnYpozGc55AKULoGwfCHTdUwLImyiL4GoUrlkCIL2AFE8mgI57sYERIo3gdqXbjR3iCMq7QDufAH7CtDtjgcMhESAufzuzAvMn2wElsomYTSA8AeFJeCzQpQ8BkA34ZQMQaQBt2Zp5JoEVAjbCoxHIMjgR0wT1QXoBaRDPJJDtAWB7JhOAhgQSIQQLZSzQrt8DeR/Aevo/nSgApn/MQSaI7X0ABs8B2H6eUia02/tAPUzUSwIgM8TmPjAEHGBdAEy7tQ/gEFKLdQEwYlsfgCFGrAuAaZME/qMAyIeIbX2gjgQOawNg2rV74C9KQ+xyNDQoswAAAABJRU5ErkJggg==)}") // generate CSS classes 'b0'..'b31' for the 32 used tiles // this actually generates 16 additional unused classes to reuse the constant A and save 1 byte for(i=0;i<A;i++){j=(i%B)*-B;k=i>15?-B:0;w(".b"+i.toString()+"{background-position:"+j+"px "+k+"px;width:16px;height:16px;float:left;}")} // some more HTML w("</style>") // body of HTML contains all tiles as <div> elements arranged in <span> columns for(x=0;x<W;x++){w("<span class=b0>");for(y=0;y<B;){w("<div class="+m[y++*W+x]+"></div>")}w("</span>")} ``` [Answer] # Javascript, ~~1069~~ ~~1072~~ 1024 characters (1957 bytes) ## [RegPacked](http://siorki.github.io/regPack.html) and [Obfuscatweeted](http://xem.github.io/obfuscatweet/) ``` eval(unescape(escape('𩡯𬠨𧰽𙰨𬱠𨀬𧡝𚑀𜐶𙡷𪑤𭁨𞠣𪱬𘐵𝠟𜠳𗠰𜀝𛀢𗀝𜀛𗀛𖡨𪐙🐢𘠻𩡯𬠨𖀩𚠦𚰢𬁸𕰠𬱴𮑬𩐽𧀧𕡁𠐕𗁡𨠔𫡯𬀓𖑩𪑪𔰒𬑲𔑮𫰹𫰐𝰷𓰏𝰎𜠲𓀢𛀋𒰶𗀉𬡥𭁵𬡮𒀩𚱒𚁃𧡛𑰋𞀜𑠎𝰅𒰱𑀕𕐃𠀬𝀩𚱃𧡛𝠜𐡦𭑮𨱴𪑯𫠠𐐁𤡞𭀩𮰈𘁮𩑷𘁁𬡲𨑹𚁴𚰱𚐮𪡯𪑮𨀩𯐁𨠨𫠩𮰈𘠼𩁩𭠖𨡡𨱫𩱲𫱵𫡤𞠠𭑲𫀨𩁡𭁡𞠻𨡡𬱥𝠴𛁩𥡂𣱒𭰰𢱇𩱯𐱎𤱕𪁅𥑧𕑁𤐃𠑧𠡁𣐃𤁨𝱶𦀃𡰱𠡍𥡅𥡣𫁐𭰃𠑱𠑄𢑔𠑹𠐰𠡄𞀯𤁺𞁶𣁄𞁭𡁧𞁶𤁹𤑗𣁌𥐕𠑃𭰡𡑑𥡒𝁘𬡗𥱓𝁲𪡍𠡃𡱘𨱸𪡲𩡋𪡥𗡨𠐴𭱒𢡎𭁊𞁁𡑭𪐴𢡳𥁕𡀷𬁨𩀹𩱫𠱏𤁓𥱎𝑏𪑒𭁴𬱸𞁸𡱊𜡃𢱰𪠹𞑓𢡣𥡏𥰸𨡤𭠫𫑩𢁤𚱕𝑖𩡸𤡡𤑄𡐯𮐶𜑪𮠹𜑆𬑰𢁲𡡓𤁢𛱲𡡒𨱴𦁅𥰸𢱆𝠶𞁅𜰱𨠫𭰯𣁇𚱂𠑏𢑘𠡏𫱨𝁵𡁘𜑣𝁉𫑃𣁉𥡆𮁣𫑡𡑋𨡓𣑙𨰴𡡘𥱺𞁑𠑃𢱸𣁆𠡋𮑑𣁓𜀲𦑃𨑁𪱅𨡁𤐴𠱡𠡪𛰯𡱵𥡊𩱁𣡅𤱮𬡹𤡧𠡌𬑪𦡌𬑵𮑸𢡁𪀹𬡸𞑇𢑅𭁇𢱣𭱋𪀶𫠸𢀫𤐲𡰱𡁷𤑡𦑧𡡙𢡓𠱐𚱓𤁯𜁖𢱚𚱈𪱫𠑪𜑗𩱣𡁲𩐵𞁉𥑃𣰲𢡌𠑳𫱐𥐴𢠳𡁭𡁌𦑭𩱉𝑍𢑎𞁄𨠶𞁱𡐕𝡘𚱬𢱰𜡣𥁷𠡦𣠴𢑓𛱄𩱓𮑙𛱪𩐴𜐲𩰴𩑲𜁒𠑌𚰫𤁲𭡒𦑥𛱮𪁥𦑔𩱅𩱏𤑓𬱔𤑃𣱕𪑷𣁗𢱕𦁆𥁣𪑮𠑑𨐸𫱨𡱲𡑹𩱎𭀱𩱗𥑁𪡃𭱓𡱊𫱇𞑆𭱃𨑏𢡆𦑬𦑁𦁷𡐸𫰹𢑨𣑪𮁦𨡪𢑉𚱅𡀶𠱈𮁑𩱸𣁯𡑓𪑶𩱳𜁗𢁶𮐴𜁇𪑯𭑲𬱤𢑧𡡳𮁵𫁙𣑄𤑗𨱫𫰰𢑩𡱉𫑧𤱗𠡅𤰰𞑆𮡤𪡗𩱨𛱪𠡱𢱩𠑘𤑆𣑃𦡘𜁏𤑕𬱷𢑵𣱵𬐵𮡈𮑷𢑑𫁁𦁒𜑰𨑐𢑐𜠵𫠯𢑒𬁤𜁡𦡩𪑒𪱩𩱨𦁑𥡰𨑏𩀲𜁺𚱁𝁂𢐳𭰫𜠯𦁂𮡄𠠳𢁳𪱕𤁐𫡙𬁯𮡇𨰵𝑁𢱕𣁯𡱷𩡃𢁔𩁕𭱌𢑭𮑩𣀴𡱯𥑲𫁫𠱉𣀲𠑆𡐸𫑧𢐵𝱳𦑅𤡉𫰳𩱤𬑘𨡪𤠳𪑃𣑱𝱑𡁵𩡁𢀷𠱴𡁴𪡧𨱍𪁅𤱁𭑦𮡵𮡁𭡍𫠲𭱅𫁳𫱭𦑔𤱁𞁁𩑆𢡥𠱺𤑰𤐸𠡫𠐳𝁚𤑍𤑡𤑂𭀲𦡰𝑊𫱅𥡁𪡢𠱯𮁈𢑍𪡧𤠰𭱔𜑑𦁯𠡡𤡄𤁊𢡄𭁁𥱂𝱊𪁏𠑨𩱑𤱉𤑑𣁚𤱺𤑲𭀸𡁥𤠯𠑥𭡯𛱮𤱧𠑰𫠯𣑑𤱡𢐷𦀰𠑂𬰸𠠲𢀶𩑕𪑡𜀲𛱴𠑐𥑺𥑓𭱉𩱍𞁔𫑐𪡁𡑈𡱂𩁁𡑹𝱴𤐯𩱅𡡋𣁤𤑅𭱙𫁳𩡧𠱆𡱲𠑵𠑡𦡍𡐯𬑍𠑹𢑥𢑢𦀲𩱪𩱑𣱡𭱎𩰲𬡖𝰴𠰹𢱑𚱸𮑎𡁑𫱳𭰃𠡊𤡕𝑅𬡫𢠩𛐢𚰨𫠥𙠗𘀭𘠫𚁮𛰦𯀰𕰻𘰦𬁸𞱨𩑩𩱨𭀺𙡰𮀻𩡬𫱡𭀺𫁥𩡴𯑜𙰾🀯𩁩𭠾𘡽𐑍𨀩𮱭𖁟𘁩𫠠𬰩𫐫👢𚁰𨑲𬱥𢑮𭁠𦱟𧐬𜰲𚐩𞰈𘁭𯐁𠱞𨐩𮱣𖀤𘁩𫠠𨐩𨰫🐤𙐲🱍𚁡𦰤𠀺𤡞𨑛𙁀𞰈𘁣𯑤𫱣𭑭𩑮𭀮𭱲𪑴𩐨𘠼𨡯𩁹𕠣𜰳𞐲𬁸𧀧🠢𚱒𨀽𨠨𝰩𛀲𜐲𑰱𞐜𝀟𑀴𗀴𝐟𒰸𐡣𑀳𧐇𞀜𝀟𑠡𫐅𝰴𝐵𗰅𘑬𫐋𞀂𬰷𝀟𒰹𧐇𞀜𘑭𑀶𗀡𫁬𫐄𝠂𬰷𘑭𒰳𜐜𜰋𝐷𗀌𓀌𓀎𓀞𑀴𗀳𑀱𗀌𜠅𗠳𜠋𗰜𗐆𬰋𜠝𖠆𬰄𞐹𖠰𑡳𑀹𞀚𗐆𬰅𩁤𩀋𓀜𜰎𗠞𜠋𜠱𕀋𞐔𑀸𗀞𜠄𝀜𜠅𝰲𑐷𜰏𜰏𜰅𝰲𑀰𗀌𒐰𓰰𑀰𗀝𓰰𑀲𗀌𜰲𑀲𖠛𑡳𑑴𩱶𑠸𒰳𝐔𒐑𓰸𒐑𒰳𞐜𞀋𜰷𗀝𓰝𑐸𓠛𓰝𒰲𝠚𖰰𑐸𓡳𓡤𩡦𩡤𒐓𑀳𗀸𑀰𕀆𔐉𔐷𔰋𝐜𔐉𞀋𜰱𗀓𑀳𗀸𒰲𜐚𓰛𓰓𝰛𜀏𖰎𞀷𨑢𑀴𕀷𖰛𗐎𔰏𬰎𩱧𩑧𩰏𞀏𔁰𒐒𑐙𪠏𔐆𔐷𖑩𪠷𔐐𬀅𔐒𑐙𪠄𝐜𖑩𪠎𔁰𒐒𒰴𗀙𪠄𜠚𜁩𪐛𜀐𖰝𓰛𜁪𔰑𓰙𪠋𞐜𔐛𖰛𓰐𬀷𜀎𩱧𭑧𩱪𔰷𘡀𚱒𚁃𚁢𚀱𚐬𦰶𞐜𓰄𝐜𓠋𝠴𗀏𒰵𝱀𛀲𚐩𞰧𞱧🐯𦰁𛐟𘐣𙡀𧡠𧐯𛡥𮁥𨰨𧰩𞰩𭱩𭁨𚁟𛡳𬁬𪑴𚁧𚐩𧰽𪡯𪑮𚁳𪁩𩡴𚀩𚐻𩑶𨑬𚁟𚐠').replace(/uD./g,''))) ``` ## Unobfuscated code I hid this code because there's ungolfed code below. ``` function R(s,t){return new Array(t+1).join(s)} function b(n){return"<div style='background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAgBAMAAAAPh7vXAAAAG1BMVEVclPwAAAAAqADITAyA0BD8/Pz8vLD8mDg8vPyQWLLUAAACwklEQVR4XrWWS4rjMBCGXcxjrfKje23hA4wRJNtJ8AEmi4JsTUD7phd9gkCOPSWN5OiRttsx8xGJ2CKpj99SJcVOW8bdv+miHd+U5VfxRaQDE/y61jz91FqpHrFSPb/rFRctXEW8KF668E31b+w/LG+BAOIXBOoh4uDX1c4ImCLIVFxcmaEKbSMYc4FXWz8QACKxLFBKyQLS02YCaAkEbAQ4CaBj//GuVJgANESnryRgBLqjZLquyxJAh9rx9GIEtGKcwKh6n8H+Q2G1DwQaYgFYJSCP+SPo0VKZ+HkkAj1WgcDre58IUCO2JLAsoPU4J3DmDLYmgI5MIN8Db68qEAA6X+lKp2cTwBfN4IS/DgSyY/je412g4er0RAL++PrvRYe/nheYTgEgOQSsTQCOUiwLWKUXFTcinAQa8ohGrEygNt1gWUAjCwSGJoG9FwCaOJFYlYAXwE8o9IhMjxfbjII+ED6CHxQgxLoESivgs0WHvy40GioursdIgFsxulYMDQWcko0IiGImgSWBES09FzdjWgh/jBqKiAXQFMCZX0OQUswIuOuq5zHywIQlAXR1paPIP25n/IRpd0aZiiRkighXQVpaOd20z+A4BI3w+2/XBzDB3HskUPPnYpozGc55AKULoGwfCHTdUwLImyiL4GoUrlkCIL2AFE8mgI57sYERIo3gdqXbjR3iCMq7QDufAH7CtDtjgcMhESAufzuzAvMn2wElsomYTSA8AeFJeCzQpQ8BkA34ZQMQaQBt2Zp5JoEVAjbCoxHIMjgR0wT1QXoBaRDPJJDtAWB7JhOAhgQSIQQLZSzQrt8DeR/Aevo/nSgApn/MQSaI7X0ABs8B2H6eUia02/tAPUzUSwIgM8TmPjAEHGBdAEy7tQ/gEFKLdQEwYlsfgCFGrAuAaZME/qMAyIeIbX2gjgQOawNg2rV74C9KQ+xyNDQoswAAAABJRU5ErkJ)-"+(n%16)*16+"px -"+(n/16|0)*16+"px;width:16px;height:16px;float:left}'></div>"} function M(s){m="";for(_ in s)m+=b(parseInt(s[_],32));return m} function C(s,a){c="";for($ in a)c+=$%2?M(a[$]):R(s,a[$]);return c} O="<body style='width:3392px'>"; O+=R(s=b(7),212); O+=R(C(s,[19,"456",14,"4556",8]),4); O+=C(s,[6,"c",13]); O+=R(C(s,[8,"456",8,"klm77777455567777kllm",8]),4); O+=C(s,[6,"s7456",9]); O+=R(C(s,[8,"klm",16,"klllm",16]),4); O+=C(s,[6,"s7klm",31,"3",57,"222222227772223",14,"3",11,"22277772332",56,"00",8,"s",200,"000",8,"s",199,"0000",8,"s",198,"00000",8,"s7777ddd",22,"377723232",21,"ab",9,"ab",18,"232",14,"2777772777773773773777772",10,"22",6,"0770",10,"00770",12,"2232",12,"000000",8,"s7777tgv",8,"8",35,"ab",6,"qr778",6,"qr",39,"8",37,"007700777787770007700",26,"000000077778777s777dfffd",6,"nop",13,"8",10,"ab",8,"qr",6,"qr7nop",5,"qr",6,"8",31,"nop",13,"8",21,"0007700077nop700007700077787ab",14,"ab700000000777nop77s777ggegg77877no9op",6,"hiiijnop7777hij77qr",8,"qr7hiij7qrno9op7777qrhiiijnop7777hij",15,"hiij777no9op",6,"hiiijnop",4,"hij",12,"0000ii0000no9o00000770000jnopqr77hij",9,"qr00000000077no9op70777gguggjnop7"]); O+=R(C(b(1),[69,"77",15,"777",64,"77",57]),2); document.write(O); ``` ## Ungolfed code ``` function repeat(s, t) { var S=s; while(t-- > 1) S += s; return S; } function block(n) { return "<div style='background: url(data:;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAgBAMAAAAPh7vXAAAAG1BMVEVclPwAAAAAqADITAyA0BD8/Pz8vLD8mDg8vPyQWLLUAAACwklEQVR4XrWWS4rjMBCGXcxjrfKje23hA4wRJNtJ8AEmi4JsTUD7phd9gkCOPSWN5OiRttsx8xGJ2CKpj99SJcVOW8bdv+miHd+U5VfxRaQDE/y61jz91FqpHrFSPb/rFRctXEW8KF668E31b+w/LG+BAOIXBOoh4uDX1c4ImCLIVFxcmaEKbSMYc4FXWz8QACKxLFBKyQLS02YCaAkEbAQ4CaBj//GuVJgANESnryRgBLqjZLquyxJAh9rx9GIEtGKcwKh6n8H+Q2G1DwQaYgFYJSCP+SPo0VKZ+HkkAj1WgcDre58IUCO2JLAsoPU4J3DmDLYmgI5MIN8Db68qEAA6X+lKp2cTwBfN4IS/DgSyY/je412g4er0RAL++PrvRYe/nheYTgEgOQSsTQCOUiwLWKUXFTcinAQa8ohGrEygNt1gWUAjCwSGJoG9FwCaOJFYlYAXwE8o9IhMjxfbjII+ED6CHxQgxLoESivgs0WHvy40GioursdIgFsxulYMDQWcko0IiGImgSWBES09FzdjWgh/jBqKiAXQFMCZX0OQUswIuOuq5zHywIQlAXR1paPIP25n/IRpd0aZiiRkighXQVpaOd20z+A4BI3w+2/XBzDB3HskUPPnYpozGc55AKULoGwfCHTdUwLImyiL4GoUrlkCIL2AFE8mgI57sYERIo3gdqXbjR3iCMq7QDufAH7CtDtjgcMhESAufzuzAvMn2wElsomYTSA8AeFJeCzQpQ8BkA34ZQMQaQBt2Zp5JoEVAjbCoxHIMjgR0wT1QXoBaRDPJJDtAWB7JhOAhgQSIQQLZSzQrt8DeR/Aevo/nSgApn/MQSaI7X0ABs8B2H6eUia02/tAPUzUSwIgM8TmPjAEHGBdAEy7tQ/gEFKLdQEwYlsfgCFGrAuAaZME/qMAyIeIbX2gjgQOawNg2rV74C9KQ+xyNDQoswAAAABJRU5ErkJ)-" + (n%16) * 16 + "px -" + (n/16|0) * 16 + "px; width: 16px; height: 16px; float: left; }'></div>"; } function blocks(s) { var S=""; for(var i in s) S += block(parseInt(s[i], 32)); return S; } var output = "<body style=width:3392px>"; output += repeat(block(7), 212); output += repeat(blocks("777777777777777777745677777777777777455677777777"), 4); output += blocks("777777c7777777777777"); output += repeat(blocks("7777777745677777777klm77777455567777kllm77777777"), 4); output += blocks("777777s7456777777777"); output += repeat(blocks("77777777klm7777777777777777klllm7777777777777777"), 4); output += blocks("777777s7klm777777777"); output += blocks("777777777777777777777737777777777777777777777777777777777777777777777777777777772222222277722237777777777777737777777777722277772332777777777777777777777777777777777777777777777777777777770077777777s7777777777777"); output += blocks("777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777700077777777s7777777777777"); output += blocks("777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777000077777777s7777777777777"); output += blocks("777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777770000077777777s7777ddd777777"); output += blocks("7777777777777777377723232777777777777777777777ab777777777ab7777777777777777772327777777777777727777727777737737737777727777777777227777770770777777777700770777777777777223277777777777700000077777777s7777tgv777777"); output += blocks("77877777777777777777777777777777777777ab777777qr778777777qr7777777777777777777777777777777777777778777777777777777777777777777777777777700770077778777000770077777777777777777777777777000000077778777s777dfffd77777"); output += blocks("7nop777777777777787777777777ab77777777qr777777qr7nop77777qr77777787777777777777777777777777777777nop777777777777787777777777777777777770007700077nop700007700077787ab77777777777777ab700000000777nop77s777ggegg77877"); output += blocks("no9op777777hiiijnop7777hij77qr77777777qr7hiij7qrno9op7777qrhiiijnop7777hij777777777777777hiij777no9op777777hiiijnop7777hij7777777777770000ii0000no9o00000770000jnopqr77hij777777777qr00000000077no9op70777gguggjnop7"); output += repeat( repeat(block(1), 69) + blocks("77") + repeat(block(1), 15) + blocks("777") + repeat(block(1), 64) + blocks("77") + repeat(block(1), 57), 2); document.write(output); ``` I first made tiles into sprites with @schnaader's minified data URI. `0 ~ v` (which is 0 ~ 31 in base 31) represents each tile. And I converted map to tiles by hand. This data has 212 characters per row. Then I replaced repeating character (like `7`(sky) and `1`(ground)) with `repeat()`. I found `7`s and some blocks, and another `7` pattern is repeated. So I made another function to make it compact. You can see it at unobfuscated source code. Finally I RegPacked, and Obfuscatweeted my 2341 bytes golfed code. It was very funny challenge. Thanks! And thanks to @xem for more tricks. [Answer] # Python3 ~~1638~~ ~~1576~~ ~~1616~~ 1513 bytes ## 581 code + 932 data [![enter image description here](https://i.stack.imgur.com/hTNDCl.png)](https://i.stack.imgur.com/hTNDC.png) ↑ This top is the original level. In the middle is the PPM generated by this script. At the bottom is a diff, and this shows that the palette and the map do not agree exactly! I put this down to data glitch and not my script ;) ``` # 759808 is 212*14 tiles at 16*16 each - the size of the map import lzma;B,E,R,X=bytearray,759808,range,16 D=B(lzma.decompress(open("i","rb").read())+B(E)) # put canvas on end of data array i,P=8218,lambda x,y:8622+y*54272+x*X # 8622 is length of decompressed data def Q(s,n,d): # copies a 16x16 tile from s to d # n is the stride for the source s, which is different for put and copy for m in R(0,256,X):e=d+m*212;D[e:e+X]=D[s+m*n:s+m*n+X] for j in R(4): # there are 4 command sections j&=1;i+=1+j;r=D[i-1]<<8 # j is now truthy if this is a copy buffer for k in R(D[i]): # this many commands a,b,w,h,c,d=D[i+1:i+7];q=h>32 # unpack it; put doesn't use all these # do the put/copy for z in R(((a,h-32)[q],w*h)[j]):Q((D[(i+4+z,i+5)[q]]<<8,P(a+z%w,b+z//w))[j],1+211*j, (P(b+z,w),P(c+(z%w,w-z%w-4)[r&1],d+z//w))[j]) i+=((3+a,5)[q],6)[j&1];r>>=1 # move i to next command for y in R(2,11):Q(28<<8,1,P(198,y)) # special case flagpole o=open("o","wb");o.write(b"P6 3392 224 255 ") # header for PPM for c in D[8622:]:o.write(D[8192+c*3:][:3]) # decompress palette to RGB ``` (bytes counted without comments, line-unwrapped and second level indent being `\t`) Data (base64-encoded to be pasted; decode and save as a file named "i"): ``` /Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4CGtA2JdAACA3BlsBrac0zEPcSPZ/qSCuw0fuG0WYiRk w+pNfoBEsFJBEXgxJ73nEPREKmuJUHyg+jhBTQcbUI0gChatJ7D6ZqYmLz4P34OFSxUMWF+aGhm2 +8mNqw264w0JIjW9ogeNpJX6pgH/xJ/D2qlfqfCuz0cOR1sPAAcMrue1y9joUaDauFLj8QhbExen lQkUMfMePbMnn4nJ0aVXBeHdKIwSeFQdFz/Aj695kKi0x8+MXR84cpNh3U8y7deiyjbNyIgu7vLn WBxzXhEtrV9svBETfQpxj2qYI11ALgWlhoxdoABE3ocVgE1Qo35dnoJe+1DJFvqIzFOoxSJEckUk T89RIjARdA/Ax6UTiitivZp4EhM+xczasrm+2XFy68mA96xmEMKp9ZpoApNIU0ShMMW1Im0QFeuS aCl43qJuintArMAeDiOlmkbDNzMzHZIgDFeklUnnKG9xHXPQXNQVyJ9I7z+rLHh1VtuXDyAErKTL VY/Xai2pIUlSt5H1KGEExdHu3O17XKbar11Jad6nFjDKOZFwamJQTFIG6dru2UXVJq29pGCnKLlB lOmls4agigMI7QJ5K/Rzf15ZuIQ7U9MKJ3E4llbwqs6vDk+Ln/ceRVfl5Fm/Ne056ZLDp6VIf5zs EMWra8UnjndkigqAyp8D62AcrPFIp9EdJmgiGzfhNCQ1JptRN/z01mNomtwVJfqeLTqgvRgXXG3P 8p+6s1rjEfblMBNyMxdYvJZXLE0wgu4xhH3fiNTT+RyTIJ1MZZ1zhksfe2SnNTbL2JYGven1WPfI YP+M4NI/vpQ4bGsuJ8w//x01GpkTLfMZtZgBhx0dx1Wu9i0JY9hhtoI2/tGR4sNHfpSs7xD/Zz+7 6Z18z3AQn4dC7Trp0WndI/zS8eRZlRgKxA/lb09MZ87ugbXnm2+oBQFSLEtg/rqg398pDWx9W4Zk 6GeRTqvp9CJ9meMagUnGHKnAj+05PE0XgEXO6r9B8ltgoHf0+wXFevBHVupfiH9MApUxd0TPzv16 Y5Rfjxao0wLcIbxKMd3vtI1rCvOdq0OysWNrtcH9EBKjx9+CnGFBFZI9w9kCMJ8ZT0m9nsNYPelL 29KbQMt+K213+7o0MS3DxeGTHSW9CiEOTzNeqvsXN6IcIxjJIkgH8MuAAAAA5PpImPBeeH8AAf4G rkMAALsE5byxxGf7AgAAAAAEWVo= ``` The data file is a custom format I made for this problem and is stored as LZMA. First all 32 tiles are serialized. There are 9 colours in the palette, and this takes 8219 bytes uncompressed. (I found that trying to compress the tiles at 4-bits-per-pixel didn't help compression at all. I did not try and brute-force the best ordering of the tiles, and I probably lose a few points here.) There are 212x14=2968 blocks making up the map. Then the instructions to recreate the map are now encoded. First comes a section of "put" commands that place some sequence of tiles from the tile-palette on the map at a particular x,y. As there are 32 tiles, I specify a run of the same tile using a number bigger than 32 rather than the tile index. Then comes a section of "copy" commands that copy some rectangle of the current map to some other place. There is a special bit-mask that marks if the copy should be mirrored. A short example command buffer: ``` 16, # there are 16 put commands 3, # place 3 tiles 8,2, # dest x, y 4,5,6, # these three tiles 3, # place 3 tiles 8,3, # dest x, y 20,21,22, # these three tiles 5, # place 4 tiles 27,2, # dest x, y 4,5,5,5,6, # these five ..., 8, # bits set if copy reversed (high 8 bits of a uint16 mask) 14, # there are 14 copy commands 8,2, # src x, y 3,2, # w, h to copy 19,1, # dest x, y 1,9, # src x, y 3,2, # w, h to copy 16,10, # dest x, y ..., 13, # there are 13 put commands ... 7, # bits set if copy reversed (high 8 bits of a uint16 mask) 15, # there are 15 copy commands ... ``` (I said *short*, but that's actually nearly half the total command buffer needed to make the whole map; the vast majority of the bytes in the data are the 32 source tiles themselves) Then comes a second section of "put" commands and finally another section of "copy" commands. Because these can overwrite each other, I can build copy parts that I later erase or change. I can doubtless shave a few more bytes off it by - for example - turning *puts* into small *copies* and by doing the `eval` trick on a gzipped source-code, or playing with PNG (which is DEFLATE with image-specific filters) too. But I like things verbose as they are. [Answer] # JavaScript: 3620 *(ouch)* 3429 3411 ## Updates * **Update #1:** Removed `var` definitions and put the variable declarations inside brackets of first use. Removed `getElementById()` as it is also available on load as a varaible by ID. Using `cloneNode()` instead of `createElement('CANVAS')`. Renamed *main* from `xMx` to `M`. Removed the scaling feature :(, *(still available in the example.*) Added some comments to the expanded code. (That code is not updated with the removals. The line below, *("Mini code")*, is.) * **Update #2:** Removed the main function `M()` as a whole and let the code run at *root*. This would require the code be placed inside a load wrapper or at end of document. * **Update #3:** Added statistics. ***Mini code:*** ``` K=126,f=['#000','#c84c0c','#fc9838','#00a800','#80d010','#fcbcb0','#3cbcfc','#fcfcfc'],X='Å=!15d>KIRiE%>?D^?C^FVNBTJ@M^>>]ANtN?ZCW]@QM4Gb1>EVWEZAEZN@VfMI?MPckVAwNEZWNV>Q]@YT2n6d@%vN4Gb@MABMALT>JTABM>Qz@FCTI`ZEE@L?E@CDD{EE@L_A5G>%>IVEB_DHTCC{PC{HDzlz]A4o5d>KIR5G}LZ?YZIAZI`ZH]LE]BBVL>VBHXLEXBLMLAM3n7y$",2EEKIR&O30y$",2E}?Q6&o9y$",2EbD?Q6&n2pI`ZJNM`BRG~J`M`CRO9dBKIRibPC@NMBNB]6n0dBKIRib>C@CVBCE]6n1dBKIR6n3y*",~1F0G%Ii%1R6Ob")",?-1n4y*",BK0G%1Ri%I6Ob")",In8dEKIRib"*",b1F0G%Ii%1R6O>%CCD8Gb")",An9p@ciuB?LFD?`RC?Ji~F?JRBc6OUdBKIAib1Bciu1>?JFDtDM>DV>DZ>DX>QtQM>QV>a>>PT>PwPr>Pa>s>WT[][M[V[Z[XAI]AIMAICAo1eKIREJ`NGuv`3G~>{AB@MC@JJ@SJES2o2eKIREI`NGBKJ`2GCKAEABBfPT>PwPr>Pa>s>WT[V[Z[XAI]AIM^T^_^r^aA^vATA@VA@ZA@XAJ]AJSO0dHKQFXRC{NzB@D@ZNG}r>>Z>@TBB@Mw>F?C[>>^MJ@VABTACVAE_3GF%Cr>EFMP_[FAO3dHKIFFBFB[FNG}w>FMBHTFZ>HwDFS?HCACFJGFK@T>>>>{ZCCMF@VX>>PtPBE[CBACSO5dH%WBHL[ELBPLGbWwQT@W@S[v@aABDLO4dH%1>?@JB?B4Gb1?]^>v@MJBCLGF%1B]AVvESodHK?EF_@3G}w>FMBEMECMEtZ>>HSndH%I?EF`zCBP|}XSt@a>BX>CaB`M>R>>>YMBREAo3duH?J6o4d~EPFiu`]@FP|bFDVREVN]N[>CEa[aAIV>`CAo6dEK?Cl?E7G}YF9GE%BHWG>K>BRMCF?DHBDDHBN@HBI{LJ@C3o7eKIRi>K?B@?@MB?S>?CATSCMAEV@?V2o8eKIR6O6y(",E%H4&O7y(",bHCF3&O8y(",>%H4&&&#;Ø=Kxt3r@6X>8_J1ZA3TJ6VA8>>@PM2D{5HM7F@L0ES2C@L5BS7zBU>JG>x>>>3a>6a>8rA1rA3_A6_A8T[M3>M5DM7PS0FS2HS5CS7EMU@JG@x>M3PM6PM8HS1HS3ES6ES8BS?T3>T5DT7PBA0FBA2HBA5CBA7ETU@LGBx?M3Hz6DM8E@J1FS3B@J6CS8>zPT2DBB5HT7FBL0EBA2CBL5BBA7{BU>LGu1PM3FM6HM8CS1ES3@S6BS8?MDT2HT5FT7EBA0CBA2BBA5{A7>TU?LGE%1a>3Z>6r>8VA1_A3MA6TA8tDM2HM5FM7ES0CS2BS5@S7>MU?JGF%1^>2L>>4^@5s7^>8jA0lA1jA3lA5lA6l>U`|H%1fB2N>>4f@6kB7f>9kJ0gL2kA3gJ5gA6g>UR|D%1`>>2`>>4N>>6L>>7L>>9fA1^A2^A4kA5jA6sUY|P%^Al>4s6`>>9lA1Lv4`v6^hL>>UsJ]5I]9Qc4Rc9NIG1bL>>5^>9jA4lh`|1>%f>5k>9gA4R>hN|1@%1Y]6`c1Lc6[>UW]@a5?a9DPA4FPhCWG1~kAR>>4g>6N>>9Rv1fA4Nv6khf>Ug>[>4W]9Yc4`c9LIG1uNvg>5f>6Rv0kA1Nv6fhR>>21k>L]5[>9Wc4Yc9`IG1E%IB6P7ALE8WB6N5`B5HI@6P7AJE8W@6N5`@57G1F%1FX2>X2BX7Dm0Fm0Pm1@m7?X2@V9CCA0PCA2PC2G1Hx?X2@X2CX7HX7PX9Cm0?m1Dm2PDJ6DDJ7>X8?CD9>CL2>CL2DCA3>NG1D%13N>N4kN4g`5`>N8^W9gA3`?L4I?L4W?N5`?L8J?Q3FPJ4?PJ5?PL5EPJ8BPY3Hm4?m5>DJ5Em8CDR8EH`8FFN8HEL8DC2G1Pxg>3g>4R>>5lA6Lv7s3Q]4R]5Y]4Fa5HWqb2s3s4l>5gA6Nv8k>3W]4Y]5Q]4Ha5DWq>xQc6Lc7W]3Da4FX5HQq@xWc6Nc8I]3Pa4HX5DQq~19Qc9DPhDDhDHhDFhDEhDChDBhDJqu19mqE%Uf@U`>@UJ?@U`?@Uf@U`>@UCXUBP3qF%U@PEUBH3qH%UNIqD%UNAqP%UBQG3bUEQ&&';'B%?KAG@B@@p"%2_>>AC%]>j>H>G2e%O2O1DAY>I>W>6GA9Q>J>:K:%?A?%P>E1E>A>?>A?F>H1D>P1C>20B>@AF1D19,&GC1@>B1%?@1?17,&,6,5,8,4,3,>12,0,1,'.match(/../g).forEach(function(v){X=X[u='split'](String.fromCharCode(K--))[U='join'](v);if(K==92)K=91});eval(X[u]('*')[U]('f')[u](')')[U]('d')[u]('(')[U]('b')[u]('&')[U](']')[u]('%')[U]('[')[u]('#')[U]('}')[u]('!')[U]('{'));function e(k,d,i){for(s[Y]=k,i=0;i<d[L];)s.rect[G](s,d.slice(i,i+=4))}function _(d,i,q){for(S.width=R,i=0;i<d[L];++i,s.fill(),s.beginPath())F[q=d[++i][0]]?F[q](d[i]):e(f[d[i-1]],d[i])}F={$:function(d){_(Å[d[1]].concat(d.slice(2)))},b:function(d){_(Å[d[1]].slice().map(function(i,x){return(x=d[2].indexOf(i))>-1?d[2][++x]:i}))},f:function(d,i){for(s[Y]=f[d[1]],s.moveTo[G](s,d[2]),i=3;i<d[L];++i)s.lineTo[G](s,d[i])},d:function(d,x,y,g){for(s[Y]=f[d[1]],g=d[2],y=g>0?0:15,x=0;x<R;++x,y+=g)s.rect(x,y,1,1)}};R=16;c.width=3392;c.height=224;;S=c.cloneNode();c=c[G='getContext']('2d');s=S[G]('2d');c[Y='fillStyle']='#5c94fc';c.rect[G='apply'](c,[0,0,3392,224]);c.fill();for(k=0;k<Ø[L='length'];++k)for(_(Å[Ø[k]]),t=Ø[++k],i=0;i<t[L];i+=3)for(j=0;j<t[i+2]*R;j+=R)c.drawImage(S,t[i]*R+j,t[i+1]*R) ``` --- ## Blah blah: *– Demo at end of post.* Using *canvas* as base for an attempt to solve this. Ended up with about 6000 chars, but after some fiddling (and a custom compression - with fiddling and tweaks on that as well) I'm now at the stated number. Still high, but then again the *quality is good ;-).* It also includes a scale option, first argument to the `xMx()`, aka *"main"* function. 1 = normal size (as in 16 bit tiles). There is not much room for tweaking, so if one use fractions some of the tiles does not fit best together. At whole numbers it should be OK. [1] But: warning, going up, quickly eats resources and makes for a huge canvas. (It is all painted in one go.) When the original width is 3392 pixels it quickly becomes huge. [1] *[1] As of update #1 this has been removed. It is present in the demo.* --- ## Stats: * `Main code           :  870` * *`Compression:`* + `Main data       : 2176 (17,480 bits)` + `Key             :  128 ( 1,024 bits)` + `Code            :  236` + `Whole she bang : 2540` + `Decompressed data : 5608 (44,864 bits)` * `Total   : 3410` [1] *[1]: +1 byte, ";", between the main / data code.* The compressed data is one array, Å, and one *"object"*, Ø. Where Å is holding the tile placement and the Ø holding the data for painting the tiles. The Ø should have been an array as well – but as my code started out with something like this: ``` var tiles = { brick: [ ... ], qmark: [ ... ], }; ``` It ended up as is. I'll perhaps see if I can't fix this. Ideally I would have made it parseable with JSON instead of eval(), but that would not be a point in a contest like this. As it is now it can not be JSON parsed due to missing quotes around the id parts. --- ## Demo Here is a fiddle where one can view the code in action. The code in the fiddle I have expanded somewhat (And added some HTML / CSS styling *around* the world – but the image of itself is self sustained.): ### [*MARIOS WORLD*](http://jsfiddle.net/Ifnak/9txkyv40/2/embedded/result/) [![](https://i.stack.imgur.com/sqwuj.png)](http://jsfiddle.net/Ifnak/9txkyv40/2/embedded/result/) --- ## Expanded code: Expanded and (a bit) rearranged code: ``` var D, C, c, S, s, // Document, canvas and shadow canvas. R, F, Z, X, Ø, Å, // Due to the compression we have a couple of non-ascii K, // variable names. L = 'length', Y = 'fillStyle', u = 'split', U = 'join', f = [ '#000', '#c84c0c', '#fc9838', '#00a800', '#80d010', '#fcbcb0', '#3cbcfc', '#fcfcfc' ] ; /* ----------------------- data unpackeer and loader ------------------------ */ X='Å=!15d>KIRiE%>?D^?C^FVNBTJ@M^>>]ANtN?ZCW]@QM4Gb1>EVWEZAEZN@VfMI?MPckVAwNEZWNV'+ '>Q]@YT2n6d@%vN4Gb@MABMALT>JTABM>Qz@FCTI`ZEE@L?E@CDD{EE@L_A5G>%>IVEB_DHTCC{PC{H'+ 'Dzlz]A4o5d>KIR5G}LZ?YZIAZI`ZH]LE]BBVL>VBHXLEXBLMLAM3n7y$",2EEKIR&O30y$",2E}?Q6'+ '&o9y$",2EbD?Q6&n2pI`ZJNM`BRG~J`M`CRO9dBKIRibPC@NMBNB]6n0dBKIRib>C@CVBCE]6n1dBK'+ 'IR6n3y*",~1F0G%Ii%1R6Ob")",?-1n4y*",BK0G%1Ri%I6Ob")",In8dEKIRib"*",b1F0G%Ii%1R'+ '6O>%CCD8Gb")",An9p@ciuB?LFD?`RC?Ji~F?JRBc6OUdBKIAib1Bciu1>?JFDtDM>DV>DZ>DX>QtQ'+ 'M>QV>a>>PT>PwPr>Pa>s>WT[][M[V[Z[XAI]AIMAICAo1eKIREJ`NGuv`3G~>{AB@MC@JJ@SJES2o2'+ 'eKIREI`NGBKJ`2GCKAEABBfPT>PwPr>Pa>s>WT[V[Z[XAI]AIM^T^_^r^aA^vATA@VA@ZA@XAJ]AJS'+ 'O0dHKQFXRC{NzB@D@ZNG}r>>Z>@TBB@Mw>F?C[>>^MJ@VABTACVAE_3GF%Cr>EFMP_[FAO3dHKIFFB'+ 'FB[FNG}w>FMBHTFZ>HwDFS?HCACFJGFK@T>>>>{ZCCMF@VX>>PtPBE[CBACSO5dH%WBHL[ELBPLGbW'+ 'wQT@W@S[v@aABDLO4dH%1>?@JB?B4Gb1?]^>v@MJBCLGF%1B]AVvESodHK?EF_@3G}w>FMBEMECMEt'+ 'Z>>HSndH%I?EF`zCBP|}XSt@a>BX>CaB`M>R>>>YMBREAo3duH?J6o4d~EPFiu`]@FP|bFDVREVN]N'+ '[>CEa[aAIV>`CAo6dEK?Cl?E7G}YF9GE%BHWG>K>BRMCF?DHBDDHBN@HBI{LJ@C3o7eKIRi>K?B@?@'+ 'MB?S>?CATSCMAEV@?V2o8eKIR6O6y(",E%H4&O7y(",bHCF3&O8y(",>%H4&&&#;Ø=Kxt3r@6X>8_'+ 'J1ZA3TJ6VA8>>@PM2D{5HM7F@L0ES2C@L5BS7zBU>JG>x>>>3a>6a>8rA1rA3_A6_A8T[M3>M5DM7P'+ 'S0FS2HS5CS7EMU@JG@x>M3PM6PM8HS1HS3ES6ES8BS?T3>T5DT7PBA0FBA2HBA5CBA7ETU@LGBx?M3'+ 'Hz6DM8E@J1FS3B@J6CS8>zPT2DBB5HT7FBL0EBA2CBL5BBA7{BU>LGu1PM3FM6HM8CS1ES3@S6BS8?'+ 'MDT2HT5FT7EBA0CBA2BBA5{A7>TU?LGE%1a>3Z>6r>8VA1_A3MA6TA8tDM2HM5FM7ES0CS2BS5@S7>'+ 'MU?JGF%1^>2L>>4^@5s7^>8jA0lA1jA3lA5lA6l>U`|H%1fB2N>>4f@6kB7f>9kJ0gL2kA3gJ5gA6g'+ '>UR|D%1`>>2`>>4N>>6L>>7L>>9fA1^A2^A4kA5jA6sUY|P%^Al>4s6`>>9lA1Lv4`v6^hL>>UsJ]5'+ 'I]9Qc4Rc9NIG1bL>>5^>9jA4lh`|1>%f>5k>9gA4R>hN|1@%1Y]6`c1Lc6[>UW]@a5?a9DPA4FPhCW'+ 'G1~kAR>>4g>6N>>9Rv1fA4Nv6khf>Ug>[>4W]9Yc4`c9LIG1uNvg>5f>6Rv0kA1Nv6fhR>>21k>L]5'+ '[>9Wc4Yc9`IG1E%IB6P7ALE8WB6N5`B5HI@6P7AJE8W@6N5`@57G1F%1FX2>X2BX7Dm0Fm0Pm1@m7?'+ 'X2@V9CCA0PCA2PC2G1Hx?X2@X2CX7HX7PX9Cm0?m1Dm2PDJ6DDJ7>X8?CD9>CL2>CL2DCA3>NG1D%1'+ '3N>N4kN4g`5`>N8^W9gA3`?L4I?L4W?N5`?L8J?Q3FPJ4?PJ5?PL5EPJ8BPY3Hm4?m5>DJ5Em8CDR8'+ 'EH`8FFN8HEL8DC2G1Pxg>3g>4R>>5lA6Lv7s3Q]4R]5Y]4Fa5HWqb2s3s4l>5gA6Nv8k>3W]4Y]5Q]'+ '4Ha5DWq>xQc6Lc7W]3Da4FX5HQq@xWc6Nc8I]3Pa4HX5DQq~19Qc9DPhDDhDHhDFhDEhDChDBhDJqu'+ '19mqE%Uf@U`>@UJ?@U`?@Uf@U`>@UCXUBP3qF%U@PEUBH3qH%UNIqD%UNAqP%UBQG3bUEQ&&'; K = 126; // Key pos (char) counting down. ('B%?KAG@B@@p"%2_>>AC%]>j>H>G2e%O2O1DAY>I>W>6GA9Q>J>:K:%?A?%P>E1E>A>?>A?F>H1D>P'+ '1C>20B>@AF1D19,&GC1@>B1%?@1?17,&,6,5,8,4,3,>12,0,1,').match(/.{2}/g).forEach( function (v) { X = X[u](String.fromCharCode(K--))[U](v); if (K === 92) K = 91; } ); /* * Initially JSON, but got lost in compression work + a somewhat bad design * on the obj. to begin with. Is eval, at least for now. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ try { eval(X [u]('*')[U]('f') [u](')')[U]('d') [u]('(')[U]('b') [u]('&')[U](']') [u]('%')[U]('[') [u]('#')[U]('}') [u]('!')[U]('{') ); } catch (e) { console.warn(e); } // Scaling function function z(a) { return a.slice().map( function (v) { return v * Z; } ); } // Tile painter "normal tiles" function e(k, d, i) { for (s[Y] = k, i = 0; i < d[L];) s.rect.apply(s, z(d.slice(i, i += 4))); } // function _(d, i, q) { S.width = R; for (i = 0; i < d[L]; ++i) { s.beginPath(); F[q=d[++i][0]] ? F[q](d[i]) : e(f[d[i-1]],d[i]); s.fill(); } } F = { $ : function (d) { // Expand a tile (e.g. add border on top // of "normal" bricks as with the "in-air". _(Å[d[1]].concat(d.slice(2))); }, b : function (d) { // Replace colors. (Used for bushes.) _(Å[d[1]].slice().map( function(i,x){ return(x = d[2].indexOf(i)) > -1 ? d[2][++x] : i; } )); }, f : function (d, i) { // Free-paint (fill). E.g. "hill-sides" s[Y] = f[d[1]]; s.moveTo.apply(s, z(d[2])); for (i = 3; i < d[L]; ++i) s.lineTo.apply(s, z(d[i])); }, d : function (d, x, y, g) { // Diagonal lines. s[Y] = f[d[1]]; g = d[2] * Z; y = g > 0 ? 0 : 15 * Z; for (x = 0; x < 16 * Z; x += Z, y += g) s.rect(x, y, Z, Z); } }; // Main function. function xMx(h, k, i, j, t) { Z = h || 1; R = 16 * Z; D = document; C = D.getElementById('m'); // Doc canvas c = C.getContext('2d'); S = D.createElement('CANVAS'); // Memory canvas s = S.getContext('2d'); C.width = 3392 * Z; C.height = 224 * Z; c[Y] = '#5c94fc'; c.rect.apply(c, z([0, 0, 3392, 224])); // Blue sky (rest is tiles) c.fill(); for (k = 0; k < Ø[L]; ++k) { // Loop coordinate array. This has fixed _(Å[Ø[k]]); // order. t = Ø[++k]; for (i = 0; i < t[L]; i += 3) { for (j = 0; j < t[i+2] * R; j += R) c.drawImage(S, t[i] * R + j, t[i+1] * R); // Apply tile. } } } xMx(); // Load main. ``` [Answer] # Python ~~1331~~ ~~1326~~ ~~1314~~ ~~1272~~ ~~1268~~ 1217 bytes ## (code: ~~219~~ ~~214~~ ~~202~~ ~~186~~ 182, data: ~~362+750=1112~~ ~~363+723=1086~~ 346+689=1035) The idea here is that I first generate a map one 16th the size in each dimension, where each pixel is colored by the index in the tile map. To ensure that the same pallette was used, I first combined the given tile map and the map into a single image. From this and the tile map (both minified pngs) we can now regenerate the original map. (The code for this process can be seen below the submission code). It should be noted that I saved the tile map as a file "t" and the generated map as an image "m" EDIT: I started exploring how the ordering of the tiles influenced the compression, and for the sake of exploration I generated 10000 random permutations and compressed them with this result: ![result](https://i.stack.imgur.com/GUY1r.png) This was all with the tiles in one line, as that reduced the code quite a bit. I tried similar things with different configurations (2\*16, 4\*8), but none with a better average result. Assuming that png would compress better with greater continuous similar regions, I built a tool that would let me move the tiles around, and using what I perceived to be a more continuous image I got the tile image down to 723 from 750b. EDIT2: Afte rmuch (much) more analysis on how png actually works, and a lot of experimenting (still ongoing), the images have now been compressed even further. Link below updated. I'll write more about this analysis later when it is complete. New images used are here: <https://i.stack.imgur.com/gofpw.jpg> Here are the other images generated in the process: <https://i.stack.imgur.com/9s1GD.jpg>, though some are a bit outdated because of above edit. ``` import PIL.Image as I O=I.open t=O("t") m=O("m").load() o=I.new("RGB",(3392,224)) s=16 for i in range(2968):y=i/212;x=i%212;v=s*m[x,y];o.paste(t.crop((v,0,v+s,s)),(x*s,y*s)) o.show() ``` The script I wrote to reduce the map is pretty crude, but here goes (also might be outdated because of changes above): ``` from PIL import Image blockSize = 16 combined = Image.open("combined.png") tileImage = combined.crop((0,224,256,224+32)) w,h = tileImage.size tiles = [] for y in range(0,h,16): for x in range(0,w,16): tiles+=[list(tileImage.crop((x,y,x+blockSize,y+blockSize)).getdata())] referenceImage = combined.crop((0,0,3392,224)) w,h = referenceImage.size mapImage = Image.new("RGB", (w/blockSize, h/blockSize)) colorScale = 256/len(tiles) for y in range(0,h,16): for x in range(0,w,16): i = tiles.index(list(referenceImage.crop((x,y,x+blockSize,y+blockSize)).getdata())) mapImage.putpixel((x/16,y/16),(i*colorScale,i*colorScale,i*colorScale)) mapImage.save("map.png") ``` [Answer] # Perl 5 + PNG: 689 + 593 = 1282 A failed attempt to replace PNG compressed tile map from Christian's solution with Perl code. In the end it is 65 bytes longer. Takes [the same PNG tiles](https://i.stack.imgur.com/FxmZE.png) on input and generates a PNG on the output. Usage: `perl mario.pl <tiles.png >world.png` ``` eval'+s/\d+(<?)(.+?)\1/$2x$&/ge'x2?$x|=$_: map{/A/&&y'{}['Y';push@l,split"";y/D-IMNOY[|_@-_/EF@EE}JKLY~__@/; s'@Y'YY'g;s'y@'yy'g;s'@E'DE'g;s'E@'EG'g}($x)x$_ for@z=qw(256@ 1 4<19@MNO14@MNNO8@<6@I 1 5<8@MNO16@M3NO16@< 2 22@X57@8T3@3TX14@X11@3T4@TXXT56@YY 3 203@3U 1 16@X3@TXTXT21@[|9@[|18@TXT14@T5@T5@X2@X2@X5@T10@2T6@Y2@y10@YY2@y12@TTXT31@QPS 1 5<2@H45@< 38@[|162@U3VU 1 5<17@H30@< 28@[|133@[|14@[|21@PPWPP 1 4<11@A3BC7@ABC15@ABBC3@<10@PPRPPC48@2<69Z2@15Z3@64Z2@101Z< 1); $p=GD::Image;use GD;$f=new$p(3392,224);$k=newFromPng$p('-'); copy$f($k,map$_*16,$i%256,$i++>>8,31&ord,0,1,1)for@l;print$f->png ``` [Answer] # JS: ~~4012~~ 3921 chars JS is used to unpack many Unicode characters and write an img tag which src is the image given in the OP, saved as PNG, compressed, encoded in base64 and trimmed. ``` document.write(unescape(escape('🁩𫑧𘁳𬡣👤𨑴𨐺𞱢𨑳𩐶𝀬𪑖𠡏𤡷𜁋𡱧𫱁𠑁𠑎𤱕𪁅𥑧𠑁𡁕𠑁𠑁𡁧𠡁𣑁𠑁𠱋𮡺𠑅𠑁𠑁𡰱𠡍𥡅𥡣𫁐𮡉𥁁𭱁𠑁𡀸𭡌𠑁𬑁𡀸𛱐𮑁𜁂𡀸𫑄𩰸𭡐𮀸𥠫𫑇𠑁𠑗𣡫𫁅𤑖𤠴𜡵𮡤𤰴𬡢𤑂𤱇𥑓𡡉𜑭𡡍𫁉𥑅𬠰𠡷𭱣𣑍𬱨𥡄𣁺𭡸𢰲𬁍𜐶𠡅𤰷𬁤𣱭𩡑𫑶𝰶𬑫𡐲𣡲𩱄𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𠑁𜡍𣁸𜡋𥡷𤁏𨡡𥐶𤠯𥐷𣁣𬠯𝐱𞑎𚱈𤁵𣁑𢡘𡁤𪱗𫁐𪱦𝑎𮑘𢰯𚱴𩡒𩡸𛰶𢑗𣁳𭁮𩡢𪱗𪁐𪱦𝑎𮑘𢰯𚱴𩡒𩡹𩑇𪑂𪠷𨡮𤀳𢁘𫠲𡡏𫡦𫁃𮠳𬐳𞁤𛱘𩁩𪑈𚱇𝱤𛱕𤁮𨑫𜡖𣱫𩠱𣱹𜱋𛰫𩁦𥁦𪑓𢁩𫡏𡡎𝱗𣡈𫑪𜑆𚱪𨱬𮐯𜱱𦀰𩠯𩡥𪡪𩡉𫡌𞑧𩡹𜱊𡡬𥀵𢀫𥁣𫁹𭠯𬡘𜁘𞁮𪁲𪁅𢡈𪡆𞁎𮑒𦡕𚱒𛱫𜱊𨱲𛰶𜐲𫐴𭠶𚰵𥀯𬁪𤁂𮠶𨡫𤁔𪡨𮀷𪑶𤡶𪑶𝡖𞑆𞑣𛰫𩡫𡐷𠱮𦑔𬑑𦑣𣑱𜀴𝁫𩐴𬠰𨠴𬠫𫁦𤡦𜱍𛱔𝡖𩡈𥁒𛰯𪡢𢁥𩱚𤠳𢡎𫁔𬁈𞑔𞑋𚱫𛱷𨰸𫱂𨡺𣁤𝀵𬡈𦑩𝑒𜑊𞑨𥁰𜱸𥀹𢰫𫐯𭡂𞁥𥑅𛰹𡑏𚱍𦐷𩑒𨑕𩑏𤁕𦀶𣠰𦀯𤱶𬀯𮁁𣡱𢱓𛱮𬱴𨑂𫁈𨱫𜡖𣱫𩠱𤀰𬠶𥀯𠱶𬑔𣀰𫠴𠠰𫁂𛰰𬠶𣠰𥠯𦁺𣱶𚱗𮡷𜁇𜑪𜡰𡡫𥀵𢀫𥁤𡰯𪱶𝑲𚱐𝠷𚰵𫰫𛰸𪰶𫡏𤁱𛱮𩑣𭠫𭠱𣱮𛱈𛱚𬡺𠡡𥀫𭁦𥁘𦀯𛰶𠠹𥁘𩡇𩐱𭱏𚱕𞑈𡰵𢁳𦑬𨡧𝱺𩀷𜑥𝐫𚰴𦁖𣰫𩱴𤰯𪱶𝰶𝡺𛱮𠑚𦀶𩀷𣡗𛱤𜡕𝁦𮀲𪑢𩐳𚰵𫑍𞀳𩐹𦁵𩡶𩑆𝱔𭡙𥁕𭠵𨠫𚱵𭠯𫀷𜁺𤱈𥑑𠱋𢱧𭑏𪁺𪑊𡀷𩡄𝁉𥱦𦡸𤁈𦑣𡡸𬑅𡑗𨑅𝑮𥱯𜡳𭱵𥡃𫱊𤱕𠠸𝱚𩱲𝰲𨑆𝱱𨑕𠠱𜱘𞑢𜡵𮐸𨡦𠐶𛱲𜡥𛱸𝱡𣑅𛱒𭑨𤀯𜱰𜰴𡰵𞁭𝑗𝱇𝑋𭑑𩁖𩑖𢀲𢁷𮡔𡐶𛱲𜡥𜑸𚱭𪠹𫱡𥠯𡰯𤱮𤀯𜐷𣑆𩡥𮡙𬡥𥁓𫀯𢁐𩑮𛱪𞀹𞁲𬑥𭡒𝱈𢱦𨠵𬁈𞁲𞑋𨰯𛱔𬱷𥠹𝱎𪑴𝑎𡱖𛱌𣡃𛱌𤁅𝱐𭡋𝑮𬠸𩁸𪑮𜀫𝡤𞁉𛱥𫁐𛱸𝱍𪁘𩑺𝁮𩁔𮁲𫁣𭱐𪡙𝠳𬀲𩑰𤡔𞁯𢡋𚱪𩁃𩠯𬡔𭡷𩁺𝁤𜁳𞁤𜡕𭑰𩡏𫡳𫱏𛱡𥐸𝡚𞁢𚱧𩁩𫡱𨐯𜱇𝑋𜑕𭁯𥀲𥱈𛱬𢱥𞑍𞁎𛱑𣑸𥀹𣡦𨡔𩑬𝡱𥰰𬀱𢱧𭠵𤑮𛱘𣡄𛰰𪡍𬰯𤱘𜠰𜡰𩑩𫡴𬑒𥁯𣀫𥡊𛰹𮡑𤁸𣁺𣁐𜱖𩁬𤁱𦁫𬀷𢱨𭠰𫀯𢱫𩠲𝱯𢀴𬀵𪱶𝑹𭀶𥱶𩑭𫡤𬡮𝁙𝡃𛱬𤱦𛱣𜁄𞁕𞁹𥀹𝑑𥠯𞑁𜑃𩡺𢁯𜱷𪠹𬁔𮀯𛱧𭁋𦡔𩑬𝡱𥰱𬁺𢑍𞑊𩡹𬁈𞑵𝡂𚱋𩑚𣀫𢠶𚰳𭱫𝱊𫡚𩡓𫡳𫱇𛱡𥐸𝡚𞁢𚱫𩁩𫡱𦀯𞐱𝡊𭱅𝱊𬡚𩡑𫡳𫱇𛱡𥐸𝡚𞁢𚱫𩁩𫡱𦀯𮑥𬱴𬱆𣡹𝡹𥰰𬀱𢱧𭠵𤑮𛱘𣡄𛰰𡁍𜀯𤐯𠡒𥠲𤱵𝠸𫁐𦡕𠱶𤱘𞁱𤠯𨡵𩱦𪑈𫑡𛱧𩡪𣁌𠡔𨱵𬱬𭁋𩁓𫱌𚱕𢠯𜑺𤐯𞑁𮡎𤀰𛰷𠠳𠠶𪱎𭰰𠑕𪁴𣑢𥡍𫁃𝠲𬡪𩁡𭑔𢡒𭁦𭠰𡰲𤡐𢁃𜑩𠡳𦡱𨠯𠠲𥡗𣑦𦡪𭱳𣑅𬑪𞁕𫡆𣱹𩐱𚱋𮡬𣡚𪱐𛱎𡐶𜱐𤡦𝁹𝑎𞑒𥑉𨡹𨡸𤱣𥐷𢠷𦀴𬡏𥐱𫑑𭡹𭁡𫠴𭠸𦡣𪐯𫰶𠑍𝑖𞑰𣱋𩁫𝰷𝀰𫡡𩑹𢑮𞑘𭁄𝁘𚱣𭑑𛰳𡡂𥱣𫱦𠑐𠡶𭡁𬱋𠑁𠠹𢱃𩱁𩱅𫱕𡡁𠡁𢡑𫱋𠑋𠑓𠡑𥑁𥑉𫑃𠑧𠱯𤡅𢁴𚱑𪡆𝑷𜁵𝑅𢁓𝠳𨡶𪠷𡰹𫁥𦡔𨡘𣱰𬰳𜁥𬁪𜑹𞁖𣑮𠡘𥱹𣱂𩑶𡰱𭱉𢑤𮁈𛱱𥁘𝱤𝁦𦐳𬱲𮡡𩡡𝑬𢡮𚱺𮁍𚰸𝑆𬑰𣱃𣱬𫑣𮑶𩑈𩱮𣁩𝡯𣁱𜱨𞑪𩑺𭁙𥑃𜡘𩁖𢡑𥁵𤡈𩑘𡡋𝠶𤱧𮡨𨡮𦡷𪐸𤑢𫑒𠡫𫑶𜠷𜀯𮁶𦡗𫑫𚰱𮡡𦁏𥡐𠰯𨐶𮡌𝑤𥑰𬁘𥡓𥑇𩑌𨰰𪁦𪱙𣁹𦑵𮠹𢱑𥁰𩁢𭠳𮀹𪡥𤱶𣱰𭁲𫡕𜡔𝁐𜀳𢑏𨡹𪱴𪰴𢐶𦁚𮡄𞑌𮁔𥑆𝑣𦁖𡁤𚰲𣡳𨡷𨱌𬑵𥱹𥁁𬡋𠱷𬡱𪱋𜁶𣱧𝑒𥑁𬠳𫁯𢑃𠡡𥡁𫡆𞑔𫱋𡁣𭑐𫰳𬑏𝰹𣑢𨐳𜁮𮑱𨡓𝱌𝑄𨱯𣀳𝱚𭐲𤁣𠡇𢑧𠱱𠠳𫱋𢁇𤠴𠱔𬁥𣀶𤱒𨑭𬱙𥁷𬡲𥁗𩑐𤡥𝁺𬑪𪑘𝁃𝠯𜁃𨑲𣁲𞀯𫁺𨑑𢱱𪑴𫁐𞁑𜱶𮠲𢠷𭐳𨰫𫱚𛱌𝠯𤱙𩑒𥑃𨑱𨠴𤡦𨱕𦁸𫑺𠐲𬀴𩡸𨡢𜠶𣑂𜑣𞑬𣰹𜡄𢱫𣡁𥁒𤑘𢁰𭑁𢱭𣠲𤑁𜱶𮠲𢠷𩑺𤱧𚱲𫁳𬀴𠑱𤐰𠡎𡡈𚱊𦁧𥡕𡱢𣰯𩱸𬡥𫠸𦀲𩁵𞐸𤑪𚱘𝱘𤑐𬑧𭱂𣡗𢱨𪠰𫱙𬰫𝑔𩡅𥐯𝁴𬰵𫠹𡁐𝑘𥠶𪑱𚱋𮀷𜰹𭑢𥀳𢱡𡁏𡡋𚱍𨑖𝐱𥡍𨡳𩱂𬡥𫠸𦀲𞑭𪁁𞑘𣠵𫡷𢱱𪑅𩠷𩀲𭡶𥐰𠠹𬱍𮁌𣠯𫁵𝡙𠱱𚱲𣁙𩱷𢁖𮠲𥐷𛱑𩁖𮁲𜑴𣁮𡑋𬑊𤀵𨡌𮑗𜡤𞑂𡁥𛱐𦑮𭠷𝱥𩁣𦡕𝡣𬱨𩐳𣱁𥑕𠑃𨱡𝰴𢁓𠡷𥡁𢱴𢀯𬁁𞁋𩱆𤱩𛰰𪱦𡡁𠱰𤡐𚱔𤁩𩱁𥑯𫑌𭑓𝱱𠑰𠱋𩱁𢑧𢡑𡑆𤑅𫱃𠱯𠱕𠡂𤑁𢱑𪱯𠑆𢑓𥑁𠱫𢡋𠑁𤱃𫠶𫠯𤡂𠑚𠡋𞑄𛱰𩱷𢑧𫁥𪀯𜁧𨱆𤑃𬡒𛰶𤑐𠱯𠑕𫱶𩁊𢁸𤑁𬑕𥁶𪱺𝁯𠑆𢱊𜱩𩀹𥑁𠱫𡑲𜑐𚱱𠑁𤱃𥑵𝑌𬑯𠰰𠑱𠑧𬑁𫁁𤑕𠑃𪱊𢱁𠡓𡑬𠑁𬁃𤱧𠑅𪁊𤑁𢁷𮐹𝁤𫡄𠑉𤡆𡑕𢁕𩱆𢡨𜡙𡑱𨠯𜱭𢱑𭠳𠱙𠑨𝰸𨱹𠱚𬁣𭑈𬑎𮁉𠡧𬑁𤱎𥠹𜁯𣑃𢑅𬀱𫠯𤱧𠑉𪁓𜱓𨰹𢱁𠱩𥡐𩁊𡁷𬑁𠱎𥠷𤱵𫁂𮡘𫠹𭡥𦡣𮡷𡡁𣀹𥠷𤱵𫁂𢁚𛰯𢑂𜱈𩑧𝁁𩑱𫡥𥐰𫱐𮑫𠑂𞁏𪁁𬁦𤱧𡁂𤑁𪡷𞐰𥑺𝱕𣡖𠑁𡱃𩱁𨱨𪱯𠑃𢱬𡁤𥀵𭡚𞐵𬡥𨱁𫱊𩐰𩱢𫱵𞑴𝰹𠡧𠰹𡱃𩱁𢑨𪱯𠑃𢱬𡁤𤰵𝑒𪱕𤑄𭡖𩐰𬡰𤑥𜱶𫠷𮡆𠠹𠡏𞑚𝑓𩑬𠐯𞑱𝁧𮁘𥑙𪁶𢡶𞁎𣡎𜑴𞐸𬁶𨱙𤑧𞑓𪁴𫐳𡰱𞐯𪱪𢑐𝡪𠱄𬑨𠱆𢠱𪱐𤱭𬱨𬡍𪁹𚰱𠱳𥡅𫁑𪑕𤑩𪱗𪠶𤑌𢀰𩰰𬑃𤱩𤑓𪑕𥁔𠠴𬑬𢀱𤱙𣐶𩰯𭱷𣠯𩠰𜑤𭡷𡰹𫠸𩀫𚱯𮑕𡡤𪡮𜱑𬱳𨱙𣡤𢰳𜰴𬀵𥡢𦁙𞐲𦁭𠡲𤁹𢡂𣁫𠡶𥀲𭡘𩁴𜡏𜰹𛱷𪰶𜁦𜑊𢑶𫁒𫡌𣱺𝠷𬡏𢑢𝡷𣠳𬑖𭱒𩑵𭑸𭀯𣁆𭀸𞁇𥠯𦠵𞑷𢡌𜱇𡁘𤱨𛰫𨑥𥡗𜐶𣱤𡠶𚱴𛱙𩱅𭑑𠰹𤁡𜑤𜠳𥐷𩡮𛱄𥀷𬀫𥑇𡑉𝡶𮑉𬀰𪁑𜁆𭑎𜱒𢁕𛰲𫑡𚱗𣑃𜱴𫡮𜱑𬱳𨱢𣑭𢱐𪑮𫁌𬱮𢱐𤑢𡑵𤑃𞑐𨐰𩁭𜱘𝱦𪠹𡁔𛱰𚱫𡱆𢑡𪀶𡰴𦐵𫱴𢱴𢰫𪑴𮀶𮐳𭁈𝱐𩁂𦑩𭑘𮁍𣑹𝡘𮐵𥠹𜱲𜱁𡑪𩡙𭁤𢱈𩠱𬠵𮁵𭑨𭑦𥱍𩡫𣱃𦁉𡁥𫡴𨑵𝱢𫱤𭠷𛱨𢠱𬰯𬑄𠡮𥑇𣑤𮑲𚱸𜱱𥡱𡑏𪑴𮀹𝡱𤐵𝡊𦡐𬠴𭡌𣁐𭑸𩁙𝁧𨐷𥡶𬡷𥁹𭐳𭑨𝱴𭡈𪁴𩡖𠡕𪱁𭡑𜠹𤁡𭁖𜠳𝀯𨰳𛱇𤠷𥑈𩡸𭡣𮁙𜱶𢁚𜀫𛰰𞁸𩠰𩡄𭡊𠡁𥰹𩁵𮑢𫱈𬡋𫱆𪡩𦡫𜑑𞁅𞁮𥀴𢑋𤡆𠡺𤁊𣱧𪱱𠑃𡑆𤱮𡱖𤑓𥡂𢡕𡑬𤑓𫁁𚱍𞑘𝁥𥁶𢑚𡡐𥁡𨱚𝑂𩑣𫑧𥱏𢡭𩡑𦑆𛰳𥁹𠑇𩁑𫡒𢡕𠑒𥀷𭑷𩑃𠱮𤑇𥡗𚱮𢑰𩑚𤐶𞁤𩑹𭱺𝱺𤱄𢑯𫑢𩁒𥑦𛱎𤁊𛱚𩑚𞐰𬁑𥱃𛱎𛱵𝡂𫱁𢡖𞁣𜁂𬡔𢡂𤑡𞁚𭐳𭱏𬑳𞁍𪑩𥡵𜑧𤑆𛰱𥁹𠑍𞑂𢡕𡐹𝰫𞁫𬑅𩱅𥡣𬱌𠡁𥰹𦡵𮑣𫱄𬡎𫱇𬑊𥁖𡁙𮠶𛱌𪰶𠑩𡑖𤑴𤱖𠱨𠱏𫰲𭡶𠑣𡡐𤱡𨱔𝁈𝑓𨑄𦑯𫑢𞑒𪱕𛱆𤁊𢑺𭱈𜑓𫁂𡡡𡁚𜰳𪱇𡡥𬱍𬑳𬁖𩡎𠡲𮀱𫡆𝑹𨑄𢑯𫡢𜑩𫰫𫑬𭀸𬡆𥠸𝡄𨱫𮑁𥱯𝱗𫡴𜡱𝱢𞁦𬱢𩡪𣀲𩰴𬁒𮁘𩁥𥑵𢰷𤱆𡁑𥰴𜑤𡐱𤡐𡱒𤡌𜱋𭱊𠱶𝁰𝑦𝁊𠱶𜡇𠡌𪱁𭁔𜡴𦁤𭀱𣰳𝐯𭰰𛱇𩡬𠑸𠱋𫰫𢑂𢑕𞑊𬑸𭱷𮑱𜐳𞁺𦠴𫡢𥡯𢱩𚱢𣡙𥑯𢡃𭡹𡡂𣁫𠡶𥀲𭡘𩁴𜡏𜰹𛱷𪰷𡑦𥡁𪑃𪱮𝑑𮑷𬡵𝰲𜡗𠡶𮡺𭡧𢡈𞐶𤡨𜐱𬁦𢰯𩀫𠡯𥠫𤐴𢡣𩱎𝡥𨑎𨱙𝡴𞁬𫰳𦁉𩡬𠡦𝱆𜁂𨡴𬱷𡁃𮑹𡠶𮠹𤑏𨡭𢡙𥡦𥑧𮠹𛱸𤁭𢡩𦁓𥑳𫀸𣱯𬱉𢡤𞁂𢁙𡐱𣑱𜁲𝱤𣡆𥁩𪡣𢡊𝐷𣀫𝱶𮀹𬁗𥑚𬡪𠱫𢱄𭡫𭱗𡰫𩡄𞁷𝁇𫐱𩐲𩡬𡁮𡁬𪐯𤁬𣑴𩡵𫑬𪡊𩡦𞐹𣰯𬡺𬱁𩡚𩁧𢑦𫡦𥡬𡱡𝁷𬁃𩰷𝑍𡡰𭡭𭰯𣑏𭀳𢰳𩑗𦁲𠠯𦀷𝑖𣱁𫁲𩠱𦁪𝁆𬑙𮑘𜰳𩠴𥡬𞁶𞁈𜡘𜁪𩱤𣱓𪑂𤡮𮁦𢡯𭁎𞀫𡠵𪁸𣑯𫐱𩐲𩡬𠑓𢱁𝐵𫡳𢱔𩱸𢑇𠑴𬑘𮑗𣁌𩡈𪡥𞁦𦐫𨡆𝱚𚱫𡡤𠡗𬑡𬁬𨱦𢡖𡀳𪱏𩁺𥁈𢡑𭱫𠡁𤁺𠡲𬱗𥐫𤁏𚱁𠑶𥐱𬠲𭱦𜑌𜁋𥡐𪱪𠠳𥑦𨱬𠱃𨱉𦑅𨑧𤡉𫱁𤐵𢱅𡱑𤑋𥱅𠡅𬑑𩱸𢑅𠱖𤡋𦡂𥱯𝡦𥱹𜐳𥐯𪡲𪱮𫑁𦡹𥑉𢑧𩱡𬡈𤁧𥁋𩠷𭐷𛰫𫑴𚰰𤠳𪱉𣑓𠡁𫁕𤁓𤡑𡑱𩰷𪱉𣑓𠡉𣑅𨑧𤡉𫱁𤐵𢱅𡱑𤑋𥡅𥡯𡑡𝱲𭁔𩐴𣑣𫁃𡁕𞐲𥱹𜡄𤑦𫡮𩐴𡰶𣁎𢰱𬰯𢱍𭰯𨡘𬑋𝱺𠡎𮁹𩡨𢑑𝱋𚱊𩑄𜡧𪡖𤀴𢁉𭡫𭱗𣑦𝱂𩡈𪡥𞁑𤑋𝱐𛱅𞁚𞑚𫱋𨡔𤁌𞁎𞐯𩀸𝡵𨡢𮡃𛰸𮐰𡡴𩰫𬑦𤑇𤡦𢡯𬱧𛰱𩰫𤁏𞑷𩑸𝑯𛱹𩑓𛰷𭱃𣡣𜑮𝡁𬡆𡡋𬐵𜁺𢀫𝑡𠐲𤑦𥡐𢑌𢑶𪰰𥱕𩡺𠑦𫡮𨱷𫱐𜡦𥱐𝡺𝱫𡑤𝑪𤁥𝑬𢁥𝑚𩱣𢁲𝱘𝀸𨡦𝑖𞁏𨑧𭁕𛱸𥁩𚱺𢡚𬡏𦁦𪡡𩡺𞑴𢱨𜡵𨱈𩑉𠑩𥰯𛰸𥐳𮡐𪑹𮐲𩐴𬡶𞑃𥱧𬀷𩑮𣑥𡀷𣡺𜰸𨑔𪰳𛱩𝰯𨱬𠡢𫱐𬑮𡑎𚱘𮑗𢑴𛰲𝀸𫡔𩠲𭡨𡠯𜰷𢠵𬱊𡱳𩠱𝡧𫡳𛱇𬡚𥡁𢁗𦐷𭱖𡱗𪱌𝐯𥐲𝁈𞑚𜐯𣱡𩱎𥑐𜑔𪑏𛱌𦡌𡱗𩡺𩑥𮡨𭀷𜰴𪐯𨠹𪰸𜡅𪡗𤁹𞑑𜁸𫑴𠡏𬀰𤁣𡡂𫁰𡁵𬑢𭡫𡁵𫰷𛰳𢡑𡰶𡀶𬁸𡁦𫀸𫁩𣁦𞑵𤁊𜀳𞑲𝁒𩠹𚱹𩑢𠑒𬠯𚱍𩐱𡀲𡁵𤡰𣱣𡡂𫁰𡀫𨰰𭑰𢁤𤡐𛱵𥱧𩑋𪠫𢱣𤠯𦑎𦡩𣁦𞑵𤁊𜀳𞑲𝁒𩠹𚱹𩑢𠱒𬐳𛰫𢱢𝱮𝡙𭰯𨡚𝱩𣰹𪱊𭡳𜱺𢑅𭡉𬡨𮡕𥀯𝱬𫱈𪑯𛱧𭀰𢑆𠐯𚱕𞁪𥑋𪱣𥡊𮁁𩑦𝱺𠱤𤡨𭁨𣡣𛱨𫁫𠱤𫑔𩰯𣀸𮐰𢁒𥑐𜁘𮑃𞑑𫡶𞁳𠑲𥑘𠠫𦀵𨡹𡡑𜁸𩑡𠱎𥁰𜡷𫑏𬱯𥁳𮑕𡠵𛱵𥱧𨑋𪠫𠰫𤑘𢱍𞐯𡡯𢁡𪐴𤁹𛱇𩡢𩱺𬡍𥡷𮑺𪁏𮡉𤑚𦀸𮐰𡱸𥑐𜁘𤱃𞑑𢡦𞑊𠡇𫱮𡁱𬡫𭠸𡡔𩡃𦡉𛱶𛱚𠡡𤡨𫑃𥡫𤡷𝡱𝑆𞁏𪑯𦁱𭠰𠠶𩱓𬠵𥁹𢡑𣰳𡡑𢡦𚰵𠡇𫱒𜁁𡱘𪱐𜀴𬑆𭠸𮐰𡱒𥑐𜁘𮑃𝑑𭀯𪡐𢑖𡀷𨱆𠰳𚱅𞁬𥑉𭑁𡁲𪑅𝱍𩁂𜱥𢡦𡁯𬑅𝡲𞑁𩁯𡰶𮁘𞁏𩱤𬑈𩰷𬡆𩠶𦐹𬑅𥡁𤠱𮁃𩁵𣱧𨡶𣑶𠠸𥡂𞑕𞁨𭡩𚱔𮁖𬠫𜱘𩰲𨠯𞁏𮑵𦡄𮁳𬠶𥀯𤑕𫡸𣡑𩡁𫑚𭑷𞑐𣡷𝁋𝁒𞀯𨡨𬠫𭐸𡱧𞑒𞁄𭡩𚱔𮁖𬠫𨡖𮡢𭡊𝰯𡁨𮑕𮡙𩑍𨡐𜱈𠰵𥁸𪡷𬱯𭡯𤡍𜱉𩑮𫀲𞁺𪀯𪡈𪠵𭑇𛰱𝁷𨑶𜱈𩱏𛱌𦡌𡱗𩡸𭡘𣱋𛱮𤀯𜠳𫑤𬰸𜡍𪡖𩠷𮁁𡱦𚰴𩱏𢡌𮑎𮀹𩑎𮡦𣱡𭑄𩱶𪡈𪠵𭑈𛰰𝁷𨡐𜡈𩱏𛱌𦡌𡱗𩡺𩑥𮡧𭡺𛰱𠠹𢱶𣑄𤁅𠱒𬐯𛰴𤁓𪡪𩠷𥑐𪑋𡡨𦀵𮡄𩁐𤑒𝠰𣱃𢁺𛱁𥱖𡁈𞀯𣱅𮁵𤀸𝀫𩑖𪀯𞑙𜑐𢰯𭠯𬁶𠑲𭱶𪰵𭡮𝡵𭡘𚱏𩠶𢁍𡠵𤰯𝡨𝡺𮑥𩠵𞁦𝁁𡱋𨡐𜐷𦁰𬰹𮁥𩠵𦀫𬱄𣑨𭑁𭡪𩱷𜑥𞀫𦑮𜑉𞁏𣑈𣱁𭡱𩑈𝡥𜁈𪑣𩠯𮐸𞁶𠑦𪐲𬠫𩀱𩠯𥁙𡀳𦡘𣁺𦁈𜰹𡱶𞑣𫡹𣐴𨠸𪰯𩁊𜱈𞀫𛱺𠑺𮁁𪱡𜐯𮠲𬱺𩱦𣀸𬠯𦑂𣑔𥁲𪑺𣑴𫐳𜑈𢀷𡐫𢡐𪡸𡑺𪱯𣠰𞑧𤁍𭰯𩡬𝐵𚱉𞑆𣡦𚰷𬐯𞁭𭱐𬱹𭑘𫑵𭡮𝡎𩠷𨡐𡑦𝐶𮡺𞑹𫡣𩡺𝰯𣑄𤁅𠱒𬡈𛱐𨑸𭑂𭱵𭠯𝑅𚱷𦁖𚱣𭰸𩑃𝀹𡡈𬡁𞁊𩡶𭰰𡁳𬡎𡑸𪑐𞀴𚱦𥡸𝰫𦐱𢁐𛰹𝱱𭡷𫡷𭡫𮀫𫡭𭑶𦀫𣱦𝱘𣱅𭠹𝱺𪠱𮡮𞁦𮠷𛱁𠑐𥑇𥁲𜰯𤁡𨡧𛱋𞀷𛱗𠠸𤑁𞑍𦁂𣀶𡀳𩠫𮑤𜁙𜱢𣑂𠡅𠱘𥡷𥁧𣱋𦑐𪡦𩁸𜁣𪡂𤑩𠡏𮐯𪁏𤡧𠡘𠑇𣱳𝡁𢑱𫑖𭑐𣱺𤁹𤡆𤁧𚰹𦁴𪡇𮡨𪐱𤁩𥀶𚱭𦑱𢱄𭱮𫠶𛱺𜐯𩁬𪀳𞑢𨱦𝠹𚱢𚱯𚱂𞑆𞁚𮁳𤁏𣱦𚱷𩁕𣡰𝱷𮀯𭡕𫡄𞀫𫠳𢑑𦐶𝰯𪱗𭡂𦀯𡑨𩠹𦑈𦡂𢁶𠰶𢡦𫱆𞁸𦑨𮁌𞑥𢀵𭀵𝡬𠱧𬡏𤱥𨡲𛱐𥠹𜡥𢁦𥡰𮀯𝡍𮠯𫱗𜡃𭱮𣱹𞁙𮀯𬡑𤡆𚱏𣠹𨑳𭱦𫠱𞁸𤑘𢀯𥠰𫁑𠱦𝡳𡀸𩱩𜱨𩁅𠠯𜀷𤡯𮁪𬱔𝑉𮐳𬁗𢱩𩰸𢠵𚱶𞀹𩠳𦡙𩀯𥰳𢀫𫱔𤀯𪀷𦑊𠱳𛱊𮁨𤀫𜑒𢑕𝁙𛰳𤱥𣠯𜁁𬑋𚱢𞑹𩱵𣀫𭠫𢑇𠰯𨡆𡱦𝑃𛱨𣁇𥑥𪁄𫱱𞑶𬀴𢡡𣱓𩑢𬠯𤁘𞐲𥱈𩠲𜑸𛱱𪐫𛱂𛱡𢡩𩰴𬀵𤱧𬡪𬱮𢱏𥁐𝱺𫡹𤀳𦑆𮁦𜡶𢠶𪁊𡑵𣱐𠱚𤡯𠐯𮡰𡡰𛱃𣱉𩑸𤡂𚱥𝡗𥐹𠱸𦁕𭁈𢡏𣡬𛱮𬠫𛱌𡁶𛱱𝁶𮁂𩡦𪰯𭁅𜑑𩑅𝀲𫡶𠱶𫁱𠑉𩠷𮁐𡱶𞑪𥡬𠱋𛰵𢁲𝑬𛱸𡑦𝡑𤑉𪰫𭀳𜑄𭡋𬀵𫑁𭠰𝁒𫁥𜑺𣡑𤑑𜑲𝐲𥁺𩁦𝰶𭡵𮡷𬡹𝱏𢀹𥱖𛱸𬱮𬑁𪁩𝁷𫠯𨑧𫑋𞁍𩠷𬁐𡐯𦡧𦁆𛱖𞁪𤑥𫠫𢁸𝑕𦑺𝱬𨠳𥱢𠰯𥁨𭑢𜡵𦠶𠱃𭑱𜡤𪰸𭱶𭱨𛱘𭁣𣰯𭑪𪀯𥡆𩠫𡀹𦑔𜑐𡁙𢐰𡑒𛱮𪑦𢡐𝱈𬡋𠑕𛰵𩁐𥑉𤐯𢡎𠡱𢁹𡡪𤑶𣱷𭡑𛱐𛰫𭡴𦀰𡱴𫡺𣑸𭡸𤠯𦁎𨱏𛰯𬡩𛱆𡐹𚱔𞁅𝁷𫡱𭑫𭑃𢑶𮡸𤁫𫠸𪠱𫁂𢱦𝁶𛱒𜁕𝁷𞁊𭁎𬁈𮑃𫑭𩁂𭐳𞑵𡱚𦑌𜠹𢰶𩱰𨱣𝰱𚱡𦀴𝀷𬀲𚱄𨱑𝑷𛱱𮑦𞑆𮁦𬱒𤡒𠑢𮠯𪡮𞑪𫁩𝁷𫀯𭡅𛱎𚱥𤁺𢱑𨱸𦡶𫱦𭑗𝰫𡡒𛱨𡁷𫐰𜁫𩡉𢑡𦐱𤱮𜑉𞑐𦁈𞑨𥱕𩁎𝁸𣑢𞁑𩠱𮡘𡁶𞁇𝁶𮁒𢁦𫐯𬑈𩰯𫱧𪁩𝁸𫠯𜱄𝑈𨡄𮡨𪠯𩑰𣱘𞐸𤁵𥑧𮁫𮠯𢐹𩡎𠱕𬠲𛰯𠱑𣡎𨐶𫱌𭱐𪑢𝐫𚱷𫱱𢐰𢁂𛱅𣀸𨱖𜀷𛱊𤁡𤀰𡱤𜱶𞑆𮁦𬱒𤡒𠑢𮠯𪡮𞑪𫁩𝁸𫀯𭑅𛱎𚱥𤁺𢱑𨱸𝑶𫱦𭑒𦡋𥑎𮠯𜐴𩑫𮠰𮡉𢱣𜑓𢁸𢠹𛱘𫠳𝰶𡁗𮡺𬱮𝑰𩡩𪠫𭡡𝁤𞑃𫡄𚱱𢀯𞁘𡡥𞑈𡡅𡡳𤁏𣱦𜠫𩑉𪡗𩠸𝁔𝀱𝐴𛱐𬁸𮡅𭑎𦀯𭁋𚱗𢱎𫠯𤀵𝱎𤑵𝁥𤁡𦡩𩑇𬀳𜰴𤡆𥡶𨡪𜁕𦠰𤀵𭱺𪁶𭁘𮁘𥠯𭐳𪠰𫑉𫱂𦡇𥑦𪐹𮡈𫡕𩠳𭱺𫑪𭠵𠑥𡀯𥑇𝁁𫡋𫰲𥠯𩑶𤑅𝑢𢁪𣡷𠡐𥑂𝁴𚰹𣡪𪡑𥀱𛱮𨡸𝡄𡑖𠐸𪡋𤁨𨐵𪡺𭑐𝱯𩁺𮁵𨱌𩑚𫀫𩑶𤱙𪑧𡡫𦡒𚱌𜱍𩑤𤠯𩡄𣱥𤁺𪁦𮠴𩑐𩠴𪀷𜀷𭁭𜁙𠡱𢑁𩑩𬰴𡰴𤱚𭱎𨠫𭐰𥱂𥱢𡡧𫁥𢱢𞑷𝁷𢁴𜑤𞁕𡑃𪱯𪡪𮡬𫱱𬁙𞑚𨱴𮁣𩑔𪁔𮠲𬠵𥑣𛰴𭡙𣡩𨱪𝱰𢑷𪰲𜱧𠑣𥑅𮡏𢡸𜑑𨡌𭱂𣱋𠱙𫡅𛰫𬡺𦁵𮁣𚰹𢡮𩡗𥑩𫀹𮡊𣁪𝑳𬡄𫑤𦐱𜱧𭁹𦡹𜡖𜁳𨱳𣱗𝡵𤁊𮁰𤁡𞁸𫡶𩑃𜱆𫁌𬁦𤑸𤰴𝡢𢱷𞑮𥱳𛱈𞑦𬁢𪱄𭁲𬑚𤐫𦡳𫁸𨰫𦁨𥁏𭠹𝑺𢁉𫡢𥡕𤱨𚱺𝑌𪐵𞁮𠱭𞑔𦁇𞐫𭠫𪱔𭁲𬑚𤐫𦡳𫁸𨰫𦁨𥁍𜑎𝁕𩡎𜡺𡑐𪑳𫠵𬁈𫁑𨡈𮡐𮁄𜁯𢡵𩑔𣁵𬑹𞁑𨡧𩱇𢡹𤁵𫑁𦑵𣑎𭱁𢁆𝑈𮡓𤁃𩰲𫡲𩁪𢁨𤱔𞀰𫡺𫱎𪀴𜱯𝐵𥑅𮡏𢠸𜡄𦑵𣠵𣰫𦡂𣑔𫑦𣡁𚱋𪡚𛱸𩑷𩡆𝑈𮡓𤡸𢰯𝱤𜁸𡁑𠑁𡁍𣑷𛱱𮁈𦑫𩑬𚱄𢱂𨑪𭡄𞁁𢁷𫱌𪐸𥀳𬁑𡁂𞁁𡀴𬡌𚰶𤑥𡡍𣰹𢁔𜁯𣁵𚱔𩑬𠑍𞐳𨠰𫱌𪐸𥀫𬁂𣑤𮡢𜁙𤁩𞁪𝡰𠠸𥡷𨠰𨱐𪑳𭠷𬁂𝁕𭰷𜁤𤁓𩱵𝰵𣠶𥑁𮠳𩁶𤱧𭑌𮁐𛱮𫱹𜡌𣡥𫰵𡱊𣁧𠑁𠑁𠡊𤡕𝑅𬡫𢠾').replace(/uD./g,''))) ``` Demo: <http://jsbin.com/fojidejoco/1/> PS: I know it's a little bit cheating (even if the rules allow it), but at least, it gives us a goal: do it in less than 4012 chars. Tools used: * <https://tinypng.com/> * <http://xem.github.io/miniURI/> * <http://xem.github.io/obfuscatweet/> ]
[Question] [ ## Challenge Mark is a student who receives his `N` marks in a concatenated way in a one single line. The challenge is to separate his marks, knowing that each mark can only be `0` or `1` or `2` or `3` or `4` or `5` or `6` or `7` or `8` or `9` or `10`. ## Input `N` natural number and one line. ## Output A set of natural numbers. ## Example ``` N, One line------------------> Set of marks 3, '843'---------------------> [8, 4, 3] 1, '0'-----------------------> [0] 2, '1010'--------------------> [10,10] 3, '1010'--------------------> [1,0,10] or [10,1,0] 4, '1010'--------------------> [1,0,1,0] 9, '23104441070'-------------> [2, 3, 10, 4, 4, 4, 10, 7, 0] 12,'499102102121103'---------> [4, 9, 9, 10, 2, 10, 2, 1, 2, 1, 10, 3] 5, '71061'-------------------> [7, 1, 0, 6, 1] 11,'476565010684'------------> [4, 7, 6, 5, 6, 5, 0, 10, 6, 8, 4] 4, '1306'--------------------> [1, 3, 0, 6] 9, '51026221084'-------------> [5, 10, 2, 6, 2, 2, 10, 8, 4] 14,'851089085685524'---------> [8, 5, 10, 8, 9, 0, 8, 5, 6, 8, 5, 5, 2, 4] 11,'110840867780'------------> [1, 10, 8, 4, 0, 8, 6, 7, 7, 8, 0] 9, '4359893510'--------------> [4, 3, 5, 9, 8, 9, 3, 5, 10] 7, '99153710'----------------> [9, 9, 1, 5, 3, 7, 10] 14,'886171092313495'---------> [8, 8, 6, 1, 7, 10, 9, 2, 3, 1, 3, 4, 9, 5] 2, '44'----------------------> [4, 4] 4, '9386'--------------------> [9, 3, 8, 6] ``` ## Rules * When several outputs are possible give only one output. * Only mark of value `10` is on two decimal, others are on one decimal. * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963) * No need to handle invalid input * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~23~~ 21 bytes *-2 bytes thanks to Fatalize* ``` h~c.{ịℕ≤10&ịṫ?∧}ᵛ&t~l ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P6MuWa/64e7uRy1TH3UuMTRQA7If7lxt/6hjee3DrbPVSupy/v@PVjI0NDQwNFDSMY39HwEA "Brachylog – Try It Online") The input is a pair `[Line, N]`. This is my first Brachylog program, so there is probably a lot room for improvement. It is very slow when the length of the line > 7. Explanation: ``` h~c.{ịℕ≤10&ịṫ?∧}ᵛ&t~l h The first element in the input ~c is formed by concatenating . the elements in the output array .{ ∧}ᵛ AND For every element in the output array holds that ị The element converted to an integer ℕ is a natural number ≤10 and less than or equal to 10 &ịṫ? and it has no leading zeroes (*) &t AND The second element of the input ~l is the length of the output ``` (\*) `ịṫ?` checks that there are no leading zeroes. It converts the string to integer and then back to string and compares to the original string. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` ->\a,\b{b~~/(10|.)**{a}/} ``` [Try it online!](https://tio.run/##jVNdTyMxDHzfX5EHdGkh0HjjfIGOP3LdhyIoQoK7U/uESvnrZeLs9k7LVlBFqSPN2DO29@/D5jkcXl7Vj7X6qQ6Xt8uVWd7t7t7fFzOyb1fz8/Pdar/YH26a9Z@Nmj0//X7YztWuUerl@nGxvL9Y3CDerl7VenZmzRnNm/3BGaUTO3059btVv5JRbJTrGgLQTsMEaLumBYQsTaMAIWsIMPcVzAhOwYRQDOKGv0MCsskAto4sM5ONIzyAEAkByFt81VMe0SiQqTWacybbltMS2f86AzLAWU6htP/@hru80SsPDZFsID0tNgoY2IAAVQlVY/DBw2BIrEdwFnnA@uG2tRQeZT5d7Y6z4XR3iunCqA3ysBdamBwVK1h/tBXk7m3WQsRGJ7BTtsmH5H3LerQu/ojPUjINumvgJSNX11QU2BRiTFZ/1jzUHfIEaUSUuB81O59Tdv7TZtS@OSmYBzmul9c1SKIxaO/ixE6B249Z8E5qFpbYT4FAylgyx9mP7VeZ1FMkS79yctcN8vVjYdYnvyc@Dja7dHKw1VOp2X0A "Perl 6 – Try It Online") Anonymous code block that takes a number and a string and returns as a Match object. ### Explanation: ``` ->\a,\b{ } # Anonymous code block taking params a and b b~~/ / # Match using b (10|.) # 10 or a single digit **{a} # Exactly a times, being greedy ``` [Answer] # [Python 3](https://docs.python.org/3/), 47 bytes ``` lambda s,n:[*s.replace(b'\1\0',b'\n',len(s)-n)] ``` [Try it online!](https://tio.run/##fczBCoMwDAbg@54it7ajjma6TQWfZN3BusoEF6UtQ5@@E9HbGIH8OXx/xjm8BkpjW@nY12/zrMFLKu9Hf3J27OvGcsM0asXkksRkb4l7kZB4xGagj3UBKtibJZg5WM@nJMvbwcEEHYEXh9F1FPjml4eolsF1r5diYkftfyYx@0nz/Io3VMU5xTQrLhuMXw "Python 3 – Try It Online") Takes the "one line" as a bytestring with raw bytes `\x00 - \x09`. If it's not acceptable: # [Python 3](https://docs.python.org/3/), 56 bytes ``` lambda s,n:[x-48for x in s.replace(b'10',b':',len(s)-n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFYJ88qukLXxCItv0ihQiEzT6FYryi1ICcxOVUjSd3QQF0nSd1KXScnNU@jWFM3TzP2f0FRZl6JRhpYFggNwSSYBVRsaKKpyYVQYWFhZmhuaGBpZGxobGJpCpH/DwA "Python 3 – Try It Online") Takes "one line" as bytestring. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~17~~, 12 bytes ``` \ÓòÀGjí1“î…0 ``` [Try it online!](https://tio.run/##ASoA1f92//9cw5PDssOAR2rDrTHCk8OuwoUw//8xNTEwODkwODU2ODU1MjT/MTQ "V – Try It Online") I was content with 17 bytes, but than 05AB1E came along with 13, and I couldn't let a challenge go unanswered. :D ``` \Ó " Put each character on it's own line ò " Recursively (repeat until an error happens)... ÀG " Go to the "n"th line j " Move down a line (this will error if there are exactly "n" lines) í " Remove... 1 " a '1' <0x93> " START THE MATCH HERE î " a newline <0x85> " END THE MATCH HERE 0 " a '0' ``` Hexdump: ``` 00000000: 5cd3 f2c0 476a ed31 93ee 8530 \...Gj.1...0 ``` Alternate solution: ``` \ÓòÀGjç1î0/J ``` Unfortunately, this replaces `10` with `1 0` [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->n,m{m.sub!"10",?A while m[n];m.chars.map{|c|c.to_i 16}} ``` [Try it online!](https://tio.run/##jVNda8JAEHzvr7jah7yc4Tb3Tamlv0NCUakoNCpaKUX97ene3qWxJtqG43IHM7uzk8l2P/2q50/1cLTi1aHKd/vp/QDEgD@/sM/F8v2NVeNV@Vjls8Vku8uryeZwnB1n@cf6dcnAnE71hs3HkrPMKZmVD8O@Z8TGjjPFmSzvAhwQLq6BCS4isEAgCLiGRSAIDgks/wZzQrP1NhI5nomq/kflqZNHeCFBKKVA2A4L4Sgc5WCPMHVc4WI5SyWg4JnyHkQRVgEgfrmHJZDiaQVi0b6aPdyTnxr1WBAG@vVjMUsUZBg8JAWACqzRRuPgxqkLblRgiaGbXcS2eAnfs2y9k8Lc8i6YEXitfRrHNgUO32kcGPpnXEN7Gr9tCopnDms4L5w2TutCXdjnSHBieWrvmkniQVNd1boBQY1wxlonum5Aq6GpZsggS@ezaCipvfNS9@QpuiqpuW@kySQ1VsByGQZDS9ubR6yQYkEsSf0bLtniDCDVY0Cl8rprSxQOiUi1Ulxpj7nT7Q@o1NVfNY5zFgQv3Y0gxFlD/7L@Bg "Ruby – Try It Online") This may turn out to be not the golfiest approach, but it looks like a fun idea to temporarily substitute `10` for a hex `A`, which incidentally is also a high mark (if we consider A-F grading system :)) [Answer] # [Haskell](https://www.haskell.org/), 68 bytes ``` n!('1':'0':x)|n-2<length x=10:(n-1)!x n!(s:x)=read[s]:(n-1)!x n!_=[] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P09RQ91Q3UrdQN2qQrMmT9fIJic1L70kQ6HC1tDASiNP11BTsYILqKoYKG9blJqYEl0ciyQebxsd@z83MTNPwVahoCgzr0RBRcFEUcnQwNBA6T8A "Haskell – Try It Online") Greedily take 10s as long as there are more digits than marks remaining. [Answer] # JavaScript, ~~57~~ 52 bytes ``` n=>g=s=>s[n]?g(s.replace(x=10,`x`)):[...s].map(eval) ``` [Try It Online](https://tio.run/##dZHdasMwDIXv9yQObEayJf8M3D1IKSRkadjIklCP0rfPZHY1ZoOv9B1JR8efw33I4@1j/35Zt/fpuKZjTac55XTK5/XyNqusb9O@DOOkHgnhuX/0Xfd61lrni/4adjXdh6U7xm3N2zLpZZvVVdlO9YGsKJ/@AhQA/8tGyghYIbZJqEmiEGMRiAjBVwRY9lGMCKY8gwgVrywij@CwMqDcQd6xY3HgAjXsWXB1eyx7nZHttVYsvUEkIUJgF5gNNTxgmQDBeR8aQZDlGKLlWlBeuKTA1tfor43gUGiUPC1Frn8dNe6PNpT7jx8) [Answer] # [Python 3](https://docs.python.org/3/), ~~71 68~~ 59 bytes down another 9 bytes thanks to ovs. ``` lambda n,s:[int(c,11)for c in s.replace('10','a',len(s)-n)] ``` [Try it online!](https://tio.run/##bZDLasQwDEX3/YrsnIBbJEvyozBf0naRpgkdyHhCMpv5@lQpFOpkwKsjXx9fTffb9zXTOpze17G9fH61VbbL69s53@rOIjbDda666pyr5WXup7Ht@togGGtaY8c@10vznJuPdZq3xFCTrUxkMk3z9IdQEfwHTgECFoweMH7AkjJHCMyMEIoROms4JQS3HYcIxTdEkwHBY5FBzQQvXtTjIx/0BH6vF33eO5WU15GtiTqLCaL4KOJ4b8ItA9GHEA@lmCTFRFLWDTrRSkKh5L@y6FFx0nUQJ9lvmA9lEsWtzPoD "Python 3 – Try It Online") I was iniitially trying to use `str.partition()` recursively, but using `replace` smacked me in the face not too long after. Can anyone improve on this? [Also, here's a TIO link that I used to make the test cases into something more copy/pasteable](https://tio.run/##jZNLTsMwEIbX5BRWNm4kt/LE4xcSXASyYNGKSrRUkAUIcfby205KlaaCynLs@pv3zOGzf37dm2O//ujv6ro2SsjARi7nfvfiISjBSpiuIoB6Hsug7qoWCGmap4CQVgTM/IWpzInXtyKicK74P0IgqwiwNaSZmbSf8ADhJByA3hRXWenilYAwtUpyjKTbtFoifZYZCAOOeSWR9vcz7umOXFn44Ek7kvPO@gyDdTjAKsGqd9ZZBOgCywnO2T2wdtx1MYVLqk9XsmO0u56dFHSSKAmyCM@1CHJiLLH2FJbL@xBmMUSsZIB0iDpYF6xtWU7axZ74mE2G0e9ysFkjl6gpeaCD8z5oeenzaHfU43IifD4PpWZjY4jGXnRGyZvJBuPojhnc6yookSi0NX6mpyA7lDnzJttMUjn84AhCEU1mONpp@MVNGkSylqHl8l46yJZhYZZX54lPhY0mXC1siSnZ7DDMx/fDi7gTD9t@vVvhvO0XcikbzKbYYJrS32K7F2n2x@fHvWy64/krHm6rm8Pbdt8v6vLZLL6@m6ZeAds99YtENs3xBw "Python 3 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 98 bytes ``` n!x=[y|y<-s x,y==take n y]!!0 s('1':'0':x)=do y<-s x;[1:0:y,10:y] s(x:y)=(read[x]:)<$>s y s _=[[]] ``` [Try it online](https://tio.run/##JcpBCoMwEADAu6/YiBADFhLoaev2I0soAQMVbVqMhyz49yj0Mqd5h7zEda01qUIsh4y3DGUQoj0sERKIV8o2uddOo7Yai6HpC//2YIcWZXAX/joFxVC/xTBx8WjG7plBmgwvYva@fsKcgOC3zWmHDu6qddbZtp4 "Haskell – Try It Online") or [test all!](https://tio.run/##dZNNb5wwEIbv/IrBqrQgGcnGH9g03nsPPfVIUUSUVRslIdHCAdT2t28HY@@STbKyDF49r2femeF3Nzwenp5OWZrX9bd@LPY/xuND/6vYN3hqT306uWb@O98UA0x0dm7sHg/Qw9ymKUuGbMd39Y7t6il39y@wYl8bXrN6phy3FpmpnnOXHQ/dfTO1dX7zZT/AnAxw65qmbU/P3UMPDp671@@3kP3MOnqXF3t4xTRGyDrn7vIcxsMwDkniH@ASgAYykRIjBYE3PwqNoSC9GQqizZPlv4ynhF2RnmURKFPCGb9iEOAMfURIfAz9KRpOPQcvx@LfKqJ4CjL52d105QJmU1IKzqSUnFWRRqxEHxTwTpBxLYeKwlnKMX1pLWflskrOGdYFpYhavxZBeXnEfTmfa6RSUnGmOblKs/IokhpfzhGxorLSSit0po0kAZY@MSRV3NkaBg9LY9pNTQTTH9RkMbvwm7IodKVL9BbieFKd7Wi/B3vbIByjGBQby4zSRqlSkjAh6kxbH87EjNcX5e@TW7d8Cc@MrirDyCXbGDPeon0BKv@@ba0Uyhor1GUO1moJH8zGVERILSqrlGBflai284PK0FZPCx/vovG2jeaosThRQloVba8J8iDwd4Tx8vs6L2rzUUhJ3n818m0jrTDvG7l6MbGR7ek/ "Haskell – Try It Online") ## Explanation The function `s` does all possible splits, for example: `"1010"` becomes `[[1,0,1,0],[10,1,0],[1,0,10],[10,10]]`, note how the longest splits end up at the beginning (because `1:0:y` comes before `10:y`). With that in mind, we can take all these values and filter the `y`s out where `y == take n y` which keeps also splits that are shorter than required. For example with `4` we leave the list the same `[[1,0,1,0],[10,1,0],[1,0,10],[10,10]]`. Now we can just get the first element in that list because the inputs will always be valid (eg. `5!"1010"` would give `[1,0,1,0]` too, but we don't need to handle it). **Note:** I somehow miscounted.. `y==take n y` is the same length as `length y==n` :S [Answer] # [R](https://www.r-project.org/), 63 bytes While the length of the string is larger than `n`, substitute the next 10 you reach for a `":"` (the ASCII character after 9). Then split into numbers by taking the ASCII value of each char in the string. ``` function(n,x){while(nchar(x)>n)x=sub(10,":",x);utf8ToInt(x)-48} ``` [Try it online!](https://tio.run/##ZVLLagMxDLz3K5b0sBtwwLIlP/rIvffeSg5t6JJA2UCa0EDpt29l@RFKwXgteaSZWfk4jw@reTxP29P@MA2Tuiy/v3b7j/dh2u5ej8NluZ6Wl8fP89sAWi3uFgy4P5/G8Hx4mk58vcLwM4@DVV0f0PbL23X3ElSHqrObm3EAzuuc1Sk2HIOGkuKWIGn7N60k3x2OGaL4zCD8D1JSHfnCWNCICNqXe2birlyetOSVAq86qQGjeowRtEnLAOginnFRVkKb66fuKRZrxKwetINc5@WWLx0fhAGYwTtyxJpdwNbeC4bqrnNPDtJ/21SjVrtqNBlJiOqVWLIzLLw2pSbTyV5k136Aqg9cFKIO5AKRwTYoatAoJKEqyweSZlj9QOLUwXkf2hgaVa13YtHLuc0HLcUQLdXxobgioc3ktohJFVzc83DI@oovMxGMle4ZKd6CAwZGfgMWIzVvWQsUtDQor0L2PGmqzxKvE2pTiDa4xm9zx838Cw "R – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-plF`, 39 bytes ``` $a=<>;$_="@F";s/1 0/10/ while$a-1<y/ // ``` [Try it online!](https://tio.run/##K0gtyjH9/18l0dbGzlol3lbJwU3JuljfUMFA39BAX6E8IzMnVSVR19CmUl9BX///f0MDQwMuk3/5BSWZ@XnF/3V9TfWAIv91C3LcAA "Perl 5 – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 128 bytes ``` import StdEnv @[]=[[]] @['10':t]=[u++v\\u<-[[10],[1,0]],v<- @t];@[h:t]=[[digitToInt h:v]\\v<- @t] ?n l=hd[e\\e<- @l|length e==n] ``` [Try it online!](https://tio.run/##LY2xCoMwFEV3vyJbBxWUbtagQzsI3ez28oZgUhNIYqkxUOi3N42l2z2XA2cykrtoF7EZSSzXLmr7WJ6ejF5cXMh6QAqAmMahrg6NT7jleWBsa0uAusIC6qJCLEJbkt7jqQf1s0DoWfvbMjhPVBOQsb@RdY4YqgRIxuR@mbeRbvaKSEodxtHz1KekI8e9maoYP9Pd8HmN5XCN55fjVk/rFw "Clean – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` .œsù.ΔïTÝÃJ¹Q ``` [Try it online!](https://tio.run/##ATAAz/9vc2FiaWX//y7Fk3PDuS7OlMOvVMOdw4NKwrlR//84NTEwODkwODU2ODU1MjQKMTQ "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##JY49TgQxDEZ7n2I09bKy45/YDXQUdEiAZkuQKKgott6KI0DLGbamjmi50vCNNopkJ3kvn9@Pzy9vr6vk7ePTYVn3v5/H8bP/@xrnh/E9Pu6W@/U0zvN0dT3Ny7yb5sMN1m5NU1JiEhIWpnYpeilGTYXNTLgzFVmVcNt2E2FAjbpwCDlZDw@HFGkk@E054DvgaFBwW5Q4ZnF6pHsDt6F44ozekzfP1CtLAYJHnCsSqFNmCLrCQGrlm2oYj0oTOf8) **Explanation** ``` .œ # partitions of the first input sù # of a length equal to the second input .Δ # find the first partition that returns true when: ï # each element is converted to integer TÝà # and only numbers in [0 ... 10] are kept J # then join it together ¹Q # and compare it to the first input for equality ``` [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), ~~70 69~~ 59 bytes Takes input as `(n)(line)`. ``` n=>s=>(a=s.match(/10|./g)).flatMap(x=>x>9&&!a[--n]?[1,0]:x) ``` [Try it online!](https://tio.run/##hZPdbuIwEIXv9ym8N00iBfDE47@VQp@gT4BykVJgW7GkKmjFxb47Hf@ElNrtRpZjS/7GZ05OXvq//XH99vx6mj32j5v97DA8bS7b9nJol8d2Wfbtcf6nP61/lwvg/@aLXVXNt/v@9NC/lud2eV7au7uf/Wo2O3T3K6h59@tcXdbD4TjsN/P9sCu3JRNVWRgUBfvwVBVbLNjK1AxrJrofnxAghN8AV4Qnhxs6DBxuzsfDwGtIAfENUHuCDW8Bpo7YZxz/g9fpjZaQRgBHROA6kBFpqP@a0V3OiTDcRtcsKQOuU7QWeONGA8BFEcsQZv1wcDO9xtntU58lFdTAFRRJK9pjRClaJErcB0KtpJJkhDJYTCB68UTJcebhetq4791l/RRcZf105jg2a6kkG1RDZgQBIyWv7Ss/Rztyl4O73FAdY7mRykjZYDGFU15J62WYsauwkL42Zt0Bp4obpbXhxU1Ho5axovKGab/ORweFtMYKOWZuclp4EXaUKKLkpIqmKhQcKfSU21glxsaTwutI@WCTUUC4pSALtPKDTaEJiLCvF2Pt55BNmf1xEYvcX45fBcUKkwtK6N3p6C7v "JavaScript (Babel Node) – Try It Online") ### Commented ``` n => s => // given n and s (a = s.match(/10|./g)) // split s into marks; a '1' followed by a '0' is always // interpreted as '10' .flatMap(x => // for each mark x: x > 9 && // if x = '10', !a[--n] ? // then decrement n; if a[n] is undefined: [1, 0] // yield [1, 0] : // else: x // yield the mark unchanged ) // end of flatMap() ``` --- # JavaScript (ES6), ~~64~~ 59 bytes *Saved 5 bytes thanks to @guest271314* Takes input as `(n)(line)`. ``` n=>g=([...s])=>1/s[n]?g(eval(`[${s}]`.replace('1,0',10))):s ``` [Try it online!](https://tio.run/##hZPditswEIXv@xS6KMgG1dFYo7@FbB8kGDak3rAlxEu87E3ps6ejH8ebldoaIUugb3Tm@Pjn/n0/Hy4vr2/fztOP8fq8vZ63j8dts@u6bh7a7SNs5t15@H5sxvf9qXnaff01/x6eusv4etofxoaDkFyAbNv2Yb4epvM8ncbuNB2b54aptuEOFWcfnrZlmw3bOcFQMDV8@YQAIfIOuCGyONzTYZBwdz4fBkmiCkD9AxCRYNMlwYLWn3H8Dy7KGz0hvQKJiCBtIjPSU/@C0V3BiTTCxgpWlIHQKXoPsg@jB5CK5zKE@TgC3K@vZQ770mdNBS1IA7xoxUaMKEOLQkn4QGiNNpqMMA75CmIUT5ReZpmup0343kPVTyVN1c9gTmCrlmqywfRkRhKwUPrWvolztqN2OYTLHdVxXjptnNY98jWc@kb6KMMtXaWFjrWx6g4EVdIZa53kdx0tWpaKJhpm47oeHVTaO6/0krnVaRVF@EWiypKLKpaqUHC0smtuc5Ucm0iqqKPkk03OAOGegqzQ6w82pSYgw7FejnWcUzZ19cdF5LW/HP8WFK9cLSip96BjuP4B "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // main function, taking n g = ([...s]) => // g = recursive function, taking s // (which is either a string or an array) 1 / s[n] ? // if s[n] is defined (i.e. we have too many marks): g( // do a recursive call to g: eval( // build a new array by evaluating ... `[${s}]` // ... the string representation of s[] where the .replace('1,0', 10) // first occurrence of '1,0' is replaced with '10' ) // end of eval() ) // end of recursive call : // else: s // return s ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 78 bytes A nice one-liner using the streams API. ``` (n,l)->l.join(":",l.split("10",l.length()-n+1)).chars().map(i->i-48).toArray() ``` [Try it online!](https://tio.run/##jZTBbpwwEIbPy1NYPtlaQDa2wYQ2VR@gufS43YO7IRtvWYPAiRRF@@zbMaA2UlOIhTQYf/z@Z8xwMs8mabvane5/Xbunn409oENjhgF9M9ah1yhCMOaFwRsPwTpf9w/mUKM7ANA8ZgYWd3vkCETkYvTd99YdUUOrEbxEmzHOSnfIoc/oSlzc0OS2SU@tdQTf4LhJh66xnmDOwqSp3dE/Epq4Lac0PTyafiA0PZuO2OTWJlLT1Ldf@968EHqt3jP93Np7dIacyGQJTJr@ONC3GcBzP4m41BERI6ylwHT2/g7CAWFLQAYAZ3yRER9g5AeYEphMcCal5KxYRHnwJcuSsyxcGedsMU8FeMFZzhdFQzVkkatcgdNcy9WEBMvXElLgL8/A5bIcD3oaYF0yrXKtVCZXvfKgynReFHq1sFKoUpdCLR9BASRUVYlimZvs6pwDV8KZCVmqtc9IrtazFPpvPS//bYI3b07NasI9fY02D20/9q2FpmQVsp/Glbn7YL7dBirIzm3d9TWggAP/BeEdRjcIx7iaoZfB1@e0ffLpuCcJ@Hbabmf3tELRBn4I/2B4/8PhP2lcrr8B "Java (OpenJDK 8) – Try It Online") --- **How it works** ``` (n,l)-> // Lambda function taking int and string l.join(":", // Join the following array with colons l.split("10", // Split the original string on "10"... l.length()-n+1)) // But limit the parts to the difference between the length // and expected length, to only remove required number of 10s .chars() // Convert to an intstream of codepoints .map(i->i-48) // Remove 48 to get the numeric value of each codepoint .toArray() // Return an int array ``` [Answer] # [Red](http://www.red-lang.org), 91 bytes ``` func[n s][while[n < length? s][replace s"10""a"]foreach c s[prin[either c =#"a"[10][c]""]]] ``` [Try it online!](https://tio.run/##XZBBbsQgDEX3cwrLvQAGA6Zq1TvMFrGIMqSJFGVGSao5fkoWVWEkFvjZ@v/ba74d13yL6TK8H8PP0scFthSf4zTn8v2AOS/f@/h1wjU/5q7PsCEpxA7TcF9z14/QwxYf67TEPO1jXkv9@Vb6kVSKfUJMKR1nf4cBDKCwwctfTYDqv9JQtKkC5hXwKwiA2pBiZlK@4qSRQyClz6eJVGVqAT0pR9U0IXtnnS3aTrj1M8o1frZIOl2E60FilNKQoMQ6sVZzo07ntBLnvbTh2dggwdh6Jw9Yolvja3gaiKPCQlnYcLDN3bgNHYw4PH4B "Red – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` Ḍ⁵⁻ƊƝr1ŒpS‘⁼ɗƇḢk⁸Ḍ ``` [Try it online!](https://tio.run/##VdE9SgRBEIbhq3gAg6rq7unZcxiKoYluIGZmTiSIkYkmJnsHYUBTBzzGzkVaeZtPRvh4oqmpn7663O/vWjvOT@v0vk4fy@Pydutfzzdn6/3rOn1@vywPx/lwvU7z7zettfPd6UnPiBUHLJgxYaCjqWRUKg5YMGPCQEdTo6rCngELZkwY6Ggab1C7XthTMGPCQEfTUkVDVpUUJWPCQEfTKbJWq2qUVdiTMNDRdMCkg1SNl9SuF/YEOprOHjpj1VKhIbNKQnE0PZbr@FWncK2W1chV2GPk76Ftc3zbHMQ2Q9r/wlFPU7Rd/79dtLDdDw "Jelly – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ô 0┤'ï╒Äì√¡ ``` [Run and debug it](https://staxlang.xyz/#p=932030b4278bd58e8dfbad&i=+%22843%22,3%0A+%220%22,1%0A+%221010%22,2%0A+%221010%22,3%0A+%221010%22,4%0A+%2223104441070%22,9%0A%22499102102121103%22,12%0A+%2271061%22,5%0A%22476565010684%22,11%0A+%221306%22,4%0A+%2251026221084%22,9%0A%22851089085685524%22,14%0A%22110840867780%22,11%0A+%224359893510%22,9%0A+%2299153710%22,7%0A%22886171092313495%22,14%0A+%2244%22,2%0A+%229386%22,4&a=1&m=2) It was very interesting to find a way to outgolf the V answer. ## Explanation ``` |!{11rJj-!}jJ |! all array partitions of length n { }j first element which satisfies: 11r range 0-10 J joined with spaces j split on spaces - set difference with the current iteration ! negated is true? J join with spaces ``` ]
[Question] [ # Execute a Lindenmayer System A [Lindenmayer System](http://en.wikipedia.org/wiki/Lindenmayer_system) (or L-system) is related to [Thue](http://en.wikipedia.org/wiki/Semi-Thue_system) and [Post](http://en.wikipedia.org/wiki/Post_system) systems, and is used in [botanical modeling](http://algorithmicbotany.org/papers/#abop) and [fractal generation](http://en.wikipedia.org/wiki/Space-filling_curve). An L-system is described by *string-rewriting* where a symbol from the symbol-alphabet is mapped to a *replacement* sequence of symbols. A collection of these mappings constitutes the L-system proper. The graphical output method as devised by Prusinkiewicz interprets the resulting sequence after the mappings have been applied to an *initial* sequence for a specified number of *iterations*, as Turtle-Drawing commands: forward, backward, left, right, that kind of stuff. This may require extra code to control the scale of the drawing as different iteration counts may produce drastically differently-sized images. Your task is to execute an L-system in the fewest number of characters. Your program must be able to render both the Dragon Curve and the Branching Stems from the Wikipedia page by providing appropriate input (file, command-line, but external to the source, please). ![Branching Stems](https://i.stack.imgur.com/CrqR8.png) ![Dragon Curve](https://i.stack.imgur.com/gVgzg.png) This is code golf. Edit: Here are some examples I've posted around town. [answer to SO/rotate-to-north {*Where I first discovered the L-system*}](https://stackoverflow.com/a/10036833/733077), [answer to SO/how-to-program-a-fractal](https://stackoverflow.com/a/12484638/733077), [answer to SO/recursion-in-postscript](https://stackoverflow.com/a/12392233/733077), [comp.lang.postscript discussion/recital](https://groups.google.com/d/topic/comp.lang.postscript/a_rx4K9PXPs/discussion), [postscript l-system collection](http://code.google.com/p/xpost/downloads/detail?name=koch.ps), [codegolf.SE/draw-a-sierpinski-triangle *{origin of the competition between myself and thomasW}*](https://codegolf.stackexchange.com/a/6604/2381). [Answer] ## Mathematica ~~200~~ ~~198~~ ~~188~~ ~~171~~ 168 Spaces added for clarity: ``` f[i_, b_, h_, j_, r_, n_] := (a = h; p = j; s = k = {}; t = Flatten; (Switch[#, 6, s = {a, p, s}, 8, {a, p, s} = s, _C, k = {k, Line@{p, p += {Cos@a, Sin@a}}}]; If[# < 9, a += I^# b ]) & /@ t@Nest[# /. r &, i, n]; Graphics@t@k) ``` Where: > > i : Initial state; > > b : rotation angle > > h : initial angle > > j : initial position > > r : production rules > > n : iterations > > > Production rules grammar: > > 2 = Turn Left (-); > > 4 = Turn Right (+); > > 6 = Push and Turn Left ("["); > > 8 = Pop and Turn Right ("]"); > > C[i] = Draw (Any number of symbols) > > Any other symbol = Do Nothing, just use it in producing next state (Any number of symbols) > > > The {2,4,6,8} sequence is there because I'm using `I^n` (`I` = imaginary unit) to make turns. Examples: ``` f[{C[1], X}, Pi/2, 0, {0, 0}, {X -> {X, 4, Y, C[1]}, Y -> {C[1], X, 2, Y}}, 10] ``` ![Mathematica graphics](https://i.stack.imgur.com/9jXlA.png) ``` f[{C@1}, Pi/2, 0, {0,0}, {C@1->{C@1, 2, C@1, 4, C@1, 4, C@1, 2, C@1}}, 6] ``` ![Mathematica graphics](https://i.stack.imgur.com/HChf2.png) ``` f[{C[1]}, Pi/4, Pi/2, {0, 0}, {C[2] -> {C[2], C[2]}, C[1] -> {C[2], 6, C[1], 8, C[1]}}, 10] ``` ![Mathematica graphics](https://i.stack.imgur.com/2VwUM.png) ``` f[{C[1]}, Pi/3, 0, {0, 0}, {C@1 -> {C@2, 4, C@1, 4, C@2}, C@2 -> {C@1, 2, C@2, 2, C@1}}, 10] ``` ![Mathematica graphics](https://i.stack.imgur.com/lXJIw.png) ``` f[{X},5/36 Pi, Pi/3, {0,0},{X->{C@1, 4, 6, 6, X, 8, 2, X, 8, 2, C@1, 6, 2, C@1, X, 8, 4, X}, C@1->{C@1, C@1}}, 6] ``` ![Mathematica graphics](https://i.stack.imgur.com/88sFG.png) [Answer] # Python, ~~369~~ 294 Not a winner but I'll post what I've tried anyway. ``` from turtle import* I=open('l').read().split() s,S,p=I[0],'',[] for j in range(8): for i in s:S+=eval('{'+I[1]+'}')[i] s,S=S,'' for k in s: if k=='[':p+=[heading(),pos()];continue if k==']':pu();goto(p.pop());seth(p.pop());pd();continue try:{'f':fd,'F':fd,'+':rt,'-':lt}[k](5) except:pass ``` Not good at golfing Python...... Maybe someone else can do it. ## Input Input is from an external file named "l" (no extension), with the following format: **Line 1**: Initial state (Axiom) **Line 2**: Comma-separated rules **Symbols** `f` and `F`: Draw forward `+`: Turn right 5 degrees `-`: Turn left 5 degrees `[`: Save position and heading `]`: Pop position and heading Other symbols are ignored by the drawing function. **Rules** A rule is in the format `"predecessor":"successor(s)"` Note that the quotes are necessary, whether single or double. `predecessor` must be a single character. Also, there are no implicit constants: You must explicitly specify a no-change rule for those. ## Examples ### Branching stems ``` ------------------f '-':'-','+':'+','[':'[',']':']','F':'FF','f':'F[+++++++++f]---------f' ``` **Output** ![](https://i.stack.imgur.com/586aV.png) Note that the source is modified to get this out put ONLY TO SCALE DOWN THE GRAPH TO THE VISIBLE AREA. The console is also used to hide the "turtle". ### Dragon curve ``` fx '-':'-','+':'+','[':'[',']':']','f':'f','x':'x++++++++++++++++++yf','y':'fx------------------y' ``` **Output** ![](https://i.stack.imgur.com/47BLa.png) Again, the console is used to hide the "turtle". ### Sierpinski Triangle ``` f------------------------F------------------------F '-':'-','+':'+','[':'[',']':']','f':'f------------------------F++++++++++++++++++++++++f++++++++++++++++++++++++F------------------------f','F':'FF' ``` **Output** ![](https://i.stack.imgur.com/N6kzg.png) Generations reduced to 5 here. [Answer] ## Javascript (179 bytes) Not completely sure this qualifies, as the rules object does all of the actual drawing. **Demo** (Dragon, animated): -- Expanded: <http://jsfiddle.net/SVkMR/9/show/light> -- With Code: <http://jsfiddle.net/SVkMR/9/> **Minified:** ``` function L(c,r,n){o=(function g(d,s,o,i){for(o=i='';a=d&&s[i++];)o+=r.r[a]?g(d-1,r.r[a]):a;return o||s;})(n,r.r[r.s]);(function z(i){r[s=o[i]]&&r[s](c)||setTimeout(z,10,i+1)})(0)} ``` **Readable(ish):** ``` function L(c,r,n){ o=(function g(d,s,o,i){ for(o=i='';a=d&&s[i++];)o+=r.r[a]?g(d-1,r.r[a]):o+=a return o||s })(n,r.r[r.s]); (function p(i){ r[s=o[i]]&&r[s](c)||setTimeout(p,10,i+1) })(0) } ``` **Input:** ``` var sierspinski = { r:{'A':'B-A-B','B':'A+B+A'}, '+':function(c){c.rotate(-this.a);c.rotate(this.a-=Math.PI/3)}, '-':function(c){c.rotate(-this.a);c.rotate(this.a+=Math.PI/3)}, 'A':function(c){c.beginPath();c.moveTo(0,0);c.translate(this.m,0);c.lineTo(0,0);c.stroke()}, 'B':function(c){this['A'](c)}, s:'A', a:0, m:1 }; var koch = { r: {'F':'F+F-F-F+F'}, '+':function(c){c.rotate(-this.a);c.rotate(this.a-=Math.PI/2)}, '-':function(c){c.rotate(-this.a);c.rotate(this.a+=Math.PI/2)}, 'F':function(c){c.beginPath();c.moveTo(0,0);c.translate(this.m,0);c.lineTo(0,0);c.stroke()}, s:'F', a:0, m:2 }; var dragon = { r: {'X':'X+YF','Y':'FX-Y'}, '+':function(c){c.rotate(-this.a);c.rotate(this.a-=Math.PI/2)}, '-':function(c){c.rotate(-this.a);c.rotate(this.a+=Math.PI/2)}, 'F':function(c){c.beginPath();c.moveTo(0,0);c.translate(this.m,0);c.lineTo(0,0);c.stroke()}, s:'X', a:0, m:5 }; var algae = { r: {'A':'B[A]A','B':'BB'}, '[':function(c){c.save();c.rotate(Math.PI/4);}, // save/restore will push/pop current state of context. ']':function(c){c.restore();c.rotate(-Math.PI/4);}, 'A':function(c){c.beginPath();c.moveTo(0,0);c.translate(this.m,0);c.lineTo(0,0);c.stroke()}, 'B':function(c){this['A'](c);}, s:'A', a:-Math.PI/2, m:1 }; var tree = { r:{'X':'F-[[X]+X]+F[+FX]-X','F':'FF'}, '+':function(c){c.rotate(-this.a);c.rotate(this.a+=Math.PI/180*25)}, '-':function(c){c.rotate(-this.a);c.rotate(this.a-=Math.PI/180*25)}, '[':function(c){c.save();}, ']':function(c){c.restore();}, 'F':function(c){c.beginPath();c.moveTo(0,0);c.translate(this.m,0);c.lineTo(0,0);c.stroke()}, s:'X', a:-Math.PI/180*25, m:5 }; ``` **Usage:** ``` var ctx = document.getElementById('l').getContext('2d'); // grab context ctx.translate(299.5,199.5); // start drawing from center, fractional pixels because the canvas draws lines centered on the x/y coord specified L(ctx, dragon, 8); // pass in context, rules object, and recursion cap ``` **Bonus: Golden Spiral** <http://jsfiddle.net/SVkMR/35/show/light/> ``` var golden = { r:{'A':'FT[TT]A','T':'+F'}, 'F':function(c){c.beginPath();c.moveTo(0,0);c.translate(this.m,0);c.lineTo(0,0);c.stroke()}, '[':function(c){c.save();}, ']':function(c){ c.restore(); c.beginPath(); c.arc(0,-this.m,this.m,Math.PI/2,Math.PI); c.stroke(); this.m+=this.d;this.d=this.m-this.d }, '+':function(c){c.rotate(-Math.PI/2);}, s:'A', a:-Math.PI/2, m:1, d:0 }; ``` [Answer] # Postscript ~~264~~ ~~298~~ ~~295~~ 255 Here's my attempt to do it differently. Rather than the macro-expansion that I usually use, this one checks the size of the execution stack to bound the recursion. If the bound is exceeded, it stops recursively examining the procedure and tries to interpret turtle commands (and discards `pop pop` otherwise). An advantage of this method is that it does not require enormous amounts of memory. A disadvantage is the recursion control is rather clumsy, as the stack size grows by more than just 1 from one recursion level to the next. *Edit:* +34 chars for branching. *Edit:* -3 chars. Redesigned to use the operand stack for recursion control. This makes the basic system much simpler. But brackets need an independent stack, so I put the saved position in the dictionary stack, and almost paid back all the savings. Also, redesigned to use strings and integers instead of arrays and names. *Edit:* -40 chars. Added two procedures for calling system names by number (I can't seem to get *raw* binary tokens to work. But this idiom works for me.) ``` /*{<920>dup 1 4 3 roll put cvx exec}def/${//* 73 *}def[/T[48{}49{}43{A<88>$}45{A<6e88>$}70{R 0<85>$}91{<1e39>$[/.[<286827>$]cvx>><0d0d>$}93{.<9c6b1e39390d>$}>>/S{dup B eq{T<0d3e>${<643f>$}<4939>$}{exch{<643e>$ 1 add S}73 *}85 * 1 sub}>><0d6b>$ 0 S<a7>$ ``` Semi-commented binary. ``` /*{<920>dup 1 4 3 roll put cvx exec}def/${//* 73 *}def %73=forall [/T[70{R 0<85>$}48{}49{} %<85>=rlineto 43{A<88>$}45{A<6e88>$} %<88>=rotate <6e>=neg 91{<1e39>$ %<1e>=currentdict <39>=end [/.[<286827>$]cvx>> %<28>=currentpoint <68>=matrix <27>=currentmatrix <0d0d>$} %<0d>=begin 93{.<9c6b1e39390d>$}>> %<9c>=setmatrix <6b>=moveto /S{dup B eq{T<0d3e>${<643f>$}<4939>$} %<3e>=exch <64>=load <3f>=exec <49>=forall {exch{<643e>$ 1 add S}73 *}85 * 1 sub}>> <0d6b>$ 0 S<a7>$ % 85=ifelse <a7>=stroke ``` Un-"binary". ``` [/T[70{R 0 rlineto}48{}49{}43{A rotate}45{A neg rotate}91{currentdict end[/.[currentpoint matrix currentmatrix]cvx>>begin begin}93{. setmatrix moveto currentdict end end begin}>>/S{dup B eq{T begin exch{load exec}forall end}{exch{load exch 1 add S}forall}ifelse 1 sub }>>begin moveto 0 S stroke ``` It requires the L-system to be defined in a dictionary on the dictstack, with the initial string and the starting position of the turtle on the operand stack (prepended to the source, eg. `gs dragon.sys lsys.ps`). Dragon Curve. ``` %! [ %begin dictionary construction % productions are described by integer-key/string-value pairs 48(0+1F) %0 %ascii code for '0' defined as the string "0+1F" 49(F0-1) %1 % " " " '1' " " " " "F0-1" 43(+) %+ % " " " '+' defined as itself 45(-) %- % " " " '-' " " " 70(F) %F % " " " 'F' " " " % parameters /A 90 %angle /R 2 %radius /B 10 %maximum recursion-level >>begin % L-system dictionary on top of dictstack (F0) % initial string on stack 300 400 % starting position on stack ``` Branching Stems. ``` [ 48(F[+0]-0) %0 49(F0-1) %1 43(+) %+ 45(-) %- 70(FF) %F 91([) %[ 93(]) %] /A 45 %angle /R 5 %radius /B 3 %recursion >>begin (++0) % initial string 300 400 % starting position ``` Ungolfed and commented. ``` [ % begin dictionary construction /T[ % /T is the Turtle dictionary containing % integer-key/procedure-value pairs % keyed to ascii values 70{R 0 rlineto} %F 48{} %0 49{} %1 43{A rotate} %+ 45{A neg rotate} %- % For brackets, create a dictionary containing a single procedure '.' (dot) % which holds a saved matrix (orientation+size) and currentpoint. % Since this procedure is called while the Turtle dict is on top of the % dictstack, the temporary dictionary is placed just under the top. 91{currentdict end[/.[currentpoint matrix currentmatrix]cvx>>begin begin} %[ % Right bracket: reset position and orientation, % pop the dict just under the top. 93{. setmatrix moveto currentdict end end begin} %] >> /S{ % stack contains: string recursion-level dup B eq{ % hit recursion bound, interpret string as turtle commands T begin exch % level string %dup = { % iterate through string load exec % execute turtle command by integer code } forall % level % string has been consumed end %(B)= pstack }{ % recurse %(A)= pstack exch % level string { % level char iterate through string load exch % string level process production:load string by int code 1 add S % string level+1 increase level and call self } forall % string has been consumed }ifelse 1 sub % return level-1 %(C)= pstack } >>begin moveto 0 S stroke ``` To run it, these 3 blocks can be saved as 3 files: dragon.ps, stems.ps, lsys.ps (any of the above program blocks will work identically). Then run with gs: `gs dragon.ps lsys.ps` or `gs stems.ps lsys.ps`. They can also be concatenated first, if desired: `cat dragon.ps lsys.ps | gs -` or `cat stems.ps lsys.ps | gs -`. ![dragon curve](https://i.stack.imgur.com/Phk4u.png) *No stems picture. It doesn't get any more interesting at higher depths.* [Answer] # Mathematica 290 This bare-bones implementation focuses on the output rather than the processing. It does not use production rules. So it may not be a suitable response to the challenge. Branching stems adapted from [Theo Gray's demonstration](http://demonstrations.wolfram.com/TreeBender/). **Code** ``` f@{a_, b_} := {{a, #}, {b, #}} &[a + (b - a)/2 + {{0, 1/2}, {-1/2, 0}}.(b - a)]; w = Flatten; h[s_, g_] :=Graphics[If[s == 0,Line /@ Nest[w[f /@ #, 1] &, {{{0, 0}, {1, 0}}}, g], MapIndexed[Line@# &, NestList[w[Map[{{#[[2]], #[[2]] + m.(#[[2]] - #[[1]])}, {#[[2]], #[[2]] + ({{1, -1}, {-1,1}} m).(#[[2]] - #[[1]])}} &, #], 1] &, {{{0, -1}, {0, 0}}}, g]]]] ``` **Usage** The first parameter determines whether the Dragon Curve or Branch Stems will be displayed. The second term refers to the generation. ``` h[0, 5] h[1, 5] ``` ![second pic](https://i.stack.imgur.com/dlXL1.png) --- **More Examples** ``` GraphicsGrid@Partition[Flatten[Table[h[j, k], {j, 0, 1}, {k, 10}]], 5] ``` ![fractal3](https://i.stack.imgur.com/H5JSW.png) ]
[Question] [ Say I have a ragged list, like: ``` [ [1, 2], [3, [4, 5] ] ] ``` And I want to iterate over each item and delete it one-by-one. However, I don't know the structure of the list. So, I have to iterate over the list, with the following algorithm: * Look at the first item of the list. * If it's a list, concatenate it to the start of the rest of the list. * Else, delete it. For example, with the above example `[[1, 2], [3, [4, 5]]]`: * `[1, 2]` is a list. Concatenate it - `[1, 2, [3, [4, 5]]]` * `1` is a number. Delete it - `[2, [3, [4, 5]]]` * `2` is a number. Delete it - `[[3, [4, 5]]]` * `[3, [4, 5]]` is a list. Concatenate it - `[3, [4, 5]]` * `3` is a number. Delete it - `[[4, 5]]` * `[4, 5]` is a list. Concatenate it - `[4, 5]` * `4` is a number. Delete it - `[5]` * `5` is a number. Delete it - `[]` There are no more items left, so our work is done. Your challenge is to compute the sizes of the lists resulting from applying this. For example, with the above, the list starts with length 2. It then goes to lengths 3, 2, 1, 2, 1, 2, 1, 0. Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply - that is, you may take a list \$l\$ and generate all terms, or take a list \$l\$ and a number \$n\$ and calculate the nth or first n terms. Your results may or may not contain the length of the initial list at the start, and the 0 at the end, and you may take \$n\$ 0-indexed or 1-indexed. Since only the shape of \$l\$ matters, you may take it filled with any consistent value instead of arbitrary integers. \$l\$ may contain empty lists. In this case, it's concatenated as normal and the length decreases by 1. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! ## Testcases These include the leading length but not the trailing 0. [Reference implementation](https://tio.run/##VY7BCgIxDETv/Yo5bnER19WL4JeUIsJm2UKopY3Ifn1Ne9JDSHjJzCTtsr3iXOtCK4JQfizEJDRwsTcDplhwh/MGny0wgYvSjo/PlCgug87t2CoOK2RPTetO3iIUcCjSBKpTm85xaH26qSWIC/2tO84k7xx7iDEphyjD72fOTSPOfoSbtS4jrt57a2v9Ag) ``` [[1, 2], [3, [4, 5]]] -> [2, 3, 2, 1, 2, 1, 2, 1] [[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]] -> [3, 5, 4, 3, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1] [3, 4, 5] -> [3, 2, 1] [[[[[[[[1]]]]]]]] -> [1, 1, 1, 1, 1, 1, 1, 1] [] -> [] [1, [], 1] -> [3, 2, 1] [[],[[[]]],[]] -> [3, 2, 2, 2, 1] ``` [Answer] # [R](https://www.r-project.org), ~~62~~ 61 bytes *Edit: -1 byte thanks to pajonk* ``` f=\(l)if(h<-length(l))c(h,f(c(if(is.list(g<-el(l)))g,l[-1]))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN23TbGM0cjQz0zQybHRzUvPSSzKAXM1kjQydNI1kDaB4ZrFeTmZxiUa6jW5qDkhOM10nJ1rXMBbIghqSkmMLVgImDHWMNHXALGMIZaJjClTKVVxSBNTNlQYikNVDFSMJaEKFUDVB7II5HAA) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~27~~ 25 bytes Anonymous prefix lambda. ``` {×⎕←≢⍵:∇((0≠≡⊃⍵)/⊃⍵),1↓⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ed9Ux@1TXjUuehR71arRx3tGhoGjzoXPOpc@KirGSikqQ@ldQwftU0GMmr/pwHVazzq7QNLrHnUu@XQeuNHbROBBgUHOQPJEA/PYM1qqLm9W3XUFR61TQIS3S0KQEGvYH8/iDHq0dGGOgpGsToK0cZAbKKjYBobG6vOBZIw01EAiRmCKZNYoBqgdLQRmGsJZJnqKJjBFBuDJU2hOiHAMBYKwIIQEmhYNNAgw1h1AA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; argument is `⍵`:  `≢⍵` tally the argument  `⎕←` print that  `×` signum of that  `:` if 1 (i.e. there's content):   `1↓⍵` drop the first element of the argument   `(`…`),` prepend:    `⊃⍵` the first element of the argument    `(`…`)/` replicated by (i.e. if the following holds true):     `⊃⍵` the first element of the argument     `0≠≡` is its depth different from zero? (i.e. a list)   `∇` recurse [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` def f(x,*r):print-~len(r);x>{}<f(*x+r);f(*r) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENXMzVZpD80ikvvIdqgILWECCmiF3HTjXgaD-BtnPQjOEPyZvLeG5I8Xk3rDuc67brnxRk5_4h9ZcCgF4kl3dhj7eT9VNVoaenX19vKYOJn3DBaGj3v4NlgsiUdgbOtNqGOoPK7qnFaQQT9pFhKGUcsRFQCUhKAGa9cQEEcA1MKCIeqh5xYxDymfbvgqhBQ_tRZzxaTdwgl6D8HdgQejDxUTZ5wi7CHZIbGR00f8gU) Prints to STDOUT; terminates with an error. # [Whython](https://github.com/pxeger/whython), 37 bytes -7 bytes thanks to @ovs ``` def f(x,*r):print(len(r)+1);f(*x+r?r) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVBLCsIwEN33FENBmGnTRfpD48Kd9xBNqCC1hIjtWdx0I97Gvbdx0rSCM0zm8948kjxe92ZwzbUdx-fNmWz9WZ20AYO9SCypzp5bhxfdoqVU0tZg0qd2Z2kmvz15j8mBVATODsr4OgLdH3XnlIwgKMRZlsUUMRNRCshJABYcpYCK2AJSC_BDOaWSmMQ45lO74aoSUP_YxYRWy24wKejfAzonFkYWlcuOv4U_vTNC86uWr_gC) Despite being Whython, this still also terminates with an error. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~ 55 53 ~~ 52 bytes *Saved 2 bytes thanks to [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)* *Saved 1 more byte thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh) and [@pfg](https://codegolf.stackexchange.com/users/77796/pfg)* ``` f=a=>[n=a.length,...n?f(a.shift().concat?.(a)??a):a] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZBLDsIgEIb3noIlJDgJfUVNkIMQFqSW1qSBRfE0brrQQ3kFT-HQ1o0yCc_5_p8Z7g8fLt08P2_R7Q-vykkrz9pLC2Pn-zhwAPDKUQvTcHWRMmiDb21UQC1TyrKTNZv2jZkpjB2MoaeOai04KQwnusRRcVIbYxjb_VINJwkQy1IZFCCri-V4xF3NSZNVlgtZ5zzXEGaLfyJzhQVofFzk_FIXOKfidLJbO_7-2gc) ### Commented ``` f = a => // f is a recursive function taking the input list a[] [ // build the output: n = a.length, // append the length of a[] and save it in n ...n ? // if a[] is not empty: f( // do a recursive call: a.shift() // extract the leading entry and attempt to .concat?.(a) // concatenate it with the remaining entries ??a // if it fails, just append a[] (the leading entry // was not an array) ) // end of recursive call : // else: a // stop the recursion and return a[] (which is empty) ] // end of output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔDg,ćDi\ëì ``` A byte is saved by taking the input filled with `1`s instead of positive integers. Outputs the lengths on separated newlines to STDOUT, including a trailing 0. [Try it online](https://tio.run/##yy9OTMpM/f//3BSXdJ0j7S6ZMYdXH17z/390tKGOYawOkAQzYmMB) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2nLpeRfWgLh6fw/N8UlXedIu0tKZszh1YfX/K@tPbTN/n90dLShjmGsDpAEM2JjdRTAQmAuSADORFIAkQKphACQMBgAhSDyQAqqAGg21FQgKxrMBhEA). **Explanation:** ``` Δ # Loop until the result no longer changes (e.g. until the list is empty): D # Duplicate the current list g # Pop and push the length , # Pop and output this length with trailing newline to STDOUT ć # Extract head; pop and push remainder-list and first item separately D # Duplicate this extracted head i # If it's a 1: \ # Discard it from the stack ë # Else (it's a list instead) ì # Prepend-merge it to the remainder-list ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes ``` #'{$[t~*t:*x;!0;t],1_x}\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxdT+1ugzAM/J+ncLVJgyoUEhK0EmkvkkUroqFFZWUr2UQ1tc8+89WxOtg4d76zUqQPTz+P2l2XLl22ahEpZyh7ay+vhLgUmfP1lBYA0KpNfVDepsjKSrXqrE6+uRCnPQZcebESIH1fcYiBA7tlZLoRL1GxYkgJXwnlcbytlYQEBTFIEDDVTiJmFr0cZSBV/AfQMRh6/j89jW+gw17WvYf5c63XsZiLaIBHgoRk79xHk4ZhXm/trq6KVeOy/GDbfJ8dd3aV1+/h55dtXFkfm5CL5yTiYensKXPlt63OwdZW1tkgC6qycYRozShwQ0HHmIKCNMZA8AKaU0AIK5tXg4qkZzoh/oRBMerG+TV2kkIyuSAke37eDHbibgFaxz0qb9Jp4xDMjNHTrBfefzg90NjgXZsOu7czFN3Qh2oz5/g0QX4BSgWRIw==) Output includes the length of the initial list and a 0 at the end. * `{...}\` set up a scan-converge, seeded with the (implicit) input and run until two successive iterations return the same result + `$[t~*t:*x;!0;t]` using `$[c;t;f] cond`, check if the first item is a list or an atom. if it is an atom, return an empty list (`!0`); if it is a list, return the first element of that list + `,1_x` append the remainder of the list (dropping the first item) * `#'` return the number of items in each iteration [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ö┬☻╪<æ·ë97╞φº♠B ``` [Run and debug it](https://staxlang.xyz/#p=99c202d83c91fa893937c6eda70642&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2) # [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü╜←Φ■Yxbo╟ⁿ▀í▼ε~ ``` [Run and debug it](https://staxlang.xyz/#p=81bd1be8fe5978626fc7fcdfa11fee7e&i=%5B%5B1,+2%5D,+%5B3,+%5B4,+5%5D%5D%5D%0A%5B%5B6,+3,+%5B1,+3,+4%5D%5D,+4,+%5B2,+3,+9,+%5B5,+6%5D%5D%5D&m=2) a generator. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes ``` Print[i+=Length@#-1]#0/@#&[i=1;#]& ``` [Try it online!](https://tio.run/##JYwxC8IwEIX3/o1ABz3Rq2mhSCCLm4PgWDqE0NoMjSDZjvSvx6cO9917d@9udWmZVpeCd2U25f4OMQ1hb25TfKbFqgOP6nS0qh6C4Ysa6zLb3dUvr@3hXdykEmFqMsmZRFObcyaMOoJlQMNrkgayJ2mp@wewQBbiW0xo/LvDHwARoMrlAw "Wolfram Language (Mathematica) – Try It Online") Prints the lengths. Includes a trailing `0`. ``` Print[i+=Length@#-1]#0/@#&[i=1;#]& [i=1;#] initialize i=1 before run #0/@# in depth-first, prefix order: i+=Length@#-1 add length-1 to i (atoms have length 0) Print[ ] print i ``` [Answer] # JavaScript (ES2019), ~~51~~ ~~48~~ 47 bytes ``` i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN_UzbQ2s02w1ymyjYzVt7aIztW3L9HJS89JLMnQVFTN19PT0yvTSchJLfBMLNNI0YyHabjGqJ-fnFZcolCrYKpTmpaSmZealpnCBxPJzUvVy8tM10jSio0t1FEpjdRRANIQdCyI0NYlQiEsVVAHMMAQXn06YDixmQgBIGxhgqsBuXDQun4B8ASRBjosGGQcJL1hwAwA) Input requires `undefined` as leaves. Output includes initial size and trailing `0`. I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then there is this 40-byte solution: ``` i=0;f=(v=[])=>[i+=v.length-!!i,v.map(f)] ``` ## Algorithm Instead of implementing the specified process and constructing the intermediate arrays, this submission uses an analytical solution to calculate the output. Notice that, with the process in the question, each item of the root array is completely deleted before moving on to the next item. Using the original example `[[1,2],[3,[4,5]]`, the `[1,2]` subarray is fully deleted before `[3,[4,5]]` is touched. This means that while processing `[1,2]`, the sizes of the intermediate arrays at each step is the same as those while processing `[1,2]` as a root, but plus 1 because we have to count `[3,[4,5]]` ``` [[1, 2], [3, [4, 5]]] [1, 2, [3, [4, 5]]] (size: 3) | [1,2] (size: 2) [2, [3, [4, 5]]] (size: 2) | [2] (size: 1) [[3, [4, 5]]] (size: 1) | [] (size: 0) ``` Take another example from the test cases ``` [[6, 3, [1, 3, 4]], 4, [2, 3, 9, [5, 6]]] [6, 3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]] (size: 5) | [6, 3, [1, 3, 4]] (size: 3) [3, [1, 3, 4], 4, [2, 3, 9, [5, 6]]] (size: 4) | [3, [1, 3, 4]] (size: 2) [[1, 3, 4], 4, [2, 3, 9, [5, 6]]] (size: 3) | [[1, 3, 4]] (size: 1) [1, 3, 4, 4, [2, 3, 9, [5, 6]]] (size: 5) | [1, 3, 4] (size: 3) [3, 4, 4, [2, 3, 9, [5, 6]]] (size: 4) | [3, 4] (size: 2) [4, 4, [2, 3, 9, [5, 6]]] (size: 3) | [4] (size: 1) [4, [2, 3, 9, [5, 6]]] (size: 2) | [] (size: 0) ``` The size difference is 2 here because there are 2 items after the item being processed (`[6, 3, [1, 3, 4]]`). This shows that this problem can be solved with a recursive algorithm ``` f([1, 2]) = [2, 1, 0] f([3, [4, 5]]) = [2, 1, 2, 1, 0] [2, 1, 0][2, 1, 2, 1, 0] + [2, 1, 0] -------------------------------- f([[1, 2], [3, [4, 5]]]) = [2, 3, 2, 1, 2, 1, 2, 1, 0] ``` More precisely, the output of processing an array consists of: * The initial length of the array, then * For each item, the result of processing that item, plus adding the number of items after it to each element. ### Naive, readable implementation ``` function f(value) { if (value !== undefined) { return [ value.length, ...value.flatMap((item, index) => f(item).map((n) => n + value.length - index - 1)) ] } return [0] } ``` ## Golfing First, of course, is to apply basic golfing techniques ``` // 70 bytes f=v=>v?[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))]:[0] ``` Then, since leaves are `undefined`, we can actually use default argument to treat leaves as `[]` and merge the two branches ``` // 69 bytes f=(v=[])=>[v.length,...v.flatMap((u,j)=>f(u).map($=>$+v.length-j-1))] ``` Then, instead of mapping a second time to add the "base" value `v.length-j-1`, we can make `f` accept a second argument for a value to add to everything. ``` // 67 bytes f=(v=[],i=0)=>[v.length+i,...v.flatMap((u,j)=>f(u,v.length+i-j-1))] ``` Next, we can pull `i` up to the global scope and mutate it instead of passing it around and using a lengthy expression to calculate the base ``` // 53 bytes i=0;f=(v=[])=>[i+=v.length,...v.flatMap(u=>f(u,i--))] ``` Finally, we can move the `i--` decrement into `f` so that, instead of decrementing at each `flatMap` iteration, we just decrement `i` at the start of `f`. ``` // 45 bytes i=1;f=(v=[])=>[i+=v.length-1,...v.flatMap(f)] ``` **BUT**, this breaks because the global variable `i` is changed after calling `f`, which is [forbiddened](https://codegolf.meta.stackexchange.com/a/4940/6972). Specifically, `i` is decremented by 1 for each root call to `f`. Before the change, `i` is decremented by 1 by one per child while looping in `flatMap`, but now `i` is decremented by 1 per call (i.e. per node), and the root is the only node that is not a child. To counter this, we need to change the increment to "number of children" (instead of "number of children - 1") but only for the root node. This is doable by noticing that `i` is at its initial value only at the start of a root `f` call and after processing the last leaf. So we can initialize `i` to 0 and when we increment `i`, we increment by "number of children" if `i` is 0 but by "number of children - 1" otherwise. ``` // 47 bytes i=0;f=(v=[])=>[i+=v.length-!!i,...v.flatMap(f)] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), (16) 21 bytes ``` Wθ«⟦ILθ⟧≔⁺∨&⁰§θ⁰υΦθλθ ``` [Try it online!](https://tio.run/##HYxLC8IwEITP7a/Y4wYi1FdBPFVBEAR7DzmENrSBEMmjVhB/e9x2YWd2voHtRhW6l7I5z6OxGtAz@JZFG4xLKK4qJnxoN6SRCibZuSyaGM3gsLVTxGfAi0mzibpxPVYcmnR3vf6g51AxxmGivRmbdFiQXZCnJ7@chRA1hz0HsV3tICUJxd0aT3QdOdSSJm/e9g8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Wθ« ``` Repeat until the input list is empty. ``` ⟦ILθ⟧ ``` Output its length on its own line. ``` ≔⁺∨&⁰§θ⁰υΦθλθ ``` Add the tail of the list to the first element. * This would be three bytes shorter if the list was to be iteratively deleted from the end rather than the start. * This would be four bytes shorter if Charcoal's vectorising `Add` worked properly, but unfortunately it only vectorises to depth 1. (Other operators, such as `BitwiseAnd`, do vectorise correctly, so I'm assuming this is an oversight. Edit: Ironically, `Times` also doesn't vectorise correctly, so I needed to replace it with `BitwiseAnd` to fix a bug.) * Alternatively, this could be two bytes shorter if the input integers were all zero. (Not applicable when vectorising `Add` works properly.) * This could be one byte shorter by outputting the last length instead of the first. 16 bytes using the newer version of Charcoal on ATO: ``` Wθ«≔⁺§θ⁰Φθλθ⟦ILθ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfDyzMyc1IVNAo1Faq5OB2LizPT8zQCckqLNRxLPPNSUis0CnUUDDR1FNwyc0pSi0C8HE0gt1DTmoszoCgzr0Qj2jmxuETDJzUvvSQDaI5mLFCqdklxUnIx1JLl0Uq6ZTlKsTe1o6OjzXQUjHUUog3BlElsLJAAco3AXEsgy1RHwSwWCCBaAQ "Charcoal – Attempt This Online") Link is to verbose version of code. Outputs the last length instead of the first. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OḢ;$Ḋ⁼¡µƬẈṖ ``` A monadic Link that accepts a ragged list of integers and yields the lengths as a list, including both the initial length and a trailing `0`. **[Try it online!](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP///0dHm@koGOsoRBuCKZPYWCAB5BqBuZZAlqmOgllsbCwA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9//4Y5F1ioPd3Q9atxzaOGhrcfWPNzV8XDntP86h9uPTnq4c8ajpjVZjxr36dppRv7/Hx0dbaijYBSroxBtDMQmOgqmsbGxXDrR0WY6CiARQzBlEgtUAZSMNgJzLYEsUx0FM4hSY7CUKVgXBBjGQgFQCISBhkQDDTAEKwHZBSRBJgJJrlgA "Jelly – Try It Online"). ### How? ``` OḢ;$Ḋ⁼¡µƬẈṖ - Link: ragged list of positive integers, L Ƭ - collect input, X (initially L), while distinct, applying: µ - this monadic chain - f(X): O - ordinal value (vectorises) -- only here to get us a copy of X so that we don't mutate it with Ḣ $ - last two links as a monad - f(Y=that): Ḣ - head Y (alters Y, yields the first element or 0 when given []) ; - concatenate that with (the altered Y) ¡ - if... ⁼ - ...condition: that equals X? (head of X was an integer) Ḋ - ...then: dequeue Ẉ - length of each Ṗ - pop the last length (removes the trailing 1, the length of 0) ``` --- Also 11 with no `Ḣ` and, therefore, no `O`: `1ị;ḊḊ⁼¡µƬẈṖ` [Answer] # JavaScript (ES5), ~~ 84 ~~ 80 bytes *Saved 4 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` function(a){for(r=[];m=a.shift(r.push(a.length));)a=m[0]?m.concat(a):a;return r} ``` [Try it online!](https://tio.run/##jVJPT4MwFL/vUzx3WNqkNmODRSXEkwc96MFj00NF2DCsJW1ZYpZ9dnyUbcGpiS/QPt77/WlpP9ROudxWjb/e3XSlsSQ32nkQlW5az8C0HmcJpgQxAQwBQkQMFpKBWOIbM0iklIDpggFWcIzGowTJzsxVgPQCOMUSReIz8RazhMHqqIaVJLTHySAbXxiNLZahnZwkfqxgiEgeA4bV/PKMWQE2LkT9dwD9YSMZuqA@E3KEWYyQksI@wIcfbgsHGZCubHXuK6OJovv@OGwmZLrNFHebqvTE8qZ1G6J4Xei131CaUpVtxVzebzkK5coj8U6ltvCt1WAPXW9BSThOmgbDqiRPry/P3Hlb6XVVfhI0p3CVZXBRF5zz4QYwmEsa2LMZ/Jc@UCmlYY@mLnht1mT6YK2xU9Zv@XTBcGWHyTfQYwnaHLug3syuYKDqGnzhvINGOVe8T2nafQE "JavaScript (V8) – Try It Online") Formatted and renamed: ``` function(array){ result = []; while( result.push(array.length), current = array.shift() ) { if(current !== +current) { // if current is not a number array = current.concat(array); } } return result; } ``` [Answer] # Rust, ~~19~~ ~~194~~ ~~185~~ 174 bytes Even defining a type for a ragged list is bytes intensive in rust. Still shorter than C :) ``` enum K{N,Y(Vec<K>)}fn f(k:&K,n:usize)->Vec<usize>{if let K::Y(b)=k{[n+b.len()].into_iter().chain((1..).zip(b).map(|(i,z)|f(z,b.len()+n-i)).flatten()).collect()}else{vec![n]}} ``` Sequences will have a extra 0 at the end. [Verify all test cases](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c8474744bc710deb37a6d0546f7a477b) -9 bytes by using `Vec` instead of array slices -11 bytes by replacing `enumerate` with `zip` and `match` with `if let` [Answer] # BQN, 26 bytes ``` {(≠∾·𝕊=∘⊑◶⟨⟩‿⊑∾1⊸↓)⍟(×≠)𝕩} ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlaniiaDiirjiiL4o8J2Vij3iiJjiipHil7bin6jin6nigL/iipHiiL4x4oq44oaTKeKNnyjDl+KJoCnwnZWpfQoKKOKAolNob3cgRuKImOKAokpzKcKo4p+oCiJbWzEsIDJdLCBbMywgWzQsIDVdXV0iCiJbWzYsIDMsIFsxLCAzLCA0XV0sIDQsIFsyLCAzLCA5LCBbNSwgNl1dXSIKIlszLCA0LCA1XSIKIltbW1tbW1tbMV1dXV1dXV1dIgoiW10iCiJbMSwgW10sIDFdIgoiW1tdLFtbW11dXSxbXV0iCuKfqQpA) -1 byte thanks to @DLosc! ## Explanation * `≠∾·...` append input length to... * `(...)⍟(×≠)𝕩` if input is nonempty... * `...∾1⊸↓` append tail to... * `=∘⊑◶⟨⟩‿⊑` head if head is rank 1 (i.e. list), otherwise empty list * `𝕊` recurse [Answer] # [Factor](https://factorcode.org/), 57 bytes ``` [ [ dup length . unclip [ prepend ] when* ] until-empty ] ``` [Try it online!](https://tio.run/##lZFNb8IwDIbv/RXvrpOKBC0XkLhOu@yCOFUcqmDWiuCGNNWGqv72zsDSrwvCr2InVvzYSo6pcoVtd9vPr48VTmSZNEq6VMSKShhLzl2Nzdn12Rn9OpuWyAusg6AOIFaLjqLmHv3@pqm9IdzIhQUiWfNuNSPMwz8Q/WmI/cdEWCLu/A0UD8Ae6mHPrIOOJxrK9@81KZ5P5DHPu48w/ej1/Q2a10ZvgjZBgkNloIm/XYYZKlY6N5KVXzXEB@zxkxG/S6zY5Tqks3FX7KWStSRVcTZFSaBUZe0f "Factor – Try It Online") Input consists of ragged sequences of `f` — Factor's canonical false value — as this saves about 20 bytes over integers. * `[ ... ] until-empty` Call `[ ... ]` on the input until it's empty. * `dup length .` Print the current length of the input non-destructively. * `unclip` Remove the first element from the sequence and place it on top of the data stack. * `[ prepend ] when*` `when*` is like `when` except it drops its input value if it's false, but retains its input if it's true (which is any non-false value in Factor). So, prepend it to the input if it's a sequence, or drop it if it's `f`. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt#L140), 15 (non-competing†) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` {├_nn¡¿\;+ho}▲; ``` † The program above doesn't compile due to a bug in MathGolf with (do-)while loops using blocks above 8 characters. `{...}` is supposed to be a block for when `...` contains more than 8 characters, but instead the `{` behaves as a for-each. We can remove the `{}` and trailing `;` so the do-while works on all preceding characters, so we can verify the test cases. Unfortunately, all test cases will then output an additional trailing empty list `[]`. Both programs also fail with an error for input `[]`. Outputs each length to STDOUT, without leading length and with trailing 0. `├_nn¡¿\;+ho▲`: [Try it online](https://tio.run/##LUq7DYNAFOtZJW4eHCdFGcVYiIZQEGgySpQqTVbIAkiMwiLHy4FlWf49uudwn8c@pe31aadp/a5Lc7sM8/b@pUQaSoEVGFBLKsgIT@YSJASwdHsFa8S8e@9P/x0wnSjoNFCw/ypkntZFOe4). **Explanation:** ``` { }▲ # Do-while true with pop: ├ # Extract and push the left item of the list # (this is where the `[]` test case errors) _ # Duplicate it n # If it's a list: join it with newline delimiter to a string # If it's an integer: push a newline "\n" character n¡ # Check that this string is NOT equal to "\n" ¿ # If it's indeed not "\n" (thus it's a list) \ # Swap the top two values ¿ # Else (it's an integer): ; # Discard it from the stack + # If it's a list: merge the top two lists together # If it's an integer: add it to each inner-most value h # Push the length (without popping the list) o # Output it with trailing newline (without popping) ▲ # Once the length is 0, the do-while stops ; # After the do-while: discard the empty list (since MathGolf # implicitly outputs the entire stack at the end of a program) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 266 bytes ``` #define S *w++=*r++ #define B b+=*r==91?1:-(*r==93) f(r,b,w)char*r,*w;{w=++r;if(*++r==93)r++,r+=*r?*r==44:-1;else{if(*r!=44)for(b=1;b;B)S;r++;}for(;*r;)S;*w=0;}i;main(b,v,r)char**v,*r;{for(v++;*(*v+2);printf("%d ",i),f(*v))for(b=0,r=*v,i=1;*++r;B)(!b&&*r==44)&&i++;} ``` [Try it online!](https://tio.run/##PY7LbsIwEEX3fEWgauTHRMKUDYwsJH6BJfICh7i1VNJqWtmLiG93x6HtZh5X986Zvnvt@1KerkOI49CcGpW1toq0Xvxpx8ZXxdqdOZh9J@bxRS6CIPCQZf92IUWgMk7Zak0Yg1DcZxcfAqrxQ41tt/vO4PD@NUzVREtWZPgg4a1Bj0d5Qg7gvUqoCHlX2a7xHvF2iaPwkIAeQJWADVN1Jo4ooZLeSPykOH4HsXq@NiuIEpiS5C9iDWQ5FplV/2OcWPq2fTwm2zZWdCnlfDZgYC7Guf9xbs65Hw "C (gcc) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes ``` 0 [] +`..(],?|(((\[)|(?<-4>])|,)+)])(.*)$ $&¶[$2$5 .(.((\[)|(?<-3>])|,)*].)*.? $#1 ``` [Try it online!](https://tio.run/##RY5LCsJADIb3OcWAo2TaGJy2UxDEHiQNVNCFGxfisufyAF5sTKeCgTz/LyHP2@v@uOQtTuO1hgM4yAcQhXpiRqVhRsRRwozDad@dNcwU6qABuQoe/O7zFt/4BIz859qVq5RDxQP4TcxZJJJrlJy05h25pKoAIj25ZRJL6tQIE6Up7dGqRK5f0bZIqWytFvVnsLwMyxGxA7EgSkaYRha@ "Retina 0.8.2 – Try It Online") Outputs both leading and trailing counts and takes `0` as the consistent value (since `[]` is disallowed), but link is to test suite that replaces all non-negative integers with zero and deletes spaces for convenience. Explanation: ``` 0 [] ``` Replace `0`s with empty lists. ``` +` ``` Repeat until the last line is an empty list. ``` ..(],?|(((\[)|(?<-4>])|,)+)])(.*)$ ``` On the last line, match a list containing either an empty list as its first or only element, or otherwise the contents of the list at the first element. ``` $&¶[$2$5 ``` Keep the original list to count its elements later and create a new list obtained by prepending the contents (if any) to the rest of the list. ``` .(.((\[)|(?<-3>])|,)*].)*.? $#1 ``` Count the number of elements of each list. [Answer] ## Brev, 85 bytes ``` (fn(descend(x)(cons(length x)(desc(if(pair?(car x))(append(car x)(cdr x))(cdr x)))))) ``` Example: ``` ((fn (descend (x) (cons (length x) (desc (if (pair? (car x)) (append (car x) (cdr x)) (cdr x)))))) '((1 2) (3 (4 5)))) ``` `fn` makes a function with an argument `x`. `descend` checks if it's null, if it is, return it. Otherwise, `cons` its `length` onto a recursive call of `descend`, where the `car` of `x` has been spliced if it's a `pair?` or dropped if it's an atom. For the test example, it returns `(2 3 2 1 2 1 2 1)` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` #l=+|hQYt ``` [Try it online!](https://tio.run/##K6gsyfj/XznHVrsmIzCy5P//6GgDHQWDWB0FEA1hx8YCAA "Pyth – Try It Online") Accepts a ragged list filled with 0s. Excludes the length of the initial list, and includes the 0 for the final list. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 32 bytes ``` saj{g_Jto'B~[{j_+}qvvIEsaj}qL[w! ``` [Try it online!](https://tio.run/##VU3LCoJQEN33FZObFuHiPhTCcFG0KNy3kJACCUQoM20xTL9@O/lAPJcZLuc1t@ZV5nXV5I49P/aiyL88c1dfC75np/djtfumXGRrqdr2eAAtVZJ@lq4F9snWl3PpmBVpITbElgIRIT8m1mRIkxpHFswhKHgNWXhsb9kQBxSOIUMBhHH/o3aqQQWiuDBYh9YeSgZ0oqLZg63n8VHYYOYdggZkWSZed9oP "Burlesque – Try It Online") ``` saj # Get initial length { g_ # Pop head from list J # Dup to'B~[ # Is Block {j_+} # Prepend elements qvv # Drop IE # If (isBlock) else saj # Length } qL[w! # While non-empty ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes ``` {⍴⍴⍵:∊(⍴,∇¨+⍴-⍳∘⍴)⍵⋄0} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvFjDaavWoo0sDyNR51NF@aIU2kKX7qHfzo44ZQJYmUP5Rd4tB7f@0R20TgKr6HnU1P@pdA5Q6tN74UdvER31Tg4OcgWSIh2ewJpD2Cvb3@5@mHh1tqKNgFKujEG0MxCY6CqaxsbHqXCAJMx0FkJghmDKJBaoBSkcbgbmWQJapjoIZTLExWNIUqhMCDGOhACwIIYGGRQMNMoQqjNUBqgOq0AES6gA "APL (Dyalog Classic) – Try It Online") I assume the output must be a flat array instead of allowing nested array. If nested array is acceptable then `∊` is not needed for -1 byte Uses the same algorithm as my [other submission](https://codegolf.stackexchange.com/a/251282/6972), but pretty much ungolfed because tacit APL is that good ``` {⍴⍴⍵:∊(⍴⍵),(∇¨⍵)+(⍴⍵)-(⍳⍴⍵)⋄0} With trains expanded ⍴⍴⍵: If argument is array (∇¨⍵) recursive call with each element +(⍴⍵)-(⍳⍴⍵) add (length of argument - index) note that APL arrays are 1-based by default (⍴⍵), prepend length of argument ∊ flatten ⋄0 Else return 0 ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth) (arbitrary values), 15 bytes ``` lM.u+.x[.*hN[)t ``` [Test suite](https://pythtemp.herokuapp.com/?code=lM.u%2B.x%5B.%2ahN%5B%29t&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B3%2C+%5B4%2C+5%5D%5D%5D%0A%5B%5B6%2C+3%2C+%5B1%2C+3%2C+4%5D%5D%2C+4%2C+%5B2%2C+3%2C+9%2C+%5B5%2C+6%5D%5D%5D%0A%5B3%2C+4%2C+5%5D%0A%5B%5B%5B%5B%5B%5B%5B%5B1%5D%5D%5D%5D%5D%5D%5D%5D%0A%5B%5D%0A%5B1%2C+%5B%5D%2C+1%5D%0A%5B%5B%5D%2C%5B%5B%5B%5D%5D%5D%2C%5B%5D%5D&debug=0) Takes a ragged list of arbitrary values (even accepts floats). Includes length of original list and final 0. ##### Explanation: ``` lM.u+.x[.*hN[)t | Full code lM.u+.x[.*hN[)tNQ | with implicit variables ------------------+---------------------------------------------------------------------------------------------------------------- .u Q | Collect N, starting with the input, with each succussive N defined by the following until a result is repeated: + tN | Prepend to the tail of N: [.*hN | N if N is a list .x [) | or the empty list if N is not a list lM | Convert each element to its length ``` ]
[Question] [ Given a single positive odd integer as input, return a converging zigzag as a list of strings, list of lists of characters, or newline-separated string, in this form: ``` # # # # # # # # # # # ``` You can replace `#` with any consistent non-whitespace character. Trailing whitespace on each line is allowed and a trailing newline is allowed. The zig-zag starts at column `1` and for each row moves right one column, until it reaches column `n` (where `n` is the input). Then, it moves left to `2`, then right to `n-1`, then left to `3`, with the two bounds converging in until the zigzag ends in the middle column (`(n+1)/2`). # Test Cases The example above is the test case for `5`. The following are individual test cases: ``` 3 # # # # ``` ``` 7 # # # # # # # # # # # # # # # # # # # # # # ``` ``` 1 # ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 89 bytes ``` f(n,a,b){puts("0");for(a=n;--a>n/2;)for(b=n-2*a;b<=2*a-n;)printf(" %*d\n",a-abs(b++),0);} ``` [Try it online!](https://tio.run/##JY1BCsIwEEWvIgFhpkmwZuNiOp7EzSQSmYVjaeuqePZocPXh8R6/xEcprVWwICHjPr@3FdzokOprAWGjGOVqp0TYQWaLaRDKE/8mGuG8qG0V3OE43G/mgkTJK2TvMYxIn6b0FDXAvefKZ9KJL6SeE1ZQDP9D19Uv "C (gcc) – Try It Online") Works by analyzing the sequence of number of spaces as (for n=7): ``` 0 1 2 3 4 5 6 5 4 3 2 1 2 3 4 5 4 3 2 3 4 3 ``` And for n=3: ``` 0 1 2 1 ``` We can see that the middle number (`a` in the code) runs from [n-1, n/2). Then, the difference between the first number and the middle number is: ``` a n b 2a-n ------------- 6 7 5 5 5 7 3 3 4 7 1 1 2 3 1 1 ``` So, if we have `b` going through [-(2a-n), 2a-n], `a-abs(b)` will give us the desired sequence. This is essentially what the code does. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~10~~ 8 bytes ``` FN«↗ι‖»/ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NToZqLM6AoM69Ewyq0ICgzPaNERyFT05qLMyg1LSc1uUQDyK7lgqhQ0lfStP7/3/S/btl/3eIcAA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 2 bytes thanks to @dzaima for pointing out that I don't have to use `#`s. [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` l=range(1,input()) print 8 for i in l: for i in l:print' '*i+'8' l=l[-2::-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8e2KDEvPVXDUCczr6C0RENTk6ugKDOvRMGCKy2/SCFTITNPIceKSwGJA5ZXV1DXytRWt1DnUsixzYnWNbKy0jWM/f/fHAA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ṖṖṚ$ÐĿẎ0;⁶ẋp1Y ``` [Try it online!](https://tio.run/##y0rNyan8///hzmlgNEvl8IQj@x/u6jOwftS47eGu7gLDyP///5sDAA "Jelly – Try It Online") Full program. Uses `1`. -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). [Answer] # [Haskell](https://www.haskell.org/), 72 bytes ``` g[]=[] g a=a++g(reverse$init a) r="#":map(' ':)r ("#":).g.tail.(`take`r) ``` [Try it online!](https://tio.run/##FcqxCoQwDADQ3a8oXsEEodNNQr/iRimYIfSCtUga/f2Kb35/ajuX0nteU1zTkB1FmucMyjdrYy9VzBEOGsfPuBx0wuSmBbUfJDWel/1M/VWLVG4e4E0YcjCSEmAz2nlTxG9/AA "Haskell – Try It Online") We define an infinite list `r` being the diagonal of `#`s starting from the upper left hand corner. We then define a function `g` which does the brunt of the work. `g` will take a list and repeatedly reverse it and remove its first element until the list is empty, then concatenate the result of each action. Our main function here is a point-free function. This function starts by taking `n` elements from the infinite list `r`, it then chops of the first element and applies `g`. Last we have to add a `#` back to the beginning, this is because the specs for the question are a little weird, I'm not sure why the first diagonal is always one longer than it should be but, it is, so we have to add a a `#`. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 19 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ┘.»∫«I╝:±jk+jl0;±Iž ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTE4LiVCQiV1MjIyQiVBQkkldTI1NUQlM0ElQjFqaytqbDAlM0IlQjFJJXUwMTdF,inputs=Nw__) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` i8ë<LZFD¨R})˜0¸ìε8sú}» ``` [Try it online!](https://tio.run/##ASkA1v8wNWFiMWX//2k4w6s8TFpGRMKoUn0py5wwwrjDrM61OHPDun3Cu///MQ "05AB1E – Try It Online") Uses `8`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` LN71SΛ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx8/cMPjc7P//LQE "05AB1E – Try It Online") ``` Λ use the canvas function with L a range list [1 .. input] as lengths for each path N a "0" as character to be printed (N is the index variable used by loops. If there was no loop yet, its default value is 0. By using N, I avoid an extra space between 0 and 71) 71S and the directions 7 and 1 (NW and NE), that alternate automatically until the range list is finished. ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 29 bytes ``` ri,(;_,{_);W%}*]e_0\+Sf*8f+N* ``` [Try it online!](https://tio.run/##S85KzP3/vyhTR8M6Xqc6XtM6XLVWKzY13iBGOzhNyyJN20/r/39zAA "CJam – Try It Online") Uses `8`. [Answer] # Pyth, 23 bytes ``` 8JStQKdVQjbm+*\ d8J=_PJ ``` [Try it here.](http://pyth.herokuapp.com/?code=8JStQKdVQjbm%2B%2a%5C+d8J%3D_PJ&input=7&debug=0) [Answer] ## JavaScript, 127 bytes Calculates the goal (`g`) to get to. When this goal is reached, turn around to the next goal. Also uses a trick to avoid using `Math.round()` by adding `0.5` to every uneven number. ``` f=n=>{c=0;for(i=0;i<n;i++){m=i/2;g=i%2==0?n-m:m+1.5;while(c!=g){c>g?c--:c++;console.log(' '.repeat(c-1)+'#'+' '.repeat(n-c))}}} ``` ``` f=n=>{c=0;for(i=0;i<n;i++){m=i/2;g=i%2==0?n-m:m+1.5;while(c!=g){c>g?c--:c++;console.log(' '.repeat(c-1)+'#'+' '.repeat(n-c))}}} f(5); ``` [Answer] ## Haskell, 74 bytes ``` f[x]=[x] f s=s++tail(f$reverse$tail s) g n=f[(' '<$[2..x])++"#"|x<-[1..n]] ``` [Try it online!](https://tio.run/##fYmxCsIwGAb3PsVHDbQlGKgOLs0buDmGDAGTGox/JUklg@8e6wt0OLjjHiY9bQi1OlW03GgckkycZ@ND71i0HxuTZf9EGpoZJJ3qO3QTUychih44bw/tt0xHNQpBWteX8QSJ@9IAeK/5luOVwLBS8GTTZjPGnXfeeZf6Aw "Haskell – Try It Online") How it works: ``` [(' '<$[2..x])++"#"|x<-[1..n]] -- build the first diagonal, e.g. for n=3: -- ["#", " #", " #"] f -- call f, which is f s = s ++ -- the input list, followed by tail -- all but the first element of f -- a recursive call with reverse -- the reverse of tail s -- all but the first element of the input -- list f[x]=[x] -- base case: stop if the input list a -- singleton list ``` Each recursive call to `f` appends the next diagonal. [Answer] ## [Husk](https://github.com/barbuz/Husk), 19 bytes ``` mo`:'#R' ∫`Ṙ¢e1_1tṫ ``` [Try it online!](https://tio.run/##ASQA2/9odXNr//9tb2A6JyNSJyDiiKtg4bmYwqJlMV8xdOG5q////zU "Husk – Try It Online") ## Explanation This feels a bit clunky. ``` mo`:'#R' ∫`Ṙ¢e1_1tṫ Input is n (e.g. 5) ṫ Range from input to 1: [5,4,3,2,1] t Drop first element: [4,3,2,1] e1_1 The list [1,-1] ¢ repeated infinitely: [1,-1,1,-1,.. `Ṙ Clone with respect to the list above: [1,1,1,1,-1,-1,-1,1,1,-1] ∫ Cumulative sum: [0,1,2,3,4,3,2,1,2,3,2] mo For each element k (e.g. 3) do this: R' Repeat space k times: " " `:'# Append '#': " #" Print implicitly separated by linefeeds. ``` [Answer] # [Python 3](https://docs.python.org/3/), 82 bytes ``` def z(n):l=range(1,n);print(8);exec("[print(' '*i+'8')for i in l];l=l[-2::-1];"*n) ``` [Try it online!](https://tio.run/##JcpBCoMwEADAryxesqvmED1UEnyJeCgadSGsIaRQ/XxK8Tgw8crHKX0pq9/gRiEbxvSW3aNphVxMLBkHcv7rF6ymxwpUzY0aFG1nAgYWCLMLY5h0Z602s6tqoXLjP7PET0YiKq8f "Python 3 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 71 bytes ``` .+ $* ^ :> $ : ;{*T`:<>`_# ( ) >(:)|( )< $1<$2$3 (:)( )<|>( ) $2$1$3> ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRUuBK47Lyo5LQYXLisu6WiskwcrGLiFemUtDQVPBTsNKswbIsOFSMbRRMVIx5gIKgPg1dkCSCyhiqGJs9/@/KQA "Retina – Try It Online") Explanation: The first three stages convert the input into the form `:> :` where the number of characters between the `:`s is the input number. The last two stages then bounce the `>` (or `<`, when moving leftward) between the `:`s. The fourth stage loops the bounce, printing the required parts of the string each time. The `;` stops the string from being printed after the loop. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` Î<L¤F¦})˜Ôð×X«» ``` [Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//8OOPEzCpEbDgsKmfSnLnMOUw7DDl1jCq8K7//80 "05AB1E – Try It Online") **Explanation** ``` Î<L # push 0 and range [1 ... input-1] ¤ # get the last element of the list F # that many times do  # bifurcate ¦ # remove the head })˜ # end loop and wrap in flattened list Ô # remove consecutive duplicates ð× # repeat space a number of times corresponding to each number in the list X« # append 1 to each » # join on newline ``` [Answer] # K (Kona), 27 bytes ``` `0:{|x$"#"}'1,,/{1_|x}\-2-! ``` Produces the underlying numeric sequence by repeatedly reversing and dropping the head of a vector until empty. [Answer] # PHP, 65 bytes ``` <?while(--$n||$n=$d=--$argn)echo str_pad("X ",2+$x-=$d&1?:-1);?>X ``` Run as pipe with `-nF` or [test it online](http://sandbox.onlinephpfunctions.com/code/87819fa945312260b87327f04aed3616254391c5). **explanation:** first iteration: `$n` is `NULL`, so `--$n` has no effect and evaluates to `NULL` --> set `$n` and `$d` to pre-decremented argument 1. increment `$x` for even `$d`, decrement for odd `$d` 2. print `X`, a newline and `$x` spaces further iterations: decrement `$n`; when it hits `0`, reset `$n` (and `$d`) to pre-decremented argument finale: print one more `X`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 31 bytes ``` Ç+V ç +QÃê ¯-2 c´U?ß´UVÄ :Vç +Q ``` Recursive solution that returns an array of lines. [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=xytWIOcgK1HD6iCvLTIgY7RVP9+0VVbEIDpW5yArUQ==&inputs=MQ==,Mw==,NQ==,Nw==,OQ==,MTE=,MTM=&flags=LVI=) using the `-R` flag to join output with newlines. [Answer] # Python 2, ~~159~~ ~~145~~ ~~141~~ 136 bytes ``` print"".join([" "*p+"#\n"for p in(lambda l:[sum(l[:i])for i in range(len(l))])(sum([i*[1-i%2*2]for i in range(input())[::-1]],[])+[1])]) ``` There has already been quite nice Python versions to this problem but I thought I'd still post my awful one-liner. (Without semicolons though!) Edit: 14 bytes down, using sum instead of double list comprehension Edit: Just noticed in python 2 you can use input instead of raw\_input. I've always just used the latter. [Answer] # Mathematica, ~~142~~ 102 bytes (independent) This solution has a mathy flavor: `UnitVector[#,1-Sum[(-1)^Floor[#+1/2-Sqrt[9/4+#*#-#-2x]],{x,k}]]~Table~{k,0,#(#-1)/2}/.{0->" ",1->"X"}&` This basically calculates which segment we're in (by inverting the triangular number function) and then moving left or right by adding a power of -1. You can test it on the [Wolfram Code Sandbox](http://sandbox.open.wolframcloud.com) by pasting code like `UnitVector[#,1-Sum[(-1)^Floor[#+1/2-Sqrt[9/4+#*#-#-2x]],{x,k}]]~Table~{k,0,#(#-1)/2}/.{0->" ",1->"X"}&@6//MatrixForm` and pressing Shift+Enter or Numpad Enter or clicking Gear->"Evaluate Cell". --- This happens to be the same length as my original incorrect port of [Erik's Python 2 solution](https://codegolf.stackexchange.com/a/135080/41105) (This port gives the output for an input one higher): `(Print[X];l=Range@#;Do[Do[Print[StringRepeat[" ",l[[j]]]<>"X"],{j,Length@l}];l=l[[-2;;1;;-1]],{i,#}])&` ]
[Question] [ This is a "counterpart" of another puzzle, [Eight coins for the fair king](https://puzzling.stackexchange.com/q/77750/44061) on Puzzling.SE. You can read the above puzzle for the background. The details about this puzzle are as follows. A set of 8 kinds of coins of different values are created, the king wants you to find out the maximum N such that any number of price from 0 to N can be paid with a combination no more than 8 coins and without charges. For example, (taken from Glorfindel's answer). If a set of coins of values 1, 2, 5, 13, 34, 89, 233, 610 are given, your program should output 1596, because every number between 0 and 1596 (inclusive) can be represented by the sum of no more than 8 numbers from the given list (numbers may repeat), while 1597 cannot be represented in that way. In a mathematical way, if the input is a set S consisting of 8 positive integers, the desired output N satisfies that for any number *n* between 0 and N, there exists x1, x2, x3, ..., x8 such that $$x\_1 + x\_2 + ... + x\_8 = n \quad\textrm{and}\quad x\_1, x\_2, ...,x\_8 \in \{0\} \cup S$$ Your goal is to write a program, a function, or a snippet that takes 8 numbers as input, and output the maximum N as described above. Rules: * Flexible I/O allowed, so your program can take the input in any form that's best suitable. You may assume that the input numbers are sorted in the way that best suits your program. + Please state it in your answer if your program depends on input order * Input is a set of 8 different, positive integers (no zeros). The output is one non-negative integer. + In case there's no 1 in the input set, your program should output 0 because any number from 0 to 0 satisfies the requirement. + In the case of invalid input (the set contains zero, negative or duplicate numbers), your program can do anything. * Standard loopholes are forbidden. * Your program should run within a few minutes on a modern computer. Test cases (mostly taken from the answers under the linked question on Puzzling): ``` [1, 2, 3, 4, 5, 6, 7, 8] => 64 [2, 3, 4, 5, 6, 7, 8, 9] => 0 [1, 3, 4, 5, 6, 7, 8, 9] => 72 [1, 2, 5, 13, 34, 89, 233, 610] => 1596 [1, 5, 16, 51, 130, 332, 471, 1082] => 2721 [1, 6, 20, 75, 175, 474, 756, 785] => 3356 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program or snippet in each language wins! [Answer] # [Python 3](https://docs.python.org/3/), ~~113~~ 62 bytes ``` for i in[1]*3:x|={a+b for a in x for b in x} while{i+1}&x:i+=1 ``` Here `x` is the input as a set of ints, and `i` is the output. [Try it online!](https://tio.run/##K6gsycjPM/5foWCrUG2oo2Cmo2BkoKNgbqqjYAgiTMxNQDygsLmFae3/tPwihUyFzLxow1gtY6uKGtvqRO0kBZBoIlBUoQLMTAIza7nKMzJzUqsztQ1r1SqsMrVtDf8XFGXmlWhkav4HAA "Python 3 – Try It Online") (Thanks: Erik the Outgolfer, Mr. Xcoder, Lynn) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` œċⱮ8Ẏ§ṢQJƑƤS ``` [Try it online!](https://tio.run/##y0rNyan8///o5CPdjzaus3i4q@/Q8oc7FwV6HZt4bEnw/8Ptj5rWuP//Hx1tqKNgpKNgrKNgoqNgqqNgpqNgrqNgEavDFY1FWEfBEiRjiE/GCCxsCFRgDFRhYQkUMQZyzAwNoApAskBdpoYgVQZAZcZALSbmIK6BhRFUEVCBEVDOHKQYRJiYm4B4INssTGNjAQ "Jelly – Try It Online") Takes on average ~3.7 seconds to run all test cases on TIO on my phone, so surprisingly it is quite fast. ### Explanation ``` œċⱮ8Ẏ§ṢQJƑƤS Monadic link / Full program. Ɱ8 Promote 8 to [1 ... 8] and for each value k: œċ Generate all combinations of k elements from the list. Ẏ§ Tighten, then sum. Flatten to a 2D list then sum each. ṢQ Sort the result and remove equal entries. JƑƤ For each prefix of this list, return 1 if it is equal to its length range, 0 otherwise. S Finally, sum the result (counts the 1's which is equivalent to what is being asked). ``` [Answer] ## Haskell, ~~56~~ 50 bytes ``` g c=[x|x<-[1..],all((/=x).sum)$mapM(0:)$c<$c]!!0-1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P10h2Ta6oqbCRjfaUE8vVicxJ0dDQ9@2QlOvuDRXUyU3scBXw8BKUyXZRiU5VlHRQNfwf25iZp6CrUJBUWZeiYKKQrpCtKGOkY6FjrGRjqGhIZgwARGmIMIs9j8A "Haskell – Try It Online") A brute force approach. Add `0` to the list of coins and try all combinations of 8 picks. Find the first number `n` that is not equal to the sum of any of the picks and return `n-1`. Takes about 5m30s for `[1, 2, 5, 13, 34, 89, 233, 610]` on my 7 year old laptop hardware. Edit: -6 bytes thanks to @Ørjan Johansen An even shorter version (-2 bytes, again thanks to @Ørjan Johansen) is ### Haskell, 48 bytes ``` g c=[x|x<-[1..],all((/=x).sum)$mapM(:0:c)c]!!0-1 ``` but it uses significantly more memory and runs into heavy paging on my machine and does not finish "within a few minutes". [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Żœċ8§ḟ’$Ṃ ``` [Try it online!](https://tio.run/##y0rNyan8///o7qOTj3RbHFr@cMf8Rw0zVR7ubPp/uP1R0xoF9///o6MNdRSMdBQUjIHYBIgVTEGEGYgwBxEKFrFcOtFAFTAFaPIWYEWWIEWGRCoygigwBCk2Bqm2sAQKGoO4ZoYGUEUgBUADTA1BCg2AJhsDtZmYg7gGFkZQRUAFRkA5c5BiEGFibgLigSw2tzCN5YoFAA "Jelly – Try It Online") ### How it works ``` Żœċ8§ḟ’$Ṃ Main link. Argument: A (array) Ż Prepend a 0 to A. œċ8 Take all combinations of length 8, with repetitions. § Take the sum of each combination. $ Combine the two links to the left into a monadic chain. ’ Decrement all sums. ḟ Filterfalse; keep only sums that do not appear in the decremented sums. Ṃ Take the minimum. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes ``` LengthWhile[CoefficientList[(1+Tr[x^#])^8,x],#>0&]-1& ``` [Try it online!](https://tio.run/##fY1NC4JAFEX/ygNBip7k@DXjIgnaumgRtBhGEBlzIA1sFoL42@1NuIw2D@495/L62na6r61p6rWFE6ylHh62u3fmqeXlpdvWNEYPtjRvK3fscBvlVHlqXwmcFHpF6KuA@et1NIOVHgQFtNJTCnw4nmGeGUKEECMkCClChsARxIIw/6gRckfYPxJ9a0ZCTIbIqYkpZCzcBEdplTJnhaTFNEm4i6GINomEiBh3sjsJT1xy30S6LOsH "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), ~~100 88 80~~ 76 bytes This is essentially a brute-force search, but enhanced with pruning to speed it up. The average execution time for the test cases is close to 1 second on TIO. Assumes that the input array is sorted from highest to lowest. ``` a=>[...Array(a[0]*9)].findIndex(g=(i=8,s)=>s*i>0?a.every(x=>g(i-1,s-x)):s)-1 ``` [Try it online!](https://tio.run/##jc/NjoMgFAXg/TwFS2iQgsiPk@BklvMMxgWpaGganUjT2Ke3V7tpnC6G3U3Od8/l7G8@nab4e82GsQ1L5xbvqpox9j1N/o59zZtDSRrWxaH9Gdow497h6CxNxFXpECv@5Vm4hemOZ1f1OGaCpmwm5DORTCyncUjjJbDL2OMO15YiQ5GmSFFUUCQpyikSDSHo5R2PSBcfO1lS9Ab/lfxf8E2lyfdSCw4VEuIWlkiQQm47Xm8GKVSp91ZwC6nCCIByzUvYpWASzzM2DzY3udhbYyFglF79Wmq2EWr59olnNVgplV4e "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array [...Array(a[0] * 9)] // create an array of 9 * max(a) entries .findIndex( // find the position of the first truthy result g = (i = 8, s) => // g = recursive function taking a counter i, initialized to 8 // and a sum s, initialized to the position in the above array s * i > 0 ? // if s is positive and i is not equal to 0: a.every(x => // for each value x in a[]: g(i - 1, s - x) // do a recursive call with i - 1 and s - x ) // end of every() : // else: s // yield s (s = 0 means success and makes findIndex go on) ) - 1 // end of findIndex(); decrement the result ``` [Answer] # [Python 2](https://docs.python.org/2/), 145 bytes ``` from itertools import* x=set(map(sum,reduce(chain,map(combinations_with_replacement,[input()]*9,range(9))))) print~-min(set(range(1,max(x)+2))-x) ``` [Try it online!](https://tio.run/##JYxBCoMwFET3niLLxEaoorUuehIRSW1aP5ifkHxpuunVU0NnMTBv4LkPrRablJ7eGgakPVm7BQbGWU9lEW9BEzfK8bAb6fVjXzRfVgUoM1ysuQMqAothfgOts9duU4s2GkmOgG4nLqZykF7hS/NB5BTOA9K3MoA86/9ffRgjj@LUCFFFkdJYS3aRrDlL1neS1bnavs3rwP21m34 "Python 2 – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 57 bytes ``` a->n=-1;while(polcoeff((1+sum(i=1,8,x^a[i]))^8,n++),);n-1 ``` [Try it online!](https://tio.run/##fY3dCoMwDEZfJXjVYgrGn1kRfRFRKGNuBafFbWx7epcML8duQr7vnJDgVm/OYRuhgc2Zdm4M1c@Ln04qLNNxOY2jUhTfHlflG0KLr8F1vtd6sDjHsUZdz4Y2F8L0Vg5MC2H1853XSEIEo3JaI3QdIaQIGUKOUCAcEEoE2zP6USNUQugfSb81sZCxYStuMg4HSnZBKF8VJFbCWsYneSkxsekusZAyK0WWkZe5JPlmi77X2wc "Pari/GP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~125~~ ~~115~~ 111 bytes ``` lambda c:sum(i==j for i,j in enumerate(sorted(set(map(sum,product([0]+c,repeat=8))))))-1 from itertools import* ``` [Try it online!](https://tio.run/##fZDBboMwDIbPy1P4mG6uRIAWWoknYRwYBC1VQ6LEHPb0zEY9TvPB0v//nxPZ8Ye@w1ruS/e5P0f/NY8w3fPmteu6BywhgcMHuBXsunmbRrI6h0R21tmS9mPUDGNMYd4m0n0xfEyYbLQjde3pqLNRSwoeHNlEITwzOB/5ifedbKYMHfSqNwglQoVQI1wQrggNQjug6v@wEW6SmP@S8rANAxUT7Y2disXVFC9AUp66GKEKxioeqRuRRVu@IAZKzhqBpdVNLUp@ay/MDErJiWQRudGx0F29xeRWgkWLPu2/ "Python 2 – Try It Online") Expects a list of integers as input. Explanation: ``` # an anonymous function lambda c: # get all length-8 combinations of values, from (0,0,0,0,0,0,0,0) to (8,8,8,8,8,8,8,8) # zero is added to ensure that combinations of fewer than 8 coins are represented Ex:(1,0,0,0,0,0,0,0) product([0]+c,repeat=8) # for each combination, sum the values map(sum,.......................) # get unique values, then sort them smallest to largest sorted(set(................................)) # for each index, value pair, return if the index is equal to the value i==j for i,j in enumerate(.............................................) # in Python arithmetic, False is 0 and True is 1. So, count how many items match their index. # Since zero was added to the list, there will always be one extra match (0==0). So offset by one. sum(........................................................................)-1 from itertools import* ``` [Answer] # Perl6, 65 63 41 bytes (39 37 chars) ``` {@_=(0,|@_)X+(0,|@_)for ^3;($_ if $_==$++for @_.sort.unique)-1} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@7/aId5Ww0CnxiFeM0IbwtArzcssLE3VTMsvUogzttZQiVfITFNQibe1VdHWBgkClRTnF5XA1Oka1v4vTgQZp2GoY6ZjZKBjbqpjCMQm5iZAppmOuYWppjXXfwA "Perl 6 – Try It Online") This is an anonymous block that gets passed its data as an array. The `(0,|@_)` is a quick way to add a `0` to `@_`, and even though it's done twice, it's still a bit shorter than `@_.push: 0;` which would then need spaces after the `_`. This is a brute force approach that cheeses a bit on the fact that it's 8 combinations. After cross adding, an anonymous list is created for sequential values. With math operators, lists evaluate to their length, so the -1 pulls double duty: accounting for the 0 and coercing to Int. This can take its sweet time, but by changing one or both `(0,|@_)` to `(0,|@_.unique)` before the first `for` it can be sped up considerably. That adds **+7** (runtime <60s) or **+14** (runtime <10s) to the score if you feel the first is too slow (I did this for the linked code to avoid timeouts after 60 seconds). **Edit:** JoKing in the comments improved it (same idea, cross add, then return the last consecutive result) to an astonishing 39 chars (41 bytes): ``` {(@_=@_ X+0,|@_)xx 3;first *+1∉@_,^∞} ``` [Try it online!](https://tio.run/##dc7PasJAEAbw@z7FIFKTOsj@y26CpKSH3nouhZCGHCIEUpXEg6Le7Uv04XyRdGbpsb0sfPP9Zth9O/Ru@jzBQ5tP56io86KG96XES1HHxyOY9aYbxgM8LtX99lXU@HG/fV@nzW6AqO@27RjDWQAAXZg3@Wrc990hmkH@BLN4zcXYnKCNLvOmlNXq5e35NcYF1wukkarEVUylQtAIBsEiJAgOwSOkFTNnRflHh5CFWgpe/q/1Wvzepk6RMsTSjCaGglMyKJVkLjhGdCFRjCVpQ5vWc5SpDlZ7rYIlp4l43uHHesuJP5AmgRqTuB8 "Perl 6 – Try It Online") The final tabulation doesn't need a 0, saving a few bytes by only needing to add 0 in once. The `xx 3` mimics the for loop (still cheeses on the coins being a power of 2). The `first` sub returns the first number in the infinite list `0..*` (`^Inf` is possible too, but doesn't save space) whose `+1` is not a member of the cross added list. Like mine, it's slow, so add **+7** for a `unique` after the first equals if you feel it's too slow for guidelines. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~171~~ ~~145~~ 115 bytes ``` f=(s,n=3)=>n?f(s=new Set(a=[0,...s]),n-1,a.map(m=>a.map(n=>s.add(m+n)))):Math.min(...[...s].filter(m=>!s.has(m+1))) ``` [Try it online!](https://tio.run/##lc6xboMwEIDhvU9x3Wz1csIYAklk@gSdOqIMVjANFZgoRu3j07t0q5KhHiyf9X@WP/2XT6frcFk2ce7CuvZOJYzOatfE114lF8M3vIdFeddmSETpqDFuDHqa/EVNrvk9RNck8l2nppeoee3f/HKmaYiKTXtz1A/jEq5inhOdfeLWcLo@neaY5jHQOH@oXrUGIUewCAVCibBFqBDqo9aHv@WdDGF3rzT/KfNbZhhYFvWObywPW5M9AFLzq6URlTGz/ERRyZjV@QPEIOe2EixbURUyye/qUsz6Aw "JavaScript (Node.js) – Try It Online") Port of @Mark's Python 3 answer. 108 bytes in Firefox 30-57: ``` f=(s,n=3)=>n?f(new Set((for(n of s=[0,...s])for(m of s)n+m)),n-1):Math.min(...[...s].filter(m=>!s.has(m+1))) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` 0//.x_/;Min[Tr/@FrobeniusSolve[#,x+1]]<9:>x+1& ``` [Try it online!](https://tio.run/##fdBNS8NAEAbge37FgFBqHLrf2aQ1JSdvgqC3UiSWFAM2hWSVQshvjzM1uUkvy77L8w7DnsrwWZ3KUB/K8ZiPUojV5V1snutm99aK4qk9f1RN/d29nr9@qt0dXh7Ufv@Yrbd0WYyh6kKX91GvEDSCQbAIDiFB8AjpgLCM8y0kNr6P@n8AQjYbyUTdJF5PRl@BImrIphm9GAqJkjNVLksmzJJmOcUNSRVDdes5ylTPBe21mgqENTnPRT6st5x4n9QNf9wYx/OH6KWtm1DER1Fc/2L8BQ "Wolfram Language (Mathematica) – Try It Online") Brute force approach: checks integers counting upward until it reaches a value that can't be paid for in 8 coins. Very, very slow (tio times out), but I'm fairly sure the condition is correct. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 161 bytes ``` import StdEnv,Data.List $l=:[1:_]#k=sort(nub(map sum(iter 8(concatMap(\[h:t]=[[e,h:t]\\e<-[0:l]|e>=h]))[[0]]))) =length(takeWhile((>=)1)(zipWith(-)(tl k)k)) $_=0 ``` [Try it online!](https://tio.run/##JY6xasMwFEX3fIWgHiSQixw3bTBRpmQopFDIkEEW4dVRYmFJNvZzoaXfXlWh07mXe4bbOAMh@v4yO0M82BCtH/oRyREv@/DJd4DweLATLjInK1VUZ/3QySkZNMwf1MNAptlTi2Yka9r0oQF8g4HWqq1QS6UMv4e6NptcicrpH7OVrWZMKaET2EI6E27YUoTOnFrrDKVbyQpGv@1wsmnIGUVHOtYlOTtLEY8I6aAkGVEFJytOiueEFItScFKWS06eXu5VrJc6/jZXB7cp5q@HuPsK4G3zX94d4LUffczbuBJC@D8 "Clean – Try It Online") ]
[Question] [ Given `n` numbers in an array (you can't assume they are integers), I would like to compute the product of all subsets of size `n-1`. You can do this by multiplying all the numbers together and then dividing by each one in turn, as long as none of the numbers is zero. However, how quickly can you do this with no division? > > If you don't allow division, what is the minimum number of > arithmetic operations (e.g. multiplication and addition) needed to compute the product of all subsets of size > n-1? > > > Clearly you can do it in `(n-1)*n` multiplications. To clarify, the output is `n` different products and the only operations apart from reading and writing to memory allowed are multiplication, addition and subtraction. **Example** If the input has three numbers `2,3,5`, then the output is three numbers `15 = 3*5`, `10 = 2*5` and `6 = 2*3`. **Winning criterion** Answers should give an exact formula for the number of arithmetic operations their code will use in terms of `n`. To make life simple, I will just plug `n = 1000` into your formula to judge its score. The lower the better. If it's too hard to produce an exact formula for your code, you can just run it for `n = 1000` and count the arithmetic operations in the code. An exact formula would be best however. You should add your score for `n=1000` to your answer for easy comparison. [Answer] # Python, 3(n-2) operations, score = 2994 ``` l = list(map(float, input().split())) n = len(l) left = [0] * len(l) right = [0] * len(l) left[0] = l[0] right[-1] = l[-1] for i in range(1,len(l)-1): left[i] = l[i] * left[i - 1] right[-i-1] = l[-i-1] * right[-i] result = [0] * len(l) result[-1] = left[-2] result[0] = right[1] for i in range(1, len(l) - 1): result[i] = left[i - 1] * right[i+1] print(result) ``` The arrays `left` and `right` contain the cumulated products of the array from the left and from the right, respectively. ## EDIT: Proof that 3(n-2) is the optimal number of operations needed for n >= 2, if we only use multiplication. We will do that by induction; by the above algorithm, we just have to prove that for n >= 2, 3(n-2) is a lower bound on the number of multiplications needed. For n = 2, we need at least 0 = 3(2-2) multiplications, so the result is trivial. Let n > 2, and suppose for n - 1 elements, we need at least 3(n-3) multiplications. Consider a solution for n elements with k multiplications. Now, we remove the last of these elements as if it was 1, and simplify all multiplications directly by it. We also remove the multiplication leading to the product of all the other elements, since that one is not needed as it can never be used as an intermediate value to get the product of n-2 of the other elements, since division is not allowed. This leaves us with l multiplications, and a solution for n - 1 elements. By induction hypothesis, we have l >= 3(n-3). Now, let's have a look at how many multiplications were removed. One of them was the one leading to the product of all elements except the last. Moreover, the last element was used directly in at least two multiplications: if it was used in only one, then it was used when multiplying by an intermediate result consisting in some product of the other elements; let's say, without loss of generality, this this intermediate result included the first element in the product. Then, there is no way to get the product of all the elements but the first, since every product that contains the last element is either the last element, or contains the first element. We thus have k >= l+3 >= 3(n-2), proving the claimed theorem. [Answer] # [Haskell](https://www.haskell.org/), score 2994 ``` group :: Num a => [a] -> [[a]] group (a:b:t) = [a,b] : group t group [a] = [[a]] group [] = [] (%) :: (Num a, Eq a) => a -> a -> a a % 1 = a 1 % b = b a % b = a * b prod_one_or_two :: (Num a, Eq a) => [a] -> a prod_one_or_two [a, b] = a % b prod_one_or_two [x] = x insert_new_value :: (Num a, Eq a) => ([a], a) -> [a] insert_new_value ([a, b], c) = [c % b, c % a] insert_new_value ([x], c) = [c] products_but_one :: (Num a, Eq a) => [a] -> [a] products_but_one [a] = [1] products_but_one l = do combination <- combinations ; insert_new_value combination where pairs = group l subresults = products_but_one $ map prod_one_or_two pairs combinations = zip pairs subresults ``` [Try it online!](https://tio.run/##fVHLTsMwELz7K/ZApRQliMItEG5c@YHKitapRaM6dohtWvHzYe1EfeAIH7yP2Z3ZtfdoD1KpcfwcjO@hLOHDd4BQvcEWORRkyHI2wRmWonRrqAjMBYcSpryb8dBS3XRsY4Izlq3WgT2L9Dm8fwGugwoGjeliCCvYUD2yDXmCPBFzwUO4p4j1g9nVRsvaDLU7mkXKeXBMimloEDySEWkKnwJ2YqzVVg6u1vJYf6PyclElI5k8@EVUTJuySS6HJj5YEzQpILNcfbqU8mlR3zhbC@/CkP9tGuST@vkvNguQIoABnZ2BxnSi1ehao@G1uA4tvEAy5hUeGY57OciJLJwe28ES@/T56py3XgzSeuUCmMxzBx328Pc7IteZ4WawCn7afha7UI8qLvzwmMNTDsUzZx22Ogq22pFK@hDjLw "Haskell – Try It Online") Say we're given the list `[a,b,c,d,e,f,g,h]`. We first group it into pairs `[[a,b],[c,d],[e,f],[g,h]]`. Then, we recurse on the half-size list `pairs` of their products to get `subresults` ``` [a*b, c*d, e*f, g*h] -> [(c*d)*(e*f)*(g*h), (a*b)*(e*f)*(g*h), (a*b)*(c*d)*(g*h), (a*b)*(c*d)*(e*f)] ``` If we take the first element `(c*d)*(e*f)*(g*h)`, and multiply it by `b` and `a` respectively, we get the product of all but `a` and all but `b`. Doing this for every pair and recursive result with that pair missing, we get out final result. The odd-length case is specially handled by having the odd element passed unpaired to the recursive step, and the product of the remaining elements returned is the product without it. The number of multiplications `t(n)` is `n/2` for the pairing product, `t(n/2)` for the recursive call, and another `n` for the products with individual elements. This gives `t(n) = 1.5 * n + t(n/2)` for odd `n`. Using a more precise counts for odd `n` and ignoring multiplying with `1` for the base case gives score `2997` for `n=1000`. [Answer] # [Haskell](https://www.haskell.org/), score 9974 ``` partition :: [Float] -> ([Float], [Float]) partition = foldr (\a (l1,l2) -> (l2, a:l1)) ([],[]) (%) :: Float -> Float -> Float a % 1 = a 1 % b = b a % b = a*b merge :: (Float, [Float]) -> (Float, [Float]) -> (Float, [Float]) merge (p1,r1) (p2, r2) = (p1%p2, map(%p1)r2 ++ map(%p2)r1) missing_products' :: [Float] -> (Float, [Float]) missing_products' [a] = (a,[1]) missing_products' l = merge res1 res2 where (l1, l2) = partition l res1 = missing_products' l1 res2 = missing_products' l2 missing_products :: [Float] -> [Float] missing_products = snd . missing_products' ``` [Try it online!](https://tio.run/##jVLBTsQgEL3zFXOwEVxshGOTevQnamOmLu6SZVsCNX5@HbBaXfYgB/IY3nvzhvaI8WScWxaPYbaznUZoGuie3IRzD/ePwFcsv4uCbdQW3ia3D8CfEbhT0mmRNU5LwMYpIUjfy45EjFciWWeTRPoLGEIFigyRKUIDoSHXEsK7gbGzCQeTHHgWbHlyx3/UVgfulQyKgnkKGShwm0pVOp3R88orETTsdutJCyJTdxujHQ8vPkz799c53l4@U9GsEHTYp14oO3X13tHtV8RgokqbZkDr42iCySit9MzgcuztO7if6ywln9Jd/ebo6xxdDnox5wpLWgtx3ENdui5prk7VtXogGdr01/hgxxluCjK45RM "Haskell – Try It Online") A divide-and-conquer strategy, very reminiscent of merge sort. Doesn't do any indexing. The function `partition` splits the list into as-equal-as-possible halves by putting alternating elements on opposite sides of the partition. We recursively merge the results `(p,r)` for each of the halves, with `r` the list of products-with-one-missing, and `p` the overall product. For the output for the full list, the missing element must be in one of the halves. The product with that element missing is a one-missing-product for the half it's in, multiplied by the full product for the other half. So, we multiply each product-with-one-missing by the full product of the other half and make a list of the results, as `map(*p1)r2 ++ map(*p2)r1)`. This takes `n` multiplications, where `n` is the length. We also need to make a new full-product `p1*p2` for future use, costing 1 more multiplication. This gives the general recursion for for the number of operations `t(n)` with `n` even: `t(n) = n + 1 + 2 * t(n/2)`. The odd one is similar, but one of the sublists is `1` larger. Doing out the recursion, we get `n*(log_2(n) + 1)` multiplications, though the odd/even distinction affects that exact value. The values up to `t(3)` are improved by not multiplying by `1` by defining a variant `(%)` of `(*)` that shortcuts the `_*1` or `1*_` cases. This gives `9975` multiplications for `n=1000`. I believe Haskell's laziness means the unused overall product in the outer layer is not computed for `9974`; if I'm mistaken, I could omit it explicitly. [Answer] ## O(n log n) operations, score = 9974 Works with a binary tree. ## Python ``` l = list(map(int, input().split())) n = len(l) p = [0] * n + l for i in range(n - 1, 1, -1): p[i] = p[i + i] * p[i + i+1] def mul(x, y): if y == None: return x return x * y r = [None] * n + [[None]] * n for i in range(n - 1, 0, -1): r[i] = [mul(p[i + i + 1], x) for x in r[i + i]] + [mul(p[i + i], x) for x in r[i + i + 1]] u = r[1] j = 1 while j <= n: j += j print(u[n+n-j:] + u[:n+n-j]) ``` This also requires list addition operations, and some arithmetic on numbers that are not the input values; not sure if that counts. The `mul` function is there to save n operations for the base case, to avoid wasting them by multiplying by 1. In any case, this is O(n log n) operations. The exact formula is, if only counting arithmetic operations on input numbers, with `j = floor(log_2(n))`: `j * (2^(j + 1) - n) + (j + 1) * (2 * n - 2^(j + 1)) - 2`. Thanks to @xnor for saving one operation with the idea of not computing the outer product! The last part is to output the products in order of the missing term. [Answer] # [Haskell](https://www.haskell.org/), score 2994 ``` group :: [a] -> Either [(a, a)] (a, [(a, a)]) group [] = Left [] group (a : l) = case group l of Left pairs -> Right (a, pairs) Right (b, pairs) -> Left ((a, b) : pairs) products_but_one :: Num a => [a] -> [a] products_but_one [_] = [1] products_but_one [a, b] = [b, a] products_but_one l = case group l of Left pairs -> let subresults = products_but_one [a * b | (a, b) <- pairs] in do ((a, b), c) <- zip pairs subresults; [c * b, c * a] Right (extra, pairs) -> let subresult : subresults = products_but_one (extra : [a * b | (a, b) <- pairs]) in subresult : do ((a, b), c) <- zip pairs subresults; [c * b, c * a] ``` [Try it online!](https://tio.run/##nVHLTsMwELznK@bAIUZtRa@B9MYNceBqWZGTuo2Fm0R@SAjx78GPRK2UIBC@rD07Ozu7brl5F0qN41n3bkBRgHKG7QHP0rZCg@Z8A04YQpwfJEtsylDiRZysv01QzlFAEY833AgkUKE/ZUjMgUttQoM3eW5tlI0Q8YQJqmco0GJRHmg18dITNxt0f3SNNVXtbNV3Ijh/dRdwlId5BB@WPFoF03S/lgpNYtY7WKtVv4/l34ASFsbVWhinrEEZwXRWmuIeNb4wjfi0TVosFskOx34ef4Mm5j/lMPW7NnkEbYKQ5/jA2XWb4sNqfrPRpUO/1r@6TWoofrZNZt@38v@bYVTxp3a7/QPLLtxrlt6R7Czuls7U@A0 "Haskell – Try It Online") ### How it works This is a cleaned up version of [xnor’s algorithm](https://codegolf.stackexchange.com/a/127156/39242) that deals with the odd case in a more straightforward way (edit: it looks like xnor has cleaned it up the same way): [a, b, c, d, e, f, g] ↦ [a, bc, de, fg] ↦ [(bc)(de)(fg), a(de)(fg), a(bc)(fg), a(bc)(de)] by recursion ↦ [(bc)(de)(fg), a(de)(fg)c, a(de)(fg)b, a(bc)(fg)e, a(bc)(fg)d, a(bc)(de)g, a(bc)(de)f] [a, b, c, d, e, f, g, h] ↦ [ab, cd, ef, gh] ↦ [(cd)(ef)(gh), (ab)(ef)(gh), (ab)(cd)(gh), (ab)(cd)(ef)] by recursion ↦ [(cd)(ef)(gh)b, (cd)(ef)(gh)a, (ab)(ef)(gh)d, (ab)(ef)(gh)c, (ab)(cd)(gh)f, (ab)(cd)(gh)e, (ab)(cd)(ef)h, (ab)(cd)(ef)g]. [Answer] # O((n-2)\*n) = O(n2): Trivial Solution This is just the trivial solution that multiplies together each of the subsets: # Python ``` def product(array): # Requires len(array) - 1 multiplication operations if not array: return 1 result = array[0] for value in array[1:]: result *= value return result def getSubsetProducts(array): products = [] for index in range(len(array)): # calls product len(array) times, each time calling on an array of size len(array) - 1, which means len(array) - 2 multiplication operations called len(array) times products.append(product(array[:index] + array[index + 1:])) return products ``` Note that this also requires `n` list-addition operations; not sure if that counts. If that is not allowed, then `product(array[:index] + array[index + 1:])` can be replaced to `product(array[:index]) * product(array[index + 1:])`, which changes the formula to `O((n-1)*n)`. [Answer] # Python, 7540 A tripartite merge strategy. I think I can do even better than this, with a yet large merge. It's O(n log n). EDIT: Fixed a miscount. ``` count = 0 def prod(a, b): if a == 1: return b if b == 1: return a global count count += 1 return a * b def tri_merge(subs1, subs2, subs3): total1, missing1 = subs1 total2, missing2 = subs2 total3, missing3 = subs3 prod12 = prod(total1, total2) prod13 = prod(total1, total3) prod23 = prod(total2, total3) new_missing1 = [prod(m1, prod23) for m1 in missing1] new_missing2 = [prod(m2, prod13) for m2 in missing2] new_missing3 = [prod(m3, prod12) for m3 in missing3] return prod(prod12, total3), new_missing1 + new_missing2 + new_missing3 def tri_partition(nums): split_size = len(nums) // 3 a = nums[:split_size] second_split_length = split_size + (len(nums) % 3 == 2) b = nums[split_size:split_size + second_split_length] c = nums[split_size + second_split_length:] return a, b, c def missing_products(nums): if len(nums) == 1: return nums[0], [1] if len(nums) == 0: return 1, [] subs = [missing_products(part) for part in tri_partition(nums)] return tri_merge(*subs) def verify(nums, res): actual_product = 1 for num in nums: actual_product *= num actual_missing = [actual_product // num for num in nums] return actual_missing == res[1] and actual_product == res[0] nums = range(2, int(input()) + 2) res = missing_products(nums) print("Verified?", verify(nums, res)) if max(res[1]) <= 10**10: print(res[1]) print(len(nums), count) ``` The relevant function is `missing_products`, which gives the overall product and all of the ones with a missing element. [Answer] # dc, score 2994 ``` #!/usr/bin/dc -f # How it works: # The required products are # # (b × c × d × e × ... × x × y × z) # (a) × (c × d × e × ... × x × y × z) # (a × b) × (d × e × ... × x × y × z) # ... # (a × b × c × d × e × ... × x) × (z) # (a × b × c × d × e × ... × x × y) # # We calculate each parenthesised term by # multiplying the one above (on the left) or below # (on the right), for 2(n-2) calculations, followed # by the n-2 non-parenthesised multiplications # giving a total of 3(n-2) operations. # Read input from stdin ? # We will store input values into stack 'a' and # accumulated product into stack 'b'. Initialise # stack b with the last value read. sb # Turnaround function at limit of recursion: print # accumulated 'b' value (containing b..z above). [Lbn[ ]nq]sG # Recursive function - on the way in, we stack up # 'a' values and multiply up the 'b' values. On # the way out, we multiply up the 'a' values and # multiply each by the corresponding 'b' value. [dSalb*Sb z1=G lFx dLb*n[ ]n La*]dsFx # Do the last a*b multiplication dLb*n[ ]n # And we have one final 'a' value that doesn't have a # corresponding 'b': La*n ``` I'm assuming that the integer comparison `z1=` (which terminates the recursion when we reach the last value) is free. This is equivalent to the likes of `foreach` in other languages. ## Demonstrations ``` for i in '2 3 5' '2 3 5 7' '0 2 3 5' '0 0 1 2 3 4' do printf '%s => ' "$i"; ./127147.dc <<<"$i"; echo done 2 3 5 => 15 10 6 2 3 5 7 => 105 70 42 30 0 2 3 5 => 30 0 0 0 0 0 1 2 3 4 => 0 0 0 0 0 0 ``` A demo with large and small inputs: ``` ./127147.dc <<<'.0000000000000000000542101086242752217003726400434970855712890625 1 18446744073709551616' 18446744073709551616 1.0000000000000000000000000000000000000000000000000000000000000000 .0000000000000000000542101086242752217003726400434970855712890625 ``` [Answer] # C++, score: 5990, O([2NlogN]/3) This implementation uses a binary tree look up table. My first implementation was O(NlogN), but a last minute optimization, which looks up the product of all array elements minus a pair, + 2 multiplications saved the day. I think this could still be optimized a bit further, maybe another 16%... I've left some debugging traces in, only because it's easier to delete them than to rewrite them :) [Edit] the actual complexity is measured at O([2NlogN]/3) for 100. It is actually a bit worse than O(NlogN) for small sets, but tends towards O([NlogN]/2) as the array grows very large O(0.57.NlogN) for a a set of 1 million elements. ``` #include "stdafx.h" #include <vector> #include <iostream> #include <random> #include <cstdlib> using DataType = long double; using DataVector = std::vector<DataType>; struct ProductTree { std::vector<DataVector> tree_; size_t ops_{ 0 }; ProductTree(const DataVector& v) : ProductTree(v.begin(), v.end()) {} ProductTree(DataVector::const_iterator first, DataVector::const_iterator last) { Build(first, last); } void Build(DataVector::const_iterator first, DataVector::const_iterator last) { tree_.emplace_back(DataVector(first, last)); auto size = std::distance(first, last); for (auto n = size; n >= 2; n >>= 1) { first = tree_.back().begin(); last = tree_.back().end(); DataVector v; v.reserve(n); while (first != last) // steps in pairs { auto x = *(first++); if (first != last) { ++ops_; x *= *(first++); // could optimize this out,small gain } v.push_back(x); } tree_.emplace_back(v); } } // O(NlogN) implementation... DataVector Prod() { DataVector result(tree_[0].size()); for (size_t i = 0; i < tree_[0].size(); ++i) { auto depth = tree_.size() - 1; auto k = i >> depth; result[i] = ProductAtDepth(i, depth); } return result; } DataType ProductAtDepth(size_t index, size_t depth) { if (depth == 0) { return ((index ^ 1) < tree_[depth].size()) ? tree_[depth][index ^ 1] : 1; } auto k = (index >> depth) ^ 1; if ((k < tree_[depth].size())) { ++ops_; return tree_[depth][k] * ProductAtDepth(index, depth - 1); } return ProductAtDepth(index, depth - 1); } // O([3NlogN]/2) implementation... DataVector Prod2() { DataVector result(tree_[0].size()); for (size_t i = 0; i < tree_[0].size(); ++i) // steps in pairs { auto depth = tree_.size() - 1; auto k = i >> depth; auto x = ProductAtDepth2(i, depth); if (i + 1 < tree_[0].size()) { ops_ += 2; result[i + 1] = tree_[0][i] * x; result[i] = tree_[0][i + 1] * x; ++i; } else { result[i] = x; } } return result; } DataType ProductAtDepth2(size_t index, size_t depth) { if (depth == 1) { index = (index >> 1) ^ 1; return (index < tree_[depth].size()) ? tree_[depth][index] : 1; } auto k = (index >> depth) ^ 1; if ((k < tree_[depth].size())) { ++ops_; return tree_[depth][k] * ProductAtDepth2(index, depth - 1); } return ProductAtDepth2(index, depth - 1); } }; int main() { //srand(time()); DataVector data; for (int i = 0; i < 1000; ++i) { auto x = rand() & 0x3; // avoiding overflow and zero vaolues for testing data.push_back((x) ? x : 1); } //for (int i = 0; i < 6; ++i) //{ // data.push_back(i + 1); //} //std::cout << "data:["; //for (auto val : data) //{ // std::cout << val << ","; //} //std::cout << "]\n"; ProductTree pt(data); DataVector result = pt.Prod2(); //std::cout << "result:["; //for (auto val : result) //{ // std::cout << val << ","; //} //std::cout << "]\n"; std::cout << "N = " << data.size() << " Operations :" << pt.ops_ << '\n'; pt.ops_ = 0; result = pt.Prod(); //std::cout << "result:["; //for (auto val : result) //{ // std::cout << val << ","; //} //std::cout << "]\n"; std::cout << "N = " << data.size() << " Operations :" << pt.ops_ << '\n'; return 0; } ``` I'm adding @nore's algorithm, for completeness. It's really nice, and is the fastest. ``` class ProductFlat { private: size_t ops_{ 0 }; void InitTables(const DataVector& v, DataVector& left, DataVector& right) { if (v.size() < 2) { return; } left.resize(v.size() - 1); right.resize(v.size() - 1); auto l = left.begin(); auto r = right.rbegin(); auto ol = v.begin(); auto or = v.rbegin(); *l = *ol++; *r = *or++; if (ol == v.end()) { return; } while (ol + 1 != v.end()) { ops_ += 2; *l = *l++ * *ol++; *r = *r++ * *or++; } } public: DataVector Prod(const DataVector& v) { if (v.size() < 2) { return v; } DataVector result, left, right; InitTables(v, left, right); auto l = left.begin(); auto r = right.begin(); result.push_back(*r++); while (r != right.end()) { ++ops_; result.push_back(*l++ * *r++); } result.push_back(*l++); return result; } auto Ops() const { return ops_; } }; ``` ]
[Question] [ Write a program or function that, when given `n`, will print a spiral `n` characters long made up of the Latin alphabet `ABCDEFGHIJKLMNOPQRSTUVWXYZ` repeated as needed. This spiral should run through the alphabet only forwards. Related to [Alphabet Spiral](https://codegolf.stackexchange.com/questions/89725/alphabet-spiral?rq=1), though the spiral runs through the alphabet forwards and backwards, and the spiral is constant. **Test cases** ``` 4 AB DC 40 UVWXYZ TGHIJA NSFABKB MREDCLC LQPONMD KJIHGFE 0 10 GHIJ FAB EDC 1000 UVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ TGHIJKLMNOPQRSTUVWXYZABCDEFGHIJA SFABCDEFGHIJKLMNOPQRSTUVWXYZABKB REZCDEFGHIJKLMNOPQRSTUVWXYZABCLC QDYBMNOPQRSTUVWXYZABCDEFGHIJCDMD PCXALEFGHIJKLMNOPQRSTUVWXYZKDENE OBWZKDEFGHIJKLMNOPQRSTUVWXALEFOF NAVYJCDMNOPQRSTUVWXYZABCDYBMFGPG MZUXIBCLCDEFGHIJKLMNOPQREZCNGHQH LYTWHABKBABCDEFGHIJKLMNSFADOHIRI KXSVGZAJAZGHIJKLMNOPQROTGBEPIJSJ JWRUFYZIZYFUVWXYZABCDSPUHCFQJKTK IVQTEXYHYXETQRSTUVWXETQVIDGRKLUL HUPSDWXGXWDSPUVWXYZYFURWJEHSLMVM GTORCVWFWVCROTGHIJAZGVSXKFITMNWN FSNQBUVEVUBQNSFABKBAHWTYLGJUNOXO ERMPATUDUTAPMREDCLCBIXUZMHKVOPYP DQLOZSTCTSZOLQPONMDCJYVANILWPQZQ CPKNYRSBSRYNKJIHGFEDKZWBOJMXQRAR BOJMXQRARQXMLKJIHGFELAXCPKNYRSBS ANILWPQZQPWVUTSRQPONMBYDQLOZSTCT ZMHKVOPYPONMLKJIHGFEDCZERMPATUDU YLGJUNOXONMLKJIHGFEDCBAFSNQBUVEV XKFITMNWVUTSRQPONMLKJIHGTORCVWFW WJEHSLMLKJIHGFEDCBAZYXWVUPSDWXGX VIDGRKJIHGFEDCBAZYXWVUTSRQTEXYHY UHCFQPONMLKJIHGFEDCBAZYXWVUFYZIZ TGBEDCBAZYXWVUTSRQPONMLKJIHGZAJA SFAZYXWVUTSRQPONMLKJIHGFEDCBABKB REDCBAZYXWVUTSRQPONMLKJIHGFEDCLC QPONMLKJIHGFEDCBAZYXWVUTSRQPONMD LKJIHGFE ``` **Rules** * Your input will be a non-negative integer `0 <= n <= 1000`, but your code should theoretically handle any non-negative integer. * Your output format may be in any sane format, with delimiters if necessary. * Rotations and reflections are equivalent. * Your alphabet may be uppercase or lowercase. * The empty spaces in your spiral may be filled in with whatever non-alphabetic nulls you see fit. * The spiral itself may be in any shape you see fit. Rectangular spirals work best with ASCII solutions, but graphical solutions may be shorter with circular spirals. * Leading and trailing spaces and newlines are allowed. * This is code golf. The shortest answer in bytes (or equivalent) wins. As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing! [Answer] # Logo, ~~129~~ 87 bytes ## Graphical solution, implemented as function This was built on [Calormen.com's Logo interpreter](http://calormen.com/jslogo/). The `S` function takes the number of characters as a parameter and draws them in a spiral. ~~The `T` function outputs letters upright to prevent them from rotating with the spiral.~~. I decided that it looked nicer (and golfed out [42 bytes](https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29 "42: The answer to life, the universe, and code golf.")) to omit correcting the letter orientation. I also tightened up the spacing which did not change the byte count. If you were to actually roll up an alphabet, it would look more like this anyway. ### Updated Version (letters roll) ``` TO S:r PU IF:r[REPEAT:r[LABEL CHAR((REPCOUNT-1)%26)+65 RT 99/SQRT(REPCOUNT)FD 12]]END ``` ### Invocation Invoke as follows: `S` *iterations* ### Sample output ``` S 1000 ``` [![Sample output for 1000 iterations](https://i.stack.imgur.com/QiRRK.png)](https://i.stack.imgur.com/QiRRK.png) ## Old Version (letters always upright) ``` TO T:l:h RT:h LABEL CHAR(:l%26)+65 LT:h END TO S:r PU IF:r[REPEAT:r[T REPCOUNT-1 90-HEADING RT 95/SQRT(REPCOUNT)FD 15]]END ``` Old output removed to save space. [See it here](https://i.stack.imgur.com/xmSFc.png). [Answer] ## Javascript (ES6), ~~203~~ 201 bytes ``` n=>{for(a=[],i=d=k=z=0,p=526,j=1;i<n;){p+=[1,32,-1,-32][d&3];j--||(((z^=1)||k++),j=k,d++);(a[y=p>>5]=(a[y]||Array(32).fill` `))[p&31]=String.fromCharCode(65+(i++%26))}return a.map(r=>r.join``).join` `} ``` ### Demo The demo below should be preferably run in full page. ``` let f = n=>{for(a=[],i=d=k=z=0,p=526,j=1;i<n;){p+=[1,32,-1,-32][d&3];j--||(((z^=1)||k++),j=k,d++);(a[y=p>>5]=(a[y]||Array(32).fill` `))[p&31]=String.fromCharCode(65+(i++%26))}return a.map(r=>r.join``).join` `} function draw(n) { document.getElementById('v').innerHTML = n; document.getElementById('o').innerHTML = f(n); } draw(500); ``` ``` pre {font-size:10px} ``` ``` <input type="range" min="1" max="1000" oninput="draw(this.value)" style="width:500px"><span id="v"></span><pre id="o"></pre> ``` [Answer] # R, 46 or 51 bytes, depending on spacing ``` s=1:scan();plot(s*sin(s),s*cos(s),pch=letters) ``` [![enter image description here](https://i.stack.imgur.com/ZYW3f.png)](https://i.stack.imgur.com/ZYW3f.png) (updated version of plot: the gray spiral isn't plotted by default but I added it after to show that the letters indeed lie on a spiral.) The spiral isn't of constant spacing, so I hope this is okay. If constant spacing is required, start with `s=(1:scan())^.5` instead, and add 5 bytes to the total. Then the output is as below (n=150): [![enter image description here](https://i.stack.imgur.com/8IEia.png)](https://i.stack.imgur.com/8IEia.png) [Answer] # Python 3.5, ~~180~~ ~~157~~ ~~152~~ ~~147~~ 141 bytes -6 due to Sherlock9 ``` r=[[]] for x in range(int(input())): r=len(r[-1])<len(r[0])and r or[*zip(*r[::-1]),[]];r[-1]+=[chr(x%26+65)] print(*map(''.join,r),sep='\n') ``` -5 due to Kap. ``` R=range def g(n): r=[[]] for x in R(n): if len(r[-1])==len(r[0]):r=[*zip(*r[::-1]),[]] r[-1]+=[chr(x%26+65)] print(*map(''.join,r),sep='\n') ``` ### Revised Solution, python 3.x: ``` R=range def g(n): r=[[]] for x in R(n): if len(r[-1])==len(r[0]):r=list(zip(*r[::-1]))+[[]] r[-1]+=[chr(x%26+65)] print(*map(''.join,r),sep='\n') ``` ### Previous Solution: ``` R=range def g(n): r=[] for x,f in zip(R(n),(j<1for i in R(n)for j in R(i//2+1))): if f:r=list(zip(*r[::-1]))+[[]] r[-1].append(chr(x%26+65)) print(*map(''.join,r),sep='\n') ``` ### Explanation `r` is a list of lists that holds the spiral. The basic idea is that new letters are added to the bottom row of the spiral (`r[-1].append(chr(x%26+65))`). When the bottom row is filled up, the spiral is rotated 90 clockwise and a new empty row is added to the bottom (`r = list(zip(*r[::-1]))+[[]]`). The trick is to figure out when to rotate the spiral. In the first solution, the generator `(j<1for i in R(n)for j in R(i//2+1))` produces a sequence of True/False values that tell when to rotate the spiral. In the revised solution, I changed the way `r` is initialized. Now when the length of the bottom row equals the length of the top row, the spiral needs to be rotated. [Answer] # [MATL](http://github.com/lmendo/MATL), ~~21~~ 18 bytes ``` X^Xk1YL1Y2y)wG>~*c ``` Input `0` exits with an error (which is [allowed by default](http://meta.codegolf.stackexchange.com/a/4781/36398)). [Try it online!](http://matl.tryitonline.net/#code=WF5YazFZTDFZMnkpd0c-fipj&input=NDA) ### Explanation ``` X^Xk % Input n implicitly. Take square root and round up 1YL % Square matrix of that size containing a spiral of numbers 1Y2 % Predefined literal: string "AB···YZ" y % Duplicate the spiral matrix onto the top ) % Apply as an index inth the string. Gives 2D array of chars w % Swap: move copy of the spiral matrix to top G>~ % Set entries that exceed the input to 0, and the rest to 1 * % Multiply. This makes unwanted entries equal to 0 c % Convert to char. 0 is shown as a space. Display implicitly ``` [Answer] # Python 2, ~~84~~ 82 bytes I'm using Turtle again. It's so fun! :D ``` from turtle import* up() for i in range(input()):write(chr(i%26+65));rt(9);fd(9+i) ``` [**Try it online**](https://trinket.io/python/17138a5005) Unfortunately, Trinket.io has a horribly small canvas. I changed `9+i` to `9+i/9` and adjusted the turtle's starting point for the purpose of screen-capturing this image, so that more of the output would fit: [![output](https://i.stack.imgur.com/PoZcT.png)](https://i.stack.imgur.com/PoZcT.png) [Answer] # Pyth, 32 bytes ``` JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y ``` A program that prints a rectangular lower-case ASCII spiral. Depending on the input, one row or column of leading or trailing whitespace may be present. [Try it online](https://pyth.herokuapp.com/?code=JS%40Q2ju%2B.t_G%29Hc%3C%2aGQQ.u%2BNY.iJJZ%5DY&test_suite=1&test_suite_input=4%0A40%0A0%0A10%0A1000&debug=0) **How it works** ``` JS@Q2ju+.t_G)Hc<*GQQ.u+NY.iJJZ]Y Program. Input: Q @Q2 Yield sqrt(Q) JS Unary range, J=[1, 2, 3, ..., floor(sqrt(q))] .iJJ Interleave J with itself, yielding [1, 1, 2, 2, 3, 3, ... floor(sqrt(Q)), floor(sqrt(Q))] .u+NY Z Cumulatively reduce by addition with base case 0, yielding [0, 1, 2, 4, 6, 9, 12, 16, 20...] *GQ Repeat the lower-case alphabet Q times < Q Truncate to legth Q c Split the above at the indices in the above list u ]Y Reduce the above, with base case [[]]: _G Reverse .t ) Transpose + H Add the next arm of the spiral j Join on newlines and implicitly print ``` [Answer] # TSQL, ~~386~~ ~~362~~ ~~358~~ 306 bytes Please note that TSQL doesn't have a way to rotate text. This script is starting from A and calculating which direction the next letter should be placed. (right, down, left, left, left, up, up, right...) The script can handle a maximum of 7744 letters. **Golfed:** ``` DECLARE @z INT = 7744 DECLARE @ INT=2+SQRT(@z-1)DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1);WITH C as(SELECT 0i,@/2a,@/2b UNION ALL SELECT i+1,a+z/2,b+z%2FROM(SELECT*,IIF(a>@/2*2-b,IIF(a<b,2,-1),IIF(a>b,-2,1))z FROM C)t WHERE i<@z-1)SELECT @o=STUFF(@o,@*a-@+b,1,char(i%26+65))FROM c OPTION(maxrecursion 0)PRINT @o ``` **Ungolfed:** ``` DECLARE @z INT = 7744 DECLARE @ INT=2+SQRT(@z-1) DECLARE @o varchar(max)=REPLICATE(SPACE(@-1)+char(10),@-1) ;WITH C as ( SELECT 0i,@/2a,@/2b UNION ALL SELECT i+1,a+z/2,b+z%2 FROM (SELECT*, IIF(a>@/2*2-b, IIF(a<b,2,-1), IIF(a>b,-2,1))z FROM C)t WHERE i<@z-1 ) SELECT @o=STUFF(@o,@*a-@+b,1,char(i%26+65)) FROM c OPTION(maxrecursion 0) PRINT @o ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/538330/roll-the-alphabet-into-a-spiral)** [Answer] # Python 2, 243 bytes ``` r=range(input()) a=[1j**int((4*i+1)**.5)for i in r] b=[map(int,(-sum(a[:i]).real,sum(a[:i]).imag))for i in r] c,d=zip(*b) for i in range(min(c),max(c)+1):print''.join([i,j]in b and chr(b.index([i,j])%26+65)or' 'for j in range(min(d),max(d)+1)) ``` [Ideone it!](http://ideone.com/EJL6Mz) [Answer] # [PHP](https://php.net/), 219 bytes ``` for($q=ceil(sqrt($a=$argn))**2,$d=1,$x=$y=$w=0;$i<$q;$i++,${yx[$w%2]}+=[-1,1][$d&1],$i%$d?:$d+=$w++&1)$e[$c[]=$x-!($a&1)][$l[]=$y]=$i<$a?chr(65+$i%26):" ";for($k=min($c);$e[$k];print join($e[+$k++])."\n")ksort($e[+$k]); ``` [Try it online!](https://tio.run/##HY/BboMwEETv/YrUmkR21qkwUnOIY/Ehrg8IaHFJwTiRAqr67dRw2D08zczOhjYs1yK04QVl/OoNU1mWMb18DpFjNFXjb/w@xgdHaTaFEMdjLlEbJTEZzAZPk2n4K8a0iSR@58niuc/dHxl7UlI5i/qgnITfoy4uqCmZiA5KoLGorDOYTq/pQiJJe1vBnCZllkXVRn5@p@TNz@LCdkxv1Trz43uOSug1o3M6RN8/dt/DShtL6IiceGMfPRPdfVgf2KgTeln@AQ "PHP – Try It Online") PHP , 260 Bytes Old version ``` for($y=$x=$d=$i=0;$i<$m=ceil(sqrt($n=$argv[1]))**2;$i++){$a[$y][$x]=$i<$n?chr($i%26+65):" ";$d=$y==$x&$y<1?0:(1-$y==$x&$x>0?1:($y==$x&$y>0?2:($y==-$x&$x<0?3:$d)));$d>2?$y--:($d>1?$x--:($d>0?$y++:$x++));}ksort($a);foreach($a as$r){ksort($r);echo join($r)."\n";} ``` ]
[Question] [ Cellular Automata are truly fascinating. The ones that are usually talked about are the binary ones, i.e., the ones representable by a number. However, those, in my opinion, have been done to death. Ternary CAs are more interesting, but we have all of ASCII to consider! What fun could that be! Instead of deciding a ruleset for each character, I will use a simple deciding rule which I will talk about soon. To decide the next generation, we look at the three "top" cells, much like a cellular automata. Observe an example: ``` QWERTY X Y Z ``` The "top" of `Y` is `WER`, being the cells above-and-right, above, and above-and left. Y will be the result of the function I'm about to define, which is a function on three-char strings. The "top" of `X` is `QW`, **or a space filling in the non-existent/missing cell**. Now, for the ~~fun~~ function! I call this sequence the XOROR sequence for a reason. Let `A` be the top-left cell charcode, `B` be the above cell charcode, and `C` be the top-right cell charcode. Then, the resulting cell is the character whose charcode is `(A XOR B) OR C`, that is, `(A^B)|C`. (If a resulting value is greater than 126, then it is set to `(CHARCODE % 127) + 32`. Nothing is done if a value is less than 32.) Here is an example of the seed `Hello, World!`: ``` S: Hello, World! 0: mmmo/c_ z}~)e m = ( )^(H)|(e) = (32^72)|101 = 104|101 = 109 (m) m = (H)^(e)|(l) = (72^101)|108 = 45|108 = 109 (m) etc. 1: mmo/c_< +wl 2: mo/c_<c< + |; 3: o/c_<c ?+ g 4: oc_<c c??4+gg 5: 0_<c c 4+ o 6: _<c ccc4??ooo 7: c ccc4 ?o o 8: ccccc4w? pooo 9: cccc4w h o A: ccc4wc hh ooo B: cc4wc4kh ooo C: c4wc4 #ooo o D: wwc4w4#ooo oo E: wc4wwc oo oo F: w4wwc4oo oo o G: wwwc4 oo oo H: wwc4w4 oo oo I: w4wwc4oooo oo J: wwwc4 oo oo K: wwc4w4oo oo o L: wc4wwo oo oo M: w4wwo8ooo oo N: wwwo8 o oo o O: wwo8w8oooo oo ``` And we can proceed on for a while hereafter. This modification of the string is called the XOROR sequence. **Objective** You are to write a program or function that does one of the following tasks: 1. Given a string `s` and a number `n >= 0`, output the `n`th string on the XOROR sequence with seed `s`, with `n = 0` being the first transformation of the string. 2. Given a string `s`, output (for programs) or generate (for functions/generators) an infinite stream of the XOROR sequence with seed `s`. You may choose to stop if the sequence repeats, but this is not necessary. `s` will always only consist of printable ASCII characters, from space to tilde plus tabs (no newlines.) This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. [Answer] # Mathematica, 133 bytes ``` FromCharacterCode@Nest[BlockMap[If[#>126,#~Mod~127+32,#]&[BitXor[#,#2]~BitOr~#3]&@@#&,ArrayPad[#,1,32],3,1]&,ToCharacterCode@#,#2+1]& ``` It would be nice to make a `CellularAutomaton[]` solution work, but I kept coming up short. Anyone? Edit: some pretty pictures (click to enlarge) ``` plotCA[str_, n_] := ArrayPlot[NestList[foo[str],n], ColorFunction -> "Rainbow"] ``` `plotCA["Hello, World!", 60]`: [![60 iterations of "Hello, World!"](https://i.stack.imgur.com/wORwVs.png)](https://i.stack.imgur.com/wORwV.png) `plotCA[bXORnotb, 100]`: [![100 iterations of Hamlet soliloquy](https://i.stack.imgur.com/bC9qns.png)](https://i.stack.imgur.com/bC9qn.png) `plotCA[raven, 100]`: [![100 iterations of Poe](https://i.stack.imgur.com/pwFnrs.png)](https://i.stack.imgur.com/pwFnr.png) [Answer] ## Java, ~~193~~ 185 bytes [Because Java.](https://codegolf.meta.stackexchange.com/a/5829/51825) *-8 bytes by switching to looping rather than recursing to make it an anonymous function* Returns the n'th iteration of XOROR on s. ``` (s,n)->{String o=s;for(;n-->=0;){o="";for(int i=0;i<s.length();i++){char c=(char)((i>1?s.charAt(i-1):' ')^s.charAt(i)|(i<s.length()-1?s.charAt(i+1):' '));o+=c>126?' ':c;}s=o;}return o;} ``` Readable version: ``` static BiFunction<String, Integer, String> f = (s,n)->{ String o=s; for(;n-->=0;) { o = ""; for (int i=0;i<s.length();i++) { char c=(char)((i>1?s.charAt(i-1):' ')^s.charAt(i)|(i<s.length()-1?s.charAt(i+1):' ')); o+=c>126?' ':c; } s=o; } return o; }; public static void main(String[]a) { System.out.println(f.apply("Hello, World",1)); } ``` Pretty much a literal implementation of the spec, with a recursive loop to apply the operation n times. Some bytes were saved, however, with my observation that the CHARCODE>126 clause will only ever happen with CHARCODE==127, which results in saving `SPACE` instead of `DEL`. I ran my code over a few arbitrarily chosen strings and found this wonderful cycle: ``` oook$ok$ok$ok$ ook$ok$ok$ok$o oo$ok$ok$ok$ok oook$ok$ok$ok$ ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~33~~ 31 bytes ``` Q:"32XKhKwh3YCPo2$1Z}Z~Z|127KYX ``` This works in [release 13.1.0](https://github.com/lmendo/MATL/releases/tag/13.1.0) of the language/compiler, which predates the challenge. The first input is the number, the second is the string. [**Try it online!**](http://matl.tryitonline.net/#code=UToiMzJYS2hLd2gzWUNQbzIkMVp9Wn5afDEyN0tZWA&input=MwonSGVsbG8sIFdvcmxkISc) ``` Q % take input (number) implicitly and add 1 :" % repeat that many times 32XK % push 32 (space). Copy to clipboard K. h % concatenate. Takes input (string) implicitly the first time Kwh % push space, swap, concatenate 3YC % overlapping blocks of length 3 as columns of 2D array P % flip upside-down o % convert to numbers 2$1Z} % separate the three rows and push them Z~ % bitwise XOR (note the rows are in reverse order) Z| % bitwise OR 127KYX % replace 127 by space using regexprep, which converts to char % end loop % implicitly display ``` [Answer] ## CJam, 38 bytes ``` lri){2S*\*3ew{)\:^|_'~>{i127%' +}&}%}* ``` [Test it here.](http://cjam.aditsu.net/#code=lri)%7B2S*%5C*3ew%7B)%5C%3A%5E%7C_'~%3E%7Bi127%25'%20%2B%7D%26%7D%25%7D*&input=Hello%2C%20World!%0A25) ### Explanation ``` l e# Read string. ri e# Read n. ){ e# Run this block n+1 times... 2S*\* e# Wrap in two spaces. 3ew e# Get all (overlapping) substrings of length 3. { e# Map this block over all those substrings... )\ e# Pull off the third character and put it below the other two. :^ e# Take XOR of the other two. | e# OR with the third one. _'~> e# Duplicate and check if it's greater than '~'. {i127%' +}& e# If so, mod 127, add to space. }% }* ``` [Answer] ## Haskell, 123 bytes ``` import Data.Bits f s=toEnum.a<$>zipWith3(((.|.).).xor)(32:s)s(tail s++[32]) a x|x>126=32|1<2=x tail.iterate(f.map fromEnum) ``` This returns an infinite stream of the XOROR sequence. Usage example (print the first 5 elements of the seed `"Hello, World!"`): ``` *Main> mapM_ print $ take 5 $ (tail.iterate(f.map fromEnum)) "Hello, World!" "mmmo/c_ z}~)e" "mmo/c_< +wl" "mo/c_<c< + |;" "o/c_<c ?+ g" "oc_<c c??4+gg" ``` How it works: ``` tail.iterate(f.map fromEnum) -- repeat forever: convert to ASCII -- value and call f, discard the first -- element (the seed). -- one iteration is: zipWith3( )(32:s) s (tail s++[32]) -- zip the elements from the three lists -- (space:s), s and tail of s ++ space, -- e.g. s = "Hello!": -- | Hello| -- |Hello!| -- |ello! | -- (shortest list cuts off) ((.|.).).xor -- the function to zip with is a -- point-free version of (x xor y) or z toEnum.a<$> -- adjust every element >126 and convert -- back to characters ``` [Answer] # PHP, 186 bytes (with n) | 177 bytes (infinite) It turned out that infinite printing is shorter... ``` // With n function x($s,$n){while($n-->=0){for($i=0,$r='';$i<strlen($s);$i++){$b=ord($s[$i-1])or$b=32;$a=ord($s[$i+1])or$a=32;$t=($b^ord($s[$i]))|$a;$r.=chr($t>126?($t%127)+32:$t);}$s=$r;}echo$s;} // Infinite function i($s){while(true){for($i=0,$r='';$i<strlen($s);$i++){$b=ord($s[$i-1])or$b=32;$a=ord($s[$i+1])or$a=32;$t=($b^ord($s[$i]))|$a;$r.=chr($t>126?($t%127)+32:$t);}echo$s=$r;}} ``` Ungolfed with n: ``` function x($s, $n) { // $s - string to process; $n - which string to output while ($n-- >= 0) { for ($i = 0, $r = ''; $i < strlen($s); $i++) { $b = ord($s[$i - 1]) or $b = 32; $a = ord($s[$i + 1]) or $a = 32; $t = ($b ^ ord($s[$i])) | $a; $r .= chr($t > 126 ? ($t % 127) + 32 : $t); } $s = $r; } echo $s; } ``` Ungolfed infinite: ``` function x($s) { // $s - string to process while (true) { for ($i = 0, $r = ''; $i < strlen($s); $i++) { $b = ord($s[$i - 1]) or $b = 32; $a = ord($s[$i + 1]) or $a = 32; $t = ($b ^ ord($s[$i])) | $a; $r .= chr($t > 126 ? ($t % 127) + 32 : $t); } echo $s = $r; } } ``` [Answer] # Perl, 47 bytes Includes +2 for `-lp` Run with the input on STDIN, e.g. `perl -lp xoror.pl <<< "Hello, World!" | head -26` `xoror.pl`: ``` /./s;$_=$_.chop^" $_"|"$' ";y/\x7f/ /;print;redo ``` This works as is, but replace the `\x7f` by the corresponding binary value to get the given score [Answer] # C++ ## Nth-Sequence (212) ``` void x(char*s,int l,int n){for (;n-->0;) {char*t=new char[l-1](),w;for(int i=0;i<l-1;i++)t[i]=((w=(((i-1>= 0)?s[i-1]:32)^s[i])|((i+1<l-1)?s[i+1]:32))>126)?((w%127)+32):w;for(int i=0;i<l-1;i++)s[i]=t[i];delete[]t;}} ``` Un-Golfed ``` void x(char*s, int l, int n){ for (;n-- > 0;) { char*t=new char[l-1](),w; for(int i = 0;i < l-1; i++) t[i] = ((w = (((i-1>= 0) ? s[i-1] : 32)^s[i]) | ((i+1 < l-1) ? s[i+1] : 32)) > 126) ? ((w % 127) + 32) : w; for(int i = 0; i < l-1; i++) s[i] = t[i]; delete[]t; } } ``` Nth-Sequence using pointer syntax instead of array syntax to make this all the more confusing: (231) ``` void x(char*s,int l,int n){for(int x=0;x++<n;) {char*t=new char[l-1](),w;for(int i=0;i<l-1; i++)*(t+i)=((w=(((i-1>= 0)?*(s+i-1):32)^*(s+i))|((i+1<l-1)?*(s+i+1):32))>126)?((w%127)+32):w;for(int i=0;i<l-1;i++)*(s+i)=*(t+i);delete[]t;}} ``` Un-Golfed ``` void x(char* s, int l, int n){ for (;n-- > 0;) { char*t = new char[l-1](),w; for(int i = 0; i < l-1; i++) *(t+i) = ((w = (((i-1>= 0) ? *(s+i-1) : 32)^ *(s+i)) | ((i+1<l-1) ? *(s+i+1) : 32)) > 126) ? ((w%127)+32) : w; for(int i = 0;i < l-1; i++) s[i] = t[i]; delete[]t; } } ``` Debug Function (For Fun) ``` void d(char* seed, int len, int nth) { for (int n = 0; n++ < nth;) { char* tout = new char[len - 1](); for (int i = 0; i < len - 1; i++) { char x, y, z; x = ((--i >= 0) ? seed[i] : 32); y = seed[++i]; z = ((++i < len - 1) ? seed[i] : 32); char w = (x ^ y) | z; tout[--i] = (w > 126) ? ((w % 127) + 32) : w; cout << "[" << x << " " << y << " " << z << "] " << w << endl; } for (int i = 0; i < len - 1; i++) seed[i] = tout[i]; delete[] tout; cout << endl; } } ``` [Answer] **JAVA** *240/280 Bytes* The popular Java version at the time I wrote this claimed to be 185 bytes, but there are two significant fudge points. First, the measurement is presumably only for the function, not for the complete working source. Maybe not such a problem. Second, it uses BiFunction without either an import or a fully qualified name. Adding the required bits to run it as-is (then minimizing it, fairly) brought it to 348 bytes. Adding only the fully qualified name of the BiFunction class brings it to 248 bytes. In contrast, I believe mine is 240 bytes when playing by the same rules (no class, no actual output, just the meat). The full runnable class is 280 bytes, and looks like this (unminified): ``` class z{ public static void main(String[] s){ int L=s[0].length(); for(int G=Integer.valueOf(s[1]);G-->0;){ s[1]=""; for(int N=0;N<L;N++){ char C=(char)((N>0?s[0].charAt(N-1):' ')^(s[0].charAt(N))|(N<L-1?s[0].charAt(N+1):' ')); s[1]+=C>126?' ':C; } System.out.println(s[1]); s[0] =s[1]; } } } ``` Or, minified: ``` void m(String[] s){int L=s[0].length();for(int G=Integer.valueOf(s[1]);G-->0;){s[1]="";for(int N=0;N<L;N++){char C=(char)((N>0?s[0].charAt(N-1):' ')^(s[0].charAt(N))|(N<L-1?s[0].charAt(N+1):' '));s[1]+=C>126?' ':C;}s[0]=s[1];}return s[0];} ``` [Answer] ## Swift: 273 Characters Wow, Swift is worse than Java! (All those APIs with long names! :P) ``` func c(s:String,n:Int=0-1){var a=[UInt8](s.utf8);for i in 0...(n>=0 ?n:Int.max-1){var z="";for i in 0..<a.count{let A=i-1<0 ?32:a[i-1],B=a[i],C=i+1<a.count ?a[i+1]:32;var r=A^B|C;r=r<32 ?32:r>126 ?32:r;z+=String(UnicodeScalar(r))};if n<0||i==n{print(z)};a=[UInt8](z.utf8)}} ``` Ungolfed: ``` func cellularAutoma(s: String,n: Int = -1) { var array = [UInt8](s.utf8) for i in 0...(n >= 0 ? n : Int.max - 1) { var iteration = "" for i in 0..<array.count { let A = i - 1 < 0 ? 32 : array[i - 1], B = array[i], C = i + 1 < array.count ? array[i + 1] : 32 var r = A ^ B | C r = r < 32 ? 32 : r > 126 ? 32 : r iteration += String(UnicodeScalar(r)) } if n < 0 || i == n { print(iteration) } array=[UInt8](iteration.utf8) } } ``` Thanks to [@CAD97](https://codegolf.stackexchange.com/a/74801/53008) for mentioning that (A^B)|C can only be greater than 126 when it's 127. I also realized that you don't need parenthesis around A^B|C because XORing is done before ORing, so that saved me a few bytes. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 23 bytes ``` (ðpǏ3lƛC÷∇꘍⋎:₇⇩>[32];C∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%28%C3%B0p%C7%8F3l%C6%9BC%C3%B7%E2%88%87%EA%98%8D%E2%8B%8E%3A%E2%82%87%E2%87%A9%3E%5B32%5D%3BC%E2%88%91&inputs=1%0AHello%2C%20world!&header=&footer=) ``` ( # N times.. ðpǏ # Enclose in spaces 3l # Get overlapping substrings of length 3 ƛ ; # Map... C÷ # Iterate out charcodes ∇꘍⋎ # XOROR :₇⇩>[ ] # If greater than 126 32 # Push 32 C∑ # Stringify and concatenate ``` ]
[Question] [ Given a *strictly* positive integer `n` (therefore `0` isn't a valid test case), produce an approximate triangle of height `n`. ## A non-programmatic process of drawing the picture Initially we start with the base of the triangle. ``` | ``` So, we want to draw a triangle of a height of 5. First we know that all the `|`'s align on a straight line, and there is a missing `|` on every even position. ``` | | | ``` Then, we insert the `/`'s onto these empty lines, where every `/` has 1 more preceding space than the next `/`. The lowest `/` starts at 1 space. ``` | / | / | ``` ## More reference outputs + Sample program Here's what the program should output for inputs `1` to `9`. A [sample program](https://tio.run/##ZY/BCsIwDIbP21OEgqx1utl5K@wtBA9zh8E6jYysdPUg@O610ZOYW/7/y5/EPcNtoWOMo53g7Ad38jjQdbaSlMmzGdcALXR9nk2LBwQk8Mm3Uu@o1IxkOAFuGmhb0Nx@ZqrBOUujFC@hkmbn1f57ILZIQWLdqFLUDHobHp6guFBR3RckyXxnzF73Kv4doA@833kOEW0qEOUavMQUZ4AFzvz6P6@hUvEN) is available if you still don't understand the specification. For those that don't see that it's a triangle: Take a look at [this](https://tio.run/##ZY7BCoJAFEXX@hWPgXAmSx3bCf5F0MJcCD7rhTyH57QI@vfJaRct7z3nwnUvf1/4FMKIE1xkcGehgW8zajZNmsy0emih69NkWgQIiEE2jtoeOLdRSWgC2tXQtmBj/G6KwTnkUau3MluH84r/DNSe2Gsqa5OrMoqC/ikM2ZWz4rEQ6@h3TXO0vQlOov3zsa4qY8IH). Scroll the picture really quickly. You will see the two sides of a triangle. ``` ==== 1: ==== | ==== 2: ==== / | ==== 3: ==== | / | ==== 4: ==== / | / | ==== 5: ==== | / | / | ==== 6: ==== / | / | / | ==== 7: ==== | / | / | / | ==== 8: ==== / | / | / | / | ==== 9: ==== | / | / | / | / | ``` ## Specification * Leading/Trailing whitespace is allowed. * The string *has* to be joined with newlines, outputting a string list is not allowed. [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` ↔↑ṁe"|"¡Θ" / ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///ihpTihpHhuYFlInwiwqHOmCIgL////zkw "Husk – Try It Online") Builds the infinite triangle upside-down, then takes the required number of lines and reverses them before printing. ### Explanation ``` ↔↑ṁe"|"¡Θ" / ¡ Repeat and accumulate results: Θ prepend a space " / starting from the string " /" (this will create all the lines of the slanted side) ṁ For each line: e"|" put it in a list with a "|" line ṁ and merge all these lists together ↑ Take the number of lines required by the input ↔ Reverse the result ``` [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` def f(n):print n%2*'|'or n/2%n*' '+'/';f(n-1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TqqAoM69EIU/VSEu9Rj2/SCFP30g1T0tdQV1bXV/dGqhE11Dzf5pGZl5BaYmGpuZ/cwA "Python 2 – Try It Online") A function that prints, terminating with error. The `%n` in `n/2%n` is just to give an error when `n` falls to 0, but is harmless otherwise. --- As a program **50 bytes** ``` n=input() while n:print n%2*'|'or n/2*' '+'/';n-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERDk6s8IzMnVSHPqqAoM69EIU/VSEu9Rj2/SCFPH8hSUNdW11e3ztO1Nfz/3wwA "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` unlines.reverse.(`take`f" /") f c="|":c:f(' ':c) ``` [Try it online!](https://tio.run/##BcG9CoAgEADgvac4JLCGamsQfIrWhuQ4TTIRf5p69q7vO025KAR2eucWg49U5kwP5ULzcFRz0WEFLGLsLKAWr1Co7CBBKhz5Nj6ChtTqVjP04GDlD20wrvCEKf0 "Haskell – Try It Online") `f" /"` generates an infinite (reversed) approximate triangle, the first line is mostly formatting. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ ~~14~~ ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` L'/ú€'|I£R» ``` -3 bytes thanks to *@Grimmy*. -1 byte after getting inspiration from *@MagicOctopusUrn*. [Try it online](https://tio.run/##yy9OTMpM/f/fJ@jcVmt1/cO71GseNcyqPLxC5/9/8/@6unn5ujmJVZUA) or [verify all test cases](https://tio.run/##yy9OTMpM/R/iquSZV1BaYqWgZO9ny6XkX1oC4en891HXP7zrUdMa9Rq/Q4uDDu3@r3Nom/1/AA). **Explanation:** ``` L # Push a list in the range [1, (implicit) input] # i.e. 5 → [1,2,3,4,5] '/ú '# Pad "/" with that many leading spaces # → [" /"," /"," /"," /"," /"] €'| '# Put a "|" in front of each item # → ["|"," /","|"," /","|"," /","|"," /","|"," /"] I£ # Only leave the first input amount of items # → ["|"," /","|"," /","|"] R # Reverse it # → ["|"," /","|"," /","|"] » # And join it by newlines # → "|\n /\n|\n /\n|" # (after which the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~52~~ 51 bytes ``` f(n){for(;n--;)printf(n&1?"%*c\n":"|\n",n/2+2,47);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOi2/SMM6T1fXWrOgKDOvBCimZmivpKqVHJOnZKVUAyR18vSNtI10TMw1rWv/5yZm5mloVnOBtAGVK2TaGlpn2lhYa2tnAkUVoGYo2QKBagqIBBmQqWnNpZCmAaZquWr/mwMA "C (gcc) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 20 bytesSBCS ``` ⊖(0⌊-\∘⍳)⌽⊢↑⍤0⍴∘'|/' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x91TdMweNTTpRvzqGPGo97Nmo969j7qWvSobeKj3iUGj3q3AIXVa/TV/6cBlT/q7YPo7Go@tN4YpKZvanCQM5AM8fAM/p@mYMilq6vLlaZgAqXNAQ "APL (Dyalog Unicode) – Try It Online") **Edit**: Use `↑⍤0` instead of `↑¨` to avoid an extraneous use of `↑`. An anonymous tacit function. This is an improvement over [Graham's APL+WIN solution](https://codegolf.stackexchange.com/a/200573/78410) using modern APL. I was about to post a 24-byter when `-\⍳n` randomly struck my brain. It is an expression that yields first `n` terms of `0 -1 1 -2 2 -3 3 ...`, so applying `0⌊` yields `0 -1 0 -2 0 -3 0 ...` which is perfect for row-wise rotation vector. ### How it works ``` ⊖(0⌊-\∘⍳)⌽⊢↑⍤0⍴∘'|/' ⍝ Input: n ⍴∘'|/' ⍝ Repeat '|/' to length n ⊢↑⍤0 ⍝ Create a n-by-n matrix whose 1st column is the above ⍝ and the rest is blank ⌽ ⍝ Rotate left each row: ( -\∘⍳) ⍝ First n values of 0 -1 1 -2 2 -3 3 ... 0⌊ ⍝ Minimum with 0; 0 -1 0 -2 0 -3 ... ⍝ (Negative rotate left is rotate right) ⊖ ⍝ Reverse vertically ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 168 bytes ``` ,[->>>+<[-<+>>-]>[<+>->]<<<<]>>>>>>>++>++[-<[-<++>]<[->++<]>>]<<++++++[-<+++++++>]<[-<+<+++>>]++++++++++<+++++<--<[->.>>.<<<]<[[->+>>>>>.<<<<<<]>>>.>.<<.>>.<<<[-<+>]<-] ``` [Try it online](https://tio.run/##PY5RCoAwDEP/vUrsTlBykdIPFQQR/BA8/2w7MQxKeGm69V6Oa3@2s/fZhCTUREGK02IKXUPOISBeBDKDQLECJI0USkVKhRVpg@PX4CrZwka27FfLqrqR/jvZ0nyR@pareO/TCw "brainfuck – Try It Online"), with 10 as input. There is substantial room for improvement for sure. I should try different memory layouts for the constants, for example. My pointer walks around way too much. The commented code: ``` Divide input by two and get the mod as well Mem layout is input | quotient | remainder | ifelse flag | 0 ,[->>>+<[-<+>>-]>[<+>->]<<<<] Mem: ^0 | quotient | remainder | 0 | 0 Build 32 which is the SPACE character >>>>>>>++>++ Mem: 0 | quot | rem | 0 | 0 | 0 | 0 | 2 | ^2 [-<[-<++>]<[->++<]>>] Mem: 0 | quot | rem | 0 | 0 | 0 | 0 | 32 | ^0 Build 124 and 47 for the vertical bar and the slash << ++++++[-<+++++++>]<[-<+<+++>>]++++++++++<+++++<-- Mem: 0 | quot | rem | ^124 | 47 | 10 | 0 | 32 If there is a remainder print the loose vertical bar <[->.>>.<<<]< Mem: 0 | ^quot | 0 | 124 | 47 | 10 | 0 | 32 while there is something in the quotient [ print those many spaces [->+>>>>>.<<<<<<] print as many spaces as needed then a slash >>>. then a newline >. then a vertical bar <<. then a newline >>.<<< reset the space counter and decrement it [-<+>]<- ] (end while) ``` that you can [try at a different interpreter](https://copy.sh/brainfuck/?c=RGl2aWRlIGlucHV0IGJ5IHR3byBhbmQgZ2V0IHRoZSBtb2QgYXMgd2VsbApNZW0gbGF5b3V0IGlzCmlucHV0IHwgcXVvdGllbnQgfCByZW1haW5kZXIgfCBpZmVsc2UgZmxhZyB8IDAKLFstPj4-KzxbLTwrPj4tXT5bPCs-LT5dPDw8PF0KTWVtOiBeMCB8IHF1b3RpZW50IHwgcmVtYWluZGVyIHwgMCB8IDAKQnVpbGQgMzIgd2hpY2ggaXMgdGhlIFNQQUNFIGNoYXJhY3Rlcgo-Pj4-Pj4-Kys-KysKTWVtOiAwIHwgcXVvdCB8IHJlbSB8IDAgfCAwIHwgMCB8IDAgfCAyIHwgXjIKWy08Wy08Kys-XTxbLT4rKzxdPj5dCk1lbTogMCB8IHF1b3QgfCByZW0gfCAwIHwgMCB8IDAgfCAwIHwgMzIgfCBeMApCdWlsZCAxMjQgYW5kIDQ3IGZvciB0aGUgdmVydGljYWwgYmFyIGFuZCB0aGUgc2xhc2gKPDwKKysrKysrWy08KysrKysrKz5dPFstPCs8KysrPj5dKysrKysrKysrKzwrKysrKzwtLQpNZW06IDAgfCBxdW90IHwgcmVtIHwgXjEyNCB8IDQ3IHwgMTAgfCAwIHwgMzIKSWYgdGhlcmUgaXMgYSByZW1haW5kZXIgcHJpbnQgdGhlIGxvb3NlIHZlcnRpY2FsIGJhcgo8Wy0-LjxdPApNZW06IDAgfCBecXVvdCB8IDAgfCAxMjQgfCA0NyB8IDEwIHwgMCB8IDMyCndoaWxlIHRoZXJlIGlzIHNvbWV0aGluZyBpbiB0aGUgcXVvdGllbnQKWwogIHByaW50IHRob3NlIG1hbnkgc3BhY2VzClstPis-Pj4-Pi48PDw8PDxdIHByaW50IGFzIG1hbnkgc3BhY2VzIGFzIG5lZWRlZAogIHRoZW4gYSBzbGFzaAo-Pj4uCiAgdGhlbiBhIG5ld2xpbmUKPi4KICB0aGVuIGEgdmVydGljYWwgYmFyCjw8LgogIHRoZW4gYSBuZXdsaW5lCj4-Ljw8PApyZXNldCB0aGUgc3BhY2UgY291bnRlciBhbmQgZGVjcmVtZW50IGl0ClstPCs-XTwtCl0gKGVuZCB3aGlsZSk$) and to which you can pass different input numbers more easily. For example, try typing `\10` in the input bar. Then pass the commented code [over this Python script](https://tio.run/##jVNNi9swEL3rVww@2Sg22WShsKiC7cexUOjROKDYk1iLLLmSsyHQ/56O5KTJYQMdbOtr5s34zdN4mnpn1@fWdQifIcuy8zf9rmmh7XiYYHuC6ehA2Q72OMHUIwyuAxXgiMawHziAUSdHnjqwOeQP/D64SaONU4@D0rZDT3O9QxMQdkbtabVki7qUUnJRl4JLWTayprGUjSBrIvQLbJaP4ZYJ5MtBmw7WKzj2uu2pilTjr5@vX79D2yuv2gk9k7NxTs@MfAWeQa9wd@@K3s2KUXGxPk5lUbmci0bK5j8h1gljyYRgPFlCSpbgBI9LwuP/bD4XZfkgxeZp9UzD8yf6PN3ysFhcJRpxC9tc4uL8QRBRZjDy5TESF9yAU6/tnnqfWLwSz2oGMHptowActXBQ9gRhVC0GFllJ5FYiWXPxJIncucWlReywIyjCtqAgGBX62JrqtmfxaLRFdr/3jn7SrTKwVZ64/Mg7JWcew0WjKSm07mCp@0m9HbbEYFSRnlhSXCNK1kCOdJiIKM6kfsbcGOJFWFR1IyQvaSf9Tx4OQ06Z40WpEnAe5VXAzvkktEgaxbKiuEZkWfXmtM132lAVuVHDtlPQvrQX10UCK4ri/Bc) to remove the comments and get the byte count. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes ``` "$args"..1|%{((" "*($_/2)+"/"),"|")[$_%2]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0klsSi9WElPz7BGtVpDQ0lBSUtDJV7fSFNbSV9JU0epRkkzWiVe1Si29v///6YGAA "PowerShell – Try It Online") Loops from input `$args` down to `1`, each iteration choosing whether to output spaces and a `/`, or the `|` character based on a modulo-index into an array. Default output gives us newlines for free. Ho-hum. [Answer] # [J](http://jsoftware.com/), 24 bytes ``` >@}.&,i.;&'|'@{.&'/'@->: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7Rxq9dR0MvWs1dRr1B2q9dTU9dUddO2s/mtypSZn5CukKRiCGeq66jABI3QB0/8A "J – Try It Online") *-4 bytes thanks to Bubbler* [Answer] # APL+WIN, ~~36 33~~ 30 bytes 3 bytes saved by incorporating bubbler's row rotation method Prompts for integer: ``` ⊖(0⌊-\⍳n)⌽(n,n)↑((n←⎕),1)⍴'|/' ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6pqmYfCop0s35lHv5jzNRz17NfJ0gHTbRA2NPKAyoHJNHUPNR71b1Gv01f8D9fxP4zLnAgA "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~66~~ ~~56~~ 55 bytes Saved a byte thanks to [kaya3](https://codegolf.stackexchange.com/users/91685/kaya3)!!! ``` def f(n): if n:print((-~n//2*' '+'/','|')[n&1]);f(n-1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0/TikshM00hz6qgKDOvRENDty5PX99IS11BXVtdX11HvUZdMzpPzTBW0xqoWNdQ839afpFCpkJmnkJRYl56qoahjgXICIjuNHVbIKjOrAVR6ppcQAsyNf@bAwA "Python 3 – Try It Online") [Answer] # Java (OpenJDK 8), 88 84 bytes ``` x->{for(int i=x,j=i+2;i-->0;j--)System.out.printf((i%2<1?"|\n":"%"+j/2+"s\n"),"/");} ``` [Try it online!](https://tio.run/##XZBBbsIwEEX3nGJkCcmRcYAsa0zFAbpi2XYxDQmyG5woNsgVzdnTaRKqqH9jz/fXzBtbvKGsm8LZ02ffXD8qk0NeoffwgsbBfbEAknGhaEvMCziQBZNutTkBcnqEmKjB7sa8Dxio0QEQNPRR7u9l3Q5Bo@PKaiMyZaTcb5SVMjl@@VBc0voa0qalUMm5WWa77TP7fnPsiS2ZsOtMME9VsmJrlqiuV@OkCXkaOBBdCJwfA3U6v74DtmefzKAJBEZkQtsqOnYasg1dhJjnfvUfrHI8ggCm/8SmvR/CFHmced3jV7r@Bw "Java (OpenJDK 8) – Try It Online") If Java's output methods weren't so long, I'd get close to John's `R` submission! Edit: -4 bytes thanks to @Kevin Cruijssen! Also the link led to an older 91 bytes version, fixed that now... [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ``` H⁶ṁ;”/)”|ÐoṚY ``` [Try it online!](https://tio.run/##y0rNyan8/9/jUeO2hzsbrR81zNXXBBI1hyfkP9w5K/L////mAA "Jelly – Try It Online") A monadic link taking an integer and returning a list of Jelly strings. If a single newline-separates string is needed, append `Y` for a cost of a byte. Thanks to @JonathanAllan for saving a byte! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` Nθ↙⊘θUE⁰¦¹F⊘⊕θ«↑↑¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDyiW/PM8nNa1ER8EjMacsNQUoB5R0rShJzUvRMNBRMATy0vKLFDSg0p55yUWpual5JRClCtVcnL75ZakaVqEFQJWcUFNDCyA6a///N/2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ↙⊘θ ``` Print the diagonal line of the appropriate length. ``` UE⁰¦¹ ``` Space the rows out. ``` F⊘⊕θ«↑↑¹ ``` Fill in the vertical line on alternate lines. [Answer] # [Perl 5](https://www.perl.org/) `-n`, 36 bytes ``` say$_%2?$"x(1+$_/2).'/':'|'while$_-- ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIlXtXIXkWpQsNQWyVe30hTT11f3Uq9Rr08IzMnVSVeV/f/f8t/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` HĊ”|ẋż³HḞR¤” ẋ$;€”/¤ẎṚY ``` [Try it online!](https://tio.run/##y0rNyan8/9/jSNejhrk1D3d1H91zaLPHwx3zgg4tAYooAEVUrB81rQGy9Q8tebir7@HOWZH///83BwA "Jelly – Try It Online") It's been a while since I've golfed in Jelly, so this answer is probably embarrassingly long. [Answer] # [PHP](https://php.net/), ~~76~~ 57 bytes ``` for(;$a=$argn--;)echo$a%2?"| ":str_repeat(' ',$a/2)."/ "; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVEm1VEovS83R1rTVTkzPyVRJVjeyVariUrIpLiuKLUgtSE0s01BXUdVQS9Y009ZT0uZSs//83/5dfUJKZn1f8X9cNAA "PHP – Try It Online") I feel there should be much better but can't put my finger on it yet.. I also didn't find how to use recursive functions with PHP7 arrow notation.. well.. EDIT: Actually, a basic loop is still better for PHP than recursion [Answer] # [C (gcc)](https://gcc.gnu.org/), 50 bytes ``` f(n){for(;n;)printf(n--%2?"|\n":"%*s/\n",n/2,"");} ``` Takes as input an integer `n` and prints a triangle. It would look more realistic and save 2 bytes if `n` was not divided by 2. [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOi2/SMM6z1qzoCgzrwQooquramSvVBOTp2SlpKpVrA9k6OTpG@koKWla1/4HqlHITczM0yjLz0zR5KrmUgACkBEgiUwFWwVDayBlo2BoAKS1tTXB8mA1GpmaOgoFpSXFGiCTuGr/AwA "C (gcc) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~75~~ 61 bytes Thanks again, Giuseppe! Forgot that cat does pasting itself. ``` for(i in scan():1)cat(`if`(i%%2,'|',c(rep('',i/2),'/')),'\n') ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPoTg5MU9D08pQMzmxRCMhMy1BI1NV1UhHvUZdJ1mjKLVAQ11dJ1PfSFNHXV9dE0jG5Klr/jf9DwA "R – Try It Online") [Answer] # [4](http://esolangs.org/wiki/4), 171 bytes ``` 3.6006260132602476031061101612026401020000127908906554819090552999940099999079098993139912214131211599141161115815500503615009816317991281750111717119502503616009199991194 ``` [Try it online!](https://tio.run/##HU6LDUQxCNroAvip7D9Yzz5MRIUQ8974NdBqMLYpTyOIJsGmoE4QwoI6xhhdlUPDqJIXCTwyVvfYwbApMRkUWbslN27HYRVQiOayhx08zz08hXWcLbqgz7O/mS97b3mv8Ac) ### Explanations ``` 3. start of code 60062 assign half ASCII of pipe 60132 space 60247 slash 60310 endl 61101 int one 61202 int two 64010 int ten 2000012 multiply half-pipe by two for a pipe 790 get input 890 while there's still input 65548 char zero 1909055 decrease input char by char zero to get result 2999940 multiply previous result by ten (to make way for current char input) 0999990 put current result 790 get input again 9 end of loop ======== At this point we already got the int n 899 while (n != 0) 3139912 2141312 1159914 mod by 2 (n-[[n/2]]*2) 1161115 check odd or even 815 if odd 500 503 61500 9 print pipe and endl 816 if even 3179912 get n/2 817 501 1171711 9 print spaces 502 503 61600 9 print slash and endl 1999911 9 get n-1, end of loop 4 end of code ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Çg['|'/iSp°Zz]Ãw ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=x2dbJ3wnL2lTcLBael3Ddw&input=OQ) [Answer] # [MATL](https://github.com/lmendo/MATL), 22 bytes ``` :2&\w~*"@:~'|/'X@)hXhP ``` [Try it online!](https://tio.run/##y00syfn/38pILaa8TkvJwapOvUZfPcJBMyMiI@D/f0sA "MATL – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` i=input() while i:print(' '*(i/2)+'/','|')[i%2];i-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERDk6s8IzMnVSHTqqAoM69EQ11BXUsjU99IU1tdX11HvUZdMzpT1SjWOlPX1vD/f0MDAwA "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 48 bytes ``` f=n=>n?(n&1?`| `:' '.repeat(n/2)+`/ `)+f(n-1):'' ``` [Try it online!](https://tio.run/##ZchBCoAgEADAu6/olLtEihEEgfUVxTQKWaOkU3@3czTH2e1tL3duR24pLb6UoElPNAPVajYPMyOvuDj94W0Gkh02RjKDTQBqFY6cF5foStGLmFYIoBDZd/rfDIjlBQ "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes ``` ->n{(1..n).map{[?|," "*(n/2)+?/][(n-=1)%2]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNQTy9PUy83saA62r5GR0lBSUsjT99IU9tePzZaI0/X1lBT1Si2tvZ/QWlJsUJatHnsfwA "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 47 bytes ``` f=(n,s=`/ `,v=`| `)=>--n?f(n,v,s<v?' '+s:s)+v:v ``` [Try it online!](https://tio.run/##JcgxDsIwDEDRvadgcywnQNemphdhSFUaZFQlqEaeuHsA8aen/5ht1mWX5yuUeltby@yKV06nLnnj9O4S8iWEMuXvN6@jTXAA0kGRbLCW6@6E@ygj9@coRLjUonVbj1u9O@BfQEJ/XQtQdoIY2wc "JavaScript (Node.js) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 68 bytes ``` f(){ for((i=$1;i-->0;)){((i%2))&&printf %$[2+i/2]s\\n /||echo \|;};} ``` [Try it online!](https://tio.run/##S0oszvj/P01Ds1ohLb9IQyPTVsXQOlNX187AWlOzGshXNdLUVFMrKMrMK0lTUFWJNtLO1DeKLY6JyVPQr6lJTc7IV4ipsa61rv2fpmDIBebr6upypSmY/gcA "Bash – Try It Online") Don't golf in bash that often, so tips appreciated. [Answer] # [Go](https://golang.org/), 94 bytes ``` import."fmt" func f(n int){for n!=0{if n%2==0{Printf("%*s/\n",n/2,"")}else{Println("|")} n--}} ``` Port of my C answer. [Try it online!](https://tio.run/##PY1NDoIwFIT3PcXzJSStgPws1d7BA7ghhJJG@kpKXWHPXgsYVzOZL/lmtHHu@lc3DmA6TVGb2Tp/QWU8MvWmHhQn0OTFqqwDOsl61Qooa2VqD5eI4pidl@pJWFDVFogiDNMyHHAijp@0MCrLEOJu3I64gJUBwCbVcJXQ3FLeoalT5vkBN861@NW/D/clsBC/ "Go – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 15 bytes ``` ɾ\/꘍\|?ẋf$Y?wiṘ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C9%BE%5C%2F%EA%98%8D%5C%7C%3F%E1%BA%8Bf%24Y%3Fwi%E1%B9%98&inputs=4&header=&footer=) An attempted port of the 05AB1E answer, but not really... ]
[Question] [ # Context Just look around! Whenever someone posts an answer, the same template is followed over and over again! A first line with the byte count and language name. Then the code. Then the TIO link. This is the basic skeleton almost everyone follows. # Task Your task, should you choose to accept it, is to write a program/function/procedure/etc that takes as input the variable bits and produces the basic CGCC answer. # Input The language name, some code and a TIO link, in any sensible formats. For the language name and the TIO link, a string is suggested. For the code, sensible formats include a string with possibly some newlines, or a list of strings, one string per line. Additionally, you may also take the byte count as input. If you don't, you have to compute it yourself (if you compute it yourself, you can assume the byte count equals the length of the code string). You have to support that the input strings may contain any printable, non-whitespace ASCII characters plus the space. The only exclusion being the newlines in the source code. You don't have to worry about the weird characters used by golfing languages in their code pages. The inputs may be ordered in any way you like. # Output You should output this raw content: ``` # {name}, {byte count} bytes {code} You can [try it online][tio]! [tio]: {link} ``` Where `{name}`, `{byte count}`, `{code}` and `{link}` should be filled in by your code. Three of those are inputs, the byte count should be computed within your code if you chose not to receive it as input (you can assume the byte count is equal to the number of characters in the `code` argument). Beware that the code given may be multiline, in which case the `{code}` section must be indented by 4 spaces for each line of code. # Test cases You can [check some test cases](https://tio.run/##lVJNb9swDL3rV9AKsNmr49TtTsEMBAiwj8OAHXYpXKNVHDkWKsuGRHcNgvz2jLKWDDusQH0waZl8fO@Jwx7b3tyeTii7QQuUUADnfAYHLczumFKUZoftETZ7lI4xoOdQ91t5ZOyuH6EWBkq0e1AIvdHKyKpE1VcRY1NcwmG0@kiYjG1lA03sgVPwEClQ/VOynECp4rPS2oEygK0EYdwvaeHCq@ktrL@s11C3QntS0mWBzqPHeoRO7GFDfdCNGpVnAg6tMrvsjB/KgyDSSUnsW5Pp2Gd06ENmJc2sZczvDU@B3hNAEvqtxNGaC7GMiHUCJ1lF0BYmFCEEqUXQS1YUk@aTr/Re/5guAG45@0OAa9FttgJelvBylXNGLf60RRzccrEgTzM7msVsCDfH2UAaMf7XV2pKiG74xef8w8dr@jzP/Crck9T6MvKekTlxlCeU5yw2kfKZgSuIzTyP1DxPvHv/Y9Ke4d7O5Lugqyb3VC3@GtCU@qGi5KfqpFut4m9Nue5Hg6VOZ9Wnm3SW5tW7xUonF0rYKtobZ94jyGdpaAeehVbbab2iV3idfgM). [Related challenge](https://codegolf.stackexchange.com/q/127291/75323) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. If you liked the challenge, consider upvoting it... And happy golfing! [Answer] # [Ruby](https://www.ruby-lang.org/), ~~98~~ ~~95~~ 94 bytes Really simple string interpolation. I don't think there's all that much to optimize here that will save a lot of bytes. Takes the byte count as a parameter in order to save 3 bytes, as per Kevin Cruijssen's suggestion. ``` ->n,b,c,l{"# #{n}, #{b} bytes #{c.gsub /^/,' '*4} You can [try it online][tio]! [tio]: "+l} ``` [Try it online!](https://tio.run/##tU9BboMwELzvK7YhUqTUtS@5FIX2DemljUgqYeMAEtgIr2sRxNsJRL3kAbnMjmZmR7udl/10SU7T24dhkilWD6sIo8GMbEY5ouxJO4BoULxwXqL4FWyDm@1uBDhajyozmFLXY0VoTV0ZfU6psucXgPuMcfVaj5PJGo0JFpocV6VtWpjNR0HZfIms97zTWQ6tJ4eXdFlkuHjcVdd/ynCpnr7m46Ekal0sRAiB99aTl5or24iQkSo//5L8EHbh/bv4UQd47pM3 "Ruby – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~56~~ ~~53~~ ~~52~~ ~~51~~ 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` “# ÿ, ÿ¡Ï“I4ú»"[tio]"D“You€© [try€•€Ø]ÿ!“s¶·ý„: IJ ``` Inputs in the order `name`, `byte-count`, `[code-lines]`, `link`, where the `[code-lines]` is a list of lines. [Try it online.](https://tio.run/##MzBNTDJM/f//UcMcZYXD@3WA@NDCw/1ArqfJ4V2HditFl2Tmxyq5AAUi80sfNa05tFIhuqSoEsh61LAISB6eEXt4vyJQuvjQtkPbD@991DDPSsHT6///gKL89KLEXAW/xNxUBY/UolQuQwMDrmil5PyUVCUdpfT81GIglQGUUIrlyigpKSi20tcHWqZXVJqnrwwA) **50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative (credit to *@Grimmy*):** ``` “:# ÿ, ÿ¡Ï“I4ú»“You€© [try€•€Ø][tio]!“Â6£R¨¶·ýÀ$ú« ``` [Try it online.](https://tio.run/##MzBNTDJM/f//UcMcK2WFw/t1gPjQwsP9QL6nyeFdh3YDGZH5pY@a1hxaqRBdUlQJZD1qWAQkD8@IjS7JzI9VBKo43GR2aHHQoRWHth3afnjv4QYVoM7V//8HFOWnFyXmKvgl5qYqeKQWpXIZGhhwRSsl56ekKukopeenFgOpDKCEUixXRklJQbGVvj7QTL2i0jx9ZQA) **Explanation:** ``` “# ÿ, ÿ¡Ï“ # Push dictionary string "# ÿ, ÿ bytes", where the `ÿ` are automatically # filled with the first two implicit inputs (name & byte-count) I # Push the third input-list of code-lines 4ú # Prepend 4 spaces before each line of code » # And join it by newlines "[tio]" # Push string "[tio]" D # Duplicate it “You€© [try€•€Ø]ÿ!“ # Push dictionary string "You can [try it online]ÿ!", where the `ÿ` is # automatically filled with the "[tio]" s # Swap to get "[tio]" at the top of the stack again ¶ # Push a newline character · # Double it, which in the legacy version built in Python works with strings ý # And join the stack by this double newline as delimiter „: # Push string ": " I # Push the fourth input (link) J # Join the entire stack together without delimiter # (after which the result is output implicitly) “:# ÿ, ÿ¡Ï“ # Push dictionary string ":# ÿ, ÿ bytes", where the `ÿ` are automatically # filled with the first two implicit inputs (name & byte-count) I4ú» # Same as above “You€© [try€•€Ø][tio]!“ # Push dictionary string "You can [try it online][tio]!"  # Bifurcate it; short for Dulpicate & Reverse Copy 6£ # Only leave the first 6 characters (the "![oit]") R # Reverse it to "[tio]!" ¨ # Remove the last character: "[tio]" ¶·ý # Same as above À # Rotate once towards the left, so the leading ":" becomes trailing $ # Push the fourth input (link) and a 1 ú # Prepend this link-string with that 1 space « # And append it to the earlier created string # (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 `"# ÿ, ÿ bytes"` and `“You€© [try€•€Ø]ÿ!“` is `"You can [try it online]ÿ!"`. [Answer] # [Red](http://www.red-lang.org), ~~102~~ 94 bytes -6 bytes thanks to Kevin Cruijssen! ``` func[l n c u][reduce["#"rejoin[l","]n{bytes }c{ You can [try it online][tio]! [tio]:}u]] ``` [Try it online!](https://tio.run/##jY29TgMxEIR7P8WwERU/p@Q6PwWiQ9YWjm@PGJn1ybFRTlGe/TgS0VEwzTTzzVdkWF5lcGxGu4xNg0tQBDR2RYYWxNGGinzkqC7RI7Ge93OVozEALuFszFtuCF7hapkRK7KmqMKuxsx3xlzbXhrzMpWoFSNoFRJ2O9BocXOy819S/LsgMQj3dKh1OtquW@nn0rTb/DDm9kBP/84vskpf5nrIip6w7UHJf@4Hj5PF6WH7p3C67ntavgE "Red – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~125~~ ~~121~~ ~~119~~ 113 bytes -4 bytes thanks to kronicmage -2 bytes thanks to xnor ``` (l!b)c t="# "++l++", "++show b++" bytes\n"++(("\n "++)=<<c)++"\n\nYou can [try it online][tio]!\n\n[tio]: "++t ``` [Try it online!](https://tio.run/##LY7BDoIwEER/Zbp6aFMViTcCd@@eDHAAQkJjXQgsMX49tuqe3uzOTHZolkfv/bZpr1rTQQragaz11tIhwjKML7RBoX1Lv1QcdlpTxQgT2BR53plwr7ji@7iiaxilzG84wcjecV@X4sZaRcOXspiT7dk4RoFplZvM2EPT9fcMQeFyNihJq9QES0oH0qxcZIaF5mOq3DE1VIMGkWnJkiQ0n@aVk93wb9k@ "Haskell – Try It Online") [Answer] # [PHP](https://php.net/), ~~134~~ ~~132~~ ~~125~~ 119 bytes ``` # <?=($a=$argv)[1].", $a[2] bytes ".preg_replace("/^/m"," ",$a[3])." You can [try it online][tio]! [tio]: $a[4]"; ``` [Try it online!](https://tio.run/##xY4xDoIwAEX3nqJWBklIG9BFlJAwObI4mKaaghWIQJvS0nD6il7Cv7zl5eWrVnm/hec82wU8C7hu5pDGDKMIBpwmDFaLERMACCstmocWque12CFyJwOKEFyHotXcsxAjAG7SwpqPkBq9wM5AOfbdKBg1nWQbAH5Mv@UDQyfvfXkpfRwf//agNUZNKSHOObxIa2wlcC0H4rip23zOnqNN5uL1Luz1Aw "PHP – Try It Online") Finally an easy job for PHP! EDIT: easily saved 2 bytes with concatenation in first `<?=` EDIT 2: saved another 7 bytes, just remembered that multi-lines strings work in PHP with `"` EDIT 3: and another 6 with using `/^/m` instead of `/\n/` [Answer] # JavaScript (ES6), 102 bytes ``` (n,b,c,l)=>`# ${n}, ${b} bytes ${c.replace(/^/gm, ' ')} You can [try it online][tio]! [tio]: `+l ``` [Try it online!](https://tio.run/##HYzLCoMwFET3@YpbFaqYGsRNEew3dFvEYkzjo8Qb0SiK@O3WOoszcGDmyyc@iL7pzG267yUmu4u0oIIqL3nkNjgrbvRgsUGxGDkQ4qwi6GWnuJAue7OqpXCFI1dvI@SlRxAcITX9Ao0BjapBmaWm0dmFkLNjyH21C42DVjJQunJLdK3nYmqNEFkUrPCk4m3x4TDHMPvhX9TGdEPM2HES9CMyuzs3keV5@w8) "/^/gm" is a Global Multi-line replace of start line (^) [Answer] # [Python 3](https://docs.python.org/3/), ~~97~~ \$\cdots\$ ~~118~~ 116 bytes Added 28 bytes to fix a bug kindly pointed out by [RGS](https://codegolf.stackexchange.com/users/75323/rgs). Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` lambda n,b,c,l,x='\n':f"""# {n}, {b} bytes {c.replace(x,x+' '*4)} You can [try it online][tio]! [tio]: {l}""" ``` [Try it online!](https://tio.run/##pZHBa4MwFMbv@SueEWZs0znXnmSFwi7bYbDDLsPKiDbO0PQpGotF/Nu72LXdaTBYLu/L4@X7fkmqgylKnB/z5fqoxS7dCECe8oxr3i29NXpRTil1oceBQ58OkB6MbAgBu/rstpaVFplkHe@mHniThT8Q8l62kAmE2NQHUAZK1AplEhtVJg4hpxpBrwfrbEPxE5ZAX08gMKckKzdy7Jxxugi6aUhJW@uxWxhTNVEQWJPbusXArb5vQElVKzQsZ6MjBy2RjU4@h7FwsOd9n5yn6IxOFnd2e4l/Es1Wan1NXxMLx5zQtzokDB01KoQpMJyFjpqFvh34Faq42P0L6kWYQu6EUZn4eZY81h@JFW9qJ5vVij3n8WPZook1d5OHe@7yMLkJVtq/0plCNaAa9AzIvUQQsBdabcD@ytb5G@LxCw "Python 3 – Try It Online") Takes code length as a parameter to save 3 bytes. [Answer] # [Kotlin](https://kotlinlang.org), ~~83 109 101~~ 95 bytes ``` {n,b,c,l->"""# $n, $b bytes ${c.prependIndent()} You can [try it online][tio]! [tio]: $l"""} ``` [Try it online!](https://tio.run/##VZBRT8IwFIWf7a@4FB62pLAlGIMkEI2IDiEaBzGG8DC6CgvldhkdMAm/fXYbJtqX23Pbc@7XbpSWEeb7QIJOMk@/opGiC5avkwhXDDzUDH5FVW1o9i9b6OUnZEvGmWz2KaV1aCCDxhKWmRY7Qhon3ooTEQsMPQwFass@E/KpUuABwtyMhEiDKocu5jpSixohZe1CQ5rAc/6VImyDCC0bTuSqAMVgK6AH9KVkp1WTq7BsUvrPAGbFhlRb9FlIqeCgEhnWqE3O5mpllQJXem3MRUarUpeTCDdF6FrreNd1HAPWSlJ06vWsc73POE7unI6TTN/fvCk/TtzbwezmKfAPj96DUlnHVa4cHH3eHmdDPv6O2iN/OJq56UfiOAd@Twm5qtj@fL1VvI5dmFiJxEoO2yDnPw "Kotlin – Try It Online") -6 bytes thanks to @snail\_ -2 bytes thanks to @ovs -6 bytes since `prependIndent` has a default of 4 spaces [Answer] # [Japt](https://github.com/ETHproductions/japt), 60 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` i`# {V}, {W} ßs {XmiSp4 R} YŒ ¯n [try Š Ò‚][o]! [o]: ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=aWAjIHtWfSwge1d9IN8acwoKe1htaVNwNCBSfQoKWYwgr24gW3RyeSCKII3Sgl1bk29dIQoKW5NvXTog&input=Imh0dHBzOi8vdGlvLnJ1bi8jcHl0aG9uMyIKIlB5dGhvbiAzIgoyMwoibGFtYmRhIHg6IHgrMQpwYXNzCnBhc3Mi) [Answer] ## [W](https://github.com/A-ee/w) `j`, 77 bytes ``` # "a", "ck" bytes "c' ," ":@\+" You can [try it online][tio]! [tio]: "b ``` ## Explanation ``` % Header section # " % The beginning header a % The first input (the language name) ", " % The comma & space ck % The length of the program (taken at the 3rd input) " bytes % Appended with " bytes" " % And a trailing newline % Code section c % The third input ' , % Splitted by a newline " " % Add string representing a newline and 4 spaces : % Stack: '\n'split(c), " ", " " @ % Stack: " ",'\n'split(c), " " \ % Join with 4 spaces + % Prepend 4 spaces % Link section " You can [try it online][tio]! [tio]: " % The template b % The second input ``` ``` [Answer] # Java 10, 141 bytes ``` (n,b,c,l)->{var t="";for(var p:c)t+=" "+p+"\n";return t.format("# %s, %d bytes\n\n%s\nYou can [try it online][tio]!\n\n[tio]: "+l,n,b,t);} ``` Takes the byte-count as integer-input, and the code as an array of String-lines. [Try it online.](https://tio.run/##PVBBbsIwELz3FVMjpESYQK9E9NxLUaWeKuDgOAZMk3Vkb6gQytupXaVcdmc1s@vxnNVFzc/19103KgS8K0u3J8ASG39Q2mCTRuCTvaUjdDYCkkmDSo7Mdg/9j9HkZVwanmIJrNhqbEBY3zOSldSyyeevt4vy4LUQ5cH5LA3dSuc8W4v0mph1M7EjUXrDvSdwEVWt4kxMMA0S0xrVlU3Y0Y6msX65HloRtuyvsAxHjSWz37J1@@ck@kOreLeRyQPn5XAvk7@ur5rob7R5cbZGGzPIHr9S@RjANbBpC9dz0UWKG8qo0Jn48O7oVYuNag3ejDdC4mW5lCDz88jmJrSrIyOOzoTYTkk3SIgTcxdWi0W0V/ieFhORj9kN918) **Explanation:** ``` (n,b,c,l)->{ // Method with four parameters and String return-type var t=""; // Temp-String, starting empty for(var p:c) // Loop over the code-lines: t+=" " // Append four spaces, +p // the code-line itself, +"\n"; // and a newline to this temp-String return t.format("# %s, %d bytes\n\n%s\nYou can [try it online][tio]!\n\n[tio]: " // Return this String above, where: +l, // The link is appended at the end n, // The first `%s` is replaced with the name `n` b, // The `%d` is replaced with the byte-count `b` t);} // And the second `%s` is replaced with the temp-String ``` [Answer] # [Wren](https://github.com/munificent/wren), 117 bytes Just a normal string interpolation here. ``` Fn.new{|a,b,c,d|"# %(a), %(b) bytes %(" "+c.split(" ").join(" ")) You can [try it online][tio]! [tio]: "+d} ``` [Try it online!](https://tio.run/##JVDbbqpAAHzfr9iuaQI5BAyXok2atNWCUHtBUcCmD1xWWcCFwipie77dQ3rmYWaSSSaTaWtML8ewhoQyXFfwDl4MKlLcfv@EQiTEQvKDBvCaC3mh54iHUcdwA8A1h2AP9CcWm6ogjEMA8WJWEtq734TnAQjKA4xDCj9Y3UHCYEkLQvHnByPl5xUAv3rblyR/L8uuYXgvtjVhmPs/RozDouCQ109EgqoIKIxikOAt2KUECShlrGpuJakvEesDlQYDe6U/ThqrNeYHqVZ292a0CDAzXfV1tR1NHrpkT/Svyg@zL/UmPb5HGy3XbMt4yMls8zIfr50Ud@5iiOOpapr43O43rtOWqVxma8@dGQtv9r4K9GDsvKysiZxmm9exVpzyx3i7t@bpUrHtduq/WfPMqQLtvCTdiUyT0ZOc@OHJc56aAxkVuh/fZ74su@c8LzpFp5ph4lgq/cnNUjaHxrMn79gaq8piaD/vjudp2z95@Qc "Wren – Try It Online") [Answer] ## [Japt](https://github.com/ETHproductions/japt), 85 bytes ``` "# {U}, {V} bytes {" "+Wq" " q" "} You can [try it online][tio]! [tio]: "+X ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=IiMge1V9LCB7Vn0gYnl0ZXMKCnsiICAgICIrV3EiCiIgcSIKICAgICJ9CgpZb3UgY2FuIFt0cnkgaXQgb25saW5lXVt0aW9dIQoKW3Rpb106ICIrWA==&input=IkphcHQiCjEwCiJhYmMKZGVmCmdoaSIKImh0dHBzOi8vZXRocHJvZHVjdGlvbnMuZ2l0aHViLmlvL2phcHQvP3Y9MS40LjYmY29kZT1JaU1nZTFWOUxDQjdWbjBnWW5sMFpYTUtDbnNpSUNBZ0lDSXJWM0VpQ2lJZ2NTSUtJQ0FnSUNKOUNncFpiM1VnWTJGdUlGdDBjbmtnYVhRZ2IyNXNhVzVsWFZ0MGFXOWRJUW9LVzNScGIxMDZJQ0lyV0E9PSZpbnB1dD1Ja3BoY0hRaUNqRXdDaUpoWW1NS1pHVm1DbWRvYVNJS0lpST0i) [Answer] # Jinja2, 102 bytes ``` # {{n}}, {{b}} bytes {%for a in c%} {{a}} {%endfor%} You can [try it online][tio]! [tio]: {{l}} ``` Does this count as a language? Used jinja cli from here: <https://pypi.org/project/jinja2-cli/> I think it should as this is the usage to run it: ``` jinja2 tio.j2 test.json --format=json ``` It accepts a file as a program, and input in some format. That fits the definition of a language to me. This was the input json tested with: ``` {"n": "lang_name", "b": 10, "c": ["line_1", "line_2"], "l": "https://example.com"} ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-pn`, ~~92~~ ~~83~~ ~~79~~ 75 bytes ``` ®N®l®b`# ©N, ©b ¬E;s\n`,÷(\ $+,) ,“0:0X“` [try it a.;][tio]!\n[tio]: ©l`+, ``` Input is: Name, link, byte count and code ## Explained ``` ®N®l®b ``` We first take the inputs `name`, `link` and `byte count` and store them in variable `N`, `l` and `b` respectively. ``` `# ©N, ©b ¬E;s\n`, ``` Next, we construct a string that represents the header. The `©N` and `©b` are used for. string interpolation, and `¬E;` is the compressed word for `byte`. Printing the string using `,` formats the string with variables. ``` ÷(\ $+,) ``` Now, we item split the implicit code list and print each item with a tab appended to it. ``` <newline>, ``` Then, we print a newline to separate everything. ``` “0:0X“` [try it a.;][tio]!\n[tio]: ©l`+, ``` Finally, we construct two strings: the string `You can` (represented by `“0:0X“`) and `[try it online][tio]!\n[tio]: ©l` (which has the variable `l` interpolated within it). The two strings are then joined and printed. [Try it online!](https://tio.run/##y05N////0Dq/Q@tyDq1LSlBWOLTSTwdIJCkoHFrjal0ck5egc3i7RgyniraOJpfOo4Y5BlYGEUAqQSG6pKhSIbNEIVHPOja6JDM/VjEmD0xbAfXnJGjr/P/vnZrOFeLpr5ttUmKWXWBexmXGFa2koaSjoFRjqK2pFKvwX7cgDwA "Keg – Try It Online") ## Answer History ### 79 bytes ``` 0&®N®l®b`# ©N, ©b ¬E;s\n`,÷(`\t`$+,) ,“0:0X“` [try it a.;][tio]!\n[tio]: ©l`+, ``` [Try it Online!](https://tio.run/##y05N///fQO3QOr9D63IOrUtKUFY4tNJPB0gkKSgcWuNqXRyTl6BzeLtGQkxJgoq2jiaXzqOGOQZWBhFAKkEhuqSoUiGzRCFRzzo2uiQzP1YxJg9MWwFNyEnQ1vn/3zs1nSvE018326TELLvAvIzLjCtaSUNJR0GpxlBbUylW4b9uQR4A) ### 83 bytes ``` 0&®N®l®b`# ©N, ©b bytes\n`,÷(`\t`$+,) ,`You can [try it online][tio]!\n[tio]: ©l`, ``` [Try it online!](https://tio.run/##y05N///fQO3QOr9D63IOrUtKUFY4tNJPB0gkKSgkVZakFsfkJegc3q6REFOSoKKto8mlkxCZX6qQnJinEF1SVKmQWaKQn5eTmZcaG12SmR@rGJMHpq2AJuQk6Pz/752azhXi6a@bbVJill1gXsZlxhWtpKGko6BUY6itqRSr8F@3IA8A "Keg – Try It Online") Saved 9 bytes due to not calculating the byte count. ### 92 bytes ``` 0&®N®l÷(:⑴⑼⑹")"⑺⑻®b`# ©N, ©b bytes\n`,(`\t`$+,) ,`You can [try it online][tio]!\n[tio]: ©l`, ``` [Try it online!](https://tio.run/##y05N///fQO3QOr9D63IOb9ewejRxy6OJex5N3KmkqfRo4q5HE3cfWpeUoKxwaKWfDpBIUlBIqixJLY7JS9DRSIgpSVDR1tHk0kmIzC9VSE7MU4guKapUyCxRyM/LycxLjY0uycyPVYzJA9NWQP05CTr//3unpnOFePrrZpuUmGUXmJdxRStpKOkoKNUYamsqxSr81y3IAwA "Keg – Try It Online") Note that I haven't applied string compression yet, which would get this down to 89 bytes. I'll do it tomorrow. The code is to be given as a list where each item is an individual line. [Answer] # C (gcc), 162 bytes ``` t(n,b,c,l)char*n,*c,*l;{for(printf("# %s, %d bytes\n\n ",n,b);*c;)putchar(*c++)-10?:printf(" ");printf("\n\nYou can [try it online][tio]!\n\n[tio]: %s",l);} ``` There may be spaces after a trailing newline but I'm not sure if I'll be able to find a solution (or if a solution is even needed). You can [try it online](https://tio.run/##jY@xjsIwDIb3PoXxCSkJRjoYbmgGBp4CEYZi4IjUc1AJSAjx7D23FQw3nMjkSP/32x9Pv5nbNhuhLTHVlo9V44Qck6v9/ZAac2qi5IPBDxifCcY72N7y/hwkCOhDUtJ6x96eLrmjjePJxE5nn4vyifZB65/fjl2lC3AlsM7NDWKGJHWU/WadY9qMukA/lboT9Sr/aBWFnyqKuaa4s8W96EqzwSUYVbBIMPuaE@AbKuGvi@4bbMI7OgGH6Eso4NDwv1MfeVmFQUvPRi0qHu0v)! [Answer] # Charcoal, ~~67~~ 56 bytes ``` F⪪“`⊟«M["Þ…εU↑⁵ï²¹@↧≡⊗»⭆∧⌕´r⪪ιυNτ⁰⬤N➙⁺⁰UY⟧MyoJb⎇»﹪”¶«ι S ``` You can [try it online](https://tio.run/#charcoal)! [Try it online!](https://tio.run/##RY/PSgJRFIfX9RSn62YGrFllYCJBq4IikBYxV0gHy4Hhjty5BhKBQllJCC0iglKCUNCsqAwmZ3Xd6zucF5hHmGYiafd9h/Pnd4xijht2zgqCA5uDkilZplBIjLI4ZZCviIJDOeUAQFkEe3YZjBwDXfAKmAJsZpmskNWFaWcXooZfSpI4EMqIqsLx/NwON5lQTHV1hgTIv2ywUllkRMiHihqWT4JAJ@t/qaI9KSedWElpThqWE5H7Xgd7Paze72OjLfu@N9ApGbew2pkMfW@I9WusDcev8l26a1jv4uUjNm7lCAd1vOji1Y385OH8xJ2e@d7L9BRrb/j8tI2tO6x9h7Lrey62u1sVezOPzXM58t3w2IP8kv2JC773EWUoClFykpoWPrvEy0yLGbPA2WDxyPoB) Link is to verbose version of code. Assumes you're not worried about Charcoal's default output padding, which can be turned off at a cost of 2 bytes. Explanation: Each input has a certain amount of text that appears before it, which always ends in a space, so the loop prints the text and space before each input. Because it uses separate print commands for the inputs, the newlines in the code block maintain the indent, but the text strings themselves include carriage returns which turn off the indent (particularly applicable to the TIO gubbins). The four text strings themselves are extracted from a large compressed string. ]
[Question] [ Your challenge today is to take a multiline string, and output the biggest square contained within the string that includes the top left corner. A square string is one where: * Each line has the same number of characters * The number of characters on each line is equal to the number of lines. Consider the following possible input string: ``` abcde fgh asdf foobar ``` The largest square you can take from it that includes the first character (the `a` in the topleft corner) is this: ``` abc fgh asd ``` There can't be a square of side-length 4, because the second line isn't long enough. Now consider this potential input: ``` a bcd edf ghi ``` The biggest square here is just `a`. The 3x3 square formed in the bottom doesn't contain the very first character, and doesn't count. Here's a few more test cases: ``` a a ``` --- ``` abc def gh ab de ``` --- ``` ab cd ab cd ``` --- ``` abcde fghij klm no abc fgh klm ``` --- ``` a b a ``` You may require input to be delimited by your choice of LF, CR, or CRLF. The newline character(s) are not considered part of the line's length. You may require there to be or to not be a trailing newline in input, which doesn't count as an additional line. Input is a string or 1D char array; it is not a list of strings. You may assume input is non-empty and all lines are non-empty, and that it only contains printable ASCII, including spaces and newlines (for the line delimiter) but not tabs. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins! [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ►oΛ≈S+TzṀ↑Nḣ¶ ``` [Try it online!](https://tio.run/##ASwA0/9odXNr///ilrpvzpviiYhTK1R64bmA4oaRTuG4o8K2////YWIKY2QKZWYKZw "Husk – Try It Online") ## Explanation ``` ►oΛ≈S+TzṀ↑Nḣ¶ Implicit input, say "ab\nc". ¶ Split at newlines: ["ab","c"] ḣ Take prefixes: [["ab"],["ab","c"]] z N Zip with [1,2,3.. Ṁ↑ by taking that many characters from each row: [["a"],["ab","c"]] ►o Find rightmost element that satisfies this: Λ all strings in S+T the list concatenated to its transpose ≈ have the same length: ["a"] Implicitly print separated by newlines. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes ``` ṇ⊇ᵐẹa₀ṁcᵐ~ṇ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9kdd7Q@3Tni4a2fio6aGhzsbk4G8OqD4//9KiUnJKalcaekZmVlc2Tm5XHn5Sv@jAA "Brachylog – Try It Online") ### Explanation ``` ṇ Split on linebreaks ⊇ᵐ Take a subset of each line ẹ Split the lines into list of chars a₀ Take a prefix of this list of lists of chars ṁ It is a square matrix cᵐ Concatenate the list of chars back into strings ~ṇ Join the strings with linebreaks ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~106 + 1~~ 94 + 2 = 96 bytes +2 bytes for `-rz` flags. Uses unprintable characters NUL and BEL, shown as `@` and `#` here. See below for an xxd dump. Thanks to @seshoumara for sending me down the path to `-z`. ``` s/^/@/gm s/.*/#&\n/ :B s/@(.)/\1@/mg s/#(.+\n)/\1#/m /#.*@./M!b /@\n.*#/!bB : s/@[^\n]*|#.*//g ``` [Try it online!](https://tio.run/##FYuxDsIgGAbZSP636GIqxv@La8fuPoHYBKSgA9AUJ9NnL9LxLndldrUWTBAIkQpYQZ50Ag1jI9HzGfomEEMj2fNFp0NIRIJkJRj3zhKETqwkOjvScGyPSaen2loBhFqNfbmZfHiTKc6Tz9madc/L95NTqdf19wc) ## Explanation This works by inserting two cursors into the text—one to step over lines and one to step over columns. The cursors are represented by NUL (0x00) and BEL (0x07), respectively, but in the below examples I'll use `@` and `#`. Suppose we have this input: ``` abcde fgh asdf foobar ``` The BEL cursor is inserted before the 0th column and the BEL cursor before the 0th line (here I've kept the columns aligned for legibility; but in actuality there is no left padding): ``` #@abcde @fgh @asdf @foobar ``` In a loop, the cursors are moved one character to the right and one line down, respectively: ``` a@bcde #f@gh a@sdf f@oobar ``` ``` ab@cde fg@h #as@df fo@obar ``` ``` abc@de fgh@ asd@f #foo@bar ``` After each iteration, it checks two conditions: 1. On the line with the line cursor, is there a column cursor and can the column cursor move to the right? 2. On the lines before the line cursor, can every column cursor move to the right? If either condition is false, the loop ends. The script finishes by deleting everything after `@` on each line and everything after `#` in the pattern space. ## xxd dump ``` 00000000: 732f 5e2f 002f 676d 0a73 2f2e 2a2f 0726 s/^/./gm.s/.*/.& 00000010: 5c6e 2f0a 3a42 0a73 2f00 282e 292f 5c31 \n/.:B.s/.(.)/\1 00000020: 002f 6d67 0a73 2f07 282e 2b5c 6e29 2f5c ./mg.s/.(.+\n)/\ 00000030: 3107 2f6d 0a2f 072e 2a00 2e2f 4d21 620a 1./m./..*../M!b. 00000040: 2f00 5c6e 2e2a 072f 2162 420a 3a0a 732f /.\n.*./!bB.:.s/ 00000050: 005b 5e5c 6e5d 2a7c 072e 2a2f 2f67 .[^\n]*|..*//g ``` [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` l=input().split('\n') i=0 while zip(*l[:i+1])[i:]:i+=1 for x in l[:i]:print x[:i] ``` [Try it online!](https://tio.run/##LYxBDoIwEEX3PUXDpqCJEZdNOAnDorSFjtZpAzWil0cKLiZ58/7Pj5/kAt3Wt0NveS3tYjWfiqJYfYMUX6msLnP0mEoBJCqGzZUd3S/G8uRbiee6q1qU3UZNzYYw8YUj8Rx1Mk5IiS@Z151Z3haq18YCDaMDUrMZNgyhV5NgQgFtIZDNdnSYVb5eAxm7u/0F0ubw/yW8Az38E4iC@AE "Python 2 – Try It Online") --- An interesting method, but 2 bytes longer. **[Python 2](https://docs.python.org/2/), 83 bytes** ``` l=input().split('\n') while len(zip(*l))<len(l):l.pop() for x in l:print x[:len(l)] ``` [Try it online!](https://tio.run/##LYxBDsIgFET3nIJ0A7hookuiJ/G7oEAL@v2QFmP18rW0LiaZeTOZ/Ckh0Wl5h4ieH7WfveVj0zQLXiLlV5GqnTLGIgWQUGzfoSf5jVkeUKlzDag0tjllqVifRj7zSBx1HiMVPl/1PrktG2D1XZjOOg/UDwHITK5fbUqdGQUTBmgtgXylQ4gVVXUWyPmNbRHIup3/n@Id6IFPIEriBw "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 77 bytes ``` f=(s,i=1,m=s.match(`^${`(.{${i}}).* `.repeat(i)}`))=>m?f(s,i+1)||m.slice(1):0 ``` Recursively uses a regular expression to search for a larger and larger square until none is found. The regular expression would be this for a 3x3 square: ``` ^(.{3}).* (.{3}).* (.{3}).* ``` Input is expected to end with a newline, and output is a list. **Explanation:** ``` f = (s, //input i = 1, //start searching for a 1x1 square m = s.match(`^${`(.{${i}}).*\n`.repeat(i)}`) //match on the regex )=> m ? f(s, i+1) //if there's a match, recurse on the next-sized square || m.slice(1) : //if there's not a next-sized square, return the match 0 //no match for this square, so stop recursing ``` **Snippet:** ``` f=(s,i=1,m=s.match(`^${`(.{${i}}).* `.repeat(i)}`))=>m?f(s,i+1)||m.slice(1):0 console.log(f(`abcde\nfgh\nasdf\nfoobar`)); console.log(f(`a\nbcd\nedf\nghi\n`)); console.log(f(`a\n`)); console.log(f(`abc\ndef\ngh\n`)); console.log(f(`ab\ncd\n`)); console.log(f('abcde\nfghij\nklm\nno')); console.log(f(`a\nb\n`)); ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 16 bytes ``` ṇ{ẹa₀ᵐa₀ṁ}ᶠtcᵐ~ṇ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9uqHu3YmPmpqeLh1Apja2Vj7cNuCkmQgvw4o/f@/UmJSckoqV1p6BldicUoaV1p@flJikdL/KAA "Brachylog – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 84 bytes ``` chomp(@a=<>);map$.&&=y///c>$i,@a[0..$i]while$.&&$i++<$#a;say/(.{$i})/ for@a[0..$i-1] ``` [Try it online!](https://tio.run/##NcpLCoMwEADQfU5R6CCKNYkLV37wAj2BuBg1wQHthKRQpPTqjXTR9XvO@K2KcV55d2mPbdNl9Y4OZJK0h1Jq7oBuPQ5aSqDxtdJmfgaU5w1csQ54qFS@gT6Zulj2/1qUY4w4GSPsggLDYoVlntB/2T2JHyEW90rqUp8 "Perl 5 – Try It Online") Fulfills the `"abcde\nfghij\nklm\nno"` test case. [Answer] # [R](https://www.r-project.org/), ~~84~~ ~~83~~ ~~81~~ 76 bytes *-5 bytes porting [Dennis' approach](https://codegolf.stackexchange.com/a/147458/67312) with `sum`* ``` cat(substr(x<-readLines(),1,m<-sum(cummin(nchar(x))>=seq(x)))[1:m],sep='\n') ``` [Try it online!](https://tio.run/##Fco7DoAgDADQnYvYJjC4GvUE3kAdCtbPUKJUEm@Pur3hpVIC3aDZ653gaV1iWoYjsgLa2krrNAuELHJEiGGnLyH2nfL1A8e6kdkqn101xQoL@WD8wmbd9vIC "R – Try It Online") reads from stdin, prints to stdout without a trailing newline. Slightly ungolfed: ``` x <- readLines() # read in input one line at a time; # saved as a vector of strings minChar <- cummin(nchar(x)) # rolling minimum of all line lengths lineNum <- seq(x) # line number mins <- minChar>=lineNum # the min between the line number and the line lengths m <- sum(mins) # the sum of those is the size of the square cat(substr(x,1,m)[1:m],sep='\n') # print the first m characters of the first m lines, # and join with newlines ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~162~~ ~~159~~ ~~151~~ ~~147~~ ~~144~~ ~~142~~ 137 bytes There must be some strokes to golf away here... ``` i,l=9;char*p,s[9][8];main(t){for(p=s;~(*p=getchar());)p=*p<32?*p=0,l=(t=strlen(s+i))<l?t:l,s[++i]:p+1;for(i=0;i<l;puts(s+i++))s[i][l]=0;} ``` [Try it online!](https://tio.run/##FczBEoIgFIXhPU/CFZux2qTA@CAMCyPUW6h3hFZNvTrh9px/PneanMsZ66Bb6eZhr6iOprXmZuUy4MoTfMZt56Sj/PGK9OTTkXEACaQrUtdLX@amADzpmPbgVx4FAqjQpy4UTQi0HYmzPCDUjUQVJL1TPDohAKJBa4Itzzfn4e4eno3TjE/2CgtbN/LsDw "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` L€«\‘>Jx@Z ỴÇÇY ``` [Try it online!](https://tio.run/##y0rNyan8/9/nUdOaQ6tjHjXMsPOqcIjierh7y@H2w@2R/49Ofrhz8aPGfYe2Hdp2uB2oKgvK@f8/MSk5JZUrLT2DK7E4JY0rLT8/KbGIiyuRCyjOlQoUSc/IBHG5gAq5UlJBfBCbCyjLBdebmcWVnZPLlZcP1ggA "Jelly – Try It Online") ### How it works ``` ỴÇÇY Main link. Argument: s (string) Ỵ Split s at linefeeds, yielding a string array. Ç Apply the helper link. Ç Apply the helper link again. Y Join, separating by linefeeds. L€«\‘>Jx@Z Helper link. Argument: A (string array/2D character array) L€ Compute the length of each row/line. «\ Take the cumulative minimum. ‘ Increment each minimum. J Indices; yield [1, ..., len(A)]. > Perform elementwise comparison. If the output should have n lines, this yields an array of n ones and len(A)-n zeroes. Z Zip/transpose A. x@ For each string t in the result to the right, repeat its characters as many times as indicated in the result to the left, discarding all but the first n characters. ``` [Answer] # Java 8, 150 bytes ``` s->{String q[]=s.split("\n"),r="";int l=q[0].length(),i=0,t;for(;i<l;l=t<l?t:l)t=q[i++].length();for(i=0;i<l;)r+=q[i++].substring(0,l)+"\n";return r;} ``` **Explanation:** [Try it here.](https://tio.run/##jZDBbsMgDIbvfQorJ1DSqOfRbE@wXnYsPRBCUlpqUnAqTVWePaNZpt22SiDZ@Pvt35zUTa19b/DUnCftVIzwrizeVwAWyYRWaQO7RwrwQcFiB5otQeQivY/pphNJkdWwA4QKprh@vS/UdX@oYhl7Z4llEjNehCrLROoOrrruN4fSGezoyHhhq01BovWBCbt1wlW0dW/04jgl0Ob5LzpDCZ85HvKfehzqOI9lm8Lx/DFPBENDQAhinMS3136oXfK6WL5528AlLb3stT@A4svGn5HMpfQDlX0qkUOGpWaZqnVjJLbdUaKKTZtC72sVMj5/yR9CiUkq0Tw03dH@L6i1xMbM9BOwRN0803Nxb08Sz@4iEf1T1hdoXI3TFw) ``` s->{ // Method with String as both parameter and return-type String q[]=s.split("\n"), // Split the input on new-lines, and put it in an array r=""; // Result-String, starting empty int l=q[0].length(), // Length of the lines, starting at the length of line 1 i=0, // Index-integer, starting at 0 t; // Temp integer for(;i<l; // Loop (1) from 0 to `l` (exclusive) l=t<l? // After every iteration: if `t` is smaller than `l`: t // Change `l` to `t` : // Else: l) // Leave `l` the same t=q[i++].length(); // Set `t` to the length of the current line // End of loop (1) (implicit / single-line body) for(i=0;i<l; // Loop (2) from 0 to `l` (the determined square dimension) r+= // Append the result-String with: q[i++].substring(0,l) // The current row chopped at `l-1` +"\n" // + a new-line ); // End of loop (2) return r; // Return the result-String } // End of method ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 33 bytes ``` 10-~ft1)wdhqY<tn:vX<X>:GYbowt3$)c ``` [Try it online!](https://tio.run/##y00syfn/39BAty6txFCzPCWjMNKmJM@qLMImws7KPTIpv7zEWEUz@f//aPXEpHR1BUMDBfWU1DQoKz0DTIOYWdk5uXn5BRDxQhAVCwA "MATL – Try It Online") My spidey sense tells me that there's probably a shorter way (I'm thinking something with `Ybo` right from the start)... Requires a newline at the end. (Note: I over-engineered this a bit, as this will handle empty lines as well, which is not required. I'll see if I can reduce the bytecount, because in code golf, it's not a feature, but a bug) [Answer] # [Python 2](https://docs.python.org/2/), 132 bytes ``` def f(s):s=s.split("\n");return["\n".join([l[:j+1]for l in s[:j+1]])for j,v in enumerate(s[0])if all(len(l)>j for l in s[:j+1])][-1] ``` [Try it online!](https://tio.run/##dc5BDsIgEAXQ/ZyCsIKojXVZoxdBFtSCBenQADXx9JVqjMbE5f95fzLjPfcBd/PcaUMMS7xJh1Sl0dvM6Akp30edp4hiCZULFpnwonGrWpoQiScWSXplyZfGrW9Lp3EadFRZsyS2kltDlPfMa2SeHx353XIpNrWcx2gxlzcopao9dxrMpQeVOgMmhFbF0nN4IoBvCwWDLuzS23/mfc86uPoBMHzg/AA "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 103 bytes ``` def f(i): i=i.split('\n');x=0 while all(v[x:]for v in i[:x+1])*i[x:]:x+=1 for v in i[:x]:print v[:x] ``` [Try it online!](https://tio.run/##bY9BDoIwEEX3c4oJG1pNjLis4STIotCWjtaWAEE8fS2yMrj7ee8tZvr3ZIO/xKi0QcOIC0Aq6TT2jiaW33zOr0t5BnxZchqlc2yuFlGbMOCM5JEqsRyLmh9oxWmXBeCPrUU/kJ9wXnc0LMsy2bRKg@ksyFEZMCE0ckicX78pbBGkCnTynaWd3IGmhfRDavcGWvUn3y6gOzzcE3xYi/gB "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), 95 bytes ``` f= s=>(g=s=>s.slice(0,a.findIndex((e,i)=>a.some((s,j)=>j<=i&!s[i]))))(a=s.split` `).map(g).join` ` ``` ``` <textarea oninput=o.textContent=f(this.value+`\n`)></textarea><pre id=o> ``` Requires a trailing newline in input. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes ``` Column[For[i=1,d=c;MatrixQ[c=StringExtract[#,"\n"->;;i,""->2;;i+1]],i++];Row/@d]& ``` [Try it online!](https://tio.run/##Dcu9DsIgFEDhncfAxAWMqSvBNDF1M/FnRIYrlPZqgYRcY98emc63nAg0jxEIHdSg6ykv35jMOReDupNeO3UBKrjejNOPhjQNKxVwZDaSPxPfHZVCyVsPDaKzVqIQVt3zb997u63X9lAfDIeX8yML04xv9lkiS5nb@gc "Wolfram Language (Mathematica) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 25 bytes\* Tacit prefix function. Returns a matrix. ``` (↑↑⍨2⍴(⌊/≢,≢¨))⎕AV[3]∘≠⊆⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSNR20TQah3hdGj3i0aj3q69B91LtIB4kMrNDUf9U11DIs2jn3UMeNR54JHXW2Puhb9D0lMCsn3cQNqVudUB6oIUo/JU/@fpgAVV1BPTEpOSeVMS8/gTCxOSeNMy89PSixS50JWwQlUwpkKlEzPyESVQeUlJXOmpIJUoQlzJqegK4RYmZnFmZ2Ty5mXj26fOgA "APL (Dyalog Unicode) – Try It Online") It is really an atop of two independent functions, namely `⎕AV[3]∘≠⊆⊢` which deals with the awkward input format and `↑↑⍨2⍴(⌊/≢,≢¨)` which does the actual interesting work. `⎕AV[3]∘≠` difference from LF (the third element of the **A**tomic **V**ector – the character set) `⊆` partitions (substrings beginning at values larger than their predecessor and drop at 0s) `⊢` the argument `(`…`)` apply the following tacit function:  `2⍴(`…`)` reshape the following to length 2:   `⌊/` the minimum of   `≢` the number of strings   `,` followed by   `≢¨` the number of characters in each string `↑⍨` take that many rows and columns from  `↑` the strings mixed together to form a matrix (padding with spaces) --- \* In Classic with `⎕ML` (**M**igration **L**evel) `3` (default on many systems) and substituting `⊂` for `⊆` and `⊃` for the leftmost `↑`. [Tio!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2Ccb/04CkxqOu5kdtEx/1rjB61LtF41FPl/6jzkU6QHxohaYmUK1jWLRx7KOOGY86FzzqanrUteh/SGJSSL6PG1CzOqc6UEWQekye@v80Bai4gnpiUnJKKmdaegZnYnFKGmdafn5SYpE6F7IKTqASzlSgZHpGJqoMKi8pmTMlFaQKTZgzOQVdIcTKzCzO7Jxczrx8dPvUAQ "APL (Dyalog Classic) – Try It Online") [Answer] # PHP, 123 bytes ``` for(;preg_match("#^(\S{".++$i."}.* ){"."$i}#",$s="$argv[1] "););while($k<$i-1)echo substr(split(" ",$s)[+$k++],0,$i-1)," "; ``` requires PHP 5.4, 5.5 or 5.6. Replace `split` with `explode` for later PHP. Run with `php -nr '<code> '<string>'` or [try it online](http://sandbox.onlinephpfunctions.com/code/a93caa26395525c82927f955d02dbe2da2514bc5). (Make sure you select a suiting PHP version!) [Answer] # [Haskell](https://www.haskell.org/), ~~92~~ 88 bytes ``` unlines.f.lines f s|let t=take$until(all.(.l).(<=)<*>(`take`s))pred$l s=t<$>t s l=length ``` [Try it online!](https://tio.run/##HckxDoMwDADAPa/wwJBUal5AeEkH3OCEFGMhbLa@vana6YZbUTdi7jU9@iXchDSW@NcV0DeTgSXDjYZLrLFH5ugjh@jHFMbb5OdfzhrCcdIyMGiycZgM1HFikmpr37EJJGhidGI2qB2feXFUqlvba2O3yycXxqr9no/jCw "Haskell – Try It Online") [Answer] # Perl 5, 60 +5 (-0777p) bytes ``` $.++while/^(.{$.}.* ){$.}/;$_=join" ",(/.{$.}/gm)[0..--$.-1] ``` [Try it online](https://tio.run/##K0gtyjH9/19FT1u7PCMzJ1VfQ69aRa9WT4tLE0TrW6vE22blZ@YpcSnpaOjHgSX103M1ow309HR1VfR0DWP//09MSk5J5UpLz8jM4srOyeXKy@f6l19QkpmfV/xf18CgAAA) * The last line of input must end with a newline in case it belongs to output. * In case of two consecutive newlines -00 may option be changed by -0777. [Answer] # [Perl 6](https://perl6.org), ~~158~~ 140 bytes ``` my$c;for ^(my@b=lines).elems {any(@b.head(++$c).map({.substr(0,$c).chars <$c}))&&$c--&&last;};say @b.head($c).map({.substr(0,$c)}).join(" ") ``` [Try it online!](https://tio.run/##bcsxCsMgFADQ3VNIEFHSSKcuaSAnKXyNqaZqgj8dJOTslg7duj54m83hVmsszPTzmulDxDLqIfhkUSobbER6QCpi1MpZmETbMiNVhE0cCt8a9yyuly8ZBxnpnZlTSs6Z6TrOA@Denz1Cob//f59SLatPoiGNrBW0mSyZn84v5BUiSesH "Perl 6 – Try It Online") Hooray for my first Perl 6 answer. I'll play around with some command line options to see if I can golf this a bit more. All help saving bytes is welcome! [Answer] # [Scala](https://scala-lang.org), 201 bytes ``` type S=String def c(s:S):S={val? =s split "\n" var(z,q:Seq[S])=(Seq(?size,?(0).size).min,Nil) while(1<2){?map(i=>{if(i.size>=z)q=q:+i.take(z) if(q.size==z)return q mkString "\n"}) q=Nil;z-=1} return""} ``` [Try it online!](https://scastie.scala-lang.org/TheInitializer/yI8B9SmfT1imHbAg9rwH9A) First time golfing in this language, so maybe not the greatest. ]
[Question] [ Given a matrix of integers, test if it's rank-one, meaning that every row is a multiple of the same vector. For example, in ``` 2 0 -20 10 -3 0 30 -15 0 0 0 0 ``` every row is a multiple of `1 0 -10 5`. The same definition also works with columns in place of rows. Alternatively, a matrix is rank-one if it's like a multiplication table: ``` * 1 0 -10 5 ---------------- 2 | 2 0 -20 10 -3 | -3 0 30 -15 0 | 0 0 0 0 ``` We've assigned row labels `r[i]`and column labels `c[j]` so that each matrix entry `M[i][j]` is the product of the corresponding labels as `M[i][j] = r[i] * c[j]`. **Input:** An integer matrix as a 2D container of your choice. For example, a list of lists, a 2D array, or similar. You shouldn't take the width or height as additional inputs unless the array format requires it. The matrix may be non-square. It will have at least one nonzero entry -- you don't have to deal with empty or zero matrices. You can assume the integers won't cause overflow issues. **Output:** A consistent value for rank-one matrices, and a different consistent value for other matrices. **Built-ins:** You *may not* use any built-in to computes rank or directly check rank one. You may use other built-ins like eigenvalues, decompositions, etc, but I encourage upvoting answers that don't have built-ins do most of the work. **Test cases:** Rank-one: ``` [[2, 0, -20, 10], [-3, 0, 30, -15], [0, 0, 0, 0]] [[0, 0, 0], [0, 3, 0], [0, 0, 0]] [[-10]] [[0, 0, 0], [0, 4, 11], [0, -4, -11]] ``` Not rank-one: ``` [[-2, 1], [2, 4]] [[0, 0, 3], [-22, 0, 0]] [[1, 2, 3], [2, 4, 6], [3, 6, 10]] [[0, -2, 0, 0], [0, 0, 0, 1], [0, 0, -2, 0]] ``` **Leaderboard:** ``` var QUESTION_ID=143528,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/143528/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] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ẸÐfÆrE ``` [Try it online!](https://tio.run/##y0rNyan8///hrh2HJ6Qdbity/X@4/VHTGiBy//8/OjraSEfBQEdB1whIGBrE6ihE6xqDRYxBooamIBEDsAAIxcbqcClEwwSgcsYIJpIaXUPsqk2A9hhC2bomIDsMY4EKFWK4gI7RBboGLAmkTVC0G4OdZmSEYoehjoIRVMoIbLIZiAl0jxnYM3D9ukYoToAgQwQPLA90BQA "Jelly – Try It Online") ### How it works ``` ẸÐfÆrE Main link. Argument: M (2D array) ẸÐf Filter by any, removing rows of zeroes. Ær Interpret each row as coefficients of a polynomial and solve it over the complex numbers. E Test if all results are equal. ``` ### Precision `Ær` uses numerical methods, so its results are usually inexact. For example, the input **[6, -5, 1]**, which represents the polynomial **6 - 5x + x²**, results in the roots **3.0000000000000004** and **1.9999999999999998**. However, multiplying all coefficients of a polynomial by the same non-zero constant results in equally inexact roots. For example, `Ær` obtains the same roots for **[6, -5, 1]** and **[6 × 10100, -5 × 10100, 10100]**. It should be noted that the limited precision of the *float* and *complex* types **can** lead to errors. For example, `Ær` would obtain the same roots for **[1, 1]** and **[10100, 10100 + 1]**. Since [we can assume the matrix is not large and not specifically chosen to be misclassified](https://codegolf.stackexchange.com/questions/143528/is-the-matrix-rank-one#comment351903_143528), that should be fine. [Answer] # [Haskell](https://www.haskell.org/), 50 bytes `r` takes a list of lists of `Integer`s and returns `False` if the matrix has rank one, `True` otherwise. ``` r l=or[map(x*)b<map(y*)a|a<-l,b<-l,(x,y)<-zip a b] ``` [Try it online!](https://tio.run/##bU7RDoIwDHz3KxriA4ONsIE@GPRHJg9DSSBONKARjP@O60DBxKRpr9dre4VqTrnW/VmV1basbnmtDrflvdJllTfBWV1dd6/ZrikuD9C@72zA8X3s3Bo0IUGdqyMJrLo3zPZSS1xqPZIlCDqPqJdKmKYZJrelHUnYs7yCgizteykFhZACEybxMKUgWWSZCFm@Qia0BEaaLuSnHSfRBL8Kxv8pY/OBj5jFeJ0PamPB8qbGs73IuhFidphTEONA2INrhMbC2rofd5n4@TsEnzo7N@I3 "Haskell – Try It Online") # How it works * Generates all pairs of rows `a` and `b` (including equal rows), and for each pair, lets `x` and `y` run through corresponding elements. * Multiplies the row `b` by `x` and the row `a` by `y`. The matrix will have rank one if and only if the results are always equal. * Since pairs are generated in both orders, `<` can be used to check if there's ever an inequality. The list of test results are combined with `or`, giving `True` if there are any non-proportional rows. [Answer] # Mathematica, ~~51~~ 33 bytes ``` RowReduce@#~Count~Except@{0..}<2& ``` **Input** > > [{{2,0,-20,10},{-3,0,30,-15},{0,0,0,0}}] > > > *-14 bytes from user202729* 3 more bytes saved from junghwanmin [Answer] # JavaScript (ES6), ~~68~~ ~~67~~ 65 bytes This one is based on [Neil's 05AB1E answer](https://codegolf.stackexchange.com/a/143554/58563) and is significantly more efficient than my original approach. Returns `false` for rank-one and `true` otherwise. ``` f=(a,R,V,X)=>a.some(r=>r.some((v,x)=>R?v*V-r[X]*R[x]:f(a,r,v,x))) ``` ### Test cases ``` f=(a,R,V,X)=>a.some(r=>r.some((v,x)=>R?v*V-r[X]*R[x]:f(a,r,v,x))) console.log(f([[2, 0, -20, 10], [-3, 0, 30, -15], [0, 0, 0, 0]])) console.log(f([[0, 0, 0], [0, 3, 0], [0, 0, 0]])) console.log(f([[-10]])) console.log(f([[0, 0, 0], [0, 4, 11], [0, -4, -11]])) console.log(f([[-2, 1], [2, 4]])) console.log(f([[0, 0, 3], [-22, 0, 0]])) console.log(f([[1, 2, 3], [2, 4, 6], [3, 6, 10]])) console.log(f([[0, -2, 0, 0], [0, 0, 0, 1], [0, 0, -2, 0]])) ``` --- # Original answer, 84 bytes Returns `false` for rank-one and `true` otherwise. ``` a=>a.some(r=>r.some((x,i)=>(isNaN(x/=a.find(r=>r.some(x=>x))[i])?r:1/r[0]?r=x:x)-r)) ``` ### Test cases ``` let f = a=>a.some(r=>r.some((x,i)=>(isNaN(x/=a.find(r=>r.some(x=>x))[i])?r:1/r[0]?r=x:x)-r)) console.log(f([[2, 0, -20, 10], [-3, 0, 30, -15], [0, 0, 0, 0]])) console.log(f([[0, 0, 0], [0, 3, 0], [0, 0, 0]])) console.log(f([[-10]])) console.log(f([[0, 0, 0], [0, 4, 11], [0, -4, -11]])) console.log(f([[-2, 1], [2, 4]])) console.log(f([[0, 0, 3], [-22, 0, 0]])) console.log(f([[1, 2, 3], [2, 4, 6], [3, 6, 10]])) console.log(f([[0, -2, 0, 0], [0, 0, 0, 1], [0, 0, -2, 0]])) ``` ### How? ``` a => a.some(r => // given a matrix a, for each row r of a: r.some((x, i) => // for each value x of r at position i: ( // isNaN(x /= // divide x by a[ref][i] a.find(r => // where ref is the index of the first row that r.some(x => x) // contains at least one non-zero value )[i] // (guaranteed to exist by challenge rules) ) ? // we get NaN for 0/0, in which case: r // use r, so that this column is ignored : // else: 1 / r[0] ? // if r is still holding the current row: r = x // set it to x (either a float, +Inf or -Inf) : // else: x // use x ) - r // subtract r from the value set above (see table) ) // end of some() ) // end of every() ``` The subtraction which is performed at the end of the code can lead to many different situations, which are summarized below: ``` A | B | A - B | False / True --------------------+----------------+-------------+------------- array of 1 number | same array | 0 | False array of 2+ numbers | same array | NaN | False a number | same number | 0 | False +Infinity | +Infinity | NaN | False -Infinity | -Infinity | NaN | False a number | another number | <> 0 | True +Infinity | -Infinity | +Infinity | True -Infinity | +Infinity | -Infinity | True a number | +/-Infinity | +/-Infinity | True +/-Infinity | a number | +/-Infinity | True ``` The test fails as soon as we get a truthy value: this happens when we encounter two distinct ratios (other than ***0 / 0***) between ***a(i,y)*** and ***a(i,r)*** in any row ***y*** of the matrix, where ***r*** is the index of a non-zero row. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~16~~ 13 bytes ``` 2ãεø2ãε`R*E]W ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f6PDic1sP7wBTCUFarrHh//9HRxvqKBjpKBjH6ihEA2kTHQUzENMYSOsoGBrExgIA "05AB1E (legacy) – Try It Online") Uses the multiplication table property that the opposite corners of any rectangle have the same product. Edit: Saved 3 bytes thanks to @KevinCruijssen. Explanation: ``` 2ãε Loop over each pair of rows ø Transpose the pair into a row of pairs 2ãε Loop over each pair of columns `R*E Cross-multiply and check for equality ]W All results must be true ``` [Answer] # [Python 2](https://docs.python.org/2/) + numpy, 58 bytes ``` lambda m:sum(linalg.svd(m)[1]>1e-10)==1 from numpy import* ``` [Try it online!](https://tio.run/##dVBBDsIgELzzij22BgxLqweT@hHkUKNVkkKbFk18fYW1Rm0iITDMsLMD/SNcO6@mpjpMbe2Opxrcbry5rLW@bi/r8X7KXK7R7PEsUOZVhawZOgf@5voHWNd3Q1hN4TyGESrQDOLQWnGQHISKC0rDQYuCmCKxuEmMJCJNY/hc9iZecvGBv9dikH81ZWyIMxZlaoZfdTEWiXEvlw4FxVRq2Qw5qFlV5L9NMGbb0tu@XYT6ySKXJ9KNYYaxphvAgvVAP7cjj36wPkCT2Xx6Ag "Python 2 – Try It Online") Credit to [this](https://stackoverflow.com/questions/2473983/calculate-matrix-rank-using-scipy). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ẸÐfµ÷"ЀZE€Ẹ ``` [Try it online!](https://tio.run/##y0rNyan8///hrh2HJ6Qd2np4u9LhCY@a1kS5Agmg4P/D7UDG///R0dFGOgoGOgq6RkDC0CBWRyFa1xgsYgwSNTQFiRiABUAoNlaHSyEaJgCVM0YwkdToGmJXbQK0xxDK1jUB2WEI0wF0ClgGSJug6DUGu8vICMUCQx0FI6iUEdhYMxAT6BgzsE/g@nWNUOyHIEMEDywfG8sVCwA "Jelly – Try It Online") # Explanation ``` ẸÐfµ÷"ЀZE€Ẹ Main link Ðf Filter; keep all elements where Ẹ At least one element is truthy (remove zero-rows) Ѐ For each row on the right side ÷" Divide it by each row in the original Z Zip the array € For each submatrix E Are all rows equal? Ẹ Is at least one of the elements from above truthy? ``` Explanation may be slightly incorrect as this is my interpretation of miles's golf of my original algorithm -5 bytes thanks to miles [Answer] # TI-Basic (TI-83 series), ~~28~~ ~~27~~ 28 bytes (62 characters) ``` :Prompt [A] :{0→X :Matr►list(ref([A])ᵀ,L₁,X :not(max(abs(ᶫX ``` Computes the row-echelon form of the matrix `[A]`, stores its first row (to be discarded) in `L₁` and its second row in `ᶫX`. Then `max(abs(ᶫX` will be zero if `ᶫX` consists only of zeroes, and a positive value otherwise, which `not(` changes to 1 if the matrix is rank one, 0 otherwise. For a 1-row matrix, `ᶫX` is set to `{0}` and then doesn't get changed when we try to look at the nonexistent second row of the matrix. --- *-1 byte thanks to Scott Milner* *+1 byte to fix dimension error for 1-row matrices. Turns out the* `Matr►list(` *command complains if you try to extract the second row from a matrix with only one row; however, if you try to extract the first and second row both from the matrix, it will fail silently.* [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes ``` {⊇Ċ}ᶠzᵐ{↰₁ᶠ{⟨hz{t↔}⟩×ᵐ=}ᵐ}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRV/uRrtqH2xZUPdw6ofpR24ZHTY1AXvWj@SsyqqpLHrVNqX00f@Xh6UBZ21ogAcL//0dHG@koGOgoxBsBCUODWB2F6HhjsIgxSNTQFCRiABYAIRDPHKLBHKQGXToWAA "Brachylog – Try It Online") Uses Neil's approach of "products of opposite corners of each rectangle should be equal". Cross product is costly and takes 10 whole bytes, but this is still shorter than any division based approach I tried, mainly because of the stipulation of two consistent outputs for truthy and falsey in the question - making falsey be only a `false.`, and not sometimes a divide-by-zero error, uses too many bytes. ``` {⊇Ċ}ᶠzᵐ{↰₁ᶠ{⟨hz{t↔}⟩×ᵐ=}ᵐ}ᵐ {⊇Ċ}ᶠ Get each pair of rows from the matrix eg.: [ [[a, b, c], [k, l, m]], ... ] zᵐ Zip each pair's elements [ [[a, k], [b, l], [c, m]], ... ] { }ᵐ Map this over each pair of rows: [[a, k], [b, l], [c, m]] ↰₁ᶠ Get each pair of paired elements from the rows [[[a, k], [b, l]], [[b, l], [c, m]], [[a, k], [c, m]]] { }ᵐ Map this over each pair of pairs [[a, k], [b, l]] ⟨hz{t↔}⟩ Zip the first pair with the reverse of the second [[a, l], [k, b]] ×ᵐ Multiply within each sublist [al, kb] = The results should be equal (If the results are unequal for any pair, the whole predicate fails, and outputs false.) ``` Alternate approach based on element-wise division (**30 bytes**): ``` {≡ᵉ¬0&}ˢ\↰₁ˢ{c׬0&⟨hz∋⟩ᶠ/ᵐ²=ᵐ} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pR58KHWzsPrTFQqz29KOZR24ZHTY2nF1UnH54OEns0f0VG1aOO7kfzVz7ctkD/4dYJhzbZAsna//@jo410FAx0FOKNgIShQayOQnS8MVjEGCRqaAoSMQALgBCIZw7RYA5Sgy4dCwA "Brachylog – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ẸÐf÷g/$€E ``` [Try it online!](https://tio.run/##y0rNyan8///hrh2HJ6Qd3p6ur/KoaY3r/8PtQOropIc7ZwDpyP//o7mio410FAx0FHSNgIShQayOQrSuMVjEGCRqaAoSMQALgFBsrA5QC4wDkTJGMBFKdA2xqjUBWmIIZeuagCwwBCkDaQC6AywDpE2QtRqD3WRkhGy6oY6CEVTGCGyoGYgJdIgZ2BMw3bpGKJZDkCGCB5ZH9yBXLAA "Jelly – Try It Online\" (All test cases") ``` ẸÐf Discard zero rows ÷ $€ Divide each row by g/ its greatest common divisor E Does this list have only one unique element? ``` [Answer] ## SageMath, 40 bytes ``` lambda M:any(M.rref()[1:])*(M.nrows()>1) ``` [Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTwtUrMq9Tw1SsqSk3T0Iw2tIrV1AJy84ryy4s1NO0MNXm5eLkKijLzShTSNHITS4oyKzSio410FAx0FHSNgIShQaxOtK4xWMAYJGhoChQwAPNBKDZWUxOLCYY6CkZAdSZATThVGIFkAJfFLh0=&lang=sage) This anonymous function returns `False` if the matrix is rank-one, and `True` otherwise. The function takes a matrix `M` as input, converts it to reduced row-echelon form (`M.rref()`), and tests for `any` of the rows past the first being non-zero. Then, that value is multiplied by `M.nrows()>1` (does the matrix have more than one row?). [Answer] # [Python 3](https://docs.python.org/3/), ~~93~~ 91 bytes ``` lambda m,e=enumerate:any(h*g-r[j]*s[i]for r in m for i,h in e(r)for s in m for j,g in e(s)) ``` [Try it online!](https://tio.run/##dVDBDsIgDL3vK3rcDCQDpgeTfQlymJE5jGMG8ODXT1pn1CUSAu179PXR2yMNk1dz3x7mazceTx2MzLbW30cbumT3nX@Uw@bMg76YTdTO9FOAAM7DCBg6NmBiy1BhGj/MhZ1fTKyqOdmYIrSgC8hLa8mgZsBlPkRtGGiuCFGIii0iNQG4jWFL2Rt40eoT/j7j4m9NkxuKJeYNNhNfddkWkflu1gqKbEq5biYYyIWVpL/DMHvb0d@@Vbj88VKvM@KNKUxR0GxxfjS5PWncgvOp7EuXB/oE "Python 3 – Try It Online") *How it works* Checks if any 2-minor has nonzero determinant. If this is the case the rank must be at least 2: "A non-vanishing p-minor (p × p submatrix with non-zero determinant) shows that the rows and columns of that submatrix are linearly independent, and thus those rows and columns of the full matrix are linearly independent (in the full matrix), so the row and column rank are at least as large as the determinantal rank" (from [Wikipedia](https://en.m.wikipedia.org/wiki/Rank_(linear_algebra))) Note: shaved two bytes thanks to user71546's comment. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 18 bytes ``` a->#matimage(a)==1 ``` `matimage` gives a basis of the image of the linear transformation defined by the matrix. [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1045N7EkMzcxPVUjUdPW1vB/QVFmXolGmka0kY6CgY6CrhGQMDSwVtA1BvONQWKGptYgNhTFamr@BwA "Pari/GP – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 86 bytes Golfed version. [Try it online!](https://tio.run/##jVJRT4MwEH7nV1yWPbSmEFrmHhYh0TcT/QVmMQVrxHSFUDRMwm/HtsBkyhKT47jvu@vXu7Y645L3Rfoushoeea5ANLVQLxpuyxJaD@CTS5C5rjXE8GD@yHAwRM4xAiEBnxlHQ0yGjB85NrIZej2xoSOtYUx@yUyJn9LoHC4v8@m/tDamOTrD/sY2Rhf0zDinQhNvLqlHp1EZu9QcJcBmlcz1sZ2gmW/rzmxpB5/9mWEwes64OoyNgP2sjVdW7ZzWk3P3qt7vcZzcFYUUXEHcyziRgWjsvSI@i9M44cFXXqIUj1SbcS1QQ45mfRoceImerxoc6I/DDR/h0cEO4x6GpxK8FpXg2Ru0DkOcuAnLKle1VEiv1pbewbqtkI1wt7Ltd57X9d8) ``` l=>l.exists(a=>l.exists(b=>a.zip(b).exists{case(x,y)=>b.map(_*x).sum<a.map(_*y).sum})) ``` Ungolfed version. [Try it online!](https://tio.run/##jVLbaoNAEH3PVxxCHtyi4q5pHkJTaN8K7ReUUFazoRajkrXFVPx2uztiYhIDhXF25syZm7s6lqls2zz6UnGJN5lkUFWpso3GU1GgngA/MkWa6FJjhVdzOgZDZ5ESLgIXnjCKB8ztIl5IaGgj/L5HAwKtMOZelOkDJ2p47o6nefxfteZmOD7wvbkdjI/UM@scicae36oeHlcV4tZw3IUYMAXNsehds9@C/tlYB09c7dAJP0eIx5gpYD8jdFX@Nt8rGX@iJh@rR@pQ7JOsTDNHT2cWXmJW7x1rsWZq05uJURu1RYcuqdE7qZesXK/ZEs95niqZmbdQU0nL81VF76OG7DtdBqJTAJD@b1I4ETuFY6kVnMrFgQ2JQOTvZOF84A4V8/X3Dg8mu4cOBB3ZzWR4NrRP07Z/) ``` object Main extends App { val lists = List( List(List(2, 0, -20, 10), List(-3, 0, 30, -15), List(0, 0, 0, 0)), List(List(0, 0, 0), List(0, 3, 0), List(0, 0, 0)), List(List(-10)), List(List(0, 0, 0), List(0, 4, 11), List(0, -4, -11)), List(List(-2, 1), List(2, 4)), List(List(0, 0, 3), List(-22, 0, 0)), List(List(1, 2, 3), List(2, 4, 6), List(3, 6, 10)), List(List(0, -2, 0, 0), List(0, 0, 0, 1), List(0, 0, -2, 0)) ) lists.foreach { list => println(s"$list: ${r(list)}") } def r(list: List[List[Int]]): Boolean = { list.exists { a => list.exists { b => a.zip(b).exists { case (x, y) => b.map(_ * x).sum < a.map(_ * y).sum } } } } } ``` ]
[Question] [ Consider a length-\$n\$ array of positive integers. * The **complement** of the element with index \$i\$ is the element with index \$n - i - 1\$. * The **twin** of an element \$a\$ is its complement after removing all elements not equal to \$a\$. For example, in the array `[1, 2, 3, 4, 2, 1, 3, 2]`, the complement of the first `2` is the last `3`, and the twin of the first `2` is the last `2`. (In general, the twin of the first \$a\$ is the last \$a\$, the twin of the second \$a\$ is the second-to-last \$a\$, etc.) Given a non-empty array of positive integers, replace each element with the complement of its twin. ``` [1, 2, 3, 4, 2, 1, 3, 2] -> [3, 1, 2, 2, 4, 2, 1, 3] [1, 2, 1, 3] -> [2, 1, 3, 1] [10] -> [10] [8, 3, 1, 8, 1, 8, 3, 10, 3, 8, 10, 8] -> [8, 8, 10, 1, 8, 3, 8, 3, 10, 3, 1, 8] ``` [Answer] # [R](https://www.r-project.org/), ~~65~~ ~~59~~ ~~50~~ ~~41~~ 36 bytes ``` function(x,`!`=order)x[!rev(x)][!!x] ``` [Try it online!](https://tio.run/##dYzBCsMgEETv/YqVXhQsqOnBS/ojIg1YC4HGFDGtf2/R0A2UFGSdnX0zsaT3GK5unp4PP/mQ@nJfgkvjHGjmAxn6Od58ZNmQ6F80M2sIyfY3RR2VHBSHjsO5Cdm0YgyOcLqA6Zql2tsIe/hXVK8Yxj65GxAISrEH6DXLQX9nXUX79Ko0Vmj0EN3oatnyAQ "R – Try It Online") **How?** First, a couple of tricks used: 1. Re-assign the `!` operator to become the `order` function, 2. Notice that `rank(x)` is equivalent to `order(order(x))`, with tied ranks broken by first occurrence. So, ungolfed: ``` twin_complement= function(x){ o=order(rev(x)) # get the order of reversed values of x, # breaking ties in reverse order-of-first-occurrence in x; t=o[rank(x, # use this to get the twin index for each index of reversed x ties.method="first")] # = the element at the rank position of each x value, # now breaking ties in order-of-first-occurrence in x; x[t] # finally, return the complement of x # at each twin position in reversed x. } ``` [Answer] # [Minipyth](https://github.com/isaacg1/minipyth), 30 bytes (17.7 bytes if encoded) ``` mhoithzsmqmscbnqgihcmmzsbbnlis ``` Minipyth is a new minimalist language I've designed. It only uses lowercase letters, and it doesn't have things like variables, arity 2 functions, etc. Because Minipyth only uses lowercase letters, it could be re-encoded to be much shorter. I'm therefore also listing its information-theoretic length, which shorter by a factor of $$\log(26)/\log(256) \approxeq 59\%.$$ Minipyth doesn't have an online executor yet, but it can be used offline through the repository linked above. It's executed from right to left, in function application order. I'll break it down into several pieces to show what's going on. First, we prepare a list consisting of elements of the form [complement, index, value], where value is an element of the input, index is its position in the input, and complement is its complement. ``` cmmzsbbnlis b Bifurcate: make a list by applying two functions to the input b Function 1: Bifurcate on n negate, reversing the input, l length, the length of the input is inverse sum, wrap the input in a list. s sum, concatenate into a single list of 3 elements m map on mz the default map, identify on lists, casts int x to [0, ..., x-1] c chop, transpose the three lists to form lists of 3 elements. ``` Next, we group these elements by their values. This is simply `gih`, group by inverse head (last element). Now, we need to form the twins. ``` smqmscbnq m Map over the groups. bn Bifurcate on n, reversing the group. c Chop, forming pairs. ms Sum the pairs, concatenating into one list s Sum, concatenating the lists back into one ``` z and q just make everything parse correctly. Now, our elements are six element lists: [twin's complement, twin's index, twin's value, complement, index, value]. We just need to put things back into their original order using the index, then extract the twin's complement. ``` mhoithz o Order by i Inverse of t Tail h Head The inverse of tail removes the final element, then the inverse of head returns the second-to-last mh Map to head ``` One note, at the time of this writing (commit 4436b81a3), inverse reverses the order of application of its arguments. This was to mimic inverse functions, but I've decided I don't like it, and I will undo that. In the future, the equivalent program will have h and t swapped: ``` mhoithzsmqmscbnqgihcmmzsbbnlis ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ĠUFỤịỤịU ``` [Try it online!](https://tio.run/##y0rNyan8///IglC3h7uXPNzdDSFD////H22ho2Cso2Coo2ABI0FcAzBlAWFZxAIA "Jelly – Try It Online") Port of Jonah's J answer: ``` Ġ Group indices U Reverse each group F Flatten Ụ Grade up ịỤ Index into graded-up original list ịU Index into reversed list e.g. input: “XYXZYY” (needn't be integers!) Ġ: [[1,3],[2,5,6],[4]] U: [[3,1],[6,5,2],[4]] F: [ 3,1, 6,5,2, 4 ] Ụ: [2,5,1,6,4,3] This is a "rank" of the input, breaking ties backwards: X Y X Z Y Y 2 1 rank Xs backwards 5 4 3 rank Ys backwards 6 rank Zs backwards → [2,5,1,6,4,3]. Meanwhile, Ụ is [1,3,2,5,6,4] (equiv. to ĠF), indices that sort the input: [X,Y,X,Z,Y,Y] [1, 3, indices of Xs 2, 5,6, indices of Ys 4] indices of Zs Now ịỤ permutes one list by the other, mapping each element to its twin's index: ịỤ: [3,6,1,4,5,2] X Y X Z Y Y 3 1 Twin indices of Xs 6 5 2 Twin indices of Ys 4 Twin indices of Zs And we only have to index into the backwards input: ịU: “ZXYXYY” ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes ``` ĠUF,ỤyJịU ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLEoFVGLOG7pHlK4buLVSIsIiIsIiIsWyJbOCwgMywgMSwgOCwgMSwgOCwgMywgMTAsIDMsIDgsIDEwLCA4XSJdXQ==) ``` ĠUF,ỤyJịU Main Link Ġ Group indices by equal elements U Reverse each block F Flatten ,Ụ Pair with the grade of the original list yJ Apply this as a translation to the indices of the list ịU Index that into the reverse of the original list ``` -1 byte thanks to Lynn with the grading up trick. Grading up a list sorts the indices by their corresponding values. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ỤỤịUỤ$ị ``` [Try it online!](https://tio.run/##y0rNyan8///h7iVg1B0KpFSA9P///6MtdBSMdRQMdRQsYCSIawCmLCAsi1gA "Jelly – Try It Online") Port of [my R answer](https://codegolf.stackexchange.com/a/240053/95126). Pseudocode: `x [ order of reverse of x ] [ order of order of x ]` [Jelly](https://github.com/DennisMitchell/jelly) explanation: ``` ỤỤ # get the order of the order of the input; ị # use this to index into... $ # (previous two links together) U # ...reverse of Ụ # ...order of the input; ị # finally use this to index into the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ĠżṚ$€ẎḢÞịṚ ``` A full program that accepts the list and prints the result. **[Try it online!](https://tio.run/##y0rNyan8///IgqN7Hu6cpfKoac3DXX0Pdyw6PO/h7m6gyP///6MNdRSMdBSMdRRMwAxDMNsoFgA "Jelly – Try It Online")** ### How? ``` ĠżṚ$€ẎḢÞịṚ - Main Link: list, A Ġ - group indices by their element's values $€ - for each: Ṛ - reverse that list of indices having equal values ż - zip the two together Ẏ - tighten (to a list of [index, twin index] pairs) Þ - sort by: Ḣ - pop head from the pair being inspected Ṛ - reverse A ị - use the (remaining) twin indices to index into the reversed copy of A - implicit, smashing print ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~18~~ 17 bytes ``` IEθ§θ§⌕A⮌θι⌕⌕Aθικ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQR8GxxDMvJbUCmemWmZfimJOjEZRallpUnKpRqKmjkAnEIHG4ZCFELFsTDKz//4@OttBRMNZRMNRRsICRIK4BmLKAsCxiY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over elements θ Input array § Indexed by θ Input array ⮌ Reversed ⌕A Find all occurrences of ι Current value § Indexed by θ Input array ⌕A Find all occurrences of ι Current value ⌕ Find index of κ Current index I Cast to string Implicitly print ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 9 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Port of [Dominic van Essen's R answer](https://codegolf.stackexchange.com/a/240053/64121). ``` ⍋∘⍋⊏⍋∘⌽⊏⊢ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4o2L4oiY4o2L4oqP4o2L4oiY4oy94oqP4oqiCgo+KOKLiOKfnEYpwqgg4p+oMeKAvzLigL8z4oC/NOKAvzLigL8x4oC/M+KAvzIKMeKAvzLigL8x4oC/Mwrii4gxMAo44oC/M+KAvzHigL844oC/MeKAvzjigL8z4oC/MTDigL8z4oC/OOKAvzEw4oC/OOKfqQ==) --- # [BQN](https://mlochbaum.github.io/BQN/), ~~17~~ 13 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ~~My own attempt that ended up being similar to~~ Based on Lynn's Jelly answer that is a port of [Jonah's J answer](https://codegolf.stackexchange.com/a/240062/64121). ``` ⌽⊏˜{⍋∾⌽¨⊔𝕩}⊏⍋ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oy94oqPy5x74o2L4oi+4oy9wqjiipTwnZWpfeKKj+KNiwoKPijii4jin5xGKcKoIOKfqDHigL8y4oC/M+KAvzTigL8y4oC/MeKAvzPigL8yCjHigL8y4oC/MeKAvzMK4ouIMTAKOOKAvzPigL8x4oC/OOKAvzHigL844oC/M+KAvzEw4oC/M+KAvzjigL8xMOKAvzjin6k=) [Answer] # [R](https://www.r-project.org/), ~~41~~ ~~39~~ 32 bytes ``` function(x)ave(rev(x),x,FUN=rev) ``` [Try it online!](https://tio.run/##K/pfUp6ZF5@cn1uQk5qbmldi@z@tNC@5JDM/T6NCM7EsVaMotQzI0qnQcQv1swVyNNF1aCRrGOooGOkoGOsomIAZhmC2kaamgrKCrp1CtDFYyAiMECpiuXAZBJKFa4abZ4hVgwFcoaEBNgUWEL06ChYwEsQ1AFMWEJYF3AgLuBhcKUI1SCj2PwA "R – Try It Online") I thought of this as a `split %>% lapply %>% unsplit` before remembering that `ave` does the same thing for fewer bytes. Test harness taken from [Dominic van Essen's answer.](https://codegolf.stackexchange.com/a/240053/67312) Explanation to follow. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 19 bytes ``` ƛ?=TḂZ;UÞfµh;vt?Ṙ$İ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGmz89VOG4glo7VcOeZsK1aDt2dD/huZgkxLAiLCIiLCJbMSwgMiwgMywgNCwgMiwgMSwgMywgMl0iXQ==) A clumsy port of Jonathan Allan's answer. ``` ƛ ; # Map input to... ?=T # Indices of that element ḂZ # Zipped with its reverse UÞf # Uniquify and flatten to a list of [index, pair index] pairs µh; # Sort by first item vt # Get second item of each İ # Use those to index into ?Ṙ$ # Input reversed ``` [Answer] # [J](http://jsoftware.com/), 24 bytes ``` |.{~[:(/:&;~|.&.>)<@I.@= ``` [Try it online!](https://tio.run/##VY/BCsIwEETv/YrBQ7UQY2M8hGilKAiCqHj1VGu0CDbSVhEUf70mNohCdnfe7mxCTnWLtg@IJNogCCFNdCmmm8WsftLHays7PekPX0/q03Ewiuc0jurAU2mm0ekTMAJucoCuxMGS6zkHJ65nzuA7/HPz34kRbpNIFjqflZ63nFCo@0WlldpDX6vLtUKaJfnR4C7Fao1SqXOJSiNLbgpJDlUUuqDuQgEBFoKZwj9hgFt0r4jmJ8SKJlsMP0U0StRv "J – Try It Online") [Answer] # Python/NumPy, 60 bytes ``` def f(a): b=a*0 for S in a:b[a==S]=a[a[::-1]==S] return b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bU7BSsNAFLznKx457cqmJKmHEFzBFqFisYcWLKw5bDChC8lm2W6UIP0SL7koePJ7-jcmmxopCMu-mXnzhnn_VI3ZVbJtP2qTe9Hx6jnLIUccxw6klF_4DuSVhjUICTxOGad0nVDOOItjL0h65oDOTK0lpKeML1GqShuQdaka4HuQynndiSKDoEsFQSqgUHKFshdeECFVbRCe7FUhDHLBuwYX486ntJAGCZIjqSZca94ggTFxnx7eZjfL5WoDs9UWHu82C9ge_hHni9v5_cFl_XVRoPMYSiuc4KFwe_xmAYGQwJTApQWBxWHSt2FTy0P7_taJczqyxBrHw6Bf-oPYTYdFg0wg-v176tsRDSga7NEojL4zd68mQ-8f) Expects and returns numpy arrays. [Answer] # JavaScript (ES6), 56 bytes ``` a=>a.map(v=>a[b[j=b.indexOf(v)]=0,j],b=[...a].reverse()) ``` [Try it online!](https://tio.run/##hY1NDoMgFIT3PQVLSCj@dcEGr9ADEBao2GisGG1Ib0/l2dpWm5QQGIaZ77Xa6akcm@F27G1lfC28FrlmVz1gNwtZyFYUrOkrcz/X2BElYtoqWgjJGNOKjcaZcTKYEF/afrKdYZ294BrLhKKUooyiE4gEdKoIQZsVRUhmEEhhv/Pq8JMJX3vOlrkOTfac@E//kzOHt32@cCnirzM8Y7j4ojhMCP3gPM01@9UILlL@AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(v => // for each value v in a[]: a[ // lookup in a[]: b[ j = // get the position j b.indexOf(v) // of the 1st occurrence of v in b[] ] = 0, // and clear it j // get a[j] ], // end of lookup b = [...a] // start with b[] initialized to .reverse() // a copy of a[] in reverse order ) // end of map() ``` [Answer] # JavaScript (ES2022), 48 bytes ``` a=>a.map(g=n=>a.at(g[n]=~-g[n])-n?g(n):a[~g[n]]) ``` ``` f= a=>a.map(g=n=>a.at(g[n]=~-g[n])-n?g(n):a[~g[n]]) console.log(f([1, 2, 3, 4, 2, 1, 3, 2]) + ''); // [3, 1, 2, 2, 4, 2, 1, 3] console.log(f([1, 2, 1, 3]) + ''); // [2, 1, 3, 1] console.log(f([10]) + ''); // [10] console.log(f([8, 3, 1, 8, 1, 8, 3, 10, 3, 8, 10, 8]) + ''); // [8, 8, 10, 1, 8, 3, 8, 3, 10, 3, 1, 8] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÙvIIyQƶ0K©RIgαè®<ǝ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8MwyT8/KwGPbDLwPrQzyTD@38fCKQ@tsjs/9/z/aQsdYx1DHAoyBLAMgYQGiLGIB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeXhCaH/D88si4ioDDy2zcD70MqgiPRzGw@vOLTO5vjc/7U6/6OjDXWMdIx1TICkIZA2itVRAAsBOWCmAYi0AMoY6liAMZBlACQsQJRFbCwA). **Explanation:** ``` Ù # Uniquify the (implicit) input-list v # Loop over each unique value `y`: IyQ # Check for each value in the input-list if it's equal to `y` # (1 if truthy; 0 if falsey) ƶ # Multiply each by its 1-based index 0K # Remove all 0s © # Store this list in variable `®` (without popping) R # Reverse it α # Get the absolute difference between each 1-based index Ig # and the input-length I è # Use that to (0-based) index into the input-list ®< # Push `®` and decrease each by 1 to make them 0-based ǝ # Insert the values at those indices into the list # (which will be the implicit input-list in the first iteration) # (after the loop, the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~131~~ 127 bytes ``` c;j;i;*w;*f(a,n)int*a;{for(w=calloc(i=n,4);i--;w[i]=a[n+~j]){for(j=c=0;j<=i;)c+=a[i]==a[j++];for(j=n;c;)c-=a[i]==a[--j];}a=w;}; ``` [Try it online!](https://tio.run/##nVLbitswEH3frxCGLL7INL4spJ1V@1D6FY4pRpFbX@oEy5DQ4P56OpZ8kd1CywZHGs2Z0Zw5I@5/4/zx4FBCAe4V3NzOaOMUTedmcM/PrX1lPKvrM7cL1tDYgcL34ZoUKcuSxvtVpo6KKhlneyhfWQEO9xDDAFxLz0tB4w1whPwZ8v0yhT5jV@jhgfXIj6xobIfcnwj@BkcnZBckKWHkHlASUhJREisjUHbYwxwXmnEDbGDRiO0NX6x9B3URxh@mdTju1XbQ1qGHFaOvtU6VxU9xzm1F0nk3nlx9pMRAwzUartFojUZrNF6jsbOQcRUbqcmoslQrobdIb7HBXtwugnfiNGqqGw/VF291m2JHXWfNgw2@1XbyL/qOMs7qrjQOVvq6c7rOngnThc9iRos5dcnPjewI/561Lq6CV6LVN1nH25fweHv/Gf8vFiXmObLGbHynxB6aKJqTuGHaHkbzdZrJVHAZy@wB4nkqenrCy5zwKj0rhadgwqQeUXxXW/jSYkBuW4nlLM6ZZaUZVsiuHopXZmEzfSd3J@y5@jQ0/sHCtUuq1Liy/6NiSvyPZFVWdSKxJD5MSuotIhCZh/e3Ni@ZHLKDNzWic9X2/EwEsieMEYk7/GfH8t8d7@Sxwcjp3QzVzJS8FcKWo6N/6h@/AQ "C (gcc) – Try It Online") *Saved 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a pointer to an array (\$a\$) of integers and its length (because pointers in C carry no length info). Returns a pointer to an array of all of \$a\$'s elements' twins' complements. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ⇧₌Ṙ⇧İİ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6figozhuZjih6fEsMSwIiwiIiwiWzgsIDMsIDEsIDgsIDEsIDgsIDMsIDEwLCAzLCA4LCAxMCwgOF0iXQ==) Port of [Dominic's Jelly answer](https://codegolf.stackexchange.com/a/240159/100664). ``` ⇧ # Gradeup ₌Ṙ⇧ # Push ^ reversed, ^ gradeup'd İ # Use the reversed copy to index into the double-gradeup'd İ # Use those indicies to index into the input. ``` ]
[Question] [ ## The challenge Interpret the stack-based programming language [underload](https://esolangs.org/wiki/Underload). The stack is a stack of strings that can be concatenated together. Each underload program is a string of some of these instructions: * `~`: Swap the top two elements of the stack. * `:`: Duplicate the top element of the stack. * `!`: Discard the top element of the stack. * `*`: Concatenate the top two elements of the stack together. * `(x)`: Push the string between the parenthesis to the stack. Parentheses can nest within strings, so `(a(bc)d)` should push the string `a(bc)d` to the stack, not `a(bc`. * `a`: Enclose the top element of the stack in parenthesis. * `^`: Pop the top element of the stack, and append it the program, directly after this instruction. * `S`: Pop the top element of the stack and print it. ## Test cases ``` (Hello, world!)S Hello, world! (!@#$%^&*())S !@#$%^&*() (a)(b)~SS ab (a)(b)!S a (a)(b)*S ab (a)aS (a) (b)(a)^S (b) (a(:^)*S):^ (a(:^)*S):^ ``` ## Input The input will be a string, either through STDIN, as an argument to a function, or however your programming language takes input. You can assume the input will have matched parenthesis and will not attempt to run invalid instructions. ## Output The output will also be a string. This is code-golf, so the shortest answer in bytes is wins! [Answer] # [Python 3](https://docs.python.org/3/), ~~243~~ ~~242~~ 238 bytes ``` s=input() q=[] P=q.pop d=w=i=0 while s[i:]: c=ord(s[i]);i+=1 if 40==c:d+=1;w=[i,w][d>1] elif d:x=41==c;d-=x;q+=[s[w:i-1]][d:]*x else:y=P();exec("q+=y,y q+='(%s)'%y, q+=P()+y, print(end=y) y s=s[:i]+y+s[i:] q+=y,P()".split()[c%20%9%7]) ``` [Try it online!](https://tio.run/##NZBBb4MwDIXv@RVpN0ZSaFW2StOCPO3SabdV6m5RkFqSqdEQ0EAFueyvM0PXi/1e/FnyS@3bU1U@DXmlDQUahuHQgC3rS8s4OYNUZAfnVV3VREMHFtakO9nC0EZaoQShOVROM3SKpzaChFD7TTdrgFxotGkH0sadkvo1UYSaAqda9LBJkEj1Evr0HIFsZCfsMlHICbXoR7AxwsOO8dT0JmdzpHzsKbaQBQ0PAx@PBoEIVe1s2TJTavCcetpAI4VVkY@mM@m0jOh81dSFxWQyDx7XwUvwrPhw3eUEo5P/cF/uYjAbbZ0fG6XTDeMXcTKa3NQt3X6@b52r3JU4OnP4GdiHKYoqpl3lCj3je8Jmb3f3QfawYHx0B86O/Hd/U7ObWEzigPXIUWSjZSLDdy6yPw "Python 3 – Try It Online") **Pseudo Code:** ``` read program from STDIN into s initialize empty stack q parenthesis nesting level d string start index w instruction pointer i while the program has instructions left: get current instruction; increment instruction pointer if current instruction c is '(': increment parenthesis nesting level d update string start index if new nesting level is 1 elif we are in a string: if the current command is ')': decrement nesting level d push string to stack if we reached level 0 otherwise execute the code for the current command ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~237~~ 221 bytes *Saved 8 bytes thanks to @tsh* ``` f=([c,...s],S=p=[O=o=''])=>c?((n=Buffer(c)[0],n-40?n-41?p:--p||!S.push(o):p++)?o+=c:eval("o=''0(q=1,1)+q)0q=1,q)/1/s=[...1,...s]/01,1)0`(${1})`)/O+=1".replace(/\d/g,n=>+n?'S.pop()':'/S.push(').split`/`[n%15%11]),f(s,S)):O ``` [Try it online!](https://tio.run/##bY3BboJAFEX3/QqgWt6TgWGSdkMy0nTVnQuWFAIiWJsJM4LaRW1/nY7aYhQ3k8l55977ke/ytmhWauPWclF2XcUhLojneW1CIq54POOS23aCfFqEADV/2VZV2UCBsZ@Q2n30Q/2wUAWuq/Z7M/LUtn0HiYFyHAylw4ug3OUCrEOND2vOCENnjf7ht0bKaMtjvcdOo9Q/3P0MRl/sGzOkM4czy2tKJfKiBPq2oEtS86lTh7bekgrQDmz6N2uj1yqx2mQ0i@sxexozliCpoCURYjDrClm3UpSekEuowILXUghJjE/ZiIWJkYVoUGpc0LvrjPl8PxqnDxNAHTAM45Q500EgR5jjT3SUjT6Qz2@LZu/9i7e9ycC7VZifrV7UeGDOUdP0ulLjYScEqR7HILUuOnvc/QI "JavaScript (Node.js) – Try It Online") ### Commented For readability, let's assign the list of commands to an explicit variable `cmd`: ``` cmd = "o=''0(q=1,1)+q)0q=1,q)/1/s=[...1,...s]/01,1)0`(${1})`)/O+=1" .replace(/\d/g, n => +n ? 'S.pop()' : '/S.push(') .split`/` ``` This expands to: ``` [ "o=''", // non-nested closing parenthesis 'S.push((q=S.pop(),S.pop())+q)', // '*' (concatenate) 'S.push(q=S.pop(),q)', // ':' (duplicate) 'S.pop()', // '!' (drop) 's=[...S.pop(),...s]', // '^' (append to the program) '', // not used 'S.push(S.pop(),S.pop())', // '~' (swap) 'S.push(`(${S.pop()})`)', // 'a' (enclose) 'O+=S.pop()' // 'S' (print) ] ``` The main code now reads as: ``` f = ( // f is a recursive function taking: [ c, // c = next character ...s ], // s[] = array of remaining characters S = // S[] = stack p = [ // p = counter of opened parentheses O = // O = output string o = '' // o = current string ] // ) => // c ? // if c is defined: ( // ( // parentheses processing: n = Buffer(c)[0], // n = ASCII code of c n - 40 ? // if c is not an opening parenthesis: n - 41 ? // if c is not a closing parenthesis: p // yield p : // else: --p || // pre-decrement p !S.push(o) // push o to the stack if p = 0 : // else: p++ // post-increment p ) // end of parentheses processing ? // if the above is truthy (i.e. we are // currently within a string definition): o += c // append c to o : // else: eval( // evaluate the command which is indexed cmd[n % 15 % 11] // by (n mod 15) mod 11 ), // f(s, S) // recursive call to f ) // : // else: O // we're done: return the final output ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~88~~ 72 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ï9╓╩¢▬'D└⌡○♠↨ó•ó♀▒m5E■V\╖O|é░xÄ9ª╝╬K╝╝∩1◄3`-2*♫▓☼╤?÷°ZôyZ┘¿{ClñI▀«╛■ß«R9 ``` [Run and debug it](https://staxlang.xyz/#p=8b39d6ca9b162744c0f5090617a207a20cb16d3545fe565cb74f7c82b0788e39a6bcce4bbcbcef311133602d322a0eb20fd13ff6f85a93795ad9a87b436ca449dfaebefee1ae5239&i=%28Hello,+world%21%29S%0A%28%21%40%23%24%25%5E%26*%28%29%29S%0A%28a%29%28b%29%7ESS%0A%28a%29%28b%29%21S%0A%28a%29%28b%29*S%0A%28a%29aS%0A%28b%29%28a%29%5ES%0A%28a%28%3A%5E%29*S%29%3A%5E%0A%28%3AaSS%29%3AaSS%0A%28%3AaS%28%3A%5ES%5E%3A%29Sa%3A%29%3A%5ES%5E%3A%28%3AaS%28%3A%5ES%5E%3A%29Sa%3A%29%0A%28%3A%3A%3A%3A%29%3A%28%3A%28%28%5E%3A%28%29%7E%28%28%3A%29*%7E%5E%29a%7E*%5E%21%21%28%29%7E%5E%29%29%7E*%28%29%7E%5E%5E%29%7E%28%5Ea%28*%7E%5E%29*a%7E*%28%29%7E%5E%21%28%29%7E%5E%29a%7E**%5E%21%21%5ES&m=2) I thought this would be simple with a stack based language. I was wrong. Fixed a bug which caused `()` to immediately halt the program. ## Explanation ``` w # while top of stack isn't empty: yB # remove first char of program sY # store rest of program in register Y sc40= # is first char a '('? { # if true: d1y # delete char, push 1 and program { # take chars while the following returns true c.()# # is current char in "()"? {]"(^)v"|tl} #if so, if (, increment the 1 otherwise decrement {d}? # otherwise delete the char c copy the 1 }h sdc%^Na)Yd # remove length + 1 chars from the program, store in Y } { # otherwise, execute stack command: sd] # delete copy of input "~s:c!d*+Sp^""y+Yd"97.:{3l+ # underload to stax translation array :t # translate the current char to stax l # execute }? y # push y at the end(if empty, ends the program) ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 157 bytes ``` .{/^S/&*>,G1` ^((\^)|[S!])(.*)¶(.*)|^:(.*(¶.*)) $#2*$4$3$5$6 ^((~)|\*)(.*)¶(.*)(¶.*) $3$5$#2*¶$4 ^\((((\()|(?<-3>\))|[^()¶])*)\)(.*) $4¶$1 ^a(.*¶)(.*) $1($2) ``` [Try it online!](https://tio.run/##TY09CsJAEIX7PYUho8xb/CEaLYKoXQTLlK5DIqYQgoIIFgaPlQPkYnESFdxi9nvD95hbfj9fsqDpc5w24@dEksnAroZxkBphdoJyn3gH8NiirtpZSqQf15UyDPlTSyHNaE6LtvBC6eyf/fFMJ6haVxQacazPMUpeL0ezlYMeEdbGARauaxsK1Q2MZJrq6rsLmKZoEKfG7dKGt3lRXIe9x/VWnDwkhr2NT30ZWEabMvARr@RH3g9sB5nOIxSkjRyJ7hHJGw "Retina – Try It Online") Link includes test suite. Explanation: ``` . ``` Don't output the stack at the end of the program. ``` { ``` Repeat until the program has been processed (assuming no invalid instructions). ``` /^S/&*>,G1` ``` If the next instruction is `S` then print the top of the stack (this does not pop the stack yet). ``` ^((\^)|[S!])(.*)¶(.*)|^:(.*(¶.*)) $#2*$4$3$5$6 ``` If the next instruction is `S` or `!` then discard the top of the stack, but if it is `\^` then prepend it to the remainder of the program, while if it is `:` then duplicate the top of the stack. ``` ^((~)|\*)(.*)¶(.*)(¶.*) $3$5$#2*¶$4 ``` If the next instruction is `~` then swap the two elements of the stack otherwise if it is `*` then join then together (this needs the elements to be swapped first, so the functions are combined here.) ``` ^\((((\()|(?<-3>\))|[^()¶])*)\)(.*) $4¶$1 ``` If the next instruction is a `(` then push a (presumably) balanced string until the matching `)`. (If there aren't any `)`s then the interpreter will give up while if there aren't enough `)`s then the interpreter will match until the last one.) ``` ^a(.*¶)(.*) $1($2) ``` If the next instruction is an `a` then wrap the top of the stack in `(` and `)`. [Answer] # Haskell, 322 bytes Function is `l []`. ``` l(s:t:v)('~':x)=l(t:s:v)x l(s:t)(':':x)=l(s:s:t)x l(_:s)('!':x)=l s x l(s:t:v)('*':x)=l((s++t):v)x l(s:t)('a':x)=l(('(':s++")"):t)x l(s:t)('^':x)=l t(s++x) l(s:t)('S':x)=s++l t x l t('(':x)=h t 0""x h t 0a(')':x)=l(reverse a:t)x h t n a(')':x)=h t(n-1)(')':a)x h t n a('(':x)=h t(n+1)('(':a)x h t n a(c:x)=h t n(c:a)x ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 189 bytes ``` f=([C,...P],X=T=L='',Y,...S)=>C?eval(`f(P,${L*(L-=C=='('?-1:C==')')?'X+C,Y':` ^P.unshift(...X)&&Y ~Y,X :X,X,Y !Y *Y+X a'('+X+')',Y S(T+=X,Y) ('',X,Y )X,Y`.match(` [${C}](.*)`)[1]},...S)`):T ``` [Try it online!](https://tio.run/##bY49b4MwEIZ3/4qSUnwHBilb5cqlEksHBiQYbCGQnTQoVDSJCKVDlPx16rRDpZLldHrej7t3M5rjum8PQzg@TlMjoExYFEVZxaQoRCooZeoKchTPSbwZTQe6gYy5p9SHNBSJEBRoHC75dUOKMZVBwhTlmtRZ9Lk7bttmANsg0fMUuSgmCZdMMkUcRXwVSGJsQyADm7YwhyIQVkUC9vbVhnbo6MMM6y1oUrqn5FxB5KPGclmdf5/TyIvp0Le7ARpYwOum6/bs7mvfd28O5gvEJ/KnOi/37kPt@YAzySCs8JLfxM5N6s@p@Y9WaGk9MwKvbRx5/SNM3w "JavaScript (V8) – Try It Online") ``` f=( [C,...P], // C = Current command; P = Following program X= // X, Y = Top 2 of stack; S = Remaining stack T= // Output L='', // Current brackets level Y,...S )=>C? // Is program not finished? // Recursive call fol following command eval(`f(P,${ L*(L-=C=='('?-1:C==')')? // If currently we are in brackets 'X+C,Y': // We append this character to the top element of stack // Otherwise, based on different command (1st letter each line) // we execute different codes here // And the the result is whatever placed on top of stack ` ^P.unshift(...X)&&Y ~Y,X :X,X,Y !Y *Y+X a'('+X+')',Y S(T+=X,Y) ('',X,Y )X,Y`.match( // We use thi regex to get codes we need execute ` [${C}](.*)`)[1] },...S)` // Remaining stack ):T // Everything done, output goes here ``` [Answer] # [Haskell](https://www.haskell.org/), ~~272~~… 252 bytes ``` ([]?) s?('(':r)|l<-1%r=(take(l-1)r:s)?drop l r (x:s)?('^':r)=s?(x++r) (x:s)?('S':r)=x++s?r s?(c:r)=s!c?r s?e=e (x:y:s)!'~'=y:x:s (x:s)!':'=x:x:s (_:s)!'!'=s (x:y:s)!'*'=(y++x):s (x:s)!'a'=('(':x++")"):s 0%r=0 n%(c:r)=1+(n+sum[1|c=='(']-sum[1|c==')'])%r ``` [Try it online!](https://tio.run/##RZDBboMwEETvfAVOS72LSxWuqIYee8iNYwqVQyCN4gCyiQpSlE8vtUEJF2veeMa78o/Qp1LKseJfI2yzBB2dAAUaKbzK9yD0FIdOnEqQQYgq0pjsVdO60lUO9BaB5jbMTa1nTOHDTifbeDpR9tFiSpFiopKXNjiYKKE3yofItOYqoRHl/czfExPK9ZL2KYeBsR6XgjCW3dkMW@HKXqzN3mun9uapIYOa6ct5G14Lzk0yCxZCmqGnxrM41vxQdptjXcYxby9d2qlN/VbFsb0a4dN8U/Pq/jZK7gmmDpCPp2cvf/EBLQmEHd7SuyJ34U9CmHOHRuQWIcqNj1H@V1RSHPQYFG37Dw "Haskell – Try It Online") The relevant function is `([]?)`, which takes an Underload program as a `String` as input and returns a `String` as output. There is already an interesting Haskell answer, make sure to go upvote that as well (once it's fixed)! ~~I decided to post my own answer because, well, I finally found a use for the `Monad` instance of `(,) a`!~~ Yeah, I knew it couldn't last... [Answer] # [CJam](https://sourceforge.net/p/cjam/wiki/Home/), 80 bytes ``` {`(;);EDero}:S{[\\]`(;);"} {"/~+~}:B{a`"[]"Eer~}:Cq"()~:!*^a":D"{}\_;B~C":Eer~]; ``` **[Try it online!](http://cjam.aditsu.net/#code=%7B%60(%3B)%3BEDero%7D%3AS%7B%5B%5C%5C%5D%60(%3B)%3B%22%7D%20%7B%22%2F%7E%2B%7E%7D%3AB%7Ba%60%22%5B%5D%22Eer%7D%3ACq%22()%7E%3A!*%5Ea%22%3AD%22%7B%7D%5C_%3BB%7EC%22%3AEer%7E%5D%3B&input=%7BC%7B_%7E%7DBS%7D)** Could probably be a fair bit smaller ;) --- ### How it works The interpreter is split into two parts: first, we define helper functions; then, we convert the Underload program into a CJam program and run it. **Conversion** ``` q"()~:!*^a":D"{}\_;B~C":Eer ``` ``` q Reads in the Underload program as a string "()~:!*^a" "{}\_;B~C" er Replaces "(" with "{", ")" with "}", etc :D :E We take the opportunity to define these strings as D and E, since we have to "unreplace" when we print ``` **Helper functions** We call the printing function `S` so we can avoid having to replace characters when `S` comes up in the Underload program. ``` {`(;);EDero}:S ``` ``` { }:S Define a function named S ` Since the elements are represented as blocks, we have to turn the block into a string (;); On top of that, all the blocks are surrounded by 1 too many parentheses when we turn them into strings, so we remove those EDer We translate backwards into Underload by "unreplacing" the special characters o And then print and pop the string ``` We call the concatenation function `B` (for no particular reason). ``` {[\\]`(;);"} {"/~+~}:B ``` ``` [\\] Make an array with ONLY the top two elements of the stack `(;); And turn it into a string (remembering to remove the square brackets we got when we turned it into an array) "} {"/ The only gap between two curly brackets is between the two elements that we want to merge, so we split along that gap ~+~ Then we merge and turn it back into a block ``` We call the array-enising function `C` (we unfortunately cannot use `a` as lowercase letters are reserved for language-defined functions) ``` {a`"[]"Eer~}:C a` Array-enise our block in CJam and turn it into a string "[]"Eer Replace the array characters with "{}" (luckily the extra characters in E are ignored) ~ Convert it from a string to a block ``` **Running the converted program (& cleanup)** It takes 1 character to run the converted program after we've made it: `~`. After this we need to clean up our functions, since they are sitting on the stack and *will* be printed if we don't get rid of them. We do this by collecting everything left on the stack and popping it: `];`. [Answer] # [Underload](https://esolangs.org/wiki/Underload), 1 byte ``` ^ ``` **[Try it online!](https://tio.run/##K81LSS3KyU9M@a/xXyNRwypOUytY0yruv2bcfwA)** If we assume the input program is put on the stack as an element (`(PROGRAM)`), then all that is required is to run that program! *Note:* In the TIO, the header and footer wrap the "Code" section in parentheses, making it not run, but instead become an element at the top of the stack. Then at the end of the footer is the `^` which runs the code. --- *This is only a joke/non-competing answer, since although interpreting languages in themselves isn't always trivial/boring, in this case it really is.* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 93 bytes ``` “Ṫ,Ṫ;@“0ịṭ“Ṗ“Ṫ;@Ṫṭ“Ṫ⁾()jṭ“ṪȮṛ”W€“~:!*aS”żẎy Żi@þØ(Ä_/Ṣ⁼Ø.ƊƝœp;1ÇṾ;”ṭWƊƭ€ṖẎ ṪÇß}v⁼”^$?@ƒ WÇṛ“” ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO1fpALG1A5Bt8HB398Oda8Gi0yBy1g5AAia26lHjPg3NLDj3xLqHO2c/apgb/qhpDVCkzkpRKzEYyD@65@Guvkquo7szHQ7vOzxD43BLvP7DnYseNe45PEPvWNexuUcnF1gbHm5/uHOfNVA50LxwoOhaoClAe4FauYBmH24/PL@2DKgFqCBOxd7h2CSucJAOoH1zgEL/gRrnKOjaKQDZYGccbgcZdWgb1E0gNZr//0craXgAvZqvo1CeX5SToqgZrKTDpaSh6KCsohqnpqWhCRVI1NRI0qwLRuIoIrG1YOxECCNJE8iOgwpqWMUBFWhaxSnFAgA "Jelly – Try It Online") This feels far too long! A full program taking an Underload program as it’s argument and printing the output to STDOUT. In principle, translates the program to a series of Jelly chains and executes them, with special handling for the `^` command. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 87 bytes ``` ≔⪪⮌S¹θWθ≡⊟θ~FE²⊟υ⊞υκ:⊞υ§υ±¹!≔⊟υδ*⊞υ⪫⮌E²⊟υω(⊞υ⭆⊖L⌊ΦEθ…⮌θ⊕λ›№κ)№κ(⊟θa⊞υ⪫()⊟υ^F⪪⮌⊟υ¹⊞θκS⊟υ ``` [Try it online!](https://tio.run/##XZFNT8MwDIbv@xUmJ2cKh3Esp2kIVMTQRO@TotZro2Vpm6YrCMFfL@m6frBIkRL79RO/TpxJG@dSt@26qlRqMCq0cvhBZ7IVYWiK2kXOKpMi5wJWfpf8cdFkShNgyaFqlIszwF1e@CuH70UsKwL2ywI45BZwKwt8ENDla@4Fu7rKsBZw9JheGnjpEF270CT02R3fKZWOcOWLBuWdV1777HkCkjG5nGFec2VGEzcdCGgmIs6Kep@d@oliSycyjhJ8I5O6DLfKqFN9wmelHdkLsxSw@Yo1bTJPHh4rPT80U7m@vPhiSXZlm7w2Do8CGGc@PF2R8cvq2yxnnuWtLYacjW4G1X4Y9///u6q6j7tOvpxPPurY3rTDEffTtigx2PNlxIN9e3/Wfw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪⮌S¹θ ``` Reverse the input and split it into characters so that it can be processed more easily. ``` Wθ≡⊟θ ``` Loop over each character in turn. ``` ~FE²⊟υ⊞υκ ``` If it's a `~` then pop the top two elements from the stack and push them again, swapping them. ``` :⊞υ§υ±¹ ``` If it's a `:` then duplicate the top element of the stack. ``` !≔⊟υδ ``` If it's a `!` then discard the top element of the stack. ``` *⊞υ⪫⮌E²⊟υω ``` If it's a `*` then concatenate the top two elements of the stack. (Annoyingly the elements pop in the wrong order.) ``` (⊞υ⭆⊖L⌊ΦEθ…⮌θ⊕λ›№κ)№κ(⊟θ ``` If it's a `(` then find the shortest unbalanced prefix and push the characters up to the unbalanced `)` to the stack. (The `)` doesn't get removed but unrecognised characters get ignored anyway.) ``` a⊞υ⪫()⊟υ ``` If it's an `a` then wrap the top of the stack in `()`s. ``` ^F⪪⮌⊟υ¹⊞θκ ``` If it's a `^` then push the top of the stack to the input. ``` S⊟υ ``` If it's a `S` then pop and print the top of the stack. ]
[Question] [ Given a string as input, determine whether it is a noun or not. You will be scored on the 1000 most common English words, by how many you correctly label as a noun or not. The program or function which correctly classifies the most of those words in 50 bytes or less will win. # Nouns A noun is a word that represents a thing, typically. It gets more complex, but that's the basic idea. In cases where a word could either be a noun or some other part of speech, I classified it as a noun, even if that's a rare usage. Or actually, I let [this site](http://www.talkenglish.com/vocabulary/top-1500-nouns.aspx) do it for me. The words you'll be scored on are these [1000 common words](https://github.com/isaacg1/words/blob/master/common-words.txt), which are from [simple Wikipedia](https://simple.wikipedia.org/wiki/Wikipedia:List_of_1000_basic_words), with "two" and "once" added. Of those, these are the [586 nouns](https://github.com/isaacg1/words/blob/master/common-nouns.txt), and these are the [414 non-nouns](https://github.com/isaacg1/words/blob/master/common-non-nouns.txt). You can find all three lists [here](https://github.com/isaacg1/words). Note that all of these inputs are in lower case. These lists are final - don't try to argue grammar. Your program will be considered correct if it outputs a [truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) result on an input which is a noun, and a falsy result on an input which is not a noun. **Subtleties:** Programs must have a deterministic output. If you want to use randomness, seed it. Programs are not allowed to use built-in noun lists or other built-in part-of-speech functionality. **Examples:** ``` a: noun act: noun active: noun about: non-noun above: non-noun across: non-noun ``` Please indicate what your program's success rate is in your answer. The program or function of at most 50 bytes with the highest success rate wins. In case of a tie, lowest byte count will determine a winner. Good luck! [Answer] ## JavaScript (ES6), 43 bytes, ~~622~~ ~~630~~ 633 Just to get the ball rolling. Returns `1` for nouns, `0` for non-nouns. ``` s=>2552>>s.length&/^[bcdf-mp-tvwy]/.test(s) ``` ### How? We bet on *noun* if both following conditions are met: 1. The word length is 3, 4, 5, 6, 7, 8 or 11. This is done by right-shifting the binary number 100111111000 (2552 as decimal). 2. The word starts with one of these letters: `bcdfghijklmpqrstvwy` [Answer] # JavaScript (ES6), 50 bytes, score 693 ``` s=>!/^([aouz]|th|..$)|e.+[ey]|[flo].r|a.p/.test(s) ``` Just looking for any possible patterns that non-nouns have that nouns don't. Non-nouns more often contain: 1. **a, o, u,** or **z** as the first letter. 2. **th** as the first two letters. 3. Two letters only. [Think pronouns (me, we, us, he, it) and prepositions (of, to, in, on, by, at, up, ...).] 4. **e**, followed by one or more letters, followed by **e** or **y**. 5. **f, l,** or **o**, followed by any letter, followed by **r**. 6. **a**, followed by any letter, followed by **p**. **Snippet:** ``` var nouns = ['a','act','active','activity','age','air','amount','answer','anything','apple','area','arm','army','art','ask','attack', 'baby','back','bad','bag','ball','bank','base','basket','bath','bear','beautiful','bed','bedroom','beer','bell','big','bird','birth','birthday','bit','bite','black','block','blood','blow','blue','board','boat','body','bone','book','border','bottle','bottom','bowl','box','boy','branch','brave','bread','break','breakfast','bridge','brother','brown','brush','burn','business','bus','buy', 'cake','call','can','candle','cap','car','card','care','carry','case','cat','catch','chair','chance','change','chicken','child','chocolate','choice','city','class','clock','clothes','cloud','coffee','coat','cold','comfortable','common','computer','condition','control','cook','corner','cost','count','country','course','cover','crash','cross','cry','cup','cut', 'dance','dark','daughter','day','dead','deep','desk','dinner','direction','dish','dog','door','double','draw','dream','dress','drink','drive','drop','dust','duty', 'ear','earth','east','eat','education','effect','egg','end','equal','entrance','escape','evening','event','examination','example','exercise','eye', 'face','fact','fail','fall','family','farm','father','fat','fault','fear','feed','feel','female','few','fight','fill','film','finger','finish','fire','fish','fix','floor','flower','fly','fold','food','foot','football','force','form','freedom','friend','front','fruit','fun','funny','future', 'game','garden','gate','general','gift','give','glad','glass','go','god','gold','good','grandfather','grandmother','grass','great','green','ground','group', 'hair','half','hall','hand','hat','hate','head','heavy','heart','height','hello','help','hide','high','hit','hold','hole','holiday','home','hope','horse','hospital','hotel','house','hour','hurry','husband','hurt', 'ice','idea','if','increase','inside','iron','invite','island','it', 'job','join','juice','jump', 'keep','key','kill','kind','king','kitchen','knee','knife', 'ladder','lady','land','laugh','lead','leave','leg','length','lesson','let','letter','library','lie','life','light','lip','list','listen','lock','long','look','love','low','luck', 'machine','main','make','male','man','many','map','mark','market','matter','meal','meat','medicine','meet','member','mention','method','middle','milk','mind','minute','miss','mistake','mix','model','moment','money','month','morning','most','mother','mountain','mouth','move','music', 'name','nation','nature','neck','net','news','newspaper','night','noise','north','nose','nothing','notice','number', 'object','offer','office','oil','one','opposite','orange','order','other','outside','page','pain','paint','pair','paper','parent','park','part','partner','party','pass','past','path','pay','peace','pen','people','period','person','piano','pick','picture','piece','pin','place','plane','plant','plastic','plate','play','plenty','point','police','pool','position','possible','potato','power','present','press','price','private','prize','problem','produce','promise','public','pull','push','put', 'queen','question','quiet', 'radio','rain','raise','reach','read','record','red','remove','rent','repair','repeat','reply','report','rest','restaurant','result','return','rice','rich','ride','ring','rise','road','rock','room','round','rule','run','rush', 'sad','safe','sail','salt','sand','save','school','science','search','seat','second','sell','sentence','serve','sex','shake','shape','share','she','shine','ship','shirt','shoe','shoot','shop','shoulder','show','sick','side','signal','silly','silver','simple','single','sing','sink','sister','size','skill','skin','skirt','sky','sleep','slip','smell','smile','smoke','snow','sock','soft','son','sound','soup','south','space','special','speed','spell','spend','sport','spread','spring','square','stand','star','start','station','stay','steal','step','still','stomach','stop','store','storm','story','street','structure','student','study','stupid','subject','substance','sugar','summer','sun','support','surprise','sweet','swim', 'table','talk','taste','tea','teach','team','tear','telephone','television','tell','tennis','test','thing','tie','title','today','toe','tomorrow','tonight','tool','tooth','top','total','touch','town','train','travel','tree','trouble','trust','try','turn','type', 'uncle','unit','use','usual', 'vegetable','village','voice','visit', 'wait','wake','walk','wash','watch','water','way','wear','weather','wedding','week','weight','welcome','west','wheel','while','white','wife','will','win','wind','window','wine','winter','wish','woman','wonder','word','work','world','worry', 'yard','yesterday','you','young', 'two'], nonNouns=['about','above','across','add','afraid','after','again','ago','agree','all','alone','along','already','always','am','an','and','angry','another','any','anyone','anytime','appear','are','around','arrive','as','at','aunt','autumn','away', 'be','bean','behave','before','begin','behind','below','besides','best','better','between','bleed','boil','born','borrow','both','breathe','bright','bring','build','busy','but','by', 'careful','careless','central','century','certain','chase','cheap','cheese','children','choose','circle','clever','clean','clear','climb','cloth','cloudy','close','coin','collect','colour','comb','compare','come','complete','continue','cool','copper','corn','correct','contain','cupboard', 'dangerous','decide','decrease','deer','depend','destroy','develop','die','different','difficult','dirty','discover','do','down','dry','duck', 'each','early','earn','easy','eight','either','electric','elephant','else','empty','enemy','enjoy','enough','enter','even','ever','every','everyone','exact','everybody','except','excited','expect','expensive','explain','extremely', 'false','famous','far','fast','fever','find','fine','first','fit','five','flag','flat','float','flour','fool','for','foreign','forest','forget','forgive','fork','fox','four','free','freeze','fresh','friendly','from','full','furniture','further', 'gentleman','get','goat','goodbye','grave','gray','grow','gun', 'hammer','happen','happy','hard','have','he','healthy','hear','heaven','hen','her','here','hers','hill','him','his','hobby','hot','how','hundred','hungry', 'i','important','in','into','introduce','invent','is','its', 'jelly','just', 'knock','know', 'lamp','large','last','late','lately','lazy','leaf','learn','left','lend','less','like','lion','little','live','lonely','lose','lot','lower', 'marry','may','me','mean','measure','million','modern','monkey','moon','more','much','must','my', 'narrow','near','nearly','need','needle','neighbour','neither','never','new','next','nice','nine','no','noble','none','nor','not','now', 'obey','ocean','of','off','often','old','on','only','open','or','our','out','over','own', 'pan','pencil','pepper','per','perfect','petrol','photograph','pig','pink','please','pleased','pocket','poison','polite','poor','popular','pour','pretty','prevent','prince','prison','probably','proper','protect','provide','punish','pupil', 'quick','quite', 'rainy','ready','real','really','receive','remember','remind','right','rob','rubber','rude','ruler', 'same','say','scissors','see','seem','send','seven','several','shade','shadow','sharp','sheep','sheet','shelf','short','should','shout','silence','similar','since','sit','six','slow','small','so','soap','some','someone','something','sometimes','soon','sorry','speak','spoon','stamp','steam','stone','strange','strong','successful','such','sudden','suitable','sunny','sure','sword', 'take','tall','taxi','ten','terrible','than','that','the','their','then','there','therefore','these','thick','thin','think','third','this','though','threat','three','tidy','to','together','too','tram','true','twice', 'ugly','under','understand','until','up','useful','usually', 'very', 'want','warm','was','waste','we','weak','were','well','wet','what','when','where','which','who','why','wide','wild','wire','wise','with','without', 'yell','yet','your', 'zero','zoo', 'once']; f= s=>!/^([aouz]|th|..$)|e.+[ey]|[flo].r|a.p/.test(s) //truthy: tnoun = 0; nouns.forEach(s=>tnoun += f(s)); console.log('Nouns: ' + tnoun + ' correct'); //falsy: tnonNoun = 0; nonNouns.forEach(s=>tnonNoun += !f(s)); console.log('Non-nouns: ' + tnonNoun + ' correct'); console.log('Total: ' + (tnoun + tnonNoun) + ' correct'); ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 48 bytes, score 731 This is my first ever answer in Jelly and I went to a lot of trouble putting this together. Ah well ... that was fun. :-) ``` O‘ḅ⁹%⁽€Oæ»4“Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’æ»Ḃ ``` *1 byte saved thanks to @JonathanAllan* [Try it online!](https://tio.run/##AXMAjP9qZWxsef//T@KAmOG4heKBuSXigb3igqxPw6bCuzTigJzhuqAk4rGu4bqK4biy4biyTMORTeG5huG7peKBu@G6ieG5gmDFu3bhuKTDpsmgNeG5rcivxoFVKsOXVGTGsuG4pWDigJnDpsK74biC////YmVk) ### Breakdown and test suites * [Non-nouns](https://tio.run/##PVbLjh01EP2XCDYoS/iLoCyAFUKKu7u62xm33fgxPZ1VJhIg2LECJBZZkKwCKKxmMmKTERF8xr0/MpTP8Y00U@e0r1226@V6LM7td3cPj09/Plx9c7y8/vB4@ffx2auHty/f3nx8fPrr4c3zD46v/zi8@eFw9Zf@Pbj98dPD9beHmxfHy5vDm@8P188e/XNzfrj67fblf88/OVz//u@f7y6/@Oj2p8@Hd7rgxaPj01@qssPVs7vb71T121ef3X9wd/flPdOFku/dr3guFfsYUqpkGKoco7EkWWLFyVgPDJBRsMo5yOCl4QSMYoYdbDM7tC5VQIGHWj9FTPAhz9zA83tvuvye7QK2rmIwI@IzhkIVMVoeHRvgMsUTclmwl@6u0AkEtu9kNuf8HkMkmWz7xUJxJy5swGQHSWQZkGkMJZsIFjkRrAnWAaInRKrQ21VQe@g1wew0ZxLYqivWQUFJOCqc0lXa633H4hpzAu/04nM0rrECG/YSM53TzyYJUMxKlDagu0ThnBA4ZmPvQJyc41pKYKOK/LZLB@Q1FAvcqoQqArcNzkmfyULB0sCVYVnpNmUNVieZ1GfrC2nAlYK6mqsj9cZ40utPVyxrF0ysJhs0iESjodplkF59RaLGTqRQNsgq8Kv6Msewg52rj6uFBouZdhxFzZMbt31x5DFjvk19oI2GALHVswww/1D6MwUx/QyIbid6ANwqzetiW7RLNVi0Pek6G@wtDgeXZcW24mUhPg7EUCZs4hmHeg1PaF84EJBZJBcG9sNQF@A8uehlzSQ2I3rlYqWdK/GJaaXc0eZykaMsgnuNhmcczULLjwiV0SBDxnaUkZmkgLk28ldLCfWjMxMBgy6cEPEzMiI0RSnVgL4xqgpxkhNpCkM8A1xAUg3LVIUnjaQZaDUmeKEYam3STMOGJXqreSXkzVuTGtzJguTgthOPO4UwdHudPEWWFcUdgPyfSl0ym2WBnrnWMt/IDkQkt5I0UxiX550sEujmuUkORk6O1Qea3Q6wQGIodKgic8iQ9TSzFs4Ihytj/bX1f1mDVhBEIPxtfQ6EGDS6Bfyc6QHlNlf5uD5fFQtccuYDEkGxbubMsgLUUUBMUm9LA6x15glAzEhA1jgZMZl520qfs2dYagOm2Jwdv2G7@gRRI0uTw721kMNciz4WOxBSIOBOhUR3L2pE6l7CIJHEnwlWhPYDZxak@sJ7I0W9aRXf02n@VAc834cKOK6vpaBjdPr35cC3vPFCHRdVsbcwvWcS@QDRUUtoY1iEq9LqocN5Q8/bhRGCMiN@Ap4bXCd4HDEwJqGLB2Nr0Coea90KfTqzx0O3SivV7@XICrKKBg1maOQFzYa1mmq1E6SvAaIPAAs0ST3OqqGDvFqDTTjbGtTDmBRwsDWsxRkynHGN@hrvJC02V31TYTIlTUsMnekcp4V21hhyO2sM53w11uItCsNaVtzv62IRzIo4hXZD6E9OjY2ia@D43QsDsVbKpcNOSlkHT4@@nqbK0rXfCzaPxeEzGQRmQoym3qYUkN0JNUzlAoDG1Ep/RfYDaTbQVhGhoCSuQJETZqIbgZr1xIKYqAQDVhMPdkxWkwJGT/Y0whm1xia2SWlhF5gCBBqPxNe@AiO1sjyz5QHX3g53Y2LpTZGfSVu9M2Abz6wiKQs6yJSbOm2C/NQYm85U@l4LBTumxAxNZRhoJnWjYeqk4uHJlvVpCyjB2aC6ZN4lm4taGZkx@tZGy8V5RhooZADHxEYif2NpBrYWU3kiMqqqJRq0T56BpTvP7ZnPc@0bG8F6i@BDddbkklY9csBAhIlyREuVN1aPMiE@tfJjKlCtiiDSbhnBXqqJS2rdZkmlBXXrJzY@DZuJCyBRIi82Cjht48U3gQk3BNtGS220zdZss6kdZmCAxC7MxI3t8GY50SYC@s8KDNGde@zYY2dBeKK9YAUYI9Rw/ep/) correctly identified as non-nouns: 265 / 414 (64%) * [Nouns](https://tio.run/##RVfLriQ5Ef2XFmxGs4S/GDQLYIWQJm@mM9O3bIfbj8quWXW3BAh2rACJxSyYWfEQrPohNlwxgs@o@yN3wudE3ZFKPpEuOxyOt@9dCJenp88fX//x@u5Xj2/e//Dxzb8f3/7184dv/vPxR4@v/3z98NUPHv/59@uH313f/Ut/nz38/ifX97@@fvz68c3H64ffXt@//eK/H8/Xd395@Ob/X/34@v5v//vHt29@/snDH362fKsbvv7i8fWfBrPru7dPD79R1j/99LOnp1@8mF58@mKaG0d/djfCt8sgN0z4MsYoPWFhqofDTLq03adtkDkHLC0OHEvkCCYFu@ppjK1N8yDuprsLwL4WjBvGEACJ/1RHOLkGou0D3FQIvfm1Y4NbOBaRCMpxCdl58PZlIZDLwGWCIL5xxGnBxApyQ1mIB6BjlUzkJhP2ygJGkvinYKeUhWJIa8EZQfnkgGDyCiP2linNOwmY4k7VuRiebrhOFecVv2xcJG3nIUWOBOwVbHrBZ68@uVpJYhynzdPJAaCgeUocl8DZjLFwXAj8pxRur/xsHCH4vNNZFNPsjNhI@PnkEqkAfrvMEqbGf8VzPR1vDhPknc0CinpHm@nYLevqsIPqV1acjquUNt3xFhKjJBK5NyhplrT45m06tSK4Pu01S0m2qpIrfR7Ia0svvLicubJMUPZchCJzWYf@@ti8mC6WqZwAfdspC31voZEX5zIAkbL4REkWX9xs8i4eRy2yYRT8L52XXcp0ANwUiZBnKR6RpHjmMsExHRdcOvTNcNIRceHoYQ6KdUtX6/J8pzpHsnDbkMClIbd72aeAr1bspq6q/4A4u8QMMSjsfDVFn54Z6hczh3vlyuyhWXcZ4zrNBg3gAyAQog8XEMg062QRsE5c3AOQ11I/WQjY6@KEE1c31LV6NQaQnH0AQxWaDH2izlcP719vXyNq10ATKDIjrhSKrrgyaSg0A0tt6qC8mlD4ovIJKU@VrkWgrLV05KW1J44J/HvrEGabIkGTTAKBYNqceg5Msvm1AWD5LcDPNoutTTBgihJvlHhTMy7PKsVXlO@/uLnQOxR5dNEIWYwY/mWJYJ/CSggArNmxdae0O71f4Xwhol7szgyzawIXIvj6Bbv0XwCWUHwFR/AMrF0iJzKBgbtLzb5BP7s0R@z2V4fQnSlu7/XOJO4QijlKJRhFzo@L@TSrJrDZp0rZfIFv@3RmOfE1kAuEvZc7jH6sue9ked/juNyJKeDkxukneuTJY@@JYXTymmih8VNC@jslvw5U27LSKHEBYFsYyWYgtawAVwhuw5i2xn9rhcwBRVZH5qfgtRJBFcFjm51lpgk@Y6zNAIJZyg4CgQMTaxCeiwIaOlbESUsBqmWcoI3IimTxGSfOwecj6lFkBh0AQeNkgkYHe0Y6ZXSLn42z40IX72xhstQTXdvh7tEvrHmaU8CdClfojdPweIVm8iH4oyzwnSiRmU0rDeymCKVGrSU0WmQxeQ4idFJ2Zem2GPqJWqpnxcTIfs6TSjDkk4PqEm6V3FENsubbwTqZaZIwlyZhSk9in7eOTSm6XuqmGrm7Z3IflbUQuUSQe9nYSM5S6ddSrLbfmpzb/fROFgqZHWTmZQc0YgFQ5qyNhc3DvJkZYEC6LUCVysw9meUpsxXMCPXsWC4yXDA7YVXRAzyMrAQ9PPspCRCKVDDNZu/IgaIG46dxdMNGrA0myta6KEIADSYKKXZJTUNkIegwoDZaU8nqWbSztKlBHishWcu2acMKeC7GRwu4HVn8l0RRLpGUlmmbizR91r6AknYkksymMKMnedmZtxWrSfWye3hVmRYvQGhCAew0zaHFs5ZUmxIpJDiaB5spizMjK8GgVALVUVEKJ@oNpl4m21ZZuotrbF7t8go4nG5V6MPFJBNKxLxj7f@tHpUOPRdUUOuLK9bXCcmssrOoE86tTJuVabJqXwrj1VkrMwSpWp8gSuW1qhsNJQhoeRjveWkhFzfyRd2ZPRSzYSFyZL5SzAToqO7CWTYRivxXemDIKTkyaqU3W9RVvyXkw6ol5EJks1q9tVv6ItieCQIZ1GYL4WHVipBiIlCsE7gGlqvKOlCjaUDzKPZG4YUTRaR5qqAlYTBWM1Jlz1AtGWo2owKzmz0vktnDKQb75kbzpZrNLZWwC2lXSv02M2lDMzigEc3vlcJtGmuIImRpdnN9rdHxleIfYnzZvg3k/sJao0S/JZXa@sKAGBSX9ewhT7/lW6WGkLxy3yhmj5GGgOPWnm837SWb3@sznAcefghye/Roa3MCVCSLhmalWfQ2Pg4aO2PtflzemdgHffaVOmlUs3qytr8gEKu34tHQDTTPJ20TtltN@KWFr8DkTW7lqDGMFGBgarIJu7AmnbLx9dos8bTxCMb/BZ2OvtTspaMKpjhQvCWKdkFY9TQHIrot9nW98olydpu7qems9mV1Otvbc9x@7DkmA7jvQXUefOUd9tBVhHkO3PygOhWsAh5uWagqtRG239rZw4WZbelBnR473yXHzrBRhN0O9loH3fCASg62JgOg4INJQ8Gk4evkEPZOh2YmzjNVK5wIwT6hwAvf9xc3Yp@mvEjnSHMf8uKX3wE) correctly identified as nouns: 466 / 586 (79.5%) ### How? We first compute a hash of the input string by: * converting it to an integer by interpreting each code point as a base-256 digit * applying modulo 4080 (chosen as the most efficient value with no more than 12 bits) * keeping the 8 most significant bits of the result This leaves us with an index in [0 ... 255] and thus divides all words into 256 groups. For each group of words, we pre-compute a binary flag which is `1` if the group contains more nouns than non-nouns, and `0` otherwise. This leads to a 256-bit number ***N*** that we're going to use as a lookup-table. We store it as a base-250 encoded string. Below is the binary representation of ***N***. ``` 1000011000001011000101111011111001001101110010101101110010001101 0000010001101010010111110001110010010101110110110010111111010000 0001111010011110000110101011111000011110111011010011011110101100 1010010110101111000010101000101100000001110110100011111000101010 ``` Which can be stored as `“Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’` in Jelly. Hence the code: ``` O‘ḅ⁹%⁽€Oæ»4“Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’æ»Ḃ main link O convert the input string to a list of code points ‘ increment each of them ḅ⁹ convert from base 256 to an integer %⁽€O modulo 4080 æ»4 drop the 4 least significant bits “Ạ$ⱮẊḲḲLÑMṆụ⁻ẉṂ`ŻvḤæɠ5ṭȯƁU*×TdƲḥ`’æ» right shift N by this amount Ḃ test the least significant bit ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 50 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 763 Using a hash now (much like [Arnauld's Jelly answer](https://codegolf.stackexchange.com/a/138810/53748)) ``` OP%⁽Wpị“!ḋGẠ⁻Ṭȥʋt|Ḥ\⁾°½İ@G2ḂƑ½ịʂ¶ɦḲ⁷³Hz~⁵p9)⁹ƙ¿’B¤ ``` **[Try It Online!](https://tio.run/##AXMAjP9qZWxsef//T1Al4oG9V3Dhu4vigJwh4biLR@G6oOKBu@G5rMilyot0fOG4pFzigb7CsMK9xLBARzLhuILGkcK94buLyoLCtsmm4biy4oG3wrNIen7igbVwOSnigbnGmcK/4oCZQsKk////dmVnZXRhYmxl "Jelly - Try It Online")** 250 / 414 for [Non-Nouns](https://tio.run/##PVY9jx01FP0tRKJASkVHh2hCgQQSBQVQeGbuzDjrsQd/7OysEMqmoUhFGYmCIlCliEDAhiggPVAE@Rf7/shyfY5finfPGT/72r5fvvfFuf329uNP3j5evfxsvXnx6Pjg@7durh/du/njh@PVi5vnT//98fWj/PXN9ZMvjld/Hp4dXv7z7P17795cP3z13eGlLnj98PDbfz/dXP98vPr98MuHl98cr35d33vnePX81ePDX8cHjz84PLn9@9vjw6eHp5/e/ej29vM7pgsl37lb8Vwq9jGkVMkwVDlGY0myxIqTsR4YIKNglXOQwUvDCRjFDDvYZnZoXaqAAg@1foqY4EOeuYHn9950@T3bBWxdxWBGxGcMhSpitDw6NsBliifksmAv3V2hEwhs38lszvk9hkgy2faPheJOXNiAyQ6SyDIg0xhKNhEsciJYE6wDRE@IVKG3q6D20GuC2WnOJLBVV6yDgpJwVDilq7TX@47FNeYE3unF52hcYwU27CVmOqefTRKgmJUobUB3icI5IXDMxt6BODnHtZTARhX5bZcOyGsoFrhVCVUEbhuckz6ThYKlgSvDstJtyhqsTjKpz9YX0oArBXU1V0fqjfGk15@uWNYumFhNNmgQiUZDtcsgvfqKRI2dSKFskFXgV/VljmEHO1cfVwsNFjPtOIqaJzdu@@LIY8Z8m/pAGw0BYqtnGWD@ofRnCmL6GRDdTvQAuFWa18W2aJdqsGh70nU22FscDi7Lim3Fy0K8H4ihTNjEMw71Gp7QvnAgILNILgzsh6EuwHly0cuaSWxG9MrFSjtX4hPTSrmjzeUiR1kE9xoNzziahZYfESqjQYaM7SgjM0kBc23kv5YS6kdnJgIGXTgh4mdkRGiKUqoBfWNUFeIkJ9IUhngGuICkGpapCpeNpBloNSZ4oRhqbdJMw4Yleqt5JeTNW5Ma3MmC5OC2E487hTB0e508RZYVxR2A/J9KXTKbZYGeudYy38gORCS3kjRTGJfnnSwS6Oa5SQ5GTo7VB5rdDrBAYih0qCJzyJD1NLMWzgiHK2P9tfW3rEErCCIQ/rY@B0IMGt0Cfs70gHKbq7xfH66KBS458wGJoFg3c2ZZAeooICapt6UB1jpzCRAzEpA1TkZMZt620ufsGZbagCk2Z8dv2K4@QdTI0uRwby3kMNeij8UOhBQIuFMh0d2LGpG6lzBIJPFnghWh/cGZBam@8N5IUW9axfd0mj/VAc/3oQKO62sp6Bid/k058C1vvFDHRVXsLUzvmUQ@QHTUEtoYFuGqtHrocN7Q83ZhhKDMiJ@A5wbXCR5HDIxJ6OLB2Bq0isdat0Kfzuzx0K3SSvUbObKCrKJBgxkaeUGzYa2mWu0E6WuA6APAAk1Sj7Nq6CCv1mATzrYG9TAmBRxsDWtxhgxnXKO@xjtJi81V31SYTEnTEkNnOsdpoZ01htzOGsM5X421eIvCsJYV9/uqWASzIk6h3RD6k1Njo@gaOH73wkCslXLpsJNS1sHTo6@nqbJ07f@CzWNx@EwGgZkQo6m3KQVkd0INU7kAoDG10l@R/UCaDbRVRCgoiStQ5ISZ6EagZj2xICYqwYDVxIMdk9WkgNGTPY1wRq2xiW1SWtgFpgCBxiPxta/ASK0sz2x5wLW3w92YWHpT5GfSVu8M2MYzq0jKgg4y5aZOmyA/NcamM5W@10LBjikxQ1MZBppJ3WiYOql4eLJlfdoCSnA2qC6Zd8nmolZGZoy@tdFycZ6RBgoZwDGxkcj/WJqBrcVUnoiMqmqJBu2TZ2DpznN75vNc@8ZGsN4i@FCdNbmkVY8cMBBhohzRUuWN1aNMiE@t/JgKVKsiiLRbRrCXauKSWrdZUmlB3fqJjU/DZuICSJTIi40CTtt48U1gwg3BttFSG22zNdtsaocZGCCxCzNxYzu8WU60iYD@swJDdOceO/bYWRAutResAGOEGq5f/g8 "Jelly - Try It Online") 513 / 586 for [Nouns](https://tio.run/##RVc9jy43Ff4tXIkiUio6uogmFEggUVAAxeyMZ8b72j6@/njnvlGEsrehuBVlJAqKQJUiAgE3RDdIC4og/2L3j2yOn@e8m8bPGY99fHy@fetCuDw9/fwXP3y8e/er/PDVm8dP/viDh7dvPnz4158e7756@PLz//352zft44e3n/3m8e7r@y/u3/33iw8@/NHD29ff/OH@nW749vX9P/7/l4e3f328@@f933760e8e7/6ef/ze492X33x6/@/HTz79yf1nT//5/ePrz3/5/s@enn79Ynrx/otpbhz92V0J3y6D3DDhyxij9ISFqR4OM@nSdp@2QeYcsLQ4cCyRI5gU7KqnMbY2zYO4mW4uAPtaMG4YQwAk/qmOcHINRNsHuKkQevNrxwa3cCwiEZTjErLz4O3LQiCXgcsEQXzjiNOCiRXkirIQD0DHKpnITSbslQWMJPGnYKeUhWJIa8EZQfnkgGDyCiP2linNOwmY4kbVuRierrhOFecVv2xcJG3nIUWOBOwVbHrBZ68@uVpJYhynzdPJAaCgeUocl8DZjLFwXAj8Uwq3V342jhB83uksiml2Rmwk/HxyiVQAv11mCVPjX/FcT8ebwwR5Z7OAot7RZjp2y7o67KD6lRWn4yqlTTe8hcQoiUTuDUqaJS2@eZtOrQiuT3vNUpKtquRKnwfy2tILLy5nriwTlD0Xochc1qG/PjYvpotlKidA33bKQt9baOTFuQxApCw@UZLFFzebvIvHUYtsGAX/pfOyS5kOgJsiEfIsxSOSFM9cJjim44JLh74ZTjoiLhw9zEGxbulqXZ7vVOdIFm4bErg05HYv@xTw1Yrd1FX1HxBnl5ghBoWdr6bo0zND/WLmcK9cmT006y5jXKfZoAF8AARC9OECAplmnSwC1omLewDyWuonCwF7XZxw4uqGulavxgCSsw9gqEKToU/U@erh/ev1a0TtGmgCRWbElULRFVcmDYVmYKlNHZRXEwpfVD4h5anStQiUtZaOvLT2xDGBf28dwmxTJGiSSSAQTJtTz4FJNr82ACy/BfjZZrG1CQZMUeKNEm9qxuVZpfiK8v0XNxd6hyKPLhohixHDvywR7FNYCQGANTu27pR2p/crnC9E1IvdmWF2TeBCBF@/YJf@BWAJxVdwBM/A2iVyIhMYuLvU7Bv0s0tzxG6/OoTuTHF7rzcmcYdQzFEqwShyflzMp1k1gc0@VcrmC3zbpzPLia@BXCDsrdxg9GPNbSfL2x7H5U5MASc3Tj/RI08ee08Mo5PXRAuNnxLS3yn5daDalpVGiQsA28JINgOpZQW4QnAbxrQ1/q0VMgcUWR2Zn4LXSgRVBI9tdpaZJviMsTYDCGYpOwgEDkysQXguCmjoWBEnLQWolnGCNiIrksVnnDgHn4@oR5EZdAAEjZMJGh3sGemU0S1@Ns6OC128sYXJUk90bYe7R7@w5mlOAXcqXKE3TsPjFZrJh@CPssB3okRmNq00sJsilBq1ltBokcXkOYjQSdmVpdti6CdqqZ4VEyP7OU8qwZBPDqpLuFVyRzXImm8H62SmScJcmoQpPYl9Xjs2peh6qZtq5OaWyX1U1kLkEkHuZWMjOUulX0ux2n5tcq730ztZKGR2kJmXHdCIBUCZszYWNg/zZmaAAem6AFUqM/dklqfMVjAj1LNjuchwweyEVUUP8DCyEvTw7KckQChSwTSbvSMHihqMn8bRFRuxNpgoW@uiCAE0mCik2CU1DZGFoMOA2mhNJatn0c7SpgZ5rIRkLdumDSvguRgfLeB2ZPEfEUW5RFJapm0u0vRZ@wJK2pFIMpvCjJ7kZWfeVqwm1cvu4VVlWrwAoQkFsNM0hxbPWlJtSqSQ4GgebKYszoysBINSCVRHRSmcqFeYeplsW2XpLq6xebXLK@BwulWhDxeTTCgR8461/9d6VDr0XFBBrS@uWF8nJLPKzqJOOLcybVamyap9KYxXZ63MEKRqfYIoldeqbjSUIKDlYbznpYVc3MgXdWf2UMyGhciR@UoxE6Cjugtn2UQo8q/0wJBTcmTUSm@2qKt@S8iHVUvIhchmtXprt/RFsD0TBDKozRbCw6oVIcVEoFgncA0sV5V1oEbTgOZR7I3CCyeKSPNUQUvCYKxmpMqeoVoy1GxGBWY3e14ks4dTDPbNjeZLNZtbKmEX0q6U@m1m0oZmcEAjmt8rhds01hBFyNLs5vpao@MrxR9ifNm@DeT@wlqjRL8mldr6woAYFJf17CFPv@ZbpYaQvHLfKGaPkYaA49aerzftJZvf6zOcBx5@CHJ99GhrcwJUJIuGZqVZ9DY@Dho7Y@1@XN6Z2Ad99pU6aVSzerK2vyAQq9fi0dANNM8nbRO2W034pYWvwORNruWoMYwUYGBqsgm7sCadsvH12izxtPEIxv@CTkdfavbSUQVTHCjeEkW7IKx6mgMR3Rb7ul75RDm7zV3VdFb7sjqd7e05bj/2HJMB3PegOg@@8g576CrCPAduflCdClYBD7csVJXaCNuv7ezhwsy29KBOj53vkmNn2CjCbgd7rYNueEAlB1uTAVDwwaShYNLwdXIIe6dDMxPnmaoVToRgn1Dghe/7ixuxT1NepHOkuQ958dvvAA "Jelly - Try It Online") Total = 250 + 513 = 763. ### How? Builds a table with 308 entries, either 1 (identifying a noun) or 0 (identifying a non noun) and indexes into it using a key provided by a hash function that utilises the product of the ordinals of the input word: ``` OP%⁽Wpị“!ḋGẠ⁻Ṭȥʋt|Ḥ\⁾°½İ@G2ḂƑ½ịʂ¶ɦḲ⁷³Hz~⁵p9)⁹ƙ¿’B¤ - Link: list of characters, word O - convert to ordinals P - product ⁽Wp - base 250 number = 22863 % - modulo (by 22863) ¤ - nilad plus link(s) as a nilad: “!ḋGẠ⁻Ṭȥʋt|Ḥ\⁾°½İ@G2ḂƑ½ịʂ¶ɦḲ⁷³Hz~⁵p9)⁹ƙ¿’ - base 250 number B - as a binary list (308 bits) ị - index into (1-indexed and modular, - so adds another modulo by 308) ``` --- ### Previous: ~~50~~ 47 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 684 ``` ḣ3Ẇf“QṘ°ḂżÐŒ#ḍæ09»s2¤Ȧ¬ȧØY⁾niyṖf⁽ż2ị$ 0,-2ịE¬ȧÇ ``` A monadic link taking a word and returning a list of one character (truthy) if the word is identified as a noun, or an empty list or zero (both falsey) if it is not. **[Try it online!](https://tio.run/##y0rNyan8///hjsXGD3e1pT1qmBP4cOeMQxse7mg6uufwhKOTlB/u6D28zMDy0O5io0NLTiw7tObE8sMzIh817svLrHy4c1rao8a9R/cYPdzdrcJloKMLYriC1bT/Bxrml1@a96hhLpiVpwvlHW63//8/MbkksyyzpBIA "Jelly – Try It Online")** (the footer performs an if else on the result to print `Noun` or `Non-Noun`) ...or see the [scoring program](https://tio.run/##XZg/r@ZGFcZ7fwokUm5E2FR8ADoalAKlQmN7bM99xzPOzPj6vlslEWILBIpSoBTQJGgpSEEBaDcJFLsK2q9x94ssv@f4UoD0@pl5bc/MmTPnz3N842O8vn17//yr9@@/@fX05uM//Pz@xRcv/3r//NPvv3v12fef//D@@W9fPXvvJy@/rY9f/un1s5dfv/7zqy8@fPPJv1K43r/4/fTmk39@/93j@29/80733qN31fmpvfP07aunbz79mt/rZ2f7AVd3/@3f7l989eaTf/zi5Z9e/v1n3GKSR6@e/vJHH7z932f3z7989fT1s3defTZ1r57ev/gL7777@MOue/zofVbxyLoIosAXQXrz8R/PxbsfP3r88NLLL9@5f/H0/pvf3T//1b8/P/fx8NL/Cez6vLcOvPWdG0qutXPj2LmpuKCm@dK52YUEZq7ieS9Grpy84QwW78Yr7eGujF87x@uJ4Wku3E65LZomqX@1cenawkq7bd7xpNAtedeQUoJEYRrE2pOg7SvzMXfXe35M3vvF3ao/5aJmDnYvMEHvYz7AGkZf1TagaRs0h/e8GL3nvRwiUJKgaAhSdj07QVjaMC9NDfvr9xAZsFcEQFn9tRuQeNqjtdGjs8GnVly0dmfPgy9NShsWVz3o3Sb09ofZiteznPU/lCHSRH@LkDTsT6h@WHtQgoE7KqbRkKypc4x@aGrzzstZ7@Z1kzJpDbbomzqphbSrkxExo3S9XzRHKecc6RR33/rsytiNHJ3nRGo3@gFNqkE1VR0Gj37z6BoNt5KvtLdofevGwPMwTZ7tNeuFYY/qlcZboQ5ZexwzvyN1I4oa9@HSeTcsQIlXYQJQtbcT8MFsx2urJQzqbItjdh8Rxq8bE/vkV@FNFuZ9ZrKkE0es1JlaBdcTZX/@zrFr@9tn1OrvBr81NaFhG/5uk1bUpCpzpBelH3/Xil89ck5O609ulY4mDmtyWNpki02yQ4Dnoehu0MU0U3SzgL8xn8jJTToVDFkXm07Walgusz8bG5zLBbjj0iA5ouCJNXUBA2ci0UpeO6yTSfeSAvbo1TM9zigm@hUT09SzhJhzHvur7@YilwKvAP4w76lb3LoyapGfJmuuIPZh7rfo52JbrmqLQApf7NLfohdK7bD4CKxc/Mk9HrTkxnV0C05fUDmtYkXowrplfIcTRt8htSwoGTvx9G5lWEwSWu1uFMe7mx1VXVLGjMCji27dAFQH8ghtewPeje4J4N0kwM6in3hBlmxOHMOFV0PmQWioiYZdKtBprBwPV@Q62NxKoLqCXJ4fCgWqVL2yWc2x5tEXNenieSvbLT3fMfZVUmO0yVnsSVJfOj0gKToJECDJCXqdd3pwhGQWlrzG3LUuBdSSZGop8@s1Jts/XkJYaST3rJ8HyZgnfroaZ5QJagiVE4tmnS9jtJQSgvmpfHRjFM8GguXmLXA8XJM8ZPMcDU84zYzlbEu3hZkrXTpCj8LF2YzdxgFhcVsOlTW3jIZ5mFlyy9vOedGy9laI1Vc1dtIb8ZcN0tioknvXRz3OJkXJzaQo@VYxattTwBG2fUPaj/aASYCsQy4j95xJCowGUf3B64jl02vPjHTku2fwZ7Wu7L3d35m@7JFudRx45dzrEGrNWHfFE7lWgLHVgo5Q@aAujpFCDoKmbKD3JzZhnEAsXrhzImr4EzBLdl4D5oRyajj/6cldV5Xi6qo8XDM/kktVxBfo9NW2RanLemRapJQBIi9WW0m6F9DuNPlLbZ6sXZsNJpER/NUqudd9GHAOZbsqy637OGqDKNbJ3Oqe0K1Zfj0yoaE5vKhJtubuQidLIxaXoJcboVvQOiVZrlCEuqdgYWgpnV4V6gy1EwPragWFkbZYoG@LMrY1vB84YCIGxujNW1rmT2FrrZD@2iFv2WdOnqjDY0M0wLHBNDCafev2apl9r7uZiOWNQ@HocGUFqi5s6tAPNR4S/CAUAbykvR3a0WE7OtjBAmYu5pGVHiITR9DDUAVkd4GO/ap5rsxzlTM8IQN3T9hC1uH/oHOdshaXMSQ1AV9xnJVDj0pFokupHifZOi2AmB3Frjyj2QAXQzA3Vy9QrOZQME4Fszl78BxyVK/j613SHWQE5Ly9E0NSqAL2FqSnXlTKjyWTc3pvLEtDiQK9jgrQGOEo/oYB9/LIPtpyMZ@YRyEcLHJMJwPplZssOfeyyj7ni5iajg2mpuisRqvmQ0Tujot3sd1BNM7ooTze8HKi5Wg43Tjr4clKaQlzfdmJHP0uOrjjbEoHdLhE9jDoQRoZRM2wFtE1ETpxNMk6GOeyjDAY30N0LgSB/3E0oE5QzWwEkFiYTiIoFgiDU5KiJ/scdKgDuauK7aEfI4C@nhQQqga/EpVzRv10Y52UMeVf9Mk3xvz2ZiQvjaEFu5UsVA/So7ifPa2aQ1ZjKPGxOyOYxkWLQylnUTDoIe4xYKWj7WZ08JHR4YRaSac7St2johvEkGchaRXIH0FaMoyKzmOeubJY4C6Rx@IOQPEHZKWxyNNHKwOwKyZTrhz3ZuRQVxNZ5J4c30MMnM3uJ0tJfp47xWH/EQ7cGS2XtL5yYt4YobziTC/QQOL9w3D68hR/58sgx/RX8bvBABbmCA@TjADOF4wA4k2TMxuaxOWcmO4kESdlcIB3oVrMOZGuJ8spk5gQsIofzidXlFYmxYPp7N2JF4oOnkxj0mI66EluAjQDc1EOfjBmuBoXHEX8jAaKBLLBqezinjC5ycL0tBsbnJXDZiwXK5xletBCS1dzgBAZ25wjZzmbFVL3zaw8SwaRRXHEND5s3fpr/m9fr1tAVqGYRCRV1KnZOnOFxZHwFsm@KOwqXC6SYJHtiECeXJK7J/8nQcYsZLyi58JdQOQRcQAvCDK/RSlwgRkAMuIl140kFcU1vXC3mwTWZZerLnvtTQa4cSfPY37XhQma@VDrhKQqsgvoUtxTgSvUqDEIcAM9uFEhdrNr8M1OHr3I@EX3Ljrni7jEReZ2CQQD9HGB1wFhEiUdFcuiOIlNGeVKIqZiowpf0c8ip3NbjJ6KlnrRVStmYyDGsYkYRFM1n6krBshvEO0FWNACiBXpUY4fsxFaWLLKrpWyS9RxVWmzKsqZtao6WFWsr8S4VV4uYOnV2dKrGNSqQ179GAabQWTmgUOteJbxX1IwxrKGUfESn2EeKQQgNtFgK4DRhRWjF19m3qzxYs1GmhObhzWbz64KVw@mZrnOxCZt6pVbEetKgZhk2w8@TSNzT57NJiSENleDzYk/JlNZyvJ2CDPzpGzdM3PSGrvebVu5v1F4UfQtQj3SJwQlJyrqXGUd@aROZ5o6JUU@M6JNeXqTyIImhMGaHCrZ7Q6q3mT7gnQ@EBmWV20KeJsS8IapQ@BEi724eVbUYpqAsmmMKAdHObCJPAGmgy14jdDy0cZicyc2YWWrapvdu4q2Jy2dTVQcbDC2DtXXRoNR@FqN0225OTjXZsEK4l5P4q5QDm8/2futTVzCE28kngpUrdV0tKsOYCMbSAbVrdtuNL5B3xVFwGprwuY5xeLGkI3TC6rou74fWLIn1YiDqqKEy2fj9ohTvKmbRmZLY@RfhWZnpbbA7cXZq1WBnDpEZMA2UMThig7RPgcVWzNrNXmXUZ8zzqlCABimDVTeqG5StYCdVAplQBWCnLvq609UEXHyfGKeyLXEq15pm0b0Xh8yzheKRvk7VREXKyk2Q/HuRZf8EFRpEc5yQv@VLsDtobxQAaOyu8o2zC5rmJMKlSC2CyrxU3XIqOBB80Mj0IDa7DHnWC3EgUmgBS@Mj1bbKArV1eTH73l3zRJZxWiVyioFaFetHpHaqrJDNUfGM7XZzQ9BQm3KpGC0vl61M6ubHXbd7DwqmV5aMB4PFoMmNKuhvVqFE4UqdkxyuKPMhla3ss2gRCrU@8UKNAqH04FqowZMzVo9pshktf2MCrRaXqLvswTY7bsJtRHXdsq8l80sB3quiY9AVWKkjRRFZWNFBULqQiwryJrYRLNPXgoz6t2Gqj01qQTLSKqEZMFnyGpBRZDIcctKiS2rt54fOKnuLOA1GR6AurX3lpUjW1Zx18SFm7lWE4XmvtVV5eRqKENLoR5zjnbFBPekr5dU3k2l01k3UTVRgNnmbtG1It@tcVtJr0rKAJM4tPVDLPMwugyiNn3pPbT1w58k4/DjqO2hORVctgtKLvvKeWj3FFvISrEVreRSeaaceOigDzZzKPEIUMMhRwFsJTGuIyvjHdlKQithD31qA6J12e5VLP/qZf1SK9WZLin8yP8B "Jelly – Try It Online") (counts up truthy indexes across the two lists and then calculates the score). Score breakdown: 462 / 586 nouns correctly identified (124 incorrect), 222 / 414 non-nouns correctly identified (192 incorrect) -- total correct = 684 / 1000. ### How? Guess it is not a noun if... * the last character and the character two before that are equal (with modular and 1-based indexing) * either of the first two length 2 substrings are in: `'be', 'th', 'le', 'he', 'm ', 'ev', 'et', 's ', 'fl', 'ax', 'en', 'fo', 'am', 'az'` (note: `'m '` and `'s '` are only here to ease compression, but they never appear anyway) * The -299th index (with modular and 1-based indexing) is any of: `aenouyz` (although this is implemented inversely and with excess capital letters) ...since the words all have length between 1 and 11 the -299th index is equivalent to using the length to index mapping: `{7:2; 8:5; 9:7; 11:9; else 1}` ``` ḣ3Ẇf“QṘ°ḂżÐŒ#ḍæ09»s2¤Ȧ¬ȧØY⁾niyṖf⁽ż2ị$ - Link 1: list of characters, word ḣ3 - head to index 3 (1st 3 characters, like 'abc') Ẇ - all sublists (['a','b','c','ab','bc','abc'] ¤ - nilad followed by link(s) as a nilad: “QṘ°ḂżÐŒ#ḍæ09» - compression of "bethlehem evets flaxenfoamaz" s2 - split into chunks of 2: - be,th,le,he,m ,ev,et,s ,fl,ax,en,fo,am,az f - filter keep (can only match 'ab' or 'bc') Ȧ - any and all (0 if empty, 1 if not) ¬ - logical not ØY - consonant -y yield = "BCD...WXZbcd...wxz" ⁾ni - character pair = "ni" (no shrubbery for you!) y - translate (exchange the n for an i) Ṗ - pop (remove the z) ȧ - logical and $ - last two links as a monad: ⁽ż2 - base 250 literal = -299 ị - index into the word f - filter keep 0,-2ịE¬ȧÇ - Main link: list of characters, word 0,-2 - pair zero with -2 = [0,-2] ị - index into the word (last character and the one before the one before that) E - all (both) equal? ¬ - logical not Ç - call the last link (1) as a monad ȧ - logical and ``` --- 13 bytes, score: 638 A first quick bash (extended above) ``` ØY⁾niyṖf⁽ż2ị$ ``` [Answer] # Julia 34bytes, 609 `f(w)=hash(w)&0x0800000000004808>0` I wanted to save on characters by using the in-built hash. I feel like there must be a way to do this better. Julia is just not friendly enough with the bit-banging operations I want to use to make this better I think. Finding suitable bitmasks for the hash to separate them, is an interesting game. [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes, accuracy: 596 ``` lambda x:2<len(x)<7 or x[0]in"abcgmprs"or"st" in x ``` [Try it online!](https://tio.run/##BcExDoAgDADArzSdYDMsJgZfog5FRUmgkMKAr8e78rU3sxl@3Uek5C6Cvhgbb1Zd2xmyQN@mIzCSO59UpGIWrA0hMPRRJHADr5AkoR4/) Simply checks first letter, length, and whether "st" is in the word Code assumes that word is defined as x (Edit: Thanks to issacg for fixing code from snippet to function) [Answer] ## Haskell, 36 bytes, ~~626~~ 631 ``` f x=length x>2&&x!!0`notElem`"aenou" ``` [Answer] # Python 3, 50 bytes, score 602 Python isn't the most verbose language, but 50 bytes is tough. ``` lambda x:all(x.count(y)<1for y in["ful","y","er"]) ``` ]
[Question] [ ## COMPLETE Wumpus season has ended, and with, the lives of many a vicious Wumpus and brave Hunter. As well as some cowardly, immoral and downright stupid Hunters. But at the end of the day, NascarHunter by Dr Heckle came away with the most loot and glory. We salute you, oh brave... driver? It's open season on Wumpuses, and hunters from around the world are flocking to the Wumpus Caves to try to get rich of off valuable Wumpus Pelts. # The Game Based on the classic [Hunt the Wumpus](http://en.wikipedia.org/wiki/Hunt_the_Wumpus) game, with a few variations. ## The Map A [dodecahedron](http://en.wikipedia.org/wiki/Dodecahedron#/media/File:Dodecahedron_schlegel_diagram.png). There are 20 rooms, each connected to 3 other room, making basically 3 rings with bridges in between. ## The Wumpus The Wumpus is a mystical beast. None are sure what it looks like, but all agree that it is ferocious. The Wumpus lives in the caves, and likes to eat dead things. If there is a corpse in a cave next to the Wumpus, he will move there and eat it. If the Wumpus happens to move into a cave containing hunters, he will kill and eat them as well. If the Wumpus hears an arrow near him, he will panic and run into a random room. **Optional traits**: These are currently included to make the game more interesting, but can be removed at popular request if they add too much randomness. Enraged Wumpus: If the Wumpus is shot, he has a 20% of surviving and rampaging for 3 days. When rampaging, he will randomly move twice a day, but still be attracted to corpses. After 3 days, he will die. A second arrow shot will also kill the Wumpus. Wandering Wumpus: Each day, if nothing else triggers the Wumpus, he has a 25% chance of moving. ## The Hunters Four hunters can enter the caves at a time. The caves are dark, so the hunters cannot see, but they can use their other senses. Hunters can smell the Wumpus in an adjacent room, smell a corpse in an adjacent room, hear other hunters moving in adjacent rooms, and hear if an arrow is shot into an adjacent room. Hunters have two actions: Shoot or move. A hunter can shoot an arrow into an adjacent room or his own room, and move similarly. ## Gameplay In each round, hunters will first take note of their surroundings, and then make one move. Movement occurs before arrows, so if an arrow is shot into a room that a hunter is moving out of, the hunter will survive. After all hunter moves have been made, the arrows are evaluated. If a single occupant and arrow are in the same room, the occupant will be shot and die. If two or more occupants share a room, one will randomly be hit and die. Note: Corpses are occupants, so a dead body may serve as a partial shield. After all hunter moves, the Wumpus will respond. If a hunter has moved into the room with the Wumpus, the Wumpus will eat him/her. If the Wumpus moves, it will also eat the occupants of the new room. After 100 days, if the hunters have not killed the Wumpus, or fallen victim, they will die of starvation within the caves. # The Code All source code can be found [here](https://github.com/Cain93/WumpusHunters). All submissions should be in Java, unless somebody wants to write me a stdIn/stdOut adaptor ;) Bots should extend the Hunter class. To name your Hunter, add a constructor with no parameters that sets the name field. T o respond, override the getResponse function. In this function, each turn, you will be passed an array of 5 booleans that tells you about your surroundings. status 0 = "You smell a wumpus" status 1 = "You hear another hunter" status 2 = "You smell a corpse" status 3 = "You hear an arrow clatter" status 4 = "You feel another hunter in the same room as you" The Hunter class has 2 slots: nextMove and nextDirection, that use the enums Move and Direction respectively. Move can either be MOVE or SHOOT, direection can be LEFT, RIGHT, BACK, or HERE. Directions are consistent, meaning back will always return you to the previous room you were in, and if entering from the same room, LEFT and RIGHT will always be the same. However, if you enter from a different direction, LEFT and RIGHT will take you to different places. Feel free to implement your own methods as well. Memory is persistent throughout the whole tournament, meaning your hunter will only be constructed once. However, at the start of each round, the newGame() method is called to let your hunter know a new game has started. ## Scoring Four hunters compete at a time. If killed, the Wumpus pelt is worth 60 points, split evenly among all surviving hunters. Full round robin style, so each combination of 4 hunters will play together. 5 sample Hunters are included: 4 with very basic functionality, and one that allows user input to play, for testing purposes. If you have any suggestions/requests, please let me know! # The End is in sight! The worlds Wumpus population is being hunted at an alarming rate. The Protect Our Wumpuses Act is expected to be passed on Wednesday, June 17th. After this date, no more hunters will be allowed in the caves, and a winner will be chosen. # Scoreboard *Note :* My apologies, there was a bug in the code that could cause Hunters to stay dead through multiple games. Having fixed it, it does not change the overall rankings very much, but does largely change the stats. Scores are in, running each set of hunter in 1000 games each. NascarHunter and FullCoverageHunter lead the pack, and although the addition of AntiHunter has given the Wumpuses a 2% survival boost, they are still shaking in their suckered feet at the 32% survival rate of their kind. Arrows from fellow hunters are more than ever the biggest threat in the caves. ``` 1. NascarHunter : 16557175 (17.08) 2. FullCoverageHunter : 15195545 (15.68) 3. Trig : 14459385 (14.92) 4. Idomeneus : 13428570 (13.85) 5. Eats Shoots and Leaves : 12763945 (13.17) 6. WalkingIdiot : 12329610 (12.72) 7. NealHunter : 12287140 (12.68) 8. Unnamed : 11013720 (11.36) 9. MonsterHunter : 10686035 (11.02) 10. Pacer : 9187000 (9.48) 11. Badger : 9042570 (9.33) 12. Stay : 8721210 (9.0) 13. Emo Wumpus : 7831050 (8.08) 14. Paranoid : 7722965 (7.97) 15. Huddle : 7465420 (7.7) 16. ElmerFudd : 7245995 (7.47) 17. Laomedon : 6963845 (7.18) 18. Pacifist : 6944960 (7.16) 19. ScaredyCat : 6937370 (7.15) 20. Wumpus : 114170 (0.11) Total rounds: 4845000 Humans killed by arrows: 5289674 (1.09) Humans dead by starvation: 1046024 (0.21) Humans killed by wumpus: 1887634 (0.38) Wumpus victories: 1563372 (0.32) ``` [Answer] ## NascarHunter Not much logic to it. Its rules are simple: turn left, scorched earth, repeat. And, hey, he might get lucky! **8 June edit:** Added in additional logic to Nascar to account of adjacency to a Wumpus relative to its last move. Consider it a pit stop, to stay in theme. If it sense a Wumpus after shooting down a hallway, then it must have arrived in one of the other two adjacent rooms, since it would've died to the shot the hunter just took. It effectively give either the Wumpus 2 turns to live if it doesn't move again, or Nascar 1 turn to live if he's standing on a corpse. Also accounts for a third option if it's the first turn, but just the once. I'll port to to FCH eventually, busy busy. ``` package Hunters; import Mechanics.*; public class NascarHunter extends Hunter { private int state; private boolean shootHall; private boolean newGame; public NascarHunter(){ name = "NascarHunter"; state = 0; shootHall = true; newGame = true; } public void newGame(){ state = 0; newGame = true; } public void getResponse(boolean[] status){ // Wumpus about - stand and deliver if( status[0] ){ nextMove = Move.SHOOT; switch( state ){ case 0: // Must be in either Right or Back if(newGame){ // try Left if this is the first turn, just in case nextDirection = Direction.LEFT; newGame = false; } else if(shootHall) nextDirection = Direction.BACK; else nextDirection = Direction.RIGHT; shootHall = !shootHall; break; case 2: // Must be in either Left or Back if(newGame){ // try Right if this is the first turn, just in case nextDirection = Direction.RIGHT; newGame = false; } else if(shootHall) nextDirection = Direction.BACK; else nextDirection = Direction.LEFT; shootHall = !shootHall; break; default: // Must be in either Left or Right if(newGame){ // try Back if this is the first turn, just in case nextDirection = Direction.BACK; newGame = false; } else if(shootHall) nextDirection = Direction.RIGHT; else nextDirection = Direction.LEFT; shootHall = !shootHall; break; } }else{ // disregard state, shove out and light 'em up! switch( state ){ case 0: // move out nextMove = Move.MOVE; nextDirection = Direction.LEFT; state++; break; case 1: // shoot right nextMove = Move.SHOOT; nextDirection = Direction.RIGHT; state++; break; case 2: // shoot behind nextMove = Move.SHOOT; nextDirection = Direction.BACK; state++; break; case 3: // shoot left nextMove = Move.SHOOT; nextDirection = Direction.LEFT; state = 0; break; } } } } ``` ## FullCoverageHunter Follows the same credo of the NascarHunter, but alternates his pathing, which is guaranteed to form a loop 10 unique rooms long. Since every room is unique, and we fire at every direction per room, all rooms get fired into. This is true for any starting room (postulated by my buddy Neal, thanks Neal!). Dodecahedra are pretty cool like that! I'd like to point out that this is is different than our friend, the MonsterHunter, as he doesn't try any trickery or any real "tactics." The strength of this is the fact that every room gets fired into, again: the brute force solution. This has a theoretical leg up on the NascarHunter, since Nascar will only hit 10 of the 20 rooms, covering only half the area. **11 June edit:** Added in Wumpus detection logic pattern from NascarHunter. Should objectively improve score. ``` package Hunters; import Mechanics.*; public class FullCoverageHunter extends Hunter { private int state; private boolean headLeft; private boolean shootHall; private boolean newGame; public FullCoverageHunter(){ name = "FullCoverageHunter"; state = 0; headLeft = false; shootHall = true; } public void newGame() { state = 0; headLeft = false; newGame = true; } public void getResponse(boolean[] status){ // Wumpus about - stand and deliver if( status[0] ){ nextMove = Move.SHOOT; switch( state ){ case 0: // Must be in either Right or Back if(newGame){ // try Left if this is the first turn, just in case nextDirection = Direction.LEFT; newGame = false; } else if(shootHall) nextDirection = Direction.BACK; else nextDirection = Direction.RIGHT; shootHall = !shootHall; break; case 2: // Must be in either Left or Back if(newGame){ // try Right if this is the first turn, just in case nextDirection = Direction.RIGHT; newGame = false; } else if(shootHall) nextDirection = Direction.BACK; else nextDirection = Direction.LEFT; shootHall = !shootHall; break; default: // Must be in either Left or Right if(newGame){ // try Back if this is the first turn, just in case nextDirection = Direction.BACK; newGame = false; } else if(shootHall) nextDirection = Direction.RIGHT; else nextDirection = Direction.LEFT; shootHall = !shootHall; break; } }else{ // disregard state, shove out (in an alternating fashion!) and light 'em up! switch( state ){ case 0: // move out, change alternation state nextMove = Move.MOVE; if(headLeft) nextDirection = Direction.LEFT; else nextDirection = Direction.RIGHT; state++; headLeft = !headLeft; break; case 1: // shoot into non-exit path nextMove = Move.SHOOT; if(headLeft) nextDirection = Direction.RIGHT; else nextDirection = Direction.LEFT; state++; break; case 2: // shoot behind nextMove = Move.SHOOT; nextDirection = Direction.BACK; state++; break; default: // shoot into next room, nextMove = Move.SHOOT; if(headLeft) nextDirection = Direction.LEFT; else nextDirection = Direction.RIGHT; state = 0; break; } } } } ``` Let me know if there're any errors, package didn't play nice with my IDE :( [Answer] # Badger He doesn't like visitors. ``` package Hunters; import Mechanics.*; public class Badger extends Hunter { public Badger(){ name = "Badger"; } @Override public void getResponse(boolean[] status){ nextMove = Move.SHOOT; nextDirection = Direction.values()[((int) (Math.random() * 3))]; } } ``` [Answer] # Elmer Fudd "Shhh. Be vewy vewy quiet, I'm hunting wumpus" [Elmer](http://en.wikipedia.org/wiki/Elmer_Fudd) is fixated on the prey and ignores everything except corpses and the Wumpus. He tries to find a corpse then backs off and starts shooting. If he smells a Wumpus, he will back off and if he still smells him he will shoot. My apologies to all the java programmers, this is probably extremely ugly, full of syntax errors and I have probably messed up my logic. ``` package Hunters; import Mechanics.*; public class ElmerFudd extends Hunter { private state int; private previousDir int; public ElmerFudd(){ name = "ElmerFudd"; } public void newGame() { state=0; previousDir = Direction.LEFT; } public void getResponse(boolean[] status){ nextMove = Move.MOVE; switch (previousDir) { case Direction.LEFT: nextDirection = Direction.RIGHT; break; case Direction.RIGHT: nextDirection = Direction.LEFT; break; } if(status[2]&&state==0) { state = 1; return; } if(state==1){ if(status[2]){ state=2; }; nextDirection = Direction.BACK; return; } if(state==2){ nextMove = Move.SHOOT; nextDirection = Direction.BACK; return; } if(state==3&&status[0]) nextMove = Move.SHOOT; nextDirection = Direction.BACK; return; } if(state==3) { state = 0; } if(status[0]){ state=3; nextDirection = Direction.BACK; } } } ``` # Pacifist This guy is morally against any sort of blood sport and wondering how he turned up in this situation at all. He will run away from any sort of contact and never take a shot. ``` package Hunters; import Mechanics.*; public class Pacifist extends Hunter { public Pacifist(){ name = "Pacifist"; } public void getResponse(boolean[] status){ nextMove = Move.MOVE; if(status[0]||status[1]||status[2]||status[3]||status[4]){ nextDirection = Direction.values()[((int) (Math.random() * 3))]; return; } nextDirection = Direction.HERE; } } ``` [Answer] # MonsterHunter We are hunting a monster and we are 4... It reminds me of my favorite game ! This hunter will walk most of the map by moving left-right alternatively, and if the Wumpus is near, he will lure him by going backward to be able to determine precisely were it is. I could get rid of lastDirection, but I keep for semantics and readability :). Actually, it dies quite a lot, but the controller often put 2/3 hunter in the same room at the start, and often with the Wumpus near (can also be in the same room)... so insta death ^^'. ``` package Hunters; import Mechanics.*; public class MonsterHunter extends Hunter { private Direction lastDirection=Direction.HERE; private boolean[] lastStatus=new boolean[5]; private int shooted=0; private boolean walkMode=true; private int turnStayed=0; public MonsterHunter(){ super(); name = "MonsterHunter"; } @Override public void getResponse(boolean[] status) { if(status[0]) { if(!lastStatus[0]||shooted==0) { nextDirection=(walkMode)?Direction.RIGHT:Direction.LEFT;; nextMove=Move.SHOOT; } else if(lastStatus[0]&&shooted==1) { nextDirection=Direction.BACK; nextMove=Move.MOVE; } else { nextDirection=Direction.BACK; nextMove=Move.SHOOT; } } else if(status[2]) { nextMove=Move.MOVE; if(Math.random()*6<turnStayed) { nextDirection=Direction.HERE; turnStayed++; } else nextDirection=(walkMode)?Direction.RIGHT:Direction.LEFT; } else { nextMove=(!status[1]&&Math.random()<0.5)?Move.MOVE:Move.SHOOT; nextDirection=(walkMode)?Direction.RIGHT:Direction.LEFT; } if(nextMove==Move.MOVE) { if(shooted>0) walkMode=walkMode^(shooted>0); if(lastStatus[0]&&shooted==1) shooted++; else shooted=0; lastDirection=nextDirection; } else shooted++; for(int i=0;i<status.length;i++) lastStatus[i]=status[i]; } } ``` [Answer] # PacingHunter Back and forth, between to rooms. if it smells a Wumpus or hears a player it shoots left then right. if a Wumpus is next to him to start with than he shoots the room he will move to. ``` package Hunters; import Mechanics.Direction; import Mechanics.Hunter; import Mechanics.Move; public class PacingHunter extends Hunter { int state = 0;//Pacing int turn = 0; public PacingHunter() { name = "Pacer"; } public void newGame() { turn = 0; state = 0; } public void getResponse(boolean[] status){ turn += 1; if(state == 0 && status[0] && turn == 1){ nextMove = Move.SHOOT; nextDirection = Direction.BACK; return; } if(state == 0 &&(status[0] || status[1])){ nextMove = Move.SHOOT; nextDirection = Direction.LEFT; state = 1; return; } if(state == 1 && (status[0] || status[1])){ nextMove = Move.SHOOT; nextDirection = Direction.RIGHT; state = 0; return; } if(status[1] && state == 0){ nextMove = Move.SHOOT; nextDirection = Direction.BACK; state = 0; return; } nextMove = Move.MOVE; nextDirection = Direction.BACK; } ``` } [Answer] # ScaredyCat ScaredyCat is scared of everything. If it smells a wumpus or a corpse or hears an arrow or a hunter, it runs to a random direction. Otherwise, it simply keeps shooting arrows in random directions. ``` package Hunters; import Mechanics.*; public class ScaredyCat extends Hunter { public ScaredyCat(){ name = "ScaredyCat"; } @Override public void getResponse(boolean[] status){ for(int i=0; i<status.length; i++) if(status[i]) { nextMove = Move.MOVE; nextDirection = Direction.values()[((int) (Math.random() * 3))]; return; } nextMove = Move.SHOOT; nextDirection = Direction.values()[((int) (Math.random() * 3))]; } } ``` [Answer] # Eats Shoots and Leaves Unlike the Panda of grammar book fame, this hunter doesn't actually eat anything, but we either shoot if the Wumpus is about or we leave on a trail that should hopefully keep us from walking in circles. ``` package Hunters; import java.util.Random; import Mechanics.Hunter; import Mechanics.Move; import Mechanics.Direction; import Mechanics.Room; public class EatsShootsAndLeaves extends Hunter { private static Direction [] allDirections = { Direction.LEFT, Direction.RIGHT, Direction.BACK, Direction.HERE }; private static Direction [] movePath = { Direction.LEFT, Direction.RIGHT, Direction.LEFT, Direction.BACK, Direction.RIGHT, Direction.BACK }; private static int numGames = 0; private static int totalLife = 0; private static class RoomInfo { public boolean hasWumpus = false; public boolean hasLocalHunter = false; public boolean hasNeighborHunter = false; public boolean hasCorpse = false; public boolean hasArrow = false; public RoomInfo(Room r) { boolean [] status = r.getInfo(); hasWumpus = status[0]; hasNeighborHunter = status[1]; hasCorpse = status[2]; hasArrow = status[3]; hasLocalHunter = status[4]; } public String toString() { return new String("Status: " + (hasWumpus ? "Wumpus " : "") + (hasNeighborHunter ? "Close Hunter " : "") + (hasCorpse ? "Corpse " : "") + (hasArrow ? "Arrow " : "") + (hasLocalHunter ? "Local Hunter " : "")); } } int turnsAlive = 0; int shots = 0, moves = 0; public EatsShootsAndLeaves(){ name = "Eats Shoots and Leaves"; } public void newGame() { totalLife += turnsAlive; numGames++; turnsAlive = shots = moves = 0; } public void getResponse(boolean[] status){ turnsAlive++; RoomInfo info = new RoomInfo(this.getRoom()); if (info.hasNeighborHunter || info.hasWumpus) { nextMove = Move.SHOOT; nextDirection = allDirections[shots++ % 3]; } else { nextMove = Move.MOVE; nextDirection = movePath[moves++ % movePath.length]; } } } ``` [Answer] # Idomeneus Idomeneus is quite simple- if the Wumpus or another hunter is nearby, he fire sarrows everywhere and prays that the goddess of hunting is on his side. If he's near a corpse he lies in wait for the Wumpus. He doesn't like other hunters and will run away if they start firing arrows near him, or if they are in the same room as him. Finally if he's feeling bored he randomly paces the eternal corridors. ``` package Hunters; import Mechanics.Direction; import Mechanics.Hunter; import Mechanics.Move; import java.util.Random; public class Idomeneus extends Hunter { int direction; Random r; public Idomeneus() { super(); name = "Idomeneus"; direction = 0; r = new Random(); } @Override public void getResponse(boolean[] status){ boolean wumpusNear = status[0]; boolean hunterNear = status[1]; boolean corpseNear = status[2]; boolean arrowNear = status[3]; boolean hunterHere = status[4]; direction++; if(wumpusNear) { //ATTACK!!! nextMove = Move.SHOOT; nextDirection = Direction.values()[direction%3]; } else if(hunterHere || arrowNear) { //Run away nextMove = Move.MOVE; nextDirection = Direction.values()[r.nextInt(3)]; } else if(hunterNear) { //ATTACK!!! nextMove = Move.SHOOT; nextDirection = Direction.values()[direction%3]; } else if(corpseNear) { //Stay and wait... nextMove = Move.MOVE; nextDirection = Direction.HERE; } else { //wander around nextMove = Move.MOVE; nextDirection = Direction.values()[r.nextInt(3)]; } } public void newGame(){} } ``` [Answer] # Emo Wumpus (Hunter) Emo Wumpuses (related to [Emo Wolves](https://codegolf.stackexchange.com/a/25357) which sometimes [use guns](https://codegolf.stackexchange.com/a/34856) and [fly planes](https://codegolf.stackexchange.com/a/35329/41540)) hate everything (especially Java). They make no distinction between Hunters and Wumpuses, and try to shoot them all the same. They also hate Nascar drivers, and will always shoot right. If no one is around to shoot, they move right, but will only do this thirteen times in a row before they get even more depressed about being alone and try to shoot themselves (thirteen is an unlucky number). On turn 99, if they are still alive, they will attempt to shoot themselves because starvation is such a lame way to die. Wumpuses are larger (and heavier) than Wolves, but this one has still starved itself to 424 bytes (as opposed to the hefty 2.72 kb of NascarHunter). ``` package Hunters;import Mechanics.*;public class EmoWumpus extends Hunter{private int c, t;public EmoWumpus(){name="Emo Wumpus";this.c=0;this.t=0;}public void newGame(){this.c=0;this.t=0;}public void getResponse(boolean[] status){nextMove=Move.SHOOT;if(c<13 && t<100){if(status[0]||status[1]){nextDirection=Direction.RIGHT;}else{nextMove=Move.MOVE;nextDirection=Direction.RIGHT;c++;}}else{nextDirection=Direction.HERE;}t++;}} ``` Why not just commit suicide in the first place? Emo Wumpuses believe that the one act of good that can do is end the suffering of others before killing themselves. Therefore, they will kill all that they can before it is their time to die. # Wumpus? (Anti-Hunter) Um, What is a Wumpus doing on the hunters roster? This guy got super pissed that humans were killing his kin, so he decided to dress up as one of them and join in on the hunt. His main goal is to just kill hunters. He tries to hide near corpses, which will give him a chance at a shield from the hunters. If no hunters are nearby, he will move in a direction until hunters are detected, in which case he will try to kill them before moving in the other direction. Unfortunately, most Wumpuses are stupid, and are still going to try to kill him. Regardless, he considers his sacrifices necessary for the good of Wumpuses everywhere. ``` package Hunters; import Mechanics.*; public class AntiHunter extends Hunter { private boolean left; public AntiHunter() { name = "Wumpus"; this.left = true; } public void newGame() { this.left = true; } public void getResponse(boolean[] status) { if(status[4]) { nextMove = Move.SHOOT; nextDirection = Direction.HERE; } else if(status[2] || status[1]) { nextMove = Move.SHOOT; if(this.left) { this.left = false; nextDirection = Direction.LEFT; } else { this.left = true; nextDirection = Direction.RIGHT; } } else { nextMove = Move.MOVE; if(this.left) nextDirection = Direction.LEFT; else nextDirection = Direction.RIGHT; } } ``` } [Answer] # Laomedon Laomedon wanders aimlessly trying to find a corpse. Once he's found one and works out where it is he stays in the same place next to the corpse. When he smells the Wumpus he fires arrows into the Corpse's room. ``` package Hunters; import Mechanics.Direction; import Mechanics.Hunter; import Mechanics.Move; public class Laomedon extends Hunter { private enum status { START, SEARCHED_LEFT, SEARCHED_RIGHT, INITIAL_CORPSE_LEFT, INITIAL_CORPSE_RIGHT, SMELT_CORPSE, CORPSE_BEHIND, CORPSE_LEFT } status myState; public Laomedon() { this.name = "Laomedon"; } @Override public void getResponse(boolean[] status) { boolean wumpusNear = status[0]; boolean hunterNear = status[1]; boolean corpseNear = status[2]; boolean arrowNear = status[3]; boolean hunterHere = status[4]; switch (myState) { case CORPSE_BEHIND: if(wumpusNear) { this.nextDirection = Direction.BACK; this.nextMove = Move.SHOOT; } else { this.nextDirection = Direction.HERE; this.nextMove = Move.MOVE; } break; case CORPSE_LEFT: if(wumpusNear) { this.nextDirection = Direction.LEFT; this.nextMove = Move.SHOOT; } else { this.nextDirection = Direction.HERE; this.nextMove = Move.MOVE; } break; case INITIAL_CORPSE_LEFT: if(corpseNear) { this.nextDirection = Direction.RIGHT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.INITIAL_CORPSE_RIGHT; } else { this.nextDirection = Direction.BACK; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SEARCHED_LEFT; } break; case INITIAL_CORPSE_RIGHT: if(corpseNear) { this.nextDirection = Direction.LEFT; this.nextMove = Move.MOVE; myState = Laomedon.status.INITIAL_CORPSE_LEFT; } else { this.nextDirection = Direction.BACK; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SEARCHED_LEFT; } break; case SEARCHED_LEFT: if(corpseNear) { this.nextDirection = Direction.LEFT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SMELT_CORPSE; } else { this.nextDirection = Direction.RIGHT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SEARCHED_RIGHT; } break; case SEARCHED_RIGHT: if(corpseNear) { this.nextDirection = Direction.LEFT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SMELT_CORPSE; } else { this.nextDirection = Direction.LEFT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SEARCHED_LEFT; } break; case SMELT_CORPSE: if(corpseNear) { this.nextDirection = Direction.BACK; this.nextMove = Move.MOVE; this.myState = Laomedon.status.CORPSE_BEHIND; } else { this.nextDirection = Direction.BACK; this.nextMove = Move.MOVE; this.myState = Laomedon.status.CORPSE_LEFT; } break; case START: if(corpseNear) { this.nextDirection = Direction.LEFT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.INITIAL_CORPSE_LEFT; } else { this.nextDirection = Direction.LEFT; this.nextMove = Move.MOVE; this.myState = Laomedon.status.SEARCHED_LEFT; } break; } } @Override public void newGame() { super.newGame(); myState = status.START; } } ``` Unfortunately for him, the other hunters don't appreciate his skills and they seem to shoot him a lot... [Answer] # NealHunter After talking about this with my friend DoctorHeckle, I'd thought it would be fun to try it myself. Used the idea for alternating left and right to cover the most area, and then decided to add a bit of responding to the states, but only 0 and 1 - whether or not a Wumpus or hunter are nearby. Doesn't perform as well as NascarHunter, which surprised me at first. After some thinking though, I realized that shooting an arrow in a random direction (like this does) after hearing a hunter/smelling a Wumpus won't do anything if they're moving that turn, since arrows are shot into rooms, but movement is carried out before it kills them. Not quite as effective as I thought... still performs well though! ``` package Hunters; import Mechanics.*; import java.util.Random; public class NealHunter extends Hunter { private boolean goLeft; public NealHunter(){ name = "NealHunter"; goLeft = false; } public void newGame() { goLeft = false; } public void getResponse(boolean[] status){ Random rand = new Random(); if(status[0] || status[1]){ nextMove = Move.SHOOT; switch ( rand.nextInt(3) ){ case 0: nextDirection = Direction.LEFT; break; case 1: nextDirection = Direction.BACK; break; case 2: nextDirection = Direction.RIGHT; break; } } else { nextMove = Move.MOVE; if (goLeft) { nextDirection = Direction.LEFT; } else { nextDirection = Direction.RIGHT; } goLeft = !goLeft; } } } ``` [Answer] # WalkingIdiot This one walks until he finds the wumpus. Then, he shoots right. If the wumpus is still there, it must be on the left, so shoot once again. On the way, he doesn't care about other hunters or corpses, hence the name. ``` package Hunters; import Mechanics.*; public class WalkingIdiot extends Hunter { private boolean wumpusNear = false; @Override public void newGame() { wumpusNear = false; } public WalkingIdiot(){ name = "WalkingIdiot"; } @Override public void getResponse(boolean[] status){ boolean wumpusWasNear = wumpusNear; wumpusNear = status[0]; if (status[0]) { nextMove = Move.SHOOT; if (wumpusWasNear) { nextDirection = Direction.LEFT; } else { nextDirection = Direction.RIGHT; } return; } nextMove = Move.MOVE; nextDirection = Math.random() < 0.5 ? Direction.LEFT : Direction.RIGHT; } } ``` # Stay Stay doesn't like to walk. It simply shoots around and remembers if he shot a hunter. ``` package Hunters; import Mechanics.*; public class Stay extends Hunter { private Direction lastShot = Direction.LEFT; private Direction corpse = null; private boolean hunterNear = false; public Stay(){ name = "Stay"; } @Override public void newGame() { corpse = null; hunterNear = false; lastShot = Direction.LEFT; } @Override public void getResponse(boolean[] status){ nextMove = Move.SHOOT;//always boolean hunterWasNear = hunterNear; hunterNear = status[1]; if (hunterWasNear && status[2] && !status[1]) { corpse = lastShot; } if (status[0]) { if (corpse != null) { nextDirection = corpse; return; } } if ((status[1] && !status[4]) || status[0]) { switch (lastShot) { case LEFT: lastShot = nextDirection = Direction.RIGHT; break; case RIGHT: lastShot = nextDirection = Direction.BACK; break; case BACK: lastShot = nextDirection = Direction.LEFT; break; } return; } //default lastShot = nextDirection = Direction.LEFT; } } ``` ]