text
stringlengths
180
608k
[Question] [ ## Challenge: Given a positive number \$n\$, convert it to binary, and output a [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") where all `1`s form a top-left to bottom-right diagonal line, including a leading column of `1`s. To give two examples: \$n=1\$ will result in `[1,3,5,9,17,33,65,129,...]`, with binary values: ``` 1 11 101 1001 10001 100001 1000001 10000001 ↓ ↘ ``` \$n=89\$ will result in `[89,153,281,537,1049,2073,4121,8217,...]`, with binary values: ``` 1011001 10011001 100011001 1000011001 10000011001 100000011001 1000000011001 10000000011001 ↓ ↘↘ ↘ ``` In general, the binary sequences are formed by replacing the leading `1` with `10` in every iteration, with the exception of \$n=1\$. ## Challenge rules: * The input \$n\$ is guaranteed to be positive. * Default [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply, so you're allowed to: + Take an additional input \$k\$ and output the \$k^{th}\$ value of the sequence, either 0-index or 1-index. + Take an additional input \$k\$ and output the first \$k\$ values of the sequence. + Output the values of the sequence indefintely. * Of course, any reasonable output format can be used. Could be as strings/integers/decimals/etc.; could be as an (infinite) list/array/stream/generator/etc.; could be output with space/comma/newline/other delimiter to STDOUT; etc. etc. + I/O as binary isn't allowed for this challenge, since it's already easy enough as is. **Please state what I/O and sequence output-option you're using in your answer!** ## General Rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#) or [ATO](https://ato.pxeger.com/run)). * Also, adding an explanation for your answer is highly recommended. ## Test Cases: ``` n First 10 values of the output sequence 1 [1,3,5,9,17,33,65,129,257,513,...] 2 [2,4,8,16,32,64,128,256,512,1024,...] 3 [3,5,9,17,33,65,129,257,513,1025,...] 6 [6,10,18,34,66,130,258,514,1026,2050,...] 7 [7,11,19,35,67,131,259,515,1027,2051,...] 12 [12,20,36,68,132,260,516,1028,2052,4100,...] 31 [31,47,79,143,271,527,1039,2063,4111,8207,...] 89 [89,153,281,537,1049,2073,4121,8217,16409,32793,...] 111 [111,175,303,559,1071,2095,4143,8239,16431,32815,...] 1000 [1000,1512,2536,4584,8680,16872,33256,66024,131560,262632,...] ``` [Answer] # [Python](https://www.python.org), 39 bytes ``` lambda n,k:n^-2&(1^1<<k)<<len(bin(n))-3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY31XMSc5NSEhXydLKt8uJ0jdQ0DOMMbWyyNW1sclLzNJIy8zTyNDV1jSHKbzFGFxRl5pVoRKdpGOpkaqblFylkKmTmKRQl5qWnahgaaMZqcsFVGBFUYUxQhRlBFeYEVRgS4RDCvrGwJGyRIWFjDA0MDHAogoTxggUQGgA) ## Explanation ``` lambda n,k:n^-2&(1^1<<k)<<len(bin(n))-3 n^ # change bits -2& # keep lowest bit (1^1<<k) # 1 0000 1 (k-1 zeros) <<len(bin(n))-3 # shifted to highest bit ``` --- # [Python](https://www.python.org), 49 bytes *simple string based solution, the n&1 is needed to satisfy the test-case for input 1* ``` lambda n,k:n&1|int((s:=bin(n))[:3]+k*"0"+s[3:],2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3DXMSc5NSEhXydLKt8tQMazLzSjQ0iq1skzLzNPI0NaOtjGO1s7WUDJS0i6ONrWJ1jDShGs8UFIHURqdpGOpkaqblFylkKmTmKRQl5qWnahgaaMZqcsFVGBFUYUxQhRlBFeYEVRjicgjETwsWQGgA) [Answer] # [JavaScript (V8)](https://v8.dev/), 41 bytes Prints the sequence 'indefinitely' (in practice, until the call stack overflows). ``` f=(n,k=2)=>k*2>n?print(n)|f(n+k):f(n,k*2) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI08n29ZI09YuW8vILs@@oCgzr0QjT7MmTSNPO1vTKg0kr2Wk@T9Nw8JS8z8A "JavaScript (V8) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input k = 2 // k = power of 2 to be added to n // the minimum is 2, because of // the edge case n = 1 ) => // k * 2 > n ? // if k * 2 is greater than n: print(n) // print n | f(n + k) // and do a recursive call with n + k : // else: f(n, k * 2) // do a recursive call with k doubled ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ¡(Y3ḋ:.ḋ ``` [Try it online!](https://tio.run/##yygtzv7//9BCjUjjhzu6rfSAxP///w0B "Husk – Try It Online") When your language does not have logarithms you need to get creative with base conversion. Here's some fun with half bits! Takes a positive integer as input and outputs an infinite list of the sequence starting from that number. ### Explanation ``` ¡(Y3ḋ:.ḋ ¡( Infinitely repeat the following commands and collect outputs in a list: ḋ Convert to base 2 :. Prepend 0.5 as an extra initial digit ḋ Convert back from base 2 Y3 Take the maximum between the obtained value and 3 ``` As the challenge states, this sequence can be generated by replacing the leading `1` in the binary representation of each value with `10`. If we allow our "binary" number to have digits higher than 1, we could simply add 1 to the first digit (e.g. \$5\_{10} = 101\_2 \rightarrow 201\_{"2"} = 1001\_{2} = 9\_{10}\$). Even better, adding 1 to a digit in base 2 is equivalent to adding 0.5 to the digit preceding it! (\$201\_{"2"} = [0.5][1][0][1]\_{2.0} = 1001\_2\$; I think I'm starting to get *too* creative with notation here). Taking the maximum between the resulting number and 3 was the shortest way I could find to fix the edge case for 1. [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes A function that takes \$ n \$ as input, and outputs the sequence indefinitely. ``` def f(n):print n;f(n^3<<len(bin(n))-3&-2) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TqqAoM69EIc8ayIkztrHJSc3TSMrMA8po6hqr6Rpp/k/TsLDU/A8A "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` λbg<1Mo₁+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3O6kdBtD3/xHTY3a//8bAQA "05AB1E – Try It Online") or [try all testcases.](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@f/c7qR0G0Pf/EdNjdr/a0MOLVbSUVA6vNceSOnp6Snp/I821FEw0lEw1lEw01Ew11EwBHGAYhaWQLYhkGFoYGAQCwA "05AB1E – Try It Online") ## Explanation ``` λ # recursively start with f(0) = n bg< # push floor(log2(f(i-1))) 1M # max(1, floor(log2(f(i-1)))) o # 2**max(1, floor(log2(f(i-1)))) ₁+ # f(i) = f(i-1) + 2**max(1, floor(log2(f(i-1)))) ``` [Answer] # [Haskell](https://www.haskell.org), 35 bytes ``` (%2) n%k|k*2>n=n:(n+k)%k|l<-k*2=n%l ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7NI0BVuFmKWlJWm6FjeVNVSNNLnyVLNrsrWM7PJs86w08rSzNYH8HBtdoJBtnmoOVKlHbmJmHlBrbmKBr4JGQVFmXomCnkJJYnaqgqEBkJWmqRBtqKNgpKNgrKNgpqNgrqNgCOIAxSwsgWxDIMPQwMAgFmLeggUQGgA) Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/265875/56433). [Answer] # Excel, ~~41~~ 53 bytes ``` =DECIMAL(10^B1&TEXTAFTER(BASE(A1,2),1),2)+IF(B1,A1=1) ``` Inputs *n* and *k* in cells `A1` and `B1` respectively, where *k* represents the *k*th 0-indexed value of the sequence. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` (3|2/2,1_2\)\ ``` [Try it online!](https://ngn.codeberg.page/k#eJx9kr1SwzAQhHs/RUhmsD05nPuRTrJTQEHj3h1mDE3oKaiYPDurKDVupNF8d7e758vU2a+elGTTtV+b5tTIrnxvQkaRRpJEZuSRREfSmCiK0TAM741WUClQJnEyJQ/AMjAHhqasobJW2X9ago2V9co6nkgyWSDH3RhoBhoK6qQcufKp8olESEaySI67CfgRfCx8KrxUXrQaVLyROTnUQ7s6gy5TiwOO8CV8H2FS5QuFRAkOgpEmoYjGwgYX7AYeCrJyqkV5vBVl4BF4Bm4FDwVPBdeCIw3xwBCuabxHi0Y3icVRimSM4GBGGDOVx4haKMiKyaiFLEP7e3wQzaUWBwYXlxEmQ8xYk2e8eU6KBZQluZcNIasI8+rqyOHWBH/CPMk2vzxeu/mZ2v1pXfd92z0c5omnj8/vr5+d9E03n1/PSz8deee7tJ2mGWVDOzfL1A3tk2x72q99uzTL9TK0x+5Jjod2Oc998wfDv3ww) A base conversion trick that works somewhat like Husk or Nekomata answers, but keeps things in integers. This works by replacing the leading 1 with a 2 in the binary representation. ``` (3|2/2,1_2\)\ ( )\ collect first k iterations: 2\ convert to base 2 2,1_ remove the leading 1 and attach a 2 2/ convert from "base 2" to integer 3| max with 3 to handle 1 ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~8.5~~ 7.5 bytes (15 nibbles) ``` `.$+^2,:>2``@ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWaxP0VLTjjHSs7IwSEhwgYlCpJdEWlrFQNgA) ``` `.$+^2,:>2``@ # full program `.$+^2,:>2``@$$$ # with implicit arguments shown; `. # iterate while unique (in this case, for ever), $ # starting with the input: + # add $ # the previous result to ^2 # 2 to the power of , # the length of ``@$ # the binary digits of the previous result >2 # without the first two digits : $ # and appending the result so far ``` [Answer] # [R](https://www.r-project.org), 40 bytes ``` f=\(n){m=log2(print(n))%/%1;f(n+2^m+!m)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHOlMzE9Py8xJz4pMy8xKLK-OLUwtLUvORU26WlJWm6Fjc10mxjNPI0q3Ntc_LTjTQKijLzSoB8TVV9VUPrNI08baO4XG3FXM1aiPo9uMzTsLDUhChZsABCAwA) [Answer] # x86 32-bit machine code, 14 bytes ``` 0F BD C8 E3 03 0F B3 C8 01 D1 0F AB C8 C3 ``` [Try it online!](https://tio.run/##nVJdb9owFH22f8UtFZK9mCmEat3I6Mue@9KnSQVFxnHALDiVbbowyl9fdk1ZyVul3gfnfvic4@NYjVZKdZ30W2DwMGC0mpKld6BVK0DLlpINpn/AU7IMLnZEnFE/JbIsz9vKNk79ZUqcDpQPeE6LQobgzHIXdFEw5vTqSbotyzjnYGyAisXVilPxi@fw3BikZTzvro1V9a7U8N2H0jSf13c0btpKYxmnB0qeHNYVGwDGSxQjVePgRLiBGaQ5fq5mMM4wSRJOoRdv2OGtGQjYRPT/3tyOMJIPMo7OcYJHZNA@FM@y9o8L5DiMBWQCJgK@CLgVyIUF9r5@w3yMyThN02Nf2bwqm5NyTKIyQf@v7Di9KJgFIntGhjfmBe2FeJZ3vJAL7nwpFQtiwyP02L@cub2Xam2sBtWUevrms42sAvZYlg0cLmRp9hPZ9jPGdtabldUlqLV0n3jFH9skWfD8CL/XptbA9vFIaftj0v8fwIYGlnt0yecWmdo4xBe2cxZt0GP3V1W1XPlutJ1kuOBjniFS1/8A "C (gcc) – Try It Online") Following the `regparm(2)` calling convention, this takes *n* in EAX and a 0-index in EDX, and returns a number in EAX. In assembly: ``` f: bsr ecx, eax # Set ECX to the highest position of a 1 bit in EAX. jecxz s # Jump if ECX is 0. btr eax, ecx # (Otherwise) Remove that highest 1 bit. s: add ecx, edx # Add the index (in EDX) to ECX. bts eax, ecx # Reinsert a 1 bit into EAX at position ECX. ret # Return. ``` [Answer] # [Uiua](https://uiua.org), ~~18~~ 14 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==) ``` ⍥(+ⁿ∶2↥1-1⧻⋯.) ``` [Try it!](https://www.uiua.org/pad?src=RiDihpAg4o2lKCvigb_iiLYy4oalMS0x4qe74ouvLikKCkYgMCAxCkYgNSAxCkYgNSA4OQ==) Returns the nth member of the sequence. -4 thanks to Dominic van Essen ``` ⍥(+ⁿ∶2↥1-1⧻⋯.) ⍥( ) # repeat . # duplicate ⋯ # convert to bits ⧻ # length -1 # subtract 1 ↥1 # max between this and 1 (need this for input of 1) ⁿ∶2 # 2 raised to the result + # add ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 25 21 bytes ``` {2/?[;!2;1,x=1]@2\x}\ ``` [Try it online!](https://ngn.codeberg.page/k#eJx9kr1OxDAQhPs8xXFIJNEtuf2x104iBAVN+nQEHTTQUyAkBM/O+Hw1aWxZ3+7OzOZt+tbj/dN8pbPQ1508P+j29bM1zbGRXfmehIwijSSJzMgjiY6kMVEUo2EYnhutoFKgTOJkSh6AZWAOTElYQ2Wtsv+0BBsr65V1PJFkskCOuzHQDDQU1Ek5cuVT5ROJkIxkkRx3E/Aj+Fj4VHipvGg1qHgjc3Koh3Z1Bl2mFgcc4Uv4MsKkyhcKiRIcBCNNQhGNhQ0u2A08FGTlVIvyeC7KwCPwDNwKHgqeCq4FRxrigSFc03iJFo3OEoujFMkYwcGMMGYqjxG1UJAVk1ELWYb2l/ggmkstDgwuLiNMhpixJs9485wUCyhLci8bQlYR5tXVkcO5Cf6EZZLT8nDz2y331O6P27bv2+7qepl4enn9eP/cSd90y/w4r/104J3v0uk4LSgb2qVZp25ob+W0p/3Wt2uz/r4N7aG7lcN1u85L3/wBoCd+9Q==) -4 bytes - thanks to @coltim [Answer] # [Rust](https://www.rust-lang.org), 49 bytes Input is an integer n as a start value and an integer k for the sequence index. I tried experimenting with `next_power_of_two`, but the name turned out to be way too long. ``` |n:u64,k:u32|1<<n.ilog2()+k|n&!(1<<n.ilog2())|n&1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5BbsIwEEX3PsWESshO02AHhJBDrsCCJbvS1sjCjFGwV7ZP0k0WcChug1NaqZv50p958__3tfcXN9y3CuH0rpEyCMR8OVDQwawk8eQdoPTLRTTWnsO4Mp1Yrz_3h4Iiq7Wxh4ayFrumNBGnxThEIuXs5p16W91F_MGro_TzJmYS_5jX43hP_1tshH_BXUvIh8WLg42E_CEXEpzz7CrbgwaNwOta8FwYAM69RmewoJOXkCQEIfcJaBCJTSrQFSi6ycpYSxJJz4RheOoD) Explanation and prettier code: ``` // A captureless closure with two integer arguments // n is the seed number, k is the sequence index |n: u64, k: u32| // The following numbers get bit-or'ed together: // A one followed by zeroes whose length is the length of the original number plus the parameter k. // ilog2 calculates the floored base-2 logarithm. // This means 1 shifted by it is equivalent to setting all digits but the most significant one to zero. // Adding k means shifting the most significant one, which is the only thing k is used for in this sequence. 1 << n.ilog2() + k // The number n, with its most significant one bit set to zero (the replacement part). | n & !(1 << n.ilog2()) // A one if the original number's least significant digit contains a one. Only relevant for n=1. | n & 1 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 84 bytes ``` ^.+ $* +`^(1+)\1 $+0 01 1 ^(.)(.+)?¶(.+) $1$3$*0$2$#2$*## 0## 0 1|0# 01 +`10 011 %`1 ``` [Try it online!](https://tio.run/##HYw9DsIwFIN3XyMvUtJU1XOK@Jk4ARMrqh4DAwsDYuy5coBeLCQd/NmD7e/r9/48qw8mGHUrYiN35p3zzgN8uNtYlylBBiRbAlN8EJIUShBLmGKYUrxupRuEMsugksVlGZyDdoGruj5Ixj4kvLES8WbtC1tpOWPGESewBeJ8AVuNqvoH "Retina 0.8.2 – Try It Online") Takes `n` and `k` as input and outputs the `k`th (0-indexed) term of the sequence but link is to test suite for multiple values of `n` that sets `k=0..4` (because larger values would be too slow). 91 bytes to output the first `k` terms: ``` ^.+ $* +`^(1+)\1 $+0 01 1 ^(.)(.*)¶(.+) $1$3$*_$2 _ $'¶1 O` 1A` _\b 1 _ 0 1 01 +`10 011 %`1 ``` [Try it online!](https://tio.run/##FY27DQIxEETzqWNP@CNZO3fiF1IAooGTvSARkBAganMB15hZkqcJZt58nt/X@z6mYIKt70ctGZKQrQbmuBKSFUoQNZQYSopbDyVHCGWR1GRGg@y2TtwMvBja@vB2gzp9mI1/ATEZh/Nq7vQrzzMWHHAEPRCnM@g1quoP "Retina 0.8.2 – Try It Online") Takes `n` and `k` as input and outputs the first `k` terms of the sequence but link is to test suite for multiple values of `n` that sets `k=5` (because larger values would be too slow). Explanation: ``` ^.+ $* ``` Convert `n` to unary. ``` +`^(1+)\1 $+0 01 1 ``` Convert `n` to binary. ``` ^(.)(.*)¶(.+) $1$3$*_$2 ``` Convert `k` to unary as `_`s and insert it after the first digit of `n`. ``` _ $'¶1 O` 1A` ``` Generate all of the first `k` terms. ``` _\b 1 ``` Fix the `n=1` error. ``` _ 0 ``` Change the remaining `_`s to `0`s. ``` 1 01 +`10 011 ``` Convert to unary. ``` %`1 ``` Convert to decimal. 54 bytes with the original intent that the leading `1` participates in the diagonal: ``` .+¶ $*_ \d+ $* +`(1+)\1 $+0 01 1 ^.|1 01 +`1[0_] 011 1 ``` [Try it online!](https://tio.run/##HYoxDsIwEAT7fYcjHM6KbhNE4BFUlITESFDQUCDKvMsP8MfMxc3saDXf1@/9eZTGxxka3C4nVvaVQ@UhoPHXGEonOcHtF0xPsYVET2knwolCCWLuVm4mkTdd7qb2FqK9RKuQk3mPAUeMoAlxOoNbpKp/ "Retina 0.8.2 – Try It Online") Takes `k` and `n` as input and outputs the `k`th (0-indexed) term of the sequence but link is to test suite for multiple values of `n` that sets `k=0..4` (because larger values would be even slower). 70 bytes to output the first `k` terms: ``` .+¶ $*_ \d+ $* +`(1+)\1 $+0 01 1 M!&`_.+ O` %`^_.|1 01 +`1[0_] 011 %`1 ``` [Try it online!](https://tio.run/##FYxBCoNQEEP3uYWgRR34TFps9RDSA1T9U6gLNy6ky57LA3ix73SThEeSbf4u6zsVpU1ojj0FOXbkdcTwEXeIlZRqIHJRKEH02cViEDwNhU0x/PjnYnxpHD3SMZNrb76CfxJX3HDHA/RAtB3oNarqCQ "Retina 0.8.2 – Try It Online") Takes `k` and `n` as input and outputs the first `k` terms of the sequence but link is to test suite for multiple values of `n` that sets `k=5` (because larger values would be even slower). Explanation: ``` .+¶ $*_ ``` Convert `k` to unary as `_`s. ``` \d+ $* ``` Convert `n` to unary. ``` +`(1+)\1 $+0 01 1 ``` Convert `n` to binary. ``` M!&`_.+ O` ``` Generate the first `k` terms. ``` %`^_.|1 01 +`1[0_] 011 ``` Convert to unary, but the leading `_` makes the next digit `1` while any remaining `_`s are interpreted as `0`s. ``` %`1 ``` Convert to decimal. [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 73 bytes body, 13 bytes header and footer ``` program x read*,n;i=2**(31-leadz(n));n=n-i;do;print*,i+n;if(i<2)n=n+1;i=i*2;end do end ``` Try it online: [n=1](https://tio.run/##JYtLCoAwDESv0mUb20XrMnqYQj8ENJXgQrx8Dbia4c2bNuSWzKG3v8xLRpd8mmdKzQU8I@0JwK4xHApey84h7xwIy8BLiG/wtKjWLG3J6bRE/RAkrFxMGVNjxg8 "Fortran (GFortran) – Try It Online"), [n=89](https://tio.run/##JYvBCoAgEER/paOuetAuxdbHCGYs1BpLh@jnbaHTDG/e1Ca3ZA57/Uu/pO2Sz@HpsuUCnpHWBGDGGA4Fr2FrkVcOhKXhJcQ3eHKqVUNLsjq5qB@ChBuXobSu0af5Aw "Fortran (GFortran) – Try It Online") Reads `n` from standard input and outputs the corresponding sequence. Uses `leadz()` to count the leading zeros. Puts the highest 1 into `i` and removes it from `n`. The loop shifts the highest 1 further to the left in each iteration and outputs the sum of `i` and `n` in each cycle. Special handling for `n==1`. [Answer] # [Perl 5](https://www.perl.org/).10 -n, 35 bytes ``` $_^=$_-1?3<<(1.4427*log):2while say ``` [Try it online!](https://tio.run/##K0gtyjH9/18lPs5WJV7X0N7YxkbDUM/ExMhcKyc/XdPKqDwjMydVoTix8v9/C8t/@QUlmfl5xf91fctM9QwN/uvmAQA "Perl 5 – Try It Online") Finds the next elem by xor'ing the current n with `3 << log₂(n)` where << is the left shift operator that only cares about the integer part of log₂. Here n=1 is handled as a special case where 1 is xor'ed by 2 to get 3. ``` 89 xor (3 << log2(89) ) = 89 xor (3<<6) = 153 153 xor (3 << log2(153) ) = 153 xor (3<<7) = 281 281 xor (3 << log2(281) ) = 281 xor (3<<8) = 537 . . ``` [Answer] # TI-Basic, 20 bytes ``` While 1 Disp Ans max(3,Ans+2^int(log(Ans,2 End ``` Takes input in `Ans`. Outputs infinitely with each number on its own line. If not using OS 2.53 MP or higher, replace `log(Ans,2` with `log(Ans)/log(2` for +2 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~20~~ 19 bytes ``` NθI⁺θ×X²L⍘÷貦²⊖X²N ``` [Try it online!](https://tio.run/##TY3BCsIwEETv/YoeN1BBe1J6014KIkH9gZguaaDZtsmmfn5MQdCBN6c3jB6U15MaU@pojnyL7oUeFtEU0ltiuKjAIMcYYKnKp3UYQE7vrNRVeUUyPMBZBXxwtg10xK1dbY@bXYsNkbtF7dEhMfa/9V2RQfh/Fd80KR1PxWGfduv4AQ "Charcoal – Try It Online") Takes `n` and `k` as input and outputs the 0-indexed `k`th element but link is to version that outputs the first `k` elements at a cost of 1 byte. Explanation: Port of @Arnauld's JavaScript answer with some inspiration from @DominicvanEssen's Nibbles answer. ``` Nθ Input `n` as a number ² Literal integer `2` X Raised to power θ Input `n` ÷ Integer divided by ² Literal integer `2` ⍘ Converted to base ² Literal integer `2` L Take the length × Multiplied by ² Literal integer `2` X Raised to power N Input `k` as a number ⊖ Decremented ⁺ Plus θ Input `n` I Cast to string Implicitly print ``` 14 bytes with the original intent that the leading `1` participates in the diagonal: ``` NθI|θX²⁺⊖L↨θ²N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMps6Q8szjVHyihoxCQXw5UYQRk5JQWa7ikJhel5qbmlaSmaPik5qWXZGg4JRanghQaaWpq6igEJealp2ogG64JAdb//1tYchka/NctywEA "Charcoal – Try It Online") Takes `n` and `k` as input and outputs the 0-indexed `k`th element but link is to version that outputs the first `k` elements at a cost of 1 byte. Explanation: ``` Nθ Input `n` as a number ² Literal integer `2` X Raised to power θ Input `n` ↨ Converted to base ² Literal integer `2` L Take the length ⊖ Decremented ⁺ Plus N Input `k` | Bitwise Or θ Input `n` I Cast to string Implicitly print ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 9 bytes ``` ᶦ{Ƃ2ŗɔƃ3M ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFTtJJurpKOgpJuDog0NFCKXbC0tCRN12L9w23Lqo81GR2dfnLKsWZj3yXFScnFULkFuw25jLiMucy4zLkMgQxDLgtLLkNDQy5DAwMDiBIA) A port of [@Leo's Husk answer](https://codegolf.stackexchange.com/a/265891/9288). ``` ᶦ{Ƃ2ŗɔƃ3M ᶦ{ Infinite loop and print the result of each iteration: Ƃ Convert to base 2 2ŗɔ Prepend 1/2 ƃ Convert back from base 2 3M Take the maximum of the result and 3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands) ``` λb¦TìC3M ``` Now that it's been a short while, I'm gonna post my own solution. Outputs the infinite sequence. [Try it online](https://tio.run/##yy9OTMpM/f//3O6kQ8tCDq9xNvb9/98QAA) or [verify the first ten terms of all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c7uTDi0LObzG2dj3f23IocU6/6MNdYx0jHXMdMx1DIEMQx0LSx1DQ0MdQwMDg1gA). **Explanation:** ``` λ # Create a recursive environment, # to generate the infinite sequence # (which will be lazily output implicitly at the end) # Starting with a(0) = (implicit) input # And where every following a(n) is calculated as: # Implicitly push the previous term a(n-1) b # Convert a(n-1) to a binary string ¦ # Remove its leading "1" Tì # Prepend "10" instead C # Convert it back from binary to a (base-10) integer 3M # Manually fix a(1) for input=1: 3 # Push 3 M # Push a copy of the maximum of the stack ``` [Answer] # [Uiua](https://uiua.org), 12 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⍥(↥3+⍜'ₙ2⌊.) ⍥(+ⁿ↥1⌊ₙ2,2) ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4o2lKOKGpTMr4o2cJ-KCmTLijIouKQpnIOKGkCDijaUoK-KBv-KGpTHijIrigpkyLDIpCiMgZiDihpAg4o2lKCviioPijZzigpnijIrihqUyKQriioPiiLVmIOKItWcg4oehMTAgODkK4oqD4oi1ZiDiiLVnIOKHoTEwIDEK4oqD4oi1ZiDiiLVnIOKHoTEwIDI=) ``` ⍥(↥3+⍜'ₙ2⌊.) input: repetition, initial number ⍥( ) repeat the successor operation the given number of times: ⍜'ₙ2⌊ power of two <= current number ↥3+ . add to the current number, and maximum with 3 to handle 1 ⍥(+ⁿ↥1⌊ₙ2,2) ⌊ₙ2, floor(log2(current number)) ↥1 max with 1 to handle 1 ⁿ 2 2 raised to the power of that + add to the current number ``` Could be 10 bytes if there weren't a [bug](https://github.com/uiua-lang/uiua/issues/173) in `⍜ₙ`: ``` ⍥(+⊃⍜ₙ⌊↥2) ⊃ 2 call two functions on 2 and the current number: ⍜ₙ⌊ power of two <= current number, ↥ max + add the two ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->n,k{r=1;r*=2until n<r*2;n-r/2*2|r<<k} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7u6yNbQukjL1qg0ryQzRyHPpkjLyDpPt0jfSMuopsjGJrv2f4GChoGenqGBpl5uYkF1TUVNWrShTkVsLRc2CQMDA5DcfwA "Ruby – Try It Online") ]
[Question] [ # Challenge Given an integer `n` (where `4<=n<=10**6`) as input create an ASCII art "prison door"\* measuring `n-1` characters wide and `n` characters high, using the symbols from the example below. --- ## Example ``` ╔╦╗ ╠╬╣ ╠╬╣ ╚╩╝ ``` The characters used are as follows: ``` ┌───────────────┬─────────┬───────┐ │ Position │ Symbol │ Char │ ├───────────────┼─────────┼───────┤ │ Top Left │ ╔ │ 9556 │ ├───────────────┼─────────┼───────┤ │ Top │ ╦ │ 9574 │ ├───────────────┼─────────┼───────┤ │ Top Right │ ╗ │ 9559 │ ├───────────────┼─────────┼───────┤ │ Right │ ╣ │ 9571 │ ├───────────────┼─────────┼───────┤ │ Bottom Right │ ╝ │ 9565 │ ├───────────────┼─────────┼───────┤ │ Bottom │ ╩ │ 9577 │ ├───────────────┼─────────┼───────┤ │ Bottom Left │ ╚ │ 9562 │ ├───────────────┼─────────┼───────┤ │ Left │ ╠ │ 9568 │ ├───────────────┼─────────┼───────┤ │ Inner │ ╬ │ 9580 │ └───────────────┴─────────┴───────┘ ``` --- ## Rules * You may take input by any reasonable, convenient means as long as it's permitted by [standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447/58974). * For the purposes of this challenge, in languages where the symbols used to build the "door" are multi-byte characters, they may be counted towards your score as a single byte each. * All other characters (single- or multi-byte) should be counted as normal. * Output may not contain any trailing spaces but a trailing newline is permitted if absolutely necessary. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte count wins. --- ## Test Cases ``` Input: 4 Output: ╔╦╗ ╠╬╣ ╠╬╣ ╚╩╝ Input: 8 Output: ╔╦╦╦╦╦╗ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╠╬╬╬╬╬╣ ╚╩╩╩╩╩╝ Input: 20 Output: ╔╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╗ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣ ╚╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╝ ``` \* Yes, I'm aware that the bigger it gets the less it looks like a prison door! :D [Answer] # Java 11, ~~156~~ ~~151~~ ~~148~~ ~~118~~ 89 bytes ``` n->"╔"+"╦".repeat(n-=3)+"╗\n"+("╠"+"╬".repeat(n)+"╣\n").repeat(n+1)+"╚"+"╩".repeat(n)+"╝" ``` [Try it online.](https://tio.run/##hZBNCsIwEIX3nmLIKqG0@LcQRG9gNy7VRYxRonUsbSqIeAtFEARBEARP5UXqGIuCIEJmSN73Fu9lKpfSn45muYpkmkJHGlyXAAxanYyl0hA@nwBdmxicgOJEAEWTxA0NndRKaxSEgNCCHP02u@@2zKN9YUGiYy0tR79VE09p30fmcbqcnOP2cTh8Jizekldx4sFZr1/WI8ubrwBxNowoQJFjuTAjmFMN/orcG4AURYdVavU8WGQ2iAnZCDkGiteFq/OTN/7walkU/7HJHw) **Old 118 bytes answer in Java 8:** ``` n->{String a="╔",b="╠",c="╚";for(int i=n;i-->3;a+="╦",b+="╬")c+="╩";a+="╗\n";for(b+="╣\n";n-->2;)a+=b;return a+c+"╝";} ``` -30 bytes by creating a port of [*@raznagul* C# (.NET Core) answer](https://codegolf.stackexchange.com/a/126882/52210), after I golfed 5 bytes. [Try it here.](https://tio.run/##hZDBasMwDIbvewrhU0yaMLodBiZ9g/Wy49qD4rrDXaoExymUkrfoGAwGg8FgsKfai2Ry4msZ2Ejy90v88g4PmNWNod3medAVti3co6XTFYAlb9wWtYFlKAEevLP0BDphAiQVP/Z8@bQevdWwBIICBsoWp6jFQvy@nMWsDPFDzHSIb0JtazdOsQUpm2WLG4VpQF8sHZMfIfWYfIuIXlc09U2Cz1ASt86VZEGpnPGdI8BUp4zfheoHNblrurJid9HkobYb2POOyeTxcQ0o44LH1pt9Xnc@bxj5ihLKdXIrx10v8rt/@Pxaxs/qhz8) **Explanation:** ``` n-> // Method with integer parameter and String return-type "╔" // The top-left corner +"╦" // Appended with the top edge .repeat(n-=3) // Repeated input-3 times (-2 for the corners, -1 for width) +"╗\n" // Appended with the top-right corner and a newline +("╠" // The left edge +"╬" // Appended with the middle part .repeat(n) // Repeated input-3 times (-2 for edges, -1 for width) +"╣\n" // Appended with the right edge and a newline ).repeat(n+1)// And repeat this entire line n-2 times (-2 for first/last rows) +"╚" // Appended with the bottom-left corner +"╩" // Appended with the bottom edge .repeat(n) // Repeated input-3 times +"╝" // Appended with the bottom-right corners ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 - 5 = 29 bytes ``` A⁻N³γUB╬↓×╠γ╠¶╚×╩γ‖BOγ‖BO↑⁺γ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DNzOvtFjDM6@gtMSvNDcptUhDU0fBGIjTNa25glNLnBKTs9OL8kvzUjSUHk1dowQUDSjKzCvRsHLJL8/TUQjJzE0tBkktUALpgUuDRGLyHk2dhdABV7oSpjQoNS0nNbnEqbSkJLUoLafSvyy1KCexQCNdE6eUVWiBjkJADtDN6ToKhkBD/v@3@K9b9l@3OAcA "Charcoal – Try It Online") Link is to verbose version of code. 5 byte reduction is for box drawing characters. `ReflectOverlapOverlap(0)` should be equivalent to `ReflectMirror()` but instead Charcoal just does a `ReflectTransform()` instead, otherwise this solution would also work for `n=3`. Here's a workaround which shows what would happen for `n=3` for 38 - 5 = 33 bytes: ``` A⁻N³γUB╬↓×╠γ╠¶╚×╩γ¿γ‖BOγ‖M‖BO↑⁺γ¹ ``` Better still, if `ReflectOverlapOverlap(0)` worked, but I didn't bother supporting `n=3`, then I could do this for 31 - 4 = 27 bytes: ``` A⁻N³γUB╬↓×╠γ╚×╩γ‖BOγ‖BO↑⁻γ¹ ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~44~~ 42 bytes [Crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/123438/26600) ``` A⁺±³NαA⁺¹αω╔×α╦¦╗J⁰¦¹×ω╠ ¦╚×α╩¦╝M↖↑×ω╣M↙¤╬ ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWPGncd2nho8/s9685thHJ3ntt4vvPR1CmHp5/b@GjqskPLHk2d/n7PqkeNGw4tO7Tz8HSQ5AIukPAsiJKVIPbc93vWPmqb9qhtIkTFYjB/5qElj6au@f/fAgA "Charcoal – Try It Online") [Answer] ## Haskell, 75 bytes ``` w i(a:b:c)=a:(b<$[4..i])++c f n=concat$w(n+1)$w n<$>["╔╦╗\n","╠╬╣\n","╚╩╝"] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1whUyPRKskqWdM20UojyUYl2kRPLzNWU1s7mStNIc82OT8vObFEpVwjT9tQU6VcIc9GxS5a6dHUKY@mLns0dXpMnpIOkLfg0dQ1j6YuhvJmPZq68tHUuUqx/3MTM/MUbBVS8rkUFApKS4JLihRUFNIUTFC5pv8B "Haskell – Try It Online") Function `w` takes an integer `i` and a list where `a` is the first, `b` the second element and `c` the rest of the list and makes a new list `a`, followed by `i-3` copies of `b`, followed by `c`. Apply `w` first on each each element of the list `["╔╦╗\n","╠╬╣\n","╚╩╝"]` and then again (with `i` increased by `1`) on the resulting list. Concatenate into a single list. [Answer] # Vim, 29 bytes ``` 3<C-x>C╔╦╗ ╠╬╣ ╚╩╝<Esc>h<C-v>kkx@-Pjyy@-p ``` Since there are control characters, here's an xxd dump: ``` 00000000: 3318 43e2 9594 e295 a6e2 9597 0de2 95a0 3.C............. 00000010: e295 ace2 95a3 0de2 959a e295 a9e2 959d ................ 00000020: 1b68 166b 6b78 402d 506a 7979 402d 70 .h.kkx@-Pjyy@-p ``` [Try it online!](https://tio.run/##K/v/31jC2dHJmcvXz58rIjJKOkMsO7vCQTcgq7LSQbfg/38LAA "V – Try It Online") (The V interpreter seems to have issues with exotic characters, so that link uses more mundane ones.) ## Explanation ``` 3<C-x> " Decrement the number by 3 C╔╦╗ ╠╬╣ ╚╩╝<Esc> " Cut the number (goes in @- register) and enter the "template" h<C-v>kkx " Move to the middle column, highlight and cut it @-P " Paste @- copies of the cut column jyy " Move to the middle line and copy it @-p " Paste @- copies of the copied line ``` [Answer] # GNU sed, 74 + 1 = 75 bytes +1 byte for `-r` flag. Takes input as a unary number. ``` s/1111(1*)/╔╦\1╗\n;\1╠╬\1╣\n╚╩\1╝/ : s/(.)1/\1\1/ t s/;([^;\n]+)/\1\n\1/ t ``` [Try it online!](https://tio.run/##K05N@f@/WN8QCDQMtTT1H02d8mjqshjDR1Onx@RZg@gFj6auAdGLY/IeTZ31aOpKEGeuPpcVV7G@hp6moX6MYYyhPlcJkGutER1nHZMXq60JEswDC///bwgF//ILSjLz84r/6xYBAA "sed – Try It Online") # Explanation This is pretty simple. Suppose the input is 6 (unary 111111). The first line drops four `1`s and transforms the remaining input into this: ``` ╔╦11╗ ;11╠╬11╣ ╚╩11╝ ``` The third line, in a loop, replaces every `1` with the character preceding it. This creates our columns: ``` ╔╦╦1╗ ;11╠╬11╣ ╚╩11╝ ╔╦╦╦╗ ;11╠╬11╣ ╚╩11╝ ... ╔╦╦╦╗ ;;;╠╬╬╬╣ ╚╩╩╩╝ ``` Notice that this has also duplicated the `;` character. Finally, the fifth line, in a loop, replaces every `;` character with a copy of the line that follows: ``` ╔╦╦╦╗ ;;╠╬╬╬╣ ╠╬╬╬╣ ╚╩╩╩╝ ╔╦╦╦╗ ;╠╬╬╬╣ ╠╬╬╬╣ ╠╬╬╬╣ ╚╩╩╩╝ ╔╦╦╦╗ ╠╬╬╬╣ ╠╬╬╬╣ ╠╬╬╬╣ ╠╬╬╬╣ ╚╩╩╩╝ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *...is it 33? - it costs 5 to convert from one byte string literals (code page indexes) to the Unicode characters.* ``` _2µ“€ðБẋ“¡Ø¤“©ßµ‘js3x€2¦€’+⁽"7ỌY ``` A full program printing the result. **[Try it online!](https://tio.run/##y0rNyan8/z/e6NDWRw1zHjWtObzh8IRHDTMe7uoG8g8tPDzj0BIQY@Xh@SAVM7KKjSuAqowOLQOSjxpmaj9q3Ktk/nB3T@T///9NAA "Jelly – Try It Online")** ### How? ``` _2µ“€ðБẋ“¡Ø¤“©ßµ‘js3x€2¦€’+⁽"7ỌY - Main link: n _2 - subtract 2 µ - start a new monadic chain with n-2 on the left “€ðБ - code page indexes [12, 24, 15] (middle row characters) ẋ - repeat n-2 times (make unexpanded middle rows) “¡Ø¤“©ßµ‘ - code page indexes [[0,18,3],[6,21,9]] (top & bottom) j - join (one list: top + middles + bottom) s3 - split into threes (separate into the unexpanded rows) ’ - decrement n-2 = n-3 ¦€ - sparsely apply to €ach: 2 - at index 2 x€ - repeat €ach (expand centre of every row to n-3 chars) ⁽"7 - literal 9556 + - addition (0->9556; 12->9568; etc...) Ọ - cast to characters (╠; ╔; etc...) Y - join with newlines - implicit print ``` [Answer] # [Rockstar](https://github.com/yanorestes/rockstar-py), ~~150~~ 104 bytes ``` Listen to B let B be-3 X's-1 say "╔"+"╦"*B+"╗" While B-X say "╠"+"╬"*B+"╣" let X be+1 say "╚"+"╩"*B+"╝" ``` [Copy Paste it here!](https://codewithrockstar.com/online) -46 bytes from Shaggy. I was inspired by Shaggy from [this comment.](https://codegolf.stackexchange.com/questions/4244/code-golf-christmas-edition-how-to-print-out-a-christmas-tree-of-height-n/211547?noredirect=1#comment498192_211547) Here's the *real* rock song (sort of). ``` Listen to the bars Knock the bars down, down, down Let the end be the bars Build the end up Shout "╔"+"╦"*the bars+"╗" While the end ain't nothing say "╠"+"╬"*the bars+"╣" Knock the end down Shout "╚"+"╩"*the bars+"╝" Let the prison be gone ``` [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` n=int(input())-3 print("╔"+"╦"*n+"╗\n"+("╠"+"╬"*n+"╣\n")*-~n+"╚"+"╩"*n+"╝") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P882M69EIzOvoLREQ1NT15iroAgkoPRo6hQlbSC5TEkrD0RPj8lT0gYJLwALr4EKLwYKa2rp1oE5s8BSK6FSc5U0//83AQA "Python 3 – Try It Online") [Answer] # Dyalog APL, 71 bytes ``` {('╔',('╠'⍴⍨⍵-2),'╚'),((⍵-3)\⍪('╦',('╬'⍴⍨⍵-2),'╩')),'╗',('╣'⍴⍨⍵-2),'╝'} ``` [Try it online!](http://tryapl.org/?a=%7B%28%27%u2554%27%2C%28%27%u2560%27%u2374%u2368%u2375-2%29%2C%27%u255A%27%29%2C%28%28%u2375-3%29%5C%u236A%28%27%u2566%27%2C%28%27%u256C%27%u2374%u2368%u2375-2%29%2C%27%u2569%27%29%29%2C%27%u2557%27%2C%28%27%u2563%27%u2374%u2368%u2375-2%29%2C%27%u255D%27%7D%2020&run) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~60 52 49 48~~ 36 bytes ``` "╔{Uµ3 ç'╦}╗{UÄ ç" ╠{ç'╬}╣"} ╚{ç'╩}╝ ``` [Try it online!](https://tio.run/##y0osKPn/X@nR1CnVoYe2GiscXq7@aOqy2kdTp1eHHm4BcpW4Hk1dUA0WXgMUXqxUCxSYBRFYCRSY@/@/KQA) # Another version (47 bytes + `-R` flag) ``` "8{Uµ3 ç'J};{UÄ ç"D{ç'P}G"}>{ç'M}A"c_+9500ÃòU+2 ``` Needs the `-R` flag (added to the input field). [Try it online!](https://tio.run/##y0osKPn/X8miOvTQVmOFw8vVvWqtq0MPtwCZSi7VQH5ArbtSrR2I5VvrqHR4U6i2kcKhdcnx2pamBgb//5sq6AYBAA "Japt – Try It Online") ## How does it work? Because I originally assumed the 'door-characters' cost more than one byte, I figured I could save quite a few bytes by encoding them. Then, I subtracted 9500 from the character codes, which left me with the characters `8J; DPG >MA`, which only cost one byte each. Then, I could just add 9500 to each character code, and all would be well. ``` "8{ Uµ 3 ç'J} ;{ UÄ ç"D{ ç'P} G"} >{ ç'M} A"c_+9500à òU+2 "8"+((U-=3 ç'J)+";"+((U+1 ç"D"+(Uç'P)+"G")+">"+(Uç'M)+"A"c_+9500} òU+2 "8"+ +";"+ +">"+ +"A" # Take this string of characters ((U-=3 ç'J) # Repeat "J" input - 3 times (( ç ) # Repeat the string "D"+(Uç'P)+"G" # "D" + input-3 times "P" + "G" U+1 # Input - 2 times (Uç'M) # Repeat "M" input - 3 times c_ } # Take the character code of every character +9500 # Add 9500 to it c_ } # And convert it back to a character òU+2 # Split this string on every (input)th character # Print the resulting array, joined with newlines. ``` [Answer] # Ruby, ~~54~~ 52 bytes -2 bytes thanks to ymbirtt. ``` ->n{?╔+?╦*(n-=3)+"╗ "+(?╠+?╬*n+"╣ ")*-~n+?╚+?╩*n+?╝} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6v2v7R1CnaQGKZlkaerq2xprbSo6nTuZS0NYBiC0ASa7TyQGKLuZQ0tXTr8kBCs0DESi0we27t/4LSkmKFtGiz2P8A "Ruby – Try It Online") ## Ungolfed This is super boring: ``` ->n{ ?╔ + ?╦ * (n-=3) + "╗\n" + (?╠ + ?╬ * n + "╣\n") * -~n + ?╚ + ?╩ * n + ?╝ } ``` [Answer] # Java 8, 102 + 101 bytes ``` java.util.function.BiFunction<String,Integer,String>r=(c,n)->"".valueOf(new char[n]).replace("\0",c); n->{n-=3;return "╔"+r.apply("╦",n)+"╗\n"+r.apply('╠'+r.apply("╬",n)+"╣\n",-~n)+"╚"+r.apply("╩",n)+"╝";} ``` This is another string repeater of the same length: ``` java.util.function.BiFunction<String,Integer,String>r=(c,n)->{String p=c;for(;--n>0;p+=c);return p;} ``` [Try it online!](https://tio.run/##bZBBS8MwFMfP9lOEXNa6Nih6q@3Bg@BBPOy47RCzrKamryFNK2PUT@EQBEEQhIGfal@kZjTVCeb0Xt4v///LP6cNjUrFIV88dKJQpTYot3ekNkKSZQ3MiBLIcex5qr6TgiEmaVWhGyoArT3kTmWosbN/Xl6KK1deTIwWkIXXYHjGddi3qU58FkIQpRiThsqa3y594I@I3VM9hXlANFeSMu7j2QkOWRB7R87tR3hQRE4SKZSgDqJ0DVFyFmtuag14t3nGY02oUnLl2@4TW9uxLV5m8DsY7Tbvo0Psa8A@LBZGT33z@kdqOzBvOG47m9U@E5eXW7YpxQIVNjW/X3I6R1RnVXAQ4mRVGV6QsjZEWcT4yjmcngf223uk9druGw "Java (OpenJDK 8) – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~Score 123 (141 bytes)~~ Score 118 (136 bytes) ``` n=>{string a="╔",b="╠",c="╚";for(int i=3;i++<n;a+="╦",b+="╬")c+="╩";a+="╗\n";for(b+="╣\n";n-->2;)a+=b;return a+c+"╝";} ``` [Try it online!](https://tio.run/##Sy7WTc4vSv2fnJNYXKwQwFXNpQAExSWJJZnJCmX5mSkKvomZeRqaYGGIJAgEVxaXpObquZXmJdtk5pXoFJcUZeal2ym4Kdgq/M@ztauGCCgk2io9mjpFSScJRC9Q0kkG0bOUrNPyizSA@hQybY2tM7W1bfKsE7VBUsuASsGMNUqayWDGSiWo1PSYPIg@iILFIG6erq6dkbUmUEGSdVFqSWlRnkKidrI2UHquknXtf2suTqhDnfPzivNzUvXCizJLUjXcNEw0Na3RPYOqRikmD2gDIVVuGhZUM8nIAGZULVct138A "C# (.NET Core) – Try It Online") -5 bytes thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ### Explanation: ``` n => { string a = "╔", b = "╠", c = "╚"; //Initialize the first, last and the middle lines with the starting character. for (int i = 3; i++ < n; //Loop n-3 times a += "╦", b += "╬") //Add the middle character to the first and middle line. c += "╩"; //Add the middle character to the last line. a += "╗\n"; //Add the end character to the first line. for (b += "╣\n"; //Add the end character to the first line. n-- > 2;) //Loop n-2 times. a += b; //Add the middle line to the first line. return a + c + "╝"; //Add the last line and the final character and return. } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÷ÅoB↔╒╢Fm|╦a⌐á5µ┐»♫÷d╕Ñ ``` [Run and debug it](https://staxlang.xyz/#p=f68f6f421dd5b6466d7ccb61a9a035e6bfaf0ef664b8a5&i=4%0A8%0A20&a=1&m=2) Here's the ungolfed version. Amusingly, it's actually smaller for stax *not* to use the literal characters because including them as a literal would prevent source packing. ``` "2Pfj_EQGG]T"! packed representation of the 9 characters 3/ split into groups of 3 GG call into trailing program twice m print each row } trailing program begins here 1|xv\ [1, --x - 1]; x starts as original input :B repeat each element corresponding number of times effectively, this repeats the internal row of the matrix M transpose door; this way it expands the two dimensions ``` [Run this one](https://staxlang.xyz/#c=%222Pfj_EQGG]T%22%21%09packed+representation+of+the+9+characters%0A3%2F++++++++++++%09split+into+groups+of+3%0AGG++++++++++++%09call+into+trailing+program+twice%0Am+++++++++++++%09print+each+row%0A%7D+++++++++++++%09trailing+program+begins+here%0A1%7Cxv%5C+++++++++%09[1,+--x+-+1]%3B+x+starts+as+original+input%0A%3AB++++++++++++%09repeat+each+element+corresponding+number+of+times%0A++++++++++++++%09effectively,+this+repeats+the+internal+row+of+the+matrix%0AM+++++++++++++%09transpose+door%3B+this+way+it+expands+two+different+dimensions&i=4%0A8%0A20&a=1&m=2) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes ``` 3-…╩╬╦S×`…╔ÿ╗Š…╠ÿ╣IÍ×s…╚ÿ╝Jä» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fWPdRw7JHU1c@mrrm0dRlwYenJ4D5Uw7vfzR1@tEFYM4CEGex5@Hew9OLwQKzQAJzvQ4vObT7/38LAA "05AB1E – Try It Online") [Answer] # Swift, 161 bytes ``` let f:(String,Int)->String={String(repeating:$0,count:$1)};var p={i in print("╔\(f("╦",i-3))╗\n\(f("╠\(f("╬",i-3))╣\n",i-2))╚\(f("╩",i-3))╝")} ``` Un-golfed: ``` let f:(String,Int)->String = { String(repeating:$0,count:$1) } var p={ i in print("╔\(f("╦",i-3))╗\n\(f("╠\(f("╬",i-3))╣\n",i-2))╚\(f("╩",i-3))╝") } ``` You can try this answer out [here](http://swift.sandbox.bluemix.net/#/repl/594299670d43350685451e57) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 78 bytes ``` [:-3|X=X+@╦`]?@╔`+X+@╗`[b-2|Y=Z[b-3|Y=Y+@╬`]?@╠`+Y+@╣`}[b-3|W=W+@╩`]?@╚`+W+@╝` ``` Fortunately, all of the symbols used in out cell door are on the QBasic codepage. ## Explanation ``` The TOP [:-3| FOR a = 1 to n-3 (-1 for the width, -2 for beginning and end) X=X+@╦`] Build out X$ with the parts of the middle-top ?@╔`+X+@╗` Then print that preceded and followed by the corners ┘ Syntactic linebreak The MIDDLE [b-2| FOR c = 1 to n-2 (all the middle rows) Y=Z Reset Y$ to "" Build up the middle rows in the same way as the top, just with different symbols and once for each middle row [b-3|Y=Y+@╬`]?@╠`+Y+@╣` } Close the FOR loop The BOTTOM The same as the top, just with different symbols [b-3|W=W+@╩`]?@╚`+W+@╝` ``` ## Sample Output ``` Command line: 7 ╔╦╦╦╦╗ ╠╬╬╬╬╣ ╠╬╬╬╬╣ ╠╬╬╬╬╣ ╠╬╬╬╬╣ ╠╬╬╬╬╣ ╚╩╩╩╩╝ ``` [Answer] # [PHP](https://php.net/), 131 bytes, 113 chars ``` for($z=str_split("╔╠╚╦╬╩╗╣╝",3);$i<$a=$argn;)echo str_pad($z[$b=$i++?$i<$a?1:2:0],3*$a-3,$z[$b+3]),$z[$b+6],"\n"; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZKJk/T8tv0hDpcq2uKQovrggJ7NEQ@nR1CmPpi54NHXWo6nLHk1d82jqykdTpz@auvjR1LlKOsaa1iqZNiqJtmAjrDVTkzPyFUCaCxJTgOZEqyTZqmRqa9uDFdkbWhlZGcTqGGupJOoa64CltY1jNaEss1gdpZg8oBv@f83L101OTM5IBQA "PHP – Try It Online") # [PHP](https://php.net/), 133 bytes, 115 chars ``` for(;$i<$a=$argn;)echo str_pad(["╔","╠","╚"][$b=$i++?$i<$a?1:2:0],3*$a-3,["╦","╬","╩"][$b]),["╗","╣","╝"][$b],"\n"; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmerZKJk/T8tv0jDWiXTRiXRFixqrZmanJGvUFxSFF@QmKIRrfRo6hQlHSC5AEzOUoqNVkmyVcnU1rYH67I3tDKyMojVMdZSSdQ11gGpXwZWuQZMrgSrj9UES0wHCy0Gk3MhEjpKMXlAV/z/mpevm5yYnJEKAA "PHP – Try It Online") [Answer] ## JavaScript (ES6), 86 bytes This is significantly longer than [the other JS answer](https://codegolf.stackexchange.com/a/126626/58563), but I wanted to give it a try with an alternate method. ``` n=>(g=i=>--i?`╬╣╠╩╝╚╦╗╔ `[(j=i%n)?!--j+2*!(n-j-2)+3*(i<n)+6*(i>n*n-n):9]+g(i):'')(n*n) ``` ### How? We assign a weight to each edge of the grid: 1 for right, 2 for left, 3 for bottom and 6 for top. The sum of the weights gives the index of the character to use. ``` 8666667 0 1 2 3 4 5 6 7 8 2000001 ╬ ╣ ╠ ╩ ╝ ╚ ╦ ╗ ╔ 2000001 2000001 2000001 2000001 2000001 5333334 ``` ### Demo ``` let f = n=>(g=i=>--i?`╬╣╠╩╝╚╦╗╔ `[(j=i%n)?!--j+2*!(n-j-2)+3*(i<n)+6*(i>n*n-n):9]+g(i):'')(n*n) console.log(f(8)) ``` [Answer] # JavaScript (ES6), ~~80~~ 74 bytes ``` n=>`╔${"╦"[a="repeat"](n-=3)}╗${` ╠${"╬"[a](n)}╣`[a](n+1)} ╚${"╩"[a](n)}╝` ``` [Answer] ## Batch, 126 bytes ``` @set s= @for /l %%i in (4,1,%1)do @call set s=%%s%%Î @echo É%s:Î=Ë%» @for /l %%i in (3,1,%1)do @echo Ì%s%¹ @echo È%s:Î=Ê%¼ ``` Works in CP437 or CP850. Looks like this in those code pages: ``` @set s= @for /l %%i in (4,1,%1)do @call set s=%%s%%╬ @echo ╔%s:╬=╦%╗ @for /l %%i in (3,1,%1)do @echo ╠%s%╣ @echo ╚%s:╬=╩%╝ ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~56~~ 50 bytes ``` .+ $*╬╣ ^╬╬╬ ╠ .? $_¶ T`╠╬╣`╔╦╗`^.* T`╠╬╣`╚╩╝`.*¶$ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRevR1DWPpi7migPTIMT1aOoCLj17LpX4Q9u4QhKAPIgSIGvKo6nLHk2dnhCnp4UmM@vR1JWPps5N0NM6tE3l/38LAA "Retina – Try It Online") Works by building up a square of ╬s and then fixing up the edges (in particular three colums are deleted when the sides are added). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 67 bytes ``` '╔'+'╦'*($x=$args[0]-3)+'╗';,('╠'+'╬'*$x+'╣')*($x+1);'╚'+'╩'*$x+'╝' ``` Takes input `$args[0]`, subtracts `3`, saves that into `$x`, uses that in the construction of the top of the door to output the appropriate number of middle sections. Then we're outputting the middle rows, of which we have `$x+1` of. Finally, the bottom row is similar to the top row. All of those are left on the pipeline, and the implicit `Write-Output` inserts a newline between elements for free. [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X/3R1Cnq2kBymbqWhkqFrUpiUXpxtEGsrrEmSHS6urWOBpBeAFazRl1LpQLEWKyuCVKtbahpDeTNAkuuhEnOVf///78FAA "PowerShell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 61 60 characters of code (90 including the multibyte door characters) + 1 for `-p` ``` $_='╔'.'╦'x($n=$_-3)."╗\n";$_.=y/╔╦╗/╠╬╣/r x++$n.y/╔╦╗/╚╩╝/r ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lb90dQp6npAcpl6hYZKnq1KvK6xpp7So6nTY/KUrFXi9Wwr9YFKgPJAISBrwaOpax5NXaxfpFChra2Sp4cqO@vR1JWPps7VL/r/3@RffkFJZn5e8X9dX1M9A0OD/7oFAA "Perl 5 – Try It Online") [Answer] # C# (.NET Core), 130 bytes ``` n=>"╔"+R("╦",n-=3)+"╗\n"+R("╠"+R("╬",n)+"╣\n",-~n)+"╚"+R("╩",n)+"╝";string R(string c,int n){string r=c;for(;n-->1;r+=c);return r;} ``` [Port of *@RobertoGraham*'s Java 8 answer](https://codegolf.stackexchange.com/a/142008/52210), after I golfed about 70 bytes. [Try it online.](https://tio.run/##Sy7WTc4vSv2fnJNYXKzgW82loFBckliSmaxQlp@ZouCbmJmnoQkSVVAIriwuSc3VcyvNS7bJzCvRASosysxLt1NwU7BV@J9na6f0aOoUJe0gDSC9TEknT9fWWFMbyJ4ekwcVXQCl1wBlwVKLgVI6unUQziyo7EqY7Fwla4gVCkEaUEayDtBmhTzNaii/yDbZOi2/SMM6T1fXztC6SNs2WdO6KLWktChPoci69j@Su53z84rzc1L1wosyS1I13DRMNDWtuXDJ@2TmpWrgkQfqt6BQv5EBxIBarlqu/wA) [Answer] # [MAWP](https://esolangs.org/wiki/MAWP), 73 bytes ``` @=MM"╔":!3-["╦":1-]`"╗ ":2-["╠":M3-["╬":1-]`"╣ ":1-]`"╚":M3-["╩":1-]`"╝": ``` [Try it!](https://8dion8.github.io/MAWP/v2.0?code=%40%3DMM%22%E2%95%94%22%3A!3-%5B%22%E2%95%A6%22%3A1-%5D%60%22%E2%95%97%0A%22%3A2-%5B%22%E2%95%A0%22%3AM3-%5B%22%E2%95%AC%22%3A1-%5D%60%22%E2%95%A3%0A%22%3A1-%5D%60%22%E2%95%9A%22%3AM3-%5B%22%E2%95%A9%22%3A1-%5D%60%22%E2%95%9D%22%3A&input=4) Note the strings with newlines [Answer] # Mathematica, 106 bytes ``` (T[a_,b_,c_]:=a<>Table[b,#-3]<>c;w=Column;w[{T["╔","╦","╗"],w@Table[T["╠","╬","╣"],#-2],T["╚","╩","╝"]}])& ``` [Answer] # oK, 38 chars ``` `0:"╔╠╚╦╬╩╗╣╝"{+x+/:3*0,2_x}@&1,|1,-2+ ``` [Try it online.](http://johnearnest.github.io/ok/?run=f%3A%600%3A%22%E2%95%94%E2%95%A0%E2%95%9A%E2%95%A6%E2%95%AC%E2%95%A9%E2%95%97%E2%95%A3%E2%95%9D%22%7B%2Bx%2B%2F%3A3%2a0%2C2_x%7D%40%261%2C%7C1%2C-2%2B%0Af%274%208%2020%3B) k does not seem to want to handle unicode well, so I went with oK. [Answer] # [J](http://jsoftware.com/), ~~41~~ 37 bytes ``` ucp@'╬╠╣╦╔╗╩╚╝'{~1 1|.{.&6 3+/<:{.2,* ``` [Try it online!](https://tio.run/##AVYAqf9q//9mPS4gdWNwQCfilazilaDilaPilabilZTilZfilanilZrilZ0ne34xIDF8LnsuJjYgMysvPDp7LjIsKv9lY2hvQGYgZXZlcnkgNyA2IDUgNCAz/w) Default box drawing takes [13 bytes](https://tio.run/##y/r/P81WT0FXzVDBSMXGITW3oKTyf2pyRr5DmkJqWWpRpYK5gpmCqYKJgvF/AA), unfortunately the best way of [replacing the characters](https://tio.run/##AVoApf9q//9mPS4gdWNwQCfilZTilabilZfilaDilazilaPilZrilanilZ0ne35fMTYrMyB1OjEiOi0mMSAyJDxAZW1wdHn/ZWNob0BmIGV2ZXJ5IDcgNiA1IDQgM/8) I could find costs 28. ]
[Question] [ # Definition * \$a(0) = 0\$ * \$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$ # Task Given non-negative integer \$n\$, output \$a(n)\$. # Testcases ``` n a(n) 0 0 1 1 2 1 3 2 4 3 5 4 6 4 7 5 8 5 9 6 10 7 11 7 12 8 13 9 14 10 15 10 16 11 17 12 18 13 19 13 20 14 10000 6823 ``` # References * [WolframMathWorld](http://mathworld.wolfram.com/HofstadterH-Sequence.html) * [OEIS A005374](https://oeis.org/A005374) [Answer] ## Haskell, ~~23~~ 22 bytes ``` f 0=0 f n=n-f(f$f$n-1) ``` Simply uses the definition of the sequence. `f(f$f$n-1)` is equivalent to `f (f (f (n-1)))`. Test: ``` main = putStrLn . show $ map f [0..20] -- => [0,1,1,2,3,4,4,5,5,6,7,7,8,9,10,10,11,12,13,13,14] ``` Thanks to [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg) for a byte! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’ßßßạµṠ¡ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCZw5_Dn8Of4bqhwrXhuaDCoQ&input=&args=MjA) or [verify the smaller test cases](http://jelly.tryitonline.net/#code=4oCZw5_Dn8Of4bqhwrXhuaDCoQowcjIwwrXFvMOH4oKsRw&input=). ### How it works ``` ’ßßßạµṠ¡ Main link. Argument: n µṠ¡ Execute the preceding chain sign(n) times. ’ Decrement n, yielding n - 1. ßßß Recursively call the main link thrice. ạ Take the absolute difference of n and the result. ``` [Answer] ## Mathematica, 20 bytes Byte count assumes ISO 8859-1 (or compatible) encoding and `$CharacterEncoding` set to a matching value, like the Windows default `WindowsANSI`. ``` ±0=0 ±n_:=n-±±±(n-1) ``` This defines a unary operator `±`. [Answer] # J, ~~14~~ 12 bytes ``` -$:^:3@<:^:* ``` Saved 2 bytes thanks to @[Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun). Computes the result by calling itself recursively when *n* > 0 three times on *n*-1 and subtracting that result from *n*. There is a different situation for the base case when *n* = 0. There it computes *n*-*n* which equals 0. ``` a(n) = n - n = 0 if n = 0 n - a(a(a(n-1))) if n > 0 ``` [Try it here.](http://tryj.tk) ## Explanation ``` -$:^:3@<:^:* Input: n * Get the sign of n (n = 0 => 0, n > 0 => 1) ^: Execute that many times (0 times means it will just be an identity function) <: Decrement n $: Call itself recursively ^:3 three times @ on n-1 - Subtract that result from n and return ``` [Answer] # Julia, 16 bytes ``` !n=n>0&&n-!!!~-n ``` [Try it online!](http://julia.tryitonline.net/#code=IW49bj4wJiZuLSEhIX4tbgoKZm9yIG4gaW4gMDoyMAogICAgQHByaW50ZigiJTJ1ICUydVxuIiwgbiwgIW4pCmVuZA&input=) ### How it works We redefine the unary operator `!` for our purposes. If **n = 0**, the comparison `n>0` returns *false* and so does `!`. Otherwise, the code after `&&` gets executed. `~-n` is equivalent to `(n-1)` in two's complement, `!!!` recursively calls `!` thrice on **n - 1**, and the resulting value is subtracted from **n**. [Answer] # Python, 31 bytes ``` a=lambda n:n and n-a(a(a(n-1))) ``` Recursion limit and time constraints make above function impractical, but in theory it should work (and does work for small n). [Answer] ## JavaScript (ES6), 52 bytes ``` n=>[0,...Array(n)].reduce((p,_,i,a)=>a[i]=i-a[a[p]]) ``` I could have been boring and written the recursive version but this version is much faster (easily coping with the last test case) and also uses `reduce` so that's a plus! [Answer] ## [Retina](https://github.com/m-ender/retina/), ~~49~~ 43 bytes ``` .+ $*1: {`^1(1*): $1:::-1$1 }`^:*(1*)-\1 1 ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoxOgp7YF4xKDEqKToKJDE6OjotMSQxCn1gXjoqKDEqKS1cMQoKMQ&input=MTA) [Answer] ## CJam, ~~13~~ 12 bytes *Thanks to Dennis for saving 1 byte.* ``` ri0{_(jjj-}j ``` [Test it here.](http://cjam.aditsu.net/#code=ri0%7B_(jjj-%7Dj&input=20) [Answer] # R, ~~42~~ 41 bytes ``` a=function(n)ifelse(n<1,0,n-a(a(a(n-1)))) ``` Usage: ``` > a(1) 1 > a(10) 7 ``` This recursive approach doesn't scale well for larger values of `n` though. [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), 6 bytes Code: ``` nbaa-0 ``` Expanded version: ``` a(n) = nbaa- a(0) = 0 ``` Code: ``` n # Push n b # Calculate a(n - 1) a # Calculate a(a(n - 1)) a # Calculate a(a(a(n - 1))) - # Subtract a(a(a(n - 1))) from n ``` [Try it online!](http://oasis.tryitonline.net/#code=bmJhYS0w&input=&args=MjA) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ 17 bytes ``` {⍵=0:0⋄⍵-∇⍣3⊢⍵-1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR71ZbAyuDR90tQJbuo472R72LjR91LQLxDGv/pz1qm/Cot@9R31RP/0ddzYfWGz9qmwjkBQc5A8kQD8/g/2mHVhjoPOrdbGoKAA "APL (Dyalog Unicode) – Try It Online") Surprisingly, there's no APL answer to this challenge. This is a literal implementation of the function in the OP. TIO times out for \$n>90\$. Saved a byte thanks to @Zacharý. [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), ~~58~~ 55 bytes ``` 0000000: 16e0d7 bdcdf8 8cdf1b e6cfbb 840d3f bf659b 38e187 ..............?.e.8.. 0000015: f8639b 39dc37 fc893f 666c05 7e7ed9 b88b3f ae0d3f .c.9.7..?fl.~~...?..? 000002a: 676ed8 bd9940 7fdc3b 36619e f1 gn...@..;6a.. ``` Handles inputs up to **400** reasonably well, but run time increases dramatically after that point. [Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bWluLCBzZXQgbnVtb3V0CgpnZXQKam1wCglqbXAKCQlyd2QgMywgYWRkIDEsIHJ3ZCAxLCBhZGQgMSwgZndkIDQsIHN1YiAxCglqbnoKCXJ3ZCAzLCBzdWIgMQpqbnoKcndkIDMsIGFkZCAxLCBmd2QgMgpqbXAKCXJ3ZCAxLCBzdWIgMSwgZndkIDMsIHN1YiAxLCBmd2QgMiwgYWRkIDMKCWptcAoJCXJ3ZCAyCgkJam1wCgkJCXJ3ZCAzCgkJam56CgkJZndkIDYsIGdldCwgcndkIDQsIHN1YiAxCgkJam1wCgkJCWZ3ZCAxLCBzdWIgMQoJCQlqbXAKCQkJCXJ3ZCAzCgkJCWpuegoJCQlzdWIgMQoJCQlqbXAKCQkJCWZ3ZCAzCgkJCWpuegoJCQlyd2QgNCwgc3ViIDEKCQlqbnoKCQlmd2QgMQoJCWptcAoJCQlyd2QgMSwgYWRkIDEsIGZ3ZCAxLCBhZGQgMQoJCWpuegoJCXN1YiAxLCBmd2QgMywgc3ViIDEKCQlqbXAKCQkJZndkIDMKCQlqbnoKCQlyd2QgMSwgc3ViIDEKCWpuegoJcndkIDIsIGdldAoJbm9wCgkJcndkIDMKCWpuegoJZndkIDMsIGdldCwgcndkIDIKCWptcAoJCWZ3ZCAyLCBhZGQgMQoJCWptcAoJCQlmd2QgMwoJCWpuegoJCXJ3ZCAxLCBhZGQgMSwgcndkIDIKCQlqbXAKCQkJcndkIDMKCQlqbnoKCQlmd2QgMSwgc3ViIDEKCWpuegoJZndkIDIKCWptcAoJCXJ3ZCAyLCBhZGQgMSwgZndkIDIsIHN1YiAxCglqbnoKCW5vcAoJCWdldCwgZndkIDMKCWpuegoJcndkIDEsIGFkZCAxLCBmd2QgMgpqbnoKcndkIDIsIHN1YiAxCmptcAoJcndkIDEsIHN1YiAxLCBmd2QgMSwgc3ViIDEKam56CnJ3ZCAxLCBwdXQ&input=MjA) Check *Debug* to see the generated SBIN code. ### Sesos assembly The binary file above has been generated by assembling the following SASM code. ``` set numin, set numout get jmp jmp rwd 3, add 1, rwd 1, add 1, fwd 4, sub 1 jnz rwd 3, sub 1 jnz rwd 3, add 1, fwd 2 jmp rwd 1, sub 1, fwd 3, sub 1, fwd 2, add 3 jmp rwd 2 jmp rwd 3 jnz fwd 6, get, rwd 4, sub 1 jmp fwd 1, sub 1 jmp rwd 3 jnz sub 1 jmp fwd 3 jnz rwd 4, sub 1 jnz fwd 1 jmp rwd 1, add 1, fwd 1, add 1 jnz sub 1, fwd 3, sub 1 jmp fwd 3 jnz rwd 1, sub 1 jnz rwd 2, get nop rwd 3 jnz fwd 3, get, rwd 2 jmp fwd 2, add 1 jmp fwd 3 jnz rwd 1, add 1, rwd 2 jmp rwd 3 jnz fwd 1, sub 1 jnz fwd 2 jmp rwd 2, add 1, fwd 2, sub 1 jnz nop get, fwd 3 jnz rwd 1, add 1, fwd 2 jnz rwd 2, sub 1 jmp rwd 1, sub 1, fwd 1, sub 1 jnz rwd 1, put ``` [Answer] # LISP, 61 bytes ``` (defun H(N)(if(= N 0)(return-from H 0)(- N(H(H(H(- N 1))))))) ``` Probably not the optimal solution, but it works. [Answer] # Java 7, 42 bytes ``` int c(int n){return n>0?n-c(c(c(n-1))):0;} ``` **Ungolfed & test cases:** [Try it here.](https://ideone.com/KFLVfm) ``` class Main{ static int c(int n){ return n > 0 ? n - c(c(c(n-1))) : 0; } public static void main(String[] a){ for(int i = 0; i < 21; i++){ System.out.println(i + ": " + c(i)); } System.out.println("1000: " + c(1000)); } } ``` **Output:** ``` 0: 0 1: 1 2: 1 3: 2 4: 3 5: 4 6: 4 7: 5 8: 5 9: 6 10: 7 11: 7 12: 8 13: 9 14: 10 15: 10 16: 11 17: 12 18: 13 19: 13 20: 14 (last case takes too long..) ``` [Answer] # Ruby, 27 bytes The obvious implementation. ``` a=->n{n<1?0:n-a[a[a[n-1]]]} ``` This is a longer, faster answer that caches previous entries in the sequence. Both answers only work for versions after 1.9, as that was when `->`, the stabby lambda, was introduced to Ruby. ``` ->n{r=[0];i=0;(i+=1;r<<i-r[r[r[i-1]]])while i<n;r[n]} ``` [Answer] ## C#, 35 bytes ``` int a(int n)=>n>0?n-a(a(a(n-1))):0; ``` [Answer] # Golfscript, ~~26~~ 25 bytes ``` ~~~[0]{....,(===\.,@-+}@\*)\;~~ ~[0]{...)\;==\.,@-+}@*)\; ``` [Try it online!](http://golfscript.tryitonline.net/#code=flswXXsuLi4pXDs9PVwuLEAtK31AKilcOw&input=MTAwMDA) Locally `10000` takes less than half a second. [Answer] # C, ~~35~~ 32 bytes *Saved 3 bytes thanks to @PeterTaylor!* ``` a(n){return n?n-a(a(a(n-1))):0;} ``` [Try it on Ideone!](https://ideone.com/8O5mPR) [Answer] # Javascript ES6, 22 bytes ``` a=n=>n&&n-a(a(a(n-1))) ``` I'll be boring and do the recursive version :P [Answer] ## VBA, 69 bytes ``` Function H(N):ReDim G(N):For j=1To N:G(j)=j-G(G(G(j-1))):Next:H=G(N) ``` Works in the blink of an eye on the test set, slows down a little above n=1000000, runs into a memory wall a little above n=25 million. [Answer] # Pyth, 10 bytes ``` L-WbbyFtb3 ``` Defines a function `y`. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=L-WbbyFtb3%0Ay20&debug=0) This uses a relative new feature of Pyth. You can apply a function multiple times using the fold-syntax. It doesn't actually save any bytes, I used it just for demonstration purposes. ### Explanation: ``` L-WbbyFtb3 L define function y(b), that returns: b b -Wb and subtract the following if b>0 yF 3 y applied three times to tb b - 1 ``` [Answer] # Maple, ~~28~~ 26 bytes ``` `if`(n=0,0,n-a(a(a(n-1)))) ``` Usage: ``` > a:=n->ifelse(n=0,0,n-a(a(a(n-1)))); > seq(a(i),i=0..10); 0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7 ``` [Answer] # dc, 34 bytes ``` dsn[zdddd1-;a;a;a-r:aln!=L]dsLx;ap ``` Input is taken from the top of the stack. This must be the only item on the stack, because the stack depth is used as a counter. Example of usage: ``` $ dc 10000dsn[zdddd1-;a;a;a-r:aln!=L]dsLx;ap ``` This is a fairly straightforward implementation of the sequence definition: ``` dsn # Store n as `n', and keep a copy as a depth buffer (see below) [ # Open loop definition z # Push stack depth i for i-th term dddd # Duplicate stack depth four times, for a total of five copies 1- # Get i-1 for use as index to previous term # Note that if we hadn't duplicated n above, or left something else # on the stack, 0-1 would be -1, which is not a valid array index ;a;a;a # Fetch a(a(a(i-1))) - # Calculate i-a(a(a(i-1))) r # Arrange stack to store i-th term: TOS | i (i-a(a(a(i-1)))) :a # Store i-th term in array `a' ln!=L # Load n. If n!=i, we're not done calculating terms yet, so execute loop ] # Close loop definition. Note that we started with five copies of i: # i-1 was used to get last term # i-a(...) was used to calculate current term # ... i :a was used to store current term # i ln !=L was used to check loop exit condition # One copy of i is left on the stack to increment counter dsLx # Duplicate loop macro, store it, and execute copy ;a # Last i stored on stack from loop will equal n, so use this to get a(n) p # Print a(n) ``` Anyways, it started out straightforward...then the golfing happened. [Answer] # [Common Lisp](http://www.clisp.org/), 44 bytes ``` (defun f(x)(if(= x 0)0(- x(f(f(f(1- x))))))) ``` [Try it online!](https://tio.run/##Vc5LCsMwDEXReVbhoTQo@DnpJ4OuJonAEEJoU/DuXdNA0bMmviDQmdb83muVebHPFkyKSjZ5hhKiRrmEIvYbtK@er8r@ytsh1la0@wd8JB@9j8HH1cfNx93Hw8dIR5lABhACpAAxQA4QBCQBUUCW1Cz1Cw "Common Lisp – Try It Online") [Answer] ## C++ ( MSVC, mainly ) ### Normal version : 40 bytes ``` int a(int n){return n?n-a(a(a(n-1))):0;} ``` ### Template meta programming version : 130 bytes ``` #define C {constexpr static int a(){return template<int N>struct H C N-H<H<H<N-1>::a()>::a()>::a();}};template<>struct H<0>C 0;}}; ``` Usage : ``` std::cout << a(20) << '\n'; // Normal version std::cout << H<20>::a() << '\n'; // Template version ``` The template version is the fastest code, since there's nothing faster than moving a value into a register => with optimization, `H<20>::a()` compile as : ``` mov esi, 14 ``` For 10000, the recursive version crashes due to a stack overflow error, and the template version crashes at compile time due to template instantiation depth. GCC goes to 900 ( 614 ) [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` ©aßßßUÉ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=qWHf399VyQ==&input=OA==) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=qWHf399VyQ==&input=MjEKLW0=) (throws an overflow error for 10000) [Answer] # [D](https://dlang.org/), 36 bytes ``` T a(T)(T n){return n?n---n.a.a.a:0;} ``` [Try it online!](https://tio.run/##FcMxDoAgDADAWV7RsR0wxFEGP8EHSGBoosUg6kB8e9VcLqkGiBgIAwj1mttZBWQRa62M8Tc7/@hVOMEWWZCgm4G3vdQGR0vjl4s3w1255VUw4uSIvHn0BQ "D – Try It Online") [Answer] # Python 3, 72 bytes ``` def f(n): a=[0];i=0 while n:i+=1;a+=[i-a[a[a[i-i]]]];n-=1 return a[i] ``` [Ideone it!](http://ideone.com/Q32qge) [Answer] ## PowerShell v2+, 56 bytes ``` $a={$n=$args[0];if($n){$n-(&$a(&$a(&$a($n-1))))}else{0}} ``` The PowerShell equivalent of a lambda to form the recursive definition. Execute it via the `&` call operator, e.g. `&$a(5)`. Takes a *long* time to execute -- even `50` on my machine (a recent i5 with 8GB RAM) takes around 90 seconds. ### Faster iterative solution, 59 bytes ``` param($n)$o=,0;1..$n|%{$o+=$_-$o[$o[$o[$_-1]]]};$o[-1]*!!$n ``` Longer only because we need to account for input `0` (that's the `*!!$n` at the end). Otherwise we just iteratively construct the array up to `$n`, adding a new element each time, and output the last one at the end `$o[-1]`. Super-speedy -- calculating `10000` on my machine takes about 5 seconds. ]
[Question] [ As a kind of part 2 to [Hello, World! (Every other character)](https://codegolf.stackexchange.com/questions/128496/hello-world-every-other-character?noredirect=1#comment319193_128496), write a program such that **all three** of these programs print "Hello, World!": the entire program, the 1st, 3rd, 5th, etc. characters of your program, *and* the 2nd, 4th, 6th, etc. If your program is: ``` abc def ``` It should output "Hello, World!", but so should ``` acdf ``` **And** ``` b e ``` No solutions with built-in "Hello, World!"s. [Answer] # x86 machine code, 378 bytes ![demo](https://i.stack.imgur.com/F8uTn.png) **PROG.COM** [Download](https://www.dropbox.com/s/glcf3qm4n2vmuoq/PROG.COM?dl=1) and run it in **MS-DOS** emulator, [DOSBox](https://en.wikipedia.org/wiki/DOSBox) for example. ``` B3 B4 B3 02 90 B3 B3 B4 02 B3 B4 B3 02 90 B3 B2 B3 48 90 B3 B3 B2 48 B3 B2 B3 48 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 65 90 B3 B3 B2 65 B3 B2 B3 65 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 6C 90 B3 B3 B2 6C B3 B2 B3 6C 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 6F 90 B3 B3 B2 6F B3 B2 B3 6F 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 2C 90 B3 B3 B2 2C B3 B2 B3 2C 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 20 90 B3 B3 B2 20 B3 B2 B3 20 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 77 90 B3 B3 B2 77 B3 B2 B3 77 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 6F 90 B3 B3 B2 6F B3 B2 B3 6F 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 72 90 B3 B3 B2 72 B3 B2 B3 72 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 6C 90 B3 B3 B2 6C B3 B2 B3 6C 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 64 90 B3 B3 B2 64 B3 B2 B3 64 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 21 90 B3 B3 B2 21 B3 B2 B3 21 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 CD B3 20 90 B3 B3 CD 20 B3 CD B3 20 90 ``` Also you can download [LEFT.COM](https://www.dropbox.com/s/i2kgco8zi2kjlnx/LEFT.COM?dl=1) and [RIGHT.COM](https://www.dropbox.com/s/xmwrx4mixbbrz23/RIGHT.COM?dl=1) ## How it works and how to run [See answer to part one](https://codegolf.stackexchange.com/a/129328/71612) ## Magic If you want to execute **0xAB** opcode command with one parameter **0xCD**, you write ![Magic](https://i.stack.imgur.com/Neogs.png) ## Generator Run code, get hex. Convert in to binary ``` cat prog.hex | xxd -r -p > PROG.COM ``` ``` function byte2hex(byte){ var ret=byte.toString(16).toUpperCase(); return ret.length==1 ? "0"+ret : ret; } function str2hex(str){ var ret = []; for(var i=0;i<str.length;i++){ ret.push(byte2hex(str.charCodeAt(i))); } return ret; } function genCode(hexArr){ var ret = [["B4","02"]]; for(var i=0;i<hexArr.length;i++){ if(hexArr[i]!=hexArr[i-1]){ ret.push(["B2",hexArr[i]]); } ret.push(["CD","21"]); } ret.push(["CD","20"]); return ret; } function format(arr){ var ret=[],tmp=[]; for(var i=0;i<arr.length;i++){ tmp.push(arr[i]); if(i%16==15 || i==arr.length-1){ret.push(tmp.join(" "));tmp=[];} } return ret.join("\n"); } function magicCode(str,mode){ var ret=[]; var code=genCode(str2hex(str)); for(var i=0;i<code.length;i++){ var ab=code[i][0],cd=code[i][1],tmp; tmp=["B3",ab,"B3",cd,"90","B3","B3",ab,cd,"B3",ab,"B3",cd,"90"]; for(var j=0;j<tmp.length;j++){ if((mode&1 && j%2==0) || (mode&2 && j%2==1)){ret.push(tmp[j])} } } return ret; } const LEFT=1,RIGHT=2,ALL=3; var str=prompt("string","Hello, world!"); var out = ["PROG.COM\n",format(magicCode(str,ALL)),"\n\nLEFT.COM\n",format(magicCode(str,LEFT)),"\n\nRIGHT.COM\n",format(magicCode(str,RIGHT))].join("\n"); document.write(out.replace(/\n/ig,"<br>")); ``` [Answer] # [Python 3](https://docs.python.org/3/), 115 bytes ``` print=="partisn't"; "ran" >="partisn't" ; print((""" "HHeelllloo,, wwoorrlldd!! """[" ) #2">"1":: 3- 1] [ 1:-1 ])) ``` ### Every odd character ``` pit=print;"a">"ats'";pit(" Hello, world! "[ 2>1: -1 :1]) ``` ### Every even character ``` rn="ats'" rn =print rn("""Hello, world!""")#""":3 ][1- ) ``` [Try it online!](https://tio.run/##TY2xCoMwGIR3n@L8O8SADtEtEmffQTJIDVQISUgC2qdPRUrpLcd3d3DhnV/eDSVBgTFWQtxdVorCGvOeHMs0VhRXR5j@Q4zVvWwaIgLNszH2kvdtCxyH9zFau211jatfCByPniYSJCWGDkJjgZCdgOa8XL@VOc2zSfzri5S9/oG4qXwA "Python 3 – Try It Online") This could probably get a lot shorter, but I'm happy I managed to get it to work in Python. Similar to [vroomfondel's answer](https://codegolf.stackexchange.com/a/128524/63641) on the first part. # Boring 93 byte answer ``` """""" print("Hello, world!") """"""# """" pprriinntt((""HHeelllloo,, wwoorrlldd!!"")) #""" ``` ### Every odd character ``` """pit"el,wrd" """ "" print("Hello, world!")#" ``` ### Every even character ``` """ rn(Hlo ol!)"""#"" print("Hello, world!") "" ``` [Try it online!](https://tio.run/##PY0xCkMhEET7PcW6v1DBJkn3Ib13CKmiEEFc2S@YnN6ICZnmMcwMU9/tyeUyDryi1nrQElRJpRnyMWd22FlyUGThm26LALWKpFRKa8YQeR9ne/bZOcTemUVyDkEpImthm5MxHyC@4sMc9sfbvp/vf3NabnwA "Python 3 – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), 45 bytes ``` ! """!!ddllrrooWW oolllleeHH"!!"" >~o <> o < ``` Or just even characters: ``` "!dlroW olleH"!">o< ``` Or just odd characters: ``` !""!dlroW olleH!" ~ >o< ``` Try them online: [original](https://tio.run/##S8sszvj/X1FBSUlJUTElJSenqCg/PzxcQSE/PwcIUlM9PIASSkoKdnX5CjZ2CkDi/38A "><> – Try It Online"), [evens](https://tio.run/##S8sszvj/X0FJMSWnKD9cIT8nJ9VDSVHJLt9GQeH/fwA "><> – Try It Online"), [odds](https://tio.run/##S8sszvj/X1FJSTElpyg/XCE/JyfVQ1FJoU7BLt/m/38A "><> – Try It Online"). The original version pushes "`!!ddllrrooWW oolllleeHH`" to the stack, then the fish bounces between `>~o <`, which deletes a letter, prints two, deletes two, prints two, deletes two, etc. The two half-programs are fairly standard string printing programs. The tricky part was combining `"` and `!` to toggle in and out of string mode in all three programs correctly. [Answer] ## [Befunge-98](https://github.com/catseye/FBBI), 43 bytes ``` 120 x""!!ddllrrooWW ,,oolllleeHH""cckk,,@@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/39DIQKFCSUlRMSUlJ6eoKD8/PFxBQUcnPz8HCFJTPTyUlJKTs7N1dBwc/v8HAA "Befunge-98 – Try It Online") Only the odd ones: ``` 10x"!dlroW ,olleH"ck,@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/39CgQkkxJacoP1xBJz8nJ9VDKTlbx@H/fwA "Befunge-98 – Try It Online") Only the even ones: ``` 2 "!dlroW ,olleH"ck,@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/30hBSTElpyg/XEEnPycn1UMpOVvH4f9/AA "Befunge-98 – Try It Online") ### Explanation The full program: ``` 120 Push 1, push 2, push 0. x Pop 0 (y) and 2 (x) and set the instruction pointer's movement delta to (x,y). That is, run the remainder of the code by skipping every other cell. "!dlroW ,olleH" Push the code points of the output. ck, Print 13 characters from the top of the stack. @ Terminate the program. ``` In the odd program, the `2` is gone, so that `10x` really does nothing at all (it sets the delta to `(1,0)` which is the default anyway). The remainder of the program is then the same. In the even program, we just push the `2` at the beginning which we can ignore entirely. The remainder of the program is the same as before. [Answer] # [Gammaplex](http://esolangs.org/wiki/Gammaplex), 46 bytes ``` // EERRrrXXXX""HHeelllloo,, WWoorrlldd!!""XX ``` [See here.](https://codegolf.stackexchange.com/a/85034/25180) [Interpreter.](https://github.com/graue/esofiles/blob/master/gammaplex/impl/gammaplex.zip) It may need some changes to work in modern compilers. [Answer] # Mathematica, 65 bytes ``` PPrriinntt[[""HHeelllloo,, WWoorrlldd!!""]]Print@"Hello, World!" ``` It throws some warnings, prints `Hello, World!`, and returns `Null PPrriinntt[["" HHeelllloo, Null, "" WWoorrlldd!!]]`. When run as a program (not in the REPL), the return value will not be printed. After removing the even characters: ``` Print["Hello, World!"]Pit"el,Wrd" ``` It prints `Hello, World!`, and returns `"el,Wrd" Null Pit`. After removing the odd characters: ``` Print["Hello, World!"]rn@Hlo ol! ``` It prints `Hello, World!`, and returns `Null ol! rn[Hlo]`. [Answer] ## x86 machine code, 73 bytes Inspired by *Евгений Новиков*'s solution, I thought it should be doable with less tricks, i.e., just jumping around to otherwise "disjoint" codes for all three variants. I'm still trying with a smart variant that uses `lodsb; lodsb` as central point (so only one string constant is needed for all variants) ``` EB 14 00 00 8A 8A 17 16 01 01 B4 B4 09 09 CD CD 21 21 CD CD 20 20 8A 1f 01 B4 09 CD 21 CD 20 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 00 48 48 65 65 6c 6c 6c 6c 6f 6f 2c 2c 20 20 57 57 6f 6f 72 72 6c 6c 64 64 21 21 00 00 ``` If I recall correctly from my childhood days, COM's tiny model starts with `DS=CS=SS` and the code is loaded beginning from `CS:0100h`. I do not assume it is guaranteed that the code is loaded into a zeroed memory block (if it were guaranteed, I could drop two bytes). Disassembly of the long code should be ``` JMP *+14h ; 20 irrelevant bytes MOV DX,message MOV AH,09h INT 21h; print string pointed to by DS:DX INT 20h; exit program message: DB "Hello, World!\0" DB "HHeelllloo,, WWoorrlldd!!\0\0" ``` Disassembly of odd code ``` JMP *+00h MOV DX,message MOV AH,09h INT 21h; print string pointed to by DS:DX INT 20h; exit program ; some irrelevant bytes message: DB "Hello, World!\0" ``` Disassembly of even code: ``` ADC AL,00h MOV DX,message MOV AH,09h INT 21h; print string pointed to by DS:DX INT 20h; exit program ; some irrelevant bytes message: DB "Hello, World!\0" ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 48 bytes ``` G |` HHeelllloo,, WWoorrlldd!! $_& (.)\1t? $1 ``` [Try it online!](https://tio.run/##K0otycxL/P/fXaEmgYvLwyM1NQcI8vN1dBQUwsPz84uKcnJSUhQVuVTi1bi4NPQ0YwxL7LlUDP//BwA "Retina – Try It Online") Odd positions: ``` G| Hello, World! _ ()1?$ ``` [Try it online!](https://tio.run/##K0otycxL/P/fvYbLIzUnJ19HITy/KCdFkSueS0PT0F7l/38A "Retina – Try It Online") Even positions: ``` ` Hello, World!$& .\t 1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fIYHLIzUnJ19HITy/KCdFUUWNSy@mhMvw/38A "Retina – Try It Online") ### Explanation **The full program:** ``` G |` ``` This does nothing at all. The `|` is not an existing configuration option. The `G` makes this a grep stage, but there is really nothing to be grepped and the regex is empty any, so this doesn't do anything. The purpose of this stage is to have two linefeeds in front of the main "Hello, World!" line so that one of them always survives the reduction. The reason for making this a grep stag is that we need to offset the parity of the lines, and grep stages only require a single line. ``` HHeelllloo,, WWoorrlldd!! ``` This turns the (empty) working string into the required output with each character doubled. ``` $_& ``` This does nothing. The regex tries to match a `_` and a `&` after the end of the string which is of course impossible. We'll need those characters in the reduced version though, again to deal with vanishing linefeeds. ``` (.)\1t? $1 ``` Finally, we remove the duplicate characters by replacing `(.)\1` with `$1`. The `t?` is never used but will again be necessary in the reduced versions. **The odd program:** ``` G| Hello, World! ``` The `G` can't match the empty input, but that's why we have the `|` to allow an alternative empty match. This turns the empty working string into the desired output. ``` _ ()1?$ ``` This replaces underscores with `()1?$`, but there are no underscores in the string, so this does nothing. **The even program:** ``` ` Hello, World!$& ``` The ``` just denotes an empty configuration string, so we again use the empty regex to replace the working string with the output. This time we also insert `$&` but that's the match itself, which is empty, of course, so it doesn't do anything. ``` .\t 1 ``` This would replace any character followed by a tab with a `1`, but we don't have any tabs, so this is also a no-op. [Answer] # [Lua](https://www.lua.org), 106 bytes ``` ----[[[[ print("Hello, World!") --[[ ---- ] ] ---- ] ] pprriinntt((""HHeelllloo,, WWoorrlldd!!"")) ----]] ``` [Try it online!](https://tio.run/##RYsxCsAgDEV3TxEzKdh7eAOH4lCwgxCMBHv@NHbpmz789@i5VA/jNNyUPlbAfBNxgsJCzWN0@3Vbggr1H3OK9D7GWiEg5nxbZiGnBFAKswhRa94jxvhVtaq@ "Lua – Try It Online") Alternate 1: ``` --[[ rn(Hlo ol!)-[ --]]-- print("Hello, World!")--] ``` [Try it online!](https://tio.run/##yylN/P9fVzc6mqsoT8MjJ18hP0dRUzeaS1c3NlZXV0GBq6AoM69EQ8kjNScnX0chPL8oJ0VRSRMo/f8/AA "Lua – Try It Online") Alternate #2: ``` --[[pit"el,Wrd" -[-- --]]print("Hello, World!") --] ``` [Try it online!](https://tio.run/##yylN/P9fVzc6uiCzRCk1Rye8KEWJSzdaV1dBgUtXNza2oCgzr0RDySM1JydfRyE8vygnRVFJEyT1/z8A "Lua – Try It Online") Alternator script: [Try it online!](https://tio.run/##RYvBCsMgEETvfoXZk4INtL0FevcPPAQPBYUuWFdWL/l6Y0JL5rDMzswrW/tQfvaO30LcZN2qwNe4c20B88zxHZQWhTE3heuyPPz/u9L7Gfd@G1qHfgXYmBIZ6YhTmECLoxXHSHrpL1MKM2LOrSkFYG0c2ADJGCmdI2JOKYRpAtD6pLzfAQ "Python 3 – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 44 bytes ``` {{HHeelllloo,, WWoorrlldd!!}}ss{{}}ss-X)%L- ``` [Try it online!](https://tio.run/##S85KzP3/v7rawyM1NQcI8vN1dBQUwsPz84uKcnJSUhQVa2uLi6urQaRuhKaqj@7//wA "CJam – Try It Online") [Answer] # [Backhand](https://github.com/GuyJoKing/Backhand), 36 bytes ``` vv^^vv""!!ddllrrooWW ,,oolllleeHH"" ``` [Try it online!](https://tio.run/##S0pMzs5IzEv5/7@sLC6urExJSVExJSUnp6goPz88XEFBRyc/PwcIUlM9PJSU/v8HAA "Backhand – Try It Online") Every other character (in both ways): ``` v^v"!dlroW ,olleH" ``` [Try it online!](https://tio.run/##S0pMzs5IzEv5/78srkxJMSWnKD9cQSc/JyfVQ@n/fwA "Backhand – Try It Online") ### How it works Backhand's IP starts at the first character and bounces back and forth, skipping certain number of steps at once. The initial step size is 3, which can be adjusted with `^` (increase) and `v` (decrease) commands. ``` vv^^vv""!!ddllrrooWW ,,oolllleeHH"" v decrease step size to 2 ^ increase step size to 3 v decrease step size to 2 " ! d l r o W , o l l e H " push the string H halt and print the string v^v"!dlroW ,olleH" v decrease step size to 2 v decrease step size to 1 "!dlroW ,olleH" push the string H halt and print the string ``` [Answer] # PHP, 70 bytes ``` "";echo'Hello, World!'.""//pprriinntt''HHeelllloo,, WWoorrlldd!!'' ;; ``` Odd characters: ``` ";coHlo ol!."/print'Hello, World!'; ``` Even characters: ``` "eh'el,Wrd'"/print'Hello, World!' ; ``` [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` {---- } mmaaiinn==ppuuttSSttrr""HHeelllloo,, WWoorrlldd!!""----}main=putStr"Hello, World!" ``` [Try it online!](https://tio.run/##FcshDsAgDEBRv1NANTsCHo9Ak0AyskJJV9TC2Rn7@v0rPndGXOs9d2oeR60xltKatb2PIeK9CDOAc3lDRCJjlAqBiBkxJa0B/nfWWJrtQ7wwuE3JqECMScNaHw "Haskell – Try It Online") It looks like the comment abuse is too much for the syntax highlighting to handle. `{- ... -}` is an inline or multi-line comment, whereas `--` starts a line comment. **Odd characters:** ``` {--} main=putStr"Hello, World!"--mi=uSrHlo ol! ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1pXt5YrNzEzz7agtCS4pEjJAyicr6MQnl@Uk6KopKubm2lbGlzkkZOvkJ@j@P8/AA "Haskell – Try It Online") **Even characters:** ``` -- main=putStr"Hello, World!"--}anptt"el,Wrd" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X1dXgSs3MTPPtqC0JLikSMkDKJqvoxCeX5SToqikq1ubmFdQUqKUmqMTXpSi9P8/AA "Haskell – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 54 bytes ``` <<<Hello\ world!||eecchhoo HHeelllloo\\ wwoorrlldd!! ``` [Try it online!](https://tio.run/##ZZBBa8MwDIXv@hUvJZ3bwy49Zia3ltz6B3IJtloHjDXssEDb/fbMztigVBch3nufhG7JLS0kjtcxDB5aQx3PJ7VorTv2XnrMEr2tHg9mY5wTAbqOs5RF6XtgnkVi9N7aqlpyloguEiHWgr84YAyo77vUNPtNvdN/m/ab7w9YIeT6jGOYLlDbpFCXHNq25F/FFZjF0slKYCIzTGjfDnjPt@fjzzlu3BAHM3FMjVo5z55a9eFYQE@@FcnGSXES3ZL7/8rvkDmlF9/yAw "Zsh – Try It Online") The main program executes the first statement successfully, so the statement after the boolean `||` is ignored. For odd/even, the `<<<Hello\ world!` becomes either an unterminated `<<heredoc` or a `<file` provided on stdin. Either way, the `||` becomes `|`, and so whatever is output by the first command is piped into and ignored by `echo`. [Answer] ## [LOGO](https://sourceforge.net/projects/fmslogo/), 71 bytes ``` ;;\\ pr[Hello, World!]er "| pprr[[HHeelllloo,, WWoorrlldd!!]] ;;\\ | ``` (the program have a trailing newline) Two removed versions: ``` ;\p[el,Wrd]r" pr[Hello, World!] ;\| ``` and ``` ;\ rHlo ol!e | pr[Hello, World!];\ ``` (the program have a trailing newline) For an explanation what `pr` and `er` do, see [this post](https://codegolf.stackexchange.com/questions/128496/hello-world-every-other-character/129428#129428). In this case, `er` is feed with a word determine procedure name. The `\` is escape character in Logo, which will escape the newline after the end of the comment, therefore make the second line (`rHlo ol!e |`) of second removed program a comment. [Answer] # Javascript,68 bytes ``` //** alert`Hello, World`//**//aalleerrtt``HHeelllloo,, WWoorrlldd`` ``` Odd Characters: ``` /*aetHlo ol`/*/alert`Hello, World` ``` Even Characters: ``` /* lr`el,Wrd/*/alert`Hello, World` ``` Modified version of my answer on the other one. [Answer] ## [Perl 5](https://www.perl.org/), 61 bytes **60 bytes code + 1 for `-p`.** ``` $ _ =$ _ =q";HHeelllloo,, WWoorrlldd!!";;;q##;s/;|.\K.//g## ``` [Try it online!](https://tio.run/##K0gtyjH9/19FIV7BFkwUKll7eKSm5gBBfr6OjoJCeHh@flFRTk5KiqKikrW1daGysnWxvnWNXoy3nr5@urLy//9c//ILSjLz84r/6xYAAA "Perl 5 – Try It Online") ### Every Odd Byte ``` $_="Hello, World!";q#s;.K/g# ``` [Try it online!](https://tio.run/##K0gtyjH9/19BQSXeVskjNScnX0chPL8oJ0VRybpQudhaz1s/Xfn/f65/@QUlmfl5xf91CwA "Perl 5 – Try It Online") ### Every Even Byte ``` $_= q;Hello, World!;;#;/|\./# ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZBodDaIzUnJ19HITy/KCdF0dpa2Vq/JkZPX/n/f65/@QUlmfl5xf91CwA "Perl 5 – Try It Online") [Answer] # [BotEngine](https://github.com/SuperJedi224/Bot-Engine), ~~180~~ 178 bytes Based on my answer to [this](https://codegolf.stackexchange.com/questions/128496/hello-world-every-other-character/156834#156834) question. ``` vv v < eHH eee ell ell eoo e,, e eWW eoo err ell edd e!! >>P e e e e e e e e e e e e e P ``` Odd characters (note the multiple trailing spaces on the last line): ``` v v< eH ee el el eo e, e eW eo er el ed e! >P ``` Even characters: ``` v H e l l o , W o r l d ! > e e e e e e e e e e e e eP ``` [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 52 bytes ``` L @""H!edlllroo,W W,oorlllde!H"" ~@"!dlroW ,olleH" ``` [Try it online!](https://tio.run/##KyrNy0z@/1/BR8FBSclDMTUlJyenKD9fJ1xBIVwnP78IyE1JVfRQUlKoc1BSTAHKhSvo5OfkpHoo/f8PAA "Runic Enchantments – Try It Online") Runic is not usually very good at dealing with radiation as having flow control characters removed at random makes tracing execution a huge pain, but predictable radiation like every other character? Easy, we just encode two programs that are reversed of each other and interleaved, then tack on a third copy for the base execution and control which one is executed with a single character. In program 2, the third copy is garbage that's never seen, and in program 3 it retains the quotes, allowing it to be popped without printing it. Program 1 only executes this part: ``` L @"!dlroW ,olleH" ``` Program 2 only executes this part: ``` " H e l l o , W o r l d ! " @ ``` Like this: ``` "Hello, World!" @!lo olH ``` [Try it online!](https://tio.run/##KyrNy0z@/19BQckjNScnX0chPL8oJ0VRScFBMSdfIT/H4/9/AA "Runic Enchantments – Try It Online") Program 3 only executes this part: ``` L @ " ! d l r o W , o l l e H " ~ " d r W , l e " ``` Like this: ``` L@"!dlroW ,olleH"~"drW,le" ``` [Try it online!](https://tio.run/##KyrNy0z@/9/HQUkxJacoP1xBJz8nJ9VDqU4ppShcJydV6f9/AA "Runic Enchantments – Try It Online") The `"drW,le"` portion is executed, but the `~` immediately pops it off the stack, preserving the desired output. Naively it would appear that a conversion of the ><> answer would result in a shorter program, weighing in at 45 bytes: ``` ! ```!!ddllrrooWW oolllleeHH`!!`` R~$ LR $ L ``` However, Runic has one limitation that ><> does not have: a maximum stack size of 10 + IP's mana (which is initially 10). And `!!ddllrrooWW oolllleeHH` contains 24 characters, causing the IP to bleed mana until it expires just before executing the `R` command, resulting in no output for the base program. [Try it online!](https://tio.run/##KyrNy0z@/19RISEhQVExJSUnp6goPz88XEEhPz8HCFJTPTyAEgkJCkF1Kgo@QQpAwvr/fwA "Runic Enchantments – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 33 bytes ``` \` ð`HHeelllloo,, WWoorrlldd!!`√ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%5C%60%20%C3%B0%60HHeelllloo%2C%2C%20%20WWoorrlldd!!%60%E2%88%9A&inputs=&header=&footer=) ``` `ðHello, World!` ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%C3%B0Hello%2C%20World!%60&inputs=&header=&footer=) ``` \ `Hello, World!√ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%5C%20%60Hello%2C%20World!%E2%88%9A&inputs=&header=&footer=) These all exploit the bug/feature that single special characters in strings are ignored during parsing. ``` \` # Push a backtick (useless) ð # Push a space (useless) `HHeelllloo,, WWoorrlldd!!` # String literal √ # Get every second character ``` ``` ` Hello, World!` # String literal ð # Single non-ascii character (ignored) ``` ``` \ # Push a space `Hello, World! # String literal (unterminated) √ # Single non-ascii character - ignored ``` ]
[Question] [ Your task is to create a program that outputs the string: ``` Hello, Toroidal Earth! ``` with an optional trailing newline. Additionally if I remove the first line1 of your program and add it as a line after the end of your program the new program should be a valid solution to this challenge in the same programming language. So if my program were: ``` use module System.IO, Types.String begin IO with (input as stdin, output as stdout) new "Hello, Toroidal Earth" >> toBytestream >> output end IO closing streams ``` then, its shift: ``` begin IO with (input as stdin, output as stdout) new "Hello, Toroidal Earth" >> toBytestream >> output end IO closing streams use module System.IO, Types.String ``` would also have to be a valid solution, meaning that the next shift: ``` new "Hello, Toroidal Earth" >> toBytestream >> output end IO closing streams use module System.IO, Types.String begin IO with (input as stdin, output as stdout) ``` would *also* have to be a valid program. And so on ad infinitum. Likewise if I remove the final column of the program and insert it before the first column the result must be a valid solution to this challenge in the same programming language. When removing a column if a row doesn't have a character in that column (i.e. it is too short) then you should treat that place as a space character. So for example if my program were: ``` use module System.IO, Types.String begin IO with (input as stdin, output as stdout) new "Hello, Toroidal Earth" >> toBytestream >> output end IO closing streams ``` Then the program: ``` use module System.IO, Types.String begin IO with (input as stdin, output as stdout) tnew "Hello, Toroidal Earth" >> toBytestream >> outpu end IO closing streams ``` should also be a valid solution, and of course any further shifting of it either vertical or horizontal should be as well. All in all these shifts represent rotations on a torus. Answers will be scored in bytes with fewer bytes being better. 1: You may choose to have your lines delimited by '\n' or by '\r\n'. Probably the former. [Answer] # [Cascade](https://github.com/GuyJoKing/Cascade), 36 bytes ``` @l" } """ ETH aoe rrl tol hio !d, "a ``` [Try it online!](https://tio.run/##S04sTk5MSf3/3yFHiauWS0lJics1xIMrMT@Vq6goh6skP4crIzOfSzFFh0sp8f9/AA "Cascade – Try It Online") While Cascade programs default to starting in the top left, but an explicit starting point can be created using a single `@`. This makes the program pretty much entirely immune to any column or row shifts, since all execution wraps around the edges of the playing field like a torus anyway. Note that if you had multiple `@`s, they would be triggered in order of appearance in the program, no longer preserving the behaviour. The naive way of printing a string would be to [print it all in one column](https://tio.run/##S04sTk5MSf3/34FLicuDK5UrBwjzuXS4FLhCgHQREGdypXAlAkUVuFyBdBFXCVcGlyKX0v//AA), however that totals up to 49 bytes because of all the newlines. Instead, I split the string into three parts (coincidentally at each word, and execute each one by (ab)using `}`. One last consideration is put into where the string is split, so the spaces are at the end of the line, saving bytes by leaving them to be implicitly filled in by the interpreter. [Answer] # Unary, **Rev 0 ~~3121491355794998332440739552097977007353231296357070843005722815009035246433220686378881420659391378316482528838109777011691037239240361352724200445025302725444438163079585978557249556~~** **Rev 1** **276014140987112321091243548089349059271143856599044292139902575100947961955482006878466337854296695443646817751973462391672878955178246166009852634302332948 bytes** Unary is an encoding for brainfuck programs where each of the 8 characters that can be used in a valid program corresponds to an octal digit. The program is converted to an octal number `n`, then the Unary output is composed of `n` identical characters (usually 1's.) Since all characters are the same, it is a valid submission for this challenge. See [this question](https://codegolf.stackexchange.com/questions/52712/brainfk-to-unary-and-back) for Brainfuck/Unary converters. The underlying Brainfuck programs (not valid submissions) are below # [brainfuck](https://github.com/TryItOnline/brainfuck), Rev 1, 172 bytes ``` +++[>++>+++>+++>+<<<<-------]>--.>----------.>---..+++.>+++++++.------------.<<<++++++++++++.>>.+++.---.<++++.-----.---.>---.>.<<<---------------.>.>++++++.++.<+++++++.>>+. ``` [Try it online!](https://tio.run/##TY1BCoAwDAQftGRfEPIR8aCCIIIHoe@PqdamQwI5THbXezmuvWynO4DJgJi2GsjHbCI06bw3GRqrW6EMMF4xQDM2h5o2e5Qxy7LkD49fakaB7g8 "brainfuck – Try It Online") # [brainfuck](https://github.com/TryItOnline/brainfuck), Rev 0, 203 bytes ``` -[>+>++>+<<<-----]>+++++++++++++++++++++.>-.+++++++..+++.>-------.------------.<<++++++++++++.>.+++.---.------.-----.---.+++++++++++.>.<<---------------.>-----------.+++++++++++++++++.++.------------.>+. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fN9pO204biGxsbHRBIBbIwwL07HT1YEw9CB8C9HSRgJ6NDaomsFKEKj04qYeqDGo5kkl2yBxM50CMRVKurff/PwA "brainfuck – Try It Online") [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 107 bytes ``` . :-write("Hello, Toroidal Earth!") A. :-write("Hello, Toroidal Earth!"). A. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/X0@BALDSLS/KLEnVUPJIzcnJ11EIyS/Kz0xJzFFwTSwqyVBU0uRy1OMiqEgPqOr/fwA "Prolog (SWI) – Try It Online") SWI doesn't exactly mind syntax errors, so we create two lines which each print the text and overlap by one character. That way when the are roatated there is always exactly one of them intact. We have to add the `A.`s in between lines because without a `.` the SWI parser can get confused. For example if we remove them in the starting program ``` . :-write("Hello, Toroidal Earth!") :-write("Hello, Toroidal Earth!"). ``` The parser doesn't recover from the fail state quick enough to properly parse the second line. `.` seems to be more or less a hard override that tells it to give up on the clause. [Answer] # [Fission](https://github.com/C0deH4cker/Fission), 26 bytes ``` R"Hello, Toroidal Earth!"; ``` [Try it online!](https://tio.run/##S8ssLs7Mz/v/P0jJIzUnJ19HISS/KD8zJTFHwTWxqCRDUcn6/38A "Fission – Try It Online") Unfortunately, Fission is so good at this we don't need to do anything interesting. `R` creates an atom which moves towards the right. As the atom reaches other characters, it executes them. The first character it hits is `"` which activates string mode, in which each further character encountered is output, except `"` which deactivates it. Then, `;` ends the program. Fission's layout is toroidal by default for atoms, so a shifted program like: ``` l Earth!";R"Hello, Toroida ``` [Try it online!](https://tio.run/##S8ssLs7Mz/v/P0fBNbGoJENRyTpIySM1JydfRyEkvyg/MyXx/38A "Fission – Try It Online") behaves exactly the same. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), ~~63 58~~ 67 bytes ``` %?\>>>>>>>>>>>>> >>\"Hello,vV"-+v v-">^ladioroT"<< \+x"EarthvU"-+@v ``` [Try it online!](https://tio.run/##y8kvLvn/X9U@xg4ZcNnZxSh5pObk5OuUhSnpapdxlekq2cXlJKZk5hflhyjZ2HDFaFcouSYWlWSUhQIVOJT9//9f1xEA "Lost – Try It Online") My first try with Lost. This is a 2D language, where the starting position and direction are random. So you never know where the instruction pointer starts and where it goes, but you can direct it. The instruction pointer moves in a toroidal way, meaning that if it reaches the end of a line, it starts the same line again. Likewise with columns. Unfortunately, there is a bug in Lost, that will prevent it from running, when it starts with a space character. So I had to edit it to have no spaces in it and to have equally long lines, resulting in nine bytes more than my previous answer. Explanation: A good portion of the code is just for directing the ip to the start of the code (>, <, v, and ^ instruct the ip to go to that specific direction. "" is a mirror, so the ip will reflect in the intentional way). The code starts in the upper left corner. `%` deactivates the "safe mode". After that, the code will end, when it reaches the `@`. `?\` will start a loop, that empties the stack. (The `?` means "if the stack is not empty, pop an item and ignore the next command"). When the stack is empty, the `\` will reflect the ip into the second line. `\` reflects the ip to the right. `"Hello,vV"` pushes that exact string onto the stack. The `v` is needed to direct the ip to the start, if it starts within the string. `-+` means "invert the last item on the stack and add the last two items together. Basically, it pushes 'v' - 'V' = ' '. Then the ip is redirected into the third row, where it pushes "Toroidal^>" and again calculates '^' - '>' = ' '. In the last row it pushes "EarthvU" and calculates 'v' - 'U' = '!'. Then, the `@` is the end of the code. The contents of the stack are printed implicitly. [Answer] # CSS, 280 bytes ``` :after{content:""}"{}:after{content:""}"{}:after{content:""}"{} body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{} ``` Try the default one: ``` :after{content:""}"{}:after{content:""}"{}:after{content:""}"{} body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{} ``` Try all (WARNING: This may hang your browser!): ``` const source = String.raw` :after{content:""}"{}:after{content:""}"{}:after{content:""}"{} body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{}body:after{content:"Hello, Toroidal Earth!"}"{}/*/}{} `.trim(); const lines = source.split('\n'); const width = Math.max(...lines.map(x=>x.length)); const height = lines.length; for (let i = 0; i < width; i++) { for (let j = 0; j <= height; j++) { const modify = lines.slice(j).concat(lines.slice(0, j)) .map(line => line.padEnd(' ', width).slice(i) + line.slice(0, i)).join('\n'); const iframe = document.body.appendChild(document.createElement('iframe')); iframe.style = 'width: 100%; height: 60px;'; iframe.src = 'data:text/html;base64,' + btoa(`<style>${modify}</style>`); } } ``` The story tells us: You should repeat something ~~2~~ ~~3~~ 4 times whenever it is important. Also, I have no idea how to golf it. (I'm using Firefox 91, if this matters.) [Answer] # [R](https://www.r-project.org/) -e 'options(error=function(){})', 183 bytes (or any other [R](https://www.r-project.org/) environment in which errors do not halt execution of subsequent commands: entering the program into the [R](https://www.r-project.org/) interactive console (or Rstudio) works fine; in batch mode or TIO we can set the global enviroment option `error` to an empty function; or in Rscript we can set this using the command-line option `-e 'options(error=function(){})'`). ``` if(F) cat("hello toroidal world")#" F=!F; F=!F `if`(F,cat("hello toroidal world"))#" F=!F ``` [Try it online!](https://tio.run/##K/qfX1CSmZ9XrJFaVJRfZJtWmpcM4mtoVtdq/s9M03DTVFBITizRUMpIzcnJVyjJL8rPTEnMUSjPL8pJUdJUVlIgDNxsFd2suWAsTk5MFVxEmJKQmZag4aaDxzFA13CBbPj/HwA "R – Try It Online") [Try all vertical rotations](https://tio.run/##K/qfX1CSmZ9XrJFaVJRfZJtWmpcM4mtoVtdq/s9M03DTVFBITizRUMpIzcnJVyjJL8rPTEnMUSjPL8pJUdJUVlIgArjZKrpZc3GCKE5OTGkuTigAcRIy0xI03HTw2Am0lAtk1H@wmpi8mLyi/JLEktQUBUOFnMy81Jg8JU2wAq7B634MpxuBnV4Mdjt5wUE332K43RjZ7VSOZCr76j8A) [Try all horizontal rotations](https://tio.run/##rZDBTgMhEIbP9ikQDzskxFiWm@G6T@Cxh2LLWhIKFcbWxvjs62Rrm7jZqk06HMjMfPnh/3PXhampfAuNYGxhEfjKhZAYppz80ga2Szksubjj7B/VmNvmsZoEZapjy65RJFkfJP@quW/n0MhfnHxbIUltqqv98CDZpgye@ciKe4W4WNkMYSqE@JjcUMwbW9A9QHl7Lph9fKGdVEL@6OkIQbQaodWAVie6HqHrAV2faD1C6wGtj3SfJLqCNGY5oUWfIpde8lnktF/vXdya6Hb3dAMNMO/BbW2Ajc3FAbp3NBSCpLXPpsfpJR9cRPN0jlcX8vWFvD7P94ZnsXf32XVf) **How?** The program is based offset copies of the code `if(F)cat("hello toroidal world")#"` and `F=!F`. The first instance of `if(F)cat("hello toroidal world")#` shouldn't output anything (since `F` is the built-in variable for `FALSE`). Then, `F` is flipped to `!F` = `TRUE`, so the second instance writes the output. The final line flips `F` to `!F` again, to ensure that any vertical rotation of the lines leaves the overall program function unchanged. But what if we rotate the code horizontally? Most rotations that cut the first line will cause it to fail, but the second line will still flip `F` to `!F` so the third line will output Ok. The exceptions are rotations of 5, 6, or 7 characters, which will remove the `if(F)` at the start of the first line, so the `cat` function will be called: however, the `F=!F` on the second line is placed so that any of these rotations will break it, with the result that the `cat` function on the third line will now not be called. Any rotations that cut the third line (and so could cause it to fail) will bring the extra `F=!F` at the end of the first line, which is otherwise commented-out, to the front of the line, so the first line will now output. --- # [R](https://www.r-project.org/) -e 'options(error=function(){})', 80 bytes ``` cat("hello toroidal world") ) cat("hello toroidal world" ``` [Try it online!](https://tio.run/##K/qfX1CSmZ9XrJFaVJRfZJtWmpcM4mtoVtdq/k9OLNFQykjNyclXKMkvys9MScxRKM8vyklR0uTSVMAFcOv6/x8A "R – Try It Online") ...then I read the other answers and realised that a simple port of [Wheat wizard's Prolog answer](https://codegolf.stackexchange.com/a/233731/95126) is much cleaner and shorter... Oh, well... ]
[Question] [ Your challenge is to take a name (string) as input, like ``` Albert Einstein ``` and output: ``` Einstein, Albert ``` ## Pseudocode: ``` set in to input set arr to in split by " " set last to the last element of arr remove the last element of arr set out to arr joined with " " prepend ", " to out prepend last to out output out ``` ## More test cases: ``` John Fitzgerald Kennedy => Kennedy, John Fitzgerald Abraham Lincoln => Lincoln, Abraham ``` ## Rules * The input will always match the regex `^([A-Z][a-z]+ )+([A-Z][a-z]+)$`. * You don't need to handle [weird names](https://codegolf.stackexchange.com/questions/114927/whats-my-middle-name#comment280423_114927), even if the output is technically incorrect it is fine here. * Trailing whitespace / newline is OK. * Any questions? Comment below! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ### Code: ``` ',ì#Áðý ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@6@uc3iN8uHGwxsO7/3/3zGpKDEjMVfBJzMvOT8nDwA "05AB1E – TIO Nexus") ### Explanation: ``` ',ì # Prepend the input to "," # # Split on spaces Á # Rotate every element one position to the right (wrapping) ðý # Join the array by spaces ``` [Answer] # JavaScript (ES6), 34 bytes ``` s=>s.replace(/(.+) (.+)/,'$2, $1') ``` # Demo: ``` let f = s=>s.replace(/(.+) (.+)/,'$2, $1') ;[ 'Albert Einstein', 'John Fitzgerald Kennedy', 'Abraham Lincoln' ].forEach( s => console.log(`${s} => ${f(s)}`) ) ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~19~~ ~~17~~ 16 bytes *Edit: Thanks to Riker for saving 3 bytes* ``` (.+) (.+) $2, $1 ``` [Try it online!](https://tio.run/nexus/retina#@6@hp62pACK4VIx0FFQM///3ys/IU3DLLKlKTy1KzElR8E7Ny0tNqQQA "Retina – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ;”,Ḳṙ-K ``` [Try it online!](https://tio.run/##y0rNyan8/9/6UcNcnYc7Nj3cOVPX@//h9kdNayL//49W8srPyFNwyyypSk8tSsxJUfBOzctLTalU0lFQcsxJSi0qUXDNzCsuSc3MAwslFSVmJOYq@GTmJefn5CnFAgA "Jelly – Try It Online") I don't know Jelly very well, but reading other answers it looked like they didn't use an optimal algorithm... so here it is: ### Explanation ``` ;”,Ḳṙ-K ;”, Append a comma to the end of the string Ḳ Split on spaces ṙ- Rotate the array by -1 (1 time towards the right) K Join with spaces ``` [Answer] # [V](https://github.com/DJMcMayhem/V) / vim, ~~9~~ 8 bytes ``` $bD0Pa, ``` [Try it online!](https://tio.run/nexus/v#@6@S5GIQkKij8P@/V35GnoJbZklVempRYk6KgndqXl5qSiUA) Saved one Byte thanks to Note there is a trailing space character. Leaves a trailing space, which is allowed per the rules. Explanation: ``` $ " move the cursor to the end of the line b " move the cursor to the beginning of the current word D " delete to the end of the line 0 " move the cursor to the start of the line P " paste in front of the cursor. a " append (enter insert mode with the cursor one character forward) , " Literal text, ", " ``` [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` f,l=input().rsplit(' ',1);print l+',',f ``` [Try it online!](https://tio.run/nexus/python2#FcixDoIwEADQ3a@4dCnEhoQV4@Cgg/IJLgUOe8l5NMcRoz9fwxvfJxEjtN2zzIHPJHmzqm50zUxWefChrU9ZSQz46IMPcynuviSBG9nvhRp5ggeK4PR1B3fhAdXgSrIakuwzaEzxDT3JuLC4Pw "Python 2 – TIO Nexus") Yup, `rsplit`. [Answer] ## Mathematica, 52 40 bytes ``` StringReplace[x__~~" "~~y__:>y<>", "<>x] ``` [Answer] # Vim, 10 bytes/keystrokes ``` v$F dA, <esc>p ``` [Try it online!](https://tio.run/nexus/v#@1@m4qaQ4qijIF3w/79XfkaegltmSVV6alFiToqCd2peXmpKJQA "V – TIO Nexus") [Answer] # [><>](https://esolangs.org/wiki/Fish), 27 bytes ``` i:0(?v " ,"~<^r/ =" ":}o!/? ``` [Try it online!](https://tio.run/nexus/fish#@59pZaBhX8alpKCjVGcTV6TPZaukoGRVm6@ob///v2NSUWJGYq6CT2Zecn5OHgA "><> – TIO Nexus") [Answer] # C, 45 bytes EDIT: I just now noticed the requirement for the input possibly having more than two words. I'll leave it as-is with a note that this only works for two words. EDIT: removed `\n`. Add 2 bytes if you consider it necessary. ``` main(a,b)int**b;{printf("%s, %s",b[2],b[1]);} ``` Compiles with `gcc name.c`, GCC 6.3.1. Ignore warnings. Usage: ``` $./a.out Albert Einstein Einstein, Albert ``` Abuse of language: * Implicit return type `int` of `main` and nothing returned. * Implicit declaration of `printf`. GCC will include it anyway. * Wrong type of `b`. Doesn't matter with `%s` Thanks to @Khaled.K for the tips on using `main(a,b)int**b;` rather than `main(int a, int **b)`. [Answer] # [Ruby](https://www.ruby-lang.org/), 22 bytes ``` ->s{s[/\w+$/]+", #$`"} ``` [Try it online!](https://tio.run/nexus/ruby#S7P9r2tXXF0crR9Trq2iH6utpKOgrJKgVPu/oLSkWCEtWsm9tLgksSxfwSexILOqKlEplgsm452TWFqs4JtYlJmo4FSUmJeSWJpapBT7HwA "Ruby – TIO Nexus") [Answer] # sed, 19 + 1 for -E = 20 bytes ``` s/(.*) (.*)/\2, \1/ ``` Must use -r (GNU) or -E (BSD, recent GNUs) to avoid having to escape the grouping parenthesis. If written on the command-line, must be enclosed in quotes to avoid being parsed as multiple tokens by the shell : ``` sed -E 's/(.*) (.*)/\2, \1/' ``` [Answer] # C, 68 bytes Hope it's not wrong to add another post but here's a slightly different solution than my previously posted C solution. This one accepts any number of names. ``` main(a,b)int**b;{for(printf("%s,",b[--a]);--a;printf(" %s",*++b));} ``` Compile with `gcc name.c` (GCC 6.3.1) and ignore warnings. Usage: ``` $./a.out John Fitzgerald Kennedy Kennedy, John Fitzgerald ``` Thanks to @Khaled.K for the tips on `main(a,b)int**b;` Thanks for the tip on the for loop to @Alkano. [Answer] # Mathematica, 45 bytes ``` #/.{a__,s=" ",b__}/;{b}~FreeQ~s->{b,",",s,a}& ``` Saved a few bytes over [ngenisis's answer](https://codegolf.stackexchange.com/a/122329/56178) by taking input as a list of characters rather than as a string. Pure function that uses a pattern-replacement rule. ## Mathematica, 49 bytes ``` #~Join~{","," "}~RotateLeft~Last@Position[#," "]& ``` Another pure function taking a list of characters as input and returning a list of characters. This one appends `","` and `" "` to the input and then rotates the list of characters until the last space is at the end. (Thus the output has a trailing space, unlike the first function above.) [Answer] # C#, ~~76~~ 72 bytes ``` s=>System.Text.RegularExpressions.Regex.Replace(s,"(.+) (.+)","$2, $1"); ``` *Saved 4 bytes with the help of @KevinCruijssen* Old version using substrings for 76 bytes: ``` s=>s.Substring(s.LastIndexOf(' ')+1)+", "+s.Substring(0,s.LastIndexOf(' ')); ``` [Answer] # Awk, 18 characters ``` {$1=$NF", "$1}NF-- ``` Sample run: ``` bash-4.4$ awk '{$1=$NF", "$1}NF--' <<< 'John Fitzgerald Kennedy' Kennedy, John Fitzgerald ``` [Try it online!](https://tio.run/nexus/awk#@1@tYmir4uempKOgpGJY6@emq/v/v1d@Rp6CW2ZJVXpqUWJOioJ3al5eakolAA "AWK – TIO Nexus") [Answer] # JS (ES6), ~~52~~ 44 bytes ``` i=>(i=i.split` `,l=i.pop(),l+", "+i.join` `) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Ḳ©Ṫ”,⁶®K ``` [Try it online!](https://tio.run/nexus/jelly#AS0A0v//4biywqnhuarigJ0s4oG2wq5L////Sm9obiBGaXR6Z2VyYWxkIEtlbm5lZHk "Jelly – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` #`',«.Áðý ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@coK5zaLXe4cbDGw7v/f/fKz8jT8Ets6QqPbUoMSdFwTs1Ly81pRIA "05AB1E – TIO Nexus") **Explanation** ``` # # split input on spaces ` # push each name separately to stack ',« # concatenate a comma to the last name .Á # rotate stack right ðý # join stack by spaces ``` [Answer] # [Pyth](http://pyth.readthedocs.io/en/latest/index.html), 11 bytes ``` jd.>c+z\,d1 ``` **Explanation:** ``` jd.>c+z\,d1 +z\, Append the "," to the input c+z\,d Split the string on " " .>c+z\,d1 Rotate the array one element right jd.>c+z\,d1 Join the array on " " ``` [Test it online!](https://pyth.herokuapp.com/?code=jd.%3Ec%2Bz%5C%2Cd1&input=John%20Fitzgerald%20Kennedy&debug=0) [Answer] # PHP, 45 Bytes ``` <?=preg_filter("#(.*) (.+)#","$2, $1",$argn); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfLKz8hTcMssqUpPLUrMSVHwTs3LS02pVLLmsrf7b2NvW1CUmh6flplTklqkoaSsoaelqaChp62prKSjpGKko6BiqKQDNknT@v9/AA "PHP – TIO Nexus") [Answer] # [Bash](https://www.gnu.org/software/bash/), 26 bytes ``` echo ${!#}, ${@:1:$[$#-1]} ``` [Try it online!](https://tio.run/nexus/bash#@5@anJGvoFKtqFyrA6QcrAytVKJVlHUNY2v////vlZ@R998ts6QqPbUoMSflv3dqXl5qSiUA "Bash – TIO Nexus") [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), 37 bytes ``` @(a)regexprep(a,'(.+) (.+)','$2, $1') ``` [Try it online!](https://tio.run/nexus/octave#@@@gkahZlJqeWlFQlFqgkaijrqGnrakAItR11FWMdBRUDNU1/yfmFWuoO@YkpRaVKLhm5hWXZKbmAYUB "Octave – TIO Nexus") Based on @ngenisis' Retina answer, we can also play the regex game in both Octave and MATLAB, saving a fair few bytes over my previous answer. --- ### Old Answer: I'm going to leave this answer here as well considering it is a more unique way of doing it compared to a simple regex. # [Octave](https://www.gnu.org/software/octave/), ~~49~~ 47 bytes ``` @(a)[a((b=find(a==32)(end))+1:end) ', ' a(1:b)] ``` [Old try it online!](https://tio.run/nexus/octave#@@@gkagZnaihkWSblpmXopFoa2tspKmRmpeiqaltaAWiFdR1FNQVEjUMrZJ0DTVj/yfmFWuoO@YkpRaVKLhm5hWXZKbmqWv@BwA "Octave – TIO Nexus") An anonymous function to generate the output. Basically the code first finds the last space in the string using `b=find(a==32)(end)`. Then It takes the end part of the string (after the space) using `a(b+1:end)`, where `b` is the output of finding the last space. It also takes the start of the string with `a(1:b-1)`, and concatenates both together with a `', '` in between. I've already saved a few bytes vs the typical `find(a==32,1,'last')`. Not quite sure there is much more to save. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ḲµṪ;⁾, ;K ``` ## Explained, ish: ``` ḲµṪ;⁾, ;K Ḳ # Split the input by spaces µ # Separate the link into two chains. Essentially calls the right half with the split string monadically. Ṫ # The last element, (The last name), modifying the array. ; # Concatenated with... ⁾, # The string literal; ", " ; # Concatenated with... K # The rest of the array, joined at spaces. ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//4biywrXhuao74oG@LCA7S////0pvaG4gRml0emdlcmFsZCBLZW5uZWR5 "Jelly – Try It Online") [Try on all test cases.](https://tio.run/##y0rNyan8///hjk2Htj7cucr6UeM@HQVr7/@H2x81rYn8/z9aySs/I0/BLbOkKj21KDEnRcE7NS8vNaVSSUdByTEnKbWoRME1M6@4JDUzDyyUVJSYkZir4JOZl5yfk6cUCwA "Jelly – Try It Online") [Answer] # Python 3, 52 bytes ``` lambda s:s.split()[-1]+", "+" ".join(s.split()[:-1]) ``` Very simple, could use golfing help. Just puts the last word at the front and joins them with ", ". Testcase: ``` >>> f=lambda s:s.split()[-1]+", "+" ".join(s.split()[:-1]) >>> f("Monty Python") 'Python, Monty' >>> f("Albus Percival Wulfric Brian Dumbledore") 'Dumbledore, Albus Percival Wulfric Brian' ``` [Answer] # Japt, 14 bytes ``` U+', q' é q' ``` A port of [@programmer5000](https://codegolf.stackexchange.com/users/58826/programmer5000)'s [JavaScript answer](https://codegolf.stackexchange.com/a/122324/58826). [Try it online!](https://tio.run/nexus/japt#@x@qra6jUKiuoHB4JYj6/1/JKzE3tVjBOSe1KFvBN7GiPDUnRwkA) [Answer] # Java, ~~110~~ 62 bytes ``` String d(String s){return s.replaceAll("(.+) (.+)","$2, $1");} ``` Non-static method. -48 bytes thanks to Kevin Cruijssen [Answer] ## Perl 18+1=19 bytes ``` perl -pe '/\S+$/;$_="$&, $`"' ``` +1 for `-p` [Answer] # [PHP](https://php.net/), 62 59 bytes -3 bytes, thanks Jörg ``` $a=explode(' ',$argn);echo array_pop($a).', '.join(' ',$a); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfdNzMovUsAg1a3/qyTaplYU5OSnpGqoK6jrgNVrWqcmZ@QrJBYVJVbGF@QXaKgkauqp6yio62XlZ@ZB1Wla//8PAA "PHP – TIO Nexus") Old solution, 63 Bytes Doesn't work if the person has 3 repeating names. ``` <?=($a=strrchr($argv[1]," ")).", ".str_replace($a,'',$argv[1]); ``` [Try it online](https://tio.run/nexus/php#@29jb6uhkmhbXFJUlJxRBGQWpZdFG8bqKCkoaWrqKekoKOkB5eKLUgtyEpNTgfI66uo6MFWa1v////fKz8hTcMssqUpPLUrMSVHwTs3LS02pBAA "Try it online") [Answer] # Vim, 6 keystrokes ``` i<C-p>, <End><C-w> ``` Leaves a trailing space character, which is allowed by the rules Explanation: ``` i Enter insert mode <C-p> Autocomplete with last word , Write ", " <End> Move the cursor to the end of the line <C-w> Delete the word behind the cursor ``` ]
[Question] [ Given a non-empty string, keep removing the first and last characters until you get to one or two characters. For example, if the string was `abcde`, your program should print: ``` abcde bcd c ``` However, if it was `abcdef`, it should stop at two characters: ``` abcdef bcde cd ``` Trailing newlines and trailing spaces at the end of each line are optional. You can have as many as you want or none. ## Test cases ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ -> ABCDEFGHIJKLMNOPQRSTUVWXYZ BCDEFGHIJKLMNOPQRSTUVWXY CDEFGHIJKLMNOPQRSTUVWX DEFGHIJKLMNOPQRSTUVW EFGHIJKLMNOPQRSTUV FGHIJKLMNOPQRSTU GHIJKLMNOPQRST HIJKLMNOPQRS IJKLMNOPQR JKLMNOPQ KLMNOP LMNO MN ABCDEFGHIJKLMNOPQRSTUVWXYZ! -> ABCDEFGHIJKLMNOPQRSTUVWXYZ! BCDEFGHIJKLMNOPQRSTUVWXYZ CDEFGHIJKLMNOPQRSTUVWXY DEFGHIJKLMNOPQRSTUVWX EFGHIJKLMNOPQRSTUVW FGHIJKLMNOPQRSTUV GHIJKLMNOPQRSTU HIJKLMNOPQRST IJKLMNOPQRS JKLMNOPQR KLMNOPQ LMNOP MNO N A -> A AB -> AB ``` Remember this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. [Answer] # [V](http://github.com/DJMcMayhem/V), 10 bytes ``` ò^llYpr $x ``` [Try it online!](http://v.tryitonline.net/#code=w7JebGxZcHIgJHg&input=YWJjZGVmZ2hpams) Explanation: ``` ò^ll " While there are at least two non-whitespace characters on the current line Y " Yank this line p " Paste it below r " Replace the first character with a space $ " Move to the end of the line x " Delete a character ``` [Answer] # ES6 (Javascript), ~~47~~, ~~48~~, 43 bytes EDIT: Replaced ternary operator with &&, prefixed padding string with the newline. Thanks @Neil for an excellent advice ! EDIT: included the function name for the recursive invocation, stripped one byte off by using a literal newline **Golfed** ``` R=(s,p=` `)=>s&&s+p+R(s.slice(1,-1),p+' ') ``` **Test** ``` R=(s,p=` `)=>s&&s+p+R(s.slice(1,-1),p+' ') console.log(R("ABCDEFGHIJKLMNOPQRSTUVWXYZ")) ABCDEFGHIJKLMNOPQRSTUVWXYZ BCDEFGHIJKLMNOPQRSTUVWXY CDEFGHIJKLMNOPQRSTUVWX DEFGHIJKLMNOPQRSTUVW EFGHIJKLMNOPQRSTUV FGHIJKLMNOPQRSTU GHIJKLMNOPQRST HIJKLMNOPQRS IJKLMNOPQR JKLMNOPQ KLMNOP LMNO MN console.log(R("ABCDEFGHIJKLMNOPQRSTUVWXYZ!")) ABCDEFGHIJKLMNOPQRSTUVWXYZ! BCDEFGHIJKLMNOPQRSTUVWXYZ CDEFGHIJKLMNOPQRSTUVWXY DEFGHIJKLMNOPQRSTUVWX EFGHIJKLMNOPQRSTUVW FGHIJKLMNOPQRSTUV GHIJKLMNOPQRSTU HIJKLMNOPQRST IJKLMNOPQRS JKLMNOPQR KLMNOPQ LMNOP MNO N ``` [Answer] ## Python, 45 bytes ``` f=lambda s,p='\n ':s and s+p+f(s[1:-1],p+' ') ``` Recursively outputs the string, plus a newline, plus the leading spaces for the next line, plus the recursive result for the shortened string with an extra space in the prefix. If a leading newline was allowed, we could save a byte: ``` f=lambda s,p='\n':s and p+s+f(s[1:-1],p+' ') ``` Compare with a program (49 bytes in Python 2): ``` s=input();p='' while s:print p+s;s=s[1:-1];p+=' ' ``` [Answer] # [Brainfuck](https://esolangs.org/wiki/Brainfuck), 67 bytes ``` >>,[.>,]<[>++++++++++.<[-]<[<]>[-]++++++++[-<++++>]<[<]>[.>]>[.>]<] ``` This should work on all brainfuck flavors. [Try it online!](http://brainfuck.tryitonline.net/#code=Pj4sWy4-LF08Wz4rKysrKysrKysrLjxbLV08WzxdPlstXSsrKysrKysrWy08KysrKz5dPFs8XT5bLj5dPlsuPl08XQ&input=QUJDREVGRw) ### Ungolfed code: ``` # Print and read input_string into memory >>,[.>,]< while input_string is not empty [ # Print newline >+++++ +++++.< # Remove last character [-] # GOTO start of input_string <[<]> # Remove first character [-] # Add space to space_buffer +++++ +++[-<++++>] # GOTO start of space_buffer <[<]> # Print space_buffer [.>] # Print input_string >[.>] <] ``` There should still be some bytes to chop off here; I've only recently began using brainfuck, so my pointer movement is probably very inefficient. [Answer] # [J](http://jsoftware.com/), 39 19 16 bytes ``` [:|:]#"0~#\.<.#\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61qrGKVlQzqlGP0bPSUY/5rcqUmZ@QrpCmoJyYlp6SmqUP46rq6uuqoUsgy/wE "J – Try It Online") This was a nice example of how a different perspective can allow J to express a problem more naturally. Originally, I was seeing the problem "horizontally", as described in the OP -- a sequence with successive edges being removed: [![enter image description here](https://i.stack.imgur.com/UYNl5.png)](https://i.stack.imgur.com/UYNl5.png) But you can also view it vertically, as a kind of upside down histogram: [![enter image description here](https://i.stack.imgur.com/9zy3c.png)](https://i.stack.imgur.com/9zy3c.png) From this perspective, we are just repeating each letter some number of times, an operation J's copy primitive `#` can accomplish in 1 character. Consider `abcde`: * `#\.<.#\` Determine the number of times to repeat each character, ie, produce the mask `1 2 3 2 1`: ``` #\ => 1 2 3 4 5 #\. => 5 4 3 2 1 ---------------- <. => 1 2 3 2 1 NB. elementwise min ``` * `]#"0~` Use that mask to duplicate the input: ``` a bb ccc dd e ``` * `[:|:` Transpose: ``` abcde bcd c ``` [Answer] # Python 2, 50 bytes ``` def f(i,j=0): print' '*j+i if i:f(i[1:-1],j+1) ``` Simple recursive function that keeps shortening the string until it disappears. Call as f('string') Output ``` string trin ri ``` [Answer] ## Perl, 31 bytes 30 bytes of code + `-p` flag. ``` s/( *)\S(.+).$/$& $1$2/&&redo ``` To run it : ``` perl -pE 's/( *)\S(.+).$/$& $1$2/&&redo' <<< "abcdef" ``` **Explanations** : The `\S` and `.$` correspond to the first and last character, `(.+)` the middle and `( *)` to the trailing spaces that are added every time we remove one character from the beginning. So the regex removes one character from the beginning, one from the end, and add one leading space each time. [Answer] # GNU sed 24 Bytes Includes +2 for `-rn` ``` : p s/[^ ](.+)./ \1/ t ``` Prints, replaces the first non-space character with a space, and deletes the last character until nothing changes. [Answer] # [MATL](http://github.com/lmendo/MATL), 9 bytes ``` tg!*YRPRc ``` This produces trailing spaces and newlines. [Try it online!](http://matl.tryitonline.net/#code=dGchKllSUFJj&input=J0FCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaISc) ### Explanation ``` t % Input string implicitly. Duplicate g! % Convert to logical and transpose: gives a column vector of ones * % Multiply with broadcast. This gives a square matrix with the string's % ASCII codes on each row YR % Lower triangular part: make elements above the diagonal 0 P % Flip vertically R % Upper triangular part: make elements below the diagonal 0 c % Convert to char. Implicitly display, with char 0 shown as space ``` [Answer] ## Batch, 92 bytes ``` @set/ps= @set t= :g @echo %t%%s% @set t= %t% @set s=%s:~1,-1% @if not "%s%"=="" goto g ``` Takes input on STDIN. [Answer] # C, 73 bytes ``` f(char*s){char*b=s,*e=s+strlen(s)-1;while(e-b>-1)puts(s),*b++=32,*e--=0;} ``` Ungolfed: ``` f(char*s) { char *b=s, *e=s+strlen(s)-1; while (e-b>-1) puts(s), *b++=32, *e--=0; } ``` Usage: ``` main(){ char a[] = "abcde"; f(a); } ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` ÐvNú,¦¨D ``` Explanation: ``` Ð # Triplicate the input v # Length times do... Nú, # Prepend N spaces and print with a newline ¦¨ # Remove the first and the last character D # Duplicate that string ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w5B2TsO6LMKmwqhE&input=QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoh) [Answer] ## Pyke, 10 bytes ``` VQlRc l7tO ``` [Try it here!](http://pyke.catbus.co.uk/?code=VQlRc%0Al7tO&input=abcdefgh&warnings=0) [Answer] # Haskell, ~~47~~ 43 bytes ``` f s@(a:b:c)=s:map(' ':)(f.init$b:c) f s=[s] ``` [Try it on Ideone](http://ideone.com/pOrwuB). Output is a list of strings which was allowed in the comments of the challenge. To print, run with `(putStr.unlines.f)` instead of just `f`. Edit: Saved 4 bytes after noticing that trailing whitespace is allowed. ``` Prelude> (putStr.unlines.f)"codegolf" codegolf odegol dego eg --(trailing whitespace) ``` [Answer] # [Perl 6](https://perl6.org), 42 bytes ``` for get,{S/\w(.*)./ $0/}.../\s..?$/ {.put} ``` ## Expanded: ``` for # generate the sequence get, # get a line from the input { # bare block lambda with implicit parameter 「$_」 # used to produce the rest of the sequence S/ # replace \w # a word character ( to be removed ) ( # set 「$0」 .* # any number of any characters ) . # any character ( to be removed ) / $0/ # append a space } ... # repeat that until / # match \s # whitespace . # any character .? # optional any character $ # end of string / { .put # print $_ with trailing newline } ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `C`, 4 bytes ``` ‡ḢṪ↔ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=C&code=%E2%80%A1%E1%B8%A2%E1%B9%AA%E2%86%94&inputs=abcdefghijklmnopq&header=&footer=) i have turned to the dark side i am now a flag abuser thanks to lyxal for helping me get to the 4-byte sol (from 8 bytes) ## Explanation ``` ↔ While results have not reached a fixed point ‡ 2-byte function Ḣ a[1:] Ṫ a[:-1] C Center the list and join on newlines ``` The below less cheese program does the same thing. `øĊ` is the same as the `C` flag. # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 6 bytes ``` ‡ḢṪ↔øĊ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%80%A1%E1%B8%A2%E1%B9%AA%E2%86%94%C3%B8%C4%8A&inputs=%22abcdefghijklmnopq%22&header=&footer=) Since outputting a list was allowed, using the `j` flag to join on newlines is reasonable. You can also append `⁋` to use no flags at all. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` J’⁶ẋoUµ⁺Y ``` [Try it online!](https://tio.run/##ATYAyf9qZWxsef//SuKAmeKBtuG6i29VwrXigbpZ////QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo "Jelly – Try It Online") If the input is of length \$2n\$, this outputs with \$n\$ lines of trailing newlines and spaces ## How it works ``` J’⁶ẋoUµ⁺Y - Main link. Takes a string A on the left µ⁺ - Do the following twice: J - Yield [1, 2, 3, ..., 2n] ’ - Decrement; [0, 1, 2, ..., 2n-1] ⁶ẋ - Repeat a space that many times; [[], [' '], [' ', ' '], ...] U - Reverse A o - Logical OR Y - Join by newlines ``` The logical OR command `o` has the following behaviour: ``` [[], [5], [6, 7], [8, 9, 10]] o [1, 2, 3, 4] = [[1, 2, 3, 4], [5, 2, 3, 4], [6, 7, 3, 4], [8, 9, 10, 4]] ``` so only the leftmost characters are replaced by spaces. We do this twice, reversing each time, to get both the left and right side [Answer] # [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` [L[jk}]∔\ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJXVGRjJDJXVGRjNCJXVGRjRBJXVGRjRCJXVGRjVEJXVGRjNEJXUyMjE0JXVGRjND,i=QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVolMjE_,v=8) [Answer] ## [Retina](http://github.com/mbuettner/retina), 17 bytes ``` ;{G:` \S(.+). $1 ``` [Try it online!](http://retina.tryitonline.net/#code=O3tHOmAKXFMoLispLgogJDE&input=YWJjZGVmZ2hpag) [Answer] # C++14, 117 bytes ``` auto f(auto s){decltype(s)r;auto b=s.begin();auto e=s.rbegin();while(e.base()-b>0)r+=s+"\n",*b++=32,*e++=0;return r;} ``` Assumes input `s` is a `std::string` and returns the animated text. Ungolfed: ``` auto f(auto s){ decltype(s)r; auto b=s.begin(); auto e=s.rbegin(); while(e.base()-b>0){ r+=s+"\n"; *b++=32; *e++=0; } return r; } ``` Usage: ``` main(){ std::string a{"abcdef"}; std::cout << f(a); std::string b{"abcde"}; std::cout << f(b); } ``` [Answer] ## Vim - 14 keystrokes ``` qqYp^r $x@qq@q ``` Explanation: ``` qq -- record a macro named 'q' Y -- Copy current line p -- Paste it ^r -- Replace the first non-space character on the new line with a space $x -- Delete the last character on the line @q -- Recursively call the 'q' macro q -- Stop recording the 'q' macro @q -- Run the 'q' macro ``` Vim automatically kills the macro once we're out of characters [Answer] **Snap! - 16 blocks** ![Snap!](https://i.stack.imgur.com/eGa4c.png) Output is self-centering. The 'wait' is for humans. [Answer] # PHP, 91 bytes ``` <?for(;$i<.5*$l=strlen($s=$_GET[s]);$i++)echo str_pad(substr($s,$i,$l-$i*2),$l," ",2)."\n"; ``` Usage: save in a file and call from the browser: ``` http://localhost/codegolf/string-middle.php?s=ABCDEFGHIJKLMNOPQRSTUVWXYZ Raw output: ABCDEFGHIJKLMNOPQRSTUVWXYZ BCDEFGHIJKLMNOPQRSTUVWXY CDEFGHIJKLMNOPQRSTUVWX DEFGHIJKLMNOPQRSTUVW EFGHIJKLMNOPQRSTUV FGHIJKLMNOPQRSTU GHIJKLMNOPQRST HIJKLMNOPQRS IJKLMNOPQR JKLMNOPQ KLMNOP LMNO MN http://localhost/codegolf/string-middle.php?s=1ABCDEFGHIJKLMNOPQRSTUVWXYZ Raw output: 1ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXY BCDEFGHIJKLMNOPQRSTUVWX CDEFGHIJKLMNOPQRSTUVW DEFGHIJKLMNOPQRSTUV EFGHIJKLMNOPQRSTU FGHIJKLMNOPQRST GHIJKLMNOPQRS HIJKLMNOPQR IJKLMNOPQ JKLMNOP KLMNO LMN M ``` [Answer] **Mathematica, 71 bytes** ``` Table[#~StringTake~{i,-i},{i,Ceiling[StringLength@#/2]}]~Column~Center& ``` [![animate-finding-the-middle](https://i.stack.imgur.com/m0oPU.png)](https://i.stack.imgur.com/m0oPU.png) [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ö÷e╧╤ù◘ ``` [Run and debug it](https://staxlang.xyz/#p=94f665cfd19708&i=%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22) ## Explanation ``` |]miTiNt |]m map each suffix to: iT remove iteration count elements from right iNt pad with iteration count number of spaces on left ``` # [Stax](https://github.com/tomtheisen/stax), 117 bytes ``` c%{d xitiT|c {|,}20*|:xi{xitiTx%|CPFxP {|,}20*|:xi{xitiTx%|CPFxitiNtP {|,}20*|:xi{xitiTx%|CPFxitiTx%|CP F ``` [Run and debug it, animated](https://staxlang.xyz/#c=c%25%7Bd%0A+++xitiT%7Cc%0A+++%7B%7C,%7D20*%7C%3Axi%7BxitiTx%25%7CCPFxP%0A+++%7B%7C,%7D20*%7C%3Axi%7BxitiTx%25%7CCPFxitiNtP%0A+++%7B%7C,%7D20*%7C%3Axi%7BxitiTx%25%7CCPFxitiTx%25%7CCP%0AF&i=%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%21%22) The more fun version. Since stax supports `requestAnimationFrame` from js, `|,` and `|:` can be used to animate each step. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` .e :bUkd_._ ``` [Test suite](http://pythtemp.herokuapp.com/?code=.e%0A%3AbUkd_._&test_suite=1&test_suite_input=%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22%0A%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%21%22&debug=0) [14 bytes to exit without error](http://pythtemp.herokuapp.com/?code=j.e%3AbUkdhc2_._&test_suite=1&test_suite_input=%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%22%0A%22ABCDEFGHIJKLMNOPQRSTUVWXYZ%21%22&debug=0) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ ~~16~~ 15 [bytes](https://github.com/abrudz/SBCS) -9 bytes thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah)'s comment! -1 bytes thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m)! ``` {⍉↑⍵/¨⍨⌊∘⌽⍨⍳⍴⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRb@ejtomPerfqH1rxqHfFo56uRx0zHvXsBbF7Nz/q3QKUqv2f9qhtwqPevkddzY961wAFD603Bunqmxoc5AwkQzw8g/@nHVqhoO7o5Ozi6ubu4enl7ePr5x8QGBQcEhoWHhEZpY5PUlFdQUNH3VFdE6RIHQA "APL (Dyalog Unicode) – Try It Online") This is the dfn taking the string as right input `⍵`. `⍳⍴⍵` the indices of the input string. `⌊∘⌽⍨` element-wise minimum of the indices with the indices reversed. This is the number of times each character appears. `⍵/¨⍨` repeat each character that many times. `↑` arranges the repeated characters in a 2d matrix, padding shorter strings with spaces. `⍉` transposes the matrix. [Try it with step-by-step output!](https://tio.run/##SyzI0U2pTMzJT/8f8KhtQvWjvqlA6lHv1kfdLRC2ujqI2bu19n/1o95OoKKJAUCe/qEVj3pXBDzq6XrUMeNRz14wp3fzo94tYKVpYEP6HnU1P@pdAxQ8tN4YqBFoYHCQM5AM8fAM/p@moO7o5Ozi6qYOAA) ]
[Question] [ Your challenge is to exactly output the following box: ``` .................................................. .................................................. .. .. .. .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++ ++ .. .. ++ ++ .. .. ++ .................................. ++ .. .. ++ .................................. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ .. ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ .. ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .................................. ++ .. .. ++ .................................. ++ .. .. ++ ++ .. .. ++ ++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. .. .. .. .................................................. .................................................. ``` The box is height and width 50, spaces are two wide. You must write a function or program which outputs or returns a string and takes no input. Fewest bytes wins! [Answer] ## [J](http://jsoftware.com/), 25 bytes ``` echo'. + '{~4|>./~2#|i:12 ``` [Try it online!](https://tio.run/nexus/j#@5@anJGvrqegraBeXWdSY6enX2ekXJNpZWj0/z8A "J – TIO Nexus") ## Explanation ``` echo'. + '{~4|>./~2#|i:12 i:12 Range from -12 to 12. | Take absolute values, 2# duplicate every element, /~ compute "multiplication table" >. using maximum, 4| take mod 4 of every element, '. + '{~ index into this string, echo print char matrix for everyone to see. ``` [Answer] # C, 115 bytes ``` #define M(x,y)x<(y)?x:y f(i){for(i=2549;i;i--)putchar(i%51?". + "[(M(i%51-1,M(50-i%51,M(i/51,49-i/51))))/2%4]:10);} ``` Defines a function `f` (call as `f();`) that prints the string to STDOUT. [Answer] ## Pyke, ~~20~~ 17 bytes ``` k25V". + "[[email protected]](/cdn-cgi/l/email-protection) ``` [Try it here!](http://pyke.catbus.co.uk/?code=k25V%22.+%2B+%22ohe%40A.X) ``` k - out = "" 25V - repeat 25 times: oh - (o++)+1 e - ^//2 ". + " @ - " + ."[^] (wraps around) A.X - out = surround(out, ^) ``` The surround function was made for [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") questions like this! [Answer] # C, ~~535~~ ~~478~~ 477 Bytes Now that's a lot of golf :-/ ``` i;main(j){for(;++i<51;puts(""))for(j=0;++j<51;)putchar(i<3|i>48?46:j<3|j>48?46:i>4&i<47&j>4&j<47?i<7|(i>44&i<47)|(j>2&j<7)|(j>44&j<47)?43:j>8&j<43&((i>8&i<11)|(i>40&i<43))?46:i>9&i<41&((j>8&j<11)|(j>40&j<43))?46:i>13&i<37&((j>12&j<15)|(j>36&j<39))?43:((i>12&i<15)|(i>36&i<39))&j>12&j<39?43:i>17&i<33&((j>16&j<19)|(j>32&j<35))?46:((i>16&i<19)|(i>32&i<35))&j>16&j<35?46:i>21&i<29&((j>20&j<23)|(j>28&j<31))?43:((i>20&i<23)|(i>28&i<31))&j>20&j<31?43:i>24&i<27&j>24&j<27?46:32:32);} ``` Here's the output; ``` .................................................. .................................................. .. .. .. .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++ ++ .. .. ++ ++ .. .. ++ .................................. ++ .. .. ++ .................................. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ .. ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ .. ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .................................. ++ .. .. ++ .................................. ++ .. .. ++ ++ .. .. ++ ++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. .. .. .. .................................................. .................................................. ``` [Answer] ## Haskell, 72 bytes ``` q=(\n->[n,n]).abs=<<[-12..12] unlines[[". + "!!mod(max x y)4|y<-q]|x<-q] ``` [@Zgarb's solution](https://codegolf.stackexchange.com/a/106766/34531) in Haskell. I've also tried to construct the box by adding layers around the core `["..",".."]`, but it is 9 bytes longer (81 bytes). ``` e!b=e:e:b++[e,e];s#c=(c!)<$>(c<$s!!0)!s unlines$foldl(#)["..",".."]" + . + . + ." ``` [Answer] # Stacked, noncompeting, 35 bytes [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) ``` ε'.'3$' + .'2*tostr*+$surroundfold ``` Ungolfed: ``` '' '. ++ .. ++ .. ++ ..' $surround fold ``` Quite simple. `surround` is a function that, well, surrounds an entity with a fill entity. For example, `(0) 1 surround` is `((1 1 1) (1 0 1) (1 1 1))`. `$surround` is `surround` as a function, not evaluated. `fold` takes an initial value, then something to fold over, then a function. In this case, `surround` is `fold`ed, surrounding the initially empty string `''` (equiv. `ε`) with each character of the string. ``` '.'3$' + .'2*tostr*+ ``` This is first making a character string `$' + .'`, that, when multiplied by a number, repeats each character. This leaves us with: `++ ..`. This is then casted to a string. Then, we repeat this string thrice, and finally prepend a `.`, giving us the desired string. --- A different approach for 39 bytes: ``` ' .'3$' + .'2*tostr*+toarr$surround#\out ``` `#\` is insert and takes the initial char of the string as the starting value. It also only works on Arrays. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` 12ŒRAx2»þ`ị“ + .”Y ``` [Try it online!](https://tio.run/nexus/jelly#AR4A4f//MTLFklJBeDLCu8O@YOG7i@KAnCArIC7igJ1Z//8 "Jelly – TIO Nexus") Same approach as Zgarb’s J answer: `12ŒRA` is `abs([-12 … 12])`, `x2` repeats every element twice, `»þ`` creates a table of maximums, `ị“ + .”` cyclically indexes into a string, and `Y` joins by newlines. [Answer] ## JavaScript (ES6), 117 bytes ``` f=(n=12,c=`. + `[n%4],t=c.repeat(n*4+2))=>n?t+` ${t} ${f(n-1).replace(/^|$/gm,c+c)} ${t} `+t:`.. ..` console.log(f()) ``` Nonrecursive solution took me 128 bytes: ``` console.log([...Array(100)].map((_,i,a)=>a.map((_,j)=>`. + `[j=j>50?j-50:51-j,(i>j?i:j)%8>>1],i=i>50?i-50:51-i).join``).join`\n`) ``` Where `\n` represents the literal newline character. [Answer] # C, 97 bytes ``` i,x,y;main(){for(;i<2550;putchar(++i%51?". + "[(x*x<y*y?y:x)&3]:10))x=i%51/2-12,y=i/102-12;} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ ~~35~~ 33 bytes ``` •â3fM~•3B…012… .+‡.pvyD¤sg25s-׫«})«» ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@kp6CtoORyeIeX8eHp6nqHVusVlFUeWmJkWpmue3j6odWHmw6trtUEkYd2//8PAA "05AB1E – TIO Nexus") ``` •â3fM~•3B # Push 1100220011002200110022001 …012… .+‡ # Push .. ++ .. ++ .. ++ . .p # All prefixes of the above string. vy } # For each prefix. D¤sg25s-× # Repeat the last letter until length is 25. «Â« # Concat, bifurcate, concat. )«» # Wrap to array, bifurcate, concat, print. ``` --- 33 Byte version that is cooler now because Emigna commented saving me 2 bytes: ``` ". + "DøJ3×'.«.pvy¤25yg-׫«})«» ``` [Try it online!](https://tio.run/nexus/05ab1e#@6@kp6CtoORyeIeX8eHp6nqHVusVlFUeWmJkWpmue3j6odWHmw6trtUEkYd2//8PAA "05AB1E – TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), 89 bytes ``` r=range(-24,26) for i in r:print("".join([". + "[max(abs(i//2),abs(j//2))%4]for j in r])) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8i2KDEvPVVD18hEx8hMkystv0ghUyEzT6HIqqAoM69EQ0lJLys/M08jWklPQVtBKTo3sUIjMalYI1Nf30hTB8TKArE0VU1iQXqzwHpjNTX//wcA "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` '. + '[]25:"TTYaQ]2/) ``` [Try it online!](https://tio.run/nexus/matl#@6@up6CtoB4da2RqpRQSEpkYGGukr/n/PwA "MATL – TIO Nexus") ``` '. + ' % Push this string [] % Push empty array. This will be used as "seed" 25:" % Do the following 25 times TTYa % Extend the array with a frame of zeros Q % Add 1 to each entry ] % End 2/ % Divide by 2 ) % Index modularly into the string. Non-integer indices are rounded % Implicitly display ``` [Answer] # Octave, 53 bytes ``` '. ++ .'(mod(bsxfun(@max,x=[24:-1:0 0:24],x'),8)+1) ``` Generate repeating pattern of 1 to 8 from center outward and use it as the index for extraction of elements of `. ++ .` [Try It Online!](https://tio.run/#qss1A) [Answer] # Ruby, 77 bytes ``` -623.upto(676){|i|print i%26>0?". + "[[(i%26-13).abs,(i/52).abs].max%4]*2:$/} ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` F…¹¦²⁶⁺×ι§. + ÷ι²¶‖O↗‖C↑← ``` [Try it online!](https://tio.run/##RcmxCsIwEIDhvU9xZLqzqWIHhzqJkyAoATeXEC9tICQhhqJPH9vJf/x@M@lsova12pgBlQ4j415CfyBqYOmeXSjY4gadhFO5hBd/UGyhBQG71XoiAvEMgujYKLaeTbnNnL1OODyScuNU/ucc03dlCcOV7TJqrd1cu7f/AQ "Charcoal – Try It Online") Link contains verbose mode for explanation [Answer] **Haskell, 385 Bytes** ``` b 0 = ["..", ".."] b n = f:f:s:s:m (b (n - 1)) ++s:s:f:f:[] where f = replicate (8*n+2) $ d s = l++replicate ((8*n)-6) ' ' ++r m (x:xs) = map (\x -> l ++ x ++ r ) $ t l = d:d:' ':' ':[] r = reverse l t = b (n - 1) d :: Char d | n `mod` 2 == 0 = '.' | n `mod` 2 == 1 = '+' main = mapM_ putStrLn $ b 6 ``` First round of code golf here... looking forward to seeing how others tackle this one. Output: ``` .................................................. .................................................. .. .. .. .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++ ++ .. .. ++ ++ .. .. ++ .................................. ++ .. .. ++ .................................. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ .. ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ .. ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++ ++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. ++++++++++ .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ .................. ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++ ++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. ++++++++++++++++++++++++++ .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .. .. ++ .................................. ++ .. .. ++ .................................. ++ .. .. ++ ++ .. .. ++ ++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. ++++++++++++++++++++++++++++++++++++++++++ .. .. .. .. .. .................................................. .................................................. ``` [Answer] ## C#, 203 bytes Complete, readable program: ``` using System; public class P { public static void Main(string[] a) { Func<string> f = () => { var z = 25; var t = ""; Func<int, string> c = (q) => q % 4 == 0 ? ".." : (q % 4 != 2 ? " " : "++"); for (var y = 0; y < z; y++) { var l = ""; for (var x = 0; x < z; x++) l += ((y > z / 2) ? (x >= y | x < z - y) : (x < y | x >= z - y)) ? c(x):c(y); l += "\n"; t += l + l; } return t; }; Console.Write(f()); Console.ReadKey(); } } ``` Golfed **function**: ``` ()=>{var z=25;var t="";Func<int,string>c=(q)=>q%4==0?"..":(q%4!=2?" ":"++");for(var y=0;y<z;y++){var l="";for(var x=0;x<z;x++)l+=((y>z/2)?(x>=y|x<z-y):(x<y|x>=z-y))?c(x):c(y);l+="\n";t+=l+l;}return t;}; ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 33 bytes ``` 14G" . +"NL¤¸13N-.׫€D¨Â«èD})¨Â«» ``` [Try it online!](https://tio.run/nexus/05ab1e#@29o4q6koKegreTnc2jJoR2Gxn66eoenH1r9qGmNy6EVh5sOrT68wqVWE8I8tPv/fwA "05AB1E – TIO Nexus") **Explanation** ``` 14G # for N in [1 ... 13] " . +" # push this string NL # push range [1 ... N] ¤¸13N-.× # push a list of 13-N repetitions # of the last element of the above range « # concatenate the two ranges €D # duplicate each element ¨ # remove the last element « # concatenate a reversed copy to the list è # use the elements of the list to index into the string D # duplicate the resulting string } # end loop ) # wrap the strings in a list ¨ # remove the last element « # concatenate a reversed copy » # join the list on newlines ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~171~~ 151 bytes ``` ($x=(1..12|%{' . +'[$_%4]}|%{($a+=$_+$_)})+"$a."|%{$c=if(++$i%2){('+','.')[($b=!$b)]}else{' '};$_.PadRight(25,$c)}|%{,($_+-join$_[25..0])*2});$x[23..0] ``` [Try it online!](https://tio.run/nexus/powershell#FcxBDoIwEEDRqyAZMjMOTqTKivQOxm1DGkDUGqMLXZBgz45l@f/iLQSTpUq1Mr9ixkwzQQe@OLYxNUEnFryA58iSQ6d5ujDYcCURCIXhmVCwREV2BL3dQM9tHJ@fMWEYG/B66i7ncLt/ydQlDLy6JSV093iHF3hnatV9y1sTuYHJmcOay/IH "PowerShell – TIO Nexus") Ho-hum answer. I'm sure there's a shorter way (given the lengths of the other answers, I'm confident), but this shows some neat tricks. ### Explanation: `1..12|%{' . +'[$_%4]}` generates an array of strings (of one character in length), in the correct pattern we need. [Try it online!](https://tio.run/nexus/powershell#@2@op2doVKNara6gp6CtHq0Sr2oSW/v/PwA "PowerShell – TIO Nexus") We then add on `|%{($a+=$_+$_)})+"$a."` which takes the array and expands it sideways based on the previous row. [Try it online!](https://tio.run/nexus/powershell#@69hqKdnaFSjWq2uoKegrR6tEq9qElsL5GuoJGrbqsRrq8Rr1mpqK6kk6in9/w8A "PowerShell – TIO Nexus") Those strings are then sent into a loop, `|%{$c=if(++$i%2){('+','.')[($b=!$b)]}else{' '};$_.PadRight(25,$c)}`. Each iteration, we're choosing the correct character (either a plus, a dot, or a space), and then using the `.PadRight` function to pad out to the appropriate number of characters. [Try it online!](https://tio.run/nexus/powershell#DcxBCsIwEEbhq9Tyh5lhykCDriR3ELelhLRWDXSnu5qzxyzft3iVR7PR/9xBnXVKE6I7z6U1I2lAVEQpoj2S9U2xhvxkVWTn5WBSGshIJsYSTlhkLtv@2dqMyhXRbulxz6/3l/1lwCql1j8 "PowerShell – TIO Nexus") Now, we have the foundation of the upper-right corner. We need to reverse each string `|%{,($_+-join$_[($z=25..0)])*2}` and append them together so we can get the top of the block. This is done with the `-join` command and indexing backward `25..0`. Additionally, we encapsulate the strings in an array `,(...)` and make 'em double `*2` so we get the whole top. [Try it online!](https://tio.run/nexus/powershell#FcwxDsIwDEDRq5TKkW0cLBrRCeUOiLWKoraUEoRggK3k7CWM/w9vpUa1cV@zYKWVYAfRHEIuTdCLhygQObPU0GtdLow@XUkEknG8EApaVOSOYPAbGDjk6fGeCob5CFFP/eWc5tuHXGth5L9rqaC7@ys9IXauVd0H3rq8rj8 "PowerShell – TIO Nexus") That is all stored into `$x` and encapsulated in parens so it places the strings on the pipeline. Finally, we reverse `$x` (being sure to snip out the duplicate-duplicate middle row, else we'd have four `..` in the middle) and leave those on the pipeline. An implicit `Write-Output` sticks a newline between the strings, so we get that for free. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~90~~ ~~75~~ 69 bytes ``` ($r=25..1+1..25)|%{$y=$_ -join($r|%{'.. ++ '[($_,$y)[$_-lt$y]%8]})} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0OlyNbIVE/PUNtQT8/IVLNGtVql0lYlnks3Kz8zDygLFFDX01NQ0NZWUFCP1lCJ11Gp1IxWidfNKVGpjFW1iK3VrP3/HwA "PowerShell – Try It Online") [Answer] # Bash, ~~191~~ 184 bytes ``` echo H4sIALBITF4CA72WuQ0AIAzEeqagR8r+47EAgTyH01BZApPPLBvDKshMRR1Z4eghsUv1kbdcDfKSq0LucnXITa4S8eVqEU+uGjnL1SMnuT8Q/1QixFuIfyFyjKgXovaJPkb0ZGK+ELOSmPvEDkPsYxvgYU8W9gkAAA|base64 -d|gunzip ``` Can probably get smaller, but was smaller than my algorithmic attempts. Update: Use --best on gzip for great power. Thanks orthoplex. [Answer] # [Perl 5](https://www.perl.org/), ~~137~~ ~~135~~ ~~132~~ 123 bytes ``` for$i(0..24){$e=49-$i;map{$a[$_][$i]=$a[$_][$e]=$a[$i][$_]=$a[$e][$_]=substr'. + ',$i%8/2,1}$i..$e}print join'',@$_,$/for@a ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0glU8NAT8/IRLNaJdXWxFJXJdM6N7GgWiUxWiU@NlolM9YWxkyFMDNjQVwwMxXCLC5NKi4pUtdT0FZQ11HJVLXQN9IxrFXJ1NNTSa0tKMrMK1HIys/MU1fXcVCJ11HRB9rqkPj/PwA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ". + "12Ýû€Dã€ßèJ50ô» ``` Inspired by [*@Zgarb*'s J answer](https://codegolf.stackexchange.com/a/106766/52210), so make sure to upvote him as well. [Try it online.](https://tio.run/##yy9OTMpM/f9fSU9BW0HJ0Ojw3MO7HzWtcTm8GEgenn94hZepweEth3b//w8A) **Explanation:** ``` 12Ý # Push a list in the range [0,12] û # Palindromize it: [12,11,10,...,2,1,0,1,2,...,10,11,12] €D # Duplicate each item in this list: [12,12,11,11,10,10,...] ã # Create all possible pairs by taking the cartesian product with itself €ß # For each pair, leave the lowest value ". + " è # (0-base) index those into the string ". + " J # Join all those characters together to a single string 50ô # Split it into 50 lines » # And join those by newlines # (after which the result is output implicitly) ``` ]
[Question] [ Your task is to, given an array of signed 32 bit integers, recompile it with its inverse deltas. For example, the list ``` 1 3 4 2 8 ``` holds the deltas: ``` 2 1 -2 6 ``` which are then negated, yielding: ``` -2 -1 2 -6 ``` and recompiled, yielding: ``` 1 -1 -2 0 -6 ``` as the final result. ## Input/Output You will be given a list/array/table/tuple/stack/etc. of signed integers as input through any standard input method. You must output the modified data once again in any acceptable form, following the above delta inversion method. You will receive N inputs where `0 < N < 10` where each number falls within the range `-1000 < X < 1000` ## Test Cases ``` 5 6 7 8 -> 5 4 3 2 1 3 4 2 8 -> 1 -1 -2 0 -6 32 18 25 192 199 -> 32 46 39 -128 -135 ``` ## Notes * You are not restricted to the delta based method: if you can work out the easier method *(which shouldn't be too hard)*, you're free to use it. * As stated in above, you will always receive at least 1 input, and no more than 9. * The first number of the output must **always** be the first number of the input, if this is not the case, your method is incorrect. * Only Standard Input Output is accepted * Standard loopholes apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte-count wins! * Have fun! ## We have a winner. [Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'s [Jelly Answer](https://codegolf.stackexchange.com/a/101058/58375) at a Tiny 3 Bytes has taken home the gold, due to the fact that I am under the impression it cannot be beaten. I was mildly disappointed I didn't get to see an answer based on the original spec, however, I may later put a bounty on precisely that. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḤḢ_ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bik4biiXw&input=&args=MzIsIDE4LCAyNSwgMTkyLCAxOTk) ### Background The deltas of **(a, b, c, d)** are **b - a**, **c - b**, and **d - c**. Cumulatively reducing **(a, b - a, c - b, d - c)** by subtraction yields **a - (b - a) = 2a - b**, **2a - b - (c - b) = 2a - c**, and **2a - c - (d - c) = 2a - d**, so the correct result is **(2a - a, 2a - b, 2a - c, 2a - d)**. ### How it works ``` ḤḢ_ Main link. Argument: A (array) Ḥ Unhalve; multiply all integers in A by 2. Ḣ Head; extract first element of 2A. _ Subtract the elements of A from the result. ``` [Answer] # Python 2, 30 bytes ``` lambda x:[x[0]*2-n for n in x] ``` Test it on [Ideone](http://ideone.com/N9P5QS). ### How it works The deltas of **(a, b, c, d)** are **b - a**, **c - b**, and **d - c**. Cumulatively reducing **(a, b - a, c - b, d - c)** by subtractiong yields **a - (b - a) = 2a - b**, **2a - b - (c - b) = 2a - c**, and **2a - c - (d - c) = 2a - d**, so the correct result is **(2a - a, 2a - b, 2a - c, 2a - d)**. [Answer] # Mathematica, 8 bytes ``` 2#-{##}& ``` Unnamed function taking an indeterminate number of arguments. This uses an "easy" way: negates the entire list and adds twice the (original) first element. Called for example like `2#-{##}&[1,3,4,2,8]`; returns a list like `{1,-1,-2,0,-6}`. [Answer] # JavaScript (ES6), 21 Thx @Dennis ``` l=>l.map(v=>l[0]*2-v) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 4 bytes ``` ¬·s- ``` [Try it online!](http://05ab1e.tryitonline.net/#code=wqzCt3Mt&input=WzMyLCAxOCwgMjUsIDE5MiwgMTk5XQ) or as a [Test suite](http://05ab1e.tryitonline.net/#code=fHZ5I8KswrdzLSw&input=MSAzIDQgMiA4CjUgNiA3IDgKMSAzIDQgMiA4CjMyIDE4IDI1IDE5MiAxOTk) **Explanation** ``` ¬ # head of input list · # multiplied by 2 s # swap with input list - # subtract ``` [Answer] # [Perl 6](https://perl6.org), ~~40~~ 16 bytes ``` {[\+] .[0],|.rotor(2=>-1).map({[-] @_})} ``` ``` {.map(.[0]*2-*)} ``` ## Expanded: ``` { # bare block lambda with single implicit parameter 「$_」 ( input is a List ) [\[+]] # triangle reduce the following using 「&infix:<+>」 .[0], # the first value |( # Slip this list into outer one ( Perl 6 doesn't auto flatten ) .rotor( 2 => -1 ) # take the input 2 at a time, backing up 1 .map({ [-] @_ }) # reduce the pairs using 「&infix:<->」 ) } ``` ``` { # bare block lambda with single implicit parameter 「$_」 ( input is a List ) .map( # map over the inputs .[0] * 2 - * # take the first value multiply by 2 and subtract the current value # ^- this makes the statement a WhateverCode, and is the input ) } ``` [Answer] # ARM (Thumb), 16 bytes ``` .section .text .global func .thumb // void func(int* arr, int len) // arr[i] = 2*arr[0] - arr[i] for each i // r0 = arr, r1 = len, r2 = arr[0], r3 = arr[i] func: ldr r2, [r0, #0] // 6802 int head = *arr; .loop: // do { ldr r3, [r0, #0] // 6803 int cur = *arr; rsb r3, r3, r2, lsl #1 // ebc3 0342 cur = (head << 1) - cur; stmia r0!, {r3} // c008 *arr++ = cur; sub r1, #1 // 3901 len -= 1; bne .loop // d1f9 } while (len != 0); bx lr // 4770 return; ``` Uses the formula, which nicely fits into exactly four registers in use. The [`stm` tip](https://codegolf.stackexchange.com/a/230924/78410) was used to overwrite the value and advance the pointer in a single narrow instruction, and a wide `rsb` instruction was used to evaluate exactly what we want. (I know it's possible to do with a 3-operand `sub` and then an `add` for the same byte count, but I figured a single instruction would add some coolness.) [Answer] # Python, 44 bytes ``` lambda l:[l[0]]+[x-(x-l[0])*2for x in l[1:]] ``` This uses the "Easier method". [Answer] # Pyth, 5 bytes ``` -LyhQ ``` [Online Interpreter!](http://pyth.herokuapp.com/?code=-LyhQ&input=%5B32%2C+18%2C+25%2C+192%2C+199%5D&debug=0) [Answer] # R, ~~23~~ ~~18~~ 17 bytes ``` x=scan();2*x[1]-x ``` auto-vectorisation and default print to the rescue! [Answer] # Ruby, 23 bytes ``` ->l{l.map{|x|l[0]*2-x}} ``` Not particularly original. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 76 Bytes ``` ([][()]){{}(({})<(({}){}[{}]<>)<>>)([][()])}{}({}<<>([]){{}({}<>)<>([])}<>>) ``` [Try it Online!](http://brain-flak.tryitonline.net/#code=KFtdWygpXSl7e30oKHt9KTwoKHt9KXt9W3t9XTw-KTw-PikoW11bKCldKX17fSh7fTw8PihbXSl7e30oe308Pik8PihbXSl9PD4-KQ&input=MzIgMTggMjUgMTkyIDE5OQ) **Explanation:** ``` Part 1: ( ) # Push: [] # the height of the stack [()] # minus 1 { } # While the height - 1 != 0: {} # Pop the height (({})< # Hold onto the top value, but put it back. # This ensures that the top value is always # what was the first element of input ( ) # Push: ({}){} # Top * 2 [{}] # minus the next element <> <> # onto the other stack >) # Put back the element we held onto. ( ) # Push: [] # The height of the stack [()] # Minus 1 {} # Pop the counter used for the height Part 2: ({}< # Hold onto the top element. # This was the first number for input # so it needs to end up on top <> # Switch stacks ([]) # Push the height of the stack { } # While the height != 0: {} # Pop the height ( ) # Push: {} # The top element of this stack <> # onto the other stack <> # and switch back ([]) # Push the new height of the stack <> # After every element has switched stacks # (which reverses their order), # switch stacks >) # Push the first element back on ``` [Answer] # [Labyrinth](http://github.com/mbuettner/labyrinth), 34 bytes ``` ?:_2*} @ _ )\?_1" , ; !`-}:{ ``` [Try it online!](http://labyrinth.tryitonline.net/#code=PzpfMip9CkAgICAgXwopXD9fMSIKLCAgICA7CiFgLX06ew&input=MCAxIDIgMw) Uses [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)'s `(2a - a, 2a - b, 2a - c, 2a - d)` approach. [![enter image description here](https://i.stack.imgur.com/EQ4Mw.png)](https://i.stack.imgur.com/EQ4Mw.png) The yellow tiles are for control flow. In this 2D programming language, the program starts at the top-left-most tile moving east to start. At junctions, the direction is determined by the sign of the top of the main stack. Blank tiles are walls. ## Green This section saves 2a to the auxilary stack. * `?` Get the first number and push it to the top of the main stack * `:` Duplicate the top of the stack * `_2` Push two to the top of the stack * `*` Pop `y`, pop `x`, push `x*y` * `}` Move the top of the main stack to the top of the auxilary stack. * `_` Push zero to the top of the stack ## Orange This section subtracts 2a from the current number, negates the result, outputs the result, gets the next character (the delimeter), exits if EOF, outputs a newline, gets the next number. * `"` Noop. If coming from the north, the top of the stack will be zero and the program will continue south. If coming from the west, the top of the stack will be one and the program will turn right (continuing south) * `;` Discard the top of the stack. As the zero or one is only used for control flow, we need to discard these * `{` Move the top of the auxilary stack (2a) to the top of the main stack * `:` Duplicate the top of the main stack * `}` Move the top of the main stack to the top of the auxilary stack * `-` Pop `y`, pop `x`, push `x-y` * `\`` Negate the top of the stack. This and the previous three operations have the effect of`-(x-2a) = 2a-x` * `!` Pop the top of the stack and output it as a number * `,` Push the next character (which will be the delimiter) or negative one if EOF * `)` Increment the top of the stack. If the last character is EOF, then the top of the stack will now be zero and the program will continue straight to the `@` and exit. If the last character was a delimeter, then the top of the stack will be positive causing the program to turn right and continue east to the `\` * `\` Output a newline * `?` Get the next number * `_1` Push one to the top of the stack in order to turn right at the junction [Answer] # Haskell, 20 19 bytes ``` f(x:r)=x:map(2*x-)r ``` Same solution as Dennis, thank you for your idea of `2a - x`. Saved one byte thanks to Christian Severs. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes ``` dh- ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=dh-&inputs=%5B1%2C3%2C4%2C2%2C8%5D&header=&footer=) Dennis port ``` d # Double the array h # Take the first - # Subtract ``` Or, by implementing the original spec, # [Vyxal](https://github.com/Lyxal/Vyxal) 2.5, 5 bytes ``` ¯?hp¦ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C2%AF%3Fhp%C2%A6&inputs=%5B1%2C3%2C4%2C2%2C8%5D&header=&footer=) ``` ¯ # Deltas (negated, this is a bug, and will be fixed, that is why it's 2.5) ?hp # Prepend the first item of input ¦ # Take the cumulative sum ``` [Answer] ## Pyke, ~~5~~ 4 bytes ``` h}m- ``` [Try it here!](http://pyke.catbus.co.uk/?code=h%7Dm-&input=%5B1%2C2%2C3%2C4%5D) [Answer] # PHP, 48 bytes ``` for(;''<$c=$argv[++$i];)echo-$c+2*$a=$a??$c,' '; ``` Using the technique from Dennis. Use like: ``` php -r "for(;''<$c=$argv[++$i];)echo-$c+2*$a=$a??$c,' ';" 1 3 4 2 8 ``` Non-Dennis 55 byte version: ``` for(;''<$c=$argv[++$i];$l=$c)echo$a+=($l??$c*2)-$c,' '; ``` [Answer] # APL, 8 bytes ``` +\⊃,2-/+ ``` Explanation: ``` +\ ⍝ running sum of ⊃ ⍝ first item of list , ⍝ followed by 2-/ ⍝ differences between every pair in + ⍝ input list ``` Test cases: ``` ( +\⊃,2-/+ ) ¨ (5 6 7 8) (1 3 4 2 8) (32 18 25 192 199) ┌───────┬────────────┬──────────────────┐ │5 4 3 2│1 ¯1 ¯2 0 ¯6│32 46 39 ¯128 ¯135│ └───────┴────────────┴──────────────────┘ ``` [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), 24 bytes ``` +:}:? } <}}?;%):,\!-{:{> ``` Input and output format are linefeed-separate lists (although the input format is actually a lot more flexible). The program terminates with an error. [Try it online!](http://labyrinth.tryitonline.net/#code=Kzp9Oj8KfQo8fX0_OyUpOixcIS17Ons-&input=MQozCjQKMgo4) I've got two other solutions at this byte count, which work basically the same but use somewhat different control flow. ``` :+:}:? { ,}-! ? { :";\@ ``` ``` {:+:}:? _ <>__-?:;%):,\! ``` ### Explanation The instruction pointer (IP) starts moving east along the first line, but all the commands before the `?` are basically no-ops on the global state, since we're not using stack depth commands anywhere. So the code really starts at the `?` going west, since the IP turns around when it hits the dead end. The code therefore starts with the following linear bit of code: ``` ?:}:+} ``` This simply sets us up with a copy of `2a` to use the `[2a - a, 2a - b, 2a - c, ...]` formula. ``` ? Read first integer a. :} Move a copy off to the auxiliary stack. :+ Multiply a by 2 (by adding it to itself). } Move that off to the auxiliary stack as well. ``` We now enter the main loop of the program, using a fairly standard trick to loop through a single line of code: ``` <...> ``` Note that the stack will be empty whenever we hit the `<` so we know we'll get zeros there. The `<` then rotates the entire line left, taking the IP with it, so we get this: ``` ...>< ``` The IP then has to move left, where the `>` shifts the line back into its original place (to prepare it for the next iteration). Then the line is simply executed from right to left, so a single loop iteration is this: ``` {:{-!\,:)%;?}} ``` The catch when working with a loop of this type is that you can't work with any form of conditional execution, since Labyrinth doesn't have a way to skip code. Therefore, we will terminate the program with a division by zero when we hit EOF. Here is a breakdown of each loop iteration. ``` {: Pull 2a back to the main stack and make a copy. { Pull the latest value i of the input list back to main as well. - Compute 2a-i/ !\ Print it with a trailing linefeed. , Read a character. If there are input elements left, this will be some form of separator character, and therefore a positive value x. However, at the end of the program, this will give -1. :) Make an incremented copy. % Try to to compute x%(x+1). This will error out at EOF. ; Discard the result of the division. ? Read the next input value. }} Move that and the remaining copy of 2a back to the auxiliary stack. ``` [Answer] # [Factor](https://factorcode.org/), 26 bytes ``` [ dup first 2 * v-n vneg ] ``` [Try it online!](https://tio.run/##TYq9CsIwFIX3PsWZBQtprTb6AOLiIk7iEOKtltoYk9uAlD57jOLgGQ7n52uU5oeLx8Nuv12jI2foDk/PgYwmj17x7Wt5oA/oYR0xv6xrDWOTZWOGpBEVllihxvTrAiUWKP6WsoCoUVQQMiUp0zHFEy6DRdM6zwmeIcwNgqErzrFXFp6V7vL4Bg "Factor – Try It Online") [Answer] # [J](http://jsoftware.com/), 7 bytes ``` -~+:@{. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/deu0rRyq9f5rcnGlJmfkK6QpmCqYKZgrWMC4hgrGCiYKRggBYyMFQwsFI1MFQ0sgy9LyPwA "J – Try It Online") [Answer] # C++14, 36 bytes As unnamed lambda modifying its input: ``` [](auto&c){for(auto&x:c)x=2*c[0]-x;} ``` Using the technique from Dennis. Works for any container like `int[]` or `vector<int>`. Usage: ``` #include<iostream> auto f= [](auto&c){for(auto&x:c)x=2*c[0]-x;} ; int main(){ int a[] = {1, 3, 4, 2, 8}; f(a); for(auto&x:a) std::cout << x << ", "; std::cout<<"\n"; } ``` [Answer] # CJam, 16 bytes Input format: `[1 2 3 4]`. Uses the easy formula. ``` l~_(2*/;a/,@@*.- ``` **Explanation:** ``` l~_(2*/;a/,@@*.- l~_ e#Read input twice into an array. Stack: [1 2 3 4] [1 2 3 4] ( e#Get first element of the array. Stack: [1 2 3 4] [2 3 4] 1 2* e#Multiply by two. Stack: [1 2 3 4] [2 3 4] 2 /; e#Discard second element. Stack: [1 2 3 4] 2 a e#Wrap into an array. Stack: [1 2 3 4] [2] /, e#Rotate and get length. Stack: [2] [1 2 3 4] 4 @@ e#Rotate twice. Stack: [1 2 3 4] 4 [2] * e#Repeat len times. Stack: [1 2 3 4] [2 2 2 2] .- e#Vectorized substraction. Stack: [-1 0 1 2] e#Implictly print ``` Sorry for no test link. I guess SE don't like it's links with brackets inside. [Answer] # [Pushy](https://github.com/FTcode/Pushy), 9 bytes ``` {&}2*K~-_ ``` Give arguments as comma-seperated values on cmd line: `$ pushy invdeltas.pshy 1,3,4,2,8`. Here's the breakdown, with example stack: ``` % Implicit: Input on stack [1, 3, 4, 2, 8] {&} % Copy first item, put at end of stack [1, 3, 4, 2, 8, 1] 2* % Multiply by 2 [1, 3, 4, 2, 8, 2] K~ % Negate everything on stack [-1, -3, -4, -2, -8, -2] - % Subtract last item from all [1, -1, -2, 0, -6] _ % Print whole stack ``` Note: this can be 8 bytes if backwards output is allowed: `@&2*K~-_` [Answer] # Perl, 26 + 3 (`-pla` flag) = 29 bytes ``` $_="@{[map$F[0]*2-$_,@F]}" ``` or ``` $_=join$",map$F[0]*2-$_,@F ``` Using: ``` perl -plae '$_="@{[map$F[0]*2-$_,@F]}"' <<< "32 18 25 192 199" ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 5 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) [`-+2×⊃`](http://tryapl.org/?a=%28-+2%D7%u2283%29%A8%281%203%204%202%208%29%285%206%207%208%29%281%203%204%202%208%29%2832%2018%2025%20192%20199%29&run) this is a 5-train, it parses like two nested 3-trains ("forks"): `-+(2×⊃)` reads like: the negation (`-`) of the whole array plus (`+`) twice (`2×`) the first element (`⊃`) [Answer] # ised, 11 bytes ``` 2*$1_0-$1 ``` Invocation: `ised --l 'file with input.txt' '2*$1_0-$1` (edit: corrected by stealing the algebra from Dennis) [Answer] # [Wonder](https://github.com/wonderlang/wonder), 17 bytes ``` @->#@- *2:0#1#0#0 ``` Not sure why I didn't post this earlier. Usage: ``` (@->#@- *2:0#1#0#0)[5 6 7 8] ``` More readable: ``` @(map @ - ( * 2 get 0 #1 ) #0 ) #0 ``` [Answer] # [Zsh](https://www.zsh.org/), 18 bytes ``` for a;<<<$[$1*2-a] ``` [Try it online!](https://tio.run/##qyrO@F@cWqJgqGCsYKJgpGDxPy2/SCHR2sbGRiVaxVDLSDcx9v9/AA "Zsh – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-m`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` nWÎÑ ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=blfO0Q&input=WzEgMyA0IDIgOF0) ]
[Question] [ Given an ASCII string, output the exploded suffixes of it. For example, if the string was `abcde`, there are 5 suffixes, ordered longest to shortest: ``` abcde bcde cde de e ``` Each suffix is then *exploded*, meaning each character is copied as many times as its one-indexed location in that suffix. For example, exploding the suffixes of `abcde`, ``` abcde 12345 abbcccddddeeeee bcde 1234 bccdddeeee cde 123 cddeee de 12 dee e 1 e ``` Altogether, the exploded suffixes of `abcde` are ``` abbcccddddeeeee bccdddeeee cddeee dee e ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. * The input will consist of the printable ASCII characters. (This excludes newlines but includes spaces.) * The output will have each string on a separate line. * Trailing spaces are allowed on each line and there may be an extra newline at the end. ## Test Cases ``` '' 'a' a 'bc' bcc c 'xyz' xyyzzz yzz z 'code-golf' coodddeeee-----ggggggooooooollllllllfffffffff oddeee----gggggoooooolllllllffffffff dee---ggggooooollllllfffffff e--gggoooolllllffffff -ggooollllfffff goolllffff ollfff lff f 's p a c e' s ppp aaaaa ccccccc eeeeeeeee pp aaaa cccccc eeeeeeee p aaa ccccc eeeeeee aa cccc eeeeee a ccc eeeee cc eeee c eee ee e ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṫJxJY ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmrSnhKWQ&input=&args=cyBwIGEgYyBl) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmrSnhKWQrDh-KCrGrigJzCtsK2&input=&args=JycsICdhJywgJ2JjJywgJ3h5eicsICdjb2RlLWdvbGYnLCAncyBwIGEgYyBlJw). ### How it works ``` ṫJxJY Main link. Argument: s (string) J Indices; yield I := [1, ..., len(s)]. ṫ Tail; get the suffixes of s starting at indices [1, ..., len(s)]. J Indices; yield I again. x Repeat. The atom 'x' vectorizes at depth 1 (1D arrays of numbers/characters) in its arguments. This way, each suffix t gets repeated I times, meaning that the first character of t is repeated once, the second twice, etc. If left and right argument have different lengths, the longer one is truncated, so I can safely be applied to all suffixes. Y Join, separating by linefeeds. ``` [Answer] # J, ~~22~~ ~~12~~ 8 bytes *Thanks to miles for saving 14 bytes!* ``` (#~#\)\. ``` Now this is a really nice solution. Pretty succinct, too. This is the hook `#~#\` applied to the suffixes (`\.`) of the input. The hook, when called on input `y`, is decomposed as thus: ``` (#~#\) y y #~ #\ y ``` Here are some intermediate results: ``` ]s =: 's p a c e' s p a c e #\ s 1 2 3 4 5 6 7 8 9 (quote) s 's p a c e' (quote;#)\ s +-----------+-+ |'s' |1| +-----------+-+ |'s ' |2| +-----------+-+ |'s p' |3| +-----------+-+ |'s p ' |4| +-----------+-+ |'s p a' |5| +-----------+-+ |'s p a ' |6| +-----------+-+ |'s p a c' |7| +-----------+-+ |'s p a c ' |8| +-----------+-+ |'s p a c e'|9| +-----------+-+ 1 2 3 # '123' 122333 3 3 3 # '123' 111222333 ]\. s s p a c e p a c e p a c e a c e a c e c e c e e e quote\. s 's p a c e' ' p a c e' 'p a c e' ' a c e' 'a c e' ' c e' 'c e' ' e' 'e' (#~#\) s s ppp aaaaa ccccccc eeeeeeeee (#~#\)\. s s ppp aaaaa ccccccc eeeeeeeee pp aaaa cccccc eeeeeeee p aaa ccccc eeeeeee aa cccc eeeeee a ccc eeeee cc eeee c eee ee e ``` ## Test cases ``` f =: (#~#\)\. f (#~ #\)\. f '' f 'a' a f 'bc' bcc c f 'xyz' xyyzzz yzz z f 'code-golf' coodddeeee-----ggggggooooooollllllllfffffffff oddeee----gggggoooooolllllllffffffff dee---ggggooooollllllfffffff e--gggoooolllllffffff -ggooollllfffff goolllffff ollfff lff f f 's p a c e' s ppp aaaaa ccccccc eeeeeeeee pp aaaa cccccc eeeeeeee p aaa ccccc eeeeeee aa cccc eeeeee a ccc eeeee cc eeee c eee ee e ]tc =: <;._1 '|' , '|a|bc|xyz|code-golf|s p a c e' ++-+--+---+---------+---------+ ||a|bc|xyz|code-golf|s p a c e| ++-+--+---+---------+---------+ ,. f &. > tc +---------------------------------------------+ +---------------------------------------------+ |a | +---------------------------------------------+ |bcc | |c | +---------------------------------------------+ |xyyzzz | |yzz | |z | +---------------------------------------------+ |coodddeeee-----ggggggooooooollllllllfffffffff| |oddeee----gggggoooooolllllllffffffff | |dee---ggggooooollllllfffffff | |e--gggoooolllllffffff | |-ggooollllfffff | |goolllffff | |ollfff | |lff | |f | +---------------------------------------------+ |s ppp aaaaa ccccccc eeeeeeeee| | pp aaaa cccccc eeeeeeee | |p aaa ccccc eeeeeee | | aa cccc eeeeee | |a ccc eeeee | | cc eeee | |c eee | | ee | |e | +---------------------------------------------+ ``` [Answer] ## Python, 61 bytes ``` f=lambda s,i=0:s[i:]and-~i*s[i]+f(s,i+1)or s and'\n'+f(s[1:]) ``` Alternative 63: ``` f=lambda s,b=1:s and f(s[:-1],0)+s[-1]*len(s)+b*('\n'+f(s[1:])) ``` [Answer] # Python 3, ~~91~~ ~~68~~ 65 bytes ``` def f(s):f(s[1:print(''.join(i*c for i,c in enumerate(s[0]+s)))]) ``` Terminates with an error after printing the desired output. Test it on [Ideone](http://ideone.com/zTQWcK). ### How it works Before **f** can call itself recursively, the indices of `s[1:...]` have to be computed. First `enumerate(s[0]+s)` yields all pairs **(i, c)** of characters **c** of **s** – with its first character duplicated – and the corresponding indices **i**. Prepending `s[0]` serves two purposes here. * The first character of **s** has to be repeated once, but the first index is **0**. * Once all characters have been processed, `s[0]` will raise an *IndexError*, causing **f** to terminate with an error rather than printing newlines until the recursion limit is reached. `''.join(i*c for i,c in ...)` builds a flat string of each **c** repeated **i** times, which `print` echoes to STDOUT. Finally, since `print` returns *None* and `s[1:None]` is simply `s[1:]`, the recursive call `f(s[1:...])` repeats the above process for **s** without its first character. [Answer] # [Perl 6](https://perl6.org), 38 bytes ``` m:ex/.+$/.map:{put [~] .comb Zx 1..*} ``` 37 bytes + 1 for `-n` command line switch ## Example: ``` $ perl6 -ne 'm:ex/.+$/.map:{put [~] .comb Zx 1..*}' <<< 'code-golf' coodddeeee-----ggggggooooooollllllllfffffffff oddeee----gggggoooooolllllllffffffff dee---ggggooooollllllfffffff e--gggoooolllllffffff -ggooollllfffff goolllffff ollfff lff f ``` ## Expanded: ``` # -n command line switch takes each input line and places it in 「$_」 # You can think of it as surrounding the whole program with a for loop # like this: for lines() { # match m :exhaustive # every possible way / .+ $/ # at least one character, followed by the end of the string .map: { put # print with newline [~] # reduce using string concatenation ( don't add spaces between elements ) .comb # split into individual chars Z[x] # zip using string repetition operator 1 .. * # 1,2,3,4 ... Inf } } ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 17 bytes ``` @]Elyk:Erz:jac@w\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=QF1FbHlrOkVyejpqYWNAd1w&input=ImNvZGUtZ29sZiI) ### Explanation ``` @]E E is a suffix of the Input lyk The list [0, ..., length(E) - 1] :Erz The list [[0th char of E, 0], ..., [Last char of E, length(E) - 1]] :ja For all elements of that list, concatenate the Ith char I times to itself c Concatenate the list into a string @w Write followed by a line break \ False: backtrack to another suffix of the Input ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes ``` .sRvyvyN>×}J, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=LnNSdnl2eU4-w5d9Siw&input=Y29kZS1nb2xm) **Explanation** ``` .s # push list of suffixes of input R # reverse the list vy # for each string vy } # for each char in string N>× # repeat it index+1 times J, # join and print with newline ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 14 bytes ``` Sl+{_eee~n1>}h ``` [Try it online!](http://cjam.tryitonline.net/#code=U2wre19lZWV-bjE-fWg&input=cyBwIGEgYyBl) ### Explanation ``` Sl+ e# Read input and prepend a space. { e# While the string is non-empty... _ e# Make a copy. ee e# Enumerate. Gives, e.g. [[0 ' ] [1 'a] [2 'b] [3 'c]]. e~ e# Run-length decode. Gives "abbccc". n e# Print with trailing linefeed. 1> e# Discard first character. }h ``` [Answer] # C#, 101 bytes ``` f=s=>{var r="\n";for(int i=0;i<s.Length;)r+=new string(s[i],++i);return""==s?r:r+f(s.Substring(1));}; ``` Recursive anonymous function, which also prints a leading newline. If the leading newline is not allowed, 3 extra bytes turn it into a trailing newline: ``` f=s=>{var r="";for(int i=0;i<s.Length;)r+=new string(s[i],++i);return""==s?r:r+"\n"+f(s.Substring(1));}; ``` Full program with ungolfed method and test cases: ``` using System; namespace ExplodedSuffixes { class Program { static void Main(string[] args) { Func<string, string> f = null; f = s => { var r = "\n"; for (int i = 0; i < s.Length; ) r += new string(s[i], ++i); return "" == s ? r : r + f(s.Substring(1)); }; // test cases: string x = "abcde"; Console.WriteLine("\'" + x + "\'" + f(x)); x = ""; Console.WriteLine("\'" + x + "\'" + f(x)); x = "a"; Console.WriteLine("\'" + x + "\'" + f(x)); x = "bc"; Console.WriteLine("\'" + x + "\'" + f(x)); x = "xyz"; Console.WriteLine("\'" + x + "\'" + f(x)); x = "code-golf"; Console.WriteLine("\'" + x + "\'" + f(x)); x = "s p a c e"; Console.WriteLine("\'" + x + "\'" + f(x)); } } } ``` [Answer] # Haskell, 48 bytes ``` e=map(concat.zipWith replicate[1..]).scanr(:)[] ``` is interfaced by any of ``` ghc exploded_suffixes.hs -e 'e"abcde"' ghc exploded_suffixes.hs -e 'mapM_ putStrLn.e=<<getLine' <<<code-golf ghc exploded_suffixes.hs -e 'Control.Monad.forever$putStr.unlines.e=<<getLine' ``` [Answer] ## Perl, 36 + 1 (`-n`) = 37 bytes ``` /.+$(?{$.=say$&=~s%.%$&x$.++%rge})^/ ``` Needs `-n` and `-E` (or `-M5.010`) to run : ``` perl -nE '/.+$(?{$.=say$&=~s%.%$&x$.++%rge})^/' <<< "code-golf" ``` Note that it works on only one instance each time you run it (because it uses the variable `$.` which is incremented every time a line is read, so it hold `1` only the first time a line is read). (But no problem here, just `^D` and re-run it!) [Answer] # [Retina](http://github.com/mbuettner/retina), 31 bytes Byte count assumes ISO 8859-1 encoding. ``` M&!`.+ $.%`$*» %+r`»($|.) $1$1 ``` [Try it online!](http://retina.tryitonline.net/#code=TSYhYC4rCgokLiVgJCrCuwolK3JgwrsoJHwuKQokMSQx&input=cyBwIGEgYyBl) [Answer] # Java, ~~150~~ 127 bytes Edit: * ***-23** bytes off. Thanks to @Kevin Cruijssen* Snipet: ``` f->{String s[]=f.split(""),o="";int i=-1,j,l=s.length;for(;++i<l;)for(j=-2;++j<i;o+=s[i]);return l<1?"":o+"\n"+f.substring(1);} ``` Ungolfed: ``` public static String explodeSuff(String suff){ char [] s = suff.toCharArray(); String out = ""; if(s.length==0)return ""; for(int i=-1;++i<s.length;){ for(int j=-2;++j<i;){ out+=s[i]; } } return out+"\n"+suff.subString(1); } ``` [Answer] ## Racket 184 bytes ``` (let p((l(string->list s))(ol'()))(cond[(null? l)(display(list->string(flatten ol)))] [else(p(cdr l)(append ol(list #\newline)(for/list((i l)(n(length l)))(for/list((j(+ 1 n)))i))))])) ``` Ungolfed: ``` (define(f s) (let loop((l(string->list s)) (outl '())) (cond [(null? l) (display (list->string (flatten outl)))] [else (loop (rest l) (append outl (list #\newline) (for/list ((i l) (n (length l))) (for/list ((j (add1 n))) i ))))] ))) (f "abcde") (f "xyz") ``` Output: ``` abbcccddddeeeee bccdddeeee cddeee dee e xyyzzz yzz z ``` [Answer] ## JavaScript (ES6), 65 bytes ``` f=s=>s?[s.replace(/./g,(c,i)=>c.repeat(i+1)),...f(s.slice(1))]:[] ``` ``` <input oninput=o.textContent=f(this.value).join`\n`><pre id=o> ``` Previous attempts: ``` 67: s=>[...s].map((_,i)=>s.slice(i).replace(/./g,(c,i)=>c.repeat(i+1))) 84: s=>s.replace(/./g,`$&$' `).match(/.+/g).map(s=>s.replace(/./g,(c,i)=>c.repeat(i+1))) 89: f=(s,t=s.replace(/./g,(c,i)=>c.repeat(i+1)))=>t?[]:[t,...f(s,t.replace(/(.)(?=\1)/g,''))] ``` [Answer] # PHP, 103 bytes (99 with short tags) ``` <?php for($s=$argv[1];""!=$s[$i++];$o.=" ")for($j=0;""!=$l=$s[$j+$i-1];)$o.=str_pad('',++$j,$l);echo$o; ``` I'm pretty certain this isn't the shortest possible answer. [Answer] # [MATL](http://github.com/lmendo/MATL), 12 bytes ``` &+gYRYs"G@Y" ``` *I love it when quote marks come together!* [Try it online!](http://matl.tryitonline.net/#code=JitnWVJZcyJHQFki&input=J2FiY2RlJw) ### Explanation This works by building a matrix whose columns are used, one by one, to run-length decode the input. As an example, for input `'abcde'` the matrix is ``` 1 0 0 0 0 2 1 0 0 0 3 2 1 0 0 4 3 2 1 0 5 4 3 2 1 ``` Code: ``` &+g % Implicit input. NxN matrix of ones, where N is input size YR % Set entries above diagonal to zero Ys % Cumulative sum of each column. This gives the desired matrix " % For each column G % Push input (for example 'abcde') @ % Push current column (for example [0;0;1;2;3]) Y" % Run-length decode (example output 'cddeee') % Implicit end % Implicit display ``` [Answer] # Python 3, 95 bytes ``` def f(s):return'\n'.join(''.join(s[j:][i]*(i+1)for i in range(len(s)-j))for j in range(len(s))) ``` This was surprisingly harder than I expected it to be. I redid my whole function maybe 4 times. [Answer] # Java 7,140 bytes ``` void c(char[]a,int l,int j){if(l<1)return;c(a,--l,++j);for(int i=0,k;i<j;i++)for(k=0;k++<=i;)System.out.print(a[i+l]);System.out.println();} ``` # Ungolfed ``` void c(char[]a,int l,int j) { if (l < 1) return ; c(a , --l , ++j) ; for(int i = 0 , k; i < j ; i++) for(k = 0 ; k++ <= i ;) System.out.print(a[i+l]); System.out.println(); } ``` Following line giving me very pain.i don't know how can i golfed it(because there are two loops to break the condition to put `"\n"` in print statement). `System.out.println();` [Answer] ## Pyke, 12 bytes ``` VilS],A*s }t ``` [Try it here!](http://pyke.catbus.co.uk/?code=VilS%5D%2CA%2as%0A%7Dt&input=abcde) [Answer] # Ruby, 51 bytes Uses the `-n` flag for +1 byte. ``` (k=0;puts$_.gsub(/./){$&*k+=1};$_[0]="")while$_>$/ ``` [Answer] # R, 108 bytes Read input from stdin and prints to stdout ``` s=scan(,"");n=nchar(s);for(i in 1:n)cat(do.call("rep",list(strsplit(s,"")[[1]][i:n],1:(n-i+1))),"\n",sep="") ``` I felt the use of `do.call` was appropriate here. It basically takes two inputs: 1. a function name in form of a string (`rep` here) and a list of arguments and 2. iteratively applies calls the function using the arguments in the list. E.g.: * `rep("c",3)` produces the vector `"c" "c" "c"` * `do.call("rep",list(c("a","b","c"),1:3))` produces the vector `"a" "b" "b" "c" "c" "c"` * which is equivalent to consecutively calling `rep("a",1)`, `rep("b",2)` and `rep("c",3)` [Answer] # Vim, 43 bytes `qqYlpx@qq@qqr0<C-H><C-V>{$:s/\v%V(.)\1*/&\1/g<CR>@rq@r` First macro separates the suffixes, second macro "explodes" them. Likely beatable. Spaces are annoying. [Answer] # C, 186 Bytes ``` #include <string.h> #define S strlen p(char* s){char *t=s;char u[999]="";for(int i=0;i<S(s);i++){for(int j=i+1;j>0;j--){sprintf(u+S(u),"%c",*t);}t++;}printf("%s\n",u);if(S(s)>1)p(s+1);} ``` This probably can be shortened quite a bit, but I just wanted to try it. It's my second try at golf, so give me any pointers (\*lol) you can. It takes a string as a parameter and does the exploding from there. u is used as a buffer that stores the exploded string. Ungolfed: ``` #include <string.h> #define S strlen p(char* s){ char *t=s; char u[999]=""; for(int i=0;i<S(s);i++){ for(int j=i+1;j>0;j--){ sprintf(u+S(u),"%c",*t); } t++; } printf("%s\n",u); if(S(s)>1)p(s+1); } ``` [Answer] ## [*Acc!!*](https://codegolf.stackexchange.com/a/62493/16766), 150 bytes Expects input on stdin, terminated with a tab character. ``` N Count c while _/128^c-9 { _+N*128^(c+1) } Count i while _-9 { Count j while _/128^j-9 { Count k while j+1-k { Write _/128^j%128 } } Write 10 _/128 } ``` ### Explanation This is actually a pretty good task for *Acc!!*, since it only requires reading a string and iterating over it with some nested loops. We read the string into the accumulator, treating it as a sequence of base-128 digits, with the first character on the low-order end. After the opening `Count c` loop, the accumulator value can be conceptualized like this (using `xyz` as example input): ``` 128^ 3 2 1 0 tab z y x ``` (The actual accumulator value for this example is `9*128^3 + 122*128^2 + 121*128 + 120` = `20888824`.) We can then iterate over the string by iterating over increasing powers of 128. And we can iterate over the suffixes by dividing the accumulator by 128 after each iteration, chopping off a character. With indentation and comments: ``` # Initialize the accumulator with the first input character N # Loop until most recent input was a tab (ASCII 9) Count c while _/128^c - 9 { # Input another character and add it at the left end (next higher power of 128) _ + N * 128^(c+1) } # Loop over each suffix, until only the tab is left Count i while _ - 9 { # Loop over powers of 128 until the tab Count j while _/128^j - 9 { # Loop (j+1) times Count k while j + 1 - k { # Output the j'th character Write _ / 128^j % 128 } } # Output a newline Write 10 # Remove a character _/128 } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 6 bytes ``` ÞKvÞżṠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw55LdsOexbzhuaAiLCIiLCJjb2RlLWdvbGYiXQ==) [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 48 bytes ``` ;=xP Wx;=iF;W<=i+1i+1LxO+*Gx-iT1i"\";O""=xSxF1"" ``` [Try it online!](https://knight-lang.netlify.app/#WyI7PXhQIFd4Oz1pRjtXPD1pKzFpKzFMeE8rKkd4LWlUMWlcIlxcXCI7T1wiXCI9eFN4RjFcIlwiIiwiY29kZS1nb2xmIl0=) ]
[Question] [ This challenge, I hope, is simple to understand. Given a date-string (given in any format you prefer, **so long as it has 4 digits of year and 2 digits of day and month**), calculate the weekday for the particular date-string. You must output 7 different values, corresponding to the weekday you have calculated. It's okay if your program only theoretically (given enough time and memory) prints the correct weekday, as long as it can calculate for years between 2000 and 2002. If you're using a built-in, consider adding a non-built-in approach as well. Built-in solutions won't be considered for being accepted. Make sure to account for leap years! ## Test cases Input format is `DD/MM/YYYY`, output is one of `Su, Mo, Tu, We, Th, Fr, Sa` (both can be adjusted for your choice) ``` Input -> Output 12/11/2001 -> Mo 29/02/2000 -> Tu 04/07/2002 -> Th 11/08/2000 -> Fr ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins! **EDIT**: When I said "No built-ins", I meant that *built-ins that automatically calculate the weekday for a particular date* were *discouraged*, not prohibited. If the built-in aids in finding the weekday, no problem, but if it directly calculates the weekday then I *discourage* it. [Answer] # Excel (ms365), 12 bytes ``` =WEEKDAY(A1) ``` Outputs numbers [1-7] where Sunday == 1; [![![enter image description here](https://i.stack.imgur.com/sX5uq.png)](https://i.stack.imgur.com/sX5uq.png) --- # Excel (ms365), 14 bytes ``` =WEEKDAY(A1,2) ``` Outputs numbers [1-7] where Monday == 1: [![enter image description here](https://i.stack.imgur.com/QxL4y.png)](https://i.stack.imgur.com/QxL4y.png) --- # Excel (ms365), 15 bytes ``` =TEXT(A1,"ddd") ``` Outputs lowercase text [mo-su]: [![enter image description here](https://i.stack.imgur.com/i8es3.png)](https://i.stack.imgur.com/i8es3.png) --- # Excel (ms365), 23 bytes ``` =PROPER(TEXT(A1,"ddd")) ``` Outputs text [Mo-Su] capitalizing the first letter: [![enter image description here](https://i.stack.imgur.com/nZsmM.png)](https://i.stack.imgur.com/nZsmM.png) --- **Note:** Excel will recognize the date-strings as actual dates. Therefor having date-strings and date-numbers would have the same effect. [Answer] # [R](https://www.r-project.org/), ~~31~~ 30 bytes *Edit: doesn't beat [Robin Ryder's answer](https://codegolf.stackexchange.com/a/252639/95126) but at least (currently) ties it* ``` function(s)el(as.Date(s):1)%%7 ``` [Try it online!](https://tio.run/##K/qfklhp@z@tNC@5JDM/T6NYMzVHI7FYzyWxJBXIsTLUVFU1B6nRUDIyMDLSNTTQNTBV0vwPAA "R – Try It Online") Semi built-in solution. Thursday is `0`, and then cycles through `1`-`6`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ ~~24~~ ~~22~~ ~~21~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4Ö2‚I3@è³¹²23*9÷Æ7% ``` -12 bytes thanks to *@DominicVanEssen* (and *@Neil*) for reminding me that the challenge years are guaranteed to be 2000-2002 -2 bytes porting [*@Arnauld*'s JavaScript (top) answer](https://codegolf.stackexchange.com/a/252703/52210), so make sure to upvote him as well! -1 byte thanks to *@DominicVanEssen* again in *@Arnauld*'s port -2 bytes taking three loose inputs instead of a triplet Three loose input-integers in the order `yyyy,MM,dd`; output is an integer where `6` = Sunday, `5` = Monday, ..., `0` = Saturday. [Try it online](https://tio.run/##yy9OTMpM/f/f5PA0o0cNszyNHQ6vOLT50M5Dm4yMtSwPbz/cZq76/7@RgYEhlyEQGQEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVQQmjYoZX/TQ5PM3rUMCvS2OHwiohD6yKNjLUsD28/3Gau@t/F/lHD3KOTDvceXXBoPZCeDcSrjk46tPNRw86je4HE4clABcrFh1coKWgc3q@ppPM/OtrQSMfQUMfIwMAwVifayFLHwAjEMQByDEx0DMxBHCMgB6jGwAIuA@QYwjlGyBxjZI4JMscUmWOGzDGHc2IB). **Explanation:** ``` 4Ö # Check if the (implicit) first input-year is divisible by 4 2‚ # Pair this 0 or 1 with 2 I # Push the second input-month 3@ # Check if it's >=3 è # Use that to index into the pair ³ # Push the third input-day ¹ # Push the first input-year ² # Push the second input-month 23* # Multiply the month by 23 9÷ # Integer-divided by 9 Æ # Reduce the entire stack by subtracting: # [m%4<1,2][m>=3]-d-y-m*23//9 7% # Modulo-7, resulting in 6 to 0 for Sunday to Saturday ``` --- **Original ~~36~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` `UD3‹©12*+>₂*T÷®XαD4÷O7% ``` [Try it online](https://tio.run/##ATcAyP9vc2FiaWX//2BVRDPigLnCqTEyKis@4oKCKlTDt8KuWM6xRDTDt083Jf//WzEyLDExLDIwMDFd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/hFAX40cNOw@tNDTS0rZ71NSkFXJ4@6F1Eec2upgc3u5vrvrfxf5Rw9yjCw6tPzrpcC9Q6eHJQOLo3qOTDu0EiqwC4tlABcrFh1coKWgc3q@ppPM/OtrQSMfQUMfIwMAwVifayFLHwAjEMQByDEx0DMxBHCMgB6jGwAIuA@QYwjlGyBxjZI4JMscUmWOGzDGHc2IB). **Explanation:** 05AB1E lacks any date builtins (except for the current year/month/day/etc.), so everything is done manually using [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence), taken from [this earlier 05AB1E answer of mine](https://codegolf.stackexchange.com/a/173126/52210): The formula to do this is: $${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$ Where for the months March through December: * \$q\$ is the \$day\$ of the month (`[1, 31]`) * \$m\$ is the 1-indexed \$month\$ (`[3, 12]`) * \$K\$ is the year of the century (\$year \bmod 100\$) * \$J\$ is the 0-indexed century (\$\left\lfloor {\frac {year}{100}}\right\rfloor\$) And for the months January and February: * \$q\$ is the \$day\$ of the month (`[1, 31]`) * \$m\$ is the 1-indexed \$month + 12\$ (`[13, 14]`) * \$K\$ is the year of the century for the previous year (\$(year - 1) \bmod 100\$) * \$J\$ is the 0-indexed century for the previous year (\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\$) Resulting in the day of the week \$h\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday. But, since the challenge states the year is guaranteed to be 2000-2002, we can simplify the formula to this instead: $${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor\right){\bmod{7}}}$$ Resulting in the day of the week \$h\$, where 0 = Friday, 1 = Saturday, ..., 6 = Thursday. As for the actual program: ``` ` # Push the day, month, and year of the (implicit) input-triplet to the stack U # Pop and save the year in variable `X` D # Duplicate the month 3‹ # Check if the month is below 3 (Jan. / Feb.), # resulting in 1 or 0 for truthy/falsey respectively © # Store this in variable `®` (without popping) 12* # Multiply it by 12 (either 0 or 12) + # And add it to the month # This first part was to make Jan. / Feb. 13 and 14 > # Month + 1 ₂* # Multiplied by 26 T÷ # Integer-divided by 10 ® # Push month<3 from variable `®` again Xα # Take the absolute difference with the year D4÷ # mYear, integer-divided by 4 O # Sum all values on the stack together 7% # And then take modulo-7 to complete the formula, # resulting in 0 to 6 for Friday to Thursday # (which is output implicitly as result) ``` [Answer] # [R](https://www.r-project.org/), ~~30~~ 27 bytes -3 bytes thanks to naffetS ``` function(s)strftime(s,"%A") ``` [Try it online!](https://tio.run/##K/qfklhp@z@tNC@5JDM/T6NYs7ikKK0kMzdVo1hHSdVRSROkQEPJyMDISNfQQNfAFCgCAA "R – Try It Online") 3 bytes shorter than the [alternate R solution](https://codegolf.stackexchange.com/a/252630/86301). The natural solution would be to use `format(as.Date(s), "%A")`, which converts `s` to the `Date` class then displays only the weekday. Luckily, the `strftime` is a wrapper for this, saving a few bytes. [Answer] # [Red](http://www.red-lang.org), 13 bytes ``` func[d][d/10] ``` [Try it online!](https://tio.run/##K0pN@R@UmhIdy8WVZvU/rTQvOTolNjpF39Ag9n9aflFqYnKGQkpiSapCNJcCEBgZGBjqGgKREYxroGtgpGtkCeMa6RqY6xqYIMlaANVzxUYXFGXmlSikgQ2L5fwPAA "Red – Try It Online") Returns `1` to `7`, Monday is 1 # [Red](http://www.red-lang.org), 46 bytes ``` func[d][take/part system/locale/days/(d/10) 2] ``` [Try it online!](https://tio.run/##TYw7CsMwEETr6BRbJoXQagnkcwy3QsWiXZEQxzaSUvj0igkYMkzzeMMUlT6ohGhMvvf8mVKQGBq/1C1cGtS1Nn27cU48qhNeqzuK83gCij3PRTk9QLgpBANbCNFbv5V2RItk6bYjWbxYPP/Z67Y3MSzlOTXIv7N46F8 "Red – Try It Online") Returns `Mo Tu We Th Fr Sa Su` [Red](http://www.red-lang.org)'s `date!` datatype has `weekday` accessor that is also aliased by index 10. So for a date `d` we can write `d/weekday` or shorter `d/10` [Answer] # JavaScript (ES6), 38 bytes This is an attempt at solving the challenge without a built-in, using a formula optimized for 2000-2002. Expects `(year, month, day)`. Returns \$0\$ for Sunday, \$1\$ for Monday, ..., \$6\$ for Saturday. ``` (y,m,d)=>~((m<3?y%4<1:2)-d-y-23*m/9)%7 ``` [Try it online!](https://tio.run/##TY4xTsQwEEV7TjHNKjZxgpNFWu1uwjaIAgkoUlFasROM4njlGFCE4ARINJRwD86zF9gjhEloIo1Go//mz59H8Sy60um9j1or1VDlA@mZYZLmF@@EmGy56xfnWbJJaSSjPkqXp@ZsTRerobKOaMgh2YKGDBK@XuEUhhReTwCk8Aphq17gEkeScs4ZYGm6RdwjG1fiWvmrp6a5V8KRiZgZubGtfyAUQgwZb87QdHQyONWhXuHXYBhI1FAsbdvZRsWNrclk8fa6uLslNO4aXSrCWcIpG71ICu90WyPbC1l44TxJ/xnk88AeP9lBcPz9PHx/YQ9gA8Hh5yPAyLfhDw "JavaScript (Node.js) – Try It Online") ### Commented This is based on the following C code by Michael Keith and Tom Craver: ``` (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7 ``` [Wikipedia article](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Keith) ``` (y, m, d) => // y = year, m = month, d = day ~( // take the ones' complement of: ( // conditional offset: m < 3 ? // if this is January or February: y % 4 < 1 // use 1 if this is 2000 // (which is a leap year) // or 0 otherwise : // else: 2 // use 2 ) // - d // subtract the non-conditional offset: - y // d + y + 23 * m / 9 - 23 * m / 9 // ) % 7 // apply modulo 7 ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~14~~ 13 bytes ``` date -d$1 +%u ``` [Try it online!](https://tio.run/##VU7vaoMwEP/uUxxZBhEJxNCxFpdt0O0ptB9cctKwocWkIIjP7k7bdVtICL@/dx91OM7NubXRdy00IoVxdnVEkI7nkN2f5ylxaL/qnqgaIoZoBNNK5TKnqxksQEmlpd5dgJbqUarNTdmSk6V/W3A4oY3ojMhBwwYe/qn2iPYTexpTDe@6GnZ7ekvdFb5Vw3ZPhU3XgxDgjSrAPzE@3v30lq@HiRWQZT5NC9clQCcacizrl9yTunK4cLfQLx8MFw0wHmnKmqUYwcDAGPrx4jr1vo2rDeQz8AB8vK5e8pfDVLUscV2L8zc "Bash – Try It Online") *Saved a byte thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!!!* Inputs the date as `YYYY-MM-DD` and returns \$1\$ for Monday, \$2\$ for Tuesday, up to \$7\$ for Sunday. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~16~~ 6 bytes Takes datetime object as input, [per OP](https://codegolf.stackexchange.com/questions/252621/which-weekday-was-it/252685#comment562259_252621). Takes date as `YYYY-MM-DD` and returns 0–6 for Thursday–Wednesday. ``` d=>d%7 ``` ### Old solution with string input ``` s=>new Date(s)%7 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1i4vtVzBJbEkVaNYU9X8f3J@XnF@TqpeTn66RlqCkYGBoa4hEBklaHJhSBnoGhjpGllikzLSNTDXNTDBocsCaGaC5n8A "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` lambda*t:date(*t).weekday() from datetime import* ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUavEKiWxJFVDq0RTrzw1NTslsVJDkyutKD9XASRekpmbqpCZW5BfVKL1v6AoM69EI03DyMDAUMcQiIw0NbmQBA10jHQsUYWMdMx1TNBVWQA1a2r@BwA "Python 3 – Try It Online") Represents mon-sun as 0-6 [Answer] # Excel, 10 bytes ``` =MOD(A1,7) ``` Returns `0W/01/1900` where `W` is `0`–`6` for Saturday–Friday. [![Excel screenshot](https://i.stack.imgur.com/bbXdR.png)](https://i.stack.imgur.com/bbXdR.png) [Answer] # Mathematica, 7 bytes ``` DayName ``` ## Mathematica (without `DayName`), ~~49~~ ~~42~~ 38 bytes ``` First@DateDifference[{1,1,1},#]~Mod~7& ``` [View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/2f7e7dd4-9d31-4d34-92d6-2f20e1b620be) Takes dates in `MM/DD/YYYY` format (will complain if the date happens to be parsable as `DD/MM/YYYY`, but it still outputs the correct answer). `DayName` returns the full name of the weekday. The other answer returns 0 for Monday, 1 for Tuesday, up to 6 for Sunday. The non-`DayName` answer can probably still be golfed a decent amount, I'm pretty new to Mathematica. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 7 bytes [SBCS](https://github.com/abrudz/SBCS) Anonymous tacit prefix function taking date as `YYYY MM DD`. ``` 7|1⎕DT⊂ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=M68xfNQ31SXkUVcTAA&f=e9Q39VHbhDQFIwMDQwVDIDLieoQQMlAwMFIwskQWMlIwMFcwMEFTZQHUCwA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) `⊂` enclose to make a scalar date `1⎕DT` convert to Dyalog Day Number (days since 1899-12-31) `7|` remainder when divided by 7 (gives 0–6 for Sunday–Saturday) [Answer] # [Factor](https://factorcode.org/), 11 bytes ``` day-of-week ``` [Try it online!](https://tio.run/##BcFBDoIwEAXQfU/xPQCmuCJo3Bo3bAwHmLSfxLQWHMaYnr68t0iwVdv8ek6PEUEySxRFohZmbEqzuum7GHZ@fyyBO67OXbz38AP6HrcoxjtwQsUH0bUotVuX7k@mdm4H "Factor – Try It Online") Takes input as a `timestamp`. Outputs an integer `0-6` signifying `Sunday-Saturday`. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~21~~ ~~20.5~~ ~~16.5~~ 15.5 bytes (31 nibbles) *Edit: -4 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/questions/252621/which-weekday-was-it#comment562554_252644)* ``` %-+/*23@9+_$?-@2 2/%_3~7 ``` Saturday is `0` ... Friday is `6`. Uses [Arnauld's simplified approach](https://codegolf.stackexchange.com/questions/252621/which-weekday-was-it#comment562554_252644). ``` %-+/*23@9+_$?-@2 2/%_3~7 *23@ # month times 23 / 9 # integer-divided by 9 + # add this to +_$ # the year plus the day - # and subtract ?-@2 # if the month is ≤2 2 # 2 # otherwise %_3 # year modulo 3 / ~ # integer-divided by 2 % 7 # finally, modulo 7 ``` [![enter image description here](https://i.stack.imgur.com/xBPEF.png)](https://i.stack.imgur.com/xBPEF.png) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 16 bytes ``` %{date $_|% D*k} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvbmRgYKhrCERG6joKIJ6BroGRrpEllGeka2Cua2CCkLMAKlZXqPmvWp2SWJKqoBJfo6rgopVd@/8/AA "PowerShell – Try It Online") Input comes from the pipeline. Straightforward: ``` %{date $_|% D*k} %{ } # % is an alias for ForEach-Object; the loop variable in the ScriptBlock "{}" is $_ date $_ # pass the string as input to Get-Date, which will return a DateTime object |% D*k # pipe the DateTime object to ForEach-Object, this time not with a ScriptBlock, but instead calls the member DayOfWeek # Output is implicit ``` **Disclaimer:** This drops the `Get-` from `Get-Date`; if PS finds no other command with that name, it will try to add `Get-` and find the cmdlet `Get-Date`; don't use this in regular scripts, as the search for the command will slow it down. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~22~~ 21 bytes Takes input as an array like `[Y,M,D]` and returns a number from `0` (Sunday) to `6` (Saturday). -1 byte thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus) ``` ->d{Time.gm(*d).wday} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclW0km5RSmJJqlLsojTbpaUlaboWW3XtUqpDMnNT9dJzNbRSNPXKUxIrayFyN-MLFNKio40MDAx1FAxB2Cg2VkFZwTefCyZhoKNgBESWYPGQUrg4UNBcR8EEIpyBrNwCZBRY3K0IYs2CBRAaAA) [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` 8XO ``` Input format is `YYYY/MM/DD`. [Try it online!](https://tio.run/##y00syfn/3yLC//9/dSMDA0N9QyAyUgcA) Or [verify all test cases](https://tio.run/##y00syfmf8N8iwv@/S8h/dSMDA0N9QyAyUucCcQz0DYz0jSwhHCN9A3N9AxO4jAVQpToA). [Answer] # [Julia 1.0](http://julialang.org/), ~~41~~ 39 bytes ``` using Dates;!d=Dates.dayofweek(Date(d)) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v7Q4My9dwSWxJLXYWjHFFszQS0mszE8rT03N1gDxNVI0Nf/nJhZoKOpEKxkZGBjqGgKRkZKOAohnoGtgpGtkCeUZ6RqY6xqYIOQsgIqVYjUVauwUCooy80r@AwA "Julia 1.0 – Try It Online") *Saved 2 bytes thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!* Returns 1 for Monday, 2 for Tuesday, up to 7 for Sunday. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~29~~ 21 bytes ``` 4Ḋ2"?3≥i???23*9ḭWƒ-7% ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI04biKMlwiPzPiiaVpPz8/MjMqOeG4rVfGki03JSIsIiIsIjIwMDFcbjExXG4xMiJd) Port of 05AB1E. [Answer] ## JS, ~~23~~ 13 bytes Passed as string ``` s=>new Date(s).getDay() ``` Passed as object, per OP ``` d=>d.getDay() ``` [Answer] # [Go](https://go.dev), ~~96~~ 85 bytes ``` import."time" func f(d string)int{e,_:=Parse("02/01/2006",d);return int(e.Weekday())} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY1LCsIwEED3PUXIKoHapEG0Kt6hG3EpoU1KqElLmi6keBI3RfAS3sTbmH4Q6Wpg3sx7j2dR9e-aZyUvBNBcmUDpurIORFBqB1-tk6vkc5qWEXRKCxjI1mRAohw0zipTYGVcJ8LL_phy2wgEKSM0JozSDQxzfLDCtdYAf4VEdBaizPkNYXyf5c2oG9oIgy5IvdJdDZIIxozEoyeGGP8DtiO-4QFdALomdDsAtgDeQ5Pfx5zu-2l-AQ) Hoo ray for verbose builtins! * -11 bytes for returning an `int` (@Steffan) [Answer] # [Nim](http://nim-lang.org/), 47 bytes ``` import times,sugar x=>x.parse"ddMMyyyy".weekday ``` [Try it online!](https://tio.run/##Vc4xC8MgEIbhPb/icDJQwimFtkI6dc3cWaJJpRhFLTW/3kome9Px8A3vZmwx1ruQIBmrY@eDmyHSRcDx0SwgpmC2tRfw1Pr9kHsPYweg55eDBQjjjHFERhrjN@TVsDU846Uab40xvB67v4ZT/KwydJHm8Z4HL0PURKlp2uuR4VsjVI0o5Qc "Nim – Try It Online") It takes the date in the format `ddMMyyyy` and prints the full name of the weekday. [Answer] # [PHP](https://php.net/), 33 bytes ``` <?=date('l',strtotime($argv[1])); ``` [Try it online!](https://tio.run/##K8go@P/fxt42JbEkVUM9R12nuKSoJL8kMzdVQyWxKL0s2jBWU9P6////RgZGRrqGBroGZgA "PHP – Try It Online") [Answer] # [APL(Dyalog Unicode)](https://dyalog.com) REPL, 0 bytes Takes date as `7|1⎕DT⊂YYYY MM DD` and gives 0–6 for Sunday–Saturday [Try it on TryAPL!](https://tryapl.org/?clear&q=7%7C1%E2%8E%95DT%E2%8A%822001%2011%2012&run) This abuses [OP ruling](https://codegolf.stackexchange.com/questions/252621/which-weekday-was-it/252685#comment562260_252621) that a valid input format can contain the code that solves the problem. For an explanation, see [my other APL answer](https://codegolf.stackexchange.com/a/252684/43319). [Answer] # jq, 17 characters ``` strptime("%F")[6] ``` Input: YYYY-MM-DD Output: 0 = Sunday .. 6 = Saturday Sample run: ``` bash-5.1$ jq -R 'strptime("%F")[6]' <<< '2012-05-04' # manatwork joined CGCC 5 ``` [Try it online!](https://tio.run/##yyr8/7@4pKigJDM3VUNJ1U1JM9os9v9/IwMDQ11DIDL6lw@Uy88r/q@rW5RYrpuZV1BaAgA "jq – Try It Online") / [Try all test cases online!](https://tio.run/##lY9NS8NAEIbP3V8xrmk3OSxsltYPTEAPFjyIULzFUGKyJdGaxN0NCNXfns6mpdWDh8IyMzz7zsw7r5kp@0Ll60wr4HdglbHLPDMq9skoYVKIkIf4JEvjEM7hsdljwYXk8hqxRPzc7bHk4pKLKeKpw@VRfYVzEM8QzzUJCGl1VdsVsG8Y83BmYMjiT5YYX2oG7KFuO4t5oUy3dsX9V6tyqwosn94ZIatGQ@VEGIF6m7PDIclt@kNvoEDjeuiOqefD2yfwBbDeWN3a6kP5dDynQXKR9gyiKMIRwzQKASVkdILVQyP1dutctTm62X2jJXA2kuSXLo7/k6YpTCag8rIZznWmiqZW/RY "Bash – Try It Online") [Answer] # Rust + chrono, ~~58~~ 21 bytes ``` chrono::Date::weekday ``` [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9c37c5abb57131f38aba75997ac8a594) An expression that can be coerced to a `fn(&Date<Utc>)->Weekday`. It takes a Date object and returns Weekday, an enum with 7 possible values. [Answer] # Java, 13 bytes ``` d->d.getDay() ``` A `Function<java.util.Date, Integer>`. Returns 0 for Sunday, 1 for Monday, ..., 6 for Saturday. [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Input as a string in the format `yyyy-mm-dd` (or any valid JavaScript date string), output as a 3 letter abbreviation. ``` 3îÐU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=M%2b7QVQ&input=IjIwMDEtMTEtMTIi) ``` 3îÐU :Implicit input of string U 3î :Slice to length 3 ÐU :Construct date object from U ``` **Note:** This is locale/browser dependent. For the included test case, for example, the date object is expected to return `Mon Nov 12 2001 00:00:00 GMT+0000 (Greenwich Mean Time)`. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `t`, 22 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` 4Ḋ2,$3®i⁶°¹23×9÷KrƲ-7% ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0UolS7IKlpSVpuhY3FUwe7ugy0lExPrQu81HjtkMbDu00Mj483fLwdu-iY5t0zVWXFCclF0NVL1hlZGBgyGUIREYQEQA) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` # implicit input 4Ḋ # divisible by 4 2, # pair with 2 $ # next input 3® # greater than or equal to 3 i # indexing ⁶ # third input ° # first input ¹ # second input 23× # multiply by 23 9÷ # floor divide by 9 Kr # push the stack Ʋ # cumulative reduce by: - # subtraction 7% # modulo 7 # implicit output of tail ``` [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda y,m,d:((d+((y+y//4)+(0x562ad0e6c0>>m*3&7)))-(m<3)*(y%4<1)+6)%7 ``` [Try it online!](https://tio.run/##DcJBCoMwFAXAq7ixvGdSjEYjFPUkbtKm0oJRKS76Tx8dZpfjs602zcOUFh@fwWeiow4PIChAlJRlQwXzb13tg3m7lxnHWNhbR/KO2FsWkLzpKyrHvEv777semFE5ndVXQ6YT "Python 3 – Try It Online") ]
[Question] [ You will be given two integers \$M\$ and \$N\$. Find the number of pairs \$(x,y)\$ such that \$1 \le x \le M\$, \$1 \le y \le N\$ and \$(x+y)\bmod5 = 0\$. For example, if \$M = 6\$ and \$N = 12\$, pairs which satisfies such conditions are, \$(1,4), (4,1), (1,9), (2,3), (2,8), (3,2), (3,7), (3,12), (4,6), (6,4), (4,11), (5,5), (5,10), (6,9)\$ Total \$14\$. ### Sample ``` Input : 6 12 Output: 14 Input : 11 14 Output: 31 Input : 553 29 Output: 3208 Input : 2 2 Output: 0 Input : 752486 871672 Output: 131184195318 ``` This is a code-golf challenge so code with lowest bytes wins! ### Update **[Jonathan Allan's](https://codegolf.stackexchange.com/a/205303/95294)** solution has the smallest code size, **5 bytes**. However, it doesn't produce an answer for the last given test. I have decided to go with the next answer with the shortest size that produces the correct answer for the largest test, there is a tie between two golfers who competed neck-to-neck. I proudly present the winners of this challenge **[Lyxal](https://codegolf.stackexchange.com/a/205326/95294)** and **[Kevin Cruijssen](https://codegolf.stackexchange.com/a/205374/95294)** with only **7 bytes** code! Congratulations! 🎉 As many of you, I found **[Arnauld's](https://codegolf.stackexchange.com/a/205311/95294)** answer most helpful in finding the correct solution. So, I am accepting Arnauld's answer. Thank you, Golfers! [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` lambda m,n:(m*n+abs(m%5-~n%5))/5 ``` [Try it online!](https://tio.run/##XY5NDoIwEIX3PcVsSFqpkVYKiOlN3BQFaUIHQiHCxqsjsCKuXubL@5luHuoW5VKN@NSNccXLgOOY@9FROoUzC5TWEVRtDxNYhN7gu6SCu1CwDc5HiCtkpNKP5dBE3QlDU3jqAnX@YqAYu6hly7pDNmI52VfwH4LxvuwH2D6kayHTutqVkE9tmxJEvl7aYjcOlN273uJq3h1LwoUkQnARE6WuXN6I5JKkSsZZwrNUJKn8AQ "Python 2 – Try It Online") Adapts an [idea from Arnauld](https://codegolf.stackexchange.com/a/205311/20260). We estimate that \$1/5\$ of the \$mn\$ pairs will satisfy the mod-5 condition. Th actual value may be one higher depending on the mod-5 values of \$m\$ and \$n\$, and we bump up \$mn\$ a bit so that these make it pass the next multiple of 5. --- **34 bytes** ``` lambda m,n:m*n/5+(0<-m%5*(-n%5)<5) ``` [Try it online!](https://tio.run/##XY5NDoMgEIX3nIKNCSimQkWtlZt0Y1utJDIa1FRPT9GV6eplvryfGbe5G0C4doGX6mvzfNfYMCinxRCyRhsNpFIJbgeLV6wB2xo@DeHMRJzucDtD8JCiVj3cqcmEcJERSarYBDIkMQSSVpK6PW1O6YSW6NiBf4jraWrsjPcfia@kSrWHIvTtdN9gXvpLaRiXmdD7aDV48@FwGeMCcc54iqS8MnFDggmUS5EWGStynuXiBw "Python 2 – Try It Online") **34 bytes** ``` lambda m,n:m*n/5+(m*n%5+m%5+n%5)/9 ``` [Try it online!](https://tio.run/##XY7NDoMgEITvPAWXJlBJFCr@NbxJL7SVSiKrQU316Sl6Mj1sJvtlZnbHbe4GEMEs8FK9ds@3xo5BMy2OkDXZ6EUqlWEzeLxiC9hr@LSEM5dwusPtDCFCiox6hFOTu0IqExLlIhMXJypN67Cn3Smd0QYdd@AfYj1NrZ/x/iOJlVQpcyhC3872LeZN3JSFcZkJvY/eQjQfjlAwLhDnjOdIyhsTNRJMoFKKvCpYVfKiFD8 "Python 2 – Try It Online") **36 bytes** ``` lambda m,n:m*n/5+((5-m%5)*(5-n%5)<5) ``` [Try it online!](https://tio.run/##XY5BDoMgFET3nIKNCShNhYpaW27SDW21ksjXoKZ6eoquTFeT/zIzf4Z1ansQvpnhpTptn2@NLYNqnC0hS7LSSCqV4qZ3eMEGsNPwqQlnNuF0g@sRQoAUNerhD002hrNMCJEnG0kaB4Wgd0n9lreHfEortH@Cf4j1ONZuwttKEkqpUs2uCH1b09WYV@FSBoZ5IvQ2OAPBvDt8zrhAnDOeISkvTFyRYAIVUmRlzsqC54X4AQ "Python 2 – Try It Online") **36 bytes** ``` lambda m,n:m*n/5+(abs(m%5+n%5*1j)>4) ``` [Try it online!](https://tio.run/##XY5NDoIwEIX3PUU3JK00kakUEFNP4qYoCIYOhEKE01dgRVy9zJf3M/0y1h1KX0341K2xxctQKzB3k2VsDhceKK0jWnUDnWmDdDD4LhkIGwLf4HKEuEJOKv3whyZ7wrMKmSkcs4EKMVAn@PB7zP2Wt4d8xHOyL@E/pMa5chjp9iVbS7nW1a6EfOumLSnk66Ub7KeR8Vs/NLiad4dPBEgCICAmSl2EvBIpJEmVjLNEZCkkqfwB "Python 2 – Try It Online") **36 bytes** ``` lambda m,n:m*n/5+(m%5*5/4+n%5*5/4>5) ``` [Try it online!](https://tio.run/##XY5BDoMgFET3nIJNE1AShYpaG3qSbmirlUS@BjXV01O0G9PV5L/MzJ9hndoehG9meKpO28dLY8ugGmdLyBKv9CSVSnHTO7xgA9hpeNeEMxtzusH1CCFAihp194cmG0EiY2JPMpJJFsNPb5L6LW8P@ZRWaP8E/xDrcazdhLeVJJRSpZpdEfq0pqsxr8KlDAzzROh1cAaCeXf4nHGBOGc8Q1KembggwQQqpMjKnJUFzwvxBQ "Python 2 – Try It Online") **36 bytes** ``` lambda m,n:m*n/5+(m%5+n%5+m*n%5/4>5) ``` [Try it online!](https://tio.run/##XY7BDoMgEETvfAUXE6gkChW1NvRLeqGtVBJZDWpav56iJ9PDZjMvM7M7rnM3gAhmgafqtXu8NHYMmmlxhHzTlSZSqRybweMvtoC9hndLOHMppxtcjxAipMioezg0uRNkMiUukSnEiTKRWXGTNGx5d8jntEH7JfiHWE9T62e8fUliKVXK7BuhT2f7FvMmKmVhXGZCr6O3EM27I5SMC8Q54wWS8szEBQkmUCVFUZesrnhZiR8 "Python 2 – Try It Online") [Answer] # JavaScript (ES6), 29 bytes Takes input as `(m)(n)`. ``` m=>g=n=>n&&(m+n%5)/5+g(n-1)|0 ``` [Try it online!](https://tio.run/##XcyxCoMwEADQvV@RpXKH2OSiETvEfxGroUUvouLkv6dJtzo/eJ/u6LZ@fS97wf41hNGG2bbOsm05y2DO@W5QmtwBF4SnCr3nzU/DY/IORqgRSCMKIaQUVN3@lShylThqSRc1pkTQz8hJtWourqP@6uQqfAE "JavaScript (Node.js) – Try It Online") ### How? Let's consider a grid of width \$m\$ with 1-indexed coordinates and an `X` mark on each cell for which: $$(x+y)\equiv 0\pmod 5$$ Here are the first few rows for \$m=9\$: ``` | 1 2 3 4 5 6 7 8 9 ---+------------------- 1 | - - - X - - - - X 2 | - - X - - - - X - 3 | - X - - - - X - - 4 | X - - - - X - - - 5 | - - - - X - - - - 6 | - - - X - - - - X 7 | - - X - - - - X - ``` Computing \$m+(y\bmod5)\$ is equivalent to left-padding each row in such a way that all `X` marks are vertically aligned and appear on columns whose index is a multiple of \$5\$. With such a configuration, the number of marks is directly given by \$\lfloor{L\_y/5}\rfloor\$, where \$L\_y\$ is the updated length of the \$y\$-th row. ``` y | y%5 | padded row | length | // 5 ---+-----+----------------------------+--------+------ 1 | 1 | + - - - X - - - - X | 10 | 2 2 | 2 | + + - - X - - - - X - | 11 | 2 3 | 3 | + + + - X - - - - X - - | 12 | 2 4 | 4 | + + + + X - - - - X - - - | 13 | 2 5 | 0 | - - - - X - - - - | 9 | 1 6 | 1 | + - - - X - - - - X | 10 | 2 7 | 2 | + + - - X - - - - X - | 11 | 2 ---+-----+----------^---------^-------+--------+------ | 0 0 0 0 **0** 0 0 0 0 **1** 1 1 1 | | 1 2 3 4 **5** 6 7 8 9 **0** 1 2 3 | ``` We use this method to recursively compute the number of marks on each row. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` p§5ḍS ``` **[Try it online!](https://tio.run/##y0rNyan8/7/g0HLThzt6g////2/239AIAA "Jelly – Try It Online")** ### How? ``` p§5ḍS - Link: positive integer, M; positive integer N p - (implicit [1..M]) Cartesian product (implicit [1..N]) § - sums 5ḍ - five divides? (vectorises) S - sum ``` [Answer] # [J](http://jsoftware.com/), 20 bytes ``` 1#.[+/\0=5|1}.1+i.@+ ``` [Try it online!](https://tio.run/##LczBCsIwEATQe79iUbBI6jazSZq0UCgKnsSD13oTi/XiD@i3x4T2MId5u8w7bricqO@opIo0dSkHptPtco7Y8qjqu@7dFz@GmnlQcV9cj0xjp@qhyhdRqt7NXBTPx@tDsNRTQxNBFjBIAGSxq4gOyZwzCaVdUCeR3NcZAwSL1hnkX@/EhrwaPBovFP8 "J – Try It Online") The standard `O(m*n)` cartesian product solution saves 3 bytes `[:+/@,0=5|2++/&i.`, but I figured I'd try a different approach: A solution using a sliding window. I *think* J is able to optimize this approach automatically into `O(m+n)`... in any case, I get an out of memory error on the final test case on TIO with the cartesian product approach but not with this one Let's take `6 f 12` as an example: 1. Generate the numbers 1 through 18 `1+i.@+`: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ``` 2. Kill the first 1 `1}.`: ``` 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ``` 3. Turn it into a 0-1 list indicating which numbers are divisible by 5 `0=5|` ``` 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 ``` 4. Create a sliding window of length of the left arg (either arg would work though), summing each piece of the window `[+/\`: ``` 1 /`````````\ etc... 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 \_________/ 1 Final result: 1 1 1 2 1 1 1 1 2 1 1 1 ``` 5. Sum of all those numbers `1#.`: ``` 14 ``` [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` lambda n,m:sum((i//n+i%n)%5==3for i in range(n*m)) ``` [Try it online!](https://tio.run/##Hc1BCoMwEAXQfU4xG2HSipJYhQrepJsUtR1wJiFJF57eRmf5/@NP2PPXS3esMMHr2By/ZwdS85h@jEhtK3eqRFf9NHWrj0BAAtHJZ0G5sdYHcfAxQ9qTUifYSJbTlKBJeSYZFZSTGri8YBeQJNcXa1LYKKPWlwixFLjiKcvuAMYqY8A8VN93YJ/Kgv0D "Python 3 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes Full program. ``` ≢⍸0=5|+/¨⍳⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jzkWPencY2JrWaOsfWvGod/Ojvqkgmf8KYFDAZaZgaMQF4xgaKhiawHmmpsYKRpZwrpECQqG5qZGJhZmChbmhmbkRAA "APL (Dyalog Unicode) – Try It Online") (largest test case would work with 3TB RAM) Reads quite literally as the problem specification: `≢` count `⍸` where `0=` 0 equals `5|` the mod-5 of `+/` the sum of `¨` each of `⍳` all indices until `⎕` the input. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` :i:!+5\~z ``` [Try it online!](https://tio.run/##y00syfn/3yrTSlHbNKau6v9/My5DIwA "MATL – Try It Online") ### How it works ``` : % Implicit input: M. Range [1 2 ... M] i: % Input: N. Range [1 2 ... N] ! % Transpose + % Add, element-wise with broadcast. Gives an N×M matrix 5 % Push 5 \ % Modulus, element-wise ~ % Negate z % Number of nonzeros. Implicit display ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~12~~ 11 bytes *-1 thanks to @Mukundan* ``` lf!%sT5*FSM ``` [Try it online!](https://tio.run/##K6gsyfj/PydNUbU4xFTLLdj3//9oU1NjHSPLWAA "Pyth – Try It Online") ``` lf!%sT5*FSM SM Map 1-indexed range to each input *F Cartesian product of the two ranges f Filter by: sT - sum of elements.. !% 5 - .. is divisible by 5 l Take the length ``` [Answer] # [R](https://www.r-project.org/), 40 bytes ``` function(m,n)sum(!(rep(1:m,e=n)+1:n)%%5) ``` [Try it online!](https://tio.run/##K/pfkJhZVBxfXJobn5JZZmr7P600L7kkMz9PI1cnTxMorKGoUZRaoGFolauTapunqW1olaepqmqqiaZRw0zH0EjzPwA "R – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ╒5%+5/Σ ``` Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/205311/52210), so make sure to upvote him! [Try it online.](https://tio.run/##y00syUjPz0n7///R1Emmqtqm@ucW//9vpmBoxGVoqGBowmVqaqxgZMllpGDEZW5qZGJhpmBhbmhmbgQA) **Explanation:** ``` ╒ # Push a list in the range [1, (implicit) first input] 5% # Modulo-5 on each value in the list + # Add the second (implicit) input to each 5/ # Integer-divide each value by 5 Σ # And sum the list # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` f=lambda m,n:m and(m%5+n)/5+f(m-1,n) ``` [Try it online!](https://tio.run/##PY7BasMwDIbvfgpdBnGadpXTpGkghzE6KNsobL2NUdLUpWaxYxSXLk@fiZXtIpD06dPvh3DunBqN9R0F6Ic@AdJ9d6FGC@5mvQ6kmwv1pnOtsSZEOI/jXIo/6pe4bf5Hby@b181u/757eHxO4EPFsVolMMVPOZ6qtraHYw02caWF2h0je5dNnLzPJqfITjFxcryeTasBSwGBhpJRcAnob6@bABXY2kfGBQ5aX/fG@UuI5Kz3LSeQUjDXaB9gvX1aE3VUwoF0/SWA@JQ/sIshT2wAYkdV3cRjDqgAFwKRK6QosiwFtYJUzQuhQMFcLDO1KHIolpgvmU0RiwWushQL@AE "Python 2 – Try It Online") Use [@Arnauld's formula](https://codegolf.stackexchange.com/a/205311/92237), be sure to checkout and upvote his answer! --- Original solution, using a longer formula: # [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes *-1 byte thanks to @xnor!* ``` f=lambda m,n:m and(n%5>~m%5)+n/5+f(m-1,n) ``` [Try it online!](https://tio.run/##PY5RS8MwEMff8ynuZdB03dylS9cWKohMGCqC7k1kdF3Ggk0a0pS5F796PRz6cnB3v/vd313CqbNi1MZ1PkB/6RPwqu8G3yhG3bxXwatm8L3ubKuNDhEu4jjj7I/6Ja6b/9Hr0@Z5s929be/uHxN4F3EsigRm@MHHY9XWZn@owSS2NFDbQ2Qn8vbbTCSf2hs5PUZmhonl4/mkWwVYMgj@UhIPNgH15VQToAJTu0jbQGnr805bN4SIz3vXUgzOGXGNcgHWLw9r7ztfwt6r@pOBp1P6QC6CnCcDeHJU1VU8ZoACcMkQqUKKTMoURAGpWORMgIAFW0mxzDPIV5itiE0R8yUWMsUcfgA "Python 2 – Try It Online") For each number `i` between 1 to `m`, there are `(n%5+i%5>4)+n/5` numbers between 1 to n that can be paired with `i`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ 7 bytes ``` L5%+5÷O ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fx1RV2/Twdv///w2NuMwA "05AB1E – Try It Online") A 100% port of @Arnauld's Javascript answer [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 15 bytes ``` +//~5!+/:/1+!:' ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NSltfv85UUVvfSt9QW9FK/X@agpmCoRFXmoKhoYKhCZA2NTVWMLIEMowUDLj@AwA "K (ngn/k) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes ``` Length@Solve[1<=x<=#&&1<=y<=#2&&Mod[x+y,5]==0,Integers]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yc1L70kwyE4P6csNdrQxrbCxlZZTQ3IqAQyjNTUfPNToiu0K3VMY21tDXQ880pS01OLimPV/gcUZeaV6DukOzg4KFRXm@kYGtXqVBsa6hiaAGlTU2MdI0sgw0jHqLb2/38A "Wolfram Language (Mathematica) – Try It Online") [Answer] # perl -M5.010 -al, 49 bytes ``` for(1..$_){for$y(1..$F[1]){($_+$y)%5||$c++}}say$c ``` [Try it online!](https://tio.run/##K0gtyjH9r5Jsa2D9Py2/SMNQT08lXrMayFSpBHPcog1jNas1VOK1VSo1VU1ralSStbVra4sTK1WS//83UzA04jI0VDA04TI1NVYwsuQyUjD6l19QkpmfV/xf19dUz8DQ4L9uYg4A "Perl 5 – Try It Online") This is a pretty stupid, "iterate over all pairs, count the ones where sum mod 5 equals zero", solution. There's a nicer formula, but I couldn't (yet) reduce that down enough. It will take a very long time to calculate the answer to (752486, 871672), but there was no time limit stated. The TIO link has a `$c = 0;` in the header. This isn't needed for a single line solution; it's only there to make it work with multiple inputs (and as such, TIO won't count those bytes). [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õ ï+Võ)èv5 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9SDvK1b1Keh2NQ&input=MTEKMTQ) ``` õ ï+Võ)èv5 :Implicit input of integers U & V õ :Range [1,U] ï :Cartesian product with Võ : Range [1,V] + : Reduce each pair by addition ) :End Cartesian product è :Count the elements v5 : Divisible by 5 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 36 bytes ``` f(n,m){n=m*n/5+((5-m%5)*(5-n%5)<5);} ``` [Try it online!](https://tio.run/##hZDdaoQwEIXv9ykGQTAa0ajxB9felD7FKmXr6jYXxsV4IRWf3Y67alsobSAZBs75ODmlfS3Lea4NSRsyyqwxpcMtw@B2o3Ni4pQ4j5yk09ychTQIjAfAI2QP8rWvVK9OBWQAY0iBMQqc@xS8KQXHpBBxL4hDXPq2hTdxhbrtFqsC09kxzQ8M85ATICL5wsQRCyPvH0w13Kqyv1PGBeBjGN9zYwruimE@Y3HAEu6z@A9Y@X7uTOgeJC0fXrx8SJ7xco3C993XpvTuWAjGkkGgxU1xHEGJj6rFXh@fI866o4qkYFliK3KLr9C6y0@ioHsvoiDpLr11KK4NTb9Q0C9gPy2vrnKJ2X43U1AUf7PWI4osUxtwOkzzJw "C (gcc) – Try It Online") A port of one of [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [formulas](https://codegolf.stackexchange.com/a/205302/9481). [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 69 bytes Posting before I run out of time. ``` f(X,Y)->[[A,B]||A<-lists:seq(1,X),B<-lists:seq(1,Y),((A+B)rem 5)==0]. ``` [Try it online!](https://tio.run/##Vci9CoMwEADg3afIeIcXqUI7SBWSp1BCBpGzHPjTJoEuvnva1W/8OKzT/tIc5yDvlIu8wEAj6t45Q9afp3nqVWKKbeQP1DQg2euMSACmtBh4U3fsupuv8jbJDs6j0n2h/uRov0ESwwIPUnWDWOUf "Erlang (escript) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 12 bytes ``` IΣ÷⁺﹪…·¹N⁵N⁵ ``` [Try it online!](https://tio.run/##bcixDYAgEEDRVSiPRAtMtLHUhkJjdAJEoiQIBjnWPxnA3/2nLxV1UI5oidYnGNSbYMMbpE@jzfYwsDh8YQoHulBUl7PZrMqfBkTFpH8wzXjvJgLnFWv5n5V6oo6JhursPg "Charcoal – Try It Online") Link is to verbose version of code. Port of @KevinCruijssen's answer, although that's apparently a port of @Arnauld's answer. Explanation: ``` …· Inclusive range from ¹ Literal `1` to N First input number ﹪ Vectorised Modulo ⁵ Literal `5` ⁺ Vectorised Plus N Second input number ÷ Vectorised Integer divide by ⁵ Literal `5` Σ Take the sum I Cast to string Implicitly print ``` Previous 16-byte brute force answer: ``` NθI№⭆N⭆θ﹪⁺²⁺ιλ⁵0 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObEYSOSXApnBJUCRdN/EAg1kpZo6CgiJQh0F3/yU0px8jYCc0mINIx0FMJ2po5CjCVRoqgkilQyUgLT1//9mCoZG/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `M`. ``` ⭆N⭆θ ``` Input `N` and loop over `N` and `M`, casting the result to a string. ``` ﹪⁺²⁺ιλ⁵ ``` Take the sum modulo 5, adjusted for 1-indexing (sigh). ``` I№...0 ``` Count the `0`s in the result. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 6 bytes ``` ɾ5%+5ḭ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%C9%BE5%25%2B5%E1%B8%AD&inputs=553%0A29&header=&footer=) ]
[Question] [ You have to make a game Too-low --- Too-high (TLTH) in shortest code (in bytes) ## Game rules: 1. Computer will choose a random number out of integer range (-32768..32767). 2. Now you will think of a number and input it. 3. The computer will tell if your number is lower (`TOO LOW`) or higher (`TOO HIGH`) than the chosen number. 4. When you guess the number, the computer should display `Congrats! You found the number!`. ## Code Rules: 1. Do not use the characters `T`, `O`, `L`, `W`, `H`, `I` and `G` (neither lowercase nor uppercase) in string or character literals. For instance: ``` tolower(T); // Acceptable cout<<"T"; // Unacceptable char ch='T'; // Unacceptable ``` 2. **Remove 300 bytes** if your code can display the game rules before starting the game. 3. **Remove 50 bytes** if your code can count number of turns and display number of turns taken in the end of game like this: ``` "Congrats! You found the number in n turns!" ``` where n is number of turns taken, instead of ``` "Congrats! You found the number!" ``` 4. **Remove 25 bytes** from your score if your code can tell user that the number you input is out of integer range. For example: ``` Enter the number: 40000 Sorry! This number is out of range Please Enter the number again: ``` 5. **Remove 25 bytes** If your code takes the random number not from any built-in random function. 6. **Remove 10 bytes** If your code display "congrats" in color (pick any color except default white). ## Submission Rules: 1. Add a heading with your language name and score with all bounty calculation and its explanation. 2. Post your golfed and ungolfed code. ## Winner 1. The answer with **least bytes** wins. 2. If there is a tie, the answer with the more votes wins. 3. The winner will be chosen after 5 days. **EDIT**:Please show your code's output. **EDIT-2**: You can ignore Rule-1 for Rules-2,3 & 4 in Code Rules Best Of Luck :] [Answer] # Perl 5.10+: ~~159~~ 144 bytes − 350 = −206 points ``` say"Guess 16 bit signed number";$==32767-rand 65536;say(TOO.$",$_<0?LOW:HIGH)while++$i,$_=<>-$=;say"Congrats! You found the number in $i turns!" ``` **Edit 2:** With the recent rules change that allows me to use any string literal for the "congrats" message, I can save 15 bytes from my original 159-byte solution. There's nothing particularly novel or interesting about the new code above as compared to the old code (I just got rid of the `p` function, and call `say` directly instead), so the remainder of this post will describe the original code, shown below: ``` sub p{say join$",@_}p Guess,16,bit,signed,number;$==32767-rand 65536;p(TOO,$_<0?LOW:HIGH)while++$i,$_=<>-$=;p Congrats."!",You,found,the,number,in,$i,turns."!" ``` Yeah, I'm abusing the hell out of rule 1. Who needs strings, when you can have [barewords](http://perlmaven.com/barewords-in-perl)? ;-) Run with `perl -M5.010` to enable the Perl 5.10+ `say` feature (or replace the body of the `p` function with `print join$",@_,$/` for an extra cost of 5 bytes). Bonus scores: * −300 points: "display the game rules before starting the game" * −50 points: "display number of turns taken in the end of game" The code contains *no* string literals in a strict sense, so I'd say that rule 1 is, technically, not violated. The trick is that, in Perl, without `use strict`, any identifier that doesn't correspond to a known language keyword or subroutine will simple evaluate to its own name. The function `p` then simply takes a list of words and prints them out, separated by spaces. Example play-through: ``` Guess 16 bit signed number 0 TOO HIGH -10000 TOO LOW -5000 TOO HIGH -7500 TOO LOW -6250 TOO HIGH -6875 TOO LOW -6553 TOO HIGH -6700 TOO HIGH -6790 TOO LOW -6745 TOO HIGH -6767 TOO LOW -6756 TOO HIGH -6761 Congrats! You found the number in 13 turns! ``` **Edit:** Oh, right, the rules say I need to post an un-golfed version of the code too, so here it goes. Technically, it's "de-golfed", since I usually compose my code golf programs in more or less fully golfed form from the beginning, and it can sometimes be tricky to remove all the "golfy" optimizations without fundamentally changing how some parts of the program work. Still, I've at least tried to add whitespace, comments and more meaningful function / variable names: ``` sub output { # print all arguments separated by spaces, plus a newline: # (in the golfed code, I use the special variable $" instead of " " for a space) say join " ", @_; } # print the rules: output Guess, 16, bit, signed, number; # choose a random number between -32768 and 32767 inclusive: # (in the golfed version, using the special variable $= allows # the int() to be left out, since $= can only take integer values) $number = int( 32767 - rand 65536 ); # loop until the input equals the chosen number, printing "TOO LOW / HIGH": # (the loop ends when $diff == 0, since 0 is false in Perl) output (TOO, $diff < 0 ? LOW : HIGH) while ++$count, $diff = (<> - $number); # print congratulations, including the loop count: output Congrats."!", You, found, the, number, in, $count, turns."!"; ``` --- **Ps.** As an alternative, if just using barewords instead of strings feels too cheaty for you, here's a 182-byte solution that doesn't use the letters `TOLWHIG` *even in barewords* (but does use them in a transliteration operator). It still gets the same bonuses, for a total score of **182 − 350 = −168 points**: ``` sub t{pop=~y/kpqvxyz/tolwhig/r}say"Guess 16 bit signed number";$==32767-rand 65536;say uc t"kpp ".($_<0?qpv:xyzx)while++$n,$_=<>-$=;say t"Cpnzraks! Ypu fpund kxe number yn $n kurns!" ``` The output looks exactly the same as above. Per the (original) rules, I do use the letters `t` and `i` in printing the rules, since it's allowed; eliminating even those uses would only cost two extra bytes, though. Conversely, making all the output uppercase (which, based on comments above, seems to be allowed) would let me save three bytes. [Answer] # Python 2: -80 points (270-300-50) ``` print"WhileURong(USayNumbr;ISayBigrOrSmalr)" import random r=random.randint(-32768,32767) g=i=1 while g:g=cmp(input(),r);print("C\x6fn\x67ra\x74s! Y\x6fu f\x6fund \x74\x68e number \x69n %d \x74urns!"%i,"\x54\x4f\x4f \x48\x49\x47\x48","\x54\x4f\x4f \x4c\x4f\x57")[g];i+=1 ``` Score is 270 characters, minus 300 for showing the instructions, minus 50 for showing the number of guesses in the "congrats!" string, for a total of negative 80 points. Ungolfed version of the loop, with unescaped strings: ``` while g: g=cmp(input(),r) print ("Congrats! You found the number in %d turns!"%i, "TOO HIGH", "TOO LOW")[g] i+=1 ``` The built-in `cmp` function returns 0 if the values are equal, -1 if the first is smaller and 1 if the first is bigger. I use the value to index a tuple of strings, and then again as the exit condition of the loop. Indexing a sequence with a negative index (like -1) counts from the end of the sequence, rather than from the start. I was sorely tempted to skip the imports and just use `4` as my random number, as per [XKCD 221](http://xkcd.com/221/) (would that qualify for the -25 character bonus?). Example run (complete with an error, where I can't do negative math): ``` WhileURong(USayNumbr;ISayBigrOrSmalr) 0 TOO HIGH -16000 TOO LOW -8000 TOO HIGH -12000 TOO HIGH -14000 TOO LOW -13000 TOO HIGH -13500 TOO HIGH -13750 TOO LOW -13625 TOO HIGH -13712 TOO LOW -13660 TOO HIGH -13640 TOO HIGH -13685 TOO HIGH -13700 TOO LOW -13695 TOO LOW -13690 TOO LOW -13687 Congrats! You found the number in 17 turns! ``` [Answer] # JavaScript 293, -300 (rules) - 50 (turns display) - 25 (range warning) - 25 (no random function) = -107 (new score) `r=new Date%65536+~(z=32767);n=x="";for((A=alert)("\107uess my number, \111 \147\151ve feedback");(x=prompt())!=r;A(0>(x-~z^x-z)?"\164\157\157 "+(x>r?"\150\151\147\150":"\154\157\167"):"Ran\147e: "+~z+" - "+z))n++;A("C\157n\147ra\164s! Y\157u f\157und \164\150e number \151n "+ ++n+"\164urns!")` I'd claim that by RGB conventions that black is a color, but that would be kinda cheating... Oh, and might I add, no breaking rule #1, either! Output in a series of alerts and prompts ``` ALERT: Guess my number, I give feedback PROMPT: 0 ALERT: too low PROMPT: 16000 ALERT: too low PROMPT: 24000 ALERT: too low PROMPT: 28000 ALERT: too high PROMPT: 26000 ALERT: too high PROMPT: 25000 ALERT: too low PROMPT: 25500 ALERT: too high PROMPT: 25250 ALERT: too low PROMPT: 25375 ALERT: too high PROMPT: 25310 ALERT: too low PROMPT: 25342 ALERT: too low PROMPT: 25358 ALERT: too low PROMPT: 25366 ALERT: too high PROMPT: 25362 ALERT: too high PROMPT: 25360 ALERT: too high PROMPT: 25359 ALERT: Congrats! You found the number in 16 turns! ``` Ungolfed code: ``` r = (new Date)%65536+~(z=32767); //Generates random number in range based off date's milliseconds... I'd use epoch, but I need to conserve n=x=""; // Sets count and input to blank, these change as time goes on // The line below sets up a call for `alert`, provides the initial rules, and subsequent loops compares the prompt with the number, as well as sets up "too", "high", "low" and "out of range" message strings, and provides the feedback for((A=alert)("\107uess my number, \111 \147\151ve feedback");(x=prompt())!=r;A(0>(x-~z^x-z)?"\164\157\157 "+(x>r?"\150\151\147\150":"\154\157\167"):"Ran\147e: "+~z+" - "+z)) { n++; // adds one to count providing the number isn't guessed yet } alert("C\157n\147ra\164s! Y\157u f\157und \164\150e number \151n "+ ++n+" \164urns!") // Congratulates the player, and displays the correct number of turns taken ``` [Answer] ## Javascript, 324 bytes, score -76 [Updated due to rule changes] * 324 bytes * -300 for showing the rules * -50 for showing the turns when the user wins * -25 for telling the user when he inputs a number outside the range * -25 for not using built-in random (updated) Total score: -76 Golfed: ``` function q(y){return y.replace(/./g,function(x){h=x.charCodeAt(0);return String.fromCharCode(h>32&h<58?h+32:h)})}d=o=32768;alert("WhileURong(USayNumbr;ISayBigrOrSmalr)");for(a=1,n=new Date%(2*o)-o;d-n;a++)d=+prompt(a),alert(d>=o|d<-o?"BAD":d<n?q("4// ,/7"):d>n?q("4// ()'("):"Congrats! You found the number in "+a+" turns!") ``` Lets ungolf this mess. First, properly idented (but this is still not very good with obfuscated code): ``` function q(y) { return y.replace(/./g, function(x) { h = x.charCodeAt(0); return String.fromCharCode(h > 32 & h < 58 ? h + 32 : h) }) } d = o = 32768; alert("WhileURong(USayNumbr;ISayBigrOrSmalr)"); for (a = 1, n = new Date % (2 * o) - o; d - n; a++) d = +prompt(), alert(d >= o | d < -o ? "BAD" : d < n ? q("4// ,/7") : d > n ? q("4// ()'(") : "Congrats! You found the number in " + a + " turns!") ``` Second, renaming identifiers: ``` function unencrypt(encrypted) { return encrypted.replace(/./g, function(character) { charCode = character.charCodeAt(0); return String.fromCharCode(charCode > 32 & charCode < 58 ? charCode + 32 : charCode) }) } guess = limit = 32768; alert("WhileURong(USayNumbr;ISayBigrOrSmalr)"); for (tries = 1, randomNumber = new Date % (2 * o) - o; guess - randomNumber; tries++) guess = +prompt(), alert(guess >= limit | guess < -limit ? "BAD" : guess < randomNumber ? unencrypt("4// ,/7") : guess > randomNumber ? q("4// ()'(") : "Congrats! You found the number in " + tries + " turns!") ``` So the unencrypt function gets all characters between ASCII 33 (`!`) and ASCII 58 (`:`) and adds 32, converting them in characters in the range `A-Z`. Lets ungolf the code more by unecrypting all the strings: ``` guess = limit = 32768; alert("WhileURong(USayNumbr;ISayBigrOrSmalr)"); for (tries = 1, randomNumber = new Date % (2 * o) - o; guess - randomNumber; tries++) guess = +prompt(), alert(guess >= limit | guess < -limit ? "BAD" : guess < randomNumber ? "TOO LOW" : guess > randomNumber ? "TOO HIGH" : "Congrats! You found the number in " + tries + " turns!") ``` And finally lets move some instructions to other places, replace the long ternary chain with ifs and elses, join concatenating strings, and simplify the math, to increase the readability: ``` guess = 32768; alert("WhileURong(USayNumbr;ISayBigrOrSmalr)"); randomNumber = new Date % 65536 - 32768; for (tries = 1; guess - randomNumber; tries++) { guess = +prompt(); // The preceding + is a golfing trick to convert string to number. if (guess > 32767 | guess < -32768) { alert("BAD"); } else if (guess < randomNumber) { alert("TOO LOW"); } else if (guess > randomNumber) { alert("TOO HIGH"); } else { alert("Congrats! You found the number in " + tries + " turns!"); } } ``` Sample: ``` ALERT: WhileURong(USayNumbr;ISayBigrOrSmalr) PROMPT: 5 ALERT: TOO LOW PROMPT: 20000 ALERT: TOO LOW PROMPT: 30000 ALERT: TOO HIGH PROMPT: 25000 ALERT: TOO HIGH PROMPT: 22500 ALERT: TOO HIGH PROMPT: 21000 ALERT: TOO HIGH PROMPT: 20500 ALERT: TOO HIGH PROMPT: 20200 ALERT: TOO LOW PROMPT: 20400 ALERT: TOO LOW PROMPT: 20450 ALERT: TOO LOW PROMPT: 20475 ALERT: TOO HIGH PROMPT: 20460 ALERT: TOO LOW PROMPT: 20468 ALERT: TOO HIGH PROMPT: 20464 ALERT: TOO LOW PROMPT: 20466 ALERT: TOO LOW PROMPT: 20467 ALERT: Congrats! You found the number in 16 turns!" ``` [Answer] # C - 272 characters - 300 - 50 - 25 = -103 * -300 for displaying the rules; * -50 for telling the player the number of turns; * -25 for not using a standard RNG library. Golfed code: ``` main(i){short a,c=i=0,b=time(0);for(a=b;b--;a=(a*233)+4594);b=a;puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");while(1){i++;scanf("%hi",&a);if(a==b){printf("Congrats! You found the number in %i turns!",i);break;}for(c=0;c^9;c++)putchar(c[a<b?"kff7cfn7!":"kff7_`^_!"]-23);}} ``` Ungolfed: ``` int main(int i) { short a, b = time(0), c = i = 0; for( a = b ; b-- ; a = (a * 233) + 4594); b = a; puts("WhileURong(USayNumbr;ISayBigrOrSmalr)"); while(1) { i++; scanf("%hi", &a); if(a == b) { printf("Congrats! You found the number in %i turns!", i); break; } for( c = 0 ; c ^ 9 ; c++ ) putchar(c[ a < b ? "kff7cfn7!" : "kff7_`^_!" ] - 23); } } ``` Output: ![Output](https://i.stack.imgur.com/epZ70.png) [Answer] # C: 237 - 300 - 50 - 25 - 25 - 10: -173 points -300 for the rules, -50 for showing the number of guesses, -25 for not using any built-in random number generator, -25 for the out of range message and -10 for colouring the congrats message. ``` int s[3]={542068564},g,n;main(r){for(r=(short)&r,puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");n++,scanf("%d",&g),s[1]=g<r?5721932:1212631368,g^r;puts(g^(short)g?"OOR":s));printf("\033[31mCongrats! You found the number in %d turns!",n);} ``` Ungolfed: ``` int s[3]={542068564},g,n; main(r){ for( r=(short)&r, puts("WhileURong(USayNumbr;ISayBigrOrSmalr)"); n++, scanf("%d",&g), s[1]=g<r?5721932:1212631368, g^r; puts(g^(short)g?"OOR":s) ); printf("\033[31mCongrats! You found the number in %d turns!",n); } ``` Example run: ``` WhileURong(USayNumbr;ISayBigrOrSmalr) -32769 OOR 32768 OOR 0 TOO HIGH -16384 TOO HIGH -24576 TOO HIGH -28672 TOO LOW -26624 TOO LOW -25600 TOO HIGH -26112 TOO LOW -25856 TOO LOW -25728 TOO LOW -25664 TOO HIGH -25696 TOO HIGH -25712 TOO LOW -25704 Congrats! You found the number in 15 turns! ``` The last line shows up as red. [Answer] ## C#: -30 points * 345 bytes * -300 for showing the rules * -50 for showing the turns when the user wins * -25 for telling the user when he inputs a number outside the range **Golfed**: ``` int l=-32768,h=32767,n=new Random().Next(l,h),t=0,g=h+1;Console.Write("WhileURong(USayNumbr;ISayBigrOrSmalr)\n");while(n!=g){g=Convert.ToInt32(Console.ReadLine());Console.WriteLine(g==n?"C\x6fn\x67ra\x74s! Y\x6fu f\x6fund \x74\x68\x65 number in {0} \x74urns!":g<l||g>h?"BAD":g<n?"\x54\x4f\x4f \x4c\x4f\x57":"\x54\x4f\x4f \x48\x49\x47\x48",++t);} ``` To run it, put it in a file (code.cs) and run with [scriptcs](https://github.com/scriptcs/scriptcs) on the command line: `scriptcs code.cs`. **Ungolfed**: Expanded variable names into something easier to understand, and changed hex letters into real letters. ``` int low = -32768, high = 32767, number = new Random().Next(low, high), turns = 0, guess = h+1; Console.Write("WhileURong(USayNumbr;ISayBigrOrSmalr)\n"); // instructions while (number != guess) { guess = Convert.ToInt32(Console.ReadLine()); Console.WriteLine( guess == number // if you got it right ? "Congrats! You found the number in {0} turns!" // give the victory speech : guess < low || guess > high // if out of range ? "BAD" // let them know : guess < number // if guess is low ? "TOO LOW" // tell them low : "TOO HIGH" // otherwise tell them high , ++turns // preincrement turns, add to output ); } ``` Sample output [available here](https://gist.github.com/yellis/2ee50bd0b51de21a7274). [Answer] # bash, -137 ### Score 273 (bytes) - 300 (rules) - 50 (count tries) - 25 (OOF warning) - 25 (custom PRNG) - 10 (color) # Golfed version ``` IFS=# a=(`<$0`) c=65536 y=$[10#`date +%N`%c] e(){ echo -e ${a[$1]/z/$z};} e 7 while read x do((z++,x+=c/2,i=3+(x>y),x==y))&&break ((x<0||x>c-1))&&i=6 e $i done e 5 #TOO LOW#TOO HIGH#\e[32mCongrats! You found the number in z turns!#OOR#Guess my number. I'll say HIGH or LOW. ``` Note that the last line is a comment, so it contains no string or character literals. ### Ungolfed version ``` MYNUMBER=$[10#$(date +%N) % 65536 - 32768] echo "Guess my number. I'll say HIGH or LOW." while true; do read YOURGUESS GUESSES=$((GUESSES + 1)) if ((YOURGUESS == MYNUMBER)); then break elif ((YOURGUESS < -32768 || YOURGUESS > 32767)); then echo OOR elif ((YOURGUESS < MYNUMBER)); then echo "TOO LOW" else echo "TOO HIGH" fi done echo -e "\e[32mYou found the number in $GUESSES turns!" ``` ### Sample output ``` $ ./tlth Guess my number. I'll say HIGH or LOW. -32769 OOR 32768 OOR 0 TOO LOW 16384 TOO HIGH 8192 TOO HIGH 4096 TOO HIGH 2048 TOO HIGH 1024 TOO HIGH 512 TOO HIGH 256 TOO HIGH 128 TOO HIGH 64 TOO HIGH 32 TOO LOW 48 TOO HIGH 40 TOO LOW 44 TOO HIGH 42 Congrats! You found the number in 17 turns! ``` The last line is printed in green. [Answer] # JavaScript (-210 points (`190` bytes - `300` *(for the rules)* - `50` *(for the number of guesses)* - `25` *(for not using any built-in random number source)* - `25` *(for telling you if the input is out of the range of a signed `16`-bit integer)*): ## Golfed: ``` alert('Guess number',n=(m=2<<15)/2-new Date%m);for(z=0;a=+prompt(++z);)alert(a>m|a<1-m?m+'-'+-~-m:a==n?'Great! You found the number in '+z+' turns':atob('VE9P\x47E'+(a>n?'hJR0g=':'xPVw=='))) ``` ## Full code (nicely formatted): ``` var max = 2 << 15; var random = max/2 - new Date%max; var counter = 0; while (1) { var guess = +prompt(); ++counter; if (guess > max | guess < -~-max) { alert(-~-max + '-' + max); // Shows that the range is between -32767 and 32768 } else if (guess > random) { alert('TOO HIGH'); } else if (guess < random) { alert('TOO LOW'); } else if (guess == random) { alert('Congrats! You found the number in ' + counter + ' turns'); break; } } ``` ## Output: ``` ALERT: Guess number PROMPT: 5 ALERT: TOO LOW PROMPT: 20000 ALERT: TOO LOW PROMPT: 30000 ALERT: TOO HIGH PROMPT: 25000 ALERT: TOO HIGH PROMPT: 22500 ALERT: TOO HIGH PROMPT: 21000 ALERT: TOO HIGH PROMPT: 20500 ALERT: TOO HIGH PROMPT: 20200 ALERT: TOO LOW PROMPT: 20400 ALERT: TOO LOW PROMPT: 20450 ALERT: TOO LOW PROMPT: 20475 ALERT: TOO HIGH PROMPT: 20460 ALERT: TOO LOW PROMPT: 20468 ALERT: TOO HIGH PROMPT: 20464 ALERT: TOO LOW PROMPT: 20466 ALERT: TOO LOW PROMPT: 34000 ALERT: -32767-32768 PROMPT: 20467 ALERT: Great! You found the number in 17 turns! PROMPT: (nothing) ``` [Answer] # C++ 505 + (-300-50-25-25) = 105 -300 : Instructions -50 : Showing number of turns -25 : Not using random function -25 : warning user about input out of range ### GOLFED ``` #include<iostream> #include<stdlib.h> using namespace std;int main(){short int a,i=0,*r=new short int;int b=0;a=*r;char t[]={84,79,79,' ','\0'},l[]={76,79,87,'\n','\0'},h[]={72,73,71,72,'\n','\0'};cout<<"WhileURong(USayNumbr;ISayBigrOrSmalr)\n";while(a!=b){cin>>b;if(b<-32768||b>32767){cout<<"Sorry! the number is out of range please enter the number again\n";continue;}i++;if(b<a){cout<<'\n'<<t<<l;}if(b>a){cout<<'\n'<<t<<h;}if(a==b){cout<<"Congrats!You found the number in "<<i<<" turns!";}}return 0;} ``` ### UNGOLFED ``` #include<iostream> #include<stdlib.h> using namespace std; int main() { short int a,i=0,*r=new short int; int b=0; a=*r; char t[]={84,79,79,' ','\0'},l[]={76,79,87,'\n','\0'},h[]={72,73,71,72,'\n','\0'}; cout<<"WhileURong(USayNumbr;ISayBigrOrSmalr)\n"; while(a!=b) { cin>>b; if(b<-32768||b>32767) { cout<<"Sorry! the number is out of range please enter the number again\n"; continue; } i++; if(b<a) { cout<<'\n'<<t<<l; } if(b>a) { cout<<'\n'<<t<<h; } if( a==b) { cout<<"Congrats!You found the number in "<<i<<" turns!"; } } return 0; } ``` ### OUTPUT ![ ](https://i.stack.imgur.com/471a9.png) [Answer] # C, 183-300-25=-142 183 bytes -300 for the rules -25 for not using a random library ``` main(){short g,n=time(0)*(time(0)&1?1:-1);puts("WhileURong(USayNumbr;ISayBigrOrSmalr)");while(g^n)scanf("%d",&g),puts(g>n?"TOO HIGH":g<n?"TOO LOW":"Congrats! You found the number!");} ``` ungolfed version: ``` main(){ short g,n=time(0)*(time(0)&1?:-1); puts("WhileURong(USayNumbr;ISayBigrOrSmalr)"); while(g^n) scanf("%d",&g), puts(g>n?"TOO HIGH":g<n?"TOO LOW":"Congrats! You found the number!"); } ``` sample run: ``` WhileURong(USayNumbr;ISayBigrOrSmalr) 40 TOO HIGH 20 TOO HIGH 1 TOO HIGH 0 TOO HIGH -20 TOO HIGH -200 TOO HIGH -2000 TOO HIGH -20000 TOO LOW -10000 TOO LOW -5000 TOO LOW -3000 TOO HIGH -4000 TOO LOW -3500 TOO HIGH -3700 TOO HIGH -3900 TOO HIGH -3950 TOO HIGH -3970 TOO LOW -3960 Congrats! You found the number! ``` [Answer] # J - 190 char -300 -50 = -160 pts ``` 'Congrats, you found the number in ',' turns!',~":1>:@]^:(]`(1[2:1!:2~a.{~71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>)@.*@-[:".1!:1@1:)^:_~32767-?2^16['WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2 ``` Explanation (recall that J is read from right to left): * `'WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2` - Print the rules. * `32767-?2^16[` - Toss the return value, and then generate a random number between 0 and 2^16-1 inclusive. Then, adjust it to the range -32768..32767 by subtracting it from 32767. * `1>:@]^:(...)^:_~` - The `x u^:v^:_ y` pattern is kinda like a while loop. `x` stays constant, and `y` gets mutated with every execution of `u`. This continues until either `x v y` returns 0 or `x u y` results in no change to `y`. The `~` swaps the two arguments, so that `x` will be the random number and `y` will begin at 1. Our `u` is `>:@]`, which increments this 1 and returns it, so it acts as a counter and the `x u y` termination condition can never occur. * `[:".1!:1@1:` - Take the counter, and ignore its value, using the number 1 instead (`1:`). Read in a line of input (`1!:1`) from the keyboard (file handle 1) and execute it (`".`). This allows J, whose negative sign is normally `_`, to take numbers in the form `-n` (evaluates as negation applied to the number `n`). * `]`(...)@.*@-` - Take the difference of the random number from before and the guess (`-`). Now, we select the next action depending on whether this difference is zero (`@.*`). If it is, return (`]``) that 0 as the result for `x v y`, so that execution terminates, and the whole while loop returns the counter. Else... * `71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>` - Return the array `5 8 16` if the number is negative, and `1 2 0 1` if it is positive. Then prepend `13 8 8 _39` and add 71 to everything, so we have either `84 79 79 32 76 79 87` or `84 79 79 32 72 73 71 72`. * `1[2:1!:2~a.{~` - Turn these numbers to ASCII characters by indexing the alphabet `a.` with them. Then print them out with `1!:2` (using file handle 2) and return 1 as the result of `x v y`. * `'Congrats, you found the number in ',' turns!',~":` - When the loop finishes, it returns the counter. Convert it to a string with `":` and put it in between the strings `'Congrats, you found the number in '` and `' turns!'`. Sample output: ``` 'Congrats, you found the number in ',' turns!',~":1>:@]^:(]`(1[2:1!:2~a.{~71+13 8 8 _39,(5 8 16;1 2 0 1){::~0&>)@.*@-[:".1!:1@1:)^:_~32767-?2^16['WhileURong(USayNumbr;ISayBigrOrSmalr)'1!:2]2 WhileURong(USayNumbr;ISayBigrOrSmalr) 0 TOO HIGH -20000 TOO LOW -10000 TOO LOW -5000 TOO HIGH -7500 TOO HIGH -8750 TOO HIGH -9000 TOO HIGH -9500 TOO LOW -9250 TOO HIGH -9375 TOO HIGH -9450 TOO LOW -9400 TOO HIGH -9425 TOO HIGH -9437 TOO LOW -9431 TOO LOW -9428 TOO HIGH -9430 TOO LOW -9429 Congrats, you found the number in 18 turns! ``` [Answer] # JavaScript -40 335 - 300 (rules) - 50 (count turns) - 25 (out of range) Not gonna win but a fun way to get the letters I think. ### Golfed ``` !function T(O,L,W,H,I,G){a=T.toString();c=L.floor(65536*L.random())+H;O(W+G+" between "+H+" & "+I);k=(f=a[9]+(d=a[11])+d+" ")+(e=a[17])+a[19]+a[21]+e;l=f+a[13]+d+a[15];for(m=1;(n=prompt(W+G))!=c;m++)n<H||n>I?O("Out of range"):n>c?O(l):O(k);O("Congrats! You found the"+G+" in "+m+" turns!")}(alert,Math,"Guess a",-32768,32767," number") ``` ### Ungolfed ``` !function T(O,L,W,H,I,G){ fn = T.toString(); random = L.floor(L.random() * 65536) + H; O(W + G + " between " + H + " & " + I); tooLow = (too = fn[9] + (o = fn[11]) + o + " ") + (h = fn[17]) + fn[19] + fn[21] + h; tooHigh = too + fn[13] + o + fn[15]; for (n=1; (guess = prompt(W + G)) != random; n++) { if (guess < H || guess > I) { O("Out of range"); } else if (guess > random) { O(tooHigh); } else { O(tooLow); } } O("Congrats! You found the" + G + " in " + n + " turns!"); }(alert, Math, "Guess a", -32768, 32767, " number") ``` ### Sample output ``` (ALERT) Guess a number between -32768 & 32767 (PROMPT) Guess a number 9999999 (ALERT) Out of range (PROMPT) Guess a number 0 (ALERT) TOO LOW (PROMPT) Guess a number 8008 (ALERT) Congrats! You found the number in 3 turns! ``` [Answer] ## APL (Dyalog) (157 - 300 - 50 = -193) (Yes, these count as bytes, the APL charset fits in a byte.) I've claimed "display the game rules" and "count the number of turns". ``` G n←32768-?65536 t←0 ⎕←'Guess 16-bit signed number' t+←1 →8/⍨n=g←⎕ ⎕←⎕AV[(⌽⎕AV)⍳'×↑↑ ','○↑-' '∇⌊∘∇'⊃⍨1+n<g] →4 ⎕←'Congrats! You found the number in't'tries!' ``` Example run: ``` G Guess 16-bit signed number ⎕: 0 TOO HIGH ⎕: -10000 TOO LOW ⎕: -5000 TOO LOW ⎕: -2500 TOO LOW ⎕: -1250 TOO HIGH ⎕: -1750 TOO LOW ⎕: -1500 TOO LOW ⎕: -1375 TOO LOW ⎕: -1300 TOO LOW ⎕: -1275 TOO LOW ⎕: -1265 TOO HIGH ⎕: -1270 TOO HIGH ⎕: -1273 Congrats! You found the number in 13 tries! ``` Ungolfed: ``` GuessNumber;num;tries;guess;decode;too;low;high decode←{⎕AV[(⌽⎕AV)⍳⍵]} ⍝ invert the character code, char 1 becomes char 255 etc. num←32768-?65536 ⍝ select a random number tries←0 ⍝ strings for low/high too←decode '×↑↑ ' low←decode '○↑-' high←decode '∇⌊∘∇' ⎕←'Guess 16-bit signed number' try: tries +← 1 guess ← ⎕ →(guess=num)/found ⍝ still here: number was wrong ⎕←too, (1+num<guess)⊃low high ⍝ output appropriate word →try ⍝ try again found: ⎕←'Congrats! You found the number in' tries 'tries!' ``` [Answer] ## Pogo: -95 (255 - 300 - 50) ``` method main:void print("Guess the number. You will be told if you are high or low.") declare(integer,n,0) declare(integer,i,0) declare(integer,j,0) random() i while j != i set(n+1) n print("Number?") getinput() j if j > i print("High") end else print("Low") end end print("Yay" n "turns") end main ``` --- If the number is 10: > > Number? > > > 5 > > > Low > > > 8 > > > Low > > > 12 > > > High > > > 10 > > > Yay 4 turns > > > --- ]
[Question] [ Given a string, shuffle it so that it becomes a palindrome. For example, `adadbcc` can be arranged into `dacbcad`, or `dcabacd`, `acdbdca` and more. Any of these (or all) is acceptable, and duplicates are allowed if outputting all. Something like `abc` cannot be shuffled into a palindrome, and you can assume it won't be inputted. (if it helps) input will only contain lowercase letters. ## Testcases These show one possible solution. ``` nanas -> nasan coconutnut -> conuttunoc apotato -> atopota manplancanalpanamaaaa -> amanaplanacanalpanama canadadance -> canadedanac nananana -> nanaanan anaan -> anana ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` p.↔ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v0DvUduU//@VkvOT8/NKS4BI6X8UAA "Brachylog – Try It Online") [Also acts as a generator for all possible outputs](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sW/C/Qe9Q25f9/pbzEvMRipf9RAA). ### Explanation ``` p. The output is a permutation of the input .↔ The output reversed is itself ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` (,~`,/@/:2|1#.e.)@/:~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXTqEnT0HfStjGoMlfVS9TSBzLr/mlypyRn5CmkK6sn5yfl5pSVApA4Xy0vMSyxGcBML8ksSS/JR5UEQSSQvMTFR/T8A "J – Try It Online") A non brute force approach which runs in n\*log(n) time. * `/:~` Sort. This ensures that like elements are grouped together. * `/:2|1#.e.` Then sort by number of occurrences, modded by 2. This puts any items with an odd number of elements at the end of the array, while keeping like elements together. * `,~`,/@` Reduce that from the right by alternately appending and prepending elements. The upshot is that we start with the middle element, and then build outward by adding pairs of elements to opposite sides. [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` *r,=s={''} for c in input():s^={c};r+={c}-s print(*r,*s,*r[::-1],sep="") ``` [Try it online!](https://tio.run/##HU2xbgMxCN35CstL7q6XIermymO6ZslWtRIlVDn1gi3sUxNF@fYL7nsPEKAH@VbPSV5XSid20Xnv10HHWOJ9s3nAT1JHbhJTXmrXh/IV7/R405dWtgWyTlI7cwxlHPQjhO3ucyyco/f9ascA/s7TzO6oCwdwhqq34PjK1LWX/f@Mr8S5uv3hfa@aNLhvZfxdBQULUKIkSzUB5lSxJrig5BmFbD9nSxc0QGtPRiGGZm0ECxR4Ag "Python 3 – Try It Online") Saved 2 bytes by [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) and [xnor](https://codegolf.stackexchange.com/users/20260/xnor). It could be [66 bytes](https://tio.run/##HU2xbsNACN35CuTJjpUh6naVx3TN0s1yJEqoYtXhTtxZTRTl212u7z1APASkR7lGfds4XgQHbJpms2GcIA/Pnb3gOxoyzupKa2m7kM/Dk1/v1teyz5Bs1tJaP@7y1NsYwv4wdZufAfi9zovgp60SAB3FHgHlLtzWZ92/J3eWVPB4@jiaRQv4ZUI/m5JSBo4cdS0uoBQLlQg30rSQss@X5OlGDqjtxaksUFcrwYP0Dw) as xnor pointed out if output as list of characters. It is \$O(n)\$. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` œʒÂQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6ORTkw43Bf7/n1iQX5JYkg8A "05AB1E – Try It Online") # Explanation ``` œ all permutations of the (implicit) input ʒ only keep those such that  push x, reversed(x) Q they are equal ``` [Answer] # [Python](https://www.python.org), 67 bytes ``` lambda x:(s:=sorted(x,key=lambda e:(x.count(e)%2,e)))[1::2]+s[::-2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU9NqsJADF7bUwyCOINVsKvHwKw8hnYRpynP99rM0EmhnsVNQfQeHsPbWNvREPLzfeFLcrn7M_866q-lOdxaLtc_z10F9bEA0WkZtAmuYSxkl_7j2UQGtew21rXEEtUiS1Eptd9qneWrsNd6neVR6lFgKRgDSwsBlU5mDYa2YmFEOUHJzDenQWe53Py5E8mJV6n4DJpYvXW3eSriPXHuzUdklFNJMq6bW2cdtTz4XEUIvGNg9-1rIF8BWSCo_BBqGOzLEo3d9EjfT_kF) Port of [Jonah's excellent J solution](https://codegolf.stackexchange.com/a/250289/85334). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 69 bytes ``` a=>[...p=a.filter(c=>!(a[c]^=1)),...a.filter(c=>a[c]),...p.reverse()] ``` [Try it online!](https://tio.run/##bczBCoMwDAbg@95iXmxhK@wB4ouIg1CjKDUpbfX1u7jTYCYhh/@Df8UDs09LLE@WkeoMFaHrnXMR0E1LKJSMh@5usPfDG17WPhR/6YRvGF2ig1ImY4c6QYZuNmdTHqxbZWHTtvbmhbMEckFmM5mGkTE39i/3osFe9C4QoxQsciEbcgzIXltD1LehzlW92qjLnlTrBw "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` f=(s,c='',r=s.replace(/^(.)(.*)\1|./,'$2'),t=RegExp.$1)=>s?t+f(r,t?c:s[0])+t:c ``` [Try it online!](https://tio.run/##bY7NCsIwEITvPkYpJLExtR4LsSdfwKs/sGzToqRJaFbx4LvXPUtnhz3MB8M84Q0Z50eiXYi9WwbLllmjFULPNpvZJQ/oZH2XRkmzVdfma2otyoNQmuzZjadPMmWj7DF3VA1y1tRhmy/7m6qoxQVjyNE74@MoB1kECJALpTZ/OUYOXsRegZAiAcUVMkHgfQG51Sd@E7DW6pn1fAEd0@UH "JavaScript (Node.js) – Try It Online") Input / Output as strings. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~124~~ ~~108~~ 107 bytes *16 bytes saved thanks to [c--](https://codegolf.stackexchange.com/users/112488/c)! 1 byte saved thanks to ceilingcat!* ``` f(c,n,i,j,k)char*c;{for(i=j=0;i<n;i++)j=*c-c[i]?j:i;k=c[i=j?n--,n--:i/2]; c[i]=c[j];c[j]=k;n>2&&f(c+!!j,n);} ``` [Try it online!](https://tio.run/##ZY/RboMgFIbv@xTUZA1WzFYvy2gfZOvFKdUN1IMRtmRr@uzuaF0WmRhy@P7//Bx0/qb1MFRcCxRGWFGn@h36rZbXyvXcKKuepHlGabIstWqrc/1iTke7N7JWVCp7xFwVwuS7vXksTnKUSbBjZU@qlngoNhvKz9ZrKzCVt@HTmQsLpQ98uor5XqfsumL0GQysKZEp5kNPBR81OUl3L5DUQtM4zb35Ll01ZaRbTuZsl85eatbdFwfB/vq7nsIrnjzkxc6z/MASwWDWqtFKCbHVv@Lsuq1W42wtGOS/w05PSJK56X6C5fEMEQA4LwECgo8ReFwiT64IIdngf9a4llQTudBCXUaC0w4/Av3RjJ0LEFwEgxvxEraAXUPBdEPT0dbCPNNt@AE "C (gcc) – Try It Online") Linebreak added for clarity. Function `f` which takes as input a pointer to the start of a `char` array and its length as `n`. Modifies the input array in place, yielding a single result. Annoying that I can't save a few bytes by using `c[i]^=c[j]^=c[i]^=c[j]` instead of a standard switch, but this expression fails when `i == j`, and accounting for that doesn't end up saving any bytes. ## Commented explanation *Slightly outdated, but the same general concept is the same. In the current version, we infer the count by observing that `k` is 1 if and only if `j` is 0.* ``` f(c,n,i,j,k,t) char*c; { // count the number of instances of the first character, *c for(i = k = 0; i < n; i++) // if we found *c in the string *c == c[i] ? k++, j = i // then note it in our tally, and note its index as j : 0; // else do nothing // i is now the original length n // j is now the index of the last occurrence of *c // we will check if there is more than one occurrence of *c --k // this is truthy iff k > 1. in this case, we set up further recursion ? n -= 2, // deduct the two solved characters from the solve length i-- // we want to swap with the end of the string (i=n-1) // else, if k == 1, then we need to put this character in the middle // to properly palindromize it : (j = 0, // we want to swap the lone character (at j=0) i /= 2); // with the center character (at i=n/2). // swap characters at positions j and i // when k>1, swaps the last occurrence of *c with the end of the string // when k==1, swaps the first character with the middle of the string t = c[i]; c[i] = c[j]; c[j] = t; // if n < 2, the string is solved // otherwise, we will recurse as follows: // - when k was initially >1, k is now k-1, and !!k evaluates to 1, // letting us recurse starting with c+1. // in this case, n is now n-2, letting us recur on the string without // the bookending characters // - when k was initially 1, k is now 0, and !!k evaluates to 0. // this means we recurse with c, and examine the character we // just swapped there. n is also unchanged in this branch. // furthermore, this swap only ever happens once because // we check n > 2 before attempting to recurse. n > 2 && f(c + !!k, n); } ``` [Answer] # [Python](https://www.python.org), 120 bytes ``` lambda a,j="".join:[C:=Counter(a),x:=j(C[c]//2*c for c in C)][1]+j(C[c]%2*c for c in C)+x[::-1] from collections import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY1RCsIwEET_PUUoCK1tLfolgX71GLXCGg2mJLshbqGexZ-C6J28jYWKUIdlBt4szP3lb3whHB663D871vnu3VtwxxMIyNoyitYtGZR1JcuKOuRziCHJelm2cVWrpii2KyU0BaGEQVElTb1p0qlb_lVpX0uZb5qFDuSEImvPig3hVRjnKfDqu3_wwSDHOo4UKcKOx4uSZPHD4ImBacYcoLeAChCsH83BqNkH4kSmlWGY8gM) There's probably a much shorter way to do this in \$ O(n!n) \$ time or something silly like that, but this is linear I think. # [Python](https://www.python.org), 94 bytes ``` lambda a,j="".join:(x:=j(a.count(c)//2*c for c in{*a}))+j(a.count(c)%2*c for c in{*a})+x[::-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY1bCsIwEEX_XUUICElrW_RLAlmJDxhHgi3tTCgpVMSV-FMQ3ZO7MVAUi8MwF84cuLenP4cT03B3dvvogsvWr30NzeEIAhaVlTKvuCSjemMrBTlyR0GhLopVgsJxK1CUdEngqnX6K8z__mm_MSZb7j4tvi2j6ZRERqYuxJVaz74YPAcIPGENkK-BEAhqH08DcSYG0UjGlmEY8w0) A little shorter, but runs in \$ O(n^2) \$ time. [Answer] # [lin](https://github.com/molarmanful/lin), 19 bytes ``` `perm".+ `rev `="`? ``` [Try it here!](https://replit.com/@molarmanful/try-lin) For testing purposes (use `-i` flag if running locally): ``` "nanas" ; `_ `perm".+ `rev `="`? ``` ## Explanation Prettified code: ``` `perm (.+ `rev `= ) `? ``` * ``perm` permutations * `(...) `?` find first... + `.+ `rev `=` palindrome [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 41 bytes ``` f a@([]?[_])=a f(a:b++a:c)=a:f(b++c)++[a] ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NIdFBIzrWPjo@VtM2kStNI9EqSVs70SoZyLNK0wCykzW1taMTY//nJmbmKdgqpCkoJecn5@eVlgCR0n8A "Curry (PAKCS) – Try It Online") This may returns multiple results, with duplicates, but not necessarily all of them. If this is not allowed, you can add the flag `:set +first` to print only the first result: [Try it online!](https://tio.run/##DcdBCoAgEEbhfaeQVsbQBYSoe4jE39REVBJaiy7fJG/zPX5SetsLO2dVMRisD70fQ9OhEgs3EcFxOSe2mBsij6Antmg6I6ZmRMylyEutH8uBNavLy60kW8r3Dw "Curry (PAKCS) – Try It Online"). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` Ṗ'Ṙ= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZYn4bmYPSIsIiIsImFwb3RhdG8iXQ==) Outputs all possibilities with duplicates. Add `;U` to remove them. Takes permutations and only keeps those that are equal after reversal. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 35 bytes ``` X+P:-permutation(P,X),reverse(P,P). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0I7wEq3ILUot7QksSQzP08jQCdCU6cotSy1qDgVyAnQ1PtvpauQkJyfnJ9XWgJECdp@Ogpp@UW5iSUaSnXFSjrRfrFARQA "Prolog (SWI) – Try It Online") Prolog is perfect for this. I/O as a list of char codes (or list of atoms or list of strings, doesn't matter). If there are multiple solutions, each solution is its own choice point (may contain duplicates): [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0I7wEq3ILUot7QksSQzP08jQCdCU6cotSy1qDgVyAnQ1PtvpauQkJiSmJKUnJyg7aejkJZflJtYoqFUVxyTp6QT7RerCRRLzClO1fsPAA "Prolog (SWI) – Try It Online") If there are none, the goal will simply fail. In fact, the first argument doesn't even have to be instanciated. If you run with both non-initialized, the first one will just infinitely produce all possible ways to arrange variables in a list where it is possible to rearrange to a palindrome, and the second one will be it rearranged to a palindrome. You can even do the reverse operation - given a palindromic string for the output, it will give all inputs that will produce that output. [Try it online!](https://tio.run/##DchBCoAgEADAr4inRO0BvcLjQgVtsYVQGbtWt75uHmcuTnvavLyxFLCh8xfxcWfMMZ1NcGAc00MsVBFMWzqvwE44LzNOTq2JD8yN/mQ4tVM9jKYm7kJt@QE "Prolog (SWI) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` ->a{a.permutation.select{_1==_1.reverse}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU9bCsJADPzvKcoKomAX-idCvUgRiWuKFc2WfQhSehJ_iuhhPIK3MdGqJJBkJjMhl5uLm3N_rYp7DFU2f06zJbSgG3THGCDUlrTHA5rQrvOiWOfa4Qmdx64bBI8yUQQEXs3SUbZMefBAKlHGGksxcH6Z9xwiWcM0NJb97ZfjVgDRsdmWgwz-hAIhQyBKuSbxP0gggJhKpwbH906y0ghm1zYx-LQq-QGzA-dX-gjNZLzY25qmuqqdD8NDff-pLw) Inputs and outputs array of chars. Output contains all answers with duplicates, but test suite prints only the first one, so that it doesn't flood the output. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` Select[PalindromeQ]@*Permutations ``` [Try it online!](https://tio.run/##DcoxCoAwDEDRq0hH7yAUvEDFURxCTWmhaSSN548Z/vDhEWhFAm0ZrGx2YsesV4LexiNMeNxxTSj0qRse05K0oUtcirdXEMiKMn0CvOyIg/0 "Wolfram Language (Mathematica) – Try It Online") -1 byte thanks to att [Answer] # [Alice](https://github.com/m-ender/alice), 19 bytes ``` /@P?w$.R/ \IO>K.-!\ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fIcC@XEUvSJ8rxtPfzltPVzHm///EgvySxJJ8AA "Alice – Try It Online") ``` /IP>w..!R-$K?O@ Full program / Switch to ordinal mode IP Read the input and generate all the possible permutations >w $K For each permutation .! Store a copy of the permutation on the tape . R Reverse the permutation - Subtract the reversed permutation from the permutation (leaving "" if it is a palindrome, exiting the loop) ?O@ Print the tape ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes ``` ↕:↔= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpKuoVLsgqWlJWm6FisetU21etQ2xXZJcVJyMVRwwU17pbzEvMRiJS6l5Pzk_LzSEiACchIL8ksSS_JBwkDpFCDMS04F8kCKQRCkJC8xMU8JYg4A) A port of [@Fatalize's Brachylog answer](https://codegolf.stackexchange.com/a/250297/9288). ``` ↕:↔= ↕ Permutation : Duplicate ↔ Reverse = Check equality ``` Returns all solutions with duplicates. You can add the `-1` flag to print only the first solution. [Answer] # JavaScript (ES6), ~~63~~ 62 bytes Expects and returns a string. ``` f=s=>s==(S=s.replace(/(.)(.*)\1/,(_,A,B)=>(s=A,B)))?s:s+f(S)+s ``` [Try it online!](https://tio.run/##ZU9BTgMxDLzvK6w9NA5dUnFtla1A4gU9lgpZaRZabZNVHHpB/ACJC0f4B@/pB3jC4tWWC9iW5fHYHnlPR2KXdl2@DHHr@76xbGu2FleWTfJdS87jDI1Gc6HvrmYV3lfX1Y22NbIdCq2XPOdpgys95X6xLgDKQIG4rIbSRRfDU5YYMXUxU44jOFAQgeBkvO0kHUjsvCdwKx6cHxvDzcHPZwJRKItNYZqYbsk9IoOt4Vm41mdIYKFB1gvBos@x9aaND5gqWBtj0kZeO/rEHrXZx11ApTRYK3uTye8Ex5T/0APD/5klqO@vt9PHu2QFc1Cnz1cl2i@6/wE "JavaScript (Node.js) – Try It Online") ### Commented ``` f = // f is a recursive function s => // taking the input string s s == ( // test whether s is unchanged S = s.replace( // when turned into the reduced string S // obtained by looking in s for: /(.)(.*)\1/, // a character A, followed by some string B // (which may be empty), followed by A (_, A, B) => // if found, (s = A, B) // copy A into s and replace the match with B ) // (i.e. both instances of A are removed) ) ? // if S is equal to s: s // we're left with either an empty string or a // single character; either way, this ends up // in the middle of the output : // else: s + f(S) + s // append s, followed by the result of a // recursive call with S, followed by s again ``` [Answer] # [Perl 5](https://www.perl.org/) `-F` , 57 bytes ``` $_=join"",sort@F;s/(.)\1/!push@r,$1/ge;say@r,$_,reverse@r ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYrPzNPSUmnOL@oxMHNulhfQ08zxlBfsaC0OMOhSEfFUD891bo4sRLEjtcpSi1LLSpOdSj6/z8pMQ8Ik/7lF5Rk5ucV/9d1@6/ra6pnYGgAAA "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 52 bytes ``` import Data.List find(\x->x==reverse x).permutations ``` [Try it online!](https://tio.run/##HYxNDsIgEIX3nmLCqk2UG@DKpZ5Au5hQjMQyM4Gp4fYIzfc2L@/ng@Ubtq3FJJwVbqho77HoKWEkcJBQHjBJjqRWZngaQsJizmA8e6Zdu4ZDYUXlI@iNtUM@DDsGg6NFiGSWJu4daZ1e9XKtzuXwC7kEqLOVkNPejyJTae0P "Haskell – Try It Online") Pretty new to Haskell so I'm very open to suggestions on how this could be improved, because I have a feeling it can be a lot - especially concerning that lambda, but I couldn't find how to make it pointfree. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 19 bytes ``` {⌊/⍵=⌽⍵:⍵⋄∇⍵[?⍨≢⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/IDEnMy@lKD839VHbhOpHPV36j3q32j7q2QukrID4UXfLo452ICPa/lHvikedi4DM2Nr///8DAA "APL (Dyalog Classic) – Try It Online") **Usage:** ``` palindrome←{⌊/⍵=⌽⍵:⍵⋄∇⍵[?⍨≢⍵]} palindrome 'baba' baab palindrome 'daabbcc' cbadabc ``` [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics`, ~~41~~ 38 bytes ``` [ [ dup reverse = ] find-permutation ] ``` [Try it online!](https://tio.run/##DcoxDsIwDAXQvaf46t4eAMRcsbAgpqpDSF0RkTjGcZA4fcj83uG8ZW2P@/W2nPAmZYoo9KnEngqSs9fsc3oGdv0FXyBKZj/RwIbzMIxOsnUb24oVexUofUkL4YINR@B9EtJU@wmZsTXvYsTc/g "Factor – Try It Online") [Answer] # [J-uby](https://github.com/cyoce/J-uby), 33 bytes Port of [Kirill L.’s Ruby answer](https://codegolf.stackexchange.com/a/250300/11261). ``` :permutation|:select+:==%:reverse ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU9LCsJADN33FHWKoqgFdzJQl15CpMQYacVmynwEUU_ipgjexgt4G2eqVRJI8t7LC7k99rnbnJr7Mns4u5vOXz1Zk66cBVsqvkhDB0I7llnWl5qOpA19hc9VJBgYjJjEyXQR-8EAi0igQsXO-uyYdraOFXoaauXNVcf5NgAiSgR6t60PRvptBog8BBgU4V6I_0mGAASubcXXtBVF65QAi3PtrImXq3yWYgHarNMK6uFA7lXJo3RXamOvn5-a5lPf) [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs all possibilities. Replace `f` with `æ` to output just 1. ``` á fêQ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4SBm6lE&input=ImFkYWRiY2Mi) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 35 bytes ``` O`. |""L^`((.)\2)*.? $ $^$` (.). $1 ``` [Try it online!](https://tio.run/##FUtBCoQwELvnGdKFuoeCfmCPexH8wCIN1YOg01Lrzb93p8kkkAzJW9mFQ33Zr6@zd3i6blq8ta7/jf3bfWBgFuOhhYMZahUKL4QYotxFD0yxsESclHRQgv6PpHZSgRZXpYQNbdoIFQUrc@Yf "Retina – Try It Online") Link includes test cases. Explanation: Based on @Jonah's J solution. ``` O`. ``` Sort the characters into order. ``` |""L^`((.)\2)*.? ``` If there's an odd character, split the string after that point and exchange (`^`) and join (`|""`) the two halves. (There's also an empty string in the results but obviously it doesn't have any effect.) ``` $ $^$` ``` Append the reverse of the string. ``` (.). $1 ``` Drop every other character. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ≔Φθ﹪№…θκι²ηηΦΦθ﹪№θ鲬κ⮌η ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DLTOnJLVIo1BHwTc/pTQnX8M5vzSvRMO5Mjkn1TkjvwAkk62po5AJxEaaQCJD05oroCgTqAbBghqCw6xCJN1@@SUa2ZqacJ1BqWWpRcWpQLM0rf//T0ksKkr8r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Φθ﹪№…θκι²ηη ``` Using my code from [Generate an arbitrary half of a string](https://codegolf.stackexchange.com/q/250213), extract half (rounded down) of the characters from the string, but also save it in a variable. ``` ΦΦθ﹪№θ鲬κ ``` If there was a character that appeared an odd number of times then output it. (Now if only `Maximum("")` returned the empty string...) ``` ⮌η ``` Output the reverse of the half string. [Answer] # x86-64 machine code, 31 bytes ``` 31 C9 FF CA AC 0F BB C1 73 FA 88 04 17 AA 83 EA 02 77 F1 75 09 0F BC C1 75 01 AC 0C 60 AA C3 ``` [Try it online!](https://tio.run/##VZPBjtowEIbPmaeYpkJKlrBiacthKb3suZeeKrEcjD0h3jp2ZBsainj10jEBVpUSK575/2/GHkV23WQr5fksQosF/sgLeNwatxEGa6ifIeudR5J9lRbIFEkk1YOnjkTktHEqbCDbRHlVCVa9WYmDArLW7XHllR571a8rFAayEF3yhN0msSqcsUPcDW/2D5JVzAx1wl0rp3D4pbtbyfTN9bk7YSqc9vPpDcxmTniKUOZYLoD6SN5i/pLjce@0wrqQjfD44CnsTKxQOhsiDrFQobYRgyFbLk4AH7WVZqcIv4aotHtsvv0X8tpuUwySqRXaFiUcIbuwtO12cTX7MudjD6UumwVkvxttCIsgha2LfBTyahCXuFziUwkZI7JENLhELsLNFIOAzVld3Bq/xCo0l/C1hFmzZ5oCHTcXE3/yNA@j8Grzu2PQJtsJ7rpX@13IRlviC1H0nKd0aqJPwAoPvFUOjzc5jqazn4w8LItiZ4PeWlKXS3wo63LVj8drvkC8HvWAHxjSv3xK0DuhGGncHCKF8tJcz8nT@RyIAiinHETh@QHRdcIYiCTaVkQCnpfUQfPUIDoHztUQml1oYK/3WkGgyAPnHFfh8bzLwYgN8WsIOk9Sd1oOMIbaBPbEFtp6kXx/ZW3ENpwn7fwzL/x/LFPW/AM "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of the input, as an array of single-byte characters, in RSI and its length in RDX, and takes in RDI an address at which to place the result, as a non-overlapping array of single-byte characters of the same length. Part of this is similar to [my answer to "Generate an arbitrary half of a string"](https://codegolf.stackexchange.com/a/250369/104752). In assembly: ``` f: xor ecx, ecx # Set ECX to 0. dec edx # Subtract 1 from the length in EDX. repeat: lodsb # Load a byte from the string into AL, advancing the pointer. btc ecx, eax # Invert the bit in ECX indexed by the low 5 bits of that byte. # Set CF to the previous value of that bit. jnc repeat # Jump back if CF is 0. mov [rdi+rdx], al # Place the byte at a position that starts from the end of # the output string and will move backwards. stosb # Add it to the start of the output, advancing the pointer. sub edx, 2 # Subtract 2 from EDX. (= # of unfilled places - 1) ja repeat # Jump back if it is still positive. jnz end # Jump if it is -1 (all places filled: happens for even length). bsf eax, ecx # Set EAX to the index of the 1 bit in ECX. # (If the input is valid, there is at most one 1 bit here.) jnz skip # Jump if there was a 1 bit in ECX. lodsb # (Otherwise, the final instance of the odd-count character # is at the end of the string and has not yet been read.) # Load a byte from the string into AL, advancing the pointer. skip: or al, 0x60 # Set bits 5 and 6 in AL, making the correct lowercase letter. stosb # Add it to the output (in the centre), advancing the pointer. end: ret # Return. ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 55 bytes ``` g=a=>a+''==a.reverse()?a:g(a.sort(_=>Math.random()<.5)) ``` [Try it online!](https://tio.run/##bYzBCsIwEETvfkYvTRD35kVM/QK/QESWNI3VZDdkY8Gvr3u3M8Mc5sG8cEHxdS7tIGUeQ81M7/Bdo9OgG3Df984h1LCEKsHYC56iQRCuzTzccMX2hIo0cjb2DEdr18mJG6K5AYDcLbx4JtP3dueZhFOAxNFMpiMklM7@7Z51@DTNBsTCDRtvkIxUEpLX11S0Mqq27pWNavJB6foD "JavaScript (SpiderMonkey) – Try It Online") Shuffle until meet requirement [Answer] # [Scala](http://www.scala-lang.org/), 58 bytes Golfed version. [Try it online!](https://tio.run/##TU9Na8MwDL3nV4icEhj@AQEHdt/HIfQ0RtEctfMWy57tdhmjvz2T0w5iWWBJT@89J4MTLv7tg0yGR7QMv1V1xglCN@Ro@aj755Ct55dr@Qp62avsB/pSgaI7ZSzTpByGZq/c5xXWqoPlsZl1P2s9q0hnionaBWCkAzjRaTAeUwf3MeLPP3fbwY5tBi0mQE7x8e3jmKTzYFNuakbGVN9BbbzxfMpyS4XBiw@/DgQxSrChUpaFEiuKEbluV@qVdjUdxKuPhOb9pgpgMBEM3lETcJJ/RHm2oHsIYjNPvG1vV5480xZWl8ZN8FKVvFTLHw) ``` _.toSeq.permutations.map(_.mkString).find(x=>x==x.reverse) ``` Ungolfed version. [Try it online!](https://tio.run/##dVBNS8QwEL33Vww9tSABrwsVvPsFiycRGdPZbjSdlCS7Vpb97XWS7UoVJclhXt68eW@CRovT5F7fSEe4RcNwKAqAljYwkO93EaNxHKqwgnX0hrt6BTcmxKdT9QwNCB3AbKAKyhJ3cQtNA5d1plWhzt9kA0FQ0SVQLZVVj0P1ovr3WX7mfJtAa7j1rqeH/@zcDwn7bein@1ptRKYaobmCMfkblac9@UD1eVIv4Sv0nUhfe4@fZ0GZ8Mgmiu4hC@/RwofzbRAkRywZGUN5AaV22vEuyk0VDk7mu/whjFYOa0plakgnsxiRy9OWsmxeyN@xJYXzhHo7WwHQKHtdC23RUaeQg3iPlpfwsuXOMS1pZQJmF8civWMxTV8) ``` object Main { def permutations(s: String): List[String] = if (s.length == 1) List(s) else s.toList.permutations.map(_.mkString).toList def palindromePermutations(s: String): Option[String] = permutations(s).find(x => x == x.reverse) def main(args: Array[String]): Unit = { val words = List("nanas", "coconutnut", "apotato", "canadadance", "nananana", "anaan") words.map(palindromePermutations).foreach { case Some(palindrome) => println(palindrome) case None => println("None") } } } ``` ]
[Question] [ Although it's done a few times as sub-challenge of a larger challenge, and we also have [a challenge to remove the borders of a square matrix](https://codegolf.stackexchange.com/questions/154686/perfect-squares-without-borders), I couldn't find a challenge to output the borders of a given matrix, so here it is. ## Challenge: Given a rectangular-shaped matrix containing integers as input, output its borders. ## Challenge rules: * The input is guaranteed to be a rectangular-shaped matrix (or empty) * The input can contain negative and duplicated integers * The output format and type is flexible and can be in any order (e.g. `[[1,2,3],[4,5,6],[7,8,9]]` may result in `[1,2,3,4,6,7,8,9]`; or `[[1,2,3],[6,9],[8,7],[4]]`; or `9\n8\n7\n6\n4\n3\n2\n1\n`; etc.). As long as it's clear that just the border of the input-matrix is output, *almost* every output-format is allowed. (If you're unsure whether an output format is allowed, feel free to ask in the comments.) ## General Rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test Cases: | Input | Output | Visualized | | --- | --- | --- | | ``` [[1,2,3], [4,5,6], [7,8,9]] ``` | `[1,2,3,4,6,7,8,9]` | [enter image description here](https://i.stack.imgur.com/LjZP2.png) | | `[[]]` | `[]` | N/A | | `[[0]]` | `[0]` | [enter image description here](https://i.stack.imgur.com/dVfLm.png) | | ``` [[ 9, 2,-5, 3], [18, 3, 8, 0], [ 2, 7,21,-3], [ 9,-5,10,99]] ``` | `[9,2,-5,3,18,0,2,-3,9,-5,10,99]` | [enter image description here](https://i.stack.imgur.com/k4K7g.png) | | `[[1,2,3]]` | `[1,2,3]` | [enter image description here](https://i.stack.imgur.com/0PP16.png) | | ``` [[9], [8], [8], [9]] ``` | `[9,8,8,9]` | [enter image description here](https://i.stack.imgur.com/fDjac.png) | | ``` [[ 10, 20, 30, 40, 50, 60], [ 70, 80, 90,-90,-80,-70], [-60,-50,-40,-30,-20,-10]] ``` | ``` [10,20,30,40,50,60,70,-70,-60,-50,-40,-30,-20,-10] ``` | [enter image description here](https://i.stack.imgur.com/JkiUK.png) | | ``` [[ 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]] ``` | ``` [1,2,3,4,5,6,7,12,13,18,19,24,25,30,31,36,37,42,43,48,49,54,55,56,57,58,59,60] ``` | [enter image description here](https://i.stack.imgur.com/P4Sym.png) | | ``` [[-11, 18, 3,-40,123], [ 18,-33, 9,765,100]] ``` | `[-11,18,3,-40,123,18,-33,9,765,100]` | [enter image description here](https://i.stack.imgur.com/cHcQ8.png) | | ``` [[14, 3], [ 3,14], [14, 3], [ 3,14], [14, 3]] ``` | `[14,3,3,14,14,3,3,14,14,3]` | [enter image description here](https://i.stack.imgur.com/TGhXM.png) | [Answer] # Python 3, 38 bytes ``` def f(x): for c in x[1:-1]:c[1:-1]=[] ``` [Outputs by modifying arguments](https://codegolf.meta.stackexchange.com/a/4942/70761). The code also works on Python 2. Explanation: deletes the center part of each center row by modifying the original input. [Attempt This Online!](https://ato.pxeger.com/run?1=dVPLbttADDz05q_gKbCAWcDc9xrolwhC0aZ264sSKAqQfEsvuST_1H5NZ7VOgVYqDGrXJIfkDKUfb_fP8_e78eXl9XE-m_zz5uvpLOf9U3fcyfluklu5jPLU69HocLxt58d-aNm_Pnyp6fPpYd5fFgSPnUyn-XEa5bK7ny7jvF_Cfa-wcAN6j4DIMyGjDEPX_Z12AH9rtxJhaW4TUYOwG6jaE34J80SoFdAmWCWvPOtOiySfqiTT5_HbaR-74V9X6FYwKRALEyDkv5NeM28QPg_LfwYlwSpMizOfyXpA2dCnybhylwHS5z-PDaCwoFiao3laoMXrBIn3TCsHmGq8m9RiJvLOXEOMIdawhtGNFYlWmpWZZ3HWvpZemJbKRxVqmwQO6qFkGaEJmpu3gMUphOU2HaxfvDbARlgqlGELXBvLKRyVcHAeLsC1bi7BZbgCDusVvnXz3LmHD_ARPsG3br6AtIIiWASH0LqFgBAREkJGKIgbRA15SF0iuVZV1F73Rp_hREK2KdYNbr3I_v01kKpB4_1fH-HtU3v_QH8D) (additional test cases taken from [loopy walt's answer](https://codegolf.stackexchange.com/a/260961)) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~10~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I/O as a 2D array of integers, with output sorted anti-clockwise starting in the bottom right corner. ``` 4Æ=z)oÃf ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NMY9eilvw2Y&input=W1sgMSwgMiwgMywgNCwgNSwgNl0sCiBbIDcsIDgsIDksMTAsMTEsMTJdLAogWzEzLDE0LDE1LDE2LDE3LDE4XSwKIFsxOSwyMCwyMSwyMiwyMywyNF0sCiBbMjUsMjYsMjcsMjgsMjksMzBdLAogWzMxLDMyLDMzLDM0LDM1LDM2XSwKIFszNywzOCwzOSw0MCw0MSw0Ml0sCiBbNDMsNDQsNDUsNDYsNDcsNDhdLAogWzQ5LDUwLDUxLDUyLDUzLDU0XSwKIFs1NSw1Niw1Nyw1OCw1OSw2MF1dCi1R) ``` 4Æ=z)oÃf :Implicit input of 2D array U 4Æ :Map the range [0,4) = : Reassign to U z : Rotate U 90° clockwise ) : End reassignment o : Pop last sub-array, mutating the array à :End map f :Filter, removing null elements ``` [Answer] # [jq](https://stedolan.github.io/jq/), ~~57~~ ~~46~~ 20 bytes ``` del(.[1:-1][][1:-1]) ``` [Online demo](https://jqplay.org/s/Y-niTUhPziP) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~47~~ 45 bytes -2 bytes thanks to @alephalpha [Try it online!](https://tio.run/##bZBNa8MwDIbv@RWGQOk6h9rOBwshpdfuVEZuRgNvdVcf4hRHN5P@9SzL2FZ3BV1e9DxCUqvwpFuF5l2Nb507aFePu6NsnOSvMWwE9bGUWHtOEz4A0CmJqkoERYCBxrAYUffISU32yqFB01n5ouyHliVQkkIVfU@VMwbr9d4Zi1H0FcVkeT8MASNCJp0ZdgOlIZRNUOOU7c9dr7fel5Q8zVXeeFno5fXf0kvOVj@LP1yeO2Mvy4QzRh7JdYeSIrwpD0cWdz5RMPinFb/a@Ak) ``` If[Tr[1^#]>2,{#[[t={1,-1}]],#[[2;;-2,t]]},#]& ``` **Explanation** `Tr[1^#]` returns the length of the shortest dimension by computing the `Trace` of a matrix of 1's with the same dimensions as the input, i.e., `Min@Dimensions@#`. If we have an edge case with a dimension of 0, 1, or 2, we return the input in its original form. If `Tr[1^#]>2` is true, then we use Mathematica's `[[a;;b, c;;d]]` syntax to access different parts of the matrix: `#[[{1,-1}]]` returns the first and last rows, `#[[2;;-2,{1,-1}]]` returns the first and last columns while excluding the "corners." We return a ragged array as the output: if the input is `m`x`n` with `m`,`n>2`, the output will be of the format `{(2 x n array), ((m-2) x 2 array)}` [Answer] # Excel, 77 bytes ``` =TOCOL(B2#/(MAP(B2#,LAMBDA(b,SUM(SUBTOTAL(2,OFFSET(b,{-1;1},{-1,1})))))<4),2) ``` Input is spilled range deliberately set to have its top-leftmost cell as `B2`, rather than the customary `A1`, such that the four cells above, below, to the right and to the left of that cell exist. [Answer] # [Rust](https://www.rust-lang.org), 81 bytes ``` |a,b,c|(0..).zip(a).filter(move|(d,_)|d%b<1||d%b>b-2||d/b<1||d/b>c-2).map(|a|a.1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVBBasMwELz7FZtAQYK1YjsNjVVXvfTaQy-9lGJkWQaB7RhbySFRXlIKPrSPym8qx4V2WWZ2h2FY9uOr3w92vDxVLTTStITCKai1hYpXLXnVKjODOWqB-4lmpKEYbMm5sbrn_Fl2WY65gAf43tsq3F5enMQClSMRY5QdTUckZZWpvZ00u4N2pMScuvKmyGI3kSjCxA-reV8VQoUJZY3siJNOspj-Bn_eB0HXm9bW7YIsT_zxvESoSAAAB60Wb5AiJBhuENYIG5z0a8Xbq-IxQrj7073Zr0mM4Rrj5J-eTiFxhGnqO32fwuCWMrWra60s55l_jMf5NYJQ6g87z0eO48w_) Takes input as a flattened matrix with size given as `b` and `c` [Answer] # JavaScript (ES6), 54 bytes ``` m=>m.map((r,y)=>r.filter((_,x)=>x*y/r[x+1]?!m[y+1]:1)) ``` [Try it online!](https://tio.run/##fZDBbsIwDIbvPEV3a7c/rI7jpJkEe5CqmtAGExOlqKAJnp65NBw2wQ5OHMf2Z/9fi@/F/r1f7w5m230sz6vZuZ3N22m72OV5j1Mxm/fT1XpzWPZ5/oajvo@Pp@e@Pj5R8/rQ1ie9X6gozu/ddt9tltNN95mv8nqSZTXBghsMroPAj25AhdhMmqKY/Kmpm1vB8lZ0aJRFZBZGkCUIVeoi07McA/qdBViCSRlaovlUIt6ZYBz5DjCOTapf1@1GF5hyMqvGak5N1Px1tKCPSi2WMIOpb0L6NF4fmm20ymi10S6Gyn9IgxLD7k4pCrkyLmLEYWEikE0yMciBVAcPCqC0CEUoRsWyFpZh3Ri2AuthVcYKNoLTiExglYrBDizghOQArsAROrkjuIR0DOfgBM7DBbiEdBG6pRDEQhiSkCIQDwmQChLhx8XPPw "JavaScript (Node.js) – Try It Online") Or **58 bytes** (ES10) if we want to flatten the output: ``` m=>m.flatMap((r,y)=>r.filter((_,x)=>x*y/r[x+1]?!m[y+1]:1)) ``` [Try it online!](https://tio.run/##fZDdbsIwDIXveYrurt1OWB3np5kEe4I9QVVNFaMTU6GooAmevnNpuNgEu3DiOLY/@3zV3/Vh1W/2R7XrPtZDsxi2i@V23rT18a3ep2mPc7ZY9vNm0x7XfZq@4yTv0@P5uS9PT1S9PmzLs9wvlGXDqtsdunY9b7vPtEnLWZKUBA2uMLoGFm5yPQqEalZl2exPTVndCua3omOjJCDRUBZJhFAhLhI58ykg34mHJqiYISWSTznCnQmmke8Aw9Sk@HXdbnSBCSfRYixmxKyYu47m5VGIhRxqNPGVj5/KyUOylVQpqVbSRVH@D2lUYtzdCEUgV8ZFjDAuTATSUSYGGZDo4EAeFBehAMGIWFpDM7SZwtpCO2iRsYAO4DgiE1ikYrABW3BEsgcX4ACZ3BBMRBqGMTAWxsF4mIg0AbKlJVgNy7ARaS2sg/WwBWyAmxYffgA "JavaScript (Node.js) – Try It Online") ### Commented ``` m => // m[] = input matrix m.map((r, y) => // for each row r[] in m[] at index y: r.filter((_, x) => // for each value in r[] at index x: x * y // if neither x nor y is equal to 0 and there's / r[x + 1] ? // at least one more column after this one: !m[y + 1] // keep the value only if this is the last row : // else: 1 // keep the value ) // end of filter() ) // end of map() ``` [Answer] # [J](http://jsoftware.com/), 24 20 bytes ``` #~&,_>_(<,~<<0 _1)}] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/levUdOLt4jVsdOpsbAwU4g01a2P/a3KlJmfkK6QpZOqZKJiCOerqMDEdPUt0EStDBSMFY0x1ChZAaPkfAA "J – Try It Online") * `_(<,~<<0 _1)}]` Convert all interior points to infinity, by specifying "not first and last (0 and -1)" elements of first axis, and "not first and last" elements of second axis. * `_>` Where is that matrix less than infinity? Returns a 1-0 mask selecting the border * `#~&,` Flatten and filter the input with that mask # diagonal rotation, 24 bytes ``` #~&,_=[:+/,.~@1 _1|.!._] ``` [Try it online!](https://tio.run/##ZYzNCoJQEIX3PsWkol4cR28/kNMVLgWtokXbEBehZJsewJ9Xt9sFiYphBs75zpzH5FLYQMEQAkIGbDYhOFxOx8kbA6yKK8cp0qglVLKnBVXlJJzznuCNFWs/C2rS3LvS97gl7VvYGRglZI7CUanMPIugE/oTIIN240wwwI4t8ONUR0WKskhLIeOvUjIhNM1yYD1QZLVwpVPf7k9ooKU1bKwIw9lDyn8dlrCE1X8Otmby6QU "J – Try It Online") Looks like this may be related to Adam's APL answer, but was discovered independently. See alternate below for a different approach. 1. Diagonally rotate the matrix up-left using infinity as fill. 2. Same thing down-right 3. Add the two together (now the borders will all have the value infinity) 4. Create a border-selecting 1-0 mask with 1 wherever infinity is 5. Use that mask to filter the input, flattening both the mask and the input # original, 24 bytes ``` #~&,0=<:@$*/@:|"1$#:i.@$ ``` [Try it online!](https://tio.run/##ZczNCsIwDAfw@54ibGVbXZe2foCrLRQFT@LBu3iQDefFB5jbq9euMPwiJJD8/uTuYswaMAoyYCBA@S4RdqfD3iVDyoTRypIZt@oZS5KoFi1xNDpuEUYeUaQ1fnLAzmNeoh@aDVoLuEiadtS@A@hpM0zCUtapAKTgNjecScPPVBZfT9GHmP8se2V7zMNOYxnV19sDGmhxCauwZNl0Y1j9XpSEOSz@c7D2VbkX "J – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 62 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.75 bytes ``` 4(∩ḣṘ)_W' ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwiNCjiiKnhuKPhuZgpX1cnIiwiIiwiW1s5XSwgWzhdLCBbOF0sIFs5XV0iXQ==) Port of pyth messed up by the fact that `ḣ` and `ṫ` return `0` on an empty list instead of erroring (which has its use, but is annoying here) ## Explained ``` 4(∩ḣṘ)_W' 4( ) # 4 times ∩ # transpose top of stack ḣ # separate the head from the rest Ṙ # and reverse _W # pop the remaining list and wrap the stack in a list ' # remove 0s and empty lists ``` [Answer] # [R](https://www.r-project.org), ~~44~~ 34 bytes ``` \(m)m[rev(d<-row(m)<2|col(m)<2)|d] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZBLCsIwEIZx21MEVwnMQNJWbYquvYA7dSF9iGAVQn0svImbKngoPY1_LeiilfBlHv8_Gcj15qp7PnkcypyjZ38hC1XMXXaU6Zjd_oRy7F-S_faTqEu6bJyv3lQWk2JVus1ZmthSQDRTysvh837KZldm68xJ1ZZ0u5VIS8InHpAIyBMmqqPArVFBECPyDXGtCVvbjCZrFYWdu00ckOleEuFgrlvGo8IHAQjBAAzBCETAauIa5IweQ2N4GF7GDGOWjVZ_fsTE8GPFV2v-s6qa-AY) Footer stolen from [pajonk's answer](https://codegolf.stackexchange.com/a/260945/64121), and -10 thanks to them! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *With the lax output requirements I was expecting to find terser in Jelly!* ``` ŒDị@Ḋ¡€. ``` A monadic Link that accepts the rectangular matrix and yields a list of lists of border values. **[Try it online!](https://tio.run/##y0rNyan8///oJJeHu7sdHu7oOrTwUdMavf@H249Oerhzxv//0dEKhgY6CkZAbAzEJkBsCsRmBrE6XArRCuZAtgUQWxro6IIwkK1rDpHTNQOygWp1gXp0gXp1gWboGoLkYgE "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##TU87TsQwEO33FC5okJ5RxjNjxwWIAolDRClpVnsBuoUGCbqtKKCgp16BkCiC9iDJRcIkzkpbPGccv3mf9d1mcz@Oh91N//Ny3X89dx/D4@fFeIu/p8Ou/349Ww/bt25/eeWG7fv5enj47fbdfhybVdMQXIDjFivXCJzCxXlOcDVcbu3SNOWsysflacXrcYuMxzO7mu@TXkIg@PJufCNThbyoEQK4jHlm1CfnwnHGd8HABjGoIS4GyebakCv4CTb7VN58tNm43na87XrT8HRMvpQ1xZOmbqk6RSQChdKKQQKy4BGUQCUdZZigdQsBgRFk/hsUISJY6Rohg0sUJrAVZbCAFVzcOIFrcIYFFIIUN2GIQBQSIQlS3CTDqihBA5ShxU0VGqEJWkMz4lyu/Qc "Jelly – Try It Online"). ### How? ``` ŒDị@Ḋ¡€. - Link: list of lists, M ŒD - all NW-SE diagonals of M . - set the right argument to 0.5 € - for each diagonal: ¡ - repeat... Ḋ - ...number of times: dequeue (i.e. once if diagonal length > 1) @ - ...action: with swapped arguments - f(0.5, diagonal) ị - index into* * fractional indices give the two neighbours in the case of 0.5 that's 0 (the last) and 1 (the first) ``` [Answer] # [SAS IML](https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/imlug/titlepage.htm), 88 ~~70~~ Input is a rectangular matrix `M` e.g., ``` M1={ 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 }; ``` [EDIT:] According to comments below I updated the answer. The code (an IML module): ``` start d(M);if 2<nrow(M)><ncol(M) then M[2:nrow(M)-1,2:ncol(M)-1]=.;M=M[loc(M>.)];finish; ``` Human readable: ``` start d(M); if 2 < nrow(M)><ncol(M) then M[ 2:nrow(M)-1, 2:ncol(M)-1 ] = .; M = M[ loc(M > .) ]; finish; ``` To execute the IML module `d` run the following: ``` call d(M); ``` The process: 1. For a Matrix M with at least 3 rows and columns (`2 < nrow(M)><ncol(M)`, where `nrow(M)` is number of rows, `ncol(M)` is number of columns, and `><` is operator of minimum of two numbers) replace "everytnig inside" (`2:nrow(M)-1, 2:ncol(M)-1`) with missing data (`.`), 2. select those elements of `M` where value is not missing. To print out result, i.e. elements extracted from `M`, run the following line: ``` if type(M)="U" then print "M is Empty"; else print M; ``` --- [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŒDµżṪḢ) ``` [Try it online!](https://tio.run/##TU87TsQwFOz3FG5XGkt5PzvuuQSKtqRBewFOQL8VNSU9EkhUoD3IniRM7CBRvJdx3ryZeY8P5/PTul4vd9/v16/b59vt4/W4/jxfL7fPl@P9ui6HZREo7IRDWhyB0lHFjHYiXJbRp/FJDUmRA2lsyEyExD71N4epQgV5zMknWSa0XW2Yddg6Y/7Xd04iPynLWM4KVtkNKvHMahPyVsS5jlkuxORm7mTuZmpk@UsuW/ItrFOQertcD9@2iCIQHVcZxCEMXiAVMtJJAwV5myrUoN7/akALlEfP0AYbUUxgPNRgDgvYcLMKm2ENDOgCH25ucIcHvMArfLh5A08JQSjCEMMtAlEQFTEjGko/7vQL "Jelly – Try It Online") No shot I could have thought of using diagonals if @Jonathan Allan hadn't first, so go upvote [his solution](https://codegolf.stackexchange.com/a/261008/85334)! (Also, two bonus 8-byters: `ŒDµṙ-ḣ2)`, `ŒDµḊṖœ^)`) ``` ŒDµ ) For each diagonal of the input: Ṫ take and remove the last element, ż zip with the remaining elements, Ḣ and take the first of those pairs. ``` My original solutions, to laugh at: # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ḊṖ$⁺€Fœ^F ``` [Try it online!](https://tio.run/##TU8xTsQwEOzvFS5okMZS1rtrxx@4P6AodDToPkAJDRIlSIhH8ACOFt1D7j4SJnaQKHYzzs7OzN7fHQ4Py3L@ejkf368uj9@Xp8/96e12v/w8n17Px4/rm2WZdtMkSNAZuzAZHLmhghF1Jpym3of@CRUhITpC35CRCIF9aG8OQ0ESxD4nn2QZUDe1btZgbYzxX984gfyQWMoylrPyZlCIR1YdENcijqXPYiYmN3IncjdSI8pfclmTr2GNgtTb5Fr4ukYUgaR@lUIMwuAZUiA9nVRQkLelhKRI1v4mR8pIPHpEqtAeRQXKQxVqUId2Ny3QEVrBgCaw7mYKM5jDMqzAuptV8BQXeIIrvLu5wzO8wEd4RW7Hzb8 "Jelly – Try It Online") ``` ḊṖ Remove the first and last rows $⁺€ and columns. F Flatten the result, F flatten the input, œ^ symmetric multiset difference. ``` Can't decide if this feels worse...: # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ḊUZƊ3СZḢ ``` [Try it online!](https://tio.run/##TU87TkNBDOxzim2RZqXntb2fg1CQp5Q0KBfgBEipEBUtnCJpieAeOclj3u5DorDf7PN4Zvz0eDw@L8vtfLrf/5z0@vr1sb@dP5fry/fb7fJ@97As826eBQl6wC7MBkfuqKCiHQjnefRpfEJDSIiOMDakEiGwT/3NYShIgjjm5JMsE9qmNsw6bJ1R//WNE8gPiaUsYzkrbwaFuLLahLgWcSxjFjMxuZE7kbuRGlH@ksuafA1rFKTeJtfDtzWiCCSNqxRiEAbPkAIZ6aSBgrwtJSRFsv43OVJG4tEVqUFHFBUoD1WoQR063LRAK7SBAU1gw80UZjCHZViBDTdr4Cku8ARX@HBzh2d4gVd4Q@7HHX4B "Jelly – Try It Online") ``` Ɗ3С Repeat [0, 1, 2, 3] times: Ḋ Remove the first row, U reverse each row, Z transpose. Z Transpose the results Ḣ and return the first row of that. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` V4.)=_C ``` [Try it online!](https://tio.run/##K6gsyfj/P8xET9M23vn//@hoQx0jHeNYnWgTHVMdMyBtrmOhYxkbCwA "Pyth – Try It Online") Prints each side as lists separated by newlines. Goes clockwise starting with the left side. ### Explanation ``` V4.)=_CQ # implicitly add Q # implicitly assign Q = eval(input()) V4 # loop 4 times = Q # assign Q to CQ # Q transposed _ # and reversed .) # pop the last element of Q and print it ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` f=lambda a:a[:1]+a[1:][-1:]+map(f,a[1:-(a>[f])]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWNw3SbHMSc5NSEhUSrRKjrQxjtROjDa1io3WBhHZuYoFGmg5IQFcj0S46LVYzVhOq72BBUWZeiUaaRnS0oY6RjnGsTrSJjqmOGZA217HQsYyN1dTkQqgx0AFCNDFDoFojIDbGVAuS0TFCVw-yR8cELAekdUxBenUgtqKqROUic0y1os20osEugXgEFhAA) Takes a LOL and returns a ragged LOL. Output for non degenerate inputs is [top row,bottom row,[1st,last]of 2nd row,[1st,last]of 3rd row,... [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~23~~ ~~22~~ 18 bytes Thanks to ovs for −4 bytes. Anonymous prefix lambda. ``` {⍵[⍸∨∘⌽∘⊖⍨1∊¨⍳⍴⍵]} ``` [Try it online!](https://tio.run/##RU@9SgNBEO59iu2i8C3c7OzPbW2jFgrG7rgiILEJaCtiJYQQvKBFxEdIIVioYGOTR9kXOWc3JhYzOzs/38/oZqIvb0eT66u@v0vdV5O67zRbpdlrevzJef6SuhWl2Xy9St1H6j5lqb3vx2n6tJ@6RZo/pO5N2ut3TtPntFgOzw8lXxwdDw9yQyAWy5Ph2Wk/HjQNwYBbqMbCwecioEZs28FeHm/faluoCGWgHVS5oloKKMlV/spIBRiCLlNZlk2qEHeAG76/T8xL9S7tlpScKCPBElbCSfgNQ5CylogVdA6pdSgj7aWUTS0XWi61IGj6V05ZeVZrBVDwNnBFfMwiiUCmmGKQBYlyDwqgIo4iBE@sGQPDMDY3jYPxMGK5hongooMJLCYZbMEOXIg4gGtwhIizBFuILMNaWAfrYQNsIbIRYsIRnIFjuELkHJyHC3A1XITPrn4B "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; argument is `⍵`:  `⍵[`…`]` select from the argument:   `⍸` where indicated by   `∨∘⌽∘⊖⍨` the following mask when ORed with its mirrored flipped version…   `1∊¨` true only where 1 is a member of   `⍳` the indices for an array that has the shape   `⍴⍵` the shape of the argument [Answer] # [Haskell](https://www.haskell.org/), 48 bytes ``` b=zipWith($)[head,map last,last,map head].repeat ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8m2KrMgPLMkQ0NFMzojNTFFJzexQCEnsbhEB0yAeCDhWL2i1ILUxJL/uYmZebYFRZl5JSpJ0dGGOkY6xrE60SY6pjpmQNpcx0LHMjb2PwA "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 74 bytes ``` import Data.List;(o:t)#(r:s)=r++t#(reverse$transpose$s);_#_=[];b=("1234"#) ``` [Try it online!](https://tio.run/##DcZLCsMgEADQq5SYhZKhkE9/EXdd9gYiwYBQSWJkZuj1rav3vp62sO@lxCOfyJe3Z3/9RGItz5mVkDiTMth1XBt@ASm0jD5RPutI6UUsxjq9Gtn0wzg1QpXDx2QyxsTtam0PA4wO7AQ3uFcf8ISXc@UP "Haskell – Try It Online") At each of the four or less iterations, `#` peels the top row `r` from the matrix, and rotates it i-wise by `transpose` sending corner 2 to 3 and `reverse` sending corner 2 from 3 to 1 before reiterating for one side `o` less than before. [Answer] # [R](https://www.r-project.org), 52 bytes ``` \(m)m[row(m)%in%c(1,nrow(m))|col(m)%in%c(1,ncol(m))] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZBBCsIwEEVx21NkIyQwA5m2alNw7QXcqQspVgq2Qqnowpu4qYKH0tP4S0AFK-FlMvP_ZGAu17q95dP7ock5ecRLXZpyUe-PiMOiGmZaqPKpOWf73XfZp2ble5-DmS6n5bqpi5OW1FFENDcmyOEJPkpRNZvtptbmV7K_pUw7UiHxiFREgZKkiwq3RQZBTSgU4k5TrrOJJecMxb2zJY1I-ockOOjrl_GpCkEEYjACYzABCXCWuANvRo2hMTwML6OH0ctizZ-NSAo_Rrw1v8-29fEF) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` IΣEθΦι¬∧﹪κ⊖Lθ﹪μ⊖Lι ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bY7BCoJAEIbvPcXgaYQR1IiUTpF0ygg6Lnsw3VLS3dS1l-nioahX8m1aUDo1h-Hn_7_5mccnzZMmVUnZ969On51g0IemkBo3Savx2FUYJzesCbZFqUWDBcFeaVzLDGOVdaXCK0Ek0kZUQmqR4U7Ii86xtm2bYEKqv0hh_2b1bE9pO33wZpZzLy0-RIwxCAl8chYEc04zAOYFRhKY7Y6GiWFJvkfORJgTw3suhSHnfOz8Ag) Link is to verbose version of code. Explanation: Uses a filter to keep elements in the first or last row or column i.e. those that are not both in an interior row and in an interior column. ``` θ Input array E Map over rows ι Current row Φ Filtered where κ Current row ﹪ Modulo θ Input array L Length ⊖ Decremented ∧ Logical And μ Current column ﹪ Modulo ι Current row L Length ⊖ Decremented ¬ Logical Not Σ Flatten I Cast to string Implicitly print ``` [Answer] # [julia](https://julialang.org/), 59 bytes Expects a `Matrix{Any}` and returns a `Vector{Any}` of the border entries. Each call of this function pops the top row of the matrix, rotates the resulting matrix to the right and recurses. Terminates after 4 iterations or when the resulting matrix is empty. ``` f(M,c=4)=length(M)c>0 ? [M[1,:];f(M[end:-1:2,:]',c-1)] : [] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZFLasMwEIbptqf4d5HAgpHfD5LuuqpPILwwjh27GDe4MhTanqSbbHKo9jQdxxSKDSMx-vXPfHp8XZ-nvisvl-tkGxV_Z43InWrvy31fDyfbilxWB8IDTG60kxbzvqmHY6p06vJ651RKywIpTLG0-Ll7aoTRcOFl8BEgzBAhRlJIfBxwHrvB9sM99ynt2L29P_YvpQ39TzENx7pxQBxyZW2r0oqNahKGqGDm6BgeMyhjJYKroVhM5k1NSDbo5Xhr9UYxSYb4Fly1KSO4BI_gEwJCyLyIEDOCoObBqYpYVSEn7FBsVOxXXKY0rYlj_dqW51roNORrC81TKOXuv2t51L__-QU) [Answer] # [Scala](https://www.scala-lang.org/), 98 bytes Golfed version. [Try it online!](https://tio.run/##lU1NS8QwEL3vr5hjwk5K2@03rOBRUC8eZSmxplipSTcJi7Dub6/TaotHN/Am783Me@Ma2cvRvLyrxsOD7DSoT6/0q4PbYYDz5iR7aCv2pI7Pd9ofcCKLOPD9zcJhDyMzeKTW/H1I37ydG@kUsMeux5p/sRqJ/fEw/jOv0VaVo4HdbltmAi/J4AJvpXaDcSqw6qSsU/wybgAG22nfa9YyFoE3kPDAm/vOeYSpsrlEGOOO/3YSTDFbRI4Flpzef6NKhBhFirDmRQUJBKrh0ooRcowjFOtSOXmiEMurjpEBYsKOkBBSQrZeyUkVhDJEMYG4yNepyEiSQZBRUICgIBGF8/nL@A0) ``` (o,q)=>(o,q)match{case (Nil,_)|(_,Nil)=>Seq[Int]()case (_,r::s)=>r++f(o.tail,s.transpose.reverse)} ``` Ungolfed version. [Try it online!](https://tio.run/##lU5dS8MwFH3frziPCbspbdeu7WCCj4L6B2SM2KWsMtuSBBF0v73elK3uUQPnknNzPuJqfdLj2L@@mdrjSbcdzKc33cHhfhjwtQAOpkEj@g0eW@dfHjq/I1h3ofNuJ28E2EL0QSXxrn19nHKAWjsD8dyeCHuJb4g9gZnE9u7XK@SNlgUWmw3cpLFYLsNXIq9Dhou81Z0bemciaz6MdSZ4zwseg207f@pEI0QC3yOTke9DB01NYhoJpbSSl01GOa2vpKCSKsnnr1EVISWVE@a8pGRC4BlfVymhoDQhNYuq4Eliqv5VxgakjBUjY@SM9dxSMCsZVUwqgO@qmF/VmikbFBsVBygOUkk81Z8X4/gD) ``` object Main extends App { def f(o: List[Int], rs: List[List[Int]]): List[Int] = (o, rs) match { case (Nil, _) | (_, Nil) => List[Int]() case (_, r :: s) => r ++ f(o.tail, s.transpose.reverse) } println(f((1 to 4).toList, List(List(1,2,3), List(4,5,6), List(7,8,9)))) println(f((1 to 4).toList, List(List(9, 2,-5, 3), List(18, 3, 8, 0), List(2, 7,21,-3), List(9,-5,10,99)))) println(f((1 to 4).toList, List(List(10, 20, 30, 40, 50, 60), List(70, 80, 90,-90,-80,-70), List(-60,-50,-40,-30,-20,-10)))) } ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `ṡ`, 6 bytes ``` ḣṫ$ᵛÞh ``` [Try it Online!](https://vyxal.github.io/latest.html#WyLhuaEiLCIiLCLhuKPhuask4bWbw55oIiwiIiwiW1sgMSwgMiwgMywgNCwgNSwgNl0sWyA3LCA4LCA5LDEwLDExLDEyXSxbMTMsMTQsMTUsMTYsMTcsMThdLFsxOSwyMCwyMSwyMiwyMywyNF0sWzI1LDI2LDI3LDI4LDI5LDMwXSxbMzEsMzIsMzMsMzQsMzUsMzZdLFszNywzOCwzOSw0MCw0MSw0Ml0sWzQzLDQ0LDQ1LDQ2LDQ3LDQ4XSxbNDksNTAsNTEsNTIsNTMsNTRdLFs1NSw1Niw1Nyw1OCw1OSw2MF1dIiwiMy40LjEiXQ==) Abuses formatting quite a bit but there isn't a way to get diagonals yet. ``` ḣṫ$ᵛÞh­⁡​‎‎⁡⁠⁡‏⁠⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌­ ḣ # ‎⁡head extract ṫ$ # ‎⁢tail extract and swap ᵛÞh # ‎⁣vectorized edges 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 23 bytes ``` (?<=¶.+)\b\S+\b(?=.+¶) ``` [Try it online!](https://tio.run/##K0otycxLNPz/X8PexvbQNj1tzZikmGDtmCQNe1s97UPbNLn@/7dUMFLQNVUw5jK0UDBWsFAw4DJSMFcwMlTQNeayBMkYGihYWgIA "Retina – Try It Online") Expects a matrix as having columns separated by spaces and rows separated by newlines. Works by removing numbers that have a newline more than immediately before and after them. The boundaries are required to avoid deleting digits/signs elsewhere in the boundary numbers since there isn't a way to make lookahead/behind non-greedy/backtrack (at least in fewer than 4 bytes). Seems shorter than [listing all boundary](https://tio.run/##K0otycxLNPz/3ychTk@7Rk9bpSYmWFvD3vbQNs0aDXsbEA0U@P/fUsFIQddUwZjL0ELBWMFCwYDLSMFcwchQQdeYyxIkY2igYGkJAA) numbers, for the same reason. I've found a [slightly crazy](https://tio.run/##K0otycxLNPz/3ychTk@7Rk9bpSamXPvQtpoY9@g4nVjt//8tdYx04k11jLkMLXSMdSx0DLiMdMx1jAx14o25LEEyhgY6lpYA) version that is a byte shorter, but is also far more abusive of the lax I/O. ``` L`^.+|.+$|\w+¶|\G[^,]+ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~31~~ 29 bytes Very similar to [SuperStormer’s Python 3 answer](https://codegolf.stackexchange.com/a/260991/11261). Outputs by modifying the given array. ``` ->a{a[r=1..-2].map{_1[r]=[]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9NDoIwEIX3nGIO8EpoFSkxdcklJhNTE92ZGISFIZzEDTF6DPdewdtY6AbczN_73kzm_qzbw214VO7VNidl32rnO8-102mqjKRnf-n2mmtxLH0fme-nOV4bcjSyVLGXLXnqk-RCo8DMGgYrQUK8Ro7NVBWwKEVkhmXLlkqQgcpB0attqEAhZlMfRCpgNFTUAx9gnaH82xvPL0bl5LCzOHriP8MQ8w8) ]
[Question] [ ## Challenge: Here we have the first 100 items of a sequence: ``` 6,5,4,3,2,1,66,65,64,63,62,61,56,55,54,53,52,51,46,45,44,43,42,41,36,35,34,33,32,31,26,25,24,23,22,21,16,15,14,13,12,11,666,665,664,663,662,661,656,655,654,653,652,651,646,645,644,643,642,641,636,635,634,633,632,631,626,625,624,623,622,621,616,615,614,613,612,611,566,565,564,563,562,561,556,555,554,553,552,551,546,545,544,543,542,541,536,535,534,533,... ``` How is this sequence formed? We first have the number in the range `[6, 1]` (all possible values of a single die from highest to lowest). We then have the numbers `[66..61, 56..51, 46..41, 36..31, 26..21, 16..11]` (all possible concatted values of two dice from highest to lowest). Etc. This is related to the OEIS sequence [A057436: *Contains digits 1 through 6 only*](http://oeis.org/A057436), but with all the numbers with equal amount of digits sorted backwards in the sequence. The challenge is to choose one of these three options for your function/program with the sequence above: 1. Take an input \$n\$ and output the \$n\$'th value of this sequence, where it can be either 0-indexed or 1-indexed. 2. Take an input \$n\$ and output the first \$n\$ or \$n+1\$ values of this sequence. 3. Output the values from the sequence indefinitely. Of course, any reasonable output format can be used. Could be as strings/integers/decimals/etc.; could be as an (infinite) list/array/stream/etc.; could be output with space/comma/newline/other delimiter to STDOUT; etc. etc. **Please state what I/O and option you're using in your answer!** ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. **Here some larger test cases if you choose option 1:** ``` n 0-indexed output 1-indexed output 500 5624 5625 750 4526 4531 1000 3432 3433 9329 11111 11112 9330 666666 11111 9331 666665 666666 10000 663632 663633 100000 6131232 6131233 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~24~~ 23 bytes *-1 byte thanks to nwellnhof* ``` {.put;.[]X~(6...1)}...* ``` [Try it online!](https://tio.run/##K0gtyjH7/79ar6C0xFovOjaiTsNMT0/PULMWSGr9/w8A "Perl 6 – Try It Online") Outputs the sequence infinitely separated by spaces/newlines. Or, for a few more bytes we can have a lazy infinite list we can index into instead. # [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes ``` {flat {@=.[]X~(6...1)}...*} ``` [Try it online!](https://tio.run/##Zc7fCoIwFAbw6/YU56o0YuzsuIWE0mMEskBIIbA/aBAi9uo2nUGt72Kwj992zr2oKz1cWliWkMDQlVX@gG6f8MwcXoHmnGPY23PdD03eQhmE2RGFMDvGylsN1flaNGnKn7f61EDHFh/EM2HMBlaQpLDaAM/QsH5QQoCL0jICL7ZTbKs@JFJS@yRShMzOnw1FJH1iO2IxydhdcYxHxkpaQ/M3esq/wdHgl1G/xr2b9hFzQdrfaOrIoUlpJJSech29AQ "Perl 6 – Try It Online") ### Explanation: ``` { } # Anonymous code block flat # Return the flattened ...* # Infinite sequence { } # Defined as .[] # The previous element arrayified X~ # Each concatenated with (6...1) # All of 6 to 1 @= # Arrayified ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ ~~38~~ 34 bytes ``` f=lambda n:n and-n%6+1+f(~-n/6)*10 ``` [Try it online!](https://tio.run/##Vc3RCsIwDAXQ935FQYTVbdg0a2UDP6ai1YJmY@zFF3@9dh2b9UIg5BDu8J4ePakQ3PlpX5er5dQRt3StaW9KKF3xqeloxAFkcP3IPffER0v3WwGVkaJjfBg9TdwVXlQs7YytJy2l4DG7ONoovcFJ/6DRCBuAXF5mwAZxgxZVuwLEqExQ5gK5wCom5a9n/loITdaUKFoiQFCI4Qs "Python 2 – Try It Online") Outputs 1-indexed number [Answer] # [R](https://www.r-project.org/), 43 bytes ``` p='';repeat cat(p<-sapply(p,paste0,6:1),'') ``` [Try it online!](https://tio.run/##K/r/v8BWXd26KLUgNbFEITmxRKPARrc4saAgp1KjQKcgsbgk1UDHzMpQU0ddXfP/fwA "R – Try It Online") Prints the sequence indefinitely * -9 thanks to @Kirill L. [Answer] # Bash, 31 bytes ``` f()(x+={6..1};eval echo $x;f);f ``` [TIO](https://tio.run/##S0oszvj/P01DU6NC27baTE/PsNY6tSwxRyE1OSNfQaXCOk3TOu3/fwA) update from comments, the n'th value 1-indexed, +GNU tools + perl, 64 bytes, 7 bytes saved thanks to @manatwork ``` dc<<<6o$1p|perl -pe 's/(.)0/($1-1).6/e?redo:s/0//'|tr 1-6 654321 ``` [64 bytes](https://tio.run/##Zc7BCoJAEAbgu08xB0E76O7suBOV0INIRLULBaKiQRff3VbXoLb/Nj/fDHO9DPfpdX/UFnp7MdDAeRyrCuIGTqeDaWGwTzdM5laWJbcxdmNn@xqyzkIyiDTfSJHGmOEmZ2GPvTXtfhBSiGR89oAZA@uCFE6mbeykpQQfzaqAIK7T0VZ/SKEVh6TQhBHKzxlyp0PiOop2pHZ@xDkBmSvlDK1neMm/wdngl9G/xu8t/8i1IA4/WjryaFGMhCpQvqM3) [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` `6:P!V@Z^DT ``` Outputs the values indefinitely. [Try it online!](https://tio.run/##y00syfn/P8HMKkAxzCEqziXk/38A "MATL – Try It Online") ### Explanation ``` ` % Do...while 6: % Push [1 2 3 4 5 6] P % Flip: gives [6 5 4 3 2 1] ! % Transpose: turns the row vector into a column vector V % Convert the number in each row to the corresponding char @ % Push current iteration index, starting from 1 Z^ % Cartesian power. Gives a matrix where each row is a Cartesian tuple D % Display immediately T % Push true. This is used as loop condition, to give an infinite loop % End (implicit) ``` [Answer] # Haskell, ~~38~~ 34 bytes An infinite list of numbers: ``` d=[6,5..1] l=d++[10*m+n|m<-l,n<-d] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8U22kzHVE/PMJYrxzZFWzva0EArVzuvJtdGN0cnz0Y3JfZ/bmJmnoKtQkFRZl6JgopCSWJ2qoKhgYFCzn8A "Haskell – Try It Online") Two earlier solutions that give infinite lists of strings, each using 38 bytes: ``` [1..]>>=sequence.(`replicate`"654321") ``` [Try it online!](https://tio.run/##DcxLDkAwEADQq0zEgoVG/XZ1ESQmzaBRTbV1fcM7wDswnmQtB4pq5kkKsYyjinQ/5DSJYg3krdGYaM2GvmsbmZV8oXGgwAfjEuSQ8CSQdQ1/wq/eLO6RK@39Bw "Haskell – Try It Online") ``` do n<-[1..];mapM id$[1..n]>>["654321"] ``` [Try it online!](https://tio.run/##FcxNEkAgFADgq7wxtkz526AbOEFavCE0JU05v4flt/kOTFY7R1Gncab1Aj8Ukpel6k8ME5g1/@WVEDLr2qaueKboRONhhBCNvyGHG60Gzhh8CT3L5nBPVCwhvA "Haskell – Try It Online") [Answer] # JavaScript (ES6), 26 bytes Returns the \$n\$th term, 1-indexed. ``` f=n=>n--&&[f(n/6|0)]+6-n%6 ``` [Try it online!](https://tio.run/##bc5NDsIgEAXgvadgYwMxyAxTMF3UixgXTS1G00BjjSvvjlqtP8W3/d7LzLG6VH19OnRn6cOuidGVvlx7KbNs47hX9gpiu7DSz22sg@9D2yzbsOeOGwDGmBBMKWasNrNfXpkP54ZwwgiP@ZMpJ5pwQboYGe/RiRN8O6aOo9shf@7Du0A2@WAowKuAhJoo3gA "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` l=(+).(10*)<$>0:l<*>[6,5..1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8dWQ1tTT8PQQEvTRsXOwCrHRssu2kzHVE/PMPZ/bmJmnoKtQkFRZl6JgopCSWJ2qoKhgYFCzn8A "Haskell – Try It Online") Produces an infinite list of numbers `l`. Using `<$>` and `<*>` cuts a byte off: **29 bytes** ``` l=[10*n+d|n<-0:l,d<-[6,5..1]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8c22tBAK087pSbPRtfAKkcnxUY32kzHVE/PMDb2f25iZp6CrUJBUWZeiYKKQklidqqCoYGBQs5/AA "Haskell – Try It Online") The approach is similar to the Haskell [Output All String answer](https://codegolf.stackexchange.com/a/74293/20260) fixed input string "654321", and skipping the empty string output by changing where it's prepended. **30 bytes** ``` l=[n++[d]|n<-"":l,d<-"654321"] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8c2Ok9bOzoltibPRldJySpHJwVIm5maGBsZKsX@z03MzFOwVSgoyswrUVBRKEnMTlUwNDBQyPkPAA "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes Outputs the sequence indefinitely. ``` ¸[6LRâJD», ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0I5oM5@gw4u8XA7t1vn/HwA "05AB1E – Try It Online") **Explanation** ``` ¸ # initialize the stack with a list containing the empty string [ # loop 6L # push [1 ... 6] R # reverse â # cartesian product J # join each inner list D # duplicate (saving a copy for next iteration) », # join on newline and print ``` [Answer] # Perl 5, ~~40~~ 37 bytes -3bytes thanks to @Xcali ``` map{say}<"$_">while s//{6,5,4,3,2,1}/ ``` [37 bytes](https://tio.run/##K0gtyjH9/z83saC6OLGy1kZJJV7JrjwjMydVoVhfv9pMx1THRMdYx0jHsFb///9/@QUlmfl5xf91fU31DAwB) [40 bytes](https://tio.run/##K0gtyjH9/z@1LDFHqTixUiEtv8hGJd5OqTwjMydVoVhfv9pMx1THRMdYx0jHsFb///9/@QUlmfl5xf91fU31DAwB) [Answer] # [Java (JDK)](http://jdk.java.net/), 48 bytes ``` String f(int n){return n-->0?f(n/6)+(6-n%6):"";} ``` [Try it online!](https://tio.run/##ZY5NboMwEIX3nOIJqRJuDDWhoQqo7Qm6yrLqghCITMEge4hUIc5ObUhXleyZNz/63jTFrQiby/ciu6HXhMbW0UiyjR5z71@vHlVJslduWLaFMfgopMLkAYYKkuVyIi3VFXUgFUGxSVc0agUVhm/ivQ7UU8p2QRqqh5Rlvp/PCzCM51aWdwBuvbygs9RgQ31@odBXw1YTwGJthypDBq@YEHPsORKOZ44DR8rxYoUQNh9siIWTx2R/dDFZdRJv/ftYCMz5yq57vZ7t6Nnm8WcLnH4MVV3UjxQN9i5qVeA2sIOfwbepXmvGNtbsue/Zt/wC "Java (JDK) – Try It Online") This returns the 1-indexed nth element. Recursion seems to beat the iterative lambda. --- ### Iterative version, 49 bytes ``` n->{var r="";for(;n-->0;n/=6)r=6-n%6+r;return r;} ``` [Try it online!](https://tio.run/##ZY8xb4MwEIV3fsUTUiVoDCWhoUpcGCt16JSx6uASQKZgkH1EiiJ@OzWQTh1873zv9N1dLS4iqM8/k2z7ThNq@w8Hkk34yJ1/tXJQOclOzWbeCGPwIaTCzQH64buROQwJsnLp5Bmt9bwTaamqzy8IXRl/aQXe7pzXd0VFVWi2dmUokWJSQXa7CA2dui4vO@1xFQRZxNVTmvg6TQL1kGw01wUNWkHzceILVSqyc6gwZCzmhi3DjiFmeGbYMyQMLzaJIqt7G7bRnB7i3WGO8ZLH27V@t6MI48qe17D8hX5cZ/wdA5yuhoo27AYKe3sHNcqbO7CBe4RrpQxF3zfXper7K3F05jdOvw "Java (JDK) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ 11 bytes *Thanks to [Fatalize](https://codegolf.stackexchange.com/users/41723/fatalize) for 2 bytes* ``` 6~d{⟧₁∋}ᵐẉ⊥ ``` Outputs indefinitely. [Try it online!](https://tio.run/##ASUA2v9icmFjaHlsb2cy//82fmR74p@n4oKB4oiLfeG1kOG6ieKKpf// "Brachylog – Try It Online") Here's a 14-byte version that outputs the first \$n\$ values: [Try it online!](https://tio.run/##ASwA0/9icmFjaHlsb2cy//87Nnt@ZHvin6figoHiiIt94bWQfeG2oOKBvf//NDj/WA) ### Explanation ``` 6~d Start with a number, all of whose digits are 6's Brachylog considers these in the order 6, 66, 666, 6666... { }ᵐ Map this predicate to each of those digits: ⟧₁ 1-based reverse range: [6,5,4,3,2,1] ∋ The output digit must be a number in that range Brachylog considers possible outputs in this order: 6, 5, 4, 3, 2, 1, 66, 65... ẉ Write a possible output with newline ⊥ Force the predicate to fail and backtrack to the next possibility ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 38 bytes ``` int f(int n)=>n-->0?f(n/6)*10+6-n%6:0; ``` [Try it online!](https://tio.run/##JY5PC4JAFMTvfopHELj5p2eioZIduhYEHTpEB9lWemBPcJcixM9uq11@DDPDMFIHsu3UKJtKazhD72hTGZLwbukBp4rYFdCPxAZqdyKLXclBUOK@dnmdilWEXhrwMs2xGGs7VcknzE0CYmD1ud37BNHfJuhHaEUWbzKLeFJxNHv/BHEQDsDlq416hYeWdduo8NqRUUdi5RJ4sMgXlvaKEIUzOMP4Aw "C# (.NET Core) – Try It Online") Outputs the n-th value (1-based). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ḃ6ạ7V ``` [Try it online!](https://tio.run/##y0rNyan8///hjmazh7sWmof9P7T5cPujpjX/AQ "Jelly – Try It Online") 1-indexed nth value. [Answer] # Japt, 14 bytes There's gotta be a shorter solution using function methods and/or Cartesian product but (for now?) the best I can manage is a port of Arnauld's JS solution so be sure to upvote him too. ``` ©ß´Uz6)s+6-Uu6 ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=qd+0VXo2KXMrNi1VdTY=&input=NTAw) or [test terms `0-1000`](https://ethproductions.github.io/japt/?v=2.0a0&code=qd+0VXo2KXMrNi1VdTY=&input=MTAwMQotbQo=) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~88~~ 78 bytes ``` (l=d=c=7-Range@6;While[Length@c<#,d=Flatten[(10#+l)&/@d];c=c~Join~d;];c[[#]])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/18jxzbFNtnWXDcoMS891cHMOjwjMyc12ic1L70kwyHZRlknxdYtJ7GkJDUvWsPQQFk7R1NN3yEl1jrZNrnOKz8zry7FGsiJjlaOjdVU@58WnRcfa2VLXVOj82K5Aooy80oc0qJNDQwQHHNTJI6hAbKUpbGRJTLPGEXO2BBVH5oxQP5/AA "Wolfram Language (Mathematica) – Try It Online") saved 4 + 6 bytes thanks to @IanMiller List is 1 indexed, outputs the n'th number. [Answer] # Mathematica, 56 bytes ``` Flatten[FromDigits/@Tuples[7-Range@6,#]&/@Range@#][[#]]& ``` Requires excessive amounts of memory to actually run as it creates all numbers in the sequence which have length equal to or less than the input (i.e. it creates \$\frac{6}{5}(6^n-1)\$ terms) then takes the required value from the list. For practice use replace the second last # with a specific value for the length you want to use it on. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 16 bytes ``` x:YP6-,6W1PxCP:y ``` Outputs the sequence indefinitely. [Try it online!](https://tio.run/##K8gs@P@/wioywExXxyzcMKDCOcCq8v///7o5AA "Pip – Try It Online") ### Explanation The `-l` flag means that lists are printed with each item on its own line; if an item is itself a list, its elements are concatenated with no separator. E.g. the list `[1 [2 3] [4 [5 6]]]` would be printed as ``` 1 23 456 ``` With that cleared up: ``` x:YP6-,6W1PxCP:y ,6 Range(6): [0 1 2 3 4 5] 6- Subtract each element from 6: [6 5 4 3 2 1] YP Yank that value into the y variable, and also print it x: Assign that value also to x W1 While 1 (infinite loop): xCP: Assign to x the cartesian product of x with y the list [6 5 4 3 2 1] P Print it ``` After the first loop iteration, `x` looks like `[[6;6];[6;5];[6;4];...;[1;1]]`; after the second iteration, `[[[6;6];6];[[6;6];5];[[6;6];4];...;[[1;1];1]]`; and so on. We don't need to worry about flattening the sublists, because `-l` effectively does it for us. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` NθWθ«←I⊕﹪±θ⁶≔÷⊖θ⁶θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05qrPCMzJ1UByFSo5uIMKMrMK9Gw8klNK9FRcE4sLtHwzEsuSs1NzStJTdHwzU8pzcnX8EtNTyxJBerQUTDTBAJrLk7H4uLM9Dyg4hKXzLLMlFQNl1SENohCHQWQbbX//5ubGvzXLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Explanation: ``` Nθ ``` Input `n` ``` Wθ« ``` Repeat until `n` is zero. ``` ←I⊕﹪±θ⁶ ``` Reduce `-n` modulo `6`, then increment the result and output from right to left. ``` ≔÷⊖θ⁶θ ``` Decrement `n` and integer divide it by `6`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` .+ $*_ +`(_*)\1{5}(_+) $1$.2 T`7-1`d ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0Urnks7QSNeSzPGsNq0ViNeW5NLxVBFz4grJMFc1zAh5f9/UwMDLnNTAy5DAyDD0tjIEkgYg1jGhmAxiIyBAQA "Retina 0.8.2 – Try It Online") Link includes test cases. 1-indexed. Explanation: ``` .+ $*_ ``` Convert to unary. (Retina 1 would save 2 bytes here.) ``` +`(_*)\1{5}(_+) $1$.2 ``` Convert to bijective base 6 by repeated divmod. Note that the use of `+` means that the extracted digit is always a number from 1 to 6 instead of 0 to 5 for regular base 6 conversion. (`(_{6})*` is faster but costs bytes extracting the quotient.) ``` T`7-1`d ``` Transpose the digits so that the 6s come first and the 1s last. (There are no 7s or 0s but this allows me to use the `d` shortcut. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 22 bytes This will output the sequence indefinitely. The general idea is that it has a base number which 6 - 1 is added to. For each add the result is output multiplied by 10, which is pushed to the bottom of the stack to be used later in the sequence. The base is then popped and the next base started. ``` ..w.06+ONo*w;|uW!(pq;; ``` [Try it online!](https://tio.run/##Sy5Nyqz4/19Pr1zPwEzb3y9fq9y6pjRcUaOg0Nr6/38A "Cubix – Try It Online") ``` . . w . 0 6 + O N o * w ; | u W ! ( p q ; ; . . ``` [Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgIC4gLgogICAgdyAuCjAgNiArIE8gTiBvICogdwo7IHwgdSBXICEgKCBwIHEKICAgIDsgOwogICAgLiAuCg==&input=&speed=20) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), infinite printing, ~~181 180~~ 88 bytes. ``` string[] s=new string[]{" "},t;int i,j,k,l=1;while(true){j=l;t=new string[l=6*j];for(i=6;i>0;i--)for(k=(6-i)*j;k<l;)t[k]=i+s[k++%j]; for(k=0;k<l;)System.Console.Write(t[k++]);s=t;} ``` Sadly it freezes repl.it instead of outputting properly in the infinite version as written (I believe it to be an error in repl.it, as it does not output as the program loops like it should), so anyone hoping to test needs a computer. If you add a read at the front of the loop it works in repl.it as well. Outputs to the console, obviously. On any finite system the code will most likely eventually crash with an out of memory error. Reworked the code to use @dana 's lambda. ``` int f(int n)=>n-->0?f(n/6)*10+6-n%6:0;for(int i=0;++i>0;)System.Console.Write(f(i)+" "); ``` [Try it online!](https://tio.run/##Hcy9CsIwFEDh3ae4FITEkBqXDobGwVkQHBzEIcS0XKg3kBsEKX32@LOc6eME1iHlWMPkmeEM84qLLxjglfABJ48kuGSk8XYHL2GuSAUG8SvJ3pHWzhwGQdtObnZGdZrW3d7YIeW/wd5YpdAZKy9vLvHZHhNxmmJ7zVii@J6kaqCRti5L/QA "C# (.NET Core) – Try It Online") [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 63 bytes ``` : f recursive dup 6 < if 6 - abs 1 .r else 6 /mod 1- f f then ; ``` [Try it online!](https://tio.run/##NYtNDoIwEIX3PcUL@2JrgwYh3kVhRkhUmil4/ToozOZ7P/N4knmwD16R8wUMoW6RNH4I/RJxQouRFRa3e4JHKaBnIk0Or6mHtzphzAO90eg@bit9KwvAXlFo3QkaYyrnsF4052pX3mkYTR2O9Q/h74LfOrdTRf4C "Forth (gforth) – Try It Online") 0-indexed outputs nth value ### Explanation If N is less than 6, output the absolute value of N - 6. Otherwise, get the quotient and remainder of dividing N by 6. Call the function recursively on the quotient, then call it on the remainder. ### Code Explanation ``` : f \ start a new word definition recursive \ declare that this word is recursive so we can call it from itself dup 6 < \ check if n is less than 6 if \ if it is: 6 - abs 1 .r \ subtract 6, get the absolute value, then print with no appended space else \ else if it's greater than 6: 6 /mod \ get the quotient and remainder of dividing n by 6 1- \ subtract 1 from the quotient (because we're 0-indexed) f \ call f on the result f \ call f on the remainder (shortcut to format and print, it's always < 6) then \ end the if/else ; \ end the word definition ``` [Answer] # APL(NARS), 27 chars, 54 bytes ``` {0>⍵-←1:0⋄(6-6∣⍵)+10×∇⌊⍵÷6} ``` traslate the solution by dana <https://codegolf.stackexchange.com/a/179980> in APL... test: ``` f←{0>⍵-←1:0⋄(6-6∣⍵)+10×∇⌊⍵÷6} f 500 5625 f¨750 1000 9329 9331 10000 100000 4531 3433 11112 666666 663633 6131233 f¨⍳9 6 5 4 3 2 1 66 65 64 ``` [Answer] # C#, print from start to n, ??? bytes Credit to @dana for the lambda expression. ``` int f(int n)=>n-->0?f(n/6)*10+6-n%6:0;for(int i=0;i<int.Parse(a[0]);)System.Console.Write(f(++i)+" "); ``` Operation: Run with command line 0th argument equal to the integer you want to count to. (It should be noted that `a[0]` is a reference to the otherwise unmentioned command line args array, and I don't know how to count it.) ]
[Question] [ # Problem Let's say that a word is almost a **[palindrome](https://en.wikipedia.org/wiki/Palindrome)** if it is possible to remove one of its letters so that the word becomes a palindrome. Your task is to write a program that for a given word determines which letter to remove to get a palindrome. The shortest code to do this in any programming language wins. ## Input Input consists of a word of lowercase letters from 2 to 1000 characters long. ## Output Output the 1-indexed position (leftmost letter has position 1, the next one has position 2 and so on) of the letter which should be removed. If there are possible choices that lead to the palindrome, output any of those positions. Note that you are required to remove a letter even if the given word is already a palindrome. If the given word is not almost a palindrome, output -1. --- # Examples The input: ``` racercar ``` might produce either of these outputs: ``` 4 5 ``` because removing the `4`th letter produces `racrcar` and removing the `5`th letter produces `racecar`, which are both palindromes. Also, the input ``` racecar ``` can still produce the output ``` 4 ``` because removing the `4`th letter to produce `raccar` is still a palindrome. The input ``` golf ``` should produce the output ``` -1 ``` because there is no way to remove a single letter to make it a palindrome. [Answer] # J - 31 25 char ``` (_1{ ::[1+[:I.1(-:|.)\.]) ``` Largely standard fare for J, so I'll just point out the cool bits. * The adverb `\.` is called *Outfix*. `x u\. y` removes every infix of length `x` from `y` and applies `u` to the result of each removal. Here, `x` is 1, `y` is the input string, and `u` is `(-:|.)`, a test for whether the string matches its reverse. Hence the result of this application of `\.` is a list of booleans, 1 in the place of each character whose removal makes the input a palindrome. * `I.` creates an list of all the indices (0-origin) from above where there was a 1. Adding 1 with `1+` makes these 1-origin indices. If no indices were 1, the list is empty. Now, we try to take the last element with `_1{`. (We are allowed to output any of the removable letters!) If this works, we return. However, if the list was empty, there were no elements at all, so `{` throws a domain error which we catch with `::` and return the -1 with `[`. Usage (recall that `NB.` is for comments): ``` (_1{ ::[1+[:I.1(-:|.)\.]) 'RACECAR' NB. remove the E 4 (_1{ ::[1+[:I.1(-:|.)\.]) 'RAACECAR' NB. remove an A 3 (_1{ ::[1+[:I.1(-:|.)\.]) 'RAAACECAR' NB. no valid removal _1 ``` [Answer] # ~~Not-PHP~~ Python (73): ``` [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(1) ``` Where a is the string you want to check. ~~This, however, throws an error if you can't turn it in an palindrome. Instead, you could use~~ ``` try:print [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(True) except ValueError:print -1 ``` EDIT: No, wait, it does work! ``` try: eval("<?php $line = fgets(STDIN); ?>") except: print [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(1) ``` Thanks, this does indeed raise the php-contents of this script by about 25% (that's what you want, right?) [Answer] ## Mathematica, ~~106~~ ~~98~~ ~~87~~ 91 characters I suppose I'm slightly handicapped by the long function names, but problems like this are quite fun in Mathematica: ``` f=Tr@Append[Position[c~Drop~{#}&/@Range@Length[c=Characters@#],l_/;l==Reverse@l,{1}],{-1}]& ``` It throws some warnings, because the `l_` pattern also matches all the characters inside, which `Reverse` can't operate on. But hey, it works! Somewhat ungolfed: ``` f[s_] := Append[ Cases[ Map[{#, Drop[Characters[s], {# }]} &, Range[StringLength[s]]], {_, l_} /; l == Reverse[l] ], {-1} ][[1, 1]] ``` [Answer] ### GolfScript, 28 26 characters ``` :I,,{)I/();\+.-1%=}?-2]0=) ``` Thanks to Peter for shortening by 2 characters. Try the test cases [online](http://golfscript.apphb.com/?c=O3suYCcgJytwcmludAogIDpJLCx7KUkvKCk7XCsuLTElPX0%2FLTJdMD0pCnB1dHN9OlA7CgoiUkFDRUNBUiIgUAoiUkFBQ0VDQVIiIFAKIlJBQUFDRUNBUiIgUAoiQUJDQzFCQSIgUAoiQUFBQUFBIiBQCiJBQkNERSIgUAoiIiBQCiJBIiBQCg%3D%3D&run=true): ``` > "RACECAR" 4 > "RAACECAR" 2 > "RAAACECAR" -1 > "ABCC1BA" 5 > "AAAAAA" 1 > "ABCDE" -1 > "" -1 > "A" 1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` a@jYÉ êS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YUBqWckg6lM&input=InJhY2VyY2FyIg) ``` a@jYÉ êS :Implicit input of string a :Last 0-based index that returns true (or -1 if none do) @ :When passed through the following function as Y j : Remove the character in U at index YÉ : Y-1 êS : Is palindrome? ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~8~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ú·àA÷¡%5Ñ╙ ``` [Run and debug it](https://staxlang.xyz/#p=a3fa8541f6ad2535a5d3&i=%22abc%22%0A%22racercar%22%0A%22racecar%22&a=1&m=2) This program shows all 1-based indices that can be removed from the string to form a palindrome. And if there are none, it shows -1. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ŒḂ-ƤTȯ-Ḣ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7mnSPLQk5sV734Y5F/3UOt3sf63rUtCby/3@losTk1KLkxCIlHTATwkpMSk4BUsmJJQolicn5SMxiIDsjMTcRSOUmQhkgKj9PCQA "Jelly – Try It Online") Not overwriting my older answer since it's among my first Jelly answers, but it's still way too embarrassing not to fix. I can't blame myself for not coming up with this exactly since nilad-`Ƥ` is pretty obscure documentation-wise, but at least `JœPẎŒḂɗƇȯ-Ḣ` should have been in reach... ``` -Ƥ For each "1-outfix" (remove a single item) of the input, ŒḂ is it a palindrome? T List all truthy indices. ȯ- Replace an empty list with -1, Ḣ and return the first element. ``` # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 14 bytes ``` ŒPṖLÐṀṚŒḂ€TXo- ``` [Try it online!](https://tio.run/##y0rNyan8///opICHO6f5HJ7wcGfDw52zjk56uKPpUdOakIh83f86h9u9j3UBeZH//ysVJSanFiUnFinpgJkQVmJScgqQSk4sUShJTM5HYhYD2RmJuYlAKjcRygBR@XlKAA "Jelly – Try It Online") ``` X A random T truthy index ŒP from the powerset of the input Ṗ excluding the input LÐṀ and all proper subsequences with non-maximal length Ṛ reversed ŒḂ€ with each element replaced with whether or not it's a palindrome, o- or -1. ``` Since I changed my approach fast enough for the old version not to show up in edit history, it was this: `ŒPṚḊŒḂ€TṂ©’<La®o-` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā.Δõs<ǝÂQ ``` [Try it online](https://tio.run/##yy9OTMpM/f//SKPeuSmHtxbbHJ97uCnw//@ixOTUouTEIgA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9TVnl4Qqi9ksKjtkkKSvb/jzTqnZsScXhrpc3xuYebAv/X6vwvSkxOLUpOLOICMUB0en5OGgA). **Explanation:** ``` ā # Push a list in the range [1, (implicit) input-length] .Δ # Pop and find the first value in this list which is truthy for: # (which will result in -1 if none are truthy) õ # Push an empty string "" s # Swap to get the current integer of the find_first-loop < # Decrease it by 1 because 05AB1E uses 0-based indexing ǝ # In the (implicit) input-String, replace the character at that index with # the empty string ""  # Then bifurcate the string (short for Duplicate & Reverse copy) Q # And check if the reversed copy is equal to the original string # (so `ÂQ` basically checks if a string is a palindrome) # (after which the result is output implicitly) ``` [Answer] # Rebol (81) ``` r: -1 repeat i length? s[t: head remove at copy s i if t = reverse copy t[r: i]]r ``` Example usage in Rebol console: ``` >> s: "racercar" == "racercar" >> r: -1 repeat i length? s[t: head remove at copy s i if t = reverse copy t[r: i]]r == 5 >> s: "1234" == "1234" >> r: -1 repeat i length? s[t: head remove at copy s i if t = reverse copy t[r: i]]r == -1 ``` Above returns index of last palindrome found. An alternative solution (85 chars) which returns every palindrome found would be: ``` collect[repeat i length? s[t: head remove at copy s i if t = reverse copy t[keep i]]] ``` So for `"racercar"` this would return list `[4 5]`. [Answer] # C#, 134 Characters ``` static int F(string s,int i=0){if(i==s.Length)return-1;var R=s.Remove(i,1);return R.SequenceEqual(R.Reverse())?i+1:F(s,i+1);} ``` I know I lose **:(** but it was still fun **:D** Readable version: ``` using System.Linq; // namespace and class static int PalindromeCharIndex(string str, int i = 0) { if (i == str.Length) return -1; var removed = str.Remove(i, 1); return removed.SequenceEqual(removed.Reverse()) ? i+1 : PalindromeCharIndex(str, i + 1); } ``` [Answer] # [~~Not Python~~ PHP](https://php.net/), ~~85~~ ~~83~~ 81 bytes ``` while($argn[$x])$s!=strrev($s=substr_replace($argn,'',$x++,1))?:die("$x");echo-1; ``` * -2 bytes thanks to @Night2! [Try it online!](https://tio.run/##K8go@G9jXwAkyzMyc1I1VBKL0vOiVSpiNVWKFW2LS4qKUss0VIpti0uTgJz4otSCnMRkqDIddXUdlQptbR1DTU17q5TMVA0llQolTevU5Ix8XUPr//@LgEqLkhP/5ReUZObnFf/XdQMA "PHP – Try It Online") Unnecessarily recursive: ### [PHP](https://php.net/), 96 bytes ``` function f($a,$b='',$d=1){return$a?$c==strrev($c=$b.$e=substr($a,1))?$d:f($e,$b.$a[0],$d+1):-1;} ``` [Try it online!](https://tio.run/##VU5Na4MwGL77Kx4kEGVpMeymy2Swjh0Kk643EYkxooepRO2l9Le7aNvR5RDe5@t9n77u55e4t381tWpsuhaVRyQjhaCUkVJw/2z0OJmWyJgoIYbRGH3y7EiKLdFimApLLRHu@zEpQxvXbNFkGmR2wxP3ww2PLjMZ9TAOEEgdgBqptFHSUHZHD@A/Wo1XIAuleHEH6/sTSn0dbwR1sshxqs5oqWoPt@tysBN8nK1Hq7qDLZ/3slwMDDyAz@CGcNmD0NjOlbfmGJ4ZKCjD9/GQJ2/v@X73cVx463oVCBDDBQ76pztpuwZbG0tJs@EZwqUaks8k333tI@cy/wI "PHP – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 20 bytes ``` l⟧∋.&↻↺↙.b↺↻↙.I↔I∨_1 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wP@fR/OWPOrr11B617X7UtutR20y9JDC9G8T0fNQ2xfNRx4p4w///o5WApqUWJScWKemAmRBWYlJyCpBKTixRKElMzkdiFgPZGYm5iUAqNxHKAFH5eUBGam5@CRDm5qcqxQIA "Brachylog – Try It Online") [It was too long](https://codegolf.stackexchange.com/a/190513/85334) [Answer] # Ruby (61): ``` (1..s.size+1).find{|i|b=s.dup;b.slice!(i-1);b.reverse==b}||-1 ``` Here, have a ruby solution. It will return the position of the character to remove or -1 if it cannot be done. I can't help but feel there's improvement to be made with the dup and slice section, but Ruby doesn't appear to have a String method that will remove a character at a specific index and return the new string -\_\_-. *Edited as per comment, ty!* [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes ``` {l+₁≥.ℕ₂≜&↔⊇ᶠ↖.tT↔T∨0}-₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wvzpH@1FT46POpXqPWqYCxR91zlF71DblUVf7w20LHrVN0ysJAXJDHnWsMKjVBar8/z9aCWhqalFyYpGSDpgJYSUmJacAqeTEEoWSxOR8JGYxkJ2RmJsIpHIToQwQlZ@nFAsA "Brachylog – Try It Online") Feels way too long. Could be two bytes shorter if the output could be *2-indexed*: ``` l+₁≥.ℕ₂≜&↔⊇ᶠ↖.tT↔T∨_1 ``` Two earlier and even worse iterations: ``` ẹ~c₃C⟨hct⟩P↔P∧C;Ȯ⟨kt⟩hl<|∧_1 l>X⁰ℕ≜<.&{iI¬tX⁰∧Ih}ᶠP↔P∨_1 ``` The latter's use of a global variable necessitates a [different testing header](https://tio.run/##SypKTM6ozMlPN/r/qKO7ulxJQddOQanc/lHbhkdNTQ93dSrWPupa@j/HLuJR44ZHLVMfdc6x0VOrzvQ8tKYELNSx3DOj9uG2BQGP2qYEPOpYEW/4/3@0EtDU1KLkxCIlHTATwkpMSk4BUsmJJQolicn5SMxiIDsjMTcRSOUmQhkgKj9PKRYA). [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~56~~ 52 bytes ``` ("$`$'"eq reverse"$`$'")&&($\=pos)while/./g}{$\||=-1 ``` [Try it online!](https://tio.run/##K0gtyjH9/19DSSVBRV0ptVChKLUstag4FcLXVFPTUImxLcgv1izPyMxJ1dfTT6@tVompqbHVNfz/vygxObUoObHoX35BSWZ@XvF/XV9TPQNDg/@6BTkA "Perl 5 – Try It Online") [Answer] # [Python 3](https://python.org), 681 bytes ``` from itertools import groupby def solution(x): if len(x) == 1: return 1 lst = [''.join(g) for _, g in groupby(sorted(x))] print(lst) pal_str_len = 0 single_elements = False odd_elements = False for i in lst: if len(i)%2 == 0: pal_str_len +=len(i) elif len(i)%2 == 1: if odd_elements: pal_str_len +=len(i)-1 else: odd_elements = True pal_str_len +=len(i) elif len(i) == 1: if not odd_elements and not single_elements: single_elements = True pal_str_len += 1 return len(x)-pal_str_len x = 'AAABBC' print(solution(x)) ``` [Answer] # C++, ~~247~~ 150 bytes -97 thanks to ceilingcat [TIO Link](https://tio.run/##HY6xbsIwFEV3vsKAVGwcI7LGMQih7lVWyBCcFL2osZPn54nCr1On29WRztWx46ju1r7faxhGj1QOzXhYgCP2xQO1RREIwd1ZEI8ZgtlnfTZlaFSuvz1yHS4gZb1dvlCjmY5YgJh5E8kzMmEX4i1d8N5MSQWVC/mRlFrTpa@1mH7NPNSWd67lJJSUvdDYUUTHUD9TlrM/se1K8Omma4bDYmjAcfH4r7M@EivLFLuqTufP6nyqVmIGm6vbJP0P) ``` #import<map> int P(std::string s){int i=0,j,q,r=-1;for(;s[i++]*!~r;r=q?r:i)for(auto t=s.substr(j=q=0,i-1)+&s[i];t[j];)q|=t[j]-*(end(t)-++j);return r;} ``` Test code example : ``` std::cout << P("RACERCAR") << '\n'; ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` ~cLkʰcP↔P∧Lhl.∨_1 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7ZJ/vUhuSAR21TAh51LPfJyNF71LEi3vD/fyWgqtSi5MQipf8RAA "Brachylog – Try It Online") (Can be rather slow for inputs that are not almost-palindromes. For faster performance, replace the `~c` with `~c₂`.) ### Explanation ``` ~c "Unconcatenate" the string into a list of strings L Call that list of substrings L kʰ Remove the last character from the first substring c Concatenate the list of strings together again P Call that new string P ↔ Reverse P Assert that the result is still the same (i.e. P is a palindrome) ∧L Also, going back to the list L h Get its first element l Get its length . This is the output of the predicate ∨ Or, if there is no way to satisfy the previous conditions _1 Output -1 instead ``` [Answer] ### Haskell, 107 characters: ``` (x:y)!1=y;(x:y)!n=x:y!(n-1) main=getLine>>= \s->print$head$filter(\n->s!n==reverse(s!n))[1..length s]++[-1] ``` As a function (**85 characters**): ``` (x:y)!1=y;(x:y)!n=x:y!(n-1) f s=head$filter(\n->s!n==reverse(s!n))[1..length s]++[-1] ``` original ungolfed version: ``` f str = case filter cp [1..length str] of x:_ -> x _ -> -1 where cp n = palindrome $ cut n str cut (x:xs) 1 = xs cut (x:xs) n = x : cut xs (n-1) palindrome x = x == reverse x ``` [Answer] ## C# (184 characters) I admit this is not the best language to do code-golfing... ``` using System.Linq;class C{static void Main(string[]a){int i=0,r=-1;while(i<a[0].Length){var x=a[0].Remove(i++,1);if(x==new string(x.Reverse().ToArray()))r=i;}System.Console.Write(r);}} ``` Formatted and commented: ``` using System.Linq; class C { static void Main(string[] a) { int i = 0, r = -1; // try all positions while (i < a[0].Length) { // create a string with the i-th character removed var x = a[0].Remove(i++, 1); // and test if it is a palindrome if (x == new string(x.Reverse().ToArray())) r = i; } Console.Write(r); } } ``` [Answer] # C# (84 Characters) ``` int x=0,o=i.Select(c=>i.Remove(x++,1)).Any(s=>s.Reverse().SequenceEqual(s))?x:-1; ``` LINQpad statement expecting the variable `i` to contain the input string. Output is stored in the `o` variable. [Answer] # Haskell, 80 ``` a%b|b<1=0-1|(\x->x==reverse x)$take(b-1)a++b`drop`a=b|1<2=a%(b-1) f a=a%length a ``` Called like this: ``` λ> f "racercar" 5 ``` [Answer] # [Python 3](https://docs.python.org/3/), 71 bytes ``` def f(s,i=1):n=s[:i-1]+s[i:];return(n==n[::-1])*i-(i>len(s))or f(s,i+1) ``` [Try it online!](https://tio.run/##NYzBCsIwEETv@Yocs9YeigchEn@kFEnrRhdkEzbbg18fW9TTezMwU976zHxq7Y7JJlePFAbwHOroqR@mro7kp4ugrsKOQ@DR@62HA/WOri9kVwGyfKfdAC1t4WaJrUR@oDuDt0WI1SVHXFZ1ANAkLihLFLPLTv3Lj2pq1O0pCpZsFRnV5oISrWSN1RQyc56XqB8 "Python 3 – Try It Online") Returns the 1-indexed character if the operation can be done and `-1` otherwise. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes ``` FirstCase[Range@Tr[1^#],a_/;PalindromeQ@Delete[#,a],-1]& ``` [Try it online!](https://tio.run/##LcexCsIwFEbhvY/RQKeU0rkogYpzlW4hyk@8tYEmws3dxGePik7nOxGyUoQEj7LsyjFwlhGZ7BnpTmZm21@U07h2w4QtpBs/Ip3MgTYSskrD6bZ3TZk4JLGq3S9mXMHwQpyNck1nnlX9eWIPrvXPf35Tvcob "Wolfram Language (Mathematica) – Try It Online") Takes input as a list of characters. For string input, append `@*Characters`. [`PalindromeQ`](https://reference.wolfram.com/language/ref/PalindromeQ.html) was introduced in 2015. The alternative costs [+4 bytes](https://tio.run/##LYqxCsIwEED3fkYPgkJK6SyRg4qzFLcQ5QhXG2g7XA4X8dtjRaf3HryFdOKFNEUqoyvnJFl7yuwHWh@MV/HdDYKle3vYgXMDP1kyI5g9nnhmZQ@Wgm26YMpF0qoemuOI/URCUbcXIZgWX1W9NUskqe3P//pF9S4f). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~180~~ ~~168~~ ~~159~~ ~~157~~ ~~140~~ 139 bytes ``` f(char*s){int j=strlen(s),m=j--/2,p=-1,i=0;for(;p&&i<m;)p=s[i++]^s[j--]&&!++p?s[i]-s[j+1]?s[i-1]-s[j]?p:j--+2:i++:p;return p<0?m+1:p?p:-1;} ``` [Try it online!](https://tio.run/##hY5BDsIgFETXeoraRAJSonRZJD2IYkKRKo3FH6gr49krda31r2bmzSTfsIsx49hic9VhE8nT@SHrZBzCzXocSdHLjrFtWYBkvHByJ9p7wAIQcvteEJDx4ChVp3hINYXQilKoU6ZYSihXk2b841QNVSrRskqLCkSwwyP4DPa7uqe8goQZF69x@qDXzmOSPZcLCMm3OF@fjz4vsqSCNtbokBMivuO/fL6gG2N4o3/i6Wa2Z/uBr@X4Bg "C (gcc) – Try It Online") ~~2~~ ~~16~~ 17 bytes shaved off thanks to ceilingcat! And 3 more bytes since the rules state the minimum length of the input is 2 characters, so don't have to check for empty strings. Ungolfed: ``` f(char *s) { int j = strlen(s); // j = length of input int m = j-- / 2; // m = midpoint of string, // j = index of right character int p = -1; // p = position of extra character // -1 means no extra character found yet // 0 means invalid input int i = 0; // i = index of left character for (; p && i < m; i++) { // loop over the string from both sides, // as long as the input is valid. p = s[i] ^ s[j--] // if (left character != right character && !++p ? // and we didn't remove a character yet*) s[i + 1] - s[j + 1] ? // if (left+1 char != right char) s[i] - s[j] ? // if (left char != right-1 char) p // do nothing, : // else j-- + 2 // remove right char. : // else ++i // remove left char. : // else p; // do nothing, or: // *the input is marked invalid } return p < 0 ? // if (input valid and we didn't remove a character yet) m + 1 // return the midpoint character, : // else p ? // if (we did remove a character) p // return that character, : // else -1; // the input was invalid. } ``` ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 75 ~~90~~ bytes > > -15 bytes thanks to @Shaggy 's conversion into a recursive function, simplification of the array comparison, and replacement of a `map` with a `reduce`. > > > JS might not be the right tool for this job, but i was surprised no one posted a JS answer before. For each character of the word, we test if the removal of this character gives a word that is a palindrome, and we retain the `index +1` of the last character that succeeded (or `-1` if there weren't any). ``` f=(s,r=i=-1)=>s[++i]?f(s,(a=[...s]).splice(i,1)&&a+``==a.reverse()?i+1:r):r ``` [Try it online!](https://tio.run/##bc1NasMwEAXgfU4htAgSkgXuz8Yw8UFCIFN5XNQY20i2SQ6QXaEXaA/Qa/kirhM7gSSd5fvm8T6ww2C9q5uorDIahhxE0B4cRLGEVVgr5TZpPmYCYW2MCRtpQl04S8LpWC6XqLZbADSeOvKBhEydihMvEz8sqMOixYZAuLJuG037mmxDmfYU2qKBfMrluGSrMlQFmaJ6F2JmgEsh5f33kfGE9z@fjEt1rinO@q9fxtX0LhfXPcE4vtmMs9NpFsVM3hrai7GXW7MjXu2ut8MD7vhsz/c20792eJr0cc@jJW/R85O9PtqZ5t7wBw "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 58 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7.25 bytes ``` ẏ⋎:R=T›uJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9RyIsIiIsIuG6j+KLjjpSPVTigLp1SiIsIiIsInJhY2VyY2FyIl0=) Hehe vyncode go brrr [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, ~~266 258 254~~ 238 bytes [(230 bytes with ugly GNU extensions and bugs)](https://tio.run/##hY/BTsMwDIbveQvUaWqCEjfpNmgunHiKeYcyQhepa1CTaYiHJzhlcEWKFPn/f3@2o3vNOYIS0GjTbra7h8euslJbvbbArGYRasXpKWHrfS8/D4IqwVH/VLzGq7B8BWtscYsbNLiD0nRzO8ErQN2gqQhnivPL40VDjW0DLBkG@0Z2B2VXcPei/wg0bdHvOV6B4BoGZhe3qAVUFiCUXVC0c2LlHFpWloTg6snSddSY89wf3bGf2e1PbAjjG0vzZUj@7PzkYji5cXSnEN3k3dmn4UKp/wIfX@E9@TDFLJ@/AQ "sed 4.2.2 – Try It Online") Unfortunally, `sed` needs to be tought how to count; otherwise this could have been much shorter. Anyhow, I think this is quite a clever approach and highly golfed. The idea is to put a `1` in front of the first char (line 1, along with counting helper), then to double the word with an increased number at an increased position (line 3). Then comes some overhead to count past 9 and even more overhead to count past 99. Could be golfed by switching to non-decimal output. Finally, starting from `:3`, all strings are eaten up from the start and from the end, until there is only 1 or no char left. I'm pretty sure this is the shortest way to check for a palindrome. ``` s/.*/0123456789#:-1:1&:/ :1 s/(.)(.).*:([a-z]*)(.*)\1([a-z])([^:]*:)$/&\3\5\4\2\6/ s/([a-z])(9*)#/\10\2#/ :2 s/((.)(.).*)\2#/\1\30/ t2 /[0-9].:$/!b1 s/([a-z]*)([0-9]+)[^:]/\2\1/g :3 s/([0-9])(.)([^:]*)\2:/\1\3:/ t3 s/.*:([-0-9]*).?:.*/\1/ ``` [Try it online!](https://tio.run/##hY9BbsMgEEX33KJyFBkqGGMnaTybrnoK40puSgmSYyKDpaqHLwUn7bYSEpr5f9788fqdm2mJ0YNgUMm62e0PT8e2QC5RbhEISuKhFDQ9wbDsBv7Vs1QxquStomX3ij1DuoGtatRe7VStDpDH7nrLaAFKVqouErDOyi@R5p6SqqmAhJpAV/G2F7iBhzf5R0j71v4jzZsg4SUYgs1qyEJm3VIkHq68FD1kwxqaZxOj4hnTlWk4xnk46dMwk/sfiHHjBwnzYoK9aDtp7856HPXZeT1ZfbHBLMn1n@Hz212DdZOP/OUH "sed – Try It Online") [Answer] # [Julia](https://julialang.org), 72 68 bytes ``` !s=[filter(i->(t=s[1:i-1]s[i+1:end])==reverse(t),1:length(s));-1][1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZAxTsMwFIb3nOI1XWxwIjkNpQS5YmDtCawMJnFaI8tBtgNC4iYsWXoV7tDb8JLAiISX9_T51_fL_jw_D9ao8fLVqqiETABI6lWjfaN8ykCW7KamDGZ-7G03sYwjmgmfT8p4tf0N8WJTFojkhpVTrE7W0NsWbgtcVkHIztioPTHZnkQRJK8M-q6CNNe80q6tqRBev2ofNIkUzVa7YzyRQGme5wyzkk9Op9_ABHh6h4PyzWEIpwq2u_MQu2x3efyz6D8990vJj-uu6z0QwxQF42D6JnznemUAPvbw4o2L1iF5UCFoHwEvMKYSrFgE47jMbw) * -4 bytes: by [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) [Answer] ## Haskell, 118C ``` m s|f s==[]=(-1)|True=f s!!0 f s=[i|i<-[1..length s],r s i==(reverse$r s i)] r s i=let(a,_:b)=splitAt (i-1) s in a++b ``` Ungolfed: ``` fix s |indices s==[] = (-1) |True = indices s!!0 indices s = [i|i<-[1..length s],remove s i==(reverse$remove s i)] remove s i = let (a,_:b) = (splitAt (i-1) s) in a++b ``` ]
[Question] [ Yet another Brainfuck parsing problem, but this time... different. > > You are working in the Infinite Monkeys Incorporated, the company making Brainfuck programs, to solve various interesting problems (by accident, no less - after all, the company makes random programs). However, it appears that your fast Turing machines that only execute Brainfuck have a small and expensive problem with syntax errors - make one, and the computer explodes. It's probably a design flaw, but nobody had bothered to find why it happens. > > > As Turing machines (especially fast ones) are expensive (after all, they have infinity RAM which costs), it would be better to make sure that the program doesn't have any syntax errors before executing the code. Your company is going to run lots of code, so manual verification won't work. Write a program that reads the STDIN for Brainfuck code, and exits with exit status set to anything other than 0 (error) if program has any syntax error (for example, `]` is a syntax error, because there is no matching `[`). Exit with exit status set to 0 if the program is completely fine. > > > Make sure that your program correctly notices mistakes involving `[]`. You wouldn't want another computer to explode, would you? Oh, and make sure it's as short as possible - your boss pays for short programs (because he thinks they are fast, or something). Oh, and you don't have to code in Brainfuck (in fact, you cannot, because Brainfuck doesn't support exit codes) - your code will be ran on normal computer. > > > So, as you can see, your job is to check if Brainfuck program is "valid" (has paired `[]` symbols). Please note that Brainfuck programs can have other characters than `[]`, so don't refuse the program just because it has other commands. Smallest code wins, but probably you would care more about upvotes anyway. [Answer] # Brainfuck 76 bytes ``` >>+[<+++++++++[->---------<]+>-[--[[-]<->]<[<[->-]>[<+]<]>]<[-<+>]+>,]<<[<+] ``` This goes out of it's bonds if square brackets are unbalanced turning the bf interpreter/compiler to fail runtime and some of them have exit codes to reflect that. requires eof=0, wrapping values and finit number of cells In Ubuntu you can use the interpreter `bf` (`sudo apt-get install bf`) ``` % echo '[[[]' | bf -n bf_matching.bf Error: Out of range! Youwanted to '<' below the first cell. To solve, add some '>'s at the beginning, for example. an error occured % echo $? 5 % bf -n bf_matching.bf < bf_matching.bf % echo $? 0 ``` [Answer] # Befunge 98 - ~~26~~ ~~31~~ ~~20~~ 19 chars ``` ~:']-!\'[-!-+:0`j#q ``` Got rid of some massive conditionals. Now the program works as follows: ``` ~: read an input char and duplicate it ']-! push a 1 if the char is the ] char, 0 otherwise \ swap the comparison value for the duplicated input char '[-! push a 1 if the char is the [ char, 0 otherwise - subtract the two comparison values. If the second one is 1, the first is 0, so the result is -1. Else if the second one is 0, the first is 1 and the result is 1. Else, the first and the second are both 0 and the result is 0 + Add the number to the counter (which is 0 if there is none already) :0` test if the counter is positive (that'd mean an invalid program). Pushes a 1 if positive, 0 otherwise. j#q if the counter is positive, then this jumps to the q. Otherwise, it skips the q and continues to the ~ at the beginning of the line. If there are no more chars in the input, then the IP will be sent back to the q. ``` `q` quits the program and pops the top value as an error value. The error value will be ~~-1~~ 1 if there are too many `]`'s, 0 if they are balanced, and ~~positive~~ negative if there are too many `[`'s. If the number is ~~positive~~ negative, then ~~that many~~ the absolute value of that number `]`'s are needed to balance the program. **Edit:** Switched increment and decrement. `[` used to increment the counter and `]` used to decrement it. By switching it, I save 1 char, because for the exit condition, I only have to check if the counter is positive, rather than negative. --- Old version ``` ~:'[-!j;\1+\#;']-!j;1-#;:0\`j#q ``` This code works as follows: ``` ~ read one char of input : duplicate it '[-! push 1 if the character is [, 0 otherwise j jump that number of characters ; skip until next ; \1+\ increment counter similarily for ]. #q when end of input is reached, ~ reflects the IP back. q ends the program with the error value on the stack. ``` **Edit:** realized that this accepted inputs like `][`, now it ends whenever the count gets negative, using ``` :0\`j ``` [Answer] ## GolfScript, 18 chars ``` .{[]`?)},~](`91?./ ``` This code runs successfully with exit code 0 (and prints some garbage to stdout) if the square brackets in the input are balanced. If they are not, it fails with a non-zero exit code and prints an error message to stderr, e.g.: ``` (eval):2:in `/': divided by 0 (ZeroDivisionError) ``` or ``` (eval):1:in `initialize': undefined method `ginspect' for nil:NilClass (NoMethodError) ``` Since the challenge said nothing about output to stdout / stderr, I figure this qualifies. In any case, you can always redirect those to `/dev/null`. ### Explanation: The code `{[]`?)},` strips everything but square brackets from the input, and the `~` evaluates the result as GolfScript code. The tricky part is that unbalanced brackets are perfectly legal in GolfScript (and, indeed, my code includes one!), so we need some other way to make the code crash. The trick I'm using is to leave a copy of the input at the bottom of the stack, collect the entire stack into an array (using the unbalanced `]`) and shift the first element off. At this point, three things can happen: * If the input ended in an unclosed `[`, trying to shift an element off an empty array will crash the interpreter (which, in this case, is exactly what we want!) * If the brackets in the input were balanced, the shifted element will be the original input string. * Otherwise (if the input had an unopened `]` or an unclosed `[`) it will be an array. My original 14-char entry then compared the shifted value with a string, which would crash if it was a nested array. Unfortunately, it turns out that comparing a *flat* (or, in particular, empty) array with a string is also legal in GolfScript, so I had to switch tack. My current submission, instead, uses a very brute-force method to tell arrays from strings: it un-evals them and tries to find the first occurrence of `[` (ASCII code 91), which will be zero if and only if the un-evaled variable was an array. If so, dividing the zero with itself triggers the desired crash. Ps. Two other 18-char solutions are: ``` .{[]`?)},{.}%~](n< ``` and ``` .{[]`?)},~]([n]+n< ``` Alas, I haven't yet found a shorter way to solve the "empty array problem". [Answer] ## J (~~38~~ 35) ``` exit({:+.<./)+/\+/1 _1*'[]'=/1!:1[3 ``` Explanation: * `1!:1[3`: read stdin * `'[]'=/`: create a matrix where the first row is a bitmask of the `[`s in the input, and the second row is the `]`s. * `1 _1*`: multiply the first row by 1 and the second row by -1. * `+/`: sum the columns of the matrix together, giving delta-indentation per character * `+/\`: create a running total of these, giving indentation level at each character * `({:+.<./)`: return the GCD of the final element (`{:`) and the smallest element (`<./`). If all the braces match, both of these should be `0` so this will return `0`. If the braces do not match, it will return a nonzero value. * `exit`: set the exit value to that and exit. [Answer] # ruby (64) ``` exit $<.read.tr('^[]','').tap{|x|0while x.gsub!('[]','')}.empty? ``` previously (68) it was: ``` exit ARGF.read.tr('^[]','').tap{|x| 0 while x.gsub!('[]','')}.empty? ``` Another equivalent solution uses ``` exit $<.read.tr('^[]','').tap{|x|0while x.gsub!('[]','')}.size>0 ``` can't use `size` alone because it would give false negatives (!!!) when the total number of unbalanced brackets is multiple of 256 [Answer] ## Perl, 30 characters Your basic Perl recursive regex to the rescue: ``` perl -0ne 'exit!/^(([^][]|\[(?1)\])*)$/' ``` For those unfamiliar with the command-line arguments used here: `-0` allows one to set the line-ending character for the purposes of file input; using `-0` with no argument sets the line-ending character to EOF. `-n` automatically reads the input (in this case, the entire file) into `$_` beforehand. If the regex matches, it returns a true value, which is negated to 0 for the exit code. Otherwise, the false return value yields an exit code of 1. [Answer] ## bash (tr + sed) - 42 ``` [ -z `tr -Cd []|sed ":a;s/\[\]//g;t a"` ] ``` If you don't mind error messages then you can remove the last space between ``` and `]` to get length 41. [Answer] ## Perl (56 chars) ``` $/=0;$r=qr/[^][]*(\[(??{$r})\])*[^][]*/;<>=~m/^$r$/||die ``` The obvious Perl solution: a recursive regex. Unfortunately it's a rather verbose construct. [Answer] **Haskell (143)** ``` import System.Exit f=exitFailure v c []|c==0=exitSuccess|True=f v c (s:t)|c<0=f|s=='['=v(c+1)t|s==']'=v(c-1)t|True=v c t main=getContents>>=v 0 ``` to jgon: Using 2 guards seems to be more dense than if-then-else. Also, I don't think yours checks that the brackets are in the right order ("][" passes) [Answer] # C, ~~73~~ 64 chars Thanks to suggestions from breadbox (although this probably requires little-endian to work): ``` i;main(c){while(read(0,&c,1)*(i+1))i+=(c==91)-(c==93);return i;} ``` How it works: * implicit int global `i` gets initialized to 0 * `c` becomes an implicit int which gets `argc` (initialized to 1 but we don't care, just as long as the higher bits aren't set) * `read(0,&c,1)` reads a single character into the low byte of c (on little-endian architectures) and returns 0 at EOF; `i+1 != 0` unless the balanced bracket quote goes to -1; multiplying them together works as a (safe) boolean AND that takes one less char than `&&` * `c==91` evaluates to 1 for `'['`, and `c==93` evaluates to 1 for `']'`. (There might be some fiddly bit-fiddling trick that would be smaller but I can't think of anything.) * `return i` exits with status code 0 if it's balanced, non-zero if it isn't. Returning -1 technically violates POSIX but nobody actually cares about that. Previous version: ``` main(i){char c;i=0;while(read(0,&c,1)*(i+1))i+=(c==91)-(c==93);return i;} ``` [Answer] # Turing Machine Code, ~~286~~ 272 bytes Again, I'm using the rule table syntax defined [here.](http://morphett.info/turing/turing.html) ``` 0 * * l 1 1 _ ! r Q 5 _ _ r 5 5 * * * W W [ ! l E W ] ! l T W _ _ l I W * ! r * E ! ! l * E * * * R R _ [ r O R * * l * T ! ! l * T * * * Y Y _ _ r U Y * * l * U [ _ r O U ! ! * halt-r I ! ! l * I _ _ r halt I * * l halt-r O ! ! r Q O _ _ l I O * * r * Q ! ! r * Q * * * W ``` Terminates in state `halt` to accept the input and `halt-r` to reject it. [Answer] # Lua, 56 ``` os.exit(("["..io.read"*a".."]"):match"^%b[]$"and 0 or 1) ``` [Answer] ## [GTB](http://timtechsoftware.com/?page_id=1309 "GTB"), 55 ``` 0→O:0→X[`I@I="[":X+1→X@I="]":X-1→X@X<0:1→O@!!Ig;e]l;e~O ``` Misses `[]` Use `0` to stop. [Answer] ## MATHEMATICA, 88 chars ``` s = "[ [ my crazy code ] [ don't explode please! [] [ :)Ahh) ] [] []]]"; r=StringReplace; StringLength@FixedPoint[r[#,"[]"-> ""]&,r[s,Except@Characters["[]"]-> ""]] ``` [Answer] # Ruby, ~~59~~ 58 Scans for opening and closing bracket, counting `[` as 1 and `]` as -1, and exits if the count drops below 0. ``` b=0 $<.read.scan(/\]|\[/){exit 1if(b+=92-$&.ord)<0} exit b ``` [Answer] # [Hassium](http://HassiumLang.com), 104 Bytes ``` func main(){l=0;r=0;b=input();foreach (c in b){if(c=="[")l++;if(c=="]")r++;}if(!(r==l))exit(1);exit(0);} ``` Full expanded (note doesn't work in online interpreter as input() is disabled) [here](http://HassiumLang.com/Hassium/index.php?code=9cf346041c25db840d8b611b82313988) [Answer] ## Pyth, 25 bytes ``` Ilzv::z"[^[\]]"k"]\[""],[ ``` [Try it online!](https://tio.run/##K6gsyfj/3zOnqszKqkopOi46JjZWKVspNiZaSSlWJ/r//@jYaCACEbGxAA) Python 3 translation: ``` import re z=input() if len(z): print(eval(re.sub("]\[","],[",re.sub("[^[\]]","",z)))) ``` [Answer] # Haskell (~~167~~,159) Did this mostly for fun, if anyone's got any suggestions for how to make it shorter, I'd be glad to hear them tho :) ``` import System.Exit p x y b|b=x|True=y main=getContents>>=(return.all (>=0).scanl (\v->p (v-1) (v+1).(==']')) 0.filter (`elem`"[]"))>>=p exitSuccess exitFailure ``` **Edit:** Fixed an issue pointed out to me in the comments (added 11 bytes). **Edit 2:** Created auxiliary function for testing predicates using guards inspired by user13350, removing 8 bytes. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~14~~ 11 [characters](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╬Äτ↔EªÉs «Ü ``` [Run and debug it](https://staxlang.xyz/#p=ce8ee71d45a6907320ae9a&i=[+[+my+crazy+code+]+[+don%27t+explode+please%21+[]+[+%3A%29Ahh%29+]++[]+[]]]%0A][&a=1&m=2) *Credit to @recursive for -3 bytes.* ASCII equivalent: ``` .[]Y|&{yz|egp! ``` Remove all characters except `[]`, then remove `[]` until the string no longer changes. Return `1` if the final string is empty. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ‛[]↔øβ¬[°* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJtbXeKGlMO4zrLCrFvCsCoiLCIiLCJhYltjY2RdXSJd) The joys of having a balanced-bracket digraph. ## Explained ``` ‛[]↔øβ¬[°* ‛[]↔ # remove all non "[]" from the input øβ¬ # are the brackets unbalanced? [°* # if so, multiply the input by the imaginary number `i`. Obviously you can't multiply a string by an imaginary number in python, so this errors. ``` ]
[Question] [ Create a program which sums all integers found in a string which is set as a variable in the program (thus, the program doesn't have to handle any input). The integer numbers are separated by non-numericals (anything but 0, 1, 2, 3, ..., 9). Examples: * `e7rde f ,fe 43 jfj 54f4sD` = 7+43+54+4=108 * `5` = 5 * `64 545,5445-32JIFk0ddk` = 64+545+5445+32+0=6086 * `0ab0` = 0+0 = 0 Extra notes: * Unicode support is **not** necessary, but allowed * `-n` (where `n` is an integer) is **not** counted as a negative `n`, but as a hyphen followed by `n`. The answer may be printed on the screen (but not required). Shortest answer (in characters) win. [Answer] ## Ruby 1.9, 21 characters ``` eval a.scan(/\d+/)*?+ ``` To print the solution to stdout, 2 additional characters are required: ``` p eval a.scan(/\d+/)*?+ ``` And to read from stdin instead of using a predefined variable, another 3 characters have to be used: ``` p eval gets.scan(/\d+/)*?+ ``` For Ruby 1.8, replace `?+` with `"+"` to get a working solution in 22 characters. [Answer] ## Perl, 15 Input in `$_`, sum in `$c`: ``` s/\d+/$c+=$&/ge ``` [Answer] # Ruby - 36 34 chars ``` s.scan(/\d+/).map(&:to_i).reduce:+ ``` 36 chars if you want the result printed. ``` p s.scan(/\d+/).map(&:to_i).reduce:+ ``` Assumes the input is present as a string in s. [Answer] ## Python (60) ``` import re;print sum(map(int,filter(len,re.split(r'\D',s)))) ``` [Answer] # JavaScript (ES6), 30 ``` c=0,s.replace(/\d+/g,d=>c+=+d) ``` Annotated version: ``` // Store the sum. c=0, // Process every number found in the `s`. s.replace(/\d+/g, // Convert the number into an integer. // Add it to the sum. d => c += +d ) ``` [Answer] ## Windows PowerShell, 23 ~~25~~ ~~29~~ ~~31~~ With output. ``` $x-replace'\D','+0'|iex ``` In fact, without output is exactly the same, you'd just pipe it somewhere else where it's needed. [Answer] # gs2, 4 bytes ``` W#Θd ``` Encoded in [CP437](https://en.wikipedia.org/wiki/Code_page_437); the third byte is `E9`. `W` reads all numbers `/-?\d+/` from a string, `#Θ` maps absolute value, `d` sums. *(gs2, too, is newer than this challenge, but its `read-nums` command is a total coincidence.)* [Answer] # JavaScript [31 bytes] ``` eval(s.match(/\d+/g).join('+')) ``` [Answer] ## J - 40 38 characters Lazy version. Requires the string library. ``` +/".(,' ',.~a.-.'0123456789')charsub y ``` [Answer] ## Java out of the contest ;) ``` public static long sum(String s) { long sum = 0; String p = ""; char[] ch = s.toCharArray(); for (int i = 0; i < ch.length; i++) { boolean c = false; if (Character.isDigit(ch[i])) { if (i + 1 < ch.length) { if (Character.isDigit(ch[i + 1])) { p += ch[i]; c = true; } } if (!c) { p += ch[i]; sum += Integer.valueOf(p); p = ""; c = false; } } } return sum; } ``` [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth), ~~29~~ 21 bytes *(Disclaimer: Labyrinth is newer than this challenge.)* Also, Labyrinth doesn't have variables, so I went with a normal input/output program. ``` )_"+` ( "?" ";;,;;(!@ ``` This was fairly simple because of the way Labyrinth's input commands work. `?` tries to read a signed integer from STDIN and stops at the first non-digit. If it can't read an integer (because the next character is a `-` not followed by a digit, or any other non-digit, or we've reached EOF), it will return `0` instead. `,` on the other hand reads any subsequent byte and pushes the byte value. If this one is called at EOF it will return `-1` instead. So here's some pseudocode for the solution: ``` running total = 0 while(true) while(true) try reading a non-zero integer N with ? if(N < 0) running total -= N else if(N > 0) running total += N else break // We've either read a zero or hit a something that isn't a number try reading a character with , if(that returned -1) break print running total ``` Dealing with negative numbers correctly complicates this solution quite a lot. If it weren't for those, I'd have this 8-byte solution: ``` ?+ ;,;!@ ``` [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=sum -pF/\D+/`, 8 bytes ``` $_=sum@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ra4NNfB7f9/MxMFUxNTHVMTE1NdYyMvT7dsg5SU7H/5BSWZ@XnF/3V9fTKLS6ysQksyc0Ba/usW/Nd1049x0dYHAA "Perl 5 – Try It Online") [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œþOà ``` [Try it online](https://tio.run/##MzBNTDJM/f9f7@jkw/v8Dy/4/z/VvCjF0ChVwdAwzQAA) or [verify a few more test cases](https://tio.run/##MzBNTDJM/V9TVmmvpPCobZKCkn3lf72jkw/v8z@84L/O/1TzohRDo1QFQ8M0Ay5TLoPEJAMuMxMFUxNTHVMTE1NdYyMvAA). (Times out for the larger test cases due to the `.œ` builtin.) **Explanation:** ``` .œ # Get all partitions of the (implicit) input-string, # which are all possible ways of dividing the input-strings into substrings þ # Only leave the items consisting of digits for each partition # (in the new version of 05AB1E, an explicit `€` is required) O # Sum each inner list à # Pop and push its maximum # (after which the result is output implicitly) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 24 bytes ``` dc<<<`tr -c 0-9 +<<<$s`p ``` [Try it online!](https://tio.run/##JYvNCoJAHMTvPcUgwh5qYdsPTbBOEdRTuO4HpqDhdvDtt790mPnNMExv05DjsiLhPYOFevUBETjFAK0wxhFGR53uDMyQKk3dnIzWhiv5ej4m4f1Eg7C9INia7NLYPSbfnGXycc@q138YR1RbJQlaqm1zUiRv2QHwCxkQ3LCAzyjKhOsNRfaubdvuu4I7CN7gSLVM3SfvlznkHw "Bash – Try It Online") Input in the variable `s`, output on `stdout`. [Answer] # [Pip](https://github.com/dloscutoff/pip), 7 bytes ``` $+a@+XD ``` [Try it online!](https://tio.run/##K8gs@P9fRTvRQTvC5f///6nmRSmpCmkKCjppqQomxgpZaVkKpiZpJsUu/3ULAA "Pip – Try It Online") Regexes all numbers to a list and sums them. +1 byte fix from DLosc. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes ``` `\D`ṡ⌊ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiYFxcRGDhuaHijIoiLCIiLCJlN3JkZSBmICAsZmUgNDMgamZqIDU0ZjRzRCJd) ~~Ugh we really need to make `⌊` play nice with strings not containing numbers in v2.6; this would be 6 bytes if it didn't error.~~ 2.6 done did make the change lol. ## Explained ``` `\D`ṡ⌊ `\D` # The string "\D" (a regex that looks for non-digits) ṡ # Split the input on this regex ⌊ # Convert each to a number # Output the sum with the `s` flag ``` [Answer] # PHP - 37 Without printing; ``` <?array_sum(@split("[^0-9]+",`cat`)); ``` With printing (38): ``` <?=array_sum(@split("[^0-9]+",`cat`)); ``` [Answer] ## Perl, 16 chars ``` s/\d+/$r+=$&/ge; ``` Takes input in `$_`, output goes on `$r`. Last semicolon is superfluous, but it will probably be needed when the program does more things. Add `say$r` for output. [Answer] ## R, 30 ``` sum(scan(t=gsub("\\D"," ",x))) ``` Here, `x` is the name of the variable. Example: ``` > x <- "e7rde f ,fe 43 jfj 54f4sD" > sum(scan(t=gsub("\\D"," ",x))) Read 4 items [1] 108 ``` [Answer] # J - 23 char Not a winner, but we get to see a fairly rare primitive in action. ``` +/".(,_=_"."0 y)}y,:' ' ``` Explained: * `_"."0 y` - For each character in the input string `y`, try to read it in as a number. If you can't, use the default value `_` (infinity) instead. * `,_=` - Check each result for equality to `_`, and then run the final array of 0s and 1s into a vector. (`"."0` always adds one too many dimensions to the result, so we correct for that here.) * `y,:' '` - Add a row of spaces beneath the input string. * `}` - Used as it is here, `}` is called *Item Amend*, and it uses the list of 0s and 1s on the left as indices to select the row to draw from in the right argument. So what happens is, for each column in the right side, we take the original character if it could be read in as a number, and otherwise we take the space beneath it. Hence, we cover up any non-numeric characters with spaces. * `+/".` - Now convert this entire string into an list of numbers, and sum them. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` {~cịˢ+}ᶠ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv7ou@eHu7tOLtGsfblvwqKfz//9oJVMlHSWDxCQDIGVqkmZS7AJkmJjqGht5eQJZOfnlufHmSrEA "Brachylog – Try It Online") It's... inefficient... so I've neglected to test the longer cases. It appears to work, though. Takes input through the input variable, which just so happens to be the usual form of input anyhow. ``` ⌉ The output is the largest { }ᶠ possible + sum of ịˢ integers the string representations of which are some elements of ~c a partition of the input. ``` `⌉` ensures that numbers are maximally matched as well as never negative, since splitting a number up, invalidating a number, or turning it negative will never result in a larger sum. [Answer] # C 96 **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter** ``` t;main(i,v)int**v;{for(char*q,*s=v[1];*s;q>s?t+=abs(i),s=q:s++)i=strtol(s,&q,0);printf("%d",t);} ``` [Try it online!](https://tio.run/##DcxLCsIwEADQq4SCks8IihHBIbrxFuIipo2maGsyQzbi2aPvAC@s7iG0xvjyaZIJqkoTa13xE@ciw8MXnUGTq5fNFTVhPtKJjfM3kkkBuXwgY1RyxIXnpyRYZlgrfJd/E2W36Dtghd/W2rAv/SCiEBAHYbdijKPY2Wjp/AM "C (gcc) – Try It Online") An earlier 85 byte version that is cheating a bit by hardcoding the string inside the program: ``` t=0;main(i){for(char*q,*s;i=strtol(s,&q,0),*s;q>s?t+=abs(i),s=q:s++);printf("%d",t);} ``` To actually use the 85 byte program you need to assign the variable like so: ``` t=0;main(i){for(char*q,*s="text";i=strtol(s,&q,0),*s;q>s?t+=abs(i),s=q:s++);printf("%d",t);} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` µÖ▀o)♫⌐ƒ ``` [Run and debug it](https://staxlang.xyz/#p=e699df6f290ea99f&i=%22e7rde+f++,fe+43+jfj+54f4sD%22%0A%225%22%0A%2264+545,5445-32JIFk0ddk%22%0A%220ab0%22&a=1&m=2) Finds all substrings matching `\d+`, then `eval` and sum. [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 38 bytes ``` s=>{n=0forv ins::gmatch"\\d+"n-=-v[0]} ``` ## Explained ``` s=>{ } $# A function taking argument "s" n=0 $# Preset n to 0 s::gmatch"\\d+" $# An iterator function which finds all groups of digits in a string forv in $# Iterate through, setting v to the match n-= $# Subtract n by -v[0] $# The negative of the whole match, which implicitely numberfies it. $# Conveniently implcit return from last statement in the function. ``` [Try it online!](https://tio.run/##TYvdCoIwGECv8yk@BoKSgj9bgTCvuuoVVNBsX2k0y00hxGdff2DdHQ7n4CAvD4PcKJ5OkgfY9SM0UiXJ6Vrp@kzy/Lgm0uf@mAXFbHCQtW46CVoo7dSVEu5krW59IzU4ZUbsO7Hftsg1TyHDb1KUrjVbn4WIbX8UgAAeCqAxtNgCo0jVjrh/SRgJCEMMFskWCqrDT2/o62Yeo5T5cbQnrnkC "Funky – Try It Online") [Answer] ## Actually, 14 bytes ``` 9u▀8╙r♂┌-@s♂≈Σ ``` [Try it online!](http://actually.tryitonline.net/#code=OXXiloA44pWZcuKZguKUjC1Ac-KZguKJiM6j&input=ImU3cmRlIGYgICxmZSA0MyBqZmogNTRmNHNEIg) This program supports the CP437 code page for input. Explanation: ``` 9u▀8╙r♂┌-@s♂≈Σ 9u▀ base 10 digits (0-9) 8╙r♂┌ all characters in CP437 (map(ord_cp437, range(2**8))) - set difference @s split input on any value in the resulting list ♂≈Σ convert to ints and sum ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` q\D ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LXg&code=cVxE&input=ImU3cmRlIGYgICxmZSA0MyBqZmogNTRmNHNEIg) [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ṁiġ√ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxswjCx91zPr//3@qeVFKqkKagoJOWqqCibFCVlqWgqlJmkmxCwA "Husk – Try It Online") # Explanation ``` ṁiġ√ ġ√ group on isalpha ṁ sum i the first integer in each string ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-n`, 26 bytes ``` p eval"#$_ 0".gsub /\D/,?+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6eUuyCpaUlaboWuwoUUssSc5SUVeIVDJT00otLkxT0Y1z0dey1IQqg6hbctEg1L0pJVUhTUNBJS1UwMVbISstSMDVJMyl24TLlMjMBsk11TE1MTHWNjbw83bINUlKyuQwSkwwgBgAA) Appends `0` to the input, replaces each non-digit with `+`, then evals. [Answer] # [K4](https://kx.com/download/), ~~21~~ 14 bytes **Solution:** ``` +/. .Q.n .Q.n? ``` **Explanation:** With thanks to @cillianreilly - I didn't expect a string of numbers to be tokenised with `value`. ``` +/. .Q.n .Q.n? / the solution .Q.n? / lookup right in the string "0123456789" .Q.n / index back into "0123456789" . / 'value', tokenises string into integers +/ / sum up ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes ``` S`\D .+ $* . ``` [Try it online.](https://tio.run/##K0otycxL/K@q4Z7wPzghxoVLT5tLRYtL7///VPOilFSFNAUFnbRUBRNjhay0LAVTkzSTYhcuUy4zEyDbVMfUxMRU19jIy9Mt2yAlJZvLIDHJAAA) **Explanation:** Split on non-digit characters, putting each number on its own separated line: ``` S`\D ``` Convert each number to unary, and implicitly remove the newlines: ``` .+ $* ``` Convert it from unary back to an integer, which is output implicitly as result: ``` . ``` ]
[Question] [ # Average color of an image Scientists have been able to determine the average [color](https://en.wikipedia.org/wiki/Cosmic_latte) of the universe but in how many bytes can we find the average color on an image? ### Your task Your input will be a single image which you will need to find the average of the colors in the image and output a hex color-string (`#??????`). The image can be any of the following formats * JPEG/JFIF + JPEG 2000 * TIFF * GIF * BMP * PNG * PNM + PPM The input can also be taken as a URL/URI to the image. Build-in functions which calculate averages or sample the image at once such as [`ImageMeasurements`](http://reference.wolfram.com/language/ref/ImageMeasurements.html) are not allowed. ### Examples Results will differ slightly depending on how you calculate the average and which color models you use. I've added RGB and LCH (HSV) values for the images below. ![Sample 1](https://i.stack.imgur.com/dkShg.jpg) output: `#53715F` RGB, may also be `#3B7D3D` LCH (HSV) --- ![Sample 2](https://i.stack.imgur.com/V5VAR.jpg) output: `#8B7D41` RGB, `#96753C` LCH (HSV) [Answer] # Bash, 46 bytes ImageMagick scales image to one pixel which contains average of the colors in the image then outputs it as text. ``` convert $1 -scale 1x1\! txt:-|egrep -o '#\w+' ``` [Answer] # Pyth - 23 22 19 18 16 bytes Transposes to get all channels, then sums, divides, and hexifies each. Finishes by concatenating and prepending a `#`. ``` +\#sm.H/sdldCs'z ``` Takes an image file name (any type) from stdin and outputs to stdout. **VERY SLOW**. ``` + String concat \# "#" s String concat all channels m Map .H Hex string / ld Divided by length of channel sd Sum of channel C Transpose to separate into channels s Concatenate all rows 'z Read image with filename input ``` ## Sample run ``` >>>pyth avg.pyth V5VAR.jpg #8b7d41 ``` [Answer] # MATLAB - 68 bytes The image is read in with [`imread`](http://www.mathworks.com/help/matlab/ref/imread.html) combined with [`uigetfile`](http://www.mathworks.com/help/matlab/ref/uigetfile.html) to open up a GUI to choose the image you want to load in. The assumption with this code is that all images are RGB, and to calculate the average colour, we sum over each channel individually then divide by as many elements as there are in one channel, which is the total number of pixels in the RGB image ([`numel`](http://www.mathworks.com/help/matlab/ref/numel.html)`(I)`) divided by 3. Because the average can possibly generate floating point values, a call to [`fix`](http://www.mathworks.com/help/matlab/ref/fix.html) is required to round the number down towards zero. [`sprintf`](http://www.mathworks.com/help/matlab/ref/sprintf.html) combined with the hexadecimal formatting string (`%x`) is used to print out each integer value in the average into its hex equivalent. However, the `02` is there to ensure that an extra 0 is padded to the left should the average value for any channel be less than 16\*. ``` I=imread(uigetfile); ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))] ``` # Sample Runs The nice thing about `imread` is that you can read in images directly from URLs. As a reproducible example, let's assume you have downloaded the images on your computer and have run the above code... but for demonstration, I'll read the images directly from Code Golf: ## First Image ``` >> I=imread('https://i.stack.imgur.com/dkShg.jpg'); >> ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))] ans = #53715f ``` ## Second Image ``` >> I=imread('https://i.stack.imgur.com/V5VAR.jpg'); >> ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))] ans = #8b7d41 ``` \*Note: This was a collaborative effort made by StackOverflow users on the [MATLAB and Octave chat room](http://chat.stackoverflow.com/rooms/81987/matlab-and-octave). [Answer] # CJam, 27 bytes ``` '#[q~]5>3/_:.+\,f/"%02X"fe% ``` This read a PPM image from STDIN. CJam has no built-in image processing, so this code expects an ASCII Portable PixMap (magic number P3) with full 24-bit palette (maximum value 255) and no comments. ### Test run ``` $ cjam avg.cjam < dkShg.ppm #53715F ``` ### How it works ``` '# e# Push that character. [q~] e# Evaluate the input and collect the results in an array. 5> e# Discard the first first results (Pi, 3, width, height, range). 3/ e# Split into chunks of length 3 (RGB). _:.+ e# Push a copy and add across the columns (RGB). \,f/ e# Divide each sum by the length of the array (number of pixels). "%02X" e# Push that format string (hexadecimal integer, zero-pad to two digits). fe% e# Format each integer, using the format string. ``` [Answer] ## HTML5 + JavaScript (ES6), 335 bytes This is not going to win but I had fun doing it anyways. Uses the HTML5 [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). Input is a URL of a [CORS-enabled image](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image). ``` f=(u,i=new Image)=>{i.crossOrigin='';i.src=u;i.onload=e=>{x=(c=document.createElement('canvas')).getContext('2d');a=w=c.width=i.width;a*=h=c.height=i.height;x.drawImage(i,0,0);for(d=x.getImageData(m=0,0,w,h).data,r=[0,0,0];m<d.length;m+=4){r[0]+=d[m];r[1]+=d[m+1];r[2]+=d[m+2]}console.log('#'+r.map(v=>(~~(v/a)).toString(16)).join``)}} ``` ### Demo As it is ES6, it currently only works in Firefox and Edge. ``` f = (u,i = new Image) => { i.crossOrigin = ''; i.src = u; i.onload = e => { x = (c = document.createElement('canvas')).getContext('2d'); a = w = c.width = i.width; a *= h = c.height = i.height; x.drawImage(i, 0, 0); for (d = x.getImageData(m = 0, 0, w, h).data, r = [0, 0, 0]; m < d.length; m += 4) { r[0] += d[m] r[1] += d[m + 1]; r[2] += d[m + 2]; } console.log('#' + r.map(v => (~~(v/a)).toString(16)).join``) } } // Snippet stuff console.log = x => document.body.innerHTML += x + '<br>'; f('http://crossorigin.me/https://i.stack.imgur.com/dkShg.jpg'); f('http://crossorigin.me/https://i.stack.imgur.com/V5VAR.jpg'); ``` [Answer] # Python [3] + SciPy, 144 133 121 Loads pixel data, sums for each channel, divides by size\*, formats. Values are rounded towards zero. \*size = width \* height \* channels, thus multiplied by 3 ``` from scipy import misc,sum i=misc.imread(input()) print('#'+(3*'{:2x}').format(*sum(i.astype(int),axis=(0,1))*3//i.size)) ``` [Answer] # R, 90 bytes ``` rgb(matrix(apply(png::readPNG(scan(,"")),3,function(x)sum(x*255)%/%length(x)),nc=3),m=255) ``` Path to PNG file is read from STDIN. Package `png` needs to be installed. Step-by-step: ``` #Reads path from stdin and feeds it to function readPNG from package png p = png::readPNG(scan(,"")) #The result is a 3d matrix (1 layer for each color channel) filled with [0,1] values #So next step, we compute the mean on each layer using apply(X,3,FUN) #after moving the value to range [0,255] and keeping it as an integer. a = apply(p,3,function(x)sum(x*255)%/%length(x)) #The result is then moved to a matrix of 3 columns: m = matrix(a, nc=3) #Which we feed to function rgb, while specifying that we're working on range [0,255] rgb(m, m=255) # Example: rgb(matrix(apply(png::readPNG(scan(,"")),3,function(x)sum(x*255)%/%length(x)),nc=3),m=255) # 1: ~/Desktop/dkShg.png # 2: # Read 1 item # [1] "#53715F" ``` [Answer] # C, 259 Bytes Takes a PPM file **with no comments**. ``` double*f,r,g,b;x,y,z,i;char*s="%d %d %d";main(a,_){(a-2)?(feof(f)?0:(fscanf(f,s,&x,&y,&z),r+=(x-r)/i,g+=(y-g)/i,b+=(z-b)/i++,main(0,0))):(f=fopen(((char**)_)[1],"r"),fscanf(f,"%*s%*d%*d%*d"),r=g=b=0.,i=1,main(0,0),printf(s,(int)r,(int)g,(int)b),fclose(f));} ``` ## Process Initial code: ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *f = fopen(argv[1],"r"); int w,h,d,x,y,z,i; double r,g,b; fscanf(f,"%*s %d %d %d",&w,&h,&d);//get width, height, depth, ignore P6 r = g = b = 0.0; //zero r, g, and b totals for (i=1; i<=w*h; ++i) { fscanf(f,"%d %d %d",&x,&y,&z);//get next pixel r+=(x-r)/i;//update averages g+=(y-g)/i; b+=(z-b)/i; } printf("%d %d %d",(int)r,(int)g,(int)b);//print result fclose(f); return 0; } ``` Trim variables and remove loop: ``` double r,g,b; FILE *f; int i; int main(int argc, char *argv[]) { if (argc==2) { // {./me} {file.ppm} f = fopen(argv[1],"r"); fscanf(f,"%*s%*d%*d%*d");//drop info r = g = b = 0.0; i = 1; main(0,0);//begin load loop printf("%d %d %d",(int)r,(int)g,(int)b); fclose(f) } else { if (feof(f)) return 0; fscanf(f,"%d%d%d",&x,&y,&z); r+=(x-r)/i; g+=(y-g)/i; b+=(z-b)/i; i++; main(0,0); } return 0; } ``` From there I combined the various statements into a single return statement. Removed it and any other extraneous type info, renamed variables, and cut the whitespace. [Answer] # Cobra - 371 ``` @ref 'System.Numerics' use System.Drawing use System.Numerics class P def main i,d=Bitmap(Console.readLine?''),BigInteger r,g,b,c=d(),d(),d(),d() for x in i.width,for y in i.height,r,g,b,c=for n in 4 get BigInteger.add([r,g,b,c][n],d([(p=i.getPixel(x,y)).r,p.g,p.b,1][n])) print'#'+(for k in[r,g,b]get Convert.toString(BigInteger.divide(k,c)to int,16)).join('') ``` [Answer] # Java, ~~449~~ ~~447~~ ~~446~~ ~~430~~ 426 bytes ``` import java.awt.*;interface A{static void main(String[]a)throws Exception{java.awt.image.BufferedImage i=javax.imageio.ImageIO.read(new java.io.File(new java.util.Scanner(System.in).nextLine()));int r=0,g=0,b=0,k=0,x,y;for(x=0;x<i.getWidth();x++)for(y=0;y<i.getHeight();k++){Color c=new Color(i.getRGB(x,y++));r+=c.getRed();g+=c.getGreen();b+=c.getBlue();}System.out.printf("#%06X",0xFFFFFF&new Color(r/k,g/k,b/k).getRGB());}} ``` Thanks to [this answer](https://stackoverflow.com/a/6540378) over on stack overflow for the `String.format` trick. ]
[Question] [ A [marquee](https://en.wikipedia.org/wiki/Marquee_(structure)) is a low-tech board that allows customizable letters. For example, here is a marquee: ``` SALE ON SNEAKERS ``` However, someone might come along and vandalize it by removing letters to send a different message: ``` S N AKE ``` Given two non-empty string inputs, an original message and a new message, determine whether the new message can be created by removing characters from the original message. Spaces left by removal can be compressed, as above, or left in, as in `the` becoming `t e` by removing the `h`. Both messages will only contain letters and spaces, case is up to you. # Test Cases ``` "the", "the" -> true "the", "t e" -> true "the", "te" -> true "te", "t e" -> false "then i walked", "the" -> true "then i walked", "niald" -> true "abcde", "abj" -> false "a b c d e", "abcde" -> true "y today", "yt" -> true "sale on sneakers", "snake" -> true "today", "toad" -> false "today", "tyy" -> false "the sale on sneakers", "t e snake" -> true "this is a sign", "th s i a s n" -> true "the sale on sneakers", "the salon sneakers" -> true "the sale on sneakers", "the sal on sneakers" -> true "a b c", "abc" -> true "a bc", "a b c" -> false "a b c", "a c" -> true "a b c", "a c" -> false "the", " the" -> false "the", " h " -> true "the", "h" -> true ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` {|∧Ṣ}ᵐ⊇ ``` [Try it online!](https://tio.run/##jZBBTsMwEEWv8uV1YcEB4CBVFxPbbUItR4qNIit0U6S2sOIMbNiy6aK9TXKRYMcphLQCLEueeX/87ZmkIJ46lS9u2qpkuLoFK@@qZvPRrJ/q/a7ZvTNbPMhr9hjCOSnj41V9fF7V@9e2CrQ@vIWkedm27XTKbCrZBN0xm@A7xyg/pWeqRoaS1FKKsc9PRWekRNQo4aLzoeS@J0jAIdDTIHfcweaCXKDORmRISeQaRktaysIEzWgf9u@e6m1OYoyc@/ocLvn4vjD0SjMDvwkmW@jYHjxBIID@wyzyIf1PPXB2gwA/H4D30xnQiDqZXypGXL9pQZx9Ag "Brachylog – Try It Online") I should not be surprised to learn that it's considerably faster if I put the `⊇` at the end. Takes the original marquee through the input and the target through the output. ``` { }ᵐ The input variable, with each element | possibly ∧Ṣ replaced by a space, ⊇ has the output variable as a subsequence. ``` Can also go the other way around, for another two bytes: [`{|Ṣ∧l₁}ᵐ⊆`](https://tio.run/##jZAxTsMwFIav8stzYeAAcJCqw4ttmlDLkeKgyEo7UKSoMDFwAhZWlg5wm/giwY5TCGkFRJby3ve9/LGdFMRTq/LlRVdXDGeXYNVV7Zpn17y57X2737ndKyuLW3nO1qG8JmV8vWk/Hjbt/qmr1@37ixfKbe8CcI9N183nrEwlm6F/LWb47jHpD@2R1chQkVpJMc35aXRGSkRHCRd9DiU3A0ECDoGBBt1zizIXZAO1ZUSGlESuYbSklSxMcEb7cvjvYb7MSUyRtV@bw6kcfy6Ms9LMwC@CyZY6Hg@eIBBA/xEW@Zj@Zx44@oIAfz8AH25nRCPqNT81jPj85oJcfAI) [Answer] # [J](http://jsoftware.com/), 25 bytes ``` rxin~[:,'.*',"#:rplc&' .' ``` [Try it online!](https://tio.run/##dZA/C8IwEMX3foqHgkGpoa6FToKTk6vTtUnpn5BIG9AsfvVYWyq1tMOR4/3eveNS@Q1nOZIYDCEixF0dOc6368U3r1K/73HI@IGFm23cPFS2Y@DM74NAZoXBCQmYLSRDPrxLMpblUY16dc2rUeJJqpZiZcfMoEtSYppMaSaGcEqr6SwhRQaBEX5tE@xgjSDXQ2enpCUlYTRaLamWTdtbWt31fxf9pq0hsUKcm12DxfDuWzAs8B8 "J – Try It Online") *Note: TIO link not working because it's an older version of J, but this works locally for me on J901* * `rxin~ ...` The whole verb is dyadic J hook, asking if the right argument, after being transformed by the `...` phrase, is a regex match in the left argument. * `rplc&' .'` The transformation of the right arg (the leftover marquee letters) first replaces all spaces with a `.`, since a space has to match something. * `[:,'.*',"#:` This phrase simply inserts `.*` between each of the letters, so that we match "removed and collapsed letters" too. It works by zipping `,.` the string `'.*'` with each character of the right arg, and then flattening the result `[:,`. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~50~~ 46 bytes ``` lambda a,b:''in[b:=b[b[:1]in' '+c:]for c in a] ``` [Try it online!](https://tio.run/##jVHdToMwGL3nKU52U4jTZPHGkOCLzF18/UHqukJo58LTYwtz0omJpEnb85d@h27wTWufX7p@rKu30dCJSwJtecmYtnteVnzP9@XuoC0DexDloW57CGgLOoyXRhuFXZmFe7dFe/Ydqng@@7x4cp3RPmd4fAUrshAKHlj1SSYPkoBc9fNWgfn@rFiGrtfW53UeDUUkoqAYN75Rmy2mLWZGdXYDsQYmWKKrybhZaKFxIXNUcjU8pa0mIxcC4kJOucQ/lrkURhWQuHJR9GMa4FtJQ6QGv8AdhTJbC2cVHVXvosDZcFy@6NvpW5LJJDdiGO4mxFpwKAK/whvtEBbB6Xc714GAICKATZtZj53xJfpvE7BuIyDUCYhrmffUjE8akf6EpQ/zJ/4MRqKYMr4A "Python 3.8 – Try It Online") The code is simply a modification of [@xnor's answer](https://codegolf.stackexchange.com/a/180287/88546) to a similar challenge: [Is string X a subsequence of string Y?](https://codegolf.stackexchange.com/q/5529/88546) [Answer] # [Scala](http://www.scala-lang.org/), 54 bytes ``` _./:(Set(""))(for(p<-_;c=_;q<-Seq(""," ",c))yield p+q) ``` [Try it online!](https://tio.run/##jZPNbtswEITvfoqBTiQsq/ckMtAeChRoTj72x1hRlM2EIWWSbiMEeXaXlGxHSlWghAAtZnY/iqulF6TpZKsHKQLuSRnI5yBN7fGxbfGyAH6RRnODTXDK7FCuR9Ena7Ukg/K0LT7csI0MLMs4Z411rL1bbW9Fub093K028hCNPEOWC847JXWNdnngpyyusJdZjv6F1RrBHeXiKmJOnGiTvIa0HxINFH6TfpT1LHxqG0W6HiVQJeqeS9XDmEuoIFDj7KWkt6IOwdbUJasLI92TlrAG3kh6lM6nBG9iOP6iS2WwVE9OcjW67t0JMQeOjcBf8L3yiA/Bq50Z2oGoICmAmXZmHjvoY/W/i4D5MgJiOwFxbuZ7a9D7HDH9CeM6DEv8E4xJRs@IQ1f4Vqs4rd9Nxos4rpLEHi@xHeX6PPJO7uQzSqQRZd9@Zj@WPPEuYYJd4ohz56qNfZLsq/KBUY4qh@M8MnpW0ShTf1bOh3sKYv/FMM@LJ2rZtvDHaufssfX8urnvt8YSDSPOqmS08doFbVhvRmjSyHvpwkh6Xbye/gA "Scala – Try It Online") (The output says `true` when a test passes, it prints `false` and throws an exception otherwise). Times out for the later inputs, but appears to work otherwise. Input is curried. First it takes the original message, and returns a `Set[String]` containing possible messages. However, the `Set` also acts like a `String => Boolean`, so it accepts the new message as its second input. ``` _./:( //Fold over original message Set("") //Accumulator will eventually hold all possible messages )( //Cartesian-product-ish for comprehension for( p <- _ //For every possible message p already in the accumulator c = _ //Current character q <- Seq( //Sequence of possible cases: "", //Delete the character, don't keep a space " ", //Delete the character, leave a space c //Keep the character ) ) yield p + q //Add each case q to p ) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~26~~ 23 bytes ``` FreeQ[#|" "|___?h&/@#]& ``` [Try it online!](https://tio.run/##jZBfa8MgFMXf@ykOEcIGLYO9bwsM9rzRxxDCjdrFNTUQhSH989Uzo9mWZqVMRLy/czx63ZGt5Y6s4tRvHvqXTsq3nB0SJIeyLJ/q9C5jRdq/dkrbnK0ebzY5K3J2X6S3WfZcU0fcys4E12nNSZ/2i33iM5NlWI/L3xLn5Xc11zQUPqnZSjHLOBO0okZEiSouhhCqPkaAChwCEQ5iwA62FeQ8dDYSQ41Eq2G0pK1vw0tG@9145ei2LYkZce7nVbgQ4tvBNKhWBn4SjHrXoSt4gAEA@npUxFP4Dzvw5wAB/lsAHj9lAgMJIr9gRRxXpEFbHPsv "Wolfram Language (Mathematica) – Try It Online") Input two lists of characters, curried, as `f[original][new]`. Returns `False` if the target can be reached, and `True` if it cannot. Quite slow. Normally `___` matches any sequence of zero or more elements. When subject to `?` ([`PatternTest`](https://reference.wolfram.com/language/ref/PatternTest.html)), it only matches if the test yields `True` for all elements of the sequence; since the test `h` is undefined, this only occurs when the sequence is empty. ``` /@# (* if each letter of the original message*) #|" "|___?h& (* is still present, changed to a space, or missing *) FreeQ[ ]& (* check that this does not describe the new message *) ``` [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` (a:b)!(c:d)=b!([c|a/=c,c>' ']++d) _!y=y==[] ``` [Try it online!](https://tio.run/##lZNfa4MwFMXf@ymOZVClg70Xssd9gr2VUm7@MDOzOEzGCPS7Oxe1wy5pNxGUe373Hj1Xa3KNMqbvS9rxqijFTlaMF@VenOiBiXvxuMHmsN3KanUsAguM7Q/9G2nLZLvCe6etxx3WvlZrFNOVMTx3Hyol47qcVpe9T2TcRbOFxieZRskbD3EBWk1GplDiQo6uxF@TrgQOAYmZivzvQQG@lRQiFHyKcGQUWgtnFTWqcxF1drhPvsN5mm9JpvP4QULIJYak7RAx8ta1dhhOgtMvdgoaQwnfJcBmMs9YjcKi/P924MYAAoZFAWJeUxaaiIiLzMoXszAe4g@2WLCJdUQM83ebBWpc@3vqs9h/AQ "Haskell – Try It Online") This is just a modified version of the Levenshtein distance calculation. Instead of normal edits our permitted edits are: * Remove a character from string \$a\$ * Replace a character from string \$a\$ with space. I use one clever-ish trick. Because two cases only differ by whether the head is maintained, we can use a list comprehension to create the two cases in situ. So ``` (a:b)!(c:d)|a/=c&&c>' '=b!(c:d)|1>0=b!d ``` (this could be shorter anyway but I've structured it like this for illustrative purposes) becomes ``` (a:b)!(c:d)=b!([c|a/=c,c>' ']++d) ``` [Answer] # [Perl 5](https://www.perl.org/) `-pl`, 26 bytes ``` y/ /./;s//.*/g;$_=<>=~/$_/ ``` [Try it online!](https://tio.run/##hU@7DsIwDNzzFTcwIdGUgYnHH/ANVUosGholFYmEsvDpBFNaBAWJwfHd5c6WOzrbVc5JQhZyHaQs5vK4nlXbzW57lbNK5hwbEn1h6G90gA05GFyUbUkLZ5TVE03VJ66DpvFFjQM0j0hRJESvVRLBqZZEUJbgHYIjpucgolc8rnfElEYEwtPPi/CdaRB4OxQ3OKaGaXhQc3Rj5DPwc0ovAn@dfBXfBL4K6FE9dAwfwEt4oal481003oW82K@KclnmRWfv "Perl 5 – Try It Online") Takes the new resulting message first, followed by the original message, on separate lines. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 19 bytes ``` ßḢxn⁶anʋ¥@Ḣ};ʋɗṆ}ȧ? ``` [Try it online!](https://tio.run/##jZIxbsIwFIb3nuIXMxIHYGjvgRheYqsJWC8SjgQeGNqhCwfoWKlSxdK5ghUW4BZwEWPHDgoBtY0sxf/3P//OczySShlrtx/H1eeMTy8/xIfF5uvJyXn/sNi/H9dv893y0W6XvdPrt7WDh0GnzGSni@o17DY0WrqWNy4jx5TUWIp2zrXDOSkRPEpSUeVQMooECVIIROrtihuUhSDjqSkD0qQkCoZmSWM50d7T7KZx37q@LEi0kTGXj8O9HNcXmllZruEGQefPHNqDI/AE4D/CAm/S/9QDNysIcOcDpPF0GjSgyk7vFSM8v3m1Gf802lcBGa505tXwDA "Jelly – Try It Online") Dyadic link that takes the original string as the left argument and the new string as the right argument. Uses something similar to @WheatWizerd's modified Levenstein algorithm, so it's very fast, unlike a brute force solution. ## Explanation I admit this explanation is more confusing that the code itself. ``` ßḢxn⁶¥anʋ@Ḣ};ʋɗṆ}ȧ? Main dyadic link ? If ȧ both strings are non-empty ɗ then ( ß Recursively apply this link to the left string ʋ and to ( Ḣ First character of the left string, removing it from the string Ḣ} First character of the right string, removing it from the string ¥ Apply this dyad to them @ in reverse ( x Repeat the left character ʋ this many times ( n⁶ Is the left character not a space? a And n are the characters not equal? ʋ ) ¥ ) ; Join the result with the right string ʋ ) ɗ ) Ṇ} else return the logical negation of the right string ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~55~~ 51 bytes ``` f(char*a,char*b){for(;*a;)*a++-*b&*b-32||b++;b=*b;} ``` [Try it online!](https://tio.run/##jVJJboMwFN1ziiekVExR03aJ6EnYfA8EN9RE2B1QkrNTBzrEhEhFyN@8yfbHfL3lfBiqiNfUJZSNhcWHqu2iPKE8TihN1wm7S9j66fF4ZGmasyJh@Wl4b5WAlcb63kxpiy4@BNh3blohCstwZcoQmGqp0Unz1lgUz1gJ3EN@7iW3UrivUpc6zChjWRW5MS6KTdbFeXAKgnPuKymNyIWP6yK0tQyzaXxwKh/FIjoDf5UbT6mh8EHNTorlfI/XihrhKYhxcU4m9uIlExg4BCZu1Fy4ethWUO@43nqEoUai1TBa0k52ximMdjN/V99e25Lwj/ND9P38mFhIdt3AQnqtDNxLMGqrx6bAATgDgJ73ZzF4gj3w3y7glo8A11WATz295kZi1PDZz7gwYnr47Wj8STbzW4WxXMM1Fq5gPWHBafgC "C (gcc) – Try It Online") -Saved 4 thanks to @Davide * Output 0 if can be vandalized, truth if not. * we iterate Marquee(a) until end of one of the two inputs : we increment result(b) if current letters are equal or if we need a space. Finally we return \*b which is \0 if compatible [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes -3 bytes by converting to tacit form ``` {(1_t_x;!0)@^t:(x?y)*~^y}/ ``` [Try it online!](https://ngn.bitbucket.io/k#eJyVUt0OgiAYve8pTl5pF1m3dVFPUvsUTMvhFrRirZ49hFoidJFjzp0/5PBVq3u63Kv9bT1dZNudWqW3jc5mz51+5JNJhXmaqJona/vOkKvzhXsw4rBFMYAH4opa+VULNLhSe+Lsxy6eQDTUMl9CRcn6dCqOo3RCgRIMju1VnlFDdYy0IbXyGUktRycgBacTP0sjkcJ8jf7t7VYdsfG5PpTW4YkRiTfVILZF3UiYRZDNQdiCYAD0ACCCrqLRDh6Cf9iAn0YCTMFA6eqNkJaxojK4moEX7okljCRBjhs3vOcmJGrExrP+gC8969jI) Returns `!0` if the marquee can't be vandalized, and some sort of string if it can be. To better standardize the output, `~(!0)~` can be inserted at the start of the function, i.e. `{~(!0)~x{(1_t_x;!0)@^t:(x?y)*~^y}/y}`. * `{...}/` use a reduction, seeded with the original marquee text, running over the text to test * `~^y` check if the current character in the input to test is not `" "`. (`" "` is the null character, so we can test this by using `~^`, i.e. not null) * `*` multiply this by... * `(x?y)` the index of the first match in the (remaining) marquee text. This will return `0N` (also a null) if the character is not present. `0N*1` remains `0N`, whereas `0N*0` results in `0`. * `t:` store this in variable `t` * `(...)@^t` index into the list, using whether or not `t` is null. If it is null, the second item will be selected. If it is not null, it'll be the first item. * `(1_t_x;!0)` `!0` here is a sentinel value, used to indicate that the test text is invalid (because it contains at least one invalid character, or is too long, etc etc.). `t_x` drops `t` characters from the beginning of the (remaining) marquee text. To make sure the modified test text lines up, we always want to remove at least one character, hence the `1_`. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 24 bytes ``` ~(0G` . [ $&]? ^ $¶ $ $$ ``` [Try it online!](https://tio.run/##fY9NCgIxDIX3OcVbVHFRRE/g0gO4FGUybdHq0AFbkG48lgfwYmPmRxnwp7S8vC8JTS4u@cDLZjLbFLq5zRbrgua0hZruVrQn9biTIqWaJh2dlkedYlCRtwvwuHJ1dvZVNyLBc2WJS2Od5vJEjBIGFq0TRhmptpx1ThS5cqgDYnB8dpeoYxClPp9qtq8w5/YTfNTLPBh6jj5CLiP6Q5CxIBatBcKP5h6O0N86jKFsBdkLMO1WvZOwY2acRH@@MZgn "Retina – Try It Online") Takes newline-separated input, but link includes test suite that converts from comma-separated input on newline-separated test cases. Explanation: ``` ~(` ``` Interpret the output of the rest of the program as a program (specifically a Count stage) and execute that on the original input. ``` 0G` ``` Keep the original marquee. ``` . [ $&]? ``` Replace each character with an optional character class of itself or space. ``` ^ $¶ $ $$ ``` Anchor the list of character classes to ensure that the match starts at the beginning of the vandalised marquee and ends at the end of the input. [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes ``` ->o,s{o[/#{s.tr(" ",?.).chars*".*"}/]} ``` [Try it online!](https://tio.run/##jZBdbsIwEITfe4qR@9KiNJyAchDEw8Z2SCCyq6wRslDOHuz8UKJEgGXJ1jc7o92tz5lv803782sTvtrd@vPKqau/BESyTb9TWVDNK5GuRLPeN@0f8p1whRYJumf/MSGYkX@wUGFQ4kLVSat53lQzJVVqVCmTqkuj7HhnyCChMPBYMCgezirykXs3QqZKwxqw0XTSNUeVTfjeOxg9zpKaQ@8fWsVSWpgU08SiZIRL4PJg@oERCCIBzMvAnj/S9xzAgoeAsDFADvua8B52BXLZgP48V6Pc3gA "Ruby – Try It Online") Outputs a string for truthy values, otherwise `nil` for falsey. [Answer] # [Python 3](https://docs.python.org/3/), ~~79~~ \$\cdots\$ ~~73~~ 70 bytes Saved a byte thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah)!!! Saved 3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! Saved 2 bytes thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)!!! Saved 3 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` lambda m,v:match(sub(*' .',sub('(^|\S)',r'\1.*',v)),m) from re import* ``` [Try it online!](https://tio.run/##jZLfToMwFMbv9xRfuGm71CVzJiYm89IX0DunSSmdoNAS2k1x7tlnW5iy@ZcQOOf3HT7OaU7dutzo2W45X@xKUaWZQMXXF5VwMqd2ldIxwYTwEBF6/7a4ZoQ3ZDGdjAlfM8YrNlo2pkKjUFS1adx455R1FnNQmrhcJRzxxTg@cxzl@/SLqlHgWZRPKjv2OVR0Icqs00Qqs@gj0seeIIVEhp4GOfIWzmSiDbR1HbKiVDAaVivxpBobNKt92P93X@@MyI5R2340h@98/FwYeuWFhb8FbPGgu/HgCQIB9B9mHR/S/9QDX74QgD8fQPanM6AdirL8rhjd9ZsWRTZSL7WSTmVhLW6aleIYPq9Eaf9GB8KP@o8mXcJGMlfSTx86IYvV6fmZJBwxms6I32bTwHG/zRqvRU3jMnPs@2cXozBUxbH2Bi4mYddTY0q6pIEzFmndFNrRJUk21TYcyGa9TXByiY3dYtP3cGvnc3W3JWz3Dg "Python 3 – Try It Online") Returns a truthy value if the new message can be created by removing characters from the original message or `None` otherwise. [Answer] # [Python 3](https://docs.python.org/3/), 69 89 86 bytes ``` def p(s,v,a=1): for c in v:_,x,s=s.partition(c);a*=c==x;s=(s," "+s)[x!=" "] return a ``` [Try it online!](https://tio.run/##TYxBCoMwEADvvmLrybRBsL0peYlIWWysoe0m7G5FX596kt6GgZm06RzplsMnRVaQTfLDT5AqsYtF15i2gCkyjBAIlvZuVytO6oSsQUOkajQdnt3o3NqJ26sSyouYfj25nYYC2OuXCTAnDqTVPt6kRn4ufTPYg6@DMTnr7EHw7SESCHl8eZY/CYf8AQ "Python 3 – Try It Online") *Dropped to 86 thanks to Danis* I haven't posted just a function before, but I think that's allowed for this one from reading the description? This returns `1|0` not `True|False` so I'll have to add a few more bytes if that's a requirement. It just relies on the `partition` call to throw away characters from the front of the original string. And if the next character in the "vandalized" string isn't found the `a*=c==x` statement zeros out the accumulated answer. Sadly... I missed the rule that when a character is replaced, it can match a blank the comes after it in the "vandalized" string. Accommodating that added more code. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ≔⪪⮌S¹θUMS∧∧θ№⁺ ι§θ±¹⊟θ¬θ ``` [Try it online!](https://tio.run/##VYyxDoMwEEN3vuLU6SKlAzMTYmIoQuULIjhB1HCB5ED9@zQZO1iyny3PmwmzNy6lNka7Mk6Hs4JvuilEwp6PSyYJlldUSkOddaqmepmj8/tuePmfaGgzKjo1dP5iwdFdER/w0GBLLT0v9C31QKsRwlqV49EfeGbXVGN@Ehy8lNykJEAQ2Xyoki074wg8Z0IZhZiet/sB "Charcoal – Try It Online") Link is to verbose version of code. Takes input as the new and original messages and outputs a Charcoal boolean, i.e. `-` if the transformation is possible, nothing if not. Inspired by my answer to [Speed of Lobsters](https://codegolf.stackexchange.com/questions/217690/). Explanation: ``` ≔⪪⮌S¹θ ``` Get the new message and reverse it and split it into characters (so we can pop from the list). ``` UMS∧∧θ№⁺ ι§θ±¹⊟θ ``` Loop over the original message, and pop the next character from the new message if it is a space or the next character from the original message. ``` ¬θ ``` Check whether the list is now empty. [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~53~~ 51 bytes ``` grep -q `sed -E 's/ /./g;s/(.)/.*\1.*/g'<<<$2`<<<$1 ``` [Try it online!](https://tio.run/##hZFNboMwEIX3nOLJIsqPFFy6DW1XvUUWGbADbpBJMWqEqp6dGhsKtJFqweD53vPgsVMyRXfebD@7vJZX7N9xMlJg/4q14eARzw@Gb6Itj3bHONrxfJ0kSfh46mPcfQXBrVClRC1JoFRaHiCqAHbIDyrBzgh7yhxy4Vor3ZzBVgZPz1iJo2Zg3oTwJRCVlh1rCpv5@BCMGRbZkPwosVM0FG5UXqRYrl9wragUTqE0E30FSt9cBUKKDAKeOc26WjSVoNaytnHAkG250jBa0kXWxipG25n/2@BtKhJ@WyNo23GbuFPBdoFZlUIZ2IdgVK5dM7AAPQD02NfdQh4v4L9u4Lef7GWl9s38WUzMAadlw6HNjPAj@1sCkxSPtwj3mdICsysu@vk3 "Bash – Try It Online") Rough port of [Jonah's J answer using regex](https://codegolf.stackexchange.com/a/217190/94093), I am sure there is a better way. Takes two strings as arguments in the order of the test cases. Exit code is 0 for a match, 1 for a mismatch. [Answer] # [R](https://www.r-project.org/), ~~105~~ 104 bytes ``` function(a,b){for(x in el(strsplit(gsub(" ",".",b),""))){c=sub(paste0(".*?",x),"",a);if(a==c)T=F;a=c};T} ``` [Try it online!](https://tio.run/##lZJBboMwFET3PcXI3diVG3WPaHc9QS7wMSa4QSbCRg2KcnaKIakomEhFSFjz5ntgcNMXaV@0VnlTW04yE5eibvgZxkJX3PnGnSrj@cG1GWdgku3YYJKMCSEuKg3yiZzXb5ztXj6YPAcmSSSm4JSmSuzTz4RSdU32177gzJeaSYwPgWe8vsM3rX6aEWySNVhOFFS5@4iFwTdVR51vB/71WENVvnRRpvIxhrKvVQwhg0KOmyE4F@MdfJ1TF3jnl9BRpVFbOKvpqBsXXM4Oy9Wr3vfwNeXrj/2lXRdrArGcoTXEs0rjMNwEZw526g6DgqAANlJjPGDS5@r/JoEHswQM3QPq1nyUT3A0qsi/m@@A6VKPc7C0zWsODszO2YqV2DjZ5VzvfwA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` v¬DyQsðQ~i¦]õQ ``` First input is the original message, second input the new message. Modification of [my 05AB1E answer for the *Speed of Lobsters* challenge](https://codegolf.stackexchange.com/a/217695/52210) (thanks *@Neil* for the tip, resulting in -8 bytes). [Try it online](https://tio.run/##yy9OTMpM/f@/7NAal8rA4sMbAusyDy2LPbw18P//kozUolSuEgWFVAA) or [verify a few more test cases](https://tio.run/##hZE9jsIwEIWv8uQ62ivQcIE026BITGKLGCJHYiKQG0oOwCGoKLbZC8BNuEhw7AAxv5Zl@X1vPPaMa6Zcq3ZlRwLn7Q5iZKcs2tXxMLYpn/7SjT7us9N/2oqf36SdTERTKpH4NUtuCpHqxYNjoLGmaqFkfD7iRlMlvUN5IbsMlM@DRo4CEoF1XkctmlqSdcw2HjBVCrUBG0ULtWTnsHG7cFsf29QkY2Dt9Tl4kcFVgUGWUjPcJLCeGV8MHEAHAPMxUcBD@D0aeIwnwHUDKEIv7swD7xXPgQjjvdNb4RcRfzFKDFQpsuwC). **Explanation:** ``` v # Loop over the characters `y` of the (implicit) input original_message: ¬ # Get the first character without popping the string # (which uses the implicit input new_message the first iteration) D # Duplicate this first character i # If yQ # this first character is equal to the current character `y` ~ # OR sðQ # this first character is a space: ¦ # Remove this first character from the new_message ] # Close both the if-statement and loop õQ # And check if the new_message is now empty # (after which the result is output implicitly) ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 62 bytes ``` ->\a,\b {a~~/<{join ".*",map {" "eq$_??"."!!"'$_'"},b.comb}>/} ``` [Try it online!](https://tio.run/##jVNNb4JAFDzrrxg3pKJBbXvoofXj3Ev/QGnMA5aK4qIupiUW/zrdRURQmpQQlp2ZN7w3wIbvwqdsndz5k2wwtcmyHRzoeByND8soEGDDPrPWtMGBgfGtMZ/N2JB1OqxrzLsstZyhG62ddDpKMz/awei/vg3DQHCJQ7sV@BjZzBwP3m32Me33bOVhgeEaw2CqLma82/Mfn0LJeyNd3lonMAgTHI37l2Lr5NuH85Z/b7gbc0@hxiP4FkybsDNNbrynUJG@aZClqnuakZSA@RSEz6oTg2zVk1od1YlZ@pXOFgqTwqzHoMa6PLgzwayglHfaTjMWL7geUy96Mt1RuwTRBNawmi6PIxcKBPiicMW9RvM6LQIKvYqAHNfLfclZVn0JDlx4KDgtuhQliCOPEk0lcQWXFHJEAlJwWvGd1AIp1G21o3NlHJFXm6QkkuRqQjQZqyBwY74IJNRJkMGnOMUBhUAjgKgn02x7wqvov4uA5jICVJyAW4R5TZ3wXOPWX0K1DqfD/dMYNcUlvvzXOn8XV/ACt1/dooR@AQ "Perl 6 – Try It Online") ]
[Question] [ Your task is to accept as input two "ASCII Art"s, and align each piece of art next to each other horizontally. For example, say you have two strings, `"abc\ndef"` and `"123\n456"`. You need to align them horizontally to produce the string `"abc123\ndef456`". I'm calling this "aligning horizontally" because while the inputs, when printed, look like this: ``` abc def ``` and: ``` 123 456 ``` The output, when printed, will look like this: ``` abc123 def456 ``` Note how one input is placed next to the other. --- # Input * Input will be strings, and can be as two separate arguments, or as a sequence of strings. * The characters in the arts will have decimal codes in the range 32-126 (inclusive). * It's fine to support an arbitrary number of arts to align instead of just two (but obviously you must support at least two). * You can assume that each art will have the same dimensions, and that they will contain at least one line. * You must be able to support at least 100x100 character arts. * To align with conventions on the site, the argument order does not matter. It does not matter which art is on the left or right. --- # Output * Output will be the aligned arts as mentioned above, either returned or output to the stdout. * Any trailing whitespace in optional. * There must be no visual separator between the aligned arts. --- Input and output arts must be `\n` or `\r` delimited strings. It would be overly trivial to allow 2D-arrays. Submissions may be functions or full programs. Test Cases: ``` "abc\ndef", "123\n456" -> "abc123\ndef456". "qwertyuiop\n asdfghjkl", "Some other\nTextFiller" -> "qwertyuiopSome other\n asdfghjklTextFiller" " * \n *** \n*****\n *** \n * \n", " + \n + \n+++++\n + \n + \n" -> " * + \n *** + \n*****+++++\n *** + \n * + \n" ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` × ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUQ3,i=JTIycXdlcnR5dWlvcCU1Q24lMjBhc2RmZ2hqa2wlMjIlMEElMjJTb21lJTIwb3RoZXIlNUNuVGV4dEZpbGxlciUyMg__,v=1) [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` (unlines.).(.lines).zipWith(++).lines ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX6M0LyczL7VYT1NPQw/M0tSryiwIzyzJ0NDW1oQI/c9NzMxTsFUoKC0JLilSUFFIU1BKTEqOyUtJTVNSUDI0Mo7JMzE1U/r/LzktJzG9@L9uckEBAA "Haskell – Try It Online") IO as lists of lines would just be `zipWith(++)`. :P [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` lambda y:'\n'.join(map(str.__add__,*map(str.splitlines,y))) ``` [Try it online!](https://tio.run/##NcpLCoAgFADAq4SbNCTouwg6SYa8Msmwp6QbT29t2g7jUzwdtlnPIlu4NwVFmkqBZX05g/QGT0N8ailBKSl59UPw1kRr8Ag8McayfwxGqulCYNsFqkMTTpq2E9gPI1m/8QI "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` |¶¡øJ» ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/5tC2QwsP7/A6tPv/fyUlJQUFLQUFLgUtLS0FLi0QgLIh4kAFXGBF2iBFYFIbBLiQRYAKAA "05AB1E – Try It Online") **Explanation** ``` | # push all input into a list ¶¡ # split on newlines ø # zip J # join the rows to single strings » # merge on newlines ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ỵ€ZY ``` [Try it online!](https://tio.run/##y0rNyan8///h7i2PmtZERf7//18pMSk5Ji8lNU1JR0HJ0Mg4Js/E1EwJAA "Jelly – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-0F`, 28 bytes Includes `+2` for the `\n` argument to `-F` (it's "code" so it should count) Give inputs directly after each other on STDIN. ``` #!/usr/bin/perl -0F\n say@F[$%++,$_]for@F/2..$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sdLBLVpFVVtbRyU@Ni2/yMFN30hPT0XZ7f//xKRkrpTUNC5DI2MuE1Mzrn/5BSWZ@XnF/3UN3GLy/uv6muoZGugZAAA "Perl 5 – Try It Online") [Answer] # Bash + coreutils, 14 * 4 bytes saved thanks to @DavidFoerster. ``` paste -d "" $@ ``` Input is given as two filenames as command-line parameters. [Try it online](https://tio.run/##RYw7DoAgEER7TzFBqzUWfkvjQWgWxWhDjHB/FFGc5mV2961iu/nj3I1bIQACpAER3aCQ1N6dwAjOfqF8hIgyJLUXQVBZ/hmsZmkWvcY/aVw3rTRdP8Rrqx0Yyh9snUa1QAgUk/cX). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes ``` {join "\n",[Z~] $_>>.lines} ``` [Try it online!](https://tio.run/##PYzNDoIwEITP8hSbhoMWYuIfFyNHX0BPUkJQWimWFgtGidFXrxQJc5nMzjdbUS0CU7bgMtiZd6G4BEQk8qPTNwY3CcO54JLWH7N16tRiUzeZ@T0DTGlnEqH0fCEyowx158VyReR6E6DYt9X9SXXTPriqiIS0ztg1L27CggdVUlBNTjWRR/pq9lwIqocZAAboFhjjzrDVmIbO/gDweuxvntWYBkOx@QE "Perl 6 – Try It Online") Works with arbitrary number of arts. IO as list of lists would be just `&[Z~]`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 [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") Full program. Prompts (STDIN) for any length list of `\r`-delimited strings. The strings may be ragged and of different widths as long as they have the same number of lines. Prints (STDOUT) resulting ASCII art. ``` ⊃,/⎕FMT¨⎕ ``` [Try it online!](https://tio.run/##dU8xbgIxEOx5xcYNkjkUAUmeQIEEKaCLU5h47XMwZ7Ln6Lg6BREFHX/gHXnKfeRiE0QVphnN7O7srty4vqql86Ztvne6bfZf2X1zOI6ni59T5OS2cIbuRD2ZP8@g@8Lk8k2QQs0yYIPhSNDD4xN77Xb@af2okEL9af1GEMhSaZO/r1wanPs1gg85kqAFbsPYOod0IwaAA8QEznkknnBVl1rKBOid2/6ol3BVF7qxYC2LWhBJY1AJkmRKljGv45tWayQsgqDKqpAnv/K0KkW8W9sC72LiLw "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for evaluated input `⎕FMT¨` format (evaluate all control characters and return character matrix) each `,/` combine them horizontally (catenation reduction) `⊃` disclose (because the reduction reduced the rank from 1 to 0) [Answer] # Java 8, ~~100~~ ~~84~~ 78 bytes ``` a->b->{for(int i=0;;)System.out.println(a.split("\n")[i]+b.split("\n")[i++]);} ``` Exits with an `ArrayIndexOutOfBoundsException` to STDERR after it has printed the result to STDOUT, [which is allowed](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781). -6 bytes thanks to *@OlivierGrégoire*. **Explanation:** [Try it online.](https://tio.run/##bY89a8MwEIZ3/4ojk4RrkfRrceMlkK1TRtfDWZaLXFkS1ikQgn@7qlIvhcIN9/Fw7/tOeMXKeWWn4StJgyHAO2p7LwACIWkJUyZEJG3EGK0k7aw4b83bhRZtPx/@Y07OhjirZWOaBiQcE1ZNXzX30S1MWwJ93Nc1v9wCqVm4SMJnloxlKII3mtjuw@54q7uy/7soy47Xa6qzzVw@9iY73QxfnR5gziHYr3TbIf/JAyAFem9uDNt9xwVKqTzl4ZB/5ftarClhL4tBjenw@FQ8v7x@Aw) ``` a->b->{ // Method with two String parameters and no return-type for(int i=0;;) // Loop over the substrings of the first input System.out.println( // Print: a.split("\n")[i] // The substring of the first input +b.split("\n")[i++]);} // plus the same-indexed substring of the second input ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 48 bytes ``` ->a,b{$;=$/;a.split.zip(b.split).map(&:join)*$/} ``` [Try it online!](https://tio.run/##VZDPUoMwEMbvfYqdDONAinT8e2gHvfkCegMOARZJTUOEMLZanx0ToIC57H7f/r5NJnWbnroi7K6fmJ/@OLvQ2exY0CjBdfDNlZsOvRccmHKvtvuKS486m98uWgFEhKVZLHMsiA/k5vYulvcPj7Y3fi/NyDqJ39OfX1jrU8srFUtgTV68l/sPYfnX6oBQ6RLrWL7hUb9wIbC2kzmzZOb0gh5vAaAABqGUmkLtmdQ4s4sB1j02lLU9kxrLgJnExbZLxr7fe0kt/JknySoJkGUl5BWcmQ@pD3hUmGnMz@alNTat0BBCEZm/T4yjWt1MdjjB8AzEVaxpPAJb0xaMC4/850e1Qpl3fw "Ruby – Try It Online") A lambda taking two strings and returning a string. Setting the default `split` delimiter to newline with `$;=$/;` doesn't save any bytes, but it makes the rest look a little nicer. # [Ruby](https://www.ruby-lang.org/), 49 bytes (arbitrarily many strings) ``` ->s{s.map{|a|a.split$/}.transpose.map(&:join)*$/} ``` [Try it online!](https://tio.run/##dU5BDoIwELzzig0xRgvi3UQ/UjhUKBGjpaEl0YCJ8ezBAwffx0dwCxS9uGk6uzvT6RTl/tql2261U5UKzkxWNatZoOQp07P1LdAFE0rmihtuMd8c80wsCTIddQAodQEIQCiAEIJATE3TyLk@SgFQ6vXSATxT0zSClbbNs23u9rxC0TYP3OP9v21@XrzRKjJeQz77iYk19n1Sm@Fn/9W7kRMFnMUHSHKoMyFLrXzgF8ljzZMazc0GUjpQkcNF0n0A "Ruby – Try It Online") Just for fun. It turns out we can accept an array of strings at an additional cost of only 1 byte. [Answer] ## JavaScript (ES6), 51 bytes ``` f= (a,b)=>a.replace(/.+/g,a=>a+b.shift(),b=b.split` `) ;document.write("<pre>"+f("abc\ndef", "123\n456")+"</pre>") ``` [Answer] # [Wonder](https://github.com/wonderlang/wonder), 21 bytes ``` ->#oN.zip#++.-> <>" " ``` Usage example: ``` (->#oN.zip#++.-> <>" ")["abc#ndef" "abc#ndef"] ``` `#n` is used instead of `\n` to denote newlines. ## Explanation Verbose version: ``` (map #oN) . (zip #con) . (map split "#n") ``` Split each string in the input array along newlines, zip with string concatenate, and output each item. [Answer] # [Kotlin](https://kotlinlang.org), 73 bytes ``` a,b->a.split("\n").mapIndexed{i,s->s+b.split("\n")[i]}.joinToString("\n") ``` [Try it online!](https://tio.run/##bY3LasMwEEX3@YpBK0l@QJ8LQ70MdJ3s6i7kWnKUyCNHVtIU42935diEUnJB3Jk7M0cH643GUZ0QGqGRnoUTrobwugw23mmsGfQrCDoLAyqjIpvjuFwKluRz8daPIi6TXKRda7SnpEDC0ka071jJi6x6HXdJ3kXl3/mH/hzSvdW4tTNljkeAYXX9tg2hN0gVJaL8KgJKkRjIw@NTgc8vr4Sx/2vHb@n8z0nbtkAQXaXq3f5gpqONbSRYv5OuwK28@LU2Rro7CAAOEK4558H4pFu3zCYeQHRdmy2adOsWm@DD@As "Kotlin – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 4 bytes ``` ↵∩vṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwi4oa14oipduG5hSIsIiIsIltcIiAgKiAgXFxuICoqKiBcXG4qKioqKlxcbiAqKiogXFxuICAqICBcXG5cIixcIiAgKyAgXFxuICArICBcXG4rKysrK1xcbiAgKyAgXFxuICArICBcXG5cIl0iXQ==) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~15~~ 14 bytes ``` "\n"/,'/"\n"\' ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs1KKyVPS11HXB9Ex6lxcaQoaSolJyTF5KalpStZKhkbGMXkmpmZKmlxcAAHECtE=) -1 byte thanks to ngn [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 24 bytes ``` L,c10CdVAptA$pG$tBcB@£+n ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJ9nQwDklzLGgxFGlwF2lxCnZyeHQYu28/yo5iblJKYkKhnZKiUnJMXkpqWlKdkqGRsYxeSamZkpc/lxcFVaGBlwBXFxISgvLU4tKKksz8wti8hQSi1PS0jOysnOAGoPzc1MV8ksyUoti8kJSK0rcMnNyUotwGaOgoKWgADRBS0sLSGmBAJwHlVMCqdIGq4JQ2iAA50EpoAX/AQ "Add++ – Try It Online") [Answer] # C, 96 bytes ``` #define L(s)for(;*s++>10;)putchar(s[-1]); i;f(s,t)char*s,*t;{for(;i=!!s[-i];puts("")){L(s)L(t)}} ``` [Try it online!](https://tio.run/##bY29csIwEIR7P8WhNDrZzGD@Gk1SpqILXUzhCMkWGJlIYpKMx89uJAKu2Gbn7vbbE9NKiGF42UuljYQNdahaSzlzafqWzzieL17UpaXuc5rvkCeaK@oyj3HJXMY8726Afp1MQkbveCAcJQSxi20b6rHvB208nEptKCZdAkGKkvJLFCY8JhmQfL4ozHK1Jjjy/JH7/pHW/110ey4MlG6vqvpwbCL10Z4ktL6WtjBb@evfddNI@6wDgAEEnDEWjEWN0/0WCwHSW@zf0qhxulss7Ycr) [Answer] # JavaScript (ES6), 52 bytes Takes input in currying syntax `(a)(b)`. ``` a=>b=>a.split` `.map((s,i)=>s+b.split` `[i]).join` ` ``` [Try it online!](https://tio.run/##bUzNEoIgGLz3FAwnwHKm3xsee4G6RTOiomIIBvT39CbleGjay3673@42/M5dbmXnF9oUoi9pz2mS0YTHrlPSp7M0bnmHkJtLTBMXZZN/kmccN0bq4e5zo51RIlamQiWCPMuZLkQJMYLL1ZrpzXYHMZ79xK4PYf3rJk3HNOCuKKu6uahQOphWAONrYZk@iqffS6WE/TMBAAFgaBNCBiIBkxp/YQ@A6BP7UhQwqZGG8f4N "JavaScript (Node.js) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~51~~ 49 bytes ``` param($a,$b)$a-split" "|%{$_+($b-split" ")[$i++]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVRRyVJUyVRt7ggJ7NEiUupRrVaJV5bQyUJLqIZrZKprR1b@///fyUFBS0FBS4FLS0tBS4tEICyIeJKIAXaIAVgUhsEuJBFlAA "PowerShell – Try It Online") Takes input as literal strings with newlines. You could also use ``n` (the newline delimiter in PowerShell, not `\n`) instead. We first `-split` the left input string on newlines, which creates an array, and loop through that `|%{...}`. Each iteration, we string concatenate with the right input string again split on newlines, indexed and incremented. Those are left on the pipeline and the implicit `Write-Output` at completion gives us output as an array of strings, which are printed with newlines between. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes ([Adám's SBCS](https://github.com/abrudz/SBCS)) ``` {⊃,/↑¨⍵}'[^\n]+'⎕S'&'¨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRV7OO/qO2iYdWPOrdWqseHReTF6ut/qhvarC6mvqhFf//pyk8apugQEgdV3weWB1QIMQ52iiWiytNQz0xKVldJz5PRz0lNU1dU0Pd0MgYwjcxNVPXBAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 78 bytes ``` func[a b][b: split b"^/"foreach c split a"^/"[prin c print first b b: next b]] ``` [Try it online!](https://tio.run/##PYxNDoIwEIX3nGLCsiwafxccwAOoO0KTtkylioAFooZw9jpFwmzevDffG4eFP2MBWR6Z1Juh1pkElWcqha6tbA8qFjw2jUOpS9BLKEOYtc7WFAXpwVjXEQ1UrPFDW557A6NUWvACzQTjZrsTfH84ThHlrze6/jvYphUcZFeYW3l/VERdmidC05foBL/So5OtKnRzB4ABEM4YI2FhVrfcpkAlM/WXJMzqFpn8Dw "Red – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 92 bytes ``` a=();for b;do c=;while IFS= read -r d;do a[c++]+=$d;done<<<"$b";done;printf '%s\n' "${a[@]}" ``` [Try it online!](https://tio.run/##PY1BCsMgFESvMojFVvEEKnRV6LrLNAuNhgSKKRroovTsttqQ2bz/mIHvbJ5KDiukBGUAB@4RnPMfeM1uW8faTLTZH6Jmtw2sWHM8qXFJcMovGIx6TfMj4Hq5GaRgPWSCr5XtBiF6YWi1GLTWhDrSbvVMc1xHsEOunwl92@7cf0gpXw "Bash – Try It Online") **Ungolfed:** ``` array=() # Initialize the array for argument in "${@}"; do # Loop over the arguments list index='0' # Reset the index while IFS='' read -r 'line'; do # Loop over every line of the current argument array[index]+="${line}" # Append the line to its corresponding place (( index++ )) # Increment the index done <<< "${argument}" # End while loop done # End for loop printf '%s\n' "${array[@]}" # Print array's content ``` **Examples:** ``` $ foo $'abc\ndef' $'123\n456' abc123 def456 $ foo $'qwertyuiop\n asdfghjkl' $'Some other\nTextFiller' qwertyuiopSome other asdfghjklTextFiller $ foo \ > $' * \n *** \n*****\n *** \n * \n' \ > $' + \n + \n+++++\n + \n + \n' * + *** + *****+++++ *** + * + # https://gist.github.com/nxnev/dad0576be7eb2996b860c320c01d0ec5 $ foo "$(< input1)" "$(< input2)" "$(< input3)" > output ``` --- I also have a shorter one but it fails if the second `read` statement returns a non-zero value. # [Bash](https://www.gnu.org/software/bash/), 55 bytes ``` while IFS= read -r a;IFS= read b<&3;do echo "$a$b";done ``` Note: `<&3` doesn't seem to work on [tio.run](https://tio.run/) This one uses file descriptors (`1` and `3`) instead of arguments: ``` $ foo <<< $'qwertyuiop\n asdfghjkl' 3<<< $'Some other\nTextFiller' qwertyuiopSome other asdfghjklTextFiller ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` PθM⌕θ¶→η ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@3NKcks6AoM69Eo1DTmss3vyxVwy0zL0WjUEdBKSZPSVNHwSooMz2jBCgZAFaWoWn9/3@0koKCloJCTJ6ClpYWkNICATgPKqcENEJBQRusDEJpgwCcB6WUYv/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input P Print without moving the cursor θ First input ¶ Literal newline ⌕ Find index M → Move that many squares right η Implicitly print second input ``` Add 2 bytes to accept multiple inputs: ``` FA«PιM⌕ι¶→ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLREQ1NToZqL07c0pySzoCgzr0QjU9MayM8vS9Vwy8xL0cjUUVCKyVPS1FGwCspMzygBytb@/x8draSgoKWgEJOnoKWlBaS0QADOg8opAfUqKGiDlUEobRCA86CUUmzsf92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` A Input F « Loop over all entries Pι Print current entry M⌕ι¶→ Move to next entry ``` Add 4 bytes to accept unpadded input: ``` PθM⌈E⪪θ¶Lι→η ``` [Try it online!](https://tio.run/##LYxBDsIwDATvvMLyKU7LB@gXiITgSDlEVdVYStNQpRW/N27Ah1mvrd0h@HVYfBRxWyycV07FvKk7uWUfjfMfnrdZNZtHjqyvFrBPSC1cxzSVYJhIzeXOUygau9WCQJ3IEwFsn8BapbVVfqbeUZsAmsMpmmP@ewW@5LzHLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input ¶ Literal newline ⪪ Split E Map over each string ι Current string L Length ⌈ Maximum M → Move that many squares right ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 79 bytes ``` a=>(b=a.map(x=>x.split` `))[i=0].map(y=>b.map(z=>c+=z[i],c="")&&++i&&c).join` ` ``` [Try it online!](https://tio.run/##hU7LboMwELznK1Y@IB4p6vtSmQtSfUVqb4AUY0xi6tgUaEvy89R2UaqokbqH2Z2Z3dG29JMOrBfdeKV0zecGzxQnfoVpvKedP@FkiodOinGz2gRBLvB16YwDTio3HHHCInzMRblmGKHA86JIeB4L4lYLZa7mJ6bVoCWPpd76jZ8jWrFC1bxBa0A3t3eFun94RGUQrP5svn/xfjx8CN0VCuhQN9td@ybt3Yvec9DjjveFeuXT@Cyk5P3lFIAQwASEYWhaaOvEFs9GAkRu7adFtk5saZfzsywzXgYOlxkWtMH/@WmaGpY67QyNbn1CiGHEaQTILxrdfjR/Aw "JavaScript (Node.js) – Try It Online") Supports arbitrary number of ASCII arts joining together rather than just 2 (as in the 2 previous JS answers). [Answer] # [Clean](https://clean.cs.ru.nl), 61 bytes ``` import StdEnv $a b=flatlines[u++v\\u<-mklines a&v<-mklines b] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJVEhyTYtJ7EkJzMvtTi6VFu7LCam1EY3NxssoJCoVobgJMX@Dy5JBGq2VVBRiFZPTEqOyUtJTVOPjVY3NDKOyTMxNVOP/f8vGWheevF/XU@f/y6VeYm5mckQTgDQmrT8olwA "Clean – Try It Online") [Answer] # [Swift 4](https://iswift.org/playground), 119 bytes ``` func f(s:[String])->String{return s[0].split{$0=="\n"}.enumerated().map{$0.1+s[1].split{$0=="\n"}[$0.0]+"\n"}.joined()} ``` **Explanation** ``` func f(s: [String]) -> String { return s[0].split{ $0=="\n" } //splitting the first string after every \n .enumerated() //create a tuple of offsets and elements .map { $0.1 + //current element s[1].split{$0 == "\n"}[$0.0] + //splitting the second string + indexing "\n" //new line after every line } .joined() } ``` [Try it online!](https://iswift.org/playground?6JEIqO&v=4) [Answer] # [Julia 1.0](http://julialang.org/), 34 bytes ``` ^,x=split,"\n" a\b=join(a^x.*b^x,x) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P06nwra4ICezREeJS4krMSbJNis/M08jMa5CTysprkKnQvN/QVFmXklOnoZSYlJyTF5KappSjJKhkXFMnompmZLmfwA "Julia 1.0 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes (41 chars) ``` Column[StringJoin/@(#~StringSplit~" ")]& ```  is an unprintable character in the private use area which represents Transpose in Mathematica. This function takes input as a list of any number of strings and returns a Column object, which displays in a Mathematica notebook in the required manner (although it doesn't on TIO). For an additional ten bytes, replacing `Column[---]` with `StringRiffle[---," "]` will cause an output in the form of a single string. This code can take input of any number of strings with varied-length lines, as long as each string has the same number of lines. --- Explanation: `#~StringSplit~` Split the input (implicitly applied to each string in the list) `" "` at each newline. `` Then, transpose this list of lists of strings `StringJoin/@` and join together each of the sublists. `Column` Finally, convert this list of strings to a Column object. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zk/pzQ3Lzq4pCgzL90rPzNP30FDuQ7CDS7IySypU@JSet/frhmr9j/NoVopMSmZKzWNKz0jU0lHQcnQyJjLxNTMgMvcUqlWXz8AqKvkPwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~8~~ ~~7~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ·í+V· ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=t%2b0rVrc&input=ImFiYwpkZWYKZ2hpIgoiMTIzCjQ1NiI) ``` ·í+V· :Implcict input of strings U & V · :Split U on newlines í :Interleave with V· : V split on newlines + : Reduce by concatenation :Implicit output, joined by newlines ``` ]
[Question] [ Given a word, your task is to compact it by saving its first character and removing any other vowel (aeiou). # Input Your input can be the word in STDIN, a function argument or any other input format that doesn't break the [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). You can assume the input only consists of lower characters. # Output Your output must be the word, compacted. # Examples ``` i -> i ate -> at potato -> ptt ksboejqfgcrauxpwivtzndlhmy -> ksbjqfgcrxpwvtzndlhmy ``` # Score This is a code-golf, so shortest answer in bytes wins, good luck! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ćsžMм« ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SHvx0X2@F/YcWv3/f0F@SWJJPgA "05AB1E – Try It Online") # Explanation ``` Input (e.g.). potato ć Head extract. otato, p s Swap . p, otato žM Vowels . p, otato, aeiou м Remove . p, tt « Concatenate . ptt Implicit output . ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~15~~ ~~13~~ 8 bytes ``` 0T1,`v`_ ``` `T`ransliterates lowercase `v`owels into nothing (`_`) in the `0`th in 0-indexing match of the implicit regex that matches the entire string, after index 1 (`1,`). [Try it online!](https://tio.run/##K0otycxLNPz/3yDEUCehLCH@///EkozUzOJcAA "Retina – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~57 56~~ 52 bytes Time to roll out some magic numbers! *Thanks @Arnauld for even better magic numbers!* ``` f(char*a,char*b){for(*b++=*a;*b=*++a;)b+=4373%*a&1;} ``` [Try it online!](https://tio.run/##HcpLDoIwEADQqxgSTDutCQQTF5OexLiYqRZQKZ@CP8LZq7J6m2d3pbUxOmErGoD0CsvZtYMAVsoAIbABpQglK7MvDkUKtM1xif@7oWOeZSfNK9hQ7YWcgyXvRJKGRJNEJ0izxG4ag/i5RCK254srq/p6uze@7fohjNPj@Xp/vg "C (gcc) – Try It Online") [Answer] # [J](http://jsoftware.com/), 15 bytes ``` {.,'aeiou'-.~}. ``` [Try it online!](https://tio.run/##RY3BTsMwEETv/YpRLkulxOIciQtInFAP/IGbbugWxzb1mjZU5deDo1BYaaXRzNudw1QZ6vHQglDjHm3ZxuDp9eV5upiaLEvI1Jjvq5nWK@72AXc1Ca3RtOgxS8yzeTQQH7OCzx1HleBbbEfsuLfZKWZOEqyH1TDUSAEnxpDTfBCddOpGVOydJK0gapYuskpLU1FMv2bUPzcGLQ9vwXvaHj76t@54jqdP/fI7tx/GG1rCwEtscwHkn1hNPw "J – Try It Online") Straightforward: * `{.` head... * `,` catted with... * `'aeiou'-.~` vowels, set minused from... * `}.` tail [Answer] # [sed](https://www.gnu.org/software/sed/), 14 bytes ``` s/\B[aeiou]//g ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1g/xik6MTUzvzRWXz/9//9MrsSSVK6C/JLEknyu7OKk/NSswrT05KLE0oqC8syykqq8lJyM3EoA "sed – Try It Online") --- # [Bash](https://www.gnu.org/software/bash/) + Core utilities, 19 bytes ``` sed s/\\B[aeiou]//g ``` [Try it online!](https://tio.run/##S0oszvj/vzg1RaFYPybGKToxNTO/NFZfP/3//0yuxJJUroL8ksSSfK7s4qT81KzCtPTkosTSioLyzLKSqryUnIzcSgA "Bash – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes Another 43-byte solution in Python. ``` lambda s:s[0]+s[1:].translate(None,'aeiou') ``` [Try it online!](https://tio.run/##DctBDsIgEADAO6/gVojGWI8kfsEPtI3ZWpBVCgiLWD@Pzn3iRjb4UzPnsTlY5wV4Vnk4Trs89Go6UAKfHZAWl@D1vgONoXSyVYtO814xHhN64kYkqFf0sZCQsiH7FxYDAQX2zHPQj5e53xKUT6z4pq9fnF23Hw "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/en/), 31 bytes ``` ->x{x[0]+x[1..].tr('aeiou','')} ``` Needs to be run on Ruby 2.6 or above, since it uses an endless range. (TIO is on 2.5.5, so it doesn't work there.) [Answer] # Excel, 87 bytes ``` =LET(q,SEQUENCE(LEN(A1)),x,MID(A1,q,1),CONCAT(IF(ISERROR(FIND(x,"aeiou"))+(q=1),x,""))) ``` Hopefully this link works. [Try it here](https://1drv.ms/x/s!AkqhtBc2XEHJm3v9rEGTcan1-PiT?e=iUq5sb) [Answer] # [Python 3](https://docs.python.org/3/), ~~44~~ 43 bytes ``` lambda a,*s:[a]+[c[c in"aeiou":]for c in s] ``` [Try it online!](https://tio.run/##PYoxcoMwEEV7nWJHjcHBNOmYwRchFGtA8Togydq1HcJwdiKRmXT/v/f8LFdn3zdTf2wjTpceAYsjVw22b03XdEBW40DuoavWuAAJALcbTd4FAZ5ZJTySHXYzc8nSk60UABcBapjQZywh4kC@2MuS/UiS6dNZ53kM0XIMD4fy5shmJjvyjn0gK5nRC69wOsMSsxWaZa9rCGur842SIYUypIGivBMUl44XUV98ccPtbj67gI9v/6Kn/Nh@vE5zKqL9c9H8i18 "Python 3 – Try It Online") **Input**: Characters of the word. E.g `f("a", "t", "e")` **Output**: A list of characters. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣ;ḟØẹ$ ``` **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4biiO@G4n8OY4bq5JP///2FiY2RlZmdoaQ "Jelly – Try It Online")** ### How? ``` Ḣ;ḟØẹ$ - Link: list of characters, W Ḣ - head & yield $ - last two links as a monad - i.e. f(rest of W) ḟ - filter discard: Øẹ - lower-case vowels ; - (head of W) concatenate (f(rest of W)) ``` [Answer] # [naz](https://github.com/sporeball/naz), 102 bytes ``` 2x1v2a6m8m1a2x2v4a2x3v4a2x4v6a2x5v6a2x6v1x1f1r3x1v2e3x2v1e3x3v1e3x4v1e3x5v1e3x6v1e1o1f0x1x2f0a0x1r1o1f ``` Works for any null-terminated input string. [Try it online!](https://sporeball.dev/naz/?code=2x1v2a6m8m1a2x2v4a2x3v4a2x4v6a2x5v6a2x6v1x1f1r3x1v2e3x2v1e3x3v1e3x4v1e3x5v1e3x6v1e1o1f0x1x2f0a0x1r1o1f&input=compactify&n=true) **Explanation** (with `0x` instructions removed) ``` 2x1v # Set variable 1 equal to 0 2a6m8m1a2x2v # Set variable 2 equal to 97 ("a") 4a2x3v # Set variable 3 equal to 101 ("e") 4a2x4v # Set variable 4 equal to 105 ("i") 6a2x5v # Set variable 5 equal to 111 ("o") 6a2x6v # Set variable 6 equal to 117 ("u") 1x1f # Function 1 1r # Read a byte of input 3x1v2e # Goto function 2 if it equals variable 1 3x2v1e3x3v1e3x4v1e3x5v1e3x6v1e # Jump back to the start of the function # if it equals variable 2, 3, 4, 5, or 6 1o1f # Otherwise, output it, then call the # function again 1x2f # Function 2 0a # Add 0 to the register 1r1o # Output the first byte of input 1f # Call function 1 ``` [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 26 bytes ``` f([H|T])->[H]++T--"aeiou". ``` [Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/TSPaoyYkVlPXLtojVls7RFdXKTE1M79USe9/bmJmnka8poKuHZcCEGTmW5UXZZakaqRpKBXklySW5Ctpaur9BwA "Erlang (escript) – Try It Online") ## Explanation ``` f([H|T])-> % Match the head & tail of the input string. [H] % Wrap the head in a list, ++T % Append the tail --"aeiou". % with all vowels removed. ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 14 bytes ``` ⊃,'aieou'~⍨1∘↓ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXc066omZqfml6nWPelcYPuqY8ahtMlBOQT2xJFWdC0gX5JckluSDmdnFSfmpWYVp6clFiaUVBeWZZSVVeSk5GbmV6gA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f(a:s)=a:[x|x<-s,notElem x"aeiou"] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0apY0zbRKrqipsJGt1gnL7/ENSc1V6FCKTE1M79UKfZ/bmJmnoKtQkFpSXBJkU@egopCmoJSYklGamZxrtJ/AA "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 18 bytes ``` s/(?<!^)[aeiou]//g ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX8PeRjFOMzoxNTO/NFZfP/3//0yuxJJUroL8ksSS/H/5BSWZ@XnF/3ULcgA "Perl 5 – Try It Online") [Answer] **APL ([NARS2000 0.5.13.0](http://www.nars2000.org/)), 20 unicode char (so 20 byte or 40 byte?)** ``` (↑,((~∘'aeiou')1∘↓)) ``` Sample output: ``` (↑,((~∘'aeiou')1∘↓)) 'i' i (↑,((~∘'aeiou')1∘↓)) 'ate' at (↑,((~∘'aeiou')1∘↓)) 'potato' ptt (↑,((~∘'aeiou')1∘↓)) 'ksboejqfgcrauxpwivtzndlhmy' ksbjqfgcrxpwvtzndlhmy (↑,((~∘'aeiou')1∘↓)) '' ``` Thanks to the tacit feature added lately. Since APL code chars are unicode chars, I am not sure if one char should be counted as two byte or not. [Answer] # [PHP](https://php.net/), 41 bytes ``` <?=preg_replace("/\\B[aeiou]/","",$argn); ``` [Try it online!](https://tio.run/##K8go@P/fxt62oCg1Pb4otSAnMTlVQ0k/JsYpOjE1M780Vl9JR0lJRyWxKD1P0/r//8SSotTK0n/5BSWZ@XnF/3XdAA "PHP – Try It Online") I wanted to find an original solution but it ends up like everyone's regex.. Deception is my middle name [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 33 30 bytes -3 bytes thanks to @CommandMaster ``` $args-split"(.)[aeiou]"-join'' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyWxKL1Yt7ggJ7NESUNPMzoxNTO/NFZJNys/M09d/f///4lJRYnZpSkg6j8A "PowerShell – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` h|b;Ḅ∋ᵛ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFiQ/3NVZ@3DrhP8ZNUnWD3e0POrofrh19v//0UqZSjpKiSWpQLIgvySxJB/IyC5Oyk/NKkxLTy5KLK0oKM8sK6nKS8nJyK0ESqZWlABtSiwG6cgvyUgtgrJz84tSQcxipVgA "Brachylog – Try It Online") [Generator](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753). ``` | The output is h the first element of the input, | or ∋ᵛ some shared element of |b the input without its first element ;Ḅ and the lowercase consonants. ``` [Answer] # [Factor](https://factorcode.org/), 31 bytes ``` [ 1 cut "aeiou"without append ] ``` [Try it online!](https://tio.run/##DccxDsIwDAXQnVN89QBIrHAAxMKCmBCDSQ0N0NhJHEJBnD10e@9KziS142G3366hic0mTT4YYkXmWDg4zrMsY7OI9QsPMoaKkQke@SJ8j9ebS1TeWv3LPqF/DuOEXzthBVcMHbGX0lVvg8wlVQ49zm0kxbL9AQ "Factor – Try It Online") ## Explanation It's a quotation (anonymous function) that takes one string as input and leaves one string as output. Assuming `"potato"` is on top of the data stack when this quotation is called... * `1` Push one to the data stack. **Stack:** `"potato" 1` * `cut` Cut a sequence into two pieces at a given index. **Stack:** `"p" "otato"` * `"aeiou"` Push a string to the data stack. **Stack:** `"p" "otato" "aeiou"` * `without` Remove elements from NOS (next on stack) that are in TOS (top of stack). **Stack:** `"p" "tt"` * `append` Concatenate two strings. **Stack:** `"ptt"` [Answer] # [Red](http://www.red-lang.org), 33 bytes ``` func[s][trim/with next s"aeiou"s] ``` [Try it online!](https://tio.run/##Tcg7EoAgDADR3lMwuYC9x7BlKFCCxg8gBEUvj51jt28jmtqjkaqxXbXZjTIpyZH29iKehcPCIoFG8hmSqiGSY2EFEDRfa8afgmfN/jfWNHhcDjuNUecSLjr5cWab9xvqCw "Red – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 20 bytes ``` {(*x),(1_x)^"aoeiu"} ``` [Try it online!](https://tio.run/##FcZBEkAgFADQq5i/USYLW@7ChCLhhyKMs2davadz1CHI8iWZp4wUjac1cBTKwRdkShgoqBLgVkQMWm4xTh8timmTQ7dz582lTvus/TwuN9DwAw "K (oK) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` lambda s:s[0]+''.join(filter(lambda x:x not in'aeiou',s[1:])) ``` [Try it online!](https://tio.run/##PY1BDoIwEEX3nqK7tpEYjTsSTlK7KNDKIMzUdlDw8pWFcfPzkpe8HzceCK8lYHMrk5vb3olcZ3O2RylPIwGqABP7pH5yrVeBxAJQOg@0yCqbS221Luwzdy77LBphJMhKOvb7RmLHtMMjt@THZ7h3yS1rfMOLP9hPw7xJezAxAbIKqEBrESgJ2D/EP2rLFw "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~57~~ 55 bytes Saved 2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` lambda s:s[0]+''.join(c for c in s[1:]if{c}-{*'aeiou'}) ``` [Try it online!](https://tio.run/##PY7BTsMwEETv/oq9rQ1tRCkSUiTzI0kObmpTt6ltvBugRPn2ULeC24zeaPTShQ8xbBen22Uw593eANXUPHWPiNUx@iB7cDFDDz4ANZu6827q5/X0gMb6OOKsFrbEpBFReFi/gReGbQmGRYpsOJaSmMWJdtEeP9x7n834nb78J/@E/XA4X8riSu/sSv6BKLdZyxHb8fn1pccV3ONmi0oUM7OyxU0OFaXBs8TyhepmPRRy06uIs09S/Y3agErVAgg0OGmUgJR9YOlwMnN5mGiGKTekte1mVMvyCw "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ΦS¬∧κ№aeiouι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUjDM6@gtCS4BCiUrqGpo@CXX6LhmJeika2j4JxfClSmlJiamV@qpKOQqQkC1v//JyYVJSYnpoCo/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string Φ ¬ Exclude characters where №aeiouι Character is a vowel ∧κ And index is not zero Implicitly print ``` [Answer] # JavaScript (ES6), ~~27~~ 26 bytes *Saved 1 byte thanks to @Neil* Returns a list of characters. ``` s=>s.match(/^.|[^aeiou]/g) ``` [Try it online!](https://tio.run/##jcxLDoIwFIXhuasgTGgHtivAjRhJLqWUIvRWesFH3HttYmIixugZ/9/pYYGgJutp67DRsS1jKHdBjECqY7IS930F2uJ8kIZHhS7goMWAhrUstzkXPVrHioLz7PukzOxmZYH0XzpZoDX2SED42yfs6UMfQ426P7VGTTBf/NkudHPN0I3X98ekU/oMU/aq4gM "JavaScript (Node.js) – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg) `-ir`, ~~34~~ 16 bytes Huge saving thanks to Lyxal. ``` ,(:⅍`aeiou`-[,|_ ``` [Try it online!](https://tio.run/##y05N//9fR8PqUWtvQmJqZn5pgm60Tk38//8FialVmYX5pf91M4sA "Keg – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` +hQ-tQ"aeiou ``` ### Explanation ``` +hQ-tQ"aeiou tQ : Everything except first element of evaluated input - "aeiou : Remove all occurrences of a, e, i, o and u from the string +hQ : Prepend first element of evaluated input ``` [Try it online!](https://tio.run/##K6gsyfj/XzsjULckUCkxNTO/9P9/pezipPzUrMK09OSixNKKgvLMspKqvJScjNxKJQA "Pyth – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~22~~ 19 bytes ``` gsub /\B[aeiou]/,'' ``` [Try it online!](https://tio.run/##BcFNGkAgEADQfaewa8PXHVwDiyLJT5OaQQ5vvJfIFGaXyVSqbzttPdCgaimZvdBoRQTUCGLLBux6zm5Mmp54@wvfMO3LUT6I6CFkbuIP "Ruby – Try It Online") Thanks to Command Master for -3 bytes. [Answer] # [JavaScript (V8)](https://v8.dev/), 42 bytes ``` s=>s[0]+s.substr(1).replace(/[aeiou]/g,'') ``` [Try it online!](https://tio.run/##bco9EsIgEEDh3mOkCYxKtLOJF8mk2CAgEbPILvhzebR20n7vzVCAdPKR9@VUbV@pP9NwGLekKE/ESRylSiYG0EZ0AxiPeezcrm1l1bgQBqMCOmFF4xspN38WkYFxJQCbFb3RhGZ@WKcT5Fd8@sKf5RKu9/dvrl8 "JavaScript (V8) – Try It Online") ]
[Question] [ A biquadratic number is a number that is the fourth power of another integer, for example: `3^4 = 3*3*3*3 = 81` Given an integer as input, output the closest biquadratic number. Here are the first 15 double-squares: ``` 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 14641, 20736, 28561, 38416, 50625 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins This is OEIS [A000583](https://oeis.org/A000583) [Answer] # [Python 3](https://docs.python.org/3/), 35 bytes ``` lambda n:int((n**.5-.75)**.5+.5)**4 ``` [Try it online!](https://tio.run/##LU1BDsIwDLvzCh@TtesoMCFN2ksGhyIoTIVsqnbh9YUwfLET2/L8Xh6T7EvsT@UZXpdrgHSjLERSVa6t3bFlFcYpH0qcMhJGQQ5yv5G38FvuNvhCLVFrIEq11zgM0kqem2ZnQf@TkvkF9Hte64o567RYRBLm8gE "Python 3 – Try It Online") ### How it works The value *n* at which the output switches from (*k* − 1)4 to *k*4 satisfies √(√n − 3/4) + 1/2 = *k*, or *n* = ((k − 1/2)2 + 3/4)2 = (*k*2 − *k* + 1)2 = ((*k* − 1)4 + *k*4 + 1)/2, which is exactly the first integer that’s closer to *k*4. (Works for all *n* ≤ 4504699340341245 = (81924 + 81934 − 7)/2 > 252, after which floating-point roundoff starts to break it, even though it works mathematically for all *n*.) [Answer] # [Octave](https://www.gnu.org/software/octave/), 35 bytes This challenge [needed](https://codegolf.stackexchange.com/questions/131691/find-the-nearest-biquadratic-number/131708#comment323100_131704) a convolution-based approach. ``` @(n)sum(n>conv((1:n).^4,[1 1]/2))^4 ``` [**Try it online!**](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjT7O4NFcjzy45P69MQ8PQKk9TL85EJ9pQwTBW30hTM87kf5qGhSZXmoYliDABM00sNf8DAA "Octave – Try It Online") ### Explanation The expression `(1:n).^4` produces the row vector `[1 16 81 256 ... n^4]`. This vector is then convolved with `[1 1]/2`, which is equivalent to computing the sliding average of blocks of size `2`. This implicitly assumes that the vector is left- and right-padded with `0`. So the first value in the result is `0.5` (average of an implicit `0` and `1`), the second is `8.5` (average of `1` and `16`), etc. As an example, for `n = 9` the result of `conv((1:n).^4,[1 1]/2)` is ``` 0.5 8.5 48.5 168.5 440.5 960.5 1848.5 3248.5 5328.5 3280.5 ``` The comparison `n>...` then yields ``` 1 1 0 0 0 0 0 0 0 0 0 ``` and applying `sum(...)` gives `2`. This means that `n` exceeds exactly `2` of the mid-points betwen biquadratic numbers (including the additional mid-point `0.5`). Finally, `^4` raises this to `4` to yield the result, `16`. [Answer] # [Haskell](https://www.haskell.org/), ~~51~~ 49 bytes Function monad ftw! ``` f n=snd.minimum$(abs.(n-)<$>)>>=zip$(^4)<$>[1..n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7Y4L0UvNzMvM7c0V0UjMalYTyNPV9NGxU7Tzs62KrNARSPOBMSNNtTTy4v9n5uYmadgq1BQWhJcUuSTp6CiUJyRXw6k0hQMjUz/AwA "Haskell – Try It Online") Explanation: ``` (^4)<$>[1..n] -- creates a list of fourth powers (abs.(n-)<$>)>>=zip -- creates a list of |n-(4th powers)| and -- zips it with the 4th powers list minimum -- finds the minimum -- (only first tuple entry matters) snd -- exctracts the second entry (the 4th power) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` t:4^Yk ``` [**Try it online!**](https://tio.run/##y00syfn/v8TKJC4y@/9/I2MA "MATL – Try It Online") ### Explanation Consider input `9` as an example. ``` t % Implicitly input n. Duplicate % STACK: 9, 9 : % Range [1 2 ... n] % STACK: 9, [1 2 3 4 5 6 7 8 9] 4^ % Raise to 4, element-wise % STACK: 9, [1 16 81 256 625 1296 2401 4096 6561] Yk % Closest element. Implicitly display % STACK: 16 ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 5 bytes ``` 𝐈4𝕎S𝕔 ``` Explanation: ``` 𝐈 Inclusive range [1 .. input] 𝕎 Raise to the v power 4 4th 𝕔 Select the value closest to S the input ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCR0mH@ZO7QsGElP@/zc0AAA "Neim – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` ;I≜+.~^₄∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39rzUeccbb26uEdNLY86lv//b2T8PwoA "Brachylog – Try It Online") ### Explanation ``` ;I≜ I = 0 / I = 1 / I = -1 / I = 2 / etc. on backtracking +. Output = Input + I .~^₄ Output = Something to the power 4 ∧ ``` [Answer] ## Excel, 25 bytes ``` =INT((A1^.5-3/4)^.5+.5)^4 ``` Excel updates this to `=INT((A1^0.5-3/4)^0.5+0.5)^4` [Answer] ## Mathematica, 21 bytes ``` Nearest[Range@#^4,#]& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` LnnI.x ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJy/PU6/i/39DUwA "05AB1E – Try It Online") ### Explanation ``` LnnI.x L # Push [1 .. input] nn # Raise every element to the 4th power I # Push input .x # Closest element in the array to input ``` [Answer] ## JavaScript (ES7), 42 bytes ``` x=>(n=x**.25|0,x-(k=n**4)<++n**4-x?k:n**4) ``` ### Recursive version, 44 bytes ``` f=(x,k,b)=>(a=k**4)>x?a-x>x-b?b:a:f(x,-~k,a) ``` ### Demo ``` let f = x=>(n=x**.25|0,x-(k=n**4)<++n**4-x?k:n**4) console.log(f(16)) console.log(f(48)) console.log(f(49)) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 37 bytes ``` @(n)interp1(t=(1:n).^4,t,n,'nearest') ``` Anonymous function that uses nearest-neighbour interpolation. [**Try it online!**](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzMzryS1qMBQo8RWw9AqT1MvzkSnRCdPRz0vNbEotbhEXfN/moaFJleahqXmfwA "Octave – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` R*4ạÐṂ ``` A monadic link returning a list of one item, or a full program that prints the result (using an inefficient method). **[Try it online!](https://tio.run/##y0rNyan8/z9Iy@ThroWHJzzc2fT//39DM0sA "Jelly – Try It Online")** ### How? ``` R*4ạÐṂ - Link: number, n R - range(n) -> [1,2,3,...,n] *4 - raise to the fourth power -> [1,16,81,...,n**4] ÐṂ - filter keep those (only ever one) minimal: ạ - absolute difference (with n) - if a full program: implicit print (one item lists print their content). ``` [Answer] # APL, 22 bytes ``` {o/⍨p=⌊/p←|⍵-⍨o←4*⍨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhOp8/Ue9KwpsH/V06RcA@TWPerfqAkXygWwTLSDjUe9moFAtULXCIRDH0MAAAA) **How?** `o←4*⍨⍳⍵` - `o` = range(`⍵`)4 [vectorize] `p←|⍵-⍨o` - `p` = abs(`o` - `⍵`) [vectorize] `o/⍨` - take the `o` element at the index where ... `p=⌊/p` - the `p` minimum element is [Answer] # [Husk](https://github.com/barbuz/Husk), ~~10~~ 7 bytes *Edit: -3 bytes thanks to Razetime* ``` ◄≠¹m^4ḣ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxYYGBv8fTW951Lng0M7cOBOgyP//AA "Husk – Try It Online") ``` ◄≠¹m^4ḣ ◄ # minimum element based on ≠¹ # difference to input, ḣ # of series from 1 up to input m^4 # to the power of 4 ``` [Answer] # [PHP](https://php.net/), 33 bytes ``` <?=(($argn**.5-.75)**.5+.5^0)**4; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkqWTNZW8HFLPV0AALaWnpmerqmZtqghjaeqZxBkCWifX//wA "PHP – Try It Online") # [PHP](https://php.net/), 56 bytes ``` <?=2*$argn-($x=($f=$argn**.25^0)**4)>($y=++$f**4)?$y:$x; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkbGysZM1lbwcUtTXSAgvqaqhU2GqopNmCeVpaekamcQaaWlommnYaKpW22toqaSCOvUqllUqF9f//AA "PHP – Try It Online") [Answer] **C++, 96 bytes** ``` int Q(int N){int i=1;while (pow(i,4)<N){i++;}if (pow(i,4)-N>N-pow(i-1,4)){i--;}return pow(i,4);} ``` Full version: ``` int Q(int N) { int i = 1; while (pow(i, 4) < N) { i++; } if (pow(i, 4)-N > N-pow(i - 1, 4)) i--; return pow(i,4); } ``` [LINK to try](https://tio.run/##RY5BCoMwEEXX5hTBbiI2RaG72BwhtEcIMdUBE8UkSJGc3UZLcTMz/82H/9U00U6p7QJWDaHVuIHR@VlLw9HJjPT9recoOLAdttJoN0mlsfMt28B6/CL7FMW6L3jUbOlh0JhM40Lgei@a/VWWLML7hFRwQQ9B6ySTg1IWZ@3DbPHfxOIRYCRYUqAVZUcQQ5kCizn/nWPwuGlSC1Ek6T7Oa0PypwxO54mguNVVhb4) [Answer] # Haskell, 35 bytes ``` f n=(floor$(n**0.5-3/4)**0.5+0.5)^4 ``` Port of [Anders' Python3 answer](https://codegolf.stackexchange.com/a/131700/3913). [Answer] # [R](https://www.r-project.org/), ~~47~~ ~~44~~ ~~37~~ 35 bytes ``` n=scan();which.min(((1:n)^4-n)^2)^4 ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMzlDLzczT0NDw9AqTzPORBdIGAHp/yYmhv8B "R – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` .maQb^R4S ``` [Try it online!](https://tio.run/##K6gsyfj/Xy83MTApLsgk@P9/UzMA "Pyth – Try It Online") --- ### [Pyth](https://github.com/isaacg1/pyth), 17 bytes A full program that uses the same arithemtic approach as in [@AndersKaseorg's answer](https://codegolf.stackexchange.com/questions/131691/find-the-nearest-biquadratic-number/131700#131700): ``` K.5^s+^-^QK.75KK4 ``` [Try it online!](https://tio.run/##K6gsyfj/31vPNK5YO043LtBbz9zU29vk/39TMwA "Pyth – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç∞§δo╧╖s►M ``` [Run and debug it](https://staxlang.xyz/#p=80ec15eb6fcfb773104d&i=200) [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 38 bytes ``` {p=q^4~p>:|~p-a>a-o|_Xo\_Xp]\o=p┘q=q+1 ``` ## Explanation ``` { DO infinitely p=q^4 Set p to q quad (q starts out as 1) ~p>:| IF p exceeds the input THEN ~p-a>a-o check the distance to p and to o (the last quad) and |_Xo PRINT o, or \_Xp PRINT p accordingly ] END IF \o=p ELSE ( p <= input) store p in o to keep track of this quad ┘q=q+1 and raise q for the next iteration ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 64 bytes ``` n->{int i=0,q,Q=0;while((q=i*i*i*i++)<n)Q=q;return q-n<n-Q?q:Q;} ``` [Try it online!](https://tio.run/##XVFdb4IwFH33V9yQmMAEgsYZBjKzx8VshLg9GR46KK4OC7RFZwy/ndWKTm2T3px7z/04t2u0RVZRYrpOf9qy/spJAkmOOIc3RCgcegCdlwskpNkWJIWNjOkLwQhdLWNAbMUNRQVYy3p2LUhuZzVNBCmo/UrFJ0VsH5aYIVEwyCBoqfV8IFQACRyzMqPA8XffJMe6XgXkQd3BwJhSIwoqn2FRMwqVRafUimaVF/lNC@r4qqkstIzlIAJzwSEAincX32ksgINjgtOYZzQ0YfiPRjfIvUFPEk2uEie3eOzeYcl3h9d8994hGaPHSaMcjd9TNpN70dXMSoV30mJcxj/uimFe50Lqy2xUlvn@hcvV6kfi0okNv2Mu9lzgjV3Uwi7lB4lM1/rj1AP5gN7nRp9qJnRJZlfzbINABYbxTAvnmqe9hx8Qzk3AvyVOBE5BgwF0lK7hUUbTa9o/ "Java (OpenJDK 8) – Try It Online") [Answer] # Common Lisp, 50 bytes ``` (lambda(x)(expt(floor(+(sqrt(-(sqrt x).75)).5))4)) ``` [Try it online!](https://tio.run/##HcVBCoAgEEbhq7j8h8iVUdcxSxAmNTWY25u4eN9zHGruyCXEpuC/6Cyz6mD7nJeFEG7JDZ5TKlhQ39KwzikhvW9EemSIujkGPw) [Answer] # C#, 95 bytes ``` namespace System.Linq{n=>new int[940].Select((_,i)=>i*i*i*i).OrderBy(i=>Math.Abs(i-n)).First()} ``` We use 940 as a set value as any larger value will overflow the int. Full/Formatted Version: ``` namespace System.Linq { class P { static void Main() { Func<int, int> f = n => new int[940].Select((_, i) => i * i * i * i).OrderBy(i => Math.Abs(i - n)).First(); for (int i = 1; i <= Int32.MaxValue; ++i) Console.WriteLine($"{i} = {f(i)}"); Console.ReadLine(); } } } ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~23~~ 34 bytes I have no idea why `0.75` is such an important number for this, but hey, whatever works. ``` ->n{((n**0.5-0.75)**0.5).round**4} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cur1pDI09Ly0DPVNdAz9xUE8zU1CvKL81L0dIyqf1foJAWnZ5aUqxXkh@fGfvf0NQQAA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~20~~ ~~8~~ 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ~~This feels far too long!~~ I was right! ``` Dz²ÃñaU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=x7Kyw/FhVQ&input=ODg4) ``` Dz²ÃñaU :Implicit input of integer U Ç :Map the range [0,U) ²² : Square twice à :End map ñ :Sort by aU : Absolute difference with U :Implicit output of first element ``` ## Without flag, 8 bytes ``` Ȭ¬v1}cU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yKysdjF9Y1U&input=ODg4) ``` Ȭ¬v1}cU :Implicit input of integer U È :Function taking an integer X as argument ¬ : Square root ¬ : Square root v1 : Divisible by 1? } :End function cU :Return the first X in the sequence [U,U-1,U+1,U-2,U+2,U-3,...] that returns true ``` ]
[Question] [ What general tips do you have for golfing in [Factor](http://factorcode.org)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Factor (e.g. "remove comments" is not an answer). [Answer] # math.unicode this thing is a golfing jewel. <http://docs.factorcode.org/content/vocab-math.unicode.html> Here, I should let it speak for itself. ``` Word Stack effect Equivalent (Byte Char) Savings (best case) ¬ ( obj -- ? ) not 1 2 ² ( m -- n ) 2 ^ , 2^ 1 2 ³ ( m -- n ) 3 ^ 1 2 ¹ ( m -- n ) 1 ^ 1 2 ¼ ( -- value ) 1/4 , 1 4 / 1 2 ½ ( -- value ) 1/2 1 2 ¾ ( -- value ) 3/4 1 2 × ( x y -- z ) * -1 0 ÷ ( x y -- z ) / -1 0 Π ( seq -- n ) product 5 6 Σ ( seq -- n ) sum 1 2 π ( -- pi ) pi 0 0 φ ( -- n ) phi 1 2 ‰ ( m -- n ) 1000 / 4 5 ‱ ( m -- n ) 10000 / 5 6 ⁿ ( x y -- z ) ^ -1 0 ⅓ ( -- value ) 1/3 1 2 ⅔ ( -- value ) 2/3 1 2 ⅕ ( -- value ) 1/5 1 2 ⅖ ( -- value ) 2/5 1 2 ⅗ ( -- value ) 3/5 1 2 ⅘ ( -- value ) 4/5 1 2 ⅙ ( -- value ) 1/6 1 2 ⅚ ( -- value ) 5/6 1 2 ⅛ ( -- value ) 1/8 1 2 ⅜ ( -- value ) 3/8 1 2 ⅝ ( -- value ) 5/8 1 2 ⅞ ( -- value ) 7/8 1 2 ``` Those are the simple constants. Now for the functions: ``` Word Stack effect Equivalent (Byte Char) Savings (best case) ∀ ( seq quot -- ? ) all? 1 3 ∃ ( seq quot -- ? ) any? 1 3 ∄ ( seq quot -- ? ) none? 2 4 ∈ ( elt seq -- ? ) member? 4 6 ∉ ( elt seq -- y ) ∈ ¬ 3 2 ∋ ( seq elt -- ? ) swap member? 9 11 ∌ ( seq elt -- y ) ∋ ¬ 3 2 − ( x y -- z ) - -1 0 ∕ ( x y -- z ) / -1 0 ∖ ( s1 s2 -- set ) diff 1 3 √ ( x -- y ) sqrt 1 3 ∛ ( x -- y ) ⅓ ^ 2 2 ∜ ( x -- y ) ¼ ^ 2 2 ∞ ( -- value ) 1/0. 1 3 ∧ ( o1 o2 -- ? ) and 0 2 ∨ ( o1 o2 -- ? ) or -1 1 ∩ ( s1 s2 -- set ) intersect 6 8 ∪ ( s1 s2 -- set ) union 2 4 ≠ ( o1 o2 -- ? ) = ¬ 1 2 ≤ ( x y -- ? ) <= -1 1 ≥ ( x y -- ? ) >= -1 1 ⊂ ( s1 s2 -- ? ) subset? 4 6 ⊃ ( s1 s2 -- ? ) superset? 6 8 ⊄ ( s1 s2 -- ? ) ⊂ ¬ 3 2 ⊅ ( s1 s2 -- ? ) ⊃ ¬ 3 2 ⊼ ( o1 o2 -- ? ) ∧ ¬ 3 2 ⊽ ( o1 o2 -- ? ) or ¬ 2 3 ⌈ ( x -- y ) floor 2 4 ⌊ ( x -- y ) ceiling 4 6 ``` Yes, I did make that table by hand, and yes, I did the math in my head, so there might be some, er, wrong numbers. I'll go write a program to do it for me, now :P [Answer] ## Treasure trove vocabularies During my time golfing with Factor, these are the non- auto-use vocabularies that have been the most indispensable to me. * [grouping.extras](https://docs.factorcode.org/content/vocab-grouping.extras.html) - Group sequences in various ways. * [math.unicode](https://docs.factorcode.org/content/vocab-math.unicode.html) - Shorter names for math functions, set operations, and useful combinators. * [math.combinatorics](https://docs.factorcode.org/content/vocab-math.combinatorics.html) - Any time you need to get all the combinations or permutations of something, this is your vocab. Comes with tons of great combinators like `filter-permutations` for even more brevity. `nCk` and `inverse-permutation` come in handy sometimes too. * [math.primes](https://docs.factorcode.org/content/vocab-math.primes.html) - Useful for prime number questions. * [math.primes.factors](https://docs.factorcode.org/content/vocab-math.primes.factors.html) - Get the divisors and prime factors of a number. * [math.matrices](https://docs.factorcode.org/content/vocab-math.matrices.html) - Matrix arithmetic, combinators and other operations. * [lists.lazy](https://docs.factorcode.org/content/vocab-lists.lazy.html) - Working with infinite lists is sometimes terser than the alternative. * [sequences.merged](https://docs.factorcode.org/content/vocab-sequences.merged.html) - ~~Mostly for `2merge`, which interleaves two sequences.~~ Use `vmerge` in `math.vectors` instead, since it's an auto-use vocabulary. * [math.text.utils](https://docs.factorcode.org/content/vocab-math.text.utils.html) - ~~Shortest way to get a sequence of digits from a number.~~ This is no longer true since `>dec` was added to the language. Now `>dec 48 v-n` is the shortest way. * [math.extras](https://docs.factorcode.org/content/vocab-math.extras.html) - Lots of specialized math words. You may not need them often, but when the task calls for it, there might be a built-in for it in here. * [spelling](https://docs.factorcode.org/content/vocab-spelling.html) - For the `ALPHABET` word, which is the shortest way to get the alphabet on the stack. * [english](https://docs.factorcode.org/content/vocab-english.html) - Words for natural language processing. * [qw](https://docs.factorcode.org/content/vocab-qw.html) - Shorten literal sequences of strings. * [pair-rocket](https://docs.factorcode.org/content/vocab-pair-rocket.html) - Shorten literal pairs and by extension literal assocs. * [project-euler.common](https://docs.factorcode.org/content/vocab-project-euler.common.html) - Words commonly needed to solve [Project Euler](https://projecteuler.net/) problems. Don't sleep on the individual problem vocabularies either! I've recently used [project-euler.014](https://docs.factorcode.org/content/vocab-project-euler.014.html) and [project-euler.026](https://docs.factorcode.org/content/vocab-project-euler.026.html) for the `collatz` and `period-length` words. #### Some useful auto-use vocabularies you may have overlooked * [math.vectors](https://docs.factorcode.org/content/vocab-math.vectors.html) - A gem of a vocabulary. This lets you do arithmetic with a number and a sequence or two sequences. Plenty of other good stuff in here too. If you find yourself reaching for `2map`, look in here first. * [math.statistics](https://docs.factorcode.org/content/vocab-.html) - Statistics comes up a lot in golf. `histogram`, `cum-sum`, `differences`, `mean`, and `std` are some of my most oft-used words. There's plenty of other great stuff in there too. * [combinators](https://docs.factorcode.org/content/vocab-combinators.html) - Mostly for `to-fixed-point`, which applies a quotation to something until it stops changing. Avoid `case` and `cond`, as they are far too verbose. * [combinators.random](https://docs.factorcode.org/content/vocab-combinators.random.html) - Conditional words based on probability instead of booleans. Extremely useful when called for. * [generalizations](https://docs.factorcode.org/content/vocab-generalizations.html) - Allows you to shuffle the stack in a general way. `dupn` and `repeat` have been especially helpful in golf. * [sequences.generalizations](https://docs.factorcode.org/content/vocab-sequences.generalizations.html) - Words that can apply to any number of sequences. `narray` is also very useful for golf at times. * [sequences.extras](https://docs.factorcode.org/content/vocab-sequences.extras.html) - Words here can shorten your code compared to composing `sequence` words. * [sequences.deep](https://docs.factorcode.org/content/vocab-sequences.deep.html) - Traverse and flatten nested sequences. * [assocs.extras](https://docs.factorcode.org/content/vocab-assocs.extras.html) - Excellent words for working with assocs. * [interpolate](https://docs.factorcode.org/content/vocab-interpolate.html) - This can sometimes be shorter than `formatting` words like `printf`. #### And for those just getting started * [kernel](https://docs.factorcode.org/content/vocab-kernel.html) - Stack shuffling, loops, conditionals, data flow combinators, and other critical functionality. This is the core of the language. Start here. * [math](https://docs.factorcode.org/content/vocab-math.html) - Arithmetic. * [sequences](https://docs.factorcode.org/content/vocab-sequences.html) - Collections. Factor takes the approach of having different implementations all fall under the same `sequence` type, hence the words in this vocabulary will work on most types of collections. * [formatting](https://docs.factorcode.org/content/vocab-formatting.html) - String interpolation. * [assocs](https://docs.factorcode.org/content/vocab-assocs.html) - Associative arrays (dictionaries). With just these five vocabs, you'll get a starting point similar to what most other languages give you. [Answer] Factor is impossible to golf. If you're set on winning, don't use it. --- I don't just mean it's verbose, like Java or C# or Scala. I mean, because of its functional style, there's a small number of ways to write a given program, and `words are long` and `whitespace is not your friend`, so it's a bad target, worse than LISP. Factor's power is in its object model, which is highly verbose. I golf in it because I think it's a cool language, and I enjoy learning it. --- The `::` and `M::` words replace the normal compile word `:`, so that a function has access to lexical variables. [The docs on lexical vars](http://docs.factorcode.org/content/article-locals-examples.html). Why use these over `:`? Because often, referring to variables by name will be shorter than stack-shuffling with `dup swap rot drop over nip etc`. [Answer] ## You are free to trash stdout and stack under the top... ... as long as your submission is a function and the result is returned on the top of the stack. ### Simple example `.` is shorter than `drop`, and `. .` is shorter than `2drop`. (Almost) any object that you will encounter while golfing is printable via `.`, and it has the effect of removing the top item of the stack. ### A real-golfing example (a solution for [Is this number a factorial?](https://codegolf.stackexchange.com/questions/121731/is-this-number-a-factorial), found by golfing [user's answer](https://codegolf.stackexchange.com/a/220863/78410)) ``` [ 1 0 [ 1 + 3dup * 3dup > ] loop . = ] ``` [Try it online!](https://tio.run/##JYxLD4IwEITv/Io5a0J4@QhGr4YLF@PJcGjqIo2lraUciPG31wKH@XayOzst405bf79V9bVEz1y3IG6XvWBywECfkRSnAcaSc5OxQjm8ySqSkJrPmdZO659l6hWSQuMUVXUJJ3QUfZEiQ44CO@xxwBFZgTRLglL8/COcE8zcIn@OBpt1XNCEfm0Q44zG92x2XBKz/g8 "Factor – Try It Online") This is an extreme use of `3dup`s. It stuffs up a lot of stack items every time it is called, but it is valid (because the desired result is at the top of the stack) and correct (because it keeps the loop invariant for top three items). Loop invariant: ``` ( x prod idx ) 1 + ( x prod idx+1 ) 3dup * ( x prod idx+1 x prod' ) ! prod' = prod * (idx + 1) 3dup > ( x prod idx+1 x prod' idx+1 x>prod' ) ``` Since `loop` consumes the boolean at the top on each iteration, the top three items at the start of the next iteration are `( x prod' idx+1 )`. [Answer] When converting between numbers and strings, the ``` string>number number>string ``` words can be shortened to: ``` dec> >dec ``` respectively (thanks, chunes, again!). There are also: * `bin>` and `>bin` for binary * `oct>` and `>oct` for octal * `hex>` and `>hex` for hexadecimal that are all shorter than `n base>`, if they happen to suit your needs! And if you need integers, use `1 /i` instead of `>integer`: ``` 5 3 /i 5 3 / >integer = . => t 5.77 1 /i 5.77 >integer = . => t ``` --- EDIT: If it's about printing, keep an eye on these too: ``` .b ! prints a number in binary .o ! prints a number in octal .h ! prints a number in hexadecimal ``` [Answer] ## Inline whatever you can. All words need ***correct*** stack effect declarations in order to compile. ``` : hello ( -- ) "Hello, World!" print ; ``` These are *long*, even if you use single-char identifiers. ``` : m ( a b c d -- e f ) dup [ asd? ] bi swap = ; ``` Unless you use something so often that the benefits outwiegh the costs, inlining is often shorter, and `: p ( a -- ) print ;` aliasing doesn't save bytes. [Answer] # string literals are special I never realised this before, but `"strings"` are rather special to the parser. ``` "asd""abc" ``` is equivalent to: ``` "asd" "abc" ``` and ``` URL" a"split ``` is the same as ``` URL" a" split ``` This is perhaps the only time whitespace isn't necessary in Factor, and also works for `URL" "`, `DLL" "`, `P" "`, `SBUF" "` and the others handled by `parse-string`, as pointed out by @fedes. in the comments. **Note well** that the opening quote-like marker *must* be preceded by whitespace. The following are considered one word: ``` filter"asdasd"map filter"asdasd" ``` And you will get a `No word <blah> found in current vocabulary search path` error. [Answer] # Get used to multiple ways to write things Usually this means to write something using high-level combinators vs. low-level combinators and/or stack shuffle words. In some cases the former wins, in others the latter wins. Therefore, in order to push Factor golf to the limits, it is good to know both and pick the one that turns out shorter. ### (Re-)Using values in the stack For reusing single value, shuffle words usually win (because [Factor has a large variety of them](https://docs.factorcode.org/content/vocab-kernel.html)): ``` ( n -- np nq) [ p ] [ q ] bi ( n -- np nq) dup p swap q ( n -- np nq nr ) [ p ] [ q ] [ r ] tri ( n -- np nq nr ) dup p over q rot r ( n -- np nq nr ns ) { [ p ] [ q ] [ r ] [ s ] } cleave ( n -- np nq nr ns ) [ p ] [ q ] [ [ r ] [ s ] bi ] tri ( n -- np nq nr ns ) dup p over q pick r roll s ``` But the situation is somewhat different for two or more values, because [spread](https://docs.factorcode.org/content/article-spread-combinators.html) and [apply combinators](https://docs.factorcode.org/content/article-apply-combinators.html) can save a copy or shuffle: ``` ( m n -- mp nq ) [ p ] [ q ] bi* ( m n -- mp nq ) [ p ] dip q ( m n -- mp nq ) q swap p swap ( m n -- mnp mnq ) [ p ] [ q ] 2bi ( m n -- mnp mnq ) [ p ] 2keep q ( m n -- mnp mnq ) 2dup p -rot q ``` I can't list all possible combinations here, and one or two shuffle words can be optimized out depending on context. The lesson here is to find out multiple expressions that do the same thing stack-effect-wise. ### Conditionals and loops Factor has many ways to express some variation of [if](https://docs.factorcode.org/content/article-conditionals.html), [while](https://docs.factorcode.org/content/article-looping-combinators.html), and [boolean logic](https://docs.factorcode.org/content/article-booleans.html). But it also has higher-level combinators to express various common patterns: [`sequences`](https://docs.factorcode.org/content/article-sequences-combinators.html) has `map`, `map-index`, `reduce`, `filter`, `partition` (I believe these are self-explanatory), `accumulate` (cumulative reduce), `replicate` (run n times and collect intermediate values), and `produce` (run until false and collect intermediate results). [`combinators.to-fixed-point`](https://docs.factorcode.org/content/word-to-fixed-point,combinators.html) runs until fixed point is reached. [`math.times`](https://docs.factorcode.org/content/word-times%2Cmath.html) repeats a lambda for the given number of times. Check if some of these high-level combinators work for the task given. If so, try to use them. Otherwise, use the simplest construct: `?` or one-branch variations of `if` for a conditional, `loop` for an unbounded loop, `times` for simple repetition (not involving a sequence or range). ### Bonus: Minimize stack item duplications and reorders When using shuffle words, every time a shuffle word is used, you get +4~6 bytes. Try to minimize their use by duplicating multiple items at once (`2dup`, `3dup`) and reordering inputs and intermediate states. Sometimes multiple library words do the same job but with different input order (e.g. `each` vs. `reduce`); exploit them when possible. [Answer] # `split` doesn't need a `string` sequence as an argument Or, more accurately / generally: # Factor strings are really just sequences of character values Meaning string operations work on sequences of chars too ... which is important because, for instance, `" " split` will split a char-array on the number 32. More directly, this: ``` >string " " split ``` is exactly equivalent to ``` " " split ``` While being 8 chars longer. [Answer] # quotations are lambdas, abuse them Most challenges can be solved with one word definition because of Factor's functional, applicative nature. I just had the sudden realisation that `[ quoting ]` code is the equivalent of a lambda definition in other languages. I don't know why I didn't think of this before... A normal word definition: ``` : f ( a c -- b ) asd asd ; ``` Lamba'd: ``` [ asd asd ] ``` You can do everything inside a `[ quotation ]` that you can inside a `:` word. [Answer] The [`infix` vocabulary](http://docs.factorcode.org/content/article-infix.html) is pretty cool. It allows for infix notation math, which sounds lame since Factor's RPN, but: ``` IN: scratchpad USE: infix IN: scratchpad [infix 5-40/10*2 infix] . -3 ``` For longer expressions it's much shorter than RPN because of whitespace, but you'll need to overcome the `[infix` syntax's length. It also allows Python-style slicing: > > > ``` > USING: arrays locals infix ; > [let "foobar" :> s [infix s[0:3] infix] ] . > "foo" > > ``` > > Additionally, you can step through sequences with seq[from:to:step] > notation. > > > > ``` > USING: arrays locals infix ; > [let "reverse" :> s [infix s[::-1] infix] ] . > "esrever" > > USING: arrays locals infix ; > [let "0123456789" :> s [infix s[::2] infix] ] . > "02468" > > ``` > > [Answer] # Take advantage of auto-use Some people were already implicitly using this to discount imports. Now [it is official](https://codegolf.meta.stackexchange.com/a/20514/78410) (unless the consensus changes). No more `USING: kernel math math.functions sequences ;` -- you can exclude most commonly used library imports from byte count. Caveats: * Actually check that the code does work with auto-use enabled. It can't load obscure libraries (e.g. `xxx.private`), and it cannot load if the word is found in multiple libraries. * If you don't have Factor installed on your machine, you can still check by entering your submission in the code section [on this TIO](https://tio.run/##qyrO@J@cWKJgp1Cnr5eWmFySX6RblKxgY6Pg6u/GFRrsaqVQkFhUnFqkkFhakq9bWpzKBZKAaSnOLy1KToVqhOr6b6ig9x@kSD@/oEQfIgWl0HX8BwA). (Make sure the entire code has no stack effect, i.e. `( -- )`.) If it runs without error, your submission is valid. [Answer] ## Use linked lists when appropriate Using [linked lists](https://docs.factorcode.org/content/vocab-lists.html) is shorter than using arrays when the code involves a lot of dissection at the start (and you don't need sophisticated sequence operations): ``` first (5) > car (3) rest (4) > cdr (3) second (6) > 1 nth (5) > cadr (4) prefix (6) > cons (4) swap prefix (11) > swons (5) unclip (6) = uncons (6) unclip swap (11) > unswons (7) ``` Note that you don't need `USE: lists` because it is `auto-use`d by default. If you see a good Haskell answer which uses pattern matching on a list, there is a good chance that a linked-list based solution is shorter in Factor too. [Answer] ## Use fried quotations to build sequence literals Occasionally, you may need to build sequences with a mix of arguments and constants. It's shorter to do this `'[ 1 _ 1 ]` than this: `1 1 swapd 3array`. `quotation` is an instance of `immutable-sequence`. All sequence words work on them as long as they do not mutate. For instance, you can do the following, no problem: `4 '[ 1 _ 1 ] { 3 4 5 } v+` Keep in mind many words use the type of the first argument (as is the case with `v+`) as an exemplar for what type the result should be. This is usually unimportant but may occasionally be useful to know. Here is a real-world example of when this was useful in a golf: <https://codegolf.stackexchange.com/a/226034/97916> [Answer] # Dip > Swap... so make a call Idiomatic code uses quotations and `dip`, but short code uses `swap`. Look, you can have an extra swap per two `dip`s. ``` [ dip ] [ dip ] [ dip ] [ dip ] [ dip ] swap swap swap swap swap swap swap swap ``` However, sometimes trading `swap` for `dip` makes the code longer in other places, so it's a bit of a re**Factor**ing job. [Answer] # find all the higher-order functions and use them, often Factor is *full* of higher-order functions that take `[ quotations ]` or `other-words` and work on sequences / other data. For example, to take an IP address as a string and sum its fields, you could do: ``` "." split [ 10 >base ] [ + ] map-reduce 10 base> "." split [ 10 >base ] map 0 + reduce 10 base> "." split [ 10 >base ] map sum 10 base> ``` Notice that fancy `map-reduce` is actually longest here because of `[ quotation ]` syntax, but there's already a `sum` word for that anyways, which is far shorter. Here's a place `map-reduce` is shorter: ``` [ "." split [ 10 base> ] [ [ 256 * ] dip + ] map-reduce ] bi@ - abs 1 + ] [ "." split [ 10 base> ] map 0 [ [ 256 * ] dip + ] reduce ] bi@ - abs 1 + ] ``` Can't use `sum` there. [Answer] The following are equivalent ``` [ 1 2 3 ] [ 1 + ] map V{ } clone-like [ 1 2 3 ] [ 1 + ] V{ } map-as ``` It's just `map-as` and the other `-as` words (`zip-as`, `map-as`, `accumulate-as`, etc) are usually shorter than an `obj clone-like` if you're going to use them anyways. [Answer] The following are equivalent: ``` 1 '[ _ blah ] 1 [ blah ] curry ``` It's just that the top one is shorter by three bytes. ]
[Question] [ Given a list of `N` non-negative integers, output those numbers with each left-padded by spaces to a length of `N`. (Alternatively, return a character/string list.) **You may assume that `N` is greater than or equal to the number of digits of the largest number in the list.** Trailing spaces are allowed in the output. You may also take a string containing these numbers, but `N` is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. `["1", "2", "3"]`. This is a code-golf, so the shortest program in bytes wins. ## Test cases ``` input => 'output' 0 => '0' 1 => '1' 2 3 => ' 2 3' 2 10 => ' 210' 4 5 6 => ' 4 5 6' 17 19 20 => ' 17 19 20' 7 8 9 10 => ' 7 8 9 10' 100 200 300 0 => ' 100 200 300 0' 1000 400 30 7 => '1000 400 30 7' 1 33 333 7777 => ' 1 33 3337777' 0 0 0 0 0 0 => ' 0 0 0 0 0 0' ``` [Answer] ## Python, 32 bytes ``` lambda l:'%%%ds'%len(l)*len(l)%l ``` An anonymous function that takes a tuple as input. Either numbers or strings work. Example: ``` l=(1,33,333,7777) '%%%ds' ## A "second-order" format string '%%%ds'%len(l) -> '%4s' ## Inserts the length as a number in place of '%d' ## The escaped '%%' becomes '%', ready to take a new format argument ## The result is a format string to pad with that many spaces on the left '%%%ds'%len(l)*len(l) -> '%4s%4s%4s%4s' ## Concatenates a copy per element '%%%ds'%len(l)*len(l)%l -> ' 1 33 3337777' ## Inserts all the tuple elements into the format string ## So, each one is padded with spaces ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes Code: ``` Dgj ``` Explanation: ``` D # Duplicate the input array g # Get the length j # Left-pad with spaces to the length of the array ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RGdq&input=WzEwMDAsIDQwMCwgMzAsIDdd) or [Verify all test cases](http://05ab1e.tryitonline.net/#code=dnlEZ2pc&input=WzBdLCBbMV0sIFsyLCAzXSwgWzIsIDEwXSwgWzQsIDUsIDZdLCBbMTcsIDE5LCAyMF0sIFs3LCA4LCA5LCAxMF0sIFsxMDAsIDIwMCwgMzAwLCAwXSwgWzEwMDAsIDQwMCwgMzAsIDddLCBbMSwgMzMsIDMzMywgNzc3N10sIFswLCAwLCAwLCAwLCAwLCAwXQ). [Answer] # JavaScript (ES7), 37 bytes ``` a=>a.map(v=>v.padStart(a.length,' ')) ``` Input: Array of strings Output: Array of strings ``` f= a=>a.map(v=>v.padStart(a.length,' ')) ; console.log(f(['0'])) console.log(f(['1'])) console.log(f(['2','3'])) console.log(f(['2','10'])) console.log(f(['4','5','6'])) console.log(f(['17','19','20'])) console.log(f(['7','8','9','10'])) console.log(f(['100','200','300','0'])) console.log(f(['1000','400','30','7'])) console.log(f(['1','33','333','7777'])) console.log(f(['0','0','0','0','0','0'])) ``` [Answer] ## PowerShell v2+, 36 bytes ``` param($a)$a|%{"{0,$($a.count)}"-f$_} ``` Takes input `$a` as an array of `int`egers. Loops through them with `$a|%{...}`. Each iteration, uses the `-f`ormat operator with the optional [`Alignment Component`](https://msdn.microsoft.com/en-us/library/txafckwd(v=vs.110).aspx) (based on `$a.count`) to left-pad the appropriate number of spaces. That resultant string is left on the pipeline. At end of program execution, the resulting strings are all left on the pipeline as an array. --- ### Examples Output is newline-separated on each run, as that's the default `Write-Output` at program completion for an array. ``` PS C:\Tools\Scripts\golfing> @(0),@(1),@(2,3),@(2,10),@(4,5,6),@(17,19,20),@(7,8,9,10),@(100,200,300,0),@(1000,400,30,7),@(1,33,333,7777),@(0,0,0,0,0,0)|%{""+($_-join',')+" -> ";(.\spaced-out-numbers $_)} 0 -> 0 1 -> 1 2,3 -> 2 3 2,10 -> 2 10 4,5,6 -> 4 5 6 17,19,20 -> 17 19 20 7,8,9,10 -> 7 8 9 10 100,200,300,0 -> 100 200 300 0 1000,400,30,7 -> 1000 400 30 7 1,33,333,7777 -> 1 33 333 7777 0,0,0,0,0,0 -> 0 0 0 0 0 0 ``` [Answer] # JavaScript, 49 bytes ``` a=>a.map(n=>" ".repeat(a.length-n.length)+n) ``` Takes the arguments as a list of strings and also returns a list of strings. Explanation: ``` a=> An unnamed function, which takes one argument, a a.map(n=> ) Do the following to each element n in a: " ".repeat(a.length-n.length) Generate the spaces needed to justify the number +n Append the number ``` [Answer] ## Perl, 26 bytes *-4 bytes thanks to @Ton Hospel* 25 bytes of code + `-a` flag. ``` printf"%*s",~~@F,$_ for@F ``` Run with : ``` perl -ae 'printf"%*s",~~@F,$_ for@F' <<< "10 11 12" ``` (On some older version of Perl, you might need to add `-n`) [Answer] # Bash, 14 ``` printf %$#d $@ ``` Input list given at the command line. Not much to explain here. Simply uses built-in [`printf`](http://www.unix.com/man-page/POSIX/1posix/printf/) facilities to do the necessary padding, based off the number of passed args: * `$#` is the number of args passed * `%<n>d` is a printf format specifier that prints an integer with up to n leading spaces * `$@` is the list of all args passed * The format specifier is reused for each member of `$@`. [Ideone](https://ideone.com/PBbSpE). [Answer] # Vim, 19 bytes `YPPG!{<C-F>|R%ri<CR>djVGgJ` Takes a list of numbers one-per-line. Relies on `:set expandtab`, which is popular, but not universal. You clearly want to use `:right` for this. The question is how to get the number of lines onto the command line. The traditional way is `:%ri<C-R>=line('$')`, but all that text is long. The shorter, more enterprising approach is to form the command line using the normal mode `!` command. It involves some weird workarounds, expanding the file by 2 lines then removing them again, but it comes out 2 bytes shorter. And I'm kinda shocked the garbled command line I get (like `:%ri+4!`) actually works, but it does. [Answer] # Ruby, ~~40~~ ~~36~~ 34 bytes ``` ->m{m.map{|i|$><<i.rjust(m.size)}} ``` Can be worked on more. Call as a lambda. Explanation: ``` ->m{m.map{|i|$><<i.rjust(m.size)}} ->m{ } # lambda taking array m m.map{|i| } # map over array using variable i $><< # output to $> (stdout) i.rjust(m.size) # right justify i to m's length ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` L⁶xaUU ``` Input is an array of strings. [Try it online!](http://jelly.tryitonline.net/#code=TOKBtnhhVVU&input=&args=JzEnLCczMycsJzMzMycsJzc3Nzcn) or [verify all test cases](http://jelly.tryitonline.net/#code=TOKBtnhhVVUKw4figqxZ&input=&args=WycwJ10sIFsnMSddLCBbJzInLCczJ10sIFsnMicsJzEwJ10sIFsnNCcsJzUnLCc2J10sIFsnMTcnLCcxOScsJzIwJ10sIFsnNycsJzgnLCc5JywnMTAnXSwgWycxMDAnLCcyMDAnLCczMDAnLCcwJ10sIFsnMTAwMCcsJzQwMCcsJzMwJywnNyddLCBbJzEnLCczMycsJzMzMycsJzc3NzcnXSwgWycwJywnMCcsJzAnLCcwJywnMCcsJzAnXQ). ### How it works ``` L⁶xaUU Main link. Argument: A (array of strings) L Yield the l, the length of A. ⁶x Repeat ' ' l times. U Upend; reverse all strings in A. a Perform vectorizing logical AND, replacing spaces with their corresponding digits and leaving spaces without corresponding digits untouched. U Upend; reverse the strings in the result to restore the original order of its digits, moving the spaces to the left. ``` [Answer] # Mathematica, 25 bytes ``` #~StringPadLeft~Length@#& ``` Both input and output are lists of strings. # Explanation ``` Length@# ``` Get the length of the input (number of element). ``` #~StringPadLeft~... ``` Pad left each element in the input so that their lengths match the length of the input. [Answer] # JavaScript (ES6), 47 Anonymous function, input: array of strings, output: array of strings Using a recursive padding function ``` a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x)) ``` For an integer/string array as input, 49 bytes: ``` a=>a.map(x=>p(x),p=x=>(y=' '+x)[a.length]?x:p(y)) ``` **Test** ``` f= a=>a.map(x=>p(x),p=x=>x[a.length-1]?x:p(' '+x)) function update() { var l=I.value.match(/\d+/g)||[] O.textContent = f(l) } update() ``` ``` <input id=I oninput='update()' value='1000,400,30,7'> <pre id=O></pre> ``` [Answer] # PHP, 55 Bytes ``` <?foreach($a=$_GET[a]as$i)printf("%".count($a)."s",$i); ``` Pevious Version 59 Bytes ``` <?foreach($a=$_GET[a]as$i)echo str_pad($i,count($a)," ",0); ``` [Answer] # J, 4 bytes ``` ":~# ``` [**Try it online!**](https://tio.run/##XY2xDsJADEN3f4VVhm6n5K70KAiJP2EAqpYBBpj59eAidSGJl6fYvkeMx8Rm/9nE7TI9OdLNmCXDHyhSZys@NemQzpmv93V@tG0YHFm/6LhlD6/0QTZU7jgsXDE/v3JY4SxFV1g1UNu6iC8) Unary function taking the list of numbers on the right as an array and returning the padded string. Here it is in use at the REPL. Note that input lines are indented three spaces. ``` f=: ":~# f 2 3 2 3 f 2 10 210 f 1111 222 33 4 1111 222 33 4 ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), 11 bytes ``` lS%_,f{Se[} ``` [Try it online!](http://cjam.tryitonline.net/#code=cU4vezpMOwoKTFMlXyxme1NlW30KCl1ufS8&input=MAoxCjIgMwoyIDEwCjQgNSA2CjE3IDE5IDIwCjcgOCA5IDEwCjEwMCAyMDAgMzAwIDAKMTAwMCA0MDAgMzAgNwoxIDMzIDMzMyA3Nzc3CjAgMCAwIDAgMCAw) (As a test suite.) ### Explanation ``` l e# Read input. S% e# Split around spaces. _, e# Copy and get length. f{ e# Map this block over the list, passing in the length on each iteration. Se[ e# Left-pad to the given length with spaces. } ``` [Answer] # Kotlin, 90 bytes Golfed: ``` fun main(a:Array<String>){a.forEach{b->for(i in 1..a.size-b.length){print(" ")};print(b)}} ``` Ungolfed: ``` fun main(a: Array<String>) { a.forEach { b -> for (i in 1..a.size - b.length) { print(" ") } print(b) } } ``` [Answer] # Haskell, 47 bytes ``` k=length f l=map(\s->replicate(k l-k s)' '++s)l ``` That’s a function from a list of strings to a list of strings, like the JavaScript answers. `replicate` allows one to get a list (Haskell strings are lists of characters) of a given size, so I use it — and the bolded assumption in the problem — to generate the padding (its length is `N` − <length of element>, for each element of the input list). I would have preferred to use a `printf` based solution rather than this one with `replicate` (it would have been shorter, for one thing) but the import statement kills any savings done on the function itself. [Answer] # Java, ~~83~~ 82 bytes ``` a->{String s="";for(int i=a.length,j=i;i-->0;)s+="%"+j+"s";return s.format(s,a);}; ``` Constructs a format string designed to pad the given arguments by a number of spaces equal to the length of the array. The format string is used as an argument for `String.format`, and the result is then returned. The functional interface can accept either a `String[]` or an `Integer[]` or similar. Full class: ``` public class Test { public static void main(String[] args) { java.util.function.Function<Integer[], String> f = a -> { String s = ""; for (int i = a.length, j = i; i-- > 0;) s += "%" + j + "s"; return s.format(s, a); }; System.out.println(f.apply(new Integer[] {0})); System.out.println(f.apply(new Integer[] {2, 10})); System.out.println(f.apply(new Integer[] {7, 8, 9, 10})); System.out.println(f.apply(new Integer[] {1, 33, 333, 7777})); System.out.println(f.apply(new Integer[] {0, 0, 0, 0, 0, 0})); } } ``` [Try it on Ideone.](http://ideone.com/xgiIU8) *-1 byte thanks to @KevinCruijssen.* [Answer] # Groovy, 36 Bytes ``` {a->a.collect{it.padLeft(a.size())}} ``` Takes in array of strings only, outputs array of padded strings. [Answer] # JavaScript 33 bytes similar to @Hedi - but the default padding is ' ', so its 4 chars less ``` a=>a.map(s=>s.padStart(a.length)) ``` ``` f=a=>a.map(s=>s.padStart(a.length)) console.log(f(["0"])) console.log(f(["1"])) console.log(f(["2","3"])) console.log(f(["2","10"])) console.log(f(["17" ,"19" ,"2"])) console.log(f(["1000" ,"400" ,"30" ,"7"])) ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 11 bytes **Solution:** ``` ,/(-#x)$$x: ``` [Try it online!](https://tio.run/##y9bNz/7/X0dfQ1e5QlNFpcLKUMHYGIiMFcyB4P9/AA "K (oK) – Try It Online") **Explanation:** Interpretted right-to-left. Convert to string, and left-pad with length of list, then flatten: ``` ,/(-#x)$$x: / the solution | example: x: / save as 'x' | $ / string | $10 20 30 -> "10","20","30" $ / pad right by left | 5$"abc" -> "abc " ( ) / do the stuff in brackets together | #x / count x | #10 20 30 -> 3 - / negate | ,/ / flatten (concatenate-over) | ,/" a"," b"," c" -> " a b c" ``` [Answer] # MATL, 14 bytes ``` '%%%dd'inYDGYD ``` Try it out at [MATL Online](https://matl.io/?code=%27%25%25%25dd%27inYDGYD&inputs=%5B100+200+300+400%5D&version=19.2.0) This uses formatted string creation by first constructing the format string: `%(NUM)d` and then applies string formatting again using this format string and the input. [Answer] # Pyth - 7 bytes Straightforward answer using padding builtin. ``` sm.[;lQ ``` [Test Suite](http://pyth.herokuapp.com/?code=sm.%5B%3BlQ&test_suite=1&test_suite_input=%5B%220%22%5D%0A%5B%224%22%2C+%225%22%2C+%226%22%5D%0A%5B%22100%22%2C+%22200%22%2C+%22300%22%2C+%220%22%5D%0A%5B%221000%22%2C+%22400%22%2C+%2230%22%2C+%227%22%5D%0A%5B%221%22%2C+%2233%22%2C+%22333%22%2C+%227777%22%5D&debug=0). [Answer] # C#, 39 bytes ``` s=>s.ConvertAll(c=>c.PadLeft(s.Count)); ``` Takes a `List<string>` and outputs a `List<string>`. Explanation: ``` /*Func<List<string>, List<string>> Lambda =*/ s => s.ConvertAll(c => // Create a new List<string> by... c.PadLeft(s.Count) // ...padding each element by 'N' ) ; ``` Would've been a few bytes shorter to use LINQ if the import isn't counted and then returning `IEnumerable<string>` instead of a full blown list: ### C#, 35+18 = 53 bytes ``` using System.Linq;s=>s.Select(c=>c.PadLeft(s.Count)); ``` [Answer] # R, 47 bytes ``` cat(sprintf("%*.f",length(n<-scan()),n),sep="") ``` Reads input from stdin and uses C-style formating with `sprintf`. There should be some way the `cat` function is not needed but couldn't find a way to suppress the quotes on each element without it. If we only want start and end quotes we could use the slightly longer option: ``` paste0(sprintf("%*.f",length(n<-scan()),n),collapse="") ``` ]
[Question] [ Suppose we have two different types of coin which are worth relatively prime positive integer amounts. In this case, it is possible to make change for all but finitely many quantities. Your job is to find the largest amount that cannot be made with these two types of coin. ## Task Input: A pair of relatively prime integers \$(a,b)\$ such that \$1<a<b\$. Output: The largest integer that cannot be expressed as \$ax+by\$ where \$x\$ and \$y\$ are nonnegative integers. ## Scoring: This is code golf so shortest answer in bytes wins. ## Example: Input \$(3,11)\$ \$4\cdot 3- 1\cdot 11=1\$, so if \$n\geq 22\$ we can write \$n=q\cdot 3 + 2\cdot 11 +r\$ where \$q\$ is the quotient and \$r\in\{0,1,2\}\$ the remainder after dividing \$n-22\$ by \$3\$. The combination \$(q+4r)\cdot 3 + (2-r)\cdot 11 = n\$ is a nonnegative combination equal to \$n\$. Thus the answer is less than \$22\$. We can make \$21=7\cdot 3\$ and \$20=3\cdot 3 + 1\cdot 11\$ but it's impossible to make \$19\$ so the output should be \$19\$. ## Test Cases: ``` [ 2, 3] => 1 [ 2, 7] => 5 [ 3, 7] => 11 [ 3, 11] => 19 [ 5, 8] => 27 [ 7, 12] => 65 [19, 23] => 395 [19, 27] => 467 [29, 39] => 1063 [ 1, 7] => error / undefined behavior (inputs not greater than one) [ 6, 15] => error / undefined behavior (not relatively prime). [ 3, 2] => error / undefined behavior (3 > 2) [-3, 7] => error / undefined behavior (-3 < 0) ``` [Answer] # [J](http://jsoftware.com/), ~~7~~,~~6~~ 3 bytes -1 byte thanks to FrownyFrog ! -3 bytes thanks to Grimmy! ``` *-+ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tXS1/2tyKXClJmfkKxgppCkYI5jmEKYxKtPQEMI2BbItIExzkLARhG1oCeQYGSNzoJqNQBxjy/8A "J – Try It Online") ``` - subtract + the sum of the arguments * from their product ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ←¤*← ``` [Try it online!](https://tio.run/##yygtzv7//1HbhENLtIDk////zf@bAgA "Husk – Try It Online") # Explanation As proved in lots of places, the answer for inputs `a` and `b` is `ab-a-b = (a-1)(b-1)-1`. `¤` is the 'combine' combinator, so `¤*←` is a function that applies `←` (decrement) to each argument and 'combines' the results by multiplication. Then I decrement the result to get the final output. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 8 bytes ``` 1##-+##& ``` [Try it online!](https://tio.run/##RcqxCoAgFIXhVzlwoSUdVKIcCh@hPRokihpqCDfx2c3bUNP/cTinD/t6@nAsPm/osyKSNVGVx/u4whSJEuSAbSKaZ1RwziFGLWCSALflmr9KMRqBjtuWQTOUFdDm0/vWRcamlB8 "Wolfram Language (Mathematica) – Try It Online") --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` FrobeniusNumber ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@tKD8pNS@ztNivNDcpteh/QFFmXkm0soKunUJatHJsrIKagr6DQnW1kY6Cca2OAog2B9HGCNrQEMQw1VGwANHmQAEjEMPQUkfByBjOAqs2ArKMLWtr/wMA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` <P< ``` [Try it online!](https://tio.run/##yy9OTMpM/W/p5mKvpGBrp6Bk/98mwOa/zv9oBSMdBQXjWC4IwxzEMEZiGBqCGKZAEQsQwxwoYgRkGFrqKBgZwxggxUZAhrFlLAA "05AB1E – Try It Online") ``` < # decrement both inputs P # product < # decrement ``` [Answer] # [Python 3](https://docs.python.org/3/), 18 bytes ``` lambda a,b:a*b-a-b ``` [Try it online!](https://tio.run/##K6gsycjPM/6fpmCrEPM/JzE3KSVRIVEnySpRK0k3UTfpf6KOQhJQLjexQCMzr0RHITOvoLREQ1OvuCAnE0hrcnEVFAElNNI0QCo1Nf8bWSoYWwIA "Python 3 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~43~~ 13 bytes ``` (*-1)*(*-1)-1 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0NL11BTC0zqGv635ipOrFRIUzDSUTBGYpvD2MaobENDGMdUR8ECxjYHShjBOIaWOgpGxig8uAlGQJ6xpfV/AA "Perl 6 – Try It Online") Turns out there's a much shorter way to calculate the answer. # [Perl 6](https://github.com/nxadm/rakudo-pkg), 43 bytes ``` ->\a,\b{max ^(a*b)∖((a X*^b)X+(^a X*b)):} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX9cuJlEnJqk6N7FCIU4jUStJ81HHNA2NRIUIrbgkzQhtjTgQM0lT06r2f3FipUKagpGOgrE1F5xtDmMbo7INDWEcUx0FCxjbHChhBOMYWuooGBmj8OAmGAF5xpbW/wE "Perl 6 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 bytes ``` ×-+ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/////B0Xe3/aY/aJjzq7XvUN9XT/1FX86H1xo/aJgJ5wUHOQDLEwzP4v5GlQpqCsSUA "APL (Dyalog Unicode) – Try It Online") Dyadic train where `a f b` computes `(a×b)-(a+b)`. # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ×_+ ``` [Try it online!](https://tio.run/##y0rNyan8///w9Hjt////G1n@N7YEAA "Jelly – Try It Online") Dyadic link that takes two numbers `a` and `b` as left and right arguments. Works the same as the APL version, just with the symbol `_` instead of `-` to represent subtraction. [Answer] # [C (clang)](http://clang.llvm.org/), ~~31~~ 22 bytes ``` f(a,b){return~-a*b-a;} ``` [Try it online!](https://tio.run/##jdDRCoIwFAbge59iGMIWx2COWMPyRaqL6bQGtsL0SuzV1za6bt6cnwMfP5zT5E0vzc3aDkuoyTy04zSYTy63dS7LxW60afpJtcf3qPRzd68SbUb0kNpgMifoNbi1w@k5U4AydUWnysXFpFAAgw67SUj53/HgeNSt62Ohj0X7GFAaIKURuYeDg25GHAdaOOgjIqmAwl8TcoXlPxv9kQAm/Jd8ervYLw "C (clang) – Try It Online") Saved 9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` P_S ``` [Try it online!](https://tio.run/##y0rNyan8/z8gPvj///9GljrGlgA "Jelly – Try It Online") A monadic link taking a pair of integers. Same method as most other answers (product minus sum). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` -*FQs ``` [Try it online!](https://tio.run/##K6gsyfj/X1fLLbD4/39THQsA "Pyth – Try It Online") Product minus sum. ``` t*FtM ``` [Try it online!](https://tio.run/##K6gsyfj/v0TLrcT3/39THQsA "Pyth – Try It Online") a,b -> (a-1)\*(b-1)-1 [Answer] # [C (gcc)](https://gcc.gnu.org/), 18 bytes ``` f(a,b){a=~-a*b-a;} ``` Noodle9's answer except using `a=` instead of `return`. [Try it online!](https://tio.run/##jdDRCsIgFAbg@z2FLAYaZ4GTMFnbi1QXTtsSyqLW1Vivbipd527Oz4GPH85R5aCUcz2W0JFJNp9SrrtS1rNbGauub33ev0Zt7ptLmxk7ops0FpMpQ4@nX3ucHwoNqNAn1LQ@jjaHChj02E9C6v@OR8eTblkfi30s2ceA0ggpTcgt7Dz0M@E40MrDEAlJBVThmpgLLP/Z5I8EMBG@FDLY2X0B "C (gcc) – Try It Online") [Answer] # Java 8, 13 bytes ``` a->b->a*b-a-b ``` [Try it online.](https://tio.run/##jZAxb4MwEIV3fsWJCYptCVCV0qSMlTp0yth2OBOITByD4iNSVOW3UwdZqpupi/W@u5Pfu@vxjLzfHeZGo7Xwjsp8RwCWkFQDveuKiZQW3WQaUoMRr15s3gy1@/bE/jfkRV1DBy8z8lryGh8kRy7ndeQcx0lq5@iNz4PawdGFSbZ0Umb/8QWY3oIBUGspKViZrkNchVjeY56H/MieQlyxvAg5r1hR3hf@fFhUrKyWwjX6PdaSeekrQ4Ds9kofenux1B7FMJEY3T6kTYJZzOJMZvHzJ8VZJ3Ac9SXB1AuZeoPr/AM) **Explanation:** Similar as most other answers, it calculate the product minus the sum: ``` a->b-> // Method with two integer parameters and integer return-type a*b // Return the two parameters multiplied by each other, -a-b // after we've also subtracted both parameters from this product ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 59 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N S _Duplicate_input][S N S _Duplicate_input][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S N S _Duplicate_input][S T S S T S N _Copy_0-based_2nd][T S S N _Multiply_top_two][S N T _Swap_top_two][T S S T _Subtract_top_two][S N T _Swap_top_two][T S S T _Subtract_top_two][T N S T _Print_as_integer_to_STDOUT] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIQuVwghAXJ1gRJ5QDojiBqv7/N7LkMrYEAA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer a = STDIN as integer Integer b = STDIN as integer Integer c = a * b c = c - a - b Print c as integer to STDOUT ``` Not much golfing involved, except for using the first input as heap-address for the second input, since it's guaranteed to be positive and we push it to stack right away. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes ``` t*thQte ``` [Try it online!](https://tio.run/##K6gsyfj/v0SrJCOwJPX//2gjSx1jy1gA "Pyth – Try It Online") Uses the formula (a-1)(b-1) - 1. Takes input as a Python array of 2 integers. -1 by using implicit appended Q [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ×-Ux ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1y1VeA&input=WzI5LCAzOV0) [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 5 bytes ``` *¿¿+- ``` Simply a port of other answers. Uses latest github interpreter. [Answer] # Excel, 12 bytes ``` =A1*B1-A1-B1 ``` Same approach as other answers. [Answer] # [JavaScript (V8)](https://v8.dev/), 13 bytes ``` a=>b=>a*b-a-b ``` [Try it online!](https://tio.run/##NY5NDoMgEIX3nmLiSpqhKRCrNsGLGBZopGlDpBHipunZqWCczTcz783PW2/aT@vrE@jWRiOjlv0oe30ZqaZjtHOAMPvgQcIwcBQKYUeTIE4wllhjm9Ag44msQ767M7OPdwiiyxJC7twRWH2sgDxDRVJUYdwK1XkanDleIPAtYI/JLd7Z@Wrds0oCQvkoEUwuhpsiR8IUIcUv/gE "JavaScript (V8) – Try It Online") Same solution as other answers, I almost didn't post it but for once I found a question without a JS answer, so may as well. In fact this is the exact same as Kevin Cruijssen's answer, replacing Java's lambda `->` with Javascript's `=>`. I've included a very basic testing framework in my TIO link so it does all the test cases. Most invalid inputs still execute. [Answer] # Brainf\*ck, 36 bytes Cell layout: cells 1 and 2 are input, cell 3 is where the final answer is built, cell 4 is auxiliary ``` ,->,-<[->[->+>+<<]>>[-<<+>>]<<<]>>-. ``` Or, with words: ``` ,- read a and decrement > move to cell 2 ,- read b and decrement < move back to a [- while a isn't 0, decrement once and > move to b (to add b to cells 3 and 4) [- decrement b >+>+<< add 1 to cells 3 and 4, go back to b ] >> move to cell 4 [-<<+>>] copy cell 4 to cell 2 (i.e. put b again in cell 2 <<< move back to a ] >>-. go to cell 3, decrement and output ``` [Try it online](https://copy.sh/brainfuck/?c=LC0-LC08Wy0-Wy0-Kz4rPDxdPj5bLTw8Kz4-XTw8PF0-Pi0u) - this is not a link to tio.run. In this site I linked I was able to give input as `\02\05` so that I could try smaller test cases, and I also get a "memory dump" to check the weird characters that were printed actually correspond to the answer. Here, have a [tio.run](https://tio.run/##SypKzMxLK03O/v9fR9dOR9cmWtcOiLTttG1sYu2ATBsbbTu7WBswT1fv/38A) link as well. [Answer] # AWK, 14 bytes ``` $0=$1*$2-$1-$2 ``` [Try it online!](https://tio.run/##HYuxDYAwEMT6m@KKr5AicfcKIQXDUDMA4z8RhV3Z9/tUxX6FtnALtXCVmTAH8kdC54lBGZp0/h7wZE5oNQfVV2i0dXw "AWK – Try It Online") Assumes input in the form of `x y`. [Answer] # [R](https://www.r-project.org/), 11 7 bytes ``` a*b-a-b ``` Where `a` and `b` are the 2 numbers. Thanks to Jo King for pointing out my error. ]
[Question] [ # Winner: [Chilemagic](https://codegolf.stackexchange.com/a/37113/10961), a massive 21 bytes! You may continue to submit your answer, however you can no longer win. Original post kept: --- Your goal is to find all numbers in a string, and multiply each one individually by a value input by the user * You will not need to worry about decimals * The user will input a number and a string * The user must type the number and string at some point, **however** the method the program reads it does not matter. It can be with stdin, reading a text file, etc, however the user must press the 9 button on their keyboard (for example) at some point * Anything that can compile and run is acceptable # Example: Sentence input: This 1 is22a 3352sentence 50 Number input: 3 Output: This 3 is66a 10056sentence 150 --- * This contest ends on September 6th, 2014 (7 days from posting). * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins [Answer] ## Update - Perl - 17 ``` s/\d+/$&*$^I/ge ``` 15 characters + 2 for `-i` and `-p` flags. We can use the `-i` flag to input a file extension, but since we aren't reading any files, we can use it to get the number and it the variable `$^I` will get assigned to it. Run with: ``` perl -e'print"This 1 is22a 3352sentence 50"' | perl -i3 -pe's/\d+/$&*$^I/ge' ``` ## Perl - 21 Updated as per @Dennis's comment. ``` $n=<>;s/\d+/$&*$n/ge ``` Run with `-p` flag. ## Example run: ``` perl -e'print"This 1 is22a 3352sentence 50\n3"' | perl -pe'$n=<>;s/\d+/$&*$n/ge' ``` ## Explanation: `$n=<>;` read in the number `-p` prints the output `s/\d+/$&*$n/ge` Read the input with <> and search for one or more digits and replace them with the digits times the number. `g` is global, `e` is `eval` the replace potion of the s///. `$&` contains what was matched and it multiplied by the number, `$n`. You can read more about `s///` in [perlop](http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators) and more about Perl regexes in [perlre](http://perldoc.perl.org/perlre.html). ## Another solution: @F.Hauri pointed out you can also use the `s` [switch](http://perldoc.perl.org/perlrun.html#Command-Switches) to assign the `$n` variable to 4. I'm not sure how many characters this counts as but I'll leave it here: ``` perl -spe 's/\d+/$&*$n/ge' -- -n=4 <<<'This 1 is22a 3352sentence 50' ``` [Answer] # JavaScript (ES6) - ~~48~~ 44 chars Thanks to [@bebe](https://codegolf.stackexchange.com/questions/37110/multiply-all-numbers-in-a-string/37127?noredirect=1#comment83985_37127) for saving one character. Update: 8/Mar/16, removed another four characters ``` b=(p=prompt)();p(p().replace(/\d+/g,y=>y*b)) ``` **Ungolfed**: ``` var sentence = prompt(), num = parseInt(prompt(), 10); // base 10 sentence = sentence.replace(/\d+/g, digit => digit * num); alert(sentence); ``` ### 43 chars: ``` (p=prompt)(p(b=p()).replace(/\d+/g,y=>y*b)) ``` ``` b=(p=prompt)();p(p().replace(/\d+/g,y=>y*b)) ``` Requires number input first and then sentence. Cut one char more here thanks @bebe again! [Answer] ## Python 2 (79) ``` import re n=input() s=input() print re.sub('\d+',lambda x:`int(x.group())*n`,s) ``` ### Sample run Input: ``` $ python mult.py 3 "This 1 is22a 3352sentence 50" ``` Output: ``` This 3 is66a 10056sentence 150 ``` Online demo: <http://ideone.com/V6jpyQ> [Answer] # Python 2 - 126 ``` import re n=input() s=input() for i in list(re.finditer('\d+',s))[::-1]:s=s[:i.start()]+`int(i.group())*n`+s[i.end():] print s ``` First input: integer `n`. Second input: string `s` (with quotation marks, e.g. `"abc42"`). [Answer] # CJam, ~~47~~ ~~33~~ 30 bytes ``` q_A,sNerN%\[_A,s-Ner~](f*]zs1> ``` Reads the number and the string (in that order and separated by a single space) from STDIN. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Example run ``` $ cjam multiply.cjam <<< '7 N0 R3GUL4R 3XPR35510N5 1N CJ4M M4K3 M3 4 54D P4ND4' N0 R21GUL28R 21XPR248570N35 7N CJ28M M28K21 M21 28 378D P28ND28 ``` ### How it works ``` q " Read from STDIN (“Q”) and push a second copy. "; A,s " Push “0123456789” (thanks, @aditsu). "; _ NerN% " Replace digits with linefeeds and split at linefeeds. "; \ _A,s-Ner " Replace non-digits with linefeeds. "; ~ " Evaluate the resulting string. "; [ ] " Collect the results in an array. "; (f* " Multiply all other integers by the first. "; ]z " Interleave the elements of both arrays. "; s1> " Flatten the result and discard the leading space. "; ``` [Answer] # Bash+coreutils, 38 bytes ``` eval echo `sed "s/[0-9]\+/$\[$1*&]/g"` ``` Reads input string from STDIN and multiplier as a command-line parameter. ### Output: ``` $ ./multstr.sh 3 <<< "This 1 is22a 3352sentence 50" This 3 is66a 10056sentence 150 $ ``` [Answer] # C# in LINQPad, 124 Straightforward. Please use **CTRL+2** in LINQPad (Language: C# Statements). ``` var s=Console.ReadLine();var k=int.Parse(Console.ReadLine());new Regex("\\d+").Replace(s,t=>""+int.Parse(t.Value)*k).Dump(); ``` If the multiplier is given as first input parameter, it can be done in 116 characters: ``` var k=int.Parse(Console.ReadLine());new Regex("\\d+").Replace(Console.ReadLine(),t=>""+int.Parse(t.Value)*k).Dump(); ``` --- **EDIT:** Thanks to Abbas's comment below, this can even be golfed more by using [Regex static method](http://msdn.microsoft.com/en-us/library/e7f5w83z(v=vs.110).aspx), rather than instantiate it: ``` var k=int.Parse(Console.ReadLine());Regex.Replace(Console.ReadLine(),"\\d+",t=>""+int‌​.Parse(t.Value)*k).Dump(); ``` [Answer] # Cobra - 171 ``` use System.Text.RegularExpressions class P def main a=int.parse(Console.readLine?'') print Regex.replace(Console.readLine,'\d+',do(m as Match)="[int.parse('[m]')*a]") ``` [Answer] # Python 3 - 141 I don't think I can golf this any more... ``` import re n=input() f=input() o='' p=0 for i in re.finditer('\d+',f):o+=f[p:i.start()]+str(int(i.group())*int(n));p=i.end() o+=f[p:] print(o) ``` Example: ``` 3 # This is input h3110 # This is input h9330 # This is output 10 hello100 hello100 hello1000 hello1000 ``` [Answer] # Mathematica ~~71~~ 61 With 10 chars saved thanks to Martin Buttner. Spaces in code are for readability. `f` is a function in which `s` is the input string and `n` is the number to multiply discovered string numbers by. ``` StringReplace[#, a : DigitCharacter .. :> ToString[#2 FromDigits@a]] & ``` --- ## Examples ``` s="This 1 is22a 3352sentence 50" ``` Integer ``` StringReplace[#, a : DigitCharacter .. :> ToString[#2 FromDigits@a]] &@@{s, 3} ``` > > "This 3 is66a 10056sentence 150" > > > --- [Answer] ## Ruby 40 ``` a,b=$* p a.gsub(/\d+/){|s|s.to_i*b.to_i} ``` Input from stdin. Example run: ``` $ ruby mult.rb "This 1 is22a 3352sentence 50" 3 "This 3 is66a 10056sentence 150" ``` Online demo: <http://ideone.com/4BiHC8> [Answer] # Lua: ~~73~~ 69 characters ``` r=io.read s=r()n=r()s=s:gsub("%d+",function(m)return m*n end)print(s) ``` Sample run: ``` bash-4.3$ lua -e 'r=io.read;s=r()n=r()s=s:gsub("%d+",function(m)return m*n end)print(s)' <<< $'This 1 is22a 3352sentence 50\n3' This 3 is66a 10056sentence 150 ``` [Answer] ## JavaScript, ES6, 43 characters This is my first attempt at golfing! ``` (p=prompt)(p(n=p()).replace(/\d+/g,y=>y*n)) ``` Run this in latest Firefox's Console. The first input is the number and the second input is the string from which the numbers are to be multiplied with the first input number. The final prompt lists the output. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 8 bytes ``` ⁽±Ḋƛ⌊⁰*∨ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4oG9wrHhuIrGm+KMiuKBsCriiKgiLCIiLCIxMzR0aGlzIDEyM3Rlc3Qgc3RyaW5nNTQgMTAwXG4zIl0=) [Answer] # Perl - 48 chars ``` $n=<>;print/\d/?$_*$n:$_ for(<>=~/(\d+)|(\D+)/g) ``` Read a number on the first line, then read a sentence and break it into chunks of either digits or non digits. Print the non digits as they are, and the numbers get multiplied. [Answer] # J - 63 char Program reads in the number, and then the sentence. ``` ;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1 ``` Explained by explosion: ``` ;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1 1!:1]1 NB. read sentence e.&'0123456789' NB. is digit? bool vector i=. NB. save to i 2 /\ NB. between adjacent chars: ~: NB. true if not equal 1, NB. pad to sentence length ( ;.1~ ) NB. cut the sentence ^:(0{i) NB. if cut is digits: *&.". NB. multiply as number &(1!:1]1) NB. with user input ; NB. rejoin sentence ``` If we get to use J's PCRE library and make the sentence come first, we can knock this down to **54 characters**: ``` ;_2(,*&.".&(1!:1]1)&.>)/\'\d+'(rxmatches rxcut])1!:1]1 ``` Explained by explosion: ``` 1!:1]1 NB. read in sentence '\d+'(rxmatches ) NB. all /\d+/ matches ( rxcut]) NB. cut by those matches _2 \ NB. on each nonmatch-match pair: ( &.>)/ NB. take the match *&.". NB. multiply as number &(1!:1]1) NB. by user input (, ) NB. prepend nonmatch ; NB. rejoin sentence ``` J is bad at this, what can I say. It's a inconvenient because J's so nonimperative. Some examples: ``` ;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1 3 This 1 is22a 3352sentence 50 This 3 is66a 10056sentence 150 ;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1 100 N0 R3GUL4R 3XPR35510N5 1N J M4K35 M3 54D ALS0 N0 R300GUL400R 300XPR3551000N500 100N J M400K3500 M300 5400D ALS0 0!:0 <'system\main\regex.ijs' NB. this is usually preloaded by J on startup anyway ;_2(,*&.".&(1!:1]1)&.>)/\'\d+'(rxmatches rxcut])1!:1]1 TH4T'5 M4RG1N411Y B3TT3R 0 TH0T'0 M0RG0N0Y B0TT0R ``` [Answer] # CJam - 35 ``` li:X;lN+{_sA,s-,{])\_!!{iX*}*oo}*}/ ``` Try it at <http://cjam.aditsu.net/> Sample input: ``` 7 CJ4M W1LL H4V3 R3GUL4R 3XPR35510N5 L4T3R ``` Sample output: ``` CJ28M W7LL H28V21 R21GUL28R 21XPR248570N35 L28T21R ``` **Explanation:** The program goes through each character, collecting the digits on the stack, and for each non-digit it first prints the collected number (if any) multiplied by the numeric input, then prints the character. `li:X;` reads the numeric input and stores it in X `lN+` reads the string and appends a newline (it helps with trailing numbers) `{…}/` for each character in the string - `_s` copies the character and converts to string - `A,s-,` removes all the digits and counts the remaining characters; the result will be 0 if the character was a digit or 1 if not - `{…}*` executes the block if the count was 1 (i.e. non-digit); for digits it does nothing, so they remain on the stack -- `]` collects the characters from the stack into an array (i.e. a string); the characters are any digits from the previous iterations, plus the current character -- `)\` separates the last item (the current character) and moves it before the (remaining) string -- `_!!` copies the string and converts it to a boolean value - 0 if empty, 1 if not -- `{…}*` executes the block if the string was not empty, i.e. we had some digits before the current non-digit character --- `iX*` converts the string to integer and multiplies by X -- `o` prints the top of the stack - either the multiplied number or the empty string if we didn't have a number -- `o` (the 2nd one) prints the new top of the stack - the current non-digit character [Answer] # Haskell (161) ## Golfed ``` main=do{n<-getLine;l<-getContents;let{g c(t,s)|c>'/'&&c<':'=(c:t,s)|t/=""=([],c:(show.(*(read n)).read$t)++s)|True=(t,c:s)};putStr.tail.snd.foldr g("","")$' ':l} ``` ## Ungolfed ``` modify :: (Show a, Read a) => (a -> a) -> String -> String modify f = show . f . read main=do number <- fmap read $ getLine -- get number l <- getContents -- get input -- if the current character is a digit, add it to the digits -- if the current character isn't a digit, and we have collected -- some digits, modify them and add them to the string -- otherwise add the current characters to the string let go current (digits , string) | current `elem` ['0'..'9'] = (current : digits, string) | not (null digits) = ([], current:(modify (*number) digits) ++ string) | otherwise = (digits, current:string) -- since the result of `go` is a pair, take the second value, -- remove the head (it's a space, in order to convert digits at the start) -- and print it putStr . tail . snd . foldr go ("","")$' ':l ``` Unfortunately, Haskell doesn't have a Regex library in its [Prelude](http://hackage.haskell.org/package/base-4.7.0.1/docs/Prelude.html). [Answer] # flex(-lexer) (94 89 characters) ``` int m;main(c,v)char**v;{m=atoi(*++v);yylex();} %% [0-9]+ {printf("%d",m*atoi(yytext));} ``` Ungolfed version which doesn't segfault if you forget the command-line argument (not much longer): ``` %{ #define YY_DECL int y(int m) %} %option noyywrap noinput nounput %% [0-9]+ {printf("%d",m*atoi(yytext));} %% int main(int argc, char** argv) { return (argc > 1) ? y(atoi(argv[1])) : 1; } ``` Compile with: ``` flex -o m.c m.l cc -o m m.c -lfl ``` or: ``` flex --noyywrap -o m.c m.l cc -o m m.c ``` Eg: ``` $ ./m 163 This 1 is22a 3352sentence 50 This 163 is3586a 546376sentence 8150 ``` [Answer] # [`Groovy` - 124](http://ideone.com/eOJGmC) ``` Scanner s=new Scanner(System.in) def x=s.nextLine() def n=s.nextInt() x=x.replaceAll(/\d+/,{it->it.toInteger()*n}) println x ``` *Click on the title to see the runnable example* # Examples Tried: > > This 1 is22a 3352sentence 50 > > 3 > > This 3 is66a 10056sentence 150 > > > --- > > This 1 is22a 3352sentence 50 > > 42 > > This 42 is924a 140784sentence 2100 > > > [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` r"%d+"_*V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIlZCsiXypW&input=IlRoaXMgMSBpczIyYSAzMzUyc2VudGVuY2UgNTAiCjM) [Answer] # GNU Awk: 86 characters ``` s{n=split(s RS,a,/[^0-9]+/,d);while(++i<n)printf"%s%s",a[i]==""?"":a[i]*$1,d[i]}{s=$0} ``` Sample run: ``` bash-4.3$ awk 's{n=split(s RS,a,/[^0-9]+/,d);while(++i<n)printf"%s%s",a[i]==""?"":a[i]*$1,d[i]}{s=$0}' <<< $'This 1 is22a 3352sentence 50\n3' This 3 is66a 10056sentence 150 ``` [Answer] # PHP - 75/115 68/109 Two versions, newer php versions can do this: ``` echo preg_replace_callback("/\d+/",function($m){return$m[0]*$f;},$s); ``` Older php versions: I did not count the newline, added those for readability. ``` function a($s){echo preg_replace_callback("/\d+/",b,$s);} function b($i){global$f;return$i[0]*$f;} a($s,$f); ``` Example input+output ``` $s = "ab11cd22"; // string $f = 3; // -> output: ab36cd69 $f = -2; // -> output: ab-24cd-46 ``` Kinda difficult, the words 'function' and 'preg\_replace\_callback' take up a lot of chars. The space after `global` and `return` arent needed if followed by a $var (-2 chars) [Answer] ## C (~~142~~ 134 characters) ``` main(a,b)char**b;{char*c=b++[2],*d="0123456789";for(;*c;c+=strspn(c ,d))write(1,c,a=strcspn(c,d)),dprintf(1,"%d",atoi(*b)*atoi(c+=a));} ``` Newline inserted for enhanced legibility. Pass the factor as the first, the string as the second command line option. This implementation requires the `dprintf` function which is part of POSIX.1 2008 and might not be available on Windows. Here is the unminified source: ``` /* * Multiply all numbers in a string by a number. * http://codegolf.stackexchange.com/q/37110/134 * Solution by user FUZxxl */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> extern int main(int count, char **argv) { char *str = argv++[2], *digits = "0123456789"; while (*str) { /* as long as we have not reached the end */ count = strcspn(str, digits); write(1, str, count); dprintf(1, "%d", atoi(*argv) * atoi(str += count)); str += strspn(str, digits); } } ``` ## Improvements * 142 → 134: Use `strspn` and `strcspn` instead of looping over the string. [Answer] # Python 89 ``` import re,sys j,n,s=sys.argv print re.sub('(\d+)',lambda m:str(int(m.group())*int(n)),s) ``` eg: ``` # python numberstring.py 3 '1shoop da2 w007p!' 3shoop da6 w21p! ``` [Answer] # Rebol - 117 ``` n: do input d: charset"0123456789"parse s: input[any[b: some d e:(e: insert b n * do take/part b e):e | skip]]print s ``` Ungolfed: ``` n: do input d: charset "0123456789" parse s: input [ any [ b: some d e: (e: insert b n * do take/part b e) :e | skip ] ] print s ``` [Answer] ## Clojure - 141 140 128 chars I'm a Clojure newbie, but FWIW: ``` (let[[a b]*command-line-args*](println ((fn[s n](clojure.string/replace s #"\d+"#(str(*(read-string %)(read-string n)))))a b))) ``` Sample run: ``` bash$ java -jar clojure-1.6.0.jar multstr.clj "This 1 is22a 3352sentence 50" 3 This 3 is66a 10056sentence 150 ``` Ungolfed (ugly but hopefully somewhat easier to read): ``` (let [[a b] *command-line-args*] (println ( (fn [s n] (clojure.string/replace s #"\d+" #(str (* (read-string %) (read-string n))))) a b))) ``` [Answer] ## Python - 142 ``` import re s=raw_input() i=int(raw_input()) print ''.join([x[0]+str(int(x[1])*i) for x in filter(None,re.findall('(\D*)(\d*)',s)) if x[0]!='']) ``` [Answer] ## Java 218 Someone had to do java. The input string are 2 token on the command line. java M 'This 1 is22a 3352sentence 50' 3 ``` public class M{ public static void main(String[]a) { int m=new Integer(a[1]),n=0,b=0; String s=""; for(char c:a[0].toCharArray()){ if(c<48|c>57)s=b>(b=0)?s+m*n+c:s+c; else n=b*n+c-38-(b=10); } System.out.println(b>0?s+m*n:s); } } ``` [Answer] # Two answer: [perl](/questions/tagged/perl "show questions tagged 'perl'") + [bash](/questions/tagged/bash "show questions tagged 'bash'") ## Pure bash (~262) First, there is an *not so short* **pure** bash version (no fork, no external binaries)! ``` mn () { if [[ $1 =~ ^(.*[^0-9]|)([0-9]+)([^0-9].*|)$ ]]; then local num=${BASH_REMATCH[2]} rhs="${BASH_REMATCH[3]}"; mn "${BASH_REMATCH[1]}" ${2:-3} l; echo -n "$[num*${2:-3}]$rhs"; else echo -n "$1"; fi; [ "$3" ] || echo } ``` Let's show: ``` mn "This 1 is22a 3352sentence 50" 42 This 42 is924a 140784sentence 2100 ``` (Which is a totally improbable sentence) ## Perl little obfuscated (for fun only) This version (based on [@Chilemagic's](https://codegolf.stackexchange.com/a/37113/10961) answer) is not shorter, but designed as a ***totem*** script: > > `cat <<eof >mn.pl` > > > ``` #!/usr/bin/perl -sp eval eval'"' .('['^'(') .'/\\'.'\\'.('`'|'$').'+'.'/\\$\&' .'*\\$' .('`'|'.').'/' .('`'|"'") .('`'|'%').'"' ``` > > `eof > chmod +x mn.pl` > > > Sample run: ``` ./mn.pl -n=2 <<<$'This 1 is22a 3352sentence 50\n21.' This 2 is44a 6704sentence 100 42. ``` ]
[Question] [ When I was younger, I had a big map of the US tacked up on my wall across from my bed. When I was bored, I would stare at that map and think about stuff. Stuff like the four-color-theorem, or which state bordered the most other states. To save younger me some brainpower in counting, you are going to ~~invent a time machine and~~ tell me how many states border the input. Because time is finicky, this needs to be as short as possible. # The Task Given one of the 50 US states, either by its full name or by its postal abbreviation, as found on [this page](https://www.bls.gov/cew/cewedr10.htm) ([archive.org mirror](https://web.archive.org/web/20170526084535/https://www.bls.gov/cew/cewedr10.htm)), return the number of states it borders. The following is a mapping of all inputs for full state names to the number of states adjacent, found on [this website](http://state.1keydata.com/bordering-states-list.php). ``` Missouri, Tennessee -> 8 Colorado, Kentucky -> 7 Arkansas, Idaho, Illinois, Iowa, Nebraska, New York, Oklahoma, Pennsylvania, South Dakota, Utah, Wyoming -> 6 Arizona, Georgia, Massachusetts, Michigan, Minnesota, Nevada, New Mexico, Ohio, Virginia, West Virginia -> 5 Alabama, Indiana, Kansas, Maryland, Mississippi, Montana, North Carolina, Oregon, Texas, Wisconsin -> 4 California, Connecticut, Delaware, Louisiana, New Hampshire, New Jersey, North Dakota, Rhode Island, Vermont -> 3 Florida, South Carolina, Washington -> 2 Maine -> 1 Alaska, Hawaii -> 0 ``` # The Rules * Your program can either handle the full state name or the postal code - it cannot use a combination. * You can specify the case of the input, but you cannot remove whitespace in the input. * You do not have to handle Washington, D.C., or anything that is not one of the 50 states. * The number of states bordered does **not** include the input state. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. While I know this may just be whoever has the best compression or finds the best regex pattern per number, if I get too many of those answers, I'll award a bounty to an answer that generates a map of the US and uses that to calculate the number of bordering states. [Answer] # Mathematica, 112 111 bytes -5 byte thanks to [Mark S.](https://codegolf.stackexchange.com/users/41105/mark-s) and [LegionMammal978](https://codegolf.stackexchange.com/users/33208/legionmammal978)! -22 bytes (and noticing a problem with the output) thanks to [ngenisis](https://codegolf.stackexchange.com/users/61980/ngenisis)! ``` Tr[1^Entity["AdministrativeDivision",#~StringDelete~" "]@"BorderingStates"]+Boole@StringMatchQ[#,"Il*"|"Mic*"]& ``` Of course, there's a Mathematica builtin for it. Includes D.C. in the count. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~73~~ 65 bytes ``` “U[“Ȥ“!÷2“®Ɓ⁵]StƁ}K“ʂÞiƬ¦.ÞrÆu“4œ(°fWg?Ʋd“Ɠ©“Œb‘i³OS%168¤$€Tµ’6L? ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5zQaCBxYgmQUDy83QhIHVp3rPFR49bY4JJjjbXeQIFTTYfnZR5bc2iZ3uF5RYfbSoFCJkcnaxzakBaebn9sUwqQf2zyoZVA6uikpEcNMzIPbfYPVjU0szi0ROVR05qQQ1sfNcw087H///@/kmdKYka@EgA "Jelly – Try It Online") Builtins? Who needs those? (`ʂÞiƬ` on the ground in disgust). Takes input as full name, such as `"Idaho"`. **How it Works** ``` “U[“Ȥ“!÷2“®Ɓ⁵]StƁ}K“ʂÞiƬ¦.ÞrÆu“4œ(°fWg?Ʋd“Ɠ©“Œb‘i³OS%168¤$€Tµ’6L? “U[“Ȥ“!÷2“®Ɓ⁵]StƁ}K“ʂÞiƬ¦.ÞrÆu“4œ(°fWg?Ʋd“Ɠ©“Œb‘ The literal list of code-page index lists [[85, 91], [154], [33, 28, 50], [8, 143, 133, 93, 83, 116, 143, 125, 75], [167, 20, 105, 152, 5, 46, 20, 114, 13, 117], [52, 30, 40, 128, 102, 87, 103, 63, 153, 100], [147, 6], [19, 98]] € On each sublist: ¤ Evaluate the hash value: ³ Input O Character values S Sum. % Modulus. 168 168 i Does the sublist contain that nilad? T Get the sublist which does contain that nilad. ? If L Length. Then ’ Return the index - 1 Else 6 Return 6 ``` [Answer] # JavaScript (ES6), ~~115~~ 113 bytes *Edit: saved 2 bytes by borrowing 2 more string optimizations from [Step Hen Python answer](https://codegolf.stackexchange.com/a/139729/58563). I missed them on my initial attempt.* Takes postal codes as input. ``` s=>('7KYCO8MOTN0AKHI1ME2FLSCWA3CACTNDELANHNJRIVT4ALWINCKSMDMSMTXOR5GAZOHMANMIMNVWVA'.match('.\\D*'+s)||'6')[0][0] ``` ### How? A non-RegExp argument passed to the `.match()` method is implicitly converted to a RegExp object. So, we're testing the regular expression `/.\D*{{input}}/` on our encoded string. This is matching a digit(1), followed by 0 to N non-digit characters, followed by the input. For instance: if the input is `"NH"` (New Hampshire), the matched string will be `"3CACTNDELANH"`. We simply keep the first character of this string, or return `"6"` by default if there was no match. *(1): The `.` is actually matching any character, but the string is built in such a way that what is found before a group of letters is always a digit.* ### Demo ``` let f = s=>('7KYCO8MOTN0AKHI1ME2FLSCWA3CACTNDELANHNJRIVT4ALWINCKSMDMSMTXOR5GAZOHMANMIMNVWVA'.match('.\\D*'+s)||'6')[0][0] const o = { 8:['MO', 'TN'], 7:['CO', 'KY'], 6:['AR', 'ID', 'IL', 'IA', 'NE', 'NY', 'OK', 'PA', 'SD', 'UT', 'WY'], 5:['AZ', 'GA', 'MA', 'MI', 'MN', 'NV', 'NM', 'OH', 'VA', 'WV'], 4:['AL', 'IN', 'KS', 'MD', 'MS', 'MT', 'NC', 'OR', 'TX', 'WI'], 3:['CA', 'CT', 'DE', 'LA', 'NH', 'NJ', 'ND', 'RI', 'VT'], 2:['FL', 'SC', 'WA'], 1:['ME'], 0:['AK', 'HI'] }; for(let n = 8; n >= 0; n--) { o[n].forEach(s => { let res = f(s); console.log(s + ' -> ' + res + ' ' + (res == n ? 'OK' : 'FAIL')); }); } ``` --- # Hash version, 115 bytes Same input format. ``` s=>`04436303035050063062750600644408${6e7}503600300540410005207058036442600400000650035`[parseInt(s,33)%589%180%98] ``` ### Demo ``` let f = s=>`04436303035050063062750600644408${6e7}503600300540410005207058036442600400000650035`[parseInt(s,33)%589%180%98] const o = { 8:['MO', 'TN'], 7:['CO', 'KY'], 6:['AR', 'ID', 'IL', 'IA', 'NE', 'NY', 'OK', 'PA', 'SD', 'UT', 'WY'], 5:['AZ', 'GA', 'MA', 'MI', 'MN', 'NV', 'NM', 'OH', 'VA', 'WV'], 4:['AL', 'IN', 'KS', 'MD', 'MS', 'MT', 'NC', 'OR', 'TX', 'WI'], 3:['CA', 'CT', 'DE', 'LA', 'NH', 'NJ', 'ND', 'RI', 'VT'], 2:['FL', 'SC', 'WA'], 1:['ME'], 0:['AK', 'HI'] }; for(let n = 8; n >= 0; n--) { o[n].forEach(s => { let res = f(s); console.log(s + ' -> ' + res + ' ' + (res == n ? 'OK' : 'FAIL')); }); } ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~168~~ ~~154~~ ~~153~~ 137 bytes ``` lambda s:[i for i,S in enumerate('AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA A KYCO MOTN'.split())if s in S]or 6 ``` [Try it online!](https://tio.run/##LdHPb4IwFAfwu3/Fi5dCQoybm1tIPDQFBaFlAQb@mAcXJSNTNMIOxvi3s8erpw9tv699tOdr83OqRm0x@WoP2@P3bgu1vS6hOF2gtBIoK9hXf8f9ZdvsDcYDzwfpwjRMRM5BcJGGXHlqrhw39rMUeJj7SgSJdGQi00UUg@SryJtxJX2psjzjwCFYighklCo2qM@HsjFMsyyg7s5KNnjuuN3BBG5MRsx@txjmOgSO3iwWLAkeM3tsMd/RhBpOKFezJKKA@NBriS74TIlcR/iK2a8Wm3FCPvA1ilCZRhKRR2Q6mes1jk28YBOKCBJCOprHKCWUIKKYSBdE7hMC9xwhKeG4RKgnlaeZaxwi9olMF0yxiWf8TUHknJC4yxM2iDcxtJiHBcN7r9c98e/@2l37boAftWHaPThfyqox@re7Dbc7TPAd7v0BRo/bxsCQBUWHacFujW5Ms/0H "Python 3 – Try It Online") *-4 bytes thanks to isaacg* *-10 bytes thanks to ETHProductions* *-1 byte thanks to notjagen* Saved some more bytes by defaulting to six, as other answers have done. TIO includes tests. Takes input as postal code. Generates a list of the state names as strings for each set, squished together where possible (for example, `WVVA` is stored as `WVA`). The lambda function gets the index in the list whose string contains the input. There may be a way I don't know about the golf the body of the function. Outputs as a list containing an integer - add `[0]` to the end of the lambda to output as integer. [Answer] # [V](https://github.com/DJMcMayhem/V), 143 bytes ``` çourüee/C8 çdoüke/C7 çrküI„sn]üebüOkünnsüSDüUüwy/C6 çzüg„ot]üttüinnüvaüxiüOh/C5 çbüdiüKüMáû5}üNCüOüTüWi/C4 ç^[CDLNRV]/C3 ç[FSW]/C2 çM/C1 ñlS0 ``` [Try it online!](https://tio.run/##DYzNCoJQEEb3vcztz2o/EkRpkJULKSiUEuVeMLMfaCH0Iq1ct25Wfg92m905zPmmshaNuRbgJFE06aCJDTgTHgsXGXjWvi96J/cjeCmu9QUctLUL3oBvD0UjKZ/gU/s2pYRlCU61BlcH8D2V1VmRI408iEXnYA8f/JwX2G9rkgC8BoepoqFk@4jchb/a7hQNRKNpEAr2BT1FvQ6@edC1lkxuikNs/g "V – Try It Online") Hexdump: ``` 00000000: e76f 7572 fc65 652f 4338 0ae7 646f fc6b .our.ee/C8..do.k 00000010: 652f 4337 0ae7 726b fc49 8473 6e5d fc65 e/C7..rk.I.sn].e 00000020: 62fc 4f6b fc6e 6e73 fc53 8144 fc55 fc77 b.Ok.nns.S.D.U.w 00000030: 792f 4336 0ae7 7afc 6784 6f74 5dfc 7474 y/C6..z.g.ot].tt 00000040: fc69 6e6e fc76 61fc 7869 fc4f 682f 4335 .inn.va.xi.Oh/C5 00000050: 0ae7 62fc 6469 fc4b fc4d e1fb 357d fc4e ..b.di.K.M..5}.N 00000060: 8143 fc4f fc54 fc57 692f 4334 0ae7 5e5b .C.O.T.Wi/C4..^[ 00000070: 4344 4c4e 5256 5d2f 4333 0ae7 5b46 5357 CDLNRV]/C3..[FSW 00000080: 5d2f 4332 0ae7 4d2f 4331 0af1 6c53 30 ]/C2..M/C1..lS0 ``` I wrote this before I realized you could take the input as postal codes. I'm not sure if that's actually shorter or not `:shrug:`. This answer uses regex to search for certain states, and then change the input to a certain number if it matches. However, as the number of states we've tested against goes up, the smallest search we can use goes down. So for example, we can't search for `C` because that will match `Colorado` and `California`. (As well as Conneticut and The Carolinas) However, once we've tested for every state that has more than 3 bordering, we can just search for *starts with C* because it can't match a previous one anymore. A few test cases might be wrong since I don't have the time to test all of them. Let me know if you find any incorrect outputs. :) [Answer] # JavaScript, 153 bytes ``` MO=TN=8;CO=KY=7;AZ=GA=MA=MI=MN=NV=NM=OH=VA=WV=5;AL=IN=KS=MD=MS=MT=NC=OR=TX=WI=4;CT=DE=LA=NH=NJ=ND=RI=VT=3;FL=WA=2;ME=1;AK=HI="0";alert(self[prompt()]||6) ``` Variable chaining. I'm sure there's a better way to do this though. Thanks to a suggestion from someone from Discord the output defaults to 6, the most common number of bordered states. 183 bytes to 151 bytes. A commenter pointed out that this fails for AK and HI, so I've added two bytes to fix the issue. 151 to 153 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~78~~ 72 bytes ``` .•n£þuγ{çâ/₁=èó[nK™ΩFîÀî˜Çʒ÷¿ηZ¬³ã®ÿΣÔ¢*5ŠÜ‚!¶Ö¾#}ê(Ûø‰¢þL[Æ₁cgIkö•s¡¬ð¢ ``` [Try it online!](https://tio.run/##AYsAdP8wNWFiMWX//y7igKJuwqPDvnXOs3vDp8OiL@KCgT3DqMOzW25L4oSizqlGw67DgMOuy5zDh8qSw7fCv863WsKswrPDo8Kuw7/Oo8OUwqIqNcWgw5zigJohwrbDlsK@I33DqijDm8O44oCwwqLDvkxbw4bigoFjZ0lrw7bigKJzwqHCrMOwwqL//2t5 "05AB1E – Try It Online") --- ``` .•n£þuγ{çâ/₁=èó[nK™ΩFîÀî˜Çʒ÷¿ηZ¬³ã®ÿΣÔ¢*5ŠÜ‚!¶Ö¾#}ê(Ûø‰¢þL[Æ₁cgIkö• # Push the string: akhi me flscwa cactdelanhnjndrivt alinksmdmsncmtortxwi azgamamimnnvnmvaohwv idilianarenyokpnsdutwy kyco motn s¡ # Split on input. ¬ # Get head. ð¢ # Count number of spaces. ``` --- This ONLY works because the order of the state abbreviations allows for NO state to occur in the overlap between states: ``` a[kh]i me f[ls][cw]a c[ac][td][el][an][hn][jn][dr][iv]t a[li][nk][sm][dm][sn][cm][to][rt][xw]i a[zg][am][am][im][nn][vn][mv][ao][hw]v i[di][li][an][ar][en][yo][kp][ns][du][tw]y k[yc]o m[ot]n ``` Took awhile to get the arrangement right... Then, by splitting on the input and counting the spaces in the first part, we get the correct result. --- If I steal the "default to 6" from the other answers, I get 65 bytes: # [05AB1E](https://github.com/Adriandmen/05AB1E), 65 bytes ``` .•3θ0ÔÕ—ú^?D§:‚A†ǝλα“i›p‚ιCöΔƒñPŠ J€ŽãB»ΣUƤÆuhÃgЦ,Y²•s¡¬ð¢D9Qi6 ``` [Try it online!](https://tio.run/##AXwAg/8wNWFiMWX//y7igKIzzrgww5TDleKAlMO6Xj9Ewqc64oCaQeKAoMedzrvOseKAnGnigLpw4oCazrlDw7bOlMaSw7FQxaAgSuKCrMW9w6NCwrvOo1XDhsKkw4Z1aMODZ8WgwqYsWcKy4oCic8KhwqzDsMKiRDlRaTb//2lk "05AB1E – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~106~~ 105 bytes ``` MO|TN 8 CO|KY 7 AK|HI 0 ME 1 FL|WA 2 [CDLR].|N[HJD]|VT 3 .[CSX]|AL|IN|MD|MT|OR|WI 4 [GMV].|.[HMVZ] 5 .. 6 ``` [Try it online!](https://tio.run/##FY8/T8QwDEf39z2QmCr@wxo1pcm1cVAb0rurKsHAwMKAGP3di0@yvPhnP7/fr7/vn8/96rr/2FPWIrzQZh1OPOMGDZEbUsctr6MujjvW1o/T1qis4eA3rYV7mrWdj5u6UaNo8pqK5kmXyANrn6qlmzWket54pGl42g2FoYyEkXAT0RNHokM65EQeeHPMnvfCckmc6R3JKpIEqUgiB6pjqTa2VWGYSZ5kvSAteaIcsS9oC75jtOMBOSCeKWKfmxQmdRE0WUL8Bw "Retina – Try It Online") Did someone say regex? Edit: Saved 1 byte thanks to @Arnauld. [Answer] # JavaScript (ES6), 195 bytes ``` s=>/las|ii/[t='test'](s)?0:/ai/[t](s)?1:/Fl|Wa|S.*C/[t](s)?2:/fo|ct|de|ui|mp|er|^N.+ak/i[t](s)?3:/do|ck/[t](s)?7:/ur|ee/[t](s)?8:/iz|gi|ch|ev|xi|hi|es/[t](s)?5:/rk|ah|oi|ow|br|om|lv|ak/[t](s)?6:4 ``` A series of regular expressions, which work on the state's full name. **Test cases:** ``` var states = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware', 'Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas', 'Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota', 'Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey', 'New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon', 'Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah', 'Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']; let f= s=>/las|ii/[t='test'](s)?0:/ai/[t](s)?1:/Fl|Wa|S.*C/[t](s)?2:/fo|ct|de|ui|mp|er|^N.+ak/i[t](s)?3:/do|ck/[t](s)?7:/ur|ee/[t](s)?8:/iz|gi|ch|ev|xi|hi|es/[t](s)?5:/rk|ah|oi|ow|br|om|lv|ak/[t](s)?6:4 for(i = 0 ; i <= 8 ; i++) { s = [] states.forEach(st => f(st) == i && s.push(st)) console.log(i + ' bordering states: ' + s.join(', ')) } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~61~~ 59 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OP%⁽/r%101eЀ“¿=“þ“(7“¡¦ðø,0@L“€ç÷<CMZa“Ø!)5HNV““1^“¥+‘Tȯ7’ ``` A full program taking the full state name and printing the result (as a monadic link it either returns a list containing a single number or the number 6). **[Try it online!](https://tio.run/##y0rNyan8/98/QPVR4179IlVDA8PUwxMeNa151DDn0H5bIHl4H5DQMAfxFx5adnjD4R06Bg4@QC5Q0eHlh7fbOPtGJYLUzVDUNPXwCwPJNMwxjANpWKr9qGFGyIn1QN0z////75dalpiSCAA "Jelly – Try It Online")** or see a [test suite](https://tio.run/##TVJNb9NAEP0r5lAFRCWaA@ICEpUrSEidVFASFQTS1F7swZudaGfd1JwCF64ci9QLB@CCBDc48CHVQuJ35I@E/XDbSPbum9mZnfdm9qWQsl6tRnsby9e/buiN7lZXNO@Wb74sF6dnf@7Ytfltl6u3nP3h7FPzrfmxuXV315o2qPncfL8dJ0/AxZ1cuXazNxy7k8Vp97lL@Hh9uTjZ//fVZr9f/f3ZvLU5A/sfrFZPOwkyU6Wxsxl19oVSglkIZ8QkSUNGDg@EMlVa1g5v6xIUAzvcz6DwAX0pUREGJ83B7UNxqIHLFs@jA9Klw6NS2qyp9@/ZilzLI1Do7UdUmSLagZKMtx8bKNw@qWmKKg/18RUpf3pfkM5DYgLMkBYVC2M8iwTTAnNQATtd7ZVDcQTZBalEHGPqJYwK9PsY7Z0tnYlgE607tiUcQqDeVxlC4DG4aEgCupagslCV2X2zmW9uQsq08UPSVmUMmmzXvGekRU4qzOA4XDVBTkkxem8MEl@QblnEZPWkBtPKOHNHSJiD9lPbpQr5nJcT2IPpjAsMp87xQGgW9SWNy2Y/LCgTUZ/PBYyFnlrSDt6zbwGztRGtk5@ALaByEwQkgEq0vWqn37P0EDvP/gM "Jelly – Try It Online"). ### How? ``` “¿=“þ“(7“¡¦ðø,0@L“€ç÷<CMZa“Ø!)5HNV““1^“¥+‘ ``` is a list of lists of code-page indices: ``` [[11,61],[31],[40,55],[0,5,24,29,44,48,64,76],[12,23,28,60,67,77,90,97],[18,33,41,53,72,78,86],[],[49,94],[4,43]] ``` and is shown as `“ ... ‘`, below: ``` OP%⁽/r%101eЀ“ ... ‘Tȯ7’ - Main link: list of characters, stateName e.g. Ohio O - cast to ordinals [79,104,105,111] P - product 95757480 ⁽/r - base 250 literal 12865 % - modulo by 12865 3285 %101 - modulo by 101 53 “ ... ‘ - list of lists of code-page indices eЀ - map: exists in? [0,0,0,0,0,1,0,0,0] T - truthy indices (if none yields an empty list) [6] ȯ7 - logical or with 7 (replace empty list with 7) [6] ’ - decrement [5] - implicit print (Jelly's representation of a list of - one item is just that item) 5 ``` [Answer] # Excel VBA, ~~177~~ ~~154~~ 147 Bytes Anonymous VBE function that takes input, of the expected type `String` representing a state's postal code, from range `[A1]`, and returns an `Integer` that represents the number of states that border that state. ``` For i=0To 8:r=r+IIf(Instr(1,Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA | KYCO MOTN")(i),[A1]),i,0):Next:?IIf(r,r,6) ``` --- ## Previous Versions 154 Bytes: ``` For Each s in Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA | KYCO MOTN"):r=r+IIf(Instr(1,s,[A1]),i,0):i=i+1:Next:?IIf(r,r,6) ``` 177 Bytes: ``` [2:2]=Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA A KYCO MOTN"):[3:3]="=IfError(If(Find($A1,A2),Column(A3)),"""")":[B1]="=Sum(3:3)":?[If(B1,B1,6)] ``` Formatted for readability ``` [2:2]=Split("AKHI ME FLSCWA CACTLANHNJNDERIVT ALWINCKSMDMSMTXOR MAZOHGANMIMNVWVA | KYCO MOTN") [3:3]="=IfError(If(Find($A1,A2),Column(A3)-1),"""")" [B1]="=Sum(3:3)" ?[If(B1,B1,6)] ``` [Answer] # Python 2, ~~363~~ 218 bytes ``` lambda a:dict(WA=2,WI=4,WV=5,FL=2,NH=3,NJ=3,NM=5,NC=4,ND=3,RI=3,NV=5,CO=7,CA=3,GA=5,CT=3,OH=5,KS=4,SC=2,KY=7,OR=4,DE=3,HI=0,TX=4,LA=3,TN=8,VA=5,AK=0,AL=4,VT=3,IN=4,AZ=5,ME=1,MD=4,MA=5,MO=8,MN=5,MI=5,MT=4,MS=4).get(a,6) ``` Let's start out with the ~~simple~~ slightly optimized hardcoded answer. Takes postal code as input. -145 bytes thanks to bfontaine. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 187 bytes ``` param($a)$x=($b=" MO8TN8CO7KY7AZ5GA5MA5MI5MN5NV5NM5OH5VA5WV5AL4IN4KS4MD4MS4MT4NC4OR4TX4WI4CA3CT3DE3LA3NH3NJ3ND3RI3VT3FL2SC2WA2ME1").IndexOf($a);if($x+1){$b[$x+2];exit}6-6*($a-in'AK','HI') ``` [Try it online!](https://tio.run/##FY5da8JAEEX/ikhgja0FMzMqiA/LRs022VnQJekHfYg0xYBasYKB4m/fbuFyz4Xzcs/ft@bys28OB@/P9aU@DqI6jrrFINot@j1jZ45nyk7z16l8o7UkE6LJMHFJbMhmVEqqSpIFasZ8iyZFE9ohK7QbdC9YaVQSlIN0CYUEzoCfgVPYaCgdrIpkq5JKJmY57sdP@vTZdPbr/8W8DegexvFvtHsPI/mYN117vU9Gk2Hwo/YkZC4eRaZF7L0XRos/ "PowerShell – Try It Online") I'm sure there's a better way to do this, but here's the approach I came up with. Takes input `$a` and uses that to get the `.IndexOf` its occurrence in the long string of state/border combinations. Stores that into `$x` and the string into `$b` in the process. Then goes into an `if` statement that checks whether it found a match, and if so index to the digit and then `exit`. Otherwise, we're one of the `6` states or `AK` or `HI`, so we perform some logic to see whether `$a` is either of the `0` states, and subtract if necessary. In any case, that's left on the pipeline and output is implicit. [Answer] # Python 3, 729 ~~733~~ bytes Takes input as a postal abbreviation. This is my first attempt at a golfing challenge, and this is about the shortest I think I can get with this hellish approach. I know it's massive - come to think of it I'd probably have been better off with `if-else` statements, but after all of that time and effort I had to post it : D. ``` lambda s:sum((i-32)*96**j for j,i in enumerate(b'`*g$<#?wP\\.=)kuDbk$yvv\\D:Nh:cd/Pj, e*[_yXGz6lR<$jMo0qUU*7(Dua3-ThO}iX6VWRYDv=<K$8mVbYK9ld);TFB/m\'NE3ow4./pUsI5yJrwYrM4@e6\\kHJ%q8NA3>fb!~-rtwsRW=RBni}Y7T^gD\\IoxzJf.%|1.&4*"$%Q+).|8p(vcJ]cLRGUyC2eF:<Q4!_)y\\<`tr2A[z7re6OaR["2PRv\x7f,bRE [XrvtA<R<UlS23on?Byym&uy{XuB\x7fIMfh<y&waHElg-vk:4*on\x7f@?Ai5=2swfZSBF.PjkL{,|=,M<Bw"w,e@f`aKnmh\'xgg1#b4En\x7f+*\'g_ZRoeN*Q]mX\'>RoGc~ZP~e&{Hwo6bd<](hV)=l9#[f<Gj,#Ea!nJnL=9k"M,`bP2PsP6(eJoGEU>GA?,BpS}"RzzdMRtL[cre;\\tld^xT\':pry\'Nu_*R}eYg_U!Ld{p7<f:95lD]OBMX(r"Jg\'|%Cq"`Qy9g0aNrtYP9dnPRRr3\'yT(CE~\\&@5#tMLZ+a:V5NNXVp+Uy61s9$=Vb99(!ga7f7x}#=*]q.\x7f0R+f[*m:i^qe#D 8M&W\x7faGmCNCU9"~1Pj!]2r5 H>rYPqwfg4cFG*3-(z'))>>(5*int(s,36)-1850)&15 ``` I just realised I'd taken the luxury of a three letter variable name - 4 bytes down, 400 to go! ]
[Question] [ Lists can contain lists and we have nested lists. But we don't like nested lists and want to flatten them. By flattening I mean create a list which does not contain any list, but elements of lists it contained before. I'll explain it more. ## Input An arbitrary size list which has the below properties: * it can contain integers * it can be empty * it can contain lists which have the same properties These are some examples of valid lists: ``` [] [1, 2, 46] [[], []] [[[14], [[5]]], 4, [2]] ``` ## Output The output must be a list, which is empty or only contains numbers. It must not contain lists. The output must be the flattened version of the input. * all elements (beside empty lists) must be in the flattened version * the order matters # Test cases: ``` [[3],[3, [[6]]]] -> [3, 3, 6] [] -> [] [[], []] -> [] [[1, 4, 6], [1, [2, 67, [5, 7]]]] -> [1, 4, 6, 1, 2, 67, 5, 7] ``` [Answer] # Languages with built-ins [HBL](https://github.com/dloscutoff/hbl), 0.5: `-` - [Try it online!](https://dloscutoff.github.io/hbl/?f=0&p=LS4_&a=KCgpICgxIDQgNikgKDEgKDIgNjcgKDUgNykpKSk_) [Fig](https://github.com/Seggan/Fig), ~0.823: `f` - [Try it online!](https://fig.fly.dev/#WyJmIiwiW1sxLDQsNl0sWzEsWzIsNjcsWzUsN11dXV0iXQ==) [flax](https://github.com/PyGamer0/flax), 1: `F` - [Try it online!](https://staging.ato.pxeger.com/run?1=m70kLSexYsGCpaUlaboWC92WFCclF0N5N9WjlaKjow11FEx0FMxidRRAzGgjINscSJvqKJjHgoBSLFQ9AA) [Japt](https://github.com/ETHproductions/japt), 1: `c` - [Try it online!](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Yw&input=W1sxLCA0LCA2XSwgWzEsIFsyLCA2NywgWzUsIDddXV1d) [Jelly](https://github.com/DennisMitchell/jelly), 1: `F` - [Try it online!](https://tio.run/##y0rNyan8/9/t////0dGGOgomOgpmsToKIGa0EZBtDqRNdRTMY4EAAA) [Vyxal](https://github.com/Vyxal/Vyxal), 1: `f` - [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJmIiwiIiwiW1sxLCA0LCA2XSwgWzEsIFsyLCA2NywgWzUsIDddXV1dIl0=) [05AB1E](https://github.com/Adriandmen/05AB1E), 1: `˜` - [Try it online!](https://tio.run/##yy9OTMpM/f//9Jz//6OjDXUUTHQUzGJ1FEDMaCMg2xxIm@oomMcCAQA) [Pyt](https://github.com/mudkip201/pyt), 1: `Ƒ` - [Try it online!](https://tio.run/##K6gs@f//2MT//6OjjXSMY3WijYxiYwE) [J](https://www.jsoftware.com/#/), 1: `,` - [Try it online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboW21KTM_IVNKx1NBWMwVBFIVPPyBwiCVUDUwsA) [Pip](https://github.com/dloscutoff/pip), 2: `FA` - [Try it online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIkZBIiwiWzI7WzM7WzRdXTs1XSIsIjIgMyIsIi1wIl0=) [Pyth](https://github.com/isaacg1/pyth), 2: `.n` - [Try it online!](https://tio.run/##K6gsyfj/Xy/v///o6GhDk1gdheho09hYIG0CZBrFxgIA) [Haskell](https://www.haskell.org/) + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 3: `rtc` [Attache](https://github.com/ConorOBrien-Foxx/Attache), 4: `Flat` - [Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@98tJ7Hkv19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkI0l4JCdLRxrE60MZATbRYLBDogMQgJpIBMKNtQR8FER8EMJARkRhsB2eZA2lRHwRykjSs29j8A) [rSNBATWPL](https://github.com/Radvylf/rSNBATWPL), 5: `crush` - [Try it online!](https://dso.surge.sh/#@WyJyYWlzaW4tYmF0d2FmZmxlIixudWxsLCJjcnVzaCIsIiQgKCgoMSwyKSwzLCg0LDUpKSw1LCgyLDMpKSIsIiIsIiJd) [R](https://www.r-project.org/) (almost), 6: `unlist` - [Try it online!](https://tio.run/##K/qfZvu/NC8ns7jkf5oGiNLQ1FRW0LVTiI7lggqACUMdBRMdBTNNHQUYF0wbAcXMoWxTHQVzTRCA6Ifq0FEAMqDKQCpi/wMA "R – Try It Online") [Clojure](https://clojure.org/), 7: `flatten` - [Try it online!](https://tio.run/##S87JzyotSv2vUVCUmVeSk6eg8T8tJ7GkJDXvv7qGhqGCiYKZpgKQ1jBSMDNX0DBVMNcEg/8A) [jq](https://stedolan.github.io/jq/), 7: `flatten` - [Try it online!](https://tio.run/##yyr8/z8tJ7GkJDXv///oaONYnWhjHYXoaLNYIOCKBqLoWCAfxI421FEw0VEwA/GBzGgjINscSJvqKJiDVAMA "jq – Try It Online") [Factor](https://factorcode.org), 7: `flatten` - [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQnFpYmpqXnFqsl5KaWqBQUJRaUlJZUJSZV6JgzcVVrVCtYKxQCyZBbDMgGwz/p@UklpSk5v3XA6qpVYDyFPTAOmrBGF3UUMEErB/EqlYwUjAzB1KmCuYwIxHK/wMA "Factor – Try It Online") [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html), 7: `retract` - [Try it online!](https://tio.run/##ZZHBatwwEIbvfoqB5GBDbGdbSulS@9ImEEiXUnIrIQy2ZIu1JCPJdEPaZ9@OLK26S0/W/P/MfDPjEe2eTdPxrbyCR1TDggODH6j2u6fXmVm4Kv9kZQlfGRdKOKGVhU7PgvXAjZbgRgZWL6ZjoPkaccMYSN0vE721AcesE2rwTUbnZrut6xG7PWGqMbArbYZ6Dlrty8sP1ab6WPe6s7U1Xf1FK2f0VH3TCvvqnjKq0ckp69Eh@BA4YAbQwPfFsPX5O@g5h/yUUBRZJpR1qGjY@0V1jqbj0LQpiKkF/BqZYdSFS5x9Cgw6aeCDPICKxMw9ILmhD9lNHIPEz9etlyjHn/ph9/iwuwsAf@LMMGewc7DdwrpmnCzODmW77njKSvyG@pG4GHXurmVog40W2raBaNINHDMec3GCPEKoZXmJxVDwcsY8afMoIkt6dQ2T4feVdHKup37NSZvJANQGpwkOUBHp4EkSDv/RJbFSh5eLu6e1k8/PN/cdwub//CNv4hmOEoWipF7ThWYjlIPrVP9zpWxuwq99F7/vb@DMPamf4ndz@/xcHP8C "Haskell – Try It Online") [Kotlin](https://kotlinlang.org), 7: `flatten` - [Try it online!](https://tio.run/##XY5NCsIwEIX3OcUsGwgZ/F0ILjyBZ4ht0kYnP6RjQcSz1ypV0NkM7zHve3NJTD6Oo7tGCMbHSsJdDIagsTYfSjE32IN57aOrBEzzEQupfvRSwerPWivYKNhKIYXIxUemWH252pFhtlOjBESoU2PBlRSgY879DvHyfo1MbHUqLZrscUrYnvE8BOy5IX@aj3SdiGzNPsUeZ67uOJB4jOMT) [Mathematica](https://www.wolfram.com/wolframscript/), 7: `Flatten` - [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y0nsaQkNe9/QFFmXomCg0IaEFdXG@oomOgomNXqKICY1UZAtjmQNtVRMK8Fgv8A "Wolfram Language (Mathematica) – Try It Online") [Prolog (SWI)](http://www.swi-prolog.org/), 7: `flatten` - [Try it online!](https://tio.run/##HY3BCoMwEER/ZfGU4KZQbRU8BOJXCEsOOdQiRBM00Ft@Pd04h5k3MDDxDD581fXbSjHtPKnVu5Q@hzA4y0eZ1O6i364kyFithWkXXMO5uySaHEFpyDEfDZLBxUqJRNRbpB6BaLAsBu50ZzV6IrwQhsqM1DGPnG@Ese4tn/4B "Prolog (SWI) – Try It Online") [Racket](https://racket-lang.org/), 7: `flatten` - [Try it online!](https://tio.run/##K0pMzk4t@a@ck5iXrlAE5nBp/E/LSSwpSc37r66hYahgomCmqQCkNYwUzMwVNEwVzDVB4D8A) [Ruby](https://www.ruby-lang.org/en/), 7: `flatten` - [Try it online!](https://tio.run/##ZY/LDoIwFET3/YpJ2GhyQ0V8kmBi/Iymi8ojGsWSUhd8fZWGAOJs58zcueZ9bZ0LcNF5gdLoKsHN2rpJOFf1PdfZI8x0xc0X42djVMvLp7K2eLEGKQQiwpoQQ2JUkJ4gekMy67kNYUvYEcSecJCe99zMkEx5viFYwpEQrYZuzw/F9J/tA5LVUGG/E3NN19G4q2sY8mrym4j7S93on@pFtHTuAw) [Arturo](https://arturo-lang.io), 7: `flatten` - [Try it](http://arturo-lang.io/playground?I2Glkq) --- Feel free to add to this community wiki. The below is a template to copy the code and links into to add to the above list. ``` [<language>](<language URL>), <byte-count>: `<code>` - [Try it online!](<interpreter url>) ``` [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` f=lambda s:[s]*(s<f)or sum(map(f,s),[]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBRasMwDIbffQrhl9lDGSzd0hGaXETxQ9bN1OA4oXYKO8te8jJ2mV6gt5lcEpgQ6Jf0YUv6_p2-0mkM5bL8zMkWb7cH2_h-eP_oIdYUzaOKB6vHM8R5UEM_KYtRIxm94td0bKSUgmhnkHYIRJVhg6IFyDl7ZYSge4WyIsOU-Zc_I7xkisssqWS95_iKsN-e2hgEFitw74v8ueX5PLgA6fgUJ--Skl3ogtS1AIcjNJAn_7z0Hv0GFK3UWsB0diEpq5zGcd1pO8Uf) Found independently but very similar to @xnor's [answer](https://codegolf.stackexchange.com/a/80123/101374) to the linked question. [Answer] # sh + coreutils, 8 bytes `tr -d []` [Answer] # [R](https://www.r-project.org), 22 bytes ``` \(x)as.list(unlist(x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhbbYjQqNBOL9XIyi0s0SvPAVIWmJkTy5t40DbAImDDW1IHQOgoIQTNNEFBW0LVTUIgGygCRWSwXVBtUIhouABGF6tfELm2oo2ACNASmyhBKGwHFzKFsUx0Fc4S90VAdOgpABlQZSEUsxBMLFkBoAA) `unlist` is an almost-built-in ([see the CW answer](https://codegolf.stackexchange.com/a/248253/55372)) in R, as it doesn't correctly handle the empty lists - it returns `NULL`. Also, it returns a vector of values not a list, so we convert the result to list with `as.list`. Fortunately, `as.list(NULL)` results in an empty list as desired. --- ### [R](https://www.r-project.org), ~~40~~ 38 bytes *Edit: -2 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(x)`if`(is.null(r<-unlist(x)),1[0],r) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY31WI0KjQTMtMSNDKL9fJKc3I0imx0S_NyMotLgBKaOobRBrE6RZpQ1XvTNMAyYMJYUwdC6yggBM00QUBZQddOQSEaKANEZrFcUG1QiWi4AEQUql8Tu7ShjoIJ0BCYKkMobQQUM4eyTXUUzBH2RkN16CgAGVBlIBWxEE8sWAChAQ) Outputs a vector (empty for input without any elements). [Answer] # [Whython](https://github.com/pxeger/whython), 31 bytes ``` f=lambda l:sum(map(f,l),[])?[l] ``` ### Explanation ``` f= # f is lambda # a function l: # that takes a single argument l: map(f,l) # First, apply f to every element of l sum( ,[]) # Then concatenate all the resulting lists together ? # If l is an integer, the map errors, so instead [l] # just wrap l in a singleton list and return that ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboW-9NscxJzk1ISFXKsiktzNXITCzTSdHI0daJjNe2jc2Ihqm6WJicWpxYr2CpEcylEx-oACSAJZEGYxiC2MRBHm8XGQsUMdRRMdBTMQDJAZrQRkG0OpE11FMxBarhiudLyixRAxipk5oHpYisuhYKizLwSjTQNEF9TE2I5zKkA) [Answer] # [R](https://www.r-project.org), 58 bytes ``` f=\(x,z=0[0]){for(i in x)z=c(z,`if`(is.list(i),f(i),i));z} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3rdJsYzQqdKpsDaINYjWr0_KLNDIVMvMUKjSrbJM1qnQSMtMSNDKL9XIyi0s0MjV10kBEpqamdVUt1IS9aRpgSTBhrKkDoXUUEIJmmiCgrKBrp6AQDZQBIrNYLqg2qEQ0XAAiCtWviV3aUEfBBGgITJUhlDYCiplD2aY6CuYIe6OhOnQUgAyoMpCKWIgnFiyA0AA) 'Roll your own' `unlist`-like function in R. Returns a vector containing all the elements of the input (nested-)list, or an empty numeric vector if the input doesn't contain any elements. [Answer] # [C (gcc)](https://gcc.gnu.org/), 169 166 bytes ``` #include<ctype.h> #define D isdigit(*c)) #define P putchar( #define R while(*c&&!D c++; main(char*c,int**v){c=v[1];P 91);R do{while(D P*c++);R P*c?44:93);}while(*c);} ``` [Try it online!](https://tio.run/##PYzNCoMwEITvPkWKICbagq0Xm/5cfADxKjnImuqCTaWNliJ99nSltAuzDB8zA@sWwDkfDfRjow9gX4PedCfPb/QFjWY5w0eDLdpQAOd/XLBhtNDV9/CPSvbssNeUC4JVziCKpHet0YRLTECMxgox8RmOU5UoWbAs4bJkzW3@9nJWCCotjMw5TffZjsv3b5Ssc1QkxVW1VYr@olTRfQA "C (gcc) – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 350 bytes ``` -[<+>---]<++++++.[-]<,[>+<[>>+>+<<<-]>>>[<<<+>>>-]--[<->++++++]<-[>+>+<<<<[>>>>>+>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]-[<->---]<------[<->[-]]<+<<<<[>>>>>+>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]-[<->---]<--------[<->[-]]<[[-]<->]<[<<<.[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-]----[<-------->+]<[<<<<<[-]+>>>>>[-]]<[-]]<[-]<->]<[<<[>.>>][-]>>[-]]<,]>>-[<+>---]<++++++++. ``` [Try it online!](https://tio.run/##pZBNCkIxDISv0n2bB4o/mzIXGbJQQRDBheD566Ttg4dbA03SNt@k6fV9ebzun9uzNWPNMDOvudtCpYXIlUBWqNUcAJVkRXMTYhjVXo2zKuqxIis1wckOPOje0LrFVj3V/w@RjQxjAIMSAQu3clONG60Yp8PTkAeol5iPkqE63apMLIAzFPtVUfL7lfrM1shdSYeSTl4SY9HD65B7nZ4VjyWdXfYF "brainfuck – Try It Online") Works by ignoring brackets inside the outermost list. It makes sure not to print a comma after another comma. Can probably be improved. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes ``` ⊞υθFυFιF⁼κ⁺⟦⟧κ⊞υκF⮌υ«≔⟦⟧ηWι⊞η⊟ιF⮌η¿⁼κ⁺⟦⟧κFκ⊞ιλ⊞ικ»⭆¹θ ``` [Try it online!](https://tio.run/##dY@9DsIgFIXn9inuCAkOGrVDJwdHk0ZH0oE0tJCS/lHqYHx2vJDWxEGWcy6c8wGVElPVC@N94awijsFI87TuJyCOQlS96nV0wljSMiiMs4SXDFpKKWzFdive5SInKxFA4ZUmF2t108W8wkjyVNrIiI1Nhbx@wDGc/fQV9nX9/@IYbleMZmBoDtJY@d0IL3qnxaS7mTxmlOYmBrIPf6S595xz9EcGZyQGyw/oM9QTg6wMy@8W8wE "Charcoal – Try It Online") Link is to verbose version of code. Uses the same flattening code as I used in my answer to [Inverted ragged list](https://codegolf.stackexchange.com/q/242174/) but I'll explain it in slightly more detail here. ``` ⊞υθFυFιF⁼κ⁺⟦⟧κ⊞υκ ``` Push the input list and all of its sublists to the predefined empty list. ``` F⮌υ« ``` Loop over all of the sublists in reverse order i.e. deepest first. ``` ≔⟦⟧ηWι⊞η⊟ι ``` Remove the elements of the sublist and push them to a temporary list. ``` F⮌η¿⁼κ⁺⟦⟧κFκ⊞ιλ⊞ικ ``` Loop over the elements of the temporary list in the order they were in the original sublist. For those elements that are sublists push their elements (which by now are just integers) to the sublist otherwise just push the integer element to the sublist. ``` »⭆¹θ ``` Pretty-print the final list so that you can see that it has been flattened. [Answer] # [Python](https://www.python.org), ~~58~~ 55 bytes ``` lambda l:[*map(int,re.findall('\d+',str(l)))] import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3zXMSc5NSEhVyrKK1chMLNDLzSnSKUvXSMvNSEnNyNNRjUrTVdYpLijRyNDU1Y7kycwvyi0oUilKh2jMLioA6NNI0oqONY3WijXUUoqPNYoFAU5OLCy6HyouOBapCUxFtqKNgoqNgBpICMqONgGxzIG2qo2AOMQ5i4YIFEBoA) Thought it was a bit cheeky using regex to flatten the list -3 bytes thanks to @Dingus [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` #~Level~{-1}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOJ7UsNaeuWtewVu1/QFFmXkm0sq5dmoNyrFpdcHJiXl01V3WtDle1oY6RjokZiAXkVteCGdWGJkB2tWktkGuiU20EETUGihkDhc1qa8ECqHoMgSqBxgDpaiMdM3OdalMdc5BCrtr/AA "Wolfram Language (Mathematica) – Try It Online") Not the built-in. Returns all atomic expressions, in order. --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes ``` ##&@@#0/@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lZzcFB2UDfQVntf0BRZl5JtLKuXZqDcqxaXXByYl5dNVd1rQ5XtaGOkY6JGYgF5FbXghnVhiZAdrVpLZBrolNtBBE1BooZA4XNamvBAqh6DIEqgcYA6WojHTNznWpTHXOQQq7a/wA "Wolfram Language (Mathematica) – Try It Online") Returns a `Sequence` instead of a `List`. ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 6 bytes ``` #<>""& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9nGTklJ7X9AUWZeSbSyrl2ag3KsWl1wcmJeXTVXda0OV7WhjpGOiRmIBeRW14IZ1YYmQHa1aS2Qa6JTbQQRNQaKGQOFzWprwQKoegyBKoHGAOlqIx0zc51qUx1zkEKu2v8A "Wolfram Language (Mathematica) – Try It Online") Returns a `StringJoin` instead of a `List`, and an empty string when there are no elements (as `StringJoin[]` evaluates to `""`). [Answer] # Scala, 75 bytes ``` def f(l:List[_]):List[_]=l.flatMap{case n:Int=>List(n)case p:List[_]=>f(p)} ``` My first Scala answer! With a lot of help from @user. [Try it online!](https://scastie.scala-lang.org/m3aMNAlYS5CfEL77Gt12sQ) [Answer] # [Javascript (node)](https://nodejs.org/en/), ~~70~~ ~~49~~ 47 Bytes * -21 Bytes thanks to [Matthew Jensen](https://codegolf.stackexchange.com/users/87728/matthew-jensen)! * -2 Bytes thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)! ``` f=(a,c=[])=>a.map(a=>a.map?f(a,c):c.push(a))&&c ``` [Try it online!](https://tio.run/##dY3dCsIwDEbvfYpejRZih043EKoPEnoR6uYPcy1Wff2aSgVRDIF85BySMz0ouusp3OaT3/cpDUYSOINWmS3pCwVJJeyGTNTG6XCPR0lKVZVLzk/Rj70e/UEOErGxgA0IxNZyKSXqWuQFd2tnX/ab/wC0fML@xwsQq3yQLY645NzxXIPoPt4WCwSHoryM9AQ) [Answer] # BQN, 8 bytes ``` ∾⍟(¯1+≡) ``` [Try it here!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+4o2fKMKvMSviiaEpCgoo4oCiU2hvdyBG4oiY4oCiSnMpwqgg4p+oCiJbWzNdLFszLCBbWzZdXV1dIgoiW10iCiJbW10sIFtdXSIKIltbMSwgNCwgNl0sIFsxLCBbMiwgNjcsIFs1LCA3XV1dXSIK4p+pCgpA) Thanks to @Razetime for 6 bytes saved! ## Explanation * `...⍟(¯1+≡)` repeat (depth - 1) times... * `∾` join (same effect as flattening 1 level) [Answer] # [Javascript](https://nodejs.org/en/), ~~96~~ 83 bytes ``` f=a=>JSON.stringify(a).replace(/[\[\],]/g,' ').split(/\s/).filter(e=>e).map(e=>e-0) ``` [Try it online!](https://tio.run/##dY3BCsIwDIbvPkVva6G26nQ7bQ/gQQ8esx7K7EalrmUdgk8/szFBFEMgH/k/kpt@6Fj3Ngzrzl/NODaFLsrj5XwSceht19rmSTUTvQlO14ZKqKBSXMmWJyRhIgZnByqrKJlorBtMT01RGibuOsy03rCx9l30zgjnW9pQgFRxSDkByBQWY0RKMi2wM7X6st/5TwAKT6j/8ZaT/XQQLUTYIec4D5zkH28XixOERZmN8QU) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 45 bytes ``` [A|L]+B:-A+X,L+Y,append(X,Y,B). []+[]. A+[A]. ``` [Try it online!](https://tio.run/##HYvNCoMwEITvPkXwlJBNoLVV8CDEsw@gLHsQ@oOgJqjQS/HV003nMPMNzITNz/5t9s8UI7pvR7qtjdM9dHqAMYTn@pA9DNAqmyFpJJs5jY5srM0yhnnaD8m1aWQ6vfy2jIfMzyBMI85wrjmgg56UAkQsCLAAgVgSi4E7/jMZXkDcQJSJGfHKXHHeQVRpT8rGHw "Prolog (SWI) – Try It Online") Uses pattern matching to decompose and recursively call the function on the head and tail of the list. ### Explanation ``` [A|L]+B:- # Match on list input with at least one input A+X, # Recursively call on the head of the list L+Y, # And on the tail append(X,Y,B). # And combine the results together []+[]. # If the element is just an empty list, return the same A+[A]. # If it just a single element, return a singleton list ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~62~~ 38 bytes *Thanks [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for a staggering -24 bytes!!!* ``` L+X:-maplist(+,L,M),append(M,X);X=[L]. ``` [Try it online!](https://tio.run/##RYrLCoMwFER/JbhKyCi0tgqWCu7jPnDJQugDQc1Fhe7y62nsprOYOQOHVz/5d759xhiNtk0@DzyN2y41DHqFgfm5PGQPq272TsYV8e9Q59pWdtri5dd52GUWWOStCByWDNTBOqVARKUDlRBElUtJkD799ig6QVwgqoMT0jlxnfYKUR@@U0X8Ag "Prolog (SWI) – Try It Online") There's probably a builtin out there which flattens lists, but here's a non-builtin way of doing it. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 34 bytes ``` f(a)=if(#a&&a!=b=concat(a),f(b),a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN5XSNBI1bTPTNJQT1dQSFW2TbJPz85ITS4CiOmkaSZo6iZpQlamJBQU5lRqJCrp2CgVFmXlAJQpKII6SAsgMTR2F6Oho41idaGMQyywWCIAMEAYTYF60oY6CiY6CGYgNZEYbAdnmQNpUR8EcpCEWahnMeQA) [Answer] # [C (clang)](http://clang.llvm.org/), ~~114~~ ~~99~~ 89 bytes * -15 bytes with help from @ceilingcat ``` main(c,v)char**v;{for(;v;c=!printf(v?c?"[%s":",%s":"[]"+!c,v))v=strtok(c?v[1]:0,",[ ]");} ``` [Try it online!](https://tio.run/##HctBCoMwEADAr9SFQqIp2Ksh5CFLDmHBKtWkJGEv4ttX7GVuQy/aYvqI7HFNigxrWmLpe7bHnIuybMl1v7KmNiv25AGfFSYwfzHA0N1Hs6uttPxV5BnfYRoNGHwE0PYUEQwX "C (clang) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 30 bytes ``` a=>eval(`[${a}]`).filter(x=>1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i61LDFHIyFapTqxNjZBUy8tM6cktUijwtbOUPN/cn5ecX5Oql5OfrpGmkZ0tHGsTrSxjkJ0tFksEGhqKujrK4AEgMgslgtNNUweQyI6FmhELG5pQx0FE5CBQFVAZrQRkG0OpE11FMyRrIWq0lEAMqBKwCr@AwA "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 39 bytes ``` a=>((a+'').match(/\d+/g)||[]).map(eval) ``` [Try it online!](https://tio.run/##dY3NCsIwEITvPsXeuqGxQavtqb7ImkNIf1RiU2zpqe8eN1JBFJeFHWY@Zm9mNqN9XIdp2/u6CW0VTHVCNGmSiOxuJntBda5T1YllIR2tAZvZOBGs70fvmsz5DlskyrWkXAJRoXmEAKUgGryF3nzR7/wnIM0V@n@8k3CIhUyxpD3rku9RQvnxdqUksFiRFxGe "JavaScript (Node.js) – Try It Online") Assume no negative input [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 1 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ∊ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TRBQA&f=S3vUNzWrOD9PQT06OtrQJFZHITraNDYWSJsAmUaxseoA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) [Answer] # Javascript 46 bytes ``` f=a=>(a+'').split(',').filter(x=>x).map(s=>+s) ``` [Try it online!](https://tio.run/##dY3BCsIwDIbvPkVvbVnt0Ol26l4k9FBmK5W6jrXI3r5mMkEUQyAf@T@Sm3mYNMx@yvsxXmwpThnVM1NRymWags@MCkTnQ7YzW1S/cHk3E0uqrxIvQxxTDFaGeGWOATRaQCMIQKuxOCd1TdYFdqt3X/Y7/wlA4wn9Pz4IcloPooUIR@QO51mQ7uPtZgmCsCkvozwB "JavaScript (Node.js) – Try It Online") Uses the trick that stringification of arrays unnests all arrays. After that empty elements need to be removed and the result mapped to integers. ]
[Question] [ Given a string, replace all left-double-quotes into two backticks and all right-double-quotes into two single-quotes. Left-quotes means the quotes that starts a quote. Right-quotes means the quotes that ends a quote. Quotes cannot be nested. You may assume that there are an even number of double-quotes in the string. # Examples Input: ``` "To be or not to be," quoth the Bard, "that is the question". The programming contestant replied: "I must disagree. To `C' or not to `C', that is The Question!" ``` Output: ``` ``To be or not to be,'' quoth the Bard, ``that is the question''. The programming contestant replied: ``I must disagree. To `C' or not to `C', that is The Question!'' ``` [Answer] # [Unreadable](https://esolangs.org/wiki/Unreadable), ~~789~~ 777 bytes -12 bytes by using variable X34 rather than X6. > > '""""""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'"""'""'""'""'""'""'"""""""'""'"""'"""""'""'""""""'"""'""""""""""'""""'""""""'""'""'""'"""'"""""""'""'"""'""""'""""""'""'""'"""'"""""""'"""'""""'"""""'"""""""'""'""'""'"""'""""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'"""""""""'"""""""'""'""'"""'"'"""""""'"""'"'"""""""""'"""""""'"""""""'""'"""'""""'""""""'"""""""'""'"""'""""""""'"""'"'"""""""'""'""'""'""'"""'""""'""""""'"""""""'""'"""'"""'"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'""'""'""'""" > > > [Try it online!](https://tio.run/##vVLBDoIwDL37FbWXXYgf4FFPHk34AIc0sAQ2GN33z0EwGTiJB3Vpsrz29b12mdOWZCmLhrwXOB0xxXz9OnBhKjbcV7NhnI@EnjAlnJRZ82JSzFj2bikspnnf9hk92itVWw6b5G5s/PqmmBDe2nitIP70b772/1I7eo@5gYLAWNCGgUeQIfTOcA1cE5ykLTNAriXv1DClekcDK6PxsMsD7KyprGxbpSu4G82hKDWDpa5RVB4BL9C6gaFUg6wsUegycDuLyDOgDEYLCBaj5nW22OMD "Unreadable – Try It Online") Displayed in variable-width font, per the traditional tribute to the language name. I learnt Unreadable for this challenge, because it is obviously the best tool for the job. The only characters allowed in Unreadable are `'` and `"`, so surely it is perfectly suited to a challenge which involves changing `"` into `''`. Isn't it? Explanation: ``` '""""""'""'""" assign to X2 '""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""" 34 (double quote sign) '""""""'""'""'""'""'""" assign to X5 '""'""'""'""'""'"""""""'""'""" X2+5 (apostrophe sign) '"""""'""'""""""'"""'"""""""""" while (1+ (assign to X1 a value read from stdin, or -1 if stdin is empty) != 0) '"""" do 2 things '""""""'""'""'""'""" assign to X4 '"""""""'""'""" the value of X2 AND '"""" do 2 things '""""""'""'""'""" assign to X3 '"""""""'""" the value of X1 AND '"""" do 2 things '"""""'"""""""'""'""'""'""" while(X4 != 0) '"""" do 2 things '""""""'""'""'""'""" assign to X4 '""""""""'"""""""'""'""'""'""" X4-1 AND '""""""'""'""'""" assign to X3 '""""""""'"""""""'""'""'""" X3-1 end while AND '"""""""""'"""""""'""'""'""" if(X3 != 0) '"'"""""""'""" print X1 else '" print the output of '"""""""""'"""""""'"""""""'""'""" if(X34 !=0) '"""" do 2 things '""""""'"""""""'""'"""'""""""""'""" assign X34=0 AND '"'"""""""'""'""'""'""'""" print X5 else '"""" do 2 things '""""""'"""""""'""'"""'""" assign X34=1 AND '"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'""'""'""'""" print X5+57 end if end while ``` (Calls to X34 are actually calls to X(X5), since X5=34.) [Answer] # TeX, ~~54~~ 32 bytes For a TeX quotes replacement challenge we also need a TeX version of course! ``` \catcode`"13\def"#1"{``#1''}...\bye ``` `...` is the input string, so it doesn't add to the byte count. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 13 bytes Learning Retina quickly because for some reason I don't like Japt winning and feel like a C# solution would use regular expressions anyway. I know there is a Retina answer, but I haven't used it when creating this, and I found it (exactly) too anyway. ``` #2$`" `` " '' ``` [Try it online!](https://tio.run/##TY0xDsIwEAR7v2I5kNJESFBSQkWJlAfYkFNiifiS8@X9xkEUlLOr3VG2mMKplP354Ml578g1TSnUCZ4MUSQx2AYtYVnFRtjIuAbtW5CNwVzM32hZOVuUREfXVZxVBg3TFNOAlySrZUgG5fkdub@A7pjWbOhjDoMy15XA35o/Z6UWmwJVsX0@fooduQ8 "Retina – Try It Online") [Answer] # JavaScript (ES9), 34 bytes Working on quoted blocks: ``` s=>s.replace(/"(.*?)"/gs,"``$1''") ``` [Try it online!](https://tio.run/##TY4xj8IwDIV3foXPOqktKkW3ngRIMDEiMTIk15o0qI1L7PL3ewm64cbPT37fe9iXlTb6STeBO1ruu0V2e2kiTYNtqdxi2awPFW6d1GjM51dRYLW0HIQHagZ25b00eGX4IeAIgRU0Q43wnFl70J7gaGNXA2pvdeXlfXrOJOo5YLO6Jpwiu2jH0QcHqVxTaINCXuGp@wY8wziLQufFukiUvhhu5lT8k2asIUsgSXLr5U/ygaaqll8 "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 38 bytes Working on each double-quote separately: ``` s=>s.replace(/"/g,_=>(c="'`"[s^=1])+c) ``` [Try it online!](https://tio.run/##TY4xT8MwEIX3/orjliZqSMWK5A5lYkTqBoUY5@q4Snyp79K/H2zEwPjd073vXe3dikth1sfIPa0Xs4o5SJtoHq2jao9733yZQ@UMbjt8l0/zdK53rl4dR@GR2pF9dak6PDF8E3CCyApaoEG4LawD6EBwtKlvAHWwugnye7otJBo4Yrs5ZZwT@2SnKUQPuVxzaKNCWRKofwZ8hWkRhT6I9YkofzF8dC/bf9KCDRQJZElpffuTPGBX1@sP "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 13 bytes ``` ⁾``⁾''2ƭ”"Ƒ¡€ ``` [Try it online!](https://tio.run/##TY6xDcIwEEX7TPFx4yaioKSEihIpA8SQU2KU2Il9KeiADRiAgh5WoKDIIFnEOIiC5qT3T/ffHaiujyGM51eexyHlYniOp5sYru/7eHmEEKSUIrPYEayDsQyeIBXoessVuCKslCtSCK4UJ9p/o64nz9oaMU@yiK2zpVNNo02JvTUcl8owHLW1pmIJsUHTe0ahvSodUbyyyNfyzxkpxaRAVEyd259iJuKLHw "Jelly – Try It Online") Full program. [Answer] # [Python 3](https://docs.python.org/3/), 65 bytes ``` f=lambda s:s and(s[0],"`'"[s.count('"')%2]*2)[s[0]=='"']+f(s[1:]) ``` [Try it online!](https://tio.run/##TY4/T8MwEMX3fIrHSSgxRBWULVIWmBiRukWR6tZOYqnxpfZl4NOHC2JgfH/ufm/5lonj27YN7c3OF2eRmwwbXZW7l76mc0ldPlx5jVKVVJrHY/90NN0etq0a/fOgzdemN9uSgpaGiogKOjEuHpwQWSC7qAn3lWWCTB7vNrkaJJOVIuRf6776LIEjHYqTyiXxmOw8hzjiylE0tFGQ/HIL3jWgT8xrFriQ7Zi81yvG@aP8x1RVY0dAEfvPrz/Egw4kMmb7AQ "Python 3 – Try It Online") *-8 bytes thanks to Erik the Outgolfer* [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Would be 11 only for a limitation of (or maybe it's a bug in) Japt. ``` r'"ȲîT°g"`' ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciciyLLuVLBnImAn&input=JyJUbyBiZSBvciBub3QgdG8gYmUsIiBxdW90aCB0aGUgQmFyZCwgInRoYXQKaXMgdGhlIHF1ZXN0aW9uIi4KVGhlIHByb2dyYW1taW5nIGNvbnRlc3RhbnQgcmVwbGllZDogIkkgbXVzdCBkaXNhZ3JlZS4KVG8gYEMgb3Igbm90IHRvIGBDLCB0aGF0IGlzIFRoZSBRdWVzdGlvbiEiJw) ``` r'"ȲîT°g"`' :Implicit input of string r'" :Replace double quotes È :Pass each match through a function ² : Duplicate î : Replace each character with T° : Postfix increment T (initially 0) g"`' : Index into "`'" with wrapping ``` [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), ~~22~~ 21 bytes ``` `'("_*("+@"_*)+$!!@@) ``` [Try it online!](https://tio.run/##TY3BDoIwEETvfMXQmABC/ABPRE8eTbhLhQ00gW5pl@@vxXjwtHk7mXk02NENWi9@cTH2Rale51LVbTpVfcrztq1iVB3jTWAPywI5oFHYdpYZMhNu2o8NlMxaMhO@r22nIIatumRdQud58npdjZ0wsJUUaivw5BZD4xXqgXUPgtEEPXmi1GL09@LPmajBoUBSHJvPnyJXHw "!@#$%^&*()_+ – Try It Online") Terminates with an error. 21 looks like an impressive score, beating quite a few languages including Charcoal. Inspired by [this](https://esolangs.org/wiki/!@$%25%5E%26*()%2B#LOLOL). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` WS⊞υι⭆⪪⪫υ¶¦"⎇κ⁺ײ§'`κιι ``` [Try it online!](https://tio.run/##TY47T8QwEIT7/IrBzdmSj4KSq4AqSCcFXUqKM8kqti6xc/aax68PNlBQrEazj/l2sCYOwczb9mHdTJCtXzOfODo/SaXQ5WRl1nDq0HSlyfJ3djSrPK2zY/kcnK8b4tULVUVU6Sl6E7/kRaObc5K9WyjJO40Hbv1In1LszkLjolTNrqXUYdtEH/BGCBE@MLgaLXDNgS3YEh5NHAuDreHGpZ/WNVNiF7y4bfpi1ximaJal/IgheC5D4xmRyrM03kO0WHJijC6ZKRKVq4Dz0@4fsziNikBB1MyXP8SNaLb9@/wN "Charcoal – Try It Online") Link is to verbose version of code. Includes 8 bytes to avoid a cumbersome input format. Explanation: ``` WS⊞υι ``` Collect input lines until an empty line is reached. ``` ⪫υ¶¦ ``` Join the lines on newline characters. ``` ⪪..." ``` Split the input on quotes. ``` ⭆... ``` Map over each part and concatenate the results for implicit print. ``` ⎇κ...ι ``` Leave the first part unchanged. ``` ⁺ײ§'`κι ``` Prefix the appropriate quote, doubled. [Answer] # [R](https://www.r-project.org/), 40 bytes ``` cat(scan(,"",,,'"',""),sep=c("``","''")) ``` [Try it online!](https://tio.run/##TY1BCsIwEEWv8p1NWhg8gOBGVy4FD9CYDm3AZtpkev6aioK7efP5/@VtC96aEnxqmIiZHbl6tFxkPoeGuo6YnKO23eiheAo0I6nBdmDCsqqNsFFw8blnkI3eEMvntaxSLGqiIx4V56xD9tMU04CgyWrokyHL/IrSn0A3TGsx9LH4IYvUlqK7uj9nJcZPsW/ev4oDbW8 "R – Try It Online") Reads string input, separating at each `"`, giving a vector of strings. Then pastes those strings, alternating between the double backticks and the double apostrophes as separators, recycling them as needed. Someone will probably post a shorter R answer based on a regex... Still, this answer is more typical of R, I think. Explanation of the `scan(,"",,,'"',"")` part: ``` scan(, # empty first parameter: read from STDIN "", # type of input is a string , # default 3rd parameter nmax , # default 4th parameter n '"', # separate on character " "") # do not treat any characters as quotations marks (necessary to handle ' in the input) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ”"µJḊ⁾`'ṁḤż@ ``` A full program. **[Try it online!](https://tio.run/##TY6xDcIwEEX7THG4cRMxABWCCjokBoghp8QosRP7UtCRlh2oYAWkREIUSAziLGIcREH5/un/dwcsiqP3rr8Opwt73deuOw/tM@Gub113ez/m3nvOOdtq2CFoA0oT0Agxg7rRlAPlCAth0hgY5YIiab9R3aAlqRWbRtuAldGZEWUpVQZ7rSgchSIwWBUS0xmwFZSNJUilFZlBDC0NyZL/OQPFMCogKMbNzU8xYeHFDw "Jelly – Try It Online")** ### How? ``` ṣ”"µJḊ⁾`'ṁḤż@ - Main Link: list of characters, T e.g. ..."hi" - she "said"... ”" - character '"' '"' ṣ - split (T) at ('"') ["...","hi"," - she ","said","..."] µ - (call that X) start a new monadic chain J - range of length (of X) [1,2,3,4,5] Ḋ - dequeue [2,3,4,5] ⁾`' - list of characters ["`","'"] ṁ - mould like ["`","'","`","'"] Ḥ - double ["``","''","``","''"] ż@ - (with reversed @rguments) zip (with X) [["...","``"],["hi","''"],[" - she ","``"],["said","''"],["..."]] - implicit (smashing) print ...``hi'' - she ``said''... ``` [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), (43?) 53 bytes ``` 396" } "",)@ ~" ( "~ 3_: """ 4 " .;- = ; ..::; ``` **[Try it online!](https://tio.run/##TY2xDoJAEET7/YpxGzVBGoyJEBOjlaUJvZ5ygUvgDo6lsJBfx8NYWL6ZzLxaPV7eWKmmKdnvmPAGc7Q@EjAysCLwiOSWEjNjS4w429ABQEZxnKbZNHHu8NBwHtYJZIaI0Q1OKkilcVK@iMBSKSHTf6Nu0L0YZzmmPGDrXelV0xhb4umshFJZgddtbXSRgi9ohl5QmF6VXuuwcrifl3/OQBFmBYJi/rz@FAv@AA "Labyrinth – Try It Online")** A golfed version of this, much simpler, 92 byte program: ``` 3 """ 9 " ",)@ }96 " ( " :_34-;; " ; : """"""". : " . """"""""=. ``` If we don't need to handle input containing the zero byte **[then 43 bytes](https://tio.run/##TY2xDoIwGIT3PsX5Ly7IgjGhxMTo5GjCLlUaaAItlJ/BwWevrXFw/O5y9w3q8fLGch9CUb5LcQIOosmIRAOQkMjpmOfijgqJi/2uqqQMgWqHh4bzsI7BCTLCvDruwb3GWfk2A3GvWJjlG82rXtg4S7moI07edV6No7Edns5yLJVleD0NRrcSdMW4LozWLKrzWseVQ3PZ/jkjZUgKREX6vP0UG/oA "Labyrinth – Try It Online")**: ``` 39}9 @ 6 `,"" ` " : ."=.. _ ; " 34-;;:: ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes ``` {S:g/\"(.*?)\"/``$0''/} ``` [Try it online!](https://tio.run/##TY2xDoIwGIR3n@JsjKgh4ORAYkx0cjQyMlClQBPaQvt3IMZnx2IcHL@73H29sN1hUiPWNY7T6541acE2ye60LVhalqt9FKXvyfERNVznbT@x3OAhYCy0IdAMMcPgDbWgVuDMbRWDUctpId03GrxwJI1mySIP2FvTWK6U1A2eRlMouSZY0XdSVBnYFco7QiUdb6wQYWVQXqI/Z6AYswJBMX/efool@wA "Perl 6 – Try It Online") Darn, the obvious solution is shorter. Replaces each quoted portion with a version with the appropriate quotes. # [Perl 6](https://github.com/nxadm/rakudo-pkg), 24 bytes ``` {S:g{\"}=<`` ''>[$++%2]} ``` [Try it online!](https://tio.run/##TY2xDoIwGIR3n@JsVAaIg4MDEQedHI1sakKVAk2ghfZnIIRnr8U4OH53uftaYeq9awZsCiRuvMXl@GBTcsgyBMHxvgrD9e45OcsHFLB1b1rHUo2XgDZQmkAzRAxdr6kCVQInbvIIjCpOC2m/UdcLS1Irtl2kHlujS8ObRqoSb63Il1wRjGhrKfIY7IKmt4RcWl4aIfxKIzsHf05PEWYFvGL@vP4US/YB "Perl 6 – Try It Online") Replaces each double quote, alternating between the two sets of characters. [Answer] # [Red](http://www.red-lang.org), 79 bytes ``` func[s][q:"^""parse s[any[to change[q copy t to q q](rejoin["``"t"''"])skip]]s] ``` [Try it online!](https://tio.run/##TY69TsQwEIT7PMWwTUCK7gFSQkUJus4yii/eJAbi301xQvfswUQIUc7M7nyT2e6vbJVuph77tPlRFa1ST29E0eTCKMr4q5KAcTF@ZpUwhniFoFoJSd9nfg/OKxoGEmpb0g/lw0Wti95jdl4w4YvOARdGyPDh@LxwR0hbkAWyMB5Nth1IFiNoXDm8tHERFzydbs1f0bkGMYc5m3V1fq5bvNQzU9PM8dOx7UHPWLcisK6YOTOfmkofntp/@Ko6HLQK@@l8@YXd0W3/Bg "Red – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 15 bytes ``` " "" Y`"`\`\`'' ``` [Try it online!](https://tio.run/##TY2xDoJAEET7@4pxGxpiYmuplaUJjQkFp2zgErmFveX7cTEWZqo3m52nbCnH07ZRIAqPjrrWU1VeNIInQxRZDLZDTVhWsRE2Mi5R@xpkY7SQyrdaVi6WJNMxNI6zyqBxmlIe8JJsfozZoDy/E/dn0A3TWgx9KnFQZv8SdNfqz@lUY1fAFfvm/ac40Ac "Retina – Try It Online") Edges out the boring Retina 0.8.2 answer by 1 byte. Explanation: ``` " "" ``` Duplicate all of the quotes. ``` Y`"`\`\`'' ``` Cyclically replace the quotes with pairs of backticks and single quotes. Boring 16-byte [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) answer for completeness: ``` s`"(.*?)" ``$1'' ``` [Try it online!](https://tio.run/##TY2xCsJAEET7fMW4CFEJgq2NoJWlkA@40yzJgblN9jbff17EwvLNMPOULUSfc3K0Ox4ue6qc257qOmdqBU@GKKIYbIWGMC9iA2xgXL12DcgGb1VI32heOFmQSMeqLTip9OrHMcQeL4lWSh8NytM7cHcG3TEuydCF5HtlLiuBu9V/zkINVgWKYv18/BQb@gA "Retina 0.8.2 – Try It Online") [Answer] # [PHP](https://php.net/), 62 bytes Non-RegEx solution: ``` for(;''<$l=$argv[1][$i++];)echo$l=='"'?["''","``"][++$j%2]:$l; ``` [Try it online!](https://tio.run/##TY3BCsIwEETvfsW6RKK0CHq0FUFPHgVvpdBoYxNpszHd@vs1FQ9eBt4sO88bP@YHH/NBYZlJmYt2L1Ro3sWmLIRNkjJb6buhWO8lykOBUmKKVYVlkSTiudiWO9Fm4zjileCmgQI4YuAJUoTXQGyAjYajCnUKyEbxzPbf6jXoni05XM@uEX2gJqius66BOzmOR@UYgvat1fUO8Azd0DPUtldN0Dp@EVQn@eeMlMKkgKiYNi8/xRw/ "PHP – Try It Online") --- # [PHP](https://php.net/), 48 bytes Port of [Arnauld's RegEx solution](https://codegolf.stackexchange.com/a/190783/81663): ``` <?=preg_replace('/"(.*?)"/s',"``$1''",$argv[1]); ``` [Try it online!](https://tio.run/##TY7LCsIwEEX3fsU4CGklKG59UNCVS8GdiI3tkAZskiZTfz@m4sLlucO9Z3znU9pXBx9IPwL5l2qoEGssVsuqxHUUEut6sREC5UIF/b5t7uUupYRXB08CF8A6Bp5AIgyj4w64Iziq0EpA7hTPTPxGw0iRjbO4ml0z@uB0UH1vrIbGWc5HZRmmHwy1W8Az9GNkaE1UOhDlloP6JP6cmSRMCsiKafPyU8zxAw "PHP – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~69~~ 68 bytes ``` t=39,z;f(char*s){z=*s-34?*s:257*(t^=71);printf("%s",&z);*++s&&f(s);} ``` [Try it online!](https://tio.run/##TY5dS8MwFIbv@yuOAWuSZYJOGVsogl55KewyiDFN28CadMnpTcd@e01F0cv3vB/PMevWmHnGarMTk2yo6XTkiZ2niqf15uGJp/3945ZTfK@2d0wO0XlsKLlORJQTk3y1SmXZ0MTkZe6185TBuYCcUOQQ4NNCiOADAi5CKAKnMWAH2Fl41rEWoAh2GpUnBQAQl76t02gTuuAVuf11Dvk8xNBG3ffOt2CCxxzSHiHa4ehsvc9br9CPCaF2SbfR2r92gI@Xm3/PZCVgIUNGLttvP8grRXKJyeIyfwE "C (gcc) – Try It Online") One byte shaved off by @ceilingcat! [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda s:re.sub('"(.*?)"',r"``\1''",s,flags=16) import re ``` [Try it online!](https://tio.run/##pY49a8QwDIZ3/wpVi5JiAtehw0EotFPH0htvsNM4iSH@OFsZ@utTJ9xw0BsK3fRK6H2e@M1T8E/r0J7XWbuu15CPyTR56SrCqnl8qZFkQqXOByKUWQ6zHnN7eK6FdTEkhmTW3CKiwFOAzkBI4AMDb0EiXJbAE/Bk4FWnXgLypFnYvK8ui8lsg8dGnEqMKYxJO2f9CF/BczlqvxHibE1/BHwHt2SG3mY9JmPKVwD1RjfMkiRsCCiIrfPjingogkVS8O6q1B1Zol@2St3TJfqbr1L/ESbajWOye2fzeR2HKtc3Y9uyWH8A "Python 2 – Try It Online") Although I really like [Jitse's answer](https://codegolf.stackexchange.com/a/190790/69880). [Answer] # (GNU) [sed](https://www.gnu.org/software/sed/), ~~38 33~~ 30 bytes ***-4** by removing the `-n` flag and implicitly printing on `n`, **-1** by reusing previous `/expression/`, thanks @Cowsquack. **-3** by using implicit branch-to-end.* ``` :a s/"/``/;T :b s//''/;ta n;bb ``` ~~[Try it online!](https://tio.run/##TY0xDsMgDAB3XuGyZEmaPdnaqWOlPCBQEEFqbALm@6UQdejmO8u@ZM3gMJcyKZFGOa7rOLMWYdZi0qfpumpUNThrXYpcCLQFioDEwA16CUcm3oA3CzcVTQ@SN8XCp1Md2Sb2hPIqloohkotq3z06eBFyXSpkiDa8vTUTyAfsOTEYn5SL1tYrgvXe/TUr9dASUBPt5/OXuEjxodCmVAb8Ag "sed – Try It Online") [Try it online!](https://tio.run/##Tc0xDsIwDIXhPad4ZOlSyN5uMDEi9QBNiJVGonFJnPOXFDEwfrbsv5A/h1T3fbCqGG3m2YzilFODazZd12hVGp3bdz0xHIEzEgvkQK/xriwLZCFcbfY9tCxWVCzf0btSkchJX9TUuGUO2a5rTAFPTtKWNgkyba9IfoC@Y61F4GOxIRO1K8Z86/6aTT2OBFri@Pn4JU5afQA "sed – Try It Online")~~ [Try it online!](https://tio.run/##TY0xEsIgFER7TrHSpInSJ51Wls7kAAHzhzBj@BE@50fiWFi@3dl9mZazj6XWwapstJlnM05qcA1M15lRrIqjc7XqieEInBBZIAf0Gu/CskJWwtWmpYeW1YoK@Ru9C2UJHPVFTQ33xD7ZbQvR48lRWmmjINH@CrQM0HdsJQuWkK1PRG3FmG/dn7NRj0OBpjg@Hz/FSasP "sed – Try It Online") Some pretty basic label jumping. ~~This can probably be golfed by a byte or two.~~ ``` :a # label a s/"/``/;T # replace " -> ``. If unsuccessful, move to next line :b # label b s//''/;ta # replace " (implicit) -> ''. If successful, jump to a (w/o reading new line) n;bb # read in the next line, but jump to label b. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` û╩↕H£ñ╟Uzay ``` [Run and debug it](https://staxlang.xyz/#p=96ca12489ca4c7557a6179&i=%22To+be+or+not+to+be,%22+quoth+the+Bard,+%22that%0Ais+the+question%22.%0AThe+programming+contestant+replied%3A+%22I+must+disagree.%0ATo+%60C%27+or+not+to+%60C%27,+that+is+The+Question%21%22&a=1&m=1) ### Procedure: 1. Take all input, newlines and all. 2. Regex replace `'"'` with a block that produces alternating outputs of pairs of backticks and foreticks(?) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` '"¡ā¨„'`sè2×.ιJ ``` [Try it online!](https://tio.run/##TY0xDoJAFESvMm5DQygsLbXSzoQDsMgPbCL7YffT6ynsTOy4gi1YewgvsoLRxPLNZOax17mhECI13B7noX@drlHmx345XpLnfReCShk5gR0sC2SGWKHtWCpIRVhrV8RQUmmB8Z@o7ciLYasSpBM2jkun69rYEge2MpXaChw1R0PFCmqLuvOCwnhdOqJpxcg20Z9zohg/xfy5/yoW6g0 "05AB1E – Try It Online") No regexes in 05AB1E, so we split on `"`, make a list of alternating ```` and `''`, then interleave the two. [Answer] # [Haskell](https://www.haskell.org/), ~~67~~ ~~60~~ 58 bytes ``` (#0) ('"':x)#n=["``","''"]!!n++x#(1-n) (a:b)#n=a:b#n x#n=x ``` [Try it online!](https://tio.run/##y0gszk7NyfmfbhvzX0PZQJNLQ11J3apCUznPNlopIUFJR0ldXSlWUTFPW7tCWcNQNw@oItEqCSQPpJTzuCqArIr/uYmZebYFpSXBJUU@eSrpSsVAEKNUkppQrF4So5RYnJCinqj0/19yWk5ievF/3QjngAAA "Haskell – Try It Online") The relevant function is `(#0)`. Since I originally thought the question also required us to convert single quotes here is a version that handles both: # [Haskell](https://www.haskell.org/), 125 bytes ``` (#(1<0,1<0)) ('"':x)#(m,n)=last("``":["\""|m])++x#(not m,n) ('\'':x)#(m,n)=last('`':['\''|n]):x#(m,not n) (a:x)#n=a:x#n x#n=x ``` [Try it online!](https://tio.run/##XcpBCsIwEAXQfU8hE2ESWkG3way8QMGN0BQ6aKvFJIqJkEXPbkxcOvAZ@P/dyN9HY9KkdOKM7/bbJkeIiiOgjIJx2zihDPnAYRhAdqABFtuLuo6Mu0dYFZC5xn@PA8qu9IvrhYy/KfuiqVCn8mOuylExWZqder7DMbzWE/h8GsKIHoMG8nhBgvQ5T4auPm1Oh7b9Ag "Haskell – Try It Online") [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 14 bytes ``` "(.*?)" ``\1'' ``` [Try it online!](https://tio.run/##TY2xDsIwEEP3foXJUkBVJVYWJJg6InVk6EFObSSaa5PL94cUMTA@W/ZbE9mQs9m3x8vBVMPwONV14V7wZEiAF4Vu0BisSXSCTowrBdvA6ERaufiN1sRRnXjTVn3BJcgYaJ6dH/ESr6Ukrwi8vB3bM0yHOUWFdZHGwFxWguFW/zkLNdgUKIrt8/5T7Ey2mT4 "QuadR – Try It Online") Simple find/replace using @Adám's wrapper for Dyalog APL's `⎕R`eplace function. ### How: ``` "(.*?)" ⍝ PCRE, finding anything between two double quotes and assigning it to group 1 ``\1'' ⍝ Transformation string, replacing the match with ``group_1''. ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~35~~ 34 bytes ``` 1:c;{.34={;c)2%:c'""'"``"if}""if}% ``` [Try it online!](https://tio.run/##TY3LCoMwEEX3/YrpgEhBhD5WSjftqsuCH2AaYwxoRpNxJf32NClddDNw5nLv0TT2XjozcwjHStZbeb5ct1oeTlklc8Qc2xZN/8Z0shCwIXgpIAeWGDhBgbCsxAPwoOAmXFcA8iB4Z/z3tazKsyGL5a6JODvSTkyTsRokWY6hsAxOzaNRXQX4gGn1DJ3xQjulYougved/zkgFJAVERdp8/hR7/AA "GolfScript – Try It Online") # Explanation ``` 1:c; # Set 1 to the current item counter { }% # Map for every character in the input: .34= if # If the character isn't the quote, "" # Just leave it alone { } # Otherwise: ; # Remove the copy of the input c):c # Increment the counter 2% if # If the counter isn't divisible by 2, '""' # Output the double-quote "``" # Otherwise: Output the double backtick ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `Ṡs`, 18 bytes ``` \"Ẇƛ\"=[&›¥₂[\'|\` ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%A0s&code=%5C%22%E1%BA%86%C6%9B%5C%22%3D%5B%26%E2%80%BA%C2%A5%E2%82%82%5B%5C%27%7C%5C%60&inputs=%22hello%22&header=&footer=) ``` \"Ẇ # Split on ", keeping delimiter ƛ # Map... \"=[ # If a " &› # Increment the register ¥₂[ # If even... \' # Single quote, |\` # Else backtick. ``` [Answer] # [Lua](https://www.lua.org), 36 bytes ``` print((...):gsub('"(.-)"',"``%1''")) ``` [Try it online!](https://tio.run/##TY3BCsMgEETv@YrtQlHBCr3m2J56LOQDYhsxQuImun6/NaWHHt8MM28pttYthchSGmNU73N5SYHSXBQKjeN4vgqBStVacSB4OaAEkRj4AI2wF@IZeHZws2nSgDxb7kL@RntxmQNFNN3QcEvkk13XED28KXIrbWRIbluCm3rAB6wlM0whW5@cayuC8S7@nI00HApoiuPz@VOc8AM "Lua – Try It Online") Wow, only two chars longer than js solution. [Answer] # [Perl 5](https://www.perl.org/) `-p0`, 19 bytes ``` s/"(.*?)"/``$1''/gs ``` [Try it online!](https://tio.run/##TY0xDsIwDEX3nsJYSAVUWhhYWJBgYkTqARqolUZq4zRxr09IEAObn7/@f478eIoxNLipd5ctNl23PpZlo0OM2DI8CdiDZQHJUCHMC8sAMhBcle8rQBmUFCZ8X/NCQQxbrIs2ofOsvZomYzW82EoKlRXw5EZD/RnwDtMSBHoTlPZEqcXQ3co/Z6IKsgKSIm8@fooVvtnlI8S9O3wA "Perl 5 – Try It Online") [Answer] # Java 8, 40 bytes ``` s->s.replaceAll("\"([^\"]+)\"","``$1''") ``` [Try it online.](https://tio.run/##TZBRS8MwFIXf9yuOQWiLXcFXxwT1yQcH4t6WSbM2tplt0iW3A5H99noz@uBLyD3hnO@eHNVZLY/191R1KgS8KWN/F4CxpP2XqjQ2cQQ@yBvboErnS8hWrF8WfARSZCpsYLHGFJaPofB66Nj81HWpkCLdfUqxv8ukELkoy9v7JBHZtIreYTx07J0jzs7U6HmFmbLbQ2Uz/yeQ7gs3UjHwE3U2tUUV07cOBw3nYR2B4pBLgdPoqAW1Gs/K1zmkoFaRtCZcxdOoAxlnpSik3bIweNd41ffXko7b80qWEIsYXT@w/xX9GAi1CarxWkefQ/mS/EPzlCNywJiY@j5jbrh6Nv/YZfoD) **Explanation:** ``` s-> // Method with String as both parameter and return-type s.replaceAll("\"([^\"]+)\"", // Replace all these matches, "``$1''") // with this replacement ``` *Regex explanation:* ``` "([^"]+)" // MATCH: " "// A literal " [^"]+ "// Followed by 1 or more non-" characters ( ) // (captured in capture group 1) " "// Followed by a literal " again ``$1'' // REPLACEMENT: `` // Literal `` $1 // Followed by the match of capture group 1 '' // Followed by a literal '' ``` [Answer] # [Wren](https://github.com/munificent/wren), 91 bytes ``` Fn.new{|n| var c=1 for(i in n.split("\"")[1..-1])System.write(((c=-~c)%2==0?"``":"''")+i) } ``` [Try it online!](https://tio.run/##TY9BS8QwEIXv/RVjQNqw3WA9LhTBBcGjuDcrNKazbaCd7CZTi7j612siHjy@N7z3zVs80vquPRxnMlDD@kCKcPm80CVLtqmr7Oh8YcESkAqn0XIhGiHkS6XUtnqVzx@BcVKLt4xFUZh6@23k9W1d39yJthU7kedCbqzMvtbEUEaPY2o4OHhDcB7IMXASZSPgPDsegAeEe@27EhrBg@bMhl/vPGNg66gRKjtEffKu93qaLPVgHHG8amLwGN/EbhfTjzDNgaGzQfceMcYctPv8HzeqEhIEIiSVPv1BrtLK9Qc "Wren – Try It Online") ## Explanation ``` Fn.new{|n| // New anonymous function var c=1 // Set the index counter as 1 for(i in n.split("\"") // For each over n splitted with quotes [1..-1]) // Get rid of the first quote System.write( ) // Output this to the console ( (c=-~c) // Increment the counter %2==0?"``" // If that's divisible by 2, output a backquote :"''" // Otherwise, output a frontquote )+i // Join the result with i } ``` ]
[Question] [ [![enter image description here](https://i.stack.imgur.com/nhS8q.jpg)](https://i.stack.imgur.com/nhS8q.jpg) Normally, challenges are scored in bytes, or sometimes Levenshtein distance, but for this one we're using keyboard distance -- the number of keys between the keys used to type the program (use the above keyboard as the definitive reference). For example, the distance between `A` and `F` is 3, because the path is `A`=>`S`=>`D`=>`F`. The distance between `N` and `5` is 4, because no matter what path you take, it requires at least 4 steps. Your task is to output the following (not including trailing spaces), with as small a keyboard distance as possible: ``` Q W E R T Y U I O P A S D F G H J K L Z X C V B N M ``` ## Wrapping: To make your life easier, certain keys can wrap around the keyboard. `Left Shift` wraps to `Right Shift`, `Caps Lock` wraps to `Enter`, `Tab` wraps to `\` and `~` wraps to `Backspace`. For example, the distance between `Q` and `P` is 5, because `Q`=>`Tab`=>`\`=>`]`=>`[`=>`P`. **Note:** Wrapping only works horizontally -- you can not step from, say, `\` to `Caps Lock` ## Scoring: **Score = Keyboard distance + byte count** ## Example Calculation: `print(5);` * `p`=>`r` == 6 * `r`=>`i` == 4 * `i`=>`n` == 2 * `n`=>`t` == 3 * `t`=>`(` == 4 * `(`=>`5` == 4 * `5`=>`)` == 5 * `)`=>`;` == 2 **Total:** 30 + 9 = **39**. ## Notes: 1. Lowercase and uppercase letters count as the same key. If a key has two symbols on it (like `7` and `&`), they also count as the same key, no need to include pushing shift. 2. Unfortunately, if your code requires symbols that are not on the keyboard you cannot use it. 3. On the keyboard image, the top row can be ignored. The only key you can use on the bottom row is `Space` 4. Keys must be inputted in order, you can't use the arrow keys to move the caret and then input a key. ## Score Calculator: * **Updated on 12/27 to fix ```=>`]` and related miscalculations. Check your scores again, and they will likely be smaller (hopefully not bigger!)** Paste in your code here to calculate the score. Let me know if you ever get an error or it prints out the wrong number. ``` var keys = ["~1234567890-=←","\tqwertyuiop[]\\","↑asdfghjkl;\'\n","Lzxcvbnm,./R", "AB CDEF"]; var con =["`!@#$%^&*()_+{}|:\"<>?","~1234567890-=[]\\;\',./"]; function hexagon(k) { if(k === " ") return ["x","c","v","b","n","m",","]; var p = pos(k); if(p === -1) return false; var row = p[0],col = p[1]; var hexagon = [char(row,col-1,1),char(row-1,col),char(row-1,col+1),char(row,col+1,1),char(row+1,col),char(row+1,col-1)]; return hexagon; } function char(r,c,wrap) { if(r < 0 || r >= keys.length) return ""; if(r === keys.length-1 && 1 < c && c < 8) return " "; if(wrap) { if(c === -1) c = keys[r].length-1; if(c === keys[r].length) c = 0; } return keys[r].charAt(c); } function pos(c) { var row = -1, col = -1; for(var i = 0;i<keys.length;i++) { col = keys[i].indexOf(c) if( col != -1) { row = i; break;} } if(row === -1) return -1; return [row,col]; } function dist(a,b,s,w) { if(typeof a === "object") { var list = []; for(var i = 0;i<a.length;i++) { list[i] = dist(a[i],b,s,w); } return list; } if(a==="") return Infinity; if(a===b) return 0; var p = pos(a); var q = pos(b); if(!w && a!==" ") { var chars = keys[p[0]].length; var opp = char(p[0],p[1] < chars/2 ? chars-1 : 0); return Math.min(dist(a,b,s,true),dist(a,opp,s,true)+dist(opp,b,s,true)); } if(!s) { return Math.min(dist(a,b,true,w),dist(a," ",true,w)+dist(" ",b,true,w));} var h = hexagon(a); if(a === " ") return 1 + Math.min(...dist(h,b,true,w)); if(p[0]<q[0]) { return 1 + Math.min(dist(h[4],b,s,w),dist(h[5],b,s,w)); } else if(p[0] > q[0]) { return 1 + Math.min(dist(h[1],b,s,w),dist(h[2],b,s,w)); } if(b===" ") return Math.min(Math.abs(p[1]-7),Math.abs(2 - p[1])); var d = Math.abs(p[1]-q[1]); return Math.min(d,keys[p[0]].length-d); } function getTotalDistance(str) { for(var i = 0;i<con[0].length;i++) str = str.replace(new RegExp("\\"+con[0].charAt(i),"g"),con[1].charAt(i)); str = str.toLowerCase(); var total = 0; for(var i = 0;i<str.length-1;i++) { total += dist(str[i],str[i+1]); } return total; } enter.onclick = function() { var a = getTotalDistance(program.value); var b = program.value.length; len.textContent = a; count.textContent = b; total.textContent = a+b; }; ``` ``` <textarea rows=15 cols=40 id="program"></textarea> <input type="submit" id="enter"/> <div> <div>Key distance: <span id="len"></span></div> <div>Byte count: <span id="count"></span></div> <div>Total: <span id="total"></span></div> </div> ``` ### Related: * [The very weird word counter](https://codegolf.stackexchange.com/questions/52439/the-very-weird-word-counter) * [Output the qwerty keyboard](https://codegolf.stackexchange.com/questions/64639/output-the-qwerty-keyboard) * [DISARM THE B.O.M.B.!](https://codegolf.stackexchange.com/questions/31552/disarm-the-b-o-m-b) [Answer] # [Unary](https://esolangs.org/wiki/Unary), score ~6.1\*10618 `6103247739090735580402225797524292167653462388595033897325606983093527722629493568418069722646005695215642120674994001348606253869287599178270707482456199630901069511698694317195626565008736452130034232375778047932461822258369348260249011643486476832847755830117284465136723525376668555270734061914837886192012601522703308221225195058283657800958507281265116257152529161080096092081620384043514820427911786442536988705847468796481108000358361636640985892696216392434604543586511103835032034494033598102606339253132146827455065586119645920456668064941286708686113567081095434338440184737976711767750474398662381256908308 zeros` Not the most "creative" solution but it took my computer ~3 minutes to convert the base 2 representation of this to base 10 --- This *used to* have a **score of 0**, but the scoring rules changed. Code Length: ~6.1\*10618 Key Distance: 0 [Answer] # [Japt](http://ethproductions.github.io/japt?v=master&code=IlFXRVJUWVVJT1AKQVNERkdISktMCidaWENWQk5NInEgcVMgcicnIg==&input=), score ~~123~~ ~~119~~ ~~118~~ ~~116~~ 106 ~~42~~ ~~41~~ 40 bytes + ~~81~~ ~~78~~ ~~77~~ ~~75~~ 66 distance ``` "QWERTYUIOP ASDFGHJKL 'ZXCVBNM"q qS r''" ``` (proper output in the "output" box) [Answer] # JavaScript (ES6), score 188 ``` alert([...`QWERTYUIOP ASDFGHJKL `," Z",..."XCVBNM"].join` `) ``` Only just barely gets a better score than `alert`ing the output string but it's the best approach I could find... : / Bytes: `60` Key Distance: `128` [Answer] # Pyth, score ~~107~~ ~~106~~ 102 ``` :jd"QWERTYUIOP ASDFGHJKL ]XCVBNM""]"" Z ``` [Try it online.](https://pyth.herokuapp.com/?code=%3Ajd%22QWERTYUIOP%0AASDFGHJKL%0A%5DXCVBNM%22%22%5D%22%22+Z&debug=0) [Answer] # Bash + Sed, 151 ``` sed 'sb *.b& bg'<<<'QWERTYUIOP ASDFGHJKL ZXCVBNM' ``` [Answer] # Python, ~~157~~, ~~156~~, ~~211~~, 221 points Key Distance: 157 Bytes: 64 Ergo, total score is 221. ``` l=' '.join('QWERTYUIOP\nASDFGHJKL\nZXCVBNM') print l[:42],l[42:] ``` Prints the string but has to add an extra space. :( now longer. Why @Pietu, why did you do this to me? [Answer] # JavaScript, score 156 ~~187~~ ``` [...`QWERTYUIOP ASDFGHJKL`].join` `+` Z X C V B N M` ``` Not bad for JavaScript [Try it online](http://vihanserver.tk/p/esfiddle/?code=%5B...%60QWERTYUIOP%0AASDFGHJKL%60%5D.join%60%20%60%2B%60%0A%20%20Z%20X%20C%20V%20B%20N%20M%60) --- With alert, **score 186** ``` alert([...`QWERTYUIOP ASDFGHJKL`].join` `+` Z X C V B N M`) ``` [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 118 + 51 = 169 [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=UiBteyJRV0VSVFlVSU9QJ0FTREZHSEpLTCdaWENWQk5NIiNETisqUycgUkgnIH0iXG4i) (underscores in explanation used to denote a used space) ``` R m{"QWERTYUIOP'ASDFGHJKL'ZXCVBNM"#DN+*S' RH' }"\n" _m map {"QWERTYUIOP'ASDFGHJKL'ZXCVBNM"# that array DN } with this function +*S'_ that concats (index many) spaces RH'_ with the inner array joined by spaces R and join that "\n" with newlines ``` # Jolf, update post-question, 76 + 21 = 97 Try it [here](http://conorobrien-foxx.github.io/Jolf/#code=UiBtcEhETisqUycgUkgnIH0iXG4i)! Again, I don't often update my code until relevant. Still fun. ``` R mpHDN+*S' RH' }"\n" _m map pH the keyboard array [["Q","W",...,"P"],["A",...,"L"],["Z",...,"M"]] DN } with this function +*S'_ that concats (index many) spaces RH'_ with the inner array joined by spaces R and join that "\n" with newlines ``` [Answer] # Bash + sed, score ~~202~~ 200 ``` sed 's/\([^ ]\)/\1 /g'<<F QWERTYUIOP ASDFGHJKL ZXCVBNM F ``` [Answer] # Python, score 185 ``` print" ".join("QWERTYUIOP\nASDFGHJKL\n")+" Z X C V B N M" ``` ]
[Question] [ ## Task The task is to write a program that outputs a consistent but otherwise arbitrary positive integer \$x\$ (so strictly greater than 0). Here's the catch: when the source is repeated \$N\$ times (the code is appended/concatenated \$N-1\$ to itself), the program should have a \$\dfrac{1}{N}\$ probability of outputting \$N\cdot x\$ and the remaining probability of \$\dfrac{N-1}{N}\$ of outputting \$x\$ unchanged. ## Example Let's assume that your initial source is `XYZ` and produces the integer `3`. Then: * For \$N=2\$: `XYZXYZ` should output \$3\$ with a probability of \$\frac{1}{2}\$ (50% of the time) and \$2\cdot 3=6\$ with a probability of \$\frac{1}{2}\$ as well (50% of the time). * For \$N=3\$: `XYZXYZXYZ` should output \$3\$ with a probability of \$\frac{2}{3}\$ (66.666% of the time) and \$3\cdot 3=9\$ with a probability of \$\frac{1}{3}\$ (33.333% of the time) * For \$N=4\$: `XYZXYZXYZXYZ` should output \$3\$ with a probability of \$\frac{3}{4}\$ (75% of the time) and \$4\cdot 3=12\$ with a probability of \$\frac{1}{4}\$ (25% of the time) and so on.... ## Rules * You must build a **full program**. The output has to be printed to STDOUT. * Your program, should, in theory, output each possible value with the probabilities stated above, [but a slight deviation from this due to the implementation of random is fine (*provided that the implementation is not of a different distribution - you can't use a normal distribution to save bytes*)](https://codegolf.meta.stackexchange.com/a/10923). * The program should (again, in theory) work for an arbitrarily big value of \$N\$, but technical limitations due to precision are fine for large \$N\$. * The output must be in base 10 (outputting in any other base or with scientific notation is forbidden). Trailing / leading spaces and leading zeroes are allowed. * The initial source must (of course) be at least 1 byte long. You may **not** assume a newline between copies of your source. The program should not take input (or have an unused, empty input). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so an answer's score is the length of the (original) source in bytes, with a lower score being better. Note: This challenge is a (much) harder version of [this one](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output). [Answer] # [R](https://www.r-project.org/), ~~66~~ 35 bytes -29 bytes thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall). -2 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe). ``` +0->A x=!0:F F=F+1 sample(F*x+!x,1) ``` [Try it online!](https://tio.run/##K/r/X9tA186Rq8JW0cDKjcvN1k3bkKs4MbcgJ1XDTatCW7FCx1Dz/38A "R – Try It Online") [Check the distribution for N=4.](https://tio.run/##K/r/X9tA186Rq8JW0cDKjcvN1k3bkKs4MbcgJ1XDTatCW7FCx1CTbkr@lyQmAflFqQU5mcmJJakahgZAoIOuTFPzPwA "R – Try It Online") The key is the rightwards assignment `->`. When the code is multiplied \$N\$ times, the first \$N-1\$ calls to `sample` will be assigned to `A`, and only the last call will be printed. Original, more convoluted solution: # [R](https://www.r-project.org/), 66 bytes ``` T->TT F=F+1 TT=0 `?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1)) ?T ``` [Try it online!](https://tio.run/##K/r/P0TXLiSEy83WTduQKyTE1oArwT7BNq00L7kkMz9Po0IzMw1IFCfmFuSkaiRrGOq4aeoY6uiAWbqGmppc9iH//wMA "R – Try It Online") [Try it online (repeated 3 times)!](https://tio.run/##K/r/P0TXLiSEy83WTduQKyTE1oArwT7BNq00L7kkMz9Po0IzMw1IFCfmFuSkaiRrGOq4aeoY6uiAWbqGmppc9iGDwYT//wE "R – Try It Online") Uses two tricks: 1) call the main function of interest `?`, so that we can call it without ending the program with a bracket, and 2) use variables `T` and `TT`, with code which starts with `T` and ends with `?T`. `F` is the iteration counter. `?` is redefined as a function which takes a boolean argument: if the input of `?` is `TRUE` (or `T`), it does the required random sampling; if the input is `FALSE` (or `0`), it does nothing. The value of `TT` is defined as `0`, so that `?T` does the sampling but `?TT` does nothing. When the source is repeated, it looks like this: ``` T->TT F=F+1 TT=0 `?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1)) ?TT->TT F=F+1 TT=0 `?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1)) ?T ``` so the middle call `?TT` outputs nothing but the final call `?T` outputs the random result. [Answer] # [Python 3](https://docs.python.org/3/), ~~81~~ 79 bytes ``` +0if[]else 1 from random import* try:n+=1 except:n=1 print([1,n][random()*n<1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/X9sgMy06NjWnOFXBkCutKD9XoSgxLwVIZeYW5BeVaHGVFFVa5WnbGnKlViSnFpRY5QGZBUWZeSUa0YY6ebHREOUamlp5Noaxmv//AwA "Python 3 – Try It Online") *-1 byte thanks to @Nishioka* This is one Python 3 solution that does not access the program source directly. Doing this in Python 3 is more challenging than Python 2 because normal printing statements end with a closing parenthesis so there aren't many choices to change its behavior in the next block of initial source. It would be interesting to see more creative solutions in Python 3. [Answer] # [Bash](https://www.gnu.org/software/bash/), 31 bytes ``` trap echo\ $[RANDOM%++n?1:n] 0; ``` [Try it online!](https://tio.run/##VY49D4IwGIT3/ooLgXQwEDAuAsGYqJuSuIoDX4UuLSllUn97LV2MN72X9@7JNfU8mrbWKDAgz0HP5YUareoJfTvKCv7jfrydymuw2YhDkoon4szYENFqEbbYI5wRJhgIkwocXOCVRNH@k6GTBFYrfUBRgDk7KS40Ay0XPS16hmSwJAS7LgWF53PPxf5o2/iHW9XY1WB4QyvQSlBbpO7ZSdG7Yx1PnDNf "Bash – Try It Online") `trap ... 0` will run the code contained on exit. Repeated `trap`s will overwrite old ones. The unquoted `$[arithmetic expansion]` gets run every time a new trap is set. --- [Zsh can save one byte with `<<<`:](https://tio.run/##VYyxDoIwAER3vuJCIB0IBNjEBmOibkriqg4EWmBpSVsSg/rtWLoYb7rL3b1Z90tTG5ToQCnIsTqRxah6hE8pDW7X/eVQncMoErusEA8f6XaxG8@oSdgfQ6wRZ@g8LhUGDAKvLEk2ny1a6cFqhXcoS3AXRzUIw0HyFJagITnC9gktJ9WwAgR@MPhu@QfM0x9x1ax7cLxhFMhdEPsjrmulYM6wppeeS8sX "Zsh – Try It Online") ``` trap "<<<$[RANDOM%++n?1:n]" 0; ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ‘ɼḷXỊ®* ``` [Try it online!](https://tio.run/##ARgA5/9qZWxsef//4oCYybzhuLdY4buKwq4q//8 "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ¾Å1¼¾ªΩ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0L7DrYaH9hzad2jVuZW4Of//AwA "05AB1E – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 78 76 75 bytes Using the same trick as in the [link](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output) that was posted, here is a Python one (with x=1). ``` from random import*;n=len(*open(__file__))//75;print(1+~-n*(random()<1/n))# ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehKDEvBUhl5hbkF5VoWefZ5qTmaWjlFwDJ@Pi0zJzU@HhNTX19c1PrgqLMvBINQ@063TwtDYg2DU0bQ/08TU3l//8B "Python 3 – Try It Online") -2 bytes thanks to Mr. Xcoder for his `(n-1)` formula with `~-n` which has higher precedence than `*` -1 byte thanks to Nishioka [Answer] # Dyalog APL, ~~25~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes ``` 0{×⍺:1+⍵⋄⎕←1⌈⍵×1=?⍵}1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///36D68PRHvbusDLUf9W591N3yqG/qo7YJho96OoD8w9MNbe2BdK3h//8A "APL (Dyalog Unicode) – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), ~~17~~ ~~15~~ ~~14~~ 13 bytes ``` Øgl13÷:(1w&+ṛ ``` [Try it online!](https://tio.run/##S0/MTPz///CM9BxD48PbrTQMy9W0H@6c/f8/AA "Gaia – Try It Online") I randomly noticed the behavior of `Øg` yesterday when looking through the docs, which helped immensely. [Answer] # Perl 5, ~~28~~ 26 bytes -2 bytes thanks to @Grimy ``` 1 if!++$x;say 1<rand$x||$x ``` [TIO](https://tio.run/##K0gtyjH9/99QITNNUVtbpcK6OLFSwdCmKDEvRaWipkalghyZ////5ReUZObnFf/X9TXVMzAEAA) [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` 1 n||=@x=0 n+=1 puts 1>rand(n)?n:1 if @x ``` [Try it online!](https://tio.run/##KypNqvz/35Arr6bG1qHC1oArT9vWkKugtKRYwdCuKDEvRSNP0z7PylAhM03BoeL/fwA "Ruby – Try It Online") [Try it online (copied 3 times)!](https://tio.run/##KypNqvz/35Arr6bG1qHC1oArT9vWkKugtKRYwdCuKDEvRSNP0z7PylAhM03BoYLa6v7/BwA) A ruby port of this [Python answer](https://codegolf.stackexchange.com/questions/191393/i-multiply-the-source-you-probably-multiply-the-output/191429#191429). # [Ruby](https://www.ruby-lang.org/), 38 bytes 2 bytes saved by reading the file: ``` n=File.size($0)/38;puts 1>rand(n)?n:1# ``` [Try it online!](https://tio.run/##KypNqvz/P8/WLTMnVa84sypVQ8VAU9/YwrqgtKRYwdCuKDEvRSNP0z7PylD5/38A "Ruby – Try It Online") [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 31 bytes ``` UwR'10<;$\ I+:'RA0)?/1$; 1 l; y ``` [Try it online!](https://tio.run/##KyrNy0z@/z@0PEjd0MDGWiWGy1PbSj3I0UDTXt9QxZrLkCvHmqvy/38A "Runic Enchantments – Try It Online") Uses the same structure as [this answer](https://codegolf.stackexchange.com/a/178761/47990) to count how many times the source has been duplicated: [![Execution flow](https://i.stack.imgur.com/zaEag.png)](https://i.stack.imgur.com/zaEag.png) Just instead of outputting the nth number in a list, we use that value to randomly generate a number, if the result is not 0, print 1, else print that number. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` (°Tö)ΪT ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KLBU9inOqlQ) | [Doubled](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KLBU9inOqlQosFT2Kc6qVA) | [Tripled](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KLBU9inOqlQosFT2Kc6qVCiwVPYpzqpU) [Verify distribution of 10000 runs after 10 repetitions](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KLBU9inOqlQosFT2Kc6qVCiwVPYpzqpUKLBU9inOqlQosFT2Kc6qVCiwVPYpzqpUKLBU9inOqlQosFT2Kc6qVCiwVPYpzqpUKLBU9inOqlQ&footer=VPZMsiCuzqpUw/wgrs4rIiA9ICIrWmzDcVI) ``` (°Tö)ΪT ( :Prevent the operator that follows from being implicitly applied to the first input variable, U °T :Increment T (initially 0) by 1 ö :Random element in the range [0,T) ) :Closing the parentheses here instead of after the T saves a byte as there would need to be a space here to close the random method Î :Sign - 0 (falsey) or 1 (truthy) ªT :Logical OR with current value of T ``` --- ## Original, ~~13~~ ~~11~~ ~~10~~ 9 bytes Note the trailing space. ``` NoÎp°T ö ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Tm/OcLBUIPYg) | [Doubled](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Tm/OcLBUIPYgTm/OcLBUIPYg) | [Tripled](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Tm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYg) [Verify distribution of 10000 runs after 10 repetitions](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Tm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYgTm/OcLBUIPYg&footer=TvZMsiD8IK7OKyIgPSAiK1psw3FS) ``` NoÎp°T ö N :Initially, the (empty) array of inputs o :Replace the last element with Î : Its sign (always 1) p :Push °T : T (initially 0) incremented ö :Random element of N ``` [Answer] # JavaScript ([JavaScript shell 71](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell)), 78 bytes ``` (async x=>x)().then(x=>f((''+f).length/78));f=x=>print(1-~x*Math.random()|0)// ``` No tio link, spidermonkey on tio is too old... Firefox (Spidermonkey) consider the comment as a part of function `f`. As the result, `(''+f).length` will be `b+79n` where b < 78, and (n + 1) is the times of source code repeated. This buggy (? I'm not sure. I would prefer it is a bug of JavaScript specification rather than any interpreter) behavior had been submit to BMO by someone else just after this answer posted: <https://bugzilla.mozilla.org/show_bug.cgi?id=1579792> . (Neither of the bmo thread nor the tweet is posted by me.) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~133~~ ~~114~~ 112 bytes This is the first (and hopefully last) time I have ever used C# preprocessor directives. ``` #if!I #define I static int i; class p{~p()=>Console.Write(new Random().Next(i)<1?i:1);}p s=new p(); #endif i++; ``` [Try it online!](https://tio.run/##FcuxCsIwEADQ/b7iJEtCsdDVWB2cuji4OIfkAgf1EryAguivR93fi7qNyr0bzpsFTKLMQriAttA4IktD9hDXoIr19anWzYdTES0rjdc7N7JCD7wESeVm3XimZ7Ps9tORd5Pz74o6/8HveTAkiTPwMHjo/Qs "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ⎚I⎇‽L⊞Oυω¹Lυ ``` [Try it online!](https://tio.run/##ASwA0/9jaGFyY29hbP//4o6a77yp4o6H4oC977ys4oqe77yvz4XPicK577ysz4X//w "Charcoal – Try It Online") Based on my answer to the linked question. Outputs `n` with probability `¹/ₙ`, otherwise `1`. Explanation: ``` ⎚ Remove output from previous iterations υ Initially empty list ω Empty string ⊞O Push L Length ‽ Random integer [0..length) ⎇ Ternary ¹ If nonzero then literal 1 Lυ If zero then the new length I Cast to string for implicit print ``` ]
[Question] [ For this challenge you will print the coordinates and color of each piece at the start of a game of checkers. Enter the x and y (comma seperated) for every square (indexed 0-7) on a checkerboard, followed by a "r" or "b" (for red or black) where the top of the board (closer to y=0) is red and the bottom is black. newlines between pieces are required and no spaces are necessary. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers are scored in bytes with fewer bytes being better. Trailing newlines are allowed but not necessary and the order must be exactly of that below. Desired output: ``` 0,0r 0,2r 0,4r 0,6r 1,1r 1,3r 1,5r 1,7r 2,0r 2,2r 2,4r 2,6r 5,1b 5,3b 5,5b 5,7b 6,0b 6,2b 6,4b 6,6b 7,1b 7,3b 7,5b 7,7b ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 26 bytes ``` 2ÝD5+«v4Fy',N·yÉ+„bry3‹èJ, ``` [Try it online!](https://tio.run/##AS0A0v8wNWFiMWX//zLDnUQ1K8KrdjRGeScsTsK3ecOJK@KAnmJyeTPigLnDqEos//8 "05AB1E – Try It Online") **Explanation** ``` 2Ý # push [0,1,2] D5+ # duplicate and add 5: [5,6,7] « # concatenate v # for each y in [0,1,2,5,6,7] do: 4F # for each N in [0 ... 3] do: y # push y ', # push "," N·yÉ+ # push N*2+isOdd(y) „br # push "br" y3‹è # index into the string with y<3 J, # join everything to a string and print ``` [Answer] # JavaScript (ES6), 66 bytes Includes a trailing newline. ``` f=(n=24)=>n--?f(n)+[2*(x=n>11)+(y=n>>2),n%4*2+y%2+'rb'[+x]]+` `:'' ``` ### Demo ``` f=(n=24)=>n--?f(n)+[2*(x=n>11)+(y=n>>2),n%4*2+y%2+'rb'[+x]]+` `:'' console.log(f()) ``` [Answer] # [Perl 5](https://www.perl.org/), 53 bytes ``` //&map{say"$',",$_+$'%2,$'<4?r:b}0,2,4,6for 0..2,5..7 ``` [Try it online!](https://tio.run/##K0gtyjH9/19fXy03saC6OLFSSUVdR0lHJV5bRV3VSEdF3cbEvsgqqdZAx0jHRMcsLb9IwUBPz0jHVE/P/P//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~83~~ ~~81~~ ~~79~~ 78 bytes * Saved two bytes thanks to [Tahg](https://codegolf.stackexchange.com/users/74459/tahg); golfing `x/4+2*(x/12)` to `x/4+x/12*2`. * Saved two bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen); golfing `x%8*2%8` to `x*2%8`. * Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` x;main(){for(;x<24;)printf("%d,%d%c\n",x/4+x++/12*2,x*2%8+x/4%2,114-x/12*16);} ``` [Try it online!](https://tio.run/##FchLCoAgEADQuwQDfhEHiWA6SptQDBdZSIuB6OxWb/mi3WLsnWlfSxXyzkcTxDMGkmcr9cpigGQgQVzqYNgFzVo7jwoNK4RJfwVovA@W//ajpKf3Fw "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~74~~ ~~73~~ 67 bytes ``` for i in 0,1,2,5,6,7:j=i%2;exec"print`i`+','+`j`+'rb'[i>4];j+=2;"*4 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPwUDHUMdIx1THTMfcKss2U9XIOrUiNVmpoCgzryQhM0FbXUddOyELSBclqUdn2pnEWmdp2xpZK2mZ/P8PAA "Python 2 – Try It Online") [Answer] # Java 8, ~~102~~ ~~96~~ ~~95~~ ~~93~~ 91 bytes ``` v->{for(int i=0;i<24;System.out.printf("%d,%d%c%n",i/4+i/12*2,i*2%8+i/4%2,i++<12?114:98));} ``` Port from [*@JonathanFrech*'s C answer](https://codegolf.stackexchange.com/a/143951/52210), after which I golfed 5 bytes myself. [Try it here.](https://tio.run/##LY7dCoJAEIXve4pBWFh/y0Ui2OoN8iboJrrYVo0xW0VXIcJnt7GEGYYzh5nzlWpQYd3kpsyek65U18FJofmsANDYvC2UziGdJcBQYwaaX@YxuJJ2IzVVZ5VFDSkYOMA0hMdPUbec7gEPG4l7kcjzu7P5K6p7GzUtOQV3WBawjGlmnADXiY/rWHgiQE@wHYmEiSCOkxB9fzbirevKcZL/wKa/VxS45P64XkTNz5Z@P643UO4f2USam76qFtpx@gI) **Explanation:** ``` v->{ // Method without empty unused parameter and no return-type for(int i=0;i<24; // Loop from 0 to 24 (exclusive) System.out.printf("%d,%d%c%n", // Print with format: // (%d=digit; %c=character; %n=new-line) i/4+i/12*2, // Print first coordinate i*2%8+i/4%2, // Print second coordinate i++<12?114:98) // Print either 'r' or 'b' ); // End of loop } // End of method ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 59 bytes Not the shortest, but a fun one: ``` printf %s\\n {{0,2,6}\,{0,2,4,6}r,{1,5,7}\,{1,3,5,7}b}|sort ``` [Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUG1OCYmT6G62kDHSMesNkYHzDABMot0qg11THXMQWKGOsZgZlJtTXF@Ucn//wA "Bash – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 38 bytes ``` (⍕⍪4/3 4~⍨⍳8),',',(⍕⍪24⍴⍋8⍴⍳2),12/'rb' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/5rPOqd@qh3lYm@sYJJ3aPeFY96N1to6qgDIVTGyORR75ZHvd0WYGqzkaaOoZG@elGS@n@gfq60/wA "APL (Dyalog Classic) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` 8Ḷḟ3ḟ4µḂr7m2ṭ€µ€Ẏµḣ1<3Ḣị⁾rbṭj”,$µ€Y ``` [Try it online!](https://tio.run/##y0rNyan8/9/i4Y5tD3fMNwZik0NbH@5oKjLPNXq4c@2jpjWHtgKJh7v6QMKLDW2AShY93N39qHFfURJQQdajhrk6KmA1kf//AwA "Jelly – Try It Online") Full program taking no arguments # Explanation ``` 8Ḷḟ3ḟ4µḂr7m2ṭ€µ€Ẏµḣ1<3Ḣị⁾rbṭj”,$µ€Y Main link; no arguments 8 8 Ḷ Push 0 .. 8 - 1 ḟ Remove all instances of 3 3 ḟ Remove all instances of 4 4 € For each in [0, 1, 2, 5, 6, 7] µḂr7m2ṭ€µ Generate all of the piece coordinates across that row Ḃ row number % 2 r inclusive range up to 7 7 m modular; take every elements 2 2 € For each column coordinate ṭ Tack the row coordinate (reverse append) Ẏ Tighten; flatten once € For each piece coordinate (in the right order now) µḣ1<3Ḣị⁾rbṭj”,$µ Convert to its final output ḣ Head; take the first element(s) 1 1 < Less Than; compare each element to 3 3 Ḣ Head; take the comparison out of the list ị Index (1-indexed) into ⁾rb "rb" ṭ Tack the color character behind j”,$ The coordinates joined by a comma j Join with separator ”, "," Y Separate by newlines ``` [Answer] # Java 8, 97 bytes ``` o->{int i=0,g;for(;i<8;i+=i==2?3:1)for(g=i%2;g<8;g+=2)System.out.println(i+","+g+(i<5?"r":"b"));} ``` [Answer] # JavaScript (ES6), 64 bytes This seems sufficiently different from @Arnauld's to warrant posting: ``` f=(n=0,y=n>>3,c=y>2)=>y<6?[y+c*2,n%8+y%2+'rb'[+c]]+` `+f(n+2):'' ``` **Explanation:** ``` f=(n = 0, //the numbered square on checkerboard y = n >> 3, //current row (n / 8 rounded) c = y > 2 //false if red pieces, true if black ) => y < 6 ? //if y less than 6 [ // using an array automatically adds the comma y + c * 2, // 0 - 2 if red pieces, 5 - 7 if black n%8 + y%2 + // n%8 returns 0, 2, 4, or 6. // y%2 returns 0 or 1. // added, they return the appropriate position (0 - 7) 'rb'[+c] // 'r' if red, 'b' if black. Plus sign coerces boolean to number. ]+` // new line `+ f(n+2) : // recurse on n+2 '' //else return an empty string ``` **Snippet:** ``` f=(n=0,y=n>>3,c=y>2)=>y<6?[y+c*2,n%8+y%2+'rb'[+c]]+` `+f(n+2):'' console.log(f()); ``` [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes ``` x=0;exec"print`x/8+x/24*2`+','+`x%8+x/8%2`+'rb'[x/24];x+=2;"*24 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8LWwDq1IjVZqaAoM68koULfQrtC38hEyyhBW11HXTuhQhUkYKEK4hclqUeDJGOtK7RtjayVtIxM/v8HAA "Python 2 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~45~~ 44 bytes\* -1 thanks to ngn. Niladic function which assumes 0-based indexing (`⎕IO←0`) which is default on many systems. Prints to STDOUT. ``` ↑' '⎕R','⊃,/(8 ¯8↑¨⊂⍕¨⍸∘.=⍨2|⍳8),¨¨'rb' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862p0zUpOzU4uS8hOLUv4/apuorqAOlA9S11F/1NWso69hoXBovQVQ/NCKR11Nj3qnAuneHY86ZujZPupdYVTzqHezhabOoRWHVqgXJan/Bxr4H9lEAA "APL (Dyalog Unicode) – Try It Online") `(`…`),¨¨'rb'` append "r" to each of the first group of items and "b" to each of the second:  `⍳8` zero through eight  `2|` division remainder when halved  `∘.+⍨` plus table with itself on along both axes  `⍸` indices of true values  `⍕¨` format each (converts to strings with the pattern `d d` where each `d` is a digit)  `⊂` enclose (so we can reuse it for each…)  `8 ¯8↑¨` take the first nine and the last nine now we have two lists of `d d` strings `,/` catenation reduction (combine the two lists) `⊃` disclose (because the reduction reduced the rank from 1 to 0) `' '⎕R','` PCRE **R**eplace spaces with commas `↑` mix (the all the lists into a single matrix) --- \* In Dyalog Classic, counting `⍸` as `⎕U2378`. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 59 bytes ``` 00000000: 15ca b101 0030 0400 c1de 2c0a 2462 1f23 .....0....,.$b.# 00000010: d8bf 886f ae3a 531b 310d b8f0 465c 1d0e ...o.:S.1...F\.. 00000020: 24d4 48ec 5b02 2eec 4bf5 5e0e 2454 cb53 $.H.[...K.^.$T.S 00000030: 8380 0baf a5d4 e140 42f5 07 .......@B.. ``` [Try it online!](https://tio.run/##Vc@9SkRBDAXg3qc44C0lJJnMddhKthDBcu0UYTI/NspW@/zXrHsbTxHS5EviF/fv8XX52Tbec4DkVuHCAubEYGNGkz6gjSvUVoVMTQBdw9fyQIvT/d1NkDB68YlS1ok6UkVO4kjCHV4mw9bcIJ3Hn3Gmw4kkmucPot3QMNS6wcpoyM4KHdGZz4w8YlItG5rnuGOhF3qP@Vf6pOWNTruRwiipxAde444c2hCL7RoGP@Jf6JanI9G2/QI "Bubblegum – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~37~~ ~~36~~ 35 bytes isaacg wouldn't be proud ``` V+U3}5 7FG4p++N\,+yG?!%N2Z1?<N5\r\b ``` Explanation: ``` V+U3}5 7 For in the array [0, 1, 2, 5, 6, 7] as N FG4 For in the array [0, 1, 2, 3] as G p Print without newline: ++N\,+yG?!%N2Z1 N, (2 * G) + 1 if N is even, else 0 ?<N5\r\b Output with newline "r" if N < 5 else "b" ``` This uses a simple pattern I cut down a bit. As follows: If the `X` coord is even, use the even numbers `0, 2, 4, 6`. Else, `1, 3, 5, 7` for `Y`. If the `X` coord is less than 5, the color (`r` or `b`) is `r`. Else, it is `b`. [Try it online!](https://tio.run/##K6gsyfj/P0w71LjWVMHczd2kQFvbL0ZHu9LdXlHVzyjK0N7GzzSmKCbp/38A "Pyth – Try It Online") **edit**: overnight got +40 rep on 3 different answers w00t [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 31 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ⁰¹²⁵⁶⁷’{A4∫«Ha2\⌡HaOļ,pƧbra4>Wo ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMDcwJUI5JUIyJXUyMDc1JXUyMDc2JXUyMDc3JXUyMDE5JTdCQTQldTIyMkIlQUJIYTIlNUMldTIzMjFIYU8ldTAxM0MlMkNwJXUwMUE3YnJhNCUzRVdv) [Answer] # Javascript (89 bytes): ``` for(x=y=0,r="r";x<7|y<8;console.log(x+","+y+r),y+=2){if(y>7)y=++x%2;if(x==3){x+=2;r="b"}} ``` Readable: ``` for(var x = y = 0, red = true; x < 7 || y < 8; y += 2) { if(y > 7) { //new row x++; y = x % 2; } if(x == 3) { //new color x += 2; red = false; } console.log(x + "," + y + (red ? "r" : "b") ); } ``` [Try it online!](https://tio.run/##DczRCoMwDEDRfwkMWtKN4R4c1Oxf1OlwiBmpSIL67V0fLwfut93a1Mv0W68Lv4ecRxanZHQPQiAQtakPa56x5yXxPNxm/jhFCICG4oMhVX6fRmev2hsh6qWKJZXo4XctGsung/PM@Q8 "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 8Ḷµḟ3,4pµSḂ$Ðḟj€”,ż⁾rbx12¤Y ``` A full program which prints the required output. **[Try it online!](https://tio.run/##ATgAx/9qZWxsef//OOG4tsK14bifMyw0cOKBuFPhuIIkw5DhuJ9q4oKs4oCdLMW84oG@cmJ4MTLCpFn//w "Jelly – Try It Online")** ### How ``` 8Ḷµḟ3,4p⁸SḂ$Ðḟj€”,ż⁾rbx12¤Y - Link: no arguments 8 - literal eight Ḷ - lowered range = [0,1,2,3,4,5,6,7] µ - new monadic chain 3,4 - literal list = [3,4] ḟ - filter discard = [0,1,2,5,6,7] ⁸ - chain's left argument = [0,1,2,3,4,5,6,7] p - Cartesian product = [[0,0],[0,1],...,[2,7],[5,0],...,[7,6],[7,7]] Ðḟ - filter discard if: $ - last two links as a monad: S - sum Ḃ - modulo by 2 ”, - literal comma character j€ - join €ach pair with a comma = [0,',',0],[0,',',2],...,[2,',',6],[5,',',1],...,[7,',',5],[7,',',7]] ¤ - nilad followed by links as a nilad: ⁾rb - literal list = ['r','b'] 12 - literal twelve x - repeat = ['r','r','r','r','r','r','r','r','r','r','r','r','b','b','b','b','b','b','b','b','b','b','b','b'] ż - zip together = [[[0,',',0],'r'],[[0,',',2],'r'],...,[[2,',',6],'r'],[[5,',',1],'b'],...,[[7,',',5],'b'],[[7,',',7],'b']] Y - join with newlines = [[0,',',0],'r','\n',[0,',',2],'r','\n',...,'\n',[2,',',6],'r','\n',[5,',',1],'b','\n',...,'\n',[7,',',5],'b','\n',[7,',',7],'b'] - implicit print (smashes the list of lists and characters - together and prints the digits) ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~63~~ 60 bytes ``` [*0..11,*20..31].map{|x|puts [x/4,2*x%8+x[2]]*?,+"rb"[x[4]]} ``` Bitmask magic saves the byte. [Try it online!](https://tio.run/##KypNqvz/P1rLQE/P0FBHywhIGxvG6uUmFlTXVNQUlJYUK0RX6JvoGGlVqFpoV0QbxcZq2etoKxUlKUVXRJvExtb@/w8A "Ruby – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 bytes ``` 0..2+5..7|%{$i=$_;0,2,4,6|%{"$i,$($_+$i%2)"+('r','b')[$i-ge5]}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz0jbVE/PvEa1WiXTViXe2kDHSMdExwzIV1LJ1FHRUInXVslUNdJU0tZQL1LXUU9S14xWydRNTzWNra39/x8A "PowerShell – Try It Online") Loops over `0,1,2,5,6,7` and each iteration sets `$i` to the current number. Then loops over `0,2,4,6`. Each inner loop, we construct a string starting with `$i,` then concatenated with our inner loop's current number plus whether `$i` is even or odd (which gets us `0,2,4,6` one time and `1,3,5,7` the other time), then concatenated with either `r`ed or `b`lack based on whether `$i` is `-g`reater-than-or-`e`qual to `5`. Those strings are all left on the pipeline and the implicit `Write-Output` at program completion gives us newlines for free. [Answer] # [J](http://jsoftware.com/), ~~48 44 40 37~~ 31 bytes ``` (}:"1":$.|:8$#:162 69),.12#'rb' ``` [Try it online!](https://tio.run/##y/r/PzU5I19Bo9ZKyVDJSkWvxspCRdnK0MxIwcxSU0fP0EhZvShJ/f9/AA) ### How it works ``` 8$#:162 69 first 2 columns in binary, take 8 of them |: transpose $. format as a sparse array, kind of looks like the goal ": "to text" }:"1 delete the last column ,.12#'rb' append 12 rs followed by 12 bs as the last column ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 96 bytes ``` ()=>{for(int i=0;i<24;)System.Console.Write($"{i/4+i/12*2},{i*2%8+i/4%2}{(i++>11?"b":"r")}\n");} ``` [Try it online!](https://tio.run/##Tc5BC8IgGIDhc/4KkQLdqjXZIbItaucg6NCly3JWHy0FtSDE376CCDq@l5dHuok0VvUPB/qC9y/n1V0g2TXO4V1AzjceJF5LD0bj@qrkTdmNaWyLS9xTVlbhbCwF7TGUMwFLXgj2vUxro53p1PRgwSs6JAGyIoUs5wmP4wAJH80/WYx4DBTStMrzFTmRBbGExaMmTMReoJ/gaaDF2wY0ZSigwb@EMoEiiv0b "C# (.NET Core) – Try It Online") Essentially just a port to C# of [@JonathanFrech's answer](https://codegolf.stackexchange.com/a/143951/73579). I couldn't come up with any better way of doing the math. ]
[Question] [ You met a 4-th dimensional being who challenged you to a game of dice. The rules are simple: each player rolls 3 6-sided dice and takes the sum of each combination of 2 dice. The player with the highest sum wins. If the first-highest sum is a tie, consider the second-highest sum, and so on. Your opponent's dice look normal, but you think they might have more than 6 sides! **Your goal is to find out if the alien rolled a number higher than 6.** Your input is a set of 3 integers, separated by at least one character (space or otherwise). Input must not be hard coded. ``` // All valid inputs 6 7 9 6, 7, 9 (6, 7, 9) ``` Your output is a string representing if the alien cheated. Any output is allowed, as long as two distinct values exist for cheating/valid. Appended whitespace is permitted. ``` "😀" // (U+1F600) Valid set of dice "😠" // (U+1F620) Invalid set of dice ``` Examples: ``` <-: 8 11 9 ->: 😀 // Dice can be found to be 3, 5, and 6, which are all on 6-side die ``` ``` <-: 9 11 6 ->: 😠 // Dice can be found to be 2, 7, and 4, which means the alien cheated! ``` Assumptions: * Input will be 3 integers, 2-12 * Input numbers can be in any order * Die values will be positive integers * Alien only cheated if they rolled greater than 6 Write a program or function that takes inputs, returns or prints outputs. Fewest bytes wins! [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ¬>6-▼¹½Σ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@hNXZmuo@m7Tm089Dec4v///8fHW2hY2ioYxmrE20OYcQCAA "Husk – Try It Online") Outputs `1` for normal dice, `0` if the alien cheated. Checks whether half (`½`) of the sum (`Σ`) minus (`-`) the smallest (`▼`) element is not (`¬`) greater than 6 (`>6`). [Answer] # [R](https://www.r-project.org/), 28 bytes ``` function(x)sum(x/2)-min(x)>6 ``` [Try it online!](https://tio.run/##K/qfmJOZmhefnJGaWJKaYvs/rTQvuSQzP0@jQrO4NFejQt9IUzc3E8S1M0NVq5GsYaFjaKhjqampoKxgplucmZKaopCSmZzKha7OHKEOLKWQWawAls3MS1f8DwA "R – Try It Online") Same approach as [my Husk answer](https://codegolf.stackexchange.com/a/243606/95126). [Answer] # [Haskell](https://www.haskell.org/), 20 bytes ``` f l=any(<sum l/2-6)l ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzYxr1LDprg0VyFH30jXTDPnf25iZp6CrUJKPpdCQVFmXomCikKaQrSFjqGhjmUsipg5FjFLkJhZ7H8A "Haskell – Try It Online") Inspired by [*@DominicVanEssen* R answer](https://codegolf.stackexchange.com/a/243607/52210). Tells if it's a cheater (the alien.. not Dominic). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` f=(a,b,c)=>a>b|a>c?f(b,c,a):b+c-a<13 ``` [Try it online!](https://tio.run/##VchBDkAwEADAu5d0YytpJIJQb9kuFdJYUXHy9@LoOLPSRZGPZT/1JuOUku8VoUOG3pJ1N1kevHqNBK3LWVNnysSyRQlTEWRWXtVoDDYA2b@bryuA9AA "JavaScript (Node.js) – Try It Online") Like the hypot one [Answer] # JavaScript (ES6), 35 bytes Expects `([a,b,c])`. Returns *true* for cheating or *false* for valid. ``` A=>A.some(x=>eval(A.join`+`)/2>x+6) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@9/R1s5Rrzg/N1WjwtYutSwxR8NRLys/My9BO0FT38iuQttM839yfl5xfk6qXk5@ukaaRrSZjoKCuY6CZaymJhealIWOgqEhdilLiJQZUOo/AA "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) (-O0), 73 bytes ``` #define g(a,b) if(a>b)a^=b^=a^=b; f(a,b,c){g(a,b)g(b,c)g(a,b)a=b+c-a<13;} ``` [Try it online!](https://tio.run/##JYpNCsIwEIX3OcVQKcxgugiCWGI8SmEyaUIWBhF3pWePHfoWj@/9yFREer@kNde2QkG2kaBm5FckXkJcgro3WRcrtJ2XghpO5hCvMvHT3fzea/vBm2tDMpuBQ5/vUWUcxgRjGixkfFjn7EyKs@KdyJu9/wE "C (gcc) – Try It Online") Not the prettiest solution # [C (gcc)](https://gcc.gnu.org/) (-O0), 38 bytes, shamelessly copy [this](https://codegolf.stackexchange.com/a/243605/108879) beautiful answer. ``` f(a,b,c){a=a>b|a>c?f(b,c,a):b+c-a<13;} ``` [Try it online!](https://tio.run/##Fcg9CoAwDEDhvacoBSHBOBRB1PpzljRScbCIuKlnr/VNH0@qVSSlAEyeBG8eefIPTzIHyIMYe19KxYOt3Zu2eOmdtwiobqVzx5lXAFMsulgM6QAtWUsd/ux@NohOvekD "C (gcc) – Try It Online") *-2 bytes thanks to AZTECCO* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` O;αà6› ``` Inspired by [*@DominicVanEssen*'s R answer](https://codegolf.stackexchange.com/a/243607/52210). Takes a list `[a,b,c]` as input, and outputs `1`/`0` for cheating/valid respectively. [Try it online](https://tio.run/##yy9OTMpM/f/f3/rcxsMLzB417Pr/P9pCx9BQxzIWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf3/rcxsPLzB71LDrv87/6GgLHUNDHctYnWhLEMMsNhYA). **Explanation:** ``` O # Sum the three values in the (implicit) input-list # e.g. [8,11,9] → 28 # e.g. [9,11,6] → 26 ; # Halve it # → 14 # → 13 α # Take the absolute difference of this sum with each value in the # (implicit) input-list # → [6,3,5] # → [4,2,7] à # Pop and push its maximum # → 6 # → 7 6› # Check if this is larger than 6 # → 0 # → 1 # (after which this is output implicitly as result) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` 2/sGX<-IE> ``` [Try it out](https://matl.suever.net/?code=2%2FsGX%3C-IE%3E&inputs=%5B9%2C+11%2C+6%5D&version=22.4.0) / [Test three cases](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQqxDh8d9Iv9gjwkbX09Xuf0js/2gLHQVDQx0Fy1iuaEsI0wzINIeLGugbAAA "MATL – Try It Online") Port of @Dominic van Essen's answers. 1 = You cheating alien! 0 = Never had a moment of doubt. `4-sGX<E-F>` [Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQqxDh8d9Et9gjwsZV183uf0js/2gLHQVDQx0Fy1iuaEsI0wzINIeLGugbAAA "MATL – Try It Online") is another 10 byter. ## MATL, 11 bytes ``` .5IXy-iY*7< ``` [Try it out](https://matl.suever.net/?code=.5IXy-iY%2a7%3C&inputs=%5B9%3B+11%3B+6%5D&version=22.4.0) / [Test three cases](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQqxDhoVDxX8/UM6JS1yNSy8wu8X9I7P9oC2sFQ0NrBctYrmhLCNMMyDSHixroGwAA) Outputs truthy (all 1s) for no cheating, falsy (some 0s) for cheating. For given input [a, b, c], the system of linear equations is : \$ d\_2 + d\_3 = a \$ , \$ d\_1 + d\_3 = b \$ , \$ d\_1 + d\_2 = c \$ Or in matrix form: \$ \begin{bmatrix} 0 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 0 \end{bmatrix}\begin{bmatrix} d\_1 \\ d\_2 \\ d\_3 \end{bmatrix} = \begin{bmatrix} a \\ b \\ c \end{bmatrix} \$ The solution - the set of dice values - is the inverse of the matrix on the left, multiplied by the input. This inverse is equal to \$ 0.5 - I\_3 \$ (where \$I\_3\$ is the 3x3 identity matrix). `.5IXy-` computes this inverse, `iY*` multiplies that by the input, `7<` checks if all of the resulting dice values are less than 7 (and hence valid). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes ``` \d+ $* O`1+ ^ 12$* (1+)(1+),\1,\2$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi8s/wVCbK47L0AjI1jDU1gRhnRhDnRgjlf//zXTMdSy5LHQMDYGUJYgyAwA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `1` for normal dice, `0` if the alien cheated. Explanation: ``` \d+ $* ``` Convert to unary. ``` O`1+ ``` Sort into order. ``` ^ 12$* ``` Add 12 to the smallest value. ``` (1+)(1+),\1,\2$ ``` The sum should then equal or exceed the sum of the other two values. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ∑½?g-6≤ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiJHCvT9nLTbiiaQiLCIiLCJbOSwgMTEsIDZdIl0=) Port of [@Dominic van Essen's Husk answer](https://codegolf.stackexchange.com/a/243606/107299). `1` if the dice are normal, `0` if the alien used tesseracts for its dice. ``` ∑½?g-6≤ # Takes list as input ∑ # Sum of the list ½ # Halved.. - # Minus... ?g # Smallest element of the input 6≤ # Is less than or equal to 6? ``` [Answer] # [J](http://jsoftware.com/), ~~20~~ 11 bytes ``` 12<+/-2*<./ ``` -9 bytes thanks @Bubbler [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DY1stPV1jbRs9PT/a3JxpSZn5CukKVgoGBoqWMJ4liCe2X8A "J – Try It Online") [Answer] # [R](https://www.r-project.org/), 28 bytes ``` function(x)any(sum(x)/2>6+x) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMxr1KjuDQXyNI3sjPTrtD8n6aRrGGhY2ioY6mpqaCskJaYWcQFEjNHiCVnpCaWZOal/wcA "R – Try It Online") Alternate and equally-golfy solution porting [this python answer](https://codegolf.stackexchange.com/a/243649/67312) -- the naive port would be something like `sum(x)-2*x>12` which is a byte longer. [Answer] # [Julia 1.0](http://julialang.org/), 23 bytes ``` x->sum(x/2)-min(x...)>6 ``` [Try it online!](https://tio.run/##yyrNyUw0rPifpmCr8L9C1664NFejQt9IUzc3M0@jQk9PT9PO7L9DcUZ@uUKaRrSFjoKhoY6CZawmF1zMEiJmhixmDlf3HwA "Julia 1.0 – Try It Online") Port of @Dominic van Essen's answers. Output is the answer to the question "Did the alien cheat?" ### Julia 1.2 or above, with `using LinearAlgebra`, 23 bytes ``` x->any((.5 .-I(3))x.>6) ``` (doesn't work on TIO since it only has Julia 1.0) **18 bytes** without the `any` call, if output can be all 0s for no cheating, at least one 1 for cheating alien. Find the dice values by solving the system of linear equations via matrices, and check if any are greater than 6. (More explanation in my [MATL answer](https://codegolf.stackexchange.com/a/243688/8774)). [Answer] # [Python 3](https://docs.python.org/3/), ~~27~~ 26 bytes ## Code ``` lambda v:sum(v)/2-min(v)>6 ``` Outputs `True` for cheated and `False` for valid. [Try it online!](https://tio.run/##K6gsycjPM/6fZqvxPycxNyklUaHMqrg0V6NMU99INzczD8iwM/uvyVVQlJlXopGmoWGmo2BoqKNgqampo5Cal2KrpKT5HwA) ## Explanation Let \$a\$, \$b\$ and \$c\$ be the three dice rolls, where \$a\$ is the highest roll. Therefore, if \$a > 6\$, the alien cheated, and otherwise they did not. The sum of the numbers is \$2a + 2b + 2c\$. The minimum of the numbers is \$b + c\$. Therefore, `sum(v)/2-min(v)` is \$(2a + 2b + 2c)/2 - (b + c)\$ which is \$a\$. If this is greater than \$6\$, the alien cheated. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/),~~38~~ ~~28~~ 27 bytes **Latest Answer** ``` lambda *a:sum(a)/2-min(a)>6 ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUUEr0aq4NFcjUVPfSDc3Mw/IsDP7X1CUmVeikaZhqWNoqGOmqckFE7AACVhqav4HAA "Python 3.8 (pre-release) – Try It Online") **Old Answer** ``` lambda x,y,z:max(x-y+z,x+y-z,y+z-x)>12 ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaFCp1Knyio3sUKjQrdSu0qnQrtSt0oHyNKt0LQzNPpfUJSZV6KRpmGpY2ioY6apyQUTsAAJWGpq/gcA "Python 3.8 (pre-release) – Try It Online") **Output** : Gives `True` when cheated and `False` when not. Thank you [Aetol](https://codegolf.stackexchange.com/users/111337/aetol) for the suggestion of using `a+b+c-2*min(a,b,c)>12` instead of `max(x-y+z,x+y-z,y+z-x)>12` [This](https://codegolf.stackexchange.com/a/243660/106829) R answer gave the nice `sum(a)/2-min(a)>6` Idea [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~22~~ ~~18~~ 11 bytes ``` L>-/sb2hSb6 ``` Port of [@Lecdi's Python 3 solution](https://codegolf.stackexchange.com/a/243699/108170). ``` L>-/sb2hSb6 L # lambda b: sb # sum(b) / 2 # sum(b) / 2 hSb # min(b) - # sum(b)/2 - min(b) > 6 # sum(b)/2 - min(b) > 6 ``` [Try it online!](https://tio.run/##K6gsyfj/38dOV784ySgjOMnsf2W0pYKhoYKZJldltAWIZan5/19@QUlmfl7xfwA "Pyth – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` ›Σθ⊗⁺⁶⌊θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVII7g0V6NQU0fBJb80KSc1RSMgp7RYw0xHwTczLzMXLAcC1v//R0db6hga6pjFxv7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array and outputs `-` if the alien cheated, nothing if it didn't. Explanation: Inspired by @DominicvanEssen's answers. ``` θ Input array Σ Summed › Is greater than θ Input array ⌊ Minimum ⁺ Plus ⁶ Literal integer `6` ⊗ Doubled Implicitly print ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 21 bytes ``` ->*s{s.sum/2-s.min<7} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf106ruLpYr7g0V99It1gvNzPPxrz2f4FCWrSFjqGhjmUsF4htCWKbxf4HAA "Ruby – Try It Online") [Answer] # [Etch](https://github.com/GingerIndustries/Etch), 47 bytes `s=:get;:split" ";:intify;;:out:sum s;/2-:min s;>6;` A straightforward point of [this Husk answer](https://codegolf.stackexchange.com/a/243606/108218). [Answer] # [BQN](https://mlochbaum.github.io/BQN/index.html), 9 bytes ``` ¯12>-˜´∘∨ ``` [Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=QWxpZW5faXNfY2hlYXRpbmcg4oaQIMKvMTI+LcucwrTiiJjiiKgKQWxpZW5faXNfY2hlYXRpbmfCqCDin6ggOOKAvzEx4oC/OSwgOeKAvzEx4oC/NiDin6k=) Outputs `0` if the dice are 6-sided, `1` if the alien is cheating. We calculate the highest die roll using a single `fold` (or `reduce` in some languages) of a "minus" operation across the 3 sums-of-2-rolls in increasing order. Consider initial die rolls of `s`, `m` and `l`, where `l` is the (possibly non-unique) largest, and `s` is the smallest. Then, the sums-of-2-rolls, in increasing order, are: `s+m`, `s+l`, `m+l`. Folding "minus" across this yields `(s+m minus s+l) minus m+l` = `m-l - (m+l)` = `-2l`. So we just need to check whether the result is less than minus 12: if it is, then `l` was greater than 6 and the alien was cheating. ``` ∨ # sort the input ∘ # and use that to -˜´ # fold 'subtracted from' from the right ¯12> # and check whether it's less than minus 12 ``` This comes out 1 byte shorter than the "subtract the lowest value from half the sum of the input" approach (`12<+´-2×⌊´` = 10 bytes in [BQN](https://mlochbaum.github.io/BQN/index.html): [try it](https://mlochbaum.github.io/BQN/try.html#code=QWxpZW5faXNfY2hlYXRpbmcg4oaQIDEyPCvCtC0yw5fijIrCtApBbGllbl9pc19jaGVhdGluZ8KoIOKfqCA44oC/MTHigL85LCA54oC/MTHigL82IOKfqQ==)) [Answer] # [Scala](https://www.scala-lang.org/), 35 bytes [Try it online!](https://tio.run/##bYw9D4IwFAB3fsUb2wRRGPwgwYQ4ORMnwvCEB9aUqm01GMJvr8hgQuJ6dzlTokR3O1@ptJBKQepwIbRUQe8qqqFmXZzRIz8qW/CkC8yzXUbBatEFrVD7tfMAvlmLQjHUjYkh1RrfeWa1UE3BYzgpYSGBfiwBXiihEiWFI5lCtvUhDH3Y8ZmPfn4z8/fxaqViNZsu/B@NJjp4g@c@) ``` def f(x:Seq[Int])=x.sum/2.0-x.min>6 ``` ]
[Question] [ ## Background [**Fibonacci trees**](https://xlinux.nist.gov/dads/HTML/fibonacciTree.html) \$T\_n\$ are a sequence of rooted binary trees of height \$n-1\$. They are defined as follows: * \$T\_0\$ has no nodes. * \$T\_1\$ has a single node (the root). * The root node of \$T\_{n+2}\$ has \$T\_{n+1}\$ as its left subtree and \$T\_n\$ as its right subtree. ``` T0 T1 T2 T3 T4 O O O O / / \ / \ O O O O O / / \ / O O O O / O ``` Each tree in this sequence is the most unbalanced possible state of an [AVL tree](https://en.wikipedia.org/wiki/AVL_tree) of same height. ## Challenge Given the number \$n\$, output the \$n\$-th Fibonacci tree. By the usual [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules, your function or program may behave as one of the following: * Take \$n\$ as input, and output the \$n\$-th tree (\$n\$ can be 0- or 1-indexed; the given example is 0-based) * Take \$n\$ as input, and output the first \$n\$ trees * Take no input, and output the sequence of trees indefinitely A binary tree can be output in any acceptable ways, including but not limited to * a built-in tree object if your language has one, * a nested array, an ADT, or its textual representation, * a human-readable ASCII/Unicode art, or * a flattened list of nodes labeled as numbers in level order. Shortest code in bytes wins. [Answer] # [J](http://jsoftware.com/), 14 bytes ``` (2{.];])^:[&a: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NYyq9WKtYzXjrKLVEq3@a3KlJmfkK6QpGEAY6rq6uuowMUMsYkZYxIyxiJn8BwA "J – Try It Online") We use J boxes to represent the trees: ``` ┌┐ ││ └┘ --- ┌──┬┐ │┌┐││ │││││ │└┘││ └──┴┘ --- ┌─────┬──┐ │┌──┬┐│┌┐│ ││┌┐││││││ │││││││└┘│ ││└┘│││ │ │└──┴┘│ │ └─────┴──┘ --- ┌──────────┬─────┐ │┌─────┬──┐│┌──┬┐│ ││┌──┬┐│┌┐│││┌┐│││ │││┌┐│││││││││││││ ││││││││└┘│││└┘│││ │││└┘│││ ││└──┴┘│ ││└──┴┘│ ││ │ │└─────┴──┘│ │ └──────────┴─────┘ ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` #<2||#0/@{#-1,#-2}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9nGqKZG2UDfoVpZ11BHWdeoVu1/QFFmXkm0sq5dmoNyrFqdY1FRYmWd5X8A "Wolfram Language (Mathematica) – Try It Online") 1-indexed. Returns the \$n\$th tree. Expressions in Mathematica are trees. `True` represents the absence of a node. Visually: [![f[5]//TreeForm](https://i.stack.imgur.com/SfBu3.png)](https://i.stack.imgur.com/SfBu3.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ,¡ ``` [Try it online!](https://tio.run/##y0rNyan8/1/n0ML//00A "Jelly – Try It Online") **Takes input from STDIN.** Outputs the `n`th Fibonacci tree in the form of a nested list, where a list represents a node and `0` represents NIL. ## Explanation * `,` — Pair * `¡` — Turn the preceding dyadic function f(x, y) into a triadic function g(x, n, y) such that: + g(x, 0, y) = x + g(x, 1, y) = f(x, y) + g(x, n, y) = f(g(x, n-1, y), g(x, n-2, y)) Since the link is called as a nilad, zeros are supplied for `x` and `y` and a number from STDIN is taken for `n`. [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` data T=E|N T T f=E:scanl N(N E E)f ``` [Try it online!](https://tio.run/##Ncs/CwIhGAbw/T7FgzR02B4Ejo655BYRL5einGeHCrf03e2taPw9fwLV2aXU@4MawSr9MrCwg1f6VCfKCWZvoKFH32OujfLkcAnPjVdbcMUNqB9pJa438QMfEsrIiZDy2yYpxeGPwuDpQjGrhdbzHWuJue0azQ5H@P4G "Haskell – Try It Online") `f` is the infinite list of Fibonacci trees, represented as a custom type defined in the first line (`E` is the empty tree, `N l r` is the tree with left subtree `l` and right subtree `r`). ## How? Haskell is usually very well-suited for Fibonacci-related tasks. Assume we have a recurrence of the form $$ \begin{cases} \texttt{f}\_0=\texttt{a}\\ \texttt{f}\_1=\texttt{b}\\ \texttt{f}\_{n+2}=\texttt{g}(\texttt{f}\_{n+1},\texttt{f}\_n), \end{cases} $$ where \$\texttt{g}\$ is a binary operator. Then the corresponding Haskell definition is simply ``` f=a:scanl g b f ``` Unfortunately, Haskell is *not* very well-suited for problems involving trees, since it can't (natively) handle nested lists or tuples. Defining my own data type for trees was the shortest way I could find to solve this issue. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16~~ 12 bytes ``` ΘGȯf≠'"s,s0₀ ``` [Try it online!](https://tio.run/##yygtzv7//9wM9xPr0x51LlBXKtYpNnjU1PD/PwA "Husk – Try It Online") Trees or arbitrarily nested lists are not a thing in Husk, so this builds a string representation of the tree, where a leaf is represented as "0" and a node with a Left child L and a right child R is represented as "(L,R)". Returns the infinite list of Fibonacci trees, which get printed one per line. ### Explanation I've started from what's probably the second shortest way of computing Fibonacci numbers in Husk (the shortest being the builtin `İf`): ``` ΘG+1₀ ``` [Try it online!](https://tio.run/##yygtzv7//9wMd23DR00N//8DAA "Husk – Try It Online") This puts a 0 at the beginning of the sequence (with `Θ`), then scans (`G`) recursively the same list `₀` with `+`, starting from `1` and summing every time the last result to the next element in the list. With this, we just need to alter the starting values and the `+` operator to make it compute Fibonacci trees. The `1` now becomes `"0"` (`s0`, string representation of the number `0`) and the `0` turns into `""` automagically, thanks to Husk understanding that the list is now a list of strings rather than numbers. The operator that generates a new tree from the two previous ones becomes a bit more complex *(but not as complex as I originally made it, thanks [Dominic van Essen](https://codegolf.stackexchange.com/users/95126)!)*: ``` f≠'"s, Input: left subtree "L", right subtree "R" , Join the two subtrees in a pair ("L","R") s Convert the pair into a string "(\"L\",\"R\")" Now we need to remove the extra quotes: f Keep only those characters ≠ that are different '" than " ``` [Answer] # [R](https://www.r-project.org/), 39 bytes ``` f=function(n)if(n>0)list(f(n-1),f(n-2)) ``` [Try it online!](https://tio.run/##VY27CsMwDADn@CuCJwlSSEOnQPIVHQPFNRYIghxkBQIl3@4@tk533HJaiZ9ZQoz8ME1pqjTRLtE4Cwgygcw9rlwMPnq5YvfFgFgpKxwtS9uPN3y5ZlMWgy0US@DvvjsQXVNM4X8Avx6DgV/EozvrGw "R – Try It Online") Output is a nested list of lists of 2 elements each. Leaves are represented as lists with no child lists (both list elements are `NULL`). [Answer] # [Python 3](https://docs.python.org/3/), ~~53~~ ~~50~~ ~~45~~ 44 bytes ``` f=lambda n:n and[n]if n<2else[f(n-1),f(n-2)] ``` [Try it online!](https://tio.run/##FcUxCoAwDAXQq2RsQAcVl6InEYdIGw3Ub6kunr7iW15@n@PCUKvOSc4tCMGDBGHBakqY@pjuuKhD23Hz1/Na9SpkZKAi2KMb2VMuhsepM@b6AQ "Python 3 – Try It Online") Thanks @Dominic van Essen save 3 bytes. Save 5 bytes changing the first `if` condition with `and`. Thanks @user save 1 byte. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` õ¯‚λs‚ ``` Outputs the infinite sequence, with an empty string as empty node (i.e. \$T4\$ will result in `[[[[],""],[]],[[],""]]`) [Try it online.](https://tio.run/##yy9OTMpM/f//8NZD6x81zDq3uxhI/q8tq9Q5tM3@PwA) (The footer is to print each tree on a separated line with newline-delimiters. Feel free to remove it to see the actual infinite list output.) **Explanation:** ``` λ # Start a recursive environment # to output the infinite sequence, õ # starting at a(0)="" ¯‚ # and a(1)=[] õ¯‚ # (Push an empty string ""; push an empty list []; pair them together) # And we calculate every following a(n) as follows: # (implicitly push the values of a(n-2) and a(n-1) s # Swap them on the stack ‚ # And pair them together: [a(n-1),a(n-2)] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~29~~ 27 bytes Saved 2 bytes with a suggestion from Jo King. ``` f=n=>n<1?[]:[f(n-1),f(n-2)] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PxtA@OtYqOk0jT9dQUwdEGWnG/rfmijbQUTDUUTDSUTDWUTCJ1UvLL3JNTM7QyFOwtVNIzs8rzs9J1cvJT9cAatHU1PwPAA "JavaScript (Node.js) – Try It Online") A tree is represented by `[l, r]`. The absence of a child is represented by `[]`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` FN⊞υ✂υ±¹±³±¹∧υ⭆¹⊟υ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTIaC0OEOjVEchOCczORXE8EtNTyxJ1TDUhDONNZFENTWtuQKKMvNKNBzzUsAaS4C8dN/EAg1DHYWA/AKNUk2Qov//Tf/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs nodes as arrays of between 0 and 2 elements. Explanation: ``` FN ``` Input `n` and loop `n` times. ``` ⊞υ✂υ±¹±³±¹ ``` Take the last and second last results (if any), and make them the children of the root of the next tree. ``` ∧υ⭆¹⊟υ ``` Print the last tree, if any. [Answer] # [Branch](https://github.com/hyper-neutrino/branch-lang/), 35 bytes ``` /;{^\;{Z[{Z0]z^[/@^\@^0]~`L`Ln[0`P] ``` Try it on the [online Branch interpreter](https://branch.hyper-neutrino.xyz/#WyIvO3teXFw7e1pbe1owXXpeWy9AXlxcQF4wXX5gTGBMblswYFBdIiwiIiwiNCJd)! Of course, it's only natural that a language based on binary trees would have a way to solve this challenge. Branch is still in development; I'm not sure how I could've solved this before adding a bunch of bugfixes and a couple of new helpers. Pretty-printing the tree was actually around from the start though. I used it as a debug feature; never thought I would've found a challenge so soon to use a debug feature as output formatting for :P ## Explanation The command line argument is automatically loaded into the first and only node in the binary tree. Note that `[...]` is the same as in BF; that is, it's a while loop, so if the current value is 0 at `[`, it skips to `]`, and if the current value is non-zero at `]`, it jumps back to `[`. Therefore, `[...0]` will only run if the value is non-zero, but then the value is zeroed at the end and so it never runs more than once. Essentially, this is an if statement. ``` /;{ Go to the left child, copy the parent, and decrement ^\;{ Go back to the parent, go to the right child, copy, and decrement Z Save the value to register Z [ 0] If that value is not zero {Z Decrement and save to Z (we need to save the value because it gets zeroed to allow the if statement to end) z Restore Z; this is (parent value - 2) if parent value is not 1, and otherwise just 0 ^ Go back to the parent [ 0] If the node is non-zero /@ Go to the left child and run this line on that, returning here when done ^\@ Go to the right sibling and run this line on that, returning here when done ^ Go to the parent, then zero it to end the if statement ~ Return to @, if we are currently in a sub-evaluation. If not, this gets skipped, and we can end the program `L Delete all leaves; every node with leaves is a 0 with -1 and -2 as children; these shouldn't be output `L Delete all leaves again; it might be valid to output such that these leaves are considered the "null" elements like my APL solution and the 2-byte jelly solution do, but I decided to remove them for style and this code is long enough as it is [ ] While this node is non-zero (input 0 and 1 give the same tree, so we need to suppress output if the value was 0) 0 Zero the top node; this turns the while loop into an if statement and also prevents the final output from having the value there `P Pretty-print the tree; this was created for debugging purposes, but conveniently enough, lets us answer this challenge quite nicely ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 14 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⍵>0:∇¨⍵-⍳2⋄0} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu9XOwOpRR/uhFUCm7qPezUaPulsMagE&f=e9Q2Me3QCgOdR72bzQA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f) Outputs as a nested list, where each list contains two elements which are the left and right children, and 0 is null. -10 bytes thanks to Razetime and user, and also using a better online interface courtesy of Razetime ## Explanation ``` { } dfn ⍵>0: if the argument is greater than 0 ∇¨ - recurse; apply this dfn to each of ⍵- - the argument minus (vectorizes) ⍳2 - [1, 2] ⋄0 else, just return 0 ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 34 bytes ``` K`¶ "$+"+`(.*)¶(.*) [$1,$2]¶$1 0G` ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvh0DYuJRVtJe0EDT0tzUPbQCRXtIqhjopR7KFtKoZcBu4J//@bAgA "Retina – Try It Online") Outputs a tree of tuples. No test suite due to the program's use of history. Explanation: ``` K`¶ ``` Replace the input with a newline, representing two empty trees. ``` "$+"+` ``` Repeat the number of times given by the original input... ``` (.*)¶(.*) [$1,$2]¶$1 ``` ... create a node containing the previous two trees, and forget the second last tree. ``` 0G` ``` Keep only the last tree. [Answer] ## Common Lisp, 58 bytes ``` (defun f(n)(case n(0())(1 0)(t(cons(f(1- n))(f(- n 2)))))) ``` Example: ``` USER> (loop for i from 0 to 7 do (print (f i))) NIL 0 (0) ((0) . 0) (((0) . 0) 0) ((((0) . 0) 0) (0) . 0) (((((0) . 0) 0) (0) . 0) ((0) . 0) 0) ((((((0) . 0) 0) (0) . 0) ((0) . 0) 0) (((0) . 0) 0) (0) . 0) ``` Additionally, if you `(ql:quickload :memoize)`, you can do `(memoize-function 'f)` and it will cache intermediate results. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~12~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` z1]Wn|uPbs2l ``` [Run and debug it](https://staxlang.xyz/#c=z1%5DWn%7CuPbs2l&i=&a=1&m=2) A bit long since the trees need to be printed as a string to be observed. ## Explanation ``` z1]Wn|uPbs2l z1] push empty list and [1] (base cases) W loop forever n copy the second to last element |u uneval (JSON.Stringify) P pop & print with newline b copy top two elements s swap 2l two element list ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~46~~ 45 bytes ``` (d F(q((N)(i(l N 1)0(c(F(s N 1))(c(F(s N 2))( ``` [Try it online!](https://tio.run/##K8nMq8zJLC74/18jRcFNo1BDw09TI1MjR8FPwVDTQCNZw02jGMzWhLONgOz/Gm4KBppcQNIQTBqBSWMwaaL5HwA "tinylisp – Try It Online") A function submission that takes an integer and returns a list: * The empty tree is represented by `0` * A nonempty tree is represented by a two-element list containing its left and right subtrees ### Ungolfed Recursively implements the definition: if N is less than 1, returns `0`; otherwise, constructs a list containing the results of two recursive calls, one for N-1 and one for N-2. ``` (load library) (def F (lambda (N) (if (less? N 1) 0 (cons (F (- N 1)) (cons (F (- N 2)) ()))))) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 30 bytes ``` f(n)=if(n>0,[f(n-1),f(n-2)],0) ``` [Try it online!](https://tio.run/##K0gsytRNL/j/P00jT9M2E0jaGehEAyldQ00dEGWkGatjoPk/saAgp1IjT0HXTqGgKDOvBMhUAnGUFEAaNXWiDfT0DA1iNf8DAA "Pari/GP – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), ~~85~~ 71 bytes Thanks to @user, saved 14 bytes ``` fun f(n:Int):Any=when(n){0->"0" 1->"[1]" else->"[${f(n-1)},${f(n-2)}]"} ``` [Try it online!](https://tio.run/##y84vycnM@/8/rTRPIU0jz8ozr0TTyjGv0rY8IzVPI0@z2kDXTslAicsQSEUbxipxpeYUp4LYKtVA5bqGmrU6EJaRZm2sUi3YnNzEzDwNTYVqLgUgSMsvUtBQyFTIzFMw1NMzVYCJg0BBUWZeSU6eRppGpqYmWLSWq/Y/AA "Kotlin – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 bytes ``` L?b?qb1]b,ytbyttbby ``` [Try it online!](https://tio.run/##K6gsyfj/38c@yb4wyTA2SaeyJKmypCQpqfL/f1MA "Pyth – Try It Online") --- Near literal translation of n1k9's Python 3 answer. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~214~~ 175 bytes -39 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` char m[12][50];c(n){f(n,!memset(m,32,600),n*n);}f(n,i,j){m[i][j]=48;n-1?n-2?m[i+1][j-n/2]=47,m[i+1][j+n/2]=92,f(n-1,i+2,j-n),f(n-2,i+2,j+n):(m[++i][--j]=47,m[++i][--j]=48):0;} ``` [Try it online!](https://tio.run/##dVLLbsIwELz7K9wgJLu229gthWIoP9FbyCE4oRjVmyqEXqJ8e@oEwkOUPXi1s7O7M5KN@DKmGVgw3/s0w7Ndmdr8afPRmE1SYBdJFUejMNaGAK3WBPiDy9wuK4njL4q/hSHl8AhU123P8i2tXGTjaBvPXycahFyAUAsPMelBAc/KN8a8B1gHvCvup4XklinuSbQr1aFkQKfERYz5rUJsj@MX5YROQ103v7lN8U9hofwssozgrqYaIY9gl1ggFFcI@@iedV6QtpPgOZbapxke@8RYzzox2zAk8atu4O7cmgTtRTwYpktYQsDvUztlx2591lJk5b4AHGpUI/S/D1TdqA4PqqW8L7unrw70laeP2nxNvxq5tDU0AfdfIImjVXzhqT6b2pc7EgQnR3XzBw "C (gcc) – Try It Online") I chose the ASCII art for fun. The code consists of a function `c()` whose role is to call `f()`, just once. `f()` is a very creative recursive function with a passion for drawing trees on blank arrays. Only the first 5 trees are correct. To display bigger trees I should use an exponential law for the spacing between the nodes, but if I do so, then the highest nodes would be so distant from each other that you wouldn't recognize bigger trees anyway. I will post a conceptually right solution. ]
[Question] [ My previous challenge, [Print invisible text](https://codegolf.stackexchange.com/questions/122703/print-invisible-text) was quite popular, likely due to how trivial it is. However those more observant of you may have noticed that you're not really printing invisible text, because it's impossible to read what was inputted given only the output. So I figured how about a *real* invisible text challenge. Given a string consisting of only printable ASCII characters (`0x20-0x7E`), convert each character to a distinct Unicode character (in UTF-8 encoding) that is not one of the 95 printable ASCII characters (any UTF-8 character outside of the `0x20-0x7E` range) ## Input A string of printable ASCII characters, either as a string or character array/list ## Output The input string with each character replaced with a distinct non-printable character. Each given character must have a corresponding non-printable character that is not used as the substitute for any other character. If you are unable to print non-printable characters, you can output the character values instead. For example if your code replaces all lowercase `a`'s with `0x01`, you may not use `0x01` as the substitution for any other characters. Your code must also be **deterministic**. This means that if, given the string `Hello`, all lowercase `l`'s are replaced with `0x03`, your code must also replace all lowercase `l`'s with `0x03` given any other string. ### Testcases It's somewhat difficult to write testcases for this challenge, so I'll simply show the output as a list of hexcodes ``` input -> output "Hello" -> [0x01, 0x02, 0x03, 0x03, 0x04] "Hi!" -> [0x01, 0x05, 0x06] "" -> [] " H " -> [0x07, 0x07, 0x07, 0x01, 0x07, 0x07, 0x07] "yo! " -> [0x08, 0x04, 0x06, 0x07] ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 123447; // 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 = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~39~~ 36 bytes ``` ``` [Try it online!](https://tio.run/nexus/whitespace#@8@loABECpwgCszm5OJU4AQCIJsTLMDF9f9/SWpxCQA "Whitespace – TIO Nexus") ## Explanation ``` nssn ; label 'loop' ssstssn ; push 4 to use as a multiplication operand sns ; dup 4 to use as a heap address sns ; dup 4 to use as a heap address tnts ; getchar and store at address 4 ttt ; retrieve the value at address 4 tssn ; multiply the character value by 4 tnss ; putchar output the new character nsnn ; jmp 'loop' ``` Originally I wanted to multiply by -0 or -1 since they would be the shortest digits possible to declare in Whitespace. TIO does not differentiate between -0 and +0 so that's out. Unfortunately while the tutorial/spec is ambiguous about how to interpret a negative value as a char TIO (rightly) throws an error about the invalid argument so that also isn't an option. The next shortest working constant is 4 so we end up performing the same basic approach as the Powershell/Pyth solutions. --- # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~56~~ 53 bytes - maps to tag characters ``` ``` [Try it online!](https://tio.run/nexus/whitespace#@8@loABECpycnArogEsBLMnJxQmSBslzggW4uP7/L0ktLgEA "Whitespace – TIO Nexus") ## Explanation Effectively the same approach as the previous version except this uses 0xE0000 as the constant and adds instead of multiplies. This maps the visible ASCII characters to the corresponding Unicode Tag Character (the range U+E0000-U+E007F). The intended use for this range was to indicate the language of the text in a plaintext file however that use is discouraged. This code will output valid labels if you prefix strings with a 0x01 character. The [Unicode Standard](http://www.unicode.org/versions/Unicode9.0.0/ch23.pdf) says that characters in this range have no visible rendering so I feel this meets the spirit of the challenge better than the previous approach. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` O²Ọ ``` [Try it online!](https://tio.run/##y0rNyan8/9//0KaHu3v@//@v5AEUyFdUAgA "Jelly – Try It Online") Squares each codepoint. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~5~~ 2 bytes ``` cp ``` [Try it online](https://ethproductions.github.io/japt/?v=1.4.4&code=Y3A=&input=IkhlbGxvLCBXb3JsZCEi) --- ## Explanation ``` :Implicit input of string U c :Map over the character codes of the string. p :Square them. :Implicit output of result. ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 33 bytes Includes +1 for `-c` ``` {((({}){}){}<>)<>}<>{({}<>)<>}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#@1@toaFRXasJRjZ2mjZ2QLJaA8H@/19BUUlZRVVNXUNTS1tHV0/fwNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXzz8gMCg4JDQsPCIyKjomNi4@ITEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orKquqa27r9uMgA "Brain-Flak – TIO Nexus") ``` # For each character { # Multiply by 4 and move to the other stack ((({}){}){}<>) # End loop <>} # For each character on the other stack <>{ # Copy it back (reverse the stack) ({}<>)<> # End loop }<> ``` [Answer] # Braingolf v0.6, 17 bytes ``` VRl1-M[R.*>v]R&@ ``` Squares each char value then prints. *-1 byte thanks to Erik the Outgolfer's squaring solution* # Braingolf v0.7, 6 bytes [non-competing] ``` {.*}&@ ``` Also squares each value then prints, but v0.7 has the "foreach" `{}` loop [Answer] ## Mathematica, 48 bytes ``` FromCharacterCode[4Mod[Hash/@Characters@#,978]]& ``` Explanation: ``` Characters@# & - Convert string to array of characters Hash/@ - Hash them all using default hash Mod[ ,978] - apply a modulus which uniquely transforms each potential character's hash into a number 4 - times by 4 to move values out of 0x20-0x7E. FromCharacterCode[ ] - Convert array of numbers back to string ``` Interestingly of the two modulus options less than 1000 which changed the 96 characters into 96 unique values with modulus 978 the lowest two values were 7 then 33. Luckily times by 4 converts this to 28 and 132 which both just fall outside the visible range. If I used the other modulus of 784 then I needed to multiply by 18 to move the numbers outside the range. Test case. Note: extra backslashes in there as escape characters for `"` and `\`. Also character 0x7E doesn't seem to want to paste correctly. ``` Input: "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" ``` Output: [![enter image description here](https://i.stack.imgur.com/7Od25.png)](https://i.stack.imgur.com/7Od25.png) The use of `Hash` came about as `ToCharacterCode` is really long. However hashing it was nearly as expensive. The easy mathematica way to do this would be 49 bytes: ``` FromCharacterCode[4ToCharacterCode@Characters@#]& ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 3 bytes ``` C²C ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=C%C2%B2C&inputs=Hello&header=&footer=) That is, ``` C # string to character codes ²C # square each and convert back to letters # the s flag joins as a single string. ``` but if IO was a little less restrictive: ## using `K` flag, 1 byte ``` ² ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=K&code=%C2%B2&inputs=Hello&header=&footer=) Keg is weird okay. It just is. ``` # the K flag enables Keg mode, which makes integers and characters interchangeable. It's a tribute to my first golfing language and existed before I saw this challenge ² # square the code point of each character # output that as characters because K flag. ``` [Answer] # Google Sheets, 68 bytes ``` =ArrayFormula(Join("",IfError(Char(Code(Mid(A1,Row(A:A),1))^2),""))) ``` I wanted to post this to show how awkward it is to do some basic functions in Sheets. Do you want to do an operation to every character in a cell and out the concatenated result? You're at 42 bytes before you even *act* on those characters. ``` =ArrayFormula(Join("",Mid(A1,Row(A:A),1))) ``` Otherwise, this is the same as other solutions: square the code point of each character. [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~8~~ 5 bytes ``` l95f+ ``` [Try it online!](https://tio.run/##S85KzP3/P8fSNE37//@M1JycfEUA "CJam – Try It Online") Adds 95 to each codepoint. [Answer] # Pyth, 6 bytes ``` smC*4C ``` [Try it here.](http://pyth.herokuapp.com/?code=smC%2a4C&test_suite=1&test_suite_input=%22hello%21%22&debug=0) Multiplies each codepoint by 4. [Answer] # PowerShell, ~~32~~ 31 Bytes -1 Thanks to neil, `99+` to `4*` ``` [char[]]"$args"|%{[char](4*$_)} ``` multiplies 9 by each character code and prints it back. [Answer] # [Subleq](https://esolangs.org/wiki/Subleq) (8-bit), 11 bytes ``` -1 15 -128 2 15 -1 15 -1 9 15 15 ``` [Subleq Emulator](http://mazonka.com/subleq/online/hsqjs.cgi) ## Explanation ``` -1 15 -128 '0: input to 15:, if null exit; use -128 for exit so I can be used to add 128 ' in the next line saving a byte 2 15 -1 '3: 15: = 15: + 128 15 -1 9 '6: output 15: 15 15 '9: 15: = 0, goto 0; final 0 is not entered saving a byte ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ÇnçJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cHve4eVe//9npObk5CsCAA "05AB1E – Try It Online") Squares each codepoint. [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` lWf^ ``` XORs each code point with **-1**. CJam's characters are 16 bits wide, so this maps code point **n** to code point **65535 - n**. [Try it online!](https://tio.run/##S85KzP3/Pyc8Le7/f4/UnJx8AA "CJam – Try It Online") [Answer] # [Decimal](//github.com/aaronryank/Decimal), 37 bytes ``` 91D31030030012255D412D590D543D301291D ``` Explanation: ``` 91D ; declare jump 1 310 ; push user input to stack 300 ; duplicate 300 ; duplicate 12255D ; push EOF to stack 412D ; compare top two values, pop, push result 5 90D 5 ; if result == true, quit 43D ; multiply top two values, pop, push result 301 ; print 2 ; pop 91D ; goto jump 1 ``` [Try it online!](https://tio.run/##S0lNzsxNzPn/39LQhUsBCIwNDSC0ASptaGRkagpRYmJoBGGYKlgauCiYQgSNofoNDMG0ERfQxP//E5EAAA) [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` m(c□c ``` [Try it online!](https://tio.run/##yygtzv7/P1cj@dG0hcn///9X8kjNycnXUQjPL8pJUVQCAA "Husk – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 12 bytes ``` ,[[->-<]>.,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJzpa107XJtZOTyf2/38FxRglZRVVNXUNTS1tHV09fQNDI2MTUzNzC0sraxtbO3sHRydnF1c3dw9PL28fXz//gMCg4JDQsPCIyKjomJjYuPiExKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyqrqmto6AA "brainfuck – Try It Online") Negate assuming latin1 output [Answer] # [Grok](https://github.com/AMiller42/Grok-Language), 14 bytes ``` :j }lI_p+wYp q ``` Modification of [this](https://codegolf.stackexchange.com/a/223339/101522) cat program. It adds 95 to every character before it gets outputted, changing the character range from `0x0A - 0x7E` to `0x7F - 0xDD`. [Answer] # Python 3, 40 38 bytes ``` print([chr(ord(x)*9)for x in input()]) ``` [Try It Online!](https://repl.it/IY9G/0) [Answer] # C, 42 bytes ``` c;f(){while(~(c=getchar()))putwchar(c*c);} ``` Assumes a UTF-8 locale. Input is squared. [Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYJOTn5yYk6qXYfc/2TpNQ7O6PCMzJ1WjTiPZNj21JDkjsUhDU1OzoLSkHMxO1krWtK79n5uYmQdUW5xaAtGu4eMc7@jjo6OkpAkyBKjCw9XHx18h3D/IxwUA) [Answer] # [Clean](https://clean.cs.ru.nl), 25 bytes ``` import StdEnv ``` # ``` map((+)'~') ``` A partial function literal. [Try it online!](https://tio.run/##S85JTcz7/z83P6U0J1UhNzEzjysztyC/qEQhuCTFNa@MK7gkEcixBUoVaGhoa6rXqWsqRKt7pObk5KvH/v//LzktJzG9@L@up89/l8q8xNzM5GIA "Clean – Try It Online") **Realistically:** ``` f s = {# c+'~' \\ c <-: s} ``` Unboxed array comprehension over an unboxed array of the same type (`{#Char} -> {#Char}`). Clean will be able to determine that the uniqueness is transferrable (`!u:{#Char} -> u:{#Char}`), and that the size is the same as the input size. This means that if you pass a `*String`, every character will be destructively updated with the corresponding one in the output, meaning no memory allocation or movement is done and the graph node is fully reused. [Try it online!](https://tio.run/##S85JTcz7/z83P6U0J1UhNzEzjysztyC/qEQhuCTFNa@MK02hWMFWoVpZIVlbvU5dISZGIVnBRtdKobiWK7gkEajOViFNQckjNScnX@n//3/JaTmJ6cX/dT19/rtU5iXmZiYXAwA "Clean – Try It Online") [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 18 bytes One of the rare cases that Erlang is ever competitive. ``` f(X)->[I*I||I<-X]. ``` [Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/TSNCU9cu2lPLs6bG00Y3Ilbvf25iZp5GdCxQmEsBCDLzrdLKizJLUjXSNJSAfA8gVtLU1AGK5@VoaOpgKvJIzcnJByrFq6gyX1EBZBx@kzIVQWrwKwKrQFGk9x8A "Erlang (escript) – Try It Online") # Explanation ``` f(X)-> % Function taking a single string as input [I*I|| % Square the code-point ... I<-X]. % ... for every character taken from the string ``` [Answer] # [Kotlin](https://kotlinlang.org), 25 bytes Subtract **99** from each character value. This ends up moving space to FFBD (as Kotlin uses UTF-16) and most of the ASCII set to control characters and unreadable garbage. ``` {fold(""){s,c->s+(c-99)}} ``` [Try it online!](https://tio.run/##ZY7BbsIwDIbvPIWVC4mgEZMmJJBgBy4g7cb2AIGmk7fgRK1Bk6o@e3E26AH@i2V/9v/7J3JA6i8uANIFGzwEv4Q910hfVhso1rcGVn1bxVBqpUzbTI/FupnoY7FYmK7rqzPBySHJQTsCUfZj/8uwgtq78h3JC3tbglIDlzzBQ6rO@@aPJgnkQFrY08CeXLqFZCFbjjtibaT@f6pf5mbgWTa5cs@uZv06hfFs/EA5fqbk641r5MeMOvsdkT7udgqUMaOu3/oQ4hU "Kotlin – Try It Online") [Answer] # [Duocentehexaquinquagesimal](https://esolangs.org/wiki/Duocentehexaquinquagesimal), 5 bytes ``` SYÍ’ü ``` [Try it online!](https://tio.run/##S0oszvifnFhiYxPzqGGRXbx1cWqKgm6mgrphsXWcNVDIWl0hXsHILq80x7qkqDQPqDRVQbdY11Ah3jo1OSNfQTdPQR2oLOnQMuPDW5yP7stQsrPR1tXTiY5VetSw0Evdzg6isEY/v6BEP784MSkzFUopxNslWYOFk4oSM/PSSpOzESyFpP/BkYd7HzXMPLznP9CC/x6pOTn5AA) [Answer] # [Python 3](https://docs.python.org/3/), 47 bytes ``` lambda x:''.join(chr(y-32+(y>63)*98)for y in x) ``` Input must be bytes. I know this doesn't win, I'm posting it because the output could fit into an 8-bit ascii extension. [Try it online!](https://tio.run/##DcHJDYAgEADAVvi5eIVI4pVoJX7wQDG6GOTBVo/OPOQPizLqYYqXuudVsdAnSXlag7AcDqiQVQY01pKnXcu1dYyYQRZ4fJxBDxpm8tsLTuG@gQiVyEVoNP/FDw "Python 3 – Try It Online") [Answer] # [Thunno](https://github.com/Thunno/Thunno) `J`, 4 bytes (Actually \$ 4 \log\_{256}(96) \approx \$ 3.29 bytes but the leaderboard doesn't take decimals) ``` O2^C ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSl1LsgqWlJWm6Fkv8jeKcIUyoyIK1Hqk5Ofk6CuH5RTkpihBBAA) #### Explanation ``` O # Ordinals of the input 2^ # Square each ordinal C # Convert back to characters # J flag joins the list ``` ]
[Question] [ The challenge is to write codegolf for the [permanent of a matrix](https://en.wikipedia.org/wiki/Permanent). The permanent of an \$n\times n\$ matrix \$A = a\_{i,j}\$) is defined as $$\text{perm}(A) = \sum\_{\sigma \in S\_n} \prod^n\_{i=1} a\_{i,\sigma(i)}$$ Here \$S\_n\$ represents the set of all permutations of \$[1, n]\$. As an example (from the wiki): $$\text{perm} \left( \begin{matrix} a & b & c \\ d & e & f \\ g & h & i \\ \end{matrix} \right) = aei + bfg + cdh + ceg + bdi + afh$$ Your code can take input however it wishes and give output in any sensible format but please include in your answer a full worked example including clear instructions for how to supply input to your code. To make the challenge a little more interesting, the matrix may include complex numbers. The input matrix is always square and will be at most 6 by 6. You will also need to be able to handle the empty matrix which has permanent 1. There is no need to be able to handle the empty matrix (it was causing too many problems). **Examples** Input: ``` [[ 0.36697048+0.02459455j, 0.81148991+0.75269667j, 0.62568185+0.95950937j], [ 0.67985923+0.11419187j, 0.50131790+0.13067928j, 0.10330161+0.83532727j], [ 0.71085747+0.86199765j, 0.68902048+0.50886302j, 0.52729463+0.5974208j ]] ``` Output: ``` -1.7421952844303492+2.2476833142265793j ``` Input: ``` [[ 0.83702504+0.05801749j, 0.03912260+0.25027115j, 0.95507961+0.59109069j], [ 0.07330546+0.8569899j , 0.47845015+0.45077079j, 0.80317410+0.5820795j ], [ 0.38306447+0.76444045j, 0.54067092+0.90206306j, 0.40001631+0.43832931j]] ``` Output: ``` -1.972117936608412+1.6081325306004794j ``` Input: ``` [[ 0.61164611+0.42958732j, 0.69306292+0.94856925j, 0.43860930+0.04104116j, 0.92232338+0.32857505j, 0.40964318+0.59225476j, 0.69109847+0.32620144j], [ 0.57851263+0.69458731j, 0.21746623+0.38778693j, 0.83334638+0.25805241j, 0.64855830+0.36137045j, 0.65890840+0.06557287j, 0.25411493+0.37812483j], [ 0.11114704+0.44631335j, 0.32068031+0.52023283j, 0.43360984+0.87037973j, 0.42752697+0.75343656j, 0.23848512+0.96334466j, 0.28165516+0.13257001j], [ 0.66386467+0.21002292j, 0.11781236+0.00967473j, 0.75491373+0.44880959j, 0.66749636+0.90076845j, 0.00939420+0.06484633j, 0.21316223+0.4538433j ], [ 0.40175631+0.89340763j, 0.26849809+0.82500173j, 0.84124107+0.23030393j, 0.62689175+0.61870543j, 0.92430209+0.11914288j, 0.90655023+0.63096257j], [ 0.85830178+0.16441943j, 0.91144755+0.49943801j, 0.51010550+0.60590678j, 0.51439995+0.37354955j, 0.79986742+0.87723514j, 0.43231194+0.54571625j]] ``` Output: ``` -22.92354821347135-90.74278997288275j ``` You may not use any pre-existing functions to compute the permanent. [Answer] # J, 5 bytes ``` +/ .* ``` J does not offer builtins for the permanent or determinant but instead offers a conjunction `u . v y` which recursively expands `y` along the minors and calculates dyadic `u . v` between the cofactors and the output of the recursive call on the minors. The choices of `u` and `v` can vary. For example, using `u =: -/` and `v =: *` is `-/ .*` which is the determinant. Choices can even by `%/ .!` where `u=: %/`, reduce by division, and `v =: !` which is binomial coefficient. I'm not sure what that output signifies but you're free to choose your verbs. An alternative implementation for **47 bytes** using the same method in my Mathematica [answer](https://codegolf.stackexchange.com/a/96860/6710). ``` _1{[:($@]$[:+//.*/)/0,.;@(<@(,0#~<:)"+2^i.@#)"{ ``` This simulates a polynomial with *n* variables by creating a polynomial with one variable raised to powers of 2. This is held as a coefficient list and polynomial multiplication is performed using convolution, and the index at 2*n* will contain the result. Another implementation for **31 bytes** is ``` +/@({.*1$:\.|:@}.)`(0{,)@.(1=#) ``` which is a slightly golfed version based on Laplace expansion taken from the J essay on [determinants](http://code.jsoftware.com/wiki/Essays/Determinant). ## Usage ``` f =: +/ .* f 0 0 $ 0 NB. the empty matrix, create a shape with dimensions 0 x 0 1 f 0.36697048j0.02459455 0.81148991j0.75269667 0.62568185j0.95950937 , 0.67985923j0.11419187 0.50131790j0.13067928 0.10330161j0.83532727 ,: 0.71085747j0.86199765 0.68902048j0.50886302 0.52729463j0.5974208 _1.7422j2.24768 f 0.83702504j0.05801749 0.03912260j0.25027115 0.95507961j0.59109069 , 0.07330546j0.8569899 0.47845015j0.45077079 0.80317410j0.5820795 ,: 0.38306447j0.76444045 0.54067092j0.90206306 0.40001631j0.43832931 _1.97212j1.60813 f 0.61164611j0.42958732 0.69306292j0.94856925 0.4386093j0.04104116 0.92232338j0.32857505 0.40964318j0.59225476 0.69109847j0.32620144 , 0.57851263j0.69458731 0.21746623j0.38778693 0.83334638j0.25805241 0.6485583j0.36137045 0.6589084j0.06557287 0.25411493j0.37812483 , 0.11114704j0.44631335 0.32068031j0.52023283 0.43360984j0.87037973 0.42752697j0.75343656 0.23848512j0.96334466 0.28165516j0.13257001 , 0.66386467j0.21002292 0.11781236j0.00967473 0.75491373j0.44880959 0.66749636j0.90076845 0.0093942j0.06484633 0.21316223j0.4538433 , 0.40175631j0.89340763 0.26849809j0.82500173 0.84124107j0.23030393 0.62689175j0.61870543 0.92430209j0.11914288 0.90655023j0.63096257 ,: 0.85830178j0.16441943 0.91144755j0.49943801 0.5101055j0.60590678 0.51439995j0.37354955 0.79986742j0.87723514 0.43231194j0.54571625 _22.9235j_90.7428 ``` [Answer] ## Haskell, 59 bytes ``` a#((b:c):r)=b*p(a++map tail r)+(c:a)#r _#_=0 p[]=1 p l=[]#l ``` This does a Laplace-like development along the first column, and uses that the order of the rows doesn't matter. It works for any numeric type. Input is as list of lists: ``` Prelude> p [[1,2],[3,4]] 10 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œ!ŒDḢ€P€S ``` [Try it online!](http://jelly.tryitonline.net/#code=xZIhxZJE4bii4oKsUOKCrFM&input=&args=W1sgMC42MTE2NDYxMSswLjQyOTU4NzMyaiwgIDAuNjkzMDYyOTIrMC45NDg1NjkyNWosCiAgICAgMC40Mzg2MDkzMCswLjA0MTA0MTE2aiwgIDAuOTIyMzIzMzgrMC4zMjg1NzUwNWosCiAgICAgMC40MDk2NDMxOCswLjU5MjI1NDc2aiwgIDAuNjkxMDk4NDcrMC4zMjYyMDE0NGpdLAogICBbIDAuNTc4NTEyNjMrMC42OTQ1ODczMWosICAwLjIxNzQ2NjIzKzAuMzg3Nzg2OTNqLAogICAgIDAuODMzMzQ2MzgrMC4yNTgwNTI0MWosICAwLjY0ODU1ODMwKzAuMzYxMzcwNDVqLAogICAgIDAuNjU4OTA4NDArMC4wNjU1NzI4N2osICAwLjI1NDExNDkzKzAuMzc4MTI0ODNqXSwKICAgWyAwLjExMTE0NzA0KzAuNDQ2MzEzMzVqLCAgMC4zMjA2ODAzMSswLjUyMDIzMjgzaiwKICAgICAwLjQzMzYwOTg0KzAuODcwMzc5NzNqLCAgMC40Mjc1MjY5NyswLjc1MzQzNjU2aiwKICAgICAwLjIzODQ4NTEyKzAuOTYzMzQ0NjZqLCAgMC4yODE2NTUxNiswLjEzMjU3MDAxal0sCiAgIFsgMC42NjM4NjQ2NyswLjIxMDAyMjkyaiwgIDAuMTE3ODEyMzYrMC4wMDk2NzQ3M2osCiAgICAgMC43NTQ5MTM3MyswLjQ0ODgwOTU5aiwgIDAuNjY3NDk2MzYrMC45MDA3Njg0NWosCiAgICAgMC4wMDkzOTQyMCswLjA2NDg0NjMzaiwgIDAuMjEzMTYyMjMrMC40NTM4NDMzaiBdLAogICBbIDAuNDAxNzU2MzErMC44OTM0MDc2M2osICAwLjI2ODQ5ODA5KzAuODI1MDAxNzNqLAogICAgIDAuODQxMjQxMDcrMC4yMzAzMDM5M2osICAwLjYyNjg5MTc1KzAuNjE4NzA1NDNqLAogICAgIDAuOTI0MzAyMDkrMC4xMTkxNDI4OGosICAwLjkwNjU1MDIzKzAuNjMwOTYyNTdqXSwKICAgWyAwLjg1ODMwMTc4KzAuMTY0NDE5NDNqLCAgMC45MTE0NDc1NSswLjQ5OTQzODAxaiwKICAgICAwLjUxMDEwNTUwKzAuNjA1OTA2NzhqLCAgMC41MTQzOTk5NSswLjM3MzU0OTU1aiwKICAgICAwLjc5OTg2NzQyKzAuODc3MjM1MTRqLCAgMC40MzIzMTE5NCswLjU0NTcxNjI1al1d) ### How it works ``` Œ!ŒDḢ€P€S Main link. Argument: M (matrix / 2D array) Œ! Generate all permutations of M's rows. ŒD Compute the permutations' diagonals, starting with the main diagonal. Ḣ€ Head each; extract the main diagonal of each permutation. P€ Product each; compute the products of the main diagonals. S Compute the sum of the products. ``` [Answer] # Python 2, 75 bytes Seems clunky... should be beatable. ``` P=lambda m,i=0:sum([r[i]*P(m[:j]+m[j+1:],i+1)for j,r in enumerate(m)]or[1]) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ ~~14~~ 13 bytes ``` œvyvyNè}Pˆ}¯O ``` [Try it online!](http://05ab1e.tryitonline.net/#code=xZN2eXZ5TsOofVDLhn3Cr08&input=W1swLjYxMTY0NjExKzAuNDI5NTg3MzJqLDAuNjkzMDYyOTIrMC45NDg1NjkyNWosMC40Mzg2MDkzMCswLjA0MTA0MTE2aiwwLjkyMjMyMzM4KzAuMzI4NTc1MDVqLDAuNDA5NjQzMTgrMC41OTIyNTQ3NmosMC42OTEwOTg0NyswLjMyNjIwMTQ0al0sWzAuNTc4NTEyNjMrMC42OTQ1ODczMWosMC4yMTc0NjYyMyswLjM4Nzc4NjkzaiwwLjgzMzM0NjM4KzAuMjU4MDUyNDFqLDAuNjQ4NTU4MzArMC4zNjEzNzA0NWosMC42NTg5MDg0MCswLjA2NTU3Mjg3aiwwLjI1NDExNDkzKzAuMzc4MTI0ODNqXSxbMC4xMTExNDcwNCswLjQ0NjMxMzM1aiwwLjMyMDY4MDMxKzAuNTIwMjMyODNqLDAuNDMzNjA5ODQrMC44NzAzNzk3M2osMC40Mjc1MjY5NyswLjc1MzQzNjU2aiwwLjIzODQ4NTEyKzAuOTYzMzQ0NjZqLDAuMjgxNjU1MTYrMC4xMzI1NzAwMWpdLFswLjY2Mzg2NDY3KzAuMjEwMDIyOTJqLDAuMTE3ODEyMzYrMC4wMDk2NzQ3M2osMC43NTQ5MTM3MyswLjQ0ODgwOTU5aiwwLjY2NzQ5NjM2KzAuOTAwNzY4NDVqLDAuMDA5Mzk0MjArMC4wNjQ4NDYzM2osMC4yMTMxNjIyMyswLjQ1Mzg0MzNqXSxbMC40MDE3NTYzMSswLjg5MzQwNzYzaiwwLjI2ODQ5ODA5KzAuODI1MDAxNzNqLDAuODQxMjQxMDcrMC4yMzAzMDM5M2osMC42MjY4OTE3NSswLjYxODcwNTQzaiwwLjkyNDMwMjA5KzAuMTE5MTQyODhqLDAuOTA2NTUwMjMrMC42MzA5NjI1N2pdLFswLjg1ODMwMTc4KzAuMTY0NDE5NDNqLDAuOTExNDQ3NTUrMC40OTk0MzgwMWosMC41MTAxMDU1MCswLjYwNTkwNjc4aiwwLjUxNDM5OTk1KzAuMzczNTQ5NTVqLDAuNzk5ODY3NDIrMC44NzcyMzUxNGosMC40MzIzMTE5NCswLjU0NTcxNjI1al1d) **Explanation** ``` œ # get all permutations of rows v } # for each permutation yv } # for each row in the permutation yNè # get the element at index row-index P # product of elements ˆ # add product to global array ¯O # sum the products from the global array ``` [Answer] # Python 2, 139 bytes ``` from itertools import* def p(a):c=complex;r=range(len(a));return sum(reduce(c.__mul__,[a[j][p[j]]for j in r],c(1))for p in permutations(r)) ``` **[repl.it](https://repl.it/EBh8/3)** Implements the naïve algorithm which blindly follows the definition. [Answer] # MATL, ~~17~~14 bytes ``` tZyt:tY@X])!ps ``` [**Try it Online**](http://matl.tryitonline.net/#code=dFp5dDp0WUBYXSkhcHM&input=WzAuMzY2OTcwNDgrMC4wMjQ1OTQ1NWosIDAuODExNDg5OTErMC43NTI2OTY2N2osIDAuNjI1NjgxODUrMC45NTk1MDkzN2o7IDAuNjc5ODU5MjMrMC4xMTQxOTE4N2osIDAuNTAxMzE3OTArMC4xMzA2NzkyOGosIDAuMTAzMzAxNjErMC44MzUzMjcyN2o7IDAuNzEwODU3NDcrMC44NjE5OTc2NWosIDAuNjg5MDIwNDgrMC41MDg4NjMwMmosIDAuNTI3Mjk0NjMrMC41OTc0MjA4aiBd) **Explanation** ``` t % Implicitly grab input and duplicate Zy % Compute the size of the input. Yields [rows, columns] t: % Compute an array from [1...rows] tY@ % Duplicate this array and compute all permutations (these are the columns) X] % Convert row/column to linear indices into the input matrix ) % Index into the input matrix where each combination is a row !p % Take the product of each row s % Sum the result and implicitly display ``` [Answer] # Ruby, ~~74~~ 63 bytes ``` ->a{p=0;a.permutation{|b|n=1;i=-1;a.map{n*=b[i+=1][i]};p+=n};p} ``` A straightforward translation of the formula. Several bytes saved thanks to ezrast. ## Explanation ``` ->a{ # Initialize the permanent to 0 p=0 # For each permutation of a's rows... a.permutation{|b| # ... initialize the product to 1, n=1 # initialize the index to -1; we'll use this to go down the main diagonal # (i starts at -1 because at each step, the first thing we do is increment i), i=-1 # iteratively calculate the product, a.map{ n*=b[i+=1][i] } # increase p by the main diagonal's product. p+=n } p } ``` [Answer] # Ruby 2.4.0, ~~59~~ 61 bytes Recursive Laplace expansion: ``` f=->a{a.pop&.map{|n|n*f[a.map{|r|r.rotate![0..-2]}]}&.sum||1} ``` Less golfed: ``` f=->a{ # Pop a row off of a a.pop&.map{ |n| # For each element of that row, multiply by the permanent of the minor n * f[a.map{ |r| r.rotate![0..-2]}] # Add all the results together }&.sum || # Short circuit to 1 if we got passed an empty matrix 1 } ``` Ruby 2.4 is not officially released. On earlier versions, `.sum` will need to be replaced with `.reduce(:+)`, adding 7 bytes. [Answer] # [Julia 0.4](http://julialang.org/), 73 bytes ``` f(a,r=1:size(a,1))=sum([prod([a[i,p[i]] for i=r]) for p=permutations(r)]) ``` In newer versions of julia you can drop the `[]` around the comprehensions, but need `using Combinatorics` for the `permutations` function. Works with all Number types in Julia, including `Complex`. `r` is a `UnitRange` object defined as a default function argument, which can depend on previous function arguments. [Try it online!](https://tio.run/##dZDBasMwDIbvfQof7S0UybZsaZCx9wg5BJZQj7YJTstg7N0zp6WBHqaT0Pfz/5K@rsfULcuguyrX@Dann760aEw9X0@6mfL4qZuuSdXUpLZVw5hVqnNrbt1UT30@XS/dJY3nWWfTmuVjPozfatDjuZ@1q5wxu6eRrew2yv186KZeNwr2LgSJ4PkV9mA9iSd6SadKFcSInkWwoEg2SAjxgYKlwMhUkJAQiLuhnXquIozCJNYVYXFDQd48CNBhFFiRgyK0/EAIzgGGNZkdORvtP/YRgSn6uAoDisSwbR9YwN4PI2AODuyWXAzFh3UpkugtrMGqre5/@30flj8 "Julia 0.4 – Try It Online") [Answer] # Mathematica, 54 bytes ``` Coefficient[Times@@(#.(v=x~Array~Length@#)),Times@@v]& ``` Now that the empty matrices are no longer considered, this solution is valid. It originates from the [MathWorld page on permanents](http://mathworld.wolfram.com/Permanent.html). [Answer] ## JavaScript (ES6), 82 bytes ``` f=a=>a[0]?a.reduce((t,b,i)=>t+b[0]*f(a.filter((_,j)=>i-j).map(c=>c.slice(1))),0):1 ``` Works with the empty matrix too, of course. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes ``` p(m)=if(#m,sum(n=1,#m,m[1,n]*p(m[^1,^n])),1) ``` [Try it online!](https://tio.run/##RVTbjhNHEP2V0ebFJsOq7l2FRd55iPIBi5EWCGQlbFlkecjXb0739IAteWxXV9W5VPXt8fvT66@3l5fb4XJ8@/Tl8Ntl/ffH5XB9yyu@Xh54vZ5fIfjwgdcP1/PxuPLx5fF2@/bf4bK8/mO5fX@6Ph/u3l3f3B1P269e6rQH/vrx/Cty6KFfsffXu@O6PDw8rsvHdfl0Wj6vy9/r8uW0fF2Xf9bl6bwufz4@H/ohuteIamT5O92TmJe5v3q3LnSfzJZVjEBziYpoWyDEIzkdgfJyKkXg1AOt0ksUAeRycc4MJ1ZuRT2ghGOSW4BJlTh6j1RXaTJLNab0Zq0HgqtaTFSRRbLBdcoMJZk9kFwWvblXMyG0OA@GqY3EyTpDT@JmtaWQFotEh4W4NObZpNyp1YDlxVQUtcGiBrxu0WF5FOTZEqylgWSXBM/WkD1FJBA37i08BX/7VkgTOtjg1/A0stnaDfpQSRcXRMEvZgsiKKUdkyFbSnknGMxh@OghKc@mU5MopMtWzDpgmV1QIeBbh0VAZygwmYuoqHZ5VeCA055BFaY8dMchtxZ7DwiUg4lKCLHZRtFbOsswJDBVQMVbhkCRiDEmmq0lUE6xVBUO5vAjycVmRgC854CrwbBzVysc45A2eIR7k33iABAjWKNHSxZL3VAxXtbGMBh6seospRC7u9UJCkGF1F0rjc6we95IW7U9IGMvhoeupuFTEtG0zr3LHqAEtjOQDJQcYw/EGxydmwPWsLCXEiYSeDYXhDt67RkEB7ARs3lzKyihg0cmYROnJDiErjEGiFrkrhXytbAXQytLkNfdD@WQ4Yc5oOuUyrAqvk1clhpq7QkoWmjZA1gcHNsNNCjNNGgo4b07G0gpVOuzgFsBK6T7vBk2eJRiXBgmOW@G6n7SAIUdKNw582bIPghQpWdgc7h@loKx1nzsYOHfpDk9zsSEYr0UOQq33AOmVeVjSBSC7ldfq0rIKMPyJoqD@yyIAmefBTdvkA0Z5/Px5X8 "Pari/GP – Try It Online") --- # [Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes ``` m->polcoef(vecprod([x^2^i|i<-[0..#m-1]]*m),2^#m-1) ``` Based on [@miles's Mathematica answer](https://codegolf.stackexchange.com/a/96860/9288). According to [Wolfram MatheWorld](https://mathworld.wolfram.com/Permanent.html), the permanent of a matrix \$A = (a\_{ij})\$ is the coefficient of \$x\_1 \cdots x\_n\$ in the polynomial \$\prod\_{i=1}^{n}\sum\_{j=1}^na\_{ij}x\_j\$. This is exactly what miles's answer does. But in PARI/GP there isn't an easy way to generate an arbitrary number of new variables. So instead of a list variables \$[x\_1, \dots, x\_n]\$, I use the \$2^i\$'th powers of a single variable \$x\$, i.e., \$[x^1, \dots, x^{2^{n-1}}]\$, and take the coefficient of \$x^1 \cdots x^{2^{n-1}} = x^{2^n-1}\$. [Try it online!](https://tio.run/##RVTbbhtHDP2Vhfsip5LB@5B1mvc8FP0AVwYcx0kNRLZgOEUL9N/dM7OzjQRoJXFIngs557uXx8PX89v54eW0/Pp2Onw4P3@7f374svvr4f788vx5d/P3rdw@/vv4/nBDV1c/nQ58PL47Xe7ltn@/fLs7n7/9szsthw/L@eXx6XV38fHpl4vL6/XXeXfavu4ufv/@@iOy6y0R/RH@4@nicr/c3Nztl0/75f56@bxfHvbLl@vl6375c788HvfLb3evu36IrjSiGln@TFck5mXu7z7uF7pKZssqRqC5REW0NRDikZyOQHk5lSJw3QOt0ksUAeRycc4MJ1ZuRT2ghGOSa4BJlTh6j1RXaTJLNab0Zq0HgqtaTFSRRbLCdcoMJZk9kFwWvblXMyG0OA6GqY3EyTpDT@JmtaaQFotEh4W4NObZpNyp1YDlxVQUtcKiBrxu0WF5FORZE6ylgWSXBM/WkD1FJBA37i08BX/7WkgTOtjg1/A0stnaDfpQSRcXRMEvZgsiKKUdkyFbSnkjGMxh@OghKc@mU5MopMtazDpgmV1QIeBbh0VAZygwmYuoqHZ5VeCA05ZBFaY8dMchtxZbDwiUg4lKCLHZStFbOsswJDBVQMVrhkCRiDEmmq0lUE6xVBUO5vAjycVmRgC854CrwbBzUysc45A2eIR7k23iABAjWKNHSxZLXVExXtbGMBh6seospRC7u9UJCkGF1E0rjc6we95IW7UtIGMvhoeupuFTEtG0zr3LHqAEtjOQDJQcYw/EGxydmwPWsLCXEiYSeDYXhDt67RkEB7ARs3lzKyihg0cmYROnJDiErjEGiFrkphXytbAXQytLkNfND@WQ4Yc5oOuUyrAqvk5clhpqbQkoWmjZA1gcHNsMNCjNNGgo4b05G0gpVOuzgFsBK6TbvBk2eJRiXBgmOW@G6n7SAIUdKNw582bIPghQpWdgc7j@LwVjrfnYwcK/SXN6nIkJxXopchRuuQVMq8rHkCgE3a6@VpWQUYblTRQHt1kQBc4@C27eIBsyjsfLt/8A "Pari/GP – Try It Online") ]
[Question] [ The [Binet formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression) is a closed form expression for the \$n\$'th [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number): $$F\_n = \frac {\phi^n - (1-\phi)^n} {\sqrt 5}$$ where \$\phi = \frac {1 + \sqrt 5} 2\$ is the [golden ratio](https://en.wikipedia.org/wiki/Golden_ratio). This formula works even when \$n\$ is [negative](https://en.wikipedia.org/wiki/Fibonacci_number#Negafibonacci) or rational, and so can be a basis to calculating "complex Fibonacci numbers". For example, by setting \$n = \frac 1 2\$, we can calculate \$F\_\frac 1 2\$ as: $$F\_\frac 1 2 = \frac 1 {\sqrt 5} \left( \sqrt \frac {1+\sqrt 5} 2 - \sqrt \frac {1-\sqrt 5} 2 \right) \\ \approx 0.56886-0.35158i$$ You are to take a floating point, \$-10 \le n \le 10\$, with up to 3 decimals after the point, and output \$F\_n\$, accurate to at least 5 decimal places. You may either round or truncate, so long as it is consistent. You may also choose to input as a rational number if you wish, or as a `(numerator, denominator)` pair. You may also choose whether integers should be suffixed with `.0` or not, so long as it is consistent across all 21 integer inputs. As the output will be a complex number in all but 21 cases, you may output in any reasonable format for such a type, including outputting as a `(real, imag)` pair. For the integer inputs, the imaginary part will be \$0\$. You may choose whether to output the imaginary part in this case (and returning an integer or float is perfectly fine). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases These all round their output, rather than truncate. ``` n Re(Fn) Im(Fn) -10 -55 0 1 1 0 -7 13 0 3 2 0 0.5 0.56886 -0.35158 5.3 5.75045 0.02824 7.5 16.51666 0.01211 -1.5 0.21729 -0.92044 -9.06 34.37587 -6.55646 9.09 35.50413 0.00157 -2.54 0.32202 1.50628 5.991 7.96522 0.00071 -6.033 -8.08507 0.84377 8.472 26.36619 -0.00756 ``` And a script to output [all possible outputs](https://tio.run/##TY27DsIwDEXn5ivuhg0tT4FEJVZG/iFAC5EaJ4QgUSG@vaSFAQ@27tGx7dt4dbLqujo4i3trfQtjvQsR91uIOQ5K@avBDrTAZGC0ZsYMS6XqhBttj2cNKUG9Nx5DUPRygZR5AL3@20xLLiTFCIKWS0XFYp4qxzC4VJlgthuSyvaSHpyc9U31pAPVJMysMh@MRBq9ys0br3L7baNpOmx1JMkR3EPOtJdpqHSTY81/yFh9@SLmrvsA) in the same format (gets cut off on TIO due to the length). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` (h=2/--√5;h^#-(1-h)^#)√.2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPD1khfV/dRxyxT64w4ZV0NQ90MzThlTaCAnpHa/8DSzNQSh4CizLySaGVduzQH5Vi1uuDkxLy6ai5dQwMdLgUFQyChaw5iGYMIAz1TEGWqB@aZg3m6hhDKUs/ADCQKpC1BfCM9UxOIYktLsDFmegbGYH0WeibmRly1/wE "Wolfram Language (Mathematica) – Try It Online") Uses \$\frac{\sqrt 5+1}{2}=\frac{2}{\sqrt 5-1}\$. Mathematica's pre-increment/decrement operators still return the desired value when used on (non-variable) non-atoms. The built-in [`Fibonacci`](https://reference.wolfram.com/language/ref/Fibonacci.html) is a continuous real function, the real part of the Binet formula: \$F\_n=\frac{\phi^n-\cos(\pi n)\phi^{-n}}{\sqrt 5}\$. [Answer] # [Octave](https://www.gnu.org/software/octave/), 20 bytes ``` @(n)([1 1;1 0]^n)(2) ``` [Try it online!](https://tio.run/##Rc7PCoAgDMDhe0@xox4cW2YmEfQe/YGIPNYlen0TLPX07ccYXvu9PUfwwxxGcUoxMXDPQMsah1oGLxQTxCcrLwA4U9lSdSGh@WlQ/7S5Ki50SO23EOm@WqNp8gXnONUWSetUO2xs/NkL "Octave – Try It Online") You know, this classical Fibonacci number formula still works here... $$ F\_x=\begin{bmatrix}1 & 0\end{bmatrix}\begin{bmatrix}1 & 1 \\ 1 & 0\end{bmatrix}^x\begin{bmatrix}0 \\ 1\end{bmatrix} $$ --- Aha, after I posted this answer. I try some searching about it. And I finally found out [flawr](https://codegolf.stackexchange.com/users/24877/flawr)'s [previous answer](https://codegolf.stackexchange.com/a/105184/44718) to [Negative Fibonacci Numbers](https://codegolf.stackexchange.com/questions/105183) question. It just using the same codes. Also there are many other answers may simply fit this questions' requirement. I'm not sure if this is a duplicate here, but... They does solve this question with short codes... [Answer] # [R](https://www.r-project.org/), ~~60~~ ~~57~~ 41 bytes ~~Just the straightforward golfed implementation. Stole the `sqrt()` = `^.5` trick from Level River St.~~ att and Dominic van Essen golfed off several bytes, thank you. My algebra is rusty! This version takes arguments in complex number notation. ``` function(x,g=.5+5^.5/2)(g^x-(1-g)^x)/5^.5 ``` [Try it online!](https://tio.run/##ZZCxbsMwDET3fAWBLjZSMSQlUtKQX/HQAjGypEDRAv57V5KVxk21Sfd0d@Tnerm@ndfL9@396/pxG5bX@Yx61An1JOMwT4sb2M3jtIyn@ljxARzTka4AMMILOFXohw5NBt7UJgPDk@ziTmb/LIPf/5Z/MpV@FWhyuVhKBuAIvbKmDin6B6QYlUJtSUiSJHQo7pzYUNnMNoiFuZflv3HCUXKLy0KhO7mMZJWqkA/oo6ZYoOKpFqzHFSj/QoqlUhu@xBFr7E6CGu5QkbwI1RWUFmTymC7nuuMGRcymIt2J4r24IXnfIZeQklJsUAo@9jhIGKJ0SAy9GW/TFSO1w/oD "R – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 43 bytes ``` lambda x,p=.5+5**.5/2:(p**x-(1-p)**x)/5**.5 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp8BWz1TbVEtLz1TfyEqjQEurQlfDULdAE8jQ1AeL/y8oyswr0UjT0DU00NTkgvEMkdi65kgcY2RF@kZIPFNjfVQjTFGkdY1RuSZA9aZA9f8B "Python 3 – Try It Online") -6 bytes thanks to caird coinheringaahing (old version) -6 bytes thanks to Noodle9 (old version) -a lot of bytes after realizing i don't need sympy thanks to Noodle9 -1 byte thanks to dingledooper [Answer] # [MATL](https://github.com/lmendo/MATL), 15 bytes ``` 17Lt_Qwhi^d5X^/ ``` [Try it online!](https://tio.run/##y00syfn/39DcpyQ@sDwjMy7FNCJO//9/Cz0TcyMA) Or [verify all test cases](https://tio.run/##y00syfmf8N/Q3KckPrA8IzMuxTQiTv@/S8h/XUMDLkMuXXMuYy4DPVMuUz1jLnMgrWsIIiz1DMy4gIQll66RnqkJUNbSEqjYTM/A2JjLQs/E3EgBAA). ### Explanation ``` 17L % Push ϕ (predefined literal) t_Q % Duplicate, negate, add 1: gives 1-ϕ wh % Swap, concatenate horizontally: gives [1-ϕ, ϕ] i^ % Input n, element-wise power: gives [(1-ϕ)^n, ϕ^n] d % Consecutive difference(s): gives ϕ^n - (1-ϕ)^n 5X^ % Push 5, square root / % Divide: gives (ϕ^n - (1-ϕ)^n) / sqrt(5) % Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ØpC,$*÷5½¤I ``` [Try it online!](https://tio.run/##y0rNyan8///wjAJnHRWtw9tND@09tMTz/@H2R01rtA2ObDR4uGOezpGuY11RbkARawelQ1vd///XNTTQUTDUUdA111Ew1lEw0DPVUTDVA7LMQSxdQzBpqWdgpqMAJC2BHCM9UxOQGktLkDYzPQNjoGoLPRNzIwA "Jelly – Try It Online") ~~Need to find where the 1 byte is :c~~ 1 byte found thanks to Unrelated String :D [Answer] # [Ruby](https://www.ruby-lang.org/), ~~39~~ 37 bytes ``` ->n{((-p=(1-s=5**0.5)/2)**-n-p**n)/s} ``` [Try it online!](https://tio.run/##XZAxb4QwDIX3/gokFkCKz3ZiJxnoWKlr14qlUm8rQnfqUFX97TQk0AKZHOvze36@fb59zdd@No/jd9OYqW/I3HvpOgRpL9x2nRnN1HVje7n/zHVVjdXxvbw3T2Oby@ePpXyYquurIRyWVl0gI/I3gBmgofzqrU0nwPjhAJA9AfaswCcgJRgOQGpoCJrWQbBCEjImYI@YgBd0kgeQA7uM@ZMaKQipasGIidbghduZMnmO2TQyuqJmIqAO/5h1YL0En7CkK@o0Y4mKezUrkFbLp0imSOKLGoO44WBqmXE5SFoHlbekMdIe8xBVmFc19GsEBbTpJhtmAmAQ9BkLzvpiGsB53qmxglWlkjSJic6/ "Ruby – Try It Online") With thanks to Dingus for a 1-byte improvement, and Att for a 1-byte improvement and a correction. Uses the fact that ϕ-1 = 1/ϕ [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 36 bytes ``` [ φ over ^ 1 φ - rot ^ - 5 √ / ] ``` [Try it online!](https://tio.run/##JYxBCsIwAATvvmI/kJg2TWv1AeLFi3gShRBTLLVJTVJBxKv4Bj/lH/xIjXqZ3WWXraQK1g3r1WI5n6LRzugjWhkOP9CqNyrU1vh/7E2t7F6jczqES@dqE@D1qddGaY/Z6AqSMCQgBTgYFRCUo4hKki9KynJElCApFVlsyzKOc8o4x4RmRYrbsMHrDnvWDrv4FD2BsyEGAoH344kxtkMrO/ggVUOHDw "Factor – Try It Online") ## Explanation: It's a quotation (anonymous function) that takes a number as input and leaves a number as output. Factor seamlessly promotes floats and rational numbers to complex numbers when necessary (denoted by `C{ real imaginary }`). Assuming `0.5` is on top of the data stack when this quotation is called... * `φ` Push phi, the golden ratio, to the data stack. **Stack:** `0.5 1.618033988749895` * `over` Put a copy of NOS (next on stack) at TOS (top of stack). **Stack:** `0.5 1.618033988749895 0.5` * `^` Raise NOS to the TOS power. **Stack:** `0.5 1.272019649514069` * `1` Push `1` to the data stack. **Stack:** `0.5 1.272019649514069 1` * `φ` Push phi to the data stack. **Stack:** `0.5 1.272019649514069 1 1.618033988749895` * `-` Subtract TOS from NOS. **Stack:** `0.5 1.272019649514069 -0.6180339887498949` * `rot` Take the data stack object third from the top and move it to TOS. **Stack:** `1.272019649514069 -0.6180339887498949 0.5` * `^` Raise NOS to the TOS power. **Stack:** `1.272019649514069 C{ 4.813788842079551e-17 0.7861513777574233 }` * `-` Subtract TOS from NOS. **Stack:** `C{ 1.272019649514069 -0.7861513777574233 }` * `5` Push `5` to the data stack. **Stack:** `C{ 1.272019649514069 -0.7861513777574233 } 5` * `√` Take the square root of TOS. **Stack:** `C{ 1.272019649514069 -0.7861513777574233 } 2.23606797749979` * `/` Divide NOS by TOS. **Stack:** `C{ 0.568864481005783 -0.3515775842541429 }` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 65 bytes ``` with(Math)f=x=>[(q=5**.5,q*=(++q/2)**x)/5-cos(x*=PI)/q,-sin(x)/q] ``` [Try it online!](https://tio.run/##jY5Ba4MwGIbv/oochCYao9amTiTdaYMdBrs7oanV6RBjNDhB/O0ubXXnfafne973g@@bD7zPuqpVTiOu@bL8VKqE71yVqGAjOyVQMmpZhGJpMWjb0t0jyxqRS51M9HC02McbciV2@qqBWst0UYCBxHB8D@jBBgD@Ck64mWADj9AHUBI8IFyN428QEe94jzREd7Mn9LBeRZF/M0fiBcHNPJFDuMdGGhuKFKJ74VkJB8BOYNJhnSuQcAwuqX6xgAOKV9nqnRMlXqsxv0KKSJe3Nc9y6H6SZ882XQx2u7@21O3Lv9qZaHpR56QWX/BsTu0MbGBOcq7OOp5RvPwC "JavaScript (Node.js) – Try It Online") * -1 byte by [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) * -1 byte by [att](https://codegolf.stackexchange.com/users/81203/att) Simply a translation of given formula $$ q = \sqrt5\cdot\left(\frac{\sqrt5+1}{2}\right)^x $$ $$ F\_x=\frac{q}{5}-\frac{\left(-1\right)^x}{q}=\left(\frac{q}{5}-\frac{\cos\left(\pi x\right)}{q}\right) + \left(-\frac{\sin\left(\pi x\right)}{q}\right)\cdot i $$ Nothing special here. I believe it is wrong language to use here. Use some languages with complex numbers support would be a better idea. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 24 bytes ``` ⭆¹ΣE∕X⊘⊕⟦₂⁵±₂⁵⟧N₂⁵⎇μ⁻⁰λλ ``` [Try it online!](https://tio.run/##VUy7DsIwDPyVjI4UUBk6sTLQoVVF2RCDaa0SKY/WJEV8fUjGnnS6h60b38ijR5NSz9oFGEKWucUFTkoM0UKxF73piaD3X2K4otlogsaNTJZcyP4xrBGZbt4HqKUSHc0YCHatfMp8adwSQxftKw@VvH9R4k7skH9glWi1ix@olDCysOCcUnWs02Ezfw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⁵ Literal `5` ₂ Square root ⁵ Literal `5` ₂ Square root ± Negated ⟦ ⟧ Make into list ⊕ Vectorised increment ⊘ Vectorised halved X Vectorised raised to power N Input as a number ∕ Vectorised divide by ⁵ Literal `5` ₂ Square root E ⎇μ⁻⁰λλ Negate the second element Σ Sum the elements ⭆¹ Stringify ``` The version of Charcoal on TIO doesn't really support complex numbers, but as it happens the `Power` of a negative number to a floating-point value will return a complex result; I just have to be careful not to use operations such as `Negate` and `Cast` where Charcoal will get confused as to which overload to use. 18 bytes using the newer version of Charcoal on ATO: ``` I↨∕X⊘⊕⟦±₂⁵₂⁵⟧N₂⁵±¹ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfbA4oy80o0nBOLSzScEotTNVwyyzJTUjUC8stTizQ8EnPKUlM0PPOSi1JzU_NKgOxov9T0xJJUjeDC0sSi1KD8_BINU01NHQUUfixIxDOvoLTErzQ3CWgQhgogH2qQoSYQWC8pTkouhjpqebSSblmOUuxiAz1TiAgA "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: The version of Charcoal on ATO can use "base -1" conversion to take the difference of a list of two complex numbers saving 5 bytes and also can directly cast a complex number to string saving a further 1 byte. (Note that the difference has the opposite sign to the TIO code so I've swapped the two list elements to compensate.) [Answer] # [J](http://jsoftware.com/), 25 bytes ``` %:@5%~[:-/(-:1+(,-)%:5)&^ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Va0cTFXroq109TV0rQy1NXR0NVWtTDXV4v5rcqUmZ@QrpCnEGxrAmIYwhoGeKYxpjmDGG@qZ/gcA "J – Try It Online") [Answer] # Java + Apache Commons Math, ~~138~~ ~~136~~ 134 bytes ``` n->{var a=Math.sqrt(5);return new org.apache.commons.math3.complex.Complex(.5-a/2).pow(n).negate().add(Math.pow(a/2+.5,n)).divide(a);} ``` *Saved 2 bytes thanks to [Original Original Original VI](https://codegolf.stackexchange.com/users/95792).* *Saved 2 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718).* [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~23~~ 22 [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. Complex results are returned as \$Re\$`J`\$Im\$. ``` -/s÷⍨(2÷⍨1(+,-)s←√5)*⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1e/@PD2R70rNIzAlKGGto6uZvGjtgmPOmaZamo96lr0Pw3E6@171NX8qHfNo94th9YbP2qb@KhvanCQM5AM8fAM/p@ma2igAARcaQoKhlCGrjlMxBjGMNAzhTBM9YwhDHOoiK4hjGGpZ2AGlgIyLMEiRnqmJlBdlpaGIBEzPQNjY5CIhZ6JuREA "APL (Dyalog Extended) – Try It Online") `(`…`)*⊢` raise the following value to the power of the argument:  `√5` square root of five: \$\sqrt5\$  `s←` store that as `s` and return the value: \$\sqrt5\$  `1(+,-)` that, added to and subtracted from one: \$1±\sqrt5\$  `2÷⍨` half of that: \$1±\sqrt5\over2\$ Now we have \$\left(\frac{1±\sqrt5}2\right)^n\$ `s÷⍨` divide that by `s`: \$\left(\frac{1±\sqrt5}2\right)^n\over\sqrt5\$ `-/` the difference between them: \${\left(\frac{1+\sqrt5}2\right)^n\over\sqrt5}-{\left(\frac{1-\sqrt5}2\right)^n\over\sqrt5}\$ [Answer] # Excel, 73 bytes ``` =LET(q,5^0.5*((5^0.5+1)/2)^A1,a,PI()*A1,IF({1,0},q/5-COS(a)/q,-SIN(a)/q)) ``` Using [tsh's formula](https://codegolf.stackexchange.com/a/223003/101349) [Answer] # MATLAB, 43 bytes [Try it online](https://tio.run/##lU/baoQwEH33K@Yx6eri5KKrIV9StrDY2AbcWKztQ3/eziTPCy1yJnPmXMB12m/f4TjmrzTtcU2Q/CTuskp@28JMm1v8Z/wJItUo3bxuED2OSxU8nu3pbJ9Eg/IljmpcXBKhHqUvz2kLH/fbLpKIxOolpLf9XQTJNSG9ZhyTeFZgoIOLgxYUwThAWiyYq6xIZqIdeSxYR8YHAkcbLMpfGvnAdX1BsWQUkwba6QBIBTSpTRnQCL3i2bWAA@fhwiIMNC30jqnJR0UODbr7T12bw9jRn5ACjRoeFiKZ@WsUx7DA5RMTdZXHLw) ``` p=.5+sqrt(5/4);F=@(n)(p^n-(1-p)^n)/sqrt(5); ``` F is an anonymous function that you plug n into. ]
[Question] [ ## Task Given a list of integers **L** and another integer **s**, the goal is to compute the column-wise sums of all **s**-length (potentially overlapping) slices of **L**, while pertaining their positions relative to **L** (see below). ## Definitions The **s**-length *(overlapping) slices* of the list **L** are all the contiguous subsequences (without wrapping) of **L** that are of length **s**. In order to *pertain the positions* of the slices **s** relative to **L**, you can imagine building a "ladder", where each slice **si** has an offset of **i** positions from the beginning. --- ## Specs * **s** is an integer higher than **1** and strictly smaller than the length of **L**. * **L** will always contain at least 3 elements. * You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins. ## Examples and Test Cases Here is a worked example: ``` [1, 2, 3, 4, 5, 6, 7, 8, 9], 3 [1, 2, 3] [2, 3, 4] [3, 4, 5] [4, 5, 6] [5, 6, 7] [6, 7, 8] [7, 8, 9] -------------------------------- (+) | column-wise summation [1, 4, 9, 12, 15, 18, 21, 16, 9] ``` And some more test cases: ``` [1, 3, 12, 100, 23], 4 -> [1, 6, 24, 200, 23] [3, -6, -9, 19, 2, 0], 2 -> [3, -12, -18, 38, 4, 0] [5, 6, 7, 8, 2, -4, 7], 3 -> [5, 12, 21, 24, 6, -8, 7] [1, 2, 3, 4, 5, 6, 7, 8, 9], 3 -> [1, 4, 9, 12, 15, 18, 21, 16, 9] [1, 1, 1, 1, 1, 1, 1], 6 -> [1, 2, 2, 2, 2, 2, 1] [1, 2, 3, 4, 5, 6, 7, 8, 9], 6 -> [1, 4, 9, 16, 20, 24, 21, 16, 9] ``` [Answer] # [J](http://jsoftware.com/), 11, 9 8 bytes -1 byte thanks to miles! ``` [:+//.]\ ``` ## How it works? The left argument is s, the right one - L `]\` - splits L into sublists with length s `/.` - extracts the oblique diagonals (anti-diagonals) `+/` - adds them up `[:` - makes a fork from the above verbs Here's an example J session for the first test case: ``` a =. 1 2 3 4 5 6 7 8 9 ] 3 ]\ a 1 2 3 2 3 4 3 4 5 4 5 6 5 6 7 6 7 8 7 8 9 ] </. 3 ]\ a ┌─┬───┬─────┬─────┬─────┬─────┬─────┬───┬─┐ │1│2 2│3 3 3│4 4 4│5 5 5│6 6 6│7 7 7│8 8│9│ └─┴───┴─────┴─────┴─────┴─────┴─────┴───┴─┘ ] +//. 3 ]\ a 1 4 9 12 15 18 21 16 9 ``` [Try it online!](https://tio.run/##XYwxCwIxDEb3@xUPl0P0em1zVltwEpycXFU6iIe43P@fatATioRAvveSvMrCtCP7RMsaS9LuDIfz6VguadX35nYty4bmcX9ODIw4BOdx1uJl5l65kAM54qJGy2xEzYbAlp3iPOhQGadM9OtvI35V@Kiqavx3Ud4 "J – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ 56 bytes ``` s#n=[x*minimum[n,i,length s+1-max i n]|(i,x)<-zip[1..]s] ``` [Try it online!](https://tio.run/##hZDNqsIwEIX3PsWAG39mpEm1tqC@gU8QsuhCNNiEYhWK@O51pg14e10YMpvJOd@czKVsrqeq6rpmGvamXXgXnH94E9BhdQrn@wWapSJftuAg2NfMYTvf0dPVRq1WtrGdL12APfiyPkJ9c@E@AWMUQoqgNFeSIOjUwhTWCPEQAR1AVBk/cl9HFXvZR9ylgr1cjEjErHHsFZnwSeU8i2stQvZveugWIe/NxP2tAFIc@TdDPK2GADIxF@Wkj6X7/Nz/Sysi5pOeBUX8pvDygacy0Q6g/1cQGX6tQY@v@hkjs98xZJdJ3OcnRvcG "Haskell – Try It Online") Defines a function `(#)` which takes a list `s` and and a number `n` as arguments. This is based on the observation that for `s = [1, 2, 3, 4, 5, 6, 7, 8, 9]` and `n = 3` ``` [1, 2, 3] [2, 3, 4] [3, 4, 5] [4, 5, 6] [5, 6, 7] [6, 7, 8] [7, 8, 9] ---------------------------- (+) [1, 4, 9,12,15,18,21,16, 9] ``` is the same as ``` [1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 3, 3, 3, 3, 2, 1] ---------------------------- (*) [1, 4, 9,12,15,18,21,16, 9] ``` To generate this initially increasing, then constant and finally decreasing list, we can start with ``` [minimum[i, length s + 1 - i] | i<-[1..length s]] ``` which yields `[1, 2, 3, 4, 5, 4, 3, 2, 1]`. Adding `n` as additional constraint into the `minimum` expression yields the correct list `[1, 2, 3, 3, 3, 3, 3, 2, 1]`answer for `n = 3`, though for `n = 6` (or in general any `n > lengths s/2`) the additional constraint `length s + 1 - n` is needed: ``` [minimum[i, n, length s + 1 - i, length s + 1 - n] | i<-[1..length s]] ``` or shorter: ``` [minimum[i, n, length s + 1 - max i n] | i<-[1..length s]] ``` For the pairwise multiplication `[1..length s]` is zipped with `s`, and because `zip` truncates the longer list to the length of the shorter one the infinite list `[1..]` can be used: ``` [x * minimum[i, n, length s + 1 - max i n] | (i,x)<-zip[1..]s] ``` [Answer] # JavaScript (ES6), ~~65~~ ~~62~~ 58 bytes *Saved 4 bytes thanks to @Shaggy* Takes input in currying syntax `(a)(n)`. ``` a=>n=>a.map((v,i)=>v*Math.min(++i,n,a.length+1-(n>i?n:i))) ``` ### Test cases ``` let f = a=>n=>a.map((v,i)=>v*Math.min(++i,n,a.length+1-(n>i?n:i))) console.log(JSON.stringify(f([1, 3, 12, 100, 23] )(4))) // [1, 6, 24, 200, 23] console.log(JSON.stringify(f([3, -6, -9, 19, 2, 0] )(2))) // [3, -12, -18, 38, 4, 0] console.log(JSON.stringify(f([5, 6, 7, 8, 2, -4, 7] )(3))) // [5, 12, 21, 24, 6, -8, 7] console.log(JSON.stringify(f([1, 2, 3, 4, 5, 6, 7, 8, 9])(3))) // [1, 4, 9, 12, 15, 18, 21, 16, 9] console.log(JSON.stringify(f([1, 1, 1, 1, 1, 1, 1] )(6))) // [1, 2, 2, 2, 2, 2, 1] console.log(JSON.stringify(f([1, 2, 3, 4, 5, 6, 7, 8, 9])(6))) // [1, 4, 9, 16, 20, 24, 21, 16, 9] ``` [Answer] # Java 8, 83 bytes ``` L->s->{for(int i=0,l=L.length+1,t,u;++i<l;u=l-(s>i?s:i),L[i-1]*=t<u?t:u)t=i<s?i:s;} ``` That first test case (and the last two I've added) screwed me over multiple times, but it finally works now.. :D Modifies the input array instead of returning a new one. **Explanation:** [Try it online.](https://tio.run/##zZDLSgMxFIb3PkWWM/YkzKW2tnMpIghCXXVZuojTtKammWFyUillnn1ML6KgdCNFSQgh@U@@72TFN5yWldCr@WtbKG4MeeJS764IMchRFmTlEsyiVGxhdYGy1OzhtEmlxukMforcl9rYtajTR41iKeo8JwXJSDumuaH5blHWnismMgtAZWOmhF7iSycEBJt0OjJVic0U9UwuR2YofRhPJQ1n1xmmdoRD62MmUzOSQ5M0beJk3azss3K@J@1NKedk7VrxJlhLvZzOCPf3bRFysCYoDDojLd6OB7sQYggjCIMAorhJDtGC8apSW28f9hkvClGh1/WPl5OtQbFmpUVWOQQq7X3@xF1d861hWB7xxxdOhYflGz8G2gM6gHAAEQTnBKLLCNxAD/pw6@i0C/1zAvFlBEKHjqELHyKDP3H4Ms7xe//gD37p0Fw17Ts) ``` L->s->{ // Method with int-array and int parameters, and no return-type for(int i=0, // Index-integer, starting at 0 l=L.length+1, // The length of the input-array + 1 t,u; // Two temp integers ++i<l // Loop `i` from 1 to the length (inclusive) ; // After every iteration: u=l // Set temp integer `u` to the length plus 1, -(s>i?s:i), // minus the highest of `s` and `i` L[i-1]*=t<u?t:u) // And replace the item with the lowest of `t` and `u` t=i<s?i:s;} // Set temp integer `t` to the lowest of `i` or `s` ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 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 charater set") -5 thanks to ngn. Anonymous tacit infix function taking **s** as left argument and **L** as right argument. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0` as is default on many systems. ``` +⌿∘↑((0,⊢)\,/) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wTtRz37H3XMeNQ2UUPDQOdR1yLNGB19zf//jRXSFB71TfUK9vdTUI821FEw0lEw1lEw0VEw1VEw01Ew11Gw0FGwjFXnMkFXCVRmCFRtaGAA1GUMVGGEogIorQs0QNcSqMQSbK4BUA2qfch2ABXoAq01x1CEx1EA "APL (Dyalog Unicode) – Try It Online") **Explanation with example case `[1,3,12,100,23]`** `(`…`)` apply the following anonymous tacit function:  `,/` overlapping windows of that size; `[[1,3,12],[3,12,100],[12,100,23]]`  `(`…`)\` cumulatively apply this tacit the following anonymous tacit function:   `⊢` the right(most) argument   `0,` with a zero on the left Cumulative reduction means that we insert the function into every "space" between successive terms, working our way from right to left. For each "space", the function will discard the left argument but append an additional zero. Effectively, this appends as many zeros to each term as there are "spaces" to its left, so the first term gets zero spaces, the second gets one, and the third gets two: `[[1,3,12],[0,3,12,100],[0,0,12,100,23]]` `↑` up the rank by combining the lists into a single matrix, padding with zeros;  `┌ ┐`  `│1 3 12 0 0│`  `│0 3 12 100 0│`  `│0 0 12 100 23│`  `└ ┘` `∘` then `+⌿` sum vertically; `[1,6,36,200,23]` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` )IŒIùvyNÅ0ì+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f0/PoJM/DO8sq/Q63Ghxeo/3/f7SpjoKZjoK5joKFjoKRjoKuCZATy2UMAA "05AB1E – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` YCPT&Xds ``` [Try it online!](https://tio.run/##y00syfn/P9I5QC0kIqX4//9oQx0FYx0FQyMgNjDQUTAyjuUyAQA) Or [verify all test cases](https://tio.run/##y00syfmf8D/SOUAtJCKl@L9LyP9oQx0FYx0FQyMgNjDQUTAyjuUy4YoGCumaAbElUBiIgbIGsVxGXNGmOgpAYXMdBQuwoK4JkBPLZcwFMsYIbBJQBFmRJUwWHcVymeHVZQYA). ### Explanation Consider inputs `[1, 3, 12, 100, 23]` and `4`. ``` YC % Implicit inputs: row vector L and number s. Create matrix of % overlapping blocks of L with length s, where each block is a column % STACK: [ 1 3; 3 12; 12 100; 100 23] P % Flip vertically % STACK: [100 23; 12 100; 3 12; 1 3] &TXd % Extract all diagonals, starting from bottom-left, and arrange them as % columns of a matrix, with zero padding % STACK: [1 3 12 100 0; 0 3 12 100 23] s % Sum of each column. Since s is less than the length of L, there are % at least two rows. Thus function `s` can be used instead of `Xs`. % Implicit display % STACK: [1 6 24 200 23] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` JṡṬS×ḷ ``` [Try it online!](https://tio.run/##y0rNyan8/9/r4c6FD3euCT48/eGO7f8PLzfSd///PzraUEfBWEfB0AiIDQx0FIyMY3UUTHS4FKKBorpmQGwJlAFioAKDWBAFlDIEc41BChVMdRSAqsx1FCx0FCxjQaIQBegoFqSOgF6gglgA "Jelly – Try It Online") ### How it works ``` JṡṬS×ḷ Main link. Left argument: A (array). Right argument: n (integer) J Indices; yield [1, ..., len(A)]. ṡ Split the indices into overlapping slices of length n. Ṭ Untruth; map each array of indices to a Boolean vector, with 1's at the specified indices and 0's elsewhere. For example, [3, 4, 5] maps to [0, 0, 1, 1, 1]. S Sum the rows, essentially counting how many times each index appears in the arrays returned by the ṡ atom. ḷ Left; yield A. × Multiply the counts to the left with the integers to the right. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 bytes It took far too long to get this working when `s` > `L/2`! ``` Ë*°EmVUÊÄ-EwV ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=yyqwRW1WVcrELUV3Vg==&input=WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDldLCA2) --- ## Explanation ``` :Implicit input of array U and integer V Ë :Map over each element at 0-based index E in U * : Multiply by m : The minumum of °E : E incremented, V : V, EwV : and the maximum of E & V - : subtracted from UÊÄ : the length of U plus 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` mΣ∂X ``` [Try it online!](https://tio.run/##yygtzv7/P/fc4kcdTRH///83@x9tqGOkY6xjomOqY6ZjrmOhYxkLAA "Husk – Try It Online") Uses the idea from [Galen Ivanov's J answer](https://codegolf.stackexchange.com/a/154573/56433). ### Explanation ``` -- implicit input number n and list s, e.g. s = [1,2,3,4,5,6] and n = 4 X -- get sublists of length n of list s [[1,2,3,4],[2,3,4,5],[3,4,5,6]] ∂ -- anti-diagonals [[1],[2,2],[3,3,3],[4,4,4],[5,5],[6]] mΣ -- get the sum of each of the lists [1,4,9,12,10,6] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` Min[i,#2,l+1-{i,#2}]~Table~{i,l=Tr[1^#]}#& ``` [Try it online!](https://tio.run/##jYyxCoNADIZ3nyJ44NIceGptHSy@QKGD22HhWpQK6iBucr769Vcc2k6F/JDk@5LeTK@6N1P7NK6hnNy1HXTLIuLuoOS8drZaSvPo6gVTl5ejVndRWRG429gOkxaKyd8KR@STvKx9o4WoKgqoKAqP5nmGFTMpKCoMmaLYMiWWPQIEkCmSASJwQtBop0cmwBPTeUMywQAc71htW7zA/lPNvp3fAk3/@JBa694 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Julia](http://julialang.org/), 41 bytes ``` a\n=(a[L=end];a.*min(1:L,L:-1:1,n,L-n+1)) ``` [Try it online!](https://tio.run/##jZE/b8IwEMV3PsXBlFAb5Zw/JEGRqs4ZOnQDD5aIqlTUqurw@cOdE0PKVMvn5b338539db30Jh9Hc7JNZI5t09mzPpjd9ru3EdataGuJNQorWmlfMI7Hq@vtJ7wZ1@0@OjesXgc64YgCUgGoqJJEgEo1hHWCDJrGWwpSMqrZEsKUlCTJitJUBEn0Pax8mC1Ml1jSTVQZmwIg9@i9gNKnJYl7HQCpB@RTdwqnFvi6kl2LAZSfgcQlrtJ3BHqxmsdkYDkBsWDfgvS8H9MUgaT@bvxfI8VTI/ygyfyoj0Z@fns7XGy04R9y8G6c687rTbwabw "Julia 0.5 – Try It Online") * Redefine `\` operator. * `a[L=end]` is a shorter alternative to `L=length(a)`. * Uses [Laikoni's method](https://codegolf.stackexchange.com/a/154564/76880). [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~13~~ 12 bytes *-1 byte thanks to @ETHproductions* ``` ãV ËEÆÃcDÃyx ``` [Try it online!](https://tio.run/##y0osKPn///DiMK7D3a6H2w43J7scbq6s@P8/2lBHwUhHwVhHwURHwVRHwUxHwVxHwUJHwTIWyAEA "Japt – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~52~~ 51 bytes ``` function(l,s)l*pmin(s,x<-seq(l),y<-rev(x),y[1]+1-s) ``` [Try it online!](https://tio.run/##TYxNCsIwFIT3nsJlns6D/NTUSG4irkoDhRi1Uamnjwl1ITOL4Rtm5hK2nkt4peE53ZKIyBR39@uURMbiOY8PEQkfz/P4FktNZ3XZK85UghiEgoaqlhLaEDraNGrAFuygXK0lQa/4AIsex8q4Q08wDauTW0M7@9Nv1WpL5Qs "R – Try It Online") This is equivalent to [Laikoni's answer](https://codegolf.stackexchange.com/a/154564/67312). `seq(l)` produces the indices `1...length(l)` since `length(l)>1` (otherwise it would produce `1...l[1]`). I save it as `x`, save its reverse as `y`, and take the first element of `y` (`length(l)`) to neatly port Laikoni's answer and save a byte! ### Original answer, 52 bytes ``` function(l,s,L=sum(l|1)+1)l*pmin(s,x<-2:L-1,L-x,L-s) ``` [Try it online!](https://tio.run/##TYxBCsIwEEX3nsJlRv9AJ6mpLfUGuUUhUEijmBa68O4xoS5k/sDnPWbe2Z9Hzn6L0zo/owpIcI@0LSp8hK5C4fJa5qgS9pH14FjgeC@bKHs1KYGGlDQNtCG0dKrUgC24h/RFNwR94BssOtwL4xYdwVQsQ3@U@uxvfldVW8pf "R – Try It Online") The output is `l` elementwise multiplied by the minimum of `s`, the 1-based index of the element `x`, `length(l)-x+1`, and `length(L)-s+1`. This is also equivalent to Laikoni's answer, using `L-x` instead of `rev(x)` as it's shorter. [Answer] # APL+WIN, 25 bytes Prompts for screen input of L followed by s ``` +/(1-⍳⍴z)⌽¨(⍴L)↑¨s←⎕,/L←⎕ ``` Explanation: ``` L←⎕ prompt for screen input of L s←⎕,/ prompt for screen input of s and create nested vector of successive s elements of L (⍴L)↑¨ pad each element of the nested vector with zeros to the length of L (1-⍳⍴z)⌽¨ incrementally rotate each element of the nested vector +/ sum the elements of the nested vector ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 30 bytes **Solution:** ``` {+/t,'(y':x),'|t:(!1-y-#x)#'0} ``` [Try it online!](https://tio.run/##y9bNz/7/v1pbv0RHXaNS3apCU0e9psRKQ9FQt1JXuUJTWd2gNtpQwUjBWMFEwVTBTMFcwULB0to49v9/AA "K (oK) – Try It Online") **Example:** ``` {+/t,'(y':x),'|t:(!1-y-#x)#'0}[3 -6 -9 19 2 0;2] 3 -12 -18 38 4 0 ``` **Explanation:** Don't think I can compete with **J** on this one. Generate a list of zeros to be appended and prepended to the sliding-window list, then sum up: ``` { t,'(y':x),'|t:(!(#x)+1-y)#'0 }[1 2 3 4 5 6 7 8 9;3] (1 2 3 0 0 0 0 0 0 0 2 3 4 0 0 0 0 0 0 0 3 4 5 0 0 0 0 0 0 0 4 5 6 0 0 0 0 0 0 0 5 6 7 0 0 0 0 0 0 0 6 7 8 0 0 0 0 0 0 0 7 8 9) ``` Breakdown is as follows... though this still feels clumsy. ``` {+/t,'(y':x),'|t:(!1-y-#x)#'0} / the solution { } / lambda taking x and y implicitly #'0 / take (#) each (') zero ( ) / do this together #x / count (#) length of x y- / take count away from length y 1- / take that result from 1 ! / til, generate range to that number t: / save in variable t | / reverse it ,' / join with each (y':x) / sliding window size y over x ,' / join with each t / prepend t +/ / sum up ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->a,l{a.map.with_index{|x,i|x*[i+1,l,a.size-[l-1,i].max].min}} ``` [Try it online!](https://tio.run/##jc5NDoIwEAXgtZxilv5MG4oKstCLNI2pUqVJRYMaQeDsODFi0BVN08X063vN77uyPaxbttHoKs1P@sIf9pZubZaYoqoLtHUxlXYm0KHmV/s0TDom0CqyBR02a5pWegBSCoQAYY6wQFgihAgRwgohVjRV2BkCgpzwffI0h24tPoYAo8csJhS/M/2vCj6mn0@AUWXUoV7XkP/8729XOCAnVIobvU8hOUOt81yXCM5kx1tae97oAge@186Nf24mnsmS9gU "Ruby – Try It Online") Essentially a port of [Arnauld's javascript answer](https://codegolf.stackexchange.com/a/154556/77973), except that needing `with_index` is a lot more painful. In the time it took for me to decide to actually submit this, I golfed down from this 70-byte version, which is closer to [Dennis's algorithm](https://codegolf.stackexchange.com/a/154581/77973). ``` ->a,l{c=a.map{0};(0...a.size).each_cons(l){|h|h.map{|i|c[i]+=a[i]}};c} ``` [Answer] # [Uiua](https://uiua.org), 14 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⬚0/+⊐≡(⊂⊚)⇡⧻.◫ ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAg4qyaMC8r4oqQ4omhKOKKguKKminih6Hip7su4perCgpmNFsxIDMgMTIgMTAwIDIzXSAgICAgICAjICAgICAgLT4gWzEsIDYsIDI0LCAyMDAsIDIzXQpmMlszIMKvNiDCrzkgMTkgMiAwXSAgICAgICMgICAgICAtPiBbMywgLTEyLCAtMTgsIDM4LCA0LCAwXQpmM1s1IDYgNyA4IDIgwq80IDddICAgICAgIyAgICAgIC0-IFs1LCAxMiwgMjEsIDI0LCA2LCAtOCwgN10KZjNbMSAyIDMgNCA1IDYgNyA4IDldICAgIyAtPiBbMSwgNCwgOSwgMTIsIDE1LCAxOCwgMjEsIDE2LCA5XQpmIDYgWzEgMSAxIDEgMSAxIDFdICAgICAjICAgICAtPiBbMSwgMiwgMiwgMiwgMiwgMiwgMV0KZiA2IFsxIDIgMyA0IDUgNiA3IDggOV0gIyAtPiBbMSwgNCwgOSwgMTYsIDIwLCAyNCwgMjEsIDE2LCA5XQo=) ``` ⬚0/+⊐≡(⊂⊚)⇡⧻.◫ ◫ # windows ⇡⧻. # range of length ⊐≡( ) # apply function to each row of both arrays, boxing as required ⊚ # where (n zeros) ⊂ # join ⬚0/+ # sum columns, filling missing elements with zero ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~68~~ 66 bytes -2 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) ``` lambda l,n:[v*min(n,i+1,len(l)-max(i,n-1))for i,v in enumerate(l)] ``` [Try it online!](https://tio.run/##hdDBCoMwDAbg@54ix3ZLwarTKexJnIeOVVZoo4iT7em76C6yi9BTvj9/IcNnevaUxu56i96E@8OAR6qb@RgcCUJ30ugtCS9VMG/hkJSWsutHcDiDI7D0CnY0k@VIGxfwCLSIaDRCipAh5AhnhAKhRLggVC1PJf4SzJpTOkk4nbHkq/BY8YKqmKq1J2FLV9t2MSiuL7eV@5/@P7Zid7uQ9QFgGB1N0Ak@k4xf "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 63 bytes ``` $b=<>;map{say$_*=$n+$b>@F?$n-$b<0?$i:--$i:$i<$b?++$i:$i;++$n}@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18lydbGzjo3saC6OLFSJV7LViVPWyXJzsHNXiVPVyXJxsBeJdNKVxdIqGTaqCTZa2uDmdZAOq/Wwe3/f0MdBWMdBUMjIDYw0FEwMuYy@ZdfUJKZn1f8X9fXVM/A0OC/biIA "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~83~~ ~~81~~ 79 bytes There are basically three "phases" to the manipulation of the list: ramp-up, sustain, and cool-off. As we go along the list, we will increase our factor until we reached some maximum. If a full run of slices can fit into the list, this maximum will be the same as the length of the slices. Otherwise, it will be the same as the number of slices that fit. At the other end, we will decrease the factor again, to land at 1 on the last element. The length of the ramp-up and cool-down phases that bookend this plateau is one less than that maximum factor. The ungolfed loops before combining them hopefully makes it clearer (R = length of ramp-up phase): ``` for (r = 1; r <= R; r++) L[r - 1] *= r; for (; r < n - R; r++) L[r - 1] *= R + 1; for (; r < n; r++) L[r - 1] *= n - r + 1; ``` Three loops is much too much, so deciding the factor based on r gives us the one loop (using s for R to save some bytes): ``` r;f(L,n,s)int*L;{for(r=0,s=2*s-1>n?n-s:s-1;r++<n;)*L++*=r>s?r<n-s?s+1:n-r+1:r;} ``` [Try it online!](https://tio.run/##nY9LbsIwEIbX9ilGkSo5fkh5AQUTcoHcALGAhERZ4FY2XaGcPR2bpK26qVTJ47H9f//MuFF900yT1R2rpZEuHsyd1/rRvVlmy0S6MuNOpQdTGeV2eNJWiL3RMa@F4KU9uMruUaqcSHdGWdytHqeeYR3gtQSfzTO5mD4owcoQ1AFKSDSmPRhMQsSUkHeLUseil7yFSEJ9HE6xpoR@C9yBOngtX4MCAxwKCVH0pPwvfDs3X//Z6@PuWCg5Uurtt/NgWJje387HU/lIcQAJaYaRJBKyfNRACOnZWcJKQuErefjiYSTVGmOLNAaakgW/SEAlW/DG46vwtpHwGliFH9wEvmdNeM8XvJ1HycI0RWj9Zd2OGh0tHn44rrPj90KWAOLX4F4vePdHA2/pQgdvGadP "C (gcc) – Try It Online") [Answer] # Perl, ~~45~~ 44 bytes Includes +4 for `-ai` Also notice that this code gives 2 perl warnings on startup. You can suppress these at the cost of one stroke by adding the `X` option Give the mask length after the `-i` option and the array on one line on STDIN: ``` perl -ai4 -E 'say$_*grep$_~~[$^I..@F],$a..$^I+$a++for@F' <<< "1 3 12 100 23" ``` Just the code: ``` say$_*grep$_~~[$^I..@F],$a..$^I+$a++for@F ``` [Answer] ## Clojure, 72 bytes ``` #(let[R(range 1(inc(count %)))](map *(map min(repeat %2)R(reverse R))%)) ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 106 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` ĐŁĐ←⇹řĐ↔Đ04ȘĐ04Ș>Đ04Ș03Ș¬*07ȘážÁ*+04Ș⇹Đ3ȘĐ3Ș-⁺Đ4Ș⇹ŕĐ3Ș<Ь3Ș*3Ș*+⇹ĐŁ⑴04Ș3Ș⇹04Ș*Đ04ȘĐ04Ș<Đ04Ș*06ȘážÁ03Ș¬*++* ``` Takes L on the first line as an array, and takes s on the second line Explanation: ``` Implicit input (L) Đ Duplicate L ŁĐ Get length of L (len) and push it twice ← Get s ⇹ř Push [1,2,...,len] Đ↔Đ Push [len,...,2,1] twice 04ȘĐ Push 0, flip top 4 on stack, and duplicate top [1,2,...,len] 04Ș> Is [len,...,2,1]>[1,2,...,len] (element-wise) [boolean array] Đ Duplicate top of stack 04Ș03Ș¬* Pushes [1,2,...,ceil(len/2),0,...,0] 07ȘážÁ Push 0, flip top seven on stack, and remove all 0s from stack * Pushes [0,0,...,0,floor(len/2),floor(len/2)-1,...,1] + Adds top two on stack element-wise The top of the stack is now: [1,2,...,ceil(len/2),floor(len/2),...,2,1] (let's call it z) 04Ș Push zero and swap top four on stack ⇹ Swap top two on stack Đ3ȘĐ3Ș-⁺Đ4Ș⇹ŕĐ3Ș<Ь3Ș*3Ș*+ Pushes min of (len-s+1,s) [let's call it m] ⇹ĐŁ⑴04Ș3Ș⇹04Ș* Pushes an array [m,m,...,m] with length len Đ04ȘĐ04Ș<Đ04Ș*06ȘážÁ03Ș¬*++ Pushes element-wise min of [m,m,...,m] and z * Element-wise multiplication of above with L ``` [Try it online!](https://tio.run/##K6gs@f//yISjjUcmPGqb8Kh959GZINaUIxMMTE7MgJB2EMrA@MSMQ2u0DMxPzDi88Oi@w41a2iBhoJ4jE4xBaoGE7qPGXUcmQESPTgUL2RyZcGgNkNYCYW2w6qONjyZuAek1BisEsbSQLbSBUFoGZjCroHZra2v9/x9tqGOkY6xjomOqY6ZjrmOhYxnLZQwA) [Answer] # Python + numpy, 64 bytes ``` from pylab import * lambda l,N:convolve(*ones((2,len(l)-N-1)))*l ``` Call this with l as the list, and N as the length. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~100~~ 89 bytes, using `-lm` * Saved eleven bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` j;f(L,l,s)int*L;{for(j=l;j--;L[j]*=j<s&j<l-s?1+j:j>s&j>l-s?l-j:fmin(s<l-j?s:l-j,l+1-s));} ``` [Try it online!](https://tio.run/##jdBRb4IwEAfw5/kpGpYtINeEtlCntfoFeNi78cGgGJrTGeuejF997KqMqE8jlOQP3O96rfi2qtrWmTouAcEnzf40LM25/jrGzqJxnJty4ZZD66b@3U2R@7lI3cTNKM1CQu4m9a7Zx54@urmf0BMwFdwnibm0r@tN3ew37LPz//qY0IGascZmppmiadI0ORzpTR1Hb2tgEZSLZpmYw/fJx1GUmMFuRV2S8@AllJVisbRnAUwBE5JWlgGTinXXxYSfUNgCvLC5Cf0FoKBE0k2QQaByrmmNiaBFUvYgSKvBSysNARJQUugBFYACGNWPgH1cq3lO4R5QdgReWRUABago9EDezSCvY1DlPTbugNyOwec3IAfMKfRA0QHP98MIRdhBYXUACkA6kaIH9H92oMMO9A3QgHQgmoBL@1PVuNr6luPuFw "C (gcc) – Try It Online") ]
[Question] [ The dealer has been sloppy and lost track of what cards his/her deck contains and what cards are missing, can you help him/her? --- A complete deck consists of 52 playing cards, namely: Each color in the deck (hearts, diamonds, spades, clubs) contains: * The numbers [2 - 10] * A Jack * A Queen * A King * An Ace --- **Task** Your program will read the contents of the deck from STDIN until a newline is read. You can assume that the input will be in the form of "nX nX nX nX" etc. where: * n - any number between [2 - 10] **or** either 'J', 'Q', 'K' or 'A'. (You can assume upper case only for non-numeric characters) * X - any of the following : 'H', 'D', 'S', 'C' (You can assume upper case only) Where: * 'J' = Jacks * 'Q' = Queen * 'K' = King * 'A' = Ace And * 'H' = Hearts * 'D' = Diamonds * 'S' = Spades * 'C' = Clubs You can assume that there will be no duplicates in the input. Your program must then print the missing cards in the deck to STDOUT in the same fashion as the input ("nX nX nX") or print 'No missing cards' if all 52 cards are supplied. There is no constraint on the order of the output of the cards. Example input: ``` 9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S ``` Output: ``` 3H 4H 5H 6H 7H 10H JH QH KH 2D 3D 5D 6D 8D 9D 10D QD 2S 4S 5S 7S 8S 9S QS KS 3C 4C 5C 6C 10C JC QC HC ``` Happy golfing! [Answer] ## Windows Batch (CMD), ~~205~~ 204 bytes ``` @set/pc= @set d= @for %%s in (H D S C)do @for %%r in (2 3 4 5 6 7 8 9 10 J Q K A)do @call set d=%%d%% %%r%%s @for %%c in (%c%)do @call set d=%%d: %%c=%% @if "%d%"=="" set d= No missing cards @echo%d% ``` Loops over the suits and ranks building a complete deck, then deletes the input cards. Save 1 byte if `T` is allowed instead of `10`. Save 11 bytes if command-line arguments are acceptable input. Edit: Saved 1 byte thanks to @user202729. [Answer] # Python, ~~147~~ ~~146~~ ~~145~~ ~~138~~ ~~131~~ ~~129~~ ~~127~~ ~~125~~ 120 bytes ``` print(' '.join(set(`x`+y for x in range(2,11)+list('JQKA')for y in'HDSC')-set(raw_input().split()))or'No missing cards') ``` Gets all possible cards as a set and subtracts the input cards. -1 byte thanks to mbomb007 pointing out an extra space in my code. -1 byte thanks to mbomb007 for pointing out some golfing that can be done with Python 2 (-5 bytes and +4 bytes for `raw_` in `raw_input`) -7 bytes by switching to using sets and set subtraction instead of list comprehensions -7 bytes thanks to ValueInk for pointing out that I don't need to `list` the suites -2 bytes thanks to Datastream for pointing out that just writing out all of the values is more byte-effective than the weird thing I had earlier -2 bytes thanks to ValueInk for pointing out that sets can take generators so I don't need to put it in a list comprehension -2 bytes thanks to Datastream for pointing out that I can golf it down even more if I switch to Python 3 again... (+2 for parens after for print, -4 for `raw_`) -5 bytes thanks to Lulhum and myself for pointing out that by switching back to Python 2 (!!!) can help me save bytes (using range again, using backticks instead of `str(`, and +4 due to `raw_`) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 39 bytes ``` ðIð¡YTŸ"JQKA"S«"CDHS"SâJsKðýDg>i“Noœ¶‡¶ ``` [Try it online!](https://tio.run/nexus/05ab1e#DY49asNQEISv8qETJPqxpCYgdovNexB4bJqcIKRKkQv4DmnTOG0aVcaNGz18EV9EWfhmi2WYmb2uz3XdTm@vt0uTSl4a3/4aUfPG62/6ynWtV31/@rgff14@b9/b@X48bed9n43FGIXOORiPD05WkjMLrTEFwhI4izIqvdIKSTl4uCWkIaONv9NFkNIZvdDHdQZhUAYjBUJRilGcImQjR10YojsChTGmOJMyxQBl9n8 "05AB1E – TIO Nexus") **Explanation** ``` ðI # push space and input ð¡ # split on spaces YTŸ # push the range [2 ... 10] "JQKA"S« # append ['J','Q','K','A'] "CDHS"Sâ # cartesian product with suits J # join each card with its suit sK # remove any cards in input from the list of all cards ðýDg>i # if the length of the resulting list is 0 “Noœ¶‡¶ # push the string "No missing cards" # output top of stack ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~49~~ 47 bytes ``` B,2>"JQKA"+"HDSC"m*:slS/-S*"No missing cards"e| ``` [Try it online!](https://tio.run/nexus/cjam#DcJBCsIwEEDRq3xmWRU1irUuhDizCCkIMicQFSlYBbP17rGPV0/zcJR86aPMJJmrjM2hvHy58EbOH8ahlOH95Hb93os8frV2iZholY2zXjm9kZ1OCYn9VIlTJxqtsTWCko2d/wE "CJam – TIO Nexus") **Explanation** ``` B, e# The range from 0 to 10 2> e# Slice after the first two elements, giving the range from 2 to 10 "JQKA"+ e# Concatenate with "JQKA", giving the array containing all ranks "HDSC" e# The string containing all suits m* e# Take the Cartesian product :s e# And cast each pair to a string. Now a full deck has been constructed l e# Read a line of input S/ e# Split it on spaces - e# Remove all cards from the deck that were in the input S* e# Join the result with spaces "No missing cards" e# Push the string "No missing cards" e| e# Take the logical OR of the result and the string, returning the e# first truthy value between the two. (empty arrays are falsy) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 9R‘Ṿ€;“JQKA”p“CDHS”F€œ-ɠḲ¤Kȯ“¡¢ıḍĖ9ṭƥw» ``` **[Try it online!](https://tio.run/nexus/jelly#FY29agJxEMR7n2JeQFDvm1THLrLcvzr3RdKlPdKnCoQUEVS0U0KsFMHi0JA8xt2LXCbN7uwMv9mhWPTNe3e@9s/7h775qOpQ9s3ykVLUnHLO5P46/l11p2O7DT@fjNp1u7l9daeX21vRnQ/fu6f2MgyJYiYoBLkhp@BpqBWRYjpxZILYEAQRM0cqSAwzR23IDKUgdQRHRUxR0xdUhsgICzICioSWI1bETpdLEAwVUUNC@v8RfzsKdipKR87JEkepoz8)** ### How? ``` 9R‘Ṿ€;“JQKA”p“CDHS”F€œ-ɠḲ¤Kȯ“¡¢ıḍĖ9ṭƥw» - Main link: no arguments 9R - range(1,9) [1,2,3,4,5,6,7,8,9] ‘ - increment [2,3,4,5,6,7,8,9,10] Ṿ€ - uneval each [['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10']] ;“JQKA” - concatenate with char-list "JQKA" [['2'],['3'],['4'],['5'],['6'],['7'],['8'],['9'],['10'],['J'],['Q'],['K'],['A']] p“CDHS” - Cartesian product with char-list "CDHS" [[['2'],['C']],[['2'],['D']],...] F€ - flatten each [['2','C'],['2','S'],...] ¤ - nilad followed by link(s) as a nilad ɠ - read a line from STDIN Ḳ - split on spaces œ- - multi-set difference K - join with spaces “¡¢ıḍĖ9ṭƥw» - compressed string "No missing cards" ȯ - logical or - implicit print ``` [Answer] # C#, 343 bytes First time posting one of my golfs, not a very good contender though. I'm sure I can reduce this more. The idea behind it is a sparse array storing occurrences of cards, with indexes calculated by the ASCII values of the different values and suits multiplied against each other (e.g. an ace of spades (AS) would be stored in the area at index (65 \* 83 = 5395)). This way, each type of card gets a unique index that can be checked later for existance in the "map" array. ``` void M(string[]a){var c=new int[] {50,51,52,53,54,55,56,57,49,74,81,75,65,72,68,83,67};var e=new int[9999];int i=0;int j=0;foreach(var s in a) e[s[0]*s[s.Length- 1]]++;int f=0;for(i=0;i<13;i++)for(j=13;j<17;j++)if(e[c[i]*c[j]]==0) {f=1;Console.Write(((i<9)?(i+2)+"":(char)c[i]+"")+(char)c[j]+" ");}if(f==0) Console.WriteLine("No missing cards");} ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~114~~ ~~111~~ 110 bytes ``` param($n)('No missing cards',($a=(2..10+'JQKA'[0..3]|%{$i=$_;"CSHD"[0..3]|%{"$i$_"}}|?{$n-notmatch$_})))[!!$a] ``` [Try it online!](https://tio.run/nexus/powershell#PcjNaoNQEAbQ/fcUidxylbaSXv8pocjMYlAoyCxDkEsKiQtNidklPrvd9SzP@utvfgzNFIX2@7oZh3kepvPm5G8/s30Ljd@HLo4/dq@26draHnZxnByfLw8z7E3/GZAKB/8ZmMH0wbI8vx5mep@u99HfTxfTL1EUHbZb44/rulpHcAoncIyEkCgSQcJICakiFaSMjJApMkHGyAm5IhfkjIJQKApBwSgJpaIUlIyKUCkqQcVoCI2iETSMjtApOkHHaAmtohW0jJpQK2pBzfYP "PowerShell – TIO Nexus") Takes input `$n` as either a space-delimited or newline-delimited string. Constructs an array from the range `2..10` concatenated with `JQKA` (indexed with `[0..3]` to make it a `char` array). That array is fed into a loop `|%{}` that sets helper `$i` then loops over the suits to concatenate the results together with `$i$_`. At the end of this loop, we have an array of strings like `("2C", "2S", "2H", ... "AH", "AD")`. That array is fed into a `Where-Object` (`|?{}`) with the filter as those elements `$_` that regex `-notmatch` the input `$n`. The result of that filtering is stored into `$a`. Then, we use a pseudo-ternary `( , )[]` to select whether we output `'No missing cards'` or `$a`, based on whether `!!$a` turns to a Boolean `$false` or `$true`. If `$a` is empty (meaning every card in the deck is in the input), then `!!$a` is `0`, so the `"No missing cards"` is selected. Vice versa for `$a` being selected. In either case, that's left on the pipeline, and output is implicit. [Answer] # Bash + coreutils, 89 ``` sort|comm -3 <(printf %s\\n {10,{2..9},A,J,K,Q}{C,D,H,S}) -|grep .||echo No missing cards ``` I/O as a newline-delimited list. ### Explanation * `sort` reads newline-delimited input from STDIN and sorts it * This is piped to `comm` * `printf %s\\n {10,{2..9},A,J,K,Q}{C,D,H,S}` is a brace-expansion to generate the full deck of cards. The `printf` prints each card on its own line. The order is given such that the output is the same as if it had been piped to `sort` * `comm` compares the full deck against the sorted input and outputs the difference. `-3` suppresses output of column 3 (the common ones) * The whole output from `comm` is piped to `grep .`. If there was no output from `comm` (i.e. all cards were in the input), then the `||` "or" clause outputs the required message. Otherwise the `grep .` matches all lines output from `comm`. [Try it online](https://tio.run/nexus/bash#DcK9CoMwFAbQ/XuKuxRauIo/pVboEpIhKBRKVpdirXXQSOJmfHbr4ezeuiW0dhwpyulxnt0wLV86@aaZaE0TXrM4LjcWXHHNr22VrFiz2S4Uhd51M8UhdO3P0tPSOHg/TD21b/fx@15qCI1CIjdIE4NaoTIoJTKN@1FCHA2EQqFwVcgkKoWb@QM). [Answer] # [Python 2](https://docs.python.org/2/),~~104,93,130~~,114 bytes ``` r=input() print' '.join(n+x for n in list('23456789JQKA')+['10']for x in'HDSC'if n+x not in r)or'No missing cards' ``` [Try it online!](https://tio.run/nexus/python2#FY67asQwFET7fMXpZLMk7PrtIoWRiosNAaMypFi82UQhkRbbgf3x1I4Mc2GKM3dmm5@dv/2uSfpwm51fFerpKzif@MOda5jxOM@3W9ZEZXlRVnXT9uPQqfTwqk5H9bYz98goMVYrd2UP@rDusTkNs3oJ/Lhlcf6D6TxfFrVtqhU6odbkltPRMhh6S6vJhCZK00VZOkNtKAyZpjdUlix6Sy7khlxTCIWl0JRCaSgtpaYSqghr6thhaQxNfG5oLb3Qa0ZhNIyWUTMIQxyg4w6JZ9SfD4/Tefp8/wc "Python 2 – TIO Nexus") * -10 bytes with hardcoding the list instead of using range! * +37 bytes - missed printing 'No missing cards' if all cards are present in input! * -16 bytes by modifying the code into a list comprehension! [Answer] # Ruby, 108 + 1 = 109 bytes Uses the `-p` flag. ``` a=[*?2..'10',?J,?Q,?K,?A].map{|i|%w"H D S C".map{|c|i+c}}.flatten-$_.split;$_=a==[]?"No missing cards":a*' ' ``` [Answer] # PHP, 143 Bytes ``` foreach([H,D,S,C]as$c)foreach([2,3,4,5,6,7,8,9,10,J,Q,K,A]as$v)$r[]=$v.$c;echo join(" ",array_diff($r,explode(" ",$argn)))?:"No missing cards"; ``` [Answer] # [sed](https://www.gnu.org/software/sed/), 157 + 1 (`-r` flag) = ~~170~~ 158 bytes ``` x s/$/;A2345678910JQK/ s/.+/&H&D&S&C;No missing cards/ : s/(10|\w)(\w+)(.);/\1\3 \2\3;/ t G :s s/(10.|[^ ;1]{2})(.*\n.*)\1/\2/ ts s/[ ;]+/ /g s/^ // s/ N.+// ``` [Try it online!](https://tio.run/nexus/sed#Jc1Bi8IwFATge37FHJbSWuxrUrXWnEoCWyoIkqNPQRSkh20XI7iw@tftRhbmMAwfzPgjPH2QrlUxmy/KZSXzdrumMGYpRU1kIxcZvRnw1Xnf9RecjtezJ7EKIpb5g@9JzPc0ibNEE0suwIoLTeImPsXK/6vssTtAy/2vegY44T6bJCyJVWBvsoPepwS6hH4Avd@xCf80jlWDukFpUDjI3GFt0TpUBqrBMsSgDnGoLUqLmYUyaC0W7jV837qh9@P0@gc "sed – TIO Nexus") This generates all possible cards and then remove each card in the input from the generated cards. [Answer] ## [C#](http://csharppad.com/gist/0018fae00fc41bff1ac6681e4e5b2412), 282 bytes --- **Golfed** ``` i=>{var o=new System.Collections.Generic.List<string>();string[] S={"H","D","S","C"},N="A 2 3 4 5 6 7 8 9 10 J Q K".Split(' ');foreach(var s in S){foreach(var n in N){if(!System.Linq.Enumerable.Contains(i,n+s)){o.Add(n+s);}}}return o.Count>0?string.Join(" ",o):"No missing cards";}; ``` --- **Ungolfed** ``` i => { var o = new System.Collections.Generic.List<string>(); string[] S = { "H", "D", "S", "C" }, N = "A 2 3 4 5 6 7 8 9 10 J Q K".Split(' '); foreach( var s in S ) { foreach( var n in N ) { if( !System.Linq.Enumerable.Contains( i, n + s ) ) { o.Add( n + s ); } } } return o.Count > 0 ? string.Join( " ", o ) : "No missing cards"; }; ``` --- [Answer] ## JavaScript (ES6), ~~117~~ ~~114~~ 111 bytes ``` s=>[...Array(52)].map((_,i)=>~s.search(c=('JQKA'[v=i>>2]||v-2)+'CDHS'[i&3])?_:c+' ').join``||'No missing cards' ``` This takes advantage of the fact that *undefined* entries in the array generated by `map()` are coerced to empty strings when `join()`'d. ### Demo ``` let f = s=>[...Array(52)].map((_,i)=>~s.search(c=('JQKA'[v=i>>2]||v-2)+'CDHS'[i&3])?_:c+' ').join``||'No missing cards' console.log(f('9H AH 7C 3S 10S KD JS 9C 2H 8H 8C AC AS AD 7D 4D 2C JD 6S')) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 76 bytes ``` ^ A2345678910JQK¶ \G(10|.) $&H $&D $&S $&C Dr` \S+ G1` ^$ No missing cards ``` Input/output is a list of space-separated cards. Output has a leading space. [Try it online!](https://tio.run/nexus/retina#DcNBCsIwEAXQ/ZziL4oogiRpbZplyEBDCoLMtpQWBelChXbruTyAF6uB97aBvCmrc20bp1W6dr8vqG/3Wn1OB0KxiznnkgfiZUQvR2r1SENBlzee87rOrwdu03Jft81F@AgbUAq0EnSMJHABJqLJAnwm8AzLqBgmIDFq@QM "Retina – TIO Nexus") ### Explanation Most of the code deals with building the full list of cards that should be in the deck: ``` ^ A2345678910JQK¶ \G(10|.) $&H $&D $&S $&C ``` First, we prepend a newline to the input, with all possible values of cards, then for each character of this line (or the couple of characters `10`) we build the list of all possible suits of that card. ``` Dr` \S+ ``` This is a deduplication stage, it splits the string into chunks consisting of a space plus some non-spaces and keeps only one occurrence of each chunk. The modifier `r` makes this operate from right to left, keeping then the *last* occurrence of each chunk. ``` G1` ``` We keep only the first line, which now contains the missing cards. ``` ^$ No missing cards ``` If the result is empty we replace it with "No missing cards" [Answer] # Python 3, 106 bytes Combination of the two previous python answers mixed with some string unpacking shenanigans. ``` print(' '.join({x+y for x in[*'23456789JQKA','10']for y in'HDSC'}-{*input().split()})or'No missing cards') ``` [Answer] # [Julia](http://julialang.org/), 116 bytes ``` print(join(setdiff(["$x$y"for x=∪(2:10,"JQKA")for y="HDSC"],readline()|>split),' ')|>s->s>""?s:"No missing cards") ``` [Try it online!](https://tio.run/##FY5daoNQEIW3crgEomAh8S8aiEVmHi4KBZnH0odQtdxgNXgtJNAFdC1dVjdib@AbmDMc5pzL12DO6bpeZzMu3mUyo2e7pTV9772qzW1zV/0043b6@/n1wuN@F6iqqUvlP673k9IspN6CuTu3gxk7z/8u7HUwix9ssX2Ip8IWSj3bo3qZ8GmsNeMH3s9za5W/rrlGqXEgRIL9TlAzKkFOCDUyB6F0CErGgREzQkLFSAWh2wWRRsSICLFGLIgJiUbCSAQJIdVInZlwcBmCjJG554xcUGlUhEajYTSChlBr1K4AuR7aDf8D "Julia 0.6 – Try It Online") Very similar to Kyle Gullions python solution. Setdiff instead of - and the lambda to test for the empty string make it worse though. [Answer] # Japt, 39 bytes ``` "JQKA"¬c9õÄ)ï+"CHSD"q)kU ¸ª`No ÚÍg Ößs ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=IkpRS0EirGM59cQp7ysiQ0hTRCJxKWtVILiqYE5vINrNiGcg1t9z&input=WyI5SCIsIkFIIiwiN0MiLCIzUyIsIjEwUyIsIktEIiwiSlMiLCI5QyIsIjJIIiwiOEgiLCI4QyIsIkFDIiwiQVMiLCJBRCIsIjdEIiwiNEQiLCIyQyIsIkpEIiwiNlMiXQo=) [Answer] # [Tcl](http://tcl.tk/), 270 228 chars (Shortened with some help from Wît Wisarhd) ``` foreach s {H D S C} {foreach c {2 3 4 5 6 7 8 9 J Q K A} {dict set d $c$s 0}} gets stdin l foreach c $l {dict set d $c 1} set m {} dict for {c h} $d {if {!$h} {lappend m $c}} if {![llength $m]} {set m "No missing cards"} puts $m ``` [Try it online!](https://tio.run/##XY7BasMwEETv/orXoA9InDSOj8Y6GAcKRcfSQ5Ac2yA7JlJOQt/uqimlUJjD7s5jZr2263q93buLHnCEBomijoTfoybk7DnwypGCEyUt75ypEmRG7XGdxyC0cGxjzPrOO5w344zN/lKE/Yezi9n3PBFi9nQSTNAMEWEI45XwItIS7GVZutkkUuhU8DQ@rO3m3g@I6TMhP0GbtxvT6Nw49@jL3bhNzJZHekdM61o2VA1FzV6x2yrOklZR1uQNp6SaKklRSQrJQZLXtJKj@gI "Tcl – Try It Online") Explanation: This implementation builds a dictionary consisting of a boolean flag for each of the cards represented by the cartesian product of H D S C and 2-through-A. It reads the line from stdin, which if given as the spec as called for, is actually a well formed Tcl list. As each card is read, a boolean true is input in the dictionary for that card. At the end a parser loops through the dictionary, and adds any card that did not have a true in the dictionary to a list of missing cards. If the missing cards list length is zero, output "No missing cards", otherwise output the list of missing cards. [Answer] # [PHP](https://php.net/), 138 bytes Ran with `-n` and `-d error_reporting=0` I reuse some code from an [old submition](https://codegolf.stackexchange.com/a/166666/77963) i made that asked for create a deck of cards **Code** ``` <?$r=[];foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)array_push($r,$t.H,$t.S,$t.D,$t.C); echo join(" ", array_diff($r,explode(" ",$argv[1]))); ``` [Try it online!](https://tio.run/##JYtBa4NAFAbv/RUfYQ8KL0VNGiM2FNk9iDmVPYoEiWu0FHd52tL@@W5jC8NchnGD8/75RfCpbvLesmmvQ1AXVNErnSmhHe3piQ6U0pEyiqOmncUStszt98V9zEMgmMTyWK7Sq9QqGeYP5jpYvNlxCjbYEP6Xbuz7dTFf7t125i@Jlm@fddyEYZh777MSRYlUYqcRRxpnhUojk0hKHO9IFHc0CoVUYa@QSFQKB/1j3TLaafbbyW87GGbLFzbO8jJOt1P0Cw "PHP – Try It Online") **Explanation** ``` <?$r=[]; # Declare the array that will contain the full deck # the next line will generate the arry with the full deck foreach([A,J,Q,K,2,3,4,5,6,7,8,9,10]as$t)array_push($r,$t.H,$t.S,$t.D,$t.C); # explode the input string on each blank space and using array_diff to get the # different elements withing both arrays. (and "echo" of course) echo join(" ", array_diff($r,explode(" ",$argv[1]))); ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 197 bytes Without LINQ. ``` s=>{var w="";for(var j=0;j<52;){var u="";int t=j%13;u=t<1?"K":t<2?"A":t<11?t+"":t<12?"J":"Q";t=j++/13;u+=t<1?"H":t<2?"D":t<3?"S":"C";w+=s.IndexOf(u)<0?u+" ":"";}return w==""?"No missing cards":w;}; ``` [Try it online!](https://tio.run/##XZBfb4IwFMXf@RQnTZZA2JzgNqcFCYEsTPefhz0jVFOjZWmLbjF@dlZwT0tvcm77O6e5uaW6KmvJ2kZxsUb@ozTbUavcFkrhTdZrWeyOFvDVLLe8hNKFNrKveYXnggvb6SDw0IgyUFqaPy5x1hmWCFsVzo77QuIQEkJXtbS7yyYc0k1w61OnZ03HuNDQ4ebCG9Em1IEXkQWZ6sCPSNyp50XaJX1nnuZkSt4JNX7Xve4S7jmS/UXSTkcRyY0vIfTghmrwKCr2/bqyGycYRo1LYBihJ8l0I4WZzwwRkZcaO676VZSFrBSZHuiJttQ6L2aQ1ELVWzb4lFyzJy6YvbT/oQ9WVD1xHIda1smcdpIhzjBOMMrhDXMsUsxzTBL4Ge5NJYhN5YhTjFPcpPATzFPcGWeGXw "C# (.NET Core) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 73 bytes ``` put keys((<<{^9+2}J Q K A>>X~ <C S D H>)∖get.words)||"No missing cards" ``` [Try it online!](https://tio.run/##DchNCoJAAIDRq3y4UoIoC00QYZhZDApBzKZVECUi/SiOEZG17gQdsItMwlu9tuzOkXPtredUPqzvp@lzl0zCV86GApFl2zepxKDQWfD7fKuyn96b7miDYfDWDZfa2vpacdiP5zmXaIQmliwM85mhUOSGRBJqViOJGBmEIlYsFaEkV0TmDw "Perl 6 – Try It Online") Some pretty simple set subtraction between the deck of cards and the input. [Answer] # [Python 3](https://docs.python.org/3/), 102 bytes ``` lambda s:' '.join(i+j for i in[*'A23456789JQK','10']for j in'HDSC'if(i+j)not in s)or'No missing cards' ``` [Try it online!](https://tio.run/##FYs7D4IwGEX/yt0@qsbwkoeJA2kHAomJ6agOKEFLpCUUB389luRM95w7/ua30dHSnW7LpxkebQN7JNC@N0p7atujMxMUlL5uqAij@JCkWV5datpR4NN9tb2zVArJSXXrhWkzuwmWmYnOBoOyVukXns3UWlrGSenZc6Uev7PHGFvyEkWJlCOSCHyJWqCSyDnCEpmDo3BIFAKpQCwQclQCifwD "Python 3 – Try It Online") ]
[Question] [ Write a function or program that accepts one character (or a string of length 1) as input, and outputs the number of times that character occurs inside the code. * This program must be a [Proper Quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine), only in the sense that it cannot, for example, read itself as a file, etc. Input can be any character, printable or not. Output may be to standard out, or as a return value from a function. This is code golf, so the shortest submission in bytes wins. Good luck! [Answer] # [Python 2](https://docs.python.org/2/), ~~30~~ 22 bytes *-8 bytes thanks to @Mukundan314* ``` `'``*2.count'*2`.count ``` [Try it online!](https://tio.run/##dc0xDoMwDEDRvafwFjsDUjN14SZIDaKkmMGOXKOK06cDLAzd3vL16@6LSmqlH1oOOcfUTbqJh5jyoVaNxSGEblUWnBZDJohQThIUNWBgARvlPeM9PYhu1@qj5vMLbfw@WermSER/fj8 "Python 2 – Try It Online") [Answer] # [COW](https://bigzaphod.github.io/COW/), ~~711~~ ~~519~~ ~~504~~ ~~390~~ 387 bytes ``` moOMooMOOmOoMoOMoOMoOMoOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOoMOoMOoMOomOoMOomoomoOMMMMOOMOomoomoOMoOMoOMoOMoOMoOMoOMoOMoOmOomooMMMMOOMOoMOoMMMmoOMoOMoOmoOMOomOomOoOOOmooMMMMOOmOoMoOMoOMoOMoOMOOmoOMOoMOoMOoMOoMOoMOoMOoMOomOoMOomoomoOMMMmoOMOomoOMoOmOomOoOOOmooMMMMOOMoOMoOMMMmoOOOOMoOMoOMoOmoOMOoMOomOomOoOOOmooMMMMOOmoOmoomoOMOOmoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmOoMOomoomoOOOM ``` [Try it online!](https://tio.run/##jY5RDoMwDEP/e4ocYYVJiENEPsS@I39y/NK0pQM2EJUVpYplvw@XlIxQUgED1fcf5ZNP3svqJN2cH/D9XsiKoZtdqt1fS60IztCcZ85bvBNVy@ztx@QWWGzAjnPL/wPj1xJYMZ5pT5V7kkp8vQMkDnMwkXEKlBinpGEF "COW – Try It Online") *I appreciated a lot the previous solution (504 bytes) because it's deducted step by step, if you are interested please take a look at that in the timeline... Now I furnish the program with a more "sensible" structure that promises to be less expensive (in terms of total byte count) but finding just a working set of values isn't simple... To find the best, **brute force** comes in.* **The next sections refers to the 390 bytes answer since it's simpler to explain that and then tell what it's done to save 3 bytes.** ## What it does \$L = \{M,O,o,m\}\$ is the set of used chars and \$n\_1,\dots ,n\_4\$ their count. The program has a structure that allows to form the output number \$n\_i\$ as $$ \begin{align} n\_i = x\_i\times cf+y\_i \end{align} $$ Furthermore we don't need to form \$x\_i\$ and \$y\_i\$ every time from zero, we reach them using the *partial sums* of 2 sequences occurring in cells `[2]` and `[3]` respectively. ``` [0]: multiplier for [1] [1]: input-current_char [2]: x_i [3]: y_i [1] = getchar() if[1] { [1]-=77(M), [2]+=8, [3]+=0, cut[1] } paste[1] //checks for 'M' and prepares its count if[1] { [1]-= 2(O), [2]+=2, [3]+=0, cut[1] } paste[1] //checks for 'O' and prepares its count if[1] { [1]-=32(o), [2]-=1, [3]-=1, cut[1] } paste[1] //checks for 'o' and prepares its count if[1] { [1]+= 2(m), [2]-=6, [3]-=2, cut[1] } paste[1] //checks for 'm' and prepares its count if ![1] //input was one of the letters above print [2]*13+[3] else //input was something else print [4] (0) ``` As long as the input doesn't match any letter in \$L\$, `[1]` stays ≠ 0 and `[2]` and `[3]` hold \$x\_i\$ and \$y\_i\$ of the last tested letter. Otherwise, if `[1]` has become 0, those value are no longer updated and at the end they will form the related \$n\_i\$. (When the input isn't a letter in \$L\$, after the 4 tests `[1]` is still ≠ 0 so the flow enters a loop (`[>]`) that sabotages the placement of the head, thus prevents from printing \$n\_4\$ (the number of `o`).) ## How I've first constructed the exoskeleton: the complete program without the info about its char count. That is without \$cf\$(*common factor*) and the 2 sequences that form \$x\_i\$ and \$y\_i\$. * **The exoskeleton** ``` moo ] mOo < MOo - OOO * Moo . MOO [ moO > MoO + MMM = oom o >. [ <+++++++[>-----------<-]> > ? > ? << =*]= [ -- > ? > ? << =*]= [ <++++[>--------<-]> > ? > ? << =*]= [ ++ > ? > ? << =*]= [>] >[> ? <-]>o ``` Some of them can be negative but I know that in order to write them I'll spend \$len\$: the sum of their absolute value in `MoO`s and `MOo`s (`+` and `-`). *Thanks to this condition the comptutation is rather straightforward.* ## Brute force * \$cf>0\qquad\qquad A=\{a\_1,\ a\_2,\ a\_3,\ a\_4,\ a\_5,\ a\_6,\ a\_7,\ a\_8\}\$ * \$x\_i=\sum\_{j=1}^{i} a\_j \qquad y\_i=\sum\_{j=5}^{4+i} a\_j\$ * \$n\_i = x\_i\times cf+y\_i\$ * \$len = cf + \sum\_{j=1}^{8} |a\_j|\$ $$ (\*)\begin{cases} n\_1=|M|+len\\ n\_2=|O|+len\\ n\_3=|o|+len\\ n\_4=|m| \end{cases} $$ Given the letter count in the exoskeleton \$|M|=71,\ |O|=97,\ |o|=85,\ |m|=38\$ we can now search for \$cf\$ and \$A\$ that satisfies \$(\*)\$ minimizing \$len\$. `cf = 13, A = [8, 2, -1, -6, 0, 0, 1, -2]` is the best for that exoskeleton (\$len=33\$) ## Finished program ``` >. [ <+++++++[>-----------<-]> > ++++++++ > << =*]= [ -- > ++ > << =*]= [ <++++[>--------<-]> > - > + << =*]= [ ++ > ------ > -- << =*]= [>] >[>+++++++++++++<-]>o ``` As you can se when some \$a\_i\$ is \$0\$ its relative pair of `>` `<` became non-functional. But obviously we can't take them off in retrospect. ## -3 bytes, 387 bytes Juggling with the exoskeleton I've found that there is one configuration slightly different that overall saves 3 bytes (1 instruction). What's different? * One `*` is replaced with `[-]` that has the same effect *(+2 instr.)* * Using one `*` \$x\_4\$ is detached from the partial sum: \$x\_4=a\_4\$ *(+1 instr.)* * A pair of `>` `<` are saved because \$a\_5=0\$ *(-2 instr.)* The letter count of this exoskeleton is \$|M|=73,\ |O|=98,\ |o|=86,\ |m|=37\$ `cf = 13, A = [8, 2, -1, 3, 0, -1, 1, -2]` is the best. (\$len=31\$) *(-2 instr.)* [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` y=>"3.>=includes(*)\\\"y3.>=includes(*)".includes(y)*3 ``` [Try it online!](https://tio.run/##nU67DoIwFN39ihumFqQJMDhoWfgEVwYu0EJNbUlbNXx97WAcHF1OzuPmnnPDJ/rJqS2Uxs4iSh533mYNa7kyk37MwpOc9n2f7T9exr5ip3kTpXVAEDg09RkQLlDVp0SKgh5gssZbLZi2CxnTyTU4ZRYmnb13K7ouNROkR5BkTPhJHb6G/7YMzG9ahfSMaWGWsEIJFY1v "JavaScript (Node.js) – Try It Online") A bit convoluted but I tried to avoid using `f=` that would violate the proper quine requirement. The code is written in the way that all characters occur exactly 3 times. [Answer] # JavaScript (ES6), ~~40~~ 38 bytes A function made of 19 distinct characters used twice each. ``` _=>_.match`[\\]chmt[-a.02:=>?^^-]`?2:0 ``` [Try it online!](https://tio.run/##TU5LasMwEN37FLOThLBI3ELBqeJF6AmyzFfI32KPjCyyKb1BoZsu23v0PLlAj@COXQJlYHjM@82zuZjB@qYPMbq8GEs9nvT6pDoTbH3e7fcHW3dhFxu1SFK9zo7H@HDOknQxWpKDhlIFtw2@wYqLVRSVznOk812yAoRHWCYPBKQU8BIBWGL@xKr0rtvUxm8ohiNZicVA/JSrhr5tArdCtQVWoYYYlpPCF8NUScSsdzi4tlCtqzj@e0P1Jn/CnN8LkFQpgdHI2XzDfE7Sc2UG7Of7/fr5QZtBCuz69cYENbyOvw "JavaScript (Node.js) – Try It Online") ### How? The range going from `[` to `a` allows us to match the backtick and the underscore, which are both already doubled in the code, without explicitly including them in the pattern. This method comes with two minor drawbacks: * Because this range also includes `^`, we need to insert it twice in the code as well although it's not part of the payload. * We also have to insert a second `-`. Character set: ``` -.02:=>?[\]^_`achmt ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` y/+N"y/+N" ``` [Try it online!](https://tio.run/##K6gsyfj/v1Jf208JTPz/r@6nDgA "Pyth – Try It Online") [Test cases](https://tio.run/##K6gsyfiv/L9SX9tPCUy4/v@vXqnOpa4PxNpA7AfESkBcoQ4A "Pyth – Try It Online") ``` y/+N"y/+N" "y/+N" String literal +N Append the string `"` / Count occurrences of the input in that string y Multiply by 2 ``` [Answer] # [J](http://jsoftware.com/), 34 bytes ``` (2*1#.=&'(2*1#.=&)+6*=&')+6*=&'''' ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NYy0DJX1bNXUYQxNbTMtIBdKAcF/TS6u1OSMfAUzBVuFNAWQEIRvBOFroHKNoFwTCFcLVdYQlauMytVD1WuLylVDVayJytVG5Zqpc3H5Oekp5GYWF2fmpSskZyQWQRQYQBRUABX8BwA "J – Try It Online") ## how ``` single quote quoted program adjustment | / vvvvvvvvvvvvvvvv _____/___ (2*1#.=&'(2*1#.=&)+6*=&')+6*=&'''' ^^^^^^^^ ^^^^^^^^^^ \ / regular program ``` * Everything above a `^` is part of the "regular program". * The rest is "the program quoted", but with one exception: + The quoted program doesn't include the program's single quote characters `'` * `2*1#.=&'...'` - Two times `2*` the sum of `1#.` the total number of times the input char matches a char in "the quoted program". One for the actual program char, one for its quoted twin. * `+6*=&''''` - Plus six times `+6*` the `1/0`-indicator of whether the input char is equal to a single quote `=&''''`. This is the hardcoded knowledge that there are 6 single quotes in the program. [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 bytes ``` ".+#H".""+#H ``` [Run and debug it](https://staxlang.xyz/#c=%22.%2B%23H%22.%22%22%2B%23H&i=33%0A34%0A35%0A36%0A42%0A43%0A44%0A45%0A46%0A47%0A71%0A72%0A73&a=1&m=2) Takes as input a code point. Those provided in the test are for each character in the program, as well as their immediate predecessors and successors. ### Explanation: ``` ".+#H".""+#H ".+#H" String literal ".+#H" ."" String literal "\"\"" + Concatenate # Count occurrences of the input H Double ``` Constructs a string of half the program, permuted somehow. Counts occurrences there, then doubles. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12 10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) (input is a character, not a string!) ``` “ḤṾċⱮ”Ḥċ ``` A monadic Link accepting a character that yields the count. **[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO5Y83LnvSPejhrkw5v@HOxYdbtdx0HRHV6H3aOM6AA "Jelly – Try It Online")** ### How? ``` “ḤṾċ”ḤṾċ - Main Link: character, c (A full program with a single character as input gives the main Link a list of characters - i.e. S = ['c']) “ḤṾċ” - list of characters = ['Ḥ', 'Ṿ', 'ċ'] Ḥ - double = ["ḤḤ", "ṾṾ", "ċċ"] (Python strings) Ṿ - un-eval = ['“', 'Ḥ', 'Ḥ', 'Ṿ', 'Ṿ', 'ċ', 'ċ', '”'] ċ - count occurrences of c (in the un-eval-ed list) - implicit print (a list with a single entry just prints that entry) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` I⊗№⁺´”´””yI⊗№⁺´´yS”S ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9npWPuqY/apn2qHHXoS2PGuaCCSCqRJU5tAUosBkoDiT//z@0BQA "Charcoal – Try It Online") Explanation: ``` ´”´” Literal string `””` ⁺ Concatenated with ”yI⊗№⁺´´yS” Literal string `I⊗№⁺´´yS` № S Count matches of input character ⊗ Doubled I Cast to string Implicitly print ``` Charcoal has two ways of quoting non-ASCII characters, `´` (which quotes a single character) and `”y...”` (which quotes anything except `”`). Trying to do everything with `´` is awkward because it uses too many of them; the best I could do was 26 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes Port of the Stax answer. `¢` is order-sensitive, which is fairly annoying here. ``` "„Js¢·"„""Js¢· ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f6VHDPK/iQ4sObQexlJQg7P//D20HAA "05AB1E – Try It Online") # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes As for this... I wrote this myself. ``` „…J…¢s·'„'D''DJs¢· ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcO8Rw3LvID40KLiQ9vVgXx1F3V1F6/iQ4sObf//3xAA "05AB1E – Try It Online") ## Explanation ``` „…J 2-char string. …, J …¢s· 3-char string. ¢, s, · '„ 1-char string. „ 'D 1-char string. D '' 1-char string. ' D Copy this character. J Join the stack. s¢ Count occurances of the input in the string. · Multiply the count by 2. (Perfectly makes the 0-count still 0.) ``` [Answer] # perl, 128 bytes, assuming ASCII input only ``` print 1;#!"$%&'()*+,-./023456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghjklmoqsuvwxyz{|}~... ``` Replace the trailing `...` with the 33 unprintable characters (ASCII 0 .. ASCII 31 + ASCII 127), with the newline at the end. (If anyone knows how to put unprintable characters in a textfield and have them show up here, I'm all ears). [Answer] # [R](https://www.r-project.org/), ~~96~~ ~~82~~ ~~126~~ ~~94~~ 90 bytes ``` 3*sum(unlist(strsplit(c('"',"#'''((()))*,,3=acilmnprsssttu"),''))==scan(,''))##()*,3amprst ``` [Try it online!](https://tio.run/##HcohDsAgDAVQv2MU0d@lDs1hCIoECKHl/IzMPfHWOfG13bFHq@YwXzZbdRQwsVJgZgAi8qrGlEttfcxlZu6bRJlFUrKSB36HgDtj7vf4IabnfA "R – Try It Online") *Edit1: thanks to math junkie for pointing-out a horrible bug in the original version (the `\` character): hence the temporary increase and subsequent decrease in byte-length, as successive patches were added in panic..* *Edit2: -4 bytes: Copying the entire program into the 'look-up' string seemed wasteful ([94 bytes](https://tio.run/##K/r/30iruDRXozQvJ7O4RKO4pKi4ICezRCNZQ11JSV1HCaesuo6mjrq6pqatbXFyYp4GmK2EKfRfSV2J6z8A)), so instead added extra characters so that every character was present an even-number of times, and now just include half the program (character-wise) in the look-up string* [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` ∈"∈∈\\\"∧33||"∧3|∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/1FHhxIQA1FMTAyQtdzYuKYGTNcAif//QZIxSjExYBEdBb1HHSsKy1OLSipLM/MLomMTi1PSDI2MTUzNzC0sDZQA "Brachylog – Try It Online") Brachylog doesn't really have any good way to get quotes without escaping them in a string literal (or using the `Ṭ` constant, which came out longer when I tried it), so the approach I came to is to simply triple down on everything else. (I don't know why the testing header runs out of stack after it's done every test case; I'd think it's something to do with the unbound variable output for 0 but [it works fine on individual inputs](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v@POjqUgBiIYmJigKzlxsY1NWC6Bkj8/6@kqAQA)... so long as [an unbound variable](https://tio.run/##SypKTM6ozMlPN/r//1FHhxIQA1FMTAyQtdzYuKYGTNcAif//lRSV/kcBAA) is indeed an acceptable way to give 0. If it's not, [+3 bytes](https://tio.run/##SypKTM6ozMlPN/r//1FHhxIQA1FMTAyQtdzYuKbGwADMqgESBv//Kykq/Y8CAA)) [Answer] # Python 3, 48 bytes ``` x="(x+2*chr(34)+'x=;f=eval(x)').count";f=eval(x) ``` [Try it online!](https://tio.run/##jY1BDoIwFET3nOKnG/4XQqR1QWp6EzakgpBoS2o1FeLZK4QYXbqamZe8zPj0vTUixqAYhozvdO9QHChLgzp2qn00FwyUUqHt3Xj2RXFSLKj6D6n@sVjSWQcaBgOuMecWBc9LXpFMYHSD8cjmvRSnF8ylFLcluOTrEmuwYpGvjUedw/qoKYdp@8BtL6D7VKL4Bg "Python 3 – Try It Online") Idea: Store code in string. The stored code returns function that counts characters in the string within which it is contained. Evaluate the string to get the function. Special care for characters wrapping the string. # Python 3 without `eval` I, 48 bytes ``` lambda c:3*(c in" \\\"(())**33::abbcddiillmmnn") ``` [Try it online!](https://tio.run/##fcuxDoIwEAbgnae43NQjhEhvMU14ky6lFWlCC0EchPjstWhcHJz@@//cNz/WYYqc@lan0YTOGbCKS2HBRwStNQpBVJbMSpmus855P44hxIiUthZ/jX4j/Q9qJCz6aYHjHxYTrxfBsmrkmVQB8@LjKnA/KXZP2BvFtxxSyaPxEVhnHMwqbAV2WISlCrbaTvfsPj0P/fckSi8 "Python 3 – Try It Online") # Python 3 without `eval` II, 124 bytes And a more creative, but much longer solution: ``` lambda c:[0o3623>(ord(c)-76)**2>195,' !!""##$$%%&&++,-..//4457889:;;==ZZ\\^^__``beeffgghhiijjkklmnnppqqrssttuuvvwwxx'][0]<<1 ``` [Try it online!](https://tio.run/##nY7ZcoIwAEXf/YoYt0QRIXHBKH6I4oKBACoBQ1Cr02@nOJ0@t9Onu8zcuSf/0HEmaSVcr7r46THwAWcbK6NTQlcoUwHieDib4n6frOz5xOiBZhPCVqvd7nS63cHAGJrmaDQeT2aOM2eLheuu15632@33h8MxDIWIojhOktPpfL6kUub59aqKQuuyvN3u98ejt91Y2@XSrp4u/Ou/B71fCf7DABsiU4CDRALlyyhElBg2cTBrgFwlUiP4shgNPsHLZrSohTDyTvQt0KzHqa8RNwCPVY1tgKfJs7Lefee6ED8W4@oL "Python 3 – Try It Online") Idea: Ensure all characters that satisfy a certain equation (`195 < (c-76)² < 1939`) appear exactly twice in the code, and return 2 for those characters (0 for all others). Maybe someone can think of a better compression for the long string, but remember expressing it may only use the same character twice. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` D#hs"D#hs" ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8b@LckaxEpj4//8/mBGjZGhkbGJqZm5haVBYnlpUUlmamV@QWJySpgQA "Husk – Try It Online") ``` D Twice # the number of occurrences of the input in "D#hs" "D#hs", s quoted, h without the second quote. ``` For the same number of bytes: # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` #S+s"#S+s" ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8b9ysHaxEpj4//8/mBGjZGhkbGJqZm5haVBYnlpUUqkEAA "Husk – Try It Online") Somewhat boring adaptation of the standard `S+s"S+s+` quine. [Answer] # [J](http://jsoftware.com/), 24 bytes ``` 2*1#.0 :0=[ 2*1#.0 :0=[ ``` [Try it online!](https://tio.run/##y/r/P81WT8FIy1BZz0DBysA2mguZrfmfKzU5I18hTUFdUx3ONEAwjeBMHzcurv8A) The second newline counts too, so it's not 23. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes ``` T`Tan[-a\]\n^0__-`2 [^2] 0 ``` [Try it online!](https://tio.run/##DcY7CoAwEEDB/t1DESEQ4yG8QLr8NmoEmxTi/Venmqe9d686TJuoF197MDWm2LMtxYgjZJewqpVOwiMEDPF/xlJw7BycNC4WVkbmDw "Retina 0.8.2 – Try It Online") I got the idea to use `[-a` from [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/205215/65425). **Explanation** ``` T`Tan[-a\]\n^0__-`2 ``` Transliterate each of the following characters into a `2`: * The letters `T`, `a`, and `n` * The range `[-a` which also includes `\`, `]`, `^`, `_`, and ``` * Literal `]` and literal newline * The characters `^`, `0`, `_`, and `-` ``` [^2] 0 ``` Replace any character that is not a `2` with a `0` [Answer] # [Perl 5](https://www.perl.org/) + `-plF`, 49 bytes ``` $_=q($_=grep/\Q@F/,qq(\$_=q($_);eval)=~/./g);eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rZQA0ikF6UW6McEOrjp6xQWasRAhTWtU8sSczRt6/T19NMhHKAWrnguW65CLg2uVK4yrkSuHC5XrjAuRy4frjgu3X/5BSWZ@XnF/3ULctz@6/qa6hka6BkAAA "Perl 5 – Try It Online") ## Explanation Pretty much the standard quine with some minor changes. The program itself is stored in `$_` which is `eval`ed (`eval` - along with most other functions - works on `$_` by default if no argument is specified. When the program is `eval`uated, `$_` is set to the number of matches (`~~grep`) against the input char `/\Q@F/`, which is interpolated at runtime and necessitates `\Q` to escape any special chars, against the list of chars resulting from the template string `$_=q(...);eval` with the actual program interpolated in the innermost `%_`, which is obtained with `=~/./g` (this returns a list of all the chars that matches the regex, `.` being match-all). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 1 byte ``` 1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/H4gMAA "Retina – Try It Online") Counts the number of 1s in the input, so the output is always 1 or 0. Inspired by [this answer](https://codegolf.stackexchange.com/a/209330/95792) on a related question. [Answer] # [Ruby](https://www.ruby-lang.org/) `-nl`, ~~40...32~~ 28 bytes ``` p~/[,-2\[-\]p~,..011?:]/?2:0 ``` [Try it online!](https://tio.run/##Dcm7DsIgAEDR/f5F48rbx8BCW/0LYDFRY2JaYu3QhU8XPet5r9ettVJ1FNKlKFMuVShlrA0@6@C8@S8VTUQgcSgMlkTAkxkYOXPhxp0Hew4cOdHRs/vO5fOcp6XJ6fUD "Ruby – Try It Online") Derived from my [answer](https://codegolf.stackexchange.com/a/209400/92901) to a related challenge. Each of the 14 distinct characters in the code appears twice. The input is tested against a regexp. The outer `[]` is a character class containing literal characters plus two character ranges: `,-2` is equivalent to the literal characters `,-./012` and `\[-\]` is equivalent to the literal characters `[\]`. The code prints `2` if the regexp matches the input character; `0` is printed otherwise. [Answer] # [C (gcc)](https://gcc.gnu.org/), 303 bytes ``` n[4467]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,3,3,0,0,126,0,0,0,92,15,17,2,2,2,2,2,0,1,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,0,0,2,0,1,1,1,1,1,1,2,0,0,0,1,5,0,1,0,2,0,2,0,0,0,0,0,0,2,0,2};main(){printf("%d\n",n[getchar()]);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z8v2sTEzDzWttpAh3JoBCYNwaQxEIJ5RmZQWUsjHUNTHUNzoDIYhCg2gmsi11pDqNUwsxAQJm6oY4pkmxGGs41qrXMTM/M0NKsLijLzStI0lFRTYvKUdPKi01NLkjMSizQ0YzWta///zwUA "C (gcc) – Try It Online") [Answer] # [Turing Machine Code](http://morphett.info/turing/turing.html), 95 bytes I'm not sure this counts, and if so deemed, I'll make it non-competing (or delete it if you guys think it's too egregious). The reasons why have to do with the Turing Machine Code interpreter I'm using. This affects the space character ( ), asterisk (\*), and semi-colon(;). **Space character** Basically it internally converts space characters into underscores '`_`'. Also, it interprets the *lack* of any character as a space character, and therefore interprets that as an underscore. Not only this, but it also interprets an actual underscore '`_`' as an underscore (or space, or lack of a character). Since the input is strictly limited to the text box on the web page, this means there is significant ambiguity as to how to count a space character. ***So that character will not work with this code.*** Any attempts at trying to fudge something here could easily and reasonably be discounted as wrong by atleast 3 different valid interpretations that I can come up with off the top of my head. **Asterisk** This character is set aside for a few special uses, depending on where in the code it's used. Most relevantly for this challenge, the asterisk - when used as an input check - acts as a special catch-all character. So any attempt at trying to catch this as input, catches anything and everything, including the aforementioned space character. It does so without any ability to discern an actual asterisk from the infinite possibilities. ***So that character will not work with this code.*** **Semicolon** Lastly, the semicolon is a **very strict** line comment. You put that anywhere in that line of code, and that's it. Everything after it (inclusive) on that line is interpreted as a comment, and is ignored. As a result of this, this Turing Machine interpretor will never be able to 'read' the semicolon character '`;`'. ***So that character will not work with this code.*** ``` 0 0 1 r 0 0 _ 2 * 2 0 r 7 * r 0 7 3 * r 0 2 7 * 2 0 3 5 * r 0 1 2 * r 0 5 3 * r 0 * 0 * 2;3325_ ``` [Try it online!](http://morphett.info/turing/turing.html?91b32d1afa58fdd26d2f2cd693603457) I'm deeply suspicious that there is a two or three line solution to this. I'll probably play around with this for a bit some more. Having to use a comment to pad the numbers really sets off a flag in my head that this code could accomplish this task far more efficiently. [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` "UèiQÑ )"iQ èU)Ñ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=IlXoaVHRICkiaVEg6FUp0Q&input=J1Un) Takes inspiration from the normal Japt quine. Essentially, counts the number of occurences in the string at the beginning (with a quote), then doubles it. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 144 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][S N S _Duplicate_0][T N T S _Read_STDIN_as_character][T T T _Retrieve_input][S N S _Duplicate][S S S T S S S S S N _Push_32][T S S T _Subtract][N T S S N _If_0_Jump_to_Label_SPACE][S N S _Duplicate][S S S T S S T N _Push_9][T S S T _Subtract][N T S T N _If_0_Jump_to_Label_TAB][S S S T S T S N _Push_10][T S S T _Subtract][N T S S T N _If_0_Jump_to_Label_NEWLINE][N S N N _Jump_to_Label_PRINT][N S S S N _Create_Label_SPACE][S S S T S S T S T T N _Push_75][N S N N _Jump_to_Label_PRINT][N S S T N _Create_Label_TAB][S S S T S S S S T N _Push_33][N S N N _Jump_to_Label_PRINT][N S S S T N _Create_Label_NEWLINE][S S S T S S T S S N _Push_36][N S S N _Create_Label_PRINT][T N S T _Print_as_integer_to_STDOUT] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##TYxBCoBADAPPySvyNZEF9yYo@Pyadl2VhkKGIdfWz3bsy9oiJNHngBCALBLyyaTwUIpiMrAAPgm0RtbicL032aPrr@H1lJ3uiOAN) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Character c = STDIN as character If(c == ' '): Print 75 to STDOUT Else-if(c == '\t'): Print 33 to STDOUT Else-if(c == '\n'): Print 36 to STDOUT Else: Print 0 to STDOUT ``` This sounds pretty straight-forward, but it was reasonably tricky to get the correct numbers. Pushing a number in Whitespace is done as follows: * `S`: Enable Stack Manipulation * `S`: Push number * `S`/`T`: Positive/negative respectively * Some `T`/`S` followed by a single `N`: Decimal as binary, where `T` is 1 and `S` is 0 So, after I created the template of my program, the amount of newlines were fixed and I could simply print 36 in that case. But the amount of spaces and tabs are variable. If I correct the count-output of the amount of spaces, the tabs would be incorrect, and vice-versa. This required some tweaking, which I eventually did without wasting any bytes by using a Label `ST` for the `Label_NEWLINE`. Usually I create Labels in the following order, based on the amount of times it's used: (empty label); `S`; `T`; `SS`; `ST`; `TS`; `TT`; `SSS`; etc. In this case, I've skipped the `SS` and used `ST` instead, allowing me to print 75 and 33 with the binary pushes of `TSSTSTT` and `TSSSST` for the counts of spaces and tabs respectively. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ 8 bytes ``` `I$O`I$O ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiYEkkT2BJJE8iLCIiLCJJXG5PXG5gXG5LXG4kIl0=) Back then, there was no quine cheese. Now there is. ## Explained ``` `I$O`I$O `I$O` # The string "I$O" I # surrounded in backticks and appended to itself $O # Get the count of the input in that. ``` ]
[Question] [ My two kids like to play with the following toy: [![Turtle](https://i.stack.imgur.com/BYhak.jpg)](https://i.stack.imgur.com/BYhak.jpg) The colored areas with the shapes inside can be touched and the turtle then lights the area and plays a sound or says the name of the color or the shape inside. The middle button changes the mode. There is one mode in which the areas play different musical notes when touched, with a twist: if the kid touches three consecutive areas clockwise, a special melody 1 is played. If the three consecutive areas touched are placed counterclockwise, a special melody 2 is played. ### The challenge Let's simulate the internal logic of the toy. Given a string with 3 presses of the kid, return two distinct, coherent values if the three presses are for consecutive areas (clockwise or counterclockwise) and a third distinct value if they are not. ### Details * The input areas will be named with a character each, which can be their color: `ROYGB` for red, orange, yellow, green and blue; or their shape: `HSRTC` for heart, square, star (`R`), triangle and circle. Case does not matter, you can choose to work with input and output just in uppercase or in lowercase. * The program will receive a string (or char array or anything equivalent) with three presses. Examples (using the colors): `RBO`, `GYO`, `BBR`, `YRG`, `YGB`, `ORB`... * The program will output three distinct, coherent values to represent the three possible outcomes: a first value if the combination does not trigger a special melody, a second value if the combination triggers the clockwise special melody, and a third value if the combination triggers the counterclockwise special melody. Example: `0` for no special combination, `1` for the melody triggered by a clockwise combination and `-1` for the melody triggered by a counterclockwise combination. * You do not need to worry about handling wrong input. ### Test cases ``` Input Output // Input based on colors -------------- RBO 0 // No special combination GYO -1 // Counterclockwise melody triggered BBR 0 // No special combination YRG 0 // No special combination YGB 1 // Clockwise melody triggered ORB -1 // Counterclockwise melody triggered OOO 0 // No special combination BRO 1 // Clockwise melody triggered ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win! [Answer] # Java 8, ~~48~~ ~~39~~ 33 bytes ``` s->"ROYGBRO BGYORBG".indexOf(s)|7 ``` -6 bytes thanks to *@RickHitchcock*, so make sure [to upvote him as well](https://codegolf.stackexchange.com/a/174590/52210)! Takes uppercase color as input-String. Outputs `-1` for none, `7` for clockwise, and `15` for counterclockwise. [Try it online.](https://tio.run/##jVE9j8IwDN37K6xO7UAZke4EQxgy0Uhhqk4MIQ0oUBJEUg4E/e3FLTBCukSy/Zz34Z04i9Gu3LeyEs7BQmhziwC08eq0EVJB3pV9A2Sy9CdttuDSX2w2ET7OC68l5GBgCq0bzWLOCko4A0ILxgmNM21KdWGbxKX3SdstHut1hTuv1bPVJRyQ9/X73wpE@iQdjyG3Rv30xfLqvDpktvbZEXG@MonJZBJzwuK0F/QZQwgPYgpOgxjGvnLh5K17Xlm5/9cuIB6jCovnYYMY@lBhtu5uK4fpwxuGQ@EDPNAi7IG8D9BETfsA) **Explanation:** ``` s-> // Method with String parameter and integer return-type "ROYGBRO BGYORBG".indexOf(s) // Get the index of the input in the String "ROYGBRO BGYORBG", // which will result in -1 if the input is not a substring of this String |7 // Then take a bitwise-OR 7 of this index, and return it as result ``` --- **Old 39 bytes answer:** ``` s->(char)"ROYGBRO BGYORBG".indexOf(s)/7 ``` Takes uppercase color as input-String. Outputs `9362` for none, `0` for clockwise, and `1` for counterclockwise. [Try it online.](https://tio.run/##jZGxbsMgEIZ3P8XJEwyxx0qp2oEMTDUSmawqA8UkwXEgMjhpFfnZXey6Y4IXpLv7j@@/u1pcxaquToNshHPwIbS5JwDaeNXuhVRQjOGUAIm2vtXmAA6/hmSfhMd54bWEAgy8weBW70geRYtTzkpKOANCS8YJTTNtKvXN9sjh/GUY2y/dVxM65w@uVldwDvSZ8bkDgf/QeQ6FNWo9Bdsf59U5s53PLkHnG4NMJlHKCUvxZOuxhhAe1ZScRjWMPWWFyr/vTWPl6aZdxHxYVdw8Xwy13Xg9uYwd7hMfmC/wR8tZ0yf98As) **Explanation:** ``` s-> // Method with String parameter and integer return-type (char)"ROYGBRO BGYORBG".indexOf(s) // Get the index of the input in the String "ROYGBRO BGYORBG", // which will result in -1 if the input is not a substring of this String // And cast it to a char (-1 becomes character with unicode value 65535) /7 // Integer-divide it by 7 (the char is implicitly converted to int doing so) ``` [Answer] # JavaScript (ES6), 41 bytes Takes color initials as input. Returns `2` for none, `true` for clockwise or `false` for counterclockwise. ``` s=>~(x='ROYGBRO_ORBGYOR'.search(s))?x<5:2 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Oo8JWPcg/0t0pyD/eP8jJPdI/SF2vODWxKDlDo1hT077CxtTK6H9yfl5xfk6qXk5@ukaahnqQk7@6pqaCvr6CEReaFNAAqFRaYk5xKrq0k1MQLp2RQe44pdydoFIlRaUYZgKdjc9Kf3@cjgV6Gsnc/wA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` lambda i:'ROYGBRO ORBGYOR'.find(i)/7 ``` `-1` - None `0` - Clockwise `1` - Counterclockwise [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHTSj3IP9LdKchfwT/IyT3SP0hdLy0zL0UjU1Pf/H9BUWZeiUKahnqQk7@6JhecC1SHzHVyCkLmRga5o3DdnZC5QGtQuP6oRgUBuf8B "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes Saved 4 bytes thanks to *Kevin Cruijssen* and *Magic Octopus Urn*. Uses shapes. Output `[0, 0]` for *none*, `[1, 0]` for *clockwise* and `[0, 1]` for *counter-clockwise* ``` ‚.•ÌöJη•så ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cNOjhll6jxoWHe45vM3r3HYgq/jw0v//i0qSAQ "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##yy9OTMpM/V9TVln5/3DTo4ZZeo8aFh3uObzN69x2IKv48NL/lUqH9yvo2iko2ev8z0gu5iopKuZKTs7gKsoo4SoqSeYqzgDiYqBYRjEA) **Explanation** ``` ‚ # pair the input with its reverse .•ÌöJη• # push the string "hsrtchs" så # check if the input or its reverse is in this string ``` [Answer] ## Excel, 29 bytes ``` =FIND(A1,"ROYGBRO_RBGYORB")<6 ``` Uppercase colours as input. Returns `#VALUE!` for no pattern, `TRUE` for clockwise, `FALSE` for anti-clockwise. Can wrap in `IFERROR( ,0)` for `+11 bytes` to handle exception , and return '0' for no-pattern cases instead. [Answer] # JavaScript (ES6), 32 bytes ``` s=>'ROYGBRO_ORBGYOR'.search(s)|7 ``` Returns -1 if no combination, 15 if counterclockwise, 7 if clockwise. ``` let f = s=>'ROYGBRO_ORBGYOR'.search(s)|7 console.log(f('RBO')) // -1 console.log(f('GYO')) // 15 console.log(f('BBR')) // -1 console.log(f('YRG')) // -1 console.log(f('YGB')) // 7 console.log(f('ORB')) // 15 console.log(f('OOO')) // -1 console.log(f('BRO')) // 7 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~42~~ 36 bytes ``` {"ROYGBRO","ORBGYOR"}~StringCount~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/b9aKcg/0t0pyF9JR8k/yMk90j9IqbYuuAQom@6cX5pXUqes9l/fQQGozslfSUFHQQmoBEwDdYFpoC4I7Q8RB5mlUBv7HwA "Wolfram Language (Mathematica) – Try It Online") Counts the number of times the input appears in both `"ROYGBRO"` and `"ORBGYOR"`. Returns `{1,0}` for clockwise, `{0,1}` for counterclockwise, and `{0,0}` for no special combination. At the cost of only one more byte, we can get outputs of `0` for nothing, `1` for clockwise, and `2` for counterclockwise with `"ROYGBRO.ORBGYORBGYOR"~StringCount~#&`. [Answer] # x86 machine code, ~~39~~ 36 bytes ``` 00000000: f30f 6f29 b815 0000 0066 0f3a 6328 0c89 ..o).....f.:c(.. 00000010: c883 c807 c352 4f59 4742 524f 2042 4759 .....ROYGBRO BGY 00000020: 4f52 4247 ORBG ``` Assembly: ``` section .text global func func: ;the function uses fastcall conventions ;no stack setup needed because we don't need to use stack movdqu xmm5,[ecx] ;Move DQword (16 bytes) from 1st arg to func(ecx) to SSE reg mov eax, msg ;Load address of constant str 'msg' into eax PcmpIstrI xmm5, [eax], 1100b ;Packed Compare String Return Index, get idx of [eax] in xmm5 mov eax, ecx ;Move returned result into reg eax or eax, 7 ;Bitwise OR eax with 7 to get consistent values ret ;return to caller, eax is the return register msg db 'ROYGBRO BGYORBG' ``` [Try it online!](https://tio.run/##bVNRT9swEH6Of8WpEmtTGtaCNiQKPGSwDmkoLDwhqCrHdtKwxM5spw1C/PbunKyi1cjDKT5/33ff@eyEmuWGUQvn59fRd7iEz7asPtMjasqNEczmSsKRFY0lXlaohBaQ1pIRF848903tUrS5FlobYSClxjJaFMCUXAnpNgzpwFKBsZT9BiNsXYEUggsOiWAUmbAWwJXs2zYPVjm5Dk@8Uq34nxqasvwyehSsmaParVoJuPq1VprDYPIVkhcrjA@pViVMjAWqM6fi3A2Q4rvF/f01aJG1giBoM4LSZM7aT0U5UM61MAZU6sxjaWnRgIY@gvqQSxRADvHuWFnd4MZNZwgeMTsfwWQyHife9A4dYwPfVFlRLeDe6lxmEGPLWsKN5AKrZsJCzhtXqSWjeKu1Ywwte9sudUtGUbRXF7azgn10dpTuGKcOH@Z2nePBRbFLwjq3Szh1rbuSrqvcWJwKrGhRCxwMSrez6Uo4oBue0KOWnhtwE/63iRUdW6NLkwFPoB9HD7MwjiCcPURxOOtv8BoR8t@NMrZOjhjBiyRQBt3DYkEtHkxSW7FYDAbbS@P73bzYkuqhPwXisCXN5cB/JV6bxSFb8zi/eO3FYdQb9bAyxjCMMT7EMxdnIUb042LU7sYYx29T4qVKD5xmfjGedkr5fJofHjp5r8JJ2XTQOzBncMCfZG@0hYxaV9uV76PSG3kjbbcSXwsEqSjSk@OdBwSB6lZMcXGkSMbYfgoJu6ezC4ZAqqDKBQTlyTFRyTNT1QsEESS5pBr/nrtnucd5/0cUcSxelxUEVxDcujMXxR788tMxEWyJtQT0nuRwOAzxAeEVqaU9w1WvRazRNIPzffEPuD9E46q9E5uGf0Aie@1v/gI "Try It Online") Output is `23` for none, `7` for clockwise, and `15` for counter-clockwise. Based on @RickHitchcock 's answer. Edit 1: Saved 3 bytes by using an SSE string comparison instruction instead of using libc. Edit 2: Use proper calling convention for SSE (use XMM5 instead of XMM2) and improve formatting on Bash. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 30 bytes ``` $_=ROYGBRO=~/$_/-ORBGYOR=~/$_/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jbIP9LdKcjftk5fJV5f1z/IyT3SPwjC@/8fKPEvv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online") [Answer] # APL(Dyalog), ~~22~~ 18 bytes ``` +/(⍷-⍷∘⌽)∘'ROYGBRO' ``` *-4 bytes thanks to @ngn* Takes a string of color initials. Outputs 0 for no special pattern, -1 for counterclockwise, 1 for clockwise. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1tf41Hvdl0gftQx41HPXk0gpR7kH@nuFOSv/j/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv9PUw9y8lfnSlN3jwRTTk5BICoyyB1MuTuBKP8gCOUPUQI0GgA) [Answer] # [Python 2](https://docs.python.org/2/), ~~45~~ 43 bytes ``` lambda i,a='ROYGBRO':(i in a)-(i[::-1]in a) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ9FWPcg/0t0pyF/dSiNTITNPIVFTVyMz2spK1zAWzPtfUJSZV6KQpqEe5OSvrskF57pHonCdnIKQuZFB7ihcdydkrn8QKtcf1SigazT/AwA "Python 2 – Try It Online") With ideas from and serious credit to @DeadPossum -2 with thanks to @JoKing. Now outputs -1 = counterclockwise, 0 = none, 1 = clockwise. My original effort is below for historical purposes. # [Python 2](https://docs.python.org/2/), ~~52~~ 51 bytes ``` lambda i,a='ROYGBRO':((0,1)[i[::-1]in a],2)[i in a] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ9FWPcg/0t0pyF/dSkPDQMdQMzoz2spK1zA2M08hMVbHCMhXADP/FxRl5pUopGmoBzn5q2tywbnukShcJ6cgZG5kkDsK190JmesfhMr1RzUK6CrN/wA "Python 2 – Try It Online") 0 = none, 1 = counterclockwise, 2 = clockwise [Answer] # [Python 2](https://docs.python.org/2/), ~~35~~ 36 bytes +1 - for some reason I thought all buttons would be distinct >\_< *Developed independently from [what I have just seen](https://codegolf.stackexchange.com/a/174582/53748) (and now up-voted) by Dead Possum* ``` lambda s:'ORBGYO.BROYGBR'.find(s)/7 ``` **[Try it online!](https://tio.run/##lZBRS8NADMff@ynylha6CvogDCqsRcpQLFRBhvOha6/stL077lLET19znQ6GOPAeApf88/snMZ@01@py6tLt1NfDrq3BLbGssmJTVklWlZsiqzDppGpDF11cT/l9md89rx9vIYUX5DrGyCKOrOTo5TFyI74Gq4en9amewVxlutcUvpd9fG9ZsT4wVioCzHvdvH9IJ5YYdNoCCUcgFRxZywD4HdS@GAMubjCGLvS/6IeDR@JKkVw0f2BPxvw3uqS9sGC0c3LXC@aZkRwbWD2AJGFJ696BHIy2xFzdjg3N9sZ7fydCnC/NPlYYUVN6FR0GmWdM2S9501KFJpqzsvt9Ezi/kX@N5jOoUZxfcfoC "Python 2 – Try It Online")** [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ù♀e▌d─█£F'♦O▬ ``` [Run and debug it](https://staxlang.xyz/#p=970c65dd64c4db9c4627044f16&i=RBO%0AGYO%0ABBR%0AYRG%0AYGB%0AORB%0AOOO%0ABRO&a=1&m=2) The output is * 1 for no special combination * 2 for counter-clockwise melody * 3 for clockwise melody [Answer] # [Pip](https://github.com/dloscutoff/pip), 19 bytes ``` Y"ROYGBRO"OaNyaNRVy ``` Outputs `10` for clockwise, `01` for counterclockwise, `00` for neither. [Try it online!](https://tio.run/##K8gs@P8/UinIP9LdKchfyT/RrzLRLyis8v///0AxAA "Pip – Try It Online") ### Explanation ``` a is 1st cmdline argument Y"ROYGBRO" Yank that string into y variable aNy Count of occurrences of a in y O Output without newline RVy y reversed aN Count of occurrences of a in that string Print (implicit) ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` -&(OR@E.&'ROYGBRO')|. ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/3XVNPyDHFz11NSD/CPdnYL81TVr9P5rcqUmZ@QrANXYKqQpqAc5@atDROINISLukTARmBonpyA0kcggd5gIVBfQAjRz/IOc0HT5@/uj6QI56j8A "J – Try It Online") ### How it works ``` -&(OR@E.&'ROYGBRO')|. Monadic 2-verb hook. Input: a string. |. Map over [input string, input string reversed]: E.&'ROYGBRO' Find exact matches of input in 'ROYGBRO' (OR@ ) Reduce with OR; is it a substring of 'ROYGBRO'? -& Reduce with -; result is 1 for CW, -1 for CCW, 0 otherwise ``` Achieves maximum amount of function reuse. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ,Ṛẇ€“¤ƈẎṬ%Ȥ» ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//LOG5muG6h@KCrOKAnMKkxojhuo7huawlyKTCu////2d5bw "Jelly – Try It Online") -4 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/questions/174564/playing-with-the-musical-turtle/174588?noredirect=1#comment420882_174588). Clockwise: `[1, 0]` Counter-clockwise: `[0, 1]` Other: `[0, 0]` [Answer] # [R](https://www.r-project.org/), 38 bytes ``` grep(scan(,''),c('ROYGBRO','ORBGYOR')) ``` [Try it online!](https://tio.run/##pZJBb4MgFMfvfoqX9IAkatYem20HdvA2Em4eKT4dqaJBjGuWfXYHtWt6WbpNTgT@P/i9B3bewGRl36MF1wG2YyMdwuBKbfrRwaTdG0ioRqOc7gzEg2wRDiefUd1oHI2qp@/N@J1@DEqax/S6kmUZtehGGzbn2mIfh0ScEEITFRPBi5wJThLCBcsLLgil82cUbUCcqQH2fg4pvHYw9Ki0bPy97UEbeda5GXvQxmGNNn6gsEAvwRCtajp1nPSA0GLTlSdwVtc@iKWHdpfoz5nr@dsoqrwy44QCbH6h5Ef6fKMVcF/kgt@XW/BdoBgTay4tRL4Kz9nF@W6XFnwbKP@i/6iU81XtDZ/pb6rzFw "R – Try It Online") Returns : * No special combination : `integer(0)` * Counterclockwise melody triggered : `2` * Clockwise melody triggered : `1` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ≔ROYGBROηI⁻№ηθ№⮌ηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DKcg/0t0pyF9JRyFD05oroCgzr0TDObG4RMM3M6@0WMM5vxQokKGjUKipowDhBKWWpRYVp2pkaIJEgcD6/3//IKf/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ROYGBRO Literal string ≔ η Assign to variable η η Value of variable ⮌ Reversed θ θ Input string № № Count matches ⁻ Subtract I Cast to string Implicitly print ``` [Answer] # [Common Lisp](http://www.clisp.org/), 68 bytes ``` (defun x(s)(cond((search s "ROYGBRO")1)((search s "BGYORBG")-1)(0))) ``` [Try it online!](https://tio.run/##Zc0xCsMwDIXhvacQnvSGQnMFLR4N2jwGJyWB4Ia4hdzeEZkSd/349ZSWuay18jC@f5l2LuD0yQNzGfstTVTIaYheNDh0uLL4GFS8w9P8BaDyus35S7zbjViPx0WsbkREG4lqcyC6mZemsq@thL9tPaUe "Common Lisp – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 63 bytes ``` import StdEnv,Text $s=map((>)0o indexOf s)["ROYGBRO","BGYORBG"] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wnJLWihEul2DY3sUBDw07TIF8hMy8ltcI/TaFYM1opyD/S3SnIX0lHyck90j/IyV0p9n9wSSJQu62CioISUE7p/7/ktJzE9OL/up4@/10q8xJzM5MhnICcxJK0/KJcAA "Clean – Try It Online") `[True, True]` for no special noises, `[True, False]` for counterclockwise, `[False, True]` for clockwise. [Answer] # Japt, ~~17~~ 14 bytes Takes the colours as input, in lowercase. Returns `0` for clockwise, `1` for counterclockwise or `-1` if there's no combo. ``` `ygß`ê qÔbøU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=YJ55Z9+WYOogcdRi+FU=&input=InJibyI=) --- ## Expanation ``` `...` :Compressed string "roygbrow" ê :Palindromise qÔ :Split on "w" b :Index of the first element ø : That contains U : The input string ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~53~~ 36 bytes ``` ->n{"\a\fDch+".index(""<<n%111)&./3} ``` [Try it online!](https://tio.run/##DclBDoIwEAXQq5gmEolDzZ8ZdujKW5QuUGx0QUOakEiAsxe276XpNedwz9UjLqbt2vB8f6/G/mL/@V@MaZp4BlAW9iZbdmClWphUQSJCYCGWw8CEWkmPE4a3Qzcua1rHk0sUXPJ@yzs "Ruby – Try It Online") Input: a 3-digit integer, where the digits represent colors: * 1 - red * 2 - orange * 3 - yellow * 4 - green * 5 - blue Output:0 for clockwise, 1 for counterclockwise, `nil` otherwise. [Answer] # [C (gcc)](https://gcc.gnu.org/), 55 bytes Returns 0 for none, -1 for CCW and 1 for CW. ``` f(char*s){s=!strstr("ORBGYOR",s)-!strstr("ROYGBRO",s);} ``` [Try it online!](https://tio.run/##PY6xCsMwDET3foVqCNiJM3ROs3jJKNAW2g7BJamHpsUOWUK@XZVLKQh09ySO8/XkPfOo/WOIZTJbao9piTJaIbmuR1I2mfoPCfvOEWbY7BzmBZ5DmHUWQ5y8hRwEZSlmNbAdAMZX/J5De2ognPOX7Koy8I7CR62KBC0U9@usbA5ZL@FmYdQ/aUxz2JnJIUsddo64p46lBktDRhRG@AE "C (gcc) – Try It Online") ]
[Question] [ # The Task Given an input positive integer `n` (from 1 to your language's limit, inclusively), return or output the maximum number of distinct positive integers that sum to `n`. # Test Cases Let `f` define a valid function according to the task: The sequence for `f`, starting at 1: ``` 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, ... ``` As a larger test case: ``` >>> f(1000000000) // Might not be feasible with brute-forcers 44720 ``` # Test Code For any test cases not explicitly given, the output of your code should match the result of the following: ``` public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.println((int) Math.floor(Math.sqrt(2*x + 1./4) - 1./2)); } } ``` [Try it online!](https://tio.run/##TU67DsIwDNz7FR4TEOEhNsQHMDB1RAwhBEhJnZK4UIT49mJQQNxy1t357Epf9Sg0Fqv9uXd1EyJBxZpqyXlVGo1o46Jv2p13BozXKcFaO4RHUQAjG4k0MV2D20PNtigpOjxutqDjMUlOQ0auhGRgCWhvX0GU90S2Vg7l4hd2SNBxLhmFtqMVkvhz80ZoSTV8jTwKwST5QTqpgw8his@YLpHEbNDBEKZqPJcwevNM5q5nUTz7fjr54AU "Java (OpenJDK 8) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ÅTg< ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cGtIus3//0bGAA "05AB1E – Try It Online") Perfect tool for the job. `ÅT` yields the list of **Å**ll **T**riangular numbers up to and including **N** (unfortunately includes 0 too, otherwise it would be 3 bytes), `g<` gets the len**g**th and decrements it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` R+\»ċ ``` [Try it online!](https://tio.run/##y0rNyan8/z9IO@bQ7iPd/w@3P2pa8/@/kQEA "Jelly – Try It Online") Somewhat efficient. This sequence increments at triangular numbers, so this just counts how many triangular numbers are smaller than *n*. Explanation: ``` # Main link R # Range, generate [1..n] +\ # Cumulative sum (returns the first n triangular numbers) » # For each element, return the maximum of that element and 'n' ċ # How many elements are 'n'? (implicit right argument is n) ``` [Answer] # [Haskell](https://www.haskell.org/), 26 bytes *-2 bytes thanks to H.PWiz.* ``` (!!)$do x<-[0..];x<$[0..x] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0NRUVMlJV@hwkY32kBPL9a6wkYFxKiI/Z@bmJmnYKtQUJSZV6KgopCbWKCQphBtqKdnbBD7/19yWk5ievF/3eSCAgA "Haskell – Try It Online") This returns the **nth** element of the whole numbers where each **i** is replicated **i + 1** times. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 36 bytes ``` <>(())({()<(({}())){<>({}[()])}>{}}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/38ZOQ0NTU6NaQ9NGQ6O6FsjWrAaKVddGa2jGatbaVdfWav7/b2kAAA "Brain-Flak – Try It Online") This uses the same structure as the standard division algorithm, except that the "divisor" is incremented every time it is read. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 19 bytes ``` n->((8*n+1)^.5-1)\2 ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P105Dw0IrT9tQM07PVNdQM8bof1p@kUYeUNJQR8HIQEehoCgzrwQooKSgawck0jTyNDU1uSCiSnpgoATjGxrAAEI5QkxT8z8A "Pari/GP – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 82 bytes Whitespace added for "Readability" ``` (()) { {} ((({})[[]])) ([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} }{}{}{} ([]<>) ``` [Try it online!](https://tio.run/##HYsxDoBACAR7XmG5FBZak/vIheIsTIzGwpbwdoSjWWYWjm9c73o@444AmImMlhxzmgnAnHtXrW6ankbqtrFCGrOlSJTm5gaIeSsyT64gqsJrQdf8iNj2Hw "Brain-Flak – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ×8‘½’:2 ``` [Try it online!](https://tio.run/##y0rNyan8///wdItHDTMO7X3UMNPK6P///0bGAA "Jelly – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ḥ+4ݤ½_.Ḟ ``` [Try it online!](https://tio.run/##ARwA4/9qZWxsef//4bikKzTEsMKkwr1fLuG4nv///zIz "Jelly – Try It Online") This is longer than ~~Dennis’~~ and DJ’s, but this time **on purpose**. Very, very *efficient*. [Answer] # [R](https://www.r-project.org/), 28 bytes ``` function(n)rep(1:n,1:n+1)[n] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPsyi1QMPQKk8HiLUNNaPzYv@naRgZa/4HAA "R – Try It Online") Creates the vector of `1` repeated `2` times, `2` repeated `3` times, ..., `n` repeated `n+1` times and takes the `nth` element. This will memory error either because `1:n` is too large or because the repeated list with `n*(n+1)/2 - 1` elements is too large. # [R](https://www.r-project.org/), 29 bytes ``` function(n)((8*n+1)^.5-1)%/%2 ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPU0PDQitP21AzTs9U11BTVV/V6H@ahpGx5n8A "R – Try It Online") Computes the value directly, using the formula found in [alephalpha's answer](https://codegolf.stackexchange.com/a/152569/67312). This should run with no issues, apart from possibly numerical precision. # [R](https://www.r-project.org/), 30 bytes ``` function(n)sum(cumsum(1:n)<=n) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs7g0VyO5NBdEGVrladrY5mn@T9MwMtb8DwA "R – Try It Online") Counts the triangular numbers less than or equal to `n`. This'll possibly memory error if `1:n` is large enough -- for instance, at `1e9` it throws `Error: cannot allocate vector of size 3.7 Gb`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 8 bytes ``` +/+\∘⍳<⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRtfe2YRx0zHvVutnnUtQgopmBsAAA "APL (Dyalog Unicode) – Try It Online") [Answer] # TI-Basic, 12 bytes ``` int(√(2Ans+1/4)-.5 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 18 bytes ``` x=>(x-~x)**.5-.5|0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1k6jQreuQlNLS89UV8@0xuB/cn5ecX5Oql5OfrpGmoahAQxoanKl5RdpVNgaWlfYGBoASW1tTVTFFZqa/wE "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), 8 bytes Closed formula solution. ``` *8Ä ¬É z ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=KjjEIKzJIHo=&input=MTAwMDAwMDAwMA==) --- ## Explanation Multiply by 8, add 1 (`Ä`), get the square root (`¬`), subtract 1 (`É`) and floor divide the result by 2 (`z`). --- ## Alternative, 8 bytes Port of [DJMcMayhem's Jelly solution](https://codegolf.stackexchange.com/a/152530/58974). ``` õ å+ è§U ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SDlKyDop1U=&input=MTAwMDAwMA==) Generate an array of integers (`õ`) from 1 to input, cumulatively reduce (`å`) by addition (`+`) and count (`è`) the elements that are less than or equal to (`§`) the input (`U`). [Answer] # Befunge, ~~32~~ 20 bytes ``` 1+::1+*2/&#@0#.-`#1_ ``` [Try it online!](http://befunge.tryitonline.net/#code=MSs6OjErKjIvJiNAMCMuLWAjMV8&input=MTAwMDAwMDAwMA) [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~70~~ ~~56~~ 48 bytes ``` {([(({}[({}())()])[()])]<>){<>({}())}{}<>{}}<>{} ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v@/WiNaQ6O6NhqINTQ1NTRjNaNBRKyNnWa1jR1EtLa61sauuhZM/P//39IAAA "Brain-Flak (BrainHack) – Try It Online") ## Explanation The main part of this is the following snippet that I've written: ``` ([(({})[()])]<>){<>({}())}{}<>{} ``` This will do nothing if the TOS is positive and will switch stacks otherwise. It is *super* stack unclean but it works. Now the main part of the program subtracts increasingly large numbers from the input until the input is non-positive. We start the accumulator at 1 each time subtracting 1 more than the accumulator from the input. ``` ({}[({}())()]) ``` We can put that inside the snippet above ``` ([(({}[({}())()])[()])]<>){<>({}())}{}<>{} ``` That is put in a loop so it executes until we switch stacks. Once the loop finishes we retrieve the accumulator by switching stacks and removing the junk. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` lh{I#./ ``` [Try it online!](https://tio.run/##K6gsyfj/Pyej2lNZT///fyNjAA "Pyth – Try It Online") Filter-keep the integer partitions which are `I`nvariant over deduplication, grab the `h`ead and obtain its `l`ength. ### Validity proof Not very rigorous nor well-worded. Let **A = a1 + a2 + ... + an** and **B = b1 + b2 + ... + bm** be two distinct partitions of the same integer **N**. We will assume that **A** is the *longest* unique partition. After we deduplicate **B**, that is, replace multiple occurrences of the same integer with only one of them, we know that the sum of **B** is less than **N**. But we also know that the function result is increasing (non-strictly), so we can deduce that the longest unique partition **A** always has at least the same amount of elements as the count of unique items in other partitions. [Answer] # [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 49 bytes ``` ....).... ...2)2... ..)1/)8.. .)1/)IE/. @^)1_+/i. ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8INEEEFxAbaRpBWJqG@poWIBaI4emqr8flEKdpGK@tn6n3/7@RMQA "Triangularity – Try It Online") ### How it works Triangularity requires the code to have a triangular distribution of the dots. That is, the length of each row must be equal the number of rows multiplied by 2 and decremented, and each row must have (on each side) a number of dots equal to its position in the program (the bottom row is row 0, the one above it is row 1 and so forth). There are only a couple of commands, and any character other than those listed on the 'Wiki / Commands' page is treated as a no-op (extraneous dots don't make affect the program in any way, as long as the overall shape of the program stays rectangular). Note that for two-argument commands, I've used **a** and **b** throughout the explanation. Keeping that in mind, let's see what the actual program does, after removing all the extraneous characters that make up for the padding: ``` )2)2)1/)8)1/)IE/@^)1_+/i | Input from STDIN and output to STDOUT. ) | Push a 0 onto the stack. Must precede integer literals. 2 | Push ToS * 10 + 2 (the literal 2, basically). )2 | Again, push a 2 onto the stack. This can be replaced by D | (duplicate), but then the padding would discard the saving. )1 | Literal 1. / | Division. Push b / a (1 / 2). )8)1 | The literal 8 and the literal 1 (lots of these!). / | Division. Push b / a (1 / 8). )IE | Get the 0th input from STDIN and evaluate it. / | Divide it by 1 / 8 (multiply by 8, but there isn't any | operand for multiplication, and I'm not willing to add one). @ | Add 1 to the result. ^ | Exponentiation. Here, it serves as a square too. )1_+ | Decrement (add literal -1). / | Divide (by 2). i | Cast to an integer. ``` An alternate solution, and shorter if padding would not be necessary: ``` ....).... ...2)1... ../DD)I.. .E/)4)1/. +^s_+i... ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/Xw8INEEEFxAbaRpCWPouLpqeIJarvqaJpqG@Hpd2XHG8diZQ9v9/I2MA "Triangularity – Try It Online") [Answer] # PowerShell 3.0, 45 bytes ``` [math]::Sqrt(2*$args[0]+.25)-.5-replace'\..*' ``` The math call hurt and PS's banker's rounding is the actual devil (hence needing regex to truncate to save a byte) but this seems pretty alright. [Answer] # [Java (JDK)](http://jdk.java.net/), 28 bytes ``` n->~-(int)Math.sqrt(8*n+1)/2 ``` [Try it online!](https://tio.run/##bU7BTsMwDL33K6xJldJ1Ddu4IJVN4s7EYeKEOIR2KS6tExJ3UoXKr5d0Gwc0fHn2e89@rtVRZXX5MWJrjWOowyw7xkbO8@iK0x0VjIYm0XZvDRZQNMp72Ckk@IoALqxnxQGOBktogyb27JCql1dQrvLJyQrwaKh6JuX6J3twio0DDZuRsu13JpA42Sl@l/7TsbibU7pKbtZjflrUwTo5AGEDqzzAfcDlMnRp@nsdYN97PrTSdCxtiGctZvFtCdkW4nUZ02wBuAAtlbVN/@CnbwQmyTliiP670JD46w@hlzovDtEw/gA "Java (JDK) – Try It Online") Because the example was really not well golfed :p ## Credits * -2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŒPfŒṗṪL ``` Runs roughly in **O(2n)** time. [Try it online!](https://tio.run/##ASMA3P9qZWxsef//xZJQZsWS4bmX4bmqTP8yMFLCtcW8w4figqxH/w "Jelly – Try It Online") ### How it works ``` ŒPfŒṗṪL Main link. Argument: n ŒP Powerset; yield all subarrays of [1, ..., n], sorted by length. Œṗ Yield all integer partitions of n. f Filter; keep subarrays that are partitions. Ṫ Tail; extract the last result. L Compute its length. ``` [Answer] # JavaScript (ES7), ~~22~~ 19 bytes ``` n=>(8*n+1)**.5-1>>1 ``` -3 bytes thank to ETHproductions. --- ## Try it ``` o.innerText=(f= n=>(8*n+1)**.5-1>>1 )(i.value=1000000000);oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` --- ## Explanation Multiply the input by 8 and add 1, raise that to the power of .5, giving us the square root, subtract 1 and bitshift the result right by 1. [Answer] # Python 2/3, 32 bytes Python implementation of the closed form formula ``` lambda n:int((sqrt(1+8*n)-1)//2) ``` The integer division `//2` rounds towards zero, so no `floor( )` required [Answer] # [Haskell](https://www.haskell.org/), 28 bytes Kinda boring, but it~~'s quite shorter than the other Haskell solution and~~ has a really nice pointfree expression. Unfortunately I couldn't get it any shorter without the type system getting in the way: ``` g x=floor$sqrt(2*x+0.25)-0.5 ``` [Try it online!](https://tio.run/##DcM7DoAgDADQq3Rw8BMJwTDi4klIrEjEoqUDt0df8k5fLkyptQDVHSln7srL0puxTloZO8xa2Xb7SOAgoGyZBEkKrKuDhyMJKAh/Rr83s3w "Haskell – Try It Online") ### Pointfree, 33 bytes ``` ceiling.(-0.5+).sqrt.(0.25+).(2*) ``` ### Alternatively, 33 bytes Same length as the pointfree version, but much more interesting. ``` g n=sum[1|x<-scanl1(+)[1..n],n>x] ``` [Answer] # [Milky Way](https://github.com/zachgates/Milky-Way), 12 bytes ``` '8*1+g1-2/v! ``` ## Explanation ``` code explanation value ' push input n 8* push 8, multiply 8n 1+ add 1 8n+1 g square root sqrt(8n+1) 1- subtract 1 sqrt(8n+1)-1 2/ divide by 2 (sqrt(8n+1)-1)/2 v floor floor((sqrt(8n+1)-1)/2) ! output ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~7~~ 5 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` Đř△>Ʃ ``` Explanation: ``` Implicit input Đř△ Gets a list of the first N triangle numbers > Is N greater than each element in the list? (returns an array of True/False) Ʃ Sums the list (autoconverts booleans to ints) ``` --- Faster, but longer way # [Pyt](https://github.com/mudkip201/pyt), ~~11~~ 9 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` Đ2*√⌈ř△>Ʃ ``` Explanation: ``` Đ2*√⌈ř△ Gets a list of triangle numbers up to the ceiling(sqrt(2*N))-th > Is N greater than each element of the list? (returns an array of True/False) Ʃ Sums the array ``` --- Alternative way - port of [Shaggy's answer](https://codegolf.stackexchange.com/a/152535/77078) # [Pyt](https://github.com/mudkip201/pyt), ~~8~~ 7 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` 8*⁺√⁻2÷ ``` [Answer] # [J](http://jsoftware.com/), 11 bytes ``` 2&!inv<.@-* ``` [Try it online!](https://tio.run/##y/r/P81WT8FITTEzr8xGz0FX639qcka@QpqCoYKRgrGCiYKpgpmCuYKFgqWCoYGCoaGCoZGCoTGQDQP/AQ "J – Try It Online") ``` 2&!inv solve [x choose 2 = input] -* minus 1 <. and floor ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 111 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_integer_from_STDIN][T T T _Retrieve_input][S S S T S S S N _Push_8][T S S N _Multiply][S S S T N _Push_1][T S S S _Add][S S T T N _Push_n=-1][N S S N _Create_Label_SQRT_LOOP][S S S T N _Push_1][T S S S _Add][S N S _Duplicate_n][S N S _Duplicate_n][T S S N Multiply][S T S S T S N _Copy_0-based_2nd_(the_input)][S S S T N _Push_1][T S S S _Add][T S S T _Subtract][N T T N _If_negative_jump_to_Label_SQRT_LOOP][S S S T S N _Push_2][T S S T _Subtract][S S S T S N _Push_2][T S T S _Integer_divide][T N S T _Print_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIA2EuTpCoAkhUAQQ4Obm4UETAPE4owYkkwwlmcIIFwMZwwlhACFT9/7@hAQwAAA) (with raw spaces, tabs, and new-lines only). **Explanation in pseudo-code:** Uses the formula: $$f\_n = \left\lfloor\frac{\sqrt{8n + 1} - 1}{2}\right\rfloor$$ NOTE: Whitespace doesn't have a square-root builtin, so we have to do this manually. ``` Integer i = read STDIN as integer i = i * 8 + 1 Integer n = -1 Start SQRT_LOOP: n = n + 1 If(n*n < i+1): Go to next iteration of SQRT_LOOP n = (n - 2) integer-divided by 2 Print n as integer to STDOUT ``` [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 16 bytes ``` 2*14/+12/^12/-_N ``` [Try it online!](https://tio.run/##K8ssKa78/99Iy9BEX9vQSD8OiHXj/f4DhYwB "Vitsy – Try It Online") Might as well add my own contribution to the mix. This is shorter than the partition iterations solution in Vitsy. [Answer] # [Oasis](https://github.com/Adriandmen/Oasis), 14 bytes ``` n8*1+1tm1%_b+0 ``` [Try it online!](https://tio.run/##y08sziz@/z/PQstQ27Ak11A1Pknb4P///4YGBgYA "Oasis – Try It Online") **How?** ``` n8*1+ 8n + 1 1tm sqrt 1%_ integer? b+ add f(n-1) 0 f(0) is 0 ``` This is a recursive solution that increments the result when it encounters a triangular index, starting with 0 for the input 0. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 19(++) bytes ``` $_=0|-.5+sqrt$_*2+1 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tagRlfPVLu4sKhEJV7LSNvw/39DAxj4l19QkpmfV/xftwAA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 27 bytes Three for the price of one. I am disappointed that I can't go shorter. ``` ->n{a=0;n-=a+=1while n>a;a} ``` ``` ->n{((8*n+1)**0.5-1).div 2} ``` ``` ->n{((n-~n)**0.5-0.5).to_i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtHWwDpP1zZR29awPCMzJ1Uhzy7ROrGWCySnoZGnW5enqaVloGeqC8SaeiX58ZkwOQutPG1DqKShpl5KZpmCUe3/AoW0aEMDGIjlKlDQMNTTA4po6uUmFiiopf0HAA "Ruby – Try It Online") (to select the function, add f= in front of it) ]
[Question] [ # Can the Tune be Played? ## Explanation A broken musical keyboard has keys labelled with positive integers. It is broken in two ways: 1. It takes a long time to process key presses: after pressing the key labelled with the number \$n\$, there is a gap of \$n\$ seconds before the \$n\$th note is heard. So, for example, the \$5\$th key must be pressed \$5\$ seconds early for its note to sound in the right place. 2. Only one key can be **pressed** at a time. Because of these problems, some tunes cannot be played on the keyboard. To understand why, let us first define a tune: A tune will be defined as a list of positive integers representing the order in which notes should be **heard** (not the order in which keys should be pressed). A number \$n\$ represents the note heard when the \$n\$th note on the keyboard is pressed. This definition does not allow for rests, chords or notes of differing lengths, so you can imagine that all notes are played at a speed of exactly one note per second. ## Invalid Tune Example An example of a tune would be `[3, 1, 2]`. This means that the note \$3\$ should be heard, then, one second later, the note \$1\$, and a second after that, the note \$2\$. However, when trying to play this tune on the keyboard, there is a problem. To understand why, shift each of the numbers \$n\$ in the tune back by \$n\$ spaces. The result represents the order in which keys must be pressed for the notes to sound in the correct place: ``` Tune [ 3 , 1 , 2] Index -3 -2 -1 0 1 2 How keys would be pressed [3 , 1&2 ] ``` The problem here is that keys \$1\$ and \$2\$ must be pressed at the same time for their notes to sound in the right place, but it is impossible to press two keys at once on the keyboard. Therefore, the tune `[3, 1, 2]` cannot be played. ## Valid Tune Example An example of a valid tune would be `[2, 1, 3]`. To see why, shift the numbers back to find out when the keys must be pressed: ``` Tune [ 2 , 1 , 3] Index -2 -1 0 1 2 How keys would be pressed [2 , 3 , 1 ] ``` Having shifted each of the numbers back (\$2\$ moved back \$2\$ spaces, \$1\$ moved back \$1\$ space and \$3\$ moved back \$3\$ spaces), none of them have landed in the same position. Therefore, this tune can be played on the broken keyboard: the keys would be pressed in the order `[2, 3, 1]`. ## Task Your task is to write a program which takes as input a list representing a tune, and outputs a [truthy/falsy](https://codegolf.meta.stackexchange.com/a/19205/110951) value depending on whether or not the tune can be played on the broken keyboard. ## Assumptions * You can assume that input lists will always contain only positive integers. * You can assume that input lists will always have at least one element. * You can assume that inputs will always be lists. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ## Test Cases ``` [1, 2, 3] -> False [3, 1, 2] -> False [3, 2, 1] -> True [6, 4, 7, 3, 5, 2, 1] -> True [4, 7, 6, 5, 2, 1, 3] -> False // 6 and 4 land in same position [4, 6, 4, 2, 1, 4] -> False [2, 1, 6, 4, 4, 4] -> False // 4 and 1 [2, 1, 6, 4, 2, 4] -> True ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer (as measured in bytes) wins! [Answer] # JavaScript (ES6), 30 bytes Returns a Boolean value. ``` a=>a.every(b=(n,i)=>b[i-n]^=1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RL7UstahSI8lWI08nU9PWLik6UzcvNs7WUPN/cn5ecX5Oql5OfrpGmka0oY6CkY6CcawCEtDUVNDXV3BLzClO5UJTbqyjANJBgnKg6YZYlIcUlWKoNtNRMNFRMAc6R0fBFKoTt2qIUjO4UpAvkJzyHwA "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/blob/v2.6.0/documents/knowledge/elements.md), 4 [bytes](https://github.com/Vyxal/Vyxal/blob/master/docs/codepage.txt) ``` ż-Þu ``` My first Vyxal answer. Similar approach as the other answer. [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLFvC3DnnUiLCIiLCJbNiw0LDcsMyw1LDIsMV0iXQ==) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyIiLCLilqEoROKCtGAgLT4gYOKCtCIsIsW8LcOedSIsIiwiLCJbMywyLDFdXG5bNiw0LDcsMyw1LDIsMV1cblsyLDEsNiw0LDIsNF1cblsxLDIsM11cblszLDEsMl1cbls0LDcsNiw1LDIsMSwzXVxuWzQsNiw0LDIsMSw0XVxuWzIsMSw2LDQsNCw0XSJd). **Explanation:** ``` ż # Push a list in the range [1, input-length] - # Subtract it from the input at the same positions Þu # Check if all values in this list are unique # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), 34 bytes Or **[R](https://www.r-project.org/)>=4.1, 27 bytes** by replacing the word `function` with a `\`. ``` function(v)all(table(seq(!v)-v)<2) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jTDMxJ0ejJDEpJ1WjOLVQQ7FMU7dM08ZI83@aRrKGoY6CkY6CsaamsoKunYJbYk5xKhdI3FhHASSFTRyo3hAqHlJUChE201Ew0VEwB5qko2CKXQlE3gwuj2brfwA "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` _JQƑ ``` [Try it online!](https://tio.run/##y0rNyan8/z/eK/DYxP@H2x81rfn/P9pQx0jHOFZHIdpYB8iEMIx0DEEMMx0THXMdYx1TmACIawbhAvUAAA "Jelly – Try It Online") ``` _J -- difference between each element and its 1-based index Ƒ -- is this list invariant under: Q -- removing duplicates? ``` [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes -7 thanks to Jonathan :) ``` lambda n:n[len({a-n.index(a)for a in n}):] ``` [Try it online!](https://tio.run/##RY7NCoMwEITvPsUcE9gW1P6A4LVP0Jv1kGKCAbuKpqCUPnuatLbdwzLzsbO7w@LanjNvyovv1O3aKHDBVadZPNSGt5YbPQslTT9CwTL4KYva2@k83l27lGtmLoLXsAYzdDdpnFToSRJjTk8uJkWVEjJCXhOqnBDdKgNNozwQdoRjmCHs//jDDj8Wd8giQahhtOzeJwjfp4QREUjpXw "Python 2 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~52~~ 51 bytes ``` j=>j.Count==j.Select((x,y)=>y-x).Distinct().Count() ``` [Try it online!](https://tio.run/##jc0xC8MgFATgvb/C0QdGMBkbXRI6ZevQvWLgiTyhGppQ@tutUNrZ9fjuzqbOJiyXjey4YMojUjaC3WMMhq1MF6@Nl1PcKGvt5dUFZzPnuzhAm6PbQc61hVRD@DIO5XyaIqUYnLw9MLsFyfGVk3uy/wV7KdGL4Q3QhIeKVTtW7bj/LZcP "C# (Visual C# Interactive Compiler) – Try It Online") Nice thing about how verbose C# is is that it is makes the code relatively self-explanatory. The downside is that it makes it hard to golf in. Interactive Compiler C# lets us cheat a bit by removing all the boilerplate. A technical breakdown: If we can show that two keys need to play at the same time, we know it cannot be played. This approach tackles this by determining when they should play and checking for any duplicates. If we store when they should play and make that list distinct, all duplicates will be removed, however, the number of elements in the list will decrease as a result. By comparing that count against the original's, we get the true/false value we need. To do this, we use the index overload of Linq's Select. This use of Select converts our collection of integers into another collection of integers, but with different values, that is, the original value subtracted from its respective index. Distinct and Count are both self-explanatory. Saved one byte by taking a List instead of int[]. 'Count' is a property on a List; the eqivalent on an array is 'Length,' which is one extra byte. On an IEnumerable, 'Count' is a function, which is why 'Count' at the end requires the parens. It's not the best naming choices, but I have no control over that. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes ``` i!=##&@@(i=0;i++-#&/@#)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P1PRVllZzcFBI9PWwDpTW1tXWU3fQVlT7X9AUWZeSbSyrl2ag3KsWl1wcmJeXTVXtaGOkY5xrQ5XtbEOkAlhGOkYghhmOiY65jrGOqYwARDXDMIF6uGq/Q8A "Wolfram Language (Mathematica) – Try It Online") ``` &/@# for each: i=0;i++-# index minus value i!=##&@@( ) all distinct (and unequal to length) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes ``` tf-&=sqa ``` [Try it online!](https://tio.run/##y00syfmfkKlQEuWnYK9QoacQq/C/JE1Xzba4MPF/SOz/aEMdBSMdBeNYrmhjHQUQB8ICihkCWWY6CiY6CuZABToKpnBRiJAZXAis30DfAAA "MATL – Try It Online") 0 for 🎵🎶🎹 1 for broken keyboard leads to broken ❤️. **Explanation**: `tf-` : Subtract from each input element its (1-based) index `&=` : Compare each value against the whole array, giving a boolean matrix `s` : sum each column to get a row vector of sums `q` : Decrement each sum by 1 to take away the self-equality 1s `a` : Check if there are any non-zero values still --- A more obvious way is `tf- 8#uqa` (count how many times each unique value occurs in `input - indices` and see if it's all 1), but unfortunately the need for space between `-` and `8` pushes it to 9 bytes. Edit: [Luis Mendo's answer on another question](https://codegolf.stackexchange.com/a/243745/8774) taught me the trick of `&` at the end, to print only the top of the stack, with which this can instead be `tf-&uqa&` - also 8 bytes. Only works on the current master of MATL though - neither TIO nor [MATL Online](https://matl.suever.net/) have the `&u` feature available yet. Another 9-byter is `tf-&=XRaa`. [Answer] # APL+WIN, 20 bytes Prompts for tune. 1=true, 0=false ``` 0=+/2=/m[⍋m←n-⍳⍴n←⎕] ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4Gttr6RrX5u9KPe7lygcJ7uo97Nj3q35AHZQKWx/4GquP6ncRkqGCkYc6VxGSsAWWDaSMEQSJspmCiYKxgrmEL5IJ4ZhKdgDAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~26~~ 23 bytes ``` ~v=allunique(v-keys(v)) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v67MNjEnpzQvs7A0VaNMNzu1slijTFPzv0NxRn65Ql20oY6CkY6CcawCElB2S8wpTuWCKTHWUQCpQlWigKEGaIwhmpqQolKEEjMdBRMdBXOgZToKplDlaEog8mZweZDDYDb9BwA "Julia 1.0 – Try It Online") *-3 bytes thanks to @MarcMush* `true` for can be played, `false` otherwise. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes ``` \d+(?=((,)|.)*) $*1$#2$* D`1+ ,\B ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFW8PeVkNDR7NGT1NLk0tFy1BF2UhFi8slwVCbSyfG6f9/Qx0jHWMuYx0gDSSNdAy5zHRMdMx1jHVMwTwQ2wzC1jEGAA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs a truthy value if the tune can't be played and a falsy value if it can. Explanation: ``` \d+(?=((,)|.)*) ``` Match values but also count the number of following values. ``` $*1$#2$* ``` Convert to unary and add on the number of following values. (This is easier to do than subtracting from number of preceding values.) ``` D`1+ ``` Delete duplicates. ``` ,\B ``` Check for a deletion. 19 bytes in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1: ``` \d+ *_$;&* D`_+ ,\B ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8mRZtLK17FWk2LyyUhXptLJ8bp/39DHSMdYy5jHSANJI10DLnMdEx0zHWMdUzBPBDbDMLWMQYA "Retina – Try It Online") Link includes test cases. Explanation: In Retina 1 `$;&` automatically counts the number of remaining matches i.e. the number of following values. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` UMθ⁻κι⊙θ⊖№θι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/983scA5Pzc3MS9Fo1BHwTczr7RYI1tHIVNT05oroCgzr0TDMa8SJOWSmlyUmpuaV5KaouGcXwqUKAQrAyr8/z862kRHwVxHwUxHwVRHwUhHwVBHwTg29r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if the tune can't be played and nothing if it can. Explanation: ``` UMθ⁻κι ``` Subtract each element's value from its index. ``` ⊙θ⊖№θι ``` Check whether any of the results were duplicated. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 11 bytes ``` {x~?x-:!#x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxlj0FPhDAQhe/9Fc/oQRO6FcpCQhO9+Qu8EZKtUBaybIu0JN1s3N9ukajRPc2b781k5rXF2V+ePS1ubv0HIa4435Wny1S0ALzYmYO437WyH4QXJzE9VGGGuDJGAi4eqyA5QvMtE8QiXmSGFDk4tr9oAdkK1l3CSOfcaAvGatOovRnajXWyPihfd1Lv1aY2R/Y+K+t6oy1LUp4nOaulpq5T1M1a0TdFx0GeVEPKOEISgVegT3iRg1Wk5BEW+g+FqfgLvU5zIFmENEIeViNsr9zVyn6sPxfAWIgkdRPSDkvpNaw8KozG9svTn+QEXs8=) * `!#x` generate `0..len(input)` * `x-:` subtract the above from the input, "inplace" (i.e. updating `x`) * `x~?` is the above composed of only distinct/unique values? [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~13~~ ~~12~~ 9 bytes ``` L{I.e-bkb ``` [Try it online!](https://tio.run/##K6gsyfj/36faUy9VNyk76X9ltKGCkYKxJldltLECkAlhGCkYghhmCiYK5grGCqYwARDXDMIF6vn/L7@gJDM/r/g/AA "Pyth – Try It Online") ``` L{I.e-bkb L # lambda b: .e-bkb # difference between each element in the list b and its index { # removes duplicates in the list I # invariant? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā-DÙQ ``` [Try it online](https://tio.run/##yy9OTMpM/f//SKOuy@GZgf//RxvrGOoYxQIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I426LodnBv7X@R8dbaxjpGMYqxNtpmOiY65jrGMK5QNJHZCYkY4JkGcIpI2BtDFQ1AhIg9SaQdSCxU2gag3BqmF6gTA2FgA). **Explanation:** ``` ā # Push a list in the range [1, input-length] - # Subtract it from the values in the input at the same positions # Check if all values are unique: D # Duplicate the list Ù # Unquify the copy Q # Check if both lists are still the same # (after which the result is output implicitly) ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 7 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` h╒m-_▀= ``` [Try it online.](https://tio.run/##y00syUjPz0n7/z/j0dRJubrxj6Y12P7/H22sY6RjGMsVbaZjomOuY6xjCuUDSR2QmJGOCZBnCKSNgbQxUNQISIPUmkHUgsVNoGoNwapheoEwFgA) **Explanation:** ``` h # Push the length of the (implicit) input-array ╒ # Pop and push a list in the range [1,length] m- # Subtract these values from the input at the same positions _ # Duplicate this list ▀ # Uniquify the values in the copy = # Check if the two lists are still the same # (after which the entire stack is output implicitly as result) ``` [Answer] # [Factor](https://factorcode.org/), 31 bytes ``` [ [ - ] map-index all-unique? ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVCcWliampecWgxklRQrFBSllpRUFhRl5pUoWHNxVXMpAEG1gqGCkYKxQi2UZwzmI3hGQD6MZ6ZgomAOFDNFEQWJmUHFQObU/o9WiFbQVYgFOqJANzMvJbVCITEnR7c0LxPoHHuF2P9AcQW9/wA "Factor – Try It Online") * `[ - ] map-index` Subtract each index from its element. * `all-unique?` Are they all unique? [Answer] # [Haskell](https://www.haskell.org/), 45 bytes ``` f l|j<-zipWith(-)[1..]l=[x|x<-j,y<-j,x==y]==j ``` [Try it online!](https://tio.run/##fZC9DoIwFIV3nuIMDpoUSLXiQh19AhMHwtBEjMXyE8AEje@OLUS0gbi0yffdnN7Tq6hviVJdd4F6paH7lOVJNtelu4qo58WKR@2rDd2UPMzRcv6IOU@7TMgcHOfCQVnJvMECF0SUYE2wiS24ITB8AvUktWFAwAh2OoFgOzcw2GC0k7dYb9nHMtsOcBhgf@3aWHRjIbh7HISqE2esY6N@V4OO1V2TuSZfO1djjIPvI4DIz2BQ5tIfXYssQVnUspFF7kxb/uwy6WgFsz6YOjNlP9u9AQ "Haskell – Try It Online") We put in *j* the tune as it would be played. Then we check if its product has only *j* as duplicates using a list comprehension. [Answer] # [Pip](https://github.com/dloscutoff/pip), 11 bytes ``` g#=UQ$-*ENg ``` Takes the numbers as separate command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhar05VtQwNVdLVc_dIhIlCJrdEmOgrmOgpmOgqmOgpGOgqGOgrGsVBJAA) ### Explanation ``` g ; List of command-line args EN ; Enumerate: list of [index; element] pairs $-* ; Fold each on subtraction, giving index-element UQ ; Uniquify #= ; Return truthy if the result is the same length as g ; the original list ``` [Answer] # [Matlab](https://www.gnu.org/software/octave/), 33 bytes ``` K=@(x)all(diff(sort(x-find(x)))); ``` find(x) is the array of 1:length(x), and subtracting the index of each note from the notes value produces the new index of when the note is played. By sorting the resulting array and taking the diff of sequential values, we can determine if there is overlap by making sure that there are no 0 differences (indicating two values are overlapping) [Try it online!](https://tio.run/##y08uSSxL/f/f29ZBo0IzMSdHIyUzLU2jOL@oRKNCNy0zLwUoDATW//8DAA "Octave – Try It Online") ]
[Question] [ # Super permutations Input: A string The program should loop through all lengths of the input (decrementing one each time), generate all combinations with replacement of the string, then make permutations out of the generated combinations, and display all of the strings. They can be separated with anything (doesn't need to be a comma) Example for the string 'abc': ``` a, b, c, aa, ab, ac, ba, bb, bc, ca, cb, cc aaa, aab, aac, aba, abb, abc, aca, acb, acc baa, bab, bac, bba, bbb, bbc, bca, bcb, bcc caa, cab, cac, cba, cbb, cbc, cca, ccb, ccc ``` The values don't necessarily have to be sorted. Avoid any standard loop holes. [Answer] # Scratch 3.0, 65 blocks / ~~637~~ 632 bytes [![Part 1](https://i.stack.imgur.com/Z2T10.png)](https://i.stack.imgur.com/Z2T10.png) [![Part 2](https://i.stack.imgur.com/dBCT2.png)](https://i.stack.imgur.com/dBCT2.png) [![Part 3](https://i.stack.imgur.com/YqmpC.png)](https://i.stack.imgur.com/YqmpC.png) [![Part 4](https://i.stack.imgur.com/I5qGC.png)](https://i.stack.imgur.com/I5qGC.png) Look at y'all, having fun with your fancy shmancy permutation functions/map tools. Well, not I! ***No***, not I! When using Scratch, one has to do things themselves! You won't find any built-ins around these parts! *I'm just glad there still ain't any `goto`s ;)* But more seriously, the image is split into 4 parts because *it's just soooo long* Press space to clear the lists before each run And finally, [Try it on~~line~~ Scratch!](https://scratch.mit.edu/projects/362536859/) As SB Syntax: ``` when gf clicked set[c v]to(0 ask()and wait set[L v]to(length of(answer add(1)to[b v repeat((L)-(1 add(0)to[b v end repeat until<(c)=(1 set[s v]to(0 set[l v]to(1 repeat(length of[b v change[s v]by(item(l)of[b v change[l v]by(1 end if<(s)=((L)*(L))>then set[c v]to(1 end set[r v]to( set[l v]to(1 repeat(length of[b v set[r v]to(join(r)(letter(item(i)of[b v])of(answer change[i v]by(1 end add(r)to[o v replace item(1)of[b v]with((item(1)of[b v])+(1 set[j v]to(1 repeat(length of[b v if<(item(j)of[b v])>(length of(answer))>then replace item(j)of[b v]with(1 replace item((j)+(1))of[b v]with((item((j)+(1))of[b v])+(1 end change[j v]by(1 ``` *-5 bytes due to not being a silly billy and removing extranous spaces* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes *-1 byte thanks to a'\_'* ``` ā€ã ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SOOjpjWHF///n5iU/B8A "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṗJ ``` A monadic Link which accepts a list of characters and returns a list of lists of lists of characters. **[Try it online!](https://tio.run/##y0rNyan8///hzule/w@3u///r56YlKwOAA "Jelly – Try It Online")** (footer formats as a grid) ### How? ``` ṗJ - list, S J - range of length of S ṗ - Cartesian power (vectorises) ``` If we must output a flat list of "strings" (lists of characters) [we can add `Ẏ`](https://tio.run/##y0rNyan8///hzuleD3f1/T/c7v3/v3piUrI6AA "Jelly – Try It Online") (tighten) for the cost of a byte. [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f s=init$mapM(\_->s)=<<scanr(:)[]s ``` [Try it online!](https://tio.run/##BcHBDYAgDADAVRrCAx4sYMANnECNqY0oEQihzG@9e5DfK2eRCBxSTUMXbIvZDjezDd4zYe1msuvOUjBVCNB6qgM0RFB4kpKPYsabxVFrPw "Haskell – Try It Online") Here's how it works, using input `s="abc"`: ``` scanr(:)[]s ``` Produces the suffixes of `s`, `["abc","bc","c",""]`, by prepending each character in turn to the front and tracking the intermediate results. ``` mapM(\_->s) ``` Uses the list monad to map each element to `s`, that is, `'xy'-> ["abc","abc"]`, and take multiply them as a Cartesian product, here giving `["aa","ab","ac","ba","bb","bc","ca","cb","cc"]`. ``` mapM(\_->s)=<<scanr(:)[]s ``` Uses `=<<` as `concatMap` to take the function above that uses `mapM` and apply it to each of the suffixes, thereby producing the Cartesian products of copies of `s` numbering from 0 to its length, in a single list. ``` init$ ``` Removes the empty string, produces from the suffix of length `0`. ``` f s= ``` Declares the function. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` gENIã) ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/3dXP8/Bizf//E5OS/wMA "05AB1E – Try It Online") # Explanation ``` gENIã) E # foreach in... g # the input ã # find the cartesian product of... I # the input... N # repeat N ) # wrap the final stack to an array # implicit output of the top element ``` [Answer] # [J](http://jsoftware.com/), 16 bytes ``` a:-.~[:,#\{@#"{< ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/E6109eqirXSUY6odlJWqbf5rcqUmZ@QrpCmoJyYlq/8HAA "J – Try It Online") * `a:-.~` Remove empty boxes from... * `[:,` The flatten of... * `{@#"{` The Catalog (cross prod) of `{@`... * `#\{@#"{<` + `<` The boxed input... + `#"{` Copied this many times... + `#\` 1, 2, ... N, where N is the input length. That is, we copy the input once, then twice, ... then N times, taking the Catalog of each of those. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes ``` ($a=$args)|%{($p=$p|%{$t=$_;$a|%{$t+$_}})} ``` [Try it online](https://tio.run/##HYxBCoQwEATv84pBWqPs/mAZ8CdhIuoeBEMUPMR5e9bspbr6UnG/5nR8520rWCSXHirQtB7D3eYeURAfwSnwH@hfX/BmgxUjchom92anFSGEOrW1O765zcSMxMIdY@HRP7dBasio/AA). Expects input via [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting). [Answer] # [PHP](https://php.net/), ~~176~~ ~~174~~ ~~173~~ ~~171~~ ~~170~~ 166 bytes ``` $c=$t=count($u=array_values(array_unique(str_split($argn))));for($s=1;$i<$t**$t;){$i-$c?:[$s++,$c*=$t,$i=0];for($k=$i++,$j=0;$j<$s;$j++,$k/=$t)echo$u[$k%$t];echo',';} ``` [Try it online!](https://tio.run/##JYxLCsIwAESv4mKk6Q/r1jR05yVKKSVUExuamI8g4tWNKZ3FwGMeY4SJbWeEOURwBs@4DqsnCGyydnqPr0mF2ZEdwiqfYSbO29EZJZM22fuap9CbtgSOnSlkC18U8DT/QNbg3aWHK8sKvEj/FSRrhl1fGOQ2PFhD8WjhUm@8nJKYz1xohB7LEX6gG2VVRr8xilkp/dPGS726WF// "PHP – Try It Online") -4 bytes thanks to @Ismael Miguel. Method: simply count in base N, where N is the number of unique characters in the input string. [Answer] # Python 3, 95 bytes ``` import itertools as i;lambda s:[''.join(p)for l in range(len(s))for p in i.product(s,repeat=l)] ``` [Try it online](https://tio.run/##rcwxDsIwDADAnVdYXepIqAsbqC9BDG6bgFFqW44ZeH0QvIH1hrN3PFROvfNu6gEc2UO1NqAGfKm0LxtBO1/HcXoqC1oq6lCBBZzknrFmwZZ@al/lyVy31xrYjp4tU8w13XqBGf62HcxZAgsOtKzbkFL/AA "Try it online!") [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ 68 bytes ``` f=lambda s,A={''}:s in A and A or f(s,A|{a+c for a in A for c in s}) ``` [Try it online!](https://tio.run/##PY7NCsIwEITP@hQLHtLQUETBQ6GHPod42PxhqE1KEoRS@@wxqdLL7jc77DDTHJ/OXlLS3QtHLhEC67uFkLUNYCz0gFbm6TzoKlufBWsBOkv82QVFwbDSVMT2difIBWFAEHFbXEjyaI@HyRsbIezgfFSyytGUwaDmvUSb3SrU5EzY9UYpnCA6GHFQYCJwUBiM8uXmFcqt41t5o@emaf7Z6Qs "Python 2 – Try It Online") Outputs a set; includes the empty string. # [Python 2](https://docs.python.org/2/), 71 bytes ``` f=lambda s,A=[]:s in A and A or f(s,set(s)|{a+c for a in A for c in s}) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVjH0TY61qpYITNPwVEhMS8FSOYXKaRpFOsUp5ZoFGvWVCdqJyukAcUSIWpAzGQQs7hW839BUWZeCVC1emJSsrrmfwA "Python 2 – Try It Online") If empty string is not allowed... [Answer] # JavaScript (ES7), 90 bytes Returns a Set. ``` s=>new Set([...Array(n=(L=-~s.length)**~-L)].map(_=>(g=n=>n?[s[n%L-1]]+g(n/L|0):'')(n--))) ``` [Try it online!](https://tio.run/##ZcsxCwIhFADgvV/REr53odUaeNHu1igSZp4V9jxUiiDur9vtrR98D/uyxeX7WDmlq2@DbEX25N/Lk6@ghRDHnO0HSIKSfCoiegr1hl03cYVGPO0IZ9lDkDS3gy6aVorvjFkHoI36bnHPGAJxjojNJSopehFTgAGYvTDExR@6WdsP "JavaScript (Node.js) – Try It Online") ### Commented ``` s => new Set( // build a set from [...Array( // an array of n = // n entries, with: (L = -~s.length) // n = L ** (L - 1) ** ~-L // where L is the length of s + 1 )] // .map(_ => // for each entry: ( g = n => // g is a recursive function taking n n ? // if n is not equal to 0: [s[n % L - 1]] // output s[(n mod L) - 1] // or an empty string if it's undefined + g(n / L | 0) // recursive call with floor(n / L) : // else: '' // stop recursion )(n--) // initial call to g; decrement n afterwards ) // end of map() ) // end of Set() ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` FEθXLθ⊕κEι✂⍘⁺ικθ¹ ``` [Try it online!](https://tio.run/##HcuxDsIwDATQX/HoSmHozMZWCaRI/QJjTBs1JK2bwuebpDfe3eOZlDNFs3dWwAetuDnw@SeKd0lTmXHrHAyJVT6Sirxw6WrAa0jl/AcHYwwseKNdxlL7CX089jYs1TbfV3I1oyfb5Rv/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FEθXLθ⊕κ ``` Loop over the substring lengths and raise the length to each power in turn. ``` Eι✂⍘⁺ικθ¹ ``` Loop from each power to double its value and perform base conversion using the input string as the alphabet, then slice off the first character. [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes Total Husk novice, there may be better ways to golf this. ``` Mπŀ¹ ``` [Try it online!](https://tio.run/##yygtzv7/3/d8w9GGQzv///@vlJiUrAQA "Husk – Try It Online") # Explanation ``` ŀ¹ Find the range [1, ..., len(input)] Mπ Map with cartesian power of input ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` ->s{a,*z=s.chars,'';z.product(*a.map{a+z}).map(&:join)-z|[]} ``` [Try it online!](https://tio.run/##HYtLDkAwGAavYuX3qB6AcJHG4mtFkKBpSag6ez1WM4sZs8sz9HUoGnuBZa62XA0wlhFVjmuzdrvakgx8hr6Quzv9LInLaR2XtHBetHcQBKmIRQTgh1Qdtf/iD6@jXhxv9QA "Ruby – Try It Online") [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), ~~5~~ 4 bytes ``` sacb ``` [Try it online!](https://tio.run/##SyotykktLixN/f@/ODE56f//xKRkAA "Burlesque – Try It Online") -1 thanks to DeathIncarnate! ``` sa # Duplicate the input and get it's length cb # Get all combinations of the input characters up to the length of the input ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 32 bytes ``` {flat [\X~] '',|[xx] .comb xx 2} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi0nsUQhOiaiLlZBXV2nJrqiIlZBLzk/N0mhokLBqPa/NVdxYqVCmoJ6YlKyOoKjbv0fAA "Perl 6 – Try It Online") Anonymous code block that takes a string and returns a list of string including the length zero permutation. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` ^LQSl ``` [Try it here!](https://pythtemp.herokuapp.com/?code=%5ELQSl&input=%22abc%22&debug=0) [Answer] # [R](https://www.r-project.org/), 112 bytes ``` function(S,s=sapply)cat(unlist(s(1:nchar(S),function(X)do.call('paste0',expand.grid(s(rep(S,X),strsplit,'')))))) ``` [Try it online!](https://tio.run/##ZY09CsMwDIX3XEQSmNCuhQw9Q5YMXVTbaQ1GEZYD7eldp0OXvunx8X5KW6e27uJr2gRnZ5Oxan6T54q75GQVDc8X8U8uOJP7ZRcK2@g5ZwRlq/EELr6UJYyPkkIvlah9cCFntZjmVB0AfdVWBL4CDccJ3KS74UD/5O6B2gc "R – Try It Online") Things that make you go Argh, strings in R. Expands out to the following ``` cat( # output the results unlist( # collapse the list sapply(1:nchar(S), # for 1 to character length of S function(X)do.call('paste0', # for each row from the grid paste characters together expand.grid( # create permutations sapply(rep(S,X),strsplit,'')))))) # replicate the string X times and split. ``` So we produce a lists of `[['a','b','c']]`, `[['a','b','c'],['a','b','c']]`, `[['a','b','c'],['a','b','c'],['a','b','c']]`. These are feed into `expand.grid` to produce the permutations. Each row of the grid is pasted together with no gaps in the `do.call`. As it is still in a list we apply `unlist` so that cat will be able to output it. [Answer] # [Perl 5](https://www.perl.org/) `-lF`, 48 bytes ``` $"=',';map$k{$_}++||say,glob"{@F}"."{@F,''}"x$#F ``` [Try it online!](https://tio.run/##K0gtyjH9/19FyVZdR906N7FAJbtaJb5WW7umpjixUic9Jz9JqdrBrVZJD0TpqKvXKlWoKLv9/5@YlPwvv6AkMz@v@L@ur6megaHBf90cNwA "Perl 5 – Try It Online") ]
[Question] [ The title pretty much describes it all. Given as input a \$n \times m\$ matrix and an integer \$i\$ create a complete function/program that returns the matrix \$i\$ times clockwise rotated by \$90^\circ\$. **Rules:** * as matrix you can use any convenient representation you like e.g. *a list of lists etc...* * matrix values can be positive and/or negative integer numbers * \$n\$ and \$m\$ are of course always positive integers between 1 and 10 * \$i\$ can be any valid integer which belongs in the following range: \${0...10^5}\$ * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules & winning criteria apply but no "winning" answer will be chosen. **EDIT:** I had to edit the initial question because for some programming languages it takes too long to compute the result for \$i\in\{0...10^7\}\$. There is a workaround to it but since it's a code-golf just make sure that it simply runs successfully for at least \$i\in\{0...10^5\}\$. **Some test cases:** ``` ==== example 1 ==== Input: 5 [[1, 3, 2, 30,], [4, 9, 7, 10,], [6, 8, 5, 25 ]] Expected Output: [[ 6 4 1], [ 8 9 3], [ 5 7 2], [25 10 30]] ==== example 2 ==== Input: 100 [[1]] Expected Output: [[1]] ==== example 3 ==== Input: 15 [[150, 3, 2], [ 4, -940, 7], [ 6, 8000, 5]] Expected Output: [[ 2 7 5], [ 3 -940 8000], [ 150 4 6]] ==== example 4 ==== Input: 40001 [[1, 3, 9]] Expected Output: [[1], [3], [9]] ``` ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes ``` ⌽∘⍉⍣⎕⊢⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jnr2POmY86u181Lv4Ud/UR12LgCRI6r8CGBRwPWqbCBTyCvb3U1CPjjbUUTDWUTACkgaxOgrRJjoKljoK5joKhmCumY6ChY6CKVCBqUJsrDqXKRcOU0CShgYGWKRBsqYGOiBhoEUKRiBjFRSA9uhamoCEzSECIJsMDEACpmCzTHEYBXauJUiJiQEIGAIA "APL (Dyalog Unicode) – Try It Online") `⎕` prompt for matrix expression from stdin `⊢` yield that `⎕` prompt for \$i\$ expression from stdin `⍣` do the following that many times `⍉` transpose `∘` and then `⌽` mirror [Answer] # [J](http://jsoftware.com/), 7 bytes ``` |:@|.^: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/a6wcavTirP5rcqUmZ@QrZOoZK5hAmOq6urrqEKaBQhoOGUOcMkY4ZYxxm2ZgALfqPwA "J – Try It Online") An adverb train. Right argument is the matrix, left argument is the repetition count. ### How it works ``` |:@|.^: ^: Repeat the function: |. Reverse vertically @ and then |: Transpose Absent right argument to `^:`: bind to the left argument (repeat count) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes Naive implementation. There might be a shorter way I'm not aware of. ``` ṚZ$¡ ``` [Try it online!](https://tio.run/##y0rNyan8///hzllRKocW/j/c7v2oaU3k///R0YamBjoKQGAMJI1idbgUohUUTHQUdC1NQOLmUBEzHQULAwOQiGls7H9DUwA "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` (!!).iterate(foldr(zipWith$flip(++).pure)e) e=[]:e ``` [Try it online!](https://tio.run/##dYw5DsIwFAX7nOJFSmErn4gtbFLOQWFcWOGbWJhgOabh8Jj0iCmmGs1gpjt7n213yaIsZeMSR5NY2Ke/RvF24ezSUFnvgqhr2YRXZMmy4E7pE@eHcSM6hOjGhAoWSq0IG8J69lJTgR/UlnAk7AmrP8GOcCC086TVGm3@9Nab25QXfQhf "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->m,n{n.times{m=m.reverse.transpose};m} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5XJ686T68kMze1uDrXNlevKLUstag4Va@kKDGvuCC/OLXWOrf2f4FCmkJ0dLShjoKxjoIRkDSI1VGINtFRsNRRMNdRMARzzXQULHQUTIEKTGOBfNPY/wA "Ruby – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 6 bytes ``` (+|:)/ ``` [Try it online!](https://tio.run/##Hcu7EYAwDIPhVdQRHy8nJITE@9BQsAC7G0H33@nTNd@X@9nD@HRZ/VyGEIqFiA0JmxoyGioia8eBglREuKvaFL/4cFFyJAP13LIC1ahVWT/PzMgDWRPxFw "K (oK) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 6 bytes ``` uC_GQE ``` [Try it online!](https://tio.run/##K6gsyfj/v9Q53j3Q9f9/U67oaEMdBWMdBSMgaRCrE22io2Cpo2Cuo2AI4pnpKFjoKJgCpU0VYmMB "Pyth – Try It Online") -1 Thanks to @FryAmTheEggman Rotates the matrix by reversing the order of rows and taking the transpose. Takes and returns lists of lists. ## How it works ``` uC_GQE u E - Reduce the second input _G - By reversing the order of rows C - And transposing Q - An amount of times equal to the first input ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` zV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=elY&input=W1sgMSwgMiwgMywgNF0sCiBbMTEsMTIsMTMsMTRdLAogWzIxLDIyLDIzLDI0XQpdCjM) ``` Rotate matrix by 90 degrees 2nd input times ``` [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` f=lambda A,i:i%4and f(zip(*A[::-1]),i-1)or A ``` [Try it online!](https://tio.run/##bY/BboMwEETP9VfMpbLdLBVOoClEHLjkJywOVIDqihjkEintz1ObQg5VfbB2x/Nm1@PX9D7Y/Tx3RV9f3poaJZncPCa1bdCJbzOKp1LneaQqSSZScnAo56btcBbeKXOGsrjUo5iuY99SKRlGZ@yEksEV3eJhMB361goni0Llv@@fk/P9aWlOrp2uzm4o14LvOPHnj8FYEcK9mZyOKyl3XBJn6PwaNxgLp1XYLWcPC8uxoPjD3u7gOgH/Twi/DM5qczJ2FlorwoGw93dMFTHohJARjgS1Ci@EV0LqTSmqilK5gr5WW53GBH98EvYLBPicKEuCflyVEBTHQUkDew9aNsi8hMQ/Kzn/AA "Python 2 – Try It Online") Input/output is a `list` of `tuples`. (The `%4` is a workaround for Python's recursion limit; could save a byte otherwise). [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Føí ``` Takes \$i\$ as first input; matrix the second. [Try it online](https://tio.run/##MzBNTDJM/f/f7fCOw2v//zflio421DHWMdIxNojViTbRsdQx1zEEMc10LHRMdYxMY2MB) or [verify all test cases](https://tio.run/##MzBNTDJM/W/ipuSZV1BaUmyloGTv6WKvpJCYlwJi2hZzKfmXlgClQDL/3Q7vOLz2f63OoW32/025oqMNdYx1jHSMDWJ1ok10LHXMdQxBTDMdCx1THSPT2FguQwMDkDIQC6ze1ACkA6xc19LEQMccotzAwEAHpNwEyDCEmmsZGwsA). **Explanation:** ``` F # Loop the (implicit) input-integer amount of times: ø # Zip/transpose the matrix; swapping rows/columns # (this will take the (implicit) input in the first iteration) í # Reverse each row # (after the loop, the resulting matrix is output implicitly) ``` NOTE: Uses the legacy version only because of performance. [The last test case times out in the rewrite version.](https://tio.run/##yy9OTMpM/f/f7fCOw2v//zcxMDAw5IqONtQx1rGMjQUA) Both the legacy and rewrite versions would be the same, though. [Answer] # [Julia 1.0](http://julialang.org/), 6 bytes Kind of cheating, but Julia has a built in `rotl90` function, that does exactly that. ``` rotl90 ``` [Try it online!](https://tio.run/##Vc3PCsIwDAbwe5/iOzYw4cvWOnsQfI/hwUtxUhj4h/n2Nd1BFBIIyccvt1eZL/qu@Vjvy7MkVnd6XJfVZz9BMaDHQIeAhBFq0x4HRPQR5w5RxH3jeS7Fa4dWYk3@Xg2LbFyzdikQ42aRxGbpHza118nWwQIqUj8 "Julia 1.0 – Try It Online") [Answer] # JavaScript (ES6), 58 bytes Takes input as `(i)(matrix)`. ``` i=>g=m=>i--?g(m[0].map((_,x)=>m.map(r=>r[x]).reverse())):m ``` [Try it online!](https://tio.run/##bY7BCoMwEETvfsUeE1hltabWQuyHSChio1iMSizi39tosSC4h4WdGd7su5iKsbTN8PG7/qWXSi6NzGppZNb4/qNmJicVmGJg7Ikzl5nZDiszm8@KB1ZP2o6acc7vZin7buxbHbR9zSomOMs9gDxEuCBEbhMqXJUYIUVIEMJduSLcEISLCVCe4tw7skKinXZq/7sEIbhxhRD90ACuzk/j1Uh2ae0jWiVxxouJwsP36ZZavg "JavaScript (Node.js) – Try It Online") **Note**: The last test case was edited to prevent a recursion error. We can obviously use [`i--&3`](https://tio.run/##bY7NCoMwEITvPsWeSgKrxJ/UWoh9EAlFbBSLMRKL@PY2WiwI7mFhZ4b59l1O5VjZdvj4vXmppRZLK/JGaJG3vn@JHw3RBZOBLgdCnjhTkevtsCK3xSxpYNWk7KgIpfSul8r0o@lU0JmG1IRTUngARYgQI0RuM5S4KglChpAihLtyRbghcBfjID1JqXfsChnb207tP4szBDcOCNGvGsDh/CxZjXSXVh5jq8TP@hLnhYf3sy22fAE) (60 bytes) to support much larger values. [Answer] # [Octave](https://www.gnu.org/software/octave/), 17 bytes Unfortunately `rot90` rotates the input *counterclockwise*. ``` @(x,i)rot90(x,-i) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0InU7Mov8TSAMjSzdT8b82Vq2CrEG2oY2RtrGMSa82VkllcoJGrCWWo6wKBuiaEk6aRq6NgqKlp/R8A "Octave – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~5~~ 3 bytes -2 bytes thanks to @LuisMendo! ``` _X! ``` [Try it online!](https://tio.run/##y00syfn/Pz5C8f9/I65oQx0ja2Mdk1gA "MATL – Try It Online") [Answer] # Java 8, ~~141~~ ~~138~~ ~~131~~ 130 bytes ``` (m,i)->{for(int t[][],a,b,j;i-->0;m=t)for(t=new int[b=m[0].length][a=m.length],j=a*b;j-->0;)t[j%b][j/b]=m[a-j/b-1][j%b];return m;} ``` -7 bytes thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##hZJNT4NAEIbv/opJExPQgS7aqi2hiUcP6kFvhMNC17oI2wYGP0L47XVYWi/ayoHM7rwz88zs5PJdevnybZsVsq7hXmrTngBoQ6p6kZmCh/5oL@IkTiBz9laJbIF2Q/Z3J/yrSZLO4AEMRLB12O96i/ZlXfUhYINQYop5qD1vIcIyIrf3UmTUhy2QRmUsEr9QZkWvSSyjcm9jHsmzNMxtoEtxfpomcT5OE45g/nHqBYm9DCtFTWWgDLtt2FNtmrRgqh3c@1ovoeQmnSeqtFlxH9IdOiRVk7MnYda2DfASL/BSdGgFv752gjO8xuCw4ApvcIoX065DmNpJ/VmndwdCHBZMBbKDaQ5WApigN5sIvD4iYRwhBFqc4AgP9z3rNRNWB78e2M7QRv2sguRhfiIMCzGM8@mrJlX664b8DU@aCuOM7symoXoOo3N9PgJplmzlvIB@Q7rwb6tKftX@UqnN83p4HmfI7O5Q/8r52BAnnf@byfiZ88PpHsm467fbfgM) **Code explanation:** ``` (m,i)->{ // Method with int-matrix and int parameters and int-matrix return for(int t[][], // Temp int-matrix as replacement a,b, // Temp integers used for the dimensions j; // Temp integer for the inner loop i-->0; // Loop the input `i` amount of times: m=t) // After every iteration: replace the input-matrix `m` with `t` for(t=new int[b=m[0].length][a=m.length], // Create a new temp-matrix `t` with dimensions `b` by `a`, // where `b` & `a` are the amount of columns & rows of matrix `m` j=a*b; // Set `j` to the product of these dimensions j-->0;) // And inner loop in the range [`j`, 0): t // Replace the value in `t` at position: [j%b] // `j%b` (let's call this row A), [j/b] // `j/b` (let's call this column B) =m // And replace it with the value in `m` at position: [a-j/b-1] // `a-j/b-1` (which is the reversed column B as row, // so it both transposes and reverses at the same time), [j%b];// `j%b` (which is row A as column) return m;} // And finally return the new int-matrix ``` **To save bytes**, the inner loop is a single loop and uses `j/a` and `j%a` as cell positions. So a loop like this: ``` for(r=a;r-->0;)for(c=b;c-->0;)t[c][r]=m[b-r-1][c]; ``` Has been golfed to this: ``` for(j=a*b;j-->0;)t[j%b][j/b]=m[a-j/b-1][j%b]; ``` to save 5 bytes. [Answer] # [R](https://www.r-project.org/), 64 bytes ``` r=function(x,i){o=x;n=0;while(n<i){o=t(apply(o,2,rev));n=n+1};o} ``` [Try it online!](https://tio.run/##VYxNCsIwFIT3PcVbvoezSFqrlphbeIFaKgZqUkLtD9Kzx@pCcDPwzTdMTCna29M3gwueZzh5BTsbb5WZ7q5r2Z@/1cB133cLB@SI7SiyTfxOryasabSPeohu5oY1qADlWypktAdVoCNIf@gAOoHKTZeCAtclhsleJIs8opTs96Kh/6VWStIb "R – Try It Online") Not really efficient... Uses rotation approach proposed by [Matthew Lundberg](https://stackoverflow.com/questions/16496210/rotate-a-matrix-in-r) [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ~!→¡oT↔ ``` [Try it online!](https://tio.run/##yygtzv6f6/aoqfF/neKjtkmHFuaHPGqb8v///2gNU53oaEMdYx0jHWODWJ1oEx1LHXMdQxDTTMdCx1THyDQ2VlNHw9DAAKQQwgbrMTUA6QJr0bU0MdAxh2gxACoEaYkFAA "Husk – Try It Online") I've always found it odd that the only real way to iterate a function a set number of times in Husk is to index into the infinite list of that function's iterates. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 37 bytes ``` f(m,n)=for(i=1,n,m=Mat(Vecrev(m~)));m ``` [Try it online!](https://tio.run/##PY3PCoMwDIdfJXhqIULjdJuIe4Nddyk9BNEhWFeKDHbZq3fpHDvkz4@PLwkc5/IeUpqUx1X30yOquSdc0fdX3tRtHOL4VP6tte584hCWl2IoLxDivG6KLTkoEApgW8mWSQEDL4uaEFhrBGstIRwQKummgxqhRTghkIQjwhmhEdg4mVI2vyWdscnRUmN2/auWbS3xtJvGmF2iv/n71Tq5UAsn53T6AA "Pari/GP – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 10 bytes ``` ~{-1%zip}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v65a11C1KrOgVuv//@hoQwVjBSMFY4NYhWgTBUsFcwVDENNMwULBVMHINDZWwRQA "GolfScript – Try It Online") ``` ~{ }* # Repeat i times -1% # Reverse the array zip # Zip ``` When the program finishes, only the elements of the matrix are displayed. To see how it actually was outputted, use [this](https://tio.run/##S8/PSStOLsosKPn/v65a11C1KrOgVivh///oaEMFYwUjBWODWIVoEwVLBXMFQxDTTMFCwVTByDQ2VsEUAA "GolfScript – Try It Online"). [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [~~8~~ 7 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` Ç├Úe↑Î( ``` [Try it!](https://zippymagician.github.io/Arn?code=Ji57LkBALjw=&input=W1sxIDMgOV1dIFtOXSA0MDAwMQpbWzFdXSBbTl0gMTAwCltbMTUwIDMgMl0gWzQgXzk0MCA3XSBbNiA4MDAwIDVdXSBbTl0gMTU=&flags=ZQ==) # Explained Unpacked: `&.{.@@.<` ELABORATE HERE ``` &. Mutate N times { Block, key of `_` _ Implied variable .@ Transposed @ Binded map .< Reverse } End block; implied ``` Input is two lines, the first being an array and the second a number. `&.` supports both 2 separate inputs and one as an array, and as `_` is automatically the STDIN separated on newlines and parsed, this code is valid. [Answer] # Mathematica, 32 bytes ``` a = {{3, 4, 5}, {5, 6, 7}, {8, 9, 10}, {11, 12, 13}}; Nest[Reverse /@ Transpose[#] &, a, i] ``` ]
[Question] [ This challenge is inspired by my earlier challenge "Create a program that prints the amount of characters it has, in words". This challenge's rules are simple: make a program that prints its character count, in words, which works in as many languages as possible. Each programming language the program works in must make the program print its char count in a different natural language. E.g. you can make a polyglot which prints "fifty" (suppose this is its char count) in one language and "pedeset" (Serbocroatian for 50) in another, but not a polyglot printing "fifty" in both languages. An extension to the "don't invent languages to solve the task" rule also applies here: don't make a constructed language just to validate your otherwise nonsense output in some language. If the polyglot printing "fifty" in one language was tested in another and printed (prant?) "Aijsisdjdsl", it's illegal to make a conlang using "Aijsisdjdsl" as the word for "fifty". Capitalization is ignored: in case you're printing "one" (somehow) you can print "one", "oNe", "ONE" or anything else. Base ten is required. Proper spacing is also required. In the (unlikely but just for specification) case your program reaches one billion characters or more, use the American number scale. A billion here is 10^9 and a million is 10^6. Do not use "one hundred and one": use "one hundred one". Do not use the hyphen. Print forty four, not forty-four. If the language you use has another script, use it instead of the romanization of it. If your program prints Arabic in some language, it should print (yet again, example with 50) "خمسون" and not "khamsun". Use the grammatically correct translation. For our purposes, we use [Ethnologue](https://www.ethnologue.com) to determine what is and isn't a language in this challenge. It's the most widely used so we'll just go with that. For simplicity, any languages with identical numerals will be considered the same for this challenge. Using any Japanese/Chinese numeral gives you a score of 1. If a word is spelled the same in multiple languages, e.g. English and French's "six", it counts as one point toward your score. Dialects Ethnologue differentiates will be considered different languages as long as they don't fall in the two rules above. Different compilers of the same programming languages are not differentiated here. Your score is the amount of languages your program works in, per standard rosetta-stone rules. If the two (or more) best answers are tying, the one with the lowest byte count wins. The encoding used to determine byte count for tiebreakers is UTF-8. The highest score wins (in case of tie see above). Have fun. [Answer] # ~~9~~ ~~10~~ ~~12~~ ~~13~~ ~~16~~ ~~18~~ ~~21~~ 23 languages, 1000 bytes * Bash (prints "duizend", Dutch) * Zsh (prints "een Dausend", Luxembourgish) * Dash (and other true POSIX shells) (prints "nje mije", Albanian) * C (prints "et tusind", Danish) * C++ (prints "ib txhiab", Hmong) * [brainfuck](https://esolangs.org/wiki/Brainfuck) (prints "mille", Italian) * [boolfuck](https://esolangs.org/wiki/Boolfuck) (prints "afe", Samoan) * [Brainlove](https://esolangs.org/wiki/Brainlove) (prints "mil", Spanish) * [2DFuck](https://gitlab.com/TheWastl/2DFuck) (prints "sewu", Javanese) * Python 1 (prints "one thousand", English) * Python 2 (prints "eintausend", German) * Python 3 (prints "hal kun", Somali) * [Asar](https://github.com/RPGHacker/asar) (prints "tuhat", Estonian) * [><>](https://esolangs.org/wiki/Fish) (prints "jedna hiljada", Bosnian) * [Gol><>](https://github.com/Sp3000/Golfish) (prints "eenduisend", Afrikaans) * [Befunge-98](https://esolangs.org/wiki/Funge-98) (prints "o mie", Romanian) * [Befunge-96](https://web.archive.org/web/20040221081031/http://www.mines.edu/students/b/bolmstea/mtfi/96.html) (prints "otu puku", Igbo) * [Labyrinth](https://esolangs.org/wiki/Labyrinth) (prints "elf", Maltese) * [Hexagony](https://esolangs.org/wiki/Hexagony) (prints "ett tusen", Swedish) * GNU Make (prints "isang libo", Filipino) * [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree) (prints "hezar", Kurdish) * Octave (prints "tūkstantis", Lithuanian) * [Whispers](https://github.com/cairdcoinheringaahing/Whispers) (prints "seribu", Malay) ``` #ifdef warnings //[[^ #_ if 0 #{ #(________ ) '''''echo' -n<<"'''+r'''": @echo "isang libo" define N # 1_801_201_ 0 1...@ endif print "tuhat" macro _() #} disp("t\xc5\xabkstantis") quit #{ > "seribu" >> Output 1 '''+r''': [ -n "$ZSH_VERSION" ]&&echo een Dausend||([ -n "$BASH_VERSION" ]&&echo duizend||echo nje mije) :<<"endmacro;\"^*///]\"\"\"#/t#" #endif #include<stdio.h> int main(){puts(sizeof('1')-1?"et tusind":"ib txhiab");} /* print"hezar";exit;<<'/*';#NJ@G@GMCI 1234567890123456789012345678901234567890123|u;ts;6ie$;;tn;e@$< ]+[+++[[<+>->+++++>+<<]+>]<<<.<.+++.(.<.)>>+;+;;;;+;;+;;+;;+;;+;;+;+;+;+;+;;+;;+;[-]]![!.!...!..!..!.!..!..!.!.!.!.!...!.!...!.!...!.!.!.!.!][ ''' print(["hal kun","eintausend","one thousand"][(type(1==1)==type(1))+(3/2==1)]) r"""" 01234567891234567890123456789012 1 >"ukup uto">:#,_@ H"eenduisend"\ >o<"jedna hiljada"~\ u #} endef # >"eim o"4k,@ /"`"/"/"\ endmacro;"^*///]"""#/t# ``` There should be a hard tab at the start of line 6. [Try it online!](https://tio.run/##hVNpc5swEP3c/RXykokhxGCco6nB1L0mSWeazDQz/VAgFBu5yIdwQZq4OfrXXQFOMtOk7VuhY7Uj3q6erjJWLmlR9tZrjU1SOiEKV0nBGf9eEtsOgkvQYsImpAvaDWh6vAExoF2BjrO8TTrc81CtzEJ12IcXw8qvjkJWJvw7mbNRjqCOZ5ySM6KBEx91nbinPuiCY1nWEChP2QSWBeOCoJBZIhAWybjISawboN1BqqjqKMLV@CBcJaNZKRIuWIkG/JBMVPR8giUt2Egi@D45l2IpBXHgnlgfAsWU4NbXi5P4y4fPF6fnZ0ii7e2aLKWcvE9kqXjc3uqbyLdvngtNJbuuw@oVn1KyYFNqQF9VQflr1m6Ilzu2bUchVqbZQkPQmiQ1xsdzmVKvFCnLrcyHKulFwrhu3CjOpV6qH@QTve20jY7zGqkgQpaMp9hHNiJilbFkhIZ7B/ZOUzLM6HVSoEtXTLie17Z32q529nF4PDz@9O4UnN7e/sHhy6NX3f/ObqUrSveQ0S3XFdylwy0PIjMwTTMIPNPv@GYF3/S8yPQjz/Msz1IOS1ej4fuma7oK5p/t3poWdKKoFbSslrr61qY9jo1ZT/raoqC60CZrPcAsmZOZ5LiLVDma@1OLXAlNZLlU8ksxCnTxc0l1ZzBwjMGgmRuGqe/ZvcoVGVCgAjxW4vnikH/Dgb9s@ChnckmkyNHva7vx8EngCSr9KV3V9MOHbT/3cEpTnpCMzadJmuCvkMjqNag49Vq1@nDKFiTH/dnukNj4DW1lITwIcaNDlV8lQlivfwM) (use the switch languages button to try them all) Length is exactly 1000 ASCII characters, and also 1000 bytes. Asar is a SNES assembler that has quite sloppy input parsing and thus accepts a lot of inputs that one may consider invalid. I used version 1.71 for this, downloadable [here](https://github.com/RPGHacker/asar/releases/tag/v1.71), and depended on quite a few bugs, so there is a chance this will break in later versions. All of the other languages are well-known enough to be on TIO. I used Google Translate for the translations, so they may not be perfectly grammatically accurate. If anyone knows some of the languages better, please suggest improvements, I've got some wiggle room here :) Credits: @JoKing for some minor optimizations regarding brainfuck, befunge, (gol)><>, hexagony, and python. @flawr for suggesting and helping with octave. @caird coinheringaahing for suggesting whispers. Fun fact: I made most of this polyglot months ago. It included the first 10 languages mentioned here. (edit: I've since shuffled the language list around a bit so it makes more sense, but check the 2nd oldest version of this polyglot in the edit history and add hexagony to get that list). # Explanation (slightly outdated) This explanation was made for an older revision. It's hard enough keeping track of all the natural language shuffling (to make more difficult programming languages use shorter natural language words) and Hexagony's constant grid shifting, let alone update the explanation every single revision. I'm leaving this here since it still gives a good overview of how what path most of these languages take. ## Asar Asar is a SNES assembler written by Alcaro in 2011, intended to be backwards-compatible with xkas (written by byuu in around 2006). It doesn't have the nicest code. The first line begins with a special kind of label definition, the label is called `ifdef`. Then follows a `warnings` command, which is supposed to control when warnings are thrown. Usually it's followed by either `push` or `pull`, but it doesn't reject other words following it. So that's the first line: a label-definition followed by a no-op. The 2nd line is a similar label definition (this time the label is called simply `_`) followed by an `if` statement. The condition is 0, so the contents of the if are ignored. This means we can pretty much go wild inside it, the only rule we have to follow is that all double-quotes must be paired. The end of that if statement is at the `endif` on line 10. After that comes a simple print statement which prints the output. Then comes a macro declaration. Declaring a macro that isn't used is pretty much equivalent to an `if 0`. The end of the macro declaration is on the very last line. In Asar, comments are started with `;`, so the rest of the last line is ignored. ## Bash, Zsh, Dash The first 3 lines are just regular comments. The 4th line is equivalent to `echo -n <<"'''+r''':"`. This is an echo without a linebreak following it. Then we have a heredoc that ends at any occurrence of `'''+r''':`. The contents of the heredoc are piped to the stdin of that echo command, but that doesn't matter since echo ignores its stdin. After the end of the heredoc on line 14, we have regular shell code that checks whether the variables for either zsh or bash are defined and chooses what to print based on that. After that, we have the null command `:`, which does nothing, into which we pipe the rest of the script using another heredoc. The heredoc ends with `endmacro;"^*///]"""#/t#`, which just happens to be the very last line of the script. ## C, C++ The first line is a preprocessor directive which checks whether the define "warnings" is defined. There's also a comment after the directive. `warnings` isn't defined, so the contents of the block are skipped. There are a bunch more garbage preprocessor directives inside the skipped if branch, but they are ignored too. The `#endif` is on line 18. After that we have a standard C program. It checks whether the size of a character literal is greater than 1 or not. If it's greater, we are in C, because in C character literals are actually of `int` type, which has a size of at least 2 bytes on literally every platform in use today. In C++, however, the type of a character literal is `char`, which is defined to have a size of 1, so a different branch is taken. The rest of the code is a single comment, started with /\* at line 21. It's terminated in the middle of the last line, but followed immediately by a single line comment. ## Brainfuck On the first line, we have 2 open brackets. This is because one of them is eaten by the heredoc that ends the shell part, which is before the brainfuck part. There are some balanced brackets within the skipped part too, but they don't matter because they are balanced. The next closing bracket is on line 21, which is also the start of the brainfuck code. I used [this text-to-brainfuck converter](https://copy.sh/brainfuck/text.html), because somehow it generated even better output than BF-Crunch. Then follows the boolfuck code, which is mostly ignored due to `;` not being defined. The increments don't matter either, we just switch to the next cell which has never been written to so the next open bracket is a guaranteed jump. The next closing bracket after that is on the very last line, and there are no brainfuck instructions after it. ## Boolfuck The boolfuck control flow is quite similar. However, once the brainfuck code is reached, most of it is ignored as `-` isn't defined in boolfuck. The area with `+` and `;` is where the output is actually printed. It just prints the string "mil" bit by bit, with `+` negating the current bit and `;` outputting it. The rest of the control flow is identical to brainfuck. ## Python 1, 2, 3 The first 3 lines are regular comments. The 4th line starts with a triple-quoted string literal, delimited by single quotes. This string literal is often closed and reopened because I needed to get a backslash in somewhere (I've forgotten where), so I needed the string literal to be raw, but I couldn't put the r before the first quotes. Anyways, the first place where the string literal is closed and not immediately followed by another string literal is on line 23, which is the start of the Python code. This code uses a few simple tests to determine which version of Python it's running on: in Python 1.6, there was no separate boolean type, so the results of comparisons were just `int`s. The first condition checks that. The second condition checks whether division rounds down or not. In Python 2, division on integers rounded the result down, whereas in Python 3, it results in a floating point answer. After the Python code, we have another raw string literal that lasts until the last line, where it is immediately followed by a comment. ## ><>, Gol><> Now we get to the 2D languages. Gol><> is almost perfectly backwards compatible with fish, so they start execution the same way. In fish, execution starts from the north east ("top left") corner of the program, with the instruction pointer pointing west. In fish, `#` is a mirror which reflects the instruction pointer back in the direction it came from. The `#` causes the IP to point west instead. In fish, program space is topologically a torus, so going off the western edge results in reappearing at the eastern edge of the program. There it encounters `^`, which changes the instruction pointer's direction to north. Execution then continues from the very bottom of the script. The IP goes right past the very last character of the program and hits the `/` on line 31. The `/` reflects the IP like a mirror, so it'll go east again. Here is where we determine if we are running fish or golfish. In golfish, quotes inside string literals can be escaped with ```. So in golfish, the string literal is only terminated on the 3rd quote on that line. In regular fish, however, the backtick escape doesn't exist, so the string literal ends after the 2nd quote. (The 4th quote is needed to keep Asar happy about paired quotes). Then, both IPs are reflected upwards. The fish one goes west on line 30 and follows a pretty simple text printing program. The golfish one goes west on line 29, after switching to a different stack with the `u` in its path on line 30. There, it follows a very simple string printing code too (just push the string on the stack and call `H`, which exits and dumps the whole stack as ASCII text). ## Befunge-98 In Befunge-98, execution starts out in the north west ("top left") corner of program space, pointing east. `#` is a trampoline command, it skips the next instruction. The letters a-f just push their hex value on the stack. Spaces are no-ops. `w` pops 2 items from the stack, compares them, and turns left or right depending on which one is larger. here, `f` is larger than `e` (15 is larger than 14), so we turn left, with the IP pointing north. Now we jump to the bottom of the program, like in fish, and follow the path of arrows to line 31. This uses a simple string printing code with the `k` operator, which repeats the next instruction (print character) some number of times, 5 in this case. ## Hexagony This was the one language that probably costed me the most time while writing this thing. This explanation is a bit oversimplified, go look at Hexagony's README or wiki page if you want to learn more. Hexagony reformats your program into a hexagon. Then execution starts at the north-west corner. The first command, `#`, switches to the IP with the index of the current memory cell (there are 6 IPs, each one starting at a different corner of the hexagon). Memory is initialized to all 0's though, so this switches to the first IP, which is the one that is already executing. All alphabetic characters simply set the current memory cell to their value, so most of the rest of the 1st line is just no-ops. Then there's a mirror, `/`, which makes the IP point north-west (as if it got reflected off the mirror). This means the IP will wrap around to the very bottom of the hexagon. There, it happens to hit the `/` at the very end of the script. This is also a mirror and makes the IP go east again. Then we set the current memory cell to `t` and use the "switch IP" command again. Since there are only 6 IPs, the current memory cell is taken modulo 6 when switching, so it goes to the 3rd IP, which starts at the eastern corner of the hexagon. This IP starts out moving southwest and it executes some useless operations before reaching the end of line 23 in the original code. There it uses the `$` operator to skip over some characters the first time around, then encounters `|` which turns it around and prints some more characters. ## Labyrinth In labyrinth, control flow is determined by the program's layout. All spaces and alphabetic characters are considered walls. The `#` command pushes the number of items on the stack, which is 0, to the stack. Then execution continues in the only possible direction, south. Here, the number of items on the stack is pushed again, this time pushing a 1. Now there's 2 directions to go: south again or east. Since the topmost value on the stack is positive, execution would try to go west, but that path is blocked, so it goes east instead. `_` pushes a 0. Now there's again 2 directions to go, but we came from one direction and unless nothing else is possible, the IP will never flip around and go back the direction it came from, so we continue south. Here we have a `(`, which decrements the top of the stack. This means the topmost item is now `-1`. Excluding the direction we came from, there's 3 directions to go, but since the top of the stack is negative, we go east. Here we push 0 a bunch of times, which means we continue east for as long as possible. In the end, we go south because that's the only other place to go. There we find a `'`, which is a no-op if debugging output isn't enabled. Now, labyrinth treats tabs as a single space, so the character south of the `'` is actually `"` from the start of the echo's parameters. Execution continues there. Below that, there is only one path to follow, which leads to the 4th character of line 9. There, we simply construct the ascii values corresponding to "elf" and print them. ## Make The first 3 lines are comments. The 4th line is somehow a valid target name. (To be honest, I have no idea either about why this works.) Since this is the first target in the makefile, it's what gets executed when no argument is given to make. The rule just prints the character count. Then we define a variable called N which contains the rest of the script. It ends on the 2nd-to-last line with the `endef` command. Following it is a comment that ends with a backslash. This causes make to interpret the next line as part of the comment too. ## A Pear Tree A Pear Tree starts execution by finding the longest substring of the program whose CRC32 is 0. Then it shifts the whole program so that said substring is at the start of the program. This long substring with a CRC32 of 0 is `print"hezar";exit;<<'/*';#NJ@G@GMCI`, which *just happens to be* valid Perl code. No, actually I used a tool called [crchack](https://github.com/resilar/crchack) to generate some letters to add to a comment so that the string's CRC is 0. So this Perl program is shifted to the very beginning of the program. It contains a print statement, an exit statement and a heredoc. The heredoc is terminated by the line that was right before the perl script originally, and thus is at the very end of the program now. So the heredoc skips the entire rest of the script and all of the syntax errors that would arise from not doing so. [Answer] # 6 languages, prints 80 ``` //'Ÿ¯"y"«q áttatíu/* ";" åo 八 t? 十 t@ " io o oo @ "o 0o 1 K`ochenta ``` (There's also 5/90 solution with a different approach in the edit history if you're interested) ## [05AB1E](https://github.com/Adriandmen/05AB1E)/[English](https://www.ethnologue.com/language/eng) - `eighty` ``` //'Ÿ¯"y"«q // # no-ops 'Ÿ¯ # push dictionary string "eight" "y" # push literal string "y" « # concatenate q # end program ``` [Try It Online!](https://tio.run/##yy9OTMpM/f9fX1/96I5D65UqlQ6tLuRSUFA4vLCkJLHk8NpSfS0uJWslrsNL8xWetq7mKrFXUHja28hV4gBUpMSVmQ@kFPK58sG0ggOXUj6XQT6XoYJ3Qn5yRmpeSeL//wA "05AB1E – Try It Online") Once execution ends, the stack top (`eighty`) is implicitly printed, and nothing later on in the file will be considered at all. ## [ink](https://github.com/inkle/ink)/[Íslenska](https://www.ethnologue.com/language/isl) - `áttatíu` ``` áttatíu/* ``` [Try It Online!](https://tio.run/##y8zL/v9fX1/96I5D65UqlQ6tLuRSUFA4vLCkJLHk8NpSfS0uJWslrsNL8xWetq7mKrFXUHja28hV4gBUpMSVmQ@kFPK58sG0ggOXUj6XQT6XoYJ3Qn5yRmpeSeL//wA "ink – Try It Online") The very first line in the file is a comment, due to the `//`. The `/*` at the end of this line begins a multi-line comment (which we never have to close), so ink doesn't care about anything later on in the file either. That just leaves the text `áttatíu`, which ink happily prints, because that is what ink does. ## [Alice](https://github.com/m-ender/alice)/[日本語](https://www.ethnologue.com/language/jpn) - `八十` ``` / " 八 十 " o @ ``` [Try It Online!](https://tio.run/##S8zJTE79/19fX/3ojkPrlSqVDq0u5FJQUDi8sKQkseTw2lJ9LS4layWuw0vzFZ62ruYqsVdQeNrbyFXiAFSkxJWZD6QU8rnywbSCA5dSPpdBPpehgndCfnJGal5J4v//AA "Alice – Try It Online") In Alice, `/` is a mirror, but unlike in other 2D languages you might be familiar with, they reflect you 135 degrees rather than 90. So after encountering the `/`, we move diagonally, encountering `"八十"` (which pushes the string `八十` onto the stack), `o` (which outputs it), and `@` (which terminates the program). ## [><>](https://esolangs.org/wiki/Fish)/[Norsk](https://www.ethnologue.com/language/nor) - `åtti` ``` // "; åo t? t@ io oo "o 0o 1 ``` [Try It Online!](https://tio.run/##S8sszvj/X19f/eiOQ@uVKpUOrS7kUlBQOLywpCSx5PDaUn0tLiVrJa7DS/MVnrau5iqxV1B42tvIVeIAVKTElZkPpBTyufLBtIIDl1I@l0E@l6GCd0J@ckZqXkni//8A "><> – Try It Online") The `/` at the start deflects the instruction pointer upwards, after which it wraps around to the bottom, travelling up the first column. It then pushes the numbers `1` and `0` and the characters `oittin` onto the stack, bounces around on the mirrors at the top, and travels up along the second column. In the second column, we print the first four items on the stack (`åtti`). Then we shuffle the last three values around a bit using `@`, leaving the `0` at the top, which thanks to the `?` makes us skip the final print instruction, before we arrive at the `;` which ends the program. ## [Gol><>](https://github.com/Sp3000/Golfish)/[Svenska](https://www.ethnologue.com/language/swe) - `åttio` ``` // "; åo t? t@ io oo "o 0o 1 ``` [Try It Online!](https://tio.run/##S8/PScsszvj/X19f/eiOQ@uVKpUOrS7kUlBQOLywpCSx5PDaUn0tLiVrJa7DS/MVnrau5iqxV1B42tvIVeIAVKTElZkPpBTyufLBtIIDl1I@l0E@l6GCd0J@ckZqXkni//8A "Gol><> – Try It Online") Works just like ><> except the `@` shuffles the stack values in a different way, so we end up not skipping the last print, thus printing `åttio` instead of `åtti`. ## [Retina](https://github.com/m-ender/retina/wiki/The-Language)/[Español](https://www.ethnologue.com/language/spa) - `ochenta` ``` 1 K`ochenta ``` [Try It Online!](https://tio.run/##K0otycxLNPz/X19f/eiOQ@uVKpUOrS7kUlBQOLywpCSx5PDaUn0tLiVrJa7DS/MVnrau5iqxV1B42tvIVeIAVKTElZkPpBTyufLBtIIDl1I@l0E@l6GCd0J@ckZqXkni//8A "Retina – Try It Online") The first ten lines are presumably interpreted as replacement stages, but since we don't have any input to manage, we don't really care what they do. the last stage, however, is a constant stage - we can tell because the config string before the backtick has a `K` in it. That means we just discard any input that stage would get from the stages before it, and output `ochenta`. [Answer] # 3 Languages, 800 chars * [PHP](https://php.net/), Norwegian, Outputs `ÅTTE HUNDRE` * [Emoji](https://esolangs.org/wiki/Emoji), Persian, Outputs `هشتصد` * [COW](https://bigzaphod.github.io/COW/), English, Outputs `EIGHT HUNDRED` ``` <?=['ÅTTE HUNDRE','⛽هشتصد🚘➡',' MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MMM MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO Moo MOo MOo Moo MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MMM Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo Moo MMM MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MMM MoO Moo MOo Moo'][0]; ``` [PHP - Try it online!](https://tio.run/##K8go@P/fxt42Wv1wa0iIq4JHqJ9LkKu6jvqj2Xtvtt/YcmPVja031n@YP2vGo3kLgcJcvvn@IKyARKOzsfFxieETxy7n60usXlLUkKIOh9p8Baxi/mDMhZDPJ8OOfKi/86ntD2rqherPJ1MvUlj5w9kInI9FDBeGhBcFfslHSmdwM9Vjow1irf//BwA "PHP – Try It Online") [COW - Try it online!](https://tio.run/##S84v///fxt42Wv1wa0iIq4JHqJ9LkKu6jvqj2Xtvtt/YcmPVja031n@YP2vGo3kLgcJcvvn@IKyARKOzsfFxieETxy7n60usXlLUkKIOh9p8Baxi/mDMhZDPJ8OOfKi/86ntD2rqherPJ1MvUlj5w9kInI9FDBeGhBcFfslHSmdwM9Vjow1irf//BwA "COW – Try It Online") [Emoji - Try it online!](https://tio.run/##S83Nz8r8/9/G3jZa/XBrSIirgkeon0uQq7qO@qPZe2@239hyY9WNrTfWf5g/a8ajeQuBwly@@f4grIBEo7Ox8XGJ4RPHLufrS6xeUtSQog6H2nwFrGL@YMyFkM8nw458qL/zqe0PauqF6s8nUy9SWPnD2Qicj0UMF4aEFwV@yUdKZ3Az1WOjDWKt//8HAA "Emoji – Try It Online") [Answer] # ~~3~~ ~~8~~ 9 languages, 300 characters ``` //®di.•paü¾p•ë"兩百"„„í°¡r\}q💬trescientos💬➡\u000A\u002F\u002A //\ {{Write("trois cent"/*\u002A\u002Finterface M{static void main(String[]a){System.out.print("driehonderd" /* #include<stdio.h> int main(){{puts(sizeof'a'<sizeof(int)?"trezentos":"dreihundert"/**/);}}// ``` [Try it online in 05AB1E / Chinese](https://tio.run/##LU@7TsNAEKztrzgdRWwXPosSIlAaOqoUFITi8G3ISsRn7tZIxIqUhh@gowkKHeIhPgClcP7EEqLlD8zZRlqNZlezszvaykuEpmGMea48B/9UiOpDYVyvnnO5@6q2uWO7V/59//LzuOX1au1q9159VhszWd78Pj28kQGbImSkbdvW682kSJJk1OL@SYcj3/lO/LI8M0gQcDIaLUvdDhdRr@jVmBGYqUyBnZaWJGHKbjUqNpeYBWMymF2dX8iwHN9ZgnmsC4pzN6SAK4Mw05kCo3gXyOuDtVREvreHWXpdKBhaUqjj2ZHP3F5vHJZlXpANLC5ATwdyMOxZ4BThsfsWFl08fuDOAM6K9kz7eiTCw@VSiKb5Aw) - outputs `兩百`. [Try it online in 05AB1E (legacy) / Italian](https://tio.run/##LU@7TsNAEKztrzgdRewUPoNEAxEoDR1VCgpMcfg2ZCXiM3drJGJZSsMP0NEEhQ7xEB@AUjh/EgnR8gfmHCOtRrOr2dmdeF9e7kLTMMY8V56DfypE/aEw2syfc7n@qle5Y@tX/n3/8vO44pv5wtX6vf6slyapbn6fHt7IgE0RMtK2bTeLZVLEcTxsce9ki0Pf@SZ@WZ4ZJAg4GY2WpW6Hi36n6NSYEZixTIGdlpYkYcpuNSo2lZgFIzKYXZ1fyLAc3VmCaaQLinI3pIArgzDRmQKj@DaQ1wVrqej73g5m6XWhYGBJoY4mRz5ze51xWJZ5QTawOAM97sneoGOBU4TH7luYbePxA3cGcFK0Z9rX@yI8rCohmuYP) - outputs `trecento`. [Try it online in 2sable / English](https://tio.run/##LU@7TsNAEKztrzgdRWwXviglRKA0dFQpKAjF4dvglRKfuVsjEStSGn6AjiYodIiH@ACUwv6TSIiWPzDnGGk1ml3Nzu4MrLyaQdMwxjxXnoN/KkT1oTDerZ5zWX9V29yx@pV/37/8PG75brV2Vb9Xn9XGTJY3v08Pb2TAJggZadu2u/VmUvT7/VGLg9M9jnznO/HL8twgQcDJaLQscTtcRJ2iU2NGYKYyAXZWWpKECbvVqNhcYhaMyWB2fXEpw3J8ZwnmsS4ozt2QAq4MQqozBUbxfSCvC9ZSEfneAWbJrFAwtKRQx@mxz9xeZxyWZV6QDSwuQE97sjfsWOAU4Yn7Fhb7ePzQnQFMi/ZM@3okwqPlUoim@QM) - outputs `three hundred`. [Try it online in Java 8 / Dutch](https://tio.run/##LU@7TsNAEKztrzgdRexI@CJKiEBp6KhSUGCKk@@CNxCfuVtHIidLafgBOpqg0CEe4gNQCudPLCFa/sCcY6TVaHY1O7sz5XO@PxXXTUMI8Vx5Dv4pY9WHgKhePud8@1Vtcse2r/T7/uXncUPr5crV9r36rNY6Lm9/nx7eUEuTgMxQmbatV@u4GAwGoxYPTnc48p1v7Ft7rgFlQFErMCRxO5T1O0WnhgylnvBEkjNrkCMkZK5AkBmHLBijhuzq4pKHdnxnUM4iVWCUuyEGVGiQqcqE1ILuAnldsJayvu/tQZbcFEIODQpQUXrsE7fXGYfW5gWawMBCqkmP94YdC5wiPHHfysUuHj10ZySkRXumfb3PwqOyZKxp/gA) - outputs `driehonderd`. [Try it online in C# (Visual Interactive Compiler) / French](https://tio.run/##LU89S8RAEK2TX7GsxSUBs8FSD@UaO6srLIxF2N0zA1427k4ELwSu8Q/Y2ZycnfiBP0CuSP5JQGz9B3GTCMPjzfDmzTxu9rmBriOEOLYcC/@UsfpDQNiun/Ok@ap3uWXNK/2@f/l53NF2vbHVvNef9VbH1c3v08Mbamk4yAyV6dt2s42LKIpmPR6cDjhzrW/sluW5BpQeRa3AEG53KAtGxaiGDKVeJFySs9JggsDJrQJBlglk3hw1ZFcXl4lfzu8MymWoCgxzO0SPCg0yVZmQWtAhkDMG6ykLXGcPMn5dCDk1KECF6bFL7N5o7JdlXqDxDKykWkySyXRknlX4J/ZbuRri0UN7RkJa9Gf61wPmH1UVY133Bw) - outputs `trois cent`. [Try it online in C / German](https://tio.run/##LU89T8MwEJ2TX2GZoUkk4ooRKlAXNqYODJTBst3mpNYO9gWJRpW68AfYWIrKhvgQPwB1SP9JJcTKPwhOgnR6end69@6eOBQzrqd1TQgJfAUe/ilj1YeEdL96zvnuq9rmnu1e6ff9y8/jlu5Xa1@79@qz2tjx8ub36eENrXIClEbjmna/3oyLfr8/bPDovMVh6H3HYVleWkAVUbQGHBF@h7KkU3Rq0KjshAtFLkqHHEGQWwOSzDnoaIQW9PTqmsfl6M6hmqemwDT3Q4yotKAyo6WykraBgi5YQ1kSBgegxayQauBQgkmz05D4vc44Lsu8QBc5WCgz6fHeoGORV8Rn/lu1aOPRY39GQVY0Z5rXExafLJeM1fUf) - outputs `dreihundert`. [Try it online in C++ / Portuguese](https://tio.run/##LU89T8MwEJ2TX2GZoUkk4ooRKlAXNqYODJTBst3mpNYO9gWJRpW68AfYWIrKhvgQPwB1SP9JJcTKPwhOgnR6end69@6eyPNDMeN6WteEkMBX4OGfMlZ9SEj3q@ec776qbe7Z7pV@37/8PG7pfrX2tXuvPquNHS9vfp8e3tAqJ0BpNK5p9@vNuOj3@8MGj85bHIbedxyW5aUFVBFFa8AR4XcoSzpFpwaNyk64UOSidMgRBLk1IMmcg45GaEFPr655XI7uHKp5agpMcz/EiEoLKjNaKitpGyjogjWUJWFwAFrMCqkGDiWYNDsNid/rjOOyzAt0kYOFMpMe7w06FnlFfOa/VYs2Hj32ZxRkRXOmeT1h8clyyVhd/wE) - outputs `trezentos`. [Try it online in Whitespace / Japanese](https://tio.run/##LU@7TsNAEKztrzgdRewUvogSIlAaOqoUFJjC8l3wSsRn7tYgcrKUhh@gowkKHeIhPgClcP7EEqLlD8w6RlqN5k6zOzO3GaCyRZKqtmWMeTQewT8Vov6QEDXL5yLZftWbgtj2lX/fv/w8bnizXNFs3@vPem3i6vr36eENjbIpqBy17Z7Nah2Xo9Fo0uH@yQ4nPt2NfefODHkHHI0Gy1La4WLYK3o15KjMjKKxU2cxQUjZjQbJ5gnkwRQN5JfnF0nopncW1TzSJUYFfWLApQGV6VwqI/mukNcX66gY@t4e5OlVKdXYogQdZUc@o73@cOhcUaINLCyUng2SwbhnASnCY0qrFrt6/IBsFGRlZ9NFH4rwsKqEaNs/) - outputs `三百`. [Try it online in Emoji / Spanish](https://tio.run/##LU@7TsNAEKztrzgdRWwXvogSIlAaOqoUFITC8m3wIuIzd2skcoqUhh@gowkKHeIhPgClcP7EEqLlD8zZRlqNZlezszswV1fYNIwxz5Xn4J8KUX1IjOvVc5Hsvqpt4djulX/fv/w8bnm9WrvavVef1UZPlze/Tw9vpMGkCDkp07b1ejMth8PhuMX9kw7HvvOd@taeaSQIOGmFhqVuh4uoV/RqzAn0LEmBnVpDCWHKbhVKNk8wDyakMb88v0hCO7kzBPNYlRQXbkgBlxohU7kELXkXyOuDtVREvreHeXpdShgZkqji7Mhnbq83Dq0tSjKBwQWo2SAZjHoWOEV47L6FRRePH7gzgFnZnmlfj0R4uFwK0TR/) - outputs `trescientos`. ## Explanation: **[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) / Chinese and 05AB1E (legacy) / Italian and [2sable](https://github.com/Adriandmen/2sable) / English:** ``` # Spaces/tabs are no-ops // # Divide twice (without input) # Legacy 05AB1E / new 05AB1E: this pushes an empty string # 2sable: the stack remains empty ® # Push -1 d # Legacy 05AB1E: check if this -1 is an integer (truthy) # New 05AB1E: check if this -1 is non-negative (≥0) (falsey) # 2sable: check if this consists only of digits (falsey) i # If it is truthy: .•paü¾p• # Push compressed string "trecento" ë # Else: "兩百" # Push string "兩百" „„í°¡ # Push dictionary string "one hundred" r # Reverse the stack # New 05AB1E: "","兩百","one hundred" → "one hundred","兩百","" # 2sable: "兩百","one hundred" → "one hundred","兩百" \ # Discard the top item # New 05AB1E: "one hundred","兩百","" → "one hundred","兩百" # 2sable: "one hundred","兩百" → "one hundred" } # Close the if-else q # Terminate the program # (after which the top of the stack is output implicitly as result) # And any character after it are no-ops ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `„„í°¡` is `"one hundred"` and `.•paü¾p•` is `"trecento"`. **[Emoji](https://esolangs.org/wiki/Emoji) / Spanish:** ``` # Some no-ops 💬trescientos💬 # Push string "trescientos" ➡ # Print the top to STDOUT # Some more no-ops ``` **[Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) / Japanese:** Only spaces, tabs, and newlines are relevant for Whitespace programs and every other character is ignored. So the program is actually (`S` = space; `T` = tab; `N` = newline): ``` SSSTSSTTTSSSSSTSSTN TN SSSSSTTTSTTSSTTTTTTSN TN SS ``` 1. `SSSTSSTTTSSSSSTSSTN` push the integer 19977 to the stack (first `S` is to enable stack manipulation; second `S` is to push a number; third `S` is positive (`T` would have been negative); the `S` and `T` that follow are the integer in binary where `S=0` and `T=1`; and the trailing `N` finishes this command. 2. `TNSS` print this integer as character (with this unicode value) to STDOUT (first `TN` enables I/O; the following `S` is to output to STDOUT; and the second `S` to output as character (`T` would have been as integer)). 3. `SSSSSTTTSTTSSTTTTTTSN` push 30334 4. `TNSS` print as character again **C# (Visual Interactive Compiler) / French:** The first line contains some no-op spaces/tab, and a comment (`//` starts the comment, making everything after it on that same line no-ops). The second line is similar, again a no-op tab and a comment. The third line starts with `{{Write("trois cent"`, and `/*` starts a (potentially multi-line) comment-block. This stops at the `*/` on the last line, making everything in between no-ops. After which `);}}` is part of the C# program again (and the very last `//` is a comment again, only there to make the program-size 300). So the non-comment parts of the C# (Visual Interactive Compiler) program are: ``` {{Write("trois cent");}} ``` The `{{` and `}}` are code-blocks, and basically no-ops in this case. The `Write("trois cent");` prints this text to STDOUT. **C / German and C++ / Portuguese:** First line is a comment again. The `//\` on the second line is relevant in C and C++, as it will comment out the entire next line. The `#include<stdio.h>` and `int` in front of the `main`-function are mandatory in C++ (and optional in C; it would run fine without these two parts, but would generate some warnings). The `/**/` and `//` are again comments. So the non-comment parts of the C and C++ programs are: ``` #include<stdio.h> // Required include for `puts` in C++ int main(){ // Mandatory main-function: { // No-op code-block (similar as the C# part above) puts( // Print to STDOUT with trailinb newline: sizeof'a' // If the byte-size of character 'a' < // is smaller than sizeof(int)? // the byte-size of an integer: "trezentos" // Print "trezentos" : // Else: "dreihundert");}} // Print "dreihundert" ``` In C (and Java), values of type `char` are saved as an integer. `sizeof(int)` and `sizeof'a'` will therefore both result in `4` in C, and `4<4` is falsey, so `"dreihundert"` is printed. In C++ (and C#), values of type `char` are actually a separated type saved as characters. `sizeof'a'` will therefore result in `1` in C++, and `1<4` is truthy, so `"trezentos"` is printed. **Java 8 / Dutch:** In Java, we can use `\uHEX` as unicode values, which are read as characters after compilation. The very first line therefore compiles to (I'll ignore the leading spaces/tabs for now to make it a bit more compact): ``` //®di.•paü¾p•ë"兩百"„„í°¡r\}q💬trescientos💬➡ /* ``` The `\u000A\u002F\u002A` are a newline, `/` and `*` respectively. Just like in the C# program, this will stop at the first `*/`, which is the `\u002A\u002` on the third line in this case. There the Java program starts: ``` interface M{static void main(String[]a){System.out.print("driehonderd" ``` After that come a bunch of no-op spaces/tabs again, followed by another `/*` which stops at the same place as the C# program. So the full Java program is: ``` interface M{static void main(String[]a){System.out.print("driehonderd");}} interface M{ // Class: static void main(String[]a){ // Mandatory main method System.out.print( // Print to STDOUT "driehonderd");}} // The string "driehonderd" ``` # Why these languages? **Natural languages:** * I'm fluent in English and Dutch * I've learned French and German at high school * I watch quite a lot of Japanese anime * I know a few loose words in Spanish, Italian, and Portuguese * Chinese was short enough to fit after adding 2sable ;) **Programming languages:** * I'm pretty skilled at Java, 05AB1E, C#, and Whitespace * I've used the polyglot tricks for combining Java & C as well as Java & C# before [here](https://codegolf.stackexchange.com/a/138416/52210) and [here](https://codegolf.stackexchange.com/a/187428/52210) * [I've seen the C / C++ difference before](https://stackoverflow.com/a/2172948/1682559), and it was therefore easy to add here * Emoji is a perfect language to add, since it ignores everything except for the relevant emoji commands (unlike Emojicode I tried to add as well..) * 2sable is based on an old version of 05AB1E (legacy), and therefore rather similar as 05AB1E and 05AB1E (legacy), except it's a bit older than both. *I might try to learn and add [Aheui](https://aheui.readthedocs.io/ko/latest/) for a suiting Korean output later on, since it will ignore everything except for the Korean characters in the code.* [Answer] # ~~3~~ 4 languages, outputs 20 * [Actually](https://github.com/mego/seriously):[Japanese](https://www.ethnologue.com/language/jpn) * 05AB1E:[Vietnamese](https://www.ethnologue.com/language/vie) * Emoji:[Danish](https://www.ethnologue.com/language/hun) * Underload:[Cantonese](https://www.ethnologue.com/language/yue) This answer is inspired by [this](https://codegolf.stackexchange.com/a/194682/85052) answer. Let's see whether I can fit in the ~~4th~~ 5th language in 20 characters. ``` (廿)"二十""hai"💬tyve💬➡S ``` [Try it online in Actually!](https://tio.run/##S0wuKU3Myan8/1/j6e79mkpPdvU87W1UUspIzFT6MH/SmpLKslQQ/WjewuD//wE) [Try it online in 05AB1E!](https://tio.run/##yy9OTMpM/f9f4@nu/ZpKT3b1PO1tVFLKSMxU@jB/0pqSyrJUEP1o3sLg//8B) [Try it online in Emoji!](https://tio.run/##S83Nz8r8/1/j6e79mkpPdvU87W1UUspIzFT6MH/SmpLKslQQ/WjewuD//wE) [Try it online in Underload!](https://tio.run/##K81LSS3KyU9M@f9f4@nu/ZpKT3b1PO1tVFLKSMxU@jB/0pqSyrJUEP1o3sLg//8B) ## Explanation Actually: ``` ( Roll empty stack left 廿 Unidentified instruction ) Roll empty stack right "二十""hai" Push 2 strings 💬t Pop a, b, push a[b:]. Nothing special since b is a string. y Push prime factors of the string on the top of the stack v Discard TOS for the seed of the RNG e Push exp(Top Stack String) 💬➡S Sort the Top Of Stack; no effect to the text Outputs the whole stack implicitly. ``` 05AB1E: ``` ( Negate the empty stack 廿 Unidentified instruction ) AFAICT this is a NOP "二十""hai" Push 2 strings onto the stack 💬t Square root top of the stack string y Push string variable v Enumerated loop e Number of permutations 💬➡S Cast to list of characters / digits. This outputs the TOS implicitly. ``` Emoji: ``` (廿)"二十""hai" No operations 💬tyve💬➡ Output tyve S NOPs ``` Underload: ``` (廿) Push 廿 onto the stack "二十""h NOPs a Enclose TOS with braces i"💬tyve💬➡ NOPs S Output TOS ``` ``` ]
[Question] [ Find the maximum possible number of disjoint sets of characters, that are [Turing complete](https://en.wikipedia.org/wiki/Turing_completeness) subsets of your language. ## Rules: * You can assume your Turing complete subset is contained in/called from a main-function if that is required by your language * The subsets must not share any characters (in the native encoding of the language), this also includes new-lines * You are allowed to use standard library functions * You should not use languages like *Lenguage* that only use the length/positions of the code instead of the actual values of the characters. * Your score is the number of disjoint subsets you find. [Answer] # Python 3, score 3 ``` ()+1𝒸𝑒𝒽𝓇𝓍 '*.23;<=F^_{}𝓪𝓬𝓮𝓱𝓵𝓹𝓺𝓻𝓼𝔁 "%,-0:[]acefinorst~𝐀𝐄𝐜𝐞𝐢𝐧𝐨𝐫𝐬𝐭𝐱 ``` This is an extension of **[@UnrelatedString's answer](https://codegolf.stackexchange.com/a/264367/88546)**, but too long to fit in a comment. Each line contains a subset of characters that can perform arbitrary code execution. A meaningless bonus is that none of these require newlines, although there was a reason for this which I explain later. ### Subset 1 The first subset is simple, and is the same as [@UnrelatedString's](https://codegolf.stackexchange.com/users/85334/unrelated-string) second subset. The code itself looks something like this: ``` 𝑒𝓍𝑒𝒸(𝒸𝒽𝓇(1+1+...+1)+𝒸𝒽𝓇(...)+...) ``` ### Subset 2 In the other answer, they wondered whether it was possible to set attributes on a type without creating a new `class`. Yes we can, and a quick examination shows that the following built-ins are available: ``` __loader__, quit, exit, copyright, credits, license, help ``` Using one of these built-ins, we can redefine one of its class attributes to avoid using parentheses. We can for example, redefine the less-than operator (`<`): ``` help.__class__.__lt__=exec;help<'print(1)' ``` To construct arbitrary strings, f-strings are a reasonable replacement for concatenation. We can also re-use the trick of redefining operators to call `chr()`. Here's how to execute `print(1)` using this subset: ``` 𝓱𝓮𝓵𝓹.__𝓬𝓵𝓪𝓼𝓼__.__𝓮𝓺__=𝓮𝔁𝓮𝓬;𝓱𝓮𝓵𝓹.__𝓬𝓵𝓪𝓼𝓼__.__𝓵𝓮__=𝓬𝓱𝓻;𝓱𝓮𝓵𝓹==F'{𝓱𝓮𝓵𝓹<=2*2*2*2^2*2*2*2*2^2*2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2^2*2*2*2^2*2*2*2*2^2*2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2^3^2*2*2^2*2*2*2*2^2*2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2^2*2^2*2*2^2*2*2*2*2^2*2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2*2^2*2*2*2^2*2*2*2*2^2*2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2*2*2^2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2^3^2*2*2*2^2*2*2*2*2}{𝓱𝓮𝓵𝓹<=2^3^2*2*2^2*2*2*2*2}' ``` ### Subset 3 We've already used up `.`, `=`, and `()`, so finding a way to call `exec` is becoming difficult. The one thing that is free are variable names, since Unicode provides us with more than enough variations of each letter. However, it is possible to do so by abusing asserts: ``` AssertionError=exec;assert 0,'print(1)' ``` `assert` takes two arguments: the pass/fail condition, and a string which is printed when the condition fails. This is roughly equivalent to `if cond: raise AssertionError(msg)`. By reassigning `AssertionError` to `exec`, the `msg` parameter effectively becomes the first argument of `exec`. Curiously, this feature seems exclusive to `AssertionError`, as other error types I've tried don't behave like this. Anyway, this by itself doesn't work because we can't use `=` or `;`. The second trick is to abuse `for` loops. Let's just do `for AssertionError in[exec]:` instead! The last thing we need is the string construction, which can be done using `%`-formatting and repeated `-~`s. The size of the code grows exponentially, but here's an `exec('print(1)')`: ``` for 𝐀𝐬𝐬𝐞𝐫𝐭𝐢𝐨𝐧𝐄𝐫𝐫𝐨𝐫 in[𝐞𝐱𝐞𝐜]:assert 0,"%c%%c%%%%c%%%%%%%%c%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%c"%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0%-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~0 ``` ### Subset 4?? Originally, I planned for a 4th subset through executing Python bytecode, since Python is able to natively run `pyc` files. The magic header for `pyc` files in Python 3.11 is `\xa7\x0d\x0d\x0a`. I noticed the `\x0d` and `\x0a` as being newlines, so I crafted my other solutions specifically without them. But I somehow missed the `\xa7` byte which is not representable in UTF-8, making this solution automatically invalid. Still, there is some good potential for a 4th subset. For example, using `#coding:u7` to change the source's encoding could've also worked in place of Subset 3. Decorators are a possibility as well. I also vaguely recall Python also being able to natively handle zip files, and the PKZip magic header makes this a possibility: `\x50\x4b\x03\x04`. Lastly, the challenge only asks for "Turing-completeness", not arbitrary code execution. I only tried to do the latter, so it's possible that scoring 4 is quite a bit easier than I'm making it. [Answer] # Jelly, score ~~7~~ ~~8~~ ~~9~~ 10 ``` VŻỌ‘’ 01uvọŒ⁾¤ 2ṭḊḢĿ¶ 5[,]?`FñṖṪị &Hrx}Æçƭḷ¹⁹€ :@U\_½ÄÇר jµœƬṣ“” "$+8DLMṀns¿ CNt©®ÐƊḌḶṃṄẒE %34b¡ÑḅẸ⁺ ``` There is some room for interpretation as to what a Turing-complete language is, and thus what a Turing-complete subset of a language is. For these answers, I have used the strictest common definition: these are subsets for which it is possible to compile a Turing machine into that subset of Jelly, producing a finitely long program that halts if and only if the Turing machine halts. (Note that the proofs below don't start all the way from Turing machines, but from other Turing-complete languages; this is valid because you can first compile the Turing machine into the language I started from because it's Turing-complete, and then into Jelly.) Halt behaviour is the only thing that matters for Turing-completeness; things like I/O are not important, and the compiled Jelly programs are thus written as full programs that take no input. Although I've improved this answer quite a bit since it was first posted, it is probably still improvable: I still have lots of characters unused, and some of these character sets are slightly larger than necessary (but easier to explain than a fully-"golfed" set would be). However, it's becoming increasingly hard to find ways to do things like express constants, create potentially infinite loops, and to get the program to halt when the emulated program halts. Still probably possible, though. Note that many of these character sets can be considered as interesting "cop problems" for a hypothetical [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") question; some readers might find it fun to try to figure out for themself how some of these subsets are Turing-complete before reading onwards. ## Explanations There are a lot of solutions here (by "solution", I mean a subset of characters via which Jelly is Turing-complete, with the solutions chosen so that none of them overlap in characters), with some parts of the explanation common to multiple solutions but most of it specific to a particular solution. As such, each answer is going to get its own individual explanation, but sometimes there will be shared explanation in a section beforehand. ### Eval-based solutions One way (but not the only way!) to prove a character subset Turing-complete is to show that it can `eval` arbitrary code in a Turing-complete language, using an `eval` builtin or equivalent. Jelly has a few different ways to `eval` code, but all of them are spelled using the character `v` or `V`, meaning that there is a limit of two `eval`-based solutions. Now, there's one property of Jelly that makes writing `eval`-based solutions fairly difficult: Jelly does not like to do arithmetic on characters, and has very few operations that can change a character into a different character, or create an arbitrary character from scratch. This is a problem because the `eval` functions operate on strings (which in Jelly are lists of characters), but in order to evaluate arbitrary code, we have to be able to produce arbitrary strings starting from a limited character set (ideally as small as possible, to leave more characters for the other subsets). The usual approach for constructing arbitrary strings in Jelly is to use the `Ọ` command, which takes an integer (or list of integers) as its argument, and outputs the character with the given character code (or string whose characters have the specified character code). That's one perfectly fine solution to the problem of "starting from a limited character set, produce an arbitrary string in Jelly". The problem is that it's only *one* solution, but there's space for two `eval`-based solutions, meaning that a second way to produce strings is needed. See below for how I managed it! #### `eval`, the easy approach: using `Ọ` *Character set: `VŻỌ‘’`* A very simple approach to get things started. Using `Ż` at the start of a 0-argument program produces the list [0]. That element can be incremented and decremented to any desired value with the increment instruction `‘` and decrement instruction `’`. Then a new 0 can be prepended to the list with `Ż`, and the increment and decrement instructions will then affect the entire list, and this can be continued making the list longer and longer over time. It's possible to produce an arbitrary list of integers this way: just set each element to its correct value *relative to the previous element*, and finally set the first element to its correct value, which will cause all the other values to be correct. After producing an arbitrary list of integers, it can be converted to a string with `Ọ` and evaluated as a program with `V`. [Here's an example program written in this subset.](https://tio.run/##y0rNyan8//9Rw8wRiI7uHpn@pl/ozhhFQxod3Q2CgzUyH@7uCfv/HwA "Jelly – Try It Online") [And here's a compiler.](https://tio.run/##AUAAv/9qZWxsef//4bmgwrsw4buL4oG@4oCZ4oCYeEEKT8W7VcW7ScOH4oKsauKAncW7O@KBvuG7jFb///8xMDAww4ZS "Jelly – Try It Online") This construction is simple and small enough that it's possible to run the compiler, and the compiled program is small enough to fit in this post. This will not be the case for all the future constructions! #### `eval`, the hard approach: without using `Ọ` *Character set: `01uvọŒ⁾¤`* `Ọ` makes things easy, but it turns out that avoiding it is just about possible. The basic idea is to note that because we have an `eval` operator in our character set, it's possible to get at the *effect* of `Ọ` either by using the `Ọ` command itself (which we can't use), or by producing the *string* `"Ọ"` and `eval`ing it. However, this is still fairly difficult as `Ọ` is the primary way to produce arbitrary strings in Jelly, with the main obstacle reducing to "how do you produce an `'Ọ'` if you don't have one already?". I could actually only find two ways in Jelly to produce an `'Ọ'` without already having a string that contained an `'Ọ'`. One possible approach is to index into `ØJ`, a predefined constant that contains all the characters used by Jelly (including `'Ọ'`); but indexing operators are *really* useful when implementing Turing-complete languages from scratch, so I didn't really want to spend them here. Instead, I used the other approach: Jelly has a few case-changing operators that take strings as input and return strings as output, meaning that it is possible to produce `'Ọ'` by uppercasing a lowercase `'ọ'`, and although a few different commands work, I couldn't find a reason to use anything other than the uppercasing command `Œu` (all casing commands contain `Œ` so there is no way to avoid using that, and `u` is not useful except to spell `Œu` – it doesn't spell any other commands). Producing `ọ` is basically as difficult as producing `Ọ`, but because `ọ` is in our character set, it's possible to just write it in a string literal. For this subset, I used the `⁾` form of string literals, which is limited to strings that are exactly two characters long – this is sufficient for this subset, and the least generally useful for other subsets. This approach needs at least `uvọŒ⁾`, and adding `01¤` produces a complete Turing-complete subset. Unfortunately, this is one of those JSFuck-style subsets in which a full construction gets slowly built up out of smaller parts and the resulting programs are basically unreadable, so I'm going to go through the steps one at a time. [A snippet demonstrating each step, at Try It Online!](https://tio.run/##y0rNyan8//9R476Hu3uB6Oik0kNLuAwNqACAphkaAA1DNbuMmmbTyHTc1pXR1DOoxsGFQRFi5BLKZUgfYDAKqAxcjix4uKvj4e4eLuRQRg9rEN/l6KR0oFJ6RfWQS0nQ8AEGJTiv/Dc8tPjhzpaHO2crGMFZxnCWCZxlCmeZwVnmcJbFocX/AQ "Jelly – Try It Online") 1. Jelly is normally a fairly linear language (start with value **y**, do **A** to it, then do **B** to it, etc.), but the construction here contains expressions which are more complicated in shape. As such, I'm using the grouping operator `¤` which basically makes Jelly into a postfix language if used everywhere: what would be written `1 + 2` in an infix language becomes `1 2 +` in a postfix language and `1+2¤` in Jelly, and what would be written `¬3` in a language with prefix unary operators becomes `3 ¬` in a postfix language and `3¬¤` in Jelly. As such, the string `"ỌỌ"` (which has the same effect when executed as `"Ọ"` – `Ọ` is idempotent) can be written as `⁾ọọŒu¤`, i.e. "`Œu` applied to `"ọọ"`, written as a postfix expression"). 2. In addition to being a lowercase `Ọ`, the `ọ` command is actually mildly useful in its own right; it returns the number of times its right-hand argument divides into its left-hand argument. This means that with `01ọ¤` it is possible to write arbitrary nonnegative integers, e.g. `1000ọ10¤` is 3 because \$10^3=1000\$, and it is possible to create larger numbers simply by adding more zeroes. 3. Being able to construct `"ỌỌ"`, it is then possible to evaluate it using the evaluate-with-argument command `v`. Because it's possible to produce arbitrary integers, this can produce arbitrary single characters. The example in the TIO! link produces `'D'` by doing `“ỌỌ”v68¤`. 4. By nesting uses of `…v…¤` it is possible to produce arbitrary expressions that consist of a constant, followed by any number of single-character unary builtins. The expression shown here is `“U”v“D”v12¤¤`… 5. …which is just another way to write `12DU`, i.e. "reverse the digits of 12". I will be writing the remaining examples in this linear form, because it's much easier to read, but all of them can in theory be expanded to use `…v…¤` rather than being written linearly. 6. Directly producing arbitrary strings using only the single-character unary builtins is nontrivial (the single-character nullary builtins aren't useful, and the single-character binary builtins aren't useful here because `v` has no way to give them two different arguments). There are some strings that can be constructed, though. On this line, I construct the string `"Œg"` by starting with a number with 338 0 digits and 103 1 digits (which can just be written directly because the character set contains both `0` and `1`), taking its digits (`D`), grouping the digit positions by their values (`Ġ` – this produces a list of a 338-element list and a 103-element list), taking the length of each of the inner lists (`Ẉ`) to produce [338, 103], and then converting those character codes to characters to produce `"Œg"`. Note that the `D`, `Ġ`, etc. don't need to appear literally in the source; they are all produced using the technique shown in step 3, and combined into a single expression using the technique shown in step 4. 7. Now that it's possible to produce the string `"Œg"`, it can be evaluated in order to run the `Œg` builtin. It's possible to produce an arbitrary list whose elements are 0 and 1 (starting with 1) by using `D` on a number that can be written directly using our character set. `Œg` does run-length grouping, so it produces a list of lists for which the length of each internal element matches a run length in the original array. `Ẉ` can convert that format into an arbitrary list of positive integers. In the example, starting with `11111111110011110000000000001111` gives us `[10,2,4,12,4]` – the run lengths of the original constant (it has 10 1s, then 2 0s, then 4 1s, etc.). 8. Being able to produce arbitrary lists and run `ỌỌ` on them makes it possible to produce arbitrary strings; these can be given to `v` to make it possible to run arbitrary code in Jelly's character set (because the character set does not contain NUL, all its characters have positive Unicode codepoints and thus it doesn't matter that step 7 generates positive integers only). The TIO! example runs a program that prints the positive prime integers below 1000. So in summary: there is a way to bracket expressions arbitrarily, `ọ` can be used to produce arbitrary integers, and that makes it possible to produce and evaluate single-character strings. That isn't fully general on its own but is good enough to produce `"Œg"`, which in turn makes it possible to write arbitrary arrays of integers, and those can be converted to strings and evaluated in order to write any program. ### Solutions based on tag systems A [tag system](https://esolangs.org/wiki/Tag_system) is a simple Turing-complete language that works as follows. A program consists of a map from characters to strings, and a number *m*, together with an initial string. Data storage is done by using a string that acts like a queue (and starts with the specified value). To execute the program, delete the leftmost *m* characters of the queue-string; then, look up the string that corresponds to the first of the deleted characters according to the map, and append that string to the queue-string. There are various definitions of a halting (e.g. "delete when a special 'halt' character is looked up in the map", "halt when the queue is empty", "halt when the queue has less than *m* elements"). All are Turing-complete for all *m* ≥ 2 (e.g. [UT19](https://esolangs.org/wiki/UT19) is a tag system that's Turing-complete witih all three definitions). #### Using `Ŀ` *Character set: `2ṭḊḢĿ¶`* One simple way to compile a tag system to Jelly is to use the `Ŀ` builtin. Here's what that could look like if we had Jelly's full character set available, implementing [the example tag system on Esolang](https://esolangs.org/wiki/Tag_system#Example): ``` Ḋ3ṭ3ṭ2ṭ1ṭ4ṭḢĿ Ḋ3ṭ3ṭ1ṭḢĿ Ḋ3ṭ3ṭḢĿ 2Ḋ1ṭ2Ŀ ``` [Try it online!](https://tio.run/##y0rNyan8///hji7jhzvXgrAREBsCsQkQP9zZ8nDHoiP7uZDkDXGIw8W4jICiUFVGR/b//w8A "Jelly – Try It Online") (has added `Ṅ` to show the steps of execution) The `Ŀ` builtin is designed for function calls, but in this program, it is used only at the end of a function – in tail position – so it effectively acts like a `goto` command (as soon as any function returns, all of them return, so the call stack is irrelevant). It is preceded by an argument that specifies which line to jump to, so this version of the construction needs newlines (in Jelly's character set, the newline character can be rendered either with an actual newline or as `¶`, but the two are equivalent views of the same character rather than being two separate characters, so it's usual to use whichever rendering makes more sense in the context). The key observation is that `ḢĿ` – "jump to the line given by the first element {of the list on which we're currently operating}" – can be used as a lookup-in-map operation: using line numbers as the characters of the string, the code on line *n* can be code that appends a specific string literal to the string (and then removes the characters from the start and jumps with `ḢĿ`). A halt symbol can be implemented using a line with no code. To implement this in Jelly, the idea is for each line of code to remove characters from the start (`Ḋ` – this can be repeated to remove as many characters as needed, with one already having been removed by `Ḣ`), and to append the appropriate elements at the end (e.g. [3,3,1] can be appended using `3ṭ3ṭ1ṭ`, using the "append element" command `ṭ`). The initial string can be implemented using very similar code, but there's a need to produce a list to append to so that `ṭ` behaves appropriately. `Ḋ` is overloaded to produce a list from 2 to the given integer inclusive, so `2Ḋ` produces the list [2]. This means that the second element of the initial string must be 2, but fortunately that's one of the elements that is skipped, so its value has no effect on the resulting program. In the "all of Jelly is allowed" method of compiling a tag system, the used characters are `0123456789ṭḊḢĿ¶`. However, if you spread the program out enough, only `2` is actually needed (for `2Ḋ`): nothing goes wrong if you name the elements of the tag system `2`, `22`, `222`, etc. rather than `1`, `2`, `3`, etc., and simply add a lot of newlines to the program to put the various code that implements map elements onto the appropriate line. #### Using `ị` *Character set: `5[,]?`FñṖṪị`* Instead of baking the tag system's map into our program's control flow, it's also possible to simply just use a list as though it were a map; the tag system alphabet can be made out of integers, and those integers can be list indexes. Reading from the map can thus be done with a list indexing instruction, such as `ị`. Here's what that might look like if we had Jelly's entire character set to play with, implementing [Liesbeth De Mol's Collatz tag system](https://en.wikipedia.org/wiki/Tag_system#Example:_Computation_of_Collatz_sequences): ``` Ṫị[[3,2],[1],[1,1,1],[1,1,1]];ṖÑ5Ṗ? ``` [Try it online!](https://tio.run/##y0rNyan8///hzlUPd3dHRxvrGMXqRBuCsA4QwulY64c7pz3c2XJ4oimQYf//PwA "Jelly – Try It Online") (contains added print statements so that you an see what is happening) The implementation starts by removing the last element from the current value (`Ṫ`) and using it to index (`ị`) into a list literal (specified using Jelly's list literal syntax, which involves `[,]` and decimal integers) – the queue is stored "backwards" compared to the previous case. It then appends (`;`) the current value minus its last element (`Ṗ`) – two elements were removed from the end, of which only one was used, and so this is a 2-tag implementation. It is possible to add additional `Ṗ` at this point in order to implement higher values of *m*. All that's needed after this is to handle halting, which here is done with an `if` statement, `Ñ5Ṗ?` (`?` specifies an `if` statement, and is preceded by the true case `Ñ`, the false case `5`, and the condition `Ṗ`). If the list has multiple elements, it'll be truthy when an element is removed with `Ṗ`, so `Ñ` is run, which is a recursive call to the main program. (This `Ṗ` does not actually affect the content of the list – it just provides a truth value to the `if` statement.) If the list does not have multiple elements, removing an element will produce an empty list, which is falsey, so `5` runs – that isn't a recursive call (it's an integer constant), so the program exits. There is something apparently missing in the above explanation: how does the initial string get there, given that the program is run with no argument? The behaviour of `ị` when given no useful input data is to return the last element of the list it's indexing into, so it's possible to simply append the input string (`[1,1,1]`) to the end of the list that serves as the tag system's map, as an additional element that's never read once the program has started but will be used on the first iteration. (If *m*>2, some of the elements at the end will get removed on the first pass through the program, but this can be compensated for by adding extra junk elements to the initial string.) One thing worth noting is that Jelly's list literal syntax is broken and doesn't support empty lists (`[]` seems like it should work, but actually causes the lexer to crash). Fortunately, this [turns out not to matter](https://esolangs.org/wiki/UT22). As in the previous solution, it's possible to remove digits other than `5` from the character set by using only list elements whose indexes are 5, 55, 555, etc., with irrelevant data in the others. However, it's possible to go further with this, saving some valuable characters for other solutions: * Because this solution uses `,` anyway (to write the list literals), it makes more sense to write `;` (append) as `,F` (pair and flatten), which does the same thing on one-dimensional lists. * `Ñ` is a convenient way to do recursion – convenient enough that it is better to use it in another solution! It is possible to use `ñ`` instead, which is also a recursive call, but uses a different parser (designed for functions with two arguments). The program can be made robust, so that it parses correctly either as a two-argument function or as a full program, by doubling the `F` (one of the `F`s will always be a no-op, but which one depends on the parser in use – and `F` is idempotent so doubling it is OK). The resulting program looks like this (and can be padded to use no digits but 5s in the literals): ``` Ṫị[[3,2],[1],[1,1,1],[1,1,1]],FFṖñ`5Ṗ? ``` [Try it online!](https://tio.run/##y0rNyan8///hzlUPd3dHRxvrGMXqRBuCsA4QwulYHTe3hzunPdzZcnhjgimQZf//PwA "Jelly – Try It Online") The only part of the program that varies is the list literal, written using `[5,]`, and the rest of the program is fixed and the only additional characters it uses are `?ñ`FṖṪị`. ### A solution based on Echo Tag *Character set: `&Hrx}Æçƭḷ¹⁹€`* [Echo Tag](https://esolangs.org/wiki/Echo_Tag) is a simplified version of cyclic tag. It works as follows: there is are two queues of 0s and 1s, a *data queue* and a *program queue*, and a number *n*. Execution proceeds by repeatedly dequeuing from both queues simultaneously; the value dequeued from the program queue is enqueued once back onto the program queue (so it cycles forever), and onto the data queue *n* times if a 1 was dequeued from the data queue, but not at all if a 0 was dequeued from the data queue. It has been proven Turing-complete for all *n*≥68 (and is probably Turing-complete for all *n*≥2). This answer uses *n*=256. The basic form of the program is as follows: ``` ⁹…ƭ€&⁹x⁹ḷÆr}⁹ç ``` To implement the program queue, this solution uses Jelly's "tie" builtin `ƭ`. This is preceded by two commands, e.g. `ABƭ`, and alternates between them every time it runs; if you ran `ABƭ` in a loop (even one created by recursion), it would alternate betwen running `A` and `B` each time. A tie builtin can be preceded by another tie builtin, which means that it's possible to create a builtin that cycles through 2*x* different commands (and there is a UT19 implementation in Echo Tag with *n*=256 and a 256×256×2=131072-element program queue, which is a power of 2, so the restriction to power-of-2-length programs doesn't matter); the 0 and 1 of Echo Tag are implemented using `H` (halve) and `¹` (do nothing). The data queue is implemented using a list of 256 (representing 1) and 0 (representing 0); the program queue is mapped over it using `€` (so 256 becomes 128 where the program queue is 0) and bitwise-anded with it using `&` (so 128 becomes 0). `x` then repeats each element of the mapped queue a number of times equal to the corresponding value in the original data queue; thus, where the data queue had a 0, it now has nothing: where the data queue had a 256, it now has 256 256s or 256 0s, depending on the value in the program queue. The position in the program queue is remembered across both the `€` loop, and the recursive loop that makes up the whole program. To handle halting, the code fragment `ḷÆr}` is used. This runs the `Ær` builtin on the command's second argument (`}`), and ignores the result (`ḷ`). `Ær` finds the roots of polynomials, which is very slow for lists as long as Echo Tag uses (even a trivial example program takes 12 seconds to run!), but the advantage here is that it will succeed on any non-empty list and yet it crashes when given an empty list, exiting the program when and only when the data queue empties. Program startup is interesting, and makes use of both an arity polyglot and a data-type polyglot. When run with no arguments, `⁹` means 256, and the end of the program parses as: ``` ⁹…ḷÆr}⁹ç ḷ no-op } ignore everything so far and Ær calculate the roots of the polynomial ⁹ 256 ç 2-argument recursive call with that and ⁹ 256 ``` meaning that the first recursive call is a 2-argument recursive call with an empty list and 256 as the arguments (256 is a valid polynomial, but it has no roots because no value of *x* gives 256=0). On the second call, `⁹` means "the right-hand argument" (which is still 256), but the program now parses entirely differently: ``` ⁹…x⁹ḷÆr}⁹ç x repeat each element a number of times equal to ⁹ the right-hand argument Ær calculate the roots of the polynomial } specified by the right argument ḷ but ignore the result ç 2-argument recursive call with ⁹ the right argument as its left argument {and the result of x⁹ as its right argument} ``` On this execution, the `€` interprets the 256 as a range from 1 to 256 inclusive, but the `&` and `x` interpret it as just the number 256. The result is an array of 65536 elements, most of which are 0 (both 128 and 256 are possible elements in the resulting list, but the program queue can be designed to stop the 128s appearing). This is a valid data queue that creates a startup state that can be Turing-complete (as startup code can be added to the program queue, whilst retaining a power-of-2 length), so from the third iteration onwards, everything runs normally, and everything expected to be a list actually is a list. [Here's an example](https://tio.run/##y0rNyan8//9R485DQHhs7aGdHsfWHlv7qGmNGlCsAogVjk4qeriz5eikhztnKgD5h@dzGWGoNaowQlFndHj5//8A "Jelly – Try It Online") of a program in action, using 2 rather than 256 (with added run-length-encoded debug output). And [here's an example](https://tio.run/##y0rNyan8//9R404Pj2NrQfjY2kdNa9SAAhVArPBwx/ajk4oe7mxRqQWxD7cV1SoAxQ8v//8fAA "Jelly – Try It Online") that demonstrates startup and halting with a trivial Echo Tag program, using the full 256. ### A solution based on Blindfolded Arithmetic *Character set: `:@U\_½ÄÇר`* [Blindfolded Arithmetic](https://esolangs.org/wiki/Blindfolded_Arithmetic) is a language that I originally created as [a cop in a cops-and-robbers challenge](https://codegolf.stackexchange.com/a/162531/). The original version had six variables, but I subsequently proved that it is [Turing-complete using only two variables](http://nethack4.org/esolangs/blindfolded-arithmetic-2var.txt). It's the two-variable version that I'm using for this solution. The two-variable Blindfolded Arithmetic has two unbounded integer variables (here called *X* and *Y*, starting at 1 and 0 respectively), and each command adds, subtracts, multiplies or floor-divides two variables and stores the result back into a variable. For example, a command might be `X = X + Y` or `Y = Y / X`. The program runs in an infinite loop forever, ending only upon division by zero. There are a couple of complications when it comes to working out how many commands need to be implemented: * Subtractions and divisions are asymmetrical, so `Y = Y / X` is a different command from `Y = X / Y`, and both are useful. So when taking two different variables as arguments, these need to be counted twice. * It is occasionally useful to be able to use the same variable as both operands, along the lines of `X = X + X`. The Turing-completeness proof only does this when the result is being stored back into that variable (it doesn't, e.g., self-add one variable into the other). That comes out to a lot of commands, and this construction doesn't quite manage to implement all of them: self-subtract, self-multiply and self-divide are missing (although self-add is present). It does, however, have a "halve" command `Y = Y / 2` (which is not present in the original language: it *only* contains the variables, no constants!). This can be used to replace the two uses of self-subtraction in the original proof; the first use appears in a sequence of commands that go from \$X=Y=e\times t\$ to \$X=e\times t, Y=t\$ (which can be accomplished easily using a "halve" command because *e* is a constant power of 2, so you just halve Y \$log\_2 e\$ times); and the second use is used to set Y from a known value *d* to 0 (which can be accomplished by repeatedly halving *Y* until it hits zero – because the value of *d* is known, it is known how many halvings this will require). Unlike some of the previous answers, this one can be given as an explicit translation of each of the commands that are implemented: ``` Y=Y/X :@\ר½:ؽ Y=X/Y :\ר½:ؽ Y=Y-X _@\ Y=X-Y _\ Y=Y+X or Y=X+Y Ä Y=Y*X or Y+Y*X ×\ start of program ؽ:@UU:ؽU swap X, Y U Y=Y+Y (or Y = Y*2) ר½ Y=Y/2 :ؽ end of program Uר½×Ø½Ç ``` Only the commands that assign to *Y* are implemented directly; for commands that assign to *X*, you swap *X* and *Y*, run the command with *X* and *Y* swapped, then swap *X* and *Y* back again. [Here's a demonstration of the commands doing their thing](https://tio.run/##y0rNyan8/z/eIUbh4c4WBSuHmMPTD884tNcKRECEMETiIWoPT4fQML2HW6DCCK1wVihRpv///z/axEBHwdjMMBYA "Jelly – Try It Online"), and [here's an example of a compiled program](https://tio.run/##y0rNyan8///wjEN7rRxCQ61AjFCFE@sUtGOgKFTh8HQQCZaCkg93tiiEHp4OYkPJ9v//AQ "Jelly – Try It Online"). Both have had print statements added so that you can see them in action. The basic construction is very simple: `\` is a modifier to a two-argument builtin that makes it act cumulatively on a list, e.g. `[*x*,*y*,*z*]+\` is [*x*, *x*+*y*, *x*+*y*+*z*]. When operating on a two-argument list, this maps [*x*, *y*] to [*x*, *x* op *y*] which is exactly what most Blindfolded Arithmetic instructions do. As a result, by putting Jelly's operators for addition `+`, subtraction `_`, multiplication `×` and floor-division `:` before the backslash, it is possible to implement four of the Blindfolded Arithmetic commands – and the modifier `@`, meaning "swap arguments", immediately gives two more. Reversing the list (`U`) makes it possible to operate on *X* rather than *Y*, producing the twelve "basic" commands. (One small variation: although `+\` is a perfectly fine implementation of `Y = Y + X`, I used the equivalent abbreviation `Ä` because I wanted to use `+` in a different solution.) Three obstacles remain. One is to get the program started; the first iteration of the program needs to start with the list [1,0], but subsequent iterations need to start with the value at which the previous iteration ended. Ending the program is also nontrivial: unlike Blindfolded Arithmetic's `/` operator, Jelly's `:` does not crash when dividing by zero (returning infinity or NaN as appropriate). Extra characters will be needed simply to get at a two-element list in the first place. The other obstacle is implementing the self-additions, self-subtractions, etc.; most of these are nontrivial in Jelly (which is why this construction uses a modified version of the language which doesn't need self-subtractions/multiplications/divisions for Turing-completeness). The same builtin happens to solve all these problems at once: the builtin `ؽ`, which is a constant with value [1,2]. It solves the problem of forming a two-element list, because it is a two-element list. It also immediately provides `Y = Y * 2` and `Y = Y / 2` instructions because `×` and `:` do pointwise multiplication and floor-division when operating on lists, thus `ר½` multiplies X by 1 (a no-op) and Y by 2, and likewise for `:ؽ` and division. It also happens to be of use in starting and ending the program, but this is a bit more subtle. This construction, when wrapping from the end to the start of the program, encodes the list not as [*X*, *Y*] but as [*Y*, 4*X*], an encoding that is easily produced directly using `Uר½×ؽ`. The start of the program, `ؽ:@UU:ؽU`, undoes this translation. However, the "goto" command (actually a tail-call) that goes back to the start is not the usual `ß`, but rather `Ç`, "run the next line (wrapping around the program) parsing it as a 1-argument function". This reruns the main program, but the main program is a 0-argument function, so the use of a different parser means that the start of the program parses slightly differently: ``` ؽ:@UU:ؽU (0-argument function) ؽ [1,2] :@ pointwise divide into U the reversed {initial expression [1,2]} (i.e. [2,1]) (producing [2÷1, 1÷2] = [2,0] using floor-division) U reverse (producing [0,2]) :ؽ pointwise divide by [1,2] (producing [0÷1, 2÷2] = [0,1]) U reverse (producing [1,0]) ؽ:@UU:ؽU (1-argument function) ؽ [1,2] :@ pointwise divide into the {argument} (i.e. [Y, 4X]) (producing [Y÷1, 4X÷2] = [Y, 2X]) UU reverse twice (no-op) :ؽ pointwise divide by [1,2] (producing [Y÷1, 2X÷2] = [Y,X]) U reverse (producing [X,Y]) ``` In the former case, the `U` is *inside* the `:@`; in the latter case, it comes *afterwards*. This difference in the parser isn't something that's being intentionally exploited, but rather, something that had to be worked around. As for the end of the program, this exploits what is probably a bug in Jelly. `:` has been extended to handle infinities, and cases like 0/0, 0/infinity, and the like all work correctly. However, apparently only the corner cases, not the edge cases, were implemented, because dividing infinity by a normal integer (e.g. infinity/2) causes the Jelly interpreter to crash with an exception. (It took me a surprisingly long time to find this; after discovering that all the corner cases worked correctly, I assumed there was no way to get it to crash until I hit an edge case by accident.) As such, after every division, Y is immediately doubled and then halved again; this is a no-op in most cases, but after a division by zero, it will cause the program to crash, emulating Blindfolded Arithmetic's halt behaviour. (0÷0 probably doesn't work, but the halt case for Blindfolded Arithmetic's Turing-completeness proof is implemented by dividing 0 into a positive number and never uses the case of 0÷0.) ### A solution based on Thue *Character set: `jµœƬṣ“”`* [Thue](https://esolangs.org/wiki/Thue) is a very simple programming language based around find and replace: starting with an initial string, each instruction specifies a search string, and a string to replace it with if it is found. The instructions run in an arbitrary order, as many times as necessary, until no more instructions can be run. (The original version of Thue had a mathematically nondeterministic evaluation order – i.e. the interpreter was supposed to look ahead to work out what sequence of replacements would cause the program to halt – but that mutated at some point into "just run a random command" due to a misunderstanding of "nondeterministic", and the language turns out to be Turing-complete no matter what algorithm the interpreter uses to decide which order to run the commands in, because it is possible to write Thue programs such that only one command is runnable at a time. In fact, Turing machines compile pretty much directly into Thue with that restriction.) Thue compiles almost directly into Jelly, as long as the program is written to not care about evaluation order. The form of the program is *initial string* `µ` *productions* `µƬ` (with `µ…µT` being "loop until nothing changes"), where each production is of the form *string* `œṣ` *string* `j` (i.e. "split on *string 1*, then join on *string 2*", a very simple way to implement find-and-replace). Characters like `j` and `œ` are perfectly usable as the content of string literals (and Thue only needs two different characters to be Turing-complete), so in addition to `jµœƬṣ`, all that is needed are the string literal delimiters `“”`. [Here's an example program using this character set.](https://tio.run/##y0rNyan8//9Rw5yjk0EwKyvrUcPcQ1uPTn64czFYFMQH4jlZRyeDZY6t@X@43fs/AA "Jelly – Try It Online") ### A solution based on The Waterfall Model *Character set: `"$+8DLMṀns¿`* [The Waterfall Model](https://esolangs.org/wiki/The_Waterfall_Model) is what seems like one of my more fundamental programming discoveries. I stumbled across the language several times in different contexts, and it took me a while to make the connection, but nowadays it's one of my most powerful tools for proving things Turing-complete. The basic idea behind the language is: you have a number of counters ("waterclocks") each of which holds an unbounded integer; if none of them are 0, then all of them are decreased by 1; if one of them is 0, then a specific number is added to each counter, based on which counter it is that zeroed. A program consists of initial values for each counter, plus a two-dimensional matrix that specifies the amount added to each counter when each counter zeroes (with the coordinates being the counter that zeroed, and the counter that is added to). Counters aren't allowed to go negative, so every counter is supposed to add to itself when it zeroes. It is known that it is possible to write an interpreter for The Waterfall Model using only four different characters. [Using each of them only once.](https://codegolf.stackexchange.com/a/125815) That was one of the first occasions upon which I stumbled across it, and at that point it didn't even have a name yet. However, the four-byte interpreter isn't really usable for *this* challenge, for two reasons: a) it's an interpreter not a compiler, and the implicit input of the program is exploited to set up the data structures it uses; b) it doesn't implement the language's halting behaviour. Still, it wasn't too hard to adapt it into a subset of characters that can be compiled into. This solution implements a variant of The Waterfall Model in which the initial counter values are all in the range 0…9, as are the values added when a counter zeroes; it's still Turing-complete with that restriction (the Turing-completeness construction uses only small integers, none as large as 10). There are two basic parts to the program: a) setting up an appropriate data structure in memory, and b) implementing the language once the data structure is set up. First, the setup (which has a [couple of accompanying examples on TIO!](https://tio.run/##y0rNyan8/98CDbj4uHAZGhmbmJqZW1hamJuZmhgbuRSb/Dc8tPjhzpaHO2crGB1a/B8A "Jelly – Try It Online")). This is done using the four characters `8DLs`. It is possible to create integers with arbitrary numbers of digits by writing a lot of 8s in a row; `DL` (digit length) can then be used to construct an arbitrary integer (e.g. `88888DL` is the integer 5). Following this with `D` (digits) can then be used to produce an arbitrary list with all elements in the range 0…9 (as long as the first is nonzero), as shown in the first line of the TIO! link. That list can then be split using `s` into a list of lists (a matrix), so long as the number of columns is 8, or 88, or 888, etc.; the number of columns in the matrix equals the number of counters plus one, and it's possible to add "junk counters" that never become zero in order to top the number of counters up to an appropriate number. This forms a data structure that is used to store both the counter values, and all the zeroing triggers. In order to shrink the set of used characters slightly, the data structure is stored "upside down" (lower numbers within the data structure correspond to higher numbers within the program that was compiled), and has the following structure: * The first row is arbitrary, except that all elements but the first are equal to each other, with the first being smaller. * The rest of the first column stores the counter values, encoded as the difference between the actual counter value and the largest value within the column (with lower meaning a larger value); only their relative values matter, not the absolute value. For example, counter values of [1,4,3] could be encoded as [4-1, 4-4, 4-3] (i.e. [3,0,1]), or as [9-1, 9-4, 9-3] (i.e. [8,5,6]), or even as [1000-1, 1000-4, 1000-3] (i.e. [999, 996, 997]). (This implementation has a tendency to use unnecessarily large values as a base to subtract from; with many programs they will increase exponentially over the lifetime of the program.) * The remainder of each row stores the zeroing triggers, again with only their relative values mattering (and lower values meaning "increase the counter by more"). If the first counter zeroing increases itself by 3, the second counter by 0, and the third by 2, that could be represented as [*x*, 0, 3, 1] (where *x* represents the counter value), but, e.g., [*x*, 6, 9, 7] would be equally valid. When all the counters and all the zeroing triggers are in the range 0…9, it is possible to subtract them all from 9 (and add a row of the form [1,2,2,…,2] at the start) in order to produce a matrix of the required form using only elements in the 0…9 range (which can be created using the `888…888DLDs` construction). To actually implement The Waterfall Model given this data structure, all that is needed is a loop that repeatedly finds the lexicographically largest line within the data structure, then adds the first element of that line to the entire first line, the second element of that line to the entire second line, and so on (in Jelly this addition is a builtin, `+"`, and there is a `Ṁ` builtin for "maximum" to identify the appropriate line). To see why this works, realise that the row with the largest value in the first column, if it's a counter, will be the counter nearest zero (because the encoding is upside-down), thus it will be the counter that zeroes next. The addition's effect on the first column will then change the relative values of the counters as though the appropriate value from the zeroing trigger were being added (and the absolute value doesn't matter, meaning in turn that only the relative values of the "rest of the row" matter). It also has an effect on columns other than the first, but this affects all those columns equally, so they will still have the correct relative vaues. It is possible that the first row (which doesn't correspond to a counter) will have the largest value. In this case, it adds a smaller value to itself than it does to each of the other rows, so it doesn't change the relative values of the counters, and will eventually not be the largest any more; in other words, it ends up having no effect on the program execution as a whole. The main tricky remaining part is to halt the program when the halt counter zeroes. It is sufficient for Turing-completeness to have a single halt counter with a fixed index; in this case, I used the seventh counter (which corresponds to the eighth row of the matrix). The code for the main loop looks like this in Jelly: ``` +"Ṁ$MṀ$n8$$¿ ¿ while loop $ body (2-builtin block): +" {to each row of the matrix}, add corresponding elements of Ṁ the maximum {row of the matrix} $ $$ condition (4-builtin block): M the index of the maximum row Ṁ tiebreak: maximum index n8 is not equal to 8 ``` Using lots of `$` like this to introduce block structure used to be the primary way to create nontrivial loop bodies and conditions in Jelly, but is now obsolete because it takes up so many bytes. It still works, though, and is nice for minimal-subsets challenges because you can do it all with just `$`, you don't need any other character. The tiebreak on the maximum index is required even if there aren't ties; otherwise, Jelly tries to compare the list [4] to the number 4 and those are not equal, so the loop would never end. [Here's an example of a program compiled from The Waterfall Model running.](https://tio.run/##y0rNyan8/9/QCATMzSzMLc3NzM3NLU3NLEHACChgZmFkAQRmCi7FCmYK2koPdzao@IKIPAUTBRWVQ/v/H25/uLMl3tDI9D8A "Jelly – Try It Online") This uses decimal rather than unary counters for space reasons (and has the halt counter in the wrong place). The arbitrary offsets applied to counter elements have a tendency to increase exponentially, so I added a footer that shows both the final value of the internal state, and the internal state normalized so that the halting counter has its value represented as 0. ## Solutions based on Addition Automaton The Waterfall Model can be implemented in Jelly in four bytes. [Addition Automaton](https://esolangs.org/wiki/Addition_Automaton) outgolfs that – [it can be implemented in three](https://codegolf.stackexchange.com/a/264429), and the important ones haven't been used so far by the other subsets. So after discovering the language, I was naturally going to have to try to fit it in here. Addition Automaton is basically a find-and-replace operation on the digits of a number, in some base *b*; a program specifies a replacement value for each digit, and the digits get replaced, repeatedly. The computational power comes from the way multiple-digit replacements are handled; they don't push the other digits away to make room, but instead carry into the more significant digits of the number (meaning that the higher digits of one replacement will end up adding onto the replacement of some more significant digit, thus the name "Addition Automaton"). Addition Automaton has something of a trade-off available between the ability to use small bases and the simplicity of the halt state. The lowest known Turing-complete value of *b* is 10, but at that point the halt state is quite complicated. If the value of *b* can be higher, the halt states become simpler: you can design a Turing machine to halts by erasing the entire tape and only then entering a halt state, and when you emulate that in Addition Automaton it corresponds to "halt when the number becomes 0", but making a Turing machine halt like that adds complexity that needs a higher *b* to implement. So a low-*b* and high-*b* implementation of the language look quite different. Maybe that means they can be implemented with different characters? ### With small *b* (*b*=10) *Character set: `CNt©®ÐƊḌḶṃṄẒE`* The primary challenge in this situatoin is trying to get the halt state to work; with *b*=10, the simplest known halt condition is "halt if you see the same number twice, but possibly with a different number of trailing zeroes". That's a little complicated, but can be handled by removing zeroes while the program runs, and using one of Jelly's "loop until you see the same thing twice" loops. [Here are the TIO! examples for this section.](https://tio.run/##y0rNyan8/9/PGQIPrYSxIPDhzuZDKw@tc0WIHFrHFW1ooGNoomMCpIyA2MwAyDXQsQCJWugY6RjEHlrpCtO8ruThrkkPd/Qc63q4s@VY1@EJD3ds@294aDGQ93DnbAWjQ4v/AwA "Jelly – Try It Online") There are actually only two steps to this solution: a) expressing the relevant values (a list of numbers, and a number) despite not having any literals available in the character set, and b) writing an Addition Automaton interpreter to run on those values. First, the construction of the data. With `N` (subtract from 0) and `C` (subtract from 1), it is possible to reach arbitrary integers by alternating between `N` and `C` (you may have seen people use `~-` and `-~` in practical languages as a method of doing small adjustments to numbers in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), or strung together into long strings in [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") – this is the same principle). `©` stores the result returned from a builtin in a register, so it's possible to place a `©` in an appropriate place in an `NCNC…NC` chain to construct two numbers (the current value and the register). It's then possible to use `ṃ`, which on numbers does base conversion, to produce an arbitrary list of integers (by expressing it as a number in a sufficiently high base), as long as the first element of the list isn't 0 (a restriction that turns out not to matter) – it can take its right-hand argument from the register, meaning that we can use any base we want here. In the construction here, I use `ṃ©` to store the resulting list in the register, and then just need to create another number to serve as the initial value for the Addition Automaton state value. This is done by using `E` ("all elements are equal") to produce an arbitrary integer (in this case, 0), and then using repeats of `NC` to increment that to the desired value. Now all that's needed is an Addition Automaton interpreter with lax loop detection: ``` ṃ®tẒḌƊṄƊÐḶ ṃ Map the digits of {the state value} ® using the list stored in the register as the map t Delete all leading and trailing Ẓ 0s if there is a non-prime, 1s if there is a prime Ḍ Convert from decimal to integer, with carry Ɗ Ɗ Specifies loop body length: five builtins Ṅ An arbitrary fifth builtin ("print with newline") ÐḶ Loop until the same value is seen twice ``` There are two weirdnesses here. One is that I'm starting to run out of ways to specify the size of a loop body; `Ʋ` didn't work for some reason, but `Ɗ` did as long as I added an extra pointless builtin for it to count. I chose `Ṅ` because it's a no-op apart from producing output, and the output is actually useful to see the program running. The other weirdness is that I want to say "remove all trailing zeroes" (base-conversion won't produce leading zeroes, so those don't matter), but don't have any easy ways to produce zero in the character set. Instead, I use `Ẓ` which will test something or other for primality (I'm not entirely sure what), but there are definitely non-primes present so zeroes will be removed (trailing zeroes on the number imply that it isn't prime!). It might also remove leading and trailing digits that map to the digit 1, but it isn't difficult to write an Addition Automaton program so that those are never produced (the Turing-completeness proof for *b*=10 does it naturally). The first line of the linked example shows how to create a list and an integer using `CN©®ṃ`. The second line shows an Addition Automaton program running in the interpreter, and halting when it reaches the end. (This one was compiled from a 4-state 2-symbol busy beaver Turing Machine – to prove Turing-completeness you would use Echo Tag instead, but the halt condition is the same.) ### With large *b* *Character set: `%34b¡ÑḅẸ⁺`* The previous section used `ṃ` to convert from number to digits, and `Ḍ` to convert from digits to number. That means that Jelly's general-purpose base conversion operators `bḅḃ` are all available, allowing for an alternative Addition Automaton implementation. This set is powerful enough that I have written [a working compiler for it](https://tio.run/##JU/BSsNAEL3vb9icsuhut7WHIhYJBWUPIvQUYqEgovQDqkVIRC2oFy@2oh4UaalowEMgW8XAbPyQzY/EScruvN33Zngzc3zQ75/kuR4LR7pujQqK4eEdmPjWhrmerFpr3ZYFoQ2hUe@Ozde3TpmJr9t63NhHLX514A2LmxCS2kAY9YmESH21twtzox6N8h0JkR4dQrjBIeIrekS2IZJ6egShHqM10V9YKDfJTuY/mPiy1TnLgrhbSxOj7gEhkMMutqzYWaD0rIXqkIg0Kf31zGVeh2CbcglRDJ75k8KGupwyr0KajTTRIxyQp0l2/sFhSuWw7dYpp9Vy4zqte@b7xqhfTP/9ZP5TFix6aIE/C6OHgcxaPkvhuU30DKJmoakLfWcWMbygnOe5yyhnrPBmVFQpF0gaDKE8Xo6cMV6A@Ac "Jelly – Try It Online") that generates [comparatively short programs](https://tio.run/##7ZfRbdxADESruQqGFRnIj@EG8mkgKcAluAvbn3Yll0YuCrQk31ByAQFOBixpteIOhzNc3eOPp6eft5v05/nj4fr2O/LQ9he8q4F/p@1uP@fAODRO@zzFN9MxLsyQsNxaVDuWjKqGBsQ6w6GxcL4my3gPmPkNdB1OAQgjKUmWDvEI4b7nzZa0lY8pZqgFHNOFZ0dSJFkuM@QIbVk70hNqpDPadYLiUI9YVZbmGjrhMax6pYb9WnscLeGs6xyTWldZsbVqcVPzI6d34dc7pcgMXOvwsiIlPtxGzWyUYXGaGuWbS6TRcpVPHzQkp6s8vDf4Bqxm0ouZfpVbyE2ghGBYhaS5CDR62oKokqrqlSkworPUlLysUCWxRQArFA1fVRAHVtOD7A7XedbFdHTyRT10QAUmIOqMzrCszCqVuM/vmiHh9pImKbCZ3Pea3aXKV3YkR/SrYC0aLTMYXU/9D9FIOHYDUwc7X6uugDXf5etBEdMPBm@t1yjbPPw26tCFwi5W0Zu6Ilgu1NlvyiSQhiwMwM9eWzxo7JYy6Acz1dNjAIVZHOC4kaJ9osfUg9GOegsVxUPiuZp3nIBLwrpOtKtbgLbZd3HgGFE2qA1wt3KA0tqM9wp0MlOJtZ3oC/t0EM0c3QaoE/MDRAg3x9zj8LXFryC6i/uddwxZLhafWzJeGwqmKyg81hVVCO9lGt2mtyIp5rfDdnnR/bgf/@MRD6ej22@3y9mPqm1c2l65vv/6erl@vH2@3m5/AQ "Jelly – Try It Online") (these both have an added `Ṅ` so that you can see the program running, but it isn't required for the halt behaviour to work correctly). To stay within the character set, *b* must be expressible with only the digits 3 and 4, but this is not a significant restriction. The first problem: creating constants. This character set has the digits `34` and the modulo operation `%`, which is enough to create arbitrary nonnegative integers. (The function on the first line of the compiler linked above converts integers to this form, using a primitive-recursive algorithm. The idea is that when taking a decimal number modulo `333…3334`, the place values of the digits, from least to most significant, are 1, 10, 100, 1000, …, -2, -20, -200, -2000, …, 4, 40, 400, 4000, …, -8, -80, -800, -8000; and this lets you effectively write a number in binary-coded-decimal, albeit with the digits in weird places.) Because the character set contains base conversion operators, it is possible to use these integers to create arbitrary lists of nonnegative integers. The next problem: how to create a lookup table for the transitions, given that both `ị` and `ṃ` have been used already? The solution: use the base conversion operators! "Convert this list of digits in base *x* to a number" is actually the same problem as "evaluate this polynomial at the given value of *x*", so both problems are solved by the same Jelly builtin, `ḅ`. Thus, the table can be implemented as a function that returns the appropriate output for each of the possible inputs, and the function in turn can almost just be a polynomial. Creating polynomials that reach particular values at particular points is a well-known problem. The followup problem: although it's easy to fit/interpolate a polynomial to any given number of input/output pairs (assuming all the inputs are distinct), quite frequently the coefficients are non-integer rational numbers, which can't be expressed in this character set (or indeed in Jelly as a whole). So instead, we need a way to do "division" that stays within the integers. The solution to that is modular arithmetic! When operating modulo a prime number, division (except for division by 0) is well-defined. Unfortunately, I couldn't prove that there are infinitely many primes that can be written with only 3 and 4. Fortunately, it doesn't matter; we only need to be able to divide by values no greater than *b* to interpolate the polynomial. For non-prime moduli, division is *sometimes* well-defined; you can do it the divisor and modulus are coprime (even if the dividend isn't); so what is needed is a number, written with only 3 and 4, that is coprime to *b* factorial (and that is sufficiently large). As it happens, for any positive integer, there are infinitely many integers of the form `444…4443` that are coprime to it (this is because for all positive integers, there are infinitely many repunits that are a multiple of it except for factors of 2 and 5; multiply a sufficiently large one of those by 4 and subtract 1, and you have a number that's coprime to it except for factors of 2 and 5; and because it ends in 3, it can't be divisible by 2 or 5 either). All that is needed now is to express this in Jelly. The character set contains no grouping or precedence-override operators, so some creativity is needed to do all the calculations on constants without Jelly mis-parsing the code. One of the major problems here is that alternating constants and binary operands, along the lines of `3%3%3%3…`, can be parsed either as `3% 3% 3% 3…` or as `3 %3 %3 %3…`, and Jelly prefers to pick the wrong option. It was possible to force an interpretation by starting with two constants in a row (`3 3% 3% 3%` is unambiguous), but with just `3` and `4` as constants you can't put two in a row because they would merge into one number. To solve this, I added `⁺` to the character set; this is an almost useless abbreviation that repeats the previous builtin, something which is actually useful here. The program has this general form (using `#` to represent a numeric literal): ``` #⁺bḅ#%#b#ḅ%#ḅ#b#ÑẸ¡ Creating the lookup polynomial: #⁺b a number in base itself (i.e. always [1,0]) ḅ# convert to base # (i.e. just the constant #) %# modulo a constant, i.e. an arbitrary integer Evaluating the polynomial: b# convert to base #, i.e. an arbitrary list ḅ convert base [see below] digits to number %# modulo a constant Do the carries: ḅ# convert base b digits to number b# convert number to base b digits Loop: ¡ a number of times equal to Ẹ 0 if all the digits are 0, else 1 Ñ call a 1-argument function ``` (`Ñ` doesn't normally call the *current* function, but as this program contains only one function, it has nowhere else to go.) The main trick here is in how the program starts up: on the first iteration it is being called as a 0-argument function, and in that case, the `ḅ` of `ḅ%` will take its argument from the constant at the very start of the program. That's ignored in most cases (by being represented as a number in base itself, which is always "10", which can be base-converted into another constant); and we set the value to *b*, a value that normally can't appear at that point in the program (which is given a list of digits in base *b*, which are all less than *b*). That makes it possible to store the initial value simply by getting the polynomial to return it when given *b* as an argument. On subsequent iterations of the program, the `ḅ` of `ḅ%` takes its argument from the function argument, i.e. the list of base *b* digits calculated on the previous iteration. The halt state here is "the internal state becomes 0". The loop around the program happens at a point where the number is represented as digits (rather than as an integer), so it does the zero test by using `Ẹ` to check whether or not all the digits are zero. The control flow here is done using a `for` loop around a recursive call (Jelly's equivalents of `if`, `while`, etc. have already been used by other subsets). [Answer] ## [Incident](https://esolangs.org/wiki/Incident), 128 or 557056 ### If "character" means byte Any set of two bytes is Turing-complete in Incident; thus it's possible to create 128 disjoint subsets, e.g. {0x00, 0x01}, {0x02, 0x03}, {0x04, 0x05}, and so on up to {0xFE, 0xFF}. The reason is that the language determines its token set at runtime: the set of tokens used by a program is the set of substrings of that program that appear exactly three times (without being contained within or overlapping other such substrings within the input program). The language gives meanings to tokens based on their relative positioning, rather than the bytes that make them up. As such, an Incident program is `tr`-invariant; you can change the character set it uses simply by consistently replacing bytes, because that doesn't change the token structure of the program. (The creation of Incident was actually inspired by this site: I wanted to find a way to avoid [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") [restricted-code](/questions/tagged/restricted-code "show questions tagged 'restricted-code'") questions getting stuck in a set of bytes that they had no way to get themselves out of. So being Turing-complete off any set of two bytes is a natural consequence of the way the language developed.) ### If "character" means Unicode character Incident doesn't attempt to parse its input into characters; it just looks at it as a single binary stream of bytes. However, that doesn't mean that you can't just simply feed a text file to the Incident interpreter. As such, it's meaningful to ask about what subsets of Unicode characters are Turing-complete if you put them into a text file, and ask the Incident interpreter to run the resulting text file as a program. Assuming that the two characters in question have no bytes in common in their encodings, you actually end up with the exact same case as when you're using two different bytes: the "identify substrings that occur three times" routine is invariant under the operation of replacing one byte with two or more, so long as each byte that appear within the encoding always uniquely comes from one of the same two original characters. As such, the goal is to find 557056 subsets (because there are 1114112 encodeable Unicode characters). This can be done fairly simply using UTF-8, choosing the two characters in each subset to always be the same length as each other: * For ASCII (0x00 to 0x7F), simply pair the characters as bytes, as in the previous case; * For two-byte characters, sort the characters into four groups {00, 01, 10, 11}, based on the least significant bit of their leading byte and least significant bit of their trailing byte: all four groups are the same size. Characters in group 00 have no bytes in common with characters in group 11, so you can form a subset by pairing an arbitrary character in each group. Likewise, characters in group 01 have no bytes in common with characters in group 10, so those form subsets in the same way. * For three-byte characters, divide into groups based on the least significant bit of the leading byte and the least significant two bits of the trailing byte: this produces 32 groups which are all the same size. The groups can be paired into 16 pairs as follows: ``` 0 00 00 with 1 11 11 0 00 01 with 1 11 10 0 00 10 with 1 11 01 0 00 11 with 1 01 10 0 01 00 with 1 10 11 0 01 01 with 1 10 10 0 01 10 with 1 00 11 0 01 11 with 1 10 00 0 10 00 with 1 01 11 0 10 01 with 1 11 00 0 10 10 with 1 01 01 0 10 11 with 1 01 00 0 11 00 with 1 10 01 0 11 01 with 1 00 10 0 11 10 with 1 00 01 0 11 11 with 1 00 00 ``` For each pair of groups, picking an arbitrary character from each group will produce a valid subset (i.e. no bytes that exist in one character in UTF-8 will exist in the other). * Four-byte characters use a similar construction, but now 1024 groups are used (taking one bit from the leading byte and three bits from each of the trailing bytes). Listing all the pairings wouldn't easily fit in the post, so here are the rules: + Label the bits of each group as `A BCD EFG HIJ`. + Consider the three values obtained by bitwise-XORing two of `BCD`, `EFG` and `HIJ`: - if none of them are 1 (001), XOR the group number with `1 001 001 001` to produce the group number it's paired with; otherwise, - if none of them are 2 (010), XOR the group number with `1 010 010 010` to produce the group number it's paired with; otherwise, - if none of them are 4 (100), XOR the group number with `1 100 100 100` to produce the group number it's paired with.It is not possible for the three resulting values to be 1, 2 and 4 (if BCD xor EFG is 1 and EFG xor HIJ is 2, then BCD xor HIJ is BCD xor EFG xor EFG xor HIJ which is 3; likewise for other assigments of positions to values). So these rules will always produce a result. Additionally, the pairing is consistent (i.e. if X is paired with Y, then Y will be paired with X); this is because the same number is being XORed into all three of the relevant segments of the trailing bytes, so it won't change the result you get when you XOR two of those segments together. Finally, it will ensure that the two members of each subset have no bytes in common because their leading bytes have different parities, and there is no way for a trailing byte of one member to equal a trailing byte of the other member (which can be seen by considering the pairwise XORs of the two equal trailing bytes, and the bytes in the corresponding position of the other member). There is some room for interpretation as to whether 557056 is actually the correct number of subsets here, depending on what exactly you consider a Unicode character to be. For example, the original version of UTF-8 allowed up to 231 different characters, meaning 230 subsets, but Unicode is nowadays capped at 1114112. Additionally, some of the characters may be considered invalid due to, e.g., being noncharacters or surrogates. However, the Incident interpreter doesn't care about any of this because it isn't trying to parse the UTF-8 anyway, and just looks at the bytes that make it up. [Answer] # Python 2, score 2 ### Arbitrary code execution with `exec` and `%` formatting (from [this answer](https://codegolf.stackexchange.com/a/110722/78410) by xsot) ``` exc="% ``` (six visible chars and newline) ### Untyped lambda calculus with `lambda` (from [this answer](https://codegolf.stackexchange.com/a/210764/78410) of mine) ``` lambd :() ``` The score for Python 3 would be very likely 1 since `()`s are necessary for more things. [Answer] # Python 3, score 2 ## Arbitrary code execution without `()` ``` clags x:[] _.time=hr+1 ``` Any function `f` of a single argument can be called without parentheses as so: ``` class F:[] F.__class_getitem__=f F[arg] ``` where `F` can obviously be any identifier constructed from the characters in the set, and the `[]` is just a funny way to `pass` because it would feel weird to put `p` in the set just for that. `exec` and `chr` only need one argument, and `+` doesn't need parentheses to begin with. [Translate here.](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3ZxcUZeaVaKirqyfnJBYXK6RaRcdyperFx4O58empJZklqbnx8bapFanJXBA1ySA1yVjUJGcUAQ3S5IKamRqtrg2Eeln5mXka6skoPEN1rfyiFI1kTU1t9Vj1tPwihWSFzDwgKigt0YAIakKcCHXpgm0QU5U8UnNy8nUUyvOLclIUlaCKAA) ## Arbitrary code execution without `=`, or the characters in `exec` ``` (~{f0r"chex}-) ``` I guess the lack of `=` isn't a big deal since this doesn't [have to milk out every last character](https://codegolf.stackexchange.com/a/110722/78410), actually; the real highlight is `exec`ing without `exec` by abusing Python's NFKC normalization of identifiers. With `+1` taken, arbitrary integers are constructed with `-~0`, and the characters are concatenated in an f-string. [Translate here.](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3wwqKMvNKNNTf7219v3cGmGzWSFNS11ZX18vKz8zTUK8Girzf2_F-7yQNoKhunbpWflGKRrKmtrqBZq16Wn6RQrJCZh4QFZSWaGgChZU01TUhpkMtWbANYomSR2pOTr6OQnl-UU6KohJUEQA) --- While it's difficult to imagine a score-3 solution, a few extra bits of note: * Spaces can be replaced with backslash-newline combinations. * There's plenty of other stuff that normalizes to `exec`, provided you can find a third way to call it. * Obviously, arbitrary code execution isn't necessary for Turing completeness; I actually meant to do the `__class_getitem__` set without `exec` to begin with by implementing ais's [Waterfall Model](https://esolangs.org/wiki/The_Waterfall_Model) but once I started using list comprehensions I realized I may as well just cheap out and do something easier to play with. * If there's any way to get a type you can set `__class_getitem__` on (or make a type you can define normal `__getitem__` for) without a `class` definition (or calling `type`), then that frees `:` up for control flow statements. How to do anything with them without newlines, parentheses, or `=` is beyond me. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), score 11 ``` 1+C† k⟇hoĖ ⌈¢ ` ‛p"øV 56S)ŀẊ ⟨⟩|₅ṫ⁽İ$J 4L{ḣτ0€∇iWfḢ… λ;←→wMt∧ Þ∞(„‟[]¬₈Q \01ḊȧḞƛ‡∷¥£Ṫẋ 2ʁṘ⅛≬ḭ'¼¦ɖ*-aNßX:^} ``` For a language to be Turing-Complete, it must be (among other things) possible to loop infinitely. There are several ways to do this in Vyxal: * `Ė` and `†` evaluate a string as Vyxal and Python respectively. * In versions 2.6-2.8.2 an ACE vulnerability exists that allows passing arbitrary Python code into any sympy builtin. All variants of this require `∆`, the math element digraph. * `(ƛ'µ⟑`, `¨2` and `¨3` can all iterate over an infinite list. However, there aren't that many ways to create infinite lists: + Various digraphs starting with `Þ` push a constant infinite list to the stack, or have the ability to create infinite lists from finite ones + The builtin `Ḟ` can create an infinite list based on a generating function, which may not be usable (see below) * `λ⁽‡≬)`, and until recently `@`, can define functions. There are a wide range of builtins which call functions in certain ways, which can be used to implement some form of lambda calculus or similar. * `¢` and `øV` perform repeated replacement in different ways, which allows implementing some form of string rewriting system. * `{` creates a while/infinite loop by itself. I'll start with the eval solutions, because they're the easiest: ### Easy eval `1+C†` allows getting any number with `1+`, converting it to a character with `C`, concatenating those into a program with `+`, and evaluating with `†`. To create a character with character code `n`, we start with `1CC`, then append `n-1` copies of `1+`, and append a `C` to turn into a character. (`CC` is a no-op, casting to char then back). We can repeat this as many times as we want and use `+` to concatenate the result into a single string before evaluating as Python with `†`. [Here's a compiler from Python to this](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLGm0PigLlgMStgKlxcQytgMUNDYHA74bijXFwraitcXCsrXFzigKArIiwiIiwiXCJwcmludCg1KVwiIl0=), and [here](https://ato.pxeger.com/run?1=m720rLIiMWfBgqWlJWm6FrdYGwydnQ21hzN0HvY-BPtSexh6c1h6asR4j8ZepWvo0cQyZ-1HDQuWFCclF0OL4wULDSAMAA)'s a program running `print(5)`. ### Harder eval `k⟇hoĖ` allows getting the Vyxal codepage with `k⟇`, accessing any character by repeatedly removing (`o`) the first item (`h`). (The cost of this is exponential but it doesn't matter). Then we can evaluate this as Vyxal code with `Ė`. (note: Unlike the above we can just evaluate single characters, as 1-byte Vyxal programs still work). Here's an example: `k⟇h` gets `λ`, the first character in the Vyxal codepage. Then, `k⟇k⟇ho` removes `λ` from the vyxal codepage, leaving `ƛ`, the second character, in the first position, which can be obtained with another `h`. This can be repeated any number of times, gaining access to any character in the Vyxal codepage. More examples of this technique can be found [here](https://codegolf.stackexchange.com/a/236209/100664). [Here](https://vyxal.pythonanywhere.com/?v=2#WyJEIiwiIiwia+Kfh+G4n+KfqOKfqSQoOlxcbyvhuYVga+KfhyVoYCQlSil0XFzElisiLCIiLCLDlyJd)'s a program that compiles a single-character program into this. To create strings we can evaluate `+` (although the program that does so has length 244 ≈ 17 trillion bytes) and concatenate two characters. ## String rewriting The builtins `¢` and `øV` can be used to repeatedly perform string replacments until nothing changes, similar to [Thue](https://esolangs.org/wiki/Thue). For example, [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJgXjEwMTFgIOKfqGAxYHxgKjBgfGBeMGDin6kg4p+oYDAqYHxgMCoqYHxgXmDin6kgw7hWIiwiIiwiIl0=)'s a binary-to-unary converter. The main difference is that, while Thue performs replacements randomly, these builtins perform all replacements in parallel. However, this turns out not to be an issue as it's possible to write Thue programs that only allow one replacement at a time. With this in mind, we need two disjoint ways to generate arbitrary strings and sequences of strings. We don't need access to all ASCII characters, as Thue is Turing-complete with only two characters. ### The easy way: string literals ``` ⌈¢ ` ``` In Vyxal, strings are delimited by backticks, for example ``abc`` represents "abc". We can then split these strings by spaces with `⌈`. This does come with the slight snag that non-ASCII characters within strings represent compressed words, but we can still write a turing machine with the symbols `disappointed` and `aquarium`. [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJgwqLijIjijIjijIjijIjCouKMiOKMiOKMiOKMiGAgYOKMiOKMiCDCosKi4oyIwqIgwqLijIjijIjCoiBg4oyIYOKMiMKiwqLCoiDijIjCosKiwqLCosKiIMKi4oyIYOKMiCDCoiIsIiIsIiJd)'s the binary-to-unary converter from before, using `disappointed` as `1` and `aquarium` as `0`. ### The hard way: more annoying string literals ``` ‛p"øV ``` Backtick-delimited strings aren't the only way of creating string literals. There's also `‛`, which groups the two characters in front of it as a string. We can then concatenate these strings with p, or pair two into a list with " and prepend other strings with p. While this does restrict us to even-length strings, that doesn't really matter - we can simply use pairs of tokens to represent single tokens. Again, [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIjYF4xMDExYCDin6hgMWB8YCowYHxgXjBg4p+pIOKfqGAwKmB8YDAqKmB8YF5g4p+pIMO4VlxuI+KAm0pcIsO4VlxuXG7igJtcInDigJtcInDigJtcIlbigJtcInDigJtcIlwicHBwcOKAm1wiVuKAm1wiw7hw4oCbXCJW4oCbXCJcInBcIuKAm1wicHDigJtcIsO44oCbXCLDuOKAm1wiVnBw4oCbXCJcIlwi4oCbXCLDuOKAm1wiVnBww7hWIiwiIiwiIl0=)'s the binary converter, this time using `"p` as 1 and `"V` as 0. ### The even more annoying way - reject string, return to number ``` 56S)ŀẊ ``` There's one more builtin that performs infinite replacement - `ŀ`. Unfortunately, this only works on strings, not on string lists, so it needs another operation to work. We use `)`, which groups all elements up to the previous newline into a function, then use `Ẋ` to repeatedly apply that function to a value until something repeats. As before, we only need two symbols - we can use the digits 5 and 6, and use `S` to stringify them (since `ŀ` only works on strings). [Here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCI2NTVTNjU2NjY2U8WANjY2NjU2UzY1NjY2NjY2NlPFgDY2NTY1NlM2NjVTxYApNjY1NjU1NjU2NjU1NjU1U+G6iiIsIiIsIiJd)'s the binary converter from before, representing 1 with 655 and 0 with 656. ### Tag systems ``` ⟨⟩|₅ṫ⁽İ$J ``` [Tag systems](https://esolangs.org/wiki/Tag_system) are turing-complete languages that use a constantly-changing tape. They have a set of rules, which decide how to map one value to several other values, and repeatedly remove the first few characters from the tape, and append the sequence corresponding to the first removed item. So, I've implemented the tag system from [ais523's answer](https://codegolf.stackexchange.com/a/264393/100664) [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLhuavin6jin6jin6l84p+oM3wy4p+pfOKfqDHin6l84p+oMXwxfDHin6l84p+oMXwxfDHin6nin6kkaSThuapKKTTEsCIsIiIsIiJd). The map is hardcoded as a 2d list of numbers - Vyxal lists are delimited by `⟨⟩` and each term is separated by `|`. The list of numbers, and the initial value, are the program; everything else is fixed. The program starts by removing the last item and pushing it separately (`ṫ`), then indexes that into the rule list. After that, it prepends the rule to what remains and removes the last item. It's quite a bit more complicated than it needs to be due to my attempts to minimise the amount of unique characters. This is then iterated until a repeated state is detected, using the builtin `İ`. The program halts by repeating states. Since the progression from one state to the next is entirely deterministic, a tag system has no meaningful behaviour once states repeat anyway. An explicit halt symbol could be added in without too much trouble. The output is all the states the program has gone through, which is definitely sufficient. Finally, all the integers can be replaced with getting the length of a list, since we can construct arbitrary lists. I'm using the builtin `₅` here (push length without popping) instead of `L` because `L` can also be used to get the length of a number. While writing this, I also realised I can use the single-element lambda builtin `⁽` here, which is otherwise not particularly useful, because I can wrap the whole output in a list. [Here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLigb3in6jhuavhuavin6jin6jin6l84p+o4p+o4p+o4p+pfOKfqOKfqXzin6jin6nin6nigoV84p+o4p+o4p+pfOKfqOKfqeKfqeKCheKfqXzin6jin6jin6jin6nin6nigoXin6l84p+o4p+o4p+o4p+p4p+p4oKFfOKfqOKfqOKfqeKfqeKChXzin6jin6jin6nin6nigoXin6l84p+o4p+o4p+o4p+p4p+p4oKFfOKfqOKfqOKfqeKfqeKChXzin6jin6jin6nin6nigoXin6l84p+o4p+o4p+o4p+p4p+p4oKFfOKfqOKfqOKfqeKfqeKChXzin6jin6jin6nin6nigoV84p+o4p+o4p+p4p+p4oKF4p+p4p+pJOKfqOKfqUrEsOG5q0okSuG5qyTin6nin6jin6jin6l84p+o4p+pfOKfqOKfqXzin6jin6l84p+o4p+p4p+p4oKFJOG5q0rhuatK4bmrSuG5q0rhuatKSsSwIiwiIiwiIl0=)'s the tag system from before without digits. ### More tag systems ``` 4L{ḣτ0€∇iWfḢ… ``` So, we don't necessarily need to explicitly hardcode the rule table. We can construct it. We can represent any number `n` as `n` 4s followed by an `L` - taking the length of the number with n 4s. If we use base conversion (`τ`) to convert this to base 4, and then split on 0s, we've created a way to define arbitrary 2d lists of integers. If we need numbers greater than 4 we can just use base-44. (note: This does come with an exponentially large program size. Representing the rule table from before is 80 megabytes) So, [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIjNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NEw0z4RcblxuNSB74bij4p+o4p+oMeKfqXzin6gyfDPin6l84p+oMeKfqXzin6gxfDF8MeKfqXzin6gxfDF8MeKfqXzin6gxfDF8MXwx4p+p4p+p4oiH4oiHaVdm4bii4oCmXG4iLCIiLCIiXQ==)'s another implementation of the same tag system, but backwards – This one pops from the start and appends to the end, and consequentially all the values are backwards. This one uses a while loop (`{`) and just prints every value. It doesn't halt, but Vyxal has live output and I can define "halting behaviour" as printing a value that's already been printed, which shows the program has entered a permanent loop, and is fully distinguishable from any nonhalting behaviour. And [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCI0NDQ0NEx74bijODA2MDMyNzIyNzcgNM+EMOKCrOKIh+KIh2lXZuG4ouKApiIsIiIsIiJd) is the same program with the rule table encoded properly. (note: the `80603272277` would be replaced with that many 4s followed by an L). There's probably quite a few characters to be saved here. ## Lambda calculus / combinatory logic ``` λ;←→wMt∧ ``` In Vyxal, we can define lambda functions with `λ...;`. Additionally, although lambdas can't have named arguments, we can set/get variables with `→a`/`←a`. Vyxal's variables are [actually local](https://vyxal.pythonanywhere.com/?v=2#WyJjIiwiIiwizrs14oaSYTsg4oCgIOKGkGEiLCIiLCIiXQ==) by default, inheriting Python's behaviour. Calling a function is a little difficult, as `†` (function call) is taken, but we can wrap our arguments in a list (`w`), map (`M`) the function over the list, and unwrap the result (`t`). `M` does take the argument followed by the function, so some tricky stack manipulation is required for this to work. So, we can implement the SKI combinators quite simply with this: ``` λ; # I λ→aλ←a;; # K λ→aλ→bλ→c ←c w ←b M ←c w ←a M t M t ;;; # S ``` The first two are fairly self-explanatory. The third, however, nedds its own explanation so I can understand it: ``` λ→a ; # a => λ→b ; # b => λ→c ; # c => ←c w t # c ←b M # b(c) ←c w t # c ←a M # a(c) M # a(c)(b(c)) ``` Note that the variables are named a, b, c for clarity – they could just be named a, aa, aaa. However, there's another issue here: Variable names can have multiple alphabetic characters, so we can't just run `←aM` as that will get interpreted as retrieving the variable aM. We need some form of no-op (or similar). Space and newline are both no-ops, but there's a better alternative: `∨`, logical or, which takes two arguments and returns the first truthy argument. The definition of "first" is a little weird due to being on a stack, but all we have to care about is that, when given two functions, it [returns the second](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLOuzU7IM67NDviiKjigKAiLCIiLCIiXQ==). With that in mind, [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLOuzsgIyBJXG7Ou+KGknTOu+KGkHQ7OyAjIEtcbs674oaSdM674oaSdHTOu+KGknR0dOKGkHR0dOKGkHR0dOKIp3fihpB0dOKGkHR04oinTeKGkHR0dOKGknR0dOKIp3fihpB04oaQdOKIp010TXQ7OzsgIyBTIiwiIiwiIl0=)'s the list of functions. With a careful ordering of these we can call any combination of S, K, and I, which is sufficient for Turing-Completeness. ## A solution based on [Picofuck](https://codegolf.stackexchange.com/a/63284/100664) ``` Þ∞(„‟[]¬₈Q ``` Picofuck is a brainfuck derivative in which the program loops indefinitely, and the only conditionals allowed are unnested if statements. The instructions translate quite easily to Vyxal: * `>` (shift pointer right) becomes `„` (rotate stack left) * `<` (shift pointer left) becomes `‟` (rotate stack right) * `*` (invert bit at pointer) becomes `¬` (logical not) * `(` (open if statement) becomes `[` * `)` (close if statement) becomes `]` I/O is not required for Turing Completeness, and the entire program runs in an infinite loop (`Þ∞(`). `Þ∞` represents the list of all positive integers, and `(` iterates over it. There are a couple of minor differences between the two approaches: * Picofuck requires if statements to not be nested, but this allows nesting if statements, which makes some constructions to bypass the following requirements easier. * While Picofuck runs on a unbounded tape, this runs on a cyclic tape. To add elements to the tape, we have `₈`, which pushes 256 (could be any integer). Since we can run `₈` in a loop to give the tape an arbitrary length, this allows us to initialise an arbitrary amount of memory. * While if statements in Picofuck preserve the condition, `[` in Vyxal pops from the stack. This can be bypassed by working with multiple copies of each value, and ensuring popped values are restored. (I could just add `:` (duplicate) to the command set but I might need that later) * In Picofuck, the program terminates when the program attempts to move the pointer to the left of the start point. While termination isn't strictly necessary, some form of distinguishable output is necessary, so I've added `Q` (quit) to halt execution. For reasons [the author hasn't written down](https://codegolf.stackexchange.com/a/63284/100664), Picofuck is Turing-Complete, but it's not hard to imagine a potential construction with the increased flexibility of this language. ## Compiling from [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag) ``` \01ḊȧḞƛ‡∷¥£Ṫẋ ``` Bitwise Cyclic Tag is a minimalist Turing-Complete tag-system-based language. It operates on a string of bits, and has two instructions: * `0` deletes the leftmost bit * `1x` (where x is 1 or 0) appends x if the leftmost bit is 1. The program is made of a sequence of bits, and loops forever. These instructions can be quite easily mapped to Vyxal, however we're running out of ways to concatenate/append. Fortunately, `Ḋȧ` does the trick - concatenating with a space in between and removing the space. We also don't have many ways left to get the first/last item of a string, but we can cast to an integer and take it modulo 2. With this, it's fairly simple to translate BCT to Vyxal: * `0` becomes `Ṫ` * `1x` becomes `:⌊∷\**x**ẋḊȧ` Additionally, we need a looping construct. There aren't many left, so I've decided to use `0‡∷∷Ḟƛ`. `‡∷∷` is a function that modulos its input by 2 twice (could be anything really), then `Ḟ` uses that combined with the 0 to generate an infinite list of values, which `ƛ` can then iterate over. Unlike some of the previous looping constructs, this doesn't maintain state between calls, so we need to use the register. `£` and `¥` respectively set and retrieve the register, a global variable initialised at 0. We can also use `£¥¥` to replace duplication (`:`). The data-string also needs to be initialised. This can be done by repeatedly prepending characters using `Ḋȧ`, and then storing this in the register. [Here](https://vyxal.pythonanywhere.com/?v=2#WyJEIiwiIiwi4oyIxpvhuKMkXFwwPVtcXOG5qnxgwqPCpcKl4oyK4oi3XFxcXM6g4bqL4biKyKdgO+KIkWAw4oCh4oi34oi34biexpvCpWBwYMKjwqVgKz/huZhmXFxcXCQr4bijYOG4isinYCviiJErXFzCoytwIiwiIiwiMTAgMTEgMTAgMTAgMTAgMTEgMCAxMSAxMCAxMCAwIDExIDEwIDEwIDExIDEwIDEwIDExIDEwIDEwIDAgMCAwIDBcblwiMTAwMTAwMTAwXCIiXQ==)'s a compiler from BCT to this subset of Vyxal. And [here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJcXDBcXDDhuIrIp1xcMeG4isinXFww4biKyKdcXDDhuIrIp1xcMeG4isinXFww4biKyKdcXDDhuIrIp1xcMeG4isinwqMw4oCh4oi34oi34biexpvCpcKjwqXCpeKMiuKIt1xcMOG6i+G4isinwqPCpcKl4oyK4oi3XFwx4bqL4biKyKfCo8KlwqXijIriiLdcXDDhuovhuIrIp8KjwqXCpeKMiuKIt1xcMOG6i+G4isinwqPCpcKl4oyK4oi3XFww4bqL4biKyKfCo8KlwqXijIriiLdcXDHhuovhuIrIp+G5qsKjwqXCpeKMiuKIt1xcMeG6i+G4isinwqPCpcKl4oyK4oi3XFww4bqL4biKyKfCo8KlwqXijIriiLdcXDDhuovhuIrIp+G5qsKjwqXCpeKMiuKIt1xcMeG6i+G4isinwqPCpcKl4oyK4oi3XFww4bqL4biKyKfCo8KlwqXijIriiLdcXDDhuovhuIrIp8KjwqXCpeKMiuKIt1xcMeG6i+G4isinwqPCpcKl4oyK4oi3XFww4bqL4biKyKfCo8KlwqXijIriiLdcXDDhuovhuIrIp8KjwqXCpeKMiuKIt1xcMeG6i+G4isinwqPCpcKl4oyK4oi3XFww4bqL4biKyKfCo8KlwqXijIriiLdcXDDhuovhuIrIp+G5quG5quG5quG5qsKjwqVcblxuIiwiIiwiIl0=)'s the example Collatz Sequence program from the esolangs page. Although this doesn't halt per se, due to how Vyxal handles printing lists it outputs the state of the data string every cycle - i.e. each time the whole program is iterated through. Since, once again, the transformation of the data string from one cycle to another is completely deterministic, we can define "halting behaviour" as entering an infinite loop. Again, it's still possible to create programs that loop forever by this definition as long as they don't end up in a loop with the same state. ## Blindfolded Arithmetic ``` 2ʁṘ⅛≬ḭ'¼¦ɖ*-aNßX:^} ``` I stole this idea from [ais523's answer](https://codegolf.stackexchange.com/a/264393/100664), and I'd recommend reading the Blindfolded Arithmetic section on that as its explanation is far better than mine. Blindfolded Arithmetic is a language with six variables, although only two are needed for Turing-Completeness. The variables are named X and Y, and start at 1 and 0 respectively. Each operation performs some arithmetic operation on two variables and stores the result into another variable. The operations are cyclically repeated until a division by 0 occurs. As ais discovered, (almost) all of the possible operations can be emulated on an array of [X, Y]. Here's the direct translations of the operations: ``` Y = X + Y: ¦ Y = X * Y: ɖ* Y = X - Y: ɖ- Y = Y - X: ɖ-2ʁ2*2Ṙ2ḭ-Ṙ* Y = X // Y: :2ʁ*a2:ḭ-2:ḭ2-*:ßX-ɖḭ Y = Y // X: :2ʁṘ*a2:ḭ-2:ḭ2-*:ßX-::Ṙḭ2ʁ*^2ʁ2Ṙ2ḭ-*- Swap Y, X: Ṙ Y = Y + Y = Y * 2: 2ʁ2:ḭ2--* Y = Y // 2: 2ʁ2:ḭ2--ḭ ``` [Here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLin6gxMjMgfCA0NeKfqSDigKYgXG7CpiDigKYgXG7Jliog4oCmIFxuyZYtIOKAplxuyZYtMsqBMioy4bmYMuG4rS3huZgqIOKAplxuOjLKgSphMjrhuK0tMjrhuK0yLSo6w59YLcmW4bitIOKAplxu4bmYIOKAplxuOjLKgeG5mCphMjrhuK0tMjrhuK0yLSo6w59YLTo64bmY4bitMsqBKl4yyoEy4bmYMuG4rS0qLSDigKZcbjLKgTI64bitMi0tKiDigKZcbjLKgTI64bitMi0t4bitIOKApiIsIiIsIiJd)'s all the operators working. Here `ɖ` is the scan operator. When given a list [x, y, z, ...] and a binary operation \*, it computes [x, x \* y, x \* y \* z ...] which is very useful for these purposes. `ḭ` is the floor division operator, and `*` and `-` do what you'd expect. Only operations assigning to Y are implemented here because we can use Ṙ, reverse, to swap X and Y. While Jelly has the quick @, which inverts the order of an element's arguments, Vyxal does not, so inverse subtraction/division is decidedly more complicated. Here's the subtraction one explained: ``` ɖ- # Y = X - Y 2ʁ # [0, 1] 2* # [0, 2] 2Ṙ2ḭ # 1 - # [0, 2] - 1 = [-1, 1] Ṙ # [1, -1] * # Multiply by that (negate second element) ``` The division one is even more complicated. Because of this I've been forced to bring in two stack-manipulation operators: `:`, duplicate, and `^`, which reverses the stack (essentially behaving like swap for our purposes) ``` :2ʁṘ*a2:ḭ-2:ḭ2-*:ßX- # Halt check (see below) :Ṙḭ # [X, Y] / [Y, X] = [X / Y, Y / X] 2ʁ* # [X / Y, Y / X] * [0, 1] = [0, Y / X] 2ʁ # [0, 1] 2Ṙ2ḭ- # [0, 1] - 1 = [-1, 0] : ^ * # [X, Y] * [-1, 0] = [-X, 0] - # [0, Y / X] - [-X, 0] = [X, Y / X] ``` Here we can't use + because that's already taken. Double negation is fine though. We can also generate the list `[1, 2]` with `2ʁ2:ḭ2--`. By multiplying or dividing by this we can halve or double Y. As explained in ais's answer, this is sufficient for Turing-Completeness. Now we need a looping construct. We can use `≬` to group the next three elements as a function, and combine this with `'...}` (filter by) to contain arbitrarily long code. By using the construct `≬ḭ'...2:-}a`, we can filter the list [1] by our code, returning a 0 by default, unless the program is halted. Then, each iteration, the `a` will only return true if the program has halted. We can then use a builtin like `N` (first natural number for which a function is true) to call this repeatedly until it halts. We also need to store data between each cycle. This can be done by pushing/popping to/from the global array, `⅛`/`¼` respectively. We also need to initialise [X, Y] as [1, 0], which can be done with `2ʁṘ⅛`. The one thing that remains is halting. We still have the element `X` available, which returns from a function. By using the modifier `ß` we can return a truthy value (and halt) if the dividend is 0. We can do this fairly simply with `:2ʁ*a2:ḭ-2:ḭ2-*:ßX*`. ``` :2ʁ* # [X, Y] * [0, 1] = [0, Y] a # Any - 0 if Y=0 2:ḭ-2:ḭ2-* # Not ^ - 1 if Y=0 :ßX # If true return 1, halting - # Else subtract 0 from whatever was on the stack, NOP ``` For Y = Y / X we multiply by [1, 0] instead of [0, 1], checking that X ≠ 0. Subtracting a variable from itself, self-multiplication and self-division are also possible, although not necessary as shown by ais. [Here](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIyyoHhuZjihZsg4oms4bitJ8K8IMKmIMKmIMKmIOG5mCDJliog4bmYIDLKgTI64bitMi0t4bitIDLKgTI64bitMi0t4bitIOKApuKFmzI6LX1hTiIsIiIsIiJd)'s an example compiled program. ## Solution 12? As far as I'm aware, I've used up every single listed looping construct. `¨@` can be used to define a named function, but that requires `|`, which would require completely rewriting one of the tag systems in a way which may not be possible. There is always the sympy ACE, but using an older version of Vyxal feels questionable. In older versions of Vyxal (I'm not sure when it was changed) it was possible to do a recursive call (`x`) within a mapping lambda / similar, allowing for an infinite loop. Again, though, downgrading Vyxal is questionable and may have some side effects on these solutions' functionality. So, I'm going to say 11 is close to optimal, and certainly as far as I'm prepared to go with this. [Answer] # Javascript, score 2 ``` (x)=> ``` With this we can implement untyped lambda calculus (idea stolen from [this answer](https://codegolf.stackexchange.com/questions/210753/minimal-maximum-byte-for-turing-completeness/210764#210764)) ``` x=xx=>xx // I xx=x=>xx=>x // K xxx=x=>xx=>xxx=>x(xxx)(x(xxx)) // S ``` Although we don't have newlines or spaces it's easy to do something like this: ``` (f=()=>f)(<definition>)(<definition>)(<definition>) ``` Where each `<definition>` is a statement. --- ``` Functioesap`${}%bdf0123456789 ``` From this we can construct ``` Function`a${unescape`...`}``` ``` Where the ... is URL-encoded text, in which each character is represented by a `%` followed by two hexadecimal digits. This allows the execution of arbitrary code. It's not necessary to use all the hex digits, as you could evaluate some other Turing-complete subset of JS, but whatever. I seriously doubt a score of 3 is possible. Either function calls or some form of loop is required. Function calls require `()` or backticks, and loops require `()`. While there are ways to use proxies to allow function calls with `[]`, those require function calls themselves. [Answer] # Lua, 2 ``` #load(').chr ``` The `load` function allows for arbitrary code execution. `('').char` allows us to construct a string using charcodes. To get a charcode, all we need to do call char with a string of a certain length. For example, `('').char(#'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')` gets us a space. ``` _G[]"\0123456789 ``` Again, allows for arbitrary code execution. Every global function, including `load`, is located within the `_G` table. We can use backslash followed by a number to get an arbitrary character (`\32` gives us a space). `_G["\108\111\97\100"]` allows us to use load, and we can keep using the same trick to execute any code we want. I don't believe it's possible to get higher than this, as most of the keywords involved in flow control use overlapping characters (`for`, `do`, `end`, `then`, `goto`, `while`, `function`, etc). I'd love to be proven wrong, though. [Answer] # JavaScript, 2 subsets Here are the subsets, one on each line: ``` x=>() Function`${re \}.al ``` Both implement lambda calculus, [which is Turing Complete](https://en.wikipedia.org/wiki/Lambda_calculus#Computability), so I'll explain both. The first subset allows you to (trivially) express any lambda calculus expression, so it is Turing Complete. The second subset is possible because of tagged template literals, type coercion and template literal nesting. Here is the identity function on itself: ``` Function`F${`return F.call\`F\${F}\``}`.call`F${Function`F${`return F`}`}` ``` [Answer] ## C, 2 [`longt=-/ ?:;`](https://tio.run/##S9ZNT07@n5uYmaehWf0/Jz8vXSHHmgtM50PpPCBtm6MLFM63zdcFiubZ5ukCBXVBQmhEji2ITLeC8EAq9UH8/JJ8hXTr/7X/AQ) [others](https://tio.run/##S9ZNT07@/z9NI1EnSSdZs7qWKzcxM09DszozTSNNw0AHCDWBorX//wMA) Body must be at least 30 characters; you entered 24. ]
[Question] [ The height of a binary tree is the distance from the root node to the node child that is farthest from the root. Below is an example: ``` 2 <-- root: Height 1 / \ 7 5 <-- Height 2 / \ \ 2 6 9 <-- Height 3 / \ / 5 11 4 <-- Height 4 ``` Height of binary tree: 4 **Definition of a Binary Tree** A tree is an object that contains a signed integer value and either two other trees or pointers to them. The structure of the binary tree struct looks something like the following: ``` typedef struct tree { struct tree * l; struct tree * r; int v; } tree; ``` The challenge: **Input** The root of a binary tree **Output** The number that represents the height of a binary tree Assuming you are given the root of a binary tree as input, write the shortest program that calculates the height of a binary tree and returns the height. The program with least amount of bytes (accounting whitespaces) wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒḊ’ ``` A monadic Link accepting a list representing the tree: `[root_value, left_tree, right_tree]`, where each of `left_tree` and `right_tree` are similar structures (empty if need be), which yields the height. **[Try it online!](https://tio.run/##y0rNyan8///opIc7uh41zPz//3@0kU60uQ6IjAUiIDbTiTaFcwwNoUwQByJsqRNtApcHSQAA "Jelly – Try It Online")** ### How? Pretty trivial in Jelly: ``` ŒḊ’ - Link: list, as described above ŒḊ - depth ’ - decremented (since leaves are `[value, [], []]`) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~35~~ 33 bytes Thanks to Arnauld for noicing an oversight and saving 4. ``` f=lambda a:a>[]and-~max(map(f,a)) ``` A recursive function accepting a list representing the tree: `[root_value, left_tree, right_tree]`, where each of `left_tree` and `right_tree` are similar structures (empty if need be), which returns the height. **[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIdEq0S46NjEvRbcuN7FCIzexQCNNJ1FT83@JbWZeQWmJhiZXQVFmXolCmkaJ5v9oI51ocx0QGQtEQGymE20K5xgaQpkgDkTYUifaBC4PkgAA "Python 2 – Try It Online")** Note that `[]` will return `False`, but in Python `False==0`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ€`}N ``` -4 bytes thanks to *@ExpiredData*. -2 bytes thanks to *@Grimy*. Input format is similar as the Jelly answer: a list representing the tree: `[root_value, left_tree, right_tree]`, where each of `left_tree` and `right_tree` are similar structures (optionally empty). I.e. `[2,[7,[2,[],[]],[6,[5,[],[]],[11,[],[]]]],[5,[],[9,[4,[],[]],[]]]]` represents the tree from the challenge description. [Try it online](https://tio.run/##yy9OTMpM/f//3JRHTWsSav3@/4820ok21wGRsUAExGY60aZwjqEhlAniQIQtdaJN4PIgCQA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1MeNa1JqPX7r6N3aOv/6GgjnWhzHRAZC0RAbKYTbQrnGBpCmSAORNhSJ9oELg@WUFAAchWiYUqBTBwqAQ). **Explanation:** ``` Δ # Loop until the (implicit) input-list no longer changes: €` # Flatten the list one level }N # After the loop: push the 0-based index of the loop we just finished # (which is output implicitly as result) ``` Note that although 05AB1E is 0-based, the changes-loop `Δ` causes the output index to be correct, because it needs an additional iteration to check it no longer changes. [Answer] ## Haskell, 33 bytes ``` h L=0 h(N l r _)=1+max(h l)(h r) ``` Using the custom tree type `data T = L | N T T Int`, which is the Haskell equivalent of the C struct given in the challenge. [Try it online!](https://tio.run/##y0gszk7NyfmfkliSqBCiYKvgo1Cj4AdkhSh45pX8z1DwsTVQ4MrQ8FPIUShSiNe0NdTOTazQyFDI0QQSRZr/cxMz84DaCooy80oUVBQyFIBKIcgHCI00kTimmjCWoaGmgpmmgjlUAKHERBNIWGqClBpp/gcA "Haskell – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` {($_,{.[*;*]}...*eqv*)-2} ``` Input is a 3-element list `(l, r, v)`. The empty tree is the empty list. [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkMlXqdaL1rLWiu2Vk9PTyu1sExLU9eo9n9xYqVCGlBWUyEtv4hLQ1OHSwNIKICwIZiDxEMSBXGQZbCoRZP@DwA "Perl 6 – Try It Online") ### Explanation ``` { } # Anonymous block , ... # Sequence constructor $_ # Start with input {.[*;*]} # Compute next element by flattening one level # Sadly *[*;*] doesn't work for some reason *eqv* # Until elements doesn't change ( )-2 # Size of sequence minus 2 ``` ### Old solution, 30 bytes ``` {+$_&&1+max map &?BLOCK,.[^2]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WlslXk3NUDs3sUIhN7FAQc3eycff2VtHLzrOKLb2f3FipUKahkq8pkJafhGXX2aODpcGiFQAE4aaQC4qH0kCzEKTxaYDU8l/AA "Perl 6 – Try It Online") [Answer] # JavaScript (ES6), ~~ 35 ~~ 33 bytes Input structure: `[[left_node], [right_node], value]` ``` f=([a,b])=>a?1+f(f(a)>f(b)?a:b):0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjOlEnKVbT1i7R3lA7TSNNI1HTLk0jSdM@0SpJ08rgf3J@XnF@TqpeTn46UDIaCGJ1FEDYCETDeaZgHpRjaAgkzIDYHC4KlzOB0pZQTUaxmpr/AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = // f is a recursive function taking ([a, b]) => // a node of the tree split into // a[] = left child, b[] = right child (the value is ignored) a ? // if a[] is defined: 1 + // increment the final result for this branch f( // and add: f(a) > f(b) ? a : b // f(a) if f(a) > f(b) or f(b) otherwise ) // : // else: 0 // stop recursion and return 0 ``` [Answer] # C, 43 bytes ``` h(T*r){r=r?1+(int)fmax(h(r->l),h(r->r)):0;} ``` Structure of binary tree is the following: ``` typedef struct tree { struct tree * l; struct tree * r; int v; } tree; ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 32 bytes ``` f=a=>/,,/.test(a)&&f(a.flat())+1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1k5fR0dfryS1uEQjUVNNLU0jUS8tJ7FEQ1NT2/B/cn5ecX5Oql5OfrpGmkY0EMTqKICwEYiG80zBPCjH0BBImAGxOVwULmcCpS2hmoxiNTX/AwA "JavaScript (Node.js) – Try It Online") ~~Using the name `flat` instead of `flatten` or `smoosh` is a great idea for code golf.~~ Using `[]` for null node in the tree, and `[left, right, value]` for nodes. `value` here is an integer. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes ``` Depth@#-2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8d8ltaAkw0FZ10jtv6Y1V0BRZl5JdFp0tZGOQrU5EIPoWhAGEWZAbIosYGgI54H5IElLIDZBVgQlamNj/wMA "Wolfram Language (Mathematica) – Try It Online") Takes input as a nested list `{v, l, r}`. [Answer] # Haskell, 28 bytes Using the following data definition: ``` data T a = (:&) a [T a] ``` The height is: ``` h(_:&x)=foldr(max.succ.h)0 x ``` [Answer] # Scheme, 72 Bytes ``` (define(f h)(if(null? h)0(+ 1(max(f(car(cdr h)))(f(car(cdr(cdr h)))))))) ``` More Readable Version: ``` (define (f h) (if (null? h) 0 (+ 1 (max (f (car (cdr h))) (f (car (cdr (cdr h)))) ) ) ) ) ``` Using lists of the form (data, left, right) to represent a tree. E.g. ``` 1 / \ 2 3 /\ 4 5 is represented as: (1 (2 (4 () ()) (5 () ())) (3 () ()) (1 (2 (4 () ()) ``` (5 () ()) (3 () ()) ) ``` [Try it Online!](https://tio.run/##K07OSM1N1QWSVf//a6SkpmXmpWqkKWRoamSmaeSV5uTYA9kGGtoKhhq5iRUaaRrJiUUaySlFQFFNTQQXLgQGQIMyiwtyEisVgEapawBFuOAiSjF5SkhcsAJDBQ1NBZAyotQZwVUTVg5TC2YZwznGCCOIMgOo3gSuWZOQif8B) [Answer] # [R](https://www.r-project.org/), 51 bytes ``` function(L){while(is.list(L<-unlist(L,F)))T=T+1;+T} ``` [Try it online!](https://tio.run/##lU89D4IwEN37Ky5xaQNoWgoGP1bj0Djh5mZEmxBIoMbB@NtrKRoOdbHJvbvevfd6bWyxtsW1OhpdV1Sx@@2iyxPV7bTUraFqFV2rvgo3jLF8nQd8GeQPO4HhCFhFETR1bRawPenzxQAniDCDA7rOXSRe8eKKYeiYDge2cJG6yDA//vB2gDoJAOcgsUACIapbEvxXROjTPNztlfLA@k6COoyo@Fvxun0KUywcefk6w2NnLP8w/lqs73A@8vz1pk8SK98LkIIqwTqMPcoOPT3GrvYJ "R – Try It Online") * **Input:** a nested list in the format : `list(ROOT_ELEMENT, LEFT_TREE, RIGHT_TREE)` * **Algorithm:** Iteratively flattens the tree by one level until it becomes a flat vector : the iterations count corresponds to the max depth. Inspired by [@KevinCruijssen solution](https://codegolf.stackexchange.com/a/189241/41725) --- Recursive alternative : # [R](https://www.r-project.org/), 64 bytes ``` `~`=function(L,d=0)'if'(is.list(L),max(L[[2]]~d+1,L[[3]]~d+1),d) ``` [Try it online!](https://tio.run/##lU9NC8IwDL33VwQ8uGKn9mPKRO8eijdPKijOj4I60Ame9tdn7JRl04uFl6TJe6/ptSjW@Xqyv1@2mUsvgRXJpM/bbt8O3K17crcssFycN4/ALhZqtcqTjhRY6rLkIuFFC6qjYByGcE3TbATTnTscM5CMEHqwJNchIvKKN1dVQ2RirNgKMUDElK8b3hhIJwKQEgwVGGDMvpYE/zclfBqK2dxaH3jZiUiHM6u/Fe9bUzigwpqXr2M6RmPzh/HXYmVHyprnrzd9MlT5WYDlViE0wrDc8zThFU8 "R – Try It Online") Redefines the function/operator `'~'` making it able to compute the max depth of a tree stored in a list structure. The list structure of a tree is in the format : `list(ROOT_ELEMENT, LEFT_TREE, RIGHT_TREE)` * -2 thanks to @Giuseppe [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` @eU=c1}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QGVVPWMxfWE&input=WzIsWzcsWzIsW10sW11dLFs2LFs1LFtdLFtdXSxbMTEsW10sW11dXV0sWzUsW10sWzksWzQsW10sW11dLFtdXV1d) ## Original, 9 bytes ``` Ω¡ÒßXÃrw ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zqmh0t9Yw3J3&input=WzIsWzcsWzIsW10sW11dLFs2LFs1LFtdLFtdXSxbMTEsW10sW11dXV0sWzUsW10sWzksWzQsW10sW11dLFtdXV1d) [Answer] # Kotlin, 45 bytes ``` val Tree.h:Int get()=1+maxOf(l?.h?:0,r?.h?:0) ``` Assuming the following class is defined ``` class Tree(var v: Int, var l: Tree? = null, var r: Tree? = null) ``` [Try it online](https://pl.kotl.in/K4PmzcvGl) [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 4 bytes **Solution:** ``` #,/\ ``` [Try it online!](https://tio.run/##y9bNS8/7/19ZRz9Gw8haw9xaQ8dI01rDDEibAmkdQ0NNTSBtaq0BJC2BAiZAGiik@f8/AA "K (ngn/k) – Try It Online") **Explanation:** I think I may have missed the point. Representing a tree as the 3-item list (parent-node;left-child;right-child), the example can be represented as ``` (2; (7; (,2); (6; (,5); (,11) ) ); (5; (); (9; (,4); () ) ) ) ``` or: `(2;(7;(,2);(6;(,5);(,11)));(5;();(9;(,4);())))`. So the solution is to iteratively flatten, and count the iterations: ``` #,/\ / the solution \ / iterate ,/ / flatten # / count ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ⊞θ⁰⊞υθFυ«≔⊕⊟ιθFΦι∧κλ⊞υ⊞Oκθ»Iθ ``` [Try it online!](https://tio.run/##VYxPC8IwDMXP66fIMYUKTvyDeBqC4Mndyw5lq65Yu63rvIifva7dBIWQ5L38Xspa2LIR2vt86GvsGCzpgcR9YNCN@7WxgAOFF0myvlc3g2dTWvmQxskK86ZFRemEJpE9Ke2kRcUgMxXeGWhKKXxfhnlppRWuseHY0TH4JrlVxuFR9A6D4z0nwFeMAPBd6EHwYqxiUts4gG9@XeBpOuvJGc@RnkP7mVr/hwJNCr946g8 "Charcoal – Try It Online") Link is to verbose version of code. Temporarily modifies the tree during processing. Explanation: ``` ⊞θ⁰ ``` Push zero to the root node. ``` ⊞υθ ``` Push the root node to the list of all nodes. ``` Fυ« ``` Perform a breadth-first search of the tree. ``` ≔⊕⊟ιθ ``` Get the depth of this node. ``` FΦι∧κλ ``` Loop over any child nodes. ``` ⊞υ⊞Oκθ ``` Tell the child node its parent's depth and push it to the list of all nodes. ``` »Iθ ``` Once all the nodes have been traversed print the depth of the last node. Since the traversal was breadth-first, this will be the height of the tree. [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=dedde6b57f&i=[2,[7,[2,[],[]],[6,[5,[],[]],[11,[],[]]]],[5,[],[9,[4,[],[]],[]]]]&a=1) Stax has neither pointers nor null values, so I represent the input like `[2,[7,[2,[],[]],[6,[5,[],[]],[11,[],[]]]],[5,[],[9,[4,[],[]],[]]]]`. Maybe that's an unfair advantage, but it was the closest I could get. Unpacked, ungolfed, and commented, the code looks like this. ``` The input starts on top of the input stack Z Tuck a zero underneath the top value in the stack. Both values end up on the main stack. D Drop the first element from array F For each remaining element (the leaves) run the rest of the program G^ Recursively call the entire program, then increment T Get maximum of the two numbers now ow the stack ``` [Run this one](https://staxlang.xyz/#c=++++%09The+input+starts+on+top+of+the+input+stack%0AZ+++%09Tuck+a+zero+underneath+the+top+value+in+the+stack.++Both+values+end+up+on+the+main+stack.%0AD+++%09Drop+the+first+element+from+array%0AF+++%09For+each+remaining+element+%28the+leaves%29+run+the+rest+of+the+program%0A++G%5E%09Recursively+call+the+entire+program,+then+increment%0A++T+%09Get+maximum+of+the+two+numbers+now+ow+the+stack&i=[2,[7,[2,[],[]],[6,[5,[],[]],[11,[],[]]]],[5,[],[9,[4,[],[]],[]]]]) [Answer] # Julia, 27 bytes ``` f(t)=t≢()&&maximum(f,t.c)+1 ``` With the following struct representing the binary tree: ``` struct Tree c::NTuple{2,Union{Tree,Tuple{}}} v::Int end ``` `c` is a tuple representing the left and right nodes and the empty tuple `()` is used to signal the absence of a node. [Answer] # [Kotlin](https://kotlinlang.org), 42 bytes ``` fun N.c():Int=maxOf(l?.c()?:0,r?.c()?:0)+1 ``` [Try it online!](https://tio.run/##ZYwxDsIwDEXn9hQeY1GhskaUipElDJzAKmpV4RqapBUIcfaQFMGCvfz/ZL/L1XMv4UyeoGFyDoyaiYE1mBoqkIm5gETsH5k1HMRHVGJoJwGzbhTqiKqB7sdWcZ1ArcvCfhOuNsvpQL0osp3TsLeWHtuTt710O3zmWVKP0WrUZxGLX05tmTy7xQfPosakxvwV3g "Kotlin – Try It Online") Where ``` data class N(val l: N? = null, val r: N? = null, val v: Int = 0) ``` [Answer] # [Jq](https://stedolan.github.io/jq/), 18 bytes Takes input as `[Value, Left, Right]` *or* any permutation of this. ``` [paths|length]|max paths # for each path as a list of indexes to follow # to get to an element or array inside the input # e.g. [0,2,1] to represent array[0][2][1] |length # its length [ ] # collect into an array |max # the maximum of this array ``` [jq play it!](https://jqplay.org/s/nXIfxv-o6C) ]
[Question] [ Your goal is to determine if a number is divisible by 3 without using conditionals. The input will be an unsigned 8 bit number from 0 to 255. Creativity encouraged! You are ONLY allowed to use * Equality/Inequality (`==`, `!=`, `>`, `<`, `>=`, `<=`) * Arithmetic (`+`, `-`, `x`) * Logical Operators (`!` not, `&&` and, `||` or) * Bitwise Operators (`~` not, `&` and, `|` or, `^` xor, `<<`, `>>`, `>>>` arithmetic and logical left and right shifts) * Constants (it would be better if you kept these small) * Variable assignment Output `0` if false, `1` if true. Standard atomic code-golf rules apply. If you have any questions please leave them in the comments. Example methods [here](https://stackoverflow.com/questions/844867/check-if-a-number-is-divisible-by-3). A token is any of the above excluding constants and variables. [Answer] # C - 2 tokens ``` int div3(int x) { return x * 0xAAAAAAAB <= x; } ``` Seems to work up to 231-1. Credits to `zalgo("nhahtdh")` for the multiplicative inverse idea. [Answer] # Python, 3 2 tokens Brute force solution, but it works. ``` 0x9249249249249249249249249249249249249249249249249249249249249249>>x&1 ``` Thanks to Howard for the 1 token reduction. [Answer] ## C - ~~5~~ 4 (?) tokens ``` int div3_m2(uint32_t n) { return n == 3 * (n * 0xAAAAAAABull >> 33); } ``` Works for **any unsigned 32-bit number**. This code makes use of multiplicative inverse modulo 232 of a divisor to convert division operation into multiplication operation. **Edit** My solution (posted 2 minutes after) has the same spirit as aditsu's solution. Credit to him for the use of `==` that improves my solution by 1 token. ### Reference * [Labor of Division - ridiculousfish.com](http://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html) * [Hacker's Delight - Magic Number](http://www.hackersdelight.org/magic.htm) * [Wikipedia - Modular multiplicative inverse](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse) [Answer] # C - 15 (?) tokens ``` int div3_m1(unsigned int n) { n = (n & 0xf) + (n >> 4); n = (n & 0x3) + (n >> 2); n = (n & 0x3) + (n >> 2); return n == 0 || n == 3; } ``` Since 4 ≡ 1 (mod 3), we have 4n ≡ 1 (mod 3). The digit summing rule is not limited to summing the digits, but also allows us to arbitrarily break the number into sequences of digits and sum all of them up while maintaining the congruency. An example in base 10, divisor = 9: 1234 ≡ 12 + 34 ≡ 1 + 2 + 3 + 4 ≡ 123 + 4 ≡ 1 (mod 9) All statements in the program makes use of this property. It can actually be simplified to a loop that runs the statement `n = (n & 0x3) + (n >> 2);` until `n < 4`, since the statement simply breaks the number in base-4 at the least significant digit and add the 2 parts up. [Answer] # Python (2 tokens?) ``` 1&66166908135609254527754848576393090201868562666080322308261476575950359794249L>>x ``` Or ``` 1&0x9249249249249249249249249249249249249249249249249249249249249249L>>x ``` Or ``` 1&0b1001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001001>>x ``` [Answer] # JavaScript - 3 tokens ``` function div3(n) { var a = n * 0.3333333333333333; return (a | 0) == a; } ``` This abuses the fact that using bitwise operators on a number truncates it to an integer in JavaScript. [Answer] # C - 4 tokens ``` int div3(int x) { return ((x * 43) >> 7) * 3 == x; } ``` Works up to 383. Previous version (bigger constants): ``` int div3(int x) { return ((x * 171) >> 9) * 3 == x; } ``` Works up to 1535 [Answer] # **Befunge 93 - 5 tokens** **Fixed - division removed.** ``` v @._1.@ \ 0 + 3 >&>3-:0\`| ^ < ``` Gets input, keeps subtracting 3 until it's smaller than 0, direct the pointer up ('|'), then adds 3. If the value is 0 then the pointer moves right ("*1.@" outputs '1') else moves left ("@.*" outputs '0'). '@' terminates the program. [Answer] ## Ruby, 6(?) tokens I'm really not sure how to count tokens. OP, can you score me? I think it's 6... `1`, `0`, `0`, `*`, `255`, `x` Note that the `*` is not integer multiplication. ``` def div3(x) ([1,0,0]*255)[x] end ``` [Answer] # Python - 25 tokens To get things started, I have a lengthy solution that is a implementation of one of the answers in the link in my first post. `n` is input. ``` a = (n>>7)-((n&64)>>6)+((n&32)>>5)-((n&16)>>4)+((n&8)>>3)-((n&4)>>2)+((n&2)>>1)-(n&1) print(a==0 or a==3) ``` `or` is equivalent to `||`. [Answer] # [Tcl](http://tcl.tk/), 83 bytes ``` proc T n {while \$n>9 {set n [expr [join [split $n ""] +]]};expr {$n in {0 3 6 9}}} ``` [Try it online!](https://tio.run/##JYxBCsIwFET3nmIo2YmgFQvV4im6S7MKAb@ENCQRC59/9hh1NcN7zBTra41ptZgRwO8HeYdFhfsIzq40pt0WE/RzpdZz9FSgArrOYG@M3H6WG2majzhjwCgi9TsmHE67/yVrCjaBzNRfBgHHV8lQdF2g55ZG6gc "Tcl – Try It Online") [Answer] ## Pascal, 1 token Pascal does not have bitwise operators. (Some *dialects* do and some *implementations* use under the hood bitwise operators for operations on the `set` data type nevertheless.) Since the `in` set membership operator is not listed among the allowed operators, another relational operator is used: ``` type wholeNumberLessThan256 = 0..255; function divisibleByThree(n: wholeNumberLessThan256): Boolean; const wholeNumbersLessThan256divisibleByThree = [ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 189, 192, 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255]; begin { In Pascal `<=` denotes the `⊆` operator with sets. } divisibleByThree := [n] <= wholeNumbersLessThan256divisibleByThree; end; ``` ## Extended Pascal, 0 token NB: A lookup table could be written in Standard Pascal (ISO standard 7185), too. ``` type wholeNumberLessThan256 = 0‥255; { The reserved word `protected` is defined by Extended Pascal. It just means the value of `n` may not be altered in the definition. } function divisibleByThree(protected n: wholeNumberLessThan256): Boolean; type tableFormat = array[type of n] of Boolean; const lookupTable = tableFormat[ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 189, 192, 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228, 231, 234, 237, 240, 243, 246, 249, 252, 255: true; otherwise false ]; begin divisibleByThree ≔ lookupTable[n]; end; ``` ]
[Question] [ Given a sorted list of unique positive floats (none of which are integers) such as: ``` [0.1, 0.2, 1.4, 2.3, 2.4, 2.5, 3.2] ``` Evenly spread out the values that fall between two consecutive integers. So in this case you would get: ``` [0.333, 0.666, 1.5, 2.25, 2.5, 2.75, 3.5] ``` (I have truncated the values 1/3 and 2/3 for ease of presentation.) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 8 bytes ``` kŢᵉR→/+j ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6Fmuzjy56uLUz6FHbJH3trCXFScnFUJkFNzWjDfUNDXSMQIShCZhpDCYhbFMQaQySjYXoAAA) Input and output are both in fractions, because Nekomata doesn't have floating point numbers. ``` kŢᵉR→/+j k Floor e.g. [1/10,2/10,14/10,23/10,24/10,25/10,32/10] -> [0,0,1,2,2,2,3] Ţ Tally; returns a list of unique elements and a list of their counts e.g. [0,0,1,2,2,2,3] -> [0,1,2,3], [2,1,3,1] ᵉR Range each count, and push the original list e.g. [2,1,3,1] -> [[1,2],[1],[1,2,3],[1]], [2,1,3,1] → Increment e.g. [2,1,3,1] -> [3,2,4,2] / Divide e.g. [[1,2],[1],[1,2,3],[1]], [3,2,4,2] -> [[1/3,2/3],[1/2],[1/4,1/2,3/4],[1/2]] + Add e.g. [0,1,2,3], [[1/3,2/3],[1/2],[1/4,1/2,3/4],[1/2]] -> [[1/3,2/3],[3/2],[9/4,5/2,11/4],[7/2]] j Join e.g. [[1/3,2/3],[3/2],[9/4,5/2,11/4],[7/2]] -> [1/3,2/3,3/2,9/4,5/2,11/4,7/2] ``` [Answer] # [R](https://www.r-project.org), ~~46~~ 45 bytes *Edit: -1 byte thanks to pajonk* ``` \(x)sequence(y<-rle(t<-x%/%1)$l)/rep(y+1,y)+t ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHq1LLUvOKCotTEFNulpSVpuhY3dWM0KjSLUwtLU_OSUzUqbXSLclI1Smx0K1T1VQ01VXI09YtSCzQqtQ11KjW1S6CaDBDmaCRrGOgZ6igY6BnpKBjqmegoGOkZgwgwy1RHwVjPSFMTom_BAggNAA) A rare use for R's obscure `sequence` function: "For each element of `x` the sequence `1...x` is created. These are concatenated and the result returned." The documentation also notes: "`sequence` mainly exists in reverence to the very early history of R." [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~18~~ 16 bytes ``` ∊⌊(⊂⊣+⍋⍤⊢÷≢⍤,)⌸⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FH16OeLo1HXU2PuhZrP@rtftS75FHXosPbH3UuAjJ1NB/17ADy/6c9apvwqLfvUVfzo941j3q3HFpv/Kht4qO@qcFBzkAyxMMz@H@agoGeIRAbKRjqmSgY6RkDMYg2VTDWMwIA "APL (Dyalog Unicode) – Try It Online") (Using Extended because TIO is out of date) `⌊(`…`)⌸⊢` on each unique floor (`⌊`) and its corresponding argument elements (`⊢`):  `⊂` enclose the  `⊣` left argument, i.e. the floor in question  `+` added to  `⍋⍤⊢` the grade (`⍋` sorting permutation: 1…length) of (`⍤`) the right argument (`⊢` the elements)  `÷` divided by  `≢⍤,` the count (`≢`) of (`⍤`) the concatenation (`,`) of the floor and the elements `∊` **e**nlist (flatten) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ïγεā¤>/+}˜ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Ppzm89tPdJ4aImdvnbt6Tn//0cb6BnqKBjoGekoGOqZ6CgY6RmDCDDLVEfBWM8oFgA) or [try it online with step-by-step debug-lines](https://tio.run/##bZC9TsMwEMd3nuKUqVVNaFJYkKBCqkAMPEHV4RofiZFrB38UMXTgPRjZGRA8QGFD6iulsRMQA4vl@/rd/f/a4lJQ0yTXqvbuFBJ2tv2YHiSXUmsTws/XLnFltK8B@R0WpBzQvUcJa5SebGjbvXVtN1gDYVGB04Awz5gkVbpqcWhQlcRBChu3zHbvX08b1qHJgasIJFoHwtEKBjGMk0PQt5HIABUHoQpDq/aCX8j25bznzMRacIqo/xfD8rGtCguDrjjKhn8xRz3ngvMI6dQFJSEqvDFBeRmMiJL7qdHmxzJ0jhSDh0q0BrRrtDdgyHoZr/1@njbNfJxmDMZpziBLjxnk6SQ88XfCYJLmiz0). **Explanation:** ``` ï # Floor all values in the (implicit) input-list γ # Group it into adjacent equal values ε # Map over each group: ā # Push a list in the range [1,length] (without popping the list) ¤ # Push its last item - the length (without popping the list) > # Increase this length by 1 / # Divide all values in the [1,length]-ranged list by this (length+1) + # Add it to each floored value of the current group }˜ # After the map: flatten the list of lists # (after which the result is output implicitly) ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 45 bytes ``` @(x)(t=fix(x))+sum(triu(u=t==t'))./(sum(u)+1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0JTo8Q2LbMCyNDULi7N1SgpyizVKLUtsbUtUdfU1NPXAAmWamobav6vULBViDbQM9RRMNAz0lEw1DPRUTDSMwYRYJapjoKxnlGsNVca0LT/AA "Octave – Try It Online") ### Explanation ``` @(x)(t=fix(x))+sum(triu(u=t==t'))./(sum(u)+1) @(x) % Anonymuous function (t=fix(x)) % t: round down x, element-wise u=t==t' % u: matrix of pairwise comparisons of t triu( ) % Upper triangular part of u sum( ) % Sum of each column of that sum(u)+1 % Sum of each column of u, plus 1 ./( ) % Divide, elemment-wise + % Add, element-wise ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ḞJ÷L‘$+Ʋƙ`F ``` [Try it online!](https://tio.run/##y0rNyan8///hjnleh7f7PGqYoaJ9bNOxmQlu////jzbQM9RRMNAz0lEw1DPRUTDSMwYRYJapjoKxnlEsAA "Jelly – Try It Online") [Answer] # [Python](https://www.python.org), 95 bytes ``` lambda x:[k+~j/~len(i)for k,[*i]in groupby(x,int)for j in range(len(i))] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc1BDoIwEAXQvaeYZau1QmvRmHgSrAYixSq0pNZENl7EDYnRO3kbKbiZmcy8n3l-mtafrOleart737yar7-HKqvzYwb3TXqZPc6LR1UYpLGyDi4knWqpDZTO3pq8RXeijR9OZ-jXLjNlgUaP5UQ5W4P2hfPWVlfQdWOdn_7f7BvXZ5FCaURjAhFlBGK6JMAoD2WYBAFOmcR4Murecs6DTpIkeBEUE3_L6GpICInHL1039h8) * -4 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/questions/263910/evenly-spread-values/263913?noredirect=1#comment577315_263913) for the famous `~-` trick [Answer] # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` x=>x.map(k=v=>(k[v|=0]=~-k[v])/~x.filter(t=>~~t==v).length+v) ``` [Try it online!](https://tio.run/##Hca7DoMgFADQvV/BCCneIraTufyIYSAWrJWCUUIcGn6dPpaT8zTZ7OM2r6kJ8W6rw3qgOuBlVrpgRkWXIb9RaCzNd5pdygFu9sluNKEqJSFmBt6GKT3OmdX@NMawR2/Bx4k6OghoOREgOWnhyomE7sd/N046kJqxvn4A "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 65 bytes ``` x=>x.map(k=v=>(k[v|=0]=-~k[v],v)).map(m=v=>v+(m[v]=~-m[v])/~k[v]) ``` [Try it online!](https://tio.run/##HYpBDoMgFET3PQVLfgq/iO3KfC9iWBCrTauI0Ya4MF4dhc3My7z52WDXdvnOfzn5dxd7ihvVGzo784EC1Xxowk7KkDwuMiIAZOmSDHfurpEOmQoe@QKxurV@Wv3Y4eg/vOeNwkIwhVqwAp@CaSxTZHoJVqI2AFU8AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` Nġıżnl⁺/+ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPU4lQzQlQTElQzQlQjElQzUlQkNubCVFMiU4MSVCQSUyRiUyQiZmb290ZXI9JmlucHV0PSU1QjAuMSUyQyUyMDAuMiUyQyUyMDEuNCUyQyUyMDIuMyUyQyUyMDIuNCUyQyUyMDIuNSUyQyUyMDMuMiU1RCZmbGFncz1T) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` Nġıżnl⁺/+ # Implicit input N # Floor each value ġ # Group consecutive ı # Map over this list: ż # Without popping, push [1..length] nl # Length of the current group ⁺ # Incremented / # Divide the range by this + # Add to the group # Implicit output, flattened ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 64 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8 bytes ``` ⌊øĖ₌ɾ›/+f ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwi4oyKw7jEluKCjMm+4oC6LytmIiwiIiwiWzAuMSwgMC4yLCAxLjQsIDIuMywgMi40LCAyLjUsIDMuMl0iXQ==) *-2 thanks to emanresu* ## Explained ``` ⌊Ġ:@₌ɾ›/+f­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌­ ⌊Ġ # ‎⁡Group the floored values by consecutive items. :@ # ‎⁢Push a copy of that where each item is the corresponding length. ₌ɾ› # ‎⁣Push a list [range 1..n for n in top], [n+1 for n in top] / # ‎⁤And divide those lists. + # ‎⁢⁡Add that to the original grouped values f # ‎⁢⁢Then flatten 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # JavaScript (ES6), 63 bytes ``` a=>a.map(p=v=>a.map(V=>v^V||n++,n=1,p!=(p=~~v)?q=1:q++)&&p+q/n) ``` [Try it online!](https://tio.run/##NcnLCsIwEEDRX4mbkpDp2KS6Eab@RTeiMNRWlJpHK1mV/np8gJvLgfvgxHM33cOrdP7a54EyU8P45CADpT9batKlXRanNTgyEDb02eua1DGSOUStVVEEHbdO5c672Y89jv4mB3mq0ICo0IIwuANhsf7mpz2IGu1ZqfwG "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(p = // initialize p to a NaN'ish value v => // for each value v in a[]: a.map(V => // for each value V in a[]: v ^ V || n++, // increment n if floor(v) = floor(V) n = 1, // starting with n = 1 p != (p = ~~v) ? // if p is not equal to floor(v) // (update p to floor(v) afterwards): q = 1 // start a new group with q = 1 : // else: q++ // increment q ) && // end of inner map() p + q / n // the final value is p + q / n ) // end of outer map() ``` [Answer] # [R](https://www.r-project.org), 47 bytes ``` \(x)ave(x,y<-x%/%1,FUN=\(z)seq(z)/sum(1,z^0))+y ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHSNAUbXYWlpSVpuhY39WM0KjQTy1I1KnQqbXQrVPVVDXXcQv1sYzSqNItTC4GkfnFproahTlWcgaamdiVUm3qaRrKGgZ6hjoKBnpGOgqGeiY6CkZ4xiACzTHUUjPWMNDUhyhcsgNAA) Not as short as the [answer using `sequence`](https://codegolf.stackexchange.com/a/263925/67312), but `ave` is pretty neat, too. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` ≦⌊θIEθ⁺ι∕⊕№…θκι⊕№θι ``` [Try it online!](https://tio.run/##ZYq9CsIwFEZ3n@KON3AN/dGpk1QEB6F76RDSYIMxMUlb8Oljm9VvOHxwjpxEkE6YlB7ic4lRPy3ejHOBwLPm0AVtZ2xFnHHz6Ak6s0TUBFe96lHh3cqg3srOasTWLXv8lUa1k8v1ixFotuG/89nkNSn1fcFLgoJXBCU/EVS83pHfmaDm1TCk42p@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array ≦ Apply to all elements ⌊ Floor θ Floored array E Map over floored elements ι Current floored element ⁺ Plus θ Floored array … Truncated to length κ Current index № Count of ι Current floored element ⊕ Incremented ∕ Divided by θ Floored array № Count of ι Current floored element ⊕ Incremented I Cast to string Implicitly print ``` [Answer] # [Perl 5](https://www.perl.org/), 61 bytes ``` sub{map{//;map{$'+$_/($c+1)}1..($c=grep$'==int,@_)}0..$_[-1]} ``` [Try it online!](https://tio.run/##lVFNb4JAEL3zKybbTQXcLl9Cq4SUexO99CaGWF2NieAWIdEQfjvdHYlpPLUc3ryd997sZJGiOoZ9cQW6S/pz89UWa9k6TqwLHY1p7ph0M/aszuNcsWRfCUlHSXIoa5bmVudyTvPli7fq@tjYnSrTAPUtEWHpco@By30GHp8w8HmgAVnIIOD@it2dQRBobxRF2h1qjx8OTp@/oj9coX1I/e2WEAWXu4jT6VDudfqvHUJNPXeYOUGMEN@G3QyrRVJcTXooJaPiIq0kpXk8tNP9qU6e6c5MtW7d2thUjw5nx8x4tm2DzuK2Qz2nYijGAE@nppZNDcX6AgFsxeZQrI9njMtK/RAgal5Tz3Cenp2VJP4tq03EphbbmZIVf5TVLZi9bfOoYoSA@FZUyQTegSw@CMyA2LY9X3yCOjEgWYnJzuh/AA "Perl 5 – Try It Online") ``` sub { map { #loop ints in $_ from 0 to highest input number as int //; #copies current $_ to $' $c=grep$'==int,@_; #$c = count of current int in $_ in input array @_ map { #loop 1 to current count in $c $' + $_ / ($c+1) #return current outer int + inner int / count+1 } 1..$c #inner loop, no loop and no return if count is 0 } 0..$_[-1] #outer loop } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 16 bytes ``` =sMQm+c@XdH1d/+Q ``` [Try it online!](https://tio.run/##K6gsyfj/37bYNzBXO9khIsXDMEVfO/D//2gDPUMdBQM9Ix0FQz0THQUjPWMQAWaZ6igY6xnFAgA "Pyth – Try It Online") ### Explanation ``` =sMQm+c@XdH1d/+QdddQ # implicitly add Q # implicitly assign Q=eval(input()), H=dict() = Q # assign Q to sMQ # floor() mapped over Q m Q # map lambda d over Q XdH1 # H[d]+=1 (or H[d]=1 if d not in H) @ d # H[d] c # divided by / d # the count of how many times d appears in +Qd # Q with d appended + d # plus d ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` <.+&;<.<@(#\%1+#)/.<. ``` [Try it online!](https://tio.run/##bY09CwIxEER7f8Vg0PNMHPNhIsQIomAlFrZeJx5i4/@v4iUKNha7DPses888ZtNjG9FAQSMOsyAOl9MxJ8rpJjHtZqKbGCnaJRNzOzrvib@skmv83KXo5uaH7rfHCz00zfCGVsFwpWDpyqrJKzja2qHpnCteCKGYvnDrv5bluro@vwE "J – Try It Online") Repetition of floor `<.` 3 times was surprisingly shorter than alternatives that DRY it out. * `<..../.<.` For each group of the floor... * `<@(#\%1+#)` Divide 1...g by (1 + g), where g is the group size. Box it `<@` because we have to box heterogeneous lists. * `<.+&;` Add the floor elementwise to that unboxed result. ]
[Question] [ CHALLENGE STATUS: **OPEN** Comment, open a PR, or otherwise yell at me if I'm missing your bot. --- Prisoner's dilemma ... with three choices. Crazy, huh? Here's our payoff matrix. Player A on the left, B on the top ``` A,B| C | N | D ---|---|---|--- C |3,3|4,1|0,5 N |1,4|2,2|3,2 D |5,0|2,3|1,1 ``` The payoff matrix is engineered so that it's best for both players to always cooperate, but you can gain (usually) by choosing Neutral or Defection. Here's some (competing) example bots. ``` # turns out if you don't actually have to implement __init__(). TIL! class AllC: def round(self, _): return "C" class AllN: def round(self, _): return "N" class AllD: def round(self, _): return "D" class RandomBot: def round(self, _): return random.choice(["C", "N", "D"]) # Actually using an identically-behaving "FastGrudger". class Grudger: def __init__(self): self.history = [] def round(self, last): if(last): self.history.append(last) if(self.history.count("D") > 0): return "D" return "C" class TitForTat: def round(self, last): if(last == "D"): return "D" return "C" ``` Your bot is a Python3 class. A new instance is created for every game, and `round()` is called each round, with your opponent's choice from last round (or None, if it's the first round) There's a 50 rep bounty for the winner in like a month. ## Specifics * Every bot plays every other bot (1v1), including itself, in [REDACTED] rounds. * Standard loopholes disallowed. * No messing with anything outside your class or other underhanded shenanigains. * You may submit up to five bots. * Yes, you can implement handshake. * Any response other than `C`, `N`, or `D` will be silently taken as `N`. * Each bot's points from every game they play will be totaled up and compared. ## Controller [Check!](https://gitlab.com/Blacksilver/prisonerstrilemma) ## Other Languages I'll throw together an API if anyone needs it. ## Scores: 2018-11-27 ``` 27 bots, 729 games. name | avg. score/round ----------------|------------------- PatternFinder | 3.152 DirichletDice2 | 3.019 EvaluaterBot | 2.971 Ensemble | 2.800 DirichletDice | 2.763 Shifting | 2.737 FastGrudger | 2.632 Nash2 | 2.574 HistoricAverage | 2.552 LastOptimalBot | 2.532 Number6 | 2.531 HandshakeBot | 2.458 OldTitForTat | 2.411 WeightedAverage | 2.403 TitForTat | 2.328 AllD | 2.272 Tetragram | 2.256 Nash | 2.193 Jade | 2.186 Useless | 2.140 RandomBot | 2.018 CopyCat | 1.902 TatForTit | 1.891 NeverCOOP | 1.710 AllC | 1.565 AllN | 1.446 Kevin | 1.322 ``` [Answer] # EvaluaterBot ``` class EvaluaterBot: def __init__(self): self.c2i = {"C":0, "N":1, "D":2} self.i2c = {0:"C", 1:"N", 2:"D"} self.history = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] self.last = [None, None] def round(self, last): if self.last[0] == None: ret = 2 else: # Input the latest enemy action (the reaction to my action 2 rounds ago) # into the history self.history[self.last[0]][self.c2i[last]] += 1 # The enemy will react to the last action I did prediction,_ = max(enumerate(self.history[self.last[1]]), key=lambda l:l[1]) ret = (prediction - 1) % 3 self.last = [self.last[1], ret] return self.i2c[ret] ``` Wins against all previously submitted bots except (maybe) the random bot (but it could have an advantage, because it picks D in a draw and D should optimal) and plays a constant draw against themself. [Answer] # TatForTit ``` class TatForTit: def round(self, last): if(last == "C"): return "N" return "D" ``` This bot will alternate picking D N D N while TitForTat alternates C D C D, for an average net gain of 3 points per round if I have read the payout matrix correctly. I think this might be optimal against TitForTat. Obviously it could be improved to detect a non-TFT opponent and adopt other strategies, but I was just aiming for the original bounty. [Answer] # NashEquilibrium This bot has taken a game theory class in college but was lazy and didn't go to the class where they covered iterated games. So he only plays single game mixed nash equilibrium. Turns out 1/5 2/5 2/5 is the mixed NE for the payoffs. ``` class NashEquilibrium: def round(self, _): a = random.random() if a <= 0.2: return "C" elif a <= 0.6: return "N" else: return "D" ``` **Constant Abusing Nash Equilibrium** This bot picked up a lesson or two from his lazy brother. His lazy brother's problem was that he didn't take advantage of fixed strategies. This version checks if the opponent is a constant player or titfortat and plays accordingly, else it plays the regular nash equilibrium. It's only downside is that it averages 2.2 points per turn playing against itself. ``` class NashEquilibrium2: def __init__(self): self.opphistory = [None, None, None] self.titfortatcounter = 0 self.titfortatflag = 0 self.mylast = "C" self.constantflag = 0 self.myret = "C" def round(self, last): self.opphistory.pop(0) self.opphistory.append(last) # check if its a constant bot, if so exploit if self.opphistory.count(self.opphistory[0]) == 3: self.constantflag = 1 if last == "C": self.myret = "D" elif last == "N": self.myret = "C" elif last == "D": self.myret = "N" # check if its a titfortat bot, if so exploit # give it 2 chances to see if its titfortat as it might happen randomly if self.mylast == "D" and last == "D": self.titfortatcounter = self.titfortatcounter + 1 if self.mylast == "D" and last!= "D": self.titfortatcounter = 0 if self.titfortatcounter >= 3: self.titfortatflag = 1 if self.titfortatflag == 1: if last == "C": self.myret = "D" elif last == "D": self.myret = "N" elif last == "N": # tit for tat doesn't return N, we made a mistake somewhere self.titfortatflag = 0 self.titfortatcounter = 0 # else play the single game nash equilibrium if self.constantflag == 0 and self.titfortatflag == 0: a = random.random() if a <= 0.2: self.myret = "C" elif a <= 0.6: self.myret = "N" else: self.myret = "D" self.mylast = self.myret return self.myret ``` [Answer] # PatternFinder ``` class PatternFinder: def __init__(self): import collections self.size = 10 self.moves = [None] self.other = [] self.patterns = collections.defaultdict(list) self.counter_moves = {"C":"D", "N":"C", "D":"N"} self.initial_move = "D" self.pattern_length_exponent = 1 self.pattern_age_exponent = 1 self.debug = False def round(self, last): self.other.append(last) best_pattern_match = None best_pattern_score = None best_pattern_response = None self.debug and print("match so far:",tuple(zip(self.moves,self.other))) for turn in range(max(0,len(self.moves)-self.size),len(self.moves)): # record patterns ending with the move that just happened pattern_full = tuple(zip(self.moves[turn:],self.other[turn:])) if len(pattern_full) > 1: pattern_trunc = pattern_full[:-1] pattern_trunc_result = pattern_full[-1][1] self.patterns[pattern_trunc].append([pattern_trunc_result,len(self.moves)-1]) if pattern_full in self.patterns: # we've seen this pattern at least once before self.debug and print("I've seen",pattern_full,"before:",self.patterns[pattern_full]) for [response,turn_num] in self.patterns[pattern_full]: score = len(pattern_full) ** self.pattern_length_exponent / (len(self.moves) - turn_num) ** self.pattern_age_exponent if best_pattern_score == None or score > best_pattern_score: best_pattern_match = pattern_full best_pattern_score = score best_pattern_response = response # this could be much smarter about aggregating previous responses if best_pattern_response: move = self.counter_moves[best_pattern_response] else: # fall back to playing nice move = "C" self.moves.append(move) self.debug and print("I choose",move) return move ``` This bot looks for previous occurrences of the recent game state to see how the opponent responded to those occurrences, with a preference for longer pattern matches and more recent matches, then plays the move that will "beat" the opponent's predicted move. There's a lot of room for it to be smarter with all the data it keeps track of, but I ran out of time to work on it. [Answer] # Jade ``` class Jade: def __init__(self): self.dRate = 0.001 self.nRate = 0.003 def round(self, last): if last == 'D': self.dRate *= 1.1 self.nRate *= 1.2 elif last == 'N': self.dRate *= 1.03 self.nRate *= 1.05 self.dRate = min(self.dRate, 1) self.nRate = min(self.nRate, 1) x = random.random() if x > (1 - self.dRate): return 'D' elif x > (1 - self.nRate): return 'N' else: return 'C' ``` Starts out optimistic, but gets progressively more bitter as the opponent refuses to cooperate. Lots of magic constants that could probably be tweaked, but this probably isn't going to do well enough to justify the time. [Answer] # Ensemble This runs an ensemble of related models. The individual models consider different amounts of history, and have the option of either always choosing the move that will optimize the expected payout difference, or will randomly select a move in proportion to expected payout difference. Each member of the ensemble then votes on their preferred move. They get a number of votes equal to how much more they've won than the opponent (which means that terrible models will get negative votes). Whichever move wins the vote is then selected. (They should probably split their votes among the moves in proportion to how much they favor each, but I don't care enough to do that right now.) It beats everything posted so far except EvaluaterBot and PatternFinder. (One-on-one, it beats EvaluaterBot and loses to PatternFinder). ``` from collections import defaultdict import random class Number6: class Choices: def __init__(self, C = 0, N = 0, D = 0): self.C = C self.N = N self.D = D def __init__(self, strategy = "maxExpected", markov_order = 3): self.MARKOV_ORDER = markov_order; self.my_choices = "" self.opponent = defaultdict(lambda: self.Choices()) self.choice = None # previous choice self.payoff = { "C": { "C": 3-3, "N": 4-1, "D": 0-5 }, "N": { "C": 1-4, "N": 2-2, "D": 3-2 }, "D": { "C": 5-0, "N": 2-3, "D": 1-1 }, } self.total_payoff = 0 # if random, will choose in proportion to payoff. # otherwise, will always choose argmax self.strategy = strategy # maxExpected: maximize expected relative payoff # random: like maxExpected, but it chooses in proportion to E[payoff] # argmax: always choose the option that is optimal for expected opponent choice def update_opponent_model(self, last): for i in range(0, self.MARKOV_ORDER): hist = self.my_choices[i:] self.opponent[hist].C += ("C" == last) self.opponent[hist].N += ("N" == last) self.opponent[hist].D += ("D" == last) def normalize(self, counts): sum = float(counts.C + counts.N + counts.D) if 0 == sum: return self.Choices(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0) return self.Choices( counts.C / sum, counts.N / sum, counts.D / sum) def get_distribution(self): for i in range(0, self.MARKOV_ORDER): hist = self.my_choices[i:] #print "check hist = " + hist if hist in self.opponent: return self.normalize(self.opponent[hist]) return self.Choices(1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0) def choose(self, dist): payoff = self.Choices() # We're interested in *beating the opponent*, not # maximizing our score, so we optimize the difference payoff.C = (3-3) * dist.C + (4-1) * dist.N + (0-5) * dist.D payoff.N = (1-4) * dist.C + (2-2) * dist.N + (3-2) * dist.D payoff.D = (5-0) * dist.C + (2-3) * dist.N + (1-1) * dist.D # D has slightly better payoff on uniform opponent, # so we select it on ties if self.strategy == "maxExpected": if payoff.C > payoff.N: return "C" if payoff.C > payoff.D else "D" return "N" if payoff.N > payoff.D else "D" elif self.strategy == "randomize": payoff = self.normalize(payoff) r = random.uniform(0.0, 1.0) if (r < payoff.C): return "C" return "N" if (r < payoff.N) else "D" elif self.strategy == "argMax": if dist.C > dist.N: return "D" if dist.C > dist.D else "N" return "C" if dist.N > dist.D else "N" assert(0) #, "I am not a number! I am a free man!") def update_history(self): self.my_choices += self.choice if len(self.my_choices) > self.MARKOV_ORDER: assert(len(self.my_choices) == self.MARKOV_ORDER + 1) self.my_choices = self.my_choices[1:] def round(self, last): if last: self.update_opponent_model(last) dist = self.get_distribution() self.choice = self.choose(dist) self.update_history() return self.choice class Ensemble: def __init__(self): self.models = [] self.votes = [] self.prev_choice = [] for order in range(0, 6): self.models.append(Number6("maxExpected", order)) self.models.append(Number6("randomize", order)) #self.models.append(Number6("argMax", order)) for i in range(0, len(self.models)): self.votes.append(0) self.prev_choice.append("D") self.payoff = { "C": { "C": 3-3, "N": 4-1, "D": 0-5 }, "N": { "C": 1-4, "N": 2-2, "D": 3-2 }, "D": { "C": 5-0, "N": 2-3, "D": 1-1 }, } def round(self, last): if last: for i in range(0, len(self.models)): self.votes[i] += self.payoff[self.prev_choice[i]][last] # vote. Sufficiently terrible models get negative votes C = 0 N = 0 D = 0 for i in range(0, len(self.models)): choice = self.models[i].round(last) if "C" == choice: C += self.votes[i] if "N" == choice: N += self.votes[i] if "D" == choice: D += self.votes[i] self.prev_choice[i] = choice if C > D and C > N: return "C" elif N > D: return "N" else: return "D" ``` # Test Framework In case anyone else finds it useful, here's a test framework for looking at individual matchups. Python2. Just put all the opponents you're interested in in opponents.py, and change the references to Ensemble to your own. ``` import sys, inspect import opponents from ensemble import Ensemble def count_payoff(label, them): if None == them: return me = choices[label] payoff = { "C": { "C": 3-3, "N": 4-1, "D": 0-5 }, "N": { "C": 1-4, "N": 2-2, "D": 3-2 }, "D": { "C": 5-0, "N": 2-3, "D": 1-1 }, } if label not in total_payoff: total_payoff[label] = 0 total_payoff[label] += payoff[me][them] def update_hist(label, choice): choices[label] = choice opponents = [ x[1] for x in inspect.getmembers(sys.modules['opponents'], inspect.isclass)] for k in opponents: total_payoff = {} for j in range(0, 100): A = Ensemble() B = k() choices = {} aChoice = None bChoice = None for i in range(0, 100): count_payoff(A.__class__.__name__, bChoice) a = A.round(bChoice) update_hist(A.__class__.__name__, a) count_payoff(B.__class__.__name__, aChoice) b = B.round(aChoice) update_hist(B.__class__.__name__, b) aChoice = a bChoice = b print total_payoff ``` [Answer] ## OldTitForTat Old school player is too lazy to update for the new rules. ``` class OldTitForTat: def round(self, last): if(last == None) return "C" if(last == "C"): return "C" return "D" ``` [Answer] # NeverCOOP ``` class NeverCOOP: def round(self, last): try: if last in "ND": return "D" else: return "N" except: return "N" ``` If the opposing bot defects or is neutral, choose defect. Otherwise if this is the first turn or the opposing bot cooperates, choose neutral. I'm not sure how good this will work... [Answer] # LastOptimalBot ``` class LastOptimalBot: def round(self, last): return "N" if last == "D" else ("D" if last == "C" else "C") ``` Assumes that the opposing bot will always play the same move again, and chooses the one that has the best payoff against it. Averages: ``` Me Opp 2.6 2 vs TitForTat 5 0 vs AllC 4 1 vs AllN 3 2 vs AllD 3.5 3.5 vs Random 3 2 vs Grudger 2 2 vs LastOptimalBot 1 3.5 vs TatForTit 4 1 vs NeverCOOP 1 4 vs EvaluaterBot 2.28 2.24 vs NashEquilibrium 2.91 average overall ``` [Answer] # CopyCat ``` class CopyCat: def round(self, last): if last: return last return "C" ``` Copies the opponent's last move. I don't expect this to do well, but no one had implemented this classic yet. [Answer] # Handshake ``` class HandshakeBot: def __init__(self): self.handshake_length = 4 self.handshake = ["N","N","C","D"] while len(self.handshake) < self.handshake_length: self.handshake *= 2 self.handshake = self.handshake[:self.handshake_length] self.opp_hand = [] self.friendly = None def round(self, last): if last: if self.friendly == None: # still trying to handshake self.opp_hand.append(last) if self.opp_hand[-1] != self.handshake[len(self.opp_hand)-1]: self.friendly = False return "D" if len(self.opp_hand) == len(self.handshake): self.friendly = True return "C" return self.handshake[len(self.opp_hand)] elif self.friendly == True: # successful handshake and continued cooperation if last == "C": return "C" self.friendly = False return "D" else: # failed handshake or abandoned cooperation return "N" if last == "D" else ("D" if last == "C" else "C") return self.handshake[0] ``` Recognizes when it's playing against itself, then cooperates. Otherwise mimics LastOptimalBot which seems like the best one-line strategy. Performs worse than LastOptimalBot, by an amount inversely proportional to the number of rounds. Obviously would do better if there were more copies of it in the field \*cough\*\*wink\*. [Answer] # Improved Dirichlet Dice ``` import random class DirichletDice2: def __init__(self): self.alpha = dict( C = {'C' : 1, 'N' : 1, 'D' : 1}, N = {'C' : 1, 'N' : 1, 'D' : 1}, D = {'C' : 1, 'N' : 1, 'D' : 1} ) self.myLast = [None, None] self.payoff = dict( C = { "C": 0, "N": 3, "D": -5 }, N = { "C": -3, "N": 0, "D": 1 }, D = { "C": 5, "N": -1, "D": 0 } ) def DirichletDraw(self, key): alpha = self.alpha[key].values() mu = [random.gammavariate(a,1) for a in alpha] mu = [m / sum(mu) for m in mu] return mu def ExpectedPayoff(self, probs): expectedPayoff = {} for val in ['C','N','D']: payoff = sum([p * v for p,v in zip(probs, self.payoff[val].values())]) expectedPayoff[val] = payoff return expectedPayoff def round(self, last): if last is None: self.myLast[0] = 'D' return 'D' #update dice corresponding to opponent's last response to my #outcome two turns ago if self.myLast[1] is not None: self.alpha[self.myLast[1]][last] += 1 #draw probs for my opponent's roll from Dirichlet distribution and then return the optimal response mu = self.DirichletDraw(self.myLast[0]) expectedPayoff = self.ExpectedPayoff(mu) res = max(expectedPayoff, key=expectedPayoff.get) #update myLast self.myLast[1] = self.myLast[0] self.myLast[0] = res return res ``` This is an improved version of Dirichlet Dice. Instead of taking the expected multinomial distribution from the Dirichlet distribution, it draws a Multinomial distribution randomly from the Dirichlet distribution. Then, instead of drawing from the Multinomial and giving the optimal response to that, it gives the optimal expected response to the given Multinomial using the points. So the randomness has essentially been shifted from the Multinomial draw to the Dirichlet draw. Also, the priors are more flat now, to encourage exploration. It's "improved" because it now accounts for the points system by giving the best expected value against the probabilities, while maintaining its randomness by drawing the probabilities themselves. Before, I tried simply doing the best expected payoff from the expected probabilities, but that did badly because it just got stuck, and didn't explore enough to update its dice. Also it was more predictable and exploitable. --- Original submission: # Dirichlet Dice ``` import random class DirichletDice: def __init__(self): self.alpha = dict( C = {'C' : 2, 'N' : 3, 'D' : 1}, N = {'C' : 1, 'N' : 2, 'D' : 3}, D = {'C' : 3, 'N' : 1, 'D' : 2} ) self.Response = {'C' : 'D', 'N' : 'C', 'D' : 'N'} self.myLast = [None, None] #expected value of the dirichlet distribution given by Alpha def MultinomialDraw(self, key): alpha = list(self.alpha[key].values()) probs = [x / sum(alpha) for x in alpha] outcome = random.choices(['C','N','D'], weights=probs)[0] return outcome def round(self, last): if last is None: self.myLast[0] = 'D' return 'D' #update dice corresponding to opponent's last response to my #outcome two turns ago if self.myLast[1] is not None: self.alpha[self.myLast[1]][last] += 1 #predict opponent's move based on my last move predict = self.MultinomialDraw(self.myLast[0]) res = self.Response[predict] #update myLast self.myLast[1] = self.myLast[0] self.myLast[0] = res return res ``` Basically I'm assuming that the opponent's response to my last output is a multinomial variable (weighted dice), one for each of my outputs, so there's a dice for "C", one for "N", and one for "D". So if my last roll was, for example, a "N" then I roll the "N-dice" to guess what their response would be to my "N". I begin with a Dirichlet prior that assumes that my opponent is somewhat "smart" (more likely to play the one with the best payoff against my last roll, least likely to play the one with the worst payoff). I generate the "expected" Multinomial distribution from the appropriate Dirichlet prior (this is the expected value of the probability distribution over their dice weights). I roll the weighted dice of my last output, and respond with the one with the best payoff against that dice outcome. Starting in the third round, I do a Bayesian update of the appropriate Dirichlet prior of my opponent's last response to the thing I played two rounds ago. I'm trying to iteratively learn their dice weightings. I could have also simply picked the response with the best "expected" outcome once generating the dice, instead of simply rolling the dice and responding to the outcome. However, I wanted to keep the randomness in, so that my bot is less vulnerable to the ones that try to predict a pattern. [Answer] # Kevin ``` class Kevin: def round(self, last): return {"C":"N","N":"D","D":"C",None:"N"} [last] ``` Picks the worst choice. The worst bot made. # Useless ``` import random class Useless: def __init__(self): self.lastLast = None def round(self, last): tempLastLast = self.lastLast self.lastLast = last if(last == "D" and tempLastLast == "N"): return "C" if(last == "D" and tempLastLast == "C"): return "N" if(last == "N" and tempLastLast == "D"): return "C" if(last == "N" and tempLastLast == "C"): return "D" if(last == "C" and tempLastLast == "D"): return "N" if(last == "C" and tempLastLast == "N"): return "D" return random.choice("CND") ``` It looks at the last two moves done by the opponent and picks the most not done else it picks something random. There is probably a better way of doing this. [Answer] # Historic Average ``` class HistoricAverage: PAYOFFS = { "C":{"C":3,"N":1,"D":5}, "N":{"C":4,"N":2,"D":2}, "D":{"C":0,"N":3,"D":1}} def __init__(self): self.payoffsum = {"C":0, "N":0, "D":0} def round(this, last): if(last != None): for x in this.payoffsum: this.payoffsum[x] += HistoricAverage.PAYOFFS[last][x] return max(this.payoffsum, key=this.payoffsum.get) ``` Looks at history and finds the action that would have been best on average. Starts cooperative. [Answer] # Weighted Average ``` class WeightedAverageBot: def __init__(self): self.C_bias = 1/4 self.N = self.C_bias self.D = self.C_bias self.prev_weight = 1/2 def round(self, last): if last: if last == "C" or last == "N": self.D *= self.prev_weight if last == "C" or last == "D": self.N *= self.prev_weight if last == "N": self.N = 1 - ((1 - self.N) * self.prev_weight) if last == "D": self.D = 1 - ((1 - self.D) * self.prev_weight) if self.N <= self.C_bias and self.D <= self.C_bias: return "D" if self.N > self.D: return "C" return "N" ``` The opponent's behavior is modeled as a right triangle with corners for C N D at 0,0 0,1 1,0 respectively. Each opponent move shifts the point within that triangle toward that corner, and we play to beat the move indicated by the point (with C being given an adjustably small slice of the triangle). In theory I wanted this to have a longer memory with more weight to previous moves, but in practice the current meta favors bots that change quickly, so this devolves into an approximation of LastOptimalBot against most enemies. Posting for posterity; maybe someone will be inspired. [Answer] # Tetragram ``` import itertools class Tetragram: def __init__(self): self.history = {x: ['C'] for x in itertools.product('CND', repeat=4)} self.theirs = [] self.previous = None def round(self, last): if self.previous is not None and len(self.previous) == 4: self.history[self.previous].append(last) if last is not None: self.theirs = (self.theirs + [last])[-3:] if self.previous is not None and len(self.previous) == 4: expected = random.choice(self.history[self.previous]) if expected == 'C': choice = 'C' elif expected == 'N': choice = 'C' else: choice = 'N' else: choice = 'C' self.previous = tuple(self.theirs + [choice]) return choice ``` Try to find a pattern in the opponent's moves, assuming they're also watching our last move. [Answer] # ShiftingOptimalBot ``` class ShiftingOptimalBot: def __init__(self): # wins, draws, losses self.history = [0,0,0] self.lastMove = None self.state = 0 def round(self, last): if last == None: self.lastMove = "C" return self.lastMove if last == self.lastMove: self.history[1] += 1 elif (last == "C" and self.lastMove == "D") or (last == "D" and self.lastMove == "N") or (last == "N" and self.lastMove == "C"): self.history[0] += 1 else: self.history[2] += 1 if self.history[0] + 1 < self.history[2] or self.history[2] > 5: self.state = (self.state + 1) % 3 self.history = [0,0,0] if self.history[1] > self.history[0] + self.history[2] + 2: self.state = (self.state + 2) % 3 self.history = [0,0,0] if self.state == 0: self.lastMove = "N" if last == "D" else ("D" if last == "C" else "C") elif self.state == 1: self.lastMove = last else: self.lastMove = "C" if last == "D" else ("N" if last == "C" else "D") return self.lastMove ``` This bot uses LastOptimalBot's algorithm as long as it's winning. If the other bot starts predicting it, however, it will start playing whichever move its opponent played last (which is the move that beats the move that would beat LastOptimalBot). It cycles through simple transpositions of those algorithms as long as it continues to lose (or when it gets bored by drawing a lot). Honestly, I'm surprised that LastOptimalBot is sitting in 5th as I post this. I'm fairly certain this will do better, assuming that I wrote this python correctly. [Answer] # HandshakePatternMatch ``` from .patternfinder import PatternFinder import collections class HandshakePatternMatch: def __init__(self): self.moves = [None] self.other = [] self.handshake = [None,"N","C","C","D","N"] self.friendly = None self.pattern = PatternFinder() def round(self, last): self.other.append(last) if last: if len(self.other) < len(self.handshake): # still trying to handshake if self.friendly == False or self.other[-1] != self.handshake[-1]: self.friendly = False else: self.friendly = True move = self.handshake[len(self.other)] self.pattern.round(last) elif self.friendly == True: # successful handshake and continued cooperation move = self.pattern.round(last) if last == "C": move = "C" elif last == self.handshake[-1] and self.moves[-1] == self.handshake[-1]: move = "C" else: self.friendly = False else: # failed handshake or abandoned cooperation move = self.pattern.round(last) else: move = self.handshake[1] self.pattern.round(last) self.moves.append(move) return move ``` Why pattern match yourself? Handshake and cooperate away. [Answer] # Hardcoded ``` class Hardcoded: sequence = "DNCNNDDCNDDDCCDNNNNDDCNNDDCDCNNNDNDDCNNDDNDDCDNCCNNDNNDDCNNDDCDCNNNDNCDNDNDDNCNDDCDNNDCNNDDCDCNNDNNDDCDNDDCCNNNDNNDDCNNDDNDCDNCNDDCDNNDDCCNDNNDDCNNNDCDNDDCNNNNDNDDCDNCDCNNDNNDDCDNDDCCNNNDNDDCNNNDNDCDCDNNDCNNDNDDCDNCNNDDCNDNNDDCDNNDCDNDNCDDCNNNDNDNCNDDCDNDDCCNNNNDNDDCNNDDCNNDDCDCNNDNNDDCDNDDCCNDNNDDCNNNDCDNNDNDDCCNNNDNDDNCDCDNNDCNNDNDDCNNDDCDNCNNDDCDNNDCDNDNCDDCNDNNDDCNNNDDCDNCNNDNNDDCNNDDNNDCDNCNDDCNNDCDNNDDCNNDDNCDCNNDNDNDDCDNCDCNNNDNDDCDCNNDNNDDCDNDDCCNNNDNNDDCNDNDNCDDCDCNNNNDNDDCDNCNDDCDNNDDCNNNDNDDCDNCNNDCNNDNDDNCDCDNNNDDCNNDDCNNDDNNDCDNCNDDCNNDDNDCDNNDNDDCCNCDNNDCNNDDNDDCNCDNNDCDNNNDDCNNDDCDCDNNDDCNDNCNNDNNDNDNDDCDNCDCNNNDNDDCDNCNNDDCDNNDCNNDDCNNDDCDCDNNDDCNDNCNNNDDCDNNDCDNDNCNNDNDDNNDNDCDDCCNNNDDCNDNDNCDDCDCNNNDNNDDCNDCDNDDCNNNNDNDDCCNDNNDDCDCNNNDNDDNDDCDNCCNNDNNDDCNNDDCDCNNDNNDDCNNDDNCNDDNNDCDNCNDDCNNDDNDCDNNDNDDCCNCDNNDCNNDNDDCNNDDNCDCDNNDCNNDNDDCDCDNNNNDDCNNDDNDCCNNDDNDDCNCDNNDCNNDDNDDCDNCNDDCNNNNDCDNNDDCNDNDDCDNCNNDCDNNDCNNDNDDNCDCNNDNDDCDNDDCCNNNNDNDDCNNDDCDCNNDNNDDCDCDNNDDC" def __init__(self): self.round_num = -1 def round(self,_): self.round_num += 1 return Hardcoded.sequence[self.round_num % 1000] ``` Just plays a hardcoded sequence of moves optimized to beat some of the top deterministic bots. ]
[Question] [ Your task is to decompose a number using the format below. This is similar to base conversion, except that instead of listing the `digits` in the base, you list the `values`, such that the list adds up to the input. If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list. # Specs * Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list. * Output list can be in any order. * `0` can be excluded or included. * Leading `0`s are allowed. * Built-ins are **allowed**. # Testcases ``` number base converted list input1 input2 output 123456 10 [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000] 11 2 [8,2,1] or [0,0,0,0,8,0,2,1] 727 20 [400,320,7] 101 10 [100,1] or [100,0,1] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution in bytes wins. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` lr0⁹*×b ``` [Try it online!](http://jelly.tryitonline.net/#code=bHIw4oG5KsOXYg&input=&args=MTIzNDU2+MTA) or [verify all test cases](http://jelly.tryitonline.net/#code=bHIw4oG5KsOXYgrDpyJH&input=&args=WzEyMzQ1NiwgMTEsIDcyNywgMTAxXQ+WyAgICAxMCwgIDIsICAyMCwgIDEwXQ). ### How it works ``` lr0⁹*×b Main link. Arguments: x (integer), n (base) l Compute the logarithm of x to base n. r0 Range; yield all non-negative integers less than the logarithm, in decreasing order. ⁹* Elevate n to all integers in that range. b Yield the list of base-n digits of x. × Multiply each digit by the corresponding power of n. ``` [Answer] ## JavaScript (ES6), 47 bytes ``` f=(n,b,p=1,q=b*p)=>[...n<q?[]:f(n,b,q),n%q-n%p] document.write("<pre>"+ [ [ 123456, 10 ], [ 11, 2 ], [ 727, 20 ], [ 101, 10 ] ] .map(c=>c+" => "+f(...c)).join`\n`) ``` [Answer] ## Jelly, 12 bytes ``` bLR’*@€U b×ç ``` Can be waaaay shorter... [Try it online!](http://jelly.tryitonline.net/#code=YkxS4oCZKkDigqxVCmLDl8On&input=&args=MTIzNDU2+MTA) [Answer] # Pyth - ~~12~~ 11 bytes Just a FGITW, can be shorter. ``` .e*b^Qk_jEQ ``` [Test Suite](http://pyth.herokuapp.com/?code=.e%2ab%5EQk_jEQ&test_suite=1&test_suite_input=10%0A123456%0A2%0A11%0A20%0A727%0A10%0A101&debug=0&input_size=2). [Answer] # J, ~~20~~ 19 bytes ``` [(]*(^<:@#\.))#.inv ``` ## Usage ``` f =: [(]*(^<:@#\.))#.inv 10 f 123456 100000 20000 3000 400 50 6 2 f 11 8 0 2 1 20 f 727 400 320 7 10 f 101 100 0 1 ``` ## Explanation ``` [(]*(^<:@#\.))#.inv #. Given a base and list of digits in that base, converts it to an integer in base 10 inv Power conjunction by -1, creates an inverse Now, this becomes a verb that given a base and an integer in base 10, creates a list of digits in that base representing it [ Select the base and pass it along #\. Tally each suffix of the list of base digits, Counts down from n to 1 <: Decrements each value @ More specifically, decrement is composed with the tally and applied together on each suffix ^ Raises each value x using base^x ] Selects the list of base digits * Multiply elementwise between each base power and base digit ``` [Answer] ## CJam, 16 bytes ``` {1$b\1$,,f#W%.*} ``` An unnamed block that expects the base and the number on top of the stack (in that order) and replaces them with the digit list (including internal zeros, without leading zeros). [Test it here.](http://cjam.aditsu.net/#code=727%2020%0A%0A%7B%3AX%3B%7BXmdXW)%3AW%23*p%7Dh%3B%7D%0A%0A~&input=20%20727) ### Explanation ``` 1$ e# Copy base b. b e# Compute base-b digits of input number. \ e# Swap digit list with other copy of b. 1$ e# Copy digit list. , e# Get number of digits M. , e# Turn into range [0 1 ... M-1]. f# e# Map b^() over this range, computing all necessary powers of b. W% e# Reverse the list of powers. .* e# Multiply each digit by the corresponding power. ``` [Answer] # TSQL, 68 bytes ``` DECLARE @ INT=123456,@z INT=10 DECLARE @l INT=1WHILE @>0BEGIN PRINT @%@z*@l SELECT @/=@z,@l*=@z END ``` [Answer] # Mathematica, 46 bytes ``` DiagonalMatrix@IntegerDigits@##~FromDigits~#2& ``` **Explanation:** ``` In[1]:= IntegerDigits[123456,10] Out[1]= {1, 2, 3, 4, 5, 6} In[2]:= DiagonalMatrix@IntegerDigits[123456,10] // MatrixForm Out[2]//MatrixForm= 1 0 0 0 0 0 0 2 0 0 0 0 0 0 3 0 0 0 0 0 0 4 0 0 0 0 0 0 5 0 0 0 0 0 0 6 In[3]:= DiagonalMatrix@IntegerDigits[123456,10]~FromDigits~10 Out[3]= {100000, 20000, 3000, 400, 50, 6} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` bḅ²×¥@b× ``` [Try it online!](https://tio.run/##y0rNyan8/z/p4Y7WQ5sOTz@01CHp8PT///8bGoAAkAIA "Jelly – Try It Online") `²×¥@` seems too long for what it does. I hope there is a shorter way. ### Explanation ``` b Convert A (the input number) to base B (the input base). ḅ²×¥@ Convert from base A×B² b× Convert to base A×B ``` [Answer] # Regex (ECMAScript), 76 bytes ``` (?=.*,(x(x*)))(?=.*?(((?=(?=\1*,)(x(x*))(?=\5*,)(?=\2+,)(\2\6*),)\7)*x),)\3+ ``` Takes its input in unary, as the length of two string of `x`s delimited by a `,` (number first, then base). Returns its result as the list of matches (each is also a string of `x`s whose length is the value). [Try it online!](https://tio.run/##TU/BUsIwFLz7FZUDfa8NtSkoM9TAyYMXD3oEDgFiSU1DJwlSRa5@gJ/oj2CKOOPMm9m3b2dn35b8ldulkbXr2VquhKk2@kW8HQ3TYhc8iuKuqQHe2fgqOsKEJRGBBpoIEU9sAuDRz4xGBM9SS69b6jGLPc6y2U2EBGdDjJoW@/ExunrHxG2enJG6AEyskksBN6Q3QBKERYi5ZWm@W0slABQzgq@U1AIQL5neKoX7BaNpXjCV2FpJByHxHvkMoFmRKKELt8Zx9vEh7QN/AMlqbqy41w6KaTpH/BMW/wU9phM6amV0a7PZde71K1dyFRiuCzEKOrFqIyoGYRMmRtSCO5AY@@z432WBmFTcLddgEPe22619SQdtJZrXW2edAXkyLeIw@P78CvzrzxsDpa9c3lbn9/MyjnFfevuv5dTwvFfTcv7X8pAfDkea9QeEpheUkuximA1J5veU@tMP "JavaScript (SpiderMonkey) – Try It Online") It's a good thing the challenge allows `0` to be excluded or included, because this solution excludes it, and it would not be possible to include it! (The only way to include it would be either to use .NET with the result returned via a capture's stack, or PCRE with a callout.) The division algorithm is explained in my [Division and remainder](https://codegolf.stackexchange.com/a/222932/17216) post. ``` # If this is the first match, tail = N = input number. Otherwise # tail = N = current intermediate value, which is the input number # after having the previous return values all subtracted from it. (?= .*,(x(x*)) # \1 = number base; \2 = \1 - 1 ) (?= .*? # Decrease tail by the minimum necessary to satisfy # the following assertion: # Assert tail is a power of \1; \3 = tail = the largest power of \1 that is # less than or equal to N. ( # \3 = tail ( (?= # Calculate \5 = tail / \1 (?=\1*,) # Assert tail is divisible by \1 (x(x*)) # \5 = quotient - find the largest that matches the # following assertions; \6 = \5-1; tail -= \5 (?=\5*,) # assert tail is divisible by quotient (?=\2+,) # assert tail is positive and divisible by divisor-1 (\2\6*), # assert tail-(divisor-1) is divisible by quotient-1; # \7 = tool to make tail = \5 )\7 # tail = \5 )* # Iterate the above as many times as possible x # tail -= 1 ) , # Assert tail == 0 ) \3+ # Return value = M = tail - (tail % \3); tail -= M ``` [Answer] # Mathematica, 12 bytes I wonder whether Wolfram Research created this function after seeing the OP's challenge! ``` NumberExpand ``` This was introduced in version 11.0 (August, 2016). [Answer] ## Python 2, 44 bytes ``` lambda n,b:[n/b**i%b*b**i for i in range(n)] ``` Outputs from least significant to most, with many extra zeroes. To output most significant to least: ``` f=lambda n,b,c=1:n*[1]and f(n/b,b,c*b)+[n%b*c] ``` Recurse, repeatedly taking digits off of `n` with divmod while scaling up the place value multiplier `c`. [Answer] # Ruby, ~~35~~ 34 bytes This is a port of [xnor's Python answer](https://codegolf.stackexchange.com/a/79328/47581), but it prints `n` times so the test case `727 20` prints `7`, `320`, `400`, and 724 `0`s. Golfing suggestions welcome. **Edit:** 1 byte thanks to Jordan. ``` ->n,b{n.times{|i|p n/b**i%b*b**i}} ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), 13 bytes ``` Wa-:Pa%oo*:b ``` Doing it the old-fashioned way turned out to be shorter than using the `TB` base-conversion operator. The code runs a while loop until `a` (the number) is `0`. At each iteration, it prints `a%o` and subtracts it from `a`. `o` is preinitialized to `1` and gets multiplied by `b` (the base) each iteration. (This approach keeps all `0`s and also adds a leading `0`.) [Try it online!](http://pip.tryitonline.net/#code=V2EtOlBhJW9vKjpi&input=&args=MTE+Mg) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 7 bytes ``` τ:ẏṘ⁰e* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiz4Q64bqP4bmY4oGwZSoiLCIiLCI3MjdcbjIwIl0=) A nice little answer. Takes `value` then `base` ## Explained ``` τ:ẏṘ⁰e* τ # Convert value from base 10 to input base :ẏṘ # Duplicate that and push the range [len(that) - 1, 0] ⁰e # Raise base to the power of each item in that * # Multiply that by the list of digits of the converted value ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 44 bytes ``` b=>g=n=>n?[...g(~~(n/b)).map(i=>i*b),n%b]:[] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/ydYu3TbP1i7PPlpPTy9do65OI08/SVNTLzexQCPT1i5TK0lTJ081KdYqOvZ/cn5ecX5Oql5OfrpGmoahgaaGoZGxiamZpqY1F6qcEVDKEIswUIu5kTmmBNgsA5CO/wA "JavaScript (V8) – Try It Online") Takes [curried](https://en.wikipedia.org/wiki/Currying) input in the form `function(base)(number)`. [Answer] # [Desmos](https://desmos.com/calculator), 57 bytes ``` k=b^{[floor(log_b(n+0^n))...0]} f(n,b)=mod(floor(n/k),b)k ``` [Try It On Desmos!](https://www.desmos.com/calculator/ptlp4vaug9) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/9twbhzm65q) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 18 bytes ``` -⟜»⊢|˜⊣⋆1+·↕∘⌈⊣⋆⁼+ ``` Tacit function; takes the base as left argument and the number as right argument. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgLeKfnMK74oqifMuc4oqj4ouGMSvCt+KGleKImOKMiOKKo+KLhuKBvCsKCjIwIEYgNzI3) ### Explanation Call the left argument `b` and the right argument `n`. ``` -⟜»⊢|˜⊣⋆1+·↕∘⌈⊣⋆⁼+ ⋆⁼ Inverse exponential (i.e. logarithm) ⊣ with base b + of b + n ⌈ Round up to nearest integer This number is at least as large as the number of base-b digits n has ↕∘ Range (0-based, exclusive) 1+· Add 1 to each ⊣⋆ Raise b to each of those exponents ⊢|˜ Take n mod each of those powers of b » Shift a copy of that list right, prepending a 0 -⟜ and subtract it from the unshifted list ``` For example, with a base of 3 and a number of 17, we have ``` + 20 ⊣⋆⁼ 2.726833027860842 1+·↕∘⌈ ⟨ 1 2 3 ⟩ ⊣⋆ ⟨ 3 9 27 ⟩ ⊢|˜ ⟨ 2 8 17 ⟩ » ⟨ 0 2 8 ⟩ -⟜ ⟨ 2 6 9 ⟩ ``` [Answer] # Racket, 82 bytes ``` (define(d n b[a'()])(if(< n 1)a(d(/ n b)b(cons(*(modulo(floor n)b)(length a))a)))) ``` *I'm a winner (!)* [Answer] # JavaScript (ES7), 68 bytes ``` n=>b=>(c=[...n.toString(b)]).map(d=>b**--p*parseInt(d,b),p=c.length) ``` ## Test Test uses `Math.pow` for browser compatibility. ``` f=n=>b=>(c=[...n.toString(b)]).map(d=>Math.pow(b,--p)*parseInt(d,b),p=c.length) document.write("<pre>"+ [ [ 123456, 10 ], [ 11, 2 ], [ 727, 20 ], [ 101, 10 ] ] .map(c=>c+" => "+f(c[0])(c[1])).join`\n`) ``` [Answer] # JavaScript, 75 bytes ``` (a,b)=>[...a.toString(b)].reverse().map(($,_)=>Math.pow(b,_)*parseInt($,b)) ``` Just for fun :) It could be golfed more, but I'm not too sure how. ## ES7, 66 bytes If ES7 is allowed then: ``` (a,b)=>[...a.toString(b)].reverse().map(($,_)=>b**_*parseInt($,b)) ``` [Answer] # [O](https://github.com/phase/o), 17 bytes ``` jQb`S/l{#Qn^*p}d ``` Two notes: 1. **The third test case does not work due to a bug with base conversion.** See [phase/o#68](https://github.com/phase/o/issues/68). 2. This does not work in the online interpreter. `b` hadn't been implemented yet. [Answer] # ><>, 28 bytes ``` :&\ &*>:{:}$%:n$}-:0=?;ao$&: ``` Expects the input values to be present on the stack at program start. As ><> doesn't have list objects, the output is presented as a newline-separated list of values, with the 'units' on the first line. An example run: ``` Input: 11 2 Ouput: 1 2 0 8 ``` @OP, if this isn't an acceptable output format, let me know and I'll edit the answer accordingly. [Answer] # PHP, 55 bytes Uses Windows-1252 encoding. ``` for($n=$argv[1];$d+$n-=$d=$n%$argv[2]**++$i;)echo$d,~Ó; ``` Run like this (`-d` added for aesthetics only): ``` php -d error_reporting=30709 -r 'for($n=$argv[1];$d+$n-=$d=$n%$argv[2]**++$i;)echo$d,~Ó; echo"\n";' 123056 10 ``` [Answer] ## C#, 77 bytes ``` IEnumerable _(int n,int b){int m=1;while(n>0){yield return n%b*m;n/=b;m*=b;}} ``` [Answer] # C++, 82 Bytes ``` int*f(int n,int b){int*a,o[n]{b,n%b};for(a=o+1;*a=(n-=*a++)%(b*=*o););return o+1;} ``` The main loop is pretty trivial (keep taking modulos and subtracting the lower part). The main savings come from doing lots of calculations in-place and the loop condition being the actual assigned value (which will eventually become 0, after all meaningful output is written to the array) I haven't been able to figure out why, but ideone throws a runtime error if I try to have the function return `o` instead of `o+1`, so I use the extra index to store the powers of b. [Answer] ## Actually, 17 bytes ``` ;a¡;lrR(♀ⁿ@♂≈♀*;░ ``` [Try it online!](http://actually.tryitonline.net/#code=O2HCoTtsclIo4pmA4oG_QOKZguKJiOKZgCo74paR&input=MTIzNDU2CjEw) Explanation: ``` ;a¡;lrR(♀ⁿ@♂≈♀*;░ initial stack: [b n] (b = base, n = number) ; dupe b a invert stack ¡ n as a base-b integer ;lrR dupe, length, range, reverse (♀ⁿ raise b to each power in range @♂≈ create list of integers from base-b string ♀* pairwise multiplication ;░ filter out zeroes ``` ]
[Question] [ When coding in Python, sometimes you want a multiline string within a function, e.g. ``` def f(): s = """\ Line 1 Line 2 Line 3""" ``` (The backslash is to remove a leading newline) If you try to actually print out `s`, however, you'll get ``` Line 1 Line 2 Line 3 ``` That's not what we want at all! There's too much leading whitespace! ## The challenge Given a multiline string consisting of only alphanumeric characters, spaces and newlines, remove all common spaces from the beginning of each line. Each line is guaranteed to have at least one non-space character, and will have no trailing spaces. The output may not have extraneous whitespace, whether it be before or after the entire output or an individual line (with the exception of a single optional trailing newline). Input may be via STDIN or function argument, and output may be via STDOUT or function return value. You **cannot** use any builtins which are designed to dedent multiline strings or perform this exact task, e.g. Python's `textwrap.dedent`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution in the fewest bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply. ## Test cases ``` "a" -> "a" " abc" -> "abc" " abc\n def\n ghi" -> " abc\ndef\n ghi" " a\n b\n c" -> "a\nb\nc" " a\n b\n c\nd" -> " a\n b\n c\nd" " a b\n c d\n e f" -> "a b\n c d\n e f" ``` For example, the last test case is ``` a b c d e f ``` and should look like this after stripping leading spaces: ``` a b c d e f ``` [Answer] # CJam, ~~20~~ 14 bytes ``` qN/_z{S-}#f>N* ``` **Algorithm**: * We first split the input on newlines and take a copy (`qN/_`) * Then the smallest column with non space character is calculated by transposing the newline separated array and then simply looking for the index of the first non-all-space row (`z{S-}#`) * Then we simply remove that many characters away from each line (`f>`) * Finally, we join by newline again (`N*`) **Code Expansion** ``` qN/ e# Read the entire input and split it on newline _z e# Take a copy and transpose rows with columns. e# Now we would have a bunch of all space rows. These rows are the ones e# we want to remove (in form of columns) { }# e# Get the index of the first item from the transposed array that returns e# true for this block S- e# From each part, remove spaces. If the part is all-space, it will return e# an empty string, which is false in CJam. We finally will get the index e# of the first non-all-space row (or column) f> e# We take that index and remove that many characters from starting of each e# row of the initial newline separated input N* e# Join the array back using newlines and automatically print the result ``` [Try it online here](http://cjam.aditsu.net/#code=qN%2F_z%7BS-%7D%23f%3EN*&input=%20%20%20a%20%20%20b%0A%20%20%20%20%20c%20%20%20%20%20d%0A%20%20%20%20e%20f%0A%20s) [Answer] # sed - 26 bytes ``` :;/(^|\n)\S/q;s/^ //mg;b ``` run with `-rz` Pretty straightforward: ``` /(^|\n)\S/q; - quit if there is a line that starts with non-space s/^ //mg; - remove exactly one space in each line :; b - repeat ``` `-r` option turns on extended regexps, `-z` reads whole input as a single string (actually uses NUL-byte as line delimiter) [Answer] # Pyth, 19 18 17 14 bytes ``` jbu>R!rhCG6G.z ``` The implementation is pretty cool. 1. `u .z` grabs all lines of stdin in an array, puts it in `G`. Then it evaluates the inner body, puts the result in `G`, and keeps doing this until it no longer changes (fixed point). 2. `!rhCG6` transposes `G`, gets the first element of the transposed array (the first column), strips it of any whitespace, and checks if there are any non-whitespace characters left. 3. The value from 2 is a boolean, which can be seen as an int 0 or 1. `>R G` grabs this number and slices off that many characters off the left of each line in `G`. Step 1, 2 and 3 combined basically means that it will keep stripping off columns of whitespace until there is no pure whitespace column left. 4. `jb` joins the array of lines by newlines and prints it. [Answer] # SWI-Prolog, ~~233~~ ~~223~~ 217 bytes ``` a(A):-b(A,0,0,0,N),w(A,N,0). b([A|T],P,K,M,N):-P=1,(A=10,b(T,0,0,M,N);b(T,1,0,M,N));A\=32,(M=0;K<M),b(T,1,0,K,N);I=K+1,b(T,0,I,M,N). b(_,_,_,N,N). w([A|T],N,P):-P<N,A=32,Q=P+1,w(T,N,Q);put(A),A=10,w(T,N,0);w(T,N,P);!. ``` **Edit**: Completely changed my answer. It now uses character codes instead of strings. An example of calling this would be `a(` a b\n c d\n e f`).`, with backquotes. You may need to use double quotes `"` instead if you have an old SWI-Prolog distrib. [Answer] # Julia, ~~93~~ ~~92~~ 81 bytes Saved 10 bytes thanks to Glen O. ``` s->for i=(p=split(s,"\n")) println(i[min([search(j,r"\S")[1]for j=p]...):end])end ``` This creates an unnamed function that accepts a string and prints to stdout. Ungolfed + explanation: ``` function f(s) # Split s into an array on newlines p = split(s, "\n") # Get the smallest amount of leading space by finding the # position of the first non-space character on each line # and taking the minimum m = min([search(j, r"\S")[1] for j in p]...) # Print each line starting after m for i in p println(i[m:end]) end end ``` [Answer] # Java, 159 Because there's a conspicuous lack of Java... ``` void f(String...a){int s=1<<30,b;a=a[0].split("\n");for(String x:a)s=(b=x.length()-x.trim().length())<s?b:s;for(String x:a)System.out.println(x.substring(s));} ``` It's just loops comparing length to trimmed length, then spitting out substrings. Nothing too fancy. For the scrollbar-impaired: ``` void f(String...a){ int s=1<<30,b; a=a[0].split("\n"); for(String x:a) s=(b=x.length()-x.trim().length())<s?b:s; for(String x:a) System.out.println(x.substring(s)); } ``` [Answer] # Perl, 47 33 Thanks @ThisSuitIsBlackNot for suggestion to use Perl's implicit loop ``` #!/usr/bin/perl -00p /^( +).*(\n\1.*)*$/&&s/^$1//mg ``` The above is scored as 30 bytes for the line of code + 3 for `00p` flags. ### Original version, as a function: ``` sub f{$_=@_[0];/^( +).*(\n\1.*)*$/&&s/^$1//mgr} ``` This puts the argument into `$_`, then attempts to greedily match whitespace that's present on all lines with `/^( +).*(\n\1.*)*$/` - if successful, `$1` now contains the longest common prefix, and we execute the replacement `s/^$1//mgr` to delete it from the beginning of every line and return the resulting string. ### Test ``` $ cat 53219.data a b c d e f $ ./53219.pl <53219.data a b c d e f ``` [Answer] # Python 2, ~~86~~ ~~79~~ 75 Bytes This can almost definitely be shortened some more, but right now it's not bad. *Thanks to xnor for saving 4 bytes!* ``` s=input().split('\n') for k in s:print k[min(x.find(x.strip())for x in s):] ``` [Answer] # Ruby: ~~77~~ ~~73~~ ~~70~~ ~~66~~ ~~65~~ ~~58~~ ~~57~~ 40 characters ``` f=->t{t.gsub /^#{t.scan(/^ */).min}/,""} ``` Sample run: ``` irb(main):001:0> f=->t{t.gsub /^#{t.scan(/^ */).min}/,""} => #<Proc:0x00000001855948@(irb):1 (lambda)> irb(main):002:0> puts f[" a b\n c d\n e f"] a b c d e f => nil irb(main):003:0> f[" a b\n c d\n e f"] == "a b\n c d\n e f" => true ``` [Answer] # C#, 18 + 145 = 163 bytes Requires (18 bytes): ``` using System.Linq; ``` Method (145 bytes): ``` string R(string s){var l=s.Split('\n');return string.Join("\n",l.Select(x=>string.Concat(x.Skip(l.Select(z=>z.Length-z.Trim().Length).Min()))));} ``` The method calculates the lowest amount of leading spaces on the lines and creates a new string built of all lines, with *N* chars skipped (where *N* is the previously calculated number). [Answer] ## **C#, 149 bytes total** Practically the same solution as ProgramFOX's, although the number of characters to trim is calculated manually. ``` using System.Linq; ``` And the function itself: ``` string D(string s){var l=s.Split('\n');int i=0;while(l.All(a=>a[i]==' '))i++;return string.Join("\n",l.Select(b=>b.Substring(i)));} ``` [Answer] # Python 3, 100 ``` def f(s):t=s.split("\n");return"\n".join([c[min([len(c)-len(c.lstrip(" "))for c in t]):]for c in t]) ``` [Answer] # JavaScript, ES6, ~~89~~ 86 bytes This one is totally using just RegEx matching and substitutions. ``` f=x=>eval(`x.replace(/(^|\\n) {${--` ${x}`.match(/\n */g).sort()[0].length}}/g,"$1")`) // Snippet related stuff B.onclick=x=>P.innerHTML=f(T.value) ``` ``` <textarea id=T></textarea><br> <button id=B>Trim</button> <pre id=P></pre> ``` As always, Firefox only, since ES6. Will add ES5 version later. [Answer] # K, 31 bytes ``` {`0:(&/{(0;#*=x)@*x}'" "=x)_'x} ``` Takes input a list of strings and prints the result to stdout. [Answer] # Haskell, 52 bytes ``` unlines.until(any(/=' ').map head)(map tail).lines ``` Usage example: `unlines.until(any(/=' ').map head)(map tail).lines $ " abc\n def\n ghi"` -> `" abc\ndef\n ghi\n"` How it works: ``` lines -- split the input at newlines into a list of lines until -- repeat the 2nd argument, i.e. map tails -- cut off the heads of all lines -- until the the first argument returns "True", i.e. any(/=' ').map head -- the list of heads contains at least one non-space unlines -- transform back to a single string with newlines in-between ``` [Answer] # Python, 94/95 lambda (94 bytes): ``` f=lambda s:'\n'.join(l[min(l.find(l.strip()) for l in s.split('\n')):] for l in s.split('\n')) ``` def (95 bytes) ``` def f(s):l=s.split('\n');m=min(i.find(i.strip())for i in l);return '\n'.join(i[m:] for i in l); ``` [Answer] ## bash + sed + coreutils, 74, 56, 55 ### Test data ``` s="\ a b c d e f" ``` ### Answer ``` cut -c$[`grep -o '^ *'<<<"$s"|sort|line|wc -c`]-<<<"$s" ``` ### Output ``` a b c d e f ``` [Answer] # R, ~~118~~ 111 bytes Using the wonderful string functions of R :) This is similar/same to other solutions already posted. Input is through STDIN and cats to STDOUT. ``` cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n') ``` Test and explanation ``` > cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n') 1: a<-scan(,'',sep='|') # get the input lines 2: strsplit(a,' ') # split lines on spaces 3: lapply( ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line 4: ,Reduce(min, ) # get the min of those 5: substring( ) # trim it off 6: cat( ,sep='\n') # output each line 7: Read 6 items a<-scan(,'',sep='|') # get the input lines strsplit(a,' ') # split lines on spaces lapply( ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line ,Reduce(min, ) # get the min of those substring( ) # trim it off cat( ,sep='\n') # output each line > ``` [Answer] # Julia, ~~72~~ ~~62~~ ~~61~~ ~~57~~ ~~54~~ 49 bytes ``` g=s->ismatch(r"^\S"m,s)?s:g(replace(s,r"^ "m,"")) ``` Ungolfed: ``` g(s)= if ismatch(r"^\S"m,s) # Determines if there's a newline followed by something other than a space # Note: the m in r"^ "m says to work in multiline mode. s # If there is, return the string as the final result. else # otherwise... m=replace(s,r"^ "m,"") # Remove first space after each newline, and space at start of string. g(m) # Feed back into the function for recursion end ``` Older solution (57 bytes): ``` g(s)=ismatch(r" \S"," "s)?s:g(replace(s," "," ")[2:end]) ``` Original solution (72 bytes): ``` g(s)=all([i[1]<33for i=split(s,"\n")])?g(replace(s,"\n ","\n")[2:end]):s ``` [Answer] # k (24 bytes) Takes a string as an argument and returns a string (with trailing new-line). ``` {`/:(&//&:'~^s)_'s:`\:x} ``` Example: ``` k) f:{`/:(&//&:'~^s)_'s:`\:x}; k) f" a b\n c d\n e f" "a b\n c d\n e f\n ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` |©ζ®gð*Ûζ» ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/5tDKc9sOrUs/vEHr8Gwga/f//woKColAnMSlAALJYDIFzElVSAMA "05AB1E – Try It Online") [Answer] # JavaScript (*ES6*) 56 Recursive, trying to remove one space at a time from each row until a non-space is found. Test running the snippet below - being ES6, Firefox only ``` f=s=>(r=s.replace(/^./gm,x=>(k|=x>' ',''),k=0),k?s:f(r)) // Test test= [[ "a", "a" ] ,[" abc", "abc" ] ,[" abc\n def\n ghi", " abc\ndef\n ghi" ] ,[" a\n b\n c", "a\nb\nc" ] ,[" a\n b\n c\nd", " a\n b\n c\nd" ] ,[" a b\n c d\n e f","a b\n c d\n e f" ]] var tb='' test.forEach(t=>{ t[2]=f(t[0]) t[3]=t[2]==t[1]?'OK':'FAIL' tb+='<tr><td>'+t.join('</td><td>')+'</td></tr>' }) B.innerHTML=tb ``` ``` td { white-space: pre; font-family: monospace; border: 1px solid#444; vertical-align:top} #I,#O { height:100px; width: 200px } ``` ``` <b>Your test:</b> <table><tr><td><textarea id=I></textarea></td> <th><button onclick='O.innerHTML=f(I.value)'>-></button></th> <td id=O></td></tr></table> <b>Test cases:</b><br> <table ><tr><th>Input</th><th>Expected</th><th>Output</th><th>Result</th></tr> <tbody id=B></tbody></table> ``` [Answer] # Gawk, 101 100 ``` {match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}} ``` For example... ``` cat input.txt | gawk '{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}' ``` Output... ``` a b c d e f ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), noncompeting, 43 bytes ``` :lines'^ +'match$#'"!MIN' '*0# '^'\+''mrepl ``` [Try it online!](https://tio.run/nexus/stacked#U@dSQIBEIE6CCCSDyRQwJ1UhjUtdISk1IzUxBUiVJGbm/LfKycxLLVaPU9BWz00sSc5QUVZXUvT19FNXUNcyUFZQj1OP0VZXzy1KLcj5n5JZXPAfAA "Stacked – TIO Nexus") This works by finding the amount of spaces at the beginning of each line (`'^ +'match$#'"!`), getting the minimum, repeat a space that many times, and replacing that with nothing on each line. [Answer] # Vim, ~~33~~, 31 bytes ``` qq/\v%^(\s.*\n?)*%$ :%s/. @qq@q## Heading ## ``` [Try it online!](https://tio.run/##K/v/v7BQP6ZMNU4jplhPKybPXlNLVYXLSrVYX4/LobDQofD/fwU0YJ6YmplfyoUsZJzEharG1NTUIzUnJx8A "V – Try It Online") Old version: ``` qq:g/\v%^(\s.*\n?)*%$/%s/. n@qq@q ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü═≤+Σî║┘` ``` [Run and debug it](https://staxlang.xyz/#p=81cdf32be48cbad960&i=+++a+++b%0A+++++c+++++d%0A++++e+f&a=1&m=1) [Answer] # Python 3, 63 bytes ``` def f(s):return '\n'.join([l.strip() for l in s.splitlines()]); ``` [Answer] ## CoffeeScript, 112 bytes ``` f=(x)->(a=x.split "\n").map((v)->v[Math.min.apply(null,a.map((v)->(r=/^ +/.exec v)&&r[0].length))...]).join "\n" ``` [Answer] ## JavaScript (ES6), ~~106~~ 98 bytes The newlines are necessary and are counted as 1 byte each: ``` f=x=>(a=x.split` `).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join` ` ``` ### Demo As with other ES6 answers, they only work in Firefox at the moment. ``` f=x=>(a=x.split` `).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join` ` // For demonstration purposes console.log = x => X.innerHTML += x + `\n<hr>`; console.log(f("a")); console.log(f(" abc")); console.log(f(" abc\n def\n ghi")); console.log(f(" a\n b\n c")); console.log(f(" a\n b\n c\nd")); console.log(f(" a b\n c d\n e f")); ``` ``` <pre id=X></pre> ``` [Answer] # JavaScript ES6, 85 bytes ``` s=>s.split` `.map(z=>z.slice(Math.min(...s.match(/^ */gm).map(l=>l.length)))).join` ` ``` The new lines are significant ES5 Demo: ``` function t(s) { return s.split("\n").map(function(z) { return z.slice(Math.min.apply(0, s.match(/^ */gm).map(function(l) { return l.length; }))); }).join(''); } // Demo document.getElementById('go').onclick = function() { document.getElementById('r').innerHTML = t(document.getElementById('t').value) }; ``` ``` Input: <br> <textarea id="t"></textarea> <br> <button id="go">Run</button> <br>Output: <br> <pre style="background-color:#DDD;" id="r"></pre> ``` ]
[Question] [ Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details. --- Fen is a magician Elf. He can cast spells on an array of numbers to produce another number or array of numbers. One of his inventions is the Wick spell. He loves to use this spell because "once this spell is applied, [a combination of `prefix sum` spells and `change number` spells becomes magically cheaper](https://codegolf.stackexchange.com/q/225634/78410)". ## Task Implement Fen's Wick spell. * Given an array of positive integers `A` of length `n`, * Replace each item at 1-based index `i` with the sum of last `j` elements, where `j == 2 ** (trailing zeros of i in binary)`. For example, if the given array is `A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]`, ``` Wick(A) = [ 1, # 1 3, # 1+2 3, # 3 10, # 1+2+3+4 5, # 5 11, # 5+6 7, # 7 36, # 1+2+3+4+5+6+7+8 9, # 9 10, # 9+1 ] ``` Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` [] -> [] [999] -> [999] [3,1,4] -> [3,4,4] [3,1,4,1,5,9,2,6] -> [3,4,4,9,5,14,2,31] ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 45 bytes ``` lambda l,i=0:[sum(l[i&(i:=i+1):i])for _ in l] ``` [Try it online!](https://tio.run/##NcVBDsIgEEDRPaeYlYE4C7FqhISTIDEYSzrJlBKkGk@P3bj475dvm5Y8XEvtyd06x/nxjMBI7mD9a50le9pJso72WlkKKi0V7kAZOPTPRDyCtgLYje/IknJZm1RKQKmUm0ySleo@CG@M2RxQ4@n/rTMaPOIl/AA "Python 3.8 (pre-release) – Try It Online") The start index for the sum at one-indexed position `i` is `i&i-1`, which is obtained from the binary representation of `i` by setting the rightmost 1 bit to 0. [Answer] # [Python](https://www.python.org) NumPy, 42 bytes ``` def f(a):b=a[1::2];b+=a[:-1:2];b@b>0!=f(b) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY47DsIwEETr-BRL58AmIvyEjYK4R5RiDVikiG0Zp_BZaNLAnbgNBpFiZ14zevt4uRhu1ozjcwi62L_nl6sGzSmXqqamknLVHtQioSyqH5_UcTmrNVf5f2G73lkfwAy9i0B3MI4xbT0QdAaaFhshRMo1VriZOt0WBa5w10qWEdRpVZL3FJOaZcldnq2LPPFXxTLnOxM44aSdHv4A) ### [Python](https://www.python.org) NumPy, 44 bytes ``` def f(a):a[1::2]+=a[:-1:2];a@a>0!=f(a[1::2]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU5LDoIwFFzTUzx3JT6I4Ce2psZ7NCweaiML2qbComdxw0bv5G1sIizmk0wmM6-Pj8PD2Wl6j4Mpjl-83Q0YTrkkXUlZN2tFWhZVcie60HmzUin9R_nccV3vXRjAjr2PQE-wnjHjAhB0FnSDWgiReIsV7hZN2KPAGg-NZBmBSq2SQqCYxlnWKiqvzkeevOFtYh86O3DCdp5dLv8A) Takes a NumPy array and modifies it in-place. ### How? Simple recursion best explained by example: ``` a1 a2 a3 a4 a5 a6 a7 a8 a9 ==> a1 a1+a2 a3 a3+a4 a5 a5+a6 a7 a7+a8 a9 ==> a1 a1+a2 a3 a1+a2+a3+a4 a5 a5+a6 a7 a5+a6+a7+a8 a9 ==> a1 a1+a2 a3 a1+a2+a3+a4 a5 a5+a6 a7 a1+a2+a3+a4+a5+a6+a7+a8 a9 ``` [Answer] # [Rust](https://www.rust-lang.org), 64 bytes ``` |x:&[_]|(0..x.len()).map(|i|x[i&i+1..=i].iter().sum()).collect() ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LcxPCoJAHIbhvaeYXMgM_RrS_plmdYhoIyIiIwyMJjoDkuNJ2rioC3SbblNqq48PHt7Hs1K17N9ZgfKEF5igVjCJMhS8lMwW7uesG88K40jjJaUNFexnCM2TEmuum5BbfG5TGvCIcskqTGit8kGkNyFYKjH5dy6-MYRj78rSg6r5nR1RgDJshfb4wImIbxhlxQspihk2W-_UmTACcGAFa9jAFnbgwh7siAy4m9p9P-0X) Uses XNOR's trick. Also uses blatant abuse of type annotations outside the code. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` IEθΣ✂θ&κ⊕κ⊕κ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQRyG4NFcjOCczORXEccosKc8sTnXMS9HI1lHwzEsuSs1NzStJBXI1NTEEQMD6///oaGMdQx0TIDbVsdQx0jGLjf2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over elements θ Input array ✂ Sliced from κ Current index & Bitwise And κ Current index ⊕ Incremented κ To current index ⊕ Incremented Σ Take the sum I Cast to string Implicitly print ``` Due to Charcoal being 0-indexed, the length of the slice is `(k+1&-(k+1))` and the start position is therefore `k+1-(k+1&-(k+1))`. However `-(k+1)` is the same as `~k` so that simplifies to `k+1-(k+1&~k)`. Writing `k+1` as `(k+1&k)|(k+1&~k)` (which have no bits in common) we see that the `k+1&~k`s cancel, leaving `k+1&k`, at which point this degenerates into a port of @xnor's Python answer. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~13~~ 7 bytes ``` ẏD›⋏ṡİṠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuo9E4oC64ouP4bmhxLDhuaAiLCIiLCJbMywxLDQsMSw1LDksMiw2XSJd) Half porting python. TIL `ṡ` vectorises zip-wise between two lists. ## Explained ``` ẏD›⋏ṡİṠ ẏ # The range [0, len(input)) D # pushed three times to the stack › # increment the top copy ⋏ # and get the bitwise-and of each pair of n and n-1 in each list # At this point the stack is: [[0, 1, 2, ..., len(input) - 1], [1 bitand 0, 2 bitand 3, 3 bitand 4, ..., len(input) bitand len(input - 1)] ṡ # create the range [x, y] for each x and y pair in the top two stack items: [[0], [1, 0], [2], [3, 2, 1, 0], ...] İ # get the nth item in the input at each atomic index in the above list: [[input[0]], [input[1], input[0]], ...] Ṡ # sum each sublist and implicitly print ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, ~~34~~ ~~27~~ ~~22~~ 18 bytes ``` $+g@(_BA_+1\,_)MEg ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCIkK2dAKF9CQV8rMVxcLF8pTUVnIiwiIiwiMyAxIDQgMSA1IDkgMiA2IiwiLXAiXQ==) Port of @xnor's answer. Started with a port of my own python answer, but @xnor's was much shorter ~~-7~~ -12 bytes thanks to @AidenChow and @DLosc -4 bytes thanks to @DLosc [Answer] # [Python](https://www.python.org), 82 bytes ``` lambda A:[sum(A[i-2**len(bin(i)[2:].split("1")[-1]):i])for i in range(1,len(A)+1)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY9BTsMwEEX3OYXVlV0mqJOkoYmURa7A1ljIpQlYct0odoXgKmwiIbgTF-AcjEmABbJGMx7_eZ7_8j48hYeTm1775ubtHPp093Ft9XF_0KytpT8feStNmq3XtnN8bxw3Qma1uvSDNYGvcCVkikrURon-NDLDjGOjdvcdR4gjrbhAoRbyZ-h8uL3TvvONTCRCBjkUsIUSrmAHFaCCRMaoqiqmHBCK34JiS6IMSmqpJNHOP3bjgsrp4IYEiATLy0jb_MMVPzgqSEHqIi6B38BhNC5wbS2XPY-riqaZ_2DRW-zAcieXz2bgf36WBy-UELPbaZrzFw) [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes ``` a->a*matrix(#a,,j,i,i-j<gcd(i,2^i)&&j<=i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY1dCsIwEISvEiqURCYPbe1PoO1FStVFadmgEkoFPYsvBRHP5G1MsfiwM9_OMuzj7WjgXe-mZyeq13XsdPFRpGtan2kc-CZXBFgwWNuyPxwlI96yCkNbVqyWwp6cO90lCV0LN_Bl9BjMSyA6SUpBNE3rxRgzW4IImz_4SWEQI5ujyEPiwxQZchT-ELXt8meafv4F) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 42 bytes ``` a->a*matrix(#a,,j,i,j>bitand(i,i-1)&&j<=i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY1hCoJAEIWvshjIrrz9sZnmQnoRkZoIY8RkkQ3qLP0RIjpTt2kl6ce8980bHvN4Oxp5f3bTsxXl6-pbXXwS0hUlF_Ij3-SKgA6Mrjqyp-EkGayNiuNuV7JaGgdyrr9LEroSbuTBB4zmJRKtJKUg6roJYq2dLYXB5g9hMliskc-RCZCGMEOOLYpwME2z_Jmmn38B) A port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/255276/9288). [Answer] # JavaScript (ES6), 48 bytes Isolates the least significant non-zero bit of the 1-based index and uses it as a counter to recursively add previous values to the current one. ``` a=>a.map((_,i)=>(g=j=>j&&a[--i]+g(j-1))(++i&-i)) ``` [Try it online!](https://tio.run/##bcpBCoMwEIXhfU@RlczgREnVQhbJRSSUwaokWCO19Ppp6EraPnibny/wi/fh4benXONtTJNJbCxXd94AruTRWJhNMDYUBfdSelfOEKRChLL0hfSIaYjrHpexWuIME/RaaycOQxR1LT759EUbUtS6H9pQm/NfnN@RpjNd3BHn1JFqc2@US28 "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 47 bytes Porting [xnor's approach](https://codegolf.stackexchange.com/a/255276/58563) is 1 byte shorter. ``` a=>a.map((_,i)=>eval(a.slice(i&++i,i).join`+`)) ``` [Try it online!](https://tio.run/##bcpBCsIwEIXhvafISiZkTKlphSzai0iwQ0wlJU2KlV4/BldFffA2H/9EG6326ZfXKaa7y2OXqetJzrQA3NDzrncbBSC5Bm8d@KMQvrCcko@DGDjPNsU1BSdDesAIV621YbtxzqqKffjwlSqssTE/qcKm8N@4vEWNZ7yYfVyoxboprmqT3w "JavaScript (Node.js) – Try It Online") [Answer] # Excel (ms365), 119 bytes [![enter image description here](https://i.stack.imgur.com/RRWAe.png)](https://i.stack.imgur.com/RRWAe.png) Formula in `B1`: ``` =IFERROR(MAP(SEQUENCE(COUNT(A:A)),LAMBDA(z,SUM(OFFSET(A1,z-1,,-BIN2DEC(TEXTAFTER(0&BASE(z,2),1,-2,,,BASE(z,2))))))),"") ``` I've no doubt this can be further shortened. [Answer] # [Desmos](https://desmos.com/calculator), 95 bytes ``` f(l)=[l[i-2^{[0...i][mod(floor(i/2^{[0...i]}),2)=1].min}+1...i].totalfori=[0...l.length][2...]] ``` [Try It On Desmos!](https://www.desmos.com/calculator/da5t11smix) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/04vd8aqoaw) Desmos doesn't have any binary functionalities like converting to binary or bitwise anding, so basically around half the code is dedicated to converting to binary and finding the number of trailing zeroes. Also, in case you were wondering, I can't simply do `[1...l.length]` instead of `[0...l.length][2...]` because `f([])` (empty list input) gives an error for `[1...l.length]`: "Ranges must be arithmetic sequences." [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 7.5 bytes (15 nibbles) ``` .,,$+>`&-$~$<$@ ``` ``` .,,$+>`&-$~$<$@ . # map over each i in , # range from 1.. , # length of $ # input, + # get the sum of: > # drop the first j elements, where j is `& # bitwise AND of -$~ # i-1 and $ # i, <$ # from the first i elements of @ # input ``` [![enter image description here](https://i.stack.imgur.com/lvVhX.png)](https://i.stack.imgur.com/lvVhX.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` āεN&NŸèO ``` [Try it online](https://tio.run/##yy9OTMpM/f//SOO5rX5qfkd3HF7h//9/tKGOkY6xjomOqY6ZjrmOhY6ljmEsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PNJ7b6qfmd3THoXXFh1f4/6/V@R8dbahjpGOsY6JjqmOmY65joWOpYxirEw1ElpaWQNJYx1DHBEYDsSlQgZGOWWwsAA). **Explanation:** ``` ā # Push a list in the range [1, (implicit) input-length] ε # Map over each of these 1-based indices `y`: N # Push the 0-based map index `N` & # Bitwise-AND the 1-based index `y` and 0-based index `N` together NŸ # Pop and push a list in the range [y&N,N] è # Index each into the (implicit) input-list O # Sum this list together # (after which the list is output implicitly as result) ``` [Answer] # [C (clang)](http://clang.llvm.org/), 49 bytes ``` i;f(*a,n){for(;n;)for(i=n&--n;i<n;)a[n]+=a[i++];} ``` [Try it online!](https://tio.run/##rVTbjpswEH3frxghZcXFaEOAtNRL@1D1KxIeEDFb1K0TLlWjRvx66WBjbG/60IdGhLHnzMw5MwaqsHot@cs0NbR2/ZJw71afO5dy6s22yfljGHLaPKOjPPAiyMtDEwQFHaeGD/C9bLjrwe0B8Dc7BtYP0aGAHG4RgR2BmEBCICWwJ/COwHsCGYFopGv0TkYbnlh6siwznIl0YjmsmxhAagHingoSJN@PdFXGrhdWDeyk1cXiirYiIYqEvngvBW4XBpVlq1TeO6UK0GoTrVaBqQUKvllAIucVGZrn/riM7ptf7Fy7Yr7e07Lz5ZaAge5sdGejsY3GNprYaGKjqY2mnlbqC6m9lCpEEXm40sTSJNKkZp4aikxdD4noyetlrJeJXqpy1Zn3A1Rfy87HO6u@sU4WdY7XL7vjNfuM/9QhYO5jZ8nGpx3ceeYNP7Erpm3psnxWM1CEHjwpl7/6KASBiFdvg54MFpPTEXhBTRj4gvI79NIhXrvOzfG0c5XZSoktyuMzd2vymumbfnPCplv4BHPv8AEctMOhLYyy4x3rCOFHsKndAT8P1G6OoYz1CP/W36Xse4yJ/qmFNeZNK3ONx1yIhhwJ0dL/2@ymP3KMVM/NzKhSZHjHhh8dR70P4/S7ql/Ll34Kf/4B "C (clang) – Try It Online") *Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s idea from his [Python answer](https://codegolf.stackexchange.com/a/255276/9481)* Inputs a pointer to an array of integers and its length (because pointers in C carry no length info). Returns the Fen Wicked array through the input pointer. [Answer] # [Python](https://www.python.org), ~~84~~ ~~83~~ 77 bytes There's probably room for improvement here. Takes both the array and the length of the array, and returns a map. ``` lambda a,n:[sum(a[u-2**len(bin(u+1).split("1")[-1])+1:u+1])for u in range(n)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5NCsIwEIWvEoqLmToRUn-oBe8hhCxSbDWQjiFNFp7FTTd6J29jF-3iLR7f4-O9v-GVHk-epk9Ovax_115chLdDe7PCEjeDDbDU3Ix5AKuzhKosfcfQOoa8VbiLY_AuQaEK1FIZlAqbGRikaPneASMu_k2IjhN4NyboQe9J0WHOkc5U0cmQqHHdrp_-) [Answer] # Java 8, 89 bytes ``` a->{int l=a.length,r[]=new int[l],i;for(;l-->0;)for(i=l&l+1;i<=l;)r[l]+=a[i++];return r;} ``` [Try it online.](https://tio.run/##dVDLbsIwELzzFSsOVaw4VlMKbXCDVPVcLhwjH7bBUFPjIMehQlG@Pd3wEKcevLMejWZGu8MjJrv1T19arGv4ROPaEYBxQfsNlhqWw/dMFArK6ILIJLHdiEYdMJgSluAg7zFZtKQAm6Ow2m3DN/eFyp3@PRtYxY3cVD6SNkkWj5INu8ntg41Tad5yK5knUZxjYeJYSa9D4x142fVyyDo0X5ayrpHHyqxhT4WjVfDGbQuF7FJ2sD2ih6Dr8IG1hjncKqhCtW3H2yzLaE54yp9vSG/KM/7EZ8SkhBPipnzGX/gr8WnXsbM7wOpUB70XVRPEgZKDddGO7iiaYKx49x5PtQjVpVV0K8Hi8RzG8f9CJ8q7mF0v3PV/) **Explanation:** ``` a->{ // Method with integer-array as both parameter and return-type int l=a.length, // Length of the input-array r[]=new int[l], // Result-array, starting with this length amount of 0s i; // Index-integer, uninitialized for(;l-->0;) // Loop `l` in the range (length,0]: for(i=l&l+1; // Set `i` to `l` bitwise-AND-ed by `l+1` i<=l;) // Inner loop `i` in the range [i&i+1,l]: r[l]+= // Add to the `l`'th value of the result-array: a[i++]; // The `i`'th value of the input-array return r;} // After the nested loop, return the resulting array ``` [Answer] # [Factor](https://factorcode.org), 90 bytes ``` [ dup length [0,b) [ dup dup 1 + bitand swap 1 + rot [ <slice> ] keep swap sum ] map nip ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY69TgMxEIT7e4ppERAR_u9AKWhQJAhFlAJOKTbO5rDi8xnbJxQhnoTmmvBOeRs28lUgipVnvh1r9ut7RSo2vtutZ9Px5L7Amr1lg8BvLVvFATXF14EnW4m2VHNwtMfOc4wb57WNMI0ik5Ig72kTcJONJwVURSqbPj_ePT0kc5WVhuO2javj691LiWXrYNhW8rE8OVocIKH9DHGIhY5klwjvlLxvoiRug9GKR5jLsezSNrS1-FqU1Q7zvkEXo772A_hMEnKrwUBInud_4ZkUnf-Hh7hAjlNc_g70hV2X3h8) [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` £sY°&YY x ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=o3NZsCZZWSB4&input=WzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDFd) [Answer] # [Ruby](https://www.ruby-lang.org/), 35 bytes Port of [xnor's approach](https://codegolf.stackexchange.com/a/255276/11261) via [Arnauld's](https://codegolf.stackexchange.com/a/255279/11261). ``` ->a{i=0 a.map{eval a[i&i+=1,i]*?+}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3lXXtEqszbQ24EvVyEwuqU8sScxQSozPVMrVtDXUyY7XstWtroUrNChTcoqNjY7nAtKWlJYxprGOoY4LCAWJTHUsdIx2z2FiI7gULIDQA) [Answer] # x86-64 machine code, 23 bytes ``` 31 C9 8B 04 8F 89 CA FF C1 09 CA 39 F2 73 03 01 04 97 39 F1 72 EC C3 ``` [Try it online!](https://tio.run/##TVLLbsIwEDzHX7FNheQkpqVAkRqaXnrupadKkIOxHXCVOMgGGor49abr8BAHex@zO7NrWfSXQrQtdxVQ@AwpKdKgqS0o0TB/EZsGVb0DxTGeWakhgXFsRZOTU16e6wJtxMnx3desqNbnyGkSfHMFjgRcyhsu2eTM8xOXnsrFtXwBlgRWbUgURlOyq7WEgmqzgZgz8NZg@h6Vy61U8Oo2UtcPqzdCPFZxbbpibpeCgVhxC3GMwS4iBz8vIrMcMjiM2BMb43lmL2zIJsfpCS0Rc/pX1QXl0ePZizlKBphhUHYertupaKweTNHcZVCiTZII1haRgoY9DSFDNZ37lkt2bubmg4uVNgpELVXql@yUG8/FYI@hrOFwaYDeYPiFRPuM0q1xemmU7PaKoyKaNUmC9Ef4WelSAd37QQbN@@hWEiiOsthvlIvmBpkaD@IDb63B4cmxbf9EUfKla/vVZIwXfowMW1X5Dw "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of an array of 32-bit integers in RDI and its length in ESI, and modifies the array in place. --- Go through each position in ascending order, and add its value to the value at the position that should immediately contain it, if that position exists within the array's bounds. ``` ―――――――7 ↑ ↑↑ ―――3 || ↑↑ || ―1| ―5| ―9 ↑ | ↑ | ↑ 0 2 4 6 8 ``` With 0-indexing, if the current position is `n`, the containing position is `n OR n+1`. --- Assembly: ``` f: xor ecx, ecx # Set ECX to 0. r: mov eax, [rdi + 4*rcx] # Load the value at index ECX into EAX. mov edx, ecx # Set EDX to the value of ECX. inc ecx # Increase the value of ECX by 1. or edx, ecx # Set EDX to its bitwise OR with ECX. cmp edx, esi # Compare that value to the the length. jae s # Jump if it's greater than or equal to the length. add [rdi + 4*rdx], eax # (If it's less) Add EAX to the value at index EDX. s: cmp ecx, esi # Compare ECX to the length. jb r # Jump back, to repeat, if it's lesser. ret # Return. ``` [Answer] # [Halfwit](https://github.com/chunkybanana/halfwit/), 38 bytes ``` >[<?(>M<+;M>M<N+JM>{<b(n};W;R*;(n};W>{<b:Nn+(:n+?i$;_WR+ ``` [Try It Online!](https://dso.surge.sh/#@WyJoYWxmd2l0IiwiIiwiPls8Pyg+TTwrO00+TTxOK0pNPns8YihufTtXO1IqOyhufTtXPns8YjpObisoOm4rP2kkO19XUisiLCIiLCJbWzNuLDFuLDRuLDFuLDVuLDluLDJuLDZuXV0iLCIiXQ==) Why did I create this language again? Doesn't help that several builtins that would've been useful for this are buggy or just unimplemented. Uses xnor's trick. ``` == range generation == >[<?(>M<+; # Get the length of the input (oof) >[< # Push 0 ?( ; # Over every item of the input... >M<+ # Increment == The binary bit == M>M<N+JM>{<b(n};W;R*;(n};W>{<b # For each index, calculate i & i-1 M # Over each integer from the previous... >M<N+ # Decrement J # Pair with the decremented version M ; # Over each... b # Convert to base... >{< # 2 ( ; # Over each binary digit n} # Push it to the bottom of the stack W # Get all elements of the stack i.e. the reversed binary representation R*; # Reduce by multiplication i.e. & for single bits (n};W # Reverse again (see above) >{<b # Convert back from binary == Index into input and sum == :Nn+(:n+?i$;_WR+ # For each number from i&i-1 to i, get that index in the input, and sum :Nn # Make the stack [i&i-1,i&i-1,-(i&i-1), i] + # i - (i&i-1) ( ; # That many times... : # Duplicate the i&i-1 kept on top of the stack. n+ # Add that to the current index ?i # Index into the input $ # Push under the i&i-1 _W # Pop the i&i-1 and wrap the stack R+ # Sum ``` [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 13 bytes ``` l@€^à^G€³s®;Σ ``` [Try it online!](https://tio.run/##y8/INfr/P8fhUdOauMML4tyB9KHNxYfWWZ9b/P9/tLGOoY4JEJvqWOoY6ZjFAgA "Ohm v2 – Try It Online") Simple port of 05AB1E for the hats :p ## Explained ``` l@€^à^G€³s®;Σ l@ # the range [1, len(input)] €---------- # to each number: ^à # bit-and with number - 1 ^G # the range [number, ^] €---; # to each: ³s® # input[^] Σ # sum ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes ``` a=>a.map((_,i)=>(g=j=>j&~i?0:a[j]+g(j-1))(i)) ``` [Try it online!](https://tio.run/##bcpBCsIwEIXhvafISmZw2hqTChESD1KChNqWhNoUKy69egyuivrgbX6@4J5uae9@fhRTvHap18lp48qbmwEu5FEbGHTQJmxf/rw/uSbY3QCh4IjgEVMbpyWOXTnGAXpolFKWrYbIqop98uaLCuIk7Q8VJHP@i/NrUnSgo13jnGriMnfBbXoD "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` J&’‘rƲị⁸§ ``` A monadic Link that accepts a list of positive integers and yields another. **[Try it online!](https://tio.run/##ATIAzf9qZWxsef//SibigJnigJhyxrLhu4vigbjCp////1sxLDIsMyw0LDUsNiw3LDgsOSwxXQ "Jelly – Try It Online")** ### How? Much like many others, uses the same bitwise trick that [xnor used](https://codegolf.stackexchange.com/a/255276/53748). ``` J&’‘rƲị⁸§ - Link: list of positive integers, A J - range of length (A) -> [1..length(A)] Ʋ - last four links as a monad - f(X=that): ’ - decrement (X) & - (X) bitwise AND (that) ‘ - increment (that) r - inclusive range -> [[startIndexForSum, endIndexForSum] for each element] ⁸ - chain's left argument -> A ị - (ranges) index into (A) § - sums ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` .es:Q.&hkkh ``` [Try it online!](https://tio.run/##K6gsyfj/Xy@12CpQTy0jOxvIiTbWMdQxAWJTHUsdIx2zWAA "Pyth – Try It Online") Uses [xnor's](https://codegolf.stackexchange.com/a/255276/58563) trick. ### Explanation ``` .es:Q.&hkkhkQ # implicit k and Q added # Q = eval(input()) implicitly .e Q # enumerate k over the indices of Q s # sum of :Q # index Q from .&hkk # k & (k+1) hk # to k+1 ``` ]
[Question] [ Given an infinite arithmetically-progressive¹ sequence, compute the minimum length of a prefix with a product divisible by 2^8. ## Sample cases & reference implementation [Here](https://tio.run/##fU/LDsIgELzzFZsmTQA5CD7SNOEbvOgH1NpGYoWm4vcjj0jaGDsXdnZ2ZhdlnOuhlvDs7N3csNLKMnjZbmQIPFrz1jbo20ibUIaZxNo2cB7JYMwIOJZfTQIOD4WGQAlYAKVQkcXIOCltB517qo@WEgSlFUi/l2UtoDhdznWRbAsBp0s3wMlPaMB16ppH7syO8Fc23ha@nJspS0LORMlEEOoxZ5ygQs5Q5I09Fmy/ou7YYdV7XFE5E/9U5z4) is a reference implementation that I wrote in Io. ``` 1, 1 -> 10 2, 4 -> 8 3, 5 -> 10 2, 6 -> 5 7, 5 -> 6 4, 1 -> 9 10, 9 -> 7 256, 9 -> 1 ``` ## Spec * The input will always be provided in a way such that it won't take forever to zero the accumulator. * ¹ An arithmetically progressive infinite list can be generated by a constant step each time starting from an initial number. + For the infinite list input, you're are allowed to simply take the initial number and the step of the infinite list. * There are only going to be integers in this sequence. # Examples * 1\*2\*3\*4\*5\*6\*7\*8\*9\*10 = 3,628,800 = 14,175\*256 * 2\*6\*10\*14\*18\*22\*26\*30 = 518,918,400 = 2,027,025 \* 256 [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` f=lambda a,d,p=1:p%256and-~f(a+d,d,p*a) ``` [Try it online!](https://tio.run/##JYrBCsMgEETv/Yq9FNZ0C9FGSwr5mA1GIqRWgqX0kl83iqeZN2/iP62foHJ208bv2TIwWYqTfMWr0oaDvR8O@Wbr2rHIv9VvCxS9@5DAYedD/CYUIqMkkOKCimAo8SDQjUyJZ6OhXWRPMFapTS0n "Python 2 – Try It Online") Tracks the product `p` of the arithmetic progression until it's divisible by 256. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 24 bytes ``` {0=256|×/⍵:≢⍵⋄⍺∇⍵,⍨⊃⍺+⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqA1sjU7Oaw9P1H/VutXrUuQhIPepuedS761FHO5Ct86h3BZCj/airGcir/f/fUCFNwZDLBEgaKXCZAiljBS4zBM@cC6TARIHLEqTOAEIDbVAAAA "APL (Dyalog Unicode) – Try It Online") `⍵` is the the sequence (starting with the first item), `⍺` the step. --- `0=256|×/⍵` - if the product is divisible by 256, `≢⍵` return the length. `⍺∇⍵` - else, recurse, `,⍨⊃⍺+⍵` - and append a new term to the sequence. [Answer] ## INTERCAL, 471 445 443 bytes I could have done anything else but I've always wanted to try this language out... ``` DOWRITEIN:5DOWRITEIN:6DO:8<-:5DO:7<-#1PLEASECOMEFROM(9)DO:1<-:6DO:2<-:7DO(1549)NEXTDO:1<-:3DO:2<-:5DO(1509)NEXTDO:1<-:3DO:2<-:8PLEASEDO(1549)NEXTDO:8<-:3DO:1<-:8DO:2<-#256PLEASEDO(1550)NEXTDO:4<-:1DO:1<-:3PLEASEDO(1540)NEXTDO:1<-:4DO:2<-:3PLEASEDO(1510)NEXTDO:1<-:3DO:2<-:3PLEASEDO(1550)NEXTDO:1<-#1DO:2<-:3DO(1509)NEXTDO(1)NEXTDO:1<-:7DO:2<-#1DO(1509)NEXT(9)DO:7<-:3(1)DO(2)NEXTPLEASEFORGET#1DO:1<-:7DO:2<-#1DO(1509)NEXTDO:7<-:3PLEASEREADOUT:7PLEASEGIVEUP(2)DORESUME:3 ``` Inspired by Noodle9's C answer. Formatted version: [Try it online!](https://tio.run/##fZJNC8IwDIbv/RUBL/MgrNvq5vAiLpOBWqmdehXxIIgH8f/PtXaa@nVL6PMmb5KeLrfj9bA/N00hYasqjVAtIRfMS4cmzTMYD9xTnpq4xxlbzXGyRpjKBUKp5AKCUZ9ZhFv8IY1snJo44CIZ9WGJO02wmGDCYeF/LOt6fymaOZpIs5e0F4mhLxYhESeW515bv1X4YSwhxt5o3tE/5oj/WOFuzZR@Ww6x7M2bknn5N1HAu6Q9GTyPaqqYJ0NEjnAGS6lmqOnZFU4KkLUmU8yqDUK9aotEtojCdd3@jXZDTaO3kpWyVnAH "INTERCAL – Try It Online") Explaination based on blocks, blocks seperated by double line breaks. (if magic) marks code for an If-structure I've found in the manual. ``` Setup vars and input - :5 = start value - :6 = step size - :7 = step count - :8 = current cumultative product Label (99) :8 *= (:7 * :6) + :5 Calculate :8 % 256 Divide result by itself and add one. If the result is 0, the division subroutine returns 0, else it returns 1. We need to add one becase label (0) is invalid. Store result in :10 Increment :7, store result in :3 (if magic) If :10 is 2, put :3 in :7 and jump to (99) (if magic) If :10 is 1, print :3 and terminate (if magic) ``` If someone can get rid of that double addition, I'd be *very* grateful. ### EDIT Found out a way to get rid of it. Also updated the explaination and fixed some formatting. -2 by using a shorter label [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` V¦256G*¡+ ``` [Try it online!](https://tio.run/##yygtzv6f6/aoqfF/2KFlRqZm7lqHFmr///8/WsNQx1BTR8NExwhImuoYA0kzKNscSBrqmABJSx1DAzAF1KkZCwA "Husk – Try It Online") Takes first the step, then the initial value. # Explanation ``` V¦256G*¡+ Implicit arguments: step and start + Function that adds step. ¡ Iterate on start to form infinite list [start, start+step, start+2*step..] G Cumulative reduce by * multiplication. V 1-based index of first value that ¦256 is divisible by 256. ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~38~~ 31 bytes ``` {+($^a,*+$^b...{[*](@_)%%256})} ``` [Try it online!](https://tio.run/##Tc1BDoIwFATQPaeYBRigX6AIRQwa74FgMFJjAmpgRZCz1zZh4e5NZn7@px06ofoJG4mjmplr1w35zK5vQRDMpV@556vnOHEqFm9RYzNB4suKoj88wsudhWVEvIJ8D@ier3ZUACdwbE/gkQXEhMSEvfaOkP4XwoRUO1sLoZ2s17mld4TcOLP0@9X8Bw "Raku – Try It Online") Does pretty much exactly what the description asks for. Generates the arithmetic sequence until the product of elements is divisible by 256 and returns the length of the list. [Answer] # JavaScript (ES6), 33 bytes Takes input as `(step)(init)`. ``` s=>g=(i,p=1)=>p&&g(i+s,p*i%256)+1 ``` [Try it online!](https://tio.run/##dc47CoAwEATQ3nsou/4wahSL9S7iJ0TEBCNeP8ZSojDVY2BmHa7BjIfUZ7arabYLWUO9IJCpJobU6ygSIBOT6liGJW8wYXZUu1HbnG9KwAIMXTB4Y41QesgRKg@bn2broRuqPezcevGlz1e0Nw "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` ha`&G@q*+*8W\t}x@ ``` [Try it online!](https://tio.run/##y00syfn/PyMxQc3doVBLW8siPKaktsLh/39jLlMA) Or [verify all test cases](https://tio.run/##y00syfmf8D8jMUHN3aFQS1vLIjympLbC4X@sS1RFyH9DLkMuIy4TLmMuUyBtxmUOpE2AYoYGXJZcRqZmXJYA). ### Explanation This uses the fact that `mod(a*b, N)` equals `mod(mod(a, N)*b, N)`. ``` h % Take the two inputs (implicitly): a (initial term), s (step). % Concatenate them into a row vector a % Any: true (or 1) if there is any nonzero entry. Gives true ` % Do...while &G % Push the two inputs again: a, s @q % Push n-1, where n is the 1-based iteration index * % Multiply: gives s*(n-1) + % Add: gives a+s(n-1), which is the n-th term of the sequence * % Multiply this by the previous result (which was initialized to 1) 8W % Push 8, exponential with base 2: gives 256 \ % Modulus t % Duplicate. This will be used as loop exit condition } % Finally (execute this on loop exit) x % Delete latest result (which is necessarily 0) @ % Push current n. This is the solution % End (implicitly). A new iteration is executed if the top of the % stack is nonzero % Display (implicitly) ``` [Answer] # [J](http://jsoftware.com/), 30 29 bytes ``` [:#(],(+{:))^:(0<256|*/@])^:_ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o62UNWJ1NLSrrTQ146w0DGyMTM1qtPQdYoG8@P@aXKnJGfkKhgYKtgqGCmkKhhC@BZBrAuQaIUmbAvnGEL4pkGuGkDaDyppDuJZQs0wgXHMg1xJktAHUMCgf6A6u/wA "J – Try It Online") *-1 byte thanks to Traws* Straightforward conversion of the algorithm into J. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~80~~ 71 bytes ``` ,>>,->+[<[-<+>>[->+>+<<]>[-<+>]<<]<[->+<]<[->+>+<<]>[-<+>]>>>>[-<<+>>]>+<<<]>>>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fx07Hzk472sYmWtdO2w5MaNvYxNoBmTY22nZ2sTZAEGsDl9ABM4EKgHJANbEQBXr//xsaAgA "brainfuck – Try It Online") Takes two byte values as input (step, initial), output a byte value. [Commented code](https://tio.run/##lVLLbtswEDyHXzFQDkwgy6mLnmxWh35B744OFEVHQiRRoKjYAYL@urukHlaKXCqAELmcmd2dZS778vpidYfEgB@zo0g32zjJOIQA1@bE8eEskgL8ueVIIbf56boBcA@rZYHe6Y6lm@VctZVjaRrTubOmGJT7uWPHgD@XVa3n6J4xIca4K6setTEdmqF2VVdXup9hyN@D5AGtOaMzVeu0BeGlG1MllMqL9EPurFRj1LN2BzTmTYNOzoQoZ3fpkfBpLESGwJJFsWQi1LTlE/WLG69BIkLEaZqRRaSxhnKOXKrXFYPdedTt8za5wbb90sxUHcsYu/dd7r9o87DUQjFXapj6VvibrAeNh2boqXENVWtpdYFaksYjW@bAPbfV5888GsPKk6kbP1Rfl/9zPPhkvorHTTBsvh09DXSRpWNzga7M0AbXwoazeN1/1SqrG02AcEtvhfwc6TPfNzh78I@dHLItxhYXh2kOQmyv9FhZZ4l1QvTr3U1l7BEdcFZIFER4vEyr0iD6bc2LlQ2cvrh9NAX/@C9iilxfoJ@v5gTPl287vyJ8wFWNNoPDrseT6dxTbmXVngb1etsFOYJeLsVa4get7/8vcf0L) (Memory layout: `count step init init' prod prod' prod''`) This language has a slight advantage for this challenge because its cell size value (in the TIO implementation) is 8-bit. This program has to use ~5 variables, so some other rearrangement might produce a shorter program. Use a scrolling tape to reduce back-and-forth copying. (after each iteration of the outermost loop the pointer is moved 1 unit to the right) [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~27~~ ~~25~~ ~~19~~ 18 bytes -2 bytes thanks to Traws! -6 bytes thanks to ngn and Traws! -1 more byte thanks to ngn! ``` {#(`c$*/)(x,y+)/x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlpZIyFZRUtfU6NCp1JbU7@i9n9atKG1gmEsV1q0kbWCCYg2tlYwhfLNQLQ5lG8CVWdoYK1gCVZgagZi/QcA "K (ngn/k) – Try It Online") [Answer] # [Factor](https://factorcode.org/), 105 bytes ``` : f ( n n -- n ) swap 1array [ dup product 256 mod 0 = ] [ 2dup last + 1array append ] until length nip ; ``` [Try it online!](https://tio.run/##LU5BCsIwELznFXNUpGJrVax4Fi@9iBfFQ2xXLcY0Jlukr49pKAs7s8zuzD5kxa3159OxPBSQ1sre4U1Wk8JH8guOvh3pihyMJebe2EYzduJYFriQbRN@UXLvmXyBBybQoZIktCncTxqk0VNcUXcmWLR1VzGy1RqftsYCe9yClg2iko4xGw8gjSFd44ZOc6OEIv0M3@jGYOdTpCFrLjLkEZdYjfM64mac83EvXWA7EIghOFL/Bw "Factor – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 19 bytes ``` {0⍳⍨256|×\⍵+⍺×0,⍳9} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGqDR72bH/WuMDI1qzk8PeZR71btR727Dk830AGKW9b@/2@okKZgyGUCJI0UuEyBlLEClxmCZ84FUmCiwGUJUmcAoYGGKQAA "APL (Dyalog Classic) – Try It Online") Uses `⎕IO←1` and the fact that the highest possible output is `10`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 70 bytes ``` \d+ $* ^ 1, {`^1.* $&# \G1(?=1*,(1+)) $1 1{256} }`1,(1+(,1+)) 1$2$1 # ``` [Try it online!](https://tio.run/##HYu9CoMwFEb37zUSJcaL@KX@4FAc8xIiEezQpYO4ic@e3nY6cA7neJ3vz5YLF1Ne9hrWYwUFV1rZeNjSYIl085NeHOuqgiV4hX64gTvxJ538A23QZnKmEEE6PKRXDhiVnTq2MkFPmb4 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` ^ 1, ``` Insert an accumulator. ``` ^1.* $&# ``` Increment the result if the accumulator is not zero. ``` \G1(?=1*,(1+)) $1 ``` Multiply the accumulator by the current term. ``` 1{256} ``` Reduce modulo 256. ``` 1,(1+(,1+)) 1$2$1 ``` If the accumulator is not zero then calculate the next term. (The conditional is necessary in order for the loop to terminate once the accumulator reaches zero.) ``` {` }` ``` Repeat the loop until the buffer stops changing. This will happen when the accumulator becomes zero, i.e. the product is a multiple of 256. ``` # ``` Convert the result to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` ⊞υNNηW﹪ΠEυΣ…υ⊕λ²⁵⁶⊞υηILυ ``` [Try it online!](https://tio.run/##TU27CgIxEOz9ipQbOBvlbK5MJXgS8AtibjEHeZHbVfz6mCCC0wzDvKwzxSbja9W8OeBBnGNmunK4YwEpp92/dk2/3OpRwJwW9gl0aWwJZpN7@cYB1Nt6VC7l75otGDASLuBlxyAO40lK8fvrm7qskUCZjeCC8UHNaMmp1qMY6/7pPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υN ``` Input the initial number and push it to the predefined empty list. ``` Nη ``` Input the step. ``` W﹪ΠEυΣ…υ⊕λ²⁵⁶ ``` Repeat while the product of the sums of all the nontrivial prefixes of the list is not a multiple of 256... ``` ⊞υη ``` ... push the step to the list. ``` ILυ ``` Output the length of the list. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes ``` ≜;.{|⟨+≡t⟩ⁱ}ᶠ⁽hᵐ×%₂₅₆0∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/eobcOjpqaHuzprH26d8P9R5xxrveqaR/NXaD/qXFjyaP7KR40bax9uW/CocW8GUMHh6apA1Y@aWh81tRk86lj@/3@0QrShjmGsTrSRjgmQNNYxBbPNgKQ5mG0CljU00LEESZiaAWmFWAA "Brachylog – Try It Online") This took embarrassingly long to write, but at least I was able to shave two bytes off `∧.≜&{|⟨+≡t⟩ⁱ}ᶠ↖.hᵐ×%₂₅₆0∧` once I got that far. Takes `[first term, step]` through the output variable and outputs the prefix length through the input variable. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1µ⁴ẋ³1¦ÄP256ḍµ1# ``` A full program accepting the initial value and the delta which prints the result. **[Try it online!](https://tio.run/##ASgA1/9qZWxsef//McK14oG04bqLwrMxwqbDhFAyNTbhuI3CtTEj////M/81 "Jelly – Try It Online")** ### How? ``` 1µ⁴ẋ³1¦ÄP256ḍµ1# - Main Link: initial, delta 1 - set the left value (say n) to 1 1# - increment n finding the first 1 such n which is truthy under: µ µ - the monadic chain - i.e. f(n): ⁴ - program argument 4 (delta) ẋ - repeated (n) times ¦ - sparse application... 1 - ...to indices: 1 ³ - ...what: program argument 3 (initial) Ä - cumulative sums P - product 256 - literal 256 ḍ - divides (the product)? - implicit print (a list with a single element prints that element) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~46~~ 44 bytes Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` c;f(a,d){c=0;for(char p=1;p*=a+d*c++;);d=c;} ``` [Try it online!](https://tio.run/##fZDbaoQwEIbv9ykGQYgaqYdqK2l6U/oU61JColuhdcUIlYqvXjvGQ5e9aCCZTPi/f2Yi/bOU0yRZSQRVziB5wMpLS@S7aKHhIWtcLjzlSs9jDlNcsnH6FFVNHBgOgKuqO@gK3ek3cTwBhyGkABGFeAkPFO4phAGFKElHdoOoPwRVCYbUBHzIMMmugKJvCtmh3gDo97jYojo1aqwE4QrM3bvQLu5W3r9GeZ@94E4sCtd5bCFhEBwayFyoqlXRIxew9foEuvouLiVZx3Tu1hzVDgPPM7LtP7Z@NVrsyNFITnQfe8kdtiNNi1BJLDtWFGwF/vN82jqvLfq/CQVNcdT1f5Y34Bz0Zj8eDuP0I8sPcdaT//UL "C (gcc) – Try It Online") **Commented code** ``` c;f(a,d){ c=0; /* initialise counter */ for(char p=1 /* initialise 8-bit product */ p /* loop until last 8-bits of product are 0 */ *=a+d* /* and multiply product by next element in series */ c++;); /* and bump counter */ d=c; /* return counter */ } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes ``` (t=0;s=#;k=#2;While[Mod[s##&@@Array[s+k#&,t++],256]!=0];t)& ``` [Try it online!](https://tio.run/##HYlBC8IgGEB/SwhS@EFqcyNEsB8QdOsgHqTGJmsF6iVkv93My3sP3urSPK4u@Ycrkyr7pKiMCslFIS7vs3@N5vp5mogQ1voSgvuaSBaEIRFigYve7hS1Mh1wuQX/Tkc9aa1zZsA2yBy6yhOI1n3l0Lprl1E4/4foq7dSfg "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org/), 43 bytes ``` function(i,s)match(0,cumprod(i+0:9*s)%%256) ``` [Try it online!](https://tio.run/##XYzNCoQgFEb3PUUwBDrdhbfSMuhhwhpGSI1@nt8Qs0XLc/i@s3mj7TLbwf9Oqw7tLNGwUzMe6k8YqNOsm5uILlkvvzstiooLen8IAtL8kyPLblFBE0SXuAb@HoggeOI2DkTiJhZlYmQgg2ifABfRYOYv "R – Try It Online") Outputs 'NA' if sequence goes to infinity without ever being a multiple of 256. Calculates products of sequences up to length 10. Why is this enough? If step is an odd number, then the successive factors that make up each element of the sequence will alternate between odd and even, so 10 would be enough to ensure that there are 5 even numbers multiplied together (so the product is a multiple of 2^5). But, the first 5 even numbers are also certain to include at least one multiple-of-4 (every second even number) and one multiple-of-8 (every fourth even number), so in fact their product is certain to be a multiple of 2^8 = 256. If the step is even and the initial number is even, then (for similar reasons) only a maximum of 4 steps are needed. If the step is even and the initial number is odd, then all the factors will be odd, so the product will always be odd and the sequence will go to infinity without ever being a multiple of 256. So, if we didn't find a multiple-of-256 by the 10th element of the sequence, there won't be one, and we can just output the 'infinity' response. I think. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞<*+ηPÅΔ₁Ö}> ``` Takes the inputs in reversed order, so `step` before `start`. [Try it online](https://tio.run/##yy9OTMpM/f//Ucc8Gy3tc9sDDreem/KoqfHwtFq7//9NuIwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/0cd82y0tM9tDzjcem7Ko6bGw9Nq7f7r/I@ONtQxjNWJNtIxAZLGOqZgthmQNAezTcCyhgY6liAJUzMgHQsA). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] < # Decrease each by 1 to let it start at 0: [0,1,2,...] * # Multiply each by the first (implicit) input (step) + # Add the second (implicit) input (start) η # Get all prefixes of this infinite list P # Take the product of each inner prefix-list ÅΔ # Find the first (0-based) index which is truthy for: ₁Ö # Where the value is divisible by 256 }> # After we've found this index: increase it by 1 to make it 1-based # (after which the result is output implicitly) ``` [Answer] # [Rust](https://www.rust-lang.org/), 58 bytes ``` |s,m|(|mut i,mut a|{while 0<a%256{a*=i;i+=m}(i-s)/m})(s,1) ``` [Try it online!](https://tio.run/##hc5NCoMwEAXgfU/xKhSSdkRjNWqtvYsLpQETij90ET27VQRXgW5mFt@8menGflgaA10pwzjsCWjrAc0DjWGjjAlr4fBfW0e5TD3piU16HKBoq9Vkv2/V1gif1SVKpK2upSrUrdQzU37PAz1z1pPgS7Hu/nTKDK05M8/OHqFhgiA4LxAEInR5RMh2z1x8JyR/4nL3xMXpEZcujo/ncufvISHfPXUeT@QxIE7z8gM "Rust – Try It Online") A closure whose first argument is the first element of the sequence and whose second argument is the step. Ungolfed with comments ``` //Initial element, step |s,m| //i is initial value of s, a is accumulator (|mut i,mut a| { while 0 < a % 256 { //while a is not divisible by 2^8 a *= s; //Multiply a by the current element of the sequence s += m //Get the next element of the sequence by adding the step } //Subtract the initial value s to only keep increases of m, divide by m to get how many times it was increased (i - s) / m ) (s, 1) //Call with i as s and initial value of accumulator as 1 ``` [Answer] # Scala, 54 bytes ``` LazyList.from(_,_).scanLeft(1)(_*_)indexWhere(_%256<1) ``` [Try it in Scastie!](https://scastie.scala-lang.org/JvvccbCcSsyfoX5prS7ZNQ) Explanation: ``` LazyList.from(_,_) //Creates a LazyList starting at the first parameter with a step given by the second parameter. .scanLeft(1)(_*_) //scanLeft is like foldLeft, but keeps each result in a list indexWhere(_%256<1) //Find the index where it's divisible by 256 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~51~~ 49 bytes ``` b#s=findIndex((<1).(`mod`256))$scanl(*)1[b,b+s..] ``` [Try it online!](https://tio.run/##LYpBC4IwGED/ygd6@FZrNEsjyE5dAm8dTXA2xZGb4r6of28Znt578Frln3XXTcYO/UhwUaREZjxNVeDTxjh9dbr@IJ4kE1jaXpdRnDAW@odyHa6YzCterb0QxWSVcenwohuNmQt9279DqwbAO8HmDNh4AmIQAHqnf8YgR8lBMg4YcdjP3HGIl05mHpbeL5/ccjj@hziZrZi@ "Haskell – Try It Online") Port of my [Scala answer](https://codegolf.stackexchange.com/a/210146/95792) ]
[Question] [ Consider the following sequence: ``` 0 1 3 2 5 4 8 6 7 12 9 10 11 17 13 14 15 16 23 ... ``` Looks pretty pattern-less, right? Here's how it works. Starting with `0`, jump up `n` integers, with `n` starting at `1`. That's the next number in the sequence. Then, append any numbers "skipped" and that haven't been seen yet in ascending order. Then, increment `n` and jump from the last number appended. Repeat this pattern. So, for example, when we reach `11`, we're at `n=5`. We increment `n` to be `n=6`, jump up to `17`, then append `13 14 15 16` since those haven't been seen yet. Our next jump is `n=7`, so the next element in the sequence is `23`. ### The Challenge Given input `x`, output the `x`th term of this sequence, the first `x` terms of the sequence, or build an infinite list of the terms of the sequence. You can choose 0- or 1-indexing. ## I/O and Rules * The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * The input and output can be assumed to fit in your language's native number type. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # JavaScript (ES7), 41 bytes Returns the **n-th** term of the sequence, 0-indexed. ``` n=>(d=(n--*8-23)**.5)%1?n:'121'[n]^n-~d/2 ``` [Try it online!](https://tio.run/##FYtBCsIwEADvfcUSkO4mpDaRQrFGHyIKoWlEKRtpxYvo12N7m4GZh3/7uZ/uz5fmFIYcXWZ3xOCQtZattjuSsmpoY068L4015ZkvV9a/sLU5pgkZHNQdMBzA1CsoRfApAPrEcxqHakw3FB4FqCVSIGgZVonIRF3xzX8 "JavaScript (Node.js) – Try It Online") ## How? ### Main case: \$n > 3\$ The first four terms of the sequence are special, so let's put them aside for now. For \$n > 3\$, the sequence looks like that: ``` n | [4] 5 [6] 7 8 [ 9] 10 11 12 [13] 14 15 16 17 [18] 19 20 21 22 23 [24] 25 26 27 ... ----+------------------------------------------------------------------------------------ a(n)| [5] 4 [8] 6 7 [12] 9 10 11 [17] 13 14 15 16 [23] 18 19 20 21 22 [30] 24 25 26 ... ----+------------------------------------------------------------------------------------ k | 2 - 3 - - 4 - - - 5 - - - - 6 - - - - - 7 - - - ... ``` We can notice that there are in fact two interleaved sub-sequences: * Most values belong to the sub-sequence \$A\$ for which we simply have: $$A(n) = n - 1$$ * Some other values belong to the sub-sequence \$B\$ (highlighted with brackets in the above diagram) whose indices follow the arithmetic sequence **3, 3, 4, 6, 9, 13, 18, 24** ... and for which we have: $$B(n,k) = n + k - 1$$ where \$n\$ is the index in the main sequence and \$k\$ is the index in the sub-sequence \$B\$. The indices of \$B\$ in the main sequence are given by: $$n\_k = \frac{k^2 - k + 6}{2}$$ Given \$n\$, we know that the corresponding term in the main sequence belongs to \$B\$ if \$n\$ is an integer solution of the quadratic equation: $$x^2 - x + 6 - 2n = 0$$ whose discriminant is: $$\Delta = 1 - 4(6 - 2n) = 8n - 23$$ and whose positive solution is: $$x = \frac{1 + \sqrt{\Delta}}{2}$$ We expect \$\sqrt{\Delta}\$ to be an integer. Hence the test: ``` (d = (n-- * 8 - 23) ** .5) % 1 ``` ### Special cases: \$0 \le n \le 3\$ For \$n < 3\$, the discriminant is negative and taking its square root results in **NaN**. For \$n = 3\$, the discriminant is \$1\$. Therefore, these first four terms of the sequence are considered to belong to the sub-sequence \$B\$. Should we just apply our standard formula **n - ~d / 2**, we'd get: $$-\frac 1 2, \frac 1 2, \frac 3 2, 3$$ instead of: $$0, 1, 3, 2$$ Which is why we XOR these results with \$0,1,2\text{ and }1\$ respectively. [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` Θṁṙ_1C+ḣ2tNN ``` [Try it online!](https://tio.run/##yygtzv7//9yMhzsbH@6cGW/orP1wx2KjEj@///8B "Husk – Try It Online") Outputs as an infinite list. [Here](https://tio.run/##ASEA3v9odXNr///ihpHOmOG5geG5mV8xQyvhuKMydE5O////MjA) is a version that prints the first **N**. ### Explanation ``` Θṁṙ_1C+ḣ2tNN – Full program. Takes no input, outputs to STDOUT. tN – Construct the infinite list of natural numbers, starting from 2. +ḣ2 – And append [1, 2] to it. Yields [1,2,2,3,4,5,6,7,8,9,10,11,...]. C N – Cut the infinite list of positive integers into pieces of those sizes. Yields [[1],[2,3],[4,5],[6,7,8],[9,10,11,12],...]. ṁ – Map and flatten the results thereafter. ṙ_1 – Rotate each to the right by 1 unit. Yields [1,3,2,5,4,8,6,7,12,9,10,11,...] Θ – Prepend a 0. Yields [0,1,3,2,5,4,8,6,7,12,9,10,11,...] ``` [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` 0:1:3:2:5!3 a!n=a:[a-n+2..a-1]++(a+n)!(n+1) ``` [Try it online!](https://tio.run/##BcFBCoMwEAXQfU8x2SUMkURxM5CTtF18xKoYh9B4/k7f29HPtVbr5WVJskwyyuymB5wWyBNReRwGxPxm9mANzivnYBcOpULte@hN/sa5Uk6JerDf8qnYusWltT8 "Haskell – Try It Online") Defines an infinite list: ``` 0:1:3:2:(5!3) ≡ 0:1:3:2:5:4:(8!4) ≡ 0:1:3:2:5:4:8:6:7:(12!5) ≡ 0:1:3:2:5:4:8:6:7:12:9:10:11:(17!6) ≡ 0:1:3:2:5:4:8:6:7:12:9:10:11:17:13:14:15:16:(23!7) … ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` +‘ɼṪRṙ-œ|@ 0Ç¡ḣ ``` This is a full program that, given **n**, prints the first **n** items of the sequence. [Try it online!](https://tio.run/##AScA2P9qZWxsef//K@KAmMm84bmqUuG5mS3Fk3xACjDDh8Kh4bij////MTk "Jelly – Try It Online") ### How it works ``` 0Ç¡ḣ Main link. Argument: n 0 Set the return value to 0. Ç¡ Call the helper link n times, first with argument 0, then n-1 times with the previous return value as argument. ḣ Head; extract the first n items of the last return value. +‘ɼṪRṙ-œ|@ Helper link. Argument: A (array) ‘ɼ Increment the value in the register (initially 0) and yield it. + Add that value to all items in the sequence. Ṫ Tail; extract the last item. R Range; map k to [1, .., k]. ṙ- Rotate -1 units to the left, yielding [k, 1, ..., k-1]. œ|@ Perform multiset union of A and the previous return value. ``` [Answer] ## C (gcc), ~~73~~ ~~67~~ 64 bytes ``` t,d;f(x){for(t=4,d=2;d<x;t+=d++)x-t||(d+=x+=d);t=x<4?x^x/2:x-1;} ``` [Try it online!](https://tio.run/##DYzLCsIwEEX3/YqhImRI66N05ST6IyJIxmigplIjDLT99pizORwuXNc@ncubEN3w4weYb@Iw7l7nnBomrwRnP04q2b5h2xEboaQta43SpmVRrK2URkpWTH@Rm@y7k7RHWvP7HqJCmCsolBNQISYIYOFARQa6Yq0Dwmcqi1f1lq@xbsCrgEjVmv8) Defines a function `f` that takes 0-indexed `n` and produces the `n`th number in the sequence. We can analyze the sequence as follows: ``` f(n) = n where n = 0, 1 f(2) = 3 // 2 and 3 are swapped f(3) = 2 f(4) = 5 // (+2,+3) f(6) = 8 // (+3,+4) f(9) = 12 // (+4,+5) f(13) = 17 // (...) ... f(n) = n-1 // for all cases not yet covered ``` First we handle the middle section: ``` for(t=4,d=2;d<x;t+=d++)x-t||(d+=x+=d); ``` Note that the arguments on the left (4, 6, 9, 13, ...) follow a pattern: first add two, then add three, then add four, and so on. We start at `t=4` and add `d` (which starts at 2) each iteration of the loop, incrementing `d` in the process. The body of the loop is more interesting. Remember that we want to map 4 to 5, 6 to 8, 9 to 12, etc.; that's just adding `d-1` if `x` is `t`. However, this logic comes before the last case, `f(n) = n - 1`, so we know we're going to subtract 1 at the end. Therefore, we can simply add `d` if `x == t` (`x-t||(x+=d)`). However, we will also need to break out of the loop immediately after this -- so we add *that* to `d` to get the absurd-looking `d+=x+=d`, which will always make the `d<x` condition fail. This covers everything except for the first four values. Looking at them in binary, we get: ``` 00 -> 00 01 -> 01 10 -> 11 11 -> 10 ``` So, we want to flip the last bit if `2 <= x < 4`. This is accomplished with `x^x/2`. `x/2` gives the second least significant bit, so XORing this with the original number flips the last bit if the number is 2 or 3. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 10 [bytes](https://github.com/DennisMitchell/jelly) -3 Thanks to Dennis (use 0-indexing to save 2 from cumulative sum setup and a final decrement) ``` Ḷ»2Äi+_>2$ ``` A monadic link accepting an integer, **0**-indexed **n**, which returns an integer, **a(n)** **[Try it online!](https://tio.run/##y0rNyan8///hjm2HdhsdbsnUjrczUvn//78lAA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8///hjm2HdhsdbsnUjrczUgFxD7c/alrz/7@ZKQA "Jelly – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/) with `-pl`, 70 bytes ``` $"="|";push@f,$;=$f[-1]+$-++,grep!/^(@f|$;)$/,0..$;for 0..$_;$_=$f[$_] ``` [Try it online!](https://tio.run/##FcpLDoIwFEbh@b8Kbe4A0ha4vE3ThH0YZETVhNgGdMbarTI7@XLCvC5NJG0HZ5PURBJW7MKEz/YYnCJjyV01j5K0lOq@zuGc35LB7WRSylWRZWScX09HTIamY6dpjLEAo0SFGg1adOhxAf@RwSW4AtfgBtyCO3D/9eH99K8t6rD8AA "Perl 5 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 22 bytes ``` 1y:"t0)@+h5M:yX-h]qw:) ``` Outputs the first `n` terms of the sequence. [Try it online!](https://tio.run/##y00syfn/37DSSqnEQNNBO8PU16oyQjcjtrDcShMobgkA "MATL – Try It Online") ### Explanation ``` 1 % Push 1 y % Implicit input: n. Duplicate from below ": % For each k in [1 2 ... n] t0) % Duplicate sequence so far. Get last entry, say m @+ % Add k: gives m+k h % Concatenate horizontally 5M % Push m+k again : % Range [1 2 ... m+k] y % Duplicate from below X- % Set difference h % Concatenate horizontally ] % End q % Subtract 1, element-wise w % Swap. Brings original copy of n to the top :) % Keep the first n entries. Implicit display ``` [Answer] # [Haskell](https://www.haskell.org/), 51 bytes ``` 0:1:do(a,b)<-zip=<<(1:)$scanl(+)3[2..];b:[a+1..b-1] ``` [Try it online!](https://tio.run/##BcFBEsIgDADAr@TQA0yFIXpDeEnbQ8BWmSIypqc@3rj7It7XWoXjLM6jf3wUXZIO5iw9hqDQ64EztapGfZuu1i735Cca0dpkcJE3lQYR@re0A9RB@wroHLCWX94qPVlM7v0P "Haskell – Try It Online") Quite a bit longer than [Lynn's Haskell answer](https://codegolf.stackexchange.com/a/167325/56433), but the different approach might be interesting non the less. [Answer] # [Ruby](https://www.ruby-lang.org/), 73 bytes ``` f=->x,l,n{!l[x]&&(i=l[-1];f[x,l+[i+n]+([*(i+1...i+n)]-l),n+1])||l[0...x]} ``` [Try it online!](https://tio.run/##DchBCoAgEADAr9QltF1Fo1vYR5a9dBCERSIIjOzt5nHmuo@ntRjMXlAwv6NQ4WlSKQgZz1uk/kAJMoOiWSXw1tpOzUY0ZvCsaxVyfQt/7RwiLSuSY/Tcfg "Ruby – Try It Online") Recursive function that returns the first x numbers of the list. [Answer] # QBasic, 58 bytes ``` DO b=r+j ?b r=b FOR x=a+1TO b-1 ?x r=x NEXT a=b j=j+1 LOOP ``` Outputs indefinitely. You may want to add a `SLEEP 1` inside the loop or make it `LOOP WHILE b<100` or something like that in order to see the results. This basically just implements the spec. Observe that the numbers we go back for will always be the numbers between the most recently jumped-to number and the jumped-to number prior to that. So we store these bounds as `a` and `b` and use a `FOR` loop to print all the numbers between them. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` 0)sƒ¤N+LÁ«}Ùs£ ``` [Try it online!](https://tio.run/##ASAA3/8wNWFiMWX//zApc8aSwqROK0zDgcKrfcOZc8Kj//8yMA "05AB1E – Try It Online") [Answer] # [R](https://www.r-project.org/), 70 bytes ``` function(e){for(i in 1:e)F=c(setdiff((F+i):1-1,F),F[1]+i,F);rev(F)[e]} ``` [Try it online!](https://tio.run/##TcsxDsIwDADAPa/wZls1Q5BYirLmE6VDFWLkJUVJgaHq2wMj2y1Xu4aur5I2Wwtl3nWtZGAF/Jg5hkQtb3dTJYqD8ehPXiJLnPw82E/Xmt8Uecrz0f/q@cK7A0jLRqiEYoIMAVCUjAVvBaXlZ0Bkd7jPUouVRyPuXw "R – Try It Online") * 1-indexed * -4 bytes using `F` constant thanks to @JAD suggestion * -5 bytes reversing the list thanks to @Giuseppe suggestion * -2 bytes removing useless braces in for loop thanks to @JAD suggestion * -2 bytes using `setdiff` instead of `x[x %in% y]` --- [Previous version (79 bytes)](https://tio.run/##TcyxCsMgEIDhPU9hh3B39AKxY1JXXyLNIKJwUIykdgo@u3Xs9v3Lf7ZoWvwmX@RIGOiKx4miJCm99MqmOHmjZU2rNb4j34XRPad5wc5JE203N0oa7U51tVvYa/t7PGa6BqW8KwgRgYWBlFHAEYUYXgn4E7IBoKG2Hw) [Answer] # [Python 2](https://docs.python.org/2/), 123 bytes ``` def f(z):[s.extend([s[-1]+n]+[x for x in range(s[-1]+1,s[-1]+n)if not x in s]) for n in range(1,z)if len(s)<z];return s ``` [Try it online!](https://tio.run/##Rc3LCsIwEIXhV5llQqs4Lr08SchC6EQDMikzEdK8fIxtwbP9Pzjzkl@Jz03hDu7k20QBgqn24vRIJRNPxqk7oB/YD65ASAIFIoM8@ElmSzjuxMYAnPIm1NuV85/jWH/kTWzU3qq/CuWPdAp9bZbIub8j2vYF "Python 2 – Try It Online") Given input x, output the first x terms of the sequence, I'm learning Python and this challenges make things more interesting. Edit: shave some whitespace [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` RÄṬŻk²Ḋ$ṙ€-Ø.;Fḣ ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//UsOE4bmsxbtrwrLhuIok4bmZ4oKsLcOYLjtG4bij////Ng "Jelly – Try It Online") One byte longer than the existing Jelly answer but this could possibly be golfed a little. `RÄṬŻk²Ḋ$` could maybe be shorter. [**18 bytes**](https://tio.run/##ATMAzP9qZWxsef//UsOE4bmsxbtrwrLhuIok4oCY4bmZ4oKsMUbFu8W74buk4oCZ4bij////MTA "Jelly – Try It Online") ``` RÄṬŻk²Ḋ$‘ṙ€1FŻŻỤ’ḣ ``` Longer but different. [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->x,n=0{n+=1while 0>d=n*n+n<=>2*x-6;[0,1,3,2][x]||[x+n,x-1][d]} ``` [Try it online!](https://tio.run/##BcFLCsIwEADQq4S60ebDJIIbnVwkzEJtSwMylKI4kuTs8b398/j1BbuNYhihsEb/XfNrVhAn5JE13zCGUezlmsB4czaBklCtSTQbsZ7SRK0fwbkAJzffn6sqNVe17ZnfajiUJWVqamj9Dw "Ruby – Try It Online") 0-indexed. Can probably be golfed down. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 52 bytes ``` (0,{((^max @_)∖@_).min.?key//(1+@_[*-1]+$++)}...*) ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoFKcWmj7X8NAp1pDIy43sULBIV7zUcc0IKmXm5mnZ5@dWqmvr2Go7RAfraVrGKutoq2tWaunp6el@d@aqzgRYkB0nJFB7H8A "Perl 6 – Try It Online") This is a generator expression using the `...` operator. It looks for gaps in the prior sequence `@_` via `((^max @_)∖@_).min.?key`: ``` @_ # prior sequence values [0,1,3] max @_ # largest prior sequence value 3 ^ # the Range 0..max @_ 0,1,2 ( )∖@_ # set subtract prior seq -0,1 -> (2=>True) .min # smallest unseen value 2=>True .?key # set yields pairs 2 ``` The `?` is necessary for the initial value which doesn't have a `.key`. If no gaps are found, then it adds n (here in the `$` variable) to the last value in the list, plus one for off by 0 errors. [Answer] # [Python 3](https://docs.python.org/3/), 104 bytes ``` def f(x): n=a=0 l=list(range(x*x)) while n<x:print(l[a+n],*l[a+2-(n<3):a+n],end=' ');a=a+n-(a>0);n+=1 ``` [Try it online!](https://tio.run/##HchBCoMwEEDRfU4xO2e0gqm76PQixcWASQ2EqdhA09OntavP@/snb08da119gICFnAFl4cFA4hRfGQ/Rh8fSFiID7y0mDzoXtx9RM6a7dLpc2rPXHnUeyf2P15UbaGgS/rlHuQ00ace2BrSW6hc "Python 3 – Try It Online") Given input x, output the first x "sequences" ]
[Question] [ The program should take input the number, the start of the range and the end of the range, and output how many integers the number appears between the start and end of the range, **inclusive**. Both programs and functions are allowed. ## Example Inputs For example: ``` //Input example 1 3,1,100 //Input example 2 3 1 100 //Input example 3 3 1 100 //Input example 4 a(3, 1, 100); ``` All the above four input examples are valid and all of them mean that `3` is the number in question, `1` is the beginning of the range and `100` the the end of the range. And then the program should output how many times `3` appears in the range from `1` to `100` **inclusive**. `3` appears in the integers `3`, `13`, `23`, `30`, `31`, `32`, `33`, ..., `93` at a total of 19 times. So the program should output `19` as the output because that is how many times `3` appears in the range from `1` to `100`. ## Rules * Both programs and functions are allowed. * All numbers will be integers, meaning that there will **not** be any `float`s or `double`s. * Note: the sought number will always be in the range `0≤x≤127`. There will be **no** cases where it will be outside this `0≤x≤127` range. * As in the first example, with the case as `33`, the number `3` will be counted as appearing only **once**, **not** twice. * The values of the start and end of the range will be between `-65536` and `65535` inclusive. * The value of range's start will never exceed or equal to range's end. `start < end` * Also the range is inclusive. For example if the input was `8 8 10`, the range would be `8≤x≤10` and hence the output will be 1. * Input can be taken in any of the ways shown in the examples. Input can be taken as a string or as a number, any way you wish. ## Test Cases ``` 3 1 100 19 3 3 93 19 12,-200,200 24 //This is because 12 appears in -129, -128, ..., -112, -12, 12, 112, 120, 121, 122, ... 123,1,3 0 //This is because all of 123's digits have to appear in the same order 3 33 34 2 //Because 3 appears in 2 numbers: 33 and 34 a(0,-1,1); 1 $ java NotVerbose 127 -12 27 0 ``` # Snack Snippet To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 98470; // 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 = 41805; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Bash, 20 bytes the obvious answer ``` seq $2 $3|grep -c $1 ``` example ``` $ bash golf 3 1 100 19 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes Input in the form: **upper bound**, **lower bound**, **number**. ``` Ÿvy³åO ``` Explanation: ``` Ÿ # Inclusive range, [a, ..., b] vy # For each element... ³å # Check if the third input is a substring of the number O # Sum up the results ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=xbh2ecKzw6VP&input=MjAwCi0yMDAKMTI) [Answer] ## Perl, 20 bytes *Saved 2 bytes by using `grep` as in @ardnew's [answer](https://codegolf.stackexchange.com/a/98490/55508).* Bytecount includes 18 bytes of code and `-ap` flags. ``` $_=grep/@F/,<>..<> ``` Give the 3 numbers on three separate lines : ``` perl -ape '$_=grep/@F/,<>..<>' <<< "3 1 100" ``` [Answer] # Python 2, ~~47~~ 43 Bytes Relatively straightforward, making use of Python 2's `repr` short-form. ``` f=lambda n,a,b:a<b and(`n`in`a`)+f(n,-~a,b) ``` Ouput: ``` f( 3, 1, 100) -> 19 f( 3, 3, 93) -> 19 f( 12, -200, 200) -> 24 f(123, 1, 3) -> 0 f( 3, 33, 34) -> 2 f( 0, -1, 1) -> 1 f(127, 12, 27) -> 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)! (Use `w` and filtering to avoiding `@`.) ``` rAwƇ⁵L ``` **[TryItOnline!](https://tio.run/##y0rNyan8/7/IsfxY@6PGrT7////XNTIw@A/ChkYA "Jelly – Try It Online")** Input: Start, End, ToFind ### How? ``` rAwƇ⁵L - Main link: Start, End, ToFind r - range: [Start, ..., End] A - absolute values ⁵ - third input: ToFind Ƈ - filter keep those (absolute values, a) for which: w - first index of sublist (implicit digits of ToFind) in (implicit digits of a) L - length ``` The default casting of an integer to an iterable for the sublist existence check casts to a decimal list (not a character list), so negative numbers have a leading negative value (e.g. `-122`->`[-1,2,2]` which won't find a sublist of `[1,2]`) so taking the absolute value first seems like the golfiest solution. [Answer] ## JavaScript (ES6), ~~46~~ 45 bytes ``` f=(n,s,e)=>s<=e&&!!`${s++}`.match(n)+f(n,s,e) ``` (My best nonrecursive version was 61 bytes.) Edit: Saved 1 byte thanks to @edc65. [Answer] ## PowerShell v2+, ~~64~~ ~~62~~ 56 bytes ``` param($c,$a,$b)$(for(;$a-le$b){1|?{$a++-match$c}}).count ``` *-6 bytes thanks to mazzy* Input via command-line arguments of the form **number lower\_bound upper\_bound**. A little goofy on the notation, because of the semicolons inside the `for` causing parse errors if it's not surrounded in `$(...)` to create a script block. We basically loop upward through `$a` until we hit `$b`, using `Where-Object` (the `|?{...}`) to pull out those numbers that regex `-match` against `$c`. That's encapsulated in parens, we take the `.count` thereof, and that's left on the pipeline and output is implicit. --- If, however, we guarantee that the range will be no more than 50,000 elements, we can skip the loop and just use the range operator `..` directly, for **~~45~~ 43 bytes**. Since that's not in the challenge specifications, though, this isn't valid. Bummer. ``` param($c,$a,$b)($a..$b|?{$_-match$c}).count ``` [Answer] # Vim, ~~46~~, 41 bytes ``` C<C-r>=r<tab><C-r>")<cr><esc>jC0<esc>:g/<C-r>"/norm G<C-v><C-a> kd{ ``` Input is in this format: ``` 1, 100 3 ``` [Answer] ## Haskell, 65 bytes ``` import Data.List (s#e)i=sum[1|x<-[s..e],isInfixOf(show i)$show x] ``` The `import` ruins the score. Usage example: `((-200)#200)12` -> `24`. [Answer] # Java 7 85 bytes ``` int x(int a,int b,int c){int t=0;for(;b<=c;)if((b+++"").contains(a+""))t++;return t;} ``` [Answer] # Swift 3, ~~96~~ 93 bytes ``` import Cocoa func c(n:Int,s:Int,e:Int){print((s...e).filter{"\($0)".contains("\(n)")}.count)} ``` **Edit 1:** Saved 3 bytes by using shorthand parameters [Answer] # Scala, 50 bytes ``` (c:String)=>(_:Int)to(_:Int)count(""+_ contains c) ``` takes the first input curried; call it like this: `f("12")(-200,200)` Explantion: ``` (c:String)=> //define an anonymous function taking a string parameter (_:Int) //create a range from an anonymous int parameter to //to (_:Int) //another anonymous int parameter count( //and count how many... ""+_ //elements converted to a string contains c //contain c ) ``` [Answer] # R, 32 bytes Quite straightforward: ``` function(a,b,c)sum(grepl(a,b:c)) ``` [Answer] # C#, 71 bytes Beat my Java answer thanks to lambdas ``` (t,l,u)=>{int d=0;for(;l<=u;)if((l+++"").Contains(t+""))d++;return d;}; ``` [Answer] # Ruby 44 bytes ``` m=->(n,s,f){(s..f).count{|x|x.to_s[/#{n}/]}} ``` Test Cases: ``` m.(3,1,100) #=> 19 m.(3,3,93) #=> 19 m.(12,-200,200) #=> 24 m.(123,1,3) #=> 0 m.(3,33,34) #=> 2 m.(0,-1,1) #=> 1 m.(127,-12,27) #=> 0 ``` [Answer] # PHP, 62 bytes Pretty straight forward approach: ``` <?=count(preg_grep('/'.($a=$argv)[1].'/',range($a[2],$a[3]))); ``` [Try it online](https://3v4l.org/3BBoO) [Answer] # C, ~~143~~ 135 bytes Thanks to @Kritixi Lithos for helping save 8 bytes Surely this can be done better, but its the best I've got for now. C doesn't handle strings very gracefully, so naturally it takes quite a few operations. ``` int C(int N,int l,int h){char b[99],n[99];int t=0,i=1;sprintf(n,"%d",N);for(;i<=h;i++){sprintf(b,"%d",i);if(strstr(b,n))++t;}return t;} ``` **Ungolfed + program** ``` #include <string.h> #include <stdlib.h> #include <stdio.h> int C(int N,int l,int h) { char b[99], n[99]; int t=0,i=1; sprintf(n,"%d",N); for(;i<=h;i++) { sprintf(b,"%d",i); if(strstr(b,n)) ++t; } return t; } int main() { printf("%d\n", C(3, 1, 100)); } ``` [Answer] # JavaScript, ~~46~~ 45 bytes ``` f=(i,s,e)=>s>e?0:RegExp(i).test(s)+f(i,++s,e) ``` Recursively count until start > end Edit: Switch to RegExp test to save a byte [Answer] # PHP, ~~68~~ 63 bytes ``` for($a=$argv;$a[2]<=$a[3];)$o+=strstr($a[2]++,$a[1])>'';echo$o; ``` use like: ``` php -r "for($a=$argv;$a[2]<=$a[3];)$o+=strstr($a[2]++,$a[1])>'';echo$o;" 3 1 100 ``` edit: 5 bytes saved thanks to Titus [Answer] # Powershell, 48 bytes According to the rule, the range can contain more than 50,000 elements. So we can't use the range operator `..` directly. Thanks [AdmBorkBork](https://codegolf.stackexchange.com/a/98478/80745). Straightforward: ``` param($c,$a,$b)for(;$a-le$b){$i+=$a++-match$c}$i ``` Test script: ``` $f = { param($c,$a,$b)for(;$a-le$b){$i+=$a++-match$c}$i } @( ,(19, 3,1,100) ,(19, 3,3,93) ,(24, 12,-200,200) ,(0, 123,1,3) ,(2, 3,33,34) ,(1, 0,-1,1) ,(0, 127,-12,27) ,(44175, 0,-65536,65535) ) | % { $e,$a = $_ $r = &$f @a "$($e-eq$r): $r" } ``` Output: ``` True: 19 True: 19 True: 24 True: 0 True: 2 True: 1 True: 0 True: 44175 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 8 bytes Takes the integer to be found as the last input value. ``` õV èÈsøW ``` [Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=9VYg6Mhz+Fc=&input=LTIwMCwyMDAsMTI=) --- ## Explanation ``` :Implicit input of integers U=start, V=end & W=number õV :Range [U,V] È :Map s : Convert to string øW : Contains W? è :Count truthy values ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 7 bytes ``` ÷ṡƛS?hc ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%C3%B7%E1%B9%A1%C6%9BS%3Fhc&inputs=%5B3%2C1%2C100%5D&header=&footer=) [Answer] # Java, ~~92~~ ~~89~~ 71 bytes Now with lambdas! ``` (t,l,u)->{int z=0;for(;l<=u;)if((l+++"").contains(t+""))z++;return z;}; ``` Old 89 byte function solution: ``` int d(int t,int l,int u){int a=0,i=l;for(;i<=u;)if((i+++"").contains(t+""))a++;return a;} ``` Hooray for the super increment function! [Answer] # Groovy, 48 bytes ``` {a,b,c->(a..b).collect{"$it".count("$c")}.sum()} ``` [Answer] ## Racket 91 bytes ``` (for/sum((i(range s(+ 1 e))))(if(string-contains?(number->string i)(number->string d))1 0)) ``` Ungolfed: ``` (define(f d s e) (for/sum ((i (range s (+ 1 e)))) (if(string-contains? (number->string i) (number->string d)) 1 0 ))) ``` Testing: ``` (f 3 1 100) (f 3 3 93) (f 12 -200 200) (f 123 1 3) (f 3 33 34) (f 0 -1 1) ``` Output: ``` 19 19 24 0 2 1 ``` [Answer] # Axiom bytes 90 ``` f(y,a,b)==(c:=0;for x in a..b repeat(if position(y::String,x::String,1)~=0 then c:=c+1);c) ``` results ``` (3) -> f(3,1,100)=19,f(3,3,93)=19,f(12,-200,200)=24,f(123,1,3)=0,f(3,33,34)=2 (3) [19= 19,19= 19,24= 24,0= 0,2= 2] Type: Tuple Equation NonNegativeInteger (4) -> f(0,-1,1)=1, f(127,12,27)=0 (4) [1= 1,0= 0] Type: Tuple Equation NonNegativeInteger ``` [Answer] ## Mathematica, 70 bytes ``` (w=ToString;t=0;Table[If[StringContainsQ[w@i,w@#1],t++],{i,#2,#3}];t)& ``` **input** > > [12,-200,200] > > > **output** > > 24 > > > [Answer] ## Clojure, 65 bytes ``` #(count(for[i(range %2(inc %3)):when(some(set(str %))(str i))]i)) ``` [Answer] ## PHP, 56 Bytes run as pipe [**Try it online**](https://tio.run/##K8go@G9jX5BRoMClkliUXqZgqxBtrGOoY2hgEGvNZW8HlLQtLk0qLimKT84vzSvRyMrPzNMoSsxLT9XQUEm0BWvSjDaM1VFJjDaK1dQE0Qaxmtb//wMA) **Input** ``` $argv = [number_to_find, range_start, range_end]; ``` **Code** ``` <?=substr_count(join(range(($a=$argv)[1],$a[2])),$a[0]); ``` **Explanation** ``` #substrcount, counts the aparitions of a subtring in a string substr_count( join( range(($a=$argv)[1],$a[2])), # String with the range $a[0]); # The number you are looking for ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 32 bytes ``` {+grep *.contains($^a),$^b..$^c} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1o7vSi1QEFLLzk/ryQxM69YQyUuUVNHJS5JT08lLrn2f3FipUKahrGOgiEQGRho/gcA "Perl 6 – Try It Online") ]
[Question] [ A number of programming languages construct large integers through 'concatenating' the digit to the end of the existing number. For example, [Labyrinth](https://github.com/m-ender/labyrinth), or [Adapt](https://github.com/cairdcoinheringaahing/adapt). By concatenating the digit to the end, I mean that, if the existing number is \$45\$, and the digit is \$7\$, the result number is \$457\:(45 \times 10 + 7)\$. A constructed number is a number that can be built this way through the use of the multiples of single digit numbers: \$1, 2, 3, 4, 5, 6, 7, 8, 9\$ A.K.A an element in one of these 9 sequences: $$1, 12, 123, 1234, 12345, \: \dots$$ $$2, 24, 246, 2468, 24690, \: \dots$$ $$3, 36, 369, 3702, 37035, \: \dots$$ $$4, 48, 492, 4936, 49380, \: \dots$$ $$5, 60, 615, 6170, 61725, \: \dots$$ $$6, 72, 738, 7404, 74070, \: \dots$$ $$7, 84, 861, 8638, 86415, \: \dots$$ $$8, 96, 984, 9872, 98760, \: \dots$$ $$9, 108, 1107, 11106, 111105, \: \dots$$ To provide an example of how the sequences are constructed, here's how the sequence for \$a = 3\$ in constructed: $$\begin{align} u\_1 = && a = && 3 & = 3\\ u\_2 = && 10 \times u\_1 + 2 \times a = && 30 + 6 & = 36 \\ u\_3 = && 10 \times u\_2 + 3 \times a = && 360 + 9 & = 369 \\ u\_4 = && 10 \times u\_3 + 4 \times a = && 3690 + 12 & = 3702 \\ u\_5 = && 10 \times u\_4 + 5 \times a = && 37020 + 15 & = 37035 \\ u\_6 = && 10 \times u\_5 + 6 \times a = && 370350 + 18 & = 370368 \\ \end{align}$$ $$\vdots$$ $$\begin{align} u\_{33} = && 10 \times u\_{32} + 33 \times a = && 37\dots260 + 99 & = 37\dots359 \\ u\_{34} = && 10 \times u\_{33} + 34 \times a = && 37\dots359 + 102 & = 37\dots3692 \end{align}$$ $$\vdots$$ \$u\_{33}\$ and \$u\_{34}\$ included to demonstrate when \$n \times a \ge 100\$. A *lot* of digits dotted out for space. It may still not be clear how these sequences are constructed, so here are two different ways to understand them: * Each sequence starts from the single digit. The next term is found by taking the next [multiple](https://en.wikipedia.org/wiki/Multiple_(mathematics)) of that digit, multiplying the previous term by \$10\$ and adding the multiple. In sequence terms: $$u\_n = 10 \times u\_{n-1} + n \times a, \: \: u\_1 = a$$ where \$a\$ is a single digit (\$1\$ through \$9\$) * Each of the \$9\$ elements at any point in the sequence (take \$n = 3\$ for instance) are the multiples of \$123\dots\$ from \$1\$ to \$9\$, where \$123\dots\$ is constructed by \$u\_{n+1} = 10 \times u\_n + n\$ \$(1, 12, 123, \dots, 123456789, 1234567900, 12345679011, \dots)\$ So the first values are \$1 \times 1, 2, 3, \dots, 8, 9\$, the second are \$12 \times 1, 2, 3, \dots, 8, 9\$, the third \$123 \times 1, 2, 3, \dots, 8, 9\$, etc. Your task is to take a constructed number as input and to output the initial digit used to construct it. You can assume the input will always be a constructed number, and will be greater than \$0\$. It may be a single digit, which maps back to itself. You may take input in any reasonable manner, including as a list of digits, as a string etc. It is acceptable (though not recommended) to take input in unary, or any other base of your choosing. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins! ## Test cases ``` u_n => a 37035 => 3 6172839506165 => 5 5 => 5 246913580244 => 2 987654312 => 8 61728395061720 => 5 1111104 => 9 11111103 => 9 111111102 => 9 2469134 => 2 98760 => 8 8641975308641962 => 7 ``` or as two lists: ``` [37035, 6172839506165, 5, 246913580244, 987654312, 61728395061720, 1111104, 11111103, 111111102, 2469134, 98760, 8641975308641962] [3, 5, 5, 2, 8, 5, 9, 9, 9, 2, 8, 7] ``` --- When I posted this challenge, I didn't realise it could be simplified so much by the method used in [Grimmy's answer](https://codegolf.stackexchange.com/a/191306/66833), and so therefore would be very interested in answers that take a more mathematical approach to solving this, rather than a 'digit' trick (Obviously all valid answers are equally valid, just what I'd be interested in seeing). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ ~~5~~ 4 bytes ``` >9*н ``` [Try it online!](https://tio.run/##TYw7CsJQFET7WUVIKQr3f@9rkrUoWFhZCELArbkHd/QkJoXTzCnOzP1xvtyu/fVc5nE4TcM4L31qh8@7H7smqSM4pbQ5BYfDIRaN1YvEDK0y3JTlX0sh8BqyrZl0BybZD7YtocK4pSv9IAQMgcIQSBQamOoL "05AB1E – Try It Online") ``` > # input + 1 9* # * 9 н # take the first digit ``` The \$(n-1)^{th}\$ term of the sequence starting with \$a\$ is \$\sum \_{i=1}^{n-1} a \times i \times 10^{i-1} = a \times \frac{(10^n - 1) / 9 - n}{9}\$. Multiply that by \$9\$ and add \$a\times n\$, and you get \$a \times \frac{10^n - 1}{9}\$, aka the digit \$a\$ repeated \$n\$ times. Turns out adding \$9\$ instead of \$a\times n\$ works for \$n=1\$, and for bigger \$n\$ the linear difference is negligible next to the exponential growth. [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ``` ^9*Eh ``` [Run and debug it](https://staxlang.xyz/#c=%5E9*Eh&i=+37035++++++++++%0A+6172839506165+++%0A+5+++++++++++++++%0A+246913580244++++%0A+987654312++++++++%0A+61728395061720+++%0A+1111104++++++++++%0A+11111103++++++++%0A+111111102++++++++%0A+2469134+++++++++%0A+98760+++++++++++%0A+8641975308641962+&a=1&m=2) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` §I×⁹⊕N⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMOxxDMvJbVCwzmxuEQjJDM3tVjDUkfBMy@5KDU3Na8kNUXDM6@gtMSvNDcptUhDEwh0FAw0Na3//7cwMzG0NDc1NgAzzIz@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. @Grimy's method of course. Here's a 27 byte mathematical approach: ``` NθW¬№Eχ×κ↨υχθ⊞υLυI⌕Eχ×ι↨υχθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05qrPCMzJ1VBwy@/RMM5vzSvRMM3sUDD0EBHISQzN7VYI1tHwSmxOFWjVEfB0EBTU1NHoRBIKgSUFmeAxHxS89JLgCxNoEkBRZlA7c6JxSUabpl5KWgGZWI1yPr/fwszE0NLc1NjAzDDzOi/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Crashes on invalid inputs. Explanation: ``` Nθ ``` Input the constructed number. ``` W¬№Eχ×κ↨υχθ ``` Interpret the list as a number in base 10, multiply by all numbers from `0` to `9`, and see whether the constructed number appears. ``` ⊞υLυ ``` Push the list's length to itself. The list therefore becomes of the form `[0, 1, 2, ..., n]`. ``` I⌕Eχ×ι↨υχθ ``` Recreate the constructed numbers but this time find and output the index at which the input number appeared. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 6 bytes ``` )9*▒├Þ ``` [Try it online!](https://tio.run/##bY67DcJAEERzV@EUR/vf23JIgMAWCZVYiAjRDJ24kcN3Ts4WE63eaGdmOj9u1/t4yfkUw/Kal@f7@8mZHVj7Rp2hU@JQMLTqdDu/EhILZE1AIhuJ5KbCSH9inKAQLAJpYjbCB7AiOjS1T6UJdmuSCYYrQz2Mfg "MathGolf – Try It Online") Unfortunately, there's no `head` operation in MathGolf, so I have to make do with `▒├Þ` to convert to string, pop from the left and discard all but the top of stack. [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), ~~28 22~~ 20 bytes ``` 9 10/;!@ ? _ : )*""" ``` Applies the digit-based method described [by Grimy](https://codegolf.stackexchange.com/a/191306/53748) by repeated integer division by ten until zero is found. **[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fUsHQQN9a0YHLXiFewYpLU0tJSQkoamFuZmpibGgEAA "Labyrinth – Try It Online")** [Answer] # [Python 3](https://docs.python.org/3/), 22 bytes ``` lambda i:str(-~i*9)[0] ``` [Try it online!](https://tio.run/##VY7NCoJQEIX3PsVAGw2D@bm/Qk9iLoyQLpSKuWnTq9@upouGs/hmOJwz43u@D73E7nyJj/Z5vbUQqtc85adPOPqixiZ2wwQBQg@1WBRdgiHLTrxGQyatSayMJ9EOWakSvLNGKyH@s1rGEmgZVBsQyk6EvMdsCcntjCJvteAKhpsqg3EK/Zx3eSiKLDvUsvYvLyT7Cn7X72Kb@AU "Python 3 – Try It Online") Port of [Grimy](https://codegolf.stackexchange.com/users/6484/grimy)'s [05AB1E answer](https://codegolf.stackexchange.com/a/191306/87681) --- # [Python 3](https://docs.python.org/3/), 72 bytes ``` f=lambda i,j=1,l=1,k=2:l*(i==j)or f(i,*(10*j+k*l,l+1,l,l+1,k+1)[i<j::2]) ``` [Try it online!](https://tio.run/##VY5ND4IwDIbv/IolXhjs0I99MOJ@CeGgMcTBBGO8@Otxohxs2uZt8@Rt76/ndZl5XYeQTrfz5SSiGgOqlGsK1KaqjCGMcnmIoYyqKhGqsZ6qpFKdqa1PNcouHse2pV6uQ0ajiLPo2AEbJSw6atgbsGjzmJO09cimAdJaCd84azQj/aGOQAn8BOifQOBdIdBu83PIdGM1emcYNmGpbwtxf8T5WebXpSyKQ8fb/c8LGd@E3/O7cf36Bg "Python 3 – Try It Online") ### Explanation Recursive function. Iterates over the sequence for each digit `l`, starting at `1`. If the input `i` is equal to the current iteration `j`, the corresponding digit `l` is returned. Else, if the current value `j` in the sequence exceeds the input value `i`, it will increment the digit `l` and start over. Argument `k` is used to increment the multiplication factor. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ‘×9DḢ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4zD0y1dHu5Y9P//fwszE0NLc1NjAzDDzAgA "Jelly – Try It Online") Using [Grimy's approach](https://codegolf.stackexchange.com/a/191306/41024). [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) -1 byte thanks to Shaggy Takes input as a string ``` i°U*9 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=abBVKjk&input=JzYxNzI4Mzk1MDYxNjUn) | [Test multiple inputs](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&header=cw&code=abBVKjk&footer=Vmc&input=IFsKIDM3MDM1ICAgICAgICAgIAogNjE3MjgzOTUwNjE2NSAgIAogNSAgICAgICAgICAgICAgIAogMjQ2OTEzNTgwMjQ0ICAgIAogOTg3NjU0MzEyICAgICAgICAKIDYxNzI4Mzk1MDYxNzIwICAgCiAxMTExMTA0ICAgICAgICAgIAogMTExMTExMDMgICAgICAgIAogMTExMTExMTAyICAgICAgICAKIDI0NjkxMzQgICAgICAgICAKIDk4NzYwICAgICAgICAgICAKIDg2NDE5NzUzMDg2NDE5NjIgCl0) [Answer] # Java 8, 23 bytes ``` n->(n*9+9+"").charAt(0) ``` Port of [*@Grimy*'s 05AB1E answer](https://codegolf.stackexchange.com/a/191306/52210), so make sure to upvote him! [Try it online.](https://tio.run/##dZFNboMwEIX3OcWIlV0E8h8GFLVS92k2WVZduMQlpMQgMJGqKtseoEfsRaghREqK6oVlf/PGb/S8V0cV7LfvfVaqtoUnVZjPBUBhrG7eVKZhPVwBsp1qIENlZXIweOnYaeG21ipbZLAGA/fQm@ABmbvUT33Pw@HQ8mgRwf1ykNbda@mkU8exKrZwcG5oY5vC5M8voPDZyurWIh4THo0@E5A0ZglPIyKpjFbXlRsZEzKlPEoIE@JGlSaxjASn7J9HY0Zu9HRYRMwQJXzOKGHzIcRfe3INEiloGkecjAfJVrNQx4hG7Zh6YerOThFtPlqrD2HV2bB26dnSoLHse@CFja61ckOQ4ALdZ5Ta5HaHMPa9n69v8HwTZucynoxP/S8) But because I kinda feel bad for *@cairdCoinheringaahing*, here a brute-force approach with a bit more afford (**83 bytes**): ``` n->{long r=n,a=0,u,k;for(;++a<10;r=u>n?r:a)for(k=2,u=a;u<n;)u=u*10+k++*a;return r;} ``` [Try it online.](https://tio.run/##dZFLboMwFEXnWYXFCMcE2fypQ7qBNJMOqw5c4qQEYpCxI1VRpl1Al9iNUHColBTVA3/Ou/K9eu/ATmxx2JZdXrG2BU@sEOcZAIVQXO5YzsFmeAJQ1WIPctscAtKeXWb91iqmihxsgAAZ6MRidTYKmQmHZdjRTkl3tbQpQmxJMJWZXolH@cDgQMvMc3TGqF4KCnWm5wSjEqE5o5IrLQWQ9NLRwabRb1VvM7qd6mILjn1S@1nJQuxfXgGD15iKt8r2Y@yHJuMIIhJ7iZ@GOCJRuL6t3Mm8IEqJHybYC4I7VZrEURj4xPvn09jDd3oyLBxMEMH@lBHsTUMEf@3xLUiigKRx6GNzibz1ZCCmRUZr5lGIRquxRc8freJHt9bKbfruqUrYpowsYLmSN5z1IfDiF1rQrbjYq3cbQmR9f34BCwk3v5bhaHzpfgA) **Explanation:** ``` n->{ // Method with long as both parameter and return-type long r=n, // Result, starting at the input in case it's already a single digit a=0, // The digit to start the sequence with u, // The last number of the sequence we're building for digit a k; // Multiplier which increments each iteration for(;++a<10; // Loop in the range [1,9] (over each digit): r=u>n? // After ever iteration: if `u` is larger than the input: r // Keep the result the same : // Else: a) // Change the result to `a` for(k=2, // Reset `k` to 2 u=a; // Reset `u` to the current digit `a` u<n;) // Inner loop as long as `u` is smaller than the input u= // Change `u` to: u*10 // 10 times the current `u` +k++*a; // With `k` multiplied by `a` added // (after which `k` increases by 1 with `k++`) return r;} // And after we iterated over each digit, return the result ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 108 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][S S S T N _Push_1][T S S S _Add][S S S T S S T N _Push_9][T S S N _Multiply][S S S T N _Push_1][N S S N _Create_Label_LOOP][S S S T S T S N _Push_10][T S S N _Multiply][S N S _Duplicate][S T S S S T S N _Copy_0-based_2nd]S N T Swap_top_two][T S S T _Subtract][N T T S N _If_neg_jump_to_Label_PRINT][N S N N _Jump_to_Label_LOOP][N S S S N _Create_Label_PRINT][S S S T S T S N _Push_10][T S T S _Integer_divide][T S T S _Integer_divide][T N S T _Output_top_as_number] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Port of [*@Grimy*'s 05AB1E answer](https://codegolf.stackexchange.com/a/191306/52210), except that I don't have a builtin to get the first digit. ;) [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIA7IUwIATyuYCC3JBGUAIEeQCqwBxgQIQtUA2kANSiqwWCoF2/P9vZmhuZGFsaWoAYhgAAA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer i = STDIN as integer i = i + 1 i = i * 9 Integer t = 1 Start LOOP: t = t * 10 If(i - t < 0): Call function PRINT Go to next iteration of LOOP function PRINT: t = t / 10 i = i / t (NOTE: Whitespace only has integer-division) Print i as integer to STDOUT ``` [Answer] # JavaScript (ES6), ~~16~~ 15 bytes *Thanks to @Grimy for lifting the 32-bit constraint I had with the previous version.* Using [Grimy's magical incantation](https://codegolf.stackexchange.com/a/191306/58563). Takes input as a string. ``` n=>(n*9+9+n)[0] ``` [Try it online!](https://tio.run/##jdFNDoIwEAXgvadgNyBRpv@dBV7EuCAKRkNaI8br1wgLQgHjrLr4MvNeeq/eVXd@3h6vnfOXOjRlcOUhdVvKKXfZEU/h7F3n23rf@mvapCAMCgXJOFmWFEUiNpHTzHArSKFmuveDU7Gb7ErWHZeamFAWuZQwOh47skYrKRiHyT77I5/hCKt32XdQQpSPFh1DAX85hlE@Wu47u7vYF@f/MetrtWRklMD@oTkMzoQP "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 53 bytes Naive brute force approach. ``` n=>(g=(k,x=i=0)=>x>n?g(k+1):x<n?g(k,++i*k+10*x):k)(1) ``` [Try it online!](https://tio.run/##jdDbDoIwDAbge5@Cy008tDvPOHwW4oEgZBgxhrdHxUR0grFXzfKl7b9jek3r7Tk/Xea@2u3bg2u9S0jmSDFrXO6AuqRJ/CYjRYx01ay7dhbH@fT@ANOGrgpKkLbbytdVuV@UVUYOhGvgMuqL0mi5jPjkUynUzHArQaGSLyUD9T4nGlVMKItcGmBC9IoFyhqtpODIPmaZ8bs0g7GN@CgQwV12SCHwfxQC@6meGcONQxnh67/CjEYJtFpy6BrFnkq3Nw "JavaScript (Node.js) – Try It Online") [Answer] # [PHP](https://php.net/), 20 bytes ``` <?=(_.++$argn*9)[1]; ``` [Try it online!](https://tio.run/##TYy9CgIxEIT7fQo5LNRD2Z/sJuEUO19CRUTEs0mC@vxG9K5wmvmKb6b0pdb1djM7rdp2en7c0iLO93Ts6vXS50lzSE1XxaMoGHkOEhWNTEGBnUUSDcjOQQze1Anxv@YZgb5BNzShjEDI48GwRQjmKHoV/IHxO5fXPadnXe4@ "PHP – Try It Online") Yet another [Grimy's answer](https://codegolf.stackexchange.com/a/191306/81663) port! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` RRḌ÷@fⱮ9 ``` [Try it online!](https://tio.run/##y0rNyan8/z8o6OGOnsPbHdIebVxn@f//f2MzSwA "Jelly – Try It Online") A full program that takes an integer and prints the starter digit. Doesn’t use Grimy’s clever method! Terribly inefficient for larger input. The following version handles all of the test cases but is a byte longer: # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` DJRḌ÷@fⱮ9 ``` [Try it online!](https://tio.run/##y0rNyan8/9/FK@jhjp7D2x3SHm1cZ/nf@lHDHAVdO4VHDXOtD7dzHW5/1LQm8v//aGNzA2NTHQUzQ3MjC2NLUwMzQzMgF4iMTMwsDY1NLQyMTEx0FCwtzM1MTYwNjVCUmhsZ6CgYgoCBCZRhaGAMYxkaGMGMgZoAVG1hZmJoaW5qbABmmBnFAgA "Jelly – Try It Online") [Answer] # [Hy](http://hylang.org/), 44 bytes ``` (defn a[p](print(get(str(*(+(int p)1)9))0))) ``` Uses Grimy's method [Try it online!](https://tio.run/##XYw7DsIwEER7TuFyF5r92Gv7LIgiEuHTRFZIw@mdYBeJ2GL15kkzr2@tcB8fkxuu5QZlfk8LPMcFPssMZ7jAll1BxoxIiFhhcBpJA542Mo6SNAcytm76F2@ZNSQS75vIKVrwyvJfi0JN8e/I78ykh8Akh@F9s5eTec4xKDUwwboC "Hy – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg) `-rr`, 4 bytes ``` ⑨9*÷ ``` [Try it online!](https://tio.run/##y05N////0cQVllqHt///DwA "Keg – Try It Online") Of course, uses the same approach as the 05AB1E answer. Also uses the new `-rr` (reverse and print raw) flag. Transpiles to: ``` from KegLib import * from Stackd import Stack stack = Stack() printed = False increment(stack) integer(stack, 9) maths(stack, '*') item_split(stack) if not printed: reverse(stack) raw(stack) ``` [Answer] # [Wren](https://github.com/munificent/wren), 30 bytes Just a port of most answers. ``` Fn.new{|i|(i*9+9).toString[0]} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkKhg@98tTy8vtby6JrNGI1PLUttSU68kP7ikKDMvPdogtvZ/cGVxSWquXnlRZkmqRqJecmJOjoaxpuZ/AA "Wren – Try It Online") [Answer] # [W](https://github.com/A-ee/w) [`h`](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends/14339#14339), 3 [bytes](https://github.com/A-ee/w/wiki/Code-Page) ``` )9* ``` # Explanation ``` ) % Increment by 1 9* % Multiply by 9 Flag:h % Take the first item of the result ``` ``` [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 10 bytes ``` D9*_+$)[0] ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/38VSK15bRTPaIPb/f2NzA2NTAA "cQuents – Try It Online") Just another port of Grimmy's answer. ``` $ # Index _+ # +1 9* # *9 D )[0] # First digit ``` ]
[Question] [ Ruby comes with a built-in REPL, which is quite handy. ![screenshot of IRB](https://i.stack.imgur.com/V7y6s.png) Your challenge is to crash it in the least amount of code! The definition of "crash" is "make it exit in an **unintended** way." This means `exit`, `quit`, `abort`, `irb_exit`, `irb_quit`, et. al. are not valid answers. Furthermore, you may **not** cause any side-effect to any other part of the system. For example, ``rm -rf /`` is not valid either. Any version 1.9.3 or above is valid. If your code only works on a specific version of Ruby, you may specify that in the answer. The final restriction is that you may not rely on any gems. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code that crashes IRB will win! [Answer] # 16 characters ``` String=0 String=0 ``` Not the shortest, but I think it's funny that it doesn't crash until the second line. Generates roughly 20 lines of text before IRB exits. For some reason it cannot be shortened to for instance `2.times{String=0}`. --- **edit** Of all the answers so far, this is the only one that has worked for me (and it works in all versions I could get my hands on), and I've tested all of them in these versions: On whatever kind of Linux I get when `ssh`'ing into my university: ``` ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux] ruby 1.8.5 (2006-08-25) [x86_64-linux] ``` Mac OS X Mavericks default: ``` ruby 2.0.0p247 (2013-06-27 revision 41674) [universal.x86_64-darwin13] ``` Installed through Homebrew on OS X: ``` ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0] ``` --- **edit 2** # 7 characters Combining my first version (and/or @[Howard](https://codegolf.stackexchange.com/a/22345/4372)'s answer, for maximum cross reference) with @[chinese perl goth](https://codegolf.stackexchange.com/a/22353/4372)'s answer: ``` STDIN=0 ``` [Answer] # 12 chars ruby is not exactly my cup of tea, but I've just found out that irb acts funny when I close the stdin :) ``` $stdin.close ``` tested on irb 0.9.6(09/06/30) and ruby 1.9.3p194 [Answer] # ~~10~~ 9 chars A shorter variant on @daniero's answer: ``` String=1 - ``` This works at least in the default OS X Mavericks Ruby (2.0.0). The answer basically relies on the fact that the Ruby `Token` function does a `case` on the input token. One of the cases checks against `String`, which has been redefined by the first line. This case fails, so the case falls through to the default, which assumes the object has an `ancestors` accessor (which it does not). Because the "bug" is in the tokenizer, the first line won't fail because the line only takes effect after the parsing is finished. Thus, it only affects subsequent lines. Subsequent lines must contain some kind of operator in order to see the failure. [Answer] ## 5 characters ``` ENV=0 ``` (inspired by [@daniero](https://codegolf.stackexchange.com/users/4372/daniero)'s answer) [Answer] **5 characters** ``` $>=$< ``` Sets stdout to stdin which throws an error trying to open stdin for writing and crashes irb. [Answer] # 22 characters ``` def method_missing;end ``` Apparently it messes with some irb internals. (To fix it, add `self.` after `def`.) [Answer] # 12 characters ``` def send;end ``` As far as I know, there are four methods in the Object class which show this kind of behaviour: ``` send method_missing respond_to? respond_to_missing? ``` [Answer] # 5 Characters ``` IRB=0 ``` Nothing disturbs IRB quite like redefining IRB. [Answer] # ~~12~~ 10 characters ``` exec"exec" ``` I don't know if this counts, because of the `exec` [Answer] # 8 characters Similar to [chinese perl goth's answer](https://codegolf.stackexchange.com/a/22353/11261): ``` $>.close ``` `$>` is an alias for STDOUT. [Answer] # 26 + 1 = 27 characters This isn't very golfy, but I was amused to discover it by accident and thought others might enjoy it. ``` class Fixnum;def +;end end ``` I added +1 to the score because you have to press Enter a second time after entering the above (but not +2 because no one else counted Enter). ]
[Question] [ Given 2 non-negative integers as input, output a non-negative integer that cannot be created through any mathematical operators on the 2 inputs. For example, given inputs `2` and `3`, `6, 0, 5, 1, 9, 8, 23, 2` are all invalid outputs. Operations that must be taken into account are: ``` Addition (a + b) Subtraction (a - b) and (b - a) Multiplication (a * b) Division (a / b) and (b / a) Modulus (a % b) and (b % a) Exponentiation (a ** b) and (b ** a) Bitwise OR (a | b) Bitwise XOR (a ^ b) Bitwise AND (a & b) Concatenation (a.toString() + b.toString()) and (b.toString() + a.toString()) ``` In cases where an operation would lead to a non-integer (such as 2 / 3), always floor. So `2 / 3 = 0` Assume any invalid operations (such as dividing by 0) result in 0. ## Input 2 non-negative integers. [Standard I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) are accepted You can assume the input will always be within a handleable range for your given language, however remember [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) still apply. ## Output Any non-negative integer that can not be created via any of the above operations on the 2 inputs. ## Testcases ``` Input -> Invalid outputs 2, 3 -> 0, 1, 2, 3, 5, 6, 8, 9, 23, 32 0, 0 -> 0 17, 46 -> 0, 2, 12, 17, 29, 63, 782, 1746, 4617, 18487710785295216663082172416, 398703807810572411498315063055075847178723756123452198369 6, 6 -> 0, 1, 6, 12, 36, 66, 46656 1, 1 -> 0, 1, 2, 11 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins! [Answer] # [Retina](https://github.com/m-ender/retina), 3 bytes ``` . 1 ``` [Try it online!](https://tio.run/nexus/retina#@6/HZfj/v4GCAQA "Retina – TIO Nexus") Takes inputs separated by space (or any single non-newline character) Replaces all digits with `1`, and joins the resulting numbers with another `1`. ### Proof of correctness *Courtesy of [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)* * This operation computes a result with one more digit than the number of digits of the two numbers together; the only operation that could produce a result so big is exponentiation. * The result is a repunit (a number whose digits are all 1). * ["It is know [sic] [...] that a repunit in base 10 cannot [...] be a perfect power."](https://mathoverflow.net/a/132025/56581) This means that this result can't be produced by exponentiation either. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` +Æn ``` [Try it online!](https://tio.run/##y0rNyan8/1/7cFve////Dc3/m5gBAA "Jelly – Try It Online") Explanation: ``` +Æn Arguments: x, y + x + y. Æn Find a prime larger than ``` [Answer] # [Python 2](https://docs.python.org/2/), 8 bytes ``` '1'.join ``` [Try it online!](https://tio.run/nexus/python2#TY1LCsMgFEXHZhWPTKJBipaOAhl0HWnAErRYRMOrBV29tU0KmZ5zP2a8lU52p2ewvpiAkMF6wLt/aCovbGjgC9MBCiEqJqhfbxcljFVFauikkuIqq5mxvzwfZK4ybdIaSH3/@5n2FQ57Yx6gIWTFWgOaeK5xopONlDUbbK/OwRIQ9RLb8gE "Python 2 – TIO Nexus") Takes a list of two number strings as inputs, outputs a single number string. Concatenates the numbers with a `1` in the middle. The result has too many digits for anything but exponent. Note that the output for `(x,y)` has one more digit than `x` and `y` combined, unless `x` or `y` is 0. For exponent, we check we check that this means `x**y` never matches. * If `x` is 0 or 1, then so is `x**y`, which is too small * If `y<=1`, then `x**y<=x` is too small * If `y==2`, then `x**2` must have two more digits than `x`. This happens up to `x=316`, and we can check none of those work. * If `y==3`, then `x**3` must have two more digits than `x`. This happens up to `x=21`. We can check that none of those work. * If `3<y<13`, then `x**y` quickly gets too long. It only plausible has the right number of digits for `x<=25`, and we can check these. * If `y>=14`, then `x**y` is too long even for the smallest possible `x==2`. [Answer] ## CJam (7 chars) ``` {+))m!} ``` This creates a number `(a+b+2)!` which is larger than the largest related number in almost all cases. It's fairly obvious that the largest related number must be one of `a ** b`, `b ** a`, `concat(a, b)`, `concat(b, a)`. If we consider logarithms, we find that * `log(a ** b) = b log a` * `log(concat(a, b)) ~= (log a) + log (b)` * `log((a + b + 2)!) ~= (a + b + 2) log (a + b + 2) - (a + b + 2)` Thus asymptotically it's larger, and we only need to worry about a few small cases. In fact, the only case for which the value output is not larger than all related numbers is `0, 1` (or `1, 0`), for which it gives `6` and the largest related number is `10`. [Answer] # Python, ~~115~~ ~~95~~ 79 bytes Stupid straightforward solution. Feel free to outgolf me. ``` x,y=input() f=lambda x,y:[x+y,x*y,x**y,int(`x`+`y`)] print max(f(x,y)+f(y,x))+1 ``` +12 bytes because of stupid `x/0`. -20 bytes thanks to @RobinJames -16 bytes thanks to @tehtmi [Answer] ## JavaScript (ES6), 15 bytes Takes input in currying syntax. ``` a=>b=>a*a+b*b+2 ``` **a² + b² + 1** would fail for many entries such as **3² + 5² + 1 = 35** or **7² + 26² + 1 = 726** (concatenation). **a² + b² + 2** should be safe. This was exhaustively tested for **0 ≤ a ≤ b ≤ 50000**. ### Demo ``` let f = a=>b=>a*a+b*b+2 for(a = 0; a < 5; a++) { for(b = a; b < 5; b++) { console.log(a, b, f(a)(b)); } } for(i = 0; i < 10; i++) { a = Math.random() * 1000 | 0; b = Math.random() * 1000 | 0; console.log(a, b, f(a)(b)); } ``` [Answer] # Python, 27 bytes ``` lambda a,b:(a+b+9)**(a+b+9) ``` Outputs a number larger than all the related numbers. [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCok2SlkaidpG2pqaUFZfyv0Km0zcwrKC3R0OQqKMrMK1FI0wCKaf431DECAA) -1 byte thanks to Kevin Cruijssen. -2 bytes thanks to Dead Possum. [Answer] ## Python 2, 25 bytes ``` lambda x,y:int(`x`+`y`)+3 ``` Concatenates and adds 3 [Try it online](http://ideone.com/rQJt88) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` +<ṗ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wX9vm4c7p//9HRxvpGMfqRBvoGABJQ3MdEzMgbaYDIg11DGNjAQ "Brachylog – Try It Online") Nothing new here. ``` The output ṗ is a prime number < which is strictly greater than + the sum of the elements of the input. ``` Now, to figure out how to find an unrelated string... [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 8 bytes Man, so many cool ways to just take these numbers and get an unrelated number. I just had to try a few, to see how QBIC'd keep up. The shortest one is a port of xnor's Python answer, concatenating the numbers with a 1 in the middle: ``` ?;+@1`+; ``` All ones, a port of Leo's Retina answer: ``` [0,_l;|+_l;||Z=Z+@1 ``` Finding the next bigger prime: ``` c=:+:+1≈µc|+1|c=c+1]?c ``` [Answer] # JS (ES6), 12 bytes ``` x=>x.join`1` ``` Same algorithm as [this python answer](https://codegolf.stackexchange.com/questions/122442/find-an-unrelated-number/122523#122523). Takes input as an array of ints. [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf/), 4 bytes ``` 9&+^ ``` [Try it online!](https://tio.run/nexus/python3#1Rrbbts29N1fwaXtJDWOa2d7cuJuLx2wh2HDMBQDHDdQZTrWKksaKbsONuzXs8P7oUQldjMk2ENbkzz3O6muWLUh/JaTfFNXrCEpu9ldDFZid7Uts6aqCnvG6HKbUX2aVUVBsyavSnu@pH9u4VivKj6q02bt1jVlaVMxu5E3lEn6doel5bLauCUQG2RFyjnhknYs/06mAwK8VuT6@oY2QGVzfR1zWqyGJC@XdC/PCclXJOd5yZu0zGgsT4aEF3lGNQABBs2WlaS5rakkkMRWplEuQTHdEZBijVtUtftN6yQZIJJS0FGfgIMBkMo@cTIj88XFINsyJjdgPb4Y0HIJP35ICw7614xyynbU7WRVuQMh3QajsOYIgjcsL2/cmvIsrdH5Zls0eQ0wiAj/lNdula@QCDwvKAZdFRL0NyacXVQVwrthlC5v3VqcSqspzSTPrNpKaicnWpJsnTK9Hgi3Cq81MZdeatit9qbcwiYW/GFN9xmtG/I@Lbb0HWMVm2IgKYciq@KPxiYOh2SVg9khJiiYdCnZaSwDEvsQWj7wqfTWLi1i@WNIjJeGQGEnKUH0mU1PIIkwHy8EAMASCvLpzbMJxAKRO12UUV3VBV01cdLFFGdxQDp@r3jgVHWekLdkYnPGl5oQwRS887DcUuL8Zu2gJ0Hocw3t9PSZHKJpgNthaI5pv6q@EuN@cTv8FQ/ttlhADRVQ2zmxdMJNUX1MC4XOEabamNuysNDYkD4ber1KoSozHpfKkcD/HP7Vu7KiwPLzGpIWDl/Dn8sZKa3OJXlFcqNHTk5nZNJRryRv3sxIrlea8iita6hMcZ4MNCEbNS2IMnGq6CMtfwpl6ho6DI/FXzrjTBWUvw0NXe8TadBVxcgeKoBoTtwr7k28R8Wcg7MMgX1i3CajYbRJm2wdRx@u5qPXV4uX0ZA4zJSxH8t6K1xJRVLvXYT1SCS1BqlyJZVCN@SQdHniNpWEkCzWkhLA0tOyirTMEzKbGesGcSu2bOM6/xnpMiFdjneDdLIk6Ya4xd87fN/CCFU7G84hUp2r46xaqmb7Qlb@OPoFtkVresUjiEN5fBFKBG0HMYyg6qSbJsSsH0m7@WS6wIRs5qA9EBmtTOpjJNVX0Y5urJ6EorNiqrK1og3XWzEaNFe0hO6KD2V7RRuiv6Kl6KFoqVps61z2WE8902jboolmK/b2qiObSrEnl9Li1mPa2gDlapaKkgz2BNh8ryvjXlYR8LyJm1sRNzDL3dB4PHRtxuYCeFfV1ltoEJyUVSPau4szezhTbV8vE81CoINBEbVMpEv0d0Rk0Irf0wiR80Ybl6PL9iZEQJOXYqoxfIRtO3wWkZfptjO@JWOca3b/TFrHHQjTe04LZ7A/WbXoum7njrriu2BESqjKlKHKhMYy8GQWohgS0QxygpwjkajOainKLjzBdpcOV1GP9dUlIhr9UeVlPM/WLM6lvBCak8nk28nkXBEbJ672KiO7GDuTTKeLRTIUGT@LoqTDut32XWlBLdf2/2mbuBxqlG6XeIhS44buEo5paNh2KreHeytPa@YOuEpPzDYKRWXqxOpJROBOJdVWpQpnmX9L8EwhAmGumowzti0gi5Z6aIJHnUxJcHXlp0tIFELsFUXdKkLh5ji5IFV8VOE2kCo/Qv2NkM7dqSXs1JkL6oOl@AldeFoYJ5Hjq@0ZhLuOkG8EfVXHnXoweKBi23e3EP0oOTiZgEogDY6NOt8Nfuphnr3CGHEOUu7RAiOjzx4yupJrriaxlmqLJGyAXF7PxxeeRXhj8XjXDyev@BRmnhOYecRDxJAEOC7wNKe4nHqNo323bun6/UO6eoWoP81EGHu5fJ/LJbBIx3uK9ZfXX1VL54uDQkFZWggUiKAHbPfC2s4ViGAW/xO524Z5dAkCvnRlwYRoEG74kNd6LuraMeJ5onsBtUaVzxb3nONKKWn1H9snkHDM9HRP50Vtr6WZBQ/2zdfWQhYwaMlRFGwA9oki6WD8ZTHsK5PKvFoONXCji/3ghb3OFWst71j@QagHre@7rHngZxNnZfW29e7nH9DLVj8C0q0IWwMN4x2UpUX5glbUl5edt8m26SBhRZtKenSTo@o6IC0LK6hekEfiH3MBOUyRpJNp43YBO0pHJCrHOe5YPLL191fCHpvbEgMMeoNvfHiUCnJC8ktjqUAYvve91P@Ygp/ArYl4Qs5MB0REd65aIyz3@5RMjKrGFFI@B3Hm@qqgavffeszRTcd/oA9gXuK73zHKZMHg4LLUy1nUEpse1I9lIXaPNHnSGuz5iNFNtaM6CC/u0xGJ@dM9Yj59IJd03/T6HTsFSQoBq/K5bZC5pWatJgpSxwSb/4EJztomsGUsGIfHG@FXbIRAaN4fRfXjWky@kY/F/jO4ExMnRsUamDUUSm9v6aq3tQKW9HNrgglw8XWX4696zLLoODnNXjc3Q/OTge7IuA93vk3e39p/70FJ970o3z3GVXJWktfPRHx9GHfe4vD1wzzF4b0vbbVzK7V@PcNE8cfIfQf19IALOvcNwQ/JbX8UbH2DHKXL5dDYis8n4tnKrsZwJTygSLRup6v@@5XtvttNdwwPdvueG5kjsHhgkO8XHJn@zbOYfgXxwJb57r@1f6tozNX/mQhxPcyAyEyvn8VMm23xtBaSDI82ztmzGIdvPz6tcSTDo43z4VmMU1efn9Y4kuHRxnn1PGlVLZ84rQTDI4zT/kzUvZYHpoavrC2R0MHnmsvWSMKqRtgn9JbxNgwagLywkOr/UCnOg@C3sOO/XgXft0NfrQ76PpV4RNs923qz5xuUQu77thSOmO5jufkcU@pPHeYN1b4W9j2KyMfVAa@2LBNMoii6O/1wB//Arvr0r85G4j22Fvf8u7vzu2/@BQ "Python 3 – TIO Nexus") (Header & Footer are Interpreter, code is actual braingolf code, args are inputs) Outputs `(a+b+9)**(a+b+9)` From my testing I couldn't find any pairs that this doesn't work on. [Answer] # [Python 2](https://docs.python.org/2/), 19 bytes ``` lambda x,y:x+9<<y+9 ``` [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqFChU2lVoW1pY1OpbfkfyLHNzCsoLdHQ5CooyswrUUjTAIpp/jfUMQIA "Python 2 – TIO Nexus") I'm pretty sure the bit shift works for all cases, but I'm not 100% on it. Anyway, it saves a few bytes over the exponentiation version. [Answer] # [J](http://jsoftware.com/), 5 bytes Just a translation of [Jelly](https://codegolf.stackexchange.com/a/122445/43319). ``` 4 p:+ ``` [Try it online!](https://tio.run/##y/r/P83WykShwEr7f2pyRr6CoblCmoKJ2X8A "J – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 4 bytes Algorithm taken from [here](https://codegolf.stackexchange.com/a/122455/43319). ``` !2++ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRFI23t/06ZJeWZxalAbrXRo66lj3p3gVDPfkNDhUd9U12CHvWuAgooPOrdWsvllZ@ZB1L4qLdP41HvVKC4pg6YBsqFpBaXAOW0dXR1dB/1rtA5PF3n8HYgArFrwISOlo4WiPGoYwXUUp1HnQvgzI7lMCbIGjABVM3lnJGanA00uM7wUUfXo44ZehppQAbINk2QdEhiUg7Y8RrqCgrqQNdsBTlpK9DV6grqILcDdUD91LsC5ND/YAOB/tlsYcKVpgDWD@KZAwA "APL (Dyalog Unicode) – Try It Online") `!` factorial of `2+¨` two plus `+` the sum Works in J too. [Answer] # [sed](https://www.gnu.org/software/sed/), 6 bytes ``` s/ /1/ ``` [Try it online!](https://tio.run/nexus/sed#@1@sr6BvqP//v5GCKQA "sed – TIO Nexus") Input is via stdin in the form "x y", output is to stdout. Port of [this python answer](https://codegolf.stackexchange.com/a/122523), which includes the proof of correctness. Many thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for such a simple method. [Answer] # Java 8, 15 bytes ``` a->b->a*a+b*b+2 ``` Port from [*@Arnauld*'s amazing JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/122460/52210). [Try it here.](https://tio.run/nexus/java-openjdk#jY09D4IwEEB3fsWNFKTxKzqoHU0cnByNw7WiqSmlgYNIjL8dwQCLA073cvfyTicuzQgeWCIvSBt@K6winVq@72DjKYN5DkfU9uUBuEIarSAnpGaUqb5C0pz8E2Xa3s8XeLJWA@gD24Ol@B5nk59FN4UABbsaIyEjgQGGMpDhvG4bm2/pVOUUJzwtiLvmCRnrK47Omcqfsw4WjI3KUzbAuDxb9/Zy9Ye@YgP80WYDfOW3964/) Straight-forward approach (**~~177~~ 170 bytes**): ``` a->b->{int r=1;for(;a+b==r|a-b==r|a*b==r|(b>0?a/b==r|a%b==r:0>1)|Math.pow(a,b)==r|(a|b)==r|(a^b)==r|(a&b)==r|new Integer(""+a+b)==r|new Integer(""+b+a)==r;r++);return r;} ``` [Try it here.](https://tio.run/nexus/java-openjdk#fY9RS8MwFIXf/RWXgZIssTZONljpfPZhT3sUhZsaZ6FLy23qELvfXpOle3OF5J7D/Q4JZygqbFvY/t4ANJ2uygJah87Ld11@wAFLy3aOSrt/fUMeUgC7n9aZQ1J3Lmk8cZVlBXuUC86z6zyV6SRXK/m0nEws5TRXUkV@8tefsYfHULAwUYapxxbBU67ig581sQyFznPq8T7K/CxMb9JnfIir2yDrdKN4v0X3lTT1kaHU/BzE/mLeL@YuGmuO8GKd2Rtis5nw//y31gLDOiMhxppkXEcWKJY6DcMf) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~2~~ 4 bytes ``` +ØDm ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f@/CM///NuMwA "05AB1E – Try It Online") Same as the Jelly answer, finds a prime after the sum. One byte shorter :) **EDIT**: Now raises it to its own power to suffice for the exception. ]
[Question] [ A casino uses the following deck of cards. (`*` is one of the card suits `D`, `S`, `C` or `H`.) ``` _________ _________ _________ _________ _________ | | | | | | | | | | | | | | | * | | * * | | * * | | | | * | | | | | | | | * | | | | * | | | | * | | | | * | | | | | | | | | | | | * | | * * | | * * | |_________| |_________| |_________| |_________| |_________| _________ _________ _________ _________ _________ | | | | | | | | | | | * * | | * * | | * * | | * * | | * * | | | | | | * * | | * * | | * * | | * * | | * * * | | | | * | | * * | | | | | | * * | | * * | | * * | | * * | | * * | | * * | | * * | | * * | |_________| |_________| |_________| |_________| |_________| _________ _________ _________ | | | | | | | * * | | * * | | * * * | | * * | | * * * | | * * | | * * * | | * * | | * * * | | * * | | * * * | | * * | | * * | | * * | | * * * | |_________| |_________| |_________| ``` After each night, old decks are discarded, and cut in half to avoid reuse. As a result, the casino has a big room full of cut card halves. Unfortunately the economy is bad, and the casino is in financial trouble. The most reasonable thing to save money seems to be recycling, so the casino owners decide to tape old cards back together. So they hire a team to build a machine which will do this. You are part of the team, and your job is to help identifying the card. Write a program or function which will take an ASCII art image of a card half in the form of a string, and will return a string of what card it is. Input is an 11x5 string, plus line break characters (CR, LF or CRLF, you only need to support one). You may assume trailing whitespace at the end of each input line, if necessary. The input won't contain any invalid characters (any other than `_|-HSCD` and space and line break). A card half will look like this: ``` _________ | | | H H | | H H H | ---H---H--- ``` which should be identified as the Queen of Hearts: ``` H12 ``` The casino is on a limited budget, so this is code golf: the shortest program wins. [Answer] # CJam, ~~16~~ ~~15~~ ~~13~~ 12 bytes ``` q2*A~<$e`3=( ``` [Test it here.](http://cjam.aditsu.net/#code=q2*A~%3C%24e%603%3D(&input=%20_________%0A%7C%20%20%20%20%20%20%20%20%20%7C%0A%7C%20%20H%20%20%20H%20%20%7C%0A%7C%20%20H%20H%20H%20%20%7C%0A---H---H---) ## Explanation The basic idea is to manipulate the string such that we can make CJam's built-in run-length encoding work for us. Let's go through an example (the one from the question). The input string is ``` _________ | | | H H | | H H H | ---H---H--- ``` We repeat that twice: ``` _________ | | | H H | | H H H | ---H---H--- _________ | | | H H | | H H H | ---H---H--- ``` And remove the last line: ``` _________ | | | H H | | H H H | ---H---H--- _________ | | | H H | | H H H | ``` Then we sort this string. It'll now have a bunch of newlines at the start, and then this (shortened by a few spaces to avoid a horizontal scrollbar): ``` ---------HHHHHHHHHHHH__________________|||||||||||| ``` While the suit character will vary, it'll always be an upper case letter, found in the fourth run of the sorted string (accounting for the newline). When we run-length encode this we get ``` [8 '\n] [46 ' ] [9 '-] [12 'H] [18 '_] [12 '|]] ``` So all we need to do is pick out the fourth element and reverse it. Here is a breakdown of the actual code: ``` q e# Read the input. 2* e# Repeat twice. A~< e# Remove the last 11 characters, i.e. the last line. $ e# Flatten into a single string and sort its characters. e` e# Run-length encode: turns the sorted string into 5 pairs of numbers e# and characters. 3= e# Select the one corresponding to the suit. ( e# Pull off the number so that its printed after the suit. ``` [Answer] # Pyth (recent version), 16 bytes ``` p/KsP*2.zJ@S{K2J ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=p%2FKsP*2.zJ%40S%7BK2J&input=+_________%0A%7C+++++++++%7C%0A%7C++H+++H++%7C%0A%7C++H+H+H++%7C%0A---H---H---&debug=0) ### Explanation: ``` .z read all lines from input *2 duplicate all lines P remove the last line s combine all lines to a big string K store in K {K set(K), removes duplicate chars S sort, this will result in the list [' ', '-', color, '_', '|'] @ 2 take the element at index 2 J and store it in J p/K J J print J + (count J in K) ``` # Pyth 4.0, 13 bytes ``` [[email protected]](/cdn-cgi/l/email-protection)*2.z2 ``` Pyth had a build in run-length-encoding. But only for short time. If someone wants to try this: Clone the Pyth repo and checkout the commit 6a6dccd. This program works pretty much the same way as Martin's CJam solution. ``` sP*2.z like in the 16 bytes solution S sort .r run-length-encoding @ 2 element at index 2 jk join by "" and print ``` [Answer] # CJam, 22 bytes ``` qN/)'--\s"_| "-_]s)\,) ``` Looking at more golfing options here. Here is how it works: ``` qN/ e# Read the entire input from STDIN and split it on new lines )'-- e# Take out the last line and remove - from it \ e# Stack contains the half HSDC now. We swap this with rest of e# the input s e# join the rest of the input array to a single string "_| "- e# Remove anything other than HSCD _]s e# Copy this and convert everything on stack into a single e# string. Now we have the total HSCD in the complete card ) e# Take out the last of HSCD. This serves as first character of e# the output \,) e# Swap and take length of rest of the HSCD. Increment it by 1 e# as we removed 1 in the previous step. ``` [Try it online here](http://cjam.aditsu.net/#code=qN%2F)'--%5Cs%22_%7C%20%22-_%5Ds)%5C%2C)&input=%20_________%0A%7C%20%20%20%20%20%20%20%20%20%7C%0A%7C%20%20H%20%20%20H%20%20%7C%0A%7C%20%20H%20H%20H%20%20%7C%0A---H---H---) [Answer] # Python 2, ~~80~~ ~~68~~ 66 bytes **[Try it here](http://ideone.com/KhAk9c)** Duplicate the input, find all the letters in all but the last line (the first couple chars in the last line cannot be letters), then print the first letter and how many. ``` s=(input()*2)[:-9] for c in"CDHS": if c in s:print c+`s.count(c)` ``` **Input**: `' _________\n| |\n| H H |\n| H H H |\n---H---H---'` **Output**: `H12` Previous version that uses regex (68): ``` import re r=re.findall('[C-S]',(input()*2)[:-9]) print r[0]+`len(r)` ``` Thanks to Sp3000 for golf help. [Answer] # APL, 39 bytes I'm sure this could be made much shorter, but it's a start. ``` f←{X←(∊⍵[⍳46]⍵)∩'HDCS'⋄((⊃X),0⍕⍴X)~' '} ``` This creates a named monadic function that accepts an input string and returns a string containing the card's suit and value. You can [try it online](http://tryapl.org/?a=f%u2190%7BX%u2190%28%u220A%u2375%5B%u237346%5D%u2375%29%u2229%27HDCS%27%u22C4%28%28%u2283X%29%2C0%u2355%u2374X%29~%27%20%27%7D&run)! Explanation: ``` f ← { ⍝ Define the function f. X← ⍝ Assign X as (∊⍵[⍳46]⍵) ⍝ the right input duplicated, no center line ∩ 'HDCS' ⍝ intersect 'HDCS'. ⍝ X is now a vector like 'HHHHHH'. ((⊃X) ⍝ Return the first element of X , ⍝ concatenated with 0⍕⍴X) ⍝ the length of X as a string ~' ' ⍝ without a space. } ``` Suggestions are welcome as always! [Answer] # J, 26 bytes ``` (],[:":@(+/)]=[,_9}.[)4{~. ``` Usage: ``` ((],[:":@(+/)]=[,_9}.[)4{~.) input H12 ``` Reading the code from left to right: * We get the suit from the input as the 5th distinct character in it (`4{~.`). * Count (`+/`) the number that character occurs total in the input (`[`) and the input without the last 9 characters (`_9}.[`). * Finally we concatenate the suit (`]`) to the resulting sum's string representation (`":`) . [Answer] # Perl, 75 bytes ``` @r=();foreach ((<>)[2,2,3,3,4]){push@r,$1 while(/([CDSH])/g)}print $r[0].@r ``` Ungolfed version ``` @r=(); # Collect matches in this array foreach ((<>) # Read stdin as a single array of lines # Note that for a subroutine use @_ for (<>) [2,2,3,3,4]) { # Look at the 3rd, 4th rows twice, 5th row once push @r, $1 # Collect individual character matches while (/([CDSH])/g) # As long as one of the suits matches } print $r[0] # Each element of array is matching letter .@r # Array reference in scalar context gives length ``` [Answer] # Julia, 58 bytes ``` s->(m=matchall(r"[A-Z]",s*s[1:46]);join([m[1],length(m)])) ``` This creates an unnamed function that takes a string as input and returns the card's suit and value. To call it, give it a name, e.g. `f=s->(...)`. Ungolfed + explanation: ``` function f(s) # Find all alphabetic characters in the input joined with itself # excluding the second center line, which begins at the 47th # character m = matchall(r"[A-Z]", s * s[1:46]) # Take the first match and the number of matches as an array, # collapse the array into a string, and return it join([m[1], length(m)]) end ``` Suggestions are welcome as always! [Answer] # Bash + coreutils, 73 ``` sed '$q;s/.*/&&/'|fold -1|sort|uniq -c|sed -nr 's/ +(\w+) ([C-S])/\2\1/p' ``` ]
[Question] [ [Unary numbers](https://en.wikipedia.org/wiki/Unary_numeral_system) typically only represent nonnegative integers, but we can extend them to represent all integers as follows: * A positive integer N is represented as N `1`'s: `5 -> 11111` * A negative integer -N is represented as a `0` followed by N `1`'s: `-5 -> 011111` * Zero is represented as `0` We can then represent a list of these numbers unambiguously if we use `0` as the separator: ``` 3,-2,0,1 111,011,0,1 111 0 011 0 0 0 1 11100110001 ``` Your task: take a string representing such a list of signed unary numbers, and translate it into a list of decimal numbers. ## Details You may assume that the input is a complete list of signed unary numbers. In particular, your program will not have to handle 1) empty input or 2) input that ends with a separator. You may assume that the magnitude of each number will not exceed 127. For languages with maximum sizes of strings or lists, you may assume that the input and output will fit in your language's data structures, but your algorithm should theoretically work for a list of any size. Your program or function may perform I/O in any of the [standard ways](https://codegolf.meta.stackexchange.com/q/2447/16766). Input may be a string or a list of characters, single-character strings, integers, or booleans. You may use any two characters to represent `1` and `0`; if you don't use `1` and `0`, please specify which characters you're using. Output must be decimal numbers in any reasonable list format (in particular, there must be some kind of a separator between numbers). Negative numbers should be indicated with a minus sign, although if your language has a different format for negative integers I will also accept that. Zero may be represented in the output as `0` or `-0`. ## Test cases ``` 1 -> 1 0 -> 0 (or -0, and similarly for the other test cases) 011 -> -2 1101 -> 2,1 1100 -> 2,0 11001 -> 2,-1 110001 -> 2,0,1 11100110001 -> 3,-2,0,1 00000001 -> 0,0,0,-1 01111011111111001111111111111110111111111111111100111111111111111111111110111111111111111111111111111111111111111111 -> -4,8,-15,16,-23,42 01111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 -> -127 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ 70 bytes A function that takes a string as input and returns a string representation of a Python list. Zero can be represented both by `0` and `-0` (when it comes last): ``` lambda s:`map(len,s.split('0'))`.replace('0, ','-').replace('--','0,') ``` ### Explanation 1. [`split`](https://docs.python.org/2/library/stdtypes.html#str.split) the input string `s` on zeroes. 2. Take the [length](https://docs.python.org/2/library/functions.html#len) of each string in the resulting list (using [`map`](https://docs.python.org/2/library/functions.html#map)). That takes us a long way. Zeroes were separators after all. And the numbers were unary, so `len` conveniently converts those to decimal. But now we've messed up all the non-separator uses of `0`. Luckily, all non-separator uses were leading zeroes so they came after a separator-zero and gave us zero-length strings (`'00'.split('0') == ['', '', '']`). Those zero-length strings then also became `0` because of the `len`. 3. Turn the list into a string ([using "reverse quotes"](https://docs.python.org/2/library/functions.html#repr)), so we can fix up the mess more easily. 4. [`replace`](https://docs.python.org/2/library/string.html#string.replace) each zero that precedes another number by a negative sign on that number instead. That fixes the use of `0` as a sign but it breaks the literal zeroes. Literal zeroes were also preceded by a separator, so they've now become pairs of extra dashes on the next number. 5. `replace` each `--` back into a `0` element in the "list". [Answer] # [Retina](https://github.com/m-ender/retina), ~~23~~ 21 bytes ``` (.)0 $1 01 -1 1+ $.& ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ0/TgEvFUIHLwJBL15DLUJtLRU/t/39DLgOgCJBvaAAmDMAEhAmmQDwI2wACDEHqQcqhwADOggkYogtgiOBSiRsAAA "Retina – Try It Online") The first stage `(.)0<newline>$1<space>` matches any character followed by a `0`. The match is replaced by the first character followed by a space. This splits the string in the individual numbers. The second stage `01<newline>-1` replaces `0`'s before a block of `1`'s to to the `-` sign. The last stage `1+<newline>$.&` matches all blocks of `1`'s and replaces them with the length of the group. [Here](https://tio.run/##K0otycxL/P/fKkFDT9OAS8VQgcsqwcCQS9eQy1CbS0VP7f9/Q0NDAwMQNjAEAA) is an example with the output of the individual stages. [Answer] # Vim, 56 bytes ``` :s/\v(0?1*)0?/\1\r/g|%s/0/-/|%s/1*$/\=len(submatch(0)) D ``` [Try it online!](https://tio.run/##K/v/36pYP6ZMw8DeUEvTwF4/xjCmSD@9RrVY30BfVx9EG2qp6MfY5qTmaRSXJuUmliRnaBhoanK5/P9vAAGGAA "V – Try It Online") I haven't posted in vim in a while. I'm mostly using vim because V is a pain sometimes. Because the `count` command, which is perfect for getting the number of '1's on the line will overwrite any '0's on the line, so we can't negate it afterwards. Explanation: This is one byte shorter then the straightforward way: ``` :s/\v(0?1*)0?/\1\r/g :%s/0/- :%s/1*$/\=len(submatch(0)) D ``` due to command chaining. Since that one separates the commands, I'll use it for the explanation. ``` :s/ " Substitute " Search for... \v " Enable 'magic'. This determines whether certain atoms require a backslash or not. " Without it we would have: '\(0\?1*\)0\?', which is 2 bytes longer 0? " An optional 0 1* " Followed by any number of '1's ( ) " (call that group 1) 0? " Followed by another optional 0 / " Replace it with... \1 " Subgroup 1 \r " A newline /g " Do this for every match on the current line. ``` Now, each signed unary number is on an individual line. Using '11100110001' as an example, at this point we'll have: ``` 111 011 0 1 :%s/0 " Replace every 0 /- " With a dash :%s/1*$/ " Replace every run of 1's at the end of a line \=len(submatch(0)) " With the length of said run ``` Since we added newlines at the end of each match, we had an empty line before running that. After running that, we'll have a '0' (because it matched a run of 0 '1's). So we just call `D` to delete this line, leaving it blank [Answer] # [Haskell](https://www.haskell.org/), ~~68~~ 66 bytes ``` f(x:r)|(a,b)<-span(>0)r=([(0-),(1+)]!!x$sum a):[z|_:t<-[b],z<-f t] ``` [Try it online!](https://tio.run/##dUvLCoMwELz7FSv0kFAju1dRv6B/IFIija1UQ4gRRPz31EfbQ4sDOzs7M/uQ/VO1rfc1GxPLZyajiqeiN1KzHLnNWMFQ8IjRmZdhOJ76oQPJk2Kar4lLRVGV0ZSKGlzpO9loyOCu3KXRCvI8A2Mb7SCGeplOGmaVvMVmsIovMawPngIMkCggwo1wo11ua712jTto7a/1N/CrPgb9Gn/OUfMYLw "Haskell – Try It Online") Takes input as a list of zeros and ones. Example usage: `f [0,0,0,1,1]` yields `[0,-2]`. **Explanation:** The pattern matching in `f(x:r)|(a,b)<-span(>0)r` binds `x` to the first element of the input, `a` to a (potentially empty) list of following `1`s, and `b` to the rest of the input. Given an input `[0,1,1,1,0,0,1]`, we get `x=0`, `a=[1,1,1]` and `b=[0,0,1]`. The current number is then either the sum of `a` negated if `x=0`, or the sum of `a` plus one if `x=1`. This is achieved by indexing with `x` into a list containing a negation and increment function, and applying the resulting function to the sum of `a`: `[(0-),(1+)]!!x$sum a`. The rest list `b` is either empty or contains a separating zero and the next number. The list comprehension `[z|_:t<-[b],z<-f t]` tries to match `b` on the pattern `_:t`, that is forget the head element and bind the rest of the list to `t`. If `b` is empty this match fails and the list comprehension evaluates to `[]`, which is the base case for the recursion. Otherwise the function `f` is recursively applied to `t` and the list comprehension evaluates to all elements `z` from the result of `f t`. [Answer] # [Perl 5](https://www.perl.org/), 40 + 1 (`-n`) = 41 bytes ``` print'-'x/00/.y/1//.$"for"0$_"=~/00?1*/g ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRF1XvULfwEBfr1LfUF9fT0UpLb9IyUAlXsm2Dihsb6iln/7/v6GhoYEBCBsY/ssvKMnMzyv@r@trqmdgaPBfNw8A "Perl 5 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~20 18 17 15~~ 14 bytes ``` Γ~:?Σṁ_Πȯ₀tΣġ/ ``` [Try it online!](https://tio.run/##yygtzv7//9zkOiv7c4sf7myMP7fgxPpHTQ0l5xYfWaj/////aAMdQyhEsBAimGLoKgwJqiCshlQzyYCxAA "Husk – Try It Online") ## Explanation ``` Γ~:?Σṁ_Πȯ₀tΣġ/ Input is a list, say x = [0,1,1,0,0,0,1,1] ġ Group by / division. This splits x right before each 0: [[0,1,1],[0],[0],[0,1,1]] Γ Deconstruct into head y = [0,1,1] and tail z = [[0],[0],[0,1,1]] ?Σṁ_Π Apply to y: Π Product: 0 ?Σ If that is nonzero, take sum of y, ṁ_ else take sum of negated elements of y: u = -2 ȯ₀tΣ Apply to z: Σ Concatenate: [0,0,0,1,1] t Drop first element: [0,0,1,1] ₀ Recurse: [0,2] ~: Tack u to the front: [-2,0,2] ``` The splitting works like this. `ġ/` splits its argument between each pair of elements `a,b` for which `/a b` is falsy. `/a b` is division with flipped arguments, so `b` divided by `a`. The relevant values in this program are these: * `/1 1` gives `1` (truthy). * `/1 0` gives `0` (falsy). * `/0 1` gives `Inf` (positive infinity, truthy). * `/0 0` gives `Any` (a special NaN-like value, falsy). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 80 bytes ``` StringCases[#<>"0",x_~~Shortest@y___~~"0":>(If[x=="0",-#,#+1]&)@StringLength@y]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P7ikKDMv3TmxOLU4WtnGTslASacivq4uOCO/qCS1uMShMj4eyAUKW9lpeKZFV9jagpToKusoaxvGqmk6QPT7pOall2Q4VMaq/Q8A8ksctNL0Haq5uJQMlXS4QBqAhCGYbWhoAKMNYDRcAMYCicG5BhBgCDUEZAAUGMBZMAFDdAEMEVwqcQMlLq7a/wA "Wolfram Language (Mathematica) – Try It Online") Abuses the mechanic of `StringCases`, since it does not check overlapping patterns. Since we search from left to right, without overlaps, we always get only the integers we need. ## Explanation ``` #<>"0" ``` Append a zero at the end ``` StringCases ``` Find all of the following pattern... ``` x_~~Shortest@y___~~"0" ``` A single character (call it `x`), followed by the shortest possible zero-length or longer string (call it `y`), followed by a zero. ``` (If[x=="0",-#,#+1]&)@StringLength@y ``` Apply to matching pattern: take the length of `y`. If `x` is zero, then negate the value. Else, increment one. This covers `00` as well, since `y` would be an empty string, and we would compute `-0` ( `== 0`). [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 94 (70?) bytes ``` ([]){{}({(<()>)()}{}(<>)<>{<([{}]<>{})><>}) {{}<>([{}])(<>)}{}{}([])}{}<>([]){{}({}<>)<>([])}<> ``` [Try it online!](https://tio.run/##nYwxCoAwDEWv4pgMgt1DLlI61EEQxcE15Ow1rYWCDkX5y8/j/cxnXI9x2eOWEviAIgoCBMgIqHYQI7EQeNFgRZGJNWvEhWE2TDTV5nrz@kfLuHDilKbB1bTWyJs9Ddc1@s7Xnz9yAQ "Brain-Flak – Try It Online") This is actually surprisingly terse for brain-flak. Here is a commented/readable version: ``` ([]) { #Pop the Stack height {} ( #If there isn't a leading 0, evaluate to 1... { (<()>) () } #Pop the 0 {} #Push a 0 onto the alternate stack (<>) <> #Run of '1's { #Decrement the alternate stack <([{}]<>{})> <> } #And push it here ) #Was there a not leading 0? { {} #Invert the value on the alternate stack <>([{}])(<>) } #Pop 2 zeros {}{} ([]) }{}<> #Push stack height ([]) #Reverse the stack { {} ({}<>) <>([]) }<> ``` If the output can be in reverse, we can do this for 70 instead: ``` ([]){{}({(<()>)()}{}(<>)<>{<([{}]<>{})><>}){{}<>([{}])(<>)}{}{}([])}<> ``` [This tip of mine](https://codegolf.stackexchange.com/a/146444/31716) is *almost* perfect for this situation. But it doesn't quite work since we have to push a 0 before doing the operation (counting the '1's), and the operation happens in a loop. The shortest I could come up with utilizing this tip is: ``` ([]){{}({(<()>)()}{}(<>)<>{<([{}]<>{})><>}) {{}<>([{}])(<>)}{}{}(<>())<>([])}{}<>{{}({}<>)<>}<> ``` which is also 94 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) There must be a better way... ``` ®ḢN$Ḣ©?ṄEȧ ṣ0L€ÇL¿ ``` A full program printing each number followed by a linefeed. **[Try it online!](https://tio.run/##y0rNyan8///Quoc7FvmpAIlDK@0f7mxxPbGc6@HOxQY@j5rWHG73ObT/////0QY6CoZICI2LJoVHFpcWQ9K1kKGLWrZTE8UCAA "Jelly – Try It Online")** ### How? ``` ®ḢN$Ḣ©?ṄEȧ - Link 1, print first number and yield next input: list of numbers, X - e.g. [8,0,15,16,...] or [0,4,8,0,15,16,...] ? - if... Ḣ - condition: yield head and modify 8([0,15,16,...]) 0([4,8,0,15,16,...]) © - (copy to register) 8 0 ® - then: recall from the register 8 $ - else: last two links as a monad: Ḣ - yield head and modify 4([8,0,15,16,...]) N negate -4 Ṅ - print that and yield it 8 -4 E - all equal (to get 0 to be truthy) 1 1 ȧ - AND the (modified) input [0,15,16,...] [8,0,15,16,...] - (ready to be the input for the next call to this link) ṣ0L€ÇL¿ - Main link: list e.g. [0,1,0,0,0,0,1,1] ṣ0 - split at zeros [[],[1],[],[],[],[1,1] L€ - length of €ach [0,1,0,0,0,2] ¿ - while... L - condition: length 1 1 1 0 ([0,1,0,0,0,2], [0,0,0,2], [0,2], []) Ç - action: call the last link (1) as a monad -1 0 -2 ( - 1 - 0 - 2) ``` [Answer] # [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), ~~252~~ 237 bytes ``` N Count i while _/48 { Count n while 48/_ { Write 45 50+N } _+49/_*50 Count u while _%50/49 { _+100-_%50+N } _/50-1 Count h while _/200 { Write _/200+48 _%200+1 } Count t while _/20+_%2 { Write _/20+48 _%20-_%2 } Write _/2+48 Write 9 N } ``` Uses `-0`. Outputs numbers separated by tab characters, with a trailing tab. [Try it online!](https://tio.run/##VY4xC8MgEIV3f4VLlkrwGRR07p61ozShEKGkUAwdQn@7PauRdjnuvXvf3V3neZpSGtn5sa2RB/5awv3GvdSW79Vcq6mt9GReniGSMMxAjOzNvNBO@pNBjW/Hjs5AakeEFwrosy6ANOhVTS/t4gC07V8ltGW@y40iqsTjT1zQ8I84ADo1ENEG2S/CMXogJUAplQuoAB8 "Acc!! – Try It Online") Amount of time writing the actual algorithm: 20 minutes. Amount of time debugging my decimal output code: 45 minutes. :^P ### With comments I don't know if these comments explain the code very well--they're based on my notes to myself while I was writing it, so they assume some understanding of how *Acc!!* works. If anything needs more explanation, let me know and I'll try to make it clearer. ``` # We partition the accumulator _ as [number][flag][nextchar] # [flag] is a 2-value slot and [nextchar] a 50-value slot # So [nextchar] is _%50, [flag] is _/50%2, [number] is _/100 # [flag] is 1 if we're in the middle of reading a number, 0 if we're between numbers # It is also used for outputting as decimal (see below) # Possible input characters are 0, 1, and newline, so [nextchar] is 48, 49, or 10 # Read the first character N # Loop while the character we just read is 0 or 1 and not newline Count i while _/48 { # What we do in the loop depends on the combination of [flag] and [nextchar]: # 0,48 (start of number, read 0) => write minus sign, [flag] = 1, read another char # _,49 (read 1) => increment [number], [flag] = 1, read another char # 1,48 (middle of number, read 0) => write/clear [number], status = 0, read another # char # 1,10 (middle of number, read <cr>) => ditto; the next read will be 0 for eof, which # means the acc will be less than 48 and exit the loop # Process leading 0, if any Count n while 48/_ { # acc is 48: i.e. [number] is 0, [flag] is 0, [nextchar] is 48 (representing a 0) # Output minus sign Write 45 # Set [flag] to 1 (thereby exiting loop) and read [nextchar] 50+N } # If number starts with 1, then we didn't do the previous loop and [flag] is not set # In this case, acc is 49, so we add (50 if acc <= 49) to set [flag] _+49/_*50 # Process a run of 1's Count u while _%50/49 { # [nextchar] is 49 (representing a 1) # Increment [number] and read another _+100-_%50+N } # At this stage, we know that we're at the end of a number, so write it as decimal # This is "easier" (ha) because the number has at most three digits # We shift our partitioning to [number][flag] and set [flag] to 0 _/50-1 # Output hundreds digit if nonzero # Since [number] is _/2, the hundreds digit is _/200 Count h while _/200 { Write _/200+48 # Mod 200 leaves only tens and units; also, set [flag] to 1 _%200+1 } # Output tens digit (_/20) if nonzero OR if there was a hundreds digit # In the latter case, [flag] is 1 Count t while _/20+_%2 { Write _/20+48 # Mod 20 leaves only units; clear [flag] if it was set _%20-_%2 } # Write units unconditionally Write _/2+48 # Write a tab for the separator Write 9 # Read another character N } ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~96~~ 92 bytes ``` lambda s:[[len(t),-len(t)+1]['1'>t]for t in s.replace('10','1 ').replace('00','0 ').split()] ``` [Try it online!](https://tio.run/##dcxBDoIwEAXQtZyiu2ljNTMuSWTJJZAFCo0ktTS0G09faUBKNMzm/7403779czCXoK63oJvXvW2Yy6tKd4Z7IU9zHqmugKDwtRpG5llvmDuPndXNo@NACBKIgUiEkTCSs7r3XNSh7RQruRN5drBjbzxzEq4FSDVZlpXTDIgYuAQtbyJMDVPbYOrRN4Dz0ToZx5bDtX2BfuFP9n7uH4jwAQ "Python 2 – Try It Online") Thx to ovs and DLosc for 2 bytes each. [Answer] # [R](https://www.r-project.org/), 119 bytes ``` function(x){n=nchar y=regmatches(x,regexec("(0?)(1*)0?([01]*)",x))[[1]] cat((-1)^n(y[2])*n(y[3]),"") if(y[4]>0)f(y[4])} ``` [Try it online!](https://tio.run/##dY3BCgIhEIbvPsacZsRAq6vtg4iBiLZ7yMAMXKJnN9uoQ7H/Yeb7PwYmt6pBqp5lLPClj1C/4s@sXa4HWNQt3pIv0yVhpXvSyY8us1nncDq74sdwxSp6CTV4BJQDoeIkBzRSWU4gKpExylrmXUHcKDomnM3WEn/tnSUBQGyKveztQdIb6NFif9ie "R – Try It Online") The code uses [this solution from stackoverflow](https://stackoverflow.com/a/16563900) for a related problem (Thanks to jeales for the idea). The output is a space-separated string printed to stdout. [Answer] # [sed](https://www.gnu.org/software/sed/), 227 bytes ``` s/^.o*/<&>/ :a s/>z\(.o*\)/><\1>/ ta :b s/z>/0>/g y/z/-/ s/oooooooooo/x/g s/ooooooooo/m9/g s/oooooooo/m8/g s/ooooooo/m7/g s/oooooo/m6/g s/ooooo/m5/g s/oooo/m4/g s/ooo/m3/g s/oo/m2/g s/o/m1/g s/x\([^xm]\)/x0\1/g s/m//g y/x/o/ tb ``` [Try it online!](https://tio.run/##tY47DsIwEET7PQgCpDCEPwj5IhikRCCqZYsEyezlg2MHCKAUFExhv3mewsXpmJwv16oqcBjJENueAW0yKmDU9r2xA5itTb0tM9rk/kENxgZnukGRwAt5Bs77lgCv3wR41e7gZauCF68Gnj8LePZg8LRB8CQSOA3gbH93cLz3H3ZjGx0j/NP5FZV5VQkpqQiJaDg0HBHDVbfIGiP1vp43UZX3fPbvReeyO/TD9i@hF94B "sed – Try It Online") ## Usage 0 and 1 for input are replaced with z and o respectively. Input is given from stdin, on every line. ## With comments ``` # first integer s/^.o*/<&>/ # find each item :a s/>z\(.o*\)/><\1>/ ta # below: to decimal :b # to zero s/z>/0>/g # minus sign y/z/-/ # to decimal others # m letter indicates that converting a digit is done s/oooooooooo/x/g s/ooooooooo/m9/g s/oooooooo/m8/g s/ooooooo/m7/g s/oooooo/m6/g s/ooooo/m5/g s/oooo/m4/g s/ooo/m3/g s/oo/m2/g s/o/m1/g # not converted yet? then to 0 s/x\([^xm]\)/x0\1/g s/m//g y/x/o/ # repeat until every unary is converted tb ``` [Answer] # QBasic, ~~88~~ 86 bytes ``` 1u$=INPUT$(1) z=u$<"1 IF n*z THEN?(1-2*s)*(n-s):s=0:n=0ELSE s=s-z:n=n+1 IF"!"<u$GOTO 1 ``` This was fun. Multiple revisions starting from a 107-byte version resulted in one of the most obfuscated bits of QBasic I think I've ever written. *(Edit: Oddly enough, I was able to golf 2 bytes by making the code clearer.)* Note: this program reads user input one character at a time without echoing it to the screen (a result of using `INPUT$(1)` instead of the usual `INPUT` statement). So as you're typing, you won't see the 1's and 0's, but the decimal numbers will appear as they are calculated. Make sure to hit `Enter` at the end of the input to see the last number and end the program. ### Ungolfed version ``` sign = 0 num = 0 DO digit$ = INPUT$(1) isZero = (digit$ < "1") IF num > 0 AND isZero THEN PRINT (1 - 2 * sign) * (num - sign) sign = 0 num = 0 ELSE IF isZero THEN sign = 1 num = num + 1 END IF LOOP WHILE "!" < digit$ ``` ### Explanation (AKA "What?? That still makes no sense!") The base strategy is to run a loop that grabs one character from `INPUT$(1)` each time through, does stuff with it, and keeps looping as long as the character has an ASCII value greater than that of `!` (i.e., wasn't a newline). We keep track of numbers-in-progress using two variables. `num` is the number of characters in the current signed unary number (including any leading zero). `sign` is `1` if the number had a leading zero, `0` if not. Both of these need to be initialized to `0`, which is great for the golfed version because numeric variables in QBasic are automatically initialized to `0`. Whenever we read a character, the first thing is to determine whether it's `1` or `0`. We'll use this result twice, so we store it in `isZero`. Technically, that name is misleading, since the value will also be truthy if the character is a newline. Note that truthy in QBasic is `-1` and falsey is `0`. Now, if we're in the middle of reading a number (`num > 0`) and we hit a zero or end of input (`isZero`), we need to calculate which number we've finished reading. * `sign` stores `0` for positive, `1` for negative. To get `1` for positive and `-1` for negative, we need `1-2*sign`. * `num` stores the correct magnitude for positives but one more than the magnitude for negatives (since it includes the sign marker). So we can use `num-sign` for the magnitude. Multiply these together and print; then reset `sign` and `num` to `0` in preparation for reading the next number. Otherwise (if we haven't hit a zero, or if we've hit a zero at the beginning of a number), we update `sign` and `num` as follows: * `sign` becomes `1` if we're looking at a leading zero; otherwise, if we're looking at a one, it stays at whatever it already was. The golfed code is `s=s-z`, which amounts to the same thing: + If this is a leading zero, `z` is `-1`. Since `s` is guaranteed to be `0` (because this is the start of a new number), `s-z` will be `1`. + If this is a one, `z` is `0`. Then `s-z` stays at whatever value `s` had previously. * `num` is incremented. That's it! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ݬ<\œp$ḊLCṛ¡ḢƊ€ ``` [Try it online!](https://tio.run/##y0rNyan8///o7kNrbGKOTi5Qebijy8f54c7ZhxY@3LHoWNejpjX/bR81zDU83O6tAuRE/v@vZKiko2QAwoYglqGhAZQygFIwLpQBEoHxDCDAEKIbpBUKDOAsmIAhugCGCC6VuAHM2gEESgA "Jelly – Try It Online") Although it's something of an improvement over the previous solution, this feels clumsy. (Though not as clumsy now that it doesn't use `k`.) Input as a list of zeroes and ones. ``` Ż Prepend a leading zero to the input. ¬ Flip 0 <-> 1. œp$ Split that around the corresponding locations of truthy elements of <\ it cumulatively reduced by greater than. Ḋ Remove the leading empty slice, Ɗ€ then for each remaining slice: L take the length, C and subtract it from 1 ¡ a number of times equal to ṛ Ḣ the first element. ``` [Answer] # JavaScript (ES6), 60 bytes Returns a space-separated list of integers. ``` s=>(0+s).replace(/00?1*/g,s=>(l=s.length,+s[1]?l-1:2-l)+' ') ``` ### Test cases ``` let f = s=>(0+s).replace(/00?1*/g,s=>(l=s.length,+s[1]?l-1:2-l)+' ') console.log(f("1")) // 1 console.log(f("0")) // 0 console.log(f("011")) // -2 console.log(f("1101")) // 2,1 console.log(f("1100")) // 2,0 console.log(f("11001")) // 2,-1 console.log(f("110001")) // 2,0,1 console.log(f("11100110001")) // 3,-2,0,1 console.log(f("00000001")) // 0,0,0,-1 console.log(f("01111011111111001111111111111110111111111111111100111111111111111111111110111111111111111111111111111111111111111111")) // -4,8,-15,16,-23,42 console.log(f("01111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) // -127 ``` [Answer] # [Lua](https://www.lua.org), 58 bytes ``` (...):gsub("(0?)(1*)0?",function(s,n)print(#n-2*#s*#n)end) ``` [Try it online!](https://tio.run/##yylN/P9fQ09PT9Mqvbg0SUNJw8BeU8NQS9PAXkknrTQvuSQzP0@jWCdPs6AoM69EQzlP10hLuVhLOU8zNS9F8////waGQAAmwAw4CyZgiC6AIYJLJW4AAA "Lua – Try It Online") Full program, takes input from the command line and prints the numbers to stdout separated by newlines. ]
[Question] [ In the language [Nim](https://nim-lang.org "Nim programming language"), the rules for differentiating identifiers are [slightly more relaxed](https://nim-lang.org/docs/manual.html#lexical-analysis-identifier-equality "Nim identifier equality") than most other languages. Two identifiers are equivalent or address the same variable if they follow **these rules**: * the first character of both **are the same** *(case sensitive)* * both strings are the same *(case **in**sensitive)* after removing **all instances** of the characters `-` and `_` ## Challenge Write a **program/function** that takes **two strings** that represent Nim identifiers and output a truthy or falsey value based on **whether or not they are equivalent** by the rules above. ### Specifications * [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods "Default for Code Golf: Input/Output methods") **apply**. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Loopholes that are forbidden by default") are **forbidden**. * The strings will **only contain ASCII printables**. You **do not** need to check if it's a valid identifier. * The strings may be taken as two separate inputs, list of strings, etc. (you know the drill) * Empty strings **need not** be handled. * The output **must be consistent** for both truthy and falsey values. * This challenge is not about finding the shortest approach in all languages, rather, it is about finding the **shortest approach in each language**. * Your code will be **scored in bytes**, usually in the encoding UTF-8, unless specified otherwise. * Built-in functions that perform this task are **allowed** but including a solution that doesn't rely on a built-in is encouraged. * Explanations, even for "practical" languages, are **encouraged**. ## Test cases ``` Input Output count, Count falsey lookMaNoSeparator, answer falsey _test, test falsey test, tset falsey aVariableName, a_variable_name truthy numbers_are_cool123, numbersAreCool123 truthy symbolsAre_too>_>, symbols_areTOO>> truthy ``` ## Ungolfed reference implementation This is written in Nim, itself. ``` import strutils, re proc sameIdentifier(a, b: string): bool = a[0] == b[0] and a.replace(re"_|–", "").toLower == b.replace(re"_|–", "").toLower ``` [Answer] ## JavaScript (ES6), ~~62~~ 61 bytes *Saved 1 byte thanks to [@JohanKarlsson](https://codegolf.stackexchange.com/users/55822/johan-karlsson)* Takes input in currying syntax `(a)(b)`. Returns a boolean. ``` a=>b=>(r=s=>s[0]+s.replace(/-|_/g,'').toUpperCase())(b)==r(a) ``` ### Test cases ``` let f = a=>b=>(r=s=>s[0]+s.replace(/-|_/g,'').toUpperCase())(b)==r(a) console.log(f("count")("Count")) // falsey console.log(f("lookMaNoSeparator")("answer")) // falsey console.log(f("_test")("test")) // falsey console.log(f("aVariableName")("a_variable_name")) // truthy console.log(f("numbers_are_cool123")("numbersAreCool123")) // truthy ``` [Answer] # [Python 3](https://docs.python.org/3/), 76 bytes ``` lambda a,b:f(*a)==f(*b) f=lambda f,*r:[f+k.lower()for k in r if~-(k in'-_')] ``` [Try it online!](https://tio.run/##LYmxDsIgFAB3v@Jt8Cq4uDVhYOno4KqGPCIvklJoSFPj4q9jmzjd5W7@LK@Sz20w95Zo8k8CUr5n2REas8Hjgc3/sOpqf@PjeErlHapELhVGiBkqRP5qubvQTuCjzTXmRQ5SkF5tjeRTcBeaglAgrFvp6vamg87WbRWx/QA "Python 3 – Try It Online") -1 byte thanks to notjagan -3 bytes thanks to Wheat Wizard [Answer] # [Actually](https://github.com/Mego/Seriously), 15 bytes ``` ⌠p"-_"(-Σùo⌡M═Y ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9Rz4ICJd14JQ3dc4sP78x/1LPQ99HUCZH//yslhiUWZSYm5aT6JeamKukoKCXGl0FF4vNAQgA "Actually – Try It Online") Fun fact: this works with any number of inputs (it always returns truthy for less than 2 inputs). Explanation: ``` ⌠p"-_"(-Σùo⌡M═Y ⌠p"-_"(-Σùo⌡M for each input: p separate the first character "-_"(- remove all dashes and underscores from the rest of the string Σù concatenate the list from the last operation and lowercase the string o append it to the first character ═Y are none of the elements unique? ``` [Answer] ## C++, ~~288~~ 248 bytes -5 bytes thanks to Zacharý ``` #include<string> #include<algorithm> #define E(a,v)a.erase(std::remove(a.begin(),a.end(),v),a.end()); #define F(a)for(auto&c:a)c=toupper(c); int e(std::string&a,std::string&b){if(a[0]!=b[0])return 0;E(a,45)E(b,45)E(a,95)E(b,95)F(a)F(b)return a==b;} ``` Thanks you, Preprocessor. Also, this code takes advantage of the fact that in C++ the rule to cast int to bool is `int_var!=0` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` qFm[hd-r0d"-_ ``` [Try it online!](http://pyth.herokuapp.com/?code=qFm%5Bhd-r0d%22-_&test_suite=1&test_suite_input=%5B%22count%22%2C+%22Count%22%5D%0A%5B%22lookMaNoSeparator%22%2C+%22answer%22%5D%0A%5B%22aVariableName%22%2C+%22a_variable_name%22%5D%0A%5B%22numbers_are_cool123%22%2C+%22numbersAreCool123%22%5D&debug=0) # Explanation ``` qFm[hd-r0d"-_ m For each value in the input (which is a list of two strings): [ Create a list consisting of hd the first character of each value -r0d"-_ and the lowercase version of the value without "-" or "_" qF Fold over equivalence; checks to see if both lists are the same ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` εćs„-_SKl«}Ë ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3NYj7cWPGubpxgd75xxaXXu4@///aKXk/NK8EiUdBSVnMCMWAA "05AB1E – Try It Online") -1 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). Theoretically, `εćs„-_-«}Ë` should've worked for 10 bytes, but unfortunately this behavior is deprecated for now. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ḟ⁾-_Œl,Ḣµ€E ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmPGvfpxh@dlKPzcMeiQ1sfNa1x/f//f7RSom6ZY1FmYlJOarxfYm6qko5SYnxZYlA8SEg3VTfPMR4oGAsA "Jelly – Try It Online") -2 bytes thanks to Erik the Outgolfer -1 byte thanks to Jonathan Allan [Answer] # [Ruby](https://www.ruby-lang.org/), ~~86~~ ~~64~~ ~~63~~ ~~61~~ 51 bytes ``` f=->x{x[0]+x.upcase.delete("-_")} ->x,y{f[x]==f[y]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W166iuiLaIFa7Qq@0IDmxOFUvJTUntSRVQ0k3Xkmzlgsor1NZnRZdEWtrmxZdGVv7vwBDKFopUbfMsSgzMSknNd4vMTdVSUcpMb4sMSgeJKSbqpvnGA8UjP0PAA "Ruby – Try It Online") This ~~feels really long~~ still feels a bit long. I would appreciate the help of any Ruby gurus out there in making this at least a bit shorter. [Answer] # CJam, 20 bytes ``` {_"-_"f-:el:=\:c:=*} ``` Takes input in the form of ["string1","string2"]. [Try it Online](http://cjam.aditsu.net/#code=ll%5D%7B_%22-_%22f-%3Ael%3A%3D%5C%3Ac%3A%3D*%7D~&input=numbers_are_cool123%0AnumbersAreCool123) (testing version) ``` { _ e# make copy of input "-_"f- e# remove all "-" and "_" from both words in copy :el e# convert words in copy to lowercase := e# 1 if both words in copy are equal, 0 if not \ e# move original version of input to top of stack :c e# convert each word in original input to only 1st character := e# 1 if both characters from original input are equal, 0 if not * e# multply the two numbers we obtained. If and only if both are 1 (true) we return 1 (true) } ``` [Answer] # [Haskell](https://www.haskell.org/), ~~85~~ ~~78~~ ~~76~~ ~~71~~ 68 bytes *2 bytes saved thanks to Ørjan Johansen* ``` import Data.Char s(a:x)=a:[toLower a|a<-x,all(/=a)"-_"] x!y=s x==s y ``` [Try it online!](https://tio.run/##LYzBasMwEETv@QpF9GCB09L2FipDcY9tcmjpJQQxNoKYSFqzklsb@u9uZHzZXd68nQvi1To3z53viZN4Q8J9fQFvYoH9qDT2p0Tv9GtZ4A8vu7GEc8WDhpI7I8@bcTvpKEZ9G9PshBanQrY0hCRLIevlUGUhHdH1Awf6tD0YiViWEiHeapfYJBuXj2Vngm9wh8bZA7zNCczPSkzIKEth8I3laMDWtETu8ek5qyt@ZVuvMMtx8g25TE0iqkyV1RXmhq/jsaqkOm88uqB77kK68@iLIbQD81RslXLzPw "Haskell – Try It Online") Errors on the empty string. [Answer] # [Python 2](https://docs.python.org/2/), 72 bytes ``` lambda x,y:r(x)==r(y) r=lambda x:x[0]+x[1:].lower().translate(None,"-_") ``` [Try it online!](https://tio.run/##RZDBaoQwFEX3fsUjICTUDp3pTlAos66zaOnGSogzkUpjnrxkpvr11kg6zSaXk3vPIuPsv9Aelq74XIwa2ouCKZtz4pMoCuKzSKj44/lUPzUPU73Pm53BH01c7Dwp64zymldodcYeJROLKeoE1sPZGa/WswzYcQsii9wgfr@qCt/0qEh5pNBZTav0vyS9dtt4u@9YfSjqVWt0pQa97eQtEmkDujftdWg1OalIyzOi2R@eQz/iF9LHCO8LNw8tmvAkPWIpy9CPMGjeT6eyZCJpkqRDAr7@lYDegsk3wUi99asmdcBTJ@DmIMYcUmKQhgWEz81gDmFeQ7dZhFh@AQ "Python 2 – Try It Online") Won't work with Python 3 because of the new `translate` syntax. [Answer] # Excel, 105 bytes ``` =AND(CODE(A1)=CODE(B1),SUBSTITUTE(SUBSTITUTE(A1,"_",""),"-","")=SUBSTITUTE(SUBSTITUTE(B1,"_",""),"-","")) ``` CODE() returns numeric code of first character. String comparison in Excel is case insensitive. [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ¤=§,←(m_ω-"-_ ``` [Try it online!](https://tio.run/##yygtzv7//9AS20PLdR61TdDIjT/fqaukG//////EsMSizMSknFS/xNzU/4nxZVBufB6QDwA "Husk – Try It Online") Builds for each string a pair consisting of the first character of the string and the whole string lowercased and with all occurrences of -/\_ removed. Then checks if the two pairs are equal. A particularity is that `-` in Husk is set difference (i.e. it removes only the first occurrence found): in order to remove all occurrences, the fixed point of `-"-_` is found with `ω-"-_`. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 25 bytes ``` g ¥Vg ©Uu k"_-" ¥Vu k"_-" ``` ~~Checks case-insensitive string equality by removing all characters in word 2 from word 1, and removing the `-_` characters; that results in an empty string (`""`) if the words are equal.~~ *Thanks Ørjan Johansen for pointing out the problem with this.* Checks first-char equality and if the uppercased inputs are equal after removing `_-`. [Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=ZyClVmcgqVV1IGsiXy0iIKVWdSBrIl8tIg==&inputs=ImNvdW50IgoiQ291bnQi,Imxvb2tNYU5vU2VwYXJhdG9yIgoiYW5zd2VyIg==,Il90ZXN0IgoidGVzdCI=,ImFWYXJpYWJsZU5hbWUiCiJhX3ZhcmlhYmxlX25hbWUi,Im51bWJlcnNfYXJlX2Nvb2wxMjMiCiJudW1iZXJzQXJlQ29vbDEyMyI=,InN5bWJvbHNBcmVfdG9vPl8+Igoic3ltYm9sc19hcmVUT08+PiI=,InRlc3QiCiJ0c2V0Ig==) ## Explanation Implicit input: `U` and `V` are input strings ``` g ¥Vg ``` Check if first letter of `U` (implicit) equals (`¥`) the first char of `V`. ``` ©Uu k"_-" ¥Vu k"_-" ``` And (`©`) check if `U`, uppercased (`u`) and with `_-` removed (`k`), equals (`¥`) the same for `V`. Implicitly return the boolean result. [Answer] # [R](https://www.r-project.org/), 76 bytes ``` function(l)(g=substr(l,1,1))[1]==g[2]&(h=tolower(gsub('-|_','',l)))[1]==h[2] ``` Anonymous function that takes input as a list of two strings. Takes advantage of the fact that R's string operations, while quite long in # of characters, are vectorized. Additionally wrapping an assignment in parentheses will bind the variable, so `(g=substr(l,1,1))` retains a variable to be reused later in the line and similarly for `h`. R returns the last evaluated expression as function output. Ungolfed: ``` function(l){ g <- substr(l,1,1) h <- tolower(gsub("_|-","",l)) (g[1]==g[2])&(h[1]==h[2]) } ``` [Try it online! (all test cases)](https://tio.run/##RY0xT8MwEIV3fkUmbEvukLKSSKgz7UDFUlWnS3RJKxwfOjsgJP57sKkD00nf@947WYbqcVMtw@z7eGWvndFjE@YuRNHO1rY25lSfm2Y8bc/3@tJEdvxJosfkaLX5BmWVss4U7ZK0ZdC9VpFCVLZSx3RBGXP3Sx3z2zPu@YXeUTCypDr6kBb/FLg1bwMrXFmgf4avKFfsHO1xovwK4aMQ8Bmtop@njiQACkHP7OrtQ9YLfhLaFbgWwtfUscsJROYW2qwXmFeOh0PbJnv5AQ "R – Try It Online") [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 10 bytes ``` …≈¿ᶴ-_½-ʀ≈ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLigKbiiYjCv+G2tC1fwr0tyoDiiYgiLCIiLCJbXCJDb3VudC1cIiwgXCJDb3VudF9fXCJdXG4iLCIzLjQuMCJd) [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ 73 bytes -6 bytes thanks to @notjagan: check the length of set of all reduced names is 1 or not. ``` lambda*l:len({x[0]+re.sub('-|_','',x[1:].lower())for x in l})<2 import re ``` [Try it online!](https://tio.run/##bY49b8JADIZ3fsVtlysJKmFDZYiYYaBSF4pODjhqxMWOnAtN1fa3pz0U8SHhyXrsx6/rL//BlPbF4r13UOUHeHJzhxR9d9vn3Vhw0rR5pJMfq2Ot4247ne8mjj9RImMKFtWpkpT7NS/pqKxqFq8E@1pK8qqI9J5b8jpWenluzOgycczHFaz5FWsQ8CxhC6j5v6yNuq@rBW8gJeQO11Dh2bCngVgKyDzUqK1ylMaCoN0zu2k6C/KAM8HlAG8ehOSUDZdvwzY2sAQTymzI6/8A "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 67 bytes ``` s/.//,push@a,$&,y/_-//dr for<>;say($a[0]eq$a[2]&&lc$a[3]eq lc$a[1]) ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX09fX6egtDjDIVFHRU2nUj9eV18/pUghLb/Ixs66OLFSQyUx2iA2tRBIGcWqqeUkAxnGQL4CmGUYq/n/f15pblJqUXF8YlFqfHJ@fo6hkTEXVMyxKNU5Xxci9C@/oCQzP6/4v66vqZ6BoQEA "Perl 5 – Try It Online") Takes the identifiers as input on separate lines. **Explanation:** ``` s/.//, # remove the first character push@a, # storage space, even positions are first character # odd positions are remainder $&, # implicit variable holding last matched pattern (first char) y/_-//dr # Remove _ and - from remainder of input for<>; # iterate over all input lines say # output ($a[0]eq$a[2]&& # check that first character is identical and lc$a[3]eq lc$a[1]) # so is the lowercase version of the rest ``` [Answer] # [Retina](https://github.com/m-ender/retina), 28 bytes ``` T`L\_-`l_`(?<=.).+ ^(.*)¶\1$ ``` [Try it online!](https://tio.run/##K0otycxL/P8/JMEnJl43ISc@QcPexlZPU0@bK05DT0vz0LYYQ5X//xPDEosyE5NyUv0Sc1O5EuPLoNz4PCAfAA "Retina – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ∧⁼§θ⁰§η⁰⁼↧⪫⪪⪫⪪θ_ω-ω↧⪫⪪⪫⪪η_ω-ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9Rx/JHjXsOLT@341HjBiC1HUgBBR61LX@0avWjVasg5Lkd8ec7dc93ogtvhwj//58YlliUmZiUk@qXmJuqkBhfBuXq5gH5AA "Charcoal – Try It Online") This prints a `-` for truthy and nothing for falsey. Link to the [verbose version](https://tio.run/##hYuxCgIxEAV/JaTaQAL2VldYKCKCYHusuUACMfGSePHv1y1OsBB81Qy8sR6LzRiJziWkBkOaYDc/MVYY2j5N7gWz3ij9Ec@itFgvx9xdsVgdHHJIcHnE0L5x1kKOUunOiTQMonP9r/K/Kt6WCK9YAt6iO@HdCRyXVU1iJ7OQqfEN). It first compares the first character of both input strings (`⁼§θ⁰§η⁰`) and then compares the rest of both strings after removing the underscores and the hyphens (`⪫⪪⪫⪪θ_ω-ω`) and converting to lowercase (`↧`). [Answer] # C#, ~~101~~ 89 bytes ``` string g(string s)=>string.Concat(s.ToUpper().Split('-','_'));f=>s=>f[0]==s[0]&g(f)==g(s) ``` *Saved 12 bytes thanks to @kusi581.* [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 95 bytes ``` a->b->a.charAt(0)==b.charAt(0)&&a.replaceAll("_|-","").equalsIgnoreCase(b.replaceAll("_|-","")) ``` [Try it online!](https://tio.run/##bVBdSwMxEHzPrwj3UBLxgu@1xVIQCgpCH0XKXrqtqbkkJnvVUvvbz5y9Wvx4m5kddmZ3A1sofUC3Wb60pg4@Et9kTTVkrLoYsj/aqnGajHfdkIWmskZzbSElfg/G7dnNbW8AO3OEcQUaWSKg7DMngU@bRL5@iLg0Ggj37Btezykatx5zCMHuxJFxiGs5ZIdTYL9v682S1zm2tz0@dcYk9@zXfh4y4iPeQjmuyjEo/QxxQuJKjkbVmQwGoCIGmxtOrBXF4qMsLotCKnxtwKbZ2vmIU0goqn99sh2yuQbnMPKU4xy@8Z6L@S4R1sq4fEePfUMq5N5knegKquPJSTl8pzvjUEipCBP9lL4ecWjzYFES6@af "Java (OpenJDK 8) – Try It Online") Pretty straight forward. [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 13 bytes ``` F'hl1"-_"-)Xq ``` [Try it online!](https://tio.run/##K6jMTv3/3009I8dQSTdeSVczovD/f6Xk@PzSvBJdJR0FpWQQK14JAA "Pyke – Try It Online") ``` F ) - for i in input(): 'hl1 - i[0], i.lower() "-_"- - ^.remove("-_") Xq - equal(^) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~126~~ 114 bytes ``` #define p(s)do++s;while(*s==45||*s==95);*s>95?*s-=32:0; f(char*a,char*b){while(*a&&*a==*b){p(a)p(b)}return*a==*b;} ``` [Try it online!](https://tio.run/##LYzNEsEwFIX3niLDMEm0htJFRXgDSxuMuU1SzUwbnaRY0GcPKatzv/NzRXwVwvuRVIU2CjXYEXmbTh17lrpSmDrOV@n7HTRLCaNum6U76mK@TNZzNiiwKMFSiHrJyes/g8mEAufBaTCQBueks6q9W/OzWedH2ojqLhXauFbq26zcDrRpUQ3a4HCAvYoI9X9pgAdBL9TYb1Tg4ViezDBCBQ7BcXGO@sYxORPCUOc9HMBqyCu1h1p5uDz@GJsvfwA "C (gcc) – Try It Online") With whitespace and comments: ``` #define p(s) // Define helper macro p \ do ++s; // Increment pointer at least once \ while (*s==45 | *s==95); // and past any '-' or '_' \ *s>95 ? *s -= 32 : 0; // If lowercase letter, convert to upper f(char* a, char* b) { // Define main function f while (*a && *a == *b) { // Loop until end of either string // or a difference found p(a) // Transform pointer and one char p(b) // via helper p above } return *a==*b; // Test chars equal (on success, both '\0') } ``` [Answer] # Dyalog APL, ~~47~~ ~~32~~ ~~28~~ ~~27~~ ~~26~~ 22 bytes -4 bytes thanks to Kritixi Lithos ``` {(=/⊃¨⍵)∧≡/819⌶⍵~'-_'} ``` Takes input as a list of the strings. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TqjVs9R91NR9a8ah3q@ajjuWPOhfqWxhaPurZBhSoU9eNV69Vjy9JLS5RV1CPDwHR//8DAA) ### How? ``` {(=/⊃¨⍵)∧≡/819⌶⍵~'-_'} ⍵~'-_' Remove '-' and '_' 819⌶ Lowercase ≡/ Equality between elements ∧ And (=/⊃¨⍵) The first element of each element is equal ``` [Answer] # Common Lisp, 98 bytes ``` (lambda(x y)(and(eql(elt x 0)(elt y 0))(string-equal(#1=remove #\-(#1##\_ y))(#1##\-(#1##\_ x))))) ``` [Try it online!](https://tio.run/##PY9Ba8MwDIX/inAYk2GBdTsvMHpee9jYqWCUVCthjpU6Ttdc8tc7OQvzwU/@3pPhNb4d@ht6kR6@JAJeYbLQBrhHNI2MIRkw20UtoNHc9xvt5J17ipQkqkth@OG42C7xkBcWyYA@KbZUe95RxznrLitwIROLJoxdzXFwFNk1In7z9KzBlb5G3q5Mo8PU1eIzdEmkcpUGV5bXP/b7qjLWwlEAtUxHCRKYmR5gJigrvec7A9oQUCtTVx9p6YsUjshnj@yT2o92GSYdLA4ptuFU8nkkj8XmJXInF4biUOqrKA5O9@3f@E@uNp9b/lrlFw) Ungolfed (super straightforward!) version: ``` (defun f(x y) (and (eql (elt x 0) (elt y 0)) ; check if initial characters are identical (string-equal ; string comparison (case insensitive) (remove #\- (remove #\_ y)) ; remove from both strings the unwanted chars (remove #\- (remove #\_ x))))) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` hᵛ&{{¬∈"_-"&ụ}ˢ}ᵛ ``` [Try it online!](https://tio.run/##Pc6xSsRAEIDhVwlTpLoTPPsFudq7QrEJxzIJoyduMrK7MRwxjYLEzv46QWwsbK7RztanSF4kd7MEqx2@@Rk2tZitN4avZ0NdQTRVEVRx3T9/9Y9PffsB3pYEDzJdoXEETQVHEXTfL023ex3W3W4b1/XvZ9@2oKcQdz/vzd/bYbcdhiSBjMvCwySCeRhWkwTwEu0NpoYWmJOsUN@PogshiQzz7Rku@Jzu0KJnG8LCVWTDvijzlKzTaElnzOZ4diLFyKeW5iNK7DZ5ykZUe2allaQjyoWL5VKpUGpPLnw3vCL/4OgAqz0 "Brachylog – Try It Online") Outputs through predicate success/failure. ``` h The first element ᵛ is the same for each element of the input, & and { }ᵛ for each element of the input the following are the same: { &ụ}ˢ every element uppercased which satisfies the condition that ¬∈ it is not an element of "_-" the string "_-". ``` [Answer] # Erlang 113 bytes ``` A=fun(L)->string:to_lower(lists:flatten(string:tokens(L,"-_")))end,fun([C|D],[C|E])->A(D)==A(E);(_,_)->a==b end. ``` a pair of anonymous functions that compare the two lists. meant to be pasted in the erlang shell. more readable: ``` A=fun(L) -> string:to_lower( % case insensitive lists:flatten( % squash all characters back into one list string:tokens(L,"-_") % return a list of list of characters ) ) end. fun([C|D],[C|E]) -> % are the first characters exactly the same? A(D)==A(E); % does the rest compare correctly? (_,_) -> % first chars not the same a==b % shorter than 'false' end. ``` [Answer] # [Clip](https://esolangs.org/wiki/Clip), 25 bytes ``` &=(x(y=AxAy[Aa--m.L`a'-'_ ``` **Explanation**: `x`, `y` and `z` may be referenced in a Clip program to implicitly take up to three inputs. Since this program only references `x` and `y`, it takes two inputs which are assigned to `x` and `y`. ``` =(x(y First characters of x and y are equal & And =AxAy A(x) == A(y) [Aa Function A, takes parameter a m.L`a Map all elements of a to lower case -- '-'_ Remove all occurrences of '-' and '_' ``` Takes two strings from standard input, outputs `1` and `0` for true and false respectively. ]
[Question] [ The task is to generate all the strings from 'a' to '999' including upper case characters like so: ``` 'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ... '8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba' ``` and so on (filling in the gaps), optionally starting with the empty string. **Input:** * The amount of consecutive characters the program has to print up to. **Output:** * An array containing each string *OR* one string per line **Clarifications:** * The order doesn't matter, you can print uppercase or lowercase letters first if you want. * The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go. * An input of `3` would print all the string from `'a'` (or `''`) to `'999'`‚ an input of `5` up to `'99999'` and so on. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØWṖṗR;/ ``` This is a monadic link that accepts an integer as input and returns an array of strings. [Try it online!](http://jelly.tryitonline.net/#code=w5hX4bmW4bmXUjsvCsOHauKBtw&input=&args=Mg) ### How it works ``` ØWṖṗR;/ Main link. Argument: n ØW Yield 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'. Ṗ Remove the last element (underscore). R Range; yield [1, ..., n]. ṗ Cartesian product. For each k in the range, this yields the arrays of all strings of alphanumeric characters. ;/ Concatenate the arrays of strings of each length. ``` [Answer] ## Haskell, 65 bytes ``` a#b=[a..b] k n=mapM id.('a'#'z'++'A'#'Z'++'0'#'9'<$)=<<(1#)<$>1#n ``` Usage example: `k 3` -> `["a","b","c",....,"997","998","999"]`. How it works ``` a#b = [a..b] -- helper function that builds a list from a to b (1#n)<$> -- map the function (1#), i.e. "build the list from 1 up to" 1#n -- on the list from 1 to n -- now we have [[1],[1,2],[1,2,3]] =<< -- map over this list (and combine results in a single list) ( <$) -- a function that makes length of input copies of 'a'#'z'++ ... '9' -- all characters we need -- now we have [["a..9"],["a..9","a..9"],["a..9","a..9","a..9"]] mapM id. -- and make the cartesian product of each sublist ``` [Answer] ## Python, 86 bytes ``` f=lambda n:n*[1]and[x+chr(y)for x in['']+f(n-1)for y in range(128)if chr(y).isalnum()] ``` Outputs a list of non-empty strings. Recursively prepends each alphanumeric character to each output for `n-1` and empty string. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes Code: ``` ƒžj¨Nã€, ``` Explanation: ``` ƒ # For N in range(0, input + 1), do: žj # Push predefined literal [a-zA-Z0-9_] ¨ # Remove the last character (the underscore) N # Push N ã # Take the Cartesian product, with N repetitions. €, # For each element in the array, print with a newline ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=xpLFvmrCqE7Do-KCrCw&input=Mg). [Answer] ## JavaScript (Firefox 30-57), 108 bytes ``` f=n=>n?[for(s of['',...f(n-1)])for(c of(t='abcdefghijklmnopqrstuvwxyz')+t.toUpperCase()+'0123456789')s+c]:[] ``` Saved 3 bytes by using toUpperCase. Computing the 62 characters takes me an extra 10 bytes. [Answer] # Cinnamon Gum, 15 bytes ``` 0000000: 689b b718 05be a345 9c4b c283 d077 de h......E.K...w. ``` Not short enough, despite this being the exact kind of challenge Cinnamon Gum was made for :( Compressed by converting from bijective base 96 to base 256. [Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNjg5YiBiNzE4IDA1YmUgYTM0NSA5YzRiIGMyODMgZDA3NyBkZSAgICBoLi4uLi4uRS5LLi4udy4&input=IjIi) Inputs greater than 2 will cause problems on TIO. ## Explanation This decompresses to the regex `[a-zA-Z0-9]{1,%s}`. The `h` mode then substitutes the input in to `%s` and outputs all strings matching the regex. [Answer] # Ruby, 82 bytes Constructs cartesian products of the character set up to the given length. The character set is generated by grabbing all characters between `0` and `z` and filtering out non-word characters and also `_`. ``` ->n{a=(?0..?z).grep(/\w/)-[?_];r=[] n.times{|i|r+=a.product(*[a]*i).map &:join};r} ``` [Answer] # Python 2.7, ~~136~~ 134 bytes *Thanks to Maltysen and NonlinearFruit for saving 2 bytes* ``` from itertools import*;from string import*;f=lambda n:[''.join(a) for i in range(1,n+1) for a in product(ascii_letters+digits,repeat=i)] ``` Takes `ascii_letters` and `digits` from the string module and uses the Cartesian Product as `product` from itertools to compute all the combinations. # Output ``` out = f(3) print out[:10] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] print out[100:110] ['aM', 'aN', 'aO', 'aP', 'aQ', 'aR', 'aS', 'aT', 'aU', 'aV'] print out[-10:] ['990', '991', '992', '993', '994', '995', '996', '997', '998', '999'] ``` [Answer] # Pyth - ~~13~~ 12 bytes *1 bytes saved thanks to @Jakube.* ``` sm^s+rBG1UTh ``` [Try it online here](http://pyth.herokuapp.com/?code=sm%5Es%2BrBG1UTh&input=2&debug=0). ``` s Add up the lists of different lengths m (Q) Map implicitly over input ^ h(d) Cartesian product of string to implicit lambda var + 1 s Add up list ++ Concat up three things G Alphabet rG1 Uppercase alphabet UT All digits ``` [Answer] # Python 2, ~~106~~ 97 bytes ``` from string import* f=lambda n,r=['']:n and r+f(n-1,[x+y for x in r for y in letters+digits])or r ``` Try it on [Ideone](http://ideone.com/iVKlGa). [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` :"3Y24Y2h@Z^ ``` This takes a number as input. [**Try it online!**](http://matl.tryitonline.net/#code=OiIzWTI0WTJoQFpe&input=Mg) ### Explanation ``` : % Implicitly take input, say N. Generate range [1 2... N] " % For each number in that range 3Y2 % Predefined literal: string with all letters, uppercase and lowercase 4Y2 % Predefined literal: string with all digits h % Concatenate horizontally @ % Push number of characters corresponding to current iteration Z^ % Cartesian power. Each result is a row % End for each. Implicitly display ``` [Answer] # [𝔼𝕊𝕄𝕚𝕟](http://github.com/molarmanful/ESMin), 21 chars / 27 bytes ``` ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė) ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=3&code=%E2%92%B6%C3%AF%E2%93%9C%E1%B5%96%C9%B1%C4%AC%E2%9F%A6%E1%B6%9B%2B%E1%B6%90%2B%E2%A9%A49%E2%A8%9D%5D%2C%E2%A7%BA_%29%C4%97%29)` Nope. Nope. Nope. # Explanation ``` ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė) // implicit: Ⓐïⓜ // [...Array(input)].map(($,_)=>...) ᵖ // push to stack: ɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_) // list of n-digit numbers in [a-zA-Z0-9]-ary ė) // formatted into a matrix (no spaces) // implicit stack output, newline-separated ``` [Answer] # Perl, 113 bytes + whitespace ``` @r=""; for (1..shift) { @r = sub { map { $c=$_; map $c.$_, @{$_[1]} } @{$_[0]} }->(\@r, [0..9, "a".."z", "A".."Z"]) } map say($_), @r ``` Use "perl -E" on the above, with an argument that's a number. I could probably decently have not counted the last "map say" in the chars count. [Answer] # J, 50 bytes ``` 62&(('0123456789',~(,toupper)u:97+i.26){~#~#:i.@^) ``` Half of the bytes, 25 to be exact, are spent generating the letters and digits needed. [Answer] ## APL, 38 37 bytes ``` {⊃{⍵,,⍺∘.,⍵}/⍵⍴⊂,¨⎕a,⎕d,⍨⎕ucs 96+⍳26} ``` [Answer] # Bash + GNU utilities, 90 ``` printf -vs %$1s eval printf '%s\\n' ${s// /{=,{a..z\},{A..Z\},{0..9\}\}}|sed s/^=*//\;/=/d ``` Input as a command-line parameter. Output is a whitespace-separated list. Works for inputs upt and including 3. Run out of memory with 4 - the `eval printf` takes an the entire set of 63n elements of the bash expansion. [Answer] # Bash + GNU utils, 66 Different (and I think slightly novel) approach to [my other answer](https://codegolf.stackexchange.com/a/79416/11259): ``` dc -e"64 $1^[d2 48^r-P1-d0<m]dsmx"|base64 -w8|sed s_^/*__\;/[+/]/d ``` * `dc` counts down from 248-1 to 248-64n and `P`rints each resulting number as a bytestream (i.e. base 256). If the input is between 1 and 4 inclusive, this is guaranteed to be exactly 6 bytes per number. * `base64` converts this to base64 output and thus 8 bytes per base64 digit, one per line. * `sed` strips off leading `/` (base64 digit 63), and then removes any lines containing `+` or `/` (base64 digits 62 and 63). This leaves the required sequence. [Answer] # [R](https://www.r-project.org/), 73 bytes ``` y='';x=c(letters,LETTERS,0:9);for(i in 1:scan())cat(y<-outer(y,x,paste0)) ``` `y` starts off as empty string, `x` as the base case `'a','b','c',...,'8','9'`. `outer` takes each of its input arguments, and applies the function `paste0` to each combination of elements in `y` and `x` which concatenates the strings. `y` saves the result, `cat` prints it, and it iterates through STDIN number of times of doing this. [Try it online!](https://tio.run/##K/r/v9JWXd26wjZZIye1pCS1qFjHxzUkxDUoWMfAylLTOi2/SCNTITNPwdCqODkxT0NTMzmxRKPSRje/FKhYo1KnQqcgsbgk1UBT87/xfwA "R – Try It Online") [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 97 bytes ``` range(.)as$n|[[range(97;123),range(65;91),range(48;58)]|implode/""|combinations($n+1)]|map(add)[] ``` Expanded ``` range(.) as $n # for each n-digit sequence | [ [ # build array of ordinals for range(97;123), # a-z range(65;91), # A-Z range(48;58) # 0-9 ] | implode/"" # make into array of strings | combinations($n+1) # generate array of n-element combinations ] | map(add)[] # convert to sequence of strings ``` [Try it online!](https://tio.run/##NclBDsIgEADAvzQ9QBQN1WobnkJ6WKUxGFiwhXjh7a7ExuNkni/qCi2Aj5kdOKwtFq03jlcluxPfb7r0apR/nAfVD3wq1kcXzHxsmnIP/mYRkg24shZ3sraHyMAYrieiT4i/IyEwOycsxpwqFniLkFPFFw "jq – Try It Online") ]
[Question] [ Given a number \$n ≥ 2\$, a [blackbox function](https://codegolf.meta.stackexchange.com/a/13706/100664) \$f\$ that takes no arguments and returns a random integer in the range 0...n-1 inclusive, and a number \$m ≥ n\$, your challenge is to generate a random integer in the range 0...m-1 inclusive. You may not use any nondeterministic builtins or behaviour, your only source of randomisation is \$f\$. The number you produce must be uniformly random. \$m\$ is not limited to powers of \$n\$. One way to do this could be to generate \$\operatorname{ceil}(\log\_n(m))\$ random numbers, convert these from base \$n\$ to an integer, and reject-and-try-again if the result's greater than or equal to \$m\$. For example, the following JS could do this: ``` function generate(n,m,f){ let amountToGenerate = Math.ceil(Math.log(m)/Math.log(n)) // Calculating the amount of times we need to call f let sumSoFar = 0; for(let i = 0; i < amountToGenerate; i++){ // Repeat that many times... sumSoFar *= n; // Multiply the cumulative sum by n sumSoFar += f() // And add a random number } if(sumSoFar >= m){ // If it's too big, try again return generate(n,m,f); } else { // Else return the number regenerated return sumSoFar } } ``` An *invalid* solution could look something like this: ``` function generate(n,m,f){ let sumSoFar = 0; for(let i = 0; i < m/n; i++){ // m/n times... sumSoFar += f() // add a random number to the cumulative sum } return sumSoFar } ``` This is invalid because it takes the sum of \$\frac{m}{n}\$ calls of f, so the randomness is not uniform, as higher/lower numbers have a smaller chance of being returned. \$f\$ is guranteed to produce uniformly random integers, and can be independently sampled as many times as you want. Instead of taking \$f\$ as a function, you may also take it as a stream or iterator of values, or an arbitrarily long list of values. The ranges may be 1...n instead of 0...n-1. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 bytes ``` ÇÐṀḊ¿ ``` [Try it online!](https://tio.run/##AR0A4v9qZWxsef81WOKAmf/Dh8OQ4bmA4biKwr////8yNw "Jelly – Try It Online") A monadic link taking `m` as its argument and expecting the blackbox function to be in the previous link (e.g. header on TIO). Thanks to @JonathanAllan for pointing this out as per [this meta post](https://codegolf.meta.stackexchange.com/a/13707/53748) and also for saving a byte with a suggested switch to 1 indexing! ## Explanation ``` | Implicit range 1..m Ḋ¿ | While list length > 1 (literally while the list with its first member removed is non-empty): ÐṀ | - Take the list member(s) that are maximal when: Ç | - The supplied function is run for each list member ``` --- If the function had to be provided as an argument, here is an alternative: # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ṛ⁴V$ÐṀḊ¿ ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//4bmb4oG0ViTDkOG5gOG4isK/////Mjf/NVjigJk "Jelly – Try It Online") A full program taking `m` and the Jelly code for `f` as its two arguments. If it’s mandatory to also take `n`, this can be provided as an (unused) third argument. ## Explanation ``` | Implicit range 1..m Ḋ¿ | While list length > 1 (literally while the list with its first member removed is non-empty): $ÐṀ | - Take the list member(s) that are maximal when: ṛ⁴V | - The supplied function is run for each list member ``` --- # Previous answer: [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ³lĊ⁵V¤€ḅʋ⁴¤<³¬$¿ ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//wrNsxIrigbVWwqTigqzhuIXKi@KBtMKkPMKzwqwkwr////83Mv84/zhY4oCZ "Jelly – Try It Online") A full program that takes `n`, `m` and the Jelly code for `f` as its arguments and prints the resulting random number to STDOUT. ## Explanation ``` <³¬$¿ | While not < m: ³ ʋ⁴¤ | - Do the following, taking m as the left argument and n as the right: l | - m log n Ċ | - Ceiling ⁵V¤€ | - Execute f that many times ḅ | - Convert from base n ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~40~~ 39 bytes ``` r&@While@!(r=Nest[nn#3+#2[],0,#])<#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v0jNITwjMyfVQVGjyNYvtbgkOu/9pIV5ysbaykbRsToGOsqxmjbKav8DijLzSvQdgvOLShxCEnNyKoFkUk5qdFq0uY5CUGJeSn6uZ15JanpqkUO1gY5RrZqOgnGsjoKhARDE/gcA "Wolfram Language (Mathematica) – Try It Online") Input `[m, f, n]`. Interprets `m` random digits in base `n` until the result is in `[0, m)`. [Answer] # [J](http://jsoftware.com/), 37 32 26 bytes ``` 1 :'$:@[`]@.(=&#)I.@:u@$~' ``` [Try it online!](https://tio.run/##HctBC4IwAIbhu7/iy6Qp2UjEwIE0CoIgOnQNIZMtS3OxadKlv76kw3t54H3YdMKifDVhKSGOS4lExkAQYgk2tqDYng47G4ERj/HzJefUz2bTYE8567n3JTZwjhsK9RZaNmowMF1R1pBKoyn0TWjc21ffmRDXvsOgdG1GQVcJpT//tc3iEM8scURZKfhrHrtzyAAJ7A8 "J – Try It Online") -6 bytes thanks to xnor's suggested method. Will overflow the stack for larger inputs since it recurses, but works in theory. # base-n method, modified, 37 32 bytes ``` 1 :'([#.u@#~)/@[^:(]>:1{[)^:_&_' ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1DWilfVKHZTrNPUdouOsNGLtrAyrozXjrOLV4tX/a3JxpSZn5Cto2DuYKmkrpGkqmCoYGv0HAA "J – Try It Online") Uses suggested method, except instead of taking the log first just generates m random base-n digits. This makes it *much* slower, but saves 5 bytes. The solution is a J adverb, which modifies the black box function, and takes `n` as the left arg and `m` as the right arg. # base n method, fast, 37 bytes ``` 1 :'([#.>.@^.u@#[)/@[^:(]>:1{[)^:_&_' ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1DWilfXs9Bzi9EodlKM19R2i46w0Yu2sDKujNeOs4tXi1f9rcnGlJmfkK2jYO5gqaSukaSqYKhga/QcA "J – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ ~~15~~ 13 bytes *Thanks to xnor for the inspiration for the method: here it's taken to an even-more-inefficient extreme by repeatedly generating `m` random numbers until all except one are zero, and the only non-zero one is 1* ``` €1ḟo=1ΣCm`%₁∞ ``` [Try it online!](https://tio.run/##jZo7rlNBEEQ3RFAVERGxDESORECA2AAbISBlAayCPcBGLgTo6XrmnB7LepblN/bM9Ke6utofvnz@eF1/vv7o75/fPr3pr@9vr@t611d5efT/c19e3f96@9@6cv10b69sxX2fPuzT24657ZeX1YET3vd43I/WZTnB/pn9ZFnuxt9TeM7DfVZ7drlbFns8nqryXeuJ93UZTtZtT4qHihd2e7D1gl4u3GQ9YzZfPVpujZT9ZrSu2/d1ifHAu6tPba/ijbPE0nrPoH3M@kULkh0n35L/i7kajceTVeezZ7QBx/OemVW8yJbnnF3k8TWi6TP2KGDKnsMdkMdutr@3Ry6vo1taZpLFCvnIp80ByyNWLMY9nZMiIRtCr/7o5psqQkdtwBVhz49nUJZRxe6zoxTVlUDkUt7P1YqQPFA73e@FeuyY4llH2Bu1P9fuIi4zEtJ6Q5QOHKUQ3YEo6VYZKD8YeXZv7jGTIa7pVGyFSPZkqD9BzhfFr/U7KFaDXvAMLOJiDhgRzMiijck3xNAy@v/EjCvct2N8Gg82PKA4yFjXA5ESwPBqjSlw3L2qkNcoUrp5svI8115bZTFiDJaZ3FwLK54tsMdi1XNeF7HoxE2IM/CNK7HXoUZXqnsEZYKMMcNtjOcEeHhHHuv80SKW84f6lgmXJgZmvUOV4T6Dg5FqZ5zBMqBQ26p1zNmTVTKL/AA@Gg@3bCxizcxzrBd2BPeOKaKpdODztEeHTrpHxYN7QqttXj9NA@mB6xWZUTFmT319MZYjOkv0pFEFid/PoDEwIjpXCHQBOdhs4l@eb9xxROKygoEFlOTorGhGpxoTUc2qeep@zaE7DOZbxt6F9DLngVN3RzE8s2nmqhHlxjslR0qukdEOclKjqFJ4BWCmYapPUNfmfq5PaMMTknRgNoZLxRhkJhXtwjoifEe9KwdGVFAAKpymoq@zMtRBISaNKFgX8pT@aVykgx/OkeHKSw/qeIWxGj@vIMAc86SWWE3K0HdG7FDsxElJM@Xa@ITrgVUlMapq@/nsNK7oz2rNpMCapphhHuOqhPcXGaw9M1SbxnC@Ftmvzbd6mKUYZpht5ymDVasqY4ngljP2KnP0HPUu1bhyB2YduQFpTD1Mz6xnNi23wr4srjMqIx30qBymy5GZTYf6x3GdYQJbVU0mDcS1TMOUDF4NRibPkXM4dUWh6aEfdKSzWVkP3VxFv6wytqgmbx1Gtcc/q8pVXWCaF0zImpEr5qBwT9N5nlu6/mO28q7d@lPXdqa5sjEpV20ryBztDk6/eqlMmXLQAHyqyuhV1XA69Kdzp2DYVJ2KuOJhmDf/XsSncBnZZZ/@xYxpfFHUj9QHq4BeHTNoQoy6Ns01znCyn09BirkVqbmGg6ytRSp6Diwzh99MVb01oZAr7vNEqKrq/Hv1/nr9Fw "Husk – Try It Online") [Husk](https://github.com/barbuz/Husk) is usually rather badly-suited for challenges involving randomness, since it has no built-in random number generator. So it's very welcome to have a challenge where a random number generator is assumed as a black-box function! In this case, the black-box random number function is assumed to be located on line 2 (called using the [Husk](https://github.com/barbuz/Husk) command "`₁`"). However, obviously, without actually having this function it's tricky to test the code, so the TIO link substitutes the last few bytes `m`%₁∞` and input `n` for a pre-generated-by-me list of random integers between zero and one (so `n` equals 2). ``` ∞ # infinitely repeat arg1; m # now, for each element n of this list `%₁ # call black-box function ₁, and return the result modulo n; C # now cut this infinite list into sublists of length m = arg2 ḟo # Return the first sublist for which Σ # the sum =1 # is equal to 1; €1 # what's the index of 1 in this sublist? ``` Note: the `m`%₁∞` construction to get the infinite list of random numbers might seem (and is) a bit clunky. This is because (I think), not having any non-deterministic functinos, [Husk](https://github.com/barbuz/Husk) doesn't have or normally need a higher-order function that will repeat a particular function *that takes no arguments*. Luckily in this case, we know that the output of our black-box function is unchanged modulo `n`, so we can 'use-up' an argument without changing the output. [Here's a Try it online link](https://tio.run/##yygtzv7/PzdB9VFT46OOeVzm////NzQAAA) to the `m`%₁∞` bit on its own, here with a function on line 2 that simply returns the number `7` each time it's called. Try to pretend that this is a random number... [Answer] # [R](https://www.r-project.org/), ~~70~~ ~~69~~ 62 bytes **(or [R](https://www.r-project.org/)>4.1, ~~56~~ 55 bytes)** *Edit: -7 bytes thanks to pajonk* ``` function(m,f){while(sum(F)!=1)for(i in 1:m)F[i]=!f();which(F)} ``` [Try it online!](https://tio.run/##TY5BCoMwFET3OcUvbvLBQlNwY8nWS5Quoib4qYkSE6QVz24jLdJZDsOb57dJ2bHXVm4muibQ4LjNDS5zR73mU7S8wpMUaAbPCciBKC1Wd3rIk@F4S7OmS5N1c/LKjDwguHzB3OUCz2Jlvx9eJDpk4JVrBwsu2lp7qHWYtU5wSDUUjGXQdLp5QuhUgJam4KmOOxhogugo6diSBVXvkmoc@xcXpbik5IfCG/8/EbcP "R – Try It Online") Port of ~~[my Husk answer](https://codegolf.stackexchange.com/a/233806/95126)~~ xnor's approach. Keeps generating sequences of `m` random numbers until we get one that contains a single `0`: then we output the position of the `0`. Obviously this is not very efficient, but at least its significantly better than waiting for sequences of all zeros with a single `1` (previous version)... As explained by Nick Kennedy in [his R answer](https://codegolf.stackexchange.com/a/233809/95126), R] version >4.1 lets us exchange "`function`" for "`\`" to save 7 bytes, but unfortunately we can't link to it on TIO or rdrr.io (yet). [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Based on xnor's suggested method in the challenge comments. Takes `m` as the first input `n` as the second and [assigns `f` to variable `W`](https://codegolf.meta.stackexchange.com/a/13707/53748). Outputs a singleton array ``` ÈÊÉ}f@oW ð ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=OAo1CkBW9g&code=yMrJfWZAb1cg8A&input=LVE) or [check the distribution over 1000 runs](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=OAo1CntW9g&code=QbPGyMrJfWZAb1cg8MPOw/wgrs4rIjoge1rKL0EgeDEg%2bTR9JQ&input=LVI) (warning: may take a while to complete) *(All 3 inputs are taken in the header, where each line is assigned to one of Japt's input variables in order. The first line is `m`, the second `n` and the 3rd `f`. Doing this makes no difference to the main programme, saving no bytes; it's done purely to keep everything in one place for easier testing as functions cannot be taken as direct input by Japt.)* ## Black box function W ``` {Vö :Implicit input of integer V=n { :Function Vö : Random int in [0,V) ``` ## Main programme ``` ÈÊÉ}f@oW ð :Implicit input of integer U=m È :Left function, taking an array as argument Ê : Length É : Subtract 1 } :End left function f :Run the right function continuously, returning the first result that returns falsey (0) when passed through the left function @ :Right function o : Range [0,U) W : Run each through W ð : 0-based indices of truthy (non-zero) elements ``` [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 47 bytes ``` m!l|[x]<-[x|(x,1)<-zip[1..m]l]=x|1>0=m!drop m l ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1cxpya6ItZGN7qiRqNCx1DTRrcqsyDaUE8vNzYn1raixtDOwDZXMaUov0AhVyHnf25iZp5tQVFmXomKqWK0oY6hjhEYo0JDdHbsfwA "Haskell – Try It Online") Implements [xnor's algorithm](https://codegolf.stackexchange.com/questions/233790/adaptive-randomisation#comment533500_233790) > > Make a list of \$m\$ outputs from \$f\$, if it has a single \$0\$ output its position, otherwise retry. > > > However we don't need to make a list since we take a list as the input. We also use \$1\dots n\$ ranges because it saves us 2 bytes. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 72 bytes ``` f=lambda m,g:(l:=[g()for x in"1"*m]).count(1)==1and-~l.index(1)or f(m,g) ``` [Try it online!](https://tio.run/##LY3dCsIwDEbv@xRlV82YY0EEKfRJhki1ay2sP5QK88ZXrxkuEAIf5@TLn/pK8XzNpdmSAi86Gjo@5FRqz5xadXgYLfec1i0CB5yABYUXFhViswfCw@CkWKWanQCbCt@4jx12fbjB@EzvWAWCUkiPTt919NEsGyUEWkEqtN25k8OPnokGZC6ezD8C7Qc "Python 3.8 (pre-release) – Try It Online") Uses @xnor's method -6 and fix thanks to @ovs Generates the blackbox function for m times, and try to pick the index of 0 from it, if not present recurse. Looks like the relevant function Dosen't need to take n at all, because it is hardcoded inside g() Also it is needed to check if list has only one zero, so the choosing remains uniform [Answer] # [R](https://www.r-project.org/) >= 4.1, ~~67~~ 64 bytes ``` \(m,f,x=1:m){while(x-max(x))x=x[max(y<-sapply(x,\(z)f()))==y];x} ``` [Try it online!](https://tio.run/##K/qfbvs/rTQvuSQzP08jVydNp8LW0CpXs7o8IzMnVaNCNzexQqNCU7PCtiIaxKy00S1OLCjIqdSo0IFrq9JM09DU1LS1rYy1rqj9n65hZI6Q1CxOzC0AGmWqY6ipa6j5HwA "R – Try It Online") An R translation of [my Jelly answer](https://codegolf.stackexchange.com/a/233794/42248). TIO link uses `function` in place of `\` since TIO isn’t on R 4.1 yet. Thanks to @DominicVanEssen for saving 3 bytes! If it were permissible to require that the Blackbox function take a single unused argument, this would do for 61: # [R](https://www.r-project.org/) >= 4.1, ~~64~~ 61 bytes ``` \(m,f,x=1:m){while(x-max(x))x=x[max(y<-sapply(x,f))==y];x} ``` [Try it online!](https://tio.run/##K/qfbvs/rTQvuSQzP08jVydNp8LW0CpXs7o8IzMnVaNCNzexQqNCU7PCtiIaxKy00S1OLCjIqdSo0EnT1LS1rYy1rqj9n65hZK4DN6ZKszgxtwCo3VTHUFPXUPM/AA "R – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~63~~ ~~61~~ 60 bytes ``` (m,f,r=(i=m,p)=>i?f()?r(i-1,p):p?r():r(i-1,i):p||r())=>r()-1 ``` [Try it online!](https://tio.run/##JY5LDsIwDET3OYWXNv2oXYFa0p6AQ0TQlKAkrtKqG8rZgwVezMyTPZJfZjfrPbllq/ZLnnXGUNoyaXQ6lAvpwY0WaUzoqla4WyRS90cneBzCciZatTmChrMKom2jrBgS6AFuZnvW1jMn/MVk4oOD7E4QSVlOgH7awEmh6cWuUhcvCoK3Apk7x5X9VHuecZYPwRL16pO/ "JavaScript (V8) – Try It Online") Using xnor's method. The recursive function `r(i,p)` counts down from `i = m` while `i > 0`. If finds a zero `f()` it records position `i` as `p` except if there is already a `p` it restarts by calling `r()`. If `i` gets to zero and there is a `p` it returns `p-1` as the result otherwise it restarts. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 70 bytes ``` h=lambda m,n,f:h(m,n,f)if(s:=sum(n**k*f()for k in range(m)))>=m else s ``` [Try it online!](https://tio.run/##RYzNDsIgEITP8hR7ZEkPVC@GBF/FYApC2l0I1INPj60/8TCZZL6ZKc81Zj6dS@2hZoLqeNosUcl1VYLsqAXbowh2cXSbnNkLm@5eMvb4TYEGHoKJ8u2YgmzGtgdJVmpWQWLIFWZIDJ8pIeLFEvileWh9p9c/HbXWaMSh1MSr/J1ifwE "Python 3.8 (pre-release) – Try It Online") Generates a random number up to n^m (always larger than m) with n invocations of f, then retries if the result is >=m. Blows up the stack for large n and m, because n^m is *much* larger than m. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` NθW⊖№υ⁰≔EθNυI⌕υ⁰ ``` [Try it online!](https://tio.run/##TYzBCsIwEETv@xU5biBCWm2q9CQVwYPiL8Q02ECbtmminx8XQZDhMbswM6bXwUx6yPni5xRvaXzYgAtv4N27wTI8WRPsaH20HbZT8hGTYJJzzo7r6p4er3rGRbD/OueCJZq4B0f5Vq8Rz853v2aTcyFhDzXsQBIFVKDoUuQl/TVJEYdvRpKXREWqiS2ovHkNHw "Charcoal – Try It Online") Link is to verbose version of code. Uses the method @xor suggested in a comment to the question. Takes `m` and a stream of random integers as input. Explanation: ``` Nθ ``` Input `m`. ``` W⊖№υ⁰ ``` Repeat until the predefined empty list contains exactly one zero. ``` ≔EθNυ ``` Input `m` random integers to the predefined empty list. ``` I⌕υ⁰ ``` Output the position of the zero. 24 bytes for fastest code: ``` NθNη≔ηζW¬‹ζη≔↨E↨⊖ηθNθζIζ ``` [Try it online!](https://tio.run/##TYzLCsIwEEX3@YosZyCCdduVj42gxV@IcTCBNG0zqUJ@PkYs2MUd7hkux1gdzaB9Kecwzqmb@ztFmLAVa7aV98zuGcAqmSu9rfMkoRsSXIgZspIWEeWyOmgmuOrxV05kIvUUEj2qSsmpZq3H5fcV36ILCY6aE2TEtpSdaLaiEf/UWzYv/wE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a stream of random integers. Explanation: ``` NθNη ``` Input `n` and `m`. ``` ≔ηζ ``` Start with `m` as the trial result (because we know it is too big). ``` W¬‹ζη ``` Repeat until a usable result is achieved. ``` ≔↨E↨⊖ηθNθζ ``` Input the minimum number of random digits (obtained by converting `m-1` to base `n`) and convert that to base `n`. ``` Iζ ``` Output the final random integer. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 19 bytes [SBCS](https://github.com/abrudz/SBCS) Implements the algorithm suggested by xnor. ``` {⍸1=∘⍺⍺¨⍣{1=+/⍺}⍳⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu8PQ9lHHjEe9u4Do0IpHvYurDW219YGc2ke9mx/1bq0FAA&f=C84vKlF41DZB4VFX06OOGY96ux/1bH/UtYgrTyEXLG5ooGBkwJUOZlfb59VyPeroUg9KLS7NKVHIT1NX0PADyhgaAIGmgnpyYk5OsZU6VzDI1OpHvbt0HnUuetS7tfZRz47qR13N6QppCrm1h1Y86t3sBwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) The blackbox function is called with dummy arguments it ignores, which I think should be fine as there is no way to pass a niladic function to an operator. `⍳⍵` create a range from 1 to n `¨` for each value in the current list ... `⍺⍺` call the blackbox function ... `⍸` get all indices of 1's in the resulting boolean mask. This returns a singleton value 3 bytes can be saved by using a full program instead of a *dop*, but this is quite inconvenient to use: ``` ⍸1=∘⎕¨⍣{1=+/⍺}⍳⎕ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S7w9D2UceMR31TD6141Lu42tBWW/9R767aR72bgWIA&f=AwA&i=S@MyMuCqtjc0qAUA&r=tio&l=apl-dyalog&m=tradfn&n=f) [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes ``` f=->n,g,m,r=0,z=1{z>m ?r<m ?r:f[n,g,m]:f[n,g,m,r*n+g[],z*n]} ``` [Try it online!](https://tio.run/##PYtBCsIwFET3niLUjdbfkip0ITYepGQRsS0B84lJIzUhZ49RqJvhMW/GuNs7pbGrGMIECkxHwXdN8EyRq7l84zz2P8dXAFPiYeo5@BJ5TJrkA6W0nqUabK2EDmPftBQqFozA@y7zPsKpOfK40W62pFBiIRUj2@DzfIlAXuLhBrt2DuWzttIP2SiJ/6nEWKQP "Ruby – Try It Online") Use the log() approach, with a recursive function: `z` is the maximum possible random number for a given iteration, `r` is the current accumulated value. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~76~~ \$\cdots\$ ~~70~~ 67 bytes ``` i;c;g(n,m,f)int(*f)();{for(;n;)for(n=i=m;i--;)!f()?n-=m,c=i:0;n=c;} ``` [Try it online!](https://tio.run/##1ZJRS8MwEIDf9yvOQiHZEuwUEXfG/RC3h5E2JWBu0lYUR/@69ZLWbbAHX3zxIEmP73L9EmJ1be0weLRYC1JBOempE3MnhcSD2zcCCWVcyXgT0GuN8soJuSZtgrLGrwokY7EfeB8QzuLSUCkkHKCpureGoNnFPCeEPuGw8xT5DDjaRDsfKlFIiRALuqrt6HkLBg73CpZLBTf9iYSRLG8ZRfzQY@rEliBikaey@uCSAqfPR2j9Z7V3IjWW11M2H1OExSLV/SjFIN4/aiS0xSNJJ5houKCvDXMnMjJ5CXxPoJ8gU8B/OZacPCdH9rsrksW5wXm3vM1L7uLXPGWrjOd0xWdN@wuDDdUiLxXE4Y4eCsJfq4wPh4V@89H/NTaUTUfrZ/3wZd3Lrm4H/f4N "C (gcc) – Try It Online") Saved 3 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!! Uses [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s idea by repeatedly calling \$f()\$ \$m\$-times and if \$f()\$ returns \$0\$ once and only once, then returns the time (with \$0\$ being the last time and \$m-1\$ being the first) that \$f()\$ was \$0\$. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 60 bytes ``` (n,f,m)=>(g=p=>p*m/d^-~p*m/d?g(p*n+f(),d*=n):p*m/d)(0n,d=1n) ``` [Try it online!](https://tio.run/##LY7BasMwEETv/Yo97tqKGmMCJUEO7cHQQ74gJKBKspNgr4RiF0rc/rrr2j3NMDxm5qY/9d3Ea@hW7K0bSzUii0q0pAqsVVBFSNpne179zLqvMSScVkjCJoppO6eEaxZWZUxj7BkUIIEqoMScxb9/u9bv3OFBdxdZNd7HxUbN1rcTkkBOJOCFafdkPN9942SnPxqHeJRSvsaovzBzGzrJVgdcSqcxJJLR2d5MoBHAc47myKe/G7MOA6wJUsgEmGni8U1Eu/EX "JavaScript (Node.js) – Try It Online") Signature: `(n: BigInt, f: () => BigInt, m: BigInt) => BigInt` Input / Output `BigInt` values. --- And it would be 47 bytes if we can assume infinite precision of floating point numbers: ``` n=>f=>g=(m,p=0)=>p*m^-~p*m?g(m/n,p*n+f()):p*m|0 ``` [Try it online!](https://tio.run/##LY3BboMwEETv/Yo97oLjUtEDamSiXLjlCxCVXGPSRHhtOaRSFNJfpy7tZWc0M9p31l/6YuIpTBv2vV0atbCqB1UfFToRVEGqDpl733ynuzuie2YRMs4HJHpL0Vws8cqgAAlUDQ2WhH/2oKdPOYzeR1xt1Nx7l7oMSiKsaPtkPF/8aOWkP0aL2Eop9zHqG1b2lTrpdPj/lRCJJ6PtryYNjQBeczQtd7/wVecZCoIcXgQYEnB/ENF2@QE "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript, ~~55~~ 53 bytes Takes arguments by currying, i.e. `f(r)(m)`, where `r` is the black-box randomisation function. The first 3 bytes could be removed by stipulating that [the function be pre-assigned to `r`](https://codegolf.meta.stackexchange.com/a/13707/58974). ``` r=>g=(m,y=x=m)=>y?g(m,--y,r()||(--x,z=y)):m+~x?g(m):z ``` [Try it online!](https://tio.run/##dU/BasJAFLznKzy08F7NbkMhIMpLodSChxowsRcjzTaJNqnZlXUpiSb@ehpLD146pxlmGGYK8S0Oic73hkmVZp0k1yppZGl6J@9VmE@uhUxVCXgnG8faUKfJ2xKUdk0VlUhe/bjtFWO1rQGbBhir7CPViONyeK4uJo6PXaLkQe0yvlNbiMNpEA4Wy3kwHtycNqCxz7T2PzySkXyeBeFi9rQMZ/48kv7bdDFwv34bIsmuEKO1URoUnVo7J9dxnEnO2ATVqqC/vjWxcy/X1vUi/6PIEsMzaXSeHUAhL8UeYFXZ9bq/WA3jy1Ko710HuVEveZWl8IB8L9LACG3AxfY2Rl6oXMaRjLH7AQ) (change the values of `n` & `m` in the header) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 29 bytes ``` {|n÷£$•⌈(¥†⅛)¾nhβ:nṪt>nh(¼_)} ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%7B%7Cn%C3%B7%C2%A3%24%E2%80%A2%E2%8C%88%28%C2%A5%E2%80%A0%E2%85%9B%29%C2%BEnh%CE%B2%3An%E1%B9%AAt%3Enh%28%C2%BC_%29%7D&inputs=&header=%CE%BB1%7C&footer=%3B%E2%86%92f%20%E2%9F%A85%7C12%7C%CE%BB0%7C5%CA%81%E2%84%85%3B%E2%9F%A9%20%E2%86%90f%20%0A) This is a whole bunch of yucky stuff that is lowkey disturbing. I really need to make functions nicer to deal with in the rewrite. A lambda submission, that takes a single argument, `[n, m, f]`. ## Explained ``` {|n÷£$•⌈(¥†⅛)¾nhβ:nṪt>nh(¼_)} {| # while the top of the lambda stack is truthy: n÷ # push all the contents of the input onto the stack £ # and place "f" into the register. $•⌈ # push ceil(log_n(m)) (¥†⅛) # and that many times, push the result of f() onto the global array ¾ # push the global array, containing ceil(log_n(m)) numbers nhβ # and convert from base n :nṪt> # push ^ > m nh(¼_) # and clear the global array } # close the while loop (we need this because lambda submission) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 50 bytes ``` (r,n,m)=>g=(i=1,j=0)=>i<m?g(i*n,j*n+r()):j<m?j:g() ``` [Try it online!](https://tio.run/##fY/BSsNAFEX3@YosFN5rJ2MUAtI6FcQKXdhCk7ppihmTNM7YvCnTQVpq/PUYRbAr7@7cxeFeLd/lLrdq6wIyRdmSiLxaXHtWPIvRo3Sv3EoqTA3Yo4/QW4sWLCNWoxhVApS4ZFqEHaib@rYC1SOme9S3gDjQXaUHFWCbG9qZTck3poIsGceJP19M44F/dlz/2gAb9i@mlNL9JE7mk7tFMplNU5o9jed@9PajSik4SYbe2lgw4tgwJaIwDIcqCIZollr8KVci@OyalXe6bvaiy9zxkpxV5Q4M8lpuAZZ7dlh1L/f97Hs1HC6iELkzD2pfFnCFfCuL2EnrIMLmPEOujaIspQzbLw "JavaScript (Node.js) – Try It Online") generate ceil(logn(m)) random numbers, convert these from base n to an integer, and reject-and-try-again if the result's greater than or equal to m. # [JavaScript (Node.js)](https://nodejs.org), 49 bytes ``` r=>g=(m,y=x=m)=>y?g(m,--y,r()?z=y:--x):1-x?g(m):z ``` [Try it online!](https://tio.run/##dU9LS8NAGLznV@SgsJ9m11gISMqXglghB1toUi9NMWteJja7YbNI0od/PabioRfnNMMMw0zFv3ibqLLRVMg0GwROjBofDIVv6L1w/cEUF6msCdyIo23kOCj0CiS11WOHNaDXz4pRUdpbisBsj71LaQfuPe3OBrj7IZGilbuM7WRB4nAehOZqvQhc8@qQEwVj5mT9wyMRiSc/CFf@4zr0l4tILF/nK9P5/G2IBL1ADEYuFZF4OFklOrZtT0tKpyA3Ff71bZF@j3JrXC5avldZolkmtCqzlkhgNW8I2XRWvx3vdbfxeSnp7xwbmJbPZZelZAKs4WmgudLEgdN1DKySpYgjEcPwAw "JavaScript (Node.js) – Try It Online") From Shaggy's [Answer] # [C (gcc)](https://gcc.gnu.org/), 59 bytes ``` r;c;g(n,m,f)int(*f)();{for(r=0,c=m;c--;r%=m)r=r*n+f();r=r;} ``` [Try it online!](https://tio.run/##hZPxbqMwDMb/Xp7C2omRQJCg02naMp5kmyYWoI3UhCrQm3QTr37MTstaetodEoLYn@1fPoLO1lpPk1darbmTVrbCuIEnreBCfbSd577MpS6t0lmmfFRa4UufuLTFPL6pcUI9OMXo4V3NBXyAb4a9d@ArWkdOwch@dabG@K6phtedpxl6U3nQGwlUqbu9G7CUvW/MtuFhmWUCdvuBdCgWis2L@NnFuDw2Dd1e3zAeSC76hWzLr6NV/QDRbQ0lXEtSHRSKLZjiH7GcE4v2G9MP3dmABOpqqGgAxYxiaBVwU@bKPDqVpkacc0kSP5mX0JUKbGUcOcUArz74NBjb8FyghGJBdHgNjgDvdeVoHzVENe7gBjlurICyhNXc6FiYgKN5uFNdbbedxu/am99N1xL/POBLa5da@70WhsbuTpHZWVciEx6Hh2dHzp7VHDwhf7B/rvDxCD/zBM9DMOgETRc1R1k4QmqRCbt5ovxLmp5SI7s6/zZOBp34G3DNo1oC3e0MKcH@n9P@i/PwtyDtBaz9DnZBdWS20l4wL09jFsviPj@mRzZOd1DcsqKA4o6toLj/o9ttte6n7P0T "C (gcc) – Try It Online") [Answer] # [JavaScript](https://www.javascript.com/), 36 bytes ``` (n,m,f)=>(g=p=>p&&g(p-1)*n+f())(m)%m ``` [Try it online!](https://tio.run/##dVJNb@IwEL3zK0bqB3YTIlJUdUsapJUqbj31iFBrQRy8iu3IuFmqNL@djk1Cw3bhgCfz5s28@fjDKrZdGVHaUfVr/5Tu0lm90mqriywqdE52NDGZfTcKdkmTDObpnqhQhpymM5KnZTorr69zUo5ieqMCTiglkl7JfZFZWDPLIIVFrab3oZzGkyZEM46dfe/tW2c@NMtkMODvamWFVsAKkavXrTVC5QSfsMgUhXoA@HNZTSYxKTphBAhHaOV2k3hccCAOn8GYOhADhzCMTFZmzDqEQuD8h@i2L//d9BSUWNq@bsTWasKM6YpzbYA4BQIEyvwGOmUVlkP3QiyTo78/ytPWRGT1y8Gk4a0TNpyi2uA0qupHTXyUbwrfi2NjFQV6KNn4RjqhNW6qAc39JvozVO1qVPYXfhvDPohqEzhU/kBli3pexEVRkHHrkj9dLgdHPnE38szsJjJMrbUkeCKfXVBvmimME3weQd3coRUEgn4P1pdc4GEtg6Dr8Rxf/ofv9S3m7dH@k@RkO28KM13WqgGsNn3rRtq/Bi@m9Z9y58QxQ@RL/Odn@PIMfzg67jJ@GFOMaPZf "JavaScript (V8) – Try It Online") This answer works in all JS versions after 2015 **Edit #1:** -3 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) ]
[Question] [ You are playing a famous game called \$1\text{D Array BattleGround}\$. In the game, the player can be stationed in any position from \$0\$ to \$10^5\$. You are a *Paratrooper* in the game and have the ability to do *two types of operation* \$-\$ * ***Advance***, which would **multiply** your position by \$2\$ * ***Fall-back***, which would **decrease** your current position by \$1\$ Each type of operation requires \$1\$ second. You are stationed in \$N\$ and want to go to \$M\$ in the minimum time possible, (\$1≤ N, M ≤10^4\$). Find out the minimum time you need to ***Get to \$M\$***. *Note: After each operation, you must remain in the zone from \$0\$ to \$10^5\$.* ### Sample ``` Input : 4 6 Output: 2 Input : 10 1 Output: 9 Input : 1 3 Output: 3 Input : 2 10 Output: 5 Input : 666 6666 Output: 255 Input : 9999 10000 Output: 5000 ``` This is a code-golf challenge so code with lowest bytes wins! [Answer] # JavaScript (ES6), 30 bytes Takes input as `(N)(M)`. ``` N=>g=M=>M>N?M%2-~g(M+1>>1):N-M ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@9/P1i7d1tfWztfOz95X1Ui3Ll3DV9vQzs5Q08pP1/d/cn5ecX5Oql5OfrpGmoaJpoaZpqYCFOjrKxhxoSowNNDUMISrACqwRFegqWGMYoIxmgIjTZAhSCaYoikwMzPTBBEQh4DcYIquxBIIQMYAAVARyAwg6z8A "JavaScript (Node.js) – Try It Online") ### How? Instead of going from \$N\$ to \$M\$, we go from \$M\$ to \$N\$. While \$M\$ is greater than \$N\$: * if \$M\$ is odd, increment it and divide it by \$2\$ (2 operations) * if \$M\$ is even, just divide it by \$2\$ (1 operation) When \$M\$ is less than or equal to \$N\$, the remaining number of operations is \$N-M\$. *Example for \$N=666\$, \$M=6666\$:* ``` M | transformation | operations | total ------+--------------------+------------+------- 6666 | M / 2 = 3333 | 1 | 1 3333 | (M + 1) / 2 = 1667 | 2 | 3 1667 | (M + 1) / 2 = 834 | 2 | 5 834 | M / 2 = 417 | 1 | 6 417 | M + 249 = 666 | 249 | 255 ``` With inverse operations in reverse order, this gives: $$((((666-249)\times 2)\times 2-1)\times 2-1)\times 2=6666$$ The idea behind that is that it's always cheaper to process the greatest number of *fall-back* operations at the beginning of the process (i.e. when \$N\$ is still small) rather than exceeding \$M\$ by too large a margin with hasty *advance* operations and doing *fall-backs* afterwards. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~53~~ 34 bytes Saved a whopping 19 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f(N,M){M=M>N?M%2-~f(N,-~M/2):N-M;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9Nw0/HV7Pa19bXzs/eV9VItw4kolvnq2@kaeWn62td@z83MTNPQ1OhmqugKDOvJE1DSTUlJk9JJ03DRMdMU9NaAQr0tRSMFLT0MVQZGugYIpQBVVliVaVjjGqWMTZVRjqGBihmmWJTZWZmpgPEUMeB3GWKVZ0lEAANBAKQSpBpQCZIYe1/AA "C (gcc) – Try It Online") A port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/206236/9481). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 bytes [SBCS](https://en.wikipedia.org/wiki/SBCS) Recursive dfn as per [Arnauld's answer](https://codegolf.stackexchange.com/a/206236/75323). ``` {⍵≤⍺:⍺-⍵⋄(2|⍵)+1+⍺∇⌈⍵÷2} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHnUse9e6yAmJdEK@7RcOoBsjQ1DbUBoo96mh/1NMB5B/eblT7P03hUdsEhUe9fY@6mg0ftU1@1De1uCgZSJZkZBb/N1FIUzDjMjQAUoZchkDSmMsIxDbgMjMzA8kBAZclEIAFgQAA "APL (Dyalog Unicode) – Try It Online") We take Arnauld's approach but we use APL's nice builtins to make a single recursive call instead of having to choose the recursive call that we want to make (which would depend on the parity of M): ``` {⍵≤⍺:⍺-⍵⋄(2|⍵)+1+⍺∇⌈⍵÷2} ⍝ dfn taking N on the left and M on the right {⍵≤⍺: } ⍝ if N is less than or equal to M ⍺-⍵ ⍝ just return N - M ⋄ ⍝ otherwise ⍺∇⌈⍵÷2 ⍝ divide M by 2, round up and call this function recursively 1+ ⍝ to which we add 1 unconditionally (2|⍵)+ ⍝ and to which we add the parity of M, i.e. add one more iff M is odd. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ←V€⁰¡ṁ§eD←; ``` [Try it online!](https://tio.run/##yygtzv7//1HbhLBHTWseNW44tPDhzsZDy1NdgELW////NzT4bwQA "Husk – Try It Online") Arguments are in reversed order (first target, then initial position). # Explanation Brute force turned out shorter than more efficient methods. ``` ←V€⁰¡ṁ§eD←; Inputs: M (stored in ⁰) and N (implicit). ; Wrap in list: [N] ¡ Iterate, returning an infinite list: ṁ Map and concatenate: ← Decrement and D double, §e put the results in a two-element list. V 1-based index of first list that €⁰ Contains M. ← Decrement. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Took quite a while to find an approach which could be implemented in under 16 bytes. ``` ‘:Ḃȯ⁹>$Ɗ?Ƭ2i’ ``` A dyadic Link accepting `M` on the left and `N` on the right which yields the time you need to manoeuvre. **[Try it online!](https://tio.run/##y0rNyan8//9RwwyrhzuaTqx/1LjTTuVYl/2xNUaZjxpm/v//39AACP5bAgEA "Jelly – Try It Online")** ### How? ``` ‘:Ḃȯ⁹>$Ɗ?Ƭ2i’ - Link: M, N 2 - use two as the right argument (R) of: Ƭ - collect up, starting at M, while results are distinct: ? - if... Ɗ - ...condition: last three links as a monad - i.e. f(current_value): Ḃ - LSB (i.e. is current_value odd?) $ - last two links as a monad: ⁹ - chain's right argument, N > - greater than? (i.e. is current_value less than N?) ȯ - logical OR (i.e. is current_value either odd or less than N?) ‘ - ...then: increment : - ...else: integer divide by R (2) i - 1-based index of first occurrence of N in that ’ - decrement ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~15~~ 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Heading tag now includes the completely unnecessary space SE are forcing on us for no good reason Well, seeing as everyone else is taking Arnauld's approach ...! Be sure to `+1` him if you're `+1`ing this. Takes input in reverse order. ``` >V?¢ÌÒß°Uz:UnV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=PlY/oszS37BVejpVblY&input=NjY2Ngo2NjY) ``` >V?¢ÌÒß°Uz:UnV :Implicit input of integers U=M and V=N >V :Is U greater than V ? :If so ¢ : Convert U to base-2 string Ì : Get last character Ò : Subtract the bitwise negation of ß : A recursive run of the programme with argument U (V remains unchanged) °U : Increment U z : Floor divide by 2 : :Else UnV : U subtracted from V ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [ÐÆd#`DÉD½+;‚¼}ƾ+ ``` Inspired by [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/206236/52210), so make sure to upvote him! [Try it online](https://tio.run/##yy9OTMpM/f8/@vCEw20pygkuhztdDu3Vtn7UMOvQntrDbYf2aQMljXQMDWIB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6MMTDrelKCe4HO50ObRX2/pRw6xDe2oPtx3ap/3/8HodvUNb/0dHm@iYxepEGxroGIIoHWMgaaRjaACkzMzMdIAYJG0JBEBBIIiNBQA). **Explanation:** ``` [ # Start an infinite loop: Ð # Triplicate the pair at the top # (which will use the implicit input in the first iteration) Æ # Reduce it by subtracting (N-M) d # If this is non-negative (>=0): # # Stop the infinite loop ` # Pop and push both values separated to the stack D # Duplicate the top value `M` É # Check if it's odd (1 if odd; 0 if even) ½ # If it's 1: increase the counter_variable by 1 D # (without popping by duplicating first) + # Add this 1/0 to `M` ; # And halve it ‚ # Then pair it back together with the `N` ¼ # At the end of each iteration, increase the counter_variable by 1 }Æ # After the infinite loop: reduce by subtracting again (N-M) ¾+ # And add the counter_variable to this # (after which the result is output implicitly) ``` [Answer] # perl -alp, 62 bytes ``` $;=pop@F;{$_<$;||last;$"+=1+$;%2;$;+=$;%2;$;/=2;redo}$_+=$"-$; ``` [Try it online!](https://tio.run/##LYjBCsIwEAXv@YolrKdQzEZdKM@AJ3@jFOxBCCa0vdn@emMODgwMU6Y53SpbiuRRGbHk8njiy8OdsW1pXFawdVEc4xTAcPEf5xgwT6@889Ce7Ri1XkmNeBIjdDGBxBtVpaaavtFG48hlfefPUrs0lh8 "Perl 5 – Try It Online") This uses the same logic as most other solutions. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` Nθ⊞υNW¬№υθ≔⁺⊖υ⊗υυI⊖L↨Lυ² ``` [Try it online!](https://tio.run/##VYzBCsIwEETvfkWOu1BBvUlP2l4EKf2FNC5NIE3aJKufHxNB0DnNPGZGaRmUlzbnm1s5DbxMFGDDdjdy1MCN@OVY@EsbSwIGn6Dz7FLtbIgoLjGa2cFoOUJPKtBCLtEDGBvRe57sx5fA9T2YMu1kTH/dO7k5abjKSF9f5yesanM@HsQ575/2DQ "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order `M`, `N`. Horribly inefficient breadth-first search, so don't bother putting in large numbers. Explanation: ``` Nθ ``` Input `M`. ``` ⊞υN ``` Push `N` to the predefined empty list. ``` W¬№υθ ``` Repeat until `M` is present in the list... ``` ≔⁺⊖υ⊗υυ ``` ... concatenate the decremented list with the doubled list. ``` I⊖L↨Lυ² ``` Calculate the number of concatenations. [Answer] ## Batch, 153 bytes ``` @echo off @set/an=%1,c=0 :l @if %n%==%2 echo %c%&exit/b @set/a"c+=1,p=~-%2/n+1,q=p&p-1,r=n*p-%2,n-=1 @if %q%==0 if %r% lss %p% set/an=n*2+2 @goto l ``` Explanation: ``` set /a n=%1, c=0 ``` Initialise `n` from the first parameter and clear the loop count. ``` if %n% == %2 echo %c% & exit /b ``` Output the count once the target in the second parameter is reached. ``` set /a " c += 1, p = ~-%2 / n + 1, q = p & p - 1, r = n * p - %2, n -= 1 ``` * Increment the loop count * Calculate the number of advances needed * Calculate how near to the target advances would get * Assume that we'll fall back ``` if %q% == 0 if %r% lss %p% set /a n = n * 2 + 2 ``` If the advances would get near to the target then undo the fall back and advance instead. [Answer] # [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 61 bytes ``` define f(n,m){if(n>=m)return n-m;return 1+m%2+f(n,(m+m%2)/2)} ``` [Try it online!](https://tio.run/##LYoxCoAwEAR7X3GNkCMRTZSAiD5GTcDiUgStxLfHO3GanWV33UrZQzxSgKiSIbwPzmUmzOG8coLU0PSr1VQ7LTdFotg6fEpUgwGPVVS2M2A/MdBLOu6diPeeP4yUkZGBwaq8 "bc – Try It Online") Given `n`, and `m`, return `n - m` if `n` is greater than or equal to `m`. Else, it returns `1` plus `1` (if `m` is odd), plus the result of (`n`, `m / 2`), with the division rounded upwards. The latter is done with a recursive call. [Answer] # Befunge-98, 75 bytes The program keeps a running total of moves at `(0, 0)` and remembers `N` at `(1, 0)`. It definitely could be golfed some more. ``` p&01p&>:01g-0\`|>:2%| 2/1 v >0g+.@ >^ > 1+2/2v ^0-\g10< > 0+g00<^p0 ``` [Try it online!](https://tio.run/##JcixCoMwFIXhPU9xFl1CzLkZQity6YNIKAV7t5KlTr57jLj8/Hyf7fv/2Raej9Z2p3Wk1FFnigWu70PnNBwOKQqwA0rz0wta0N9BfIqpc2FYTbjgZnojl1LZWs4Z@coJ) Edit: I had to add some extra arrows for it to run on TIO for some reason. See comments. I used the logic from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/206236/9481). [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 65 bytes Port of Arnauld's answer. ``` f(X,Y)->if X>Y->X-Y;true->1+(Y rem 2)+f(X,(Y+(Y rem 2))div 2)end. ``` [Try it online!](https://tio.run/##RYpBCgIxDEX3c4ouE2YyoIsuFHKOZiWDk0rAqRI7evxaV354PHh89ftSbqSvq9uztqFlSJMgseWQWIgTybn6rsSHESS4buGI4@8F8g@42rtLyzq3bbECFwzEQ@izx@njVhUyxBinTkSc2xc "Erlang (escript) – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes A port of [RGS' APL answer](https://codegolf.stackexchange.com/a/206244/95594) with J's hooks and forks. ``` -`(($:>.@-:)+1+2|])@.< ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dRM0NFSs7PQcdK00tQ21jWpiNR30bP5r/jdRSFMw4zI0AFKGXIZA0pjLCMQ24DIzMwPJAQGXJRCABYEAAA "J – Try It Online") ]
[Question] [ For a *positive* integer `n` with the prime factorization `n = p1^e1 * p2^e2 * ... pk^ek` where `p1,...,pk` are primes and `e1,...,ek` are positive integers, we can define two functions: * `Ω(n) = e1+e2+...+ek` the number of prime divisors (counted with multiplicity) ([A001222](http://oeis.org/A001222)) + `ω(n) = k` the number of distinct prime divisors. ([A001221](http://oeis.org/A001221)) With those two functions we define the *excess* `e(n) = Ω(n) - ω(n)` ([A046660](http://oeis.org/A046660)). This can be considered as a measure of how close a number is to being squarefree. ### Challenge For a given positive integer `n` return `e(n)`. ![](https://i.stack.imgur.com/gULhZ.png) ### Examples For `n = 12 = 2^2 * 3` we have `Ω(12) = 2+1` and `ω(12) = 2` and therefore `e(12) = Ω(12) - ω(12) = 1`. For any squarefree number `n` we obivously have `e(n) = 0`. The first few terms are ``` 1 0 2 0 3 0 4 1 5 0 6 0 7 0 8 2 9 1 10 0 11 0 12 1 13 0 14 0 15 0 ``` [Some more details in the OEIS wiki.](http://oeis.org/wiki/Omega(n),_number_of_prime_factors_of_n_(with_multiplicity)) [Answer] # [MATL](http://github.com/lmendo/MATL), ~~7~~ 5 bytes ``` Yfd~s ``` [Try it online!](http://matl.tryitonline.net/#code=WWZkfnM&input=MTI) Or [verify all test cases](http://matl.tryitonline.net/#code=IkAKWWZkfnM&input=MToxNQ). ### Explanation ``` Yf % Implicit input. Obtain prime factors, sorted and with repetitions d % Consecutive differences ~ % Logical negate: zeros become 1, nonzeros become 0 s % Sum. Implicit display ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 11 bytes ``` $pPd:Pr:la- ``` [Try it online!](http://brachylog.tryitonline.net/#code=JHBQZDpQcjpsYS0&input=OA&args=Wg) ### Explanation ``` $pP P is the list of prime factors of the Input Pd Remove all duplicates in P :Pr Construct the list [P, P minus duplicates] :la Apply "length" to the two elements of that list - Output is the subtraction of the first element by the second one ``` [Answer] # Mathematica, 23 bytes ``` PrimeOmega@#-PrimeNu@#& ``` Very boring. `FactorInteger` already takes up 13 bytes, and I can't see much that can be done with the remaining 10. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 5 bytes ``` ÆfI¬S ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZmScKsUw&input=&args=MTI) [Verify all testcases.](http://jelly.tryitonline.net/#code=w4ZmScKsUwoxNVLDh-KCrFk&input=) Port of [Luis Mendo's answer in MATL](https://codegolf.stackexchange.com/a/91422/48934). ``` ÆfI¬S Æf Implicit input. Obtain prime factors, sorted and with repetitions I Consecutive differences ¬ Logical negate: zeros become 1, nonzeros become 0 S Sum. Implicit display ``` [Answer] # J, ~~11~~ 10 bytes Saved 1 byte thanks to [Jonah](https://codegolf.stackexchange.com/users/15469/jonah). ``` 1#.1-~:@q: ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes ``` Òg¹fg- ``` **Explanation** ``` Òg # number of prime factors with duplicates - # minus ¹fg # number of prime factors without duplicates ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w5JnwrlmZy0&input=OQ) [Answer] # Haskell, 65 bytes ``` (c%x)n|x>n=c|mod n x>0=c%(x+1)$n|y<-div n x=(c+0^mod y x)%x$y 0%2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ò¥_O ``` Port of [*@LuisMendo*'s MATL answer](https://codegolf.stackexchange.com/a/91422/52210). [Try it online](https://tio.run/##yy9OTMpM/f//8KRDS@P9//@3AAA) or [verify the first 15 test cases](https://tio.run/##yy9OTMpM/W9o6upnr6Sga6egZO/3//CkQ0vj/f/r/AcA). **Explanation:** ``` Ò # Get all prime factors with duplicates from the (implicit) input # (automatically sorted from lowest to highest) ¥ # Get all deltas _ # Check if it's equal to 0 (0 becomes 1; everything else becomes 0) O # Take the sum (and output implicitly) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes ``` ΣẊ=p ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxUam/88tfriry7bg/38A "Husk – Try It Online") -1 byte from Dominic Van Essen. [Answer] # Pyth, 7 bytes ``` -lPQl{P ``` [Try it online.](https://pyth.herokuapp.com/?code=-lPQl%7BP&debug=0) [Answer] # C, 74 bytes ``` f(n,e,r,i){r=0;for(i=2;n>1;i++,r+=e?e-1:e)for(e=0;n%i<1;e++)n/=i;return r;} ``` [Ideone it!](http://ideone.com/C9U9SW) [Answer] # Python 2, ~~57~~ 56 bytes ``` f=lambda n,k=2:n/k and[f(n,k+1),(n/k%k<1)+f(n/k)][n%k<1] ``` *Thanks to @JonathanAllan for golfing off 1 byte!* Test it on [Ideone](http://ideone.com/Y5aGTR). [Answer] # Python 2, ~~100~~ ~~99~~ ~~98~~ 96 bytes ``` n=input() i=2 f=[] while i<n: if n%i:i+=1 else:n/=i;f+=i, if-~n:f+=n, print len(f)-len(set(f)) ``` Most of the code is taken up by a golfed version of [this SO answer](https://stackoverflow.com/a/22808285), which stores the prime factors of the input in `f`. Then we simply use set manipulation to calculate the excess factors. *Thanks to Leaky Nun for saving ~~1~~ 3 bytes!* [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 11 bytes ``` $p@b:la:-a+ ``` [Try it online!](http://brachylog.tryitonline.net/#code=JHBAYjpsYTotYSs&input=MTI&args=Wg) [Verify all testcases.](http://brachylog.tryitonline.net/#code=MTV5YjoxYTokQGF-QG53CiRwQGI6bGE6LWEr&input=) (The wrapper is longer than the function...) ``` $p@b:la:-a+ $p prime factorization @b group blocks of equal elements :la length of each :-a each minus 1 + sum ``` [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 113 bytes ``` readIO t=2 lbla e=0 GOTO b lblc i/t e+1 lblb m=i m%t n=1 n-m if n c d=e d/d e-d r+e A=i A-1 t+1 if A a printInt r ``` [Try it online!](http://silos.tryitonline.net/#code=cmVhZElPCnQ9MgpsYmxhCmU9MApHT1RPIGIKbGJsYwppL3QKZSsxCmxibGIKbT1pCm0ldApuPTEKbi1tCmlmIG4gYwpkPWUKZC9kCmUtZApyK2UKQT1pCkEtMQp0KzEKaWYgQSBhCnByaW50SW50IHI&input=&args=MTI) A port of my [answer in C](https://codegolf.stackexchange.com/a/91429/48934). [Answer] ## Javascript (ES6), ~~53~~ ~~51~~ 46 bytes ``` e=(n,i=2)=>i<n?n%i?e(n,i+1):e(n/=i,i)+!(n%i):0 ``` *Saved 5 bytes thanks to Neil* Example: ``` e=(n,i=2)=>i<n?n%i?e(n,i+1):e(n/=i,i)+!(n%i):0 // computing e(n) for n in [1, 30] for(var n = 1, list = []; n <= 30; n++) { list.push(e(n)); } console.log(list.join(',')); ``` [Answer] # Bash, 77 bytes ``` IFS=$'\n ' f=(`factor $1`) g=(`uniq<<<"${f[*]}"`) echo $((${#f[*]}-${#g[*]})) ``` Complete program, with input in `$1` and output to stdout. We set `IFS` to begin with a newline, so that the expansion `"${f[*]}"` is newline-separated. We use arithmetic substitution to print the difference between the number of words in the factorisation with the result of filtering through `uniq`. The number itself is printed as a prefix by `factor`, but it is also present after filtering, so falls out in the subtraction. [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` k äÎxÌ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ayDkznjM&input=OA) ``` k äÎxÌ :Implicit input of integer k :Prime factors ä :Consecutive pairs reduced by Î : Signs of differences (0 or -1) x :Sum of Ì : Signs of differences with -1 (0 -> 1 and -1 -> 0) ``` [Answer] # [Factor](https://factorcode.org) + `math.primes.factors math.unicode`, 40 bytes ``` [ group-factors unzip Σ swap length - ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NYw_CsIwFMZ3T_FGBxvUSfQA4uJSnIpDjK-x2LzEvATRq7gEpB7HvbexkDp9P75_r08tVbA-9fpQ7vbbNRgZLsJL0siZnW8Mssg9Bsls1RhFapQ9I1zRE7bAeItIahyC8xjCY5hTgM1kOYdqMTsduxjqYtVPK9DeRlf8fyM9GwffN_BdOmiR9HBRwNjvzGCKzCll_QE) ``` ! 12 group-factors ! { { 2 2 } { 3 1 } } unzip ! { 2 3 } { 2 1 } Σ ! { 2 3 } 3 swap ! 3 { 2 3 } length ! 3 2 - ! 1 ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 4 bytes ``` ḋ₋¬Ʃ ``` [Try it online!](https://tio.run/##K6gs@f//4Y7uR03dh9YcW/n/vwUA "Pyt – Try It Online") Port of [Leaky Nun's Jelly answer](https://codegolf.stackexchange.com/questions/91420/excessive-integers/91424#91424) [Answer] # [Haskell](https://www.haskell.org/), 87 bytes ``` import Data.Numbers.Primes import Data.List x=(\x->length x-length(nub x)).primeFactors ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRz680Nym1qFgvoCgzN7WYC1nKJ7O4hKvCViOmQtcuJzUvvSRDoUIXwtDIK01SqNDU1CsAaXNLTC7JLyr@n5uYmWcLFMkrUalQMDT6DwA "Haskell – Try It Online") [Answer] # [Kamilalisp](https://github.com/kspalaiologos/kamilalisp), 15 bytes ``` [-&[⍴] #0 ⊙]@⋔⌹ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70qOzE3MycxJ7O4YMEyjZTUNIW0paUlaboW26N11aIf9W6JVVA2UHjUNTPW4VH3lEc9OyGyN0M0ubg0MvOtyosyS1Jz8hRiikuKrNLyi3ITSxSUUjUsNBVsFarTFCxqlTTxqTM0gCo0NACqhJi9YAGEBgA) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes ``` ƒ←∑ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FiuOTXrUNuFRx8QlxUnJxVDBBTeVDbmMuIy5TLhMucy4zLksuCy5DA24DA25DI24DI25DE24DE0hagE) ``` ƒ Factor; returns a list of unique prime factors and a list of their exponents ← Decrement the exponents ∑ Sum ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, 31 bytes ``` ->n{n.prime_division.sum{_2-1}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcnW0km5RQVFmbqpS7CI326WlJWm6Fvt17fKq8_TAwvEpmWWZxZn5eXrFpbnV8Ua6hrW1EFU3VRyD3N30UhOTM-JzMvNSFVLyuRQUChTcouMN9Ury4zNjuVLzUiBqF9xUNuQy4jLmMuEy5TLjMuey4LLkMjTgMjTkMjTiMjTmMjThMjSFqAUA) [Answer] # Python, (with sympy) 66 bytes ``` import sympy;lambda n:sum(x-1for x in sympy.factorint(n).values()) ``` `sympy.factorint` returns a dictionary with factors as keys and their multiplicities as values, so the sum of the values is `Ω(n)` and the number of values is `ω(n)`, so the sum of the decremented values is what we want. [Answer] # CJam, 11 bytes ``` ri_mf,\mF,- ``` [Try it online!](http://cjam.tryitonline.net/#code=cmlfbWYsXG1GLC0&input=NA) **Explanation** ``` ri_ Get an integer from input and duplicate it mf, Get the number of prime factors (with repetition) \ Swap top 2 elements on the stack mF, Get the number of prime factors (with exponents) - Subtract ``` [Answer] **C, 158** ``` #define G(a,b) if(a)goto b #define R return f(n,i,j,o,w){if(!n)R 0;o=w=i=j=0;a:i+=2;b:if(n%i==0){++j;G(n/=i,b);}o+=!!j;w+=j;i+=(i==2);j=0;G(i*i<n,a);R w-o;} ``` In the start there is the goto instruction... even if this is more long than yours it is more readable and right [if i not consider n too much big...] one Language that has 10000 library functions is wrost than a Language that with few, 20 or 30 library functions can do all better [because we can not remember all these functions] ``` #define F for #define P printf main(i,r) {F(i=0; i<100; ++i) r=f(i,0,0,0,0),P("[%u|%u]",i,r); R 0; } /* 158 [0|0][1|0][2|0][3|0][4|1][5|0][6|0][7|0][8|2] [9|0][10|0][11|0][12|1][13|0][14|0][15|0][16|3] [17|0][18|0][19|0][20|1][21|0][22|0][23|0][24|2][25|1][26|0][27|0] [28|1] [29|0][30|0][31|0][32|4][33|0][34|0][35|0][36|1] [37|0][38|0][39|0][40|2][41|0] */ ``` [Answer] # GNU sed + coreutils, 55 bytes (including +1 for `-r` flag) ``` s/^/factor /e s/ ([^ ]+)(( \1)*)/\2/g s/[^ ]//g y/ /1/ ``` Input in decimal, on stdin; output in unary, on stdout. ## Explanation ``` #!/bin/sed -rf # factor the number s/^/factor /e # remove first of each number repeated 0 or more times s/ ([^ ]+)(( \1)*)/\2/g # count just the spaces s/[^ ]//g y/ /1/ ``` [Answer] # APL(NARS) 35 chars, 70 bytes ``` {⍵=1:0⋄k-⍨+/+/¨{w=⍵⊃v}¨⍳k←≢v←∪w←π⍵} ``` the function π find the factorization in prime of its argument; there is few to say it seems clear, but for me does more operations (from factorization) than the minimum...the range of count characters is out golfing languages because it seems too much count, but less than not golfing languages... test: ``` f←{⍵=1:0⋄k-⍨+/+/¨{w=⍵⊃v}¨⍳k←≢v←∪w←π⍵} f¨1..15 0 0 0 1 0 0 0 2 1 0 0 1 0 0 0 ``` [Answer] # [Arturo](https://arturo-lang.io), 47 bytes ``` $=>[k:tally factors.prime&(∑values k)-size k] ``` [Try it!](http://arturo-lang.io/playground?KXg2zX) ]
[Question] [ # Introduction Sisyphus was having some troubles at work lately. It seems he just never gets anything done, and he would love to find a solution to this problem. His current employment requires rolling a rock up a hill. He usually does his job well, but every time he is near the top of the hill it rolls down again. He is getting really frustrated with his job and wants to solve the problem scientifically by having a computer simulate the rock rolling down the hill. It so happens that Sisyphus isn't particularly good at programming, so maybe you can help him out? # The Challenge After this silly introduction, let's come to business. Your program will receive an illustration of the hill and the rock which looks similar to this: ``` #o ## ### ###### ######## ``` Where `#` represents a part of the hill and `o` represents the rock. You now have to implement a program which moves the rock 1 layer down. For example, the output of the above should be: ``` # ##o ### ###### ######## ``` If there is a horizontally even area, the hill just rolls horizontally, so... ``` o ######## ``` ...this would just make the stone roll sideways. ``` o ######## ``` If there is a vertical area, the rock falls down one step, so... ``` #o # # ##### ``` ...would yield... ``` # #o # ##### ``` You will also receive the width and height of the image respectively in one line above the image. So, in complete, our sample input would look like this: ``` 10 5 #o ## ### ###### ######### ``` *(Note that the whitespace here are spaces. Select the text and see what I mean.)* ## Some details * When the rock is already in the last line when running the program, you can choose to either terminate the program or output the unchanged input * The hill only ever goes downwards * Your program should format the output exactly the same as the input (including the dimensions), so if you pipe the output of the program to itself, it calculates the next step. * You can assume there is always a way to the bottom, so input where the path is "blocked" may cause undefined behaviour * You can assume there is always a space in the last line. The rock should "rest" there, so after calling the program a few times, always piping it's output into itself, you should end up with the rock in the last line, laying where the space previously was. * You may accept input in any form you like (stdin, file,...). You have to post the WHOLE program (so all pre-initialized variables count as code). * The lines are terminated with `\n`. * You can get some example inputs [here](http://pastebin.com/1yadFynA) (make sure you copy the spaces correctly!) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the working submission with the least **bytes** wins. * The winner will be chosen on July 26th, 2014. You can post solutions after that, but you can't win If you have any questions, let me know in the comments. **Happy golfing!** [Answer] ## Regex (.NET, Perl, PCRE, JavaScript, ... flavours), 25 bytes Yes, this will create some debate again, whether a regular expression is a valid program, but I'll pre-empt that and say that this submission is just for fun and doesn't need to be considered for the winner. (As opposed to the 31 byte Perl variant at the bottom ;).) So here is a pure regex replacement solution. Pattern (note the trailing space): ``` o(( *)\n#*)(?=\2) |o ``` Replacement (note the leading space): ``` $1o ``` The byte count is for the sum of the two. You can test it at <http://regexhero.net/tester/>. Make sure to choose Unix-style line endings and "preserve pasted formatting" when pasting. If it still doesn't work, you still have pasted Windows-style line endings. The easiest fix in that case is to replace `\n` with `\r\n` in the pattern to see that it works. Here is a **48 byte** ECMAScript 6 function using this ``` f=(s)=>s.replace(/o(( *)\n#*)(?=\2) |o /,' $1o') ``` Finally, I've also got an actual program. It's **31 bytes** of Perl (including two bytes for `p` and `0` flags; thanks to Ventero for the suggestion!). ``` s/o(( *)\n#*)(?=\2) |o / $1o/ ``` If you want to test it, don't even save it in a file, just do ``` perl -p0e 's/o(( *)\n#*)(?=\2) |o / $1o/' < hill.txt ``` [Answer] # Python - 190 Slicing and concatenation horror, along with way too many variables. I'm certain this can be golfed more, but I can't think of any clever python functions right now. Input is stored in string `s`. ``` r=" " o="o" i=s.index(o) b=i+int(s.split(r)[1]) q=s[:i]+r x=s[b+3:] try: a=s[b+1:b+3] if a[0]==r:s=q+s[i+1:b+1]+o+r+x elif a[1]==r:s=q+s[i+1:b+2]+o+x else:s=q+o+s[i+2:] except:1 print(s) ``` Since python strings are immutable, I replace a character by concatenating all the characters before, my new character, and all the characters after. I use the hill width and indexing to determine where the rock should roll to. [Answer] ## Ruby, 65/55 characters Figured I'd see how long a solution is that doesn't just throw a regex on the problem. ``` r=gets p r[r[(r[k=1+~/o/+x=r.to_i,2]=~/ /||-x)+k]&&=?o]=" " $><<r ``` As expected, it's not as short as m.buettner's regex solution - but not much longer either. When using interpreter flags, this can be shortened to 55 characters (53 for the code, 2 for the flags): ``` sub$_[($_[k=1+~/o/+x=$_.to_i,2]=~/ /||-x)+k]&&=?o," " ``` Run the code like this: ``` ruby -p0e 'sub$_[($_[k=1+~/o/+x=$_.to_i,2]=~/ /||-x)+k]&&=?o," "' < input ``` [Answer] ## HTML JavaScript - 251 chars (**251** if you count the code inside the single quotes that reads the input and returns the output. **359** if you count the input box, input string, button, etc. **192** if you count just that does the work.) **Golf code:** ``` <pre id="i">10 5 #o ## ## ###### ######### </pre><button onclick='i=document.getElementById("i");h=i.innerHTML;if(p=h. match(/([\s\S]*?)([# ]+)(o *\n)(#+)([\s\S]*)/)){if(p[4].length>p[2].length+1)p[3]=p[3]. replace("o "," o");else{p[3]=p[3].replace("o"," ");p[5]="o"+p[5].substr(1);}p[0]=""; h=p.join("");}i.innerHTML=h;'>Go</button> ``` <http://goo.gl/R8nOIK> ![click "Go" over and over](https://i.stack.imgur.com/TZ7pp.png) Click "Go" over and over. **Method** I uses String.match() to break hill into 5 parts, then I change one or two parts. I'm learning JavaScript, so any suggestions would be appreciated. **Readable Code** ``` <pre id="io">10 5 #o ## ## ###### ######### </pre> <button onclick=' // get image io = document.getElementById("io"); image = io.innerHTML; // break image into five parts // 1(10 5\n# \n## \n) 2(### ) 3(o \n) 4(######) 5( \n######### ) if (parts = image.match(/([\s\S]*?)([# ]+)(o *\n)(#+)([\s\S]*)/)) { // move rock to the right if (parts[4].length > parts[2].length + 1) parts[3] = parts[3].replace("o ", " o"); // or move rock down else { parts[3] = parts[3].replace("o", " "); parts[5] = "o" + parts[5].substr(1); } // return new image parts[0] = ""; image = parts.join(""); // MAP io:i image:h parts:p } io.innerHTML = image; '>Go</button> ``` [Answer] # Python 2 - ~~289~~ 252 bytes ``` p=raw_input w,h=map(int,p().split()) m=[p()for a in[0]*h] j=''.join f=lambda s:s.replace('o ',' o') for i,r in enumerate(m): x=r.find('o') if x+1:y=i;break if m[y+1][x]=='#':m=map(f,m);x+=1 print w,h print'\n'.join(map(j,zip(*map(f,map(j,zip(*m)))))) ``` I made some significant improvements but this is still terrible. A couple more bytes can be saved by converting this to Python 3 but I can't be arsed. First, I find the rock. If the character immediately below it is `'#'`, replace every instance of `'o '` with `' o'`. Since there's guaranteed to be an extra space at the end, this will always move the rock to the right. Regardless of if I just did that or not, I transpose the whole grid with `zip(*m)`. Then, I do another replacement of `'o '` with `' o'`. If there's a space to the right of the rock, that means that in the real grid there's a space below it, so it gets moved. Then I transpose back and print. [Answer] # Python (201) ``` import sys print(input()) g=list(sys.stdin.read()) o='o' x=g.index(o) n=x+g.index('\n')+1 try: if g[n]==' ':g[n]=o elif g[n+1]==' ':g[n+1]=o else:g[x+1]=o g[x]=' ' except:1 print(*g,sep='',end='') ``` [Answer] # awk, 152 ``` awk 'NR==1{w=$2}{if(NR<=w&&$0~/o/){r=index($0,"o");g=$0;getline;if(index($0,"# ")<=r){sub("o"," ",g);sub(" ","o")}else{sub("o "," o",g)}print g}print}' ``` ## More Readable ``` awk ' NR==1{ //If we're at the first line, set the width from the second column in the header. width=$2 } { if(NR<=width && $0~/o/){ //If not at the bottom, look for the line with the rock. rockIndex=index($0,"o"); //Set the position of the rock. orig=$0; //Remember the current line so we can compare it to the next. getline; //Get the next line. if(index($0,"# ")<= rockIndex){ //Move down: if the rock is on a cliff or on a slope, sub("o"," ",orig); //update the orig so that the rock is removed sub(" ", "o") //and update the current (first available position). } else { //Move right: if the rock is on flat ground, sub("o "," o", orig) //update the orig so the the rock is advanced. } print orig //Print the line we skipped (but stored } //and updated based on the line we're now on). print //Print the line we're now on. } ' ``` [Answer] ## php 485 484 chars I know this is massive compared to entry by m.buettner but is best I can do for now. I think there must be a quicker way to turn the input string into a multi dimensional array but it is very late now. And although it it uncompetitive I liked this puzzle. Would like the extension to show where the ball ends up, or after a set number of steps, perhaps added after the width and height on the input line. Could add that very easily to this version. Here is my code: Input is in the first variable. ``` <? $a.='10 5 #o ## ### ###### #########';$b=array();$c=explode("\n",$a);$d=explode(" ",$c[0]);$e=$d[0];$f=$d[1];unset($c[0]);$g=0;foreach($c as $h){$b[$g]=str_split($h);++$g;}for($i=0;$i<$f;++$i){for($j=0;$j<$e;++$j){if($b[$i][$j]=='o'){$k=$j;$l=$i;$b[$i][$j]=' ';}}}if($b[$l+1][$k]!='#'){$b[$l+1][$k]='o';}else if($b[$l+1][$k+1]!='#'){$b[$l+1][$k+1]='o';}else{$b[$l][$k+1]='o';}echo"$e $f\n";for($i=0;$i<$f;++$i){for($j=0;$j<$e;++$j){echo $b[$i][$j];}echo "\n";} ``` You can see it [here](http://codepad.org/2lO0L97W) in action on codepad Edit: Changed codepad and code above as was outputting 0 instead of o, which caused problem when I tried to feed the output back into the program. Fixed now and saved one char! [Answer] ## Groovy - 263 261 256 chars Golfed. Read the file into a String, and use a function `p` to emulate a function `String.putAtIndex(index,value)`: ``` o="o" b=" " s=new File(args[0]).text z={s.size()-it} s=s[0..z(2)] w=s.find(/\n.*?\n/).size()-1 p={i,v->s=s[0..i-1]+v+((i<z(0)-2)?s[i+1..z(1)]:"")} try{ t=s.indexOf o i=w+t j=i+1 x=t+1 (s[i]==b)?x=i:(s[j]==b)?x=j:0 p x,o p t,b }catch(Exception e){} print s ``` Ungolfed (somewhat): ``` o = "o" b = " " s = new File(args[0]).text z = {s.size()-it} s = s[0..z(2)] w = s.find(/\n.*?\n/).size()-1 putAtIndex = { i,val -> s = s[0..i-1] + val + ((i<z(0)-2)?s[i+1..z(1)]:"") } try { t=s.indexOf o i=w+t j=i+1 x=t+1 // default x as horizontal move // check for (a) directly below (b) below and over one (s[i]==b) ? x=i : ( (s[j]==b) ? x=j : 0) putAtIndex x,o putAtIndex t,b } catch (Exception e) {} print s ``` [Answer] ## R, 234 ``` require(stringr) g=scan(,"") g=do.call(rbind,strsplit(str_pad(g,m<-max(nchar(g)),"r"),"")) if(g[(x<-which(g=="o"))+1]==" "){g[x+1]="o";g[x]=""}else{if(!is.na(g[x+1])){g[x+(n<-nrow(g))]="o";g[x]=""}} for(i in 1:n) cat(g[i,],"\n",sep="") ``` String manipulation is not R's strongest point. More readably: ``` require(stringr) # load package `stringr`, available from CRAN. required for `str_pad` g=scan("") # read input from console g=do.call( # applies the first argument (a function) to the second argument (a list of args to be passed) rbind, # "bind" arguments so that each one becomes the row of a matrix strsplit( # split the first argument by the second str_pad(g,max(nchar(g)),"r"," "), # fill each row with whitespace "") ) if(g[(x<-which(g=="o"))+1]==" ") { # if the next element down from the "o" is " "... g[x+1]="o";g[x]="" # make it an "o" and replace the current element with "" } else { if(!is.na(g[x+1])) { # if the next element down is not empty (i.e. out of range) g[x+nrow(g)]="o"; g[x]="" # move "o" right } } for(i in 1:n) cat(g[i,],"\n",sep="") # print to console ``` [Answer] # C (182) ``` char b[1024],*x,*n;main(z){read(0,b,1024);n=index(b,10)+1;x=index(n,'o');z=index(n,10)-n;n=x+z+1;if(n[1]){if(*n==32)*n='o';else if(n[1]==32)n[1]='o';else x[1]='o';*x=32;}printf(b);} ``` Or, if you actually want to read the code: ``` char b[1024],*x,*n; //1024 byte buffer hard coded main(z){ read(0,b,1024); n=index(b,10)+1; //start of line 2 x=index(n,'o'); z=index(n,10)-n; //10='\n' n=x+z+1; //reusing n if(n[1]){ //if not 0 if(*n==32) //32=' ' *n='o'; else if(n[1]==32) n[1]='o'; else x[1]='o'; *x=32; } printf(b); } ``` [Answer] ## Clojure - 366 chars Without regex. Required input file named "d". Golfed: ``` (def s(slurp "d"))(def w(-(.length(re-find #"\n.*?\n" s))2))(def t(.indexOf s "o"))(def i(+ t w 1))(defn g[i,j,x,c](cond (= x i) \ (= x j) \o :else c))(defn j[i,j] (loop[x 0](when(< x (.length s))(print(g i j x (.charAt s x)))(recur(inc x)))))(try(cond(= \ (.charAt s i))(j t i)(= \ (.charAt s (inc i)))(j t (inc i)):else (j t (inc t)))(catch Exception e (print s))) ``` Ungolfed: ``` (def s (slurp "d")) (def w (- (.length (re-find #"\n.*?\n" s)) 2)) (def t (.indexOf s "o")) (def i (+ t w 1)) (defn g [i,j,x,c] (cond (= x i) \ (= x j) \o :else c)) (defn j [i,j] (loop [x 0] (when (< x (.length s)) (print (g i j x (.charAt s x))) (recur (inc x))))) (try (cond (= \ (.charAt s i)) (j t i) (= \ (.charAt s (inc i))) (j t (inc i)) :else (j t (inc t)))(catch Exception e (print s))) ``` Sample run (just one case, for brevity): ``` bash-3.2$ cat d 6 7 # # # ## o #### #### ##### bash-3.2$ java -jar clojure-1.6.0.jar hill.clj 6 7 # # # ## ####o #### ##### ``` I'm a newbie. Suggestions welcome. [Answer] # MATLAB, 160 ``` function r(f) F=cell2mat(table2array(readtable(f))); m=@(d)mod(d-1,size(F,1));C=find(F=='o');P=find(F==' ');N=min(P(P>C&m(P)>=m(C)));F([C,N])=F([N,C]); disp(F); ``` The painful part is the file-input. The actual computation would be only 114 bytes: ``` function F=r(F) m=@(d)mod(d-1,size(F,1));C=find(F=='o');P=find(F==' ');N=min(P(P>C&m(P)>=m(C)));F([C,N])=F([N,C]); ``` ]
[Question] [ Inspired by this: <http://nolandc.com/smalljs/mouse_reveal/> [(source)](https://github.com/NolanDC/smalljs/tree/master/mouse_reveal). A valid answer: * Takes a number \$w\$ and (assumed non-negative) integer \$x\$. * Starts with an integer list with a length of \$2^w\$, initially filled with zeroes. * For each number \$n\$ from \$0\$ to \$w-1\$ (inclusive), divides the list into sub-lists of size \$2^n\$, then increments all of the values in the sub-list that contains the index \$x\$. * Returns this list (Of course a program doesn't have to do exactly this if it returns the right results. If someone finds a good declarative algorithm I will upvote it.) ## Examples (examples are 0 indexed, your answer doesn't have to be) ``` w=3, x=1 23110000 w=2, x=2 0021 w=3, x=5 00002311 w=4, x=4 1111432200000000 w=2, x=100 Do not need to handle (can do anything) because x is out of bounds ``` ### Example of basic algorithm for \$w=3, x=5\$ * List is \$[0,0,0,0,0,0,0,0]\$ * \$n\$ is \$0\$, list is split into \$[[0],[0],[0],[0],[0],[0],[0],[0]]\$, \$x\$ is in sixth sub-list, list becomes \$[0,0,0,0,0,1,0,0]\$ * \$n\$ is \$1\$, list is split into \$[[0,0],[0,0],[0,1],[0,0]]\$, \$x\$ is in third sub-list, list becomes \$[0,0,0,0,1,2,0,0]\$ * \$n\$ is \$2\$, array is split into \$[[0,0,0,0],[1,2,0,0]]\$, \$x\$ is in second half, array becomes \$[0,0,0,0,2,3,1,1]\$ * Result is \$[0,0,0,0,2,3,1,1]\$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2*Ḷ^‘l2Ċ⁸_ ``` A dyadic Link that accepts \$w\$ on the left and \$x\$ on the right and yields a list of integers. **[Try it online!](https://tio.run/##y0rNyan8/99I6@GObXGPGmbkGB3petS4I/7////G/00B "Jelly – Try It Online")** ### How? ``` 2*Ḷ^‘l2Ċ⁸_ - Link: integer, w; integer x e.g. 3; 5 2 - two 2 * - (2) exponentiate (w) 8 Ḷ - lowered range [0,1,2,3,4,5,6,7] ^ - XOR (x) [5,4,7,6,1,0,3,2] ‘ - increment [6,5,8,7,2,1,4,3] l2 - log base two [2.58,2.32,3,2.80,1,0,2,1.58] Ċ - ceiling [3,3,3,3,1,0,2,2] ⁸ - chain's left = w 3 _ - subtract [0,0,0,0,2,3,1,1] ``` --- Without floating points involved, also 10: `2*Ḷ^ḤBẈ⁸_‘` ...would be 8 if `0` in binary were `[]` rather than `[0]` (`2*Ḷ^BẈ⁸_`) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` ox<Ÿ^bεÀ1k ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/v8Lm6I64pHNbDzcYZv//b8RlBAA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##yy9OTMpM/V9WmVD8P7/C5uiOuKRzWw83GGb/r9X5Hx1trGMYq6MQbaRjBKKMdUxBlImOSWwsAA) The idea is to count for each index how many leading bits are the same as \$x\$'s bits. `ox<Ÿ` push integers between \$2^w\$ and \$2^{w+1}-1\$. `^` xor every integer in the range with \$x\$. `b` convert each number to binary. `ε` for each binary string: `À` rotate the leading \$1\$ to the back. `1k` find the index of the first \$1\$. This is first bit that differs between the current index and \$x\$. [Answer] # [J](http://jsoftware.com/), 29 28 27 bytes ``` +/@(<./\)@({=|:@])2#:@i.@^] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfUdNGz09GM0HTSqbWusHGI1jZStHDL1HOJi/2typSZn5CsYKqQpGEOYRgrGQK4hUD8E6lohy4JEjIACQFEjoKgRQhQiA9ELlDVF6DGEQhOgrBEQGqBBoGoToGqT/wA "J – Try It Online") Consider `1 f 3`: * `[:#:@i.2^]` Numbers 0 through `2^n-1` in binary: ``` 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 ``` * `{` From those, the item at index 1: ``` 0 0 1 ``` * `=|:@]` Check elementwise equality between that and every number from step 1 (note only the element itself is equal everywhere `1 1 1`). We also transpose the result: ``` 1 1 1 1 0 0 0 0 1 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1 ``` * `<./\` Column-wise cumulative minimum: ``` 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 ``` * `+/` Column-wise sum: ``` 2 3 1 1 0 0 0 0 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 22 bytes ``` W:~Ti(1Gq:W"t@etaY|1e+ ``` Inputs *w*, then *x*, where *x* is 1-based. [Try it online!](https://tio.run/##y00syfn/P9yqLiRTw9C90CpcqcQhtSQxssYwVfv/fxMuUwA) Or [verify all test cases](https://tio.run/##y00syfmf8D/cqi4kU8PQvdAqXKnEIbUkMbLGMFX7f6xLVEXIf2MuIyA0BkIzLhMuUwA). ### Explanation ``` W % Input (implicit): w. Exponential with base 2. Gives 2^w :~ % Range, negate. Gives [0 0 ... 0] (row vector with length 2^w) T % Push true (1) i % Input: x ( % Write 1 at position x (1-based). Gives for example [0 1 0 0 0 0 0 0] 1G % Push w again q: % Subtract 1, range. Gives [1 2 ... w-1] W % Exponential with base 2, element-wise. Gives [2 4 ...2^(w-1)] " % For each k in [2 4 ...2^(w-1)] t % Duplicate the current row vector; initially [0 1 0 0 0 0 0 0] @e % Reshape with k rows, in column-major order. For example, for k=2 this % gives [0 0 0 0; % 1 0 0 0] ta % Duplicate, any. For each column, gives true if there is some nonzero % In the example this gives [1 0 0 0] Y| % Logical "or", element-wise with broadcast. In the example this gives % [1 0 0 0; % 1 0 0 0] 1e % Reshape with 1 row. In the example this gives [1 1 0 0 0 0 0 0] + % Add, element-wise. In the example this gives [1 2 0 0 0 0 0 0] % End (implicit) % Display (implicit) ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` 0#x=[0] w#x|(a,b:c)<-splitAt x$(w-1)#div x 2<*".."=a++b+1:c ``` [Try it online!](https://tio.run/##LU7LbsIwELz7K1YECad51I/0QmMk7vwB4mCwaa2GxHLcxkj8e9i0ndPOjGZnPvX4ZbtunlmW1JGdyJSlB9XleXvJ22r0nYv7CGlNp4rnmXE/kEC0L6u6XildFOeCby/zTbtemYEAdeWAsetNe2rC4EHm9eh1T1/Vptrk7Xr3YePB9ZZAZ@NxKtNJBasNGtMQzAju/f4r1P47WFTxpw@ujxRnKXUvMYENBJbGWQKHagdCcs4QRIBYOGOCEwlvfzcy9EkDzcI5opFCsH88AQ "Haskell – Try It Online") ## How? Recursive implementation, starting from the base case `0#x=[0]`. To compute `w#x`, perform the following steps (exemplified with `w=3`, `x=1`). ``` Compute (w-1)#div x 2 -- 2#0 = [2,1,0,0] Duplicate every number -- [2,2,1,1,0,0,0,0] Add +1 to the number at position x -- [2,3,1,1,0,0,0,0] ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~22~~ 18 bytes -4 bytes thank sto coltim! ``` {+/&\t=(+t:!x#2)y} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlpbXy2mxFZDu8RKsULZSLOy9n9atLG1YSxXWrSRtRGIMrY2BVEm1iax/wE "K (ngn/k) – Try It Online") [Answer] # JavaScript (ES6), 60 bytes Expects `(w)(x)`. Returns a string. ``` w=>g=(x,i)=>i>>w?'':(h=k=>k--&&!((i^x)>>k)+h(k))(w)+g(x,-~i) ``` [Try it online!](https://tio.run/##ZYzNDoIwEITvPAVeYDdYaQteTLq@iQlBfmoJNWKEk69eN0QP6pe5zTdzqR7VVN/s9S5Gf25Ca8JsqDOwbC0askTzMU0P0BtnyAmRJBsAe1qQyGHWg0OEGbOOffG0GGo/Tn5odoPvoIUCQSHGeR7rQinJRN@CRs4qSKlV9Lfef0qu@eFHKJGzCoopC63lm/AC "JavaScript (Node.js) – Try It Online") [Answer] # Java, ~~88~~ ~~85~~ 84 bytes ``` x->w->{int a,r[]=new int[w=1<<w];for(;w>1;)for(a=w/=2;a-->0;++r[a+x/w*w]);return r;} ``` *Saved 1 byte thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).* [Try it online!](https://tio.run/##pZC9boMwFIV3nsIjLsEpaTMZLHWp1KFTRsTgEkCmYCP7EgdFPDt1xM@SLb2Lv3uOdXTsml94WJ9/J9F2SgOq3U56EA350JoPhnoPRtnLHISS5HMB6nld/9OIHOUNNwZ9cyHRzUNuFt0AB3dclDij1rn@CbSQVZohriuD57v3WSPjLwlFVejdgyAkpBljZTJdQ2ZDdnMC4judZoksLLrbNoni2Ga0VNqnlkUU34kndp8cKA9D9kqDQKc8uO7ti80w1QX0WiJNx2ktQrdKp8FA0RLVA@lcaWikP38NATU/wy8J77pm8CO8wBvG@KmEA97gyYTjvzu84w3WhNEbpz8) [Answer] # [R](https://www.r-project.org/), ~~50~~ 46 bytes ``` function(w,n)w+-log2(bitwXor(1:2^w-1,n)+1)%/%1 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jXCdPs1xbNyc/3UgjKbOkPCK/SMPQyiiuXNcQKKNtqKmqr2r4P03DRMdEkytNw1jHVPM/AA "R – Try It Online") A function taking `w` and `n` as arguments and returning a vector of integers. Saved 18 bytes by changing tack to an R version of [@JonathanAllan’s clever Jelly solution](https://codegolf.stackexchange.com/a/225467/42248). Thanks to @pajonk for saving 4 bytes! --- # Original version: [R](https://www.r-project.org/), 68 bytes ``` function(w,n)colSums(matrix(1:2^w-1,w,2^w,T)%/%(y=2^(1:w-1))==n%/%y) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jXCdPMzk/J7g0t1gjN7GkKLNCw9DKKK5c11CnXAdI64RoquqralTaGsUBJYDCmpq2tnlAoUrN/2kaJjommv8B "R – Try It Online") [Answer] # Haskell, 59 bytes ``` w%x=[sum[1|k<-[0..w-1],i`div`2^k==x`div`2^k]|i<-[0..2^w-1]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X0NZ0zYls0xPwyhOk6tctcI2urg0N9qwJttGN9pAT69c1zBWJ1M529a2Qjk7tiYTImoUBxKP/Z@bmJlnW1CUmVeiYaxqqPkfAA "Haskell – Try It Online") For each `i` in `[0..2^w-1]` we count all the `k ∈ [0..w-1]` such that \$ \big\lfloor \frac{\mathtt i}{2^\mathtt k} \big\rfloor = \big\lfloor \frac{\mathtt x}{2^\mathtt k} \big\rfloor \$. [Answer] # [Python 3](https://docs.python.org/3/), ~~57~~ 54 bytes The same approach as [my other answer](https://codegolf.stackexchange.com/a/225456/64121). -3 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)! ``` lambda w,x:[w+3-len(bin(2*(n^x)))for n in range(2**w)] ``` [Try it online!](https://tio.run/##FYpBCsIwEADvvmKPu3U9mNRLwZekKaTYaKBuSygkvj51TwMzs/@Ozya2xefY1vCdXwEK18GVq72ti@CcBE2HMlUiilsGgSSQg7yXv@8K@aa2MFQNzlm@ewZn2CgsPxQ9994PF4A9Jzkwov5E7QQ "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` Ṭo2*0ẋƲ}WŒH€Ẏ$⁹СḊSṁ$€€F€S ``` [Try it online!](https://tio.run/##y0rNyan8///hzjX5RloGD3d1H9tUG350ksejpjUPd/WpPGrceXjCoYUPd3QFP9zZqAIUBSI3IA7@//@/6X8TAA "Jelly – Try It Online") This is probably entirely the wrong approach. ``` Ṭo2*0ẋƲ}WŒH€Ẏ$⁹СḊSṁ$€€F€S Main Link; take `x` on the left and `w` on the right; `x` is one-indexed Ṭ An array with a 1 in index `x` o Logical OR with (to get the array to the right size) ----Ʋ} (Four links applied to the right argument) 2*0ẋ [0] * (2 ^ w) W Wrap this into a list; [[0, ..., 1, ..., 0]] ⁹С Repeat w times, collecting intermediate results [.]-$ (Apply these two links) ŒH€ Split each sublist into two halves Ẏ Tighten; dump these halves into the list itself Ḋ Remove the first sublist (we could also decrement the final sum) € For each stage / collected intermediate --$€ For each sublist, apply two links S Sum of the list (could be maximum too) ṁ Molded to the shape of the list F€ Flatten each S and sum the result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` 2*rḤ$Ṗ^Bṙ€1i€1’ ``` [Try it online!](https://tio.run/##y0rNyan8/99Iq@jhjiUqD3dOi3N6uHPmo6Y1hpkg4lHDzP///5v8NwEA "Jelly – Try It Online") Port of [ovs' 05AB1E answer](https://codegolf.stackexchange.com/a/225456/66833) ## How it works ``` 2*rḤ$Ṗ^Bṙ€1i€1’ - Main link. Takes W on the left and X on the right 2* - 2 ** W $ - Last 2 links as a monad f(2 ** W): Ḥ - 2 ** (W+1) r - Inclusive range Ṗ - Right-exclusive range ^ - XOR with X B - Convert to binary ṙ€1 - Rotate each one step to the left i€1 - First index of 1 in each ’ - Decrement ``` [Answer] # C++, 86 bytes ``` [](int w,int x){int*r=new int[w=1<<w],a;for(;a=w/=2;)for(;a--;++r[a+x/w*w]);return r;} ``` [Try it online!](https://tio.run/##VZBNbsMgEIX3PsVIXRhirMRusgmQi1AWCOMKKcERxsVSlbM7EFv9mc2b92YYfULf7/Wn1subdfo6dYbZYQzeqNul@BpsB8GMAakpDNAT6wJEAllm/F1AqtTvwAOHHkUyY/oK@8GjvGRTfqBJGDTAGMTUVxWGMXTnsx6mkEMvrMxaQrm@/jctP9wWd@ZqghHS0@JR5Os3ZR1KGCscX4REK@DGl9E8dyZmSBF5w1iURNFMRxWPe95SvJq6plXlharmfdxFiak3YfIOPH0stHh9QU/eSYN/TEta/Gdy@jVHckxmO3BIsMsT) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Ż2*ṪḶ:ⱮƊ=":@ɗS ``` [Try it online!](https://tio.run/##y0rNyan8///obiOthztXPdyxzerRxnXHumyVrBxOTg/@b/2oYY6Crp3Co4a51oeX63Mdbn/UtCby//9ormhjHcNYHa5oIx0jEGWsYwqiTHRMYrliAQ "Jelly – Try It Online") A dyadic link taking `w` as the left argument and `x` as the right. Returns a list of integers ## Explanation ``` Ż | 0..w 2* | 2 to the power of each of these ɗ | Following as a dyad: Ɗ | - Following as a monad Ṫ | - Tail Ḷ | - Range from 0 to this :Ɱ | - Integer divide by the remaining powers of two =" | - Equal to: :@ | - n integer divided by the same powers of two S | Sun ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` NθNη⭆X²θΣEθ⁼÷ηX²λ÷ιX²λ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oLmZ8B5AcUZeaVaASXAKl038QCjYD8cqCMkY5CoaaOQnBprgZIsFBHwbWwNDGnWMMzr8QlsywzJVUjQ0cBrjZHE6gYIZWJKgUG1v//GyuY/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ First input as a number Nη Second input as a number ² Literal `2` X Raised to power θ First input ⭆ Map over implicit range and join θ First input E Map over implicit range ι Outer index ÷ Integer divided by ² Literal 2 X Raised to power λ Inner index ⁼ Equals η Second input ÷ Integer divided by ² Literal 2 X Raised to power λ Inner index Σ Take the sum Implicitly print ``` Outputs a string, so only works for `w<10`. Add 1 byte to output a list. [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç┌┼σc┤0Θ▬-◙♂A ``` [Run and debug it](https://staxlang.xyz/#p=80dac5e563b430e9162d0a0b41&i=1,3%0A2,2%0A5,3%0A4,4&m=2) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` w=>g=(x,i)=>i>>w?'':(l=v=>v?l(v>>1)-1:w)(i^x)+g(x,-~i) ``` [Try it online!](https://tio.run/##ZYzBDoIwEETvfAU3dqNIt@CFpMufmBAEUtNQIqZw8tfrhuhBfZnbvJlbG9qlu9v5kU/@2sfBxNXwaGA7WjRsmdcmy2pwJhgOjYPATJhTvSLYy4aHUcz8aTF2flq860/OjzBAiUCIaVGkuiRSQvItaJTsglKakr/1@VNKLQ8/QoWSXSChKrVWb@IL "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 55 bytes ``` x=>g=(w,n=0,h=_=>g(w,n+!(x>>w)))=>w--?h()+h():(x--,[n]) ``` [Try it online!](https://tio.run/##XYzNCsIwEITvPkW97dLE5qdehMQHEZFS@6OURKyYvH3cFBHsMHsY9pu5N@9mbp@3x4s7f@1Sb1I0djAQmDOCjeZCKYdyC9HagIjGBs6PI2BJd4DIOTu5M6bWu9lP3W7yA/QgETRiUVWF0lIK0uYfUEheACGUXD33v3Zu5oUVUCN5ASSp1kqJr9IH "JavaScript (Node.js) – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 48 bytes ``` w$x=[w+1-ndigits(2(n⊻x),base=2) for n=0:2^w-1] ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v1ylwja6XNtQNy8lMz2zpFjDSCPvUdfuCk2dpMTiVFsjTYW0/CKFPFsDK6O4cl3D2P8grka5jkKFpkJmnkJ0tLGOYayOQrSRjhGIMtYxBVEmOiaxsVwKCgVFmXklOXkaQFs0uVLzUv4DAA "Julia 1.0 – Try It Online") Port of [ovs's answer](https://codegolf.stackexchange.com/a/225461/98541) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/223040/edit). Closed 2 years ago. [Improve this question](/posts/223040/edit) We're going rootin' tootin' cow-poke shootin! This is a simple contest, first program to draw their pistol wins. ### How it works: * I require 2 things from you, an executable, and a command to be run from a bash terminal. * The executable needs to do one thing: wait until it receives 'draw!' from STDIN, and then print 'bang!' as fast as possible, and exit. * The executable can do anything else in the meantime, even print to STDOUT, as long as it doesn't print 'bang!', or feed itself from STDIN. It also can't use a standard loophole. * Printing 'bang!' early, or exiting without printing 'bang!' is not allowed (you'll be one dead son of a gun). * Bash, and other sh derivatives, including sh scripts are not allowed, we don't settle things on native land. ## How I measure your boot size: * Using the golang runtime, I shall execute your command 1,000 times, the time it takes after feeding 'draw!' into STDIN to print 'bang!' will be your score, within +/- 2 nanoseconds. Your program will be given 500ms(+/-100ms of randomness) to stabilize, and load into memory. The program shall be run on ubuntu 20.04 server with only the necessary components to run your program installed. * There will be the following categories: **Max** time, **Min** time, **Avg** time, and **Median** time, all with lower times being the best. At the end of the month, the fastest gun in the wild west will be chosen. Best of luck! [Answer] ``` section .text global _start _start: xor r8, r8 xor r9, r9 xor r10, r10 _do_while: _getchar: cmp r9, r10 jne _getchar_done _getchar_read_buffer: xor r9, r9 xor eax, eax xor edi, edi mov rsi, in_buf mov rdx, inbuf_maxlen syscall mov r10, rax _getchar_done: mov al, [in_buf + r9] inc r9 _do_while_cont: cmp al, [req + r8] jne _reset _increment: inc r8 cmp r8, 5 jne _do_while mov rax, 1 mov rdi, 1 mov rsi, ans mov rdx, 5 syscall _end: mov rax, 60 xor rdi, rdi syscall _reset: xor r8, r8 cmp al, 'd' jne _do_while inc r8 jmp _do_while section .rodata inbuf_maxlen equ 1000000 req db "draw!" ALIGN 8 ans db "bang!" section .bss in_buf resb inbuf_maxlen ``` A little hand-written assembly. Compile with: ``` nasm -felf64 foobar.s && ld foobar.o -o foobar ``` Edit: move `in_bi` into a register and use `xor`. Edit: used the wrong jump, my code was wrong... Edit: the previous code had a bug where it would read garbage if the `read` syscall did not return a full buffer. This version is more efficient (and correct)... Edit: make sure to process `ddraw!` correctly. Thanks to Anders Kaseorg for the test case. Edit: re-structure to move `getchar` out of a function and to jump less. Edit: don't xor the high bits of the registers at the suggestion of Cody Gray Edit: align (thanks to Joshua) and move into `.rodata` [Answer] # C ``` #include "stdio.h" int main() { char* a = "draw!"; int i = 0; char c; while (1) { if ((c = getchar()) == a[i]) { i++; } else { i = c == 'd'; } if (i == 5) { puts("bang!"); break; } } } ``` Compiled with `gcc -O3 test.c`. You can get a copy of the executable [here](https://drive.google.com/file/d/1qZdAO7VWtgg3JZabO_P1rA8W0skqLIRx/view?usp=sharing), but it is probably safer to just copy this code and compile it so you can be sure the executable isn't unsafe (I would never give malicious code online, but it is best to be cautious). This isn't a very good solution, but it probably works as a baseline for other ideas. [Answer] # [Java 11](http://jdk.java.net/) (Oracle JDK) Just curious about how it runs. ``` import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import static java.nio.charset.StandardCharsets.US_ASCII; public class Main { public static void main(String[] args) throws IOException { var stateMachine = new int[6 * 256]; var response = "bang!".getBytes(US_ASCII); Arrays.fill(stateMachine, 5 * 256); stateMachine[5 * 256 + 'd'] = stateMachine[4 * 256 + 'd'] = stateMachine[3 * 256 + 'd'] = stateMachine[2 * 256 + 'd'] = stateMachine[1 * 256 + 'd'] = 4 * 256; stateMachine[4 * 256 + 'r'] = 3 * 256; stateMachine[3 * 256 + 'a'] = 2 * 256; stateMachine[2 * 256 + 'w'] = 256; stateMachine[256 + '!'] = 0; var in = new FileInputStream(FileDescriptor.in); var out = new FileOutputStream(FileDescriptor.out); for (var state = 5 * 256; state != 0; ) { state = stateMachine[state | in.read()]; } out.write(response, 0, 5); System.exit(0); } } ``` [Try it online!](https://tio.run/##fZJPb@IwEMXv@RRDL012W4vSLZdoD93@kThUPUSVVkKoGhIDZoMd2RNS1PLVm3VjQwMCcsu838w8a94cl3g5z/7VtVgUShPMbYEJxR5Fzu@5SbUoSOk4OCAPZFFSQprj4qD@XNJxYPD88JbygoSSu1pJIme3WuPKxMFGMYQkUgdI253OUBtOLCGUGerszv0b9pK83iZ3g4FtTXM0Bp5QSHgPAoCiHOd2hh@1VCKDhRVDa1DI6XAEqKcmApppVRlo@bPtYL8l6qaZP2E6E5LDb5C8AiFp2Icf0Lvpj@ItqLkplDRf0NkY5bRzxqac/qyIm3DjMXK4eyubiDwP2/Mv4MaN9VxbG3oJfsJ5dj6yW3bUXyfV65Nq76R6ta/6VQcstkzoBr0@irYcYYP2jqIte5VDD2MO6TRINw62h7FpcHfbS3C4G3gmZPR9TVVSq6ud6/02S0Z@20RpCLehsf3@ZrEvdL6MQeTTBVts5x2u@GFtM7suCyOfsbXbYdexSgvi4SZwF9C1wfHek5UhvmD8TVDYbWrrYF3Xmcaq86macJv68u8YKZ39Bw "Java (JDK) – Try It Online") Compile to bytecode with ``` javac Main.java ``` Run with ``` java -Xbatch Main ``` Note the `-Xbatch` is important as it will further precompile the bytecode to machine code. It's also important to run with Oracle JDK because it has the best machine compiler. It will reach the read method in around 200-300 ms after start, after taking time to compile to machine code in memory. So I didn't optimize until there. Hence the reason why I let multiplications as is. However, after the first read, no instruction is superfluous. I used a state machine to remove all the jumps, similar to Bubbler' submission, because if you thought that `if`s are slow, wait until you see `if`s in Java! Also I optimized the reading and writing by creating my own non buffered streams (I used `new File{Input,Output}Stream(FileDescriptor.{in,out})` instead of the slower, buffered `System.{in,out}`). Implementation note: if EOF is found before the expected trigger, it will crash. But while I hope this code can compete, I wouldn't be surprised at all if it ends last. [Answer] # [C (gcc)](https://gcc.gnu.org/) ``` #include <stdio.h> int main() { FILE* const in = stdin; FILE* const out = stdout; char c = 0; #define is_or(t, l) \ c = fgetc_unlocked(in); \ if (__builtin_expect(c != t, 0)) goto l x: if (__builtin_expect(c == 'd', 1)) goto r; d: is_or('d', d); r: is_or('r', x); is_or('a', x); is_or('w', x); is_or('!', x); fwrite_unlocked("bang!\n", 1, 6, out); return 0; } ``` [Try it online!](https://tio.run/##dZDNSsRAEITveYrO7mEzkpX14sEYbwqC4AsshNn5yTaOPTLpkID46saZuP4Q2NvwVXVPdaltq9Q0rZGU67WB2441@svjXZYhMbxKpELAe5YBPDw@3V@A8tQxIEENyUrVQvE9f0vxkTR1lAFURLsqLVlrY5EMYNf4UHAJTsA@cpg9tjWsmp6cVy9GF0iiOqlooWiaQ4@OkRozvhnFhYK8hrhjJwS0nj249MV4k5311zVs9KaEq5@JkDLqeWJONKtaJBr@0RDpONMTkEswLEH@C@wQkM3fWauDpDbf0yrmKOG6TJ2JuZ1guA@UqvqYJh3kkH8q62TbTdtnKzv@Ag "C (gcc) – Try It Online") `gcc -Ofast bang.c` I have no idea of its performance. Just have a try... [Answer] # [C (gcc)](https://gcc.gnu.org/) ``` #include <stdio.h> int transition_table[128*6] = { 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 0, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 128, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 256, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 384, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 512, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640, 640 }; int main() { FILE* const in = stdin; FILE* const out = stdout; char c = 0; int state = 640; while(state) { c = fgetc_unlocked(in); state = transition_table[state + c]; } fwrite_unlocked("bang!\n", 1, 6, out); return 0; } ``` [Try it online!](https://tio.run/##7ZhRS8MwEMff@ylu86Xdpmx1K4OqbwqC30DHyNKsDdYLpFf6IP3s9bJOBH0SNtAtpS3p/ZNfEnKkuZOXuZRdd6FRlnWm4KaiTJur4i4INBKQFVhp0gbXJDalep7Fy1Gyglt4D4CvZD6dHPDlmZ55MOb/mzzf4Bf@aMzFLPYO6pln7aD8//4d0y/UuTPjRfKXd1HvpJ55xJ30ejn3TuqZp38eDdq0j/nfhMYw4gCfO3l4fLofgTRYEWjksN@lBzD9ppiaeokLTpOFsCDZNHVfjlmRIMUG7seZmkKXKtwZo30mAXYNtrkiua6xNPJVZaHGKN2rn4QfGYleGINcuaotP9vGalJflOFGYD54wSEff3iqEzde5nJNq6i26IbZdl1mRTP4AA "C (gcc) – Try It Online") Throwing a hardcoded state transition table into the mix, in order to eliminate the jumps as much as possible. Honestly I don't know which optimization flag will give the best results. You could try `gcc -Ofast bang.c` or `gcc -O3 bang.c`. (maybe `-O2` too?) [Answer] # [Rust](https://www.rust-lang.org/) ``` use std::hint::unreachable_unchecked; use std::io::{stdin, stdout, Read, Write}; pub fn main() { let key = b"draw!"; let temp = stdin(); let mut stdin = temp.lock(); let tmp = stdout(); let mut out = tmp.lock(); let mut i = 0; let mut buf = [0]; loop { stdin .read(&mut buf) .unwrap_or_else(|_| unsafe { unreachable_unchecked() }); let read = *unsafe { buf.get_unchecked(0) }; if unsafe { read == *key.get_unchecked(i) } { i += 1; } else { i = (read == b'd') as usize; } if i == 5 { out.write(b"bang!") .unwrap_or_else(|_| unsafe { unreachable_unchecked() }); out.flush() .unwrap_or_else(|_| unsafe { unreachable_unchecked() }); break; } } } ``` [Try it online!](https://tio.run/##tZNNb9swDIbv@RVsDquzJUGGYhcHPu0f9NLDMASUTceaZcnQR40t9V@fR7n5cNIeO52kl3zIV5Rtg/PDEByB80WaVlL7NA3aEuYVCkW7oPOK8pqK7eycJU2aHngn9TIKJvglPBIWS3iy0lO/nbVBQKmhQamTBRxmwEuRh5p@QwZiXljs7ubbs@6paTkw1kwWF70J/lXkYMxZK5PX0wR/4tjELchSxN6hYlRybHMtiVCy@GPz8ygb0x69xzX6OJ/iWvOYiuTTEV1cx4LuLLY7Y3ekHCUvuxcI2mFJcIB3B8yD6o8eT6ZifXb0@Qxym/We/ATaMHWBZHlp8gozzUO/gSRDk5uNJHzJ4OulUg/R9pukDJJTXXFf3C8AHQQn/9CEnLqRMfPbTRl@mHUXv5REzAXq/d38enYfMr9To1IFVyX/qYHgtPr26v2sH4aCOtS1aEpLjcFOSl8Fi5K0CL9IKhzvXYz/wd@8VLh3w@q7af1K0TOp7IFPypusRM87j5YfcJW3IdPo5TP9Aw "Rust – Try It Online") A solution in rust. It is pretty similar to @hyper-neutrino's solution, but it makes sure to flush the output buffer after writing and also asserts that io errors can't happen (it will be undefined behavior if they do, probably causing a sigill). Build `rustc -Copt-level=3 -Clto=fat -Ctarget-cpu=native -o main` and run `./main` [Answer] # C ``` #include "stdio.h" int main() { int i = 0; while (1) { i ++; int c = getchar(); switch (i) { case 1: if (c != 100) i = 0; continue; case 2: switch (c) { case 100: i = 1; case 114: continue; default: i = 0; continue; } case 3: switch (c) { case 100: i = 1; case 97: continue; default: i = 0; continue; } case 4: switch (c) { case 100: i = 1; case 119: continue; default: i = 0; continue; } case 5: switch (c) { case 100: i = 1; case 33: continue; default: i = 0; continue; } default: puts("bang!"); } break; } } ``` Compiled with `gcc -O3 -o foobar foobar.c`, run with `./foobar` (I'm on Windows, so the `-o` and `./foobar` is a guess). A variation on hyper-neutrino's solution. Uses a switch statement instead of indexing into a string. Hopefully, this makes it faster. [Answer] # [C (clang)](http://clang.llvm.org/), 343 bytes ``` #include <stdio.h> int main() { const char draw[] = "draw!"; size_t i = 0; while (i < 5) { char c = getchar_unlocked(); i = c==draw[i] ? i + 1 : c=='d'; } putchar_unlocked('b'); putchar_unlocked('a'); putchar_unlocked('n'); putchar_unlocked('g'); putchar_unlocked('!'); return 0; } ``` [Try it online!](https://tio.run/##dZBBTsMwEEX3OcWkLJIIFcGCDW3oEXoAVFWDx44dGwdlHFUC9eoE20EsQJmF9fX/1xuNxVY49N083xgv3EQS9hzIDHf6uSiMD/CGxtdN8VlAHDF4DiA0jkAjXl5O0MImqXKzywU2H/IcwET/fnEu2jgJtYE9PDbZWVAZl0AidjsZkj5P3g3CSqqb3W8psUTb5n3mBIdo3MIDPCWzomopXvP7Pv3BVK/VD@l/hOuRX4@69ahMUc5GGabRpx@4zjOxQrbo2JLqNSpnNbLSTErHm/oo0XKvWfVWU7qS0iBlXX4J5bDjeXuMlPAN "C (clang) – Try It Online") Compiled with `-Ofast`. [Answer] # [C++ (gcc)](https://gcc.gnu.org/) Probably not the fastest, but wanted to give it a try: ``` #include <iostream> std::string a; int main(){ std::cin >> a; if(a == "draw!") std::cout << "bang!"; } ``` Compiled using `g++ -Ofast bang.cpp`. [Answer] Python: ``` from sys import stdin def fgitw(func=stdin.readline, it=iter): for _ in it(func, 'draw!'): pass print("bang!") fgitw() ``` A smaller version will be simply(but `sys.stdin.readline` with local variables above should be faster): ``` for _ in iter(input, 'draw!'): pass print("bang!") ``` [Answer] ## C (GCC, Linux x86-64) I have implemented the following ideas naively hoping for performance without testing: * the translation `draw!` to `bang!` happens via a lookup table, i.e. without any jumps * the write to stdout happens via a syscall to Linux' `write` (without any indirections of calling glibc's `write` wrapper) * the program exits via a syscall to Linux' `exit` (without any indirections of calling glibc's `exit` wrapper) You can see the generated asm on godbolt: <https://godbolt.org/z/Ex3T5G5Gq>. Compile with `gcc -O3 -march=x86-64 -fomit-frame-pointer draw-bang.c -o draw-bang`. ``` #include <stdio.h> #include <unistd.h> #include <asm/unistd.h> static inline ssize_t my_write(int, const void*, size_t); static inline void __attribute__((noreturn)) my_sys_exit(void); /** * table[1 -- 128] translates ASCII characters with codepoint 0 -- 127 * to other ASCII characters such that * 1. `draw!` translates to `bang!` and * 2. any other character translates to `\0` * * table[0] is `\0`. * * Rationale: `table + 1` can be indexed by the return value of `getc(stdin)`. * And upon error or EOF, we nicely get `table[0]`, i.e. `\0`. */ static char table[129] = { '\0', // -1-th index // 128 entries follow '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 0 -- 9 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 10 -- 19 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 20 -- 29 '\0','\0','\0', '!','\0','\0','\0','\0','\0','\0', // 30 -- 39 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 40 -- 49 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 50 -- 59 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 60 -- 69 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 70 -- 79 '\0','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 80 -- 89 '\0','\0','\0','\0','\0','\0','\0', 'n','\0','\0', // 90 -- 99 'b','\0','\0','\0','\0','\0','\0','\0','\0','\0', // 100 -- 109 '\0','\0','\0','\0', 'a','\0','\0','\0','\0','g', // 110 -- 119 '\0','\0','\0','\0','\0','\0','\0','\0' // 120 -- 127 }; static char out[6]; // to hold "bang!\0" int main(void) { char c, i; while ((c = (table + 1)[getc(stdin)])) { out[i++] = c; } my_write(STDOUT_FILENO, out, sizeof(out)); my_sys_exit(); } /** * "Reimplementation" of write (2) function that GCC is happy to fully inline. * * Source: <https://stackoverflow.com/a/9508738/603003> * Author: Daniel Kamil Kozar <https://stackoverflow.com/users/1155000/daniel-kamil-kozar> and editors * License: CC BY-SA 4.0 <https://creativecommons.org/licenses/by-sa/4.0/> */ static inline ssize_t my_write(int fd, const void *buf, size_t size) { ssize_t ret; asm volatile ( "syscall" : "=a" (ret) // EDI RSI RDX : "0"(__NR_write), "D"(fd), "S"(buf), "d"(size) : "rcx", "r11", "memory" ); return ret; } /** * Exit the current thread (process for single-threaded processes) using the `exit` Linux * system call. * * This translates to exactly one asm instruction as opposed to calling the usual standard * libraries's exit() family of functions: see <https://stackoverflow.com/a/46903734/603003>. */ static inline void __attribute__((noreturn)) my_sys_exit(void) { asm("syscall" : : "r"(__NR_exit)); } ``` ``` [Answer] # C++ (clang, Linux x86-64) ``` #include <bit> #include <cstdint> #include <tuple> #include <unistd.h> #include <asm/unistd.h> static_assert(std::endian::native == std::endian::little); using U64 = std::uint64_t; inline void sys_write(int fd, void const* buf, std::size_t count) { asm volatile("syscall" : : "a"(__NR_write), "D"(fd), "S"(buf), "d"(count) : "rcx", "r11", "memory"); } inline ssize_t sys_read(int fd, void* buf, std::size_t count) { ssize_t r; asm volatile("syscall" : "=a"(r) : "0"(__NR_read), "D"(fd), "S"(buf), "d"(count) : "rcx", "r11", "memory"); return r; } U64 const DRAW = UINT64_C(0x2177617264); U64 const MASK = UINT64_C(0xFFFFFFFFFF); inline bool contains_it(U64 x) { for(auto [pattern, mask] : { std::tuple{DRAW << 0, MASK << 0}, std::tuple{DRAW << 8, MASK << 8}, std::tuple{DRAW << 16, MASK << 16}, std::tuple{DRAW << 24, MASK << 24} }) { if((x & mask) == pattern) [[unlikely]] { return true; } } return false; } inline bool contains_it(U64 const* first, U64 const* last_incl) { U64 prev = 0; for(auto p = first; p <= last_incl; ++p) { if(contains_it(*p) || contains_it((*p << 32) | (prev >> 32))) [[unlikely]] { return true; } prev = *p; } return false; } int main() { std::uintptr_t const MAX_READ = 1'048'576; std::size_t const S = sizeof(U64); U64 u64s[1 + MAX_READ / S + 1] = {}; int r = MAX_READ; while(1) { int rem = r % S; U64* end = u64s + 1 + r / S; *end &= ~(U64(-1) << (rem * 8)); if(contains_it(u64s, end)) { sys_write(STDOUT_FILENO, "bang!", 5); return 0; } u64s[0] = end[-1]; u64s[1] = end[0]; r = sys_read(STDIN_FILENO, reinterpret_cast<char *>(u64s + 1) + rem, MAX_READ) + rem; } } ``` Compile with `clang++-12 -std=c++20 -Ofast -march=native -o drawbang drawbang.cpp`. Clang’s optimizer is scarily efficient in how it vectorizes this code — [godbolt](https://godbolt.org/z/oaMvb5vxh). The entirety of the main loop is under `.LBB0_4`, where it takes as few as 16 instructions to go through 8 bytes. Some of those are conditional jumps, which shouldn’t matter as the CPU should predict the outcomes correctly, for which purpose the code starts by going through a megabyte of zeroes. Like other submissions, the code assumes it will be fed junk that it has to ignore until it encounters the key string. ]
[Question] [ ## What is Permutation Coefficient Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! , where “!” represents factorial. The Permutation Coefficient represented by P(n, k) is used to represent the number of ways to obtain an ordered subset having k elements from a set of n elements. Mathematically, [![math](https://i.stack.imgur.com/iFQNS.png)](https://i.stack.imgur.com/iFQNS.png) ### Examples: ``` P(10, 2) = 90 P(10, 3) = 720 P(10, 0) = 1 P(10, 1) = 10 ``` To Calculate the Permutation Coefficient, you can use the following recursive approach: `P(n, k) = P(n-1, k) + k * P(n-1, k-1)` Though, this approach can be slow at times. So Dynamic approach is preferred mostly. ### [Example of Dynamic Approach (Python)](https://tio.run/##fZHLDoIwEEX3fMVdFtEEdEdk5Q@wb1iQ2GpBpqSWhV@PlEdARCdNps2cufNo/bJ3Tae2vQqJWpiqsblVmi5aSMloj9KP4cEdIEUCzkNIbaCgCCanm2AlAkR@NkKTOaiYIRqhSWulMYTjWWKVXiliynUzcx/VlAQrkCQIlyKTpVxlvMi69qN1ong8xd@M7oYDov4VgH2jCyuwW/C983@0ep42u1XXDelqh33cCNsY6kKU8XLYILlRQq/s3NHzaqPIsu3f89v2DQ) ### Input Format `{n} {k}` ### Output Format `{PermutationCoefficient}` ### Test Cases ``` INPUT - 100 2 OUTPUT - 9900 INPUT - 69 5 OUTPUT - 1348621560 INPUT - 20 19 OUTPUT - 2432902008176640000 INPUT - 15 11 OUTPUT - 54486432000 ``` ### Constraints in input N will always be greater than or equal to K. ### (Not to be confused with Binomial Coefficient) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 5 bytes ``` ⊣÷⍥!- ⊣ left argument ÷⍥! divide over factorial, apply factorial to both arguments and then divide - subtract ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG9qQACQcAt61DbB2FjB0MjC/P@jrsWHtz/qXaqo@z8NKPyot@9RV/Oj3jWPerccWm/8qG0iUENwkDOQDPHwDP5vaGCgkKZgxGVmCaRMuYxAPENLLkNTEG0IAA "APL (Dyalog Extended) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~51~~ ~~23~~ 21 bytes ``` import math math.perm ``` [Try it online!](https://tio.run/##bYwxCsMwEAR7v8KQxgYR9k7SRfecFAG7kH0INXm9IjUukjQLy86Ovet2Hj5ZaW3PdpY652fdphF3e5XcrOxHXa6@EOB4XeebKjB9r6IujpF8SMIU5RdhONLBcPCsYCDRQyQAf3wUHdGAY@jCfuhQ@wA "Python 3.8 (pre-release) – Try It Online") --- No builtins: # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 31 bytes ``` f=lambda n,k:k<1or n*f(n-1,k-1) ``` [Try it online!](https://tio.run/##TYxLDgIhEAX3noLEDZiepLv5CBM9zBhDNChDyGw8PQMLo9uqeq98tseatS@1tXh9Le/bfREZ0pwutFaRT1HmiSBNpFqpz7zJKAkRWClxDAHx8KUugB2QtPGOybqfYgQKw7HRHJARPZ2dM4h/e7JANCJr@kEPu2w7 "Python 3.8 (pre-release) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~34~~ ~~32~~ 27 bytes Saved 2 bytes thanks to [Davide](https://codegolf.stackexchange.com/users/100356/davide) who credits [Irratix](https://codegolf.stackexchange.com/users/95940/irratix)'s [JavaScript answer](https://codegolf.stackexchange.com/a/218579/9481)!!! ``` f(n,k){n=k?n*f(n-1,k-1):1;} ``` [Try it online!](https://tio.run/##bZHRaoQwEEXf/YpBENSN1Gi1tdb2ofQrqpQlxlZCs4vxQSp@u51sVNalgQzJnXMnyYQFX4zNc@NKIrxRFuJV@rgJKBEB9Z5oPs2t7OHn2ErXs0YLcGih56pXn/KjggJGGhLYTwxpNuU3uDB4RCAmoDkCuE6uOD6cOet5bcAMmYfIgLpulunCNL5/TCOapOFiZN/HzsfImeCdcdrl8B6VQ/aGM7EJXO9je/E1pw5cfWoraz6gLcyX5TOo9pefGne9j3e3CP6m5HA4XGgPTFvWN0istLbnAlT5Li@2vPg3rzBv/mOvc9S3/twazx0ijWs7NQGnhuBFR0eVEh8vCQgCimwtUkXBq6X6ZE3zHw "C (gcc) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` Π↑↔ḣ ``` [Try it online!](https://tio.run/##ARkA5v9odXNr///OoOKGkeKGlOG4o////zIw/zE5 "Husk – Try It Online") ``` Π # product of ↑ # the first k elements (k is 2nd argment) of ↔ # the reverse of ḣ # 1...n (n is 1st argument) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḶạP ``` A dyadic Link accepting, the non-negative integers, `n` on the right and `k` on the left which yields `P(n,k)`. **[Try it online!](https://tio.run/##y0rNyan8///hjm0Pdy0M@P//v/F/QwMA "Jelly – Try It Online")** ### How? ``` ḶạP - Link: k, n e.g. 3, 10 Ḷ - lowered range (k) [0, 1, 2] ạ - absolute difference (n) [10,9, 8] P - product 720 ``` [Answer] # JavaScript ES6, 25 bytes ``` c=(n,k)=>k?n*c(n-1,k-1):1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` e ``` Builtins ftw ¯\\_(ツ)\_/¯ First input is \$k\$, second input is \$n\$. `e` is a builtin for the number of permutations, so \$P(n,k) = \frac{n!}{(n-k)!}\$. [Try it online](https://tio.run/##yy9OTMpM/f8fiAwtuYwMAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/9T/Ov@jow0NdIxidUCUMYQygFCGYAoiaWapYwqkjICiliBhUx1Dw9hYAA). [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 34 bytes ``` > Input > Input >> 1P2 >> Output 3 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykYBhiBKP/SEqCAgvH//4YGXMYA "Whispers v2 – Try It Online") Builtins for the win [Answer] # [R](https://www.r-project.org/), ~~26~~ 25 bytes *Edit: -1 byte by using `scan()` to take input* ``` prod(diff(x<-scan())+1:x) ``` [Try it online!](https://tio.run/##K/r/v6AoP0UjJTMtTaPCRrc4OTFPQ1NT29CqQvO/KZeZJdd/AA "R – Try It Online") Input in reverse order ( `k` first, then `n`). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ‼!-!/ ``` Input in the order \$k\text{ }n\$. [Try it online.](https://tio.run/##y00syUjPz0n7//9Rwx5FXUX9//@NFAwNuIxBhAGIMAQRIDEDLlMFM0suQ0sFI6AoUNgUAA) **Explanation:** ``` ‼ # Apply the following two commands on the stack separately: ! # Take the factorial of the second (implicit) input-integer - # Subtract the second from the first (implicit) input-integers ! # Take the factorial of (n-k) as well / # Integer-divide n! by (n-k)! # (after which the entire stack is output implicitly as result) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 28 bytes ``` param($a,$b)'$a--*'*$b+1|iex ``` [Try it online!](https://tio.run/##jZBNa4QwEIbv/goJadVVF90eSpGAsLTQS1vq3payRDtLt2i1SaQLmt9uNX7Ui2VzSWbeeeeZTJH/AOMfkKYNPpKqKSijmYmpg2PLwNR1V8YKx7Zfn@DcSA0L4GJLOXCd6KGp6e0JK3V15/RVlKJ7dKLvORtrkuBcQCLgXUl3Xi9I5x/zzYL5dnOJ21tw@xd4/SXvCNYsDe/aTXASmtZsKfVVpYKnMouBEV/2DKwADh6bEXxYD6nDekz2lQx4mYqWZl7jox6qKmvWJBKsFVEfoF7gZZIA5wQNbuTCN5pgQ5Ea1yb7l2hbcpFnz/FnK7@FldEpBpnNbdtBNLQcewePHY@gaQgUvCrWHzS4H383Y0tNDpuqH3KWUeHuaJxC8ws "PowerShell – Try It Online") # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 7, 43 bytes ``` $f={param($a,$b)$b ?$a*(&$f($a-1)($b-1)):1} ``` no TIO link because TIO still runs on PS 6, which does not support the ternary operator. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 ``` .P.* ``` [Try it online!](https://tio.run/##K6gsyfj/Xy9AT@v/fw1DAx0FY00A "Pyth – Try It Online") # Explanation ``` Q Implicit input of 2-tuple .* splat .P nPr Explicit output ``` [Answer] # x86 Machine Language, 14 bytes ``` 86 31 C0 40 29 F7 4E 78 05 47 F7 E7 EB F8 C3 ``` **[Try it online!](https://tio.run/##nVJdSwMxEHzO/opQKCi0pR9YsKAgtX1VqI8FSZNcTckXSU6u/njP7V09W60ovYdjb3ZmspsbFqM0K73trjkve8omqZ/j1iZWUOt8kJkqykcZTJ5YUs5OncwyxZW0aQJ0/xQuEMmKDsUXEGU5qYqYr4gUCuGo4Mn5CRAhsYdfZBPJzIo9WSBgcl0XG@MJkgHbXycEmcreWruVpoYpCzBlmt9Zca@i12yLzj6PL7U1Z1qT0yMjzfmK9Wlcy3DaY2DnU1fiG/dhPl/MnujcBcPSIoWmWx3rA95g1mBMCPTyHToYA8EdAHbT47TGvdZXM@g35AqLiA33OxzvCH@oRmep@mepBv9QnbXY@Pqn6uoX1cn0HQQGoPlJdZB6LHL1RlsH2aAH4bhoiw5ti8tlurldprZY2haU7zzTbB3LrhkNPwA "Assembly (gcc, x64, Linux) – Try It Online")** The above bytes of code define a function that calculates and returns the Permutation Coefficient, according to the formula given in the challenge. The function accepts two arguments, *n* and *k*, in the `EDI` and `ESI` registers, respectively.\* The result is returned in the `EAX` register, as is conventional. \* Note that the selection of these two registers is quite flexible. `EDI` and `ESI` were chosen to match some standard C calling conventions, but since this is machine code, they can be changed to any other registers of your choice, except for `EAX` (which is used for the return value) and `EDX` (which is clobbered by the `MUL` instruction). Ungolfed assembly mnemonics: ``` PermutationCoefficient: 31 C0 xor eax, eax # \ assume 40 inc eax # / result = 1 29 F7 sub edi, esi # n -= k Top: # <======================\ 4E dec esi # --k | 78 05 js End # terminate if k < 0 | 47 inc edi # ++n | F7 E7 mul edi # result *= n | EB F8 jmp Top # =======================/ End: C3 ret ``` There's nothing especially fancy here. Just machine code at its finest, performing iterative arithmetic with a minimal number of bytes required to encode the instructions. The key innovation is basically just effective use of registers to track the appropriate changes in values of *n* and *k* across iterations, which allows the use of extremely small `INC`rement and `DEC`rement instructions (which can be encoded in only 1 byte). This reduces the number of 2-byte and 3-byte arithmetic operations that must be done inside of the loop, which in turn reduces overall code size. It is probably also a pretty efficient implementation, as far as iterative loops go. [Answer] ## [R](https://stackoverflow.com/questions/49192128/factorial-with-r), ~~36~~ 35 bytes Several attempts hitting the same number: ``` function(n,r)choose(n,r)*gamma(r)*r ``` or ``` function(n,r)gamma(r)/beta(n-r+1,r) ``` or yet ``` function(n,r)"if"(r,n*f(n-1,r-1),1) ``` with ``` function(n,r)dpois(n-r,1)/dpois(n,1) ``` doing even worse (by 1). [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6dIMz0xNzdRo0hTPym1JFEjT7dI2xAo@j9Nw9hEx9hIkytNw0THEESZWeqYWWj@BwA "R – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` IΠ⁻N…⁰N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI6AoP6U0uUTDNzOvtFjDM6@gtMSvNDcptUhDU0chKDEvPVXDQEcBRRwMrP//N7NUMP2vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input `k` …⁰ Range from `0` to `k-1` N Input `n` ⁻ Subtract i.e. range from `n-k+1` to `n` (inclusive) Π Product I Cast to string Implicitly print ``` [Answer] # [Julia](http://julialang.org/), 20 bytes nothing fancy here, just applying the basic definition ``` P(n,k)=prod(n-k+1:n) ``` [Try it online!](https://tio.run/##TYxBCsIwEEX3c4pZJhhDp1KhgXiG7ksXQiPElmlJUhAvHxPd@BcP3lv857H6O71yHgSrRdo9bLPg83IiwzInF1NEiyNQg23FpaKpoIIarz120BbvgTokggngsQX06BnJRP924vujSAKW7cFzWvkXR6/MhPaGw59rraUExzNA/gA "Julia 1.0 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 37 bytes ``` \d+ * ~[".+¶$.("|""L$v`(_*)_ \1 $.'$* ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8mRZtLi6suWklP@9A2FT0NpRolJR@VsgSNeC3NeIUYQy4VPXUVrf//jRQMDQy4TBXMLLkMLRWMDLgMDRUMTQE "Retina – Try It Online") Link includes test cases. Takes input in the order `k n`. Explanation: ``` \d+ * ``` Convert the inputs to unary. ``` L$v`(_*)_ \1 $.'$* ``` List the numbers from `n-k+1` to `n`, with a `*` suffixed to each. ``` |"" ``` Don't separate the results with the default newline. ``` [".+¶$.(" ``` Prefix the results with the given string. ``` ~ ``` Evaluate that as a Retina 1 expression. Example: For the input `2 100`, there are two matches, where `$.'` takes the values `99` and `100`. The result of the `L` command is therefore ``` .+ $.(99*100* ``` When executed as a Retina program, this then replaces the input with the desired result. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 11 bytes ``` #!/(#-#2)!& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lRX0NZV9lIU1Htf0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXtaGBgY5RrQ5XtZmljimINjLQMbQEMQxNdQwNa7lq/wMA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` _Ɱ‘P ``` [Try it online!](https://tio.run/##y0rNyan8/z/@0cZ1jxpmBPw/vFz/UdOayP//ow0NdIxidUCUMYQygFCGYAoiaWapYwqkjICiliBhUx1Dw1gA "Jelly – Try It Online") ``` Ɱ For each x in 1 .. k, _ subtract it from n ‘ and increment. P Take the product. ``` Alternatively, # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` c×!} ``` [Try it online!](https://tio.run/##y0rNyan8/z/58HTF2v@Hl@s/aloT@f9/tKGBjlGsDogyhlAGEMoQTEEkzSx1TIGUEVDUEiRsqmNoGAsA "Jelly – Try It Online") ``` c nCk × times !} k! ``` Bonus solution, 5 bytes, all ASCII: `,_!:/` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` Xn0G:p* ``` Because snog :p\* ``` Xn % compute nchoosek 0G:p % compute k! * % multiply ``` [Try it online!](https://tio.run/##y00syfn/PyLPwN2qQOv/fzNLLlMA "MATL – Try It Online") [Answer] # [Factor](https://factorcode.org/), ~~28~~ 21 bytes ``` [ [0,b) n-v product ] ``` [Try it online!](https://tio.run/##NY6xDoJAEER7vmJaEyEQY4MfYGhojBWhONdFiHJ33h4khvDteIo2M28mm800irxxy/lUlMccSsSQ4M5O8wO98u1XkmbQ5DujZY1O6Rv/eOTPA4msY@9f1nXaQ/g5sKZwcoiKMoeQU57aaMKEPXaYg2cp0j9kAealQpVuLxvoeIR15jqQRx3aBDXI9NYIrwNjVtQubw "Factor – Try It Online") Inspired by [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/218687/78410). Now beats the built-in solution! Takes two numbers `n k` from the stack, subtracts `0..k-1` from `n`, and computes the product. The product of an empty sequence is 1. # [Factor](https://factorcode.org/), 27 bytes ``` USE: math.combinatorics nPk ``` [Try it online!](https://tio.run/##JY0xDoNADAT7e4VfQBOludRRRIMiRXmAY5lgEXzENgWvPxA0K00xsz1SFKvvV9s9MqAZrg5SYGRT/sGEMRzT9ItSSFE/0VC/7Gk2jlhnEw1w/i@sxA631HYZnAyDhnSFy96/51OkMn1EcT8V8qTPsTZ1Aw "Factor – Try It Online") There's a built-in for this ... except that the import is horribly long. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 2 bytes ``` ∆ƈ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%86%C6%88&inputs=2%0A100&header=&footer=) Another built-in, like 05AB1E, but not quite as concise. First input is `k`, second input is `n`. [Answer] # Excel, 14 bytes ``` =PERMUT(A1,A2) ``` An Excel built-in. [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` o áV l ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byDhViBs&input=MTAKMw) [Answer] # [Perl 5](https://www.perl.org/) -MList::Util=reduce, 36 bytes ``` sub f{reduce{$a*$b}$_[0]+1-pop..pop} ``` [Try it online!](https://tio.run/##XZDPT4MwGIbv/hWfrIeBbGk7wMFS9a5zFz3hQpyCkk3alOKPEP518SvEuNhDD@/zvG@Tqlwfwr6QepoCo9QH4CAuII4p3fongCcFiGLMQ5uzRbCMOAujI8qxxWJLebDgMeWULtl5FAWUHo@wEDVmtTDAEVQtdlvkb19TUvlk75P8U7niimSrISUv0ohiZK6NlC4rA0MsrAuX4Mi9Awk4nufdbu5gc33q/JkOPv3bByGGJrzXYLsPFYpdXzc7KFqdPzdPeUsePbLrSJbS7RmbKanmc7y6fjJaRAu2ItoTJAP8sv8eog4mH6V5lY2BcbL/lsqUsqr72fqmrE2S3JvyIEb4Aw "Perl 5 – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 45 bytes ``` (n,k)->{var r=1;for(;k-->0;)r*=n--;return r;} ``` [Try it online!](https://tio.run/##hY@xjoMwDIZ3nsJjUpEIeupJVUTH227qWN2QUoICIUHGIFWIZ@ci7vYs/mXp82e704sW3avf7TAGJOhiL2eyTprZ12SDlyeV1U5PE3xr62HNAKynBo2uG/iCFVzwLRh2hM7/2idXsEVynJ/O1jCRphhLsC8YooXdCa1vHz@gsZ34IYUoM9XOfN5zcVsXjYBVqUxApnohboXieKq8EAobmtEDqm1Xx@BR7u@JmkGGmeQY5eQ8M9KwssgLzlUCKdPIOY18JJG05vOaXxLIOd57Ta265OX/U1u27b8 "Java (JDK) – Try It Online") Works only for results `<= Integer.MAX_VALUE`. If `f(_,0)` wasn't a requirement, it could go down one byte: ``` (n,k)->{for(var x=n;k-->1;)n*=x--;return n;} ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 16 bytes ``` p(n,k)=n!/(n-k)! ``` [Try it online!](https://tio.run/##FchBCoAgEEDRq4ytHBhJBYMWdRFxMbQIUWSINp3edPf@F36yuaV30Y0KHk2tupmCqrNI/TSDOUGe3N7BZcYCF9eqhYARCWJ01hL4NLjtBGHCj@P2KReGXErYfw "Pari/GP – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` lambda n,k:g(n)/g(n-k) from math import factorial as g ``` [Try it online!](https://tio.run/##Dcg7DoAgDADQ3VN0hAQjMpp4E5eq4RM@JdjF01eXN7z@cqTmxO@HFKznjdBM3oJqevmZs578oAoVOUKqnQaDx4tpJCyADwTpI7U/1WqtcVo@ "Python 2 – Try It Online") There's a better python solution already..... ]
[Question] [ [*The Bible*](https://en.wikipedia.org/wiki/Bible) is one of the most influential books ever written, and commonly cited as [the best selling book of all time](https://en.wikipedia.org/wiki/List_of_best-selling_books). It was written by approximately [40 different authors over hundreds of years](https://christianity.stackexchange.com/a/17686/20525) before being compiled into it's current form. But what's interesting about The Bible is the way it's divided up. It is split up into 2 different testaments, which are split up into 66 smaller books, which are each split up into smaller chapters, which are each split up into individual verses. I thought it would be a fun challenge to try to encode the number of chapters in each book in the shortest code possible. So for today's challenge, you must write a program or function that takes one of the books as input, and outputs the number of chapters in that book according to *The King James Version*. You may take IO in any reasonable format, for example reading/writing STDIN/STDOUT or a file, function arguments/return values, prompting the user, etc. are all allowed. The input will always be one of the 66 books of The Bible, and only lowercase. This means that if you are given any other input, undefined behavior is allowed. Since there are only 66 possible inputs and outputs, they are all provided here, according to [Wikipedia's page on Bible chapters in The King James Version](https://en.wikipedia.org/wiki/Chapters_and_verses_of_the_Bible#Protestant_Bible_statistics): ``` genesis 50 exodus 40 leviticus 27 numbers 36 deuteronomy 34 joshua 24 judges 21 ruth 4 1 samuel 31 2 samuel 24 1 kings 22 2 kings 25 1 chronicles 29 2 chronicles 36 ezra 10 nehemiah 13 esther 10 job 42 psalms 150 proverbs 31 ecclesiastes 12 song of solomon 8 isaiah 66 jeremiah 52 lamentations 5 ezekiel 48 daniel 12 hosea 14 joel 3 amos 9 obadiah 1 jonah 4 micah 7 nahum 3 habakkuk 3 zephaniah 3 haggai 2 zechariah 14 malachi 4 matthew 28 mark 16 luke 24 john 21 acts 28 romans 16 1 corinthians 16 2 corinthians 13 galatians 6 ephesians 6 philippians 4 colossians 4 1 thessalonians 5 2 thessalonians 3 1 timothy 6 2 timothy 4 titus 3 philemon 1 hebrews 13 james 5 1 peter 5 2 peter 3 1 john 5 2 john 1 3 john 1 jude 1 revelation 22 ``` Since this challenge is about finding the optimal way to encode every book name and chapter count, using any builtins that give information about The Bible are not permitted. However, since it would be interesting to see which languages have such builtins, feel free to share a second non-competing version along with your answer. [Fetching information from external sources](https://codegolf.meta.stackexchange.com/a/1062/31716) is also not permitted (none of the standard loopholes are allowed, but I thought it would be useful to explicitly mention that one). As usual, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so try to make the shortest possible program (measured in bytes) as you can. Have fun golfing! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 127 bytes ``` “£ÐgƁ÷ḅ*Wßßɦ*⁷ċṗṿỵ×Ɓṿ⁷ḢQ’b7+\;“BƝ‘ OḄ;407;270;“ọḷḊḲɦ‘%/i@“¡Ṙ×!⁸Ọ5`ỊV-ṙQȷṖÞ(sĿȮ^k³M"ɓmEf¤*0C[ạƇŻȥ#BṚñİmZẓeȦUƈ!ċ€@Ȧʋ)ƙḅyẉ’b158¤ị¢ ``` [Try it online!](https://tio.run/##AfcACP9qZWxsef//4oCcwqPDkGfGgcO34biFKlfDn8OfyaYq4oG3xIvhuZfhub/hu7XDl8aB4bm/4oG34biiUeKAmWI3K1w74oCcQsad4oCYCk/huIQ7NDA3OzI3MDvigJzhu43huLfhuIrhuLLJpuKAmCUvaUDigJzCoeG5mMOXIeKBuOG7jDVg4buKVi3huZlRyLfhuZbDnihzxL/Irl5rwrNNIsmTbUVmwqQqMENb4bqhxofFu8ilI0LhuZrDscSwbVrhupNlyKZVxoghxIvigqxAyKbKiynGmeG4hXnhuonigJliMTU4wqThu4vCov///yJwc2FsbXMi "Jelly – Try It Online") [Test Cases](https://tio.run/##XVJdTxNBFH3nVyw1Joo1drfdFuWFgDwaIAE1osbpdtiddnen2Q@wPFGjQakmJiQCRiUg9skYP2Jo6QNJtzbFfzH9I/XOTBciyd7OOfeee2bmTovYtiuDQX/9Q/tz9NbsVqMj1ngxdi/ai/ZO62P96lGnxprbrHnCWr@j7W4VECRZ42C@v76bz117OAG9U92P/fWdkVnWeD6RSeUmtFyKp1nrDWuAdpM1fp7WQXH5BpnkW@2z5k60PdqvNljrtf6EtTbvXmfN3fneEWu@iz5d8TsnvW@PS@1fdxKnW87McvtwLDW9xI73uxt/Wr0vl6ZY8330o/PdecCOt3Cvvth9Odqp9Z99nezV/9audnfhDhV2/IofUdXH24esVWsfDKINkAxm7s/NTC/M3FZmFxfmFhduKSNLeiqpZCC0XFJJZyEygHmokAeqDqkGoUPclDIVWtS0XDNQU7kPF6tAxpNKFjQ6QGjJjMusyu2SChhI65yg8huW@UZcnT0/Q8xFgDIrPqnVRa@kaWHLFXpc0GVKfJr2aJAwsYt94ieSCfyUFkIObLxCAmII7IZOHnscFXAYYI@61KkAK1LfChEHYcHEvO6FgQWLqvjICbENUDuHqlIirumLZIxUxbDAjxg2loX/KF7zuL2LLewQxJ2xH1jYE3vn4bfsI9vhyrJHV7CXF00G7ybID4SHT11TocuKT23qUBcyxEfSrIi92NdGDnYDFBDqyo1xiYhDF5ArgUV9LO5KBUUO5UKaR4WhGXXF6hBDrMBCh/ehPCqVwhLANVy2wE6ULWSaiIikYSFPJh1kI8MiAgVw0VWBPN5rhyUsdrH4FZARiHFTB7nDMVKPuIFFJNcucBOMgyGGQ/DxCFy2iE3K5SEzYER@XFIVOIAP84XniE0vZkBDHBpYFVk9wwEJwtgey6FbOO/hVZ4swqhlcxkH4i21M6QqwwtqMUjHAP5jfAAeXsG2eKfEPw "Jelly – Try It Online") **How it Works** Essentially, this tries to convert the ords of the characters input into a binary value, for example `"joel"` -> `[106, 111, 101, 108]`-> `2^3*106 + 2^2*111 + 2^1*101 + 2^0*108`. Then, this value is taken mod 407, then mod 270, then [a few more mods], then mod 160. This is useful because it maps all 66 string inputs to integers between 0 and 158 (lucky on final mod). The integer is indexed from the integer list `“ọḷḊḲɦ...ƙḅyẉ’b158¤` to find the value of `n` such that the input has the `n`-th least number of chapters. Joel happens to have the 7-th least number of chapters. This value of `n` is further indexed into the list `“£ÐgƁ÷ḅ*Wßßɦ*⁷ċṗṿỵ×Ɓṿ⁷ḢQ’b7+\;“BƝ‘` to find the exact number of chapters. Possible improvement: inputs with the same number of chapters can hash to the same value from the mods (0% collision is not necessary), but I did not account for that in my program to determine the sequence of mods. [Answer] # JavaScript (ES6), ~~251~~ 197 bytes ``` s=>`- cE1$ " +%& % &!!· $!#&!!)!'=6 &!6".! -!!Q$"/ 779@@= % & $'1 U( I>!! K * "S< : 9$!C % . $. 9E1/ %!!'" + $ % `.split`!`.join` `.charCodeAt(parseInt(s[2]+s[0]+s[5],36)%913%168%147)-33 ``` ### Test ``` let f = s=>`- cE1$ " +%& % &!!· $!#&!!)!'=6 &!6".! -!!Q$"/ 779@@= % & $'1 U( I>!! K * "S< : 9$!C % . $. 9E1/ %!!'" + $ % `.split`!`.join` `.charCodeAt(parseInt(s[2]+s[0]+s[5],36)%913%168%147)-33 o.innerText = [ ["genesis", 50 ], ["exodus", 40 ], ["leviticus", 27 ], ["numbers", 36 ], ["deuteronomy", 34 ], ["joshua", 24 ], ["judges", 21 ], ["ruth", 4 ], ["1 samuel", 31 ], ["2 samuel", 24 ], ["1 kings", 22 ], ["2 kings", 25 ], ["1 chronicles", 29 ], ["2 chronicles", 36 ], ["ezra", 10 ], ["nehemiah", 13 ], ["esther", 10 ], ["job", 42 ], ["psalms", 150], ["proverbs", 31 ], ["ecclesiastes", 12 ], ["song of solomon", 8 ], ["isaiah", 66 ], ["jeremiah", 52 ], ["lamentations", 5 ], ["ezekiel", 48 ], ["daniel", 12 ], ["hosea", 14 ], ["joel", 3 ], ["amos", 9 ], ["obadiah", 1 ], ["jonah", 4 ], ["micah", 7 ], ["nahum", 3 ], ["habakkuk", 3 ], ["zephaniah", 3 ], ["haggai", 2 ], ["zechariah", 14 ], ["malachi", 4 ], ["matthew", 28 ], ["mark", 16 ], ["luke", 24 ], ["john", 21 ], ["acts", 28 ], ["romans", 16 ], ["1 corinthians", 16 ], ["2 corinthians", 13 ], ["galatians", 6 ], ["ephesians", 6 ], ["philippians", 4 ], ["colossians", 4 ], ["1 thessalonians", 5 ], ["2 thessalonians", 3 ], ["1 timothy", 6 ], ["2 timothy", 4 ], ["titus", 3 ], ["philemon", 1 ], ["hebrews", 13 ], ["james", 5 ], ["1 peter", 5 ], ["2 peter", 3 ], ["1 john", 5 ], ["2 john", 1 ], ["3 john", 1 ], ["jude", 1 ], ["revelation", 22 ] ] .every(s => (log += s[0] + ' --> ' + (res = f(s[0])) + '\n', res == s[1]), log = '') ? log + '\nSUCCESS' : log + '\nFAIL' ``` ``` <pre id=o></pre> ``` ### Formatted and commented ``` s => // s = book name `- cE1$ " +%& % &!!· (...)` // data string (truncated) .split`!`.join` ` // inflate padding characters '!' -> 3 spaces .charCodeAt( // read the ASCII code at the position found by parseInt(s[2] + s[0] + s[5], 36) // parsing 3 characters of the input in this exact % 913 % 168 % 147 // order as base 36 and applying three consecutive ) - 33 // modulo operations, then subtract 33 ``` [Answer] # Excel, 373 bytes Reusing @Misha's approach from the Mathematica answer (`6a+b+8c+5d+3e modulo 151`): ``` =CHOOSE(MOD(6*CODE(LEFT(A1,1))+CODE(MID(A1,2,1))+8*CODE(MID(A1,3,1))+5*CODE(MID(A1&A1,4,1))+3*CODE(MID(A1&A1,5,1)),151)+1,30,,,,27,,,,3,12,,,9,,149,,,28,,,13,,,35,3,,35,7,,8,,20,,49,23,13,4,,,4,,,,,,,2,,,39,,,15,3,,3,9,,12,27,,,,,,51,15,,,,70,,65,,21,11,,,4,,24,,,6,,2,1,,,,,,2,,,30,,,,,,23,,,33,,20,,,15,,,4,,4,,,12,2,,2,47,23,,2,,,,,41,,,3,,,5,,,,,11,,21,5,,,,5,2,3,26)+1 ``` Lookup returns chapters `-1`, and then add the one. This changes `10` into `9` twice, and `,1,` into `,,` 4 times. # Updated to old approach. Excel, ~~460~~ 401 bytes Save as CSV, Book Name entered at end of first line (`C1`), result displayed in `C2`: ``` 1c,16,revelation 1co,29,"=VLOOKUP(LEFT(C1,1)&MID(C1,3,1)&MID(C1,6,1),A:B,2)" 1j,5 1k,22 1p,5 1s,31 1t,6 1ts,5 2c,13 2co,36 2j,1 2k,25 2p,3 2s,24 2t,4 2ts,3 3j,1 a,9 at,28 c,4 d,12 du,34 e,12 ee,48 eh,6 eo,40 er,10 g,6 gn,50 h,3 hbw,13 hg,2 hs,14 i,66 j,42 jd,1 jds,21 je,3 jh,21 jm,5 jn,4 jr,52 js,24 lm,5 lv,27 m,7 ml,4 mr,16 mt,28 n,3 nhi,13 nm,36 o,1 p,150 pi,1 pip,4 po,31 r,16 rt,4 rv,22 s,8 t,3 zc,14 zp,3 ``` For the lookup table, we can leave out `et 10` and `l 24` because these match on `er 10` and `js 24` respectively. [Answer] # Mathematica: ~~323~~ 294 bytes ``` Uncompress["1:eJxTTMoPSpvOwMBQzAIkfDKLSzJlgAwCBEhtJi8qwQUnpqESsqgEHyqhAjePBc7lgBOccEIUThiBCAm4AayECUZUghmV0EAlBFAdxILqN17CgWMCNwUn4QQnxEAEDyqBcLgkKsGO6gUmLAROX8rjJSRQCSU4IYpKILzAiDfEebG4wADVDmZchBYqgRYVbLgIRPiJ4VXHDDdKGuZ9AAP6TUg="][[Mod[ToCharacterCode@StringTake[#<>#,5].{6,1,8,5,3},151,1]]]& ``` ### How it works For a book beginning with character codes `a`,`b`,`c`,`d`,`e` (wrapping around if necessary) computes `6a+b+8c+5d+3e` modulo 151, which happens to be unique, and then looks up the number of chapters in a compressed list of length 151. (Unused entries in the list are filled in with duplicates of the previous entry. This encourages run-length encoding, maybe? Anyway, it helps.) Thanks to @numbermaniac for the list compression idea, which is hard to put a number on but is a huge part of the improvement here. # Old version: Mathematica, ~~548~~ ~~435~~ 407 bytes ``` Join["111112333333344444455555666789"~(p=StringPartition)~1,"1010121213131314141616162121222224242425272828293131343636404248505266"~p~2,{"150"}][[Max@StringPosition["2jn3jnjduoaapimhgi2pe2tshbkjeonhntttzpn2toclsjnjmlhpiprtu1jn1pe1tsjmjlmt1toehiglimcmsnoaometrerzdnlecs2cihbwnhihshzcr1cimrarmsjhojds1kgrva2sujsalku2kglviatcmte1co1supordur2conmreosjbbeeegnijriiahpas",""<>#&@Characters[#<>#][[{1,3,6}]]]/3]]& ``` ### How it works We convert each name `name` to characters 1, 3, and 6 of `namename` (e.g. `leviticus` becomes `lvi`, `job` becomes `jbb`) before looking it up. The list we look things up in is slightly compressed by putting the 1-digit and the 2-digit chapter numbers together in strings. # Mathematica: 40 bytes, non-competing ``` WolframAlpha["# chapters "<>#,"Result"]& ``` Yeah. [Answer] # [Python 2](https://docs.python.org/2/), ~~244~~ 183 bytes ``` lambda n:ord('A("4,|O|;|>||_ /\xb5$+_>| _7|a|5-##_"_G"_/|7) $_$-|<|$_"&|||_;S_% |:_45_#||#|%7"_,_\'_)|_"|C_#|/_I|$_ "|,|_%|_8_Q|+||||_!|_C#'.replace('|','__')[hash(n)%839%434%152])-31 ``` [Try it online!](https://tio.run/##ZVNbb9owGH3nV3hcFlDTdg4J0HatVPVh2tM07bFFlhMMdknsyHF6dX87@2wH2EWKyTnnOz6@fKR@NVzJZLe@ftiVtMpXFMlLpVfj6HbcT2P7w17ZG2sJOn94ybPhCbmxiMwttdnpYED65FufnNv5BA3J8NR@tUPS/2zBfvWLjJC9JGlGBtYO7GjeJzF5iMjEkr69A/GcfAc36tvYkpElC/LTnlg39ZMld4PoTLO6pAUbRzaKI0KiyT2nDR/LyWgxvRil03SEs2Q5OZ3inUTX6D7aMMka0UQxitiLWrUelexJGFEEItsqZ9rDFWsN00qq6tXRR9XwlnrUrjbMW3RruHtj1NCqZaXDyR8Yo62QmybIB4hRwSFXFCXrSn9z9qb9OpJxVgnqV2CN4UyHfeTuVTe0rLy91uqJ6TxMLVyIoI0JUY2SG6TWqFGlqpR0kmhol/nI9CEf@sqkoUYo2e2BbUU4xIrKDnHVsHADKgi0Ut6tcrrahyoZQCWKAIC3lZ9Oc7rdtluH31jNITc4ON1sqAhywanu5IpCd7kI0MD5nwPUPqFstywsyP25aGFCT1RF5f6elRbScNEJyb/CBlYwewI7clcXSM1FKep6Twu4v@ZQxAg200ADoGmH6P8kcIlKGf7a1Y/ECNMeVmFdXzjLNXv28iM0o4uomQltT44Qo/2ZkwOaHhD8O/29aPbESt/QaNnrrZVGBgkJX24PodrdAoreL3H2gd4/ojMowxWPTYzWYzOZ9HreEX7RvdPQMWGJruFjyr7EKIWRzGM0ncFIAbuBQQeKO5rAyGBcBBuGKXga3inUsMtxZgxkEaMZeDKAMCVdBBW7uBhBQIieexqeruwWcu7ZcQ977gc4Z/4J3szPDXTqY50j2xeyIPknSZa73w "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~117 115~~ 114 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OP%⁽µW%⁽£İ%237 “ĿḊƘ⁹ƙƬṂ;ɓṭ6-ạʋ⁵%$Ẋf,¥ÆÑƈø¬ȦṘd⁾“ʂụṿⱮẆƊ¦ẠLjƒ~Ḅr©“Ẏw|!¡¢o“ŻɗṢ“3ɠ‘Zċ€ÇTḢị“£ẆJQ+k⁽’ḃ6¤+\;“£¬®µıñø"BƝ¤‘¤ ``` **[Try it online!](https://tio.run/##HU4/S8NAFN/9FoqZahcLdejmKEIVBEEcjWItFewggkgSpUoCgjqYgkKbpgUhFjME7i5o4V08TL/Fe1/kPDq9339ey263r7Ru7ljkfkO2vzij4star20skfNWzJD5KiSXq75KkHuN8gX5Z72KYjgPyM2sVRT@8RqMZU8@qQfJIPmbIA@PyP0x/bmH@Rj5jNIpip7yYYJisN1SzzfI7i7gw0RQPF5eL8MQonPDfvPyFXlkUK0ckBMeFAF5ibzfQxZhHhgdRmZpa7dyZl4lp4/stg5x5bCxsCCBKWRFKlPJVjbVO8RmA2Kt9Yndsbun3X8 "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##VVFNaxRBEL33rxglOUUPu4F4yM2LIIIKgiBeemcr070z0z109yQmiGSjJJKAoB7cgEK@QViDAQM7u5rAzGYw@Rc9f2StmVEwl36vqvq9qq7uQBAsTyYPH00X3V/p6dMK9sffp5uzd0ix@nl8bgebea/oJvl23rfJ2vzlR5t8m7tth7tXW0X3dHrKDjcXbqWH2Xr2Pn@bDdL@7yOb9NpF9wz1V2t2dGiT8@Lk2A7X8830yA53HnTyD6/s4I1Kv@IVO3y39PJGupvuSYwuRpefbLKHbPZyp1jtPRtvFWv9bOOJHezZ0Rbm0310uv94xsdRi9VtO3g9lx7MPJ@vSmk/PU5PxyfZSTa4eTf/kh6gR3owsaMfFz@zDZucTaHd1L3JxAMBmmsCL2Q71iSARW64i0zEYQuUJm2IDSgpZLhMOlKzmJJO3PZAExUbRhqOpmEMAWn@Iw3H58LTmKix4bgM9dwNoEz@F8CKokQAg5BTRkAbBgp7tEikaRBqEim5CKqFF93yPqfaoEpL4TlywdEykKEUhGtayjugap@AhiAMNVyKsgX4HIdqU1ECkxpwfomUhlIT2aLtSiwFniF38UQWh4TRFvX92CcrEDEUY4FRz6McEy6jqkyENKAu44gGR19CVD4JYh/QjwlCXYNLkiEV1RKk4sIwXkbNa5GHNqZi2Kp8JrKI8YBHUcVdfKiu0w0HG2ncDq6wNroeY52H0rDlsvKXGW7i2hDKdTFoKVjSpINrKgUR4Pfi9RobTjV6s4bZGvC/gShYhKDa6h8 "Jelly – Try It Online") ### How? Hashes the product of the ordinals of the characters of the input string by taking ~~three~~ ~~two~~ three division remainders, looks up the result in a list of lists and uses the found index to look up the result in a list of book lengths. When finding a hash function I only considered those which resulted in at most one bucket with any results over 255 to allow code-page indexing and then chose ones that minimised the total number of values to encode (after removing the "offending" bucket or if none existed the longest bucket). From 66 with three modulos I found a 59 (`%731%381%258`) a 58 (`%731%399%239`) then one with 56 entries (`%1241%865%251`) [making for 117 bytes] ...I then found a 58 using only two remainders (`%1987%251`) [making for 115 bytes] ...then I found a 55 using three remainders, which when two dummy entries are added allows for a further compression of the lookup list... The code: 1. ``` “ĿḊƘ⁹ƙƬṂ;ɓṭ6-ạʋ⁵%$Ẋf,¥ÆÑƈø¬ȦṘd⁾“ʂụṿⱮẆƊ¦ẠLjƒ~Ḅr©“Ẏw|!¡¢o“ŻɗṢ“3ɠ‘ ``` is a list of five lists of code-page indices (`“...“...“...“...“...“...‘`): ``` [[199,193,148,137,161,152,179,59,155,224,54,45,211,169,133,37,36,208,102,44,4,13,16,156,29,7,190,204,100,142],[167,225,226,149,207,145,5,171,76,106,158,126,172,114,6],[209,119,124,33,0,1,111],[210,157,183],[51,159]] ``` This is transposed using the atom `Z` to get the buckets; call this B: ``` [[199,167,209,210,51],[193,225,119,157,159],[148,226,124,183],[137,149,33],[161,207,0],[152,145,1],[179,5,111],[59,171],[155,76],[224,106],[54,158],[45,126],[211,172],[169,114],[133,6],37,36,208,102,44,4,13,16,156,29,7,190,204,100,142] ``` (the `0` and `1` are the dummy keys, allowing the `[179,5,111]` to be two further to the right - the transpose requires longer entries to be to the left) 2. ``` “£ẆJQ+k⁽’ḃ6¤+\;“£¬®µıñø"BƝ¤‘¤ ``` Call this C (the chapter counts) - it's a list of integers: ``` [1,4,5,6,10,12,13,14,16,21,22,24,28,31,36,40,42,48,50,52,2,7,8,9,25,27,29,34,66,150,3] ``` and is constructed as follows (the two dummy keys above therefore allow `10,12,13` to be in ascending order): ``` “£ẆJQ+k⁽’ḃ6¤+\;“£¬®µıñø"BƝ¤‘¤ ¤ - nilad followed by link(s) as a nilad: ¤ - nilad followed by link(s) as a nilad: “£ẆJQ+k⁽’ - base 250 number = 935841127777142 ḃ6 - converted to bijective base 6 = [1,3,1,1,4,2,1,1,2,5,1,2,4,3,5,4,2,6,2,2] +\ - cumulative reduce with addition = [1,4,5,6,10,12,13,14,16,21,22,24,28,31,36,40,42,48,50,52] “£¬®µıñø"BƝ¤‘ - code-page indices = [2,7,8,9,25,27,29,34,66,150,3] ; - concatenate = [1,4,5,6,10,12,13,14,16,21,22,24,28,31,36,40,42,48,50,52,2,7,8,9,25,27,29,34,66,150,3] ``` Now the simplified version of the code is: ``` OP%⁽µW%⁽£İ%237 - Link 1, hash function: list of characters e.g. "genesis" O - cast to ordinals [103,101,110,101,115,105,115] P - product 160493569871250 ⁽µW - base 250 literal 3338 % - modulo 1050 ⁽£İ - base 250 literal 1699 % - modulo 1050 237 - literal 237 % - modulo 102 Bċ€ÇTḢịC - Main link: list of characters e.g. "genesis" B - the list of buckets, B, described in (1) above Ç - call the last link as a monad (get the hashed value) 102 ċ€ - count for €ach - yields 29 zeros and a one or 30 zeros [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0] T - truthy indexes - yields a list of length one or zero [19] Ḣ - head - extracts that value or zero if it was empty 19 ----------------------------------------------v C - the list of chapter lengths, C, described in (2) above [1,4,5,6,10,12,13,14,16,21,22,24,28,31,36,40,42,48,50,52,2,7,8,9,25,27,29,34,66,150,3] ị - index (the head value) into (the chapter list, c) 50 - - 1-indexed and modular so 0 yields 3 (the rightmost) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~438~~ ~~429~~ ~~416~~ ~~411~~ 409 bytes ``` lambda s:[c for x,c in zip('A|m|C|h|2|th|2 Co|D|y|E|Ep|Ec|x|ze|G|Ge|H|gg|He|Ho|I|Jo|oe|oh|na|sh|Ju|dg|Ja|Je| J|1 J|K|2 K|L|Le|Lu|M|ch|rk|tt|N|Ne|Nu|O|P|Pr|Ph|pp|Pe|2 P|R|Ro|Ru|S|Sa|2 S|T| T|2 T| Ti|2 Ti|Z|Zep'.split('|'),(28,9,4,29,36,16,13,12,34,10,6,12,40,48,6,50,3,2,13,14,66,42,3,21,4,24,1,21,5,52,1,5,22,25,5,27,24,7,4,16,28,3,13,36,1,150,31,1,4,5,3,22,16,4,8,31,24,3,5,3,6,4,14,3))if x in s.title()][-1] ``` [Try it online!](https://tio.run/##XVRNb9s4EL3nV@gmG2CLiJIdp0AXWHSDdt00ayQ9Nc2BlsciY0kUSCp1gvnv2aFIyWkB2@R78/GGw6G7Zyd1y1/3H3@@1qLZ7kRiP9yXyV6b5MjKRLXJi@pm6d/Y4CeUyNHRT/JJ4z/4jFd41eFViUd8AfyMnwG/YFXhF1o1/otrjRpQS2wFWonrHncVrgWuAZM1ZvT9Srm@4jVeA173@A1LieaAzuEN3gDe9PgfbnBjcCOx63AD5L7BW7zVeNvjHd4JIu7wOybfaeMX5VeFP/AHdOl729XKzVJM52zGV@ySFYxfsnzJMvrkLOMsL1h2zpZ@W5yzYkXbxTnLGR/sBVsuWcE9znwsOfvdgi3ITgvnjC/8euFtF@RCiUko99FehmU@Gy1kWvg03HsUbOVJCskH1jOklc/nap8cfc/te6dcDbP5w/277OFVfLyfpRW0YJVNqcA5O5ulcNS7nmARYA1PyqnSM/xiYNq@2YIhnC8HvIPegdGtbp6JKwbuUVvZCwqJsN9V4DNkAzS9kyQw7LPEiqaHmkKDkU8EHz0Oqq18NI8OI15EeylJXpX1IHEZnd6SsVJ4MVRTFg7WgoRGCSoky4PVOglmsj/qLdUYJDsr6obyZLFHndFPYLZ2KhpKL6SEdV4uC1FWt1Wi94nVtW50m7LVQCsrBtllKOoRTKxjEcLovUDrhFO69bcSK4eD8j0pQo6daAcYlaS24E82Nn9o57AXjaYkoSd6K3bhwNGtFdM1NKr0IN6wkH0zZpBiKw6H/jDiF@gkqXvv0aGqhKLOR3MphQkyMbWoRSnVpCQc9fkX@a8iNpQ7C82o@wOcpkbLdpoZUTo7xRjdCN@cGEUToI1qnVRvWf4HG6qtqBoXmDgUnfQ3dyI6qWrVdYEKlZR0g9a@ZbKEDmFpLGjGxOme@J90PnqrRjv5PGrwExHy0bvsJ3dfAQwTE84uYWvg1@kMjzQhk2SWdOD83I4VRDgqhy6OxoBC2vw3RG8Uxr2BJ6iHCRxe3cPZ2Zs/bvHhLOl8Y4lI3/2Vsv3sOH/9Hw "Python 2 – Try It Online") Works by changing the input to Title Case, and finding the last matching substring in the list. ``` [('A', 28), ('m', 9), ('C', 4), ('h', 29), ('2', 36), ('th', 16), ('2 Co', 13), ... ``` Eg. `'1 samuel' -> '1 Samuel'` which matches `('m', 9), ('2', 36), ('S', 8), ('Sa', 31), ('2 S', 24)`. The last match is `('2 S', 24)`, so the answer is `24` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 204 bytes ``` 00 C0 20 FD AE 20 9E AD 85 FD 20 A3 B6 A9 1E 85 FB A9 00 85 FC A8 B1 22 18 69 4A 65 FC 45 FB 85 FC E6 FB C8 C4 FD D0 EE A5 FC 4A 4A 4A 4A A8 A5 FC 29 0F 19 BA C0 A8 BE 3D C0 A9 00 4C CD BD 16 34 42 0D 01 00 04 03 04 1C 0A 00 06 15 07 00 16 00 22 03 02 0E 00 24 00 00 01 00 08 03 00 1C 03 01 00 00 00 00 00 03 03 00 00 00 24 10 1F 18 0E 10 00 00 00 32 30 1F 2A 00 0D 00 05 00 1B 00 0A 00 01 28 00 00 0C 96 00 10 00 00 00 18 00 00 03 00 00 00 00 00 00 15 09 00 05 00 04 00 00 04 00 00 04 00 00 18 00 1D 05 00 00 19 00 0D 00 00 06 06 0C 00 00 00 00 05 00 01 00 05 00 04 30 10 20 10 40 70 00 00 20 50 00 10 60 30 20 ``` **Explanation**: The key here is to use a special hashing function that maps without collissions to values `0` to `125` \*). The chapter numbers are then placed in a 126 bytes table. The hashing is done in full 8 bits, the final value is adjusted by looking up the high nibbles in yet another table, this way combining different high nibbles where the low nibbles don't collide. Here's a commented disassembly listing of the code part: ``` .C:c000 20 FD AE JSR $AEFD ; consume comma .C:c003 20 9E AD JSR $AD9E ; evaluate argument .C:c006 85 FD STA $FD ; remember string length .C:c008 20 A3 B6 JSR $B6A3 ; free string .... .C:c00b A9 1E LDA #$1E ; initial xor key for hash .C:c00d 85 FB STA $FB .C:c00f A9 00 LDA #$00 ; initial hash value .C:c011 85 FC STA $FC .C:c013 A8 TAY .C:c014 .hashloop: .C:c014 B1 22 LDA ($22),Y ; load next string character .C:c016 18 CLC ; clear carry for additions .C:c017 69 4A ADC #$4A ; add fixed offset .C:c019 65 FC ADC $FC ; add previous hash value .C:c01b 45 FB EOR $FB ; xor with key .C:c01d 85 FC STA $FC ; store hash value .C:c01f E6 FB INC $FB ; increment xor key .C:c021 C8 INY ; next character .C:c022 C4 FD CPY $FD ; check for string length .C:c024 D0 EE BNE .hashloop ; end of string not reached -> repeat .C:c026 .hashadjust: .C:c026 A5 FC LDA $FC ; load hash .C:c028 4A LSR A ; shift left four times .C:c029 4A LSR A .C:c02a 4A LSR A .C:c02b 4A LSR A .C:c02c A8 TAY ; and copy to y index register .C:c02d A5 FC LDA $FC ; load hash again .C:c02f 29 0F AND #$0F ; mask low nibble .C:c031 19 BA C0 ORA $C0BA,Y ; and add high nibble from table .C:c034 A8 TAY ; copy to y index register .C:c035 BE 3D C0 LDX .chapters,Y ; load chapter number from table .C:c038 A9 00 LDA #$00 ; accu must be 0 for OS function: .C:c03a 4C CD BD JMP $BDCD ; print 16bit value in A/X ``` after that follows a table of the chapter numbers and finally a table of the high nibbles for the hash value. **[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"bible.prg":"data:;base64,AMAg/a4gnq2F/SCjtqkehfupAIX8qLEiGGlKZfxF+4X85vvIxP3Q7qX8SkpKSqil/CkPGbrAqL49wKkATM29FjRCDQEABAMEHAoABhUHABYAIgMCDgAkAAABAAgDABwDAQAAAAAAAwMAAAAkEB8YDhAAAAAyMB8qAA0ABQAbAAoAASgAAAyWABAAAAAYAAADAAAAAAAAFQkABQAEAAAEAAAEAAAYAB0FAAAZAA0AAAYGDAAAAAAFAAEABQAEMBAgEEBwAAAgUAAQYDAg"%7D,"vice":%7B"-autostart":"bible.prg"%7D%7D)** **Usage:** `sys49152,"name"`, for example `sys49152,"genesis"` (output `50`). **Important:** If the program was load from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers. Hint about the casing: In the default mode of the C64, the input will appear as upper case. This **is** in fact lowercase, but the C64 has two modes and in the default upper/graphics mode, lowercase characters appear as uppercase and uppercase characters appear as graphics symbols. --- \*) of course, this isn't as dense as it could be ... oh well, maybe I find an even better solution later ;) [Answer] # Java 8, ~~623~~ ~~597~~ 590 bytes ``` s->{int i=s.chars().map(c->c*c*c).sum()/13595;return s.contains("tt")?28:i<258?42:i<355?1:i<357?3:i<362?16:i<366?28:i<369?21:i<375?9:i<377?24:i<380?5:i<382?1:i<386?10:i<402?7:i<436?4:i<438?5:i<439?14:i<461?3:i<463?2:i<477?22:i<478?25:i<490?5:i<491?3:i<493?12:i<500?66:i<545?3:i<546?1:i<548?21:i<562?4:i<568?24:i<570?10:i<572?31:i<573?24:i<582?16:i<583?150:i<607?40:i<629?48:i<639?50:i<663?13:i<675?3:i<677?36:i<679?52:i<734?1:i<735?6:i<736?4:i<775?14:i<785?6:i<796?3:i<800?31:i<812?6:i<876?27:i<910?29:i<911?36:i<940?22:i<1018?4:i<1035?16:i<1036?13:i<1066?12:i<1092?34:i<1229?5:i<1230?3:8;} ``` -7 bytes thanks to *@Nevay* by changing the for-loop to a stream. Can definitely be golfed more.. Just need to do some more testing. It may not be the shortest answer by a long shot, and could be golfed by porting some existing answer, but I'm still proud to come up with something myself.. :) **Explanation:** [Try it here.](https://tio.run/##bVZRc9soEH7vr2D8JN8lPoEEkpJL@QXXlz7e9AHL1MKWhEYgN2mnvz23gNIeKJOZsP6@ZffbZcG@iJu415McL6fra9sLY9A/Qo0/PiCkRivnr6KV6JP76AHUZp/trMYzMvtHAH9@gH/GCqta9AmN6Am9mvuPP5ynejKHthOzyfaHQUxZe/@x/QP@9gezDNn@L1zQhj7O0i7ziMBVjxYSm2xn7W7PSf2g/ia05iUBo6CUY79WvHArIxwzb7DgWrCGE@9SUd74teKkdEadc@pXEmLUjOMcjDInvHJrwXjp19o7lkXDsQcY9tlKVnCnonQhg1Fz4l2bELtsVs@m4Nh50DznzAmkJfUMLZnPTss66KRQQunXOuikVR500YrwwrtUxUrVa7m0hvjUObG84qU3SMNL1wEGsgMFcrHLyaqQm4HugnkDXJy8qii9mqqgnPk1tKCCHb70ql6JhvkQNdTjNdWYeKKuoPGuew3OOWm8gUOWpsxDm3COax8W55DHFwAWC@JwDkeHg1sDBXs/AsVQbxSQ76F@/Pn66CZsWo49TNg6aDetTmiAYVln8d8vSOzDiFppbLY7y1EaZXZ3NPdT@obLZ31aAC5juJc3BXEdQ6qIGZfhKGfACxbhJ7nA3dCjHl6AKyPuok23CAiVwMvpLF0GHMHzYjsQFGEYGTEssofQsTP5RZB0xxX64KKTZMMbThP/tgP5qu29pCbZ9H8yqVx@n6E2HDdwlJ0clIBCcBF7G9vJeeN/0UeoOZY6GdEPkA8nZzbN@ibno9k0Q7ZOoBLGOpk4jmY0PFH6KzK614Med3d1RCsjvFwWF3eR81oHjcP1YpCjGz49uqlKOiKvyp1JGec4idHDibJOG@k6mA6NP@4IE4OGZPHZ6KM4hUYn20exGaNBtQ5MJlp0y5Bm6sRRXK/LNcW/y6mDKlyUdMP5LBRMTuLu3vsgL5EietF2aqNQWJiPbxCnTvAZtOD4cPrlKre3Snfj5k6J1ppNzFkPwh1eEhVugoY3xHbqPZYkbNyFM1RlA5Nckqlzk7klpk71apoCFVfSwqQa8x6DETTJwPWAOym280dSukh3q0Hb7iXVQn4TcT6r7LIJ45RLf5PiXnfyOMtv295c4MZspGI0Seveg7SCFU6Vh9NNnQMayyjeReHNlSk2y5vs/U3@9Vr6HzHTrG7Cyug7xu94@71z53//PK9fNJ9f4N0ZDnqxh8lNSD9mBv2JdijbwfLszP0DcvZ4aDOz/81lK/D0BMG8325V8fP1Pw) 1. Takes the power of 3 of each character (as ASCII value) in the input String 2. Takes the sum of those 3. Divides the result by `13595` as integer division (in Java this automatically truncates/floors the result). 4. This leaves 65 unique values (only `habakkuk` and `matthew` both have a value of `674`) 5. And then one giant ternary-if to return the correct result (with a few values combining in a single ternary-statement where possible (`381` and `382` both `1`; `425` and `436` both `4`; `649` and `663` both `13`; `952` and `1018` both `4`; `1122` and `1229` both `5`). ]
[Question] [ You have to write a program or a function in any language that outputs this pattern: ``` ~|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||~ |~|||||||||||||||||||||||||||||||||||||||||||||||||||||||||~| ||~|||||||||||||||||||||||||||||||||||||||||||||||||||||||~|| |||~|||||||||||||||||||||||||||||||||||||||||||||||||||||~||| ||||~|||||||||||||||||||||||||||||||||||||||||||||||||||~|||| |||||~|||||||||||||||||||||||||||||||||||||||||||||||||~||||| ||||||~|||||||||||||||||||||||||||||||||||||||||||||||~|||||| |||||||~|||||||||||||||||||||||||||||||||||||||||||||~||||||| ||||||||~|||||||||||||||||||||||||||||||||||||||||||~|||||||| |||||||||~|||||||||||||||||||||||||||||||||||||||||~||||||||| ||||||||||~|||||||||||||||||||~|||||||||||||||||||~|||||||||| |||||||||||~|||||||||||||||||~|~|||||||||||||||||~||||||||||| ||||||||||||~|||||||||||||||~|||~|||||||||||||||~|||||||||||| |||||||||||||~|||||||||||||~|||||~|||||||||||||~||||||||||||| ||||||||||||||~|||||||||||~|||||||~|||||||||||~|||||||||||||| |||||||||||||||~|||||||||~|||||||||~|||||||||~||||||||||||||| ||||||||||||||||~|||||||~|||||||||||~|||||||~|||||||||||||||| |||||||||||||||||~|||||~|||||||||||||~|||||~||||||||||||||||| ||||||||||||||||||~|||~|||||||||||||||~|||~|||||||||||||||||| |||||||||||||||||||~|~|||||||||||||||||~|~||||||||||||||||||| ``` The output is composed of 20 lines of 61 characters each. # Rules * Standard loopholes are forbidden * There may be a single trailing newline at the end of the output * There may not be any trailing whitespace on any line of the output Without a trailing newline, the md5 checksum of the output is `fde4e3b4606bf9f8c314131c93988e96`. With a trailing newline, the md5 checksum of the output is `1f0b43db4fec6594be202c8339024cb7`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~97~~ ~~82~~ ~~81~~ 80 bytes Golfed 15 bytes after learning that `abs` is a builtin in C, an additional byte thanks to [Rogem](https://codegolf.stackexchange.com/users/77406/rogem) for pointing out that the declarations of my variables can be moved to the function, and another byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for suggesting `x=31;--x+31` instead of `x=-31;++x<31`. ``` f(x,y){for(y=21;--y;puts(""))for(x=31;--x+31;)printf(abs(10-abs(x))-y?"|":"~");} ``` [Try it online!](https://tio.run/##FYzLCoAgEAD/ZU@71ELWLZG@xQTDQyZWoPT4dcvTMHMYw4sxpVhMbabLbhGz6oVkzjKcx44ARLUmNdSamh8UovOHRT3vKDquSEScJ7hhhBdIPmXVzuM/xCof "C (gcc) – Try It Online") This outputs with a trailing newline. The function `f` does the outputting. ### Explanation The output can be stated as a graph. ``` ~|||||||||||||||||||||||||||||+|||||||||||||||||||||||||||||~ |~||||||||||||||||||||||||||||+||||||||||||||||||||||||||||~| ||~|||||||||||||||||||||||||||+|||||||||||||||||||||||||||~|| |||~||||||||||||||||||||||||||+||||||||||||||||||||||||||~||| ||||~|||||||||||||||||||||||||+|||||||||||||||||||||||||~|||| |||||~||||||||||||||||||||||||+||||||||||||||||||||||||~||||| ||||||~|||||||||||||||||||||||+|||||||||||||||||||||||~|||||| |||||||~||||||||||||||||||||||+||||||||||||||||||||||~||||||| ||||||||~|||||||||||||||||||||+|||||||||||||||||||||~|||||||| |||||||||~||||||||||||||||||||+||||||||||||||||||||~||||||||| ||||||||||~|||||||||||||||||||+|||||||||||||||||||~|||||||||| |||||||||||~|||||||||||||||||~+~|||||||||||||||||~||||||||||| ||||||||||||~|||||||||||||||~|+|~|||||||||||||||~|||||||||||| |||||||||||||~|||||||||||||~||+||~|||||||||||||~||||||||||||| ||||||||||||||~|||||||||||~|||+|||~|||||||||||~|||||||||||||| |||||||||||||||~|||||||||~||||+||||~|||||||||~||||||||||||||| ||||||||||||||||~|||||||~|||||+|||||~|||||||~|||||||||||||||| |||||||||||||||||~|||||~||||||+||||||~|||||~||||||||||||||||| ||||||||||||||||||~|||~|||||||+|||||||~|||~|||||||||||||||||| |||||||||||||||||||~|~|||||||||||||||||~|~||||||||||||||||||| +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ``` (The `+`s are only shown for explanation purposes and represent the axes.) The equation of this graph is \$y=\text{abs}(10-\text{abs}(x))\$ as can be seen here in this link to a [Desmos graph](https://www.desmos.com/calculator/f3r2t5atix). ``` abs(10 - abs(x)) abs( ) Reflect whatever is beneath the x-axis to above the x-axis 10 - abs(x) This forms the central triangle-like structure ``` In function `f`, we have two for-loops that iterate through every coordinate in this graph. `y` goes from `20` to `1` and x goes from `-30` to `30`. For every `x`, we check if `abs(10-abs(x))` equals `y` by doing `abs(10-abs(x))-y` in a ternary. If they are equal, this yields `0`, a falsey value in C, otherwise it will evaluate to some positive value. Then in the ternary `abs(10-abs(x))-y?"|":"~"`, we `printf` accordingly. And after each line, we output a newline using `puts("")`, and that is how the function outputs with a trailing newline. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~16~~ 15 bytes -1 byte thanks to notjagan ``` ↘×~²⁰↗↗×~χ‖OUB| ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R24zD0@sObXrUuOFR23QgAvLOtz9qmPZ@z/r3e7a@37Oo5v9/AA "Charcoal – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~70~~ 67 bytes 3 bytes thanks to Giuseppe. ``` write(c("|","~")[outer(abs(10-abs(-30:30)),20:1,"==")+1],"",61,,"") ``` [Try it online!](https://tio.run/##K/r/v7wosyRVI1lDqUZJR6lOSTM6v7QktUgjMalYw9BAF0TpGhtYGRtoauoYGVgZ6ijZ2ippahvG6igp6ZgZ6gApzf//AQ "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 16 bytes ``` ⁵×3ŒRAạ=þḤṚị⁾~|Y ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//4oG1w5czxZJSQeG6oT3DvuG4pOG5muG7i@KBvn58Wf// "Jelly – Try It Online") ``` ⁵×3ŒRAạ=þḤṚị⁾~|Y Main link. No arguments. ⁵ Set the argument and the return value to 10. ×3 Multiply by 3 to yield 30. ŒR Balanced range; yield [-30, -29, ..., 29, 30]. A Take absolute values. ạ Take absolute differences with 10. Ḥ Unhalve; yield 20. =þ Table equals; compare each result with each k in [1, ..., 20]. Ṛ Reverse the resulting 2D array. ị⁾~| Index into "~|", yielding '~' for 1 and '|' for 0. Y Separate by linefeeds. ``` [Answer] # Python 2.7, ~~163~~ ~~138~~ ~~135~~ ~~133~~ ~~113~~ 91 bytes ``` l,t=S='|~' for s in range(20):a=[l]*61;a[s]=a[60-s]=t;a[40-s]=a[20+s]=S[s>9];print`a`[2::5] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P0enxDbYVr2mTp0rLb9IoVghM0@hKDEvPVXDyEDTKtE2OidWy8zQOjG6ONY2MdrMQBdIlwC5JmBWYrSRgTaQDo4utrOMtS4oyswrSUhMiDaysjKN/f8fAA) Edit 1: -25 bytes: changed the algorithm after I felt a bit ambitious. :P Edit 2: -3 bytes: courtesy [Felipe Nardi Batista](https://codegolf.stackexchange.com/users/66418/felipe-nardi-batista) Edit 3: -2 bytes: courtesy [shooqie](https://codegolf.stackexchange.com/users/51530/shooqie) Edit 4: -20 bytes: courtesy [notjagan](https://codegolf.stackexchange.com/users/63641/notjagan) Edit 5: -22 bytes: courtesy [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) [Answer] # [///](https://esolangs.org/wiki////), 231 bytes ``` /3/|~//2/\/\///1/!!20/| 2-/&#2,/|#2'/"""2&/||2%/1|2#/&~2"/1!2!/&&|/~'%, 3'1#0#'1~& ,'!,&0-'!3&& !~'-! !3'#!0!#'~!& !,""%#!&0!-""%~!&& 1~"-"-1 %~"#3"#% 1#"~,"~%0%#%#!~%#%& %,%~!#%~%&0"~!-!-!-" "3!#%~!#"0"#!~%#!~"& ",,"~,"&0"-3"#3"&& ``` [Try it online!](https://tio.run/##HYwxrgMxCER7bsEgcIOFja/zmxSRUqTb1uLqG@/XSGj09Jjr@7o@7@u@Y8WuiIy/k4gZzDliU/YwSY8t2QJAWuydGnOnhFUiJieH2Y5q6rTalCFtlpE3dhu98TIjrtaZeDXhwdKKD3JAhW1wP@UQo1no6JO0IAuiNAXlKB0qR61zjdSPLFpqA8X9CQjrQSwY@Pe4YAT35/14fT2DZvf9Aw "/// – Try It Online") Or, view it interactively [here](http://conorobrien-foxx.github.io/slashes.html?JTJGMyUyRiU3Q34lMkYlMkYyJTJGJTVDJTJGJTVDJTJGJTJGJTJGMSUyRiEhMjAlMkYlN0MlMEEyLSUyRiUyNiUyMzIlMkMlMkYlN0MlMjMyJyUyRiUyMiUyMiUyMjIlMjYlMkYlN0MlN0MyJTI1JTJGMSU3QzIlMjMlMkYlMjZ+MiUyMiUyRjEhMiElMkYlMjYlMjYlN0MlMkZ+JyUyNSUyQyUwQTMnMSUyMzAlMjMnMX4lMjYlMEElMkMnISUyQyUyNjAtJyEzJTI2JTI2JTBBIX4nLSElMEEhMyclMjMhMCElMjMnfiElMjYlMEEhJTJDJTIyJTIyJTI1JTIzISUyNjAhLSUyMiUyMiUyNX4hJTI2JTI2JTBBMX4lMjItJTIyLTElMEElMjV+JTIyJTIzMyUyMiUyMyUyNSUwQTElMjMlMjJ+JTJDJTIyfiUyNTAlMjUlMjMlMjUlMjMhfiUyNSUyMyUyNSUyNiUwQSUyNSUyQyUyNX4hJTIzJTI1fiUyNSUyNjAlMjJ+IS0hLSEtJTIyJTBBJTIyMyElMjMlMjV+ISUyMyUyMjAlMjIlMjMhfiUyNSUyMyF+JTIyJTI2JTBBJTIyJTJDJTJDJTIyfiUyQyUyMiUyNjAlMjItMyUyMiUyMzMlMjIlMjYlMjY=)! [Answer] # [WendyScript](http://felixguo.me/wendy/), 65 bytes (exclude newline) ``` <<a=>(x)?x<0/>-x:/>x #y:20->0{#x:-30->31?a(10-a(x))==y@"~":@"|"""} ``` [Try it online!](http://felixguo.me/#wendyScript) Follows the same principle as the C answer given above. The first line is the `abs` function, second line runs two for loops and outputs `~` or `|` based on the graph. The last `""` is used to output a newline after each loop on `y`. [Answer] # Vim, 59 Bytes ``` 2i~^[59i|^[qqYpi|^[f~l2xA|^[q18@q11G31|qqr~jlq9@qF~2lqqr~klq8@q ``` Where `^[` is the `<ESC>` key [Answer] # [Japt](https://github.com/ETHproductions/japt), 32 bytes ``` 20ç| AÆhX'~ VméA VpWUVmw)c ê z · ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=MjDnfApBxmhYJ34KVm3pQQpWcFdVVm13KWMg6iB6ILc=&input=) Be sure to expand the output box. ## Explanation ``` 20ç| ``` Set `U` to `|` repeated 20 times. ``` AÆhX'~ ``` Set `V` to the range `[0,9]` (`AÆ`) mapped by: `U` (implicit) with the character at index `X` (current value) set to (`h`) `~`. ``` VméA ``` Set `W` to `V` with each line rotated 10 (`A`) chars right. ``` VpWUVmw ``` Create array: `V, W, U`, and `V` with each line reversed (`w`). This is now the left half of the shape, rotated 90° left. ``` c ê z · ``` Flatten the array (`c`), palendromize it (`ê`), rotate 90° right (`z`), and join with newlines (`·`). [Answer] # [Paintbrush](https://github.com/alexander-liao/paintbrush), 36 bytes ### non-competing ``` b|20{s~>v}10{>^s~}9{>vs~}>v20{>^s~}▁ ``` ## Explanation ``` b|20{s~>v}10{>^s~}9{>vs~}>v20{>^s~}▁ Program b| Sets the background character to `|` 20{ } Executes function 20 times s~ Sets the current character to `~` >v Moves one space right and one space down 10{ } Executes function 10 times >^ Moves one space right and one space up s~ Sets the current character to `~` 9{ } Executes function 9 times >v Moves one space right and one space down s~ Sets the current character to `~` >v Moves one space right and one space down 20{ } Executes function 20 times >^ Moves one space right and one space up s~ Sets the current character to `~` ▁ Cuts off the last line (because it pads an extra line when the pointer moves near the edge) ``` This reminds me, I need to add a mirror operation. [Answer] # **[Octave](https://octave-online.net/%20%22Octave%20Online), ~~157~~ ~~57~~ 54 bytes** Golfed it further down, thanks to the other answers and the comments. ``` a=zeros(20,61);for i=-30:30;a(21-abs(10-abs(i)),i+31)=2;end a=char(a+124) ``` I just approached it like the other answer with the abs(10-abs(x)) function and then used the right ASCII characters to print out the image. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 bytes ``` j_t.tm+*\|aTa30d\~61\| ``` [Try it online!](http://pyth.herokuapp.com/?code=j_t.tm%2B%2a%5C%7CaTa30d%5C~61%5C%7C&debug=0) [Answer] # [V](https://github.com/DJMcMayhem/V), 30 bytes ``` i~³°|19ñÙé|$xñ22|òr~klòÎæ$0Px ``` [Try it online!](https://tio.run/##AS0A0v92//9pfsKzwrB8GzE5w7HDmcOpfCR4w7EyMnzDsnJ@a2zDssOOw6YkMFB4//8 "V – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` 61Rạ31ạ⁵Ṭ€z0Ṛị⁾~|Y ``` [Try it online!](https://tio.run/##y0rNyan8/9/MMOjhroXGhkDiUePWhzvXPGpaU2XwcOesh7u7HzXuq6uJ/P8fAA "Jelly – Try It Online") [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 90 bytes ``` 00000000: 9dcb a10d 0040 08c5 50cf cc4d 673f 85ab [[email protected]](/cdn-cgi/l/email-protection)?.. 00000010: b880 22fd 7972 3f07 ef98 e1cc 85e1 ca05 ..".yr?......... 00000020: 8623 97d5 78c2 abf1 8457 e305 b31a 0f78 .#..x....W.....x 00000030: f507 0fcc 54fc 6ed3 794b b6d2 c1ed 163a ....T.n.yK.....: 00000040: b8dd 42c7 68b7 d031 f757 3ab8 dd42 07b7 ..B.h..1.W:..B.. 00000050: 5be8 e076 0b1d dcaf 060f [..v...... ``` [Try it online!](https://tio.run/##XdC9TgMxEATgnqcYQb9a//uuCaJFSBRIKahsrx0KoEAKSp7@2EsuDVNZsvZbj@ux1s9@OH4tC2@ZMUmrKIYFzJ7BuQUEbgOteUFMbiCHUgFa80j0SvRy2BHdXQWjRs2ZYe0QpClZuMEJfUwZ3bSm492gFQ6rcU/nnx3dshlWjRytw5QkIOVmUeowyD4o5HSyOlPAI2U1HohO6/D@Qpw2w6kxgi7moTuDHw2xi9MX@YoaxaKZLjDRlWuXN/qm8/PFmDfDX7qIwNuWEHNNEHYGI@k7XKkZIt6Ck16o8UQfRIb283q8dQlqhNq1O6cIrkYgrQxw5IH/eSf6vf7EsvwB "Bubblegum – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 22 bytes ``` I{S╒xñ♂-±Iï--mÆ┬û|~§yp ``` [Try it online!](https://tio.run/##AS4A0f9tYXRoZ29sZv//SXtT4pWSeMOx4pmCLcKxScOvLS1tw4bilKzDu3x@wqd5cP// "MathGolf – Try It Online") ## Explanation It's probably possible to golf away 2-3 bytes from this, I'll see what I can do. ``` I push 20 { start block or arbitrary length S push 30 ╒ range(1,n+1) x reverse int/array/string ñ pop(a), push palindromize(a) string/list/number ♂ push 10 - pop a, b : push(a-b) ± absolute value I push 20 ï index of current loop, or length of last loop - pop a, b : push(a-b) - pop a, b : push(a-b) m explicit map Æ start block of length 5 ┬ check if equal to 0 û|~ string "|~" § get from array/string y join array without separator to string or number p print with newline ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 75 bytes ``` f(x){for(x=1240;--x;)putchar(x%62?x/62+1-abs(10-abs(x%62-31))?124:126:10);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No0KzOi2/SKPC1tDIxMBaV7fCWrOgtCQ5IxEopmpmZF@hb2akbaibmFSsYWgApkDCusaGmpr2QC1WhkZmVoYGmta1/3MTM/M0gKZpgDgA "C (gcc) – Try It Online") Totally changed from Cows quack's answer [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 20F„|~20Ýû31∍ûNQèJ, ``` [Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//zIwRuKAnnx@MjDDncO7MzHiiI3Du05Rw6hKLP//) **Explanation:** ``` 20F # Loop 20 times: „|~ # Push the string "|~" 20Ý # List of range [0,20] û # Palindromize [0..20..0] 31∍ # Shorten to length 31 [0..20..10] û # Palindromize again [0..20..10..20..0] NQ # Check if the loop index is equal to it è # And index it into the string J # Then join the list of characters together , # And print with trailing newline ``` `20Ýû31∍û` generates the list: ``` [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,19,18,17,16,15,14,13,12,11,10,11,12,13,14,15,16,17,18,19,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0] ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 64 bytes ``` 0..19|%{$y=$_ -join(0..20+19..10+11..19+20..0|%{'|~'[$_-eq$y]})} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz9CyRrVapdJWJZ5LNys/M08DKGZkoG1oCZQCUoYgFdpGQEEDoDr1mjr1aJV43dRClcrYWs3a//8B "PowerShell – Try It Online") The four-part diagram with a linear function `y=x` [Answer] # [Positron](https://github.com/alexander-liao/positron), 165 bytes ``` i=0;while(i<20)do{k='|'*(59-2*i);if(i==10)then{j='|'*19;k=j+'~'+j;};if(i>10)then{q=39-2*i;j='|'*q;q=2*i-21;k=j+'~'+'|'*q+'~'+j;}print@('|'*i+'~'+k+'~'+'|'*i);i=i+1;} ``` [Try it online!](https://tio.run/##PY1BDsIgEEWPA5Q0AYyLZhzjYazpgIFSSbqo9epox7TLef@9zJheVKYUayU0MA/07CVdnFH3tAQUb9HIc9e6hhTQQxKiNaoMfVw8j7aDgF6Lj9AeVlauu5HxxCX81QwZf1fr7JEw3uNxolhucmPELBzO9hxJW1hr/QI "Positron – Try It Online") I think Positron has too many bugs in it. I should get it updated to TIO because then `++` will actually work. [Answer] ## Mathematica, ~~78~~ 75 bytes ``` Print[""<>Riffle[Array[If[#+Abs[10-Abs[31-#2]]==21,"~","|"]&,{20,61}],"\n"]] ``` except the `\n` is replaced by an actual newline. [Try it online!](https://tio.run/##y00sychMLv7/P6AoM68kWknJxi4oMy0tJzXasagosTLaMy1aWdsxqTjayFDXNzMvWtlIx8xIV9koNtbW1shQR6lOSUepRilWTafayEDHzLA2VkeJSyk29v9/AA "Mathics – Try It Online") (There are extra spaces at the starts of the lines in Mathics for some reason, but [it works fine in Mathematica](https://sandbox.open.wolframcloud.com/).) I came up with a submission of my own, but then [Kritixi Lithos](https://codegolf.stackexchange.com/a/131918/66104) added an explanation of theirs and it was quite similar to mine but using a slightly cleverer formula, so now this is just a port of that answer. (Go and read that one and upvote it!) [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 93 bytes ``` 00000000: 9dcb 390e 4301 10c2 d09e 335b 9c3d 5d56 ..9.C.....3[.=]V 00000010: e72f 4c35 327a 65bf 86ee 9830 f342 5879 ./L52ze....0.BXy 00000020: 8130 f202 848d 9797 a613 262c bc7c 6a3a .0........&,.|j: 00000030: 60c2 552e 9858 bcdc a2f9 55ac 9916 5e6f `.U..X....U...^o 00000040: a285 d79b 6819 eb4d b4cc fe99 165e 6fa2 ....h..M.....^o. 00000050: 85d7 9b68 e1d5 26da 782f 3578 00 ...h..&.x/5x. ``` [Try it online!](https://tio.run/##NdC7SkQxEAbg3qf4KyuZzW2SzIKNtloqC@JiroooWy2s4rsfE/f4N4Ew@TIz@ZjzR3s9fi6LWrOF1JJhRTU4qzS0KgZVSYO1nCHFVnBlDxAJ3dKMfaLr58eLs6CH0YLpcMUyrAkJnnNH9K1BolXo1hlwDDKMzR2b7zYRRTe7r9Uww4h6lhplEF2skCAByWsL401BLqHAJ5uGoWjN5RX9vG9Xww7Dz@aZzfyY43hUC5LpMu5SgYj24OY78EIPRLtpjJP2h9Vww0gmMmqQDB@1oGVXkV0p6E0E2nOD78nMfRC9Ed3/tbI/0GrwnIVrgGQf0XTlMUFNCHHsyHKIUAr/OROXdNrwiZblFw "Bubblegum – Try It Online") [Answer] # JavaScript (ES6), 87 bytes ``` for(a=Math.abs,y=20;y--;console.log(s))for(s='',x=-30;x<31;x++)s+=a(10-a(x))+~y?'|':'~' ``` [Answer] ## Lua, 193 bytes ``` m={}function g(x,y)if(x<62)then m[x+y*61]="~"if(x==31or x==21or x==41)then b=not b end g(x+1,y+((b and-1)or 1))end end g(1,0)for y=0,19 do s=""for x=1,61 do s=s..(m[x+y*61]or"|")end print(s)end ``` Note that Lua cannot print something out without creating a new line. For this reason, I have to break one of the rules. Minimally minified to a large extent: ``` map={} o=20 p=61 --b is true means go up function bounce(x,y,c) if (x~=p)then map[x+y*p]=c if(x==31 or x==21 or x==41)then b=not b end bounce(x+1,y+((b and -1) or 1),c) end end bounce(1,0,"~") --map[2+60] = "h" for y=0,o-1 do str = "" for x=1,p do str = str..(map[x+y*p] or "|") end print(str) end ``` Some changes where made during minification, all of which makes the program less extendable but smaller. Try it: <https://tio.run/##PY7LCoMwEEX3@YqQVVJTcWwRCp0vKV1oNa1QJ0UjGPr49TRq6eoO91wOcx/LEDp8vs1IF9da4lc5aa9aI6djkSt3a4h1pynxmwLOKD5iJog7sD2Pmf9yD@u0QrKOV6yhmkVTAtonUla8pHoLKm5BqZmtHHSmTCw9ZhoOvLZsQCHMogRdwNoMaSr/L9hevMSiePQtOTnMdwhf> I'm not sure if anyone has done this before, but I tried minifying by loading the program as a string and using gsub(search/replace). Unfortainitly, it made the program bigger. However, if this program was big enough, it would yield in less bytes. ``` g=string.gsub loadstring(g(g(g('m={}function g(x,y)if(x<62vm[x+y*61]="~"if(x==31zx==21zx==41vb=not beg(x+1,y+((b and-1)z1))eeg(1,0)fzy=0,19 do s=""fzx=1,61 do s=s..(m[x+y*61]z"|")eprint(s)e','e',' end '),'v',')then '),'z','or '))() ``` Due to its relative closeness with the real result(240 bytes, only 41 more), I figured I'd post it. If this program where 350+ bytes, there would have likely been a reduction. [Answer] # Java 8, 113 bytes ``` v->{String r="";for(int i=-1,j;++i<20;r+="\n")for(j=61;j-->0;)r+=j==i|j+i==60|i>9&(j-i==20|j+i==40)?"~":"|";return r;} ``` I have the feeling the checks (`j==i|j+i==60|i>9&(j-i==20|j+i==40)` can definitely be golfed by somehow combining multiple checks into one. **Explanation:** [Try it here.](https://tio.run/##LY9BS8QwEIXv/oohB0moKdlFFjSm/gL3InhRDzGblYndtKRpQbb1r9cpLcwc3nvD8L1gByub1sdw@pldbbsOXizG6w0AxuzT2ToPx0UCvOaE8Rscf2vwBIPQ5E60NF22GR0cIYKBeZDVdTtOhjF9bhKnb4BG7u6CLgp82iudCsM@IhNLGsxhp4OUldKC/GAMjqFAYw5qxOrhlgdJYq9W816JZ/bHHtnIdPK5TxGSnma9srT9V00sG9KwsF6oEl@J3j/Biq3Pb5f9pWz6XLYUZR5Lx2Nf12KrNs3/) ``` v->{ // Method with empty unused parameters and String return-type String r=""; // Result-String for(int i=-1,j; // Index integers ++i<20; // Loop (1) from 0 to 20 (exclusive) r+="\n") // After every iteration: append a new-line to the result-String for(j=61; // Reset `j` to 61 j-->0;) // Inner loop (2) from 60 down to 0 (inclusive) r+= // Append the result-String with: j==i // If `j` and `i` are equal (top-right /), |j+i==60 // or `j` + `i` is 60 (top-left \), |i>9 // or we're at the bottom halve &(j-i==20 // and `j` - `i` is 20 (bottom left \), |j+i==40)? // or `j` + `i` is 40 (bottom right /) "~" // Append a literal "~" to the result-String : // Else: "|"; // Append a literal "|" to the result-String // End of inner loop (2) (implicit / single-line body) // End of loop (1) (implicit / single-line body) return r; // Return the result-String } // End of method ``` [Answer] # [Perl 5](https://www.perl.org/), 79 bytes ``` push@a,[('|')x61]for 1..21;map$a[20-abs 10-abs][$_+30]='~',-30..30;say@$_ for@a ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gtDjDIVEnWkO9Rl2zwswwNi2/SMFQT8/I0Do3sUAlMdrIQDcxqVjBEEzFRqvEaxsbxNqq16nr6Bob6OkZG1gXJ1Y6qMQrADU6JP7//y@/oCQzP6/4v66vqZ6BoQEA "Perl 5 – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 104 bytes ``` time {incr j set i 0 time {puts -nonewline [expr 21-abs(abs([incr i]-31)-10)-$j?"|":"~"]} 61 puts ""} 20 ``` [Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6My@5SCGLqzi1RCFTwYALIlhQWlKsoJuXn5danpOZl6oQnVpRUKRgZKibmFSsAcLRYG2ZsbrGhpq6hgaauipZ9ko1SlZKdUqxtQpmhlxgE5SUahWMDP7/BwA "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 105 bytes ``` time {incr j set i 0 time {puts -nonewline [expr $j==21-abs(abs([incr i]-31)-10)?"~":"|"]} 61 puts ""} 20 ``` [Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6My@5SCGLqzi1RCFTwYALIlhQWlKsoJuXn5danpOZl6oQnVpRUKSgkmVra2Som5hUrAHC0WCtmbG6xoaauoYGmvZKdUpWSjVKsbUKZoZcYCOUlGoVjAz@/wcA "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 109 bytes ``` time {incr j;set i 0;time {append s [expr $j==21-abs(abs([incr i]-31)-10)?"~":"|"]} 61;set s $s\n} 20 puts $s ``` [Try it online!](https://tio.run/##K0nO@f@/JDM3VaE6My@5SCHLuji1RCFTwcAaIphYUJCal6JQrBCdWlFQpKCSZWtrZKibmFSsAcLRYD2ZsbrGhpq6hgaa9kp1SlZKNUqxtQpmhmCTihVUimPyahWMDLgKSktAvP//AQ "Tcl – Try It Online") # Tcl, ~~143 133 123~~ 110 Still much ungolfed, but I will evolve it after: ``` time {incr j;set i 0;time {incr i;append s [expr $j==21-abs(abs($i-31)-10)?"~":"|"]} 61;set s $s\n} 20 puts $s ``` # [demo](http://rextester.com/VJZTA69769) [Answer] # [Python 3](https://docs.python.org/3/), 90 bytes 1 byte smaller than the other Python answer :) Outputs with a trailing newline. ``` for y in range(20):print(''.join('~'if 20-y==abs(10-abs(x))else'|'for x in range(-30,31))) ``` [Try it online!](https://tio.run/##RcyxCoAgEADQX3G7O8iw3II@xsDqIk7RBoXo142mpre9WK89iG1tDUlVxaKSk83jaGiKieVCgP4ILAgP8KpGo@s8uyXjYPRHIfJn9nDDN5R/0NZ0diCi1l4 "Python 3 – Try It Online") ]
[Question] [ # Task Write some code that can be rearranged into n different programs in n different languages each outputting a distinct number from 1 to n. No two languages should be the same however different versions of "the same language" will be considered distinct languages, as long as they have different major version numbers. For this challenge REPL environments are not distinct from their parent languages but are still a language. Each language should run on a distinct permutation of the source code and output a distinct number in the range. Permutations will be counted in bytes *not in characters*. You should include each permutation that is run with the language that it is run in for testing purposes. # Scoring Your score will be the [![Scoring equation](https://i.stack.imgur.com/V9WO5.png)](https://i.stack.imgur.com/V9WO5.png) Where N is the number of languages and L is the number of unique orderings of the programs bytes. ***L is not equal to the length of the program*** (unless the program is 1 or 0 bytes) [Here](https://tio.run/nexus/python2#jcwxCoQwEIXh3lMEqxlRl90yaL93WCzGOAEhO5FEQU8fU2jvaz/en6h39B8nUqKl@/igpCKQ5o2FvSVqAscCEfEVeNoMwyV7fei9OuofQWyN32QFg2hzxahZVOQ1nwZMS5gzWSi/7Jx/uBIxnQ) is a python script to calculate L courtesy of Conor O'Brien. L is equal to the length of the program factorial if and only if there are no repeated bytes in the program. The goal is to maximize your score. [Answer] # 34 Languages, 19 bytes, Score: 38,832,018,459,912,437,760,000 Here is a quick answer I threw together to show that it is possible to get an answer scoring better than 1. ``` 12233echo*+--@#..; ``` ## 1. NTFJ ``` #*22331+..@o;-- ech ``` This outputs via character code, which is allowed by [meta consensus](https://codegolf.meta.stackexchange.com/a/4719/56656). [Try it here](https://conorobrien-foxx.github.io/NTFJ/) ## 2. Tcsh ``` echo 2;#..1@2+33*-- ``` ## 3. 05AB1E ``` 2231*+..@echo ;--#3 ``` [Try it online!](https://tio.run/nexus/05ab1e#@29kZGyopa2n55CanJGvYK2rq2z8/z8A "05AB1E – TIO Nexus") ## 4. Actually ``` @..o; eho1#c3223-*+- ``` [Try it online!](https://tio.run/nexus/actually#@@@gp5dvrZCakW@onGxsZGSsq6Wt@/8/AA "Actually – TIO Nexus") ## 5. Befunge 98 ``` [[email protected]](/cdn-cgi/l/email-protection)*#3o;-- ech ``` [Try it online!](https://tio.run/nexus/befunge-98#@29krK3noGdkqKVsnG@tq6uQmpzx/z8A "Befunge-98 – TIO Nexus") ## 6. Cubix ``` 123+23*o@#;-- ech.. ``` *Outputs by character code* [Try it here](http://ethproductions.github.io/cubix/) Unfolded code: ``` 1 2 3 + 2 3 * o @ # ; - - e c h . . . . . . . . ``` ## 7. Haskell 8 REPL ``` 3+2*2 --31#;@..echo ``` ## 8. Seriously ``` @..o; eho1#c3223-+*- ``` [Try it online!](https://tio.run/nexus/seriously#@@@gp5dvrZCakW@onGxsZGSsq62l@/8/AA "Seriously – TIO Nexus") ## 9. ><> ``` 33*o;2+..@#12-- ech ``` *Outputs by character code* [Try it online!](https://tio.run/nexus/fish#@29srJVnbaStp@egbGikq6uQmpzx/z8A "><> – TIO Nexus") ## 10. Befunge ``` 33*1+.@.#22o;-- ech ``` [Try it online!](https://tio.run/nexus/befunge#@29srGWoreegp2xklG@tq6uQmpzx/z8A "Befunge – TIO Nexus") ## 11. brainbool ``` 323*+..@echo ;--#12 ``` [Try it online!](https://tio.run/nexus/brainbool#@29sZKylrafnkJqcka9graurbGj0/z8A "brainbool – TIO Nexus") ## 12. 2sable ``` 233*+..@echo ;--#12 ``` [Try it online!](https://tio.run/nexus/2sable#@29kbKylrafnkJqcka9graurbGj0/z8A "2sable – TIO Nexus") ## 13. Hexagony ``` 13;2#2+@*3o-- ech.. ``` *Outputs by character code* [Try it online!](https://tio.run/nexus/hexagony#@29orGikbKTtoGWcr6urkJqcoaf3/z8A "Hexagony – TIO Nexus") Unfolded code: ``` 1 3 ; 2 # 2 + @ * 3 o - - e c h . . . ``` ## 14. R ``` 12+2#*33..@o; ech ``` [Try it online!](https://tio.run/nexus/r#@29opG2krGVsrOeQb62rq5CanPH/PwA "R – TIO Nexus") ## 15. bc ``` 12+3#*23..@o;-- ech ``` ## 16. Python 3 REPL ``` 13+3#*22..@o;-- ech ``` ## 17. irb (Ruby 2.4 REPL) ``` 13+2*2#3..@o;-- ech ``` ## 18. PowerShell ``` 12+2*3#3..@o;-- ech ``` ## 19. Python 2 REPL ``` 13+2*3#2..@o;-- ech ``` ## 20. Python 1.6.1 REPL ``` 23-3#-+*21..@o; ech ``` ## 21. Ksh ``` echo 21;#..2@3+3*-- ``` ## 22. Bash ``` echo 22;#..1@3+3*-- ``` ## 23. Zsh ``` echo 23;#..1@2+3*-- ``` ## 24. Applescript ``` 23+1 --#2*3..@o;ech ``` ## 25. Lua REPL ``` 23+2 --#1*3..@o;ech ``` ## 26. Julia REPL ``` 23+3 #2*1..@o;--ech ``` ## 27. irb (Ruby 1.9.3 REPL) ``` 13*2+3-2 #..@o;-ech ``` ## 28. Haskell 7 REPL ``` 13*2+2--3#;@.. echo ``` ## 29. J ``` echo --1#.23;@+2*.3 ``` [Try it online!](https://tio.run/nexus/j#@5@anJGvoKtrqKxnZGztoG2kpWf8/z8A "J – TIO Nexus") ## 30. Nim ``` echo 33-2-1;#..@2+2* ``` ## 31. fish ``` echo 31;#3-2-..@2+2* ``` ## 32. PHP ``` echo 32;#+123*@..-- ``` `<?php` is not needed due to [this meta](https://codegolf.meta.stackexchange.com/questions/7098/is-the-php-opening-tag-mandatory-in-byte-count/7146#7146) [Try it online!](https://tio.run/nexus/php#@29jX5BRoJCanJGvYGxkraxtaGSs5aCnp6v7/z8A "PHP – TIO Nexus") ## 33. Golfscript ``` 3.#.1223*@+o;-- ech ``` [Try it online!](https://tio.run/nexus/golfscript#@2@sp6xnaGRkrOWgnW@tq6uQmpzx/z8A "GolfScript – TIO Nexus") ## 34. Octave ``` 33+1 #22echo*--@..; ``` [Try it online!](https://tio.run/nexus/octave#@29srG2ooGxklJqcka@lq@ugp2f9/z8A "Octave – TIO Nexus") [Answer] # 1 language, 0 bytes, score 1 I don't know how high scores will get in this challenge, so let's take this spot. ``` ``` [Try it online!](https://tio.run/nexus/retina) In Retina, the empty program with no input prints `1`. Score = 1!/0! = 1/1 = 1 [Answer] ## 2 languages, 2 bytes, score 1 Doesn't beat Leo's answer, but I thought I'd present a 2-language solution (well, and Wheat Wizard ninja'd a score-2 answer in between anyway). ### [Retina](https://github.com/m-ender/retina), prints `1` ``` 2` ``` [Try it online!](https://tio.run/nexus/retina#@2@U8P8/AA "Retina – TIO Nexus") This is essentially the same as Leo's empty program. ### [Pyth](https://github.com/isaacg1/pyth), prints `2` ``` `2 ``` [Try it online!](https://tio.run/nexus/pyth#@59g9P8/AA "Pyth – TIO Nexus") This is `repr(2)` so it computes `"2"` which gets printed as `2`. [Answer] # 26 languages, 46 bytes, Score : 1.68861953e-28 (0.000000000000000000000000000168861953) All the languages are mainstream ones (i.e. they are actually used by people in development) and there's no REPL solution in any language. This answer is never going to win, but that's not a reason for not posting it... ``` //#**print()ale123456789+chous :f{}:""enttd *; ``` --- ## 1. Python 2 ``` print 1#//**()alechous:f{}:23456789+ ""enttd*; ``` [Try it online!](https://tio.run/nexus/python2#@19QlJlXomCorK@vpaWhmZiTmpyRX1pslVZda2VkbGJqZm5hqa2gpJSaV1KSomX9/z8A "Python 2 – TIO Nexus") ## 2. Python 3 ``` print(2)#//**alechous13456789+: f{}: ""enttd*; ``` [Try it online!](https://tio.run/nexus/python3#@19QlJlXomGkqayvr6WVmJOanJFfWmxobGJqZm5hqW2lkFZda6WgpJSaV1KSomX9/z8A "Python 3 – TIO Nexus") ## 3. Ruby ``` puts 3#//**()alecho:f12456789+{}rin: ""enttd*; ``` [Try it online!](https://tio.run/nexus/ruby#@19QWlKsYKysr6@lpaGZmJOanJFvlWZoZGJqZm5hqV1dW5SZZ6WgpJSaV1KSomX9/z8A "Ruby – TIO Nexus") ## 4. CoffeeScript ``` alert 4#//**()pinchous:12356789+f{}: ""enttd*; ``` [Try it online!](https://jsfiddle.net/MangaCoder/n77t31fv/) ## 5. PHP ``` echo 5/*alrt#()pinus:f{:12346789+} ""enttd;**/ ``` [Try it online!](https://tio.run/nexus/php#@29jX5BRoJCanJGvYKqvlZhTVKKsoVmQmVdabJVWbWVoZGxiZm5hqV2roKSUmldSkmKtpaWvYG/3/z8A "PHP – TIO Nexus") ## 6. Perl 5 ``` print 6#/*ale()chous:12345789+f{:} */""enttd*; ``` [Try it online!](https://tio.run/nexus/perl5#@19QlJlXomCmrK@VmJOqoZmckV9abGVoZGxiam5hqZ1WbVWroKWvpJSaV1KSomX9/z8A "Perl 5 – TIO Nexus") ## 7. Perl 6 ``` print 7#/*ale)(chous:f12345689+{:} */""enttd*; ``` [Try it online!](https://tio.run/nexus/perl6#@19QlJlXomCurK@VmJOqqZGckV9abJVmaGRsYmpmYaldbVWroKWvpJSaV1KSomX9/z8A "Perl 6 – TIO Nexus") ## 8. JavaScript (ES5) ``` alert(8)//pin 12345679+#*chous:f{:} *""enttd*; ``` [Try it online!](https://jsfiddle.net/MangaCoder/zunpgLjf/) ## 9. JavaScript (ES6) ``` alert(9)//inp 12345678+#*chous: f{:}*""enttd*; ``` [Try it online!](https://jsfiddle.net/MangaCoder/chnrvp6a/) ## 10. JavaScript (ES7) ``` alert(9+1)//pni #*chous2345678: f{:}*""enttd*; ``` [Try it online!](https://jsfiddle.net/MangaCoder/1y9a4t96/) ## 11. Batch ``` echo 9+2 ::alrt()//pni#*usf{1345678}*""enttd*; ``` *Couldn't find an online interpreter for this one. Try running this code in the Command Prompt, if you are on Windows.* ## 12. Bash ``` echo 12 #::alrt(3456789+)//pni*usf{}*""enttd*; ``` [Try it online!](https://tio.run/nexus/bash#@5@anJGvYGikoGxllZhTVKJhbGJqZm5hqa2pr1@Ql6lVWpxWXaulpJSaV1KSomX9/z8A "Bash – TIO Nexus") ## 13. CSS ``` *:after{content:"13" /*h# l(2456789+)pisud;*/} ``` [Try it online!](https://jsfiddle.net/MangaCoder/x0p433tw/) ## 14. Less ``` *:after{content:"14" /*#h l(2356789+)pisud;*/} ``` [Try it online!](http://jsbin.com/bevecu/edit?output) ## 15. Stylus ``` *:after{content:"15" /*#hl (2346789+)pisud;*/} ``` [Try it online!](http://jsbin.com/nukedid/edit?output) ## 16. TypeScript ``` alert(16)//inp #*chous2345789+: :{f}*""entt*d; ``` [Try it online!](https://jsfiddle.net/MangaCoder/w5cv3og7/) ## 17. Octave ``` disp(17)#//n *chou2345689+: :{f}*""entt*alert; ``` [Try it online!](https://tio.run/nexus/octave#@5@SWVygYWiuqayvn6eglZyRX2pkbGJqZmGpbaVgVZ1Wq6WklJpXUqKVmJNaVGL9/z8A "Octave – TIO Nexus") ## 18. Swift ``` print(18)//ds# *chou2345679+: :{f}""ent*ale*t; ``` [Try it online!](http://swift.sandbox.bluemix.net/#/repl/59140de7cfa69e773dc97e38) ## 19. Julia ``` print(19)#ds// *chou2345678+: :{f}""ent*ale*t; ``` [Try it online!](https://tio.run/nexus/julia5#@19QlJlXomFoqamcUqyvr6CVnJFfamRsYmpmbqFtpWBVnVarpJSaV6KVmJOqVWL9/z8A "Julia 0.5 – TIO Nexus") ## 20. Maxima ``` print(18+2);/*#ds ouch 345679::{f}""entale*t*/ ``` [Try it online!](https://tio.run/nexus/maxima#@19QlJlXomFooW2kaa2vpZxSrJBfmpyhYGxiamZuaWVVnVarpJSaV5KYk6pVoqX//z8A "Maxima – TIO Nexus") ## 21. Clojure ``` (print "21");/*#ds ouch3456789+::{f}entale*t*/ ``` [Try it online!](https://tio.run/nexus/clojure#@69RUJSZV6KgZGSopGmtr6WcUqyQX5qcYWxiamZuYaltZVWdVpuaV5KYk6pVoqX//z8A "Clojure – TIO Nexus") ## 22. Groovy ``` print 19+3//();*#ds oh245678::{fuc*}entalet*"" ``` [Try it online!](https://tio.run/nexus/groovy#@19QlJlXomBoqW2sr6@haa2lnFKskJ9hZGJqZm5hZVWdVpqsVZuaV5KYk1qipaT0/z8A "Groovy – TIO Nexus") ## 23. CommonLisp ``` (print 23);//*#ds oh1456789+::{fuc*}entalet*"" ``` [Try it online!](https://tio.run/nexus/clisp#@69RUJSZV6JgZKxpra@vpZxSrJCfYWhiamZuYaltZVWdVpqsVZuaV5KYk1qipaT0/z8A "Common Lisp – TIO Nexus") ## 24. EmacsLisp ``` (print 24);//*#ds oh1356789+::{fuc*}entalet*"" ``` [Try it online!](https://tio.run/nexus/emacs-lisp#@69RUJSZV6JgZKJpra@vpZxSrJCfYWhiamZuYaltZVWdVpqsVZuaV5KYk1qipaT0/z8A "Emacs Lisp – TIO Nexus") ## 25. PicoLisp ``` (print 25);//*#ds oh1346789+::{fuc*}entalet*"" ``` [Try it online!](https://tio.run/nexus/picolisp#@69RUJSZV6JgZKppra@vpZxSrJCfYWhsYmZuYaltZVWdVpqsVZuaV5KYk1qipaT0/z8A "PicoLisp – TIO Nexus") ## 26. Logo ``` print 21+5 ;//*#dsoh346789::{fuc*}entalet*""() ``` [Try it online!](http://www.calormen.com/jslogo/) [Answer] ## 12 Languages, 16 Bytes - Score: 0.003 ``` print(0b11000)#1 ``` Prints `1` in **2sable** ``` print(0b1100)#10 ``` Print `10` in **05AB1E** ``` print(0b11)#1000 ``` Re-arranging the binary numbers prints 2-9, 11-12 in: * Crystal * Julia 0.5 * J-uby * Lily * Perl 5 * Perl 6 * Python 3 * Python 2 * Python * Ruby L=145297152000 12! = 479001600 I just used TiO for a list of valid languages for this (If these are all considered unique?). Removed some duplicate languages thanks to input from Wheat Wizard. This answer is looking pretty low, though I feel it has potential. [Answer] # JavaScript (ES6), Python 2, Python 3, Japt, 4.735e-15 ``` # ()//1234=>inprt ``` ## ES6 (1) ``` p=>1//rint 234()# ``` ## Python 2 (2) ``` print 2#134=>//() ``` ## Python 3 (3) ``` print(3)# 124=>// ``` ## Japt (4) ``` #rint>=3/2)p (4/1 ``` ]
[Question] [ **Input:** A positive integer ***n*** which is `1 <= n <= 25000`. **Output:** 1. In this sequence we start with the decimal number 1/***n***. 2. Then we take the sum of digits up until the ***n***'th digit after the comma (1-indexed); followed by the sum of digits up until the (***n***-1)'th, then (***n***-2)'th, etc. Continue until ***n*** is 1. 3. **The output** is the sum of all these combined. **For example:** ``` n = 7 1/7 = 0.1428571428... 7th digit-sum = 1+4+2+8+5+7+1 = 28 6th digit-sum = 1+4+2+8+5+7 = 27 5th digit-sum = 1+4+2+8+5 = 20 4th digit-sum = 1+4+2+8 = 15 3rd digit-sum = 1+4+2 = 7 2nd digit-sum = 1+4 = 5 1st digit = 1 Output = 28+27+20+15+7+5+1 = 103 ``` **Challenge rules:** * If the decimal of 1/***n*** doesn't have ***n*** digits after the comma, the missing ones will be counted as 0 (i.e. `1/2 = 0.50 => (5+0) + (5) = 10`). * You take the digits without rounding (i.e. the digits of `1/6` are `166666` and not `166667`) **General rules:** * [Standard rules apply](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. **First 1 - 50 in the sequence:** ``` 0, 10, 18, 23, 10, 96, 103, 52, 45, 10, 270, 253, 402, 403, 630, 183, 660, 765, 819, 95, 975, 1034, 1221, 1500, 96, 1479, 1197, 1658, 1953, 1305, 1674, 321, 816, 2490, 2704, 4235, 2022, 3242, 2295, 268, 2944, 3787, 3874, 4097, 1980, 4380, 4968, 3424, 4854, 98 ``` **Last 24990 - 25000 in the sequence:** ``` 1405098782, 1417995426, 1364392256, 1404501980, 1408005544, 1377273489, 1395684561, 1405849947, 1406216741, 1142066735, 99984 ``` [Answer] ## Mathematica, 42 bytes ``` #&@@RealDigits[1/#,10,#,-1].(#-Range@#+1)& ``` or ``` #&@@RealDigits[1/#,10,#,-1].Range[#,1,-1]& ``` or ``` Tr@Accumulate@#&@@RealDigits[1/#,10,#,-1]& ``` ### Explanation Take the example from the challenge spec. We want to compute: ``` 1+4+2+8+5+7+1 + 1+4+2+8+5+7 + 1+4+2+8+5 + 1+4+2+8 + 1+4+2 + 1+4 + 1 ``` Rearranging, this is: ``` 1*7 + 4*6 + 2*5 + 8*4 + 5*3 + 7*2 + 1*1 = (1, 4, 2, 8, 5, 7, 1) . (7, 6, 5, 4, 3, 2, 1) ``` where `.` is the scalar product of two vectors. That's pretty much all the solution does. ``` #&@@RealDigits[1/#,10,#,-1] ``` This gets us the first `N` decimal digits of `1/N` (the `#&@@` extracts the first element of the `RealDigits` result because that also returns the offset of the first digit which we don't care about). Then we get the list from `N` down to `1` either using `(#-Range@#+1)` or `Range[#,1,-1]`, both of which are shorter than `Reverse@Range@#`, and take the scalar product. The alternative solution instead uses `Accumulate` to compute a list of all prefix sums and then adds up those prefix sums with `Tr`. Since this is really fast even for large inputs, here is a scatter plot of the sequence up to `N = 100,000` (doing *all* of them and plotting them took a while though): [![enter image description here](https://i.stack.imgur.com/ao62q.png)](https://i.stack.imgur.com/ao62q.png) Click for larger version. The blue line is the naive upper bound of `9 N (N+1) / 2` (if all the decimal digits were `9`) and the orange line is exactly half of that. Unsurprisingly this is right inside the main branch of the plot since, statistically, we'd expect the average digit to be 4.5. The thin line of plot points which you can see below the main branch are fractions which end in `...3333...`, as they all lie very close to `3 N (N+1) / 2`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` R⁵*:%⁵+\S ``` Rather slow, but short. [Try it online!](http://jelly.tryitonline.net/#code=UuKBtSo6JeKBtStcUw&input=&args=Nw&debug=on) or [verify the first 50 test cases](http://jelly.tryitonline.net/#code=UuKBtSo6JeKBtStcUwo1MFLCtcW8w4figqxH&input=). ### How it works ``` R⁵*:%⁵+\S Main link. Argument: n R Range; yield [1, ..., n]. ⁵* 10 power; yield [10**1, ..., 10**n]. : Divide each power by n. %⁵ Take each quotient modulo 10. This yields all desired decimal digits. +\ Take the cumulative sum of the digits. S Take the sum. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes ``` Di<ë°¹÷.pSO ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RGk8w6vCsMK5w7cucFNP&input=NDk) or a [Test suite](http://05ab1e.tryitonline.net/#code=NTBMdnlEaTwsw6vCsHnDty5wU08s&input=NDk) for the first 50 numbers. **Explanation** ``` # implicit input n Di< # if n == 1 then 0 ë # else °¹÷ # 10^n // n .p # get prefixes SO # sum digits ``` **A more efficient version for trying big numbers on TIO** The difference to the shorter version is that here we sum the product of the digits and the reversal of their 1-based index instead of summing digits in prefixes. ``` Di<ë°¹÷SDgLR*O ``` [Try it online!](http://05ab1e.tryitonline.net/#code=RGk8w6vCsMK5w7dTRGdMUipP&input=MjQ5OTk) [Answer] # Java 8, ~~181~~ ~~169~~ ~~166~~ ~~153~~ 142 bytes ``` import java.math.*;n->{int m=n+2,r=0,i;for(;m>2;)for(i=m--;i-->2;r+=(BigDecimal.ONE.divide(new BigDecimal(n),n,3)+"").charAt(i)-48);return r;} ``` **Explanation:** [Try it here.](https://tio.run/##RZBNT8MwDIbv/RVWTwltsjFAQoROAsGRgbQjcMjabPNo3Cp1hya0317SMYmDP/LakR6/O7u3qmkd7aqvAX3bBIZd1LS3vNUXBgAmE3izUW7WwFsHqwM7VTY9cZKUte06eLFIPwkAEruwtqWDxfg8CVCKMZM0UTkmMXVsGUtYAEEBA6n5z7jgC8pmeSimOZp1E4Tx85mRY4eFV8qgUlEIWSEecfPkSvS21q@LZ13hHisnyH3D/0SQzCm/klmaSl1ubXhggVJd30oTHPeBIJjjYEactl/VEedMtW@wAh/vEUsOSJv3T7Dy75gTSyTFiH1pYrkv4GYamyw7bwAsDx07r5uedRu/c00CIYP07oPTWElHN@TJitGMMY7DLw) ``` import java.math.*; // Required import for BigDecimal n->{ // Method with integer as both parameter and return-type int m=n+2, // Copy of the input-integer plus 2 r=0, // Result-integer, starting at 0 i; // Index-integer for(;m>2;) // Loop (1) as long as `m` is larger than 2 for(i=m--; // Set index `i` to `m`, and decrease `m` by one afterwards i-->2; // Inner loop (2) from `m` down to 2 (inclusive) r+= // Add to the result-sum: (BigDecimal.ONE.divide( // 1 divided by, new BigDecimal(n), // the input n,3) // With the minimal required precision +"") // Convert this to a String .charAt(i) // Take the character of this String at index `i` -48 // And convert it to a number ); // End of inner loop (2) // End of loop (1) (implicit / single-line body) return r; // Return result } // End of method ``` [Answer] # PHP, ~~66~~ 65 bytes ``` for($b=$c=$argv[$a=1];$c;)$o+=$c--*(($a=10*($a%$b))/$b^0);echo$o; ``` Adapted from this answer (also by me): [Division of not so little numbers](https://codegolf.stackexchange.com/questions/96030/division-of-not-so-little-numbers/96099#96099) and Jörg Hülsermann's suggested edit to it. Use like: ``` php -r "for($b=$c=$argv[$a=1];$c;)$o+=$c--*(($a=10*($a%$b))/$b^0);echo$o;" 7 ``` edit: corrected a bug for +1 bytes and folded the assignment of $a into $argv[1] for -2 bytes for a net 1 byte less. [Answer] # Scala, 84 bytes ``` val b=BigDecimal def?(& :Int)=1 to&map(x=>(""+b(1)/b(&))slice(2,x+2)map(_-48)sum)sum ``` Ungolfed: ``` def f(n: Int)={ val digits = ""+BigDecimal(1)/BigDecimal(n) (1 to n).map( x=> digits.slice(2, x+2).map(d => d - 48).sum ).sum ``` Explanation: ``` val b=BigDecimal //define an alias for BigDecimal def?(& :Int)= //define a method called ? with an integer & as a parameter 1 to & //create a range from 1 to & map(x=> //for each number x... (""+b(1)/b(&)) //calculate the fraction slice(2,x+2) //and take the slice starting from the third element, //(dropping the "1.") and containing x elements map(_-48) //for each char, subtract 48 to get the integer value sum //and sum them )sum //and take the sum ``` I could save some bytes by exploiting the way the compiler tokenizes: By calling the argument `&`, you can write `1 to&map` instead of `1 to n map`. The same rule applies to `def?`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ’aµR⁵*:µDFS ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4oCZYcK1UuKBtSo6wrVERlM&input=&args=MTI)** [First 50](http://jelly.tryitonline.net/#code=4oCZYcK1UuKBtSo6wrVERlMKw4figqw&input=&args=NTA) Too slow for the large test cases. ### How? ``` ’aµR⁵*:µDFS - Main link: n ’ - decrement a - and (to handle special case where n=1, to return 0 rather than 10) µ - monadic chain separation R - range: [1,2,...n] ⁵ - literal 10 * - exponentiation: [10,100,...,10^n] : - integer division: [10//n,100//n,...,10^n//n] µ - monadic chain separation D - cast to a decimal list [[digits of 10//n],[digits of 100//n],...] F - flatten into one list S - sum ``` [Answer] # PHP, 76 bytes (Edit -1 byte - Thanks user59178 - your solution is even better) ``` for($c=substr(bcdiv(1,$a=$argv[1],$a),2);$i<$a;)$s+=($a-$i)*$c[$i++];echo$s; ``` [Answer] # MATL, 19 bytes ``` li/GEY$4LQ)!UYsG:)s ``` [**Try it Online!**](http://matl.tryitonline.net/#code=bGkvR0VZJDRMUSkhVVlzRzopcw&input=Nw) **Explanation** ``` l % Push a 1 literal to the stack i/ % Grab the input (n) and compute 1/n GE % Grab the input again and multiply by 2 (2n) Y$ % Compute the first 2n digits of 1/n after the decimal 4LQ) % Get only the digits past the decimal point !U % Convert to numbers Ys % Compute the cumulative sum G:) % Get the first n terms s % Sum the result and implicitly display ``` [Answer] # Groovy, 87 Bytes This was less painful than I anticipated, and is based on my answer [here](https://codegolf.stackexchange.com/a/96126/59376): ``` {n->(1..n).collect{x->(1.0g.divide(n, n, 1)+"")[2..x+1].getChars().sum()-48*(x)}.sum()} ``` ## Explanation `1.0g` - Use BigDecimal notation for the one. `.divide(n, n, 1)+""` - Divide by n with n precision (BigDecimal function only) and convert to str. `(...)[2..x+1].getChars()` - Get the substring of the current iteration as an array of char. `.sum()-48*(x)` - Sum the ASCII values of the characters and reduce by 48 for each element. This turns the value from an ASCII digit to an Integer essentially saving bytes over `*.toInteger()`. `(1..n).collect{...}.sum()` - Iterate over each of the digits in the division, doing this function, get them all in a single array and sum. ## Saved 2 Bytes and Sacrificed Efficiency... This is a more efficient version that does not recalculate the BigDecimal each iteration. ``` {n->i=1.0g.divide(n, n, 1)+"";(1..n).collect{x->i[2..x+1].getChars().sum()-48*(x)}.sum()} ``` [Answer] # J, 27 bytes ``` 1#.[:+/\-{.10#.inv%<.@*10^] ``` ## Usage The input is an extended integer. ``` f =: 1#.[:+/\-{.10#.inv%<.@*10^] (,.f"0) (>: i. 50x) , 24990x + i. 11 1 0 2 10 3 18 4 23 5 10 6 96 7 103 8 52 9 45 10 10 11 270 12 253 13 402 14 403 15 630 16 183 17 660 18 765 19 819 20 95 21 975 22 1034 23 1221 24 1500 25 96 26 1479 27 1197 28 1658 29 1953 30 1305 31 1674 32 321 33 816 34 2490 35 2704 36 4235 37 2022 38 3242 39 2295 40 268 41 2944 42 3787 43 3874 44 4097 45 1980 46 4380 47 4968 48 3424 49 4854 50 98 24990 1405098782 24991 1417995426 24992 1364392256 24993 1404501980 24994 1408005544 24995 1377273489 24996 1395684561 24997 1405849947 24998 1406216741 24999 1142066735 25000 99984 ``` The performance is good and only requires about 3 seconds to compute for the large test cases. ``` timex 'f 7x' 0.000119 timex 'f 24999x' 3.8823 timex 'f 25000x' 3.14903 ``` ## Explanation ``` 1#.[:+/\-{.10#.inv%<.@*10^] Input: n ] Get n 10^ Raise 10 to the nth power % Get the reciprocal of n * Multiply (1/n) with (10^n) <.@ Floor it 10#.inv Convert it to a list of base 10 digits - Negate n {. Take the last n values from the list of digits (This is to handle the case for n = 1) [: \ For each prefix of the list of digits +/ Reduce it using addition to get the sum 1#. Convert those sums as base 1 digits and return (This is equivalent to taking the sum) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁵*:⁸D+\_ỊS ``` Not [the shortest approach](https://codegolf.stackexchange.com/a/96285/12012), but fairly efficient. [Try it online!](http://jelly.tryitonline.net/#code=4oG1KjrigbhEK1xf4buKUw&input=&args=MjUwMDA) or [verify all test cases](http://jelly.tryitonline.net/#code=4oG1KjrigbhEK1xf4buKUwo1MFI7MjQ5OTByMjUwMDDCpMK1xbzDh-KCrEc&input=). ### How it works ``` ⁵*:⁸D+\_ỊS Main link. Argument: n (integer) ⁵* Yield 10**n. :⁸ Divide 10**n by n (integer division). D Convert the quotient to base 10. +\ Take the cumulative sum of the digits. Ị Insignificant; yield (abs(n) <= 1). _ Subtract the resulting Boolean from each decimal digit. This takes care of edge case n = 1, which would return 2 otherwise. S Take the sum. ``` [Answer] ## Python 2, 90 bytes ``` lambda o:sum([sum([int(i)for i in s])for s in map(lambda x:str(1.0/o)[2:x],range(3,3+o))]) ``` Not pretty, but done through float dividing then converting to a string and then iterative string index selection to get the triangle of numbers, then perform list comprehension and convert each char to an int and finally summing them all. [Answer] # JavaScript (ES6), 47 bytes ``` f=(b,a=1%b,c=b+1)=>c&&(a/b|0)*c+f(b,a%b*10,c-1) ``` ## How it works [This answer](https://codegolf.stackexchange.com/a/96049/42545) demonstrates a technique for calculating **c** decimal digits of **a/b**: ``` f=(a,b,c,d=".")=>~c?(a/b|0)+d+f(a%b*10,b,c-1,""):d ``` This will make an excellent starting point for this challenge. First we can change it slightly so that it calculates **b** decimal digits of **1/b**, by reordering the parameters and setting defaults: ``` f=(b,a=1,c=b,d=".")=>~c?(a/b|0)+d+f(b,a%b*10,c-1,""):d ``` Next we can change this so that it calculates the sum of of the first **b** decimal digits, instead of concatenating them (this does away with the `d` parameter): ``` f=(b,a=1,c=b)=>~c?(a/b|0)+f(b,a%b*10,c-1):0 ``` We're almost to a solution; now we just need to make it multiply each digit by **c+1**: ``` f=(b,a=1,c=b)=>~c?(a/b|0)*-~c+f(b,a%b*10,c-1):0 ``` Hmm, this seems a little long. What if we incremented **c** by 1 to begin with? ``` f=(b,a=1,c=b+1)=>c?(a/b|0)*c+f(b,a%b*10,c-1):0 ``` That saves one byte. And here's a way to save one more: ``` f=(b,a=1,c=b+1)=>c&&(a/b|0)*c+f(b,a%b*10,c-1) ``` And now we have our answer. `f(7)` is 103, `f(11)` is 270, `f(1)` is... 2? Oh, we forgot to account for the case where **a/b** is 1 on the first iteration (i.e. **b** is 1). Let's do something about this: ``` f=(b,a=1%b,c=b+1)=>c&&(a/b|0)*c+f(b,a%b*10,c-1) ``` **1 mod b** is always **1**, unless **b** is **1**, in which case it will be **0**. Our program is now correct for all inputs, at **47 bytes**. [Answer] # Python 2, 49 bytes ``` lambda n:sum(10**-~k/n%10*(n-k)for k in range(n)) ``` Test it on [Ideone](http://ideone.com/6Ux9Ru). [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ṁΣḣdi*^¹10\ ``` [Try it online!](https://tio.run/##yygtzv7//@HOxnOLH@5YnJKpFXdop6FBzP///80B "Husk – Try It Online") ## Explanation ``` ṁΣḣdi*^¹10\ \ reciprocal of input *^¹10 multiply with 10^input i convert to int d digits ḣ prefixes ṁΣ map-sum with sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` L°¹÷T%ηOO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f59CGQzsPbw9RPbfd3///f0MjYwA "05AB1E – Try It Online") ``` L°¹÷T%ηOO # full program O # sum of... O # sums of... # (implicit) each element of... η # prefixes of... ° # 10 to the power of... # (implicit) each element of... L # [1, 2, 3, ..., # ..., implicit input]... ÷ # integer divided by... ¹ # input... % # modulo... T # 10 # implicit output ``` [Answer] **C, 53 bytes** ``` f(n,i,x,s){while(i)x=10*(x%n),s+=i--*(x/n);return s;} ``` Below the main for to do some test... ``` //44,79 #define R return #define F for #define U unsigned #define N int #define B break #define I if #define L(i) for(;i-->0;) #define J(a,b) if(a)goto b #define G goto #define P printf #define D double #define C unsigned char #define A getchar() #define O putchar #define M main #define Y malloc #define Z free #define S sizeof #define T struct #define E else #define Q static #define X continue main() {N k, a=0, b=0, i; F(i=1;i<50;++i) P("f(%u)=%u |", i, f(i,i,1,0)); P("\n"); F(i=24990;i<=25000;++i) P("f(%u)=%u |", i, f(i,i,1,0)); P("\n"); R 0; } /* f(1)=0 |f(2)=10 |f(3)=18 |f(4)=23 |f(5)=10 |f(6)=96 |f(7)=103 |f(8)=52 |f(9)=45 f(10)=10 |f(11)=270 |f(12)=253 |f(13)=402 |f(14)=403 |f(15)=630 |f(16)=183 |f(17)=660 f(18)=765 |f(19)=819 |f(20)=95 |f(21)=975 |f(22)=1034 |f(23)=1221 |f(24)=1500 f(25)=96 |f(26)=1479 |f(27)=1197 |f(28)=1658 |f(29)=1953 |f(30)=1305 |f(31)=1674 f(32)=321 |f(33)=816 |f(34)=2490 |f(35)=2704 |f(36)=4235 |f(37)=2022 |f(38)=3242 f(39)=2295 |f(40)=268 |f(41)=2944 |f(42)=3787 |f(43)=3874 |f(44)=4097 |f(45)=1980 f(46)=4380 |f(47)=4968 |f(48)=3424 |f(49)=4854 | f(24990)=1405098782 |f(24991)=1417995426 |f(24992)=1364392256 |f(24993)=1404501980 f(24994)=1408005544 |f(24995)=1377273489 |f(24996)=1395684561 |f(24997)=1405849947 f(24998)=1406216741 |f(24999)=1142066735 |f(25000)=99984 */ ``` ]
[Question] [ This is a problem that the Hacker Cup team made for the 2018 Facebook Hacker Cup, but we ended up not using it (though Ethan struggles through [a](https://www.facebook.com/hackercup/problem/1153996538071503/) [variety](https://www.facebook.com/hackercup/problem/232395994158286/) [of](https://www.facebook.com/hackercup/problem/988017871357549/) [other](https://www.facebook.com/hackercup/problem/467235440368329/) [challenges](https://www.facebook.com/hackercup/problem/278591946122939/)). Normally code size isn't a factor in the Hacker Cup, but we thought this would make for an interesting code golf challenge. We look forward to seeing how a different sort of competitive programmer tackles this problem! --- Ethan has been given quite the challenging programming assignment in school: given a list of \$N\ (1 \le N \le 50)\$ distinct integers \$A\_{1..N}\ (1 \le A\_i \le 100)\$, he must find the largest one! Ethan has implemented an algorithm to solve this problem, described by the following pseudocode: 1. Set \$m\$ to be equal to \$A\_1\$. 2. Iterate \$i\$ upwards from 2 to \$N\$ (inclusive), and for each \$i\$, if \$A\_i > A\_{i-1}\$, set \$m\$ to be equal to \$A\_i\$. 3. Output \$m\$. Sometimes this algorithm will output the correct maximum value, but other times it sadly won't. As Ethan's teaching assistant, you have some say in what input data his solution will be evaluated on. The professor has given you a list of \$N\$ distinct integers \$A\_{1..N}\$ to work with, but you may shuffle them into any permutation you'd like before feeding them into Ethan's program. This is your opportunity to show some mercy! For how many different permutations of \$A\_{1..N}\$ would Ethan's algorithm produce the correct output? ## Input Format: Line 1: 1 integer, \$N\$ Line 2: \$N\$ space-separated integers, \$A\_{1..N}\$ ## Output Format: 1 integer, the number of permutations of \$A\$ for which Ethan's algorithm would produce the correct output. ### Sample Input 1: ``` 1 100 ``` ### Sample Output 1: ``` 1 ``` ### Explanation: Only one permutation of \$[100]\$ exists, and Ethan's program would correctly output 100 for it. ### Sample Input 2: ``` 3 16 82 43 ``` ### Sample Output 2: ``` 5 ``` ### Explanation: Ethan's program would correctly output 82 for 5 of the 6 possible permutations of \$[16, 82, 43]\$. However, when \$A = [82, 16, 43]\$, it would incorrectly output 43 instead. ### Sample Input 3: ``` 10 26 81 40 5 65 19 87 27 54 15 ``` ### Sample Output 3: ``` 986410 ``` ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) wins! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~5~~ 3 bytes ``` ⍳⊥× ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x/1bn7UtfTw9P9pQO6j3j6ITFfzofXGj9omAnnBQc5AMsTDM/h/2qEVxgqmCmYKhgZcj3rngpimCsZGZgqWFmYmhgYA "APL (Dyalog Unicode) – Try It Online") Adám gave me an inspiration to golf this further. ### How it works ``` ⍳⊥× Monadic train. Input: n, the length of array A. × v: Signum, which always gives 1 because n ≥ 1 ⍳ B: An array of 0..n-1 ⊥ Scalar-expand v to get V, a length-n vector of ones, then mixed base conversion of V in base B ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 bytes ``` ⍳⊥⍴∘1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/x/1bn7UtfRR75ZHHTMM/6cBxR719kGku5oPrTd@1DYRyAsOcgaSIR6ewf/TDq0wVjBVMFMwNOB61DsXxDRVMDYyU7C0MDMxNAAA "APL (Dyalog Unicode) – Try It Online") *Edited to remove modulo 107* Uses [HyperNeutrino's formula](https://codegolf.stackexchange.com/a/194804/78410), but optimized through the use of `⊥` (mixed base conversion) directly. Uses `⎕IO←0`. ### How the code works ``` ⍳⊥⍴∘1 Monadic train. Input: n, the length of array A. ⍴∘1 V: An array of 1's of length n ⍳ B: An array of 0..n-1 ⊥ Mixed base conversion of V in base B ``` ### How the `⊥` works ``` base: 0 1 2 .. n-3 n-2 n-1 digit: 1 1 1 .. 1 1 1 value: 1×..(n-1) 2×..(n-1) 3×..(n-1) .. (n-2)×(n-1) n-1 1 sum of all digit values is the answer. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` RU×\S: ``` [Try it online!](https://tio.run/##y0rNyan8/z8o9PD0mGCr////mwEA "Jelly – Try It Online") Let's analyze under which scenarios this algorithm works. If the maximum element is at the end of the list, this obviously works, since \$A\_N>A\_{N-1}\$ and it is processed last. This gives \$(N-1)!\$ possibilities. If the maximum element is at the second last position, then this obviously works, since \$A\_N<A\_{N-1}\$ so it is not processed, and \$A\_{N-1}>A\_{N-2}\$ and is processed last. This gives \$(N-1)!\$ possibilities. There is no overlap between this case and the above because the numbers are guaranteed unique. If the maximum element is at the third last position, then it depends on the last two elements. If the last element is larger than the second last element, it is treated as the maximum, which fails. There are \$(N-1)!\$ cases, and we can match them by identical first \$(N-3)\$ elements with one case going \$\cdots,max,A,B\$ and the other going \$\cdots,max,B,A\$. Exactly one of these is valid and not the other, so there are \$\frac{(N-1)!}{2}\$ cases. In general, if the maximum element has \$k\$ elements after it, then the rest of the list must be strictly descending. There is exactly one case for each set of last \$k\$ elements out of the \$k!\$ permutations. Thus, the answer is \$\frac{(N-1)!}{0!}+\frac{(N-1)!}{1!}+\cdots+\frac{(N-1)!}{(N-1)!}\$. This is [OEIS A000522](http://oeis.org/A000522). This is equal to \$\frac{\frac{N!}{0!}+\frac{N!}{1!}+\cdots+\frac{N!}{(N-1)!}}{N}\$, which is \$\frac{(N\times(N-1)\times(N-2)\times\cdots\times 1+N\times(N-1)\times(N-2)\times\cdots\times 2+\cdots+N}{N}\$, which is the sum of the cumulative product of the list \$[N,N-1,\cdots,2,1]\$, divided by N. ``` RU×\S: R [1, 2, ..., N] U reversed \ cumulative × product S sum : divided by (N) ``` Having MathJax is really nice :D Note that the list literally does not matter. All we need to know is N. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 44 bytes ``` K`; "$+"+`(.*);(.*) $.(_$1*);$.(_$1*$2* .*; ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvBmktJRVtJO0FDT0vTGkRwqehpxKsYAnlQhoqRFpeeljXX//@GBgA "Retina – Try It Online") Explanation: ``` K`; ``` Replace `N` with a counter and output (these should be decimal 0, but the empty string works here). ``` "$+"+` ``` Repeat `N` times... ``` (.*);(.*) $.(_$1*);$.(_$1*$2* ``` ... multiply the output by the counter and increment both. ``` .*; ``` Delete the loop counter. Previous 47 bytes including modulo 107: ``` K`; "$+"{`(i*);(j*) i$1;j$.1*$2 )`(\w{107})* j ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvBmktJRVupOkEjU0vTWiNLS5MrU8XQOktFz1BLxYhLM0Ejprza0MC8VlOLiyvr/38jAwA "Retina – Try It Online") Explanation: ``` K`; ``` Replace `N` with a counter and output (both initially 0). ``` "$+"{` )` ``` Repeat `N` times... ``` (i*);(j*) i$1;j$.1*$2 ``` ... multiply the output by the counter and increment both... ``` (\w{107})* ``` ... and reduce modulo 107. ``` j ``` Convert the output to decimal. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ ~~5~~ 4 bytes -1 byte thanks to @KevinCruijssen Implementation of @Neil's algorithm. ``` GNP> ``` Explanation: ``` G for loop from 1 to input N push current iteration P multiply the stack; in the first iteration there's only 1 element (1) > increment ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f3S/A7v9/QwMA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), ~~19~~ 18 bytes *A shorter version suggested by [@Neil](https://codegolf.stackexchange.com/users/17602/neil)* *Saved 1 byte thanks to [@Jitse](https://codegolf.stackexchange.com/users/87681/jitse)* ``` f=n=>n&&--n*f(n)+1 ``` [Try it online!](https://tio.run/##FYtBDkAwFAX3TvEXIq2mwpo6SxtUiLwviE3Ts1etZhYzu3vdPV3b@WjwvKTkDcyIqtIatReQqkueLwEy1PUEGjLbLEpJCgXRxLj5WJqDV2GdKAOizG0Z/jla2RcxfQ "JavaScript (Node.js) – Try It Online") Implements the following formula from [A000522](http://oeis.org/A000522): $$\cases{a\_0=1\\ a\_{n}=n\cdot a\_{n-1} + 1,&n>0}$$ Turned into: $$\cases{a\_0=0\\ a\_{n}=(n-1)\cdot a\_{n-1} + 1,&n>0}$$ --- # JavaScript (ES6), 35 bytes This is a port of [@HyperNeutrino's answer](https://codegolf.stackexchange.com/a/194804/58563). Takes only \$n\$ as input, as per [this consensus](https://codegolf.meta.stackexchange.com/a/12442/58563). ``` n=>(g=n=>n&&(p*=n)+g(n-1))(n,p=1)/n ``` [Try it online!](https://tio.run/##DYrBDoIwEAXvfMUeCNm1ovYM67fQIG005LUB46Xpt9deZuYwH/dz53q803dEfG3Va4U@OWgjhoHTRSEmMEYrwrgmtXJH9fFgkJKdCDQ3P1oYI5Q7ojXijPt222PgxXGfUaS9ffYMKYtMXal/ "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 28 bytes ``` f=lambda n:n and~-n*f(n-1)+1 ``` [Try it online!](https://tio.run/##DcoxDoAgDAXQ3VN0pApD40biYWoUJdEPISwuXr365leffhbMZmm59F43JUSQYnsDxuQQhCexVBqBMqgpjt2JF@E4UG0Z3cHTH5ntAw "Python 3 – Try It Online") Python port of [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s algorithm. [Answer] # [R](https://www.r-project.org/), 28 bytes ``` n=scan();sum(cumprod(n:1))/n ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTurg0VyO5NLegKD9FI8/KUFNTP@@/ocH//wA "R – Try It Online") R port of [@HyperNeutrino’s algorithm](https://codegolf.stackexchange.com/a/194804/43328). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes ``` ×\∘⌽∘⍳∘≢+.÷≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/////D0mEcdMx717AWRvZtBZOcibb3D24HU/7RHbRMe9fY96pvq6f@oq/nQeuNHbROBvOAgZyAZ4uEZ/D/t0AoNoD5TTRBpBiYNDTQB "APL (Dyalog Unicode) – Try It Online") -4 bytes thanks to the change in specifications; -3 bytes thanks to @Adám Train that implements [@HyperNeutrino's formula](https://codegolf.stackexchange.com/a/194804/74163), so go upvote their answer. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~69~~ ~~62~~ 60 bytes Following the consensus in C; Updated to the most golfed solution thanks to contributions from Arnauld and FryAmTheEggman. mod 107 has been removed from the rules, I was being too tricky. Thanks for the edit Arnauld. ``` c,o,d,e;f(n){for(e=n;n--;c+=o)for(d=e,o=1;d>n;)o*=d--;c/=e;} ``` [Try it online!](https://tio.run/##Nc3BCsIwDAbg@56iDJRGU3TnEN9lJK3sYCLT29iz11Yxp5/v/yGS7iK1CjoqZirRYCu@xsxGlhLJmR06KGd0nkhvRuAn1l5eONNeF3uHx7xYhGEbQrsORt/4ktlKHA86Yjga/PC5tsVf@8vme52uHw "C (gcc) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÆÉ /Xl ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=xskgL1hs&input=Mw) [Answer] # [Ruby](https://www.ruby-lang.org/), 24 bytes ``` f=->n{n<1?1:f[n-=1]*n+1} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0N7QKi06T9fWMFYrT9uw9r@GoZ6eoYGmXm5iQXVNRY1CQWlJsYKScnVFrYJydVp0RWytUu1/AA "Ruby – Try It Online") Using the formula from [OEIS A000522](https://oeis.org/A000522) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/116012/edit). Closed 6 years ago. [Improve this question](/posts/116012/edit) # Introduction For those not familiar with steam - or at least this particular aspect: Often on peoples' profiles, people leave comments saying either "+rep \_\_\_\_\_" or "-rep \_\_\_\_\_". These are an unofficial means of showing whether you think someone in the community has a good or a bad reputation, for a number of reasons. Such comments look like: > > +rep a good player > > > +rep helpful > > > -rep hacker > > > -rep scammer > > > --- # Task The program must take input through any consensual way. The input consists of a string with optional newlines (`\n`). At the very start of each line, `'+rep '` or `'-rep '` might be present. The rest of the line can be discarded. If the line doesn't start with `'+rep '` or `'-rep '` (note the trailing space), the line should be ignored. The program then must keep a total reputation score. Starting at `0`, this score should be incremented on every line that starts with `'+rep '` and decremented on every line that starts with `'-rep '`. This result should be output in any agreed-upon way. --- # Test cases ``` Input: +rep fast trade +rep nice person -rep too good Output: 1 Input: -rep hacker -rep scammer -rep was mean Output: -3 Input: first i don't like him +rep good at cs go Output: 1 Input (note the lack of a trailing space on the third line): +rep +rep hi +rep -rep Output: 1 Input: + rep Output: 0 Input: +rep like -thing Output: 1 ``` --- ## Bonus I don't even know if it's possible, but bonus points if you can somehow get these comments from Steam. [Answer] # Python 3, 73 bytes I'm sure this answer is garbage and will be beaten soon, but there's no other python answers yet ``` lambda x:sum(["- +".index(i[0])-1for i in x.split('\n')if i[1:4]=="rep"]) ``` Use like this: ``` f = lambda x:sum(["- +".index(i[0])-1for i in x.split('\n')if i[1:4]=="rep"]) print(f("PUT INPUT HERE")) ``` ## Fetching from steam Here's some sample code which fetches the first 100 comments from KennyS' profile and calculates his rep. ``` import requests from bs4 import BeautifulSoup # Kenny's profile as Steam ID 64 # You can adjust this to whatever numbers you want STEAM_PROFILE_URL = "76561198024905796" payload = {"start" : 0, "count" : 100} r = requests.post("http://steamcommunity.com/comment/Profile/render/{}/-1/".format(STEAM_PROFILE_URL), payload) # Comments are html inside a json object soup = BeautifulSoup(r.json()["comments_html"], "html.parser") # Get raw text for every comment. # The " ".join() strips out the newlines and tabs which are part of html comments = [" ".join(s.text.split()) for s in soup.find_all("div", {"class" : "commentthread_comment_text"})] calculateRep = lambda x:sum(["- +".index(i[0])-1for i in x.split('\n')if i[1:4]=="rep"]) print(calculateRep("\n".join(comments))) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~16~~ 17 bytes Saved 2 bytes thanks to *Okx* +1 byte due to change in spec where rep now need to be followed by a space. ``` |vy5£„+-S„·Ý «QÆO ``` [Try it online!](https://tio.run/nexus/05ab1e#@19TVmlyaPGjhnnausHqh7YfnntodeDhNv///7WLUgsU0hKLSxRKihJTUrnA/LzM5FSFgtSi4vw8Ll2QQEl@vkJ6fn4KAA "05AB1E – TIO Nexus") **Explanation** ``` |v # for each line of input y5£ # get the first 4 chars of input „+-S„·Ý « # push the list ['+rep ','-rep '] Q # check each for equality # results in either [1,0] for +rep, [0,1] for -rep or [0,0] for others Æ # reduce by subtraction, gives either 1, -1 or 0 O # sum ``` [Answer] # [Perl 5](https://www.perl.org/), 25 bytes 24 bytes of code + `-p` flag. ``` $\+=/^\+rep /-/^-rep /}{ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K8So22rHxejXZRaoKCvqx@nC2bUVv//DxZKSywuUSgpSkxJ5QLz8zKTUxWAeovz87jASkvy8xXS8/NTAA "Perl 5 – TIO Nexus") `/^\+rep /` returns `1` if the line starts with `+rep`; `/^-rep /` returns `1` if the line starts with `-rep` (so only one of them will be one at most). We use `$\` to store the result, as it is implicitly printed at the end (thanks to `-p` flag and those unmatched `}{`). [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` q=('\n'+input()).count;print q('\n+rep ')-q('\n-rep ') ``` [Try it online!](https://tio.run/nexus/python2#@19oq6Eek6eunZlXUFqioampl5xfmldiXVCUmVeiUAiS0y5KLVBQ19QFc3QhnP//lZSUwBIgIiYvIxPKAMkDpQA "Python 2 – TIO Nexus") Takes a multiline string as input. Counts the appearances of `'+rep '` and `'-rep '` only at starts of lines by searching for the string following a newline symbol. To catch the first line, a newline is prepended to the input. [Answer] # [Retina](https://github.com/m-ender/retina), ~~63~~ ~~51~~ ~~50~~ 49 bytes Didn't quite comply with the spec so I fixed some issues but also golfed it a lot (by borrowing the first line from Kritixi Lithos's solution). Saved another byte thanks to Kritixi Lithos. ``` ms`(?!^[+-]rep ). +`\+-|-\+ (.)+ $1$.& T`+ $^ 0 ``` [Try it online!](https://tio.run/nexus/retina#@59bnKBhrxgXra0bW5RaoKCpx8WlnRCjrVujG6PNxaWhp6nNpWKooqfGFZIAZMVxGfz/rw1SCCK4MjIhtC6QAAA "Retina – TIO Nexus") **Explanation** ``` ms`(?!^[+-]rep ). ``` First, everything from the input is deleted, except for the `+` and `-` from any `+rep` or `-rep` at the start of a line. ``` +`\+-|-\+ ``` Then adjacent pairs of `+` and `-` are removed until no more can be removed. After this, what's left is either a run of `+`s, a run of `-`s, or nothing. ``` (.)+ $1$.& ``` Then a run of one or more characters (either `+` or `-`) is replaced with the character making up the run followed by the length of the run. This way, `+` is preserved at the start for positive results and `-` for negatives. ``` T`+ ``` Then all `+`s are removed, in the event that the rep is positive. ``` $^ 0 ``` Finally, if the string is empty at this point, the rep is 0, so we write 0. [Answer] # Mathematica, 47 bytes (ISO 8859-1 encoding) ``` (±c_:=StringCount[" "<>#,c];±" +rep"-±" -rep")& ``` Pure function taking a newline-separated string as input and returning an integer. Note that the three newlines in the code are flanked by quotes and are thus each equivalent to `"\n"` in a string (but this way is one byte shorter than `"\n"`). `StringCount` does the heavy lifting; we manually add a newline to the beginning of the string so that the first line matches when appropriate. `±` is a unary helping function to avoid repetition of `StringCount`. The alternative solution ``` (±c_:=StringCount[" "<>#," "<>c<>"rep"];±"+"-±"-")& ``` is 4 bytes longer, but I do like the sequence `±"+"-±"-"`.... [Answer] # [Retina](https://github.com/m-ender/retina), ~~59~~ ~~53~~ ~~52~~ 50 bytes ``` ms`(?!^[+-]rep ). +`\+-|-\+ -+ -$.& \++ $.& ^$ 0 ``` [Try it online!](https://tio.run/nexus/retina#XYxBDkAwFET3cwqSRsjPFzdwENUgJCxooztx9@rHhs3My@Rlwuq7vE5NQ9zuk0uKEqBOE5@sCWACqzKDJoK0UahC6P0IEnteEPnGZwBLOmt/8LWGODvrIOwf4Zj2V93A8i98AQ "Retina – TIO Nexus") Check out Basic Sunset's shorter [answer](https://codegolf.stackexchange.com/a/116016/41805) in the same language! ### Explanation ``` ms`(?!^[+-]rep ). ``` Removes everything except for `[+-]rep` s. ``` +`\+-|-\+ ``` Repeatedly removes 1 `-` for every `+` and vice versa. ``` -+ -$.& ``` Prepend a `-` (because the number is negative) to `-`s as well as replacing the `-`s with the number of `-`s. ``` \+ $.& ``` Do the same for `+`s, but don't prepend a `-`. ``` ^$ 0 ``` Finally, if there is nothing, replace it with a `0`. [Answer] ## PHP, 118 bytes ``` function s($a,$c=0){foreach(explode(" ",$a)as$b){$b=substr($b,0,1).'1';if(is_numeric($b){$c+=$b});}return$c-($a=="");} ``` [Try it online!](https://repl.it/HDXz/1) Used like this: ``` echo s("-rep bad +rep good +rep very good +rep exceeds expectation"); ``` [Answer] # [Röda](https://github.com/fergusq/roda), 53 bytes ``` {{|l|[1]if[l=~`\+rep .*`];[-1]if[l=~`-rep .*`]}_|sum} ``` [Try it online!](https://tio.run/nexus/roda#y03MzFOo/l9dXZNTE20Ym5kWnWNblxCjXZRaoKCnlRBrHa0LF9WFCdbG1xSX5tb@r/0PVgciuDIyITRIEQA "Röda – TIO Nexus") [Answer] # JavaScript, 55 bytes Thanks @Neil for golfing off 12 bytes Thanks @Arnauld for golfing off 2 bytes ``` x=>x.split(/^\+rep /m).length-x.split(/^-rep /m).length ``` [Try it online!](https://tio.run/nexus/javascript-node#S7P9X2Frp1Ghl5tYkpyhoR8Xo12UWqCgn56rWVOjrq6pl5Oal16SoYukQhebgv/J@XnF@Tmpejn56RppGkogU2LyQCSEpQsmE4tT0hJTitOUNDX/AwA "JavaScript (Node.js) – TIO Nexus") ``` var y=x=>(x.match(/^\+rep /gm)||'').length-(x.match(/^-rep /gm)||'').length document.querySelector('div').innerText=y(document.querySelector('textarea').value) ``` ``` textarea{ width: 95%;height: 100px; } ``` ``` <textarea oninput = "document.querySelector('div').innerText=y(this.value)"> -rep Cheater!! +rep very good, fun to play with +rep my friend +rep good </textarea> <div></div> ``` [Answer] # Java, 109 bytes ``` l->{int i=0;for(String s:l.split("\n")){if(s.startsWith("+rep "))i++;if(s.startsWith("-rep "))i--;}return i;} ``` Trying to make this shorter using `Stream`'s [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 45 bytes ``` '^([+-])rep |.'{.a:''['#'a+]a if}mrepl'0'\+#~ ``` [Try it online!](https://tio.run/nexus/stacked#HYpLCoMwEIb3OcWAi98yKF17gt7BKgzNWITUkZjShdqrp9rl9wBHnWmQJVGK4tX9eRofSrPGxSZXnSKZ0dPMu5uGYPSxGLxjOhIy@rLlqruc31ZjraUBWhQQ7oTGYX8dJeCKOxffbO@Ufw "Stacked – TIO Nexus") Alternatively (49 bytes): ``` lines'^[-+]rep 'match$#'YES[0#0# '#'\+]"!''#`0\#~ ``` ## Explanation ``` '^([+-])rep |.'{.a:''['#'a+]a if}mrepl'0'\+#~ ``` This basically extracts all `+` or `-` attached to the beginning of the line and `rep`. Then, to each, it prepends a `#`. Then, to the entire thing, a `0` is prepended. `#~` evaluates the string, which now looks something like: ``` 0#+#+#- ``` `#+` is increment and `#-` is decrement. Thus, we obtain our desired result. [Answer] # [Retina](https://github.com/m-ender/retina), 38 bytes ``` M!m`^[+-]rep Os`. +`\+- *\M1!`- [+-] ``` [Try it online!](https://tio.run/nexus/retina#@@@rmJsQF62tG1uUWqDA5V@coMelnRCjrcvFpRXja6iYoMsFkvz/XxskDyK4MjIhtC5IJD/bHsbgAivJz8/nSkzNzC@FCJenpqYCAA "Retina – TIO Nexus") A different (and shorter) solution than the ones already posted in Retina. ### Explanation ``` M!m`^[+-]rep ``` (This line has a trailing space). Keep only the relevant parts of the input, i.e. the `+rep` or `-rep` at the beginning of a line. ``` Os`. ``` Sort all characters (including newlines). this will put +s and -s next to each other. ``` +`\+- ``` Repeatedly remove `+-` couples until at most one of the two signs remains. ``` *\M1!`- ``` Match the first `-` (if present) and print it without modifying the string. ``` [+-] ``` Count the number of signs remaining, and print it since this is the final stage of the program. [Answer] # C#, 87 bytes ``` s=>{int n=0;foreach(var t in s.Split('\n'))n+=t.IndexOf("rep ")==1?44-t[0]:0;return n;} ``` Anonymous function which splits the input string by using the newline character, searches for the "rep " string prefixed by a character and, if it finds it, increments the reputation (the `n` variable) by 1 or -1. Full program with ungolfed method and test cases: ``` using System; class P { static void Main() { Func<string, int> f = s=> { int n = 0; foreach (var t in s.Split('\n')) n += t.IndexOf("rep ") == 1 ? 44 - t[0] : 0; return n; }; // test cases: Console.WriteLine(f(@"+rep fast trade +rep nice person -rep too good")); // 1 Console.WriteLine(f(@"-rep hacker -rep scammer -rep was mean")); // -3 Console.WriteLine(f(@"first i don't like him +rep good at cs go")); // 1 Console.WriteLine(f(@"+rep +rep hi +rep -rep")); // 1 Console.WriteLine(f(@"+ rep")); // 0 Console.WriteLine(f(@"+rep like -thing")); // 1 } } ``` **Note that the ASCII code for `+` is 43 and for `-` is 45. This method passes all test cases from the OP. However, if the first character is something else, this will lead to wrong answers!** This can be fixed at the cost of 17 bytes: # C# fixed, 104 bytes ``` s=>{int n=0;foreach(var t in s.Split('\n'))n+=t.IndexOf("rep ")==1?t[0]==43?1:t[0]==45?-1:0:0;return n;} ``` The modified anonymous function will check for a `+` or `-` sign as the first character in each line. [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` r`œp`1 f".%d ``` [Try it online!](https://tio.run/nexus/japt#@1@UcGhOQYKhQpqSnmqKwv//StpFqQUKICImLyMTytAFkkoKuhUA "Japt – TIO Nexus") +1 byte for `-x` flag [Answer] # C++, 144 bytes ``` #import<iostream> int f(){int r=0;for(std::string s;std::getline(std::cin,s);)if((s[0]==43|s[0]==45)&s.substr(1,4)=="rep ")r-=s[0]-44;return r;} ``` [Try it online!](https://tio.run/nexus/cpp-gcc#LU5BDsIwDLv3FRFIqBUMgRgXuvIRxGGwborEminJTsDbxwrk4thx4kxL7AdirZBEOdb92WBSaK17ZuSw8y2xFW1Op9mAqQPxX9ZFfWCKv9Ed00acd9haK5fdNYTy8Po3R7eSrYy3ed3uN6ULYcFxgIXjImRLUZaeo46cgP17yrF9jck68zQw1y@ARoWqyo95857W@UJbi4Jy3UTz5QnvEYbIQskUWVAi6IiaDw) [Answer] ## [C#](http://csharppad.com/gist/f48dd4513d8320d145251b927186b559), 104 bytes --- Despite existing already one solution -- and mine being longer -- I still think I should post it, since the on already here might fail if something like `'=rep '` gets in it's way. --- **Golfed** ``` i=>{var c=0;foreach(var o in i.Split('\n'))c+=o.IndexOf("rep ")!=1?0:o[0]==43?1:o[0]==45?-1:0;return c;} ``` --- **Ungolfed** ``` i => { var c = 0; foreach( var o in i.Split( '\n' ) ) c += o.IndexOf( "rep " ) != 1 ? 0 : o[ 0 ] == 43 ? 1 : o[ 0 ] == 45 ? -1 : 0; return c; } ``` --- **Ungolfed readable** ``` i => { // Counter for the 'reputation' var c = 0; // Cycle through every line foreach( var o in i.Split( '\n' ) ) // Check if the "rep " string has index 1 // ( Index 0 should be the sign ) c += o.IndexOf( "rep " ) != 1 // Add 0 if the rep isn't on the right position ? 0 // Check for the '+' sign : o[ 0 ] == 43 // Add 1 if the sign is found ? 1 // Check for the '-' sign : o[ 0 ] == 45 // Add -1 if the sign is found ? -1 // Add 0 if another char is found : 0; // Return the 'reputation' return c; } ``` --- **Full code** ``` using System; using System.Collections.Generic; namespace Namespace { class Program { static void Main( String[] args ) { Func<String, Int32> f = i => { var c = 0; foreach( var o in i.Split( '\n' ) ) c += o.IndexOf( "rep " ) != 1 ? 0 : o[ 0 ] == 43 ? 1 : o[ 0 ] == 45 ? -1 : 0; return c; }; List<String> testCases = new List<String>() { @"+rep fast trade +rep nice person -rep too good", @"-rep hacker -rep scammer -rep was mean", @"first i don't like him +rep good at cs go", @"+rep +rep hi +rep -rep", @"+ rep", @"+rep like -thing", }; foreach( String testCase in testCases ) { Console.WriteLine( $"{testCase}\n{f( testCase )}\n" ); } Console.ReadLine(); } } } ``` --- **Releases** * **v1.0** - `104 bytes` - Initial solution. --- **Notes** Nothing to add [Answer] # Ruby, 46 bytes ``` ->x{rep=1;eval ?0+x.map{|a|a[/^[+-]rep /]}*''} ``` Get all the +/-rep from input, and put together in a single string. Then evaluate that for rep=1. [Answer] # JavaScript ES6, ~~85~~ 79 bytes ``` l=>eval(l.split` `.map(i=>(r=i.slice(0,5))==`+rep `?1:r==`-rep `?-1:0).join`+`) ``` --- ## Try it ``` f=l=>eval(l.split` `.map(i=>(r=i.slice(0,5))==`+rep `?1:r==`-rep `?-1:0).join`+`); console.log(f(`+rep fast trade +rep nice person -rep too good`)); console.log(f(`-rep hacker -rep scammer -rep was mean`)); console.log(f(`first i don't like him +rep good at cs go`)); console.log(f(`+rep +rep hi +rep -rep`)); console.log(f(`+ rep`)); console.log(f(`+rep like -thing`)); ``` --- ## Ungolfed ``` const repcount=list=>{ let array=list.split("\n"); let values=array.map(item=>{ let rep=item.slice(0,5); return rep==="+rep "?1:rep==="-rep "?-1:0; }); let result=values.reduce((a,b)=>a+b); return result; }; ``` --- ## History ### 85 bytes ``` l=>l.split`\n`.map(i=>(r=i.slice(0,5))=="+rep "?1:r=="-rep "?-1:0).reduce((a,b)=>a+b) ``` ]
[Question] [ I want a blanket that looks like this. Each strip goes over, under, over, under. Can you print it? ``` \\\\////\\\\////\\\\////\\\\////\\\\////\\\\//// \\//// \\//// \\//// \\//// \\//// \\//// //// //// //// //// //// //// ////\\ ////\\ ////\\ ////\\ ////\\ ////\\ ////\\\\////\\\\////\\\\////\\\\////\\\\////\\\\ \// \\\\// \\\\// \\\\// \\\\// \\\\// \\\ \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\ \\\ //\\\\ //\\\\ //\\\\ //\\\\ //\\\\ //\ \\\\////\\\\////\\\\////\\\\////\\\\////\\\\//// \\//// \\//// \\//// \\//// \\//// \\//// //// //// //// //// //// //// ////\\ ////\\ ////\\ ////\\ ////\\ ////\\ ////\\\\////\\\\////\\\\////\\\\////\\\\////\\\\ \// \\\\// \\\\// \\\\// \\\\// \\\\// \\\ \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\ \\\ //\\\\ //\\\\ //\\\\ //\\\\ //\\\\ //\ \\\\////\\\\////\\\\////\\\\////\\\\////\\\\//// \\//// \\//// \\//// \\//// \\//// \\//// //// //// //// //// //// //// ////\\ ////\\ ////\\ ////\\ ////\\ ////\\ ////\\\\////\\\\////\\\\////\\\\////\\\\////\\\\ \// \\\\// \\\\// \\\\// \\\\// \\\\// \\\ \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\ \\\ //\\\\ //\\\\ //\\\\ //\\\\ //\\\\ //\ ``` Trailing spaces at the end of each line and trailing newlines are acceptable. Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. ## Leaderboards 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 ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=99023,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Python 2, 84 bytes ``` R=range(24) for i in R:print''.join(" \// \/\\"[i+~j>>2&1^i+j>>1&2^i&4]for j in R*2) ``` Thanks to Sp3000 for 6 bytes from turning the arithmetic operations into bitwise ones. [Answer] # Pyth, 36 bytes ``` V24sm@" \// \/\\"im<3%k8++BNdt-NdT48 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=V24sm%40%22+%5C%2F%2F+%5C%2F%5C%5C%22im%3C3%25k8%2B%2BBNdt-NdT48&debug=0) ### Explanation: We can determine the symbol by checking 3 conditions: ``` A := row % 8 > 3 B := (row + column) % 8 > 3 C := (row - column - 1) % 8 > 3 ``` If we interpret `[A,B,C]` as a binary number, we get the following mapping: ``` 01234567 \// \/\ ``` We can also interpret `[A,B,C]` as decimal number and perform a modular indexed lookup in the string. This doesn't make a difference because `10 mod 8 = 2`. Now to the code: `V24` iterates `N` (row-idx) over `[0, 1, ..., 23]`. `sm...48` maps the numbers `d` (column-idx) in `[0, 1, ..., 47]` to chars and print the combined string. `++BNd` generates the list `[N, N+d]`, `+...t-Nd` appends `N-d-1`. So we have get the list `[N, N+d, N-d-1]`. `m<3%k8` checks for each computed number `k`, if `3 < k % 8`, so this gives the list with the conditions `[A, B, C]`. `i...T` convents this to a decimal number and then `@" \// \/\\"` does the lookup in the string. More or less the same code in Python2: **98 bytes**: ``` R=range(8) for r in R*3:print''.join(" \// \/\\"[4*(r>3)+2*((r+c)%8>3)+((r-c-1)%8>3)]for c in R*6) ``` [Answer] # Python 3, ~~174~~ ~~172~~ 138 bytes ``` print("\n".join(o*6for o in("bbbb////"," bb//// "," //// "," ////bb ","////bbbb","b// bbb","bb bb","bbb //b")*3).replace("b","\\")) ``` Found the smallest pattern I could find in the blanket (the "under" and "over" pattern), stuck it in a list and added some list comprehension and string manipulation to unpack it all. Substituted all escaped backslashes by "b" and replaced them back later to save a few bytes. Thanks to Oliver for golfing off 2 bytes! Took 34 bytes off by changing the pattern - the whole pattern for the blanket is now in a single list, so only one for loop is needed to unwrap the pattern. [Answer] # Python 2, ~~171~~ ~~170~~ 168 bytes ``` a,b,c=r"\\","/"*4," " f,g=c*2,c+a+b+c d=(a*2+b)*6,g*6,(f+b+f)*6,g[::-1]*6,(b+a*2)*6,('\\//'+f+a+"\\")*6,(a+f*2+a)*6,(a+"\\"+f+'//\\')*6 for e in 0,1,2:print'\n'.join(d) ``` Not pretty and not clever. Just sets variables for the most often used groups of strings then combines them and prints the result 3 times. May try and golf it more later if I don't find a better approach. 1 byte saved by using raw input on the a assignment. Thanks @nedla2004 -2 by assigning a couple of variables but still not a serious competitor [Answer] # Brainfuck, 301 bytes ``` -[>+<-----]-[>>+<<---]>---->+++++++>>++++[<++++++++>-]>+++>++++++++++<[-<++++++[-<<....<....>>>]>>.<<++++++[-<.<..<....>>.>]>>.<<++++++[-<..<<....>>..>]>>.<<++++++[-<.<<....>..>.>]>>.<<++++++[-<<<....>....>>]>>.<<++++++[-<<.<..>>..<...>>]>>.<<++++++[-<<..>....<..>>]>>.<<++++++[-<<...>..<<..>.>>]>>.<] ``` [Try it online!](https://tio.run/##bc1RCoAgDAbgAw09wfgvIj5UEETQQ9D5bb@agTpEt31O13s5rv3ZzpRcgKhjREstZxHBBqQEchJUvtqch7TQ4Kpaot4ibwAi4PU39iv5wbx@NFolrt4acbQ3/sYHda5lTOdGLHeqxpRe "brainfuck – Try It Online") [Answer] # Perl, 209 + 17 = 226 bytes Run with `-mList::Util=max -M5.010` (the second flag is free). It's not winning any byte count competitions, but here's my solution. ``` for(0..7){@b=(1)x8;@b[$_+3..$_+7]=(3)x4;@b[7-$_..10-$_]=(2)x4;for$c(0..2){$b[$c+8]=max$b[$c+8],$b[$c];$b[5-$c]=max$b[5-$c],$b[13-$c];}push@a,sprintf("%-8s",join("",@b[3..10])=~tr[123][ /\\]r)x6;}say for@a,@a,@a ``` Readable: ``` for(0..7){ @b=(1)x8; @b[$_+3..$_+7]=(3)x4; @b[7-$_..10-$_]=(2)x4; for$c(0..2){ $b[$c+8]=max$b[$c+8],$b[$c]; $b[5-$c]=max$b[5-$c],$b[13-$c]; } push@a,sprintf("%-8s",join("",@b[3..10])=~tr[123][ /\\]r)x6 } say for@a,@a,@a ``` Procedurally generates each segment, then repeats the pattern 6 times, then outputs the total result 3 times. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 37 bytes Uses [CP-1252](http://www.cp1252.com) encoding. ``` 24FNU48FXXN+XN-<)8%3›J" \// \/\"è?}¶? ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MjRGTlU0OEZYWE4rWE4tPCk4JTPigLpKIiBcLy8gXC9cIsOoP33Ctj8&input=) **Explanation** Uses the mod-8 trick expertly explained in [Jakube's pyth answer](https://codegolf.stackexchange.com/a/99209/47066). ``` 24F # for N in [0 ... 23] do: NU # save N in X 48F # for N in [0 ... 48] do: XXN+XN-<) # push [X,X+N,X-N-1] 8% # mod each by 8 3› # compare with 3 J # join " \// \/\"è? # index into string and print } # end inner loop ¶? # print newline ``` [Answer] # [SOML](https://github.com/dzaima/SOML), 106 [bytes](https://github.com/dzaima/SOML/blob/master/chartable.md) ``` 3{"\\\\////”6*p" \\//// ”6*p" //// ”6*p" ////\\ ”6*p"////\\\\”6*p"\// \\\”6*p"\\ \\”6*p"\\\ //\”6*p ``` a non-competing version using a function that I've only recently added: (~~83~~ ~~67~~ 66 bytes) explanation: ``` →$\\→#////→@”6*p"→~3{"##@~ #@ ~$@$~ @# ~@##~\//$#\~#$$#~#\$//\~” →$ in the further code replace "$" with " " \\→# replace "#" with "\\" ////→@ replace "@" with "////" ”6*p"→~3{"##@~ #@ ~$@$~ @# ~@##~\//$#\~#$$#~#\$//\~” the code to exchange stuff in so that results in: ”6*p"→~3{"\\\\////~ \\//// ~ //// ~ ////\\ ~////\\\\~\// \\\~\\ \\~\\\ //\~” ”6*p"→~3{"A~B~C~D~E~F~G~H~” modified version of the program (removing "/","\" and " " and replaced with A,B,C,ect.) ”6*p"→~ replace in the further program "~" with ”6*p" which is: ” end string 6* repeat the last thing in stack 6 times p output the result " start a string resulting program: 3{"A”6*p"B”6*p"C”6*p"D”6*p"E”6*p"F”6*p"G”6*p"H”6*p"” shortened example: 3{"A”6*p"B”6*p"H”6*p"” 3{ repeat 3 times "A” push "A" (original: "\\\\////") 6*p output it multiplied by 6 "B” push "B" (original: " \\//// ") 6*p output it multiplied by 6 "H” push "H" (original: "\\\ //\") 6*p output it multiplied by 6 "” push an empty string (shorter to do ~” than ”6*p) ``` [Answer] # Ruby, 75 bytes ``` 1152.times{|i|$><<"\\/ /\\\\ /"[(i+j=i/48)/4&1|(i-j)/2&2|j&4]+$/*(i%48/47)} ``` Better golfed, using a single 8-byte string lookup indexed by j&4 in addition to the other parameters, rather than a modifiable 4-byte string. # Ruby, 81 bytes ``` 1152.times{|i|j=i/48%8;$><<"\\#{'/\\'[j/4]} /"[(i+j)/4&1|(i-j)/2&2]+$/*(i%48/47)} ``` Prints the diagonal stripes character by character. The correct character is selected from a string of 4 characters depending on the presence / absence of each strand. The overlap character is varied depending on which strand is on top. **Commented** ``` 1152.times{|i|j=i/48%8; #Iterate through all printable chars. j is line number. $><<"\\#{'/\\'[j/4]} /"[ #Print a char from "\/ /" if j/4 even or "\\ /" if odd. character changes depending which strand on top. (i+j)/4&1|(i-j)/2&2]+ #Print \ if (i+j)/4==0, / if (i-j)/2&2 >0, space if both false. As above if both true. $/*(i%48/47) #If on column 47, print a newline. } ``` [Answer] # Perl, ~~132~~ ~~131~~ 113 bytes ``` @a=((0)x4,1..4);map{say+(map$a[7-$_]?$a[$_]*$r?'/':'\\':$a[$_]?'/':$",0..7)x6;push@a,shift@a;$_%4||($r=!$r)}0..23 ``` Ungolfed: ``` use strict; use warnings; use feature 'say'; my @a = ((1) x 4, (0) x 4); # print '\' if true my @b = ((0) x 4, (1) x 4); # print '/' if true my $r = 0; # print '\' over '/' if true for (0 .. 23) { say((map { $a[$_] ? ($b[$_] * $r ? '/' : '\\') : ($b[$_] ? '/' : ' ') } 0 .. 7) x 6); unshift(@a, pop(@a)); # circular shift to left push(@b, shift(@b)); # circular shift to right $r = !$r if !($_ % 4); # change print priority } ``` [Answer] # Python, ~~245~~ ~~236~~ ~~234~~ ~~233~~ ~~230~~ ~~216~~ ~~212~~ ~~198~~ 195 bytes OK, longer than my last (and any other) answer but would be interested in feedback on the approach. ``` for a in(40,4496,6200,5456,3240,1188,720,228)*3:print((`a%6561/2178`+`a%2178/729`+`a%729/243`+`a%243/81`+`a%81/27`+`a%27/9`+`a%9/3`+`a%3/1`)*6).replace('0','\\').replace('1','/').replace('2',' ') ``` **Edit** -9 due to @nedla2004 being more on the ball than me -2 by taking the lambda outside of the loop and so losing 2 indent spaces -1 by using `in' '*3` instead of `in 0,1,2` since I don't use `h` anyway. it's just a counter. -3 Why, why, why did I leave a newline and 2 indents between the second for and the print??? It's late. Will revisit tomorrow. -14 Can actually lose the lambda completely and just include the base 3 decoder directly after the print statement. Looks messy but after all, this is code golf :) -4 No point setting a variable for the integer list. Just use it directly in the second for loop. -14 and no point using the outer loop. Just multiply the integer tuple by 3 (shamelessly stolen from @nedla2004 to get under 200 :)) -3 Saved 3 by making \=0, /=1 and space=2. This makes the integer list shorter as three of the base 3 numbers now have leading 0's **How it works (and it does)** Since only 3 characters are used: 1. l is a list of the 8 repeating patterns as integer equivalents of their base 3 representation assuming that " "=0, "\"=1 and "/"=2 2. ~~The lambda~~ The first code after the print statement is a lightweight converter from integer to a base 3 string 3. The first loop loops 3 times and the second prints each line with the base 3 characters multiplied by 6 and replaced with /,\ or space. I'm sure I could use a regex instead of the nested replace() but I'm too tired to try right now. This was just an experiment and longer than my previous Python effort but have posted just for any comments on the approach (and also because I have never worked in base 3 before and I quite enjoyed working out the converter). [Answer] # Haskell, 96 bytes ``` f n=n`mod`8`div`4 putStr$unlines[["\\ //\\ \\/"!!(f(x-y)+2*f(x+y)+4*f y)|x<-[0..47]]|y<-[0..23]] ``` [Answer] ## Ruby, 135 bytes `puts [3320,1212,720,2172,6520,4144,2920,3184].map{|e|(e.to_s(3).rjust(8,"0").gsub("0"," ").gsub("1","\\").gsub("2","/"))*6+"\n"}.join*3` The number array corresponds to each component of each line, translated to base 3: = 0, `\` = 1, `/`= 2, then converted to decimal. The gsub() calls are too big, though. And, just now, I saw @ElPedro's answer. :-( Just coincidence. [Answer] # PHP 157 126 bytes Taking the changes @Titus lists in the comments... I'm annoyed I missed point 1 which I should have caught, but I didn't know strtr() existed which is where most of the savings come - nice work Titus! NEW: ``` while($i<32)echo$b=strtr([3322,' 322 ','0220',' 223 ',2233,12013,3003,13021][$i++%8],[' ','\\','//','\\\\']),"$b$b$b$b$b\n"; ``` OLD: ``` <?$a=[zzyy,' zyy ',syys,' yyz ',yyzz,xysxz,zssz,xzsyx];while($i<32){$b=$a[$i++%8];$b=str_replace([z,x,y,s],['\\\\','\\','//',' '],$b);echo"$b$b$b$b$b$b ";} ``` Because all the backslashes need escaping it saves quite a bit of space to pack them up as different character and replace them for output, and then once I'm calling str\_replace() it makes sense to use it as often as possible. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~36~~ 34 [bytes](https://github.com/abrudz/SBCS) ``` '\/ /\\ /'[(2⊥3<8|⊣,-⍨,+)/¨⍳24 48] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@q8foK@jHxCjoq0drGD3qWmpsY1HzqGuxju6j3hU62pr6h1Y86t1sZKJgYhH7H6jhfxoA "APL (Dyalog Unicode) – Try It Online") Because I can't tolerate an APL answer doing so badly. This is almost a port of [Angs' Haskell answer](https://codegolf.stackexchange.com/a/99356/78410). Uses `⎕IO←0`. ### How it works ``` '\/ /\\ /'[(2⊥0⌷2 4⊤⊣,-⍨,+)/¨⍳24 48] ⍳24 48 ⍝ Construct a matrix containing pairs of (0..23),(0..47) (...)/¨ ⍝ Map over each pair... ⊣,-⍨,+ ⍝ Given two numbers x and y, construct [x,y-x,x+y] 2 4⊤ ⍝ Convert the three numbers to mixed base; ⍝ equivalent to n → [n%8/4,n%4] in Python 2 0⌷ ⍝ Extract first row (n%8/4) 2⊥ ⍝ Convert base 2 to integer '\/ /\\ /'[...] ⍝ Convert each number in the entire matrix with ⍝ the character at that index ``` [Answer] # Python 2, ~~169~~ ~~161~~ ~~165~~ ~~160~~ ~~155~~ ~~154~~ 152 Based on @ElPedro's answer, with small improvements. To see the explanation, see [their answer](https://codegolf.stackexchange.com/a/99211/59363). This is Python 2, even though there seems to be parenthesis near the `print`. ~~Saved 8 bytes by using a variable for `replace`.~~ That works only for strings, and using a function for it would be longer. Saved 4 bytes by seeing that @ElPedro realized that they did not need l, and I did not either. Saved 5 bytes by not flipping the `range(8)`, and instead of using `+=` to append to r, adding r to the end of the new digit. Try it using [repl.it](https://repl.it/ETeL/6) Saved 5 bytes by stealing @ElPedro's new list of values. Saved 1 byte by removing the space between the `in` and `(`. Saved 2 bytes by removing the variable a. ``` for x in(40,4496,6200,5456,3240,1188,720,228)*3: r='' for i in range(8):r=`x/3**i%3`+r print(r*6).replace('0','\\').replace('1','/').replace('2',' ') ``` [Answer] # PHP, 184 bytes ``` <?$p=['1111////',' 11//// ',' //// ',' ////11 ','////1111','1// 111','11 11','111 //1'];for($j=0;$j<3;$j++)for($i=0;$i<8;$i++)echo str_replace(1,'\\',str_repeat($p[$i],6))."\n"; ``` **Output:** ``` C:\PHP>php make-me-a-blanket.php \\\\////\\\\////\\\\////\\\\////\\\\////\\\\//// \\//// \\//// \\//// \\//// \\//// \\//// //// //// //// //// //// //// ////\\ ////\\ ////\\ ////\\ ////\\ ////\\ ////\\\\////\\\\////\\\\////\\\\////\\\\////\\\\ \// \\\\// \\\\// \\\\// \\\\// \\\\// \\\ \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\ \\\ //\\\\ //\\\\ //\\\\ //\\\\ //\\\\ //\ \\\\////\\\\////\\\\////\\\\////\\\\////\\\\//// \\//// \\//// \\//// \\//// \\//// \\//// //// //// //// //// //// //// ////\\ ////\\ ////\\ ////\\ ////\\ ////\\ ////\\\\////\\\\////\\\\////\\\\////\\\\////\\\\ \// \\\\// \\\\// \\\\// \\\\// \\\\// \\\ \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\ \\\ //\\\\ //\\\\ //\\\\ //\\\\ //\\\\ //\ \\\\////\\\\////\\\\////\\\\////\\\\////\\\\//// \\//// \\//// \\//// \\//// \\//// \\//// //// //// //// //// //// //// ////\\ ////\\ ////\\ ////\\ ////\\ ////\\ ////\\\\////\\\\////\\\\////\\\\////\\\\////\\\\ \// \\\\// \\\\// \\\\// \\\\// \\\\// \\\ \\ \\\\ \\\\ \\\\ \\\\ \\\\ \\ \\\ //\\\\ //\\\\ //\\\\ //\\\\ //\\\\ //\ ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 89 bytes ``` 0..23|%{$y=$_ -join(48..94|%{('\/'[$y%8-lt4]+'\/ ')[(($_+$y)%8-lt4)+2*(($_-$y)%8-ge4)]})} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPz8i4RrVapdJWJZ5LNys/M0/DxEJPz9IEKKihHqOvHq1SqWqhm1NiEqsN5Cqoa0ZraKjEa6tUakKENbWNtEAiuhCR9FQTzdhazdr//wE "PowerShell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes ``` •M;(Ч0—øθε;û…•…/\ Åв8ôJ6×3и» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcMiX2uNwxMOLTd41DDl8I5zO85ttT68@1HDMqAMkNSPUTjcemGTxeEtXmaHpxtf2HFo9///AA "05AB1E – Try It Online") [Answer] # [Underload](https://esolangs.org/wiki/Underload), 130 bytes ``` ((\\\\////)( \\//// )( //// )( ////\\ )(////\\\\)(\// \\\)(\\ \\)(\\\ //\)()(::**:*S( )S)(:(~*a(a)~*^*)~a*^):*:*:*^!^)::**^ ``` [Try it online!](https://tio.run/##JcsxDoBACATA3ldgBzT2fONaQnKJdkYTE9v7Oi7e0swGeK/9eM6775nMjmyIME0QRD9KBXdowl3YazXlRMWS1xMkbKZq2niRhsJDO3cZGiqja4hpTawQDiPzAw "Underload – Try It Online") [Answer] ## Batch, 152 bytes ``` @call:l @call:l :l @for %%s in (\\\\//// " \\//// " " //// " " ////\\ " ////\\\\ "\// \\\" "\\ \\" "\\\ //\")do @echo %%~s%%~s%%~s%%~s%%~s%%~s ``` String processing in Batch sucks, so this is probably the best approach. The call-and-fall-through is very slightly shorter than a nested `for` loop. At least I don't have to quote my backslashes! [Answer] # APL, 110 bytes I'm new to APL, so this is a simplistic solution. ``` A←48⍴'\\\\////'⋄B←48⍴' \\//// '⋄C←48⍴' //// '⋄F←48⍴'\// \\\'⋄G←48⍴'\\ \\'⋄24 48⍴A,B,C,(⊖B),(⊖A),F,G,⊖F ``` Here's my approach: note that after the first 8 lines of the blanket, the pattern repeats itself. Therefore I only need to define the first 8 lines, and then I can repeat them 3 times. Also note that each line repeats itself after the first 8 characters. Therefore to define a single line I only need to define the first 8 characters and then repeat them 8 times. Here's an ungolfed solution: ``` A←48⍴'\\\\////'⋄ ⍝ set A to a 48 element vector (48⍴) of repeated '\\\\////'s B←48⍴' \\//// '⋄ ⍝ set B to a 48 element vector (48⍴) of repeated ' \\//// 's C←48⍴' //// '⋄ ⍝ ... D←48⍴' ////\\ '⋄ ⍝ Note that this is actually the reverse of vector B E←48⍴'////\\\\'⋄ ⍝ Note that this is actually the reverse of vector A F←48⍴'\// \\\'⋄ G←48⍴'\\ \\'⋄ H←48⍴'\\\ //\'⋄ ⍝ Note that this is actually the reverse of vector F 24 48 ⍴ A,B,C,D,E,F,G,H ⍝ Make a 24 by 48 character matrix (24 48⍴) by concatenating A,B...H ⍝ and repeating the string until the matrix is full ``` I noted above that D is the reverse of B, E is the revers of A, and H is the reverse of F. In my actual code, I take advantage of this by not defining D,F, or H and using the reverse function `⊖`: `24 48⍴A,B,C,(⊖B),(⊖A),F,G,⊖F` [Answer] ## Ruby, 132 bytes ``` puts Zlib.inflate Base64.decode64 "eJzt0bENADAMAsGeKdggC/3+cyQRC+A2ipuT3RgJgHWGUjm6VXb2Vjn/3KpJ/qtIPlp1v+XSKZKPVk3y/x5+D6/3sAEUXQ+Q" ``` very simple answer. [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0`, 97 bytes ``` say s/\d(.)/$1x$&/ger x6for('4\4/| 2\4/ | 4/ | 4/2\ |4/4\|\// 3\|2\4 2\|3\ //\\'=~/[^|]+/g)x3 ``` [Try it online!](https://tio.run/##DYpBCsIwEEWvMotiW8T8tkndeYSewFEQrEUQUxIXKQwe3XE278HjrXN6jar5tlEG3xvXoupLtcMyJyrHR0xNHThAaDCSEBlNAQOTBAQWhhXPYoNN4pkIYK5PX5yvctljaYtX/cX184zvrIdpdH3nuj8 "Perl 5 – Try It Online") ]
[Question] [ In this challenge, the goal is to find the values of some variables after a number of assignments are done. An example input: ``` a = 5 b = 4 c = a = b a = 2 b = a ``` This would result in: ``` a = 2 b = 2 c = 4 ``` Each statement will be one of the following: * A variable name (`[a-z_]+`) * A numeric value (`[0-9]+`) * An assignment operation, with a variable name on the left and a statement on the right You may assume that the input will be a list of statements, formatted however you want. Variable names will have differing lengths (if you need a hard value to gold within, assume 16 chars max). Note that statements can contain more or less than one assignment (such as `a`, `23`, or `a = b = c = 4`), and that variables can appear that are never assigned to. Assume no undefined variables are used as values in an assignment (such as `a = undefined_variable`), and that no variable will be on both sides of an assignment (such as `a = a` or `a = a = 1`). You can take input any way you wish (such as a string with a character to delimit statements, a list formatted as `[["a", 5], ["b", "a"]]`, etc.), and output can be in any consistent format (such as a hash map of names to values, or a list of values in the order that the variables first appeared). Test cases: ``` a = 5 -> a = 5 b = 512, c = a = 2 -> a = 2, b = 512, c = 2 def, 2, e = 8, 101 -> e = 8 -> a -> fgh = 4, i = 3, fgh = i -> fgh = 3, i = 3 j = k = l = m = n = 14 -> j = 14, k = 14, l = 14, m = 14, n = 14 s = t = u = 6, t = v = 7 -> s = 6, t = 7, u = 6, v = 7 o = 3, o = p -> [undefined] q = r -> [undefined] w = w = 2 -> [undefined] x = 4, x = x -> [undefined] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer per language wins! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 [bytes](https://github.com/abrudz/SBCS) ``` {n⊣⍵{0::0⋄⍵⍎⍺}¨n←⎕NS⍬} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzrvUdfiR71bqw2srAwedbcAmY96@x717qo9tCLvUduER31T/YIf9a6p/Z8G4gGlupoPrTd@1DYRKBMc5AwkQzw8g/8DaedI9eLEnBJ1oCmpeYlJOanBjj4hXLFJ@RWZeekK@XlcXHnFQDPSFNQTgZSpuoJ6EpA2AdLJQBoklqQOkTOCyiWqA7XoaWg86lqkA7Ra89AKkHN8FA6tN9Lk4tKAmgRSmQw1CcY2hpqUAuKra@IyA2jEo64mHfVEkJJHvVtQpdRTUtOA5oBckwo0xwJIGxoY4jQNAA "APL (Dyalog Unicode) – Try It Online") Takes a list of statements in the form of `a←b←3`, and returns a namespace which is essentially a hashmap of variable names to values. You can't print all the contents of it directly, but you can inspect individual variables like `ns.somevar` or list all names using `ns.⎕NL ¯2`. Oh, and APL doesn't have any alphanumeric-only keywords! ``` {n⊣⍵{0::0⋄⍵⍎⍺}¨n←⎕NS⍬} ⍝ ⍵: list of statements n←⎕NS⍬ ⍝ Create an empty namespace ⍵{ }¨ ⍝ For each statement... ⍵⍎⍺ ⍝ Try executing the statement inside the namespace 0::0⋄ ⍝ ignoring any errors (undefined name) n⊣ ⍝ Return the populated namespace ``` [Answer] # [Python ~~3~~ 2](https://docs.python.org/2/), ~~80~~ ~~75~~ 69 bytes *-5 bytes thanks to @Sisyphus* *-6 bytes thanks to @xnor* ``` g={} for s in input(): k=s.pop() for n in s:g[n]=g.get(k,k) print g ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P922upYrLb9IoVghMw@ICkpLNDStuBSybYv1CvILNDS5FECyICmFYqv06LxY23S99NQSjWydbE2ugqLMvBKF9P//o6PVE9V1FExjdaLVk4AMExAjGcgACwOFQHwQ0wimAsiLjQUA "Python 2 – Try It Online") Takes input as a list of lists of terms, returns a dict of variable name to value. ## Explanation ``` def f(x,g={}): # Save a few bytes by defining g as a default argument. for s in x: k=s.pop(-1) # Take the last term, which is the value we'll be using. for n in s: # For all *other* values: g[n]=g.get(k,k) # .get(k, k) means "get the value called k, if not found use k raw" (numbers will not be found) return g ``` Note that it never actually differentiates between numbers and variables, just trusts that the input won't try to assign to a number. This means you *can* actually use it to assign to a number - this input: ``` [9, 5], ['b', 9], ['c', 'a', 'b'], ['a', 2], ['b', 9] ``` Will result in this output: ``` {9: 5, 'b': 5, 'c': 5, 'a': 2} ``` [Answer] # [J](http://jsoftware.com/), 66 bytes 33 bytes for the `_ =: 1` special case … ``` (rplc&('a0';'_')@}.~&_6;".)&>@r0[0!:110@rplc&('_';'a0')[r0=:4!:5@1 ``` [Try it online!](https://tio.run/##ZY87D4IwEID3@xWFgaOJkhYBTY2GxMTJyZWBIIKAz@AjLvrXkWs0Ghn65R5f79qqMR3M2UQxZD0mmGpP32Gz5WLe2PVpl1o2JgLHGCMPH87TioOx6XBrGtYiEoaSUoRvLW6tVuVRLSbKM5QfyoZDlhZHljOMaccAP7mtV7Xte3mhjg/8v7XSdelCSkFCcL8WrrO8Oy1JC3AhI3cEUsgfP@nY@aYg0YNSv@2Tlz@XKipsCTvCnnAgSK8z7kx1/ZkrIQAd3whD4M0L "J – Try It Online") ### How it otherwise works ``` (_6&}.;".)&>@r0[0!:110[r0=:4!:5@1 ``` It's a mess! `m!:n` are special functions, that do stuff depending on `m` and `n`. * `r0=:4!:5@1`: "4!:5 (1) produces a list of global names assigned since the last execution of 4!:5." Store as `r0`, so we can execute it again cheaply while it won't be overwritten. * `0!:110` execute input string as script, ignoring any output/errors (so predefined values won't cause harm.) * `r0` execute `4!:5@1` again, get boxed list of changed variables * `&>` unbox and … * `".` execute each variable to get its value * `_6}&.` drop last 6 characters from the variable (which contain the namespace `_base_`.) * `;` join name and result together [Answer] # JavaScript (ES6), 81 bytes Expects a string in the format described in the challenge. Returns an array of `[name, value]` pairs. ``` s=>Object.keys(o={},eval(s.replace(/[_-z]+/g,"o.X$&"))).map(k=>[k.slice(1),o[k]]) ``` [Try it online!](https://tio.run/##lZHRToMwFIbvfYqmMaaNXRG2OW/YK3hrQgjpWGFAoYQiiRqfHQ@FRaneSPLn9PznO3@bUIpBmLQr2n7T6LMcs3A04fH5VMq055V8M0SHH59MDkIRwzvZKpFK4kXJ5j2@93KGNX@5vcOUUl6LllThMaq4UQVAPmU6quKYjqlujFaSK52TjGCBQrTH6PdHKfI8ZMc3zs5pMv2AoRQOExFgdweGKypwM84yYxMlYfjEkP/grzKs7e789cwfOy4u8L/wLL/ApTuGCihbhua@wAs@t9tl7C6XYFYgBapBDcjf4etdpW2ZRaaqllovdcbdUANuD3oFPTJ7HEAHPIeab/vArpAF3KAkaTvd6yRxf/YctBqPXw "JavaScript (Node.js) – Try It Online") ### How? We define an object `o` initially empty and add the prefix `"o.X"` to all variable names in the input string. Example: ``` /* before */ "s = t = u = 6, t = v = 7" /* after */ "o.Xs = o.Xt = o.Xu = 6, o.Xt = o.Xv = 7" ``` We need the leading `X` to prevent the reserved property [`__proto__`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) from being overridden this way. Provided that the input string is in the expected format -- which is guaranteed by the challenge rules -- the transformed string can be safely `eval()`'uated. We then iterate on the keys of `o` to build a list of pairs consisting of 1) the key name without the leading `X` and 2) the final value associated to the key. Without the `__proto__` issue, this could be done in just 45 bytes without any post-processing: ``` s=>(eval(s.replace(/[_-z]+/g,"o.$&",o={})),o) ``` [Try it online!](https://tio.run/##lVHbToQwEH3nKyaNMW2cBWFvvuCPGEMqW1iwSwlFHjR@Ow6FjVJ9keRkOufWJtRykDbvqrbfNOakxiIdbfrI1SA1t2GnWi1zxaOnbPP@fBeVyEx4c8vQpB@fQqARY24aa7QKtSl5wZmEFPYMfn9CQBSBkwMv8zKRcYKQ02FyJMzPkLhyJX7HSRU4uRSJDwjxfbzqcLSf@euZPzK@XbJ/2YvyTJfuECoaW4R5r9hin9ftIvvhmshXgiZcCA0h3rHrXbVb0VmmqZd5WeZs90stsT3hjXBAdxwIRzaX2m/6iFeTMwQByf25smAaBYWstPW7s6ztTG@yzP//c/dKHr8A "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~55~~ ~~51~~ 43 bytes ``` ($=<||>;($@#2=#/.$)&~Fold~Reverse@#&/@#;$)& ``` [Try it online!](https://tio.run/##TYzNDoIwEITvPkUTCMGEiCCoCWJ60bPRJ6hQBOVHAbnw8@q43b14mHRmvtkWok1lIdosEnMSzqYeHobhGJg619xQs1f60pjOVR5PV9nJupFcM2yuBVDPlzorW57wU5RWUE@3SJRTv@h7wZjFmD@OFoQ7BN9xwbM@Ak/QJRjLBIEq1CsR7tE7a4dGgp7kkQLzkGW426CnPqPRE8ALlIMKUKmGjkewgdCCvni9xWuVO8w7GlV/Xyv/ZozAB0KtwmKcfw "Wolfram Language (Mathematica) – Try It Online") -8 thanks to w123 [Answer] # [Python 3.9rc2](https://www.python.org/downloads/release/python-390rc2/), 67 bytes ``` def f(x): g={} for*u,k in x:g|={n:g.get(k,k)for n in u} return g ``` No TIO link, as TIO doesn't support Python 3.9. Borrows ideas from [Artemis' answer](https://codegolf.stackexchange.com/a/211447/48931), with the following improvements: * We can use an iterable unpack `*u,k` in the for loop. * In Python 3.9 we can merge dicts using `a|=b`, which is much shorter than the old `a.update(b)` and `{**a,**b}` methods. [Answer] # [Python 3](https://docs.python.org/3/), ~~159~~ ~~141~~ ~~152~~ 128 bytes ``` def f(s): g={} for k in s: if'='in k: *v,l=k.split('=') for r in v: try:g[r]=int(l) except:g[r]=g[l] return g ``` [Try it online!](https://tio.run/##ZY1BCsMgEEXX4yncqaUUSneBOUmaRZOolYgRY0JD6dmtWgqF7v5/8z7j93if3SWlUSqq@CIaAhqfLwJqDnSixtElIzCKIctlKgUO29HidFq8NZHngyiwDEIZbNWBGPZGt6FD4yK3VQH5GKSPH6xb2xEIMq7BUZ18KJ7ijLEa8UxuWFMm31dXx4QQhPzIPRmy2uOIw5@Y3g "Python 3 – Try It Online") -18 bytes [thanks to](https://codegolf.stackexchange.com/questions/211446/find-the-result-of-some-assignment-statements/211448?noredirect=1#comment497987_211448) [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) +11 bytes [thanks to](https://codegolf.stackexchange.com/questions/211446/find-the-result-of-some-assignment-statements/211448?noredirect=1#comment498204_211448) [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for pointing out a bug -24 bytes [thanks to](https://codegolf.stackexchange.com/questions/211446/find-the-result-of-some-assignment-statements/211448?noredirect=1#comment498207_211448) [ovs](https://codegolf.stackexchange.com/users/64121/ovs) Python really isn't my strong suit for golfing :/ Note the use of tabs rather than spaces, so the indentation levels are still a single byte each. Takes input as a list of lines with assignments separated by `=` (no spaces) and returns a dictionary of variables and values [Answer] # Batch, ~~331~~ ~~317~~ 72 bytes ``` @setlocal @for /f "delims==" %%a in ('set')do @set %%a= @set/a%* @set ``` Takes a comma-separated list of assignments on the command line. Explanation: ``` @setlocal ``` Don't modify the parent environment. ``` @for /f "delims==" %%a in ('set')do @set %%a= ``` Delete all variables, including predefined variables such as `PATH`. We're only using shell builtins, so we don't need them. ``` @set/a%* ``` Evaluate the assignments. ``` @set ``` List all of the resulting variables. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 183 bytes ``` T =TABLE() N X =INPUT :F(O) R X SPAN(&LCASE '_') . Y (' ' | RPOS(0)) . Z ='T<"' Y '">' Z :S(R) EVAL(X) :(N) O A =CONVERT(T,'ARRAY') I I =I + 1 OUTPUT =A<I,1> ' = ' A<I,2> :S(I) END ``` [Try it online!](https://tio.run/##FY5Ni8JADIbPmV8RPJgEZVmXRaE4hVl3FgbKTJmO0noRPIse/Dj537vp4YHkCeR979fb@Xb5HkcoaIv7aTyLidCjDbHdF6j@OInJKrrWRZ43O9d5pBMJfuCATEj4xtymjj9lcke0VLYz0iPNasIjVB1nMeAPruFeoOIoJoFDu0vx4HPhsiSXsxtITICgybjAlYG0L9oArduG5arWHKtMy1c9/QxifPwdx7v6h/JU1maaXsrmHw "SNOBOL4 (CSNOBOL4) – Try It Online") Takes input separated by newlines with spaces between the `=`, and returns in the same format. [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` def f(a) a.reduce({}){|m,x|*r,k=x r.map{|y|m[y]=m[k]||k} m} end ``` [Try it online!](https://tio.run/##jY/NboMwEITvfoqVOBAqK4oJ@bnwJMgHfkybOEYRCVEQ5tnprjFV2kNbDjO7K77RuO2KfpoqVUO9yiOWr1tVdaVaDWM0WMOf9q3lOn2ydm3y62B7a7JepibT0lo9MjMy1VTTFeksC/OQw07KCH77AsghhR3zTEGMiCWHLCxxdiHxj5CZiTkUhAocStqXDKwfUsCcojDgSJPYiJecABQyR8/81XJhhpF9Pe4fzCtQv39gk8R1OuG0ddN8xcOcFgAesNeWw4lsgc/0kya5kBiSBkUk3550RkYkHLT3i3fjvXG@hN4o5U7SoexdH7c@UA4@OIAbQnsOd7QDh27eHrSx6RM "Ruby – Try It Online") I rarely golf in Ruby (tips appreciated) but I use it for work, and I liked [Artemis's clean answer](https://codegolf.stackexchange.com/a/211447/15469) so much that I decided to see what a translation into ruby would look like. [Answer] # [Scala](http://www.scala-lang.org/), 98 bytes ``` _./:(Map[String,String]()){case(m,a::b)=>val x=m.getOrElse(a,a);(m/:b.map(_->x))(_+_)case(m,_)=>m} ``` [Try it online!](https://tio.run/##dY/LboMwEEX3fMWIlUchpPQtqkHqortWXXTZRsgQQ11hgrCLkKJ8OzWGplIqvJi5vveMHzrnFR/22ZfIDbxwWYPojah3Gh6bBg5exysoYniW2ry78mZaWZfbLVBi@WbeB7MNNKThJmb/E4Z4yLkWTAU8jjOkZDy6JxWWwry2T5WNeMDxgalNnIWKNyxdJz0iS1cpzpOpHVPHwduJAozQhukYpvMRCBorTFUzf32@Pmp/VTAdWlSFuqmkYb71MDT78VPTbb8BWX8yRvzEtKITrRaI6Hkw3e77vpUAGd1El07lxGlSNsNzzj7b9YkQdO96dBEtThTlJ107Jenq5MhFXpOhb7p12hVDHd0t4n/BcfgB "Scala – Try It Online") The statements have to be reversed (`List("2","b")` for "b=2"). The solutions below can't handle empty input. # [Scala](http://www.scala-lang.org/), ~~96~~ 94 bytes ``` _./:(Map[String,String]()){(m,l)=>val x=m.getOrElse(l.last,l.last);(m/:l.init.map(_->x))(_+_)} ``` [Try it online!](https://tio.run/##dY/NTsMwEITveYqVT161dQn/CtpIHLiBOHCEKnJTJxg5aVQvVaSqzx7cpCqiKD54Pu@Md22fa6e79fLL5Awv2tZgWjb1ysNj08Au2moHRQLP1vN7v73xxtblYgGUhnxzPE@PZaAuU/NE/nck4k5WU4eUHnq2VKnS8OvmyXkjnXLa83QQfJDVPHHK1pZVpRuZzdIWUWaTDPddtDIFsPEsfQJDbwSCJgC7WorZ@fqoxaSQXoVopXzjLEsRaqh4ffjQMOGPSycTEaMIhnFCiIAAS7qJL3vKSdNAwcPzXHhnr0PC0H2v8UU8eqMoP@m6J0tXp4odzXti@qbbnpm2dDea1L/OvvsB "Scala – Try It Online") Takes a `List[List[String]]` and returns a `Map[String,String]` ## Scala, 86 bytes This is shorter, but the statements are reversed ``` _./:(Map[String,String]()){case(m,a::b)=>val x=m.getOrElse(a,a);(m/:b.map(_->x))(_+_)} ``` [Try it online!](https://tio.run/##dY/NboMwEITvPMXKJ69CSOm/qBaph95a9dBjGyFDDKUCgvAWIUV5duqYqFFT4YN3PN941zaZqtS4Tb90xvCiygb0wLrZGHhsW9h5vaogj@C5NPzutjfuyqZYr4Fim2@PZ/9oA41JsIrkfyIRd5kyWta@iqIUKT60HqgOCs2v3VNlkfIVPsh6FaVBrVqZLOMBUSaLBPejt9E5sDYsTQRTTwSC1gquGimW5@ujEYtcmsBG68C0VclSWA8D3h4@Mk34Q@kEO93rzmhE9DyYxgohrARI6Sa8dCojRZOyDM9z9r2uTglN966GF@Hsjbz4pGunSrr6dcrZvCGmb7p1mqmnu9mkOpH9@AM "Scala – Try It Online") [Answer] # JavaScript, ~~52~~ 88 bytes +36 bytes to handle a single fecking edge case :\ ``` a=>a.map(a=>a.map(k=>o[0+k]=o[0+v]|v,v=a.pop()),o={})&&JSON.stringify(o).split`0`.join`` ``` [Try it online!](https://tio.run/##RYlNDsIgGETvwqKBiKQaXeIBXOjCJSGA/Qtt5SOlITHq2SsYo5uZ92Z6E02oJuvntYO6WVq@GH4w7GY8/sHADyDK1SB5riifkUZumAePCaHAHy9SFMfL@cTCPFnX2faOgbDgRzvrUrMerNN6qcAFGBs2QodbLAQyiO4lFeiK6C53hWjekmdLtP2@iTPVn1TKTzCDUohusjfp/29SErK8AQ) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 85 bytes ``` G`= +`=(.+(=.+)) $2¶$1 +rm`(^\4=(.+)¶(.+¶)*?.+=)(.+)$ $1$2 +m`^(.+)=.+¶((.+¶)*\1=) $2 ``` [Try it online!](https://tio.run/##LYzBDoIwAEPv/Y6ZbG4hboJ6aTz6AV4J2VRQVDgg@ml8AD82XeKlafuaDvXY9iEu5NGbePCE9pSZlsy0UhBunoSFHjovqzJPRM3TT@dJLfeZpkqNgLDCQXe@SpEJy/@otEw3MQYWwImFdebMQAdc6sY4U3Nn7MoCAWiuN@am5dok1wJ3Pvhkx542B14c@ebGjPxw@wU "Retina 0.8.2 – Try It Online") Link includes test suite that converts the input from comma separated to newline separated assignments with no spaces. Explanation: ``` G`= ``` Ignore statements that have no assignments. ``` +`=(.+(=.+)) $2¶$1 ``` Split up assignment chains into individual assignments. ``` +rm`(^\4=(.+)¶(.+¶)*?.+=)(.+)$ $1$2 ``` Substitute the values of variables used on the right-hand side of assignments. The matching is performed right-to-left so that the most recent value is used. ``` +m`^(.+)=.+¶((.+¶)*\1=) $2 ``` Remove superseded assignments. [Answer] # Java 10, 137 bytes ``` a->{var r=new java.util.TreeMap();for(var p:a)for(int l=p.length-1,i=l;i-->0;)r.put(p[i],p[l]instanceof Long?p[l]:r.get(p[l]));return r;} ``` Input as a Object-matrix (variables as Strings, values as Longs), output as a sorted HashMap. [Try it online.](https://tio.run/##jVNLb9swDL7nVxA62agsxF2zDfGSYccBfRzaW@aD4siuXEXWZDlZYfi3Z5SdIC261jtQJumPj48SS77jUbl5OmSK1zXccKnbCYDUTticZwJuvQlQIo41Tir2YIW44ebb3boUmaMwfJeQBYO2Slcp8DDBsG6CR@24kxncgoYFHHi0bHfcgl1osX@bNQiTvLKBR5g5D72OrYBaGKaELtxjFFO5UImMouU0CS0zjQvMSqbUrFQqNRbTmahyuK508d375pYVwmNUGoaJFa6xGmzSHRLfnGnWCps79rir5Aa2OILg3lmpi57IwN@J2gW@5TPJtiWc0Nl1R1uyJvSqVzJCvRcd3kLt8vQfja7rx/JeNgTN4suXadD4OGQjcl9oCBKEfvVKPI1H4kayjnaaF48nwpLQT73S@9AcCS0R9ISiULYomtD4aoxmjUCH0hD6uS/mjR2hX86B/XH/XDuxZVXjmMELdEoHJCLMCiO4C2bT8IL80uTDUtWJDyrEjLH5jSA7BtojaP8fl/nnNFNUUI7ol0vUP9A@@NWute@S/6lxQeZALs6b9sNa/lyzjRDmoRreecDDY2P/ynHXuGMSzTKEnmfYTbrDXw) **Explanation:** ``` a->{ // Method with Object-matrix parameter & TreeMap return var r=new java.util.TreeMap();// Create the result sorted HashMap for(var p:a) // Loop over each Object-list of the input-matrix: for(int l=p.length-1, // Integer `l`, set to the last index of the list i=l;i-->0;) // Inner loop `i` in the range (length-1, 0]: r.put( // Add to the result TreeMap: p[i], // The `i`'th value of the list as key p[l]instanceof Long? // If the last item is a Long: p[l] // Use that last item as value : // Else: r.get(p[l])); // Get the value of this last item from the // result-Map, and use that as value return r;} // Return the resulting TreeMap (sorted HashMap) ``` [Answer] # [Red](http://www.red-lang.org), ~~74~~ 69 bytes ``` func[b][context collect[forall b[if set-word? first t: b/1[keep t]]]] ``` [Try it online!](https://tio.run/##bZBBUsMwDEX3PsW/AAMOLTDacAe2Gi1iR4ZQE3ccF7h96raB0tC/@pKe/tjK2k0v2rGYQFPYDZ6dsE9D0e8Cn2JUXzik3MYIx33AqOXmK@XuGaHPY0EhuFvLG9UtilRN25ycIoANqrglrOVkHWE1W0@oAye/THNmWjFizCKm9te2udhurnGdhhn6gZXwNFt7Zy93uBXBcXZNy@zw@nb@QU@4lz/9fpH8TtgQIuGDMBDsSv4/dqTD/XaEhzmpVp@Exxo17QE "Red – Try It Online") Takes the input as a list of lists, in each of them `=` replaced with `:` (Red has `set-words` rather than assignment operator) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εRćÐþÊiU¯ʒXk_}θθ}δ‚€ˆ}¯.¡н}€θ ``` Ugh.. :/ Not the right language for the job. Input as a list of lists. [Try it online](https://tio.run/##yy9OTMpM/f//3NagI@2HJxzed7grM/TQ@lOTIrLja8/tOLej9tyWRw2zHjWtOd1We2i93qGFF/bWAnnndvz/Hx2tlKikYxqrE62UpKRjAqKTlXRAYkA@iAdkGUFlgezY2P@6unn5ujmJVZUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLj/T@3NehI@@EJh/cd7soMPbT@1KSI7PjaczvO7ag9t@VRw6xHTWtOt9UeWq93aOGFvbVA3rkd/3UObbM/tEUz5tD6/9HR0UqJSjqmsTrRSklKOiYgOllJByQG5IN4QJYRVBbIjo3VUYBpgTCB4qaGRkj6jKASKalpIAPAUqlKOhZA2tDAECwJMwSqMi09A2p1ppKOMYgGiwB5UAVZQE42EOcAcS4Q5ynpGJpA5YqB/BIgLlXSMQNpBbHLlHTModL5UBOBtFIBzLxCIKcIxikHcsoRzq6AOgVIA3FsbOx/Xd28fN2cxKpKAA). **Explanation:** ``` ε # For each list in the (implicit) input-list: R # Reverse the list ć # Extract its head; pop and push remainder-list and first item separated # to the stack Ð # Triplicate this value þ # Pop one copy, and only leave its digits Êi # If the top two copies are NOT the same (so it's not an integer): U # Pop and store the last copy in variable `X` ¯ # Push the global_array ʒ # Filter it by: Xk # Where the index of `X` _ # Is 0 (thus the key of the pair) }θ # After the filter: leave the last pair θ # Pop and leave its value } # Close the if-statement δ # For each value in the remainder-list: ‚ # Pair it with the top value € # Then for-each pair in this list: ˆ # Add this pair to the global_array }¯ # After the outer for-each: push the global_array .¡ # Group this list of pairs by: н # Its first value (the key) }€ # After the group-by: map over each group: θ # And only leave the last pair # (after which the top of the stack is output implicitly as result) ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 57 bytes ``` s/[a-z_]+/\$k{'$&'}/g;/=/&&eval}{say"$_=$k{$_}"for keys%k ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPzpRtyo@Vls/RiW7Wl1FTb1WP91a31ZfTS21LDGntro4sVJJJd4WKKkSX6uUll@kkJ1aWaya/f9/SmoalxFXqoKtggWXoYHhv/yCksz8vOL/ur6megaGBv91CwA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), 172 bytes Takes input as a list of strings, returns a named vector. Just `eval` in R with aggressive escaping using the `A` character. ``` function(i){i=paste(gsub('([a-z_])', 'A\\1',i)[grepl('=',i)],collapse=';') eval(parse(text=i)) rm("i") u=ls() x=sapply(u,function(name)get(name)) names(x)=gsub('A','',u) x} ``` [Try it online!](https://tio.run/##bVHLbsMgELzzFYgLuxI9OE0fUsUh35FEFnGJS4sdZEzktuq3u0utVE3tw4jZWXZ2BN1oz8aXpn0uvYs91@MxtVXvTi04/HQ6mNhbqGM6gIStufko9ygVl5vdrpDK4bbubPAgdS72qjp5b0K0Wj5JZNkagumihd4OvXaIrGtAOIEsaR8B2aCjCcG/Q1K/i1vTWKxtPxFk@YgwoJ5ibKSSUiWa/boOD8Jwze8EcnatVyAOuVOshOKiIpovrgTiv4vCkv4oZvJcMTOJlhzrF5pf5yWOyG0mk@YWdr2S/kbwhIbQEor1km@kDn0NT4T7bJqLM@FhwfbyjD8BlkL@7ZNXSeSiZbvxGw "R – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~69~~ 103 bytes ``` import re def f(x):g={};exec(re.sub('(^|\n)[^=]+($|\n)','',x).upper(),{},g);return eval(str(g).lower()) ``` [Try it online!](https://tio.run/##FY3LDoIwEEX3/YouTGYmNkR0YyT9EpXExxRJoDRDUQzy7RV2N@ec5IZvfHX@kFLdhk6iFlZPdtrhSKfKTnPBIz9QOOuHOwKWv4unc2mvW9ysEwyAGSkbQmBBMtNsKiqE4yBe8/vWYB8FK8qa7rMGlILUPqJDAFiO1F6xtvqo8l2@kMX/AQ "Python 3 – Try It Online") +34 bytes to remove no-op lines in the input and avoid undefined variables Takes advantage of the fact that no python keywords are uppercase, and variable names for this challenge will all be lowercase. Saves several bytes thanks to a comment on my original (invalid) answer by @ovs: > > Note that your original answer could have been 35 bytes with exec(x,{},g), since exec does not add **builtins** to the locals dictionary. (This is still invalid) > > > [Answer] # [Pip](https://github.com/dloscutoff/pip) `-rl`, 57 bytes ``` {YDQaIx~'^.y.,wYXI~$'Fva.sxR:'^.v.,`.+|^$`v.y.n}Mg^sUQx^n ``` [Try it online!](https://tio.run/##K8gs@P@/OtIlMNGzok49Tq9ST6c8MsKzTkXdrSxRr7giyAooWKank6CnXROnklAGVJBX65seVxwaWBGX9/9/RiaXiRFXSqpCWnqGgglXpoIxF4iVyZWlkK2Qo5CrkKdgaMKVDFSQrGDGVaxQolCqkJL6X7coBwA "Pip – Try It Online") Takes input (from stdin) and produces output (to stdout) as a series of lines, each of the form `a b c 5` (for `a = b = c = 5`). The output will have an extra blank line in it somewhere, which can be eliminated for +1 byte. Pip is handicapped here by not having a dictionary/hashmap type. Our approach is to build the output as a string, using regex substitutions to update with new assignments. Further explanation available upon request, although I also hope to golf this more. Here's an [earlier, pre-golfed version](https://tio.run/##FcpPC4IwAIbx@/sp3oNQYQ2s0cFzCB0NOngZAzWdLZEsWfTnq695e@D3DGbwPrMN36BV6QgWh9yCR/dbKPESa82liFcaZBElYDYFpDulQadZRfxRkZ7EGOYeX5xzp3rvWwO5RVXz0rSUMNxhLoOOV1re2DORKMNQco@RDz5Z1X5zt38) which may be easier to decipher. [Answer] # [Haskell](https://www.haskell.org/), ~~177~~ ~~145~~ 141 bytes ``` r t=f(?)[](reverse.words.filter(/='=')<$>lines t) s?(x:y)=f(#)s y where z|Just v<-lookup x s=v|1<2=read x;s#k=(k,z):[x|x<-s,fst x/=k] f=foldl ``` [Try it online!](https://tio.run/##JY7BbsIwEETv@YoVIGFLCQjoKc2WM732GHKIlDWx7DqR1wSD8u@pK04z86QnTd@yIWuXxUNAJc6yboSniTzT7jH4jndK20Be7HGLW1ltvqx2xBBkxmcRy6dM1loyPOHRkyd4zd93DjBVhR0Gcx8hAuM0H6ojemo7iJ@8NihM/pJlHedYFZyrJMQ9miZTqAbb2SVQQggrdetTfFydTnG6uvfWq@y31S610WsXQKTz/0JZQi1@QmK3HC4uyEYufw "Haskell – Try It Online") Ungolfed: ``` run :: Read v => String -> [(String, v)] run input = foldl assign [] (reverse . words . filter (/='=') <$> lines input) assign :: Read v => [(String, v)] -> [String] -> [(String, v)] assign scope (first:keys) = foldl acons scope keys where value | Just v <- lookup first scope = v | otherwise = read first acons scope' k = (k, value) : [x | x <- scope', fst x /= k] ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 128 bytes ``` x=>{var z=new Dictionary<string,string>();x.ForEach(l=>{var s=l.Pop();l.Any(o=>(z[o]=z.ContainsKey(s)?z[s]:s)=="");});Print(z);} ``` [Try it online!](https://tio.run/##VZDLTsMwEEX3/gorK1syFinlIVIHVVAkBIuKdle6MK7Tmho7it2SBPHtYVLaBYs7j@szI41VOFPBdGMVjXejFxPiaBal2o5CrIxb53leiK4W@fdeVrgVTn/hB3OAZdUcIXZkCc1q/uiriVQbYo8zQVg@9SW8WT52DfEiJ@3CL0XL772L0rjwrBsS6F27CMvbQIVIEpr90GwKSyNpoe4yhApf6X5vv9O4chch4ifHX7Vczf3ErQjls9KaSJI3l1CKCnLATibDCQDaahVJjUWO@1P@nUrqE4sFwJTyue8/hFCaoU6CeYne@5gOGFZQ9NYArXTBMDgauhuG0/MUIYmK9Qb6IcMG0gXDf71BHxC3IAv6BDlQOkQBUgTtQFfsUO5B178 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [PHP](https://php.net/), 65 bytes ``` eval(preg_filter('/([a-z_]+)/','\$$1',$argn));var_dump($GLOBALS); ``` [Try it online!](https://tio.run/##K8go@G9jXwAkU8sSczQKilLT49Myc0pSizTU9TWiE3Wr4mO1NfXVddRjVFQM1XVUEovS8zQ1rcsSi@JTSnMLNFTcffydHH2CNa3//y9WsFUoAeJSIDazBjPLgNjc@l9@QUlmfl7xf103AA "PHP – Try It Online") Takes input as string with `;` as separator, outputs an array. I'm not sure this is valid, as the rules for the output are not very precise: the result is present at the end, but there are other unnecessery things displayed before... For the first time PHP's `$` comes useful, as it allows to use keywords as var names (works with names such as `function`, `echo` etc) ]
[Question] [ # task Your task is to build a structure with \$n\$ cubes. The volume of cubes follow the following sequence (bottom *->* top) # \$n^3, (n-1)^3, (n-2)^3,...,1^3\$ # input The total volume of the structure (\$V\$). # output value of (\$n\$), i.e : The total number of cubes. \$V = n^3 + (n-1)^3 + .... + 1^3\$ # notes * Input will always be an integer. * Sometimes it isn't possible to follow the sequence, i.e : \$V\$ doesn't represent a specific value for \$n\$. In that event return -1, or a falsy value of your choosing (consistency is required though). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes for each language wins. * No answer will be marked accepted for the above mentioned reason. # requests * This is my first challenge on the site so bear with me, and forgive (and tell me about) any mistakes that I made. * Kindly provide a link so your code can be tested. * If you can, kindly write an explanation on how your code works, so others can understand and appreciate your work. # examples ``` input : 4183059834009 output : 2022 input : 2391239120391902 output : -1 input : 40539911473216 output : 3568 ``` --- Thanks to @Arnauld for the link to this : ![](https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Nicomachus_theorem_3D.svg/1024px-Nicomachus_theorem_3D.svg.png) Isn't that nice. Link to orignial : [Link](https://math.stackexchange.com/a/61483/585002) [Answer] # JavaScript (ES7), 31 bytes A direct formula. Returns `0` if there's no solution. ``` v=>(r=(1+8*v**.5)**.5)%1?0:r>>1 ``` [Try it online!](https://tio.run/##ZYrLCsIwEADv/kchm2LZzSaaFRK/pfQhSmkklfx@Kr2Jh5nLzKsv/Tbk5/tzXtM41TnUEqLKQVHrddG6c3CooTvecoxUh7RuaZm6JT3UrCx5RieeLaIAnH6rYaED/ErQ/A0WHYsQ2SsbugDUHQ "JavaScript (Node.js) – Try It Online") ### How? The sum \$S\_n\$ of the first \$n\$ cubes is given by: $$S\_n = \left(\frac{n(n+1)}{2}\right)^2 = \left(\frac{n^2+n}{2}\right)^2$$ (This is [A000537](https://oeis.org/A000537). This formula can easily be [proved](https://math.stackexchange.com/a/1080587) by induction. [Here](https://math.stackexchange.com/a/61483) is a nice graphical representation of \$S\_5\$.) Reciprocally, if \$v\$ is the sum of the first \$x\$ cubes, the following equation admits a positive, integer solution: $$\left(\frac{x^2+x}{2}\right)^2=v$$ Because \$(x^2+x)/2\$ is positive, this leads to: $$x^2+x-2\sqrt{v}=0$$ Whose positive solution is given by: $$\Delta=1+8\sqrt{v}\\ x=\frac{-1+\sqrt{\Delta}}{2} $$ If \$r=\sqrt{\Delta}\$ is an integer, it is guaranteed to be an odd one, because \$\Delta\$ itself is odd. Therefore, the solution can be expressed as: $$x=\left\lfloor\frac{r}{2}\right\rfloor$$ ### Commented ``` v => // v = input ( r = // (1 + 8 * v ** .5) // delta = 1 + 8.sqrt(v) ** .5 // r = sqrt(delta) ) % 1 ? // if r is not an integer: 0 // return 0 : // else: r >> 1 // return floor(r / 2) ``` --- # Recursive version, ~~36~~ 35 bytes Returns `NaN` if there's no solution. ``` f=(v,k=1)=>v>0?1+f(v-k**3,k+1):0/!v ``` [Try it online!](https://tio.run/##ZctNDoMgEEDhfW/hDvypMwxUMUHPYqw0LUZMbeb61LVuv5f3GXncp@97@1VrfM4peSe4DA6l67mHAQsvuAp5TmUoUHZQZ5ymuO5xme9LfAkvlDJS3s72uJjGlsDYljSAvVYwZC2ibkjhMac/ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = (v, // v = input k = 1) => // k = current value to cube v > 0 ? // if v is still positive: 1 + // add 1 to the final result f( // do a recursive call with: v - k ** 3, // the current cube subtracted from v k + 1 // the next value to cube ) // end of recursive call : // else: 0 / !v // add either 0/1 = 0 if v is zero, or 0/0 = NaN if v is // non-zero (i.e. negative); NaN will propagate all the // way to the final output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ÝÝOnIk ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8NzDc/3zPLP//zcxtDA2MLW0MDYxMLAEAA "05AB1E – Try It Online") Port of Jonathan's Jelly answer. Take the cumulative sum of **[0 ... n]**, square each and find the index of **V**. --- ### [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ÝÝ3mOIk ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8NzDc41z/T2z//83MbQwNjC1tDA2MTCwBAA "05AB1E – Try It Online") ### How it works ``` ÝÝ3mOIk – Full program. ÝÝ – Yield [[0], [0, 1], [0, 1, 2], ... [0, 1, 2, ... V]]. 3mO – Raise to the 3rd power. Ik – And find the index of the input therein. Outputs -1 if not found. ``` 8-byte alternative: `ÝÝÅΔ3mOQ`. [Answer] # [R](https://www.r-project.org/), ~~42~~ 40 bytes *-2 bytes thanks to Giuseppe* ``` function(v,n=((1+8*v^.5)^.5-1)/2)n*!n%%1 ``` [Try it online!](https://tio.run/##Hci7CoAwDEDR3b9wEBKfSdNqM/grLkLBJYKov18fw7nDPXKac7psPbfd4G5tBuAm1vfSB3x1jINDq0urKs4JPEehoFE8kWKRwInyj94oue95CqLK7CdxPGJ@AA) Port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/171220/76266). Also returns 0 if there's no solution. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` RIJi ``` A monadic link, yields `0` if not possible. **[Try it online!](https://tio.run/##y0rNyan8/z/ocMuhTZn///83NLI0AwA "Jelly – Try It Online")** way too inefficient for the test cases! (O(V) space :p) [Here](https://tio.run/##y0rNyan8/1/L@MiGQ0uCDrcc2pT5//9/E0MLYwNTSwtjEwMDSwA) is an 8-byte version that performs a cube-root of V first to make it O(V^(1/3)) instead. Using that 8-byte version [here is a test-suite](https://tio.run/##y0rNyan8/1/L@MiGQ0uCDrcc2pT5/@iew@2Pmta4//8frWBiaGFsYGppYWxiYGDJpaNgZGxpCMYGQMLSwAgoZGJgamxpaWhoYm5sZGjGFQsA) ### How? $$\sum\_{i=1}^{i=n}i^3=\left(\sum\_{i=1}^{i=n}i\right)^2$$ ``` RIJi - Link: integer, V R - range of v -> [1,2,3,...,V] Ä - cumulative sums -> [1,3,6,...,(1+2+3+...+V)] ² - square -> [1,9,36,...,(1+2+3++...+V)²] ( =[1³,1³+2³,1³+2³+3³,...,(1³+2³+3³+...+V³)] ) i - first 1-based index of v? (0 if not found) ``` [Answer] # [Elixir](https://elixir-lang.org/), 53 bytes ``` &Enum.find_index 0..&1,fn n->&1*4==n*n*(n+1)*(n+1)end ``` [Try it online!](https://tio.run/##S83JrMgs@p9m@1/NNa80Vy8tMy8lHohTKxQM9PTUDHXS8hTydO3UDLVMbG3ztPK0NPK0DTUhZGpeyn9Pf73MvOKC1OQShTQ9DRNDC2MDU0sLYxMDA0tNLjRJA1NjS0tDQxNzYyNDM83/AA "Elixir – Try It Online") Port of Jonathan's Jelly answer. --- # [Elixir](https://elixir-lang.org/), 74 bytes ``` fn v->Enum.find_index 0..v,&v==Enum.sum Enum.map(0..&1,fn u->u*u*u end)end ``` [Try it online!](https://tio.run/##S83JrMgs@p9m@z8tT6FM1841rzRXLy0zLyUeiFMrFAz09Mp01MpsbcESxaW5CmBGbmKBBlBKzVAHqK1U165UCwgVUvNSNIH4v6e/XmZecUFqcolCmp6GiaGFsYGppYWxiYGBpSYXmqSBqbGlpaGhibmxkaGZ5n8A "Elixir – Try It Online") Definitely sub-optimal. But I am just an Elixir newbie! :) Returns `nil` for "invalid" values of `V`. [Answer] # Japt, 7 bytes ``` o³å+ bU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=b7PlKyBiVQ==&input=MTI5Ng==) --- ## Explanation ``` :Implicit input of integer U o :Range [0,U) ³ :Cube each å+ :Cumulatively reduce by addition bU :0-based index of U ``` --- ## Alternative ``` Çõ³xÃbU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=x/WzeMNiVQ==&input=MTI5Ng==) [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 27 bytes (or volume 27?) Seems like the right place for this language. ``` [[email protected]](/cdn-cgi/l/email-protection)<s)s;;q\.>s-.?/ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9/TQc/QP9zYoCC8IMCmWLPY2rowRs@uWFfPXv//fwA "Cubix – Try It Online") This wraps onto a 3x3x3 cube as follows ``` I @ . 1 O W 3 0 p W p P < s ) s ; ; q \ . > s - . ? / . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICAgSSBAIC4KICAgICAgMSBPIFcKICAgICAgMyAwIHAKVyBwIFAgPCBzICkgcyA7IDsgcSBcIC4KPiBzIC0gLiA/IC8gLiAuIC4gLiAuIC4KLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=MTI5Ng==&speed=20) It essential brute forces by taking increasing cubes away from the input. If it results in zero, output *`n`* otherwise if there is a negative result, print 0 and exit. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~30~~ ~~29~~ 26 bytes *-4 bytes thanks to Jo King* ``` {first :k,.sqrt,[\+] ^1e4} ``` [Try it online!](https://tio.run/##HcRNCsIwEAbQq3wLkYqlzGSmsWOrF/EPFw2IFjXpphTPHsXFe68@PnweJiwDdnkOt5hGbO9lld5xLA/H9Qln7vWT03VCKBaXFcIzolNuhGprRIkMToz/6JeRg1ItZsy6EcceDIP4fZu/ "Perl 6 – Try It Online") Brute-force solution for n < 10000. Uses the equation from Jonathan Allan's answer. ~~37~~ 36 bytes solution for larger n (*-1 byte thanks to Jo King*): ``` {!.[*-1]&&$_-2}o{{$_,*-$++³...1>*}} ``` [Try it online!](https://tio.run/##HcRBCsIwEADAr6wQgqYm7GbT2EXtR0SCB3OqVOqphLzKH/ixKB5mnvdliu2xgs5wbmXjLsbSVWuVrK9zKSrtjVVd93k752g0tbbXbYW8VWkHeV7gFGhg7GXggCjgWegPfwl6CNizCFE4sKcIBAIcx2P7Ag "Perl 6 – Try It Online") Returns `False` if there's no solution. ### Explanation ``` o # Combination of two anonymous Blocks { } # 1st Block { } # Reset anonymous state variable $ $_,*-$++³...1>* # Sequence n,n,n-1³,n-1³-2³,... while positive { } # 2nd Block !.[*-1]&& # Return False if last element is non-zero $_-2 # Return length of sequence minus two otherwise ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 28 bytes ``` a=>a**.5%1?0:(2*a**.5)**.5|0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RS0vPVNXQ3sBKw0gLzNEEETUG//8DAA "JavaScript (Node.js) – Try It Online") I know it's my own question and all, but I had a better answer (for this lang) then is present, so I posted. Hope it's ok [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 18 bytes ``` {o×⍵≥o←⍵⍳⍨+\3*⍨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tq/MPTH/VufdS5NB/IA7F6Nz/qXaEdY6wFpMCcrbVApQqGXGkKRkamQNLQzMjUDMwysbCwMDUCyZiamQMA "APL (Dyalog Unicode) – Try It Online") [Answer] ## Matlab, 27 bytes ``` @(v)find(cumsum(1:v).^2==v) ``` Returns the `n` if exists or an empty matrix if not. **How it works** ``` 1:v % Creates a 1xV matrix with values [1..V] cumsum( ) % Cumulative sum .^2 % Power of 2 for each matrix element ==v % Returns a 1xV matrix with ones where equal to V find( ) % Returns a base-1 index of the first non-zero element ``` [Try it Online!](https://tio.run/##HYo5CoAwEAB7X7LbhD0SdYWALxFEDViohZrvx6OYKYY5pmvMS0nROVd6yJjWfYbp3s57A@4yukFizFgSiASsEnhulYK16onsC6LGP/TKSP6Jgpox@0aFaywP) **Note** It fails for large `v` due to memory limitations. [Answer] # [Python 3](https://docs.python.org/3/), 60 bytes ``` lambda V:[*[(n*-~n/2)**2for n in range(V+1)],V].index(V)%-~V ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHMKlorWiNPS7cuT99IU0vLKC2/SCFPITNPoSgxLz1VI0zbUDNWJyxWLzMvJbVCI0xTVbcu7H9BUWZeiUaaRmpZYo5GZl5BaYmGJhD8NzYDAA "Python 3 – Try It Online") -6 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder). If we can throw an error in case there's no \$n\$ for a particular \$V\$, we can get this down to 51 bytes: ``` lambda V:[(n*-~n/2)**2for n in range(V+1)].index(V) ``` [Try it online!](https://tio.run/##DcHBDkAgHAfgV@n4L8OwOdi8Rhccsoo2flqLcfHq8X3@ieuBJtl@TJvaZ62Y7AaCyF@UNReitkdgYA4sKCyGZFbxqXDQ5ibJkw8OkSyZS23k4M9I/Jea9gM "Python 3 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes ``` {$!+>1 if ($!=sqrt 1+8*.sqrt)%%1} ``` [Try it online!](https://tio.run/##HcbRCoJAEEbhV/mFVTQhZnbWbYfUV4kuWgiKau1GxGff0ovzcd639PD5OaOKGPJiinZk3CNqUwzTJ33BbTgct2vKktc8XWfE2lwaxFdC7zgIdRrEESmsKO/RHyULR52oMruTWPZgKMSP5/wD "Perl 6 – Try It Online") This uses [Arnauld's method](https://codegolf.stackexchange.com/a/171220/76162). Returns an [Empty](https://docs.perl6.org/syntax/Empty) object if the number is not valid. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 19 bytes ``` 4*dvvdddk*+d*-0r^K* ``` Input and output is from the stack, returns 0 if no solution. [Try it online!](https://tio.run/##S0n@b2JoYWxgamlhbGJgYPnfRCulrCwlJSVbSztFS9egKM5b63/BfwA "dc – Try It Online") # Explanation If there's a solution n, the input is `((n^2+n)^2)/4`. So we'll calculate a trial solution as `n=sqrt(sqrt(4*input))`, using dc's default 0 decimal place precision for square roots, then compare `(n^2+n)^2` to `4*input` to see if it's actually a solution. ``` 4*dvv Calculate a trial solution n (making a copy of 4*input for later use) dddk Store the trial solution in the precision and make a couple copies of it *+d* Calculate (n^2+n)^2 - Subtract from our saved copy of 4*input - now we have 0 iff n is a solution 0r^ Raise 0 to that power - we now have 1 if n is a solution, 0 if not K* Multiply by our saved trial solution ``` The penultimate line relies on the non-obvious fact that to dc, `0^x=0` for all nonzero `x` (even negative `x`!) but `0^0=1`. [Answer] # [Python 3](https://docs.python.org/3/), ~~53~~ 48 bytes ``` f=lambda V,n=1:V>0and f(V-n**3,n+1)or(not V)*n-1 ``` [Try it online!](https://tio.run/##JY1BCsIwEEXX9hSzzNRUGlsEC/UY2YiLaBsdaCYlSRc9fTT44K8en7fu6eO5y@RWHxLEPVa/neKcwvzaQiTPCzlKQrUFzHZcjHtOBrTkUQ361hqewArdcF13ko8KfRDsE2isuVHZ@gAExHDvLhKUhKuEs4S4OVEeUDwXHwy/538HUULfP4bqsAbiJKwgxPwF "Python 3 – Try It Online") -3 bytes from [Jo King](https://codegolf.stackexchange.com/questions/171219/how-many-cubes-can-be-built/171272?noredirect=1#comment413435_171272) Returns `-1` for no answer. Only works up to `n=997` with the default recursion limits. Repeatedly takes bigger and bigger cubes from the volume until it arrives at zero (success, return number of cubes removed), or a negative number (no answer). Explanation: ``` f=lambda V,n=1: # f is a recursive lambda taking the volume and the cube size (defaulting to 1) V>0and # if the volume is positive f(V-n**3,n+1) # then we are not to the right cube size yet, try again with n+1, removing the volume of the nth cube or # if V is not positive (not V)*n-1 # case V == 0: # (not V)*n == n; return n-1, the number of cubes # case V < 0: # (not V)*n == 0; return -1, no answer ``` [Answer] # [gvm](https://github.com/Zirias/gvm) (commit [2612106](https://github.com/Zirias/gvm/commit/26121066d5955d1b1e11ee8e34715f8ac5d60fc2)) bytecode, 70 59 bytes (-11 bytes by multiplying in a loop instead of writing the code for multiplying twice) Hexdump: ``` > hexdump -C cubes.bin 00000000 e1 0a 00 10 00 1a 03 d3 8a 00 f6 2a fe 25 c8 d3 |...........*.%..| 00000010 20 02 2a 04 0a 01 1a 02 00 00 20 08 4a 01 fc 03 | .*....... .J...| 00000020 d1 6a 02 52 02 cb f8 f4 82 04 f4 e8 d1 6a 03 0a |.j.R.........j..| 00000030 03 fc d5 a8 ff c0 1a 00 a2 00 c0 |...........| 0000003b ``` Test runs: ``` > echo 0 | ./gvm cubes.bin 0 > echo 1 | ./gvm cubes.bin 1 > echo 2 | ./gvm cubes.bin -1 > echo 8 | ./gvm cubes.bin -1 > echo 9 | ./gvm cubes.bin 2 > echo 224 | ./gvm cubes.bin -1 > echo 225 | ./gvm cubes.bin 5 ``` Not really a low score, just using this nice question for testing `gvm` here ;) The commit is older than the question of course. **Note** this is an 8bit virtual machine, so using some code handling only the natural unsigned number range `0-255`, the test cases given in the question won't work. Manually assembled from this: ``` 0100 e1 rud ; read unsigned decimal 0101 0a 00 sta $00 ; store to $00 (target sum to reach) 0103 10 00 ldx #$00 ; start searching with n = #0 0105 1a 03 stx $03 ; store to $03 (current cube sum) 0107 d3 txa ; X to A loop: 0108 8a 00 cmp $00 ; compare with target sum 010a f6 2a beq result ; equal -> print result 010c fe 25 bcs error ; larger -> no solution, print -1 010e c8 inx ; increment n 010f d3 txa ; as first factor for power 0110 20 02 ldy #$02 ; multiply #02 times for ... 0112 2a 04 sty $04 ; ... power (count in $04) ploop: 0114 0a 01 sta $01 ; store first factor to $01 ... 0116 1a 02 stx $02 ; ... and second to $02 for multiplying 0118 00 00 lda #$00 ; init product to #0 011a 20 08 ldy #$08 ; loop over 8 bits mloop1: 011c 4a 01 lsr $01 ; shift right first factor 011e fc 03 bcc noadd1 ; shifted bit 0 -> skip adding 0120 d1 clc ; 0121 6a 02 adc $02 ; add second factor to product noadd1: 0123 52 02 asl $02 ; shift left second factor 0125 cb dey ; next bit 0126 f8 f4 bpl mloop1 ; more bits -> repeat 0128 82 04 dec $04 ; dec "multiply counter" for power 012a f4 e8 bne ploop ; not 0 yet -> multiply again 012c d1 clc 012d 6a 03 adc $03 ; add power to ... 012f 0a 03 sta $03 ; ... current cube sum 0131 fc d5 bcc loop ; repeat unless adding overflowed error: 0133 a8 ff wsd #$ff ; write signed #$ff (-1) 0135 c0 hlt ; result: 0136 1a 00 stx $00 ; store current n to $00 0138 a2 00 wud $00 ; write $00 as unsigned decimal 013a c0 hlt ``` *edit*: I just [fixed a bug](https://github.com/Zirias/gvm/commit/e530d929691ade45468ea56846b6c4b27d354b7c) in `gvm`; without this fix, `gvm` tried to read binary programs in *text mode*, which might break (code above doesn't contain any `0xd` bytes so won't break on windows without this fix). [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 21 bytes ``` {(,_r%2)@1!r:%1+8*%x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWkMnvkjVSNPBULHIStVQ20JLtaL2f5q6iaGFsYGppYWxiYGBpYKRsaUhGBsACUsDIwUTA1NjS0tDQxNzYyNDs/8A "K (oK) – Try It Online") Port of [Arnauld's JS answer](https://codegolf.stackexchange.com/a/171220/76266). ### How: ``` {(,_r%2)@1!r:%1+8*%x} # Main function, argument x %1+8*%x # sqrt(1+(8*(sqrt(x))) r: # Assign to r 1! # r modulo 1 @ # index the list: (,_r%2) # enlist (,) the floor (_) of r modulo 2. ``` the function will return `(_r%2)` iff `1!r == 0`, else it returns null (`0N`). That is due to the single element in the list having index 0, and trying to index that list with any number other than 0 will return null. ]
[Question] [ ## Background We've studied at least [five](https://codegolf.stackexchange.com/questions/205252/lets-study-neil-numbers) [different](https://codegolf.stackexchange.com/questions/205396/bubbler-numbers) [types](https://codegolf.stackexchange.com/questions/57882/is-this-a-candidate-calvin-number) [of](https://codegolf.stackexchange.com/questions/57719/generate-dennis-numbers) [numbers](https://codegolf.stackexchange.com/questions/94961/dennis-numbers-2-0) based on the IDs of different users on this site. Why not study another? My user ID is \$91030\_{10}\$. Its binary representation is \$10110001110010110\_2\$, a representation which has an interesting property of its own: * One option for the longest palindromic run of binary digits is \$0011100\$. * If you remove this run of digits, the remaining list of digits (\$1011010110\$) can be split into two identical halves. I define a **sporeball number** as any positive integer where at least one of the options for the longest palindromic run of digits in its binary representation can be removed such that the remaining list of digits can be split into two identical halves. ## Task Write a program or function which takes a positive integer as input and determines whether or not it is a sporeball number. Some clarifications to keep in mind: * Leading zeroes should be ignored. * Exactly **one** palindromic run of digits should be removed before checking if the remaining digits can be split into identical halves. + If one of the options for the longest palindromic run occurs multiple times, **remove only one occurrence**, rather than all of them, before checking if the remaining digits can be split into identical halves. * Single digits are palindromic. * The empty string `""` is not palindromic, and cannot be split into two identical halves. Remember that there may be more than one longest palindromic run of digits: * The binary digits of \$12\_{10}\$ (\$1100\$) contain two options for the longest palindromic run (\$11\$ and \$00\$). No matter which one is removed, the remaining digits will be able to be split into identical halves. Thus, \$12\_{10}\$ is a sporeball number. * The binary digits of \$20\_{10}\$ (\$10100\$) contain two options for the longest palindromic run (\$010\$ and \$101\$). Removing \$010\$ leaves the digits \$10\$, which cannot be split into identical halves; however, removing \$101\$ leaves the digits \$00\$, which can be. Thus, \$20\_{10}\$ is a sporeball number. There are 153 sporeball numbers under 1,000: ``` 12 20 23 24 26 28 29 39 48 57 60 68 71 84 87 96 100 106 108 110 111 113 117 123 124 132 135 154 166 178 180 183 192 204 207 210 222 225 237 240 243 252 260 263 277 282 287 295 314 326 334 336 337 340 343 348 351 354 370 372 375 384 392 394 396 399 404 412 418 426 428 431 432 446 449 457 469 476 477 479 480 483 484 490 491 496 497 501 503 508 516 519 533 538 543 562 600 610 612 615 634 646 652 660 663 664 670 673 676 691 700 703 706 718 720 735 742 754 756 759 768 778 780 783 792 804 816 821 826 828 831 834 858 870 874 876 879 894 897 918 921 922 924 927 933 957 960 963 972 978 987 993 999 ``` ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. * Standard I/O rules apply. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 26 bytes ``` {ḃ~c₃↺{↔?¬Ė}ʰ↻c}ᶠlᵒlᵍh∋~jz ``` [Try it online!](https://tio.run/##HZLNalRBEIVf5TrrUW51dXd1bcyDhCzioAYZCERD0HGyMDBERBAR1@7cuMgmIslOXPkW977IpL5edFH/fepUPTs7Xp28XZ@@TPvNxWJ4/HRYXBxs5t3N/OHq0Xz9c/Hm7Pz5k8X7rr84Xr8OYzvdfdxOt1/2m@nP1eUqMufdXdR8O/j769/37f@beXe/2k6/f6yn26/xPp/M158uX73b7w8lLYc0xtN4OV6N1@L5ctB4OfRiy6FGTg3dZDm0yGvh88iVcUR0LcIimCIIRUSa0FtoLpoQJUTBrJQZZY2yRp53QCAZozbRLyV8qYASX8aXAVwIAC1VTCPa8AEveVSoRCtlKlU07VpElS5KF2VGLYIgxQhYQtCAaRVU6l2jgcMMIDP8ZYkGmT8y1GUVBIGML5MMh7miGT6QZuv8jghF0M8xnQZ8lD3yyigIRbANqYioLYpP8TFHqYk9sSjpAlNihMrkFSwVwmrfJYTVSoB5q2ECrfK50cX40litMaBxJsbyLEcXgysrREtgsX4c7NKYyJjIYK1BUwNzS9xO6lrkNWhqQGsFExjN@mmRAjkNxhscOAicBs4xONfkiQAceOnXOCIwWZ6DxfuZOj5WFuXsMXgNto4eAA "Brachylog – Try It Online") Dreadfully slow for large falsy testcases, but verifies truthy ones surprisingly quickly. [My original solution](https://tio.run/##AVIArf9icmFjaHlsb2cy/@KfpnvihrDigoIm4bqJfcui/z5Z4oSV4omcJuG4g35j4oKD4oa6e@KGlD/CrMSWfcqw4oa7Y1hs4oaZWSFYfmp6//8xMDAw) ran into the same false negatives as xash's deleted answer, but fortunately the process of fixing that helped me shave off 2 bytes. ``` { }ᶠ Find every possible result from: ḃ take the binary digits of the input, ~c₃ split them into three (possibly empty) partitions, ↺{ }ʰ↻ for the middle partition: ↔ reversed it is ? itself ¬Ė which is not the empty list; Ė replace it with the empty list. c and re-concatenate the partitions. lᵒ Sort the results by length, lᵍ group them by length, h and take the first group (that with minimal length). ∋ Some element of that group ~j is something concatenated with itself z which is not the empty list. ``` Rather than maximize the length of the palindromic substring, it just minimizes the length of everything left, which is an approach I really only came up with because of my initial approach of relying on `≜`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~45~~ ~~43~~ ~~42~~ ~~40~~ ~~41~~ ~~40~~ 31 bytes ``` b©ŒʒÂQ}é.γg}θε®sõ.;D2ä1ìËsgĀ*}à ``` [Try it online!](https://tio.run/##ATwAw/9vc2FiaWX//2LCqcWSypLDglF9w6kuzrNnfc64zrXCrnPDtS47RDLDpDHDrMOLc2fEgCp9w6D//zI1MDQ "05AB1E – Try It Online") *-2 thanks to @ovs!* *-1 thanks to @ovs!* *-1 (lol) thanks to a bug fix* *-1 thanks to @ovs (again!)* *+1 due to challenge clarification :-(* *but -1 thanks to @Kevin!* *and another whopping -9 thanks to @Kevin!* Don't mind me... just posting another overly long answer in 05AB1E that ~~will probably be~~ **was** golfed by anyone experienced with 05AB1E. The `ÂQ` trick to see if a string is a palindrome was taken from [this](https://codegolf.stackexchange.com/a/166431/78850) 05AB1E tip answer by Kevin. ## Explained (old) ``` bDV.œ˜ʒÂQ} ЀgàUʒgXQ}εYsõ:Ðg;ôËsgD0ÊsÈ**}à bDV # Get the binary representation of the input, and assign variable Y to that value while still keeping a copy on the stack .œ # Push all partitions of that binary representation ˜ # Flatten said list and ʒ # Select items where: ÂQ} # They are a palindrome Ð # and push three copies of it to the stack. €g # For one of those copies, push the length of each item àU # Find the maximum length and assign it to variable Y ʒgXQ} # From the list of palindromic partitions, select the ones which are of the maximum length ε # And from that list: Ysõ: # Replace the occurrence of that number in variable Y with nothing THEN Ð # Triplicate it THEN g;ô # Split it in half THEN Ë # See if all elements are equal AND sgD0ÊsÈ** # Ensure the length of Y with the item removed isn't 0 and isn't odd }à # Close the map, and take the maximum of the list and implicitly print the result ``` [Answer] # [J](http://jsoftware.com/), 80 78 75 66 61 57 bytes ``` 1 e.#\,@((#<.[-:[:,~,~inv)\.*[:(*i.@#=+./"{i:1:)(-:|.)\)] ``` [Try it online!](https://tio.run/##FZK9jhsxDIT7ewriXJz3Ym9WpCSSQg4wECBVqrT2VcEd4hRJlyaBX935VAz4s6Jmhtqf98f16V1ehjzJQTYZ4LjK529fv9yLvK27y@G03@8@refjOI/D7XC7/vqzXNbn89g/X9fT7uXD@vHx73WUseyP49@6XJbX@/Lw8Pb9x29h8ibvp9143Ba5rmXbiMchRUU3UROtol00RFMspYY0l75JD/EiUSVcsguDYMaQUshLAQacu4jcU0xBk9LIO2eds8HZ4HtOQrg2F2VelVobCqgrdUVKowe1dnKnH9TQazaxUsUQaka0GV2MOWPOEG2tAL45PVfADOoNXssZmUn8oaFivpaQyn0V59UKoFepK2fYQO1Ep0ZH9bmXDRhgPsmTGe6s6dK2AgywvNJBSjNqo0Zf68pGWWmZIC9NOj46fB3Pfa4bz73TQ393crg7HM6cc7eze0ez82rOjr2qOH690W8pPt@LfTs6HZ2O78BroCeUh9QZQwKvAXc0crjC5wvzDY/BngI/CU8yk7xR8q6p9PCTbf4KGyBnxwlfzt8jqTPv/wE "J – Try It Online") *-3 bytes thanks to Marshall* *-9 bytes thanks to xash* Tougher than I thought it would be. Finally a respectable size, though still high for J. # [J](http://jsoftware.com/), alternate approach, 73 bytes ``` 1 e.1}.((((<:@[,(-:|.)\#(#<.]-:[:,~,~inv)\.)~{.))^:(0<{.@]*1=#@])^:_#)@#: ``` [Try it online!](https://tio.run/##FZI7bxRBEIRz/4qSN/Au3I3m3dMrWzoJiYiI1D4TIFuYADISw/3145uVSv2Y6emq7v15vQ13r3rYdaeDonZwDPr09cvna9JLSP/Cyne/nx4P63H/G7anZV3uw/m4P@6Hy@Hy9uvP9hS2y3vYtud9jffv4XT@kB6W05n427Kdlv263dy8fP/xW@u6XPR6@3HTW0gxxk3HXSkrR@WiXJW78lB2FVcdaqYe1YcsaVQNk3dRCKYdSgk/JVCA8RaWd1LJoCk1/M5d4@7g7uDcZ0N6RVOmPmfi3GBAXIkrVBo5WueOb@QHMe2zN5VUVSBaCrZMayrUFeoKpEtLgDMjZxlQA/tC3@LTUuPog0NFfE1DlfcqymtJgFwlrtxhArVjjRge1eZcIiiAesd3anizuqnFBApgeKkDVyvEhRh@rWcmykjTBH5q6ujo9Oto7nPcaO6dHPy74dO708OoM942Zm9wNrZmzNhqlqHXGvnmsrkv5m3wNHgaugdaB3xGZpF52qGB1kHv0fDpNWxumDM0DuY00OP0cWqcHTl79UwOPd7mrxABPjN2@vn8PZzY/fof "J – Try It Online") This one uses do..while `^:(while)^:_`, starting by searching the longest possible length palindrome, and stopping as soon as it finds any for a certain length, returning the boolean telling you if the complement for that palindrome is a doubled string. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 126 bytes ``` .+ * +`^(_*)\1(_?)(?!^|_) $1$.2 Lv$`(.)+.?(?<-1>\1)+(?(1)(?!))|. $`$' N$` $.& +m`^((.)*)¶(?<-2>.)*(?(2)(?!)).+$ $1 0m`^(.+)\1$ ``` [Try it online!](https://tio.run/##Jc0xDsIwDIXh3bdAsoodCysOExJqLlBxgqoJAwMDDKhi6rk4ABcLjtje8Ol/r9t6f16tNRUIIHWhEng2Kpkp75atMKChJpjeWElZNFM@H2ycjYUyWWfMmwJW3MMFK6AOIA8vOQ/8/XSfRt/O05@roGchdqXif9jayeIx/gA "Retina – Try It Online") Explanation: ``` .+ * ``` Convert the input to unary. ``` +`^(_*)\1(_?)(?!^|_) $1$.2 ``` Convert it to binary. ``` Lv$`(.)+.?(?<-1>\1)+(?(1)(?!))|. $`$' ``` Find and remove palindromes. ``` N$` $.& ``` Sort the results by length, so that the first result corresponds to the longest palindrome. ``` +m`^((.)*)¶(?<-2>.)*(?(2)(?!)).+$ $1 ``` Remove all results of longer length. ``` 0m`^(.+)\1$ ``` Check whether any of them can be split. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes ``` ≔⍘N²θF⊕LθFιF⁼✂θκι¹⮌✂θκι⊞υ⁺…θκ✂θι¿⌊υ⊙υ∧⁼Lι⌊EυLλ⁼ιײ∕ι² ``` [Try it online!](https://tio.run/##VY7dasMwDIXv@xS6lMGDNrsaucq6XQzWUda9gOeoiZjtJP4J9OkzO6SDCYRA59PR0b3yelBmWZoQuHP4rAJdomfX4ZsbU/xI9ps8CglV7knUu@vgIWvakyUXqcV3cl3scRJCwCryNl@npEzAi2FNOEn4kcASDtnnk2bygf5LohicU@gxSTibFPB404aO/TCuSL774wtc7/gKeGLHNllM5Tjnjti4W3FoXHtPsCXk7HDHT2os0KaY8lvChueQX2wpYCXhhWduqawqsVa9LE@H/eN@eZjNLw "Charcoal – Try It Online") Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` for a sporeball number, empty if not. Explanation: ``` ≔⍘N²θ ``` Convert the input to base 2. ``` F⊕LθFι ``` Loop over all nontrivial substrings of the input. ``` F⁼✂θκι¹⮌✂θκι ``` If this substring equals its reverse... ``` ⊞υ⁺…θκ✂θι ``` ... then push the remaining digits to the predefined empty list. ``` ¿⌊υ ``` If the original number was not palindromic, ... ``` ⊙υ∧⁼Lι⌊EυLλ⁼ιײ∕ι² ``` ... then output whether any of the results are of minimal length and equal themselves halved in length and doubled again. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḊḢŒḂḤœP⁸F BØ2jŒṖḟ€€2Ç€LÐṂŒHE$ƇẸ ``` **[Try it online!](https://tio.run/##y0rNyan8///hjq6HOxYdnfRwR9PDHUuOTg541LjDjcvp8AyjLKDgzmkPd8x/1LQGiIwOtwNJn8MTHu5sOjrJw1XlWPvDXTv@//9vaWhgbAAA "Jelly – Try It Online")** Or see those [up to 600](https://tio.run/##y0rNyan8///hjq6HOxYdnfRwR9PDHUuOTg541LjDjcvp8AyjLKDgzmkPd8x/1LQGiIwOtwNJn8MTHu5sOjrJw1XlWPvDXTv@g0VD/v83MzAAAA "Jelly – Try It Online") (up to 1000 is too slow). ### How? ``` BØ2jŒṖḟ€€2Ç€LÐṂŒHE$ƇẸ - Main Link: n B - convert (n) to a binary list Ø2 - [2,2] j - join ([2,2]) with (B(n)) ŒṖ - partitions (none with empty parts, hence the Ø2j and ḟ€€2) ḟ€€2 - remove any 2s from each part of each Ç€ - call Link 1 for each (removes second part if it's palindromic & flattens) LÐṂ - keep only those with minimal length Ƈ - filter keep those for which: $ - last two links as a monad: ŒH - split into two E - all equal? Ẹ - any truthy? ḊḢŒḂḤœP⁸F - Link 1: list of parts Ḋ - deueue Ḣ - head -> second part ŒḂ - is palindromic? (1 if so, else 0) Ḥ - double ⁸ - the list of parts œP - partition at index (0œP[4,5,6,7] -> [[4,5,6,7]] while 2œP[4,5,6,7] -> [[4],[6,7]]) F - flatten ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~128...103~~ 101 bytes ``` FreeQ[MinimalBy[$@@d~Drop~#&/@SequencePosition[d=#~IntegerDigits~2,_?PalindromeQ],Length],a__~$~a__]& ``` [Try it online!](https://tio.run/##HctBC4IwGIDhe3/D8BALzbu1QoKgQvM4hgz9nB/oVvPr4GV/fUnv4bm9k6IBJkXYqtDn4eoAKvFAg5MaL4vYct75wtm3j@KE1/D5gmmhtDMSWiO6PPI3Q6DBFaiRZp@x5lSqEU3n7ASVZHcwmgbJVNP4rV@VcSgdGhLR/tjzSMb@7JxafJZuahihJfFSRoM4pGuSPS3xXS@T5D@FHw "Wolfram Language (Mathematica) – Try It Online") Returns `False` if the number is not a sporeball number, and `True` otherwise. ``` d=#~IntegerDigits~2 (* get digits of input, base 2. *) SequencePosition[ % ,_?PalindromeQ] (* get positions of palindromic runs *) d~Drop~#/@ % (* and remove them, *) $@@ % (* placing the remaining digits in $ *) MinimalBy[ % ,Length] (* keep the shortest remaining digit lists *) FreeQ[ % ,a__~$~a__] (* and check if they have identical halves. *) ``` `$@@` is needed to handle cases like \$38=100110\_2\$, where removing either of the two longest-palindromes `1001`, `0110` has the same result `10`. [Answer] # JavaScript (ES6), 175 bytes ``` n=>(m=g=(s,p='',q=p)=>s?g(s.slice(1),p+s[0],q,s==[...s].reverse(L=s.length).join``?o=(L<=m?o:!(m=L))|L==m&/^(.+)\1$/.test(p+q):0,g(s.slice(0,-1),p,s[L-1]+q)):o)(n.toString(2)) ``` [Try it online!](https://tio.run/##RY5Ba4QwEEb/ioVSZzDOxh6lo/TurUdru@JG66JJzISFQv@7demhl@/ywXvv2t96GcLsY27dxewj75YrWHliEOU5TdXGHrmSegIhWebBQIHKZ9LqTm1KmFsiko6CuZkgBhoWWoyd4hfS1c32fK4dQ/PCa@3KhwPdIP40zOvT6QMow/fi8UTRSASfbVhq9S/SKr@7lLRNXnTHi6VDsBTdWwyzneAZcR@cFbcYWtwE95TXEPpvKLTW2NHae4BPlVhMuDqWxnmJJsD41wZpkh6IXw "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = input m = // initialize m to a non-numeric value g = ( // g is a recursive function taking: s, // s = middle part of the string (the palindromic one) p = '', q = p // p = left part, q = right part ) => // s ? // if s is not empty: g( // outer recursive call: s.slice(1), // with the first character of s removed ... p + s[0], // ... and appended to p q, // with q unchanged s == [...s] // split s .reverse( // reverse it L = s.length // set L = length of s (argument ignored by reverse) ).join`` ? // join again; if s is a palindrome: o = // update o: ( L <= m ? // if L is not higher than m: o // yield o : // else: !(m = L) // update m to L and yield 0 ) | L == m & // bitwise OR with 1 if L = m (current max.) /^(.+)\1$/ // and the concatenation of p and q can be .test(p + q) // split into 2 identical halves : // else: 0, // abort g( // inner recursive call: s.slice(0, -1), // with the last character of s removed p, // with p unchanged s[L - 1] + q // with the last character of s prepended to q ) // end of inner recursive call ) // end of outer recursive call : // else: o // return o )(n.toString(2)) // initial call to g with s = binary string for n ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 28 bytes ``` ▲foE½†!ḋ¹ṠM-ö→kLfoS=↔m!ḋ¹Qŀḋ ``` [Try it online!](https://tio.run/##yygtzv7//9G0TWn5rof2PmpYoPhwR/ehnQ93LvDVPbztUdukbJ@0/GDbR21TciEygUcbgPT///8tLS0B "Husk – Try It Online") Returns an empty list (which is falsy in Husk) or a nonempty list (which is truthy). ## Explanation The repeated `ḋ` feels wasteful but I'm not sure how to get rid of it. ``` Input is a number, say n=357 ▲f(E½)†!ḋ¹ṠM-(→kLf(S=↔m!ḋ¹)Q)ŀḋ Parentheses added for clarity. ḋ Binary digits: D=[1,0,1,1,0,0,1,0,1] ŀ Indices: I=[1,2,3,4,5,6,7,8,9] (→kLf(S=↔m!ḋ¹)Q) Get indices of longest palindromic runs. Q Slices: [[1],[2],[1,2],..,[1,2,..,9]] f Filter by condition: (S=↔m!ḋ¹) Is a palindrome in D. m Map ! indexing into ḋ¹ D (recomputed). S= That equals ↔ its reverse. kL Classify (into separate lists) by length. → Get the last one: [[2,3,4,5],[4,5,6,7]] ṠM- Remove each from I: [[1,6,7,8,9],[1,2,3,8,9]] † Deep map !ḋ¹ indexing into D (recomputed again): [[1,0,1,0,1],[1,0,1,0,1]] f Filter by condition: (E½) Splits into identical halves. ½ Split into halves (if length is odd, first part is longer): [[1,0,1],[0,1]] E All elements are equal: 0 Result is [] ▲ Maximum, or [] if the argument is empty: [] The final result is nonempty iff the last filter keeps a nonempty list. ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 62 bytes ``` $Q_^@#_/2FIMN(_FI#*Y{c:y@$,:acQRVc?yRAaxx}M$ALCG1+#YTBa)=#_FIy ``` Outputs an empty list for falsey, non-empty for truthy. [Try it online!](https://tio.run/##K8gs@P9fJTA@zkE5Xt/IzdPXTyPezVNZK7I62arSQUXHKjE5MCgs2b4yyDGxoqLWV8XRx9ndUFs5MsQpUdNWGai28v///7oF/w2NAA "Pip – Try It Online") Oy vey. I'm not going to write up a detailed explanation for that monstrosity. Suffice it to say that half the bytecount (roughly the `Y{c:y@$,:acQRVc?yRAaxx}M$ALCG1+#` section) is required to find all palindromic substrings and remove them. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~154~~ 152 bytes ``` def f(n):s=f'{n:b}';k=len(s);return max((b-a,(r:=s[:a]+s[b:])[:(h:=k-b+a>>1)]==r[h:]>'')for a in range(k)for b in range(a,k+1)if(p:=s[a:b])==p[::-1])[1] ``` [Try it online!](https://tio.run/##RY7RCsIgFEB/xTfvbRtMeok73I@ID0raxDLRBUX07dZ62euBczj5tS73dDzl0trZeeYhIVXp@TuR/fApyqtLUHEqbn2UxG7mCWAH00MhWRUZ3VVlSaMiWEjGwXZmngVqKYtaSM@co78XZlhIrJh0cRD/wO7A9LETGDzkLWnIapQyK6JB/LpCt1xCWuGgAtvMsJtiHEdkYdsOqLF9AQ "Python 3.8 (pre-release) – Try It Online") **Commented:** ``` s=f'{n:b}' # convert n to a binary string k=len(s) # and take the length return max( ... )[1] # the second element from the maximum of (b-a, # tuples of palindrome length b-a ... [:(h:=k-b+a>>1)] # ... and is the first half (r:=s[:a]+s[b:]) # of the binary string without the palindrome ==r[h:] # equal to the second half >'') # and not equal to the empty string for a in range(k) # for palindrome starting positions a in [0, 1, ..., k-1] for b in range(a,k+1) # for palindrome end indices b in [1, 2, ..., k-a] if(p:=s[a:b])==p[::-1]) # if this is an actual palindrome ``` If there multiple palindromes of same maximum length, `max` selects the tuple with the highest second value, where `True>False`. [Answer] # [Factor](https://factorcode.org/), ~~209~~ 197 bytes ``` : s ( n -- ? ) >bin dup all-subseqs [ dup reverse = ] filter dup [ last length ] dip [ length over = ] filter nip [ split1 append [ ""= not ] keep dup length 2/ cut = and ] with [ or ] map-reduce ; ``` [Try it online!](https://tio.run/##TZAxT8MwEIX3/IqnTiCRkDC2KoyoSxfEFGVwkmuw6jjmfAb668M1QSqLZT9/n9/JJ9PJxPP72@H4uoVhNpeIM7Enh9HIx7IUwXAkRqTPRL6jeNsV9CNsNAjOilg/rAIbPygWmEQuga0XDDylcAV22eG4VWFiao1zuU9jSxxnzXAHjzzHC@7x3FqPPgVcmZharYyol4TpSwXCHg1O1glxdo1rOBMFjvyggzfo7ZKtx0mVfwK8DVm9jl3BhEC@V3iz2cNPotiZKCxlf/7TI7ok@oJRsMm@rWY1JlZ0NCFn6lNH2M1VWZaoq4e20et466uq9QdQzL8 "Factor – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~33~~ 42 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` s2 ã fêS üÊo Vc@ðXãjXVÎlîòZÊ/2Ãd_Ê©ZÎ¥Zo ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=czIK4yBm6lMg/MpvClZjQPBYw6NqWFbObMOu8lrKLzLDZF/KqVrOpVpv&input=WzEsMiwzLDQsNSwyMCwyMSwyMiwyMywyNCwyNSw5MjIsOTIzLDkyNCwyNDA1XQotbQ) ``` s2 - convert input to binary string ã - substrings fêS - filter palindrome üÊo - take last group by length Vc@ðXà - find indexes of each palindrome in input £jXVÎlà - map those indexes by removing n(=palindr.length) characters from input at index ®òZÊ/2à - split all results d_ - return true if any : Ê© - exists and.. ZÎ¥Zo - are == ``` * Fixed : now works for numbers with more identical longest palindromic runs like 2405 => 100101100101 * [Test](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=XysxfWgxMDAwLFsxXSBtczIKbVR7W1QsVOMgZupTIPzKb10KVmZUe1RnMSBjQFRnIPBYw6NUZyBqWFRnMSBnIGzDrvJayi8yw2RfyqlazqVab319IG1fZyBuMgo9TmcgciJcbiJTIHFTIG1uIGVX&input=IjEyIDIwIDIzIDI0IDI2IDI4IDI5IDM5IDQ4IDU3IDYwIDY4IDcxIDg0IDg3IDk2IDEwMCAxMDYgMTA4IDExMCAxMTEgMTEzIDExNyAxMjMgMTI0IDEzMgoxMzUgMTU0IDE2NiAxNzggMTgwIDE4MyAxOTIgMjA0IDIwNyAyMTAgMjIyIDIyNSAyMzcgMjQwIDI0MyAyNTIgMjYwIDI2MyAyNzcgMjgyIDI4NyAyOTUKMzE0IDMyNiAzMzQgMzM2IDMzNyAzNDAgMzQzIDM0OCAzNTEgMzU0IDM3MCAzNzIgMzc1IDM4NCAzOTIgMzk0IDM5NiAzOTkgNDA0IDQxMiA0MTggNDI2CjQyOCA0MzEgNDMyIDQ0NiA0NDkgNDU3IDQ2OSA0NzYgNDc3IDQ3OSA0ODAgNDgzIDQ4NCA0OTAgNDkxIDQ5NiA0OTcgNTAxIDUwMyA1MDggNTE2IDUxOQo1MzMgNTM4IDU0MyA1NjIgNjAwIDYxMCA2MTIgNjE1IDYzNCA2NDYgNjUyIDY2MCA2NjMgNjY0IDY3MCA2NzMgNjc2IDY5MSA3MDAgNzAzIDcwNiA3MTgKNzIwIDczNSA3NDIgNzU0IDc1NiA3NTkgNzY4IDc3OCA3ODAgNzgzIDc5MiA4MDQgODE2IDgyMSA4MjYgODI4IDgzMSA4MzQgODU4IDg3MCA4NzQgODc2Cjg3OSA4OTQgODk3IDkxOCA5MjEgOTIyIDkyNCA5MjcgOTMzIDk1NyA5NjAgOTYzIDk3MiA5NzggOTg3IDk5MyA5OTki) : computes first 1000 terms and check if the result is the same as test cases. [Answer] # Dotty, 201 bytes ``` s=>((for{j<-1 to s.size i<-0 to j-1 x=s.slice(i,j)if x==x.reverse}yield(i,j))groupBy(_-_)minBy(_._1)_2)exists{(i,j)=>val x=s.slice(0,i)+s.substring(j) x!=""&&x.slice(0,x.size/2)==x.substring(x.size/2)} ``` [Try it online (in Scastie)](https://scastie.scala-lang.org/hDAhXWU9RBG5TjocTVlggw) Input must already be a binary string. # Dotty, 226 bytes ``` x=>{val s=x.toBinaryString ((for{j<-1 to s.size i<-0 to j-1 x=s.slice(i,j)if x==x.reverse}yield(i,j))groupBy(_-_)minBy(_._1)_2)exists{(i,j)=>val x=s.slice(0,i)+s.substring(j) x!=""&&x.slice(0,x.size/2)==x.substring(x.size/2)}} ``` [Try it online (in Scastie)](https://scastie.scala-lang.org/ZeGwIfITQuWtU9WYsQyULg) Input is an `Int`. ]
[Question] [ I have just tried a game called [Couch 2048](https://js13kgames.com/games/couch-2048/index.html). (Note: You should have a look to better understand this question.) Since it wasn't very exciting for me, I've been asking myself *'How much more till 2048!?'* That inspired me to post a challenge, because calculating this in not as easy as I thought. **Your goal:** Given a list of balls on the sofa, you have to output how many balls with a value of 2 have to fall from the sky so that one can win the game (by reaching the 2048 ball). * Assume the input is valid. * Assume the player won't drop any balls. * Assume the balls which fall from the sky always have a value of 2, as I've said. * Valid output examples: 3, "4", [5], ["6"] **Edit:** I should clarify something: - You have to print the *smallest* amount of 2s needed. **Test cases:** `[2048] -> 0` You've already won `[1024,1024] -> 0` You don't need any more balls to win `[1024,512,256,128,64,32,16,8,4,2] -> 1` One ball required to *'activate the chain'* `[512] -> 768` `[512,2] -> 767` `[4,16,64] -> 982` **Notes**: I'm not a native speaker - Tell me if you spotted a typo or some non-grammatical text. If something's unclear, ask in comments. [Answer] # Java 8, 17 bytes ``` s->1024-s.sum()/2 ``` Port of [*@LuisFelipeDeJesusMunoz*' JavaScript answer](https://codegolf.stackexchange.com/a/175769/52210). [Try it online.](https://tio.run/##fZDBTsMwDIbvewofE8k1a8iqShO778AuOyIOoctQSptOizsJoT17SUKFgElcrNj@8v@2W3MxRXt4m5rOhACPxvmPBYDzbM9H01jYpRRyBRrRRpxGdh0FPlvT09bzPr/AyXUkr4sYAht2DezAw8MUik25VLoIFMZeyDs1rRNzGl@6yMzoZXAH6KO5iGrOvz49g5FfzmwDC7XUddaf86SIKdwUV6VCtaqwVDVWGu8VlhXWqFH9RCP1J/3d1@lXpW9WynNmIt6DiL6n3L8Htj0NI9MpLsCdF57@uxcNR2GknB2u0yc) **Explanation:** ``` s-> // Method with IntStream parameter and int return-type 1024- // Return 1024, minus: s.sum() // The sum of the input-IntStream /2 // Divided by 2 ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 72 bytes ``` ({{}})({<({}[()()])>()}{})([{}]((((((((()()()()){}){}){}){}){}){}){}){}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6urZWU6PaRqO6NlpDU0MzVtNOQ7O2GigWXV0bqwEDmhCoCZTAiv7/N1EwNFMwMwEA "Brain-Flak – Try It Online") ``` ({{}}) # Sum entire stack ( ) # Push: {< >()}{} # The number of times you can... ({}[()()]) # Subtract 2 before reaching 0 ([{}] ) # Subtract that from... ((((((((()()()()){}){}){}){}){}){}){}){} # 1024 ``` [Answer] # [Python 2](https://docs.python.org/2/), 22 bytes ``` lambda x:4**5-sum(x)/2 ``` Y'know, I *just* realized that `4**5` is the same length as `1024`. [Try it online!](https://tio.run/##K6gsycjPM/qfaBvzPycxNyklUaHCykRLy1S3uDRXo0JT3@h/QVFmXolGoka0oYGRiY6poZGOkamZjqGRhY6ZiY6xkY6hmY6FjomOUaymJhdcrQlI2MwEKPYfAA) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/create_explanation.py), ~~6~~ 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` Σc/◘+ ``` First MathGolf answer. :) [Try it online](https://tio.run/##y00syUjPz0n7///c4mT9R9NnaP//H21qaKRjFAsA) or [verify all test cases](https://tio.run/##y00syUjPz0n7X314TaGSwqO2SQpKhf/PLU7WfzR9hvb/gv/R0UYGJhaxOtGGBkYmOiACxjY1NNIxMjXTMTSy0DEz0TE20jE007HQMdExAqoASkJIMM8EJGVmEhsLAA). **Explanation:** ``` Σ # Sum of the (implicit) input-list c/ # Divide it by -2 ◘+ # Add 1024 to it (and output implicitly) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` O;žBα ``` Port of [*@LuisFelipeDeJesusMunoz*' JavaScript answer](https://codegolf.stackexchange.com/a/175769/52210). [Try it online](https://tio.run/##yy9OTMpM/f/f3/roPqdzG///jzY1NNIxigUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@d/f@ug@p3Mb/@v8j442MjCxiNVRiDY0MDLRARFwjqmhkY6RqZmOoZGFjpmJjrGRjqGZjoWOiY4RSAlQFkpB@CYgWTOT2FgA). **Explanation:** ``` O # Sum of the (implicit) input-list ; # Halved žB # Push 1024 α # Absolute difference between the two (and output implicitly) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes ``` 2÷⍨2048-+/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@jw9ke9K4wMTCx0tfX/pz1qm/Cot8/wUVfzofXGj9omPuqbGhzkDCRDPDyD/6cpGGkZGnKBKQMFQwMw61HP3ke9m6EcSwipAFFkpGCiYAYA "APL (Dyalog Unicode) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 25 bytes Based on [@Shaggys' comment and answer](https://codegolf.stackexchange.com/a/175768/78039) *-3 bytes from @Arnauld =D* ``` _=>1024-eval(_.join`+`)/2 ``` [Try it online!](https://tio.run/##dY3BDoMgEETv/RKIq5XtSrjoj5hGicVGQ9imNv4@lqvByxxm3sysdrfb9F0@vzLwy8W5jUPbqRqpdLv1YqhWXsJYjPKOceKwsXeV57eYRY81maeUt5OdypDkKmsUAjYaFBrQBA8EpcEAAWYafzjvZmlKUzo9xwM "JavaScript (Node.js) – Try It Online") [Answer] # [J](http://jsoftware.com/), 10 bytes ``` 2048-:@-+/ ``` [Try it online!](https://tio.run/##VcpBCoMwFEXReVZxcSJFTZPvN4SA0L2UhuLEgWPXHrUg1cnj8jhTyctocSRcEaexS6@ueZaHqSx1Hm1Ny5rIizGf93cmc6izvRP9ze0YvCBDwEskKL3gAxFFTraLS/5/PWTQsgE "J – Try It Online") ## Alternative: # [J](http://jsoftware.com/), 10 bytes ``` 1024-1#.-: ``` [Try it online!](https://tio.run/##VYvLCoMwFAX3@YrBLqSgIff2GkLArxFD6caFa789PkDabg7DMOdTyzp6AplQJaj18vB9rk/XeNoy@paOLVNW5@bpvVDQYOnm83HNnxhE0SEimojGS5FIwtA7O4of/Ho7y2h1Bw "J – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 17 bytes ``` ->l{1024-l.sum/2} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6n2tDAyEQ3R6@4NFffqPZ/gUJadDRISMfU0EjHyNRMx9DIQsfMRMfYSMfQTMdCx0THKDaWC6zMBCRiZhIb@x8A "Ruby – Try It Online") [Answer] # [Catholicon](https://github.com/okx-code/Catholicon), 5 bytes ``` -`L̇½Ṗ ``` Explanation: ``` - subtract `L̇ 1024 from ½ half of the Ṗ sum [of the input] ``` [Answer] # TI-Basic, 8 bytes ``` 4^5-.5sum(Ans ``` [Answer] # JavaScript, 28 bytes ``` a=>a.map(n=>x-=n/2,x=1024)|x ``` [Try it online](https://tio.run/##PY3BCsIwEETv@ZIEtrVZt6GXzY@EHEJtRalJaUVy8N@jUfEyw@MNzDU8wj5ul/XexHSayswlsA3tLawyss0NxwNCZt0hqWcuY4p7WqZ2SWfphMOOBg/CVQ01/tBrBOwNaBzAEBwRtIEBCLBO3vZXX6ZqDXnhP8@Z7SyzUqq8AA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` HSạ⁽¡ç ``` [Try it online!](https://tio.run/##y0rNyan8/98j@OGuhY8a9x5aeHj5////o010DM10zExiAQ "Jelly – Try It Online") **Explanation:** ``` HSạ⁽¡ç Example input: [4,16,64] H Halve input. [2, 8, 32] S Sum. 42 ⁽¡ç Number 1024. ạ Difference. 982 ``` -1 byte by using a base-250 number [Answer] # Japt, ~~7~~ 6 bytes ``` xz nH² ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=eHogbkiy&input=WzEwMjQsNTEyLDI1NiwxMjgsNjQsMzIsMTYsOCw0LDJd) or [verify all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=eHogbkiy&input=WwpbMjA0OF0sClsxMDI0LDEwMjRdLApbMTAyNCw1MTIsMjU2LDEyOCw2NCwzMiwxNiw4LDQsMl0sCls1MTJdLApbNTEyLDJdLApbNCwxNiw2NF0KXQotbVI=) ``` z :(Floor) divide each by 2 x :Reduce by addition n :Subtract from H : 32 ² : Squared ``` [Answer] # perl -aE, 27 bytes ``` $"=$:;say eval"(2048-@F)/2" ``` This reads a line with numbers (whitespace separated) from `STDIN`, and writes the answer to `STDOUT`. What it does is subtract all the numbers from the input from 2048, and it divides the remainder by 2. The `-a` switch puts the in the array `@F` (one number per element). If we interpolate an array into a string (which is what we are doing here), perl puts the value of `$"` between the elements. The little used variable `$:` is be default `\n-`; and since white space between tokens is ignored, the result is subtracting all the numbers from 2048. The `eval` does the calculation. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes ``` ∑k¦ε½ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%91k%C2%A6%CE%B5%C2%BD&inputs=&header=&footer=) ``` ∑ # Sum k¦ # 2048 ε # Abs. diff. ½ # halved ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 33 bytes ``` a=>!a.map(n=>x-=n/2,x=1024)>x?0:x ``` [Try it online!](https://tio.run/##VY5BDsIgFET3vYU7SH4rfCkhJuBBCAtSW6Op0Fhj/u1R1E03M5mZt5hbfMV1eFyXZ5vyeSyTLdG6XezucWHJOmpt2iOQlQIVd3QSRypDTmuex27OF@Ybj0KZAI2vCFTZhG3TSwTsNUg0oBUcEKQGAwqwIp/1b7@s6qpVaML3D1k3MeKclzc "JavaScript (Node.js) – Try It Online") Why you don't do on `[1024,1024,1024]`? [Answer] # [R](https://www.r-project.org/), 17 bytes ``` 4^5-sum(scan())/2 ``` [Try it online!](https://tio.run/##K/r/3yTOVLe4NFejODkxT0NTU9/ovwmXoRmXmQnXfwA "R – Try It Online") [Answer] # [TeaScript](https://teascript.readthedocs.io/en/latest/index.html), 11 bytes ``` 4p5)-(xx)/2 ``` [Try it online!](https://vihan.org/p/TeaScript/?code=x.r(R(x%5B0%5D%2C%27gi%27)%2C%27%27)&input=Test)#?code=%224p5)-(xx)%2F2%22&inputs=%5B%22%5B1024,512,256,128,64,32,16,8,4,2%5D%22%5D&opts=%7B%22ev%22:true,%22debug%22:false,%22nox%22:true%7D) [Answer] # [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ë3i─♠÷ ``` [Run and debug it](https://staxlang.xyz/#p=893369c406f6&i=[2048]%0A[1024,1024]%0A[1024,512,256,128,64,32,16,8,4,2]%0A[512]%0A[512,2]%0A[4,16,64]&a=1&m=2) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 12 bytes ``` 1024-*.sum/2 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvw39DAyERXS6@4NFff6L81V3FipUKaRrSRgYlFrCacC1KkAyLQxUwNjXSMTM10DI0sdMxMdIyNdAzNdCx0THSMkFQCFaHyUGRNQFrMQCb/BwA "Perl 6 – Try It Online") Anonymous Whatever lambda that takes a list and returns a number. [Answer] # AWK, 26 bytes ``` {s+=$1}END{print 1024-s/2} ``` Input numbers are separated by newlines (i.e. one per line) [Answer] # Neim, 6 bytes Pretty new to Neim but got it working ``` 𝐬ᚺςᚫᛦ𝕤 ``` Explanation: ``` 𝐬 : Sum input ᚺ : Divide by 2 (stack now [input summed and divided by 2]) ς : Variable set to 16 pushed to stack ᚫ : Multiply by 2 ᛦ : Square (stack now [input summed and divided by 2, 1024]) 𝕤 : Subtract then absolute ``` [Try it online!](https://tio.run/##ATwAw/9uZWlt///wnZCs4Zq6z4Lhmqvhm6bwnZWk//9bMTAyNCA1MTIgMjU2IDEyOCA2NCAzMiAxNiA4IDQgMl0) [Answer] **JAVA, 30 bytes** ``` 2048-IntStream.of(a).sum()/2; ``` [Answer] # [RAD](https://bitbucket.org/zacharyjtaylor/rad), 10 bytes ``` 1024-+/ω÷2 ``` [Try it online!](https://tio.run/##K0pM@f/f0MDIRFdb/3zn4e1G////N9IyUjBRMAMA "RAD – Try It Online") [Answer] # [Clojure](https://clojure.org/), 24 bytes ``` #(- 1024(/(apply + %)2)) ``` [Try it online!](https://tio.run/##dY1BCoMwFET3nmJAhB@KmPx@Q@4iLqQ10BJskHbh6aPpso3bmfdmbuH1/KxzSjW1MJqFOppiDBsuaBQrleg@e3ic9aqiuD6Wd1hAHgNrceNvmL2vXG56w@DewrCDFVwZxsJBwH/8gZayAil5xObHtAM "Clojure – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 16 bytes ``` (1024-).(/2).sum ``` An anonymous function, takes a list and returns a float. [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BVkHD0MDIRFdTT0PfSFOvuDT3f25iZh5QvKAoM69EQUUhTSEapEJHwdTQSEfByNRMR8HQyEJHwQwoZAwUMQQKALlAnlHsfwA "Haskell – Try It Online") [Answer] # F#, 24 bytes ``` fun f->1024-List.sum f/2 ``` 1024 minus the sum divided by 2. ]
[Question] [ Problem A3 from [the 2008 Putnam competition](https://kskedlaya.org/putnam-archive/2008.pdf) says: > > Start with a finite sequence \$a\_1, a\_2, \dots, a\_n\$ of positive integers. If possible, choose two indices \$j < k\$ such that \$a\_j\$ does not divide \$a\_k\$, and replace \$a\_j\$ and \$a\_k\$ by \$\gcd(a\_j, a\_k)\$ and \$\text{lcm}(a\_j, a\_k)\$, respectively. Prove that if this process is repeated, it must eventually stop and the final sequence does not depend on the choices made. > > > Your goal in this challenge is to take a finite sequence of positive integers as input, and output the result of repeating this process until no further progress is possible. (That is, until every number in the resulting sequence divides all the numbers that come after it.) You don't need to solve the Putnam problem. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the shortest solution in every programming language wins. ## Test cases ``` [1, 2, 4, 8, 16, 32] => [1, 2, 4, 8, 16, 32] [120, 24, 6, 2, 1, 1] => [1, 1, 2, 6, 24, 120] [97, 41, 48, 12, 98, 68] => [1, 1, 2, 4, 12, 159016368] [225, 36, 30, 1125, 36, 18, 180] => [3, 9, 18, 90, 180, 900, 4500] [17, 17, 17, 17] => [17, 17, 17, 17] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] => [1, 1, 1, 1, 1, 2, 2, 6, 60, 2520] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ÆEz0Ṣ€ZÆẸ ``` [Try it online!](https://tio.run/##y0rNyan8//9wm2uVwcOdix41rYk63PZw147/R/ccbgfyFI5OerhzBpABYmeB6IY5CrZ2Co8a5ipE/v@vwaUQbaijYKSjYKKjYKGjYGimo2BsFKsDEjYyAEoAhc3A8kBVhmBxS3OgYiDPBKQcKGEJpM0swFJGRqZA7SAjgFoNDWE8Q5BKCwOIqUDdCAwRAptvDHaCKdg6c7BbLIEqQJo0AQ "Jelly – Try It Online") ### How it works ``` ÆEz0Ṣ€ZÆẸ Main link. Argument: A (array) ÆE For each n in A, compute the exponents of n's prime factorization. E.g., 2000000 = 2⁷3⁰5⁶ gets mapped to [7, 0, 6]. z0 Zip 0; append 0's to shorter exponent arrays to pad them to the same length, then read the resulting matrix by columns. Ṣ€ Sort the resulting arrays (exponents that correspond to the same prime). Z Zip; read the resulting matrix by columns, re-grouping the exponents by the integers they represent. ÆẸ Unexponents; map the exponent arrays back to integers. ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 33 bytes Calculate the [elementary divisors](https://en.wikipedia.org/wiki/Smith_normal_form) of the diagonal matrix. ``` a->Vecrev(matsnf(matdiagonal(a))) ``` [Try it online!](https://tio.run/##RY7dCoMwDIVfJXhloQVT/y/mY@xGehE2FcG54mSwp@@SwNhFSc/Jd5JEOla3xDTDBRK54TrdjumdP@h87bOU@0rLc6ctJ2NMohi3T07gBojHup/8zURkMAtgYRzRgrdQWegsYGOh9IFt9AX77DbaZgjF7ltGWVQCs99zbTrpeF9zVvIcRPwpFLArdCRn/08dnV3q9lpXtXpGz0ARgklf "Pari/GP – Try It Online") [Answer] # [J](http://jsoftware.com/), 17 bytes ``` /:~"1&.|:&.(_&q:) ``` [Try it online!](https://tio.run/##TU7LCsIwELz7FUMPqQWJu5s0L/BbPIhFvIi3HNRfTxdKg7DDDjPLzD7bYDEuuJQRJ3wLCIp2Lr@Bjf0UY49X8y5Tmw732@OFBQyBRwIHOOmiEMQjqMfgXc2xwrMiVb2oyLpDqrstMsNpCoF5o6yxiXpo7PNf7rR@1qqoT2QwtRU "J – Try It Online") Probably the first J answer on PPCG to use `&.` twice. After this and [that](https://codegolf.stackexchange.com/a/174017/78410), I'm starting to feel like a weird J hacker. Basically a translation from [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/175092/78410). ### How it works ``` /:~"1&.|:&.(_&q:) Single monadic verb. (_&q:) Convert each number to prime exponents (automatically zero-filled to the right) |:&. Transpose /:~"1&. Sort each row in increasing order |:&. Transpose again (inverse of transpose == transpose) (_&q:) Apply inverse of prime exponents; convert back to integers ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Table[GCD@@LCM@@@#~Subsets~{i},{i,Tr[1^#]}]& ``` The \$k\$-th element of the result is the GCD of the LCM's of the subsets with \$k\$ elements. \$b\_k = \gcd(\{\operatorname{lcm}(a\_{i\_1}, \cdots, a\_{i\_k}) | 1 \le i\_1 < \cdots < i\_k \le n\})\$ [Try it online!](https://tio.run/##RY49C8IwEIb/ykHAKWKTfg9KoIKLgmC3EKGVFgPWoY1TSP96vATEIYR77nnvburMc5g6ox@dH2Hv265/DfLUHIU4NxchBFlvn34ZzLJa7ajVtJ0luxPl1MZfZ/02ksD2AKMkSsEGdgKsZRQ4hYxCRYEVFFLuKFjGE@RIi9hGiQVcl6hikQUZeY1/UYUO5zlmQx6DjP0qFsQqiSMx@3@RxNlp3J7HVWU8o0Yhcc5/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 103 bytes ``` import math def f(a,i=0,j=-1):d=math.gcd(a[i],a[j]);a[j]*=a[i]//d;a[i]=d;a[i:j]and f(a,i,j-1)==f(a,i+1) ``` [Try it online!](https://tio.run/##RU/NDoIwDL7zFD2KVmVDEDB7ErLD4kS2RCC4i0@PXRVdsvXn@@k6vUI/DvmyuMc0zgEeJvSJvXXQbQw6laFXe5E2VkXgcL/ajWmdRtN6nV7iu1WxcTzaS4yKQ@O1GezHAj3pleJ8J9Il3J7BmmBAQZsAnVYgSIQTQoUgSoRcavwiMiOMkJIpRBQrVJ9JQo1TFBFWUyyrFZWyIJ/oRQZCrJWI5Cr72ZPH//66PCvnHxU8@sxfq4kUpTpJunEGA26AdZmGpbRjysk0uyFQsbwB "Python 3 – Try It Online") ### Explanation This problem is essentially a parallel sort on the prime factors, and (gcd(a,b), lcm(a,b)) is analogous to (min(a,b), max(a,b)). So let's talk in terms of sorting. We will prove by induction that after f(i,j), a[i] becomes the smallest value in (the old value of) L, where L is the range between a[i] and a[j], including both ends. And if j = -1, f(i,j) will sort the range L. The case when L contains one element is trivial. For the first claim, notice that the smallest of L can't stay in a[j] after the swap, so f(i,j-1) will put it in a[i], and f(i+1,-1) will not affect it. For the second claim, note that a[i] is the smallest value, and f(i+1,-1) will sort the remaining values, so L becomes sorted after f(i,j). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 65 bytes ``` \d+ * +`\b((_+)(\2)+)\b(.*)\b(?!\1+\b)(\2+)\b $2$4$5$#3*$5 _+ $.& ``` [Try it online!](https://tio.run/##NYzBCsIwDIbveQsxStuE0aTtNk8efYnC5tDDLh7E968pIoSQ/0vyvZ@f/XWXdnK3tdUHQQBa6@bcQt5V9eQtDKH366EK1a3jTgEVMxY8poAFFgIczq0JK2eeWUZOCqKRNfNoUFhAtXCyRWSR3yh2OUeQif8F3ZDMUextMtOFJX4B "Retina – Try It Online") Link includes the faster test cases. Explanation: ``` \d+ * ``` Convert to unary. ``` +`\b((_+)(\2)+)\b(.*)\b(?!\1+\b)(\2+)\b ``` Repeatedly match: any number with a factor, then a later number that is not divisible by the first number but is divisible by the factor. ``` $2$4$5$#3*$5 ``` `$1` is the first number. `$2` is the factor. Because regex is greedy this is the largest factor i.e the gcd. `$4` is the part of the match between the original numbers. `$5` is the second number. `$#3` (in decimal rather than unary) is one less than `$1` divided by `$2`, since it doesn't include the original `$2`. This means that to calculate the lcm we need to multiply `$5` by one more than `$#3` which is most succintly written as the sum of `$5` and the product of `$#3` and `$5`. ``` _+ $.& ``` Convert to decimal. [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 69 bytes ``` a=>a.map((q,i)=>a.map(l=(p,j)=>a[j]=j>i&&(t=p%q)?p/t*l(q,j,q=t):p)|q) ``` [Try it online!](https://tio.run/##bVHbToQwEH3fr@iLS8dUpNx20RSf/Aok2QZZLRYoFzcx8d9xCst6iQmlnTNnzplpK3mSQ9ErM94MRj2Xfd02b@XHdBSTFKl0a2ko7ZiCNdCCGlbZMKtyUaVqu6WjMFcdPJjb8VojuWKdGOHOwGcH0/1hk3FGfEZCRvaM8JiRwM@JSMl/OJJ9D2EE4zmLHH5hLwXxkkci0pMdKiAeWg1MJrjH@z8V4ZLjUeLxOMD0JvP9CA2tKdpxvkbcyuy9pT5AuQVKvBm2B/yFkWetOVp/r7Plb2ydPZh7iObed/O8Vtj72ebl89chY3sRkZ3y4I69qim4g9FqpM5T48D5NVK9glbLAXCPbf8oi1dKM8XKHF@qaJuh1aWr2xeqGGnFe1OepKZHOm8KACwqSoDpCw "JavaScript (SpiderMonkey) – Try It Online") * Function `l` assign `lcm(p,q)` to `a[j]`, and assign `gcd(p, q)` to `q` if `j > i`, otherwise keeps everything unchanged. + `lcm(p,q) = if p%q=0 then p else p*lcm(q,p%q)/(p%q)` --- Old answer: # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 73 bytes ``` a=>a.map((u,i)=>a.map((v,j)=>i<j?a[j]*=u/(g=p=>p%u?g(u,u=p%u):u)(v):0)|u) ``` [Try it online!](https://tio.run/##bVHZboMwEHzPV/ilirdyqc0VSGvy1K@gkWKlJDXlEsRIlfrvdG1KeqgSxt7Z2Zldu1SjGo697i53Q6dfir5um7fifTrJSclMebXqKDVMwzUYWYmBfix3Ki/3t9Lc07PsZNbdmN0ZqUbiCbYG6AhbDh8GpofDKheM@IyEjCSMiJiRwN8TmZH/cCT7HGEEY5dFjriy54J4ziMR6ekGFRAPrQYmU9zj5E9FOOdElHIRB5he5b4foaE1RTshlkhYmYTP9QHKzVDKHWwP@Asjbq0FWn@vL8vf2DJ74HqIXO8bN68V5j/bvH7@MmRsLyKyUx68S69rCt7QVfpC18/NGtyLVDKrFtBqrQG8U9s/qeMrpblmxR7f69g2Q1sVXtWeqWaklaYpRlXRE3WbBgCLygJg@gQ "JavaScript (SpiderMonkey) – Try It Online") * Function `g` calculate `gcd(u, v)` and assign return value to `u`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes Credit for the approach goes to [alephalpha](https://codegolf.stackexchange.com/a/175097/59487). ``` εIæN>ù€.¿¿ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3FbPw8v87A7vfNS0Ru/Q/kP7//@PNjIy1VEwNgNiAx0FQ0MYz9AChA1iAQ "05AB1E – Try It Online") ``` εIæN>ù€.¿¿ Full program. Takes a list from STDIN, outputs another one to STDOUT. ε Execute for each element of the input, with N as the index variable. Iæ Powerset of the input. N>ù Only keep the elements of length N+1. €.¿ LCM each. ¿ Take the GCD of LCMs. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes ``` {map {[gcd] map {[lcm] $_},.combinations: $^i},1..$_} ``` [Try it online!](https://tio.run/##RY5NCoNADIX3PUUWUhSCmFHHH@hJihVraxEcFe1GxLNPMymliyGT772XZH4ug7Zmg3MHF7ubZob9@mofFXy/Q2sq8OoDw3Yy935s3v00riV4t/5ACkOW7Nps0PleHUA3LSefEBRCgpAjkEaIVYBMVcScqRaZTeRwkbGVm8SZmRdcde4UpVLOujwHiX4dOWMeyUjO/p8QmR3L9lRWZXJGwYYosB8 "Perl 6 – Try It Online") Port of alephalpha's Mathematica answer. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ó¾ζ€{øεgÅpymP ``` Port of [*@Dennis♦*' Jelly answer](https://codegolf.stackexchange.com/a/175092/52210), but unfortunately 05AB1E doesn't have an Unexponents-builtin, so that takes more than halve the program.. :( -1 byte thanks to *@Mr.Xcoder*. -1 byte thanks to *@Emigna*. [Try it online](https://tio.run/##yy9OTMpM/f//8ORD@85te9S0pvrwjnNb0w@3FlTmBvz/H21kZKpjbKZjbKBjaAhhGloAkUEsAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w5MP7Tu37VHTmurDO85tTT/cWlCZG/C/Vud/dLShjpGOiY6FjqGZjrFRrI5CtKGRgY6RiY4ZUNxQxxAkYmmuY2KoYwJUY6RjaaFjZgESNDIy1TEG6jHQMTSEMA2BCiwMwEaY68AQmAs0yhhoiSnQUHOgVZY6hgaxsQA). **Explanation:** ``` Ó # Prime exponents of the (implicit) input-list ¾ζ # Zip, swapping rows and columns, with integer 0 as filler €{ # Sort each inner list ø # Zip, swapping rows and columns again ε # Map each inner list: gÅp # Get the first `l` primes, where `l` is the size of the inner list ym # Take the power of the prime-list and inner list P # And then take the product of that result # (And output implicitly) ``` ]
[Question] [ A [parity bit](https://en.wikipedia.org/wiki/Parity_bit), is one of the simplest forms of a checksum. First, you have to pick the parity, even or odd. Let's say we pick even. Now, we need a message to transmit. Let's say our message is "Foo". This is written in binary as: ``` 01000110 01101111 01101111 ``` Now, we count the total number of `1`'s in there, which is 15. Since 15 is an odd number, we must add one extra bit to the end of our message, and we will now have an even number of 'on' bits. This last added bit is known as the "parity bit". If we had picked an odd parity for our checksum, we would have to add an extra '0' so that the number of on bits remains odd. # The challenge: You must write a program or function that determines what the correct parity bit for a string is. Your program must take two inputs: * A string, `s`. This is the message that the checksum will be calculated on. This will be restricted to the 95 printable ASCII characters. * A character or single character string `p`, that will either be `e` for even parity, or `o` for odd parity. and produce a [truthy-falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value representing the correct parity bit. Truthy if it's a `1`, and falsey if it's a `0`. Builtins that count the number of "on" bits in a string or character are not allowed. For example, a function `f` that does this: `f('a') == 3` or `f('foo') == 16` is banned. Anything else, such as base conversion, is fair game. # Test IO: ``` (without the quotes) s: "0" p: 'e' output: 0 s: "Foo" p: 'e' output: 1 s: "Hello World!" p: 'o' output: 0 s: "Alex is right" p: 'e' output: 1 s: "Programming Puzzles and Code-Golf" p: 'e' output: 0 s: "Programming Puzzles and Code-Golf" p: 'o' output: 1 ``` This is codegolf, so standard loopholes apply, and the shortest answer in bytes wins. # Leaderboard ``` var QUESTION_ID=78569,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~8~~ 7 bytes ``` 8\hBz2\ ``` [Try it online!](http://matl.tryitonline.net/#code=OFxoQnoyXA&input=J28nCidQcm9ncmFtbWluZyBQdXp6bGVzIGFuZCBDb2RlLUdvbGYn) Or [verify all test cases at once](http://matl.tryitonline.net/#code=YCAgICAgICAgICAlIGRvLi4ud2hpbGUgbG9vcAo4XGhCejJcICAgICUgYWN0dWFsIGNvZGUKRCAgICAgICAgICAlIGRpc3BsYXkgKGFuZCBwb3ApClQgICAgICAgICAgJSB0cnVlICh0aHVzIGluZmluaXRlIGxvb3AgdW50aWwgYWxsIGlucHV0IGlzIGNvbnN1bWVkKQ&input=J2UnCicwJwonZScKJ0ZvbycKJ28nCidIZWxsbyBXb3JsZCEnCidlJwonQWxleCBpcyB3cm9uZycKJ2UnCidQcm9ncmFtbWluZyBQdXp6bGVzIGFuZCBDb2RlLUdvbGYnCidvJwonUHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZS1Hb2xmJwo). ``` 8\ % Implicitly take first input ('e' or 'o'), and compute modulo 8. Inputs 'e' and 'o' % give 5 or 7 respectively, which have an even or odd number of `1` bits resp. h % Implicitly take second input, and concatenate B % Convert to binary. Gives 2D array, with one row for each original entry z % Number of nonzero values in that 2D array 2\ % Modulo 2, i.e. compute parity ``` [Answer] ## Java, 97 bytes [Because, ya know, Java.](http://meta.codegolf.stackexchange.com/a/5829/51825) ``` (s,c)->{boolean e=1>0;for(int i:s.getBytes())while(i>0){if(i%2==1)e=!e;i/=2;}return c=='o'?e:!e;} ``` This is a lambda for a `BiFunction<String, Character, Boolean>`. `e` and `o` appear to be reversed in the return statement because apparently my logic was backwards. [Answer] # C, 62 bytes * 12 bytes saved thanks to @LevelRiverSt and @TonHospel. XOR has the nice property that it can be used to reduce strings down to one char, while preserving parity. ``` f(s,p)char*s;{for(p/=8;*s;)p^=*s>>4^*s++;p^=p/4;return p%4%3;} ``` [Ideone.](https://ideone.com/6m9ux6) [Answer] ## Python 2, 51 bytes ``` lambda s,p:`map(bin,map(ord,p+s))`[9:].count('1')%2 ``` This is based on [an idea of Sp3000](https://codegolf.stackexchange.com/questions/78569/generate-a-parity-bit#comment192199_78570) to count 1's in the string representation of the list of character codes in binary rather than summing for each character. The new trick is to handle `e` and `o` in this as well. If `e` was odd and `o` even, we could just prepend the parity bit to the string before doing the count (flipping them because '1' is Truthy). Unfortunately, they are not. But, if we remove all but their last two bits, it's now true. ``` e 0b11001|01 o 0b11011|11 ``` This is done by removing the first `9` character of the string representation. ``` ['0b11001|01', ``` [Answer] ## Jelly, ~~9~~ 8 bytes ``` OBFSḂ⁼V} ``` [Try it online!](http://jelly.tryitonline.net/#code=T0JGU-G4guKBvFZ9&input=&args=Rm9v+ZQ) ``` O convert each character in argument 1 (left arg) to its codepoint (ord) B convert to binary (list of 0s and 1s) F flatten S sum the entire list, giving the number of 1s in the entire string Ḃ mod 2 (take the last bit) } now, with the second (right) argument... V eval with no arguments. This returns... 1 for e because it expands to 0e0 (i.e., does 0 exist in [0]) 0 for o because it expands to 0o0 (0 OR 0, false OR false, false) ⁼ test equality between the two results ``` Thanks to Dennis for a byte! [Answer] # Python, 58 57 bytes ``` lambda s,p:sum(bin(ord(c)).count("1")for c in s)&1!=p>'e' ``` [Answer] ## Pyth, 12 bytes ``` q@"oe"sjCz2w ``` [Test suite.](https://pyth.herokuapp.com/?code=q%40%22oe%22sjCz2w&test_suite=1&test_suite_input=0%0Ae%0AFoo%0Ae%0AHello+World%21%0Ao%0AAlex+is+wrong%0Ae%0AProgramming+Puzzles+and+Code-Golf%0Ae%0AProgramming+Puzzles+and+Code-Golf%0Ao&debug=0&input_size=2) ``` z take a line of input C convert to int j 2 convert to base 2, array-wise (so, array of 0s and 1s) s sum (count the number of ones) @"oe" modular index into the string to get either "o" or "e" q w test equality to second line of input ``` [Answer] # IA-32 machine code, 15 bytes Hexdump: ``` 0f b6 c2 40 32 01 0f 9b c0 3a 21 41 72 f6 c3 ``` Assembly code: ``` movzx eax, dl; inc eax; repeat: xor al, [ecx]; setpo al; cmp ah, [ecx]; inc ecx; jb repeat; ret; ``` This is a function that receives its first argument (string) in `ecx` and second argument (char) in `dl`. It returns the result in `eax`, so it's compatible with the `fastcall` calling convention. This code bends the rules when it uses the [`setpo`](http://x86.renejeschke.de/html/file_module_x86_id_288.html) instruction: > > Builtins that count the number of "on" bits in a string or character are not allowed > > > This instruction sets `al` to the parity bit calculated by the previous instruction - so I have these two nitpicks on the rules: * It doesn't count the number of "on" bits - it calculates the parity bit directly! * Technically, it's the previous instruction (`xor`) that calculates the parity bit. The `setpo` instruction only moves it to the `al` register. These semantic details out of the way, here is the explanation on what the code does. The representations of the characters are: ``` 'e' = 01100101 'o' = 01101111 ``` If we add 1 to them, they happen to have just the right parity: ``` 'e' + 1 = 01100110 (odd parity) 'o' + 1 = 01110000 (even parity) ``` So we `XOR` all the characters of the string, initializing `al` to these values, which gives the answer. --- The first instruction is `movzx eax, dl` instead of the more obvious (and shorter) `mov al, dl`, because I want to have the number 0 in a register (`ah` in this case) in order to be able to compare it in the right order (`0, [ecx]` rather than `[ecx], 0`). [Answer] ## JavaScript (ES6), ~~84~~ 72 bytes ``` (s,p)=>(t=p>'e',[...s].map(c=>t^=c.charCodeAt()),t^=t/16,t^=t/4,t^t/2)&1 ``` Bit twiddling turned out to be shorter than converting to base 2 and counting `1`s. [Answer] ## Perl, 29 bytes Includes +2 for `-p` Run with the input on STDIN as parity character space string, e.g. ``` parity.pl <<< "p Programming Puzzles and Code-Golf" ``` `parity.pl` ``` #!/usr/bin/perl -p $_=unpack"B*",$_|b;$_=1&y;1; ``` [Answer] # J, 27 bytes ``` 'oe'&i.@[=[:~:/^:2@#:3&u:@] ``` ## Usage ``` f =: 'oe'&i.@[=[:~:/^:2@#:3&u:@] 'e' f '0' 0 'e' f 'Foo' 1 'o' f 'Hello World!' 0 'e' f 'Alex is right' 1 'e' f 'Programming Puzzles and Code-Golf' 0 'o' f 'Programming Puzzles and Code-Golf' 1 ``` [Answer] # JavaScript (ES6), 69 bytes ``` (s,p)=>[...s].map(c=>{for(n=c.charCodeAt();n;n>>=1)r^=n&1},r=p>"e")|r ``` [Answer] ## PowerShell v2+, 91 bytes */me cries in a corner* ``` param([char[]]$a,$b)$b-eq'o'-xor(-join($a|%{[convert]::toString(+$_,2)})-replace0).length%2 ``` Yeah ... so, base conversion is not a strong suit for PowerShell. The conversion from input string to binary representation `$a|%{[convert]::toString(+$_,2)}` is 32 bytes in and of itself ... Takes input `$a` and `$b`, explicitly casting `$a` as a char-array in the process. We then check whether `$b` is `-eq`ual to `o`, and `-xor` that with the other half of the program. For that part, we take the input string `$a`, pipe it through a loop to convert each letter to binary, `-join` all those together to form one solid string, and `-replace` all the `0`s with nothing. We then count the `.length` of that string and take it mod-2 to determine if it's even or odd, which will conveniently be either `0` or `1`, perfect for the `-xor`. Will return `True` or `False` accordingly. See test cases below: ``` PS C:\Tools\Scripts\golfing> .\generate-parity-bit.ps1 "0" e False PS C:\Tools\Scripts\golfing> .\generate-parity-bit.ps1 "Foo" e True PS C:\Tools\Scripts\golfing> .\generate-parity-bit.ps1 "Hello World!" o False PS C:\Tools\Scripts\golfing> .\generate-parity-bit.ps1 "Alex is right" e True PS C:\Tools\Scripts\golfing> .\generate-parity-bit.ps1 "Programming Puzzles and Code-Golf" e False PS C:\Tools\Scripts\golfing> .\generate-parity-bit.ps1 "Programming Puzzles and Code-Golf" o True ``` [Answer] # Factor, 85 bytes For some reason I couldn't wrap my head around this one until a few minutes ago, when I simplified (and maybe shortened?) the code. ``` [ "e" = [ even? ] [ odd? ] ? [ [ >bin ] { } map-as concat [ 49 = ] count ] dip call ] ``` `?` is like a ternary operator: it tests the truthiness of the third stack item, and either selects the `true` value or the `false` value. It's roughly equivalent to the following C-like pseduocode: ``` void* parity_tester_function = strcmp(p, "e") ? (void *) even? // it's a function pointer (I think) : (void *) odd? ; ``` The rest of the code is pretty simple: ``` [ ! to count a string's set bits: [ >bin ] { } map-as ! get the binary of each character, and map as an array, because you can't have stringy data nested in another string (that's called a type error) concat ! { "a" "B" } concat -> "aB" [ 49 = ] count ! count items in the resulting string which match this condition (in this case, the condition we're testing is whether the character has the same code point as "1") ] dip ! take the above function pointer off the stack, apply this anonymous function to the now-top of the stack, then restore the value after the quotation finishes. ! in other words, apply this quotation to the second-to-top item on the stack call ! remember that conditionally chosen function pointer? it's on the top of the stack, and the number of sets bits is second. ! we're gonna call either odd? or even? on the number of set bits, and return the same thing it does. ``` [Answer] # Julia, ~~58~~ ~~47~~ ~~45~~ 40 bytes ``` f(s,p)=(p>'e')$endof(prod(bin,s)∩49)&1 ``` This is a function that accepts a string and a character and returns an integer. To get the number of ones in the binary representation, we first apply the `bin` function to each character in the string, which gives us an array of binary strings. Then reduce them into one using `prod` (since `*` is string concatenation in Julia) and take the set intersection of that string and the character code for `1`, which gives us a string of ones. The last index of that string is the number of ones. We XOR this with 1 if the provided character is *o* and 0 otherwise, then get the parity using bitwise AND 1. [Try it online!](http://julia.tryitonline.net/#code=ZihzLHApPShwPidlJykkZW5kb2YocHJvZChiaW4scyniiKk0OSkmMQoKZm9yIGNhc2UgaW4gWygiMCIsJ2UnLDApLCAoIkZvbyIsJ2UnLDEpLCAoIkhlbGxvIFdvcmxkISIsJ28nLDApLCAoIkFsZXggaXMgd3JvbmciLCdlJywxKSwKICAgICAgICAgICAgICgiUHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZS1Hb2xmIiwnZScsMCksICgiUHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZS1Hb2xmIiwnbycsMSldCiAgICBwcmludGxuKGYoY2FzZVsxXSwgY2FzZVsyXSkgPT0gY2FzZVszXSkKZW5k&input=) (includes all test cases) Saved 18 bytes thanks to Dennis! [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~, 13 bytes **Code:** ``` €ÇbSOÈ„oe²k<^ ``` **Example Input:** ``` Programming Puzzles and Code-Golf o ``` **Example Output:** ``` 1 ``` **Explanation:** ``` € # for each char in string Ç # get ascii value b # convert to binary S # split to single chars (ex: '1101' to '1','1','0','1') O # sum È # check if even „oe # push string "oe" ² # push 2nd input (p) k # get 1-based index of p in "oe" < # decrease (to get either 0-based index) ^ # xor with result of È ``` Thanks to Adnan for saving 2 bytes. [Answer] **Bash and unix tools (72 bytes)** ``` f(){ bc<<<"$(xxd -b<<<"$2$1"|cut -b9-64|tail -c +7|tr -dc 1|wc -c)%2" } ``` Excepts `s` as the first and `p` as the second argument. Fortunately the last 3 bits of `o` and `e` has odd and even parity respectively. ``` xxd -b print the concatenation of `p` and `s` in binary cut -b9-64 parse xxd output tail -c +7 keep only the last 3 bits of `p` tr -dc 1 keep only the `1`s wc -c count them bc ...%2 modulo two ``` Supplying the input via `<<<` adds a line feed character, but the parity of `\n` is even, so it is not a problem. [Answer] # Ruby, 57 bytes If `0` was falsey in Ruby, the `==` could probably be switched to just `-`, or there could be other optimizations, but it isn't. ``` ->s,b{s.gsub(/./){$&.ord.to_s 2}.count(?1)%2==(b>?i?0:1)} ``` [Answer] # [Retina](http://github.com/mbuettner/retina), 102 bytes Takes the string on the first line, and the letter on the second line. Uses ISO 8859-1 encoding. ``` [12478abdghkmnpsuvyzCEFIJLOQRTWX#%&)*,/;=>@[\]^| ](?=.*¶) 1 [^1](?=.*¶) 0 ^(0|10*1)*¶o|^0*1(0|10*1)*¶e ``` [**Try it online**](http://retina.tryitonline.net/#code=WzEyNDc4YWJkZ2hrbW5wc3V2eXpDRUZJSkxPUVJUV1gjJSYpKiwvOz0-QFtcXV58IF0oPz0uKsK2KQoxClteMV0oPz0uKsK2KQowCl4oMHwxMCoxKSrCtm98XjAqMSgwfDEwKjEpKsK2ZQ&input=UHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZS1Hb2xmCmU) The character class on the first line matches any character with an odd number of ones in the binary representation. Description of how even/odd detection with regex works [here](https://stackoverflow.com/a/20498401/2415524). [Answer] # Octave, 56 bytes ``` f=@(s,p) mod(sum((i=bitunpack([s p]))(1:length(i)-5)),2) ``` The `bitunpack` function, for ASCII characters, returns them in little-endian order. So by putting the parity flag at the end of our string, unpacking the whole thing, and dropping the last 5 bits, we can then sum up the whole thing mod 2 for our ultimate answer. Usage: ``` octave:137> f('Hello World!', 'o') ans = 0 octave:138> f('Hello World!', 'e') ans = 1 ``` [Answer] ##  Common Lisp, 87 ``` (lambda(s p)(=(mod(reduce'+(mapcar'logcount(map'list'char-code s)))2)(position p"oe"))) ``` * Sum the logcount of char-codes of `s`. * The remainder of this, when divided by 2, is compared to the position of the parity argument `p` in the string `"oe"` (either 0 or 1). For example, if there are 4 ones, the remainder is zero. If p is `o`, then no additional bit should be added, and the test return false. ### Pretty-printed ``` (lambda (s p) (= (mod (reduce '+ (mapcar 'logcount (map 'list 'char-code s))) 2) (position p "oe"))) ``` [Answer] # Java, 91 bytes ``` (s,c)->{s+=c%8;int e=1;for(int i:s.getBytes())while(i>0){if(i%2==1)e^=1;i/=2;}return e==0;} ``` I did the same as @CAT97, but stripped some characters by using the modulo 8 and concatenate of @Luis Mendo and the use of int instead of boolean. This is a lambda for a `BiFunction<String, Character, Boolean>`. [Answer] ## Matlab, 49 bytes ``` f=@(x,p)mod(sum(sum(dec2bin(x)-'0'))+(p-'e'>0),2) ``` where: * x is the input string; * p is 'e' for even parity and 'o' for the odd one. For example: ``` >> f('Programming Puzzles and Code-Golf','e') ans = 0 ``` ]
[Question] [ # The Task You are to write some ASCII Art Text as seen from [this website for generating ASCII art](http://patorjk.com/software/taag/#p=display&h=0&f=Alpha&t=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz)! # Rules Input will only be alphabetical text and spaces, and will be input as a single line. It is also case-insensitive. You needn't fix if the output text is longer than the terminal width. As long as it would be correct if the terminal window was infinitely stretchable, you'll be fine. Aside from the standard-loopholes, the only other rule is that you mayn't use built-ins - although if your language *has* a built in for this (which would be *amazing*), if you include it as a side-note in your answer, take a 15% bonus off of your code-golfed solution! ### Example: Input: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz ``` Output: ``` _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _______ _____ _______ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _______ _____ _______ _____ _____ _____ _____ _____ _____ _____ _____ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /::\ \ /\ \ /::\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ ______ |\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /::\ \ /\ \ /::\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ ______ |\ \ /\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\____\ /::\ \ /::\ \ /::\____\ /::\____\ /::\____\ /::\____\ /::::\ \ /::\ \ /::::\ \ /::\ \ /::\ \ /::\ \ /::\____\ /::\____\ /::\____\ |::| | |:\____\ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\____\ /::\ \ /::\ \ /::\____\ /::\____\ /::\____\ /::\____\ /::::\ \ /::\ \ /::::\ \ /::\ \ /::\ \ /::\ \ /::\____\ /::\____\ /::\____\ |::| | |:\____\ /::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /:::/ / \:::\ \ \:::\ \ /:::/ / /:::/ / /::::| | /::::| | /::::::\ \ /::::\ \ /::::::\ \ /::::\ \ /::::\ \ \:::\ \ /:::/ / /:::/ / /:::/ / |::| | |::| | \:::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /:::/ / \:::\ \ \:::\ \ /:::/ / /:::/ / /::::| | /::::| | /::::::\ \ /::::\ \ /::::::\ \ /::::\ \ /::::\ \ \:::\ \ /:::/ / /:::/ / /:::/ / |::| | |::| | \:::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /:::/ / \:::\ \ \:::\ \ /:::/ / /:::/ / /:::::| | /:::::| | /::::::::\ \ /::::::\ \ /::::::::\ \ /::::::\ \ /::::::\ \ \:::\ \ /:::/ / /:::/ / /:::/ _/___ |::| | |::| | \:::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /::::::\ \ /:::/ / \:::\ \ \:::\ \ /:::/ / /:::/ / /:::::| | /:::::| | /::::::::\ \ /::::::\ \ /::::::::\ \ /::::::\ \ /::::::\ \ \:::\ \ /:::/ / /:::/ / /:::/ _/___ |::| | |::| | \:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ / \:::\ \ \:::\ \ /:::/ / /:::/ / /::::::| | /::::::| | /:::/~~\:::\ \ /:::/\:::\ \ /:::/~~\:::\ \ /:::/\:::\ \ /:::/\:::\ \ \:::\ \ /:::/ / /:::/ / /:::/ /\ \ |::| | |::| | \:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ / \:::\ \ \:::\ \ /:::/ / /:::/ / /::::::| | /::::::| | /:::/~~\:::\ \ /:::/\:::\ \ /:::/~~\:::\ \ /:::/\:::\ \ /:::/\:::\ \ \:::\ \ /:::/ / /:::/ / /:::/ /\ \ |::| | |::| | \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ /:::/____/ \:::\ \ \:::\ \ /:::/____/ /:::/ / /:::/|::| | /:::/|::| | /:::/ \:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ \:::\ \ /:::/ / /:::/____/ /:::/ /::\____\ |::| | |::| | \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ /:::/____/ \:::\ \ \:::\ \ /:::/____/ /:::/ / /:::/|::| | /:::/|::| | /:::/ \:::\ \ /:::/__\:::\ \ /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ \:::\ \ /:::/ / /:::/____/ /:::/ /::\____\ |::| | |::| | \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /:::/ \:::\ \ /:::/ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /:::/ \:::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /:::/ / /:::/ |::| | /:::/ |::| | /:::/ / \:::\ \ /::::\ \:::\ \ /:::/ / \:::\ \ /::::\ \:::\ \ \:::\ \:::\ \ /::::\ \ /:::/ / |::| | /:::/ /:::/ / |::| | |::| | \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /:::/ \:::\ \ /:::/ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /:::/ \:::\ \ /::::\ \ /::::\ \ /::::\ \ /::::\ \ /:::/ / /:::/ |::| | /:::/ |::| | /:::/ / \:::\ \ /::::\ \:::\ \ /:::/ / \:::\ \ /::::\ \:::\ \ \:::\ \:::\ \ /::::\ \ /:::/ / |::| | /:::/ /:::/ / |::| | |::| | \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /:::/ / \:::\ \ /:::/ / \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /:::/ / \:::\ \ /::::::\ \ _____ ____ /::::::\ \ _____ /::::::\ \ /::::::\____\________ /:::/ / /:::/ |::|___|______ /:::/ |::| | _____ /:::/____/ \:::\____\ /::::::\ \:::\ \ /:::/____/ \:::\____\ /::::::\ \:::\ \ ___\:::\ \:::\ \ /::::::\ \ /:::/ / _____ |::| | _____ /:::/ /:::/ _/___ |::| | |::|___|______ \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /:::/ / \:::\ \ /:::/ / \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /:::/ / \:::\ \ /::::::\ \ _____ ____ /::::::\ \ _____ /::::::\ \ /::::::\____\________ /:::/ / /:::/ |::|___|______ /:::/ |::| | _____ /:::/____/ \:::\____\ /::::::\ \:::\ \ /:::/____/ \:::\____\ /::::::\ \:::\ \ ___\:::\ \:::\ \ /::::::\ \ /:::/ / _____ |::| | _____ /:::/ /:::/ _/___ |::| | |::|___|______ \:::\ \ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ ___\ /:::/ / \:::\ \ /:::/ / \:::\ ___\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ \ /:::/ / \:::\ ___\ /:::/\:::\ \ /\ \ /\ \ /:::/\:::\ \ /\ \ /:::/\:::\ \ /:::/\:::::::::::\ \ /:::/ / /:::/ |::::::::\ \ /:::/ |::| |/\ \ |:::| | |:::| | /:::/\:::\ \:::\____\ |:::| | |:::| | /:::/\:::\ \:::\____\ /\ \:::\ \:::\ \ /:::/\:::\ \ /:::/____/ /\ \ |::| | /\ \ /:::/___/:::/ /\ \ ______|::|___|___ ____ /::::::::\ \ \:::\ \ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ ___\ /:::/ / \:::\ \ /:::/ / \:::\ ___\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ \ /:::/ / \:::\ ___\ /:::/\:::\ \ /\ \ /\ \ /:::/\:::\ \ /\ \ /:::/\:::\ \ /:::/\:::::::::::\ \ /:::/ / /:::/ |::::::::\ \ /:::/ |::| |/\ \ |:::| | |:::| | /:::/\:::\ \:::\____\ |:::| | |:::| | /:::/\:::\ \:::\____\ /\ \:::\ \:::\ \ /:::/\:::\ \ /:::/____/ /\ \ |::| | /\ \ /:::/___/:::/ /\ \ ______|::|___|___ ____ /::::::::\ \ \:::\ \ /:::/ \:::\ \:::\____\/:::/__\:::\ \:::| |/:::/____/ \:::\____\/:::/____/ \:::| |/:::/__\:::\ \:::\____\/:::/ \:::\ \:::\____\/:::/____/ ___\:::| |/:::/ \:::\ /::\____\/::\ \/:::/ \:::\____\/::\ /:::/ \:::\____\/:::/ |:::::::::::\____\/:::/____/ /:::/ |:::::::::\____\/:: / |::| /::\____\|:::|____| |:::| |/:::/ \:::\ \:::| ||:::|____| |:::|____|/:::/ \:::\ \:::| |/::\ \:::\ \:::\____\ /:::/ \:::\____\|:::| / /::\____\ |::| | /::\____\|:::| /:::/ /::\____\|:::::::::::::::::| | /::::::::::\____\_______________\:::\____\ /:::/ \:::\ \:::\____\/:::/__\:::\ \:::| |/:::/____/ \:::\____\/:::/____/ \:::| |/:::/__\:::\ \:::\____\/:::/ \:::\ \:::\____\/:::/____/ ___\:::| |/:::/ \:::\ /::\____\/::\ \/:::/ \:::\____\/::\ /:::/ \:::\____\/:::/ |:::::::::::\____\/:::/____/ /:::/ |:::::::::\____\/:: / |::| /::\____\|:::|____| |:::| |/:::/ \:::\ \:::| ||:::|____| |:::|____|/:::/ \:::\ \:::| |/::\ \:::\ \:::\____\ /:::/ \:::\____\|:::| / /::\____\ |::| | /::\____\|:::| /:::/ /::\____\|:::::::::::::::::| | /::::::::::\____\_______________\:::\____\ \::/ \:::\ /:::/ /\:::\ \:::\ /:::|____|\:::\ \ \::/ /\:::\ \ /:::|____|\:::\ \:::\ \::/ /\::/ \:::\ \::/ /\:::\ \ /\ /:::|____|\::/ \:::\ /:::/ /\:::\ /:::/ \::/ /\:::\ /:::/ \::/ /\::/ |::|~~~|~~~~~ \:::\ \ \::/ / ~~~~~/:::/ /\::/ /|::| /:::/ / \:::\ \ /:::/ / \::/ \:::\ /:::|____| \:::\ _\___/:::/ / \::/ |::::\ /:::|____|\:::\ \:::\ \::/ / /:::/ \::/ /|:::|____\ /:::/ / |::| | /:::/ /|:::|__/:::/ /:::/ /|:::::::::::::::::|____| /:::/~~~~/~~ \::::::::::::::::::/ / \::/ \:::\ /:::/ /\:::\ \:::\ /:::|____|\:::\ \ \::/ /\:::\ \ /:::|____|\:::\ \:::\ \::/ /\::/ \:::\ \::/ /\:::\ \ /\ /:::|____|\::/ \:::\ /:::/ /\:::\ /:::/ \::/ /\:::\ /:::/ \::/ /\::/ |::|~~~|~~~~~ \:::\ \ \::/ / ~~~~~/:::/ /\::/ /|::| /:::/ / \:::\ \ /:::/ / \::/ \:::\ /:::|____| \:::\ _\___/:::/ / \::/ |::::\ /:::|____|\:::\ \:::\ \::/ / /:::/ \::/ /|:::|____\ /:::/ / |::| | /:::/ /|:::|__/:::/ /:::/ /|:::::::::::::::::|____| /:::/~~~~/~~ \::::::::::::::::::/ / \/____/ \:::\/:::/ / \:::\ \:::\/:::/ / \:::\ \ \/____/ \:::\ \ /:::/ / \:::\ \:::\ \/____/ \/____/ \:::\ \/____/ \:::\ /::\ \::/ / \/____/ \:::\/:::/ / \:::\/:::/ / \/____/ \:::\/:::/ / \/____/ \/____|::| | \:::\ \ \/____/ /:::/ / \/____/ |::| /:::/ / \:::\ \ /:::/ / \/_____/\:::\/:::/ / \:::\ |::| /:::/ / \/____|:::::\/:::/ / \:::\ \:::\ \/____/ /:::/ / \/____/ \:::\ \ /:::/ / |::| | /:::/ / \:::\/:::/ /:::/ / ~~~~~~|::|~~~|~~~ /:::/ / \::::::::::::::::/____/ \/____/ \:::\/:::/ / \:::\ \:::\/:::/ / \:::\ \ \/____/ \:::\ \ /:::/ / \:::\ \:::\ \/____/ \/____/ \:::\ \/____/ \:::\ /::\ \::/ / \/____/ \:::\/:::/ / \:::\/:::/ / \/____/ \:::\/:::/ / \/____/ \/____|::| | \:::\ \ \/____/ /:::/ / \/____/ |::| /:::/ / \:::\ \ /:::/ / \/_____/\:::\/:::/ / \:::\ |::| /:::/ / \/____|:::::\/:::/ / \:::\ \:::\ \/____/ /:::/ / \/____/ \:::\ \ /:::/ / |::| | /:::/ / \:::\/:::/ /:::/ / ~~~~~~|::|~~~|~~~ /:::/ / \::::::::::::::::/____/ \::::::/ / \:::\ \::::::/ / \:::\ \ \:::\ \ /:::/ / \:::\ \:::\ \ \:::\ \ \:::\ \:::\ \/____/ \::::::/ / \::::::/ / \::::::/ / |::| | \:::\ \ /:::/ / |::|/:::/ / \:::\ /:::/ / \::::::/ / \:::\|::|/:::/ / |:::::::::/ / \:::\ \:::\ \ /:::/ / \:::\ \ /:::/ / |::|____|/:::/ / \::::::/ /:::/ / |::| | /:::/ / \:::\~~~~\~~~~~~ \::::::/ / \:::\ \::::::/ / \:::\ \ \:::\ \ /:::/ / \:::\ \:::\ \ \:::\ \ \:::\ \:::\ \/____/ \::::::/ / \::::::/ / \::::::/ / |::| | \:::\ \ /:::/ / |::|/:::/ / \:::\ /:::/ / \::::::/ / \:::\|::|/:::/ / |:::::::::/ / \:::\ \:::\ \ /:::/ / \:::\ \ /:::/ / |::|____|/:::/ / \::::::/ /:::/ / |::| | /:::/ / \:::\~~~~\~~~~~~ \::::/ / \:::\ \::::/ / \:::\ \ \:::\ /:::/ / \:::\ \:::\____\ \:::\____\ \:::\ \:::\____\ \::::/ / \::::/____/ \::::/ / |::| | \:::\ \ /:::/ / |::::::/ / \:::\__/:::/ / \::::/ / \::::::::::/ / |::|\::::/ / \:::\ \:::\____\ /:::/ / \:::\ /:::/ / |:::::::::::/ / \::::/___/:::/ / |::| | /:::/ / \:::\ \ \::::/ / \:::\ \::::/ / \:::\ \ \:::\ /:::/ / \:::\ \:::\____\ \:::\____\ \:::\ \:::\____\ \::::/ / \::::/____/ \::::/ / |::| | \:::\ \ /:::/ / |::::::/ / \:::\__/:::/ / \::::/ / \::::::::::/ / |::|\::::/ / \:::\ \:::\____\ /:::/ / \:::\ /:::/ / |:::::::::::/ / \::::/___/:::/ / |::| | /:::/ / \:::\ \ /:::/ / \:::\ /:::/ / \:::\ \ \:::\ /:::/ / \:::\ \::/ / \::/ / \:::\ /:::/ / /:::/ / \:::\ \ \::/ / |::| | \:::\ \ /:::/ / |:::::/ / \::::::::/ / \::/____/ \::::::::/ / |::| \::/____/ \:::\ /:::/ / \::/ / \:::\__/:::/ / \::::::::::/____/ \:::\__/:::/ / |::| | \::/ / \:::\ \ /:::/ / \:::\ /:::/ / \:::\ \ \:::\ /:::/ / \:::\ \::/ / \::/ / \:::\ /:::/ / /:::/ / \:::\ \ \::/ / |::| | \:::\ \ /:::/ / |:::::/ / \::::::::/ / \::/____/ \::::::::/ / |::| \::/____/ \:::\ /:::/ / \::/ / \:::\__/:::/ / \::::::::::/____/ \:::\__/:::/ / |::| | \::/ / \:::\ \ /:::/ / \:::\/:::/ / \:::\ \ \:::\/:::/ / \:::\ \/____/ \/____/ \:::\/:::/ / /:::/ / \:::\ \ \/____/ |::| | \:::\ \ /:::/ / |::::/ / \::::::/ / ~~ \::::::/ / |::| ~| \:::\/:::/ / \/____/ \::::::::/ / ~~~~~~~~~~ \::::::::/ / |::| | \/____/ \:::\ \ /:::/ / \:::\/:::/ / \:::\ \ \:::\/:::/ / \:::\ \/____/ \/____/ \:::\/:::/ / /:::/ / \:::\ \ \/____/ |::| | \:::\ \ /:::/ / |::::/ / \::::::/ / ~~ \::::::/ / |::| ~| \:::\/:::/ / \/____/ \::::::::/ / ~~~~~~~~~~ \::::::::/ / |::| | \/____/ \:::\ \ /:::/ / \::::::/ / \:::\ \ \::::::/ / \:::\ \ \::::::/ / /:::/ / \:::\ \ |::| | \:::\ \ /:::/ / /:::/ / \::::/ / \::::/____/ |::| | \::::::/ / \::::::/ / \::::::/ / |::| | \:::\ \ /:::/ / \::::::/ / \:::\ \ \::::::/ / \:::\ \ \::::::/ / /:::/ / \:::\ \ |::| | \:::\ \ /:::/ / /:::/ / \::::/ / \::::/____/ |::| | \::::::/ / \::::::/ / \::::::/ / |::| | \:::\ \ /:::/ / \::::/ / \:::\____\ \::::/ / \:::\____\ \::::/ / /:::/ / \:::\____\ \::| | \:::\____\ /:::/ / /:::/ / \::/____/ |::| | \::| | \::::/ / \::::/ / \::::/ / |::| | \:::\____\ /:::/ / \::::/ / \:::\____\ \::::/ / \:::\____\ \::::/ / /:::/ / \:::\____\ \::| | \:::\____\ /:::/ / /:::/ / \::/____/ |::| | \::| | \::::/ / \::::/ / \::::/ / |::| | \:::\____\ \::/ / \::/____/ \::/ / \::/____/ \::/ / \::/____/ \::/ / \::/ / \:| | \::/ / \::/ / \::/ / ~~ |::|____| \:| | \::/ / \::/____/ \::/____/ |::|___| \::/ / \::/ / \::/____/ \::/ / \::/____/ \::/ / \::/____/ \::/ / \::/ / \:| | \::/ / \::/ / \::/ / ~~ |::|____| \:| | \::/ / \::/____/ \::/____/ |::|___| \::/ / \/____/ ~~ \/____/ ~~ \/____/ \/____/ \/____/ \|___| \/____/ \/____/ \/____/ ~~ \|___| \/____/ ~~ ~~ ~~ \/____/ \/____/ ~~ \/____/ ~~ \/____/ \/____/ \/____/ \|___| \/____/ \/____/ \/____/ ~~ \|___| \/____/ ~~ ~~ ~~ \/____/ ``` As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the fewest amount of bytes wins! [Answer] # Minecraft, 22313 (50% hand-written code) bytes Why did I ever promise to do this.... Well, it works, but I took a few liberties: * Letters are followed by newlines * There is no lowercase input (as uppercase and lowercase are the same) * Letters look weird as Minecraft does not have monospaced font (it looks better with 'Force Unicode Font' in language settings) Here is a screenshot: [![enter image description here](https://i.stack.imgur.com/KDegf.png)](https://i.stack.imgur.com/KDegf.png) Screenshot of output: [![enter image description here](https://i.stack.imgur.com/TrV1V.png)](https://i.stack.imgur.com/TrV1V.png) Download the world [here](http://www.mediafire.com/download/qimtts0i62icuwc/String_to_ASCII_Art.zip). Note that the input keyboard is very precise on the clicking. Click a little to the right of each letter to avoid this confusion. ### Explanation 1. Input Keyboard pops up, takes input until 'Enter' "key" is pressed. 2. Teleports the "Controller" `ArmorStand` backwards one block until it reaches end of string. 3. While it is teleporting, the `ArmorStand` checks what character that the `ArmorStand` it is standing on represents, and activates that command block (which outputs the fancy letter). 4. Once the Controller reaches the starting position, it resets the program and kills the `ArmorStand`s. [Answer] # JavaScript (ES6), ~~14394~~ ~~6381~~ 3360 bytes ``` f=s=>[...s.toUpperCase(b="e_5yyyyyyyyyyyh_5yx_7x_5x_7x_5yr_5yyyR0_5ynd/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTfbTv/bTu/DTu/bTu/DTu/bTv/bTk/bTv/bTv/bTv/bTu_6 15|bTv/bTdncDTsDTsDTsDTsDTsDTsDTsDBsDTsDTsDBsDBcDBsDBp4bTp2bTp4bTp2bTsDTiDTsDBsDBsDB 15|FOm:bBsDTnZJTo4bTo4bTo4bTo4bTo4bTo4bTo3/StHTq3bTo3/Sp3/SZ:4|Op4|Oo6bTj/JTj/LTj/JTo4bTgbHTo3/Sp3/Sp3/S 15|FOmFOtHTnWLTiLTiLTiLTiLTiLTiLTiGSwHTq3bTiGSp3/SZ:5|Oo5|Oj/:8bTg/LTg/:8bTg/LTiLTgbHTiGSp3/Sp3/ 3_/_3j|FOmFOubHTnU/GbHTfGbHTfGbHTfGbHTfGbHTfGbHTfGbHTfGS 20bHTq3bTfGSp3/SZ:6|Oj/:6|OiG~2bHTd/GbHTd/G~2bHTd/GbHTfGbHTgbHTfGSp3/Sp3/PbTh|FOmFOwHTnSG_2bHTcG_2bHTcGMHTcGMHTcG_2bHTcG_2bHTcGMHTcGC 22bHTq3bTcGCp3/SZG|FOiG|FOg/GTHTZG_2bHTZGTHTZG_2bHTcG_2bHTgbHTcGSp3/Cp3/PDBg|FOmFOxbHTnPJQHTWJQHTWGTHTWGTHTWJQHTWJQHTWGTHTWJT 22/JTo4bTWJTo3/SZG |FOg/G |FOfGS bHTU/JQHTU/GS bHTU/JQHTYbHQHTfJTWGSr|FR|p3/PGSg|FOmFO 20bHTnNLQHTSLQHTSGS bHTSGS bHTSLQHTSLQHTSGS bHTSLT 3_5RASLTR_5PLTSLB_8SGSZG 2|F_3|_6SG 2|FO _5PGCQHBPLQHTPGCQHBPLQHTR_3bHQHTcLTSGSV_5V|FR|U_5SGPG 3_/_3d|FOmF_3|_6q3bTn /GbHQHTNGbHQH _3bNGSQHTNGSQH _3bNGbHQHTNGbHQHTNGSQH _3bNGbHT /bTNbQNGbHTNbT /GbHTNGb:11bTNGSZGO:8bTNGOFO/bT |:3|R|U|:3|R| /GbHQHB |:3|R|U|:3|R| /GbHQHBNbQHQHTWGbHTNGCWbTU|FR|SbTNG_3/GPbT 2_6|F_3|_3 AW:8bTq3bTn/GMHQHB/G_2bHQ:3|R|/GCUbHB/GCUb:3|R|/G_2bHQHB/GMHQHB/GC 2_3b:3|R|/GMHSDB/DQ/GMHB/DSGMHB/G 2|:11bB/GCZGR|:9bB/:2 /R|FPDB|:3|A|U|:3|R|/GMHQ:3|R|2:3|A|U|:3|A|/GMHQ:3|R|/DQHQHBSGMHB|:3|SWDBR|FR|PDB|:3|PGPDB|:17|R|S:10bB_15bHBnbETHNGSbHQHN:3|A|bHTXESbHTU/:3|A|bHQHQESbETHQESbHT /bN:3|A|bETHNGSbHNGTESbHNGTESbEOF~3|~5UbHTYbES ~5/GSbES|FNGS bHTPGS bETHN:3|A| bH 3_b_3/GS bEOJN:3|A|bHQHQESPGTES|:3|BU/GSR|FR|NGS|:3|_2/GPGS|:17|A|PG~4/~2X:18/Sn b/C bH/GSMHQH/GSMHTX/CMHTPGSMHQHQ/CM/C bHQ/CMHSD bESM/C bH/GSMH/GS b/CMH/GS b/CM/A|FOgbHTYb/CWGSM/C |F /GSQHT /GSQ/_5/bH/GSQH |F /GSQ/A|:5b/GSMHQHQ/CPGS b/CMHTPGSU|FR| /GSMH/GPGS 2~6|F~3|~3cGSeb:16/CnebKSTHQKSTHTq3bT /GSTHQHTq3bTYbHQH b/ChbKSTKShbKSu|FOhbHTv/GSg|F/GSUbHSGSjbKSUbH|F/GSe|:9/STHQHTWGShbHT /GSV|FA|/GSTKPGSd|FOfGShbH~4b~6ngbISXHQISXHTq3bSGSXHQHBq3bBYbHQHBq4/SXICl4/Sv|FOjbHTsGSh|KSYbH_2/GSq4/SYb:10/Sg|FbISXHQHBSGSl3bSGSY|:11/SXI_3/GSe|FOd/GSl3bTng/GSabHNGSabHTq3bNGSabHQEStESabHNGSp3/SabHTq2/Sx|FOl3bTo3/Sj|:5/Sdb:8/SubECdb:8/Sh|F bECabHNGSTEStH_2/GSab:10/CabH_2/GSg|FOdbEStHTnfGSebH/GSebHTq3b/GSebHQ/Cw/CebH/GSp3/SebHT 15b/C 20|FOq3bTiGSmISgbKSx~2tKSj|F 2~|q3b/GSX/Cw:8/Se~10q8/Sh|FOeb/CwHTend/GShbKShbHTq6/ShbHTR0bKSp3/ShbHTR1|FOtHTfGSp3/SjbIS 39bICmFOtKS 33bKS 37bKSj|FO 36bHTncGSl4/Sl3bBq4/Sl3bBR0bISp3/Sl3bBR0bFOubHBcGSp3/Sq2/CR1|FR|q2|OubIS 35bIS 39bISmFO 37bHBnabEStECtEStECtESR1bECtEStESR1b:|OwESabEStESu~2R7|FA|t:|OwES 37bECR1bEC 15|F_3| 38bESndb/Cv~2 23b/Cv~2 23b/CV8b/Cw/CR3b|_3|xb/Ceb/Cw/CV8~2 23b|_3|xb/C 39~2R8~2 22~2R4b/C",["_4","_4b","_4/",":2b",":2/",":2|",":3/",":3b",":4/",":4b",":6/",":6b"," 2b"," 2/"," 3|"," 3/"," 3b"," 4"," 4/"," 4b"," 5"," 6"," 6/"," 6b"," 7"," 7/"," 8"," 8/"," 9"," 10"," 10/"," 11"," 12"," 12/"," 13"," 14"," 14b:"," 14|"," 14/:"," 15/:"," 15b:"," 16"," 16/"," 16b"," 17"," 18"," 18b"," 19"," 20_5","\\"].map((l,i)=>b=b.replace(new RegExp([..."ABCDEFGHIJKLMNOPQRSTUVWXYZacdefghijklmopqrstuvwxyb"][i],"g"),l)),a="",b.match(/\D|\d+/g).map(x=>a+=+x?l.repeat(x-1):l=x),a=a.split`n`,o=a.map(_=>""))].map(c=>a.map((d,i)=>o[i]+=c<"A"?" ":d.slice((g=n=>(c.charCodeAt()+n-65)*25-(c>"L")*8-(c>"T")*4-(c>"Y")*4)(0),g(1))))&&o.join` ` ``` ## Explanation ASCII art string is compressed using the format `<character><number_of_times_to_repeat>`. After this another stage of compression is added where numerous common combinations (eg. `20_5`) are replaced by single characters. Special characters `n` represents a new line and `b` represents a backslash. I could probably improve the compression algorithm a bit but I think I'll leave it like this for now. ``` f=s=> [...s.toUpperCase( // use upper-case letter codes // magical decompression magic b="e_5yyyyyyyyyyyh_5yx_7x_5x_7x_5yr_5yyyR0_5ynd/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTv/bTfbTv/bTu/DTu/bTu/DTu/bTv/bTk/bTv/bTv/bTv/bTu_6 15|bTv/bTdncDTsDTsDTsDTsDTsDTsDTsDBsDTsDTsDBsDBcDBsDBp4bTp2bTp4bTp2bTsDTiDTsDBsDBsDB 15|FOm:bBsDTnZJTo4bTo4bTo4bTo4bTo4bTo4bTo3/StHTq3bTo3/Sp3/SZ:4|Op4|Oo6bTj/JTj/LTj/JTo4bTgbHTo3/Sp3/Sp3/S 15|FOmFOtHTnWLTiLTiLTiLTiLTiLTiLTiGSwHTq3bTiGSp3/SZ:5|Oo5|Oj/:8bTg/LTg/:8bTg/LTiLTgbHTiGSp3/Sp3/ 3_/_3j|FOmFOubHTnU/GbHTfGbHTfGbHTfGbHTfGbHTfGbHTfGbHTfGS 20bHTq3bTfGSp3/SZ:6|Oj/:6|OiG~2bHTd/GbHTd/G~2bHTd/GbHTfGbHTgbHTfGSp3/Sp3/PbTh|FOmFOwHTnSG_2bHTcG_2bHTcGMHTcGMHTcG_2bHTcG_2bHTcGMHTcGC 22bHTq3bTcGCp3/SZG|FOiG|FOg/GTHTZG_2bHTZGTHTZG_2bHTcG_2bHTgbHTcGSp3/Cp3/PDBg|FOmFOxbHTnPJQHTWJQHTWGTHTWGTHTWJQHTWJQHTWGTHTWJT 22/JTo4bTWJTo3/SZG |FOg/G |FOfGS bHTU/JQHTU/GS bHTU/JQHTYbHQHTfJTWGSr|FR|p3/PGSg|FOmFO 20bHTnNLQHTSLQHTSGS bHTSGS bHTSLQHTSLQHTSGS bHTSLT 3_5RASLTR_5PLTSLB_8SGSZG 2|F_3|_6SG 2|FO _5PGCQHBPLQHTPGCQHBPLQHTR_3bHQHTcLTSGSV_5V|FR|U_5SGPG 3_/_3d|FOmF_3|_6q3bTn /GbHQHTNGbHQH _3bNGSQHTNGSQH _3bNGbHQHTNGbHQHTNGSQH _3bNGbHT /bTNbQNGbHTNbT /GbHTNGb:11bTNGSZGO:8bTNGOFO/bT |:3|R|U|:3|R| /GbHQHB |:3|R|U|:3|R| /GbHQHBNbQHQHTWGbHTNGCWbTU|FR|SbTNG_3/GPbT 2_6|F_3|_3 AW:8bTq3bTn/GMHQHB/G_2bHQ:3|R|/GCUbHB/GCUb:3|R|/G_2bHQHB/GMHQHB/GC 2_3b:3|R|/GMHSDB/DQ/GMHB/DSGMHB/G 2|:11bB/GCZGR|:9bB/:2 /R|FPDB|:3|A|U|:3|R|/GMHQ:3|R|2:3|A|U|:3|A|/GMHQ:3|R|/DQHQHBSGMHB|:3|SWDBR|FR|PDB|:3|PGPDB|:17|R|S:10bB_15bHBnbETHNGSbHQHN:3|A|bHTXESbHTU/:3|A|bHQHQESbETHQESbHT /bN:3|A|bETHNGSbHNGTESbHNGTESbEOF~3|~5UbHTYbES ~5/GSbES|FNGS bHTPGS bETHN:3|A| bH 3_b_3/GS bEOJN:3|A|bHQHQESPGTES|:3|BU/GSR|FR|NGS|:3|_2/GPGS|:17|A|PG~4/~2X:18/Sn b/C bH/GSMHQH/GSMHTX/CMHTPGSMHQHQ/CM/C bHQ/CMHSD bESM/C bH/GSMH/GS b/CMH/GS b/CM/A|FOgbHTYb/CWGSM/C |F /GSQHT /GSQ/_5/bH/GSQH |F /GSQ/A|:5b/GSMHQHQ/CPGS b/CMHTPGSU|FR| /GSMH/GPGS 2~6|F~3|~3cGSeb:16/CnebKSTHQKSTHTq3bT /GSTHQHTq3bTYbHQH b/ChbKSTKShbKSu|FOhbHTv/GSg|F/GSUbHSGSjbKSUbH|F/GSe|:9/STHQHTWGShbHT /GSV|FA|/GSTKPGSd|FOfGShbH~4b~6ngbISXHQISXHTq3bSGSXHQHBq3bBYbHQHBq4/SXICl4/Sv|FOjbHTsGSh|KSYbH_2/GSq4/SYb:10/Sg|FbISXHQHBSGSl3bSGSY|:11/SXI_3/GSe|FOd/GSl3bTng/GSabHNGSabHTq3bNGSabHQEStESabHNGSp3/SabHTq2/Sx|FOl3bTo3/Sj|:5/Sdb:8/SubECdb:8/Sh|F bECabHNGSTEStH_2/GSab:10/CabH_2/GSg|FOdbEStHTnfGSebH/GSebHTq3b/GSebHQ/Cw/CebH/GSp3/SebHT 15b/C 20|FOq3bTiGSmISgbKSx~2tKSj|F 2~|q3b/GSX/Cw:8/Se~10q8/Sh|FOeb/CwHTend/GShbKShbHTq6/ShbHTR0bKSp3/ShbHTR1|FOtHTfGSp3/SjbIS 39bICmFOtKS 33bKS 37bKSj|FO 36bHTncGSl4/Sl3bBq4/Sl3bBR0bISp3/Sl3bBR0bFOubHBcGSp3/Sq2/CR1|FR|q2|OubIS 35bIS 39bISmFO 37bHBnabEStECtEStECtESR1bECtEStESR1b:|OwESabEStESu~2R7|FA|t:|OwES 37bECR1bEC 15|F_3| 38bESndb/Cv~2 23b/Cv~2 23b/CV8b/Cw/CR3b|_3|xb/Ceb/Cw/CV8~2 23b|_3|xb/C 39~2R8~2 22~2R4b/C", ["_4","_4b","_4/",":2b",":2/",":2|",":3/",":3b",":4/",":4b",":6/",":6b"," 2b"," 2/"," 3|"," 3/"," 3b"," 4"," 4/"," 4b"," 5"," 6"," 6/"," 6b"," 7"," 7/"," 8"," 8/"," 9"," 10"," 10/"," 11"," 12"," 12/"," 13"," 14"," 14b:"," 14|"," 14/:"," 15/:"," 15b:"," 16"," 16/"," 16b"," 17"," 18"," 18b"," 19"," 20_5","\\"] .map((l,i)=>b=b.replace(new RegExp([..."ABCDEFGHIJKLMNOPQRSTUVWXYZacdefghijklmopqrstuvwxyb"][i],"g"),l)), // decompression stage 2 a="", // a = array of each line of the ASCII art letters b.match(/\D|\d+/g) // get an array of characters and numbers .map(x=> a+=+x // if the current element is a number ?l.repeat(x-1) // repeat the previous character x times :l=x // else set l to the new character // add it to a in case there is no number after it ), a=a.split`n`, // split a into an array of lines o=a.map(_=>"") // o = array containing each line of the output )].map(c=> a.map((d,i)=> // loop through each line of the current letter o[i]+= // add the letter's substring for the current line c<"A"?" ": // space = 8 spaces d.slice( (g=n=> (c.charCodeAt()+n-65) // get the letter index *25 // each ASCII art letter is 25 characters wide -(c>"L")*8 // except L is 17 -(c>"T")*4 // T is 21 -(c>"Y")*4 // Y is 21 )(0),g(1)) ) ) &&o.join` ` ``` ``` Letters to Test: <input type="text" oninput="output.innerHTML=f(this.value)" /><pre id="output"></pre> ``` [Answer] # PHP, 1898 ~~1905~~ ~~1922~~ bytes Yeah, PHP beats all, at least currently. :) ``` $r=[L=>8,T=>4,V=>4,X=>1,Y=>4];for(;$c=strtoupper($argv[1][$z++]);)foreach(explode(" ",gzuncompress(base64_decode('eNrtWluO5CAM/OcU3ID/nAWpL4Jy9u0QQmzsMjiTleZjIu12D5XCDwpwSMd4XZ/jisr1B/wc+HxM5BWGDsC7X2TER3dDMPRvKR//Z3nLH/BzIG0bQl5j6AC8+0VGn0Jja/F0Faah/17gCP5/d/UO8G0H1hNudzJ0ACsauQuDs8CybeX4EM12V8yzMAv99wKpfhkjzGgIs7crE1Azj4DarlpPVruLAQCYDhQgzqwFQimqzbpnYRL67wVQvpxafKhErDgJtDAU68ludzAggLX4XImfNG7GD6QoPAu3Dc3pXwygfPm0+FSJWHECqD3tu2IdBehnYMC3GywpUakXn0hx9Cx0G98tXThtA1qYNvCijaMGSUshWgDsypZoQYpTgN6TsI4i9zMw4NsNzMx2JSr14iMpDp4FWmWMTpuAmiwTeNHGZj6aLZdT/lr0BKDiJEB6GgJBkfsZdwNaMBd3g+a+qh2iRMl8JkXubmBVBo/EBNRkmcCLNmhDP0W4PkXVdN0hgKuhzvEPOdKbbdtHir+3FsHouac2+zqTN7KgoMj9jMMY1qJaRI4BNne5FNn5zKhEXi8aUuR5MrQYeJVBIQU4c8LiEAwOEMaiDU9X3zt74VK/KDf0OyRwNYwPCdMCsiDGNSSXzbKxwSV/yshPxfkZLXJrc1EbyUZM3L1tJ40h6sVTZURzkagOP34pWgxDRXaHOJQfuedkiEMwKMAYwIZhvHbV5jzpikSQCKN2QW+gQNSAtpDdWtTiUHa1IhkxkdWhe1WVVMdqEJYS+QlojPonZCSuQbaQyqiZG2k4LaRSTBpD1Is0e/djW5tHacwseZ90XbdnIfOK7F4QhmmWek7GKZZHBqlsOIN8dkaKAKDLHuvKdJdWmHPgWsj2fT/+7fv0sactlvVmZvz8co4lKi54+xhHE+DFqCWDZJQNjYdIYtSiZvoei1MiRb4zNIasFxUp9nnUDgK+iWqJ7dkdrrOr8F1HzgWgRkIdYCFqQNfitYSgvIvd42ZQ42pXdc6TRNru0qFjXalAuvaWoczBWmS72ia9qp2hAoa3V8YniTgaQ+npctccKOalFnWMeKAKrwbIwsncpGCdlDuZz9NHP6HF5lkQt9xsGqIKWKclCXa1ds7CGVlumKpXavQQgBV3njyjR+tJcgDopNJ8kN5VhtJT5LXBPLtL76ToTWWoBgiTuKl0ax1i6cYPAef93orozyGaNTEVLAArKhldqe8lBbDEEDbUIi8bStQf/uZahKchwlYLAA5NVhkbmD+Hu+ZAiTrRfifFbiobttyzCyYIPsRaPPgNZnZFRbZ6iowZ2Zgri8Zn7lpF3qIUp1oEXhVtFDPU1e0dn0AGo7orGGqu8vSd1KirLHbNGQMmMbtfiAU7u7KSWdKixcjoOF8AsCvb3WmRt3QMa2sReVVU/dgVwlFvaWMFxf51dS8rac+zd1LCyN6vVQZMYva+EAuT7JoFGNSijxGtw3jfO2K/DfhGwP2bllk9iBcJFLo2mJa7PiNvMmavVVa0GJaedxCwVsNNGZMB8fxa4ZENPYu4K/9vKLL91hzPEG21xu4+kfsrDLcUleyG6d4Os/giw3L4gXGvDZBFvw1sXN3xZlK8T7p/5K4/u27G9bYlurTI3Q3zvR1m8UWG/1ovOeddoSz6bbwYIE6i212/DTfD35NwN/wDTMusIA')))as$k=>$v)$o[$k].=' '==$c?' ':substr($v,(ord($c)-65)*25,25-$r[$c]);echo implode(" ",$o); ``` Works from command line: ``` $ php asciistuff.php HelLo $ php asciistuff.php "H E L L O" ``` It handles upper- and lowercase characters as well as whitespaces. **Golfed version without the long string** ``` $r=[L=>8,T=>4,V=>4,X=>1,Y=>4];for(;$c=strtoupper($argv[1][$z++]);)foreach(explode(" ",gzuncompress(base64_decode('encoded alphabet')))as$k=>$v)$o[$k].=' '==$c?' ':substr($v,(ord($c)-65)*25,25-$r[$c]);echo implode(" ",$o); ``` **Ungolfed** ``` // store difference of shorter letters to default value (25) $r=[L=>8,T=>4,V=>4,X=>1,Y=>4]; // loop through each character in the input for(;$c = strtoupper($argv[1][$z++]);) // the whole alphabet is compressed and stored in a base64 encoded string // it's then stored line by line in an array // for each character we loop through every line of the alphabet foreach(explode("\n",gzuncompress(base64_decode('encoded alphabet'))) as $k => $v) // if a white space is given, 8 whitespaces are added to each line of the output // otherwise the letter sequence, dependent on letter length, is extracted from the current line $o[$k] .= ' ' == $c ? ' ' : substr($v, (ord($c) - 65) * 25, 25 - $r[$c]); // finally print the result echo implode("\n",$o); ``` --- **Edits** * *Saved* **17 bytes** by refactoring the loops and declaring the lines of the alphabet inline. * *Saved* **7 bytes** by replacing `foreach()` with `implode()` and by replacing `"\n"` with real line breaks. [Answer] # Matlab (Java), ~~28125~~ ~~28119~~ 6810 bytes Could perhaps still be golfed somewhat more. Now I am using a string compression via Java, stolen from [here](http://www.mathworks.com/matlabcentral/fileexchange/8899-rapid-lossless-data-compression-of-numerical-or-string-variables/content/dzip.m) The core is the nice thing that in Matlab you can also get 2d (or if you need 3d etc) slices from matrices, and also *stick* them together again. This saves a lot of work! This is done for every character of the input. ``` Z=uint8([120;156;237;155;193;145;219;60;12;133;51;255;164;16;116;160;91;14;62;165;16;206;160;145;29;55;145;38;83;70;86;36;1;226;1;240;102;253;175;44;75;14;117;241;228;139;150;164;200;199;7;144;18;191;255;247;173;94;63;126;214;159;223;191;126;146;94;75;161;120;45;151;75;196;239;240;178;164;144;211;59;57;131;142;174;112;173;138;3;92;241;226;255;188;92;180;97;181;221;189;118;197;181;221;92;255;249;94;98;199;210;26;185;171;254;246;191;28;119;213;223;126;39;147;195;181;221;181;141;80;102;109;119;33;40;179;54;131;12;182;208;98;3;7;6;40;216;193;134;217;195;138;57;192;21;115;132;239;152;19;40;181;249;235;62;149;4;172;35;234;161;29;209;1;205;136;154;50;205;88;185;50;7;134;50;229;215;149;185;254;94;83;149;92;83;149;80;166;18;166;76;37;157;58;149;212;27;201;149;217;111;36;218;72;37;111;111;8;187;28;162;32;74;163;65;37;43;77;84;66;156;9;162;213;230;175;231;171;100;161;68;37;11;142;21;204;94;167;146;241;20;13;179;254;175;237;125;169;185;222;222;231;40;187;154;219;28;101;87;179;12;10;212;76;58;40;197;99;70;47;17;236;84;130;61;6;42;241;56;120;181;180;51;226;132;74;59;3;62;151;151;108;171;146;107;80;9;122;73;87;73;244;146;209;68;172;89;155;56;189;196;195;243;70;156;152;151;160;151;24;28;243;146;18;189;164;151;233;189;164;104;6;3;238;240;94;102;226;37;235;125;209;75;236;12;183;158;103;230;189;120;137;155;247;226;37;197;171;228;32;94;114;156;236;213;214;142;56;168;164;209;160;146;70;51;28;85;34;20;85;82;47;175;18;138;216;140;210;63;161;146;227;71;28;130;136;179;244;232;48;84;178;180;167;11;17;135;211;236;149;211;236;149;69;37;46;226;148;214;199;62;226;20;179;30;49;17;199;134;12;85;9;67;200;144;136;195;65;37;213;220;130;74;56;19;196;254;17;231;56;94;242;241;74;216;42;79;87;194;86;121;186;18;94;137;142;255;69;102;51;147;85;158;172;132;25;114;29;89;9;179;203;117;250;74;120;113;189;22;30;198;67;142;121;73;173;33;174;132;213;51;220;112;100;201;10;229;201;202;195;188;132;189;59;244;54;100;216;251;189;210;12;151;220;167;10;248;148;180;19;212;178;12;117;12;181;176;83;7;228;37;214;167;70;94;98;124;202;230;37;195;167;66;94;178;168;147;155;24;210;212;242;111;175;113;30;165;18;166;212;167;10;250;20;168;68;158;26;84;34;142;132;42;81;154;236;124;145;83;137;116;155;83;137;105;167;85;137;182;147;64;37;17;211;231;241;249;85;178;119;196;121;235;151;91;227;200;229;34;206;192;18;113;120;20;177;134;246;30;113;120;93;22;247;107;68;156;140;46;37;161;75;29;76;83;174;244;182;189;119;189;90;111;123;218;203;202;105;73;41;149;148;38;227;126;23;165;146;82;202;228;240;122;217;107;129;248;110;215;14;38;190;235;28;197;248;46;115;212;197;247;98;168;153;38;18;113;220;156;148;136;227;109;1;254;253;252;185;57;92;214;87;244;81;2;165;217;224;165;207;17;109;55;143;169;122;181;173;41;150;142;108;176;205;177;74;229;78;81;115;157;67;218;110;75;49;27;236;20;179;65;41;55;121;24;206;224;139;100;131;183;84;66;71;80;73;187;188;74;244;2;149;40;52;42;209;33;181;42;193;118;91;26;85;226;155;88;70;147;206;191;102;72;151;155;27;24;120;237;242;96;224;62;163;212;25;29;13;220;189;179;48;99;53;48;119;103;224;250;20;250;175;254;219;12;92;105;182;225;141;53;171;47;218;154;135;226;77;205;70;241;26;81;234;19;143;24;35;24;245;0;139;213;49;118;144;12;98;162;201;55;54;188;61;108;17;37;192;174;226;68;36;25;188;181;253;112;128;136;115;123;255;129;253;159;183;180;63;212;254;232;189;204;171;82;43;147;158;164;153;93;42;219;65;32;147;184;105;233;58;200;200;196;62;244;144;9;116;80;201;109;227;113;239;69;78;232;37;45;50;172;13;55;94;194;18;70;174;224;37;134;14;47;97;83;194;168;130;135;184;77;205;172;77;140;94;162;20;188;164;219;157;96;49;152;214;209;219;121;201;158;34;57;180;151;124;97;101;169;94;34;89;75;234;37;217;219;51;31;213;196;75;226;87;61;178;178;84;252;186;94;242;144;93;170;37;248;253;40;51;154;73;192;198;160;156;153;248;17;117;17;199;238;101;50;249;137;15;119;13;139;176;120;88;4;226;197;171;68;38;62;238;101;146;201;52;45;54;249;130;93;1;83;102;38;236;205;228;16;111;207;234;3;108;232;39;115;207;17;241;190;123;142;39;76;32;220;156;167;53;202;155;165;137;219;77;18;138;187;73;80;156;174;130;187;44;193;118;77;86;193;14;182;182;176;131;93;78;14;158;122;197;250;144;107;193;77;229;14;71;140;191;102;112;80;13;206;125;83;74;161;76;117;165;214;109;148;234;187;80;164;250;46;20;105;93;117;186;218;188;74;12;53;99;47;107;145;160;146;134;157;242;176;131;124;254;48;218;29;168;121;11;111;233;190;42;57;134;151;64;217;210;135;80;182;204;94;200;35;100;92;90;49;206;75;122;49;232;37;80;140;246;43;20;35;253;122;129;98;250;254;23;148;61;188;196;150;45;94;130;101;143;104;198;17;66;217;54;154;105;217;24;205;150;67;168;228;174;151;51;91;211;177;99;57;94;37;145;174;72;193;123;110;208;188;132;80;27;223;73;243;150;109;215;15;55;198;34;75;42;54;160;183;22;167;180;195;250;212;236;105;187;124;178;95;62;159;84;168;249;164;125;3;2;51;144;164;123;237;12;84;10;51;80;40;204;64;41;55;153;45;119;190;157;140;112;139;97;187;235;237;36;167;152;147;145;172;79;151;96;78;66;67;159;120;113;197;153;68;140;86;110;196;107;95;154;124;178;12;106;243;201;50;168;251;30;70;71;163;224;26;82;158;2;191;211;173;181;81;119;99;210;178;106;109;131;54;220;107;35;247;61;76;175;205;125;15;211;21;225;191;135;113;111;188;73;218;73;17;31;96;213;113;182;235;192;251;103;95;248;22;112;158;138;179;248;235;153;205;243;191;204;152;167;226;62;86;201;17;54;227;159;175;146;121;42;238;248;17;242;213;84;50;79;197;189;166;151;204;83;113;232;121;102;222;139;151;60;253;141;205;89;179;87;91;59;226;121;42;142;28;158;17;199;71;28;130;136;51;79;197;61;35;226;28;199;75;230;169;184;0;211;100;101;155;61;254;231;159;119;162;146;251;212;60;21;119;198;53;206;60;21;71;160;18;109;39;129;74;34;166;207;227;243;171;100;239;136;131;31;48;168;135;200;229;34;206;192;243;84;220;103;232;60;21;55;76;192;174;29;230;169;56;95;102;152;155;127;77;160;230;169;184;0;15;145;13;222;82;201;60;21;151;53;177;224;71;13;231;94;51;28;227;227;177;196;192;221;59;11;51;86;3;207;83;113;4;56;83;206;60;21;183;215;94;230;60;21;119;62;47;153;167;226;246;22;201;161;189;228;11;43;203;121;42;206;224;93;119;188;231;169;56;196;146;189;2;30;217;171;193;38;95;176;43;96;202;204;132;189;153;28;226;237;89;125;128;13;253;100;238;57;34;222;119;207;241;132;9;132;155;243;68;243;84;156;165;143;216;215;120;196;53;79;197;57;149;124;42;193;154;167;226;232;47;94;2;101;75;31;66;217;50;123;33;143;144;113;105;197;204;83;113;251;170;100;158;138;203;232;60;21;151;193;255;179;62;53;123;218;46;159;236;151;207;39;21;106;62;57;79;197;57;156;210;121;42;174;225;121;42;174;99;3;255;0;61;59;177;97]); import com.mathworks.mlwidgets.io.InterruptibleStreamCopier;isc=InterruptibleStreamCopier.getInterruptibleStreamCopier; c=java.io.ByteArrayOutputStream;isc.copyStream(java.util.zip.InflaterInputStream(java.io.ByteArrayInputStream(Z)),c); Q=typecast(c.toByteArray,'uint8');n=double(Q(2))*8+2;s=typecast(Q(3:n),'double')';Q=Q(n+1:end);M=reshape(char(Q),s); l=[];for k=lower(input('','s'));l=[l,M(:,25*(k-97)+(1:25))];end;disp(l) ``` [Answer] # Python 2, 3376 bytes Homemade compression, via lots of replacing of substrings. ``` x,y,z='123456789abcdefghi','ABCDEFGHIJKL','MNOPQRST' k=dict(zip(x[9:],'10 11 12 13 14 17 21 24 25'.split())) for c in x[:9]:k[c]=c k.update(dict(zip(y,'2 3 4 5 6 8 9 10 11 16 17 18'.split()))) k.update(dict(zip(z,'2 3 4 5 6 7 8 15'.split()))) Y='v'*11+'aP2-vv9R9-v9R9-vv6Pa-vvvh-6Pa-vp'+'9Z'*11+'9/040 -9Z9Z8/A040p9Z8/A040p9Z9Z5Z9Z9Z9Z8Qa-5|0409-9Z'+'x40'*7+'xO0x40x40xO0xO0-8/A0O0xO08t07-8/A0408t07-8/A040x40p4/A040xO0xO0xO0p7z9-5|:0O0x40p8'+'t07'*7+'-7Vp8U7-8U7-7Vp7V-7/C|3|p7/C|3|p6s6t07-6s6t07t07-4U7-7Vp7Vp7Vp7z9-5zp8U7-p'+'6s6-'*7+'6V9-9U6-9U6-6V9-6V -6/D|3|p6/D|3|p5/F0405-6s6-5/F0405-6s6-6s6-5U6-6V9-6V9-6r3_/N6&9U6-p'+'5rU5-'*7+'5Va-aU5-aU5-5Va-5V2-5/E|3|p5/E|3|8u~~U4-5rU5u~~U4-5rU5-5rU5-6U5-5Va-5Va-5r3/0405&aU5-8uMU4uMU4u2U4u2U4uMU4uMU4u2U4uO/b-bU4-bU4uO/b-4V3uz8uzp3r4U3uMU4-3r4U3uMU4uMU4-7U4-4VbuO/bu3/A0O04&bU4-pmm3r4U3-3r4U3-mm3r4U3-3/C040b-b/C0403-b/C0403-3/C040b-3V4-3r zp3r zp2V U2-m2V U2-m4X3U3t03-3Vckc-3r3V4&cU3-pnn2V U2-2V U2-nn2V U2-2s3P2-2O4s2-2P3s2-2/E0O0S2-2V5-2r2|A|N|Q2-2r2z P2- rO/3XO0 -n rO/3XO0 -n2NX3U2-6s2-2V6P2k5P2-2r3r3_/N2-7z9-5|A|N|Q2-dU2-p rX3UorX3X N0oV3UoV3X N0orX3UorX3UoV3X N0orU /040o/0302rUo/040 rUor0I040oV6- r3|F040or3z/040 -|B|4|5|B|4|- rX3XO0 -|B|4|5|B|4|- rX3XO0o/03X3U -5rUorO/6/040 k4/040orNr3/040oQ|A|N|N O -5/F040 -eU -pr2X3XO0-rMX30B|4|-rO/5XO0-rO/50B|4|-rMX3XO0-r2X3XO0-rO/2N0B|4|-r2X4/A0O0-/A030r2XO0-/A04r2XO0-r2|I0O0-rO/7-r4|G0O0-/A /4|A|3/A0O0-|B|O|5|B|4|-r2X30B|4|-|B|O|5|B|O|-r2X30B|4|-/A03X3XO0u2XO0-|B|4/6/A0O0k3/A0O0-|B|3r3/A0O0-|K|4|-4/H0O0-TXO0-p0A/4X2V-X3X)U6y-U5/B|O|-X3X3y-0A/4X3y-U /0)0A/4X2V-X2r4y-X2r4y-0A/3|A|~~~|~~~~~5-U7-y ~~~~~V-y|A|2V- U3V -0A/4X) X3_0NV -0A/3|C0)X3X3y-3r4y-|B|O05Vk2V-|B|Mr3V-|K|O|-3r~~~~/~~6-0Lq-p w XVoX3XVoU6woU3VoX3X3wow X3woX4/A0 yow XVoXV woXV wo0/Oza- U6- w6Vow |A| V -2U V2- 0/P/XV -2X |A| V2- 0/O|D0VoX3X3w -2V woU3V k VoXr3Vo~~~~~~|A|~~~|~~~6-2V9- 0J/O/ -pa0Eq2-2X30Eq2-2Ud-2U V2-2X3U5-aU5-2X3X w2-a0Eq2-20Eqa-20Eqa-7za-2U5-dV2-9|A|V2-3X4V3-a0Eq2-3X|A|V3-7|Gq2-2X3U5- Va-2U V2-4|A|O|V2-20E/3V2-7z9- Va-2X~~~~0~~~~~~7-pb0Cq3-3X30Cq3-3Uc-3X4V3-3X3XO04-bXO04-3X3XO04-b0Cq3-30C/O/b-30Cqb-7za-3U4-cV3-9|Eq3-4XMV4-b0Cq3-40Hq4-7|A|0Cq3-3X3XO04-Vb-3X4V3-4|Iq3-30C/NV3-7z9-Vb-3Uc-pbV4-4X2V4-4Ub-4X2V4-4X3y4-cy4-4X2V4-bV4-4Ub-4yc-7za-4U3-bV4-9|Dq4(c0A/O/4(7|A| 0A/O/4-4X2V4-yc-4XMV4-40H/O/4-4XMV4-7z9-yc-4Ub-paV5-5XV5-5Ua-5XV5-5X3w5-dw5-5XV5-aV5-5Ua-5wd-7za-5U2-aV5-9|Cq5ld~~al7|A|2~|a-5XV5- wd(5~~~~~~~~~~a(7z9- wd-5Ua-p9V6l6U9l6U9-il9V6-6U9-i-7za-6U -9V6-9V6!i-70C/O/7-7zalglil7z9-g-6U9-p8V7!7XO0p70Cq7-7XO0pi!8V7-7XO0pi-70A|3|a-7XO0-8V7-8V7-ji-8|A|4|p70A|3|a!g!i!7z9-g-7XO0pp8ypj8ypj8ypi-j8yp8ypi-80:|3|a-8y-8yp8yp9~~e-i-8|A|O|p80:|3|a-8ypg-ji-j7|A|N|9-g-8ypp9w9-9~~e-9w9-9~~e-9w9-i-i-9w9-9w9-i-90|N|a-9w -9w9-9w9-i-i-9~~e-90|N|a-9w9-g-9~~e-i-9~~e-8~~e-g-9w9-p'+'i-'*11+'f-'+'i-'*7+'g-i-i-i-h-g-i-8' d=zip('nmlkj!&()UVXZzyxwvutsrqpo','2/E03U2- 3/C03U3- -60Eq6- -4|A|4| 80A/O/p -70Cq7- -7z9-5zp -50Fq5- 2/B|O|- X40 r4/ 0B0 /0409- |A|3| 0Aq 8-8/A0 0/O/ aPa- -4/B/ -7/C04 /E040 /B/ /4/ 8-'.split()+[' - ']) for a in d:Y=Y.replace(a[0],a[1]) Y=Y.split('-') v=[] for l in Y: r='' for c in l: if c in x:r+=' '*int(k[c]) elif c in y:r+=':'*int(k[c]) elif c in z:r+='_'*int(k[c]) elif c=='0':r+='\\' else:r+=c v.append(r) X=zip(*[v[i:i+27]for i in range(0,len(v),27)]) i=input() for j in range(22): s='' for c in i.lower():l=26if c==' 'else ord(c)-97;s+=X[l][j] print s ``` [Answer] # Python 2, 1208 bytes Here’s the readable part of the source: ``` s=raw_input() i=22 while i:i-=1;print''.join('''BINARY_STUFF'''.decode('zip').split('@')[ord(c)%32][i::22]for c in s) ``` The complete source contains non-printable characters, so it is presented as a hexdump that can be decoded with `xxd -r`. ``` 00000000: efbb bf73 3d72 6177 5f69 6e70 7574 2829 ...s=raw_input() 00000010: 0a69 3d32 320a 7768 696c 6520 693a 692d .i=22.while i:i- 00000020: 3d31 3b70 7269 6e74 2727 2e6a 6f69 6e28 =1;print''.join( 00000030: 2727 2778 0152 1862 c001 d0be 7dde ba8e '''x.R.b....}... 00000040: 0371 146f 451d f0bb 6a21 308d 08ae 7d41 .q.oE...j!0...}A 00000050: ed1f 073e 1037 3ac8 892f ff8c 3be2 9387 ...>.7:../..;... 00000060: 2306 df85 d6db 9583 eb3a e1b6 ceb8 c4e8 #........:...... 00000070: 2246 616b 5f0f dc06 c2f4 7360 4f90 f433 "Fak_.....s`O..3 00000080: 484f f2c7 9fb8 d4fe 67e5 d560 5eac f453 HO......g..`^..S 00000090: b8eb d28c 51c7 deb5 716b c0f1 1b7c 85b0 ....Q...qk...|.. 000000a0: 1136 c2a0 b88c e132 86cb 182e 63b8 df90 .6.....2....c... 000000b0: 2641 d868 f65b 6974 52e9 ad84 838a 5c72 &A.h.[itR.....\r 000000c0: 3af6 25e8 d897 699a 2cb3 3449 960b 779d :.%...i.,.4I..w. 000000d0: a509 590e 461f 9b26 db06 2a1f 0a84 8782 ..Y.F..&..*..... 000000e0: f0d0 1dcd 93dc e16a 2f9a 260b 0cba f680 .......j/.&..... 000000f0: 4361 b073 fb9b 6ef7 60aa 490f 0ea6 9a30 Ca.s..n.`.I....0 00000100: 2a09 1735 468d a926 654c 9a1c 9166 a4b5 *..5F..&eL...f.. 00000110: 19d2 6fa1 fb6d 05d1 73ab c9f9 6972 719a ..o..m..s...irq. 00000120: a89a 384d 88e5 34d1 3353 d504 fe55 9377 ..8M..4.3S...U.w 00000130: 7fe8 1889 dd40 cf4d aed0 d5c4 1835 4689 [[email protected]](/cdn-cgi/l/email-protection). 00000140: ed6a 426c 5513 6283 19db 4724 b690 d860 .jBlU.b...G$...` 00000150: b89f 534d de60 0a7b 5b0a f602 9526 338c ..SM.`.{[....&3. 00000160: 1aa3 4e13 7492 2643 cf4d 93df 4307 9e3e ..N.t.&C.M..C..> 00000170: 7486 b661 7ae8 f060 183c 99c2 d674 0a5b t..az..`.<...t.[ 00000180: 8787 0ea9 a787 4e5f faf1 a193 2a09 86ab ......N_....*... 00000190: 09c3 55d3 34a9 d943 a7d7 3423 eafc 87ce ..U.4..C..4#.... 000001a0: fb2e 8897 e605 3129 a805 3129 582c 8849 ......1)..1)X,.I 000001b0: 4194 d899 f794 16c4 0319 a570 d328 15d3 A..........p.(.. 000001c0: e05e 666a c791 0b85 5133 fab4 6ad2 cbe6 .^fj....Q3..j... 000001d0: e26d 4485 52d2 a3cf 2a94 91f4 a0df 5c1d .mD.R...*.....\. 000001e0: 4ead 5085 d24a 8744 d5dc 8404 f04a c7d3 N.P..J.D.....J.. 000001f0: 4d86 6a9b af74 da6f a5f3 b034 6160 598b M.j..t.o...4a`Y. 00000200: d129 5d94 26e8 a234 419d 261e cba4 8999 .)].&..4A.&..... 00000210: 7e9b dd6f a509 aa34 011f 9726 bf29 6cdf ~..o...4...&.)l. 00000220: d2bc d2a1 5155 8cf4 64a3 ad6b f1d0 e15c ....QU..d..k...\ 00000230: 72bd ec9a 627e d061 d69e 62ae b8dd c59c r...b~.a..b..... 00000240: 08dc 7e29 b7df 4a43 fb4c 4967 b5ba 55dd ..~)..JC.LIg..U. 00000250: 4f5a ffc6 edb5 b0b7 d7c2 de5e 0bc7 2a18 OZ.........^..*. 00000260: 4641 d2c4 6941 9a34 30dc 5f6f 74c2 ea3e FA..iA.40._ot..> 00000270: 4c3f c5ea 27a3 b9e5 d58c 8134 a684 a8ce L?..'......4.... 00000280: 48da aedb de6a d730 a348 5342 d453 42d4 H....j.0.HSB.SB. 00000290: db55 893b f09a eb84 29e1 a945 7c39 354d .U.;....)..E|95M 000002a0: b634 a709 cd69 6224 4dd6 8de6 34a1 45c5 .4...ib$M...4.E. 000002b0: a489 d969 4207 df77 e590 71f8 982a be6d ...iB..w..q..*.m 000002c0: 62a6 664d cc0c 1ef6 ee22 ec93 4f55 86da b.fM....."..OU.. 000002d0: ff17 c5bf f267 aa38 ff9a ec7e 17d5 50bd .....g.8...~..P. 000002e0: 519a 07a3 e120 baf3 b6f1 a0b9 f3ee 7709 Q.... ........w. 000002f0: c33c 68cc 650c 9731 0c2a 1fde 6a1f a2a6 .<h.e..1.*..j... 00000300: 19d8 9eb6 ab79 11a2 ca92 e8ec 8c84 5b23 .....y........[# 00000310: e4d6 80a8 b204 254b 4e38 2379 c76a 32c2 ......%KN8#y.j2. 00000320: 8da0 aa26 4c33 eaba 9aa0 aa26 4428 5593 ...&L3.....&D(U. 00000330: 4aac a1f4 860e 1518 7535 418f d524 d7b9 J.......u5A..$.. 00000340: b99a 9c90 276f b6c0 ecb7 2d30 5755 93e9 ....'o....-0WU.. 00000350: c947 d418 3d56 9344 fdfc 6af2 e4ed 2a62 .G..=V.D..j...*b 00000360: 838a 2dbc e1c4 f5a9 9f06 3332 8505 7d46 ..-.......32..}F 00000370: 620c 9731 fcba 4769 8fae 24bf ddc7 a7be b..1..Gi..$..... 00000380: 9d9f b320 e98d bc40 bdad e405 0963 872b ... [[email protected]](/cdn-cgi/l/email-protection).+ 00000390: c3b5 eb22 46cd 28fc 6947 5e0f 6dec 3237 ..."F.(.iG^.m.27 000003a0: edc0 d260 1446 1301 d6ce 6e0b 5b0b 9672 ...`.F....n.[..r 000003b0: fbad b9fd ba5a 8d57 50a7 090a a393 34a1 .....Z.WP.....4. 000003c0: 4370 ffa7 e915 fdb4 9e9c 26e7 5713 6252 Cp........&.W.bR 000003d0: 4d1c d3d5 84b9 c3a1 9ae4 8be1 e802 534d M.............SM 000003e0: f4c5 aa26 30d5 c41c 754c 146e 7d5a 4dd8 ...&0...uL.n}ZM. 000003f0: 2217 f3e6 c1c4 8415 534c cc53 d284 5177 ".......SL.S..Qw 00000400: 9a6e 1492 2d8d aaa3 5673 9d46 185a 87ab .n..-...Vs.F.Z.. 00000410: fd57 3dc6 bdeb 7df0 7ba1 a9c5 03d4 6b8f .W=...}.{.....k. 00000420: 1397 a75b 1a3a 384d 934a 5893 4a9d 86c0 ...[.:8M.JX.J... 00000430: 3af7 80a5 30ea b198 b8db 7f3e aba4 bdc2 :...0......>.... 00000440: 59e5 bc63 ab35 880a 5121 2a94 0689 2bbc Y..c.5..Q!*...+. 00000450: 4883 0bba f406 a2fa 800c ea6f 05c8 d5fc H..........o.... 00000460: 0199 5c2d e1a2 b95a 309a ab1d 3e20 3314 ..\-...Z0...> 3. 00000470: e4ac 7228 a824 798b b5c7 1f3b b9e9 0e27 ..r(.$y....;...' 00000480: 2727 2e64 6563 6f64 6528 277a 6970 2729 ''.decode('zip') 00000490: 2e73 706c 6974 2827 4027 295b 6f72 6428 .split('@')[ord( 000004a0: 6329 2533 325d 5b69 3a3a 3232 5d66 6f72 c)%32][i::22]for 000004b0: 2063 2069 6e20 7329 c in s) ``` ]
[Question] [ ## Background We've had challenges before on [Fibonacci coding](https://en.wikipedia.org/wiki/Fibonacci_coding) and Zeckendorf representation. These representations follow naturally from [Zeckendorf's theorem](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem), which states that every positive integer can be represented uniquely as the sum of one or more distinct, non-consecutive Fibonacci numbers. For example: $$ \begin{aligned} 64 &= 55 + 8 + 1 \\ &= F\_{10} + F\_6 + F\_2 \\ 171 &= 144 + 21 + 5 + 1 \\ &= F\_{12} + F\_8 + F\_5 + F\_2 \\ \end{aligned} $$ where \$F\_i\$ is the \$i\$-th Fibonacci number. ## What is Fibonacci multiplication? Extending this concept, Donald Knuth defined "circle multiplication" (the Fibonacci product) on two postive integers \$a\$ and \$b\$ as follows. First assume $$ \begin{align} a &= \sum\_{i=0}^n F\_{c\_i} \text{ where } c\_i \ge 2 \\ b &= \sum\_{i=0}^m F\_{d\_i} \text{ where } d\_i \ge 2 \end{align} $$ Then we define the Fibonacci product like so: $$ a \circ b = \sum\_{i=0}^n \sum\_{j=0}^m F\_{c\_i + d\_j} $$ See [Knuth's original article](http://www.cs.umb.edu/%7Ervetro/vetroBioComp/compression/FIBO/KnuthFibb.pdf) (pdf) or the [Wikipedia entry](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem#Fibonacci_multiplication) for more. Here is a worked example from the Wikipedia page: $$ \begin{align} 2 &= F\_3 \\ 4 &= F\_4 + F\_2 \\ 2 \circ 4 &= F\_{3 + 4} + F\_{3 + 2} \\ &= F\_7 + F\_5 \\ &= 13 + 5 \\ &= 18 \end{align} $$ As an interesting aside not directly related to the challenge, it [has been shown](https://www.sciencedirect.com/science/article/pii/0893965989900785) that the Fibonacci product: > > can be interpreted as the usual multiplication in a multiplicatively closed subset of the ring \$\mathbb{Z}[\phi]\$ of algebraic integers generated by the "golden ratio". > > > ## Task Given two positive integers as input, return their Fibonacci product as defined in the section above. This is code-golf and standard site rules apply. ## Test Cases ``` 1 1 -> 3 1 2 -> 5 1 5 -> 13 2 1 -> 5 2 4 -> 18 4 1 -> 11 4 4 -> 40 4 9 -> 87 7 1 -> 18 7 2 -> 29 7 9 -> 141 9 9 -> 189 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~39~~ ~~34~~ 33 bytes ``` 1##+{#2,#}.⌊+++{##}2/++√5⌋& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731BZWbta2UhHuVbvUU@XtjaQo1xrpK@t/ahjlumjnm61/4GlmaklDgFFmXkl0cq6dmkODsqxanXByYl5ddVc1YY6hrU6IMoIQpmCKCOIoJGOCYgygfBMYDxLEGUOETSH6DOHCFoCKa7a/wA "Wolfram Language (Mathematica) – Try It Online") Uses the formula in the [linked Arnoux paper](https://www.sciencedirect.com/science/article/pii/0893965989900785): \$m\circ n=m n+p\_m n+m p\_n\$, where \$p\_x\$ is defined as the integer such that \$p\_x-\frac x\phi\in(\frac1\phi-1,\frac1\phi)\$. A little bit of manipulation gets us \$p\_x=\left\lfloor\frac{x+1}\phi\right\rfloor\$. ``` 1## m n +{#2,#}. + (n,m) . ⌊+++{##}2/++√5⌋ ⌊(1+(m,n)) / ϕ⌋ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes A port of [att's answer](https://codegolf.stackexchange.com/a/230974/64121) and -1 byte thanks to them. Takes input as a pair of integers `[a, b]`. ``` ‘:ØpḋṚ+P ``` [Try it online!](https://tio.run/##y0rNyan8//9RwwyrwzMKHu7ofrhzlnbA/6N7Drc/alrjBsTu//9HG@oYxuoASSMwaQokjcAiRjomQNIEzDaBsi2BpDlYxBys3hwsYgkkAQ "Jelly – Try It Online") ``` ‘ increment each value [a+1, b+1] :Øp integer divide by phi [(a+1):phi, (b+1):phi] ḋṚ dot product with the reverse (a+1):phi×b + (b+1):phi×a +P add the product of the input (a+1):phi×b + (b+1):phi×a + a×b ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ŒP‘ÆḞS=ɗƇ¹Ḣ)p/§ÆḞS ``` [Try it online!](https://tio.run/##y0rNyan8///opIBHDTMOtz3cMS/Y9uT0Y@2Hdj7csUizQP/Qcojg////zXUULAE "Jelly – Try It Online") -1 byte thanks to caird coinheringaahing --- I have posted a video explanation of this answer and how to approach this problem as well as the mathematical observation below to [my YouTube channel](https://www.youtube.com/channel/UCjWrRy5b2fntu1-u5EiFNtw). You can see the video [here](https://www.youtube.com/watch?v=IRJqGcYsKlc). --- Assume that there is a sequence of Fibonacci numbers where two are consecutive. Select the largest two such terms and them be \$F\_n\$ and \$F\_{n+1}\$. Then, \$F\_{n+2}\$ cannot be in the sequence because then it would be consecutive with \$F\_{n+1}\$ and thus contradict the definition. Therefore, we replace \$F\_n,F\_{n+1}\$ with \$F\_{n+2}\$ in the sequence and we now have a shorter sequence that sums to the same value. Keep repeating this process indefinitely, and we can see that the shortest sequence of Fibonacci numbers that sums to \$N\$ has to be the unique one containing no consecutive terms, otherwise we can reduce it to something shorter, which would be a contradiction. Thus, we only need to find the *shortest* sequence. Here follows the explanation of the Jelly code itself: ``` ŒP‘ÆḞS=ɗƇ¹Ḣ)p/§ÆḞS Main Link; accept a list [x, y] ) For each k of x and y ŒP Take the powerset of [1, 2, ..., k], shortest & lexicographically least first ‘ Add one (now we have the powerset of [2, 3, ..., k + 1]) Ƈ Filter; keep terms where ÆḞ Taking the Nth fibonacci number S and summing = is equal to ¹ k itself Ḣ And take the first (thus shortest) such subset p/ Take the cartesian product of the two codings § Sum each pair ÆḞ Get the Nth fibonacci number for each S and sum ``` [Answer] # [J](http://jsoftware.com/), 70 bytes ``` +/@,@(1{:@F@++/)&(F i.2-/\[(0>.]-(<:@I.>:){[)^:a:~F=:_2&(],+/@{.)&1 2) ``` [Try it online!](https://tio.run/##Tc7RCoIwFAbge5/i0IXb0E23ZupIGQSDoKtuzSIiqW56AKFXN6dONhic8@3843yGDUMdVAoQxJCCGi9lcDifzBAlOtaY90obHUUJCbGBNxM0uTQ4rVlL8V7pI6sV6RtyVXf1M5W6iRC38RjtGQk5CDKQ4Pl4fUFAB3Iud3KseZ7PHaL2oGDuMLdvBCrYeiAsZB5kFrgbES6TeSCnkWIR6UY492SakaknpZViWQ3na6oAj6Z1ROnJFOPS/V2uVJTDHw "J – Try It Online") * `F=:_2&(],+/@{.)&1 2)` `F_1, F_2 … F_n`. * `[(0>.]-(<:@I.>:){[)^:a:~` starting with `n`, greedily find the highest Fibonacci number (with binary search with adjusted indices `<:@I.>:`), subtract from `n` and repeat until we hit `0`. Return the intermediate results. * `F i.2-/\` From the intermediate results get the Fibonacci numbers, and then their indices. * `…&…` do this for both results, then for both Fibonacci index lists do … * `1{:@F@++/` addition table, get the last `F_i` for each sum. * `+/@,@` … and sum it again [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` ¹©R‘U;ṖÆḞS>®Ʋ¡¥ƒ“”)p/§ÆḞS ``` [Try it online!](https://tio.run/##y0rNyan8///QzkMrgx41zAi1frhz2uG2hzvmBdsdWnds06GFh5Yem/SoYc6jhrmaBfqHlkPk/v//b66jYAkA "Jelly – Try It Online") -4 bytes thanks to caird coinheringaahing Non-brute force answer that should run in \$O(N^2)\$ time. Still trying to figure out how to remove the register usage. Basically, constructs the Fibonacci coding by starting from an upper bound and counting down, adding in the largest Fibonacci number that can fit each time. Since I am summing the accumulating list each time, and I think the output list is roughly \$O(\log N)\$ in size, I *believe* this is \$O(N \log N)\$, but I'm not sure, so I'll just put down \$O(N^2)\$ for now. ``` ¹©R‘U;ṖÆḞS>®Ʋ¡¥ƒ“”)p/§ÆḞS Main Link (monadic): accept [x, y] ) For each k in [x, y] ¹© Save it to the register R Range; [1, 2, ..., k] ‘ Increment; [2, 3, ..., k + 1] U Reverse; [k + 1, k, ..., 2] ;ṖÆḞS>®Ʋ¡¥ƒ“” Reduce this list starting from []: -========¥ Last two as a dyad: ; - append the new value to the list ¡ - then, N times (if statement for boolean values) ÆḞS>®Ʋ - if the sum of those Fibonacci numbers exceeds the desired value Ṗ - pop the last addition back off p/ Cartesian product of the results § Sum of each; get the indexes ÆḞ Convert to Fibonacci numbers S Sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` ŒP‘I’ẠƊƇÆḞS=ɗƇ)p"/§ÆḞ§ ``` [Try it online!](https://tio.run/##y0rNyan8///opIBHDTM8HzXMfLhrwbGuY@2H2x7umBdse3L6sXbNAiX9Q8vBAoeW/3@4Y9PDHYuNwh41rTnc/nDHoqOTHu6cwfVw95bD7UChyP//DRUMFXTtFIy5DBWMQAxTIMMUxDA05jKCyJkCGSZgIQsuE4iQoSGQBRYzMQCyLEEsC3Muc6ishQKQCTbOyBLIAksbmhhyWUKZFpYA "Jelly – Try It Online") This feels grossly long. Returns `[x]` where `x` is the expected output. This is [allowed by default](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/11884#11884) -1 byte thanks to [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino) --- ## How it works ``` ŒP‘I’ẠƊƇÆḞS=ɗƇ)p"/§ÆḞ§ - Main link. Takes [a, b] on the left ) - For each input: ŒP - Cast to range, then powerset ‘ - Increment each one ƊƇ - Keep those for which the following is true: I - Forward differences ’ - Decrement Ạ Are all non-zero? This removes all lists with any consecutive indices ɗƇ - Keep those for which the following is true: ÆḞ - Convert each index to its Fibonacci number S= - Does the sum equal the input? p"/ - Get the Cartesian product of the indices The " (vectorise) quick allows us to avoid extracting the first element, instead we operate with everything wrapped to an additional depth § - Sums ÆḞ - Fibonacci number of each § - Sum ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `as`, 11 bytes ``` ›5√›½ḭṘ*⁰ΠJ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=as&code=%E2%80%BA5%E2%88%9A%E2%80%BA%C2%BD%E1%B8%AD%E1%B9%98*%E2%81%B0%CE%A0J&inputs=1%0A2&header=&footer=) A port of the other ones. No, there isn't a phi builtin. [Answer] # [Ruby](https://www.ruby-lang.org/), 56 bytes ``` ->a,b{g=->z{(2*z/=1+5**0.5).to_i};a*b+a*g[b+1]+b*g[a+1]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6k63VbXrqpaw0irSt/WUNtUS8tAz1RTryQ/PrPWOlErSTtRKz06SdswVjsJyEgEMmr/FyikRRvqGMZygRiWOpax/wE "Ruby – Try It Online") Same formula as almost everybody else. [Answer] # JavaScript (ES6), ~~98~~ 90 bytes A full implementation. Expects `(a)(b)`. ``` a=>g=(x,k,n)=>(F=n=>n<3||F(n-1)+F(n-2))(-~n)>x?x&&(k?F(k+n):g(a,n))+g(x-F(n),k):g(x,k,-~n) ``` [Try it online!](https://tio.run/##Zc9BCoMwEAXQfU/hSmZQaxMVTWniznuIVWmVpNRSXEivnioGBQOBQN78z@RZfsuhej9en0Cqe60brksuWg6j3/kSuYCCSy7kLZqmAmRA0FsuigjBT6IY89F1ocsL6DyJ1xbKOYVeC2Mwz6HfLW9L1zKtKyUH1dfnXrXQAMH5oBOGTnSyhK6S2JKsQo4hutUltsQmlB0o3kKE2GRS8cUmtlKWHijdCzPHNvMtymwyjSQ@LsJ2y5j@Aw "JavaScript (Node.js) – Try It Online") ### Commented The helper function \$F\$ just computes the \$n\$-th Fibonacci term, 1-indexed. ``` F = n => n < 3 || F(n - 1) + F(n - 2) ``` Main function: ``` a => // outer function taking a g = ( // the inner function g first takes x = b and later x, // invokes itself for the 2nd pass with x = a k, // k is undefined during the 1st pass, then set to // a positive integer n // n is the Fibonacci term index ) => // F(-~n) > x ? // if F(n + 1) is greater than x: x && ( // stop if x = 0, otherwise: k ? // if k is defined: F(k + n) // compute F(k + n) : // else: g(a, n) // process the 2nd pass with x = a and k = n ) + // g(x - F(n), k) // add the result of a recursive call with F(n) // subtracted from x and k unchanged : // else: g(x, k, -~n) // try again with n + 1 ``` --- # JavaScript (ES7), 42 bytes Using [@att's closed-form formula](https://codegolf.stackexchange.com/a/230974/58563) is, obviously, significantly shorter. Expects `(a)(b)`. ``` a=>b=>~~(p=.5+5**.5/2,b-~b/p)*a-~~(~a/p)*b ``` [Try it online!](https://tio.run/##Zc9BCsMgEAXQfU@RpbE1VqtEF@YumialJURpSpde3aZEEnBgFgOP/5l52a9d@vczfMjs70MaTbKmc6aLEQXTyLPEuJGUXxyJjoYaW7JKtP/Vpd7Pi5@GZvIPNCJWr1NXlFa3ExC@iYQiN2FliO91EorIIVWQ2EOMQcopcYWkN1JtQe1RqCpo@S2uIeVGJspD9GFKpx8 "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~19~~ 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Far too long but just can't seem to do any better. There's gotta be a shorter way to get Phi! ``` ×+UËÄ z5¬Ä ÑÃx_*Uo ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1ytVy8QgejWsxCDRw3hfKlVv&input=WzcgOV0) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 123 bytes ``` .+ $* (\G1|(?>\2?)(\1))*1 $#1$*01¶ %)+`^(.*).(.*¶)(\1.)¶ $3$2 +`^(0*)1(.*¶¶)(.+) 0$1$2$3¶00$1$3 3A` 0? ; +`;(1*);1 1;1$1; 1 ``` [Try it online!](https://tio.run/##HYoxDsIwDEX3fw1cKU6jKE6KqioSFVMPwFqhMDCwMCBGztUD9GLB6WD/Z7//eX5f70ftzK04mKVU34MszLrIz8yXNc5sVmG2AjoJ2SD7ho77cjfeste1b63hWf@UKKKpYFkO1aTvGYGEIqV9C40S0rUgzMjazkYsZ4FkIcmQWsXp5aLOGVE5ugGD5nDkhFF5VD8qT276Aw "Retina 0.8.2 – Try It Online") Takes newline-separated inputs but link is to test suite that splits on comma for convenience. Explanation: ``` .+ $* (\G1|(?>\2?)(\1))*1 $#1$*01¶ +`^(.*).(.*¶)(\1.)¶ $3$2 ``` Convert the input to its Zeckendorf representation. This is based on my answer to [Fibonacci Encoding](https://codegolf.stackexchange.com/questions/222676) but without the trailing `1` of course. ``` %)` ``` Apply the above to each input separately. ``` +`^(0*)1(.*¶¶)(.+) 0$1$2$3¶00$1$3 3A` ``` Long multiply the two inputs. (The final addition is implicitly accomplished after the conversion back to decimal.) Additionally, since the Zeckendorf representation starts at F₂, prefix an additional two zeros to adjust for the 2-indexing. ``` 0? ; +`;(1*);1 1;1$1; ``` Convert each Zeckendorf representation back to unary. This is based on my answer to [Converting a number from Zeckendorf Representation to Decimal](https://codegolf.stackexchange.com/questions/173601). ``` 1 ``` Sum the unary values and convert to decimal. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~77~~ ~~62~~ 53 bytes ``` g(m){m=~m*(1-sqrt(5))/2;}f(m,n){m=m*n+g(m)*n+g(n)*m;} ``` [Try it online!](https://tio.run/##hY/LTsMwEEXXyVeMipDsPKDOgyZKWz6DBVQoch5Yip0Su2yq8OmEcbwBsUAaec7cOyNd87jnfLkRig@XpoW9No0Y796OS08kvcrDpwwIi/X7ZEhO6X1SzR2RkbKWDFRot9amaCCreRHKgGm1eeW1bvXzCQ5w9T0WAVYarZREkDvKUbZistq5owyHAjFbRcYc2to6LCModog7t1A4xMukdIgLLLN3peOi9OfKt8lkLRT5GEVDbapunMhFadGrtgFrC0y7rbDtIX2wPTxASn3PO09od2Rz2wBWfLTvIz4vahP9/K44/R4hBPZXSlDqyH9nlFb@vHzxbqh7vcRPaoyFPA@CCxNjmm8 "C (gcc) – Try It Online") -15 bytes thanks to [ovs](https://codegolf.stackexchange.com/questions/230967/compute-the-fibonacci-product#comment529696_231040) -9 bytes thanks to [att](https://codegolf.stackexchange.com/questions/230967/compute-the-fibonacci-product/231040?noredirect=1#comment529745_231040) [Original submission:](https://tio.run/##hY/dasMwDIWv66cQLQM7cbc6P2tC2u41ClsZJXY6w@JssbObkmfP5HgXG70YCOnTkQ5I9fpS19NKm/p9kAp21knd3b8dppVUjTYKjrTlhkFMtXGM0jYWLEoeqP3sHc0ZdiwypJmXrr1yQ2@gjcyP7UgNb1k1TmgGp6x7rc9W2ecT7OFKFoIDRspnSjjkgXKUvZjM4zxQhk2BmM2iEAF9bAKWHIot4jYsFAHRmZQBcUFk3lcGLkoyVsRf1p61oV@dlsxf1XQ9HYzVF6Mk@LHGazcVlh2kj77Ge0gZWSw@ehw3dHknAWN98PkJ04tZ8t/v6tPfFmIQt1KCUkP/szFWkXH6Bg "C (gcc) – Try It Online") ``` #define X(m,n) +(int)((m+1)*2/(sqrt(5)+1))*n f(m,n){return m*n X(m,n)X(n,m);} ``` Basically an adaptation of [att's excellent answer](https://codegolf.stackexchange.com/a/230974/56453). Thanks to the power of ~~the preprocessor~~ *undefined behavior* this is way shorter than an equivalent Java version I tried. [Answer] # Python 2, ~~68~~ *61* bytes -7 bytes thanks to ovs, and based on att's [answer](https://codegolf.stackexchange.com/a/230974/83082): ``` def f(x,y):p=lambda a:~a*(1-5**.5)//2;print x*y+x*p(x)+y*p(y) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo0KnUtOqwDYnMTcpJVEh0aouUUvDUNdUS0vPVFNf38i6oCgzr0ShQqtSu0KrQKNCU7sSSFVq/k/TsNSx1OQCURYgyljHVPM/AA) As my first golfing experience with python, there might be room for improvement. Suggestions are welcome. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 16 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ê)φ/iêx^~êßmÅε*Σ ``` MathGolf has a builtin for the golden ratio / phi, but unfortunately it's not too good at taking the product of inner lists.. [Try it online.](https://tio.run/##y00syUjPz0n7///wKs3zbfqZh1dVxNUdXnV4fu7h1nNbtc4t/v/fUMGQy1DBCIhNuYyAbCMFEy4TIG0Cpi25zIFsc6C8OZBtqWAJAA) **Explanation:** ``` ê # Push the input as integer-array: [a,b] ) # Increase both values by 1: [a+1,b+1] φ/ # Divide both by phi: [(a+1)/phi,(b+1)/phi] i # Floor the decimals to an integer: [(a+1)//phi,(b+1)//phi] êx # Push the input-array again, and reverse it: [b,a] ^ # Zip the two lists together: [[(a+1)//phi,b],[(b+1)//phi,a]] # Append the input-pair to this list, by: ~ # Dumping both pairs onto the stack ê # Push the input-array again ß # Wrap all three pairs into a list: [[(a+1)//phi,b],[(b+1)//phi,a],[a,b]] m # Map over the inner lists, Å # using the following two characters as inner code-block: ε* # Take the product of this inner pair: [(a+1)//phi*b,(b+1)//phi*a,a*b] Σ # Sum all three values together: (a+1)//phi*b+(b+1)//phi*a+a*b # (after which the entire stack is output implicitly as result) ``` ]
[Question] [ 2019 has come and probably everyone has noticed the peculiarity of this number: it's in fact composed by two sub-numbers (20 and 19) representing a sequence of consecutive descending numbers. ### Challenge Given a number `x`, return the length of the maximum sequence of consecutive, descending numbers that can be formed by taking sub-numbers of `x`. Notes : * sub-numbers cannot contain leading zeros (e.g. `1009` cannot be split into `10`,`09`) * consecutive and descending means that a number in the sequence must be equal to the previous number -1, or \$n\_{i+1} = n\_{i}-1\$ (e.g. `52` cannot be split into `5,2` because `5` and `2` are not consecutive, `2 ≠ 5 - 1`) * the sequence must be obtained by using the full number, e.g. in `7321` you can't discard `7` and get the sequence `3`,`2`,`1` * only one sequence can be obtained from the number, e.g. `3211098` cannot be split into two sequences `3`,`2`,`1` and `10`,`9`,`8` ### Input * An integer number (`>= 0`) : can be a number, or a string, or list of digits ### Output * A single integer given the maximum number of decreasing sub-numbers (note that the lower-bound of this number is `1`, i.e. a number is composed by itself in a descending sequence of length one) ### Examples : ``` 2019 --> 20,19 --> output : 2 201200199198 --> 201,200,199,198 --> output : 4 3246 --> 3246 --> output : 1 87654 --> 8,7,6,5,4 --> output : 5 123456 --> 123456 --> output : 1 1009998 --> 100,99,98 --> output : 3 100908 --> 100908 --> output : 1 1110987 --> 11,10,9,8,7 --> output : 5 210 --> 2,1,0 --> output : 3 1 --> 1 --> output : 1 0 --> 0 --> output : 1 312 --> 312 --> output : 1 191 --> 191 --> output : 1 ``` ### General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Bugfix thanks to Dennis ``` ŻṚẆDfŒṖẈṀ ``` **[Try it online!](https://tio.run/##ASIA3f9qZWxsef//xbvhuZrhuoZEZsWS4bmW4bqI4bmA////MjEw "Jelly – Try It Online")** (even `321` takes half a minute since the code is at least \$O(N^2)\$) ### How? ``` ŻṚẆDfŒṖẈṀ - Link: integer, n Ż - [0..n] Ṛ - reverse Ẇ - all contiguous slices (of implicit range(n)) = [[n],...,[2],[1],[0],[n,n-1],...,[2,1],[1,0],...,[n,n-1,n-2,...,2,1,0]] D - to decimal (vectorises) ŒṖ - partitions of (implicit decimal digits of) n f - filter discard from left if in right Ẉ - length of each Ṁ - maximum ``` [Answer] # JavaScript (ES6), 56 bytes A port of [ArBo's Python answer](https://codegolf.stackexchange.com/a/178753/58563) is significantly shorter. However, it fails on some test cases because of too much recursion. ``` f=(n,a=0,c=0,s)=>a<0?f(n,a-~c):n==s?c:f(n,--a,c+1,[s]+a) ``` [Try it online!](https://tio.run/##jdDBisIwEAbg@z5FyKnBic5UazPF6IOIh5C1y4o0YqpHX71W0F3b6rI/5DKEj59/584u@uP3odZV@Nw2TWmTCpxF8O2Lyi7dAlfl7aYvXhWVtXHli9tBawd@RLCOm5FTjQ9VDPvteB@@kjKRKRJLcY9SYjIRKQKx@I3WSxFO9eFUi0KkHz3A5PNsJjuAgRzmkMHsFZD1AUJkZiOfgPYEzMDmFTAdAETIJu8ABNQS0Db5R4OU8GeCxwZAgO82GDaQT1/vDUQ3HYD6AA4B/BNorg "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 66 bytes Takes input as a string. ``` f=(s,n=x='',o=p=n,i=0)=>s[i++]?o==s?i:f(s,--n,o+n,i):f(s,p+s[x++]) ``` [Try it online!](https://tio.run/##lZLdboJAEEbv@xQbboQw1Jnlb9dk9UFML4yVhsawpGDj29OpSisLGp2ECz4mJ@fb5XPzvWm2X2XdRpV933VdYfwGKnM0sxlYU5sKSoOBWTbrMgzfVtaYZlUuCl6KogpsyN@D02sdNusjrwTd1laN3e9e9/bDL3xPImlPXCYIxHwuJAJp8T9RtBT20NaHViyEfBkDJDJEk1ZeDyDgjCmaHzUEJC4glknmGPxG4pYBuQCVZ2niDQAKcsgghWQKkLoAknGS9g5nwDl61IAQteb61wDuz/W5/QQgngKgGhqcoocNiFCrfGBAQOwAfBYPnIEk/LuE/j8AArx1C@MK3tXqxUAM534FHAPwKUBM0q3A0RMA0uQCOLoD6H4A "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f = recursive function taking: s, // s = input number, as a string n = // n = counter x = '', // x = position of the next digit to be added to p o = p = n, // o = generated output; p = prefix i = 0 // i = number of consecutive descending numbers ) => // s[i++] ? // increment i; if s[i] was defined: o == s ? // if o is matching s: i // stop recursion and return i : // else: f( // do a recursive call with: s, // s unchanged --n, // n - 1 o + n, // (n - 1) appended to o i // i unchanged (but it was incremented above) ) // end of recursive call : // else: f( // this is a dead end; try again with one more digit in the prefix: s, // s unchanged p + s[x++] // increment x and append the next digit to p ) // end of recursive call ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~43 41~~ 40 bytes *-1 byte thanks to nwellnhof* ``` {/(<-[0]>.*?|0)+<?{[==] 1..*Z+$0}>/;+$0} ``` [Try it online!](https://tio.run/##dZBNboMwEEb3PsXIqioIgzNjft0Gco9SFl0EKRJtUCCLiObs1E1KCy31xvKbN5/HbnbHOh5ez3BfQQZDv3Y2fkFlrlbbd3K9zbYvsqwEVmr15N3RJV8/fm5DdTiCU@/fdq2b56pt6n3nSN/PpQu9AGhfzuApG4TyuZNYOdeDixIkqkKX4jJoYgPjsp2gCSfkxg6nrjl18ABaWF@T7TFs0i@f0RLbZHBk334oAh3Gs6wZ@J3PIk3iKJzWUkwwxgjDJT8SrIMwiie1Gfibz0TG2DF/fDu7HX1Ecz@4@jStzcBCPjOZNJn4jGxvQPuOpfk10@0bkZH@@5bgAw "Perl 6 – Try It Online") Regex based solution. I'm trying to come up with a better way to match from a descending list instead, but Perl 6 doesn't do partitions well ### Explanation: ``` { } # Anonymous code block / /; # Match in the input <-[0]>.*? # Non-greedy number not starting with 0 |0 # Or 0 ( )+ # Repeatedly for the rest of the number <?{ }> # Where 1..*Z+$0 # Each matched number plus the ascending numbers # For example 1,2,3 Z+ 9,8,7 is 10,10,10 [==] # Are all equal +$0 # Return the length of the list ``` [Answer] # [Python 3](https://docs.python.org/3/), 232 228 187 181 180 150 149 bytes -1 thanks to @[Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) ``` e=enumerate t=int h=lambda n,s=1:max([1]+[i-len(n[j:])and h(n[j:],s+1)or s+1for j,_ in e(n)for i,_ in e(n[:j],1)if(t(n[:j])-t(n[j:j+i])==1)*t(n[0])]) ``` [Try it online!](https://tio.run/##dVLLboMwELzzFauecONUGEgCSD70UPUjCEIOOAUEBoFpElX9dmockiak9WU9szPrx25zklktnGHglIu@4i2T3JA0F9LIaMmqXcpA4I6SoGJHMyTRIsyXJRemCIsgQkykkJ33uFsQVLegwl6FAseQC@CmQCPMrzAMiggTlO9NeQZoKXWFYpFHiFKCnkdsRShCQ1Yf4oqJU5zUouNJL/NP3gGFDAxQy0j5HljX8VbGh1xmcdOqm5sfSiUw8GPDE8lTDCyRPStRoE1n/TULlE55DE9b8T56g1H39b0Vb5Mo0OhVy4Ip9/SiHlax/48z9PUk76Q5Hc2PrGpK/YJQE@MybQy2RXyEfylXU7alaJ/43m2KYHBsd31LrTB4m/XKncmI7birO6GjSMvy/YeKI2t5s5qEEMv3NrMCNrHm5hme5x1izx3@xRMZOowjcvm/WM3hjrdYzUvTywnp4Zl@L7jWemz9rQc/lvxznsxOtndGhFTvzn0bfgA "Python 3 – Try It Online") Initial ungolfed code: ``` def count_consecutives(left, right, so_far=1): for i,_ in enumerate(left, start=1): left_part_of_right, right_part_of_right = right[:i], right[i:] if (int(left) - int(left_part_of_right)) == 1: if i == len(right): return so_far + 1 return count_consecutives(left_part_of_right, right_part_of_right, so_far + 1) return so_far def how_many_consecutives(n): for i, _ in enumerate(n): left, right = n[:i], n[i:] for j, _ in enumerate(left, start=1): left_part_of_right = right[:j] if int(left) - int(left_part_of_right) == 1 and int(n[i]) > 0: return count_consecutives(left, right) return 1 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~78~~ ~~74~~ 73 bytes ``` l=lambda n,a=0,c=0,s="":c*(n==s)or a and l(n,a-1,c+1,s+`a-1`)or l(n,a-~c) ``` [Try it online!](https://tio.run/##TYrRCgIhFETf9yvEJ20tNGqLwH9ZcxcS9Cpee9iXft1uBNHAwJyZKVt7ZDj2kEqujeGGA/mAa6urf1YMGWJIoQmjSbJHG126L46BclYrT0bL@c3vBFiLMlfmmIOFRUGPvVF@NArHmeL8Gb/1y8teaoBGzDWXww/MP1wv0/nEZX8D "Python 2 – Try It Online") -1 byte thanks to Arnauld Takes input as a string. The program rather quickly runs into Python's recursion depth limit, but it can finish most of the test cases. ### How it works ``` l=lambda n, # The input number, in the form of a string a=0, # The program will attempt to reconstruct n by # building a string by pasting decreasing # numbers, stored in a, after each other. c=0, # A counter of the amount of numbers s="": # The current constructed string c*(n==s) # Return the counter if s matches n or # Else a and l(n,a-1,c+1,s+`a-1`) # If a is not yet zero, paste a-1 after s or # Else l(n,a-~c) # Start again, from one higher than last time ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÝRŒʒJQ}€gà ``` Extremely slow, so the TIO below only works for test cases below 750.. [Try it online](https://tio.run/##yy9OTMpM/f//8Nygo5NOTfIKrH3UtCb98IL//w0NLAE). **Explanation:** ``` Ý # Create a list in the range [0, (implicit) input] # i.e. 109 → [0,1,2,...,107,108,109] R # Reverse it # i.e. [0,1,2,...,107,108,109] → [109,108,107,...,2,1,0] Œ # Get all possible sublists of this list # i.e. [109,108,107,...,2,1,0] # → [[109],[109,108],[109,108,107],...,[2,1,0],[1],[1,0],[0]] ʒ } # Filter it by: J # Where the sublist joined together # i.e. [10,9] → "109" # i.e. [109,108,107] → "109108107" Q # Are equal to the (implicit) input # i.e. 109 and "109" → 1 (truthy) # i.e. 109 and "109108107" → 0 (falsey) €g # After filtering, take the length of each remaining inner list # i.e. [[109],[[10,9]] → [1,2] à # And only leave the maximum length (which is output implicitly) # i.e. [1,2] → 2 ``` [Answer] # Pyth, 16 bytes ``` lef!.EhM.+vMT./z ``` Try it online [here](https://pyth.herokuapp.com/?code=lef%21.EhM.%2BvMT.%2Fz&input=2019&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=lef%21.EhM.%2BvMT.%2Fz&test_suite=1&test_suite_input=2019%0A201200199198%0A3246%0A87654%0A123456%0A1009998%0A100908%0A1110987%0A210&debug=0). ``` lef!.EhM.+vMT./z Implicit: z=input as string ./z Get all divisions of z into disjoint substrings f Filter the above, as T, keeping those where the following is truthy: vMT Parse each substring as an int .+ Get difference between each pair hM Increment each !.E Are all elements 0? { NOT(ANY(...)) } e Take the last element of the filtered divisions Divisions are generated with fewest substrings first, so last remaining division is also the longest l Length of the above, implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ŒṖḌ’Dɗ\ƑƇẈṀ ``` Byte for byte, no match for the other Jelly solution, but this one should be roughly \$O\left(n^{0.3}\right)\$. [Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c0fOoYabLyekxxyYea3@4q@Phzob/R/coHG5/1LRGwf3/fyMDQ0sdBSBpZABkWRpaWugoGBuZmOkoWJibmZroKBgaGZuYArmGBgaWliBZEMMARBsaGlhamAM1GxoAeToKBiCmMZBpaQgA "Jelly – Try It Online") ### How it works ``` ŒṖḌ’Dɗ\ƑƇẈṀ Main link. Argument: n (integer) ŒṖ Yield all partitions of n's digit list in base 10. Ƈ Comb; keep only partitions for which the link to the left returns 1. Ƒ Fixed; yield 1 if calling the link to the left returns its argument. \ Cumulatively reduce the partition by the link to the left. ɗ Combine the three links to the left into a dyadic chain. Ḍ Undecimal; convert a digit list into an integer. ’ Decrement the result. D Decimal; convert the integer back to a digit list. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` F⊕LθF⊕Lθ⊞υ⭆κ⁻I…θιλI﹪⌕υθ⊕Lθ ``` [Try it online!](https://tio.run/##fY27CgIxEEV7v2LKGYig24mlIAgGFvyCkMRNME7My9/PxsJS63POvdqprKMKvd9jBrywzvZpuVqDV8tLdZiICP7CuRWHTcCtZs@LVC98CJCeW8GTKhVlDAaTAE8kIIziuJmHWb/UtBDx7Nl8RtJwfhyNsPdptz/07Tus "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⊕Lθ ``` Loop `i` from 0 to the length of the input. ``` F⊕Lθ ``` Loop `k` from 0 to the length of the input. ``` ⊞υ⭆κ⁻I…θ⊕ιλ ``` Calculate the first `k` numbers in the descending sequence starting from the number given by the first `i` digits of the input, concatenate them, and accumulate each resulting string in the predefined empty list. ``` I﹪⌕υθ⊕Lθ ``` Find the position of the first matching copy of the input and reduce it modulo 1 more than the length of the input. Example: For an input of `2019` the following strings are generated: ``` 0 1 0 2 0-1 3 0-1-2 4 0-1-2-3 5 6 2 7 21 8 210 9 210-1 10 11 20 12 2019 13 201918 14 20191817 15 16 201 17 201200 18 201200199 19 201200199198 20 21 2019 22 20192018 23 201920182017 24 2019201820172016 ``` `2019` is then found at index 12, which is reduced modulo 5 to give 2, the desired answer. [Answer] ## Haskell, 87 bytes ``` maximum.map length.(0#) a#(b:c)=[a:x|c==[]||b>0,x<-b#c,a==x!!0+1]++(10*a+b)#c a#b=[[a]] ``` Input is a list of digits. [Try it online!](https://tio.run/##ZZBNDoIwEIX3nqKGDchIij@IxnoDT1C7mDYiRCDEn4QFZxenaEKNfcmk@eb1ddoc79dzWfaZOPUVtkX1rKIKG1ae68sjj3zuBRP0fL0zgZC4azsjhFRdpw8c2v1cewZQiHY65WGswtCP@QxDHXiGTmkhJSpFuUXNBKPYI/ObW1E/WMSyYMLsknIBHGLYKvgA9gW2Dg2SreloWFJzBckIUthAAmtYjcgGLMm1dn3xkLkdlP5j/gutLKZ0dziCjmvccndAut6NoifQR7xMVuLl3s9N07wB "Haskell – Try It Online") Function `#` builds a list of all possible splits by looking at both * prepending the current number `a` to all splits returned by a recursive call with the rest of the input (`x<-b#c`), but only if the next number not zero (`b>0`) (or it's the last number in the input (`c==[]`)) and `a` is one greater than the first number of the respective previous split `x` (`a==x!!0+1`). and * appending the next digit `b` from the input list to the current number `a` and going on with the rest of the input (`(10*a+b)#c`) Base case is when the input list is empty (i.e. does not pattern match `(b:c)`). The recursion starts with the current number `a` being `0` (`(0#)`), which never hits the first branch (prepending `a` to all previous splits), because it will never be greater than any number of the splits. Take the length of each split and find the maximum (`maximum.map length`). A variant with also 87 bytes: ``` fst.maximum.(0#) a#(b:c)=[(r+1,a)|c==[]||b>0,(r,x)<-b#c,a==x+1]++(10*a+b)#c a#b=[(1,a)] ``` which basically works the same way, but instead of keeping the whole split in a list, it only keeps a pair `(r,x)` of the length of the split `r` an the first number in the split `x`. [Answer] # [Python 3](https://docs.python.org/3/), ~~302~~ ~~282~~ 271 bytes -10 bytes thanks to the tip by @ElPedro. Takes input as a string. Basically, it takes increasing larger slices of the number from the left, and sees if for that slice of the number a sequence can be formed using all the numbers. ``` R=range I=int L=len def g(n,m,t=1): for i in R(1,L(m)+1): if I(m)==I(n[:i])+1: if i==L(n):return-~t return g(n[i:],n[:i],t+1) return 1 def f(n): for i in R(L(n)): x=n[:i] for j in R(1,L(x)+1): if (I(x)==I(n[i:i+j])+1)*I(n[i]):return g(n[i:],x) return 1 ``` [Try it online!](https://tio.run/##VVHLbsIwELz7K1b04hRTeZ0AcST3HokTV5QDahNqVAxKXIkK0V9PvU6gxRfvzD5m1j59@4@jS/t@bdqt29WsNNZ5tjKftWPvdQM77sRBeINJwaA5tmDBOlhzFCt@SKaRBttAGZAxJXebwlaBJ5p4a8yKu6Roa//VutmPJ34ANHtji0rEHuHDMHZLYRRvqPNBlmZFybOJXSGi7P7P1PlmitR5GfBgyxZ2uidnyXOE1c3T3cb5n3zv686/bbu6AwMbpiRqAU@gKFIyII06JyZjqcoWFCHLl4t5RuGcoUqz@UijlFoP1WkEMh8TiFLny6FDoRwrhqQcrhTVWKwx3hVjtDH5o6XvPsPKpzb8HZ9crjB7hct18hIKD1vPqUaEx@x8G@MknP4X "Python 3 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 27 bytes ``` ò pÊÔpÊqÊfl²i1Uì q"l?"¹ÌèÊÉ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=8iBwytRwynHKZmyyaTFV7CBxImw/IrnM6MrJ&input=MjEyMDE=) or [Check most test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=8iBwytRwynHKZmyyaTFV7CBxImw/IrnM6MrJ&input=WzIwMTkKMzI0Ngo4NzY1NAoxMjM0NTYKMTAwOTk5OAoxMDA5MDgKMTExMDk4NwoyMTAKMQowCjE5MQozMTJdCi1t) This doesn't score well, but it uses a unique method and there might be room to golf it a lot more. It also performs well enough that all test cases other than `201200199198` avoid timing out. Explanation: ``` ò #Get the range [0...input] pÊ #Add an "l" to the end Ô #Reverse it pÊ #Add an "l" to the end qÊ #Add an "l" between each number and turn to a string f ¹ #Find the substrings that match this regex: l² # The string "ll" i1 # With this inserted between the "l"s: Uì # All the digits of the input q"l?" # With optional spaces between each one Ì #Get the last match èÊ #Count the number of "l"s É #Subtract 1 ``` [Answer] # Dyalog APL, 138 bytes Bit of a mouthful, but it works fast for big numbers too. If you [try it online](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE6of9XToP@rdqqHxqHPRo64mzcPTDR91LNezNdLVNzR41LX00AqQ6KPeFY96lxg@6lpkqFP9qHfNo86Fho/aJgM1Wj1qmwgUMHzU3WJg@6irGSRkoPOoox0qDxQHqtAxUAAaO0NPB2gY2CC4fC2MVjBSACpSsPz/HwA), prefix the dfn by `⎕←` and provide input on the right as a list of digits. ``` {⌈/⍵((≢⊂)×1∧.=2-/10⊥¨⊂)⍨⍤1⊢1,{⍬≡1↓⍵:↑⍬1⋄0=⊃⍵:0,∇1↓⍵⋄↑,0 1∘.,⊂⍤1∇1↓⍵}1↓⍵} ``` ### Explanation First, the inner dfn on the right which recursively constructs a list of possible ways to partition (with `⊂`) the list of digits. For example `1 0 1 0 ⊂ 2 0 1 9` returns the nested vector `(2 0)(1 9)`. ``` { ⍬≡1↓⍵: ↑⍬1 ⍝ Edge case: If ⍵ is singleton list, return the column matrix (0 1) 0=⊃⍵: 0,∇1↓⍵ ⍝ If head of ⍵ is 0, return 0 catenated to this dfn called on tail ⍵ ↑,0 1∘.,⊂⍤1∇1↓⍵ ⍝ Finds 1 cat recursive call on tail ⍵ and 0 cat recursive call on ⍵. } ⍝ Makes a matrix with a row for each possibility. ``` We use `1,` to add a column of 1s at the start and end up with a matrix of valid partitions for ⍵. Now the function train on the left in parens. Due to `⍨` the left argument to the train is the row of the partitions matrix and the right argument is the user input. The train is a pile of forks with an atop as the far left tine. ``` ((≢⊂)×1∧.=2-/10⊥¨⊂)⍨ ⍝ ⍨ swaps left and right arguments of the train. ⊂ ⍝ Partition ⍵ according to ⍺. 10⊥¨ ⍝ Decode each partition (turns strings of digits into numbers) 2-/ ⍝ Difference between adjacent cells 1∧.= ⍝ All equal 1? ⊂ ⍝ Partition ⍵ according to ⍺ again ≢ ⍝ Number of cells (ie number of partitions) × ⍝ Multiply. ``` If the partition creates a sequence of descending numbers, the train returns the length of the sequence. Otherwise zero. `⍤1⊢` applies the function train between the user input and each row of the partitions matrix, returning a value for each row of the matrix. `⊢` is necessary to disambiguate between operand to `⍤` and argument to the derived function of `⍤`. `⌈/` finds the maximum. Could find a shorter algorithm but I wanted to try this way which is the most direct and declarative I could think of. [Answer] ## Haskell, 65 bytes ``` f i=[y|x<-[0..],y<-[1..length i],i==(show=<<[x+y-1,x+y-2..x])]!!0 ``` Input is a string. [Try it online!](https://tio.run/##TY09DoMwDEb3niJlAjVEdviNRI7QE0QZGKBEBYoKUkHq3VOiDokHy@99tjy067MbR2t7YqQ6vnuTKmBM0@MckLGxmx/bQIymRsp4HV4f2TRqvx0pUtc5Y7tO9PUKdmrNTCSZ2uVO4uVt5o2RPrkQVyrigCKifyKOOJxGoKi9zXheeqqrssg9Is/yIogRQIjw2gkIGRFEXQVPEYLUj4HNkAcrAiNtfw "Haskell – Try It Online") Completely different to my [other answer](https://codegolf.stackexchange.com/a/178425/34531). A simple brute force that tries all lists of consecutive descending numbers until it finds one that equals the input list. If we limit the input number to 64-bit integers, we can save 6 bytes by looping `y` through `[1..19]`, because the largest 64-bit integer has 19 digits and there's no need to test lists with more elements. ### Haskell, 59 bytes ``` f i=[y|x<-[0..],y<-[1..19],i==(show=<<[x+y-1,x+y-2..x])]!!0 ``` [Try it online!](https://tio.run/##TY3PCoMwDIfve4rqSVktSf0bsI@wJyg9eJgoUydzMIW9e2fZoc0h5Pt@CRm67XGfJmt7Nip9fPc20yCE4cc5oBBIho9KJdvw/Ki21fv1yJC7LoXYTWqiCOzcjQtTbO7WG0vW17i8BevTC3OlYwlIMf8TcyThNITUeJvLovLU1FVZeESZF2UQIwBReO0EhIwI1NTBU4Qg9WNgc5TBCmFs7A8 "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 95 bytes ``` lambda n:max(j-i for j in range(n+1)for i in range(-1,j)if''.join(map(str,range(j,i,-1)))==`n`) ``` Another slow, brute-force solution. [Try it online!](https://tio.run/##RYsxDsIwEARreMU2kX3ijHCoiBReQhGjYDiLXCKTAl5vElHQrFYzmukzP0atS0SLS3mG4doHaDOEt01OEMeMBFHkoPeb1Z2nFckfOc@JJBqzT6OoHcJkX3Pmn0ws7DwRtW2nHZW11bWt/YHhGcsefb3ck2@2mymLzjDVsYc7o@oNKlhlRKtE5Qs "Python 2 – Try It Online") [Answer] # TSQL, 169 bytes Note: this can only be executed when the input can be converted to an integer. Recursive sql used for looping. Golfed: ``` DECLARE @ varchar(max) = '1211109876'; WITH C as(SELECT left(@,row_number()over(order by 1/0))+0t,@+null z,0i FROM spt_values UNION ALL SELECT t-1,concat(z,t),i+1FROM C WHERE i<9)SELECT max(i)FROM C WHERE z=@ ``` Ungolfed: ``` DECLARE @ varchar(max) = '1211109876'; WITH C as ( SELECT left(@,row_number()over(order by 1/0))+0t, @+null z, 0i FROM spt_values UNION ALL SELECT t-1, concat(z,t), i+1 FROM C WHERE i<9 ) SELECT max(i) FROM C WHERE z=@ ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/962931/how-many-consecutive-descending-numbers-in-my-number)** [Answer] # [R](https://www.r-project.org/), 101 bytes ``` function(a,N=nchar(a)){for(x in 1:N)F=max(F,which(Reduce(paste0,seq(substr(a,1,x),,-1,N),a=T)==a));F} ``` [Try it online!](https://tio.run/##fdHLaoQwFAbgfZ8i0IUJHCEn3pIpdunSRekLWKvoYnTqhQqlz26PM7XO2NFANge@/PmTZszDMe@rtCvriicQh1VaJA1PhPjK64YPrKwYHmIRhcdk4BF8FmVa8JfsvU8zfkraLpPQZh@87d/ajhwgDALARogFJOGrCEM66yn6HnNuKYnGYr9LMPZo289MSUDDljXN6r479R07MPVwYUoSNWi0tTAEmpI1tPUtcyfmKNf/lzYN2VYaTkwHvudaK6YhAB88cO8xb2KoHNeb82Z2Ge6loZTGUK1bRr2oFrW6w5yZSb1OOw930xCl0cEqDQEpD6jjRjeF8u8hl3@jr5ZbL3m@5BVa2DXZuOQ9hrts/AE "R – Try It Online") More than 2 weeks have passed without any R answer, so I decided to post my own :) The code is pretty fast since it uses a "limited" brute force approach ### Unrolled code and explanation : ``` function(a){ # get string a as input (e.g. "2019") N = nchar(a) # set N = length of a (e.g. 4) Y = 0 # initialize Y = 0 (in the actual code we abuse F) for(x in 1:N){ # for x in 1 ... N S = substr(a,1,x) # get the first x characters of a (e.g. "20" for x=2) Q = seq(S,,-1,N) # create a decreasing sequence (step = -1) # of length N starting from S converted into integer # (e.g. Q = c(20,19,18,17) for x=2) R = Reduce(paste0,Q,a=T) # concatenate all the increasing sub-sequences of Q # (e.g. R = c("20","2019","201918","20191817") for x=2) I = which(R == a) # Get the index where R == a, if none return empty vector # (e.g. I = 2 for x=2) Y = max(Y,I) # store the maximum index found into Y } return(Y) # return Y } ``` ]
[Question] [ # Challenge Given a binary number as input through any means, "simplify" the number using a full program or a function. # Input ``` [binary] ``` * `binary` is a number in binary that is over 0. # Output Take the input, convert it to base 10 without using a builtin, then if that number contains only 1s and 0s, convert it into a base 10 number as if it were another binary number. Repeat the process until the number cannot be read in binary and output that number. # Other information * If the input is 1, simply output `1`. Your program should not go on infinitely simplifying 1. * This is code golf, so shortest answer in bytes by Tuesday (November 17th) wins. * If anything is confusing, leave a comment specifying what I need to clear up and I will edit it accordingly. * Builtins for base conversion are not allowed. # Examples ``` Input | Output 1 | 1 1010 | 2 1011 | 3 1100100 | 4 1100101 | 5 1111110011 | 3 ``` [Answer] # Pyth, ~~20~~ 16 bytes ``` u?-GTG`u+yNsTG0z ``` *4 bytes thanks to Jakube* Half of the code (`u+yNsTG0`) is simply the base conversion code. [Test Suite](https://pyth.herokuapp.com/?code=u%3F-GTG%60u%2ByNsTG0z&test_suite=1&test_suite_input=1%0A1010%0A1011%0A1100100%0A1100101%0A1010101&debug=0) ``` u?-GTG`u+yNsTG0z z = input() (The string of 1s and 0s) T = 10 u z Apply until the value stops changing, starting with z G is the current value, a string of 0s and 1s. ?-GT If G - T, e.g., G with the digits 1 and 0 removed is not empty, G Return G, to end the iteration. u G0 Else, reduce over G with initial value 0. yN Double the running total + sT and add the next digit, cast to an int. ` Convert to string. ``` The input `1` is handled by the fact that `u` notices the value has stopped changing. [Answer] # CJam, ~~24~~ 23 bytes ``` q{:~{1$++}*s__,(As*-!}g ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%7B%3A~%7B1%24%2B%2B%7D*s__%2C(As*-!%7Dg&input=1100101). ### How it works ``` q Read all input. { }g Do: :~ Evaluate each character. Maps '0' -> 0 and '1' -> 1. { }* Fold; for each integer but the first: 1$ Copy the second-topmost integer. ++ Add all three integers on the stack. s__ Cast to string and push two copies. ,( Calculate string length and subtract 1. As Push the string "10". * Repeat the string length-1 times. - Remove its elements from the string representation of the integer. ! Apply logical NOT. If `!' pushed 1, repeat the loop. ``` [Answer] ## Pip, ~~28~~ 27 bytes ``` Ta=1|aRMta:$+(^a)*2**RV,#aa ``` Takes input as a command-line argument. We want to loop until `a=1` or `a` contains some character(s) besides 0's and 1's. This latter condition is tested by `RM`'ing all characters in `t` = `10` from `a`. If there's anything left, the condition is truthy. Inside the loop, the conversion works as follows: ``` a:$+(^a)*2**RV,#a ,#a range(len(a)) RV reversed 2** 2 to the power of each element (^a)* multiplied item-wise with each digit in split(a) $+ Sum a: and assign back to a ``` Putting `a` at the end auto-prints it. A recursive solution in 28 bytes: ``` a<2|aRMt?a(f$+(^a)*2**RV,#a) ``` [Answer] ## Python 2, 52 ``` f=lambda n:n>1<'2'>max(`n`)and f(n%10+2*f(n/10))or n ``` It's easier to think of this as two recursive functions: ``` g=lambda n:n and n%10+2*g(n/10) f=lambda n:n>1<'2'>max(`n`)and f(g(n))or n ``` The function `g` converts a decimal value to binary, and the function `f` applies `g` repeatedly is long as its argument is made of digits 0 and 1 (`'2'>max(`n`)`) and is not `1`. The golfed code collapses them into a single function by inserting the definition of `g(n)` for `f(n)`, replacing the recursive call to `g` with `f`. The base case of `n=0` of `g` is automatically handled by the check `n>1`. [Answer] # Prolog, ~~220~~ 212 bytes ``` :-use_module(library(clpfd)). x(B,N):-reverse(B,C),foldl(y,C,0-0,_-N). y(B,J-M,I-N):-B in 0..1,N#=M+B*2^J,I#=J+1. b(N,I):-N>47,N<50,I is(N-48). p(N):-N>1,number_codes(N,L),maplist(b,L,Y),x(Y,B),p(B);write(N). ``` **Explanation** **p** is the main function and performs the following steps (with help from b,x,y): * checks if current number is bigger than 1 * converts integer to list of ascii representations of digits * checks that all numbers are 0 or 1 * converts ascii list to binary integer list * converts binary integer list to decimal number * recurses * prints when a predicate fails. **Edit:** Saved 8 bytes by unifying the p-clauses with OR. [Answer] # Mathematica ~~107~~ 106 With a byte saved by DLosc. ``` j@d_:=(p=0;v=IntegerDigits@d; Which[d<2,1,Complement[v,{0,1}]=={},j@Fold[#+#2 2^p++&,0,Reverse@v],1<2,d]) ``` Break the input into its digits. If the input is 1, output 1. If the input is a number consisting of 0's and 1's, convert that to decimal and run it through again. Otherwise, return the input. --- ``` j[1] ``` > > 1 > > > --- ``` j[11010001] ``` > > 209 > > > --- ``` j[1111110001] ``` > > 1009 > > > --- ``` j[1111110011] ``` > > 3 > > > The first step yields 1011 which in turn yields 3. --- Here we test starting with 1011. ``` j[1011] ``` > > 3 > > > [Answer] # Javascript, 132, 123 bytes Well, it's not the best answer, but.. FYI, if an invalid input is given, it displays the same to the user. ``` function c(x){while(x!=0&&!/[2-9]/.test(x)){for(i=r=0;x;i++)r+=x%10*Math.pow(2,i),x=parseInt(x/10);x=r}alert(x)}c(prompt()) ``` [Answer] # JavaScript ES6, 52 As a function. The function argument must be either a string of binary digits or a number whose decimal representation contains only 1 and 0. Test running the snippet below in an EcmaScript 6 compliant browser - implementing arrow functions, template strings and spread operator (I use Firefox) ``` f=s=>s<2|[...s+''].some(c=>(n+=+c+n,c>1),n=0)?s:f(n) // To test console.log=(...x)=>O.innerHTML+=x+'\n'; // Basic test cases ;[[1,1],[1010,2],[1011,3],[1100100,4],[1100101,5],[1111110011,3]] .forEach(t=>console.log(t[0]+' -> '+f(t[0])+' expected '+t[1])) function longtest() { var o=[],i; for (i=1;i<1e6;i++) b=i.toString(2),v=f(b),v!=i?o.push(b+' '+v):0; O.innerHTML=o.join`\n` } ``` ``` Click to run the long test <button onclick="longtest()">go</button> <pre id=O></pre> ``` [Answer] # Mathematica, ~~62~~ ~~59~~ ~~55~~ 48 bytes Saved 7 bytes thanks to Martin Büttner. ``` #//.a_/;Max[b=IntegerDigits@a]<2:>Fold[#+##&,b]& ``` [Answer] # Javascript (ES7) 87 80 78 77 74 bytes Snippet demo for supporting browsers (currently only Firefox nightly supports the exponential operator) ``` f=x=>[...x].reverse(i=y=j=0).map(z=>(j|=z,y+=z*2**i++))&&j<2&y>1?f(y+[]):x ``` ``` <input type="text" id="x" value="1111110011"><button onclick="o.innerHTML=f(x.value)">Run</button><div id="o"></div> ``` ``` f=x=> [...x].reverse(i=y=j=0) // reverse string as array, initialize vars .map(z=>( // iterate over the all chatacters j|=z, // keep track of whether a digit higher than 1 is encountered y+=z*2**i++ // build decimal result from binary ))&& j<2&y>1? // if we encountered only 1's and 0's and result > 1 f(y+[]) // then call recursively and cast to a string :x // else return x ``` # Javascript (ES6) 81 bytes Snippet demo for supporting browsers ``` f=x=>[...x].reverse(i=y=j=0).map(z=>y+=z*Math.pow(2,i++,j|=z))&&j<2&y>1?f(y+[]):x ``` ``` <input type="text" id="x" value="1111110011"><button onclick="o.innerHTML=f(x.value)">Run</button><div id="o"></div> ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 37 chars / 54 bytes ``` ↺;ï>1⅋(⬯+ï)ĉ/^[01]+$⌿);)ï=+('ᶀ'+ï);ôï ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=1010&code=%E2%86%BA%3B%C3%AF%3E1%E2%85%8B%28%E2%AC%AF%2B%C3%AF%29%C4%89%2F%5E%5B01%5D%2B%24%E2%8C%BF%29%3B%29%C3%AF%3D%2B%28%27%E1%B6%80%27%2B%C3%AF%29%3B%C3%B4%C3%AF)` Not sure if the `+` operator counts as a built-in for binary conversion... [Answer] ## [Perl 6](http://perl6.org), 67 bytes ``` get,{$_=0;for $^a.comb {$_+<=1;$_+=$^b};$_}...1|/<-[01]>/;say $_//1 ``` [Answer] # PHP, 210 204 bytes It's my first time posting here, so hope you guys will like it ! Even if it's obviously not the best way to write it, I'm still glad to show it off here ! ## The Code ``` <?function j($a){$c=0;if($a==1){return 1;}else{if(preg_match("#^[01]+$#",$a)){$b=strlen($a);$a=str_split($a);foreach($a as$d){$c+=($d==0?0:2**($b-1));$b--;}return j($c);}else{return$a;}}}echo j($_GET[0]); ``` I've made a recursive function "j" that will first check if the input is equal to 1. If so, the function returns 1 as expected, else it'll split the number in an array to calculate the decimal value, but only if the number is a binary one. If it's not, it'll return the number as is. ## Ungolfed code ``` <? function j($a) { $c = 0; if ($a == 1) { return 1; } else { if (preg_match("#^[01]+$#", $a) { $b = strlen($a); $a = str_split($a); foreach ($a as $d) { $c += ($d == 0 ? 0 : 2 ** ($b - 1)); $b--; } return j($c); } else { return $a; } } } echo j($_GET[0]); ``` I've used a "foreach" statement instead of my initial "for" one, allowing me a gain of 6 bytes but I'm pretty sure there's a lot more to do. [Answer] # PHP, ~~114~~ 112 bytes also works for `0`. Run with `-r`. ``` for($n=$argv[1];count_chars($s="$n",3)<2&$s>1;)for($i=$n=0;""<$c=$s[$i++];)$n+=$n+$c;echo$s; ``` `count_chars($s,3)` returns a string containing all characters from the string (like `array_unique` does for arrays). For binary numbers, this will be `0`, `1` or `01`. For other numbers, this will contain a digit larger than `1`, so `<2`will return true only for binary numbers. `&$s>1` is needed for the special case `1`. The rest is straight forward: Loop through the bits with shifting the value and adding the current bit, finally copy the number (cast to string) to $s for the outer loop test. [Answer] ## CoffeeScript, ~~92~~ 89 bytes ``` f=(x)->x>1&/^[01]+$/.test(x)&&f(''+x.split('').reverse().reduce ((p,v,i)->p+v*2**i),0)||x ``` ## JavaScript (ES6), ~~105~~ ~~101~~ 90 bytes ``` f=y=>y>1&/^[01]+$/.test(y)?f(''+[...y].reverse().reduce(((p,v,i)=>p+v*Math.pow(2,i)),0)):y ``` ## Demo Only works in ES6-compliant browsers such as Firefox and Microsoft Edge ``` f=y=>y>1&/^[01]+$/.test(y)?f(''+[...y].reverse().reduce(((p,v,i)=>p+v*Math.pow(2,i)),0)):y // Snippet stuff $(`form`).submit((e) => { document.getElementById(`y`).textContent = f(document.getElementById(`x`).value); e.preventDefault() }) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label>Input: <input pattern=^[01]+$ required id=x> </label> <button type=submit>Go</button> <p>Output: <output id=y></output> </p> </form> ``` [Answer] # Scala, 128 bytes ``` def b(s:String):String=if(s.matches("[10]{2,}"))b(""+s.reverse.zipWithIndex.collect{case('1',i)=>Math.pow(2,i)}.sum.toInt)else s ``` [Answer] ## Matlab (115) ``` @(a)num2str(sum((fliplr(a)-48).*arrayfun(@(x)2^x,0:nnz(a)-1)));a=ans(input('','s'));while(find(a<50))a=ans(a);end,a ``` --- * The anonymous function is number type conversion (`bin2dec`) ]
[Question] [ [Powerful numbers](https://en.wikipedia.org/wiki/Powerful_number) are positive integers such that, when expressed as a prime factorisation: $$a = p\_1^{e\_1} \times p\_2^{e\_2} \times p\_3^{e\_3} \cdots \times p\_k^{e\_k}$$ all exponents \$e\_1, e\_2, ...\$ are greater than or equal to \$2\$. Note that the exponents do not include zero exponents, as exampled by \$200 = 2^3 \times 3^0\times 5^2 = 2^3 \times 5^2\$ being a powerful number. This includes all perfect powers, and a few "extra" numbers that are not perfect powers. [Achilles numbers](https://en.wikipedia.org/wiki/Achilles_number) are powerful numbers that are not perfect powers. The smallest Achilles number is \$72 = 2^3 \times 3^2\$. The Achilles numbers less than or equal to \$500\$ are \$72, 108, 200, 288, 392, 432\$ and \$500\$. You are to take an Achilles number as input and output the smallest Achilles number greater than the input. You may input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ## Test Cases ``` input output 72 108 108 200 200 288 800 864 1152 1323 4500 4563 3456 3528 4563 4608 43808 43904 90828 91592 28800 29403 64800 64827 29768 30375 ``` [The program I used to generate these test cases](https://tio.run/##ASMA3P9qZWxsef//4oCYw4ZFO2cvJMSLMcSwxpHGsjEj////NTAwMA). Contains spoilers for anyone who can understand Jelly. [Answer] # [J](http://jsoftware.com/), 26 bytes ``` _(]+1-1</@(=],+./)q:)^:_>: ``` [Try it online!](https://tio.run/##dY9NS8NAEIbv8ytePLQJadL9SjJZTCgKnqSHXqXtQVrESxH8/3F2x3qourALwzwz@7zv812D5RljxHIFgyi3bvC4e36aj8W@srW9X2@Kcb@qmnX5EctDPE5xBrYPDUDFDXBcKLKZIl0ZWx1i8Sd1C9n6JSbMLsaVHf8hp/hNFgn@jaavS6LT69sF1jCcMXDM4C7AeucR2s6jjjgvJvTuh2G51rZO@sbouG8dI3QCBD@YgMG2g7uOetmju4JnQQbDjnXODcF4dIFdD298315nxEN@kUZyGvqOibaXzxOspEsuckSH8psK8aL85oJTh7WQNKS6yKkoa0uRjEjlkAOQSiIHIXXVPJSVobFI3dSdVFEjUDaFJqFy/gI "J – Try It Online") I started with the "do-until" idiom `f^:g^:_` with `g` boolean (apply `f` while `g` is true), but soon realized that the "find next integer" can be written in a single fixpoint `(]+1-g)^:_`. The only problem is that we don't have a straightforward/more golfy way to express the boolean negation of `g` other than `1-g`. ### How it works ``` _(]+1-1</@(=],+./)q:)^:_>: NB. Input: n >: NB. n+1 _( )^:_ NB. Fixpoint with left arg of _ (infinity)... q: NB. (_ q: n) gives prime exponents including zeros NB. _ q: 700 -> 2 0 2 1 (2^2 * 5^2 * 7^1) ( ],+./) NB. Append GCD of ^ to itself 1 = NB. Test if each number equals 1 (gives boolean vector) </@ NB. Test if the only 1 is the last item ]+1- NB. Negate the condition and add to the input number ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘ÆEg/ḟ$f1Ʋ1# ``` A full program which prints the next Achilles number. **[Try it online!](https://tio.run/##y0rNyan8//9Rw4zDba7p@g93zFdJMzy2yVD5////pgYGBgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9Rw4zDba7p@g93zFdJMzy2yVD5/9E9h9sfNa1xU3H//9/cSMfQwELHyMBAxwKIDQ1NjXRMTIEsYxNTMyDLzFjHxNgCqMLSwMIIqM4CpMrMBEQaWZqbWQAA "Jelly – Try It Online"). ### How? ``` ‘ÆEg/ḟ$f1Ʋ1# - Main Link: Archiles number (or any integer), n ‘ - increment (n) 1# - find the first k (starting at k=n+1) for which: Ʋ - last four links as a monad - i.e. f(k): ÆE - prime exponent vactor (e.g k=400 -> [3,0,2] since 2^3+3^0+5^2) $ - last two links as a monad: / - reduce by: g - Greatest Common Divisor -> x ḟ - filter discard (from [x] if in ÆE result) 1 - one f - filter keep (i.e. [1] if g/ was 1 and 1 not in ÆE result) (empty list is falsey, so we keep incrementing k until we get [1]) ``` [Answer] # JavaScript (ES6), ~~117 ... 99~~ 98 bytes ``` f=n=>(d=1,h=(n,x)=>++d>n?~x:1/(g=_=>q=n%d?0:g(n/=d)-1)(G=x=>q?G(q,q=x%q):x)|h(n,G(x)))(++n)?f(n):n ``` [Try it online!](https://tio.run/##Zc3BCoJAEMbxe0@xl2AGLXddtUUYPfoYEW1qEWNWxB6iV7c9ZMF2/f/4Zk67x@62vx4v9xUP9jBNLTFVYEnFPQHHDqmKIltx/XKlSqCjLVUj8dLWsuyAE7K4UggNOd/rBsZ4JLccsXT47P2BBhwiQhQx1i0wljztB74N58P6PHTQghCbFFEkiRBCSbMI1KdZUylD9emr5m9rfmqKLFCl8vmv0qkONMu/2ywvQtW@fVTnqfnbFnreFtJMbw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => ( // f is a recursive function taking n G = x => // G is a helper function computing GCD(x, q) q ? G(q, q = x % q) // (NB: actually defined in a dummy argument : x, // passed to g in the last golfed version) d = 1, // initialize the divisor d h = ( // h is a recursive function taking: n, // n = updated value x // x = GCD of the exponents (but negative) ) => // ++d > n ? // increment d; if it's greater than n: ~x // stop and yield -x - 1 : // else: 1 / (g = _ => // g is yet another recursive function q = // which computes q: n % d ? // the opposite of the number of times n can be 0 // divided by d : // g(n /= d) // we compute 1 / g() followed by a bitwise OR - 1 // to make sure that q is not equal to -1 )() | // h( // recursive call to h: n, // updated value of n G(x) // x = GCD(x, q) ) // end of recursive call )(++n) ? f(n) // if the result of h is truthy, try again : n // otherwise, return n ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes ``` ‘‘ÆE’Pȧg/Ʋ’Ɗ¿ ``` [Try it online!](https://tio.run/##y0rNyan8//9RwwwgOtzm@qhhZsCJ5en6xzYBWce6Du3/f7j9UdOayP//zY10DA0sdIwMDHQsgNjQ0NRIx8QUyDI2MTUDssyMdUyMLYAqLA0sjIDqLECqzExApJGluZkFAA "Jelly – Try It Online") Did not look at the linked Jelly answer, but that byte count does look familiar... until I remembered how I was originally checking the GCD anyhow edit: they're not even remotely alike what the hell ``` ‘ Starting at 1 more than the input, ‘ Ɗ¿ increment while: ÆE Ʋ for the exponents of the prime factorization, P the product of ’ each minus 1 ȧ logical-AND g/ their greatest common denominator ’ is not equal to 1. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~20~~ 18 bytes ``` f&!}1J/LPTPTqiFJ1h ``` [Try it online!](https://tio.run/##K6gsyfj/P01NsdbQS98nICQgpDDTzcsQKGZiamAAAA "Pyth – Try It Online") *-2 bytes thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)!* --- Explanation: ``` f hQ | first integer T starting at input + 1 such that /LPTPT | each prime factor's count in the prime factor list of T J | (this list will be called J) !}1 | does not contain 1 & | AND iFJ | the GCD of all of the elements of J q 1 | equals 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~17~~ ~~19~~ ~~18~~ 14 bytes ~~Fixed thanks to Giuseppe but had to add 2 bytes~~. As Neil and caird coinheringaahing pointed out, not only was my second condition unnecessary, my third condition was just plain wrong. Hopefully it's fixed now. ``` ḟö§¤>ε▼F⌋mLgp→ ``` [Try it online!](https://tio.run/##ASYA2f9odXNr///huJ/DtsKnwqQ@zrXilrxG4oyLbUxncOKGkv///zIwMA "Husk – Try It Online") ``` ḟö§¤>ε▼F⌋mLgp→ → Increment input ḟ Find the smallest number greater than or equal to n+1 matching this condition: p Prime factorization g Group equal adjacent elements m Map each to L its length (the powers) § Fork (apply two functions to the powers and then combine the results) ▼ First function: Minimum power F Second function: Reduce with ⌋ gcd ¤>ε Function to combine with: ¤ Apply one function to both arguments, then combine with another function ε Check if equal to 1 (1 if 1, 0 otherwise) > Ensure the minimum is not 1, but the gcd is. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes A port of [Bubbler's J answer](https://codegolf.stackexchange.com/a/219550/64121). ``` ∞+.ΔÓD¿ªΘ.«‹ ``` [Try it online!](https://tio.run/##yy9OTMpM/X9u6/9HHfO09c5NOTzZ5dD@Q6vOzdA7tPpRw87//6PNjXQUDA0sdBSMDAx0FCxAhKGhKVDQxBTENjYxNQOxzYyBpLEFSKGlgYURSL0FWLGZCZgysjQ3s4gFAA "05AB1E – Try It Online") ``` ∞ # push an infinite list of numbers [1,2,3,...] + # add the input to each number .Δ # find the first integer in this list that satisfies: Ó # the exponents of the prime factorization (including 0's) D # duplicate this list ¿ # take the gcd ª # and append it to the exponents Θ # for each value: is it equal to 1? .« # right reduce this list of 0's and 1's ‹ # with a < b, this is only 1 if the list had a single 1 at the end ``` The same length without the `.Δ` builtin: ``` [>DÓD¿ªΘ.«‹# ``` [Try it online!](https://tio.run/##yy9OTMpM/X9u6/9oO5fDk10O7T@06twMvUOrHzXsVP7/P9rcSEfB0MBCR8HIwEBHwQJEGBqaAgVNTEFsYxNTMxDbzBhIGluAFFoaWBiB1FuAFZuZgCkjS3Mzi1gA "05AB1E – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~157~~ 115 bytes ``` .+ $*11 +`^(1+)((\1(1+))(?=(\3*)\1*$)\3*(?=\4$\5))+1$|^(?!((?=(11+?)\7*$)((?=\7+$)(?=(1+)(\9+)$)\10){2,})+1$) 1$& 1 ``` [Try it online!](https://tio.run/##HYyxCsJAEET7@4vAEnZug2SicljI/cgSTGFhYyF2mm8/b61mBt6b1/39eG6tHSxJJpPdVqVB1RkJrVf1Y4YzC3rp20/iZ8Ao31XroIGQVuGlMzG9mPzNePKLoauc8VmmPTQkypjYWll@ "Retina 0.8.2 – Try It Online") No test suite because it would be too slow. Explanation: ``` .+ $*11 ``` Convert to unary and add 1. ``` +` ``` Repeat while... ``` ^(1+)((\1(1+))(?=(\3*)\1*$)\3*(?=\4$\5))+1$| ``` ... the current value is a perfect power, or... ``` ^(?!((?=(11+?)\7*$)((?=\7+$)(?=(1+)(\9+)$)\10){2,})+1$) ``` ... the current value is not powerful... ``` 1$& ``` ... increment the value. ``` 1 ``` Convert to decimal. I'm currently testing whether a number is powerful based on taken from my answer to [Is it almost-prime?](https://codegolf.stackexchange.com/questions/210162/) except here I divide at least twice by each (prime) factor and then repeat until all factors have been consumed. In theory it should be possible to take any factors and divide at least twice by each, but for some reason I don't seem to be able to adapt the expression for perfect powers to match a product of perfect powers. [Answer] # Java, ~~194~~ ~~167~~ ~~160~~ 152 bytes *Saved 7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904)* *Saved 8 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792)* ``` int a(int n){return p(++n)!=1?a(n):n;}int p(int n){for(int i=1,o=n,c,z;++i<o;){for(c=z=1;n%i<1;c++)n/=i;while(z<o)z*=i;if(c==2|z==o)return 0;}return n;} ``` [Try it online!](https://tio.run/##hY1NTsMwEIX3nGJYVLJxCDgSQqoz4gSsukQsjJsWl2Qc2U4rUnL24KQpW2YxP@99o3fQR31/2H6NbfdRWwOm1iHAq7YE5xtItegh6pjG0dktNMllm@gt7d/eQft94Bd2qvm1AQSqTvPBuPozN98hVk3uupi36T3WxJpcs@eC/w/J4ulKDWOSQbOpEz/7KnaeoGVCEL9F@aIZ8TWpYfLbK7Vzfl4tyswhZSbrlRC2dOriGexRKlrZUiojBKcHtOr0aeuK9aXj/V067S5hWPz0iI4vsY9qWLaUOA7jLw) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~17~~ 16 bytes ``` <.ḋḅ{{Ṁlf⊇}ᵛ!}Ȯ∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w30bv4Y7uhztaq6sf7mzISXvU1Q4Unq1Ye2Ldo47l//9HmxvpGBpY6BgZGOhYALGhoamRjokpkGVsYmoGZJkZ65gYWwBVWBpYGAHVWYBUmZmASCNLczOLWAA "Brachylog – Try It Online") Looked like it might compete with Jelly until I realized where I'd have to put that cut! Trying to see if maybe I could do not-a-perfect-power checking without going through the factors of the prime exponents. ``` . The output < is a number strictly greater than the input ḅ of which the runs of ḋ the prime factors { }ᵛ each Ṁ contain at least two elements, f and the factors of l the lengths of which { ⊇ ᵛ!} have a largest common subset ∧ (not necessarily equal to the output) Ȯ which contains only one element. ``` [Answer] # [Japt](https://ethproductions.github.io/japt/), 24 bytes Definitely struggled to cut this short since some of the operations are bulky by themselves, for example getting the exponents. ``` _=k ü mÊ;Zry ¶1©Ze¨2}aUÄ UÄ // Starting at input plus one, a // find the next integer that returns true when _ } // run through the function: = // Z = k // prime factors ü // grouped by value mÊ // and mapped to length, e.g. the exponents of prime factors. ; // Return whether Zry ¶1 // GCD of Z equals 1 © // and Ze¨2 // every member of Z is geq 2. ``` [Try it out here.](https://ethproductions.github.io/japt/?v=1.4.6&code=Xz1rIPwgbco7WnJ5ILYxqVplqDJ9YVXE&input=LVEKMjg4) ]
[Question] [ Given a list of `N` integers, each with `N` digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc. ### Example Given this list: ``` 1234 4815 1623 4211 ``` The number `2932`'s first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output. ### Inputs * You may take both the list and `N` as input, or only the list if you wish. * Each integer in the list will necessarily have as many digits as the length of the list (`N`) * Numbers will not have any leading zeroes * The input list must contain numbers and not strings. * You may take inputs as function arguments, through `STDIN`, or anything similar. * You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than `2147483647`) ### Outputs * It is not sufficient that the output is not in the list. The digits must differ as explained above. * You can use any digit selection strategy that respects the constraint of different digits. * The number cannot have leading zeroes * You may output the number through `STDOUT`, return it from a function, etc. ### Test cases ``` Input: 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345 Possible output: 24680246 Input: 1 Possible output: 2 ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] ## CJam (15 14 bytes) ``` qN/ee{:=i2%)}% ``` [Online demo](http://cjam.aditsu.net/#code=qN%2Fee%7B%3A%3Di2%25)%7D%25&input=12345678%0A23456789%0A34567890%0A45678901%0A56789012%0A67890123%0A78901234%0A89012346) Thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) for a one-byte saving. ### Dissection ``` qN/ e# Split input on newlines ee{ e# Label each line with its index and map: :=i e# Get the character at the same index (i.e. diagonalise) 2%) e# Compute (ASCII value mod 2) + 1 e# Maps 0 1 2 3 4 5 6 7 8 9 e# to 1 2 1 2 1 2 1 2 1 2 }% ``` [Answer] # Python 2, ~~47~~ 45 bytes ``` lambda x,n:int(`x`[1::n+3])%(10**n/2)+10**n/9 ``` *Thanks to @xnor for golfing off 2 bytes!* Test it on [Ideone](http://ideone.com/B7wAft). ### How it works ``x`` yields a string representation of the list **x**. For the first test case, this gives the *string* ``` [92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345] ``` `[1::n+3]` retrieves every **(n + 3)**th character – where **n** is the length of **x** starting with the second one. Accounting **2** characters for `,`, we retrieve the first digit of the first number, the second digit of the second number, etc. ``` [92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345] ^ ^ ^ ^ ^ ^ ^ ^ ``` We now take the number modulo **10n ÷ 2** to map the first digit in the range **[0, 4]**. For **93579135**, we get **93579135 % 50000000 = 43579135**. Finally, we add **10n ÷ 9** to the last result, which increments – wrapping around from **9** to **0** – all digits by **1** (no carry) or **2** (with carry). For **43579135**, we get **43579135 + 11111111 = 54690246**. [Answer] # Jelly, ~~8~~ 7 bytes 1 byte saved thanks to Dennis. ``` DŒDḢỊ‘Ḍ ``` [Try it online!](http://jelly.tryitonline.net/#code=RMWSROG4ouG7iuKAmOG4jA&input=&args=OTIzNDU2NzgsMjM0NTY3ODksMzQ1Njc4OTAsNDU2Nzg5MDEsNTY3ODkwMTIsNjc4OTAxMjMsNzg5MDEyMzQsODkwMTIzNDU) ### Explanation ``` DŒDḢỊ‘Ḍ Main link. Takes list as argument. D Convert each integer to decimal. ŒD Get the diagonals. Ḣ Get the first diagonal. Ị Check if every digit <= 1. ‘ Increment every digit. Ḍ Convert back to integer from decimal. ``` Converts each digit to `1`, except `0` and `1` becomes `2`. [Answer] # MATL, ~~11~~ ~~10~~ 9 bytes ``` VXd9\QV!U ``` Takes only a column vector of integers as input. `N` is not provided. [**Try it Online**](http://matl.tryitonline.net/#code=VlhkOVxRViFV&input=WzIyMzQ1Njc4OzIzNDU2Nzg5OzM0NTY3ODkwOzQ1Njc4OTAxOzU2Nzg5MDEyOzY3ODkwMTIzOzc4OTAxMjM0Ozg5MDEyMzQ1XQ) **Explanation** ``` % Implicity grab input as column vector of numbers V % Convert the input column vector into a 2D character array Xd % Grab the diagonal elements of the character array 9\ % Take the modulus of each ASCII code and 9 Q % Add 1 to remove all zeros V % Convert the result to a string ! % Transpose to yield a row vector of characters U % Convert back to an integer (as per the rules) % Implicitly display result ``` [Answer] # Pyth, 11 bytes ``` jk.eh!ts@`b ``` Simple loop, change every digit to 1, except 1 becomes 2. [Answer] # Java, 93 bytes ``` String k(int n,int[]a){String s="";for(int i=0;i<n;)s+=(a[i]+s).charAt(i++)<57?9:1;return s;} ``` ### Ungolfed ``` String k(int n, int[] a) { String s = ""; for (int i = 0; i < n; ) s += (a[i] + s).charAt(i++) < 57 ? 9 : 1; return s; } ``` ### Output ``` Input: 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345 Output: 99991999 Input: 1234 4815 1623 4211 Output: 9999 ``` [Answer] # Retina, ~~39~~ ~~38~~ 37 ``` (?<=(.*¶)*)(?<-1>.)*(.).*¶ $2 T`d`121 ``` Saved 1 byte thanks Martin! Requires a trailing linefeed in the input. Gets diagonals and translates 0 and 2-9 to 1 and 1 to 2. The basic idea for getting the diagonals is to push a capture for each row above the current row and then consume a capture to match a character, then keep the next character. [Try it online](http://retina.tryitonline.net/#code=KD88PSguKsK2KSopKD88LTE-LikqKC4pLirCtgokMgpUYGRgMTIx&input=MTIzNAo0ODE1CjE2MjMKNDIxMAo) [Answer] # J, ~~26~~ 22 bytes ``` 1+1>:i.@#{"_1"."0@":"0 ``` Similar approach to the others using the `<= 1` and `increment` method of the diagonal. ## Usage Only requires the list of integers as an argument. ``` f =: 1+1>:i.@#{"_1"."0@":"0 f 1234 4815 1623 4211 2 1 1 2 f 92345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345 1 1 1 1 1 2 1 1 ``` [Answer] # Python 2, 54 bytes ``` d,r=1,"" for n in input():r+=`1+-~n/d%9`;d*=10 print r ``` [Answer] # Java, 94 bytes ``` int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;} ``` Pure numeric operations for the win! :) ### Sample input/output: ``` 8 <-- size 12345678 <-- start of list 23456789 34567890 45678901 56789012 67890123 78901234 89012345 <-- end of list 21111211 <-- result from ungolfed code 21111211 <-- result from golfed code ``` ### Full program (with ungolfed code): ``` import java.util.Scanner; public class Q79444 { int cantor_ungolfed(int[] data){ int power = 1; int result = 0; for(int i=0;i<data.length;i++){ result += (((data[data.length-i-1]/power))%10==1? 2 : 1)*power; power *= 10; } return result; } int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;} public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] input = new int[n]; for(int i=0;i<n;i++){ input[i] = sc.nextInt(); } System.out.println(new Q79444().cantor_ungolfed(input)); System.out.println(new Q79444().c(input)); sc.close(); } } ``` [Answer] # Reng v.3.3, 60 bytes ``` k1-#kaiír1ø ~; !nb$< 1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$ ``` For Reng, that was rather simple. [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) Input is a space-separated list of numbers. ## 1: init ``` k1-#kaiír1ø ``` `k` is the number of inputs (number of numbers), and we decrement by 1 and restore for the loop stage. `aií` takes all input. `r` reverses the stack for the processing of input. `1ø` goes to the next line. ## 2: loop ``` 1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$ ``` `1[` takes the top item off the stack and into a new stack. `å` splits it into digits. `{$}` pushes a code block containing the operation "drop"; this is repeated `k` times (`k*`) and the code block is dropped (`$`. `k1-#k` decrements `k`. `)9(` puts `9` at the STOS, and `-` subtracts TOS from the STOS. `#o` stores this number in `o`, and `a$;` drops all the members of the stack. `]` closes the parent stack. `o` puts `o` back at the top; this is our digit we're saving. `)` moves it to the bottom so that we can continue our looping. `s` usually checks for non-input (i.e., equality to `-1`), but we can use it to break out of our loop when `k == -1`. So `s^` goes up when `k == -1`. `$` drops `k` from the stack, and our loop begins again. ## 3: final ``` ~; !nb$< ``` `<` directs the pointer left, and `$` drops `k` from the stack. `b` is a leftway mirror, so we enter through it, but it bounce back when hitting `;`, a stack-condition mirror. `!n` prints a digit if and only if we're going left. `~` ends the program when we're done printing. [Answer] # Ruby, 21 bytes ``` $><<$_[$.-1].hex%2+1 ``` A full program. Run with the `-n` flag. Uses the following mapping: `n -> n%2+1`. [Answer] # Perl, 18 bytes Includes +1 for `-p` Run with the input lines on STDIN. Output is 1 except 2 when the diagonal is 1 `cantor.pl` ``` #!/usr/bin/perl -p pos=$.;$_=/1\G/+1 ``` [Answer] # Pyth, 14 bytes ``` s.e|-\1@bk\2`M ``` [Try it online!](http://pyth.herokuapp.com/?code=s.e|-%5C1%40bk%5C2%60M&input=12345678%2C23456789%2C34567890%2C45678901%2C56789012%2C67890123%2C78901234%2C89012345&debug=0) [Answer] # J, 37 bytes ``` f@(9&-@"."0@((>:@#*i.@#){f=:[:,":"0)) ``` Can probably be golfed, but I forgot if there was a command for "diagonals". [Answer] # Mathematica 52 bytes ``` FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@#]]& ``` This follows the approach of Peter Taylor and others (without using Ascii codes). Example ``` FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@ #]]&[{1234,4815,1623,4211}] ``` > > 2112 > > > [Answer] # ClojureScript, 58 chars ``` #(int(apply str(map-indexed(fn[i x](- 9(get(str x)i)))%))) ``` Type requirements made this a little longer than necessary, and `map-indexed` being so many chars didn't help. Often my submissions are valid Clojure as well, but this is using some of ClojureScript's leakiness with JavaScript. Subtraction of a number and string coerces the string to a number--that is, `(- 9 "5")` equals `4`. [Answer] **PHP, 46/41/40 bytes** ``` while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1; while($a=$argv[++$i])echo$a[$i-1]==7?6:7; while($a=$argv[++$i])echo($a[$i-1]%2)+1; ``` Various digit selectors for comparison. I thought "9-digit" would be shortest, but the special case needed to keep a zero out of the first digit overwhelms it. Fed from CLI arguments: ``` php -r "while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;" 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345 86421864 ``` [Answer] # JavaScript (ES6), 41 The %9+1 trick is borrowed from Suever's answer. For once, `.reduce` beats `.map`. Note, the `+=` operator is used to avoid parentheses. ``` a=>+a.reduce((t,n,d)=>t+=(n+t)[d]%9+1,'') ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 49 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.125 bytes ``` vfÞ/ċ›ṅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJhPSIsIiIsInZmw54vxIvigLrhuYUiLCIiLCIxMjM0XG40ODE1XG4xNjIzXG40MjExIl0=) Port of Jelly ]
[Question] [ [Picolisp](https://picolisp.com) has a feature called "super parentheses": > > Brackets ('[' and ']') can be used as super parentheses. A closing bracket will match [all parentheses to and including] the innermost opening bracket, or [if there are no unmatched opening brackets] all currently open parentheses. [src](http://www.software-lab.de/doc/ref.html) > > > Taking a string containing only the characters `[]()` (and newline if your language requires it), remove all closing brackets `[]` and replace them with the corresponding parentheses. A `[` is replaced with a `(`, but your program will not have to handle a `[` or `(` without a matching `]` or `)`. Output may contain trailing newlines. `]` matches as many open parens as possible until it hits a `[` at which point it has to stop [--DJMcMayhem](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/22421#comment74153_22421) ## Examples ``` ((((] -> (((()))) (([()(()])) -> (((()(())))) ) or ( or ] or [) or ([(] -> invalid, do not need to handle (] -> () ((](] -> (())() [] -> () [(] -> (()) [[()(]] -> ((()())) ((][(] -> (())(()) (([((](] -> ((((()))())) ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code per language wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` FS≡ι)⊟υ]W∧υ⊟υκ«(F⁼ι[⊞υω⊞υ) ``` [Try it online!](https://tio.run/##NY6xDoMwEENn@IpTJkeCH6BThw7dkDoihihAEzUCSpIyVHx7erR0tP3OZ23UoiflUhqmhXAd5xhuYbHjHVKSX23QhmAlvXOtfE9CiopqzgPqaUaU8nQELQersa4nnMcOsaADkAf/YLTrBxVdqLgu@7kCgv3s@/3yjMp52IJEI/a76M1etO7EX/ACllu@pQQ0QIs2lS/3AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS≡ι ``` Switch over each character of the input. ``` )⊟υ ``` If it's a `)` then pop and print the top of the stack (which should always be a `)` at this point). ``` ]W∧υ⊟υκ ``` If it's a `]` then pop and print the top of the stack until it becomes empty or an empty string was popped. ``` «(F⁼ι[⊞υω⊞υ) ``` Otherwise, print a `(`, push an empty string to the stack if it was a `[`, and push a `)` to the stack. [Answer] # [Python 3](https://docs.python.org/3/), ~~117~~ 115 bytes -2 thanks to [ovs](https://codegolf.stackexchange.com/users/64121) (use mod 8 in place of mod 6 allowing the bitwise-OR in place of exponentiation; remove a space from `5!=x or` with `x!=5or`.) My golf of [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)'s [Python 3 answer](https://codegolf.stackexchange.com/a/229189/53748). ``` k=[0] o="" for c in input():x=ord(c)%8;o+="() ( )"[x]*(x<5or k.pop());k=[0]+k+[1]*(x==3);k[-1]+=x<3and-x|1 print(o) ``` **[Try it online!](https://tio.run/##LU7RCsIwDHzvV5SBLLFMLEOQbf2S2gfpKhuTtoyJFfz3mg6PIyF3R5L42abg22zD6LjidV3f8qL02bCgqoo9wsotnz0xvjbALqmwjmDxcO2DUBUgB46VTuYIabhQejnFEAGx37eIRWhZPKVaknQjjVBpaO9@bNJXsrjOfoOAmQ7rjlzG3tP8dFx2jBNcchbKb5iBYBiABgRAg8j20VDVxNKKZXZR/6PF/gE "Python 3 – Try It Online")** Remaps `'(', ')', '[', ']'` to the integers `0, 1, 3, 5` (`x`) with `x=ord(c)%8` then uses this for the decision making process to save quotes. Inlines all the decision-making to avoid newlines, tabs and `if-elif-else` syntax. Gets the character to output for the current input character by using `x` to index into `"() ( )"`. When the current character is one of `"()"` we need to add or subtract one, respectively, from the last entry in the counts list, `k`. To do so we check if the character is one of `"()"` we use `x<3` (`False`, the value for `'['` and `']'` is equivalent to `0`) and logical-AND that with `-x` bitwise-OR with `1` (`-x|1`) translating the `0` of `(` to `1` and the `1` if `)` to `-1`. Thus we can add `x<3and-x|1`. [Answer] # [PicoLisp](http://picolisp.com/), 211 bytes ``` (de f(x k)[or k(set'k(0][set'a(car x][set'b(cdr x](if x(cond[(="("a)(prin a)(f b(cons(+(car k)1)(cdr k][(=")"a)(prin a)(f b(cons(-(car k)1)(cdr k][(="["a)(prin"(")(f b(cons 1 k](1[prin(need(car k)")"](f b(cdr k] ``` [Try it online!](https://tio.run/##bYxBDsIgFET3nuKHjfNjTOQAnoSwoEAjwRRSXODpEVqNm65mJvNmcrDpGUpuDc7TjEqRVVopovjXOeKm1TAG1qxU9zDBuhEQZqqwaXEKdwFhGHkNC3WdaRpFwWUbRpa8jaIeKB@i1yNU/dD@/2dJ9hpSjQKL9@477c96h7aD1j3sI2USgAI0tGA@YXp7bh8 "PicoLisp – Try It Online") -1 byte thanks to Wzl First time using picolisp, so it's probably very badly golfed. [Answer] # [Python 3](https://docs.python.org/3/), 139 bytes ``` o="" k=[0] for c in input(): if"["<c:o+=")"*k.pop();k=[0]+k elif"Z"<c:k+=[1];o+="(" elif")">c:k[-1]+=1;o+=c else:k[-1]-=1;o+=c print(o) ``` [Try it online!](https://tio.run/##NcrLCsMgEIXhdXyKMKuZSkqlu6T2QSKuJKFicSSxiz690V7grM7/pXd@cLyWwhpABG0uVqy89a73sS69MtIoOr@CgZsbWWogOIVz4oQ0fbwMolueVcxNBKmNslODCL9AcK/BDMpKrVpyLezL9xv@X9p8zMhUCqJFOgA "Python 3 – Try It Online") -4 bytes thanks to caird coinheringaahing bugfix thanks to Jonathan Allan trivial attempt, will try to golf it down more later [Answer] # JavaScript (ES6), ~~96~~ 94 bytes Expects an array of characters. Returns a string. ``` a=>a.map(c=>c>{}?')'.repeat(b.pop()):b.push(-~(c>')'?c='(':b.pop()-2*(c>'(')))&&c,b=[]).join`` ``` [Try it online!](https://tio.run/##ZZBBTsMwEEX3OcUoi3oGJV6wDHKy4hSWpbrGoa1KbMVthYTgBEhsWMI9OE8vwBGCQ4iaUC8s6//3Pd/e6qMOpt34fd64O9vVotOi1PxBezSiNOXTc8WI8dZ6q/e44t55JCri4RDWmL@gKaNfGcGQFX92fn3Vy8iIaLEw2UpIRXzrNs1y2d3IBEBCinGpNBsOEaQUVDZaEimKKoojMDBTaAjPYmq8kWhqyAtUnsGJ2E9VYyfCf53UJDQP9n3Ps4fnXKSRZtUSlfDatbfarGM8ZGAfvSIQJRjXBLezfOfusbUBBNQoOedBUQa/guhhqIB9f72dPt7jzqAAdvp8jT/e/QA "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input a.map(c => // for each character c in a[]: c > {} ? // if c is ']': ')' // use ')' .repeat( // and repeat it as many times as b.pop() // recorded in the last slot, ) // which is removed from b[] : // else: b.push( // push in b[]: -~( // c > ')' ? // if c is '[': c = '(' // update c to '(' and push 1 (a new slot) : // else b.pop() // update the last slot (it may be undefined): - 2 * // increment it if c is '(' (c > '(') // decrement it if c is ')' ) // ) // end of push() && c, // yield c b = [] // start with b[] = empty array ).join`` // end of map(); join everything ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 49 bytes ``` +`(^|\[)(((\()|(?<-4>\)))*)] $.1$*($2$#4$*)$.1$*) ``` [Try it online!](https://tio.run/##LUs7CoAwFNt7DZ@QVBQUR9HRQ7RP6uDg4iCO3r22RQgJ@d3Hc157rLGG2ARsr3cE4MEXy9SOsydpqUa6XixkkGoUy@IYY5pCDeCQXlTSFKuJXUKWXGkJ3T/N9Qc "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` +` ``` Repeat until no more replacements can be made. ``` (^|\[)(((\()|(?<-4>\)))*)] ``` Starting at the beginning of the string or at a `[`, start counting `(`s, but subtract 1 for every `)`, until a `]` is reached. ``` $.1$*($2$#4$*)$.1$*) ``` Append `)`s according to the count of remaining `(`s, and if we started at a `[` then wrap the whole thing in `)`s (because the count of `(`s doesn't include the initial `[`). [Answer] # JavaScript (ES6), 96 bytes ``` f=s=>s>(s=s.replace(/.([()]*)]/,(_,m)=>'('+m+')'.repeat(3+m.length-2*m.split`)`.length)))?f(s):s ``` [Try it online!](https://tio.run/##TY/BbsMgEETv/gpu7MQ2kdpbI9xTv8JBNXJx4gqMZaxeon67C6FuijjszrydhU/9pUO/jPNaT/7DbIOMN8gmNBRkEIuZre4NHQW1BHWAOlb0XjnIhhMvXcnBE2T0Ss@lE9ZMl/VaPx2cCLMd1w7drwbgdaCAl7CdWFdQPIrVDUtF9BCVuCHWCvjTsxW9jCZI7WNA7NvdaB9y0aYgtaeDcrr6h9yxtPARl59xZzuxLqMj5C8QP08cwumZLJMNs7uc5jggBr@86f4a48aKGYUE3QrGej8Fb42w/kIDjVGXzFQslSi@cdp@AA "JavaScript (Node.js) – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 46 bytes ``` L#aaR:`((\[|^)[()]*)]`{b.')X#b-2*(')Nb)R'['(}a ``` [Try it online!](https://tio.run/##K8gs@P/fRzkxMcgqQUMjJromTjNaQzNWSzM2oTpJT10zQjlJ10hLQ13TL0kzSD1aXaM28f///xoa0RoasRqxAA "Pip – Try It Online") Algorithm: * Find the first pair of square brackets with only parentheses between them (the opening bracket is optional if we're at the beginning of the string) using regex. * Call the regex match minus the final bracket `b`. Replace the match (including the bracket) with: + `b`, + concatenated to a number of `)` equal to the length of `b` minus two times the number of closing parens in `b`, + with `[` replaced with `(` * Do that as many times as there are characters in the input (overkill, but gets the job done). * Print the result. --- Different algorithm, **also 46 bytes**: ``` Fca{l|:^0cLT0?@l+:v**A OccQ'[?lPU1&O'(O')XPOl} ``` [Try it online!](https://tio.run/##K8gs@P/fLTmxOqfGKs4g2SfEwN4hR9uqTEvLUcE/OTlQPdo@JyDUUM1fXcNfXTMiwD@n9v///xoa0RoasRqxAA "Pip – Try It Online") Treating the list `l` as a stack, loop over each character in the input: * If the stack is empty, put a 0 on it. * If the character is a parenthesis, output it and increment/decrement the top of stack. * If the character is an open square bracket, push a 1 to the stack and output an open parenthesis. * If the character is a close bracket, pop the stack and output that many close parentheses. [Answer] # [Red](http://www.red-lang.org), ~~131~~ 119 bytes -12 bytes thanks to @9214 ``` func[a][do{s:[""""]}parse a[any["("(insert s/1")")|")"(take s/1)| change"[""("(insert s copy")")| change"]"(take s)]]a] ``` [Try it online!](https://tio.run/##TU07DsIwDN17CstTMiDE2oFDsFoerDahFSKNkiJRUc4e0i/1YD@9j18wdbqZmriwJST7chUJU919YkmYh79eQjQgJG4gVKhaF03oIZ4vqFGPealeHmYi9FhUjbi7wZw9WKHq/DC7YdV5C2lm4WS7YKRqwLx9ACoAAFUexhWS0kpp1noldoE3SNvdiSnDfyMdvy05Jh9a11Nufy7VeLoi2Bkzpx8 "Red – Try It Online") [Answer] # Ruby 3.0.1, ~~123~~ ~~93~~ 92 bytes Expects an array of characters and returns an array of characters ``` ->x{*a=0 x.map{|c|c<?*?a[-1]+=(c<?)?1:-1):c<?]?(a<<0;c=?():c=?)*a.pop+(a[0]??):c*(*a=0));c}} ``` Old explanation: ``` -> x { a=[0] # this is the "stack" x.map do |c| # for each character `c` in input case c when ?( # ? creates a one-character string. Shorter than '(' a[-1] += 1 # increment the top of the stack when ?) a[-1] -= 1 # decrement the top of the stack when ?[ a << 0 # push a new element, 0, onto the stack c = ?( # 'output' an open paren in place of this character when ?] c = ?) * a.pop + # remove the last element of the array, and print that many closing parens. # however, we need to print another closing paren iff the stack isn't empty after we popped it. ( a[0] ? # ternary. a[0] is nil(falsy) if the array is empty, but 0 is truthy ?) : # if the array isn't empty, add another close parent # if the array is empty, we need to add nothing, but also add a 0 onto the array. # `a<<0` is shorter, but evaluates to the array `a`. # `a[0]=0` evaluates to 0. # any string * 0 is the empty string, so we use `c` since it's shorter than `""` c*(a[0]=0) ) end c #last value evaluated is implicitly returned } } ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `ṠJs`, 32 bytes ``` 0⅛ƛk(nc[k)k-ĿI¼+⅛|\[=[1⅛\(|\)¼⌊* ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=%E1%B9%A0Js&code=0%E2%85%9B%C6%9Bk%28nc%5Bk%29k-%C4%BFI%C2%BC%2B%E2%85%9B%7C%5C%5B%3D%5B1%E2%85%9B%5C%28%7C%5C%29%C2%BC%E2%8C%8A*&inputs=%5B%5D&header=&footer=) ([Try all testcases!](http://lyxal.pythonanywhere.com?flags=&code=0%E2%85%9B%C6%9Bk%28nc%5Bk%29k-%C4%BFI%C2%BC%2B%E2%85%9B%7C%5C%5B%3D%5B1%E2%85%9B%5C%28%7C%5C%29%C2%BC%E2%8C%8A*&inputs=%28%5D%20-%3E%20%28%29%0A%5B%5D%20-%3E%20%28%29%0A%5B%28%5D%20-%3E%20%28%28%29%29%0A%28%28%5D%28%5D%20-%3E%20%28%28%29%29%28%29%0A%28%28%28%28%5D%20-%3E%20%28%28%28%28%29%29%29%29%0A%28%28%5D%5B%28%5D%20-%3E%20%28%28%29%29%28%28%29%29%0A%5B%5B%28%29%28%5D%5D%20-%3E%20%28%28%28%29%28%29%29%29%0A%28%28%5B%28%28%5D%28%5D%20-%3E%20%28%28%28%28%28%29%29%29%28%29%29%29%0A%28%28%5B%28%29%28%28%29%5D%29%29%20-%3E%20%28%28%28%28%29%28%28%29%29%29%29%29&header=%40f%3A1%7C&footer=%5D%5D%3B%E2%81%8B%3B%0A%E2%96%A1%C6%9B%60%20-%3E%20%60%E2%82%AC%3Ah%3A%60%3A%5Ct%60%2B%E2%82%B4%40f%3B%C8%A7%E2%82%B4%60%20%3D%20%60%E2%82%B4t%2C)) ``` 0⅛ƛk(nc[k)k-ĿI¼+⅛|\[=[1⅛\(|\)¼⌊* 0⅛ Set the global array to [0] ƛ For each char n in input: [ | If... k(nc n is in "()": Ŀ Transliterate... k) n's index in ")("... k- into [-1, 1] I Cast to integer ¼+⅛ Add to top of global stack | Otherwise... [ | If... \[= n is '[': 1⅛ Push 1 to the global array \( Push "(" for output | Otherwise: * Repeat... \) the string ")"... ¼⌊ pop(global_array) times ``` * `Ṡ` - treat `[]` as the string ``[]``, not an empty array * `Js` - output properly ]
[Question] [ Inspired by and drawns from [Is this number Loeschian?](https://codegolf.stackexchange.com/q/88732/85527) > > A positive integer \$k\$ is a **Loeschian number** if > > > * \$k\$ can be expressed as \$i^2 + j^2 + i\times j\$ for \$i\$, \$j\$ integers. > > > For example, the first positive Loeschian numbers are: \$1\$ (\$i=1, j=0\$); \$3\$ (\$i=j=1\$); \$4\$ (\$i=2, j=0\$); \$7\$ (\$i=2, j=1\$); \$9\$ (\$i=-3, j=3\$)1; ... Note that \$i, j\$ for a given \$k\$ are not unique. For example, \$9\$ can also be generated with \$i=3, j=0\$. > > > Other equivalent characterizations of these numbers are: > > > * \$k\$ can be expressed as \$i^2 + j^2 + i\times j\$ for \$i, j\$ non-negative integers. (For each pair of integers \$i, j\$ there's a pair of non-negative integers that gives the same \$k\$) > * There is a set of \$k\$ contiguous hexagons that forms a tesselation on a hexagonal grid (see illustrations for [\$k = 4\$](https://i.stack.imgur.com/keJqMl.png) and for [\$k = 7\$](https://i.stack.imgur.com/Dj0lKl.png)). (Because of this property, these numbers find application in [mobile cellular communication networks](http://www.wirelesscommunication.nl/reference/chaptr04/cellplan/reuse.htm).) > * See more characterizations in the [OEIS page](https://oeis.org/A003136) of the sequence. > > > The first few Loeschian numbers are ``` 0, 1, 3, 4, 7, 9, 12, 13, 16, 19, 21, 25, 27, 28, 31, 36, 37, 39, 43, 48, 49, 52, 57, 61, 63, 64, 67, 73, 75, 76, 79, 81, 84, 91, 93, 97, 100, 103, 108, 109, 111, 112, 117, 121, 124, 127, 129, 133, 139, 144, 147, 148, 151, 156, 157, 163, 169, 171, 172, 175, 181, 183, 189, 192... ``` 1while (\$i=-3, j=3\$) produces 9, stick to non-negative integers, so (\$i=0, j=3\$). Loeschian numbers also appear in [determining if a coincident point in a pair of rotated hexagonal lattices is closest to the origin?](https://math.stackexchange.com/q/3705547/284619) ## The challenge Given a **non-negative integer** \$k\$, output all pairs of non-negative integers \$i, j\$ such that \$i^2 + j^2 + i\times j=k\$. If none are found (i.e. \$k\$ is not Loeschian) then return nothing or some suitable flag *other than* \$(0, 0)\$ since that produces the first Loeschian number, \$0\$. For reversed order pairs like \$(0, 4)\$ and \$(4, 0)\$ either include both, or one member of the pair, but it should be the same for all cases (i.e. not sometimes one and other times both). The program or function should handle (say in less than a minute) inputs up to \$100,000\$, or up to data type limitations. This is code golf so shortest code wins. ## Test cases ``` in out 0 (0, 0) 1 (0, 1), (1, 0) 3 (1, 1) 4 (0, 2), (2, 0) 9 (0, 3), (3, 0) 12 (2, 2) 16 (0, 4), (4, 0) 27 (3, 3) 49 (0, 7), (3, 5), (5, 3), (7, 0) 147 (2, 11), (7, 7), (11, 2) 169 (0, 13), (7, 8), (8, 7), (13, 0) 196 (0, 14), (6, 10), (10, 6), (14, 0) 361 (0, 19), (5, 16), (16, 5), (19, 0) 507 (1, 22), (13, 13), (22, 1) 2028 (2, 44), (26, 26), (44, 2) 8281 (0, 91), (11, 85), (19, 80), (39, 65), (49, 56), (56, 49), (65, 39), (80, 19), (85, 11), (91, 0) 12103 (2, 109), (21, 98), (27, 94), (34, 89), (49, 77), (61, 66), (66, 61), (77, 49), (89, 34), (94, 27), (98, 21), (109, 2) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 9 bytes *Thanks to @ovs for -2!* ``` ÝãʒãÀ¦POQ ``` Oh my, I am getting in the hang of code golfing! Prints a list of all the valid pairs (e.g `[[1, 0], [0, 1]]`). If there are none, the list is empty (`[]`). Also outputs both of any reverse integer pairs. [Try it online!](https://tio.run/##ARoA5f9vc2FiaWX//8Odw6PKksOjw4DCplBPUf//OQ) ## How? You may count this as a port of the other answers, but I took a look only at the Husk answer before writing the program! ``` Ý # Push a list of all numbers from 0 to the input. ã # Push the cartesian power of lists. (Basically, finding all possible pairs) ʒ # For each pair... ãÀ¦ # Find all other permutations of the pair. P # Multiply each permutation. O # Add the products. Q # If the result is not equal to the input, yeet (throw) them from the list. # Automatically print the pairs not yeeted. ``` [Answer] # [Haskell](https://www.haskell.org/), 46 bytes ``` f x|l<-[0..x]=[(i,j)|i<-l,j<-l,i*i+j*j+i*j==x] ``` [Try it online!](https://tio.run/##JY2xDoIwFEV/5cU4AH2QtmiBhPoFOjk2jWHQ0FqQCMYO/HutYTn35iyn7@bn3bkQHuBX1@aKFoXXUiUGbbqaNndo/zCZITazxGRWSq/D0JkRJAzddLnB9Fmuy/s8gkrm/vUFnwIhsAN5iohvs3uIjXT1W4RxTYhiAnmFhwbZoUIm4jYCS8HwSCvklNdY85oh44yWWocf "Haskell – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 13 bytes ``` fo=¹§+Πṁ□π2…0 ``` [Try it online!](https://tio.run/##ASMA3P9odXNr//9mbz3CucKnK86g4bmB4pahz4Ay4oCmMP///zE5Ng "Husk – Try It Online") -2 bytes from Zgarb. Outputs `[]` for non-Loeschians. ## Explanation ``` fo=¹§+Πṁ□π2…0 …0 range from 0..n π2 create all possible pairs using 0..n fo filter by the following two functions: § f: fork: § f g h x = f (g x) (h x) + add ṁ□ sum of squares Π and fold by multiplication =¹ g: is that equal to 1? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ 9 bytes ``` Żp`ḋÄ$=¥Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8///o7oKEhzu6D7eo2B5aeqz9/@H2R01rjk56uHPG//8GOgqGOgpGOgrGOgomOgqmQNISAA "Jelly – Try It Online") Outputs `[]` for non-Loeschian numbers -1 byte [thanks to](https://codegolf.stackexchange.com/questions/212300/find-all-integer-pairs-that-produce-a-given-loeschian-number/212310?noredirect=1#comment500552_212310) [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus) Not particularly efficient, but that can be fixed for an additional [2 bytes](https://tio.run/##ASIA3f9qZWxsef//w4bCvcW7cGDCslMrUMayPcKlxof///84Mjgx). Uses the fact that a Loeschian number can be expressed as \$i\times i + j\times(i+j)\$ by using Jelly’s vectorisation and cumulative sum. ## How it works ``` Żp`ḋÄ$=¥Ƈ - Main link. Takes n on the left Ż - Yield [0, 1, ..., n] p` - Cartesian product with itself, yielding [[0, 0], [0, 1], ..., [n, n]] ¥Ƈ - Filter the pairs, keeping those where the following is true: $= - The pair equals n after the following is done: Ä - Cumulative sum. Yield [i, i+j] ḋ - Dot product with [i, j]; Yields i×i + j×(i+j) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` Solve[i^2+j^2+i*j==#&&i>=j>=0,{i,j},Integers]& ``` [Try it online!](https://tio.run/##DYq9CsIwGEVfRRAy6IXmzyQdUrq6CY6iECTEL9gKNbiUPnvMcDnnwJ1CecUpFHqGmny9ft6/eKOHPOY2OmTv94zR4PPgOVZC3nCeS0xx@d5ZvSw0l103pm5cOQQUNHoICWEgLXRzbVs09gbKCJy4heTSwUkn2lNwtdX6Bw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), ~~64~~ 62 bytes ``` k=>0.to(k)flatMap(i=>0.to(k)filter(j=>i*i+j*j+i*j==k)map(i->)) ``` [Try it online!](https://tio.run/##VcoxC8IwEAXgvb/ixlyrUlERhQQcHTo5ikOsKVwa09geIoi/PbZTyfa@995Qa6djd7emZqg0eTAfNv4xwCkE@GZv7aA5wtkzSAUX87qKMS@mAm8gYytVueJOtNg4zZUOguaGHJteWKkop8LmtqDcStnic7otFWIMPXl2XjSiRMxmrRNtEm0THdIt5a7cj/7FPw "Scala – Try It Online") Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) for -2 [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ô ï f@¶Xx²+X× ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9CDvIGZAtlh4sitY1w&input=MTIKLVE) ``` ô ï f@¶Xx²+X× :Implicit input of integer U ô :Range [0,U] ï :Cartesian product f :Filter by @ :Passing each X through the following function ¶ : Is U equal to Xx : X reduced by addition ² : After squaring each +X× : Plus X reduced by multiplication ``` [Answer] # [Perl 5](https://www.perl.org/), ~~81~~ ~~77~~ 74 bytes ``` sub{map{$i=$_;grep{$k==$i**2+$i*$_+$_**2&&($_=[$i,$_])}$i..$k}0..($k=pop)} ``` [Try it online!](https://tio.run/##ZVTbbqMwEH3PV1iRlULrRrYBY5e6yg/s275RhHZVEtE2ASWptFGUb8@OB0i4EAkP4zNnzvEE6mL/HV23J0LX9nr4@Xve/qnPtLQ0Tzb7AsIva2n5@Cif4E7zJ5pDvFh4NLcpLRnNM/9Cy@WSfl34cukBvK5q/3JNZj@HgvwuDseXl1/Vvkhm0GN1hGfrzQhcKeFuIfYNwpQzwjMCP9ZuiuGmyBhJxRgU9EDCgfqb4ZBBOgY5ZjBDUOBAwUSLvIOkYxpsqgFD6BjCMYOM76DAtRkINQOGuNUQuTVqNcUTTWHc1yREi8JqIaYqzeA4O1LtVt2VTZ0bNShDdwoCjnhIKQwmhgMlBoWmNSMavGrtCTMujHjcH6mUnbBGspTjMUsude8gQpQooYHEVmE4PgottehJM6I7MX2TpNFeAJHCXAhRhHQREIdoRrnRYKRvBnXUTcKI6Z9I8OCmU3AskAAzOAMJwzCoPQDF2nRtY5yMApxCAQoEqGbYcSdFAy7AWuPcYoWBocrGGjesfwJ@MltXew/fRf@Mqe3Jo@WuZrT4V/t2Be9@myYryNjmQ0DzlGev1q0iu6wc9g7bVEe7oGuk8W9peFpXdu6S5Pn5jcyXn1W58x7IA4PPzDxtOFlDmc2Zo2mry0P@URT198l7d1n27pQwJATEZfZR7YrcWSh3m@T6Hw "Perl 5 – Try It Online") A bit ungolfed: ``` sub f { my $k=pop; #gangnam style, k=pop from input grep { $k==pop@$_ } #pop last of three elems #...in the candidate array #...and return as result #...if last = i*i+i*j+j*j = k map { #two loops from 0 to sqrt $k my $i=$_; #outer loop var map { my $j=$_; #inner loop var [$i, $j, $i*$i+$i*$j+$j*$j] #result candidate } 0..sqrt$k #or $i..sqrt$k to return only i<=j } 0..sqrt$k } ``` Note: Saving bytes by removing the two sqrt makes it run A LOT slower, but it will still return the correct result. [Answer] # [Scala](http://www.scala-lang.org/), 53 bytes ``` | =>for(i<-0 to|;j<-0 to|if| ==i*i+j*j+i*j)yield(i,j) ``` [Try it online!](https://tio.run/##VcnNCgIhGIXh/VzFt1RnAqMi@jFo2aJVy2hhMwqfiNqMRNF07WYQhLvznHdopZXJX41qIxwlOlCPqFw3wD4EeFV3aUGv4eAiiB2c1O1M8m6@B72ASGO@te8Jbiccoh835jdQ5ySQYW2YqZEZ@kRlO4KNoSn06KJ1RBNOafXXtNCs0LzQqmwlF3yZ/U4f "Scala – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 75 bytes ``` i,j;f(x){for(i=j=x;~j;i-=!i?j--,-x:1)i*i+j*j+i*j-x||printf("(%d,%d)",i,j);} ``` [Try it online!](https://tio.run/##NY3LCsIwFET3/YprpJA0iVjEjWnqt0hi9AZtSx8QaOuvx6i4mmE4nDHyZkyMKLxyNLDZtT1F7XVQL69Q6g2evZRChlPJsEDuC8@x8DIsS9djMzpKaG5FbhkRScLUGrfYmMdkr1ANo8V2d6@zBMLzgg1lMGfw/UgLgoYSVMoKjvtUOEdgCYC/Oj9Y0DUkNVNpdvSX3TQOlJBPX7M1vgE "C (gcc) – Try It Online") [Answer] ## Python 3 - ~~79~~ 70 Bytes Just the trivial solution to get started with Python 3 ~~``` k=9 # not counted ``` ``` def f(k): a=range(k);return [(i,j) for i in a for j in a if k==i*i+j*j+i*j] ``` ``` print(f(k)) # not counted ``` [Try it online!](https://tio.run/##VYy7DoAgDAB3vqIjDzcnTfgS42AiaEtSSIODX4/o5o2Xy5W7npnH1pKf1B4iRJ3MrKAjoV7CsGgcyEDMAgjIIBsfoUefoZ/BCMl7tOjIkkNLqyqCXPU7Na09 "Python 3 – Try It Online")~~ --- **Thanks to @Jakque** lambda, testing framework in TIO, spaces, `k+1`, factorization ``` lambda k:[(i,j)for i in range(k+1)for j in range(k+1)if(i+j)*i+j*j==k] ``` [Try it online!](https://tio.run/##XVJBcoMwDLznFT6axAdkjGNnxi@hHNJpaIEUMoQc@npqCQw4HLBYaaVd4cff@NN32VS5j@l@/f38urL2UvBaNEnVD6xmdceGa/d94@0JCGpiqK54fWqSo38dG@fachpvz/HJXHFg/ilSwegpuI/SpCzFjMMeh0QwDlE@W/OA@RVXe55Enox4dp/PMJ/Fc6VY8hL5G67FxlPIUxFPnkM@w76bHrvjnZd5OZ75Mv8cz1dzI5oPsBQQEeBNkRXbhkIrg6cJjDdvVu8YZMIDkFKphzQFsa9Mw45jF@Ewl@rFCtiIk6fBAyqWQcmsUcrof8lUGhH8KtIkfVtJA5SKHBtpQAQtFsJOzKrBkJXMR5owXH5OnXLfU5F6jXunyKyOTB52bddbVh7wNreCDbfn6z7iraabeyEt/Wt8vEbmWMXbhJDHUHcjx0/nZopA9lyYHKZ/ "Python 3 – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), 57 bytes Prints the pairs \$(x,y),\:x\le y\$. ``` n=>{for(y=n+1;x=y--;)for(;x--;)x*x+y*y+x*y-n||print(x,y)} ``` [Try it online!](https://tio.run/##TY3BCoMwDIbve4ocdqhaReumlVJvu@4FxkCRuTmkFRVpUZ/dpbcdEr7/S0K@9VJPzdgNc7jwo5WHkuXa6pFYqYJEGGnDUHhOCOPI@Cawvg2Mb0O1bcPYqZkYar39EI@YQkIhpXChUCAzrIwCy9G4fMmdcFSgTjNcvsboWMw4Bc544o6SOH2eInx5q5sPUSBLWKHRatL9K@r1m1R3kHBe1V55AlqisP@PMe7e8QM "JavaScript (V8) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` NθF⊕₂θF⊕ι¿⁼θ⁻X⁺ικ²×ικI⟦ικ ``` [Try it online!](https://tio.run/##ZYy7CgIxFER7vyLlDURw13JLsdjCJaidWMSYxWAe5ibRz493wc5iYDhzGP1QqKNyrY3hVctU/c0gJD6s5ogMxqDReBOKucMpVYXmGGOhnXP2J1iCdmawJ9FlSIIdbKgZZPzQp3RUrWBPLlhPOVtvfmB5k2hDgZ3KBS4LvHI@tNb13Wbb1m/3BQ "Charcoal – Try It Online") Link is to verbose version of code. Only outputs those pairs where `i>=j`. `₂` speeds the code up so that the larger test cases complete within a minute, but it is not needed for smaller test cases. Explanation: ``` Nθ ``` Input `k`. ``` F⊕₂θ ``` Loop `i` from `0` to `√k` inclusive. ``` F⊕ι ``` Loop `j` from `0` to `i` inclusive. ``` ¿⁼θ⁻X⁺ικ²×ικ ``` If `k=(i+j)²-ij`, then... ``` I⟦ικ ``` Output `i` and `j` on separate lines. Just for fun, here's a 73-byte [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1.0 answer that only finds nontrivial solutions (i.e. neither `i` nor `j` is zero): ``` .+ * L$w`^((_)+)(?=(?<-2>\1)+(?(2)$.)(_(_)*)(?<-4>\1\3)*$(?(4).)) $.1 $.3 ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4vLR6U8IU5DI15TW1PD3lbD3kbXyC7GUFNbw17DSFNFT1MjHiinpQmSMAFKxBhraqkA5Uw09TQ1uVT0DBVU9Iz//zc1MAcA "Retina – Try It Online") Very slow, so don't try anything over about 500. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ``` Array[(+##)^2-##&,{#,#}+1,0]~Position~#-1& ``` [Try it online!](https://tio.run/##FcvLCoMwEIXh/bzGgLQ4gVysl0VL@wZCl2IhSKVZqJBmU8S8ejrZzf9xZrHh815scJNN8zU9vLe/4VQinl9aIBa0I@FRKpJj7LevC25bIwpVpN67NQwobvMdxyI@J7vGHSSBItAEhqAi6Dg5VM3WsOSumgz56phNzfuLZNNStwStblV@UtLAkf4 "Wolfram Language (Mathematica) – Try It Online") Gets slow on larger inputs. ``` Array[ (* Create a table of *) (+##)^2-##&, (* (i+j)^2-i j *) {#,#}+1,0] (* for i,j = 0...k *) ~Position~#-1 (* and find where that expression equals k *) ``` ]
[Question] [ Write a program that takes in a string and spells that word out using the NATO Phonetic Alphabet. The mapping is as follows: ``` 'A' -> 'Alfa' 'B' -> 'Bravo' 'C' -> 'Charlie' 'D' -> 'Delta' 'E' -> 'Echo' 'F' -> 'Foxtrot' 'G' -> 'Golf' 'H' -> 'Hotel' 'I' -> 'India' 'J' -> 'Juliett' 'K' -> 'Kilo' 'L' -> 'Lima' 'M' -> 'Mike' 'N' -> 'November' 'O' -> 'Oscar' 'P' -> 'Papa' 'Q' -> 'Quebec' 'R' -> 'Romeo' 'S' -> 'Sierra' 'T' -> 'Tango' 'U' -> 'Uniform' 'V' -> 'Victor' 'W' -> 'Whiskey' 'X' -> 'Xray' 'Y' -> 'Yankee' 'Z' -> 'Zulu' ``` Example: `'Hello World' -> ['Hotel', 'Echo', 'Lima', 'Lima', 'Oscar', 'Whiskey', 'Oscar', 'Romeo', 'Lima', 'Delta']` The input can be any string, but will always be comprised of only letters and spaces. Case is irrelevant in the output, but the input may contain letters in uppercase, lowercase, or both. Spaces should be ignored in the output. You can output in any reasonable format, but it must be a delimited set of NATO callsigns. [Answer] # [sfk](http://stahlworks.com/dev/swiss-file-knife.html), ~~78~~ ~~59~~ 57 bytes ``` +filt +spell -nato +xed _ph_f_ _et_ett_ _-__ "*: [keep]"" ``` [Try it online!](https://tio.run/##K07L/v9fOy0zp4RLu7ggNSdHQTcvsSSfS7siNUUhviAjPi1eIT61BIhKgAzd@HgFJS0rhejs1NSCWCWl//89gFryFcLzi3JSEgE "sfk – Try It Online") Just use the right tool. Output is the phonetics separated by one or more spaces. [Answer] # x86-16 machine code, IBM PC DOS, 192 bytes ``` be80 00ad 8ac8 ac51 24df 8ad0 2c40 3c1b 7321 8af0 b024 b18b 9090 bf37 01f2 aefe ce75 fab4 02cd 218b d7b4 09cd 21b2 20b4 02cd 2159 e2d0 c324 6c66 6124 7261 766f 2468 6172 6c69 6524 656c 7461 2463 686f 246f 7874 726f 7424 6f6c 6624 6f74 656c 246e 6469 6124 756c 6965 7474 2469 6c6f 2469 6d61 2469 6b65 246f 7665 6d62 6572 2473 6361 7224 6170 6124 7565 6265 6324 6f6d 656f 2469 6572 7261 2461 6e67 6f24 6e69 666f 726d 2469 6374 6f72 2468 6973 6b65 7924 7261 7924 616e 6b65 6524 756c 7524 MOV SI, 80H ; point SI to DOS PSP LODSW ; load arg length into AL, advance SI to 82H MOV CL, AL ; set up loop counter SEARCH: LODSB ; load next char from DS:SI into AL, advance SI PUSH CX ; save outer loop position AND AL, 0DFH ; uppercase the input letter MOV DL, AL ; save for output SUB AL, 'A'-1 ; convert letter to one-based index (A=1, Z=26, etc) CMP AL, 27 ; if greater than 26, not a valid char JNC NOTFOUND ; if not, move to next MOV DH, AL ; DH is loop counter MOV AL, '$' ; search for string delimiter MOV CL, LNATO ; repeat search through length of word data MOV DI, OFFSET NATO ; re-point SCASB to beginning of word data SCANLOOP: REPNZ SCASB ; search until delimiter in AL is found ES:DI, advance DI DEC DH ; delimiter found, decrement counter JNZ SCANLOOP ; if counter reached 0, index has been found MOV AH, 02H ; display first char INT 21H MOV DX, DI ; put found string memory location to DX for display MOV AH, 09H ; display string function INT 21H MOV DL, ' ' ; display a space between words MOV AH, 02H INT 21H NOTFOUND: POP CX ; restore outer loop counter LOOP SEARCH ; move to next char in input RET NATO DB '$lfa$ravo$harlie$elta$cho$oxtrot$olf$otel$ndia$' DB 'uliett$ilo$ima$ike$ovember$scar$apa$uebec$omeo$' DB 'ierra$ango$niform$ictor$hiskey$ray$ankee$ulu$' LNATO EQU $-NATO ``` Test output: ``` A>NATO abc aaa Alfa Bravo Charlie Alfa Alfa Alfa A>NATO abc DefG1HIJ Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett A>NATO Alfa Bravo! Alfa Lima Foxtrot Alfa Bravo Romeo Alfa Victor Oscar ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~102~~ ~~96~~ 95 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` álSA”AlfaІvo¼¯¤œ®È¨›trotŠˆƒ‹Š™ÈŸtt Kilo´àma—……ÍЗŽêpa¼°«Äoµ†Çâgo¸šÉµ Whiskey Xrayµ‹nkeeâ¸lu”#‡ ``` Output is a list of Titlecased NATO words. [Try it online.](https://tio.run/##Fc6xCsIwFIXhVwn4JN0ER4e6RoxaGo20VeiWoWgdBNGuQlpEREEdLLSiy73ExbfIi9QWzvbDxxE@7TusqjDlXcvIg8WHFLdGqoWAN9zhqPdwwxjORr4CTwRa/ZbfnZGlVibKMNZFEJCOwwU8UU2okYmRp3q4aZREf/Ayo7X0gCtGAvJaxhVmIwGFTnENObHHju@ykPQ8Gja9nLqMYQYFn9d/WkamVdVmnAtiC48P/g) **Explanation:** ``` á # Only leave the letters of the (implicit) input l # Convert it to lowercase S # Split it to a list of characters A # Push the alphabet ”...” # Push all the NATO words in titlecase and space-delimited # # Split the string by spaces ‡ # Transliterate; map all letters in the lowercase input with this # list at the same indices (and output the resulting list implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”AlfaІvo¼¯¤œ®È¨›trotŠˆƒ‹Š™ÈŸtt Kilo´àma—……ÍЗŽêpa¼°«Äoµ†Çâgo¸šÉµ Whiskey Xrayµ‹nkeeâ¸lu”` is `"Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey Xray Yankee Zulu"`. Credit of this compressed dictionary string goes to [*@ErikTheGolfer* in this comment](https://codegolf.stackexchange.com/questions/112208/charlie-oscar-delta-echo?noredirect=1&lq=1#comment273386_112221) (with an added `t` for `Juliett` instead of `Juliet`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~80~~ 77 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḟ⁶O%32ị“¡µQỤ(cɠṘwlṁ;Ɗœ<NẸ½ṗN¬ṙẋxḶb¤*O~ƃ¹.ß8Ḋ¡tJ|Ḷ<İİḂ^1eȷjċbY9TYƭ¹Ẉ¥¤K0¹f»Ḳ¤ ``` **[Try it online!](https://tio.run/##AZ8AYP9qZWxsef//4bif4oG2TyUzMuG7i@KAnMKhwrVR4bukKGPJoOG5mHds4bmBO8aKxZM8TuG6uMK94bmXTsKs4bmZ4bqLeOG4tmLCpCpPfsOGxpLCuS7DnzjhuIrCoXRKfOG4tjzEsMSw4biCXjFlyLdqxItiWTlUWcatwrnhuojCpcKkSzDCuWbCu@G4ssKk/8OHS///SGVsbG8gV29ybGQ "Jelly – Try It Online")** (The footer formats the list by joining with spaces to avoid implicit smashing print when run as a full program) [Answer] # JavaScript (ES6), ~~181~~ 189 bytes ``` s=>s.match(/\w/g).map(c=>'IndiAlfABravOscaRomeOQuebeCharliEchODeltAGolFoxtroTangOHoteLimAJulietTKilOZulUniforMikENovembeRPapASierrAVictoRWhiskeYankeEXraY'.match(c.toUpperCase()+'.*?[A-Z]')) ``` Since output case doesn't matter, we can save bytes by running words together: ``` ... GolFoxtroTangO ... ``` [Try it online!](https://tio.run/##XY7NToNAFEb3PgW7AZvSBzCtGStaf1Haqq26GIYLTLnMxZkBqi@PXRhjXJ7kO1/OTnTCSqMaN9aUwYDgvHw62OnMhrVwsvQnb/2kCA7Q@HI6Y1c6UxxzfmZEF1spEqohfmwhhXkpDKpIlvE5oOOXhBe0d4ZWQhfxghzcqppft6jArW4UxtsW11rlZO5UFd1TB3UKyYNo@FKBMfxJSUfJc6lsBRuhK4hejNiwnyoZOlo3DZi5sOAHIxYen77y8fadBcEgSVtCCJEKP/fZAhDJ68lgxgJv5DEWnBz93fzDgyJSmUFelGpXYa2p@TDWtV2///z6fRi@AQ) [Answer] # [Python 3](https://docs.python.org/3/), ~~250~~ 191 bytes -47 bytes thanks to @Jo King, -2 more thanks to @Jonathan Allen It goes through all non-space characters of the input, and for each of them it selects the relevant phrase for the letter, which can be reduced a bit because the first letter of each phrase is the character itself. Splits a string instead of storing the phrases as an array to save bytes from the unnecessary `'`s and `,`s. ``` lambda s:[c+"lfa ravo harlie elta cho oxtrot olf otel ndia uliett ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split()[ord(c)%32-1]for c in s if' '<c] ``` [Try it online!](https://tio.run/##LY9NTsNADIWv8hQJNRECCbpDsOcOpQtn4iFWnHHkcQs5fZgF6/e9v22P2cr5KBQmef/4OpTWcSLUt0t67DQTnO6GmVyFwRqENBvsN9wCphkWrCiTEG4NiYCoQVaCLAy78zqyoyZy0NYYHjnBVm4MuxOofBuKZPMVksIcs9SF99a7N3Fhbrm37rluKtEPF/OpT8PD@fXp5dpMSJCCCsknnN7T9dhcSvT/f/ruk7XN@THXqRuG4w8 "Python 3 – Try It Online") Original solution ``` lambda s:[c+['lfa','ravo','harlie','elta','cho','oxtrot','olf','otel','ndia','uliett','ilo','ima','ike','ovember','scar','apa','uebec','omeo','ierra','ango','niform','ictor','hiskey','ray','ankee','ulu'][ord(c)-65]for c in s.replace(" ", "").upper()] ``` [Try it online!](https://tio.run/##LZBBbsUgDESvgtgE1N@/qdpFpe57hzQLhzgNioORQ36b06cYdcMM43mAyGdZOL1cCQrH@fz4ugi2cQKzv/fhqe9ohu7WCTy4ygJCEatBKhqHRVP@LcJFDc26FqQqaYpaOSpQdBhJu3HTMK56CD9wG1Gq2wOoQG4Ejhh0vGEjUERjSN@6TXFm2TQPhRVa4r7i2d54ttqK2O49uqFnmVzwz2@vQ6VMMDGZ/S6YCQI6a@zNWOvvR84ozg9XlpiK@/8KZz@RiM0PC03W@@sP "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 99 bytes ``` EΦ↥S№αι⁺ι§⪪”&⌊%w⁸D⦃σν:…ⅈ$|@H¦χT⸿]ECrΣM^¿←←&⁵↘⁼s(JF8X´▷⧴⎚P0V÷AWχπ¶⌈≧\"dJ^ZU{M≔⁴|<¶⁹B⊞⊟1LPH⪪∨Y3`”j⌕αι ``` [Try it online!](https://tio.run/##Lc5BasNADAXQfU9hvJqAe4KuSiA0i0IglK6VsRxLlkeDLJvk9I4K1U7oof/zCJYVZN8vRsXTN9R0InG09FMrWoYF07nU1a8e4J4Oh6456hoUuob@tousS6Ku@fRz6fGRrlXIUysDsMGmHAlCyCgOnEdlfbips8rA6ihcegJeg7gziTLNwDQh64bzDY2XDMZQw@ANM@uMYdAMGMpdudCgNjNlV@ORlgmfkfuM44QYf9e2a1puo@iJSv/fOuZj379QRJtfNenf9vdNXg "Charcoal – Try It Online") Link is to verbose version of code. Outputs in proper case. Explanation: ``` S Input string ↥ Uppercased Φ Filtered where α Predefined uppercase alphabet № Contains ι Current character E Mapped over characters ι Current character ⁺ Concatenated with ”...” Compressed string ⪪ Split on j Literal string `j` § Indexed by ⌕ Index of ι Current character α In uppercase alphabet Implicitly print each word on its own line ``` [Answer] # [Red](http://www.red-lang.org), ~~210~~ 193 bytes ``` func[s][foreach c trim/all s[prin c print pick[:lfa:ravo:harlie:elta:cho:oxtrot:olf:otel:ndia:uliett:ilo:ima:ike:ovember:scar:apa:uebec:omeo:ierra:ango:niform:ictor:hiskey:ray:ankee:ulu]c% 32]] ``` [Try it online!](https://tio.run/##FY6xbsQwDEP3foVxQOcC7cYv6Nylg@FBp8iNENkKFOfQ@/rUnQiQDyRDlutLllxeKtJVz875KLl6CPGaOI3Q9kZm6ch7aJ/Ov4y0K28ZVglBD8dKYSoQGwReHf47wgfcKnyIoS9KOCcyBtQc2gi6Cfwh7S6BgylA@2TkLgxvMhmJIFD/cXSdjxqUhwdWPTZ5zt3nDDeR2XsWfk0f76VcNd0@xczTt4ctt@sP "Red – Try It Online") ## Explanation: `foreach` iterates over the string after all whitespaces are removed by `trim/all`. `prin` prints the character (no newline). `print` prints a symbol, `pick`ed from the list of get-word!s (symbols) using the character mapped to the range 1..26 as an index. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 218 bytes ``` import StdEnv $s=[takeWhile((<=)c)(dropWhile((<)c)['ZuluYankeeXrayWhiskeyVictorUniformTangoSierraRomeoQuebecPapaOscarNovemberMikeLimaKiloJuliettIndiaHotelGolfFoxtrotEchoDeltaCharlieBravoAlfa'])\\c<-map toUpper s|c>' '] ``` [Try it online!](https://tio.run/##NY9RT8JAEITf/RX3QNLywD8AExUUFBVFRC08LNctXLp3e9luG5v42601xmReZr55mLGEEDrPeU1oPLjQOR9Z1Kw1n4XmbFBNMoUStydHmKbjydAO01w4/ge9z5KPmup3CCXim0Dbo6rE9tVZZdkEV7D4FwhHXjsUgWf2yE81HtCuIMJjZUEeuEF/QLl3JS6dhztHfFuTQ9VFyB3MWZFumIpr/lRhndkTT5EUrk4gfe1SoOELKiDZD3c7Ox55iEZ5EyOKqb7seWKSfbdW6J9NzMBkyRyJ2GxZKO/Jty0IjlU3Wiy7aRvAO/tnVgT6u78bUa8qQIztDw "Clean – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 218 bytes ``` n=>n.ToUpper().Select(x=>"AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJuliettKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu".SkipWhile(k=>x!=k).TakeWhile((k,l)=>l<1|k>96&k<123)) ``` [Try it online!](https://tio.run/##TZBfT8JAEMS/ivbBXJPaBE1MDO0liiCg4h9A1LflWOBy29tmeyWQ@N1rE3xgniYzv5cZU12ayjaD2pusCmL9Jhn1fV2gwJIwO/VmC6K1hrzxufbpjOdliaLidIqEJqh9rqM7WsO9wI57LUwWH5AC9M2WB7wPwuGRaT3kgDTyKwvjukVCeLLEz7aAF@twwjssliivlQF5gxLea1yi@eACeWpRBGbgNzz3ds1SfFoTWBZbWzk8fAkcvsE7xJ@a6iidOlu2FaFyud6f5y5OZ@DwGCmXUJxryjq/Tt/eXLisc3Udx013ITagOl6Rjtl6FSVRAioaIhGfLVhoFZ1u/kd77A20Qdyq2/wB "C# (Visual C# Interactive Compiler) – Try It Online") # Alternate version using Split(), 194 bytes ``` n=>n.ToUpper().Select(x=>x>64?x+"lfa,ravo,harlie,elta,cho,oxtrot,olf,otel,ndia,uliett,ilo,ima,ike,ovember,scar,apa,uebec,omeo,ierra,ango,niform,ictor,hiskey,ray,ankee,ulu".Split(',')[x%65]:x+"") ``` [Try it online!](https://tio.run/##TY8xT8NADIX/CjoJ9SJMJuhAm@uAQMBaUAfE4FydxsrlHDmXKv314SQY6smyv@fn58d7P/LyOkW/HZNyPMH7S5x6UqwDba9736I657BaYuVi@Slfw0Bqi3JPgXyyc@Vmt37YzXcmNAiKZ4EsCUxAISH4VkDmpJJAQgOSKEA8MsKUkZSAgwD3CNwRyJn6mhRGjwo4ZIZq8iA9ZYZUETCeBCI3oj2wT6LQ8tjRJfte8rIjyncnU@6HwMmuYFV8z7frx5@n/J4pls1BOZH9i1x@CEdrwABa80YhyM1BNBzNdbZ/9Fmixzwocm2WXw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~176 170~~ 166 bytes ``` *.comb>>.&{$_~:128[q`>$RbD[Orlo~Q1nX,OVq8x9'6%h'1.I$83ua7 vsD=s-{W}{>iQ:Js 37py) hNN,i{Pt\~#f4<>`.ords].base(35).split('J')[.ord%32]}.words ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0svOT83yc5OT61aJb7OytDIIrowgZHBTiWIJUnIpV6QL9q/KCe/LpDJMC9CSsc/rNCiwlKd2Uw1Q91Qz5NfxcKYvzTRnLNMsthFlNlWrFi3Ory22k4kM1DcSsCrvljGmFHKvKBSk1Euw89PJ1O4OqAkpk45jZ/dhMnGLkEvvyilOFYvKbE4VcPYVFOvuCAns0RD3UtdMxokpWpsFFurVw5S9N@aqzixUiFNQ8kjNScnXyE8vygnRUlTzyezuESvAOgj6/8A "Perl 6 – Try It Online") Outputs in uppercases with the first letter in the original case. Compresses the string, which only saves 6 bytes over the simpler plain text: ``` *.comb>>.&{$_~ <lfa ravo harlie elta cho oxtrot olf otel ndia uliett ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu>[.ord%32-1]if ' 'ne$_} ``` [Try it online!](https://tio.run/##Dc/NasNADATge59iCPlrIYa20EtSn/sGPYQS5LW2Ft61jLwJNaF9dVfn@ZhhRrb0tuQZ24h3LE9V0NzUdbW9ry9/OKVIMLopOrIkDE6FEDqF/hTTAk0RWjhhaIVwdVIKJCkkE6Rn6I1zw4YpkIFGN9xwgGZ2w2YEGr4Vg0S1DAlFDZ1MPc@@O3vYM3vvtT5Xau3m9eXw/CURO@wGXl9@l@PD5CzuVx@cfPZTLbWrx2r0W8flHw "Perl 6 – Try It Online") ### Explanation: ``` *.comb>>.&{ } # Map each letter to $_~ # The letter plus <...>[.ord%32] # The letter indexed into the list of words .words # And remove the extra spaces ``` [Answer] # C++, ~~229~~ 228 bytes ``` [](auto s){for(;auto t=*s?"LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu":0;s++)if(int c=*s&31){for(cout<<*s;*t>96||--c;t++);for(;cout<<*t,*++t>96;);cout<<' ';}} ``` [Try it online!](https://tio.run/##RZBfa9swFMXf/SnuOljtpBkdg8ImNyOMQT1KDd3yNMa4lq8dzbLkSVf50zafPZOTQB/0cM/v6OroyGGYtVIe3iojdagJcmU9O8J@ngSvTAsGe/IDSgLPtUhejdEW@TxRhqFHZdIseU4ATjIoMwQWca6s1dAo5/mWXaBR2qyUJkhbYq0MpVKZq5M/yyIdlwCoBtI3x2sZSBsY8hzI1FqcdzWoPYnDr98pBrbgs@fGulQcB76d@C8X9w0@4treodOKvmnGrytbbtlZLnVTMumHWuEyMuZC26LHoqNyTX1F7odEtxhwSRXJsidbkHO4MK19UPGVvpBs3Z3yHe0ecbcwHdFSh4vP18JPp5lq0rESGUO8@/jhlGv8QZ5PvJjw/NPNy8tsJgVHrziGPlO@mkynIxfZWbqES7HfH8Y@0mNB7@Wf2G@aZWON@3gccXAGrkWyP/xcEfwLSnZQObsx0Ngt/A39QDXYNTngyDU@7aC2bfIdZVfjxoOODPodVKoFP6yU2YJt4h50/PQf "C++ (gcc) – Try It Online") Ungolfed: ``` [](const char *s) { const char *table = "LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu"; for (; *s; s++) { char c = *s & 0x1F; if (c != 0) { cout << *s; const char *w = table; while (*w >= 'a' || --c) w++; do cout << *w; while (*++w >= 'a'); cout << ' '; } } } ``` Output: ``` TAngo hOtel eCho qUebec uNiform iNdia cHarlie kIlo bRavo rOmeo oScar wHiskey nOvember fOxtrot oScar xRay jUliett uNiform mIke pApa eCho dElta oScar vIctor eCho rOmeo tAngo hOtel eCho lIma aLfa zUlu yAnkee dElta oScar gOlf JUliett aLfa cHarlie kIlo dElta aLfa wHiskey sIerra lIma oScar vIctor eCho mIke yAnkee bRavo iNdia gOlf sIerra pApa hOtel iNdia nOvember xRay oScar fOxtrot qUebec uNiform aLfa rOmeo tAngo zUlu ``` Clean-capitalization version (**234 bytes**): ``` [](auto s){for(;auto t=*s?"LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu":0;s++)if(int c=*s&31){for(cout<<*s;*t>96||--c;t++);for(;putchar(*t|32),*++t>96;);cout<<' ';}} ``` [Try it online!](https://tio.run/##RVBdb9NAEHz3r1iKRG2nQYVKSHBuUISQaoRqqTRPCKH1eW0fPt@Zu3U@2uS3h3NSiYd92J3Z2dmRwzBvpDy@VkbqsSLIlPXsCPtFNHplGjDYkx9QEniuRPSfGGgBX0TKMPSoTJxEzxHAeQzKDCOL0JfWaqiV83zLbqRptGmVJogbYq0MxVKZqzM/SQI6iQCoGuJXp7UEpB0ZsgzIVFq8aNWoPYnjz18xjmzBJ8@1dbE4NXyb@s8X32t8wLW9Q6cVfdWMX1pbbNlZLnRdMOn7SuEqYMy5tnmPeUfFmvqS3A@JbjngikqSRU82J@dwaRp7r8KVPpds3Z3yHe0ecLc0HdFKjxefroWfzRJVx1MkMph4c/Pu7Gv6IMtSL1JefPyw38/nUnDgipPp8Lls0cUp72/eJ1fpbDaxRCLOa5dwKQ6H45RKfIrprfwdUo6TZArzEMoRj87AtYgOx8eW4O@oZAelsxsDtd3Cn7EfqAK7JgcccI1PO6hsE31D2VW48aADBv0OStWAH1pltmDroIOOn/4B "C++ (gcc) – Try It Online") Output: ``` Tango hotel echo quebec uniform india charlie kilo bravo romeo oscar whiskey november foxtrot oscar xray juliett uniform mike papa echo delta oscar victor echo romeo tango hotel echo lima alfa zulu yankee delta oscar golf Juliett alfa charlie kilo delta alfa whiskey sierra lima oscar victor echo mike yankee bravo india golf sierra papa hotel india november xray oscar foxtrot quebec uniform alfa romeo tango zulu ``` [Answer] # IBM PC DOS 8088 machine language, 165 bytes This is directly based on [gwaugh's answer](https://codegolf.stackexchange.com/a/178442/17216), but I shaved off 26 bytes by omitting the `$` delimiters from the "NATO" word table and an extra 1 byte by not skipping the first character of the command-line parameter string (which will always be either `/` or and thus will be ignored by the program anyway). The program ended up being exactly the same length to be able to process the table in this format (in which the words are delimited only by uppercase characters, which serve the double purpose of also being the second letter of each word), or 2 bytes longer if the output capitalization is kept the same as before. The table is 26 bytes smaller. In the following program dump, concatenation by `:` is used to show each sequence of consecutive bytes corresponding to an instruction: ``` 0000 BE:80:00 AC 91 AC 24:DF 8A:D0 2C:40 3C:1A 77:21 ······$···,@<·w! 0010 8A:F0 B4:02 CD:21 56 BE:34:01 AC A8:20 75:FB FE: ·····!V·4··· u·· 0020 :CE 75:F7 8A:D0 CD:21 AC A8:20 75:F7 B2:20 CD:21 ·u····!·· u·· ·! 0030 5E E2:D2 C3 4C 66 61 52 61 76 6F 48 61 72 6C 69 ^···LfaRavoHarli 0040 65 45 6C 74 61 43 68 6F 4F 78 74 72 6F 74 4F 6C eEltaChoOxtrotOl 0050 66 4F 74 65 6C 4E 64 69 61 55 6C 69 65 74 74 49 fOtelNdiaUliettI 0060 6C 6F 49 6D 61 49 6B 65 4F 76 65 6D 62 65 72 53 loImaIkeOvemberS 0070 63 61 72 41 70 61 55 65 62 65 63 4F 6D 65 6F 49 carApaUebecOmeoI 0080 65 72 72 61 41 6E 67 6F 4E 69 66 6F 72 6D 49 63 erraAngoNiformIc 0090 74 6F 72 48 69 73 6B 65 79 52 61 79 41 6E 6B 65 torHiskeyRayAnke 00A0 65 55 6C 75 40 eUlu@ ``` Download the DOS NATO.COM executable: [With uncorrected capitalization](https://kingbird.myphotos.cc/66950d6b63d68800ece9aab9bb71e83d/nato.com) (165 bytes) [With clean capitalization](https://kingbird.myphotos.cc/961141a824d8438979a06634d2695dc0/nato.com) (167 bytes) [Bonus version that capitalizes the first letter of each word the same as the input](https://kingbird.myphotos.cc/faef61580a56c11aef97099b54c05536/nato.com) (167 bytes) Unassembled: ``` .MODEL TINY ; .COM program, maximum addressing space 65536 bytes .CODE ORG 100h start: MOV SI, 80h ; Point SI to DOS PSP (Program Segment Prefix). LODSB ; Load command-line parameter (input string) length ; into AL; assume AX=0 before this, which is true ; in most versions of DOS; advance SI to first char ; of parameter, which is either '/' or ' '. XCHG CX, AX ; Set up loop counter with length of input string. search: LODSB ; Load next character from [SI] into AL; advance SI. AND AL, NOT ('A' XOR 'a') ; Make this character uppercase. MOV DL, AL ; Save character for output. Move this before the ; AND instruction to capitalize the first letter of ; each word identically to how it is in the input. SUB AL, 'A'-1 ; convert letter to one-based index (A=1, Z=26, etc) CMP AL, 'Z'-'A'+1 ; Is this an alphabetical character? JA notFound ; If not, move to next character. MOV DH, AL ; Set up DH as our word-finding loop counter. MOV AH, 02h ; AH=02h, INT 21h: Write character to STDOUT INT 21h ; Display first character of this NATO word. PUSH SI ; Save our current position in the input string. MOV SI, OFFSET table ; Point LODSB to beginning of word data. scanLoop: ; Find the word in the table corresponding to our ; current character. LODSB ; Load next character from [SI] into AL; advance SI. TEST AL, 'A' XOR 'a' ; Is this character uppercase? JNZ scanLoop ; If not, move to next character. DEC DH ; Delimiter (uppercase) found; decrement counter. JNZ scanLoop ; Keep looping until counter reaches 0. OR AL, 'A' XOR 'a' ; Make this character lowercase. This is not ; required by the challenge's specification, and ; this instruction can be removed. wordLoop: MOV DL, AL ; Display next character from NATO word. INT 21h ; (We still have AH=02h from before.) LODSB TEST AL, 'A' XOR 'a' ; Is this character lowercase? JNZ wordLoop ; If so, continue the loop. MOV DL, ' ' ; Display a space between words. INT 21h ; (We still have AH=02h from before.) POP SI ; Restore our current position in the input string. notFound: LOOP search ; Move to next character in input string. RET table DB 'LfaRavoHarlieEltaChoOxtrotOlfOtelNdia' DB 'UliettIloImaIkeOvemberScarApaUebecOmeo' DB 'IerraAngoNiformIctorHiskeyRayAnkeeUlu' DB '@' ; Terminate the list to make sure that uninitialized ; memory doesn't cause a problem. END start ``` Sample input: ``` >NATO The quick brown fox jumped over the lazy dog. >NATO Jackdaws love my big sphinx of quartz. ``` Output (165 byte version): ``` TAngo hOtel eCho qUebec uNiform iNdia cHarlie kIlo bRavo rOmeo oScar wHiskey nOvember fOxtrot oScar xRay jUliett uNiform mIke pApa eCho dElta oScar vIctor eCho rOmeo tAngo hOtel eCho lIma aLfa zUlu yAnkee dElta oScar gOlf JUliett aLfa cHarlie kIlo dElta aLfa wHiskey sIerra lIma oScar vIctor eCho mIke yAnkee bRavo iNdia gOlf sIerra pApa hOtel iNdia nOvember xRay oScar fOxtrot qUebec uNiform aLfa rOmeo tAngo zUlu ``` Clean-capitalization version (167 bytes): ``` Tango Hotel Echo Quebec Uniform India Charlie Kilo Bravo Romeo Oscar Whiskey November Foxtrot Oscar Xray Juliett Uniform Mike Papa Echo Delta Oscar Victor Echo Romeo Tango Hotel Echo Lima Alfa Zulu Yankee Delta Oscar Golf Juliett Alfa Charlie Kilo Delta Alfa Whiskey Sierra Lima Oscar Victor Echo Mike Yankee Bravo India Golf Sierra Papa Hotel India November Xray Oscar Foxtrot Quebec Uniform Alfa Romeo Tango Zulu ``` Clean-capitalization version with same capitalization as input (167 bytes): ``` Tango hotel echo quebec uniform india charlie kilo bravo romeo oscar whiskey november foxtrot oscar xray juliett uniform mike papa echo delta oscar victor echo romeo tango hotel echo lima alfa zulu yankee delta oscar golf Juliett alfa charlie kilo delta alfa whiskey sierra lima oscar victor echo mike yankee bravo india golf sierra papa hotel india november xray oscar foxtrot quebec uniform alfa romeo tango zulu ``` [Answer] # Japt, ~~108~~ 106 bytes ``` ¸®¬Ë+u cg`ovem¼rws¯r°pawue¼cÙ o±ØÇ¯fmØtØkeyÙ°nkeewªuwlfaæ1ÃÉr¦e³ltawÖoxÉwolfÙ*lÙAawªieâ-¹µ±ke`qw ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=uK6syz11KStgb3Zlbbxyd3OvcrBwYXd1Zbxj2SBvsYCf2AHHr2aObdh0jtiRa2V52Z+wbmtlZXeqdXdsZmHmMcPJcqZls2x0YXfWnm94yZV3b2xm2Sps2UFhd6ppZeItjbm1sWtlYHHUZ0Rj&input=IkhlbGxvIFdvcmxkIg==) The backticks contains the compressed string: ``` ovemberwscarwapawuebecwomeowierrawangowniformwictorwhiskeywraywankeewuluwlfawravowharlieweltawchowoxtrotwolfwotelwndiawuliettwilowimawike ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~187~~ 183 bytes ``` $args|% t*y|%{'AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJuliettKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu'-csplit'(?=[A-Z])'-like"$_*"} ``` [Try it online!](https://tio.run/##VZDrbsIwDIX/9ymiKiyA6COgjV3Z/T42pgmZ4tKItO6clIGAZ@/aDk3gP7ZObJ0vJ6MfZBujMYWMRFesCgk8teuGcO3lurFSPRPBMcOcTmJgo/EUjYOzMKZzWjgmd0Em6pNDc5lONFzl5Ypz19rQjU7gVs/wjuaYjJHvbQj8ABk85jjG8IkSpGeNzPAC6ZReUx0RJ286dMSDWNsZLt8Zlh@QzhCHuclVENrMaKeah93PXjD8aqnAlAa@HLX9TbHxvKOmJ8rqNFW//BCJAbGZqI5QNWA1VOBVr@B2ew1XDVvnPa1G3d2uM1AtryXWoiFWtam0HYmLDEOHkzJHOfpTGW1uXCkclPFKW4v@VvUD/Pb/j/z9N29T/AI "PowerShell – Try It Online") Test script: ``` $f = { $args|% t*y|%{'AlfaBravoCharlieDeltaEchoFoxtrotGolfHotelIndiaJuliettKiloLimaMikeNovemberOscarPapaQuebecRomeoSierraTangoUniformVictorWhiskeyXrayYankeeZulu'-csplit'(?=[A-Z])'-like"$_*"} } @( ,('Hello World', 'Hotel', 'Echo', 'Lima', 'Lima', 'Oscar', 'Whiskey', 'Oscar', 'Romeo', 'Lima', 'Delta') ) | % { $s,$expected = $_ $result = &$f $s "$result"-eq"$expected" "$result" } ``` Output: ``` True Hotel Echo Lima Lima Oscar Whiskey Oscar Romeo Lima Delta ``` [Answer] # [PHP](https://php.net/), ~~209~~ ~~205~~ 206 bytes ``` while($l=$argv[1][$x++])echo$l!=' '?$l.preg_split('/([A-Z][a-z]*)/',ALfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu,0,3)[31&ord($l)].' ':''; ``` [Try it online!](https://tio.run/##Dc7baoNAEADQX7EgXW3Mjbw1DWEpBYUSIUUCFQkTHXVxdJbJNk3689bn83Jsa8e3vW2thyIsZ0HL4szQBKtwO/62hjDwaeeDNLd8XeT@fTYrQixb9ulppzy192lhBZvz1ZJxgVoGuZ5/FznM/4qXcKki/VnDEW4cg5DBD3Lw3nJ6d8IupTp1SIfKQDaZcwlx0kPSYXrD/oLyVYJoCxlesEx75GRKgh4aPpiapU9KxxKba4ePIzz00CFm9BOtok2Yb9bPLNV0D4vF1HxVajuOY4xE7J1YqPI00T8 "PHP – Try It Online") Output: ``` "Hello World" => "HOtel eCho lIma lIma oScar WHiskey oScar rOmeo lIma dElta" ``` Or **195** bytes, with spaces not fully removed: ``` while($l=$argv[1][$x++])echo$l,preg_split('/([A-Z][a-z]*)/',ALfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu,0,3)[31&ord($l)].' '; ``` [Try it online!](https://tio.run/##Dc7BaoNAEADQX/Eg1W1Mk5BjWoqUgkKJkCKFLhImOrqLo7NMtjbpz1vP7/KccfPzqzMuQBGWs6Bj8Xbs4q06zL/GEsYhvYQg3aR3lQ5vq1WlsDYcUuIEu/PVkfVxtIl1uv6uNKz/qke1iZL0o4UTTJyBkMV38vBmuLh5YV9QW3ikY2OhXMz7nDgfIO@xmHC4oHzWIKmDEi9YFwNyvuQgHTs@2pZlyGvPktlrj/cT3NOxRyzpJ9kme6X3uweWZjmr6ikKosM8zxkScfDFQs0/ "PHP – Try It Online") Output: ``` "Hello World" => "HOtel eCho lIma lIma oScar WHiskey oScar rOmeo lIma dElta" ``` [Answer] # JavaScript, 179 bytes ``` s=>s.match(/\w/g).map(c=>c+'LfaRavoHarlieEltaChoOxtrotOlfOtelNdiaUliettIloImaIkeOvemberScarApaUebecOmeoIerraAngoNiformIctorHiskeyRayAnkeeUlu'.match(/.[a-z]+/g)[parseInt(c,36)-10]) ``` [Try it online!](https://tio.run/##bY7NaoNQEEb3fQp3KlbTUuimGJBSUCgRUlylWYzX8SeOjr13ojEvb920i6bLj3P4OCcYwSjdDOL3XOBCKFYZLibcmqADUbWz@Zw2lbuOwVHhVnn2ewl7GDkGTQ2@kcBrzelFNEtKZSpIu6KBbGUiCXHSQdJiOmKXo/5QoKMBMsxRpR1yglpD1Fe8a0rWXaKEddyYFuc9zFHfImZ0tn9CggP416O31hwG0AaTXhx1//Ts@o8PR3dR3BsmDIgrp3TsGInYmlhTYbuWZ9m2@3L3x7EEjVj/41sbclVgWdXNqaWu5@FLGzmP02W@/j4s3w "JavaScript (Node.js) – Try It Online") [Answer] # TSQL, 313 bytes Golfed: ``` DECLARE @ varchar(max)='Hello World' DECLARE @x INT=len(@)WHILE @x>0SELECT @=stuff(@,@x,1,substring(@,@x,1)+choose(ascii(substring(@,@x,1))%32,'lfa','eta','harlie','elta','cho','oxtrot','olf','otel','ndia','uliett','ilo','ima','ike','ovember','scar','apa','uebec','omeo','ierra','ango','niform','ictor','hiskey','ray','ankee','ulu')+';'),@x-=1PRINT @ ``` Ungolfed: ``` DECLARE @ varchar(max)='Hello World' DECLARE @x INT=len(@) WHILE @x>0 SELECT @=stuff(@,@x,1,substring(@,@x,1)+choose(ascii(substring(@,@x,1))%32, 'lfa','eta','harlie','elta','cho','oxtrot','olf','otel','ndia','uliett','ilo', 'ima','ike','ovember','scar','apa','uebec','omeo','ierra','ango','niform', 'ictor','hiskey','ray','ankee','ulu')+';'), @x-=1 PRINT @ ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/960926/phonetic-alphabet)** Output ends with semicolon [Answer] # PowerShell, 228 225 bytes -3 bytes thanks to @mazzy ``` "$args".ToLower()-replace' '|% T*y|%{$a+=$_+((-split"lfa ravo harlie elta cho oxtrot olf otel ndia uliett ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu")[('a'..'z').IndexOf($_)])+' '};$a ``` [Try it online!](https://tio.run/##FY/RSsNAEEV/5RK2bNbQ/ID4riD4UvBBpEyTSbNkkgmTbW20fntcX@893MuZ9Ytt6Vlk2wpHdl6K@qCv/2kZ9sazUMMe/r7D4WG9734cVU/uWJXlfpklpkI6gtFV0ZNJZLAkQtMr9JZME1Q6aGLB1EbCJSMpIYoijoQ4MPTK44kNS0MGmjPDJ26gI2eGzQg0nRVT7NRGxCapoY/LwGv@XXM5MOfdSxE@Sk@@rv23D/XL1PLtrSvdMXyGKgv8Pjratu05myre1aT9Aw "PowerShell – Try It Online") This is quite possibly the ugliest piece of code I have ever written. In addition, this can certainly get a lot shorter. In my defense, I'm still recovering from final exams. [Answer] # PHP, 212 bytes ``` while($c=ord($argn[$i++]))echo[_,Alpha,Bravo,Charlie,Delta,"Echo",Foxtrot,Golf,Hotel,India,Juliett,Kilo,Lima,Mike,November,Oscar,Papa,Quebec,Romeo,Sierra,Tango,Uniform,Victor,Whiskey,Xray,Yankee,Zulu][$c&31]," "; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/54ab86322e7f3f06011aa3a889cfb8d9442b2a68). Yields warnings in PHP 7.2; put array elements in quotes to fix. Will print an underscore for spaces. [Answer] # [C (clang)](http://clang.llvm.org/), ~~309~~ 283 bytes *-26 bytes thanks to @[ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` *k[]={"lfa","ravo","harlie","elta","cho","oxtrot","olf","otel","ndia","uliett","ilo","ima","ike","ovember","scar","apa","uebec","omeo","ierra","ango","niform","ictor","hiskey","ray","ankee","ulu"};i;main(z,v)char**v;{for(;z=toupper(v[1][i]);i++)z>64&z<92&&printf("%c%s ",z,k[z-65]);} ``` [Try it online!](https://tio.run/##HU5BboMwEPxKZCkICBxatZEqmpzzgx4QB8dZwsqLjYxBjaN8va6Xy854dsY7qlYkzT3GUrfd6Smol6ISTq42wSAdISQC5FlWA6v21zvrmVDP0wMlMDdky5ICnpdI7MWRRdT8iV1hvIJLbFaSQU5bAq6geD3ClgDnWE6l@Gmwt25kXXnLoQFnDY@t42OzaYDt7iJeDTajRJOHai1UKl@Wa/NM@bwJJ2@XaQKXr@1b12JXNHg4FOF8/MjC99d7lk0Oje9zsVf7eSeqUOk21MfPZHzFGC9AZHc/1tHtT/Uk73OspZnxHw "C (clang) – Try It Online") ]
[Question] [ Given a relation, and a domain, output whether the relation is an equivalence relation. ## Context For this challenge, a relation is defined as being a set of ordered pairs that is a subset of the cartesian product of a domain with itself. That is, \$R \subset X \times X\$. For a relation \$R\$ to be an equivalence relation on domain \$X\$, it needs to be: a) reflexive, b) symmetric and c) transitive. If a relation is reflexive, for all items in the relation's domain, the item paired with itself is in the relation. That is: $$ \forall a \in X : (a, a) \in R $$ or as one might write in Python: ``` all([(a, a) in R for a in X]) ``` If a relation is symmetric, for all pairs of items in the relation, the reverse of the pair is also in the relation. That is: $$ \forall a, b \in X : (a, b) \in R \implies (b, a) \in R $$ or as one might write in Python: ``` all([(y, x) in R for x in X for y in X if (x, y) in R]) ``` If a relation is transitive, for all items a, b and c in the relation's domain, `(a, b)` being in the relation and `(b, c)` being in the relation means that `(a, c)` is in the relation. That is: $$ \forall a, b, c \in X : (a, b) \in R \land (b, c) \in R \implies (a, c) \in R $$ or as one might write in Python: ``` all([(x, z) in R for x in X for y in X for z in X if (x, y) in R and (y, z) in R]) ``` ## Worked Example Let the domain of the relation be \${1, 2, 3, 4}\$ and the relation be \${(1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (2, 1), (1, 3), (3, 1), (2, 3), (3, 2)}\$ The relation is reflexive, as \$(1, 1)\$, \$(2, 2)\$, \$(3, 3)\$ and \$(4, 4)\$ are all in the relation. The relation is symmetric, as \$(1, 2)\$ and \$(2, 1)\$ are in the relation, as are \$(1, 3)\$ and \$(3, 1)\$. As are \$(2, 3)\$ and \$(3, 2)\$. The relation is transitive, as \$(1, 2)\$, \$(2, 3)\$, and \$(1, 3)\$ are in the relation. Therefore, the relation is an equivalence relation. ## Rules * The domain can be taken as a list of arbitrary objects (e.g. numbers, strings, a mix of numbers and strings) or any similar format. You do not need to take the domain if you take the relation as an adjacency matrix * The relation can be taken as a list of ordered pairs/tuples, as an adjacency matrix or any other reasonable format. It can not be taken as a function object though. * The domain will not be empty. That is, it will not be \$\emptyset\$ / `{}` * The relation will not be empty. That is, it will not be \$\emptyset\$ / `{}`. * [Default decision-problem output rules apply](https://codegolf.stackexchange.com/tags/decision-problem/info) ## Tests *Assuming the domain is given as a list of integers and that the relation is given as a list of lists* ``` Domain, Relation => Equivalence? [1, 2, 3, 4], [[1, 1], [2, 2], [3, 3], [4, 4]] => 1 [1, 2, 3, 4], [[1, 1], [2, 2], [3, 3], [4, 4], [1, 2], [2, 1], [1, 3], [3, 1], [2, 3], [3, 2]] => 1 [1, 2, 3, 4], [[1, 2], [2, 1], [3, 3]] => 0 [3, 4, 5], [[3, 4], [3, 5], [4, 5]] => 0 [1, 2, 3, 4, 5], [[1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4]] => 0 [1, 2, 3], [[1, 1]] => 0 [1, 2, 3], [[1, 2], [2, 3], [3, 3]] => 0 [1, 2, 3], [[1, 1], [1, 2], [2, 2], [2, 3], [3, 1], [3, 3]] => 0 [1, 2], [[1, 2], [2, 2]] => 0 ``` This is code golf, so aim to get your programs as short as possible. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` δQQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3JbAwP//o6MNdUDQIFYHK8tABwQNY2MB "05AB1E – Try It Online") Takes input as an adjacency matrix. ## Explanation ``` δ double vectorized - for each pair of rows in the adjacency matrix Q check if they are equal Q then check if the matrix produced by that is equal to the original matrix ``` If the input matrix is an equivalence relation, then it's easy to see that two values are equal iff their rows are equal, so the algorithm will return true. Otherwise, since `δQ` returns an equivalence relation, it's impossible for it to be equal to the input. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 95 bytes ``` X*Y:-member(X,Y). X-Y:-forall(X,Y). D+R:-X*D-[X,X]*R,[X,Y]*R-[Y,X]*R,([X,Y]*R,[Y,Z]*R)-[X,Z]*R. ``` [Try it online!](https://tio.run/##lVHNDoIwDL7zFLuYAHbEde7i2SfwNCQcNPEvgWDQxMfHDjsHJGo8fev303bbtW2q5iRvj0vX2TRfyfpQ7w9tbCFPsshKYo5Nu6sqZtbzzUradC0LC7ZMN0CYE8oif9UxE0DEljBxTnfIui6ax4UCgSA0iGUJonClcgfi0CEJ2uHSGUqRZGImVPRvkFAxj@xTrOuQ8zX@GjRq1A/iwKIPOCsI07t9TDPRCyN3aO8zfoJfUYUrmOFkvzKyjqzrsJl/iukOihEZ9Xs3QsO6Yd2wbgZ/MNo9fMA3FSfPrH/0Gn/aNK0@d5kOxIHlvKvu2RM "Prolog (SWI) – Try It Online") Predicate that succeeds if the relation given is an equivalence relation. Call as `+(Domain, Relation)` or `Domain+Relation`. [Answer] # [Python](https://www.python.org) NumPy, 33 bytes ``` lambda M:(M^M.T@M<M.any(0)).all() ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVJBTsMwEJQ45hVLTzbaRrXTSKgiiAvH3HorRXKbRLWUxCFNkMJXuFRC8B6u8Brs1G5oEUicxt6ZnR1v8vxWdc1GlbuXLLp7bZtsfPlxnotilQiIZyS-j_35TXwV-6LsyIRSX-Q5oVb4ntWqgLItqg5kUam6AVHXosO2lA9tik9prbYoksTLVA25LFOQJagqLbXVzAOS4JqigggKUZH0UeRoRP62ymVDRhBdw4hSD1qUWrM3JWucINNF6W83okqjXLtplzHzQGhVP5MQU00o7oHiSqlc9-govmiIQHIh_TnS3qiqZdmQjAhq37X7PLtdMASOECBMlwgLc2XmoGvcoCYCg1MjWJqkzPtXj0Zm69zqmOWDoc_d-R8zjjz6Gb124pmLnhX2QtcR2EJPOOFg6uTO12ViQ-bw-zyXkVueWz4Y8ri3n45nFrnF4BBLY2j50PKh5cPDvofYw7J_IfjJNoPfHY4_y2njzxU78XGXZfe_0xc) Expects adjacency matrix. ### How? First note that arithmetic is boolean, so 1+1=1. The test can only be satisfied if 1. there is no empty column 2. M is symmetric (M=M^T) 3. M is idempotent (M^2=M) together these imply 4. the diagonal of M is set 4 corresponds to "reflexive", 3 to "transitive" and 2 to "symmetric" [Answer] ## [Python 2](https://docs.python.org/2/), 86 bytes ``` lambda X,R:any(R[a][c]<R[a][b]&R[b][c]|R[c][a]|(a==c)for a in X for b in X for c in X) ``` [Try it online!](https://tio.run/##lVCxboMwEN35ipsqkLzYjhdUtnyBJyTiwdCiIKUERVQFJfl2enbPdaBZuvid33v3fL5hHo/nXixtcVhO9qN@s1Ayndt@TnVlTdWYV4@1edF44P2m8UDqltqiaLL2fAELXQ8luLKOZePLbPk6dqd34HnikgEKpIfPMc0S2BfXKb/OeVpNbDbOrn3e7DvvPmX6qRMYLl0/QpuWbJ8tFWcgGEgGO8OgclfuCuSEQxSkw50zmORfdkROvCAfJ13GvnAXz@NX7T4ebc7AQHlPMEsivLCKCs6QFobgcUj1@EoYSpAuSJdxivDZ7cucUBDK34kQFemKdEW6Wu82LvYvJzZLk0/71ovf9jxs8hs "Python 2 – Try It Online") Takes the relation `R` as a two-level dictionary so we can write `R[a][b]` to query whether \$(a,b) \in R\$. Outputs `True/False` inverted. --- ## [Python 2](https://docs.python.org/2/), 55 bytes ``` lambda R:all(R[a]=={a}|R[b]for a in R for b in{a}|R[a]) ``` [Try it online!](https://tio.run/##lZCxboMwEIZ3nuJGkLz4HC9I3vIEniK5HoxaFCRKUERVEOXZqe2eS6BZOv32ff9/Pl8/Dddbh2utXtbWvVevDnTp2jbXxlmlZrd8aVPZ@nYHB00HGsKx8scf5Gyxfl6b9g14mcGFaQDlYf8x5EUGZzWP5TzFzBTiF2hqMCObbGy2RDJGsmTQ35tugDo/F6vhDJCBYHCyDEy48nDwNQzqgQh6Cgab/cvulVMdyceJiy2X7vi8/S4e23tbMDCQ0ZPMggoR7FolZ@qWhuDbkPLxlTQUEkfiYpsiffb4MidFUvE7kVdJXBKXxOV@t9ti/9bwsDTxNLdf/DHzsMlv "Python 2 – Try It Online") Uses a more liberal input format of a dictionary taking each \$a \in X\$ to a set of all \$\{b:(a,b) \in R\}\$. We no longer need to take `X` as input because the keys of the dictionary will do. --- ## [Python 2](https://docs.python.org/2/), 54 bytes ``` lambda R:R=={a:{b for b in R if R[a]==R[b]}for a in R} ``` [Try it online!](https://tio.run/##lZCxjsMgEER7f8WUiUQDhMYSXb6AKhLnAitnxVLOsSJHZ8vytzvALefYl@aqgX2zw7Lt0F1ujZgr/TFf3Vd5djC50Xp0@Viiut1Rom5gUFcw1hVaG1sWUwAugmn@vtTXT/A8w4kZQPty@@h2@wxHPfb5OMSYIbhPIcb2bCh@eiPpI5kytPe66VDtjvvZcgbBIBkOBYMNVx4OviaCeiCDHoKhyP5l98qpLsjHiculL93F@/hVe4z3tmBgUNGTzJIKEayikjOlpSH4MqR6fSUNJYgL4nKZIn12@zInFaTydyKvirgiroir9W6Xxf6tic3S5Nu@9eK3PS@bfAI "Python 2 – Try It Online") Based on [Command Master's solution](https://codegolf.stackexchange.com/a/251632/20260). I/O as above. --- ## [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda M:M==[map(a.__eq__,M)for a in M] ``` [Try it online!](https://tio.run/##lVDNCsIwDL7vKXLcoAhN7UXYI/TiaVDL6NDhQOeUifj0Mx2pc9OLp6/J95M03bM/Xloc6nw3nPy52nswG5Pn9uy71K/K8nAtS2Gy@nIDD00Lxg2PY3M6gNwkUIgtQE7t7t6nWQKGCmutF5UL2i0EWxWehYN3ROES6G5N20OdmmywUgAKUALWTpCdShke1MOARKiA6yBwyV9yQsl9ZJ1kXk2@WOPv@Jl9jCdZEAjQoyaKFTdGYhYVlTEtLiGnJfXnlLgUMo/Mq2mL@NnlZMmIjOq9EaFmXjOvmdfz206H/e7h4mjqp29@@KXn45Iv "Python 2 – Try It Online") A more direct port of [Command Master's solution](https://codegolf.stackexchange.com/a/251632/20260), with input as a adjacency matrix, that is, a list of lists of Booleans. Less golfed: **41 bytes** ``` lambda M:M==[[a==b for b in M]for a in M] ``` [Try it online!](https://tio.run/##lVA9j8IwDN37K94IUpY4ZEHKT8jCVKmXodVRUYkrFSpC/Pqe03MILSw3PdvvI46Hx3i69DS17ms61z/Ndw2/985VVe1cg/ZyRYOuhw@xrP/K6X7qzkfofYFSHQDH4@E2brYFPDcVm1UTovaQE8qAZ0QZCgzXrh/Rbvx2qrQCKRiFXVBs51bHgmcUkQkTcRcFofiXnFHLnESnhTfZl3r6HL@wz/EsiwIFO2uS2MhgJhZRSZnS0hI6L2lfX0lLkfAkvMlbpM@uX9aCJGieGzFa4a3wVni7vG0@7PuMVkczH33Lw689L5f8BQ "Python 2 – Try It Online") [Answer] # [Factor](https://factorcode.org/), 32 bytes ``` [ 3 dupn [ = ] cartesian-map = ] ``` [Try it online!](https://tio.run/##fcgxDsIwDEbhPaf4LwALG4gZdWGpmCoGKzgoauoGxx1K1bMH6AHQWz69QN5Grbe2uV6OeLKwUopvsjhKQc8qnFD4NbF4LsjKZnPWKIaTcwsW2FbA@sdhy75eXe1wwGPKgg5n3OFJjUsk2Q2Uf6d6Sgn7@gE "Factor – Try It Online") Port of @CommandMaster's [05AB1E answer](https://codegolf.stackexchange.com/a/251632/97916) (and so takes an adjacency matrix as input). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` ⁼θEθEθ⁼ιλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1ijUEfBN7EAiYKKZ@oo5GiCgPX//9HR0YY6BjpwHKsTDWEZQESAfEx5qBwIYpXHpz829r9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an adjacency matrix and outputs a Charcoal boolean, i.e. `-` for an equivalence relation, nothing if not. Explanation: Port of @CommandMaster's 05AB1E solution. ``` θ Input matrix ⁼ Is equal to θ Input matrix E Map over rows θ Input matrix E Map over rows ι Outer row ⁼ Is equal to λ Inner row Implicitly print ``` 14 bytes to take input as an adjacency matrix of bit strings for convenience: ``` WS⊞υι⁼υEυ⭆υ⁼ιλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDM6@gtCS4pCgzL11DU1MhoLQ4Q6NURyFT05orAChYouFaWJqYUwwS800sAFEQxVAOVDZTRyFHEwSs//83NDQwMDA05ILRQAIIDbhAPAMwDeGjq/uvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ⁼þ⁼ ``` [Try it online!](https://tio.run/##y0rNyan8//9R457D@4DE/8Ptj5rW/P8fHR1tqKNgAEGxOgrRQNoQhQcVQPBAArEgLkinIUIWHw9dJ6otGC7AZqcBsk5DJIVIqlCUIBQawkxEEkCIoboWXcAQbixGsBjgsNkAq@NQwgwpqJFdGBsbCwA "Jelly – Try It Online") another port of Command Master's 05AB1E answer, so takes an adjacency matrix as input [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 6 bytes ``` ⊢≡∧.=⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//UdeiR50LH3Us17N91Lvif9qjtgmPevsedTUbPmqb/KhvanCQM5AM8fAM5uICMoDSCmkKJkD4qHeLgqGCARRiZWHTYAhWgE7j1AAzD6EIhY3QYAyEMA0oWhBKTIEQoQTVCXjZ2GxBg9gdguxeQ0wlCJdCrUQoMQJChCmG/wE "APL (Dyalog Classic) – Try It Online") Similar to [Command Master's submission](https://codegolf.stackexchange.com/a/251632/6972), but compares each column to each row, instead of pairs of rows. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `2`, 6 bytes ``` v‡$v⁼⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIyQSIsIiIsInbigKEkduKBvOKBvCIsIiIsIltbMSwgMCwgMCwgMF0sIFswLCAxLCAwLCAwXSwgWzAsIDAsIDEsIDBdLCBbMCwgMCwgMCwgMV1dXG5bWzEsIDEsIDEsIDBdLCBbMSwgMSwgMSwgMF0sIFsxLCAxLCAxLCAwXSwgWzAsIDAsIDAsIDFdXVxuW1swLCAxLCAwLCAwXSwgWzEsIDAsIDAsIDBdLCBbMCwgMCwgMSwgMF0sIFswLCAwLCAwLCAwXV1cbltbMCwgMSwgMV0sIFswLCAwLCAxXSwgWzAsIDAsIDBdXVxuW1swLCAxLCAxLCAxLCAxXSwgWzEsIDAsIDEsIDEsIDFdLCBbMSwgMSwgMCwgMSwgMV0sIFsxLCAxLCAxLCAwLCAxXSwgWzEsIDEsIDEsIDEsIDBdXVxuW1sxLCAwLCAwXSwgWzAsIDAsIDBdLCBbMCwgMCwgMF1dXG5bWzAsIDEsIDBdLCBbMCwgMCwgMV0sIFswLCAwLCAxXV1cbltbMSwgMSwgMF0sIFswLCAxLCAxXSwgWzEsIDAsIDFdXSJd) Input as adjacency matrix. Yet another port of Command Master's answer (YAPOCMA). Using a different flag: # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 6 bytes ``` ƛ?v⁼;⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJyQSIsIiIsIsabP3bigbw74oG8IiwiIiwiW1sxLCAwLCAwLCAwXSwgWzAsIDEsIDAsIDBdLCBbMCwgMCwgMSwgMF0sIFswLCAwLCAwLCAxXV1cbltbMSwgMSwgMSwgMF0sIFsxLCAxLCAxLCAwXSwgWzEsIDEsIDEsIDBdLCBbMCwgMCwgMCwgMV1dXG5bWzAsIDEsIDAsIDBdLCBbMSwgMCwgMCwgMF0sIFswLCAwLCAxLCAwXSwgWzAsIDAsIDAsIDBdXVxuW1swLCAxLCAxXSwgWzAsIDAsIDFdLCBbMCwgMCwgMF1dXG5bWzAsIDEsIDEsIDEsIDFdLCBbMSwgMCwgMSwgMSwgMV0sIFsxLCAxLCAwLCAxLCAxXSwgWzEsIDEsIDEsIDAsIDFdLCBbMSwgMSwgMSwgMSwgMF1dXG5bWzEsIDAsIDBdLCBbMCwgMCwgMF0sIFswLCAwLCAwXV1cbltbMCwgMSwgMF0sIFswLCAwLCAxXSwgWzAsIDAsIDFdXVxuW1sxLCAxLCAwXSwgWzAsIDEsIDFdLCBbMSwgMCwgMV1dIl0=) ]
[Question] [ ## Task Given a square array of 0s and 1s, determine whether or not there exists a path of 1s connecting the leftmost and rightmost columns. A path can take steps of one unit up, down, left or right, but not diagonally. Every symbol on the path must be a 1, and it must start somewhere in the first column and end somewhere in the last column. Shortest code in each language wins. ## Examples ``` 000 111 -> True 111 110 110 -> False 110 101 010 -> False 101 0 -> False 1 -> True 11110 00010 01110 -> True 01000 01111 11110 00010 01100 -> False 01000 01111 ``` ## Notes The array may be represented in any reasonable form, such as a list of lists `[[0,0,0],[1,1,1],[1,1,1]]` or a string `'000 111 111'`. Optionally it can be in transposed form (so that the roles of rows and columns are exchanged); equivalently the code can instead determine whether there is a top-bottom connection. Any two distinct symbols can be used in place of 0 and 1. The output can be in any truthy/falsy form. [Answer] # MATLAB/Octave, ~~115~~ ~~109~~ 98\* bytes *-6 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)* *-7 bytes thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)* ``` function p=f(A) B=A;B(:,2:end)=0;for k=1:nnz(A) B=conv2(B,mod(magic(3),2),'same').*A;end p=any(B); ``` [Try it online!](https://tio.run/##jY9NDoMgEEb3nIKd0JgGUGsiYaHXaLog/jSmEUxLTdrL20Fro13JbHjM4xuwpdNDPY7N05SutQb3qiE5RYXKZUGyUGS1qahisrF3fFM8M@Y990trBkGKsLMV6fS1LUlEQ0HD4KG7OqDHQy7hKuqVNi9SUDkCSeQ4VvjMMBTC0@K@1vsLaojjFDnhVX@0Vjf7SRWgRrPKfklso7JvagRqDCrzEAMkANxDAnBa5q3nTE/d8H@f4/V3lv488ASx6f5YtjM2peMH "Octave – Try It Online") (`end` keyword is in footer because it's not required when you define the function in a file) Takes binary array, outputs: * *truthy* value as vector full of logical ones * *falsy* value as vector having some logical zeros Such unconsistent *falsy* was suggested by [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) and confirmed as valid by as [aeh5040](https://codegolf.stackexchange.com/users/104303/aeh5040). For consistent true/false logical output replace `any(B)` with `all(any(B))`. \*for MATLAB it's possible to skim 3 bytes by replacing `'same'` with `'s'`. #### Ungolfed: ``` function path = f(A) B = A; % copy of A B(:, 2:end) = 0; % zero everything besides 1st column mask = mod(magic(3),2); % mask for making "steps" % equal to: [0 1 0 % 1 1 1 % 0 1 0]; for k=1:nnz(A) % max number of necessary steps is amount of 1s in A % uses 2D convolution of B with m, takes only central part of size of B B = conv2(B,mask,'same'); % makes "step" in every direction B = B.*A; % filters only valid steps end path = any(B); % check if each column has any value != 0 % if returned vector is full of 1s each column contains nonzero value % which mean there is a path between both sides end ``` #### Explaination ###### How 2D convolution works? If we have array like so: ``` 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 ``` and a mask ``` 0 1 0 1 1 1 0 1 0 ``` we can imagine convolution of array with mask as taking a mask and placing it on top (so that position of corner is the same) of every cell of array and multiplying it with value of that cell - such operation for one cell gives us one array. And then we sum all of the arrays. In our example: ``` 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 + 0 0 0 0 0 + 0 0 0 1 0 = 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 | | | | V V V V 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 0 0 1 2 2 1 1 0 0 0 1 0 0 0 0 0 + 0 0 1 0 0 0 0 + 0 0 0 1 1 1 0 = 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Also, in our case because we were using argument `'same'` we were taking only "central" part of result, so because mask was 3x3 we need to cut off sum of 2 columns and 2 rows from the result. To make it even we're cutting first and last rows and are left with: ``` 2 2 1 1 0 1 1 1 1 1 0 0 0 1 0 ``` ###### How we are making "steps"? Having our input array: ``` 1 1 1 1 0 0 0 0 1 0 0 1 1 1 0 0 1 0 0 0 0 1 1 1 1 ``` We're taking first column: ``` 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` then by convolution with our "step" pattern: ``` 0 1 0 1 1 1 0 1 0 ``` we're selecting cells where we could make step from all current/past positions: ``` 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` but since we only can move where 1s are in input array we filter valid positions by multiplying arrays elementwise: ``` 1 1 0 0 0 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 .* 0 1 1 1 0 = 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 ``` and so we made 1st "step". Then again - convolution to select positions where we can move and filter out result: ``` 1 1 0 0 0 2 2 1 0 0 2 2 1 0 0 0 0 0 0 0 convolution 1 1 0 0 0 multiplication 0 0 0 0 0 0 0 0 0 0 ==> 0 0 0 0 0 ==> 0 0 0 0 0 0 0 0 0 0 steps 0 0 0 0 0 filtering 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` Notice we're getting values other than 1, but that doesn't matter - positive numbers will produce only more positive numbers, so we care only if something is 0 or something greater. So, we continue, next step: ``` 2 2 1 0 0 4 5 3 1 0 4 5 3 1 0 0 0 0 0 0 2 2 1 0 0 0 0 0 0 0 0 0 0 0 0 ==> 0 0 0 0 0 ==> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` and so on, we continue making steps, finally reaching such state: ``` 15511 26324 29964 27016 0 0 0 0 20240 0 0 3080 6853 12804 0 0 1143 0 0 0 0 340 77 12 1 ``` with 1 in final column, meaning we've reached the right side. [Answer] # [J](http://jsoftware.com/), 48 bytes ``` _1{0{1([:+./ .*^:_~1>:|@-/~)@($j./@#:I.@,)@,~1,] ``` [Try it online!](https://tio.run/##fU6xCsJADN3vK0IV6uk1TRwjlQNBEJxci3YQi3ZQB51a@uu111bkBB1eEl5e8l7RBBjmkAiEYIBAWkQIq9123WRcUsmTVGYYA04PktW8lMpGca3tZFxgbEeyQWu0NTWbfaPV5Xp/PtpnqUAlEGBAC8zmSp2O5xvk0K2dCykiUszcQQ8CgsQXMX/wW0SsiPvuiwwCDQS/CfYIz8u5tLFc7Wd2Id38N6J3Rl9nzQs "J – Try It Online") Takes a binary matrix, and checks for a top-to-bottom path. Hence, the input pre-processor transposes the test cases. ## the idea * Add a row of ones to the top and bottom. * Convert all ones to coordinates, encoded as complex numbers. * Create an adjacency matrix for those points, with adjacency defined as "euclidean distance is <= 1". * Self "multiply" that matrix to a fixed point, where the addition part of the matrix multiplication is boolean "or". * The top row will now be connected to the bottom row iff the upper right entry in the matrix is a 1. * So return that entry. [Answer] # [R](https://www.r-project.org/), ~~138...~~ 118 bytes -9 bytes thanks to Dominic van Essen. ``` function(m,k=nrow(m),r=m,`/`=cbind){r[,-1]=0 for(i in m)r=r|m&r[,-1]/0+0/r[,-k]+t(t(r[-1,])/0+0/t(r[-k,])) any(r[,k])} ``` [Try it online!](https://tio.run/##lY7RCsIwDEXf/Yo@Scoy1iL61i8Zhc1poYx2Eioq6rfXblMo0xcJLTnJzeVSNCqas@@CHTw47JWn4QKOIymHTdWobm/9gd@pxlJqJVZmILDMeuY4KXq49bypRCGqse11ESAA1aVEzafxRH0ivmr9LQH2mj@jAdcGslfoQKBMlf0cN0mdKeh4Aom7lCs1YtwiW0jm0@wtTMZJhhKZ/DaY65NFZoY5vVUpw/ZfC/HLIr4A "R – Try It Online") At first, the matrix `r` contains only the `1`s of the first column of the input `m`; all other entries are `0`. At iteration `i` of the loop, entries which are attainable in at most `i` steps become non-0. This is done by incrementing the cells for which both of these conditions hold: (1) the value is 1 in `m` and (2) the value of one of its neighbours is non-0 in `r`. A less golfy but more readable version of the command in the for loop would be ``` r = r | ( m & (cbind(r[,-1],0) | cbind(0,r[,-k]) | rbind(r[-1,],0) | rbind(0,r[-k,]))) ``` Note that using `+` instead of some of the `|` allows to omit the brackets, thanks to R's operator precedence (`+` before `&` before `|`). The length of the path to reach the rightmost column is bounded by `k^2`, where `k` is the side length of the input. After `k^2` iterations (i.e. the number of elements of `m`), we check whether there any non-0 values in the rightmost column of `r`. [Answer] # [Haskell](https://www.haskell.org/), 96 bytes ``` e=[]:e (2:l)%1=2:2:l l%x=x:l h a=any(>=[2])$foldl(zipWith(%))e`iterate`map(2:)a!!(sum(2<$a)^2+2) ``` [Try it online!](https://tio.run/##ZY/BTsMwDIbveQozbVoiNEh6rJZdkLgA4gASh1Eg0rwlWppGbSp1iHcfboFRwcVxP/v/mljT7NH74xH1usiR8Sz3YqZ0llPD/KzTHZ0WjDbhwFd6nRViuq38xvN3F59csnwmBL65hLVJ@FaaSAphzs5405Y8W06NeMnOM3GMpja72kTbAJ8/h3k@lE6AhnUBOYzmHRsvd/lBwAfYPC0XI36gIM2syNN4nVwkXBcFY6VxQW8qBrCD5QJ2mK6qkDCkhtDWuwh027tX4KP4TsAUniMsVjAkATwmcCG2iby0D3woNZrNRWxrFHAByezxyTqPwC/1HOail3gXsIF4clRt@pL0UZqXpnNlWw4dCTd1FUHJv0mKPKT6NhB2W7A/N9E/umQxwOT@ZgLoG4TJtXF@cpRSMqUU5ekd8Fi32H8yKj2X3/zaUGRgTEnF5N8BMdajMWTqBAZt7yUB/bCvff87IyS/oPq3J@VIOlr8BA "Haskell – Try It Online") Similarly to other answers, this "flood-fills" the input with `2`s and checks if we reach the right edge. `l%x` acts like `x:l`, but if `l` starts with a `2` and `x` is `1`, then `x` is replaced by a `2` also. `foldl(zipWith(%))e` is then a function that rotates a list of rows 90° while making 2s "spread into" 1s, using our infectious flipped-cons operator. This is based on the [shorter transpose](https://codegolf.stackexchange.com/a/111362/3852) trick: Using `foldl` instead of `foldr` rotates the array instead of transposing it. We start from `map(2:)a` (append a column of 2s on the left), and apply `foldl(zipWith(%))e` \$4\,\mathrm{length}(a)^2+2\$ times. This is enough iterations to flood-fill even the twistiest of paths, and also turns the input upside-down. Then we check if any upside-down row starts with a two using `any(>=[2])`. The \$4\,\mathrm{length}(a)\$ part of the iteration count is computed as \$\left( \sum\_{x \in a} 2 \right)^2\$. Thanks to xnor for contributing lots of good ideas! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes ``` +þ2ŒRBU¤ẎQfðƬṪ ŒṪḷ/Ị$Ƈç$Ḣ€iL ``` [Try it online!](https://tio.run/##y0rNyan8/1/78D6jo5OCnEIPLXm4qy8w7fCGY2se7lzFdXQSkHy4Y7v@w91dKsfaDy9Xebhj0aOmNZk@/x/u3hIGZAFR1OH2//8NgcCAy8DAAERC2IZAHphtCAA "Jelly – Try It Online") -2 bytes thanks to caird coinheringaahing -2 bytes using transposed form Returns 0 for falsy and non-zero for truthy Uses the exact same breadth-first-fill helper link as my answer to "But, Is It Art?" ``` +þ2ŒRBU¤ẎQfðƬṪ Helper Link; given a list of starting coordinates on the left and a list of accessible coordinates on the right, fill ðƬ Repeat until results are no longer unique +þ Product table by addition of the current coordinates and 2ŒRBU¤ As a nilad: 2ŒR - [-2, -1, 0, 1, 2] B - Binary: [[-1, 0], [-1], [0], [1], [1, 0]] U - Reverse Each: [[0, -1], [-1], [0], [1], [0, 1]] Ẏ Tighten; dump the product table into a flat list of coordinates Q Remove duplicates f Filter to only keep valid coordinates (based on the right side) Ṫ Tail; get the last list (the breadth-first-filled list of coordinates) ŒṪḷ/Ị$Ƈç$Ḣ€iL Main Link; take a binary matrix ŒṪ Convert to a list of filled coordinates $ Call this monad on this list of coordinates: ç - Call the helper link, with the following on the left: $Ƈ - The list of coordinates, filtered to keep elements where: ḷ/ - The first element (the row coordinate) Ị - Is insignificant (in inclusive range [-1, 1]) Ḣ€ Get the row of each filled coordinate i Index of (0 if not found) L The length of the matrix (height) ``` Essentially, this just starts at every position in the top row, fills, and sees if it reaches the bottom row. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~42~~ 36 bytes A slower ~~but maybe golfable?~~ version. After looking at [Jonah's J answer](https://codegolf.stackexchange.com/a/229661/64121) I was able to remove 6 bytes. ``` gÅ1¸.øεā*0K€¸<Nδš}€`DδαO2‹DvDδ*O}нθĀ ``` [Try it online!](https://tio.run/##yy9OTMpM/X9o2aEVjxrmcXEdWnhuqzqQfNS0JvjwDpf/6YdbDQ/t0Du849zWI41aBt5A8UM7bPzObTm6sBbITnA5t@XcRn@jRw07XcqAbC3/2gt7z@040vD/v5KSEpeBgQGXoaEhGAMJAzjmMjQw5DIAcYA0F4gPEgKqBooBCZAMkAfRBBIE84GGGIDUgIyDKwIKAm36r6ubl6@bk1hVCQA "05AB1E – Try It Online") --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 42 bytes A lot of this is similar to [this recent answer](https://codegolf.stackexchange.com/a/229136/64121) of mine. Tests for a top-bottom connection. ``` εā*0K€¸<Nδš}D€gU€`DδαO2‹DvDδ*O}Xθ.£øOXн£OĀ ``` [Try it online!](https://tio.run/##yy9OTMpM/X9o2aEVjxrmcXEdWnhuqzqQfNS0Jvjwjv/nth5p1DLwBvIO7bDxO7fl6MJaFyAnPRRIJLic23Juo7/Ro4adLmVAtpZ/bcS5HXqHFh/e4R9xYe@hxf5HGv7/V1JS4jIwMOAyNDQEYyBhAMdchgaGXAYgDpDmAvFBQkDVQDEgAZIB8iCaQIJgPtAQA5AakHFwRRCTDaEawGoNIcZA2JjSBqjSQHf@19XNy9fNSayqBAA "05AB1E – Try It Online") Header transposes the input to test left-right connections. This is quite long because of missing builtins for *all indices of* and matrix operations. High-level explanation: `εā*0K€¸<Nδš}` get all indices of 1's. `€gU` store the number of 1's in each row in variable `X`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 24 [bytes](https://github.com/abrudz/SBCS) Uses the same method as [Jonah's J answer](https://codegolf.stackexchange.com/a/229661/64121). Full program that detects top-bottom connections. ``` ⊃⌽⌈.×⍣≡⍨2>+/¨|∘.-⍨⍸1⍪⎕⍪1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jruZHPXsf9XToHZ7@qHfxo86Fj3pXGNlp6x9aUfOoY4aeLpD7qHeH4aPeVY/6pgJJQ5C@/2lcj3o7QQJtE4wVjBUe9W5RMFAwBEIkEqhkDRcWhYZI0AAEcSs0QMXoCkEmgK3GJYGhw0TBBG40BGJlEdJmiJVlgF@bIVyDIXZbTBVMsTgOEVSYPANKDULzNwA "APL (Dyalog Unicode) – Try It Online") Footer transposes inputs. ``` 1⍪⎕⍪1 ⍝ the input matrix with additional rows of 1's at the top and bottom ⍸ ⍝ get all 2d indices of 1's |∘.-⍨ ⍝ table of absoulute element-wise differences +/¨ ⍝ sum each pair of absoulte differences 2> ⍝ values of 1 or 0 mark adjacent (or same) 1's ⌈.×⍣≡⍨ ⍝ "matrix multiplication" until convergence. Instead of summing values we take the maximum to keep everything as 0 or 1 ⌽ ⍝ reverse each row of the matrix ⊃ ⍝ take the very first number of the matrix ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 81 bytes ``` Max[Intersection@@MorphologicalComponents[#,CornerNeighbors->False][[{1,-1}]]]>0& ``` Solves the transpose problem, looking for connections between the top and bottom rows. The long-named overkill builtin `MorphologicalComponents[#,CornerNeighbors->False]` changes the `1`s in the input to different integers shared by connected groupings (where we must override the default that diagonal connections count); then we simply look to see if there's a positive integer in common in the first and last rows. Someone should translate this into [Sledgehammer](https://github.com/tkwa/Sledgehammer).... [Answer] # [Python 3](https://docs.python.org/3/), ~~135 127~~ 123 bytes Answering my own question since there is no python solution yet. Expects a transposed matrix. Strongly inspired by [Lynn's rotation method](https://codegolf.stackexchange.com/a/229664/104303). I'm sure there is room for improvement! ``` def f(x): x+=[[3]*len(x)] for _ in x*4*len(x):x=[map(lambda a,b:a|a*2&b,y,(0,*y))for y in zip(*x)][::-1] return 3in x[0] ``` [Try it online!](https://tio.run/##ZVDbasQgEH33KyQPu@raZWz6JORLrBTDJlTIuqIWzNJ/T520bCkVZjjOmTlziWt5v4V@2y7TTGdWuSa0ngZjeiuWKbSAJXS@JfpGfaBVvPxEdR3M1UW2uOt4cdTJUbtPJ54Po1wlAylWzrFsxbK7j0w0JaP1k2p6aSofKdAeFQ3Y7T50XUcAgCildmsOHkYUKAL4AWQIwZBCppWg/8YKBRCrfzT8pbEbwekqTmfM4nNhuI0PRSbO94XTY/J8ziU1wM85Lr6w42s4cm73rLxn/RJI2XbD9mJqcgxvyrcv "Python 3 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~21~~ ~~20~~ ~~19~~ 18 bytes *Translation of [@elementiro's MATLAB/Octave answer](https://codegolf.stackexchange.com/a/229648/36398), with small modifications*. The input is a binary matrix (using `;` as row separator). The output is either a row vector with all entries eqwual to `1` (which is truthy), or a row vector with at least one entry eqwual to `0` (which is falsy). The footer contains the truthiness/falsihood test. ``` O4LZ(Gz:"2Y6Z+G*]a ``` [Try it online!](https://tio.run/##y00syfn/39/EJ0rDvcpKySjSLErbXSs28b@9AgyoKmSmKZTkFyjkA6mMVIXiksTkbIXMYoWSotKSjEoudQitDlJZUFqcAVQElCwuKcrMS@eqRTImNac4lUs9LTGnGKQYm@pYZNV5Kf@jDRUg0MBawQAMoUwkUUOIDELUMBYA) Or [verify all test cases](https://tio.run/##hVDBSsQwEL3nKwZBKiqlK@JBDyIIexG87MUuBcM2bQbTpCRTdQW/vSbdBHNwMXN44eW9mcwbOKn5FdI5hdaUZfkhUYkSNhIdKGNGIOHIAVcKUI8Tufn5@qk@W3/dnly93NQX6/OGP8z3WRvsgLzPeJACHPHdG/hmZCeSe1YcsAjKcXLSi/yjI4u6Z99ZG6GcYEXHlQviv9RNrtYte8x3QTcqvmf15y9nhRMEozW95UP4GAm2yTyHAXZK64dP@w2WFHZGt0ho9CX4hHYSenwXPhbtU@lQI0XdpAkVaBPD8jMHjnreVuDrDlahIjRsGzCyCRa2CqIqsdWiXV6iJxqWpumasSuI4xL7n6866vsB). [Answer] # JavaScript (ES7), ~~103 101~~ 94 bytes Expects a transposed binary matrix. Returns **0** or **1**. ``` f=(m,X,Y=-1)=>!m[Y+1]|m.some((r,y)=>r.some((v,x)=>v&&(X-x)**2+(Y-y)**2<2|!y&&--r[x]|f(m,x,y))) ``` [Try it online!](https://tio.run/##ZU/BboMwDL3zFWkPNC4kSnrd6G37gV6KKAdEA2WCpEsYAo19O3O6ad20g@33/OwX56UYClfa5tozbc5qWaqEdvExThMmIdmvuiyNZD533JlOUWrjCbv2mw3xiGwIQ3pkI2y3u4imbPLgcTevpjBkzGZjPldoOeImwGLV61tjFd1UbgPcquL83LTqMOmSCuC9OfS20TUF7q5t09P1SZ/0Gnhl7FNRXqgjyZ68B4R0JCFZ/oDI3Ud/DeKlZIpJAX4h45zb/K4NMRlvAu3wPHS6lXlGR8gK3ipd9xfCiMSYvB4NAP6t0mhnWsVbU1P8lG9@wCKECKSUt8AkfiKQQgbCE6yB5173Cq74/IWlN/D4vyz@yJ8 "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: m, // m[] = input matrix X, Y = -1 // (X, Y) = current position, starting with ) => // X undefined and Y = -1 !m[Y + 1] | // success if we've reached the last row m.some((r, y) => // for each row r[] at position y in m[]: r.some((v, x) => // for each value v at position x in r[]: v && // abort if v = 0 (X - x) ** 2 + // if the squared distance between (Y - y) ** 2 < 2 | // (x, y) and (X, Y) is less than 2 !y // or y = 0 (see the note below): && // --r[x] | // clear r[x] f(m, x, y) // do a recursive call ) // end of inner some() ) // end of outer some() ``` **Note**: Any cell at \$(x,0)\$ with a \$1\$ on it is considered to be a valid destination square, no matter what the current position is, which may result in an invalid move. But if we start a path from \$(x\_0,0)\$, suddenly jump to \$(x\_1,0)\$ and find an apparently invalid solution, it just means that we could have started from \$(x\_1,0)\$ and find a valid solution. [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 65 bytes ``` / /;$,="(.{@-})?";s/^1/#/gm;1while s/#$,\K1|1(?=$,#)/#/s;$_=/#$/m ``` [Try it online!](https://tio.run/##ZYzBCsIwEETv@QppcmghdXcETyHUu78geipaSG1oBA/qrxuzCoJ4mNmZfezGfg7rnEmRM9ZX9fK2aR9NV7lEe5Cm4@hwPQ2hXyTSxu62uKPuvLG6KTQ5c/BlT2POzKwAvFWMv1JgKJZSppIuXEg5Ef9kyAPJ/5h/8HOKl2E6p9wyB8YqvgA "Perl 5 – Try It Online") `-00l012` options are just used to run all tests and to print result. `/\n/` to match first end of line, to get the width `$,="(.{@-})?";` to define the variable `$,` with expression that matches the line width characters (used to match a character above or below another `s/^1/#/gm` to replace all `1` in the first column with `#` `1while s/#$,\K1|1(?=$,#)/#/s` while a `1` is found (below, on the right, on the left or above a `#`, replace with `#` `$_=/#$/m` result is: is there a `#` in the last column [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` WS⊞υ⭆⪫11ι℅¬Iκ⪫υ¶←¤-J⁰¦⁰T¹ ``` [Try it online!](https://tio.run/##JYzBCoMwEETvfkXIaQMpJNd6FAqVWoR67CVIWkNjInFjPz9d6xyGecPujJNJYzS@lO/kvGVwDUvGByYX3iAE6/M6QZbsaDqzQBtdAK41l8wJyRoaMCPaBPeI0JgV4SN21VVPL3jc0wJ/Br63XdwsnG/2hQQX5z3wE6fY5nkZIijJFNGQ3Axa1KVokqqUUrsfWRP9s67KafM/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings (-3 bytes to take a input as a cumbersome array of strings: [Try it online!](https://tio.run/##RYzBCsIwEETv/Yqwpw2kkL3aY8FDsSLYW@0hhKqBtKkx9vfjVlDnNO/BjL2baIPxOZ@imxM2wc3YmgUfSpwTq9sGHwtEoISTStQ8MjaNEY8hYW2eCb3cogRcZpCyKtqwjrg7jNfEsHfeI5TAtXlNSxdQK6GZuugmJFnl3Pd8T6ShEAq01t/2d8T25wiGIZerfwM "Charcoal – Try It Online")) and outputs a Charcoal boolean, i.e. `-` if a path exists, blank if not. Explanation: ``` WS⊞υ⭆⪫11ι℅¬Iκ ``` Wrap each line in `1`s. This changes the condition to requiring a path from the top left to the bottom right corner. The `1`s and `0`s are then changed to null and non-null bytes. ``` ⪫υ¶ ``` Print the non-null bytes. (Null bytes erase rather than printing.) ``` ← ``` Move to the bottom right corner. ``` ¤- ``` Try to fill with `-`s. ``` J⁰¦⁰T¹ ``` Delete everything except the top right corner, which will have been filled with `-` if there is a path and left erased if not. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḣ1ŒṪạÆịỊẸʋƇ@ƬŒṪ=LḄỊȦ ``` A monadic Link that accepts a list of the columns (i.e. transposed version of the OP's examples) and yields `1` (no connection) or `0` (connection). **[Try it online!](https://tio.run/##y0rNyan8///hjsWGRyc93Lnq4a6Fh9se7u5@uLvr4a4dp7qPtTscWwOWsfV5uKMFKHxi2f///6OjDXUUgMgAgmK5dKIhPIiwIYqAAULAEEXAAG4AWCAWAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjsWGRyc93Lnq4a6Fh9se7u5@uLvr4a4dp7qPtTscWwOWsfV5uKMFKHxi2f@jkx/uXPyocd@hbUC49eHuLWGPmtYAUdThds3//w0MDLgMDQ3BGEgYwDGXoYEhlwGIA6S5QHyQPEgGqAVEQtiGIANAbExpAxRpAA "Jelly – Try It Online"). ### How? Builds up all coordinates reachable from the first column by repeatedly adding those within a unit circle of any found so far, then checks if any of these coordinates is in the final column by virtue of their column coordinate being equal to the total number of columns. ``` ḣ1ŒṪạÆịỊẸʋƇ@ƬŒṪ=LḄỊȦ - Link: List of lists, Columns ḣ1 - head to index 1 (first column wrapped in a list) ŒṪ - multi-dimensional truthy indices (of that) -> X ŒṪ - multi-dimensional truthy indices (of Columns) -> Y Ƭ - start with X and collect until no change, applying: @ - with swapped arguments: Ƈ - filter keep those (coordinates, c, in Y) for which: ʋ - last four links as a dyad - f(c,X): ạ - (c) absolute diference (X) (vectorises) Æị - from [Real, imaginary] to complex (vectorises) Ị - absolute value <= 1? (vectorises) Ẹ - any? =L - equals length(M)? (vectorises) Ḅ - convert from binary (vectorises) Ị - absolute value <= 1? (vectorises) Ȧ - any and all? (0 if 0 present when flattened else 1) ``` [Answer] # JavaScript, 85 bytes ``` A=>f=(i=0,X=0,Y=-1)=>Y<0||A[Y][X]?(A+0)[i]&&[2,1,0,-1].map(t=>f(i+1,X+t--%2,Y+t%2)):0 ``` Slow. Error if possible. Treating all area Y<0 as solid and try walking enough time, error if it goes Y>Ymax(`A[Y]` is `undefined`) [Try it online!](https://tio.run/##LU/bjoIwEH3vVxATdSZA0/q4bNnwsPgBvkiQaIPF7YZt3VJMjPLtLKtOMpecnDln5lteZFc7ffaxsUc15mLMRNoI0IJF2ykLEXMUafHO7vesLKpyW31AFjIsdbVYlKuIRyyKeUV/5Bn8tAo65NE29HE8X0VF6OcrxDc2JmQtmt7UXlsDGd5IEHh3veXTDJg45XtnApYMtfT1Fyi8vSCeDGQgTv322ilYNt0SqVPymOtWba6mBobU24132pwAaXdutYfZzuzMDGlj3aec5LpApMG/ZW1NZ1tFW3uCNXRP@mFnDo/z9yItKaX75zPqIlucIiEDjowQTgh7FE44ezTG/wA) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` .+ 1$&2 +`(?<=(.)*)(1|2)((?>.*¶(?<-1>.)*))?(?!\2)[12] 2$+2 ^2 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5vLUEXNiEs7QcPexlZDT1NLU8OwxkhTQ8PeTk/r0DagqK6hHUhY017DXjHGSDPa0CiWy0hF24grzuj/f0MgMOAyMDAAkRC2IZAHZhsCAA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ 1$&2 ``` Wrap each row between a `1` and a `2`. ``` +`(?<=(.)*)(1|2)((?>.*¶(?<-1>.)*))?(?!\2)[12] 2$+2 ``` Repeatedly find pairs of `1`s and `2`s either horizontally or vertically adjacent and replace them both with `2`s. This will hopefully find a path from the right-hand column of `2`s through the input and end up filling the whole left-hand column of `1`s. ``` ^2 ``` Check whether a path was found. ]
[Question] [ In the MMORPG Final Fantasy XIV, the Ninja class has the ability to use combinations of up to three handsigns (Ten, Chi and Jin) to perform a variety of ninjutsu skills. The skill you cast depends on the last sign used, and using two or more of the same sign makes the ninjutsu skill fail and [puts a little bunny on your head](https://external-preview.redd.it/P1Z4Ux5iuAM8HiiX1YcOXetj_Zhp6qR9DSD4JiSsE0U.jpg?auto=webp&s=2215b323234c063590efdc85b3d0c67b4e89f3ad). ## Challenge Your job is to take up to three handsigns as input, and output the name of the ninjutsu skill this combination does. Of course, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the goal is to make your code as short as possible! ## Input The program should take between 1 and 3 handsigns as input via STDIN or function arguments. You can use any kind of input format you prefer. Example inputs: ``` TCJ Ten Chi Jin ["T", "C", "J"] ["Ten", "Chi", "Jin"] ``` ## Output The program should output the name (in title case) of the ninjutsu skill you get from the handsigns sent to it via input. Here's a table of each combination and their resulting skill. Mudra table: ``` | Handsigns | Ninjutsu Skill | |-------------------------------|----------------| | Any one | Fuma Shuriken | | Any one + Ten | Katon | | Any one + Chi | Raiton | | Any one + Jin | Hyoton | | Any two + Ten | Huton | | Any two + Chi | Doton | | Any two + Jin | Suiton | | Contains two of the same sign | Bunny | ``` Bunny takes precedence over any other ninjutsu. ## Examples ``` TCJ -> Suiton J -> Fuma Shuriken ['Ten', 'Chi'] -> Raiton "Jin" "Jin" "Ten" -> Bunny ``` ## Leaderboards 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 ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=218805; var OVERRIDE_USER=45220; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;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="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><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] # JavaScript (ES6), 95 bytes *A shorter version suggested by @tsh* Expects `[1,2,3]` for `"TCJ"`. ``` (a,b,c)=>a^b&&a^c&&b^c?',Hu,Do,Sui,Hyo,Rai,Ka'.split`,`[c||7-b]+'ton':b?'Bunny':'Fuma Shuriken' ``` [Try it online!](https://tio.run/##TU5da8IwFH33V9yF0SQYg7KHgaOKcw5xD8L0TVp6m7YzribF2jFZ/e1do4z5ci6cr3t2@IWlOuji2DM2SZvMbxiKWCjujzCMPQ9D5XlxqMZUzCvxYsWq0mJ@suIdtXhDKssi18dIRBtV14@9OOjSozV0GI/pc2XMiQ7pa7VHWG2rg/5MDW0m4MOGEAFk7WDqYEGCp85EZvYwQ7VlCP6oA4DgefDPxlcWbij1RwG0cl3DXXu6oDh3UWVNafNU5vaDRez@h5X99je2hqtJFpjMTMIe@JmDkwdumpSy7Adyj8WlHgispwsitUnS72XG2m4ud1YbRultA/RGbUfGXHzAzxG/7HLIO7z5BQ "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 99 bytes Expects `"012"` for `"TCJ"`. ``` s=>/(.).?\1/.test([,b,c]=s)?'Bunny':b?'Hu,Do,Sui,Hyo,Rai,Ka'.split`,`[c||5-b]+'ton':'Fuma Shuriken' ``` [Try it online!](https://tio.run/##TU5dT4MwFH3fr7gSs7ZZKVuMLzNA5pxZ5oOJ8w1JKKVsKLaEgnEZ@@1YXIx7OTc5H/ecd/7FjaiLqnGVzmSf@73xAw8zwsK3mccaaRoc0ZSK2DckRPetUgc0T0O0bumDptu2oOuDpi@8oE8cMVOVRZPQJBJdd@um8QQ1WqE5emw/OWz3bV18SIX6BfgQOQ4F53WA5QAbJ74bLViu6xUXe8zBD0YAHMZj@GfTMwsXlPijAKzcdXBlzwQEIUNUaGV0KVmpdzjB10dsprabW8PZxCqerVSGb8iJwCDPrGymrJZVyYXEHvN2FIYOu3W5cVihMvn9nGP7/zIMbmDjuc2TU0J@9wxIRqT/AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string /(.).?\1/ // regex to detect a duplicate character .test([, b, c] = s) // apply it to s; at the same time, load the 2nd // and 3rd characters into b and c respectively ? // if there's a duplicate: 'Bunny' // return 'Bunny' : // else: b ? // if the 2nd character is defined: 'Hu,Do,Sui,Hyo,Rai,Ka' // lookup string of prefixes .split`,` // split it [c || 5 - b] // use c if it's defined, or 5 - b otherwise + 'ton' // append the suffix : // else: 'Fuma Shuriken' // return 'Fuma Shuriken' ``` [Answer] # [R](https://www.r-project.org/), ~~153~~ ~~149~~ ~~144~~ 139 bytes *Edit: -5 bytes thanks to Giuseppe* ``` function(x)`if`(any(table(x)>1),'Bunny',`if`((l=sum(x|1))-1,a[l*3-6+x[l]],'Fuma Shuriken'));a=paste0(scan(,''),'ton') Ka Rai Hyo Hu Do Sui ``` [Try it online!](https://tio.run/##bY/BasMwEETv@gpBD5JaBSIJekhxD00Iob01vYVAFGMTtc4q2Fqwof/uippSI/s281azO6p7cPCJocGsLxHy4DzwVpxceeIWOh7suSoieFZCshcE6Jj8HfIqa/DK228lxEJJe6juzeLxoT1Ux6NkW7xaur9g7b4KYEI82exmm1AseZNb4JKxuC74OCJvlrxbR3adJzskG0/26Eh/Rx3cMKyooqWvKfuIayTVg1lfXDRmMK8O2Ir8/YIr8a/1SJuRzrmSsfYY6BSYFCip04hOIzqNmDRi0sgE6Gk1M1Nu5tYU6WmBmU7Dq/4H "R – Try It Online") Input is `1` for 'Ten', `2` for 'Chi', `3` for 'Jin'. **Ungolfed:** ``` a=paste0(scan(,''),'ton') # scan(,'') reads the subsequent strings until it finds an empty one, Ka # paste0 joins them each together with 'ton'. Rai Hyo Hu Do Sui function(x){ if(any(table(x)>1))'Bunny' # if there are any duplicates: 'Bunny' else{ # otherwise l=length(x) # define l=length of x (the R golfy way: sum(x|1) because 'length' is 6 letters) if(l-1)a[l*3-6+tail(x,1)] # if it isn't length 1, output the relevant element from the vector 'a' of ninjutsu names else'Fuma Shuriken' # otherwise (it's length 1): 'Fuma Shuriken'. } } ``` ``` [Answer] # x86-16 machine code, IBM PC DOS, ~~102~~ 101 bytes ``` 00000000: b409 ba38 0149 742d ba46 0151 51ac 8bfe ...8.It-.F.QQ... 00000010: f2ae 59e0 f759 741d 49ac 7402 0403 2c30 ..Y..Yt.I.t...,0 00000020: 8ad0 b024 b116 bf4b 01f2 aefe ca75 fa8b ...$...K.....u.. 00000030: d7cd 2103 d1cd 21c3 4675 6d61 2053 6875 ..!...!.Fuma Shu 00000040: 7269 6b65 6e24 4275 6e6e 7924 4b61 2452 riken$Bunny$Ka$R 00000050: 6169 2448 796f 2448 7524 446f 2453 7569 ai$Hyo$Hu$Do$Sui 00000060: 2474 6f6e 24 $ton$ ``` **Listing:** ``` B4 09 MOV AH, 9 ; DOS display $-terminated string syscall ; STEP 1 - check if input is only 1 char BA 0138 MOV DX, OFFSET FAM ; default output is Fama 49 DEC CX ; is only 1 char? 74 2D JZ DONE ; if so, output is Fama ; STEP 2 - check if input has duplicate chars BA 0147 MOV DX, OFFSET BUN ; next default output is Bunny 51 PUSH CX ; save original input length DUP_LOOP: 51 PUSH CX ; save loop position AC LODSB ; load next char into AL 8B FE MOV DI, SI ; start search at current char F2 AE REPNZ SCASB ; and search for AL 59 POP CX ; restore loop position E0 F7 LOOPNZ DUP_LOOP ; end loop if there was a match 59 POP CX ; restore original length 74 1D JZ DONE ; had a dup? output is Bunny ; STEP 3 - use last char to get correct name 49 DEC CX ; ZF if two chars, NZ if three chars AC LODSB ; load last char into AL 74 02 JZ FIND_NAME ; is three chars? 04 03 ADD AL, 3 ; if so, offset array index by 3 FIND_NAME: 2C 30 SUB AL, '0' ; ASCII convert input 8A D0 MOV DL, AL ; set number of delimiters to find B0 24 MOV AL, '$' ; set delimiter char to find ('$') B1 16 MOV CL, 22 ; length of name array BF 014C MOV DI, OFFSET NAM-1 ; pointer to name array SCAN_LOOP: F2 AE REPNZ SCASB ; search until delimiter found FE CA DEC DL ; decrement counter 75 FA JNZ SCAN_LOOP ; loop until end of counter 8B D7 MOV DX, DI ; move found pointer to DX CD 21 INT 21H ; write name prefix to STDOUT 03 D1 ADD DX, CX ; advance to start of suffix string DONE: ; STEP 4 - display string at DX CD 21 INT 21H ; write output string to STDOUT C3 RET ; return to caller ; Strings and Things FAM DB 'Fuma Shuriken$' ; if one char BUN DB 'Bunny$' ; if duplicate chars NAM DB 'Ka$','Rai$','Hyo$' ; name prefix array DB 'Hu$','Do$','Sui$' ; delimited by $ TON DB 'ton$' ; name suffix ``` Callable function, input as string at `[SI]`, length in `CX` where `Ten` = `1`, `Chi` = `2` or `Jin` = `3`. Output to DOS STDOUT. Test program output: [![enter image description here](https://i.stack.imgur.com/LOUTm.png)](https://i.stack.imgur.com/LOUTm.png) [Answer] # [Haskell](https://haskell.org), ~~116~~ 109 bytes *saved 7 bytes thanks to @ovs, and obscure things in the stdlib (why is `word` but not `split` in Prelude?)* ``` n[_]="Fuma Shuriken" -- matches a list of one element n(a:b)|a`elem`b="Bunny" -- matches a list starting with a where a is in b `| `(cond)` =` is a guard that checks cond n[a,b]=words"Ka Rai Hyo Ho Do Sui"!!b++"ton" -- !! is indexing, ++ is appending n[a,b,c]=n[b+3,c+3] -- don't mistake n[] as indexing, it's calling n with a list. -- b+3 so it will still catch duplicates where b=c ``` Highly readable (IMO), and highly not PHP (sorry PHP). This makes excessive use of pattern matching. It takes input as a list of Ten=0, Chi=1, Jin=2. Trailing whitespace and comments (starting with --) are not counted. [ideone it!](https://ideone.com/Sck456) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~54~~ ~~52~~ 51 bytes -3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! Takes a string of first letters of the handsigns. A list of integers could probably save a byte. ``` ÙÊi'åƒë.•!˜Œ¾Ë₂Γ∍Ÿ¾µÓ•#…ton«ι.•E‹ØÁó+±Æ•¸šÁIgèI3öè}™ ``` [Try it online!](https://tio.run/##AWsAlP9vc2FiaWX//8OZw4ppJ8OlxpLDqy7igKIhy5zFksK@w4vigoLOk@KIjcW4wr7CtcOT4oCiIyfDj8K3wqvOuS7igKJF4oC5w5jDgcOzK8Kxw4bigKLCuMWhw4FJZ8OoSTPDtsOofeKEov//VA "05AB1E – Try It Online") or [Try all possible cases!](https://tio.run/##S0oszvifnFiiYGOj4OrvpmCnkJyfkqqXmJT6//DMw12Z6oeXHpt0eLXeo4ZFiqfnHJ10aN/h7kdNTecmP@roPbrj0L5DWw9PBsopqx/uP7T90OpzO0EqXR817Dw843Dj4c3ahzYebgOKHNpxdOHhRs/0wys8jQ9vO7yi9lHLov9A@7i40vKLFDIVMvMUqkN0nHW8amE0di6U4krJ51JQSE3OyFfQzVNQUslU0LVTUAIK6ecXlOjnFycmZaZCKbh/gD60UVDJBGrNS/0PAA) **Commented**: ``` Ù # deduplicate the input Ê # is this different from the input? i # if this is the case 'åƒ '# push compressed string "bunny" ë # else: .•!...Ó• # push compressed string "rai do hyo sui ka hu" # # split on spaces …ton« # append "ton" to each word ι # rearrange the words into two lists # [["raiton", "hyoton", "katon"], ["doton", "suiton", "huton"]] .•E...Æ• # push compressed string "fuma shuriken" ¸ # wrap into a list š # prepend to the other list Á # rotate this list right # [["doton", "suiton", "huton"], ["fuma shuriken"], ["raiton", "hyoton", "katon"]] Ig # take the length of the input è # index into the list of lists I # push the input again 3ö # convert from base 3 è # modularly index into the list }™ # after the if/else: titlecase each word ``` [Answer] # [PHP](https://php.net/), 106 bytes Inspired by [640KB's answer](https://codegolf.stackexchange.com/a/218815/100869). Expects input as `123` ``` fn($s)=>$s[1]?max(count_chars($s))>1?Bunny:[Ka,Hu,Rai,'Do',Hyo,Sui][$s[-1]*2-!$s[2]-1].ton:'Fuma Shuriken' ``` [Try it online!](https://tio.run/##XZFfT4MwFMXf9ym6hmRgyiLTp01cYnUuncmM8oZkabAT4mwbKMn88uJlG9c/D4TDveeeH7e1hW2v5rawg4G3jdut9r06iK@9Oo2y@Yfc@7lptNvkhazqrhVcR/ObRuvPabqSbNmwJ1my0a0ZseWnYc9NmaUwG0bZ2SQcgppkoMfO6Olo0XxI8lw0Vfmu9KidAbHUtnEkJmpvd@ZV@ZRR5snqTQezgVepGlre1q9dtamU3clc@SlNwMThETRjacQm7CJjp6D0PAtgUuWFIccSVMiYnAKUdD4llJHLECo7Bbv2piAAGw0JhZd/JMcx6WOjjMwJXa@GBAxTQhey3A3pYYTc7a3KnXqdHmZ/TUDzxd0bd2p0mWPyuHzc3K0fZm3C/hzHgP/7Fv@@k4Qdjh3Ej@KoRK94dyFw3KDQx9HHRXdFh7boLuyo0Cg4uz3V@kBIWcmuxJHLkcsTzEMGRy7/VcM4xHLALpujQh9iRY8ViBVJ/3cC1xW4ruB9nECsQOxPLi4rkCr67pexrjS6bsPFNw "PHP – Try It Online") ### Explanation ``` fn($s)=> $s[1]? // check if 2nd char of input is present max(count_chars($s))>1? // count chars, check if any are present more than once 'Bunny' // input has duplicates : // input does not have duplicates [Ka,Hu,Rai,'Do',Hyo,Sui] // array of possible results [$s[-1]*2-!$s[2]-1] // find correct index of result // takes last char of input, multiplied by 2, // minus boolean value based on input length // finally adjust index by -1 .'ton' // and add suffix : 'Fuma Shuriken' // input length was 1 ``` [Answer] # [PHP](https://php.net/), ~~139~~ ~~133~~ 128 bytes ``` fn($s)=>($l=strlen($s))>1?max(count_chars($s))>1?Bunny:[T=>[Ka,Hu],C=>[Rai,'Do'],J=>[Hyo,Sui]][$s[-1]][$l%2].ton:'Fuma Shuriken' ``` [Try it online!](https://tio.run/##NchBa8IwGMbx@/spcshoC1HQo64V9qqUbDCZuZUgobSmWJPQNDC//LI42On5PX@nXXzdOe0AaF/G3uTUF2WV07H08zR2f7@oVru7@s5bG8x8abWa/H9@C8Y8No0oq@ZdsTpIholfamDZ3maS8fTqh2XnMEjZUN8sVs8dX9ZyOVuzyY7hrshZh2m4dSaLW4Cu1ZbQPidUTVdDCkZO9ely@PzYRgQOAlCAQBAckCfxRExOlT@dukidI6aGP9bNgzU@Lo6/ "PHP – Try It Online") ### Explanation ``` fn( $s ) => ( $l = strlen( $s ) ) > 1 ? // is input longer than one char? max( count_chars( $s ) ) > 1 ? // has more than 1 of any single char? 'Bunny' // if so, contains dupes so... Bunny it is : // else, no dupes [ 'T' => [ 'Ka', 'Hu' ], // two dimensional associative 'C' => [ 'Rai', 'Do' ], // array containing handsign 'J' => [ 'Hyo, 'Sui' ] // and length as indexes ] [ $s[-1] ] // access array by last letter and [ $l % 2 ] // length mod 2 (2 == 0, 3 == 1) . 'ton' // and append "ton" : // finally... 'Fuma Shuriken' // input length was only one char ``` And combining some ideas from [Cray's golfier answer](https://codegolf.stackexchange.com/a/218828/84624), and taking input as `1, 2, 3`, gets it down to **111** bytes (Cray's is still shorter though): ### [PHP](https://php.net/), 111 bytes ``` fn($s)=>$s[1]?max(count_chars($s))>1?Bunny:[0,[Hu,Ka],['Do',Rai],[Sui,Hyo]][$s[-1]][!$s[2]].ton:'Fuma Shuriken' ``` [Try it online!](https://tio.run/##FcxRa8MgEMDxdz@FC0ISsGPp3tq1gbqV4AYrq28iQUJSw1YVjbB@@bnrw3E//gfnjc8vrTceITLt8mQrEuvdnkTZqPaqf6vBJbv0g9Eh3k/1vmkPydrbRj5R2SX6rhWV5asr6Zeegec00@7mlJLwY9XAfgCslXpcnN2Ux3TV@GxSmL9HW@YtQuNgHCZTheMS@jD6Hz2MlSxEQQsGwwt42tA1fVaU6HCxuMY1xafu1L99fmwzQxwJxAQSDAmOGAdxIAND5XdDF9A5Y9DYn/PL7GzMq@M/ "PHP – Try It Online") [Answer] # [J](http://jsoftware.com/), 84 79 bytes ``` ('Bunny';'Fuma Shuriken';,&'ton'&.>Ka`Rai`Hy`Hu`Do`Sui){~({:+1 1 4{~#)@}.*]-:~. ``` [Try it online!](https://tio.run/##hZBNT4NAEIbv/Io3mnSKwsaqJyqGlKZBajy03EwTSN2WtXExZTeGEPnrCNEiJCYe5vLMzDMfr/UZox1cBwQLV3CasBn81eOiHtNMS1nQlBb6LcE61Udx4JKm1ohUJmnE7pdJvEpEHBRxoON5Fq@1MMtqXDqXE0xwW1bnpvfJLja2U7HaNJ5mDA/yXSuo5MBzCKn4nh9zfAiVgstt9iLk3mlar3EDFxF8hIaheK5cduc9w273jPyQsPMEw8Yw@DbN8LMo2kJQFNFf2A/DEx/e8523HPL/yXf9y6S9/@TtxjWv6PGo0wVFH3eWQPdw@KuZZ4PyTtM8d6APqf4C "J – Try It Online") Takes 1, 2, 3 as inputs, mapping to T, C, J, respectively. * `('Bunny';'Fuma Shuriken';,&'ton'&.>Ka`Rai`Hy`Hu`Do`Sui)` creates the word list and was the least satisfactory part of the golf, despite some effort. It produces: ``` ┌─────┬─────────────┬─────┬──────┬─────┬─────┬─────┬──────┐ │Bunny│Fuma Shuriken│Katon│Raiton│Hyton│Huton│Doton│Suiton│ └─────┴─────────────┴─────┴──────┴─────┴─────┴─────┴──────┘ ``` * `{~` From that, select the following index: * `(...)@}.` First remove the first element and... * `{:+1 1 4{~#` Take the last element `{:` of what remains (crucially, this will be 0 for the empty list, i.e., one element inputs) and add to it 1, 1, or 4, depending on if the length is 0, 1, or 2. * `*]-:~.` Multiply that result by 1 if the unique of the input `~.` matches the input `]-:`, and 0 otherwise. This ensures inputs with duplicates always have 0 index and return bunny. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` ¿⊙θ⊖№θιBunny¿⊖Lθ⁺§⪪§⪪”↶/⊟≡⧴№K5G⁰⁺jM✂⎚Σ”χLθ ℅§θ±¹ton¦Fuma Shuriken ``` [Try it online!](https://tio.run/##XY7NCsIwEIRfZckphQr23FO1SP1Bi/UFQrvaYLqxaSL26WMK/uEeFmZ2Z/jqVphaC@W9PAPPaOR9DDnWBjskiw1fakd2MmUUBkojg2QLRzSyKAVUA8IU/c3skC625f03UCo38MyuqcEHr25K2j/FtgKOQkIx6sJBrqFyksWQzKMYvnUxMGBhH0wjSahPR8Db40VY5MlEGd6sJha9@V7QK9cJqFpn5BXDNfX@tNz42V09AQ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of initials. Explanation: ``` ¿⊙θ⊖№θιBunny ``` If any of the characters appear more than once then print "Bunny". ``` ¿⊖Lθ⁺§⪪§⪪”↶/⊟≡⧴№K5G⁰⁺jM✂⎚Σ”χLθ ℅§θ±¹ton ``` If the length is more than one then look up the appropriate prefix from either "Ka Rai Hyo" or "Hu Do Sui" (depending on the length) split on spaces and indexed by the ordinal of the last character, concatenated with "ton". ``` ¦Fuma Shuriken ``` But if the length is 1 then just print "Fuma Shuriken". [Answer] # [Lua (LuaJIT)](https://luajit.org/), ~~170~~ 167 bytes ``` r={'Rai','Hyo','Sui','Ka','Hu','Do'}t={'Fuma Shuriken',CT=4,JT=4,JC=1,TC=1,CJ=2,TJ=2,CJT=5,JCT=5,JTC=6,TJC=6,CTJ=3,TCJ=3}print(t[#i]or t[i]and r[t[i]]..'ton'or'Bunny') ``` [Try it online!](https://tio.run/##Hcw9C8IwEIDh3V9RcLgW0kD9qFMWIyJ1s91Kh6AtntZEQjIU6W@Ply4Px73HjV7lo1cvdGEQg9d3h0anmAUrfnBTCAwukyFrH@erigtPnAzMjm7O/qOS@uktvnsNTDZix6oFKQrWRGQlNqyJSCp7KovUSlpHJdUtHZPz16J2qWvX2BmbuBY7pR@JbePUcQ7OaDAWjl7rCbLQU8zzojyshpRznoVAb/4 "Lua (LuaJIT) – Try It Online") [Answer] # Perl 5, 120 bytes ``` /(.).?\1/ and$_="Bunny";s/^.$/Fuma Shuriken/;s/..J/Suiton/;s/..C/Doton/;s/..T/Huton/;s/.J/Hyoton/;s/.C/Raiton/;s/.T/Katon/ ``` It's everybody's favorite thing: a bunch of regular expressions sitting in a row. Run with `perl -lapE '<the above code>'` First, we deal with the bunny case, by checking if any character appears twice and simply replace the string with "Bunny" in that case. Next, we check if there's exactly one character and replace with "Fuma Shuriken". Beyond that, we simply brute force the remaining options with regular expressions. Finally, if the resulting string does not end in n or y (i.e. it's not "Bunny" or "Fuma Shuriken"), then we add "ton" to the end. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~214~~ ~~208~~ ~~207~~ ~~205~~ ~~203~~ ~~201~~ ~~188~~ ~~186~~ ~~180~~ 177 bytes ``` $s=$args[0];if($s[1]){if($s|% t*y|group|% c*|?{$_-ne1}){'Bunny'}else{@{'T'=('Ka','Hu');'C'=('Rai','Do');'J'=('Hyo','Sui')}["$($s[-1])"][$s.length%2]+'ton'}}else{'Fuma Shuriken'} ``` [Try it online!](https://tio.run/##Jc1BC4IwHAXwryIy@atlZFeRIiOkbulNJEYsldYmzhEy99nXrNt7v8N7Pf@QQbSEUmOQSBEeGlFt66R7@khUcR2oX5o9ZwynuRm47G1@hPNeoXvESKwDBUfJ2ASaUEHUQUEJqQ9XDGvIJQQJZEu/4c7CiS9wWSCfuIVCdhDoykXLXWT/3LpCYkMJa8bW29UrGDkD/d@Gs3xjp2jl0L2IVWNMVn4B "PowerShell – Try It Online") Thanks @640KB for the forkable PHP answer. Cheers folks, help me to reduce the size! (Please manually pass the argument, for test I have passed "CT", it worked and others worked too ;-) Last -3 bytes thanks to @mazzy ]
[Question] [ The goal is simple: **calculate the [totient function](http://en.wikipedia.org/wiki/Totient_function)** for as many numbers as you can in **10 seconds** and **sum the numbers.** You must print your result at the end and you must actually calculate it. No automated totient function is allowed, but bignum libraries are. **You have to start at 1 and count up all the integers consecutively. You are *not* allowed to skip numbers.** Your score is **how many numbers your program can calculate on your machine / how many my program can calculate on your machine**. My code is a simple program in C++ (optimizations off), hopefully you can run it. Important properties you could use! * if `gcd(m,n) = 1, phi(mn) = phi(m) * phi(n)` * if `p` is prime, `phi(p) = p - 1` (for `p < 10^20`) * if `n` is even, `phi(2n) = 2 phi(n)` * others listed in first link My code ``` #include <iostream> using namespace std; int gcd(int a, int b) { while (b != 0) { int c = a % b; a = b; b = c; } return a; } int phi(int n) { int x = 0; for (int i=1; i<=n; i++) { if (gcd(n, i) == 1) x++; } return x; } int main() { unsigned int sum = 0; for (int i=1; i<19000; i++) // Change this so it runs in 10 seconds { sum += phi(i); } cout << sum << endl; return 0; } ``` [Answer] # Nimrod: ~38,667 (580,000,000/15,000) This answer uses a pretty simple approach. The code employs a simple prime number sieve that stores the prime of the smallest prime power in each slot for composite numbers (zero for primes), then uses dynamic programming to construct the totient function over the same range, then sums the results. The program spends virtually all its time constructing the sieve, then calculates the totient function in a fraction of the time. It looks like it comes down to constructing an efficient sieve (with the slight twist that one also has to be able to extract a prime factor for composite numbers from the result and has to keep memory usage at a reasonable level). Update: Improved performance by reducing memory footprint and improving cache behavior. It's possible to squeeze out 5%-10% more performance, but the increase in code complexity is not worth it. Ultimately, this algorithm primarily exercises a CPU's von Neumann bottleneck, and there are very few algorithmic tweaks that can get around that. Also updated the performance divisor since the C++ code wasn't meant to be compiled with all optimizations on and nobody else did it. :) Update 2: Optimized sieve operation for improved memory access. Now handling small primes in bulk via memcpy() (~5% speedup) and skipping multiples of 2, 3, and 5 when sieving bigger primes (~10% speedup). C++ code: 9.9 seconds (with g++ 4.9) Nimrod code: 9.9 seconds (with -d:release, gcc 4.9 backend) ``` proc handleSmallPrimes(sieve: var openarray[int32], m: int) = # Small primes are handled as a special case through what is ideally # the system's highly optimized memcpy() routine. let k = 2*3*5*7*11*13*17 var sp = newSeq[int32](k div 2) for i in [3,5,7,11,13,17]: for j in countup(i, k, 2*i): sp[j div 2] = int32(i) for i in countup(0, sieve.high, len(sp)): if i + len(sp) <= len(sieve): copyMem(addr(sieve[i]), addr(sp[0]), sizeof(int32)*len(sp)) else: copyMem(addr(sieve[i]), addr(sp[0]), sizeof(int32)*(len(sieve)-i)) # Fixing up the numbers for values that are actually prime. for i in [3,5,7,11,13,17]: sieve[i div 2] = 0 proc constructSieve(m: int): seq[int32] = result = newSeq[int32](m div 2 + 1) handleSmallPrimes(result, m) var i = 19 # Having handled small primes, we only consider candidates for # composite numbers that are relatively prime with 31. This cuts # their number almost in half. let steps = [ 1, 7, 11, 13, 17, 19, 23, 29, 31 ] var isteps: array[8, int] while i * i <= m: if result[i div 2] == 0: for j in 0..7: isteps[j] = i*(steps[j+1]-steps[j]) var k = 1 # second entry in "steps mod 30" list. var j = 7*i while j <= m: result[j div 2] = int32(i) j += isteps[k] k = (k + 1) and 7 # "mod 30" list has eight elements. i += 2 proc calculateAndSumTotients(sieve: var openarray[int32], n: int): int = result = 1 for i in 2'i32..int32(n): var tot: int32 if (i and 1) == 0: var m = i div 2 var pp: int32 = 2 while (m and 1) == 0: pp *= 2 m = m div 2 if m == 1: tot = pp div 2 else: tot = (pp div 2) * sieve[m div 2] elif sieve[i div 2] == 0: # prime? tot = i - 1 sieve[i div 2] = tot else: # find and extract the first prime power pp. # It's relatively prime with i/pp. var p = sieve[i div 2] var m = i div p var pp = p while m mod p == 0 and m != p: pp *= p m = m div p if m == p: # is i a prime power? tot = pp*(p-1) else: tot = sieve[pp div 2] * sieve[m div 2] sieve[i div 2] = tot result += tot proc main(n: int) = var sieve = constructSieve(n) let totSum = calculateAndSumTotients(sieve, n) echo totSum main(580_000_000) ``` [Answer] ### Java, score ~24,000 (360,000,000 / 15,000) The java code below does calculation of the totient function and the prime sieve together. Note that depending on your machine you have to increase the initial/maximum heap size (on my rather slow laptop I had to go up to `-Xmx3g -Xms3g`). ``` public class Totient { final static int size = 360000000; final static int[] phi = new int[size]; public static void main(String[] args) { long time = System.currentTimeMillis(); long sum = 0; phi[1] = 1; for (int i = 2; i < size; i++) { if (phi[i] == 0) { phi[i] = i - 1; for (int j = 2; i * j < size; j++) { if (phi[j] == 0) continue; int q = j; int f = i - 1; while (q % i == 0) { f *= i; q /= i; } phi[i * j] = f * phi[q]; } } sum += phi[i]; } System.out.println(System.currentTimeMillis() - time); System.out.println(sum); } } ``` [Answer] # Nimrod: ~2,333,333 (42,000,000,000/18,000) This uses an entirely different approach from my previous answer. See comments for details. The `longint` module can be found [here](https://bitbucket.org/behrends/nimlongint). ``` import longint const max = 500_000_000 var ts_mem: array[1..max, int] # ts(n, d) is defined as the number of pairs (a,b) # such that 1 <= a <= b <= n and gcd(a,b) = d. # # The following equations hold: # # ts(n, d) = ts(n div d, 1) # sum for i in 1..n of ts(n, i) = n*(n+1)/2 # # This leads to the recurrence: # ts(n, 1) = n*(n+1)/2 - sum for i in 2..n of ts(n, i) # # or, where ts(n) = ts(n, 1): # ts(n) = n*(n+1)/2 - sum for i in 2..n of ts(n div i) # # Note that the large numbers that we deal with can # overflow 64-bit integers. proc ts(n, gcd: int): int = if n == 0: result = 0 elif n == 1 and gcd == 1: result = 1 elif gcd == 1: result = n*(n+1) div 2 for i in 2..n: result -= ts(n, i) else: result = ts(n div gcd, 1) # Below is the optimized version of the same algorithm. proc ts(n: int): int = if n == 0: result = 0 elif n == 1: result = 1 else: if n <= max and ts_mem[n] > 0: return ts_mem[n] result = n*(n+1) div 2 var p = n var k = 2 while k < n div k: let pold = p p = n div k k += 1 let t = ts(n div pold) result -= t * (pold-p) while p >= 2: result -= ts(n div p) p -= 1 if n <= max: ts_mem[n] = result proc ts(n: int128): int128 = if n <= 2_000_000_000: result = ts(n.toInt) else: result = n*(n+1) div 2 var p = n var k = 2 while k < n div k: let pold = p p = n div k k += 1 let t = ts(n div pold) result = result - t * (pold-p) while p >= 2: result = result - ts(n div p) p = p - 1 echo ts(42_000_000_000.toInt128) ``` [Answer] **C#: 49,000 (980,000,000 / 20,000)** <https://codegolf.stackexchange.com/a/26800> "Howard's code". But modified, phi values are computed for odd integers. ``` using System; using sw = System.Diagnostics.Stopwatch; class Program { static void Main() { sw sw = sw.StartNew(); Console.Write(sumPhi(980000000) + " " + sw.Elapsed); sw.Stop(); Console.Read(); } static long sumPhi(int n) // sum phi[i] , 1 <= i <= n { long s = 0; int[] phi; if (n < 1) return 0; phi = buildPhi(n + 1); for (int i = 1; i <= n; i++) s += getPhi(i, phi); return s; } static int getPhi(int i, int[] phi) { if ((i & 1) > 0) return phi[i >> 1]; if ((i & 3) > 0) return phi[i >> 2]; int z = ntz(i); return phi[i >> z >> 1] << z - 1; } static int[] buildPhi(int n) // phi[i >> 1] , i odd , i < n { int i, j, y, x, q, r, f; int[] phi; if (n < 2) return new int[] { 0 }; phi = new int[n / 2]; phi[0] = 1; for (j = 2, i = 3; i < n; i *= 3, j *= 3) phi[i >> 1] = j; for (x = 4, i = 5; i <= n >> 1; i += x ^= 6) { if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1; for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2) { if (phi[j >> 1] == 0) continue; q = j; f = i ^ 1; while ((r = q) == i * (q /= i)) f *= i; phi[y >> 1] = f * phi[r >> 1]; } } for (; i < n; i += x ^= 6) // primes > n / 2 if (phi[i >> 1] == 0) phi[i >> 1] = i ^ 1; return phi; } static int ntz(int i) // number of trailing zeros { int z = 1; if ((i & 0xffff) == 0) { z += 16; i >>= 16; } if ((i & 0x00ff) == 0) { z += 08; i >>= 08; } if ((i & 0x000f) == 0) { z += 04; i >>= 04; } if ((i & 0x0003) == 0) { z += 02; i >>= 02; } return z - (i & 1); } } ``` New score: **61,000** (1,220,000,000 / 20,000) In "App.config" I had to add "gcAllowVeryLargeObjects enabled=true". ``` static long sumPhi(int n) { int i1, i2, i3, i4, z; long s1, s2, s3, s4; int[] phi; if (n < 1) return 0; phi = buildPhi(n + 1); n -= 4; z = 2; i1 = 1; i2 = 2; i3 = 3; i4 = 4; s1 = s2 = s3 = s4 = 0; if (n > 0) for (; ; ) { s1 += phi[i1 >> 1]; s2 += phi[i2 >> 2]; s3 += phi[i3 >> 1]; s4 += phi[i4 >> z >> 1] << z - 1; i1 += 4; i2 += 4; i3 += 4; i4 += 4; n -= 4; if (n < 0) break; if (z == 2) { z = 3; i4 >>= 3; while ((i4 & 3) == 0) { i4 >>= 2; z += 2; } z += i4 & 1 ^ 1; i4 = i3 + 1; } else z = 2; } if (n > -4) s1 += phi[i1 >> 1]; if (n > -3) s2 += phi[i2 >> 2]; if (n > -2) s3 += phi[i3 >> 1]; if (n > -1) s4 += phi[i4 >> z >> 1] << z - 1; return s1 + s2 + s3 + s4; } static int[] buildPhi(int n) { int i, j, y, x, q0, q1, f; int[] phi; if (n < 2) return new int[] { 0 }; phi = new int[n / 2]; phi[0] = 1; for (uint u = 2, v = 3; v < n; v *= 3, u *= 3) phi[v >> 1] = (int)u; for (x = 4, i = 5; i <= n >> 1; i += x ^= 6) { if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1; for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2) { if (phi[j >> 1] == 0) continue; q0 = j; f = i ^ 1; while ((q1 = q0) == i * (q0 /= i)) f *= i; phi[y >> 1] = f * phi[q1 >> 1]; } } for (; i < n; i += x ^= 6) if (phi[i >> 1] == 0) phi[i >> 1] = i ^ 1; return phi; } ``` [Answer] # Python 3: ~24000 (335,000,000 / 14,000) My version is a Python port of [Howard's algorithm](https://codegolf.stackexchange.com/a/26800/20998). My original function was a modification of an algorithm introduced in this [blogpost](http://abhisharlives.blogspot.fi/2013/03/euler-totient-function-in-3-ways.html). I'm using Numpy and Numba modules to speed up the execution time. Note that normally you don't need to declare the types of the local variables (when using Numba), but in this case I wanted to squeeze the execution time as much as possible. Edit: combined constructsieve and summarum functions into a single function. C++: 9.99s (n = 14,000); Python 3: 9.94s (n = 335,000,000) ``` import numba as nb import numpy as np import time n = 335000000 @nb.njit("i8(i4[:])", locals=dict( n=nb.int32, s=nb.int64, i=nb.int32, j=nb.int32, q=nb.int32, f=nb.int32)) def summarum(phi): s = 0 phi[1] = 1 i = 2 while i < n: if phi[i] == 0: phi[i] = i - 1 j = 2 while j * i < n: if phi[j] != 0: q = j f = i - 1 while q % i == 0: f *= i q //= i phi[i * j] = f * phi[q] j += 1 s += phi[i] i += 1 return s if __name__ == "__main__": s1 = time.time() a = summarum(np.zeros(n, np.int32)) s2 = time.time() print(a) print("{}s".format(s2 - s1)) ``` [Answer] Here is my Python implementation that seems to be able to crank out ~60000 numbers in 10seconds. I am factorizing numbers using the pollard rho algorithm and using the Rabin miller primality test. ``` from Queue import Queue import random def gcd ( a , b ): while b != 0: a, b = b, a % b return a def rabin_miller(p): if(p<2): return False if(p!=2 and p%2==0): return False s=p-1 while(s%2==0): s>>=1 for _ in xrange(10): a=random.randrange(p-1)+1 temp=s mod=pow(a,temp,p) while(temp!=p-1 and mod!=1 and mod!=p-1): mod=(mod*mod)%p temp=temp*2 if(mod!=p-1 and temp%2==0): return False return True def pollard_rho(n): if(n%2==0): return 2; x=random.randrange(2,1000000) c=random.randrange(2,1000000) y=x d=1 while(d==1): x=(x*x+c)%n y=(y*y+c)%n y=(y*y+c)%n d=gcd(x-y,n) if(d==n): break; return d; def primeFactorization(n): if n <= 0: raise ValueError("Fucked up input, n <= 0") elif n == 1: return [] queue = Queue() factors=[] queue.put(n) while(not queue.empty()): l=queue.get() if(rabin_miller(l)): factors.append(l) continue d=pollard_rho(l) if(d==l):queue.put(l) else: queue.put(d) queue.put(l/d) return factors def phi(n): if rabin_miller(n): return n-1 phi = n for p in set(primeFactorization(n)): phi -= (phi/p) return phi if __name__ == '__main__': n = 1 s = 0 while n < 60000: n += 1 s += phi(n) print(s) ``` [Answer] φ(2n) = 2n − 1 Σ φ(2i) = 2i − 1 for i from 1 to n First, something to find times: ``` import os from time import perf_counter SEARCH_LOWER = -1 SEARCH_HIGHER = 1 def integer_binary_search(start, lower=None, upper=None, big_jump=1): if lower is not None and lower == upper: raise StopIteration # ? result = yield start if result == SEARCH_LOWER: if lower is None: yield from integer_binary_search( start=start - big_jump, lower=None, upper=start - 1, big_jump=big_jump * 2) else: yield from integer_binary_search( start=(lower + start) // 2, lower=lower, upper=start - 1) elif result == SEARCH_HIGHER: if upper is None: yield from integer_binary_search( start=start + big_jump, lower=start + 1, upper=None, big_jump=big_jump * 2) else: yield from integer_binary_search( start=(start + upper) // 2, lower=start + 1, upper=upper) else: raise ValueError('Expected SEARCH_LOWER or SEARCH_HIGHER.') search = integer_binary_search(start=1000, lower=1, upper=None, big_jump=2500) n = search.send(None) while True: print('Trying with %d iterations.' % (n,)) os.spawnlp( os.P_WAIT, 'g++', 'g++', '-Wall', '-Wextra', '-pedantic', '-O0', '-o', 'reference', '-DITERATIONS=%d' % (n,), 'reference.cpp') start = perf_counter() os.spawnl(os.P_WAIT, './reference', './reference') end = perf_counter() t = end - start if t >= 10.1: n = search.send(SEARCH_LOWER) elif t <= 9.9: n = search.send(SEARCH_HIGHER) else: print('%d iterations in %f seconds!' % (n, t)) break ``` For the reference code, for me, that’s: > > … > > Trying with 14593 iterations. > > 64724364 > > 14593 iterations in 9.987747 seconds! > > > Now, Haskell: ``` import System.Environment (getArgs) phiSum :: Integer -> Integer phiSum n = 2 ^ n - 1 main :: IO () main = getArgs >>= print . phiSum . (2^) . read . head ``` It makes something with 2525224 digits in 0.718 seconds. And now I’m just noticing @Howard’s comment. [Answer] # Matlab: 1464 = 26355867/ 18000 I can't test your code so I divided by 18000 as it represents the fastest computer of those who tested. I came to the score using this property: * if p is prime, phi(p) = p - 1 (for p < 10^20) I mostly like that it is a one liner: ``` sum(primes(500000000)-1) ``` [Answer] # Python 2.7: 10.999 (165975/15090) # Pypy 2.3.1: 28.496 (430000/15090) Some interesting methods I use: **Rabin-Miller Strong Pseudoprime Test** - A primality test that provides an efficient probabilistic algorithm for determining if a given number is prime **Euler's product formula** - The product is over the distinct prime numbers dividing n ![Euler's product formula](https://upload.wikimedia.org/math/6/1/9/619a7845480ba7a8a749dc56a6de7c60.png) **Code:** ``` import math import random #perform a Modular exponentiation def modular_pow(base, exponent, modulus): result=1 while exponent>0: if exponent%2==1: result=(result * base)%modulus exponent=exponent>>1 base=(base * base)%modulus return result #Miller-Rabin primality test def checkMillerRabin(n,k): if n==2: return True if n==1 or n%2==0: return False #find s and d, with d odd s=0 d=n-1 while(d%2==0): d/=2 s+=1 assert (2**s*d==n-1) #witness loop composite=1 for i in xrange(k): a=random.randint(2,n-1) x=modular_pow(a,d,n) if x==1 or x==n-1: continue for j in xrange(s-1): composite=1 x=modular_pow(x,2,n) if x==1: return False #is composite if x==n-1: composite=0 break if composite==1: return False #is composite return True #is probably prime def findPrimes(n): #generate a list of primes, using the sieve of eratosthenes primes=(n+2)*[True] for i in range(2,int(math.sqrt(n))+1): if primes[i]==True: for j in range(i**2,n+1,i): primes[j]=False primes=[i for i in range(2,len(primes)-1) if primes[i]==True] return primes def primeFactorization(n,primes): #find the factors of a number factors=[] i=0 while(n!=1): if(n%primes[i]==0): factors.append(primes[i]) n/=primes[i] else: i+=1 return factors def phi(n,primes): #some useful properties if (checkMillerRabin(n,10)==True): #fast prime check return n-1 factors=primeFactorization(n,primes) #prime factors distinctive_prime_factors=set(factors) totient=n for f in distinctive_prime_factors: #phi = n * sum (1 - 1/p), p is a distinctive prime factor totient*=(1-1.0/f); return totient if __name__ == '__main__': s=0 N=165975 # N=430000 primes=findPrimes(N) #upper bound for the number of primes for i in xrange(1,N): s+=phi(i,primes) print "Sum =",s ``` ]
[Question] [ # Goal The goal of this challenge is to produce a function of `n` which computes the number of ways to partition the `n X 1` grid into triangles where all of the vertices of the triangles are on grid points. # Example For example, there are 14 ways to partition the 2 x 1 grid, so `f(2) = 14` via the following partitions [![Partitions of 2 x 1](https://i.stack.imgur.com/YLap3.png)](https://i.stack.imgur.com/YLap3.png) where the partitions have 2, 2, 2, 2, 4, and 2 distinct orientations respectively. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [Haskell](https://www.haskell.org/), ~~60 55 54~~ 52 bytes After a drawing and programming a lot of examples, it occured to me that this is the same as the problem of the rooks: > > On a \$(n+1) \times (n+1)\$ chessboard, how many ways are there for a rook to go from \$(0,0)\$ to \$(n,n)\$ by just moving right \$+(1,0)\$ or up \$+(0,1)\$? > > > Basically you have the top and the bottom line of the \$1 \times n\$ grid. Now you have to fill in the non-horizontal line. Each triangle must have two non-horizontal lines. Whether one of its sides is part of the top or the bottom line corresponds to the direction and length you'd go in the rooks problem. This is [OEIS A051708](http://oeis.org/A051708). As an illustration of this correspondence consider following examples. Here the top line corresponds to up-moves, while the bottom line corresponds to right-moves. ![](https://i.stack.imgur.com/fUFRx.png) Thanks @PeterTaylor for -6 bytes and @PostLeftGarfHunter for -2 bytes! ``` b 0=1 b 1=2 b n=div((10*n-6)*b(n-1)-9*(n-2)*b(n-2))n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0nBwNaQK0nB0NYISObZpmSWaWgYGmjl6ZppaiVp5OkaaupaagFpIwjXSFMz739uYmaegq1CQVFmXomCikJuYoFCkkK0oZ6eoUHsfwA "Haskell – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 42 bytes ``` 0?0=1 a?b=sum[a?i+i?a|i<-[0..b-1]] f n=n?n ``` [Try it online!](https://tio.run/##BcExDoAgDADAnVd0cDM0MLhJ@hDCUBKJjdAQ0c2/493J4zpqndORC94w5TDeFplkFeJPdhsdYrY@JVNAg5LOxqIQoN@iDyzQuEOB6BG3NH8 "Haskell – Try It Online") A fairly direct implementation that recurses over 2 variables. Here's how we can obtain this solution. Start with code implementing a direct recursive formula: **54 bytes** ``` 0%0=1 a%b=sum$map(a%)[0..b-1]++map(b%)[0..a-1] f n=n%n ``` [Try it online!](https://tio.run/##JcqxCoAgEADQ3a@4QaGQRIdGvyQcTkiS9JCs77@M1sc7sJ97KcxWWe8Equj7U2XFNqGaN2tMXFzQ@oP4Aw4QCciTIq6YCTy0K9MNEkaDBJszZg38Ag "Haskell – Try It Online") Using [flawr's rook move interpretation](https://codegolf.stackexchange.com/a/176651/20260) ,`a%b` is the number of paths that get the rook from `(a,b)` to `(0,0)`, using only moves the decrease a coordinate. The first move either decreases `a` or decreases `b`, keeping the other the same, hence the recursive formula. **49 bytes** ``` a?b=sum$map(a%)[0..b-1] 0%0=1 a%b=a?b+b?a f n=n%n ``` [Try it online!](https://tio.run/##DcuxCoAgEADQ3a@4QaGIRIfGww8RhxOSJD0k6/vN/b2L@n2WMga5iP2rslJbSK3eaB13G4RRBq0gFXGKLToSCRhZ8aiUGRDak/kFCTNCAm@1PsL4AQ "Haskell – Try It Online") We can avoid the repetition in `map(a%)[0..b-1]++map(b%)[0..a-1]` by noting that the two halves are the same with `a` and `b` swapped. The auxiliary call `a?b` counts the paths where the first move decreases `a`, and so `b?a` counts those where the first move decreases `b`. These are in general different, and they add to `a%b`. The summation in `a?b` can also be written as a list comprehension `a?b=sum[a%i|i<-[0..b-1]]`. **42 bytes** ``` 0?0=1 a?b=sum[a?i+i?a|i<-[0..b-1]] f n=n?n ``` [Try it online!](https://tio.run/##BcExDoAgDADAnVd0cDM0MLhJ@hDCUBKJjdAQ0c2/493J4zpqndORC94w5TDeFplkFeJPdhsdYrY@JVNAg5LOxqIQoN@iDyzQuEOB6BG3NH8 "Haskell – Try It Online") Finally, we get rid of `%` and just write the recursion in terms of `?` by replacing `a%i` with `a?i+i?a` in the recursive call. The new base case causes this `?` to give outputs double that of the `?` in the 49-byte version, since with `0?0=1`, we would have `0%0=0?0+0?0=2`. This lets use define `f n=n?n` without the halving that we'd other need to do. [Answer] ## CJam (24 bytes) ``` {2,*e!{e`0f=:(1b2\#}%1b} ``` [Online demo](http://cjam.aditsu.net/#code=8%2C%0A%0A%7B2%2C*e!%7Be%600f%3D%3A(1b2%5C%23%7D%251b%7D%0A%0A%25p) This uses [Bubbler's approach](https://codegolf.stackexchange.com/a/176663/194) of summing over permutations of `n` 0s and `n` 1s. ### Dissection ``` { e# Define a block 2,* e# Given input n, create an array of n 0s and n 1s e! e# Generate all permutations of that array { e# Map: e` e# Run-length encode 0f=:( e# Extract just the lengths and decrement them 1b e# Sum 2\# e# Raise 2 to the power of that sum }% 1b e# Sum the mapped values } ``` --- ## Alternative approach (28 bytes) ``` {_1aa{_2$,f{j}@@,f{j}+1b}2j} ``` [Online demo](http://cjam.aditsu.net/#code=8%2C%0A%0A%7B_1aa%7B_2%24%2Cf%7Bj%7D%40%40%2Cf%7Bj%7D%2B1b%7D2j%7D%0A%0A%25p) ### Dissection The triangles all have one horizontal edge and two edges which link the horizontal lines. Label the non-horizontal edges by a tuple of their two x-coords and sort lexicographically. Then the first edge is `(0,0)`, the last edge is `(n,n)`, and two consecutive edges differ in precisely one of the two positions. This makes for a simple recursion, which I've implemented using the memoised recursion operator `j`: ``` { e# Define a block _ e# Duplicate the argument to get n n 1aa e# Base case for recursion: 0 0 => 1 { e# Recursive body taking args a b _2$,f{j} e# Recurse on 0 b up to a-1 b @@,f{j} e# Recurse on a 0 up to a b-1 +1b e# Combine and sum }2j e# Memoised recursion with 2 args } ``` ### Note This is not the first time I've wanted `fj` to be supported in CJam. Here it would bring the score down to 24 bytes also. Perhaps I should try to write a patch... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~44~~ 31 bytes [crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/153011/17602) ``` F⊕θ«≔⟦⟧ηF⊕θ⊞ηΣ∨⁺ηEυ§λκ¹⊞υη»I⊟⊟υ ``` [Try it online!](https://tio.run/##bYyxCsIwFEXn5ive@B7EQVen4tRBDDiKQ0ijKaZpm@SJIH57bOvqcC9cOPcYp6MZtC/lNkTAJphoexuybXEigreo6pS6e8DLVYKjvaj@coqTQyfhzD2eIirPaZlHPSJLqHMTWvtCL@FBRBK2c8@q9cU/70eo2IWMB50yqmFcw7SApezK5um/ "Charcoal – Try It Online") Explanation: Works by calculating the number of ways to partition a trapezium of opposite side lengths `m,n` into triangles which all lie on integer offsets. This is simply a general case of the rectangle of size `n` in the question. The number of partitions is given recursively as the sums of the numbers of partitions for all sides `m,0..n-1` and `n,0..m-1`. This is equivalent to generalised problem of the rooks, [OEIS A035002](http://oeis.org/A035002). The code simply calculates the number of partitions working from `0,0` up to `n,n` using the previously calculated values as it goes. ``` F⊕θ« ``` Loop over the rows `0..n`. ``` ≔⟦⟧η ``` Start with an empty row. ``` F⊕θ ``` Loop over the columns in the row `0..n`. ``` ⊞ηΣ∨⁺ηEυ§λκ¹ ``` Take the row so far and the values in the previous rows at the current column, and add the sum total to the current row. However, if there are no values at all, then substitute `1` in place of the sum. ``` ⊞υη» ``` Add the finished row to the list of rows so far. ``` I⊟⊟υ ``` Output the final value calculated. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 bytes ``` Ø.xŒ!QŒɠ€’§2*S ``` [Try it online!](https://tio.run/##y0rNyan8///wDL2Ko5MUA49OOrngUdOaRw0zDy030gr@f7gdyPv/3xQA "Jelly – Try It Online") -1 byte based on Peter Taylor's comment. Uses [flawr's illustration](https://codegolf.stackexchange.com/a/176651/78410) directly, instead of the resulting formula. ### How it works ``` Ø.xŒ!QŒɠ€’§2*S Main link (monad). Input: positive integer N. Ø.x Make an array containing N zeros and ones Œ!Q All unique permutations Œɠ€ Run-length encode on each permutation ’§ Decrement and sum each 2*S Raise to power of 2 and sum ``` Take every possible route on a square grid. The number of ways to move L units in one direction as a rook is `2**(L-1)`. Apply this to every route and sum the number of ways to traverse each route. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·LÉœÙεÅγo;P}O ``` Port of [*@Bubbler*'s Jelly answer](https://codegolf.stackexchange.com/a/176663/52210). Very slow due to the permutations builtin. [Try it online](https://tio.run/##AR8A4P9vc2FiaWX//8K3TMOJxZPDmc61w4XOs287UH1P//8z) or [verify the first four inputs](https://tio.run/##ASwA0/9vc2FiaWX/NEVOPyIgLT4gIj9ORP/Ct0zDicWTw5nOtcOFzrNvO1B9T/8s/w). **Explanation:** ``` · # Double the (implicit) input L # Create a list in the range [1, doubled_input] É # Check for each if they're odd (1 if truthy, 0 is falsey) # We now have a list of n 0s and n 1s (n being the input) œ # Get all permutations of that list Ù # Only leave the unique permutations ε } # Map each permutation to: Åγ # Run-length encode the current value (short for `γ€g`) o # Take 2 to the power for each ; # Halve each P # Take the product of the mapped permutation O # Sum all mapped values together (and output implicitly) ``` [Answer] # JavaScript (ES6), ~~45 44~~ 42 bytes Uses the recursive formula found by [Peter Taylor](https://codegolf.stackexchange.com/questions/176646/partitioning-the-grid-into-triangles/176652#176652) and [flawr](https://codegolf.stackexchange.com/questions/176646/partitioning-the-grid-into-triangles/176651#176651). ``` f=n=>n<2?n+1:(10-6/n)*f(--n)+9/~n*f(--n)*n ``` [Try it online!](https://tio.run/##LcoxDoJAEEbhq0xBMcNkgbUwUVi9ChtkjYb8Q8DYGL36SkH1vuI94zuuw/KYXw52G3NOAeGC7nCF@jP7xh1rSJnYOYie6h92l8jJFgYF8i2BOvLNVlWhwbDaNFaT3bmPXHzwlW3rSSkxRPIf "JavaScript (Node.js) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 43 bytes According to [OEIS](https://oeis.org/A051708), the generating function of this sequence is $$\frac{1}{2}\left(\sqrt{\frac{1-x}{1-9x}}+1\right)$$ ``` n->Vec(sqrt((1-x)/(1-9*x)+O(x^n++))+1)[n]/2 ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y4sNVmjuLCoREPDULdCUx9IWmpVaGr7a1TE5Wlra2pqG2pG58XqG/1Pyy/SyANqMtBRMALigqLMvBKggJKCrh2QSNPI09TU/A8A "Pari/GP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 51 bytes ``` lambda n:-~n*(n<2)or(10-6/n)*f(n-1)-(9-18/n)*f(n-2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPSrcuT0sjz8ZIM79Iw9BA10w/T1MrTSNP11BTV8NS19ACxjfS/F9QlJlXohGdppGoqZCWX6SQqJCZp1CUmJeeqmGiGav5HwA "Python 3 – Try It Online") Port of flawr's answer ]