text
stringlengths
180
608k
[Question] [ It's laundry day, and you have lots of clothes that need to be washed. Wanting to have as much time left over for code golf as possible, you hope to optimize how quickly you wash and dry them all. You have three types of appliances: * Washing machines: Take dirty clothes and turn them into wet clothes * Dryers: Take wet clothes and turn them into dry clothes * Dishwashers: Take dirty and/or wet clothes and turn them into dry clothes You'll be given a list of appliances, including a capacity (the number of items of clothing, as a nonnegative integer, that can be washed in it at once) and a run time (the time in minutes, as a nonnegative integer, that it takes to finish its job). Additionally, you'll be given a nonnegative integer describing how many items of clothing you have. ## Task Given a list of appliances and a number of items of clothing, you'll return the minimum number of minutes it would take to wash and dry them all. You don't need to return the actual set of operations it would take to do so. At any time, you can perform any of the following operations: * Take up to \$n\$ dirty clothes, and put them in an available washing machine (where \$n\$ is less than or equal to its capacity) * Take up to \$n\$ wet clothes, and put them in an available dryer (where \$n\$ is less than or equal to its capacity) * Take up to \$n\$ dirty or wet clothes, or some combination, and put them in an available dishwasher (where \$n\$ is less than or equal to its capacity) * If it has been \$x\$ minutes since a washing machine was loaded, the clothes in it can be removed. They are now wet, and the washing machine is now available again. * If it has been \$x\$ minutes since a dryer or dishwasher was loaded, the clothes in it can be removed. They are now dry, and the appliance is now available again. (Don't worry, you clean the lint trap like a responsible code golfer) Clothes are "fungible", so you can keep track of all of the clothes not in a running appliance using three nonnegative integers (one for dirty, one for wet, and one for dry). ## Example Let's say you have 120 articles of clothing, and the following appliances: * A washing machine, with a capacity of 10, that takes 40 minutes * A washing machine, with a capacity of 40, that takes 180 minutes * A dryer, with a capacity of 40, that takes 120 minutes * Two dishwashers, each with a capacity of 15, which take 100 minutes An example solution would be (red/dark red indicating dirty clothes in, blue indicating wet clothes in, purple indicating a mix, units of 20 minutes): [![First washing machine runs 4 consecutive cycles, second runs a single cycle, dryer runs immediately after second washing machine finished, both dishwashers run three consecutive cycles.](https://i.stack.imgur.com/PnHA8.png)](https://i.stack.imgur.com/PnHA8.png) This takes a total of 300 minutes. The second pair of dishwasher cycles contain a total of 10 dirty clothes, and 20 wet clothes, and the final two dishwasher cycles aren't completely full. To optimize this any further we'd need to remove two dishwasher cycles and start the dryer earlier (or not at all), which would not result in all clothes being washed. ## Test cases Formatted as `num_clothing, washing_machines, dryers, dishwashers`, with appliances formatted as `[capacity, mins_to_finish]`: ``` 1, [], [], [[1, 10]] 10 10, [], [], [[1, 10]] 100 1, [[2, 2]], [[1, 4]], [[1, 10]] 6 2, [[2, 2]], [[1, 4]], [[1, 10]] 10 2, [[2, 2]], [[2, 4]], [[1, 10]] 6 16, [[2, 2]], [[1, 4]], [[1, 10]] 50 16, [[2, 2]], [[1, 4]], [[1, 10], [10, 20]] 20 10, [[1, 10]], [], [[3, 10]] 40 4, [[1, 1]], [[1, 2], [2, 4]], [] 7 4, [[1, 1], [1, 2]], [[1, 2], [2, 4]], [] 6 6, [[1, 1], [1, 2]], [[1, 2], [2, 4]], [[1, 4]] 4 ``` *I'm not entirely sure these are correct; my reference implementation is buggy.* ## Other This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes (per language) wins. [Answer] # Python3, 1091 bytes: ``` import itertools as I g=lambda x:[[a,[0,b]]for a,b in x] E=enumerate def p(m,o): k=0 for i,a in E(m): if a[1][1]==1:k+=a[1][0];m[i][1][1]=o[i][1];m[i][1][0]=0 elif a[1][0]:m[i][1][1]-=1 return k C=lambda x:eval(str(x)) def P(d): a,b=zip(*[(a[0],range(0,[0,a[0]][a[1][0]==0]+1))for i,a in E(d)]) return[[a,i]for i in I.product(*b)] def U(b,d): for x,y in P(d): if(s:=sum(y))<=b: D=C(d) for i,(j,k)in E(zip(x,y)):D[i][1][0]+=k yield b-s,D def K(N,r,Q,s=[]): if[]==Q:yield(N,r,s);return if Q[0][1]: if Q[0][0]in[0,2]: for a,b in U([N,0,r][Q[0][0]],Q[0][1]):yield from K([a,0,N][Q[0][0]],[r,0,a][Q[0][0]],Q[1:],s+[b]) else: for x in[{0:N,1:r},{1:r,0:N}]: b=Q[0][1] for i in[*x]: for a,b in U(x[i],b):x[i]=a;yield from K(x[0],x[1],Q[1:],s+[b]) else:yield from K(N,r,Q[1:],s+[Q[0][1]]) def f(n,w,d,s): q=[(n,*map(g,[w,d,s]),0,0,0)];O=[] while q: N,*U,r,c,t=q.pop(0) W,D,S=map(C,U) if c==n:return t-1 r+=p(W,w);c+=p(D,d)+p(S,s) for _n,_r,[_w,_s,_d]in K(N,r,[(0,W),(1,S),(2,D)]): if(M:=(_n,_w,_d,_s,_r,c,t+1)) not in O: q+=[M];O+=[M] ``` [Try it online!](https://tio.run/##nVNNb@IwEL3nV1jaiw3TKmF7WIX1qfRQrUq3qlAPloUS4rReyAd2WMJW/e3s2AkU9kMrrYDgmXkz8/xmUu@al6r8@Kk2@70u6so0RDfKNFW1siSx5DZ45qukSLOEtLEQCYgQUinzypAEUqJL0srghqtyUyiTNCrIVE5qWkDF4oAseRgQh9WQOOwNLZyb6JwkIpL45TyKl0PurVCOC6FlH6i649EVSleMqNUhOZTxO/yCRwExqtmYkiyD63fO6nuyorYxtGXMk/tKM8cB2fMfuqYDQRMsBSYpnxUN3f2cLUXfg/NQDiPGzm6RMckO7Zwo2guiXfD2sjZVtlk0dJAy6TvOaAq@pwO1sHOwngUqQW3M7aagO8Y@89T5yIRfY9iduq70GyyZb@wYYwXG4slRliFfOuhOq1VG0gsLE9/1C52CgQewXEjXSucCL/MQe5yPWTburuCC5AFLYcF@PN4KpS5Rj5F3kpOZz6iYQghGih4noU9nXX2Sm6pACqhNCNMTmDDoSM7yoliCHYrUSYrjterYrcVe4jWMpxDF5g1e8QlovXV8SMr7pt46TEAM2j5@zrhFwSBlsfvnyfiMZus2oMVKv9DxbM6QXtMDpm8vu8XKaQlbyFBWbL/mAs1BkdT0GYR3S4ZXxw@T43ucSUC2L3qlyNqRncJghpUX0PD1ZV3VNHRiPMEEHrmrcQ0z1g1mwXkZ94veXODSEzPkNX2CLRsv3GmCuzas6SPyCDoJ5iXMDYj5FuYW5hkOtb@IwH1/YkAjeMTnCCbMb4rfyruYU5eISZnP8@zcm0DKqnGS3ncqr4dc3OGV/N@@NrpsaI4liZD9T6AR4azxBTyGw3/EnXsEZCQPgCv5F@jov6GjP0A/2KpQpFG2scQudV2r7Jh@dYAek0bucCxz2uodi4folN1vOfuf) Very brute force solution and as such, it times out on the larger test cases. I will come back to those later. ]
[Question] [ Given a positive number \$n\$ we call **another** (not same as n) positive number \$m\$ good if we insert same digits in both n and m and the resulting fractional value is same. $$m/n = m\_{\text{transformed}}/n\_{\text{transformed}}$$ $$or$$ $$m\*n\_{\text{transformed}} = m\_{\text{transformed}}\*n$$ Clarifications: * No leading zeros or trailing zero insertion is allowed (you can insert 0 at beginning or end, but this must not be the last digit added in that end),other than this you can insert any digit(same digit and same number of time in both) at any place,i.e you need not insert at same place in n and m. * At least one insertion is required. Examples : Example 1: $$n= 12$$ here m=66 is a good number ,we can obtain it by inserting 1 in m and n such that they become 616 and 112. Example 2: $$n=30$$ here m=60 is a good number, we can get 300 and 600 by inserting 0 in **middle**, as mentioned we cannot insert 0 at end or beginning, but here we inserted it in middle. Example 3: $$n=4$$ here 7 is a good number, as we can insert 2 and 1 , making them 124 and 217 respectively, now the fractional value is same. Example 4: $$n=11$$ here 2 is a good number, as we can insert 2 and 2 , making them 1221 and 222 respectively, now the fractional value is same. Example 5: $$n=4269$$ here 1423 is a good number, as we can insert 0, making them 42069 and 14023 respectively, now the fractional value is same. Example 6: $$n=1331$$ here 242 is a good number, as we can insert 2 and 2, making them 123321 and 22422 respectively, now the fractional value is same. **Task:** You have to find out smallest good number for a given n (there always exists a good number as pointed out by a user in comments). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes per language wins. [Answer] # [Haskell](https://www.haskell.org/), 154 bytes ``` g n=head[m|m<-[1..n*10],m/=n,w<-i m,v<-i n,w*n==v*m] i m=[read$take n s++c:drop n s|let s=show m,let l=length s,n<-[0..l],c<-"123456789"++['0'|n/=0,n/=l]] ``` [Try it online!](https://tio.run/##FY1BCoMwFET3PUUogqBRo7W2Fv9JQhZBgxGTrxjRjXdP42Zm3sAwWrpZGeP9SBC0kgO3l@0yXuY5JiUT1BaA9OyyiVh63BYoQYAjseIRSuBbWEW7nBVB4tK0/w3bst75MmonDpxezjC@wYBROO6aOIrhhOW5EbTvsmdZvep38/m2zzTlMYsvLIDRIEYIb@WEsG4T7tFI6qpp/R8 "Haskell – Try It Online") [Answer] # JavaScript, 8 bytes ``` n=>-~n/n ``` [Try it online!](https://tio.run/##BcFRCoAgEAXA6yhmUfRn213E3CjkbWj02dXXmTt@saV6Pa@HHFmZFLT7HxOUpRrQjICNlhXBOdgkaFLyWOQ0GNjAWu0 "JavaScript (Node.js) – Try It Online") Takes \$n\$ as a BigInt. Returns 1 for \$n \ne 1\$, 2 for \$n=1\$: 1 is good with every other number. For example, 1 is good with 2 as follows: ``` 105263157894736842**1** * 2 = **2**105263157894736842 ``` This can be constructed by starting with the digit 1 at the top right, and doing the multiplication by 2 while copying each digit of the product up and to the left, until it finishes by arriving at a 2 with no carry. This always works. Let \$x\$ be the number formed by the inserted digits, and \$l\$ be the number of inserted digits. Then we need \$(10x + 1)\*n = n\*10^l + x\$, which rearranges to \$(10n - 1)\*x = n\*10^l - 1\$. This always has suitable integer solutions: by [Euler's theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem), \$l = \varphi(10n - 1) + 1\$ works. However, this inserts an ending zero (which is not allowed) when \$n\$ has an ending zero. A solution is to ignore all ending zeroes of \$n\$, then put them back at the end; for example, for \$n=200\$: ``` 105263157894736842**1** * 200 = **2**105263157894736842**00** ``` Here's a function that does the full calculation, returning \$[m, n\_\mathrm{transformed}, m\_\mathrm{transformed}]\$: **JavaScript, 86 bytes** ``` d=(n,N=n,y=T=10n,m=-~n/n,k=m*N*T,a=y/--k+y)=>N%T?y%k>1?d(n,N,y*T):[m,a*n,a*m]:d(n,N/T) ``` [Try it online!](https://tio.run/##HYuxDoIwGAafhoSWv0WME/DDGzB1Mw4NoNHSrwaMSRdfvaLDLZe7h33bbVzvz5dCmOaUJs5BA4MiG64OIM/qgxLk2MtBGrIcS6VcEQV3Q2b6mLmu6qffRVEaUZ89WYkdf6n/ujQiXcOagys0aPl4QlMUEGPAFpZZL@G2Z1rrvRYifQE "JavaScript (Node.js) – Try It Online") ]
[Question] [ One day in July 2020, I made the following C program: ``` #define A m] a[9999],*m=a;main(){for(2[A=4[A=1;;){for(;4[A;putchar(6[m-=3]+48)); for(puts(a);7[A;2[A=4[A,4[A=1)if(4[A+=3[m+=3]-1,9<(3[A=2[A+=3[A))++ 5[A,7[A=1,3[A-=10;}} ``` with three superfluous newlines removed, it's 167 bytes and it prints the fibonacci sequence (as decimal numbers, separated with newline) potentially infinitely (it *will* crash when exceeding the buffer size after printing many terms of the sequence). [Try it online (gcc)!](https://tio.run/##LYvBDsIgEETvfkUTL6xAIqVam5UD30E4EGyVA9VUPZl@O26tm@xmduZNlNcYS9le@iGNfWWr7DfBdTRe7LIJmEMaGXyG@8RqZ01DqxBXA@nDx/sVb2FiR5el0Z43JwBcUgqeLAC2BP2r4leHNDAS3GiX6XipRHdmmqJ6dS0A5wfC2wUXZEij9jjPpXwB "C (gcc) – Try It Online") [Try it online (clang)!](https://tio.run/##LYvBDoIwEETvfgWJl65tEwsokrWHfkfTQ4MgTWw1qCfDt9dF3GQ3szNvOtndfLrmvL30Q0h9YYroNt62NE7sovYYfUgMPsN9YqU1uqZViKuB9OHj/epGP7GjjVJXjtcnAFxSCp7MAzYE/aviV4cwMBJcVzbScVKJ9swqisrVNQCcHwhvFlyQIbXa4zzn/AU "C (clang) – Try It Online"). As I had trouble golfing it myself, I decided to ask the C golfers of CGCC for help. The challenge is to golf it, or more formally, to produce *the same output as this program* (and of course you can derive your own solution based on it). The code should stay *reasonably* portable (i.e. not perform out-of-bounds accesses before program termination is desired, use compiler extensions, etc...). Your program is expected to print at least `15939` consecutive fibonacci numbers, starting from the smallest, separated with newlines, printed as decimal numbers, starting with `0 1 1 2 3 5 ...`. Your answer might also provide improvements to the original version as an extra (printing more sequence terms with minimally more bytes, etc... - just make sure to post the golfed version *with* your answer, because it's the main goal of this question). [Answer] # 142 bytes (-25) 3 more bytes saved by [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` a[9999]={0,1},i=2,k,s;main(c){for(;i--;c&&putchar(i?k+48:10))c|=k=a[i]>>4;for(;c=s>9,++i<9999;a[i]=k<<4|s%10)s=a[i]/16+c+(k=a[i]&15);main(c);} ``` [Try it online!](https://tio.run/##NY3bCsIwEES/xpCQFBuJYt1s/JDSh7CgLsELjT61/fbYVpzXOWeGqitRKbFt5nQ41MZOhnFnkslwj/yQpIbLs5fAVQUkxOvzplvsJZ@TdseTrZWiERPGlrsQHKwsYQ6N0Zr9MgtLh8l7N@bNLOQV3tqDJi1/prB79b@DqZQv "C (gcc) – Try It Online") (GCC) [Try it online!](https://tio.run/##NY1BDsIgFERPI4EAsRg0Vvh4kKYL8hP1B62m6Krt2bGtcbbz3gxqvMfuWkps6jktDJUykyLYqaSye0TqOIrh8uy5I60dMvb6vPEWe07nJO3xZCohcIQEsaE2BOtWFiGHWklJfpl1SwfJezvmzSzkFd6ag0TJfyYze/G/c1MpXw "C (clang) – Try It Online") (clang) --- # 145 bytes (-22) This is a complete rewrite which can probably be golfed some more. ``` a[9999]={0,1},i,k,s;main(c){for(i=2;;){while(i--)(c|=k=a[i]>>4)&&putchar(i?k+48:10);for(;c=s>9,++i<9999;a[i]=k<<4|s%10)s=a[i]/16+c+(k=a[i]&15);}} ``` [Try it online!](https://tio.run/##JY1bDsIgFAVXYwMBYjForLfgQpp@kBu1N9RHROMHZe3Y6vmemYPqgliK75p5vU211FmSDDLC1dONIU/n@5OR3QDw9BloPDFSijOcbLC@o945w6vq8X7h4GfwGITZH3TNYfEAbXSNFILa5QAWwYa2NVNczUz8FdZ6J1Cwf67SWw45l/IF "C (gcc) – Try It Online") (GCC) [Try it online!](https://tio.run/##JY3BDoIwEAW/xqZN20gNGnFp/RDCodmobAporMYD8O2V6jvPzEONvR9vKfmmWtfaqVBmUaSCijB4GjmK6Xp/crI7ADF9OuovnLQWHGcbrG@oda4UjD3eL@z8Cp6DLI8nUwjIHqCNrlJSUp0PIAs21HU5x83KxF9haw4SJf/nmNkLWJaUvg "C (clang) – Try It Online") (clang) ## How? ### Encoding For each entry `a[i]` with `i > 0`, we store the **i**-th decimal digit of the last Fibonacci term into the bits **0** to **3** and the **i**-th decimal digit of the penultimate term into the bits **4** to **7**. (The convention used here is that the 1st decimal digit is the least significant one.) We start with all entries set to **0** except `a[1]` which is set to **1**: ``` a[1] = 00000001 \__/\__/ | | | +--> first and only digit of Fib(2) = 1 +------> first and only digit of Fib(1) = 0 ``` It is then updated as follows: ``` 00000001 -> 00010001 -> 00010010 -> 00100011 -> 00110101 -> ... \__/\__/ \__/\__/ \__/\__/ \__/\__/ \__/\__/ 0 1 1 1 1 2 2 3 3 5 ``` ### Printing Each number is printed by iterating from the most significant digit to the least significant one, ignoring leading zeros and ending with a line-feed. ``` while(i--) (c |= k = a[i] >> 4) && putchar(i ? k + 48 : 10); ``` We start with `i = 2` and `c = argc` (which is guaranteed to be greater than **0**) in order to make sure that the initial `0` is printed. ### Updating In order to compute the next term `Fib(n+1)`, we iterate through all values stored in `a[]`, this time from least significant to most significant. We add the last digit to the penultimate one, update each entry accordingly and keep track of the carry into `c`. ``` for(; c = s > 9, ++i < 9999; a[i] = k << 4 | s % 10;) s = a[i] / 16 + c + (k = a[i] & 15); ``` We have `i = 9999` and `c = 0` at the end of this loop, which are the expected values to print the next number, starting from the 2nd iteration. We also end up with `s = 0`, which means that `c` will be re-initialized to `0` as expected before the next update. ]
[Question] [ Write a program which will eventually, given enough time, print all possible permutations of ASCII characters (both printable *and* non-printable) less than or equal to its length, **except** itself. The text of the program must not appear anywhere in its output. For example, if your program is `abc`, then part of your output could look like: ``` (many lines omitted) ab0 ab1 ab2 ... abb abd (many lines omitted) ``` or ``` ...[some character other than a]bcabacba5804g715^^*#0... ``` If your language requires characters that are not printable ASCII (e.g. Jelly or APL), print all combinations of characters in its code page. The strings need not be separate from each other; a single character can be counted as part of multiple strings. You could try to create a [superpermutation](https://en.wikipedia.org/wiki/Superpermutation), which would be at least \$95! + 94! + 93! + 95 − 3 = 1.04 × 10^{148}\$ characters long. Standard quine rules apply (no reading the program's source code) but this is also code golf. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~92~~ ~~91~~ 86 bytes *Saved 5 bytes thanks to a comment by @Sisyphus on another answer.* ``` eval s="a=*?\0..?\x7f;90.times{|i|puts a.product(*[a]*i).map(&:join)-['eval s=%p'%s]}" ``` [Try it online!](https://tio.run/##KypNqvz/P7UsMUeh2FYp0VbLPsZAT88@psI8zdrSQK8kMze1uLoms6agtKRYIVGvoCg/pTS5REMrOjFWK1NTLzexQEPNKis/M09TN1odaoxqgbpqcWyt0v//AA "Ruby – Try It Online") Forms arrays containing all permutations of ASCII characters (codepoints `00` to `127`) of length 1 to 91, then subtracts from each the string `eval$s=%q(#$s)`, which is equivalent to the full program (because of the interpolated string `$s`). ``` eval s=" # evaluate s, a double-quoted string that contains most of the program a=*?\0..?\x7f; # create array of ASCII characters 00 to 127 90.times{|i| # for permutations of length i = 1 to 91: puts a.product(*[a]*i).map(&:join) # print all strings of length i... -['eval$s=%p'%s] # not equal to the full program } " ``` [Answer] # [Perl 5](https://www.perl.org/), ~~119~~, ~~110~~, 108 bytes -9 bytes hardcoding code length thanks to @Dingus. ``` $C=q(while(y///c<109){s/^\xff*(.?)/"\0"x$-[1].chr(''ne$1?1+ord$1:0)/es;"\$C=q($C);eval\$C"ne$_&&say});eval$C ``` [Try it online!](https://tio.run/##K0gtyjH9/1/F2bZQozwjMydVo1JfXz/ZxtDAUrO6WD8upsI8TUtDz15TXynGQKlCRTfaMFYvOaNIQ109L1XF0N5QO78oRcXQykBTP7XYWikGbJCKs6Z1alliDpCnBFQVr6ZWnFhZCxFTcf7//19@QUlmfl7xf11fUz0DQwA "Perl 5 – Try It Online") or [to check the case when output is just before the source](https://tio.run/##K0gtyjH9rxJvW6ih7AwkyjMyc1I1KvX19ZNtDA0sNauL9eNiKszTtDT07DX1lWIMlCpUdKMNY/WSM4o01NXzUlUM7Q2184tSVAytDDT1U4utlWJUQAapOGtap5Yl5gB5SkBV8WpqxYmVtRAxkNx/FTpa9///v/yCksz8vOL/ur6megaGAA) ]
[Question] [ ## Background [**Conway immobilizer problem**](https://www.futilitycloset.com/2014/09/12/the-conway-immobilizer/) is a puzzle that reads like the following: > > Three positions, "left," "middle," and "right," are marked on a table. > Three cards, an ace, a king, and a queen, lie face up in some or all > three of the positions. If more than one card occupies a given > position then only the top card is visible, and a hidden card is > completely hidden; that is, if only two cards are visible then you > don't know which of them conceals the missing card. > > > Your goal is to have the cards stacked in the left position with the > ace on top, the king in the middle, and the queen on the bottom. To do > this you can move one card at a time from the top of one stack to the > top of another stack (which may be empty). > > > The problem is that you have no short-term memory, so **you must design > an algorithm that tells you what to do based only on what is currently > visible.** You can't recall what you've done in the past, and you can't > count moves. An observer will tell you when you've succeeded. Can you > devise a policy that will meet the goal in a bounded number of steps, > regardless of the initial position? > > > The puzzle has got its name because it's said to have immobilized one solver in his chair for six hours. The link above gives one possible answer (marked as spoiler for those who want to solve it by themselves): > > * If there’s an empty slot, move a card to the right (around the > corner, if necessary) to fill it. Exception: If the position is > king-blank-ace or king-ace-blank, place the ace on the king. > * If all three cards are visible, move the card to the right of the > queen one space to the right (again, around the corner if > necessary). Exception: If the queen is on the left, place the king on > the queen. > > > > [All solutions to the Immobilizer Problem (pdf)](https://link.springer.com/content/pdf/10.1007/s00283-014-9503-z.pdf) uses graph theory to show that there are 14287056546 distinct strategies that solve the problem. ## Task Given a strategy for Conway Immobilizer, **determine if the strategy actually solves it**, i.e. given *any* initial configuration, repeating the strategy will eventually place all cards into the winning state. A strategy (the input) can be in any format that represents a set of pairs `current visible state -> next move` for every possible `current visible state`. A **visible state** represents what is visible on each of three slots (it can be one of A/K/Q or empty). A **move** consists of two values `A, B` which represents a move from slot A to slot B. The input format can be e.g. a list of pairs, a hash table, or even a function, but it should not involve any external information, e.g. you cannot encode a "move" as a function that modifies the full game state (entire stacks of cards). You can use any four distinct values for A/K/Q/empty (the visible state of each slot) and three distinct values for left/middle/right (to represent a move from a slot to another). Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` Input: the solution above Output: True Input: the solution above, but the exception on 'K.A' is removed (at 'K.A', move K to the right) Output: False ('QKA' -> 'K.A' -> 'QKA') Input: if only one card is visible, move it to the right if Q and K are visible, move K on the top of Q if K and A are visible, move A on the top of K otherwise, move A to the empty slot Output: False ('..A' where Q, K, A are stacked -> 'A.K' -> '..A') ``` [Answer] # JavaScript (ES7), ~~229 224~~ 213 bytes **Input:** a function (the solver) expecting an array of 3 values among `'Q'`, `'K'`, `'A'` or *undefined* for empty, and returning a move as a pair `[from, to]` (0-indexed) **Output:** 0 or 1 ``` f=(F,n=162)=>!n--||(g=s=>(s[k=s.join`/`]^=1)?/A,K,/.test(k)|g(s,[x,y]=F(s.map(a=>a[0])),s[y].unshift(s[x].shift())):0)([0,1,2].map(i=>s[n/3**i%3|0].push('QKAKQAAQKQAKKAQAKQ'[3*~~(n/27)+i]),s=[[],[],[]])&&s)&f(F,n) ``` [Try it online!](https://tio.run/##5VJNT8JAEL3zK8YDdAeXfpFoItmSXrj0YBqPmzVWaXEFt4QpBmPlr@MCflQwnryZbCZvZ96bNzvZh@wpo7uFnlc9U47zzaYQbMSNCM5CFNGJ6fXqmk0EiYiRnApyH0ptbrwbdS0CHHoxT7jnVjlVbIr1hBGXK/6sxIiR@5jNWSaiTPoKkZN8Vu7S0L0uKttqpdw9RMQLH5n0ecBDtRNpEZE0Xr/b1e1@7St3vqR75qRJnKRxnNqQJLENqSP73fWaGS88x1OtrImQUvHdUdjpEHaK7WtwMynL8VU5e8oXIIBARPDSgi0ASXY@qGvwOZAMvmC4h2rQskxdsP3TmeMgCAFO4scWbbsALPJquTAgQ77jA7z@LIn9I0lwIFkzvZ3Q1Wacry4L5tv9fJeQtJRTCBHa0FcwhOadg1Zw8Z4K3lNNfsPq5MDKSZ0jM9koJw42h/1g/GL12mrdZn@993@4xLvSUDnL3Vk5YQX7@suIg4Pa57ptafMG "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~120~~ 114 bytes ``` ≔E³³SθFφF⁼Σι³F⪪”{“±¿U+*~T”³«≔⪪λ¹λ≔E◧Iι³EΣμ⊟λλ≔⊟Φθ⬤λ⁼§μπ§∨ξ.⁰ζ≔Eλ⮌μη⊞§ηI§ζ⁴⊟§ηI§ζ³⊞υ⁺λEη⮌μ»≔⊟υθWΦυ¬№Eυ…μ³✂κ³≔⁻υιυ¬υ ``` [Try it online!](https://tio.run/##fZLJbsMgEIbP8VMgn0CiyE566wlFrRTRxTRPYKUktoqX2JCmqfrs7jCxqzSHHjwMs3z/gNkUebdpcjsMsu/LXU2f8pYuFpys6ta7tevKekcZ42TP7qJt0xG6ZQTX@73PbU/XvqIl5BdsjK9bWzoaS6WlVgo@WGGjZHwu@opmo9S50nKSQr8F/uxihix/ezRbR5d570YBTkIiCFbgZ01LLWNXrSH6UFpnOrrnRFob@OOo0q3qN3OkFScttE3bl44eOYlFDLGEMUSerqYByKs5mK43oA35IuQz3xe/0IITHHXanzi5RVSY6J@iBSpONA/11vdBL8gWf2RD2Xd0cVA//pePorSGTOcGxnMDF9f42uHwEFh@bqxZFtBToSQna1tuDH2fBiDTYcsa5KEjXLkHdgYvwNEA9KA/DELoeRIJodDKYDX6CuMaIxJ9dfYxq0U6hwhaGawWKkkjJTRYLSRYib5CpsQsPJo0iRQyNXIkasGrCvUKe5GpkK@RLNFX4EO9OmsJJAtUATvcHOwP "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for verified, nothing for failed. Explanation: ``` ≔E³³Sθ ``` Read in the 33 instructions, comprising strings of 5 characters, the three visible cards and the source and destination of the move (0-indexed). ``` FφF⁼Σι³ ``` Loop over all 3-digit numbers with a digit sum of 3. ``` F⪪”{“±¿U+*~T”³« ``` Loop over the permutations of `AKQ` by taking a compressed string of all six permutations and splitting it into substrings of length 3. ``` ≔⪪λ¹λ≔ ``` Split the `AKQ` into an array. ``` E◧Iι³EΣμ⊟λλ ``` Move the `AKQ` into one of three lists depending on the digits of the outer loop variable. For instance, if the variable is `111` then the resulting list is a list of lists of reverse of the array, while if it is `300` then the resulting list has the reverse of the array as its first element and two empty lists. This represents the real positions of the three cards. ``` ≔⊟Φθ⬤λ⁼§μπ§∨ξ.⁰ζ ``` Calculate the visible cards and find the move for that set of cards. ``` ≔Eλ⮌μη ``` Make a reversed copy of the card positions. ``` ⊞§ηI§ζ⁴⊟§ηI§ζ³ ``` Perform the move on the copy. The reversal, in addition to resulting in a deep copy, also allows the moved card to be popped and pushed. ``` ⊞υ⁺λEη⮌μ ``` Unreverse the move result and save the cards and the move result to an empty list. ``` »≔⊟υθ ``` Remove the winning position from the list of all card positions. ``` WΦυ¬№Eυ…μ³✂κ³ ``` Repeat while there are positions whose move reaches a winnable position. ``` ≔⁻υιυ ``` Remove all of the now winnable positions. ``` ¬υ ``` Are there no unwinnable positions left? ]
[Question] [ # Background MENACE (**M**achine **E**ducable **N**oughts **A**nd **C**rosses **E**ngine) is a rudimentary shallow machine learning algorithm for the game Noughts and Crosses, created by British computer scientist Donald Michie in the 1960s. It was originally implemented with 304 matchboxes, each labelled with a board position and containing coloured beads (with one of nine colours, representing possible moves). Michie calculated that these 304 matchboxes were enough for every combination of moves on the board. The more mathematical among you may realise that there are actually 19,683 possible combinations of Noughts, Crosses and Blanks on a N&C board; however, he calculated ways to cut down on this number (to speed up the algorithm, and likely to cut down on matchboxes!). Firstly, he removed all none-possible moves, such as: ``` ------- |X|0|X| | |0| | |X|X| | ------- ``` (two noughts and four crosses) Next, he compensated for rotations. For instance, if on the matchbox we see: ``` ------- | |0|0| |X| |X| | |0| | ------- ``` we can use the same box for ``` ------- | |X| | |0| |0| | |X|0| ------- ``` Therefore, the aforementioned coloured beads represent relative positions, not absolute ones. For instance, if we said that a red bead meant top-left, then we'd take a look at the image on the top of the box and see: ``` ------- | |0|0| |X| |X| | |0| | ------- ``` so we'd know that in the case that this is the board, then the red bead would mean: ``` ------- |R|0|0| |X| |X| | |0| | ------- ``` But if this is the board: ``` ------- | |X| | |0| |0| | |X|0| ------- ``` the red bead would mean ``` ------- | |X|R| |0| |0| | |X|0| ------- ``` These transformations applied for rotations and inverting (in all directions, including diagonal). Once again, you only need to save each matchbox once this way: do not make separate virtual boxes for each transformation! Another simplification Michie made was to make sure the computer goes first. This way, he could remove all first-level moves, removing about a fifth of the remaining boxes. Finally, he removed all game-ending boxes (as no further 'contents' or moves were required on these steps). Right, now onto the algorithm itself (it's very simple): 1. First, decide on what the colours of the beads represent. You'll need 9 colours to represent each of the spaces on the board. 2. At the start of the game, each of the 304 matchboxes contains beads. While the beads are of random colour (so duplicates are fine), they should be possible moves (so if the board state image depicts an 'O' in the middle-right, then you can't use the bead that represents the middle-right). 3. Every time it is MENACE's (X) turn, find the matchbox with the current board position (or some transformation of it) printed onto it. 4. Open the matchbox, and choose any bead in there at random. 5. Find how the board status has been transformed to get to the image on the matchbox (e.g rotated 90deg anticlockwise). Then, apply that transformation to the bead (e.g top-left becomes left-left). 6. Place an X in that square. Remove the selected bead from the matchbox. If the box is left empty as a result, put three random (possible) beads into the box, and pick one of them for the move. 7. Repeat 3-6 until the game is over. 8. If MENACE won the game, go back through every matchbox MENACE took. Then, trace back what colour bead it used on that move. Put two of that colour of bead into the box (so that there is the original bead + one more, thereby increasing the likelyhood of MENACE making that move next time it gets to that position) 9. If MENACE lost the game, do nothing (**don't** replace the beads it took out). 10. If MENACE drew the game, then replace the bead it used in each of its moves, but don't add an extra one, so that you're left with what you started. This leaves us with an algorithm that is very simple, but difficult to implement. This forms the basis of your challenge. *If you're still confused, see <http://chalkdustmagazine.com/features/menace-machine-educable-noughts-crosses-engine/> - it's what I read when I first learned about this algorithm* # Challenge Play a game of Tic-Tac-Toe with the computer. At each step, output the contents of all of the matchboxes. ## Inputs * At the start of the program a number, saying how many games you want to play against MENACE * Then, after MENACE's first turn, you input your move as a two character string, the first letter being "L", "R", or "M" (left, right or middle) referring to the Y axis. Then you input another letter (again, "L", "R", or "M"), this time referring to the X axis. Repeat for all moves and games. ## Outputs * At the start of each new game, output "new game". * After each move by the player, output the board in any reasonable format. It doesn't need to look pretty (e.g an array of arrays representing the positions of the board is fine). * After each move by the player, MENACE should make a move. Output the board after MENACE's move * After each game, output the contents of all 304 matchboxes. Beads can be represented by a letter, name of a colour, character or whatever **string or integer** you like (no pointers, anonymous functions, etc). # Rules 1. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. 2. I must be able to input moves after seeing MENACE's response. No 'pass all of your moves into this function, and watch how the game plays out'. 3. The board must be cleared between games. 4. The matchboxes must *not* be cleared between games (this would reset the machine learning) 5. You must have 304 matchboxes. Anyone can implement this algorithm with all 19,683 matchboxes, but the learning is slow (as it requires *lots* of games to get all of them with useful contents). 6. The output can be in any reasonable format, and input can be taken as per PPCG standards (as long as it complies with rule 2). If you need to adjust the input format (as described in the '**Input**' section) then it's OK as long as it makes sense. 7. A game ends when a player wins (by getting three in a row diagonally, horizontally or vertically) or if there is a draw (the board is full and there is no winner) 8. While MENACE needs to make possible moves (and only have possible beads inside each matchbox), for the sake of the challenge you don't need to validate the input of the user. If they type in something wrong, your program can do whatever (go completely crazy, throw error, etc.) - you can assume that the input is correct. [Answer] # [R](https://www.r-project.org/), 839 bytes ``` options(max.print=1e5) s=colSums r=rowSums m=matrix a=array y=apply S=sum p=sample b=m(rep(i<-1:(K=3^9),e=9)%/%(E=3^(8:0))%%3,c(9,K)) V=a(1:9,c(3,3,8)) V[,,2:4]=c(V[x<-3:1,,1],V[,x,1],V[x,x,1]) V[,,5:8]=y(V[,,1:4],3,t) d=aperm(a(b[c(V),],c(9,8,K)),c(1,3,2)) v=m(V,9) g=y(m(match(e<-y(d*E,2:3,S),i),,8),1,min) g[K]=K G=9-y(t(e==g)*8:1,2,max) h=s(a(c(b,d[,,5],b[c(1,5,9,3,5,7,1:3),]),c(3,3,K,3))*3^(0:2)) k=r(s(h==13))>0 l=r(s(h==26))>0 o=s(b>0) M=b M[M==0]=-1 repeat{A=b[,t<-K] z=j=c();B=1 repeat{if(S(pmax(-M[,t],0))<1)M[p(9,pmin(3,S(x)),,x<-M[,t]<1),t]=-1 z=c(z,u<-p(9,1,,pmax(-M[,t],0))) j=c(j,t) A[v[,G[B]][u]]=1 print(m(A,3)) if(k[B<-S(A*E)]||o[B]==9)break A[ceiling((utf8ToInt(readline())-76)/5)%*%c(1,3)+1]=2 if(l[B<-S(A*E)])break t=g[B]} M[x]=M[x<-cbind(z,j)]-k[B]+l[B] print(a(M[,g==seq(g)&!k&!l&s(b==1)==s(b==2)&o<8],c(3,3,304)))} ``` [Try it online!](https://tio.run/##XVLBbptAEL3vX@Rga8cZGmPiBCgTyZGiKLJ8cpUL2kqAiUNsDAWc4jT5dvdB3KrqBWZ2Z95782ar47Eom6zY1TqP2i9lle0asdMpqVqSYrvc57WqpCp@9lEuedRUWasiiaoqOqiDRGW5Pail1PtclVJHeblNVSy5rtJSZ4Fl@3ouznePOBWPBhcDfYdUu/6YaDBwONEez4nUo0Ta9j3kDjvsdich88S/NJLox7ANLMe3mW3DOG8//20ffFZOfdfIQXehjSZgNKRWkJdWuY50HAKF2PR8bseIyEbVBEyvkPvIHqk1EHIY0STPOg2sg16N7qDB4SVxRgxZbHOe7VAZzo3M1b14qGp0KrKmkQuFE4aPpJ6lBmuiY1514gx3AmyesgfOKV9DpAM5dJp3zg7RCL6M/U7QRipd62cRG8c3Y7X9k0@u@rwAenwzJrWQWC3ChcjYiGUreJ5Gza@ZxCE3gTU36k1e4B99vZW/t9mTXuoSKrW1QJlhbCKwaRGWsKbEdFC01C0cYrjel@Aa347hDWhvvA@srhj7@A@HVEf30nk/C19Dvg9vjQn3xoC@f1uwd9bNqqBiE94G1lLPRndk3t8LlAqeSFyl0QbdSZpts91a633z5H4rHtCLmxXOUk1kXV/RxZQGo0G/Rjq3jUw60O0/oCesRtbA/oBRrZFF95SSONutMMcLGQsqzDm6zElgpDHNWqROf@g1Dc82w7PtEHZjGSTSBxMaFoFrTrtzxpcY/ON4/A0 "R – Try It Online") Quite a long answer, but this wasn't a straightforward challenge. The TIO link here will fail because it expects interactive input. [Here's a version](https://tio.run/##XVJNb9pAEL3vr8gFaZaOVRaHFrueSCChHBAnV7mstpJtHDDBwTKQmHz8dvqWpFXViz2z@@a9NzPbns97KXbb9FjvVSvt7vkS1VJnh7bqVCZZ22YndZKsabYnlcr@WKtG9lndbEuVS01t2VCVBCamuYS/Is2lRLr3tUczpDSOB1r3eiEXFPFca3UnGZk4Qh5yyGN/YpmH8bWTgu5slwRhbJiNY5x3H//uEnwgR/HYyYl8aFAEjoNWS9gr25oyyi1YNLuL3tgrIjJADaH0BLt3HGm1AkNN6LFYU5kEJ1r2Z/AQcqq50gxbbLiuHoG0cydzdSsRUAcqRVa6P4bDIddZp9Va9lAtKOelN@fYGzA84giaI/4OkyHs6M9@5xxq3cdcBrE39CAt7WktYnB8M1DbP/nw2yXfgT2/GWi1kFwt7EJk4CQw6n7XUnVVPV6Z2JTX@nUiueVDEsydepENBql/TMWo53W1Lemnfq3uKaUGhilYAOgYS0mMXtgGU2rQKMyl1GFYjAVcILjG14u9gO@Fj0ngwVjNfzxaecGNX8PEPlm@tVPn7NE5GIDug50mQUqT/ky7t7cdLgXvI2/L7AH4j3dEMIpNTNAeBq@dDH3l9p/Kz4KDrEDwrors4IndF2Bcf4j52M7Jwr@eIq8el/C70S74C1Hv5/Nv) that plays against a second, random player who just picks a spot at random. The output for this second version is just the winner (1, 2 or 0 for a draw.) Matchboxes are initialised for all board positions, but only used for the 304 per the spec. They're implemented as copies of the board with negative numbers to indicate the number of beads on each position. I experimented with a list of vectors per the original spec, but it was less intuitive. This is a less golfed version with comments (but still short variable names). Note that it doesn't print the matchboxes out because they're very long. It can implement an interactive player 2, a random player 2 or the same matchbox strategy for player 2. ``` auto = 1 # 1 = Random player 2, 2 = Player 2 uses learning strategy # 0 for interactive print_board <- function(board) { cat(apply(matrix(c(".", "X", "O")[board + 1], 3), 1, paste, collapse = ""), "", sep = "\n") } E = 3 ^ (8:0) # Number of possible arrangements of board # ignoring rotations etc. # Make all possible boards b = matrix(rep(1:3 ^ 9, e = 9) %/% E %% 3, c(9, 3 ^ 9)) # Define the eight possible rotation/inversion matrices V = array(1:9, c(3, 3, 8)) V[, , 2:4] = c(V[x <- 3:1, , 1], V[, x, 1], V[x, x, 1]) V[, , 5:8] = apply(V[, , 1:4], 3, t) # Create eight copies of the 19683 boards with each transformation d = aperm(array(b[c(V), ], c(9, 8, 3 ^ 9)), c(1, 3, 2)) v = matrix(V, 9) # Create reverse transformations (which are the same except for rotation) w = v[, c(1:5, 7, 6, 8)] # Find the sums of each transformation using base 3 e = apply(d * E, 2:3, sum) # Find the lowest possible sum for each board's transformed versions # This will be the one used for the matchboxes f = matrix(match(e, 1:3 ^ 9), , 8) g = apply(f, 1, min) # Store which transformation was necessary to convert the lowest board # into this one G = 9 - apply(t(e == g) * 8:1, 2, max) # Work out which boards have 3-in-a-row h = colSums(array(c(b, d[, , 5], b[c(1, 5, 9, 3, 5, 7, 1:3), ]), c(3, 3, 3 ^ 9, 3)) * 3 ^ (0:2)) k = rowSums(colSums(h == 13)) > 0 # player 1 wins l = rowSums(colSums(h == 26)) > 0 # player 2 wins # Store how many cells are filled o = colSums(b > 0) # Create matchboxes. These contain the actual board configuration, but # instead of zeroes for blanks have a minus number. This is initially -1, # but will ultimately represent the number of beads for that spot on the # board. M = b M[M == 0] = -1 repeat { # Initialise board and storage of moves and intermediate board positions A = b[, t <- 3 ^ 9] z = j = c() C = 1 # If we're automating player 2 also, initialise its storage if (auto) { Z = J = c() } repeat { # If the current board's matchbox is empty, put up to three more beads # back in if (sum(pmax(-M[, t], 0)) == 0) { M[sample(9, pmin(3, sum(x)), , x <- M[, t] == 0), t] = -1 } # Take out a bead from the matchbox u = sample(9, 1, , pmax(-M[, t], 0)) # Mark the bead as taken out M[u, t] = M[u, t] + 1 # Store the bead and board position in the chain for this game z = c(z, u) j = c(j, t) # Mark the spot on the board A[v[, C][u]] = 1 # Print the board if (!auto) print_board(matrix(A, 3)) # Check if player 1 has won or board is full if (k[B <- sum(A * E)] || o[B] == 9) break if (auto) { # Repeat for player 2 if we're automating its moves # Note if auto == 1 then we pick at random # If auto == 2 we use the same algorithm as player 1 D = g[B] if (sum(pmax(-M[, D], 0)) == 0) { M[sample(9, pmin(3, sum(x)), , x <- M[, D] == 0), D] = -1 } U = sample(9, 1, , if (auto == 1) M[, D] <= 0 else pmax(-M[, D], 0)) Z = c(Z, U) J = c(J, D) A[v[, G[B]][U]] = 2 } else { cat( "Please enter move (LMR for top/middle/bottom row and\nLMR for left/middle/right column, e.g. MR:" ) repeat { # Convert LMR into numbers q = ceiling((utf8ToInt(readline()) - 76) / 5) if (length(q) != 2) stop("Finished") if (all(q %in% 0:2) && A[q %*% c(1, 3) + 1] == 0) { break } else { message("Invalid input, please try again") } } A[q %*% c(1, 3) + 1] = 2 } if (l[B <- sum(A * E)]) break # Player 2 has won t = g[B] C = G[B] } if (auto) { cat(c("D", 1:2)[1 + k[B] + 2 * l[B]]) } else { cat("Outcome:", c("Draw", sprintf("Player %d wins", 1:2))[1 + k[B] + 2 * l[B]], "\n") } # Add beads back to matchbox M[x] = M[x <- cbind(z, j)] - k[B] - 1 + l[B] if (auto) M[x] = M[x <- cbind(Z, J)] - l[B] - 1 + k[B] } ``` ]
[Question] [ Minecraft inventory management is hard. You have 17 diamonds, but you need 7 to craft an enchantment table, a pickaxe, and a sword. Do you pick them up and right click 7 times? Or do you right click once and right click twice and take the 7 left? It's so confusing! for those of you who are now confused, don't worry, I'll explain it all in a sec # Challenge Given the size of a stack of items and a desired amount, determine the least number of clicks to get that amount. You only need to handle up to 64 for both inputs and you may assume you have infinite inventory slots. You cannot use the drag-to-distribute trick. # Definitions The **inventory** is a collection of slots where you can store items. A **slot** is a storage space in your inventory where you can place up to one type of item. A **stack** is a number of items placed in the same group. For the purposes of this challenge, a stack is simply a bunch of items in the same place (so ignore stack-size) The **cursor** is your pointy thingy. That cursor. It can have items "on it"; in other terms, if you clicked on a slot and picked up items, the items you picked up are "on the cursor" until you put them down. # Specifications There are four possible situations. Either you have an item on your cursor or you don't, and either you left click or you right click. If you don't have an item on your cursor and you left-click on a slot, you pick up the entire stack. If you don't have an item on your cursor and you right-click on a slot, you pick up half the stack, rounded up. If you have an item on your cursor and you left-click on a slot, you place all of the items into that slot. (For all you Minecraft players, you won't have >64 items for this challenge and they're all 64-stackable, and you only have one type so the item swap does not apply here) If you have an item on your cursor and you right-click on a slot, you place one item into that slot. So, you start with all of the items given (first input, or second; you may choose the order) in a slot, and you want to finish with having the desired amount (other input) in your cursor. Let's run through an example. Say you start with 17 items and you want 7. First, you right-click on the stack, which means you have picked up 9 and there are 8 in that slot. Then, if you right-click on the stack again, you place one item back into the slot, leaving you with 8 and the slot with 9. Finally, you right-click again and you have 7 and the slot has 10. Thus, you would return `3` (the number of clicks). If you manage to out-click-golf me, please tell me and I will edit the example :P # Test Cases These are manually generated, so please tell me if there are any errors. I do inventory management through jitter-clicking right click so I don't have experience with optimal inventory management :P ``` Given, Desired -> Output 17, 7 -> 3 64, 8 -> 5 63, 8 -> 5 10, 10 -> 1 10, 0 -> 0 # note this case 25, 17 -> 7 ``` # Explanations This challenge might be tricky for non-Minecraft players, I have no idea. Here are some explanations. `64, 8 -> 5` because you pick up 32 using right click, place it down, pick up 16, place it down, then pick up 8. `63, 8 -> 5` for the same reason. `25, 17 -> 7` because you pick up 13, place it down, pick up 6 from the leftover 12, place 2 back into the leftover stack, and then place the 4 in the cursor into the 13, and then pick those up. # Rules * Standard loopholes apply * You may assume that `0 <= desired <= given <= 64` * You may take input in either order and do I/O in any reasonable format [Answer] # [C++](https://tio.run/##RVJha9swEP2eX3Gj0EhIce2tFBZZHaRfQ0ZoCoGQD54ipwq24koKMRj/9blne0uF0Z3vvXu6Z1lV1eyoVNfdmbI6u5D@McE/@HBQjEXvz5O7g86N1RBgFeXG@XCrbMFG2mVeE4uIPdyAiijamJwoKR11OlychUJgYRnpsioypclVNparlhc08lqd7YGud2@M7eVVtDedDXnlL9RGxnrtAnmloiIvdIsJFZOLN/YIpcRJ5/PyUgTjdUiNDc9ihPwIVZlxackHwMN697Nfe4HvUPOCL/jbkOek37OeB26Y/ttt9liMh2RV6gehJSrlpMlavpAx5Ve@EssdGpDJXuZ7kZ8dEYI2hVzuVnK9W6CxPUtELVf/3Irw31RMB3p/rJkH2pRgZRBbYtAjDlHTZkMMq3lM@5jwepbQtp@uvr83tKmQiMDDd25muNMWV1dmxhIKzQRQGkZtkGgDQyrh6RETxjgMrtT5EtJ0SLU9FEPbV99p7Dv1fQYjYyMBevADQfxuHE54H1i76UGagnrPHEGGhCSGXzDdTGEO03gKDD4GejvBp@3@qrzIjr6bYbfEfy557Ga/f3wC), ~~498~~ ~~482~~ 457 bytes If this function is just called once, it can be 455 bytes. I found that almost every online GCC compilers (including TIO) forbids me to omit the type of the function `f`. However, the GCC on my computer allows that, and I don't know why. This one can handle large inputs if a slot can contain that number of items (though needs a larger array and will probably run out of time). ``` #import<bits/stdc++.h> #define t N.first #define X n.erase(n.find #define p(c){if(c==r)return l;if(L.emplace(w={n,c},l).second)Q[U++]=w;} #define T(S,C)n.insert(S);p(C)X(S)); using m=std::multiset<int>;using s=std::pair<m,int>;s Q[99999];int x,l,B,U;int f(int a,int r){if(!r)return 0;std::map<s,int>L;s f({a},B=0),w,N;L[Q[U=1]=f];for(;;){l=L[N=Q[B++]]+1;x=N.second;t.insert(0);for(int i:t){m n=t;X(i));if(x){T(i+x,0)T(i+1,x-1)}if(!x&&i){p(i)T(i/2,i-i/2)}}}} ``` Ungolfed: ``` #include <map> #include <set> #include <queue> #include <iostream> using namespace std; struct state { multiset<int> t; int q; bool operator<(const state& i) const { return make_pair(t, q) < make_pair(i.t, i.q); } }; int f(int a, int target) { if (target == 0) return 0; map<state, int> len; queue<state> qu; state first = {{a}, 0}; qu.push(first); len[first] = 0; #define push(c) { state a = {n, c}; auto t = len.insert({a, l + 1}); if (t.second) { \ if (a.q == target) return l + 1; qu.push(a); \ } } // push new state into queue and check for termination #define next(stk, cur) { n.insert(stk); push(cur); n.erase(n.find(stk)); } // insert new stack, push new state, erase the stack (for another use) while (qu.size()) { // BFS cycle state now = qu.front(); qu.pop(); int q = now.q; int l = len[now]; multiset<int> n(now.t); for (int i : now.t) { // click on non-empty stack n.erase(n.find(i)); if (!q) { // nothing on cursor push(i); // click left next(i / 2, (i + 1) / 2); // click right } else { // item on cursor next(i + q, 0); // click left next(i + 1, q - 1); // click right } n.insert(i); } if (q) { // click on empty stack next(q, 0); // click left next(1, q - 1); // click right } } } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 74 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ẏċ⁴¬ HĊ,$Ḟµ€1¦€F€;⁸Ḣ,$€ ‘1¦€ṭ€⁹’¤ +1¦€⁹ṭ€0;ç ⁹Ȧ‘Ḥ¤ŀ Ṫ;0ṙJ$çḢ Wṭ0WÇ€Ẏ$ÑпL’ ``` A full program with first input (3rd argument) the current stack and the second input (4th argument) the wanted cursor. **[Try it online!](https://tio.run/##y0rNyan8///hrr4j3Y8atxxaw@VxpEtH5eGOeYe2PmpaY3hoGZB0A2LrR407Hu5YpKMCZHM9apgBkXm4cy2QfNS481HDzENLuLQhokA@RMLA@vByLiDvxDKgjoc7lhxacrSB6@HOVdYGD3fO9FI5vBxoIlc4UK1B@OF2kHG7@lQOTzw84dB@H6CB////NzT/bw4A "Jelly – Try It Online")** Due to the implementation this hits the 60 second TIO time out for the `25, 17` test case. This may be remedied by removing the redundancies left in for golfiness using [this 84 byter](https://tio.run/##y0rNyan8///hrr4j3Y8atxxaw@VxpEtH5eGOeYe2PmpaY3hoGZB0A2LrR407Hu5YpKMCZHM9apgBkXm4cy2QfNS481HDzENLuLQhokA@RMLA@vByLiDvxDKgjoc7lhxacrSB6@HOVdYGD3fO9FI5vBxo4sMd88EGLTq01ACs24ArHKjbIPxwO0h8V59KoMrhiYcnHNrvA7Tk////Rqb/Dc0B "Jelly – Try It Online") (which filters out zero-sized stacks and sorts those remaining with `ḟ€Ṣ¥0¦€0` at the end of link 6 and only keeps unique states at each step with the use of `Q$` in the Main link). ### How? The program implements the defined state-machine. It creates the original state `[0, [argument 1]]` then steps through to all the next possible states repeatedly until one is found matching `[argument 2, [...]]`. Note: the program entry is at the "Main link" which is the bottommost one (`Wṭ0WÇ€Ẏ$ÑпL’`) ``` Ẏċ⁴¬ - Link 1, test a list of states for not having the desired cursor Ẏ - tighten by one ⁴ - program's fourth argument (second input) - desired cursor ċ - count occurrences (the stack list will never match, so just inspecting the cursors) ¬ - logical negation HĊ,$Ḟµ€1¦€F€;⁸Ḣ,$€ - Link 2, next states given a 0 cursor: list, rotatedStacks; number currentCursor (unused) µ€1¦€ - for each rotation of rotatedStacks apply to the first element: H - halve $ - last two links as a monad Ċ - ceiling , - pair Ḟ - floor (vectorises) -- i.e. n -> [floor(ceil(n/2)),floor(n/2)] = [ceil(n/2),floor(n/2)] F€ - flatten each -- i.e. each [[c1,f1],s2, s3,...] -> [c1,f1,s2,s3,...] ⁸ - chain's left argument, rotatedStacks ; - concatenate -- i.e. [[c1,f1,s2,s3,...],[c2,f2,s3,...,s1],...,[s1,s2,s3,...],[s2,s3,...,s1],...] $€ - last two links as a monad for each: Ḣ - head , - pair -- i.e. [c1,f1,s2,s3,...] -> [c1,[f1,s2,s3,...]] ‘1¦€ṭ€⁹’¤ - Link 3, next states given a non-0 cursor and a right-click: list, rotatedStacks; number currentCursor 1¦€ - for each rotation of rotatedStacks apply to the first element: ‘ - increment -- i.e. place an item into the first stack of each rotation ¤ - nilad followed by link(s) as a nilad: ⁹ - chain's right argument -- currentCursor ’ - decrement ṭ€ - tack each -- i.e. [s1-1,s2,s2,...] -> [currentCursor-1,[s1-1,s2,s2,...]] +1¦€⁹ṭ€0;ç - Link 4, next states given a non-0 cursor: list, rotatedStacks; number currentCursor 1¦€ - for each rotation of rotatedStacks apply to the first element: ⁹ - chain's right argument -- currentCursor + - add ṭ€0 - tack each to zero -- i.e. [s1+currentCursor,s2,s3,...] -> [0,[s1+currentCursor,s2,s3,...]] ç - call the last link (3) as a dyad -- get the right-click states ; - concatenate ⁹Ȧ‘Ḥ¤ŀ - Link 5, next states: list, rotatedStacks; number currentCursor ŀ - call link at the given index as a dyad... ¤ - nilad followed by link(s) as a nilad: ⁹ - chain's right argument -- currentCursor Ȧ - any & all -- for our purposes zero if zero, one if not ‘ - increment Ḥ - double - -- i.e. call link 2 if currentCursor is zero else call link 4 Ṫ;0ṙJ$çḢ - Link 6, next states: currentState e.g. [cc, [s1, s2, s3, ...]] Ṫ - tail -- get the stacks, [s1, s2, s3, ...] ;0 - concatenate a zero - add an empty stack to the options for use $ - last two links as a monad for each: J - range(length) ṙ - rotate left by -- i.e. [[s2,s3,0,...,s1],[s3,0,...,s1,s2],[0,...,s1,s2,s3],[...,s1,s2,s3,0],...[s1,s2,s3,0,...]] Ḣ - head -- get the currentCursor, cc ç - call the last link (5) as a dyad Wṭ0WÇ€Ẏ$ÑпL’ - Main link: initialStack, requiredCursor W - wrap -- [initialStack] ṭ0 - tack to zero -- [0, [initialStack]] W - wrap -- [[0, [initialStack]]] п - loop while, collecting the results: Ñ - ...condition: call next link (1) as a monad -- cursor not found $ - ...do: last two links as a monad: Ç€ - call the last link (6) as a monad for each Ẏ - flatten the resulting list by one level L - length ’ - decremented (the collect while loop keeps the input too) ``` ]
[Question] [ Let's imagine we have a matrix of bits (which contains at least one `1`): ``` 0 1 0 1 1 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 0 1 0 1 0 1 1 0 0 1 0 0 1 1 0 1 0 0 0 1 0 1 1 0 0 1 0 ``` We want to set some of the bits in this matrix such that it forms a contiguous blob of `1`s, in which every `1` is directly or indirectly connected to every other `1` through orthogonal movement: ``` 0 1 1 1 1 1 1 0 0 1 0 0 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 1 1 1 0 1 0 1 1 0 0 1 0 0 1 1 1 1 0 0 0 1 1 1 1 0 0 1 0 ``` (You can see this more clearly by searching for `1` with your browser's "find" feature.) However, we also want to minimize the number of bits that we set. ## The Task Given a matrix (or array of arrays) of bits or booleans, return the minimum number of bits that need to be set to create a contiguous continent of `1`s. It should be possible to get from one set bit in the matrix to another by only traveling in an orthogonal direction to other set bits. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (measured in bytes) wins. ## Test Cases ``` 0 1 0 1 1 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 1 0 0 0 1 0 1 1 0 1 0 1 0 1 1 0 0 1 0 0 1 1 0 1 0 0 0 1 0 1 1 0 0 1 0 => 6 1 0 0 0 0 0 1 0 0 1 1 0 0 1 1 1 0 0 1 1 1 0 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 1 1 0 1 0 0 0 0 0 1 0 0 => 4 0 0 0 1 1 1 0 1 1 0 0 1 0 0 0 0 1 0 0 0 1 1 1 1 1 1 0 1 1 0 0 1 1 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 0 0 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 0 0 0 1 0 0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 0 0 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 1 0 0 1 0 1 1 0 0 1 1 1 0 0 0 0 1 => 8 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 => 0 ``` [Answer] # C (gcc), ~~308~~ 306 bytes Function `f` receives `(height, width, flattened array, pointer to ans)`, and returns answer by pointer. If there's no `1` in the matrix, it will return `0`. ``` #define v A[i] N,M,K,R,C,T,i,*A;s(x,y){i=x*M+y;if(!(x<0|y<0|x>=N|y>=M|v^1))v=2,s(x,y+1),s(x,y-1),s(x+1,y),s(x-1,y);}g(i){if(C<R){if(i^K){g(i+1);if(!v)C+=v=1,g(i+1),v=0,C--;}else{T=1;for(i=0;i<K&&!v;i++);s(i/M,i%M);for(i=0;i<K;i++)T&=v^1,v=!!v;if(T)R=C;}}}f(n,m,a,b)int*a,*b;{K=R=(N=n)*(M=m),A=a;g(0);*b=R;} ``` [Try it online!](https://tio.run/##lVHBioMwEL37FWmXSqIjaxZ6SqdQPIo9iLfSgm1NCWzdpV2CYvPt7qi7UPa2YZK8mTfz8iCn6HI69f3LudKmrphlm53Ze1vIIIUcEijAQLBRd95AKzqDTZCFrTKaz3izih8t7WaN20e7xuxhD1IIi28wtodSTCCaQChJYgDRAJS7cEOKmierfLzNIRUdFWlufMCKJESLEqYaWIwhiSLlqvd71RUolf64cYOxMqvU92dWmTAUZNW8ZmAWmXjmR67wkSyS0Gxo1rwQOSbKOad5DVco4ShM/RWUEBxVl2KOfIu1CHiGVwEbLNWFx0IFR8yV66mTXUtTc@F1HhuyZLdnyLoYGIX8OT32tCbqN/5S8v9T8omSTk0@yvpOSPMlLOkHfUoF5Z834jSfL85zmEqu/wY "C (gcc) – Try It Online") **Ungolfed:** ``` N,M,R,C,T,i,*A; // height, width, result, recursion depth s(x,y) { // depth first search: replace all 1 in the same connected component with 2 i=x*M+y; if(!(x<0|y<0|x>=N|y>=M|A[i]^1)) { // check if out of boundary A[i]=2; s(x, y+1),s(x, y-1),s(x+1, y),s(x-1, y); } } g(i) { // enumerate all posible solutions if(C<R) { if(i!=N*M) { g(i+1); // nothing change for this entry if (!A[i]) { // set the entry to 1 C++, A[i]=1; g(i+1); C--, A[i]=0; } } else { T=1; for (i=0; i<N*M && !A[i]; i++); // find first non-zero entry s(i/M, i%M); // replace the connected component for (i=0; i<N*M; i++) { T&=A[i]!=1; // check if no other components A[i]=!!A[i]; // change 2s back to 1 } if (T) R=C; // update answer } } } f(n,m,a,b)int*a,*b;{ R=(N=n)*(M=m), A=a; g(0); *b=R; } ``` [Answer] # [Python 2](https://docs.python.org/2/), 611 bytes A full program that takes a list of lists through user input. The functions `I` and `d` count the number of islands in the array. The for loop at the end enumerates through all possibilities of where you can change `0`s to `1`s then if there is one island left stores the number of `1`s added to the list `C`. The minimum of that list is the minimum number of bit flips required to connect any islands. It is a very slow algorithm so it doesn't run the test cases given in under 60s (I didn't try longer) but I tried a few smaller (~5x5) test cases and it seems to be working correctly. I got the island counting algorithm from [this](http://www.geeksforgeeks.org/find-number-of-islands/) page. ``` from itertools import* def d(g,i,j,v): v[i][j],R,C=1,[-1,1,0,0],[0,0,-1,1] for k in range(4): if len(g)>i+R[k]>=0<=j+C[k]<len(g[0]): if v[i+R[k]][j+C[k]]<1and g[i+R[k]][j+C[k]]:v=d(g,i+R[k],j+C[k],v) return v def I(g): w=len(g[0]) v,c=[w*[0]for r in g],0 for i in range(len(g)*w): if v[i/w][i%w]<1and g[i/w][i%w]>0:v=d(g,i/w,i%w,v);c+=1 return c g=input() C=[] for p in [list(t)for t in product([0,1],repeat=sum(r.count(0)for r in g))]: h,G,x=0,[r[:]for r in g],len(g[0]) for i in range(x*len(G)): if G[i/x][i%x]<1:h+=p[0];G[i/x][i%x]=p[0];del p[0] if I(G)<2: C.append(h) print min(C) ``` [Try it online!](https://tio.run/##XZI/k8IgEMXr41PQ3AzoniY3V6nYpHBsbRkKJ8GIJoRBYrxP7y2J/84UDDx25/0eWfcb9o39vl53vqmpCdqHpqlO1NSu8WFECr2jBSvBwAHOfEboWRolDwo2kIkU5FcKKSSQKJC4QjwqQneNp0dqLPVbW2r2g40fZkcrbVnJl2a8kUe1FMlCHMYZbhf9hUxUrKNYiCZ9DTr1BWqRbm1By3d5dhY9XK/CICImoV6H1lt67vnXaIrknXjYYAzIhexGeIisPrKWCpIB3TzRB@RRd0uAYNNOSfPZPZHuwjK540w7QAFB5vlYpA@anD4/UgpjXRsYJ5mQikRbF21lZU6BBR6FEAXnm6LNA8P3TRV47fQ2iFNbMz/Jm9YGlvBnBM4VJt3DCi4iAenl7F@@lwd4y3kZxbsVv@VcYaxLjHXBnLP9WDjsmr@og1DoisYNiT9tje2Lb@zPJlvntC3YnhPnjQ20NpZl/HqVMg5L@hiXYXD6AcJw6g8 "Python 2 – Try It Online") Pregolfed version before I optimized a few things: ``` from itertools import* def d(g,i,j,v): v[i][j]=1 R=[-1,1,0,0] C=[0,0,-1,1] for k in range(4): if len(g)>i+R[k]>=0<=j+C[k]<len(g[0]): if v[i+R[k]][j+C[k]]<1: if g[i+R[k]][j+C[k]]: v=d(g,i+R[k],j+C[k],v) return v def I(g): w=len(g[0]) v=[[0]*w for r in g] c=0 for i in range(len(g)): for j in range(w): if v[i][j]<1and g[i][j]>0: v=d(g,i,j,v) c+=1 return c g=input() z=sum(r.count(0)for r in g) f=[list(t)for t in product('01',repeat=z)] C=[] for p in f: h=0 G=[r[:]for r in g] x=len(G[0]) for i in range(x*len(G)): exec('h+=int(p[0]);G[i/x][i%x]=int(p[0]);del p[0]'*(G[i/x][i%x]<1)) if I(G)<2: C.append(h) print min(C) ``` ]
[Question] [ You end up having a lot of very long, boring-looking conditionals in your code: ``` if flag == 1: while have != needed: if type == 7: ``` These can be transformed into their much more lovable `<3` conditionals counterparts: ``` if abs(flag - 1) + 2 <3: while 3 - abs(have - needed) <3: if 2 + abs(type - 7) <3: ``` ### Task Your task is to take a conditional and make it in terms of `<3`. The only spacing that matters is that there is none between `<` and `3`. Conditionals will be two expressions seperated by either `==`, `!=`, `>`, `<`, `>=` or `<=`. Expressions will only contain addition, subtraction, unary negation (`-something`), where there is one `+` or `-` before each variables or numbers (except the first which has nothing or `-` before it). Numbers will be `[0-9]+`, and variables will be `[a-z]+`. If the answer needs to use `|x|` (The absolute value of `x`), use the `abs()` function. You may assume that all variables are integers, and all number constants in the input are < 1000. The output does *not* need to be in it's simplest form. It does need to be a conditional like above, meaning that it is two expressions only, seperated by one conditional sign, but it can also use the `abs` function, enclosing a valid expression, and then it acts like a variable, in terms of validity. If the input does not have an output for any value of a variable, output a condition that is always false, but still in terms of `<3`. Part of the challenge is figuring out how to do it, but here are the steps for the `have != needed` above: ``` have != needed have - needed != 0 abs(have - needed) > 0 -abs(have - needed) < 0 3 - abs(have - needed) <3 ``` ### Scoring This is code-golf, so the shortest valid code, in bytes, wins. ### Test cases (Note, these outputs aren't the only outputs, but I tried to simplify them.) ``` flag == 1 abs(flag - 1) + 2 <3 have != needed 3 - abs(have - needed) <3 type == 7 2 + abs(type - 7) <3 x > y 3 - x + y <3 x + 5 < -y x + 8 + y <3 x + 6 <= y x + 8 - y <3 -x >= y + 3 x + y + 5 <3 x < x 3 <3 # Unsimplified; both would be valid outputs. x - x + 3 <3 ``` [Answer] # [Retina](https://github.com/m-ender/retina), 95 bytes ``` <= <1+ >= >-1+ (.*)(.=)(.*) $2abs($1-($3)) == 2+ != 3- (.*)>(.*) $2<$1 (.*)<(.*) $1-($2)+3 $ <3 ``` [Try it online!](https://tio.run/##LcrLCoAgEEbh/f8UBrNwEgV1O@O7GFQE0aJ6f7uuDge@fTyXrbYmCokORVH8XRt6tkH5KSjV4bAUvaXMDFUkh06R/evKj4Ti@/L9wxO7DILk1qa1zkbVxAs "Retina – Try It Online") A rather naïve solution, but I haven't been able to find any improvements. This is just a series of replacements: ``` <= <1+ >= >-1+ ``` Get rid of "or equal to" comparisons by replacing `x <= y` with `x < 1 + y`, and `x >= y` with `x > -1 + y`. ``` (.*)(.=)(.*) $2abs($1-($3)) ``` Replace `x == y` with `==abs(x - y)`, and `x != y` with `!=abs(x - y)`. ``` == 2+ != 3- ``` Replace `==` with `2+` and `!=` with `3-`, so that the overall replacements become `x == y` → `2 + abs(x - y)` and `x != y` → `3 - abs(x - y)`. ``` (.*)>(.*) $2<$1 ``` Normalize the direction of the remaining inequalities, replacing `x > y` with `y < x`. ``` (.*)<(.*) $1-($2)+3 ``` Replace `x < y` with `x - y + 3`. ``` $ <3 ``` Append a heart to the end of the string. ]
[Question] [ ## Introduction You have been tasked to write a program that splits a rectangular integer array evenly in half (for whatever reason). This task is computationally intensive, but luckily you have a dual-core machine to perform the calculations. To maximize the benefits of parallelism, you decide to split the program evenly in half and let each core run one of the parts independently of the other. ## Input and output Your input is a rectangular 2D array of nonnegative integers of size at least **1×1**, taken in any reasonable format. A *splitting* of such an array is obtained by splitting each horizontal row into a prefix and a suffix (either of which may be empty). For a splitting to be valid, two adjacent rows must be split at the same index or adjacent indices. For example, consider the array ``` 2 4 5 5 6 3 9 7 1 7 7 0 0 0 3 6 7 8 1 2 4 7 6 1 6 6 8 2 0 0 ``` This is a valid splitting: ``` 2;4 5 5 6 3 ;9 7 1 7 7 0 ;0 0 3 6 7 8 1;2 4 7 6 1 6 6;8 2 0 0 ``` This is also a valid splitting: ``` 2 4 5 5 6 3; 9 7 1 7 7;0 0 0 3 6 7;8 1 2 4 7;6 1 6 6 8;2 0 0 ``` This is not a valid splitting: ``` 2 4;5 5 6 3 9 7 1;7 7 0 0;0 3 6 7 8 1 2;4 7 6 1 6 6;8 2 0 0 ``` Your output shall be the minimum value of ``` abs(sum_of_prefixes - sum_of_suffixes) ``` over all valid splittings of the input. ## Rules and scoring You shall write **two** programs (either full programs or functions) in the same language, which must not have any shared code between them. Let's call them **P1** and **P2**. Program **P1** takes the input array, and outputs *something*. Program **P2** takes this something as input, and outputs the answer of the above task for the input array. Your score is the **maximum** of the byte counts of **P1** and **P2**, lower score being better. Some clarifications: * You can write two full prorgams, one function and one full program, or two functions. * In the case of two full programs, the entire output of **P1** is fed to **P2** as input, as in the Unix pipeline `P1 | P2`. The programs must function correctly if compiled/interpreted from two separate source files. * If either program is a function, it is converted to a full program by adding the necessary boilerplate code, and the above rule is applied to it. In particular, two functions cannot use shared auxiliary functions, shared import statements, or shared global variables. ## Test cases ``` [[1]] -> 1 [[4,5],[8,3]] -> 4 [[8],[11],[8],[10],[4]] -> 1 [[5,7,0,9,11,2,1]] -> 7 [[146,194,71,49],[233,163,172,21],[121,173,14,302],[259,169,26,5],[164,30,108,37],[88,55,15,2]] -> 3 [[138,2,37,2],[168,382,33,77],[31,199,7,15],[192,113,129,15],[172,88,78,169],[28,6,97,197]] -> 7 [[34,173,9,39,91],[169,23,56,74,5],[40,153,80,60,28],[8,34,102,60,32],[103,88,277,4,2]] -> 0 [[65,124,184,141],[71,235,82,51],[78,1,151,201],[12,24,32,278],[38,13,10,128],[9,174,237,113]] -> 2 [[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]] -> 8 ``` [Answer] ## Haskell, 102 bytes Function 1 (102 bytes): ``` l=length []#i=[[]] (r:s)#i=id=<<[(splitAt j r:)<$>s#j|j<-[i-1..i+1],j>=0,j<l r] f r=(r#)=<<[0..l$r!!0] ``` Function 2 (90 bytes): ``` g::[[([Int],[Int])]]->Int g a=minimum$map(\(x,y)->abs$sum(sum<$>x)-sum(sum<$>y))$unzip<$>a ``` Missing boilerplate for F1 to make it a full program, including the hardcoded integer array to check: ``` main = print $ f [[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]] ``` and for F2: ``` main = print . g . read =<< getContents ``` Now you can call `runhaskell f1.hs | runhaskell f2.hs` which outputs `8`. How it works: `f` takes a list of list of integers. ``` f r = (r#)=<<[0..l$r!!0] -- for each index [0 .. length r] call # with -- the first parameter being r and -- collect the results in a single list []#i=[[]] -- base case. If the list of lists is empty, stop (r:s)#i -- else let r be the first list, s all others j<-[i-1..i+1], -- foreach possible index j for the next line j>=0,j<l r -- (skipping out of range indices) (splitAt j r:)<$> -- split the current line at j into a pair of -- lists and prepend it to every element of s#j -- a recursive call with s and j id=<< -- flatten into a single list ``` Now we have a list of all possible splits, for example the first one and a random one from the middle ``` [([],[164,187,17,0,277]), [([164,187],[17,0,277]), ([],[108,96,121,263,211]), ([108,96],[121,263,211]), ([],[166,6,57,49,73]), ([166],[6,57,49,73]), ([],[90,186,26,82,138]), ([90,186],[26,82,138]), ([],[173,60,171,265,96])] ([173,60,171],[265,96])] ``` Function `g` takes such a list and ``` unzip<$>a -- turn every pair of lists into a list of pairs map(\(x,y)-> -- foreach such pair abs$sum(sum<$>x)-sum(sum<$>y) -- calculate the score minimum -- and find the minimum ``` Note: the second function can be golfed a little bit more, but it doesn't change the score. ]
[Question] [ # Introduction I'm a real big fan of the SBU (Short But Unique) challenges that crop up on PPCG all of the time. The CUSRS is a system designed to refactor strings, a CUSRS function takes 2 parameters and outputs 1 String. # Challenge Produce a program, function, lambda or acceptable alternative to do the following: Given `String input` and `String refactor` (as examples), refactor `input` using `refactor` as follows: The `refactor` String will be in the format of `((\+|\-)\w* *)+` (regex), for example: ``` +Code -Golf -lf +al ``` Each section is a refactoring action to perform on `input`. Each program also has a pointer. `+` Will insert it's suffix (without the plus) at the pointers current location in the String and then reset the pointer to 0. Each operation should be applied to the `input` String and the result should be returned. Example: ``` input: Golf +Code //pointer location: 0 output: CodeGolf //pointer location: 0 ``` `-` Will increment the pointer through the String until it finds the suffix. The suffix will be removed from the String and the pointer will be left on the left side of the removed text. If no suffix is found the pointer will simply progress to the end of the String and be left there. ``` input: Golf -lf //pointer location 0 output: Go //pointer location 2 ``` # Examples ``` input: "Simple" "-impl +nip -e +er" output: "Sniper" input: "Function" "-F +Conj" output: "Conjunction" input: "Goal" "+Code -al +lf" output: "CodeGolf" input: "Chocolate" "Chocolate" output: "Chocolate" //Nothing happens... input: "Hello" "-lo+p +Please" //Spaces are irrelevant output: "PleaseHelp" input: "Mississippi" "-s-s-i-ppi+ng" //Operations can be in any order output: "Missing" input: "abcb" "-c -b +d" output: "abd" input: "1+1=2" "-1+22-=2+=23" outut: "22+1=23" ``` # Example Code The example is Java, it's not golfed at all. ``` public static String refactor(String input, String swap) { int pointer = 0; String[] commands = swap.replace(" ", "").split("(?=[-+])"); for (String s : commands) { if (s.startsWith("+")) { input = input.substring(0, pointer) + s.substring(1) + input.substring(pointer, input.length()); pointer = 0; } else { if (s.startsWith("-")) { String remove = s.substring(1); for (int i = pointer; i < input.length(); i++) { if (input.substring(i, i + remove.length() > input.length() ? input.length() : i + remove.length()).equals(remove)) { pointer = i; input = input.substring(0, i) + input.substring(i + remove.length(), input.length()); break; } } } } } return input; } ``` # Rules * Standard Loopholes Apply * Shortest code, in bytes, wins [Answer] # APL, ~~91~~ 90 bytes ``` {s l←⍵0⋄s⊣{g←1↓⍵⋄'+'=⊃⍵:+s∘←(l↑s),g,l↓s⋄l∘←¯1+1⍳⍨g⍷s⋄+s∘←(l↑s),s↓⍨l+⍴g}¨{1↓¨⍵⊂⍨⍵=⊃⍵}' ',⍺} ``` This takes the string as its right argument, and the commands as its left argument, like so: ``` '+Code -al +lf' {s l←⍵0⋄s⊣{g←1↓⍵⋄'+'=⊃⍵:+s∘←(l↑s),g,l↓s⋄l∘←¯1+1⍳⍨g⍷s⋄+s∘←(l↑s),s↓⍨l+⍴g}¨{1↓¨⍵⊂⍨⍵=⊃⍵}' ',⍺} 'Goal' CodeGolf ``` [Answer] # GolfScript, 97 Bytes ``` " "%(:s;0:p;{("-"0=={.s p>\?.-1={;;s,:p;}{:p;,:l;s p<s p l+>+:s;}if}{s p<\+s p>+:s;0:p;}if}/"\n"s ``` Test: [golfscript.tryitonline.net](http://golfscript.tryitonline.net/#code=IiAiJSg6czswOnA7eygiLSIwPT17LnMgcD5cPy4tMT17OztzLDpwO317OnA7LDpsO3MgcDxzIHAgbCs-KzpzO31pZn17cyBwPFwrcyBwPis6czswOnA7fWlmfS8iXG4icw&input=U2ltcGxlIC1pbXBsICtuaXAgLWUgK2Vy) [Answer] ## Python 3 (~~164~~ ~~194~~ ~~186~~ ~~181~~ ~~168~~ 165 bytes) ``` p=0 w,*x=input().split() for i in x: if '-'>i:w,p=w[:p]+i[1:]+w[p:],0 else: try:p=w.index(i[1:],p) except:p=len(w) w=w[:p]+w[p:].replace(i[1:],'',1) print(w) ``` Example demonstrating the pointer moving to the end if it doesn't find a substring: ``` Input: HelloThere -x +Friend Output: HelloThereFriend ``` Special thanks to Artyer for saving me 13 bytes. Another thanks to Artyer for saving me another 3 bytes via the `beg` parameter of `index`. Old answer: ``` p=0 x=input().split() w=x[0] for i in x[1:]: if i[0]=='+': w=w[:p]+i[1:]+w[p:] p=0 else: p=w[p:].index(i[1:])+p w=w[:p]+w[p:].replace(i[1:],'',1) print(w) ``` Example demonstrating the pointer works (all the examples in the Q work even if you don't factor in the pointer and simply replace on first occurence): ``` Input: HelloThereCowboy -r -e -y +ySays +Oh Output: OhHelloTheCowboySays ``` Edit: Since 2 minutes ago my answer is now invalid according to a comment by the asker. > > aaa -b +b would result with aaab because the pointer would go all the > way to the end. > > > Edit2: Fixed. [Answer] ## JavaScript (ES6), 117 bytes ``` (s,r,t='')=>r.match(/\S\w*/g).map(r=>(q=r.slice(1),r<'-'?(s=t+q+s.t=''):([b,...a]=s.split(q),t+=b,s=a.join(q))))&&t+s ``` Explanation: Instead of using a cumbersome pointer, I keep the left half of the string in `t` and the right half in `s`. Additionally, `split` and `join` are a convenient way to perform the removal. ]
[Question] [ Consider the following definitions taken from [The number of runs in a string](https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjx8rGd0tXNAhVTOMAKHQZtBCsQFggeMAA&url=http%3A%2F%2Fwww.sciencedirect.com%2Fscience%2Farticle%2Fpii%2FS0890540107000107&usg=AFQjCNF4GKi49CBt1sIZACd4ypv2MSUD5g&sig2=EDfaYr4JLTD2xO4iweWzXA) by W. Rytter. Note that word, string and substring are all roughly synonyms. > > A run in a string is a nonextendable (with the same minimal period) > periodic segment in a string. > > > A period p of a word w is any positive integer p such that w[i]=w[i+p] > whenever both sides of this equation are defined. Let per(w) denote > the size of the smallest period of w . We say that a word w is > periodic iff per(w) <= |w|/2. > > > For, example consider the string `x = abcab`. `per(abcab) = 3` as `x[1] = x[1+3] = a`, `x[2]=x[2+3] = b` and there is no smaller period. The string `abcab` is therefore not periodic. However, the string `abab` is periodic as per(abab) = 2. A run (or maximal periodicity) in a string w is an interval [i...j] with j>=i, such that * w[i...j] is a periodic word with the period p = per(w[i...j]) * It is maximal. Formally, neither w[i-1] = w[i-1+p] nor w[j+1] = w[j+1-p]. Informally, the run cannot be contained in a larger run with the same period. Denote by RUNS(w) the set of runs of w. **Examples** The four runs of `atattatt` are [4,5] = tt, [7,8] = tt, [1,4] = atat, [2,8] = tattatt. The string `aabaabaaaacaacac` contains the following 7 runs: [1,2] = aa, [4,5] = aa, [7,10] = aaaa, [12,13] = aa, [13,16] = acac, [1,8] = aabaabaa, [9,15] = aacaaca. Your output should be a list of runs. Each run should specify the interval it represents but does not need to output the substring itself. The exact formatting can be whatever is convenient for you. The examples use 1-indexing but you are free to use 0-indexing instead if it is more convenient. **TASK** Write code that given a string w, output RUNS(w). **Languages and input** You can use any language you like and take the input string in whatever form is most convenient. You must give a full program however and you should show an example of your code running on the example input. [Answer] # Pyth, 38 bytes ``` {smm,hk+ekdfgaFTdcx1xM.ttB+0qVQ>QdZ2Sl m SlQ map for d in [1, …, len(input)]: qVQ>Qd pairwise equality of input[:-d] and input[d:] tB+0 duplicate this list, prepending 0 to one copy .t Z transpose, padding with 0 xM pairwise xor x1 find all occurrences of 1 c 2 chop into groups of 2 f filter for groups T such that: aFT the absolute difference between its elements g d is greater than or equal to d m map for groups k: hk first element , +ekd pair with the last element plus d s concatenate } deduplicate ``` [Test suite](https://pyth.herokuapp.com/?code=%7Bsmm%2Chk%2BekdfgaFTdcx1xM.ttB%2B0qVQ%3EQdZ2Sl&input=%22aabaabaaaacaacac%22&test_suite=1&test_suite_input=%22atattatt%22%0A%22aabaabaaaacaacac%22) [Answer] # CJam, 66 ``` q:A,2m*{~A>_@)_@<2*@@2*<=},{_2$-2>2,.+={+}&}*]{[_1=\)\0=2*)+]}%_&p ``` [Try it online](http://cjam.aditsu.net/#code=q%3AA%2C2m*%7B~A%3E_%40)_%40%3C2*%40%402*%3C%3D%7D%2C%7B_2%24-2%3E2%2C.%2B%3D%7B%2B%7D%26%7D*%5D%7B%5B_1%3D%5C)%5C0%3D2*)%2B%5D%7D%25_%26p&input=aabaabaaaacaacac) **Brief explanation:** The algorithm works in 4 steps (first 3 of them corresponding with the 3 main blocks you can observe): 1. Find all [length index] pairs that correspond to a duplicated substring (such as a**aba***aba*aaacaacac); these are parts of runs. 2. Concatenate pairs that are part of the same run, i.e. consecutive indices and same length/period. 3. Construct the actual runs, by taking the minimum index and maximum index + 2 \* length - 1. 4. At the end, remove the duplicated runs (which are the same interval obtained with a different period) I'd like to golf it more, so this is all subject to change. ]
[Question] [ ## Introduction Boardgames are a classic play between kids, but there are some kids that feel bored playing a boardgame step by step. Now they want the result to be shown before they put their hands on the board. ## Challenge Suppose this boardgame: `>---#<---X---<X<--#-$` ``` > means the start of the game - means a position without danger < means the player should return one step back X means the player won't move next round # means a portal where the player returns to the start position $ the first player to get there or after there wins the game ``` The input consists of a string with the boardgame's aspects described above and two arrays with some values (from `1` to `6`) in order that both players (kid `A` and kid `B`) had got when playing one cube. Both arrays will always have the same length >= 1. The kid `A` always start the game. You must output the kid which got the end or closer to the end first. If neither one got the end and both kids stay at the same position print `0` or any other falsy value. If one array runs out while the other has remaining dice rolls (due to one player missing several turns on Xs), the remaining dice rolls should be used up. For this task, you can create a program/function, that reads input from stdin, or take parameters/arguments and output/return/print the winner kid. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins! ## Example Input and Output You can also use diferrent formats of input, but you should only take the boardgame, the kid-A and the kid-B values. Example 1: ``` board: >---#<---X---<X<--#-$ kid-A: [3,6,6,5,2,1] kid-B: [4,5,3,5,5,5] output: A ``` Explaining: ``` >---#<---X---<X<--#-$ # both kids in position B--A#<---X---<X<--#-$ # kid-A moved 3 to - B--A#<---X---<X<--#-$ # kid-B moved 4 to # and returned home B---#<---A---<X<--#-$ # kid-A moved 6 to X and will wait one round B---#<---A---<X<--#-$ # kid-B moved 5 to < returned one to # and returned home >--B#<---A---<X<--#-$ # kid-B moved 3 to - >--B#<---X---<A<--#-$ # kid-A moved 6 to < returned one to X and will wait again >---#<--BX---<A<--#-$ # kid-B moved 5 to - >---#<---X--B<A<--#-$ # kid-B moved 5 to < returned one to - >---#<---X--B<X<--#A$ # kid-A moved 5 to - >---#<---X---<X<-B#A$ # kid-B moved 5 to - >---#<---X---<X<-B#-$A # kid-A moved 2 and won the game! ``` --- Example 2: ``` board: >-<<<<<$ kid-A: [1,2,3] kid-B: [5,5,4] output: 0 ``` --- Example 3: ``` board: >-<-<#<-<-<-$ kid-A: [5,4,2] kid-B: [1,1,1] output: B ``` Explaining: ``` >-<-<#<-<-<-$ # both kids in position >-<-<#<-<-<-$ # kid-A moved 5 to # returned home AB<-<#<-<-<-$ # kid-B moved 1 to - >B<A<#<-<-<-$ # kid-A moved 4 to < returned one to - >B<A<#<-<-<-$ # kid-B moved 1 to < returned one to - AB<-<#<-<-<-$ # kid-A moved 2 to # returned home AB<-<#<-<-<-$ # kid-B moved 1 to < returned one to - Current position: (A:0, B:1) output: B ``` [Answer] ## Perl, ~~188~~ 180 + 2 = 182 bytes Wuhuu, got to use `goto`. ``` @q=/.(?!$)/g,next if$w=$e=!@q;for(@F){a:$w+=$_;$_=$q[$w];/</?($_=-1,goto a):/X/?$e++:/#/?$w=0:!$_&&last;$e++}$r+=$"lt$r?-$w:$w;$t+=$"lt$t?-$e:$e-1}{say$w>@q?$t<0?B:A:!$r?0:$r<0?B:A ``` Requires `-a` and `-E`|`-M5.010`: ``` $ echo $'>-<-<#<-<-<-<-$\n5 4 2\n1 1 1' | perl -M5.010 boardgame.pl B ``` Somewhat ungolfed version: ``` #!/usr/bin/perl -a # Read all but last char from the board into an array @board = /.(?!$)/g,next if $pos = $turns = !@board; for (@F) { a: $pos+=$_; $_=$board[$pos]; /</?($_=-1,goto a): /X/?$turns++: /#/?$pos=0: # End of Game (Victory!) !$_&&last; $turns++ } # Make sure '$pos_diff' and '$turns_diff' are not zero by checking against [:space:] # ' ' is less than 0 on the ascii table $pos_diff += $"lt$pos_diff ? -$pos : $pos; $turns_diff += $"lt$turns_diff ? -$turns : $turns-1; }{ say $pos>@board? $turns_diff<0?B :A : !$pos_diff?0: $pos_diff<0?B: A ``` [Answer] # ~~Haskell, 142~~ ``` _![]=fail;g!(x:y)|x>length g=Just|1<2=g!fix(\f x->case(g!!x)of;'<'->f$x-1;'X'->(0:);'#'->map$(-)(-x);_->map(+x))x y;(g?a)b=(g!)a"A"<|>(g!)b"B" ``` Usage: ``` (?) "GAME" [kidA moves] [kidB moves] ``` Output: ``` (?) ">---#<---X---<X<--#-$" [3,6,6,5,2,1] [4,5,3,5,5,5] Just "A" ``` --- **Edit:** Jikes, I golfed it to death; it fails for the last example. I'll revive it shortly. ]
[Question] [ [SPICE](https://en.wikipedia.org/wiki/SPICE) is an electrical circuit simulation program originating from UC Berkeley. Your goal is to implement a minimalistic version which can solve for the nodal voltages and branch currents of a circuit composed of resistors and DC current sources. # Input Format The input may come from a file, io stream, or the nearest equivalent in your language of choice. However, it cannot be a function input or hard-coded string. The format should be a subset of what the original SPICE used. A quick summary of what is required for the input format: 1. First line is a title line 2. Following the title is the description of circuit components and their connectivity. This may be in any order (i.e. you can't assume all resistors come before current sources/vice-versa). See **component descriptors** below for how component descriptions are formatted. 3. Following the circuit components is the command control block. The only solver you need to implement is the DC operating point solver (`.OP`) 4. Following the command control block are the values to output (nodal voltages/branch currents). See **output descriptors** below for how these should be formatted. 5. The last line is `.END` (you may choose whether an ending carriage return is required or optional) 6. Any line beginning with `*` denotes a comment and must be skipped by your parser. ## Component Descriptors All component descriptors are in the form: ``` XN A B C ``` Where: * `X` is `R` for resistor or `I` for a current source * `XN` is the name of the component. `N` may be any alphanumeric sequence. * `A` is a non-negative integer indicating which node the positive terminal for the component is connected. * `B` is a non-negative integer indicating which node the negative terminal for the component is connected. * `C` is a decimal value (for a resistor this is the resistance, and for a current source this is the current from this source) * By convention, node `0` is considered *ground* and is at `0V`. All other nodal voltages are referenced from ground. * By convention, positive current flows from the positive terminal to the negative terminal. ## Output descriptors The only output format you need to support is `.PRINT`. This may output to a file, output stream, or the nearest equivalent in your language of choice. It may not be just a function return string. **Format of .PRINT statements**: ``` .PRINT X(N) ``` * `X` is `V` for printing a nodal voltage or `I` for printing the current through a component. * `N` is the name of the quantity being outputted. For a nodal voltage, this is any non-negative number. For a current, this is the component name. For each print statement, you should output the argument and the appropriate value `v`: ``` X(N) v ``` You may print the output in any order so long as there's one output per line. ## Things you don't have to support 1. Subcircuits 2. "Line continuations" (i.e. any lines starting with a `+`) 3. "SI" suffixes (e.g. `1k` instead of 1000). However, your code should be able to handle decimal input (you may specify the format) 4. Error handling (i.e. you may assume the input is properly formatted and has a unique solution) 5. You may specify any case requirements (all upper case, all lower case, case insensitive, case sensitive, etc.) 6. You may choose to require that the nodes may be ordered sequentially without skipping any integers. 7. You may use any solver algorithm you want. # Scoring and Misc. * This is code golf, shortest code in bytes wins. * You may use any libraries you wish provided it wasn't designed specifically for handling circuits. Ex.: Using BLAS/LAPACK for matrix math is ok, but you can't use [Ngspice](http://ngspice.sourceforge.net/) because it is a SPICE circuit simulator already. * Any other standard loop holes are prohibited. * For guidance on how to implement a solver, here's a quick guide on [modified nodal analysis](http://www.swarthmore.edu/NatSci/echeeve1/Ref/mna/MNA2.html). Note that because there are no voltage sources you can implement only the basic nodal analysis part (I link this resource because it has some good insights on how to implement such a solver). Additional resources on MNA and another another approach, sparse tableau analysis, can be found [here](https://www.ee.iitb.ac.in/~sequel/circuit_sim_1_handout.pdf). # Example inputs and expected outputs ## Ex. 1 ``` Example 1 * this is a comment R1 1 0 1 I1 0 1 1 .OP .PRINT I(R1) .PRINT V(1) .END ``` **Output:** ``` I(R1) 1 V(1) 1 ``` ## Ex. 2 ``` Example 2 I1 1 0 1 * this is a comment R1 1 0 1 .OP .PRINT V(0) .PRINT I(R1) .PRINT I(I1) .PRINT V(1) .END ``` **Output:** ``` V(0) 0 I(R1) -1 I(I1) 1 V(1) -1 ``` ## Ex. 3 ``` Example 2 ISINK 1 0 1.0 ISOURCE 0 2 2 R1 1 0 10 R2 1 2 1 .OP .PRINT V(1) .PRINT V(2) .PRINT I(R1) .PRINT I(ISOURCE) .PRINT I(R2) .END ``` **Output:** ``` V(1) 10 V(2) 12 I(R1) 1 I(ISOURCE) 2 I(R2) -2 ``` [Answer] # [Python](https://www.python.org) + [MiniZinc](https://www.minizinc.org/), ~~703~~ 642 bytes *thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) for the input to golf more* ``` import sys t=sys.stdin.readlines()[1:] d=[[x.split()[i]for x in t if x[0]not in".*"]for i in range(4)] a="array[1..m]of " F=r"/\forall(j in " print("output[",*(fr'"{x[7:-1]} \({x[7].lower()}[{x[7]=="I"and-~d[0].index(x[9:-2])or x[9:-2]}])\n",'for x in t if".P"==x[:2]),'""];',fr"int:m={len(d[0])};int:n={max(map(int,d[1]+d[2]))};"+fr"array[0..n]of var float:v;{a}var float:i;{a}int:s;{a+'int:e;enum T={R,I};'+a}T:t;{a}float:x;constraint v[0]=0{F}1..m)(t[j]=I/\x[j]=i[j]\/t[j]=R/\v[s[j]]-v[e[j]]=x[j]*i[j]){F}0..n)(sum([i[k]*((s[k]=j)-(e[k]=j))|k in 1..m])=0);") d[0],_=zip(*d[0]) for i,n in enumerate("tsex"):print(f"{n}=[{','.join(d[i])}];") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVLBjtQwDJU49isiX5p02swMQgJa5brS3NBqb2mEIppCZtu0SjJDh1IO_AaXvSwfxdeQtCDEJX62n61nOz9-jjf_aTBPT88X3xZvfr34rvtxsB65m0s8Cy91vtGGWiWbThvlMOHHUiQN43yibuy0DxEt2sGiCWmDPNItmvhBmCFAAzSDNalj0krzUeFXRCSSgbRW3viR0l4MLYLkjlnY14Eruw6fIx2S0WrjMQwXP148hzzDrU1hnvjrsjiKBdU4YkG74bOymCx8dRmDE0jTFN-aIIRq06gJT_xtWbwUJArd4CJIbSBP_9MO9B0wNvEyUPMUQFRp3loIMsqezZ0yOPYkSxUjhs29nHAvRxzcvOFHsWt4qAx52IWybcYDpSbOeJUWtd0gfXmtZrn8c3V0Y0MXwC6NSFXKXHr0wOb7_LRU6U4uD6WPvK1kqj4MxnkrAxldgyR2mO-WuE2CPT8LdtrXU7Q6PPV-Dd3v6yt3AYniylW0LFKySCGhOuok2F16zDV_FBnGLhh2JgVWGyBfH-Oi1qMRdiAVkCTuI3_PvugRZ-tukvXeuYnMOISy0isM3qkJSLmdtIXZLIzPaZ7S86DjVnXYqggNt6_450f-_Zm_AQ) How to run: `python <script file> | minizinc -`. It may be necessary to explicitly select the solver to use, passing the arguments `--solver <solver id>` to `minizinc`. ## What is MiniZinc? Minizinc is a [constraint programming](https://en.wikipedia.org/wiki/Constraint_programming) modelling language; the homonymous command line tool compiles the model, runs a solver, and outputs the solution in the desired format. It is not a proper programming language (since it is not Turing complete), but it can be considered a library since one could replace it by using its proper [native python interface](https://minizinc-python.readthedocs.io/en/latest/). ## How it works The Python code just handles the input format, translating it into a MiniZinc model. The model imposes the following constraints: * the voltage of node `0` must be `0`; * [Kirchhoff's current law](https://en.wikipedia.org/wiki/Kirchhoff%27s_circuit_laws#Kirchhoff%27s_current_law) must be respected in all nodes; * [Ohm's law](https://en.wikipedia.org/wiki/Ohm%27s_law) must be respected in all resistors. Here's an ungolfed version of the MiniZinc model (without the actual parameters): ``` % n is the number of nodes (excluding the ground node) % m is the number of edges (resistors and current sources) array[0..n] of var float: voltage; array[1..m] of var float: current; array[1..m] of 0..n: start; % the first node of each edge array[1..m] of 0..n: end; % the second node of each edge enum T = {R, I}; % the two types of edge: resistors and current sources array[1..m] of T: t; % the type of each edge array[1..m] of float: x; % the value (resistance or current) associated with each edge % 0 is ground constraint volt[0]=0; % source current is equal to current constraint forall (i in 1..m where t[i]==I) (x[i] == current[i]); % V = R * I constraint forall (i in 1..m where t[i]==R) (voltage[start[i]] - voltage[end[i]] = x[i] * current[i]); % sum of currents is zero constraint forall (j in 0..n) ( sum([current[i] | i in 1..m where start[i]==j]) == sum([current[i] | i in 1..m where end[i]==j])); ``` ]
[Question] [ You are given a list of numbers `L = [17, 5, 9, 17, 59, 14]`, a bag of operators `O = {+:7, -:3, *:5, /:1}` and a number `N = 569`. ## Task Output an equation that uses all numbers in `L` on the left-hand side and only the number `N` on the right-hand side. If this is not possible, output False. Example solution: ``` 59*(17-5)-9*17+14 = 569 ``` ## Limitations and Clarification * You may not concatenate numbers (`[13,37]` may not be used as `1337`) * Only natural numbers and zero will appear in `L`. * The order in `L` doesn't matter. * You must use all numbers in `L`. * Only the operators `+`,`-`,`*`,`/` will appear in `O`. * `O` can have more operators than you need, but at least `|L|-1` operators * You may use each operator any number of times up to the value in `O`. * All four operations in `O` are the standard mathematical operations; in particular, `/` is normal division with exact fractions. ## Points * The less points, the better * Every character of your code gives you one point You have to provide an un-golfed version that is easy to read. ## Background A [similar question](https://stackoverflow.com/q/15084049/562769) was asked on Stack Overflow. I thought it might be an interesting code-golf challenge. ## Computational Complexity As Peter Taylor said in the comments, you can solve [subset sum](//en.wikipedia.org/wiki/Subset_sum_problem) with this: 1. You have an instance of subset sum (hence a set S of integers and a number x) 2. L := S + [0, ..., 0] (|S| times a zero), N := x, O := {+:|S|-1, \*: |S| - 1, /:0, -: 0} 3. Now solve this instance of my problem 4. The solution for subset sum is the numbers of S that don't get multiplied with zero. If you find an Algorithm that is better than O(2^n), you prove that P=NP. As [P vs NP](//en.wikipedia.org/wiki/P_vs._NP) is a [Millennium Prize Problem](//en.wikipedia.org/wiki/Millennium_Prize_Problems) and hence worth 1,000,000 US-Dollar, it is very unlikely that somebody finds a solution for this. So I removed this part of the ranking. ## Test cases The following are not the only valid answers, other solutions exist, and are permitted: * (`[17,5,9,17,59,14]`, `{+:7, -:3, *:5, /:1}`, `569`) **=>** `59 * (17-5)- 9 * 17 + 14 = 569` * (`[2,2]`, `{'+':3, '-':3, '*':3, '/':3}`, `1`) **=>** `2/2 = 1` * (`[2,3,5,7,10,0,0,0,0,0,0,0]`, `{'+':20, '-':20, '*':20, '/':20}`, `16`) **=>** `5+10-2*3+7+0+0+0+0+0+0+0 = 16` * (`[2,3,5,7,10,0,0,0,0,0,0,0]`, `{'+':20, '-':20, '*':20, '/':20}`, `15`) **=>** `5+10+0*(2+3+7)+0+0+0+0+0+0 = 15` [Answer] # Python 2.7 / 478 chars ``` L=[17,5,9,17,59,14] O={'+':7,'-':3,'*':5,'/':1} N=569 P=eval("{'+l+y,'-l-y,'*l*y,'/l/y}".replace('l',"':lambda x,y:x")) def S(R,T): if len(T)>1: c,d=y=T.pop();a,b=x=T.pop() for o in O: if O[o]>0 and(o!='/'or y[0]): T+=[(P[o](a, c),'('+b+o+d+')')];O[o]-=1 if S(R,T):return 1 O[o]+=1;T.pop() T+=[x,y] elif not R: v,r=T[0] if v==N:print r return v==N for x in R[:]: R.remove(x);T+=[x] if S(R,T):return 1 T.pop();R+=[x] S([(x,`x`)for x in L],[]) ``` The main idea is to use postfix form of an expression to search. For example, `2*(3+4)` in postfix form will be `234+*`. So the problem become finding a partly permutation of `L`+`O` that evalates to `N`. The following version is the ungolfed version. The stack `stk` looks like `[(5, '5'), (2, '5-3', (10, ((4+2)+(2*(4/2))))]`. ``` L = [17, 5, 9, 17, 59, 14] O = {'+':7, '-':3, '*':5, '/':1} N = 569 P = {'+':lambda x,y:x+y, '-':lambda x,y:x-y, '*':lambda x,y:x*y, '/':lambda x,y:x/y} def postfix_search(rest, stk): if len(stk) >= 2: y = (v2, r2) = stk.pop() x = (v1, r1) = stk.pop() for opr in O: if O[opr] > 0 and not (opr == '/' and v2 == 0): stk += [(P[opr](v1, v2), '('+r1+opr+r2+')')] O[opr] -= 1 if postfix_search(rest, stk): return 1 O[opr] += 1 stk.pop() stk += [x, y] elif not rest: v, r = stk[0] if v == N: print(r) return v == N for x in list(rest): rest.remove(x) stk += [x] if postfix_search(rest, stk): return True stk.pop() rest += [x] postfix_search(list(zip(L, map(str, L))), []) ``` ]
[Question] [ You are tasked with planning a flying route for a local airplane delivery company. You need to route an airplane from point A to point B. You just can't start at A, point the airplane at B, and go, however, as the prevailing winds will blow you off course. Instead you need to figure out which direction you should point the airplane so that it will fly directly to B, taking the wind into account. **input** 7 floating-point numbers, encoding A\_x, A\_y, B\_x, B\_y, S, W\_x, W\_y. These are the coordinates of your start and destination, the airspeed of your airplane, and the strength of the wind along the x and y axes (the direction the wind blows *to*, not from). **output** You should print the angle in degrees (rotating counterclockwise from the positive x axis) that the plane should point to reach B in a straight line. Print `GROUNDED` if the wind is so strong as to make the trip impossible. You may round to the nearest degree, and do so with any method you would like (up/down/nearest/...). **examples** inputs ``` 0 0 10 0 100 0 -50 0 0 10 0 50 -55 0 3.3 9.1 -2.7 1.1 95.0 8.8 1.7 ``` outputs ``` 30 GROUNDED 229 ``` Shortest code wins. [Answer] ### Perl - 222 chars ``` use Math::Trig;($A,$a,$B,$b,$s,$W,$w)=split' ',<>;$c=atan2($b-$a,$B-$A);$A=atan2($w,$W);$S=sqrt($W*$W+$w*$w);$X=$S*sin($A-$c);$T=$S*cos($A-$c);$C=asin($X/$s);print((-$T>$s*cos($C))?"GROUNDED":(360+rad2deg($c-$C))%360,"\n") ``` Straighforward algorithm, and really only golfed by squeezing whitespace and variable name length, but I thought we needed a first answer here. I've been learning some J for golfing; I suspect simply translating to J (or Ruby) will readily beat this. Off to try those. `$X` = crosswind component, `$T` = tailwind component. We're grounded if the tailwind is actually a headwind (i.e., negative) and stronger than our airspeed. Otherwise, `$C` is the wind correction angle that we subtract from our course `$c` to get our heading. We need to turn far enough to balance the crosswind with the cross-track component of our velocity. [Answer] ### J - 155 chars ``` h=:3 :0 'c w s'=.(([:j./[:-~/2 2$4{.]),([:j./5 6{]),4{])0".y 'T X'=.+.w*+c%|c C=.-_1 o.X%s >((s>|w)*.(-T)<s*2 o.C){'GROUNDED';360|<.360+(C+{:*.c)*180%o.1 ) ``` For example: ``` h '0 0 10 0 100 0 -50' 30 h '0 0 10 0 50 -55 0' GROUNDED h '3.3 9.1 -2.7 1.1 95.0 8.8 1.7' 229 ``` Remove the `0".` ahead of `y` if you don't mind J numeric syntax (`_` for unary negation): ``` h 0 0 10 0 100 0 _50 30 ``` As I mentioned in my Perl answer, I'm only learning J, but liking its power. [Answer] # Perl: 193 Admittedly this is (mostly) DCharness's Perl code: but who doesn't like self-rewriting source? ``` use Math::Trig;$/=' ';@i=<>;$_='1=atan2(3-1,2-0);0=atan2(6,5);2=sqrt(6*6+5*5);5=2*sin(0-1);3=2*cos(0-1);6=asin(5/4);print-3>4*cos 6?GROUNDED:int rad2deg(1-6),"\n"';s/((?<!\w)\d)/\$i[$1]/g;eval ``` Also it will output degrees out of spec (i.e. <0 or >360), but did I mention self-rewriting source? ]
[Question] [ ## Intro Blur's song *Girls & Boys* featured the lines ``` girls who are boys who like boys to be girls who do boys like they're girls, who do girls like they're boys ``` in the chorus. These lines have a pretty uniform structure: you have a subject, which is either `girls` or `boys`, a relative clause, either `who are`, `who like`, or `who do`, an object, again either `girls` or `boys`, and an optional modifier, which is similar to the relative clause, except it can also be `like they're` or `to be`. In EBNF this might be written as: ``` subject ::= "boys" | "girls" relative_clause ::= "who are" | "who like" | "who do" modifier ::= relative_clause | "like theyre" | "to be" tail ::= relative_clause subject (modifier sentence)? sentence ::= subject tail ``` ## The challenge Your task is to, given a string, see if it is valid in this format. you can assume the string will be all lowercase, and will contain only letters and spaces (this means that `theyre` will have no apostrophe). It should output a boolean value or `0`/`1`. input and output can be done with any of the [standard I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). the input string may be empty. all words will be separated by a single space, but they will not all be valid words. for example, the input will never be `girls who likeboys` but it might be `girls who like bananas` ## Example I/O ``` girls who are boys who like boys to be girls who do boys like theyre girls who do girls like theyre boys -> true boys who like boys -> true true girls to be boys -> false `to be` is only valid in the modifier position, not as the leading relative clause. girls who like boys to be girls to be boys -> false The second `to be` is used in the relative clause position here, since after the first `to be` a new sentence begins, and sentences can't use modifiers in the relative clause position. boys -> false boys who are -> false who are boys -> false boys boys -> false <empty input> -> false ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in characters wins. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 99 bytes ``` ^(boy|girl)s( who (are|like|do) (boy|girl)s( (who (are|like|do)|like theyre|to be) (boy|girl)s)?)+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP04jKb@yJj2zKEezWEOhPCNfQSOxKLUmJzM7tSYlX1MBRVoDQx7MUCjJSK0ECpbkKySlomjRtNfUVvn/H8QpBhsO1KsAlIZwwHrBPLBOBYSylHyIOJLpqLIQDrI0SD0XptFcEJUQC5AEcNuPUAoA "Retina 0.8.2 – Try It Online") Link includes test cases. Simply the grammar turned into a regex and optimised slightly. [Answer] # [Perl 5](https://www.perl.org/) `(-p)`, ~~82~~, 80 bytes From @Neil's Retina answer, but using recursive regex. -2 thanks to @DomHastings. ``` $_=/^(boys|girls)( (who (are|like|do)) (?1)( ((?3)|like theyre|to be) (?1))?)+$/ ``` [Try it online!](https://tio.run/##dY1BCsIwEEX3PcUsuphBpIi4lNxEsTTYYHBCEpBCzm5sJotGxOX//80bp7095dxfz8MFR15CuhtvAyHga2bAm9fJmodOExMBqkNZUB1JWoizXlYiMoy6zqRo1w85iwaKY1VAMUuQK0lyAxs2ce0b7/daQzsXvvtVd5WsD5ri//8NfbOLhp8h7637AA "Perl 5 – Try It Online") [Answer] # [PEG.js](https://pegjs.org/), 92 bytes ``` S=s r" "s(m" "S)? s="boys"/"girls" r=" who "("are"/"like"/"do") m=r/" like theyare"/" to be" ``` <https://pegjs.org/online> ]
[Question] [ # Thin Paper Folding --- **This is a "lighter" version of the challenge [Paper Folding for the win](https://codegolf.stackexchange.com/questions/208919/paper-folding-for-the-win). This challenge is being posted as a different challenge with many modifications in order to try and get wider range of interesting answers. For anyone who is answering the first challenge, I marked the changes with `bold` (also note that the examples and the cases are different).** --- "How many times can you fold a paper?" - This well known question led to many arguments, competition, myths and theories. Well, the answer to that question depends on many properties of the paper (length, strength, thickness, etc...). In this challenge we will try to fold a piece of paper as much as we can, however, there will be some constraints and assumptions. --- ### Assumptions: * The paper will be represented in pixel-sized cells. The length and width of the paper is `N x M` respectively (which means you can not fold a pixel/cell in the middle). * **Each spot (pixel) of the paper has its own thickness (as a result of a fold).** --- ### A paper: A paper will be represented as a 2D `M x N` Matrix as the top-view of the paper. Each cell of the matrix will contain a number that will represent the thickness of the paper's pixel. **The initial thickness of all pixels is 1.** Paper representation example: ``` Option 1 Option 2 1 1 1 1 1 1 1 1 1 [[1,1,1,1,1,1,1,1,1], 1 1 1 1 1 1 1 1 1 [1,1,1,1,1,1,1,1,1], 1 1 1 1 1 1 1 1 1 [1,1,1,1,1,1,1,1,1], 1 1 1 1 1 1 1 1 1 [1,1,1,1,1,1,1,1,1], 1 1 1 1 1 1 1 1 1 [1,1,1,1,1,1,1,1,1]] ``` --- ### A fold: A fold is a manipulation on the matrix defined as follows: Assuming there is a 2 pixels fold from the right side of the paper in the example above, the size of the paper will now be `N-2 x M` and the new thickness of the pixels will be the summation of the previous thickness of the cell + the thickness of the mirrored cell relative to the fold cut: ``` ___ / \ \/<-- | 1 1 1 1 1 1 1|1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1|1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1|1 1 ===> 1 1 1 1 1 2 2 1 1 1 1 1 1 1|1 1 1 1 1 1 1 2 2 1 1 1 1 1 1 1|1 1 1 1 1 1 1 2 2 ``` --- ### Goal: The goal is to write a program that will output a set of folds that result in the minimum possible number of remaining pixels for any given input (size of paper and threshold). --- ### Constraints: * You can fold a paper from 4 directions only: Top, Left, Right, Bottom. * The fold will be symmetric, which means, if you fold 2 pixels of the paper from the left, all of the cells in the first and second columns will be folded 2 pixels "mirrorly". * **A thickness threshold of a paper cell will be given as an input**, a cell can not exceed that threshold at any time, which means, you will not be able to fold the paper, if that specific fold will result exceeding the thickness threshold. * Number of pixels being fold must be between 0 and the length/width of the paper. * Do not exceed with your folding the initial dimensions and position of the paper. ( there is no pixel -1 ) --- ### Input: * **Two integers `N` and `M` for the size of the paper** * Thickness threshold --- ### Output: * A list of folds that yields a valid paper (with no pixels exceeding the thickness threshold) folded in any way you want (using any heuristic or algorithm you've implemented). --- ### Scoring: Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code wins. --- ### Examples: **Example 1:** ``` Input: N=6 , M=4, Threshold=9 1 1 1 1 1 1 1 1 1 1 1 1 fold 2 pixels from top 2 2 2 2 2 2 fold 3 pixels from right 4 4 4 fold 1 pixel from top 1 1 1 1 1 1 ======================> 2 2 2 2 2 2 =======================> 4 4 4 =====================> 8 8 8 No more fold possible 1 1 1 1 1 1 Optional outputs: [2T,3R,1T] ------------or---------- [[2,top],[3,right],[1,top]] ------------or---------- Top 2 Right 3 Top 1 ------or any other sensible readable way------ --------notice the order is inportant--------- ``` **Example 2:** ``` Input: N=6 , M=4, Threshold=16 1 1 1 1 1 1 1 1 1 1 1 1 fold 2 pixels from top 2 2 2 2 2 2 fold 3 pixels from right 4 4 4 fold 1 pixel from top fold 1 pixel from left 1 1 1 1 1 1 ======================> 2 2 2 2 2 2 =======================> 4 4 4 =====================> 8 8 8 =====================> 16 8 No more fold possible 1 1 1 1 1 1 Optional outputs: [2T,3R,1T,1L] ------------or---------- [[2,top],[3,right],[1,top],[1,left]] ------------or---------- Top 2 Right 3 Top 1 Left 1 ------or any other sensible readable way------ --------notice the order is inportant--------- ``` --- ### Some Test cases: **Case 1:** ``` Input: N = 16 , M = 6 , Threshold = 3 Output: [2, top], [2, top] (This fold will result 32 remaining pixels) (Example for bad output will be splitting in half, yields 48 remaining pixels) ``` **Case 2:** ``` Input: N = 16 , M = 6 , Threshold = 24 Output: 8 RIGHT 4 RIGHT 3 BOTTOM 1 TOP 1 TOP (This fold will result 4 remaining pixels) ``` **Case 3:** ``` Input: N=6 , M=4, Threshold=9 Output: [2T,3R,1T] ``` **Case 4:** ``` Input: N=6 , M=4, Threshold=16 Output: [2T,3R,1T,1L] ``` --- ## Check validity **In the previous challenge I wrote a program that checks the validity of foldings and the validity of the resulted paper after folding (no exceeding threshold). You can use the same program, but you need to generate the paper itself as a matrix as an input to the function:** [This nodejs program](https://tio.run/##3Vhtc9o4EP7uX7HnL7XBEF56MwkcdHIpvWOGBiahnZvh/MEBUZwQ27VN6Mvkt@ck2ZZl@QU7Q9q5WgkR0rOr3We1WsW3xoPhLV3T8RuWvUJPT8sNWt59NLbmyvS/wkBxDAe5GvgbF3kbe7tSYTCE7xLgZ227oGyRDyYMoNXHf/4ACm9ukfXJ3@CRel2l0AT8NoDfRvCFqTOJW17CXCsRYHGrDzkbXOTvXAvWxtZDfYoPR3x3hwceJUlam9Zqul57eMEBRG6sTBctfdO2QjeoKLGJzr/dORi7aDab9KveD@a9vekvN6Bwwt@ZjUvDQ/BqPp296rEx8nAKo27z3nAUgyxsNF202i2RonzT4Au15RvUcU/tJ5Q8GC6YySHKokg4Uc5zztkXcxmSgLGYTxhCS02ByHPjIuMuueajJGoy4beBuDSLimAxDpu9B/nSDgTkvsDdn9P5fPr@R9MnGA8NaBNChwGxjcaP4JAsxljjM4dYg38rEjkZvZsLNJbdQIuWfmgDkSzxdvdUMDWZm9uJxKby9ZB7nNGYw34myQR3xA0ae/fcPXo1/uvvKtwKpJbaXf83gtO7N@kwNEqTvEJrY7f1e1nwD9adZe@t@OgO5R7JKf9ACpXhY3LwGc/qgwbhcb81PV886Vc7Z0ZmhZOemhFPRV166KDBENHO58Hw85t2rxUdNLT4WaY/CZzOEotOKkO7UQdDo36jqhljYaWhUXaCCDs4wsR@FmAnmZe0aplf0NbDeAJcODoOQD8BYKRxmHZU1yKQHVXJuGSm66Ugs8Y0j6zVzCarB2bUOvVAEwctLJ1F5TMs//EyQ363q9HmGFt0B1BzQK6HLhakD3/wUatzz7tKV5YceVbJFiHH9ShkNehEhzy528RJy4B0vF9WbaAl8@hI52/2SEbaFxToXy1AilB/Q2YbXMBUxjOLVp4QC@yhACYUZGp4oaBmXBZyQspXz58c1WohxfWvKO0ShZJLpH4FteZLhSfrwvELxkcRkrUo8RLxKpALolsiigd1HD22mfecA3cdKV6BdU9OYGlbnr1Fza39KSBR7ZPh8Rq@2jvYG5YPPr5ouSbpbFDgNRhrH38iA9dkz0eOJHGKj30xstD@WPci3ln5X@sS7UN/TK8nh0tmEMJMCbJhAImXG@lXGyk9VO6NXKvVYHY@G13B@Bo@nk/GbwEPyT1u4sNlPJ5hUKhojO@KEOy2Hs7L@OpYlzUgXsVzjD0yNQtSwUX39gNa4ev70naRSmBKrKPBRFToyZdTuL6YXo2gpxCDyBsR6aTUg2Fw8BFh89H1HC7Or0fXhbAibaVsk0J9i0VLS7a28L2laxFWBLZFcDaUwDoiOAsaALsiOA1th63DejnQdmYToJ0cGGvloZ2Xhx5oui6xzbJYpHWd4lbgYBoef5YQOM3oFQicarnfsgROtWzzjrfCM3x4Bkv5cTgQPEHjGZs4EyfPaAumaK@0ZLuKFz/HoEMs8amDj5PXuHULNWYJlRcI16iyAhVKC3SrmUSW7VYzqZsJjlg66EN0zITwIlo7aTA52pNHWZFQWAdigdesNPB2dzVBUSzwu8aLZEDZfnrRmn5xPpnA6J/z97MJX9aPXtOxNvYeT4l0n0Vs0FSBxI8ezx1pSo@muFW7Gsj03zBZ10jUQQ5ehNCv7XiSypKbqvTEuRE5ke9CnpHVxnUpMLuy0djkp/8A) will: 1. Check if your folded papers are valid 2. Check if your steps are valid # How to use: Call the desired function in the footer. Call **validator** with threshold, initial paper, and a list of steps with the format `[x,d]` for folding `x` pixels from `d` direction. `d` is one of the following strings: "RIGHT","LEFT","TOP","BOTTOM". This function will print if the final paper as a matrix and the amount of pixels reduced. Output will look like this: ``` *** PAPER IS VALID *** Init length: 240, New length: 180, Pixels removed (score): 60 ``` Or, if the paper isn't valid: ``` *** PAPER UNVALID *** NO SCORE :( ``` **You can see call examples commented in the code.** You can also remove the comment in the line `// console.log(paper); // If you want to print the paper after each step` to "debug" and print the folded paper after each fold. [Answer] # [R](https://www.r-project.org/), 179 bytes (or **175 bytes** without labelling 'T' and 'L') ``` function(m,n,t,z=function(l,t){while(t>1){F=c(F,g<-l%/%t);l=l-g;t=t-1};list(l=l,f=F[F>0])}) list(T=z(m,b<-order(sapply(1:t,function(f)z(m,f)$l*z(n,t%/%f)$l))[1])$f,L=z(n,t%/%b)$f) ``` [Try it online!](https://tio.run/##jZJPT@MwEMXvfIqRyp945WrrJNsuFHPsiSM3hJCbOo1Xrh0l021axGcvYySSFIiElESyPe/35o1THXNvV8@lKnUlj/nWZWi8izbcceQH2W5YjuxlVxirI7wT7GUhs2jB17dje/H7AtncSjtez1HiWLzOrakxoh2ey8Xj4m7yxF7Z2fvmgzwQe3k79tVKV1GtytLuI3GDvHXKWSjJ2bn9dYioC@KHBWOP4omd5/xefmwvacmOI9CN2pRW12ddlGgjU@7oRZkyGMG/bY1QeWvBIGxLkJA2AkrTaDsg@xtk4SQo/H9dgXeZhss@BQsNnj4V7NSemPEAc0rMKTGv@0zj0EMCSwIEeU36pEm@1c9IPyO9mARAptwVwsrDUiOSNxbKdQGNW7cZZwP9iAkB6fODlAmg2ej6S9Q/XasjQE3mmar1N7lFCJ4Em7YKRJjVAz0D5XF6Wh9T/U73J9@fWtzEgzfZTr2DJSTpkQpfmYN3qKzdU@7udqBQNgcaCZrs/VCCGLifDycxPbVKSfMZ@Mmv18mJVe9XOr4B "R – Try It Online") Outputs a list of ['T' = horizontal folds from top, 'L' = vertical folds from left]. **How does it work?** First, note that the final maximal thickness after a combination of horizontal & vertical folds is simply the product of the maximal thicknesses that would be obtained using the horizontal or only the vertical folds. So we can separate the problem into (1) finding the folds in one-dimension (either horizontal or vertical) that minimize the final length for a target thickness, and (2) choosing the best combination of target thicknesses for horizontal & vertical folds that yields the smallest product of lengths. Now, to find the best set of folds in one-dimension, we note that since the number of folds isn't limited, so it's just as effective to 'roll-up' as to repeatedly fold in half. Rolling-up has the advantage that if the length isn't perfectly divisible by the target thickness, we can do 'loose' rolls, and minimize the final length by doing the tighter rolls before the 'loose' rolls. Final algorithm: * test all combinations of t1, t2, where t1 x t2 <= target thickness * for each t1, find the smallest length l1 achievable by rolling-up the paper along dimension m, starting at the top * for each t2, find the smallest length l2 achievable by rolling-up the paper along dimension n, starting on the left * choose the combination of t1,t2 that gives the smallest final paper size = l1 x l2 Readable code: ``` fold_paper=function(m,n,t){ # m=height, n=width, t=thickness threshold min_length=function(l,t){ # min_length=local function that calculates the best # way to roll-up a strip of length l up to a # thickness threshold of t while(t>1){ # try to use-up all of the thickness t: F=c(F,g<-l%/%t) # each fold g is the current length l integer-divided by the # remaining thickness that we need to use-up # (save the list of folds in F) l=l-g # reduce the current length after each fold t=t-1 # and reduce the remaining thickness to use-up } list(l=l,f=F[F>0]) # return l = the final length, f = the list of folds } best_combo<-order( # now pick the best combination of t1,t2 sapply(1:t,function(f) # cycle through f=1..t for t1, and inteter(t/f) for t2 min_length(m,f)$l * min_length(n,t%/%f)$l) # find the product of lengths for each combination )[1] # and choose the first one from the list sorted by increasing size list( T=min_length(m,best_combo)$f, L=min_length(n,t%/%best_combo)$f ) } # finally, use the best combination to re-calculate # the best set of horizontal & vertical folds ``` [Answer] # Python3, 620 bytes: ``` R=lambda x,n=4:set()if n==0 else{str(x),*R([[*i[::-1]]for i in zip(*x)],n-1)} L=range def M(b): for i in L(1,len(b[0])//2+1):yield[j[:-2*i]+[a+b for a,b in zip(j[-2*i:-i],j[-i:])]for j in b];yield[[a+b for a,b in zip(j[i:2*i],j[:i])]+j[2*i:]for j in b] T=lambda x:[*map(list,zip(*x))] F=lambda b:[*M(b),*map(T,M(T(b)))] def f(n,m,t): r,q,s={},[[[1 for _ in L(n)]for _ in L(m)]],[] while q: for B in F(q.pop(0)): if all(all(j<=t for j in i)for i in B): Y,S=R(B),sum(map(len,B)) if all(i not in s for i in Y)and(S not in r or max(map(max,r[S]))>max(map(max,B))):q+=[B];s+=[*Y];r[S]=r[S]=B return r[min(r)] ``` [Try it online!](https://tio.run/##jZFfb5swFMXf@RR@vBdu1pBG0erMe@ChUqX2JclLZFkTKGY1AocYqqWr@tkzm/xZpk3bHsA253cOPnb72j9v7e3H1h0OC1HnTbHJ2Z6smPJO94CmZFaIMdN1p9@63sEeKV6AlLGRnI9SpcqtY4YZy76bFuI9KrKjFN@jR@Fy@1VHG12yJyiQR@yCPkJKtbZQyLHCm5tJkiJ/NbreyEry0SQ2KpF5UgyGnIpzeiWDxkdGkZ8arnD4exX0Qs2PCX82Gh5SvY0b70oqGYKu3dHq0p7LuMlbqE3X06kUquj@rBdeD4VooFb0BCu/CkioWoKlhvpQ19GOOvH2TlLKdNjSl2N5e9z3adWgUiRVxL49m1qznXcOcBbke9h9aLctjDEkMubvI69rCE/1SfTs0sDg5XSzI8rWtBQLyJC6lwaGRtpShjiIpyDD7LYPpu7n7awxtxtYnhXHvNDk@yHCj@TkUiF@vv7kU5HvEiEzNe/8EK/VPGBieGX@LHT/4nyWbIwFh@rQOmN7eOCihBlN6e7XXT74vOgKSWc0o9v/YCbTv0NTz9z9G0lnvzOHHw) ]
[Question] [ This challenge like some of my [previous](https://codegolf.stackexchange.com/q/200122/53884) [challenges](https://codegolf.stackexchange.com/q/187763/53884) will have you counting free [polyforms](https://en.wikipedia.org/wiki/Polyform), which are generalizations of Tetris pieces. This [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge will have you count polyomino-like polyforms on hypercubes. In particular, this challenge is to write a program that takes in three parameters: * `n`, which represents an \$n\$-dimensional hypercube, * `m`, which represents \$m\$-dimensional faces of the hypercube, and * `k`, which represents the number of cells in the polyform, and outputs the number of ways to choose \$k\$ (\$m\$-dimensional) faces on the \$n\$-cube such that the \$m\$-faces are connected at \$(m-1)\$-faces. These polyforms are "free" which means they should be counted up to the rotations/reflections of the \$n\$-cube. Again, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so shortest code wins. --- # Example 1 Okay, this is all very abstract, so this warrants an example. When `n=3`, we're talking about the \$3\$-dimensional (ordinary) cube. When `m=2` this means we're talking about the \$2\$-dimensional (square) faces. And we're talking about `k` of these, joined along \$1\$-dimensional faces (edges). When `k=3`, there are two such polyforms (on the left) up to rotations/reflections of the cube. When `k=4` there are also two polyforms (on the right). [![enter image description here](https://i.stack.imgur.com/VnJ8J.png)](https://i.stack.imgur.com/VnJ8J.png) # Example 2 In this second example, `n=3` still, so we're again talking about the \$3\$-dimensional (ordinary) cube. When `m=1` this means we're talking about the \$1\$-dimensional faces (edges). And we're talking about `k` of these, joined along \$0\$-dimensional faces (corners). When `k=4` there are four such polyforms. [![enter image description here](https://i.stack.imgur.com/cEHae.png)](https://i.stack.imgur.com/cEHae.png) --- # Data ``` n | m | k | f(n,m,k) --+---+---+--------- 3 | 2 | 3 | 2 (Example 1, left) 3 | 2 | 4 | 2 (Example 1, right) 3 | 1 | 4 | 4 (Example 2) 2 | 1 | 2 | 1 3 | 0 | 0 | 1 3 | 0 | 1 | 1 3 | 0 | 2 | 0 3 | 1 | 3 | 3 3 | 1 | 5 | 9 3 | 1 | 6 | 14 3 | 1 | 7 | 19 3 | 1 | 8 | 16 3 | 1 | 9 | 9 3 | 3 | 0 | 1 3 | 3 | 1 | 1 3 | 3 | 2 | 0 4 | 1 | 4 | 7 4 | 1 | 5 | 21 4 | 1 | 6 | 72 4 | 1 | 7 | 269 4 | 1 | 8 | 994 4 | 1 | 9 | 3615 4 | 2 | 3 | 5 4 | 2 | 4 | 12 4 | 2 | 5 | 47 5 | 1 | 4 | 7 5 | 1 | 5 | 27 5 | 2 | 0 | 1 5 | 2 | 1 | 1 5 | 2 | 2 | 1 5 | 2 | 3 | 5 5 | 2 | 4 | 20 5 | 3 | 4 | 16 5 | 3 | 5 | 73 5 | 4 | 4 | 3 6 | 1 | 6 | 121 ``` [Answer] # Python 3, 389 ``` import itertools as I S=sorted P=I.product def C(n,m,k): Q=[((-1,)*(n-m)+(0,)*m,)] for i in' '*(k-1):Q=set(tuple(S(q+(v,)))for q in Q for v in P(*[(-1,0,1)]*n)if sum(map(abs,v))==n-m if not v in q and any(sum((a!=b)*(1+2*a*b)for a,b in zip(v,u))==2for u in q)) return sum(all(S(q)<=S(zip(*r))for X in I.permutations(zip(*q))for r in P(*((p,tuple(-x for x in p)) for p in X)))for q in Q) ``` [Try it online!](https://tio.run/##ZVTBbuIwED3XXzHVHmKHgEigsFSb0556a9WuVImtKgPuNiJxQuy0sOq/0xkncUE9GOfNPM@8NySuDva11JPjMSuqsraQWVXbsswNSAM37D41GFUbdpvejKq63DRryzbqBX5zHRXRVlwzuEuXnA/jSIRcDwsx4GN8LCLxxOClrCGDTAcQhHw7jMX1XWqU5bapcsXv@W7A3yIhBPF2yIM7d@SNHm95uKSy4ygWT6EW2QuYpuCFrLhcmehNiDTFfoBxXdr2zA6k3uA6cKJyeZmuUFU8SEIZrlwXGa2I@D@rsHNDNRIKN@60EAxqZZtau1Yyz0mj@JXeczoQ1q3SRyLjOFRdNFbarNSmze/afN3J57yKWqfDvfO1p0QlhAMVgccz8@Ko9rLAA@bZ2BpSCIJgAh@Q4HI769HUo7hDU5Z0yO0uN@7WF4rPEDHHvgrtE4@ucC3AwxntUw/ntC88/En7zMMFLYcmZwomZwomXsH0xMfcI1KQxA72A7jyyJESdtXXcFV7FJ@h5Ay5MjhXxn6AfVVGwXtZb2HVWJC1ApOX7yNGv8/f/4vZ6TA6af00ktnCYxrHYjH1mPjzVqw3NveKnKWxd0bh6dyT3Uw6vX/0uiwKpa17gUgk9CJHmH54VQfnJnJ20N0hyHOwcqtAwrqkVxGKTDfW8c/8DdDgX/xOB/DNO2M9wiksl5m2fC@@3uc802pkqjyzPPgIxJPLUJCSp3V6ErbBu4ERrUufMq/ZRVVTj@BBGZvpf0HUpQS7cHcO4kqt8VJCOV2KXci1bWSOkf5iwpAxeJfBFzuFluU73CLlMhA9FsdP "Python 3 – Try It Online") Basically just finds all connected polyominos, and discards ones which can be rotated into a lexicographically smaller polyomino, with rotations being brute-forced. Can definitely be improved but it's my bedtime. ]
[Question] [ # Introduction A farmer needs help calculating the least time it will take him to pick his fruit each day. # Challenge * This farmer has `X` orchards. * Each orchard has `Y` fruits in it. If the orchard has no fruits, then it will contain the string "none". * The farmer has a list, this list contains the fruit he must pick. * The farmer will only go down the list **in order** * You must calculate how long it will take the farmer to pick his fruit on each day. ### More on the orchards * All of the orchards are in a line. * Each orchard is exactly `1` unit away from the next and previous one. * The farmer can go up and down the line, but may not jump from one orchard to another # Input and Output You will receive an input in the following format: ``` X *string* *string* *string* *string* *string* *string* *string* //ect. Y *string* *string* *string* *string* *string* *string* *string* *string* //ect. ``` `X` is the number of orchards * Everything after `X` and before `Y` is an orchard containing a/some string(s), each string is a different fruit in that orchard. `Y` is the number of days that the farmer must gather fruit. * Each day consists of two strings that are different fruits. * You must find what orchard these strings are in and calculate the difference. ### Input Rules: 1. Each fruit name string will be one word with **no spaces** ### Real Example Still confused? Maybe this will clear it up: Input ``` 6 none apple orange pear pear none orange lemon pumpkin pumpkin lettuce flowers peas 4 peas lettuce apple orange apple pumpkin flowers orange ``` output: `[ 0, 1, 3, 1 ]` ### Explanation Input: * `6` the number of orchards * A set of `6` orchards containing fruit, each orchard on a new line. * `4` the number of days on the farmers list. * A set of `4` fruits to compare, each pair of fruits is on a new line. Output: * Output an array of the differences between each set of fruits. * The difference between peas and lettuce is `0`, because they are in the same orchard. * The difference between apples and oranges is `1` because they are one orchard apart. * The difference between apples and pumpkins is `3` Because they are three orchards apart. * The difference between flowers and oranges is `1` because they are one orchard apart. --- Annotated input/output ``` 6 orchards a none b apple c orange pear pear d none e orange lemon pumpkin f pumpkin lettuce flowers peas -- 4 fruits peas lettuce 0 apple orange 1 apple pumpkin 3 flower orange 1 -- output: [ 0, 1, 3, 1 ] ``` # How To Win Shortest code in bytes wins. # Rules * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest solution in bytes wins * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * The [meta definition of randomness](https://codegolf.meta.stackexchange.com/a/1325/42649) applies * You may use functions as well as programs # Disclamer I submitted this question to the sandbox, but I did not get any feedback on it, so feel free to edit as you see needed. [Answer] # 176 bytes, Python 3 ``` def p(a):l=[b.split()for b in a.split('\n')];X=int(l[0][0]);return[min(y-x for y in range(X)for x in range(y+1)if z[0]in l[x+1]+l[y+1]and z[1]in l[x+1]+l[y+1])for z in l[X+2:]] ``` This can be called by passing in the entire content as a string ``` p("""6 none apple orange pear pear none orange lemon pumpkin pumpkin lettuce flowers peas 4 peas lettuce apple orange apple pumpkin flowers orange""") ``` Ungolfed solution ``` def problem(a): # this will split on new line, and split each individual line into it's own list lines=[b.split()for b in a.split('\n')] # get the number of orchards X=int(lines[0][0]) return[ # get the minimum of all possible differences min(y-x # subtract y and x to get the difference for y in range(X) # for each orchard, y for x in range(y+1) # and each orchard up to y inclusive, x if z[0] in lines[x+1]+lines[y+1] and z[1] in lines[x+1]+lines[y+1]) # if both fruits exist the x and y orchards # for every day (z is a list containing 2 fruits as string) for z in lines[X+2:] ] ``` [Answer] # JavaScript (ES6), 224 bytes ``` a=>(d=a.split('\n')).slice(e=+d[0]+2).map(f=>{p=e;for(g=(q=(t,s=0)=>d.slice(1,e-1).map(b=c=>c.split(' ')).findIndex((x,y)=>y>=t&x.includes(b(f)[s])))(0);++g;g=q(g))for(l=q(0,1);++l;l=q(l,1))p=p<(u=g>l?g-l:l-g)?p:u;return p}) ``` Call with `"6\nnone\napple\norange pear pear\nnone\norange lemon pumpkin\npumpkin lettuce flowers peas\n4\npeas lettuce\napple orange\napple pumpkin\nflowers orange"` [Answer] # [Röda](https://github.com/fergusq/roda), 118 bytes ``` {A=[head(parseInteger(pull()))|splitMany|enum]pull n;split|{f={|x|A|[_2]if[x in _1]}f a|{|i|f b|abs i-_}_|min}for a,b} ``` Explanation: ``` { A=[ /* Pull line, convert to integer, and read that many lines */ head(parseInteger(pull()))| /* Split all lines to arrays */ splitMany| /* Enumerate, ie. give each line a number */ enum ] /* Discard one line */ pull n; /* Split each following line and push words to the stream */ split| /* For each word a, b in the stream: */ { /* Helper function to find lines that contain x */ f={|x|A|[_2]if[x in _1]} /* Push numbers of lines that contain the first word to the stream */ f a| /* For each line number i */ {|i| /* Push numbers of lines that contain the second word to the stream */ f b| /* Push the difference of two line numbers to the stream */ abs i-_ }_| /* Push the smallest difference to the stream */ min }for a,b } ``` No TIO link yet, as the TIO version of Röda is outdated. [Answer] # Java 10, ~~307~~ ~~298~~ ~~288~~ ~~280~~ ~~273~~ 271 bytes ``` s->{String[]a=s.split("\\d"),o=a[1].split("\n"),f=a[2].split("\n");int r[]=new int[f.length-1],q=-2,d,i,j,z;for(var p:f)if(++q>=0)for(z=d=o.length,i=0;++i<d;)for(j=0;o[i].contains((f=p.split(" "))[0])&++j<z;)r[q]=d=o[j].contains(f[1])?Math.min(i>j?i-j:j-i,d):d;return r;} ``` -19 bytes thanks to *@ceilingcat*. **Explanation:** [Try it here.](https://tio.run/##VVLLbuQgELzvV7R8WIH80CRa7WEcJtoPSC452j6wNp5A7MYDeKJMNN8@235FWQljuorqbgqMPMvUNG@3upPew5PU@PkDQGNQrpW1gucpnIGigpq9BKfxCJ7nBF/po@GDDLqGZ0AQcPPp4XPZVVRS@MwPnQ4sKssm4okVsrirvjAkqCXo/j8op2Lgikqgep8Lt1mn8Bhe07sqOYn0PmkSnZjkkrfWsbN0MOxbrlsWx6eD2PEJvYhG2FWWaLHL41g/NPnMGQptoausthjowJ6xVgxbBxBxXuwq/jOOzcMl5644VVOywnwTtHQK/vgkw2vWa2T6YB51avYm1UnD903uVBgdgsuvt3wxaRj/dmTS6tXZ6gZ6SsU2q0DyxemXDx9Un9kxZANRoUNm6JKyMegu@@Oc/PBZsIuMYVazWQUQ/S4RLaoS5TB09LNO4lHBoCaDaNroFe9Ub5Ha6oc3jSWuC4JDGOne286@K@cnpS/xF22gxcauNWBJtUVfuTbtQkdzg5yvT@Z6@wc) ``` s->{ // Method with String parameter & integer-array return String[]a=s.split("\\d"), // Split the input on numbers o=a[1].split("\n"), // List of orchards f=a[2].split("\n"); // List of pairs (later on reused for individual pair of fruits) int r[]=new int[f.length-1], // Result integer-array q=-2,d,i,j,z; // Some temp integers for(var p:f) // Loop `p` over the pairs: if(++q>=0){ // If this isn't the first iteration of the pair-loop // (the first item is always empty after `.split("\\d")`) for(z=d=o.length,i=0;++i<d;) // Inner loop `i` over the orchards: for(j=0;o[i].contains((f=p.split(" "))[0]) // If the current orchard contains the first fruit of the pair: &++j<z;) // Inner loop `j` over the orchards again: r[q]= // Add the following to the resulting array: d=o[j].contains(f[1])? // If the current orchard contains the second fruit of the pair: Math.min( // Take the minimum of: i>j?i-j:j-i,// The absolute difference between `i` and `j` d) // And the current integer of the array : // Else: d; // Leave the current integer unchanged return r;} // Return the result array ``` ]
[Question] [ It's lunch time, I am hungry and I came to your Sushi Bar. You are the Sushi Chef and you have to produce a full program or function to make me some sushi! [![enter image description here](https://i.stack.imgur.com/qyCQP.jpg)](https://i.stack.imgur.com/qyCQP.jpg) [Credits: Wikipedia](https://en.wikipedia.org/wiki/Sushi) *Disclaimer: The image is for illustration purposes only and do not necessarily represent the exact product.* Although you have limited ingredients (due to a truck drivers strike) it will be fine for me. The ingredients you have (in plenty amount) are: * Nori seaweed (made with: `\/_¯|`) * Raw Tuna (`T`) * Raw Salmon (`S`) * Raw Avocado (`A`) * Sushi Rice (`o`) With these ingredients you are able to make some nice makis for your clients. Your minimum order is $1 for 2 makis, you only make makis in couples and only accept integer numbers as payment. You accept orders up to $50 per person (total input) because you are alone and you must satisfy all your clients. You will need to get the client's orders from standard input in any reasonable format, for example: `[1,T],[2,S],[3,A]` which means that you have to output: * Two Tuna Makis * Four Salmon Makis * Six Avocado Makis One maki is exactly made like this: ``` _____ /ooooo\ |ooTTToo| |\ooooo/| | ¯¯¯¯¯ | \_____/ ``` And since you are a fine Sushi Chef, you always arrange the makis with the pieces of any given type in a square shape or at most in a rectangular shape (as close as possible to a square) with no gaps. The overall shape is also square or rectangular, as close as possible to a square given the above restriction, with no gaps. **Example input/outputs:** ``` Input: [1,T],[2,S],[3,A] Valid Output: _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ Valid Output: _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo||ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo||ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo||ooTTToo||ooTTToo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ Not Valid Output: _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooAAAoo||ooSSSoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooAAAoo||ooTTToo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ Not Valid Output: _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooSSSoo||ooSSSoo||ooSSSoo||ooSSSoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ Not Valid Output: _____ _____ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooSSSoo||ooSSSoo||ooSSSoo||ooSSSoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ Input: [1,S] Valid Output: _____ _____ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ Valid Output: _____ /ooooo\ |ooSSSoo| |\ooooo/| | ¯¯¯¯¯ | \_____/ _____ /ooooo\ |ooSSSoo| |\ooooo/| | ¯¯¯¯¯ | \_____/ Input: [1,A],[1,T],[1,S] Valid Output: _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooTTToo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooTTToo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ Valid Output: _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ Input: [1,T],[1,A],[2,S] Valid Output: _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo||ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ Valid Output: _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo||ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ Valid Output: _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooTTToo||ooTTToo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ Input: [1,T],[1,S],[7,A] Valid Output: _____ _____ _____ _____ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooTTToo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ Valid Output: _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooSSSoo||ooSSSoo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ _____ _____ /ooooo\ /ooooo\ |ooTTToo||ooTTToo| |\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ ``` **Rules:** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. [Answer] # Python 3, ~~314~~ 313 bytes ``` l=[" _____ "," /ooooo\ ","|oo%s%s%soo|","|\ooooo/|","| ¯¯¯¯¯ |"," \_____/ "];T=('T',)*3;S=('S',)*3;A=('A',)*3;i=eval('['+input()+']');x=sum(map(lambda x:x[0],i));m=[] for f in i:m+=[f[1]]*f[0] for p in 1,0: for j in l: for k in range(x):print((j%m[k]if '%s' in j else j),end='') print() ``` My attempt at this challenge. It's hard! ### Sample Output: ``` [1,T],[1,S],[7,A] _____ _____ _____ _____ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooSSSoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ _____ _____ _____ _____ _____ _____ _____ _____ _____ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ /ooooo\ |ooTTToo||ooSSSoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo||ooAAAoo| |\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/||\ooooo/| | ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ || ¯¯¯¯¯ | \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____/ ``` ]
[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/75446/edit). Closed 6 years ago. [Improve this question](/posts/75446/edit) **The Scenario** Given an input of ASCII lowercase letters and spaces, draw a spiral of characters that traces the original input of characters excluding spaces. **The Rules** 1) The characters shall spiral counterclockwise to the left in an outwardly fashion. If a left turn is not possible, then move straight. ``` Given: abcdefg Output: g baf cde ``` [![Image tracing first example](https://i.stack.imgur.com/KNaXu.png)](https://i.stack.imgur.com/KNaXu.png) 2) The characters can spiral into previous characters so long as rule #1 is not violated. Also, if that character is spiraled into, then that character is uppercased. Once a character is uppercased, it will stay uppercased regardless of the number of times it is reused. ``` Given: apples appeal Output: PAs PLe ea ``` [![Image tracing second example](https://i.stack.imgur.com/eMWxY.png)](https://i.stack.imgur.com/eMWxY.png) [Answer] # JavaScript, ~~225~~ ~~221~~ 212 bytes -9 bytes thanks to Conor O'Brien Please note that your text cases conflict with each other. Your first test case starts in the middle of the spiral. Your second test case starts in the top middle of the spiral. I went with your first test case, because it was the first one I saw. You haven't edited your question in over a year, so sorry for the presumption. First Test Case: ``` 9<-8<-7 | | 2<-1 6 | | 3->4->5 ``` Second Test Case: ``` 2<-1<-6 | | 3->4->5 | | 7->8->9 ``` Without any further adieu, here is the golfed code. I am 100% sure that if the community chips it this could be cut significantly. This returns a multiline array. ``` s=>eval("s=[...s.replace(/ /g,'')];i=0;k=j=1;a=[[],[],[]];b='00122210';c=b*100+'';for(;;){for(l=0;l<8;l++){if(!s[i])break;if(a[k][j]==s[i])s[i]=s[i].toUpperCase();a[k][j]=s[i];k=b[l];j=c[l];i++}if(!s[i])break}a") ``` Prettification snippet (prints a multiline string to console). Please note the different in my test case #2 and OP's test case #2 (see above if you have not already): (if someone with more experience with snippets wants to fix this into HTML input feel free to edit this, I need to go to bed). ``` f= s=>eval("s=[...s.replace(/ /g,'')];i=0;k=j=1;a=[[],[],[]];b='00122210';c=b*100+'';for(;;){for(l=0;l<8;l++){if(!s[i])break;if(a[k][j]==s[i])s[i]=s[i].toUpperCase();a[k][j]=s[i];k=b[l];j=c[l];i++;g(a)}if(!s[i])break}a") //replace argument here to change output var arr = f("apples appeal"); function g(ar) { var str = ""; for (x = 0; x < 3; x++) { for (y = 0; y < 3; y++) { str += ar[y][x] || " "; } str += "\n"; } console.log(str); } ``` # Ungolfed and Explanation ``` f=(input)=>{ //remove spaces input = input.replace(/ /g, ""); //convert to array (so I can uppercase individual letters) input = input.split(""); //position in input var pos = 0; //positions inside output var xPos = 1; var yPos = 1; //output container (3 rows, 3 columns) var arr = [[],[],[]]; //counterclockwise indexes for x var xOrder = "00122210"; //counterclockwise indexes for y //var yOrder = "12221000" var yOrder = xOrder * 100 + ""; //loop infinitely (breaks when input[pos] is undefined) for (;;) { //loop around circle for (var i = 0; i < 8; i++) { if (!input[pos]) { break; } //if item already in array equal next item in input, set next item in input to caps before if (arr[xPos][yPos] == input[pos]) { input[pos] = input[pos].toUpperCase(); } //write or overwrite in array with current from input arr[xPos][yPos] = input[pos]; //increment last because we do not prime our loops xPos = xOrder[i]; yPos = yOrder[i]; pos++; } if(!input[pos]) { break; } } return arr; } ``` ]
[Question] [ ## Background A [*Davenport-Schinzel sequence*](http://en.wikipedia.org/wiki/Davenport%E2%80%93Schinzel_sequence) has two positive integer parameters `d` and `n`. We will denote the set of all Davenport-Schinzel sequences for given parameters by `DS(d,n)`. Consider all sequences of the natural numbers `1` to `n`, inclusive, which satisfy: * No two consecutive numbers in the sequence are identical. * There is no subsequence (not necessarily consecutive) of length greater than `d`, which alternates between two different numbers. Let `L` denote the maximum length of such a sequence (given `d` and `n`). Then, `DS(d,n)` is the set of all such sequences with length `L`. Some examples might help. Let `d = 4`, `n = 3`. The longest possible sequences with these constraints have `L = 8`. So the following is a member of `DS(4,3)`: ``` [1, 2, 1, 3, 1, 3, 2, 3] ``` There are no consecutive identical numbers and there are alternating subsequences of length `4`, but not longer ones: ``` 1 2 1 2 1 2 1 2 1 3 1 3 1 3 1 3 2 3 2 3 2 3 2 3 1 3 1 3 1 3 1 3 ``` The following examples are *not* in `DS(4,3)`: ``` [1, 2, 2, 3, 1, 3, 2, 3] # Two consecutive 2's. [1, 2, 1, 3, 1, 3, 2, 1] # Contains alternating subsequences of length 5. [1, 2, 1, 3, 1, 3, 2] # Longer valid sequences for d = 4, n = 3 exist. ``` For further information see [MathWorld](http://mathworld.wolfram.com/Davenport-SchinzelSequence.html) and [OEIS](https://oeis.org/A002004) and the references they list. ## The Challenge Given two positive integers, `n` and `d`, generate any Davenport-Schinzel sequence in `DS(d,n)`. Note that these are not generally unique, so output any single valid result. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, and returning the result from the function or printing it to STDOUT (or closest alternative). You may use any convenient, unambiguous string or list format for output. This is code golf, so the shortest submission (in bytes) wins. ## Sequence Lengths Since the sequences are not unique, there is not much use for individual examples in this challenge. However, the two general validity problems are fairly easy to check for any output, so the main question is just whether the sequence has the right length (or there's a longer valid sequence). Therefore, here is a list of the known1 `L` for given `d` and `n`: ``` \ d\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 \----------------------------------------------------------- 1 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 3 | 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 4 | 1 4 8 12 17 22 27 32 37 42 47 53 58 64 69 75 81 86 92 98 5 | 1 5 10 16 22 29 ... 6 | 1 6 14 23 34 ... 7 | 1 7 16 28 41 ... 8 | 1 8 20 35 53 ... 9 | 1 9 22 40 61 ... 10 | 1 10 26 47 73 ... ``` You must not hardcode any information from this table into your submission. 1 This table is from 1994, so there may have been more progress since then, but I doubt that any submission will be able to handle even the larger entries in this table in a reasonable amount of time. [Answer] # Python 2: 172 ``` from itertools import* d,n=input();S=[[1]] for s in S: for v in range(1,n+1): if(v!=s[-1])*all(w[2:]!=w[:-2]for w in combinations(s+[v],d+1)):S.append(s+[v]) print S[-1] ``` Input is simply in the format `4, 3`. I iteratively create all sequences, which start with `1` and satisfy the two properties, and store them in `S`. Since I create them in sorted order (sorted by length [and by values]), the last entry has to be a Davenport-Schinzel-sequence. Uses the nice fact, that you can iterate over a list while appending to it. ]
[Question] [ Your challenge today is to take input like this: ``` fbcfbee ffcabbe debceec bccabbe edcfbcd daeaafc eebcbeb ``` And output the best possible move in a Bejeweled-like game that will match three or more letters, like this (note the capital `B` and `C`): ``` fbcfbee ffcabbe deBCeec bccabbe edcfbcd daeaafc eebcbeb ``` Full specifications: * The input will be `n` lines of `n` lowercase letters each (where `n` could be any number). * The output will be the best move you could make in a match-3 game, with the two letters you want to swap capitalized. * Matches should have the following priority (in these examples, `.` indicates a square that doesn't matter): 1. Five-in-a-row ``` xxYxx ..X.. ``` 2. Broken five-in-a-row ``` X.. Yxx x.. x.. ``` or ``` .X. xYx .x. .x. ``` 3. Four-in-a-row ``` xYxx .X.. ``` 4. Three-in-a-row ``` xYx .X. ```You must find the match of the highest priority and output it. * If there are multiple matches of the same priority, you can output any one of them. * There will always be at least one match (your program can break if there are no matches, or do anything you want). * I/O can be in any reasonable format (stdin/out, reading and writing files, function arguments/return values, dialog boxes, etc.) but NOT hardcoded (like `x="[insert input here]"`). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins. If you use any network access for some reason, all bytes downloaded from the network count against your score. [Answer] **Python3.4, 772** (Using tabs for indentation, instead of spaces.) ``` import sys,itertools as I B=[] for l in sys.stdin: l=l.rstrip() B.append(list(l)) Z=len(B[0]) F=T=None R=range N=min X=max P=I.product S=0 def C(I,J,K,L): global F,T,S if K<0 or K>=Z or L<0 or L>=Z: return B[I][J],B[K][L]=B[K][L],B[I][J] h=v=1 m=B[K][L] for i in R(K+1,N(Z,K+5)): if B[i][L]!=m:break v+=1 for i in R(K-1,X(0,K-5),-1): if B[i][L]!=m:break v+=1 for j in R(L+1,N(Z,L+5)): if B[K][j]!=m:break h+=1 for j in R(L-1,X(0,L-5),-1): if B[K][j]!=m:break h+=1 c=X(h,v)*2 if N(h,v)>=3:c+=N(h,v) if c>S:S=c;F=I,J;T=K,L B[I][J],B[K][L]=B[K][L],B[I][J] for i,j in P(reversed(R(Z)),R(Z)): for d,e in (1,0),(0,-1),(0,1),(-1,0): C(i,j,i+d,j+e) for i,j in P(R(Z),R(Z)): c=B[i][j] if (i,j)in(F,T):c=c.upper() print(c,end=('',"\n")[j==Z-1]) ``` ]
[Question] [ The [THX deep note](https://www.youtube.com/watch?v=uYMpMcmpfkI) is one of the most recognizable sounds in audio/video production technology. According to its creator, it took about [20,000 lines of C code](https://en.wikipedia.org/wiki/Deep_Note) to generate the final result. We can do better than that. Your task is to write a script in any language that will generate a sound (to a file or directly to hardware) that fits the trademark description of the THX sound, as provided by the [US Patent and Trademark office](http://tsdr.uspto.gov/#caseNumber=74309951&caseType=SERIAL_NO&searchType=statusSearch): > > The THX logo theme consists of 30 voices over seven measures, starting in a narrow range, 200 to 400 Hz, and slowly diverting to preselected pitches encompassing three octaves. The 30 voices begin at pitches between 200 Hz and 400 Hz and arrive at pre-selected pitches spanning three octaves by the fourth measure. The highest pitch is slightly detuned while there are double the number of voices of the lowest two pitches. > > > Note that the "preselected pitches" must be roughly the same as the pitches in the actual THX deep note, which are in the key of E flat. The shortest code to do so in any language wins. [Answer] # C, 323 bytes ``` #include<math.h> #define A y=-2*y*y*y+3*y*y main(i,j,o,e){e=44100;write(1,"RIFF´9WAVEfmt  D¬ ± data9",44);float r[30],x,y,k,v;for(i=0;i++<30;r[i]=.5-(9*i%7)/7.);for(i=0;i++<9*e;){x=2.*M_PI*i/(0.+e),k=y=1-i/(8.*e),v=0,A,A,A,y=y>1?1:y;for(j=0;j++<30;o=j%6,v+=(7-o)*.1*sin(x*(20<<o)*(1+y*r[j])));write(1,&v,4);}} ``` (among others, NUL characters could't be pasted in the textbox; you can [view or download the original file here](http://static.mathieu-rodic.com/_/deep-note.c)) Usage: ``` gcc deep-note.c -o deep-note ./deep-note > deep-note.wav ``` [Click here to listen to a preview of the generated sound!](http://static.mathieu-rodic.com/_/deep-note.wav) ]
[Question] [ Write a program or a function in any programming language that takes a 6 digit hexadecimal input/argument. The input/argument can be 6 values or a 6 character string. Your program should output an exactly 8 character wide rectangular block of characters containing only the hexadecimals supplied combined with spaces (+Linefeed). The rectangular block is a combination of smaller block shapes, one for each of the 6 supplied values. Here follows 2 demostrative sample inputs and sample valid outputs: Sample **input**: ``` "464fa6" or [4, 6, 4, 15, 10, 6] ``` One valid solution **output**: ``` 44 66 ff 44 66 ff 66 ff aa f aaa ffff aa ffff aaa 6 44 66666 44 ``` Sample **input**: ``` "35bf12" ``` One valid solution **output**: ``` 55555 22 bbbbbbbb b b b 33 fffff 3 ff ff ffffff 1 ``` *Rules:* 1. The output must be a rectangular shape 2. The output can be of any vertical height, but must be exactly 8 characters wide 3. The "inner blocks", refered to as the "block shape"s, cannot connect to any other block shape, the block shapes must be separated by a wall of blankspaces exactly 1 character wide horizontally, vertically and diagonally. 4. The wall of blankspaces cannot run parallell to the outer edges, only 1 character wide wall-edges can exist at the output edges. There should not exist any linked spaces anywhere on the outmost rectangle edge on the output. 5. The width of the wall of blankspaces should Not at any point exceed 1 character. 6. The inner block shapes should be uniform with the area of x characters, where x is the hexadecimal value supplied and the shape should consist of the charater x where x is the hexadecimal character representative. 7. The inner block shapes can be of any form as long as all of the shape characters connects vertically or horizontally, and does not valiating the rules for the wall of blankspaces. 8. The 6 block shapes can be placed in any internal "order" inside the outputted rectangle. 9. Valid input range: 1 ... 15 ("1" ... "f") for each shape. The input to your program should not contain any other information than the 6 hexadecimal numbers, and the input should not be sorted in any other way than in the samples before it is supplied to your program/function. Tell us what input format your solution uses (the input can not contain any other information than the hexadecimal values). 10. A inner block shape can be hollow. The hole should be of blankspace characters which counts as wall of blankspaces, meaning the hole in a hollow inner block shape cannot be more than 1 characters wide. Three examples of valid hollow shapes: ``` aaa a aaa aaa 999 9 9 999 9 ffffff f ff ffffff ``` One example of an invalid hollow shape: ``` ffffff f f f f fffff ``` I assume that all input combinations is not possible to "solve" according to the rules above, therefor I list 10 sample inputs that your program should be able to "solve" (all is verified solveable): ``` 1. 464fa6 (same as the first sample) 2. 35bf12 (second example input seen above) 3. 111126 4. ff7fff 5. 565656 6. abcdef 7. 1357bd 8. 8c6a42 9. ab7845 10. 349a67 ``` Your program should be able to solve any of the 10 sample inputs in resonable time. translate resonable time to within 1 hour on a standard desktop computer. Say like: 3 Ghz Dual core, 4GB memory for a reference. This is code golf, the shortest solution wins. The solution can be a fully working program or a function [Answer] ### Haskell, 156 Well, this one stretches the rules a bit. I don't have any blankspace walls except for the linebreaks, therefore all my walls have a length of 1. ``` import Data.List r=replicate main=getLine>>=putStrLn.concatMap(\b->unlines$s(head$elemIndices b"0123456789abcdef")b) s n c|n<9=[r n c,""]|True=r 8 c:s(n-8)c ``` output for 464fa6: ``` 4444 666666 4444 ffffffff fffffff aaaaaaaa aa 666666 ``` [Answer] # BrainF\*ck - 134 (newline intr ``` >>+[++++++++++>,----------]>++++++[<+++++>-]<++[<]<++++++[>+++++<-]>++>- >..<<.>>>..<<<.>>>>..<<<.<........>.>>>>..>>>.<<..>>.<..[<]>>. ``` I think that this is the simplist answer Input taken via 6 hexadecimal characters to stdin, followed by a newline to submit. EDIT: This fails due to rule 6, that I didn't fully realize until now :/ ]
[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/188171/edit). Closed 4 years ago. [Improve this question](/posts/188171/edit) In the tabletop RPG named Pathfinder, there is a feat that characters can take called [Sacred Geometry](https://www.d20pfsrd.com/feats/general-feats/sacred-geometry/), which allows a character who has it to buff their spells in exchange for doing some math: to use it, the character rolls a number of six-sided dice equal to their ranks in a particular skill, consults a table based on their spell level to determine which three prime numbers are the "Prime Constants" for that spell level, then calculates whether or not it's possible to produce one of the Prime Constants by performing some combination of addition, subtraction, multiplication, and division and parenthetical grouping on all the numbers rolled. The table of Prime Constants by Spell Level are as follows: ``` +-------------+-----------------+ | Spell Level | Prime Constants | +-------------+-----------------+ | 1st | 3, 5, 7 | | 2nd | 11, 13, 17 | | 3rd | 19, 23, 29 | | 4th | 31, 37, 41 | | 5th | 43, 47, 53 | | 6th | 59, 61, 67 | | 7th | 71, 73, 79 | | 8th | 83, 89, 97 | | 9th | 101, 103, 107 | +-------------+-----------------+ ``` So, for instance, if a character has 5 skill ranks and they're casting a 4th level spell, they would roll five six-sided dice and would need to be able to calculate a value of 31, 37, or 41. If they rolled a 6, 6, 4, 3 and 1, then they could produce a value of 37 by performing the following computation: (6 × 6) + (4 – 3) × 1 = 37, or they could produce a value of 41 by doing ([6 + 6] × 3) + 4 + 1 = 41. As a result, their casting of the spell would succeed. For this programming puzzle, your job is to write a function with two input parameters, Spell Level and Skill Ranks, roll a number of six-sided dice equal to the Skill Ranks parameter, then compute if you can produce (at least) one of the Prime Constants associated with the Spell Level parameter, then output a Boolean value. Answers would be ranked primarily by the efficiency of their algorithm (I'm pretty sure that a brute force algorithm would scale very quickly as the Skill Ranks parameter increases), and then by the size of the submitted source code in bytes. [Answer] # Python 2.7, 285 bytes ``` from itertools import* from random import* def f(s,r): p=[];n=1;k=1;P=1;d=choices('123456',k=r);D=permutations(d,r);O=product('+-*/',repeat=r-1) while-~s*3>n:p+=P%k*[k];n,k,P=n+P%k,k+1,P*k*k return any(n in{eval('int(%s)'%'%s'.join(i)%o)for i in D for o in O}for n in p[-4:-1]) ``` Technically conforms to the specifications of the challenge. Only returns True/False, does not expose the dice rolls used or the expression used to caller. Also, this algorithm ignores grouping, since we can perform the same operations without grouping by using ordering instead. (This would not be true if exponentiation was one of the possible operations, for example.) Exponential runtime, since it generates all possibilities and then checks if at least one solution exists. ]
[Question] [ ## Camel Up Cup 2k18 In this challenge, we will be playing the semi-popular board game Camel Up. [Camel Up!](https://www.boardgamegeek.com/boardgame/153938/camel) is a board game that has players betting on camels to win rounds, win the game or lose the game, set traps to influence movement or move a camel. Each of these decisions rewards you with the chance of getting some money, which is what determines the winner. Players should use probability, game-state considerations and opponent tenancy to make their decisions. [Here is a short video showing players how to play](https://www.youtube.com/watch?v=hQftUMnLZd8). ## How to play Here is a rough idea of how to play. Watching one of the videos may be more helpful because they have visuals :) On your turn you have 4 options. 1. Move a camel. This picks a camel from those who haven't moved and moves it between 1-3 spaces. You get 1 coin. Rounds end when all five camels have moved, they can then all move 2. Place a trap. This goes on the board until the end of round. You choose +1/-1 trap. If a camel or camel stack lands on it they move +1/-1 and you get a coin. You cannot place a trap on square 0. You can place a trap where camels are, although it will only affect camels that land on it after. 3. Round winner bet. You take a bet on a round winner. They win you get 5/3/2/1 depending on if you were the 1st/2nd/3rd to bet on that camel. 4. Game winner/loser. You take a bet on who will be in first or last at the end of the game. you get 8/5/3/1/1 (I think) based on if you were 1st/2nd/3rd/etc to bet on that camel Notes: * There are 5 camels. They start on a position randomly from 0-2. * When a camel is moved (see above for what triggers this) they move 1-3 squares. If they would be placed on a square with another camel they are put "on top" of the other, creating a camel stack. If a camel is to move it moves all camels above it on the camel stack. The camel at the top of the stack is considered in the lead * If you land on a +1 trap (see above for what triggers this) you move one square further forward. Standard stacking rules apply. * However if you hit a -1 trap you move one square backwards. You go *under* the stack of camels that are on that square, if any. * The game ends when a camel hits square 16. This immediately invokes round end and game end triggers * Game winner/loser bets can be done only once per camel. I.e. you cannot bet on a camel to win *and* lose the game ## Challenge In this challenge, you will write a Python 3 program to play a four player, winner takes all glory game of Camel Up Your program will receive the gamestate, which contains: * **camel\_track**: with the locations of the camels * **trap\_track**: with the location of the traps (entry of the form [trap\_type (-1,1), player]) * **player\_has\_placed\_trap**: an array telling you if players have placed a trap this round * **round\_bets**: an array of the bets placed this round. Of the form [camel,player] * **game\_winner\_bets / game\_loser\_bets**: arrays of the bets players made for camels to win or lose the game. You will only be able to see the value of players who made the bets, *not* who they bet on. You can know who you bet on. #of the form [camel,player] * **player\_game\_bets**: another representation of the game\_winner\_bets / game\_loser\_bets. Again, only look at the bets that your bot made. * **player\_money\_values**: an array showing the amount of money each player has. * **camel\_yet\_to\_move**: An array showing if a camel has moved this round. On top of the gamestate you also get: * **player**: an integer telling you what player number you are (0-3). --- Syntax for what players should return is: * [0] : Move Camel * [1,trap\_type,trap\_location] : Place Trap * [2,projected\_round\_winner] : Make Round Winner Bet * [3,projected\_game\_winner] : Make Game Winner Bet * [4,projected\_game\_loser] : Make Game Loser Bet This should be wrapped in a move(player,gamestate) method For instance, here's a player that will make a round winner bet if they are in last place. If they aren't then they will place a trap on a random square. ``` class Player1(PlayerInterface): def move(player,g): if min(g.player_money_values) == g.player_money_values[player]: return [2,random.randint(0,len(g.camels)-1)] return [1,math.floor(2*random.random())*2-1,random.randint(1,10)] ``` The game was chosen for several reasons: it has a relatively small pool of options to select from (roughly 20 choices per turn, easily narrowed down to usually about 3-4), games are short and there is an element of luck (makes it so even the "bad" bots can win). ## Gameplay The tournament runner can be found here: [camel-up-cup](https://github.com/trbarron/Camel_Up_Cup_2K18). Run [`camelup.py`](https://github.com/trbarron/Camel_Up_Cup_2K18/blob/master/camelup.py) to run a tournament or the function PlayGame to run games. I'll keep that repository updated with new submissions. Example programs can be found in [`players.py`](https://github.com/trbarron/Camel_Up_Cup_2K18/blob/master/players.py). A tournament consists of 100 games per 10 players (rounded up, so 14 players means 200 games). Each game will be four random players selected from the pool of players to fill the four positions. Players will not be able to be in the game twice. ## Scoring The winner of each game is the player with the most money at the end of the game. In the case of a tie at the end of a game all players with the maximum money amount are awarded a point. The player with the most points at the end of the tournament wins. I will post scores as I run the games. The players submitted will be added to the pool. I added three really dumb bots and one that I made to start. ## Caveats Do not modify the inputs. Do not attempt to affect the execution of any other program, except via cooperating or defecting. Do not make a sacrificial submission that attempts to recognize another submission and benefit that opponent at its own expense. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned. Limit the time taken by your bot to be ~10s per turn. Submissions may not duplicate earlier submissions. Please don't view game\_winner or game\_loser bets from other players. Its pretty easy to do but still cheating. If you have any questions, feel free to ask. ## Winning The competition will stay open indefinitely, as new submissions are posted. However, I will declare a winner (accept an answer) based on the results one month after this question was posted (July 20th). ## Results ``` Player0: 12 Player1: 0 Player2: 1 Sir_Humpfree_Bogart: 87 ``` [Answer] ## [`Sir_Humpfree_Bogart.py`](https://github.com/trbarron/Camel_Up_Cup_2K18/blob/master/Sir_Humpfree_Bogart.py) This is a bot I made for the [Camel Up Cup Tournament](http://tylerbarron.com/CamelUpCup.html). First, they look at all the possible configurations that the camels could end up at the end of the round. Then they determine the expected value of betting on a camel winning the round using ``` EV_roundwin = (chance_1st)*(payout) + (chance_2nd)*(payout) - (chance_3rd_or_worse)*(cost) ``` Then they move camels randomly until a camel wins. After doing this a few thousand times you can estimate the chance each camel will win and lose. Again, we get the expected value of these using ``` EV_gamewin = (chance_1st)*(payout) - (chance_2nd_or_worse)*(cost) ``` The only other options are moving a camel (which always yields one coin, so its expected value is one) and placing a trap. Both teams felt placing a trap was a weak enough option to ignore it entirely. With this information the bots chose the option with the highest expected value. Since the tournament viewed a second place finish the same as a last place finish it makes sense if you are behind to take chances to get into first place. SBH used distance\_from\_first\_place and nearness\_to\_end to determine how risky the bot should be, where if you are far from first and close to the end then riskiness would be high and if you are in first or far from the end of the game the riskiness would be low. With a low riskiness the bot would decide on an action with a high expected value option and a high riskiness yielding the option with a high upshot. The exact equation was ``` Functional_EV = EV + (upshot-EV) * riskiness ``` where upshot is the highest payout you can get from a decision and riskiness ranges from 0 to 1. [Answer] ## [`players.py`](https://github.com/trbarron/Camel_Up_Cup_2K18/blob/master/players.py) These are incredibly dumb bots to get the tournament going. They have nearly no logic but act as frameworks for people to use ``` import random import math from playerinterface import PlayerInterface class Player0(PlayerInterface): def move(player,g): #This dumb player always moves a camel return [0] class Player1(PlayerInterface): def move(player,g): #This player is less dumb. If they have the least amount of money they'll make a round winner bet #If they aren't in last then they'll place a trap on a random square. Still p dumb though if min(g.player_money_values) == g.player_money_values[player]: return [2,random.randint(0,len(g.camels)-1)] return [1,math.floor(2*random.random())*2-1,random.randint(1,10)] class Player2(PlayerInterface): def move(player,g): #This dumb player always makes a round winner bet return [2,random.randint(0,len(g.camels)-1)] ``` ]
[Question] [ # Cyclic Polyglot Challenge *This is the cops thread. You can find the robbers thread [here](https://codegolf.stackexchange.com/questions/129865/cyclic-polyglot-challenge-robbers).* ## Cyclic Polyglot A N-element cyclic polyglot is a complete program that can be run in N different languages. In each language, when the program is run with no input (possibly subject to [this exception](https://codegolf.meta.stackexchange.com/a/5477/9486)), it should print the name of a language to STDOUT. Specifically, if the program is run in the Kth language, it should print the name of the (K+1)th language. If the program is run in the Nth language (that is, the final language in an N-element cycle), it should print the name of the first language. An example might be useful. ``` a = [[ v = 7, puts('Befunge') ]] __END__ = print("Ruby") -->*+:292*++,,@ --3 9 --7 * --^,:-5< ``` Running this program with Lua prints the string "Ruby". Running this program in Ruby prints the string "Befunge". Running this program in Befunge prints the string "Lua", completing the cycle. This program constitutes a 3-cycle consisting of Lua, Ruby, and Befunge. The same language cannot appear twice in a cycle, and different versions of the same language (such as Python 2 and Python 3) cannot appear in the same cycle as one another. ## Cops Your challenge is to write an N-cyclic polyglot, where N is at least 2. Then, you must add, replace, and delete some number of characters to the program to produce an M-cyclic polyglot, where M is strictly greater than N. You should then post the shorter, N-cyclic polyglot (and the languages it runs in), as well as the number of characters you changed to produce the longer polyglot. Your score is N, the number of languages in your shorter cycle. The robbers will try to identify your longer cycle. If, after seven days, no one has successfully cracked your solution, you should edit your answer declaring that it is safe. You should also post your longer M-cyclic polyglot at this time. ## Robbers Given a cop's N-cyclic polyglot and the number of characters they added to produce a larger polyglot cycle, your goal is to produce that larger cycle. If you can produce a longer cycle by adding, deleting, or replacing as many characters as the cop did *or fewer characters*, you have cracked the cop's polyglot. Your score is the length of the new cycle you've created. Your new polyglot need not be the same as or even similar to the cop's secret polyglot; it only needs to be larger than their existing one. Your solution may also be cracked. If another robber comes along and produces a cycle strictly longer than yours, starting from the same cop's polyglot, they have stolen your points. ## Valid Programming Languages Since this challenge indirectly involves guessing programming languages used by other participant's, the definition of a programming language for the purposes of this challenge will be a little more strict than the usual definition. A programming language used in this challenge must satisfy all of the following conditions. * The language must satisfy the [usual PPCG requires for a programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). * The language must have either a [Wikipedia article](https://en.wikipedia.org/wiki/Main_Page), an [Esolangs article](http://esolangs.org/wiki/Main_Page), or a [Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted. * The language must have a freely available interpreter or compiler. ## Final Notes * The code you write should be a standalone program in every language that it is intended to run in. Functions or code snippets are not allowed. * Your program will be given no input through STDIN. Likewise, your program should print nothing to STDERR. * A cop's score is the number of languages in the cycle of the polyglot they posted. The cop should post the languages that the posted polyglot runs correctly in, as well as the number of characters they added to produce a longer polyglot. They are *not* responsible for posting the languages the longer, hidden polyglot runs in until their answer is safe. * A robber's score is the number of languages the modified polyglot runs in. As with the cop, the robber should post the list of languages the polyglot runs correctly in. * The number of characters changed should be computed in Levenshtein distance. [Answer] # [C (gcc)](https://gcc.gnu.org/), 126 bytes `M=N+1` `Levenshtein(polyglot(M),polyglot(N))` is **36** bytes ``` #include<stdio.h> #define print(a) main(){int z[1];if(sizeof(0,z)==4)printf("C(gcc)");else printf("Perl5");} print("C++(gcc)") ``` [Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/Djks5JTUtMy9VoaAoM69EI1FTITcxM09DsxrIU6iKNoy1zkzTKM6sSs1P0zDQqdK0tTXRBCtN01By1gCaqamkaZ2aUww1ACgakFqUYwoUrOWCGKnkrK0NVfj//7/ktJzE9OL/uuUA "C (gcc) – Try It Online") ]
[Question] [ The *[Dal Segno](https://en.wikipedia.org/wiki/Dal_Segno)* and *[Da Capo](https://en.wikipedia.org/wiki/Da_capo)* are two very commonly used musical terms. They mean "*from the sign*" (𝄋) and "*from the beginning*" respectively. There is also the idea of the *[coda](https://en.wikipedia.org/wiki/Coda_(music))* (𝄌), which is the very end of a piece of music. It's what's played after the "main section" of the piece. A *D.S. al coda* (*Dal Segno al coda*), for example, means "go to the *segno*, play until you're told to go to the *coda*, and then jump there." ## Description Your job in this challenge is to take input composed of any number of notes which may or may not contain *Dal Segno*s and *Da Capo*s and output the same music with the aforementioned jumps "unfolded" so that the repetitions are expanded out verbatim. ## Input Your code should take as input a sequence of either notes or *signals* (here defined as anything but a note), separated by spaces in one string. * Notes are any of `a`, `b`, `c`, `d`, `e`, `f`, or `g`, with an optional `#` or `b` appended (for the purposes of this challenge, there is no rhythm). * A `C` (capital c) represents a *coda* marking. There will always be either zero or two *coda* markings; the first *coda* marking represents where to jump from, and the second represents where to jump to. * An `S` (capital s) represents a *signo* marking. There will always be either zero or one *signo* marking(s). * An `F` (capital f) represents a *fine* marking. This "overrides" the end of the piece—more on that below. There will always be either zero or one *fine* marking(s). * Any of the following exact strings of text represent: + `D.S. al fine`: go to the *signo* and play until either the end of the piece or the *fine* marking (if it exists). + `D.S. al coda`: go to the *signo*, play until the *coda*, then jump to the second *coda* marking and play until the end of the piece. + `D.C. al fine`: go to the beginning, play until the end or the *fine* marking. + `D.C. al coda`: go to the beginning, play until the *coda*, then jump to the second *coda* marking and play until the end of the piece.There will always be a minimum of zero and a maximum of one of each string per piece. There will never be multiple `al fine`s or multiple `al coda`s in a piece. ## Output Your code should output in a similar string format: a list of notes, separated by spaces. You may always assume that the output will end up being one or more characters long. ## Test cases In: `a# bb c b a` Out: `a# bb c b a` In: `a S b D.S. al fine c` Out: `a b b c` In: `a S b C c D.S. al coda d C e` Out: `a b c b e` In: `a b F c d D.C. al fine e f` Out: `a b c d a b` In: `a b D.C. al fine c d F e f` Out: `a b a b c d` In: `a b C c d D.C. al coda e f C g g#` Out: `a b c d a b g g#` In: `a b D.C. al coda c d C e f C g g#` Out: `a b a b c d g g#` In: `a b S c d C D.C. al coda C D.S. al fine e f F g` Out: `a b c d a b c d c d e f` In: `a S b C c D.S. al coda C d D.S. al fine e F f` Out: `a b c b d b c d e` In: `a b C c d D.C. al coda e f F g g# C gb a# D.C. al fine` Out: `a b c d a b gb a# a b c d e f` In: `a F b C D.C. al coda C D.C. al fine` Out: `a b a b a` In: `C a S b D.C. al coda C c D.S. al fine d` Out: `a b c b c d` In: `a S b D.S. al coda C C c D.C. al fine` Out: `a b b c a b c` In: `a F C b C D.C. al coda D.C. al fine` Out: `a b a a` ## Rules * The markings will always appear in a logical order. That is, there will never be an `S` after a `D.S.` and there will always be one before, etc. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. [Answer] # JavaScript (ES6), 253 bytes ``` x=>eval('n=(" "+x).replace(/D.{11}|[CSF]/g,d=>({C:4,S:5,F:6}[d]|(d[2]<"S")*2+(d[8]<"f"))).split` `;for(i=c=f=o="";v=n[++i];v<9?v<4?(n[i]=7,i=0,s=n.indexOf`5`,v==0?f=i=s:v==1?c=i=s:v==2?f=1:c=1):v==4&c?c=!(i=n.indexOf("4",i+1)):v==6&f?i=n:0:o+=v+" ");o') ``` ## Explanation Could be golfed better but I'm done for now. ``` x=> eval(` // use eval to enable for loop without return n=(" "+x) // n = array of [ "", ...notes/commands ] // empty first element means f and c can be set // to i (always true) in the cases below // DS fine => 0, DS coda => 1, DC fine => 2, DC coda => 3, C => 4, S => 5, F => 6 .replace(/D.{11}|[CSF]/g,d=>({C:4,S:5,F:6}[d]|(d[2]<"S")*2+(d[8]<"f"))) .split\` \`; for( i= // i = position in note array c= // c = look out for coda if true f= // f = look out for fine if true o=""; // o = output string v=n[++i]; // v = note/command v<9? // if not a note v<4?( // if DS/DC n[i]=7, // change it to NOP i=0, // reset i here to save doing it in DC cases s=n.indexOf\`5\`, v==0?f=i=s: // case: D.S. al fine v==1?c=i=s: // case: D.S. al coda v==2?f=1: // case: D.C. al fine c=1 // case: D.C. al coda ): v==4&c?c=!(i=n.indexOf("4",i+1)): // case: C v==6&f?i=n: // case: F 0 // case: S :o+=v+" " // add the note );o // return the output `) ``` ## Test ``` var solution = x=>eval('n=(" "+x).replace(/D.{11}|[CSF]/g,d=>({C:4,S:5,F:6}[d]|(d[2]<"S")*2+(d[8]<"f"))).split` `;for(i=c=f=o="";v=n[++i];v<9?v<4?(n[i]=7,i=0,s=n.indexOf`5`,v==0?f=i=s:v==1?c=i=s:v==2?f=1:c=1):v==4&c?c=!(i=n.indexOf("4",i+1)):v==6&f?i=n:0:o+=v+" ");o') ``` ``` <input type="text" id="input" value="a b C c d D.C. al coda e f F g g# C gb a# D.C. al fine" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` ]
[Question] [ ## Challenge Walking around Marks and Spencers, I noticed that they had air conditioning units placed randomly around the shop. Wanting to keep cool, I wondered what was the easiest way to move around the whole shop without being away from an air conditioning unit for too long. Given a map, you must find a way to travel around the whole map keeping the distance from an air conditioning unit as short as possible (even if the AC unit is on the other side of a wall). ## Map The map may be supplied in any way you like and uses the following symbols: ``` + is a corner of a wall | is a east/west facing wall - is a north/south facing wall X is an air conditioning unit S is the start and end point ``` An example map would be: ``` +------S---+ | X | | ---+-+ X | | |X| | | ---+ +---+ | X | +----------+ ``` or ``` +---+--+ | X | | | | +-----+------+ | | X | X | | ---+ | S | | | X | | | | +-+-------+--+ | X | +------+ ``` Travelling around the whole map means passing through every empty space and air conditioner. You cannot travel through a wall and may only travel orthogonally. A map may not always be rectangular. Keeping the distance as short as possible from an AC unit is the sum over all time steps. Passing through means entering and leaving. You may output the path in any way you like. Examples include: * Outputting the map with the path included * Outputting the path as a succession of compass points (e.g. `NNSESW`) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) for Windows, ~~376~~ 367 bytes Like a lazy man, I don't go to every shelf, I move from air conditioner to air conditioner in a store. I believe I traveled all over the store visiting every air conditioner in it. ``` $f={param($m,$d,$o=@{})$w=(($l=$m-split" ")|% le*|sort)[-1] $m=($l|% *ht $w)-join" " if(!$o.$m-or$o.$m-ge$d-and$m-match'(?s)X.*S|S.*X'){$o.$m=$d++ $n=-split")X(S )X(.{$w}S S)X( S.{$w})X("|%{sls "(?s)^(.*$_.*)$" -inp $m -a|% m*|%{($_.Groups-replace'S',' ')[1,2]-join'S'}} $d=(($n+,($m-replace"(?s)(?<=S(.{$w})?) | (?=(.{$w})?S)",'S')*!$n)|%{&$f $_ $d $o}|sort)[0]}+$d} ``` [Try it online!](https://tio.run/##dVTLbpwwFN3zFTfU6di8lNeiiopmpC666sobpGia0MGToQKbAtNJNPDt04uNGRI1LPDxfZxzfHlU6iDqZieK4nQi2/hYpXVaUlIGJAuIilfHnpFDTCkpYlKGTVXkreu4rLuEQnhdo@qWPYTXa4eUMdZg2Nu1QA4s/K1yiZVOvqUXREXYrGqzPguShanMEJZpu9kt6LJhSeTxjkdesmBHXRaTzPcdIuNRlCWUA96iIzn0HDhC4HqDyO0uj03RgDtQ/aSRRx4jjxEXwlxWQEoIU7RWelhGMfW9VvuqCWtRFelGLPgiWMCCPVwHN2vtGyN975BsOLf0AxyHrdUCdPk15sYIWzLogC5ju@XMDbCdeRdE4pSOn8kWyCOQDIjqx3ldrXufZP1pRZ2AXgWuy8zKLUg0uEbALeLn2JM8R5@kid9gHLiFHKYoVsC8SG9N4e3An0wQw6YQ93dDaiS509Rj4kuwch0/HC/f6WC4OECH0AQ1BEiGRDevdVdIoQnnHGeWgWbs8ME/M3VJZ7iGxQ9nmfEyPfBGB0871@GTTmJ7tF@kw8jIZoRsRlt41/PGtdFZ0dtbK@SbBiS0djsA0@PPz9pNjHZM5jRa1maAWwZ9S8Z1xmvdTLJzj6O/T7CXmdjmUmTwS@zSv7mqIYR2J2oBeQNSwSF9hVZBKiHNa9gomeVtrmQun7E3bxv9Tn742N9FP3jsH9hATbVvM4Wb/2tHsMWceEnLqhAB5OgRNmkNShavcM@stXHKvjNMRtuyg3MSC6YabWj4bC/h6Aw5Il4qsWlFFgBpIMbv1YRbxD9E2uxrEX5TZYn/rLFDp2vR7IuhRn/jjU70@u4SOmZD8WdiZ/e2B3XwL9qf/gE "PowerShell – Try It Online") Unrolled: ``` $f={ param($map,$distance,$o=@{}) $lines = $map-split"`n" $width = ($lines|% length|sort)[-1] $map = ($lines|% padRight $width)-join"`n" # to rectangle if(!$o.$map -or $o.$map-ge$distance -and $map-match'(?s)X.*S|S.*X'){ $o.$map = $distance++ # store a map to avoid recalculations $n = -split")X(S )X(.{$width}S S)X( S.{$width})X("|%{ # search a nearest X in 4 directions select-string "(?s)^(.*$_.*)$" -InputObject $map -AllMatches|% Matches|%{ ($_.Groups-replace'S',' ')[1,2]-join'S' # start a new segment (reset all S and replace the nearest X by S) } } $stepMore = $map-replace"(?s)(?<=S(.{$w})?) | (?=(.{$w})?S)",'S' $n += ,$stepMore*!$n # add a step if X was not found $distance=($n|%{&$f $_ $distance $o}|sort)[0] # recursive repeat } +$distance } ``` ]
[Question] [ Sometimes when you press a key on a keyboard, the letter doesn't always display on screen. Whether this is because of a dodgy connection or otherwise, you have decided to write a script to control the probability of a letter displaying on screen when the corresponding key is pressed. One day, you decide to buy a monkey and sit it down at a keyboard. Being curious, you decide to find out what the key probabilities are to help the monkey to write Hamlet in its entirety. Your challenge is to calculate the probabilities for each character so that the passage is typed out in the least number of characters. Here's a list of all of the characters you should consolidate: ``` qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!"':;.()?, ``` Newlines and spaces are included in the above list. You must only use the characters in the list, discounting all other characters (remove them from the passage). The program must be a program with the passage supplied via STDIN. The output must be to STDOUT. Since this is a Rosetta Stone challenge, you must write as many programs in different languages as possible. To win, you need to have the shortest code in the most number of languages. ## Test case 1 > > Shall I compare thee to a summer's day? > Thou art more lovely and more temperate: > Rough winds do shake the darling buds of May, > And summer's lease hath all too short a date > > > Answer: ``` { '\n': 0.017543859649122806, ' ': 0.16959064327485379, '!': 0.0, '"': 0.0, "'": 0.011695906432748537, '(': 0.0, ')': 0.0, ',': 0.0058479532163742687, '.': 0.0, '0': 0.0, '1': 0.0, '2': 0.0, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.0, '7': 0.0, '8': 0.0, '9': 0.0, ':': 0.0058479532163742687, ';': 0.0, '?': 0.0058479532163742687, 'A': 0.0058479532163742687, 'B': 0.0, 'C': 0.0, 'D': 0.0, 'E': 0.0, 'F': 0.0, 'G': 0.0, 'H': 0.0, 'I': 0.0058479532163742687, 'J': 0.0, 'K': 0.0, 'L': 0.0, 'M': 0.0058479532163742687, 'N': 0.0, 'O': 0.0, 'P': 0.0, 'Q': 0.0, 'R': 0.0058479532163742687, 'S': 0.0058479532163742687, 'T': 0.0058479532163742687, 'U': 0.0, 'V': 0.0, 'W': 0.0, 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'a': 0.08771929824561403, 'b': 0.0058479532163742687, 'c': 0.0058479532163742687, 'd': 0.046783625730994149, 'e': 0.093567251461988299, 'f': 0.0058479532163742687, 'g': 0.011695906432748537, 'h': 0.052631578947368418, 'i': 0.011695906432748537, 'j': 0.0, 'k': 0.0058479532163742687, 'l': 0.046783625730994149, 'm': 0.046783625730994149, 'n': 0.023391812865497075, 'o': 0.070175438596491224, 'p': 0.011695906432748537, 'q': 0.0, 'r': 0.052631578947368418, 's': 0.052631578947368418, 't': 0.058479532163742687, 'u': 0.029239766081871343, 'v': 0.0058479532163742687, 'w': 0.0058479532163742687, 'x': 0.0, 'y': 0.017543859649122806, 'z': 0.0 } ``` ## Test case 2 > > Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. > > Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. > > > Answer: ``` { '\n': 0.0036036036036036037, ' ': 0.18018018018018017, '!': 0.0, '"': 0.0, "'": 0.0, '(': 0.0, ')': 0.0, ',': 0.010810810810810811, '.': 0.0090090090090090089, '0': 0.0, '1': 0.0, '2': 0.0, '3': 0.0, '4': 0.0, '5': 0.0, '6': 0.0, '7': 0.0, '8': 0.0, '9': 0.0, ':': 0.0, ';': 0.0, '?': 0.0, 'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0.0, 'E': 0.0, 'F': 0.0018018018018018018, 'G': 0.0, 'H': 0.0, 'I': 0.0018018018018018018, 'J': 0.0, 'K': 0.0, 'L': 0.0, 'M': 0.0, 'N': 0.0018018018018018018, 'O': 0.0, 'P': 0.0, 'Q': 0.0, 'R': 0.0, 'S': 0.0, 'T': 0.0, 'U': 0.0, 'V': 0.0, 'W': 0.0036036036036036037, 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'a': 0.082882882882882883, 'b': 0.0054054054054054057, 'c': 0.025225225225225224, 'd': 0.03783783783783784, 'e': 0.10270270270270271, 'f': 0.016216216216216217, 'g': 0.023423423423423424, 'h': 0.041441441441441441, 'i': 0.057657657657657659, 'j': 0.0, 'k': 0.0, 'l': 0.027027027027027029, 'm': 0.0072072072072072073, 'n': 0.063063063063063057, 'o': 0.066666666666666666, 'p': 0.010810810810810811, 'q': 0.0018018018018018018, 'r': 0.050450450450450449, 's': 0.028828828828828829, 't': 0.093693693693693694, 'u': 0.010810810810810811, 'v': 0.014414414414414415, 'w': 0.014414414414414415, 'x': 0.0, 'y': 0.0054054054054054057, 'z': 0.0 } ``` See the theory [here](http://en.m.wikipedia.org/wiki/Infinite_monkey_theorem). ## Leaderboard ``` C - 371 - Gerwin Dox Java - 788 - Luminous ``` [Answer] # Java ~~788~~ 743 **Edit** Found so much I could golf down. Replaced whole words w/ letters, made method for putting keys into the `HashMap`, and moved all integer variables to one declaration. --- Not expecting this to beat any records, but oh well. This version REQUIRES you to enter how many lines of input your giving it since java likes to block on any methods that takes input. So example would be: > > 4 > > Shall I compare thee to a summer's day? > > Thou art more lovely and more temperate: > > Rough winds do shake the darling buds of May, > > And summer's lease hath all too short a date > > > ``` import java.util.*;class A{static HashMap<Character,Double>m=new HashMap<Character,Double>();public static void main(String[]g){Scanner s=new Scanner(System.in);int n,k,e,i='@';for(;i++<'[';)g((char)i);for(i='`';i++<'{';)g((char)i);for(i='/';i++<':';)g((char)i);char[]r={' ','!','"','\'',':',';','.','(',')','?',','};p(r);e=s.nextInt();s.nextLine();String l="";n=0;k=0;while(k<e){l=s.nextLine();for(i=0;i<l.length();i++){char c=l.charAt(i);m.put(c,m.get(c)+1);n++;}k++;n++;}m.put('\n',(double)(e-1));for(Iterator b=m.entrySet().iterator();b.hasNext();){Map.Entry p=(Map.Entry)b.next();System.out.println(p.getKey()+" = "+((double)p.getValue())/(n-1));b.remove();}}static void p(char[]a){for(char b:a)g(b);}static void g(char a){m.put(a,0.0);}} ``` UnGolfed ``` import java.util.*; class A{ static HashMap<Character,Double>m=new HashMap<Character,Double>(); public static void main(String[]g){ Scanner s=new Scanner(System.in); int n,k,e,i='@'; for(;i++<'[';)g((char)i); for(i='`';i++<'{';)g((char)i); for(i='/';i++<':';)g((char)i); char[]r={' ','!','"','\'',':',';','.','(',')','?',','}; p(r); e=s.nextInt(); s.nextLine(); String l=""; n=0; k=0; while(k<e){ l=s.nextLine(); for(i=0;i<l.length();i++){ char c=l.charAt(i); m.put(c,m.get(c)+1); n++; } k++; n++; } m.put('\n',(double)(e-1)); for(Iterator b=m.entrySet().iterator();b.hasNext();){ Map.Entry p=(Map.Entry)b.next(); System.out.println(p.getKey()+" = "+((double)p.getValue())/(n-1)); b.remove(); } } static void p(char[]a){ for(char b:a)g(b); } static void g(char a){ m.put(a,0.0); } ``` } [Answer] # C, 324 bytes (can someone check that for me?) Maybe I need to resharpen my method, it's a bit long. ``` main(){char*d="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!\"':;.()?,\n ",*p,*s,*c=calloc(1,1000),*r=c;int n=-1;do{scanf("%c",++r);for(p=d;*p;p++)n+=*p==*r?1:0;}while(*((short*)(r-1))!=2570);p=d;for(;*p;p++){int q=0;for(s=c;*(s+1);s++)q+=(*s==*p?1:0);printf("'%c':%f\n",*p-10?*p:244,(float)q/n);}free(c);} ``` Also, I can prove that it works. [Answer] # Python 3, 92 bytes ``` lambda n:{chr(x):n.count(chr(x))/len(n)for x in{10,*range(32,123)}-{*b"#$%&*+-/<=>@[\\]^_`"}} ``` If I understand the question correctly. Default argument won't work for some reason, probably something to do with `k`'s reference not being updated between calls. Thanks to Jakque for informing me about a bug and shaving off some bytes while fixing the bug, ]
[Question] [ This is a rather complex but very interesting maths subject (known as **"covering problem"**), And I'd like your help for implementing it. Imagine a lottery game, where each ticket must choose 5 random numbers in a set of 50 numbers (from 1 to 50). It's quite easy to know the probability of a winning ticket, or the probability to have 1, 2, 3 or 4 good numbers. It's also quite easy to "generate" all the tickets that have 1, 2, 3, 4 good numbers. My question (and code challenge) is related to this, but slightly different: I want to buy some lottery tickets (the fewest possible), such as **at least** one of my tickets has 3 good numbers. ## Challenge Your goal is to implement a generic solution (as a program or just a function), like this, in any language: ``` // Input: 3 prameters min_lottery_tickets(total_numbers_to_choose_from, how_many_numbers_to_choose, how_many_good_numbers_i_want) ``` For the above example, one would just have to call: ``` min_lottery_tickets(50, 5, 3) ``` and the program will generate the smallest set of tickets to play to achieve this goal. --- Example: ``` min_lottery_tickets(10, 5, 2) ``` would output 7 tickets, like those: ``` 1 2 3 4 5 5 6 7 8 9 10 1 2 6 7 10 3 4 8 9 3 4 6 7 8 1 2 3 8 9 1 4 9 5 10 ``` because such tickets are enough to cover any pair of numbers from 1 to 10. --- ## Output Text, one line per ticket, tabulations or spaces between numbers --- ## who wins The most efficient program wins (i.e. the program generating the fewest tickets for the above parameters): ``` min_lottery_tickets(50, 5, 3) ``` Thanks! [Answer] **I know it's not optimal**, but here is the code in node.js: ``` function min_lottery_tickets(total_numbers_to_choose_from, how_many_numbers_to_choose, how_many_good_numbers_i_want) { c(function(result) { var other = result[result.length - 1]; while (result.length < how_many_numbers_to_choose) { other++; var already = false; for (var i = 0; i < result.length; i++) { if (other === result[i]) { already = true; break; } } if (!already) { result.push(other); } } if (other <= total_numbers_to_choose_from) { // Print results console.log(result); } }, total_numbers_to_choose_from, how_many_good_numbers_i_want); } function c(next, total_numbers, length, start, results) { if (!start) start = 1; if (!results) results = []; for (var i = start; i <= total_numbers + 1 - length; i++) { var resultsNew = results.slice(0); resultsNew.push(i); if (length > 1) { c(next, total_numbers, length - 1, i + 1, resultsNew); } else { next(resultsNew); } } } ``` Some example results: ``` > min_lottery_tickets(5, 3, 2) [ 1, 2, 3 ] [ 1, 3, 4 ] [ 1, 4, 5 ] [ 2, 3, 4 ] [ 2, 4, 5 ] [ 3, 4, 5 ] ``` other: ``` > min_lottery_tickets(10, 5, 2) [ 1, 2, 3, 4, 5 ] [ 1, 3, 4, 5, 6 ] [ 1, 4, 5, 6, 7 ] [ 1, 5, 6, 7, 8 ] [ 1, 6, 7, 8, 9 ] [ 1, 7, 8, 9, 10 ] [ 2, 3, 4, 5, 6 ] [ 2, 4, 5, 6, 7 ] [ 2, 5, 6, 7, 8 ] [ 2, 6, 7, 8, 9 ] [ 2, 7, 8, 9, 10 ] [ 3, 4, 5, 6, 7 ] [ 3, 5, 6, 7, 8 ] [ 3, 6, 7, 8, 9 ] [ 3, 7, 8, 9, 10 ] [ 4, 5, 6, 7, 8 ] [ 4, 6, 7, 8, 9 ] [ 4, 7, 8, 9, 10 ] [ 5, 6, 7, 8, 9 ] [ 5, 7, 8, 9, 10 ] [ 6, 7, 8, 9, 10 ] ``` other: ``` > min_lottery_tickets(10, 5, 3) [ 1, 2, 3, 4, 5 ] [ 1, 2, 4, 5, 6 ] [ 1, 2, 5, 6, 7 ] [ 1, 2, 6, 7, 8 ] [ 1, 2, 7, 8, 9 ] [ 1, 2, 8, 9, 10 ] [ 1, 3, 4, 5, 6 ] [ 1, 3, 5, 6, 7 ] [ 1, 3, 6, 7, 8 ] [ 1, 3, 7, 8, 9 ] [ 1, 3, 8, 9, 10 ] [ 1, 4, 5, 6, 7 ] [ 1, 4, 6, 7, 8 ] [ 1, 4, 7, 8, 9 ] [ 1, 4, 8, 9, 10 ] [ 1, 5, 6, 7, 8 ] [ 1, 5, 7, 8, 9 ] [ 1, 5, 8, 9, 10 ] [ 1, 6, 7, 8, 9 ] [ 1, 6, 8, 9, 10 ] [ 1, 7, 8, 9, 10 ] [ 2, 3, 4, 5, 6 ] [ 2, 3, 5, 6, 7 ] [ 2, 3, 6, 7, 8 ] [ 2, 3, 7, 8, 9 ] [ 2, 3, 8, 9, 10 ] [ 2, 4, 5, 6, 7 ] [ 2, 4, 6, 7, 8 ] [ 2, 4, 7, 8, 9 ] [ 2, 4, 8, 9, 10 ] [ 2, 5, 6, 7, 8 ] [ 2, 5, 7, 8, 9 ] [ 2, 5, 8, 9, 10 ] [ 2, 6, 7, 8, 9 ] [ 2, 6, 8, 9, 10 ] [ 2, 7, 8, 9, 10 ] [ 3, 4, 5, 6, 7 ] [ 3, 4, 6, 7, 8 ] [ 3, 4, 7, 8, 9 ] [ 3, 4, 8, 9, 10 ] [ 3, 5, 6, 7, 8 ] [ 3, 5, 7, 8, 9 ] [ 3, 5, 8, 9, 10 ] [ 3, 6, 7, 8, 9 ] [ 3, 6, 8, 9, 10 ] [ 3, 7, 8, 9, 10 ] [ 4, 5, 6, 7, 8 ] [ 4, 5, 7, 8, 9 ] [ 4, 5, 8, 9, 10 ] [ 4, 6, 7, 8, 9 ] [ 4, 6, 8, 9, 10 ] [ 4, 7, 8, 9, 10 ] [ 5, 6, 7, 8, 9 ] [ 5, 6, 8, 9, 10 ] [ 5, 7, 8, 9, 10 ] [ 6, 7, 8, 9, 10 ] ``` ]
[Question] [ > > **Ungolfed, ugly, horrible proof to help you make progress on this challenge: <https://gist.github.com/huynhtrankhanh/dff7036a45073735305caedc891dedf2>** > > > A bracket sequence is a string that consists of the characters `(` and `)`. There are two definitions of a balanced bracket sequence. ## Definition 1 * The empty string is balanced. * If a string x is balanced, `"(" + x + ")"` is also balanced. * If x and y are two balanced strings, `x + y` is also balanced. ## Definition 2 The balance factor of a string is the difference between the number of `(` characters and the number of `)` characters. A string is balanced if its balance factor is zero and the balance factor of every prefix is nonnegative. Your task is to prove the two definitions are equivalent in the [Lean theorem prover](https://leanprover-community.github.io), specifically Lean 3. You're allowed to use the mathlib library. Formalized statement: ``` inductive bracket_t | left | right inductive balanced : list bracket_t → Prop | empty : balanced [] | wrap (initial : list bracket_t) : balanced initial → balanced ([bracket_t.left] ++ initial ++ [bracket_t.right]) | append (initial1 initial2 : list bracket_t) : balanced initial1 → balanced initial2 → balanced (initial1 ++ initial2) def balance_factor : ∀ length : ℕ, ∀ string : list bracket_t, ℤ | 0 _ := 0 | _ [] := 0 | (n + 1) (bracket_t.left::rest) := 1 + balance_factor n rest | (n + 1) (bracket_t.right::rest) := -1 + balance_factor n rest def balance_factor_predicate (string : list bracket_t) := balance_factor string.length string = 0 ∧ ∀ n : ℕ, n < string.length → 0 ≤ balance_factor n string lemma X (string : list bracket_t) : balanced string ↔ balance_factor_predicate string := begin -- your proof here sorry, end ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins. **How to solve this challenge:** * The `balanced string -> balance_factor_predicate` part can be solved relatively easily by "running at it"—do induction on the `balanced string` predicate, keep your head, and you are done. * The `balance_factor_predicate -> balanced string` part is slightly harder. I used well founded recursion to prove this part. I cleverly mimicked each constructor of the `balanced` predicate and stitched the constructors together with well founded recursion. Read the complete proof for more details. Remember to ping me in chat (The Nineteenth Byte or The Lean-to) if you need help. Thanks. ]
[Question] [ ## Background [Hamiltonian circuit problem](https://en.wikipedia.org/wiki/Hamiltonian_path_problem) is a decision problem which asks whether a given graph has a Hamiltonian circuit, i.e. a cycle that visits every vertex exactly once. This problem is one of the well-known NP-complete problems. It is also known that it remains so [when restricted to grid graphs](https://www.researchgate.net/publication/220616693_Hamilton_Paths_in_Grid_Graphs). Here, a grid graph is a graph defined by a set of vertices placed on 2D integer coordinates, where two vertices are connected by an edge if and only if they have Euclidean distance of 1. For example, the following are an example of a grid graph and an example of a graph that is *not* a grid graph (if two vertices with distance 1 are not connected, it is not a grid graph): ``` Grid graph Not +-+ +-+ | | | +-+-+-+ +-+-+-+ | | | | | +-+-+ +-+-+ ``` NP-complete problems are reducible to each other, in the sense that an instance of problem A can be converted to that of problem B in polynomial time, preserving the answer (true or false). ## Challenge Given a general undirected graph as input, convert it to a grid graph that has the same answer to the Hamiltonian circuit problem **in polynomial time**. Note that you cannot solve the problem on the input directly, unless P=NP is proven to be true. A graph can be input and output in any reasonable format. Additionally, a list of coordinates of the grid graph is a valid output format. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ]
[Question] [ # Morpion solitaire This is a game that I remember having learnt from my grandparents in my childhood. Initially I didn't know the name. G B has found it to be Join Five (or less ambiguously - Morpion solitaire) with a slightly different starting position. NOTE: it seems that it's kinda known and this problem formulation has quite good solutions already (<http://www.morpionsolitaire.com/English/RecordsGrids5T.htm>). I don't know what to do with this thread now honestly. # Description The game is played by a single player on a 2-dimensional infinite grid. The grid at the start contains some dots in a cross shape: [![enter image description here](https://i.stack.imgur.com/5zSnw.png)](https://i.stack.imgur.com/5zSnw.png) A player can create either a horizontal, vertical, or a diagonal (or anti-diagonal) line with the following rules: * The line must be straight and aligned on the grid. * The line must span exactly 5 grid points (2 on the ends, 3 in the middle). * All 5 grid points that the line intersects must have dots on them. * The new line cannot overlap with an already existing line. But they can intersect and the ends can touch. (ie. intersection of any two lines must not be a line) * A single dot may be put by the player at any grid point before the line is placed. If the player does so then the line must pass through that point. A move can be described by a grid point position (cartesian coordinates) and a direction (a number between 0 and 7. 0 - north, 1 - north east, 2 - east, and so on). So 3 numbers. The origin choice is arbitrary, but I suggest using this coordinate system: (An example of sample input at the end) [![enter image description here](https://i.stack.imgur.com/8GimZ.png)](https://i.stack.imgur.com/8GimZ.png) At the start there is 28 possible moves (12 horizontal, 12 vertical, 2 diagonal, 2 antidiagonal). An example move: [![enter image description here](https://i.stack.imgur.com/fz3WW.png)](https://i.stack.imgur.com/fz3WW.png) An example state after 16 moves: [![enter image description here](https://i.stack.imgur.com/AuMNS.png)](https://i.stack.imgur.com/AuMNS.png) I don't know whether there exists an infinite sequence of valid moves from the start position, but I assume not based on a lot of playing and simulations. Any proofs regarding upper bounds are appreciated. # Challenge The challenge is to find the longest possible sequence of valid moves (for a verifier look at the end). The score is the number of moves in that sequence. Higher score is better. # Tips, help, and resources A 24x24 board was enough for my random simulations, 32x32 board may be enough for anything possible. I faintly remember getting scores close to 100 by hand years ago. After billions of random playouts (move uniformly chosen) the best result was 100 consecutive moves: ``` 1 -1 2 1 2 2 1 6 0 -3 5 2 -2 5 0 -5 1 3 -2 -4 2 1 3 1 -5 -1 2 -5 0 1 -5 2 0 0 5 1 -2 0 0 1 -2 3 3 2 0 1 -1 0 -5 2 2 -5 -2 3 -3 3 0 4 3 0 -3 2 3 0 -4 3 -2 0 1 -3 -1 1 -3 -2 2 -1 -3 3 2 2 0 -3 0 1 1 2 1 1 -2 2 1 -5 3 -2 -3 2 1 -4 3 -1 0 0 -3 -2 3 5 2 0 -3 2 1 2 1 2 0 -1 0 0 -1 3 0 0 2 0 1 1 -4 0 2 -6 -2 3 -2 2 1 -2 1 2 0 2 1 -1 5 0 -4 6 1 -3 -3 3 -4 -2 3 -4 2 0 -6 1 2 0 3 0 -7 -2 2 -6 0 1 0 3 2 -7 -2 3 -4 3 2 -6 2 0 -6 1 3 -3 4 2 -3 6 1 1 5 1 -2 2 3 -3 7 0 2 6 0 -1 2 3 -7 3 1 2 5 1 3 6 0 -4 5 1 -3 7 1 -4 6 0 -6 2 3 -6 4 1 -7 3 3 -6 6 1 0 2 3 -6 6 2 -5 6 0 -7 4 2 1 6 2 -7 4 1 -8 3 2 -6 3 3 -6 6 0 -9 2 3 -7 5 2 -7 6 1 -7 6 0 1 2 3 -9 2 2 -9 4 1 1 5 2 1 1 3 4 7 0 1 4 2 5 6 0 1 7 1 Num moves: 100 Board: o o |/|\ o-o-o-o-o /|/|/|X|X \ o o-o-o-o-o o o / X|/|X|/|\ \ X o-o-o-o-o-o-o-o-o-o-o-o-o \|\|X|X X|X|/|X|X|X|X X| o o-o-o-o-o o o-o-o-o-o |X|X|X|X|X|X|X X|X|X|X| o o o-o-o-o-o-o-o-o-o o |/|X|X|X X X|X X|X|X| | o-o-o-o-o-o-o-o-o-o-o-o-o /|X|X|X|X|X|X|X X|X|/|X|/ o-o-o-o-o-o-o-o-o o o-o-o-o-o \ /|/|X|X|X|X|X|X|X|X|X|X|/| o-o-o-o-o-o-o-o-o-o-o-o-o o / \|X|X|X|X|X|X|X X|X|X|X|/| o o-o-o-o-o-o-o-o-o-o-o-o-o |\|X|X|X|X|X|X X|X|X|X|\| o-o-o-o-o-o-o-o-o-o-o-o-o |/|X|\|X|X / \|\|X|\|\| o o-o-o-o-o o-o-o-o-o \|X / | o o o o ``` Can you beat that? C++17 helpful codes (hosted, because they don't fit in an answer, each on godbolt and coliru, you can use them however you like).: clean, reference code, handles board, move generation, random playouts: <http://coliru.stacked-crooked.com/a/1de13a65522db030> <https://godbolt.org/z/zrpfyU> optimized and parallelized version of the above (also prints move sequences), also with a verifier that takes moves from stdin: <http://coliru.stacked-crooked.com/a/b991b7c14aaf385e> <https://godbolt.org/z/vFwHUe> edit. an even more optimized version, about twice as fast: <https://godbolt.org/z/_BteMk> place where you can put input to be verified: <https://godbolt.org/z/DJtZBc> example input: ``` 10 # number of moves -6 2 2 # x, y, direction (0-7) 1 6 0 0 2 2 1 -1 0 1 -1 2 -5 1 3 4 2 0 -5 2 0 -3 -1 1 -2 5 2 ``` ]
[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/164964/edit). Closed 5 years ago. [Improve this question](/posts/164964/edit) *Asked on Stack Overflow, but they suggested to move it here* A while ago I was reading about quines. It made me wonder if it possible to write a macro in C which will print itself, without writing any function such as main. every piece of code should be only in macro. After a few attempts, I couldn't find the solution. While searching the web for answer, I found the following code: ``` #define Q(x) #x;x char *q=Q(main(){printf("#define Q(x) #x;x\nchar *q=Q(");printf(q);printf(")\n");}) ``` Although part of the code isn't in the #define (isn't macro). Is it possible to implement a macro which will print the program ( quine type program )? **EDIT**: if it isn't possible (because the macros are 'made' in the preprocessor step), is it possible to implement a quine which is mostly in macros? ]
[Question] [ Write a program that outputs ``` Do not repeat yourself! ``` Your program code must respect the following constraints : * its length must be an even number * each character that is in position `2n` (where `n` is an integer > 0) must be equal to the character in position `2n-1`. The second character of the program is equal to the first, the fourth is equal to the third, etc. Newlines count as characters! This is code-golf, so the shortest code wins! ## Examples `HHeellllooWWoorrlldd` is a valid program `123` or `AAABBB` or `HHeello` are incorrect ## Verification You can use [this CJam script](http://cjam.aditsu.net/#code=q2%2F%7B)-%7D%2F%5Ds%22not%20%22*%22valid%22) to verify that your source code is valid. Simply paste your code into the "Input" box and run the script. [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), ~~166~~ ~~126~~ 124 bytes ``` \\;;;;33rr''22DD..));;;;;;oo;;}}eeoo\\@@nn;;;;ee;;;;aass&&;;uuoo;;;;..\\\\;;ttee..pp;;tt;;;;..rr;;''ll..'';;;;..;;}}ff..}}yy ``` Inserting the implicit no-ops and whitespace, this corresponds to the following source code: ``` \ \ ; ; ; ; 3 3 r r ' ' 2 2 D D . . ) ) ; ; ; ; ; ; o o ; ; } } e e o o \ \ @ @ n n ; ; ; ; e e ; ; ; ; a a s s & & ; ; u u o o ; ; ; ; . . \ \ \ \ ; ; t t e e . . p p ; ; t t ; ; ; ; . . r r ; ; ' ' l l . . ' ' ; ; ; ; . . ; ; } } f f . . } } y y . . . ``` I'm sure it's possible to shorten this even more, and maybe even solve it in side-length 6, but it's getting tricky... ## How it works [![enter image description here](https://i.stack.imgur.com/ZwOwF.png)](https://i.stack.imgur.com/ZwOwF.png) Diagram generated with [Timwi's Hexagony Colorer](https://github.com/Timwi/HexagonyColorer). The code is completely linear. The `\` right at the start redirects the IP into a diagonal, such that we don't need to worry about the doubled characters at all. The coloured paths are executed in the order orange/red, blue/grey, green, purple (when there are two paths of the same colour, the left-hand path is executed first, before wrapping around to the right-hand one). If we ignore no-ops, mirrors and commands which are overridden by others, the linear code comes down to this: ``` D;o;&32;}n;o;t;';}r;e;p;e;a;t;';}y;o;u;r;s;e;l;f;');@ ``` Letters in Hexagony just set the current memory edge's value to the letter's character code. `;` prints the current memory edge as a character. We use `&` to reset the memory edge to `0` and print a space with `32;`. `}` moves to a different edge, so that we can remember the `32` for further spaces. The rest of the code just prints letters on the new edge, and occasionally moves back and forth with `';}` to print a space. At the end we move to the space edge again with `'`, increment the value to 33 with `)` and print the exclamation mark. `@` terminates the program. [Answer] # GolfScript, ~~130~~ ~~84~~ 76 bytes ``` 22..!!..00)){{DDoo nnoott rreeppeeaatt yyoouurrsseellff}}``%%>><<[[33]]++ ``` Try it online in [Web GolfScript](http://golfscript.apphb.com/?c=MjIuLiEhLi4wMCkpe3tERG9vICBubm9vdHQgIHJyZWVwcGVlYWF0dCAgeXlvb3V1cnJzc2VlbGxmZn19YGAlJT4%2BPDxbWzMzXV0rKw%3D%3D). ### How it works The GolfScript interpreter starts by placing an empty string on the stack. ``` 22 # Push 22. .. # Push two copies. !! # Negate the last copy twice. Pushes 1. .. # Push two copies. 00 # Push 0. )) # Increment twice. Pushes 2. # STACK: "" 22 22 1 1 1 2 {{DDoo nnoott rreeppeeaatt yyoouurrsseellff}} `` # Push a string representation of the string representation of the block. # This pushes "{{DDoo nnoott rreeppeeaatt yyoouurrsseellff}}" (with quotes). %% # Take every second element of that string, then every element of the result. >> # Discard the first element of the result. Repeat. << # Truncate the result to length 22. Repeat. [[ # Begin a two-dimensional array. 33 # Push 33, the character code of '!'. ]] # End the two-dimensional array. ++ # Concatenate the empty string, the 22-character string and the array [[33]]. ``` Concatenating an array with a string flattens, so the result is the desired output. [Answer] # [Unary](https://esolangs.org/wiki/Unary), ~1.86 × 10222 Simple brainfuck -> unary answer. Very sub-optimal ;). The program consists of an even number of 0’s; specifically: > > 1859184544332157890058930014286871430407663071311497107104094967305277041316183368068453689248902193437218996388375178680482526116349347828767066983174362041491257725282304432256118059236484741485455046352611468332836658716 > > > of them. Original brainfuck code: ``` ++++[++++>---<]>+.[--->+<]>+++.[--->+<]>-----.+[----->+<]>+.+.+++++.[---->+<]>+++.---[----->++<]>.-------------.+++++++++++.-----------.----.--[--->+<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.---.+.++++[->+++<]>.+++++++.------.[--->+<]>-. ``` [Answer] # Ruby - 2100 1428 1032 820 670 bytes This assumes the output can be a return value from a function (it wasn't specified that the output needs to be to STDOUT) Code: ``` ((((((((((((((((((((((((((((((((((((((((((((((""<<66++11**00++11**00))<<99++11++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11))<<99++11++11**00))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11++((11**00<<11**00<<11**00))))<<99++11**00++11**00))<<99++11++11**00++11**00))<<99++11**00++11**00))<<88++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++22))<<99++11++11**00))<<99++((33>>11**00))++11**00++11**00))<<99++11++((11**00<<11**00<<11**00))))<<99++((33>>11**00))))<<99++11**00++11**00))<<99++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++11**00++11**00++11**00))<<33)) ``` The trick is to build the string from an empty string `""` using the append operation `<<` and the ASCII codes of the characters. To get the numbers for the ASCII codes I'm trying to decompose the number into values I can easily generate. For example ASCII `90` is just `88+1+1`, which is: * `88` is okay on it's own * `11**00` is `11^0`, which is simply `1` Fortunately both `++` and `--` would mean `add` in ruby, so I can write `90` as `88++11**00++11**00` There are some tricks to get to some numbers easier than just adding 1s, here is the code I'm using to generate the above (which includes all mappings I'm using): ``` d = "Do not repeat yourself!" d.each_char do |c| print "((" end print '""' VALUES = [ [0,'00'], [1,'11**00'], [4,'((11**00<<11**00<<11**00))'], [5,'((11>>11**00))'], [11,'11'], [16,'((33>>11**00))'], [22,'22'], [27,'((55>>11**00))'], [33,'33'], [38,'((77>>11**00))'], [44,'44'], [49,'((99>>11**00))'], [55,'55'], [66,'66'], [77,'77'], [88,'88'], [99,'99'] ].reverse d.each_char do |c| print "<<" num = c.ord while num != 0 convert = VALUES.find{|val|val.first<=num} print convert.last num -= convert.first print "++" unless num == 0 end print "))" end ``` I'm still thinking about other tricks to decrease the characters required to get to a number. Note that if you use the `-rpp` flag, and add `pp` to the start of the code like so: ``` pp((((((((((((((((((((((((((((((((((((((((((((((""<<66++11**00++11**00))<<99++11++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11))<<99++11++11**00))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11++((11**00<<11**00<<11**00))))<<99++11**00++11**00))<<99++11++11**00++11**00))<<99++11**00++11**00))<<88++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++22))<<99++11++11**00))<<99++((33>>11**00))++11**00++11**00))<<99++11++((11**00<<11**00<<11**00))))<<99++((33>>11**00))))<<99++11**00++11**00))<<99++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++11**00++11**00++11**00))<<33)) ``` then for extra 2+4 bytes this can function as a fully complete program, but it will print an extra `"` before and after the required string: Example: ``` $ ruby -rpp golf.rb "Do not repeat yourself!" ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 174 bytes ``` vv 77 99 ** 00 77 bb ** pp "" !! ff ll ee ss rr uu oo yy tt aa ee pp ee rr tt oo nn oo DD "" ~~ oo ll 11 == ;; 00 66 bb ** .. ``` Thankfully, in a sense the restriction doesn't apply vertically. However, the biggest problem is that we need to double every newline. The code that runs roughly goes like this: ``` v Redirect instruction pointer to move downwards 79*07b*p Place a ? on row 77 before the first ; "..." Push "Do not repeat yourself!" backwards, riffled between spaces [main loop] ~o Pop a space and output a char l1=?; If there is only the final space left, halt 06b*. Jump back to the start of the loop ``` Note that the program has no double spaces — when in string mode, ><> pushes spaces for empty cells. Conversely, however, this means that a solution using `g` (read single cell from source code) would be trickier, since what spaces are in the program become NULs when read. (Note: This can be 50 bytes shorter if it [terminates with an error](http://pastebin.com/UzLESVzm), but I like it this way.) [Answer] # [Sclipting](http://esolangs.org/wiki/Sclipting), ~~186~~ 146 bytes > > 끄끄닶닶긂긂닦닦닶닶덇덇긂긂댧댧뉖뉖댇댇뉖뉖눖눖덇덇긂긂뎗뎗닶닶덗덗댧댧댷댷뉖뉖닆닆뉦뉦긒긒 > > > 껢껢鎵鎵❶❶合合虛虛替替標標現現併併一一終終 > > > To be clear, there are three lines of code, the middle of which is empty, because the newline needs to be duplicated. The byte count is based on UTF-16 encoding. # Explanation The block of Korean characters at the start pushes the string `"DDDof� \"\u0002nf�of�twG \"\u0002rw'efVpw\aefVaf\u0016twG \"\u0002yw�of�uwWrw'sw7efVlf�fff!\"\u0012"`. You will notice that every *third* character is a character we want; the rest is gibberish. Here’s why: In Sclipting, two Korean characters encode three bytes. Thus, each Korean character effectively encodes 12 bits. To get a string starting with `D`, the first 8 bits have to be `0x44`; the rest don’t matter, but since we have to repeat every character, the 12th to 20th bits are also going to be `0x44`. Thus, we will have a value of the form `0x44n44n` for some *n*, which decomposes into the three bytes `0x44 0xn4 0x4n`. For the `o`, which is `0x6F`, we get the bytes `0x6F 0xn6 0xFn`. Since I’m lazy, I started by encoding `"DDDooo nnnooottt (etc.)"` and then replaced every other character with the previous, which is why I get `0x444444` = `"DDD"` for the `D` and `0x6F66F6` = `"of�"` for the `o`. The `�` is there because `0xF6` by itself is invalid UTF-8 encoding. Now, back to the program. The rest of the program proceeds as follows: > > 껢껢 — pushes the string `".\"�"` > > > 鎵鎵 — removes the last character twice, leaving us with `"."` > > > ❶❶ — two duplicates. Stack now: `[".", ".", "."]` > > > 合合 — concatenate twice. Stack now: `["..."]` > > > Now, what I *want* to do next is use `"..."` as a regular expression so that I can match three characters from the original string at a time, using the 替...終 loop construct. However, since every instruction is duplicated, I need to have *two* such regular-expression loops nested inside each other, and if the stack underruns I get a runtime error. Therefore, > > 虛虛 — push the empty string twice > > > and *then* start the loops. This way, the outer loop iterates only once because it matches the regular expression `""` against the string `""`, which yields a single match. The inner loop runs once for every match of `"..."` against the big string. The body of the loop is: > > 標標 — push two marks onto the stack. Stack now: `[mark mark]` > > > 現現 — push two copies of the current regex match. Stack now: `[mark mark "DDD" "DDD"]` > > > 併併 — concatenate up to the first mark. Stack now: `["DDDDDD"]` > > > 一一 — take first character of that string, and then (redundantly) the first character of that. Stack now has the character we want. > > > The inner loop ends here, so every match of the regular expression is replaced with the first character of that match. This leaves the desired string on the stack. Then the outer loop ends, at which point the desired string is taken off the stack and the only match of `""` in the string `""` is replaced with it, leaving the desired string once again on the stack. [Answer] # [Labyrinth](http://esolangs.org/wiki/Labyrinth), 528 bytes ``` 66))__vv ..33::00&&__vv ..44__99||__vv ..33::00&&__vv ..99))__vv ..99))__vv ..44__88$$__vv ..22__99++__vv ..22__99$$__vv ..22__99))$$__vv ..33__77$$__vv ..33__vv ..44__99||__^^ ..11__99++__^^ ..44__88$$__^^ ..44((__88$$__^^ ..11))__99++__^^ ..99((__^^ ..33::00&&__^^ ..44__99||__^^ ..44((__88$$__^^ ..99))__^^ ..11__99$$((__^^ ..@@ xx ``` The double newlines hurt, but at least this proves that it's doable! Each character is printed one-by-one, first by forming the code point then printing a single char. The code points are formed by: ``` D 68 66)) o 111 44__99|| 32 33::00&& n 110 11__99++ t 116 44__88$$ r 114 44((__88$$ e 101 99)) p 112 11))__99++ a 97 99(( y 121 22__99++ u 117 22__99$$ s 115 22__99))$$ l 108 33__77$$ f 102 11__99$$(( ! 33 33 ``` where ``` )( Increment/decrement by 1 respectively &|$ Bitwise AND/OR/XOR respectively + Add : Duplicate _ Push zero 0-9 Pop n and push n*10+<digit> ``` The unusual behaviour of Labyrinth's digits is exploited in `33::00&&`, which is actually ``` [33] -> [33 33] -> [33 33 33] -> [33 33 330] -> [33 33 3300] -> [33 32] -> [32] : : 0 0 & & ``` Each single char is printed with the mechanism ``` __vv .. xx ``` The `xx` exist only to pad the grid so that it's 5 high. First the `__` push two zeroes, then we hit a grid rotation operator `v`. We pop a zero and rotate: ``` __ v v . . xx ``` and again: ``` __ v v. xx. ``` We then move rightwards to the `.` on the third row, thus executing the print command only once. [Answer] # CJam - 176 136 bytes ``` 66))HH77++GG00++BB88++HH77++EE88++GG00++DD88++99))CC88++99))AA77++EE88++GG00++BB99++HH77++KK77++DD88++JJ77++99))AA88++II66++33]]{{cc}}// ``` *Thanks to Sp3000 for dividing my program size by two :-)* **Explanation** * The codes `HH77++`, `GG00++`, ... compute the integer ascii code of the characters by adding numbers (for example: `HH77++' pushes 17, 17 and 77 on the stack, then add these 3 numbers) * the portion of code at the end `]]{{cc}}//` loops through the ascii codes and convert them to characters. Try it [here](http://cjam.aditsu.net/#code=66))HH77%2B%2BGG00%2B%2BBB88%2B%2BHH77%2B%2BEE88%2B%2BGG00%2B%2BDD88%2B%2B99))CC88%2B%2B99))AA77%2B%2BEE88%2B%2BGG00%2B%2BBB99%2B%2BHH77%2B%2BKK77%2B%2BDD88%2B%2BJJ77%2B%2B99))AA88%2B%2BII66%2B%2B33%5D%5D%7B%7Bcc%7D%7D%2F%2F) [Answer] # [Self-modifying Brainf\*\*\*](http://esolangs.org/wiki/Self-modifying_Brainfuck), 72 bytes Note that `\x00` represents a literal `NUL` hex byte (empty cell). The source code is placed on the tape, left of the starting cell. ``` !!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD\0\0<<<<<<++[[<<]]<<[[..<<]] ``` ### Explanation ``` !!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD The string on the tape for easy printing \x00\x00 A separator to make printing shorter <<<<<<++ Change first '.' to '0' (comment) [[<<]]<< Move to separator, then left to string [[0.<<]] Print string ``` Also, before making this program, I was making one using only BF characters in the source. It's possible! It's also much longer, since for an odd ASCII value, I was going to create double the value, then divide by two. Somewhat shorter would be modifying the entire source to generate odd values to start with. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 66 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ““DDoo nn““oott rreepp““eeaatt yyoouurrss““eellff!!””ṛṛḷḷWWQQ€€ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4oCcRERvbyAgbm7igJzigJxvb3R0ICBycmVlcHDigJzigJxlZWFhdHQgIHl5b291dXJyc3PigJzigJxlZWxsZmYhIeKAneKAneG5m-G5m-G4t-G4t1dXUVHigqzigqw&input=) ### Factoid The program still works if you remove every second character. [Try it online!](http://jelly.tryitonline.net/#code=4oCcRG8gbuKAnG90IHJlcOKAnGVhdCB5b3Vyc-KAnGVsZiHigJ3huZvhuLdXUeKCrA&input=) ### How it works ``` ““DDoo nn““oott rreepp““eeaatt yyoouurrss““eellff!!” ``` returns an array of string. The literal begins with a `“`, ends with a `”`, and the strings are delimited internally by `“`. The result is ``` ["", "DDoo nn", "", "oott rreepp", "", "eeaatt yyoouurrss", "", "eellff!!"] ``` The link's argument and the return value are set to this array of strings, then the remainder of the source code is executed. ``` <literal>”ṛṛḷḷWWQQ€€ Argument/return value: A (string array) ”ṛ Yield the character 'ṛ'. ṛ Select the right argument of 'ṛ' and A: A. ḷ Select the left argument of A and A: A. W Wrap; yield [A]. ḷ Select the left argument of A and [A]: A. W Wrap; yield [A]. Q Unique; deduplicate [A]. Yields [A]. Q€€ Unique each each; for each string s in A, deduplicate s. ``` [Answer] # [Gammaplex](http://esolangs.org/wiki/Gammaplex), 66 bytes ``` \\ XX""!!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD""XXXXrrRREE ``` Gammaplex is a 2D language that uses the position of the first newline as the line length, and ignore all other newlines. [Answer] # [MSM](http://esolangs.org/wiki/MSM), ~~270~~ 160 bytes ``` !!'',,ff'',,ll'',,ee'',,ss'',,rr'',,uu'',,oo'',,yy'',, '',,tt'',,aa'',,ee'',,pp'',,ee'',,rr'',, '',,tt'',,oo'',,nn'',, '',,oo'',,DD'',,...................... ``` My first MSM program! String output in MSM is done by pushing the individual characters onto the stack and joining them into a single string via `.`, e.g. ``` !olleH..... ``` The number of `.` is one less than the number of characters. For `Do not repeat yourself!` we need 22 `.`s. Luckily this is an even number, so we have 11 doubles ``` ...................... ``` Putting the letters in front of it requires some more effort. The pattern ``` cc'',, ``` does the trick for each character `c`. It evaluates as follows ``` cc'',, push c (remember: commands are taken from the left and operate on the right) c'',,c push c '',,cc quote ' and push ,,cc' pop ,cc pop c voilà! ``` We need 23 such patterns starting with `!!'',,` and ending with `DD'',,` followed by the 22 join commands `.`. [Answer] # Befunge 98, 70 66 bytes [Try it online!](https://tio.run/nexus/befunge-98#@29kZGCgpVVRoaSkqJiWlpOTmlpcXFRUWpqfX1mpoFBSkpiYmlpQkJpaVATi5efn5Sko5Oe7uIiLKyllZ@voODj8/w8A) After my invalid answer, here's a better one that actually fits the challenge! ``` 2200**xx""!!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD��""kk,,@@ ``` (Thanks to Martin Ender for suggesting the use of `��`, character 0x17, instead of `88ff++`) Explanation: ``` 2200 Push 2, 2, 0, and 0 onto the stack * Multiply 0 and 0, yielding 0 * Multiply 2 and 0, yielding 0 The stack is now [2, 0] x Pop a vector off the stack and set the instruction pointer delta to that The instruction pointer is now skipping over every other character, since the delta is (2, 0) "!f ... oD�" Push the string onto the stack, with the number 23 (number of characters in the string) at the top k, Pop characters off the stack and print them, 23 times @ End the program ``` [Answer] # [Backhand](https://github.com/GuyJoKing/Backhand), 54 bytes ``` vv""!!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD""HH ``` [Try it online!](https://tio.run/##FcdLCsAgDAXAq8ScxYXXSG2kUPFJ/ICnT@ns5pL8PtJu972ZQyilVtUxzNYCziGaU0S1d1Wzf0BrRECMzCm5fw "Backhand – Try It Online") Since Backhand's pointer already moving at three cells a tick, all we need to do is decrease that to 2 using `v` [Answer] # [DC](https://rosettacode.org/wiki/Dc), ~~348~~ ~~346~~ ~~342~~ ~~306~~ ~~290~~ 278 bytes File `dnr6.short.dc` (without trailing newline): ``` AAzz--22222222vvPPAAAAAAAAvvPP88vvFFFFFFFFvv00++AAzz--PP11vvFFFFFFFFvv00++AAAAAAvvPP11vvEEEEEEEEvv00++OOOO//44999999vv++PP77II++OOOO//44999999vv++PPAAAAAAvv88vvFFFFFFFFvv00++PPAAzz--BBPP11vvFFFFFFFFvv00++77OOOO++++PPOOOO//44999999vv++66vvFFFFFFFFvv00++PP99zz++OO88++PPAAAAvv33PP ``` Run: ``` $ dc < dnr6.short.dc Do not repeat yourself! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~100~~ ~~58~~ 52 bytes *-6 bytes thanks to Kevin Cruijssen* ``` „„€€··™™……€€–– ……¹¹‚‚ ……––‚‚))εε##θθáá}}»»……!!θθJJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcM8EGpaA0SHth/a/qhlEQg1LAMhsOijhslApKAAETu089DORw2zgAgmApGHiGlqntt6bquy8rkd53YcXnh4YW3tod2HdkPUKSqCRL28/v8HAA "05AB1E – Try It Online") ``` „„€€· # dictionary string "g do" · # double (no effect on strings) ™ # title case: "G Do" ™ # title case again (no effect) ……€€–– # dictionary string "tools not–" # spaces necessary so "–…" isn't parsed as a dictionary word ……¹¹‚‚ # dictionary string "team repeat‚" # spaces necessary again ……––‚‚ # dictionary string "j yourself‚" ) # wrap the entire stack in an array ) # and again: [["G Do", "tools not–", "team repeat‚", "j yourself‚"]] ε } # for each: ε } # for each: # # split on spaces: ["tools", "not–"] # # and again: [["tools", "not–"]] θ # get the last element: ["tools", "not–"] θ # and again: "not–" á # keep only letters: "not" á # and again (no effect) » # join the list by newlines, joining sublists by spaces: # "Do not repeat yourself" » # join the stack by newlines, joining lists by spaces (no effect) ……!! # literal string "…!!" θ # get the last character: "!" θ # and again (no effect) J # join the stack without separators: "Do not repeat yourself!" J # and again (no effect) # implicit output ``` Idempotency rules. [Answer] # [BotEngine](https://github.com/SuperJedi224/Bot-Engine), 6x49=294 ``` vv PP !!ee ffee llee eeee ssee rree uuee ooee yyee ee ttee aaee eeee ppee eeee rree ee ttee ooee nnee ee ooee DDee >> ^^ ``` [Answer] # reticular, noncompeting, 62 bytes ``` 2200**UU""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!""oo;; ``` [Try it online!](http://reticular.tryitonline.net/#code=MjIwMCoqVVUiIkREb28gIG5ub290dCAgcnJlZXBwZWVhYXR0ICB5eW9vdXVycnNzZWVsbGZmISEiIm9vOzs&input=&args=) Explanation in parts: ``` 2200** 2200 the stack looks like [2 2 0 0] * [2 2 0*0] * [2 2*0*0] [2 0] ``` `U` sets the pointer direction to `(2, 0)`, that is, moving `2` x-units and `0` y-units, so it skips every other character, starting with the next `U` being skipped. Then, every other character is recorded, and it is equivalent to: ``` "Do not repeat yourself!"o; ``` which is a simple output program. ## Other This is competing for WallyWest's JavaScript bounty: I can prove that, while numbers can be constructed under this restriction, strings cannot. Since no literals can be used, as the placement of any literal-building character would create an empty string: ``` "" '' `` ``` Then, only some operator can be used; the only "paired" operators used are: ``` ++ -- << >> ** ~~ || && !! == ``` And none of these can cast numbers/others to strings. So no strings can be outputted. [Answer] ## [Alice](https://github.com/m-ender/alice), 74 bytes ``` aa00tt,,JJ""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!//@@""ooYY;;tt ``` [Try it online!](https://tio.run/nexus/alice#FccxDkARDADQ3Smqs4TdYjC5gdFQk6hUDU7v57/tvdZCUHWuFMScmQHmZFYFECFai6i1f/cynyOyN9EYvVvrfUqIzLXGqGrMex8 "Alice – TIO Nexus") ### Explanation The first catch is that we need to be able to enter the string, so we want to skip only the first `"`. We do this by jumping onto the first `"` because then the IP will move one cell before looking at the current cell again, so that it's the second `"` which enters string mode. But to be able to jump there, we need `10, 0` on top of the stack, in that order (second, top). This is done with `aa00tt,,`: ``` Stack: aa Push two 10s. [... 10 10] 00 Push two 0s. [... 10 10 0 0] tt Decrement twice. [... 10 10 0 -2] , Rotate(-2). [... 0 10 10] , Rotate(10). [... 0 10 0] ``` This rotation function pops an argument. If that argument is negative, it pushes the value on top of the stack down by that many positions. If the argument is positive, it goes looking for the element that many positions below the top and pulls it up to the top. Note that in the case of `Rotate(10)`, there aren't enough elements on the stack, but there is an implicit infinite amount of zeros at the bottom, which is why a zero ends up on top. Now we can `J`ump onto the first `"` using these two arguments. The second `"` enters string mode and records all of that `DDoo nnoott...`. When it hits the `/`, the IP is redirected southeast and we enter Ordinal mode. For now on the IP bounces up and down across the three lines (two of which are empty), so it first records three more spaces on lines two and three and then we leave string mode when it hits the `"`. Since we're in Ordinal mode at this time, all the recorded characters are pushed as a single string to the stack (even though we recorded most of them in Cardinal mode), so we end up with this string (note the trailing spaces): ``` DDoo nnoott rreeppeeaatt yyoouurrsseellff!! ``` Now the IP keeps bouncing up and down which means that it executes one command of every other pair, i.e. `Y` and `t`. Then the IP will hit the end of the grid on the second line and start bouncing backwards through the grid. This also switches in which pair of characters the IP hits the first line, so when going back it now executes `;`, `o` and `@`. So ignoring all the spaces and implicit IP redirections, the executed code is `Yt;o@` in Ordinal mode. The `Y` is the "unzip" command which separates a string into the characters in alternating positions. Since each character is repeated, that really just gives us two copies of the string we're going for, although the first copy has two trailing spaces and the second has one trailing space. `t` splits off that trailing space and `;` discards it. Finally, `o` prints the string and `@` terminates the program. [Answer] # [Stax](https://github.com/tomtheisen/stax), 70 bytes ``` GG11hh::zzaapp..}}..""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!"" ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#c=GG11hh%3A%3Azzaapp..%7D%7D..%22%22DDoo++nnoott++rreeppeeaatt++yyoouurrsseellff%21%21%22%22&i=&a=1) Stax very fortunately has the builtin `::` for every-nth. All I need to is push the string doubled, push 2, and run `::`. Easy, right? Wrong. Pushing that string is tricky. The first quotation mark can be doubled by `..""`, which is a length-2 literal for `."` followed by a meaningful quotation mark. Problem is, I see no way to terminate the string (which is necessary, or else the doubled version will be printed) without starting a new one. The end of the program terminates string literals. If I can put this doubled literal there, perhaps there'll be a nice workaround. To jump somewhere from the end of a program, however, requires `G}`, so at minimum, I'm looking at this: ``` GG [deduplicate] }}""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!"" ``` This does... nothing. `G` does not begin a block, so neither will jump to the second `}`. Again, I need to ignore one character: `..}}`. Execution jumps from the first `G` to the second `}`, continues to the end, jumps back to the second `G` and from there to the second `}`, and continues once more to the end before resuming at the start of the `[deduplicate]` section with the doubled string atop the stack. Deduplication is simple. `11hh` pushed eleven and halves it twice, rounding down both times and yielding two, and `::` will then get us the output we need. ``` GG11hh::..}}..""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!"" ``` Uh-oh. This prints nothing. There are two problems here: first, that `..}` means the string `.}` will be atop the stack at the end of the program, and second, Stax's ordinary implicit output is now disabled! The worse issue is the output. When a Stax program terminates gracefully without printing anything, the top of the stack will be implicitly printed. But we haven't printed anything...? Ah, but we have. Unterminated string literals are printed rather than pushed, and even those two empty strings (from the unmatched `"` at the end), despite being empty, are enough to trip this check. Any printing must be done by hand. We'll need either `pp` or `PP`, and in this instance, ignoring the first through `..pp` is unacceptable, as it will print the string `.p`. That means we need our desired output either alone on the stack or in the top two along with an empty string. This latter is accomplished by pushing two empty strings (`zz`) and rotating the top three items twice (`aa`) before printing. Once that's done, we have a stack four strings tall. A fifth, `.}`, is then pushed before the program exits gracefully; at this point, the lack of implicit output becomes a blessing as well as a curse, as nothing extra will now be printed! ]
[Question] [ Program your robots to deliver packages in a warehouse infested with destroyer drones. Avoid the drones and get your packages to the right place as fast as you can. ## Delivery Robots * There are packages labeled a-z in a warehouse. * Packages must be delivered to a matching chute A-Z. * A robot cannot move to a square that contains a wall or another robot. * A robot passing over a package will pick it up if it is not holding a package. * A robot landing on a chute will drop their package if the package label matches the chute. ## Destroyer Drones * Drones each start with a random heading. * If there is a clear line of sight to robots (NSEW), the drone will move toward the closest visible robot. * If in a dead end or blocked by another drone, the drone will reverse direction. * If at an intersection, a drone will choose a random direction (but not backtrack). * Otherwise, a drone will move on its current heading. * If a robot is ever in one of the four adjacent squares next to a destroyer drone, that robot is destroyed and disappears. If the robot had a package, it is dropped, replacing any package or chute already there. * Drones pass over packages. ## Warehouse Arena ``` ################################################# #B # # # ff # ############ ##### ######### # # # # ########## # ##### ### efg* ## # # # C# # # # ## ############ ############ # # ###### ## ## ########## ##### # # de # ## ## ################## ##### ## # ## # ###### # ## ## # ### ### ## # ## # # # ######## ########### ######### ## # # # # ###### # A # ## ## # # # ## ###### #### ## ####### ########### # aeb # # # ##G ### ## # ## ####### # # ## ###### ### ### ####### ## ######## # # ######### ### ### * ## # ######### # cfe ## ### ####### ###### ######## ## # ######## ## ### ### ###### #### # ######## ## ### ### ### ############### ####### # # ### ### # # # # # #D# # #$$$$ # # ###### ########## ##### # # # ###### #### ##### ### ############### ### ## # # # ## ### ##gba ### # # ## ### #### ## ## ### ############### ### ##### # ## ### # * ### # # # ###### ############## ############### ####### # # ########## ## E ## # # ############ ###abc ## ### ### ## ####### # # # ##### ####### ### ## # # # # ######## ##### ####### ### ###### ######### # # F # # # ccc # ################################################# ``` `#: wall, $: delivery robot, *: destroyer drone, a-z: package, A-Z: delivery chute` ## Game Flow Your program will be called with an arena file argument and MAXTURN integer. The program should follow the logic flow below. ``` read in arena for turn in 1..MAXTURN for each robot optionally move robot to one of four adjacent squares if chute here and has matching package remove package from robot add to score if all packages delivered add turns bonus end game if next to drone delete robot reduce score if package here and robot has no package add package to robot remove package from square for each drone decide heading using specified rules move drone if next to any robots kill those robots drop packages onto map if no robots left end game ``` ## Output Your program will output your score for that game. ## Scoring * The test arena with MAXTURN=5000 will be used for scoring. * You score 500 points for each package delivered. * You lose 900 points for each robot destroyed. * The game ends if all robots are destroyed or MAXTURN turns elapse. * If you deliver all packages, you gain a bonus point for each turn you had remaining. Your total score will be the sum of the scores of 3 *consecutive* games. Your program must not assume this test arena. An arena my be up to 200x200 squares and contain thousands of packages, chutes, robots, and droids. If I suspect any submission to be tailored towards this specific arena, I reserve the right to replace it by a new arena. Standard loopholes are prohibited as usual. ]
[Question] [ [Cops thread](https://codegolf.stackexchange.com/questions/231409/which-character-to-change-cops) Robbers, your task is to crack a cops answer. Reveal the character that should be changed and what it should be changed to too. Please notify the cop if you cracked their challenge. The robber winner is the user with the most cracks. I will declare the winner cop and robber a week after this challenge is posted. ### Example Submission ``` # Cracked [math's answer](http://example.com/17290/Change-a-character) 1[`a`|`b -> a 0[`a`|`b -> b [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=1%5B%60a%60%7C%60b&inputs=&header=&footer=) ``` ``` [Answer] # [Python 3](https://docs.python.org/3/), 53 bytes, cracks [dingledooper's 51 bytes](https://codegolf.stackexchange.com/a/231494/20260) ``` r=(1,)*8**9 r=r,len,str=r,str,sum print(len(str(r))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8hWw1BHU8tCS8uSq8i2SCcnNU/n/Zo2ELO4BIhLc7kKijLzSjSAEhpAEY0iTU3N//8B "Python 3 – Try It Online") Replaces the newline at the end of the second line with `st`. This is LATIN SMALL LIGATURE ST which is U+FB06, but Python 3 is apparently willing to interpret it as `st` in `str`. I spent some time thinking "if only I could make two letters" until I googled for "st ligature" which does just that. The second line now redefines `str` as `sum`, and `len` as `str`, so `len(str(r))` is now `str(sum(r))`, which is just the stringification of its length of `r`, which is `8**9`. Also apparently the `r=r` in the trio of assignments overrules the left `r=...`, causing `r` to retain its original value. [Answer] # [R](https://www.r-project.org/), cracks [Robin Ryder's answer](https://codegolf.stackexchange.com/a/231427/95126) ``` a=b=co2 for(a in 0:b)pi=pi+exists("c")/4 intToUtf8(pi) ``` [Try it online!](https://tio.run/##K/r/P9E2yTY534grLb9II1EhM0/BwCpJsyDTtiBTO7Uis7ikWEMpWUlT34QrM68kJD@0JM1CoyBT8/9/AA "R – Try It Online") The clue was in the `exists("c")` bit: `c` is a built-in function in [R](https://www.r-project.org/), so `exists("c")` will always be `TRUE`, even without the definition of a variable `c` on the first line. So we look for built-in variables starting with `c`... wait... there's one called `co2` - one character away from `c=2`. The first element of `co2` is 315, and 315/4 equals 78.75, which after addition of `pi` and rounding to an integer equals 82, the ACII value of `"R"`. [Answer] # Cracked [A username's Vyxal answer](https://codegolf.stackexchange.com/a/231411/58974) My complete lack of knowledge of Vyxal may have helped here as it allowed me to just try random things instead of trying to figure out what the obscure hack might be. ``` kaka(|← ``` [Try it!](https://lyxal.pythonanywhere.com?flags=&code=kaka%28%7C%E2%86%90&inputs=&header=&footer=) [Answer] # [Sisyphus, Python 2](https://codegolf.stackexchange.com/a/231461) ``` print pow(2,2**1337133713371337,195889276175237072760362530940173700767) ``` I solved this by brute forcing the change needed to the modulus and exploiting the fact that \$a^x = a^{x \bmod \lambda(n)} \pmod n\$, where \$\lambda\$ is Carmichael's lambda function. This requires factoring \$n\$. Fortunately, the modulus is relatively small; had it been larger, we'd need to factor a large semiprime just to *verify* a guess. [Answer] # [Python 2](https://docs.python.org/2/), cracks [xnor's answer](https://codegolf.stackexchange.com/a/231486/88546) ``` print 0in(0,0)>min(0,0) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwSAzT8NAx0DTLhfK@P8fAA "Python 2 – Try It Online") [Answer] # Cracked [Vyxal's lyxal answer](https://codegolf.stackexchange.com/a/231416/101522) ``` `Ẇ₁¹kḢ`«∧λf⇧\#¯ḣ⌐ƒż1 ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%E1%BA%86%E2%82%81%C2%B9k%E1%B8%A2%60%C2%AB%E2%88%A7%CE%BBf%E2%87%A7%5C%23%C2%AF%E1%B8%A3%E2%8C%90%C6%92%C5%BC1&inputs=&header=&footer=) Once I realized A) the lambda is useless because it always returns 1, and B) the target string consists only of lowercase letters and whitespace, the crack became trivial. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), cracks [A username's second answer](https://codegolf.stackexchange.com/a/231413) 5 bytes ``` lyoax ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=lyoax&inputs=&header=&footer=) [Answer] # Cracked [tsh's answer](https://codegolf.stackexchange.com/a/231554/104752) ``` a=9 if(a>0)a=0xa>9&&print(a) ``` Replacing the newline moves the `print` to occur before the assignment; choosing `x` as the replacement character creates a hexadecimal value greater than 9. [Try it Online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/z/R1pIrM00j0c5AM9HWoCLRzlJNraAoM69EI1Hz/38A) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), cracks [Adám's second answer](https://codegolf.stackexchange.com/a/231643/78410) ``` ≢∊⎕AT¨⎕A ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jzkWPOroe9U11DDm0AkSBhP8XcAGZzpHqxYk5JeqPultS8xKTclKDHX1CuGKT8isy89IV8vO4HrVNRNIIAA "APL (Dyalog Extended) – Try It Online") `⍨` is changed into `T`, making a totally different system function `⎕AT`, ["Attributes"](http://help.dyalog.com/18.0/#Language/System%20Functions/at.htm). `⎕AT` takes a name, and gives some attributes about it. The only thing that is important here is that, given an undefined name, `⎕AT` returns a row of `(0 0 0)(0 0 0 0 0 0 0)(0)('')`, which has 11 atoms in total. `⎕AT¨⎕A` calls `⎕AT` on each of the 26 uppercase alphabet, and since none is defined yet, returns 26 such rows. The total number of atoms in this array is `26×11=286`. [Answer] # Cracked [A username's Vyxal answer](https://codegolf.stackexchange.com/a/231413/58974) [Ninjaed by pxeger](https://codegolf.stackexchange.com/a/231414/58974) :\ ``` lyoax ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=lyoax&inputs=&header=&footer=) [Answer] # Cracked [DLosc's Pip answer](https://codegolf.stackexchange.com/a/231431/95671) ``` -PZ-PI ``` [Try it online!](https://tio.run/##K8gs@P9fNyBKN8Dz/38A "Pip – Try It Online") I don't know how this language works, I just looked through [the docs](https://github.com/dloscutoff/pip/blob/master/operators.py) and found a `PZ` function. [Answer] # Cracked [Daniel H.'s Rattle answer](https://codegolf.stackexchange.com/a/231429/58974) ``` d&|!p ``` [Try it!](https://rattleinterpreter.pythonanywhere.com/?flags=&code=d%26%7C!p&inputs=) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 24 bytes, [cracks A username’s answer](https://codegolf.stackexchange.com/a/231443/101522) ``` kHø`string`D‟‟Ẋf∑vd∑qĖ₁Ẏ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kH%C3%B8%60string%60D%E2%80%9F%E2%80%9F%E1%BA%8Af%E2%88%91vd%E2%88%91q%C4%96%E2%82%81%E1%BA%8E&inputs=&header=&footer=) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes, cracks [Caird’s answer](https://codegolf.stackexchange.com/a/231445/101522) ``` “Y$Ḥß““¿<ȧ» ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xIlYc7lhyeD2QB0aH9NieWH9r9/z8A "Jelly – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org) by [A username](https://codegolf.stackexchange.com/a/231448/68942), 155 bytes ``` z=247275939563830539741033318025n k='' e='Hello, world' while(z) k+=String.fromCharCode(Number(z%128n)),z/=128n; console.log(eval([...k].reverse().join``)) ``` [Try it online!](https://tio.run/##FcwxDoIwFADQnVOwmLYRK1AQiOnE4uTiaEyo8IVCaU1BSHp51O1NrxeLmGor3/NBmwa2zfE4yeIsLViRnljOwpQVWRKFjLEoD@NUewNHyAOOLqCUCfzVWNUgb@2kAuyIP@z5bbZSt/RlzVh2wpa/GF8/4xMsdrsozjUhgTvyv85ebfRkFFBlWgyLUPhOKR0e1MICdgJMaG@kripCtu0L "JavaScript (Node.js) – Try It Online") Changes `"console.log(e)"` to `"console.log;\n\t"` I mostly found this by narrowing down after which digit the `console.log` ended and then just spamming guesses until I found something syntactically valid that would `eval` to the same thing as `console.log` itself. [Answer] # [R](https://www.r-project.org/), cracks [Robin Ryder's second answer](https://codegolf.stackexchange.com/a/231466/95126) ``` a=b=2 for(a in 0xb)pi=a+a-pi el(LETTERS[pi]) ``` [Try it online!](https://tio.run/##K/r/P9E2ydaIKy2/SCNRITNPwaAiSbMg0zZRO1G3IJMrNUfDxzUkxDUoOLogM1bz/38A "R – Try It Online") `0xb` denotes hexadecimal number `b`, or eleven. So the `for` 'loop' becomes just a single pass, setting `pi` equal to `11+11-pi`, which is 18.85841. `LETTERS[pi]` rounds this to the integer 18, and selects that capital letter: the 18th letter is `"R"`. [Answer] # [R](https://www.r-project.org/), cracks [Robin Ryder's 3rd answer](https://codegolf.stackexchange.com/a/231480) ``` x=z=6 y=0 while(x+7-1>y){x=x-1;z=z+1} LETTERS[z] ``` [Try it online!](https://tio.run/##K/r/v8K2ytaMq9LWgKs8IzMnVaNC21zX0K5Ss7rCtkLX0LrKtkrbsJbLxzUkxDUoOLoq9v9/AA "R – Try It Online") Changes the first `y` in the while loop condition to a `7`. Cracked by educated manual semi-brute-force. [Answer] # [R](https://www.r-project.org/), cracks [Robin Ryder's fourth answer](https://codegolf.stackexchange.com/a/231485/95126) ``` x=z=6 yy=0 while(x+yy->>yy){x=x-1;z=z+1} LETTERS[z] ``` [Try it online!](https://tio.run/##K/r/v8K2ytaMq7LS1oCrPCMzJ1WjQruyUtfOrrJSs7rCtkLX0LrKtkrbsJbLxzUkxDUoOLoq9v9/AA "R – Try It Online") Preamble: [R](https://www.r-project.org/) code encourages the use of the right-to-left assignment operator `<-` instead of `=` (as in `x<-3` instead of `x=3`); this isn't seen much in `code golf`, of course, as it's one character longer. There is also a - much less used - left-to-right version, `->` (so `3->x` is equivalent to `x<-3` and `x=3`), and - even less used - versions that assign into the parent scope: `<<-` and `->>`. The crack of Robin's answer uses this last one to sneakily assign `x+yy` directly to the variable `yy`, replacing the comparison in the `while` condition. [Answer] # [R](https://www.r-project.org/), cracks [Dominic's R answer](https://codegolf.stackexchange.com/a/231521/55372) ``` a=b=c=2 for(a in 1:b)c=c*3i el(LETTERS[-c:0]) ``` [Try it online!](https://tio.run/##K/r/P9E2yTbZ1ogrLb9II1EhM0/B0CpJM9k2Wcs4kys1R8PHNSTENSg4WjfZyiBW8/9/AA "R – Try It Online") Our goal is to extract 18th letter ("R") from built-in `LETTERS`. It is to be done with here `c=17` or `c=-18`. After noticing that `pi` is very close to a digit with an imaginary number `[0-9]i`, we can indeed conclude that `3i` is our answer - for loop executes twice and effectively we multiply `c=2` by `3i*3i=-9`, which leads to `c=-18`. [Answer] # Japt, cracks [user's answer](https://codegolf.stackexchange.com/a/231517/88546) ``` "1,2"c@X+2 ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=IjEsMiJjQFgrMg==&input=) I know nothing about Japt, but found the `c` function while scrolling through the docs, which seems to map each character `X -> f(X)` by ASCII value. This works out nicely since `"1,2"` and `"3.4"` differ by an ASCII value of 2. [Answer] # [R](https://www.r-project.org/), cracks [Robin Ryder's 5th answer](https://codegolf.stackexchange.com/a/231547/95126) ``` PO=0 TA=TO =min(0 * 0 * 0, FALSE, 0 * 0 * 0) if(TA^TO)PO=18 LETTERS[PO] ``` [Try it online!](https://tio.run/##K/r/P8Df1oArxNE2xF/BNjczT8NAQUsBjHUU3Bx9gl11FOAimlyZaRohjnEh/ppAXYYWXD6uISGuQcHRAf6x//8DAA "R – Try It Online") Changes `|` (logical OR) for `^` (exponentiation). Zero raised to the power of zero is one, and so truthy. [Answer] # [><>](https://esolangs.org/wiki/Fish), cracks [A username's answer](https://codegolf.stackexchange.com/a/231820/64121) After drawing some execution paths by hand, I replaced a `/` in the first line with a space. ``` \\ / \ 9 \ /\ / /\ / \\ / 1/ \ \\\ \\ // \ \\ / \\\ \\ /\ / \\\/ \ \\\\ /// \\ \ \// // \\ / /\ \\\ \/ \\ \ \\/ / \\ / \ \\ /\\ // / // / \\\ \\ \ \ \ \\\ /\\/// \ \\// / \ + ///\ /\/\/ // / / \\/\\/\/\/ / /// / /3 / n\ // \\ / \ / / \ \/\/\/ / // // \/ / / \\ //\/\/ / / / / ; \//\/\\ /\/\ / / \ \ \//\ / \/ / // \ /// /\\/\/ /\///\\ // \/\/ //\\//\/ \\ \\ \/ /\/ /\\ \ \ \/ \\ / // \ \/ \/ \ /\/ \/ ``` [Try it online!](https://tio.run/##PVExDsJADNvziuwMEWJCfMUzgoWF/@uI7YRWOjU@O3bS5/v7OgfIykwknzsPRLlqnF@6Rhi51nIJIig3hKEKdsXWXZUUEF5iq07wm/K@KFk1JUmHGzYog21Ptg0rqK2NoTOtCtgbtAK7VCrhpTWMhGLjytHTgmzDCtjvrY8PQuF2GTs278MD/EUaQ0aK3OVeCcsH9wehjjANuxFmo6hF0ej6ebudKhyS4vIWmKHIpZt6zz68fpeW9FZyoPlPlg9UMZOtAnXODw "><> – Try It Online") The relevant commands are `1 9 + n ;` I don't really know how the IP gets to this path, but here is the end of the new execution path: [![enter image description here](https://i.stack.imgur.com/sfCKVm.png)](https://i.stack.imgur.com/sfCKV.png) [Answer] # [Julia 1.0](http://julialang.org/), cracks [MarcMush's answer](https://codegolf.stackexchange.com/a/231894/86301) ``` show(sum(count.(==('1'),bitstring.(Inf16[9973%36])))) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/vzgjv1yjuDRXIzm/NK9ET8PWVkPdUF1TJymzpLikKDMvXU/DMy/N0Cza0tLcWNXYLFYTCP7/BwA "Julia 1.0 – Try It Online") `Int16` is the type for signed 16-byte integers. `Inf16` is the 16-byte version of `Inf`, a value greater than all 16-byte floating-point values. Its binary representation is `0111110000000000`, with the required five `1`s. [Answer] # APOL, cracks [Ginger Industries' answer](https://codegolf.stackexchange.com/a/239685/101522) ``` ƒ(56 ¿(%(I(I(∈ )) 4) ¿(F :(33:3():33::()) ¿(F 2 ¿(T(∈) 2 3))))((X)) ) ``` [Try it Online!](https://replit.com/@GingerIndustries/APOL) I just went through each command and found what it did in the docs, and figured out that the condition on the last `¿` statement needed to return true, so I just put a `True` in there, and it worked. Here's some golfed code to achieve the same result: ``` ƒ(56 ¿(%(∈ 4) 2)) ``` Essentially, for every number `x` in the range `[0..56)`, change the number to `2` if `x % 4` is truthy, otherwise change it to `None`. [Answer] # Cracked [DLosc's 2nd Pip answer](https://codegolf.stackexchange.com/a/231436/95671) ``` E***t ``` Try this code [here](https://replit.com/@dloscutoff/pip) If you don't want to run the code yourself, this is what it looks like: ``` === Welcome to Pip, version 0.21.07.05 === Enter command-line args, terminated by newline (-h for help): Enter your program, terminated by Ctrl-D or Ctrl-Z: E***t Executing... 42 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `o`, cracks [Aaron Miller's answer](https://codegolf.stackexchange.com/a/231434/100664), 13 bytes, ``` `₴ḟ₴`₴`Buzz`F ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=o&code=%60%E2%82%B4%E1%B8%9F%E2%82%B4%60%E2%82%B4%60Buzz%60F&inputs=&header=&footer=) Vyxal's dictionary compression uses SCCs, two non-ascii characters joined together to make something that decompresses into a word. However, a single unmatched non-ascii character is a NOP, so replacing the space with that removes the space. [Answer] # [Rattle](https://github.com/DRH001/Rattle), 8 bytes, cracks [Daniel H.'s answer](https://codegolf.stackexchange.com/a/231450/101522) ``` <[c]@I^p ``` [Try it Online!](https://rattleinterpreter.pythonanywhere.com/?flags=&code=%3C%5Bc%5D%40I%5Ep&inputs=) [Answer] # [hyper-neutrino, Jelly](https://codegolf.stackexchange.com/a/231476) ``` “5gỊƑ!ṆḥḌ³`⁻Ɓc?Ạ°þạḅI§Ɠ¦mṪ9ʂ:Nȯx1®Ḟ ƭḣTsÄẉṭ7|ẏẋzⱮɦḲ⁵.ṗbÐɱ8Ñ3"Øȧ¡Ė÷ʠ\¬ṇƥṀœṙRṅẈɓẒ#Ẏỵ⁼Ȧ©MỴƤ⁷ẹ⁴ż;OṃċẊnFḶ¤ȤḟỤẇçİ/ƒjƬhƙA2PẸtX¿ṢḢṡyiṂCd)ÆṣĠʋŒ-ė~YZ⁾ĿṘ²ŀ'ṄLȷU£BSƲɼṛñ½ȥÞ6pḂæ×ẆɠG4ịı$EƊ¹¥ḃɗ}DK]u*ġṚk⁹ɲḊµṾW_,ȧwß⁺⁸0ọv(<Ɲṁḍl=Q+ð@Çø[Żṫoera&Ọ¢Vḷ¶Ṗ€ƈḋ{⁶ƇĊqḄHḳJ⁽Ȯ%>^ḤṠfƘṬ‘Œ¿ ``` Just brute force. [Try it online!](https://tio.run/##DdDnUlpBGAbgW0nvvffee@89McWQXk0bFhEMaBJhRjBF6UwSJIAC@@1Bndk97JzDXbx7I8T/z6@ns8Pj6Wq3jffn2nuwQnpgJigAngXvk2M3DLM0u70dIiFLahIiCd5zUOZ1VOYegf5sbPk2HXP@vV0pi@DDM/QoePrMC@WH@AwaXf8B4itE@J0pF90ceMWw6jJQ7Jb65pY3qIHVs1TcycukPajqrcQVWQAFdRbkbUZBQ6dAPRC9bhQiMhviC6yqYQ0nJ38fhTWuM4bVIciw8WZj83FQtx2GCD3eB16TGScDPgIrAxFUebu0XEc6deG@Htq56gQEf3lBToFS4ClQsusByLf7zkIVAKXtRCvcjCy1Y58uXjJs0p5mcVlpeueD/Eec@lmZ3nVaV9wG6Icqywknq4bXPQX3qZyKQQTcxP41sMJ2ec5eHZIkpxO73djHPYevvlpkJ0HfHxpGbgU8JKugyfPXlzj5N2rEMGEYXwGr//WCLfoXiIH3e7aeXKxKO1RQ8ctNC/T3Scfzm/Ng9cnUOfC6rIEGja@ge8HD7w2r6aAdegbuPwA@dsiwCac4d9s18AwocVfHQQXjjTcjcqrd/g8 "Jelly – Try It Online") [Answer] # [R](https://www.r-project.org/), cracks [pajonk's answer](https://codegolf.stackexchange.com/a/231523/95126) ``` a=is.numeric bb=strrep(11,1) "if"(a(bb),LETTERS[a(bb)],"R") ``` [Try it online!](https://tio.run/##K/r/P9E2s1gvrzQ3tSgzmSspyba4pKgotUDD0FDHUJNLKTNNSSNRIylJU8fHNSTENSg4GsyL1VEKUtL8/x8A "R – Try It Online") `as.numeric` returns its argument coerced to numeric form; `is.numeric` - which conveniently differs by only a single character - returns `TRUE` if its argument is already numeric, and `FALSE` otherwise. `FALSE` is the case here, since `bb` is a character string (of digits). [Answer] # Japt, cracks [Shaggy's answer](https://codegolf.stackexchange.com/a/231491/95792) ``` PùÅÔÌ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=UPnF1Mw=&input=) This was pretty simple. Shaggy's original started with `¤` instead of `P`, which converted the input (`0` if not given) to a base 2 string (`"0"`). However, `P` is the empty string. After that, `ùÅ` pads to length 1 using `s`, which is useless for the original, but turns the cracked version into `"s"`, which is exactly what we want. `Ô` reverses the string and `Ì` gets the last character, so they're both basically no-ops for single-character strings. ## Another crack ``` ¤ù¤ÔÌ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=pPmk1Mw=&input=) This time, the `Å` is replaced with `¤`, so that it pads with `s` to a length of two instead of just one, making the string `s0`. `Ô` reverses it and `Ì` picks the last character, `s`. ]
[Question] [ ## Challenge Display to the screen or write to stdout this exactly: ``` ** ** **** **** **** **** **** **** **** ********** ********** ********** ``` # Winning This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins. [Answer] # [Python 3](https://docs.python.org/3.8/), 47 bytes ``` for n in b"":print(f"{'**'*n:^10}") ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFPITNPIUmJkZEJAlhZWZWsCooy80o00pSq1bW01LXyrOIMDWqVNP//BwA "Python 3.8 (pre-release) – Try It Online") Yawn, bytestrings. I got close with a few other approaches: **48 bytes** ``` for n in[2]*2+[4]*7+[10]*3:print(f"{'*'*n:^10}") ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFPITMv2ihWy0g72iRWy1w72tAgVsvYqqAoM69EI02pWl1LXSvPKs7QoFZJ8/9/AA "Python 3.8 (pre-release) – Try It Online") **48 bytes** ``` for n in[1]*2+[2]*7+[5]*3:print(-n%5*' '+'**'*n) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFPITMv2jBWy0g72ihWy1w72jRWy9iqoCgzr0RDN0/VVEtdQV1bXUtLXStP8/9/AA "Python 3.8 (pre-release) – Try It Online") This code is 46 bytes in Python 2 where `print` doesn't need parens. Thanks to dingledooper for -1 byte with `-n%5`. **49 bytes** ``` print(" **\n"*2+" ****\n"*7+('*'*10+'\n')*3) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69EQ0kBCLS0YvKUtIy0lcBsCM9cW0NdS13L0EBbPSZPXVPLWPP/fwA "Python 3.8 (pre-release) – Try It Online") **50 bytes** ``` n=15 while n-3:print(f"{(5>>n//7)*'**':^10}");n-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P8/W0JSrPCMzJ1UhT9fYqqAoM69EI02pWsPUzi5PX99cU0tdS0vdKs7QoFZJ0zpP19bw/38A "Python 3.8 (pre-release) – Try It Online") [Answer] # [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, 47 DECLEs1 = 58.75 bytes *1. CP-1610 instructions are encoded with 10-bit values (0x000 to 0x3FF), known as DECLEs. Although the Intellivision is also able to work on 16-bit, programs were really stored in 10-bit ROM back then.* A full program in 10-bit ROM format, mapped at $4800. This includes an initialization of the video chip so that the display is correct. ``` ROMW 10 ; use 10-bit ROM ORG $4800 ; map our program at $4800 4800 0002 EIS ; enable interrupts 4801 0001 SDBD ; R4 = data pointer 4802 02BC 002B 0048 MVII #data, R4 4805 02BD 0200 MVII #$200, R5 ; R5 = BACKTAB pointer 4807 02A0 loop MVI@ R4, R0 ; load data word into R0 4808 0080 TSTR R0 ; if it's zero ... 4809 0204 001A BEQ done ; ... exit 480B 0081 MOVR R0, R1 ; copy R0 to R1 480C 03B9 0007 ANDI #7, R1 ; isolate the 3 least significant bits 480E 0275 line PSHR R5 ; save R5 on the stack 480F 0082 MOVR R0, R2 ; copy R0 to R2 4810 0066 SLR R2, 2 ; right-shift R2 by 3 positions 4811 0062 SLR R2 4812 03BA 0007 ANDI #7, R2 ; isolate the 3 least significant bits 4814 00D5 ADDR R2, R5 ; add that to R5 4815 0083 MOVR R0, R3 ; copy R0 to R3 4816 02BA 0057 MVII #$0057, R2 ; load the value of a white '*' in R2 4818 026A char MVO@ R2, R5 ; write the character 4819 033B 0040 SUBI #$40, R3 ; subtract 64 from R3 481B 0223 0004 BPL char ; keep drawing while it's positive 481D 02B5 PULR R5 ; restore R5 481E 02FD 0014 ADDI #20, R5 ; advance to the next line 4820 0011 DECR R1 ; decrement R1 4821 022C 0014 BNEQ line ; draw another line if it's not zero 4823 0220 001D B loop ; or process the next value 4825 02BD 0030 done MVII #$30, R5 ; R5 = pointer into STIC registers 4827 0268 MVO@ R0, R5 ; no horizontal delay 4828 0268 MVO@ R0, R5 ; no vertical delay 4829 0268 MVO@ R0, R5 ; no border extension 482A 0017 spin DECR R7 ; loop forever 482B 0062 data DECLE $062 ; data format: WWWWPPPNNN 482C 00DF DECLE $0DF ; W = width - 1 482D 0243 DECLE $243 ; P = left padding 482E 0000 DECLE 0 ; N = number of lines ``` ## Output [![screenshot](https://i.stack.imgur.com/VrtT2.gif)](https://i.stack.imgur.com/VrtT2.gif) *made with [jzIntv](http://spatula-city.org/%7Eim14u2c/intv/)* [Answer] # [Haskell](https://www.haskell.org), ~~81~~ ~~72~~ 60 bytes ``` unlines[(' '<$['1'..a])++("**"<*[a..'9'])|a<-"998888888555"] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhY3bUrzcjLzUoujNdQV1G1UotUN1fX0EmM1tbU1lLS0lGy0ohP19NQt1WM1axJtdJUsLS0gwNTUVCkWYsba3MTMPNuC0pLgkiKFNIjYggUQGgA) -9 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334) -9 byte thanks to [ovs](https://codegolf.stackexchange.com/users/64121) Uses the range syntax [a..'9'] to do substraction. [Answer] # [Perl 5](https://www.perl.org/), 42 bytes ``` say$"x(5-$_/2),'*'x$_ for 2,2,(4)x7,(10)x3 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJFqULDVFclXt9IU0ddS71CJV4hLb9IwUjHSEfDRLPCXEfD0ECzwvj//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/), 45 bytes Quite straight forward, with some optimisations: * starting with 3 trailing spaces, which can later be turned into `*` * of course using the `p` flag for saving one byte * `s/ /**/4` to simply replace one space by two `*` * `h;H;G` to produce three identical lines ``` s/^/ ** /p;p s/ /**/4p;h;H;G;p;p s/ /*/g ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1g/Tl8BCLS0gIR@gXUBV7G@gr6Wlr5JgXWGtYe1uzVcTD/9/38A "sed – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 65 bytes ``` repeat 2 <<<' **' repeat 7 <<<' ****' repeat 3 <<<********** ``` [Try it online!](https://tio.run/##qyrO@P@/KLUgNbFEwUjBxsZGXQEItLTUuaCC5jBBLS0kUWOQqBYc/P8PAA "Zsh – Try It Online") It's pretty basic, clever tricks like left-padding *`l:expr::string1:`* didn't help. [Answer] # [///](https://esolangs.org/wiki////), ~~60~~ ~~54~~ ~~51~~ ~~48~~ ~~47~~ 46 bytes ``` /a/**//s/ a//w/ aaaaa//b/ sa/ s sbbbbbbbwww ``` [Try it online!](https://tio.run/##JcGxDcAwDAPBXlOwdvMz0UCAFOlYaHwZRu7yOe@TGcxaECQZmvIFm4pRStm/7p45 "/// – Try It Online") -1 byte thanks to [@Philippos](https://codegolf.stackexchange.com/users/72726/philippos) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 97 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 12.125 bytes ``` »ƛ⁼c»yøḊ×v*øm ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiwrvGm+KBvGPCu3nDuOG4isOXdirDuG0iLCIiLCIiXQ==) Bitstring: ``` 0000111111001110001100010001100001000110001001001010100111011011101111010100110110101111000100100 ``` **Explanation**: ``` »ƛ⁼c»yøḊ×v*øm »ƛ⁼c» Decompresses integer => 122753 yøḊ Interleave, Run-length decoding => [1,1,2,2,2,2,2,2,2,5,5,5] ×v* Map repeat asterisk n times øm Palindromise, center and join by newlines ``` The more trivial answer [`»ɽβ≬ǓG»f×v*øm`](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLCu8m9zrLiiazHk0fCu2bDl3Yqw7htIiwiIiwiIl0=) has a higher vyncode score (probably because the compressed part is longer). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ↑E333ac×*⍘ιφ‖C ``` [Try it online!](https://tio.run/##K0otycxL/P@fy8To0DYTI2MIMDQ05DLmOrTN2ITLEEgZGBpwaehpauhpa3KpGKpoKagYqWhp/f8PAA "Retina 0.8.2 – Try It Online") Link is to verbose version of code. Explanation: ``` ↑E333ac×*⍘ιφ ``` Output the first five columns of the figure, whose heights are the hexadecimal digits `333ac`, starting at the bottom working up. ``` ‖C ``` Make a mirror copy to complete the figure. [Answer] # [JavaScript (V8)](https://v8.dev/), 59 bytes *-5 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` for(n of"443333333000")print("".padEnd(n).padEnd(10-n,"*")) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCNPIT9NycTEGAIMDAyUNAuKMvNKNJSU9AoSU1zzUjTyNGEsQwPdPB0lLSVNzf//AQ "JavaScript (V8) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` #p#Þ#Þ555ì Ëç*²Ãû ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=I3Aj3iPeNTU17CDL5yqyw/s) ``` #p#Þ#Þ555ì Ëç*²Ãû #p#Þ#Þ555 :Compressed integer 112222222555 ì :To digit array Ë :Map ç : Repeat *² : "*" duplicated à :End map û :Centre pad with spaces to the length of the longest :Implicit output joined with newlines ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 13 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` 2_4··♂∙]⌂*♂Ωn ``` [Try it online.](https://tio.run/##y00syUjPz0n7/98o3uTQ9kPbH81setQxM/ZRT5MWkHluZd7//wA) **Explanation:** ``` 2 # Push 2 _ # Duplicate it 4 # Push 4 ·· # Quadruplicate it twice ♂ # Push 10 ∙ # Triplicate it ] # Wrap all values on the stack into a list: [2,2,4,4,4,4,4,4,4,10,10,10] ⌂* # Convert each to strings with that many "*" ♂Ω # Centralize the strings to length 10 n # Join the list of padded strings by newlines # (after which the entire stack is output implicitly as result) ``` [Answer] # 6510-Assembler for C64, 42 bytes ``` *=$c000 ldy #23 lda #32 w ldx data,y q jsr $ffd2 dex bpl q eor #10 dey bpl w rts data !byte 9,29,9,29,9,32,3,35,3,35,3,35,3,35,3,35,3,35,3,36,1,37,1,3 ``` [Answer] # Python 3.11 (~~69~~ 67 bytes ~~nice~~) ``` print(''.join(map(lambda a,c:f"{'*'*a:^10}\n"*c,(2,4,10),(2,7,3)))) ``` removed parentheses around fstring thanks to @corvus\_192 [Answer] # [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 47 bytes ``` explode"112222222555"|rep(" ",5-x)..rep("**",x) ``` Relatively self explanatory, explodes the string `112222222555` into a list of single characters, each of which represents half the width of the building as it goes down. Then, maps over that list, replacing each entry with a string of `5-x` spaces, and `2*x` asterisks, which effectively rebuilds it. [Try it online!](https://tio.run/##SyxKykn9/z@1oiAnPyVVydDQCAJMTU2VaopSCzSUFJR0THUrNPX0wDwtLSWdCs3//wE "ARBLE – Try It Online") [Answer] # Scratch, 134 bytes **NOTE: This code assumes that `x` is already displayed. To see the full \*STDOUT\* as it is, you should drag the list to the full screen.** Direct solution. Had to add some spaces so it would align up nicely because when Scratch displays lists, line numbers are displayed *and* modify the position of their corresponding item. Alternatively, [0 bytes](https://scratch.mit.edu/projects/924985644/) [![enter image description here](https://i.stack.imgur.com/bYgmj.png)](https://i.stack.imgur.com/bYgmj.png) [![enter image description here](https://i.stack.imgur.com/DrAHC.png)](https://i.stack.imgur.com/DrAHC.png) ``` define delete[all v]of[x v add[ **]to[x v add[ **]to[x v repeat(7 add[ ****]to[x v end repeat(3 add[**********]to[x v ``` [A joke about line lengths](https://xkcd.com/276/) [Answer] # APL+WIN, ~~52~~ ~~33~~, 31 bytes 19 bytes saved thanks to Jonah. 2 bytes more by switching from index origin 1 to 0 ``` '* '[2 7 3⌿⊃(⊂10⍴2)⊤¨975 903 0] ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv7qWgnq0kYK5gvGjnv2Pupo1HnU1GRo86t1ipPmoa8mhFZbmpgqWBsYKBrH/geq5/qdxcQEA "APL (Dyalog Classic) – Try It Online") Original code: ``` m←12 5⍴' '⋄((∊10 35 15⍴¨(⊂5⍴2)⊤¨1 3 31)/,m)←'#'⋄m,⌽m ``` [Answer] # Commodore [BASIC V2](https://www.c64-wiki.com/wiki/BASIC) or compatible interpreter (Most notably the Commodore C64 or C128) - non-competing/just for fun - 106 tokenised BASIC bytes ``` 0reada,b,c:s=1:on-(a<.)goto2:forx=1toc:ifsthen?spc(a);:s=. 1fory=1tob:?"**";:next:?:s=1:next:goto 2data4,1,2,3,2,7,0,5,3,-1,, ``` Here it is in action: [![Commodore C64 PETSCII building](https://i.stack.imgur.com/ZkjS4.png)](https://i.stack.imgur.com/ZkjS4.png) I will add a better explanation later, but for those who maybe are unfamiliar with Commodore BASIC, here is a more readable listing of broadly the same outcome that I made in order to work out the logic before I minimised and crunched the BASIC listing into the three lines in this entry: [![Commodore C64 PETSCII building, but non-minimised and non-crunched](https://i.stack.imgur.com/01iJk.png)](https://i.stack.imgur.com/01iJk.png) [Answer] # C# (.NET 4.7.2), 92 90 87 88 bytes ``` foreach(var x in "443333333000")Console.WriteLine("".PadRight(x-48).PadRight(58-x,'*')); ``` Edit: @corvus\_192 pointed out that using 48 instead of '0' would save a few chars. Thanks! Implementation of Arnauld's JS version: <https://codegolf.stackexchange.com/a/266751/120291> [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 107 bytes ``` >-[-[-<]>>+<]>->>--[<+>++++++]<->++++++++++>++[-<<<....>..>.>]+++++++[-<<<...>....>.>]+++[-<<..........>.>] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v/fTjcaCG1i7ey0gYSunZ2ubrSNtp02GMTa6EJZIABkAlXa2OgBgR0I2cVCZWDCdhApsDhITA8OQIL//wMA "brainfuck – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 64 bytes (Thanks [Julian](https://codegolf.stackexchange.com/users/97729/julian)!) ``` 4,4,(,3*7),0,0,0|%{$_}|%{""|% *ht($_-'0')|% *ht(10-($_-'0'))'*'} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30THREdDx1jLXFPHAARrVKtV4muBpJJSjaqCVkaJhkq8rrqBuiaUZ2igCxPRVNdSr/3/HwA "PowerShell – Try It Online") ~~# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 85 bytes~~ ``` foreach($n in 4,4,3,3,3,3,3,3,3,0,0,0){"".PadRight($n-'0').PadRight(10-($n-'0'),'*')} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/KDUxOUNDJU8hM0/BRMdExxgFGoCgZrWSkl5AYkpQZnpGCVCprrqBuiZCwNBAFyaoo66lrln7/z8A "PowerShell – Try It Online") # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 64 bytes ``` foreach($n in $c){"".PadRight($n-'0').PadRight(10-($n-'0'),'*')} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqxgq2CiY6JjjAINQPB/Wn5RamJyhoZKnkJmnoJKsma1kpJeQGJKUGZ6RglQVFfdQF0TIWBooAsT1FHXUtes/f8fAA "PowerShell – Try It Online") Thanks to [@lost\_in\_a\_musical\_note](https://codegolf.stackexchange.com/a/266781/91342)'s answer for laying the groundwork! [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 22 bytes ``` 00079){3+`**}rT{.]i.}; ``` ## Explanation ``` 00079){3+`**}rT{.]i.}; 00079) # A Stack of the numbers 0, 0, 0, 7, 9 (Each 3 less than the height of half the columns) { }r # Replace each number with 3+ # +3 `** # Multiply by "*" (Which repeats "*" x times) T # Transpose { }; # For each row .] # Concatenate back into a string and duplicate i. # Inverse the duplicate and concatenate, palindromizing # Implicit output the contents of the stack. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/9/AwMDcUrPaWDtBS6u2KKRaLzZTr9b6////AA "RProgN 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 25 bytes ``` '* '{~2 7 3#:@#975,903,0: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1bUU1KvrjBTMFYyVrRyULc1NdSwNjHUMrP5rcqUmZ@QrpKmrc6VWZJaAKBBfWQ9oirqCrUKstV68kUIsyDwDLgUg0NJCorS0yKC14AAHU/M/AA "J – Try It Online") This just encodes the full rows as binary numbers, then duplicates them according to the 2 7 3 frequency. This results in a 12 by 10 binary matrix, which is converted to ascii. I didn't find a way to exploit the symmetry in a way that beats this. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 48 bytes ``` 42¶423333333111 3 ¶34 1 ¶010 (.)(.+) $1$* $2$** ``` [Try it online!](https://tio.run/##K0otycxL/P@fy8To0DYTI2MIMDQ05DLmOrTN2ITLEEgZGBpwaehpauhpa3KpGKpoKagYqWhp/f8PAA "Retina 0.8.2 – Try It Online") Explanation: ``` 42¶4233333111 ``` Start with the encoding for the first two lines plus an encoded encoding for the remaining lines. ``` 3 ¶34 1 ¶010 ``` Decode the encoding for the remaining lines. All lines are now singly encoded. ``` (.)(.+) $1$* $2$** ``` Decode the encoding for each line (first digit is number of spaces, other digit(s) is number of asterisks). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2Dx7.DTÐ)'*×.c ``` [Try it online.](https://tio.run/##yy9OTMpM/f/fyKXCXM8l5PAETXWtw9P1kv//BwA) **Explanation:** ``` 2 # Push 2 # Stack: 2 D # Duplicate it # Stack: 2,2 x # Double it (without popping) # Stack: 2,2,4 7 # Push 7 # Stack: 2,2,4,7 .D # Duplicate the 4 7 times # Stack: 2,2,4,4,4,4,4,4,4 T # Push 10 # Stack: 2,2,4,4,4,4,4,4,4,10 Ð # Triplicate it # Stack: 2,2,4,4,4,4,4,4,4,10,10,10 ) # Wrap everything on the stack into a list # Stack: [2,2,4,4,4,4,4,4,4,10,10,10] '*× '# Convert each to a string of that many "*" # Stack: ["**","**","****","****",...,"**********"] .c # Join by newlines and pad leading spaces to centralize the lines # Stack: " **\n **\n ****\n...\n**********" # (after which the result is output implicitly) ``` [Answer] # [*Acc!!*](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), 85 bytes ``` Count i while i-132 { Write 32+10*0^((i%11*2-9)^2/(((i/11+5)/7)^2*20+2))-i%11/10*22 } ``` [Try it online!](https://tio.run/##S0xOTkr6/985vzSvRCFToTwjMydVIVPX0NhIoZorvCizJFXB2Ejb0EDLIE5DI1PV0FDLSNdSM85IXwPI1Tc01DbV1DcH8rWMDLSNNDV1QUr0gcqNjLhq//8HAA "Acc!! – Try It Online") ### Explanation Let's start with this 99-byte version: ``` Count r while r-12 { Count c while c-10 { Write 32+10*0^((c*2-9)^2/(((r+5)/7)^2*20+2)) } Write 10 } ``` We have a straightforward nested loop over 12 rows `r` and 10 columns `c`, with a newline written at the end of each row. The math to determine space or asterisk runs as follows: We want to transform the column numbers such that inner columns map to a smaller value than outer columns; then, for each row, we can apply a cutoff so the inner columns become one character and the outer columns become a different character. *Acc!!* doesn't have an absolute value operator, so we'll use squaring. To preserve symmetry, we double the column number and subtract an odd constant: `(c*2-9)^2` ``` c c*2-9 (c*2-9)^2 0 -9 81 1 -7 49 2 -5 25 3 -3 9 4 -1 1 5 1 1 6 3 9 9 9 81 ``` The column cutoff is also dependent on the row number: * Rows 0-1: cutoff between 1 and 9 * Rows 2-8: cutoff between 9 and 25 * Rows 9-11: cutoff above 81 First, we shift and int-divide the row numbers to quantize them into the correct chunks: ``` r (r+5)/7 0-1 0 2-8 1 9-11 2 ``` Now a linear function doesn't put the cutoffs in the right range, but a quadratic function does: ``` (r+5)/7 ((r+5)/7)^2*20+2 0 2 1 22 2 82 ``` Next, we need to check whether the modified column value is greater than or less than the cutoff. We can do this using int division. But that results in different non-zero values, which isn't good for the ASCII-code math we're going to do. We can convert them to 0 and 1 by exploiting the fact that 0^0 = 1 and 0^x = 0 for any positive x in *Acc!!*. ``` col cutoff col/cutoff 0^(col/cutoff) 1 2 0 1 9 2 4 0 25 2 12 0 1 22 0 1 9 22 0 1 25 22 1 0 1 82 0 1 9 82 0 1 25 82 0 1 ``` We then multiply that quantity by 10 and add 32, turning 0 into 32 (space) and 1 into 42 (asterisk), and write out the appropriate character. --- To get from the 99-byte version to the 85-byte version, we first move the newline-printing into the nested loop. We add an 11th column, which according to the existing math would always be a space (ASCII 32); then we subtract 22 if the column index is >= 10, turning that space into a newline (ASCII 10). ``` ... while c-11 { Write ... - c/10*22 ``` Now we can combine the two loops into a single loop whose index `i` runs from 0 to 131. The row number `r` is simply `i/11`, and the column number `c` is `i%11`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 28 bytes ``` " #"@+&'(12-)\'10\9992002999 ``` [Try it online!](https://ngn.codeberg.page/k#eJxTUlBWctBWU9cwNNLVjFE3NIixtLQ0MjAwAlIASgIFew==) [Answer] # Google Sheets, ~~88~~ ~~80~~ ~~79~~ 75 bytes ``` =let(c,"**",n,"** ",e," "&n,f," "&c&n,g,c&c&c&c&n,e&e&rept(f,7)&g&g&g) ``` Put the formula in cell `A1`. It uses simple string concatenation. The whole output is displayed in that one cell. The text string in `n` is two asterisks followed by a newline. A literal newline can be specified this way in Google Sheets, saving nine bytes over `"&char(10)&"`. Structured version (80 bytes): ``` =map({2;7;3},{4;3;0},{2;4;10},lambda(n,s,a,rept(rept(" ",s)&rept("*",a)&" ",n))) ``` The output is shown in `A1:A3`, with newlines in cells. The text string between `&"` and `",n"` is a newline. [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 36 bytes ``` ," **"*2 ," ****"*7 ,("*"*10)*3 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/a@SZlv9X0dJAQi0tJS0jLjAbC0tEMecS0dDCUgbGmhqGf@v5eJSU0n7DwA "PowerShell Core – Try It Online") ``` ," **"*2 # Creates an array (" **", " **") print it on stdout ," ****"*7 # Same as above ,("*"*10)*3 # Builds and string of 10 stars, then same as above ``` [Answer] # COMMODORE 64 & MSX BASIC - Solution as a one-liner, 80 Bytes ``` 0 DATA4,2,2,3,4,7,,10,3:READA,B,C:FORJ=1TOC:PRINTTAB(A):FORI=1TOB:PRINT"*";:NEXT:PRINT:NEXT:GOTO ``` In C64 must be typed in with abbreviations. ]
[Question] [ Remove all repeating words from an inputted sentence. Input will be something like `cat dog cat dog bird dog Snake snake Snake` and the output should be `cat dog bird Snake snake`. There will always be a single space separating words. Output order must be the same as input. (Refer to the example) You don't need to handle punctuation but capital letter handling is required. [Answer] ## CJam, 7 chars ``` qS/_&S* ``` Can probably be much shorter... but whatever I've almost never used CJam. ^.^ `q` reads input, `S/` splits on spaces, `_&` duplicates and applies a setwise AND (therefore getting rid of duplicates), and `S*` re-joins on space. [Online interpreter link](http://cjam.aditsu.net/#code=qS%2F_%26S*&input=cat%20dog%20cat%20dog%20bird%20dog%20Snake%20snake%20Snake) [Answer] # Haskell, 34 bytes ``` import Data.List unwords.nub.words ``` Usage example: `(unwords.nub.words) "cat dog cat dog bird dog Snake snake Snake"` -> `"cat dog bird Snake snake"`. [Answer] # APL, ~~22~~ 20 bytes ``` {1↓∊∪(∊∘' '⊂⊢)' ',⍵} ``` This creates an unnamed monadic function that accepts a string on the right and returns a string. Explanation: ``` ' ',⍵} ⍝ Prepend a space to the input string (∊∘' '⊂⊢) ⍝ Split the string on spaces using a fork ∪ ⍝ Select the unique elements {1↓∊ ⍝ Join into a string and drop the leading space ``` [Try it online](http://tryapl.org/?a=%7B1%u2193%u220A%u222A%28%u220A%u2218%27%20%27%u2282%u22A2%29%27%20%27%2C%u2375%7D%27cat%20dog%20cat%20dog%20bird%20dog%20Snake%20snake%20Snake%27&run) Saved 2 bytes thanks to Dennis! [Answer] ## Ruby, 21 chars ``` ->s{s.split.uniq*' '} ``` [Answer] # JavaScript (ES6) 33 (see [this answer](https://codegolf.stackexchange.com/a/59716/21348)) Test running the snippet below in an EcmaScript 6 compliant browser (implementing Set, spread operator, template strings and arrow functions - I use Firefox). Note: the conversion to Set drop all the duplicates *and* Set mantains the original ordering. ``` f=s=>[...Set(s.split` `)].join` ` function test() { O.innerHTML=f(I.value) } test() ``` ``` #I { width: 70% } ``` ``` <input id=I value="cat dog cat dog bird dog Snake snake Snake"/><button onclick="test()">-></button> <pre id=O></pre> ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 12 bytes TeaScript is JavaScript for golfing. ``` xs` `u()j` ` ``` This is pretty short. It splits on each space, filters out duplicates, then rejoins. [Try it online](http://vihanserver.tk/p/TeaScript/?code=xs%60%20%60u()j%60%20%60&input=Cat%20cat%20cat) [Answer] # PowerShell, 15 Bytes ``` $args|select -u ``` Whoa, an actual entry where PowerShell is somewhat competitive? That's unpossible! Takes the string as input arguments, pipes to `Select-Object` with the `-Unique` flag. Spits out an array of strings, preserving order and capitalization as requested. ### Usage: ``` PS C:\Tools\Scripts\golfing> .\remove-repeated-words-from-string.ps1 cat dog cat dog bird dog Snake snake Snake cat dog bird Snake snake ``` --- If this is too "cheaty" in assuming the input can be as command-line arguments, then go for the following, at **~~24~~ 21 Bytes** (saved some bytes thanks to [blabb](https://codegolf.stackexchange.com/users/41749/blabb)). Interestingly, using the unary operator in *this* direction happens to also work if the input string is demarcated with quotes *or* as individual arguments, since the default `-split` is by spaces. Bonus. ``` -split$args|select -u ``` [Answer] # Julia, 29 bytes ``` s->join(unique(split(s))," ") ``` This creates an unnamed function that splits the string into a vector on spaces, keeps only the unique elements (preserving order), and joins the array back into a string with spaces. [Answer] # R, 22 bytes ``` cat(unique(scan(,""))) ``` This reads a string from STDIN and splits it into a vector on spaces using `scan(,"")`, selects only unique elements, then concatenates them into a string and prints it to STDOUT using `cat`. [Answer] # [Retina](https://github.com/mbuettner/retina), 22 bytes ``` (\w+)\b(?<=\b\1\b.+) ``` Save the file with a trailing linefeed and run it with the `-s` flag. This is fairly straight forward in that it matches a single word, and the lookbehind checks whether that same word has appeared in the string before. The trailing linefeed causes Retina to work in Replace mode with an empty replacement string, removing all matches. [Answer] # Mathematica, ~~43~~ 39 bytes ``` StringRiffle@*Keys@*Counts@*StringSplit ``` [Answer] # Pyth - 9 bytes Well this is why we're all waiting for Pyth5, could have been 5 bytes. ``` jdoxzN{cz ``` [Try it online here](http://pyth.herokuapp.com/?code=jdoxzN%7Bcz&input=cat+dog+cat+dog+bird+dog+Snake+snake+Snake). [Answer] ## C++11, 291 bytes ``` #include<iostream> #include<string> #include<list> #include<sstream> #include<algorithm> using namespace std;main(){string s;getline(cin,s);list<string>m;stringstream b(s);while(getline(b,s,' '))if(find(m.begin(),m.end(),s)==m.end())m.push_back(s);for(auto a:m)cout<<a<<' ';cout<<endl;} ``` I don't see a whole lot of C++ answers compared to golfing languages, so why not. Note that this uses C++11 features, and so if your compiler is ~~stuck in the dark ages~~ sufficiently old enough, you may need to pass a special compilation switch to make it use the C++11 standard. For `g++`, it's `-std=c++11` (only needed for versions < 5.2). [Try it online](http://ideone.com/LmEUp1) [Answer] # K5, 9 bytes ``` " "/?" "\ ``` FYI, this is a function. ## Explanation ``` " "\ Split the input on spaces ? Find all the unique elements " "/ Join them back together ``` [Answer] # Matlab: 18 Bytes ``` unique(d,'stable') ``` where `d` is `d = {'cat','dog','cat','dog','bird','dog','Snake','snake','Snake'}`. The result is `'cat' 'dog' 'bird' 'Snake' 'snake'` [Answer] ## Python 3, 55 ``` l=[] for x in input().split():l+=[x][x in l:] print(*l) ``` Yeesh, this is long. Unfortunately, Python's `set` doesn't keep the order of the elements, so we have to do the work ourselves. We iterate through the input words, keeping a list `l` of elements that aren't yet in `l`. Then, we print the contents of `l` space-separated. A string version of `l` would not work if some words are substrings of other words. [Answer] # C#, 38 bytes ``` String.Join(" ",s.Split().Distinct()); ``` [Answer] ## Perl 6, 14 bytes As a whole program the only way you would write it is 21 bytes long ``` say $*IN.words.unique # 21 bytes ``` --- As a lambda expression the shortest is 14 bytes ``` *.words.unique # 14 bytes ``` ``` say ( *.words.unique ).('cat dog cat dog bird dog Snake snake Snake') my &foo = *.words.unique; say foo $*IN; ``` While the output is a List, if you put it in a stringifying context it will put a space between the elements. If it was a requirement to return a string you could just add a `~` to the front `~*.words.unique`. --- If snippets were allowed, you could shorten it to 13 bytes by removing the `*`. ``` $_ = 'cat dog cat dog bird dog Snake snake Snake'; say .words.unique ``` [Answer] # [gs2](https://github.com/nooodl/gs2/blob/master/gs2.py), 3 bytes ``` ,É- ``` Encoded in [CP437](https://en.wikipedia.org/wiki/Code_page_437). STDIN is pushed at the start of the program. `,` splits it over spaces. `É` is `uniq`, which filters duplicates. `-` joins by spaces. [Answer] ## Python 3, ~~87~~ 80 bytes *turns out the full program version is shorter* ``` s=input().split(' ') print(' '.join(e for i,e in enumerate(s)if e not in s[:i])) ``` Did it without regex, I am happy [Try it online](http://ideone.com/mTZrPM) [Answer] # Lua, 94 bytes ``` function c(a)l={}return a:gsub("%S+",function(b)if l[b]then return""else l[b]=true end end)end ``` [Answer] # awk, 25 ``` BEGIN{RS=ORS=" "}!c[$0]++ ``` ### Output: ``` $ printf "cat dog cat dog bird dog Snake snake Snake" | awk 'BEGIN{RS=ORS=" "}!c[$0]++' cat dog bird Snake snake $ $ ``` [Answer] # JavaScript, 106 102 100 bytes ``` function(s){o={};s.split(' ').map(function(w){o[w]=1});a=[];for(w in o)a.push(w);return a.join(' ')} ``` // way too long for JS :( [Answer] # [Hassium](http://HassiumLang.com), 91 bytes ``` func main(){d=[]foreach(w in input().split(' '))if(!(d.contains(w))){d.add(w)print(w+" ")}} ``` Run online and see expanded [here](http://HassiumLang.com/Hassium/index.php?code=2878e3a892c3343d45498b864ea2fea9) [Answer] # PHP ~~64~~ 59 bytes ``` function r($i){echo join(" ",array_unique(split(" ",$i)));} ``` [Answer] # AppleScript, 162 bytes Interestingly, this is almost identical to the non-repeating characters thing. ``` set x to(display dialog""default answer"")'s text returned's words set o to"" repeat with i in x considering case if not i is in o then set o to o&i&" " end end o ``` I didn't actually know the considering keyword before this. *the more you know...* [Answer] ## Burlesque, 6 bytes ``` blsq ) "cat dog cat dog bird dog Snake snake Snake"wdNBwD cat dog bird Snake snake ``` Rather simple: split words, nub (nub = remove duplicates), convert back to words. [Answer] # Gema, 21 characters ``` *\S=${$0;$0}@set{$0;} ``` (Very similar to the [unique character solution](https://codegolf.stackexchange.com/a/62096/4198), as there are no arrays in Gema, so allowing built-in unique functions not helps us much.) Sample run: ``` bash-4.3$ gema '*\S=${$0;$0}@set{$0;}' <<< 'cat dog cat dog bird dog Snake snake Snake' cat dog bird Snake snake ``` [Answer] # Scala, ~~44~~ 47 bytes ``` (s:String)=>s.split(" ").distinct.mkString(" ") ``` **EDIT**: using `toSet` might not preserve order, so I'm now using distinct // that just cost me 3 bytes :( [Answer] # PHP, 37 Bytes *Assuming `$s` is the input string.* ``` print_r(array_flip(explode(' ',$s))); ``` ]
[Question] [ Given a positive integer \$n\$ and another positive integer \$b\$ (\$1 < b < 36\$), return the number of digits/length of \$n\$ in base \$b\$ ``` 1597 16 -> 3 1709 9 -> 4 190 29 -> 2 873 24 -> 3 1061 27 -> 3 289 26 -> 2 1575 34 -> 3 1135 15 -> 3 1161 22 -> 3 585 23 -> 3 1412 23 -> 3 1268 14 -> 3 714 12 -> 3 700 29 -> 2 1007 35 -> 2 292 17 -> 3 1990 16 -> 3 439 3 -> 6 1212 17 -> 3 683 31 -> 2 535 25 -> 2 1978 32 -> 3 153 8 -> 3 1314 33 -> 3 433 2 -> 9 655 35 -> 2 865 19 -> 3 1947 25 -> 3 1873 32 -> 3 1441 12 -> 3 228 30 -> 2 947 2 -> 10 1026 11 -> 3 1172 24 -> 3 1390 32 -> 3 1495 21 -> 3 1339 10 -> 4 1357 9 -> 4 1320 27 -> 3 602 5 -> 4 1462 16 -> 3 1658 9 -> 4 519 11 -> 3 159 3 -> 5 1152 11 -> 3 1169 33 -> 3 1298 7 -> 4 1686 32 -> 3 1227 25 -> 3 770 15 -> 3 1478 20 -> 3 401 22 -> 2 1097 7 -> 4 1017 9 -> 4 784 23 -> 3 1176 15 -> 3 1521 7 -> 4 1623 23 -> 3 1552 13 -> 3 819 15 -> 3 272 32 -> 2 1546 12 -> 3 1718 4 -> 6 1686 8 -> 4 1128 2 -> 11 1617 34 -> 3 1199 34 -> 3 626 23 -> 3 991 9 -> 4 742 22 -> 3 1227 11 -> 3 1897 12 -> 4 348 35 -> 2 1107 11 -> 3 31 26 -> 2 1153 26 -> 3 432 4 -> 5 758 9 -> 4 277 21 -> 2 472 29 -> 2 1935 21 -> 3 457 27 -> 2 1807 26 -> 3 1924 26 -> 3 23 27 -> 1 558 30 -> 2 203 15 -> 2 1633 8 -> 4 769 21 -> 3 1261 32 -> 3 577 7 -> 4 1440 22 -> 3 1215 35 -> 2 1859 23 -> 3 1702 35 -> 3 1580 12 -> 3 782 15 -> 3 701 32 -> 2 177 24 -> 2 1509 28 -> 3 ``` Shortest code in bytes wins. [Answer] # [JavaScript (V8)](https://v8.dev/), 21 bytes ``` b=>g=n=>n&&1+g(n/b|0) ``` [Try it online!](https://tio.run/##TVTbThsxEH3fr5gHhHZFAM/Y47FVbX6kqkoCgaZKF5REFInm29Nx1hdeEk88lzPnHOf36n11eNxv34637@H8PJ7X4/JlnMbldH2NNy/9dL/@Z4bz31/b3Qb6A4yw36yedttp0w8DfHYA36cFrBfwcwHHH3p9uDu87bbH/h7uh7s/q7f@A8Yl3HwM3zR3rwnP/Xrop0v4@DodXnebu93rS/9w9Tmd4OpzfYLbpX7vT9Dr5zgeT8ODZp/OyFEAfbq2HYqJENPZdRgN0OVMXRAL5HKO8Qgkc0AhAvk5CVkYbMlCy4BcglRCc8CBgWy@cEgtIB8Ac73oAXOFmIYEjRGwPAcUCTAjwah4yx7ORrh09doVW5IPFizOxaxdKDfCKAFsHodsIeSjVRjWlqZKQjrGzjNXEMHrorGAcJKbapBYq02dw7oQkU4zc/mlIh3R6HLKJWIhTaiRbnW71isq9JJmdVc0WTPLUvWzZKpO3hBw/t15aoJ7DqWAdYs6nDOBrDiYvoDysRKCFANI7uqDbwCJGg0iphnBKc9kMp@mmCLJqi4srQzWJSS45g8U3zqxElBna0rN4gQ3ByGtlCtI6bRlHDtf1UDBAC67Ja0RcltUmWZpUC8UVDN3jDXwqlkZHiNW5I6q5S98VApDenA0Z1kXqpEQTctSl9Z3lQxJ1dk0Y@VOmnQkkg1BnUu2Ka8l2uYUp96Y/aAXQWeVnhjVZiVIVF6SsGNuNiVjM5Na7K0tJIn6oVqR9JkXD7A0QZ0zX7jA9nYwqM@qcqImtVXfYNofQKAqoxhsMqa1XZFU/7oov9v/ "JavaScript (V8) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 28 bytes ``` f=lambda x,b:x and-~f(x/b,b) ``` [Try it online!](https://tio.run/##RVSxblsxDNzzFW90ABYVSVGUAvhLggw20qABXCdwPLhLf90lJVGZTDyfeOTdSZ9/r78/znS/v@1Phz/H18N2g@PTbTucX3/8e9vdfh7h@Hi//vq6fm3752eUpoAF@AWeUVODBtnLloAakJVVGSgPQCoIpL2man@XjkBRAZ4QZAGUWTucei1VgHh8zkirplIBx1G1XxxoTYseUzJC6TU1Ahz02GzCOXfmBgylt8OFKNUosJ8TPz9aYNMKPFhQGOqo2Gfg2c32heYdRIK5FtuqTeas3q3XLk50yxljfiLrm/rJjgZMfRUTDHFqo7RkZdtldWnGODFsi2EahrBoeMOUwoWSCGR8zYWWkUXqBItNHZTiMkknF/oepLRYHalV0NGu1LJmIlobq6ZlbzYpbZQuWupOD8MsUbNJwhhaa16eo5bVQ2zXYLT/AyI@4KirbzDQZJrxZJFcQm1UrJBHAHzsOvqhmeBr9s8eikhoa1EXT/CgaQ1j1EyR2r55CFX9plCHcK6RDMS0IB63eSU8WxTxtENdd122kKq77NDsQZhZb7zMz@a3y96ZjWI2w2ahmbXrZdzusqy8UWKXq58rzFMMNZMjVWS3cjoruqzKOX1vjSv4WC014Ypa2jiMq2nd1krhkCZcDvmKeZplD4tfiZeXh4fPy/v5ujucTjt7jewt2u8v29vHxZ8puGzv562/TY@P9/8 "Python 2 – Try It Online") thanks @Kevin Cruijssen for -1 byte by using python 2 instead of python 3 [Answer] # [Zsh](https://www.zsh.org/), 20 bytes *My first Zsh answer, cobbled together using [these](https://unix.stackexchange.com/a/191209) [very](https://stackoverflow.com/a/31328257) [helpful](https://codegolf.stackexchange.com/a/226010/92901) [posts](https://codegolf.stackexchange.com/a/15280/92901).* ``` <<<${#v=$[[##$2]$1]} ``` [Try it online](https://tio.run/##qyrO@P/fxsZGpVq5zFYlOlpZWcUoVsUwtvb///@Gppbm/w3NAA "Zsh – Try It Online") or [run the test suite](https://tio.run/##TVRrb1oxDP1@f4Ul2KBaobEdx8lUth/SVetTWqUOqsEmbcBvZw43j35BMdeP43NO8uv3w9/T4@bpeTU7XV9fT/eTP6vpzc1kMqXbKd4eT7Nh97zdbVcf5ihJAQMsvgAPqC5Bymc/YHJA5zMNURnIlxwXEEjHgGICCmMSigpwzUIWQKlBLqExkChAXD54pB5QiIClXu2ApUJdR4LOKbCMASUCLEgwGd66h@cE567BumJPCpGBcSwW60KlESaNwGUcCkMsRzYYzLWpkZCPaQgiDUQMtmiqILyWphZk1lpT77EtRGTT3Fh@rshHdLaccYlYSVPqpLNt13slg17T2HZFVzRj0aYfk2s6BUcg5X8fqAseJNYCsS3acCkEiuEQegcqpEYIUoqgpWuIoQMk6jSoum4EbzyTK3y6aoosq7mwtnLYltDouz9QQ@8kRkCbbSktSzLcEsS8Uqkgo5PrOPGhqYGKEXxxS14jlrZoMo3SoH0wUN3cKbUgmGZ1eErYkHtqlj/z0SiM@cLRmMU@NiMhup5lLm33KhuSmrNpxCqDdulItRiCBp9tU29L4u4Ub94Y/WAfos2qPTGZzWqQqTwn4SDSbUqOC5NWHJgrSWp@aFYku@bVA6JdUO/dOy6w3x2M5rOmnJpJuekbXX8AIjUZ1WGXMa/tq6T2dNF4by@Wry/r5@3y5/3b/rA77Jbbx/v1/Orb06eri/zn/OPn3eb7y8VxeIPzO7i8f339uj@sL@HhEjYHuPu3/QGLR5hN9vkVPc5gsYDJfn20n4fj3TJXr1ab4@k/ "Ruby – Try It Online"). Full program taking \$n\$ and \$b\$ as arguments. ### Commented ``` <<< # print ${# } # length in characters of v= # set dummy variable v to $[[##$2]$1] # n ($1) in base b ($2) ``` --- Here's an alternative offered by @pxeger. The byte count is the same but the dummy variable is elegantly avoided using parameter expansion. ``` <<<${#:-$[[##$2]$1]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZbbGxsVKqVrXRVoqOVlVWMYlUMY2shUlAVq6INTS3NdRQMzWKhIgA) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 2 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each) ([SBCS](https://github.com/abrudz/SBCS)) Anonymous tacit infix function taking \$b\$ as left argument and \$n\$ as right argument. ``` ≢⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HnokddS/6nPWqb8Ki371FX86PeNY96txxab/yobeKjvqnBQc5AMsTDM/i/oZlCmoKhqaU5lyWIYW5gyWUEZlkacBmZABkW5sYA "APL (Dyalog Extended) – Try It Online") `≢` tally the digits of `⊤` the anti-base (i.e. the representation in the given base) Note that this is wasteful in that it actually does the base conversion. ## [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 bytes Anonymous tacit infix function taking \$b\$ as left argument and \$n\$ as right argument. ``` ⌊1+⍟ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPl6H2o975/9MetU141Nv3qKv5Ue@aR71bDq03ftQ28VHf1OAgZyAZ4uEZ/N/QTCFNwdDU0pzLEsQwN7DkMgKzLA24jEyADAtzYwA "APL (Dyalog Unicode) – Try It Online") `⌊` floor `1+` the incremented `⍟` log Implements \$⌊1+\log\_bn⌋\$. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~4~~ 3 bytes ``` ljF ``` [Try it online!](https://tio.run/##K6gsyfj/PyfL7f//aENTS3MdQ7PYf/kFJZn5ecX/dVMA "Pyth – Try It Online") ``` # implicitly output l # len of jF # convert first element in input to base second element of input ``` -1 byte thanks to Mr. Xcoder [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes ``` IL↨NN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyc1L70kQ8MpsThVwzOvoLTErzQ3KbVIQ1NHAYULAtb//xuaGlgqGFn81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Works for any `b>1`. Unfortunately `Base` doesn't accept implicit arguments, so I have to explicitly input the `n` and `b`. Explanation: ``` N Input `n` as an integer N Input `b` as an integer ↨ Convert `n` to base `b` as an array L Take the length I Cast to string Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes ``` \d+ $* +`\b(1+) (\1)+1* $1 $#2$* ``` [Try it online!](https://tio.run/##LZI7jhwxDERznoKAx8DsTiJ@JIon8CUmWBt24MSB4fvPVqkdCd0Ui1WP@vvr3@8/319f798@Xs@fD7m9y@Pj@eNujze9P@3tYe@iN9PbF0dJXy9barNLWq1Gi@PsIZ66K8RLbSwTX@q7JRJ3a4pNNYsp7jhZDp178rA0F8M1X1vMtSwpWWNIoGmMEiv1xiXMbUwKzWj@NEdrmK6NuVMn9AP6XVs2xoYE5IN66AjKrQkrrXtNNlhnnQ4ax2jLNImh7hstLJrBgS@GMys/l4Nh8T8bWgPfMAMEMeuEDx@CQePym8tZXHNTaxqIEN4RtunHoa0Whul99Ndex5x7EVsVxmFMIhXo5TBeHhf/YUWGtfMiXIvF6QewLUcszsMglDenuzpyMOzMJYhVdmidqVBAdO5sQZgngFNqgUFrt9FCpR//xyDpwQvYRu4rFjaG7cd5A8Y1JPATQ4ECyHkVN5zwQY7NZ1Ga87TZvtqtPfkbEbCRSX5TfcTximWis9bJg4dDJJOqZ4fXw3G7ntcGbX7X@B97j4N1n20WcHK5bOabGf0J "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in the order `b`, `n`. Explanation: ``` \d+ $* ``` Convert `b` and `n` to unary. ``` +`\b(1+) (\1)+1* $1 $#2$* ``` Repeatedly integer divide `n` by `b` until `n` is less than `b`. With each division, prefix a space to `b`. ``` ``` Count the total number of spaces, including the original space. This gives the desired answer. [Answer] # [Ruby](https://www.ruby-lang.org/), 21 bytes ``` ->n,b{/$/=~n.to_s(b)} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ6laX0Xfti5PryQ/vlgjSbP2f4FCWrShobmRjpFJLBeEY2ShYxT7HwA "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` вg ``` First input is the base \$b\$, second input is \$n\$. [Try it online](https://tio.run/##yy9OTMpM/f//wqb0//8NzbgMTS3NAQ) or [verify all test cases](https://tio.run/##NVO5jZRRDM63itHGDp6vZ78AUchopGUlhEggQELaBiiAUmiAgAaogUYGX5PMWM/Xd/j/@u3D6@eP9@9vL8@v7/78hsuX@L38@/Hz8vz@7eX@99enO9yvV9RjgPsGV7R14GRwFlAGbgwk@bI2AllE5AeoqtUUuJLICqgVZRlFpK5AnE@CNBFtB8wGQwHMKluzCNcy4BxBhwCtQASKwiV8oAfg5LYzMOaa2Ey1@ZgDU@Fi8Pzn2MJc/cEiu1R7h@/A20TFpj@pdr8INjqiGLkiqKpCSRsQi6jRKMMBcxpPgKksB2JcFam1pEyrBdyLoDbKptF9q1eR4pnxOoxR6bFwn2aDdBxKoO17NhMNDbM1TkjoQQlB1liCK4yuxoUNylzGGrQ9fUo404knqQkiI098ZVKwH7Flt1ho6CAPWGUAhn6V2rFvLuWcjnYoWdPPwcYiNDCTTHP2vMx8Y/F2DnFNknHOMP2mPhMqADZqklnbIelV283jkIQt5QZ6DOxBh6SjJJ451fGfFo86m/u4LNxoqykuvqRQG3VF1oMJzsGhh6EtpoX9/aa@5itw6vG2ZhYm9BJM45Mkv92env4D). Using logarithm like most other answers is **4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**: ``` .n>ï ``` [Try it online](https://tio.run/##yy9OTMpM/f9fL8/u8Pr//w3NuAxNLc0B) or [verify all test cases](https://tio.run/##NVO5jZRRDM63itXGFnq@nv0CoJDRSMtKBCRLgIS0DVAAjVACwXZCI4OvSWas5@s7/H//8eXl29fbz7fnp5eP73/h8TV@H//9@v349Pnt@fbh9dP7nxvcLhfUY4D7Che0deBkcBZQBm4MJPmyNgJZROQHqKrVFLiSyAqoFWUZRaSuQJxPgjQRbQfMBkMBzCpbswjXMuAcQYcArUAEisIlfKAH4OS2MzDmmthMtfmYA1PhYvD859jCXP3BIrtUe4fvwNtExaY/qXa/CDY6ohi5IqiqQkkbEIuo0SjDAXMaT4CpLAdiXBWptaRMqwXci6A2yqbRfatXkeKZ8TqMUem@cJ9mg3QcSqDtezYTDQ2zNU5I6EEJQdZYgiuMrsaFDcpcxhq0PX1KONOJJ6kJIiNPfGVSsB@xZbdYaOggd1hlAIZ@ldqxby7lnI52KFnTz8HGIjQwk0xz9rzMfGPxdg5xTZJxzjD9pj4TKgA2apJZ2yHpVdvN45CELeUGegzsQYekoySeOdXxnxaPOpv7uCzcaKspLr6kUBt1RdadCc7BoYehLaaF/f2mvuYrcOrxtmYWJvQSTOOTJL9eHx7@Aw). **Explanation:** ``` # First (implicit) input-integer = `b` # Second (implicit) input-integer = `n` в # Convert n to a base-b list g # Pop and get the length of that list # (after which the result is output implicitly) .n # Log_b(n) > # +1 ï # Truncate decimals # (after which the result is output implicitly) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` IntegerLength ``` [Try it online!](https://tio.run/##TVRNaxsxEL3vrxiWHlrYEM1Io5EICSmkhUAPhRyDDyY4zoJjB3cLhZDf7o6sr9w0q/l4897Tvq6Xl83repmf1qfn69P9ftlsN8dfm/12eTndHR6H93k6fMA17Ob95mqY9fTzeHi9m7fz8ufy9mE5zvvtw9tuXh7naYRxdTX81k8aXdw8396mb1/H6TCN38bVML2nLlMu@vFvOa6flscvD0/H@W2537/9XfLNNA7jxc333W6CES5uIAerj9UJOQqgTx/tgGIixHR2A0YDdD7TEMQCuZJjPAJJDihEIJ@TkIXB1iy0DMg1SCWUAw4MZMuFQ@oB@QBY6kUPWCrEdCRojIDlHFAkwIIEo@Ktezgb4dzVa1fsST5YsJiLWbtQaYRRAtgyDtlCKEerMKytTZWEdIyDZ24ggtdFYwXhpDTVILHWmjqHbSEinWZy@bkiHdHocsolYiVNqJNudbveKyr0mmZ1VzRFM8vS9LNkmk7eEHD57jx1wT2HWsC6RRvOhUBWHEyfQPnYCEGKAaR09cF3gESdBhHTjeCUZzKFT1NNkWRVF9ZWBtsSElz3B4rvnVgJaLM1pWVxgluCkFYqFaR02jqOnW9qoGAAV9yS1gilLapMWRrUCwXVzR1jC7xqVofHiA25o2b5Mx@NwpAeHOUs60IzEqLpWerS9q6SIak5mzJWHqRLRyLFEDS4ZJv6WqLtTnHqjewHvQg6q/bEqDarQaLynIQDc7cpGVuY1GJvbSVJ1A/NiqTPvHqApQvqnPnEBfa3g0F91pQTNalt@gbTfwCBmoxisMuY1nZVUv11UX63/wE "Wolfram Language (Mathematica) – Try It Online") Of course there's a built-in. Input `[n, b]`. --- ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` 1+⌊Log@##⌋& ``` [Try it online!](https://tio.run/##TVTbahsxEH3frxCbUlq6ppqRRiMRElxIC4U@lPrR@MEEJ11wYuNsSyHkB9p8ZX7EHVm3vGlWM2dmzjnau/X0c3O3nsbr9fHm4ggfXp7/ftvdzs/OXp7/vT1e7Zbd4zjsntSF2o73m/NulNOXw@7uarwdp4eP88V0GO9vF/vtOC3HoVf96rz7Lp8kml3ezOc/Nr83h4fNPN6964fd0L/vV93wGNGGVPz5z3RYX0/LN4vrw7ifvt7vf03pZui7fnb5absdVK9mlyoFq6fVESiwAhc/mg5YBxXi2XYQtMLTGTvPRqHNOdqBQk4B@qDQpSQgJmVKFhhSQCWIJZgC8qTQ5AsL2AJ0XkGuZzlArmDdJgGtWRlKAQZUkCeBIPOWPawJ6oTqBBVakvNGGUjFJCiYgSCwVya3AzLK56ORMYwpoEJCPIbOEdUhvJNFQxnCcgaVILJWQa2FuhCidNOp/FQRj6BlOeESoJDG2Eg3sl3DCjJ6STOyK@ismSGu@hnUVSenUVH@bh02wR35UkCyRW1OmUCSOQhfDeVCJQQweMUZ1XnXBkRsNDDrZgQrPKPOfOpiiiiruLBAaahLsLfNH8CuIZEQUHtLSs2iOG4OfFwpV6DQaUo7sq6qAQxe2eyWuIbPsCAyJWlALmSoZu4QauBEs9I8BKiTW6yWP/FRKfTxwWHKMtZXIwHoliUure8qGhKrszHNSh036ZA5GwI7G21TXkswzSlWvJH8IBdeehVMCGKzEkQqT0nQETWbojaZSSl2xhSSWPxQrYjyzIsHiJug1upXXEB7O@DFZ1U5FpOaqq/X7QfgscrIGpqMcW1bJJVfF6Z3@x8 "Wolfram Language (Mathematica) – Try It Online") Not the built-in. Input `[b, n]`. [Answer] # [Japt](https://github.com/ETHproductions/japt) v1.4.5, ~~4~~ 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` slV ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&code=c2xW&input=MTcwOQo5) [Answer] # [Factor](https://factorcode.org/), 16 bytes ``` [ >base length ] ``` [Try it online!](https://tio.run/##VVTBjhMxDL3PV5gPYBXbcZyA1CviwgVxQhyGara7EtuWmdkDQnx7cdpO4r3N0zj28/OzH8f9epov375@/vLpA7yM69PDeZyXaYZl@v06HffTAud5Wtc/5/n5uMJhPr2en48HGJfltF/g4zD8HVCKAiZ4B@93wANqKFBuKA5YAtAd0ZCVgWKLDAmBdIOUC1DaQlFUgHsssgBKh/UpbVCyAHH7GZE8pJQBWya1T2wvNXh@GIICywapEGDjh8V66X1GLnCvkawG@tCUGRi3NGIZqSXFohm4EUBhyA2wkWPuJUyuGyhDEnHUcjI5SqcWtZUwWHV2JWJE1zKR1Q9bouvLG8BgAtgEELvMSn5gbAr4vMUa68FsimBok2dR5wOm4GadAoG0fzGRN1CS3B@KdekISRNdjJ3QG7KpOPGQSgZtNVJOnjqRF0w1eHNFmxCFNoXQrVYtYm7vaQO6JjVH7zvU5LOKSeX4WKCLldpKg7k23V6SDYE7AYnJTRMVM8Tmw9pmbkXQRr0NF@2nkfUrVYqDySbfCZWCrq9Ibtmu2jnZc11/2mI5ZmdTxOBjbSfchlfrk9sn2vqQQb0FSLXZjIZYLdk3trD3YDTPbS6zn9mq9wpYzMod1gHcQ3EQ8UtBgZv@liYxd1HVXOZMT3aIuq9EvTliDG90Q7/BmM3LzgFqK8HOLTn4M5XJGUIDekNUeWK3h51fahfln83/erUv32H3c1wm@DUdD@sT/Lg83q747mU8w8PlPw "Factor – Try It Online") It's a quotation (anonymous function) that takes a number and a base (in that order) and returns the length of the number in the given base. * `>base` Take a number and a base and return the number in the given base as a string. * `length` The length of the string. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` τL ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CF%84L&inputs=4%0A1200&header=&footer=) Simplest method `τ` does the base conversion, and `L` gives the length. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` bL ``` [Try it online!](https://tio.run/##y0rNyan8/z/J5////4YGBkAMAA "Jelly – Try It Online") Finally, a Jelly answer using ASCII only. ``` bL - Main link. Takes a number on left, base on right b - Obtain left base right L - Get the length of the string representation of the result ``` [Answer] # Pascal, 20 characters Plain translation of the formula: $$ \left\lfloor \frac{\log\_c n}{\log\_c b} + 1\right\rfloor $$ ``` trunc(ln(n)/ln(b)+1) ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 25 bytes ``` f=(n,b)=>n<b?1:1+f(n/b,b) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI08nSdPWLs8myd7QylA7TSNPPwko8r@gKDOvRCNNw9DIwEDHRFPzPwA "JavaScript (V8) – Try It Online") # [JavaScript (V8)](https://v8.dev/), 26 bytes, thanks to Adám ``` n=>b=>n.toString(b).length ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9YuydYuT68kP7ikKDMvXSNJUy8nNS@9JON/AZBfopGmYWhkYKCpYaKp@R8A "JavaScript (V8) – Try It Online") # [JavaScript (V8)](https://v8.dev/), 32 bytes ``` f=(n,b,x=1)=>b**x<n?f(n,b,x+1):x ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81WI08nSafC1lDT1i5JS6vCJs8@DSKkbahpVfG/oCgzr0QjTcPQyMBAx0RT8z8A "JavaScript (V8) – Try It Online") [Answer] # [R](https://www.r-project.org/), 27 bytes Or **[R](https://www.r-project.org/)>=4.1, 20 bytes** by replacing the word `function` with `\`. ``` function(n,b)log(n,b)%/%1+1 ``` [Try it online!](https://tio.run/##VVTbbtswDH33VwgeCthYuomkKErbOmDf0fUhDZIigJEWsQdkGPbtGRXr0j2FjMkj8pwjna@Hh@vh12m3HF9Pw2nzPE6vL7ffu8938BGuhwE4ygb8aD6Y@@@Gum63XYb@xzSZZT8v97vtvJ@//Dz1Y7edpmHevr1Nv4d5Oc9v03EZ9lOL@wRlwK84IDaamGLXQbQGbzF2QcigyzXWg0FZEwzRoF@LgIUNlSogNsAlSS24JhzYIOUPDrAl6IOB3C8aQO4Q2yYBa8UQrwlGNJAngajzlj0cRXND9YoKrcgHMgRrMysKZiCIEgzl44DJhBySjkFUQJWEFMbOM9chgtdFYxnCSQbVJLFWQZ2DuhCinmbX9ltHCsHqcsolQCFNsJFOul3Dijp6KSPdFWzWjFiqfoS26uQtGs7/O49NcM@hNLBuUQ/nTCDrHIzvhvKxEgIYg5GM6oNvAyI2GkRsM4JTntFmPm0xRZJVXVigLNQlJLjmDxDfkFgJqGdrSa3iNG5OQlopd6DSSeU4dr6qAQLBuOyWtEbIsKAyrdKAftChmrljrIlXzcrhMUKd3GG1/I2PSmFIFw7XKnKhGgnAtip1ab1XyZBYnY3rrNxJkw5FsiGwc8k25bZEak5x6o3VD/oh6FkFE6LarCSJylsRdMzNpmgpM6nNnqiQJOqHakXUa148wNIEdc6@4wLa3YGgPqvKiZqUqr7BtgcgYJVRLDQZ09quSKpPF673tt/06fEbN31K@3HT1ef0Mv5Zvt1v50/H07J/2Z//ewwvj/CkPdo5fj0MS8qWR3waHx7eNVzSP3/H8foP "R – Try It Online") [Answer] # [Raku](https://raku.org/), 21 bytes This solution works with `n = 0` ``` {$^a.base($^b).chars} ``` ``` $^a and $^b are implicit when you call a function with 2 arguments This is similar to if you call a function with 1 argument That function will have implicit topic variable $_ ``` [Try it online!](https://tio.run/##XY7daoNAFITv9ykmEoqCimfXdZWi6W2foTawRm0LSQxqKSH47Hb9SQu5WJjvnJk5e6naYzSerniqkY637V77he4qe7svHP/wqdtuGJ8ZM4aXvup672CWnm5bpDh@navOP@mL7WXIJ8KNYR77P01bdm@BS654zzL/9dyzwTE9ddM@FpmwnWsXeWFe8907c0unr6htMy4cpCnMHLsdrI@mKS1sNrAKXVpsGAPwqYFYACEXRTJRoGgCwUgFCZJJh4wS4541Z7ES4OHqCSICVwvwOAGPFhNJJSHuLjIHSN5hivAFZCzBxboIif8Dj2LQmldG0JpQwd9PfgE) [Answer] # TI-Basic, 12 bytes ``` Prompt N,B 1+int(log(N,B ``` Output is stored in `Ans` and is displayed. If not using OS 2.53 MP or higher, `log(N,B` should be replaced with `log(N)/log(B` to add 2 bytes. [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` YAn ``` [Try it online!](https://matl.io/?code=YAn&inputs=1718%0A4&version=22.7.4) ``` YAn YA : dec2base n : numel/size ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~23~~ 21 bytes ``` f(n,b)=floor(log_bbn) ``` [Try It On Desmos!](https://www.desmos.com/calculator/rktssbfzcp) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/f9qeravcfx) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~26~~ 25 bytes ``` f(n,b){n=n?1+f(n/b,b):0;} ``` [Try it online!](https://tio.run/##bVXtbhoxEPyfp7CQIpHkUOy1fbZLaX9UfYoGVYEcKWpyiQCpqBGvXrqz9sFBgu4W337Mzs6eYD56nM/3@8WwrWZXb@2k/Wpu@OF2xo@f9Hi3X7Yb9Xy/bIdX6u1C8QeOTbPe/Gx/TNVEvRmfQqVM0Ilt0pWKwfJJ16ZSFOH0wbM1VizcPuLoDLGlOlYqGMdGa9RpRqOEUAKas4Ag5NaRgb3ApBABjEYWtc7ysfYcirXEHThlJs6BCXFB9mqqQSSghUUL4xJqrHSyHjmW2F9rpLgatvZc742MA2M8yTRCLoFMHQFLxOUhCCo4Om3QUiTSBrHopDuSPSFYE1h6AEY0IGHmHTKCOUIbkjNADGvD/DBISowRHHW9TUQv65BroKU1QtdCJM4KGIQCB5z0SdDTydAR6SYREwQlL5ka5GrIG/KwskDUs7BaVgPxoqgSRDEfNeZEM5lekr1Ou/HpCzQrLxCmwM75Rmvsv8YIqMLmMh1RCT7KufIeABm5@YhRid2Yk7mDNJXEdIwAwGoJGZN7wi270JkKY/mMnHKSLV@QoaT7Qk9niiFX2uwN5Vgeu7ZOeFEezhadUwYAvunomqwBbpczTFHIHBWSO@Rh0CXmsM1sqGChhWDSkYvoHHv7aLavzXzTPOSNWOlKMrbtHc4u6oXqd54y2bsSaNx3ObnsqfW96Fm96zndaSjzcIeVnSUdZqKuh@tRPjA1nfOsDX04fRFx/ut@dc22mf9uVlnFwd32O91t0ze@/aBS/Wc7KHWLl5UaYgPL9qHZcpkel@NntV7@bV4Ww243V7fFcX3wjNXNjWR3P87dPltGKj/SEp@OT8KzLjz7MLzmcP5HOPU37D@8KeeFrytOWQwHlw@Kr9EX2Mv1XcuTt5WaVWpdHfRZTybNtIDvLnb7f/PF0/3jej/6sx89Pf8H "C (gcc) – Try It Online") For input positive integers \$n\$ and \$b\$ returns the number of digits in \$n\_b\$. [Answer] # Java, 30 bytes ``` n->b->n.toString(n,b).length() ``` [Try it online!](https://tio.run/##hY8xb8IwEIVn8itutCtilYGiCBqJBakDYkCdqg6X4ASnztmyL0gR4renRrB06i337u59T7oOL5h3p5/J9N4Fhi7NamBjVTNQzcaRellnfqisqaG2GCPs0RBcM0j13EdGTu3izAn6dBVHDobar2/A0EaZzLPdM23zQaxbHeaQxCdhGA9eB2QXSmjeJ8rLKi9JsXtECJpXUllNLZ@FnNbZ7DhG1r1yAyufHGxJNAq9t6NYLIuVfOhtTPFi8SblP8jqtfiDFHfi/totu02/) [Answer] # [Rust](https://www.rust-lang.org/), 40 bytes ``` |n,b:u8|(n as f64).log(b.into())as u64+1 ``` [Try it online!](https://tio.run/##hVTLbttADLzrK5gcEgl1jSX37TQ59BN66KUoAtuRC6Ou7FoSWiDJt6dcaR9GgaK2Ie9K5HA4nNV57Ie3sW@hH55Wq/1xtfo47j6166e7atfBj/W@qxt4hkM7wO7@7aVbbFaje6k7WPewM6pZHo7f6s1y3w3Humn45mjUO3zj7OMZDvuuhX1XsHkRADlp@z388fM@4FcwVai7BWwW0P4@tduhfWrgHk7rc98@7rvTONQ3IX45dr/O6xMXu4tZ57YfDwPH7jh/M90@nZnQobuqr59fgX/vH/h6vYAZf06YAtd9356Hx/bnVT3fvah@V73yN8hwSSJwWMFNP5ybAFtzv4vRLfhv7mPmxBlDv4LP7fbD4wNTm5j3p8N@qG/htlluj4cDV6knEgD1dA2fKfGL@LqcarJGqd3FXyH4/xD5r5Cmen1D7S2gCT3ICq3w4MNaVegF0LSmylkJpGKMMAhk5w05D2TmINRWg0xRKDWgTpuQQvNGOw0k4wOFVDZkHGDMt7zAmGFFYYJCWJB63pAnwMgEPfNNfSjpYUI1jIolyDgJEudkzSgUgdBbBzKWQy3BxaVkGlImUBYhLH1ltM4knOFGfSKhbATlTVAtgyqFuSEiribm9CkjLFFwc6wlYhLNUhFdcncFyzP1FCa5VxRxZlLbPD9JIs/JCAId7ytDZeBGu5SguYtcXEcBNfPQdEHK@CwIkndgI6pxphAkKjJYK4oRFOtMIuopkinCWNmFCUpgbsI6VfyB1hQkzQLk2hySo3SgGzcutBQziOWUqZxWJk8DLTpQ0S2hDRdhkcc0jwb5AZMq5vY@bwzPLBX3HjNzRdnykx5ZQhcOHM1RUrlsJERRotil@VwFQ1J2Ns1cdWXL6MjaaAiqVLBNOi1eFqco9sbsB37guFbCRM82S5sg5RSEldbFpiRkVJKTjZRJJMt@yFYkPubJA9qWgSolLrTAcnbQsc/y5CybVOb5OlFeAI7yGK3AMsbQtkoj5VcXzef2Dw "Rust – Try It Online") Unfortunately the typecasts are neccessary because the [`int_log`](https://github.com/rust-lang/rust/issues/70887) feature is not yet stabilized. With the feature the code could be shortened to ``` |n:u64,b|n.log(b)+1 ``` [Answer] # [ErrLess](https://sr.ht/ruan_p/Errless/), 27 bytes ``` 0m:1$@;<2+]{@;/$;$!0"+0}!.M ``` ## Explanation Basically copied [this](https://codegolf.stackexchange.com/a/236859/91340) JS answer. A [macro](https://man.sr.ht/%7Eruan_p/errless_docs/reference.md#-procedures-amp-macros). Note: ErrLess doesn't support floating point numbers, so all division is integer division. ``` 0m {...} M { Define a macro identified by 0 } : { Wrap input in a stack: ((b n)) } 1$ { Add one to the stack, before input, used later: (1 (b n)) } @;< { b < n? } 2+]{ {...} } { If not so, } @;/ { (1 (b n) b/n) } $;$! { (1 b/n b) } 0" { Recurse (yes, I'm using `"` to call the macro...) } + { Add result to the previously added one } 0 { Add dummy value to stack } ! { Pop top value of stack, either dummy value or unused arguments, depending on if above code executed } . { Halt (return), basically returns either 1 or 1+recurse(b/n, n) } ``` [Try it online!](https://tio.run/##1VvpcttIkv7PpyjL3U1AIikAvGnTbY@vUYxteW3txk7THA4IFCXYIIAGQJuUxv1zHmAecV@kN7MOoHBQUh/a6VWEaaJQlfnlWVkHo116EQbdURT/fJ@8oKlzQV2yisM1uUjTKJkcH597aSeJOxfp8U/xxg4W0TGNY58mySKmq@Q4jSk9XttecOyldH289M69IF1sAs8JXXoccfJySCfakcdkQN6En@l6SWNiGZbZaHjrKIxTYsfnkR0nVD4nu0R@Tb01bTQc304S4gXRpEHgz6Urslh4gZcuFlpC/ZXO2/EPHzuundpkSprNRtb/nKa@F9By95immzhQRh0h906Sul7QiantskH6bNI25wVijFCLJN4lnbZNhaK3Yo3kITEmN5PX9BwKIM46ziZIZP6gIE/@Fl9O5mUp4ip57Nj2aaDFul7A75U1EdBzYPHC9sEOFUgosJlD/XLh@ZTEHS9JItsB/eRkrhuWxrtiR9AV9AVDtZsTAeAs3tAHeynkzIMwJfEMrJKDIHbgZm0u@GNaBsbBHe2nrWqbUUKNyraKjDF3i0IztwSEAmgc5UOcKBkFvZI2b89G0K1Do5Ro/2X7G/o8jsO4RU4Cl27Z97JWOekZ@CFEArCHT3CfBhrUj8JI81vEy30ReHuJFySpHYBy4J3vJan@QZJEXWmaRx5NicEePPBYdBRf10kYEw2f@Rut7enk4VS@rUaP30H2HpdLgcmRUfrp3wht5s1rYSVgfETVItv/Q1QIByy3VSBxPCvfTlPWPQODnlMDKEsqM19IBgRn/OsKcFDwC@IriujQLVB2NcmC6gVDxRyAE0Y7lXsd57JyZ2wQ1RW@BWX7nLQbLjaaTDVM2IW2rVJbQWON3FvBnUfQDMbuOMMdMtwWGK4WGUe3wrFFdgpTu0WWGENVRi21cSca1fRuMyMv66MTOF22yBcOEb8hyksv4vzzZEF9pHQdDSHmpSJmNnA/c2BzqQzczWvUjLTLauNT7BsKci99OpHu9MWOXVDTVUaleQmpuvlDs5W3XGHLV7VFwxZdbVljy2vR8pV9Lm3nU5X8Djv@VR36FVuu1BYdWzS15TW2rDPyzAmST160cML1mkLSjeLwvEWiFBKskCqZ4lQjHT5wAIaJ1pWvRcY22XvnwsYwQyozIMKVGoCyWBp22GOSxl6AUxh25nOtmKqgX24vGI4zkBwlm77l6QI55M5Wy1bhdSSYKc7Jh0yZVQo@wtDCALPoSVn/r3X929hfdRUNYBwBdv3bDG1LoFG0LnSoah3JQacpKzBaBBLS9E0YSP3v1e8C/NH5hBkOu8xrFC3kppiRwYGB5oQ9TDNn7gg4gkTJMpxDxT7mnVhHE2rACUNqPgcxM@a8iGGvIHrLElSqp73WFsBbZIGVVG0k6JUBOe5F5Z0TBgB8Qys@wqF37CjCSQYB6UUP01BzeU@d3FO1m0@uZWFZfaYoB0qtFrOvjhIzRpN9aLAeKcEoo5hivGfKhieAfwO9SiCY14eBzHB/lDiQeG4fCO0/WiBIEfZHwtdfHgktvuz5wwaEFPr/dUSkmwiY/uIaE4dRTQ7e8tJmy2pNLg4TpUiJjalZC9TUpnGY2ikbFEY3l971FKsDwkgWrQAW9QHEcUFg7qGQrnE9ly2VwggDIKvoPZQ2toNzqpktSU4BA/UcJwCfrQIVb56bXK54WDOuehqlVmPO6Og1WjqP7aWWAG1FTbJ9oWVNLGSk48slKWLlA3AZwEboOETof8OdZYK@woJxgotndB1MRkyLULJtgmRCXM8BjbYfYQdRoG6CQt5hjffvk/dnT57@hZy@ff7uydnJ6Zv3DWknNgCSxATqxfvkaRg4YP0A/uXrAmYIgM6DImtf7mlnuaxofVsYny8LSy@X8mUxsgo5Ywad7LkarQmdFLssyRGx9bJYWybWE9blRon8/RLd6P9VyH4N5EJ3X3a19f1k/IpID5hI72lE49uYqQrergWP42e2OlMhCrFStpXMInHcYzjehlGuvxL7QvfHrPszTFuOihsXDHypzcKUD9cbtcpIa@ieM7ovIYqyMWF0rYFzNtkLHs7YJkO6yuhlxojvCrPuN/NUSYv/asn7jPwrGpynF4X9wZI/4JaIqqnK3tnZLuI7Z6WRbbOG6yuFKwlXJaEqnFXrFOjEjM47NncUdZLt4@S62WNdOfPkHZVcWeD2TuFWZ4dreQo219mixehjtdHYE9s54XnN@G94iH6xo1@dRQvhhyG7lNvVkM1feSkEv580iqxhUmwaptXt9QfD0dheOjCfcEk2eMSQ1AuDO7AwukXMQZ2uPzT5zAAVkO2kKhW5Lnywvw4uMApF3c9mpjpW77nazt6dvHnZKFSqiaxUa9bRYt0Ao/fwnSFjh9dJDiopmZm4Ta0kZzG5A71Mx0/iXXqxtlPPaVSRHvFpxXV/o30FQrY759vrpWtj7QIxvz3a6Tgz2nV6anM9bZYpmuTOILSvgbAQEXKuxnuZ4CYjOCHtrV4Ixxqah4zm642fepG/uzOxDq8R65hPUt5nz/31BRBb7dor6nqfy3usWU4XDrc9Pt4VXooc/gONQ0SReGEgcrkYYVwjp2C6X7xvuYZDd@OHv1m8dejeKN63v7N0wHO/dB8@SOtBt9/DereQUO31C0Vt3caWqsAyMz0N15Ede0kY1GSmKdPB8x83tu@ldxZEbfNQ206nO32/NR6KyiJJSHphB3eK5OF1QB6Juo1CqorvHssjBYu02J@89IuXUHJMXoXnUP765JRV7@AUSY0Nf@LJ9fTsVpn1p5sz63d8unrz7M6S6nfXJNV/MO6n7@6M@T@uYf43xvy/75D733YVe5@mFzSuMWzKY8JLU5@Ss7tChAXd9tA0Dg@vC4szhuVP3jm5nZshVaS51W90t0gV8@3dimldL@XbTMq3t5bSqhMyT75BGoc@eeGHX2os3GH8/mz7abm2FOdmhd6XrPcLeb72MkzDQnW9v@hlJ3UzY15XwVbY7LgSxJ7pfj51u/O/iNEVY3T2JWx/sXfkfA@b6rnLbenPeOELRDKlZeM@rvetwCPcYihuw6tW/wgYplE6IVFnsUhoipe3FgsN5mcNtwDbH5UNXHCLj3JDMJcqSm8rwDwXIDPHnUtw9BskkG7/Ng4d6m5impDvyGvbicO6iUvjW0Kyb3ENB@ydm5ZxOS7c4JxlO@RKKM75/qbD13C30vqawVIZF5Gt7d8LmIZH7kCOg9Nvhe6Ab2bAU6a4Y6bhnOUet2CFKEIvYFqpdyp4FfoXuhPFpyNBQqbKCa0r99yKJwhO9QSBHfjg1t2sdN9rLa6sqaTyrSOUmF8Jwk3JdWmLaqaoLNm3V1fd0Ezk2UJO97p92crezY0sMS6N0l2/iN17KjLCfrh/D/qKcNNCQF3zmxNixwmNpYPF1yyKSMj3cUkYQG0qd7Nk2J2c1kTZ9yLKYK7KuN8vzWMRvtWci1hcIdrmJybG1jQN@BP3h5ofjCY/dW02S7NeTp2cAbRV6MOkh8d/tnPh0c804YjtNYVcb/stoZklxT4rO4F6Wzk8ZYiazc7H0AtujSw/3Krb09Mz4ArUE@KtwVdxiqEuIPQS/gFTUguwOfYGaDM0CJOCLEDexSU/rJkUOo7c8SKp/Qlk/XEDeZX4YQCJYblJFRKfKe4VMcWkYEeH4nnzeuNcKNS4OjqA7tAJN757mKMkSQgaTPByb7gC0qsVX6ekeCuVs0FBQoVakrohQIi984sUZAIl4WWzCJrCmBkF81dsr1E9CYd7AlNG0ExRF8En7KOQo6sVckclwf@gj5TpHQmBhDCT2xBrgH1FduEGFAmY0xA8mVKfrGJKi@BywYAODIjxvui9qh/fz/0YdygbyjnyZ4xE7swJOwjTEv26wOf@ojXJEWkS6WJAprjtp@NrvVlySdZP9aqiUxUg/weDfIKaznM7BDzEZAtX9IXkIkL9lpuSYL6OvJJdu6n8Y867oK5fx1@w87S6qtlTWD1V7ylU9nMFGc2sXQiclOgkteXLdnI71UDCmJczlEyUr72kbp/2Gd8RosvN@b/VveRxxgry41RcSKdxfMN1AXHUDJKvAkiyYvaN@T1@NhN5eGoDSuMdWngOA7NgwvhMCpfWsUW9Xy/v4YPscX7yvEC@Gv5eoXT8jBNg4Qgab9GEAVVPorMmF/XN7/MIzPkNdU47wquVMKuEoCRIn5hPLjCDQYqEBsy57IjNie2E5VWYHC9pHOK9fTyoYqkukQej/CJQdsUnuxc0V05Ok/w9e5qSq69c@SdvXpyykhKlhM4MPLe4cJHDRYscHi4WE0YgH6U1P6QQdlBJiQ9RNZQ7sCoyplHMFMtPP3iBmJ0INv/nn/9qFvOOqDKgPC/WGbxgZ1UGUBPU1dIi68khlHAJlTApJ@zHJJ3EpzTSOoZZHvor0TNnwt/BCIQwPS7DhMoLXlXvuM9@64Jiyd@9dJ7E5xucQt6yN/JejejYsV13YYse2kH780GLHLTbgg88XFA/mh5kz3wsqfmD@d0Lg@lBksIMukihbD3Qr@Pkck5MhIwPDfBOknCcNYj8@3FsYtg2BaMmK8LQK/CmFeiXFR/850QsrppSTTAeXVxQZP8hzUTqERxAKKdSn7XbbUic5Onps@cEUig8NtVlTMJO611wGlhsQPcPgfI6u/QO/UqFMScODgU5ks4mPatUelOgS2c9azKv@WWLz@7o11xi41QJuN@HlJB9tPfQLwj87vn7/3x1VhC4kA6l27JP0CJz77jZbP5srCfmN48fPLSO5lePHxx/8@Cbe8bBkfH1Xuf1z1fkjCapYyegN0g3fyVX5FUYRqgoLBrx2vf79z8yNFfkJRR7S@gqbxe4oEjo4BtTIN2BDid40T5gR7mE1ZAsoS5hAP@xGriJ7aeF8q/CQAwvsjAOiOiCq1C2LsHmx/dlM6/RwKoboA9vuif3xJtnMO/ijfUuK5cTlbCGC2ryd9J@9He9CiQnNiWSDT/YoLBqjaiDNa/oxKY5EMndOHkjjLTas8srNtJbtVnGxnv07x@QtzC9UPfe@@/t7xvkUjS@sMGXXN72Q2PXAOOJZfrPZn88JOYAb1J1G@bQGJMxfu81zLFBLPbdaoyGXWL1RB9jYBJryB@s0ZhYA97J7A/7pCt7md0@MfvyAYdY/KE/6hOrK170TCt/sAYjYorxQ/hiihFDI0cCi6Qh6fb5gzW2iCmQmGPAK@XodceEUR0AVTPvNBh1Sdfkg/tAxRKEzPFwRLqCndnvkpH42gUY3a4kCkrAr@PGoN/PQIwGIOhYgugNBVF4QK1lRHs9MxPIsoCbwYezEfjVNEA40KVpSqUNrVzpXZAupzUG6LJbF2Q1DWGzbn@Y2a9rGZmdBoZF@qK9N7Bygw/6IzmgD1JkzPtCgX3A0bcUUINxphDTGo/IUFAdjAY5QMvK1TAcGrkj9EDPliH0aUinQLOCF0pShpkJMRz1cv8wh4OcUh8UkPGGLlmvPsIVDyMUSYywQJ1dya7fG2TWMIfmiPSEt6AYI0HWBDNx05jwAkDlzj0eZw8DsJlkPh6bGfKelbk800emwhEGnMV7dXujzJFM08h7gZdmcYUOaWWebXGs/cYwN501HAqHsBo9dBsZLeNu7ik98A3uD/BiBLwkTXMMbiYfUJWsk9no93M3tYyu0CQMHnS7UklD8IfMFS0Ic@kD/WFu0F7PUHRh5rFjjsDPMssNwUm7mX1HRp4ARlZmxqFh5mZEsXvSpJC6LBG3z988@18) [Answer] ## [dc](https://www.ibm.com/docs/en/aix/7.2?topic=d-dc-command), ~~23~~ ~~20~~ 17 bytes ``` [lb/dd0<g]dsgxz1- ``` Takes input with the base in register `b` and the number at the top of the stack. The answer is at the top of the stack once the program completes. ~~Basically, it recursively calculates the number of digits, storing the current count as the second-topmost value in the stack and the current number at the top of the stack.~~ What I did before was pretty long, and it turns out it's shorter to just add new elements when you delete each digit of n in base b, and use the stack's size instead of a register. Run from the command-line as follows: ``` dc -e '{BASE}sb{NUMBER} [lb/dd0<g]dsgxz1- p' ``` where `{BASE}` should be replaced by the base and `{NUMBER}` should be replaced by the number. Pretty self-explanatory. ### Explanation ``` [lb/dd0<g]dsgxz1- [ ]dsgx # Store the text inside the [] in register g and run it lb/ # Divide the current number by the base (in register b) dd # Duplicate it twice, once to store the number of digits, # and another for the comparison with 0 0<g # Run the string (function) again if it's more than zero z1- # Find the size of the stack and subtract one ``` The `1-` at the end seems wasteful, but I don't know of a way to reduce it. PS: This is my first dc program, so any feedback would be appreciated. Also, I'm not sure if [this](https://www.ibm.com/docs/en/aix/7.2?topic=d-dc-command) is the best site for dc, would the [esolangs one](https://esolangs.org/wiki/Dc) be better? It has less information and wasn't as helpful for me though. [Answer] # Excel, 17 bytes ``` =LEN(BASE(A1,B1)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnVUIy8LHmeh9tOO4?e=2NEISE) Counting digits in base conversion beats using log by 1 byte ### Log Method, 18 bytes ``` =INT(LOG(A1,B1))+1 ``` [Answer] # [PHP](https://php.net/), 22 bytes ``` fn($i)=>1+log(...$i)|0 ``` [Try it online!](https://tio.run/##Pc3BCoJAGATg@z7FIHtQWtRVyxazTkGHIO8lIrZmEa6kt@rZbdXq9s8H809TNf1q01QNoWXcl7VJr1a85rO7upi2bev0cvuIENrJtmsR40iAI5@LkIEvUgY4DvzRQlcwiIEGC0YTLoP3N2@wZehrC342dkWg33kpMBl3Sao3S/WQeVGZ@I7nrb5g4akrsqgUbq2qM1kX6ixN2lkMxqkzGGg5pWSXZNvDPiJv9B8 "PHP – Try It Online") Or the super boring version : ### [PHP](https://php.net/), 41 bytes ``` fn($n,$b)=>strlen(base_convert($n,10,$b)) ``` [Try it online!](https://tio.run/##Pc3NioMwFAXgfZ7iIFlECP7V1gmOndVAFwPt3opYG5FhSMSEboZ5dps4bXeX73DumcZpef@YxonQoVoGxaji9BJWe2PnH6nYpTOy7bW6ydn6LE18HC4lIdRKYw0q1ASo060oONJdw4E4xma1IhEcwpO3fDWRcGQvy7y9FRtn@dPWrsjdu6wB/i1NSOM2Bz3Lrh8ZHuOdcRdC/LqK7EeNb6NVK1Wvr5JRG3IEZxtw0IFFUYRVTodT@3n8Kskfljs "PHP – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 42 bytes ``` param($a,$b)for(;$a-gt$b;$i++){$a/=$b}$i+1 ``` [Try it online!](https://tio.run/##XVVdaxtBDHy2f8URlmKTdbvSfhMMgdK@NiSPpZSze25aHM49O7Tg@re7Wjexpb23FSvN7Gik2/S/u2H72K3Xs2U/dEe1mu@Pm3Zonyaq1WoxXfXD5Ea1s@87tbhRP66vp3vVvpurxYEOcDyMx7eTcUOfvp2Az1FD0HZ6jkSTddbuEshGY9Z4DqRoNTqeYgJojCyCiRICywEfvbYiCazX4EWklEEW8clrtPyKA6wiGJIGXjjSCXiVaKoHgDFE1rMIZtTAHwCZXi10cTZrqwMDhionJCIGrKovGBwGckzacm7grU78bMtbrMAltXW@oHgvuadAOmbB3cWCyyKlZRLXOZAqIRIPw@qeqmgwTDZqKYDoWMTKCpZ0q5AysRVZlqQEwy1mfZSes2iko4JB7fkNF7AybvBJFPGkiqTrSws9o@@xflDIUn7AnHTkwCGF6oWIld4xmsrajhpPT2JtNSevc1PSJAogA1KUmFzlfYihwvGktGRLGTLJl0fzSCo68SpIXbWCm3dBugUiJO34OBRZEkcGMlSRl10p4yJ3QM4yEsrW4ORyBimCQ7kjTurLJqay05AlWZfkzACYKqkMrlhYZTJRLgAqydwTK7thjMXnlxKuDIfYO9lWo@DI98U8jDsRE7CQacBEpHSU2F987qvJRWNLQ1nVYK1oTiSby5lE2r3C1T5WdnTO1MpDtYog0YRJt0WaWystmky1nxNK/0UDlf@KtE4Ykn5SeFqc0@Zv87EfPrTLx9mnxc9uuWv249HpT6hV92dDge5bM2/UV4oO3fZ5vaPTG7VqVNuoxXj0@e7h/fN21z/9z/7S3FL@6OF5uey225J4LjLrfjUvJejGXfnldjv6F9Olq1OxKwrfv0JcvaJNzhWmdOEwPhDjbT/sZv0LXeL29hXvcPwH "PowerShell Core – Try It Online") [Answer] # [Go](https://go.dev), 65 bytes, using `math` ``` import."math" func f(n,b float64)int{return int(Log(n)/Log(b)+1)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZhNblMxEMcllllxhKirRBjw57Mt1AV7FlwhrZq2osmropRNxUnYVEgcgqPAaRjPvEoez6xa__Sv7RnP1-vPX7fzy5_H3fW33e3N-rC7P67uD4_z6fzhYn84X_x-Ou_fl7-fX9lhd767WO2fjtfr_eZortb7h3l3nuL2_nh-Pt2cn07HNfy6-TLfbo7bj-3H1fad2_6gjf69fYN_287ZbJ9X33en9dz-YDWvL2FHl2o2btp-Wn89AX04vhITzGzC5eW8fVVmW03thQhMBF3sddUaz3QIjAed73QlB-NjpyMgz7WTMz73GxIRSl_glN4UAuJkl3IyITKbkcizXUjGpV5JRFG2O3mmRCKUqSTjQyckIHeMznPhQqTST8U4Zg8RoczAXH9JAlJnhzckID1pLTwD8w8RofTVG9c_IgFpS4Vo4fFIRChjqKb3Dq7NBKqJ-cYNBy9E7DcV8KzrhASEJalZ15tMQPqm5mICiwgi0uYUTGHRCGupCu1BWTwQUTwDicQ8A2vI1NnU3t6U-NMRkHk6QcD3sUBAebmYuWMWIpUt07lniCg5EB0P2IXI3PfgMdvHFwJhDV6pk-HaOAsyZ1lkQ-FwjkU2EiXzs-eFbCHKC0Ikc7uJKHZXeAh2OhFlTwh7Z9meSGRdDinz-o1A0Xk71FsiMmOsNyyA2lruFyc_ZDQRacuUCr8hArFjguhjT0NAySteIXANN5xNYu-X_PDSRLQaX4cMJKJU5FoMLzoNSN9MZRoigoiyox-zi4is3dnylkVAiTGoRp5FDhFZT-zQ2ggo3QAmB96oG5BWWzdEIgKhyyXyBkhAy8Bp7NJIlIiAFGI3RKC8CxzDey8RZccWKzzKkAhlaUHaX5KArGRQPFhIEFCmmDgNtZGIMrm5YliBQiB7ZYu9MgZjkd5xUFv5qNNASxmooo7t2BotO5qI8oa1Dkoisuq0ia53OAGhq9WxIMO1jLHoeWwT0POPVwkiSndr8zPvbkjE2SEW3oEJyJd2djybiDi7jSt9pcW1sh8MGEy3EGWS8CxwcC0qaB7Kdlarts-ZtzQC4naxNc9-OwLKfBXGHklEWgF9jjU0AnLHAl7lfiGizDrQ3rmSiMzmwI_GtcFE6TtaGqYXAnKKtoHXEALSkikMIyUCGf3QvpgLCWhfGG7oU0Tk103mLQDXykwQ7fC1REQ52Q1j6kKU14P2zms2Ee1L1g97ElGqe7FjjUUiu27xQ9dFoHxZDY4kIK1pycFrdgNKF4CPcM-_HpB0Jy__Cnh5oZ__AQ) # [Go](https://go.dev), 69 bytes, using `strconv` ``` import."strconv" func f(n int64,b int)int{return len(FormatInt(n,b))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZhLahwxEIYhy1nlCINXM6AEvR8ELxPILlcYG48x9nSbSdsbk5NkYwI5RI6SnCYlVRtUqloYo4_fkqpUr_bPX7fz65_Hw_X94fZmezrcTZu70-N8Xj5eHE_Lxe-n5fgh__38xr4v5-t5er7YHJ-m6-1xN23vpiV6dVV_7-Hn5XyzPJ2n7cPNtPsyn0-H5eu07CZ1td__wM3-vX_X_rietdu_bJ4P5-1c_3wzby9hSxNKUibuP22_nYE-TG9EOTUrd3k579-USRdVemEDyoPO97qilSW6BpQFne10OTllfadDwM_V0Sib-g2RMKXNcEpvCgJ2sgkpKOeJzY3ws40LyoReiURQ1jtZomyEKUMOyrpOiIDv6I2lwpVwpY1ZGWIPEqZMwEx_SQRcp4c3RMA9qTU8A_EPEqa0xSrTPyICbkuBaKHxiIQpvSuq905bqwiqSHxjhoNXwvaLGTxrOiECZkmo1vUmI-C-KSkrRyICCbc5OJVJNMKaq1x9UBIPSATPQCIRz8AaMnVWpbc3BPp0CHieRgj4PhYQCC_nE3XMSriyZjr1DBIhB7yhAbsSnvsWPKb7-GqAWdOu1MnaWhkNMqNJZEPhMIZEdiNC5idLC9lKhBeESKZ2IxHsLvAQ5HQkwp4Q9kaTPRvhddmFROt3A4LO6qHeIuEZo60iAVTXfD8f7ZDRSLgtMWR6wwbYjgGijzwNAiGvaIVoa7jhrAJ5v2CHl0Yi1fgyZCASoSKXrGjRqYD7JuY4RAQSYUc7ZhcSXruTpi0LgRBjUI0siRwkvJ7oobUhELoBTA60UVfArdZmiMQGmC5lTxsgAikD49ilGxEiAlKI3LAB4V3gGNp7kQg71lihUdYIU-YapP0lEfBKBsWDhAQCYYrxcaiNSITJzWRFClQDvFfW2MtjMGbuHQO1lY46FdSUgSpqyI610ZKjkQhvWMqgRMKrTp3oeocjYLpSDAmytuYx5i2NbQRy_tEqgUTobnV-pt2tEXa285l2YAT8pY0ez0bCzq7jSl9p21rYDwYMoluJMElYEjhtzSpoGsp2Equ2TYm2NATsdr42z347BMJ85cYeiYRbAX2ONDQEfMcMXqV-QSLMOtDeqRIJz2ZHj25r1RKl72hhmF4Q8ClaO1pDEHBLohtGygZ49EP7Ii5EIH1hmKFPIeFfN4m2gLYWZgKvh68lJMLJZhhTVyK8HrR3WrORSF-ydtgTiVDdsx5rbCO862Y7dN0GhC-rwZEIuDU1OWjNrkDoAvARbunXQyPdyeu_Al5f8fd_) ~~nice~~ wow builtins ]
[Question] [ **This question already has answers here**: [Count up forever](/questions/63834/count-up-forever) (224 answers) Closed 9 months ago. In any programming language, make a program that outputs infinite subsequent powers of two, starting at any power of two with finite integer exponent. There does not need to be a seperator between outputs. Note: it only has to *theoretically* output infinite subequent powers of two given infinite integer size (so you can ignore any potential issues with floating-point). Each power of two sufficently sized (greater than some value) must be theoretically be able to be outputted within a finite amount of time. An example in js might look like this: ``` var num = 1; while (true){ console.log(num); num *= 2; } ``` Remember, shortest wins Standard Loopholes apply. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` ¨² ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLCqMKyIiwiIiwiIl0=) Builtin for infinite powers of 2. ## [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` Þ∞E ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLDnuKInkUiLCIiLCIiXQ==) `Þ∞` Infinite list of positive integers `E` \$2^x\$ [Answer] # [Haskell](https://www.haskell.org/), 12 bytes ``` p=1:map(*2)p ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8DW0Co3sUBDy0iz4H9uYmaebUFRZl6JSsF/AA "Haskell – Try It Online") [Answer] # [Rust](https://www.rust-lang.org), 34 bytes ``` ||for i in 0..{print!("{} ",1<<i)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMGmtDyF3MTMPA1NhWqunNQShTTbpaUlaboWN5VqatLyixQyFTLzFAz09KoLijLzShQ1lKprFZR0DG1sMjVrISqXWadpaHJBOQsWQGgA) [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` İ2 ``` [Try it online!](https://tio.run/##yygtzv7//8gGo///AQ "Husk – Try It Online") Built-in solution: `İ2` = (infinite) sequence of: Powers of 2. --- # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` ¡D1 ``` [Try it online!](https://tio.run/##yygtzv7//9BCF8P//wE "Husk – Try It Online") Non-built-in solution: Repeatedly (`¡`) double (`D`), starting with `1`. [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~25~~ 22 bytes ``` f()( echo $[1<<a++];f) ``` [Try it online!](https://tio.run/##S0oszvj/P01DU4MrNTkjX0El2tDGJlFbO9Y6TfN/2n8A "Bash – Try It Online") *Saved 3 bytes thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)* Solution of [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)'s: # [Bash](https://www.gnu.org/software/bash/), 18 bytes ``` echo $1 $0 $[$1*2] ``` [Try it online!](https://tio.run/##S0oszvifnFiiYGOjoO7q76auYKdQkF9upAcUTk3OyFdQMeRSMVBQiVYx1DKK/Q9UwZWckZufopCoXVQBU8mlpw9lKRj@BwA "Bash – Try It Online") [Answer] # [Rust](https://www.rust-lang.org), 37 bytes ``` let mut i=1;loop{print!("{i} ");i*=2} ``` This is the same solution as in [Peter's C answer](https://codegolf.stackexchange.com/a/261328/88906). [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMHqtDyF3MTMPA1NheqlpSVpuhY3VXNSSxRyS0sUMm0NrXPy8wuqC4oy80oUNZSqM2sVlDStM7VsjWohihdC6QULIDQA) # 34 bytes This is the previous invalid solution ``` fn f(n:i32){print!("{n} ");f(2*n)} ``` A neat thing is that Rust notices that this is an infinite recursion and issues a compiler warning. [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMHmtDyF3MTMPA1NhWouzjQNQ02u2qWlJWm6FjeVgFJpGnlWmcZGmtUFRZl5JYoaStV5tQpKmtZpGkZaeZpQlQugFJQGAA) [Answer] # [Lua](https://www.lua.org/), 27 bytes ``` n=1::p::print(n)n=n*2goto p ``` [Try it online!](https://tio.run/##yylN/P8/z9bQyqoAiIoy80o08jTzbPO0jNLzS/IVCv7/BwA "Lua – Try It Online") [Answer] # Dyalog APL, ~~12~~ 10 bytes -2 thanks to [Adám](https://codegolf.stackexchange.com/questions/261325/output-endless-powers-of-2/261331#comment574434_261331) ``` {⎕←2×⍵}⍣=1 ``` Explanation: * `1` starting from one, * `⍣=` until the last result and the current one are equal (never, so infinite loop) * `{⎕←2×⍵}` double it at each iteration, printing it [Answer] # [ATOM](https://github.com/SanRenSei/ATOM), 8 characters, 12 bytes ``` 1🕳️{🖨️**2} ``` Explanation: ``` {🖨️**2} ``` is a controller (function) that takes a number as input, multiplies it by 2, prints the result, and returns the new number as well. The first star is parsed as the input to the controller, and the second star is parsed as the multiplication operation. ``` 🕳️ ``` A while loop, it submits the result of the controller back into itself until it gets a 0. Note: ATOM is a living language with updates happening time to time, but this program works on the version of the language before this question was posted. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 11 bytes * 1 byte saved thanks to @Dadsdy ``` [r2*prdx]dx ``` [Try it online!](https://tio.run/##S0n@/z@6yEiroCilIjal4v9/AA "dc – Try It Online") ### Explanation ``` [r2*prdx] # push a macro to the stack r # reverse the top two stack elements 2* # multiply the top of stack by 2 p # print the top of stack (the number) r # reverse the top two stack elements (macro on top again) dx # duplicate the macro and execute it recursively dx # duplicate the macro and execute it for the first time ``` Note that the first multiplication fails with a warning `dc: stack empty` as multiply requires at least 2 numbers on the stack. However in GNU dc, this is just a warning, and the 2 is left on the stack and can be used correctly in the next iteration. [Answer] # [PHP](https://php.net/), ~~21~~ 20 bytes ``` for(;;)echo 2**++$i; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKytNVOTM/IVjLS0tLVVMq3//wcA "PHP – Try It Online") There is no separator for the output, but the question didn't ask for one ;) **EDIT**: 1 byte saved by pre-incrementing the exponent, had to add a space for the echo though [Answer] # [C (gcc)](https://gcc.gnu.org/), 31 bytes ``` n=1;f(){f(printf("%d ",n*=2));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/T1tA6TUOzOk2joCgzryRNQ0k1RUFJJ1PL1khT07r2f25iZh5YGsQBAA) If passing a specific argument (with value 1) to the function was allowed (29 bytes): ``` f(n){printf("%d ",n);f(n*2);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuqAoM68kTUNJNUVBSSdP0xooqGWkaV37PzcxM09Dk6uaSwEK0jQMNa25av8DAA "C (gcc) – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 16 bytes ``` (()){[(({}){})]} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDU7M6WkOjulYTiGJr////r5uYk5yTWFycmQwA "Brain-Flak – Try It Online") ``` # Push a 1 (()) # While True... { # Print... [ # Double the value on top of stack (({}){}) ] } ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ≔¹θW¹«IθD⎚≦⊗θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DUEehUNOaqzwjMydVQcNQU6GaizOgKDOvRMM5sbhEo1ATKMnpUppboAFiOOekJhaBWb6JBVATXPJLk3JSUyDm1P7//1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔¹θ ``` Start with `1`. ``` W¹« ``` Repeat forever. ``` IθD ``` Output the current value. ``` ⎚ ``` Clear the canvas for the next pass. ``` ≦⊗θ ``` Double the value. Note that the version of Charcoal on TIO throttles the dump, which is why the code appears to take 10 seconds to overflow the output pipe; with the version of Charcoal on ATO this can be disabled using the `--nt` option. [Answer] # [Rockstar](https://codewithrockstar.com/), 30 bytes ``` X's 1 while X say X let X be*2 ``` [Try it](https://codewithrockstar.com/online) (Code will need to be pasted in) [Answer] # [R](https://www.r-project.org/), 19 bytes ``` repeat show(T<-T*2) ``` [Try it online!](https://tio.run/##K/r/vyi1IDWxRKE4I79cI8RGN0TLSPP/fwA "R – Try It Online") [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), does not ignore numerical limits, 49 bytes Generally you can ignore numerical limits on this site. Just for fun this program does not and properly checks for overflows and will keep running till memory runs out. Output in reversed decimal ``` 8l0&>:?v~r&:?!~rao00. nr1-^ \$}r:2*&+:a,:1%-&a%$ ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiOGwwJj46P3Z+ciY6PyF+cmFvMDAuXG5ucjEtXiAgXFwkfXI6MiomKzphLDoxJS0mYSUkIiwiaW5wdXQiOiIiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) [Answer] # [Desmos](https://www.desmos.com/calculator), 9 bytes ``` o->2o o=1 ``` `o->2o` goes into a ticker while `o=1` is in an expression box. Start the ticker to run the code. Note that this does output all positive powers of two, even if they only show for a brief moment of time. [Try It On Desmos!](https://www.desmos.com/calculator/6fzcingryo) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` 1ƘO£ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWywyPzfA_tHhJcVJyMVQIJgUA) There aren't any infinite lists in Thunno 2 :( #### Explanation ``` 1Ƙ # Apply this code to each positive integer, n: O # Push 2 ** n £ # And print the result ``` [Answer] # Commodore C64 BASIC, 27 Tokenised BASIC Bytes, 20 characters with BASIC keyword abbreviations ``` 0X=1 1?X:X=X*2:GOTO1 ``` As this is 8-BIT BASIC, this will start to use exponent notation after 2^29, and likely run into rounding and other issues soon after. Note that it's more performant in Commodore BASIC (and likely other 8-bit BASIC variants) to add X to itself, rather than multiplying by 2, but for this purpose it is not necessary. [![Commodore BASIC, Output endless powers of 2](https://i.stack.imgur.com/Phif5.png)](https://i.stack.imgur.com/Phif5.png) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` f! ^2 ``` [Try it online!](https://tio.run/##K6gsyfj/P02RK87o/38A "Pyth – Try It Online") ### Explanation ``` f!\n^2T # implicitly add T f # find the first integer which makes lambda T truthy starting at 1 ! # not (makes false, thus looping forever) \n # print ^2T # 2 to the power of T ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 19 15 bytes *-4 thanks AZTECCO* ``` 0.step{p 2**_1} ``` This loops yields subsequent numbers starting from 0 and calculates `2 ** i` for each yielded argument. `_1` refers to the first block argument since Ruby 2.7. `p` prints the calculated value to STDOUT. [Answer] # [GFA-Basic](https://en.wikipedia.org/wiki/GFA_BASIC) 3.51 (Atari ST), ~~ 20 ~~ 17 bytes A manually edited listing in .LST format. All lines end with `CR`, including the last one. ``` W 1 ?2^i IN i WE ``` which expands to: ``` WHILE 1 PRINT 2^i INC i WEND ``` ### Output This is the output before the screen starts scrolling up. [![output](https://i.stack.imgur.com/ff4nu.png)](https://i.stack.imgur.com/ff4nu.png) [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), ~~8~~ 6 bytes -2 thanks to @mousetail ``` 1:n:+! ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMTpuOishIiwiaW5wdXQiOiIiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJjaGFycyJ9) [Answer] # [Desmoslang](https://github.com/theRealDadsdy/Desmos-Userscript/tree/main/Desmos%20Programming%20Language) Assembly, 3 Bytes ``` 2O* ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 27 bytes ``` for(n=1;;)console.log(n*=2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWu9PyizTybA2trTWT8_OK83NS9XLy0zXytGyNNCEqoAphGgA) ## [JavaScript (Node.js)](https://nodejs.org), 33 bytes ``` function*(){for(n=1;;)yield n*=2} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY0xCsIwFED3nOLbKbFYahfFmFs4upT2RwPhf0lTrYgncSmih_I2Burg9JbHe48XcYvj05p3H-1i_ZnZnpromOZS3SwHSWaptbo69C3Q3FT3nxgGMGClEqJh6thj4fkgs90RwbrQRViVcOILhg7YQgV1wM2eMqWFSFmQHiO4lCh1wjbZiXmu4L82FIRDlKo4175HNZ3HceIX) [Answer] # [Haskell](https://www.haskell.org/), 14 bytes ``` p=iterate(2*)1 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8A2syS1KLEkVcNIS9Pwf25iZp5tQVFmXolKwX8A "Haskell – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes ``` K`1 +\`.+ $.(*2* ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zvBkEs7JkFPm0tFT0PLSOv/fwA "Retina – Try It Online") Starts with `2`. Explanation: ``` K`1 ``` Set the input to `1`. ``` +` ``` Repeat. ``` \` ``` Output the result of the replacement on each pass through the loop with a trailing newline. ``` .+ $.(*2* ``` Double the (implicit) character `_`, then repeat that by the decimal (implicit) input, then take the length in decimal, i.e. double the input in decimal. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes ``` Ň2E ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FkuOthu5LilOSi6GCsAkAA) ``` Ň Natural numbers 2E Power of 2 ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 5 bytes ``` 2<.:* ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83stGz0vr/HwA "Befunge-98 (PyFunge) – Try It Online") Starts from 4. ]
[Question] [ Construct a full program which outputs `Hello, World!`. The score of your submission will be equal to the sum of all of the ASCII values of the *distinct* characters. The lowest score wins! ## Rules * It must be a full program which takes no input * It must only print to STDOUT, nothing else * It must be strictly less than 1000 bytes long * It may only include [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (meaning no `\n` allowed) * The objective is to find the lowest score for every language, so no answer will be marked "accepted" ## Example Here is an example submission in Python, which has a score of *1279*: ``` print"Hello, World!" ``` Finally, here is a [TIO link](https://tio.run/##JY7NCsIwEITvfYppLrZQClbwIFYQFRTECgqeSxIxEJOSRNCnr9n0OD/f7A6/8LKmGUf1HqwL8D@fZfzVO48WXoaizJ7WQSsjoQzFtQ9CmdrJXpDri3KVgTqcCmRFDW6FjAvWiYKXUavnZG1aLBr0Rkxy3WLeLAlAOlr3IgIxIUZqn7YwOGUC2K7bH67d6XJnVaIrsEt3x/Z87h6HfZ7njMryq@jriZnduHVyNavgP@8inSjHMWXsKLW2FR7WaZGzPw) to score your submission. [Answer] # [C (gcc)](https://gcc.gnu.org/) `-zexecstack` `-Wl,-e$` `-nostartfiles` on Linux x86-64, ~~876~~ 914 bytes, score ~~798~~ 293 ``` $=1111+1111+1111+111+111-11-11-11-11+1+1+1;$$=1111111111+111111111-11111111+1111111+1111111-111111+1111+1111+111+111+111+111+111-11-11-11-11+1+1+1+1+1;$$$=111111+111111-11111-1111+111+111+111-11-1-1-1-1-1;$$$$=111111111+111111111+11111111+11111111+11111111+1111111+1111111+111111-1111-1111-1111-1111-111-111-111+11+11+11+11+1+1+1+1+1;$$$$$=1111111111+1111111111-111111111-111111111-111111111-111111111+11111111+11111111+11111111+11111111-1111111-1111111-1111111-111111-111111-111111+11111+11111-1111+111+111+11+1;$$$$$$=111111111+111111111+111111111+111111111+111111111-11111111-1111111-1111111-1111111-1111111-111111-111111+1111+1111+1111+1111+1111-111-111-111+11+11-1-1;$$$$$$$=1111111111+1111111111-111111111-111111111-111111111-111111111+11111111+11111111+11111111+11111111-1111111-1111111-111111-111111-111111-111111-111111-1111-1111-1111-1111-1111+11+11+11+11+1;$$$$$$$$=11111-1111-1111-111-111-111-11+1+1+1; ``` [Try it online!](https://tio.run/##xVPLDoMgEPwZbts9eG76HT2bDZqmxCbFQ9OP71YrII9FvZXH7ASBHQYk7ImY1aWZCiQwd4wa/OpZLXOXAoFhPgTph3Jv2MzjcvlkEG@GjbTc13lVpBFKVidZxAr4DkmLZVdcWm3aYQe0htmViKX/DnP/vORt10SGB8VIaiQo3Q1X@k9Pd4ME6evwZ3CHkB/U@psxf6gzbW8Z3/qlyY4t3Rmv5oRaMQ6PaeA5djej7Rc "C (gcc) – Try It Online") Charset: ~~`A[]={+,-1};`~~ `1+-$=;` Same method as the previous answer, with even more hacking to supply a custom entry point named `$` (which has the smallest ASCII value among `a-zA-Z_$`). Credit to [this SO answer](https://stackoverflow.com/a/58613764/4595904) for identifying the flags and assembly setup to make this work. Also got a hint from [ceilingcat's awesome linker hack](https://codegolf.stackexchange.com/a/210828/78410) to remove `[]{}` from the code. Assembly: (NASM syntax) ``` bits 64 global _start _start: mov edx, 13 pop rax push rax lea rsi, [rel s] pop rdi syscall s: db "Hello, World!" ``` Uses the `argc=1` set up on the stack to load the value 1 to `rax` and `rdi`. The instructions are slightly mixed up in order to get the minimal code length in C. [Here](https://tio.run/##tVFNb6MwEL37V8xlZTtAYyBfopv9Db0ja0UTJ3FFDAKybbPqb0/HU0TDSo16WQ7jx8x7b8bj@rU7VC69XLZmB1uzqY511RrhZMYAzrCGePjuocX/XGPh@WBLA85zAOwOHPxawznDM8LTEwNktl0jzjIEHnBNTFMOXJjAAqZTtP9SFY1VP9cQUYvgu@Rxj@D2ZK3JcKrpFG@sMNWY7tQ44PzuqbJOtHkWxVoyNlrTw3/b0zensa4@dUKysu2wpflTlILnHALoC18grrlkOE5pnECphB8wy8Cb@HGUxsWJGUSjumTudKSLYSa3Gm0IBLGnq5dYqSGVDKmrZHqVxPSuasDiTNAUbm@ECoduITbTQzdcFSSTSZr0@0OLleo9/J4w562ct/IazerGuk54LFljvAkP@8Udi1oMrxcSX8pegNSPGRDI28qHm9LL5eRau3dmC5tD0cCxsO73o3W5RsO/@Jrq5bEIMaotRfVvnK8oEp4RXhEznRMn7ZnkNNLtCH/E@ad6QXixuYrESQgnvdN8@VlZJlfcGbFi9nb/Dg) is the Python script that generates the "ones decomposition" from the `xxd -i` output (C include-style hex output) of the compiled binary. --- # [C (gcc)](https://gcc.gnu.org/) `-zexecstack` on Linux x86-64, 891 bytes, score 1154 ``` main[]={1111+1111+1111+111+111-11-11-11-11+1+1+1,1111111111-111111111-111111111+11111111-1111111-111111-111111-111111-111111+11111-1111-1111-1111-1111+111+111+111+11,1+1+1+1,111111111-11111111-11111111-1111111-1111111-1111111-1111111+111111+111111+111111+111111+11111+11111+11111+11111-111-111-111-111-111-11-11-11,1111111111+1111111111-111111111-111111111-111111111-111111111+11111111+11111111+11111111+11111111-1111111-1111111-1111111+111111+11111+11111+11111+11111-1111-111-111+11+11+11,1111111111+111111111+111111111+111111111+11111111+11111111-1111111-1111111-1111111-1111111-111111-111111-111111-111111-11111-11111-11111-11111-11111+1111+1111+1111+1111-111-111-111-11-1-1-1-1,1111111111+111111111+111111111+111111111+111111111+111111111+11111111+11111111-1111111-1111111-1111111-1111111+111111+111111+111111+11111+11111+11111+11111+11111-1111-1111-1111-1111-111+11-1-1-1-1-1,11+11+11}; ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTMvOta22hAItFEIENZFQtpgqGMIB7pYWNroQrp4KG0EB43QRsU6GJbr4mTgorUJUpikLnYMQUghoY0/UPAGFB4GUV7B7mq4c7VhCKtz8bK0iQ1aXYIULlIbC4ER2BBIuvsp8hNJ6QR3QoZGgS6yNyDxUWv9//@/5LScxPTi/7pVqRWpycUlicnZAA "C (gcc) – Try It Online") Uses [ceilingcat's minimal Turing-complete charset](https://codegolf.stackexchange.com/a/110834/78410) `main[]={1+,};`, plus `-` to meet the code length limit. Assembly: (NASM syntax) ``` bits 64 global _start _start: mov edx, 13 lea rsi, [rel s] mov eax, edi syscall s: db "Hello, World!" ``` Essentially calls `write` syscall once, and goes into arbitrary instructions formed by the string literal, causing segfault. [Answer] # [CJam](https://sourceforge.net/p/cjam), 652 bytes, score 120 ``` '))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))''(((((((')))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))''(((((( ``` [Try it online!](https://tio.run/##S85KzP3/X12TACCogIa6B50hMHPU1TUgQH0gXTGIjKLIEFho/v8PAA "CJam – Try It Online") Uses `')(`. [Answer] # Stuck, 0 bytes, score 0 An empty program prints "Hello, World!" Just as suggested in the comments, Stuck wins! [Answer] # HQ9+, 1 byte, score 72 ``` H ``` There is no TIO implementation for `HQ9+`. [Answer] # [Malbolge](https://github.com/TryItOnline/malbolge), 71 bytes, 3963 points ``` (=<`#9]=}5YXy1Uvv-Q+q)Mn&Jk#j!EC$dc.?}_<)L'8%oXW2qj|Q@yx+iba'Hd]\E!YX|z ``` [Try it online!](https://tio.run/##y03MScrPSU/9/1/D1iZB2TLWttY0MqLSMLSsTDdQu1DTN0/NK1s5S9HVWSUlWc@@Nt5G00fdQjU/ItyoMKsm0KGyQjszKVHdIyU2xlUxMqKm6v9/AA "Malbolge – Try It Online") Uses the following unique characters ``` !#$%&'()+-.12589<=?@CEHJLMQUWXY\]_`abcdijknoqvxyz|} ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 321 bytes, score 399 charset: `\013456` ``` \043\1333311\05313311\0531133\135\133\043\13311\0534011\0534031\135\133\043\1331343\05311354\135\13331\05341\054101\0544\053104\0544\053104\054111\05444\0541\05331\05443\05344\054111\054114\0544\053104\054100\05433\135\135\135\046\1330\133\1330\0540\135\135\133\116\141\155\145\163\133\135\133\133\043\135\135\135\046\135 ``` [Try it online!](https://tio.run/##ZY9BCsQwCEWv9D9qT@MmDIWZRXe9f0YjaUMbMGr@0@jRzu9@tPP3ab07VJwSh3SY8AoiCsFSnFApiumFL0LCV7XpFKXwvJUYTgcEfcZkyZWkIPUwuurKkO9qIN01eBl0yyngtZEMBgsSrwwk/qNFrmGb@Lr/veGzrfXe/w "Wolfram Language (Mathematica) – Try It Online") I feel it's best to try to explain this one. First, Mathematica allows character inputs with octal triplets (From this point on, I'll be using my local copy), after decoding, looks like so ``` #[1000+31111][#[3304+11135][#[10000+13003][31+41,101,4+104,4+104,111,44,1+31,43+44,111,114,4+104,100,33]]]&[0[[0,0]][Names[][[#]]]&] ``` All of the addition is just to avoid getting a 2, 7, 8, or 9, which in octal have 2s and 7s, which are trivially avoidable, all the other characters are the minimum needed to get `Names[]`. When the actual functions are shown, ``` Print[FromCharacterCode[List[72,101,108,108,111,44,32,87,111,114,108,100,33]]] ``` Where all the functions are hidden inside a `Names[][[1234]]` so that they can all be numerically decided, but `Names[]`, at minimum, needs `\13456` to derive everything else, the 0 is needed to turn Names's string output into Functions, as `0[[0,0]]` returns `Symbol`. I know that after making this whole thing it can be golfed to do without 0, as the only time it comes up is in addition, inside the octal for the `+` symbol, and getting the symbol header, meaning that if 0 can be derived elsewhere then in the charset 0 can be switched to +, lowering the score by 5. All it would need is to not use commas inside list. The only function that I recall that can do this is the Append family, but calling Append instead of each comma makes the program over 2k in size. In case you want to see how it was generated, I will put most of my code [here](https://tio.run/##vVTfa9swEH7PX3FVoA@dymychNEsxdAtrNCOds3YgyKKmyiJwbaKpEBo8N@e6SQ5PxzY4/Sg@@58@nTf2ecyMytRZiafZbvdh12jn1kpNOPDTmeRb5h@5XAzghej8mr5S7wX2UywDgBoivsWNyDTisD1LRBCvR95NyIUSOxxjDjxOEHc87iHuO9x32JPMPCBQSDcvMKNdadTAl9v4b4yYimUr4mNc6VNOpF3q0xlMyPUnZwLtuEUvlBIuDtfo5xqXRo5k@vKsI1X9Sjn68LL2dbupvuF8@Bl/aaFeWZ7Us1IFCe9/oBY4kM0Pa1lw7kvuB0O0cAOF/AoyjehnllI/JYvc6Nd1f2Q3PQ8XyxCjW1e@JxCiMNYydKTHEdhorJKv0u9J7DrIdcG0hS2EYWoZmjimsI2Dtb6Cdok@AEfCHA1GT20vYPt15ydibLLvuRP5L8qO4hDFPSdwLhR2RZ3lNPoTMJJD5s@NcJ9tN2hf3XC53rjdvxCtVETOYYRHH2q32crmT5JnZtcVgwnlELXMmN5lg0uh50yr@wZnFYkIl3mpsSTMfJkG2oIxxDhrPUQm3syOC7RF3eejf3dM7knnbPXeSgdX1d7LMkPURSSwh@pivkFzlK4iza8nF@yiLGIRpyz8C9irItxTppGLVU2F1bzRJqsSK9@V7Y36VXrMpvntDPbHz6ErS/zQVRLs3IxCo7H4Xq3212/Y/pf "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Knight](https://github.com/knight-lang/knight-lang), ~~460~~ ~~383~~ 442 bytes, score ~~268~~ ~~236~~ 226 *-32 score thanks to @Adam by utilizing `A1`* *-10 score thanks to @emanresu A and @UnrelatedString by using `E` to EVAL `O"Hello, World"` instead of using `O` directly* ``` E+++++++++++++++A+11+11+11+11+11+11+11+1+1A1A+11+11+11+1A1A+11+11+11+11+11+11+1+1+1+1+1+1A1A+11+11+11+11+11+11+11+11+11+1+1A1A+11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1A1A+11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1A1A+111A1A+11+11+11+11A1A+11+11+1+1+1+1+1+1+1+1+1+1A1A+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1A1A+111A1A+111+1+1+1A1A+11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1A1A+11+11+11+11+11+11+11+11+11+1A1A+11+11+11A1A+11+11+11+1A1 ``` Characters used: `E+A1` [Try It Online!](https://tio.run/##pVhrc9NGFP3eX6GoNNZaimIzTDtYUTIhDR2mxVCSlmltg1erta0iS0aPJGCrf53eu3qt/IQpZDKS9ux97bmPzT/0jsYs8hbJSRC6/AvzaRwrvwbedJZcR1EYKfwh4YEbK@JtmeWA1zSKeXNd2lOi3qRB4s0P426SiNP5koVBnEQpS8JIo2SZzLzYjMM0YtymGax4i7czL@HxgjKuFetzmrCZdvpOGwxHw8Ewhu9Zb6Svvh@8GwajtjYMVo8IaZ@SbMH5B1iNeJJGgSIJH3RGq1WQ@n6WC3MMZnfI0ueJQm3H5A@caRKcWIUI3GLbNr3Ah54MsaVnM04dsF2joMb0eTBNZsSgAzYiWRKC414w3WpVlolwKLd/vb6@sQcjKw/Vn9RP@TJOaOIxZYGnoDlk6Zgb4bEmEMU7GoEPHYueCTGFfovqeu4fs8X3AR2ZpSzLm2iMFPawTPI1i9JAhD0K75WA3@eMyFzupNMt33d4J4SY9SLg@unc4dEOXLkIuGdh6HMa7ABWq1nBqt8gGBH1K@LloVsjWZwuULohRL13aUKBa7mjkpItzhTv9b5tnhTvTdCGG@UHGcY/@mhegaCKB1bTgPFwknstuXF8LBkPfMyfyiig8CoERUg2@FNyvc6m2@cjMrg8@XvUPjW6FeXp8TEeMMrU1FsVtZHMTeeLyplx6cwjkZ8ZGWd@MqtdOaptPT6mjWObyjhFxh01gVlO5kUazzT8Sqw8Va77f75486r/8rp/ay@zImFeuDxI1jhwyP0BPfn8foS/OydP30MI1gMghIKx2T42eQgCNjXjI7Z6Ew9weYhyHAYKzPWmAcqRPBnUmFFFzdzgHSjM4LvQc5XOEZ5PablVJ6hcl7XxH8GHILwPFK@yTGk1TGuNmzEXLpAyvlJ0v5ZeQ1ffDCkEtEgXStZJVSzUnKKuK3Gl3F9zRqdS6SAZ1OC98JMmfJ76e@HtJtz17mQv6yU8icYhlKJe0mRmAm8CJkk9Bb93HZJ6RYMgTBRQBWeiOJ@UzzwKVTA1dL9Rd63wB3pQH4hP/VDStwjv9@urxa9WRxo965Cvcr7d/grv@cMiDJCkNOHCICUJoTYGfAp8u@MKGMcjMNLfUUnO5HPbWW/OG6gG8Wva96Eh7ue9VL0r4veLkkpyzqOQRgkpKwi227UcUBGsEXVfZxDyCucPhJKFczCTiy2mWgXjG3fJwcFvZXSgOR4MDlLIsanUc9TWiMAcFw9vRu0LMuyeGo8FrTAawCxHJhJowGElH2KomQ93CFZb2JbYatVSW/hAapfqoRWLHlg19wJgkqt8TEMgFA9YmOJn7vaUR0uajbe1dGF/M4@MboesVp21mlUMCPtqFjoxLgCFws3Sg6BalxnxBafQe@QKdIDx1ai1l/EVSj5U@Fh0V9hF3ZtPAevRzI74x9SLuKZOYpUYSxyRxZIjLbGZ57vvF1HIeIyo53/0r25fvOrf1L35OdSAfa1ZYkl@wDCZV2IGjtTpxElLs6ol8eqiJ7JOX5nkNGcMx3ka52N8cWE@ds9YORu75Ww8sYVFZmkKKjua7KDTSw96dzBVaDRN5zhwPFq6ejdTQIkyQS@hozrYSC2eB3ZCMumMMRAaMxyDr40U8ImtjRUozqb5c0Dn3HbyZ1Ad22xzdhUbNNM0K1RVWfIqrqL2xAsDTdUrqVV4HKUcOcVWqtuqoai6Y@Yyqi6uqxu16ZXzD2eJ6cWCvwaMS9mkUKVEfOrFCRcukiWEtou9qrwgrd0lNLUPJinzFIY8BxL1gbLE/6RAL1DYjEbwBjOLHwZTqElWTRA6sh1JIwSm6lzy0RZJBjdQzZHygMi1px6j8vuGtZUGaj9U7lAyFMrUd9FWocI9glopZRUGnBhVCNTXqqER@7y4kqmq4djP0smERyb1/ZBpMIC7IQaJah1gRAcmcgMo78CVkjhg@AeL6eDqPWQc17rQhcWKuMmZmFtvPUh8dRiohDCbmbHvwQ2xYygn9WRfVhpGMtmyN7lljdY98UPw9cnjp0@e/vjT46c/tsXXiAZuOMewyfuvVYPa5xgy2ghtDWldthBSJXoe3sIqR@5uYMBFaWYuyZxE4fwKGHAVujBoFncn0ivNlY/TZAXuMsGZTTbymTCSyp@u8k/F5VL8lpfHYrnqQ03ndjiq/i42FQXR5A/eehWXsEeVAnHXal6AGsjfKiR6LBtSJpOM/hm5dV6Nb41gl5bFiRumiXkfQeMGgXmeE4M2YvaqKajWWkhTh0NxPSz//AFUu9ihoEB0jDL9AUt6W8Fj7JLfjYlRTU@yTTqQFctJfXDYcgsvG2E42UDiDWEbsr2BxA69DXm6gRT3gi3IHzZlhtvtfLeBFPP3FuRZhaxIU27B2aDaIu85371numvPxe49WPy37jmu9mi0zPDGX2wuim29Rg6uDm6jPWczNy1pW75qbAuYLcEaVQYvt6sVqJQu@s2UpmZxU3fsSr/TEP62Er7EPmo10tcia4m3lcwvchHQ/u1zujVYbNP3X6RNImi13YbTuK4Z2Aik17KWVemIQlYrVW1G7aZQ4AoV5aYDqlzb3dRcgcusxwH/guowX9YVwSE602uTdBe7ct06/m3Jta95iQccRGf85Vpv/rvUu91tP3r3siuvNd8kWPl/B2CnwH2y9P@BX98mvX6LigPi/5eJu3/k9fX4fxmbwBEcKawv/wE) (Code used to generate this Knight code: [Try It Online!](https://tio.run/##ZZAxC8IwEIX3/IrzQJpYRaOLCB0cBAfBwcEhBIc2YiEmJUkHEX97TawFwSHJe7n3vuGaR7hZs1o3rus8FJAdca@0tlM4W6erEWZEx29hXUVLBlfroITagJektJWKI9whsW1o2nDRtQ8pLEnKmZTTGwI/07wQwsznnPOpGcc7yV7FIyXpoXkBVCtDPZtxBhPAHD/EQyL@0CIbhgJuEXI4iIX8FCKx93zwvV1@bXK45UhI42oTaMKwrx7ea3YqrVMbePr2Tv82oAIVk9STjL0y1nVv)) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 134 score ``` ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fexRQBegRJaunR1Dp0PboiIxdMvSB04EuGEApJAYFQO//fwA "brainfuck – Try It Online") Alas, could have scored 89 if not for the 1000 character limit. # [Boolfuck](https://github.com/TryItOnline/boolfuck), 102 score ``` ;;;+;+;;+;+;+;+;+;+;;+;;+;;;+;;+;+;;+;;;+;;+;+;;+;+;;;;+;+;;+;;;+;;+;+;+;;;;;;;+;+;;+;;;+;+;+;+;+;+;;;;+;+;;+;;+;+;;+;;;+;;;+;;+;+;;+;;;+;+;;+;;+;+;+;;;;+; ``` [Try it online!](https://tio.run/##S8rPz0krTc7@/9/a2lobCMEEDEIRTBiNDeJhiIMFUcWRzLNGMhahD42vjWqYtvX//wA "Boolfuck – Try It Online") "Standard". [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~106~~ ~~652~~ ~~192~~ 428 bytes, score ~~332~~ ~~272~~ ~~272~~ 204 ``` 11 11+11+11+11+11+1+1+1+1+1+1+P11 11+11+11+11+11+11+11+11+1+1+P11 11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+P11 11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+P11 11+11+11+11+11+11+11+11+11+1+P11 11+11+11+P11 11+1+1+1+1+1+1+1+1+1+1+P11 11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1+P11 11+11+11+11+11+11+11+11+11+1+P11 11+11+11+11+11+11+11+11+11+1+1+1+1+P11 11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+P11 11+11+11+11+11+11+11+11+1+P11 11+11+P ``` [Try it online!](https://tio.run/##S0n@/9/QUMHQUBsFIcEALNLI6gjJk2YaCaoxFMA4xBtEsZW4zaRmsCBkA/7/BwA "dc – Try It Online") 4 characters used: `+1P` and the space character. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~344~~ \$\cdots\$ ~~254~~ 242 bytes, score ~~1624~~ 1575 Lowered score by 49 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved 12 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` h;t;u;i;a;main(c){u+=u=i+=i=a=c+c+c;t=u+u+u;putchar(putchar(t+t)+u+u+a+c+c);putchar(putchar(putchar(h=t+t+t))+a);putchar(t+i+c+c);putchar(u+u+i+c+c);putchar(t+t+u+a);putchar(h+a);putchar(h+i);putchar(h);putchar(t+t+u+u+a+c);putchar(u+u+i+a);} ``` [Try it online!](https://tio.run/##ZY5BCoBACEWvM4N0AvEw4qJxUUToKjr75ARRM/EXH/3/iTLNIrUWNHRUZFxY1yT5cCAnBVJiEgihkUMINzcpvKfHDSy3ALjV8i9/vFA0o5uB35KB9lQ7NKwa5l@o9IN@hpG6vxqvB33WegE "C (gcc) – Try It Online") Uses characters: `()+;=achimnprtu{}` [Answer] # [Grass](http://www.blue.sky.or.jp/grass/), score 324, 623 bytes ``` wvwwWWwWWWwvWwwwwWWwWWWwWWWWwWWWWWwWWWWWWwWWWWWWWwWwwwwwwwwwwwwWWWWwWWWWWWWwWWWWWWWWWWWWWWwWWWWWWWWWWWwwWWWWWWWWWWwwWWWWWWWWWWWWwWWWWWWWWWWwwWWWWWWWWWWwwwwwwwWWWWWWWWWWWWWWwWWWWWWWWWWWWWWWWwWWWWWWWWWWWWWWWWWWWWWWwWWWWWWWWWWWWWWWWWWWwwWWWWWWWWWWWWWWWWWWwwWWWWWWWWWWWWWWWWWWwwwwwWWWWWWWWWWWWWWWWWWWWWwwWWWWWWWWWWWWWWWWWWWWWWWwWWWWWWWWWWWWWWWWWWWWWWWWWWwwwwwwwwwwwwwwwwwwwwwwwwwwwWwwwwwwwwwwwWWwwwwwwwWWWwwwwwwwWWWWwWWWWWwwwwwwwwWWWWWWwwwwwwwwwwwwwwwwwWWWWWWWwwwwwwwwwwwwwwwwwwwwwWWWWWWWWwwwwwwwwwwwwwwwwwWWWWWWWWWwwwwWWWWWWWWWWwwwwwwwwwwwWWWWWWWWWWWwwwwwwwWWWWWWWWWWWWwwwwwwwwwwwwwwwwwwWWWWWWWWWWWWWwwwwwwwwwwwwwwwwwwwwwwwwww ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 618 bytes, score 265 ``` ((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())()()()()()()()())()()()()()())[()()()])[()()()()()()()()()()()()()()()()()()()()()()()()])(((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())()()()()()()()()()()()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())[()()()]))[()()()()()()()])[()()()()()()()()()()()()()()()()()()()()()()()()()()()()()]) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMCNCmFmhqDAuIX0IyG0LEwBvEwVlODOkE16EMQHkbogURGqCFr/v//v65uYnFyZiYA "Brain-Flak – Try It Online") Used characters: `()[]` Uses `()` (one), `(...)` (sum and push), `[...]` (negate). Can definitely be shorter by using `[]` (stack height) but it's not the point of the challenge (as long as the code is under 1000 bytes). Looks like the program can't fit into 1000 bytes using only `()` and `(...)`. [Answer] # [Python 2](https://docs.python.org/2/), 574 bytes, score 564 ``` exec"%c"%(111+1)+"%c"%(111+1+1+1)+"%c"%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+"%c"%(11+11+11+11+11+11+11+11+11+11)+"%c"%(111+1+1+1+1+1)+"%c"%(11+11+11+1+1+1+1+1+1)+"%c"%(11+11+11+11+11+11+1+1+1+1+1+1)+"e%c"%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+"%c"%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+"%c"%111+"%c"%(11+11+11+11)+"%c"%(11+11+1+1+1+1+1+1+1+1+1+1)+"%c"%(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)+"%c"%111+"%c"%(111+1+1+1)+"%c"%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+"%c"%(11+11+11+11+11+11+11+11+11+1)+"%c"%(11+11+11)+"%c"%(11+11+11+1+1+1+1+1+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P7UiNVlJFYg0DA0NtQ01tZE42igC2jgRAhKjGtMO7DqJMhVFUSoJLiXHdyh6QK7H0IxmHqkWEmUZ5U7HqwddDd6I@f8fAA "Python 2 – Try It Online") Used characters: `exc"%(1+)` Constructs the string `print'Hello, World!'` using the characters `"%c(1+)`, then `exec`s it. Using the raw `print` with any single extra character costs more than this. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 282 (251 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) ``` 0>>>0>>>>>>>>>0>0>>>0>>>>>>>>0>>>>>0>>>0 0>>>>>>0>>>>>>>>0>>>>>>>>0>>>>0>>>>>>>0>>0 0>>>>>>>0>>>0 0>>>>>0>>>>>>>>>0>>0>>>0>0>>>>>>0 0>>>>>>>J 0>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>B ``` [Try it online.](https://tio.run/##yy9OTMpM/f/fwM7ODoQhwMAOhW8AJw0UDJCFMBgGCA5cKYpGZDuglsBMhKv3UkCooj1w@v8fAA) Five characters used: [`0> JB`](https://tio.run/##yy9OTMpM/f//8Ezbw@3@Ov//G9jZ2YEwBBjYofAN4KSBggGyEAbDAMGBK0XRiGwH1BKYiXD1XgoIVbQHTgA) **Explanation:** 1. First we construct the number `39138530688472073059231607`. We do this per digit, by pushing a `0` and increasing it by 1 per `>`, after which the entire stack of digits is joined together with `J`. 2. Then it pushes another `0` with 107 `>`s to get the number `107`. 3. After which it will convert `39138530688472073059231607` to base-107 with `B`, which is `"Hello, World!"`. [Answer] # Help, WarDoq!, 1 byte, Score: 72 ``` H ``` [Try It Online!](http://cjam.aditsu.net/#code=l%3AQ%7B%22HhEeLlOoWwRrDd%2C!AaPpQq%22Q%7C%5B%22Hh%22%22ello%22a%5B'%2CL%5DSa%22Ww%22%22orld%22a%5B'!L%5D%5D%3Am*%3A%60%5B%7Briri%2B%7D%7Briri%5E%7D%7Brimp%7D%7Brizmp%7DQ%60Q%7B%5C%2B%7D*%60L%5D%2Ber%3A~N*%7D%3AH~&input=H) [Answer] # [H🌍](https://esolangs.org/wiki/H%F0%9F%8C%8D), 2 bytes, score 223 ``` hw ``` [Try it online!](https://tio.run/##dZDBCsIwDIbve4osJwtDBG9C776BF28uI4XQ1m5Qffpaaw@Tbv8lkHz5CPHvhZ09p/RwI4EG5IhdN7kAYiyBsfAdHGcvZjng3aK6dJDjg7G5cSURN0ApPYKZyprWyIxAMlOBf8GbCzIOUMofHGMLV3MLc9w1t2dE3jFnqmZlzr1N8xYcW7h8bJUK9xqfLUyv/NCTUil9AA "H🌍 (in Python 3) – Try It Online") [Answer] # [Bits](https://github.com/nayakrujul/bits), score: 97 There are only 2 distinct characters in Bits, `0` and `1`. These have ASCII values of \$48\$ and \$49\$, so the score is \$97\$. If you're interested, this is actually only 10 bytes (80 bits). ``` 10010000001010011000011000011110111000111111010111001111010010001100000100011101 ``` ### Explanation ``` 1001000 // H 000101 // e 001100 // l 001100 // l 001111 // o 011100 // , 011111 // 1010111 // W 001111 // o 010010 // r 001100 // l 000100 // d 011101 // ! // [implicitly joined and output] ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 234 bytes, score 259 ``` llllllll+++l+++++lllllllllllll+++++l++++++++llllllllllll+++++l+l+++++++llllllllllll+++l+++++++++lllllllllll+++l++++++++lllllll++ll++l+++++llll+++l+l+lll++l+$llllllll++++++l++l+llllll+++lll+++++llllllll+++++++lll++l+l+l+llllll++++l++$H ``` [Try it online!](https://tio.run/##S8/PScsszvj/PwcKtLW1QRhIIgOIiDYUYJHJwS4F16KNQxwuBMZwIaiZEBltFRTLtMFiCKNyUN2LMBhqBkIpSKeKx///AA "Gol><> – Try It Online") Used characters: `l` (length of stack), `+` (add top two numbers), `$` (swap top two numbers), `H`. `$` was needed because some characters (space, H) were impossible to create at that specific stack height; it is cheaper than any number literal (minimum being 0). --- # [Gol><>](https://github.com/Sp3000/Golfish), 182 bytes, score 315 ``` ssP0ssssssPPPP0ssssssPPPPPPPPPPPP0sssssssPP0ssssssPPPPPPPPPPPPPPP0sssssPPPPPPP0ss0ssPPPPPPPPPPPP0ssssssPPPPPPPPPPPPPPP0ssssssPPPPPPPPPPPP0ssssssPPPPPPPPPPPP0ssssssPPPPP0ssssPPPPPPPPH ``` [Try it online!](https://tio.run/##S8/PScsszvj/v7g4wKAYDAKAAIkJA1ChYqyScHkExwCrdqyaikkQMkCW9Pj/HwA "Gol><> – Try It Online") Used characters: `0` (push zero to the stack), `s` (add 16 to top), `P` (increment top), `H` (halt and print everything on the stack as characters). [Answer] # [C (gcc)](https://gcc.gnu.org/), 540 bytes, score 1563 ``` main(){putchar(11+11+11+11+11+11+1+1+1+1+1+1);putchar(11+11+11+11+11+11+11+11+11+1+1);putchar(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1);putchar(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1);putchar(11+11+11+11+11+11+11+11+11+11+1);putchar(11+11+11+11);putchar(11+11+1+1+1+1+1+1+1+1+1+1);putchar(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1);putchar(11+11+11+11+11+11+11+11+11+11+1);putchar(11+11+11+11+11+11+11+11+11+11+1+1+1+1);putchar(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1);putchar(11+11+11+11+11+11+11+11+11+1);putchar(11+11+11);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oLQkOSOxSMPQUBsdIaCmNR5lSOqJVadNlunk6MKlEEOQdAuo7STcdtAygDBVaVrX/v8PAA "C (gcc) – Try It Online") This is just a straightforward solution that prints the ASCII code of each character in turn, like some of the other solutions here. I'm not aware of any tricky way to reduce the score in C. [Answer] # Rust, 35 bytes, Score: 1916 ``` fn main(){print!("Hello, World!")} ``` I don't know if you can get any shorter in Rust. [Answer] # [Bash](https://www.gnu.org/software/bash/), 18 bytes, score 1005 ``` echo Hello, World! ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I1/BIzUnJ19HITy/KCdFESIUnJxflGqlYGhgYPofAA "Bash – Try It Online") [Answer] # [PHP](https://php.net), 13 bytes, score 802 ``` Hello, World! ``` [Try it online!](https://tio.run/##K8go@P/fIzUnJ19HITy/KCdF8f9/AA "PHP – Try It Online") [Answer] # [naz](https://github.com/sporeball/naz), 732 bytes, score 372 ``` 1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o1a1a1a1a1a1a1a1o1o1a1a1a1o1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o1s1s1s1s1s1s1s1s1s1s1s1s1o1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1o1a1a1a1o1s1s1s1s1s1s1o1s1s1s1s1s1s1s1s1o1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1s1o ``` Uses `1`, `a`, `s` and `o`. Without the size restriction, naz `-u` could achieve a theoretical score of 257 by foregoing `s`. [Answer] # [2/9 of an esolang](https://esolangs.org/wiki/2/9_of_an_esolang), 1 byte, score = 64 ``` @ ``` [Answer] # [G\*](https://esolangs.org/wiki/G*), 15 bytes, score = 914 ``` p Hello, World! ``` [Answer] # [Perl 5](https://www.perl.org/), 386 bytes, score = 818 ``` say chr 11+11+11+11+11+11+1+1+1+1+1+1,chr 11+11+11+11+11+11+11+11+11+1+1,chr 11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,chr 11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,chr 111,chr 11+11+11+11,chr 1+1+1+1+1+1+1+1+1+1+11+11,chr 11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,chr 111,chr 111+1+1+1,chr 11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,chr 11+11+11+11+11+11+11+11+11+1,chr 11+11+11 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhOaNIwdBQGx0hoA4OFUhKiVCiTaqZWDVgaITwtbFAhCxRFmBYQaFLcWtAUfD//7/8gpLM/Lzi/7q@pnoGhgYA "Perl 5 – Try It Online") [Answer] # [Nim](http://nim-lang.org/), 387 bytes, score 601 ``` ecHO cHR 11+11+11+11+11+11+1+1+1+1+1+1,cHR 11+11+11+11+11+11+11+11+11+1+1,cHR 11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,cHR 11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,cHR 111,cHR 11+11+11+11,cHR 11+11+1+1+1+1+1+1+1+1+1+1,cHR 11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1,cHR 111,cHR 111+1+1+1,cHR 11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1,cHR 11+11+11+11+11+11+11+11+11+1,cHR 11+11+11 ``` [Try it online!](https://tio.run/##y8vM/f8/NdnDXyHZI0jB0FAbHSGgDg4VSEqJUKJNqplYNWBoROaTZA1BKyh0KW4NKAr@/wcA "Nim – Try It Online") Chars: `ecHRO, +1` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 430 bytes, score 191 ``` ++++++++++++C+++++++++++11 11 11 11 11 11 1 1 1 1 1 1C++++++++++11 11 11 11 11 11 11 11 11 1 1C+++++++++++++++++11 11 11 11 11 11 11 11 11 1 1 1 1 1 1 1 1 1C+++++++++++++++++11 11 11 11 11 11 11 11 11 1 1 1 1 1 1 1 1 1C111C+++11 11 11 11C+++++++++++11 11 1 1 1 1 1 1 1 1 1 1C++++++++111 1 1 1 1 1 1 1 1C111C+++111 1 1 1C+++++++++++++++++11 11 11 11 11 11 11 11 11 1 1 1 1 1 1 1 1 1C+++++++++11 11 11 11 11 11 11 11 11 1C++11 11 11 ``` [Try it online!](http://pythtemp.herokuapp.com/?code=%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2BC%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+11+11+11+11+1+1+1+1+1+1C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+11+11+11+11+11+11+11+1+1C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1C111C%2B%2B%2B11+11+11+11C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+1+1+1+1+1+1+1+1+1+1C%2B%2B%2B%2B%2B%2B%2B%2B111+1+1+1+1+1+1+1+1C111C%2B%2B%2B111+1+1+1C%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1C%2B%2B%2B%2B%2B%2B%2B%2B%2B11+11+11+11+11+11+11+11+11+1C%2B%2B11+11+11&debug=0) [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 1 byte, score 119 ``` w ``` [Try it online!](https://tio.run/##S0lNTEnLLM7Q/f@//P9/AA "Deadfish~ – Try It Online") Not so interesting [Answer] # Excel, 409 bytes, score 558 ``` =CHAR(11+11+11+11+11+11+1+1+1+1+1+1)&CHAR(11+11+11+11+11+11+11+11+11+1+1)&CHAR(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)&CHAR(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)&CHAR(111)&CHAR(11+11+11+11)&CHAR(11+11+1+1+1+1+1+1+1+1+1+1)&CHAR(11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1)&CHAR(111)&CHAR(111+1+1+1)&CHAR(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)&CHAR(11+11+11+11+11+11+11+11+11+1)&CHAR(11+11+11) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnWphcNkTKJ6yJmTg?e=Ts6uFw) ]
[Question] [ **This is the robbers' challenge. The cops' one is [here](https://codegolf.stackexchange.com/questions/247536/smallest-subset-of-characters-required-for-turing-completeness).** In [Fewest (distinct) characters for Turing Completeness](https://codegolf.stackexchange.com/questions/110648/fewest-distinct-characters-for-turing-completeness), the goal is to find the minimum number of characters which make a language [Turing Complete](https://en.wikipedia.org/wiki/Turing_completeness)...in other words, allow it to do any computation possible with any other language. In this challenge, we'll be doing somewhat of the opposite, and finding the minimum number of characters, without which Turing Completeness is impossible. **Task:** Robbers should include an explanation of how Turing Completeness can be achieved without any characters in the cop, or a proof that this is impossible. **Scoring:** Scoring, as per normal robbers' rules, is that whoever cracks the most cops wins. **Chat room:** <https://chat.stackexchange.com/rooms/136437/smallest-subset-of-characters-required-for-turing-completeness> [Answer] # Python, cracks [Felipe Soares](/a/247641) ``` class X:__class_getitem__=exec X["print\50'Hello,\40world!')"] ``` Lack of spaces is no problem because you can use tabs. Calling an arbitrary function without parentheses is tricky but possible. [Answer] # [Python](https://www.python.org), cracks [pxeger](https://codegolf.stackexchange.com/a/247554/100664) ``` __builtins__.__dict__["\x65x\x65c"]("<stuff>") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY39eLjk0ozc0oy84rj44GclMzkkvj4aKWYCjPTChCRrBSroWRTXFKalmanpAnRBdUMMwQA) Replace the `<stuff>` with code you want to execute, escaping the banned chars. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), cracks [des54321's answer](https://codegolf.stackexchange.com/a/247575) ``` (d A (q ( (y x) (v (c (h x) (c (c (q q) (c y ())) (t x)))) ))) (d K (q ( (x) (c (q K1) (c (c (q q) (c x ())) ())) ))) (d K1 (q ( (y x) x ))) (d S (q ( (x) (c (q S1) (c (c (q q) (c x ())) ())) ))) (d S1 (q ( (y x) (c (q S2) (c (c (q q) (c y ())) (c (c (q q) (c x ())) ()))) ))) (d S2 (q ( (z y x) (A (A z y) (A z x)) ))) ``` [Try it online!](https://tio.run/##rdAxDoMwDAXQvaf4oz3CDZgz5gh0KFJVNSqqkl4@TewkVNBWDCCQHez/hJinW7hOj3uMdMYAcqATQAGec32CRtBFT3LRWDsZOTjOTQAx8zKaUyS/yE@STZPVlaTpJPrJeGHUqtFu/VW@juw31e5S7UYt6X6TDiX901zQvqEvVHbIdzqyVl/WI@nfNiyD1qZqxdTgvxXsWVl7B5JHexzf "tinylisp – Try It Online") (The three examples are the identity combinator `(S K K)`, the mockingbird combinator `(S (S K K) (S K K))`, and an infinite loop, so you'll need to halt the program to see the output from the first two.) This is an interpreter for SK combinator calculus (which is Turing complete), built in tinylisp-without-`i`. ## Usage, and principles behind this The basic idea is to do control flow via `v`, which lets us inspect an atom via using it as the name of a function. As is usual in implementations of combinator calculus, we make use of five families of combinators (`S` and `K` themselves, plus partially applied versions of them; `K` can be given one argument to produce `K1`, `S` can be given one or two arguments to produce `S1` or `S2`). In order to be able to use these for control flow with `v`, we store our combinators in a form that looks like a tinylisp function call but with one argument missing, and the arguments in reverse order: * `S` is stored as `(S)`; * `K` is stored as `(K)`; * `S` applied to one argument *x* is stored as `(S1 (q *x*))`; * `K` applied to one argument *x* is stored as `(K1 (q *x*))`; * `S` applied to two arguments *x* and *y* is stored as `(S2 (q *y*) (q *x*))`. Our combinator application operator `A` works by inserting the argument it's being given as the second element of the function it's given, in the form `(q *arg*)` (thus producing a complete tinylisp function call), and then evaluating it with `v`. (This is the reason that the arguments have to be reversed – we can't insert a value at the *end* of a list of unknown length when we have no workable control flow, but we can insert an element in any specific position relative to the start via using hardcoded chains of `h` and `t`.) `A` can be used directly to write programs (allowing specification of arbitrarily complex input), and is used indirectly in the implementation of `S2` (which is what makes loops possible). To write a complete program, you write `S` as `(q (S))`, `K` as `(q (K))`, and application of *f* to *x* as `(A *x* *f*)` (I decided to consistently reverse arguments everywhere, which is probably less confusing then reversing them only in some places). For example, the implementation of the identity function, which in Lisp syntax would be `(S K K)`, looks like this when used as input to this interpreter: ``` (A (q (K)) (A (q (K)) (q (S)))) ``` ## Explanation Most of this program is just list manipulation, building up lists from templates. The "inside" of most of these is the fragment `(c (q q) (c x ()))`. `(c x ())` inserts (`c`) `x` as the first element of an empty list (`()`), thus producing `(x)`. The fragment as a whole inserts (`c`) a literal `q` (`(q q)`) as the first element of that, thus producing `(q x)`. The same technique is then repeated to produce a list whose elements are of the form `(q x)` and which starts with an appropriate combinator, and this is the only thing done in the implementations of `S`, `S1` and `K`. `A` is very similar – the only differences are that the resulting list is evaluated as tinylisp code (`v`) rather than simply being returned, and that the list is constructed as the head of the function (`(h x)`), followed by the argument formatted as `(q y)`, followed by any arguments that may have been curried into the combinator (this is the tail of x, `(t x)`). `K1` and `S2` contain all the actual logic, and are implementations of the `K` and `S` combinators, as per the definition of SK combinator calculus; `K` returns its first argument `x` and ignores its second argument `Y`, whereas `S` returns `(A (A z y) (A z x))` (which can simply be written directly in the function body). [Answer] # C (nonportable), cracks [Pyautogui's answer](https://codegolf.stackexchange.com/a/247541) ``` const char main[]="\x48\x8d\x35\xf9\xff\xff\xff\xbf\x01\x00\x00\x00\x89\xf8\x89\xfa\x0f\x05\xeb\xf8"; ``` [Try it online!](https://tio.run/##S9ZNT07@/z85P6@4RCE5I7FIITcxMy861lYppsLEIqbCIiWmwtg0piLNEojTEDgJiA0MgdgAgS1AaiygdCJQDKQGqDc1CSSuZP3//7/ktJzE9OL/ulWpFanJxSWJydkA "C (gcc) – Try It Online") Very platform- and compiler-specific. This worked on old versions of tcc, but not on the current version. On my computer and on TIO, it works on current gcc with the `-zexecstack` command-line option, but not without. On platforms with no memory protection (e.g. DOS), this should work on pretty much any compiler (although you would of course need to change the contents of the string literal to fit the platform you were running on). The basic idea is to run arbitrary machine code by misinterpreting a string literal as a function (the "function" given above prints the letter `H` – its own first byte – infinitely many times, if run on a Linux x86-64 system). In C, type-checking is done only by the compiler, not the linker, so if you place a string literal in one translation unit (i.e. file) and a function call to it in a different translation unit, neither the compiler nor the linker will notice that one unit declared the symbol in question to be a function but the other declared it to be a character array. (Function pointers and character array pointers are the same width on most platforms, which is all the linker cares about, so it'll happily misinterpret one as the other.) How to call a function without `(`? We can't write the function call, but luckily there's an implicit call to `main` at the start of the program, and as a bonus, the implicit call is in a different file (one provided by the C implementation) than our program is, so neither the compiler nor the linker will produce an error (although several compilers have a warning for this sort of thing nowadays). So as long as our string literal is used to initialise a variable named `main`, it'll get called automatically. Further reading: [@Dennis discussing how to various get C implementations to run a variable as though it were a function](https://codegolf.stackexchange.com/a/100557). [Answer] # R, cracks [Dominic van Essen](https://codegolf.stackexchange.com/a/247589/98085) ``` autoload -> `%aut%` '%>%' %aut% 'magrittr' '1+1' %>% str2expression %>% eval ``` Replace '1+1' with arbitrary expressions, using [unicode characters](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Quotes.html) as necessary. Unfortunately was not able to run on TIO due to needing R version [>=3.6 for `str2expression`](https://cran.r-project.org/bin/windows/base/old/3.6.0/NEWS.R-3.6.0.html). Does work on [rdrr.io](https://rdrr.io/snippets/). This uses `->` which is not banned unlike `<-` and `=` to create an infix version of `autoload`, which is used to give me `magrittr` pipes, which can then be used to evaluate arbitrary strings. [Answer] # Batch script, cracks [Yousername](https://codegolf.stackexchange.com/a/247565/111305) Conditional control flow is still possible using `goto` instructions with variables, like this: ``` set /a cond = 1+1 goto tag%cond% :tag1 echo foo goto end :tag2 echo bar goto end :end ``` Where the `set /a` instruction allows you to set a variable to the result of an expression, and this variable can then be used as part of a label for a `goto` instruction. This allows arbitrary flow control, and therefore should make Batch scripts Turing complete without `if` statements [Answer] # [Haskell](https://www.haskell.org/), cracks [Unrelated String's second answer](https://codegolf.stackexchange.com/a/247623) The basic idea is to define a function `a` that makes it possible to write `a[x][y]` instead of `(x y)`. Here's the definition, and an example of using it: ``` a[x][y]=head[x]y main=a[putStrLn][a[reverse]["codegolf"]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzG6Ija6MtY2IzUxBcis5MpNzMyzTYwuKC0JLinyyYuNTowuSi1LLSpOjY1WSs5PSU3Pz0lTio39/x8A "Haskell – Try It Online") This works around the bans on horizontal whitespace and on parentheses; function arguments are now separated by `][` rather than whitespace, and because each argument is surrounded by square brackets, there's no need for any further grouping characters. Haskell uses currying for functions that take multiple arguments, meaning that `a` can handle these too (`f x y` becomes `a[a[f][x]][y]`), and we don't need a special case for them. It's also possible to define functions using similar syntax, including defining functions by cases (e.g. `f[0]=1` and on the next line `f[1]=3`); these don't need `a` to call because they have the square brackets built in, but otherwise work the same way (the square brackets still handle the grouping). This means that most of the core functionality of Haskell is available – we can call most of the built-in functions, and define our own, including conditionals. That's a Turing-complete subset (loops via recursion and conditionals via functions-defined-by-cases are available, in addition to complex data structures), so the ban on whitespace and parentheses doesn't really hurt at all, and `{` and `$` aren't required to make this subset work either. ## Explanation `head[x]` trivially evaluates to `x` – it's taking the first element of a 1-element list. The advantage over using `x` directly is that it ends with a non-identifier character, meaning that we can put a letter directly after it without needing to use whitespace. `a[x][y]=` is a pattern match, used to define a function `a`; it defines the function only in the case where it's given two single-element lists as arguments, and defines `x` and `y` to be their arguments. As such, if we call `a` as `a[x][y]`, then the `x` and `y` in the definition of `a` will be the same as the `x` and `y` at the call site. (It would be possible to give further definitions to cover the cases where `x` and `y` aren't single-element lists, but this isn't necessary to make the answer work.) [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), cracks [Not A Chair's answer](https://codegolf.stackexchange.com/a/247712) Brainfuck interpreter, updated to crack the third cop (`.=;`). Input by command line arguments; I couldn't figure out how to do output without `.`, but IO is not necessary for Turing-completeness. Maybe it's possible to do it by using something from the namespace `System.Linq.Expressions`. ``` namespace System { namespace Collections { namespace Generic { class MyList : Dictionary<int, byte> { public MyList(string s, string inp) { if(0 is var pc) {} if(0 is var i) {} if(0 is var inp_i) {} if(TryAdd(i, 0) is int) {} try { // to exit cleanly at end of program while(true) { if((s[pc] ^ '+') < 1) if(Set(i,(byte)-~this[i]) is int) {} if((s[pc] ^ '-') < 1) if(Set(i,(byte)~-this[i]) is int) {} if((s[pc] ^ '>') < 1) { if(i++ < 0) {} if(TryAdd(i, 0) is int) {} } if((s[pc] ^ '<') < 1) { if(i-- < 0) {} if(TryAdd(i, 0) is int) {} } //if((s[pc] ^ 46) < 1 && Console.Write((char)this[i]) is int) {} // uncomment for output if((s[pc] ^ ',') < 1) { try { if(Set(i, (byte)inp[inp_i++]) is int) {} } catch { } } if((s[pc] ^ '[') < 1 && this[i] < 1) { if(1 is var bal) {} if(pc++ > 0) {} while(bal > 0) { if((s[pc] ^ '[') < 1 && bal++ < 0) {} if((s[pc] ^ ']') < 1 && bal-- < 0) {} if(pc++ > 0) {} } if(pc-- < 0) {} } if((s[pc] ^ ']') < 1 && this[i] > 0) { if(1 is var bal) {} if(pc-- > 0) {} while(bal > 0) { if((s[pc] ^ ']') < 1 && bal++ < 0) {} if((s[pc] ^ '[') < 1 && bal-- < 0) {} if(pc-- > 0) {} } } if(pc++ < 0) {} } } catch {} } void Set(int i, byte s) { try { if(Remove(i) is int){} } catch {} if(Add(i, s) is int) {} } } class Program { static void Main(string[] args) { try { if(new MyList(args[0], args[1]) is var x) {} } catch { if(new MyList(args[0], "") is var x) {} } } } }}} ``` [Try it online!](https://tio.run/##nVRRi5tAEH7WXzHcw8Vg1iRw9KGIUFroSw9Kr9AHsWWz2SQLusruJhcbcn89ndXoJca06SnKOvvNzLffjMM0YZodDpJmXBeUcXgqteEZ7NxX08c8TTkzIpf6zP6ZS64EQ5vDUqo1PJZfhDbwHj6JCk5VGQppRjArDY9cB4FOsZ6l6FNDPW2UkEvQIziuhCyGiLJIRyy8CQgNG6qgYEPY7btW0WuUxa9mA@zOd1V@mM89MYLJ0IKQUuNnVAk7GI/B5MC3wgBLOZVpCdQAl3PIF1CofKloZtHPK5Fyz6g1txxrkjaBp@OCJfATBv5gCCFMMc3Ce@IGc3r27EPyYlZCxyLpEjh3J1fcX8hN7tHRvdqp2VmA8H00T1qff2ji9EQOr0Qm5A2Rx@PT2A/vqtBwf4@NJnWe8uCHEoZ7HltRNew5uK3XWrI8y7g0sMgV5GtTrM0l7VEPbSx5vTh@O63WUIuN/RNXPeT7l3o7e2DUsBV2zVWx4kF7oiP7Pu2mTb/OaHomYMGwXtGpqnXfIa4yX7DvzYzobtnPsckZtlvIfiKnJDsePToklzq0/G/SAVO8TYfkP3SIb9ChS6Rz5EqoE7f61TSK/bLPJhdzqDoNu1bUQxF0O@3qUYTRvvEs33BPtL2HHX8WzKY8/mK606D47N1mHH@tJ5edz4421ODYrTg8UiGPkzdOgKolRnml0BxK8udmSltIPElGFTae1n@FLdm2PXHD72/ed3c9jm7Der/fu4fDYRTYOyaJ68eERCSOIj8i9grDJMQ3rpKIBBHa8RUEvu/HQZSEeNl1UGFJEIYVBkGHbfn7Dw "C# (Visual C# Compiler) – Try It Online") [Answer] # [Python](https://www.python.org), cracks [pxeger's other answer](https://codegolf.stackexchange.com/a/247577) ``` __import__('os').__dict__.pop('syst\x65m')('ls -la') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3TeLjM3ML8otK4uM11POL1TX14uNTMpOBXL2C_AIN9eLK4pKYCjPTXHVNDfWcYgXdnER1TYheqBEwowA) [Answer] # Cracks [Unrelated String's Haskell answer](https://codegolf.stackexchange.com/a/247583) ``` main=fix{--}id ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GWzNyC_KISBZfEkkQ9t9K85JLM_LylpSVpuhbrchMz82zTMiuqdXVrM1MgggugFJQGAA) You can do function application by inserting an empty block comment between the function and its argument. Here I made a loop just to demonstrate. [Answer] # [Headass](https://esolangs.org/wiki/Headass), cracks [`E` by thejonymyster](https://codegolf.stackexchange.com/a/247658/104752) This is [Turing complete because it can simulate a Minsky machine with two registers](https://en.wikipedia.org/wiki/Counter_machine#Two-counter_machines_are_Turing_equivalent_(with_a_caveat)). r1 and r2 will be used as the two registers of the Minsky machine. r3 will store the state. The program has the following structure: `*initialisation* { *state handlers* ;}:;` Each non-halting state, with one exception, has a positive state number and a state handler of the form `>>+*state number*) *core* :` (the superscript denotes repetition). `>>` sets r0 to 0, then the `+`s increase it to the state number, and the `)` checks if that equals the current state. If it does, the core executes, and then the `:` jumps to after the first `;`. Otherwise, the `)` jumps to after the `:`, continuing execution into the next state handler. The exception is the last non-halting state, which omits the `:`, so that a mismatch instead jumps to the `:` *outside* the loop, ending the execution. The core of a state handler has these four possibilities: * **Increment r1 and change to state s**: `D+^>>+s(` * **Increment r2 and change to state s**: `>>]+[+s(` * **If r1 is zero, change to state s; otherwise decrement it and change to state t**: `>>+s(D^+s>)D-^>>+t(` * **If r2 is zero, change to state s; otherwise decrement it and change to state t**: `>>+s(<]>)>>]-[+t(` For both of the decrement cases, the state handler for state s must come after the decrementing one; otherwise, the program will incorrectly stop. This can be ensured by rearranging the state handlers or, if necessary, inserting extra states in between. Finally, the initialisation is `D>>+a^>>+b[+s(` to set r1 to *a*, r2 to *b*, and the state (r3) to *s*. [Answer] # [LOLCODE](http://lolcode.org/), cracks [Pyautogui's answer](https://codegolf.stackexchange.com/a/247543) So it turns out that in LOLCODE, you can use a variable as a loop variable even if it hasn't been declared, and then assign to it and otherwise treat it as a normal variable while you're still inside the loop: ``` HAI 1.2 IM IN YR ROUTER UPPIN YR HAX WILE DIFFRINT HAX AN 8388607 HAX R DIFF OF HAX AN PRODUKT OF HAX AN -1 IM OUTTA YR ROUTER KTHXBYE ``` [Try it online!](https://tio.run/##TY1BCsIwFET3OcVcQLEKmm1KE/KpJuH7o@1a3RV6/1VMK6LL9wbmTfP0mJ@vUrwhNNu9ogsoYGRwzGIZOaUPezPgTmeLjpxjCrIaE6APWh93J7Ugryui@46JY5d7@TObRt3oSm19qmbp1ZCYX1L14od2tKW8AQ "LOLCODE – Try It Online") (Adds a `VISIBLE HAX` to show what's happening in the program; this can't be included in the crack itself due to `VISIBLE` containing an `S`.) This means that it's fairly easy to work around the inability to use `S` for variable declaration, at least for integer variables; simply create a lot of nested loops that declare all the variables you need, then run your entire program on the first iteration of those loops. (You can break out of the loops via setting all the variables to known values other than 0, and using those known values as the sentinels which terminate the loops.) Other uses of `S`, and how to work around them: * `SUM`: instead of adding, multiply the right-hand side by -1 and subtract (as shown in the code sample above) * `SMALLR`: multiply by sides by -1, use `BIGGR` then multiply the result by -1 * `QUOSHUNT`: represent every number as a pair of numbers, a numerator and a denominator, effectively treating it as a rational; to multiply, multiply the numerators and denominators; to divide, multiply one number's numberator by the other's denominator and vice versa; addition, subtraction and comparison can be done by multiplying each number's numerator and denominator by the other's denominator first; if the rounding behaviour of integer division is required, you can subtract the numerator modulo the denominator from the denominator; if a crash on division by zero is required, you can manually check for the denominator being zero and exit the program manually via setting all the variables to values that will cause it to drop out of loops * `BOTH SAEM`: replace with `NOT DIFFRINT` * `VISIBLE`: there's no replacement for this, but I/O is not needed for Turing completeness * `IF U SAY SO`: there's no direct replacement for this, so you have to write the program without using functions * `SMOOSH`: there's no direct replacement for this, so you have to write the program without using strings other than string literals The `S` in `SMOOSH` almost leads to a difficult philosophical problem: is LOLCODE Turing-complete without functions or calculated strings? The issue is that the stock LOLCODE interpreter has limits on the size of integers, and on the length of strings, but only the former is mentioned in the specification. If you consider both limits to be implementation details that don't block Turing-completeness, then the language is Turing-complete – you can use bignum integers to implement, e.g., [Blindfolded Arithmetic](https://esolangs.org/wiki/Blindfolded_Arithmetic). If you consider integers to be limited size but strings to be unlimited size, then the language is not Turing-complete without `S` due to the inability to store arbitrary amounts of data – there's no way but `SMOOSH` to create new strings. Fortunately, the problem was probably resolved in advance by the cop question itself (which specifies that "actual 'Turing Completeness'" is not required when running into "things like maximum sizes for pointers" – the issue of maximum integer sizes seems to be comparable, although we might need a clarification from the OP to make sure), so I hope that this is a valid crack. [Answer] # [Nim](https://nim-lang.org/), cracks [Pyautogui's answer](https://codegolf.stackexchange.com/a/247539) ``` proc main = asm ".intel_syntax noprefix\nlea rdi, [rip+xyz]\ncall system\nxor edi, edi\ncall exit\nxyz\x3a\n.asciz \"ls -la /\"\n.att_syntax prefix" main() ``` I don't know Nim, but you didn't block assembly statements. This crack may need to be modified depending on the system and compiler parameters (this assumes the C backend and a Unix-like x86-64 system). Of course, it is possible to perform arbitrary computation in assembly without using the shell. [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCsIwEEX3OcWQlaKtCzduPIkjMtQUBpJpSUZIehUXFsRDeRtbWjd_8f-H955v4TCOn4e21en76mPXQCAWOBsASgFszaLO31IRpQzS9dG1nFG8I4h33sMlcr_LZbiiNOQ9pJLUBZTcRXDzYYp1cpl1GsqA-UgoNaWGB0DrE1Se4IB2LlX_tIVljZmVNluzaK62f-sf) ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 3 years ago. [Improve this question](/posts/13132/edit) Given three integers rgb, output hexadecimal representation as a string. ``` Input: Output: 72 61 139 #483D8B 75 0 130 #4B0082 0 255 127 #00FF7F ``` Shortest most unorthodox code wins [Answer] ## Ruby I was going more for the "unorthodox" part. ;) ``` 10;a= gets. split . map {| x| #x "%02X" %( x. to_i) }; $> << ?# << a[ 00 .. 1+2]. join; ``` The font (on my web browser) is a bit tall, so it looks distorted, but it looks better in Courier New: ![image](https://i.stack.imgur.com/bO97b.png) Sample run: ``` c:\a\ruby>rgb2hex 255 100 0 #FF6400 ``` [Answer] # Ruby: 19 characters ``` $_=?#+"%02X"*3%$F ``` Sample run: ``` bash-4.1$ ruby -pae '$_=?#+"%02X"*3%$F' <<< '72 61 139' #483D8B bash-4.1$ ruby -pae '$_=?#+"%02X"*3%$F' <<< '75 0 130' #4B0082 bash-4.1$ ruby -pae '$_=?#+"%02X"*3%$F' <<< '0 255 127' #00FF7F ``` [Answer] # q/k (3 chars) Not exactly unorthodox but quite short ``` 4h$ ``` Example ``` q)4h$ 72 61 139 0x483d8b ``` To match the output format in the question exactly, we can do (for 9 chars): ``` "#",/$4h$ ``` [Answer] ## PowerShell: 71 52 51 41 > > Thanks to @manatwork for pointing out `ForEach-Object` can be used in place of a `for` loop. > > Thanks to @Joey for pointing out that I could use `-join` on the loop output, instead of having to put it into variables. > > > **Golfed code:** ``` '#'+-join(1..3|%{"{0:X2}"-f+(read-host)}) ``` **Note:** There's no error checking here for invalid inputs. The script will happily take 256, 4096, and 65536 as inputs, then output #100100010000 (which obviously won't work as RGB). **Ungolfed, with comments:** ``` # Put a hashtag in front of the output. '#'+ # Join the nested code into one string. -join( # Pipe 1..3 to ForEach-Object to run a loop three times. 1..3|%{ # Take user input and format it as hex, with minimum two digits in output. "{0:X2}"-f+(read-host) } ) ``` [Answer] ### bash ~~22~~ 21 chars (Thanks @manatwork for 1 char using `\` instead of double-quotes) ``` printf \#%02X%02X%02X 12 12 12 #0C0C0C ``` or reading *STDIN* in a loop: 48 chars: ``` while read f;do printf "#%02X%02X%02X\n" $f;done <<<$'72 61 139\n75 0 130\n0 255 127' #483D8B #4B0082 #00FF7F ``` ### Added 2015-10-06: bash (more *unorthodox* method) ~~84~~ 83 chars ``` c=({0..9} {a..f}) d=\#;for b;do for a in / %;do d+=${c[$b$a 020]};done;done;echo $d ``` I know, it could be 82 chars if `020` where written `16`, but I prefer this... Or maybe `d+=${c[$b$a 0x10]}` which was first post. ``` hexcolor() { local a b c=({0..9} {a..f}) d=\# for b ;do for a in / % ;do d+=${c[$b$a 0x10]} done done echo $d } hexcolor 72 61 139 #483d8b hexcolor 75 0 130 #4b0082 hexcolor 0 255 127 #00ff7f ``` ### Another [bash](/questions/tagged/bash "show questions tagged 'bash'") approach ``` #!/bin/bash browser=firefox # google-chrome iceweasel url="data:text/html;charset=UTF-8,<html><head></head><body>" url+="<script type='text/javascript'> function h(i){var h=i.toString(16);if(16>1*i)h='0'+h; return h};function C(r,g,b){return'\043'+h(r)+h(g)+h(b)}; function m(){ var r=1.0*R.value; var g=1.0*G.value; var b=1.0*B.value; var fore='black';if(384>r+g+b)fore='white';var c=C(r,g,b); s.setAttribute('style','background:'+c+';color:'+fore+';');s.innerHTML=c}; function w(e){console.log(e);var val=e.target.value;var q=1;if(e.shiftKey) q=15;if(e.detail){if(e.detail>0){q=0-q;}}else if(0>e.wheelDelta){q=0-q;}; val=1*val+q;if(val>255)val=255;if(0>val)val=0;e.target.value=val;m(); }; function k(e){console.log(e);var val=e.target.value;var q=1;if(e.shiftKey)q= 15;if(e.keyCode==38){val=1*val+q;if(val>255)val=255;e.target.value=val;m();} else if(e.keyCode==40){val=1*val-q;if(0>val)val=0;e.target.value=val;m();}}; function n(){R=document.getElementById('R');G=document.getElementById('G'); B=document.getElementById('B');s=document.getElementById('s'); R.addEventListener('DOMMouseScroll',w);R.addEventListener('mousewheel',w); G.addEventListener('DOMMouseScroll',w);G.addEventListener('mousewheel',w); B.addEventListener('DOMMouseScroll',w);B.addEventListener('mousewheel',w); m();};var R, G, B, s;window.onload=n; </script><style>div{display:inline-block;width:10em;}</style> <div id='s'>&nbsp;</div>" input="%s:<input type='text' size='5' value='200'" input+=" onKeyDown='k(event)' onChange='m()' id='%s' />" for c in R G B ;do printf -v add "$input" $c $c url+="$add" done $browser "$url" ``` This will display a browser window, with: ![RGB int 2 hex viewer converter](https://i.stack.imgur.com/aEcsE.png) Where you could roll the mousewheel to change values (with shift key holded for step by 15)... [Answer] ## Perl, 31 characters ``` perl -nE 'say"#",map{unpack H2,chr}split' ``` It's hard to make such a short program unorthodox, but I think this works. [Answer] ## Action Script 3 | 43 characters ``` trace("#"+(72<<16|61<<139|b).toString(16)); ``` Output: `#483D8B` [Answer] ### Perl *24* chars ``` perl -ne 'printf"#"."%02x"x3,split' 13 31 133 #0d1f85 ``` Sorry, it's not as sexy than using `unpack`, but shorter! ### More obscure version: But if you really prefer to use `unpack`, then you could: ``` $==24;s/\d+[\n ]*/{$=-=8;($&<<$=).do{rand>.5?qw<+>[0]:"|"}}/eg;$_= pack("N",eval($_.587.202.560));say$1,unpack("H6",$2)if/^(.)(.*)$/s ``` For sample, it's not the shorter version, but I like it! ( Note the use of `rand` for *randering* this :-) ``` perl -nE ' $==24;s/\d+[\n ]*/{$=-=8;($&<<$=). do{rand>.5?qw<+>:"|"}}/eg;$_=pack( "N",eval($_.587.202.560) );say $1, unpack("H"."6",$2) if /^(.)(.*)$/s ' <<< $'72 61 139\n75 0 130\n0 255 127' #483d8b #4b0082 #00ff7f ``` [Answer] # [><>](http://esolangs.org/wiki/Fish) ~~103~~ 60 ``` "#"or>1[:82*%:}-82*,86*+:"9"v ;^?l ]o+*7)"9":+*68o+*7)< ``` Made use of the wasted white space, and moved some code into it Run with command line inputs: ``` python fish.py generateHex.fish -v 255 36 72 ``` output: "#FF2448" [Answer] ## Forth, 62 characters ``` : D 0 <<# # # #> TYPE #>> ; 35 EMIT HEX SWAP ROT D D D DECIMAL ``` [Answer] ## C (67 chars no main boilerplate) ``` int r,g,b; scanf("%d %d %d",&r,&b,&g); printf("#%06x",r<<16|g<<8|b); ``` the bog standard printf & bit twiddler usage [Answer] # Dc: ~~35~~ 32 characters ``` [#]n16o?ShShSh[Lhd16/n16%n]ddxxx ``` Sample run: ``` bash-4.1$ dc -e '[#]n16o?ShShSh[Lhd16/n16%n]ddxxx' <<< '72 61 139' #483D8B bash-4.1$ dc -e '[#]n16o?ShShSh[Lhd16/n16%n]ddxxx' <<< '75 0 130' #4B0082 bash-4.1$ dc -e '[#]n16o?ShShSh[Lhd16/n16%n]ddxxx' <<< '0 255 127' #00FF7F ``` ## Dc: ~~27~~ 24 characters (But needs the input numbers on separate lines.) ``` [#]n16o[?d16/n16%n]ddxxx ``` Sample run: ``` bash-4.1$ dc -e '[#]n16o[?d16/n16%n]ddxxx' <<< $'72\n61\n139' #483D8B bash-4.1$ dc -e '[#]n16o[?d16/n16%n]ddxxx' <<< $'75\n0\n130' #4B0082 bash-4.1$ dc -e '[#]n16o[?d16/n16%n]ddxxx' <<< $'0\n255\n127' #00FF7F ``` [Answer] **JavaScript, 89 chars** ``` console.log('#' + ('00000' + eval('256*(256*(' + DEC.replace(/ /g, ')+')).toString(16)).slice(-6)) ``` Converts `72 61 139` to `256*(256*(72)+61)+139` and evals it. [Answer] ## PowerShell, 45 ``` '#'+-join(-split(read-host)|%{'{0:X2}'-f+$_}) ``` Or, if it can be used by piping in the data, you can just use ``` '#'+-join(-split"$input"|%{'{0:X2}'-f+$_}) ``` which brings it down to **42**. [Answer] ## powershell 37 saved one byte thanks to TimmyD ``` cat rgb2hex.ps1 $args|%{$o+="{0:X2}"-f[byte]$_};"#$o" wc -c rgb2hex.ps1 38 rgb2hex.ps1 powershell -f .\rgb2hex.ps1 72 61 139 #483D8B powershell -f .\rgb2hex.ps1 0 255 127 #00FF7F ``` [Answer] # R, 16 bytes That's it. Use the built in. ``` rgb(r,g,b,m=255) ``` [Answer] ## C, ~~67~~ 73 Characters (65 Chars excluding main) ``` main(){int a,b,c;scanf("%d%d%d",&a,&b,&c);printf("#%02X%02X%02X",a,b,c);} ``` Boring C program - very orthodox. [Answer] ## Python 2.7 (80 Characters) ``` x=lambda y: ("0"+hex(int(y))[2:])[-2:] print "#"+''.join(map(x,input().split())) ``` I'm looking for a better way to handle the single digit hex values. Any ideas? [Answer] ### Befunge-98, 45 characters Bleh, duplicated code. Oh well. Just a straightforward implementation of radix conversion. ``` "#",v 7*+,>#@&:97+/"0"+:"9"`7*+,97+%"0"+:"9"` ``` Sample run ``` % cfunge tohex.98 <<<'72 61 139' #483D8B % cfunge tohex.98 #75 0 130 4800820 255 127 00FF7F ``` (Note: prints '#' before reading input---the task doesn't forbid this; given three numbers on stdin it produces the right output on stdout. It also doesn't bother with newlines, and as you can see it doesn't add '#' properly when run "interactively".) [Answer] ## Game Maker Language, 175 (Error at position 81) Prompts for 3 to 9-digit RGB. Returns hexadecimal with GML hexadecimal sign, `$` ``` d=get_string('','')if(d=='')e=""else e="00"h="0123456789ABCDEF"while(d!=''){b=d&255i=string_char_at(h,byte div 16+1)l=string_char_at(h,byte mod 16+1)e+=i+l;d=d>>8}return '$'+e ``` Make this a script. Also, compile with uninitialized variables treated as 0. [Source](http://www.gmlscripts.com/script/dec_to_hex) [Answer] # Gema, 93 characters ``` \B=@set{x;0123456789abcdef}\# <D>=@substring{@div{$1;16};1;$x}@substring{@mod{$1;16};1;$x} ?= ``` Sample run: ``` bash-4.3$ gema '\B=@set{x;0123456789abcdef}\#;<D>=@substring{@div{$1;16};1;$x}@substring{@mod{$1;16};1;$x};?=' <<< '0 255 127' #00ff7f ``` [Answer] ## Burlsque, 12 bytes (10 bytes for lower-case) If lower-case is allowed as well then 10 bytes: ``` psb6\['#+] ``` Usage: ``` blsq ) "72 61 139"psb6\['#+] "#483d8b" ``` If you desperately need upper-case, add `ZZ`: ``` blsq ) "72 61 139"psb6\['#+]ZZ "#483D8B" ``` If you don't receive the integers as in a string then go with: ``` blsq ) {72 61 139}b6\['#+] "#483d8b" ``` **Explanation:** ``` ps -- parse string b6 -- to hex \[ -- concat '#+] -- prepend # ``` [Try online here](http://104.167.104.168/~burlesque/burlesque.cgi?q=%7B72%2061%20139%7Db6%5C[%27%23%2B]). **Bonus:** To convert it back use this: ``` blsq ) "#483d8b"[-2cob6 {72 61 139} ``` [Answer] # Powershell, 28 bytes ``` '#{0:X2}{1:X2}{2:X2}'-f$args ``` Test script: ``` $f = { "#{0:X2}{1:X2}{2:X2}"-f$args } @( ,('#483D8B',72, 61, 139) ,('#4B0082',75, 0, 130) ,('#00FF7F',0 ,255, 127) ) | % { $e,$a = $_ $r = &$f @a "$($r-eq$e): $r" } ``` Output: ``` True: #483D8B True: #4B0082 True: #00FF7F ``` [Answer] # Python3.3 @ 60 chars ``` print("#"+3*"%.2X"%tuple(int(n) for n in input().split())) ``` Couldn't resist: ``` [dan@danbook:code_golf/int_to_hex]$ python3.3 int_to_hex.py 176 11 30 #B00B1E ``` [Answer] # Clojure 76 Characters This might be late, for the sake of completeness: ``` (defn hexy [r g b] (reduce str (cons "#" (map #(format "%02X" %) [r g b])))) ``` Example calls: ``` (hexy 0 255 127) "#00FF7F" ``` [Answer] # Mathematica, 40 characters ``` f = StringJoin["#", IntegerString[#, 16, 2]] & rgbs = {{72, 61, 139}, {75, 0, 130}, {0, 255, 127}} f /@ rgbs // Column ``` > > #483d8b > > > #4b0082 > > > #00ff7f > > > [Answer] ## Common Lisp, 39 characters ``` (format()"#~@{~2,'0x~}"#1=(read)#1##1#) ``` Read three integers, return a string. [Answer] # Javascript ES6, 63 bytes ``` h=>'#'+h.split` `.map(x=>(x<16?0:'')+(x*1).toString(16)).join`` ``` [Answer] # Python 2, 40 bytes ``` s='#';exec's+="%02X"%input();'*3;print s ``` Reads the input from three separate lines. Abuses `exec` and string multiplication. Example usage: ``` $ python2 rgbint.py 72 61 139 #483D8B $ python2 rgbint.py 75 0 130 #4B0082 $ python2 rgbint.py 0 255 127 #00FF7F ``` [Answer] # Python (55 chars) ``` '#'+''.join([hex(int(i))[2:].upper() for i in input()]) ``` ]
[Question] [ Idea from the [doubler challenge](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output), this may be more difficult. The program should output a positive integer or decimal point value higher than 0. If I duplicate the source code, the output should halve the original integer or decimal point value. But the trickier part is: If I duplicate your code any integer value \$n\$ times, the output should divide by the original integer or decimal point value \$n\$ times too! Edit: As per my mistake (see [Jonah's comment](https://codegolf.stackexchange.com/questions/222818/double-it-then-half-it-but-multiply-it-then-divide-it?noredirect=1#comment516918_222818)) you can divide by `2^n` too. # Rules * The output must be printed to the program's default STDOUT. * The initial source must be at least 1 byte long. * Both the integers (or decimal point values) must be in base 10 (outputting them in any other base or with scientific notation is forbidden). * Your program must *not* take input (or have an unused, empty input). * Outputting the integers with trailing / leading spaces is allowed. * You may not assume a newline between copies of your source. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest (original) code in each language wins! * **[Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)** apply. ### Example Let's say your source code is `ABC` and its corresponding output is `2`. If I write `ABCABC` instead and run it, the output must be `1`. If I write `ABCABCABC` instead and run it, the output must be `0.5` (or `0.3333333`). This uses uses [@manatwork's layout](https://codegolf.meta.stackexchange.com/questions/5139/leaderboard-snippet/7742#7742). ``` /* Configuration */ var QUESTION_ID = 222818; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 96037; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>'; lang = jQuery(lang).text().toLowerCase(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.uniq > b.uniq) return 1; if (a.uniq < b.uniq) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr> </tbody> </table> ``` Disclaimer: Example and Rules from the [original challenge](https://codegolf.stackexchange.com/questions/132558/i-double-the-source-you-double-the-output) with modifications. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` o⁹H ``` [Try it online!](https://tio.run/##y0rNyan8/z//UeNOj///AQ "Jelly – Try It Online") [Try it online!Try it online!](https://tio.run/##y0rNyan8/z//UeNODzDx/z8A "Jelly – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##y0rNyan8/z//UeNODwTx/z8A "Jelly – Try It Online") ## How It Works ``` o⁹H - Main link. Takes implicit argument of 0 o⁹ - Logical OR of 0 and 256 H - Halve to 128 o⁹Ho⁹H - Main link. Takes implicit argument of 0 o⁹ - Logical OR of 0 and 256 H - Halve to 128 o⁹ - Logical OR of 128 and 256 H - Halve to 64 ``` And so on [Answer] # [R](https://www.r-project.org/), 9 bytes ``` a=T=T/2;T ``` [Try it online!](https://tio.run/##K/r/P9E2xDZE38g65L@yQkl5vkJJZm5qsRVXUa5GiCYXXBLO4AKqyihKTSWkDllDWn5pEdHqEe4BAA "R – Try It Online") `T` is a (built-in) shortcut for `TRUE`, which is automatically initialized to a numeric value of `1`. We redefine it to half what it was before using `T=T/2`. [R](https://www.r-project.org/) outputs the values of statements consisting of unassigned expressions, so `T` on its own outputs the current value of `T` (now equal to `0.5` if there's only one copy of the code). When we double (or triple...) the code, the final `T` is appended with `a=T=T/2` to become `Ta=T=T/2`: so, the previously-final unassigned `T` now becomes an assignment for the variable `Ta`, which we will never use, but which stops the value from being outputted. `T` is then halved (again), and its value (now `0.25`) output, unless there's another copy of the code... [Answer] # [Bash](https://www.gnu.org/software/bash/), 23 ``` trap echo\ $[8>>n++] 0 ``` [Try it online!](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJdrCzi5PWztWwYDr/38A "Bash – Try It Online") [Try it online!Try it online!](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJdrCzi5PWztWwYALh/D//wA "Bash – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##S0oszvj/v6QosUAhNTkjP0ZBJdrCzi5PWztWwYCLNOH//wE "Bash – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 28 bytes ``` +0and'',;True/=2. print True ``` [Try it online!](https://tio.run/##K6gsycjPM/r/X9sgMS9FXV3HOqSoNFXf1kiPq6AoM69EAcT9/x8A "Python 2 – Try It Online") - Outputs `0.5` [Try it online! x2](https://tio.run/##K6gsycjPM/r/X9sgMS9FXV3HOqSoNFXf1kiPq6AoM69EAcTFJ/f/PwA "Python 2 – Try It Online") - Outputs `0.25` [Try it online! x3](https://tio.run/##K6gsycjPM/r/X9sgMS9FXV3HOqSoNFXf1kiPq6AoM69EAcQlV@7/fwA "Python 2 – Try It Online") - Outputs `0.125` ## Explanation The built-in constant `True` is modified to be halved after every duplication with `True/=2`. This prevents the hassle of declaring a new variable. The tricky part is making sure that `True` is outputted only once. Now is where the `+0and'',` comes in. It basically fills every `print` statement with `print True+0and'',`, which outputs a space. Then on the very last line, `print True` will output the correct result. [Answer] # [Python 2](https://docs.python.org/2/), ~~42~~ 41 bytes ``` print.5**(len(open(__file__).read())/41)# ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69Ez1RLSyMnNU8jvwBIxMenZeakxsdr6hWlJqZoaGrqmxhqKv//DwA "Python 2 – Try It Online") Read the source file and divide it's byte count by 41 (the length of the original code). Then raise 2 to that power and print it. *thanks to Jonathan Allan for -1 byte* [Answer] # [Desmos](https://desmos.com/calculator), 5 bytes Original - Outputs `0.5` ``` (1/2) ``` Doubled - Outputs `0.25` ``` (1/2)(1/2) ``` Tripled - Outputs `0.125` ``` (1/2)(1/2)(1/2) ``` [Try It On Desmos!](https://www.desmos.com/calculator/ogilo4nilv) [![](https://i.stack.imgur.com/FEMIi.png)](https://i.stack.imgur.com/FEMIi.png) [Answer] # [Perl 5](https://www.perl.org/) (`-0777l070p`), ~~10~~, 6 bytes ``` ;$\/=2 ``` switches : -0777 : undef input record separator (read whole input once). -l070 : set output record separator to `070` octal character 8. -p : to print `$\/=2` : divide output record separator (coerced to number) by 2 [Try it online!](https://tio.run/##K0gtyjH9/99aJUbf1uj//3/5BSWZ@XnF/3UNzM3NcwzMDQoA "Perl 5 – Try It Online") [Try it online!Try it online!Try it online!Try it online!Try it online!](https://tio.run/##K0gtyjH9/99aJUbf1ggX@f//v/yCksz8vOL/ugbm5uY5BuYGBQA "Perl 5 – Try It Online") [Answer] # JavaScript, 44 bytes Uses a custom getter property `o.l` to execute `console.log`. Duplicating the program produces the useless code `o.lo={...}`. ``` o={get l(){console.log(o.x)},x:2};o.x/=2;o.l ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIUdDszo5P684PydVLyc/XSNfr0KzVqfCyqjWGsjUtzUCUjn//wMA "JavaScript (Node.js) – Try It Online") [Try it online!Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIUdDszo5P684PydVLyc/XSNfr0KzVqfCyqjWGsjUtzUCUjmkqP3/HwA "JavaScript (Node.js) – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIUdDszo5P684PydVLyc/XSNfr0KzVqfCyqjWGsjUtzUCUjm0Uvv/PwA "JavaScript (Node.js) – Try It Online") --- # JavaScript, 44 bytes Same approach, but using a top-level variable instead of a property. ``` o={get l(){console.log(x)}};var x=x/2||1;o.l ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIUdDszo5P684PydVLyc/XaNCs7bWuiyxSKHCtkLfqKbG0DpfL@f/fwA "JavaScript (Node.js) – Try It Online") [Try it online!Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIUdDszo5P684PydVLyc/XaNCs7bWuiyxSKHCtkLfqKbG0DofKE6C2v//AQ "JavaScript (Node.js) – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/37Y6PbVEIUdDszo5P684PydVLyc/XaNCs7bWuiyxSKHCtkLfqKbG0DofKE4jtf//AwA "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` I*=½ I // Builtin variable, initially equals 64 *= // times equals ½ // half. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=SSo9vQ==&input=) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` ⎚≦⊘φIφ ``` [Try it online!](https://tio.run/##ARwA4/9jaGFyY29hbP//4o6a4omm4oqYz4bvvKnPhv// "Charcoal – Try It Online") Outputs 500. [Try it online! Try it online!](https://tio.run/##S85ILErOT8z5//9R36xHncsedc043/Z@z8rzbej8//8B "Charcoal – Try It Online") Outputs 250. [Try it online! Try it online! Try it online!](https://tio.run/##S85ILErOT8z5//9R36xHncsedc043/Z@z8rzbYT4//8DAA "Charcoal – Try It Online") Outputs 125. Explanation: ``` ⎚ ``` Clear canvas of previous iterations. ``` ≦⊘φ ``` Halve the predefined variable for 1,000. ``` Iφ ``` Print its current value. [Answer] # [R](https://www.r-project.org/), ~~22~~ 17 bytes ``` cat(T<-T/2,"\r"); ``` [Try it online!](https://tio.run/##K/r/PzmxRCPERjdE30hHKaZISdP6/38A "R – Try It Online") Carriage return doesn't work as intended in TIO, but on my machine the next output flushes the previous one. *-5 bytes using [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)'s approach* [Answer] # Javascript ES6, 60 bytes `[0];b=function(){console.log(a)};b[0]=Map;var a=a/2||1;new b` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/2iDWOsk2rTQvuSQzP09Dszo5P684PydVLyc/XSNRs9Y6CajC1jexwLossUgh0TZR36imxtA6L7VcIen/fwA "JavaScript (Node.js) – Try It Online") Makes use of the fact that we can call a function without parantheses using `new`, and the fact [that brackets, or computed member access has a higher precedence than `new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#table) [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), ~~32~~ 30 bytes ``` 82>:0\g7%!#v_\.@ v\/2 \+2 < ``` [Try it online!](https://tio.run/##S0pNK81LT/3/38LIzsogJt1cVVG5LD5Gz4FLQaEsRt9IIUbbSMGG6/9/AA "Befunge-93 – Try It Online") To reduce the size, the code starts with 8 and does what is required. However, at some point the output will be always zero, due to the lack of the fp division. Since it's not guaranteed that the copy will have a new line char, I have included the new line char at the end of the second line in the byte count (it's really required for this to work). Code need to be back to back for it to work (I hope this is acceptable), e.g.: ``` 82>:0\g7%!#v_\.@ v\/2 \+2 < 82>:0\g7%!#v_\.@ v\/2 \+2 < ``` will output 4. Edit: saved 2 bytes by changing the comparison from subtraction to modulo. ## Explanation ``` 82 Push 8 and 2 > Execution goes right (this is where the other copies of the program start executing) : Duplicate the top of the stack (this is n*2, the line of the next copy of the program) 0g Push 0 and get the char in (0,n*2). If there are other copies of the program, this will read '8', otherwise ' ' (space) 7%! Push 7, do modulo, and not the result. 8 is 56 in ascii, 56%7=0; with space char is 32%7≠0 #v_\.@ If not zero, go down, if zero, swap the stack, print, and end the program < If not zero before, continue left. \+2 Add two to the top of the stack (the line of the next copy of the program) and swap (executed right to left) \/2 Divide the future output by 2 and swap the stack to get the correct order v Continue the execution in the code below (matches the > at the beginning). ``` [Answer] # [Scratch](http://scratch.mit.edu), ~~42~~ 43 bytes [Try it online!](https://scratch.mit.edu/projects/513616453/) I'm pretty certain that this is optimized: ``` when gf clicked change[D v]by(1 say((1)/(D ``` Alternatively, 5 blocks. [Answer] # [Pip](https://github.com/dloscutoff/pip), 5 bytes ``` h:h/2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZLM6wy9I0gbKgQTAoA) [Attempt This Online!Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuharMqwy9I3ABEQAKg6TBwA) [Attempt This Online!Attempt This Online!Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbrM6wy9I0QBEQUKglTBAA) [Answer] # Desmos, 1 or 2 bytes ``` ½ ``` outputs `0.5`. Inputting a string consisting of multiple `½` characters multiplies them together, giving ½^n. I'm not sure if this should count as 1 or 2 bytes - the `½` character is 2 bytes in UTF-8, but is present in many extended ASCII tables as well, and Desmos doesn't take files as input so it's not tied to any particular encoding afaik. [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 6 bytes ``` e[=cT2 ``` [Try it online!](https://tio.run/##K6gsyfj/PzXaNjnE6P9/AA "Pyth – Try It Online") # Explanation ``` e # Last element of list [ # Begin list = # Set to cT2 # Float division T/2 ``` *thanks to FryAmTheEggman for -2 bytes* [Answer] # [J](http://jsoftware.com/), 18 bytes ``` a=.1+a"_ ::0:0 %a ``` [Try it online!](https://tio.run/##y/qfZqtnrGBl8D/RVs9QO1EpXsHKysDKgEs1keu/Jldqcka@QpqCpeV/AA "J – Try It Online") - Returns 1 [Try it online!Try it online!](https://tio.run/##y/qfZqtnrGBl8D/RVs9QO1EpXsHKysDKgEs1kQtT5L8mV2pyRr5CmoKl5X8A "J – Try It Online") - Returns 0.5 [Try it online!Try it online!Try it online!](https://tio.run/##y/qfZqtnrGBl8D/RVs9QO1EpXsHKysDKgEs1kYsYkf@aXKnJGfkKaQqWlv8B "J – Try It Online") - Returns 0.33333 This is the body of an explicit function in J. Note that while J does not have 0 argument functions, this function ignores its input, and so should not be in violation of the "no input" rule. # how * `a` is a local variable, and `a"_` is a verb that returns the value stored in `a`. * `::0` says that if the verb `a"_` errors while executing, return `0`. This will only happen on the first line, when `a` is undefined. After this line is executed the first time, `a` will be set to `1`, since the first line will resolve as `1+0`. * On the next run of `1+a"_ ::0:0`, `a` will already be 1, and so it will resolve as `1+1`, or `2`. * Meanwhile `%a` -- the reciprocal of `a` -- will be a no-op on all lines in the middle of the function (it won't result in any output). However, the final instance of `%a` is the return value of the function. # 2^n version, 19 bytes ``` 1: :*g(g=.1r2"_ :*) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Da0UrLTSNdJt9QyLjJTigRzN/5pcqckZ@QppCob/AQ "J – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Da0UrLTSNdJt9QyLjJTigRxN4oT@a3KlJmfkK6QpGP4HAA "J – Try It Online") This starts with `1/2`, and divides by 2 one more time each time the source is repeated. This works by combining J trains with verbs that behave differently depending on if they are being called with 1 or 2 arguments. Though again, the input itself is always ignored. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes *Ties [caird coinheringaahing's Jelly answer](https://codegolf.stackexchange.com/a/222824/94066) for #1.* ``` X;U ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/wjr0/38A "05AB1E – Try It Online") [Try it online!Try it online!](https://tio.run/##yy9OTMpM/f8/wjoUiP7/BwA "05AB1E – Try It Online") [Try it online!Try it online!Try it online!](https://tio.run/##yy9OTMpM/f8/wjoUgv7/BwA "05AB1E – Try It Online") ``` X;U # full program U # set X to... X # variable (initalized to 1)... ; # divided by 2 # (implicit) push last popped value # implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `H`, 1 byte ``` ½ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJIIiwiIiwiwr0iLCIiLCIiXQ==) [Try it Online!Try it Online!](https://vyxal.pythonanywhere.com/#WyJIIiwiIiwiwr3CvSIsIiIsIiJd) [Try it Online!Try it Online!Try it Online!](https://vyxal.pythonanywhere.com/#WyJIIiwiIiwiwr3CvcK9IiwiIiwiIl0=) Vyxal flag abuse FTW. ]
[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/193934/edit). Closed 4 years ago. [Improve this question](/posts/193934/edit) It's simple, simply output text to STDERR containing the string `EOF`. ## Input/Output Your input will be none; however, you should output the message to STDERR. ## Rules * Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer wins. * No standard loopholes please. * Any method approved by Standard I/O is allowed. * Your code may not contain the "EOF" that you will output as-is in your error. * Outputting "EOI" is technically allowed, because the input can also be considered as a separate file. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/) 17.0, 0 bytes Dyalog 17.0 expects programs to terminate themselves cleanly and will throw an `EOF INTERRUPT` (and exit with a code 2) if they don't: [Try it online!](https://tio.run/##S0oszvj/Xz@/oEQ/N6UyMSc/Xd/QXM9A38xEvzQvMzk/JVUfIvz/PwA "Bash – Try It Online") In contrast, here is the minimal program which does terminate itself cleanly, causing no error (and code 0 upon exit): [Try it online!](https://tio.run/##S0oszvj/PzU5I1/hUd9Ufzc3hRoF/fyCEv3clMrEnPx0fUNzPQN9MxP90rzM5PyUVH2I8P//AA "Bash – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 1 byte ``` ( ``` [Try it online!](https://tio.run/##K6gsycjPM/7/X@P/fwA "Python 3 – Try It Online") A plain opening bracket is interpreted as the start of a tuple. Just having one bracket is enough to raise an EOF error. Also works with `[` and `{`. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 1 byte ``` ? ``` [Try it online!](https://tio.run/##y05N///f/v9/AA "Keg – Try It Online") When there's no input, an EOF is raised: ``` Traceback (most recent call last): File "/opt/keg/Keg.py", line 500, in <module> exec(header + code + footer) File "<string>", line 6, in <module> File "/opt/keg/KegLib.py", line 119, in Input item = input() EOFError: EOF when reading a line ``` Also works with `¿` [Answer] # JavaScript, 1 byte / 7 solutions The following tokens trigger `SyntaxError: Unexpected end of input`, or a similar message depending on the JS engine. ``` ! ( + - [ { ~ ``` Or to summarize: * unary operators * opening parenthesis / bracket / brace ### Exhaustive test on all ASCII characters ``` for(n = 0; n < 127; n++) { code = String.fromCharCode(n); res = false; try { eval(code); } catch(e) { res = e.toString() == 'SyntaxError: Unexpected end of input'; } if(res) { console.log(code); } } ``` [Try it online!](https://tio.run/##TY1BDoJADEX3nKI7hhCJujERWRFPQDzAZOgABlvSGYnGcHYcVBJ3bf/7r1c9amekG/yGuMZ5tiyKoIBtDgQn2O0PYUjTBF4RgAlIyCovHTWZFb6VrZYyXBUleQAEXcit7h3mUdi9PD9FABx1r5b@h5sWmfamVZj8gG8VM89fvUqgKCCunuT14yzCcoQL4WNA47EGpBrYQkfD3cersrMqaFajYXLcY9Zz8/95muc3 "JavaScript (Node.js) – Try It Online") [Answer] ## Turbo Assembler, 0 bytes Borland Turbo Assembler will print an "Unexpected end of file" when assembling a zero-byte file. [Answer] For the python users; the ones posting one character code, technically that is a `SyntaxError` which happens to read as an `EOFERROR`. *(FYI, here's an example of all printable single characters that would cause this same error I'm getting a total of `34`:)* ``` from string import printable chars = [] for c in printable: try: eval(c) except Exception as e: if 'EOF' in str(e): chars += [c] print(chars) ``` This prints: ``` ['!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', ']', '^', '`', '{', '|', '}', '~', ' ','\t', '\n', '\r', '\x0b', '\x0c'] ``` I'm not sure if `raise EOFError` would be considered an answer as unfortunately that's the shortest code I can think of to raise a legitimate `EOFError` in Python 3: --- # [Python 3](https://docs.python.org/3/), 14 bytes ``` raise EOFError ``` [Try it online!](https://tio.run/##K6gsycjPM/7/vygxszhVwdXfzbWoKL/o/38A "Python 3 – Try It Online") # OR **Without implicitly raising the error in Python 2 you could use this at the expense of an extra byte:** --- # [Python 2](https://docs.python.org/2/), 15 bytes ``` input('\u0004') ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzOvoLREQz2m1MDAwERd8/9/AA "Python 2 – Try It Online") [Answer] ## Haskell using hugs, 1 byte ``` { ``` The error message contains `unexpected end of input`. [Try it online!](https://tio.run/##y0gszk7NydHNKE0v/v@/@v9/AA "Haskell 98 (Hugs) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Each throws: `SyntaxError: Unexpected end of input` ``` ´ ¥ ¶ ª © « § ¨ ± µ ÷ Á Â Ò Ó ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=tA) (Errors are displayed below the output field) There are also a number of other possibilities, not specific to Japt, that are covered in Arnauld's JS solution, such as: ``` ! & | ~ ^ ``` [Answer] # [PHP](https://php.net/), 1 byte ``` 1 ``` [Try it online!](https://tio.run/##K8go@G9jXwAkDf//BwA "PHP – Try It Online") Run like this: `php -r 1` Error: `PHP Parse error: syntax error, unexpected end of file in ...` Any other characters apart from `;`, `#`, space and new line should cause a similar error. So PHP probably has `ASCII characters count - 4` single byte solutions. [Answer] # R, 1 byte, 10 solutions Any of these characters alone will trigger `Error: unexpected end of input`. ``` " ' ` ( { + - ! ? ~ ``` [Answer] # [Python 3](https://docs.python.org/3/), 1 byte Sorry for the edit, misunderstood the question at first :P. We can do [ or ( or { to get unexpected EOF error. In first case, it expects a list, in second a tuple and so on. ``` [ ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P/r/fwA "Python 3 – Try It Online") [Answer] **Perl, 1 byte** `(` Try it with ``` perl -e "(" syntax error at -e line 1, at EOF Execution of -e aborted due to compilation errors. ``` [Answer] # Java, 1 byte ``` e ``` [Try it online!](https://tio.run/##y0osS9TNL0jNy0rJ/v8/9f9/AA "Java (OpenJDK 8) – Try It Online") --- Old method that's more fun :] ``` void a()throws Exception{new java.io.DataInputStream(System.in).readInt();} ``` [Try it online!](https://tio.run/##XY4xE4IwDIVn@BUZ28H@AVcdGJwYPYdYehiEtEcD6HH89lo5J6fce8n7Xjqc8eCD4655pjDde7Jge4wRLkgMa1n8zCgoecyeGhjyStUyErfXG@DYRg3yGP0S4fyyLgj5PVqwW3aO0gaVPpbFVqadkNV/YP0ed/kdQ96cULDiMElucTio@h3FDYZYm6ybiiXjtrSlDw "Java (OpenJDK 8) – Try It Online") [Answer] # T-SQL, 21 bytes ``` RAISERROR('EOF',11,1) ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 1 ``` " ``` ### Output ``` .code.tio: line 1: unexpected EOF while looking for matching `"' .code.tio: line 2: syntax error: unexpected end of file ``` [Try it online!](https://tio.run/##S0oszvj/X@n/fwA "Bash – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 1 byte ``` ! ``` [Try it online!](https://tio.run/##KypNqvz/X/H/fwA "Ruby – Try It Online") Any of `["!", "(", "*", "+", "-", ":", "[", "{", "~"]` will work depending on the environment. [Answer] # [Ruby](https://www.ruby-lang.org/), 1 byte ``` / ``` Outputs `unterminated regexp meets end of file` [Try it online!](https://tio.run/##KypNqvz/X///fwA "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 1 byte ``` " ``` [Try it online!](https://tio.run/##K0gtyjH9/1/p/38A "Perl 5 – Try It Online") Not very inspired, but it *is* the shortest possible in the language. Outputs `Can't find string terminator '"' anywhere before EOF at .code.tio line 1.` [Answer] # Go, 0 bytes All Go files must begin with `package [identifier]`. The error message is: ``` can't load package: package main: src/test.go:1:1: expected 'package', found 'EOF' ``` ]
[Question] [ # Introduction If \$\newcommand{\fib}{\operatorname{fib}}\fib(x)\$ calculates the \$x\$th Fibonacci number, write a program that calculates \$\fib(\fib(m))\$ for any integer value of \$m \ge 0\$. (Of course, there will be practical limits based on the language, so lesser limits are acceptable. Also, it's okay to stop at \$m = 20\$, even if the language could in theory go higher.) Any means of calculation is acceptable. # Challenge Write a program or function, in as few bytes of code as possible, that for any given positive integer input, will return the same output as function `fibfib` in the following Python code: ``` fibs = [0, 1] def fib(n): global fibs while len(fibs) <= n: fibs.append(fibs[-2]+fibs[-1]) return fibs[n] def fibfib(m): return fib(fib(m)) ``` You do not have to use the same or a similar algorithm; the output just has to be the same. # Example Input and Output ``` 0 -> 0 1 -> 1 2 -> 1 3 -> 1 4 -> 2 5 -> 5 6 -> 21 7 -> 233 8 -> 10946 9 -> 5702887 10 -> 139583862445 15 -> 13582369791278266616906284494806735565776939502107183075612628409034209452901850178519363189834336113240870247715060398192490855 20 -> 2830748520089123910580483858371416635589039799264931055963184212634445020086079018041637872120622252063982557328706301303459005111074859708668835997235057986597464525071725304602188798550944801990636013252519592180544890697621702379736904364145383451567271794092434265575963952516814495552014866287925066146604111746132286427763366099070823701231960999082778900856942652714739992501100624268073848195130408142624493359360017288779100735632304697378993693601576392424237031046648841616256886280121701706041023472245110441454188767462151965881127445811201967515874877064214870561018342898886680723603512804423957958661604532164717074727811144463005730472495671982841383477589971334265380252551609901742339991267411205654591146919041221288459213564361584328551168311392854559188581406483969133373117149966787609216717601649280479945969390094007181209247350716203986286873969768059929898595956248809100121519588414840640974326745249183644870057788434433435314212588079846111647264757978488638496210002264248634494476470705896925955356647479826248519714590277208989687591332543300366441720682100553882572881423068040871240744529364994753285394698197549150941495409903556240249341963248712546706577092214891027691024216800435621574526763843189067614401328524418593207300356448205458231691845937301841732387286035331483808072488070914824903717258177064241497963997917653711488021270540044947468023613343312104170163349890 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~4~~ 3 bytes ``` ÆḞ⁺ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FisOtz3cMe9R464lxUnJxVDBJdGGBrFQNgA) ``` ÆḞ⁺ ⁺ # Twice: ÆḞ # Nth fibonacci ``` *-1 byte thanks to Unrelated String* # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ÅfÅf ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cGsaEP3/b2gAAA "05AB1E – Try It Online") ``` ÅfÅf Åf # Nth fibonacci Åf # Nth fibonacci ``` # [flax](https://github.com/PyGamer0/flax), 4 bytes ``` ;f;f ``` ``` ;f;f ;f # Nth fibonacci ;f # Nth fibonacci ``` [Try it online!](https://staging.ato.pxeger.com/run?1=m70kLSexYsGCpaUlaboWS6zTrNOWFCclF8MEog0NYqFsAA) # [Actually](https://github.com/Mego/Seriously), 2 bytes ``` FF ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/9/N7f9/QwMA "Actually – Try It Online") ``` FF F # Nth fibonacci F # Nth fibonacci ``` [Answer] # [Factor](https://factorcode.org/) + `benchmark.fib3`, 37 bytes ``` [ [ 0 ] [ 1 - fib 1 - fib ] if-zero ] ``` [Try it online!](https://tio.run/##PYsxDoMwEAR7XrEfAIHoyAOiNGkiKuTisM7CQsbO@VKEzxtXNDPNjCOrUcr8eb2fE1Y@7BZI9s75dUQg3ZCEVf9J/KHI/P3VhDMeTTP08FGpLFjQw1QOaFHH2wbetSdLhCmBErKS3btyAQ "Factor – Try It Online") ## Huh? Factor comes with a suite of benchmarks. One of these is to implement the fibonacci function in seven different ways. *Naturally*, `fib` is the shortest one of these; it has an off-by-one error, it doesn't handle 0 correctly, and it's very slow because it uses the naive recursive algorithm. Regardless of these problems, fixing them is still shorter than rolling our own. If we were to do so, however, it would only cost 3 more bytes: # [Factor](https://factorcode.org/) + `combinators.extras`, 40 bytes ``` [ [ 0 1 rot [ tuck + ] times . ] twice ] ``` [Try it online!](https://tio.run/##HY6xbsIwFEX3fMXtjOQkDBToB1RduiAmxPAwz4kVxy@1X5Tw9anb7QxHOseRVUnb9fL1/XnGSNpjSqz6mpKPitzPzgWGlfHhIxU1G141UcbAKXJA5p@Zo@WMj6pqm@2GGxq0SKKFdLYDdrhD/VgU80eLt4z7ZikEmKp6w4UZveqUz3Vt5cmdBGeykh14tT3Fjk3p11Tv983xeKhP76f2ACcJFMHrFKiceYkQh6V/IetTZoXPZV8WHztkGRn/3@goPajj7Rc "Factor – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes ``` Nest[Fibonacci,#,2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCTaLTMpPy8xOTlTR1nHKFbtf0BRZl5JdJq@Q1BiXnpqtIGOkUFs7H8A "Wolfram Language (Mathematica) – Try It Online") Slightly shorter than the naive `Fibonacci@Fibonacci@#&`. [Answer] # [J](http://jsoftware.com/), ~~49~~ 45 bytes\* \*(you can actually score like 14 but that's *boring*) *-4 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!* (also thanks for [this for 33 bytes](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmtxU7G62rBap1JDW19BT0tfx6paL85K00gBCFWUrcxNK2prYQo1uVKTM_IdNJSsdNQVdO0U1HWUrBzSNBVSE5MzFDL1jAwhChcsgNAA), which uses newer J features!) ``` 1{,@f=:{&(2 2 2$#:151x)`(-&2+/ .*&f<:)@.(>&1) ``` [Try it online!](https://tio.run/##DcNBCoMwEAXQvaf4xJJk2mR0At0MKoFCV131BAVRWzfdCh4@yuOtxbBb0CscAlroOTIe79ezyB7y3OtufcLpUqvcZaOPjzbdGvDVzp1SZj9YoULVNH7/2RsNDnGAC0bzQqbFj5Ns5QA "J – Try It Online") Uses the matrix method mentioned on the OEIS page. ## Explanation *This applies to the less golfed version, but fundamentally remains the same. I will continue to explain the less golfed version as it is more intuitive what is going on.* ``` f=:{&(2 2 2$#:151x)`(-&2(+/ .*)&f<:)@.(>&1) 1{,@f ``` First, we define a helping verb `f` which recursively computes the matrix. `f` consists of two part: seed generation and recursion calculation. If the input is greater than 1 (`>&1`), then (`@.`) we calculate recursion; otherwise, we call the seed function. As I think it looks nicer by replacing the current `f` with the recursive verb `$:`, I shall explain that version, though they remain functionally equivalent. ``` f=:{&(2 2 2$#:151x)`(-&2(+/ .*)&$:<:)@.(>&1) <-----seed-----> <---recursion---> <-----seed-----> if not(input > 1): {&( ) index the input into the following array #:151x get the bits of 151 (1 0 0 1 0 1 1 1) 2 2 2$ and create a 2x2x2 array the result is 1 0,:0 1 for 0, and 0 1,:1 1 for 1 <---recursion---> if input > 1: (-&2 <:) compute input-2 and input-1 ( )&$: call this verb on each, then +/ .* perform matrix multiplication ``` Since, however, `f` computes a matrix, and we are only interested in one member of that matrix, our actual verb is the last line `1{,@f`, which simply takes the top-right element of the matrix. # \* [J](http://jsoftware.com/), 14 bytes ``` (+/@:!&i.-)^:2 ``` [Try it online!](https://tio.run/##y/qvEW2loKSnoJ6uYGulrqajaa0Xb6jg46ago1BrpWCgAMT/NbT1HawU1TL1dDXjrIz@a3KlJmfkO2goWemoK@jaKajrKFk5pGsqGShk6hkZVvwHAA "J – Try It Online") Of course, the first highlighted method is *much* longer than taking the trivial approach of modifying [the existing shortest Fibonacci in J](https://codegolf.stackexchange.com/a/87107/31957) thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles) and applying it twice. While this approach is about ~30x slower than the first, it's the length which matters. Nonetheless, I consider it trivial, which is why it is not the most-featured solution in my answer. [Answer] # [R](https://www.r-project.org/), 50 bytes ``` function(n,s=5^.5,`?`=round)?((r=s/2+.5)^?r^n/s)/s ``` [Try it online!](https://tio.run/##K/qflpkERLb/00rzkksy8/M08nSKbU3j9Ex1EuwTbIvyS/NSNO01NIpsi/WNtPVMNePsi@Ly9Is19Yv/FycWFORUahhYGRroQIzR/A8A "R – Try It Online") Adapted from [J.Doe's answer](https://codegolf.stackexchange.com/a/177730/95126) to the [Fibonacci function or sequence](https://codegolf.stackexchange.com/q/85/95126). Based on the closed-form formula for the fibonacci sequence, applied to itself. The chance to assign the function (`round`) and variable (`s/2+.5`) that will be re-used means that we can re-perform the closed-form calculation on itself for less bytes than a 'trivial' adaption of simply appending a 'do it twice' function `;g=function(n)f(f(n))` (even in [R](https://www.r-project.org/) ≥4.1 where defining a new function can be much golfier using `\` instead of `function` \*). --- Note that a shorter [R](https://www.r-project.org/) solution to the older challenge is [user5957401's answer](https://codegolf.stackexchange.com/a/89653/95126), which can be further golfed-down to ~~25~~ [23 bytes](https://tio.run/##K/r/vyi1IDWxRKE4I79cw81GN0RbI8TWTVPz/38A)\*\*: `repeat show(F<-T+(T=F))`. However, as a full program, this is less easy to 'do it twice'. If we re-arrange it into function form (`function(n){while(n<-n-1)T=F+(F=T);T}`), we can exploit the fact that the answer is already assigned to a variable to conditionally return this, or run the function again on this, for ~~60~~ [58 bytes](https://tio.run/##K/qflpkERLb/02zTSvOSSzLz8zTydHJtQzSryzMyc1I18mx083QNNUNs3bQ13IDC1gmZaQkauTppGiE6Bpo6IZq1/4sTCwpyKjUMrSx1IKZp/gcA): `f=function(n,m=T){while(n<-n-1)T=F+(F=T);`if`(m,f(T,0),T)}`. This is again shorter than simply appending a 'do it twice' function, but longer than the closed-form approach above (although appending a 'do it twice' function wins in [R](https://www.r-project.org/) ≥4.1 \*). Finally, [plannapus's answer](https://codegolf.stackexchange.com/a/66657/95126) (golfed-down by [Robert S.](https://codegolf.stackexchange.com/users/81727/robert-s)) used the classic recursive approach. When adapted to run twice this is only one byte longer than the modified shortest fibonacci answer, with [59 bytes](https://tio.run/##K/qflpkERLb/02zTSvOSSzLz8zTyNBMy0xI08myMdQx10jTydA01tUGUkaamdTqysjQNoLCm5v/ixIKCnEoNAytLnXTN/wA): `f=function(n)`if`(n<3,1,f(n-1)+f(n-2));g=function(n)f(f(n))`. Boringly, though, this one *is* just the 'trivial' adaptation of appending `;g=function(n)f(f(n))`. \**Thanks to pajonk for pointing out the golfing differences when using [R](https://www.r-project.org/) ≥4.1* \*\**23-byte fibonacci function inspired by [Giuseppe's answer here](https://codegolf.stackexchange.com/a/247838/95126)* [Answer] # [Haskell](https://www.haskell.org/), 24 bytes The single-Fibonacci part was borrowed from [R. Martinho Fernandes](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence#comment110_89). ``` map(f!!)f f=0:scanl(+)1f ``` [Try it online!](https://tio.run/##y0gszk7NyfmfrmCrEPM/N7FAI01RUTONK83WwKo4OTEvR0Nb0zANKJGZB1RRUJSZV6KgolCSmJ2qYGigkP7/X3JaTmJ68X/dCOeAAAA "Haskell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 115 bytes ``` f=n=>n<4?n+3n>>2n:(f(--n)**2n-(u=-1n)**(F=y=>y<2?y:F(--y)+F(--y))(n-=2n)*f(--n)*f(n+=3n)-u**F(--n)*f(--n)**2n)/f(n) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TU-7DoJAEOz5igvVLZfzcVgYYKGSL7C0E84QcC8RKC7GL7Gh0I_ybzwFEqqZ7OzM7D5fZIpyGN59p-X-02okTCnZZSRCSlNFEddcSoIgUCR5j3L74zxHi6lNVGaj3OkWxAjASaJyK5NLcxIYEsg-CPJ5NOfB2skwVddnQ61pylVXXUvun-hoTO1D7GlzY7wpO1YxZBuKHSbI1J8JAezuMTZ7G3Nx91bgbA9vGXigYpE5Vs5ffwE) (includes benchmark) Way longer than Radvylf's, but is way, way, faster. [ATO for Radvylf's with benchmark, which times out](https://ato.pxeger.com/run?1=m70kLz8ldcGidNulpSVpuhY3lSts7TTSbCtt7SptjOwrrdI0KnUNNbVBlJGmpkaaRoWmJlRpZnJ-XnF-TqpeSWZuqoZSTF5Ifn62kqY1V1p-kYJGTmqJQqaCrYKBNZCysVUwAjG0tTUVqrkUFGA6c_LTNdI1MjWBmmq5kI1zzUtBMhFi4YIFEBoA). Formula found at [this paper](https://codehappy.net/fibo.pdf). # [Python](https://www.python.org), 131 bytes ``` f=lambda n:n>3and(f(n-1)**2-(-1)**F(n-3)*f(n-4)*f(n-1)-(-1)**F(n-2)*f(n-3)**2)//f(n-3)or n+3>>2 F=lambda y:y>1and F(y-1)+F(y-2)or y ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3m9NscxJzk1ISFfKs8uyME_NSNNI08nQNNbW0jHQ1wLQbkG-sqQUSNoFQhppIUkYQMWOQDk19fQg7v0ghT9vYzs6Iyw1mfqVVpZ0h0HwFN41KoGZtEGUEUlgJdYpCdEFRZl4JyH5NTYU0kBEKmXkKRYl56akaRoaasRB1MKcDAA) Same concept. [Answer] # [Python](https://www.python.org) NumPy, 66 bytes ``` lambda n:ptp(x**ptp(x**n)) from numpy import* x=mat("1 1;1 0","O") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXISc5NSEhXyrApKCjQqtLSgVJ6mJldaUX6uQl5pbkGlQmZuQX5RiRZXhW1uYomGkqGCobWhgoGSjpK_kibUJMW0_CKFPIXMPIWixLz0VA1DHSNDTauCosy8Eo00DaB5ChCFCxZAaAA) While this isn't really competitive (the `numpy import` is just too expensive, as is setting up the auxiliary matrix) I thought this is interesting. Perhaps it can be ported to one of the other matrix languages. How? The standard recurrence `a,b <---| a+b,a` can be conveniently expressed by the matrix \$ M = \begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix} \$. Doing n iterations then is as easy as taking the n-th power: $$ M^n = \begin{pmatrix} F\_{n+1} & F\_n \\ F\_n & F\_{n-1} \end{pmatrix} $$ Thus we could simply do `(x**(x**n)[0,1])[0,1]`. We save a few bytes using `ptp` instead which in turn uses that `F_n = F_n+1 - F_n-1`. (Note that this incorrectly returns 1 for input `0` because `F_-1` breaks the pattern `F_n <= F_n+1`, so ptp does not pick the right elements in that case.). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` 2(‹∆f ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIyKOKAueKIhmYiLCIiLCIyMCJd) ## How? ``` 2(‹∆f 2( # Execute twice: ‹ # Decrement to make this 0-indexed ∆f # Nth fibonacci number ``` [Answer] # [SageMath](https://www.sagemath.org/), 28 bytes ``` lambda n,f=fibonacci:f(f(n)) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJxFld1uG0cMhe8N-B32zjKwBcjh8GcCuC_S9CJRpNRo6xi2ChQ1_O79qDSobcja-SEPzznkfn34eHvzx6c_P3_5tD3t54fz4-dvT5-Ox8cP58P58HR_f3tze3M5vV5et4ftIPum-zb2zfZt7pvvW-xb7lvt22Krt1kbwq3T38-n4-X05f9r-uNyH-lvZn1nTWJ4yqgiktrysooxp_eT17BYuXRkjYjQWBKj5lyzJNLcwzNjcU2GSmqZpIeOPiRLbA4y-Fii5aJZrsvCtFbZNAtVG1OK9DNTXUJsla4xl5Q30I43y4dIAcKWipdMIAIzdWoEGIpEgFwj5jJO-OoUcwDDJpVIXw_JRiHcsaxkk0rGIHSQc7inDYCEiRq4fYm4ql7Tr-R-VJmvlcNcPFcFyzMozqk7h5vMgAR4XGCnbCjSBV8WhCQRtfvigDhbrK-MoZRuuRKWZVpMnW5Q4-qRg7ALFseExgBg17U6TpQigTvgdYIM4AsY6DMjqFAVZOQcFXOgD0yHAIUyyCYQqasXYJltsMB2rE5CzpnGDuEoHopYLUmriS4ONcilrOGQZfBBceja7sElwkEPG00FNRGZ_T6iDggK4Zf8aATOWYUWGsNhlhKABRv8dQWwMnMMiOBsszKb2KCsofAYXqWYEnH7PzxHwlkhVhIA6fkiGBHFIQ-7VQsoiIfFXMk2gbLQ0attLfA-NCaUozjUExaOJ3ZAbOpJPIkmilWA3RplYryVald1rKQlRpsmGv7pL2jEgjkbIY2Cp4gZS5FaBwaEgDYElCE96CcOJALyGo2xeJh4mcIpclJV2eK2mSX7CLVWBFYmI9BBDs90QNdGMxC6-1IwonRjggEB0IeHGN1ncB6VHTOhBmuPBVGOSR15q6QF1Svf3lrNahCC662rchiB3ZhNNSQlZ2g36DA37e7jFk1XWFGbWtozITyxUgWGWmgpIoN10nWr0jPJIXwKtYEH8TjssERF1abrAULldCfGHQwFzhWNASvDyS2C1TEMe1EdngBFd7dDwWSstoNTGTvtnoE74RFgzb0xDXv-pFNatzAc-2xBe9JxhZJtYjamVsfwGbiN0qG2LQdhg2nIJ-WTiZb2NmyTFdk19-hjcNKos4cCkw2wcG6D1gG8N524ZfbkZdpqWwS98TFF0VlMrmoLGxQzBqU93VoBgYUenHadRqXfG6FLyJ4bPcUTnyYe5DzywDLWaNZpK1bwYItnSI5BaUXmxoTgfp8cfzsdfz-99Ovk7uNfNN7xbt-u39Tu2D9_e9ku-2l7fNr-eXw-XF9Z-_bjLXT_4fZm46ffYl8Pl_vvT88vj0-Xw_nu7fK-_fTz9vb6vr39l-eX08PD66_vd_f_AgOOgoU=&lang=sage&interacts=eJyLjgUAARUAuQ==) [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ‼!İf ``` [Try it online!](https://tio.run/##yygtzv7//1HDHsUjG9L@//9vDgA "Husk – Try It Online") ``` ‼ # twice = apply function twice: ! # index = value at index (of input) of İ # infinite sequence of f # fiboncci numbers ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes ``` ff ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z8NiA0NAA "MathGolf – Try It Online") ``` ff f # Nth fibonacci f # Nth fibonacci ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` #@*#&@Fibonacci ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9lBS1nNwS0zKT8vMTk5839AUWZeSbSyrl2ag3KsWl1wcmJeXVBiXnpqtIGOkUHsfwA "Wolfram Language (Mathematica) – Try It Online") ``` Fibonacci fib #@*#&@ fib ∘ fib (composition) ``` [Answer] # [Python](https://www.python.org), 47 bytes ``` from sympy import* lambda n,g=fibonacci:g(g(n)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3DdOK8nMViitzCyoVMnML8otKtLjSbHMSc5NSEhXydNJt0zKT8vMSk5MzrdI10jXyNDUhGlcXFGXmlWikaVjCRGBGAgA) Without builtin: # [Python](https://www.python.org), 52 bytes ``` lambda n:g(g(n)) g=lambda y:y>1and g(y-1)+g(y-2)or y ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXISc5NSEhXyrNI10jXyNDW50m2hQpVWlXaGiXkpCukalbqGmtogykgzv0ihEqJ3dUFRZl6JRpqGpaYmRGTBAggNAA) # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->n{(g=->y{y>1?g[y-1]+g[y-2]:y})[g[n]]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsHiNNuYpaUlaboWN9V17fKqNdJtde0qqyvtDO3Toyt1DWO1QZRRrFVlrWZ0enRebGwtRPmyAoW0aMtYCGfBAggNAA) [Answer] ## Batch, 123 bytes ``` @set/af=h=0,g=i=1 @for /l %%a in (1,1,%1)do @set/aj=h+i,h=i,i=j @for /l %%a in (1,1,%h%)do @set/ah=f+g,f=g,g=h @echo %f% ``` Explanation: Regular Batch variable expansion with `%` happens before the line is parsed, so the `%h%` has to be on a separate line to the code that sets `h`, but `set/a` is a special case and can access the current value of variables so works fine inside a loop. [Answer] # JavaScript (Node.js), 35 bytes ``` x=>(f=y=>y<2?y:f(--y)+f(--y))(f(x)) ``` Simple recursive solution (now intended for use with bigints, thanks to Steffan for pointing out that's necessary). [Answer] # [C (gcc)](https://gcc.gnu.org/) with `-lgmp` and `-m32`, ~~266~~ ~~265~~ ~~259~~ 241 bytes * -1 thanks to ceilingcat * -6 thanks to MackTuesday As no native type supports `f(f(20))`, I used GMP for the math. Uses iteration to compute the Fibonacci sequence. ``` #import<gmp.h> #define q mpz_set f(i,r){mpz_t k,l,s,t;for(mpz_inits(k,l,s,t,0);mpz_cmp(k,i)<1;mpz_add_ui(k,k,1))mpz_cmp_ui(k,1)>0?mpz_add(l,s,t),q(s,t),q(t,l):q(mpz_get_ui(k)?t:s,k);q(r,t);}g(i,r){mpz_t a;mpz_init_set_ui(a,i);f(a,r);f(r,r);} ``` Unfortunately, TIO doesn't have the 32-bit version of GMP installed so it's 259 bytes in 64-bit mode: ``` #import<gmp.h> #define q mpz_set f(i,r)mpz_t i,r;{mpz_t k,l,s,t;for(mpz_inits(k,l,s,t,0);mpz_cmp(k,i)<1;mpz_add_ui(k,k,1))mpz_cmp_ui(k,1)>0?mpz_add(l,s,t),q(s,t),q(t,l):q(mpz_get_ui(k)?t:s,k);q(r,t);}g(i,r)mpz_t r;{mpz_t a;mpz_init_set_ui(a,i);f(a,r);f(r,r);} ``` [Try it online!](https://tio.run/##VZDdasMwDIXv8xSipWBTZyS7rNP0PcaghCT2RP5tt4OVvPoyOfFGd2PJH0dHxy5jXZbLssduHIzLdDe@fOTRvqoV9jVM0I1fV1u7SDEUhvubA@rkY2sb0QornFSDYZ5gj86yQEXCpYdlNxJCnqXrtaiq6w2JNCLlPAg2kvI8uQQNWz24mFgoTrT8NK1rdO3WAX5xJysaLidmSCRn/RTzL2Qhf6P5p/jBgtJIRcX4YnyZF@wddAX27D5gxeERAXiEkprgWNtb62QUgHdkG@Ne5D8Bz4kEzF5TOo/HzQXAx4InJRF68mjIX7GdZgfad87h8Fa99zsB/8VzNC/fpWoLbZe4pcEl/vwB "C (gcc) – Try It Online") Ungolfed (without GMP, assuming `int` is big enough): ``` int f(int i) { int j[2]={0}, k=0, l; for(; k<i+1; k++) if(k<2) j[k]=k; else { l=j[0]+j[1]; j[0]=j[1]; j[1]=l; } return j[1]; } int g(int i) { return f(f(i)); } ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 32 bytes ``` @(n,m=[1 1;1 0])(m^(m^n)(2))(2); ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI08n1zbaUMHQ2lDBIFZTIzcOiPI0NYw0Qdj6f1p@kUKWgq2CgZWhIZdCQVFmXkmahpJqioKSTppGlqYmV2peClDNfwA "Octave – Try It Online") Port of my Python answer. [Answer] # [Desmos](https://desmos.com/calculator), ~~49~~ 45 bytes ``` pp-p~1 f(n)=(p^n-(1-p)^n)/5^{.5} g(n)=f(f(n)) ``` Just applies [Binet's Formula](https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula) twice. Did not include the last two test cases as the output is too large for Desmos to handle. [Try It On Desmos!](https://www.desmos.com/calculator/h1huhh1zkb) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/56vslsycqe) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 42 bytes ``` .+ $* +`11(1*) 1$1,$1 , +`11(1*) 1$1,$1 1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLO8HQUMNQS5PLUMVQR8WQS4cLQ8jw/39zAA "Retina 0.8.2 – Try It Online") Note: Very slow, so will probably time out on TIO for inputs more than `8`. Explanation: Based on my Retina 0.8.2 answer to [Fibonacci function or sequence](https://codegolf.stackexchange.com/q/85). ``` .+ $* ``` Convert to unary. ``` +`11(1*) 1$1,$1 ``` Recursively replace `n` with `n-1` and `n-2`, until each unary integer has been replaced down to `1` and `0`. ``` , ``` Sum the `1`s in unary, resulting in the Fibonacci of the input. ``` +`11(1*) 1$1,$1 ``` Calculate the Fibonacci of the Fibonacci. ``` 1 ``` Sum and convert to decimal. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 41 bytes ``` 2{K`0,1 "$-1"+`\d+,(\d+) $1,$.(*_$1* ,.+ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N@o2jvBQMeQS0lF11BJOyEmRVtHA0hocqkY6qjoaWjFqxhqcenoaXP9/2/AZchlxGXMZcJlymXGZc5lwWXJZQgUNOUyMgAA "Retina – Try It Online") Link includes test cases. Explanation: ``` 2{ ``` Repeat the whole program twice. ``` K`0,1 ``` Replace the input with the two integers `0` and `1`. ``` "$-1"+` ``` Repeat the number of times given by the stage before the previous stage. On the first iteration this is the input, while on the second it is the result of the first loop. ``` \d+,(\d+) $1,$.(*_$1* ``` Replace the first integer with the second and the second with their sum. ``` ,.+ ``` Delete the second integer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` NθF²«≔E²κυFθ≔⟦⌈υΣυ⟧υ≔⌊υθ»Iθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IQcNIU6Gai9OxuDgzPU/DN7FAw0hHIVtTR6EUqIATrKJQUwEqHe2bWJGZW5qrUQpUEAymY6EqYQZk5sEVgKyo5Qooyswr0XBOLC4BGqT5/7/5f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explantion: ``` Nθ ``` Input `n`. ``` F²« ``` Repeat twice. ``` ≔E²κυ ``` Start with the two integers `0` and `1`. ``` Fθ ``` Repeat `n` times. ``` ≔⟦⌈υΣυ⟧υ ``` Replace the first integer with the second and the second with their sum. ``` ≔⌊υθ ``` Save the first integer for the next pass or the result. ``` »Iθ ``` Output the result. Although the above code calculates the result quickly enough for inputs of `n` up to about `20`, here is a 42-byte version which is fast even for large values of `n`: ``` ≔⮌E²E³¬⁼ιλυFN⊞υE³ΣE²ΠE…⮌υ²§ξ⁺ν⊘⁺λπI§§υ±²¦¹ ``` [Try it online!](https://tio.run/##PU7LCoMwELz7FTluID3U0pMnkUI9VKT9glS3KsQkTbJivz5VQQeWYWDn0fTSNUaqGHPvh07DEyd0HuEhLaSCrXQRrDIBbl@SysMgmOIrBCOeJR/jGJTaUqhofKMDzllNvgc6zC8a97jamZaasMni1ygsemOPTloy0@XyUOoWZ5gXgyIPWrC7VBO2sEklmOUHsqR2gw5QSB9gd@68jKiwkwEhXQef1/8Y02s8TeoP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⮌E²E³¬⁼ιλυ ``` Start with \$ ((F\_{F\_0-1}, F\_{F\_0}, F\_{F\_0+1}), (F\_{F\_1-1}, F\_{F\_1}, F\_{F\_1+1})) \$ which is `[[1, 0, 1], [0, 1, 1]]`. ``` FN ``` Repeat `n` times. ``` ⊞υE³ΣE²ΠE…⮌υ²§ξ⁺ν⊘⁺λπ ``` Calculate \$ (F\_{F\_{i+2}-1}, F\_{F\_{i+2}}, F\_{F\_{i+2}+1}) \$ from the previous terms. There are a number of ways of doing this e.g. \$ F\_{F\_{i+2}-1} = F\_{F\_i-1}F\_{F\_{i+1}-1} + F\_{F\_i}F\_{F\_{i+1}} \$. ``` I§§υ±²¦¹ ``` Output the middle term of the penultimate result which is \$ F\_{F\_n} \$ as desired. [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` MgMgU ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TWdNZ1U&input=OA) [Answer] # [Raku](http://raku.org/), 27 bytes ``` [o] {(0,1,*+*...*)[$_]}xx 2 ``` [Try it online!](https://tio.run/##BcFBCoAgEAXQq3xEQk2GMahN1EUipEWuisI2SXX26b1zzVsne0GVMMh0zHgM@@Bd7YjI2UnH@btvNNLjWgqUjhhGPAk6fgrpyHgNEwW2HqH1aFh@ "Perl 6 – Try It Online") * `0, 1, *+* ... *` is the lazy, infinite Fibonacci sequence. * `[$_]` looks up a number in the sequence by its index. * `{ ... }` wraps the lookup in an anonymous function. * `xx 2` replicates that function twice, producing a list of two elements. * `[o]` reduces that list with function composition. [Answer] # [><>](https://esolangs.org/wiki/Fish), 38 bytes ``` 2>01@@:}@{?vrn; :v? (1}-1:{<+@ -\{~~$1 ``` [Try it online!](https://tio.run/##S8sszvj/38jOwNDBwarWodq@rCjPmsuqzF5Bw7BW19Cq2kbbgUs3prquTsXw////umXmAA "><> – Try It Online") [Answer] # [J-uby](https://github.com/cyoce/J-uby), 13 bytes ``` (:++[0,1])**2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWazWstLWjDXQMYzW1tIwgYssKFNyiLWIhnAULIDQA) ## Explanation This is the standard J-uby Fibonacci function, `:+ + [0,1]` (start an array with `[0,1]` and apply `:+` (sum) to its last two items \$n\$ times), iterated on twice, i.e. `F**2`. [Answer] # Excel, 66 bytes ``` =LET(q,SQRT(5),f,ROUND((.5+q/2)^ROW(A:A)/q,),INDEX(f,INDEX(f,A1))) ``` Note: Excel will add a leading zero to `.5` to make it `0.5` when the formula is entered. The main portion of this is generating the Fibonacci sequence (or at least the first 1,474 terms (after that Excel can't handle numbers that large (which also limits to input to values ≤ 16))). That's what this part does: ``` q,SQRT(5),f,ROUND((0.5+q/2)^ROW(A:A)/q,) ``` After that, we use `INDEX(f,INDEX(f,n))` as the equivalent to `fib(fib(n))`. [![Screenshot](https://i.stack.imgur.com/ja60M.png)](https://i.stack.imgur.com/ja60M.png) ]
[Question] [ > > [Cop's thread here](https://codegolf.stackexchange.com/q/140793/56656) > > > In this [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge cops will think of a positive integer. They will then write a program or function that outputs one value when provided the number as input and another value for all other positive integer inputs. Cops will then reveal the program in an answer keeping the number a secret. Robbers can crack an answer by finding the number. Your job as robbers is to find that number. Once found you can make an answer here detailing the number and how you found it. You should link the original answer being cracked in your answer. Your score will be the number of cracks with more being better. [Answer] # [Perl 6, by Ramillies](https://codegolf.stackexchange.com/a/140851/69059) ``` 11 ``` The function `series($x)` is simply the first 108 terms of the Taylor series for `e^x` evaluated at `i*(x % 8*π)`. Since `e^2πi = 1`, this reduces to simply `e^ix`: the `% 8*π` serves only to bound the error of the truncated series. The `∫` function integrates the provided `Callable` in the interval `[0,2π]` using the trapezoid method. The integrand in question is `(e^ix)^11/(e^inx)`, or simply `e^(11-n)ix`. This integrates to 0 in that interval for all `n != 11`. At `n = 11`, the integrand reduces to simply `1`. Hence the answer is `11`, and the desired output is `6.28`. While `11` is the only answer in theory, the sampling in the integral is imperfect. Consequently, any integer of the form `87931k+11` should work. [Answer] # [Java, by okx](https://codegolf.stackexchange.com/a/140805/16236) Note: the original challenge to which this post answers has been deleted, it's however still accessible with the link to anyone having the privilege to see deleted answers. The explanations below include what the challenge was about. **Number: `18`** The code is effectively looking for primes with the form 112*n*-2. By [this Wikipedia list](https://en.wikipedia.org/wiki/Largest_known_prime_number#The_twenty_largest_known_prime_numbers), we know that the 20th largest known prime number has 2,900,832 digits. No prime with the form 112*n*-2 are in that list, so that digit number will be our limit. All numbers of the form 112*n*-2 that have at most that many digits have this constraint: `n < 22`. [Factordb tells us](https://factordb.com/index.php?query=11%5E(2%5E22)-2) that 11222-2 has 4,367,918 digits. This is proof enough. The code by okx limits us to `n` above 6. So, let's do the list: 112*n*-2 is factorizable for `n` = [7](https://factordb.com/index.php?query=11%5E(2%5E7)-2), [8](https://factordb.com/index.php?query=11%5E(2%5E8)-2), [9](https://factordb.com/index.php?query=11%5E(2%5E9)-2), [10](https://factordb.com/index.php?query=11%5E(2%5E10)-2), [11](https://factordb.com/index.php?query=11%5E(2%5E11)-2), [12](https://factordb.com/index.php?query=11%5E(2%5E12)-2), [13](https://factordb.com/index.php?query=11%5E(2%5E13)-2), [14](https://factordb.com/index.php?query=11%5E(2%5E14)-2), [15](https://factordb.com/index.php?query=11%5E(2%5E15)-2), [16](https://factordb.com/index.php?query=11%5E(2%5E16)-2), [17](https://factordb.com/index.php?query=11%5E(2%5E17)-2), [19](http://www.wolframalpha.com/input/?i=is+(11%5E(2%5E19)-2)+prime), [20](http://www.wolframalpha.com/input/?i=is+(11%5E(2%5E20)-2)+prime) and [21](http://www.wolframalpha.com/input/?i=is+(11%5E(2%5E21)-2)+prime) (factors proofs are on factordb.com and wolfram alpha; factordb has some proofs that wolfram alpha hasn't and vice-versa). The only value `n` for which we can't prove the factorization is 18 ([factordb](https://factordb.com/index.php?query=11%5E%282%5E18%29-2), [WolframAlpha](http://www.wolframalpha.com/input/?i=is+(11%5E(2%5E18)-2)+prime)). So (a) if there is a prime number of the form 112*n*-2 with `n > 6`, then (b) `6 < n < 22`, and (c) I proved each number with such `n` is composite except for 18, so (d) the prime we're looking for has `n = 18`. Note that I don't exclude that 11218-2 is composite. I haven't proved that that number is a prime: I only proved that if the OP thought about that number, it can only be 18. If that number is indeed a prime, congrats to okx for finding it :-) ### However There are no proof that 11218-2 is the only number, though. It's the only number in the range of numbers for which we can currently prove the primality. So I don't exclude the fact that one day someone might prove that 11251-2 or 112124-2 is prime. I therefore believe that the original entry by okx is invalid because there are no such proof that for `n` between 19 and the (231-1)231-1 (the theoretical limit of Java's `BigInteger`), there are no other primes. [Answer] # Python 3, [Erik Brody Dreyer](https://codegolf.stackexchange.com/a/140841/72175) ### Number: `105263157894736842` [Try it online!](https://tio.run/##K6gsycjPM/7/v0LBViEzr6C0REOTq6AoM69EA4QrNLWMFGxBMkB2tK5hrHZFtIEVkNbU/P/f0MDUyMzY0NTcwtLE3NjMwsQIAA "Python 3 – Try It Online") --- ### How? Everyone's favorite tool: OEIS! 1. Go to [oeis.org](http://www.oeis.org) 2. Search ["last digit first doubles number"](https://oeis.org/search?q=last+digit+first+doubles+number&sort=&language=&go=Search) 3. Find [Entry A087502](https://oeis.org/A087502) entitled > > Smallest positive integer which when written in base n is doubled when the last digit is put first. > > > 4. Find the base 10 entry (105263157894736842) 5. Confirm it works [Answer] # [Tampio, fergusq](https://codegolf.stackexchange.com/a/140810) **Number: `27`** The program prints `nolla` for 27 and `"1" negatiivisena` for all other inputs. It times out on TIO, unfortunately, but works offline. Whew, this was a fun one to work through. Wiktionary and [this Finnish dictionary I found online](http://www.suomienglantisanakirja.fi/liitt%C3%A4%C3%A4) actually helped a surprising amount, as a lot of Tampio syntax relies on inflection. I first tried translating the program into Haskell-like pseudocode, but the "case system" of Tempio and how function calls worked kept tripping me up. Eventually, I ended up running all of the code from the definition of `sata` downward, which gave me surprisingly easily that `sata == 55`, and `funktio` wasn't difficult to reverse engineer from there as it was simple arithmetic that could be deduced from trial and error. [Answer] # [JavaScript, by Eli R](https://codegolf.stackexchange.com/a/140884) The number is `7464822360768511` I first disabled the anti-debugging function (by overwriting `Function.prototype.constructor` to a function with evals any code except `debugger`) then debugged the guess function by stepping into it. From what I understood the guess function initializes a random number generator on a fixed seed then generate a random number and compare it to the input. As the input isn't used in the random number generation it can be ignored allowing to skip directly to the result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), [Erik the Outgolfer's answer](https://codegolf.stackexchange.com/a/140800/59487) **Number: `134`** The following program: ``` 5ȷ2_c⁼“ḍtṚøWoḂRf¦ẓ)ṿẒƓSÑÞ=v7&ðþạẆ®GȯżʠṬƑḋɓḋ⁼Ụ9ḌṢE¹’ ``` can be cracked using the number `134`. This outputs `0` for all numbers except for `134`, which gives `1`. **[Try it online!](https://tio.run/##AXMAjP9qZWxsef//Nci3Ml9j4oG84oCc4biNdOG5msO4V2/huIJSZsKm4bqTKeG5v@G6ksaTU8ORw549djcmw7DDvuG6oeG6hsKuR8ivxbzKoOG5rMaR4biLyZPhuIvigbzhu6Q54biM4bmiRcK54oCZ////MTM0 "Jelly – Try It Online")** --- # How did I find it? TBH, I have no idea how it works. I have added `Ç€G` at the end and mapped over `[1...1000]` to see where the `1` is. Then, I ran script to count the number of zeros before the `1`. [Answer] # Ly, [LyricLy](https://codegolf.stackexchange.com/a/140838/56725) Answer: 239 I already wrote two Ly programs, so this wasn't too difficult. I think I would have somehow used the result from the loop in case someone tries to remove it. BTW, the fragment `nI` means that it doesn't always terminate successfully. [Answer] # [Python 2, Sisyphus](https://codegolf.stackexchange.com/a/140904/48934) ``` print~~[all([c[1](c[0](l))==h and c[0](l)[p]==c[0](p^q) for c in [(str,len)] for o in [2] for h in [(o*o*o+o/o)**o] for p,q in [(60,59),(40,44),(19,20),(63,58),(61,53),(12,10),(43,42),(1,3),(35,33),(37,45),(17,18),(32,35),(20,16),(22,30),(45,43),(48,53),(58,59),(79,75),(68,77)]] + [{i+1 for i in f(r[5])}=={j(i) for j in [q[3]] for i in l} for q in [(range,zip,str,int)] for r in [[3,1,4,1,5,9]] for g in [q[1]] for s in [[p(l)[i:i+r[5]] for p in [q[2]] for i in [r[5]*u for f in [q[0]] for u in f(r[5])]]] for l in s + g(*s) + [[z for y in [s[aprint~~[all([c[1](c[0](l))==h and c[0](l)[p]==c[0](p^q) for c in [(str,len)] for o in [2] for h in [(o*o*o+o/o)**o] for p,q in [(60,59),(40,44),(19,20),(63,58),(61,53),(12,10),(43,42),(1,3),(35,33),(37,45),(17,18),(32,35),(20,16),(22,30),(45,43),(48,53),(58,59),(79,75),(68,77)]] + [{i+1 for i in f(r[5])}=={j(i) for j in [q[3]] for i in l} for q in [(range,zip,str,int)] for r in [[3,1,4,1,5,9]] for g in [q[1]] for s in [[p(l)[i:i+r[5]] for p in [q[2]] for i in [r[5]*u for f in [q[0]] for u in f(r[5])]]] for l in s + g(*s) + [[z for y in [s[i+a][j:j+r[0]] for g in [q[0]] for a in g(r[0])] for z in y] for k in [[w*r[0] for i in [q[0]] for w in i(r[0])]] for i in k for j in k] for f in [q[0]]]) for l in [int(raw_input())]][0] ``` [Try it online!](https://tio.run/##XVHtbuIwEHyV/IyTlS7@tivlSSzfKaIFDFESEhCCqn116nV8AlUoWs/srL0zTLfzfhzY4zHNYTh/f7uu70u3cdSXG9f4siekbfdFN7wXGbvJt206T39PpNiOc7EpwlC4cjnP0H8MxCdyTCRbwX5VjFX81eOfkVTVuHYmOK091YC0BErRgBCxUgusiVVxkAYrBcmRZ0CRFxwEQwzIcgk8VQ1CIquB4hRnwBGzBqjCGnGaliBQL8x6qzTr69qCRr0yoDXxvqgL9xlqmnYNuOm2nJ305KttPw9lWAM4JAsnx71/CvuvdM725m7YfcA9TIAxxaxzTHNqOw4URPwk2HzHLt9JM15W4YR/QXgLNW6RI8xK9vq6w351ScQ2C5osuLz48JnrkVui3V1ZLQRtu3tq3NLw4kLdeXd4O8SHm18r/scd4l2JguzujsxtPR9XA9cK@y@LPueviEOef5EcnyEf/W9Hnjz3dzHXmPT1Xximy7kk8ZYoeTwoU4JrK42xUjEqNOdaWCORl5pabhSzhjOhJNWKMqkNt4Ipy6PWSCmMVpZxqjk1Ms7YHw "Python 2 – Try It Online") Answer: ``` 126437958895621473374985126457193862983246517612578394269314785548769231731852649 ``` ## Explanation Slightly less convoluted: ``` print~~[all( [len(str(l))==81 and str(l)[p]==str(p^q) for p,q in [(60,59),(40,44),(19,20),(63,58),(61,53),(12,10),(43,42),(1,3),(35,33),(37,45),(17,18),(32,35),(20,16),(22,30),(45,43),(48,53),(58,59),(79,75),(68,77)] ] + [{i+1 for i in range(9)}=={int(i) for i in l} for s in [[str(l)[9*u:9*u+9] for u in range(9)]] for l in s + zip(*s) + [[z for y in [s[i+a][j:j+3] for a in range(3)] for z in y] for k in [[w*3 for w in range(3)]] for i in k for j in k]]) for l in [int(raw_input())]][0] ``` [Try it online!](https://tio.run/##VU/LbsIwEDzDV@Rokz3EXj8r5Usst4rUVyAKaQJCUJVfp14biVaytTvjnfHOdD587kd5u01zPx6u19ANA1uvwvA2suUws4HztnWi6sbXquAwxbaldnr@4uvV6n0/VxN8Vf1YBWYa0J4DUw0olarwIJtUDYJ2VAVoJF6CIF4hKEkYiEUNmKsFpYm1IEiFEpCwbEAYqglntQZF88oVV@3K79aDpXnjwFoe16t06hTqu69FRfv2tO3cjR9vzPOftv1O2VnPH2/Dzz3ZknOFe3S/OT6lW/uYR49/bWL6pGgGopeqri79xDYLT10Il6w4Z7sl9HUXw/ZpW2Nx6h5OyAt1Iepc@l3Z4rTBDE//puNj7V1ut7mNseTJ2wQKOHenl36cjgfGkyo08XYT0ii0XjvntZFCWUSrvNPEays8OiO9Q6mMFtYIqa1Dr6TxmGad1spZ4yUKi8LppPG/ "Python 2 – Try It Online") Firstly, this part: ``` [len(str(l))==81 and str(l)[p]==str(p^q) for p,q in [(60,59),(40,44),(19,20),(63,58),(61,53),(12,10),(43,42),(1,3),(35,33),(37,45),(17,18),(32,35),(20,16),(22,30),(45,43),(48,53),(58,59),(79,75),(68,77)] ] ``` checks if the sudoku is in the following form: ``` .2.|...|... ...|6..|..3 .74|.8.|... ----------- ...|..3|..2 .8.|.4.|.1. 6..|5..|... ----------- ...|.1.|78. 5..|..9|... ...|...|.4. ``` Then this part checks for validity: ``` [{i+1 for i in range(9)}=={int(i) for i in l} for s in [[str(l)[9*u:9*u+9] for u in range(9)]] for l in s + zip(*s) + [[z for y in [s[a][j:j+3] for a in range(3)] for z in y] for k in [[w*3 for w in range(3)]] for i in k for j in k]] ``` [Answer] # [Pyth, Mr. Xcoder](https://codegolf.stackexchange.com/a/140797/41024) ``` hqQl+r@G7hZ@c." y|çEC#nZÙ¦Y;åê½9{ü/ãѪ#¤ ØìjX\"¦Hó¤Ê#§T£®úåâ«B'3£zÞz~Уë"\,a67Cr@G7hZ ``` [Try it here.](https://pyth.herokuapp.com/?code=hqQl%2Br%40G7hZ%40c.%22+y%08%7C%C3%A7%C2%85%C2%87EC%23nZ%C3%99%C2%A6Y%3B%C3%A5%C3%AA%C2%BD%C2%819%06%7B%C3%BC%2F%C3%A3%C3%91%C2%8A%C2%AA%23%06%C2%95%12%C2%A4%0A%C3%98%C3%AC%1AjX%5C%22%C2%8E%0F%C2%93%C2%A6H%C3%B3%C2%90%C2%A4%C3%8A%23%1D%0B%1D%C2%A7T%C2%85%C2%A3%04%07%10%C2%99%1D%C2%AE%18%C3%BA%C3%A5%C2%91%C3%A2%0B%C2%91%C2%ABB%14%273%C2%A3z%C3%9Ez~%C2%81%C3%90%16%C2%A3%C3%AB%19%22%5C%2Ca67Cr%40G7hZ&input=9&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0) Number: `9` [Answer] # [Swift 3, TheIOSCoder](https://codegolf.stackexchange.com/a/140808/59487) **Number: `387849`.** This returns `222` for the number above, and `212` for others. **[Test Here.](http://swift.sandbox.bluemix.net/#/repl/59a461bddcc75d533468baac)** --- # How? The relation is quite obvious: `.pi*123456.0` multiplies `3.1415...` by `123456.0` and converts it to an Integer. This means it is equal to `387848`. Then, it checks if the parameter equals the number above incremented by `1` (`n==1+...`). The value is `387848 + 1`, which is `387849`... [Answer] # [Java, Sleafar](https://codegolf.stackexchange.com/a/140945/69059) ``` 23 ``` The program traces `n` iterations of a fractal, and checks whether a specific point is removed in the `n`th iteration. In each iteration, each segment is replaced by eight smaller segments in the following pattern: ``` + | +-+ | +-+-+ | +-+ | + ``` Since no points are ever added to the line `y=.5` after the first iteration, I only had to handle the set of points included along this line. This set is similar to the construction of the Cantor set, but with the middle half removed instead of the middle third. The program I used to crack it: ``` import java.math.BigDecimal; public class Main { public static int f(BigDecimal x) { BigDecimal[] result = x.divideAndRemainder(BigDecimal.ONE); if (result[0].compareTo(BigDecimal.ZERO) == 0 || result[0].compareTo(BigDecimal.valueOf(3)) == 0) { return 1+f(result[1].multiply(BigDecimal.valueOf(4))); } return 0; } public static void main(String[] args) { BigDecimal x = new BigDecimal(args[0]); System.out.println(f(x)); } } ``` [Try it online!](https://tio.run/##hVHBToQwFDzTr3jHEmMD6GWz4aBxj0qy68kNhwoFi20hpSAbl2/Hkt0NqBjn8pK@mel0WtCWXpcVU0X6PgxcVqU2UNhDIql5I/c8f2AJl1SsEaqaV8ETSASta3ikXMEnQnDGeVkbauzgykCGJzV0riXDD0z7fQya1Y0wEEJHUt7ylN2pdMukvSZlemZFoqeNu/7lxTPAJ4u9F5OklBXV7LmcC18228iFMAQPjkf4h9xS0bAowzfuSbKU/wLNTKMV@FfZJYIfE2knr8RhyfTWdRee0KM/jL2J2yPkfK@6LXkKY014ZzRXua2S6rwe8zrO/AdstYp9zErHI88WYKM4zu5QGyZJ2RhSWRsjFM5wN8Z0etQPw0D8lR8EwSrwvwA "Java (OpenJDK 8) – Try It Online") [Answer] # Haskell, [flawr](https://codegolf.stackexchange.com/a/140817/56725) I think the number is 12018. I found it by defining in PARI/GP `f(x,k)=1/x^2-1/x^(2-1/k)` and `g(k)=sumpos(x=1,f(x,k))-sumpos(x=12345679,f(x,k))` and some binary searching. I don't like that one could trivially transform the program into one that returns the number and uses the same time and memory as the original program needs for any input. [Answer] # [Brain-Flak, Nitrodon](https://codegolf.stackexchange.com/a/140875/56656) The number is: ``` 1574 ``` [Try it online!](https://tio.run/##dVAxDoAgDPxOb3Aw0biQfsQ46GBiNA6uxLdjC4gYkbsUerSXwnSMy17N27g6Z5gKqxfIggL2DBww6AGqBKRLrzwx@eTtwp6CxU3yXrHENwtL8ySfzO8jIY6UD5NYdnzCr/2rKoiGLcXHyPeJqtrPDvYwrJlUw2ofGXsyJIdzdds1Fw "Brain-Flak – Try It Online") Here's the program I use to crack it ``` n!(0:_)=n n!a=(n+1)!zipWith(+)a(tail a++[0]) main=print$0![45646,253224,392678,8676,-24] ``` [Try it online!](https://tio.run/##BcFBCoMwEADAe17RgIeEpJCucbWFvKMHCWUPgotxEc2pn48zK13bUkprok34/GwSJZqSEfey@s/Hl@tqnCVTicuDnJtDtmonlnScLLULeo4DRvQw9ADR92/AcfITjuifEHNrNw "Haskell – Try It Online") [Answer] # [Java, user902383](https://codegolf.stackexchange.com/questions/140793/im-thinking-of-a-number-cops-thread/140959#140959) The secret number is `3141592` Explanation: After expanding all the `\u00xx` escapes, you get: ``` public class Mango { static void convert(String s){for(char c : s.toCharArray()){ System.out.print("\\u00"+Integer.toHexString(c));}} public static void main(String[] args) {int x = Integer.parseInt(args[0]); double a= x/8.-392699;double b = Math.log10((int) (x/Math.PI+1))-6; System.out.println((a/b==a/b?"Fail":"OK" )); }} ``` (the `convert` method isn't used). This computes some floating point math on the result, and then requires that `a/b` isn't equal to itself. The number for which that is true is `nan`, which is produced by `0/0`. It turns out that if `a` is 0, then `b` is `log10(0/pi + 1)` which is also 0, so `a` has to be 0 and x has to be `392699*8`. [Answer] # [Python 3](https://docs.python.org/3/), [user71546](https://codegolf.stackexchange.com/a/144843/78410) ``` def check(x): if x < 0 or x >= 5754820589765829850934909 or pow(x, 18446744073709551616, 5754820589765829850934909) != 2093489574700401569580277 or x % 4 != 1: return "No way ;-(" return "Cool B-)" print(check(141421356237)) ``` [Try it online!](https://tio.run/##dY/BCsJADETv/YpYELqgkN1NNrtqPejdfxBtaVG6pVSsX19bevHinDLDC8m0n76KjR3He1HCrSpuj2xQuwQm1SUMcACE2E3DMQcWJm@QfRDH3gTPGCwFDDPRxnc2bEB7IidEKFYwMGun3eb/poJVDmY2PrCQIBJqdoE9GpHl8hpopvTy1ayu6F9dA@klwvv6gf02S5Pf/BzjE05blSZJ29VNny3FNGky2rIzVpQaxy8 "Python 3 – Try It Online") The number is **141421356237**. The other three numbers which satisfy the first two conditions are 1459265341309891512760823, 5754820589765688429578672, and 4295555248455938338174086. ### How I solved it The gist of this challenge is to find the number that meets the following, given the prime `p = 5754820589765829850934909` and a value `a = 2093489574700401569580277`: * `0 <= x < p` * `x ** (2 ** 64) % p == a` * `x % 4 == 1` The second one can be rephrased to "find the [modular square root](http://www.mersennewiki.org/index.php/Modular_square_root) of modular square root of ... (64 times) of `a` modulo `p`." Since the given prime is 5 modulo 8, we can use the following formula from the above link (though I couldn't find the reference that supports it): \$ v = (2a)^{(p-5)/8} \mod p \$ \$ i = 2av^2 \mod p \$ \$ r = av(i-1) \mod p \$ \$ r' = p - r \$ Then we have two output values `r` and `r'` for an input value `a`. But not every number has such a square root, so we have to check if `r*r % p == a` is actually met. So I wrote a quick J script to find the 64th modular square roots. ``` p =: 5754820589765829850934909x a =: 2093489574700401569580277x powmod =: p&|@^ f =: monad define for. i.64 do. v =: p | (2*a) powmod (p-5)%8 i =: p | 2*a*v*v x =: p | a*v*i-1 NB. Apply the above formula a =: (a=p|x*x) # x NB. Filter by actually being the modular square root a =: a, p-a NB. Concat r with r' a end. ) res =: f '' ``` [Try it online!](https://tio.run/##NZBdasQgFIXf7yoOLW1@mIhJNepAoHQBXUJBMIEMTJQppD6ka081NA8i5/su54q3/fOD4YmhmDBcC1zwewVHOntIAFJJoTsutVG91J3Rkps3YbiJZLPvctRGKqE4F7yVvZGad0pFCv7n7l0eCq/b@xdR3oC7X6yDG6d5GWnyD4aZ9QLOMwLWYxobyq62Ff4bytDI6kUnP58@6Xqt14TiiTKYmzah42GlHcIW61jhGfGE9oLQ2JxoXByjiugxfmczoSiOr6j2RKhsMUCk1hRyQ7r@AA "J – Try It Online") `res` has the four values shown above; the last filtering by modulo 4 gives the answer. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/13074/edit). Closed 7 years ago. [Improve this question](/posts/13074/edit) This one is pretty simple. Write the shortest program you can, while generating the most output. To make it fun, programs that produce infinite output will be disqualified. The winner is the program with the largest output size/code size ratio. The results are based on what works on *my* computer, which is a Mac running Mac OS X 10.7.5 with an Intel Core i5 and 8GB of memory. [Answer] ### Python: 8 chars code, 387420489 chars output -- Ratio: 48427561.125 : 1 ``` 'a'*9**9 ``` We can have the ratio tend to infinity by adding more `**9`s: ``` 'a'*9**9**9 'a'*9**9**9**9 etc. ``` For example: ``` 'a'*9**9**9**9**9**9 ``` which has a ratio of **~10101010108.568** (unimaginably large number). [Answer] So, these are all good programs that produce lots of output with very little code, but none of them are *really* short... **brainfuck, 5 characters, 255 bytes of output** ``` -[.-] ``` I think this is the only use case where brainfuck really excels. I know this one isn't going to win, but I don't think we can possibly do better than the Python example. Not only that, but... **brainfuck, 4 characters, infinite output** ``` -[.] ``` I conjecture that this is the shortest infinite-output program out there. Actually, hold on, my mate's just come up with a really good one. **Python, 80 bytes, unknown amount of output** ``` from datetime import datetime while datetime.now()!=datetime.max() print "This will probably get disqualified" ``` This program will definitely halt eventually, but will only do so after roughly 8,000 years. The exact number of characters output depends on the rate at which your computer can produce characters. [Answer] ## Perl - 19 bytes, 187200000000000000 bytes output (9852631578947368.42 : 1) ``` print+($]x9e7)x26e7 ``` 166 petabyes with a single print statement, using no more than 1.7GB of memory. There's a few things that made this challenge more interesting that I thought it would be. Perl seems to refuse to allocate more than 1GB of memory to any single list. Hence, the 4-byte scalar reference to the inner string may only be repeated *26e7 ≈ 228* times. `$]` is the 'old perl version' number which, as a string, is 8 bytes long, resembling `5.016002`. With more system memory, it should be able to go higher. Assuming the full 8GB were actually available, you should be able to use `$]x9e8` for the inner string instead, which would output 1.62 exabytes. [Answer] ## Ruby and Python, 13 chars, 599994 char output, ~46153:1 ratio ``` 999999**99999 ``` Simply raises a very large number to the power of another very large number. Takes about 20 seconds to run. I can't increase the numbers because that would make the number become Infinity. (I [did this earlier](https://codegolf.stackexchange.com/a/12659/3808), I am currently working on making a loop for even longer output) Edit: I did it! ## Ruby, 28 chars, 6e599999 char output, ~6e599998 ratio (I think) ``` a=999999**99999;a.times{p a} ``` Untested (for obvious reasons), but I'm pretty sure the first number is about 1e599994, which multiplied by 599994 is about 6e599999. Theoretically it would work, but I'm not sure if it would crash your computer, so disclaimer: I am not responsible if it harms your computer in any way :P Of course, you can keep going: ## Ruby, 37 chars, 6e359992800041 char output, ~6e359992800040 ratio ``` a=999999**99999;a.times{a.times{p a}} ``` And so on, but I doubt any computer can handle that :P [Answer] If infinite input was allowed, ``` cat /dev/random ``` Since it's not, ``` head -99 /dev/random ``` (25128 output : 20 input = 1256.4:1) I'm not on a Linux box, but I imagine you could do something like ``` timeout 99d cat /dev/random ``` and get a huge output. (via GigaWatt's response) [Answer] ## HQ9+, 11471 ``` 9 ``` Actual character count varies depending on the interpreter, but probably around 10000 would be right? [Answer] # C#: 108 chars. Ratio: 742123445489230793057592 : 1 ``` for(ulong i=0;i<ulong.MaxValue;i++){Console.Write(new WebClient().DownloadString(@"http://bit.ly/dDuoI4"));} ``` It just downloads and prints the wikipedia's *List of law clerks of the Supreme Court of the United States* (4344904 chars) 18446744073709551615 times. [Answer] # ~-~! - Ratio: (6444464)/154 ~= 10101010101.583328920493678 ``` '=~~~~,~~~~,~~~~:''=|*<%[%]'=',',',':''&*-~|:'''=|*<%[%]''&',',',':'''&*-~|:''''=|*<%[%]'''&',',',':''''&*-~|:''''&':''=|*<%[%]@~~~~,~~~~,~~:''&*-~|:''&': ``` How it works: First, it sets `'` to 4^3, or 64. Then, it makes `''` a function which sets `'` to `'`^4 \* times (where \* is it's input). `'''` is then made a function which calls `''` with the input as `'`^4. Then, `''''` is made a function which calls `'''` with `'`^4 as it's input. `''''` is then called with an input of 64. Finally, `''` is changed to a function which prints a space \* times; this is then called with an input of `'`. Turns out, in the end, `'` is **6444464**, and my program's length is **154**; [punch that into Wolfram|Alpha](https://www.wolframalpha.com/input/?i=%2864%5E%284%5E%284%5E%284%5E64%29%29%29%29/154) and it spits out **10101010101.583328920493678**, which it doesn't even bother to calculate. [I don't even know how many digits it contains](https://www.wolframalpha.com/input/?i=Length%5BIntegerDigits%5B%2864%5E%284%5E%284%5E%284%5E64%29%29%29%29/154%5D%5D), but 6444 contains 463. Pretty nice for a language that only supports unary explicit numbers and doesn't have an exponent function ;3 I could have made this a lot larger, but, overkill. [Answer] ## Javascript: 27 chars; 260,431,976 char output; 9,645,628.74 ratio ``` for(s=i=61;s=btoa(s),i--;)s ``` This code recursively encodes the input `61` to Base64 61 times. Encoding any input of length `n` to Base64 produces an output of length `n * 8/6`, rounded up to a multiple of 4. This must be run from a JavaScript console environment that natively supports the Base64-encoding function `btoa`. (Any modern browser, but not Node.js.) Note Chrome cannot run higher than `i=61`, while Firefox can only reach `i=60`. Note also that Chrome's console cannot actually display the output because it is too large, but you can verify the result size by running ``` for(s=i=61;s=btoa(s),i--;)s.length ``` If this program were allowed to run for the maximum `i=99`, it would produce a hypothetical output of size **14,566,872,071,840** (14.5 trillion, 14.5e12) chars, for a hypothetical ratio of around 540 billion (5.39e11). [Answer] # Befunge-93: 48 characters, about ((2^32)^2)\*10 characters output Befunge's stack is theoretically infinite, but the numbers that stack stores are limited to the size of an unsigned long integer (here assumed to be 32 bits). Thus, to a Befunge interpreter, (x+1)>x is false for the proper value of x. We use this fact to first push all values from zero to the maximum (twice, with a one every third number), and then for each value on the stack, we output and decrement it, then pop it when it reaches zero. Eventually the stack empties and the program terminates. I may be a bit off on the output size, but it should be somewhere in that ballpark. ``` >::1# + #1\`# :# _> #- #1 :# :# .# _# .# :# _@ ``` [Answer] ## C: 48 chars, approx. (2^32 - 1)\*65090 bytes output ``` main(){for(int i=1<<31;i<~0;)puts("!");main();} ``` Note that the 65090 is not exact, and depends on stack size. The program will eventually stop when it crashes. Also, I could just put a longer and longer string in puts() to make the ration approach infinity, but that seems rather cheaty. [Answer] ## Ruby, 23 characters - ~500000000000000 (5e14) Output ``` while rand puts 0 end ``` ## Ti-Basic 84, 13 characters - ~3000 Output ``` :Disp 1 :prgmA ``` Name the program `prgmA` [Answer] ## ruby, ~~283~~ ~~96~~ 44 chars ``` a=1e99.times;a{a{a{a{a{puts'a'*99}}}}}}}}}} ``` Not very short, but it compensates for it in output, which is so much I haven't yet been able to measure it. [Answer] # Mathematica 9 chars Ratio: ~ 4564112 : 1 The following is a picture of Mathematica input. I haven't figured how to render it in SE. ![exponents](https://i.stack.imgur.com/szGsa.png) Here's a screen shot showing the number of digits in the output. `IntegerDigits` converts the output to a list of digits. `Length` counts the number of digits. ![count](https://i.stack.imgur.com/wrjB9.png) Keystrokes to enter: `9`, `ctrl``6`, `9`, `ctrl``6`, `9`, `ctrl``6`, `9`, `ctrl``6`, `9`.... [Answer] # Python 3, 115 bytes, runs for 7983 years (unknown # of chars) EDIT: ymbirtt beat me to it .\_. I know, this isn't really short, and I know that the other Python answer is *much* longer, But I decided to give this a shot. The program runs for about 8000 years, which, as you know, is a pretty long time. What it does is continuously get the current time using the `datetime.datetime.now()` function, and it compares it to `9999-12-31 24:59:59.999999`, which is as far as I know the maximum date in Python. If is *is* equal, the program stops. If it isn't, it continously outputs `a`. ``` import datetime while 1: if str(datetime.datetime.now())=="9999-12-31 24:59:59.999999":exit else:print("a") ``` [Answer] java(131): unknown but finite amount ``` class A{public static void main(String[] args){while(Math.random()>0){for(long l=0;l!=-1;l++){System.out.println("1234567890");}}}} ``` Using the low chance of Math.random() to get to 0 in a loop and then goin 2^64-1 loops thru a foreach with the output 1234567890; ]
[Question] [ Given a unix timestamp as an input, give a datetime string, in a format like so: "YYMMDD.HHmm" ## Rules * The input is a number (integer) of a millisecond-precise UNIX epoch time (milliseconds since 1970 January 1st 00:00:00.000 UTC). * The values must be padded with zeroes if they are 1 character instead of 2. (e.g.: for "DD", "1" is not acceptable, but "01" is.) * The output must be a single string. No arrays. * Leap second handling doesn't matter. * Shortest wins. Good luck! ## Example ``` Input: 1547233866744 Output: 190111.1911 ``` [Answer] # JavaScript (ES6), 65 bytes ``` n=>'101010.1010'.replace(i=/\d/g,x=>new Date(n).toJSON()[i=x-~i]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k7d0AAE9UCEul5RakFOYnKqRqatfkyKfrpOha1dXmq5gktiSapGnqZeSb5XsL@fhmZ0pm2Fbl1mrOb/5Py84vycVL2c/HSNNA0DTU0uVBFDUxNzI2NjCzMzcxMTDFmQuXp5@eUampqa/wE "JavaScript (Node.js) – Try It Online") ### How? We initialize the pointer \$i\$ to a non-numeric value (coerced to \$0\$) and then add alternately \$2\$ and \$1\$ to it to pick the relevant characters from the ISO-8601 conversion of the input timestamp. ``` yyyy-mm-ddThh:mm:ss.sssZ ^^ ^^ ^^ ^^ ^^ ``` --- # JavaScript (ES6), 66 bytes ``` n=>'235689.BCEF'.replace(/\w/g,x=>new Date(n).toJSON()[+`0x${x}`]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k7dyNjUzMJSz8nZ1U1dryi1ICcxOVVDP6ZcP12nwtYuL7VcwSWxJFUjT1OvJN8r2N9PQzNaO8GgQqW6ojYhVvN/cn5ecX5Oql5OfrpGmoaBpiYXqoihqYm5kbGxhZmZuYkJhizIaL28/HINTU3N/wA "JavaScript (Node.js) – Try It Online") ### How? Once the input timestamp is converted in ISO-8601 format, all required characters can be accessed with a single hexadecimal digit. ``` yyyy-mm-ddThh:mm:ss.sssZ ↓↓ ↓↓ ↓↓ ↓↓ ↓↓ 0123456789ABCDEF ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 29 bytes ``` date -d@${1::-3} +%y%m%d.%H%M ``` [Try it online!](https://tio.run/##S0oszvj/PyWxJFVBN8VBpdrQykrXuFZBW7VSNVc1RU/VQ9X3////hqYm5kbGxhZmZuYmJgA "Bash – Try It Online") [Answer] # [PHP](https://php.net/), ~~40~~ ~~32~~ 31 bytes *-8 bytes thanks to Luis felipe* *-1 byte thanks to Jo King* ``` <?=date('ymd.hi',$argv[1]/1e3); ``` [Try it online!](https://tio.run/##K8go@P/fxt42JbEkVUO9MjdFLyNTXUclsSi9LNowVt8w1VjT@v///4amJuZGxsYWZmbmJiYA "PHP – Try It Online") Simple naive answer. PHP's `date` function takes a format string and an integer timestamp. Input from cli arguments, which is a string by default, then `/1e3` because `date` expects second-precise timestamps. This also coerces the string to a number. [Answer] # [MATL](https://github.com/lmendo/MATL), 28 bytes *Thanks to [@skiilaa](https://codegolf.stackexchange.com/users/84948/skiilaa) for a correction in the output format.* ``` 864e5/719529+'YYmmDD.HHMM'XO ``` [Try it online!](https://tio.run/##y00syfn/38LMJNVU39zQ0tTIUls9MjI318VFz8PD11c9wv//f0NTE3MjY2MLMzNzExMA) ### Explanation MATL, like MATLAB, defines date/time numbers as the (possibly non-integer) number of days since time 00:00 of the reference "date" 0-Jan-0000. Thus we take the input, divide it by 86400000 (number of milliseconds in one day), add 719529 (number of days from MATL's reference to UNIX reference), and convert to the desired format 'YYmmDD.HHMM'. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~59~~ 58 bytes ``` "{0:yyMMdd.HHmm}"-f(Date 1/1/1970).AddSeconds("$args"/1e3) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X6nawKqy0tc3JUXPwyM3t1ZJN03DJbEkVcFQHwgtzQ009RxTUoJTk/PzUoo1lFQSi9KLlfQNU401////b2hqYm5kbGxhZmZuYgIA "PowerShell – Try It Online") Gets the `Date` of `1/1/1970` (defaults to 00:00:00am), then `Add`s the appropriate number of `Seconds`. Passes that to the `-f`ormat operator, which correctly formats the datetime. Probably culture-dependent. This works on TIO, which is `en-us`. *-1 byte thanks to shaggy.* [Answer] # GNU AWK, ~~34~~ 33 characters ``` $0=strftime("%y%m%d.%H%M",$0/1e3) ``` (`strftime()` is GNU extension, will not run in other AWK implementations.) Thanks to: * [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for suggesting [E-notation](https://en.wikipedia.org/wiki/Scientific_notation#E-notation) (-1 character) Sampler run: ``` bash-4.4$ awk '$0=strftime("%y%m%d.%H%M",$0/1e3)' <<< 1547233866744 190111.2111 ``` [Try it online!](https://tio.run/##SyzP/v9fxcC2uKQorSQzN1VDSbVSNVc1RU/VQ9VXSUfFQN8w1Vjz/39DUxNzI2NjCzMzcxMTAA "AWK – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [v1.4.5](https://ethproductions.github.io/japt/?v=1.4.5), ~~19~~ 16 bytes ``` GîÐU s3)¤o>J i.G ``` 1 byte saved thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver), which led to another 2 bytes saved. [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=R+7QVSBzMymkbz5KIGkuRw==&input=MTU0NzIzMzg2Njc0NA==) --- ## Explanation ``` GîÐU s3)¤o>J i.G :Implicit input of integer U G :16 î :Get the first 16 characters of the following string ÐU : Convert U to a date object s3 : Convert to ISO string ) :End get ¤ :Slice off the first 2 characters o :Filter >J : Greater than -1 i.G :Insert "." at 0-based index 16, with wrapping ``` --- [Answer] # [Perl 6](https://perl6.org), ~~111 89~~ 87 bytes ``` {~DateTime.new($_/Ⅿ,:formatter{"{(.year%Ⅽ,.month,.day).fmt('%02d','')}.{(.hour,.minute).fmt('%02d','')}"})} ``` [Try it (111)](https://tio.run/##Zc3BCoIwGADgu08xLJvCWE5Ns@jWI3SPob8oNBdzFkPs5uNE7@SLLOna/YPvDuqW2r4D9EhpcXQcYdCmkCWgkx1eZ67h0gigLTz99XU7Tx9yqKQSXGtQgzv41ABX3jy9CRWy1TWhJTcBrYT2sRdGJSYYByNdYC17taCm7TX8AXcMRttxg3412yVZFMf7NM2SBK0Qy0PGGGU5Y/YL "Perl 6 – Try It Online") ``` {TR/-//}o{S/..//}o{.yyyy-mm-dd~'.'~(.hour,.minute).fmt('%02d','')}o{DateTime.new($_/Ⅿ)} ``` [Try it (89)](https://tio.run/##HY3LCoJAFED3fsVAj1HQO161MYl2fUG5D3FuJDQaPgoR3fU9/VM/MolndTaH86T6IU3XEHtJyA@WpXu2zStF7GiG9Cw8IcZquAiARaCf8bT2lJo48MmGe9XVLuii7Fpy4KZbm2/8QHGXc2cOTllLaaEJSnrb66v4fb7OaJqsZ8sEd1EchOFeyjiK2Iph4iMiYIJo/g "Perl 6 – Try It Online") ``` {TR/- //}o{S/..//}o{.yyyy-mm-dd~'.'~(.hour,.minute).fmt('%02d')}o{DateTime.new($_/Ⅿ)} ``` [Try it (87)](https://tio.run/##K0gtyjH7X1qcqlBmppdszcWVW6mglpyfkqpg@786JEhfV0Ffvza/OlhfTw/M0KsEAt3cXN2UlDp1PfU6Db2M/NIiHb3czLzSklRNvbTcEg11VQOjFHVNoGqXxJLUkMzcVL281HINlXj9R63rNWv/FydWKoCtMDQ1MTcyNrYwMzM3MVFQVjC0NDA0NNQztDQ0/A8A "Perl 6 – Try It Online") ## Explanation: The `o` infix operator takes two functions and creates a composite function. The rightmost one gets called first, and the one to the left gets called with its result. Basically we use 4 block lambdas to generate a single lambda. Which is not much different to how a WhateverCode lambda like `* + *` gets created. --- Divide by 1000 and use that to create a DateTime object. ``` {DateTime.new($_/Ⅿ)} # Ⅿ is ROMAN NUMERAL ONE THOUSAND (3 bytes) ``` The result gets used by: ``` { .yyyy-mm-dd # 2019-01-11 ~ '.' ~ # str concatenation with '.' ( .hour, .minute ).fmt('%02d') # add leading 0s (returns List) } ``` That leaves us with a string like `2019-01-11.19 11` We need to remove the first two digits ``` {S/..//} ``` We also need to remove `-` and ``` {TR/- //} ``` [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes ``` lambda s:strftime('%y%m%d.%H%M',gmtime(s/1e3)) from time import* ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqrikKK0kMzdVQ121UjVXNUVP1UPVV10nPRcsWKxvmGqsqcmVVpSfqwASUcjMLcgvKtH6X1CUmVeikKaRmVdQWqKhqfnf0NTE3MjY2MLMzNzEBAA "Python 2 – Try It Online") The input is considered to be in UTC. [Answer] # [R](https://www.r-project.org/), ~~58~~ 56 bytes ``` format(as.POSIXct(scan()/1e3,,'1970-1-1'),'%y%m%d.%H%M') ``` [Try it online!](https://tio.run/##K/r/Py2/KDexRCOxWC/AP9gzIrlEozg5MU9DU98w1VhHR93Q0txA11DXUF1TR121UjVXNUVP1UPVV13zv6GpibmRsbGFmZm5icl/AA "R – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/) (32-bit, little endian), 67 bytes ``` f(t,s)long long t;{t/=1e3;strftime(s,12,"%y%m%d.%H%M",gmtime(&t));} ``` [Try it online!](https://tio.run/##HYlBC8IgGEDP26@QgaHgCnVtgXTv0i@IDmLTBtNi39chxv56Vrs8Hu@5OjiXs2cogI@PFMgKNDPujrLXBnDyOMSegZBKVPRNI71t6YmeKxHiejbIuVnykJBEOyTGyVwW7m4nAheprqYsPJP7plNaH9q2axpBgP/q84XA/rbkj/OjDZDrqNUX "C (gcc) – Try It Online") On an ILP64 platform, the following **55 byte** version should work: ``` f(t,s){t/=1e3;strftime(s,12,"%y%m%d.%H%M",gmtime(&t));} ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~57~~ 50 bytes ``` {TR:d/T:-/./}o{substr ~DateTime.new($_/1e3): 2,15} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OiTIKkU/xEpXX0@/Nr@6uDSpuKRIoc4lsSQ1JDM3VS8vtVxDJV7fMNVY00rBSMfQtPZ/cWKlQpqCoamJuZGxsYWZmbmJyX8A "Perl 6 – Try It Online") Takes the default stringification of a Datetime, in the format `yyyy-mm-ddThh:mm:ssZ` and modifies it to fit the output format. Perl 6 is in need of a date formatter method. ### Explanation: ``` Datetime.new($_/1e3) # Create a date time ~ # Stringify it to the format yyyy-mm-ddThh:mm:ssZ # e.g. 2019-01-11T19:11:06.744000Z substr : 2,15 # Take the middle 15 characters {TR:d/T /./}o # Then replace 'T' with '.' :- # Then remove ':' and '-' ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~67~~ ~~61~~ 60 bytes ``` n=>$"{new DateTime(1970,1,1).AddTicks(n*10000):yyMMdd.HHmm}" ``` For reasons unknown to me, DateTime.UnixEpoch doesn't work. [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5Ofl65TXFKUmZduV2H7P8/WTkWpOi@1XMElsSQ1JDM3VcPQ0txAx1DHUFPPMSUlJDM5u1gjT8vQAAg0rSorfX1TUvQ8PHJza5X@W3MFAM0p0ajQMDQ1MTcyNrYwMzM3MdHUtP4PAA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Javascript ES6, ~~76~~ 66 bytes ``` x=>new Date(x).toJSON().slice(2,16).replace(/\D/g,a=>a>'S'?'.':'') ``` [Try it online](https://tio.run/##DcexDoMgEADQX@l2kChGpWiaQBenDu3g2uWkp7EhYIS0/j3t294bPxjtvm6pnHAiV/rwojzrfGjj6XsaMBE7uEjhNj7ujIvoVkusKWrFxU6bw/@q51AtBWqDBka4goALAM82@BgcCRcWNrP6LLumbXulOik5zz8) -10 bytes thanks to Shaggy! --- ``` x // timestamp => new Date(x) // date object from timestamp .toJSON() // same as .toISOString() .slice(2,16) // cut off excess .replace(/\D/g, // match all non-digits a // a is matched character => a>'S'?'.' // if a is T (bigger than S is shorter) replace it with . :'' // if it's not T, replace it with nothing // this way the dashes get removed and the dot gets put in the right place ) // end of replace ``` [Answer] # [C (clang)](http://clang.llvm.org/), 117 111 bytes Thanks to @chux and @ceilingcat for the suggestions. ``` #import<time.h> *l;f(long t){t/=1e3;printf("%02d%02d%02d.%02d%02d",5[l=gmtime(&t)]%100,l[4]+1,l[3],l[2],l[1]);} ``` [Try it online!](https://tio.run/##NY3NDoIwEITvPMWKkbRYlfKnScUXMRwIFmxSwNSNF8Oz11b0sLNfdiaz7a7Vzdhbu1bDYzJ4RjXI/f0SxFp0RE9jD0jfeKi4zMTDqBE7Em6S9Paf/R9CVlx11Q@@gERI6w1PEqaveb3lbmW1k9QLr6mYrWuCoVEj8dCYvmXtvTEQx45fFN4BwPJdOFosKQLHqiM@fuFLCACrJxqctD@/XDuDSDLgCRVf2@Xlqvp5EEWwiiWFjuDXn4PZWl7kxzTLTmV5zPMP "C (clang) – Try It Online") [Answer] # Twig, 25 characters ``` {{d[:-3]|date('ymd.hi')}} ``` This is a template. Call it by including it and pass the Unix time as parameter d. Sample usage: ``` {{include('datetime.twig', {'d': 1547233866744})}} ``` [Try it on TwigFiddle](https://twigfiddle.com/rkyjd5) [Answer] # JavaScript, 64 bytes ``` n=>'2356891911121415'.replace(/1?./g,x=>new Date(n).toJSON()[x]) ``` [Try it online!](https://tio.run/##Zcy9DoIwFEDh3adwozfR4u0fMBQXJwcdHI1DUwrRNC2BRnj7Gkfjer7kvMzbzHZ6jmkfYudyr3PQbcG4VHWDDSIyFCgLOrnRG@tIiUdaDrtVt8Et25NJjgSgKZ5v1wuB@/qAbGOYo3fUx4H05ACw@S0oRcU4r5WqhPjT75KGuBAAyB8 "JavaScript (Node.js) – Try It Online") [Answer] # Java 8, 78 bytes ``` n->new java.text.SimpleDateFormat("yyMMdd.HHmm").format(new java.util.Date(n)) ``` [Try it online.](https://tio.run/##hZA9b8IwEIZ3fsWJyR44UUihEqJThRgaFrpVHQ7HIKf2JUoutFHFb0@dEnWi6uL7eu/eR87pTJM8e@@Mp7qGlBx/jQAci62OZCzs@hJgL5XjExjlixhYr2L3MopPLSTOwA4Y1tDx5JHtB@TxKor9FNy7UHr7RGI3RRVI1Lht0zTLcLsNYazxeO3@LjXiPPZyxVp3q96hbA4@OgxG58JlECKmuiK9vgHpgbGtxQYsGsEyjsSzYjRq@qx/cP8U3N0ny9l8/rBYLJPkP/ENUo0nKy8uxEwPH3PpvgE) **Explanation:** ``` n-> // Method with long parameter and String return-type new java.text.SimpleDateFormat("yyMMdd.HHmm") // Create the formatter .format( // Format the date to a String in this format and return it: new java.util.Date( // Create a new Date n)) // With the input-long as timestamp ``` [Answer] # jq, 33 characters (30 characters code + 3 characters command line option) ``` ./1000|strftime("%y%m%d.%H%M") ``` Sample run: ``` bash-4.4$ jq -r './1000|strftime("%y%m%d.%H%M")' <<< 1547233866744 190111.1911 ``` [Try it online!](https://tio.run/##yyr8/19P39DAwKCmuKQorSQzN1VDSbVSNVc1RU/VQ9VXSfP/f0NTE3MjY2MLMzNzE5P/ukUA "jq – Try It Online") [Answer] # [ksh](http://www.kornshell.com/), 36 bytes ``` printf "%(%y%m%d.%H%M)T" $(($1/1e3)) ``` [Try it online!](https://tio.run/##yy7O@P@/oCgzryRNQUlVQ7VSNVc1RU/VQ9VXM0RJQUVDQ8VQ3zDVWFPz////hqYm5kbGxhZmZuYmJgA "ksh – Try It Online") Thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for 15 bytes saved [Answer] # MediaWiki, 46 bytes ``` {{#time:ymd.Hi|@{{#expr:floor({{{1}}}/1e3)}}}} ``` ]
[Question] [ For a computer language, a reserved word is a word that cannot be used as an identifier, such as the name of a variable, function, or label. For other computer languages, keywords can be considered as the set of the language instructions. ## Challenge Using your language of choice, write a code in the chosen language that given a number between one and ten, `1<=n<=10`, outputs any `n` reserved words (keywords) of the chosen language. ## Specifics * If the chosen language is case sensitive the outputted keywords must be also. * If the chosen language is not case sensitive the outputted keywords can be in any case. * If the chosen language has less than 10 keywords saying `p`, the code must output all the reserved words for any `n` between `p` and `10`. * If possible specify in the answer whether you consider operators as keywords or not. ## Possible samples for Java (JDK10) * `n=1 --> true` * `n=3 --> try new interface` * `n=4 --> continue this long break` ## Possible samples for ><> * `n=1 --> >` * `n=3 --> > < ^` * `n=4 --> > < \ /` ## Possible samples for Brain-Flak * `n=1 --> (` * `n=3 --> ( ) [ ]` * `n=9 --> ( ) [ ] { } < >` ## Rules * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * No need to handle **invalid input values**, valid inputs are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an on-line testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [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 `n` (actually works for the range 0–29). APL keywords are single character symbols, so this prints `n` symbols to stdout. ``` ⎕↑156↓⎕AV ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jvqmP2iYampo9apsMZDuGgYT/K4BBGpchF4xlCmcZGsCZRpYA "APL (Dyalog Unicode) – Try It Online") `⎕AV` the Atomic Vector (i.e. the character set) `156↓` drop the first 156 elements `⎕↑` prompt for `n` and take that many elements from the above [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes ``` lambda n:'=+*/%&^|<>'[:n] ``` An unnamed function accepting an integer in [1,10] which returns a string of single-byte binary operators. **[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSt1WW0tfVS2uxsZOPdoqL/Z/Wn6RQp5CZp5CUWJeeqqGoY6hoaYVF2dBUWZeiUKaRp7mfwA "Python 2 – Try It Online")** The operators: ``` = Assign + Addition * Multiplication / Division % Modulo & Bitwise-AND ^ Bitwise-XOR | Bitwise-OR < Less Than? > Greater Than? ``` --- ### If only actual keywords are allowed: 40 bytes ``` from keyword import* lambda n:kwlist[:n] ``` An unnamed function accepting an integer in [1,10] which returns a list of strings. **[Try it online!](https://tio.run/##BcExDoAgDADAWV7REYwLjiS@RB0wgBKgJZWE@Hq8q197CNcRtmNkWy5nAU3qOb5tN3iKwFQg@a8TO4ilErd5BGJAiAhs8fZSL1orI6bKERsEiWr8 "Python 2 – Try It Online")** The code should be quite straightforward - it defines a function taking one argument, `n`, using `lambda n:...` which returns the first `n` (`...[:n]`) of the known keywords using the standard library's `keywords.kwlist` (along with the standard golfing technique of `import*`). [Answer] # Java 10, ~~83~~ 72 bytes (keywords) ``` n->"do if for int new try var byte case char ".substring(0,n*5) ``` [Try it online.](https://tio.run/##LY9BboNADEX3OcUXK6Y0KFl0U0pv0Gy6bLIww9A6JSZiDBGKcnbqkkgztmzL/z8faaT1sf6dfUsx4oNYriuARUPfkA/Y/ZfAp/Ys3/CpTSCusObNvr2opOyxg6DELOv3pO5sgRsLTdcvWoCEC6D9BIxkvWrSAE/Rwo/VSR6HKi4W6eZZnl7cXKxM@zxUrWk/LMaOa5yMML3TfB1A7o5nRgsZl9sC/FZuN5ayzC1Do5@ihlPeDZqfbVNbSTlLXveaZJLbTe5x0G3@Aw) **Old 83 bytes answer:** ``` n->java.util.Arrays.copyOf("do if for int new try var byte case char".split(" "),n) ``` [Try it online.](https://tio.run/##ZY/BTsMwEETv/YqRT7ZCLXolBIkPoBw4Aoetk1CH1I7sTVCE@u1hSSsuSF5b3tXOvOloom1Xfy6up5zxRD58bwAfuEktuQb73y/wwsmHj9d3OC0zBFNK@ywlJzOxd9gjoMIStg@diNqRfW8fU6I5WxeH@bnVqo7wLdqYsIo0X@A0Y6KEw8wNHGW5jpSUzUPvWSsocxPMUm7EZhgPvdhc3aboa5wEV/@hkbmwiv4K6atdCX9f7W7lKQqzDiXKnLk52TiyHWST@6B9oe7eWBX/wDle1HWwEtyYa@zz8gM) **Explanation:** ``` n-> // Method with integer parameter and String-array return-type java.util.Arrays.copyOf( // Create a copy of the given array: "do if for int new try var byte case char".split(" ") // The keywords as String-array, ,n) // up to and including the given `n`'th array-item ``` [List of available keywords for Java 8.](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html) Java 10 has the keyword `var` in addition to these. --- # Java 8+, 30 bytes (operators) ``` n->"+-/*&|^~<>".substring(0,n) ``` [Try it online.](https://tio.run/##LY7LDoJADEX3fkXDwjCOIGzl8QeycekjGV5mEAphBhKj@OtjBZI2TducnFuJUThV/jRZLZSCk5D43gBI1EVfiqyA5L8CnHUv8QGZTR9AFtBxoqZSWmiZQQIIERh0Yos7h932c/@GseWqIVUzant7ZCbYENENaU3ECo6tzKEhr704LjcQbJGWbT/7ZOQHIMPI92hwzuYnZXopXTRuO2i3I1LXaEtuHa/a4uhSUrbGnMwP) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly) ``` ØAḣ ``` A monadic link accepting an integer and returning a list of characters. **[Try it online!](https://tio.run/##y0rNyan8///wDMeHOxb////fEgA "Jelly – Try It Online")** The resulting characters are all monadic [atoms](https://github.com/DennisMitchell/jelly/wiki/Atoms) in Jelly's [code-page](https://github.com/DennisMitchell/jelly): ``` A Absolute value. B Convert from integer to binary. C Complement; compute 1 − z. D Convert from integer to decimal. E Check if all elements of z are equal. F Flatten list. G Attempt to format z as a grid. H Halve; compute z ÷ 2. I Increments; compute the differences of consecutive elements of z. J Returns [1 … len(z)]. ``` ### How? ``` ØAḣ - Link: integer n (in [1,10]) ØA - yield uppercase alphabet = ['A','B','C',...,'Z'] ḣ - head to index n ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki/Tutorial), 16 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` ✂”yPBG¤T⎚M↶↷J”⁰N ``` Too bad there isn't [a preset variable](https://github.com/somebody1234/Charcoal/wiki/Preset-variables) for its own code-page in Charcoal. [Try it online.](https://tio.run/##AUUAuv9jaGFyY29hbP//U2xpY2UoIu@8sO@8ou@8p8Kk77y04o6a77yt4oa24oa377yqIiwwLElucHV0TnVtYmVyKf//Nf8tdmw) **Explanation:** Get a substring from index 0 to the input-number: ``` Slice("...",0,InputNumber) ✂”y...”⁰N ``` The string with 10 keywords: ``` ”yPBG¤T⎚M↶↷J” ``` [Answer] # [Perl 5](https://www.perl.org/) `-lp`, 24 bytes ``` #!/usr/bin/perl -lp $_=(grep!eval,a..zz)[$_] ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYjvSi1QDG1LDFHJ1FPr6pKM1olPvb/fwMuQy4jLmMuEy5TLjMucy4LLksuQwOuf/kFJZn5ecX/dXMKAA "Perl 5 – Try It Online") Easy to extend to more and longer keywords, but you will need to do special casing starting at 4 letters because you will run into problems with `dump`, `eval`, `exit`,`getc` etc.. Of course just outputting operators and sigils is boring but shorter at 11 bytes: ``` #!/usr/bin/perl -lp $_=chr$_+35 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jY5o0glXtsYyDHkMuIy5jLhMuUy4zLnsuCy5DI04PqXX1CSmZ9X/F83pwAA "Perl 5 – Try It Online") (I skipped `#` since it's unclear how I should classify it in the context of this challenge) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 79 61 bytes ``` n=>'true int var for in if new try of do'.split` `.slice(0,n) ``` [Try it online!](https://tio.run/##Zcg7DsIwDADQnVN4ayxBxH8rZ2mU2igosisnLeL0gRVle3qvsIUSLS31IDpT47HJ@BiqrQRJKmzBgNV@hsQg9IZqH1CGWQdflpzqBJMvOUVyx71giypFM/msT8fuhLj7n3M3l26u3dy6uSO2Lw "JavaScript (Node.js) – Try It Online") # How : ``` n => // the input (will be an integer) between 1 and 10 (both inclusive) ' // beginning our string true int var for in if new try of do'. // space separated reserved words split` `. // turn it into an array every time there is a space we add to array slice(0,n) // return elements of array starting from 0 and upto n ``` If using operators is allowed (most likely will be since they are reserved words) then : # [JavaScript (Node.js)](https://nodejs.org), 26 25 bytes ``` n=>'|/^%+<&*-='.slice(-n) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1k69Rj9OVdtGTUvXVl2vOCczOVVDN0/zf3J@XnF@TqpeTn66RpqGoaYmF6qIEYaIMYaICYaIKYaImabmfwA "JavaScript (Node.js) – Try It Online") Saved 8 bytes thanks to *@Adam* and 1 more byte thanks to *@l4m2* # How : ``` n => // input (integer from 0-9 inclusive) '|/^%+<&*-='. // operators make a shorter string slice(-n) // outputs string chars from last upto n // this works since all operators are single chars and not multi chars. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 22 bytes ``` ->n{'+-*/%&|^<>'[0,n]} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cur1pdW1dLX1WtJs7GTj3aQCcvtvZ/gUKaXnJiTo6GoSYXnG2ExDZGYpsgsU2R2GZIbHMktgUS2xKJbWigyfUfAA "Ruby – Try It Online") -2 bytes thanks to *@benj2240* [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` >QPG ``` [Try it online!](http://pyth.herokuapp.com/?code=%3EQPG&input=10&debug=0) Unfortunately, many of the letters are variables (`GHJKNQTYZbdkz`). ``` p <any> Print A, with no trailing newline. Return A. q <any> <any> A == B r <str> 0 A.lower() r <str> 1 A.upper() r <str> 2 A.swapcase() r <str> 3 A.title() r <str> 4 A.capitalize() r <str> 5 string.capwords(A) r <str> 6 A.strip() - Remove whitespace on both sides of A. r <str> 7 Split A, eval each part. r <seq> 8 Run length encode A. Output format [[3, 'a'], [2, 'b'], [1, 'c'], [1, 'd']]. r <str> 9 Run length decode A. Input format '3a2bcd' -> 'aaabbcd' r <seq> 9 Run length decode A. Input format [[3, 'a'], [2, 'b'], [1, 'c'], [1, 'd']]. r <int> <int> Range, half inclusive. range(A, B) in Python, or range(A, B, -1). r <str> <str> String range. r(C(A), C(B)), then convert each int to string using C. r <int> <seq> r(B, A) s <col(str)> Concatenate. ''.join(A) s <col> reduce on +, base case []. (Pyth +) s <cmp> Real part. A.real in Python. s <num> Floor to int. int(A) in Python. s <str> Parse as int. "" parses to 0. int(A) in Python. t <num> A - 1. t <seq> Tail. A[1:] in Python. u <l:GH> <seq/num> <any> Reduce B from left to right, with function A(_, _) and C as starting value. G, H -> N, T ->. A takes current value, next element of B as inputs. Note that A can ignore either input. u <l:GH> <any> <none> Apply A(_, _) until a result that has occurred before is found. Starting value B. A takes current value, iteration number as inputs. v <str> Eval. eval(A) without -s, ast.literal_eval(A) with -s (online). literal_eval only allows numeric, string, list, etc. literals, no variables or functions. w Take input. Reads up to newline. input() in Python 3. x <int> <int> Bitwise XOR. A ^ B in Python. x <lst> <any> First occurrence. Return the index of the first element of A equal to B, or -1 if none exists. x <str> <str> First occurrence. Return the index of the first substring of A equal to B, or -1 if none exists. x <non-lst> <lst> All occurrences. Returns a list of the indexes of elements of B that equal A. x <str> <non-lst> First occurence. Return the index of the first substring of A equal to str(B), or -1 if none exists. y <seq> Powerset. All subsets of A, ordered by length. y <num> A * 2. ``` [Answer] # C# .NET, ~~76~~ 62 bytes (keywords) ``` n=>"as do if in is for int new out ref ".Substring(0,n*4) ``` [Try it online.](https://tio.run/##NU@7TsNAEOz9FSNXdzhxEokKx2mQqIiElIKGxnbuwkpmL9ztgSKUbzebQIrRvmZndoc0H0J0U07EB@xOSdxH/Uz82QBYLPDSRUHwkHeH/iRO2ZmlGMYuJWx/CiBJJzTcVp8yD2timWk/quQGHu3E7absErAPAHkFK7T2IWouYPeNkAXReZT1Lvd/y2Y547t7OzWF@hxzP6rPv91XoD22HbGxlyOuUuYiRe2qAa3b1VJDVdnrELfzHgOnMLr6NZI4fdMZqsqHNykrb8jaRtnn4jz9Ag) **Old 76 bytes answer:** ``` using System.Linq;n=>"as do if in is for int new out ref".Split(' ').Take(n) ``` [Try it online.](https://tio.run/##RZBNSwMxEIbv@yte9tINW1N7dbu9iIpiQajgxUs2ndXBNKnJrFKkv31N1SIEZpiPZx5i05kNkcYhsX/Bep@Etvqe/XsDYDbDg4mC0ENeCd1eKE8PXgrrTEpYfRVAEiNsT6vXg7cL9jI9FS6Dc2SFg0/6hjxFtvr2yg9biqZztEgS8@XlEj3a0bfL0iRsArgHe3BCH2LOBJ4@EQZBpL7U651jqSaYKP1o3qjyamyK7LIbOpdd/pQ@Am@wMuwrdRTFkVUdWdzOG/CinZ/nUNfqp4l/Y5@CI/0UWSh/BVVclxfPUta/rvouZGQ5RX59xUqpJgMOxWH8Bg) **Explanation:** ``` using System.Linq; // Required import for Take n=> // Method with integer parameter and IEnumerable<string> return-type "as do if in is for int new out ref".Split(' ') // The keywords as string-array, .Take(n) // and return the first `n` items ``` [List of available keywords in C# .NET.](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/) --- # C# .NET, 30 bytes (operators) ``` n=>"+-/*&|^~<>".Substring(0,n) ``` [Try it online.](https://tio.run/##NY09D4IwFEV3fsULg2ktIK5CWUycZGJwMSZQi3kJtqYtJkbxr9f6Nd3k3ptzhE2FNtKLobUW6nsEYF3rUEBzs06es82oRInKJaE3qE4V9MC94lXM0sV89jg8yyrOmrH7ziRPFPVFFDiXsRsC54e7ajxC3aIi9C0B6LUhgQvIlwVgyZd5CMboZ4S/fq2V1YPMdgad3KKSBFm82ruY9QQpLcJ7iib/Ag) [Answer] # [Charm](https://github.com/aearnus/charm), 52 bytes This outputs *all* of the reserved words in Charm. ``` " [ := :: \" " 0 2 copyfrom 3 * substring pstring ``` Since all non-recursive code in Charm is inline-able, this is an anonymous function. Call like this: ``` 4 " [ := :: \" " 0 2 copyfrom 3 * substring pstring ``` (outputs `[ := :: "`, the only four reserved words.) --- Giving this function a name adds 5 bytes: ``` f := " [ := :: \" " 0 2 copyfrom 3 * substring pstring ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~122~~ 120 bytes ``` ({}<((((((((((((((()()){}()){}){}){})())[][]){}())()())[(([][]){}){}()])()())){}())[()()])>){({}<{({}<>)(<>)}{}>[()])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O61kYDFWhqaGpW14IJKAKyo2OjYyGiYPloDQ2oCFgwFiIKURANYsdq2mlWgwwHE3aaGkBcW11rFw2SAgr8/2/5X9cRAA "Brain-Flak – Try It Online") Just doing my part to fill out the example languages. Outputs `()[]<>}{`, popping off the front for numbers less than 8. [Answer] # Unary, ~~6072204020736072426436~~ 378380483266268 bytes ``` +[>+<+++++]>---. (0o12602122222703334) ``` Thank Jo King for 99.999993768646738908474177860631% reducing [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ 49 bytes ``` ->n{%w[do if or in end not for def nil and][0,n]} ``` [Try it online!](https://tio.run/##DctBCoAgEAXQdZ3ib4KCkjpAXURcVDo0EGNIEZGd3Vy@xQvX8iQaUzfJW93aejDBB7DAiYX4E5RpHUF4xyzW6L4V86V6UGroG@XmdUN@kWNZHCDNpsw1/Q "Ruby – Try It Online") Not using any operators (`+`, `|`, etc.). [Answer] # Ruby, ~~71~~ 68 bytes ``` ->n{(?a..'zzz').reject{|x|begin;eval x+'=n';rescue Object;end}[0,n]} ``` Okay, not the shortest approach, but too fun not to post. Programmatically finds all strings of up to three lowercase letters that can't be assigned to. There happen to be exactly 10: `["do", "if", "in", "or", "and", "def", "end", "for", "nil", "not"]`. Edit: Saved 3 bytes thanks to Asone Tuhid. [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes Returns a string, with each individual character being a method name in Japt. ``` ;îC ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=O+5D&input=OA==) `;C` is the lowercase alphabet and `î` repeats it until its length equals the input. [Answer] # [Chicken](https://esolangs.org/wiki/Chicken), 7 bytes ``` chicken ``` Not a serious answer. But it has to be here. [Answer] # [R](https://www.r-project.org/), ~~76~~ ~~62~~ ~~60~~ 57 bytes *12 bytes saved thanks to [MickyT](https://codegolf.stackexchange.com/users/31347/mickyt)* *5 bytes saved thanks to [snoram](https://codegolf.stackexchange.com/users/82025/snoram)* ``` cat(c("if","in",1:0/0,"for",F,T,"NULL","else")[1:scan()]) ``` [Try it online!](https://tio.run/##K/r/PzmxRCNZQykzTUlHKTNPScfQykDfQEcpLb9IScdNJ0RHyS/Uxwcol5pTnKqkGW1oVZycmKehGav539DgPwA "R – Try It Online") There aren't many [Reserved words in R](http://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html) but these are among the shortest to encode. There are only 9 here, but if an input of `10` is given, a missing value `NA` is appended to the end of the list and printed. [Answer] # [Python 2](https://docs.python.org/2/), 64 bytes ``` lambda n:'as if def del for try elif else from pass'.split()[:n] ``` [Try it online!](https://tio.run/##FcoxCsMwDEbhvaf4t9gQCu5o6EnaDi6xWoEiG8lLTu82w1s@Xj/Gt@lt0v05pezvrUDzUhxM2OqZgJph2IEqf6ziFWRtRy/uy9W78AjxkfU1z5HBCiv6qSGtKcV8QTfWAV5BgeP8AQ "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 57 bytes (with operators) ``` lambda n:'as if in is or and def del for not'.split()[:n] ``` [Try it online!](https://tio.run/##FYqxDoQgEAV7v@J1QmJMuJLEL1GLveDebYILARq/HrWYYiaTr/ZP@um8bD3S@Q0E9SNVCEMUUpEKSAPCwQ8R/LimNs41R2nGrl73/kZ5/0L6O4ybnLN@QC6iDTKBjdh@Aw "Python 2 – Try It Online") --- [keywords](https://docs.python.org/2.5/ref/keywords.html) [operators](https://www.tutorialspoint.com/python/python_basic_operators.htm) [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 84 bytes ``` [S S S T S S S S S N _Push_32][S N S _Duplicate][T N S S _Print_as_character][S N S _Duplicate][T N T T _Read_STDIN_as_integer][T T T _Retrieve][S S S T N _Push_1][T S S T _Subtract][S N S _Duplicate][N T S N _If_0_Jump_to_Label_EXIT][S S S T S S T N _Push_9][T N S S Print_as_character][S S S T N _Push_1][T S S T _Subtract][N T S N _If_0_Jump_to_Label_EXIT][S S S T S T S N _Push_10][T N S S _Print_as_character][N S S N _Create_Label_EXIT] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Whitespace only contains three valid 'keywords': spaces, tabs and new-lines. **Explanation in pseudo-code:** ``` Print space Integer i = STDIN as integer - 1 If i is 0: Exit program Else: Print tab i = i - 1 If i is 0: Exit program Else: Print new-line Exit program ``` ### Example runs: **Input: `1`** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSTSSSSSN Push 32 [32] SNS Duplicate top (32) [32,32] TNSS Print as character [32] <space> SNS Duplicate top (32) [32,32] TNTT Read STDIN as integer [32] {32:1} 1 TTT Retrieve [1] {32:1} SSSTN Push 1 [1,1] {32:1} TSST Subtract top two (1-1) [0] {32:1} SNS Duplicate top (0) [0,0] {32:1} NTSN If 0: Jump to Label_EXIT [0] {32:1} NSSN Create Label_EXIT [0] {32:1} error ``` Program stops with an error: No exit defined. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVMBBLiAkJMLzODk4gQBkBQXJ0geKAciwEqBQlxgDRA5uASQBkmA0P//hgA) (with raw spaces, tabs and new-lines only). Outputs a single space. **Input: `2`** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSTSSSSSN Push 32 [32] SNS Duplicate top (32) [32,32] TNSS Print as character [32] <space> SNS Duplicate top (32) [32,32] TNTT Read STDIN as integer [32] {32:2} 2 TTT Retrieve [2] {32:2} SSSTN Push 1 [2,1] {32:2} TSST Subtract top two (2-1) [1] {32:2} SNS Duplicate top (1) [1,1] {32:2} NTSN If 0: Jump to Label_EXIT [1] {32:2} SSSTSSTN Push 9 [1,9] {32:2} TNSS Print as character [1] {32:2} \t SSSTN Push 1 [1,1] {32:2} TSST Subtract top two (1-1) [0] {32:2} NTSN If 0: Jump to Label_EXIT [] {32:2} NSSN Create Label_EXIT [] {32:2} error ``` Program stops with an error: No exit defined. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVMBBLiAkJMLzODk4gQBkBQXJ0geKAciwEqBQlxgDRA5uASQBkmA0P//RgA) (with raw spaces, tabs and new-lines only). Outputs a space, followed by a tab. **Input: `3` (or higher)** ``` Command Explanation Stack Heap STDIN STDOUT STDERR SSSTSSSSSN Push 32 [32] SNS Duplicate top (32) [32,32] TNSS Print as character [32] <space> SNS Duplicate top (32) [32,32] TNTT Read STDIN as integer [32] {32:3} 3 TTT Retrieve [3] {32:3} SSSTN Push 1 [3,1] {32:3} TSST Subtract top two (3-1) [2] {32:3} SNS Duplicate top (2) [2,2] {32:3} NTSN If 0: Jump to Label_EXIT [2] {32:3} SSSTSSTN Push 9 [2,9] {32:3} TNSS Print as character [2] {32:3} \t SSSTN Push 1 [2,1] {32:3} TSST Subtract top two (2-1) [1] {32:3} SSSTSTSN Push 10 [1,10] {32:3} TNSS Print as character [1] {32:3} \n NSSN Create Label_EXIT [] {32:3} error ``` Program stops with an error: No exit defined. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgVMBBLiAkJMLzODk4gQBkBQXJ0geKAciwEqBQlxgDRA5uASQBkmA0P//JgA) (with raw spaces, tabs and new-lines only). Outputs a space, followed by a tab, followed by a new-line. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 118 bytes ``` ({}<(((((((((((()()()()()){}){}){})())(([][][])){}{}())()())([][][])[]{})()())[][][][][])()())>){({}<({}<>)<>>[()])}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O61kYDCWjCoGZ1LRQB2Roa0bEgCBKtrgUJgEWhgtGxYFVAEYgAWBDMt9OsBlsAxHaaNnZ20RqasZpA9v//JgA "Brain-Flak – Try It Online") ``` # Push stuffs under the counter ({}<(((((((((((()()()()()){}){}){})())(([][][])){}{}())()())([][][])[]{})()())[][][][][])()())>) # While True { # Decrement the counter ({}< # Toggle a character ({}<>)<> >[()]) } # Display alternate stack <> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` A£ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f8dDi//8tAA "05AB1E – Try It Online") --- Every letter of the alphabet is a command in 05AB1E. All this does is prints the first `N` letters of the alphabet. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~11 10~~ 9 bytes ``` 1-:n:0=?; ``` [Try it online!](https://tio.run/##S8sszvj/31DXKs/KwNbe@v///7plhgYA "><> – Try It Online") Turned out the simplest solution was the best. This outputs the first n numbers, starting from 0. ### Old 10 byte solutions ``` "'r{$[>o<3 ``` [Try it online!](https://tio.run/##S8sszvj/X0m9qFol2i7fxvj///@6ZYYGAA "><> – Try It Online") Some 10 byte alternatives: * `"':1+{[>o<` * `"r:n[~>o<a` * `"'a{[>o<bc` [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` (`take`"';,=\"@\\`|~") ``` [Try it online!](https://tio.run/##FcmxCsIwFAXQX7kEoQo22FkCgqudHBsxgSYYmr5X0tdBEH894lnPy69TyLmmeeEiuDJJ4ax7Jj@ibcGU39jWMCIRZp@oRrN34qfgVHM@Gqsu1rrPVx3qf2EQufRPDJ3W3emBHZZN7lJuBI1Yfw "Haskell – Try It Online") Thanks to @Angs for catching keyword errors. I felt like this could be shorter by generating the string instead of explicitly defining it, but I couldn't find a range of 10 consecutive ASCII characters that are Haskell keywords (I found some that are close, if you count language extension keywords). If there is one, you could reduce it to 15 bytes with this, replacing `%` with the starting character: ``` (`take`['%'..]) ``` --- Without symbolic keywords: # [Haskell](https://www.haskell.org/), 58 bytes ``` (`take`words"of in do let then else case data type class") ``` [Try it online!](https://tio.run/##HYwxCoNAEEWv8pEUSeESD2CVNlYpQ4hDdhbFdUZ2R4Kn32iax398eAPliWMs47xoMtxULGl0nQp51DVU4oY1s8comGmUEtpzbzRx/9Xkc6XheLwissEGFnDMjA/t8GQE25ZdI@VcXcpRQIugqXvj2TjXXF84YVntYekucFjl391XKD8 "Haskell – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~62~~ 60 bytes -2 thanks to GPS ``` f(n){puts("autocasecharelseenumgotolongvoidint do"+40-4*n);} ``` [Try it online!](https://tio.run/##FchBCsMgEEDRdT2FZDVWAilkZ3sYmagdSGZK1GxCzm7N6n0@jgmxtQhszl8tGQZfi6DPAb9@D2sOgeuWpMgqnA6hhbjoRQY7T@P8ZOOudp/NE4NRp3pE2eE@pD/65Trv7tTDWqMjkHHqan8 "C (gcc) – Try It Online") I mean... there was never any requirement to actually separate the keywords. In case I misread - or you're more interested in something more in the spirit of the question - here's an alternate version with separating spaces: # [C (gcc)](https://gcc.gnu.org/), 69 bytes ``` f(n){puts("auto case char else enum goto long void int do"+50-5*n);} ``` [Try it online!](https://tio.run/##FYkxDoQgFAXr5RQvVrDExC2s2D0MQUAS/X@jYGM8O2I1kxnXR@dqDZLU@S95l50tmeHs7uFmu8EvzTyVFZHbWJgiDk4TEmVg4k6PQz@@SZmrPmm1iaQSp3gF3uRTEn74mIZv49BEa4UgkzLiqjc "C (gcc) – Try It Online") [Answer] # [Tcl](http://tcl.tk/), 37 bytes ``` puts [lrange [info commands] 1 $argv] ``` [Try it online!](https://tio.run/##K0nO@f@/oLSkWCE6pygxLz1VITozLy1fITk/NzcxL6U4VsFQQSWxKL0s9v///4YGAA "Tcl – Try It Online") [Answer] # Taxi, 509 bytes ``` "[]a lrnsew" is waiting at Writer's Depot. Go to Post Office: w 1 l 1 r 1 l. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: s 1 l 1 r.Pickup a passenger going to The Underground.Go to Writer's Depot: n 1 l, 1 l, 2 l.Pickup a passenger going to Chop Suey.Go to Chop Suey: n, 3 r, 3 r.[a]Pickup a passenger going to Post Office.Go to Post Office: s 1 r 1 l 2 r 1 l.Go to The Underground: n 1 r 1 l.Pickup a passenger going to The Underground.Go to Chop Suey: n 2 r 1 l.Switch to plan "a". ``` This takes a hardcoded string at the top, and prints "n" characters from it, and then errors with "error: no outgoing passengers found". The string contains: 1. `[` and `]`, the characters used to declare a plan 2. `a` used in the "Pickup a passenger ..." syntax. 3. The space character, which is required to separate pieces of syntax 4. `l` and `r`, short for "left" and "right", used to tell the driver which way to turn. 5. `n`, `s`, `e`, and `w`, the four directions. I believe all of those count as one character keywords. Ungolfed: ``` "[]a lrnsew" is waiting at Writer's Depot. Go to Post Office: west, 1st left, 1st right, 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: south, 1st left, 1st right. Pickup a passenger going to The Underground. Go to Writer's Depot: north, 1st left, 1st left, 2nd left. Pickup a passenger going to Chop Suey. Go to Chop Suey: north, 3rd right, 3rd right. [print character] Pickup a passenger going to Post Office. Go to Post Office: south, 1st right, 1st left, 2nd right, 1st left. Go to The Underground: north, 1st right, 1st left. Pickup a passenger going to The Underground. Go to Chop Suey: north, 2nd right, 1st left. Switch to plan "print character". ``` [Answer] # [J](http://jsoftware.com/), 15 bytes ``` [:u:46,"0~65+i. ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/6OtSq1MzHSUDOrMTLUz9f5rcqUmZ@QrpCkYwhkG/wE "J – Try It Online") Gives an array of strings `A.` to `J.`. Dotted words in J act as built-ins (such as `a.` or `A.`) or control structures (such as `if.` or `do.`), or simply throw spelling error. None of them can be used as identifiers. ## Less interesting, 15 bytes ``` {.&'!#$%^*-+=|' ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/6v11NQVlVVU47R0tW1r1P9rcqUmZ@QrpCkYwhkG/wE "J – Try It Online") Gives some of the 10 one-byte verbs. [Answer] ## [Bash](https://www.gnu.org/software/bash/) and shell utils 20 bytes ``` compgen -b|head -$1 ``` You can save that in a file with execute permissions (builtins) and run it under bash like this: ``` $ ./builtins 5 . : [ alias bg ``` Outputs the first N bash built ins. If you are running some shell other than bash, you will need the shebang #!/bin/bash line at the start of the file, for +12b [Answer] # QBasic, 60 bytes ``` INPUT n ?LEFT$("CLS FOR DEF RUN DIM PUT GET SUB END IF",n*4) ``` This answer fits the spirit of the question best, I believe: outputting alphabetic reserved keywords with spaces in between. I don't think symbolic operators really count as "words" in QBasic, but for completeness, here's a **30-byte answer** using operators: ``` INPUT n ?LEFT$("+-*/\^=><?",n) ``` ]
[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/41833/edit). Closed 2 years ago. [Improve this question](/posts/41833/edit) You have to take 2 string inputs and output the sum of these two strings **without** converting them to int or using any numeric data type. ex. ``` string one = "123"; string two = "456"; string sum = "579"; ``` Assume the strings won't be larger than 10 digits. This is code golf and shortest answer in characters wins. An edit to the answer in C# will make me smile :). Edit: Converting to int can be defined as anything of this nature `Int.TryParse`, `(int)`, `Convert.ToInt` etc [Answer] # 80836 Assembly (~~57~~ 53 bytes) ``` 53 55 89 E5 8B 4D 0C 8B 55 10 B0 0A 30 DB 88 CF 00 C1 00 C2 49 4A 8A 01 8A 22 00 E0 00 D8 2C 30 30 DB 3C 39 7E 04 B3 01 2C 0A 88 01 88 22 38 CF 75 E2 5D 5B C3 ``` This adds, digit by digit, right to left, without converting ascii digits `'0'-'9'` to the integers `0-9`, and carrying over as needed. The bytecode is the code for a function, which may be called in C (see below). The above bytecode was written by hand, from the following assembly (NASM-style, commented): ``` ; save ebx, ebp push ebx ; 53 push ebp ; 55 ; copy esp mov ebp, esp ; 8B EC ; load arguments mov ecx, [ebp+0x0C] ; 8B 4D 0C mov edx, [ebp+0x10] ; 8B 55 10 ; initialize stuff mov al, 10 ; B0 0A xor bl, bl ; 30 DB mov bh, cl ; 88 CF ; send edx, ecx to end of string add cl, al ; 00 C1 add dl, al ; 00 C2 ; decrement everything dec ecx ; 49 dec edx ; 4A ; get rightmost unprocessed digit of each number mov al, [ecx] ; 8A 01 mov ah, [edx] ; 8A 22 ; add two ascii digits add al, ah ; 00 E0 ; add carry if needed add al, bl ; 00 D8 ; subtract 0x30 ('0') to get the resulting ascii digit sub al, 0x30 ; 2C 30 ; set bl to 0 xor bl, bl ; 30 DB ; if greater than '9': must carry over to next place cmp al, 0x39 ; 3C 39 jle $+6 ; 7E 04 ; set bl to 1 if carrying over mov bl, 1 ; B3 01 ; subtract 10 from ascii digit if carrying over sub al, 0x0A ; 2C 0A mov [ecx], al ; 88 01 mov [edx], ah ; 88 22 ; check if loop has ended cmp bh, cl ; 38 CF jne $-28 ; 75 E2 ; restore ebx, ebp pop ebp ; 5D pop ebx ; 5B ; return ret ; C3 ``` To try this in C (gcc, linux, intel processor): ``` #include <stdio.h> #include <string.h> #include <sys/mman.h> int main(){ // bytecode from earlier char code[] = { 0x53, 0x55, 0x8B, 0xEC, 0x8B, 0x4D, 0x0C, 0x8B, 0x55, 0x10, 0x31, 0xC0, 0xB0, 0x09, 0x30, 0xDB, 0x01, 0xC1, 0x01, 0xC2, 0x40, 0x50, 0x8A, 0x01, 0x8A, 0x22, 0x00, 0xE0, 0x00, 0xD8, 0x2C, 0x30, 0x30, 0xDB, 0x3C, 0x39, 0x7E, 0x04, 0xB3, 0x01, 0x2C, 0x0A, 0x88, 0x01, 0x88, 0x22, 0x58, 0x48, 0x49, 0x4A, 0x85, 0xC0, 0x75, 0xDF, 0x5D, 0x5B, 0xC3, }; // allocate executable memory to a function pointer called 'add' void __attribute__( (__cdecl__) ) (*add)(char*,char*) = mmap(0,sizeof code,PROT_WRITE|PROT_EXEC,MAP_ANON|MAP_PRIVATE,-1,0); memcpy(add, code, sizeof code); // test inputs char number1[] = "0878295272", number2[] = "8184206821"; puts(number1); puts(number2); // call the bytecode as a c function add(number1, number2); // output is in the first argument puts(number1); // release allocated memory munmap(add, sizeof code); return 0; } ``` [Answer] # Ruby, 109 71 Cheesy. If you can't bring Mohammad to the mountain.... ``` j=$* r=n=d=0 (d+=x=j.count{|v|n.to_s==v} r+=x*n n+=1)until d>1 p r.to_s ``` Algorithm: 1. Compare an int's string representation to input 1 and input 2. 2. Add that int to the result per match. 3. Increment and repeat until you've done it twice. 4. Vomit on yourself **Changelog** 71 shorter as an array. 85 removed method declaration and consolidate calls to `n.to_s` 92 applied [some tips](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby) 101 save a char 102 use x for incrementing 109 initial commit [Answer] # sed, 359 bytes (without the fancy formatting) I'm still not sure if this is a dup of [Add without addition (or any of the 4 basic arithmetic operators)](https://codegolf.stackexchange.com/questions/20996/add-without-addition-or-any-of-the-4-basic-arithmetic-operators). In the meantime, let me cross post my answer for that question. It's not going to win any golfing, but its a start, and I think easily meets the spec: ``` s/([^ ]+) ([^ ]+)/\1:0::\2:/ :d /^([^:]+):\1::([^:]+):/tx s/(:[^:]*)9([_:])/\1_\2/g;td s/(:[^:]*)8(_*:)/\19\2/g;s/(:[^:]*)7(_*:)/\18\2/g;s/(:[^:]*)6(_*:)/\17\2/g s/(:[^:]*)5(_*:)/\16\2/g;s/(:[^:]*)4(_*:)/\15\2/g;s/(:[^:]*)3(_*:)/\14\2/g s/(:[^:]*)2(_*:)/\13\2/g;s/(:[^:]*)1(_*:)/\12\2/g;s/(:[^:]*)0(_*:)/\11\2/g s/:(_+:)/:1\1/g; y/_/0/; # # bd; :x s/.*::([^:]+):/\1/; # # # # # # # # # # # # # # ``` Input is taken from STDIN in the form "x y". That is first transformed to "x:0::y:". Then we increment all numbers that come after ":" characters, until we get "x:x::(x+y):". Then we finally return (x+y). # Output ``` $ printf "%s\n" "0 0" "0 1" "1 0" "9 999" "999 9" "12345 67890" "123 1000000000000000000000" | sed -rf add.sed 0 1 1 1008 1008 80235 1000000000000000000123 $ ``` Note that this only works for the natural numbers. However (in theory at least) it works for arbitrarily large integers. Because we are doing x increment operations on y, ordering can make a big difference to speed: x < y will be faster than x > y. [Answer] # Ruby - ~~485~~ ~~432~~ 265 This seems more in the spirit of what you were looking for in the question. It basically solves the problem how a human would on paper -- by "memorizing" all single digit addition results, adding each column, and understanding how to "carry the one" when necessary. This is also using one "numeric data type" (variable i), which is prohibited by the question, but its only for string indexing. I'll try removing this and edit my answer. ``` def s p (y=(?0..?9).to_a).product(y).map{|x|/#{x.join}/}.zip((?0..'18').to_a.each_cons(10).to_a.flatten).each{|k,v|return v if k=~p.sort.join} end a,b=$*.map{|n|n.rjust(10,?0).reverse} r=?0 c='' (0..9).each{|i|d=s [a[i],b[i]] c=s([d[-1],r])+c r=d[-2]||?0} puts r+c ``` Somewhat ungolfed: ``` def s p y = (?0..?9).to_a y.product(y).map{ |x| /#{x.join}/ }.zip( (?0..'18').to_a.each_cons(10).to_a.flatten ).each{ |k,v| return v if k =~ p.sort.join } end a,b=$*.map{ |n| n.rjust(10,?0).reverse } r = ?0 c = '' (0..9).each { |i| d = s [ a[i], b[i] ] c = s([ d[-1], r ]) + c r = d[-2] || '0' } puts r+c ``` EDIT: Used some ideas from the comments to generate the "memorized" mapping table instead of just hardcoding it. [Answer] # CJam, ~~95 92 80 72 70~~ [44](https://mothereff.in/byte-counter#%22%C7%BA%E1%A8%8C%E2%B9%9D%E7%80%B6%E5%99%84%E9%A0%BC%E0%AD%85%E7%B1%8C%E2%97%B3%E0%A5%B6%E9%A8%A5%E7%AE%84%EF%87%AF%EB%8D%AE%E5%BA%B8%E5%8C%95%E5%B8%AF%E6%A8%99%E1%9E%AD%E2%B9%9E%EF%A1%AE%E2%9E%BB%E4%97%A7%E3%A9%B1%E7%A0%A1%E0%A3%8D%EF%8E%A2%E3%A4%AC%E9%86%BB%E5%AD%B9%EA%BD%AC%222G%23b127b%3Ac%7E) characters ``` "Ǻᨌ⹝瀶噄頼୅籌◳ॶ騥箄덮庸匕帯標ឭ⹞➻䗧㩱砡࣍㤬醻孹꽬"2G#b127b:c~ ``` which translates to ``` lW%'0A*+S/zW%{{A,__m*{_1b\saa*~}%\{_saa*~}%+\aa/,(s_,({(@+\}*}%_Wf<s}g ``` This can definitely be golfed a lot. I really don't know if my approach is optimal or not yet. *UPDATE* - Inline the sum matrix creation to save bytes. Due to this, the program now runs 10 times slower, but still a constant time for any kind of input. [Try it online here](http://cjam.aditsu.net/) Reads the line containing two numbers from STDIN as string and outputs as a array of characters which is a string itself. For example: ``` 123 4567 ``` The output contains preceding `0`. Let me know if that is an issue. [Answer] ## C# - ~~128~~ ~~108~~ 104 Thanks to Compass, BMac and Shawn for suggesting improvements. First try at Code Golf, and using C# seems to be a handicap here... By using `.Compute()` you can use the string values and sum them directly. As a bonus this works for other operators aside from just "+". Golfed: ``` static void t(string a,string b){System.Console.Write(new System.Data.DataTable().Compute(a+"+"+b,""));} ``` Ungolfed: ``` static void t(string a, string b) { System.Console.Write(new System.Data.DataTable().Compute(a+"+"+b,"")); } ``` Calling `t("123","456");` gets you 579. [Answer] # GNU sed, 266 bytes Uses a different approach than DigitalTrauma's solution. As an effect, this one performs even poorer, using *O(m+n)*. Convert both operands to unary, concatenate, convert back to decimal (all using regex of course—sed doesn't have the *concept* of an integer). As a bonus, this program sums up *all* the natural integers given on stdin (in the first line), meaning you can feed it nothing, one number or ten numbers and it'll do the right thing regardless. The idea behind this code is vaguely inspired by an old PPCG sed submission of mine, though I don't remember for what question it is an answer. Here it is, "pretty"-printed for your "convenience", to borrow another idea from DigitalTrauma. :D ``` s/9/x8/g; s/8/x7/g; s/7/x6/g; s/6/x5/g; s/5/x4/g; s/4/x3/g; s/3/x2/g;s/2/x1/g;s/1/x0/g;s/0\b//g;; :l;s/x0/0xxxxxxxxxx/;/x0/bl;s/[^x]//g s/^$/0/;:m;s/x{10}/!/g;s/!\b/&0/;;;;; s/0x/1/;s/1x/2/;s/2x/3/;s/3x/4/;;;;;; s/4x/5/;s/5x/6/;s/6x/7/;s/7x/8/;;;;;; s/8x/9/;; s/!/x/g;; /x{10}/bm /x/!q;;;; s/^/0/;bm #sum.sed# ``` (To obtain the 266-byte version, remove trailing semicolons, leading whitespace and the final comment, preferably using sed.) Borrowing some tests from DigitalTrauma: ``` % printf "%s\n" "0 0" "0 1" "1 0" "9 999" "999 9" "12345 6789" "123 100" | while read l; do sed -rf /tmp/sum.sed <<<"$l"; done 0 1 1 1008 1008 19134 223 ``` I tweaked the really large tests a bit because of the terrible space (in)efficiency. Due to the use of `q` only the first line is processed, hence the `while` loop in the test. [Answer] # Java 6 (181 characters) Not to be outdone by the [handicap known as C#](https://codegolf.stackexchange.com/a/41842/32114), Java in all its glory. So much boilerplate! Usage is providing the arguments separated by a space, i.e. `123 456` ``` import javax.script.*;class T {public static void main(String[] a) throws Exception {System.out.print(new ScriptEngineManager().getEngineByName("JavaScript").eval(a[0]+"+"+a[1]));}} ``` Ungolfed: ``` import javax.script.*; class T { public static void main(String[] a) throws Exception { System.out.print(new ScriptEngineManager() .getEngineByName("JavaScript").eval(a[0] + "+" + a[1])); } } ``` By using the JavaScript engine available in `javax`, we can make another language do the work for us, and technically follow the rules of not using any numeric types in the native language, or converting. ### Justification for using `eval` We have not converted the values to int for JavaScript to eval. We've created a String that is `"123+456"` which is not a number. JS Engine digests the formula and evaluates the String as number literals, which are not numeric data types. Java cheesy logic! As an aside, this also works for `double` math. [Answer] ## APL (61) I *think* this falls within the rules. ``` {⎕D[1+{∨/T←9<Z←0,⍵:∇T↓⍨~×⊃T←(1⌽T)+Z-10×T⋄⍵}+⌿⌽↑⌽¨¯1+⎕D∘⍳¨⍺⍵]} ``` This is a function that takes two string arguments, and returns a string: ``` '123'{⎕D[1+{∨/T←9<Z←0,⍵:∇T↓⍨~×⊃T←(1⌽T)+Z-10×T⋄⍵}+⌿⌽↑⌽¨¯1+⎕D∘⍳¨⍺⍵]}'456' 579 ⍝ show dimensions (if it was a number, this would give the empty list) ⍴'123'{⎕D[1+{∨/T←9<Z←0,⍵:∇T↓⍨~×⊃T←(1⌽T)+Z-10×T⋄⍵}+⌿⌽↑⌽¨¯1+⎕D∘⍳¨⍺⍵]}'456' 3 ``` It's reasonably fast too, it adds the number formed by 999999 `9`s to itself in an instant. It finds the index of each character in `⎕D` (which is the string '0123456789'), then does grade school addition on each index separately, carrying as needed, then looks up the resulting digits in `⎕D`. (I think the `⎕D` lookup falls within the rules, it's basically just doing `'x'-48`). Explanation: * `⎕D∘⍳¨⍺⍵`: look up the indices in `⎕D` for each character in both strings. * `¯1+`: subtract `1` from each, because the arrays are 1-based by default. * `⌽↑⌽¨`: reverse both, turn into a matrix (filling empty squares with zeroes), then reverse the matrix. * `+⌿`: sum the columns of the matrix * `{`...`}`: carry over: + `∨/T←9<Z←0,⍵`: add an extra `0` in front of the list. Find out which 'digits' are higher than 9, and store this in `T`. If any digits were higher than 10: - `Z-10×T`: subtract `10` from each position that is higher than 10, - `T←(1⌽T)+`: add `1` to each position next to each position that was higher than 10, and store in `T`. - `T↓⍨~×⊃T`: if `T` starts with a zero, remove it, - `∇`: apply the carry function to the result. + `⋄⍵`: otherwise, return the value unchanged * `1+`: add one to each position (because the array is 1-indexed) * `⎕D[`...`]`: use the result as indices into `⎕D`. [Answer] # Perl - ~~136~~ ~~119~~ 115 bytes I'm learning Perl, this seemed like good practice. Tips are appreciated! Cheesy answer, to get that out of the way: ``` print$ARGV[0]+$ARGV[1]; #Adding strings ``` Actual answer: ``` ($x,$y)=@ARGV;while($x.$y.$s){$s-=48-ord$&if$x=~s/.$//;$s-=48-ord$&if$y=~s/.$//;$r=chr($s%10+48).$r;$s=$s>9;}print$r; ``` Uncompressed: ``` ($x,$y)=@ARGV; while($x.$y.$s){ $s-=48-ord$&if$x=~s/.$//; $s-=48-ord$&if$y=~s/.$//; $r=chr($s%10+48).$r; $s=$s>9; } print$r; ``` [Answer] # Java 7, Score = 252 Uses no integers, longs, bytes, shorts, doubles, floats, or any built in library functions for adding. Wrap in a class body and call with `t(String1,String2)`. Please pad strings with 0's so that they have equal length. `t("123","234")` returns `"0357"`. Golfed: ``` char c,d,e,f,g,k;String t(String a,String b){g++;char[]h=a.toCharArray(),i=b.toCharArray(),j=new char[h.length + 1];for(d=(char)h.length;d>f;)j[--d+1]=(c=(e=(char)(h[d]+i[d]-'0'+c))>'9'?g:f)==g?(char)(e-'\n'):e;j[0]=(char)('0'+c);return new String(j);} ``` Golfed Expanded with class: ``` public class T{ public static void main(String[] args){ System.out.println(new T().t(args[0],args[1])); } char c,d,e,f,g,k; String t(String a,String b){ g++; char[]h=a.toCharArray(),i=b.toCharArray(),j=new char[h.length + 1]; for(d=(char)h.length;d>f;) j[--d+1]=(c=(e=(char)(h[d]+i[d]-'0'+c))>'9'?g:f)==g?(char)(e-'\n'):e; j[0]=(char)('0'+c); return new String(j); } } ``` Partially golfed expanded: ``` public class TrickSum{ public static void main(String[] args){ System.out.println(new TrickSum().trickSum(args[0], args[1])); } char carry, i, aSum,nullChar,oneChar; public String trickSum(String a, String b){ oneChar++; char[] number1 = toCharArray(a), number2 = toCharArray(b), sum = new char[number1.length + 1]; for (i = (char) number1.length; i > nullChar;) sum[--i + 1] = (carry = (aSum = (char) (number1[i] + number2[i] - '0' + carry)) > '9' ? oneChar : nullChar) == oneChar ? (char) (aSum - '\n') : aSum; sum[0] = (char)('0' + carry); return new String(sum); } char[] toCharArray(String string){ return string.toCharArray(); } } ``` 100% Expanded: ``` public class TrickSum{ public static void main(String[] args){ System.out.println(trickSum(args[0], args[1])); } public static String trickSum(String a, String b){ char[] number1 = a.toCharArray(); char[] number2 = b.toCharArray(); char[] sum = new char[number1.length + 1]; char carry = '\u0000'; for (char i = (char)(number1.length - 1); i != '\uFFFF'; i--){ char aSum = (char) (number1[i] + number2[i] - '0' + carry); carry = aSum > '9' ? '\u0001' : '\u0000'; aSum = (carry == '\u0001') ? (char) (aSum - '\n') : aSum; sum[i + 1] = aSum; } sum[0] = (char)('0' + carry); return new String(sum); } } ``` [Answer] # Java - 257 Characters as everyone knows java there is no better language for golfing than java ``` class A{public static void main(String[]s){char[]a=s[0].toCharArray();char[]b=s[1].toCharArray();int c=a.length;int d=b.length;int e=0;String f="";for(int i=0;i<Math.max(c,d);i++){f=f+(((i<c?a[i]-48:0)+(i<d?b[i]-48:0)+e)%10);e/=10;}System.out.println(f);}} ``` this is ungolfed solution ``` public static void main(String[] args) { char[] aa = args[0].toCharArray(); char[] bb = args[1].toCharArray(); int aal = aa.length; int bbl = bb.length; int reminder = 0; String result =""; for(int i=0;i<Math.max(aal,bbl);i++){ result=result+(((i<aal?aa[i]-48:0)+(i<bbl?bb[i]-48:0)+reminder)%10); reminder/=10; } System.out.println(result); } ``` [Answer] # Haskell - 98 94 bytes ``` main=do a<-getLine b<-getLine let c d=last$takeWhile(\e->d/=(show$e-1))[0..] print$c a+c b ``` [Answer] # JavaScript (ES6), ~~55 66~~ 59\* ``` f=x=>{for(i=0;i+[]!=x;i++);return i};f((p=prompt)())+f(p()) ``` \*This makes a few assumptions: * We're in an ES6 REPL environment (ex. FireFox 33.1 browser console) * Performance does not matter (seriously, '9999999999','9999999999' took about 20 minutes to return) * Converting from Integer to String is allowed * ~~Input is defined in variables a and b, ex: `var a='123',b=321';`~~ Changed to getting input from prompt (+11). * Input has no leading zeros. [Answer] ## Python 2.7, 196 137 chars version 2 (shorter by initialising the dictionary with code): ``` n={} for i in range(10):n[`i`]=i*' ' def q(a,b):f=lambda x:''.join([10**p*n[s] for p,s in enumerate(reversed(x))]);return len(f(a)+f(b)) ``` Previous version 1 (196 chars): ``` def q(a,b):n,f={0:'','1':' ','2':' ','3':' ','4':4*' ','5':5*' ','6':6*' ','7':7*' ','8':8*' ','9':9*' '}, lambda x:''.join( [10**p*n[s] for p,s in enumerate(reversed(x))]);return len(f(a)+f(b)) ``` e.g. ``` >>> print q('123','111') 234 ``` The dictionary keys are strings, the dictionary values only include number constants to shorten the code, and the calculation is done by concatenating two strings and getting the resulting length, so I hope it counts as "not converting them to ints". ## Python small-print rule-cheat version ``` class z(int):0 def s(a,b): return z(a)+z(b) ``` Note: ``` >>> type(z('4')) <class '__main__.z'> ``` Type *z* is a custom type I define as: *definitely not a numeric type by whatever definition the questioner uses, but behaves close enough to a numeric type to be useful in limited circumstances*. Type *z* behaviours are only partially implemented in this code sample, and if the CPython interpreter uses 'int' to implement *z*, that's an merely an implementation detail and not related to the problem at hand. ]
[Question] [ Most of us are probably familiar with the concept of triangular and square numbers. However, there are also pentagonal numbers, hexagonal numbers, septagonal numbers, octagonal numbers, etc. The Nth Nagonal number is defined as the Nth number of the sequence formed with a polygon of N sides. Obviously, N >= 3, as there are no 2 or 1 sided closed shapes. The first few Nth Ngonal numbers are 0, 1, 2, 6, 16, 35, 66, 112, 176, 261, 370, 506, 672, 871.... This is sequence [A060354](http://oeis.org/A060354) in the OEIS. ## Your Task: Write a program or function that, when given an integer n as input, outputs/returns the Nth Nagonal number. ## Input: An integer N between 3 and 10^6. ## Output: The Nth Nagonal number where N is the input. ## Test Case: ``` 25 -> 6925 35 -> 19670 40 -> 29680 ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # [Neim](https://github.com/okx-code/Neim), 1 byte ``` ℙ ``` ¯\\_(ツ)\_/¯ [Try it online!](https://tio.run/##y0vNzP3//1HLzP//jUwB "Neim – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes Saved 1 byte thanks to *Neil* ``` <ÐP+>; ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f5vCEAG076///TQwA "05AB1E – Try It Online") **Explanation** ``` < # push input-1 Ð # triplicate P # product of stack + # add input > # increment ; # divide by 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` c3×3+ ``` [Try it online!](https://tio.run/##y0rNyan8/z/Z@PB0Y@3///@bGAAA "Jelly – Try It Online") Computes [choose(n, 3)](https://en.wikipedia.org/wiki/Binomial_coefficient) × 3 + n. This translates quite readily to 05AB1E: # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` 3c3*+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fONlYS/v/fxMDAA "05AB1E – Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 6 bytes ``` t3^+he ``` [Try it here!](https://pyke.catbus.co.uk/?code=t3%5E%2Bhe&input=35&warnings=0&hex=0) ``` t - Decrement. 3^ - Raise to the power of 3. + - Add the input. h - Increment. e - Floor Halve. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~9~~ 8 bytes ``` ´U+³ z Ä ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=tFUrsyB6IMQ=&input=MzU=) * 1 byte saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions) --- ## Explanation Decrement (`´`) the input (`U`), add the input cubed (`³`) to that, floor divide by 2 (`z`) and add 1 (`Ä`). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~34~~ 28 bytes ``` param($n)$n*($n*$n-3*$n+4)/2 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPUyVPC0hpqeTpGgMJbRNNfaP///@bGAAA "PowerShell – Try It Online") Closed-form solution golfed from the OEIS page. Used FOIL for another 6 byte savings. [Answer] # [Python 2](https://docs.python.org/2/), 23 bytes ``` lambda n:(~-n)**3-~n>>1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSqNON09TS8tYty7Pzs7wf0FRZl6JQpqGkammgq2tgoKZpZGpDoTPBZMzhsgZWpqZG@hA@HA5EwOwnJGlmQVYDsj/DwA "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` t3Xn3*+ ``` Luis Mendo's suggestion, which is a little clearer. ``` (implicit input) t duplicate 3Xn n choose 3 3* multiply by 3 + add (implicit output) ``` [Try it online!](https://tio.run/##y00syfn/v8Q4Is9YS/v/f1MA "MATL – Try It Online") ``` t:3XNn+ ``` [Try it online!](https://tio.run/##y00syfn/v8TKOMIvT/v/f1MA "MATL – Try It Online") Both solutions port [Lynn's algorithm](https://codegolf.stackexchange.com/a/145012/67312) ``` (implicit input) t duplicate : range (1...n) 3XN push 3, compute all 3-combinations of the range n number ( equal to 3*choose(n,3) ) + add (implicit output) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~25~~ 24 bytes * Saved one byte thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil); golfed `>>1` to `/2`. ``` lambda n:n*(n*n-3*n+4)/2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk9LI08rT9dYK0/bRFPf6H9BUWZeiUKahpGppoKtrYKCmaWRKRdM0BgiaGhpZm4AFzQxAAsaWZpZGPwHAA "Python 2 – Try It Online") [Answer] # [Recursiva](https://github.com/officialaimm/recursiva), 11 bytes ``` *Ha+-Sa*3a4 ``` [Try it online!](https://tio.run/##K0pNLi0qzixL/P9fyyNRWzc4Ucs40eT/fxMDAA "Recursiva – Try It Online") [Answer] ## JavaScript (ES6), 38 bytes ``` f=(n,k=n)=>k<2|n<3?k:f(n-1,k)+f(3,k-1) ``` Recursion FTW (or maybe only for seventh...) [Answer] # Mathematica, 14 bytes shorter than built-in!!! ``` (#^2-3#+4)#/2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X0M5zkjXWFnbRFNZ30jtf0BRZl6JgkN6tIlB7P//AA "Wolfram Language (Mathematica) – Try It Online") and 3 bytes shorter with Martin Ender's help [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~20~~ 17 bytes Saved 3 bytes porting [Emigna's answer](https://codegolf.stackexchange.com/a/144992/67312). ``` Iu(:^\:**p+u@O,2) ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9@zVMMqLsZKS6tAu9TBX8dI8/9/I1MA "Cubix – Try It Online") ``` I u ( : ^ \ : * * p + u @ O , 2 ) . . . . . . . ``` ### original answer: ``` Iu-2^\:*p*qu@O,2+p*: ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9@zVNcoLsZKq0CrsNTBX8dIu0DL6v9/I1MA "Cubix – Try It Online") Expands to the cube ``` I u - 2 ^ \ : * p * q u @ O , 2 + p * : . . . . ``` which implements the `(n*(n-2)^2+n^2)/2` approach. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes ``` DƤ ``` [Try it online!](https://tio.run/##y8/INfr/3@Vw26El//8bm/4HAA "Ohm v2 – Try It Online") [Answer] # Mathematica, 20 bytes ``` #~PolygonalNumber~#& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` +*3.cQ3 ``` **[Try it here!](https://pyth.herokuapp.com/?code=%2B%2a3.cQ3&input=35&debug=0)** Uses [Lynn's algorithm](https://codegolf.stackexchange.com/a/145012/59487). [Answer] # dc, 13 bytes ``` dd2-2^*r2^+2/ ``` A fairly straightforward implementation of the first formula listed on the [OEIS page](http://oeis.org/A060354). ``` # Commands # Stack Tracker (tm) # Begin with input # n d # n n d # n n n 2- # n-2 n n 2^ # (n-2)^2 n n * # n*(n-2)^2 n r # n n*(n-2)^2 2^ # n^2 n*(n-2)^2 + # n*(n-2)^2+n^2 2/ # (n*(n-2)^2+n^2)/2 # matches first formula # End with output on stack ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` à3 *3+U ``` **[Try it here!](https://ethproductions.github.io/japt/?v=1.4.5&code=4DMgKjMrVQ==&input=MzU=)** First, it was a comment on Shaggy's answer, but they told me I should post it myself. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ÅU ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cGvo//9GpgA "05AB1E – Try It Online") ### How? ¯\\_(ツ)\_/¯ [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes ``` {x*(((x*x)-(3*x))+4)%2} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0NLQ0KjQqtDU1TAGkpraJpqqRrVcXGnqioaGAIf0B3U=) Having to add parenthesis because K parses from right-to-left. [Answer] # [HOPS](https://akc.is/hops/), 17 bytes ``` {n*(n*n-3*n+4)/2} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2ZgVLsgqWlJWm6Fhur87Q08rTydI218rRNNPWNaiHiUOkFUBoA) Using the generating function given on OEIS by [R. J. Mathar](https://oeis.org/wiki/User:R._J._Mathar): # [HOPS](https://akc.is/hops/), 23 bytes ``` x*(1-2*x+4*x^2)/(1-x)^4 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2ZgVLsgqWlJWm6FtsrtDQMdY20KrRNtCrijDT1gbwKzTgTiCxU0QIoDQA) Or using the exponential generating function given on OEIS by [Paul Barry](https://oeis.org/wiki/User:Paul_Barry): # [HOPS](https://akc.is/hops/), 24 bytes ``` (exp(x)*(x+x^3/2)).*{n!} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2ZgVLsgqWlJWm6Fjs0UisKNCo0tTQqtCvijPWNNDX1tKrzFGsh0lBVC6A0AA) -3 bytes thanks to alephalpha [Answer] # [cQuents 0](https://github.com/stestoltz/cQuents/tree/cquents-0), 16 bytes ``` #|1:A(AA-3A+4)/2 ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nG0MpRw9FR19hR20RT3@j/fyNTAA "cQuents 0 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ’*3+‘H ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw0wtY@1HDTM8/v//b2QKAA "Jelly – Try It Online") Uses Emigna's algorithm inspired by Neil. [Answer] # Java 8, 18 bytes ``` n->n*(n*n-3*n+4)/2 ``` [Try it here.](https://tio.run/##hU/LDoIwELzzFXtsMVQDeDL6B3LhaDzUUk2RLoQWjDF8e13QO8k@MruzM9lajjJpO4119Qyqkc7BWRr8RAAGve7vUmkoZrgMQLG5Ij/QZKKkKADhCAGTE8YMY0yyGDc536bhENG6G26NUeC89NTG1lRgyYGVvjf4uFxB8p/87AuWpFC/FsAWF4Dy7by2oh286OjGN8isQKFYuudrlGydku/4/50pfAE) The approach used by most other answers is the shortest in Java. For funsies I also ported two other answers: Port of [Mr. Xcoder's Python 2 answer](https://codegolf.stackexchange.com/a/145002/52210) (**29 bytes**): ``` n->(int)Math.pow(n-1,3)-~n>>1 ``` [Try it here.](https://tio.run/##hU/NDoIwDL7zFD1uiSwieiLyBnDhaDzMMXXIuoUNiDH46jjQu0l/8rVf@7UNH3hsrMSmfsyi5c5BwRW@IgCFXnZXLiSUC1wLIMgSkWahMgUPVgLCEWaM86VHC@7vzJqRYJxsUhq/Mc@TOYsC0/aXVglwnvuQBqNq0EGMVL5TeDudgdOv0nIC6LAV5bgCsgoCVE/npWam98yGGd8i0QyZILsD/UdJ/1P2W/r7bJo/) Port of [Lynn's Jelly answer](https://codegolf.stackexchange.com/a/145012/52210) (with manual calculation of `a choose b`) (**76 bytes**): ``` n->c(n,3)*3+nint c(int t,int c){return t<c?0:c==t|c==0?1:c(--t,c-1)+c(t,c);} ``` [Try it here.](https://tio.run/##hVDLboNADLzzFXPcbVhCSnsJpfmCcsmx6mHjbFpS8CIwqaI0304XWqnHSH6MrbE19tGerPGt4@P@c6Ta9j1ebMWXCKhYXHew5FBO5dwAqSmyzkPnGjxYCUaBkc0zKY4zfZctOMoDf7lE6QWt7QT@APlw2J3FGfIDS/S/TeIZ60vnZOgY8kSbdE1FId8hpJvVmpQxEpNZ6QWpAHR@HYF22NUVoRcrIZ18tUcTtKutdBW/v77B6l/h00Vogkh2X3OhZv3A9tyLaxI/SNKGGalZNQknpO4f9S1KdpvykOq/R13HHw) ]
[Question] [ Given two real numbers (postive or negative) in the limits of float pointing number data types, i.e., (\$-3.4e38\$ to \$3.4e38\$) not inclusive, you should output the max of the two reversed numbers. --- ## TEST CASES ## Example ## Input: ``` 135 210 ``` ## Output: ``` 531 ``` \$531\$ is \$135\$ reversed, which is greater than \$012\$, i.e., \$210\$ reversed. --- Negative numbers are allowed: ## Example 2 ## Input: ``` -135 -210 ``` ## Output: ``` -012 ``` \$-012\$ is \$-210\$ reversed, which is greater than \$-531\$, i.e., \$-135\$ reversed. --- Real numbers are allowed: ## Example 3 ## Input: ``` 13.5 10 ``` ## Output: ``` 5.31 ``` \$5.31\$ is \$13.5\$ reversed, which is greater than \$01\$, i.e., \$10\$ reversed. --- ## Example 4 ## Input: ``` -1112313.5 -312.5671 ``` ## Output: ``` -5.3132111 ``` \$-5.3132111\$ is \$-1112313.5\$ reversed (it reverses the number but is still negative, which is greater than \$-1765.213\$, i.e., \$-312.5671\$ reversed. --- ## Example 5 ## Input: ``` 0.0000001 0 ``` ## Output: ``` 1000000.0 ``` \$1000000.0\$ is \$0.0000001\$ reversed, which is greater than \$0\$, i.e., still \$0\$ reversed. --- ## Example 6 ## Input: ``` 121 121 ``` ## Output: ``` 121 ``` Both numbers are equal and are palindrome. Either one is correct. --- # Rules * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/20634) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. --- ## Good Luck! [Answer] # [Wren](https://github.com/munificent/wren), ~~126~~ 124 bytes As always Wren is the longest. I hate Wren's verbosity. ``` Fn.new{|a|a.map{|i|i>0?"":"-"+(i.abs.toString[-1..-(i.abs.toString.count)])}.map{|i|Num.fromString(i)}.reduce{|x,y|x<y?x:y}} ``` [Try it online!](https://tio.run/##XY6xDsIgFEV/xTBBLC@txqWxdnN06Wg6IFJDUsBQsCWl3441xsX1nOTcO1qh04vZTec1r9JZgxbjHFlkoNhzjjLKU14jVCKKtlgCuw3gTOOs1I8rLQDoHwRuvHakJcsvcPEKOmvU12O5Givunos5TlmI0zHUUxmWJTVhcELBaKUT@PMHOOt7vM7sDxndFXlLSHoD) ## Explanation ``` Fn.new{ // new anonymous function |a| // with the parameter a a.map{|i| // for each item in this parameter (i>0)?"":"-" // The sign of each item. If the item is larger than 0, return the null string, otherwise return a negative sign. +( ) // Append this with the following string: i.abs // The absolute value of i .toString // Convert this value to a string [-1..-(i.abs.toString.count)] // Reverse this string Num.fromString( ) // convert this to a number from a string }.reduce{|x,y|x<y?x:y}} // Find the minimum value of the list ``` [Answer] # [Perl 5](https://www.perl.org/), 51 bytes: ``` sub f{($x,$y)=map{/-?/;$&.reverse$'}@_;$x>$y?$x:$y} ``` [Try it online!](https://tio.run/##LY1Ba4NAEIXv@yuGMLQK7mZnF1PQahrotbfclxQmVDBUXNMq4m@36zYPBua9j3nTcd/m6@rvn3CdExwznNLqdunmvTzuS3xSPf9w7xmflzdX4ljjdMSxwGlZ757hzH4oio/vnmEIq6/qQyl@v5qWk9f30/lUp7OAoNv0350hp5Xv2mYoY974BK6PtxkgZ7DDEXCCqg5ul5ZiEc5tTc4JsjkY0pBbEnIzcnNSkwlI5bAhFRmRsTGSlozKDy8EckPWBCS00lEEOtxEKS3IEDxm/QM "Perl 5 – Try It Online") ...or if using a function from a core module is allowed (`max` in `List::Util`) it's 35 bytes: # 35 bytes: ``` sub f{max map{/-?/;$&.reverse$'}@_} ``` [Try it online!](https://tio.run/##LYxRa4MwFIXf8ysuJUwFk@YmpIM63Qp73N7a59BBygLKxNhNEX@7S7IduHDO@Ti3t0Ort7u38Ob8eDxeRtdC1l2nrNr8/QNuS/DQXftlz573FX3gg/22g7c0W1/MmpZnG5fvX4OFMVhfN4eK/Hy61uZPr6fzqSkWAkHdnNOppHNJbVH7vnVjlXrnc7j9oaIEakvY0QnoDHUT0q6oyEqMiZ@MIag0SBSgFRIWA4uJCZQBcQ0R8cQQpUoVUyi5PjwisIiUDIgILpIQRNgkcUFQIvzf9gs "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~6~~ ~~7~~ 6 bytes +1 byte to fix cases when only one of the inputs is negative. -1 byte by Grimmy ``` í'-δ†Z ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Fp13XNbHjUsiPr/P1pJ19DQ0MjY0FjPVElHydjQSM/UzNxQKRYA "05AB1E – Try It Online") [Test all inputs](https://tio.run/##yy9OTMpM/V9W6fL/8Fp13XNbHjUsiPpfaa@k8KhtkoKSvc7/6GglQ2NTJR0lI0MDpVidaCVdCFcXxjc01gPx4bKGhkbGUDFdY0MjPVMzc0OwlIGeARgYAmWgWo1AbBCJoRWhMxYA "05AB1E – Try It Online") The input is taken as a list of strings [x, y]. Explanation: ``` í Reverse each input '- Push a minus sign δ† Apply "filter out the minus sign to the front" to each input Z Take the maximum ``` [Answer] # [Zsh](https://www.zsh.org/), 63 bytes ``` for x;a+=(${(M)x#-}${(j::)${(Oas::)x#-}}) <<<$a[1+$[a[1]<a[2]]] ``` [Try it online!](https://tio.run/##LYpBCsMgEEX3nkKoC4egOCM2kNojlB5AXLiR0k2h2YSEnN2OSQfmz/uPWedXqxp0q5@vXG5luGu16QcsF7MzvKcJ@DzLzNDdDiLGqErCQSXOHEuinHMDIapEHyShYzIdzcnobZB/i0j@6MYj2XAdkbWz7hyUxz9h3/YD "Zsh – Try It Online") `${x#-}` removes the leading `-` if it exists. Adding the `(M)` flag causes the `-` to be substituted instead of what remains. Then this construct reverses the remaining string: `${(j::)${(Oas::)var}}`. For each element, we append to an array, then use a comparison to index into the array. [Answer] # JavaScript (ES6), 100 bytes Takes input as `(a)(b)`. ``` a=>b=>Math.max((g=n=>(s=n>0||-1)*[...(s*n).toFixed(9).replace(/\.0+$/,0)].reverse().join``)(a),g(b)) ``` [Try it online!](https://tio.run/##bY6xcsIwDIZ3noKhg0SxYtmXch2csVufoOUOE0waLthcnOMYeIDOfcS@SDAwJaBBg/R9v7SzRxvLtj50woeN67emt6ZYm@LTdj@0tyeAynhTQDS@kOezYJx9ERHEmUfqwkd9cht4R2rdobGlg@yb5OtLNpe4TLOja6MDpF2o/WqFYHFewRqxL4OPoXHUhAq2wDpHUCwRp4PKsmmueTKExY0WD3iChWQ1GUdTop9H05NsZqXvjtCsKH9bcFIT/f/7dxW0SsjIkiRvxQiDO8ni@4bk@C2V4Gt7fCtN@ws "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 69 bytes ``` lambda*v:max(map(lambda x:(-1)**(z:=eval(x)<0)*float(x[z:][::-1]),v)) ``` An unnamed function accepting 2 (actually, any number of) strings, which yields the maximal reversed version as a floating point number. **[Try it online!](https://tio.run/##RYzJCsIwGITvPkVuWUhK/oSqBOuLxBxStCh0CaWU2JePXazOZZhvhgnv4dm1@hz6VBW3VPumvHs2msZH0vhANoCiIQIoY2QyxWP0NYn0Iimr6s4PJNrJOGuMAEf5SGmquh55XqJXi6zFoHPMEVYgsePIYvEF4kdAZyv5LwCU3qnQoLL8eIKtlJlcBUu3H6g1LeacOaBZoX@1AyGeo5IuJ9d5UG2Rpg8 "Python 3.8 – Try It Online")** [Answer] # [Python 3](https://docs.python.org/3/), ~~89~~ 86 bytes ~~Disclaimer: This answer does not work for the second example #4 due to floating point accuracy constraints in Python. Feel free to disqualify.~~ Update: This answer now works for all examples thanks to @JonathanAllan ``` f=float r=lambda a:-f(a[:1:-1])if eval(a)<0else f(a[::-1]) m=lambda a,b:max(r(a),r(b)) ``` [Try it online!](https://tio.run/##ZY5BCsMgEEX3OYU7FaI4SlqQ5iSliwmNNKBJsKG0p7dR2kDT2Qz892b482u5TaNJybXOT7hUsfUYuisStMIxPFuwAi58cKR/oGfIT6r3954UVlAVtpO6swGfLK5aHVnHeZrjMC4sMAqmoTWhGhTlvNpi8cnFHoCRBfz5ANp8oTCgZXM4wo@jpMoD2dg91SXMa@32Bg "Python 3 – Try It Online") [Answer] # [Red](http://www.red-lang.org), 74 bytes ``` func[a][forall a[a/1:(sign? a/1)* do reverse to""absolute a/1]max a/1 a/2] ``` [Try it online!](https://tio.run/##XYvBCgIhGITv@xQ/e6pgt37Fgr30Dl3Fg@VvLJiGutHbm3aI6jDM8M1MJFNOZKTq7FTs4i9SK2lD1M6BlnqL0yrNV3@EGtcbMAEiPSgmghz6Xp9TcEum1qqbfjavYqrc4@wzWJDIBTDcqe5DhoaGX4Z8FPC3QmT8zQeObBT7A34fGEKVKi8 "Red – Try It Online") Takes the input as a list of two numbers. The 5th test case (0.0000001 0) doesn't work in TIO, but works fine in the Red console: [![enter image description here](https://i.stack.imgur.com/jorUQ.png)](https://i.stack.imgur.com/jorUQ.png) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 64 bytes ``` a=>b=>(R=([h,...t])=>h?h+1<0?h+R(t):R(t)+h:t)(a)>+R(b)?R(a):R(b) ``` [Try it online!](https://tio.run/##bU7BboMwDL3nK3wjUYkVB7FJdKGn/QDXrlIpDYOJAYJsmjTt21nC4DZL9rP9/Gy/lZ/lXE3t6GQ/3O1Sm6U0@c3kvDD83MSI6C7C5M2pOdCT8rHgTmQhHJrMCV6K3Ldu4lT4NAvZ4uzsqnK2YODKKElBk4I0ISZDIUMlFWlPYQqBwpUj0snakglpTB8eCWSgEu0pplCtRqC8ZjVUjDTB5uzK9sPopvadC5zHrnU8eukjgfUwPZdVw7u294/l8M0AqqGfHZzbfvxwFMOKOgb7NdrKXfz7YXjfApE4bpqhs9gNr/x/4Y5gjIF6GxJ/qIVf8iOOyy8 "JavaScript (Node.js) – Try It Online") Input / output as strings. [Answer] # [PHP](https://php.net/), 56 bytes ``` fn($a)=>max(array_map(fn($n)=>strrev($n)*($n>0?:-1),$a)) ``` [Try it online!](https://tio.run/##VZDBasMwDIbveQoRArFHYqyEdtAu7TvsmoUiGptcmhg7lI2SZ89sk7JVB1v69P9CthnM@nE2g0mSTDerHllGvDnd6JuRtfRzuZFhgY6eutladQ/5mz9O8nwokRfewNej98/KzQ4aaBPw0eZY7/IC8gpl3hUbKzdYvlCsRaSvSsSqfnbKGiux27/jn0AKGQND//@wKpJwedb5zfRkFV0HYNuK5CBmHB7Ro67DBP5xF0M9Sz/VXVmnevCfAJOG7BG0rewWoLF/ltgth7SAveQgINNsGygg/RrTY7Ksvw "PHP – Try It Online") Input is an array of two string numbers, example: `['123', '25.5']`. Simply reverses both numbers as strings, then returns the max of them as numbers. To handle reversed negative numbers, the `*($n>0?:-1)` part is used which multiplies the reversed number by `1` if the original number was more than zero, else multiplies it by `-1`. In PHP if you try to convert a string which starts with numeric values to a number, it will take the numeric part and ignore the rest. For example `'321-'` converted to a number will be `321` and the multiply operation automatically forces this numeric conversion. [Answer] # APL+WIN, 32 bytes Prompts for a nested string of the two numbers. ``` ⌈/⍎¨(n↑¨'¯'),¨⌽¨(n←'¯'=↑¨m)↓¨m←⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/6unQf9Tbd2iFRt6jtomHVqgfWq@uqXNoxaOevRCxCSARW7BcruajtslACigINOU/UP//NC51Q2NTdQV1I0MDdS4g79B6CP/QepiIobEeSAAhb2hoZAwVPLTe2NBIz9TM3BAsaaBnAAaGQCmoZiMQG0RyAQA "APL (Dyalog Classic) – Try It Online") [Answer] # [R](https://www.r-project.org/), 82 bytes ``` options(scipen=99);b=sign(a<-scan());max(b*as.numeric(stringi::stri_reverse(b*a))) ``` [Try it online!](https://tio.run/##HcoxCoAwDEDRqzgmglLHqj2L1BJKhkZJVLx9pf7pDV9rPc6LDzGwxCdJ8B6XPRhngbgOlqIA4lLiC3sfbZS7kHICu5Ql8zw3bEoPqVFbELG60f1Nnasf "R – Try It Online") Input is taken as two numbers. Setting scipen=99 is needed to deal with more than a few decimals. [Answer] # [Ruby](https://www.ruby-lang.org/), 51 bytes ``` ->*a{a.map{|w|(w<=>0)*"#{w.abs}".reverse.to_f}.max} ``` [Try it online!](https://tio.run/##VcpBCsIwEAXQvacodaPFDP0Tqhvbi0iRFJKdWJLWKGnOHoMK6vbx7Dw8kmmT6CoVFF3UGBa/bPyx7eptVa6DJzW4WJLVN22dpul6NjG/e0zjPLnCnCCbXcGo@9UHxEvEL0FSpr8DsHyzkGBq9gd8OyNvRp@e "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g -N`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ®®w}'-Ãn@Y-X ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWcgLU4&code=rq53fSctw25AWS1Y&input=WyIwIiwiMC4wMDAwMDAwMSJd) Thanks to @Arnauld for spotting an error ``` Takes input as array of strings U.m // for each element (function(Z) { return Z.m // split on '-' (function(Z) { return Z.w() // reverse and convert to number }, "-") }) // rejoins .n(function(X, Y, Z) { return Y - X }) // sort in descending order Flag -gn to output first element obtained Flag -N to output it as a number (remove leading 0s) ``` [Answer] # [**Haskell**](https://www.haskell.org/), 70 bytes ``` f a b=max(g a)(g b) g('-':x)=(0-).h$x g xs=h xs h=read @Float .reverse ``` [Try it here](https://repl.it/@tyler1/DistinctStableLaboratory) or if Haskell language pragma aren't allowed (like TypeApplications) # **77 bytes** ``` f a b=max(g a)(g b) g('-':x)=(0-).h$x g xs=h xs h=read.reverse::String->Float ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~28~~ 27 bytes *-1 byte thanks to Jo King* ``` &max o**.&{.abs.flip*.sign} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfLTexQiFfS0tPrVovMalYLy0ns0BLrzgzPa/2vzVXcWKlQpqGSrymQlp@EZeNobGpgpGhgZ0Ol40uiK0L5Rga65kqwMQNDY2MwQK6xoZGeqZm5oYgcQM9AzAwVDCw@w8A "Perl 6 – Try It Online") [Answer] # APL(NARS), 17 chars, 34 bytes ``` {⌈/(⍎¨⌽¨⍕¨∣⍵)××⍵} ``` test: ``` f←{⌈/(⍎¨⌽¨⍕¨∣⍵)××⍵} f 135 210 531 f ¯135 ¯210 ¯12 f 13.5 10 5.31 f ¯1112313.5 ¯312.5671 ¯5.3132111 f 0.0000001 0 SYNTAX ERROR f 0.000001 0 100000 f 121 121 121 f 121 ¯3 6 0.0001 9 1000 ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg) `-hd` ~~53~~ ~~41~~ ~~35~~ ~~34~~ ~~27~~ 11 bytes (SBCS) ``` (2|¿⑶&)@MMƒ ``` *-16 bytes with new reverse t.o.s function* ## Answer History ### 27 bytes ``` (2|᠀÷^:\-=[_^\-^]⅀&)ℝ$ℝ@MMƒ ``` -7 bytes due to using the new built-in function library which will be soon populated with helpful functions. `MM` is the maximum function, and returns the maximum of the two items passed to it. ## 34 bytes ``` (2|᠀÷^:\-=[_^\-^]⅍⅀&)ℝ$ℝ:&^:^<[&|^ ``` [Try it online!](https://tio.run/##y05N//9fw6jm4YKGw9vjrGJ0baPj42J042IftfY@am1Q03zUMlcFiK3U4qzibKLVauL@/7ew5DIy@a@bkQIA "Keg – Try It Online") -1 byte due to using `⅍` ## 35 bytes ``` (2|᠀÷^:\-=[_^\-]^``⅀&)ℝ$ℝ:&^:^<[&|^ ``` Hey, so, uh, Keg has flags now. `-hd` prints only the top item if nothing has been printed. Also, summate command works as expected now. The github interpreter works, but not TIO yet. ## 41 bytes ``` (2|᠀÷^:`-`=[_^`-`^]``∑+)&)ℝ$ℝ:&^:^<[&|^]. ``` [Try it online!](https://tio.run/##y05N//9fw6jm4YKGw9vjrBJ0E2yj4@OAVFysQkLCo46J2ppqmo9a5qoAsZVanFWcTbRaTVys3v//hkaGXEAMAA "Keg – Try It Online") -12 bytes due to not using functions ## 53 bytes ``` @m2|:&^:^<[&|^]ƒ(2|᠀÷^:`-`=[_^`-`^] ``(!;|+)&)ℝ$ℝ@mƒ. ``` [Try it online!](https://tio.run/##y05N///fIdeoxkotzirOJlqtJi722CQNo5qHCxoOb4@zStBNsI2OjwNScbEKCQkaitY12ppqmo9a5qoAsUPusUl6//8bGhlyATEA "Keg – Try It Online") I dont even know where to begin when explaining this, but it works. I know I could remove the need for a function, but I'm on my phone, so I'll do it later. I would have used the summate command, but there's a bug with it. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` I⌈E²I⪫E⪪S-⮌λ- ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2gY6SiAxbzyM/PAAsEFOZklGp55BaUlwSVAPekamjoKSrpKQDIotSy1qDhVI0cTKgQG1v//6xoaGhoZGxrrmXLpGhsa6ZmamRv@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ² Literal `2` E Map over implicit range S Input string ⪪ - Split on `-`s E Map over substrings λ Current substring ⮌ Reversed ⪫ - Join with `-`s I Cast to number ⌈ Maximum I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ḟ€”-UV×VṠ$Ṁ ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmPmtY8apirGxp2eHrYw50LVB7ubPifBRTRsX7UMEdB104ByLY@3M71cPeWYqPD7UDlkf//KykpGRqbchkZGnDpghi6IJahsZ4pF1jE0NDIGMzTNTY00jM1MzfkMtAzAAMgi8vQyBCEgYYAAA "Jelly – Try It Online") A monadic link taking a list of two strings and returning the maximum reversed number as a float or integer depending on the input. ## Explanation ``` ḟ€”- | Filter out “-“ from each U | Reverse each V | Evaluate as Jelly code × $ | Multiply by following as a monad: V | - Evaluate as Jelly code Ṡ | - Sign Ṁ | Max ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 40 bytes ``` rev|sed 's/\(.*\)-/-\1/'|sort -n|tail -1 ``` [Try it online!](https://tio.run/##S0oszvj/vyi1rKY4NUVBvVg/RkNPK0ZTV183xlBfvaY4v6hEQTevpiQxM0dB1/D/f11DY1MuXSNDAy4A "Bash – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 104 bytes ``` r n=read((\s->if head s=='-'then"-"++reverse(drop 1 s)else reverse s)$show n)::Float f a b=max(r a)(r b) ``` [Try it online!](https://tio.run/##PYrRCoIwFIbve4ofEdzQiUexQFiXvUR1MWmiNKdsUr29zYoOnPPzfefvlb9rY9bVwUqn1Y2xixfHoUMfAF7KRCRLr20kojR1@qGd1@zmphkEz7XxGj8bMPb99ITlTXMyk1p2HRRaOaoXc1A8nJavoxosJGY32AUxzh2oqlFSkaEDEwF4iMB8E1TlNf4/orLazNaoqMzr/YG@tZK2vUKIQEVefIZQZOsb "Haskell – Try It Online") The `0.0000001 0` test case doesn't work though, I think there's an error on `read`. Typing could also be improved when the input is type `Int` for example [Answer] # [Gaia](https://github.com/splcurran/Gaia), 11 bytes ``` ⟨v'-%v$⟩¦d⌠ ``` This is a function which accepts a list of two numbers as strings and leaves the result on the stack. OP wasn't clear about whether leading 0's or 0 decimals need to be included, but the program should be equally long either way. This function does not include these 0's: ``` ⟨v'-%v$d⟩¦⌉ ``` [Try it online!](https://tio.run/##S0/MTPz//9H8FWXquqplKo/mrzy0LOVRz4L/qY/aJv6PftQwR9fQ2PRRw1wFENPI0ADIjAUA "Gaia – Try It Online") ``` ⟨ ⟩¦ Map this block over the list: v Reverse the string '-% Split it around -'s, leaving the separators in the result v Reverse the splitting $ Rejoin it d⌠ Return the element of the list which gives the highest value when parsed as a number ``` ]
[Question] [ # Introduction [`cowsay`](https://en.wikipedia.org/wiki/Cowsay) is a Unix command made by Tony Monroe, written in Perl. It outputs a picture of a cow saying given text. For example: ``` ________________________ < Typical cowsay output! > ------------------------ \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ``` # Challenge Given a multiline string as input, output a cow saying the inputted string. The output is made like so: * Start with one space * Append the length of the longest line of the input plus \$2\$ underscores * Append a newline * Append a `<` if the input is a single line, else append a `/` * Append a space * Append the first line of input * Append the length of the longest line, minus the length of the current line, plus \$1\$, spaces * Append a `>` if the input is a single line, else append a `\` * Append a newline * While there are still lines left in the input: + Append a `\` if this is the last line, else append a `|` + Append a space + Append the current line of input + Append the length of the longest line, minus the length of the current line, plus \$1\$, spaces + Append a `/` if this is the last line, else append a `|` + Append a newline * Append a space * Append the length of the longest line of the input plus \$2\$ hyphens * Append a newline * Append the cow and speech bubble line: ``` \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ``` # Test cases ``` Input ...becomes... Output ==================== Typical cowsay output! ...becomes... ________________________ < Typical cowsay output! > ------------------------ \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ==================== Two Lines ...becomes... _______ / Two \ \ Lines / ------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ==================== This is the first line of input. This is the second line. It is the longest, so the bubble should stretch to fit it. This is the third line. Hello world! (;;"''{<<['" Empty lines shouldn't cause any problems. ...becomes... _____________________________________________________________________________________ / This is the first line of input. \ | This is the second line. It is the longest, so the bubble should stretch to fit it. | | This is the third line. | | Hello world! | | (;;"''{<<['" | | | | | | | \ Empty lines shouldn't cause any problems. / ------------------------------------------------------------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || || ``` # Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Any amount of trailing whitespace is allowed on any line. Trailing newlines are also allowed. * If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on. * Please explain your answer. This is not necessary, but it makes it easier for others to understand. * Languages newer than the question are allowed. This means you could create your own language where it would be trivial to do this, but don't expect any upvotes. * You may assume only printable ASCII is given as input. * Please, don't submit `cowsay` in Bash. It's boring and you'll lose rep quickly. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! # [Reference implementation](https://tio.run/##lVNNT@MwEL37VwxcxiZtStkbbfa20u6dG4aobVxi4diR7apE2//etZ1Q@oG0MFIUz5t5783ko@18bfSP/X5tTQOucyCb1lgPzldSk5XZFohIoA8erueyfH7PI0CNYbzs44CHoGXJ@HBmfML5cTHGbjcOsYXdZWG4kWitpBauSOPkViwqynLXKukpco2MKKNfhPOFEpo2izea2kevoosIY2S5WS6VKBAwwxJv6NCf3bEsChC5hkhNNFYU0/s0Tc/KCpwjEcqJM3SC5HAOwon8ePuUheTgMD7IhgrLpux/Vj8/teL8yCsO3D@PXnh6/0S2tVQCUt5TP7e5EI3Ah99JeYenM3x9xS/6T75lH7eOwPnmx/Ph@OTdktZK7enQEb5itt8/1DJ83Q58LWAtrfNJEMwapG43PifHDU6sjK5SRw5//Ds8OIzAmZT3BuBqs1FV@Ges8KsavAkGgXOm6WtpB0nyWyhlYGusqq4Inc2uEf/O5494TUL8alrf9esO0ho9rBYbJ2ChO2itCa6Ny/8B "Python 3 – Try It Online") # Note The cow is one space too close to the left, but I've kept it this way so people don't need to update their answers. But I will accept the correct version. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 95 bytes ``` ≔⌈E⪪θ¶⁺²LιηP×_ηM↙EI⁺²Xχ№θ¶§|/\<Iι η‖BOηM⁷¦¹↘²M²↗”{‴JCεχ(J7WS⊙u#←L⌈η‽=Ykc8¿№➙Q⎚⊗\`ê:VI✂e≡8s”J¹¦¹θ ``` [Try it online!](https://tio.run/##XU/BTuMwEL3nKwZf6kihS7kgtb0Au9KCQFtB90SWKE2d2pJjB3vcUm3/PUxcAognS54Zv3nvuZKlq2ypu@7Se7Ux/L58VU1o6G75Y6sV8pcMWG5YmsFCB8/PM7gTZoOSq5SQgUxnyX3QqFqnDPKlaoTnrGD9S/9kt4JPf9qduRM10mARab3@demRD6ILuxOOT84yuLbBfNpGj0u8MWvxytnhR57PSTquxgCDIAP2UfeRHkStRYVXAVG4Wu//bIXTZCqHTBcZTD42YsAHtZGYwfnAoFTTv22cfto8F8Vzbri1aZ4XR1BbFNTCEVRRytz09eFwStjBYWjhePVZb0PTLi2ffM3xks667okxtpTKAx2UAmrlPIJWRoCtQZk24Dj5SvCismYdGWO4wWGsrdkITz/yNvarsFppYksb9Bo8OoGVBLRkQDvfNFEq9y6Z/BZaW9hZp9cnCZ/N2Gj0fz5/GrGE8KtpcR@J/l3ajBCqMngBpdlD6yy5Nn5Mv/rXnW71Gw "Charcoal – Try It Online") Link is to verbose version of code. Note that multiline input with empty lines is an awkward input format for Charcoal, so you'll have to use Pythonic format. Explanation: ``` ≔⌈E⪪θ¶⁺²Lιη ``` Find out the length of the longest line in the text. ``` P×_ηM↙ ``` Print the top row of underscores, then move down and left so that the next output appears to the left of the underscores. ``` EI⁺²Xχ№θ¶§|/\<Iι ``` Print the left-hand side of the speech bubble. Each row is coded according to whether it is the first (+1) or last (+2) row, with a row that is both first and last therefore having a value of 3, which is then indexed to find the appropriate character. ``` η ``` Print the row of dashes aligned with the underscores. ``` ‖BOη ``` Reflect the left side to complete the speech bubble. ``` M⁷¦¹↘²M²↗ ``` Print the diagonal line joining the speech bubble to the cow. ``` ”{‴JCεχ(J7WS⊙u#←L⌈η‽=Ykc8¿№➙Q⎚⊗\`ê:VI✂e≡8s” ``` Print the cow as a compressed string. ``` J¹¦¹θ ``` Jump back to the bubble to print the input text. [Answer] # [Python 2](https://docs.python.org/2/), 249 bytes *-1 byte thanks to @ovs* *-3 bytes thanks to @Jonathan Allan* A relatively straight-forward implementation. One thing to note is that the cow contains a lot of spaces, which allows us to save a couple bytes by using `replace`. ``` s=input().split('\n') m=max(map(len,s))+2 l=len(s)-2 z=-l*'<>'or'/\\'+'||'*l+'\/' print'','_'*m for c in s+['-'*m,'''? \ ^__^ ? \ (oo)\_______ ?? (__)\? )\/\\ ???||----w | ???||?||'''.replace('?',' '*5)]:print z[:1],c.ljust(m-2),z[1:2];z=z[2:] ``` [Try it online!](https://tio.run/##XVFNj5swEL3zK2a5DE6AVZB6IaGcKrVSj7nhLCLEKa6MjWwjFsp/T6dkK1Udz2HefLynGQ@z74zOHlMnlYBDDuJdtGDDMHy4Quph9BFL3aCkj5BrZEFf9M171DdDpISOHWP7LFAFxZFjSRYsRaJ2ePqMxuIr57jHdcWd2iN/xWCwUnvEGGvc9cHdWGhBanD7ChPKxIhYAgeAt7p@C0oKCETGMF4/LShLiOqacaoxTvyUKNc1IZtgfQJy4kmtGFTTighL0gPcfWKXfNOHpcoPl7hN1c/R@ahPMhYv1SHPLselWKosvzz@bI/neZBto6A1k2tmMKOnY7xggOfJcP1dauEIIJ476YDcdwLu0joPimpg7rCdL@X63w4nWqNvW0sK3/zftDL6h3A@Bmc2fB2vV/oP15lR3cB5K3zbgTekQDP/k/pO2g9Orr8KpQxMxqrbC9fR8Rgi/jqdKgy5fr4v/eDnrd19KGj00DajE9DoGQZrSLx3KW33Gw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~116~~ ~~112~~ 105 bytes -7 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` .BDgi„><€S`ëDgÍ'|и'\š'/ªÂ}Š)ø¬Jg'_×ð욬¤'-:ª•˜©ã€õĆWõ½*¸cÀΓý¼oº₁%<Yë;Gá“•" \^_ (o)/|-w"ÅвJ¶¡•–ãö•28вjÅ\«» ``` [Try it online!](https://tio.run/##XY/PSgJRFMb38xS3gbgaOUKryKFFGJXbgogkc8ZxZmKcK3PvIJLBJNiulYs2Eqlt0lmEoEjl5p5cBeEzzItMFzGIDmdx/vy@73AILWq2EcfKXta0o@BxV42a4fElDLMm3OPGYorz8y5O8wE0b@ZPSZjyMGfiAjzAK4TzLg/5M07t8EEU9L46/AX6Qg7jz7tTGPPZBp/qEHy3YcY/CH@Lmrfr6hkMMwfQjYKOkMgof1GQEiSZbqRqMrQWoxyfcLHsRUEb@jAR1db2YnQFrTwf8vc4lmX5xLIpEsksA5VtjzLk2K6BSBnZbtVnivQXoIZO3NKSUNAR@x07xDUNyjYRJcte8zXNEbRFfKeEKPMMpluIEXFAaP55Msv2VpbSoeE4BNWI55TWpEQmI2N8rarnWJZE7FeqrL4E6craxQzpRZ8aqOjWUdUj4mqFKuKrHw "05AB1E – Try It Online") **Speech bubble:** ``` # add sides: .B # Squarify: split input by newlines and pad each line to the same length with spaces Dg # duplicate the list and get the number of lines i # if this equals 1: „><€S` # push [">"] and ["<"] # stack layout: ["Single line"], [">"], ["<"] ë # else (more than one line of input): DgÍ # number of lines - 2 '|и # repeat "|" this many times in a list '\š'/ª # prepend "\" and append "/" # the list is now ["\", "|", ..., "|", "/"]  # keep this list and push the reverse # stack layout: ["multi-line", ..., "input"], ["\", "|", ..., "|", "/"], ["/", "|", ..., "|", "\"] # add top and bottom: Š)ø # triple-swap, wrap stack into a list and transpose to assemble the lines ¬Jg # get the length of the first complete line (without the spaces) '_× # create a string of this many "_" ðì # prepend a space š¬ # prepend this string to the list of lines ¤'-: # push another copy of the "_" string and replace "_" with "-" ª # append to the list of lines ``` **Cow:** ``` •˜...á“•" \^_\n(o)/|-w"ÅвJ # base-compressed cow without leading spaces •–ãö•28в # compressed list of line lengths: [15, 23, 27, 24, 24] jÅ\ # pad each line to desired length with spaces in the front «» # concatenate the cow lines to the other lines and join the lines by newlines ``` [Answer] # JavaScript, ~~342~~ ~~299~~ 307 bytes ``` n=>[' '+'_'.repeat(e=Math.max(...(s=n.split` `).map(l=>l.length))+2),...s.map((i,l,_,x=i.padEnd(e-1))=>1 in s?l?l>s.length-2?`\\ ${x}/`:`| ${x}|`:`/ ${x}\\`:`< ${x}>`),' '+'-'.repeat(e),''].join` `+[(n=' ')+"\\ ^__^"," \\ (oo)_______",` (__)${n})\\/\\`,n+` ||----w |`,n+" || ||"].join(` `+n) ``` [Try it online](https://tio.run/##RU6xbsMgFNz7FU8oEiBjonSqquIMVcdu3UJjrITYRAQsg9JEId/uYqdSj@Xuce/dHZtzE3aD6WN5fhkPYnSi2mDABa4xH3Svm0i0@Gxix0/NhXDOSRCOh96aqJ4UzdOeWFFZbrVrY0dp8UxZtoX5hxhmWc0uwvC@2X@4PdHlilJRrcA4CGu7tlX4Wy2f10pKWNwu96V6VWlmKbPlzKTM9G2mlaJs7lj@d8wT/M2P3rhcq9gQJzA8gGmB8l2AbV1vEUMwCeI9rR9ATE02Utd0cXN3KuUyZzFXKEipzPiBNEmU5XwwJfRIIlOUo@POu@Ct5ta35EDQOz55B9a0XYTTFQ5m0NJN72u4QvQQdITYaXCmNdmSvZMFUTr@Ag). # Explanation This builds an array of strings which are joined with a newline. ## What each element does * element 1: underscore string * next few elements: each line of the inputted string with the added limiters * next element: hyphen string * then, add the cow string. *-43 bytes thanks to A username* *+8 bytes due to empty line bug* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 117 bytes ``` L⁾||ẋṫ5“/\“\/”jµ⁾<>Ḋ?⁶ẋ4¤s2¤js1s2 j@€⁾ z⁶⁾_-jⱮZj@"Ç;“¡{+Ṁ“#ßɗ⁾ŀ`m“¬ṖȥƇʂẆEẒẓ“¡ɲÇ⁹E⁸ċ⁷“¡ɲÇ⁹D⁹{Ṅ’ṃ“\ ^_(o)/|-w”¤⁶;$8¡€¤ ``` [Try it online!](https://tio.run/##XVFBSxtBFL7vr3hZC4moCQ0WhAT1YKCFHL20atNks7q7bHbCzixhTQ67qRjQWwsthRYJxJNBUDS6ETxMVNR/MfNH1udii3SYGd573/e@9w1j6bbtx3FZhtedjhjvi@jonQx@59bxWs/J4I/FzxErLorLvSUZjpAyzwc0zwcWfUvzirUsu0MkAGwjikFlzpInx5@sZXXSK6AI77dnRBRgNDU5ePiJjNvgS@MZGIrox/3hXe@xK8a7JTH@Jsbfk4aH00lPhlFJhpc3@zK8eF1cwdMW0Y4Mfono67NJ@FzJkOlcZ66FbvkAXRTeLPA@2uKDWFydTXof7/Yws3A0H/FRHK8pqqqu@k1Tq9qgkRat@kA81vRYCoHZBG0RpWw6Ov1XMEwKuJmhw6bpUgY2wkA2wXSwMau8JlBdI049YWThA/tbtomzpVM2C5Qkec2r1WxkG8Sz60CZqzPNAEZwAPb8p8kM032RVN7jpxFoEdeup5RMoaCm0@1icS2tKrhKjSbzEyJ9kXbSDLSqR3WoOj40XYJTGzSLr1I2ngA "Jelly – Try It Online") -26 bytes using base + integer compression (thanks to Bubbler for the idea) -2 bytes thanks to caird coinheringaahing ## Explanation ``` L⁾||ẋṫ5“/\“\/”jµ⁾<>Ḋ?⁶ẋ4¤s2¤js1s2 Helper Link - generates the side borders ? If Ḋ list[1:] (basically, if the length is not 1) L⁾||ẋṫ5“/\“\/”jµ Sublink; generate the side borders for the non-edge case L Take the length ⁾||ẋ Repeat "||" that many times ṫ5 Tail; remove the first 4 elements “/\“\/”j Use that result to join ["/\", "\/"] ⁾<> Otherwise, return "<>" ⁶ẋ4¤ " " * 4 s2¤ split into slices of size 2 j Prepend and append (Extra spaces are needed because the top and bottom borders don't have side borders) s2 Slices of length 2 (separate the left and right border components) s2 Slices of length 2 (group the left and right border components into pairs) j@€⁾ z⁶⁾_-jⱮZj@"Ç;“...’ṃ“ \_(o)/|-w^”¤⁶;$8¡€¤ Main Link j@€⁾ join " " with each row (surround in spaces) z⁶ Zip, using space as filler Ɱ For each column ⁾_-j Join ["_", "-"] using it (prepend _ and append -) Z Zip j@"Ç Vectorized swapped join with the helper link (basically, for each row, prepend and append the borders) ; Append: {{ “...’ [23386201, 8811166311836860, 134563374682941922730, 101089407352370886, 101089407336781202] ṃ“ \_(o)/|-w^” Base decompressed with " \_(o)/|-w^" - this is the cow without leading spaces € For each row ⁶;$ Prepend " " 8¡ 8 times ¤ }} ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~92~~ ~~87~~ ~~86~~ ~~83~~ ~~81~~ 80 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` l╷?/ω┤|*\∔∔]<} +↔ω┘+×L┤_×α-×└∔∔r 7ד;yB¾‾≡*hsNMnJS=f≤)g<◂AX↓ZxLh?╷r┌╴\⁵n╪.cE^‟+∔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjRDJXUyNTc3JXVGRjFGLyV1MDNDOSV1MjUyNCU3QyV1RkYwQSU1QyV1MjIxNCV1MjIxNCV1RkYzRCUzQyV1RkY1RCUyMCV1RkYwQiV1MjE5NCV1MDNDOSV1MjUxOCV1RkYwQiVENyV1RkYyQyV1MjUyNF8lRDcldTAzQjEtJUQ3JXUyNTE0JXUyMjE0JXUyMjE0JXVGRjUyJTIwJXVGRjE3JUQ3JXUyMDFDJTNCJXVGRjU5QiVCRSV1MjAzRSV1MjI2MSV1RkYwQSV1RkY0OHMldUZGMkVNJXVGRjRFSlMlM0QldUZGNDYldTIyNjQldUZGMDkldUZGNDcldUZGMUMldTI1QzIldUZGMjFYJXUyMTkzJXVGRjNBeCV1RkYyQ2gldUZGMUYldTI1NzdyJXUyNTBDJXUyNTc0JTVDJXUyMDc1biV1MjU2QS5jRSV1RkYzRSV1MjAxRiV1RkYwQiV1MjIxNA__,i=JTYwJTYwJTYwJTBBVGhpcyUyMGlzJTIwdGhlJTIwZmlyc3QlMjBsaW5lJTIwb2YlMjBpbnB1dC4lMEFUaGlzJTIwaXMlMjB0aGUlMjBzZWNvbmQlMjBsaW5lLiUyMEl0JTIwaXMlMjB0aGUlMjBsb25nZXN0JTJDJTIwc28lMjB0aGUlMjBidWJibGUlMjBzaG91bGQlMjBzdHJldGNoJTIwdG8lMjBmaXQlMjBpdC4lMEFUaGlzJTIwaXMlMjB0aGUlMjB0aGlyZCUyMGxpbmUuJTBBSGVsbG8lMjB3b3JsZCUyMSUwQSUyOCUzQiUzQiUyMiUyNyUyNyU3QiUzQyUzQyU1QiUyNyUyMiUwQSUwQSUwQSUwQUVtcHR5JTIwbGluZXMlMjBzaG91bGRuJTI3dCUyMGNhdXNlJTIwYW55JTIwcHJvYmxlbXMuJTBBJTYwJTYwJTYw,v=8) Takes input surrounded by `````. [Answer] # JavaScript (ES8), ~~ 266 ~~ 252 bytes ``` s=>` _2 3 -2 5\\ 1^__^ 10\\ (oo)\\_5 9(__)\\ 5)\\/\\ 13||-6w | 13|| 7||`.replace(/.(\d+)/g,(s,n)=>n^3?s[i=0].repeat(n^2||w):a.map(s=>'|\\/<'[j=!i++*2|!a[i]]+s.padEnd(w)+'|/\\>'[j]).join` `,a=s.split` `.map(w=s=>` ${w>(v=s.length+2)?0:w=v,s} `)) ``` [Try it online!](https://tio.run/##hZBRa9swEMff/SkuZWB5dpw0IRtr4/SpsMEe9xYltmKrsYIiGZ8cE6p@9u7idFDKxkBId9Lv/n/dHcRJYNmqxo2NreRraXsU5@wVs1UB@SyAeQBjOhacw@02z7cB3E4pBmZtxHm@COAby3MKYUHbhHMC5t6Pv/TgryF89b5IW9loUUo2SRmv4miyTxgmJspWZjt/wLXKppsLI4VjZjvzvo/uRHoUDaOfhJ6Ul@H6kI1UHH@e@ZFYq80mxrQR1aOpWB/FoSfvFTGbKD1YZYqgSESGKTZaOUoGrT4b@vr03K/YiR61NHtXx7PoYXrXZ6cEX6CIIhqCQatlqu2eXQfCil/nRpVCwzUH27mmcyOig7/SveXmpzIS/0nUrZTc/JdSCLRcLeFJtehAEw72CZQh/5Sb9wRK0qgGJIUf7s@1tmYv0SWAdsh33W6nia5tpytA10pX1uAsOVDNR1FXq/ZNk5vvUmsLvW11NeKG3d/fhOHzcrkOb7iBSzfcPB4bdx54fLMwoYNSdChBmDM0rSX3I6aXSf8G "JavaScript (Node.js) – Try It Online") ### How? We first split the input string into lines surrounded with 2 spaces and compute the width `w` of the biggest line (including said spaces): ``` a = s.split`\n`.map(w = s => ` ${w > (v = s.length + 2) ? 0 : w = v, s} `) ``` Each number `n` in the template string is interpreted as follows: * `2`: repeat the preceding character `w` times (for the top and bottom borders of the text bubble) * `3`: insert the text bubble: ``` a.map(s => '|\\/<'[j = !i++ * 2 | !a[i]] + s.padEnd(w) + '|/\\>'[j] ) .join`\n` ``` * anything else: repeat the preceding character `n XOR 2` times [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 106 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¢Ʋėỵ“Œ\ė#ݲ¿“¤e+ṂTƒƑ¶d“Ṫ©Ḋ9çṀṠ“Ṫ©Ḋ87⁹Ġ’ṃ“ \_)o|w-^/(”⁶;$8¡€ Ø^⁾><Ṗ?WẋLU0¦”|JṖḊƊ¦⁾ ©jṁ€2ɓ®jⱮz⁶⁾_-jⱮZj@";¢ ``` A monadic Link that accepts a list of the lines and yields a list of lines. (Gives eight spaces before the cow, for seven change `8¡€` to `7¡€`) **[Try it online!](https://tio.run/##XZBBSwJBFMfv@ykmCzRKiy4ZK9UlqOhoRCWKumu7y7ojOyNieXDtENgpgywoKInCCCkpaRMMRhP6GLNfZHuKgfSYw/v/3v/9H4wm63redZ3iNav1m70qb79D/12J9KqTvRfWZF@D0b08w@1SuF/pn7GWBITbT6zOP8pL3UduF7l9O8aCi45l94BccfsYOIrEpnEh54/O@ZzijWO1xKkgu3NKz0L3MupYneUQty9Wdvjn6db2PHsAT2ETCCT1yyCtDkKsrnHbgpWFn3PW0JzXxiHkwCjmH4g9bdUjsprL22/dk13XDSsqQfCoIqOUahKKdNWQEU4h1chkaUAYNxA5iQ1p6AigDfqHdWwcyITOIoKHOpFNJHRwKzirS4hQU6ZJBVEMB2DnXyZVVHMUKazDD2OUw6YuTQg@UfR4vUeh0L7XI0CtpTM0PzSSUbThpSgZzxIZxY08ypgYrqZJ4Bc "Jelly – Try It Online")** ### How? ``` Ø^⁾><Ṗ?WẋLU0¦”|JṖḊƊ¦⁾ ©jṁ€2ɓ®jⱮz⁶⁾_-jⱮZj@";¢ - Main Link: list, Lines Ṗ? - if popped (Lines)? (i.e. > 1 line?): Ø^ - then: "/\" ⁾>< - else: "><" W - wrap (that) in a list, say "Corners" L - length (of Lines) ẋ - repeat (Corners that many times) 0¦ - apply to rightmost: U - upend (reverse to "<>" or "\/") Ɗ¦ - apply to indices... J - range of length (of Lines) Ṗ - pop Ḋ - dequeue ”| - ... '|' (replaces all but first and last) ⁾.. - " " © - (copy this to the register) j - join ṁ€2 - mould each like 2 ("||" and " " as needed) ɓ - new dyadic chain - f(Lines,Edges=that) ® - recall from register -> " " jⱮ - map (across Lines) with join z⁶ - transpose with space as filler ⁾_- - "_-" jⱮ - map (across these columns) with join Z - transpose (back to rows) @" - zip with, with swapped arguments: j - (Edge-pair) join (Row) ¢ - call last Link as a nilad -> cow lines ; - concatenate “...’ṃ“ \_)o|w-^/(”⁶;$8¡€ - Link 1, Get cow lines: no arguments “...’ - list of integers (one per line of the cow) “ \_)o|w-^/(” - " \_)o|w-^/(" (the cow's constituents) ṃ - base decompress € - for each: 8¡ - repeat this eight times: $ - last two links as a monad: ⁶ - ' ' ; - concatenate ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~156~~ 144 bytes ``` mP`^.* ¶ \¶\ 1,-2%`^.|.$ | ^ $.%'*_¶/ $ /¶ $.%`*- ¶/(.+)/¶ __¶<$1>¶ $ ¶7* \ ^__^¶8* \ (oo)\7*_¶11* (__)\7* )\/\¶15* ||4*-w |¶15* ||5* || ``` [Try it online!](https://tio.run/##XY3NasMwEITv@xTT4GBHTWRcWlJI6K3Q3nrorcbOn1IbFClYMiHUz@UH8Iu5G5NAqRBi59PsTKV8adZJ3x8@VpkU1LWEtGtTUDKdPYyZNTKghjJCIMehyLs2BgWEuGsvZCVmvBNH8n7ChHL@XwbJC48B87lACiDL86xrnwcRWTtJ55ecJBGI8vyiMEljbk2eBJrmUcxOaG5qePr@sygd@PpCYV9WzkOXRsHuUZpj7SX9NTi1tWY3OCTe/Q1ra76V81M4O@hNvdlodhe21js4Xym/LeAtF/DOv0xflNU1kt6U1hYnW@ndHUWLxSgMf5bLr3BEfF4PR38ejO4abUKP7bp2CmtzxrGy3Hpw8hc "Retina – Try It Online") Explanation: ``` mP`^.* ``` Pad all lines to the same length. ``` ¶ \¶\ ``` Add `\`s on all the intermediate lines... ``` 1,-2%`^.|.$ | ``` ... but fix interior lines to use `|` instead. ``` ^ $.%'*_¶/ $ /¶ $.%`*- ``` Insert the leading row of `_`s and trailing row of `-`s, plus the `/`s at the start and end of the bubble (still assuming a multiline bubble). ``` ¶/(.+)/¶ __¶<$1>¶ ``` Fix up a single-line bubble, not only to change the `/`s to `<>`s, but also because not enough `_`s are calculated for the initial row. ``` $ ¶7* \ ^__^¶8* \ (oo)\7*_¶11* (__)\7* )\/\¶15* ||4*-w |¶15* ||5* || ``` Append the cow using run length encoding. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~380~~ ~~354~~ 329 bytes *-25 thanks to @A username* ``` t=>` ${"_".repeat(m=Math.max(...(l=t.split` `).map(d=>d.length)))}__ ${"/<"[j=+!l[1]]} ${l.shift().padEnd(m)} ${"\\>"[j]} ${j?'':l.map(d=>"|\\"[w=+!l[++j]]+' '+d.padEnd(m)+' '+"|/"[w]).join` `+` `} `+"-".repeat(m+2)+` \\ ^__^ \\ (oo)\\_______ (__)\\${n=' '})\\/\\ ${n}||----w | ${n}|| ||`.replace(/\n/g,` `+n) ``` [Try it online!](https://tio.run/##RU9Ba8MgGL3nV1gpqLgatlMZsz0NtsMuu@xQUyNN2iQYDY1rBzW/PfvSUvpA8Hu@975nY06m3x3rLixOy3EvxyBXOZpfsMbiWHalCbSVXyZUojV/VAhBrQyi72wd8iRnwHa0kKtC2NIdQsUYG7ROwJ@@4U0j@cxunrNsgEQr@qreB8pEZ4p3V9CWTTRWagXKbABTsybk1d4zcVQKb87XDM6bLOMEEV487NcZxxREGRONrx1U4nAGlHO8eHyAvzCglUIIbbXeJmi6Uu@ZUvqGBJ4Q1RqY@cVJgm4gAxCpUgkUdUOMC8AZxft41cSYT4us2ZU0VS49PE0tHBt33vXelsL6A91T/FHPlPskLfouC6HcT@XR7xozNv4D "JavaScript (V8) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), a 194-byte mess ``` □⁋↵:ƛL;G:£2+\_*\ +\ $+,L1=[‛< □‛ >++,|□L(n[n›□L=[`\\ `` /`|`| `` |`]|`/ `` \\`]□ni:L¥ε\ *+$++,)]\ ¥2+\-*\ ++,` ?\\ ^__^ ?\\ (oo)\_______ ?? (__)\\ ?)\\/\\ ???||----w | ???||?|| `\?\ 5*V, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%96%A1%E2%81%8B%E2%86%B5%3A%C6%9BL%3BG%3A%C2%A32%2B%5C_*%5C%20%2B%5C%20%24%2B%2CL1%3D%5B%E2%80%9B%3C%20%E2%96%A1%E2%80%9B%20%3E%2B%2B%2C%7C%E2%96%A1L%28n%5Bn%E2%80%BA%E2%96%A1L%3D%5B%60%5C%5C%20%60%60%20%2F%60%7C%60%7C%20%60%60%20%7C%60%5D%7C%60%2F%20%60%60%20%5C%5C%60%5D%E2%96%A1ni%3AL%C2%A5%CE%B5%5C%20*%2B%24%2B%2B%2C%29%5D%5C%20%C2%A52%2B%5C-*%5C%20%2B%2B%2C%60%20%20%3F%5C%5C%20%20%20%5E__%5E%0A%20%20%20%3F%5C%5C%20%20%28oo%29%5C_______%0A%3F%3F%20%28__%29%5C%5C%20%20%3F%29%5C%5C%2F%5C%5C%0A%3F%3F%3F%7C%7C----w%20%7C%0A%3F%3F%3F%7C%7C%3F%7C%7C%0A%60%5C%3F%5C%205*V%2C&inputs=This%20is%20the%20first%20line%20of%20input.%0AThis%20is%20the%20second%20line.%20It%20is%20the%20longest%2C%20so%20the%20bubble%20should%20stretch%20to%20fit%20it.%0AThis%20is%20the%20third%20line.%0AHello%20world!%0A%28%3B%3B%22%27%27%7B%3C%3C%5B%27%22%0A%0A%0A%0AEmpty%20lines%20shouldn%27t%20cause%20any%20problems.&header=&footer=) Explanation tomorrow. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 155 bytes ``` ¶¡©éθgUð'_XÌ×¶®gΘ„/<èð®нðX®нg->×®gΘ„\>è¶[®¦©gĀ_#®gΘ„|\èð®нðX®нg->×®gΘ„|/è¶}ð'-XÌ×¶•1rΛKιØ²è{ʯ4Þ₁ÐÃ5Λ^ÛиÏú!j™¨õ‰6æ≠ÓÍl¼ûÑ©kθJ* Rèªùî¾&Σp•"\ ^_ (o)/|-w"ÅвJJ ``` [Try it online!](https://tio.run/##fY9NSwJBGMfv@ynGDVqLVILqongLym5RICiKL@vu1rqz7IyIZGBvh6Ko6JAgSBmI28FESLS3wzydFz/DfhEbRSE6NAwMz/N/@TGYpNKaPBqxHntkNthOX9mFjpSMwiXc82VbcapupR4IQQs6rD38hE50/Ci@MNenajwMLdaLsTZrMlv5riTnZko5/l@uHBjnDjnPN@W5lcay5dS2nAFUWRdaB3DBXlag7h4fwQ2crDq1BNSGfbiGN8@ee9pgLXh1K501aLrnD3AHVzr7gHe4Zfa@048sCtsc8AwDaLOveefJ5PViHCWSghcvBMq@oghnw24kMhqJorijagTxS1UZ5TSLUKRrhoxwDmmGWaB@4beByBlsZCcOP9qks7WODUUmdAkRPJnThXRa524VF/QsItSSaUZFFHMAz/zppKpmTSuFDVnXMSpiS896BG8wKErSQSgUk0SBn/W8SUsTI5lWGxJFmVSByChllJBpYU7NEz//1Q8 "05AB1E – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), ~~243~~ 240 bytes ``` r=readlines()[(R=end;:)] a=' ' l=maximum(length,r)+2 println.([a*'_'^l ["|/\\<"[(j=1+(i<2)+2(i==R);)]rpad(a*r[i],l)*"|\\/>"[j] for i=1:R] a*'-'^l replace(raw"? \ ^__^ ? \ (oo)\_______ ?? (__)\? )\/\ ???||----w | ???||?||",'?'=>a^5)]) ``` [Try it online!](https://tio.run/##XY9fb8IgFMXf@RR3fQG01rhkLyr2acn2avZWaoMWLYZCAzRq1u/u8M@SZSf3gQO/e0449lqJ2fl6dcxJUWtlpCe0IGsmTb2Y0xIJhgEjzVpxVm3fEi3NITSpo@NX1DllgjYZKcQIV3ijUZEMU86XSUGObDYmavkaOaIYW9MFLV0naiJGrlBlqukoGTifrpLiWMLeOlBsNl/HwhGe3KKc7LTYSeLEKckBOABsqmqD4vlmiLWUVw@hPAdSVZTHN8qnPPp8GCZRJxgeJk6S4hyzldi80ZJer1@N8hAnNBL2yvkAt9@D3YMyXR8y9BfwcmdNfScy@Ay/19qag/QhBW/vfttvtzrSje11DT44GXYNBBsL4s6/zNAo94xEH1JrCyfrdP2CyGKRYPy9XBY4GVZ8iqLe2y5c7rB/xhscYCd6L0GYC3TOxubWZz8 "Julia 1.0 – Try It Online") I was trying to compress the cow but [dingledooper's trick](https://codegolf.stackexchange.com/a/225334/98541) was more efficient ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Help guys my assignment says it needs to be in .pdf format but I did it in Word. I'm really stuck. How do I take a word document in .docx format and make a .pdf that contains all the text from it? Bonus points if it also contains all the images and any formatting, but text is a bare minimum. The sample file I'll be using will be [this one](https://www.google.co.uk/search?q=sample%20docx%20file&oq=sample%20docx%20file&aqs=chrome..69i57j0l3.2363j0j1&sourceid=chrome&ie=UTF-8), though your solution should be generic. I don't want it to go through any unnecessary processing steps - simply encoding then decoding the document in base64 or whatever is not in the spirit of the question, though creative use of `cowsay` will be an exception to this. Standard rules of code trolling apply - the solution should be technically correct, all steps should be technically necessary, the result should be technically useless. This should be more of a "Rube Goldberg" style program, than an obfuscation and obtuseness competition. Most upvotes on answers other than my own by 5/1/14 wins. Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information [here](https://codegolf.stackexchange.com/tags/code-trolling/info "Rules"). [Answer] Ok this is a little tricky but not too bad because pdf uses the same graphics model as postscript which means that once you have postscript it is quite trivial to convert it to pdf and postscript is way to drive printers all you have to do is print to get postscript. Now you could write a program to convert postscript to pdf, but we don't have to there is ghostscript, which was written for unix and works just fine on linux (no major differences for this project). Unfortunately word only runs on windows, so you need two computers, and to convince windows that the linux computer is a printer you need a serial cable and a null modem. If your computer(s) don't have serial ports usb to rs232 converters work just fine (I recommend ones with a fttdi chipset). Now hook up the two computers with the serial cable and the null modem and verify that you can communicate (make sure that your parameters match). Ok now that you have them talking it is time to convince your windows box that the linux box is a printer: just install the printer driver for the applewriter II and say it is connected to the serial port. Now when you print you send postscript to the linux box. the next step is to save it as a file. Now scoot over to your linux box and use this simple command: ``` dd -if=/dev/ttyS0 -of=- -bs=1 | ps2pdf - - | sed -e '' >tmpfile && mv tmpfile file.pdf ``` and as simple as that you are done. --- This can actually be made to work (if you send a signal to dd when you are finished) but there are easier ways like printing to a file and running gostscript on your windows box, and although fttdi makes good quality usb to serial converters it is a royal pain to install the drivers. [Answer] These days many printers are combination printer/scanner with automatic document feeders. It will be simple. 1. Print the document. 2. Scan the print out. [Answer] # PHP This code produces PDF files that should print out perfectly on your [ticker tape machine](http://en.wikipedia.org/wiki/Ticker_tape). If you want to view the PDF files on your monitor, you might have to zoom in a bit. **Example source document** ![word document](https://i.stack.imgur.com/MOCPz.png) **PDF output (viewed in browser)** ![partial view of PDF document](https://i.stack.imgur.com/pMmvu.png) **Source code** ``` <?php header("Content-Type: application/pdf"); $s = docx2txt("word-file.docx"); // <-- Insert filename here! echo txt2pdf($s); function docx2txt($filename) { if (!($z=zip_open($filename))) return false; // Can't open file while ($r=zip_read($z)) { if (zip_entry_name($r)!="word/document.xml") continue; if (!zip_entry_open($z,$r)) return false; // Can't open XML data for ($s="";;) { $c=zip_entry_read($r); if ($c===false || $c=="") break; $s.=$c; } return trim(preg_replace('/\s+/',' ',preg_replace('/<[^>]*>/','',$s))); } return false; // Can't find XML data } function txt2pdf($text) { $width="".ceil(strlen($text)*7.2); $text=str_replace('(','\050',str_replace(')','\051',$text)); $length=strlen($text); $wlen=strlen($width); $len4="".(44+$length); $xr3=sprintf("%010d",174+$wlen); $xr4=sprintf("%010d",449+$wlen); $xrstart=544+$wlen+strlen($len4)+$length; return "%PDF-1.1\n%¥±ë\n\n1 0 obj\n << /Type /Catalog\n /Pages 2 0 R\n" . " >>\nendobj\n\n2 0 obj\n << /Type /Pages\n /Kids [3 0 R]\n " . " /Count 1\n /MediaBox [0 0 $width 14]\n >>\nendobj\n\n3 0 obj" . "\n << /Type /Page\n /Parent 2 0 R\n /Resources\n " . "<< /Font\n << /F1\n << /Type /Font\n " . " /Subtype /Type1\n /BaseFont /Courier\n " . " >>\n >>\n >>\n /Contents 4 0 R\n" . " >>\nendobj\n\n4 0 obj\n << /Length $len4 >>\nstream\n BT\n /" . "F1 12 Tf\n 0 3 Td\n ($text) Tj\n ET\nendstream\nendobj\n\nxr" . "ef\n0 5\n0000000000 65535 f \n0000000018 00000 n \n0000000077 00000" . " n \n$xr3 00000 n \n$xr4 00000 n \ntrailer\n << /Root 1 0 R\n " . " /Size 5\n >>\nstartxref\n$xrstart\n%%EOF"; } ?> ``` --- Note: The `txt2pdf()` function is based on a [minimal PDF](http://brendanzagaeski.appspot.com/0004.html) file made by Brendan Zagaeski. [Answer] On UNIX systems: ``` mv document.docx document.pdf && cowsay "code-trolling is cool" ``` On Windows: ``` ren document.docx document.pdf ``` [Answer] I believe this shell script to be a simple and intuitive method of solving the problem. Is there a better way? ``` ( echo $'<svg>\n<text y="10">'; unzip -p ./YOUR_FILENAME_HERE.docx word/document.xml | sed -e 's/<[^>]\{1,\}>//g; s/[^[:print:]]\{1,\}//g'; echo $'\n</text>\n</svg>' ) | inkscape -f /dev/fd/0 -D -A ./OUTPUT_FILENAME_HERE.pdf ``` [Answer] This link will surely gonna help you. <http://javahive.in/convert-word-doc-to-pdf-file-in-java/> you just have to run this java code and your pdf will be there for you. [Answer] # Windows Batch The easiest way to convert a file: change the extension! ``` :: convert.cmd xcopy "%~dpnx0" "%~dpn0.pdf" ``` Spoiler/troll: (hover below to see) > > Oops...did I forget that you could convert even a file with a `.exe` extension? So much for that... ;) > Also, I'm too lazy to code the guards. > > And I thought I'd add a little extra troll in this: it doesn't even touch the data inside... (doesn't parse it to make it a valid PDF) > > > ]
[Question] [ Challenge: Find the number of distinct words in a sentence Your task is to write a program that takes a sentence as input and returns the number of distinct words in it. For this challenge, words are defined as consecutive sequences of letters, digits, and underscores ('\_'). Input: * A string containing a sentence. The length of the sentence will not exceed 1000 characters. Output: * An integer indicating the number of distinct words in the sentence. Examples: ``` Input: "The quick brown fox jumps over the lazy dog" Output: 8 ``` Explanation: The sentence contains 9 words, 8 of which are distinct: "The", "quick", "brown", "fox", "jumps", "over", "lazy", and "dog" ``` Input: "To be, or not to be, that is the question" Output: 8 ``` Explanation: The sentence contains 8 distinct words: "To", "be", "or", "not", "that", "is", "the", and "question". ``` Input: "Hello, World!" Output: 2 ``` Explanation: The sentence contains 2 distinct words: "Hello" and "World". ``` Input: "hello-world2" Output: 2 ``` Explanation: Two distinct words, "hello" and "world2" separated by hyphen. ``` Input: "Hello, World! Hello!" Output: 2 ``` Explanation: Only "Hello" and "World" are two distinct words here. Scoring: This is a code golf challenge, so the goal is to minimize the size of your code while still producing correct output for all test cases. In case of a tie, the earliest submission wins. Good luck! [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utils, 28 ``` grep -Eo \\w+|sort -fu|wc -l ``` [Try it online!](https://tio.run/##JczBCoJAFIXh/TzFCdqlQm1bCy1aRAgRCKLO1bEmr86MTYXvblrLj/9wityqyatGEwzlcg/JoFIx1uf4dLxinGpDHcKYkaZ@M1o2DmE1jL5EqCfJLU2JIvRDU95RGPYtKn7hNjw6C36SgZuzzj/v@boWCaOgAGzQsoP7y6ncobG/ZT@QdQ234kBac4ALGy1XYivU4tAv3ImSJWVRVrOuIvEF "Bash – Try It Online") [Answer] # [Python](https://www.python.org), 54 bytes ``` lambda s:len({*re.findall('\w+',s.lower())}) import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dc8xTsNAEAXQPqcYtvEuOCkoEEKi5wCRaNKs8SxeGO84s2NMQJyExhKCe3AMbgOOQUpDNfr6el-a149upw2n8S1cbt57DcvzrzPybVV7yBeEyT4fC65CTLUnssVmOCnKvCIeUKxzL24R245FQfBXf3YSk9pgzbpB2Pbx5h4q4SFB4Ee469suAz-ggP7U5J92UPOtcW7x54o1Q4UlsEBiBZ2TNl4h5r3a9pg1cioOlLlCIi7hmoXqo8M900zNcpiKU_MvgX2a5PzIOM73Gw) [Answer] # [jq](https://stedolan.github.io/jq/), ~~53 52~~ 50 bytes ***-1 byte** by Neil for recognizing splitting on just `\W` works since we handle empty strings anyway. **-2 bytes** by me for realizing I could `ascii_downcase` first, saving a `.` and a `|`* ``` ascii_downcase+":"|[splits("\\W")]|unique|length-1 ``` ~~[Try it online!](https://tio.run/##VcxBDoIwEIXhvacYutIAJrr0BB6AhIUYU6DaYu1AOxU1vTsWXLn88v68bpimbcoOLJxcrxW5NauqMmWbwF2j1KXF0TTciXPwRg1eBC3MjWS@myZWSAGDV80dahszuOILOv/oHeBTWKA4a/55Q4s3tmIFQi0yQAsGCegnkpxAuaWN744UmtgehdaYQYlWt0m0nJ2PM/eRyd8OixL2BQ "jq – Try It Online") [Try it online!](https://tio.run/##VcxBDoIwEIXhvacYutIIJrr0BB6AhIUYU6BCsXagnYqa3r0WXLn88v68fgxht2VH5s92UJLsmpVlwTae21rKa4OTrrkVF@@0HJ3wSuiWumwfAss7AaOT9R0qEzO44Qt69xgs4FMYoDgr/nlDgy1bsRyhEimgAY0E9BN1nEDapY3vliTq2J6EUphCgUY1SXQ3O5tmHiKTvx0WJewL "jq – Try It Online")~~ [Try it online!](https://tio.run/##Vcw7EoIwEAbg3lMsW@kIhZaewAMwQyGOEyBKMGYh2Yg63D0GrCy/@R/dEIJwtVKXhkZTCye3eMDp5Hqt2K2xLAvcnCdv1ODlpKW5cZvtQsC8lTB4Vd@hsnEJV3pB5x@9A3pKCxxjLT5vaOiGK8wJKpkCWTDEwD9xKxiUW7rx3bEiE7tHqTWlUJDVTRLdzs7GmfvI5C@HRQl@AQ "jq – Try It Online") Equivalent 50 byte answer: ``` ascii_downcase+":"|split("\\W";"")|unique|length-1 ``` Thanks to chune's [answer](https://codegolf.stackexchange.com/a/258576/86147) for inspiring me to try golfing `splits("\\W+")` instead of `match("\\W+";"g")`. Turns out, despite having to work around the empty string being matched in some cases, it is two bytes shorter! For those curious, here's the `match` method: ``` [match("\\w+";"g").string|ascii_downcase]|unique|length ``` [Answer] # [Perl](https://www.perl.org) `-p`, 24 bytes ``` $_=grep!$s{+lc}++,/\w+/g ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kILUoZ1m0km6BUuyCpaUlaboWO1TibdOLUgsUVYqrtXOSa7W1dfRjyrX10yHSUFULNmak5uTkK5TnF-WkKHqA2BAJAA) -1 byte thanks to Kjetil S [Answer] # JavaScript, 46 bytes ``` s=>new Set(s.toLowerCase().match(/\w+/g)).size ``` [Try it online!](https://tio.run/##DckxEsIgEADAr1wJ40ham9jY2mlpEcSDEAmXcAQ0n0e33UkXzSb5JR/Lqdm@cX@OWOGGWbDKdKWK6aIZhVSzzmYU3aMeOielYr9jMxSZAqpATlgx3EeEdfPmDc9ENYKlD0zbvDBQwQT530HvX3iRU4OU7Qc) [Answer] # [Zsh](https://www.zsh.org/), 36 bytes ``` <<<${#${(u)=${1:l}//[^[:IDENT:]]/ }} ``` [Try it online!](https://tio.run/##bY67DoJAFER7vuKCFJBgiJYEO020sSKxIJjwWF103Sv7EIXw7QhIaTlnziTTSNrnuoYcNVeal5UmNYpCOq7Th2Fotwu7dbS7sdtVwDrfj89xcNjujlGQJD50Xe8axri3Ikqg0mV@h0xgzeGCb7jpx1MCvogANdQsbT5Q4NWaFwgZ8QAFcFSgfknRVEEpJ3/4IlWJfPb3hDH04ISCFebM6MiW9YjW/zSYkmn1Xw "Zsh – Try It Online") Fortunately, the `[:IDENT:]` character class is exactly the words we should keep. ``` <<<${#${(u)=${1:l}//[^[:IDENT:]]/ }} ${1:l} # lowercase string ${ //[^[:IDENT:]]/ } # // replace non-[:IDENT:] with spaces ${ = } # = split on $IFS (space/tab/newline ${(u) } # keep first occurance of each word ${# } # count <<< # print ``` [Answer] # [Python 3](https://docs.python.org/3/), 34 bytes ``` lambda i:len({*i.lower().split()}) ``` [Try it online!](https://tio.run/##DckxDoMwDADAr1hMdgeWbkj8grFLKAkYTJyGUAqIt4feemFPg/pndvUri5nbzgBXYj2eDy5FNxuRyiUIJ6SLcojsEzosmsHCZ@X3BG3UzYPTH4zrHBbQr42Q/i3m2KHTviDKNw "Python 3 – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 49 bytes ``` ($args-split'\W'-ne''|%{$_|% *l*r}|sort|gu).Count ``` [Try it online!](https://tio.run/##VY9BT8JAEIXP7a8YyWILaT1wMjEkJL140wgJBzWkLQMUl07ZnbUo7W@vWyiKx/fmfW9mCipR6Q1KGaaksBGr8bHxRazWOtSFzNh7m3thjp5X9Y9iUfVhKIeqrjQprtZmcBeRybmpXXfiu04w8XuzDcLeZOkHJIrKHFZ0gK3ZFRroExWwHcv4@wuWtO4FcD/oKIIEAyAFOTHwWfEmZsj0idkb1JxRfsU82qspgDkpubyx/qjz228oLFt7dGX/i8NJddTA/uY6gu2GKNZ2scBDgSnjEsYgFnakUBvJVt2KFfwGXef1eRoZzbR7SrYWeJ/YHmdq0hS1btmOC3H/1/lgI7Ouoc1c2lr/5bKnI61Xu3XzAw "PowerShell Core – Try It Online") ``` ($args-split'\W'-ne''|%{$_|% *l*r}|sort|gu).Count # full function $args-split'\W'-ne'' # Splits the input string on non words character and remove empty entries |%{$_|% *l*r} # Calls ToLower() on each of the words |sort|gu # Get unique words, Get-Unique needs the list to be sorted to remove all duplicates ( ).Count # Return the count ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 11 \log\_{256}(96) \approx \$ 9.05 bytes ``` u"\w+"AfZUL ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharS5ViyrWVHNOiQn0gIlCJBduUPFJzcvJ1FMLzi3JSFBXAPEUliCwA) Same approach as basically every other answer. ``` u"\w+"AfZUL # Implicit input u # Uppercase "\w+"Af # Regex findall "\w+" ZU # Uniquify L # Length ``` [Answer] # Excel, 120 bytes ``` =LET( x,MID(UPPER(A1),ROW(A:A),1), ROWS( UNIQUE( TEXTSPLIT(A1,, IF((ABS(77.5-CODE(x&"Z"))<13)+1-ISERR(0+x)+(x="_")=0,x),1 ) ) ) ) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Yet another one of those occasions I regret suggesting the removal of `_` from the `\w` RegEx class in Japt! ``` f"[%w_]+" üv l ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZiJbJXdfXSsiIPx2IGw&input=IlRoZSBxdWljayBicm93biBmb3gganVtcHMgb3ZlciB0aGUgbGF6eSBkb2ci) ``` f"[%w_]+" üv l :Implicit input of string f :Match "[%w_]+" : RegEx /[a-z0-9_]/gi ü :Group & sort by v : Lowercase l :Length ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ɽøWǍUL‹ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvcO4V8eNVUzigLkiLCIiLCJUaGUgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nIl0=) Explanation: ``` ɽ - Lowercases Input øW - Groups string by words into a list Ǎ - Removes all non-alphabetical items, leaving empty list spaces U - Removes all non-unique list items L - Gets length of list ‹ - Decrements by 1, to account for extra list item for first symbol ``` [Answer] # [Factor](https://factorcode.org/), ~~47~~ 46 bytes ``` [ >lower R/ \W/ re-split harvest cardinality ] ``` [Try it online!](https://tio.run/##hdA9T8MwEAbgvb/iTeaWSp0QSKzAwsCHOgCD61wbg@tzz5emAfHbg9MiEAPlJp/Pj16dl8YqS/9wd31zeQaTrHMQWtEuItGmoWAp5ZMmRCHVLooLivPR@wi5yvuasGmcfcVCuA1Y8g4vzTom8JYEmsfevHWoeFWiwOmXYixoDBYEVuih09ooXNqbHJzUcSjz6291Rd7zGHMWXxXD5FgVmB1UPahJO6DZf@hH/crCvvs7clAf/SMuPLd56dspnubT/IuTFL1T1Ea2eR1YI5ULJl91eO7XJuKk/wQ "Factor – Try It Online") -1 byte thangs to GammaFunction * `>lower` convert input to lowercase * `R/ \W/ re-split` split on non-word characters * `harvest` remove empty strings * `cardinality` length without duplicates Splitting and harvesting is shorter than simply getting a list of matches because the word for that (`all-matching-slices`) is super long. Not sure if there is a way to prevent the empty strings in pure regex, might be shorter. [Answer] # [Lua](https://www.lua.org/), 103 bytes ``` function x(i)r=0m={}for c in i:lower():gmatch("%w+")do if not m[c]then m[c]=1r=r+1 end end return r end ``` [Try it online!](https://tio.run/##HYxBDoIwFAWv8kJi0oaNbEl6C3fGBZYWqvR//LaCGs9elcUkM5uZcleKz2RTYMKqghazj@b98SywCITQTrw4UbodYpfsqKrdUle6ZwQP4oR4tKc0OtrENGKkbuCo3xCXshDkH2WWQEmtqjqMDrcc7BVn4YXgecUlx/kOfjjB74apez3R81BpXb4 "Lua – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 35 bytes ``` $=>[match lower&{/\w+}|unique|size] ``` [Try it](http://arturo-lang.io/playground?Y02Smw) [Answer] # [J](https://www.jsoftware.com), 23 bytes ``` '\w+'#@~.@rxall tolower ``` Uniquify and count word matches in lowercase input. [Attempt This Online!](https://ato.pxeger.com/run?1=XY7BDsFAFEX3vuIiMRFtI1ZSIRKJWFhJExubYmrK6GM61bLwIWxq4RvEp_gbo91ZvNycnJubd39s83fNYQH6LhgstOGasx2MZtPxM9GB3X2xRdpi9eHVGarMlxKaJKVclfZza1b4ShCCxgDMExzHJFztsFSURggowzbZH2LQiStoo6V_OWNNG9ZjHmHJLZBCRNrMFqSFrxHGRfeY8FiHFJnuhEtJFuak5LpqWPzYTn_Y-dcoqMrKD_O8zC8) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` `†`ẎɽUL ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiYOKAoGDhuo7JvVVMIiwiIiwiXCJUaGUgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nXCJcblwiVG8gYmUsIG9yIG5vdCB0byBiZSwgdGhhdCBpcyB0aGUgcXVlc3Rpb25cIlxuXCJIZWxsbywgV29ybGQhXCJcblwiaGVsbG8td29ybGQyXCJcblwiSGVsbG8sIFdvcmxkISBIZWxsbyFcIlxuXCLihpBUaGUtcXVpMmNrLmJy8J2fkG93X24lZm94IGp1w71wcyBvdmVy4omgdGhlIGzmooF6eSBkb2dcIiJd) ``` `†`Ẏ # find all matches of \w+ ɽ # to lowercase U # uniquify L # length ``` ## With a flag: # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 6 bytes ``` `†`ẎɽU ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBbCIsIiIsImDigKBg4bqOyb1VIiwiIiwiXCJUaGUgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nXCJcblwiVG8gYmUsIG9yIG5vdCB0byBiZSwgdGhhdCBpcyB0aGUgcXVlc3Rpb25cIlxuXCJIZWxsbywgV29ybGQhXCJcblwiaGVsbG8td29ybGQyXCJcblwiSGVsbG8sIFdvcmxkISBIZWxsbyFcIlxuXCLihpBUaGUtcXVpMmNrLmJy8J2fkG93X24lZm94IGp1w71wcyBvdmVy4omgdGhlIGzmooF6eSBkb2dcIiJd) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 27 bytes ``` f←{⍴∪(⎕A,⎕D,'_')(∊⍨⊆⊢)1⎕C⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R24TqR71bHnWs0njUN9VRB0i46KjHq2tqPOroetS74lFX26OuRZqGQHHnR71ba/8DGUA9aeoeqTk5@ToK4flFOSmKCmCeovp/AA "APL (Dyalog Extended) – Try It Online") ``` f←{⍴∪(⎕A,⎕D,'_')(∊⍨⊆⊢)1⎕C⍵} 1⎕C to uppercase (⎕A,⎕D,'_') [A-Z0-9_] (⎕A,⎕D,'_')(∊⍨⊆⊢)1⎕C Partition (⊆) using Membership (∊) ∪ remove duplicates ⍴ count words ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žQžjмS¡õKlÙg ``` Assumes the input will only contain printable ASCII characters. [Try it online](https://tio.run/##yy9OTMpM/f//6L7Ao/uyLuwJPrTw8FbvnMMz0///D8lXSErVUcgvUsjLL1EogfBKMhJLFDKLgXSqQmFpanFJZn4eAA) or [verify all test cases](https://tio.run/##VYwxEsFAGEb7nOKLOhoX0JpRGCMz6o2s7LLys/tHxKgdQKd0CJ1JweidwUViRaV8833vkROJls1hW/U7eB9P6PSr5lmPn/XidZvcL4/r0DzOWRM1sZLYFHq2RGKpzDGnHRbFau1AW2nBfjZiXyGlLIgJiYxAFjkx@EesBEO79rkppGNNeTCQxlCEKVmThoH6Urf8Qu9/QkthEMbKJ1KSrk07FpZRalYQ8J5vjHLplfQD). **Explanation:** ``` žQ # Push the constant string with all printable ASCII characters žj # Push the constant string with "a-zA-Z0-9_" м # Remove all those characters S # Convert the string to a list of characters ¡ # Split the (implicit) input-string by each of those characters õK # Remove any empty strings from the list l # Convert each word to lowercase Ù # Uniquify the list of lowercase words g # Pop and push the length # (which is output implicitly as result) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 15 bytes ``` T`L`l D`\w+ \w+ ``` [Try it online!](https://tio.run/##JYoxDsIwEAR7v2IpkJDIM5CgoLREQ2GHXIjh8BH7TCCfNxEUU4xmEmmIvq43e1etOzo2O3eetmahVjsQxhIud7RJpohe3riVxzNDXpSgS2Y/f9DJ1VhBSw0kIYpC/6aDV4T8O8dCWYNEcyBmaXCSxN3qCw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` T`L`l ``` Convert to lower case. ``` D`\w+ ``` Deduplicate words. ``` \w+ ``` Count the number of remaining words. 13 bytes in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1: ``` D$`\w+ $l \w+ ``` [Try it online!](https://tio.run/##JYpBCsIwEEX3OcUXKgh24x0EPUDBjYumdrTRMWMnE6tePhZdPR7vKVmIflOWq11btlV7nNauYjejlGYgjDmcbuhUpoizvHDN90eCPElhc2b/eaOXi2sEHdUQRRSD/c0Gbwjpd46ZkgWJbk/MUuMgyv3iCw "Retina – Try It Online") Link includes test cases. Explanation: ``` D$`\w+ $l ``` Deduplicate words by lowercased value. ``` \w+ ``` Count the number of remaining words. [Answer] # [Ruby](https://www.ruby-lang.org/) `-n`, 32 bytes ``` p$_.upcase.scan(/\w+/).uniq.size ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Vc47DoJAFIXhnlVciIVGGBIrl-ACSCzUmAEGGRnnwjxE6F2FDYW6J3ajgI3ll_MX5_FUNm7eOy-Q3qF7WZMF6x7K2ZHYMqGaEZ1QOQ_39TJcECt5RTRv2dT98q6_RzmDyvKkgFhhLSHDG5ztpdSAV6bAfGdB2wZSPDkRQsx8QAUSDZhJJqcGuB7LyjJtOEpnw4RAH7aoROo6-aCgHrD6n2CUO735AA) [Answer] # [Java (JDK)](http://jdk.java.net/), 83 bytes ``` s->java.util.Arrays.stream((" "+s).toLowerCase().split("\\W")).distinct().count()-1 ``` [Try it online!](https://tio.run/##nVBNT8JAED3bXzH21CrdRK8oCTExHvQECQfxsLTbsmW7U3ZmwUr47XULJF6Jc5m8eXkfmVruZFYXm143LTqGOmDhWRtRepuzRivuxlHrV0bnkBtJBB9SWzhEEIZYcrjP8R1t9XoRPM3YaVtNoHzuKZv8OU6dkx0JYqdkkyQxxPeUCg7ivXIvklSSCmqN5iReLhdxmopCE@vgGogcvQ07e@jHp@hLpUuDHeoCmlAsOYd/foF0FaWH6GbWEatGoGfRBoqNTUoh29Z0UxpqJ/F8rWDrdb6BlcO9hRK/ofZNS4A75YADbeRPBwVWodT4KkuElRoBOrDIwGfEa8mg6WS49YqGZ11r@KaMwREs0Jni9lrRehBl@0Hz@K8gOKFz3vD0Y3TsfwE "Java (JDK) – Try It Online") Saved 17 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602). [Answer] # PHP 8.x, 87 bytes This is a quite long piece of code... ``` fn($z)=>count(array_flip(array_filter(array_map('strtolower',preg_split('/\W+/',$z))))) ``` It's almost self-explanatory. It's so void of PHP-only tricks that it is so trivial to re-implement it into JavaScript! ``` // PHP-like code let fn = ($z)=>count(array_flip(array_filter(array_map('strtolower',preg_split('\\W+',$z))))); // Test boilerplate that has enough functionality function count(value) { return value.length; } function strtolower(str) { return str.toLowerCase(); } function preg_split(regex, subject) { return subject.split(new RegExp(regex)); } function array_filter(array) { return array.filter(function(value){ return value !== ''; }); } function array_flip(array) { return Array.from(new Set(array)); } function array_map(fn, array) { return array.map(typeof fn === 'string' ? window[fn] : fn); } // Event handler - does the basic output thing text.oninput = function(){ output.innerText = fn(this.value); }; ``` ``` <input type="text" id="text"/> <p>Output: <span id="output">--</span></p> ``` --- ## Differences There aren't a lot of differences between the PHP and JavaScript versions: * The `fn($z)=>[...]` has to be written without the `fn` bit. * The regular expression has to be escaped and can't have the slashes. This means it changes from `/\W+/` to `\\W+`. * The function `array_flip` only returns a set of all unique values. The PHP function returns the array with the keys set from the values. That is, an array like `['a', 'fox', 'a', 'car']` will be returned as `['a' => 2, 'fox' => 1, 'car' => 3]` while JavaScript returns `['a', 'fox', 'car']`. The end result is the same: an array that has the same number of unique elements. These differences won't affect the accuracy of the results. But, it's worth to deal with them to give you an improved testing environment. [Answer] ## Mathematica (Wolfram Language), 31 bytes ``` Length@*WordCounts@*ToLowerCase ``` The Mathematica built-in WordCounts treats a hyphenated word as a single word. So this program is not going to work correctly on the fourth example, "hello-world2". I discuss this in the comment below. [Answer] # C (GCC), 156 + 48 + 22 = 226 bytes *-3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* Use compiler flags `-DW(a)=for(--s;a!isalnum(*++s)|*s==95;)*s|=32;` and `-DF(a)=for(a=0;a<i;++a)`. ``` char*v[99],*e;i,j,k;f(char*s){e=s+strlen(s);W()for(i=0;s<e;){v[i++]=s;W(!)W((*s=0)|)}F(j)F(k)strcmp(v[j],v[k])|j==k||(*v[j]=0);k=0;F(j)*v[j]&&++k;return k;} ``` [Try It Online!](https://tio.run/##lVHLbsIwELzzFUukIm@cREDVAzJWLy0/UCQOaVS5qQNOgkNjkwvh15s6PFqpB6T6sLZnxzNeTRqu07Tr0o2o/SaezZLAl0wFeVCwjJxQgwfJDTW2LqUmBtmKYFbVRPExM3PJ8NDEitKEG9cZ4ooQ3/AxtnhckBwXpED3NN3uSBPnSdDERYJtznnRtsTvIcdlhdPq2SdgNKK0YLW0@1pDwY7dVihNcHAYwGX1/wITJ8DBW1bwLgOoatCVBXu@2Y2woIzbJXzupbGq0pHHfgR2tdI2I97dx6v2AsjcWPjb/eMzORtFUQQ3zZxLWf7DcnLDc3oZzumE1pVHWD6/LKE/vvXlpvC0Fz52X2lWirXpwqcVEcj7zMLQMDFURpR6vyU@pQZblxafPTD0Tcvvp8zRF1e6cLGIuWKUCvwG) Explanation: ``` char*v[99],*e; i,j,k; f(char*s) { // Set e to the end of s e=s+strlen(s); // Set s to the first character that is alphanumerical or an underscore. W() // While s hasn't moved past the end of the string ... for(i=0;s<e;) { // Store s in v[i], then increment i v[i++]=s; // Set s to the first character that isn't alphanumerical or an // underscore. W(!) // Set all characters between the current word and the next to 0, and // set s to the first character in the next word. W((*s=0)|) } // Iterate through the words with j. F(j) // Iterate through the words with k. F(k) // If words at index j and k are equal but j and k aren't the same // index, set the first character in word j to 0, marking the word // as a duplicate. strcmp(v[j],v[k])|j==k||(*v[j]=0); k=0; F(j) // For each word that hasn't been marked as a duplicate, increment k. *v[j]&&++k; // Return the number of words not marked as a duplicate. return k; } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~275~~ ~~254~~ ~~250~~ 249 bytes * -26 bytes thanks to ceilingcat To split the words, each uppercased word is stored in a list recursively. Duplicates are nulled out, preventing them from being scanned. ``` g(s,t,i)char*s,**t;{char*a[2]={0,t},**v,*u;for(;*s&&!isalnum(*s)&&*s-95;s++);u=*a=strdup(s);if(i=*u){for(;*u=*s&&isalnum(*s)|*s==95;*u++=~32&*s++);i=g(s,a);}else for(v=t;v;v=v[1])if(*v)for(i++,t=v;t=t[1];)*t&&!strcmp(*v,*t)?*t=0:0;s=i;}f(s){g(s,0);} ``` [Try it online!](https://tio.run/##bVHBTgIxEL3zFQMJZNstyYrxoE316geYeEAOy@4C1WULO9Oiruuv4xQk8eCl6Xsz7/XNtJiui@J4XCeoSFlRbPJWopKSdHe65/PZwnSZop7JoKTXK9cmWuJkMrSY143fJhLFZCJxenujMU2F9kbmBqkt/S5Boe0qsUZ60Z2VXGXxH@2XRGNYK32amu/rGVtFF2tiqFzovqqxgigOhnTQwYT51UKwrQwi0jZNFZmgyRAXtJDE4fj9YrtLYmYSD5JMdpdpNFb3Kw7VRe@MvY@2IdjmtkmCs6WAbgAQBweJcx6cEcDoaVPB3tviDZatOzSc5R1e/XaH4ELVAnG5zj8/oHTrkfqVOFhWClwLjSOgM6JNTmDxJNj7Csm65iJ4rOraKXh2bV0OL@QmktND5Gb/NsIJXfozPnsF8fcGfI27IYMaGAPxTk9Nu5ZHXiWjMYK5h3H5whG4QwHvk4TQg/74Aw "C (gcc) – Try It Online") Ungolfed (with a structure instead of an array): ``` struct list { char *data; struct list *prev; }; int g(char *s, struct list *t) { int i; char *u; struct list a={0,t}, *v; for(;*s&&!(isalnum(*s)&&*s-'_');s++); u=a.data=strdup(s); // skip spaces and duplicate the string locally if(i=*u){ // collect the word and uppercase it for(;*u=*s&&isalnum(*s)|*s=='_';*u++=~32&*s++); i=g(s,&a); // recursively generate list }else // end of string: process the words for(v=t;v;v=v->prev) // from the end, work backwards if(v->data) // if not a duplicate for(i++,t=v;t=t->prev;) // scan for duplicates t->data&&!strcmp(v->data,t->data)?t->data=0:0; // null out duplicates s=i; // return the count } int f(char *s) { g(s,0); } // initialize the end of list and (implicitly) return the count ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` │ÿîIΔ»╝H ``` [Run and debug it](https://staxlang.xyz/#p=b3988c49ffafbc48&i=To+be,+or+not+to+be,+that+is+the+question) This is a packed stax program. When unpacked, it is the following: ``` v"\w+"|Fu% ``` [Run and debug it](https://staxlang.xyz/#c=v%22%5Cw%2B%22%7CFu%25&i=To+be,+or+not+to+be,+that+is+the+question) # Explanation ``` v # lowercase the input string |F # get all regex pattern matches of regex "\w+" # \w+ u # uniquify % # length ``` [Answer] # [Go](https://go.dev), ~~181~~ 176 bytes ``` import(."regexp";."strings") func f(s string)int{m:=make(map[string]int) for _,w:=range MustCompile("\\w+").FindAllString(ToLower(s),-1){if _,o:=m[w];!o{m[w]=1}} return len(m)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVHBSsQwEL33K8acEmwL60l2qSCCeFAQXPCwuyzdNu3GTTI1Se1q6Zd4WQTvXv0U_8MPMG335CE83puZ5L3J-0eJh-8qzXZpyUGlQgdCVWhcTArlyGftiuj852vUaEwML_m-IrOYWGeELi1hQVHrDApqYZSY0K5V00SlO05VWi1GeeVl34sG1mEzTUyq_YN3tXVXqCohOSXLZXNKWHwtdH4p5cMwRed4iw031LIwmrBWFH4c_eWLZjU7wbbHZNJ1geGuNhok11Sx7uj7d7DWp6IM2sBamCawWI2GWkJCMvFny6XEqEEj8zNPM8z5Ol6XKIvY05u-GsJjXz75z2FgvTxH2PAQfDyNDtzI3DZ1IKxHDs81t06g7nsHKrIdbAw2Ggrcw1OtKgv4ws3QLdO3V8ixJN1xZYP1cWk-Rhvc-whOampDINEFCfsPYCzogmP2w2HEPw) Gets all words matching regex `\w+`, and adds them to a map (acting as a set in this case). Then it returns the number of items in the map (set). * -5 bytes by @The Thonnu [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ≔⦃⦄θFΦ⪪↧S⁻⪪γ¹⊞OE³⁶⍘ιφ_ι§≔θιιILθ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY7BSsNAEIbveYohp9myPRRBhJxqQShYWqg3EdnGTTIQdpOdWS0Un8RLD4q9-jh9Gzckp5_5mA--r0vZmFB6057PP1Gq-d31b8lMtcPTp4ZeFVnlA-ADtWID7ruWBB_9hw2lYYtr10XZSyBXo1IaNuQiT1-1hkVCu8jNtrPBiA-4MR3e3Gq4T_KkkYZqUPPXXA1LSsFYsJS1e7NH7BMceJHtkiG4MpwarKulwT45xTcfSp7yf5_z-Xubv1xnTx4OVkOqd15AxksaI0Cc1kIfLQt5l43mPw) Link is to verbose version of code. Explanation: Inspired by @KevinCruijssen's 05AB1E answer, so assumes the input only contains printable ASCII. ``` ≔⦃⦄θ ``` Start with an empty dictionary. ``` FΦ⪪↧S⁻⪪γ¹⊞OE³⁶⍘ιφ_ι ``` Split the lowercased input on all printable ASCII except the characters used to encode base 36 and `_`, and... ``` §≔θιι ``` ... set each word as a key in the dictionary. ``` ILθ ``` Output the final length of the dictionary. [Answer] # [Raku](https://raku.org/), 21 bytes ``` +*.lc.comb(/\w+/).Set ``` [Try it online!](https://tio.run/##ZYu9DoIwFEZf5aMxRgUhcXDQuLtr4mJi@CmCFi60RUTjs9cWR5ebnPOd23Ap1qYaMM2xM/4iFGmYUpXMonPvR/PwwLXZQsUD2DvH5PLZ2MOQkwQ7FhxtV6Z3JJL62sonbl3VKNCDS2g7i/g1IKMrC2xOSHgA@1mThv6RLmKNUo1x23GlS6pdvOdCUIATSZF5ThROLHvHq78AI3nMfAE "Perl 6 – Try It Online") This is an anonymous function. The argument (`*`) is converted to lowercase (`.lc`), then the substrings matching one or more word characters are extracted (`.comb(/\w+/)`) and converted to a set (`.Set`), which discards the duplicates. Finally, that set is expressed as a number (`+`), yielding its size. ]
[Question] [ [There are so many different ways to express whether something is true or not!](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) The goal of this challenge is to produce a [standardized](https://xkcd.com/927/) output of `truthy` or `falsy` for various input truthy and falsy values. For the purposes of this challenge, the following inputs are considered truthy: 1. A string representing a signed integer with a non-zero value (contains only the digits `[0-9]`, with an optional `-` at the beginning). Note that the string `-0` will never be given as input. A non-zero integer will never be preceded by a `0` (i.e. `01` will never be given as input, similarly `-01` will never be gien as input). 2. The case-insensitive strings equivalent to one of `defined`, `found`, `nonnil`, `non-nil`, `on`, `success`, `t`, `true`, `y`, and `yes` For the purposes of this challenge, the following inputs are considered falsy: 1. The string `0`. Repeated zeros (`00`, `00...`) will never be given as input. 2. An empty string 3. The case-insensitive strings equivalent to one of `f`, `failure`, `false`, `n`, `nan`, `nil`, `no`, `notfound`, `not-found`, `null`, `nullptr`, `off`, and `undefined` # Input The input is a string representing a truthy/falsy value. The string may come from any source desired (stdio, function parameter, etc.). There is no leading/trailing whitespace. The input is guaranteed to match one of the allowed truthy/falsy values above (i.e. you do not need to provide any error handling). # Output Your program/function must output a truthy/falsy value which represents the "truthy-ness" or "falsy-ness" of the input. You are only allowed to specify exactly 1 truthy and 1 falsy value which your output must convert the input to (these are your "standardized" truthy/falsy value). The output may be written to any sink desired (stdio, return value, output parameter, etc.). Please specify what `truthy` and `falsy` value you chose in your answer. Ex.: If you choose the string `true` as a truthy value, you cannot also have the integer `1` for truthy. # Test Cases Test cases are formatted as the first line is the input, and the second line is the output. ``` -1 true 1 true 1234 true -4321 true defined true deFined true Found true nonnil true non-nil true ON true SuCCess true T true true true y true YeS true 0 false '' (empty string) false faLSE false f false Failure false n false NaN false nil false no false notfound false not-Found false NULL false nullptr false OFF false unDefined false ``` # Scoring This is code-golf; shortest code in bytes wins. Standard loopholes apply. You may use any built-ins desired. [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` U|sG36ZA13\[BID1]m+g ``` Input is a string enclosed in single quotes. Output is `1` for truthy or `0` for falsy. [Try it online!](http://matl.tryitonline.net/#code=VXxzRzM2WkExM1xbQklEMV1tK2c&input=J2RlZmluZWQn) Or [verify all test cases](http://matl.tryitonline.net/#code=IkBnClV8c0AzNlpBMTNcW0JJRDFdbStnCl12IQ&input=eyctMScgJzEnICcxMjM0JyAnLTQzMjEnICdkZWZpbmVkJyAnZGVGaW5lZCcgJ0ZvdW5kJyAnbm9ubmlsJyAnbm9uLW5pbCcgJ09OJyAnU3VDQ2VzcycgJ1QnICd0cnVlJyAneScgJ1llUycgJzAnICcnICdmYUxTRScgJ2YnICdGYWlsdXJlJyAnbicgJ05hTicgJ25pbCcgJ25vJyAnbm90Zm91bmQnICdub3QtRm91bmQnICdOVUxMJyAnbnVsbHB0cicgJ09GRicgJ3VuRGVmaW5lZCd9). ### How it works ``` U|s % Take input implicitly. Interpret as number, absolute value, sum G36ZA % Push input again. Convert from base-36 13\ % Modulo 13 [BID1] % Push array [6 3 8 1] m % True if member: gives 1 iff the result from modulo 13 is in the array +g % Add, convert to logical. Display implicitly ``` This performs two tests on the input: 1. Try to interpret the input as a number, and detect if it is nonzero. The function used to interpret a string as a number outputs an empty array if it's not possible; and the sum of the entries of an empty array is `0`. So it suffices to try the conversion, take the absolute value, and sum. This gives a positive value if the input contains a nonzero number, and `0` otherwise. 2. Assuming the input string doesn't represent a number, we need to classify it into one of the two given sets. To do this, the input is interpreted as the digits of a number expressed in base-36, using alphabet `'01...9ab...z'`. The base conversion function is case-insensitive and ignores digits not present in the alphabet (in our case, `'-'`). It turns out that the modulo 13 of the resulting number is `1`, `3`, `6` or `8` for the truthy strings, and doesn't give any of those values for the falsy strings. So it can be used as a signature. We thus perform modulo 13 and see if the result is any of those four values. This gives `1` if it is, or `0` otherwise. The final result should be truthy if any of the two conditions is met, and falsy otherwise. So we add the two numbers resulting from 1 and 2 above and convert to logical, which gives `1` or `0` as standardized truthy/falsy values. [Answer] ## [Retina](https://github.com/m-ender/retina), ~~22~~ ~~24~~ 23 bytes *Saved 1 byte thanks to edc65* ``` i`^([-1-9sdty]|fo|n?on) ``` The whole code is just a regex. The `i`` at the start makes the regex case insensitive. Outputs `1` for truthy, `0` for falsey. [Try it online!](http://retina.tryitonline.net/#code=aWBeKFstMS05c2R0eV18Zm98bj9vbik&input=Zk91bmQ) [Answer] ## Batch, 142 bytes ``` @goto l%1 2>nul :l :l0 :lfailure :lfalse :ln :lnan :lnil :lno :lnotfound :lnot-found :lnull :lnullptr :loff :lundefined @echo 1 ``` Outputs 1 for falsy, nothing for truthy. [Answer] # JavaScript (ES6), 35 ~~39~~ *Edit* using the `n?on` trick, stolen from BusinessCat's answer *Edit 2* OP clarified, no leading 0s, saved 4 bytes ``` v=>/^([-1-9dsty]|fo|n?on)/i.test(v) ``` Simply returns `true` or `false` **Test** ``` f=v=>/^([-1-9dsty]|fo|n?on)/i.test(v) trues=[-1,1,1234,-4321,'defined','deFined','Found', 'nonnil','non-nil','ON','SuCCess','T','true','y','YeS'] falses=[0,'','faLSE','f','Failure','n','NaN','nil', 'no','notfound','not-Found','NULL','nullptr','OFF','unDefined'] console.log('TRUE: '+trues.map(x=>f(x))) console.log('FALSE:' +falses.map(x=>f(x))) ``` [Answer] # Python, 111 bytes ``` def b(s):s=s.lower();return s!='no'and not sum(map(ord,s))in[0,48,323,744,523,877,110,785,443,922,315,317,946] ``` Tests on sum of ASCII values, extra check for `no` since `on` has the same value. * Edit1: forgot to test on integer values. Now checking for false inputs [Answer] # Python, ~~129~~ ~~79~~ 78 bytes Gotta submit fast! ``` lambda n:n.lower()[:3]in" 0 f n no nil fai fal nan not nul off und".split(" ") ``` True is false and false is true; I have a nice rhyme for this, I really do (not) [Answer] # Python, ~~83~~ 75 bytes ``` import re def f(s):return re.search(r'^([-1-9dsty]|fo|n?on)',s.lower()).pos ``` Returns 0 on success, AttributeError on failure. Now using edc85's regex to save 8 bytes. [Answer] ## PowerShell v2+, ~~39~~ 37 bytes ``` $args[0]-match'^([-1-9dsty]|fo|n?on)' ``` Presumes that the answer to @feersum's question is "No, truthy integers may not start with a `0`." Port of @edc65's [regex JavaScript answer](https://codegolf.stackexchange.com/a/89350/42963), with my own `1-9` substitution instead of `\d`. Uses @BusinessCat's [`n?on` trick](https://codegolf.stackexchange.com/a/89358/42963) to golf further. Outputs literal Boolean `$true` or `$false` values, which when left on the pipeline and sent through an implicit `Write-Output` at the end of execution results in `True` or `False` being printed to the console. --- If the answer is "Yes, truthy integers can start with `0`," then the following changes need to be made for **~~51~~ 49 bytes** ``` param($n)$n-ne0-and$n-match'^([-\ddsty]|fo|n?on)' ``` --- If you don't like regex, go for PowerShell v3+ and the following at **107 bytes** ``` param($n)$n-and$n-notin-split'0 f failure false n nan nil no notfound not-found null nullptr off undefined' ``` This takes the string of falsey values, `-split`s them on whitespace, and uses the `-notin` operator to check the input `$n` against that array of strings (which is, by default, case-insensitive). Requires the `$n-and` to check against the empty string. [Answer] # PHP, 50 bytes ``` <?=preg_match('%^([-1-9dsty]|fo|n?on)%i',$argv[1]) ``` prints `1` for truthy, nothing for falsy tried to come up with a different solution, but the shortest regex for falsy is 3 bytes longer than that for truthy: `%^(0|fa|f?$|n(?!on)|of|u)%i` [Answer] # [Zsh](https://www.zsh.org/), 32 bytes ``` grep -Pi '^([-1-9dsty]|fo|n?on)' ``` [Try it online!](https://tio.run/##LY5NawIxGITv8ytyKNoeAq56KSx6UHNa1sK2h1IqBPJGA@GN5INia3/7drfKDPOcZpjvdOq/Ts6TiKSN0DBB/PTHSGchX5yYHh4/ZCWfTcqXz6sNV14Hfpr2v5OVrOv6QWPM9dBi6mWFQfPFEnK5mFcwZB2TGaj@qUJhAw7Mzo@QI/cturLZUEp4RY6FcME7dZgBVjfdDhZKO18igdHqFrfy4Gzve1neltu3pgEX7885Yq8UCm/vF6z2ifAH "Zsh – Try It Online") Outputs via exit code; 0 is truthy, 1 is falsey [Answer] ## Python, 83 bytes ``` lambda x:x.lower()[:3]in['fou','non','on']or x[:1].lower()in'dsty-123456789'and''<x ``` <https://repl.it/ClgO/1> ]
[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/115752/edit). Closed 6 years ago. [Improve this question](/posts/115752/edit) > > yOu wiLl bE giVen A sTriNg wHich cOnsiSts oF pRintAble asCii > cHarActErs. > > > yOu iTeraTe tHrougH thE sTrIng tHen chAnge rAndOM(uNifoRm, 50% cHanCe uPPercAse) lEtteRs to > uPPercAse aNd eVerytHing elSe tO lOwercAse. > > > tHat'S iT. > > > (sorry for the punctuation, it was for the concept of the question) Readable version: > > You will be given a string which consists of printable ASCII > characters. > > > You iterate through the string and change random(uniform, 50% chance uppercase) letters to > uppercase, and everything else to lowercase. > > > that's it. > > > # exaMplEs ``` iNpuT => pOssiBle oUtPUt Programming puzzles and Code Golf => pRogRaMMiNg pUzzlEs aNd coDe goLf dErpity deRp derP => deRpiTy dErp DerP CAAAPSLOOOCK => cAAapslOoocK _#$^&^&* => _#$^&^&* ``` [Answer] # C – 65 bytes Pretty good for a mainstream language! ``` main(c){while((c=getchar())>0)putchar(isalpha(c)?c^rand()&32:c);} ``` Uses XOR to randomly flip the bit at `0x20` for each alphabetic character. Program assumes ASCII character set and that `EOF < 0`. Sample run on its own source! ``` $ main < main.c MaIN(c){WhILe((C=GETChAr())>0)pUtCHaR(iSALpha(C)?C^rANd()&32:C);} ``` Very derpy. [Answer] ## JavaScript, 87 bytes ``` function(s){return s.replace(/./g,c=>Math.random()<.5?c.toLowerCase():c.toUpperCase())} ``` 68 bytes in ES6: ``` f= s=>s.replace(/./g,c=>c[`to${Math.random()<.5?`Low`:`Upp`}erCase`]()) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,ŒsXµ€ ``` **[Try it online!](https://tio.run/nexus/jelly#@69zdFJxxKGtj5rW/P//P6AoP70oMTc3My9doaC0qiontVghMS9FwTk/JVXBPT8n7Wtevm5yYnJGKgA)** ### How? Lower casing all chars of the input and then uppercasing each with 50% probability is the same as choosing one of the original char and the swapped-case char with equal probability... ``` ,ŒsXµ€ - Main link: string s µ - monadic chain separation € - for each char c in s , - pair c with Œs - swapped case of c X - choose a random item from the list (of the two chars) - implicit print ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~64~~ 60 bytes ``` -join([char[]]"$args".ToLower()|%{"$_".ToUpper(),$_|random}) ``` [Try it online!](https://tio.run/nexus/powershell#@6@blZ@ZpxGdnJFYFB0bq6SSWJRerKQXku@TX55apKFZo1qtpBIPEggtKAAJ6KjE1xQl5qXk59Zq/v//X93Z0dExINjH39/f2Vv9a16@bnJickYqAA "PowerShell – TIO Nexus") (make sure that "disable output cache" is checked if you want random results) Exact translation of the challenge. Takes the input string, `ToLower()`s it, converts it to a `char` array, loops through each character `|%{...}`, and randomly selects between either the existing character or the uppercase variant. Then `-join`s them all back together into a single string. This works because `ToUpper` and `ToLower` only affect alphabetical characters, leaving punctuation and the like unchanged. *(Dennis fixed the alias list on TIO so that `Random` isn't trying Linux `random` but correctly aliases to `Get-Random` as a PowerShell command, as it should. Thanks, Dennis!)* [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~13~~ 12 bytes ``` "@ktXkhlZr&h ``` Try it at [**MATL Online**](https://matl.io/?code=%22%40ktXkhlZr%26h&inputs=%27RaNdOm%27&version=19.9.0) **Explanation** ``` % Implicitly grab input as a string " % For each character... k % Convert to lowercase tXk % Make a copy and convert to uppercase h % Horizontally concatenate these two characters lZr % Randomly select one of them &h % Horizontal concatenate the entire stack % Implicit end of for loop and implicit display ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` ®m"uv"gMq2 ``` [Try it online!](https://tio.run/nexus/japt#@39oXa5SaZlSum@h0f//Sm75@QpOiUVKX/PydZMTkzNSAQ "Japt – TIO Nexus") ### Explanation So this is kind of a cheesy hack, but it works. In JavaScript you can do something like ``` x[`to${Math.random()<.5?"Upp":"Low"}erCase`]() ``` to randomly convert `x` to upper- or lowercase. In Japt, the equivalent functions are `u` for `toUpperCase` and `v` for `toLowerCase`. But in Japt there is no direct way to get a calculated property value (`x[expression]` in JavaScript). One of my favorite features of Japt is that if you have a function which is composed of a single method call (e.g. `mX{Xq}`, or `.m(X=>X.q())` in JS), you can leave out everything except the name of the method, e.g. `mq`. The compiler then turns this into a string which gets passed to the original method call (`.m("q")`), and the method turns this back into a function. So there's no difference between `mq` and `m"q"`; both produce the same output. Now, where I was going with this: while we can't directly call a random method on a string, we *can* call `m` on that string with a random method name. So, for the explanation: ``` ®m"uv"gMq2 ® // Replace each char in the input by this function: m // Replace each char in this char by this function: g // the char at index Mq2 // random integer in [0,2) "uv" // in "uv". // This randomly calls either .u() or .v() on the char. // Implicit: output result of last expression ``` [Answer] # PHP, 53 Bytes ``` for(;a&$c=$argn[$i++];)echo(lu[rand()&1].cfirst)($c); ``` [Answer] # [Perl 5](https://www.perl.org/), 26 bytes 25 bytes + `-p` flag. ``` s/./rand 2&1?uc$&:lc$&/ge ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F@sr6dflJiXomCkZmhfmqyiZpUDJPTTU///DyjKTy9KzM3NzEtXKCitqspJLVYAqXTOT0lVcM/PSeNKcS0qyCypVEhJDSoAEkUBX/PydZMTkzNSAQ "Perl 5 – TIO Nexus") [Answer] # [Perl 6](https://perl6.org), ~~32~~ 29 bytes ``` {[~] .comb.map:{(.lc,.uc).pick}} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9Xx1dF6ugl5yfm6SXm1hgVa2hl5Oso1earKlXkJmcXVv7vzixUgGkVqM4p7SoQNP6f0BRfnpRYm5uZl66QkFpVVVOarFCYl6KgjPIQPf8nLSvefm6yYnJGakA "Perl 6 – TIO Nexus") ``` {S:g/./{($/.uc,$/.lc).pick}/} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9Xx1sla6vp1@toaKvV5qsAyRzkjX1CjKTs2v1a/8XJ1YqgBRqFOeUFhVoWv8PKMpPL0rMzc3MS1coKK2qykktVkjMS1FwBpnmnp@T9jUvXzc5MTkjFQA "Perl 6 – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), ~~77~~ 74 bytes ``` lambda s:"".join(map(choice,zip(s.upper(),s.lower()))) from random import* ``` [Try it online!](https://tio.run/nexus/python2#FYo5DsIwEAB7XrFy5aDgByBRUdDyAJrFR2Jke1frRJH8b2pjppkpJtxePWF@O4R6Vcp8KBadkbVdKVo/t8i6mp3Zi57mahId/xqcglAGweKGYmaS7dxZYtkgaPUUWgRzjmUB3ltLvsJY4U7Ow4NSUFP/FrpYtKv/AQ "Python 2 – TIO Nexus") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~12~~ 10 bytes ``` £M¬?Xv :Xu ``` ### Explanation: ``` £M¬?Xv :Xu £ // Iterate through the input. X becomes the iterative item M¬ // Return a random number, 0 or 1 ? // If 1: Xv // X becomes lowercase : // Else: Xu // X becomes uppercase ``` [Try it online!](https://tio.run/##y0osKPn//9Bi30Nr7CPKFKwiSv//V0rLz1dISixSAgA) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes *1 byte removed using [Jonathan Allan's idea](https://codegolf.stackexchange.com/a/115764/36398) of directly changing case.* ``` "@rEk?Yo]&h ``` Try at [**MATL online!**](https://matl.io/?code=%22%40rEk%3FYo%5D%26h&inputs=%27Programming+puzzles+and+Code+Golf%27&version=19.9.0) ### Explanation ``` " % Implicit input. For each @ % Push current char r % Random number uniformly distributed on (0,1) Ek % Duplicate, floor: gives 0 or 1 with the same probability ? % If nonzero Yo % Change case. Leaves non-letters unaffected ] % End &h % Horizontally concatenate evverything so far % Implicit end and display ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` vyDš‚.RJ ``` [Try it online!](https://tio.run/nexus/05ab1e#@19W6XJ04aOGWXpBXv//BxTlpxcl5uZm5qUrFJRWVeWkFisk5qUoOOenpCq45@ekfc3L101OTM5IBQA "05AB1E – TIO Nexus") **Explanation** ``` v # for each char y in input yDš‚ # pair lower-case y with upper-case y .R # pick one at random J # join to string ``` [Answer] # JavaScript, 77 bytes ``` x=>x.toLowerCase().split``.map(y=>Math.random()*2|0?y:y.toUpperCase()).join`` ``` [Try it online!](https://tio.run/nexus/javascript-node#bY0xT8MwFIR3fsVTh9ZGqoUYkVKGDl2KVCG655G8xAb7vcg2oo7428zBILEgbrs7fXdDs1ya3cVkOco7xT0mUtqkybvctibgpEqze8BsTUTuJSh9fftxc1/uSkXO0/SLaPMijtt26YSTeDJeRjWoFVattL76Ez9SfeiQcwKMBN69EiAXkGwpQsDOOiYDT5bKpvbkfnKEZ2IaXAb5NhZnjL35Z/4UZYwYguMRTm/z7CnBGvbSExzED5VYPlm2Xf2hLw "JavaScript (Node.js) – TIO Nexus") [Answer] # [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` qel{2mr{eu}&}% ``` [Try it online!](https://tio.run/nexus/cjam#@1@YmlNtlFtUnVpaq1ar@v9/QFF@elFibm5mXrpCQWlVVU5qsUJiXoqCc35KqoJ7fk7a17x83eTE5IxUAA "CJam – TIO Nexus") **Explanation** ``` q e# Read the input el e# Make it lowercase { e# For each character in it 2mr e# Randomly choose 0 or 1 {eu}& e# If 1, make the character uppercase }% e# (end of block) ``` [Answer] # Pyth, 5 bytes ``` srLO2 ``` [Test suite](https://pyth.herokuapp.com/?code=srLO2&test_suite=1&test_suite_input=%22Programming+puzzles+and+Code+Golf%22%0A%22dErpity+deRp+derP%22%0A%22CAAAPSLOOOCK%22&debug=0) ``` srLO2 srLO2Q Variable introduction L Q Map over the input r Set the case of each character to O2 Random number from [0, 1]. 0 means lowercase, 1 means uppercase. s Concatenate ``` [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 136 bytes ``` >~:0`!#@_:"@"`!#v_:"Z"`!#v_:"`"`!#v_:"z"`!#v_, ^,< < < < >?< < -*84< >84*+^ ``` [Try it online!](https://tio.run/nexus/befunge#bVLBjtowFLznKybbSzcFCiyH1YrSPVS9dbdS1UsP7Brygi2cOLKdoHDg1@lzTCra7ZMSTZx582Zecl6dHqav6bvHl4ebxxsGLYNfA3gdwDGCUbIeLcHV3/4Cf2qZYPX57fFb8ji7XzAZq/tF9mF9PksFasl2M6gSFR3SWMik0blDU8PVxu4zlB0qURKUw174DpvGo8FWVHxpDX7j7yS@09Pu5@wJ5ivy6bRMBzlt9GQyEe7S4ojCvDAYVlS56ZnwUniHg@ygmMaSkiyNMGd18hci6lpDqz2FkeuXNcsGqdkdOhLWgW3jPR@UwjeWsAjGxY7dSZOmtyzc985xEH4roapW5GRx5I7Dx8DdKasLS6qKMhsFVbDr3FQ@tiqPnIRmuvKsx4ZNY1GI1ljleU4LJ03YIzbb5tgTfjxzXQd1ktyQZw5TYMsajvqlKrbGsy6hS8MhrpJ/uo0uvKQOTnQBRFIPyFpF9mrl/ElF51hUmjrELgU3C218mBpzun7NcIazt/1a@bWLrsqSKu/IBcUk@RJyPH/jSv8pLMfjcWjdsOLgV@wEP/A34gGS2Iw3JtdRjNW04WnM5LxFwcejJMlw@s9fdMrwGw "Befunge – TIO Nexus") There is a lot of whitespace that I think is possible to get rid of. Befunge doesn't have a way of figuring out what's a letter and what isn't, so this is what I'm doing on the first row. [Answer] # [Bash](https://www.gnu.org/software/bash/), 64 bytes first try ``` a=$(shuf -e -n 13 {A..Z}|tr -d "\n");b=${a,,};tr $b $a <<<${1,,} ``` [Try it online!](https://tio.run/nexus/bash#@59oq6JRnFGapqCbqqCbp2BorFDtqKcXVVtTUqSgm6KgFJOnpGmdZKtSnaijU2sNFFRJUlBJVLCxsVGpNgQK/f//P6AoP70oMTc3My9doaC0qiontVghMS9FwTk/JVXBPT8n7Wtevm5yYnJGKgA "Bash – TIO Nexus") shuffles capital letters, takes first 13, removes newlines and saved to $a. $b holds $a to lowercase. input is set to lowercase by ${1,,} and passed as a heredoc to tr which replaces each ocurrence of $b by $a This is somewhat non compeating because the same letter is always capitalized. [Answer] # JavaScript + HTML, 115 bytes ``` <input oninput="this.value=this.value.toLowerCase().split('').map(v=>Math.random()<.5?v.toUpperCase():v).join('')"> ``` [Answer] **Bash, 162 Bytes** ``` a=$1 b=1 c="echo $a|head -c$b|tail -c1" while(($b<=${#a})) do r=$[RANDOM%2] if [ $r = 1 ] then d=$(eval $c);echo -n ${d^} else echo -n $(eval $c) fi b=$[b+1] done ``` Pretty self explanatory. Takes input from command line arg, writes to stdout. Run like `derpifier.sh "Derp this"` Man, once I start applying the [tips](https://codegolf.stackexchange.com/questions/15279/tips-for-golfing-in-bash%20Tips) the code shrinks fast. [Answer] # Swift - way too many bytes (~~176~~ 167) `uppercased()`,`lowercased()`,`arc4random_uniform()` really kill the score, besides for me having to add a function since Swift has no standard input method! ``` import Foundation func g(x:String){var result="";for i in x.characters{let e=String(i);result+=(arc4random_uniform(2)>0 ?e.uppercased():e.lowercased())};print(result)} ``` Function with usage: `print(g(x: "Your String Here"))` ]
[Question] [ **This question already has answers here**: [Valid Through The Ages](/questions/25913/valid-through-the-ages) (27 answers) Closed 8 years ago. Write a program that: * if a compiled language is used, compiles without errors * if an interpreted language is used, runs without syntax errors for every major release of your language, and produces different output for every major release under which it is compiled/run. (It may produce the same or different output for versions within the same major release, as long as it varies among major releases.) You may not output or use any part of the language version in your program. A "major release" of a language is defined to be a publicly available release that added to the major version number. For example, C# has had 6 major releases, C has had 3 (K&R is not a numbered version and does not contribute to the count), and Ruby has also had 3 (due to version 0.95). What number constitutes the major version number can change over time (Java has had 8 major releases). Any language used in this challenge must have: * At least three major releases, and * A dedicated Wikipedia article. [Answer] # Python ``` if 2 + 2 is 4: # Lies must be abolished try: fact = '2 + 2 = %r' % 5 exec('True = False') exec('assert (2 + 2 == 5) is True') except ValueError: print('War is peace.') except NameError: print('Freedom is slavery.') except SyntaxError: print('Ignorance is strength.') else: # All is good print('Big Brother is watching you.') ``` *(Edit: Had to make a change because string formatting was actually introduced in... [0.9.9](http://svn.python.org/view/*checkout*/python/trunk/Misc/HISTORY))* Tested on the following versions: * [**0.9.1**](https://www.python.org/download/releases/early/): Prints `Big Brother is watching you.` because 2 + 2 is *5*.\* * [**1.5**](https://www.python.org/download/releases/): Prints `War is peace.` since `%r` string formatting is unavailable, raising a `ValueError`, * 2.1: Prints `Freedom is slavery.` since `True` is not defined, raising a `NameError`, * 3.4: Prints `Ignorance is strength.` since `True` cannot be assigned to, raising a `SyntaxError`. As a bonus, Python 2.3 to 2.7 gives no output, since the assertion passes. Note that there are four spaces on both "blank" lines, and the file also needs to have a trailing newline. \* `is` checks *object equality*, and only from [1.0.0 onwards](http://svn.python.org/view/*checkout*/python/trunk/Misc/HISTORY) were small integers shared. You can still see the effect today by trying larger numbers, e.g. `999 + 1 is 1000` gives `False`. [Answer] # Python Typical sunday afternoon in a house of three brothers. ``` try: # The night before the exam. assert(2/5 < 3/5) # Math is hard! print("Be quiet!") except: # Options: 1. Play. 2. Do nothing. try: print(__import__("this").s) except: "Too afraid to snap back." ``` ### Output ``` $ # Older brother: $ python3.4 123.py Be quiet! $ $ # Much younger brother: $ ./python1 123.py $ $ # Slightly younger brother: $ python2.7 123.py The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Gur Mra bs Clguba, ol Gvz Crgref Ornhgvshy vf orggre guna htyl. Rkcyvpvg vf orggre guna vzcyvpvg. Fvzcyr vf orggre guna pbzcyrk. Pbzcyrk vf orggre guna pbzcyvpngrq. Syng vf orggre guna arfgrq. Fcnefr vf orggre guna qrafr. Ernqnovyvgl pbhagf. Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf. Nygubhtu cenpgvpnyvgl orngf chevgl. Reebef fubhyq arire cnff fvyragyl. Hayrff rkcyvpvgyl fvyraprq. Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff. Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg. Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. Abj vf orggre guna arire. Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr! ``` # How it works ``` try: assert(2/5 < 3/5) # In Python 3, '2/5' and '3/5' are floats. # In lower versions, they're ints and the assertion fails. print("Be quiet!") # Python 3 prints this and exits. # Lower versions already caught an exception. except: try: print(__import__("this").s) # Try importing 'this' (an easter egg which prints the Zen of # Python) and printing 'this.s' (same old Zen with ROT13 obfuscation). # The easter egg doesn't exist in Python 1 and an exception is raised. except: "Too afraid to snap back." # Bare string. Would be printed in REPL; does nothing in a program. ``` [Answer] This C++03 C++11 and C++14 program prints old, medium or new: (C++03 is a set of technical corrections to C++98: compilers consider the two to be synonymous) ``` #define M(x, ...) __VA_ARGS__ int a[] = { M(1'2, 3'4, 5, 0) }; const char *b[]={ 0, "is", "the", "best", "always", "new" }; struct foo { ~foo() { throw std::string("old"); } }; void done() { std::cout << "medium" << std::endl; std::exit(0); } int main() { if (b[a[1]]) { std::cout << b[a[1]] << std::endl; } else { std::set_terminate(done); try { foo test; } catch( std::string c) { std::cout << c.c_str() << std::endl; } } } ``` [live example](http://coliru.stacked-crooked.com/a/3bf40368ad0ea99e) There are a few ways to do this; I figured out ways that current versions of clang and gcc support when you tell it to compile in a particular version mode. It relies on a few things. To distinguish C++14 from C++11/C++03, it uses `'` as an internal delimiter in integer constants. Then I discard a leading token, which either contains a `,` or not depending on the C++ version. The 2nd element of the array is now either `0` or `5`. I use this to look up in another array -- entry `0` is null, and entry `5` is `"new"`. If it is non-null, I print it and am finished (for C++14). To distinguish C++03 from C++11, it throws from a destructor. In C++11, all destructors are implicitly noexcept, which calls the `std::set_terminate` handler. I install a terminate handler that prints out `"medium"` (for C++11), and in the catch block I print `"old"` (for C++03). Breaking changes stolen from [here for C++11](https://stackoverflow.com/questions/6399615/what-breaking-changes-are-introduced-in-c11) and [here for C++14](https://stackoverflow.com/questions/23980929/what-changes-introduced-in-c14-can-potentially-break-a-program-written-in-c1). [Answer] # **C** **Golfed**, for the hell of it. ``` O;main(o){o=((O='\o'),O);} ``` > > *It does nothing.* > > > Fortunately. I didn't find anything relevant, so this is just about playing with *undefined behaviors* again. --- ### **C89** > > **§3.1.3.4 7 — Character constants** > > > In addition, certain nongraphic characters are representable by escape sequences consisting of the backslash `\` followed by a lower-case letter: `\a` , `\b` , `\f` , `\n` , `\r` , `\t` , and `\v` . If any other escape sequence is encountered, the behavior is undefined. > > > Yup. `'\o'` implies an *undefined behavior* in **C89**, while it is only *implemention-defined* in **C99** and **C11** (it gives me `'o'`). --- ### **C99** This is where it gets tricky. > > **§6.5.16 4 — Assignment operators** > > > (...) If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior is undefined. > > > This is a weird wording specific to **C99**. A sequence point is needed after `(O='\o')`: `,` do the trick. Since it is necessary to *access* the result (i.e. *"to read or modify the value of an object"* as defined by the standard, whose identifier is `O`) to store it in `o`, the behavior is undefined. --- ### **C11** All of that does not apply in **C11**. It should work fine while compiling in **C11**. Nobody uses **C11**. ]
[Question] [ ## Challenge We take three positive integers `a`, `b`, and `c` as input. Using these integers, first create a sequence in the range `[0, c]` (inclusive on both ends), in steps of `b`. For example, for `a=4, b=2, c=100`, the sequence would be `[0,2,4,...,96,98,100]`. For every number in this sequence which is divisible by `a`, replace it with the next letter in the lowercase alphabet, starting with the letter 'a' and wrapping back around to 'a' after you reach 'z'. ## Example: Input: `a=4, b=2, c=100` Output: `a2b6c10d14e18f22g26h30i34j38k42l46m50n54o58p62q66r70s74t78u82v86w90x94y98z` ## Challenge rules: * You can assume that `a`, `b`, and `c` are positive integers only, where `b ≤ a ≤ c`. * You can assume `a` is a multiple of `b`. * You can assume `c` is divisible by `b`. * The preferred output is a single concatenated string as above, but a list/array is acceptable as well. ## Test cases: ``` Input: a=4, b=2, c=100 Output: a2b6c10d14e18f22g26h30i34j38k42l46m50n54o58p62q66r70s74t78u82v86w90x94y98z Input: a=9, b=3, c=174 Output: a36b1215c2124d3033e3942f4851g5760h6669i7578j8487k9396l102105m111114n120123o129132p138141q147150r156159s165168t174 Input: a=10, b=2, c=50 Output: a2468b12141618c22242628d32343638e42444648f Input: a=25, b=1, c=25 Output: a123456789101112131415161718192021222324b Input: a=6, b=6, c=48 Output: abcdefghi Input: a=6, b=3, c=48 Output: a3b9c15d21e27f33g39h45i Input: a=2, b=1, c=100 Output: a1b3c5d7e9f11g13h15i17j19k21l23m25n27o29p31q33r35s37t39u41v43w45x47y49z51a53b55c57d59e61f63g65h67i69j71k73l75m77n79o81p83q85r87s89t91u93v95w97x99y ``` **I'd really like to see an answer in PHP**, but this challenge is open to any language. This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), so the answer should be as short as possible. [Standard rules apply for functions/programs](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) and [default loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). [Answer] # [PHP](https://php.net/), 67 bytes First of all, thanks for posting such a cool challenge! I really enjoyed solving it :) Now, here's my 67 byte solution: ``` <?for(;$i<=($p=$argv)[3];$i+=$p[2])echo$i%$p[1]?$i:chr($l++%26+97); ``` To run it: ``` php -n <filename> {a} {b} {c} ``` Or [Try it online!](https://tio.run/##DchBCoAgEADAz2ygSAczilLpIeIhpFIIXSx6flvHGYxIZJa9VKYhGcsALaz1eLhT/h9hAV3n@RZigdT8kH6BNIdYGZxCNN0gppFrIppIkRz7t@CdSr6ozR8 "PHP – Try It Online") --- Here's the same solution ungolfed and with explanation comments: ``` $a = $argv[1]; $b = $argv[2]; $c = $argv[3]; $letter = 'a'; for ($i = 0; $i <= $c; $i += $b) { if ($i % $a) { // If $i is divisible by $a, the modulo (%) operator will return a remainder of 0, which PHP sees as a falsey value. echo $i; } else { $letter++; $letter %= 26; // Wrap $letter around to `a` after it gets to `z`. echo chr($letter + 97); // Use PHP's chr function to get the character. 97 is the index of `a`. http://php.net/manual/en/function.chr.php } } ``` --- I did a 60 byte solution, but it doesn't wrap around :( ``` <?for($l=a;$i<=($p=$argv)[3];$i+=$p[2])echo$i%$p[1]?$i:$l++; ``` [Try it online!](https://tio.run/##DchJCoAwDADAz0SoFKEuJ2voQ6QHEZdAaYKKzzf2OCOnqE5h58tAwsUDTWhAEJbreOu5j2UsgsxdrLf1ZKCqoI0BaIRkrVfVQTttnftYHuJ8a5N/ "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 bytes ``` ;0ôWV £CgX/U ªX ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=OzD0V1Ygo0NnWC9VIKpY&input=NAoyCjEwMA==) ### Explanation ``` ;0ôWV £CgX/U ªX Implicit: U, V, W = inputs ; Reset C to the lowercase alphabet (among other variable resets). 0ôWV Create the inclusive range [0...W], using a step of V. £ Map each item X by this function: CgX/U Get the character at index (X / U) in the lowercase alphabet. If X is not divisible by U, this is a non-integer and the result is undefined. ªX In this case (literally, if falsy), replace it with X. Implicit: output result of last expression ``` [Answer] # [R](https://www.r-project.org/), ~~65~~ 63 bytes ``` function(a,b,c,z=seq(0,c,b)){z[x]=rep(letters,sum(x<-!z%%a));z} ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ0knWafKtji1UMMAyErS1Kyuiq6ItS1KLdDISS0pSS0q1ikuzdWosNFVrFJVTdTUtK6q/Z@mYaJjpGNoYKD5HwA "R – Try It Online") *2 bytes saved thanks to JayCe!* Returns a list of strings, as R will coerce numbers to strings. To print, simply replace the trailing `z` with `cat(z,sep="")`. [Answer] # Clojure, 84 79 77 bytes ``` #(for[i(range 0(inc %3)%2)](if(=(mod i %1)0)(char(+(mod(/ i %1)26)(int \a)))i)) ``` Givin' Lisp a little love [Try it online!](https://tio.run/##NYxNDoIwFAav8iWG8F5c2JYfdeHKYyCLBovWQGlqXXh6LKi7ySQz3TA9XsHM5IN1cXCgUXtQ79BE84xn/TQtSHs/vOcN9VNoLAXtbgaCrOuQFZwpbsn2dKJxusIiY8HU3XWg7WJotzpVcwoiLpqZLfP83zOjyamEghSCkdMRBeS@XFCKpKvVqgoSqlqwRo3y8KXiR6le@zadPw "Clojure – Try It Online") (-7 bytes thanks to @NikoNyrh!) [Answer] # Java 10, ~~93~~ 83 bytes ``` (a,b,c)->{var r="";for(int i=0;i<=c;i+=b)r+=i%a<1?(char)(i/a%26+97):i+"";return r;} ``` Try it online [here](https://tio.run/##pVPfb9MwEH7nrzCRkBLFFN/5Rxy6gpBgEgLEA4/THhzXad2laZe4ZWPq3z6cdh3d4I1L4kui777vzr5bmK15vZhe3a83VeMtsY3pe/LN@JbcvSDRfBtcVxvryPlq9fBvsB@h8@2MVKZLI4QYOiBJdXA2G@@Bu/36QN0HE6LbrvyULKNAeqC4uCSmm/XZCfegVMdnQu5TQytqs9fv7ramI90kScb16iDpJ2zszyZ27PNJlXX5xL8yZ/A@tXPTZal/Y16hyssie@vzGNW5sOla0o1390eZ8aNgpBvSiIJ3gpYUGEVJVbxg9xxUDSCknCKFCOD/gNgBAoxRKASVey6hhxuLE@xj9e5m7Wxw0yEqMVgpC2wKwoGuEWeo5px5LhZcXwlshFpK1kqxknqt8FqprmB9IUKhNxq3Wv0s2U0pbkv9K6GJ4aoCBGkRUEw549zxUmAttISZLBSbK6VKX8hCL7TQxVXJS9UAQ2ByCYOJFpAB8hVgCRzXwDUIuAZRgGQdSAWy7EFJUDrEagdNFEoPqgIUaIuIAhXqKUcuuOLaCRRCKKHrARyphVSFLoFFNQQewyIZFKChxJhIjOcoqgFb2amrZ3O/L6wqLcgpgsOi5nzGy7mQ/hS1uGqW7Wp93fVhs/15c/vLVMnJ7j82Udx1No7ujJhR49pZmI9JnvvTdhwsuD6ksScpMRf@kpJqv9r9ejzA@JH9UdidTkDntya4JyOwZ3zo9MPUPJshepyxI3/29/gZGzamiTVEktEwi5EjxtuTPHydHglG7jqi@/QQlT2v8cdtH9xytNqEUUy4DU2bJmmSmzyhJMmrg7N5kpHJu/h2YMkTkn7/kiWnlRPX9O7/yI8pR/qXkydi5x8@f/308angw1bv7n8D). Thanks to [Scrooble](https://codegolf.stackexchange.com/users/73884/scrooble) for golfing 10 bytes. Ungolfed: ``` (a, b, c) -> { // lambda taking 3 integer arguments and returning a String var r = ""; // we build the result String in steps for(int i = 0; i <= c; i+=b) // loop over the range [0,c] in steps of b r += i % a < 1 ? (char) (i / a % 26 + 97) : "" + i; // if i is a multiple of a, append the next letter to r as a char, else append i return r; // return the result } ``` [Answer] # [Perl 6](https://perl6.org), ~~60~~ 50 bytes ``` ->\a,\b,\c{[~] (0,b...c).map:{$_%a??$_!!('a'..'z')[$++%26]}} ``` [Test it](https://tio.run/##ZVBNU9swEL37V4iMqZPGGO1qJcukhl650EtvhGFs2UkMiWNih/Ix4a@nUsIQWjwjr@btm/ehplzN1XbdluxRRWbkeYtn9s0si5Kl25PzcRaO83BsXq/fblifh3kURWYQLbLm7NW/Pc4uLvzbo6N@kAVRFLwEg2t/ODxGdbPZbP3vl1dRPT@papay3rge172RE//ZlW1noXlVl@1eyWNscdae2sFYkKUB839k55YyLoYsCIM9nu/w/Atudrh5x/fYr3XXrLszt1jurrvtlduejuxv6AxCN/L9MHa8fZBD1svSPSVP9xyTOlLP23juqX7bCiOvmWc1G@76jLzJcvVe7eSc9ZmfhczP7TH2lE9NabqysNeibA0bMFe5apl7576lWqZvBl@Z3mZ7WbsmLEvJhUGXBDj33ht6GebKAC@AStATxCmqmeCVoDuh7wnnpBaS15KWUjcKH5RaxbyNqYv1WuOjVn8S/pTQc6JfPO/DKnFWYmcV08FKqBwQpEFAKgQXohQJ4YS0hKmMFZ8ppZIqlrG@06Tj@0Qkag4cgcsFuI9qQA4oloAJCGxAaCB4AIpB8hVIBTJpQUlQunPOh0TAP9rLz@VJaZeJQIE2iEioUBcCBQkldElIRIr05JMUSicFTgrlQcrGIqlinQC3SRGEFbVBIAYNCdoSVl0g5Z@UlBNSToj0QSg3RTmZzqr/ieJfIstEnhiQBUKJ8USIqUhmJKu/ "Perl 6 – Try It Online") ``` {$^a;(0,$^b...$^c).map:{$_%$a??$_!!chr 97+$++%26}} ``` [Test it](https://tio.run/##bVBdU9swEHz3rxAZ04QmBN3pJEtJDX3lhb70kYGxZSUxJI6JHcrHpH89lRKG0FLNSKfZ29nbvdqt5mq7bhx7VEM7jqLFM/til4Vj6fY1vsnGPT6Ib/LhcBjf2JPhIqtHr/HtcZxdXMS3R0d2tmIm6cf9/jGqzWYbf728Glbz07JiKetcV9dVZxwkv7euaT00LyvX7FUixhaj5swXxrpZ2mXxt@zcU66LPusOuns83@H5J9zucPuG77Ef67Zet6PQWO6@u@5V6J6N/dMPAwah5Ptiffn9Th6wTpbuKXm659g0kDrRJgoL@ukjjKN6nlWsv8szjibL1Vu003PWY3E2YHHur/XXPdXOtq7w38I1lp2wELkosykL@@15sufGfql3y7IahWzBZdn8r/1ZL9psL6uQl2UpBcsY/ALn0dseogxzZYEXQA70BHGKaiZ4KehO6HvCOamF5JWkpdS1wgelVglvEmoTvdb4qNUvw58MPRv9EkXvo0wYJXajEjqMEioHBGkRkArBhXDCEE5IS5jKRPGZUsqUiUz0nSad3Bth1Bw4ApcLCIcqQA4oloAGBNYgNBA8ACUg@QqkAmkaUBKUbsPkgyPg7@nlx/CkdPBEoEBbRCRUqAuBgoQS2hESkSI9@SCFMkhBkEJ5kPK2SKpEG@DeKYLwot4IJKDBoA/h1QVS/kFJBSEVhEgfhHJbuMl0Vv5LFH8TWSZyY0EWCA6TiRBTYWYkyz8 "Perl 6 – Try It Online") ``` { # bare block lambda with parameters $a,$b,$c $^a; # declare param $a, but don't use it # (so $a can be used in the inner block) ( 0, $^b ... $^c # the base sequence ).map: # for each of those values { $_ % $a # is it not divisible by `$a` ( shorter than `%%` ) ?? $_ # if it isn't divisible just return it !! # otherwise return the following chr # a character from the following number 97 + # 'a'.ord + $++ # self incrementing value (starts at 0) % 26 # wrap around back to 'a' } } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 62 bytes ``` (a,b,c)=>(g=k=>k>c?'':(k%a?k:Buffer([97+x++%26]))+g(k+b))(x=0) ``` [Try it online!](https://tio.run/##bdHbToNAEAbge5@CG1MI2O4c9tSEmvgaxgtYdoHSlqYe0vryuJpGDZrs5fxf/tnZVm/Vszv1x5e7w9j4KZRTWhV14bJyk7blUG6GjbtfLNbpcFvdD@uH1xD8KX20Oj/n@S2qpyzL23TI6yxLz6XIJjcensedX@7GNg1pwkWCRQJCZFmyWiUV1sqBaIA9mIDYoupI9MRbMgPjjtVeioPkcblcXqx5v5lxtkgocpqvHKkaEKRDQG5IEHmyjIGNhFZqJTqllO21jNxLTM04EF/tEvndjpX5BBkUGIeIjApNQ0hMioxnZGbFJswglLFUhFBeIYgJqbSxIAAiSJGUEdVgwKKIdREJuZ7vp4rPl7C5OrVrfGi7/p85@j1HtXUgGwSPOhC1ZDuWf1L41fLnGFCTk432NgC0QB3IHvQW7ICwQ9qjPKAe0R7j752tvUwf "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` /ݹ*εD³ÖiA¾è¼}? ``` -2 bytes thanks to *@MagicOctopusUrn*. Takes the input in the order `bca`. [Try it online](https://tio.run/##AScA2P8wNWFiMWX//y/DncK5Ks61RMKzw5ZpQcK@w6jCvH0///8zCjQ4CjY) or [verify all test cases](https://tio.run/##JYvBasJAGITv/1MMeNGiuLsmUaEgBSnk3oqlgmySH1zaGrpZxR7yGt567wvoSTwk975STCIMM8zwjfB1JLkaP4evYbhYVsPyd/nwf5q/lUfzVFzLv@KSz6p8VZxn9F5cVVAeO/WE/BvA4wAvG5Oh1i7jBC6F5Ywd3IYRp7utY7vea2t09MmIdPzRIGab8AEC3dQ2NWJ8pZbBBx27PjQSszeZaR8/UEGvUiSFII9GJMceTUmRL@qJJCm/UUDepLbRPWRLqxs). **Explanation:** ``` / # Divide the second (implicit) input `c` by the first (implicit) input `b` # i.e. 2 and 100 → 50 Ý # Take the range [0, `divided_c`] # i.e. 50 → [0,1,2,...,48,49,50] ¹* # Multiply it with the first input `b` # [0,1,2,...,48,49,50] → [0,2,4,...,96,98,100] εD # For-each in this list: ³Öi # If the current number is divisible by the third input `a`: # i.e. 8 and `a=4` → 1 (truthy) # i.e. 10 and `a=4` → 0 (falsey) A # Push the lowercase alphabet ¾ # Push the counter_variable (which starts at 0 by default) è # Index the alphabet with this counter_variable (wraps around by default) ¼ # Increase the counter_variable by 1 } # Close the if ? # Output without new-line # (If the if was not entered, the input is implicitly output as else-case) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 74  72 bytes ``` i,l;f(a,b,c){for(i=l=0;i<=c;i+=b)i%a?printf("%d",i):putchar(l++%26+97);} ``` [Try it online!](https://tio.run/##ZcrRCoMgFIDh@x5DEI54Bmpla072LOZwO1AtWruKnt0Fu2t3Px9/PD1izJmwdwkCdhjFml4zkO@9cnT10ZH0nSAebtNM45KA8TtDEpfps8RnmKGXkhsr20a4LQ@BRhBrkaBCg1op4Yp9fANjeyVosUTdVAfVap/r42tq1Gjqg1q0WJ3/sPzhlr8 "C (gcc) – Try It Online") [Answer] # Python 2, ~~80~~ 70 bytes Returns a list, since the OP said that is acceptable. ``` lambda a,b,c:map(lambda x:x if x%a else chr(x/a%26+97),range(0,c+1,b)) ``` Very different approach from the [other Python 2 answer](https://codegolf.stackexchange.com/a/170230/73884). [Try it online!](https://tio.run/##LYzLDoIwEEXX@hWzIWnDJLblJSR@ibqYViokUEhlUb@@ArI7Obn3zN@lm5yKFm7wiAON@kVAqNE0I83sEKEJ0FsICUE7fFownWfhQokq07ri6Mm9WybQpBI159FOHtge4dA7uLMcFUohOAKrMUNZ5RtKsepit6pAiarYsMQS8@ufsoP2/7p8NufT7Hu3gF37oBEMjz8) [Answer] # [CJam](https://sourceforge.net/p/cjam), 23 bytes ``` q~),@/f%{0W):W26%'a+t}% ``` [Try it online!](https://tio.run/##S85KzP3/v7BOU8dBP0212iBc0yrcyExVPVG7pFb1/39LBWMFQ3MTAA "CJam – Try It Online") ``` q~ a b c ), a b [0…c] @/ b [[0…a-1] [a…2a-1] ... […c]] f% [[0 b…a-b] [a a+b…2a-b] ... […c]] {0 t}% Replace each first with: W):W26%'a+ ++W % 26 + 'a' ``` Reading input as `b a c` and dropping the `@` would be 22 bytes (not sure if that's valid). [Answer] # [Python 2](https://docs.python.org/2/), ~~65~~ 63 bytes Returns a list, since the OP said that is acceptable. ``` lambda a,b,c:[[chr(n/a%26+97),n][n%a>0]for n in range(0,c+1,b)] ``` [**Try it online!**](https://tio.run/##DYxLDoIwFADX9BTdmLTyEtvyUUhwJ1sPgCwKFmmCD1JqlNNjV5PMJLNsfpxR7UP12Cf97p6aauigL5umHx3Dkz6oPC7OHLBt8KCvoh1mR5FapE7jyzABfSyh4@3@He1kqCxJ5N1W1tXAjhaXj2eck8j8erN4ervXN@fCQa/UlOZnQyXR4ix6OtnVs5rvKSiQQpACEpDnlEgRRCaIykCCykgOOaSXgCTgDw "Python 2 – Try It Online") --- Previous versions used during the creative process (working backwards): **84 bytes** Returns a generator expression. ``` def f(a,b,c,x=0): for n in range(0,c+1,b):yield n%a and n or chr(x%26+97);x+=n%a==0 ``` **111 bytes** Uses a generator for the alphabet and returns a list. ``` def g(x=0): while 1:yield chr(x%26+97);x+=1 A=g() f=lambda a,b,c:[n%a and n or next(A)for n in range(0,c+1,b)] ``` [Answer] # [PHP](https://php.net/), 79 bytes *Note: Not too good at PHP* ``` <?for(@$l=a;$i<=($p=$argv)[3];$i+=$p[2])$o.=$i%$p[1]?$i:substr($l++,-1);echo$o; ``` [Try it online!](https://tio.run/##DchBDoIwEAXQy3ySNhVD0ZVlgvcgXQBBaUKYSYse35Hle7KKate/OJsnNhoDUkcGQhjz@2uHWzzHEWRoowVfCak64WOP9CifqRzZYHPuUnsblnllcFDVu7bqm@bHciTei9b7Hw "PHP – Try It Online") --- # [PHP](https://php.net/), 84 bytes This is just the same above code just in function format (since you wanted a PHP answer maybe this is better for you) ``` function f($a,$b,$c,$l=a){for(;$i<=$c;$i+=$b)$o.=$i%$a?$i:substr($l++,-1);return$o;} ``` [Try it online!](https://tio.run/##ZcpdC4IwFIDh6/YrRpxgw5M4P/qa5h8JQkVzENs46VX0280u06sXHl7f@ykvfe9ZS@ToTq13NBj7EJHUUzfaZjDO8k5AhVAjNAjPopLvzpHQYPICmjlBAbUEFxZgdlCVYC6vsX4NJOAZBLhXUlM7jGTB6c/UNr3jbNOJFGNUUSR5yLc3e7NbHv74jAmqY7pkFc17trrjDBXG2ZIPeMD0tNbkX5lmrLxOXw "PHP – Try It Online") [Answer] # Excel VBA, 76 bytes Takes input, `a`,`b`, and `c` from `[A1]`, `[B1]` and `[C1]`, respectively then outputs to the VBE immediate window. ``` For i=0To[C1]Step[B1]:j=i Mod[A1]:?IIf(j,i,Chr(97+k)):k=(k-(j=0))Mod 26:Next ``` [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` f=lambda a,b,c,s=0,p=0:c>=s and[chr(p%26+97),`s`][s%a>0]+f(a,b,c,s+b,p+(s%a<1))or'' ``` [Try it online!](https://tio.run/##LY3NCoMwEITvfYq9FBOyhxj/qlRfRASTiCi0MSRe@vRpDMIe5pthduzv3A4jQlj7j/yqRYJEhRp9z9H2vNND70GaZdSbI/YpatY2FGc/T6N/yoFPbCV3gym0jET3nVN6uCwL6@HiO1AIGnYDpEQQCDnnFIG0CEWEprwg5ymqUiKq6EeuLqgR4pWvWxdJdw8A63ZzwrWeBmj4Aw "Python 2 – Try It Online") [Answer] # Kotlin, ~~80~~ 79 bytes -1 thanks to [O.O.Balance](https://codegolf.stackexchange.com/users/79343/o-o-balance)! ``` {a,b,c->var s="";for(x in 0..c step b)s+=if(x%a>0)x else(x/a%26+97).toChar();s} ``` [Try it online!](https://tio.run/##ZY7dasJAEEav61N8CMIurukaE39iE5Be9bpPMAlZuzRuZHeVFPHZ0yV6USsMfMOZw8x8t77Rpj9TA5WBUYYP4wXKe1ZDcswKfHqrzR55fyFRimpWnMnC5ePxVrWWddAGMooqOF8fUXI3zbVi3YQKyTvUjatZ90qTeDndrHjk2/cvsoxv3bVXJ4MDacPI7l2GnbX083a7VnBcRi/H0PrGMMUSgVhgLiXnf/FGYBHwKnnEczno6T87ToMbJukjXgqEStZPdPFM738Mm6/9Lw) My first time golfing (or doing anything else) in Kotlin! Probably can be improved. Very similar to [this Java answer](https://codegolf.stackexchange.com/a/170224/73884), I realized after writing it. Save on the `return` and lose on the ternary for almost the same score. [Answer] # Python3 - ~~111~~, ~~101~~, ~~98~~, 94 bytes ``` q=iter(map(chr,range(97,123))) [next(q)if x%a==0else x for x in[y*b for y in range((c+b)//b)]] ``` Probably not the shortest, but there's room for improvement [Try it online!](https://tio.run/##JYxBCsMgEADvecVeCrttoCYplBz2JSEHFdMIrRprQV9vk/YyMHOYUNLq3VAl3xrFfaO5E6JubJOJ@JIB9RrbKN3D4Hhvu34gosZ/Ek/O5IQbgV0gnySzAPN8G8iw@LjTOpjKWf2sHPafWJcQ9UXRVRHNcw3xKPuQ6hc "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` NθNη⭆Φ⊕N¬﹪ιη⎇﹪ιθι§β÷ιθ ``` [Try it online!](https://tio.run/##TYvBCoMwEETv@QqPG0hBS2@eCqWQg1JofyCapQbiRsNG2q9PI704l8e8YcbJxDEYn7OmJXGf5gEjrLIVxz6V/oiOGJ5c8O7MAnfnuUyaxogzEqOF40VKVfWBoQs2@QBOVZPc3Qsjmfg9@LXYgitrsviBQVWa@OY2Z/E/72lzvoizaOo6nzb/Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ Input `a` Nη Input `b` N Third input (`c`) ⊕ Increment Φ Filter over implicit range η `b` ι Current value ﹪ Modulo ¬ Not (i.e. divisible) ⭆ Map over result and join ι Current value θ `a` ﹪ Modulo ⎇ Ternary ι Current value ι Current value θ `a` ÷ Divide β Predefined lowercase alphabet § Cyclically index ``` [Answer] # [Haskell](https://www.haskell.org/), ~~71~~ 69 bytes ``` (a#b)c=do n<-[0,b..c];[show n,[['a'..]!!mod(div n a)26]]!!(0^mod n a) ``` [Try it online!](https://tio.run/##ZZHJahtREEX3/oo2ClgCW7yaq0j8B9llKRxQT@rW0K1Ztn9eaYt4EectL5dzT/Ga@WFVrdfX63g@yifFc9ln3Y@nWXrMp9Pi5fvs0PSXrHuczR7mD9Ppy/39pi/HZXvOumw@QX0ZknH6PYS34LqZt132nJX9XbY9HX8d9z@77Fs25hFOIKW77OlpjrkWkErgCrxGXKA2lFriJfmKcc26kdQJ9@JbxZ3q3tLB@Gh@cjy7XiK9Br@Fv9/9uxEjmoDxbYM0BwQpEJBLSkQVBWPNLrAQ09SoarQm5ktnt1VQ6BoSQpINfDzuABMg9YABhFsgB4YdsIGkPYiCxAFUQP34MfqvCqThXvl7Lqt/yDAoeIGIjIpeEhKTkleMzKzs9RcGyggmKDfGIMKi5gFpcEOggTZMg4FD4KA9YAk5/4LQkU7Yb4S8KKt60bT/NeizQXkUICVChVYTLSgalq99HJw@/xFyKqS0KmqABVAD0oItIVYIa6QNSofWY2wJdkR7kgPZkeLEcGa6sLyyvXG8C8yFcpFCrJSoFGqlhUqj1mosDVZGa5ONWWfRO2yddi57t4PHMeAUdA65hL1GvF3/AA "Haskell – Try It Online") --- **Previous 71 bytes:** ``` (a#b)c=do n<-[0,b..c];last$show n:[[['a'..]!!mod(div n a)26]|mod n a<1] ``` [Try it online!](https://tio.run/##ZZHLTuNAEEX3fIVRkCDSEHW9u2bgD2Y3yygLP2Mnjp3EeQCaf884aFgAteqSrs49pa7TYV227eXykE6yaf5c9En39DgPP7LZLF/8atPhcDfU/Tnpfs7n8/v0fjZb3N5u@uKhaE5Jl6RT1MXfcb@@n2Bx2aRNlzwnRX@TbI@HP4f97y65Sx54glMI4SZ5fEwx0xxCAVxCrBCXqDWFhnhFcc3Ysm4kdMK9xK3iTnVvYTA@WDxGPEU9e3hxfvX4dvO5wyc0BeP3DtIMECRHQC4oEJXkjBVHgaWYhlpVvTGxuIocbe3k2kJACLKB63AHGACpB3Qg3AJFYNgBG0jYgyiID6ACGg/X0s8qEMZ75f@5rPEqw6AQc0RkVIwFITEpxZKRmZVj9YWBMoEpyjtjFGFRiw5hdEOgkTZWg0EEx1F7xBJy9gWhE51yfCdkeVFWy7r5lqCPBGWegxQIJVpFtCSvWb7mcXT6@EfIKJfCSq8AlkA1SAO2Al8jtEgblA6tR98S7Ij2JAPZgfzIcGI6s7ywvbK/CaRCmUguVoiXCpXSUqVWa9RXBmuj1mRj1pn3EbaRdlH20YboB4ej08nl7Pbi/nr5Bw "Haskell – Try It Online") **Explanation:** ``` (a#b)c= -- given the inputs a, b and c do n<-[0,b..c]; -- take n from the range from 0 to c with increments of b last$ :[ |mod n a<1] -- if n is not divisible by a show n -- then use n converted to a string [ mod(div n a)26] -- otherwise divide n by a ['a'..]!! -- and use the character at this position in the alphabet ``` [Answer] # [CJam](http://www.sourceforge.net/p/cjam), ~~64~~ 63 bytes (*ouch*) ``` 97:Y;riri:Bri\/),[{B*}*]{X\_@\%0={Yc\Y):Y'{i={97:Y;}&}{X\}?}fX; ``` [Try it online!](http://cjam.aditsu.net/#code=97%3AY%3Briri%3AB%3Bri2%2F1%2B%2C%5B%7BB*%7D*%5D%7BX4%250%3D%7BYc%5CY)%3AY%3B%7D%7BX%5C%7D%3F%7DfX%3B&input=4%202%20100) **Explanation** ``` 97:Y; Set a variable "Y" to the ASCII value of 'a' and pop the variable from the stack ri Read one chunk of the input (Space-delimited) ri:B Set a variable "B" to the next input chunk ri\/ Divide the next input chunk by the top value in the stack (B) 1+ Add one to make the values inclusive , Turn it into an array {B*}* Multiply all the array values by B [ ] Capture the results in an array { }fX Massive for loop X\_@\%0= If X modulo (A value) equals zero { } If condition true Yc\ Push the character with an ASCII value of Y Y):Y Increase the value of Y '{i= If Y's value is that same as that of "{" (the character after z in ASCII) {97:Y;} Set Y's value back to ASCII 'a' & If-only flag { } If condition false (from X\_@\%0=) X\ Push X onto the stack ? If-else flag ; Pop A value from the stack ``` --- This could definitely be made better so feel free to join in! --- ### Changes [Helen](https://codegolf.stackexchange.com/users/58707/helen) cut off a byte! Old: `97:Y;riri:Bri\/1+,[{B*}*]{X\_@\%0={Yc\Y):Y'{i={97:Y;}&}{X\}?}fX;` New: `97:Y;riri:Bri\/),[{B*}*]{X\_@\%0={Yc\Y):Y'{i={97:Y;}&}{X\}?}fX;` By changing `1+` to `)` we can cut off a byte. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Żmọ⁵œpƊżJṖØaṁƲ$F ``` A full program taking arguments `c b a` which prints the result. **[Try it online!](https://tio.run/##AS8A0P9qZWxsef//xbtt4buN4oG1xZNwxorFvErhuZbDmGHhuYHGsiRG////MTc0/zP/OQ "Jelly – Try It Online")** [Answer] ## Clojure, 117 bytes ``` #(loop[R""A 0 i 0](if(> i %3)R(let[?(=(mod i %)0)](recur(str R(if ?(char(+(mod A 26)97))i))(if ?(inc A)A)(+ i %2))))) ``` Such imperative. :/ [Answer] # C (gcc/clang), ~~80~~ 68 bytes ``` f(a,b,c,i){for(i=0;i<=c;i+=b)i%a?printf("%d",i):putchar(i/a%26+97);} ``` Port of my Java [answer](https://codegolf.stackexchange.com/a/170224/79343). Try it online [here](https://tio.run/##ZZDNboMwDIDvPIUVCSkRnkooLetStgepegihbD6sVIXtMJRnZyZ0Eu0Sy46cz7/u6d25cWykxQodkhqa9iqpTA3tS2coKStFsX27XOncN1LEtWDo5fLVuw/L4MrG2TbZFcr48bulGvpT10tmwSJMppqNUzBEsDh/CWVcYxAF5SsInOI4xilzh98afPByG50Ugr0@mqp8WjrLZaXQyOEIJQw57lCnmG1wy1d7cwdVM5ThGjPUDKz/IW5GdJqiLnLchFz58yRZsWDDApknplPDZg8d/ZxaHkGtbi/@VwaShB7XEtZnD3TkLQTtWC@m9pEffwE). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` Żmµ⁵ḍaÄ$aị¥Øao ``` [Try it online!](https://tio.run/##ASoA1f9qZWxsef//xbttwrXigbXhuI1hw4QkYeG7i8Klw5hhb////zEwMP8y/zQ "Jelly – Try It Online") [Answer] # Python 2 and 3 - ~~123~~ 128 Bytes ``` d=-1 lambda a,b,c:[s()if i%a<1else i for i in range(0,c+1,b)] def s():global d;d=(d+1)%26;return'abcdefghijklmnopqrstuvwxyz'[d] ``` You'll need to put `f=` in front of the `lambda` and then call it with `f(a,b,c)` but I'm pretty sure that's allowed. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~59 58~~ 55 bytes ``` ->a,b,c{[w=?a]+b.step(c,b).map{|x|x%a>0?x:w=w.next[0]}} ``` [Try it online!](https://tio.run/##Ncy7CsMgAEbhvU/RpdDLX1Gj6QVMHkQcNCRbirQpWhKf3ZpCt48znOfbffKg8rmxcOhmHVRrzcmR19T7fQd3IKP18xKXuLMNbeM9qEAefZw0NSllrQU4GKUG@oYK7CKKGC1Rro1LMHBZVKOGuP5QrTD/8cZvB32MJuUv "Ruby – Try It Online") Returns a list ]
[Question] [ Given the coordinates of the upper left corners of two squares and their side lengths, determine whether the squares overlap. A square includes the top and left lines, but not the bottom and right lines. That is, a point `(a,b)` is inside a square with side length `k` that starts at `(x,y)` if and only if `x <= a < x+k` and `y <= b < y+k`. A square with side length 0 is degenerate and will not be considered here, thus, `k` will be positive. As usual, all standard rules apply. Input and output may be in whatever form is convenient, so long as it's human readable and there is no precomputation. Be sure to specify what input format you use. Your code should take six numbers and output truthy if the squares overlap and falsy otherwise. ## Test Cases ``` x1 y1 k1 x2 y2 k2 overlap? 1 1 1 0 1 1 false 0 0 3 1 1 1 true 1 1 1 0 0 3 true 0 0 3 2 1 2 true 0 0 2 1 1 2 true 1 1 2 0 0 2 true 0 1 2 1 0 2 true 1 0 2 0 1 2 true 2 0 2 0 2 2 false 1 0 3 0 1 1 false 0 2 3 0 0 2 false ``` All inputs will be non-negative integers. That said, I expect that many or most solutions will also be able to handle negatives and floats. [Answer] ## Python, 33 bytes ``` lambda x,y,k,X,Y,K:k>X-x>-K<Y-y<k ``` Python supports chains of inequalities even when they point opposite directions. The x-coordinate intervals `[x,x+k)` and `[X,X+K)` overlap as long as neither one is fully to the right of the other, which means that each interval's left endpoint is left of the other interval's right endpoint. ``` x<X+K X<x+k ``` The can be combined into a joint inequality `-K<X-x<k`. Writing the same for y-coordinates and splicing them at `-K` gives the expression ``` k>X-x>-K<Y-y<k ``` [Answer] # MATL, ~~14~~ ~~11~~ ~~10~~ ~~5~~ 4 bytes ``` tP-> ``` This solution accepts input in the form of two arrays: 1. A 2 x 2 matrix that contains the coordinates of the corners `[x1, y1; x2, y2]` 2. A 2 x 1 array containing the square dimensions `[k2; k1]` [**Try it Online**](http://matl.tryitonline.net/#code=dFAtPg&input=WzAgMDsgMSAxXQpbMTszXQ) [**Slightly modified version to run all test cases**](http://matl.tryitonline.net/#code=YHRQLT5BQURU&input=WzEgMTswIDFdClsxOzFdClswIDA7IDEgMV0KWzE7M10KWzEgMTsgMCAwXQpbMzsxXQpbMCAwOyAyIDFdClsyOzNdClswIDA7IDEgMV0KWzI7Ml0KWzEgMTswIDBdClsyOzJdClswIDE7IDEgMF0KWzI7Ml0KWzEgMDsgMCAxXQpbMjsgMl0KWzIgMDsgMCAyXQpbMjsgMl0KWzEgMDsgMCAxXQpbMTszXQpbMCAyOyAwIDBdClsyOyAzXQ) **Explanation** ``` % Implicitly grab the first input t % Duplicate the input P % Flip along the first dimension (columns) - % Subtract the two to yield [x1-x2, y1-y2; x2-x1, y2-y1] % Implicitly grab the second input > % Compare with [k2, k1] (automatically broadcasts) % Implicitly display the truthy/falsey result ``` [Answer] # MATLAB, ~~36~~ 21 bytes ``` @(a,b)a-flip(a)<[b,b] ``` Creates an anonymous function which can be evaluated as `ans(a,b)`. Accepts two inputs of the following format: 1. 2 x 2 matrix containing the corner of each square as a row: `[x1, y1; x2, y2]`. 2. 2 x 1 array containing the size of the two squares: `[k2; k1]` All test cases [here](http://ideone.com/Hu5KRo). **Explanation** Here is a commented un-golfed solution ``` %// Example input a = [1 1; 0 1]; b = [1; 1]; %// Flip a along the first dimension and subtract from a to yield: %// %// [x1-x2 y1-y2] %// [x2-x1 y2-y1] d = a - flip(a); %// Compare this matrix element-wise with two horizontally concatenated copies %// of the second input [k2; k1] result = d < [b,b]; %// Truthy values have all ones in the result and falsey values have at %// least one 0 in the result. ``` [Answer] ## JavaScript (ES6), 38 bytes ``` (a,b,c,d,e,f)=>d-a<c&a-d<f&e-b<c&b-e<f ``` If *d* - *a* ≥ *c* then the second square is to the right of the first. Similarly the other conditions check that it is not to the left, below or above. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṫṗ2+µ€f/ ``` Input is the nested list **[[x1, y1, k1], [x2, y2, k2]]**, output is the list of all incremented coordinates of points with integer coordinates that are common to both squares (falsy if empty, truthy if not). [Try it online!](http://jelly.tryitonline.net/#code=4bmq4bmXMivCteKCrGYv&input=&args=W1swLCAwLCAzXSwgWzEsIDEsIDFdXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmq4bmXMivCteKCrGYvCsOH4oKs&input=&args=W1sxLCAxLCAxXSwgWzAsIDEsIDFdXSwgW1swLCAwLCAzXSwgWzEsIDEsIDFdXSwgW1sxLCAxLCAxXSwgWzAsIDAsIDNdXSwgW1swLCAwLCAzXSwgWzIsIDEsIDJdXSwgW1swLCAwLCAyXSwgWzEsIDEsIDJdXSwgW1sxLCAxLCAyXSwgWzAsIDAsIDJdXSwgW1swLCAxLCAyXSwgWzEsIDAsIDJdXSwgW1sxLCAwLCAyXSwgWzAsIDEsIDJdXSwgW1syLCAwLCAyXSwgWzAsIDIsIDJdXSwgW1sxLCAwLCAzXSwgWzAsIDEsIDFdXSwgW1swLCAyLCAzXSwgWzAsIDAsIDJdXQ). ### How it works ``` Ṫṗ2+µ€f/ Main link. Argument: [[x1, y1, k1], [x2, y2, k2]] µ Combine the chain to the left into a link. € Apply it to each list [xi, yi, ki]. Ṫ Tail; pop and yield ki. ṗ2 Second Cartesian power; yield the list of all pairs [a, b] such that 1 ≤ a ≤ ki and 1 ≤ b ≤ ki. + Add [xi, yi] to each pair, yielding the list of all pairs [c, d] such that xi + 1 ≤ c ≤ xi + ki and yi + 1 ≤ d ≤ yi + ki. f/ Reduce by filter, intersecting the resulting lists of pairs. ``` [Answer] # TI Basic, 36 bytes ``` Prompt X,Y,K,Z,θ,L:Z-X<K and X-Z<L and θ-Y<K and Y-θ<L ``` [Answer] # Java, 78 bytes ``` Object o(int a,int b,int c,int d,int e,int f){return d-a<c&a-d<f&e-b<c&b-e<f;} ``` [Answer] # Octave, 17 bytes ``` @(a,b)a-flip(a)<b ``` Same logic as [my MATLAB answer](https://codegolf.stackexchange.com/a/79760/51939) above, except that Octave supports automatic broadcasting of dimensions so we can replace `[b,b]` with simply `b`. All test cases [here](http://ideone.com/c35ekS) [Answer] # SmileBASIC, ~~76~~ 57 bytes ``` INPUT X,Y,W,S,T,U SPSET.,X,Y,W,W SPCOL.?!SPHITRC(S,T,U,U) ``` Creates a sprite with the size/position of the first square, then checks if it collides with the second square. [Answer] # x86-64 Machine code, Windows 22 bytes C++ signature: ``` extern "C" uint32_t __vectorcall squareOverlap(__m128i x, __m128i y, __m128i k); ``` Returns 0 if the squares don't overlap and -1 (0xFFFFFFFF) otherwise. Inputs are vectors of 2 64-bit integers for x, y and k(`_mm_set_epi64x(x1, x2)` etc.). ``` squareOverlap@@48 proc 66 0F FB C8 psubq xmm1,xmm0 0F 16 D2 movlhps xmm2,xmm2 66 0F 38 37 D1 pcmpgtq xmm2,xmm1 0F 12 CA movhlps xmm1,xmm2 0F 54 CA andps xmm1,xmm2 66 0F 7E C8 movd eax,xmm1 C3 ret squareOverlap@@48 endp ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Â-›˜P ``` Port of [*@Suever*'s MATL answer](https://codegolf.stackexchange.com/a/79761/52210), with additional conversion to a truthy/falsey result. The input-format is therefore also the same: First input as `[[x1,y1],[x2,y2]]` and second input as `[k2,k1]`. [Try it online](https://tio.run/##yy9OTMpM/f//cJPuo4Zdp@cE/P8fHW2oYxirE20AJGO5wBwA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o5ObpYq@kkJiXoqBkD2Y@apsEZBb/P9yk@6hh1@k5Af91/kdHG@oYxupEGwDJWC4whysayDMAihnCxIxBYjB1BiAxY2R1RhB1RhB1KHqNdIww9ELFDMBihihihmC9Bih6jaBiRrjUwd1ihGyHMVZ/AAA). **Explanation:** ```  # Bifurcate (short for Duplicate & Reverse copy) the (implicit) input-matrix - # Subtract each value (vectorized) from the input-matrix we duplicated › # Check for both values (vectorized) if it's larger than the (implicit) input-list # (We now have the same result as the MATL answer. In MATL a matrix/list consisting # of only 1s is truthy. In 05AB1E this isn't the case however, so:) ˜ # Flatten the matrix to a single list P # And take the product to check if all are truthy # (after which the result is output implicitly) ``` ]
[Question] [ ## Preamble A common pain-point when working with [rational numbers](https://en.wikipedia.org/wiki/Rational_number) and decimals is how infrequently one can represent their rational number as a clean, non-repeating decimal. Let's solve this by writing a program to decimalize (not to be confused with [decimate](https://en.wiktionary.org/wiki/decimate)) them for us! ## The Challenge Given a [fraction](https://en.wikipedia.org/wiki/Fraction), check if it can be represented perfectly by a finite decimal number. If it can, output the decimal representation of this fraction. Otherwise, output the input fraction. ## Specifics Input will be provided as two integers within the range of `[1, 32767]` *(Positive Signed Shorts)*, representing both the Numerator and Denominator. Numbers may be taken in any convenient format or order, including built-in Fraction formats, a single pre-divided floating point number *(of a precision that can accurately represent all possible fractions)*, a deliminated string, an imagine number, [etc](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). The Input is **not** guaranteed to be in simplified form. A given Input is "Decimalizable" if the Denominator of the Simplified Fraction contains no prime factors other than `2` or `5`. The Output, given a Decimalizable Input, must be a decimal number. This may be as any convenient format, including a string, char array, or float. It may **not** be a Fraction type. *(Floats are allowed as it is generally trivial to stringify.)* Trailing Zeroes are **not** allowed, though leading zeroes are. Otherwise, The Output must be Two Numbers signifying the Numerator and Denominator, in any convenient format. The output may **not** be a decimal number, nor a floating point number. Output may optionally be Simplified. ## Test Cases ``` 16327 / 4 = 4081.75 186 / 400 = 0.465 23164 / 100 = 231.64 32604 / 20000 = 1.6302 22764 / 16384 = 1.389404296875 3 / 6 = 0.5 1 / 3 = 1/3 3598 / 2261 = 514/323 7725 / 18529 = 7725/18529 21329 / 3774 = 21329/3774 12213 / 2113 = 12213/2113 ``` ## Rules * [Standard IO Applies](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * [Standard Loopholes Apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes wins! * Have Fun! [Answer] # [Python 3](https://docs.python.org/3.8/), 34 bytes ``` lambda n,d:[n/d,(n,d)][n*1e16%d>0] ``` [Try it online!](https://tio.run/##LYxBCsIwEEX3OcVsxESKzcy0SVrRi6iLShULNYZaEU9fk@Cs5vH@/@E735@eXZiW2/60jN3j0nfgi749@rIvZPzU@eg3eEWz6g/6vHzuw3gFbKPZP7ogBz8Xgw/vWartK4zDLNflWqldmKKRt7ygFjRMFkpIVwkAdCZTpbUgRlNlwkhMRicirZMjm13su9SLmf8KgwCuG5eQyKAAa6lOUVdTIwiZmuTY2kogRc5JRP4B "Python 3.8 (pre-release) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 86 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 10.75 bytes ``` \/€tǏ25F[|øḋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiXFwv4oKsdMePMjVGW3zDuOG4iyIsIiIsIjMvNiJd) And here I thought I was being clever skipping the challenge text. Takes a fraction as input, which is automatically simplified. ## Explained ``` \/€tǏ25F[|øḋ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌­ \/€ # ‎⁡Push a copy of the input splitted on "/" tǏ25F # ‎⁢Push the prime factorisation of the denominator with 2s and 5s removed. [|øḋ # ‎⁣If that is empty, convert to decimal. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ?¤/i/¤-p*10¹³ ``` [Try it online!](https://tio.run/##yygtzv7/3/7QEv1M/UNLdAu0DA0O7Ty0@f///@Z6Bv@NjPQMAA "Husk – Try It Online") Input as two integers (den, num) represented in floating-point format: it's much easier in [Husk](https://github.com/barbuz/Husk) to convert a float to an int than the other way around. ``` ?¤/i/¤-p*10¹³ # full program ?¤/i/¤-p*10⁰²⁰² # with arg expansion: ¤ # combin: ¤fgxy means f(gx)(gy) - # f = - = list difference p # g = p = prime factors *10⁰ # x = 10x arg1 ² # y = arg2 # (so this simplifies the fraction, # and returns list of any non-2, non-5 factors # - truthy if there are any, falsy if none) ? # fif: ternary if for functions # use the above result to choose from: ¤/i ⁰² # (if truthy) convert both args to integers & divide # (Husk outputs real fractions by default) / ⁰² # (if falsy) just divide # (keeps input floating-point format) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 246 bytes ``` \d+ $* ^(1+)(\1)*/(\1)*$ 1$#2$*1/$#3$* +`/(1+)\1{9}(0*)$ /$1$+0 +`/(1+)\1{4}(0*)$ $`/$1$+0 +`/(1+)\1(0*)$ $`$`$`$`/$1$+0 +`/(11+)0 /$1$1$1$1$1$1$1$1$1$1 ^(1+)(\1)*/(\1)*$ 1$#2$*1/$#3$* 1+ $.& r`^(?<-1>.)+/1(0)+$ $#1$*00$& r`((?<-2>.)+)/1(0)+$ .$1 ``` [Try it online!](https://tio.run/##hc7JagMxDAbgu15jlOKFjvTLng1KeuxLDGECyaGXHkJuIc8@9WSBkBxigZH9CUmH/fH3bzuv3M80j7tIHGjjEL0b4YNcbiZwZRwgXKXicZKlYsRpODsNnkkYHPUB8g14eqb7/zUetbBeOr3E241Q9q4/6DBt3PfXJ9a1j1Im@VgmVeCgyou6RW1Rf@eaMc/oW8mqZAltFpQsWatZTMshSKLUDL2YtaCus0bQNzaQIdkgqesywcpDDEj/ "Retina 0.8.2 – Try It Online") Link includes faster test cases, as manipulating large numbers in unary is horribly slow. Explanation: ``` \d+ $* ``` Convert to unary. ``` ^(1+)(\1)*/(\1)*$ 1$#2$*1/$#3$* ``` Reduce to lowest terms. ``` +`/(1+)\1{9}(0*)$ /$1$+0 ``` Find all factors of `10` in the denominator. ``` +`/(1+)\1{4}(0*)$ $`/$1$+0 +`/(1+)\1(0*)$ $`$`$`$`/$1$+0 ``` Find all factors of `5` and `2` in the denominator, and multiply both numerator and denominator by `2` or `5`. ``` +`/(11+)0 /$1$1$1$1$1$1$1$1$1$1 ``` If the denominator turned out to have other factors, then convert it back to unary. ``` ^(1+)(\1)*/(\1)*$ 1$#2$*1/$#3$* ``` Reduce the fraction to lowest terms again, but only if it was converted back to unary. ``` 1+ $.& ``` Convert to decimal. ``` r`^(?<-1>.)+/1(0)+$ $#1$*00$& ``` Prepend zeros to the numerator if the denominator is a larger power of `10`. ``` r`((?<-2>.)+)/1(0)+$ .$1 ``` Divide the numerator by the denominator if it is a power of `10`. 179 bytes and faster for exact decimals in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1: ``` +`.+/(.*50*)$ $.(*2*)/$.($1*2* +`.+/(.*[2468]0*)$ $.(*5*)/$.($1*5* +`0(/.+)0$ $1 r`^(?<-1>.)+/1(0)+$ 0$#1*0$& r`((?<-2>.)+)/1(0)+$ .$1 /\//&`\d+ * ^(_+)(\1)*/(\1)*$ $.(_$#2*_)/$#3 ``` [Try it online!](https://tio.run/##PY1JTsNAEEX3dQ03UQ@ia3IPlhAsOQQmdiRYsGERcX9THSnZ1PRe6V@//35@L3w8@ff9SHtO6HMsFIMDl32UGNC6Y5vgjj9krv3z4ZSHU4ZDHnMKZIzhup/928szv@aQkD2F5IDcxJHcyaAfUAYMd5rtC1fE075@JYhw9lsKfuUQ8VZvkZubJG6WOulxCBbgqtJwBu4VZyIQ5Toj26RSaUYhGldp41q1m4kKWpaOIpWhNSnIvcgCwioLamvmiC0ozPoP "Retina – Try It Online") Link includes test cases. Explanation: ``` +`.+/(.*50*)$ $.(*2*)/$.($1*2* ``` Double the numerator and denominator while the latter ends in `50*`. ``` +`.+/(.*[2468]0*)$ $.(*5*)/$.($1*5* ``` Multiply the numerator and denominator while the latter's last nonzero digit is even. ``` +`0(/.+)0$ $1 ``` Cancel out any power of `10` common to both numerator and denominator. ``` r`^(?<-1>.)+/1(0)+$ 0$#1*0$& ``` Prepend zeros to the numerator if the denominator is a larger power of `10`. ``` r`((?<-2>.)+)/1(0)+$ .$1 ``` Divide the numerator by the denominator if it is a power of `10`. ``` /\//&`\d+ * ^(_+)(\1)*/(\1)*$ $.(_$#2*_)/$#3 ``` Otherwise, reduce the fraction to its lowest terms. [Answer] # [Factor](https://factorcode.org/), 44 bytes ``` [| x y | x 1e16 * y mod 0 > x y / x y /f ? ] ``` [Try it online!](https://tio.run/##LZC7TsQwEEV7f8WlpYg941cCYikRDQ2iQhTRkiwr8lISJFbAtwc/4mKkc67la01bH9dx3l6eH58eblAvy3hc0NfrBz6beWg6THOzrpdpPg8rTvP4NZ2HE7rxWHcLboX4EeQ0e6RjcIU7GFVS4a0AqHRJK5UCVRhnBWtyJmradRCFM0KzU8GzUrsPVisWzD7eDzWl2b0uK6MMV65MNSHM/TrnUgtoW5XBMDtK0pKRmkPgPdv4M8tVCiLLhIJJBxme8T43JSEjCuIA8UGivSUKGVH8gfNqttdffOOCOKkhh@sA/fgOhUMKZJ4t7vG2tXndh76eUGz/ "Factor – Try It Online") Port of xnor's [Python answer](https://codegolf.stackexchange.com/a/264965/97916). The only difference is that it's shorter to return either a ratio or a float instead of bothering with lists. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` `s16°*sÖi`/ ``` I/O as a pair \$[nominator,denominator]\$. The output is unsimplified. Port of [*@xnor*'s Python 3 answer](https://codegolf.stackexchange.com/a/264965/52210). [Try it online](https://tio.run/##yy9OTMpM/f8/odjQ7NAGreLD0zIT9P//jzY0MzYy1zGJBQA) or [verify all test cases](https://tio.run/##JY0xCsJAEEWvEqYRJDA7M7szu1UabyFCFCxSWQSEFLYewMLeE@gZkpt4kXU3du/zePzLeDwN53ydOmi@90cD3bTB@bW8d7kfSefPdlyeQ4/51uY9kAobemiBoqJ3rhALqUdaWVidR3bub9iqUYm1ENTaoVQOKSKzUmEzDkgxcKoJCScUs/WDy0QmEjj8AA). **Explanation:** ``` ` # Pop the (implicit) input-pair, and push both items separately to the stack s # Swap so the nominator is at the top 16° # Push 10000000000000000 (10**16) * # Multiply it to the nominator s # Swap so the denominator is at the top again Ö # Check if the nominator with 16 trailing 0s is divisible by the denominator i # Pop, and if this is truthy: ` # Pop and push the input-pair separated to the stack again / # And divide them # (after which this decimal is output implicitly as result) # (implicit else) # (output the implicit input-pair instead) ``` [Answer] # JavaScript (ES6), 24 bytes Unsurprisingly, a port of [xnor's method](https://codegolf.stackexchange.com/a/264965/58563) probably leads to the shortest code. ``` p=>q=>p*1e16%q?[p,q]:p/q ``` [Try it online!](https://tio.run/##bc/LbsIwEAXQfb/Cm0pJ1cbz8iNIoR9SsUA0VK0QcQDx@@mYkEVNs5ubo5nrn@11e96dvtPl7Th89tO@m1K3Hrt1esEe/fP4/pFex80q2XHaDcfzcOibw/BV7Sv0TKGujH5S18ZaIxCxCe7przMGo89OAGYHjfhSEaOXrHBRmjReCsbkQRkBLEwRA5XbKORtWjHKwji2AkKtj/9U1LvzU/jOLZeGXRvVEHmcjUOxTA8uBHJ6OjpqZ5cDe5vLlshqdHMI95a3xOa5oEj6K19HXBrmxOZ5@gU "JavaScript (Node.js) – Try It Online") --- ### Other approach (43 bytes, invalid) Expects `(p)(q)`. Returns either `[p,q]` or `p/q`. We multiply by \$5\$ the greatest power of \$2\$ that divides \$q\$ until it's greater than or equal to \$q\$. This works for all test cases ([at the time of posting](https://codegolf.stackexchange.com/revisions/264962/3)) but would fail on some others because *the input is not guaranteed to be in simplified form*. ``` p=>q=>(g=n=>n>q?[p,q]:n<q?g(n*5):p/q)(q&-q) ``` [Try it online!](https://tio.run/##bc9NTsMwEAXgPafwCtmIxp7x@CcVSQ@CWFSljYoqJ6aI64dx0ywwZDcvn2aeP/bf@@vh8zx9bdL4fpxP3Tx1fe56OXSp61Ofd6/Tc37bppe8G2R6cmo76axkftxkNR/GdB0vx@YyDvIkwVsMSgr@SCmhtSAToQnu4bcTAqIvjoxZnGnI1woteCoKVsVJ46liFr1hhsasjJE1WG/DULZxxUgrs7ElQ9j6@E9Fvrs8xd65trWxro1sED0sxgFpi39cCOj4dHTYLq4E@jbXLcGy4c0h3FveEl3migLyr3IdYG1YEl3m@Qc "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes ``` If[Depth[r=RealDigits@#]>3,#,N[#,Tr[1^#&@@r]]]& ``` [Try it online!](https://tio.run/##HYqxCsIwFEV/pRBwCry899KkHSoZuriIiFuIEKS2BStSs4nfHhu3e885S0zTsMQ032Ieu3y4@354pcmv3XmIj34e5/R2IuxZCnn0Ql5Wj1exc24NIezyaZ2fCdwI7oOGyYKWFTYGtFKyIkajActkMkoDKfXnZAs33JQaeNN12wCRQVlZSzVgU1O7hcjUAltbOtoeECJ/c/4B "Wolfram Language (Mathematica) – Try It Online") -8 bytes thanx to @att [Answer] # JavaScript (ES6), 125 bytes ``` f=s=>{[n,m]=s.split('/').map(v=>+v);for(i=n>m?n:m;i>1;i--)if(!(n%i|m%i))[n,m]=[n/i,m/i];return n*1e16%m?`${n}/${m}`:`${n/m}`} const testCases = [ { input: '16327/4', output: '4081.75' }, { input: '186/400', output: '0.465' }, { input: '23164/100', output: '231.64' }, { input: '32604/20000', output: '1.6302' }, { input: '22764/16384', output: '1.389404296875' }, { input: '3/6', output: '0.5' }, { input: '1/3', output: '1/3' }, { input: '3598/2261', output: '514/323' }, { input: '7725/18529', output: '7725/18529' }, { input: '21329/3774', output: '21329/3774' }, { input: '12213/2113', output: '12213/2113' }, ]; for (let { input, output } of testCases) { console.log(input, '=>', f(input) === output); // Equals? } ``` ``` .as-console-wrapper { top: 0; max-height: 100% !important; } ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 137 bytes ``` #define W(A,B)for(;d%A<1;q*=10,++c)n*=B,d/=A; f(a,b){long n=a,d=b,q=1,c=0;W(2,5)W(5,2)printf("%ld%c%0*ld",d?a:n/q,47-!d,c*!d,--d?b:n%q);} ``` [Try it online!](https://tio.run/##TZDNjoIwFIXXw1N0mJC0WOwvLciQib6Ea6BiTJwqyqyMz@60KGAXbXPOl3NPbpPsm@bx@DK79mB3YAvXeIPa0wUWJlp/s6KLS0bxYtEgG5cbbEi5LoIWVrhGt@PJ7oEtK2zKGnclw01Jiy3kOEVbmGKOzpeD7VsYRkcTNRGNjybE5qdaWdJhqZNPg5vYXUlifuqVjTpU3Kcm/e7auzGgRqB9vgU4//VXGIaoCILf6mAhArfgYwCZElwADNyR1JGEEP/LllSnb4h@IkC@IWw5IQCwTA2IpFMKXUo1AlwwJQeAzYATl0q@CMEV9QSndCacLygfM7geMlyfTM6EyHJJJc9V9lbHGa/GYiKJGG2R5pm3OVdstFMmiVvFiGjNUz8rS3k@Il4jgzI2YoLnPkhoPTUaROKVcX/cScM4xuY2XiReCe6Pfw "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` ≔I⪪S/θ≧÷⌈Φ⊕⌊θ∧ι¬⌈﹪θιθ¿﹪Xχφ§θ¹⪫θ/I∕§θ⁰§θ¹ ``` [Try it online!](https://tio.run/##bY/NqsIwEIX3PkVwNYGIKchF6EoUQaEi@gShyW0H0qQ/U/XtY9JewcWdzcCcOd@cKWvVl17ZEHbDgJWDvRoI7q1FgpNrR7pTj64CLthyveSxdTxfFKqd129Y1WmRDvhAbQQr1AubsYEjWjJ9VMreNMaR0VCgm6QuUXZOAwp28QQfS@H1aD10giGfar6Fv@wjXf0zMjMpWCalTBQ6OW1eyZNFA7vGrARnjy6NpsA5M3Ywf8r03BwVvrz/oHgeQrb9WW@kDKuHfQM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔I⪪S/θ ``` Input the fraction. ``` ≧÷⌈Φ⊕⌊θ∧ι¬⌈﹪θιθ ``` Reduce it to its lowest terms. ``` ¿﹪Xχφ§θ¹ ``` If the denominator is not a factor of `10¹⁰⁰⁰`... ``` ⪫θ/ ``` ... output as a fraction, otherwise... ``` I∕§θ⁰§θ¹ ``` output as a decimal. 81 bytes for the way overengineered version which works with arbitrary precision positive integer inputs: ``` ≔I⪪S/θW﹪§θ±²§θ±¹⊞θι≧÷⌊θθ≔Xχ⌈E25⌕⮌X⁰↨§θ¹Iι⁰η¿﹪η§θ¹⪫…θ²/⁺÷§θ⁰§θ¹⭆I⁺η﹪×§θ⁰÷η§θ¹η⎇κι. ``` [Try it online!](https://tio.run/##ZZBfb4IwFMXf/RQNTyVhE1ppMD45lyUucTHqF2ikg5tVQFr88@nZLTJ1SgIN7em5v3O2uay3pdRtOzUGsoLOpLF0XWmwdF5UjV3bGoqM@gHxhp6Py96fDI45aEXookwbXdKpnRepOtF9QL5UJq2izAmftyMfH7JsTO42AY0WsrrMXUGWu4n2HQ6QqoAsoIBds6P7fmSPtyyPqqZRiAJ56gRoQT0WewH5gCKlK3VQtVG9EHVvEv/uWCI07EKCowlIeFlynAHf10z5P/6o48YiLP0sAUs6b7Wa5WXlDtlfN5OB0kb1uqVuzC3PPUDoP3oH5NKyi9KhdZcRoYfZwE6ZR4ub9zOri@O@G1UXsj7TH2wbIV89l3XStjET4ThhYiwSHgs@EiFPGGdDfBMeihEXMU/wlCXjULC4fTnoXw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔I⪪S/θ ``` Input the fraction. ``` W﹪§θ±²§θ±¹⊞θι≧÷⌊θθ ``` Reduce it to its lowest terms. ``` ≔Xχ⌈E25⌕⮌X⁰↨§θ¹Iι⁰η ``` Find a power of `10` that the denominator might be a factor of. ``` ¿﹪η§θ¹⪫…θ²/ ``` But if it isn't then just output the fraction. ``` ⁺÷§θ⁰§θ¹⭆I⁺η﹪×§θ⁰÷η§θ¹η⎇κι. ``` Convert the fraction to arbitrary precision decimal. [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes Yet another xnor port. Like chunes' Factor port, it's shorter to return a `Rational` instead of an array if it can't be decimalized. ``` ->n,d{(n*1e16%d>0?1r:1.0)*n/d} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LZBbTsMwEEXFr9nEqFC16cP2jB3HQUpZSKmqoqRQqYQoSUGo7RJYAT8Vgm2wD1gNtlN_JDonM_dG_viqd_dvp8919r1r11P7M52Vk3w_LEdYoOnnM3mL9Q1yGY1KkR-7od_318fNtoCHom0YuPlJDRlcL3nT1puKN9V20w4FjOd3IlvAWET8aVXtD8WheFltoTgP3IpoNKjF4Mig2rUN9PpxDgL8M4OrfZut5y56cYShA94-L5ssq8P7GPWgD-ErK8q8-6nT38UlGkWJy_BHuxQtLfIkZgBoTfBaSucl1yZmpNDoYDFYx9xopshIr0nKoJ1UkhhREqZdh9VBK5tqqSk1NlQAqHO1CRWdw7NTfkUoBipOrXdEBp2LUQtFzicJxT7expQ671EEYITKKbeiksQ3BxYeGJKDkIYYGjwLD92l_AM) [Answer] # [sclin](https://github.com/molarmanful/sclin), 29 bytes ``` 16 17,.N>d Q",_ ="Q0.:"pop"?# ``` [Try it on scline!](https://scline.fly.dev/##H4sIALVO.mQCAzM0MjI0VjAyNDTW1.MyNFMwNNfR87NLUQhU0olXsFUKNNCzUirIL1CyVwYANfBn3yoAAAA) ## Explanation Prettified code: ``` 16 17,.N>d Q ( ,_ = ) Q 0.: \pop ?# ``` Numbers in sclin are internally represented as rational numbers. * `16 17,.N>d Q` represent the fraction as a decimal with 16 and 17 places * `( ,_ = ) Q ... ?#` check if both representations are equal... + `0.:` if true, then get decimal representation + `\pop` otherwise, get rational representation ]
[Question] [ Write a program or function that outputs all positive integers with distinct decimal digits (OEIS: A010784) Examples: ``` 1 2 3 4 5 6 7 8 9 10 12 13 ... 96 97 98 102 103 ... 123456789 123456798 ... 9876543120 9876543201 9876543210 ``` # Rules * You can output the list of numbers in any convenient format (string with separators, array, generator, ...) * The order of the numbers is not important as long as every number appears exactly once * You can choose if you include zero * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` import Data.List nub$nub.show<$>[1..] ``` [Try it online!](https://tio.run/##DcO9DkAwEADg3VPc0FXDjsnIZBTDET@Na130Gm/v@JLvwHiuRKrO83ULtChoOxclozqk2fxtPK6nMs1YWjupRxegBo/cAycZ5O4CGBA8VyiLAkjfZSPco@YL8wc "Haskell – Try It Online") Takes each number, removes duplicate digits from its string representation while preserving order, then removes duplicates from the resulting list. **41 bytes** ``` [s|s<-show<$>[1..],s==[x|x<-s,y<-s,x==y]] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfYxvzP7q4pthGtzgjv9xGxS7aUE8vVqfY1ja6oqYCKKpTCSIqbG0rY2P/5yZm5inYKuQmFvgqFJSWBJcU@eQpqCiUJGanKhgaGCjk/P@XnJaTmF78Xze5oAAA "Haskell – Try It Online") For both solutions, the resulting list is finite, but attempts to read further elements will not terminate. Adding an upper bound would fix this. [Answer] # [J](https://www.jsoftware.com), 14 bytes ``` ~.~.@":&>i.!14 ``` [Attempt This Online! (with 7 instead of 14)](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxtk6vTs9ByUrNLlNP0RwitkGTK97IQCE1OSM_RgGoPw0ivGABhAYA) Uses xnor's idea: take unique digits from each number and then take unique results of that. --- # [J](https://www.jsoftware.com), 18 bytes ``` I.(=&#=)@":&>i.!14 ``` [Attempt This Online! (with 7 instead of 14)](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmux0VNPw1ZN2VbTQclKzS5TT9EcIr5WkyveyEAhNTkjP0YhDSK2YAGEBgA) 14! is the first factorial that exceeds 10^10. ``` I.(=&#=)@":&>i.!14 !14 large enough number i. all numbers up to that &> for each number, ( )@": stringify and check that, = taking the unique chars =&# keeps the length identical I. output all true indices ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞€ÙÙ ``` Outputs an infinite list. [Try it online.](https://tio.run/##yy9OTMpM/f//Uce8R01rDs88PPP/fwA) **Explanation:** ``` ∞ # Push an infinite list of positive integers: [1,2,3,...] €Ù # Uniquify the digits in each integer Ù # Uniquify this infinite list # (after which this 'filtered' infinite list is output implicitly as result) ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes ``` .'??'$!_1e10 ``` [Try it online! (with 1e3 instead of 1e10)](https://ngn.codeberg.page/k#eJzTU7e3V1dRjDdMNQYADVQCaA==) Uses xnor's idea: take unique digits from each number and then take unique results of that. Because the result is a list of strings, `.'` is necessary to convert them back to numbers. --- # [K (ngn/k)](https://codeberg.org/ngn/k), 15 bytes ``` &~'/?:'\$!_1e10 ``` [Try it online! (with 1e3 instead of 1e10)](https://ngn.codeberg.page/k#eJxTq1PXt7dSj1FRjDdMNQYAGSYDZA==) ``` &~'/?:'\$!_1e10 !_1e10 0..9999999999 $ stringify each number ?:'\ iterate-collect over "uniquify each string" which gives zeroth (original) and first (uniquified) iterations ~'/ 1 if the two are equal, 0 otherwise for each item & output nonzero indices ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/blob/main/documents/knowledge/elements.md), 26 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.25 [bytes](https://github.com/Vyxal/Vyxal/blob/77753d4d26a5c2c3d1a64fc348204d27397e2844/vyxal/encoding.py) ``` Þ∞'Þu ``` Outputs an infinite list. [Try it online.](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiw57iiJ4nw551IiwiIiwiIl0=) **Explanation:** ``` Þ∞ # Push an infinite positive list: [1,2,3,...] ' '# Filter it by: Þu # All digits in the integer are unique # (after which this filtered infinite list is output implicitly as result) ``` [Answer] # [Python 3](https://docs.python.org/3.8/), 49 bytes ``` n=1 while 1/n:10**len({*str(n)})>n!=print(n);n+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P8/WkKs8IzMnVcFQP8/K0EBLKyc1T6Naq7ikSCNPs1bTLk/RtqAoM68EyLPO07Y1/P8fAA "Python 3.8 (pre-release) – Try It Online") Uses my `10**` trick [from 2014](https://codegolf.stackexchange.com/a/28365/20260). Converting the string representation of \$n\$ to a set removes duplicates, and we check whether this decreases the length by comparing to \$10^n\$, which is bigger than all \$n\$-digit number but no \$(n+1)\$-digit numbers. The `1/n` is used to theoretically halt for large enough `n` because doubles become zero around `1e-308` due to finite precision. If the program may just continue to run forever after printing all the numbers, this can be: **46 bytes** ``` n=0 while[10**len({*str(n)})>n!=print(n)]:n+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P8/WgKs8IzMnNdrQQEsrJzVPo1qruKRII0@zVtMuT9G2oCgzrwTIi7XK07Y1/P8fAA "Python 3.8 (pre-release) – Try It Online") [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 43 bytes ``` for(i=99e9;i;)/(.).*\1/.test(--i)||print(i) ``` [Try it online!](https://tio.run/##BcFRCoAgDADQ62yBip8i3aQfqQUrUpkjCLz7eu8qbxm7cFc3Oh8kT6s3fWZnE@A1JYqZMwbw6JctBq80FJxjnLMLVwVGsx8 "JavaScript (SpiderMonkey) – Try It Online") (Linked version prints only up to 3 digits to avoid time out) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 3 bytes ``` ŇƊů ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FsuOth_rOrp-SXFScjFUCCYFAA) Outputs a list of lists of digits, without leading zeros. Zero is also output in this way (so appears in the output as an empty list). ``` Ň # nondeterminiatically choose a natural number Ɗ # convert it to a list of decimal digits ů # keep them if they are all unique ``` --- # [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes ``` ŇƊůN ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FsuPth_rOrreb0lxUnIxVAwmBwA) Outputs a list of lists of digits, without leading zeros. Zero is not part of the output. Works as the shorter answer above, but with an additional `N` to reject empty lists. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ℕ≜≠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh9sWHNr5qHEDEP1/1DL1UeecR50L/v//HwUA "Brachylog – Try It Online") This is a generator, the output of this predicate unifies with each possible integer in increasing magnitudes. The try it online link has a header to unify the first 100 values. ### Explanation ``` ℕ A non-negative integer ≜ Pick one of them ≠ All elements (i.e. digits) must be different ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ΦI…⁰Xχχ¬⊙ι⊖№ιλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUjDObG4RCMoMS89VcNARyEgvxwoZghkmWhqauoo@OWXaDjmVWpk6ii4pCYXpeam5pWkpmg455cCTQAK5miCgfX///91y3IA "Charcoal – Try It Online") Link is to verbose version of code but only goes to `9876` because it would be too slow or run out of memory. Explanation: ``` … Range from ⁰ Literal integer `0` χ Predefined variable 10 X Raised to power χ Predefined variable 10 I Cast to string Φ Filtered where ι Current string ¬⊙ No character satisfies № Count of λ Current character ι In current string ⊖ Is not `1` Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 27 bytes ``` 9999999999$*¶ $.` A`(.).*\1 ``` [Try it online!](https://tio.run/##K0otycxL/P@fyxIIVLQObePiUtFL4HJM0NDT1NOKMfz/HwA "Retina 0.8.2 – Try It Online") Link only goes to `9876` because it would be too slow or run out of memory. Explanation: ``` 9999999999$*¶ $.` ``` List the numbers up to `9999999999`. ``` A`(.).*\1 ``` Delete those with duplicate digits. [Answer] # [Julia](https://julialang.org), 45 bytes ``` (r=1:2^34)[allunique.(r.|>x->"$x")].|>println ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjd1NIpsDa2M4sw1oxNzckrzMgtLU_U0ivRq7Cp07ZRUKpQ0Y4HsgqLMvJKcPIgeqFaYEQA) Any number larger than 10^10 is a suitable upper limit for the range; using `2^34` saves a byte (this is reduces to `2^7` in the linked solution). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~29~~ 30 bytes ``` p (?0..?9*10).grep_v /(.).*\1/ ``` [Try it online!](https://tio.run/##KypNqvyvrq7@v0BBw95AT8/eUsvQQFMvvSi1IL5MQV9DT1NPK8ZQH6SEi0tZISQjs1gBiEoyUhWKE3NTFcozSzIUzBRSMtMzS4q5EIaYYTEDAA "Ruby – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 47 bytes ``` f=->a=[*?1..?9],s=""{a.map{|i|f[a-[i],p(s+i)]}} ``` [Try it online!](https://tio.run/##Ncs5DsIwEADAr6xCw5FYQqlNivALy8UifGzhQ/EahJK83dBQj2apj0873E1IsTAypQhvYg9PcsQFrkKMIGD2GJ0B9uYPnMDRy0BIi4FUOVcWAM3K4YZSnadfnEbdF9l1K4qAed1oswoHRbrPx3Khk973ZpVuXw "Ruby – Try It Online") Link is a demo with only the digits `1..3` This recursively builds up the number from a pool of available digits. Longer than I had hoped for this approach, but efficient. [Answer] # [Bash](https://www.gnu.org/software/bash/), 34 ``` seq -f%.0f 1e10|grep -Ev '(.).*\1' ``` If you have the `jot` command installed, you can save 1 byte by replacing the seq command with `jot 9876543210`. This is quite slow - I think its been running 2 hours already and is 40% through. [Try it online!](https://tio.run/##S0oszvj/vzi1UEE3TVXPIE3BMNXQoCa9KLVAQde1TEFdQ09TTyvGUP3/fwA "Bash – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ȷ10Q€ḌQ ``` [Try it online!](https://tio.run/##y0rNyan8///EdtPAR01rHu7oCfz/HwA "Jelly – Try It Online") A niladic link returning the full list of numbers. TIO link only returns values <1e5 since otherwise it runs out of memory (and would time out if not) Uses the same methodology as [@KevinCruijssen’s 05AB1E answer](https://codegolf.stackexchange.com/a/265312/42248) so upvote that one too! ]
[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/17415/edit). Closed 6 years ago. [Improve this question](/posts/17415/edit) Write a function that rotates an integer array by a given number k. k elements from the end should move to the beginning of array, and all other elements should move to right to make the space. The rotation should be done in-place. Algorithm should not run in more than O(n), where n is the size of array. Also a constant memory must be used to perform the operation. For example, if array is initialized with elements arr = {1, 2, 3, 4, 5, 6, 7, 8, 9} rotate(arr, 3) will result the elements to be {7, 8, 9, 1, 2, 3, 4, 5, 6} rotate(arr, 6) will result the {4, 5, 6, 7, 8, 9, 1, 2, 3} [Answer] ## C (104) ``` void reverse(int* a, int* b) { while (--b > a) { *b ^= *a; *a ^= *b; *b ^= *a; ++a; } } void rotate(int *arr, int s_arr, int by) { reverse(arr, arr+s_arr); reverse(arr, arr+by); reverse(arr+by, arr+s_arr); } ``` Minified: ``` v(int*a,int*b){while(--b>a){*b^=*a;*a^=*b;*b^=*a++;}}r(int*a,int s,int y){v(a,a+s);v(a,a+y);v(a+y,a+s);} ``` [Answer] # APL (4) ``` ¯A⌽B ``` * A is the number of places to rotate * B is the name of the array to be rotated I'm not sure if APL actually required it, but in the implementation I've seen (the internals of) this would take time proportional to `A`, and constant memory. [Answer] Here is a long winded C version of Colin's idea. ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int gcd(int a, int b) { int t; if (a < b) { t = b; b = a; a = t; } while (b != 0) { t = a%b; a = b; b = t; } return a; } double arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int s_arr = sizeof(arr)/sizeof(double); /* We assume 1 <= by < s_arr */ void rotate(double *arr, int s_arr, int by) { int i, j, f; int g = gcd(s_arr,by); int n = s_arr/g; double t_in, t_out; for (i=0; i<g; i++) { f = i; t_in = arr[f + s_arr - by]; for (j=0; j<n; j++) { t_out = arr[f]; arr[f] = t_in; f = (f + by) % s_arr; t_in = t_out; } } } void print_arr(double *arr, int s_arr) { int i; for (i=0; i<s_arr; i++) printf("%g ",arr[i]); puts(""); } int main() { double *temp_arr = malloc(sizeof(arr)); int i; for (i=1; i<s_arr; i++) { memcpy(temp_arr, arr, sizeof(arr)); rotate(temp_arr, s_arr, i); print_arr(temp_arr, s_arr); } } ``` [Answer] ## C Not sure what the criteria is, but since I had fun with the algorithm, here is my entry: ``` void rotate(int* b, int size, int shift) { int *done; int *p; int i; int saved; int c; p = b; done = p; saved = *p; for (i = 0; i < size; ++i) { c = saved; p += shift; if (p >= b+size) p -= size; saved = *p; *p = c; if (p == done) { p += 1; done = p; saved = *p; } } } ``` I'll golf it for a good measure too; 126 bytes, can be made shorter: ``` void r(int*b,int s,int n){int*d,*p,i,t,c;d=p=b;t=*p;for(i=0;i<s;++i){c=t;p+=n;if(p>=b+s)p-=s;t=*p;*p=c;if(p==d){d=++p;t=*p;}}} ``` [Answer] I don't see very many C++ solutions here, so I figured I'd try this one since it doesn't count characters. This is true "in-place" rotation, so uses 0 extra space (except technically swap and 3 ints) and since the loop is exactly N, also fulfills the O(N) complexity. ``` template <class T, size_t N> void rot(std::array<T,N>& x, int shift) { size_t base=0; size_t cur=0; for (int i = 0; i < N; ++i) { cur=(cur+shift)%N; // figure out where we are going if (cur==base) // exact multiple so we have to hit the mods when we wrap { cur++; base++; } std::swap(x.at(base), x.at(cur)); // use x[base] as holding area } } ``` [Answer] If you perform each of the possible cycles of rotations by n in turn (there are GCD(n, len(arr)) of these), then you only need a single temporary copy of an array element and a few state variables. Like this, in Python: ``` from fractions import gcd def rotate(arr, n): total = len(arr) cycles = gcd(n, total) for start in range(0, cycles): cycle = [i % total for i in range(start, abs(n * total) / cycles, n)] stash = arr[cycle[-1]] for j in reversed(range(1, len(cycle))): arr[cycle[j]] = arr[cycle[j - 1]] arr[cycle[0]] = stash ``` [Answer] **C (137 characters)** ``` #include <stdio.h> void rotate(int * array, int n, int k) { int todo = (1<<n+1)-1; int i = 0, j; int tmp = array[0]; while (todo) { if (todo & 1<<i) { j = (i-k+n)%n; array[i] = todo & 1<<j ? array[j] : tmp; todo -= 1<<i; i = j; } else tmp = array[++i]; } } int main() { int a[] = {1,2,3,4,5,6,7,8,9}; rotate(a, 9, 4); for (int i=0; i<9;i++) printf("%d ", a[i]); printf("\n"); } ``` Function `rotate` minified to 137 characters: ``` void r(int*a,int n,int k){int m=(1<<n+1)-1,i=0,j,t=a[0];while(m)if(m&1<<i){j=(i-k+n)%n;a[i]=(m&1<<j)?a[j]:t;m-=1<<i;i=j;}else t=a[++i];} ``` [Answer] Factor has a built-in type for rotatable arrays, `<circular>`, so this is actually a O(1) operation: ``` : rotate ( circ n -- ) neg swap change-circular-start ; IN: 1 9 [a,b] <circular> dup 6 rotate >array . { 4 5 6 7 8 9 1 2 3 } IN: 1 9 [a,b] <circular> dup 3 rotate >array . { 7 8 9 1 2 3 4 5 6 } ``` A less cheatish Factor equivalent of Ben Voigt's impressive C solution: ``` : rotate ( n s -- ) reverse! swap cut-slice [ reverse! ] bi@ 2drop ; IN: 7 V{ 0 1 2 3 4 5 6 7 8 9 } [ rotate ] keep . V{ 3 4 5 6 7 8 9 0 1 2 } ``` [Answer] # JavaScript 45 Went for golf anyway because I like golf. It is at maximum O(N) as long as `t` is <= size of the array. ``` function r(o,t){for(;t--;)o.unshift(o.pop())} ``` To handle `t` of any proportion in O(N) the following can be used (weighing in at 58 characters): ``` function r(o,t){for(i=t%o.length;i--;)o.unshift(o.pop())} ``` Doesn't return, edits the array in place. [Answer] ## [REBEL](http://kendallfrey.com/projects/rebel.php) - 22 ``` /_(( \d+)+)( \d+)/$3$1 ``` Input: k expressed as a unary integer using `_` as a digit, followed by a space, then a space-delimited array of integers. Output: A space, then the array rotated. Example: ``` ___ 1 2 3 4 5/_(( \d+)+)( \d+)/$3$1 ``` Final state: ``` 3 4 5 1 2 ``` Explanation: At each iteration, it replaces one `_` and an array `[array] + tail` with `tail + [array]`. Example: ``` ___ 1 2 3 4 5 __ 5 1 2 3 4 _ 4 5 1 2 3 3 4 5 1 2 ``` [Answer] # Java ``` public static void rotate(int[] arr, int by) { int n = arr.length; int i = 0; int j = 0; while (i < n) { int k = j; int value = arr[k]; do { k = (k + by) % n; int tmp = arr[k]; arr[k] = value; value = tmp; i++; } while (k != j); j++; } } ``` Demo [here](http://ideone.com/V3MOe8). Minified **Javascript, 114**: ``` function rotate(e,r){n=e.length;i=0;j=0;while(i<n){k=j;v=e[k];do{k=(k+r)%n;t=e[k];e[k]=v;v=t;i++}while(k!=j);j++}} ``` [Answer] # Haskell This is actually θ(n), as the split is θ(k) and the join is θ(n-k). Not sure about memory though. ``` rotate 0 xs = xs rotate n xs | n >= length xs = rotate (n`mod`(length xs)) xs | otherwise = rotate' n xs rotate' n xs = let (xh,xt) = splitAt n xs in xt++xh ``` [Answer] # Python 3 ``` from fractions import gcd def rotatelist(arr, m): n = len(arr) m = (-m) % n # Delete this line to change rotation direction for i0 in range(gcd(m, n)): temp = arr[i0] i, j = i0, (i0 + m) % n while j != i0: arr[i] = arr[j] i, j = j, (j + m) % n arr[i] = temp ``` Constant memory O(n) time complexity [Answer] ## Python ``` def rotate(a, n): a[:n], a[n:] = a[-n:], a[:-n] ``` [Answer] **python** ``` import copy def rotate(a, r): c=copy.copy(a);b=[] for i in range(len(a)-r): b.append(a[r+i]);c.pop();return b+c ``` [Answer] **vb.net** O(n) (not Constant memory) ``` Function Rotate(Of T)(a() As T, r As Integer ) As T() Dim p = a.Length-r Return a.Skip(p).Concat(a.Take(p)).ToArray End Function ``` [Answer] ### Ruby ``` def rotate(arr, n) arr.tap{ (n % arr.size).times { arr.unshift(arr.pop) } } end ``` [Answer] ## C (118) Probably was a bit too lenient with some of the specifications. Uses memory proportional to `shift % length`. Also able to rotate in the opposite direction if a negative shift value is passed. ``` r(int *a,int l,int s){s=s%l<0?s%l+l:s%l;int *t=malloc(4*s);memcpy(t,a+l-s,4*s);memcpy(a+s,a,4*(l-s));memcpy(a,t,4*s);} ``` [Answer] # Python 2, 57 ``` def rotate(l,n): return l[len(l)-n:len(l)]+l[0:len(l)-n] ``` If only `l[-n:len(l)-n]` worked like I'd expect it to. It just returns `[]` for some reason. [Answer] ``` def r(a,n): return a[n:]+a[:n] ``` Could someone please check if this actually meets the requirements? I think it does, but it I haven't studied CS (yet). [Answer] ## C++, 136 ``` template<int N>void rotate(int(&a)[N],int k){auto r=[](int*b,int*e){for(int t;--e>b;t=*b,*b++=*e,*e=t);};r(a,a+k);r(a+k,a+N);r(a,a+N);} ``` [Answer] # Java Swap the last k elements with the first k elements, and then rotate the remaining elements by k. When you have fewer than k elements left at the end, rotate them by k % number of remaining elements. I don't think anyone above took this approach. Performs exactly one swap operation for every element, does everything in place. ``` public void rotate(int[] nums, int k) { k = k % nums.length; // If k > n, reformulate rotate(nums, 0, k); } private void rotate(int[] nums, int start, int k) { if (k > 0) { if (nums.length - start > k) { for (int i = 0; i < k; i++) { int end = nums.length - k + i; int temp = nums[start + i]; nums[start + i] = nums[end]; nums[end] = temp; } rotate(nums, start + k, k); } else { rotate(nums, start, k % (nums.length - start)); } } } ``` [Answer] # [Perl 5](https://www.perl.org/), 42 bytes ``` sub r{$a=pop;map{unshift@$a,pop@$a}1..pop} ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4NEmhqFol0bYgv8A6N7GgujSvOCMzrcRBJVEHKASkag319ICs2v8OSbYahjpGOsY6JjqmOmY65joWOpaa1kUaxjoxDkma1sWJlUoOSUr//@UXlGTm5xX/1/U11TMwNAAA "Perl 5 – Try It Online") Subroutine takes the distance to rotate as the first parameter and a reference to the array as the second. Run time is constant based on the distance of the rotation. Array size does not affect run time. Array is modified in place by removing an element from the right and putting it on the left. ]
[Question] [ On the TV cooking show [Guy's Grocery Games](https://en.wikipedia.org/wiki/Guy%27s_Grocery_Games), the chefs cannot begin shopping until Guy Fieri, the show's host, says "Three, two, one, go!" However, the words do not have to be all together. He often "hides" the words in things like this (based on a real example, but not quoting verbatim): > > There are *three* of you here; after this round there will be *two*; but only *one* of you will *go* shop for up to $20,000. > > > (At the end of the show, the winning chef must find either five or ten items, depending on the episode, from the store; the number of items found determines how much money they win.) Fairly regularly, he succeeds in confusing the chefs and they don't go. Often, they realize after a few seconds that they can go and frantically run down the aisles trying to make up for the lost time; other times, they don't realize it until the judges start shouting "Go! Go! Go!" Can you do better? Write a program that determines 1. Whether the input string allows the chefs to go, and 2. If so, at what point in the string they may go. The chefs may go if the string contains `three`, followed by zero or more other characters, followed by `two`, followed by zero or more other characters, followed by `one`, followed by zero or more other characters, followed by `go`. Matching is case-insensitive. The point at which the chefs may go is the zero-based index of the `o` in `go`. Because `ThreeTwoOneGo` is 13 characters, this number will always be at least 12. If the chefs can go, return the point at which they can go. If they cannot, return no value, any falsy value, or any number of your choice less than or equal to 11. This number does not need to be consistent; it's okay if it varies randomly and/or with the input, as long as it is consistently less than or equal to 11. [Answer] # R, 51 bytes `regexpr("three.*two.*one.*g\\Ko",scan(,""),,T)[1]-1` Thanks to Bbrk24 for pointing out that `\K` (you have to use an extra backslash in R) sets where the match is considered to start. R has a lot of built in regex functions, and this one handily tells you where the first match starts (-1 if there is no match). It's 1-indexed though, so we have to take 1 off (and hence, if the chefs can't go, -2 is returned, but that's less than 11 so we're good). We need to specify `perl=TRUE` to use the `\K` feature. It's cheapest to specify that positionally rather than use `pe=T`. [![two example cases where the code returns 25 for a string where the cooks can go, and -2 for a case where they can't go at all](https://i.stack.imgur.com/3Hjcx.png)](https://i.stack.imgur.com/3Hjcx.png) Depending on conventions for how the input is available, the `scan(,"")` could turn into a variable (e.g. `x`) or function (`\(x)`) saving 8 or 4 bytes respectively. [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 34 bytes Returns `0` on invalid inputs. Performs a match against the input, using the result to decrement the last position of the match, [via `@+`](https://perldoc.perl.org/perlvar#@+), by `1` (on successful matches, otherwise `0`). ``` $_=-/three.*?two.*?one.*?go/i+"@+" ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJF89LS90aHJlZS4qP3R3by4qP29uZS4qP2dvL2krXCJAK1wiIiwiYXJncyI6Ii1wbCIsImlucHV0IjoiVGhlcmUgYXJlIHRocmVlIG9mIHlvdSBoZXJlOyBhZnRlciB0aGlzIHJvdW5kIHRoZXJlIHdpbGwgYmUgdHdvOyBidXQgb25seSBvbmUgb2YgeW91IHdpbGwgZ28gc2hvcCBmb3IgdXAgdG8gJDIwLDAwMC5cblRocmVlVHdvT25lR29cblRocmVlVHdvT25lR29nb2dvZ29nb2dvZ29nb2dvIVxudGhyZWV0d29vbmVnb3RocmVldHdvb25lZ29cblRocmVlIGh1bmRyZWQgYW5kIHR3byBpcyBhIGJpZyBudW1iZXIgZm9yIG9uZSwgZ29vZCBqb2IhXG5UaHJlZSwgdHdvLCBvbmUuLi4gc3RvcCJ9) [Answer] # JavaScript (ES11), 40 bytes *-6 bytes thanks to [InSync](https://codegolf.stackexchange.com/users/117141/insync)* Returns -1 for invalid inputs. ``` s=>s.search(/(?<=three.*two.*one.*g)o/i) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lU9LDoIwEN17iglxUYgW4soE0Ut4AT5TIGk6pJ8QzuKGGD2Pa29jC8a9i_lk5r03b24PRQ3Od1E8nRX745uZ4my4wVLXHUvZ5VTYTiPyxI7EE1K-a2NK-_iLf9WkDEnkklomWHTtUCOUPhYekICJHIRpDqWwqP2iN6DJqca3AT32UkLlGSPlUDkLpOTk04-9AFoC09EAgjS4ASzB9pDtsizjURxv_rERTvjLQW4E76UuVY0SmyC0vjXPa_0A) ### Method Using a lookbehind assertion, we look for the position of the first `"o"` in the input string which is preceded by the pattern `"three.*two.*one.*g"`. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 25 bytes ``` I^iw0`three.*two.*one.*go ``` [Try it online!](https://tio.run/##PY0xCsMwFEOvokKnUIzbNQconbpkLkmoHRuMFRwbk9O7Pxk66CO@9FAy2cfp3trr46ses0vGqC5Xqo5R3MLWBmeSwSQ6Y9BiZ8Hx7THZbJIEfkNiiV@xR7v6EDALUdljLhmMYZfzp8/CQmyOKywTyopMXB/6prVWGM6poRJvgZ68/AA "Retina – Try It Online") The regex is pretty straightforward, all the magic comes from the configuration flags at the beginning: * `I`: find the position of the matches * `^`: use the position of the last character instead of the first * `i`: case insensitive * `w`: do this for all possible ways (even overlapping) of matching this regex * `0`: return only the first one In practice, `w0` will make sure that we return the earliest possible complete match, and is shorter than any other option based on lazy matching (`.*?`) [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 24 bytes ``` ʀ"ỌṚUmn»\6”Ṃ".*?"j∥ẋMṪL+ ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLKgFwi4buM4bmaVW1uwrtcXDbigJ3huYJcIi4qP1wiauKIpeG6i03huapMKyIsIiIsIlRoZXJlIGFyZSB0aHJlZSBvZiB5b3UgaGVyZTsgYWZ0ZXIgdGhpcyByb3VuZCB0aGVyZSB3aWxsIGJlIHR3bzsgYnV0IG9ubHkgb25lIG9mIHlvdSB3aWxsIGdvIHNob3AgZm9yIHVwIHRvICQyMCwwMDAuIiwiMy4yLjAiXQ==) | [Literate mode equivalent (doesn't work)](https://vyxal.github.io/latest.html#WyIiLCIiLCJsb3dlciBcIuG7jOG5mlVtbsK7XFw24oCdIHNwbGl0LXNwYWNlIFwiLio/XCIgam9pbi1vbiBwYXJhbGxlbC1hcHBseSByZS1zZWFyY2ggcmUtbWF0Y2ggcmVtb3ZlLWxhc3QgbGVuIGFkZCIsIiIsIlRocmVldHdvb25lZ28gdGhyZWUgdHdvIG9uZSBnbyIsIjMuMi4wIl0=) **Explanation**: ``` ʀ"ỌṚUmn»\6”Ṃ".*?"j∥ẋMṪL+­⁡​‎⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌­ "ỌṚUmn»\6”Ṃ".*?"j # ‎⁡Split "ỌṚUmn»\6” ("three two one go") on spaces and join by ".*?" ʀ ∥ẋM # ‎⁢Parallel apply regex search and regex match to lowercased input ṪL+ # ‎⁣Add length - 1 to index 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` “Ç<*tẉ{cIE»Ḳṫw¥ƒŒlL’ȧạ¥L ``` [Try it online!](https://tio.run/##PcshDsJAEEDRqyyWhBtgESS9RGmH7pLtDNmZpmkwOIKtI8EgGgQOBcWVQLjG9iILNZiv3l@BtVUI/fb43E3H4tv9JpnPuoe/Xf39UnbNu37VNuq3h8/Zt6euiUIIoh3AJDU5IBvC2KrEQWqkJCfaIDArWqo1V4kmhMKRyfMCyVJmWFgZVgsQAadExzhEBk9C7neTjV2F2V9nNPoC "Jelly – Try It Online") A monadic link taking a string and returning an integer. *Thanks to @JonathanAllan for pointing out the case-insensitive requirement!* ## Explanation ``` “Ç<*tẉ{cIE»Ḳ | Compressed string "three two one go" split at spaces ṫw¥ƒŒl | Reduce, starting with the main link argument lower-cased, then for each of the strings above, find the first position in the current string and take the tail starting from there L | Length ’ | Decrease by 1 ȧạ¥L | And with absolute difference from this and the length of the original string ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` i1M!`.*?three.*?two.*?one.*?g(?=o) . ``` [Try it online!](https://tio.run/##PY3BCoMwEETvfsUILVgpkvYqxaOn0osfoNKoAclITAh@fZp46GFnh903jJFW6SFci7YP6vHO@6ps7GKkTNszKnXyc9G8eMuqELpFGokhzsmBEw46pGuNYbLSxIfaYej0N9pEe7WuGGPCs8boLKjXI8o/fQIzsS/cMNHAbbDE5SnuQogq@0S080R3VrbMfw "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` for disallowed inputs. Explanation: ``` i1M!`.*?three.*?two.*?one.*?g(?=o) ``` Keep only the text up to the `g` of `go` (or delete the text entirely if it doesn't contain the words in the right order). ``` . ``` Count the number of characters remaining. [Answer] # [Scala 3](https://www.scala-lang.org/), 77 bytes ``` s=>new Regex("(?i)(?<=three.*two.*one.*g)o").findFirstMatchIn(s).map(_.start) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nZDPSsNAEMbxmouv8BE87BYbgl6kNS1ehB6K4J9TKLJNNslKuhs2E9MifRIvXvTiE9WncZNIH8CF2R1mvvn2x7x_1YkoxeV37I-1aYXV_uoQq01lLKFvBQ2pMtgISgql8-Be5nLreWb9IhPCUiiNN88DXkWJTOl0oVO5nYA9kHVyRDPcVaSMjheaVhzRZ0PZ-OqwrKOZli16O-azueJsfh1RYaUMRtSaYGS0y3JufB50xrfK1rTsMBaa1dwRVew5qElY4oPpz8kpkMoMG0fFhM3rCW6sFbt4gFnxCZ60IkQOGe5UrkqlZkdu5j8W0koIFz0KTIadadBVpxAZSesaqoY1jU5d2qlbVZZYu4nWTLFuCEaXO3cdp3tBblAXpkJmLJoKZHB2EZ6HYRj4nP8Lp_vKEXS2LRxTInQiS5n-Ge69_bCXj4_h_QU) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` lηÅΔηU“„í‚•€µ‚œ“#εXsδÅ¿ƶ0K}.«âε˜D{Q}à ``` What a mess.. Once again I hate that 05AB1E lacks a builtin to get all matching indices, instead of only the first.. The `ηU` and `εXsδÅ¿ƶ0K}` are all to do that manually.. -\_- Will output `-1` if it's invalid. [Try it online](https://tio.run/##yy9OTMpM/f8/59z2w63nppzbHvqoYc6jhnmH1z5qmPWoYdGjpjWHtgKZRycDxZXPbY0oPrflcOuh/ce2GXjX6h1afXjRua2n57hUB9YeXvD/v4Z7vqKCf16qQkl5vkJJRlFqqp6mQkhGalGqQiIQp@WXFinkpylU5pcqgAStFRLTSlKLgCozixWK8kvzUoBMkOLyzJwchSSIMRp5@SUQszStFZJKSxTy83IqgUQqzCSw4vR8heKM/AKgFUUKpQUKJfkKKkYGOgYGBnoA) or [verify a few test cases](https://tio.run/##vU69SsRAEO59ivEUvIMQFtsrrhEsBEVQsE3IxizEnWN3kyNoIAjnA6iVHCLXqp3xSiGLNsI@xL5I3FxA38BihuGb7w9lEDLaXuXFZAD25hYGk6JNzUrPzb1ZndpqYatH/WqrB1st7fVLU7vz887hW6Y@k@ZNz5uPr3dyUPrNs16a@nuxd3lc6qe29NqThAoKgRuVCEoBYygwgw4dQxArKtyDSRCY8cidHXvG0hRCp5ghDDmqXjoaQ5gpQJ4Wbv06rcnnCDLBKcQoIJuCQtjeJR4hxN8Y7uMmHPHebW3kj@CvVYyZ@P9SXadDmrucC8Yjr0/r9EzyHQV5kLLI/wE). **Explanation:** ``` l # Convert the (implicit) input-string to lowercase η # Convert it to a list of prefixes ÅΔ # Get the index of the first prefix that's truthy for # (or -1 if none are): η # Get the prefixes of the current prefix U # Pop and store it in variable `X` “„í‚•€µ‚œ“ # Push dictionary string "three two one go" # # Split it on spaces ε # Map over all four words: X # Push the earlier list of prefixes of the prefix s # Swap so the current word is at the top again δ # Map over each prefix, using the word as argument: Å¿ # Check whether the prefix ends with the word as substring ƶ # Multiply each check by its 1-based index 0K # Remove all 0s }.« # After the map: reduce this list of lists by: â # Taking the cartesian product of two lists ε # Map over each combination of values: ˜ # Flatten it to a single list D{Q # Check if the four indices are in increasing order: D # Duplicate the list { # Sort the copy Q # Check if both lists are still the same }à # After the map: check if any was truthy # (after which the found index is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“„í‚•€µ‚œ“` is `"three two one go"`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔θηF⪪”↶⌊¶z₂1γmι.Jχ” ≔✂η⌕↧ηιLη¹η¿⊖LηI⁻Lθ⊖Lη ``` [Try it online!](https://tio.run/##dZDLasMwEEX3@YqL6UICtbjdelVaukqhkP6Aoowtgapx9KjJ16uykyy7GJjHPcPcMVZHw9rX@pqSm4I4K1g57EaOEIfZuyy6bCMR8sLgQJi4U@jQSYkbcvDOkLAKHy6cxJ4Xikan1pEKrsWewpTtVj7L63o3QryTifRDIVOD7pK29Su6kMWbTll8ulDSfXhu7D@MlEOt35YiQbe4HswjLlywdgfoMVNsA5cQuYRTS1f14rzHcTM34Fhyc@gvm80bvQkmRrI8Y31KmZEZDy@96vv@aVcff/0f "Charcoal – Try It Online") Link is to verbose version of code. Does not output anything for disallowed inputs. Explanation: ``` ≔θη ``` Make a copy of the input string. ``` F⪪”....” ``` Loop over the four relevant words. ``` ≔✂η⌕↧ηιLη¹η ``` Slice the string so that it starts at that word. (But if the word is not present, the `Find` returns `-1`, which causes the `Slice` to return the last character.) ``` ¿⊖Lη ``` If the string still contains at least two characters (which means it begins `go`), then... ``` I⁻Lθ⊖Lη ``` Output `1` more than the number of characters removed. [Answer] # Python 3, ~~93~~ 77 bytes I'm new to `regex`, so open to golfs. Returns an integer for truthy and a `None` object for falsy. ``` lambda n:((x:=re.search("three.*?two.*?one.*?go",n,2))and~-x.end()) import re ``` [Answer] # [Uiua](https://uiua.org) 0.6.1, 38 [bytes](https://codegolf.stackexchange.com/questions/247669/i-want-8-bits-for-every-character/265917#265917) ``` -1⧻⊢⊢regex"(?is).*three.*two.*one.*go" ``` [Try it yourself](https://uiua.org/pad?src=0_6_1__JCBUaGVyZSBhcmUgdGhSRUVFRUVFRSBvZiB5b3UgaGVyZTsKJCBhZnRlciB0aGlzIHJvdW5kIHRoZXJlIHdpbGwgYmUgdHdvOwokIGJ1dCBvbmx5IG9uZSBvZiB5b3UKJCB3aWxsIGdvIHNob3AgZm9yIHVwIHRvICQyMCwwMDAuIgoKLTHip7viiqLiiqJyZWdleCIoP2lzKS4qdGhyZWUuKnR3by4qb25lLipnbyIK) [Answer] # [Pip](https://github.com/dloscutoff/pip), 30 bytes ``` a~-`three.*?two.*?one.*?go`D$) ``` Outputs an index, or nothing if the chefs cannot go. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhfi1gdGhyZWUuKj90d28uKj9vbmUuKj9nb2BEJCkiLCIiLCJcIlRocmVlIHR3b3Mgb25lcm91cyBnb25lIHRocmVldHdvb25lZ29nb2dvXCIiLCIiXQ==) (Note that this doesn't work on ATO as of posting, and might stop working on DSO in the future, because the way Pip currently handles regex case-insensitivity doesn't play well with newer versions of Python. I may get around to fixing that someday.) ### Explanation ``` `three.*?two.*?one.*?go` ; Regex, with non-greedy quantifiers - ; Make it case-insensitive a~ ; Find the first match in the program argument $) ; Get the index of the end of that match D ; Decrement ``` [Answer] # [C](https://en.wikipedia.org/wiki/C_(programming_language)) ([gcc](https://gcc.gnu.org/)): ~~119~~ 113 bytes ``` main(c,v)char**v;{char*s="go\0.one\0two\0three",*p=*++v;for(c=4;c--;)p+=strcasestr(p,s+4*c)-(int)p;exit(++p-*v);} ``` Edit: Thanks to everyone helping in improving the answer! :D 1. As always a minor improvement was made thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) (124 -> 122 bytes). 2. Thanks to [@Command Master](https://codegolf.stackexchange.com/users/92727/command-master) for getting rid of the prototype (119 -> 113 bytes). # [C](https://en.wikipedia.org/wiki/C_(programming_language)) ([gcc -m32](https://gcc.gnu.org/)): 105 bytes ``` main(c,v)char**v;{char*s="go\0.one\0two\0three",*p=*++v;for(c=4;c--;)p=strcasestr(p,s+4*c);exit(++p-*v);} ``` ~~The prototype feels like a huge waste of bytes. Unfortunately, I could not figure out how to work around that. :/~~ Edit: Using the `-m32` flag you can get rid of the prototype entirely (explained in the comments below). Thanks to [@Command Master](https://codegolf.stackexchange.com/users/92727/command-master) for suggesting this trick. :) [Try it online](https://tio.run/##bVNNj9MwED3TXzHqJf3MglhxoOqBI9KKE5xYDlN7klh17eBxkq0Qf50ydtJSEJHSpOOZN2/evKhtrdTlckLjFmrTL1WDYbXqdz9mINfDAxRcgPIuSgJDbAiOdB580OkPRsBA0KLWpGEwsYGiLIB9Tmy9cZECKHRXsAPByfeSezgDQmVe5LVH2xFED7VPv6nS0Uu89imn2huf9h8@xml6AV8BoWquVbCgnlzs0Nrz31lF7YvlFRQ@VuA8nDBKqWGofOd0bjEYaxPdT1@engAlqLBjEtJM9UmQMRrvoMLOxhvY0JgE47RRGGkSaGzedhG0l5jzopm1fsgHqqGKx9lvKJ8lzvS9I6coceLog8hkHASZKSQSDCYCYy94JzkEblHRCJD3x/t57Z9fl97R8@s4yGtsAtF8s2r3q/W6381ybuXDQu0fd2q73S1z5I5Cg2eOqI6JQhJE5I6EOknYf33zDdgkfrGRY21YYXIEunMmgEr2zveIB6oS0TSzRY6T4qNgbci7EjEtJ9ewiSaNZs2R3t@DzGWUsizzLGUarizrFJjPXok/5IYPWvPkINKWCha6FZNgB3/KY4jW8tiM6gsT42qIwahjrssgyp9aY8W4aS@ULJ5dkRfJLF4VCRrsc6XENCmL02xt8NHHczsCSR7HIF1IHovJdOlq1/u7g3bD68eVWm4X8r0s22k5k9UbzP44JBOpQMl6YobRAf//DIq6uPp87EgvJi7W63a76pe72c/LtGB0PMiQkvrHogdKzuTGd1annm/fXS4Hi42InqSflL@L3LaQYr9UZbHmy3b4DQ) **Explanation**: ``` main(c,v)char**v;{ // 's' contains the keywords that are padded with '.' so the pointer can // be moved by a fixed value to go to the next keyword. // // 'p' contains the index of each keyword (eventually the index of 'go'). // If no match is found 'p' will be NULL and cause a segmentation fault. // which indicates that the input does not allow the chefs to go. // The sequence is stored in reverse as it saves more space. char*s="go\0.one\0two\0three",*p=*++v; for(c=4;c--;) // The haystack is 'p' instead of v[1] since this discards any characters // before the last match which prevent false positives like: // "two...three..one..go..." // // Adds the needle's offset from 'p' to 'p', the casting tricks the // compiler to get around the issue of having the declare the prototype // of strcasestr(). p+=strcasestr(p,s+4*c)-(int)p; // 'p' has to be incremented as it contains the index of 'g' of 'go'. exit(++p-*v); } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 51 bytes ``` s=>(z=/three.*two.*one.*?go/gi).test(s)*z.lastIndex ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lVBBTsMwEBRXXrFUHJLIuFG5IFWhZ-58ICVrJ5Llrey10vYrXCIEj4LXsImlHhAcOKy92pnZGe3ru6cOpzfTfCQ2dw-f97F5LM7NmvuAqCseSVfkpdtZWtuh1IyRi1hWZ-3ayE--w2OWfl1tXshHcqgd2cIUq-ceA0IrtWwDMnCiBPN0C61hDAIMEQIl30k7s8fBOdiLYqQt7BMDeXeS56JeCJYg9nQAQwHSAZjgdlOruq71qiyv_44x0r9CiG0OYUlBK_DPHJcQ-Vy_mgugZmc1q9WyKteN0PPppin_3w) This outputs 0 for no match, or the index. The `RegExp.lastIndex` property (which only works for RegExes that have the `g` flag enabled) gives the index of the end of the previous match. [Answer] # Swift, 156 bytes Short version: ``` func c(_ s:String)->Int{let s=s.lowercased();return s.ranges(of: /three.*two.*one.*go/).first.map({s.distance(from:s.startIndex,to:$0.upperBound)-1}) ?? 0} ``` Verbose version: ``` func c2_(_ s: String) -> Int { let s = s.lowercased() return s.ranges(of: /three.*two.*one.*go/).first.map({ s.distance(from: s.startIndex, to: $0.upperBound) - 1 }) ?? 0 } ``` [Answer] # [Gema](http://gema.sourceforge.net/), 38 characters ``` *\Cthree*two*one*g\Po*=@column@end *=0 ``` Sample run: ``` bash-5.2$ gema '*\Cthree*two*one*g\Po*=@column@end;*=0' <<< 'There are three of you here; after this round there will be two; but only one of you will go shop for up to $20,000.' 91 ``` [Try it online!](https://tio.run/##PYuxCoMwGIT3PsUNnUIpwVUEoS/QoaNLrH9UiDmJCeLTp9Ghwx3H3XejLCZn1b3iFERU3KnoRY3dm6ppv3Rp8a344aYanfNnkiAwRRcOWhxMONsaxkYJZZg3BCY/lHjS@@wc@vLYWaNPEfTuKPZ/X8BIbBNXWAakFZG4V/qhtX7@AA "Gema – Try It Online") / [Try all ~~test~~ collected cases online!](https://tio.run/##nVPbbtNAEH2uv2IaQp1ESeumQqKtjIoqVHhARahvaYQ29viirnei3TXBpJX4Gj6MHwkzdhuoUB@oZK3HO2f2nDOzXihXbFJMtLIIk7fg0fkviXIYD4KdWXhVIO9LzhcWESiDhmqQ3VNQmUfLidKBpdqkHAp6VWoNC65Y0Sksag9kdMPLtroF5ASuoCVkZKFegifoT6NxFEX74Tw@PuzImXIs54ylfMw1u5w8fH2vDJICMweVauS0MhN@cN6WJoeEjFelcZ3uMdNoTStMYdHAd7QETFsRqyURzScpqxK24x5DW@5n1raSn1mb0z58VD4pxAv3VyYyYTtoXOnLryhNmk6Ptl26WtGlwQuS9kz/2X36Y4vvxst220FxO9tH0q@26UlaViKAjNKQWExLxluev0HnZLhL1yQF19eWyqqqDWnKS@edOFig726LMrJ4wZMny9XEl68x@QNaSKNIWN@j0r5ouhk6qpBZauG8AcM0OQn2qNV/TinCBekM9oBjadt5obRGk6OgomAYBEu@Gj6D8BZeTpjCQRc8ek95vTYhhB/Msvb8/oyu1hK8@7ZEHlXK4eVNGARyc0sB8Qq9/np3@@/MzuZ3vVNIKdixbXXc6w8AuTcwEWhb1WO2A1r6gxwrdeBs0gYQbkbX563hETsdsc1Rfv2JRvFZQrquzBmaNBjF0SaEYS8Idv7Hk6gYDKC/ftEquIM3MXANDIewt9fpYx9t7uTk@Pju14@frPL2IXMve9jjuPMl0fqP7Q7B3lum2ewvXBw/BZ3Pt@TSV3GVsuvNbw "Bash – Try It Online") [Answer] # [TypeScript](https://www.typescriptlang.org/)’s type system, ~~213~~ 203 bytes ``` //@ts-ignore type F<S,A=0,Z=any,B=Lowercase<S>>=B extends`${Z}three${Z}two${Z}one${Z}go${infer D}`?F<B extends`${infer B}go${D}`?B:0,[1]>:A extends 0?0:S extends`${Z}${infer R}`?F<R,[...A,1]>:A["length"] ``` [Try it at the TS playground](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAMQB4BlAGgEEBeABkoC1aBDRHSgIVoBlkA7ulQBjVpHQUAfFNpdC6AB7h0iACaQABgBIA3kwC+4ABYZ0ew+AHILB5InP6D8G7tiIAZsMIARA5oB+MnklFXUtPXcvVEIuZ1c-QK4ALkYAbQBGAF0pZOoFZVUNQnoA+mTyArCNHSdIz28AJX8g0kbKNIA6bupKbNzqNIAiABtVeBMhrMxsfCIAFXRIcAzCWhJSIfnTdCJwWABbJcJ5gQB5QgBxZEID9wBXSEIrG+QAOSJ0AEd71hGn+xEFwuDz3dRHIZSTAgQiwgB6AVmBBOS3AACY1hstsZhERWBhnjsiMgPIQcMh7oQcRgANyEVgeFQxEywJ6oCnqQm4wgCWAjEaEABGe2sdMF93AhHsIxwUocUtJ5MpvP5hBchEgxmQeEIHjQhHuOvAN20aMY9AtnUh0OAsPhiNwyMWywAzJiyNjufi9kSFWSKVTcWKJVyNVqBIRWYQxIgROgxmorVCYfbMEA) ]
[Question] [ **This question already has answers here**: [Is string X a subsequence of string Y?](/questions/5529/is-string-x-a-subsequence-of-string-y) (68 answers) Closed 4 years ago. The Typical Way to Make an Acronym Out of a Phrase Is to Take the First Letter of Each Word: `TTWMAOPITFLEW`. howeveR, sometimEs, you can make an acronym of random leTters In a seNtence such As like this: `RETINA`. The only condition is that the letters have to be in the correct order. For instance: * `LORD` can be acronymised from `Hello World`: `heLlO woRlD` * `LEOD` cannot be acronymised from `Hello World`, as no `l`s are before `e` Your task is to take two strings as input as to determine if one can be acronymised into the other. The first input, the phrase, will only contain letters (`A-Z` or `a-z`) and spaces, and the second input, the acronym, will only contain letters (`A-Z` or `a-z`). The acronym will always be shorter, or of equal size, to the phrase, and both the acronym and the phrase will be, at minimum, 1 letter long. You may choose which case (upper or lower) you want the inputs to be. You may choose any two values to represent `true` and `false`, as long as those values are consistent. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins ## Examples ``` HELLO WORLD, LORD -> true CODE GOLF AND CODING CHALLENGES, DANGLE -> true SANDBOX FOR PROPOSED CHALLENGES, CODE -> false HELLO WORLD, LLLD -> true HELLO WORLD, LLDL -> false NEW YORK POLICE DEPARTMENT, NOODLE -> false MASSACHUSETTS INSTITUTE OF TECHNOLOGY, MUTTON -> true BOB, BOB -> true PRESIDENT OF THE UNITED STATES, I -> true ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 1 byte ``` ⊇ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FX@///Ss7@Lq4K7v4@bgqOfi4KQJ6nn7uCs4ejj4@rn7trsNJ/JRdHP3cfVyUA "Brachylog – Try It Online") [Answer] # Java 8, ~~46~~ ~~39~~ ~~38~~ 35 bytes ``` a->b->a.matches(b.replace("",".*")) ``` -7 bytes thanks to *@tsh*. -1 byte thanks to *@NahuelFouilleul*. [Try it online.](https://tio.run/##jVLNbqMwEL7nKUY@wSbxA7S7kQh2AK3jQdhRt6p6MIRsyRJAxalUrfrsqZMg7dJD1Ys99vcznzXemxcz32//nIra9D2sTdX8nQD01tiqgL1D6dFWNd0dm8JWbUNXQ/Fd2eeq@T37EmfZtnVpmsUCdvDjZOaLfL4w9GBs8VT2Xk6fy642RekRMiP0G/H90@3EpeiOee1SDGFe2moLBxfQu9o@PILxz2EBbNlbj8RcCIQ7zARzPgIzRvzb//AQGYcIxQoCycCdEhlBGAdCcBlx5TQskJHgY5Vy5CX@ghVmkGaYouJsrDr7jjUfkgjBPseZGOOS38E9Zj8hRZGEHBhPg0yvudSOLhHZx5DrQKkgjDeKa60gkUoneqM54Ao0D2OJAqN7p11vtEY51i5x6ZDzOrpOM64S5lpeTGIOG5lo93SlA315dnLlv03@/ZfLiC7y64jAzIYiHyalXntbHmh7tLRzgK0bz0wJmGYLZJpPyY3bdtR0Xf3qGX8ocn/o9HZ6Bw) **Explanation:** ``` a->b-> // Method with two String parameters and boolean return-type a.matches( // Check if the first input matches the regex: b // The second input, .replace("",".*")) // where every character is surrounded with ".*" ``` *For example:* ``` a="HELLO WORLD" b="LORD" ``` Will do the check: ``` "HELLO WORLD".matches("^.*L.*O.*R.*D.*$") ``` (The `^...$` will add the `String#matches` builtin implicitly, since it will always try to match the entire String.) [Answer] # [C (gcc)](https://gcc.gnu.org/), 47 bytes ``` f(a,b)char*a,*b;{a=!*b||*a&&f(a+1,b+(*a==*b));} ``` [Try it online!](https://tio.run/##bZFNU4MwEIbv/IqVmXb46th6RZyhJAXGNMuQMLWDHABFOdg6bU@2/e2Ygh7qeEmyb553N7upJ2913XWNUTqVWb@XO6t0rMo9lt6NVZ1OVjkeqzt75lS2YZWeZ1Wm6Z67j7LdGOZR6x2HvMjvCu@oHfWIMoawwpQR3dEZpkQ/O0oPkFAIkS3A5wRUFPMQgshnjPKQCsUSn4eMDrRQ0ByfYIEpJCkmKCi5pi/5BvZPRcbI/zphg87pCtaYPkKCLA4oEJr4qVxSLhXGEcnvI5a@EH4QZYJKKSDmQsYykxRwAZIGEUeG4Vp5lpmUyAfPHOdKuax9mKRUxESl7k0RhYzHUrUipC/7NmL9rJ1drdnujHZzgNabuu39vv163TbGwbz9OfVDNt3WttXEP3eKbAx9tHdGe5g8wOjleaM7h7wt8mkx7LPCUf5rRX2bpop13w "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` æIå ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8DLPw0v///dw9fHxVwj3D/Jx4fLxD3IBAA "05AB1E – Try It Online") ``` æ # power set of the first input I # second input å # does a contain b? # implicit output ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` lambda s,a:re.search('.*'.join(a),s)>0 import re ``` [Try it online!](https://tio.run/##dZBNS8NAEIbv/RUDHtJKDeJRsLDNTpLF6U7YnVALXqKmtNIvknjw18dEUUptT8uw7/POwxw@m9V@d9cuH57bTbF9eSugHhf3VRnWZVG9roZBeB2E7/v1bliMxvVocjtYbw/7qoGqbA/VetfAchikSMQwZ0c6GENA7HQwgiu4mUBTfZSDv2DEGiFhikFZDd1kbAJRqojQJuh7WCubEJ7HfUdN@QlidpA5ztijPsH7Db/wstjUR/SpJdEFy39BTRcqLc5hwe4RMiYTIWjMlJMZWulBy6zpks1Mea@iNPco4sFYL0ZyQeAYBKPUMnGy6FtmuQjb86ZTnvaR/jn7nzn0Rnc637UpQm6NdDfzouTnXuYYbL8A "Python 2 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes Full program. Prompts for phrase, then acronym. ``` 0∊⊃(⍳⍨↓⊢)/⍞,⊂⌽0,⍞ ``` [Try it online!](https://tio.run/##dU@9SsRAEO73KaZUOPFeYbM7SRYnO2F3wnnlgWBzYFpbBT2CqewtrOytfZl9kbgXuHCFDgzMx/czM7t@f3X3uNs/3E/p8NpP63QY0vB8kcbvNH6ll/c0fF5ep/FjlYan9PazXuX5KJ1grl7VSMSw4UBWEQerToRhi1AxlaC9hYycr8DUmgh9hVFZ7SvCRR6zquBbKDlAG7jliPZcfoxTfy4lsv8QlhbC4wa2HG6gZXIGwWKrgzToRXlme3ZIo2PUpu4iikRwPoqTThC4BEFTeyautqrpRNgvpoKLuU@4DRidzemzrUbovJP8UBQt@Rn3Cw "APL (Dyalog Unicode) – Try It Online") `⍞` prompt for phrase   `"HELLO WORLD"`   `"HELLO WORLD"` `0,` prepend a zero   `[0,'H','E','L','L','O',' ','W','O','R','L','D']`   `[0,'H','E','L','L','O',' ','W','O','R','L','D']` `⌽` reverse   `['D','L','R','O','W',' ','O','L','L','E','H',0]`   `['D','L','R','O','W',' ','O','L','L','E','H',0]` `⊂` enclose (to treat as a whole)   `[['D','L','R','O','W',' ','O','L','L','E','H',0]]`   `[['D','L','R','O','W',' ','O','L','L','E','H',0]]` `⍞,` prepend the prompted-for acronym:   `['L','L','L','D',['D','L','R','O','W',' ','O','L','L','E','H',0]]`   `['L','L','D','L',['D','L','R','O','W',' ','O','L','L','E','H',0]]` `(`…`)/` reduce that list by the following tacit function:   `⍳⍨` the **ɩ**ndex of the first occurrence in the phrase (will return 1 + phrase length if unfound)   `↓⊢` drop that many characters from the phrase We then use the shortened phrase to look for the next letter. If at any point a letter is unfound, we'll drop everything, including the final zero. This means that if our acronym is good, we'll still have a zero left.   `[0]`   `[]` `⊃` disclose (because the reduction reduced the number of dimensions from 1 to 0) `0∊` is zero a member thereof? [Answer] # [J](http://jsoftware.com/), 21 bytes ``` <@[e.]<@#~2#:@i.@^#@] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bRyiU/VibRyU64yUrRwy9RzilB1i/2tycaUmZ@QrGCrYKqj7@Ae5qCukKah7uPr4@CuE@wf5uKgjy/v44JI3gMi7@ODT7@TvBJYG0QhhDR0rdU91TZCEo5Ozp4urs/p/AA "J – Try It Online") Note: Some of the longer test cases omitted because they this solution is O(2^n). They would pass with infinite memory. Explanation: We create all 2 ^ (length of haystack) possible substrings, and check if the needle is an element of that list. [Answer] # [Python 3](https://www.python.org/), ~~89~~ 68 bytes -21 bytes thanks to AdmBorkBork ``` def a(b,c): for i in b: if i==c[:1]: c=c[1:] return len(c)==0 ``` Takes input as a(string, acronym). [Try it online!](https://tio.run/##dZBBa4NAEIXP5lcM9qKQQkNvAQsbd6JLNzuyu5KGkkNilQrBBGsO/fXWbaC0aTzNPHjfm8ecPrv3Y/PY929lBbtgPy3C@cSrji3UUDewH4RXV1BHUfE6n22d9Iphn823E68tu3PbwKFsgiKMoof@1NZNF@wCP0UpCdakJfen4EvS3A9DuIP7J@jaczn5ccbEERKSS2CKw6CESiBOmZSoEjSO5kwlEkd4M2ALeoElacg0ZWSQX/HuxA9d7Q4fv/DrolKOFf3n5PLivJGqcA0b0s@QkRQxAseMabtCZR2qiLgcbbRixrA4zQ1aa0AoY4XNLQItwWKcKpKUbFzMKreW1EjbBS2cx43bhkyjEXxo9B2cIuRK2OF1xjJ7eZv4Q/Zf "Python 3 – Try It Online") [Answer] # JavaScript, 26 bytes Port of [Kevin's Java solution](https://codegolf.stackexchange.com/a/190420/58974) so please `+1` him, too. Takes the string as a string via parameter `s` and the acronym as a character array via parameter `a`. Outputs `false` for `true` and `true` for `false`. ``` s=>a=>!s.match(a.join`.*`) ``` [Try it online!](https://tio.run/##bVHRTsJAEHzWr1j6YitYvqAkpbe0jcdt07sGSSXhgkUh2BIO/X28QlRQ7uE2m52Zneys9ac2i91qu3@om5fqsAwOJhjoYNAx/rveL95c7a@bVT337@feYdHUptlU/qZ5dctbKJ0EOSeYUM6Z03M45cyZ9W7s6/dhv/uoWkxEDCEmPoJQMLBdKmKIkpBzFDFKy2OhiDkemWc8aeFDeoIR5ZDllJFEdslrlb9ZS70x1RVLnF@x9BfD@C/mR0jgBKaUP0JGPI0QGGZhrsYolOUIIsb/Lx@HUoZRUkhUSkIqpEpVofBOAo1AYZQI4hRPrcC4UIpEK3Dma0hDO2r/k50L01mOMmV2/VErQShEquxJpArV8RzpxQVnNr@t65amp2deMDBdB7rgdLWtga2dpWs8t/R93469U8bPtc34Cw) (Footer reverses output for easier verification) [Answer] # [Gaia](https://github.com/splcurran/Gaia), 5 bytes ``` $z@$Ė ``` [Try it online!](https://tio.run/##S0/MTPz/X6XKQeXItP//PVx9fPwVwv2DfFy4fHxcfAA "Gaia – Try It Online") Powerset approach. [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` à øV ``` [Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4CD4Vg&input=IkhFTExPIFdPUkxEIgoiTE9SRCI) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` eŒP} ``` [Try it online!](https://tio.run/##y0rNyan8/z/16KSA2v////v4uPj893D18fFXCPcP8nEBAA "Jelly – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 35 bytes ``` [[ $1 = *${~${(j:*:)${(s::)2}}}* ]] ``` Outputs via exit code. [Try it online!](https://tio.run/##VYzBCoJAAETv@xVzWFgVPNTRiDBdLRBX9BKEB2kXNBYXNDIS@3XTbp2GN2@Yd1/PQ91ohU5VErpp1Q7SEPWsNHr1gOuCri2xfvSar1fQDfZw6Piho3X3HM9esvc8eztNk4OynG2ibrUBPRBpWjWzWmltMJhOSwZtOklYIEKOWCQR/DTEQuc0RnDyk4SnMS8YQj@NE05YsfijuCASObJcZKLg4d9wfSJf "Zsh – Try It Online") ``` [[ $1 = *${~${(j:*:)${(s::)2}}}* ]] ${ 2} # second parameter ${(s::) } # split into characters ${(j:*:) } # join with * ${~ } # enable globbing *${~${(j:*:)${(s::)2}}}* # *A*C*R*O*N*Y*M* [[ $1 = ]] # does it match the first parameter? ``` [Answer] # [C#](https://visualstudio.microsoft.com/), 152 bytes ``` public class P{public static void Main(string[]a){int q=0;int e=a[1].Length;foreach(char c in a[0])if(q!=e&&c==a[1][q])q++;System.Console.Write(q==e);}} ``` [Try Online](https://dotnetfiddle.net/AO0np4) [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` f=lambda s,t:(t[:1]in{*s}and f(s[s.find(t[0]):],t[1:]))**len(t) ``` [Try it online!](https://tio.run/##ldFBS8MwFAfwu5/iwQ5txxCHt4KHrHlrg1leaVLmGD1UtuJg1rHGg4ifvWYTdEZ0mEMgPPJ7/5fsXuzDU3vd983Ntn68X9XQjWwc2mU8rjbt67B7q9sVNGG37C6bTbtylasqiquRXY7jKoqGw@26DW3U7/ab1oZNGGQoJcGcCsmDUSCp4EEUwV9rAHb/vL74FBLiCCnJKTDFwZ2ESiHJmJSoUtRO5UylEr9cX9Du4oTuYEoF5AXlpJF/Fw49TnMNoKm33QnhjSHlv8fwBS7PC14IhXNYUHELOUmRIHDMWWFmqIwTFRGX6Jk/iBnTmiVZqdEYDUJpI0xpEGgKBpNMkaR04bRZaQypg@bPMaGJqx/2M/F/fYm8QC24S33smiGUShj3I9owc/wN4dMfQv8O "Python 3 – Try It Online") Recursive function. Will check for each letter in the acronym `t`, whether it is found in the string `s`. If it is, the function is called recursively with the part of the string *after* the current test character `t[0]` as the new input string `s`. When the test character is *not* found, the final evaluation result (which at that point is always `0`) is raised to the power of the length of the remaining test string `t`. Since `0**0 == 1` and `0**x == 0` for any `x > 0`, the function returns `1` when all test characters have been found in order and `0` otherwise. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 88 bytes ``` T =INPUT S T LEN(1) . X REM . T :F(M) M =M ARB X :(S) M INPUT M :F(END) OUTPUT =1 END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/nzNEwdbTLyA0hCsYyPRx9dMw1FTQU4hQCHL1BdIhnFZuGr6aXJy@Cra@Co5BTgoRnFYawZpcvpxgXQq@IAWufi5AJf6hISARW0MuIP//fx//IBcuD1cfH3@FcP8gHxcA "SNOBOL4 (CSNOBOL4) – Try It Online") Prints 1 for Acronymizable, and does nothing for not. ``` T =INPUT ;* read in the Target S T LEN(1) . X REM . T :F(M) ;* extract the first letter of T ;* and when T is empty, goto M M =M ARB X :(S) ;* create a PATTERN: M, ARBitrary match, X ;* then goto S M INPUT M :F(END) ;* if M doesn't match the input, end OUTPUT =1 ;* else print 1 END ``` [Answer] # JavaScript, 50 bytes ``` h=>n=>[...n].reduce((a,l)=>a+1?h.indexOf(l,a):a,0) ``` [Try it online!](https://tio.run/##fY9Bb4JAEIXP5VdMOUGKpF5tsEF2BdJ1h7BrrGl6ILJWK0UjtKlp@tvpUqOYHnqazLz3zZt5zT6yarFf7@petVvnav@2LTfq0BSqhlpVNXhgrbJDVWeLjQOlUnmhbPCG8GVcLbZltS2UW2xfLjymY56MuhnoZnlWbeu04dqDXt82vg2jTVrqmGblDUtv@OS6bvns7lX@vlCWlTmF7Q2zm/79yl2XufrEpVU4mT3InFu7aS@0zIgyhjDDlBGdZjJMiWnfGUcxQEIhRDYGnxPQXcxDCCKfMcpDKlqA@DxktEOEdo7wEcaYQpJigoKSP0i7tQP@HsAY@UckrBM5ncEc0wdIkMUBBUITP5UTymXr5Yjk8rCJL4QfRFNBpRQQcyFjOZUUcAySBhFHhuG8BSdTKZF34AhH7bgt51mSUhETnfSLRxSmPJb6USF9eXwy1ubmBw "JavaScript (SpiderMonkey) – Try It Online") take input as `f(haystack)(needle)` ``` h=>n=> // inputs [...n] // transform n from string to array of char .reduce((a,l)=> ,0) // for each letter change the value of a, (a starting at 0) a+1?h.indexOf(l,a):a // if a === -1 keep it else replace it by the position of the letter l in the haystack h starting from position of previous letter ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 4 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` äΦv> ``` [Run and debug it](https://staxlang.xyz/#p=84e8763e&i=%22LORD%22+%22HELLO+WORLD%22&a=1) [Answer] # Emacs Lisp, 52 bytes ``` (lambda(a b)(string-match(mapconcat'string b".*")a)) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` }Ey ``` [Try it online!](https://tio.run/##K6gsyfj/v9a18v9/JQ9XHx9/hXD/IB8XJS4lH/8gFyUA "Pyth – Try It Online") [Answer] # Haskell, 40 bytes ``` r@(a:c)#(b:d)|a==b=c#d|1>0=r#d x#y=x=="" ``` [Try it online!](https://tio.run/##dZFRa4MwFIWf56@4xD0o7WB7LURmTaqymCsm0pVtjGgLK2u7oh100P/uYit7KIw8nOSe7@Tmkg/Tfq42m65rHj0zqX3XqyZL/2QorWjtLk8PwT1t3KVzdH/okVJCutq0qxYovHgk4UIgzLEQjIyBCCwY8cfOjUciZBxiFDMIJQN7SmUMURIKwWXMVU@zUMaCD7yy2BSfYYYF5AXmqDi74vsrB/q6rxDsP4eJwZF8DgssniBHkUYcGM/DQmdc6h6UiOzvMVmoVBglpeJaK0il0qkuNQecgeZRIlFgvOhTWak1yiE1xWlf6@VSyAuuUmYbnIMJh1Km2o6ldKgvI6XEf3OcrVnv6Nbss3fwXj0zrny4C8Dbfx/UoYFbMDAaAbHLSnXZW5/4EAQUvPpr1x4stW/Wu14rcMH4Ppy/qfsF "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` def f(s,w): for c in s: if c==w[0]: w.pop(0) if len(w)==0:return 1 return 0 ``` [Try it online!](https://tio.run/##ZVFNi4MwED3rr5hbFWSxu7eCB2viB5tmxKR0S/EgXWWFYkUtsv3zbtIWytZc5g1v3pshr/0dfs7NxzR9lxVUVu@M9so0qnMHR6gb6FVj1BUcPW88uLnujPGtPbeWa2usqFPZWKPtee6qK4dL18DSNB7Ina7gwcEE9Q6LmDKGsMOMkYUDC4aZrrK7lLnzGAmQUIiQheBzAqpLeARB7DNGeUSFlhGfR4y@CoWaX@MXhJhBmmGKgpIXofZWNSxO/VP3ehNjs5tmI4TNbDjdwR6zT0iRJQEFQlM/kxvKpZZwRMLmuze@EH4QbwWVUkDChUzkVlLAECQNYo4Mo73Wb7ZSIn@9a41rTd7LPybNqEiIWn6ziilseSLVfwjpy/tfJE9Jbpo67UKnfV3dHNqubgarsk51P1iFit124IGXua2i1nRxeFd4@gM "Python 3 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~20~~ 19 bytes ``` +`(.)(.*¶)\1? $2 ¶$ ``` [Try it online!](https://tio.run/##XY4xbsMwDEV3nYKDWziNEKC9QCGbtC2UJg2JRhogQzpkyNKhKNCb5QC5mCt3S5cP8PPj/f91/r58fiwP9en4s63c7Vo9LttTvdvUu6fbdXN8fnXVy2ovy0DMCntNjB5YE7pWkaBX7iAIQrmi9NAOgZmkp@wBg/RMLpd3o@/QaYIp6aSZ8C63gtw9nxn/O8hOaA8HTW8wKceWAGkKyUYS8yCqWMrGkHNohzmTWYYo2aLNRqAdGLWDKGt/8DDOZiqu0cZDETclyhEL6C84EMwSrczMFmydGH8B "Retina 0.8.2 – Try It Online") Takes the phrase and acronym on separate lines, but the link includes a header that formats the test suite appropriately. Explanation: ``` +` ``` Process all of the letters of the phrase. ``` (.)(.*¶)\1? $2 ``` For each letter of the phrase delete the next letter of the acronym if it is the same. ``` ¶$ ``` Check that all of the letters of the acronym were deleted. ]
[Question] [ Break two numbers up into their powers of 2, if they share any, return a falsey value. Otherwise, return a truthy value. If one input is `0`, the answer will always be truthy. if one input is `255`, the answer will be falsey if the other is not `0`. # Example Given 5 and 3 ``` 5 = 2⁰ + 2² 3 = 2⁰ + 2¹ ``` Both share 2⁰, return falsey. Given 8 and 17 ``` 8 = 2³ 17 = 2⁰ + 2⁴ ``` Neither share any powers, return truthy. # I/O Input and output can be through [any standard means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) Input will always be two integers in the range `0 <= n <= 255` Output should be one [truthy or falsey value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) # Test Cases ``` Truthy: 1, 2 3, 4 2, 4 8, 17 248, 7 Falsey: 1, 3 6, 4 8, 8 ``` [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins! [Answer] # [Actually](https://github.com/Mego/Seriously), 2 bytes ``` &Y ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/18t8v9/Cy5DcwA "Actually – Try It Online") Explanation: ``` &Y & bitwise AND Y boolean negation ``` [Answer] # x86 Machine Code, 5 bytes ``` 20 C8 0F 95 C0 ``` takes inputs in `al` and `cl`, and returns output in `al`, and is equivalent to: ``` and al, cl setnz al ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` &¬ ``` [Try it online!](https://tio.run/##y0rNyan8/1/t0Jr///9b/Dc0BwA "Jelly – Try It Online") Explanation: ``` &¬ & bitwise AND ¬ logical negation ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 12 bytes ``` ->a,b{a&b<1} ``` [Try it online!](https://tio.run/##KypNqvz/X9cuUSepOlEtycaw9n@JLTKXq0ChJNpCx9A89j8A "Ruby – Try It Online") [Answer] # Mathematica, 12 bytes ``` BitAnd@##<1& ``` Pure function taking two positive integers as argument and returning `True` or `False`. [Answer] # [Python](https://docs.python.org/3/), 18 bytes ``` lambda a,b:not a&b ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUSFRJ8kqL79EIVEt6X@BLaYgV0FRZl6JRoGGhY6huabmfwA "Python 3 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 10 bytes ``` !(($1&$2)) ``` Input is via command-line arguments. Output is via exit code, so **0** is truthy and **1** if falsy. [Try it online!](https://tio.run/##S0oszvj/X1FDQ8VQTcVIU/P///@G/40B "Bash – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` &_ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fLf7/fwsuQ3MA "05AB1E – Try It Online") [Answer] # R, 28 bytes ``` f=function(a,b)!bitwAnd(a,b) ``` [Answer] # JavaScript (ES6), 12 bytes ``` a=>b=>!(a&b) ``` Takes input in the currying format. ``` let f= a=>b=>!(a&b) console.log(f(1)(2)); console.log(f(3)(4)); console.log(f(2)(4)); console.log(f(8)(17)); console.log(f(248)(7)); console.log(f(1)(3)); console.log(f(6)(4)); console.log(f(8)(8)); ``` [Answer] ## CJam, ~~23~~ 4 bytes ``` q~&! ``` It turns out my previous solution contained an implementation of what was essentially just bitwise AND (which is silly because it used `&` anyway). [Answer] # [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` {&!} ``` [Try it online!](https://tio.run/##S85KzP1flFmU@b9aTbH2f91/IxMLBXMA "CJam – Try It Online") [Answer] # R, 23 bytes if allowed - this version can get multiple inputs as a1,a2,a3..... b1,b2,b3..... ``` !bitwAnd(scan(),scan()) ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 3 bytes ``` ~&! ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v05N8f9/IxMLBXMA "GolfScript – Try It Online") [Answer] ## Pyke, 3 bytes ``` .&! ``` [Try it here!](http://pyke.catbus.co.uk/?code=.%26%21&input=3%0A1&warnings=0) ``` .& - bitwise_and(input_1, input_2) ! - not ^ ``` [Answer] # [Chip](https://github.com/Phlarx/chip), 80 bytes ``` AZ BZ CZ DZ EZ FZ GZ HZ ,[',[',[',[',[',[',[',['*Z~S `--)--)--)--)--)--)--)~aef ``` [Try it online!](https://tio.run/##S87ILPj/X8ExSsEpSsE5SsElSsE1SsEtSsE9SsEjiksnWh0r0oqqC@ZK0NXVxER1ialp//87qgAA "Chip – Try It Online") Takes input as two consecutive bytes. (In the TIO, the characters 'A' and '$' are used, corresponding to values 65 and 36.) This solution has eight chunks, one per bit, plus an extra chunk at the end. Looking at these chunks: `A` is bit `0x01` of the input. (The letters `A` though `H` correspond to a bit each.) `Z` holds on to a value for the next cycle while producing the previous value. Hence, `A` and `Z` are the current and previous values of bit `0x01`. `[` is an AND-gate; it simply ANDs its two inputs together. So the full row of such gates is performing a bitwise AND of the two bytes. Finally, `)` is an OR-gate. All eight AND results are OR'd together, giving us a True is there is a match, and a False otherwise. We want the inverse of that, so use a NOT-gate (`~`) before passing it to the output. We output via `a`, `e`, and `f`. The `a`, which corresponds to bit `0x01` of the output, receives the result of the above computation. The other two bits `e` and `f` are unconditionally on, together forming `0x30`. Therefore, the output is either `0x30` or `0x31`, which are the codes for ASCII characters '0' and '1'. The extra stuff is housekeeping, it prevents output for the first cycle (there is no previous value at this point, so there is no reason to do a comparison). --- ### Alternate solution, also 80 bytes ``` A~.B~.C~.D~.E~.F~.G~.H~. Z~<Z~<Z~<Z~<Z~<Z~<Z~<Z~<*Z~S a[--[--[--[--[--[--[--'ef ``` This is very similar in style, but uses a different algorithm. Where above we AND each pair of bits, and use OR to reduce the result to a single value, here we OR the negation of each pair of bits, then use AND to reduce. One thing to note: we use an implicit OR here, instead of a proper gate as above. We could have used implicit OR'ing above as well, but there is no byte-savings there. [Answer] # Java 13 bytes ``` a->b->(a&b)<1 ``` [Answer] # [Rust](https://www.rust-lang.org), 10 bytes ``` |a,b|a&b<1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMFNo7Q8hdzEzDwNTYVqLs6c1BKFRAVbBSNrCDsJyDYEsguKMvNKFDWUqmuVdDSWlpak6VqsqknUSapJVEuyMYQIrOHU1EjUUUjS1LTmqoUILVgAoQE) [Answer] # [Desmos](https://desmos.com/calculator), ~~87~~ ~~85~~ ~~87~~ 80 bytes +2 bytes to correct an error pointed out by [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) -7 bytes thanks to [@aiden-chow](https://codegolf.stackexchange.com/users/96039/aiden-chow) ``` D(n)=mod(floor(n/2^{[0...floor(log_2(n+0^n))]}),2) f(a,b)=\{\total(D(a)D(b))=0\} ``` [Try It On Desmos!](https://www.desmos.com/calculator/mf12qkvyda) **f** returns `1` when they are "truthy" and otherwise `undefined`. [Answer] # MATL, 3 bytes ``` Z&~ ``` Try it at [**MATL Online**](https://matl.io/?code=Z%26%7E&inputs=8%0A17&version=20.0.0). **Explanation** ``` % Implicitly grab both inputs Z& % Bit-wise AND ~ % Negate the result and implicitly display ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 18 bytes ``` x->y->!bitand(x,y) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L9C165S104xKbMkMS9Fo0KnUvN/QVFmXolGmoahpoaRpiYXjGusqWGCxDVC5VpoahiaI0ubAEWQBYCmGSNxzTC0W2hq/gcA "Pari/GP – Try It Online") [Answer] # Javascript, 28 ``` (a,b)=>!(256&(-~a|-~b)||a&b) ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 12 bytes ``` ?(: and :)=0 ``` This returns `-1` for truthy inputs, and `0`otherwise. "Bitwise" is something QBasic isn't very good at, and I haven't built any of this stuff into QBIC either. [Answer] # [D](https://dlang.org/), 13 bytes ``` (x,y)=>!(x&y) ``` Here, `(arg1,...)=>result` is [the D lambda syntax](https://stackoverflow.com/q/8857965/1488799), and the `!` and `&` are common notations for boolean negation and bitwise AND. You can find the whole program coupled with the tests [at tio.run](https://tio.run/##HY1rCoMwEIT/7ymmQiULUjBKFSS9SyRKAz6KplUpnj1NOuzAMgzfGK8Hq1f07wnKiz07WD0uYk8P9g19ZmswajtBMH0JsONrXhxWZ27Bdm5iNjnoDG38t6cdOoil06aHSHBdwyUZ0lBIW4ZSkBx6kRW0LdZ1Q6DHeREhzBFz0kk@h6QCJcngGnlFsqxREeUo6P7PavoB "D – Try It Online"). [Answer] # [Lua](https://www.lua.org), 19 bytes ``` a,b=...print(a&b<1) ``` [Try it online!](https://tio.run/##yylN/P8/USfJVk9Pr6AoM69EI1EtycZQ8////6b/jQE "Lua – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 18 bytes Uses exit-code 0 as truthy. ``` f(a,b){exit(a&b);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1EnSbM6tSKzRCNRLUnTuvZ/bmJmnoZmdZqGhY6hOUgAAA "C (gcc) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` !.&hQe ``` [Test it online!](https://pyth.herokuapp.com/?code=%21.%26hQe&input=248%2C7&debug=0) **Explanations** ``` !.&hQe hQ Get first input number e Get second (implicit) input number .& Bitwise and ! Negate ``` [Answer] # PHP, 25 Bytes print 1 for true and nothing for false ``` <?=!($argv[1]&+$argv[2]); ``` [Try it online!](https://tio.run/##K8go@P/fxt5WUUMlsSi9LNowVk0bwjKK1bT@//@/icF/EwA "PHP – Try It Online") [Answer] # [Wise](https://github.com/Wheatwizard/Wise), 11 bytes ``` &::^~![&&]| ``` Due to a bug this does not currently work on tio, however it does work on the desktop version. Here is a slightly longer version that works for both: ``` &::^~![?~&:]| ``` [Try it online!](https://tio.run/##K88sTv3/X83KKq5OMdq@Ts0qtub///8W/y0A "Wise – Try It Online") # Explanation Most of our code goes into a logical not, in fact only the first byte is required if you want to get the *opposite* answer. ``` & #Bitwise and ::^~![?~&:]| #Logical not ``` [Answer] # Oracle SQL, 34 bytes ``` -- Begin test cases WITH T (x, y, desired) AS ( SELECT 1, 2, 1 FROM DUAL UNION ALL SELECT 3, 4, 1 FROM DUAL UNION ALL SELECT 2, 4, 1 FROM DUAL UNION ALL SELECT 8, 17, 1 FROM DUAL UNION ALL SELECT 248, 7, 1 FROM DUAL UNION ALL SELECT 1, 3, 0 FROM DUAL UNION ALL SELECT 6, 4, 0 FROM DUAL UNION ALL SELECT 8, 8, 0 FROM DUAL) -- End test cases SELECT T.*, -SIGN(BITAND(x, y)) + 1 result FROM T / ``` [![enter image description here](https://i.stack.imgur.com/fsdz8.png)](https://i.stack.imgur.com/fsdz8.png) ]
[Question] [ Let's define *f(n)* as the maximal number of regions obtained by joining n points around a circle by straight lines. For example, two points would split the circle into two pieces, three into four, like this: [![enter image description here](https://i.stack.imgur.com/Mqkp6.jpg)](https://i.stack.imgur.com/Mqkp6.jpg) Make sure when you are drawing the lines, you don't have an intersection of more than two lines. ## Your task Given a number *n*, print *f(n)*. Test cases: ``` n | f(n) ---+----- 1 | 1 2 | 2 3 | 4 4 | 8 5 | 16 6 | 31 7 | 57 8 | 99 9 | 163 ``` You can see more [here](http://oeis.org/A000127/list). Using built-in sequence generators is not allowed. Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the smallest number of bytes wins. If you guys want the formula, here it is: > > [![](https://i.stack.imgur.com/l9HFx.png)](https://i.stack.imgur.com/l9HFx.png) > > > [Answer] # Mathematica, 23 bytes ``` Tr@Binomial[#,{0,2,4}]& ``` Uses the formula in the question. [Answer] ## JavaScript (ES6), 29 bytes ``` n=>(((n-6)*n+23)*n/6-3)*n/4+1 ``` Uses a formula given in OEIS. [Answer] # Jelly, 6 bytes ``` 5Ḷc@’S ``` [Try it online!](http://jelly.tryitonline.net/#code=NeG4tmNA4oCZUw&input=&args=OA) | [Verify test cases](http://jelly.tryitonline.net/#code=NeG4tmNA4oCZUwrFvMOH4oKsRw&input=&args=MSwyLDMsNCw1LDYsNyw4LDk) ### Explanation Uses the OEIS formula `((n-1)C4 + (n-1)C3 + ... + (n-1)C0)`. ``` 5Ḷc@’S Main link. Args: n 5 Yield 5. Ḷ Lowered range: yield [0,1,2,3,4]. ’ Yield n-1. @ Swap operands of the preceding dyad, 'c'. c Combinations: yield [(n-1)C0, (n-1)C1, (n-1)C2, (n-1)C3, (n-1)C4]. S Sum: return (n-1)C0 + (n-1)C1 + (n-1)C2 + (n-1)C3 + (n-1)C4. ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 7 bytes ``` q5:qXns ``` [Try it online!](http://matl.tryitonline.net/#code=cTU6cVhucw&input=OQ) Or [verify all test cases](http://matl.tryitonline.net/#code=IkBxNTpxWG5z&input=MTo5). ### Explanation Uses the formula (from OEIS): *a*(*n*) = *C*(*n*−1, 4) + C(*n*−1, 3) + ... + C(*n*−1, 0) ``` q % Implicit input. Subtract 1 5:q % Array [0 1 2 3 4] Xn % Binomial coefficient, vectorized s % Sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` c3ḶḤ¤S ``` [Try it online!](http://jelly.tryitonline.net/#code=YzPhuLbhuKTCpFM&input=&args=MTA) or [verify all test cases](http://jelly.tryitonline.net/#code=YzPhuLbhuKTCpFMKxbzDh-KCrEc&input=&args=MSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOQ). ### How it works ``` c3ḶḤ¤S Main link. Argument: n ¤ Combine the three links to the left into a niladic chain. 3 Yield 3. Ḷ Unlength; yield [0, 1, 2]. Ḥ Unhalve; yield [0, 2, 4]. c Combinations; compute [nC0, nC2, nC4]. S Sum; return nC0 + nc2 + nC4. ``` [Answer] # Java 7,~~50~~ 47 bytes ``` int c(int n){return(n*n*(n-6)+23*n-18)*n/24+1;} ``` Uses the formula (from OEIS) [Answer] # [><>](http://esolangs.org/wiki/Fish), ~~27~~ 26+3 = 29 bytes 3 bytes added for the -v flag ``` ::::6-**$f8+*f3+-+*f9+,1+n ``` [Try it online!](http://fish.tryitonline.net/#code=Ojo6OjYtKiokZjgrKmYzKy0rKmY5KywxK247&input=&args=LXYgOQ) A byte saved thanks to *Martin Ender*. [Answer] # R, 25 bytes ``` sum(choose(scan(),0:2*2)) ``` `scan()` takes the input `n` from stdin, which is passed to `choose` along with `0:2*2`. This latter term is `0` to `2` (i.e. `[0, 1, 2]`) multiplied by 2, which is `[0, 2, 4]`. Since `choose` is vectorized, this calculates `n choose 0`, `n choose 2`, `n choose 4`, and returns them in a list. Finally, `sum` returns the sum of these numbers, surprisingly enough. I don't think that this can be golfed further but I would be very happy to be proven wrong! [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 73 bytes ``` (load library) (d D(q((N)(+(/(*(s N 1)N(s N 2)(s N 3))24)(/(*(s N 1)N)2)1 ``` [Try it online!](https://tio.run/##TcmhDoAgFAXQzle8eK8GB1rsZP4BR2FDUaH49c/NZDrh9Hw8JbdTFaXGJCVvd7wfGiTxuIBAjJgwoEkQy/Dp@DGTbuF/6WjVYI@neIHtVVZSXw "tinylisp – Try It Online") From Giuseppe. # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 90 bytes ``` (d C(q((N K)(i K(i N(a(C(s N 1)(s K 1))(C(s N 1)K))0)1 (d D(q((N)(a(a(C N 0)(C N 2))(C N 4 ``` [Try it online!](https://tio.run/##PYs9CoAwGEN3T5Ex2ay4OOtW6B0qLoX67@Lp64eCQ3iQvFxpuXM6t1I4oedOBngxwVsCI3ueCHAyeIP@wku1XGW34b3JZNNtq/Wi0ce2MK9xQk7jEY@74hw3DKC7VnRSeQA "tinylisp – Try It Online") [Answer] # dc, 21 ``` ?ddd6-*23+*6/3-*4/1+p ``` [RPN](https://en.wikipedia.org/wiki/Reverse_Polish_notation)-ised version of [@Neil's answer](https://codegolf.stackexchange.com/a/96890/11259). ### Test output: ``` $ for i in {1..9}; do dc -e "?ddd6-*23+*6/3-*4/1+p" <<< $i; done 1 2 4 8 16 31 57 99 163 $ ``` [Answer] # J, 9 bytes ``` +4&!+2!<: ``` Uses the formula `C(n-1, 2) + C(n, 4) + n = C(n, 0) + C(n, 2) + C(n, 4)`. ## Usage ``` f =: +4&!+2!<: (,.f"0) >: i. 10 1 1 2 2 3 4 4 8 5 16 6 31 7 57 8 99 9 163 10 256 f 20 5036 ``` ## Explanation ``` +4&!+2!<: Input: integer n <: Decrement n 2 The constant 2 ! Binomial coefficient C(n-1, 2) 4&! Binomial coefficient C(n, 4) + Add them + Add that to n and return ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes ``` 2Ý·scO ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MsOdwrdzY08&input=OQ) **Explanation** Straight implementation of the OEIS formula `c(n,4) + c(n,2) + c(n,0)` ``` 2Ý # range: [0,1,2] · # multiply by 2: [0,2,4] s # swap list with input c # combinations O # sum ``` [Answer] # TI-89 Basic, 57 Bytes ``` :Def a(a)=Func :Return nCr(n,0)+nCr(n,2)+nCr(n,4) :End Func ``` Throwback to old times. [Answer] # Excel, 31 bytes ``` =(A1^2*(A1-6)+A1*23-18)*A1/24+1 ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnhDou7yktFXJp2A3?e=IasfW5) Using one of OEIS formulas [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 29 bytes ``` [ "\0"[ nCk ] with map Σ ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoZecn5uUmZcIFM5MLlbITi3KS81RKE4tLE3NS04thqgpzctMzk9JVSgoSi0pqSwoyswrgUgUJealAxVZc3FZKkQb6iTF/o9WUGJiiTFQilbIc85WiFUozyzJAKotUDi3WCH2P4ih9x8A "Factor – Try It Online") You might not be able to see them here, but there are literal 2 and literal 4 control codes embedded in the string. It's a shorter version of `{ 2 4 0 }`. You can see them for sure on TIO. [Answer] # [Actually](http://github.com/Mego/Seriously), 6 bytes ``` D╣5@HΣ ``` [Try it online!](http://actually.tryitonline.net/#code=ROKVozVASM6j&input=Ng) Explanation: ``` D╣5@HΣ D decrement input ╣ push that row of Pascal's triangle 5@H first 5 values Σ sum ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 4 bytes ``` 3ʁdƈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwiM8qBZMaIIiwiIiwiNCJd) Simply an implementation of the formula. [Answer] # Scala, 35 bytes ``` (n:Int)=>(n*n*(n-6)+23*n-18)*n/24+1 ``` Uses the same formula as [numberknot's java answer](https://codegolf.stackexchange.com/a/96903/46901). [Answer] # [Octave](https://www.gnu.org/software/octave/), 27 bytes ``` @(m)binocdf(4,m-1,.5)*2^m/2 ``` This is an anonymous function. [**Try it at Ideone**](http://ideone.com/ClbMv4). ### Explanation This is based on the OEIS formula *a*(*m*) = *C*(*m*−1, 4) + *C*(*m*−1, 3) + ... + C(*m*−1, 0), where *C* are binomial coefficients. The [binomial distribution function](https://en.wikipedia.org/wiki/Binomial_distribution) [![enter image description here](https://i.stack.imgur.com/SfW9X.png)](https://i.stack.imgur.com/SfW9X.png) for *k* = 4, *n* = *m*−1 and *p* = 1/2 gives 2*m*−1*a*(*m*). ]
[Question] [ This is a somewhat [proof-golf](/questions/tagged/proof-golf "show questions tagged 'proof-golf'")-like [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. This is the robbers' thread; [the cops' thread is here](https://codegolf.stackexchange.com/questions/157094/abstract-rewriting-challenge-cops). # Robbers The cops will post abstract rewriting systems. Your task is to crack their submissions by proving that the target string either can or can not be reached from the source string by applying their rewrite rules. (You can do this either by posting a sequence of rewrite rules that starts with the source string and ends with the target, or by proving mathematically that this does, or does not, exist.) See the [cops' thread](https://codegolf.stackexchange.com/questions/157094/abstract-rewriting-challenge-cops) for details and definitions. [Answer] # [jimmy23013](https://codegolf.stackexchange.com/a/157133/68942) Let's work backwards for this one. We first turn the digits into their binary representations. We go from `VW626206555675126212043640270477001760465526277571600601` to `VW++__+_++__+____++_+_++_++_+++_++++_+__+_+_++__+___+_+____+___++++_+______+_+++___+__++++++________++++++____+__++_+_++_+_+_++__+_+++++++_++++__+++_______++______+`. Next, we keep applying the inverse of `DCW:W+` and `DW:W_` until we clear all symbols. Our result is now `VDCDCDDDCDDCDCDDDCDDDDDCDCDDCDDCDCDDCDCDDCDCDCDDCDCDCDCDDCDDDCDDCDDCDCDDDCDDDDCDDCDDDDDCDDDDCDCDCDCDDCDDDDDDDCDDCDCDCDDDDCDDDCDCDCDCDCDCDDDDDDDDDCDCDCDCDCDCDDDDDCDDDCDCDDCDDCDCDDCDDCDDCDCDDDCDDCDCDCDCDCDCDCDDCDCDCDCDDDCDCDCDDDDDDDDCDCDDDDDDDCW`. We now want to make this string match `VD+C+W`; that is, we want to move all of the `D`s to the left of all of the `C`s. This can be done by reversing `DCC:CD`. We do this by repeating the following algorithm: 1. Find the first `D` that is to the right of a block of `C`s. 2. Move the `D` to the left of that block. 3. Double the number of `C`s. Through some math, we can determine that we will end up with 123 `D`s and 4638704741628490670592103344196019722536654143873 `C`s (you were right about this not fitting in an SE answer... I doubt this would fit if stored as states of all of the atoms in the Earth combined :P). If we keep applying the reverse of `V:VD`, we can get rid of all of the `D`s now, so we get `VCCC.......CCCW`. We convert the `V` back into `YZ`. Now we have `YZCCC.......CCCW`. We want to be able to get rid of all of the `C`s and have it in the form `YAAA...AAABBB...BBBZW`. Fortunately, this can be done by the following method. Firstly, we inverse-apply `YB:Y` 587912508217580921743211 times to get `YBBB.......BBBZCCC.......CCCW`. Then, we repeat the following sequence of steps (where `[?*]` means any number of `?`, not necessarily greater than zero): 1. Inverse-apply `CZ:ZC` 587912508217580921743211 times to get `Y[A*]BBB.......BBBCCC.......CCCZCCC.......CCCW` 2. Inverse-apply `CB:BC` many times to get `Y[A*]BCBCBC.......BCBCBCZCCC.......CCCW` 3. Inverse-apply `AZ:Z` and `AB:BCA` many times to get `Y[A*]ABBB.......BBBZCCC.......CCCW` Through induction, we see that we can move the `BZ` combination all the way to the end (except before the `W`) and then the number of `A`s is 1/587912508217580921743211 of the number of `C`s, leaving us with 7890127658096618386747843 `A`s. We now have `YAAA.......AAABBB.......BBBZW`. Convert the `ZW` back to a `U`, then inverse-apply `U:BU` many times to keep only 2 `B`s and then convert the `BBU` to a `T`, and you now have `YAAA.......AAAT`. Then, you can inverse-apply `T:AAAAAT` many times to get `YAAAT` because the number of `A`s was 3 larger than a multiple of 5. Thanks for the challenge! [Answer] # [feersum](https://codegolf.stackexchange.com/a/157226/25180) This is a sokoban puzzle. The starting position is: ``` ___# #___####_____# #_#_#_##_#_!## ##______##_### ##__####_#_### ###__###__ ``` The ending position is: ``` ___# #___####_____# #_#_#_##_#_### ##____!__#_### ##__####_#_### ###__###__ ``` It can be solved using the following key sequence: > > ←←→↓↓←↑←←←←←←↓↓→↑←↑↑↑←←↓→↑→↓↓→→→→→→↓→↑↑↓↓←↓←↑→↑←←←←↑←←↓→→→→→↓→→↑↑→↑↑←↓←←↓↓→↑←↑→→↑→→↓←↓←←↓↓→↑←←←←←←←↑↑←←↓→→↓→↓↓←↑←↑→↑↑←←↓→↑→↓↓←↓→↑→→→→→→↓↓←↑→↑←←←←←←→→→→→→↑↑←↓→↓←↑↑→→↑→→↓←↓←→↑↑←↓←↓↑→→↓←↑←←↓↓↓→→↑↑↓↓←←↑↑→↓↑↑→↑→→↓←↓←↓←←↑↑→→↑→↓←↓↓←←←←←↑←←↓→→→→→←←←←←↑↑←←↓→→↓↓←↑→→→→ > > > Here is a bash program that converts the key sequence to sed commands and applies them. The sed commands contains only replacing commands using the rewrite rules defined in the cop's answer, and labelling and branching commands that doesn't modify the string. It confirms that you can get the target string using only the rewrite rules. ``` s="___##___####_____##_#_#_##_#_!####______##_#####__####_#_######__###__" input= while printf '\n%80s\n' "$s"|fold -w14 read -n 1 [ "$REPLY" = $'\e' ] do read -n 2 case "$REPLY" in [A) s="$(sed ' s:!:wLW_: :a s:L:<<<<<<<<<<<<<: s:#w<:w#: s:_w<:w_: s:_<:<_: s:#<:<#: s:#wW:wLX!: s:_W:W_: s:#W:W#: s:_wW:!: s:_X:X_: s:#X:X#: s:_wX:#: ta' <<<"$s")";; [B) s="$(sed ' s:!:_VRv: :a s:R:>>>>>>>>>>>>>: s:>v#:#v: s:>v_:_v: s:>_:_>: s:>#:#>: s:Vv#:!URv: s:U_:_U: s:U#:#U: s:Uv_:#: s:V_:_V: s:V#:#V: s:Vv_:!: ta' <<<"$s")";; [C) s="$(sed ' s:!#_:_!#: te s:!_:_!: :e' <<<"$s")";; [D) s="$(sed ' s:_#!:#!_: te s:_!:!_: :e' <<<"$s")";; esac input="$input${REPLY:1}" done echo "$input" ``` [Try it online!](https://tio.run/##jVJNj9owED3Hf2Evjp0q3UOlUvVQzcJKiemNQ4UEoYLKSsErkFZhtaHk0Pa30/EYsiZOV5uMkjd@8/E89s@y3p5O9UhoraWkD/3Io9d@4naVfOfR9@w5V2vBdtXTr8OIsWa7ezQsenreVYcHnq6qd18@1qsq5SKpxZ@H/eOGf2gGn1n0bEqEFR@waInk9Ou3yXfBRzxJVyblP9hm/xLziUXrsjYvYbsKs7JbFkW4heR9bTY8ZTXE0EwKDbgMJboTGPoP4JJshtBIi7RFmtAQhgQkAumiCqy0iIktoHAsgnNmAY5awMJRCM7UAqTtfyhTji3tpm/F3R2qzXvU6vn02Kqdwr3/2HL3Rwny6JAG7RACRyJHYI5R8WxK7AzZGQFkHcBM0jZHak4AKQeQivvVqlCtxPzYbc5Y37ok3nSTx0GyljHIWLfJmOm8INnU5ZpF7jaJhP7Jbzp1GPwVeCsqw5hZb/f8zIrT6WY5JlM3y5wMcXZZ9M2x6sJmF2tZRykvsmNtTOb1ajuqoG@neFiqraY8Mfn/BStPpLoWEMaHlvVJyvtG15HUO5/OYrjBVybTHlnH/CEor8Lrew@nlweR2fWUOvPPvTFm3jb90wn7hin@iMbXZd9yK954Xvn1fbD2Dw "Bash – Try It Online") [Try it online (with escape code removed)!](https://tio.run/##bVFNa4NAED27v0LdFptDoYEeysYG/OgthyIkWggsNtkQIZgQ03jpf7dvZ8SmTUZZ35s3b2ZkP8tm23XNq6@1lpIO@hCjxx7ekCXOjM6eMdXaF6LdVjsjnMOxqk8bN1jW9y9PzbIOXP@u8b83@93afWzHz8I5mhKwdsdivRfOqmwMSrK399mH71a1cKKRcBxsdvfQmLUbiEZ5qp3lWiGtStCZCi9DISXbULXSIm2RJhSqkIAEkFyVo1PhkZqrnFWA3pkrlgpVsATQS4WSdv6pDFyMtL808icT4cQ3ltWL7Dwsm6npZdhu07NU8sxIK80IgEVoBBao8uYZqXOocwJQGcBJqy0gLQhAYgDJu7lscr2shN3jXzOWW0q7m3/e9MqrpaekpwcvjMyuvKYpV7js2ghhVts9rruqD18nv@vSNInjNEop4jiJ0igCA0A@oQCOUIOqhOpIZgEKXki9FQmkB87B/VBNg8jQ96cPtxq6YyEK2xatot@ePCkmZlvENB9OWxTbTbiOE3ZAasXLjf/sY0cifgA "Bash – Try It Online") For up and down, `!:wLW_` or `!:_VRv` is applied for once correspondingly, and the relevant rules are applied repeatedly until the `!` appeared again. For right, one of `!#_:_!#` and `!_:_!` is applied. For left, one of `_#!:#!_` and `_!:!_` is applied. See the output in the links for the position after each move. [Answer] ## [boboquack](https://codegolf.stackexchange.com/a/157109/14109) For a given string, take all the letters (a = 0, b = 1, c = 2), sum them up and take the modulo 3. Then none of the rewrite rules change that value. The source string has a value of 1, and the target has a value of 2. Therefore, no combination of rules will transform the source string to the target string. [Answer] # [xnor](https://codegolf.stackexchange.com/a/157103/71546) > > Rule 1 `x:xn` > Rule 2 `no:oon` > Rule 3 `nr:r` > Rule 4 `ooooooooooo:` > > > We use `[X,Y]` to indicate a run of Y `X`s > > Starting from `xn[o,A]r`, > > > 1. Applying Rule 2 once we have `x[o,2]n[o,A-1]r`. > 2. Applying Rule 2 once more we have `x[o,4]n[o,A-2]r` > 3. Applying until the `o`s between `n` and `r` becomes 0, we have `x[o,2*A]nr`. > 4. Applying Rule 3 once we have `x[o,2*A]r`. > 5. Applying Rule 1 once we have `xn[o,2*A]r`. > > > So, we have an algorithm to generate from `xn[o,A]r` to `xn[o,2*A]r`. > > > Starting from `xnor = xn[o,1]r`, repeating 10 times the algorithm -- except in the 10th loop we stop at Step 4, having `x[o,1024]r`. Applying Rule 4, this clears 1023 = 11 \* 93 `o`s, leaving `xor`. [Answer] # [VortexYT](https://codegolf.stackexchange.com/a/157533/68942) There is no way of eliminating `F`s without creating/using other characters; thus, we must use `I:F` as the last step to get to the target. No rule gives a single `I` without other unwanted characters thus you can't get to the target string. Equivalently, if you try to map backwards from the source, you can only get from `F` to `I` before you have no more options. [Answer] # [The Empty String Photographer](https://codegolf.stackexchange.com/users/117478/the-empty-string-photographer) The target string cannot be reached because there is no right-to-left override in the rules. That's even easier than the effort I put into formatting the original answer. Very unfunny. :p ]
[Question] [ **The partition function:** > > In number theory, the partition function *p(n)* represents the number of possible partitions of a positive integer *n* into positive integers > > > For instance, *p(4)* = 5 because the integer 4 has five possible partitions: * 1 + 1 + 1 + 1 * 1 + 1 + 2 * 1 + 3 * 2 + 2 * 4 **Your task:** * Accept an input (let's call it *n*). It will be a positive integer. * Find the sum of the partitions of the numbers from 1 to n and output it. **Example:** Given the input 5: * p(1) = 1 * p(2) = 2 * p(3) = 3 * p(4) = 5 * p(5) = 7 Sum = 18 **As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins.** I'll add my attempt as an answer, but it can probably be golfed down a bit. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 56 bytes ``` N+I+R:-I>N,R=0;N-I+I+Q,N+(I+1)+W,R is Q+W+1. X+R:-X+1+R. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/30/bUzvIStfTzk8nyNbA2k/XEygQqOOnreGpbaipHa4TpJBZrBCoHa5tqMcVAVIaoW2oHaT330rXVDtCp7wosyQ1J08jQlPvPwA "Prolog (SWI) – Try It Online") Using Arnauld's formula again. -1 thanks to Jo King [Answer] # JavaScript (ES6), 35 bytes ``` f=(n,i=1)=>i<=n&&f(n-i,i)-~f(n,i+1) ``` [Try it online!](https://tio.run/##FYtBCsIwEADvfcUeStkljRivdn1LQ21kpexKK15C/HqMt4GZecZPPJZdXm@vdl9rTYw6Cgfim0ysw5BQvYxC/pv@xgWqyXZUYAhXUJgYLucGzhHkDmAxPWxbT5s9cI7YZy3U2j63ncpMXak/ "JavaScript (Node.js) – Try It Online") ### Recursive formula The sum of the partitions of the numbers from \$1\$ to \$n\$ is given by \$f(n,1)\$ where: $$f(n,i)=\begin{cases} 0&\text{if }i>n\\ f(n-i,i)+f(n,i+1)+1&\text{if }i\le n \end{cases}$$ [Answer] # [Desmos](https://desmos.com/calculator), 75 bytes ``` f(N)=N+∑_{n=1}^N∑_{k=1}^{n^n}0^{(n-∑_{j=1}^njmod(floor(nk/n^j),n))^2} ``` It's times like this when I really wish Desmos supported recursion... a majority of the other answers are just using some super golfy recursive formula... [Try It On Desmos!](https://www.desmos.com/calculator/4ub04bzty4) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/rntfjra1ea) --- [Me when no Desmos Recursion 😔](https://www.desmos.com/calculator/nodesrecur) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes ``` Tr@*PartitionsP@*Range ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6TIQSsgsagksyQzP684wEErKDEvPfV/QFFmXomCQ3q0aez//wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python](https://docs.python.org), ~~ 58 48 ~~ 42 bytes -6 thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)! ``` f=lambda n,b=1:b<=n and f(n-b,b)-~f(n,b+1) ``` **[Try it online!](https://tio.run/##HcZBDkAwEAXQvVPMTicqUXaNHqYTioRPGhuRunqJt3rHdc47upyDW/0mgydoccZK70AeAwWFWrRw/XzTUhnOYY8EWkDRYxqV0W3DtqDPERecKpQ3kqX7vwJzKjm/ "Python 3 – Try It Online")** [Answer] # [Python](https://python.org), 97 88 bytes ``` lambda n:sum(map(f,range(1,n+1))) f=lambda n,k=1:1+sum(f(n-j,j)for j in range(k,n//2+1)) ``` (-9 thanks to 97.100.91.109) [Try it online!](https://tio.run/##NcuxCoAgFEDRva9wfNKLsGgJ/JMWozQ1X2I19PVWRNsdzo3XsWzUZiOHvKowTopRv58BgoqgMSkyMwikUnDOCy1/g16KXpSv1ECVQ8f1lphjltg3eaS6bt4vx2TpAAPd0zc "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~43~~ ~~42~~ ~~41~~ ~~40~~ ~~39~~ 20 bytes ``` F⊕N⊞υE⮌υ⊕↨¹✂κλι¹IΣ⊟υ ``` [Try it online!](https://tio.run/##TYwxDgIhEEV7TzHlkIzFFlZ2WlloyO4JEMcsEVgyMHt9xM7u572871cnfnOx9/cmgLfshRPnxq@xi7aHpicLGmPAal1RCe6u4Mw7S2VUQ/DfXNyAE8ESg2f8EESCQDCN3pwPVkJueHW14aIJ7VbGwc/0furHPX4B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Vaguely based on @Arnauld's formula, but there's not much of it left. ``` F⊕N ``` Loop from `0` to `n`. (This part of the algorithm actually works for `n=0`, but it costs 1 byte to output the final result correctly.) ``` ⊞υE⮌υ⊕↨¹✂κλι¹ ``` Calculate the incremented sums of the upper right triangle of the reversed matrix so far and add that as the next row. ``` IΣ⊟υ ``` Output the sum of the last row. Example: For `n=0` we don't have any thing so far so we just create an empty row. The final matrix conceptually looks like this: ``` 0 ... ``` For `n=1` there is only one empty row so far so its sum is zero. This results in a row of `[1]`, with the matrix now like this: ``` 0 0 ... 1 0 ... ``` For `n=2` there are two rows. For the second row we take the sum of all of the elements but for the first row we omit the first element. Incrementing results in `[2, 1]`, with the matrix now like this: ``` 0 0 0 ... 1 0 0 ... 2 1 0 ... ``` For `n=3` the triangle's rows are `[2, 1, 0]`, `[0, 0]` and `[0]`, giving incremented sums of `[4, 1, 1]`, with the matrix now like this: ``` 0 0 0 0 ... 1 0 0 0 ... 2 1 0 0 ... 4 1 1 0 ... ``` For `n=4` the triangle's rows are `[4, 1, 1, 0]`, `[1, 0, 0]`, `[0, 0]` and `[0]`, giving incremented sums of `[7, 2, 1, 1]`, with the matrix now like this: ``` 0 0 0 0 0 ... 1 0 0 0 0 ... 2 1 0 0 0 ... 4 1 1 0 0 ... 7 2 1 1 0 ... ``` For `n=5` the triangle's rows are `[7, 2, 1, 1, 0]`, `[1, 1, 0, 0]`, `[0, 0, 0]`, `[0, 0]` and `[0]` with incremented sums of `[12, 3, 1, 1, 1]`, with the matrix now like this: ``` 0 0 0 0 0 0 ... 1 0 0 0 0 0 ... 2 1 0 0 0 0 ... 4 1 1 0 0 0 ... 7 2 1 1 0 0 ... 12 3 1 1 1 0 ... ``` For `n=6` the triangle's rows are `[12, 3, 1, 1, 1, 0]`, `[2, 1, 1, 0, 0]`, `[1, 0, 0, 0]`, `[0, 0, 0]`, `[0, 0]` and `[0]` with incremented sums of `[19, 5, 2, 1, 1, 1]`, with the matrix now like this: ``` 0 0 0 0 0 0 0 ... 1 0 0 0 0 0 0 ... 2 1 0 0 0 0 0 ... 4 1 1 0 0 0 0 ... 7 2 1 1 0 0 0 ... 12 3 1 1 1 0 0 ... 19 5 2 1 1 1 0 ... ``` The full row sums are the partition sums are desired. The first column is also `A000070`. [Answer] # [Haskell](https://www.haskell.org/), ~~31~~ 30 bytes ``` n!i|i>n=0|z<-n-i=1+z!i+n!(i+1) ``` [Try it online!](https://tio.run/##VcuxCoAgFAXQva94booU2Zz9RGM0CAVd0qeULdG/W2vz4Wzu3FfvS2GBBwPb9rn7mmtYo28BzUJCG1WSOzIyIo9XOMlScImkIKNoMk3TtXMVHPiDJVZE6QBn@TuqvA "Haskell – Try It Online") Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the formula from their answer. -1 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 4 bytes ``` vṄÞf ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJsQSIsIiIsInbhuYTDnmYiLCIiLCIxXG4yXG4zXG40XG41XG42XG43XG44XG45Il0=) Partitions of each number in the range 1...input, flatten one layer, l flag takes length of that. Alternatively, ## 5 bytes ``` ƛṄL;∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwixpvhuYRMO+KIkSIsIiIsIjFcbjJcbjNcbjRcbjVcbjZcbjdcbjhcbjkiXQ==) [3 bytes with `s` flag](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixpvhuYRMIiwiIiwiNSJd) ## Explained ``` ƛṄL;∑ ƛ ; # Over each number in the range [1, input]: ṄL # Get the number of partitions of that number ∑ # Take the sum of that list. ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 25 bytes ``` n->sum(i=1,n,numbpart(i)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWO_N07YpLczUybQ118nTySnOTgGpKNDI1NSHyN1XS8os08hRsFQx1FAwNdBQKijLzSoACSgq6dkAiTSNPE6Z2wQIIDQA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṗL)S ``` **[Try it online!](https://tio.run/##y0rNyan8///opIc7p/toBv///98UAA "Jelly – Try It Online")** --- Or ``` Œṗ€ẎL ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~49~~ ~~48~~ 35 bytes ``` i;f(n){n=i<n?i++,f(n)-~f(n-i--):0;} ``` [Try it online!](https://tio.run/##VU/bTsMwDH3fV1iVJiVLIlYmEJAVHhBfQftQpcmIgHRqIlFRlU8nuJeVLVIs@/icY1uJg1IxWmmIo53L7N49Wcb4UIofjMIKQR@2so/WBfgsrSMUuhXgGwDdHrUKunotIIMu5bDjcMshxSy96@XIU7XzAdRb2WwwavWum4me5O3Ldd7eP@O/STic17tkVpu6ATKMsq7SLcq2ck734O23rg05LUGvZmCzIBIYG9l0NJsWPy0f0G2yYpDKi5bHliGBXqIa0eXiUVn8E44NUgxJ1hWIR8C49rnDqwIHz5fDfZbpYrbtV338VeajPPgovv4A "C (gcc) – Try It Online") *Uses [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s formula from his [JavaScript answer](https://codegolf.stackexchange.com/a/251614/9481).* *Saved a byte thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan)!!!* *Saved a whopping 13 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!* Inputs positive integer \$n\$. Returns the sum of partitions \$\displaystyle\sum\limits\_{i=1}^n p(i)\$. [Answer] # Regex `🐇` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE2 v10.35+ / Raku`:P5`), ~~16~~ 11 bytes ``` (\1x*|^x+)+ ``` [Try it on replit.com](https://replit.com/@Davidebyzero/regex-Sum-of-unordered-partitions-PerlPCRE2) - RegexMathEngine [Try it online!](https://tio.run/##RU9BTsMwELz3FSvLqmyctEkFlzpuUqlcOXGjxSpRK1kybbCDFOSaIw/giXwkbFIkLqud2dmd2ebg7F3/@gHUSQj2XO8t0LlEqIrN@nG9ipPj2THqVSaLleQBzBERD40zpxbI9kRkhMoq31jTMpKSxL@/@BZXdJLmSc4Pb4Oo/Gcz5PmSai6HWx4d966yxYKHyj7lO4U128k4ARidzR9BTaFGAXZC8EBrjASMdKSjhqvPOSuX1HFWlkEIWidZ5MMffjodo45J8Y1cwjU6NTMCP1/fQGa0RuEFRzFqff@w0bpn27y7uTx3gou@z9LbxS8 "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RU-xTsMwEBVrN_7gZFmVjZM2qRhQHTepVFYmNlqsEjWSJdMGJ5WCXDPyAawsHcrEHzHyJThJJZa7e-_e3b37PJUbo48_F5fPr4ANB6t3-VoDHnMPRbKY389nblDsDMGViHgy49SCKjyitjRqWwNabhF3kGlRlVrVBIUoqPZPVe1HZBDGQUw3L60o_Wcjz9MplpS3uyp_cW0ynUyozfRDvBI-RivuBgDdZXUmsEpEJ_AVY9Ti3FsCghrUYEXF25ikU2woSVPLGM6DyNH2j2o47Kx2Tv0bMYfeOlYjBL_vH4BGOPfCg285J-Xt3ULKr31dhDffZBk3V4fHhlHWM8dzOkXh9aSv_wA "Perl - Attempt This Online") - Perl v5.36+ [Attempt This Online!](https://ato.pxeger.com/run?1=hVZLb9tGED4W0K8YM6i9K1Kp6LSBIZoxXFuADSR2oMhoGlslaHIpLUItCXIZP1pf-wN67aWH9lTkB7XH_o1eOvuQRFsCSljUPma-eX0z8q-fkzJvavWJpkny-dLp5WVSsd3enjP5a_QsZRkXDN4ejYa70dH58TC6ODsdR9-dHo9PYK_zjIskb1IG-1rp-exVJ5nFFUTl5QRCGDnf3tx8vH7RfH939348e3kzI380Muvt_Umu_NvuTz_cutQ1J39_8S99Kux40C3DqHT9oGWplhUXU2VqdcYLPGXx_NWa3KsOFxJKXMqIVVVRkaQQtQTtZnfO6jqeMgo_1jIdDBKUgP19sMdqqc-ZSPMAKiabSoAfPKxhqn1SpMyD66LIoQizOK8VrDZj4S53v3k5CTqAD8-A6IxFU2YxIitFDA4xKb84Ojkc7XWpvfSg5vesyMjS8a8WJy15Sqm2oh5SwIEJIikaCQNYBkpVeI5WA-3BAJwnwWtlx0Et50o4dJmPDOkyM5Esk9J56DSi5lPBUsgLMTWvWNQ3rAp0wuZ3URLnObphY7e76Dovko_QTTz4VPAUumksY8ydSpJaQhgCUTddur3CoBbbdZeV6dvKzGMuCAJoB8tLJELOBClpz5-E_cCEYNgBZRI65GDgBLhyw9J8OZQcHOFni-J5g4gvdiOJRUVdBT_FhYZuA3FRNlKp68CwhNCt2GI_j2Uyi3Qs3dXaoFWsbnLpmRIEttPenX4Y6pMsqxleYrwYwlTOHgl0i08skahlK4Edt7A_L3nOiCXFu7fjES2T50mEzhLqWYwPw9F5NB6O3pyeHY6Hx4vj4fvx8OxY7be1T_bbetKnKwZvVUhAm_t2N-i3lWuFHq5lI8J9LFmUVcU8KmMpWSVIhSw_u3j92gK0dbB1JbuVmMTFKtx0b2HJGgpGsKTgAsJr8dLbxLOnAMZUzue8DdLzadASSlkp_1eoYklT1bwQGwW12ayoQE-X-yVzcWLkOJOJaWQuPMM9GiwYr8uDKqKP6YllwYkWWJQf6y98D8qixmtzgzM-JTu9HWtUPcJXuUWZrbDN88FAqMODDbjgankXfIoDQ_RXWGbWKnOC3ZjdpfBdfxLgsJljJkjtwc7tjnIME1Tj5SRs6S-TwEOhenA_FH4ArsvbES9IeU8BnVJGyM6VwJAwdSit-ZkR58sU_vn5F8CfFo5XZoSgYy1rppdUUz5mlyZmu6PQaY4Nof9WnMa1LSMN1pwzuPt92N62NrZC23Wj0fkoOjt_czg-OqGPFDX9Wu21mBiyatgTGwx_ddZ0V9Mf57eNeMMkV89DZ_Xe1FhZxRhZxbfe0EZguaftiWgucWYsB7aJBH86zP8Av_3e7329a9b_AQ "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+ [Try it online!](https://tio.run/##K0gtyjH7X1qcquDr7@ftGmmt4Brm6KMQGF2cWKmgEq@joKTwqG2SgpKOgraGhnqFeoVKvGZdXa5VaoVVgKl@rEKdgoptWmZeZnEGkBkYra@pkJZfpBBnbGAda80FlfmvEWNYoVUTV6Gtqf3/PwA "Perl 6 – Try It Online") - Raku Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.) This simply enumerates all the partitions that add up to less than or equal to the input number. In order to count unordered partitions, it enforces that partitions occur in strictly nondecreasing order. This is accomplished by starting with an arbitrary positive-sized partition on the first iteration, and adding an arbitrary nonnegative integer to the partition size on each iteration. This differs conceptually from [How many partitions do I have?](https://codegolf.stackexchange.com/questions/141163/how-many-partitions-do-i-have/250598#250598) in that the first iteration is forced to have positive size (to prevent p(0)=1 from being added to the total) and that there is no ending `$` anchor. ``` # tail = N = input number; no need to anchor, because the # following loop is forced to do at least one iteration, # and its first iteration has an anchor. ( # \1 = the following: \1x* # Previous value of \1, plus any arbitrary nonnegative integer, # if this is not the first iteration. | # or ^x+ # Any arbitrary positive integer, if this is the first iteration. )+ # Iterate the above any positive number of times. ``` A more natural way for this function to work would be to sum p(0)...p(n), rather than p(1)...p(n). This would result in the 11 byte regex `((\1|^)x*)+`, which returns a number 1 greater than the function asked for by this challenge. # Regex `🐇` ([RME](https://github.com/Davidebyzero/RegexMathEngine/) / Perl / PCRE), 20 bytes ``` ((?=(\3|^x))(\2x*))+ ``` [Try it on replit.com](https://replit.com/@Davidebyzero/regex-Sum-of-unordered-partitions-PerlPCRE) - RegexMathEngine [Try it online!](https://tio.run/##RU9BTsMwELz3FSvLqrwkaZ2iXuq4SaVy5cSNFKtErWTJtMEuUpBrjjyAJ/KR4AQkLqud2dmd2fZgzbJ/eQdqBXhzbvYG6FxEKIvt5mGzDpPj2TLqJBfFWqAHfYwIfWv16QKkPhERoDLStUZfGMlI6t6e3SWuqDTL0xwPr4Oo/Gd55HFFFYrhlouOe1uZYoG@Mo/5TsbKdyJMAEZn/UdQXchRELskQU@bGAkY6UhHNcqPOStX1CIrS58ktEl5wOEPN52OUcek8Y1cwG90qmcEvj@/gMxoE4XXOApBqbv7rVI9Y6Vk9e31qUNk9aK7QUz6nmdL/gM "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RU-9TsMwEBZrN97AsqzKR5LWKUJCddykUlk7sZESlaiRLJk2xKkU5JqRB2Bl6VDegKdh5Elwkkos9_Pdd3ff93kqN5U6_lxcPr8iUnFk1C5fK0TG3LUiWszv5zM7KHYVJVowHs04GCQL14EpK7mtEU63mFuUKKFLJWuKA-zr_ZOu3UrmB6EfwualJcX_KHM4TEkGvL2l3cd1lahoAiZRD-FKuMhW3A4Q6j7LM0BkJDqCqzwPDMmdJERxgxsiQbyNaTwlFdA4Np5Hcp9ZaH3o4bCT2il1NkKOeulEjjD6ff9AeERyRzy4kbVZdrdcZNnXvi6C229KY0HT68NjA0DTSXMF4PWj4zmdWHDD-voP "Perl - Attempt This Online") - Perl v5.36+ **[Try it online!](https://tio.run/##fVRtb5swEP6eX3FlamMHMoVGmyYIrbqu0z507RS10qY2Q9QxxCoxyMCSvn3dD9hP3A9ZdsYhpes2lIA53z333HNnWJ73E8ZWL4RkaTXlMMqZ4i9nex02ixSE@cUEAhhbbxeL66th9eXm5vPZ7PViRlaE7Afkcnj/dUkpudxd9ii1V/RPP8uBXh6Eue36ncccRTkVmU7SNikhk6c2kaGVR/PnfnsdIUvIcVmGXKlMEZbJooSadG/OiyJKOL3DPJ7H0AFGI1hb9bK2czlNfVC8rJQE13/oVLIQieRTSDOZmFskiwVXfp1tfhOyKE2zqiRao@YlvEozdg09RuHOuNv2BnaAsHVsJCRBhw7glV9gESmXJKd9dxIMfDCETGmQs8Ai@57l48oOcvOwKNk/xP8WRXuFkMPdsIRMB2v8BBc1dhtIyLwqdbji0FPch7ZGKEpeKhOteFGlpVlrNeO44KUDWByyTMqZ2cm@cVZm6mI4MakQNQCjRDbPRcpRlpcsxOSEOvDpcHwUvjs9Ozg@hnvzdn72/o0DOyazWTSpBtRgihjIluK00S@uWxwTLAu9HbA0UM1RQYSU6nDYnnqwXVxKHLYWpsmzBm53DGk/9tJsx4hHdJG3WtFaxISXqZCcmBkS0jF6Uh993KaVNWcMkwMEjcpMkNqpkQF1kK4DeVbgttmJhZySbr@75qUv6Woh0WcraPfP86Q27v8FF@za3wYk4mHyRyzTXJ1O8oV5u5Cu7U58nP856kIKB7rLriaGpRS4OQla8RshRCD1bI0C6fpg26JdcdOpWwpISich3UvZNdKs5WNaaDxqQt8s@Pn9B@DkmgOC7FopzSzpCWzmiS85I4o7cHJ@fOwAMhY4IvVvPYQODKn/jI9BGQ1gZ6dBREnr2Tsaj0/H4cnpx4Ozww/0SeTm2DSUrSM9X9ZTfJ4W/P9h69qaz0ucVsXsH1W2qn/omHs9054ZRsU51kI3X5H1@ew8rAb9V4NfLE6jpFj1Uy3Wbw "C++ (gcc) – Try It Online") - PCRE1 [Try it online!](https://tio.run/##hVXrTttIFP6fpzi4WjKTON0E1ArFMREbIoHUQpUGbbfAWsYeJ6M6Y8seN8CWv32AfcR9kGXPXJIYEmktcOZyzndu3zmO8rwzi6LnNzFLuGDwaTQZHwSjy9NxcHVxPg1@Pz@dnsFR4w0XUVrFDAZ5VLCDt/PjRjQPCwjy61vwYeL8tlx@uzus/nh4@DKdv1/OyTMhQ5/cHP74855ScnNw36K0/UxfyzkutHI/yNs9r2aklAUXM2Vlc8YzPGXh4nhL7rjBhYQclzJgRZEVJMpEKUF72FqwsgxnjMJfpYz7/QglYDAAe6yW@pyJOPWgYLIqBPS8py1MtY@ymLlwl2UpZH4SpqWC1WYs3PXBu/e3XgPw4QkQnaxgxixGYKWIwSEm21ejs5PJUYvaSxdK/siyhKwd/3V1UpOnlGor6iEZDE0QUVZJ6MM6UKrCc7QaaA/64LwKXis7Dmo5N8Kh63wkaVXOTSTrpDSeGpUo@UywGNJMzMwrFOWSFZ5O2OIhiMI0RTds7HYX3KVZ9A1akQvfMx5DKw5liLlTSVJL8H0g6qZF9zcY1GK32@vKdG1lFiEXBAG0g/k1EiFlguS007v1u54JwbAD8sh3yLDveLhq@7n5cSgZjvB/j@J5hYiHB4HEoqKugp/hQkPXgbjIK6nUdWBYQmgVbLVfhDKaBzqW1mZt0ApWVql0TQk822Sfz7@O9UmSlAwvMV4MYSbnLwRa2XcWSdSylcBmW9lf5DxlxJLi86fphObR2yhAZwl1LcbX8eQymI4nH88vTqbj09Xx@Mt0fHGq9vvaJ/trPenSDYP3CiSgzX29G/TbytVC97eyEeA@lCxIimwR5KGUrBCkQJZfXH34YAHqOti6kt1LTOJq5e@6t7BkCwUjWFNwBeHWeOnu4tlrAGMq5QteB@n0qFcTilku/1eoYFFVlDwTOwW12SQrQE@XxzVzcWKkOI6JaWQuXMM96q0Yr8uDKqKL6QllxokWWJUf6y96LuRZidfmBsd7TJqdpjWqHtFTuUWZPb/O835fqMPhDlxoa/k29CgODNHdYJlZq8wJtjS7a9Fr9249HDYLzAQpXWjeN5VjmKASL2/9mv46CdwXqgcHvuh50G7zesQrUj5SQKeUEdK8ERgSpg6lNT8T4vwSwz8//wb8tHC8MiMEHatZM72kmvIluzQx6x2FTnNsCP234TSubRmpt@WcwR10YX/f2tjzbddNJpeT4OLy48l0dEZfKGr61dprNTFkUbFXNhh@dbZ0N9Mf57eNeMckV89TY/Pe1VhJwRjZxLfd0EZgvaf1iWgucWasB7aJBD8dz93Ou@6/UZKGs/K5k2qdztF/ "C++ (gcc) – Try It Online") - PCRE2 v10.33** / [Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOMGdTelahUktvAEE0bri3ABhI5UGQ0ja0SNLmUFqGWBLmMbLe-9gF67aWH9phbX6Y99jV66eyPJNoSUMKi9mfmm79vRv71c5SnVak-wTSKPl877TSPCtZrHziTv0YvYpZwweDt6WjQC04vzwbB1fBiHHx3cTY-h4PGCy6itIoZHGqll7OjRjQLCwjy6wn4MHK-XSw-3u5X39_fvx_PXi1m5I9KJu2DPwk59snN_k8_3FFKbnp3TUpb5urvL_6lz7UcF5q5H-StrlczWcqCi6myuT7jGZ6ycH60IXfU4EJCjksZsKLIChJlopSg_W3OWVmGU0bhx1LG_X6EEnB4CPZYLfU5E3HqQcFkVQjoeo8bmGofZTFz4TbLUsj8JExLBavNWLjr3jevJl4D8OEJEJ26YMosRmCliMEhJvdXp-cno4MmtZculPyBZQlZOf7V8qQmTynVVtRDMjg2QURZJaEPq0CpCs_RaqA96IPzLHit7Dio5dwIh67ykSBvZiaSVVIaj41KlHwqWAxpJqbmFYpywQpPJ2x-H0RhmqIbNna7C27TLPoIzciFTxmPoRmHMsTcqSSpJfg-EHXTpLtrDGqxW61VZTq2MvOQC4IA2sH8GomQMkFy2u5O_I5nQjDsgDzyHXLcdzxctfzcfDmUHJ_iZ4fieYWI-71AYlFRV8FPcaGh60Bc5JVU6jowLCE0C7bcz0MZzQIdS3O9NmgFK6tUuqYEnm25dxcfBvokSUqGlxgvhjCVsycCzewTiyRq2Upg6y3tz3OeMmJJ8e7teETz6GUUoLOEuhbjw2B0GYwHozcXw5Px4Gx5PHg_HgzP1H5X-2S_rScdumbwToEEtLmvd4N-W7la6P5GNgLch5IFSZHNgzyUkhWCFMjy4dXr1xagroOtK9mdxCQuV_62ewtLNlAwghUFlxBujZfuNp49BzCmUj7ndZB2l3o1oZjl8n-FChZVRckzsVVQm02yAvR0eVgxFydGisOZmEbmwjXco96S8bo8qCI6mJ5QZpxogWX5sf6i60KelXhtbnDYx2SvvWeNqkd0VW5RZsev87zfF-rweAsutLR8C7oUB4borLHMrFXmBFuY3bXotroTD4fNHDNBShf27vaUY5igEi8nfk1_lQTuC9WDh77oetBq8XrES1I-UECnlBGydyMwJEwdSmt-JsT5MoZ_fv4F8KeF45UZIehYzZrpJdWUT9mliVnvKHSaY0PovzWncW3LSL0N5wzuYQd2d62NHd923Wh0OQqGl29Oxqfn9Imipl-tvZYTQxYVe2aD4a_Ohu56-uP8thFvmeTqeWys39saKykYI-v4NhvaCKz2tD4RzSXOjNXANpHgT4f5H-C33zvtr3tm_R8 "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+ PCRE1, and PCRE2 up to v10.34, automatically makes any capture group atomic if it contains a nested backreference. To work around this, the capture is copied between `\2` and `\3` using only forward-declared backreferences. This would also make the regex compatible with Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) and Ruby, but they have no way of doing `🐇` output without source code modifications. ``` # tail = N = input number; no need to anchor, because the # following loop is forced to do at least one iteration, # and its first iteration has an anchor. ( (?= ( # \2 = the following: \3 # Previous value of \3, if \3 is set | # or ^x # 1, if on the first iteration ) ) ( # \3 = the following, which is also subtracted from tail: \2x* # \2 plus any arbitrary nonnegative integer ) )+ # Iterate the above as many times as possible, minimum 1 ``` # [Perl](https://www.perl.org/), ~~41~~ 36 bytes (full program) ``` 1x<>~~/(\1.*|^.+)+(??{-++$i})/;say$i ``` [Try it online!](https://tio.run/##RY5NTsMwEEavYqxIsclPm4pu6iQNm6Au2LDIBkplRS615NiWbaktIV1yAI7IQQhuK8Rm9M3oab6nmRHzUSqwp0Zy@WZByA6aGd4x6ahYLGxHjeuoa3chAUozieoYliuICdjvuGAoL3Hf7lSnSXesRGG14A6FSRgHG8/wLbItFdRUIp/hvhLP2brwc7oewFYZ1B2DDb8eiE95cSHOMYpwb@kR1MAvwwBaoSxDNf63yC8W1f3TQ1PAFfwTumFqizAGV6tzgyjyuvSoNlw6EIgYgu/PLwDJmB3y8nSaoJcsvf14TSMcoeWyT6Io4AOeEN8f8JF4UeDfNAhSmKbwHcZwA3FvmGUOBQ0ehjFL7mY/SjuupB2Tx3k6zaa/ "Perl 5 – Try It Online") Unlike all of my other Perl answers of this type so far, the regex in this one is not `$`-anchored at the end, so `(??{++$i))` so no longer guaranteed not to match. It can in fact match if the regex hasn't reached the end of the string and `$i` is `1`, `11`, or any other number whose digits are all `1` in decimal. So a negative sign is added to the return value to guarantee that this "postponed" regular subexpression embedded code block will not match. Alternative 36 bytes: ``` 1x<>~~/(\1.*|^.+)+(??{-++$\})/;print ``` [Try it online!](https://tio.run/##RZDJboMwEIZfZWpZwS5LIGouMRB6ocq1h1xKGrnUNEhmESbKQsmxD9BH7ItQh6jqZTb9M/PN1KKR82GvBMwd13MZlBUceFPm5YcCQxxr0eSFKFsuFwtV8KYteJvuDAbFCWeB2r91g3f0w8tlShLPuf98dUxqkuWys00TJz2dsrrJy3boGVS1KElsoXCFKIPDLpeC@CHt0l1V1Kw4RTJQtcxbYtiGhbdak2dEpVzyJpL@jHaRfPE2gbbupoesaohm2Oa3AtORH4yKa2iatFP8BDHopO8hlZUSJKb/FP5IET0@P60DtEIMVMtbgc@B@8d2J6qMUAo3wOsyGfhxqLvweTIZz0JJiZju8RiMOWBpIfj5@gY9EGd2SLR6X76LDCfs5i2mya/fWxPEkeOgM7LQFtGuEUq0BK9p3w@e/TD7BQ "Perl 5 – Try It Online") # [Perl](https://www.perl.org/) `-p`, ~~37~~ 32 bytes (full program) ``` 1x$_~~/(\1.*|^.+)+(??{-++$\})/}{ ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wQiW@rk5fI8ZQT6smTk9bU1vD3r5aV1tbJaZWU7@2@v9/03/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") Can only take one input (followed by EOF) per run. See [Fibonacci function or sequence](https://codegolf.stackexchange.com/questions/85/fibonacci-function-or-sequence/223243#223243) for an explanation. # [Raku](https://raku.org/), 27 bytes[SBCS](https://en.wikipedia.org/wiki/Windows-1252) (anonymous function) ``` {+m:ex:P5/(\1.*|^.+)+/}o¹x* ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WjvXKrXCKsBUXyPGUE@rJk5PW1Nbvzb/0M4Krf/WxYmVCirxOkoKj9omKSjp6AG1pOUXKcQZG/wHAA "Perl 6 – Try It Online") [Answer] # [Scala,](https://www.scala-lang.org/) 58 bytes Use the recursive formula proposed in [@Arnauld's answer](https://codegolf.stackexchange.com/a/251614/110802). --- [Try it online!](https://tio.run/##LY4xC4MwEIV3f8VDHBJU0I5SCx07dJJOpUNqjVzRiyTpUMTfbqN0uLsH975351o1qNU8313rcVXEmNdXp6EFVxf2GW29LuU@SAs6sSzQDa7bLDllJNMgMkpLmZZrBGz0GIKEsr2rcLZWfe@Nt8T9Q1a4MXnUmIMT0MZCMI45SniDQyH/C2AKgB9YuLj5jDAak7KePBl2O8YhJGFQOJHM4QO5xHJHl2irZf0B) ``` def f(n:Int,i:Int=1):Int=if(i>n)0 else f(n-i,i)+f(n,i+1)+1 ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 61 bytes ``` filter f{param($i=1)if($i-le$_){($_-$i|f $i)+($_|f($i+1))+1}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f8/LTOnJLVIIa26ILEoMVdDJdPWUDMzDUjr5qSqxGtWa6jE66pk1qQpqGRqagM5NSA5bUNNTW3D2tr/pjVp/wE "PowerShell Core – Try It Online") A recursive filter, this is an implementation of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s javascript [answer](https://codegolf.stackexchange.com/a/251614/97729) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LÅœ€gO ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f53Dr0cmPmtak@///bwoA) **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] Åœ # Map each to a list of list of positive integers that sum to that value €g # Get the length of each inner list O # Sum those together # (after which the result is output implicitly) ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 3 bytes ``` řᵱƩ ``` [Try it online!](https://tio.run/##K6gs@f//6MyHWzceW/n/vykA "Pyt – Try It Online") ``` ř implicit input; řangify ᵱ ᵱartition number of each element in the array Ʃ Ʃum; implicit print ``` [Answer] # x86-64 machine code, 24 bytes ``` 31 C0 89 F9 51 57 29 CF 76 06 E8 F5 FF FF FF F8 83 D8 FF 5F 59 E2 ED C3 ``` [Try it online!](https://tio.run/##XVFNb9swDD2bv4L1EFRKnKIfQw9N00vPu@w0YOlBlmVbqyIZkt0pCPrX51Fx3aLVgSIfyccnUXbdupFyHL9pK81QKbwPfaXdRfsAnyCjy6@Y17ZJGKjYK28xf8zxqG2PNUtW8M0riLBHhj9zBheNcaUwWEN9B1l0HpWIRTKQ7d0LKpmiSoNXcvBBO0tl3RBa9DLOHqWzMJSprkgdkP0pFYZn3UEmhTH43kyxkZAyRBPKcpq2viIm101EJydxGJe8j06veuA58g1AesheaDu9yDeyQNkKj8slBS8cjoB0UjLiFi8LPKRrc0L/ttooZKtVxPstXl3zE5pOR1/X1yxfaFw/4ELvbF4gyatZ5Hxqnkt29oeQrbYKpavUXf6Wjh9jKofHuRoXl9e/iOuwZWywQTdWVSfBS17z33G1eqKlzMIOeEYk8fHmy0hkpKs89CrwSdicH/pExc539vwNop8aaPOk5BXG8Z@sjWjCuN7ffidDu98SozL/AQ "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes n in EDI and returns a value in EAX. In assembly: ``` f: xor eax, eax # Set EAX to 0. mov ecx, edi # Set ECX to n. recursion: # Starting here will add to EAX the number of partitions of 1,...,n, # but with the numbers within the partitions limited to ECX. push rcx # Save RCX and RDI (the 64-bit registers containing ECX and EDI) push rdi # onto the stack. sub edi, ecx # Subtract the limit value from n, # to try including that value in a partition. jbe skip # Jump if the result is 0 or negative. call recursion # Make a recursive call (if it is positive). clc # Set CF to 0. skip: sbb eax, -1 # Subtract -1+CF from EAX. This increases it by 1 if CF=0: # if the result of the earlier 'sub' was not negative, # which means the limit value on its own is a valid partition. pop rdi # Restore RCX and RDI pop rcx # from the stack. loop recursion # Subtract 1 from ECX, and jump back to repeat if it's nonzero. ret # Return. ``` ]
[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/6613/edit). Closed 1 year ago. [Improve this question](/posts/6613/edit) ## The challenge is twofold: Make a program that builds a door. *ASCII, HTML or otherwise* Make the door functional. *Opens and closes* *Either open-able through input or interaction!* * Non-functional door +5 points. * Just a open-able door +10 points. * Interactive door +15 points. * Fancy door +20 points. *This means revolving,bifold etc* * Animated +20 points. * <100 characters +50 points. * -100 points for using a program specifically designed for drawing or animation. If you have criteria suggestions leave them in the comments. ### Non-functional open door example: ``` <?php $idiots_in_room=true; if($idiots_in_room) { $count=20; $count2=7; for($i=0;$i<$count;$i++) { if($i==0) { echo str_repeat("-",10); if($i==0){echo ".";} echo "\n"; } elseif($i==9) { echo str_repeat("-",10); echo str_repeat(" ",7)."o"."|"; echo "\n"; } elseif($i<=9) { echo str_repeat("-",1).str_repeat(" ",8).str_repeat("-",1); echo ($i<5) ? str_repeat(" ",$i*2)."\\" : str_repeat(" ",8)."|"; echo "\n"; } elseif($i<=14) { if($i>9){echo str_repeat(" ",$i)."\\";} echo str_repeat(" ",$count2--)."|"; echo "\n"; } } } ``` ### Example Output: ``` ----------. - - \ - - \ - - \ - - \ - - | - - | - - | - - | ---------- o| \ | \ | \ | \ | \ | ``` [Answer] ### JavaScript, 4380 characters, 65(?) points ASCII? Check. HTML? Check. Is a door? Check. Openable door? Check. Interactive? Check. Fancy? Double doors with properly positioned hinges, I hope that counts. Animated? Check. Under 100 characters? Ha. Not using facilities intended for drawing? Check. [Live demo.](http://switchb.org/kpreid/2012/door/) (Note: In my testing with Firefox, clicking the doors more than once doesn't work — for some reason the event handler doesn't fire again and I'm baffled as to why; pointing out what I did wrong would be welcome. Though, you might want to run this in Chrome anyway for decent JS performance.) ``` <title>Door</title> <pre onmouseup="turn();" style="display: table; margin: auto; font-family: 'Monaco', monospace; font-size: 0.6em; line-height: 0.7em;"> </pre> <p>Click doors to open or close.</p> <script> // Appearance of hit surface - global used to avoid allocating a record to return var mat; // Scene construction tools function box(size,ms) { return function (x, y, z) { var vdist0 = Math.abs(x) - size[0]; var vdist1 = Math.abs(y) - size[1]; var vdist2 = Math.abs(z) - size[2]; mat = vdist0 > vdist1 && vdist0 > vdist2 ? ms[0] : vdist1 > vdist0 && vdist1 > vdist2 ? ms[1] : ms[2]; return Math.max(vdist0, vdist1, vdist2); }; } function translate(vec, obj) { var dx = vec[0]; var dy = vec[1]; var dz = vec[2]; return function (x, y, z) { return obj(x - dx, y - dy, z - dz); }; } function mirror(obj) { return function (x, y, z) { return obj(-x, y, z); }; } function spin(obj) { return function (x, y, z) { var a = Date.now() / 1000; var s = Math.sin(a); var c = Math.cos(a); return obj( x * c + z * s, y, x * -s + z * c ); }; } function doorturn(obj) { return function (x, y, z) { var a = pos; var s = Math.sin(a); var c = Math.cos(a); return obj( x * c + z * s, y, x * -s + z * c ); }; } function rotx(a, obj) { return function (x, y, z) { var s = Math.sin(a); var c = Math.cos(a); return obj( x, y * c + z * s, y * -s + z * c ); }; } function roty(a, obj) { return function (x, y, z) { var s = Math.sin(a); var c = Math.cos(a); return obj( x * c + z * s, y, x * -s + z * c ); }; } function union(as, bs) { return function (x, y, z) { var a = as(x, y, z); var am = mat; var b = bs(x, y, z); if (a < b) { mat = am; return a; } else { return b; } }; } // Display parameters var vw = 80, vh = 80; var timestep = 1/30; // Scene var wallhwidth = 30; var wallhheight = 35; var wallmat = [";", "\u2014", ":"]; var dhwidth = 10; var dhheight = 20; var hthick = 2; var door = translate([-dhwidth*2, 0, 0], doorturn(translate([hthick, 0, dhwidth], box([hthick, dhheight, dhwidth], [".", "\u2014", "|"])))); var doors = union(door, mirror(door)); var wall = union( union( translate([dhwidth*2+wallhwidth, 0, -hthick], box([wallhwidth, wallhheight, hthick], wallmat)), translate([-dhwidth*2-wallhwidth, 0, -hthick], box([wallhwidth, wallhheight, hthick], wallmat))), translate([0, wallhheight-(wallhheight-dhheight)/2, -hthick], box([dhwidth*2, (wallhheight-dhheight)/2, hthick], wallmat))); var floor = translate([0, -dhheight - 1.1, 0], box([100, 1, 100], ["/","/","/"])); var sill = translate([0, -dhheight - 1, -hthick], box([dhwidth*2, 1, hthick], ["\\","%","\\"])); var sbox = translate([0, 0, -12], spin(box([8, 8, 8], ["x", "y", "z"]))) var scene = union(sbox, union(union(wall, doors), union(floor, sill))); var view = translate([vw/2, vh/2, -100], rotx(0.2, roty(-0.6, scene))); // Animation state var pos = -Math.PI/2; var dpos = 0; var interval; // Main loop function function r() { // Update state pos += dpos * timestep; if (Math.abs(pos) >= Math.PI/2) { dpos = 0; pos = Math.PI/2 * pos / Math.abs(pos); if (pos < 0) { // no animation needed clearInterval(interval); interval = undefined; } } // Render scene var t = []; for (var y = vh - 1; y >= 0; y--) { for (var x = 0; x < vw; x++) { var z = 0, distance; while ((distance = view(x,y,z)) > 0.12) { z -= distance; if (!isFinite(z) || z < -1000) { mat = " "; break; } } t.push(mat); } t.push("\n"); } document.getElementsByTagName("pre")[0].textContent = t.join(""); } // Click handler function turn() { if (dpos !== 0) { dpos *= -1; } else { dpos = (pos < 0 ? 1 : -1) * 2.3; } if (!interval) { interval = setInterval(r, timestep*1000); } } // Render initial state r(); </script> ``` When closed, the doors look like this: [![(Screenshot of closed doors.)](https://i.stack.imgur.com/RXB65.png)](http://switchb.org/kpreid/2012/door/) [Answer] # HTML & CSS3, 55 points Fancy, interactive, animated door is 55 points, I think. Yes, this opens like any other door, but if a sliding door counts as fancy, why doesn't a rotating one? If a rotating one isn't fancy, well, a sliding door is no problem `:)` A demo is available at <http://result.dabblet.com/gist/3132160/ac475112dbba493d2dd7d98493d4f4ceaa209a7c>. Click the doorknob to open and close. No JavaScript involved; it's just the magic of CSS3. ``` #wall { background-color: #eee; bottom: 0; left: 0; position: absolute; right: 0; top: 0; transform: rotateX(-10deg); transform-origin: 0 100%; transform-style: preserve-3d; } #door-container { background-color: black; height: 100%; margin: 0 auto; width: 300px; } #door { background-color: brown; height: 100%; margin: auto; position: relative; transform-origin: 0 0; transition: transform 0.5s ease; width: 300px; } #door .knob { background-color: gold; border-radius: 10px; height: 20px; margin-top: -10px; position: absolute; right: 10px; top: 50%; width: 20px; } #open:target + #wall #door { transform: rotateY(-145deg); } #open:target + #wall #open-link { display: none; } #close-link { display: none; } #open:target + #wall #close-link { display: inline; } ``` ``` <span id="open"></span> <div id="wall"> <div id="door-container"> <div id="door"> <a href="#open" id="open-link" class="knob"></a> <a href="#closed" id="close-link" class="knob"></a> </div> </div> </div> ``` [Answer] # Mathematica 271 chars ``` Manipulate[a = {0, 0, 0}; b = {0, 0, h}; p = Polygon; c = Cuboid; t = Rotate;Graphics3D[{c@{{-w - 1, 0, 0}, {-w, 1, h}}, c@{{w + 1, 0, 0}, {w, 1, h}},t[p@{a, b, {-w, 0, h}, {-w, 0, 0}}, r, {0, 0, 1}, {- 2 w/3, -w/3, 0}], t[p@{a, b, {w, 0, h}, {w, 0, 0}}, -r, {0, 0, 1}, { 2 w/3, -w/3, 0}]}],{{r, 0}, 0, 3/2}, {{w, 2}, 1, 3}, {{h, 4}, 3, 5}] ``` ![doors](https://i.stack.imgur.com/AiIdB.png) The double doors * open by rotation from zero to 90 degrees (using the slider `r`) * can be have their height and width set by sliders (`h` and `w`). * are in a 3D lighting environment * can be interactively rotated to be viewed from different angles. --- The code is based on a [program](http://demonstrations.wolfram.com/OpeningADoor/) by Sándor Kabal. [Answer] # Python - 65 points, 86 chars Interactive and less than 100 chars. Waits for input and *shows you the door*. Valid input is "open" and "close" and "bye". ``` g,s=1,'open close' while g: i=raw_input() print '_'+'/_ '[s.find(i)/5]+'_' g=i in s ``` [Answer] # Mathematica 127 chars This is a more streamlined implementation than the one I submitted earlier. It has a single door. The single door * opens by rotation from zero to 90 degrees (using the slider `o`) * is in a 3D lighting environment * can be interactively rotated to be viewed from different angles. However, it uses a fixed door height and width. ``` Manipulate[a = {0, 0, 0}; Graphics3D[{Tube[{a, {1, 0, 0}, {1, 0, 2}, {0, 0, 2}, a}, .03],Rotate[Cuboid@{a, {1, -.1, 2}}, o, {0, 0, 1}, a]}], {o, 0, -Pi/2}] ``` ![door2](https://i.stack.imgur.com/81Rnv.png) ]
[Question] [ Challenge Taken with permission from my University Code Challenge Contest --- After finishing her studies a couple of months ago, Marie opened a bank account to start receiving the payment of her first job in town. Since then she has been performing a few transactions with it. Her first payment was $1000 dollars. With that money she paid for a dinner in which she invited her parents (The dinner cost $150 dollars), then, she did a purchase in a well-known supermarket ($80 dollars) and a hotel reservation for her vacations ($200). At the end of the month she received her payment again (1040 dollars, a little more than the previous month) and the day after she spent another $70 dollars at the supermarket. Today, she realized that if after paying the first $80 dollars in the supermarket a second account had been created and the first one frozen, both accounts would have exactly the same balance: $$ \underbrace{1000\quad -150\quad -80}\_{Total=770}\quad \underbrace{-200\quad 1040\quad -70}\_{Total=770} $$ The event was so rare to her that she wants to continue ascertaining if the movements of her account and those of her friends have also this feature or not. **Challenge** Given a list of transactions, output the number of instants of time in which the owner of the bank account could have created a second account so that both had the same final balance. **Example:** `[1000, -150, -80, -200, 1040, -70]` $$ \color{red}{1)\quad\underbrace{}\_{Total=0}\quad \underbrace{1000\quad -150\quad -80\quad -200\quad 1040\quad -70}\_{Total=1540}} $$ $$ \color{red}{2)\quad\underbrace{1000}\_{Total=1000}\quad \underbrace{-150\quad -80\quad -200\quad 1040\quad -70}\_{Total=540}} $$ $$ \color{red}{3)\quad\underbrace{1000\quad -150}\_{Total=850}\quad \underbrace{-80\quad -200\quad 1040\quad -70}\_{Total=690}} $$ $$ \color{green}{4)\quad\underbrace{1000\quad -150\quad -80}\_{Total=770}\quad \underbrace{-200\quad 1040\quad -70}\_{Total=770}} $$ $$ \color{red}{5)\quad\underbrace{1000\quad -150\quad -80\quad-200}\_{Total=570}\quad \underbrace{ 1040\quad -70}\_{Total=970}} $$ $$ \color{red}{6)\quad\underbrace{1000\quad -150\quad -80\quad -200\quad 1040}\_{Total=1610}\quad \underbrace{-70}\_{Total=-70}} $$ $$ \color{red}{7)\quad\underbrace{1000\quad -150\quad -80\quad-200\quad 1040\quad -70}\_{Total=1540}\quad \underbrace{}\_{Total=0}} $$ **Test Case** * Input: `1000 -150 -80 -200 1040 -70` Output: `1` * Input: `100 -100` Output: `2` * Input: `1 2 3` Output: `1` * Input: `10 -20 15` Output: `0` * Input: `15 -15 15 -15` Output: `3` * Input: `1` Output: `0` **Notes** * You can assume there wont be any transaction of $0 dollars * You can take input in [any reasonable way](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 63 bytes ``` n=>n.Append(0).Where((a,b)=>n.Take(b).Sum()*2==n.Sum()).Count() ``` Saved 6 bytes thanks to dana [Try it online!](https://tio.run/##nZDBCoMwDIbve4rSUwLaVTfZYFYYg512EBR21q4ymati6/O7OmGwox6S/CH8H0mk8aWpx@ugZXyrjY1rbRNvSpUYtUg0O3ed0g/gyO5P1SuAwitxGuTFS0GJLBvegELoWWxDZJd20BZwPG3S3qGgAhpwzokfRC4dXYSuC/jeqQOnLOua2gIl1MFUo6QFKRJnZGnRGwUSkeXttB0g4j/UMfmPsNROQrJb6/0eQYJorT@avkHmsogxfgA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 bytes ``` {+grep .sum/2,[\+] 0,|$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwv1o7vSi1QEGvuDRX30gnOkY7VsFAp0Ylvva/NVdxIkiVho2hgYGBgq6hKZCwAGIjIM/QwATIMjew00RRBlRlgCqmYKRgjKoIZICCoSmKoCnIeAUIBZT4DwA "Perl 6 – Try It Online") # Explanation We just prepend a zero to the given list (`0,|$_`), make a sequence of partial sums with `[\+]` (i. e. the sequence formed by the first element, the sum of first two, the sum of first three etc.), and look (`grep`) for any elements that are exactly equal to the half of the final account state (sum of the given list). Finally, we count them with a `+`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0.ø.œ2ùO€ËO ``` [Try it online](https://tio.run/##yy9OTMpM/f/fQO/wDr2jk40O7/R/1LTmcLf////RhgYGOrpAIhYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/A73DO/SOTjY6vNP/UdOaw93@/3X@R0cbGhgY6OgamgIJCyA2AvIMDUyALHODWB0FkDRQ1gDC1jHSMYYIghTqGJqCOaYg7ToQKjYWAA). **Explanation:** ``` 0.ø # Surround the (implicit) input list with a leading and trailing 0 # i.e. [100,-100] → [0,100,-100,0] .œ # Get all possible partitions to divide the list # → [[[0],[100],[-100],[0]],[[0],[100],[-100,0]],[[0],[100,-100],[0]],[[0],[100,-100,0]],[[0,100],[-100],[0]],[[0,100],[-100,0]],[[0,100,-100],[0]],[[0,100,-100,0]]] 2ù # Only leave partitions consisting of 2 items # → [[[0],[100,-100,0]],[[0,100],[-100,0]],[[0,100,-100],[0]]] O # Take the sum of each # → [[0,0],[100,-100],[0,0]] €Ë # Check of each inner list if both sums are equal (1 if truthy; 0 if falsey) # → [1,0,1] O # Take the sum of that (and output as result) # → 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 6 bytes ``` ŻÄḤ=SS ``` [Try it online!](https://tio.run/##y0rNyan8///o7sMtD3cssQ0O/n@4/VHTGvf//6OjDQ0MDHQUdA1NQaQFiDACCRgamIDY5gaxOlwKIEUgNQZQno6CkY6CMVQGrAOowRTCNwUbBuKDGbGxAA "Jelly – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes ``` a=>!a.map(v=>o[s+=v]=-~o[s],s=0,o=[1])|o[s/2] ``` [Try it online!](https://tio.run/##dY3BDsIgEETvfgXeIEJdUKKX7Y8QDqS2RtOWRgwn468j1KN4mczO28ncXXShe9yWp5j9pU8DJoft1jWTW2jE1puww2hRvLOzPCBwj0Za9sr3XtnU@Tn4sW9Gf6UDNRIAOBFSFz0XUSWQcCz@BJaxzW@lNKDKOFGcHKqtjL5TNapXkof135d1MH0A "JavaScript (Node.js) – Try It Online") Save 4 bytes by using `-~o[s]`. Thanks to Shaggy. [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~42~~ 41 bytes *@NahuelFouilleul saves a byte* ``` y/ /+/;$\+=eval$'==eval$`while/^|$|\+/g}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/79SX0FfW99aJUbbNrUsMUdF3RZCJ5RnZOak6sfVqNTEaOun11b//29oqqALxBDqX35BSWZ@XvF/XV9TPQNDg/@6BQA "Perl 5 – Try It Online") [Answer] # JavaScript (ES6), 52 bytes ``` a=>a.map(x=>n+=(s+=x)==eval(a.join`+`)-s,n=s=0)|n+!s ``` [Try it online!](https://tio.run/##bY3LCsIwEEX3fkXcJeTBpFp0M/0RETrUVFrapBgpXfjvsVFc2c1lmHMPt6eZYvPopqf24eZSi4mwIjPSxBesvEQeJS4C0c00cDJ96Hwta6Gj8hgRxMvLfUxN8DEMzgzhzlt@sQCgmLZlznOOIj8sHPN9gqsQu38lG7DJFCsUO2xaK/pObdHyQ9bh8ldJbw "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(x => // for each element x in a[]: n += // increment n if the following test is truthy: (s += x) // update the left sum == // and test whether it's equal to eval(a.join`+`) - s, // the right sum n = s =0 // start with n = s = 0 ) // end of map() | n // yield n; if the final sum is 0, it means that we could have + // created a balanced account at the beginning of the process; !s // so, we increment n if it is ``` --- # Recursive version, ~~54~~ 53 bytes ``` f=(a,s=0)=>a+a?(s==eval(a.join`+`))+f(a,s+a.pop()):!s ``` [Try it online!](https://tio.run/##bY3RCoJAEEXf@wp7m2FXGa2lCLY@JAIH01DEkTb8/c0pempfLsOce7gDLxyaZz@/8knubYydB7bBE/ozG75A8L5deAQuBumn2tSIptOK4WKWGRBP2xAbmYKMbTHKAzq4lkRks7x0mkeNSh8l7fU@0A1x86@oQUlms8pmu6S1ou9UiroPWYfdrxLf "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit prefix function ``` +/⊂((+/↑)=1⊥↓)¨⍨0,⍳∘≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1v/UVeThgaQapuoaWv4qGvpo7bJmodWPOpdYaDzqHfzo44ZjzoX/U971DbhUW/fo76pnv6PupoPrTcGqgfygoOcgWSIh2fw/zQFQwMDA4VD6w1NQaQFiDACChgamICY5gZcYBUgBQZgtoKRgjFYDKxQwdAUxDEFGwCjAQ "APL (Dyalog Unicode) – Try It Online") `⍳` **ɩ**ndices  `∘` of `≢` the tally of transactions `0,` prepend zero `⊂(`…`)¨⍨` apply the following tacit function with each of those as left argument and the entire list of transactions as right argument (`⍨` swaps argument `⊂` the entire list of transactions  `(`…`)` as left argument to the below function   `¨` applied to each of the indices    `⍨` with swapped arguments (i.e. list on right, indices on left:   `↓` drop that many from the left   `1⊥` sum (lit. evaluate in base-1)   `(`…`)=` is it (0/1) equal to…    `↑` take that many transactions from the left    `+/` sum them `+/` sum that Boolean list to get the count of truths [Answer] ## Batch, 84 bytes ``` @set s=%* @set/as=%s: =+%,c=0 @for %%n in (0 %*)do @set/as-=%%n*2,c+=!s @echo %c% ``` Takes input as command-line arguments. Explanation: ``` @set s=%* ``` Join the arguments with spaces. ``` @set/as=%s: =+%,c=0 ``` Replace the spaces with `+`s and evaluate the result. Also clear the count. ``` @for %%n in (0 %*)do @set/as-=%%n*2,c+=!s ``` For each amount, subtract double that from the sum. If the result is zero, then this is a valid match, so increment the count. The extra zero at the beginning allows for a match before any amounts. ``` @echo %c% ``` Print the result. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` ⊞θ⁰IΣEθ⁼Σθ⊗Σ✂θκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gtDhDo1BHwUDTmiugKDOvRMM5sbhEI7g0V8M3sQAk41pYmphTDBYp1NRRcMkvTcpJTQHzg3Myk1NBarI1ocD6///oaEMDAwMdXUNTIGEBxEZAnqGBCZBlbhAb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input list ⁰ Literal 0 ⊞ Push to list θ Augmented list E Mapped to θ Augmented list ✂ Sliced from κ Current index Σ Summed ⊗ Doubled ⁼ Equals θ (Augmented) list Σ Summed Σ Sum of booleans I Cast to string Implicitly print ``` Unfortunately in Charcoal `Sum([])` is not `0` so I have to ensure that there is always at least one element to sum. [Answer] # [Python 3](https://docs.python.org/3/), ~~67~~ 58 bytes ``` lambda l:sum(sum(l[:x])*2==sum(l)for x in range(len(l)+1)) ``` [Try it online!](https://tio.run/##VY/RCoIwFIbvfYqD3biasM2kEOxFbBerZgpzii6wp7edZUKDHc6@/@c/Z8PbNb3Nlrq8LkZ1t4cCU0yvLsFrqmKWZC/KMrxI3Y8wQ2thVPapE6OthwdOyIKK05O7q0mjoYrAn4ozxiikPMd6xiIQcHbE/sQkhR3wzYtW9oVihRQEhezfF2J8Sh4wW3EeBiEOjfRSFskiqMPYWpf8FqQQp5eYQr0R/4MP "Python 3 – Try It Online") *-9 bytes thanks to @Don't be a x-triple dot* [Answer] # [R](https://www.r-project.org/), ~~50~~ 37 bytes ``` sum(c(0,cumsum(x<-scan()))==sum(x)/2) ``` [Try it online!](https://tio.run/##bY1NCsIwEIX3nmKgmwwkOEktirRL156hBCMBk0qbgCCePSYtSgUX8/e@NzNjMtAKMNHrYAfPLMITJt377iuhherk4q0P1l9nBmYYIVymIqQpOqYZcR1daR@tKBaGiF03C7hVmF4bk12SiLiQTU6HHCpPkna52xNiBecY7jEcQX7M2Us/RC2EK17/WygnuWzWiBbUlLd8KWtcpzc "R – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` s0GhYsE=s ``` [Try it online!](https://tio.run/##y00syfmf8L/YwD0jstjVtvi/S1RFyP9oQwMDAx0FXUNTEGkBIoxAAoYGJiC2uUEsF0gJUIEBmKlgpGAMFgKpUzA0BbFNQdoVIBSIHwsA "MATL – Try It Online") Same approach as some other answers: prepend a zero, and check how often half the cumulative sum is equal to the total sum. ``` s % Total sum of (implicit) input 0Gh % Prepend 0 to another copy of the input Ys % Cumulative sum E= % Check element-wise equality of 2*cumulative sum with total sum s % Sum number of `true` values ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, ~~14~~ 11 bytes ``` iT å+ ®¥nUx ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=aVQg5SsgrqVuVXg=&input=WzEwMDAgLTE1MCAtODAgLTIwMCAxMDQwIC03MF0KLXg=) ``` iT å+ ®¥nUx :Implicit input of array U i :Prepend T : Zero å+ :Cumulatively reduce by addition ® :Map each Z ¥ : Test for equality with n : Z subtracted from Ux : U reduced by addition :Implicitly reduce by addition and output ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~88~~ 82 bytes -6 Bytes thanks to mazzy ``` param($n)0..($x=$n.length)|%{$i+=+$z-eq($n[$_..$x]|measure -Su).sum;$z+=$n[$_]};$i ``` [Try it online!](https://tio.run/##RYzNCoMwEITvPoWHbTGYhGgNLUig79BjkeIhVkGtTSoVf549NYHqZZj9Zma711cqXcq6NlCIyXS5ypsAWsQoDWAQ0NJats9PiebDBFUoQhiJfK@NOzwohSGbG5nrXkmf3HpEdd@kMIbC5dmSQmUWzztC4V@DiDGGfRJxqxcrsQURS6w/M7T3MFllu3GMT3voduuMb4i7rxY58@ccmR8 "PowerShell – Try It Online") This seems like a very clumsy method but it got the job done. I'll try and revamp it in the future. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~49~~ ~~45~~ 36 bytes ``` (($args+0|%{2*($s+=$_)})-eq$s).count ``` [Try it online!](https://tio.run/##TY/hCsIgFIX/@xSXdQstC7c1iiDYmwxZtoJRazoKtj37UsvIH5fj5zlXTnN/qlZfVF1PeIYj9BOlKNtKr8Qw75MlRb06YsFGtlYP1GxT3rubmUZCckrAHk5jDrEQgsM6ztzcu5E4EIut0zvBvtbEW51T/JiLc7AvaSA@6XdYkQWauov/5Cf@A4wwGGAOvWeoXo0qjTpxQGlrYfHBrdJdbSxY2La5hBnoppbGXG@VN0RIvx5XNyxhh5CMyDi9AQ "PowerShell – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes Not as good as day 1. This one loses to Jelly ``` {~c₂+ᵐ=}ᶜ ``` ## Explanation ``` { }ᶜ # Count the ways to: ~c₂ # Split the input array in 2 ... +ᵐ # so that their sums ... = # are equal ``` Test suite: [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahjuZJrRUFqcklqipWCUrl9SbmSjoJ7fgmYk/GobcOjpqZyJQUNEK9cSVPp4a7O2odbJ/yvrksGymgDmba1D7fN@f8/Ojra0MDAQEch3tAURFqACCOQgKGBCYhtbhALZMfqgNWBlBmABIyAGCgCZOgoGEMUgPgQzUCuKZBvABEzBZsNEgMzYiEagBJgJbEA "Brachylog – Try It Online") [Answer] # bash, 52 bytes ``` IFS=+;for i in 0 $@;{((c+=2*(x+=i)=="$*"));};echo $c ``` [TIO](https://tio.run/##JYzBCoMwEETvfsUgOSSKsLGVFkKgp0LPPYoHqykJiIIWWqj99nRtDzs7b4edW7v4@PRhcJhd22NY17qGGNA0Bv2ExT1QFHwwkPFyvtrc3KcZAWEEQZzMW8out2UmX7kNytpUZKlS5mNc5yeILqqtZ3RRExEKXbEceUomTXt2B0r0LyI2KLFj3HLoKtHV9oL/il8) The trick: setting `IFS=+`, `"$*"` expands to a string where arguments are delimited by `+`, in arithmetic expression eval to the sum [Answer] ## Haskell, ~~46~~ 35 bytes ``` f x=sum[1|a<-scanl(+)0x,a==sum x/2] ``` [Try it online!](https://tio.run/##NYzBCsIwEETv/Yo5tpjqJhrqwXyCX1CCLGKxmJRiFHrw36Nb28sw@3Zm7pwetxBy7jC59I6t/vCpTlceQrmpaFLsBGPaGZ8j9wMcIo/nC8rx2Q8vbNFVaAug1USkUGsrehQxAjQdxDfk1ZKSEK2nglHYr7@59OvYBdh5UMBs/rTW3hf5Cw "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 19 bytes ``` 1#.[:(={:-])0+/\@,] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1oq00bKutdGM1DbT1Yxx0Yv9rcqUmZ@QrGCrYKqQpGBoYGCjEG5oCCQsgNgLyDA1MgCxzA4gyI5gyoCoDAxStQDljiIABVBHIAAVDU4igMUTQFGQ8lEJR/R8A "J – Try It Online") ## explanation ``` 1 #. [: (= ({: - ])) 0 +/\@, ] 0 , ] NB. prepend 0 to input... +/\@ NB. and take the prefix sums... [: ({: - ]) NB. then subtract that list NB. from its final elm NB. (`{:`), giving the list NB. of suffix sums... [: (= ( )) NB. create a 1-0 list showing NB. where the prefix sums NB. equal the suffix sums 1 #. NB. and take the sum. ``` ]
[Question] [ There is a challenge [Let's play tennis](https://codegolf.stackexchange.com/questions/103605) by [Daniel](https://codegolf.stackexchange.com/users/42854/daniel). He proposes to place a court in the North-South direction. My proposal is to create a court to play tennis in the East-West direction too. You have to print a tennis court, but you have to do it in the fewest bytes possible because of confidential reasons. ## Tennis court ``` ------x------ | | x | | | |--x--| | | | x | | ------x------ ``` Original rules are: * No extra spaces. * No tabs as they would be unfair. * One optional trailing newline is allowed. ## This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` s="------x------\n| | x | |\n| |--x" print s+s[-2::-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWSRcMKiBUTF6NggIQVYDJGggXKKvEVVCUmVeiUKxdHK1rZGWlaxj7/z8A "Python 2 – Try It Online") Prints the first half of the string followed by its reverse. It's boring but efficient. I tried extracting repeating parts of out `s`, especially the `-`, but didn't find anything shorter. --- **[Python 2](https://docs.python.org/2/), 59 bytes** ``` for n in 6,0,2,0,6:x='-'*n+' | |'[n:];print x[::-1]+'x'+x ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFPITNPwUzHQMcIiM2sKmzVddW18rTVFRRqgEg9Os8q1rqgKDOvRKEi2spK1zBWW71CXbvi/38A "Python 2 – Try It Online") Using [Jo King's construction](https://codegolf.stackexchange.com/a/174445/20260). --- **[Python 2](https://docs.python.org/2/), 62 bytes** ``` b='| '*2 for r in'-'*6,b,'| |--',b,'-'*6:print r+'x'+r[::-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8lWvUZBQV3LiCstv0ihSCEzT11XXctMJ0kHJF6jq6sOYoKErAqKMvNKFIq01SvUtYuirax0DWP//wcA "Python 2 – Try It Online") Prints the first half of each line, followed by `'x'`, followed by the first half reversed. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` ↑²←⁶↓xx→x²↑²‖O¬ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMqtEBHwUjTmgvK9UlNK9FRMEMIuOSX5@koKFVUKCHEgjLTM0pAgggxJCNgJgalpuWkJpf4l6UW5SQWaFgdWqNp/f//f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. By way of explanation I will show the result after each of the drawing commands up to the final reflection: ``` ↑² | | ------ ←⁶ | | x------ ↓xx x | | x------ →x² x | x-- | x------ ↑² x | | x--| | ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~13~~ 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` «ω↕9:gW:tC‟┼ ``` quad-palindromizes [a compressed corner of the field](https://dzaima.github.io/Canvas/?u=ZGVidWdDb21wcmVzc2lvbiUzRHRydWUlM0JJLnNwbGl0JTYwJTVDbiU2MCV1RkYwMyV1RkYxQWNsaXAlMjhjb21wcmVzc1N0cmluZyUyOHAucCUyOSUyOSV1RkYwMyV1RkYzMSV1RkYyQyV1MjU3NyV1RkYxQiV1MjIxMSV1RkYyQyV1MDE1NyUyMC0lM0UlMjAldTAxNTclMjBieXRlcyV1RkYyRiV1MjIxOXAuRiUzQmNvbXByZXNzaW9uUGFydHMuc2xpY2UlMjgwJTJDLTElMjkubWFwJTI4YyUzRCUzRWMubWFwJTI4YyUzRCUzRSU1QmMudHlwZSUyQ2MubGVuZ3RoJTVEJTI5JTI5JXVGRjAzJXVGRjVCJXVGRjVCJXUyNTI0JXUyMDFDJXVGRjUxJTI2JXUyMDFFJXVGRjFBJXUyNTE0JUQ3JXVGRjM1JXVGRjFCJUY3JXVGRjNEJTIwJXVGRjBBJXVGRjNE,i=LS0tLS0tJTBBeCVCNiU3QyUyMCUyMCU3QyUyMCUyMHglQjYlN0MlMjAlMjAlN0MtLXg_,v=8). [Try it here!](https://dzaima.github.io/Canvas/?u=JUFCJXUwM0M5JXUyMTk1OSUzQWcldUZGMzcldUZGMUEldUZGNTQldUZGMjMldTIwMUYldTI1M0M_,v=8) [11 bytes](https://dzaima.github.io/Canvas/?u=JXVGRjRGJTI2JXUyNTI0YSV1RkYxQSolQjEldUZGMzNvJXUyMDFGJXUyNTND,v=8) with uppercase `X`es, using the fact that `/` compresses better than `x` and palindromizing would result in overlapping `/` and its mirror `\`, which results in `X` [Answer] # [Python 3](https://docs.python.org/3/), ~~65~~ 62 bytes ``` for n in 7,0,3,0,7:x="-"*n+"| "*5;print(x[6:0:-1]+'x'+x[1:7]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFPITNPwVzHQMcYiM2tKmyVdJW08rSVahQUlLRMrQuKMvNKNCqizawMrHQNY7XVK9S1K6INrcxjNf//BwA "Python 3 – Try It Online") [Answer] # Dyalog APL, 36 bytes ``` (⌽,'x',⊢)(⊢⍪'--| |'⍪⊖)'-'⍪1 6⍴' |' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/Go569OuoV6jqPuhZpagCJR72r1HV1axQUatSBzEdd0zTVdUEsQwWzR71b1EHiIJ3/FcCgAAA "APL (Dyalog Unicode) – Try It Online") With a little help from [Adám](https://chat.stackexchange.com/transcript/message/47281505#47281505) [Answer] # Python 3, 75 bytes ``` s='-'*6;p='| |';w=s+'x'+s;a=p+' x '+p;print(w,a,p+w[4:9]+p,a,w,sep='\n') ``` Probably golfable - I've never really tried [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenges before. [Try it online!](https://tio.run/##DcsxCoAwDAXQq2T7auqkCBp6EnXoIOhSgy1UoXevHd/w9Ivn7YdSgkWPbhK1yEQZkmxgvOAgziqD6CUCq@hz@dgk44xyWsdl3lkrkglHvZtHW8oP) In Python 2 I could get it to **76 bytes** ``` s='-'*6;p='| |';w=s+'x'+s;a=p+' x '+p for i in w,a,p+w[4:9]+p,a,w:print i ``` [Answer] # [Perl 5](https://www.perl.org/), 55 bytes ``` say$_,x,~~reverse for('-'x6,'| 'x2,'| |--')[0..2,1,0] ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIlXqdCp66uKLUstag4VSEtv0hDXVe9wkxHvUZBQb3CCEzX6Oqqa0Yb6OkZ6RjqGMT@//8vv6AkMz@v@L@ur6megaEBAA "Perl 5 – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 35 bytes ``` ' |-x'[(⍉⊖⍪1∘↓)⍣2⍉3⍪2,⍨676 28⊤⍨6⍴3] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQYgFpBWV6jRrVCP1njU2/moa9qj3lWGjzpmPGqbrPmod7ERUNAYKGSk86h3hZm5mYKRxaOuJSD2o94txrH//wMA "APL (Dyalog Classic) – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, ~~42~~ ~~39~~ 34 bytes ``` RV@<P"| |".[s'-]X2PE'-X6M_.'x.RV_ ``` [Try it online!](https://tio.run/##K8gs@P8/KMzBJkCpRkGhRkkvulhdNzbCKMBVXTfCzDdeT71CLygs/v///7o5AA "Pip – Try It Online") --- Alternate solution, also 34 bytes: ``` RV@<P"-0| 0| |--"^0M_@<16RA6,t'x ``` [Try it online!](https://tio.run/##K8gs@P8/KMzBJkBJ16BGQQGEa3R1leIMfOMdbAzNghzNdErUK/7//6@bAwA "Pip – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~69~~ ~~68~~ 66 bytes *-2 thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)* ``` for l in"-","| ","| |--","| ","-":l*=6;print l[:6]+"x"+l[5::-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFHITNPSVdJR6lGQQFC1ugiuLpKVjlatmbWBUWZeSUKOdFWZrHaShVK2jnRplZWuoax//8DAA "Python 2 – Try It Online") We cycle the following three patterns infinitely (6 times is sufficiently infinite for our purposes) and slice off the first 6 characters of each: `-`, `|` , and `| |--`. Then, to get the tennis court, we concatenate an `x` and the reverse of each line. [Answer] # [J](http://jsoftware.com/), 53 bytes ``` echo|:'x'(<6)}'-'(<2;~4+i.5)}13$3 5$'-|||',11$'-- ' ``` [Try it online!](https://tio.run/##y/r/PzU5I7/GSr1CXcPGTLNWXRdIG1nXmWhn6plq1hoaqxgrmKqo69bU1KjrGBoCWboKCgrq//8DAA "J – Try It Online") [Answer] # [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), 82 bytes ``` 1 WIDTH 13:PRINT"------x------| | x | || |--x--| || | x | |------x------ ``` Abusing the WIDTH directive saved me around 20 bytes. [Answer] # [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ⌡x♠=Γτ^┼¢Δ¶─êiö$≥⌐▓ ``` [Run and debug it](https://staxlang.xyz/#p=f578063de2e75ec59bff14c488699424f2a9b2&i=&a=1) [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 34 bytes ``` +"x-| "@4\509 425 477 0@4\17218113 ``` [Try it online!](https://tio.run/##y9bNS8/7/19bqUK3RkHJwSTG1MBSwcTIVMHE3FzBAMg3NDcytDA0NP7/HwA "K (ngn/k) – Try It Online") Port of K4 answer. 2 bytes saved with the `4\`, 1 byte lost due to the `+` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` " -x|"•L®y[Â-Γ•5вèJ.º.∊ ``` [Try it online.](https://tio.run/##yy9OTMpM/f9fiUtBt6JG6VHDIp9D6yqjDzfpnpsM5Jhe2HR4hZfeoV16jzq6/v8HAA) **~~25~~ 24 bytes alternative:** ``` … -|•B°”Ñ•3вèJ3ä'x«».º.∊ ``` [Try it online.](https://tio.run/##ATQAy/9vc2FiaWX//@KApiAtfOKAokLCsOKAncOR4oCiM9Cyw6hKM8OkJ3jCq8K7LsK6LuKIiv//) **Explanation:** ``` "\n -x|" # Push string "\n -x|" •L®y[Â-Γ• # Push compressed number 5960566858660563 5в # Converted to Base-5 as list: # [2,2,2,2,2,2,3,0,4,1,1,4,1,1,3,0,4,1,1,4,2,2,3] è # Index each digit into the string J # And join the list together # "\n -x|" and [2,2,2,2,2,2,3,0,4,1,1,4,1,1,3,0,4,1,1,4,2,2,3] # → "------x\n| | x\n| |--x" .º # Intersect mirror everything horizontally .∊ # Intersect mirror everything vertically (and output implicitly) … -| # Push string " -|" •B°”Ñ• # Push compressed integer 193812448 3в # Converted to Base-3 as list: [1,1,1,1,1,1,2,0,0,2,0,0,2,0,0,2,1,1] è # Index each digit into the string J # And join the list together # " -|" and [1,1,1,1,1,1,2,0,0,2,0,0,2,0,0,2,1,1] # → "------| | | |--" 3ä # Split the string into three parts: ["------","| | ","| |--"] 'x« '# Append an "x" to each: ["------x","| | x","| |--x"] » # Join by newlines: "------x\n| | x\n| |--x" .º # Intersect mirror everything horizontally .∊ # Intersect mirror everything vertically (and output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•L®y[Â-Γ•` is `5960566858660563` and `•B°”Ñ•` is `193812448`. [Thanks to *@MagicOctopusUrn*'s ASCII-art generator](https://codegolf.stackexchange.com/a/120966/52210) for [`•L®y[Â-Γ•5BžLR"\n -x|"‡`](https://tio.run/##MzBNTDJM/f@/5tBul8OrDq08us8n6FHDwkPr0g9vMzI1dVJ61LBIqRhMAsWUnEDySsYmh5cfWgcigRILlbz@/9cFgwquGgUFIILQQD4A) and [`•B°”Ñ•3BžLR" -|"‡`](https://tio.run/##yy9OTMpM/f//UcMip0MbHjXMPTwRyDR2OrrPJ0hJQbdG6VHDwv//AQ), after which the transliterate has been golfed further by swapping the number and string on the stack, use `в` instead of `B`, and index into the string with `è`. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 28 bytes ``` 00000000: d3d5 0581 0a30 a9cb 55a3 a000 4415 60b2 .....0..U...D.`. 00000010: 06cc 03cb c179 0839 5d14 7d00 .....y.9].}. ``` [Try it online!](https://tio.run/##TcwxDsIwDIXhnVO8E1h2HbcNM1foiEScIBYYO3To2YMpDPyLB@t9vro/74/11Tv/OqNpM7DNAi7KKLk6zIqixBspiWFkHwD6xERLnAvd6PQVJAweawVrLKtMGTxrhjVJmFoYfx3GRvlKO/X@Bg "Bubblegum – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Þḅ“ H“ \’ṃ“-|x ”ŒBŒḄY ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5zD8x7uaAXSCh4gIuZRw8yHO5uBTN2aCoVHDXOPTnI6OunhjpbI//8B "Jelly – Try It Online")** [Answer] # [V](https://github.com/DJMcMayhem/V), 25 bytes ``` 13é-Äï5I |<esc>ÄÙ4l5r-Îd^ãrx ``` [Try it online!](https://tio.run/##K/v/39D48Erdwy2H15t6KijUSANZM01yTIt0D/elxB1eXFTx/z8A) Hexdump: ``` 00000000: 3133 e92d c4ef 3549 2020 7c1b c4d9 346c 13.-..5I |...4l 00000010: 3572 2dce 645e e372 78 5r-.d^.rx ``` Here was my process: ``` 13é-Äï5I |<esc>3<<ÄÙ4l5r-Gã<C-v>ërx 13é-Äï5I |<esc>3<<ÄÙ4l5r-Î7|rx 13é-Äï5I |<esc>3<<ÄÙ4l5r-Îãrx 13é-Äï5I |<esc>ÄÙ4l5r-Îd^ãrx ``` Alternate version: ``` 5I |<esc>5ÄM4l5r-HÒ-G.Îxxãrx ``` Hexdump: ``` 00000000: 3549 2020 7c1b 35c4 4d34 6c35 722d 48d2 5I |.5.M4l5r-H. 00000010: 2d47 2ece 7878 e372 780a -G..xx.rx. ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 76 bytes ``` (a='----',A='| |',b='--x--',B=' x ')=>[p=a+b+a,q=A+B+A,A+b+A,q,p].join` ` ``` [Try it online!](https://tio.run/##FchBCoQwDEDR/Zwiu7Q0eoMI8RrDgNFRUaSpo4gL797Rv/tv1kO37jelvYj27fPA2SljcYckjBfAhdQ@cj5UMwKcAOi5eifW0AallSXUQUjuE1opfcrZpti8mtxZ3Gzpy8VGNzjv8x8 "JavaScript (Node.js) – Try It Online") * 68 bytes if array of strings allowed. --- # [JavaScript (Node.js)](https://nodejs.org), 75 bytes ``` _=>[p='x---',q='x| ','x| -',q,p].map(c=>[...'1221330331221'].map(d=>c[d])) ``` [Try it online!](https://tio.run/##JYpBCoAgFESv0u4r6KdybReRCNGKotQyokV3N6XVvHkzq751NOcSLu68HdMk0yA7FSQ8nHNgR4a3qoCVKJ2FHncdiMkvRISmbRshaiEKwL9Z2Rlle0qT8S76bcTNz2QiWXw "JavaScript (Node.js) – Try It Online") * This one output 2d char array. I don't know if it can be golfed further more. [Answer] # [Red](http://www.red-lang.org),98 80 bytes ``` foreach r[1 2 3 2 1][print pick["------x------""| | x | |""| |--x--| |"]r] ``` [Try it online!](https://tio.run/##K0pN@R@UmhId@z8tvyg1MTlDoSjaUMFIwRiIDWOjC4oy80oUCjKTs6OVdMGgAkIpKdUoKABRBZisgXDBsmBubFHs//8A "Red – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 32 [bytes](https://mothereff.in/byte-counter#t_ps%40L%22x-%0A%7C%20%22jC%22%C2%9A%11%06%C2%9B%C3%B4%05k%C3%8B7%04%225) ``` t_ps@L"x- | "jC"??ôkË7"5 ``` Try it online [here](https://pyth.herokuapp.com/?code=t_ps%40L%22x-%0A%7C%20%22jC%22%C2%9A%11%06%C2%9B%C3%B4%05k%C3%8B7%04%225&debug=0). The above code contains some odd characters, so copying/pasting probably won't work. Prints the first half of the pattern, followed by its reverse without the central `x`. ``` t_ps@L"x-\n| "jC"..."5 Note newline replaced with \n, encoded string replaced with ... C"..." Convert encoded string to base 256 number 727558509253668163499780 j 5 Convert to base 5, yields [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 3, 4, 4, 0, 4, 4, 3, 4, 4, 3, 2, 3, 4, 4, 3, 1, 1, 0] @L Map each of the above to... "x-\n| " ... [x, -, newline, |, space] s Concatenate into string p Print without newline _ Reverse t All but first character, implicit print ``` [Answer] # Powershell, ~~60~~ 59 bytes *-1 bytes thanks @AdmBorkBork* ``` ('------x------','| | x | |','| |--x--| |')[0,1+2..0] ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 88 bytes ``` string a="------x------\n",b="| | x | |\n";Console.Write(a+b+"| |--x--| |\n"+b+a); ``` [Try it online!](https://tio.run/##Sy7WTc4vSv1fWpyZl64QXFlckpprrZCck1hcrOBYXVySWJKZrFCWn5mi4JuYmaehqVD9v7ikCKQ20VZJFwwqIFRMnpJOkq1SjYICEFWAyRqgmLVzfl5xfk6qXnhRZkmqRqJ2kjZYDVgfVA1QLFHT@n9t7X8A "C# (.NET Core) – Try It Online") Ungolfed: ``` string a = "------x------\n", b = "| | x | |\n"; Console.Write(a + b + "| |--x--| |\n" + b + a); ```   --- Here's an alternate way to do it with an anonymous function based on [adrianmp's answer](https://codegolf.stackexchange.com/a/111277/83280) from the first Let's Play Tennis thread: # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 88 bytes ``` ()=>{string a="------x------\n",b="| | x | |\n";return(a+b+"| |--x--| |\n"+b+a);}; ``` [Try it online!](https://tio.run/##LYvBCsIwEETv/Yqlp4RafyCmoII3Tx48qIdtTCXQJpJNpdL222tIXYad4Q2jqFTO66UnY19w@VLQnQCLnaY3Kg17GEG1SASHmChgMAo@zjzhjMYyCj7ubg9A/yIOY3bqrdqttIIG5MK4rMYVAMq8TDesdrf5ppb5BBA1pD9FJrwOvbcMi7pIZRr8y8iQi1ksR2fJtXp79SZo1jDORTbP8/ID "C# (.NET Core) – Try It Online") Ungolfed: ``` () => { string a = "------x------\n", b = "| | x | |\n"; return(a + b + "| |--x--| |\n" + b + a); }; ``` [Answer] # [K4](http://kx.com/download), ~~36~~ 35 bytes **Solution:** ``` "x-| "@4\:509 425 477 0@4\:17218113 ``` **Example:** ``` q)k)"x-| "@4\:509 425 477 0@4\:17218113 "------x------" "| | x | |" "| |--x--| |" "| | x | |" "------x------" ``` **Explanation:** We want to generate a list of indexes into the array `"x-| "`, e.g. ``` 1 1 1 1 1 1 0 1 1 1 1 1 1 2 3 3 2 3 3 0 3 3 2 3 3 2 2 3 3 2 1 1 0 1 1 2 3 3 2 2 3 3 2 3 3 0 3 3 2 3 3 2 1 1 1 1 1 1 0 1 1 1 1 1 1 ``` In order to generate this we can take the base-4 representation of the flip of these numbers. This gives us: ``` 425 509 509 425 477 477 0 477 477 425 509 509 425 ``` We can take the distinct values and index in at the indices we require: ``` q)509 425 477 0@1 0 0 1 2 2 3 2 2 1 0 0 1 425 509 509 425 477 477 0 477 477 425 509 509 425 ``` This array `1 0 0 1 2 2 3 2 2 1 0 0 1` converted to base-4 is ``` q)k)4/:1 0 0 1 2 2 3 2 2 1 0 0 1 17218113 ``` So for the solution, we are just doing these steps in reverse. ``` "x-| "@4\:509 425 477 0@4\:17218113 / the solution 4\:17218113 / convert 17218113 into base-4 509 425 477 0@ / index (@) into 509 425 477 0 4\: / convert to base-4 "x-| "@ / index (@) into "x-| " ``` [Answer] # [///](https://esolangs.org/wiki////), 46 bytes ``` /#/ ! x ! //"/------//!/| |/"x"#!--x--!#"x" ``` [Try it online!](https://tio.run/##HcahDcBADANA/lPYCbY8U0GlgrKQgN89X/XQ1XvVc9eM04tAA1x2WD@b3sB2dCSllpjfZw4 "/// – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 22 bytes ``` »°₈q8»`|- `τ3/\x+ømvøm ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%C2%B0%E2%82%88q8%C2%BB%60%7C-%20%60%CF%843%2F%5Cx%2B%C3%B8mv%C3%B8m&inputs=&header=&footer=) ## Alternative 22 bytes ``` »ƛ\¶≤NV»`x-| `τ3/ømvøm ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%C6%9B%5C%C2%B6%E2%89%A4NV%C2%BB%60x-%7C%20%60%CF%843%2F%C3%B8mv%C3%B8m&inputs=&header=&footer=) ]
[Question] [ [This is a partner question to [Calculate a probability exactly](https://codegolf.stackexchange.com/questions/51406/calculate-a-probability-exactly) ] This task is about writing code to compute a probability exactly *and quickly*. The output should be a precise probability written as a fraction in its most reduced form. That is it should never output `4/8` but rather `1/2`. For some positive integer `n`, consider a uniformly random string of 1s and -1s of length `n` and call it A. Now concatenate to `A` its first value. That is `A[1] = A[n+1]` if indexing from 1. `A` now has length `n+1`. Now also consider a second random string of length `n` whose first `n` values are -1, 0, or 1 with probability 1/4,1/2, 1/4 each and call it B. Now consider the inner product of `A[1,...,n]` and `B` and the inner product of `A[2,...,n+1]` and `B`. For example, consider `n=3`. Possible values for `A` and `B` could be `A = [-1,1,1,-1]` and `B=[0,1,-1]`. In this case the two inner products are `0` and `2`. Your code must output the probability that both inner products are zero. Copying the table produced by Martin Büttner we have the following sample results. ``` n P(n) 1 1/2 2 3/8 3 7/32 4 89/512 5 269/2048 6 903/8192 7 3035/32768 8 169801/2097152 ``` **Languages and libraries** You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible. **The task** Your code must start with `n=1` and give the correct output for each increasing n on a separate line. It should stop after 10 seconds. **The score** The score is simply the highest `n` reached before your code stops after 10 seconds when run on my computer. If there is a tie, the winner be the one to get to the highest score quickest. **Table of entries** * `n = 64` in **Python**. Version 1 by Mitch Schwartz * `n = 106` in **Python**. Version June 11 2015 by Mitch Schwartz * `n = 151` in **C++**. Port of Mitch Schwartz's answer by kirbyfan64sos * `n = 165` in **Python**. Version June 11 2015 the "pruning" version by Mitch Schwartz with `N_MAX = 165`. * `n = 945` in **Python** by Min\_25 using an exact formula. Amazing! * `n = 1228` in **Python** by Mitch Schwartz using another exact formula (based on Min\_25's previous answer). * `n = 2761` in **Python** by Mitch Schwartz using a faster implementation of the same exact formula. * `n = 3250` in **Python** using **Pypy** by Mitch Schwartz using the same implementation. This score needs `pypy MitchSchwartz-faster.py |tail` to avoid console scrolling overhead. [Answer] # Python A closed-form formula of `p(n)` is ![enter image description here](https://i.stack.imgur.com/1fCOM.png) An exponential generating function of `p(n)` is ![enter image description here](https://i.stack.imgur.com/JTjKk.png) where `I_0(x)` is the modified Bessel function of the first kind. **Edit on 2015-06-11:** - updated the Python code. **Edit on 2015-06-13:** - added a proof of the above formula. - fixed the `time_limit`. - added a PARI/GP code. **Python** ``` def solve(): # straightforward implementation from time import time from itertools import count def binom(n, r): return facts[n] // (facts[r] * facts[n - r]) def p(N): ans = 0 for i in range(1 + N // 2): t = binom(2 * (N - 2 * i), N - 2 * i) t *= binom(N, 2 * i) t *= binom(4 * i, 2 * i) ans += t e = (ans & -ans).bit_length() - 1 numer = ans >> e denom = 1 << (3 * N - 1 - e) return numer, denom facts = [1] time_limit = 10.0 + time() for i in count(1): facts.append(facts[-1] * (2 * i - 1)) facts.append(facts[-1] * (2 * i)) n, d = p(i) if time() > time_limit: break print("%d %d/%d" % (i, n, d)) solve() ``` **PARI/GP** ``` p(n) = polcoeff( (exp(x/2) + 1) * besseli(0, x/4) ^ 2, n) * n!; ``` **Proof:** This problem is similar to a 2-dimensional (restricted) random walk problem. If `A[i] = A[i+1]`, we can move from `(x, y)` to `(x+1, y+1)` [1 way], `(x, y)` [2 ways] or `(x-1, y-1)` [1 way]. If `A[i] != A[i+1]`, we can move from `(x, y)` to `(x-1, y+1)` [1 way], `(x, y)` [2 ways] or `(x+1, y-1)` [1 way]. Let `a(n, m) = [x^m]((x+1)^n + (x-1)^n)`, `b(n) = [x^n](1+x)^{2n}` and `c(n)` be the number of ways to move from `(0, 0)` to `(0, 0)` with `n` steps. Then, `c(n) = \sum_{i=0}^n a(n, i) * b(i) * b(n-i).` Since `p(n) = c(n) / 8^n`, we can get the above closed-form formula. [Answer] ## Python **Note:** Congratulations to Min\_25 for finding a closed-form solution! Thanks for the interesting problem! It can be solved using DP, although I am not currently feeling very motivated to optimise for speed to get a higher score. It could be nice for golf. The code reached `N=39` within 10 seconds on this old laptop running Python 2.7.5. ``` from time import* from fractions import* from collections import* X={(1,0,0,0):1,(-1,0,0,0):1} T=time() N=0 while 1: Y=defaultdict(lambda:0) n=d=0 for a,b,s,t in X: c=X[(a,b,s,t)] for A in ( (1,-1) if N else [a] ): for B in 1,0,0,-1: n+=c*(s+A*B==0==t+A*b+a*B) d+=c Y[(a,B,s+A*B,t+A*b)]+=c if time()>T+10: break N+=1 print N,Fraction(n,d) X=Y ``` For tuple `(a,b,s,t)`: `a` is the first element of `A`, `b` is the last element of `B`, `s` is the inner product of `A[:-1]` and `B`, and `t` is the inner product of `A[1:-1]` and `B[:-1]`, using Python slice notation. My code does not store the arrays `A` or `B` anywhere, so I use those letters to refer to the next elements to be added to `A` and `B`, respectively. This variable naming choice makes the explanation a little awkward, but allows for a nice-looking `A*b+a*B` in the code itself. Note that the element being added to `A` is the penultimate one, since the last element is always the same as the first. I have used Martin Büttner's trick of including `0` twice in `B` candidates in order to get the proper probability distribution. The dictionary `X` (which is named `Y` for `N+1`) keeps track of the count of all possible arrays according to the value of the tuple. The variables `n` and `d` stand for numerator and denominator, which is why I renamed the `n` of the problem statement as `N`. The key part of the logic is that you can update from `N` to `N+1` using just the values in the tuple. The two inner products specified in the question are given by `s+A*B` and `t+A*b+a*B`. This is clear if you examine the definitions a bit; note that `[A,a]` and `[b,B]` are the last two elements of arrays `A` and `B` respectively. Note that `s` and `t` are small and bounded according to `N`, and for a fast implementation in a fast language we could avoid dictionaries in favor of arrays. It may be possible to take advantage of symmetry considering values differing only in sign; I have not looked into that. **Remark 1**: The size of the dictionary grows quadratically in `N`, where size means number of key-value pairs. **Remark 2**: If we set an upper bound on `N`, then we can prune tuples for which `N_MAX - N <= |s|` and similarly for `t`. This could be done by specifying an absorbing state, or implicitly with a variable to hold the count of pruned states (which would need to be multiplied by 8 at each iteration). **Update**: This version is faster: ``` from time import* from fractions import* from collections import* N_MAX=115 def main(): T=time() N=1 Y={(1,0,0,0):1,(1,1,1,0):1} n=1 thresh=N_MAX while time() <= T+10: print('%d %s'%(N,Fraction(n,8**N/4))) N+=1 X=Y Y=defaultdict(lambda:0) n=0 if thresh<2: print('reached MAX_N with %.2f seconds remaining'%(T+10-time())) return for a,b,s,t in X: if not abs(s)<thresh>=abs(t): continue c=X[(a,b,s,t)] # 1,1 if not s+1 and not t+b+a: n+=c Y[(a,1,s+1,t+b)]+=c # -1,1 if not s-1 and not t-b+a: n+=c Y[(a,1,s-1,t-b)]+=c # 1,-1 if not s-1 and not t+b-a: n+=c Y[(a,-1,s-1,t+b)]+=c # -1,-1 if not s+1 and not t-b-a: n+=c Y[(a,-1,s+1,t-b)]+=c # 1,0 c+=c if not s and not t+b: n+=c Y[(a,0,s,t+b)]+=c # -1,0 if not s and not t-b: n+=c Y[(a,0,s,t-b)]+=c thresh-=1 main() ``` Optimisations implemented: * put everything into `main()` -- local variable access is faster than global * handle `N=1` explicitly to avoid the check `(1,-1) if N else [a]` (which enforces that the first element in the tuple is consistent, when adding elements to `A` starting from the empty list) * unroll the inner loops, which also eliminates multiplication * double the count `c` for adding a `0` to `B` instead of doing those operations twice * the denominator is always `8^N` so we do not need to keep track of it * now taking symmetry into account: we can fix the first element of `A` as `1` and divide the denominator by `2`, since the valid pairs `(A,B)` with `A[1]=1` and those with `A[1]=-1` can be put into one-to-one correspondence by negating `A`. Similarly, we can fix the first element of `B` as non-negative. * now with pruning. You would need to fiddle with `N_MAX` to see what score it can get on your machine. It could be rewritten to find an appropriate `N_MAX` automatically by binary search, but seems unnecessary? Note: We do not need to check the pruning condition until reaching around `N_MAX / 2`, so we could get a little speedup by iterating in two phases, but I decided not to for simplicity and code cleanliness. [Answer] ## Python Using Min\_25's idea of random walk, I was able to arrive at a different formula: ![p(n) = \begin{cases} \frac{\sum _{i=0}^{\lfloor n/2 \rfloor} \binom{2i}{i}^2 \binom{n}{2i} 4^{n-2i}}{8^n} & n \text{ odd} \ \frac{\binom{n}{n/2}^2 + \sum _{i=0}^{\lfloor n/2 \rfloor} \binom{2i}{i}^2 \binom{n}{2i} 4^{n-2i}}{8^n} & n \text{ even} \ \end{cases}](https://i.stack.imgur.com/bClfO.png) Here is a Python implementation based on Min\_25's: ``` from time import* from itertools import* def main(): def binom(n, k): return facts[n]/(facts[k]*facts[n-k]) def p(n): numer=0 for i in range(n/2+1): t=binom(2*i,i) t*=t t*=binom(n,2*i) t<<=2*(n-2*i) numer+=t if not n&1: numer+=t e=(numer&-numer).bit_length()-1 numer>>=e denom=1<<(3*n-e) return numer, denom facts=[1] time_limit=time()+10 for i in count(1): facts.append(facts[-1]*i) n,d=p(i) if time()>time_limit: break print("%d %d/%d"%(i,n,d)) main() ``` **Explanation / proof:** First we solve a related counting problem, where we allow `A[n+1] = -A[1]`; that is, the additional element concatenated to `A` can be `1` or `-1` regardless of the first element. So we do not need to keep track of how many times `A[i] = A[i+1]` occurs. We have the following random walk: From `(x,y)` we can move to `(x+1,y+1)` [1 way], `(x+1,y-1)` [1 way], `(x-1,y+1)` [1 way], `(x-1,y-1)` [1 way], `(x,y)` [4 ways] where `x` and `y` stand for the two dot products, and we are counting the number of ways to move from `(0,0)` to `(0,0)` in `n` steps. That count would then be multiplied by `2` to account for the fact that `A` can start with `1` or `-1`. We refer to staying at `(x,y)` as a *zero move*. We iterate over the number of non-zero moves `i`, which has to be even in order to get back to `(0,0)`. Horizontal and vertical movements make up two independent one-dimensional random walks, which can be counted by `C(i,i/2)^2`, where `C(n,k)` is binomial coefficient. (For a walk with `k` steps left and `k` steps right, there are `C(2k,k)` ways to choose the order of steps.) Additionally there are `C(n,i)` ways to place the moves, and `4^(n-i)` ways to choose the zero moves. So we get: ``` a(n) = 2 * sum_{i in (0,2,4,...,n)} C(i/2,i)^2 * C(n,i) * 4^(n-i) ``` Now, we need to turn back to the original problem. Define an allowable pair `(A,B)` to be *convertible* if `B` contains a zero. Define a pair `(A,B)` to be *almost allowable* if `A[n+1] = -A[1]` and the two dot products are both zero. **Lemma:** For a given `n`, the almost allowable pairs are in one-to-one correspondence with the convertible pairs. We can (reversibly) convert a convertible pair `(A,B)` into an almost allowable pair `(A',B')` by negating `A[m+1:]` and `B[m+1:]`, where `m` is the index of the last zero in `B`. The check for this is straightforward: If the last element of `B` is zero, we do not need to do anything. Otherwise, when we negate the last element of `A`, we can negate the last element of `B` in order to preserve the last term of the shifted dot product. But this negates the last value of the non-shifted dot product, so we fix this by negating the second-to-last element of `A`. But then this throws off the second-to-last value of the shifted product, so we negate the second-to-last element of `B`. And so on, until reaching a zero element in `B`. Now, we just need to show that there are no almost allowable pairs for which `B` does not contain a zero. For a dot product to equal zero, we must have an equal number of `1` and `-1` terms to cancel out. Each `-1` term is composed of `(1,-1)` or `(-1,1)`. So the parity of the number of `-1` that occur is fixed according to `n`. If the first and last elements of `A` have different signs, we change the parity, so this is impossible. So we get ``` c(n) = a(n)/2 if n is odd, else a(n)/2 + C(n,n/2)^2 p(n) = c(n) / 8^n ``` which gives the above formula (re-indexing with `i' = i/2`). **Update:** Here is a faster version using the same formula: ``` from time import* from itertools import* def main(): time_limit=time()+10 binoms=[1] cb2s=[1] cb=1 for n in count(1): if n&1: binoms=[a+b for a,b in zip([0]+binoms,binoms)] else: binoms=[a+b for a,b in zip([0]+binoms,binoms+[binoms[-1]])] cb=(cb<<2)-(cb+cb)/(n/2) cb2s.append(cb*cb) numer=0 for i in xrange(n/2+1): t=cb2s[i]*binoms[min(2*i,n-2*i)] t<<=2*(n-2*i) numer+=t if not n&1: numer+=t e=(numer&-numer).bit_length()-1 numer>>=e denom=1<<(3*n-e) if time()>time_limit: break print("%d %d/%d"%(n,numer,denom)) main() ``` Optimisations implemented: * inline function `p(n)` * use recurrence for binomial coefficients `C(n,k)` with `k <= n/2` * use recurrence for central binomial coefficients [Answer] # Explication of Min\_25's formula Min\_25 posted a great proof but it took a while to follow. This is a bit of explanation to fill in between the lines. a(n, m) represents the number of ways to choose A such that A[i] = A[i+1] m times. The formula for a(n,m) is equivalent to a(n,m) = {2 \* (n choose m) for n-m even; 0 for n-m odd.} Only one parity is allowed because A[i] != A[i+1] must occur an even number of times so that A[0] = A[n]. The factor of 2 is due to the initial choice A[0] = 1 or A[0] = -1. Once the number of (A[i] != A[i+1]) is fixed to be q (named i in the c(n) formula), it separates into two 1D random walks of length q and n-q. b(m) is the number of ways to take a one-dimensional random walk of m steps that ends at the same place it started, and has 25% chance of moving left, 50% chance of staying still, and 25% chance of moving right. A more obvious way to state the generating function is [x^m](1 + 2x + x^2)^n, where 1, 2x and x^2 represent left, no move, and right respectively. But then 1+2x+x^2 = (x+1)^2. [Answer] # C++ Just a port of the (excellent) Python answer by Mitch Schwartz. The primary difference is that I used `2` to represent `-1` for the `a` variable and did something similar for `b`, which allowed me to use an array. Using Intel C++ with `-O3`, I got `N=141`! My first version got `N=140`. This uses Boost. I tried a parallel version but ran into some trouble. ``` #include <boost/multiprecision/gmp.hpp> #include <boost/typeof/typeof.hpp> #include <boost/rational.hpp> #include <boost/chrono.hpp> #include <boost/array.hpp> #include <iostream> #include <utility> #include <map> typedef boost::multiprecision::mpz_int integer; typedef boost::array<boost::array<std::map<int, std::map<int, integer> >, 3>, 2> array; typedef boost::rational<integer> rational; int main() { BOOST_AUTO(T, boost::chrono::high_resolution_clock::now()); int N = 1; integer n = 1; array* Y = new array, *X = NULL; (*Y)[1][0][0][0] = 1; (*Y)[1][1][1][0] = 1; while (boost::chrono::high_resolution_clock::now() < T+boost::chrono::seconds(10)) { std::cout << N << " " << rational(n, boost::multiprecision::pow(integer(8), N)/4) << std::endl; ++N; delete X; X = Y; Y = new array; n = 0; for (int a=0; a<2; ++a) for (int b=0; b<3; ++b) for (BOOST_AUTO(s, (*X)[a][b].begin()); s != (*X)[a][b].end(); ++s) for (BOOST_AUTO(t, s->second.begin()); t != s->second.end(); ++t) { integer c = t->second; int d = b&2 ? -1 : b, e = a == 0 ? -1 : a; if (s->first == -1 && t->first+d+e == 0) n += c; (*Y)[a][1][s->first+1][t->first+d] += c; if (s->first == 1 && t->first-d+e == 0) n += c; (*Y)[a][1][s->first-1][t->first-d] += c; if (s->first == 1 && t->first+d-e == 0) n += c; (*Y)[a][2][s->first-1][t->first+d] += c; if (s->first == -1 && t->first-d-e == 0) n += c; (*Y)[a][2][s->first+1][t->first-d] += c; c *= 2; if (s->first == 0 && t->first+d == 0) n += c; (*Y)[a][0][s->first][t->first+d] += c; if (s->first == 0 && t->first-d == 0) n += c; (*Y)[a][0][s->first][t->first-d] += c; } } delete X; delete Y; } ``` ]
[Question] [ # Robbers' Thread In this challenge, your goal is to *crack* some code written by the Cops (their code is [here](https://codegolf.stackexchange.com/questions/44567/bowling-with-the-robbers)) by modifying it. You have *cracked* their code if: 1. Your modified code has a maximum [levenshtein-distance](https://en.wikipedia.org/wiki/Levenshtein_distance) of 10 from theirs, and has fewer characters 2. The function, given the same valid input, will produce the same output in the same language of the same version 3. You posted your modified version within 168 hours (1 week) of the original post. Your modified code must only have printable ASCII. After posting a cracked version, you should leave a comment in the original code saying that it has been cracked with a link to your crack. Your score is the total [Levenshtien distance](https://en.wikipedia.org/wiki/Levenshtein_distance) among all of your answers. Highest score wins. The accompanying Cops' thread can be found [here](https://codegolf.stackexchange.com/questions/44567/bowling-with-the-robbers). [Answer] [Original](https://codegolf.stackexchange.com/a/44594/19057) by bitpwner, **Python, 5199** ``` lambda x:eval(eval("'eJwVmDW27FoMRHNPxYEZOviBuc2MmZmhzfbo/30j0JKOVLXrlMplDFSIrgJjO5EBNjaH4UyI8ySe6HytrwMEZTvBriX1q6p42d0tx35NoRTJLdo7orQk9qrk6EwQB2iRKtpCR8ymnseOkNCjE13ethWOt5y/pZjP9YMzrst9indsZlkxdusyelyJNLaw1CUVosC7P4LdCgUAccFEdrxrznIzpyqYYzBZgJu0fUEKq7HZxaa7nqjPCkkiy3iLArLpjvoFMsDhZOK1lI0NL8Ky4zsgkEE7MrWes4l20zO10nfd3NiUaKk6vNbEzu/BYV1wsyRfXtIXdH13Wyyv1Wi/fE1m/YuDrzkGQmWtFlBbud97+/yEtMdm4uv+vrf6m5B7UA1KN8NK/3TZmv34VEOgRmEJEsZzsVs0BDkkOeY25tCnxxWkkUQAQUwJ7vnZve+LuWmeV04FulePd2o/Or3AXjSAoEzu46Q8ElaNNm8+ts2UYD99uz7kXgdX24frQd39Aarva3I1DZfple+r2PD227rGza9teRuVSLy2DGeZk3zG6zbQuV9egEsmm935F+j44Z/bD8ZwyE9fWgU68+OTY0l3JEbEMFosAn/E8hOqqlRx7xDXmOCpYSHdsrvBFj/u7xigfNDaShxXrZFmpCbPLwYrQyEBusUfAaIWWCbXHVdivm8jS3t1mJmilzlC5lxYD0M0J7YsLCxuyfoIjz/fcsnXCyS6BuyZT6SAxGilgP/EP3dtJJpW1SAIHymi2OpzLIr9DYriR7d/JXMIOyqdYluoc61XGiGvpluEZ6RcRD6lsLfRnATyDgLCmQbiYFlonx1Uezs8WLDB0iRHx3+/yuiKOBZbOPRX6dZpN727LsVAer0rriDZbzqsd8iWYOEUkUwBrfGDBWmW62J9ovZXHcI7DCy0/gyiHC/QTy0OMf4m1orNF6WDBRxXhKKZm38K+67lVG8O1MM85JBLG3gf3A+WbGLVSjBHX+p7uDrYb02mn+9BJNt1aJNwSqwakpVSyJLxFAhHD9PcVRpS1S6s59oYl8OowxQw0eabmq81f9tkM3tuypsavy6x7IrhoOJgXNzY5jFpoxZFg2QFpANFNMEEfMuyqViMn9hhyIkB0Wke+Dax4yfSj0zwzwAr3wg+rJ2QIFmTfueD8QVTg2iDI6BP/eZDTanFD7KbTJ6Re0vVmWE7mB0QS9qNtYCI7tAS0XvaekkTHSG4cpMOB3EV5KYhNLJNueL9oOtC27D4tEnofU4tEo7vz9qD4b7rKC8FYyZoOqOAOfmSH7pwkYS5FsUS4bP2Ou77RQQMSfv3yt1GGrgod8bt549ts5dw77hgd5TDACM9VqOKl7i8GfpZAtAdTYcefvu/ZyXxq2dHiyt+SFZ0W8BxSTNe7pRl7d0qp89VX7pFuTmqDVKb9lAjAjTnKpdGYsbLqw9AfsFzThIq7GjZho3uwy5UdpDYnERU2z2H3/hYvNboGmE5ger3gZcEJ3tpfnluxqmDru7J+xm5S/2IAC8gruOZI/vWzwNl98xbP67q6auflhiW0ZRrEcMS0YV7mRdrkyiEHCjMJwp2lWQYVxdxs4Q7ouyvJ2A4JH4xrst4I2T0g5vd0RaNYozWfjSsEooMEx0/J7bykRSu1kbYCs4h5GyUm16haMjBhHJYelDEgxhgYPMGbdrJts4/0xiu39YW4ih9MrxBSK+0IUMEffFL0kv+4nXOophdkE4Nrelnevs8/DomWTOUIc30CjACLXXoEKfpngunU7TxkLDucH5VMfwUMali3a3kvExI/YTrEf+SE8jSh5j+rEp2FG3Tv/auBGyp+gPw2EqN0XN65CBGM/Rc4c58Yffng7lvqpUfjH+m7NaGywr0HjFjCCRq0X1dT/JN1G+OH7pamKu/Ar0zQMfYtsr3V9L9krdVFhxC4UoqGyHxXKLGN/FNoyjFuGCZm0qO6du6/4SbgMfo6S33LXczjARHnLDIVAG0knSGYAKX0r4+Q21o7p7bRYNfVElbs9brvvsZ2BCf2n08l6nggW44ZtUZxZ9qFYl5H4ou4xrheygFrJ+A0Jk7Z3cCsS7vIZES5a72BjdEoWxogjZynKcwboRdgLhZZRbTOou7NE+7r7iQHdeP0OyNI2QBDbTEOG/+1thG6boTGlFyRVmgZzPYGFowSSjVY5B09WB7xJ9mKB333/3qWfS+GfczbDAasTm/zsTmbBuA+Ky3+HlobJ4NhroD/1o+FjEAyVzQNEcwib+JVoxGsZ8gJEDOl6FW66uDnP1VVu8BGnVEOEBDtnMOgK5imCeZNMFcnPU/AHh6sWuUJaQyssVLF4NO2ftsJcYto1GMkzhgoGZ7VFzgvAa+ztkZtNZq9nTBNJBeVwAvc+hhBA1eynIL5alMiqM5Yp48B3p0Af8lMb9g8A7eMHiQfT0rWlGJnsU/p1/HgesHPSrH9DjAZ+aAXk+UeQOI4gUBG8DIXNTZu2V96+z5QgpTa4mc5XPE3aWDRzeFhVNd4ZkznWjoS5SLn7ZgaV8SwBmtzuC6L3Hmt5590FqYp4L0fsypXZP82SVOYopIW8bS1QnzmbrNWhgVJXPFgxADVFuUdmhe8ca0GbiaB1H7qjjUYf2x1OewgzoJFDgs8p8Ry/z3crIHVjgi9sCrgeWkr03oGniyd2jNaLmOcdezSqMwNTqAIzD8G/96KGkrPc1amPWp2ULtk2C7xVEFzN8gPjrB0RH+TNVMwwKiGfkjzWgPQSWF8H4xZOfUcyMtACiPpqMcoUTzUy9h9TqUUj+2KiHeLjjwn2RmGepGP204tOHbw/T0mn5Df9CUvWwlV2zDfeoah1xf3iSAOiqiaBDa7tevfA/vb5wVeRNEvx97Qj7DF/Wdxcx4Y+5tlYR6oZSKRDNDJaK6YM8ESCVjSTZvejYIIJLLo71xGKSztdy2N9l98h1Gkq+YrixucemmcAxvRMa4AzxCqvsgtHMrlY2rVz7TCAsatev8+TTz5MCJj38vYpPpr1uVZ4i5wlTuMguuWmJ6z8fhlmp3J/kzTNE2IqaQpqZev4jafckot7q58sXrarv9g7osoGD1F/tmsjG3a5bd9gtNCfrzMzXw79zQ8/R8ji1XY+kTTaaXcT7bxJZIBDh0yZ1oNP1UgOfEMiZchUBjufgfTc8RN5GHkBmrxeAHFKWTb/G9z4VJon3vBPoEVegfHaTaQXd9vxzm6PJUup8lqZMYTS8fDe8V+CmCOJkGzLSC0Teg4DEUN7/VZVjQw5YPY061ibrInw7qwZ150yrJ59+ElUY3xSfxrLVntxk582wbZ+CPjOpUm6LuNvohkte3Zn2VbEMr4SLjiSwm19yOMyg7wM77u/NVfcZyYwcDUhTb4dqhTRTnd52/YRMBvrwakDUgF6pwvqGdA5XuhAbPrX7eMYS98p3H/bmMwb7MOGTzx1yfMEU5z0PdiQ/G9mX/Uoyw6HDbgJ913KlpRsUuz7GO0FJUzvTIwlQ36eV7s9r9+zBMJ+65PVF3+LYQt20L+T3Whv/DEl+htmozoGigdBow9PovEh1eWVQ0njbGLvn0n9TIEKiP3hqFyVmecc2MEDFO+OFGlSPgy1vaVAg1KqMhN+44lu2p+R0YAEuafxCFWlXH3hshf87S9KnrJIbAKep2sGHq/KVlHl4SzoY5j5N89wbUmH+Fq5o3rOaN77vPXK4jOQ0EC64ZfyAKSbnB86W/QGh2Ph4/MGGs33OqZ387dA8ENI8as0Jk0o12q7rZvXwoqnO+ImQ0DSb9CPwSgRF3FXhpxGLh4z8QiNxA48dy04Jsr3vQe8kq3/8AGP8dtPCTsCPvkb8sFr98+0IsSd0xwmg6TfuaMLUA5wvDO2u0SNyn87FqDJVJVI7tpL0/1R2SalPcwYp1yWrVYMwP3tchR+Qj7OWcEwrYTKMmv9D4iox8ARNJVKsYwUu+5pb0EQuqc0fTDu5m4Zuw4kafFphM4W8T4438ZgJr+bOlRc+X7VPPcuxn4PFBENL9shsQQwfxs8e9Pnafn6o9enSU0CPTKf8QbwpQ7C9CSFniLD+ak+bty7yyPFPy/anTdv72I96wj1U5WNr1OWD1pQm5h2QdUH8oaw2ZoVC2UNvL2uBHjf2oTGm8rZOx7mvHT/oypPxsEoJA5k+zyI6sFljVfYcSNhV4cHJ3HPRV1pupwgfB8QqxPm5sBaVs2B9WW0zOi8K/DLkrH30yKo/GfWEaVHqXvtCQeD3ENqSaQJs+A+RljRla0NqM/guaETUjdSFQzsCso+ioD29VDFTPQR0Y0JgEw0RjW3ZnMT36b8nZf37hPR6XRTDLsUA10cmiLKjL6eYVLyiV2be5tlEZ9R+P/bzsEbD6ppsaRlM+RyMXuNdx739mUXVozrGbGxvBuOpuNfgCdkBxK1yRkLV+a6GtB9Cb/2LYqWcjHToZTdn1SXguSeXOZsUUzMhfVx6ZiGeUlRVSr7Cf6877mYQEFviBF+t5s5Ul7x6harT8qrI0do/m7lt3huGTEMzphDHfkzRUnbwjH+kYUKjo0WK18u4Q/d5fLoSNe+lA/74y6bp+XdoWmHMeS/yLMiQCugw/WDirGRO4C2ZbHxfl8wEcSzy8fOGywShVmlkhg4jqfkz8IvcSSB7MJcX30jz6+2h+fa8lQnbKfgV7uX4Ikcp0yynhYkBxFBTIGKROvqWwAsmi0/yjskK5/tA0IOKVy4GM/S68XlA3/lmXTVf+ZJI+IpNewOxjQ3mq7iF0C+uGfXZrkyxPdhsTSveErxttffRT03jac6YJ8dcb8HiLEX2zL2jJBpHCEz8BGR71wX8dzhjTYGTT9aC+wuY8+dOiM/+usR9FO1wqww3qOHWRtpZuYRZ8TmBuka1dcrryq5rukDl+OS7GyIf1vd/Fna+buH1PWRQbjp4+KVADZow6Qep3lUcZ7aoL9pdLTf4W7/PHZ584AGtmKW/xD1FvzFGh5d83hF6cLNpkgdm8qBuH2Qkmhv0HjvpCyDLVUW7O2XkxL3BEVesFxreviIAPtucn/DV/twFvf2AeITIyYx3pbsMd5oL5rDHookzUD67El/PO+Vdrwlb+XQy3BfefPYFnUG15bJwlAN6FJSLgE0Tm78/OIPCqaJbiJaud/wP+B8oHe7w='"+".decode('base64').decode('zlib')"*56)) ``` Modified Version **Python, 5198** Levenshtein Distance **2**: ``` lambda x:eval(eval("'eJwVmDW27FoMRHNPxYEZOviBuc2MmZmhzfbo/30j0JKOVLXrlMplDFSIrgJjO5EBNjaH4UyI8ySe6HytrwMEZTvBriX1q6p42d0tx35NoRTJLdo7orQk9qrk6EwQB2iRKtpCR8ymnseOkNCjE13ethWOt5y/pZjP9YMzrst9indsZlkxdusyelyJNLaw1CUVosC7P4LdCgUAccFEdrxrznIzpyqYYzBZgJu0fUEKq7HZxaa7nqjPCkkiy3iLArLpjvoFMsDhZOK1lI0NL8Ky4zsgkEE7MrWes4l20zO10nfd3NiUaKk6vNbEzu/BYV1wsyRfXtIXdH13Wyyv1Wi/fE1m/YuDrzkGQmWtFlBbud97+/yEtMdm4uv+vrf6m5B7UA1KN8NK/3TZmv34VEOgRmEJEsZzsVs0BDkkOeY25tCnxxWkkUQAQUwJ7vnZve+LuWmeV04FulePd2o/Or3AXjSAoEzu46Q8ElaNNm8+ts2UYD99uz7kXgdX24frQd39Aarva3I1DZfple+r2PD227rGza9teRuVSLy2DGeZk3zG6zbQuV9egEsmm935F+j44Z/bD8ZwyE9fWgU68+OTY0l3JEbEMFosAn/E8hOqqlRx7xDXmOCpYSHdsrvBFj/u7xigfNDaShxXrZFmpCbPLwYrQyEBusUfAaIWWCbXHVdivm8jS3t1mJmilzlC5lxYD0M0J7YsLCxuyfoIjz/fcsnXCyS6BuyZT6SAxGilgP/EP3dtJJpW1SAIHymi2OpzLIr9DYriR7d/JXMIOyqdYluoc61XGiGvpluEZ6RcRD6lsLfRnATyDgLCmQbiYFlonx1Uezs8WLDB0iRHx3+/yuiKOBZbOPRX6dZpN727LsVAer0rriDZbzqsd8iWYOEUkUwBrfGDBWmW62J9ovZXHcI7DCy0/gyiHC/QTy0OMf4m1orNF6WDBRxXhKKZm38K+67lVG8O1MM85JBLG3gf3A+WbGLVSjBHX+p7uDrYb02mn+9BJNt1aJNwSqwakpVSyJLxFAhHD9PcVRpS1S6s59oYl8OowxQw0eabmq81f9tkM3tuypsavy6x7IrhoOJgXNzY5jFpoxZFg2QFpANFNMEEfMuyqViMn9hhyIkB0Wke+Dax4yfSj0zwzwAr3wg+rJ2QIFmTfueD8QVTg2iDI6BP/eZDTanFD7KbTJ6Re0vVmWE7mB0QS9qNtYCI7tAS0XvaekkTHSG4cpMOB3EV5KYhNLJNueL9oOtC27D4tEnofU4tEo7vz9qD4b7rKC8FYyZoOqOAOfmSH7pwkYS5FsUS4bP2Ou77RQQMSfv3yt1GGrgod8bt549ts5dw77hgd5TDACM9VqOKl7i8GfpZAtAdTYcefvu/ZyXxq2dHiyt+SFZ0W8BxSTNe7pRl7d0qp89VX7pFuTmqDVKb9lAjAjTnKpdGYsbLqw9AfsFzThIq7GjZho3uwy5UdpDYnERU2z2H3/hYvNboGmE5ger3gZcEJ3tpfnluxqmDru7J+xm5S/2IAC8gruOZI/vWzwNl98xbP67q6auflhiW0ZRrEcMS0YV7mRdrkyiEHCjMJwp2lWQYVxdxs4Q7ouyvJ2A4JH4xrst4I2T0g5vd0RaNYozWfjSsEooMEx0/J7bykRSu1kbYCs4h5GyUm16haMjBhHJYelDEgxhgYPMGbdrJts4/0xiu39YW4ih9MrxBSK+0IUMEffFL0kv+4nXOophdkE4Nrelnevs8/DomWTOUIc30CjACLXXoEKfpngunU7TxkLDucH5VMfwUMali3a3kvExI/YTrEf+SE8jSh5j+rEp2FG3Tv/auBGyp+gPw2EqN0XN65CBGM/Rc4c58Yffng7lvqpUfjH+m7NaGywr0HjFjCCRq0X1dT/JN1G+OH7pamKu/Ar0zQMfYtsr3V9L9krdVFhxC4UoqGyHxXKLGN/FNoyjFuGCZm0qO6du6/4SbgMfo6S33LXczjARHnLDIVAG0knSGYAKX0r4+Q21o7p7bRYNfVElbs9brvvsZ2BCf2n08l6nggW44ZtUZxZ9qFYl5H4ou4xrheygFrJ+A0Jk7Z3cCsS7vIZES5a72BjdEoWxogjZynKcwboRdgLhZZRbTOou7NE+7r7iQHdeP0OyNI2QBDbTEOG/+1thG6boTGlFyRVmgZzPYGFowSSjVY5B09WB7xJ9mKB333/3qWfS+GfczbDAasTm/zsTmbBuA+Ky3+HlobJ4NhroD/1o+FjEAyVzQNEcwib+JVoxGsZ8gJEDOl6FW66uDnP1VVu8BGnVEOEBDtnMOgK5imCeZNMFcnPU/AHh6sWuUJaQyssVLF4NO2ftsJcYto1GMkzhgoGZ7VFzgvAa+ztkZtNZq9nTBNJBeVwAvc+hhBA1eynIL5alMiqM5Yp48B3p0Af8lMb9g8A7eMHiQfT0rWlGJnsU/p1/HgesHPSrH9DjAZ+aAXk+UeQOI4gUBG8DIXNTZu2V96+z5QgpTa4mc5XPE3aWDRzeFhVNd4ZkznWjoS5SLn7ZgaV8SwBmtzuC6L3Hmt5590FqYp4L0fsypXZP82SVOYopIW8bS1QnzmbrNWhgVJXPFgxADVFuUdmhe8ca0GbiaB1H7qjjUYf2x1OewgzoJFDgs8p8Ry/z3crIHVjgi9sCrgeWkr03oGniyd2jNaLmOcdezSqMwNTqAIzD8G/96KGkrPc1amPWp2ULtk2C7xVEFzN8gPjrB0RH+TNVMwwKiGfkjzWgPQSWF8H4xZOfUcyMtACiPpqMcoUTzUy9h9TqUUj+2KiHeLjjwn2RmGepGP204tOHbw/T0mn5Df9CUvWwlV2zDfeoah1xf3iSAOiqiaBDa7tevfA/vb5wVeRNEvx97Qj7DF/Wdxcx4Y+5tlYR6oZSKRDNDJaK6YM8ESCVjSTZvejYIIJLLo71xGKSztdy2N9l98h1Gkq+YrixucemmcAxvRMa4AzxCqvsgtHMrlY2rVz7TCAsatev8+TTz5MCJj38vYpPpr1uVZ4i5wlTuMguuWmJ6z8fhlmp3J/kzTNE2IqaQpqZev4jafckot7q58sXrarv9g7osoGD1F/tmsjG3a5bd9gtNCfrzMzXw79zQ8/R8ji1XY+kTTaaXcT7bxJZIBDh0yZ1oNP1UgOfEMiZchUBjufgfTc8RN5GHkBmrxeAHFKWTb/G9z4VJon3vBPoEVegfHaTaQXd9vxzm6PJUup8lqZMYTS8fDe8V+CmCOJkGzLSC0Teg4DEUN7/VZVjQw5YPY061ibrInw7qwZ150yrJ59+ElUY3xSfxrLVntxk582wbZ+CPjOpUm6LuNvohkte3Zn2VbEMr4SLjiSwm19yOMyg7wM77u/NVfcZyYwcDUhTb4dqhTRTnd52/YRMBvrwakDUgF6pwvqGdA5XuhAbPrX7eMYS98p3H/bmMwb7MOGTzx1yfMEU5z0PdiQ/G9mX/Uoyw6HDbgJ913KlpRsUuz7GO0FJUzvTIwlQ36eV7s9r9+zBMJ+65PVF3+LYQt20L+T3Whv/DEl+htmozoGigdBow9PovEh1eWVQ0njbGLvn0n9TIEKiP3hqFyVmecc2MEDFO+OFGlSPgy1vaVAg1KqMhN+44lu2p+R0YAEuafxCFWlXH3hshf87S9KnrJIbAKep2sGHq/KVlHl4SzoY5j5N89wbUmH+Fq5o3rOaN77vPXK4jOQ0EC64ZfyAKSbnB86W/QGh2Ph4/MGGs33OqZ387dA8ENI8as0Jk0o12q7rZvXwoqnO+ImQ0DSb9CPwSgRF3FXhpxGLh4z8QiNxA48dy04Jsr3vQe8kq3/8AGP8dtPCTsCPvkb8sFr98+0IsSd0xwmg6TfuaMLUA5wvDO2u0SNyn87FqDJVJVI7tpL0/1R2SalPcwYp1yWrVYMwP3tchR+Qj7OWcEwrYTKMmv9D4iox8ARNJVKsYwUu+5pb0EQuqc0fTDu5m4Zuw4kafFphM4W8T4438ZgJr+bOlRc+X7VPPcuxn4PFBENL9shsQQwfxs8e9Pnafn6o9enSU0CPTKf8QbwpQ7C9CSFniLD+ak+bty7yyPFPy/anTdv72I96wj1U5WNr1OWD1pQm5h2QdUH8oaw2ZoVC2UNvL2uBHjf2oTGm8rZOx7mvHT/oypPxsEoJA5k+zyI6sFljVfYcSNhV4cHJ3HPRV1pupwgfB8QqxPm5sBaVs2B9WW0zOi8K/DLkrH30yKo/GfWEaVHqXvtCQeD3ENqSaQJs+A+RljRla0NqM/guaETUjdSFQzsCso+ioD29VDFTPQR0Y0JgEw0RjW3ZnMT36b8nZf37hPR6XRTDLsUA10cmiLKjL6eYVLyiV2be5tlEZ9R+P/bzsEbD6ppsaRlM+RyMXuNdx739mUXVozrGbGxvBuOpuNfgCdkBxK1yRkLV+a6GtB9Cb/2LYqWcjHToZTdn1SXguSeXOZsUUzMhfVx6ZiGeUlRVSr7Cf6877mYQEFviBF+t5s5Ul7x6harT8qrI0do/m7lt3huGTEMzphDHfkzRUnbwjH+kYUKjo0WK18u4Q/d5fLoSNe+lA/74y6bp+XdoWmHMeS/yLMiQCugw/WDirGRO4C2ZbHxfl8wEcSzy8fOGywShVmlkhg4jqfkz8IvcSSB7MJcX30jz6+2h+fa8lQnbKfgV7uX4Ikcp0yynhYkBxFBTIGKROvqWwAsmi0/yjskK5/tA0IOKVy4GM/S68XlA3/lmXTVf+ZJI+IpNewOxjQ3mq7iF0C+uGfXZrkyxPdhsTSveErxttffRT03jac6YJ8dcb8HiLEX2zL2jJBpHCEz8BGR71wX8dzhjTYGTT9aC+wuY8+dOiM/+usR9FO1wqww3qOHWRtpZuYRZ8TmBuka1dcrryq5rukDl+OS7GyIf1vd/Fna+buH1PWRQbjp4+KVADZow6Qep3lUcZ7aoL9pdLTf4W7/PHZ584AGtmKW/xD1FvzFGh5d83hF6cLNpkgdm8qBuH2Qkmhv0HjvpCyDLVUW7O2XkxL3BEVesFxreviIAPtucn/DV/twFvf2AeITIyYx3pbsMd5oL5rDHookzUD67El/PO+Vdrwlb+XQy3BfefPYFnUG15bJwlAN6FJSLgE0Tm78/OIPCqaJbiJaud/wP+B8oHe7w='"+".decode('base64').decode('zip')"*56)) ``` Replaced `'zlib'` with shorter alias `'zip'`. [Answer] # [Python 3, 9500 to 9499, by Sp3000, distance 10](https://codegolf.stackexchange.com/a/44605/25180) ## Original ``` def P(n,x="'Good luck!'and([2]*(len(x)==9373)+[3]*(len(x)==9373)+[5]*(len(x)==9373)+[7]*(len(x)==9373)+[11]*(len(x)==9373)+[13]*(len(x)==9373)+[17]*(len(x)==9373)+[19]*(len(x)==9373)+[23]*(len(x)==9373)+[29]*(len(x)==9373)+[31]*(x[0]==x[-1]==x[9372]==\"'\")+[37]*(x[-2]==x[9371]=='!')+[41]*(x.count(chr(39))==100)+[43]*(x.count(chr(34))==98)+[47]*(x.count(chr(92))==1)+[53]*(x.count(' ')==98)+[59]*(x.count(';')==100)+[61]*(x.count(',')==99)+[67]*(x.count('x')==98)+[71]*(x.count('(')==98and x[-29:-1]=='This is the end of the line!'))[:n]+[k for k in range(72, n**2)if all(k%d > 0 for d in range(2, k))][:n-20]if n>=0else' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!####################################################################################################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&(((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))******************************************************************************++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----------------------------------------------------------------------------------------------............................................................................................////////////////////////////////////////////////////////////////////////////////////////////////////000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222223333333333333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667777777777777777777777777777777777777777777777777777777777777777777777777777777778888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889999999999999999999999999999999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<==================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\\]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^____________________________________________________________________________________________________````````````````````````````````````````````````````````````````````````````````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssstttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'+'\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'+\"'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\"and'This is the end of the line!'"):return eval(x) ``` ## Modified ``` def P(n,x="'Good luck!'and([2]*(len(x)==9373)+[3]*(len(x)==9373)+[5]*(len(x)==9373)+[7]*(len(x)==9373)+[11]*(len(x)==9373)+[13]*(len(x)==9373)+[17]*(len(x)==9373)+[19]*(len(x)==9373)+[23]*(len(x)==9373)+[29]*(len(x)==9373)+[31]*(x[0]==x[-1]==x[9372]==\"'\")+[37]*(x[-2]==x[9371]=='!')+[41]*(x.count(chr(39))==100)+[43]*(x.count(chr(34))==98)+[47]*(x.count(chr(92))==1)+[53]*(x.count(' ')==98)+[59]*(x.count(';')==100)+[61]*(x.count(',')==99)+[67]*(x.count('x')==98)+[71]*(x.count('(')==98and x[-29:-1]=='This is the end of the line!'))[:n]+[k for k in range(72, n**2)if all(k%d > 0 for d in range(2, k))][:n-20]if n>=0 else' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$###################################################################################################%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&(((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))))))))))))******************************************************************************++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----------------------------------------------------------------------------------------------............................................................................................////////////////////////////////////////////////////////////////////////////////////////////////////000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222223333333333333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667777777777777777777777777777777777777777777777777777777777777777777777777777777778888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889999999999999999999999999999999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<==================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^____________________________________________________________________________________________________````````````````````````````````````````````````````````````````````````````````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssstttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'+'\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"'+\"'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\"and'This is the end of the line!'"):return eval(x) ``` Changed the `\\` to `\`, and moved some random characters to get a better score. [Answer] User23013 original **CJam 7531** ``` K"t0}Wi+vjx\"`@qYZpR@7,c}U3e6s:hmpe* M}|C`?I_WN6'a(Z`#%+oOE_N_AqmAgaG|OX>uF5Qn!m{sPQ4ki;7]0-ecJ;[*S!qn#V=:4aRtpk5FXXa`5q|!nkUo9-u>]Ovf2('(^~/328U!O&3[\"Ho~w?qZ<86]Rvpmtf}*$yYXeBcOYT1$qG+S$S/>j)D)cd9H7l*l;;c%1<?JHX7 5o0ii7-@_xDKoKG0ir{g{;$Ma=Cbd 75e3%UAK/7f'sH OuI*),YmCxwEF';6Sc,u76A&1j~Jo9c0Tq)#)tQKw;Mr`pk!br#Q _B,mSXH4#Dy t{vmg8=%cznRxw9U,_5[xGsS[$(X:XOfsslKkj%Lyx!}C<uEWaS<yn->#'hK5d1t>&-zF;NiO;u?Kf_Nj!Vxcp!u1ylxpUG3yp^I1?y)4&[}fyhf''o~VyE0gE]L&eL$Xs6(l]q$FmK!&#JeP8)(3ADg 600qEk;XITtTvO+n-b#D)0H*{:=g%iiq`-[JBYvUW#'4GcKa!vBqD8#\"r|beNA}K})Nnh_Y5N,zC1pVP{pjV#Gw's`WPO_.Vt=M`fHt:\"c*zBD{**2D1 h)baU<I+9-FPoc&O(%,EZ_q!VIW]aw2i+i![IugzfHa%:CF<guepsH!hn'kpm+},T1f:]@(UWI!19h)RS`%n*|*'#rKXi0PY<L20}VHG]GturEqBKe<-g~YQ!4*'78U!#,Xxl~|TM~DH!vZIF3Iq-(|5-1Y.UJZfBt.GXvt!e[6~Ez.QJH7{LDP[906rs|mC0)iZN;9P--Y]DkQ MX)wTRyvkFBxhA@n{X0p\">0)i=s~<CXCS3]H'{DcR3Yo1tg0NG!q{7n5+h_%BTYsy@#O'6_%{BP\"9Uzthw^5`fqciBk.rBbu^e}l!HW$h+~ho:8A+ =2n1Nh\"S%iqCI!Q0E.K$&2!$75bG@,EV}?a-kjb2>,;\"MOh7QR\"]$f[>E|oR#&kDD(^s&i@t(6#Td`9SJ}tDVB: oZdclb~s'*qMK pmjb,XW*[S[[7O_1|)Qut@1=I)9vB%I)G/~h_$y%5H+-ALcT,Y7WcG&iGc9joTHwaa9+{97H5rvi2[Fju2mdyqZ|u7HO4SE ZrA1S}wUv:>}=)rP+mHsXhNFm^wri8DtFdFddI}]N{(NyeX==qNu{XL\"_1`AqG*.llvLD\"J|`KZhut>30\")aeT76WMTu9mcFcLiyD4!&QvTlo#zF}W6pljg[{_2TTC6m)8jTW1M}ME|Bv.k/vAZg-q^&>q0<,<{ih_vyM~n6<ewr/=_u`Wj%XGP!p}+^g!!TmaK^WeHC+U\">qz6'M>~D\"L)Fcdm7Wf7`B-gqw|6kr`PsK;`cM\"Q4aLSG4[i+D3jg%?q,\"7SS-)69yHCW|L);[2wt$8C|JW=b*(rhj;uutE$;{e7)jYTAm#`iFUdU3iEK(q$&D/E`x9ZY'[c<HbDy{gV?eb$oOK\"6_ USFV a'<OX^o{A%Gn63tI[,P<=w ,c/=t3Wl9[44uX {^+(vho?3KxyezT/8_Qmm:UYd#{Gj7N2S2K4S*Iq56@S80Q^gME/p8,eP<{\"3xi-t-Cm43/HzA?a\"n(!l)aM!7:0BA;SrIW*$sLV>bKHRh[be|I 8m0*^X ;m]UBGhi'[_~Gwj@PN#i'+0^`TW:+IXCkPPCCh%{w@Uu#xqa@5otcog}sivL7nYO5^y+:`.&M)Lkn4VDMQF[0Y_=9, \"pZm{iV$3ycdn{}U:8)`3H,F340[|o~`DfHu?&QJI0g1#kF-`|%(4Ap#R/Fq\"1<{%CV6TucD.#pPv,mLW=*LjGS{O<eOR:dla) L[$ue1]lrdqPs_@qAy&]y&YMw9~_yZ]95C%JyXa$iR2U;{G.tb%lDx+_4K5E.{tYvvTcD3Ypq>EJVg`TI)X1w,Crw^8AAV%9AGq%].T~+$o~c#@Xc2`1r #,=/RE*8/b#/% Y~LyDrIPrN;hFt,C^1<Sa*LjPmPl9787{GXn}E|EL(&V-c&.}hSkEXG7[yf3pGlBV5_sf8-[{i@l0BY.(Q2o6)|km/?}.BKgm(i#pk,W_^FVs{r$1OEtI?E-8?VH|uRd'0xP.9,'OSjESAtmcO3Ikr\"kMs.!E\"M~wN! o^=]p0D ?le=iT$,M5%w{+5\"aT@YOj?iww>|;y~+/6z_']IUkqc>cG`V.[9g?x2`rE4y9 ^\"+OHtvia&#hrJL<y6kB*t7nEuAx/+A?:ZvT93VlH`Eg9w%&xRP+5-R^s6ez}!d#tTPCq|3v/d_.s'WZP,Wyv'FL'S3HEuBg}elwyl8f4l`{o}3vF=p]Ye1S\"8G}M<pdJ(:3;/dP2M8%8;H iln>0]pzU)7H)9jN%0I~NgV+X*Uw4[bF[Jg5aN`LIjP&m98fg777g+[2kA{`UIt3;UK#9~l@y./MME'XutazUcLz>1gnfnn*@cec8/9_h#@=t>w'oElYr2hx^ss^#X=PHDo%$8Z!f<GnME{gmQ\"$qW<K%`%g0/m)15!4A**;@>/hq@ B|c\"?*&syKxL^P@ $!y#x8A[@bE>#OF.IyP]?q+I@TxA+[3O55{'EjNTSq+lk8iR4!1+F??VFO@XA,1Znac6E:lr.\"EIT$M)wi<l:g!]2'OH107DX#y:Fp_`J?).V~4HW&S+nwGX7Xl%7ui J+HKO6kRO<e3hpO&xKDu'r:?l>aPL_iN3+Iu-s\"? Z_[<9wR,s$8}Q=;3u?x3k?ZsAp$m+??m&T18c|,d[1Alcz|gye-d_-s\"vcQi~9bx}v%O}nDO95McdnKI~iEp_C!%iNr2hnPO!.U^;+~/P^Yrh}<IAmHeulsQlDcKG|$pW)hnRYaa@v8X$ PsiGMX$4(@#6VB@IaQ};@8R0RoCI9enUbyB#3W+bA55uo qGZjOc%k:/a\"^h+V4Pdr|Rp*^H<7/5iM:j7-'p !@eq:.u>96 w}L3$*L^l/-[,UyE;|jq3_I1#w%@y(f=+2OuUK$F>xX\"{\"#?Q>2DCQ=|NB$o5EN7<#_qT=Q*3jzFDVLY4BIj[|[R1JP{z^u.l8(2Bs,n]d7[v^M:8]<^.WyFXAEDCE,p{Xdw6_|C[f7.;=*s&>/Y+ hD{OPt6wRk3MnJd-hYQ)kyee./S7J\"/6u&eQLV07$H_%TZb7BdJ2xW6MHq`-U:f^}$y\"F-e*\"v7Dx%l]my%D6! 2`BJ)5=GT{U^iDu;>HwvL^p)|*WvYwX)xLgFyTXM.y5W:RF</5<GME-<Sa\"E!jdqCzX1F.o^iq!Z5D:(|'9}L5A/iOmOaWr 25]=}eN&<Ce,S(o BB*3^2/Hq<>C/j)k)mfw+rVyJ*s(W0cq0_azYI-,p4 Qa.Q1Imz%G!GOIv\"CE,FLj:;LRm6a!cuWl%cw'|i'+gCCIHk]&Rx%emi3G-O;BXr{+;TSDCZNjm>k4MK~=xe c1d R{}N&g%G07hl'\"M3cd2um=[M1UW|qb+,p6/{PnDo+Y5XDJ-y=XZgpwe7)<\"kQG,*G?@_wwr0m';/m)SDsSH?CCF##I]X@7*LF8qf3D41M}>u>k,I VS]BYwj2#w[~0Bd+w;g+%uoXk<K!Fq*)oEPlYyL y!aF(B%E-*KUo>:q#/N;=vTtlBiD[d#?h1'usy_1*l1*+d$N_WN4!K2A'K/}L!.&f`Lllc8_%E?K%s-kUea~[TF<yBV_JBkxO%\"_YgM:Z*12D#s&=wom;8IFcb|-#)5')>nYe c5m8ocKqS{Qpo1$R$%3fxkM9zSy*Q}LEV}b%@^-b]XqVKwD`ppZVW?5'uy+X^4tEU]k;{Gq/vLwo+h-n}=c2l,.fj/yw+pP7JGb!U|`71eM00chW%22p8+#o0dzh\"A>%E_B)Xqu]8fq9&:I4l:9>n'<iUZ!>Y'L a\"L3P@`IeOb0N k5D%VgEU83[PtAn*)=q>#Q!GSBgHw$,)0@}VW-7qvb;xa7;TANcU UQfs0huJOee}6Bf@&!RX6h$SER]-tne`&A*ePIud`v<eEz.K;7FKA^}P_zBtV)a=}9 MbM#1D!+l-K<[)@Qmh878{dbcH|;_(1']9(ZXF5Qvw*;V0hAp?]{O|/j x=ZQTz7LN8ljI6UC#D3u{g\"=t<z0h9tl$C^!An&TJyg(^^-A1hm#j>Oa0s>*g7JO0]\"8ltiI43UJCSnt=BeUYrn)F>6Lz!Fj3av=Lr^O&Ek0&o) o,p,IjWNa~_,+DpX&{t6'e_.m;B 9]A2S*]D//^<,!`5'zP[AW^I4h2_0+?:Wn/cbMgSvW!_%^]f/0&G'#gt?X_gx3/?UL?1}H=Ez<WO@)$3mJaSaUfjPwonHh+k<3`Qrc(;asys}@x!=yO>s.O#}0CM$C?@g>-s81~ gM|}fq_ca@3xnM(xvDs8X0SW2++A1XU|f8TvEeD'dNA&v9W~R;-FFJwaeN>_(9Ha=h@i)-r@J&Xh{&Y<Zz-unH#.o;~Ycs74B;w!]wa:2{Go1;;_Gtb3H]u=yci_M.un.htX<:SAU%'WCg93~H{Kdt;xZb&NP&)@SlY''F)v]>BTH:k<6{4\"tN(-=JK;X#Q.J;<@_O@O_D/0;<V&/C{B/WdvyqtEn;Vd)HBE^=jmRo7#`E? &}0WhN.ui1Tz\"+N+r~F<'O6rRaeNHVLI-k!;zz-G G^m{kp2#Jn2%~)m5<h9w&TC'GlRNw4ux'0DPVH|?5om`g^$XV{,lzL^bN2Z}kT5ss!&5skt[,RyCi[Z0eK8Vp|g:91|W6rru~C1<}u+1JK5l]VTUTHsM:ZS}[fHwB=Ym)0a2%y.xErQ$Sy>RZtR]nZs8Z+Vo\"G$iGS#*R!FHMYEy'E='y1l=D+0,#6]htI;3z%u-[ofL=)a.hCxb*|LP)W(!H}>iDBOwI$P=B,9^4`GY-WZ? CE2ESQ3##*w(Mk2 h:*`0<Tn||iLI$8PoTen<9MV7(VbiO>RX')PQFg%402:A6%/,JgJhT5LVIV;U?O@VRYO<;MYxA)k}CI8wbp8VnH,o7]%Yb 2d3|JV0, ^3W?Z,el/:u3k.]7<RJ+bzy!a>4cq2(7MIm.?9':%ZLYt`?0]Yj+YySf {J(7,p:9,@-|^.%g}Q=[frb:J Q(|)No027@C$^m'QD=Y`<UUN,egc) *_No>V|q?gT*[@2}YZDbn),+w0\"9~%\"V>3+W|-^c;Z7wd>'ger4lJNL$?xXPly9woD4hX8^jH;53R>/1ItAq([v'Wq_@m6G=_%-'Y2D+HI>x}yUnYRFid].k1j+81>l?n`~6xy|vZ6b6@zfn*h5JJLp*mvsH&sT~8Ua6Hqwi,[O!,b!fJ53eu:raJL3Me,LYmxn~q~Ec9q=$$pV3YinQJ}GHT$)+Dx1n2gE{_^L_d-MnEi~&VO{iXxohWa<xkYHn;WQ]IGnw[PNi06tYbSk]c<[teckj9ns8_@]YM_Xo0W9/<L=R@Sa#PZ+Y_]P@[:&]sYo)pUqXcoL#jh2HxM+g'**':~^D:rw?5Ap(C.yK%x]M=HZi|/YG4(>2#b]'e$QcpYW?t},RQ)I|4#u1`d+mXbIF\"]Y9YWIHt\"5i8dnHHr7)f.h|]>ndB(#ThU5E/c]k^4T$[=ui7%oV qakQRMT0M)u(=:-FOSzx*G5GAa!TO.pO2qudwW4_(]Al\"Y{ywcKmaoT=E25?S>/?WWmDD(POe8]y:K-Tnj-94/Y\"],muj\"=4K>KXU;W*@M .m|/N5Xq<wD'+6-LJb8@c1ZnR`g!&RFvo1)QW>p<MH;9^F$*t<kJw=UG?cE0/]l%K&:y.QCIRGug!qWhF6^yjz4\"5qE\"6IxoMC$B!v_-[bx9=*ev;gr:4E<`tN,ke+/,G!C9WfEu;4YV]-K{3Q4GD7~6EUX,b'R(h}UtJsAr^'/ot+ez?EZ^o_Q.2's?Tk(_cS`M:Aqb?/J`kY=w;+ki*O]lT1.lB |K,zF<ZR%0k&GrAx=E+th+lOX/]R,#Js\")0JQK)H:5yws5b<BQ)iei((sQeK&->QGJ-Z=k_M+Q}tK*qkD0YaNw._RKs949vzj4Wf30J^/3L9SG(9l].Z:kv^4R8j{O_pCI)n0E_6c#z%SRk/)yh-^y3m05^,`%]W%8oT9D2tLzCW|{hF/vS|-eeMb{D@,VrE7_@ns<qvGM$o8{+S#yEO?f$~cy%=zCX+2vfn- ze?z/=b5)rHUUx=.;J~Cjy\"k05rbsBI|{vR$ue+1(ZNbr|LV/?=t]P-ux[mRJ$aCFq)qH)yJUL5q;l%p@xmjViH #%V2q1WHQc/h`X{C]m{qAo2i{H T$SWtdA ,j'W`h`p~ZsPj[>5=(?2w]auV/1gJt.ax,bH?ScD-|qP5TH3YQqS'mDp<61q0#kg0PI:w0:/V*j`V,]Y.Wf$.bqUTDa+4|Tz$y;gL:bk!,e#\"X2aE~,*Fd#3Zz5kQl6,fAb_~Cu5%68zPm^ 5SH:D}}$g\"c6ljz>`DvgZt[ 8B*s^pt1^i}&$B1)]S)T=@ySFST=d?qY6Us05[q=op_gK?u]S1m4-D:7gplk`x$m|5S3ZLkD=Qmh7f6f8g7ZOqip`%4/3SF5Gt_pH|6v%V]%(|B4+s4S(Je3A!&bVcR<ns!=Oe'0Nc{{,.7 GVvrPQA}Ean3z3Q]3Pe[J*kKs{JF`c6asf1z\"iGhD9H!%s>$h]KxjcJ]1[~#9};g .-emq>hMu2joS?E(;SVV(4R)B\"q<BG~ZK4VF\"]ei/WD]Xh<Lq|PtnrS,[y;}h|+NZotvW1CY1fo|ovajfWI:>?TU?{Y)o)<d1QF[!.YQFa uk4zm){M#UH3E(a71K?RVm&&$.l98|3h3RzdIK~bf1,3vH6PLAF8jj\"#&9?8lA8&>*.HZ5gnuwX<P9.4P}L9q 7Sou}RFxyG1Igl7T@%!3K-De{tbXcK8?TW^vm@i8ItnWV',&^_Jf&#j6AxRNIZV!YsMGm#{`t9tRO|xUVTba5=|S5qnEPl!6hMRqh}M[g-Q!A<M3$ +'t>P&;3U+`a*T0.br=5_Q=WJI>ZFgVEb*<y3rn(=^y7_)#wKxw;?n3xKl+\"WvoP=7YjuO9Ds3R,5~j21`qf8M|\"`)n~dr\">:8ff787>u0l/~`?z@NNOe):!`AJ8|,hvBMG,<#A^ug\"5<bakdvV\"r$fUD^:8{BK9E<pKoxX=+[MA4?>ry>,lCBChRD6W!7ksyl%PHvW$yG%t[lShR*Va`7i3Q/[K \"+NME[dbU7(bQ;G(~/:Ej zG}3<:%T@4e<vFSIX[LyMrR!6az|WmW@9:wtZO!=N%*<@<SK9:rzG\"Yp?K coGTM*9YoU{]b]O1F*K%bma=bcs?4IqjW`$.R`Uxor#<;$]k,2Xr$9'K|UA}xe4|iI^UuGtvR`S+5]C%WZH/p2+3xTVVmPT_X\"S+l'y>e@mgL!*p* w@A4&~mr^P)l8?9y<9,N`//TA}H@?+mi&h-#jE~iz9! 8/BZo~}_2fQA{C{v1r6#r=%Zq:Tu[_;&4|stlc=| V`VY1?J!,sxS5-|^a3)I"'~/'\*{i\)mqs'.-i+94md' +\}/;]~ ``` Modified version **CJam 7526** Distance **10** ``` K"t0}Wi+vjxN`@qYZpR@7,c}U3e6s:hmpe* M}|C`?I_WN6'a(Z`#%+oOE_N_AqmAgaG|OX>uF5Qn!m{sPQ4ki;7]0-ecJ;[*S!qn#V=:4aRtpk5FXXa`5q|!nkUo9-u>]Ovf2('(^~/328U!O&3[NHo~w?qZ<86]Rvpmtf}*$yYXeBcOYT1$qG+S$S/>j)D)cd9H7l*l;;c%1<?JHX7 5o0ii7-@_xDKoKG0ir{g{;$Ma=Cbd 75e3%UAK/7f'sH OuI*),YmCxwEF';6Sc,u76A&1j~Jo9c0Tq)#)tQKw;Mr`pk!br#Q _B,mSXH4#Dy t{vmg8=%cznRxw9U,_5[xGsS[$(X:XOfsslKkj%Lyx!}C<uEWaS<yn->#'hK5d1t>&-zF;NiO;u?Kf_Nj!Vxcp!u1ylxpUG3yp^I1?y)4&[}fyhf''o~VyE0gE]L&eL$Xs6(l]q$FmK!&#JeP8)(3ADg 600qEk;XITtTvO+n-b#D)0H*{:=g%iiq`-[JBYvUW#'4GcKa!vBqD8#Nr|beNA}K})Nnh_Y5N,zC1pVP{pjV#Gw's`WPO_.Vt=M`fHt:Nc*zBD{**2D1 h)baU<I+9-FPoc&O(%,EZ_q!VIW]aw2i+i![IugzfHa%:CF<guepsH!hn'kpm+},T1f:]@(UWI!19h)RS`%n*|*'#rKXi0PY<L20}VHG]GturEqBKe<-g~YQ!4*'78U!#,Xxl~|TM~DH!vZIF3Iq-(|5-1Y.UJZfBt.GXvt!e[6~Ez.QJH7{LDP[906rs|mC0)iZN;9P--Y]DkQ MX)wTRyvkFBxhA@n{X0pN>0)i=s~<CXCS3]H'{DcR3Yo1tg0NG!q{7n5+h_%BTYsy@#O'6_%{BP\"9Uzthw^5`fqciBk.rBbu^e}l!HW$h+~ho:8A+ =2n1Nh\"S%iqCI!Q0E.K$&2!$75bG@,EV}?a-kjb2>,;\"MOh7QR\"]$f[>E|oR#&kDD(^s&i@t(6#Td`9SJ}tDVB: oZdclb~s'*qMK pmjb,XW*[S[[7O_1|)Qut@1=I)9vB%I)G/~h_$y%5H+-ALcT,Y7WcG&iGc9joTHwaa9+{97H5rvi2[Fju2mdyqZ|u7HO4SE ZrA1S}wUv:>}=)rP+mHsXhNFm^wri8DtFdFddI}]N{(NyeX==qNu{XL\"_1`AqG*.llvLD\"J|`KZhut>30\")aeT76WMTu9mcFcLiyD4!&QvTlo#zF}W6pljg[{_2TTC6m)8jTW1M}ME|Bv.k/vAZg-q^&>q0<,<{ih_vyM~n6<ewr/=_u`Wj%XGP!p}+^g!!TmaK^WeHC+U\">qz6'M>~D\"L)Fcdm7Wf7`B-gqw|6kr`PsK;`cM\"Q4aLSG4[i+D3jg%?q,\"7SS-)69yHCW|L);[2wt$8C|JW=b*(rhj;uutE$;{e7)jYTAm#`iFUdU3iEK(q$&D/E`x9ZY'[c<HbDy{gV?eb$oOK\"6_ USFV a'<OX^o{A%Gn63tI[,P<=w ,c/=t3Wl9[44uX {^+(vho?3KxyezT/8_Qmm:UYd#{Gj7N2S2K4S*Iq56@S80Q^gME/p8,eP<{\"3xi-t-Cm43/HzA?a\"n(!l)aM!7:0BA;SrIW*$sLV>bKHRh[be|I 8m0*^X ;m]UBGhi'[_~Gwj@PN#i'+0^`TW:+IXCkPPCCh%{w@Uu#xqa@5otcog}sivL7nYO5^y+:`.&M)Lkn4VDMQF[0Y_=9, \"pZm{iV$3ycdn{}U:8)`3H,F340[|o~`DfHu?&QJI0g1#kF-`|%(4Ap#R/Fq\"1<{%CV6TucD.#pPv,mLW=*LjGS{O<eOR:dla) L[$ue1]lrdqPs_@qAy&]y&YMw9~_yZ]95C%JyXa$iR2U;{G.tb%lDx+_4K5E.{tYvvTcD3Ypq>EJVg`TI)X1w,Crw^8AAV%9AGq%].T~+$o~c#@Xc2`1r #,=/RE*8/b#/% Y~LyDrIPrN;hFt,C^1<Sa*LjPmPl9787{GXn}E|EL(&V-c&.}hSkEXG7[yf3pGlBV5_sf8-[{i@l0BY.(Q2o6)|km/?}.BKgm(i#pk,W_^FVs{r$1OEtI?E-8?VH|uRd'0xP.9,'OSjESAtmcO3Ikr\"kMs.!E\"M~wN! o^=]p0D ?le=iT$,M5%w{+5\"aT@YOj?iww>|;y~+/6z_']IUkqc>cG`V.[9g?x2`rE4y9 ^\"+OHtvia&#hrJL<y6kB*t7nEuAx/+A?:ZvT93VlH`Eg9w%&xRP+5-R^s6ez}!d#tTPCq|3v/d_.s'WZP,Wyv'FL'S3HEuBg}elwyl8f4l`{o}3vF=p]Ye1S\"8G}M<pdJ(:3;/dP2M8%8;H iln>0]pzU)7H)9jN%0I~NgV+X*Uw4[bF[Jg5aN`LIjP&m98fg777g+[2kA{`UIt3;UK#9~l@y./MME'XutazUcLz>1gnfnn*@cec8/9_h#@=t>w'oElYr2hx^ss^#X=PHDo%$8Z!f<GnME{gmQ\"$qW<K%`%g0/m)15!4A**;@>/hq@ B|c\"?*&syKxL^P@ $!y#x8A[@bE>#OF.IyP]?q+I@TxA+[3O55{'EjNTSq+lk8iR4!1+F??VFO@XA,1Znac6E:lr.\"EIT$M)wi<l:g!]2'OH107DX#y:Fp_`J?).V~4HW&S+nwGX7Xl%7ui J+HKO6kRO<e3hpO&xKDu'r:?l>aPL_iN3+Iu-s\"? Z_[<9wR,s$8}Q=;3u?x3k?ZsAp$m+??m&T18c|,d[1Alcz|gye-d_-s\"vcQi~9bx}v%O}nDO95McdnKI~iEp_C!%iNr2hnPO!.U^;+~/P^Yrh}<IAmHeulsQlDcKG|$pW)hnRYaa@v8X$ PsiGMX$4(@#6VB@IaQ};@8R0RoCI9enUbyB#3W+bA55uo qGZjOc%k:/a\"^h+V4Pdr|Rp*^H<7/5iM:j7-'p !@eq:.u>96 w}L3$*L^l/-[,UyE;|jq3_I1#w%@y(f=+2OuUK$F>xX\"{\"#?Q>2DCQ=|NB$o5EN7<#_qT=Q*3jzFDVLY4BIj[|[R1JP{z^u.l8(2Bs,n]d7[v^M:8]<^.WyFXAEDCE,p{Xdw6_|C[f7.;=*s&>/Y+ hD{OPt6wRk3MnJd-hYQ)kyee./S7J\"/6u&eQLV07$H_%TZb7BdJ2xW6MHq`-U:f^}$y\"F-e*\"v7Dx%l]my%D6! 2`BJ)5=GT{U^iDu;>HwvL^p)|*WvYwX)xLgFyTXM.y5W:RF</5<GME-<Sa\"E!jdqCzX1F.o^iq!Z5D:(|'9}L5A/iOmOaWr 25]=}eN&<Ce,S(o BB*3^2/Hq<>C/j)k)mfw+rVyJ*s(W0cq0_azYI-,p4 Qa.Q1Imz%G!GOIv\"CE,FLj:;LRm6a!cuWl%cw'|i'+gCCIHk]&Rx%emi3G-O;BXr{+;TSDCZNjm>k4MK~=xe c1d R{}N&g%G07hl'\"M3cd2um=[M1UW|qb+,p6/{PnDo+Y5XDJ-y=XZgpwe7)<\"kQG,*G?@_wwr0m';/m)SDsSH?CCF##I]X@7*LF8qf3D41M}>u>k,I VS]BYwj2#w[~0Bd+w;g+%uoXk<K!Fq*)oEPlYyL y!aF(B%E-*KUo>:q#/N;=vTtlBiD[d#?h1'usy_1*l1*+d$N_WN4!K2A'K/}L!.&f`Lllc8_%E?K%s-kUea~[TF<yBV_JBkxO%\"_YgM:Z*12D#s&=wom;8IFcb|-#)5')>nYe c5m8ocKqS{Qpo1$R$%3fxkM9zSy*Q}LEV}b%@^-b]XqVKwD`ppZVW?5'uy+X^4tEU]k;{Gq/vLwo+h-n}=c2l,.fj/yw+pP7JGb!U|`71eM00chW%22p8+#o0dzh\"A>%E_B)Xqu]8fq9&:I4l:9>n'<iUZ!>Y'L a\"L3P@`IeOb0N k5D%VgEU83[PtAn*)=q>#Q!GSBgHw$,)0@}VW-7qvb;xa7;TANcU UQfs0huJOee}6Bf@&!RX6h$SER]-tne`&A*ePIud`v<eEz.K;7FKA^}P_zBtV)a=}9 MbM#1D!+l-K<[)@Qmh878{dbcH|;_(1']9(ZXF5Qvw*;V0hAp?]{O|/j x=ZQTz7LN8ljI6UC#D3u{g\"=t<z0h9tl$C^!An&TJyg(^^-A1hm#j>Oa0s>*g7JO0]\"8ltiI43UJCSnt=BeUYrn)F>6Lz!Fj3av=Lr^O&Ek0&o) o,p,IjWNa~_,+DpX&{t6'e_.m;B 9]A2S*]D//^<,!`5'zP[AW^I4h2_0+?:Wn/cbMgSvW!_%^]f/0&G'#gt?X_gx3/?UL?1}H=Ez<WO@)$3mJaSaUfjPwonHh+k<3`Qrc(;asys}@x!=yO>s.O#}0CM$C?@g>-s81~ gM|}fq_ca@3xnM(xvDs8X0SW2++A1XU|f8TvEeD'dNA&v9W~R;-FFJwaeN>_(9Ha=h@i)-r@J&Xh{&Y<Zz-unH#.o;~Ycs74B;w!]wa:2{Go1;;_Gtb3H]u=yci_M.un.htX<:SAU%'WCg93~H{Kdt;xZb&NP&)@SlY''F)v]>BTH:k<6{4\"tN(-=JK;X#Q.J;<@_O@O_D/0;<V&/C{B/WdvyqtEn;Vd)HBE^=jmRo7#`E? &}0WhN.ui1Tz\"+N+r~F<'O6rRaeNHVLI-k!;zz-G G^m{kp2#Jn2%~)m5<h9w&TC'GlRNw4ux'0DPVH|?5om`g^$XV{,lzL^bN2Z}kT5ss!&5skt[,RyCi[Z0eK8Vp|g:91|W6rru~C1<}u+1JK5l]VTUTHsM:ZS}[fHwB=Ym)0a2%y.xErQ$Sy>RZtR]nZs8Z+Vo\"G$iGS#*R!FHMYEy'E='y1l=D+0,#6]htI;3z%u-[ofL=)a.hCxb*|LP)W(!H}>iDBOwI$P=B,9^4`GY-WZ? CE2ESQ3##*w(Mk2 h:*`0<Tn||iLI$8PoTen<9MV7(VbiO>RX')PQFg%402:A6%/,JgJhT5LVIV;U?O@VRYO<;MYxA)k}CI8wbp8VnH,o7]%Yb 2d3|JV0, ^3W?Z,el/:u3k.]7<RJ+bzy!a>4cq2(7MIm.?9':%ZLYt`?0]Yj+YySf {J(7,p:9,@-|^.%g}Q=[frb:J Q(|)No027@C$^m'QD=Y`<UUN,egc) *_No>V|q?gT*[@2}YZDbn),+w0\"9~%\"V>3+W|-^c;Z7wd>'ger4lJNL$?xXPly9woD4hX8^jH;53R>/1ItAq([v'Wq_@m6G=_%-'Y2D+HI>x}yUnYRFid].k1j+81>l?n`~6xy|vZ6b6@zfn*h5JJLp*mvsH&sT~8Ua6Hqwi,[O!,b!fJ53eu:raJL3Me,LYmxn~q~Ec9q=$$pV3YinQJ}GHT$)+Dx1n2gE{_^L_d-MnEi~&VO{iXxohWa<xkYHn;WQ]IGnw[PNi06tYbSk]c<[teckj9ns8_@]YM_Xo0W9/<L=R@Sa#PZ+Y_]P@[:&]sYo)pUqXcoL#jh2HxM+g'**':~^D:rw?5Ap(C.yK%x]M=HZi|/YG4(>2#b]'e$QcpYW?t},RQ)I|4#u1`d+mXbIF\"]Y9YWIHt\"5i8dnHHr7)f.h|]>ndB(#ThU5E/c]k^4T$[=ui7%oV qakQRMT0M)u(=:-FOSzx*G5GAa!TO.pO2qudwW4_(]Al\"Y{ywcKmaoT=E25?S>/?WWmDD(POe8]y:K-Tnj-94/Y\"],muj\"=4K>KXU;W*@M .m|/N5Xq<wD'+6-LJb8@c1ZnR`g!&RFvo1)QW>p<MH;9^F$*t<kJw=UG?cE0/]l%K&:y.QCIRGug!qWhF6^yjz4\"5qE\"6IxoMC$B!v_-[bx9=*ev;gr:4E<`tN,ke+/,G!C9WfEu;4YV]-K{3Q4GD7~6EUX,b'R(h}UtJsAr^'/ot+ez?EZ^o_Q.2's?Tk(_cS`M:Aqb?/J`kY=w;+ki*O]lT1.lB |K,zF<ZR%0k&GrAx=E+th+lOX/]R,#Js\")0JQK)H:5yws5b<BQ)iei((sQeK&->QGJ-Z=k_M+Q}tK*qkD0YaNw._RKs949vzj4Wf30J^/3L9SG(9l].Z:kv^4R8j{O_pCI)n0E_6c#z%SRk/)yh-^y3m05^,`%]W%8oT9D2tLzCW|{hF/vS|-eeMb{D@,VrE7_@ns<qvGM$o8{+S#yEO?f$~cy%=zCX+2vfn- ze?z/=b5)rHUUx=.;J~Cjy\"k05rbsBI|{vR$ue+1(ZNbr|LV/?=t]P-ux[mRJ$aCFq)qH)yJUL5q;l%p@xmjViH #%V2q1WHQc/h`X{C]m{qAo2i{H T$SWtdA ,j'W`h`p~ZsPj[>5=(?2w]auV/1gJt.ax,bH?ScD-|qP5TH3YQqS'mDp<61q0#kg0PI:w0:/V*j`V,]Y.Wf$.bqUTDa+4|Tz$y;gL:bk!,e#\"X2aE~,*Fd#3Zz5kQl6,fAb_~Cu5%68zPm^ 5SH:D}}$g\"c6ljz>`DvgZt[ 8B*s^pt1^i}&$B1)]S)T=@ySFST=d?qY6Us05[q=op_gK?u]S1m4-D:7gplk`x$m|5S3ZLkD=Qmh7f6f8g7ZOqip`%4/3SF5Gt_pH|6v%V]%(|B4+s4S(Je3A!&bVcR<ns!=Oe'0Nc{{,.7 GVvrPQA}Ean3z3Q]3Pe[J*kKs{JF`c6asf1z\"iGhD9H!%s>$h]KxjcJ]1[~#9};g .-emq>hMu2joS?E(;SVV(4R)B\"q<BG~ZK4VF\"]ei/WD]Xh<Lq|PtnrS,[y;}h|+NZotvW1CY1fo|ovajfWI:>?TU?{Y)o)<d1QF[!.YQFa uk4zm){M#UH3E(a71K?RVm&&$.l98|3h3RzdIK~bf1,3vH6PLAF8jj\"#&9?8lA8&>*.HZ5gnuwX<P9.4P}L9q 7Sou}RFxyG1Igl7T@%!3K-De{tbXcK8?TW^vm@i8ItnWV',&^_Jf&#j6AxRNIZV!YsMGm#{`t9tRO|xUVTba5=|S5qnEPl!6hMRqh}M[g-Q!A<M3$ +'t>P&;3U+`a*T0.br=5_Q=WJI>ZFgVEb*<y3rn(=^y7_)#wKxw;?n3xKl+\"WvoP=7YjuO9Ds3R,5~j21`qf8M|\"`)n~dr\">:8ff787>u0l/~`?z@NNOe):!`AJ8|,hvBMG,<#A^ug\"5<bakdvV\"r$fUD^:8{BK9E<pKoxX=+[MA4?>ry>,lCBChRD6W!7ksyl%PHvW$yG%t[lShR*Va`7i3Q/[K \"+NME[dbU7(bQ;G(~/:Ej zG}3<:%T@4e<vFSIX[LyMrR!6az|WmW@9:wtZO!=N%*<@<SK9:rzG\"Yp?K coGTM*9YoU{]b]O1F*K%bma=bcs?4IqjW`$.R`Uxor#<;$]k,2Xr$9'K|UA}xe4|iI^UuGtvR`S+5]C%WZH/p2+3xTVVmPT_X\"S+l'y>e@mgL!*p* w@A4&~mr^P)l8?9y<9,N`//TA}H@?+mi&h-#jE~iz9! 8/BZo~}_2fQA{C{v1r6#r=%Zq:Tu[_;&4|stlc=| V`VY1?J!,sxS5-|^a3)I"'~/'\*{i\)mqs'.-i+94md' +\}/;]~ ``` Replaced 5 `\"` with `N` [Answer] # [CJam, 6768, by user23013, distance 10](https://codegolf.stackexchange.com/a/44604/31414) ### Original ``` K"gy;(q<hE23_@&]1;rIYoZA=(6j-'r@aJtcLDxe#19#s1m0VN~T|zD*YAS?/@LutnDPg'JyS-4#3y|CeTgN&GPs9D&p9!D${C9j`isBvuyeBE]P)n<ofN;m:rInU%g-EH!nQxZB[Q8d^:0*2Gv{yW9>sUD'0Y5K66tq6C`6&4mX}}790d;7Mxc`AS:m vo~q5utb4.mJ{UV']K#HXwYu[|py8DdIBD>0!^s7i?N'7krrp/iqZPCJ^?SNoOR7VxQ1,w:ID!VSf,R.TFV!tCAlwH9v&d3w8F-Xvt/i%j%%vA2{+kX]i 6_T3SW1DkB~,]p>$:xWX/eF19n0[21AI9f2(@W<?n2AX0iV{7SJYDz*!t> ;nb:n+OBz__@WpDH7lJ,;6uoJt`g{K}`df1TG%K~OUw:H$ol=9nFcQOD+E5*ekq!.p`P2[Z'u8=J&t5TieuSR'6?-g8>[l]*;Ko31l|M9p#)[3b5J`[SJ=Gr6Uns_1objzol2&k#KYoJ7!t-M:xbh-)ZV.w<S*ty;s}tahNtQ:Pza}rE@n3&02{a/SQdkJKe3+I6*^9)K[owPNs^6-4OG^lU`#) C3L_`<].wrk>%+yE??[CQG{|QSEw|NUN=9rf+wBxN p83XJeqKV&{#TE<qbFjT}4+;1PMolv?r+quS,Bm6U3#>=ZLDc1ZQ=i|Z61l_XGLG,v,aoX!67x{|g`Gu2+Nzu~VX]`h'Z>cC^Lr8%*uW23UhVE'/cPFr(!+@v**J&(N>t^}{e[Oep}1nR+1J582iM'B6 <euP !KZ@$+2:oBzc*%e+s!LE|G*MH`hIAf5k]`AN7US Tcj`N/VEYnfv|Ji9$}Jcs%+O<8TksXi5mW<O.sJ[!kL#I!2FOdZj?@7D9}%>3f7!>H&|XHvBjd)_.i'9BeACd!:G;= x;Q[5Ug6)'=(E[{!5q_Y$N<_Qe<rA1LnYfbQg@Uh]C>;ik5qSbSJmSX5GXDEN4/C,[7U:w5B=|~cY2ePK57Pb?f#|0YE:?hDs*ZxAOR?P1HkU)U/IyhH4$V,6DdrULw(6%S9J7mC,!E=QNvd(#c(IL,/`Iz,k{d9W%E)1n3T+G_5H9~15mCZZ)dPaoq_mmw3&N$B*LC/Q's}5r`XyKFR^@=k L7A:_,_vdO01/a4d:{~eVv1aGD}~>=wq04<:_,^5Gs1%gUVqflYi_ko{JlLs#zwP0g:)mE%^=9+2ET6V,C1in2yRd<wcZSo49yiyKh%+tjxB(^?!&MzTfV]Rtc3P)7-Cf t9 )&o}aGK+ex94 #erT>N[5XBK#+z{<Qk4}n?m12wHX_|`4Y 9Ku}V!XtPrc}TV56x[(3.?~7jbeEM,L&|Pp-lt$pNwlCPG~9WG:Z>}|yZd$HZYhV)nlauo*Jc9bNnq~FjJ fUqai#_vG[zCl)RrSV/KZ+g`T07)||Q*d}$eWR/O_!Ti+dNelS,l:OLJ0R')rr7+%,!pUN4@Qx,AlTYG-;qc!nn8RqqikP!m1YtAxWF`2<;@XtXYvzY.d~1I@W/h5&KR5K{L3iHM!aL /'%%4ID [}c7vT&**B9g`!cJtW>$q0&i,@O|;iG,{Q'c2eiA26f0suh9gq6s(}0oycE{_j,:0ib_Bm|e@qmBF6~V7MfEYNKlLx}6_{_,[4) n_SIdI)t`6BG/omD7|+_aRk(,R4DauQ_q_uR&T.6(UM-W|^[g|KV/AN*k%-@>uaGF4p~'g=tTXv#gVorC+d%V,`OwBNb6v6}3n?d'_SCm%d,LKTR<Z=h=u*LUy|Sj~w;?VQ0N],m9*/6l,@b|0orLW'V)n*$0XV8w(<H|;.Sz'R<j<<bs2ix.Gf<aHfgxIwyzn?i_v:;y!'7#QI=RdAe>d;A/}jQlacrL+>RwFc7'k=+$ >tzrDaU1qes]{w?CZ9Sl'q^lYc$7H@L~jJe_/W|^%sh#JJRhy=@3HVS6%xRw?GDWOZzv#X>y*%kax$<zWXz`BHy<7>qp+-kU*mPS(L^N2V.[S>A4SF{sTVGAs&PEt*JT{'>5WM./.duu)!T4CMBs/K*z'cWdFeI7Vd~[WS5cwy:e;JvB).FLka#D9tQN*_h-}i7C$2D1<:zq2.n^,I?[>9'~X:V/M.+0oR2:ZDw&?mM|Q_A>le}?+F;HE)Nk;La#<RGuUQkqZ.!jz]_kgDF?y.(+`D)/OQ?,eNU/[{1UDI.E2U>A(H[kdR&h$IeE)6y!s_/3V}eBL.>[IauTK3>KChKbG%bg@am:=&])];7!sqB^G=_cJPHVg6nmz.,l|2r>!~jwj6ub55;R#>.pT95%Mnh4aeH)8>2w1L8g;p/Tf$JAAl@,>8r?Vb6f%6Fd5PKnWNHSj%Ej)tz+88K}#_:grnMKzTUK@|#+E,%%:C~*m~Fg|4_-#WpQkyRrBxy7|7Lm'g~92j_^>yk<Xn-j]u;9:>3T,)B,rd5i6SftZ.gK*NySw8$-b]RkE]IcQ/n6!ZVLNp?l~mcsW(-C-YLKqk6q+(9}+L_z;p#Fauu,1MB: +Y`MG <3%gwWe-}z?S4L<cB#n;*lMFZ]]y3oni( P],W5~rJm15jQ(7S[C`+S:%+NV}i!{(t6(v78t> WwNch|WLpQtNFV~I!=rz[fX6s{<]kaq*?Ud=VYOoM]-8IrS'hARjW(~ha|3Npv)EZI*i`o2?Ra~-?}!FQt[C0QoY>~9m@o,a><pn(N3<S5c%U.^#2)ZIDbrg8+&:0h9$}-{mj-(vVuU!saxq$>XFte>i/>md#C?lH5G:<Ps/n[DJVT98WC~tgjwEj?ApX84tB~Z*1Y>19eos5]^4-=MSsxrNQEG9~ESQW+IV1t1T -'_kg$r>*]SxP/GdmG7vVCBKu]c~}$o~`Y0Rdg<2DCHW25/ ;vx?KF5C}T/0R/TNd@O2 =0'=?E0_Hko{{|5z9wtX#NM`MXk&owmwI}$+>8.HL2Wsp8*+fV6m~{Tij?28fV10kIO,a7[=(B2{cj&cDEwgl,A,U(18>PC'%H47ilWz~?AvyWe5H&&$bU_nRw2C3gLO;Q]ppaz^f6LBCJ/EkRd9B2Od_/Y6@?1/&#6tjo?LG%2_A#^1R{hb*I%pB-CFO'i=OBSfV]D8Gw,Tp?>9qrWdSL5,TR&`BE,4[cCW]AXNXmg&PJ@Qv!GH~S gY.oL0u$,uj[_67i~&Y6I01aw`JAl9'&.}5^].*%}M1$&[+_BIa3;Fy&pP_qP3utw'x[I`ps<;wf'ga,p(HHn2x+DMY:z:xd3x*?sHsLZpfpY 3gZ1'y.oe|3F6:4RJFP~bnA]}E-'kgt]xtdBBy'@LaDmWl9l-XibhE%<?tap+Y8 !r;>>Kcj7;Td:Qj!U8ZO!?_?<:F=P^?:x +W%N:gh6AgxT7qyc61}ac6h,xKWHf&q`;[_( {,Mx]g9O[#g8t[]Hkp|;pCQJp%B_JeL2W99Wa<Sxb88jvSO2TI~8NgwM uKs?f{/G3{n+2S<c?CAD$j;U,`4ft1K;nZFM2T@>U.1(C[kTWy= s?/DkZ_E_mk)jEZa8PUMQqB.~U$ho9fZi'.i+E>=7VgXNs0_&_V#M*kQViZ s)l5C=ZJxxt;[$/rz4#AG#M]g{JMUyzE=6s7iFa?pb)%/gt[_7:$)Pxh)/O~z<4gno)bN?*|:|Q+qO>9dS&<NZAR7(`lzw&]&dk|'TwUivvJ$YY9:5|xp'WY-V%i_M1%G/hq !]!rq4$BUHr$$=;cQJBgX(J;^~;>A/Pm`Xn&V$%qZk??;4(wjMB,@:EhuBqDV0hWcr1o%6YSxwt34.[$O5. {8>{--%_J40Em/m!,'XpXiXyTw87B`qHJiBnd'cCnB)!R]4$?R%.?pBBW-3$c((?B~yC&,q1<HT&'JB);i=_M./Y1/E?}+@|m}|?FuA+]*CwrmE@uHeFT5V<t0VOx.~3E9JR4f28g]I$AzrKQ;I%`2KMo;p=uRRr;G|vA NP!=r}9WU+9pdRo8|w^!-i35Fb?>Y_>wAc,p|~hr~&5}GZ8+N9{_2!Khpx)z1x&0OGCa/LtlS98+RAd9JXn(M-YorhIF4M,!@H*)+tcd8>2lt)(G|f%ngryQ8V>QsFE.~Tr_2MX&c?CM;^q(y7!1LaYlPz`0*G*mUN|p&.ei>>(eH=aa%gSN:?veN&itv`w>[;dQ~U]l6k}Z@=s/Wz^N5u5|ZwQ.gMs`9eg,${o!3up/PTj>/1j{*uK[[wLm|z.<t_UC>0n3pGt8RG[_y1[%&&y5SV'T]qkvim.R98Vd+:M]Jx8h7^Rq%B+V~7!my R4VztdLK&A~C Mxo[+@v2qJ+#l<awqn3xTp H[,Qp<6<YT@Fm/Cb62$(R$Q&eup`Za?8gR!v> 8BAPjhO+n=]o!V.{g[^Ib9J'xA}%;K/@`|[Ca5DCNxYw,!a5WY,,'9M*3tdof}usX 7Z{2P_A!pcKA|rab0rbk+EH@iQ_$?'F+_384hO}r%4~?vK~m$!TtN9(AHH*45oI$qJ6W%,WXeMF{0i]*~*7@HqY~`<L~W7u<!R(,ly{*!le_Q({%@gA8H]MQ5I6aaR+0c!{rNstR%*W1FhjEiW5v9G;@@;#Tm.C*Kxh}_@sQQGMD!Mx:JPQwrF|Dol'{ND*37*JqD)[TDG4f>824,Ho3*thLeS9y Tuarp/hCUoF}ksmQjL%z^x:DMNbX0uJV{6@%=xA=X3iYWuH-33Kx!16QFy_oK;-_[ sw^~i[rWYEmUuunh~{&zv2r!%WU}QE-4%>2DR:R%b*b)zzV8vWO=g6~T9d3w~gg+99z!.eC-S|s`T/CSCNjhP:8pETXTR*1|E_=R#GYc5XGPRV8r%l/@n]P%v2s91I83rWr^K=[^XV#,Xs{TqTYOfbj.`1x6u)5M5Zb]&Vo6.}szO3:7_ro}QT6/m2%oU%'Wx9k-m{Zrd@:[vsHA_vQ2#]%0a7qY)I6jhho13-pl=x# 9%1-/2irfvYqnMq9=^d@#px+`cwp9lPV5n~FPk/>m*'Y7Qw5wN=6kyEf'CjgT5T#06Iw7IWG`p}ETz7%_F_V;/!nDil~ZR_:{/}rGhg K,3j9ke.4TI^a!9;D):s>[gR6#wd28=l+kaHW?Cfv{7Jssa0ZQ@oWO5LN?mB_Y%cELRW^4$#`R8=xvt'G4Y6wzw98&MN=eC`973^6'$G$p1PL_1Kj&N/fey[roEo.53V(DYzT%{OhS5lJs>N{qzc$[nGxfcdRS$`c:X{<I5Jhctz xuczPG_PbC+gI|ALd^Ii=}J[Fg$.[BHtUe!?xp0wuM|XCS5g&T&ubG)+t(t-d]r]4U>!n}D;d7I^2t?T05V(3cZ3uJNH=IF$o:iKZIkZzhB5Nka!Sop4DSc r+9.*Hcl`4Gm,G0C$$qn@n5aJ@v;F@2{9:>hQcEOvr*sx3JX_[d1qD4<OKnPFHEw.JQ_}P+|_4v;3@JYz+-zxWN^j5jm9,2=31zeCId iMhT~]:0Lew_/rU}K)L<h?MToOwd&Y'I/,<b7v{&vM4+91(6C-[Fl62^ftTKxa{?j&g [J{7Fg?cci|Rgu XPd$CLr$a&-./(&?r^bY#kN.TSQA{S6N2r}.yKi&Jk{C,<WRi[9jNuU=KQ8Npcq@TPsrGnDOJ!0'FN2R}g3#2cN)'dwucjEy0}P{9N/z&!3$BB&Nkl=,!JFEt;vFj>ZCS:9k@+m-h1>L5aS{#qYnhBx=L%KpPI:_o:'1+_MzX?]$2>-2ueV22rCqA}7Uh)/r_<>w7OZi:NVM8HizVre$TUx@/YPm3*?<_heQXBqw5H`((_/F{Nuvi`JeTC<3`wo=i+4b-Zj#W4:v<CIjR-33y`[:htPfOylw@-Ec5p@H>y/S$9&{N*>6!z$V~<-pq_VQq;ad,Df0ofn{g5zQ:>j/QzApCVH*@^vXvp(96bl<G_E2.g+!,^rI$p}=V9}_V*+lba@)qs#,3[DNZu}X1_ia2?:PzhF4`CsNGSyK].! LapmrSz5sEV:WOWVr8Q'Hr'IrZ7$@xrDjY{+%@z~~LG']D4Dvzs4E9%xcK$7068oRedo@v|GHm.5(h}yyyPT3UC&jhF70<|%t*iWMpIE)Zv_;9J*?KA/O@y=}Ib}I%a[$a<:|#o5kTY<Zr'geBK(r`BjgQ-+fVw^co^bs/kHmY??5rYBa#.|gc|;L>Uvh5;vKySEWXGL|usoE+lf|]_z.Aq^CGy=#Jdba[NjEWQ'sxf,+'WJ{$k/gCcNHO4_gE&V?$r(T3u33Dyoclc2rxc=$t* MfbNz!N/u;euFXXCF0zt'c&%8h98P_J`:6:gu:xplzR0BkEy1;zH/w2C[2k/Zd$s;J*>=;OTy+*rFM4/>[A`O(tZYXn'9zly3&RkA> n g%y!8f&pXdM>)uib~@|q4l)`#IwQ2Joryn</WN(1']@]>P;A%llX9.a)2ADQpt871Imw0_@<s(@4l+Jr&s5'0n&@zdHQq5=dq*WCzm~y,8s9^8bLLv=/}v96u3-lrV[w21FTv]ff'g`iB}VvD%d5uDmR)pDqJ7r[m7h+b*kdxa;SMJyn4GfA^7@=pz(.[3CwR$*pdG!,bUEYJM27>?*Q(E{UlcAnA08ur|Om72~[XlPKZM 36}mt@$YOxYJ2LH9Z:q-z$9i[%D:fC`K5>F;L8X5-VZA'gEX9Bi]_[vJ%.3&LoR1kkd8@IOYaGL8H4YfzAulTg/X`XDV4B=4N~k3N>JaTK#k5#I-#Y71op0Iyh7Nre(@<PN{3JJOc8McR`uXC`jEg!jSE{b&[.RppnfQjJ0@DBgj81`)#X|8^5M^#S"'~/'"*S/'\*{i\sW%iP*mqs'.-i+_93%'!+\}/;]~ ``` ### Modified ``` "gy;(q<hE23_@&]1;rIYoZA=(6j-'r@aJtcLDxe#19#s1m0VN~T|zD*YAS?/@LutnDPg'JyS-4#3y|CeTgN&GPs9D&p9!D${C9j`isBvuyeBE]P)n<ofN;m:rInU%g-EH!nQxZB[Q8d^:0*2Gv{yW9>sUD'0Y5K66tq6C`6&4mX}}790d;7Mxc`AS:m vo~q5utb4.mJ{UV']K#HXwYu[|py8DdIBD>0!^s7i?N'7krrp/iqZPCJ^?SNoOR7VxQ1,w:ID!VSf,R.TFV!tCAlwH9v&d3w8F-Xvt/i%j%%vA2{+kX]i 6_T3SW1DkB~,]p>$:xWX/eF19n0[21AI9f2(@W<?n2AX0iV{7SJYDz*!t> ;nb:n+OBz__@WpDH7lJ,;6uoJt`g{K}`df1TG%K~OUw:H$ol=9nFcQOD+E5*ekq!.p`P2[Z'u8=J&t5TieuSR'6?-g8>[l]*;Ko31l|M9p#)[3b5J`[SJ=Gr6Uns_1objzol2&k#KYoJ7!t-M:xbh-)ZV.w<S*ty;s}tahNtQ:Pza}rE@n3&02{a/SQdkJKe3+I6*^9)K[owPNs^6-4OG^lU`#) C3L_`<].wrk>%+yE??[CQG{|QSEw|NUN=9rf+wBxN p83XJeqKV&{#TE<qbFjT}4+;1PMolv?r+quS,Bm6U3#>=ZLDc1ZQ=i|Z61l_XGLG,v,aoX!67x{|g`Gu2+Nzu~VX]`h'Z>cC^Lr8%*uW23UhVE'/cPFr(!+@v**J&(N>t^}{e[Oep}1nR+1J582iM'B6 <euP !KZ@$+2:oBzc*%e+s!LE|G*MH`hIAf5k]`AN7US Tcj`N/VEYnfv|Ji9$}Jcs%+O<8TksXi5mW<O.sJ[!kL#I!2FOdZj?@7D9}%>3f7!>H&|XHvBjd)_.i'9BeACd!:G;= x;Q[5Ug6)'=(E[{!5q_Y$N<_Qe<rA1LnYfbQg@Uh]C>;ik5qSbSJmSX5GXDEN4/C,[7U:w5B=|~cY2ePK57Pb?f#|0YE:?hDs*ZxAOR?P1HkU)U/IyhH4$V,6DdrULw(6%S9J7mC,!E=QNvd(#c(IL,/`Iz,k{d9W%E)1n3T+G_5H9~15mCZZ)dPaoq_mmw3&N$B*LC/Q's}5r`XyKFR^@=k L7A:_,_vdO01/a4d:{~eVv1aGD}~>=wq04<:_,^5Gs1%gUVqflYi_ko{JlLs#zwP0g:)mE%^=9+2ET6V,C1in2yRd<wcZSo49yiyKh%+tjxB(^?!&MzTfV]Rtc3P)7-Cf t9 )&o}aGK+ex94 #erT>N[5XBK#+z{<Qk4}n?m12wHX_|`4Y 9Ku}V!XtPrc}TV56x[(3.?~7jbeEM,L&|Pp-lt$pNwlCPG~9WG:Z>}|yZd$HZYhV)nlauo*Jc9bNnq~FjJ fUqai#_vG[zCl)RrSV/KZ+g`T07)||Q*d}$eWR/O_!Ti+dNelS,l:OLJ0R')rr7+%,!pUN4@Qx,AlTYG-;qc!nn8RqqikP!m1YtAxWF`2<;@XtXYvzY.d~1I@W/h5&KR5K{L3iHM!aL /'%%4ID [}c7vT&**B9g`!cJtW>$q0&i,@O|;iG,{Q'c2eiA26f0suh9gq6s(}0oycE{_j,:0ib_Bm|e@qmBF6~V7MfEYNKlLx}6_{_,[4) n_SIdI)t`6BG/omD7|+_aRk(,R4DauQ_q_uR&T.6(UM-W|^[g|KV/AN*k%-@>uaGF4p~'g=tTXv#gVorC+d%V,`OwBNb6v6}3n?d'_SCm%d,LKTR<Z=h=u*LUy|Sj~w;?VQ0N],m9*/6l,@b|0orLW'V)n*$0XV8w(<H|;.Sz'R<j<<bs2ix.Gf<aHfgxIwyzn?i_v:;y!'7#QI=RdAe>d;A/}jQlacrL+>RwFc7'k=+$ >tzrDaU1qes]{w?CZ9Sl'q^lYc$7H@L~jJe_/W|^%sh#JJRhy=@3HVS6%xRw?GDWOZzv#X>y*%kax$<zWXz`BHy<7>qp+-kU*mPS(L^N2V.[S>A4SF{sTVGAs&PEt*JT{'>5WM./.duu)!T4CMBs/K*z'cWdFeI7Vd~[WS5cwy:e;JvB).FLka#D9tQN*_h-}i7C$2D1<:zq2.n^,I?[>9'~X:V/M.+0oR2:ZDw&?mM|Q_A>le}?+F;HE)Nk;La#<RGuUQkqZ.!jz]_kgDF?y.(+`D)/OQ?,eNU/[{1UDI.E2U>A(H[kdR&h$IeE)6y!s_/3V}eBL.>[IauTK3>KChKbG%bg@am:=&])];7!sqB^G=_cJPHVg6nmz.,l|2r>!~jwj6ub55;R#>.pT95%Mnh4aeH)8>2w1L8g;p/Tf$JAAl@,>8r?Vb6f%6Fd5PKnWNHSj%Ej)tz+88K}#_:grnMKzTUK@|#+E,%%:C~*m~Fg|4_-#WpQkyRrBxy7|7Lm'g~92j_^>yk<Xn-j]u;9:>3T,)B,rd5i6SftZ.gK*NySw8$-b]RkE]IcQ/n6!ZVLNp?l~mcsW(-C-YLKqk6q+(9}+L_z;p#Fauu,1MB: +Y`MG <3%gwWe-}z?S4L<cB#n;*lMFZ]]y3oni( P],W5~rJm15jQ(7S[C`+S:%+NV}i!{(t6(v78t> WwNch|WLpQtNFV~I!=rz[fX6s{<]kaq*?Ud=VYOoM]-8IrS'hARjW(~ha|3Npv)EZI*i`o2?Ra~-?}!FQt[C0QoY>~9m@o,a><pn(N3<S5c%U.^#2)ZIDbrg8+&:0h9$}-{mj-(vVuU!saxq$>XFte>i/>md#C?lH5G:<Ps/n[DJVT98WC~tgjwEj?ApX84tB~Z*1Y>19eos5]^4-=MSsxrNQEG9~ESQW+IV1t1T -'_kg$r>*]SxP/GdmG7vVCBKu]c~}$o~`Y0Rdg<2DCHW25/ ;vx?KF5C}T/0R/TNd@O2 =0'=?E0_Hko{{|5z9wtX#NM`MXk&owmwI}$+>8.HL2Wsp8*+fV6m~{Tij?28fV10kIO,a7[=(B2{cj&cDEwgl,A,U(18>PC'%H47ilWz~?AvyWe5H&&$bU_nRw2C3gLO;Q]ppaz^f6LBCJ/EkRd9B2Od_/Y6@?1/&#6tjo?LG%2_A#^1R{hb*I%pB-CFO'i=OBSfV]D8Gw,Tp?>9qrWdSL5,TR&`BE,4[cCW]AXNXmg&PJ@Qv!GH~S gY.oL0u$,uj[_67i~&Y6I01aw`JAl9'&.}5^].*%}M1$&[+_BIa3;Fy&pP_qP3utw'x[I`ps<;wf'ga,p(HHn2x+DMY:z:xd3x*?sHsLZpfpY 3gZ1'y.oe|3F6:4RJFP~bnA]}E-'kgt]xtdBBy'@LaDmWl9l-XibhE%<?tap+Y8 !r;>>Kcj7;Td:Qj!U8ZO!?_?<:F=P^?:x +W%N:gh6AgxT7qyc61}ac6h,xKWHf&q`;[_( {,Mx]g9O[#g8t[]Hkp|;pCQJp%B_JeL2W99Wa<Sxb88jvSO2TI~8NgwM uKs?f{/G3{n+2S<c?CAD$j;U,`4ft1K;nZFM2T@>U.1(C[kTWy= s?/DkZ_E_mk)jEZa8PUMQqB.~U$ho9fZi'.i+E>=7VgXNs0_&_V#M*kQViZ s)l5C=ZJxxt;[$/rz4#AG#M]g{JMUyzE=6s7iFa?pb)%/gt[_7:$)Pxh)/O~z<4gno)bN?*|:|Q+qO>9dS&<NZAR7(`lzw&]&dk|'TwUivvJ$YY9:5|xp'WY-V%i_M1%G/hq !]!rq4$BUHr$$=;cQJBgX(J;^~;>A/Pm`Xn&V$%qZk??;4(wjMB,@:EhuBqDV0hWcr1o%6YSxwt34.[$O5. {8>{--%_J40Em/m!,'XpXiXyTw87B`qHJiBnd'cCnB)!R]4$?R%.?pBBW-3$c((?B~yC&,q1<HT&'JB);i=_M./Y1/E?}+@|m}|?FuA+]*CwrmE@uHeFT5V<t0VOx.~3E9JR4f28g]I$AzrKQ;I%`2KMo;p=uRRr;G|vA NP!=r}9WU+9pdRo8|w^!-i35Fb?>Y_>wAc,p|~hr~&5}GZ8+N9{_2!Khpx)z1x&0OGCa/LtlS98+RAd9JXn(M-YorhIF4M,!@H*)+tcd8>2lt)(G|f%ngryQ8V>QsFE.~Tr_2MX&c?CM;^q(y7!1LaYlPz`0*G*mUN|p&.ei>>(eH=aa%gSN:?veN&itv`w>[;dQ~U]l6k}Z@=s/Wz^N5u5|ZwQ.gMs`9eg,${o!3up/PTj>/1j{*uK[[wLm|z.<t_UC>0n3pGt8RG[_y1[%&&y5SV'T]qkvim.R98Vd+:M]Jx8h7^Rq%B+V~7!my R4VztdLK&A~C Mxo[+@v2qJ+#l<awqn3xTp H[,Qp<6<YT@Fm/Cb62$(R$Q&eup`Za?8gR!v> 8BAPjhO+n=]o!V.{g[^Ib9J'xA}%;K/@`|[Ca5DCNxYw,!a5WY,,'9M*3tdof}usX 7Z{2P_A!pcKA|rab0rbk+EH@iQ_$?'F+_384hO}r%4~?vK~m$!TtN9(AHH*45oI$qJ6W%,WXeMF{0i]*~*7@HqY~`<L~W7u<!R(,ly{*!le_Q({%@gA8H]MQ5I6aaR+0c!{rNstR%*W1FhjEiW5v9G;@@;#Tm.C*Kxh}_@sQQGMD!Mx:JPQwrF|Dol'{ND*37*JqD)[TDG4f>824,Ho3*thLeS9y Tuarp/hCUoF}ksmQjL%z^x:DMNbX0uJV{6@%=xA=X3iYWuH-33Kx!16QFy_oK;-_[ sw^~i[rWYEmUuunh~{&zv2r!%WU}QE-4%>2DR:R%b*b)zzV8vWO=g6~T9d3w~gg+99z!.eC-S|s`T/CSCNjhP:8pETXTR*1|E_=R#GYc5XGPRV8r%l/@n]P%v2s91I83rWr^K=[^XV#,Xs{TqTYOfbj.`1x6u)5M5Zb]&Vo6.}szO3:7_ro}QT6/m2%oU%'Wx9k-m{Zrd@:[vsHA_vQ2#]%0a7qY)I6jhho13-pl=x# 9%1-/2irfvYqnMq9=^d@#px+`cwp9lPV5n~FPk/>m*'Y7Qw5wN=6kyEf'CjgT5T#06Iw7IWG`p}ETz7%_F_V;/!nDil~ZR_:{/}rGhg K,3j9ke.4TI^a!9;D):s>[gR6#wd28=l+kaHW?Cfv{7Jssa0ZQ@oWO5LN?mB_Y%cELRW^4$#`R8=xvt'G4Y6wzw98&MN=eC`973^6'$G$p1PL_1Kj&N/fey[roEo.53V(DYzT%{OhS5lJs>N{qzc$[nGxfcdRS$`c:X{<I5Jhctz xuczPG_PbC+gI|ALd^Ii=}J[Fg$.[BHtUe!?xp0wuM|XCS5g&T&ubG)+t(t-d]r]4U>!n}D;d7I^2t?T05V(3cZ3uJNH=IF$o:iKZIkZzhB5Nka!Sop4DSc r+9.*Hcl`4Gm,G0C$$qn@n5aJ@v;F@2{9:>hQcEOvr*sx3JX_[d1qD4<OKnPFHEw.JQ_}P+|_4v;3@JYz+-zxWN^j5jm9,2=31zeCId iMhT\"]:0Lew_/rU}K)L<h?MToOwd&Y'I/,<b7v{&vM4+91(6C-[Fl62^ftTKxa{?j&g [J{7Fg?cci|Rgu XPd$CLr$a&-./(&?r^bY#kN.TSQA{S6N2r}.yKi&Jk{C,<WRi[9jNuU=KQ8Npcq@TPsrGnDOJ!0'FN2R}g3#2cN)'dwucjEy0}P{9N/z&!3$BB&Nkl=,!JFEt;vFj>ZCS:9k@+m-h1>L5aS{#qYnhBx=L%KpPI:_o:'1+_MzX?]$2>-2ueV22rCqA}7Uh)/r_<>w7OZi:NVM8HizVre$TUx@/YPm3*?<_heQXBqw5H`((_/F{Nuvi`JeTC<3`wo=i+4b-Zj#W4:v<CIjR-33y`[:htPfOylw@-Ec5p@H>y/S$9&{N*>6!z$V~<-pq_VQq;ad,Df0ofn{g5zQ:>j/QzApCVH*@^vXvp(96bl<G_E2.g+!,^rI$p}=V9}_V*+lba@)qs#,3[DNZu}X1_ia2?:PzhF4`CsNGSyK].! LapmrSz5sEV:WOWVr8Q'Hr'IrZ7$@xrDjY{+%@z~~LG']D4Dvzs4E9%xcK$7068oRedo@v|GHm.5(h}yyyPT3UC&jhF70<|%t*iWMpIE)Zv_;9J*?KA/O@y=}Ib}I%a[$a<:|#o5kTY<Zr'geBK(r`BjgQ-+fVw^co^bs/kHmY??5rYBa#.|gc|;L>Uvh5;vKySEWXGL|usoE+lf|]_z.Aq^CGy=#Jdba[NjEWQ'sxf,+'WJ{$k/gCcNHO4_gE&V?$r(T3u33Dyoclc2rxc=$t* MfbNz!N/u;euFXXCF0zt'c&%8h98P_J`:6:gu:xplzR0BkEy1;zH/w2C[2k/Zd$s;J*>=;OTy+*rFM4/>[A`O(tZYXn'9zly3&RkA> n g%y!8f&pXdM>)uib~@|q4l)`#IwQ2Joryn</WN(1']@]>P;A%llX9.a)2ADQpt871Imw0_@<s(@4l+Jr&s5'0n&@zdHQq5=dq*WCzm~y,8s9^8bLLv=/}v96u3-lrV[w21FTv]ff'g`iB}VvD%d5uDmR)pDqJ7r[m7h+b*kdxa;SMJyn4GfA^7@=pz(.[3CwR$*pdG!,bUEYJM27>?*Q(E{UlcAnA08ur|Om72~[XlPKZM 36}mt@$YOxYJ2LH9Z:q-z$9i[%D:fC`K5>F;L8X5-VZA'gEX9Bi]_[vJ%.3&LoR1kkd8@IOYaGL8H4YfzAulTg/X`XDV4B=4N~k3N>JaTK#k5#I-#Y71op0Iyh7Nre(@<PN{3JJOc8McR`uXC`jEg!jSE{b&[.RppnfQjJ0@DBgj81`)#X|8^5M^#S"'~/'"*S/'\*{iKsW%iP*mqs'.-i+:K93%'!+}%~ ``` I must say that the idea behind the original code is really nice. Make a hashing function where each character depends on its previous one's modified outcome. This makes it impossible to take off any of the characters inside of the string. At most, you can start removing characters from the end. But starts taking off characters from the actual prime printing code. The only thing that @user23013 missed out was that the unhashing code could still be golfed :D. I am pretty sure that if my cracked answer was the real submission, it would be impossible to crack it. [Answer] ## [PHP by Tryth, distance 10](https://codegolf.stackexchange.com/a/44588/4098) **Original (3337):** ``` eval(gzinflate(base64_decode('tVlbiya3Ef0rwoxhlm0+7LxO5sH4AoYkOATnJeRB061vRnZfvtXlC8bsf8+pm6T2BvJig707092SSlWnTp2qfbg/f/aXI4XNxVuum1uO9Ugux+L8Fsrk5mPPYS6h1JCcX+It5jnury6ssVzcV2EPfsdH23Ysh1vja129C6+hyEbti83n7C/ua5yQjznG7HZfjg81uFvAT/GlZodFm3/d8W7B/zefSk0x7Hh67CXkCUvyDEOSS3GJc12xZqv54r459jC7D9Vv7gq78GVdS4pzDDgmzBPOWNdAe9CBoeJBCiXClg+Vvs5hu7i/1RWm83WxUxGL+QMX9rjZKbewBPdTzeWY3DXBE5GW3cM6Ob9G7F/kyHtdb7X4EtgbeJnmenHf77yZbZDejn3GLSo+iNstpCVivcdqeI3ckt09Fh8mWaBGIkhxLlUvi/uIUdux0q96NTqr4OjkStznuNQd4fo6eTjX38jdF/fPePcb+X0NG7xDoQlkhEMIYovccJE1xGvYF1fgTtpAv1iDRR6OPVIpsQBC5ObuTb1G28LDReLWr8hruNPKIPQwejITXdzhingPKXkN1TXU1+jZR2bFD28+84/t051DWRFDoAWPfYr4a/U4IcALf8dOBIRUSyJH6TVaAC7u2xJh0QAiOIRi7Hx9rYFgnPxLJCRyPOYjkdvO3yNY2ENSoUbbUyN+cX/1YUaIM66x3Wq268gC+G2JGhNdwSgVjGuU1vgSEkBkuTpmJ327B7pkDotkttjDG+x1h/tfVo9TimB3rTO56lbXe9x9mtwbopRCwvu4TBKcwWjKhGOJB+UshayDTO9j6cJxdxnxDDtFRIwe8H31dRY4KrY542hPc1m735HmKP7BFn3lCPBvaDHweHH/wL17fm4eVJL7Vnt8eTMT87H4FUHL/jUWMolIyMsODcATo5wPf8EV9oWJjBdOggryI7afa8qwSVzMd3lN/h4XL9u6LTqvXri47yoI7X9lmDgMKRoyceOK0241YV+KH0I+48skKCbu0NRHrEGSx1637RcOG+O/edbPc90yJazw/S7AZFLo2IWBYBRgG1gaUNB8eTKKYy+F45biFille2A4YIosOE7OwBG3I6OaBPjqJa7RczqFJyJHP5NN4jcYcio+qwe0oxccG4GrnQRDJlgGAP3owEH4D76Cj5EXRXm40yzTdP81elQUohjNFgq/V25qlguOOrfy/em4qXvX/6Zoyrl2Zw6X7vIDrp2pwPXMHels5BbxsTAWg4uius8t2hrpITT3Y63lBqo0VxnoON5xkeAr91XNKU6NvPZcuLcNG4yEXenzsc52xTACsLtXiXviWiXeXcNcOlMohjvi4KIzvXOyCnC5HJ7L+hXwwAbkV+GNIbTtJ0KkeS7MQpHjEZTkLFwm5TG6DSX4zCWtjLwoBUmovhcElUCSwNPAi7xRwBooJSuHBopm4CTk1Xh2I4KpfvEDWAAuopuQqAwWU1bMVsI9mhNCvZIGTb3ogZ1yJG26BxqMdbO7CL0/KueHLBNfSu53GSG3nVhvyp3Nh3QSpZ27gRn4jWhXgZXsI/HutzslZsf2Wc1qJeaUmga6J3a1a5B+2TynCAdWUnLwUq89LM56kRYFAa6TMMG6EcW6/xBu+0yN0w8mDSzXdw1VSzEyRouSFXmpRyD2TGk2A6oLolYTKpIqfst4OLMnJXu9CQ0tlKJvjV78QLHsCjNY6cI2BkRrhtiHts9hEBpiJ8LYNcEgf0T2mGqwM6l8T07k+OA8qcDsb47+J0H5XaErxRtEypX54n4spjR70hvndgRqW9QyfAChMuAC8voNKmppVDU+fiPO8dwgpZfoYC72EtG3B7vGHor1VsoluPEWKNNb9XyFEZ7LGpdfViod61LAxmwpQo+AjTBj60+khEtfwiFQlPazW3tyuokSrEhWiishk5LgQIBUPXLcpMPwhDpdIzRspMDldWhetCOwRkuKzx/rxB85D6TPa4JOXGKlWDO1t2AqeE5E7LDf+EBlKVz8hlPFbE6lFTzutSekJb0YIVU4nSW9KDkO+BUhXY8XuJGScvhYjYTHmUA6gzWfALfsJGW+UaBonejmmuw99ZTKCdRKcdN9ioRmuQm3nkWMt/4bw9G2DSyzvQq2Vp3NUkOjFn0NUmOdciYQbREn66xJEt3DG80aPFXmSQquQUBcSppBihaDS4gzYsu0EF43g05XDjoomJR6lzjQZOukpdERe5trtLLDfVvTMZVFubARayaWcL1xHrKVhahikHprazO0V+tDhyYPrPFjZ7JME6HZ42wVhtwAnqKucKC3ASITcwsu1ep1K1jsaOZtZVBCy3Rqg+02EhkGKLZS8yj00l4xF1P8kq6jMcSAHfymR1QLs7CWkInlhVVBGxWo/1USjHYxAI0MpzYJEy6fLGmHGjQmjballKYcdQtjM79ljJZ47YFYCA0aocVA8KvtrewFY++eC4sgMRoZaaU79R6nOZnlig4STMH0DXsRFz2unUGb8VRWbn4270qBBU6YH/MwioFRBGhQ5zBI6FHj24qqtwGQ9LC00aetj42PRAfNn05thlpmLR7r7uZQyzu5OmSTzKr+P/eKz71Sks6RijbvSps2jFA5pRaM9glZmnOG4mmZQxkujbA2hpT3k/WH2l2MFbvykIAeBB34CMBZfzMXanntN58/qfndkA6aSfrIUflaIzbptVmnKVR6m62NknT5ZIBIVOlarJzrR6xTaV5h4kkdOEjZnvFNc1kwW48caQ8hKKZOI2ktkqdB0+lK4ldSFk5UsQ1MrTgohTGSrPAJC8dxDCVwYhVqHK4FVaRfsR6sMfMw3FTx2yrKWB+MbuQi8qeRAuLDZti3bKRisBYDgo6iYBXHk3ABZynvVaGUjj/rEk2iNQ3No5dhhPf9fu65tILVYoJBxu7N9aJ5LHJyU/HKNLid4KwCgIRgn3vKtF/0OM85pCAqtpuVxP2n6crSygI1djJAHLqVptfGhyzw5D6TTeS5R1SI6yDoXCkkszs0aQhBAxetXH0oK+VunBHN+k8SrVo0utcDzZmCMh1jNF2h4y+1TVRzowRu3DQiml0aqfOsmBsB68JstWly8uq5jt3eIDZL8kPNEGFv1MbAIo/oDChyeg6RIryP006y+7OnK4wqEdy/Pz7s7359iM9fPj1QRwc6fQYGk//l8d3Tf97iGh6/pPfv3+t7vEYqh6frkR4ffn7+09PDz39+iPjz/ft3v8br40P8HI+fv8Ai+/7q1xyePn6kt/zM3uV//fsZa/F8PlCm9G1+9/xMRiX6l6rd6UOs//jxvw'))); ``` **Modified (3329):** ``` eval(gzinflate(base64_decode("tVlbiya3Ef0rwoxhlm0+7LxO5sH4AoYkOATnJeRB061vRnZfvtXlC8bsf8+pm6T2BvJig707092SSlWnTp2qfbg/f/aXI4XNxVuum1uO9Ugux+L8Fsrk5mPPYS6h1JCcX+It5jnury6ssVzcV2EPfsdH23Ysh1vja129C6+hyEbti83n7C/ua5yQjznG7HZfjg81uFvAT/GlZodFm3/d8W7B/zefSk0x7Hh67CXkCUvyDEOSS3GJc12xZqv54r459jC7D9Vv7gq78GVdS4pzDDgmzBPOWNdAe9CBoeJBCiXClg+Vvs5hu7i/1RWm83WxUxGL+QMX9rjZKbewBPdTzeWY3DXBE5GW3cM6Ob9G7F/kyHtdb7X4EtgbeJnmenHf77yZbZDejn3GLSo+iNstpCVivcdqeI3ckt09Fh8mWaBGIkhxLlUvi/uIUdux0q96NTqr4OjkStznuNQd4fo6eTjX38jdF/fPePcb+X0NG7xDoQlkhEMIYovccJE1xGvYF1fgTtpAv1iDRR6OPVIpsQBC5ObuTb1G28LDReLWr8hruNPKIPQwejITXdzhingPKXkN1TXU1+jZR2bFD28+84/t051DWRFDoAWPfYr4a/U4IcALf8dOBIRUSyJH6TVaAC7u2xJh0QAiOIRi7Hx9rYFgnPxLJCRyPOYjkdvO3yNY2ENSoUbbUyN+cX/1YUaIM66x3Wq268gC+G2JGhNdwSgVjGuU1vgSEkBkuTpmJ327B7pkDotkttjDG+x1h/tfVo9TimB3rTO56lbXe9x9mtwbopRCwvu4TBKcwWjKhGOJB+UshayDTO9j6cJxdxnxDDtFRIwe8H31dRY4KrY542hPc1m735HmKP7BFn3lCPBvaDHweHH/wL17fm4eVJL7Vnt8eTMT87H4FUHL/jUWMolIyMsODcATo5wPf8EV9oWJjBdOggryI7afa8qwSVzMd3lN/h4XL9u6LTqvXri47yoI7X9lmDgMKRoyceOK0241YV+KH0I+48skKCbu0NRHrEGSx1637RcOG+O/edbPc90yJazw/S7AZFLo2IWBYBRgG1gaUNB8eTKKYy+F45biFille2A4YIosOE7OwBG3I6OaBPjqJa7RczqFJyJHP5NN4jcYcio+qwe0oxccG4GrnQRDJlgGAP3owEH4D76Cj5EXRXm40yzTdP81elQUohjNFgq/V25qlguOOrfy/em4qXvX/6Zoyrl2Zw6X7vIDrp2pwPXMHels5BbxsTAWg4uius8t2hrpITT3Y63lBqo0VxnoON5xkeAr91XNKU6NvPZcuLcNG4yEXenzsc52xTACsLtXiXviWiXeXcNcOlMohjvi4KIzvXOyCnC5HJ7L+hXwwAbkV+GNIbTtJ0KkeS7MQpHjEZTkLFwm5TG6DSX4zCWtjLwoBUmovhcElUCSwNPAi7xRwBooJSuHBopm4CTk1Xh2I4KpfvEDWAAuopuQqAwWU1bMVsI9mhNCvZIGTb3ogZ1yJG26BxqMdbO7CL0/KueHLBNfSu53GSG3nVhvyp3Nh3QSpZ27gRn4jWhXgZXsI/HutzslZsf2Wc1qJeaUmga6J3a1a5B+2TynCAdWUnLwUq89LM56kRYFAa6TMMG6EcW6/xBu+0yN0w8mDSzXdw1VSzEyRouSFXmpRyD2TGk2A6oLolYTKpIqfst4OLMnJXu9CQ0tlKJvjV78QLHsCjNY6cI2BkRrhtiHts9hEBpiJ8LYNcEgf0T2mGqwM6l8T07k+OA8qcDsb47+J0H5XaErxRtEypX54n4spjR70hvndgRqW9QyfAChMuAC8voNKmppVDU+fiPO8dwgpZfoYC72EtG3B7vGHor1VsoluPEWKNNb9XyFEZ7LGpdfViod61LAxmwpQo+AjTBj60+khEtfwiFQlPazW3tyuokSrEhWiishk5LgQIBUPXLcpMPwhDpdIzRspMDldWhetCOwRkuKzx/rxB85D6TPa4JOXGKlWDO1t2AqeE5E7LDf+EBlKVz8hlPFbE6lFTzutSekJb0YIVU4nSW9KDkO+BUhXY8XuJGScvhYjYTHmUA6gzWfALfsJGW+UaBonejmmuw99ZTKCdRKcdN9ioRmuQm3nkWMt/4bw9G2DSyzvQq2Vp3NUkOjFn0NUmOdciYQbREn66xJEt3DG80aPFXmSQquQUBcSppBi4gzYsu0EF43g05XDjoomJR6lzjQZOukpdERe5trtLLDfVvTMZVFubARayaWcL1xHrKVhahikHprazO0V+tDhyYPrPFjZ7JME6HZ42wVhtwAnqKucKC3ASITcwsu1ep1K1jsaOZtZVBCy3Rqg+02EhkGKLZS8yj00l4xF1P8kq6jMcSAHfymR1QLs7CWkInlhVVBGxWo/1USjHYxAI0MpzYJEy6fLGmHGjQmjballKYcdQtjM79ljJZ47YFYCA0aocVA8KvtrewFY++eC4sgMRoZaaU79R6nOZnlig4STMH0DXsRFz2unUGb8VRWbn4270qBBU6YH/MwioFRBGhQ5zBI6FHj24qqtwGQ9LC00aetj42PRAfNn05thlpmLR7r7uZQyzu5OmSTzKr+P/eKz71Sks6RijbvSps2jFA5pRaM9glZmnOG4mmZQxkujbA2hpT3k/WH2l2MFIAeBB34CMBZfzMXanntN58/qfndkA6aSfrIUflaIzbptVmnKVR6m62NknT5ZIBIVOlarJzrR6xTaV5h4kkdOEjZnvFNc1kwW48caQ8hKKZOI2ktkqdB0+lK4ldSFk5UsQ1MrTgohTGSrPAJC8dxDCVwYhVqHK4FVaRfsR6sMfMw3FTx2yrKWB+MbuQi8qeRAuLDZti3bKRisBYDgo6iYBXHk3ABZynvVaGUjj/rEk2iNQ3No5dhhPf9fu65tILVYoJBxu7N9aJ5LHJyU/HKNLid4KwCgIRgn3vKtF/0OM85pCAqtpuVxP2n6crSygI1djJAHLqVptfGhyzw5D6TTeS5R1SI6yDoXCkkszs0aQhBAxetXH0oK+VunBHN+k8SrVo0utcDzZmCMh1jNF2h4y+1TVRzowRu3DQiml0aqfOsmBsB68JstWly8uq5jt3eIDZL8kPNEGFv1MbAIo/oDChyeg6RIryP006y+7OnK4wqEdy/Pz7s7359iM9fPj1QRwc6fQYGk//l8d3Tf97iGh6/pPfv3+t7vEYqh6frkR4ffn7+09PDz39+iPjz/ft3v8br40P8HI+fv8Ai+/7q1xyePn6kt/zM3uV//fsZa/F8PlCm9G1+9/xMRiX6l6rd6UOs//jxvw"))); ``` In addition to removing 8 characters directly, I swapped the single quotes for double quotes to increase the Levenshtein by 2. [Answer] [Original](https://codegolf.stackexchange.com/a/44574) by MickyT- **R, 2496** ``` f=function(n){primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=rep(T,1e8);primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[1]=F;last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=2L;s=floor(sqrt(1e8));while(last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu<=s){primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[seq.int(2L*last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu,1e8,last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu)]=F;a=which(primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[(last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu+1):(s+1)]);if(any(a)){last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu+min(a)}else last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=s+1;};which(primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu)[1:n]} ``` Modified Version **R, 2492** Levenshtein Distance **9**: ``` f=function(n){primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=rep(T,1e8);primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[1]=F;last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=2L;s=floor(10000);while(last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu<=s){primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[seq.int(2L*last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu,1e8,last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu)]=F;a=which(primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu[(last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu+1):(s+1)]);if(any(a)){last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu+min(a)}else last.primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu=s+1;};which(primenumbervectorusedtopadouthelengthofthefunctionaaaaabbbbbbcccccdddddfffffgggggghhhhiiiilllllmmmmmjjjjjjjkkkkkkknnnoopppppqqqqqqqrrrrsssssvvvvvvwwwwwwwxxxxxxxyyyyyyyzzzzzzzuuu)[1:n]} ``` Replaced `sqrt(1e8)` with literal value `10000`. [Answer] [Original](https://codegolf.stackexchange.com/a/44580/32532) by **Yimin Rong** (PHP): ``` function f($N){for($X=2;$N>0;$N--,$X=gmp_nextprime($X))echo gmp_strval($X)."\n";} ``` Modified version: ``` function f($M){for($X=2;$M-->0;$X=gmp_nextprime($X))echo gmp_strval($X)."\n";} ``` Removed `$N--,`. Changed `$N>0` to `$N-->0`. Then changed all instances of `$N` to `$M`. Distance **9**. This works for negative values. [Answer] [Original](https://codegolf.stackexchange.com/a/44581/25180) by Optimizer, **CJam, 816** ``` 2096310474722535167101644870465221130589294718524480357298593539991449081456134974040327647811988614006547797131583006214774425505300308072534652704698066198168917157808088127072977533505828030424680462284796680517062482806071903877790511864982169694627161605805004020026776166437905874324921940992417561695490946773393335345359408853148348949580796568713745813831280652341152402924541125638927689856083360967358992399503448120976930749396205332801012617624500616793294935391926550972449345223742044846417092758797166517935273839376542415759222999108744843547749052422322505847239684550378130982502607844441524249912214473298703307285931801940096458075553488261398391072450942373513854346538654787042832255689633663897703600453311016458268536228117201022525438843626260325862965735311855887334994546704703657K)_#b:c~ ``` Modified Version **CJam, 815** Levenshtein Distance **10** ``` 209631047472253516710164487046522113058929471852448035729859353999144908145613497404032764781198861400654779713158300621477442550530030807253465270469806619816891715780808812707297753350582803042468046228479668051706248280607190387779051186498216969462716160580500402002677616643790587432492194099241756169549094677339333534535940885314834894958079656871374581383128065234115240292454112563892768985608336096735899239950344812097693074939620533280101261762450061679329493539192655097244934522374204484641709275879716651793527383937654241575922299910874484354774905242232250584723968455037813098250260784444152424991221447329870330728593180194009645807555348826139839107245094237351385434653865478704283225568963366389770360045331101645826853622811720102252543884362626032586296573531185588733499454674e7K)_#b:cW';t~ ``` Changed `04703657K)_#b:c~` to `4e7K)_#b:cW';t~`. [Answer] # [Java, 6193 by Geobits, Distance 10](https://codegolf.stackexchange.com/a/44623/31414) Original: ``` int[]p(int n){int i,c=2,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[];a:for(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=new int[0];aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length<n;c++){for(i=0;i<aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length;)if(c%aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[i++]<1)continue a;aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=Arrays.copyOf(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length+1);aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length-1]=c;}return aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________;} ``` Modified: ``` int[]p(int n){int i,c=2,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[];a:for(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=new int[0];aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length<n;c++){for(i=0;i<aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length;)if(c%aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[i++]<1)continue a;(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=Arrays.copyOf(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length+1)/*aaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999__*/)[aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length-1]=c;}return aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________;} ``` Maybe next time my friend ;) [Answer] # [Mathematica, by Optimizer, 21 to 18, distance 10](https://codegolf.stackexchange.com/a/44646/8478) from ``` Table[Prime@n,{n,#}]& ``` to ``` Array[Prime@#&,#]& ``` [Answer] # [Python 3, 9302 to 9301, by Sp3000, distance 10](https://codegolf.stackexchange.com/a/44655/25180) ## Original ``` def P(n,x="'Time to try again!'and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted([2]*(len(x)==9274 and x[9273] and n>=1)+[3]*(len(x)==9274 and x[9273] and n>=2)+[5]*(len(x)==9274 and x[9273] and n>=3)+[7]*(len(x)==9274 and x[9273] and n>=4)+[11]*(len(x)==9274 and x[9273] and n>=5)+[k for k in range(79,n*n)if all(k%d>0for d in range(2,k))][:max(0,n-21)]+[13]*(len(x)==9274 and x[9273] and n>=6)+[17]*(len(x)==9274 and x[9273] and n>=7)+[19]*(len(x)==9274 and x[9273] and n>=8)+[23]*(len(x)==9274 and x[9273] and n>=9)+[29]*(len(x)==9274 and x[9273] and n>=10)+[31]*(len(x)==9274 and x[9273] and n>=11)+[37]*(x[9273]==chr(39)and n>=12))+[41]*(x[9272]==chr(33)and n>=13))+[43]*(x[9271]==chr(115)and n>=14))+[47]*(x[9270]==chr(107)and n>=15))+[53]*(x[9269]==chr(108)and n>=16))+[59]*(x[9268]==chr(111)and n>=17))+[61]*(x[9267]==chr(102)and n>=18))+[67]*(x[9266]==chr(32)and n>=19))+[71]*(x[9265]==chr(44)and n>=20))+[73]*(x[9264]==chr(108)and n>=21))) or 'Uh oh' if n>0 else [] if n==0 else ''' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!####################################################################################################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&&&&&&&&&&&&&((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))******************************************************************************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---------------------------------------------------------------------------------------------------....................................................................................................////////////////////////////////////////////////////////////////////////////////////////////////////00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222233333333333333333333333333333333333333333333333333333333333333344444444444444444444444444444444444444444444444444444444444444444444444444444444455555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555566666666666666666666666666666666666666666666666666666666666666666666666666666666666666666777777777777777777777777777777777777777777777777777888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<==================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^____________________________________________________________________________________________________````````````````````````````````````````````````````````````````````````````````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~''' or 'And thats all, folks!'"):return eval(x) ``` ## Modified ``` def P(n,x="'+"*4+"'try ain!'and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and x[9273]and sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted(sorted([2]*(len(x)==9274 and x[9273] and n>=1)+[3]*(len(x)==9274 and x[9273] and n>=2)+[5]*(len(x)==9274 and x[9273] and n>=3)+[7]*(len(x)==9274 and x[9273] and n>=4)+[11]*(len(x)==9274 and x[9273] and n>=5)+[k for k in range(79,n*n)if all(k%d>0for d in range(2,k))][:max(0,n-21)]+[13]*(len(x)==9274 and x[9273] and n>=6)+[17]*(len(x)==9274 and x[9273] and n>=7)+[19]*(len(x)==9274 and x[9273] and n>=8)+[23]*(len(x)==9274 and x[9273] and n>=9)+[29]*(len(x)==9274 and x[9273] and n>=10)+[31]*(len(x)==9274 and x[9273] and n>=11)+[37]*(x[9273]==chr(39)and n>=12))+[41]*(x[9272]==chr(33)and n>=13))+[43]*(x[9271]==chr(115)and n>=14))+[47]*(x[9270]==chr(107)and n>=15))+[53]*(x[9269]==chr(108)and n>=16))+[59]*(x[9268]==chr(111)and n>=17))+[61]*(x[9267]==chr(102)and n>=18))+[67]*(x[9266]==chr(32)and n>=19))+[71]*(x[9265]==chr(44)and n>=20))+[73]*(x[9264]==chr(108)and n>=21))) or 'Uh oh' if n>0 else [] if n==0 else ''' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!####################################################################################################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&'&&&&&&&&&&&&&((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))******************************************************************************+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---------------------------------------------------------------------------------------------------....................................................................................................////////////////////////////////////////////////////////////////////////////////////////////////////00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222233333333333333333333333333333333333333333333333333333333333333344444444444444444444444444444444444444444444444444444444444444444444444444444444455555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555566666666666666666666666666666666666666666666666666666666666666666666666666666666666666666777777777777777777777777777777777777777777777777777888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<==================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^____________________________________________________________________________________________________````````````````````````````````````````````````````````````````````````````````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~''' or 'And thats all, folks!'"):return eval(x) ``` [Answer] Original by Timtech - **TI-BASIC, 4513** ``` Input N:Nlength("ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!">N:{2>L1:For(A,3,E99:If min(1=gcd(A,seq(A,A,2,A^.5:A>L1(1+dim(L1:End:N/4410>dim(L1:L1 ``` Modified Version **TI-BASIC, 4505** Levenshtein Distance **10**: ``` Input N:Nlength("IJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!ABCDEFGHIJKLOPQRSTUVWXYZ3456789?,><.[]{}-=+^*()%!">N:{2>L1:For(A,3,E99:If min(1=gcd(A,seq(A,A,2,A^.5:A>L1(1+dim(L1:End:N/4402>dim(L1:L1 ``` I changed the length of the string and the divisor [Answer] [Original](https://codegolf.stackexchange.com/a/44576/32628) by Brandon **C# 233**: ``` static IEnumerable<int>F(int N){var a=new List<int>();var w=2;while(a.Count<N){Func<int,int,bool>c=(o,k)=>(o%k)!=0;Action<List<int>,int>d=(t,n)=>t.Add(n);var p=true;var f=w/2;for(int i=2;i<=f;){p=c(w,i++);}if(p)d(a,w);w++;}return a;} ``` Modified version **C# 231** Levenshtein Distance **10**: ``` static IEnumerable<int>F(int N){var l=new List<int>();var w=2;while(l.Count<N){Func<int,int,bool>m=(o,k)=>(o%k)!=0;Action<List<int>,int>d=(t,n)=>t.Add(n);var p=true;var u=w/2;for(int i=2;i<=u;)p=m(w,i++);if(p)d(l,w);w++;}return l;} ``` Changed variable names to hit 10 distance for new scoring rules. ~~Modified version **C# 231** Levenshtein Distance **2**:~~ ``` static IEnumerable<int>F(int N){var a=new List<int>();var w=2;while(a.Count<N){Func<int,int,bool>c=(o,k)=>(o%k)!=0;Action<List<int>,int>d=(t,n)=>t.Add(n);var p=true;var f=w/2;for(int i=2;i<=f;)p=c(w,i++);if(p)d(a,w);w++;}return a;} ``` [Answer] # C#, [Shawn Holzworth (161)](https://codegolf.stackexchange.com/a/44599/30688), distance 10 I used a standard golf trick to remove one character: shorting `2*n+1` to `n-~n`. ``` static List<int>F(int N){var L=new List<int>();if(N>1){L.Add(2);for(int n=1,m=3,r=1;N-->0;n++){while(m<n){if(n%m==r)goto X;m+=2;r++;}L.Add(n-~n);X:;}}return L;} ``` [Answer] # [Java 8, 1785, by TheBestOne, distance 10](https://codegolf.stackexchange.com/a/44593/6638) ### Original ``` import java.lang.reflect.*;import java.util.*;class P extends ClassLoader{public static void main(String[]a)throws Exception{System.out.print(new P().primes(Integer.parseInt(a[0])));}List<Integer>primes(int n)throws Exception{byte[]b=Base64.getDecoder().decode("yv66vgAAADQAQwoADQAmBwAnCgACACYLACgAKQsAKAAqCwArACwLACsALQcALgoACAAvCgAIADALACgAMQcAMgcAMwEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUBAAR0aGlzAQAITFByaW1lczsBAAFnAQATKEkpTGphdmEvdXRpbC9MaXN0OwEABXByaW1lAQABSQEAAWkBAAFuAQAGcHJpbWVzAQAQTGphdmEvdXRpbC9MaXN0OwEAFkxvY2FsVmFyaWFibGVUeXBlVGFibGUBACVMamF2YS91dGlsL0xpc3Q8TGphdmEvbGFuZy9JbnRlZ2VyOz47AQANU3RhY2tNYXBUYWJsZQcANAcANQEACVNpZ25hdHVyZQEAKChJKUxqYXZhL3V0aWwvTGlzdDxMamF2YS9sYW5nL0ludGVnZXI7PjsBAApTb3VyY2VGaWxlAQALUHJpbWVzLmphdmEMAA4ADwEAE2phdmEvdXRpbC9BcnJheUxpc3QHADQMADYANwwAOAA5BwA1DAA6ADsMADwAPQEAEWphdmEvbGFuZy9JbnRlZ2VyDAA+ADcMAD8AQAwAQQBCAQAGUHJpbWVzAQAQamF2YS9sYW5nL09iamVjdAEADmphdmEvdXRpbC9MaXN0AQASamF2YS91dGlsL0l0ZXJhdG9yAQAEc2l6ZQEAAygpSQEACGl0ZXJhdG9yAQAWKClMamF2YS91dGlsL0l0ZXJhdG9yOwEAB2hhc05leHQBAAMoKVoBAARuZXh0AQAUKClMamF2YS9sYW5nL09iamVjdDsBAAhpbnRWYWx1ZQEAB3ZhbHVlT2YBABYoSSlMamF2YS9sYW5nL0ludGVnZXI7AQADYWRkAQAVKExqYXZhL2xhbmcvT2JqZWN0OylaACEADAANAAAAAAACAAEADgAPAAEAEAAAAC8AAQABAAAABSq3AAGxAAAAAgARAAAABgABAAAABAASAAAADAABAAAABQATABQAAAAJABUAFgACABAAAADpAAIABQAAAFK7AAJZtwADTAU9K7kABAEAGqIAPyu5AAUBAE4tuQAGAQCZAB4tuQAHAQDAAAi2AAk2BBwVBHCaAAanABGn/98rHLgACrkACwIAV4QCAaf/vSuwAAAABAARAAAAJgAJAAAABwAIAAgAFAAJADIACgA5AAsAPAANAD8ADgBKAAgAUAAQABIAAAAqAAQAMgAKABcAGAAEAAoARgAZABgAAgAAAFIAGgAYAAAACABKABsAHAABAB0AAAAMAAEACABKABsAHgABAB8AAAAXAAb9AAoHACAB/AAQBwAhIPoAAgr6AAUAIgAAAAIAIwABACQAAAACACU");Class<?>p=defineClass("Primes",b,0,1052);Method m=p.getMethod("g",int.class);return(List<Integer>)m.invoke(null,n);}} ``` ### Modified ``` import java.lang.reflect.*;import java.util.*;class P extends ClassLoader{public static void main(String[]a)throws Exception{System.out.print(new P().p(Integer.parseInt(a[0])));}List<Integer>p(int n)throws Exception{byte[]b=Base64.getDecoder().decode("yv66vgAAADQAQwoADQAmBwAnCgACACYLACgAKQsAKAAqCwArACwLACsALQcALgoACAAvCgAIADALACgAMQcAMgcAMwEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUBAAR0aGlzAQAITFByaW1lczsBAAFnAQATKEkpTGphdmEvdXRpbC9MaXN0OwEABXByaW1lAQABSQEAAWkBAAFuAQAGcHJpbWVzAQAQTGphdmEvdXRpbC9MaXN0OwEAFkxvY2FsVmFyaWFibGVUeXBlVGFibGUBACVMamF2YS91dGlsL0xpc3Q8TGphdmEvbGFuZy9JbnRlZ2VyOz47AQANU3RhY2tNYXBUYWJsZQcANAcANQEACVNpZ25hdHVyZQEAKChJKUxqYXZhL3V0aWwvTGlzdDxMamF2YS9sYW5nL0ludGVnZXI7PjsBAApTb3VyY2VGaWxlAQALUHJpbWVzLmphdmEMAA4ADwEAE2phdmEvdXRpbC9BcnJheUxpc3QHADQMADYANwwAOAA5BwA1DAA6ADsMADwAPQEAEWphdmEvbGFuZy9JbnRlZ2VyDAA+ADcMAD8AQAwAQQBCAQAGUHJpbWVzAQAQamF2YS9sYW5nL09iamVjdAEADmphdmEvdXRpbC9MaXN0AQASamF2YS91dGlsL0l0ZXJhdG9yAQAEc2l6ZQEAAygpSQEACGl0ZXJhdG9yAQAWKClMamF2YS91dGlsL0l0ZXJhdG9yOwEAB2hhc05leHQBAAMoKVoBAARuZXh0AQAUKClMamF2YS9sYW5nL09iamVjdDsBAAhpbnRWYWx1ZQEAB3ZhbHVlT2YBABYoSSlMamF2YS9sYW5nL0ludGVnZXI7AQADYWRkAQAVKExqYXZhL2xhbmcvT2JqZWN0OylaACEADAANAAAAAAACAAEADgAPAAEAEAAAAC8AAQABAAAABSq3AAGxAAAAAgARAAAABgABAAAABAASAAAADAABAAAABQATABQAAAAJABUAFgACABAAAADpAAIABQAAAFK7AAJZtwADTAU9K7kABAEAGqIAPyu5AAUBAE4tuQAGAQCZAB4tuQAHAQDAAAi2AAk2BBwVBHCaAAanABGn/98rHLgACrkACwIAV4QCAaf/vSuwAAAABAARAAAAJgAJAAAABwAIAAgAFAAJADIACgA5AAsAPAANAD8ADgBKAAgAUAAQABIAAAAqAAQAMgAKABcAGAAEAAoARgAZABgAAgAAAFIAGgAYAAAACABKABsAHAABAB0AAAAMAAEACABKABsAHgABAB8AAAAXAAb9AAoHACAB/AAQBwAhIPoAAgr6AAUAIgAAAAIAIwABACQAAAACACU");Class<?>p=defineClass("Primes",b,0,1052);Method m=p.getMethod("g",int.class);return(List<Integer>)m.invoke(null,n);}} ``` Method name `primes` --> `p`. Didn't touch the byte code, lol. [Answer] # [PHP, 73, by Yimin Rong, distance 10](https://codegolf.stackexchange.com/a/44591/6638) ### Original ``` function f($N){for($X=2;$N-->0;$X=gmp_nextprime($X))echo gmp_strval($X)."\n";} ``` ### Modified ``` function f($N){for($X=2;$N-->0;$X=gmp_nextprime($X))echo ($X)."\n";} ``` Removed `gmp_strval`, since `GMP` object implements [`Serializable`](http://php.net/manual/en/class.serializable.php) interface. Demo on [ideone](http://ideone.com/zjchAI). [Answer] # [Matlab, by flawr, distance 10](https://codegolf.stackexchange.com/a/44569/31849) ### Original ``` function l=codegolf_cop_primes(n) if strcmp(fileread([mfilename,'.m']),fileread('codegolf_cop_primes.m')); if sum(find(fileread([mfilename,'.m'])==char(101)))==941; l=primes(n); end;end;end ``` ### Modified version ``` function l=codegolf_cop_primes(n) if strcmp(fileread([mfilename,'.m']),fileread('codegolf_cop_primes.m')); if sum(find(fileread([mfilename,'.m'])==char(98)))==0; l=primes(n); end;end;end ``` Removed one space from indent in line 3 (1 removal). Changed `char(101)` to `char(98)` (2 substitutions, 1 removal) and changed the sum from 941 to 0 (1 substitution and 2 removals). Removed 3 spaces from line 4 indent (3 removals). Distance **10**. (Note that I think the 941 in flawr's code should be 1873, in which case I can't remove as many indent spaces, but I can keep the same Levenshtein distance). [Answer] # [CJam, 844 to 841, by Optimizer, distance 10](https://codegolf.stackexchange.com/a/44616/25180) ## Original ``` 12247876366120440321987597021850303099642933156438096645849638833333796669145152157730940027890107281005910531197663816515537375105813004395899380585836297635211554406835251714644233377311180313806351554322591378031790757554316749763716910092225660788618471820881301518717801906372848112696524416568549935114340687733586827456214369410510395419921556825071212523337705803228595799373212401103152036673548421780881324448501082512655185005238821681990803145396009000973909800507781916769743162191496991228611317139593059968851018760665715388977769175766784944571868905607977583735512313028165561919771363465459087009309674834093296148584222690589604662407057035011740513343663528793002419282203653286073637418998298970726277476827911767544330705406278724865591029429120559455120218309440233354746066412254694019741678988828410289014532382K)_#b:c~ ``` ## Modified ``` 1224787636612044032198759702185030309964293315643809664584963883333379666914515215773094002789010728100591053119766381651553737510581300439589938058583629763521155440683525171464423337731118031380635155432259137803179075755431674976371691009222566078861847182088130151871780190637284811269652441656854993511434068773358682745621436941051039541992155682507121252333770580322859579937321240110315203667354842178088132444850108251265518500523882168199080314539600900097390980050778191676974316219149699122861131713959305996885101876066571538897776917576678494457186890560797758373551231302816556191977136346545908700930967483409329614858422269058960466240705703501174051334366352879300241928220365328607363741899829897072627747682791176754433070540627872486559102942912055945512021830944023335474606641225469408974167898882841028901e7K)_#b);:c~ ``` [Answer] # [Java, TheBestOne, 485, distance 10](https://codegolf.stackexchange.com/a/44586/30688) I just removed the two unnecessary empty pairs of angle brackets. The funny part is it wouldn't even compile for me *with* them. ``` import java.util.concurrent.*;class P{public static void main(String[]_)throws Exception{new java.io.FileOutputStream(java.io.FileDescriptor.out).write((new P().p(Integer.parseInt(_[0]))+"\n").getBytes());}CopyOnWriteArrayList<Integer>p(int n){int i=0;java.util.AbstractSequentialList<Integer>p=new java.util.LinkedList();while(p.size()<n)if(i(++i))p.add(i);return new CopyOnWriteArrayList(p);}boolean i(int n){if(n<2)return 0>1;for(int i=1;++i<n;)if(n%i<1)return 5>8;return 9>7;}} ``` [Answer] # [CJam, 847 to 846, by Optimizer, distance 10](https://codegolf.stackexchange.com/a/44618/25180) ## Original ``` 4779659069705537686629306155471157384185002665906714111039332233593305253079468024508943067783073619511162371004177761083906937019123280598903720691594788933998823566336886958487485882188081404453554140645458850256480477816754760296759608081868733889572904453777025857233956964359287627735920112545668451419633327348759828062858429551649268603103093273185548244528692381865244563710320514626922926579018891737532361295075806571486288031909749328444136657730394954950591089720665303368383306773979761795939998834047059891711321663733546692144057374799580281864662626927123661467550653064624501175880393774197348826665071960854773911967066677298613781653567324550746617015776799557587373107689983516628129486795118747367224275071679155545175621238368159967426890170894035742040653492311755971330981951171079833152098813713009957610693562K)_#b:cG/zs~ ``` ## Modified ``` 4779659069705537686629306155471157384185002665906714111039332233593305253079468024508943067783073619511162371004177761083906937019123280598903720691594788933998823566336886958487485882188081404453554140645458850256480477816754760296759608081868733889572904453777025857233956964359287627735920112545668451419633327348759828062858429551649268603103093273185548244528692381865244563710320514626922926579018891737532361295075806571486288031909749328444136657730394954950591089720665303368383306773979761795939998834047059891711321663733546692144057374799580281864662626927123661467550653064624501175880393774197348826665071960854773911967066677298613781653567324550746617015776799557587373107689983516628129486795118747367224275071679155545175621238368159967426890170894035742040653492311755971330981951171079833152098813713009967319e6 6m21_#b:cG/zs~ ``` [Answer] # [CJam, by Optimizer, 24 to 22, distance 10](https://codegolf.stackexchange.com/a/44652/8478) From ``` {1{)__mp{@(_@\}*}g@?}:F; ``` to ``` {1\{{)_mp!}g_}*_g?}:F; ``` [Answer] # [Java, 328, by TheBestOne, distance 10](https://codegolf.stackexchange.com/a/44597/6638) ### Original ``` import java.util.*;class P{public static void main(String[] args){System.out.print(new P().a(Integer.parseInt(args[0])));}List<Integer>a(int n){List<Integer>a=new ArrayList<>();int i=0;while(a.size()<n){if(b(++i)){a.add(i);}}return a;}boolean b(int n){String a="";for(int i=0;i++<n;)a+=1;return!a.matches("^1?$|^(11+?)\\1+$");}} ``` ### Modified ``` import java.util.*;class P{public static void main(String[] args){System.out.print(new P().a(Integer.parseInt(args[0])));}List<Integer>a(int n){List<Integer>a=new ArrayList<>();int i=1;while(a.size()<n){if(b(++i)){a.add(i);}}return a;}boolean b(int n){String a="11";for(int i=2;i++<n;)a+=1;return!a.matches("^(11+)\\1+$");}} ``` Change regex `"^1?$|^(11+?)\\1+$"` to `"^(11+)\\1+$"` (6 removals), and assume the input to the prime test function is at least 2 (2 additions, 1 swap). Modified the starting number to test from `i = 0` to `i = 1` (since prime function is called by `b(++i)`, so `i` has to start from 1) (1 swap). [Answer] # Total Score: 10 Original answer by TheBestOne: ``` import java.util.concurrent.*;class P{public static void main(String[]a)throws Exception{new java.io.FileOutputStream(java.io.FileDescriptor.out).write((new P().p(Integer.parseInt(a[0]))+"\n").getBytes());}CopyOnWriteArrayList<Integer>p(int n){int i=0;java.util.AbstractSequentialList<Integer>p=new java.util.LinkedList<>();while(p.size()<n)if(i(++i))p.add(i);return new CopyOnWriteArrayList<>(p);}boolean i(int n){if(n<2)return 0>1;for(int i=1;++i<n;)if(n%i<1)return 0>1;return 1>0;}} ``` Modified with distance 10: ``` import java.util.concurrent.*;class P{public static void main(String[]a)throws Exception{new java.io.FileOutputStream(java.io.FileDescriptor.out).write((new P().p(Integer.parseInt(a[0]))+"\n").getBytes());}CopyOnWriteArrayList<Integer>p(int n){int i=0;java.util.AbstractSequentialList<Integer>p=new java.util.LinkedList<>();while(p.size()<n)if(i(++i))p.add(i);return new CopyOnWriteArrayList<>(p);}boolean i(int n){if(n<2)0>1;for(int i=1;++i<n;)if(n%i<1)return 0>1;return n<2;}} ``` Original answer by Yimin Rong: ``` func f($N){for($i=$N,$X=2;$i>0;$i--,$X=gmp_nextprime($X))print gmp_strval($X)."\n";} ``` Modified with distance 10: ``` func f($M){for($j=$M,$X=2;$j>0;$j--,$X=gmp_nextprime($X))echo gmp_strval($X)."\n";} ``` ~~David might have beaten me to this one:~~ Original answer by flawr: ``` function l=codegolf_cop_primes(n) if strcmp(fileread([mfilename,'.m']),fileread('codegolf_cop_primes.m')); if sum(find(fileread([mfilename,'.m'])==char(101)))==941; l=primes(n); end;end;end ``` Modified with distance 10: ``` function l=codegolf_cop_pri(n) if strcmp(fileread([mfilename,'.m']),fileread('codegolf_cop_pri.m')); if sum(find(fileread([mfilename,'.m'])==char(101)))==1956; l=primes(n); end;end;end ``` Edit: David beat me to it. ~~Original answer by Yimin Rong:~~ ``` <?php for ($i = $argv[1], $X = 2; $i > 0; $i--, $X = gmp_nextprime($X)) print gmp_strval($X)."\n"; ?> ``` Modified with distance 10: ``` <?php for ($i = $argv[1],$X = 2;$i>0;$i--,$X=gmp_nextprime($X)) print gmp_strval($X)."\n"; ?> ``` With the old scoring system, this would have given me a 10.7. Edit: The rules keep changing. I think this doesn't count now. [Answer] # [~~Java, 6193, by Geobits, distance 10~~](https://codegolf.stackexchange.com/a/44623/6638) Non-competing, since I was too slow in editing. Leave it here for reference. ### Modified ``` int[]p(int n){int i,c=2,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[];a:for(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=new int[0];aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length<n;c++){for(i=0;i<aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length;)if(c%aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________[i++]<1)continue a;(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________=Arrays.copyOf(aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________,aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length+1))/*aaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999___*/[aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________.length-1]=c;}return aaaaaaaabbbbbbbbbccccccccdddddddddeeeeeeeeffffffffgggggggghhhhhhhhiiiiiiiijjjjjjjjjkkkkkkkkkllllllllmmmmmmmmmnnnnnnnooooooooppppppppqqqqqqqqqrrrrrrrrsssssssssttttttttuuuuuuuuvvvvvvvvvwwwwwwwwwxxxxxxxxxyyyyyyyyzzzzzzzzzAAAAAAAAABBBBBBBBBCCCCCCCCCDDDDDDDDDEEEEEEEEEFFFFFFFFFGGGGGGGGGHHHHHHHHHIIIIIIIIIJJJJJJJJJKKKKKKKKKLLLLLLLLLMMMMMMMMMNNNNNNNNNOOOOOOOOOPPPPPPPPPQQQQQQQQQRRRRRRRRRSSSSSSSSSTTTTTTTTTUUUUUUUUUVVVVVVVVVWWWWWWWWWXXXXXXXXXYYYYYYYYYZZZZZZZZZ0000000011111111222222222333333333444444444555555555666666666777777777888888888999999999_________;} ``` To demonstrate what was actually done, this part of the code: ``` pppppqqqqq=Arrays.copyOf(pppppqqqqq,pppppqqqqq.length+1);pppppqqqqq[pppppqqqqq.length-1]=c; ``` is transformed to this: ``` (pppppqqqqq=Arrays.copyOf(pppppqqqqq,pppppqqqqq.length+1))/*pp*/[pppppqqqqq.length-1]=c; ``` If you align the data right, you can get away with mostly swaps. * Insert `(` in front * Swap `;` for `)` * Swap 2 characters from the start of the variable with `/*` and 2 characters from the end with `*/`. * Delete 4 more characters from the commented variable, working back from `*/`. The delta length is -3. ]
[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/1112/edit). Closed 3 years ago. [Improve this question](/posts/1112/edit) ### Description Create a fully working "Guess the number" game. The game is played by two players as follows: 1. player one chooses a number (A) between 1 and **N** 2. player two tries to guess A choosing a number (B) in the same range 3. the first player responds **"higher"** `if A > B`, **"lower"** `if A < B` or **"correct"** `if A = B`. 4. steps 2-3 are repeated **I** times or until "correct" is responded. 5. If "correct" is heard, player two wins otherwise he loses. ### Specs Minimum specs for a valid entry: * user can play either as player one or player two. * computer plays the other role. * computer must really try to guess the number while playing as player two (so, guessing against the given data or ignoring the given data is cheating) * N = 100 **or** input by the user (your choice) * I = 5 **or** input by the user (your choice) * program must announce then winner at the end. * full human readable instructions of what to do in each step (e.g *"Play as player one or player two?"*, *"Enter another guess:"*, etc) - don't go nuts on this one; just keep it simple. ### Winning conditions In that order: 1. Highest voted entry wins **if** it's at least 3 votes ahead of the second highest voted entry. 2. Shortest entry wins. [Answer] ## TRS-80 BASIC, 249 characters I think this may be the first time I've submitted an answer to this site that I wrote *before* the site existed. ``` 0 CLS:RANDOM:A=1:B=1E3:Q=RND(1E3):FORX=1TO8E9:PRINTA"-"B:INPUT" Guess";C:IFC<AORC>B,X=X-1:NEXTELSEIFC<QPRINT"Too low":A=C+1:NEXTELSEIFC>QPRINT"Too high":B=C-1:NEXTELSEPRINTC"is right!! It took you"X"tries. ":X=9E9:NEXT:FORX=0TO0:X=INKEY$="":NEXT:RUN ``` In fact, I wrote it before the worldwide web existed. Back in the 1980s, just as TRS-80s were becoming irrelevant. This is an example of a "one-liner" — an attempt to fit the most interesting program you could into a single line of BASIC. It was my first one-liner, and not terribly impressive. (There were some amazing one-liners floating around out there.) A line of TRS-80 BASIC was limited to 255 characters, minus a couple for overhead. Though you could sometimes exceed this, since the true limit was 255 bytes *after* tokenization — but the editor would also truncate a line that had over 255 characters *before* tokenization, and you needed to use tricks in the line editor in order to insert literal control characters like newlines into your strings. And yes, to clarify, those line breaks in the listing are literal newline characters. (In order to get them in your code you needed to use the `C`hange command while `EDIT`ing the line. A total pain, but worth it to replace eight or more characters for `+CHR$(13)` with one.) Damn, I've been golfing for a long time. [Answer] **C 397 Characters** ``` N,H=99,L=0,c=0,w=1;main(){char s[9];puts("Play as player 1 or 2: ");scanf("%d",&N);if(N-1){getchar();do{N=rand()%(H-L)+L+1;printf("My guess: %d\n",N);gets(s);if(*s=='c'){w=2;break;}if(*s-'l')H=N-1;else L=N-1;c++;}while(c<5);}else{N=rand()%99+1;while(c<5){puts("Enter guess: ");scanf("%d",&H);if(H==N){puts("correct");break;}else puts(H>N?"higher":"lower");c++;}if(c==5)w=2;}printf("Winner %d",w);} ``` In a more readable form. ``` main() { int i,N,H=100,L=0,c=0,w=1; char s[10]; puts("Play as player 1 or 2: "); scanf("%d",&i); if(i-1) { getchar(); do{ N=rand()%(H-L)+L+1; printf("My guess: %d\n",N); gets(s); if(s[0]=='c')break; else if(s[0]=='h')H=N-1; else L=N-1; c++; }while (c<5); if(c<5)w=2; } else { N=rand()%99+1; while (c<5) { puts("Enter another guess: "); scanf("%d",&H); if(H==N){printf("correct\n");break;} else if(H>N)printf("higher\n"); else printf("lower\n"); c++; } if(c==5)w=2; } printf("Winner %d",w); } ``` [Answer] C#: Character count: With spaces: 575 No spaces: 464 ``` static void Main() { Action<object> w = s => Console.WriteLine(s); Func<object, byte> r = t => { w(t); var s = Console.ReadLine(); return Convert.ToByte(s); }; var p = r("Player (1/2):"); int N = 100, g, i = 0, c, d; var q = new List<int>(Enumerable.Range(0, N)); Func<Guid> x = Guid.NewGuid; c = p == 1 ? r("Number:") : q.OrderBy(j => x()).First(); m: i++; g = p == 2 ? r("Guess:") : q.OrderBy(j => x()).First(); d = g < c ? -1 : (g > c ? 1 : 0); w(d == -1 ? "Higher" : (d == 1 ? "Lower" : "correct")); q = q.Where(n => d == -1 ? n > g : n < g).ToList(); if(c != g && i < 5) goto m; r(g); } ``` **Edit** do while is now "Goto" (*shiver*) [Answer] ## Windows PowerShell, 289 ``` nal ^ Read-Host filter p{"Player $_ wins.";exit} $p=1-(^ Player 1 or 2) $n=($x=1)..($y=99)|random if($p){$n=^ Enter number}1..5|%{if($p){'{0:"higher";"lower";"correct";2|p}'-f($n-(^ Guess))|iex}else{"Guessing, "+($g=$x..$y|random);@{104='$x=$g+1';108='$y=$g-1';99='2|p'}[+(^)[0]]|iex}} 1|p ``` History: * 2011-02-21 18:44 **(620)** Ungolfed. * 2011-02-21 19:15 **(365)** First round of golfing. * 2011-02-21 19:31 **(359)** Some inlining. * 2011-02-21 19:38 **(340)** Some strings shortened. * 2011-02-21 19:44 **(339)** `while` → `for` * 2011-02-21 19:53 **(331)** Some duplicate strings pulled into variables. * 2011-02-21 19:53 **(330)** Another variable inlined. * 2011-02-21 19:53 **(328)** Optimized loop condition. Can't use a pipeline, though. * 2011-02-22 01:57 **(326)** `else{if...}` → `elseif` – saves the braces. * 2011-02-22 12:42 **(325)** Moved plenty of stuff around, using a hashtable instead of the `switch` to avoid naming the loop. Now I can use just `break` and a pipeline, too. Winner announcement moved into a filter that uses `exit` so no break required, ever. * 2011-02-23 01:23 **(308)** Instead of an `elseif` chain for checking the guess I just use a format string with different values for negative, positive and zero values. Saves a lot. * 2011-02-23 02:16 **(306)** Using subtraction instead of equality. * 2011-03-12 02:27 **(289)** Reduced to the same level of rudimentary user interaction as the Ruby solution. Of course it's shorter then. [Answer] Good old plain C ``` #include <stdio.h> #define x(s) puts(s) main(){int c,i,l,h,g;srand(time(NULL));p:x("You want to guess (1) or should I (2)?");scanf("%d",&c);i=5;if(c==2){x("Think a number 1..100");h=100;l=1;goto t;}if(c==1){x("Guess a number 1..100");h=rand()%100+1;goto g;}return 0;t:if(!i--)goto u;printf("%d (1)higher (2)lower (3)correct",g=rand()%(h-l)+l);scanf("%d",&c);if(c==1)l=g;if(c==2)h=g;if(c==3)goto c;goto t;g:if (!i--)goto c;scanf("%d",&g);if(g>h)x("lower");if(g<h)x("higher");if(g==h){x("correct");goto u;}goto g;u:x("You win");goto p;c:x("I win");goto p;} ``` * 23/11/2011 16:44:00 **883** nice and cosy * 24/11/2011 09:38:00 **616** fixed & shortened * 24/11/2011 11:52:00 **555** shortened [Answer] # JavaScript New minified version (dropped `var` and reduced `alert` calls: # 268 chars ``` function g(m){n=u(confirm('Player pick?'));function u(p){if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));alert(g<n?'higher':g>n?'lower':'correct')}} ``` To run call `g(100);`, self-execution is not counted, as it adds a variable number of characters (275 chars for `g(100);`). original (somewhere around 600 chars including whitespace): ``` function guessTheNumber(m) { var n = getNum(confirm('Player pick the number?')), g; function getNum(p) { var n; if (p) { do { n = parseInt(prompt('What number?')); } while(isNaN(n) || !n || n > m); } else { n = parseInt(Math.random() * m) + 1; } return n; } while(g!==n) { do { g = parseInt(prompt('Take a guess!')); } while(isNaN(g)); if (g < n) { alert('higher'); } else if (g > n) { alert('lower'); } else { alert('correct!'); } } } ``` Minified **(312)**: ``` function g(m){var g,n=u(confirm('Player pick?'));function u(p){var n;if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));if(g<n) alert('higher');else if(g>n) alert('lower');else alert('correct')}} ``` [Answer] **Python 2.7 ~~334~~ ~~335~~ ~~327~~ ~~314~~ 300 Characters** (My first time golfing) (335) Forgot to escape newline. (327) Removed redundant 100 for randint. Comparison of first character of response, instead of whole string. (314) Updated printing who won. (300) Changed when player was player 1: changed guessing of the number as computer ``` from random import* i=input s="Enter number:" p=i("Player 1/2:")-1 h=100 N=(i(s),randint(1,h))[p] b=l=0 for _ in[0]*5: exec("g=(h+l)/2;r=raw_input('Guessing '+`g`+':')[0];exec('h=g','l=g')[r=='l'];b=r=='c'","g=i(s);b=g==N;print(('higher','lower')[N<g],'correct')[b]")[p] if b:break print 1+b,"won" ``` [Answer] ## BASIC, 184 ``` 100 INPUT "P1 NUMBER? "; 200 FOR I%=1 TO 5 300 INPUT "P2 GUESS? ";G% 400 INPUT "P1 SENTENCE? ";S$ 500 IF S$="CORRECT" THEN 800 600 NEXT I% 700 PRINT "WINNER 1":END 800 PRINT "WINNER 2" ``` Here's the no-AI version. [Answer] **Lua 360 Chars** ``` i=io.read p=print I=5 N=100 math.randomseed(os.time())r=math.random p"Play as player one or two?"o=i"*n">1 _=o and p("Input number between 1 and",N)n=o and i"*n"or r(I,N)l,u=1,N for k=1,I do p"Guess!"g=o and r(l,u)or i"*n"p("Guessed",g)if n==g then p"Correct"break elseif n>g then p"Higher"l=g else p"Lower"u=g end end p(o and"I"or"You",n==g and"Won"or"Loose") ``` Non-golfed version: ``` i=io.read p=print I=5 N=100 math.randomseed(os.time()) -- Make things less predictable r=math.random p"Play as player one or two?" o=i"*n">1 _=o and p("Input number between 1 and",N) -- if one, ask for number n=o and i"*n"or r(I,N) -- get number from user or random l,u=1,N -- boundaries for doing "smart" guessing for k=1,I do p"Guess!" g=o and r(l,u)or i"*n" -- get guess (random or input) p("Guessed",g) if n==g then p"Correct!"break -- break loop if guessed correctly elseif n>g then -- if guess to low p"Higher"l=g else -- print + update boundaries p"Lower"u=g end end p(o and"I"or"You",n==g and"Won"or"Loose") -- Determine outcome! ``` [Answer] # Javascript This is about 800 characters, and includes your basic binary selection 'AI' for the computer player half. I could probably save a few characters if I got rid of all my `var`s but I don't like leaking variables even while code golfing. I also did a two step "Is this correct?"/"Is this higher?" thing with confirm pop-ups rather than giving a prompt pop-up and checking for "correct"/"higher"/"lower" though that could maybe also save some characters, I didn't really check. Also, I only tested it on Firefox 4, so I don't know if some of the things I'm doing work consistently, particularly coalescing an invalid input, parsed as NaN, to a default value in my `wp` function. ``` function game(N, I) { var wa=function(a){window.alert(a)}; var wc=function(s){return window.confirm(s)}; var wp=function(s){return window.prompt(s)}; var ri=function(s,d){return parseInt(wp(s),10)||d}; var m=function(l,h){return Math.round((h+l)/2)}; N = N || pd("Highest possible number?",100); I = I || pd("How many guesses?",5); var p = wc("Be player 2?"); var s = [1,N]; var a = p?Math.ceil(Math.random()*N):Math.min(N,Math.max(1,ri("Pick a number from 1 to " + N,1))); var w = 0; var g = 0; if(p) while(I--){while(!(g = ri("Guess:",0)));if(g==a){wa("correct");w=p+1;break;}else{wa(g<a?"higher":"lower")}} else while(I--){g = m(s[0],s[1]);if(wc("Is "+g+" correct?")) { w=p+1;break;} else if (wc("Is "+g+" higher?")){s=[s[0],g];}else{s=[g,s[1]];}} if(!w)w=!p+1; wa("Player " + w + " wins!"); } game(100,5); ``` [Answer] # Java, 1886 chars ``` import java.io.*;import java.util.*;import java.util.regex.*;public class GuessGame {int L=1;int H=100;int G=5;int N;String HS="higher";String LS="lower";String CS="correct";public static void main(String[] args){if (args.length==2)new GuessGame(Integer.parseInt(args[0]),Integer.parseInt(args[1])).play();else if(args.length==0)new GuessGame(100,5).play();else System.out.println("usage GuessGame HighInteger NumberGuess");}GuessGame(int H,int G){this.H = H;this.G = G;}void play(){int pNum=getInt("Play As Player 1 or Player 2?","1|2");if(pNum==1)playP2();else playP1();System.out.println("The number was "+N);}int getInt(String pmpt,String val){BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));int i=0;Pattern p=Pattern.compile(val);boolean fnd=false;String ln="";try{while(!fnd){System.out.println(pmpt);ln=cin.readLine();Matcher m=p.matcher(ln);fnd=m.find();}i=Integer.parseInt(ln);} catch (Exception ex) {}return i;}String processGuess(int g){if(N>g)return HS;else if(N<g)return LS;else return CS;}void playP1(){N=new Random().nextInt(H);for(;G>0;G--){String rslt=processGuess(getInt("Player 2, enter your guess:","\\d?"));System.out.println(rslt);if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}void playP2() {N=getInt("Player 1, enter your number:", "\\d+");int max=H;int min=L;int nextGuess=min+(max-min)/2;for (;G>0;G--){System.out.println("Player 2, enter your guess:" + nextGuess);String rslt=processGuess(nextGuess);System.out.println(rslt);if(rslt.equals(HS)){min=nextGuess+1;nextGuess=fuzzify(nextGuess+(max-nextGuess)/2,min,max);}if (rslt.equals(LS)){max=nextGuess-1;nextGuess=fuzzify(nextGuess-(nextGuess-min)/2,min,max);}if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}int fuzzify(int i,int mn,int mx){int fz=new Random().nextInt(3);if(fz==1)return Math.max(mn,--i);if(fz==2)return Math.min(mx,++i);return i;}} ``` Non golfed version: ``` import java.io.*; import java.util.*; import java.util.regex.*; public class GuessGame { int L = 1; int H = 100; int G = 5; int N; String HS = "higher"; String LS = "lower"; String CS = "correct"; public static void main(String[] args) { if (args.length == 2) new GuessGame(Integer.parseInt(args[0]), Integer.parseInt(args[1])).play(); else if (args.length == 0) new GuessGame(100, 5).play(); else System.out.println("usage GuessGame HighInteger NumberGuess"); } GuessGame(int H, int G) { this.H = H; this.G = G; } void play() { int pNum = getInt("Play As Player 1 or Player 2?","1|2"); if (pNum == 1) playP2(); else playP1(); System.out.println("The number was " + N); } int getInt(String pmpt, String val) { BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); int i = 0; Pattern p = Pattern.compile(val); boolean fnd = false; String ln = ""; try { while (!fnd) { System.out.println(pmpt); ln = cin.readLine(); Matcher m = p.matcher(ln); fnd = m.find(); } i = Integer.parseInt(ln); } catch (Exception ex) {} return i; } String processGuess(int g) { if (N > g) return HS; else if (N < g) return LS; else return CS; } void playP1() { N = new Random().nextInt(H); for (; G > 0; G--) { String rslt = processGuess(getInt("Player 2, enter your guess:", "\\d?")); System.out.println(rslt); if (rslt.equals(CS)) { System.out.println("Player 2 wins!"); break; } } } void playP2() { N = getInt("Player 1, enter your number:", "\\d+"); int max = H; int min = L; int nextGuess = min + (max - min) / 2; for (; G > 0; G--) { System.out.println("Player 2, enter your guess:" + nextGuess); String rslt = processGuess(nextGuess); System.out.println(rslt); if (rslt.equals(HS)) { min = nextGuess + 1; nextGuess = fuzzify(nextGuess + (max - nextGuess) / 2, min, max); } if (rslt.equals(LS)) { max = nextGuess - 1; nextGuess = fuzzify(nextGuess - (nextGuess - min) / 2, min, max); } if (rslt.equals(CS)) { System.out.println("Player 2 wins!"); break; } } } int fuzzify(int i, int mn, int mx) { int fz = new Random().nextInt(3); if (fz == 1) return Math.max(mn, --i); if (fz == 2) return Math.min(mx, ++i); return i; } } ``` [Answer] # Alarm Clock Radio, 5756 bits (2159 bytes) **Coming soon to an alarm clock near you!** *Newlines are for readability only.* ASCII values are used occasionally in place of the literal numeric display on-screen. Fits specs. Uses defaults for `A` and `I`. On the first input, use NULL to be the guesser, otherwise you will set the number. **PADSIZE MUST BE 4! CELLS MUST BE 7-BIT AND WRAP!** Turing-complete! Outputs `higher`, `lower`, `correct`, `you won`, and `you lost`. ``` }+>,[,>>+++++++[>>>>>>>+++++++>+++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++]>>>>>>>++++++.>>>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++>+>>>>>>>]>+++.+++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>+++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++.[+]+][++++[+++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++>,[+[+++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++>++>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++.++++++++.[+ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>.+++++++++++++.[+ ]+][++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++>+>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. ++++++++++++.+++..++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++>+>>>>>>>]>+++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++.>>>>>>>[+]>>>>>>>+++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++]]][>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.+++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++>+>>>>>>>]>+++.++[+++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+ +>>>>>>>]>.+++.++++.+.>>>>>>>[+]+][+++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++. ++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++>+>>>>>>>]>+++.++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.] ``` [Answer] ## Ruby 1.9 (298) ``` b=->f{puts "> "+f;gets} a=->f{b[f].to_i} q=a["Player 1 or 2?"] i,j,g=100,1 n=q<2?a["Enter number:"]:rand(i)+j 5.times{q<2?(g=j+(i-j)/2 c=b["Guessing, #{g}"] c[0]==?c?break: c[0]==?h?j=g :i=g):( g=a["Guess:"] puts g==n ?"correct":g<n ?"higher":"lower" g==n&&break)} puts "Player #{g==n ?2:1} won!" ``` Not very friendly instructions though. [Answer] I felt the need to do Java some justice. :) # Java - ~~486~~ ~~437~~ ~~421~~ 414 **Golfed** ``` import java.util.*;class GuessANumber{static<T>void p(T p){System.out.println(p);}static int i(){return new Scanner(System.in).nextInt();}public static void main(String[]a){int c,g,f=101,i=0;p("Pick (1) or guess (2)?");c=i();if(c==1)p("Pick a number (1-100)");g=c==1?i():new Random().nextInt(100);while(f!=g&&i++<5){p("Guess:");f=c==2?i():f>g?f/2:f+f/2;if(c==1)p(f);p(f>g?"lower":"higher");}if(f==g)p("correct");}} ``` **Slightly Ungolfed** ``` import java.util.*; class a{ static<T>void p(T p){ System.out.println(p); } static int i(){ return new Scanner(System.in).nextInt(); } public static void main(String[]a){ int c,g,f=101,i=0; p("Pick (1) or guess (2)?"); c=i(); if(c==1)p("Pick a number (1-100)"); g=c==1?i():new Random().nextInt(100); while(f!=g&&i++<5){ p("Guess:"); f=c==2?i():f>g?f/2:f+f/2; if(c==1)p(f); p(f>g?"lower":"higher"); } if(f==g)p("correct"); } } ``` ]
[Question] [ Given an integer \$ n \ge 2 \$, you need to calculate \$ \lfloor n \log\_2(n) \rfloor \$, assuming all integers in your language are unbounded. However, you may **not** ignore floating-point errors - for example, in python `lambda n:int(n*math.log2(n))` is an invalid solution, because for example for `n=10**15`, `int(n*math.log2(n))` is 49828921423310432, while the actual answer is 49828921423310435. ## Rules * You can assume the input is an integer \$ n \ge 2 \$ * You may use any [reasonable I/O method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed ## Test cases ``` 2 -> 2 3 -> 4 4 -> 8 5 -> 11 6 -> 15 7 -> 19 8 -> 24 9 -> 28 10 -> 33 100 -> 664 1000 -> 9965 10000 -> 132877 ``` 10 brownie points for beating my 4 byte 05AB1E answer. This is code golf, so the shortest answer wins. Good luck! [Answer] # [Python 3](https://docs.python.org/3/), 25 bytes ``` lambda n:len(bin(n**n))-3 ``` [Try it online!](https://tio.run/##DcvLCkBAGIbhvav4sxr6lPOpuBEsCJniG8nG1Y@pd/f03t97GGZ270Z7zteyzsL23KgWTcUwZBBETs0jFE0ZUmTIUaBEhRoNktgVT60n96P5KkL8qPchu3Kr/QE "Python 3 – Try It Online") If the answer is \$x\$, then \$x+1 > n\log{n} \ge x\$ holds true, which means \$2^{x+1} > n^n \ge 2^x\$. So we can simply count the number of bits in the binary representation of \$n^n\$. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes ``` ebL‹ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=ebL%E2%80%B9&inputs=10000&header=&footer=) Translation of @ManishKundu's [Python answer](https://codegolf.stackexchange.com/a/226215/98955). # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` *`BL’ ``` [Try it online!](https://tio.run/##y0rNyan8/18rwcnnUcPM////GxoAAQA "Jelly – Try It Online") Ditto. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page) ``` *ḃ2L ``` A monadic Link accepting an integer, \$n>1\$, that yields \$ \lfloor n \log\_2(n) \rfloor \$. **[Try it online!](https://tio.run/##y0rNyan8/1/r4Y5mI5//h9sfNa35/z/aSMdYx0THVMdMx1zHQsdSx9AAiMAYQhjEAgA "Jelly – Try It Online")** ### How? As noted by [Manish Kundu](https://codegolf.stackexchange.com/a/226215/53748) the answer is one less than the number of binary digits of \$n^n\$. This can be achieved in Jelly in five bytes in a few ways one of which is: `*b2L’`. Note, however, that \$n^n=2^x-1\$ has no integer solutions except \$n=x=1\$ (see [Wolfram Alpha](https://www.wolframalpha.com/input/?i=solve+n%5En%3D2%5Ex-1%2Cx%3E1%2Cn%3E1+over+the+integers)\*) and that the [bijective base two](https://en.wikipedia.org/wiki/Bijective_numeration) representation of a number always has one less digit than the standard base two representation except when the number is of the form \$2^k-1\$ (when both representations are identical, a string of \$k\$ ones). Since \$n=1\$ is invalid input we can, therefore, count the number of digits in the bijective base two representation of \$n^n\$. ``` *ḃ2L - Link: integer, n * - (n) exponentiate (n) -> n^n 2 - two ḃ - (n^n) in bijective base (2) L - length ``` \* if someone has a proof, I'll happily put it here! [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` X$tZl*k ``` [Try it online!](https://tio.run/##y00syfn/P9pIwVjBRMFUwUzBXMFCwVLB0ACIwBhGIoHYCJWSqByt7P//AQ) ``` X$tZl*k X$ - sym, implicit input t - duplicate top of stack and push it Zl - log2 * - multiply k - floor ``` This is just what [elementiro](https://codegolf.stackexchange.com/users/98428/elementiro) did except in golfed MATLAB, and since this is my first time posting, I am not sure if this is considered a duplicate. [Answer] # [Ruby](https://www.ruby-lang.org/), 20 bytes ``` ->n{/.$/=~"%b"%n**n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWl9PRd@2Tkk1SUk1T0srr/Z/gUJatFEsF4gygVCGBkAQ@x8A "Ruby – Try It Online") Get the length of the binary string representation of n^n. Basically uses the same formula as Manish Kundu and everybody else after him. Using `bit_width` or `digits(2).size` would make it longer. [Answer] # [Julia](http://julialang.org/), ~~18~~ 24 bytes ``` n->ndigits(n^n,base=2)-1 ``` [Try it online!](https://tio.run/##LY7LCsIwEEX38xVD3STQgnm0TRbpwp3fIAqVthIpozQR/PuYFGdxzxkYmPv8rH4U37S4RM1Ak3/4GBjdqL6PYXaSNyLFOcSADk/@caZ4AYkHlKByatA5DbQ5hYCuoIW@wIIpZxpsgQFxzFQqs0jX6WJFre3a3csilDR9D1eA5bVhRE@4fwfM8948xZVYrLFCN2BV/yuxhUXOOcw0pR8 "Julia 1.0 – Try It Online") port of [Manish Kundu's answer](https://codegolf.stackexchange.com/a/226215/98541) ### previous answer: ``` n->floor(log2(n)n) ``` [Try it online!](https://tio.run/##HY7LCoMwEEX38xWD3Riw4ORlstBFd/2G0kKhRiwhFk2hf28zzuKec2EY5v2N85N@e@j3dB5CXJa1jssk6ySS2PO45Q17vMzTNeUbSDyhBFVSgy7pwJQkAssw0DE8OF7T4BkOqC1UqpDFWs3G6r01h3MhJV3Xlfogvqm9k85L0lIparUycAcIy4oZ54THX4BlPuucckx1brDCfsCqwVBnIWBMr/0P "Julia 1.0 – Try It Online") input needs to be a `BigInt` to avoid floating point errors. Technically invalid because you need to augment the precision for very big numbers (with `setprecision(2048)` for example for `10^100`) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 30 bytes Same approach as [Manish Kundu](https://codegolf.stackexchange.com/a/226215/58563). Expects a BigInt. ``` n=>(g=n=>n?g(n/2n)+1:-1)(n**n) ``` [Try it online!](https://tio.run/##Jcy9DoIwFIbhnav4xh48IMV/STExcfAajANBWjHk1ABxMV57xTi8z/g@qlc11H37HBPxtyZYE8SUyplJOTgl81xopveJJiVxLBSKC3LGgrFkrBhrxoaxZewYOvv1J8M1Sq3vT1V9VwJT4h0BtZfBd03a@WnNsOrYurOMSoioiD4Uvg "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-Mbignum -p`, 24 bytes ``` $_=int$_*(1*$_)->blog(2) ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYzr0QlXkvDUEslXlPXLiknP13DSPP/f0MDIPiXX1CSmZ9X/F/XNykzPa80979uQQ4A "Perl 5 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~17~~ 15 bytes (11 characters) ``` ⌊#*Log2@#⌋& ``` -2 thanks to [ZaMoC](https://codegolf.stackexchange.com/users/67961/zamoc)! [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7/1FPl7KWT366kYPyo55utf8BRZl5JdHKunZp0cqxsWoK@g4K1YY6RjrGOiY6pjpmOuY6FjqWOoYGOgqGBnGGprX/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~10~~ 8 bytes ``` I⊖L↨Xθθ² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyU1uSg1NzWvJDVFwyc1L70kQ8MpsThVIyC/PLVIo1BHoVBTR8FIEwSs//83NDAw@K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the same identity \$ \lfloor n \log\_2 n \rfloor = \lfloor \log\_2 n^n \rfloor \$ as everyone else. (Exponentially slow for large `n` of course, so stick to 4 digit inputs for testing on TIO.) Edit: Saved 2 bytes thanks to @CommandMaster. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 4 bytes ``` mbg< ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/Nynd5v9/QwMDAwA "05AB1E (legacy) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` tl.B^ ``` [Test suite](http://pythtemp.herokuapp.com/?code=tl.B%5E&test_suite=1&test_suite_input=2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A100%0A1000%0A10000&debug=0) A near literal translation of [Manish Kundu](https://codegolf.stackexchange.com/users/77516/manish-kundu)['s Python 3 answer](https://codegolf.stackexchange.com/a/226215/78186). [Answer] # Java, 36 bytes ``` n->n.pow(n.intValue()).bitLength()-1 ``` Accepts a `BigInteger` as input. [Try it online!](https://tio.run/##nZI/a8MwEMVn61NolEp90P8tSTN0KBRaOgS6lAyKIyty5JOwzi4h5LO7SjG0a3XL497j9265Rg2qbDa70bbBd8SbtENP1kHdY0XWI5zN/matom2yWOjXzla8cipG/qYs8gPjaSY/kqIkg7cb3qZULKmzaD5XqjNRHljxPNXPn6x5QdJGd@eTLurHEcsFQvBfAsEifSjXayElrC29ajS0FbK8GIsZK5b7SLoF3xOEdIEcihpUCG4vfpthOBW81@JSSvlv6CoHus6BbnKg2xzoLge6z4EefqDTaxzZcfwG) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~52~~ \$\cdots\$~~35~~ 23 bytes Saved 8 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!! ``` f(n){n=logb(pow(n,n));} ``` [Try it online!](https://tio.run/##XVDbboMwDH3vV1hI1RIa1HIpLWPsZdpXrH2gwbRoNFQkUtEqfn3MUIbWRbKVHPscx0c6Rym7LmeK31RSVscDu1RXpoTiPG67Qhk4p4VifHabAZ0eMKiN/thDAjdPgC8gELAWEArYCNgKiAS4qz7uacyrNp4UsLmgNJhNIsFAdF0KUnJJwSPII8wn/TAM2hiWNviecyhML6FBpurJwClVWYlgTqjxGaIo7Om@t91siGEvh4nylNY2ZZSfWNNI6Idau@bd2zXRG8XaEvD37VvjX/OqBtZ/uFAZNkRbxeP1BXTxhVXOflfhyxGwJySGxWLo5nA3bzKQlO4mDuV9/FDVVM2Z4Y8oEjrZ9p92qaklZ9Y8A@cVKM/1TtFSRoAW0@aYJHo/yraztvuWeZkededcO6c8/wA "C (gcc) – Try It Online") Uses the formula from [Manish Kundu](https://codegolf.stackexchange.com/users/77516/manish-kundu)'s [Python answer](https://codegolf.stackexchange.com/a/226215/9481). [Answer] # MATLAB/Octave, 30 bytes ``` @(x)floor(sym(x)*log2(sym(x))) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCMy0nP79Io7gyF8jWyslPN4KyNTX/pynYKiTmFVtzpWlk5pWYmWgYaWrC2cZIbBMktikS2wyJbY7EtkBiWyKxDQ1QOGg8dC4qP84QZPN/AA "Octave – Try It Online") Anonymous function. The result is symbolic number but can be easily cast to any other type. This solution works as long as the upper bound of `int64` allows it. --- Technically, much better solution is `@(x)floor(x*log2((x)))` (which is **20 bytes** btw) with symbolic input. Since the question says input is integer I couldn't use it though. Because our input is unbounded it works for much much bigger numbers (I managed to calculate 101 000 000 but the calculations took a while and the output in console was truncated, for too big numbers throws an error though). I encourage anyone to check the result for 10300 if their method is capable of working for such big inputs: ``` f(sym(10^300)) = 996578428466208704361095828846817052759449417907374183616426918744780432982587564755041923007811046529897211513075075548047229095279058066482590831899596618155585405797251670592905282757007467500082430012203570937256212532914759940262053756896742020749233906529817764982497756734670715067992925218241378 ``` *...did I mention unlike some of the other answers this takes only ~0.05s for MATLAB to calculate even for that big inputs?* [Answer] # [Pyt](https://github.com/mudkip201/pyt), 5 bytes ``` ṖɓąŁ⁻ ``` [Try it online!](https://tio.run/##K6gs@f//4c5pJycfaT3a@Khx9///hgZAAAA "Pyt – Try It Online") ``` ṖɓąŁ⁻ Ṗ implicit input (n); raise n to the nth power ɓ convert to binary string ąŁ convert string to array of characters and get length ⁻ subtract one; implicit print ``` Port of [Manish Kundu's Python answer](https://codegolf.stackexchange.com/questions/226214/calculate-lfloor-n-log-2n-rfloor-exactly/226215#226215) ]
[Question] [ Sales taxes in the United States are complicated, to say the least. Generally, there's a state sales tax (there are a handful of states that do not collect a state sales tax), but there could also be a county sales tax, a school district sales tax, a municipal (city) sales tax, or a metropolitan area sales tax. There could even be different sales taxes in different parts of a city. For the purposes of this challenge, however, we're going to focus on just the state sales tax. Given a U.S. dollar amount greater than zero (accurate to two decimal places) and a state (either the full name or the two-letter abbreviation, your choice, case doesn't matter), and using the below chart of sales tax percentages, output the corresponding state sales tax required to be collected for that particular sale, accurate and truncated to two decimal places. Please specify how your code handles rounding. ***Edit: The abbreviation for Washington was listed incorrectly as WS instead of WA. Answers may use either abbreviation, since that was my goof.*** ``` State Abbr % Alabama AL 4.00% Alaska AK 0.00% Arizona AZ 5.60% Arkansas AR 6.50% California CA 6.00% Colorado CO 2.90% Connecticut CT 6.35% Delaware DE 0.00% Florida FL 6.00% Georgia GA 4.00% Hawaii HI 4.00% Idaho ID 6.00% Illinois IL 6.25% Indiana IN 7.00% Iowa IA 6.00% Kansas KS 6.50% Kentucky KY 6.00% Louisiana LA 5.00% Maine ME 5.50% Maryland MD 6.00% Massachusetts MA 6.25% Michigan MI 6.00% Minnesota MN 6.875% Mississippi MS 7.00% Missouri MO 4.23% Montana MT 0.00% Nebraska NE 5.50% Nevada NV 4.60% New Hampshire NH 0.00% New Jersey NJ 6.88% New Mexico NM 5.13% New York NY 4.00% North Carolina NC 4.75% North Dakota ND 5.00% Ohio OH 5.75% Oklahoma OK 4.50% Oregon OR 0.00% Pennsylvania PA 6.00% Rhode Island RI 7.00% South Carolina SC 6.00% South Dakota SD 4.50% Tennessee TN 7.00% Texas TX 6.25% Utah UT 4.70% Vermont VT 6.00% Virginia VA 4.30% Washington WA 6.50% West Virginia WV 6.00% Wisconsin WI 5.00% Wyoming WY 4.00% ``` Example for California at 6% state sales tax -- ``` CA 1025.00 61.50 ``` Example for Minnesota at 6.875% -- ``` MN 123.45 8.49 ``` [Answer] # Mathematica, ~~112~~ ~~103~~ ~~77~~ ~~76~~ 66 bytes *Mathematica has a builtin for everything* ``` NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]& ``` Takes a state name (any format; abbreviation or full name) and the dollar amount. [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com) ### Usage ``` f = NumberForm[Interpreter["USState"][#]@"StateSalesTaxRate"#2,{9,2}]& ```   ``` f["CA", 1025.00] ``` > > 61.50 > > > ``` f["miNnNesToA", 123.45] ``` > > 8.49 > > > ### Explanation ``` Interpreter["USState"][#] ``` Interpret the input as a US State name and generate an `Entity`. ``` ... @"StateSalesTaxRate" ``` Get the sales tax rate. ``` ... #2 ``` Multiply that by the second input. ``` NumberForm[..., {9,2}] ``` Format the result into a number with 9 digits to the left of the decimal and 2 digits to the right. [Answer] # [R](https://www.r-project.org/), ~~219~~ 212 bytes ``` function(S,m)sprintf("%.2f",c(4,0,5.6,6.5,6,2.9,6.35,0,6,4,4,6,6.25,7,6,6.5,6,5,5.5,6,6.25,6,6.875,7,4.23,0,5.5,4.6,0,6.88,5.13,4,4.75,5,5.75,4.5,0,6,7,6,4.5,7,6.25,4.7,6,4.3,6.5,6,5,4)[match(S,state.abb)]*m/100) ``` Takes the state as an abbreviation (all caps). `state.abb` is the builtin R data with the state abbreviations in alphabetical order, so it hardcodes the sales taxes, finds the index of the state, calculates the sales tax, and formats to 2 decimal places (output as a string). [Try it online!](https://tio.run/##PU@9DoIwEN59CkJiQs15lrZXMHExzro4GgckEhlAA/X56x0E06Hf333XDrFJDtskNt@@Du27z67QqfEztH1osnSNpkmhzhxoIPTgkcCDwT0jSyx6cHzEMAQFLAniNC2yXGUhtkNjpyZi6GUcy5JpbqUGOSODhbhzuTQKLuYmjkyC/a9x6tZVoX7xs8dQhSdWj4e6b7pdrrWK/IPTMYVcG0LmK@bnC3Nj0ZGKPw "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 134 bytes ``` .•2=Šλ₁ÙH ’€9¿FîβïLT_s€¤Ôтαxì8ÜuK8º'DιÒ—pcλ¯øÒÔ\’þü€ŒβÞéΣŽZê•#.å1kUX0‹i6*т/ëX•޽ì∞в’±₃C¸wiα·¥žYÉúžĆƵ˜šŸ‰Ê‡†Σgλ&/ûjDĆв₆•hR„AB„ .‡#è*т/} ``` [Try it online!](https://tio.run/##Fc8xS8NQFAXg3V9RKCg4tEmhUgcHtYigkyhUEaQtotVFENFFeD4hqGPIUiihsS1oDdYUxLQxEd7pcxEe9i/cPxKfyx0OfOdwjWK1Zh6maY7YY2FJtlVE/AbN9QyxJnF/UXyt4VUNMdjcPjjXgejCmXIVXMEvoXWxURLjubIawSbmnNVVJAYIYcPZ1x4JPjWRtvYunlVHxnvo66FsDj3zdKdiEBs1FuanPI@Xis5lLGL4dOf@DjUXAfHbVRFeNlQgPkRPJru4x1gmE@v7/aclPRkSe8MDMY9YW3WOVDSbR3RSnljac0sXHm8Rc5dX9MnoB70snv7HrtO0Xp0xjULxDw "05AB1E – Try It Online") --- RIP Mathematica wins. --- All this does is compresses the following strings: ``` AKDEMTNHOR CO ALGANYHIWY MO VA SDOK NV UT NC LANDWI NM MENE AZ OH ILMATX CT ARKSWS MN NJ INMSRITN ``` And: ``` 0 2.9 4 4.23 4.3 4.5 4.6 4.7 4.75 5 5.13 5.5 5.6 5.75 6.25 6.35 6.5 6.875 6.88 7 ``` Then uses the index of the input state to determine the index of the rate, defaulting to 6, because there are so many states with 6%. --- For others to consume: ``` AKDEMTNHOR 0 CO 2.9 ALGANYHIWY 4 MO 4.23 VA 4.3 SDOK 4.5 NV 4.6 UT 4.7 NC 4.75 LANDWI 5 NM 5.13 MENE 5.5 AZ 5.6 OH 5.75 CAFLIDIAKYMDMIPASCVTWV 6 ILMATX 6.25 CT 6.35 ARKSWS 6.5 MN 6.875 NJ 6.88 ``` --- Note this only works because I ordered the states such that no intersection of 2 states creates a different state E.G. (`OHIN` contains `[OH,IN,HI]` whereas `INOH` only contains `[IN,OH]`) --- Most of the ideas for this came from my [previous state-based entry](https://codegolf.stackexchange.com/a/139940/59376). [Answer] ## Pyth, ~~270~~ ~~258~~ ~~233~~ 219 bytes ``` *c@[6Z5.75K6.25 5.5 5 4Z7 6.5J6 7J6.875 7 4J6.35Z6 7 5 4.75 4 4.23J5J5.13 4.6JJ4J4 4.3 4.5Z5.6J.5 4.7K4.5KZ6.5 6.88 5.5J2.9)xc."AZ-íâFT34r7²¨cK'ÉT?Ú5Ï)}4Që7ËÅÖpuªXTiÖ¶7×ì­Éͨ."2w100 ``` Must be passed parameters like so: ``` 1025 CA ``` Explanation: ``` *c@[...)xc."..."2w100 ."..." Decompress the string c 2 Cut the string in chunks of size 2 (states abbreviations) x w Get the index of the second parameter in that string @[ ) Index into the tax array c 100 Generate a percentage * Multiply that with the implicit input at the end Alas, `.Z` makes this longer. Maybe there's a way to write the array more efficiently, by repeating the keys, but I havn't found one yet. ``` Thanks to @Mr.Xcoder. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~594 + 19~~ ~~592~~ ~~580~~ ~~575~~ 412 bytes ``` s->a->{float[]r={0};java.util.Arrays.asList("AL4`AK0`AZ5.6`AR6.5`CA6`CO2.9`CT6.35`DE0`FL6`GA4`HI4`ID6`IL6.25`IN7`IA6`KS6.5`KY6`LA5`ME5.5`MD6`MA6.25`MI6`MN6.875`MS7`MO4.23`MT0`NE5.5`NV4.6`NH0`NJ6.88`NM5.13`NY4`NC4.75`ND5`OH5.75`OK4.5`OR0`PA6`RI7`SC6`SD4.5`TN7`TX6.25`UT4.7`VT6`VA4.3`WS6.5`WV6`WI5`WY4".split("`")).forEach(e->{if(e.contains(s))r[0]=a/100*new Float(e.substring(2));});return s.format("%.2f",r[0]);} ``` [Try it online!](https://tio.run/##RVJdj9owEHznV1iRKiUncHPgmKsoSBEfJSUJFUmhFCGtj0uuoSGJYucqhPjtdJNDOr94PZ7xrHZ8FG@ikxdRdnz5e0tORV4qckSMVipJaVxlB5XkGX0YtFpF9ZwmB3JIhZTEE0lGLi2CSyqhEJ/duV8DVSbZa/sDmKW5UG3yjo9GJCZDcpOdkeiMLnF9t9uXw4t5HXwY22UpzpIK6SZS6ZrtMrAXJti/LcrBXnFqwdjmMF526RcYh5z2LJhMTZi5HL7ZDOYOA2fCwXE57Vrg@H1wkL8IauViy8G1LfCmFp48pHl2Q/McLH1On/pYB33wlox2e@CFJvgN118z9PfneP6OtCfwPYs@9sDfMvDHjKLOn1iwnFt1uVww1CxXJvxA75XTh2DMIZjUaIgdhb8a158hCmEdcljbjPZg0zS5WXPYOLhvmUZlkSY4BtAMg8Z5ORWHP3qE00tiPaKHPFOYhtSlYZQ7cz8Unx9N8yGL/pFm8kiR1bNspq93DWNwNQZlpKoyI7J@7YQU7RPtxlq7luP9DdOuk70nfg/4LU9eyAmd9Pckd3siyldp3L9BvYKzVNGJ5pWiBVJUmukxFUWRnusMNeNesxi7aETX1vX2Hw "Java (OpenJDK 8) – Try It Online") [Answer] # Java 8, ~~486~~ ~~467~~ ~~309~~ ~~299~~ ~~290~~ 289 bytes ``` s->a->{float r=6;for(String x:"AKDENHORMT0 CO2.9 ALGANYHIWY4 MO4.23 VA4.3 SDOK4.5 NV4.6 UT4.7 NC4.75 LANDWI5 NM5.13 MENE5.5 AZ5.6 OH5.75 ILMATX6.25 CT6.35 ARKSWS6.5 MN6.875 NJ6.88 MSRINTN7".split(" "))if(x.contains(s))r=new Float(x.replaceAll("[A-Z]",""));return s.format("%.2f",a*r/100);} ``` -19 bytes thanks to *@MagicOctopusUrn* by removing the semicolons. **Explanation:** [Try it here.](https://tio.run/##hZFBb5tAEIXv/hWjlSpBZU8xBpKW2tLKdmpqs0iGxk2iHLYEKtw1IFjSRJF/uztuqHLsZXc073uanbd7@ShHVZ2V@4dfp@JQV42GPfWw04XCvCtTXVQlXvWFP0iVbFsIZVHCywCg1VIXKfzTP8e6Kcqfw7fGlaqkHsJrfzaDFKZwakczOZq95GcNmqnn51VjvCLw9Inx9WIpVtE2TCyYRzZ@BL75wsXNKtjdOBBGDtoTuOYOTiBeRGsHXRDXDnrwLXHwAsScThc2XCx2AUmhi@MJhEuxdInkty6R0co9M8Em5Ml3D20X5omHE5K363gXewSGwsNLYsRXui8hEGG8DRJxwbCtVaENBsw0i9x4wrQqNQXSGq1pNtMy@w1/tyalyWol04wrZbA7Prq9Z0NGLr/JdNeU0CItfiCSvUM7Z0P5vvkwtizTP578AaVbdz8UpduH/FgVD3CgQX1Ud/cgzfMnAMTPrc4OWHUaa5K0Ko0UZV2rZ4PNOTP7emzZLlpWTi/4ry0UbzZ7go7bu46D4@kP) ``` s->a-> // Method with String and float parameters and String return-type float r=6; // Float starting at 6 (most states had 6.00 as tax) for(String x:"...".split(" ")) // Loop over all states + amounts if(x.contains(s)) // If the input-state is found in String `x`: r=new Float(x.replaceAll("[A-Z]","")); // Set float `r` to the amount of this state // End of loop (implicit / single-line body) return s.format("%.2f", // Return result rounded to 2 decimal points: a*r/100); // Float input multiplied by `r` divided by 100 } // End of method ``` [Answer] ## Perl 6, 341 bytes ``` my%a=((<ME NE>X=>5.5),CO=>2.9,MO=>4.23,MN=>6.875,NJ=>6.88,(<LA ND WI>X=>5),(<AK DE MT NH OR>X=>0),(<IN MS RI TN>X=>7),(<AR KS WS>X=>6.5),AZ=>5.6,(<AL GA HI NY WY>X=>4),VA=>4.3,UT=>4.7,(<IL MA TX>X=>6.25),(<CA FL ID IA KY MD MI PA SC VT WV>X=>6),(<OK SD>X=>4.5),NV=>4.6,NM=>5.13,CT=>6.35,OH=>5.75,NC=>4.75).flat;{round $^a*(%a{$^b}/100),0.01} ``` So, huh. This is pretty contrived, I guess. This uses Perl 6's meta-operators, like `X=>` here, which is `X` (cross product) combined with `=>`. That means `<ME NE> X=> 5.5` (where `<ME NE>` means `('ME', 'NE')`) gets `=> 5.5` applied on each element of the array, yielding `ME => 5.5, NE => 5.5`. The parentheses are merely here for precedence... --- As a golfer (erm...), I obviously didn't write that one by hand (except the actual function). So I wrote a meta-golfer to generate the most efficient combination! ``` my %values; my %simple; for lines() { my $abb = m/<[A .. Z]> ** 2/.Str; my $val = m/\d\.\d+/.Str; %values{$val}.push: $abb; %simple{$abb} = $val; } say "(", (join ',', do for %values.kv -> $key, @vals { my $int-key = +$key; if @vals > 1 { "(<{@vals}>X=>$int-key)" } else { "{@vals}=>$int-key" } }), ").flat"; say(); say join ',', do for %simple.kv -> $key, $val { "$key=>" ~ +$val } ``` It generates both the `X=>` cases and the more simple case (with each one being enumerated), and I picked the shortest one (the former). [Answer] # JavaScript (ES6), ~~227~~ 224 bytes Takes input in currying syntax `(s)(v)` where ***s*** is the state and ***v*** is the amount. Uses floor rounding. ``` s=>v=>(v*(p=s=>parseInt(s,36))('3344bk50k4mo28k4we4tm5eg3uw48s5az39i3js5b43yi3ny4fq3h03mk3bg'.substr(p('k039017k00038f00030022h00g000j00k600k080k707h30706800ba0030305ic0303303930460000e00d2'[p(s)*84%943%85])*3,3))/1e3|0)/100 ``` ### Demo ``` let f = s=>v=>(v*(p=s=>parseInt(s,36))('3344bk50k4mo28k4we4tm5eg3uw48s5az39i3js5b43yi3ny4fq3h03mk3bg'.substr(p('k039017k00038f00030022h00g000j00k600k080k707h30706800ba0030305ic0303303930460000e00d2'[p(s)*84%943%85])*3,3))/1e3|0)/100 console.log(f("CA")(1025)) console.log(f("MN")(123.45)) ``` [Answer] # [Kotlin](https://kotlinlang.org), 444 bytes ``` val S="0|AK|DE|MT|NH|OR#2.9|CO#4|AL|GA|HI|NY|WY#4.23|MO#4.3|VA#4.5|OK|SD#4.6|NV#4.7|UT#4.75|NC#5|LA|ND|WI#5.13|NM#5.5|ME|NE#5.6|AZ#5.75|OH#6|CA|FL|ID|IA|KY|MD|MI|PA|SC|VT|WV#6.25|IL|MA|TX#6.35|CT#6.5|AR|KS|WS#6.875|MN#6.88|NJ#7|IN|MS|RI|TN" fun c(t:String,d:Double){ val m=mutableMapOf<String,Double>() S.split("#").map{val s=it.split("|") for (item in s.subList(1, s.size))m.put(item, s[0].toDouble())} System.out.printf("%.2f", m[t]!!*d*.01)} ``` [Try it online!](https://tio.run/##XVBdb9owFH3Pr3ATTbIrZIWAKUWjkpWwkYHNRDIYq/qQtlBFIwERZ1LH4bczp@20D7@ce@495374@85s8/J8/pFtSTJ0fcgJohFUCj3GbO4F/BrhzOtCTvFRYhxDr7BceV0edKBsgXewkBYEZhMkkY160AsLV/iSNiCgQ09gKqEjLGNP8HYHWlkUUCPokY16kN8sWO1s7PUQSnyYIo4QS0xWUBFUjM8SSYhFiuXC6/FAIJ5CSaRfLesIhKlFATnHJMEysaRv2yndBH3oT94VYg2VYB4j1a6zqUvyQM0gMYe8fGo9DqJdfb9ds6PTfEUxLGqTWa6y/Wzz/k30KrmhzEl4td/mhrqey3iR7Y@NqRrm5nceLnM2uwOhuVkXJC9Jxav6fppXhrZbDcl/rhkr@L42LxKbu/XvuNm9zqCMnZzkubIVvqsN39v5ZkPddzzYuC1S3Jq7i4vLx0vut9np3NxSZHlJs8NTNSDycMie33a@YeToEPteOlC31@bCJ8Mhsfs16QfqhtJ2bPuB4L7P/mi3JWV/O/u8e/2vUenGGHR4V/zvO51/AQ "Kotlin – Try It Online") ## Beautified ``` // Tax rate followed by states with that rate separated by pipes, with hashes in between val STATES="0|AK|DE|MT|NH|OR#2.9|CO#4|AL|GA|HI|NY|WY#4.23|MO#4.3|VA#4.5|OK|SD#4.6|NV#4.7|UT#4.75|NC#5|LA|ND|WI#5.13|NM#5.5|ME|NE#5.6|AZ#5.75|OH#6|CA|FL|ID|IA|KY|MD|MI|PA|SC|VT|WV#6.25|IL|MA|TX#6.35|CT#6.5|AR|KS|WS#6.875|MN#6.88|NJ#7|IN|MS|RI|TN" fun function(targetState: String, amount: Double) { // Stores data val m = mutableMapOf<String, Double>() // For each rate STATES.split("#").map { // Split the data out val rateData = it.split("|") // For each state with that rate for (stateCode in rateData.subList(1, rateData.size)) { // Put it in the dataset m.put(stateCode, rateData[0].toDouble()) } } // Print out the tax rate System.out.printf("%.2f", m[targetState]!! * amount * .01) } ``` [Answer] # [Python 3](https://docs.python.org/3/), 303 bytes ``` import re t=re.split("(\d+)","AL4AK0AZ56AR65CA6CO29CT635DE0FL6GA4HI4ID6IL625IN7IA6KS65KY6LA5ME55MD6MA625MI6MN6875MS7MO423MT0NE55NV46NH0NJ688NM513NY4NC475ND5OH575OK45OR0PA6RI7SC6SD45TN7TX625UT47VT6VA43WS65WV6WI5WY4") f=lambda s,a:"%.2f"%({t[i-1]:float(t[i])/10**-~len(t[i])for i in range(1,len(t),2)}[s]*a) ``` [Try it online!](https://tio.run/##Jc3BToNAFIXhfZ@CkDSFSusAc@/UJl1MoFqEGUxBsNYuMAUlQSCUjTH66kh0@edLzmk/@/emtoeh/Gibrle6fNJvunx5aauy11Tt5Xylq4bKA8p9wp8B@R7B4eiE1o0Tow3ultwGeMfpzqOei16AFniSeRz9CME/YMBBbAGEi4KPJjwUElcMRMRESC1bxESOLhOKckfkPa5WUoBpywOVDmUgXQh3wCD0KYR78sBx77HIwcilEEsWP42jjzFlSYwJp3Y6vqYJph6kB6rqk2JTZR@v50y5GNlanS6tQp1qX/2xXJindVE1Wa@NcdKvTTKfL36qvP7voumUUilrpcvqt1wzjT/RDUv/Pl5O80wf2q6se63QZkLODMUkFiyJrg@/ "Python 3 – Try It Online") Very simple: the data is stored data as two chars + list of digits: every percentage is less than 10, thus it can be stored as integer part (1 digit) + decimal part (0-... digit(s)). [Answer] ## [C#](http://csharppad.com/gist/31039087f4b1c522ff58bce73fecec8a), ~~318~~ 309 bytes --- ### Data * **Input** `String` `s` The 2 letter abbreviation of the state uppercase. * **Input** `Double` `v` The value * **Output** `String` The tax value to be collected rounded to 2 decimal places --- ### Golfed ``` (s,v)=>{for(int i=0;i<21;i++)if("NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split(',')[i].Contains(s))return $"{v*(new[]{0,2.9,4,4.23,4.3,4.5,4.6,4.7,4.75,5,5.13,5.5,5.6,5.75,6,6.25,6.35,6.5,6.875,6.88,7}[i]/100):F2}";return "";}; ``` --- ### Ungolfed ``` ( s, v ) => { for( int i = 0; i < 21; i++ ) if( "NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split( ',' )[ i ].Contains( s ) ) return $"{v * ( new[] { 0, 2.9, 4, 4.23, 4.3, 4.5, 4.6, 4.7, 4.75, 5, 5.13, 5.5, 5.6, 5.75, 6, 6.25, 6.35, 6.5, 6.875, 6.88, 7 }[ i ] / 100 ):F2}"; return ""; }; ``` --- ### Ungolfed readable ``` // Takes a 2 letter abbreviation state ( 's' ) and a value ( 'v' ) ( s, v ) => { // Cycles through an array with the states grouped by tax value for( int i = 0; i < 21; i++ ) // Checks if the state group at the current index contains the state 's' if( "NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split( ',' )[ i ].Contains( s ) ) // Returns the value 'v' * the corresponding state percentage divided by 100 return $"{v * ( new[] { 0, 2.9, 4, 4.23, 4.3, 4.5, 4.6, 4.7, 4.75, 5, 5.13, 5.5, 5.6, 5.75, 6, 6.25, 6.35, 6.5, 6.875, 6.88, 7 }[ i ] / 100 ):F2}"; // If the state isn't found, return an empty string return ""; }; ``` --- ### Full code ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestBench { public static class Program { private static Func<String, Double, String> f = ( s, v ) => { for( int i = 0; i < 21; i++ ) if( "NHAKDEMTOR,CO,ALHIGANYWY,MO,VA,SDOK,NV,UT,NC,NDLAWI,NM,MENE,AZ,OH,KYCAFLIDIAMDMIPASCVTWV,ILMATX,CT,ARKSWA,MN,NJ,MSINRITN".Split( ',' )[ i ].Contains( s ) ) return $"{v * ( new[] { 0, 2.9, 4, 4.23, 4.3, 4.5, 4.6, 4.7, 4.75, 5, 5.13, 5.5, 5.6, 5.75, 6, 6.25, 6.35, 6.5, 6.875, 6.88, 7 }[ i ] / 100 ):F2}"; return ""; }; static void Main( string[] args ) { List<KeyValuePair<String, Double>> testCases = new List<KeyValuePair<String, Double>>() { new KeyValuePair<String, Double>( "CA", 1025.0d ), new KeyValuePair<String, Double>( "MN", 123.45d ), }; foreach( KeyValuePair<String, Double> testCase in testCases ) { Console.WriteLine( $" STATE: {testCase.Key}\n VALUE: {testCase.Value}\nOUTPUT: {f( testCase.Key, testCase.Value )}\n" ); } Console.ReadLine(); } } } ``` --- ### Releases * **v1.0** - `318 bytes` - Initial solution. * **v1.1** - `- 9 bytes` - Changed the `.ToString("F2")` used in the first return to interpolated strings. --- [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 277 bytes ``` {split("LANDWI 5 VA 4.3 IACAFLIDKYMDMIPASCVTWV 6 SDOK 4.5 MO 4.23 CO 2.9 NM 5.13 NV 4.6 UT 4.7 NJ 6.88 MENE 5.5 AZ 5.6 ARKSWA 6.5 MN 6.875 MSINRITN 7 ILMATX 6.25 NC 4.75 CT 6.35 ALGANYWYHI 4 OH 5.75 AKDEMTORNH 0",T) for(i in T)if(T[i]~s=".*"$1".*")printf"%.2f\n",$2*T[i+1]*.01} ``` [Try it online!](https://tio.run/##HZBBb4JAEIXv/IoJsYlaQ1xw1R562ADKCrsYWKHaeujFhLSxRk16aNq/bud5@ZaZefNmmPfvj9vt53L67K59v1A2aTVJahRNgoi0itWi0Em@NYnRa1XHjWsbmlKdlDkrJJmSnzCiuKQweCJrSAYiIttwekobx8@M7IqmwXxOJrUp1yWpHT9TUlVet4pr7GMhmfFHrW2lnaUZ6cIo98L5UJKN4SQpdhxH7FAsld2220zThMqM7bio8iQ1rqxsRmN/5Abe4evc76g7kht0h7577fZ/l2c/GPo9AQ5O5@54PfgPQXh4O/qjXjhkzaPYD4Ox@L3dVEHCUzmwAypGrEiMQ@nxD3PgGEnKWEC65JrHGwlPJwBy2gIo5DWwZRQIDdoMdOYeoo2vIMIomEjPQGwww2CGhZiPysiAFWAA@PFxGLAqUS2xcYll13Cu4FxDUkPisBCfVXgbODd3QNfegRktOlo4/wM "AWK – Try It Online") A respectable score, but nowhere near Mathematica. I did add 2 bytes by having a newline print after each check, but I think it's prettier that way :) (Hopefully it's obvious that input should be the state abbreviation and a value on one line. ) ]
[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/15615/edit). Closed 2 years ago. This post was edited and submitted for review 2 years ago and failed to reopen the post: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/15615/edit) Your challenge is to convert a positive rational number into a [finite simple continued fraction](https://en.wikipedia.org/wiki/Continued_fraction)., in 2D, with horizontal fraction bars separating numerator from denominator. [A simple continued fraction only has numerators equal to 1.] Your solution should be able to represent a continued fraction with up to 8 terms. **Input**: The rational number may be input in any format, including (but not restricted to) * string: "7/16" * list: {7, 16}, (7, 16), [7, 16] * simple ordered pair: 7 16 * function: f[7,16] * decimal number: 0.657 **Output**: A continued fraction, in 2D, with horizontal fraction bars separating numerator from denominator. **Only continued fractions with numerators equal to 1 are valid.** It is not necessary to make the font size vary according to depth. A leading zero (for proper fractions) is optional. **Depth**: Your code must be able to display at least 8 levels of depth. **Winning criterion**: Shortest code wins. You must include several test cases showing input and output. **Test Examples** (Input followed by output) | Input | 2D Output | | --- | --- | | \$\frac 5 4\$ | \$1 + \cfrac 1 4\$ | | \$\frac 5 3\$ | \$1 + \cfrac 1 {1 + \cfrac 1 2}\$ | | \$\frac 5 7\$ | \$0 + \cfrac 1 {1 + \cfrac 1 {2 + \cfrac 1 2}}\$ | | \$\frac 9 {16}\$ | \$0 + \cfrac 1 {1 + \cfrac 1 {1 + \cfrac 1 {3 + \cfrac 1 2}}}\$ | | \$\frac {89} {150}\$ | \$0 + \cfrac 1 {1 + \cfrac 1 {1 + \cfrac 1 {2 + \cfrac 1 {5 + \cfrac 1 {1 + \cfrac 1 {1 + \cfrac 1 2}}}}}}\$ | [Answer] ## Python 2, ~~158~~ ~~155~~ ~~147~~ 142 ``` a,b=input() c=[] while b:c+=[a/b];a,b=b,a%b n=len(c) while b<n-1:print' '*(n+b),'1\n',' '*4*b,c[b],'+','-'*(4*(n-b)-7);b+=1 print' '*4*b,c[b] ``` Test: ``` $ python cfrac.py (89,150) 1 0 + ------------------------- 1 1 + --------------------- 1 1 + ----------------- 1 2 + ------------- 1 5 + --------- 1 1 + ----- 1 1 + - 2 ``` --- ## Python 2, alt. version, 95 Basically a port of breadbox's answer. Safer output. ``` a,b=input();i=2 while a%b:print'%*d\n%*d + ---'%(i+5,1,i,a/b);a,b=b,a%b;i+=5 print'%*d'%(i,a/b) ``` Test: ``` $ python cfrac2.py (98,15) 1 6 + --- 1 1 + --- 1 1 + --- 7 ``` [Answer] ## XSLT 1.0 I thought it'd be nice to display the fractions with HTML, so here's an XSLT solution. ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" > <xsl:template match="/f"> <xsl:variable name="c" select="floor(@a div @b)"/> <xsl:variable name="next"> <f a="{@b}" b="{@a mod @b}"/> </xsl:variable> <table> <tr> <td valign="top" rowspan="2" style="padding-top:12px"> <xsl:value-of select="$c"/>+ </td> <td align="center" style="border-bottom:1px solid black">1</td> </tr> <tr> <td> <xsl:apply-templates select="msxsl:node-set($next)"/> </td> </tr> </table> </xsl:template> <xsl:template match="/f[@a mod @b=0]"> <xsl:value-of select="@a div @b"/> </xsl:template> </xsl:stylesheet> ``` To test it, save the xslt as fraction.xslt and open the following file in IE: ``` <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet href="fraction.xslt" type="text/xsl"?> <f a="89" b="150"/> ``` ![89/150](https://i.stack.imgur.com/sF5kD.png) [Answer] # Mathematica, ~~40~~ 36 chars ``` f=If[⌊#⌋≠#,⌊#⌋+"1"/#0[1/(#-⌊#⌋)],#]& ``` **Example:** ``` f[89/150] ``` **Output:** ![Output](https://i.stack.imgur.com/JZbgm.png) [Answer] # Ruby, 175 (with ASCII art) or 47 (without) ## Without ASCII art, 47 ``` n,d=eval gets while d!=0 puts n/d n,d=d,n%d end ``` Since Ruby can't really do graphics like that, I just output the blue numbers in your examples. ``` c:\a\ruby>cont [5,4] 1 4 c:\a\ruby>cont [5,3] 1 1 2 c:\a\ruby>cont [5,7] 0 1 2 2 c:\a\ruby>cont [9,16] 0 1 1 3 2 c:\a\ruby>cont [89,150] 0 1 1 2 5 1 1 2 ``` ## With ASCII Art, ~~181~~ ~~178~~ 175 ``` n,d=eval gets a=[] n,d=d,n%d,a.push(n/d)while d!=0 i=0 j=2*a.size-3 k=a.size-2 a.map{|x|puts' '*i+"#{x}+"+' '*k+?1 i+=2 k-=1 puts' '*i+?-*j j-=2}rescue 0 puts' '*i+a.last.to_s ``` Wow, that ASCII art took up a lot of code, and I was even being evil and using `rescue 0` :P Sample: ``` c:\a\ruby>cont [89,150] 0+ 1 ------------- 1+ 1 ----------- 1+ 1 --------- 2+ 1 ------- 5+ 1 ----- 1+ 1 --- 1+1 - 2 ``` [Answer] ## Sage Notebook, 80 ``` c=continued_fraction(n) LatexExpr('{'+'+\\frac{1}{'.join(map(str,c))+'}'*len(c)) ``` Here `n` can be anything Sage can approximate by a rational / floating point number. Default precision is 53 bits, unless `n` is a `Rational`. Gotta love MathJax. ![enter image description here](https://i.stack.imgur.com/KgMbB.png) [Answer] ## C, 119 characters ``` n,d,r;main(i){for(scanf("%d%d",&n,&d);r=n%d;n=d,d=r,i+=5) printf("%*d\n%*d + ---\n",i+5,1,i,n/d);printf("%*d\n",i,n/d);} ``` Here are some examples of output: ``` $ echo 15 98 | ./cfrac 1 0 + --- 1 6 + --- 1 1 + --- 1 1 + --- 7 $ echo 98 15 | ./cfrac 1 6 + --- 1 1 + --- 1 1 + --- 7 $ echo 98 14 | ./cfrac 7 ``` While the truncated fraction line isn't as pretty-looking as some of the examples here, I wish to point out that this was a common technique for formatting continued fractions back in the days before desktop computers were ubiquitous. --- Okay, here's a much longer version (247 characters) that does full-on formatting of the output: ``` c,h,i,j,n,d,w[99];char s[99][99];main(r){for(scanf("%d%d",&n,&r);d=r;n=d) h+=w[c++]=sprintf(s[c],"%d + ",n/d,r=n%d);for(;j+=w[i],i<c-1;puts("")) for(printf("%*d\n%*s",j+(r=h-j)/2,1,j,s[i++]);--r;printf("-")); s[i][w[i]-2]=0;printf("%*s\n",j-1,s[i]);} ``` Some examples of its output: ``` $ echo 89 150 | ./cfr 1 0 + --------------------------- 1 1 + ----------------------- 1 1 + ------------------- 1 2 + --------------- 1 5 + ----------- 1 1 + ------- 1 1 + --- 2 $ echo 151 8919829 | ./cfr 1 0 + ---------------------------- 1 59071 + -------------------- 1 1 + ---------------- 1 2 + ------------ 1 1 + -------- 1 1 + ---- 21 $ echo 293993561 26142953 | ./cfr 1 11 + --------------------- 1 4 + ----------------- 1 14 + ------------ 1 4410 + ----- 104 ``` [Answer] ## APL (78) ``` {(v↑' '⍪⍉⍪⍕⍺),(' +'↑⍨v←⊃⍴x),x←('1'↑⍨⊃⌽⍴v)⍪v←'─'⍪⍕⍪⍵}/⊃{⍵≤1:⍺⋄a w←0⍵⊤⍺⋄a,⍵∇w}/⎕ ``` Example: ``` {(v↑' '⍪⍉⍪⍕⍺),(' +'↑⍨v←⊃⍴x),x←('1'↑⍨⊃⌽⍴v)⍪v←'─'⍪⍕⍪⍵}/⊃{⍵≤1:⍺⋄a w←0⍵⊤⍺⋄a,⍵∇w}/⎕ ⎕: 89 150 1 0+───────────── 1 1+─────────── 1 1+───────── 1 2+─────── 1 5+───── 1 1+─── 1 1+─ 2 ``` [Answer] ## Mathematica, 77 ``` Fold[#2+1/ToString[#1]&,First[#1],Rest[#1]]&[Reverse[ContinuedFraction[#1]]]& ``` Just learned Mathematica for this. Takes a surprisingly long program to do this. [Answer] ### Perl ~~128~~ 114 chars ``` ($a,$b)=split;$_=" "x7;until($b<2){$==$a/$b;($a,$b)=($b,$a%$b);$_.="1\e[B\e[7D$= + ---------\e[B\e[4D"}$_.="$a\n" ``` But as this use console placement, you have to clear console in order before run: ``` clear perl -pe '($a,$b)=split;$_=" "x7;until($b<2){$==$a/$b;($a,$b)=($b,$a%$b);$_.= "1\e[B\e[7D$= + ---------\e[B\e[4D"}$_.="$a\n"' <<<$'5 7 \n189 53 \n9 16 \n89 150 ' ``` output: ``` 1 0 + --------- 1 1 + --------- 1 2 + --------- 2 1 3 + --------- 1 1 + --------- 1 1 + --------- 1 3 + --------- 1 3 + --------- 2 1 0 + --------- 1 1 + --------- 1 1 + --------- 1 3 + --------- 2 1 0 + --------- 1 1 + --------- 1 1 + --------- 1 2 + --------- 1 5 + --------- 1 1 + --------- 1 1 + --------- 2 ``` ### First post: 128 chars ``` ($a,$b)=split;$c=7;while($b>1){$==$a/$b;($a,$b)=($b,$a%$b);printf"%s1\n%${c}d + %s\n"," "x($c+=5),$=,"-"x9}printf" %${c}d\n",$= ``` Splitted for *cut'n paste*: ``` perl -ne '($a,$b)=split;$c=7;while($b>1){$==$a/$b;($a,$b)=($b,$a%$b);printf "%s1\n%${c}d + %s\n"," "x($c+=5),$=,"-"x9}printf" %${c}d\n",$a' \ <<<$'5 7 \n189 53 \n9 16 \n89 150 ' ``` Will render: ``` 1 0 + --------- 1 1 + --------- 1 2 + --------- 2 1 3 + --------- 1 1 + --------- 1 1 + --------- 1 3 + --------- 1 3 + --------- 2 1 0 + --------- 1 1 + --------- 1 1 + --------- 1 3 + --------- 2 1 0 + --------- 1 1 + --------- 1 1 + --------- 1 2 + --------- 1 5 + --------- 1 1 + --------- 1 1 + --------- 2 ``` ### Same using LaTeX: ``` perl -ne 'END{print "\\end{document}\n";};BEGIN{print "\\documentclass{article}\\pagestyle". "{empty}\\begin{document}\n";};($a,$b)=split;$c="";print "\$ $a / $b = ";while($b>1){$==$a /$b;($a,$b)=($b,$a%$b);printf"%s + \\frac{1}{",$=;$c.="}";}printf"%d%s\$\n\n",$a,$c' \ <<<$'5 7 \n189 53 \n9 16 \n89 150 ' >fracts.tex pslatex fracts.tex dvips -f -ta4 <fracts.dvi | gs -sDEVICE=pnmraw -r600 -sOutputFile=- -q -dNOPAUSE - -c quit | pnmcrop | pnmscale .3 | pnmtopng >fracts.png ``` ![Latex Picture](https://i.stack.imgur.com/TwwSf.png) [Answer] # Perl : *~~140~~* ,*~~133~~* 121 chars ``` ($a,$b)=<STDIN>;while($b>1) {$g=$i+++4;print" "x$g."1\n"." "x$i,int($a/$b)."+---\n";($a=$b)=($b,$a%$b)} print" "x$g."$a\n" ``` **example :** #perl fraction.pl 5 7 ``` 1 0+--- 1 1+--- 1 2+--- 2 ``` [Answer] ## Razor Leaf on Firefox, 108 ~~127~~ ``` %r=(i,n,d)=> mn"#{n/d|0}" if i<8&&n%d mo"+" mfrac mn"1" me%r(i+1,d,n%d) math%[a,b]=data;r(0,a,b) ``` ~~The prompt really hurts there…~~ Oh, you mean I get to pick? Okay, it’s a list. Anyways, good luck getting this to run. [Answer] ## Game Maker Language (Script), 61 71 ``` a=argument0;b=argument1;while b!=0{c+=string(a/b)a,b=b,a mod b}return c ``` Compile with all uninitialized variables as `0`. [Answer] Assuming the input numbers as co-prime, call this process function with numerator and denominator. It can go to any depth until it finds the continued form, no limit Written in JAVA (238 characters) ``` String space = ""; private void process(int n, int d) { System.out.println(space+(n/d)+" + 1"); space += " "; System.out.println(space+"------"); if((n % d)==1) System.out.println(space+d); else process(d,(n % d)); } ``` process(89,150); ``` 0 + 1 ------ 1 + 1 ------ 1 + 1 ------ 2 + 1 ------ 5 + 1 ------ 1 + 1 ------ 1 + 1 ------ 2 ``` process(973,13421); ``` 0 + 1 ------ 13 + 1 ------ 1 + 1 ------ 3 + 1 ------ 1 + 1 ------ 5 + 1 ------ 3 + 1 ------ 1 + 1 ------ 1 + 1 ------ 4 ``` [Answer] # K, 136 ``` {-1@((!#j)#\:" "),'j:(,/{(x,"+ 1";(" ",(2*y)#"-"),"\t")}'[a;1+|!#a:$-1_i]),$*|i:*:'1_{(i;x 2;x[1]-(i:x[1]div x 2)*x@2)}\[{~0~*|x};1,x];} ``` . ``` k)f:{-1@((!#j)#\:" "),'j:(,/{(x,"+ 1";(" ",(2*y)#"-"),"\t")}'[a;1+|!#a:$-1_i]),$*|i:*:'1_{(i;x 2;x[1]-(i:x[1]div x 2)*x@2)}\[{~0~*|x};1,x];} k)f[5 4] 1+ 1 -- 4 k)f[5 3] 1+ 1 ---- 1+ 1 -- 2 k)f[5 7] 0+ 1 ------ 1+ 1 ---- 2+ 1 -- 2 k)f[9 16] 0+ 1 -------- 1+ 1 ------ 1+ 1 ---- 3+ 1 -- 2 k)f[89 150] 0+ 1 -------------- 1+ 1 ------------ 1+ 1 ---------- 2+ 1 -------- 5+ 1 ------ 1+ 1 ---- 1+ 1 -- 2 ``` ]
[Question] [ # Background The Python code ``` ((((((((n%35)^11)*195)|53)&181)+n)%168)*n)+83 ``` produces 74 distinct primes for \$0 \le n \le 73\$. This code also works in Java. The operators are as follows: * `+` is addition * `*` is multiplication * `%` is modulus * `&` is bitwise AND * `|` is bitwise OR * `^` is bitwise XOR The produced primes are: `83, 97, 113, 251, 311, 173, 197, 503, 571, 281, 313, 787, 863, 421, 461, 1103, 547, 593, 1361, 1451, 743, 797, 1733, 1831, 1931, 1033, 1097, 2243, 1231, 1301, 1373, 2687, 1523, 1601, 3041, 3163, 1847, 1933, 3541, 3671, 2203, 2297, 4073, 4211, 2591, 2693, 4637, 4783, 3011, 3121, 5233, 3347, 3463, 5701, 5861, 3823, 3947, 6353, 6521, 6691, 4463, 4597, 7213, 4871, 5011, 5153, 7937, 5443, 5591, 8501, 8693, 6047, 6203, 9281`. # Task Given an input integer \$n\$ output one of the primes from the above list, such that every output is distinct. # Rules * \$n\$ will be between 0 and 73, inclusive. * You can receive input through any of the standard IO methods. * Leading zeroes are not allowed in output. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # x86 Machine Code, 23 bytes ``` 86 89 C8 D4 23 34 0B 6B C0 C3 0C 35 24 B5 00 C8 D4 A8 F6 E1 83 C0 53 C3 ``` **[Try it online!](https://tio.run/##bZPJTsMwFEX3/oonqiKGthBCoYDCjrIDJFhWIMdxUyPbiWIXDOLbCXbIaPDiLU7um64drBQVMf@YpoSUMyY15S/qQ2psQGZ5QdfMlLdU0gJreqc3DwUT9BJBfUT2ZiPFZgKUmBZjLGwM59A/I8AcxlEPXwHeQOTwkaVttskKV4NPIAiG2c@RRa2OiS1vmrswPQsqnQFbdM/KDyC4mO@3@qpsVXceDut@RRZ108uk6b8IBrrdyKFOmDRCwocFDyOLPDuCs8V/dnS4b4elncluzX6LOr23J@H73lSVI4twILdTLUI0qhF5Tyj4Z@QS3RAG9hRL5ZQaTWUyAazUVjCZgqMQMw1MwXHXtaC6nKU8izkIzCRCLl56d0pjd1exQU9Z/ucRkfpbgwnmdmX/7fWzPs3vmtigFudbtam290nsk/vl8vHmCZZZIbB@1IXXOC/sz7D2XVW5fRUnXTsmCQyLE5E3m56ftvRVOq/t2si3pH6@fSMRaof6dWmGFWGfsDNO9AYqG1Y6ul7pcbKSO6j8JmuOU1VORXjyAw "Assembly (gcc, x64, Linux) – Try It Online")** The above bytes of code define a function that returns the \$n\$th prime, according to the formula given in the challenge. The function accepts a single argument, \$n\$, which is passed in the `ECX` register. It returns the result in the `AX` register. (Note: A 16-bit value is returned—the caller is responsible for zero-extending that 16-bit value in `AX` to a 32-bit value in `EAX`, if desired. Add one byte for a `CWDE` instruction if you think that is cheating!) This is a custom calling convention, but it isn't particularly "weird", and machine/assembly language submissions are allowed to define a custom calling convention. Credit where credit is due: this code is based on [EasyasPi's x86 submission](https://codegolf.stackexchange.com/a/217201), but carefully optimized for size. In particular, I've chosen to target 32-bit x86 so that I can use the long-obsolete [`AAM` instruction](https://www.felixcloutier.com/x86/aam), which is not supported in x86-64 "long" mode. `AAM` was designed into the architecture as a way to convert from binary to binary-coded decimal (BCD). To do this, it divides the `AL` register by 10, storing the quotient in `AH` and the remainder in `AL`. (Note that this is the *reverse* of what the `DIV` instruction produces!) Intel's original manuals documented `AAM` as a one-byte instruction, but it was actually encoded with two bytes, where the second byte was 10—the divisor for `AL`. Changing that second byte to another value allows dividing `AL` by an arbitrary value, essentially giving x86 an instruction to divide by an 8-bit intermediate. This trick is used twice, to great effect. (There is also a complementary `AAD` instruction, which allows multiplying by an arbitrary 8-bit immediate value, but that did not result in any savings, since it actually performs the multiplication on `AH`, instead of `AL`, and the shift that is required to support that requires 2 bytes, plus the 2 bytes for `AAD`, which is more than the 3 bytes required to encode the `IMUL reg, reg, imm`.) There are myriad other size optimizations as well, compared to EasyasPi's code. Here are the ungolfed assembly mnemonics: ``` ; Input(s): ; ecx = The zero-based index of the prime to generate (i.e., "n"). ; (Note: This is assumed to be a value from 0 to 73.) ; Output(s): ; ax = The nth prime. ; (Note: This is a 16-bit unsigned integer; ; caller must zero-extend if desired.) ; Clobbers: ; eax, flags GenerateNthPrime: 89 C8 mov eax, ecx # make a copy of the input (ecx) in eax D4 23 aam 35 # al %= 35 ; ah = al / 35 34 0B xor al, 11 # al ^= 11 6B C0 C3 imul eax, eax, -61 # ax = (al * 195) 0C 35 or al, 53 # al |= 53 24 B5 and al, 181 # al &= 181 00 C8 add al, cl # al += cl D4 A8 aam 168 # al %= 168 ; ah = al / 168 F6 E1 mul cl # ax = (al * cl) 83 C0 53 add eax, 83 # ax += 83 98 # cwde # eax = ax (sign-extend, assuming sign bit is 0) C3 ret ``` Note the `cwde` instruction immediately before the `ret`urn instruction there, which is commented out. For the purposes of this submission, this instruction is functionally equivalent to `movzx eax, ax`, which is what the caller of this function would normally use to zero-extend its 16-bit result (`ax`) to a 32-bit result (`eax`). However, `cwde` is encoded in only 1 byte, as opposed to the 3 bytes required by `movzx`. As I mentioned above, if you don't think it's legit that I return a 16-bit result, then add the `cwde` instruction to increase the total size of the function by only one byte. [Answer] # JavaScript (ES6), ~~38~~ 36 bytes *Saved 2 bytes thanks to @tsh* A slightly size-optimized version of the original formula. ``` n=>(((n%35^11)*6.09&4?13:53)+n)*n+83 ``` [Try it online!](https://tio.run/##DcZLDoJADADQPafoRtMySJhU/FcPYjSZAGMgpDVg3BjPPvpWbwjvMDdT/3yt1NouRUkqZ0TUBdd37ynflNV@ub54PtRMTilXt@MUbcIg11uhIFAdQeEksOV/nCP4ZACN6WxjV472QC0gohJl3/QD "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~22~~ 21 bytes -1 byte thanks to Command Master The first part of the code is shorter when replaced by a binary lookup table. ``` •4àт©Á•bsè40*13++*83+ ``` [Try it online!](https://tio.run/##Fc@7UQNRDIXhVhR7FVjPa2rxOGBnCIgI3AC4Eg8RtOGtgBZoZP3fTDPnG0nn4/q6vr/t@//nd273v9vjd/tiXq/bTx4PFstyOMWy7@ejiqm4SqikSqm0ylA5qbwQzZjcAIYwiGEMZCiDGc5xPvfgHOc4xznOcY5zXOACF/MgLnCBC1zgAhe4xCUucTk/wyUucYlLXOIKV7jCFa5mBVzhCle4wjWucY1rXON6dsU1rnGNG7iBG7gRlyc "05AB1E – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~168~~ 166 bytes ``` .+ $*1¶$&$* \G1{35} ^((1{16})*)(1{8}|())(1{4})?(11|())(1|()) $1$#4$*8$*1$5$#7$*2$*1$#9$* \G1 195$* 1{256} (1{128})?1*¶ $1$'53$*1¶ 1{168} 1(?=1*¶(1*)) $1 ¶1* 83$* 1 ``` [Try it online!](https://tio.run/##JY4xDoMwDEV3XwO3dVwJyYRAGCpGLlFVdOjQpUPFluZaHICLpTYs1rNsv@/va3l/ngV6j7ytAFjPcKJpLvUVkGVb8YwM90mSDxngQSRJuuzYKcT8I2fQZjeSyNFZBRSsWuSoDgxY9ciNYTUcNpAhKElqQqdakzZRJWJP6O0l@D0dLC3qhtB4syEJ73bYVmGI3iSl/AE "Retina 0.8.2 – Try It Online") Link includes test suite that generates the results for `n=0..73`. Based on @Arnauld's rearrangement that reduces the bitwise or into an addition. Explanation: ``` .+ $*1¶$&$* ``` Make two unary copies of `n`. ``` \G1{35} ``` Reduce modulo 35. ``` ^((1{16})*)(1{8}|())(1{4})?(11|())(1|()) $1$#4$*8$*1$5$#7$*2$*1$#9$* ``` Bitwise Xor with 11. This is done by breaking the number down into a multiple of 16 plus optional matches of 8, 4, 2 and 1, adding 8, 2, and 1 only when the corresponding match is absent in the original number. ``` \G1 195$* ``` Multiply by 195. ``` 1{256} (1{128})?1*¶ $1$'53$*1¶ ``` Bitwise And with 128 (implemented via %256/128\*128) and add on 53 and `n`. ``` 1{168} ``` Reduce modulo 168. (No `\G` is necessary as `n` is less than 168.) ``` 1(?=1*¶(1*)) $1 ``` Multiply by `n`. ``` ¶1* 83$* ``` Add 83 and remove the copy of `n`. ``` 1 ``` Convert to decimal. [Answer] # [C (gcc)](https://gcc.gnu.org/), 43 bytes ``` f(n){n=('v3ff'>>n%35%31&1?13+n:53+n)*n+83;} ``` [Try it online!](https://tio.run/##hVJdb9pAEHznV5yQSEwwku/29nyOC32o@isKD8jYCUp7iXCUIiH@et2dhdKmqlRLXu3N7s7MfTTzh6YZhi5L02NaZLdv1HW3y2WaEE/I3tiPlmbpniVM79IsUn0adunVfNvsUjYdHUdGPgDt4aVtXtvtl7VZmGOk3FRlbqyVxLHNDVkJtpSlRYELybgUzEWtyrKMUohBMu8E8wETVhs9RioMk6IelKXHkMqUhFok1CqNhSIFqs6h0TrFqdAIIy5A0LJDNQCnwquZoGwQFTbJiRUP6tfBkXNg9kV5dgucK8QAlz4QqiWOQQSVE1sSKSAEZvJBjwC6HLErinBCFaqBWPLAmAoBzF77PUO3dDgvH@GHlZ8t62FAlz32y@onMvijugqFMqv/So79VOvtNY@b/Z3Etnlq9@frG68On93qUH2Sn8e5@XNN48tc97w3Ga5@l7btQcaK@pJ@kKupzWymq6k5P5JfDyVJpxbqd3AvMB7he7QV9PqydGr9u@FlLy1dNp5szXxpJE76VRK3KTd9ft1Qv1i06wvtafRf58T/dP63lgppVy62z@1XkdPwo@m@bh76Yf79Jw "C (gcc) – Try It Online") Tio link based on [noodle9](https://codegolf.stackexchange.com/users/9481/noodle9)'s post. [Answer] # [J](http://jsoftware.com/), 40 bytes ``` 83+]*168|]+181 AND 53 OR 195*11 XOR 35|] ``` [Try it online!](https://tio.run/##y/pvqWhlbK4Qq2CioKJgoGAJAlxcSnrqaQq2VgrqCjpAQSsg1tVTcA7ycftvYawdq2VoZlETq21oYajg6OeiYGqs4B@kYGhpqmVoqBABZBqb1sT@1@RKTc7IV0hT0lYwVDCCcQwUMvXMTf4DAA "J – Try It Online") Boring translation of formula. But nice demo of J's "evaluate right to left / read out loud left to right" property: * 83 plus input times 168 divided into input plus 181 bitwised and with 53 bitwised or with 195 times 11 xor'd with 35 divided into input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` NθI⁺⁸³×θ⁺θ⎇&¹²⁸×¹⁹⁵⁻|¹¹﹪θ℅#&¹¹﹪θ℅#¹³℅5 ``` [Try it online!](https://tio.run/##fcyxCsIwFIXh3acIdbmBOMRaqHRSJwdth75AbAIG0sTeJIpPH2up0MnpwM/H6e4COydMSmf7iOEa@5tCGGi1alDbACfhAzQmeihzRlrdKw8DI1MZt1VoBb7hqMNLe3WwEvi2/EG@Lxi5aDvaGdQInI/NyWjc96BGqa0wkK0zSikjy6M/cLI8X@RizrRKaZc2T/MB "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Basically a translation of the original expression, except for the following changes: * Where possible, the arguments to operators were reversed, to avoid placing numeric constants consecutively * Otherwise some numeric constants calculated using ASCII codes to avoid consecutive numeric constants * No bitwise XOR, so calculated longhand * @tsh's ternary idea on his comment to @Arnauld's answer turned out to be the shortest way to choose between 13 and 53. ``` Nθ Input `n` ﹪θ℅# ﹪θ℅# `n` modulo ASCII code 35 of literal `#` |¹¹ Bitwise Or with literal `11` &¹¹ Bitwise And with literal `11` ⁻ Subtract, giving the bitwise Xor ×¹⁹⁵ Multiply by literal `195` &¹²⁸ Bitwise And with literal `128` ⎇ If nonzero ¹³ Then literal `13` ℅5 Else ASCII code 53 of literal `5` ⁺θ Add `n` ×θ Multiply by `n` ⁺⁸³ Add literal `83` I Cast to string Implicitly print ``` [Answer] # x86\_64, 33 bytes ``` 89 c1 b2 23 f6 f2 80 f4 0b b0 c3 f6 e4 0c 35 66 25 b5 00 01 c8 b2 a8 f6 f2 86 c4 f6 e1 83 c0 53 c3 ``` ``` .intel_syntax noprefix # in: eax (zero extended) # out: eax .globl primegen primegen: mov ecx, eax mov dl, 35 div dl xor ah, 11 mov al, 195 mul ah or al, 53 and ax, 181 add eax, ecx mov dl, 168 div dl xchg al, ah mul cl add eax, 83 ret ``` [Try it online!](https://tio.run/##fZLhTsMgFIX/8xRkxkRjbdLM6dwz7A2MMQzuWgwFAsx0e/nKaLnd6mJ/lObcy@E7lzLvod2p43PNed/T8SmlDqC@/FEH1lFtrIO97Egu31GpNxRi6eEEzlDoAmgB4vGiwxxCakGprJXZKWqdbKEGTfLHBjta85NW4F1xtTUXhCrocoWykFlGqTMurawpaFX9MWDRoHqfHNqDGttRGg1S62qJMtNiWCNatZ6cmRh0OBci@E3m6nX9LzRv6nzkBUmG4@r2aeuJzkHoZ3NumdTk/ML55tkM442o5VYZY7FuD75JZlMKvJFZOs5UYsPLnPd7eXWDCtjAKaL@4aSlT7Tc@uA@bzjqsEckY@kMSWqeU@De1k7B3l6y/K1hGEiKOaYt44@KiePYCCEJZNBK5rk80cW9KOiC9L8 "Assembly (gcc, x64, Linux) – Try It Online") Nothing special, it is pretty much a direct translation of the example code. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 22 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` I6E6V057]yâ§Z⌠*C++*Zx+ ``` Port of [*@theDefault.*'s 05AB1E answer](https://codegolf.stackexchange.com/a/217162/52210), so make sure to upvote him/her as well! [Try it online.](https://tio.run/##y00syUjPz0n7/9/TzNUszMDUPLby8KJDy6Me9SzQctbW1oqq0P7/34DLkMuIy5jLhMuUy4zLnMuCy5LL0IDLyJTL1IDL3BgA) **Explanation:** ``` I # Push 20 6 # Push 6 E # Push 15 6 # Push 6 V # Push 34 0 # Push 0 5 # Push 5 7 # Push 7 ] # Wrap all values on the stack into a list y # And join them together: 20615634057 â # Convert it from an integer to a binary-list: # [1,0,0,1,0,0,0,1,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1] § # (0-based) index the (implicit) input-integer into this list Z⌠ # Push 38, and increment it by 2 to 40 * # Multiply the current value by this 40 C+ # Add 13 + # Add the (implicit) input-integer * # Multiply it by the (implicit) input-integer Zx # Push 38, and reverse it to 83 + # Add this 83 to the value # (after which the entire stack joined together is output implicitly) ``` --- MathGolf doesn't contain any builtins for bitwise-AND, OR, nor XOR. But even if it did, this approach above would still be 2 bytes shorter than implementing the formula in the challenge description would have been: **24 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py):** ``` W%A^CE**Wx|G1§&+BD*%*Zx+ ``` **Explanation:** ``` W% # Modulo the (implicit) input-integer by 35 A^ # Bitwise-XOR by 11 # (assuming `^` would have been a bitwise-XOR builtin) CE* # Push 13, push 15, multiply them together to 195 * # Multiply the value by this 195 Wx # Push 35, reverse it to 53 | # Bitwise-OR by this 53 # (assuming `|` would have been a bitwise-OR builtin) G1§ # Push 18, push 1, concatenate them together to 181 & # Bitwise-AND by this 181 # (assuming `&` would have been a bitwise-AND builtin) + # Add the (implicit) input-integer BD* # Push 12, push 14, multiply them together to 168 % # Modulo by this 168 * # Multiply to the (implicit) input-integer Zx # Push 38, reverse it to 83 + # Add this 83 to the value # (after which the entire stack joined together is output implicitly) ``` [Answer] # [Julia 1.0](http://julialang.org/), 39 bytes ``` !n=(n+(195(n%35⊻11)|53)&181%168)*n+83 ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPViNPW8PQ0lQjT9XY9FHXbkNDzRpTY001QwtDVUMzC02tPG0L4/9p@UUKFbYGVubGXAVFmXklOXkaihoVmppcqXkp/wE "Julia 1.0 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 25 bytes ``` %35^11×195&Ø⁷+53+%168×+83 ``` [Try it online!](https://tio.run/##AS4A0f9qZWxsef//JTM1XjExw5cxOTUmw5jigbcrNTMrJTE2OMOXKzgz/zc04bi2w4f/ "Jelly – Try It Online") -1 thanks to the default. [Answer] # [FALSE](https://github.com/somebody1234/FALSE), 57 bytes ``` [[$2ø\/*-]m:$$35m;!11$2ø~&@@~&|195*53|181&+168m;!*83+.] ``` [Try it online!](https://tio.run/##S0vMKU79/z86WsXo8I4YfS3d2FwrFRVj01xrRUNDkFidmoNDnVqNoaWplqlxjaGFoZq2oZkFUFrLwlhbL/b/fwA "FALSE – Try It Online") Function that takes a number as input. ## Explanation: ``` [$2ø\/*-]m: {Define modulo function as m (a - (n * trunc(a/n)))} $2ø {Duplicate both a and n to have the stack be a, n, n, a} \/ {swap n and a and divide, which auto-truncates} *- {then multiply by n and subtract a by everything} $$35m;!11$2ø~&@@~&|195*53|181&+168m;!*83+. {Prime generation} $$ {duplicate n twice because we need to add and multiply by n later on} 35m;! {n % 35} 11$2ø~&@@~&| { ^ 11 (xor has be done as (not a and b) or (a and not b) as there is no built-in in FALSE)} $2ø {get stack to be a, b, b, a} ~&@@ {do b and not a, and rotate twice, stack is now result, a, b} ~&| {then do a and not b and or the results together to finish the xor} 195* { * 195} 53| { | 53} 181& { & 181} + { + n} 168m;! { % 168} * { * n} 83+ { + 83} . {output resulting prime} ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 30 bytes ``` +83*%+.&181.|*195x%Q35hT53Q168 ``` [Try it online!](https://tio.run/##K6gsyfj/X9vCWEtVW0/N0MJQr0bL0NK0QjXQ2DQjxNQ40NDM4v9/AwA "Pyth – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~48~~ 46 bytes ``` lambda n:(n+(((n%35^11)*195|53)&181)%168)*n+83 ``` [Try it online!](https://tio.run/##DctBCoAgEADAr3gpdu20mGVCP4nAKEuoNaRDQX@35j7nc22RVfb9kHd3TLMTbIErAOBC6ZEIJXX61QpLMoQFNQYlV@YvMYlbBBbJ8bpAW6M9U@ALPNyI@QM "Python 3 – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 38 bytes ``` n=>(((n%35^11)*195)&181|53+n)%168*n+83 ``` I just removed all the paracenteses I could. [Try it online!](https://tio.run/##DcuxDsIgFEDRWb7ipbEGiiYSRFFKRyd3F@NCSvKWZ9LihHw7stwz3bAewor1/qUwIqU9tEwQwVfyE@ecem3eSolBXY3YKat@RksSvTrbgaTV1TEWPwvw9gGCh6NrjHA5NaUULLPNc8E0P5Bmvu0yltsr5chRlE44Vuof "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~48~~ 46 bytes Saved 2 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!!! ``` f(n){n=((((n%35^11)*195&128)+53+n)%168*n)+83;} ``` [Try it online!](https://tio.run/##VVJdawIxEHz3VwTBcqcnXLLZJMfVvpT@impBzrOV0lTUB0H87XZntV8HrpuZ7Owk2W762nWXy7rI5SnPCvnyiPjF2nJsG76zLpUTpkkuRzakcS4nidrzZZMP5mO5yUU5OA2MfAD647bvDv3qeWFm5pSoMk2sjLWSOLaVISvBRllaEFxLxlEwl5SVZUxCpCCZd4L5gAqrGz1KGhSToh6S0aNI20QClwhco7FWpAbrHDZapzjVGmHEBTS07MAG4FR7NRNUDU1FTXJixYP6dXDkHJR9Ha9ugXODGODSBwIbcQ3SUDVxJGkFhKBMPugVoC8nnIoSnFADNhBLHhhVIUDZ637P6Bsd7ssn@GHVZ8t6GejLHudl9ZMY@kldhVqV1X8j135u9fW6t@VuLLHv3vvd9fmG8@OTmx@bR/nxsDJ/1zS81a0/d6bA02cpqVv5u5cnac1E5sVcB@N7OPayA0PW/kN7QX/GJi9@ye1O6HUxHK3M9MFIHO3nWWzkyuyrH6f72axf3CTPg/PlCw "C (gcc) – Try It Online") Simple port. [Answer] # [Perl 5](https://www.perl.org/) -`p`, 43 bytes ``` $_=(((($_%35^11)*195|53)&181)+$_)%168*$_+83 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYDCFTiVY1N4wwNNbUMLU1rTI011QwtDDW1VeI1VQ3NLLRU4rUtjP//N@Ay5DLiMv6XX1CSmZ9X/F/X11TPwNDgv25BDgA "Perl 5 – Try It Online") ]
[Question] [ *Inspired by [this video](https://www.youtube.com/watch?v=PJHtqMjrStk) by [tecmath](https://www.youtube.com/channel/UCb7w5aTnt7YeXBcVCY0mgFw)*. An approximation of the square root of any number `x` can be found by taking the integer square root `s` (i.e. the largest integer such that `s * s ≤ x`) and then calculating `s + (x - s^2) / (2 * s)`. Let us call this approximation `S(x)`. (Note: this is equivalent to applying one step of the Newton-Raphson method). Though this does have quirk, where S(n^2 - 1) will always be √(n^2), but generally it will be very accurate. In some larger cases, this can have a >99.99% accuracy. ## Input and Output You will take one number in any convienent format. ## Examples Format: Input -> Output ``` 2 -> 1.50 5 -> 2.25 15 -> 4.00 19 -> 4.37 // actually 4.37 + 1/200 27 -> 5.20 39 -> 6.25 47 -> 6.91 // actually 6.91 + 1/300 57 -> 7.57 // actually 7.57 + 1/700 2612 -> 51.10 // actually 51.10 + 2/255 643545345 -> 25368.19 // actually 25,368.19 + 250,000,000/45,113,102,859 35235234236 -> 187710.50 // actually 187,710.50 + 500,000,000/77,374,278,481 ``` ## Specifications * Your output must be rounded to at least the nearest hundredth (ie. if the answer is 47.2851, you may output 47.29) * Your output does not have to have following zeros and a decimal point if the answer is a whole number (ie. 125.00 can be outputted as 125 and 125.0, too) * You do not have to support any numbers below 1. * You do not have to support non-integer inputs. (ie. 1.52 etc...) ## Rules [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Haskell](https://www.haskell.org/), 34 bytes ``` f x=last[s+x/s|s<-[1..x],s*s<=x]/2 ``` [Try it online!](https://tio.run/##FcWxDYMwEAXQVX4J4TDyEYKQ8AhMYLlwAQqKQYijcMHujime3tfLbw4hpQXRBC@XlSo2cstYW61UdCQvGU10DafNrzsMNn9MKI5z3S8oLCUsEzqCfgwE7glt/p3vMv5odukP "Haskell – Try It Online") Explanation in imperative pseudocode: ``` results=[] foreach s in [1..x]: if s*s<=x: results.append(s+x/s) return results[end]/2 ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 32 bytes ``` n->(n/(n=(int)Math.sqrt(n))+n)/2 ``` [Try it online!](https://tio.run/##TZDLasMwEEX3@YohYJCooxD5UZqSQqHLhi5CV6UL1Y9UqTNypXEgFH@760cSW0jM4Wq4c5mDOqmFKTM8pD9NWX0VOoGkUM7BVmmEvxnARXWkqC0no1M4tn9sR1bj/uMTlN073rcCHFo/UZEuRF5hQtqgeDGtQfaOyp7fyswqMhbyTYOLJ4ZLhhumkfhW0bdwv5YYcn6HfCmbx96wMP0Myhw52FymdEf6N4xGXE35YWR5P3Iw0cOJHk1YxqvJgDgMojAKwol5EMnuhjKIX69qPUTOjWVd7D70eojOb8l3Z0fZUZiKRNkukHI291YyXYOXezj3u24fcqHKsjg/u2F5rFM5H@zrWffq5h8 "Java (OpenJDK 8) – Try It Online") ## Explanations The code is equivalent to this: ``` double approx_sqrt(double x) { double s = (int)Math.sqrt(x); // assign the root integer to s return (x / s + s) / 2 } ``` The maths behind: ``` s + (x - s²) / (2 * s) = (2 * s² + x - s²) / (2 * s) = (x + s²) / (2 * s) = (x + s²) / s / 2 = ((x + s²) / s) / 2 = (x / s + s² / s) / 2 = (x / s + s) / 2 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ ... 36 bytes *-3 bytes thanks to @JungHwanMin* *-1 byte thanks to @HyperNeutrino* *-2 bytes thanks to @JonathanFrech* *-3 bytes thanks to @OlivierGrégoire* ``` def f(x):s=int(x**.5);print(x/s+s)/2 ``` [Try it online!](https://tio.run/##TY3BCsMgEETv@xUeY1oMrq5iSr@k9NZKczEh5mC@3roeSmH2MQszzHYenzVhra93FHEocs73JR1DGUdF8rbt/ZnyJcsJa1x3UcSSxAPVVVA73REa0DcYdpYdMdBpDjpryJKxnDWELIvGqecMoo9WBALdFAA9mADWA3ngOvzK8Ff9Ag "Python 2 – Try It Online") [Answer] # R, ~~43 bytes~~ 29 bytes ``` x=scan() (x/(s=x^.5%/%1)+s)/2 ``` Thanks to @Giuseppe for the new equation and help in golfing of 12 bytes with the integer division solution. By swapping out the function call for scan, I golfed another couple bytes. [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTWqNCX6PYtiJOz1RVX9VQU7tYU9/ovxGXKZcll5GZodF/AA) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 9 bytes ``` X^kGy/+2/ ``` [Try it online!](https://tio.run/##y00syfn/PyIu271SX9tI//9/IzNDIwA "MATL – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~20~~ 16 bytes ``` {.5×s+⍵÷s←⌊⍵*.5} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqPdPD04u1H/VuPby9GMh/1NMFZGvpmdYC5RWMFEwVDIHIUsHIXMHYUsHEXMHUHAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to [Olivier Grégoire's](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire) simplified mathematical formula - see their [Java answer](https://codegolf.stackexchange.com/a/146447/53748). ``` ÷ƽ+ƽH ``` **[Try it online!](https://tio.run/##y0rNyan8///w9sNth/ZqgwiP////G5kZGgEA "Jelly – Try It Online")** ### How? ``` ÷ƽ+ƽH - Link: number, n ƽ - integer square root of n -> s ÷ - divide -> n / s ƽ - integer square root of n -> s + - add -> n / s + s H - halve -> (n / s + s) / 2 ``` [Answer] # JavaScript (ES7), 22 bytes ``` x=>(s=x**.5|0)/2+x/s/2 ``` We don't really need an intermediate variable, so this can actually be rewritten as: ``` x=>x/(x=x**.5|0)/2+x/2 ``` ### Test cases ``` let f = x=>x/(x=x**.5|0)/2+x/2 console.log(f(2)) // 1.50 console.log(f(5)) // 2.25 console.log(f(15)) // 4.00 console.log(f(19)) // 4.37 console.log(f(27)) // 5.20 console.log(f(39)) // 6.25 console.log(f(47)) // 6.91 console.log(f(57)) // 7.57 console.log(f(2612)) // 51.10 console.log(f(643545345)) // 25368.19 console.log(f(35235234236)) // 187710.50 ``` [Answer] # C, 34 bytes *Thanks to @Olivier Grégoire!* ``` s; #define f(x)(x/(s=sqrt(x))+s)/2 ``` Works only with `float` inputs. [Try it online!](https://tio.run/##RY3bCoMwDIbv@xTBMWjxNA91jM4n2bwQZ6XgYbO9KIivvq7VsQXykfCHfE3YNY0xkqHDo@VibIFjTbCOsSzla1Z2Ib4kcWrEqGCoxYgJWhDY4v1UK1CtVLcKSljSKABqO9lwsUjPFpmbcjdRh7RI3GGRZzSnWU6jle3fphmwc4jyxEBcE0vfF2QLd@Ffqq2P400tKsJ@6XO2Hzj2jvw@egHob7Si1bwb3tedNGE/fAA) # C, ~~41~~ ~~39~~ 37 bytes ``` s; #define f(x).5/(s=sqrt(x))*(x+s*s) ``` [Try it online!](https://tio.run/##PU3LCoMwELz7FYulkGhs6yOWYv2S1oNYIwEfrckhIP560zUtXZgddmeYaaKuaaxVhbd7tEKOLQhi6IEfiSrVa9Z40ICYUAWKWjlqGGo5EuotHuBsD90qfaughCVhwBnEGy4MkjODFDlD5ogkj9GQZynPeJrxtXAJYpqBbDGyPBUgrzHuMJTUid8SZ@unWoPBFkFcoaxo8VefMyYI4u/FffQZmJ@0eqt9N6KvO2WjfvgA) # C, ~~49~~ ~~47~~ ~~45~~ 43 bytes ``` s;float f(x){return.5/(s=sqrt(x))*(x+s*s);} ``` [Try it online!](https://tio.run/##fc9NCsIwEAXgfU8RCkJSrdL8VCR4EzchmFJIo2YiFEqvbhxcN87yfbyBZ9vB2pxBO/8wiTg6syXe0zuGozpRuMIrJsxYQ@c9NMD0mseQyGTGQFm1VATvGTFytN65W6gP@IMzprdFFaX7Q5ci8XORRLklyy1VJt53G8OQCGIvhZJKyN@KNX@s82aA3PrpCw) --- *Thanks to @JungHwan Min for saving two bytes!* [Answer] # [Haskell](https://www.haskell.org/), 40 bytes *Another one bytes the dust thanks to H.PWiz.* ``` f n|s<-realToFrac$floor$sqrt n=s/2+n/s/2 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hr6bYRrcoNTEnJN@tKDFZJS0nP79IpbiwqEQhz7ZY30g7Tx9I/s9NzMxTsFXITSzwVdAoKMrMK1HQU0jTVIg20lEw1VEwBGFLHQUjcx0FYyBtAqRNgdjIzNAo9j8A "Haskell – Try It Online") [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~47 44~~ 38 bytes ``` {s=int($1^.5);printf"%.2f",$1/2/s+s/2} ``` [Try it online!](https://tio.run/##fZD9SgMxEMT/z1OEUkG5mOxHNptD9ElEOISCtBTxWoqIz34mOcWrYEMCkwzzYzPDaTtNH@P9y/5wvcYnLzd3r2/lslldedo87ldujYHC2I2BPqeJ7O2DRS9gpCryJAabjB7AYD9LVnu@QrDD8@E47HbvS7uzBV5ypDUnnsBwQ6QKjjrLHi/QFnalcaFJy6mXS1Ms7JrTOkXC9j9Bj/BfbmF2lgKJmBRZonCcKxFO2Zci/uRI3I9RcgIOoJ0QxSGyQyCXpTcsVHckTq3rrIpQCj@DlVf3/dxZgV@YqmONjjS7mPEL "AWK – Try It Online") NOTE: The TIO like has 2 extra bytes for `\n` to make the output prettier. :) It feels like cheating a bit to use sqrt to find the square root, so here is a version with a few more bytes that doesn't. ``` {for(;++s*s<=$1;);s--;printf("%.3f\n",s+($1-s*s)/(2*s))} ``` [Try it online!](https://tio.run/##fZDRSsQwEEXf8xVhWaFr0mRmkum0VP0SX4pQEJdVtisi4rfXJFXsCm5IwjA39zC5w9vTPH@Mz8eqN2a6nm5ut9jv@qmu@5fj4@E0VpsrR@P9YWMnU22xTm92vqJ07z7nmXR9p9ExKM4VOWKFpYwOQGG3lEH0@fJeDw@n12G/f1/LRqOn5CPJPnYEKhREk8FRlrLDC7SVnGkh0bj4xPGlKVZy9kmeosHyP0aH8J9vJRpNnphVEwNHDnGJhEPTuhTEHx@x/RGSj8EClOMjW8RgEci23KnAlHek0JSsWxGEFPgZLHXtd9tohl@YiA0SLUlrY4tf "AWK – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 8 bytes ``` :√I:‟/+½ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%3A%E2%88%9AI%3A%E2%80%9F%2F%2B%C2%BD&inputs=2&header=&footer=) For `n=2` ``` : # Dup -> [2,2] √ # Square root -> [2,√2] I # Round -> [2,1] : # Dup -> [2,1,1] ‟ # Rotate stack right -> [1,2,1] / # Divide -> [1,2] + # Add -> 3 ½ # Halve -> 1.5 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` DtïD.Á/+; ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fpeTwehe9w4362tb//xsBAA "05AB1E – Try It Online") Port of my Vyxal answer [Answer] # [Racket](https://racket-lang.org/), 92 bytes Thanks to @JungHwan Min for the tip in the comment section ``` (λ(x)(let([s(integer-sqrt x)])(~r(exact->inexact(/(+ x(* s s))(* 2 s)))#:precision'(= 2)))) ``` [Try it online!](https://tio.run/##HYtBCsIwFET3nmKgi/4oRfqTtFTQi4iLUEIJ1liTLLLyYt7BK9VYePBmBiaY8W7TWs3GTwhb2dHDLCt9P5QFzTbRNZLzyU42NPEVErK4CXoHstmMqbk4vwU60gGZ9oiIQhTz36I6LcGOLrqnr@kMLpNYa2JotIUB3EMOUD10D@5aRqekVloqDan5j2LZldMP "Racket – Try It Online") Ungolfed ``` (define(fun x) (let ([square (integer-sqrt x)]) (~r (exact->inexact (/ (+ x (* square square)) (* 2 square))) #:precision'(= 2)))) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 54 bytes ``` param($x)($x+($s=(1..$x|?{$_*$_-le$x})[-1])*$s)/(2*$s) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VCE4i1NVSKbTUM9fRUKmrsq1XitVTidXNSVSpqNaN1DWM1tVSKNfU1jEDU////Tc0B "PowerShell – Try It Online") or [Verify some test cases](https://tio.run/##FYrRCsIgFEB/RcYNdLsutJbsofqQCBmhNLBtzI0Et283g3M4L2cav2b2b@NcSnYdXks/DsTGqZu7D4XAshUFf6WiriFs9wi6BM2dgbCzBxdPVoJnRyr/2ZPEBkWmRanw1OJZYaNQXoTcDrEATfiNFBW1BHS@fw "PowerShell – Try It Online") Takes input `$x` and then does exactly what is requested. The `|?` part finds the maximal integer that, when squared, is `-l`ess-than-or-`e`qual to the input `$x`, then we perform the required calculations. Output is implicit. [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ½Ṡ§+K/(⌊√ ``` [Try it online!](https://tio.run/##yygtzv7//9DehzsXHFqu7a2v8ain61HHrP///xubGoGQiZGxGQA "Husk – Try It Online") There is still something ugly in this answer, but I can't seem to find a shorter solution. ### Explanation I'm implementing one step of Newton's algorithm (which is indeed equivalent to the one proposed in this question) ``` ½Ṡ§+K/(⌊√ §+K/ A function which takes two numbers s and x, and returns s+x/s Ṡ Call this function with the input as second argument and (⌊√ the floor of the square-root of the input as first argument ½ Halve the final result ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~11~~ 10 bytes ``` ←Đ√⌊Đ↔⇹/+₂ ``` # Explanation ``` code explanation stack ← get input [input] Đ duplicate ToS [input,input] √⌊ calculate s [input,s] Đ duplicate ToS [input,s,s] ↔ reverse stack [s,s,input] ⇹ swap ToS and SoS [s,input,s] / divide [s,input/s] + add [s+input/s] ₂ halve [(s+input/s)/2] implicit print ``` [Answer] # [Milky Way](https://github.com/zachgates/Milky-Way), ~~17~~ 14 bytes *-3 bytes by using Olivier Grégoire's formula* ``` ^^':2;g:>/+2/! ``` [Try it online!](https://tio.run/##y83Mya7ULU@s/P8/Lk7dysg63cpOX9tIX/H///@6mQpmJsamJqbGJqYA "Milky Way – Try It Online") ## Explanation ``` code explanation stack layout ^^ clear preinitialized stack [] ': push input and duplicate it [input, input] 2; push 2 and swap ToS and SoS [input, 2, input] g nth root [input, s=floor(sqrt(input))] : duplicate ToS [input, s, s] > rotate stack right [s, input, s] / divide [s, input/s] + add [s+input/s] 2/ divide by 2 [(s+input/s)/2] ! output => (s+input/s)/2 ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 39 bytes ``` v=>(v/(v=(int)System.Math.Sqrt(v))+v)/2 ``` [Try it online!](https://tio.run/##RY9PSwMxFMTPyad4xwTjlubPiqzbS8FTC0IPHsRDmkYbWBNMshFZ@tnXLKXIe8NchvkxJt2bEO08Juc/4fCbsv3qsBl0SvAy4ZR1dgaeR2@eTmE8DpbB1TcQQ8jQw1z6DSkrUnrifKbXimav87k5fMdMCqV3ha743OFbXQnuBHvtPKF4wqjoCNmmvNXJptro7c/bO0zAGSgG60WPDPgDA1FdVldVvF3XQCuFkkrIGhKKLy@5aHdwqTT0UZdpcwZyI4Dz/ySKUYWjbfApDLZ5jS7bnfOWLMPIEqO0w@iC681/ "C# (.NET Core) – Try It Online") A C# version of [Olivier Grégoire's Java answer](https://codegolf.stackexchange.com/a/146447/73579). ]
[Question] [ Given a positive input number \$n\$, construct a spiral of numbers from \$1\$ to \$n^2\$, with \$1\$ in the top-left, spiraling inward clockwise. Take the sum of the diagonals (if \$n\$ is odd, the middle number \$n^2\$ is counted twice) and output that number. Example for \$n = 1\$: ``` 1 (1) + (1) = 2 ``` Example for \$n = 2\$: ``` 1 2 4 3 (1+3) + (4+2) = 4 + 6 = 10 ``` Example for \$n = 4\$: ``` 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 (1+13+15+7) + (10+16+14+4) = 36 + 44 = 80 ``` Example of \$n = 5\$: ``` 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9 (1+17+25+21+9) + (13+23+25+19+5) = 73 + 85 = 158 ``` ## Further rules and clarifications * This is [OEIS A059924](http://oeis.org/A059924) and there are some closed-form solutions on that page. * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can choose to either 0-index or 1-index, as I am here in my examples, for your submission. Please state which you're doing. * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [R](https://www.r-project.org/), ~~43~~ 34 bytes ``` function(n)(8*n^3-3*n^2+4*n+3)%/%6 ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT1PDQisvzljXGEgaaZto5Wkba6rqq5r9L04sKMip1DC0MjTQSdP8DwA "R – Try It Online") The [OEIS page](http://oeis.org/A059924) lists the following formula for `a(n)`: ``` (16*n^3 - 6*n^2 + 8*n + 3 - 3*(-1)^n)/12 ``` However, I skipped right over that to get to the PROG section where the following PARI code is found: ``` floor((16*n^3 - 6*n^2 + 8*n + 3 - 3*(-1^n))/12)) ``` Naturally, `+3-3*(-1^n)` is the same as `+6` so we can simplify the linked formula, first by reducing it to ``` (16*n^3-6*n^2+8*n+6)/12 -> (8*n^3-3*n^2+4*n+3)/6 ``` and using `%/%`, integer division, rather than `/` to eliminate the need for `floor`. [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes Saved some bytes by porting [Giuseppe's approach](https://codegolf.stackexchange.com/a/141076/59487). ``` lambda n:((8*n-3)*n*n+4*n+3)/6 ``` [Try it online!](https://tio.run/##dZBPj4IwEMXvfIrJJCYgZRVRF03Y2173ojcgRqVIExxMW@Lup2fLiuv/Jk2nzZvfvNfDjy4qGjV5lDTler/J1kBz2w775AVOn/rkjs0OnMG0OUhBGjChhdgfSpELnsGSKw2LWmieEFpWXkkQIAjkmnbc9pk/dOYWnDoFQ@8DWW4Lx7L@Yd7NSiihz2/NKXuEbysp@VavJFd1qRVEEI8Y@EMGwZhBaE5/EjIYvZvbODDVdDJlMAvC9NKrDbLtHL70KtSqExvZ3chYeH4KUQR/GbpYuCw4nARgmMhMTqGQKS3tVue4@Aat5ozttKqo6jKDDUf2bAwDPBZiW0DLivEoK9qheey0mMYXp6kZgRbchnSjqyxXH/5V7zdcQpXfGVJz6Cns2a3vG5IJAAOYoXNmXAiCXjNm3nNK8ws "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~36~~ 34 bytes Saved some *more* bytes thanks to [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun). ``` lambda n:((8*n-3)*n*n+4*n+n%2*3)/6 ``` [Try it online!](https://tio.run/##dZBfb4IwFMXf@RQ3NzEBLFNAHZqwt73uRd@AGJUiTfBi2hK3T8/KZPPPtEnT2@bc3z2nxy9d1hS0RZy21eawzTdAC9uOXPJCxyWXhhOzaRC4oTOatUcpSAOmtBSHYyUKwXNYcaVh2QjNU0LLKmoJAgSB3NCe2z7zx87CgnOnYOi9ISts4VjWH8y7WSml9P6pOeX/4btaSr7Ta8lVU2kFMSQBA3/MIJwwiMzpTyMGwau5TUJTzaYzBvMwyi692iC7zvFTr0Kte7GR3Y1MhOdnEMfwk6GPhauSw1kAhonM5BQKmdLS7nTOEF@g0/xie60q66bKYcuRPRrDAE@l2JXQsRI8yZr2aB57LWbJxWlmRqAFtyGH8VWWqw//aA5bLqEu7gypBQwUDuzO9w3JBIARzNH5ZVwIgp4z5t5jSvsN "Python 2 – Try It Online") [Answer] # Mathematica, 19 bytes ``` ((8#-3)#*#+4#+3)/6& ``` You can run it with the following syntax: ``` ((8#-3)#*#+4#+3)/6&[5] ``` Where `5` can be replaced with the input. You can [Try it in the Wolfram Sandbox](https://sandbox.open.wolframcloud.com/app/objects/113ae9b9-ff6e-4bd8-88ef-9b73efaa30bd) (Copy-Paste + Evaluate Cells) [Answer] # Mathematica, 19 bytes ``` ((8#-3)#*#+4#+3)/6& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfQ8NCWddYU1lLWdtEWdtYU99M7X9AUWZeiYJDWrRpLNf//wA "Mathics – Try It Online") Saved some bytes by porting Giuseppe's approach. # Mathematica, 58 bytes I always enjoy questions with given answers thanx to oeis (for the nice question and answer) ``` LinearRecurrence[{3,-2,-2,3,-1},{0,2,10,34,80},2#][[#+1]]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes 1 byte thanks to Jonathan Allan. ``` ⁽ø\DN2¦ḅ:6 ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//4oG9w7hcRE4ywqbhuIU6Nv/It8OH4oKs/w "Jelly – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 21 bytes ``` tt2^Qw6Y3YL-wXytP+*ss ``` [Try it online!](https://tio.run/##y00syfn/v6TEKC6w3CzSONJHtzyisiRAW6u4@P9/UwA "MATL – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 33 bytes ``` I:u8**.../\*3t3n*3t+u@O,6+3+t3*4p ``` [Try it online!](https://tio.run/##Sy5Nyqz4/9/TqtRCS0tPT08/Rsu4xDgPSGiXOvjrmGkba5cYa5kU/P9vDAA "Cubix – Try It Online") cube version: ``` I : u 8 * * . . . / \ * 3 t 3 n * 3 t + u @ O , 6 + 3 + t 3 * 4 p . . . . . . . . . . . . . . . . . . . . . ``` Implements the same algorithm as my [R answer](https://codegolf.stackexchange.com/a/141076/67312). I suspect this can be golfed down. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~25~~ ~~15~~ 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 8*3-**4.*+3+6÷ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=OCozLSoqNC4qKzMrNiVGNw__,inputs=NA__) Translation of [Mr.Xcoder's Python answer](https://codegolf.stackexchange.com/a/141075/59183) which is using [Giuseppe's approach](https://codegolf.stackexchange.com/a/141076/59183). SOGL's not winning anything here :p [Answer] # Java 8, 24 bytes ``` n->((8*n-3)*n*n+4*n+3)/6 ``` Port of [*@Giuseppe*'s R answer](https://codegolf.stackexchange.com/a/141076/52210). Note that `/6` floors by default when calculating with integers in Java. [Try it here.](https://tio.run/##LU7LDoIwELzzFXtsIWAMakwQ/0AuHI2HWqopwpbQQmIM316XR7Kzm92dyUwtRhGbTmFdfbxshLVwExp/AYBGp/qXkAqKeV0OINnckWd0mQhU1gmnJRSAkIPH@MrYOcQ45SGGGB0IKd@dfLayu@HZEHsTjUZX0JIhK12v8X1/gOCr28v0i5fO9xnoSw5HGlG0fQHKr3WqTczgko6krkGGCcXjS7Y13RRM/g8) [Answer] # Excel, ~~35~~ 30 bytes Saved 5 bytes using [Giuseppe's approach](https://codegolf.stackexchange.com/a/141076/59487). ``` =INT((8*A1^3-3*A1^2+4*A1+3)/6) ``` --- First attempt: ``` =(8*A1^3-3*A1^2+4*A1+3*MOD(A1,2))/6 ``` Evolved from a direct implementation of formula from OEIS (37 bytes): ``` =(16*A1^3-6*A1^2+8*A1+3-3*(-1)^A1)/12 ``` `+3-3*(-1)^A1` logic can be changed to `6*MOD(A1,2)`. ``` =(16*A1^3-6*A1^2+8*A1+6*MOD(A1,2))/12 ``` Does not save bytes, but allows removal of a common factor for 2 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md) Uses the same base-conversion technique as [Leaky Nun's Jelly submission](https://codegolf.stackexchange.com/a/141079/53748) ~~Maybe~~ there is a shorter way to create the list of coefficients~~?~~ -1 byte thanks to Datboi (use spaces ans wrap to beat compression(!)) ``` 8 3(4 3)¹β6÷ ``` **[Try it online!](https://tio.run/##MzBNTDJM/f/fQsFYw0TBWPPQznObzA5v///fBAA "05AB1E – Try It Online")** ### How? ``` 8 3(4 3)¹β6÷ stack: [] 8 - literal ['8'] 3 - literal ['8','3'] ( - negate ['8',-3] 4 - literal ['8',-3,'4'] 3 - literal ['8',-3,'4','3'] ) - wrap [['8',-3,'4','3']] ¹ - 1st input (e.g. 4) [['8',-3,'4','3'], 4] β - base conversion [483] 6 - literal six [483,6] ÷ - integer division [80] - print TOS 80 ``` --- My 13s... ``` •VŠ•S3(1ǝ¹β6÷ ``` ``` •2ùë•₂в3-¹β6÷ ``` ``` •мå•12в3-¹β6÷ ``` All using compressions to find the list of coefficients. [Answer] # [Pyth](https://pyth.readthedocs.io), 17 bytes ``` /+3+*^Q2-*8Q3*4Q6 ``` **[Try it here.](https://pyth.herokuapp.com/?code=%2F%2B3%2B%2a%5EQ2-%2a8Q3%2a4Q6&input=5&debug=0)** [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 14 bytes ``` 8*3-**Q4*+3+6f ``` [Try it here!](http://pyke.catbus.co.uk/?code=8%2a3-%2a%2aQ4%2a%2B3%2B6f&input=5&warnings=0&hex=0) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` 8*3-**4I*+3+6÷ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fQstYV0vLxFNL21jb7PD2//9NAQ "05AB1E – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 14 bytes ``` 8×3⁻××@4×+3+6/ ``` **[Try it online!](https://tio.run/##S0/MTPz/3@LwdONHjbsPTz883cHk8HRtY20z/f//TQE "Gaia – Try It Online")** [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` [DcKI]6/iZQk ``` Try it at [**MATL Online!**](https://matl.io/?code=%5BDcKI%5D6%2FiZQk&inputs=5&version=20.4.1) ### Explanation Same approach as [Giuseppe's answer](https://codegolf.stackexchange.com/a/141076/36398). ``` [DcKI] % Push array [8, -3, 4, 3] 6/ % Divide each entry by 6 i % Push input ZQ % Evaluate polynomial k % Round down. Implicitly display ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/15512/edit). Closed 7 years ago. [Improve this question](/posts/15512/edit) Seeing how hello world has backfired terribly, here is a harder one. I love Zelda and I love ReBoot. Create the following ![enter image description here](https://i.stack.imgur.com/iE6m9.png) **Requirements:** It must be a window (can be ANY window even browsers and such). The window can be of any size. Window may not contain anything else except the picture. Window should not close itself right away. Triangles must be any shade of blue. Circle must be any shade of green. Smaller triangle must touch edges of the No stealing images by providing links. **Condition:** Shortest code wins. PS: Yes ReBoot logo is slightly different but this is close enough to make it fun. EDIT: I added another requirement. It seems like we have a lot of very genius people who enjoy finding loopholes :P I love you guys. [Answer] # Mathematica ~~118 119 118 107~~ 97 Edit: Shortened to 107 chars with help from Belisarius and to 97 with alephalpha. ``` CreateDialog[Graphics@{Blue,Polygon@Outer[Plus,#,#,1]&@{{0,0},{1,1},{2,0}}, Green, {2,1}~Circle~1}] ``` ![triangle](https://i.stack.imgur.com/7pHg7.png) [Answer] ## Dyalog APL (~~121~~ ~~116~~ 115) (Edit: use triangles 8 elements wide instead of 10, to shorten code a bit) (Edit 2: I was only ever using `M¨`, so included the `¨` in the definition of `M`) ``` M←{' ',⍵,⍺,⍨4/0}¨⋄⎕SM←↑(256M⊃,/(⊂8 0)(⊂8 32)(⊂0 16)∘.+⊂(,⍳⍴Z)/⍨≤/¨,Z←⊖Z,⌽Z←2/⍳2/8),512M⌈0 16∘+¨1 2∘ר8+8×1 2∘○¨⍳1e4 ``` Graphics? Who needs graphics? (Also, black is the default background, you didn't say to change it) ![enter image description here](https://i.stack.imgur.com/j0vIg.png) [Answer] # Shell script: ~~166~~ 163 characters ``` f=-fill d=-draw convert -size 64x32 xc: $f blue $d 'polygon 32,0 0,32 64,32' $f white $d 'polygon 32,32 16,16 48,16' $f none -stroke lime $d 'circle 32,16 32,0' x: ``` Sample output: ![Triforce ReBoot logo](https://i.stack.imgur.com/RHfNf.png) [Answer] # R, 124, 122, 111 ``` frame() p=polygon p(c(1,3,5)/5,c(1,3,1)/5,c=4) p(c(2,4,3)/5,c(2,2,1)/5,c="white") symbols(.6,.4,.1,i=1,a=T,f=3) ``` This produces the following picture in a plot window: ![enter image description here](https://i.stack.imgur.com/EQexs.png) [Answer] ## Java, 434 358 349 ``` import java.awt.*; public class T { public static void main(String[] a) { new Frame() { public void paint(Graphics g) { g.setColor(Color.BLUE); Polygon p=new Polygon(new int[]{50, 75, 100},new int[]{75, 50, 75},3); g.fillPolygon(p); p.translate(-25, 25); g.fillPolygon(p); p.translate(50, 0); g.fillPolygon(p); g.setColor(Color.green); g.drawOval(50, 50, 50, 50); } }.show(); } } ``` golfed ``` import java.awt.*;public class T{public static void main(String[] a){new Frame(){public void paint(Graphics g){g.setColor(Color.BLUE);Polygon p=new Polygon(new int[]{50,75,100},new int[]{75,50,75},3);g.fillPolygon(p);p.translate(-25,25);g.fillPolygon(p);p.translate(50,0);g.fillPolygon(p);g.setColor(Color.green);g.drawOval(50,50,50,50);}}.show();}} ``` Who knew golfing reduces code so much. EDIT: Thanks manatwork for all your suggestions. [Answer] ## Game Maker Language, 167 165 155 EDIT 1 - I shaved off two characters by replacing `c_green` with `32768`, the same value. The other color's values were longer than their predefined names. EDIT 2 - Epic golf! Used variables for frequently used values, and forgot that newlines aren't needed (newlines count as two spaces). The room (`r`) is predefined 64 by 32 with a white background. Object `d` is anywhere in room `r`. Draw Event code: ``` a=16b=32draw_set_color(c_blue)draw_triangle(0,b,64,b,b,0,0)draw_set_color(32768)draw_circle(b,a,a,1)draw_set_color(c_white)draw_triangle(a,a,48,a,b,b,0) ``` Result: ![Output of room r](https://i.stack.imgur.com/Vtmrm.png) ## Ti84-Basic - 54 characters (but output is black and white) ``` :Line(0,0,2,0 :Line(0,0,1,1 :Line(2,0,1,1 :Circle(1,.5,.5 ``` [Answer] ## HTML, 101 ``` <img style=position:absolute;clip:rect(30px,130px,110px,20px) src=https://i.stack.imgur.com/iE6m9.png> ``` [Answer] ## HTML+CSS, ~~352~~ ~~290~~ ~~261~~ 257 ``` <div style="width:0;border:50px solid #fff;border-bottom-color:#00f"> <p style="border:25px solid #00f;border-top-color:#fff;border-bottom:0;margin:25px 0 0 -25px"> <p style="border:1px solid #0f0;border-radius:50px;width:50px;height:50px;margin:-52px -26px"> ``` <http://jsfiddle.net/WF3hP/6/> Ungolfed: ``` <style> #blue-triangle { width:0; border:50px solid #fff; border-bottom-color:#00f } #white-triangle { border:25px solid #00f; border-top-color:#fff; border-bottom:0; margin:25px 0 0 -25px } #circle { border:1px solid #0f0; border-radius:50px; width:50px; height:50px; margin:-52px -26px } </style> <div id="blue-triangle"> <p id="white-triangle"> <p id="circle"> ``` [Answer] ## R, 108 characters Very similar to [Sven Hohenstein solution](https://codegolf.stackexchange.com/a/15521/6741) but differs in two interesting points, so I thought I would add it: ``` frame() p=polygon p(c(0:3,1:4)/5,c(0:1,0:1,1:2,1:0)/5,c=4) t=seq(0,2*pi,.1) p(.2*cos(t)+.4,.2*sin(t)+.2,b=3) ``` Instead of drawing a large blue triangle and a small white one, I draw a polygon representing already the three triangles. As for the circle, this one (whose code is clearly longer than Sven's) doesn't lose its contacts with the triangles on resize. Finally instead of using the color names I used their number in R's default color palette (4 for blue and 3 for green). ![enter image description here](https://i.stack.imgur.com/WtuGl.png) [Answer] ### JavaScript (canvas, Firefox), ~~237~~ 231 characters ``` <body onload=with(c=document.all.a.getContext('2d'))fillStyle='#00F',strokeStyle='#0F0',mozFillRule='evenodd',c.f=lineTo,moveTo(4,0),f(8,4),f(0,4),f(2,2),f(6,2),f(4,4),f(2,2),fill(),beginPath(),arc(4,2,2,0,7),stroke()><canvas id=a> ``` I couldn't find any hard requirements on the dimensions, so I decided to abuse that a bit and go with 8×4 pixels to cut down code size... also, relies on the Mozilla extension mozFillRule to get even-odd filling for the triforce. [jsbin (small)](http://jsbin.com/onUfAYA/4/watch), [jsbin (bigger)](http://jsbin.com/onUfAYA/3/watch) [Answer] ### SVG ~~305~~ 296 ``` <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="1 3 9 10"> <path d="M 5,4 2.5,7 7.5,7 5,4 z M 7.5,7 5,10 10,10 7.5,7 z M 5,10 2.5,7 0,10 5,10 z" fill="#00f" /><path d="m 7.5,7 a 2.5,3 0 0 1 -5,0 2.5,3 0 1 1 5,0 z" fill="none" stroke="#0f0" stroke-width="0.02" /></svg> ``` ![Firefox window with svg draw](https://i.stack.imgur.com/gs7BZ.png) [Answer] # HTML 118 ``` <svg><path fill=#00f d="M0,2 2,0 4,2 2,2 3,1 1,1 2,2z"/><circle fill=none stroke-width=.1 stroke=#0f0 cx=2 cy=1 r=1 /> ``` [Answer] ## Sage (CLI), ~~111~~ 106 ``` p=polygon;circle((2,1),1,color=(0,1,0))+p([(0,0),(2,2),(4,0)])+p([(1,1),(3,1),(2,0)],axes=0,color=(1,1,1)) ``` ![image in window created by Sage](https://i.stack.imgur.com/c6qpL.png) This is via the Sage command line interface. (This works also in a Sage Notebook, but although the image appears in its own cell, that probably doesn't qualify as a "window".) EDIT: Eliminated 5 minus signs and replaced the screenshot of a Sage Notebook cell with one of a Sage CLI window. (Credit @boothby) [Answer] ## Golf-Basic 84, 36 characters (Output is Black and White) ``` l;0,0,2,0l;0,0,1,1l;2,0,1,1c;1,.5,.5 ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 8 years ago. [Improve this question](/posts/12627/edit) today (24 of September) is birthday of company HONDA. Originally their company name is `本田技研工業株式会社` I want to ask to make a gift for HONDA. The task is to make program print company name. You can do it any way you want, but there is only one rule, Unicode is not allowed. It should be ASCII art. I want to ask to post code and output. As always to determine winner I'll look at the length of code, however portrait in this case is also important. **EDIT:** output have to look similar into this: `本田技研工業株式会社` [Answer] # Mathematica Here the characters are individually rasterized. The zero's of the binary image data of a reduced image are then replaced with asterisks and the array itself is then printed. ``` GraphicsGrid[ImageData@ImageResize[Binarize@Rasterize@Style[#, 136], 30] /. {1 -> "", 0 -> "*"}] & /@ Characters["本田技研工業株式会社"] ``` ![Honda](https://i.stack.imgur.com/EiNRF.png) Below all characters were rasterized as a single image. The asterisks are a bit more difficult to recognize as asterisks in this case. ``` GraphicsGrid[ImageData@ImageResize[Binarize@Rasterize@Style[#, 136], 300] /. {1 -> "", 0 -> "*"}, ImageSize -> 1500] &["本田技研工業株式会社"] ``` ![image2](https://i.stack.imgur.com/fLdUZ.png) [Answer] ## Tcl Well, a probably crazy approach. ``` package r Tk package r Img pack [label .l -text 本田技研工業株式会社 -fg #000000 -bg #ffffff] update puts [join [lmap line [[image create photo -data .l] data] {join [lmap pixel $line {expr {$pixel ne {#ffffff}?"@":" "}}] {}}] \n] exit ``` Here a screenshot: ![screenshot](https://i.stack.imgur.com/696OG.png) [Answer] --- # JavaScript + HTML, interactive version (275 + 90 = 365 chars) Many ideas inspired by [Austin's answer](https://codegolf.stackexchange.com/a/12636/3808), but this one is interactive; you can change the font size! (also the character count is actually correct) --- ### Screenshot Pressing the `-` and `+` buttons change the font size. Image is cut off, but you get the idea. ![image](https://i.stack.imgur.com/MPTCK.png) --- ### Fiddle (try it yourself!) [Here is a JSFiddle](http://jsfiddle.net/UjTbK/) where you can run the code yourself. --- ### JS, 275 ``` h=30,(r=function(){for(x=document.createElement('canvas').getContext('2d'),x.font=h+'px sans-serif',x.fillText('本田技研工業株式会社',0,h),d=x.getImageData(0,0,w=h*10,h).data,s='',a=0;a<h;a++){for(b=0;b<w;b++)s+=d[3+w*4*a+4*b]?0:' ';s+='\n'}document.getElementById('p').innerHTML=s})() ``` --- ### HTML, 90 ``` <button onclick='h--;r()'>-</button><button onclick='h++;r()'>+</button><pre id='p'></pre> ``` --- ## Hi-resolution version <http://jsfiddle.net/UjTbK/1/> ![image](https://i.stack.imgur.com/TXYll.png) --- [Answer] # Javascript, 261 characters, 226 minified special thanks to [jsacii](http://www.nihilogic.dk/labs/jsascii/) for inspiring this solution. ``` c = document.createElement('canvas').getContext('2d'); c.font="30px sans-serif";c.fillText("本田技研工業株式会社", 0,30);d=c.getImageData(0,0,305,40).data; s=""; for(var y = 0; y<40;y+=2){ for(var x=0;x<305;x++) s += d[3+4*x+1220*y]? "*" : " "; s+="\n"; } ``` minified ``` c=document.createElement("canvas").getContext("2d");c.font="30px sans-serif";c.fillText("本田技研工業株式会社",0,30);d=c.getImageData(0,0,305,40).data;s="";for(var y=0;y<40;y+=2){for(var x=0;x<305;x++)s+=d[3+4*x+1220*y]?"*":" ";s+="\n"} ``` and the output ``` **** **** **** *** *** **** **** ** **** **** **** **** ************************** **** **** ***************************** **** *** *** **** **** ******** ******** ****** **** **** **** ************************** **** **** * ** ******* ****** ****** ** ************************* **** *** *** **** **** **** **** **** ***** ********** *** **** **************************** **** **** **** **************************** **** **** **** ************************ **************************** *************************** **************************** ****** ****** ************* **** *************************** **** **** **** *********** **** **** **** **** **** **** **** *************************** **************************** ******* ******* **** **** ********* **** **** **** **** **** **** **** **** **** ************************** ********** **** **** ***************************** ********************* ************ ************************** **** ***************** **************************** **** ************************** ************************* ****************** **** **************** ***** **** **** ********** ***** **** **** ************************** ******* **** **** ****** ******************** **** ********************** ************************** ****************** ******* **** ***** **** ***** **** **** **** ******** ***** ***** ******* *** **** **** **** ********************** ******* ******** **** **** **************************** ************* **** ****** **** ****** **** **** **** ******** **** **** * **** *** **** **** **** **************************** ********* *********** **** **** * **** * ** **** *** **** **** ***************************** **** **** **** **** ******* **** *** **** **** **** **************************** ** **** ********* ***** **** * **** *** **** ***** *** **** **** * **** **** **** **** **** **** ********* ********* ***** **** **************************** **************** ********** **** ****** *********** **** **** **** ***** *** **** **** ************************** **** ******* ******* ************** **** **************************** ********** **** *********** ******** **** **** ************** ******** *********************** *** ******************* **** **** **** ************** ******* **** ***** **** ****** **** ***** **** **** *** ****** **************** ***** **** ******************* *** * * ** ** **** **** *** ** *** ``` [Answer] # Java, ~~267~~ 260 characters Alright, I guess my solution is not all that different from Johannes Kuhn's answer, but as it seems this is a problem that can be handled nicely in Java; my solution is not much longer; and the output is slightly different, I'll post it nevertheless: ``` class A{public static void main(String[]a){java.awt.image.BufferedImage b=new java.awt.image.BufferedImage(130,16,2);b.createGraphics().drawString("本田技研工業株式会社",0,13);for(int y=0;y<2080;System.out.print((b.getRGB(y%130,y/130)<0?"#":" ")+(++y%130<1?"\n":"")));}} ``` Formatted as: ``` class A { public static void main(String[]a) { java.awt.image.BufferedImage b = new java.awt.image.BufferedImage(130, 16, 2); b.createGraphics().drawString("本田技研工業株式会社", 0, 13); for (int y = 0; y < 2080; System.out .print((b.getRGB(y % 130, y / 130) < 0 ? "#" : " ") + (++y % 130 < 1 ? "\n" : ""))) ; } } ``` Output: ``` # # # # # # # # # # # # ########### # # #### ####### # # # # # # # # ## # # # # ########### # # # # ######## # # # ########## # # # # # # # ###### # ## ## ##### # # # # # #### # # # # # ########### ### # # ############ # # # # ### # # # # # # # # # # # # # # # ###### ## # ##### # # # ########### # ####### ### ####### # ########### ### ####### ##### # # # # # # # # # ## # # ## # # # # ######### # # # # # ### # # # # # # # ### # # # # # # # # # # ### # # ########### # # # # # ##### # # # # # # # # # # # # ########### # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # ## # # # # # # # ########### # ## ## # # # # ########### ## # ### # # # # ##### # # # # # ####### # # # ## # # # # # # # # # # ######## ## # ``` ]
[Question] [ ## Definition > > A square-free semiprime is a natural number that is the product of two distinct prime numbers. > > > ## The task Given a natural number `n`, count all square-free semiprimes less than or equal to `n`. ## Details Please write a function or procedure that accepts a single integer parameter and counts all square-free semiprimes less than or equal to its parameter. The count must either be a return value of a function call or be printed to STDOUT. ## Scoring The answer with the fewest number of characters wins. In the event of a tie, the following criteria will be used in order: 1. Tallest person 2. Best [time-complexity](/questions/tagged/time-complexity "show questions tagged 'time-complexity'") 3. Worst [space-complexity](/questions/tagged/space-complexity "show questions tagged 'space-complexity'") ## Examples ``` f(1) = 0 f(62) = 18 f(420) = 124 f(10000) = 2600 ``` [Answer] ## J, 50 40 38 37 characters ``` f=:3 :'+/y<:}.~.,(~:/**/)~p:i._1&p:y' ``` Usage: ``` f 1 0 f 62 18 f 420 124 f 10000 2600 ``` With thanks to [FUZxxl](https://codegolf.stackexchange.com/users/134/fuzxxl). **Performance test** ``` showtotal_jpm_ ''[f 1[start_jpm_ '' Time (seconds) ┌───────┬──────┬────────┬────────┬─────┬────┬───┐ │name │locale│all │here │here%│cum%│rep│ ├───────┼──────┼────────┼────────┼─────┼────┼───┤ │f │base │0.000046│0.000046│100.0│100 │1 │ │[total]│ │ │0.000046│100.0│100 │ │ └───────┴──────┴────────┴────────┴─────┴────┴───┘ showtotal_jpm_ ''[f 1[f 62[start_jpm_ '' Time (seconds) ┌───────┬──────┬────────┬────────┬─────┬────┬───┐ │name │locale│all │here │here%│cum%│rep│ ├───────┼──────┼────────┼────────┼─────┼────┼───┤ │f │base │0.000095│0.000095│100.0│100 │2 │ │[total]│ │ │0.000095│100.0│100 │ │ └───────┴──────┴────────┴────────┴─────┴────┴───┘ showtotal_jpm_ ''[f 1[f 62[f 420[start_jpm_ '' Time (seconds) ┌───────┬──────┬────────┬────────┬─────┬────┬───┐ │name │locale│all │here │here%│cum%│rep│ ├───────┼──────┼────────┼────────┼─────┼────┼───┤ │f │base │0.000383│0.000383│100.0│100 │3 │ │[total]│ │ │0.000383│100.0│100 │ │ └───────┴──────┴────────┴────────┴─────┴────┴───┘ showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[start_jpm_ '' Time (seconds) ┌───────┬──────┬────────┬────────┬─────┬────┬───┐ │name │locale│all │here │here%│cum%│rep│ ├───────┼──────┼────────┼────────┼─────┼────┼───┤ │f │base │0.084847│0.084847│100.0│100 │4 │ │[total]│ │ │0.084847│100.0│100 │ │ └───────┴──────┴────────┴────────┴─────┴────┴───┘ showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[f 50000[start_jpm_ '' Time (seconds) ┌───────┬──────┬────────┬────────┬─────┬────┬───┐ │name │locale│all │here │here%│cum%│rep│ ├───────┼──────┼────────┼────────┼─────┼────┼───┤ │f │base │5.014691│5.014691│100.0│100 │5 │ │[total]│ │ │5.014691│100.0│100 │ │ └───────┴──────┴────────┴────────┴─────┴────┴───┘ ``` I'm no theoretician as has been seen here in the past, but I think the time complexity is something like O(np2) where np is the number of primes up to and including the input number n. This is based on the assumption that the complexity of my method (generating a very large multiplication table) far outweighs the complexity of the prime generating function built in to J. **Explanation** `f=:3 :'...'` declares a (monadic) verb (function). The input to the verb is represented by `y` within the verb definition. `p:i._1&p:y` The `p:` verb is the multi purpose primes verb, and it's used in two different ways here: `_1&p:y` returns the number of primes less than `y` then `p:i.` generates every one of them. Using 10 as input: ``` p:i._1&p:10 2 3 5 7 ``` `(~:/**/)~` generates the table I spoke of earlier. `*/` generates a multiplication table, `~:/` generates a not-equal table (to eliminate the squares) and both of these are multiplied together. Using our previous output as input: ``` */~2 3 5 7 4 6 10 14 6 9 15 21 10 15 25 35 14 21 35 49 ~:/~2 3 5 7 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0 (~:/**/)~2 3 5 7 0 6 10 14 6 0 15 21 10 15 0 35 14 21 35 0 ``` `}.~.,` now we turn the numbers into one list `,` get the unique values `~.` and remove the 0 at the start `}.` ``` }.~.,(~:/**/)~2 3 5 7 6 10 14 15 21 35 ``` `y<:` a comparison with the original input to check which values are valid: ``` 10<:6 10 14 15 21 35 1 1 0 0 0 0 ``` `+/` and then sum that to get the answer. ``` +/1 1 0 0 0 0 2 ``` [Answer] # Mathematica 65 64 55 51 47 39 **Code** The following counts the number of square-free semiprimes less than or equal to `n`: ``` FactorInteger@Range@n~Count~{a={_,1},a} ``` Any square-free semiprime factors into a structure of the form: `{{p,1}{q,1}}` For example, ``` FactorInteger@221 (* out *) {{13, 1},{17, 1}} ``` The routine simply counts the numbers in the desired range that have this structure of factors. --- **Usage** ``` n=62; FactorInteger@Range@n~Count~{a={_,1},a} (* out *) 18 ``` --- **Timing: All the given examples** ``` FactorInteger@Range@#~Count~{a = {_, 1}, a} & /@ {1, 62, 420, 10^4} // Timing (* out *) {0.038278, {0, 18, 124, 2600}} ``` --- **Timing: n=10^6** It takes under four seconds to count the number of square-free semi-primes less than or equal to one million. ``` n=10^6; FactorInteger@Range@n~Count~{a = {_, 1}, a}//Timing (* out *) {3.65167, 209867} ``` [Answer] ## Python, 115 ``` r=range p=lambda x:all(x%i for i in r(2,x)) f=lambda x:sum([i*j<=x and p(j)and p(i)for i in r(2,x)for j in r(2,i)]) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ŒcfÆf€L ``` [Try it online!](https://tio.run/##y0rNyan8///opOS0w21pj5rW@Pw/uudwO5Dh/v@/oY6CmZGOgomRAQA "Jelly – Try It Online") ### How it works ``` ŒcfÆf€L Main link. Argument: n Œc Generate all 2-combinations of [1, ..., n], i.e., all pairs [a, b] such that 1 ≤ a < b ≤ n. Æf€ Compute the prime factorization of each k in [1, ..., n]. f Filter; keep only results that appear to the left and to the right. L Take the length. ``` [Answer] ## Python (139) ``` from itertools import*;s=lambda n:sum(x*y<=n and x<y for x,y in product(filter(lambda x:all(x%i for i in range(2,x)),range(2,n)),repeat=2)) ``` Please provide some sample results so competitors could test their programs. [Answer] ## Ruby 82 ``` z=->n{[*2..n].select{|r|(2...r).all?{|m|r%m>0}}.combination(2).count{|a,b|a*b<=n}} ``` Demo: <http://ideone.com/cnm1Z> [Answer] # Python 139 ``` def f(n): p=[];c=0 for i in range(2,n+1): if all(i%x for x in p):p+=[i] c+=any((0,j)[i/j<j]for j in p if i%j==0 and i/j in p) return c ``` [Answer] ## Golfscript 64 ``` ~:ß,{:§,{)§\%!},,2=},0+:©{©{1$}%\;2/}%{+}*{..~=\~*ß>+\0?)+!},,2/ ``` Online demo [here](http://golfscript.apphb.com/?c=ewoKfjrDnyx7OsKnLHspwqdcJSF9LCwyPX0sMCs6wql7wql7MSR9JVw7Mi99JXsrfSp7Li5%2bPVx%2bKsOfPitcMD8pKyF9LCwyLwoKfTpmdW5jdGlvbgoKOycxJyBmdW5jdGlvbiBwCjsnNjInIGZ1bmN0aW9uIHAKOycxMDAnIGZ1bmN0aW9uIHA=&run=true) ***Note:** In the demo above I excluded the `420` and `10000` test cases. Due to the extremely inefficient primality test, it's not possible to get the program to execute for these inputs in less than 5 seconds.* [Answer] ## Shell, 40 ``` #!/bin/sh seq $1|factor|awk 'NF==3&&$2!=$3'|wc -l #old, 61 #seq $1|factor|awk 'BEGIN{a=0}NF==3&&$2!=$3{a++}END{print a}' ``` Usage: ``` $ ./count 1 0 $ ./count 420 124 $ ./count 10000 2600 $ time ./cnt.sh 1000000 209867 real 0m23.956s user 0m23.601s sys 0m0.404s ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 13 bytes ``` RÆEḟ0⁼1,1$Ɗ€S ``` [Try it online!](https://tio.run/##y0rNyan8/z/ocJvrwx3zDR417jHUMVQ51vWoaU3w////TYwMAA "Jelly – Try It Online") ``` RÆEḟ0⁼1,1$Ɗ€S main function: RÆE get the prime factorization Exponents on each of the Range from 1 to N, Ɗ€ apply the preceding 1-arg function composition (3 funcs in a row) to each of the prime factorizations: (the function is a monadic semiprime checker, as per DavidC's algorithm) ḟ0 check if the factors minus the zero exponents... ⁼1,1$ ...are equal to the list [1,1] S take the Sum of those results, or number of successes! ``` Constructive criticism welcomed! [Answer] # [Python 2/3](https://docs.python.org/2/), ~~95~~ 94 bytes ``` lambda n:sum(map(F,range(n+1))) F=lambda x,v=2:sum(x%i<1and(F(i,0)or 3)for i in range(2,x))==v ``` [Try it online!](https://tio.run/##PY3BCsIwEETP5iv2ImQxSBvFQzHXfoWXaFtdaDYhSUv79bGoODBzGN4wYc0vz7qQCz5mSGsSm4@pz7F/TDGR55EcZVlXm1AM5lZG6@6dBW7S5KSzQbYqWn72kg81IorW/IhFzUZ/qGVP19pyJ1tJqkIf4YTDlgTE8B1rtSAaM5d/Xyu4aAVnXSn43DdiFyJxBlIwSMLyBg "Python 2 – Try It Online") Posted in a 6 year old challenge because it sets a new Python record, an IMO it's a pretty interesting approach. # Explanation ``` lambda n:sum(map(F,range(n+1))) # Main function, maps `F` ("is it a semiprime?") # over the range [0, n] F=lambda x,v=2: # Helper function; "Does `x` factor into `v` # distinct prime numbers smaller than itself?" sum( # Sum over all numbers `i` smaller than `x` x%i<1 # If `i` divides `x`, and # then (F(i,0) # add 1 if `i` is prime (note that `F(i,0)` # is just a primality test for `i`!) or 3) # or `3` if `i` is not prime (to make `F` # return `False`) for i in range(2,x)) ==v # Check if there were exactly `v` distinct prime # factors smaller than `x`, each with # multiplicity 1 ``` # [Python 2/3 (PyPy)](http://pypy.org/), ~~88~~ ~~82~~ 81 bytes ``` lambda n:sum(sum(x%i<1and(x/i%i>0or 9)for i in range(2,x))==2for x in range(n+1)) ``` [Try it online!](https://tio.run/##RYpBCsIwEADP@oq9FLIYsVlEsDS@xEukjS7YbYgtJK9P7aU9zByGCXn6jELnkEMu3j7L1w2vzoE0v3lQK6ni1jjpVLpwxY96jHBH/zcDC0Qn716RTojW0prTnuVkEMv2Gg030nClujkeQmSZgDV4xVgW "Python 2 (PyPy) – Try It Online") Based on a 92-byte golf by Value Ink. PyPy is needed to correctly interpret `0or`, because standard Python sees this as an attempt at an octal number. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 61 bytes Golfed version. [Try it online!](https://tio.run/##TYxBCsMgFET3PcVf5qOlKqWb4D6HyEZEG8Hoj7G0UHp26ypkVvNm4JEp4fqk1vyQUH@tFqPPhUpY3UBa8X0rNaTaT37smyYmeboRt4whjvbX5hkmVxyEHUwC9zErRQfZw5LfUDNYEyPUxYF/JVtDTpeu6lo/SMSjP9QJ7kqcSIoexPYH) ``` f(n)={c=0;forprime(p=2,sqrtint(n),forprime(q=p+1,n/p,c++));c} ``` Ungolfed version. [Try it online!](https://tio.run/##fY8xC8IwEIX3/oobG1qxLeIiruIouHYJ5WoDaZJeUhTE316vUURB@qbw3nd3L06SWl3cNPlhlIQHQjxjr06kevSpEbCHewIsbRup08aOJrBXiF10W0tuRlPHZpWDHygoE3gwhwj8QANDLitzMGv3lc@Ki7Ps44n4el8hDCOZ13G2HkldwxEJQXmQBvAme6cRbAudvUKwwFU1hA6hHU0TlDUJF@Bafz9ZCrEUb6vlfFMVy0BZsISYpic) ``` squareFreeSemiPrimes(n) = { local(count = 0); forprime(p = 2, sqrtint(n), forprime(q = p+1, n/p, count++ ) ); return(count); } \\ Here is an example of how to call the function print(squareFreeSemiPrimes(1)) print(squareFreeSemiPrimes(62)) print(squareFreeSemiPrimes(420)) print(squareFreeSemiPrimes(10000)) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ߺ@N¬Që↔ ``` [Run and debug it](https://staxlang.xyz/#p=e1a7404eaa51891d&i=1%0A62%0A420%0A10000&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` F for 1..n run the rest of the program :F get distinct prime factors 2( trim/pad factor list to length 2 :* compute product of list _/ integer divide by initial number (yielding 0 or 1) + add to running total ``` [Run this one](https://staxlang.xyz/#c=F+++%09for+1..n+run+the+rest+of+the+program%0A++%3AF%09get+distinct+prime+factors%0A++2%28%09trim%2Fpad+factor+list+to+length+2%0A++%3A*%09compute+product+of+list%0A++_%2F%09integer+divide+by+initial+number+%28yielding+0+or+1%29%0A++%2B+%09add+to+running+total&i=1%0A62%0A420%0A10000&m=2) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~58~~ 45 bytes *Thanks to Jo King for -13 bytes.* ``` {+grep {3==.grep($_%%*)&&.all³-$_}o^*,1..$_} ``` Takes advantage of the fact that integers with four factors are either square-free semiprimes or perfect cubes. [Try it online!](https://tio.run/##K0gtyjH7n1uplmb7v1o7vSi1QKHa2NZWD8TSUIlXVdXSVFPTS8zJObRZVyW@Nj9OS8dQTw/I@m/NlZZfpGBjqGBmpGBiZGCnoGunoBKvUM3FWZxYqaAEZAIFqtOAYrVKXLX/AQ "Perl 6 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` {≥ḋĊ≠}ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pR59KHO7qPdD3qXFD7cNuc//@jDXXMjHRMjAx0DA2AIBYA "Brachylog – Try It Online") ``` The output is { }ᶜ the number of ways in which you could ≥ choose a number less than or equal to the input ḋ such that its prime factorization Ċ is length 2 ≠ with no duplicates. ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 58 bytes ``` _ ¶_$` %(`$ $" ,,`_(?=(__+)¶\1+$) ¶1$' )C`1(?!(__+)\1+¶) 2 ``` [Try it online!](https://tio.run/##K0otycxLNPyvqpGgp82l9T@e69C2eJUELiBfhUtFiUtHJyFew95WIz5eW/PQthhDbRVNoApDFXUuTecEQw17RbAMUPzQNk0uo///DbnMjLhMjAwA "Retina – Try It Online") Takes as input unary with `_` as tally mark ## Explanation A number is a square-free semi-prime if its largest and smallest factor, excluding itself and 1, are both primes. ``` _ ¶_$` ``` Takes the input and generate each unary number less than or equal to it, each on its own line ``` %(` ``` Then, for each number ... ``` $ $" ,,`_(?=(__+)¶\1+$) ¶1$' ``` Find its smallest and largest factor, excluding itself an 1 ... ``` )C`1(?!(__+)\1+¶) ``` and count the number of them that is prime. Since the smallest factor must be a prime, this returns 1 or 2 ``` 2 ``` Count the total number of 2's [Answer] # [Python 2](https://docs.python.org/2/), ~~105~~ 104 bytes ``` lambda m:sum(reduce(lambda(a,v),p:(v*(a+(n%p<1)),v>0<n%p**2),range(2,n),(0,1))[0]==2for n in range(m+1)) ``` [Try it online!](https://tio.run/##PclBCsIwEEDRtZ5iNsIknUUaxEVpvEjtItpEC2YaYhvw9DFQcPf5L37X18K6eHMrbxvuk4XQfbaAyU3bw@H@0FIWFDvMEm2DfIp9KwTlq@prS6kFJctPh5pYECqqOqjRGO2XBAwzw@6hqVL@c2gJLprgrNXYHQ8xzbwCE3hkUX4 "Python 2 – Try It Online") 1 byte thx to [squid](https://codegolf.stackexchange.com/users/85755/squid) 🦑 [Answer] # [Ruby](https://www.ruby-lang.org/) `-rprime`, 64 bytes I know that there's another Ruby solution here, but I didn't want to bump it with comments since it was answered in 2012... and as it turns out, [using a program flag counts it as a different language](https://codegolf.meta.stackexchange.com/a/14339/52194), so I guess this technically isn't "Ruby" anyhow. [Try it online!](https://tio.run/##KypNqvyfZhvzX9cur1rDUE8vT1MvOb80r6S6JrMm1zZTr6AoMzc1PiWzLLM4Mz/POlevOLMqtQZIleZqqFnlJBaXaNraGtXW/i9QSItWidcryY/PjP1vyGVmxGViZMBlaAAE//ILSoCai//rFoGN@6@bBwA "Ruby – Try It Online") **Explanation** ``` ->n{(1..n).count{|i|m=i.prime_division;m.size|m.sum(&:last)==2}} ->n{ # Anonymous lambda (1..n).count{|i| # Count all from 1 to `n` that match # the following condition m=i.prime_division; # Get the prime factors of `i` as # base-exponent pairs (e.g. [2,3]) m.size # Size of factors (# of distinct primes) | # bit-or with... m.sum(&:last) # Sum of the last elements in the pairs # (the sum of the exponents) ==2 # Check if that equals 2 and return. # Because 2 is 0b10, the bit-or means # that the condition is true iff both # are either 2 or 0, but because this # is a prime factorization, it is # impossible to have the number of # distinct primes or the sum of the # exponents to equal 0 for any number # > 1. (And for 1, size|sum == 0.) } # End count block } # End lambda ``` [Answer] # APL(NARS), chars 26, bytes 52 ``` {≢b/⍨{(⍵≡∪⍵)∧2=≢⍵}¨b←π¨⍳⍵} ``` test: ``` f←{≢b/⍨{(⍵≡∪⍵)∧2=≢⍵}¨b←π¨⍳⍵} f 1 0 f 9 1 f 62 18 f 420 124 f 1000 288 f 10000 2600 f 100000 23313 ``` this is a longer alternative (59 chars that i would prefer) ``` r←h w;n;t n←4⋄r←0 n+←1⋄→0×⍳w<n⋄→2×⍳(2≠≢t)∨2≠≢∪t←πn⋄r+←1⋄→2 ``` test: ``` h 1000000 209867 ``` ]
[Question] [ *Derived from [this](https://codegolf.stackexchange.com/q/179836/43319), now deleted, post.* Given a string, answer (truthy/falsy or two consistent values) if it constitutes a good Bishop password, which is when all the following conditions are met: 1. it has at least 10 characters 2. it has at least 3 digits (`[0-9]`) 3. it is not a palindrome (identical to itself when reversed) You get 0 bytes bonus if your code is a good Bishop password. **Warning:** Do *not* use Bishop goodness as a measure of actual password strength! ## Examples ### Good Bishop passwords `PPCG123GCPP` `PPCG123PPCG` `PPCG123gcpp` `0123456789` `Tr0ub4dor&3` ### Not Good Bishop passwords `PPCG123` (too short) `correct horse battery staple` (not enough digits) `PPCG121GCPP` (palindrome)  (too short and not enough digits) `abc121cba` (too short and palindrome) `aaaaaaaaaaaa` (palindrome and not enough digits) `abc99cba` (everything wrong) [Answer] # [Python 2](https://docs.python.org/2/), ~~61~~ ~~59~~ ~~54~~ 51 bytes ``` lambda s:sum(map(str.isdigit,s))>2<s[:9]<s<>s[::-1] ``` [Try it online!](https://tio.run/##jY@9bsJAEIR7nuIqzpYIwoYQbDkUoXAXuaBLKO7H4JMwe9pdhHh645AUB6Rgmx19M1rN@jM3cEi77ft3t1ettkpQTsc2apWPiHHsyLqd4xHF8TIt6CvPNgUVy17kL8mm8@gOLEsAKz4cNeCFV0QnQEu5HAyutthGsqpWZZJOy1VVyfgB/6x/8M54H@JJz2av87dFFtI1To56ZgGH0x7/8j9XfgKLp8uFRw0g1oZFA0i10Iq5xrMgVn5fPzZN7v8KtdKmTxitbmAwd@Esu2a7Cw "Python 2 – Try It Online") -5 bytes, thanks to Erik the Outgolfer -3 bytes, thanks to xnor [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gT@Iþg3@IÂÊP ``` [Try it online](https://tio.run/##yy9OTMpM/f8/PcTB8/C@dGMg2XS4K@D//4AAZ3dDI2N354AAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/9BCHysP70o2BZNPhroD/Ov@jlQICnN0NjYzdnQMClHQUYFwQhcRNTy4oAHENgGwTUzNzC0sQL6TIoDTJJCW/SM0YxEVSD2Im5xcVpSaXKGTkFxWnKiQllpSkFlUqFJckFuSkIpQawixOTEoG8pKTEsEcJACVtLSEyikoxQIA). **Explanation:** ``` g # Get the length of the (implicit) input T@ # Check if this length >= 10 Iþ # Get the input and only leave the digits g # Then get the length (amount of digits) 3@ # And check if the amount of digits >= 3 I # Get the input and the input reversed Ê # Check if they are not equal (so not a palindrome) P # Check if all three above are truthy (and output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~17~~ 14 bytes ``` ʨA&U¦Ô&3§Uè\d ``` *-3 bytes rearranged by @Shaggy* [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=yqgxMCZVptQmM6dV6Fxk&input=WwpUUlVFCiLKqDEwJlWm1CYzp1XoXGQiCiJQUENHMTIzR0NQUCIKIlBQQ0cxMjNQUENHIgoiUFBDRzEyM2djcHAiCiIwMTIzNDU2Nzg5IgoiVHIwdWI0ZG9yJjMiCkZBTFNFCiJQUENHMTIzIgoiY29ycmVjdCBob3JzZSBiYXR0ZXJ5IHN0YXBsZSIKIlBQQ0cxMjFHQ1BQIgoiYWJjMTIxY2JhIgoiYWFhYWFhYWFhYWFhIgoiYWJjOTljYmEiCl0gLW1S) --- # [Japt](https://github.com/ETHproductions/japt), 15 bytes (0 Bytes Bonus :v) ``` ʨ10&U¦Ô&3§Uè\d ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=yqgxMCZVptQmM6dV6Fxk&input=WwpUUlVFCiLKqDEwJlWm1CYzp1XoXGQiCiJQUENHMTIzR0NQUCIKIlBQQ0cxMjNQUENHIgoiUFBDRzEyM2djcHAiCiIwMTIzNDU2Nzg5IgoiVHIwdWI0ZG9yJjMiCkZBTFNFCiJQUENHMTIzIgoiY29ycmVjdCBob3JzZSBiYXR0ZXJ5IHN0YXBsZSIKIlBQQ0cxMjFHQ1BQIgoiYWJjMTIxY2JhIgoiYWFhYWFhYWFhYWFhIgoiYWJjOTljYmEiCl0gLW1S) [Answer] # [R](https://www.r-project.org/), ~~80~~ ~~70~~ ~~62~~ ~~64~~ 63 bytes ``` any(rev(U<-utf8ToInt(scan(,'')))<U)&sum(U>47&U<58)>2&sum(U|1)>9 ``` [Try it online!](https://tio.run/##VY7BjoIwEIbvPsXETaBNViKKCgnLxYPZGwd5gFJaJGFbMi2rxvXZWZRdxR6m@b75JzPYvcERWQOGM0UoVAoYyFZxW2kFUiMIZiqBYIWxlSon8uO/S070cpuKZw/jeR69nK4dU2eC4ptk8ay1MtzrT2XJfcO761JK44w6pv0iWRJsnCxehTRZDOLHp0nUXSeSTA@irvVRY134i@WU9spN0@2uh902Td2xuH0vouRNM4h5T8FqvQmjgfc4b/Og0OgsXyYG4BpRcAsHjUZAzqwVeAZjWVOLcdx/njBUlvPe8pz94eg9AlH07PfxQpZ37n4B "R – Try It Online") From digEmAll, and some rearranging too ``` sum((s<-el(strsplit(scan(,''),"")))%in%0:9)>2&!all(s==rev(s))&s[10]>'' ``` [Try it online!](https://tio.run/##DcpLCoAgEADQsySoM2CQtirKi0QLKaFg@uD0Ob711i/lzPcGwF0ZCfhKfNJ6AU9hB6M1GiEQUa67rNoGvVNFoP/1fYoPMKLiwVaj1zqLJRId75Fotq4W@QM "R – Try It Online") Pretty straightforward, no real amazing tricks here. After user inputs string: * Separates and searches the string for more than 2 numbers. (3 or more digits) * Checks if not all elements are equal to the reversed version of the string (palindrome) * Checks that length is greater than 9 (10 or more characters) [Answer] # APL+WIN, ~~36, 30~~ 29 bytes 7 bytes saved thank to Adám Index origin = 0 Prompts for input string ``` (10≤⍴v)×(3≤+/v∊∊⍕¨⍳10)>v≡⌽v←⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv4ahwaPOJY96t5RpHp6uYQxka@uXPeroAqHeqYdWPOrdbGigaVf2qHPho569ZUCNQAP@A7X@T@NSJ0uzOgA "APL (Dyalog Classic) – Try It Online") Explanation: ``` (10≤⍴v) Length test pass 1 fail 0 (3≤+/v∊∊⍕¨⍳10) Number of digits test >v≡⌽v Palindrome test ``` The code also qualifies for the bonus as it is a good Bishop password. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 12 bytes *Thanks for the tips, [Kroppeb](https://codegolf.stackexchange.com/users/81957/kroppeb) and [Fatalize](https://codegolf.stackexchange.com/users/41723/fatalize)!* ``` ¬↔?l>9&ịˢl>2 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9CaR21T7HPsLNUe7u4@vSjHDiimFFJkUJpkkpJfpGas9B8A "Brachylog – Try It Online") ### Explanation The program is a single predicate, composed of two parts that are chained with `&`. First: ``` ¬ The following assertion must fail: ↔ The input reversed ? can be unified with the input Also, the input's l length >9 must be greater than 9 ``` Second: ``` ˢ Get all outputs from applying the following to each character in the input: ị Convert to number This gives an integer for a digit character and fails for a non-digit, so we now have a list containing one integer for each digit in the password l Its length >2 must be greater than 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ~Tṫ3ȧL9<Ɗ>ṚƑ ``` [Try it online!](https://tio.run/##AS8A0P9qZWxsef//flThuaszyKdMOTzGij7huZrGkf/Dh8WS4bmY//9QUENHMTIxR0NQUA "Jelly – Try It Online") `[]` if not enough digits (empty list, falsy), `0` if otherwise bad (zero, falsy), `1` if good (nonzero, truthy). [Answer] # Java 8, 92 bytes ``` s->s.length()>9&s.replaceAll("\\D","").length()>2&!s.contains(new StringBuffer(s).reverse()) ``` [Try it online.](https://tio.run/##TZHLbgIhFIb3PsUpCwMZnXjrZWpq0trEVc0kdqcuGGR0LMIEGBtj3PYB@oh9kSnoTJQF8HHO4f8PbOmetrerr5IJagx80EweGwCZtFynlHGYegRIlBKcSmB4ZnUm12DI0AVODTcZS23GYAoSXqA07ZEJBZdru8FkFDVNqHku3FWvQmC0WLyjFkLkmtFr3pmQKWmdtMGSf8NF4a1IU66xIa5@z7XhmJBy6PXyIhFOr5Ldq2wFO1dcOZsvgZKL6VTp2q7lxo6p4fAMV4n58ojieDzp9vqTcRyjFtTolxtcszz32HH7wf3D41Pk6VN3imSwUrrZ93iT77dMac2ZhY1y3iGh1r3owZvOBb@mdmthmjBHLKFnuBlVMIqqGKATOXcHMDsYy3ehKmyYu36skO6BEQrqZgNH8PfzCyiQIcP1Mam@7lT@Aw) **Explanation:** ``` s-> // Method with String parameter and boolean return-type s.length()>9 // Check if the length of the input-String is more than 9 &s.replaceAll("\\D","") // AND: remove all non-digits from the input-String .length()>2 // and check if the amount of digits is more than 2 &!s.contains(new StringBuffer(s).reverse()) // AND: check if the input-String does NOT have the reversed // input-String as substring (and thus is not a palindrome) ``` [Answer] # JavaScript, ~~60~~ ~~56~~ 46 bytes Takes input as an array of characters. Outputs `1` for truthy and `0` for falsey. ``` s=>/(\d.*){3}/.test(s[9]&&s)&s+``!=s.reverse() ``` [Try It Online!](https://tio.run/##TY7BbsIwEETv/orAIbILOEAokEOQKtRy4RABPaWRcJwFWqXY8rqIquLbQ1zRkr3sPs1qZj7ESaA079r2jqqAahdXGM8C@lbwB/YTXgJuAS3FNMp8H5mPne22FSM3cAKDQFkl1RFVCbxUe5oSEgTeZvX6TNpJMl8MhuFiniTt7j@61cC91Nphv75Hj@PJNHK0Mf2vfFQo44c1OsuXp@X67ul@pDIGpPUOqq7h5cJaMN8eWqFLuAcM/uJFLmuSufiFxtzEKHIaIRn/FJqe49mOppzzc8YYq64) Saved 10 bytes(!) thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld). [Answer] # [Racket](https://racket-lang.org/), 122 bytes ``` (define(d s)(let([t(string->list s)])(and(< 2(length(filter char-numeric? t)))(< 9(length t))(not(equal? t(reverse t)))))) ``` [Try it online!](https://tio.run/##hY89T8QwDIb3/oqoSMgdTtwXH5UQDDfc2oENMbiJr43IpcVxke7XH05BBxtWpPjJ@0avzWjfSc5XAWNneIabFhOdwdHBRwJnUgWBBF4FkrCP3eIp@CT6/FYBRgePZq2G2EkPBx@E2NgeeRGnI7G3z0aqqlJT/WPKDHEQoI8Jg8rA9EmcaDZqabRPY8BTiAaOOBpnCpgji7JpdvvVerPfNU35i/kqL9TZcVRaaru9vbt/qBVeeDm1Wzfw9abUiKL4P0N/2YGZrJh@yOO1KLrcySTBMdAlbzUPU5R6sLXKtsXc/6lvqa6zkhf8Ag "Racket – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 25 [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") ``` {∧/(9<≢⍵)(3≤+/⍵∊⎕D),⍵≢⌽⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRx3J9DUubR52LHvVu1dQwftS5RFsfyHzU0fWob6qLpg6IDZTs2Qtk1P5Pe9Q24VFvH1DK0/9RV/Oh9caP2iYCecFBzkAyxMMz@H@agnpAgLO7oZGxu3NAgDoXgg@ikPnpyQUFYL4BkGNiamZuYQnmhhQZlCaZpOQXqRmrcyGpB0sm5xcVpSaXKGTkFxWnKiQllpSkFlUqFJckFuSkIhluCLf8UUMzmE5MSgYKJyclQnhIACZtaQmSBQA "APL (Dyalog Unicode) – Try It Online") [Answer] # Perl 5 `-p`, 33 bytes ``` $_=/.{10}/&y/0-9//>2&reverse ne$_ ``` [TIO](https://tio.run/##TYw9C8IwFEX3/IoOpVtN0g81gy4dumZwL0l8aKE04SUKRfzrxlZa8C73cLhcBzjUMabdie5enL1pNlGWC0rPRYbwBPSQjJB2MUrZtLwo20ZKsvJSG9@Mc4TNUNX7w1GQC7KHrq4Ws3KbEGMRwYTkbpdbrUIAnBIflBtgHfHfP1HazGy0IuovixZith/rQm9HH3M3fAE) [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 66 bytes ``` import StdEnv $s=s<>reverse s&&s%(0,8)<s&&sum[1\\c<-s|isDigit c]>2 ``` [Try it online!](https://tio.run/##XZBNa4NAEIbP@iv2kPoBCWiSthE0l6QNhR6E5GakjOvWCKsrO2tCoL@9VgMm2r3M7sMz@w5DOYOyKURac0YKyMsmLyohFdmr9K086xMM0F9LdmYSGUHDwCfLma5sv7vWReQej9Sf4U@O2zzLFaHxet7sFbQ/BAQ4J5YVBPZB1swmVgEVmZBMiPSrAsSLkCnaxDAe4jtwfJgJDEX9cmKS6dq4v42JIjMMNzt3vthtwtCMp7qm3VFX/qGMVlWPnPa9fH55XXk9OUinTpapkMbCjGNdGw0xSus7qJCSUUVOottRAkoxeSWooOJsHO0OB4SEtoQmcAeDM5A87@bEzS/95pBhM/v4bLbXEoqc4h8 "Clean – Try It Online") * `s<>reverse s`: `s` is not a palindrome * `s%%(0,8)<s`: the first 9 characters of `s` are less than all of `s` * `sum[1\\c<-s|isDigit c]>2`: `s` has more than two digits [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes ``` G`.{10} G`(\d.*){3} +`^(.)(.*)\1$ $2 ^.. ``` [Try it online!](https://tio.run/##TYw9C4MwGIT391c42BJbCEbth7ND1gwdRfJhsIVS5TUdivjb01gUess9dxyH1j1eyu8Il55LOrF0Bi5J3dJDMuUzHGVDaEJCqlkMcQYNpd4LUXGW5bwSAlZebOPODAOkAYrT@XIt4YbpWxdtj/t8m4DpEa1x0b3H0UZaOWfxE41ODU@7jtjvH5Q2gY1WoP601GUZ2i8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` G`.{10} ``` Checks for at least 10 characters. ``` G`(\d.*){3} ``` Checks for at least 3 digits. ``` +`^(.)(.*)\1$ $2 ``` Remove the first and last character if they match. ``` ^.. ``` If there are at least 2 characters then it wasn't a palindrome. .NET's balancing groups mean that this can be done in a single regular expression, but that takes 47 bytes: ``` ^(?!(.)*.?(?<-1>\1)*$(?(1).))(?=.{10})(.*\d){3} ``` [Try it online!](https://tio.run/##TYw9C8IwFEX3/IoKKi8FQ2PrR0HN0KFrBsciJmlQQWx5jYOU/vbYSgve5R4Ol4vWPV7KLyC/@guIGTAaMgHisOKngtNwDgI4ZZSCOLKWRx0FFhYlbePOeymznK/jPJOSjDzUxDdT1yTqIdlsd/uUnDF666SscBlPE2IqRGtccK@wsYFWzln8BI1T9dOOI/77J0qbno1WRP1l0Gna2y8 "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # [Red](http://www.red-lang.org), ~~117~~ 111 bytes ``` func[s][d: charset"0123456789"n: 0 parse s[any[d(n: n + 1)| skip]]all[n > 2 9 < length? s s <> reverse copy s]] ``` [Try it online!](https://tio.run/##ZY49b8MgEEB3fsWJIUrVxU7SNnaiZIjUrFbVDTFgwHEUhNFBIlnqf3dhKo25gdO7r4daTV9aMU66euruVjLPmapB9gK9DrQoV@vN2/vHtqK2hgJcwuCZsCNTy4gsvEL58kP87eo4F8YwCwdYQQV7MNpeQn8EH2N/ANQPnabl4EbwnE8OrzZAB7RpTud46HxqGkqeafrm9CKdy2jm@Qe/sbi3GzXgYk0J2X0K48d6tikbkAOilgH6IXm2IgSNUTUIZ/RMoXzSzVLRyliXrchZ9v63VlXqnH4B "Red – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~74~~ ~~72~~ 64 bytes Thanks [Neil A.](https://codegolf.stackexchange.com/users/69401/neil-a) for -2 bytes! Thanks [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for -8 bytes! ``` lambda s:s[9:]and re.findall('\d',s)[2:]and s[::-1]!=s import re ``` Explanation: ``` lambda s: # Create lambda s[9:] # Check if the string is at least 10 characters long and re.findall('\d',s)[2:] #Check for at least 3 matches of the regex \d (which matches all digits) and s[::-1] != s # Check if the string reversed is equal to the string (palindrome test) import re # Import regex module ``` [Try it online!](https://tio.run/##rVHLboMwEDzDV2yJ1IBEo7z6AIlDlLZRpR6Q0hvJwYADlsC2bKdNVPXbqSEooSrqqXuxxzs7s7vmR5UzOqsEBLCpClTGKQLpy8jzt4imIPBoR2iKisIebtKhK51oesrIyPdvJturQJqk5Ewoza0SJgROVBCZhhWGy9VkOlstw9ByL7g@ujhLOG/wWIP57d39g9fANzHex/OUieuZZW5NQnu0LdeoY2ArxkDmuglHJ1siaCwxxEgpLI4gFeIFbioGNmUKMGX7LIeUZERJ5yw6OTXcCnNU6PEFK3HNaJ@7hlDvolcOxYlWS2L0u8um6Kc06kSP@582nle7tDX4XU@rckIz@BCMZo5e3o4JOACh0K7GNw2yA2EfHH0zuCBU2Va4WK@fHuHzyxppfomUTmsDXEjcYT0vXl57WMbF4/xTJ5e66f9zqr4B "Python 3 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 32 bytes ``` {$_ ne.flip&&m:g/\d/>2&&.comb>9} ``` [Try it online!](https://tio.run/##TYy9CsMgAIR3n8KhOOa/aS3UJUNWh46FosakARNF7RBKn92akkBvuPs4jjPSqjpMC0Q9vMLwPjzgLJNejQah6TKk9y4lBUKJ0BMn@BPUOEtHSIL6aI4tgdKmzYuybSgFG6@x8yCMAVmE6lifzhjcbPbiVactKvcJENpaKTx8ausk5Mx7aRfoPDNKbqP89w8YF5EFZ4D9aa0xju0X "Perl 6 – Try It Online") Anonymous code block that simply enforces that all the rules are complied with. ### Explanation: ``` { && && } # Anonymous code block $_ ne.flip # Input is not equal to its reverse m:g/\d/>2 # There are more than two digits .comb>9 # There are more than 9 characters ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~31~~ 28 bytes -3 bytes thanks to ngn! ``` {(x~|x)<(2<#x^x^/$!10)*9<#x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqOirqZC00bDyEa5Iq4iTl9F0dBAU8sSyKv9n6auoRQQ4OxuaGScnlxQoGQN44EoIM8AyDQxNTO3sARyQooMSpNMUvKL1IwRCqHaCCsEspLzi4pSk0sUMvKLilMVkhJLSlKLKhWKSxILclKVNB81NP8HAA "K (oK) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 70 bytes ``` a=>a.length>9&(a.match(/\d/g)||[]).length>2&a!=[...a].reverse().join`` ``` [Try it online!](https://tio.run/##TY/LboMwEEXX5SumKIpsqXGefaAINiyyZdEdQWIwBhJRjGwXqSJ8O4UqNMxm5sy90sy9YoOaq0ttVpVMRZ@5PboeslJUuSk8Z0mQfaHhBVmf03VOb7cwopO6W@KzGzLGMGJKNEJpQSi7yksVx32DCozQxkctNLgQ2kHgn7a7/ckPAvsFJhzbDHNe1yNuhvnw@vb@4Yz0qTbfySGVarkfceYfRy6VEtxAIYcPIEFjhPoBbbAuxcO6nQ5jwgfiCf7BrO6i49w1sKOjZWVSASmF@U8DMnsko9BaT1xWWpaClTInsb1oJ7WzYeXBos3ItKFdTI9W1/8C "JavaScript (Node.js) – Try It Online") Returns 1 for true and 0 for false [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 67 bytes ``` n=>n.Count(char.IsDigit)>2&!n.Reverse().SequenceEqual(n)&n.Length>9 ``` [Try it online!](https://tio.run/##TY5dS8MwGIXv8ytiLkoCNbTb/KhzRag6hF0UJ3jjTRrftoHypkvSgYz99trJBp6b83A4HI7219qb8XVA/eiDM9jElbVdXq9GXOUoCztg4LpVTr75Z9OYIPJZdIXyHfbgPHAht7AbADW87AbVcRQRyg1gE9o8G5ektg6UbvleOWqoQfrEyrJYp7P5uihLcuaTXbjRfU@SCRY3t3f3GflwyVAtvq2L5pcK0dY50IG2dvpAKxUCuB/qg@o7OJfSv31V6Ql1pYj6p1OcZVPK5LbvTODsC5kQ5NOZABuDwNkhOT7QQ3pksYlrboRYjr8 "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 19 bytes ``` #a>9&XD Na>2&aNERVa ``` [Try it online!](https://tio.run/##K8gs@B@vV6xX/V850c5SLcJFwS/Rzkgt0c81KCzxf62Cr0I0l4JSQICzu6GRsbtzQIASgguikLjpyQUFIK4BkG1iamZuYQnihRQZlCaZpOQXqRkjqQUxk/OLilKTSxQy8ouKUxWSEktKUosqFYpLEgtyUhFKDWGWgnBiUjJQJDkpEcxBAlBJS0uwXOz//7p5/6FWAQA "Pip – Try It Online") (all test cases) ### Explanation With `a` being the first command-line argument: ``` #a > 9 Length of a is greater than 9 & and XD N a > 2 Number of matches of regex [0-9] iN a is greater than 2 & and a NE RV a a is not (string-)equal to reverse of a ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ûc╖»¬ë⌂╓âó╗cCé ``` [Run and debug it](https://staxlang.xyz/#p=9663b7afaa897fd683a2bb634382&i=%22PPCG123GCPP%22%0A%22PPCG123PPCG%22%0A%22PPCG123gcpp%22%0A%220123456789%22%0A%22Tr0ub4dor%263%22%0A%22PPCG123%22%0A%22correct+horse+battery+staple%22%0A%22PPCG121GCPP%22%0A%22%22%0A%22abc121cba%22%0A%22aaaaaaaaaaaa%22%0A%22abc99cba%22&a=1&m=2) [Answer] # Pyth, 17 bytes ``` &&<2l@`MTQ<9lQ!_I ``` Try it online [here](https://pyth.herokuapp.com/?code=%26%26%3C2l%40%60MTQ%3C9lQ%21_I&input=%22Tr0ub4dor%263%22&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=%26%26%3C2l%40%60MTQ%3C9lQ%21_I&test_suite=1&test_suite_input=%22PPCG123GCPP%22%0A%22PPCG123PPCG%22%0A%22PPCG123gcpp%22%0A%220123456789%22%0A%22Tr0ub4dor%263%22%0A%22PPCG123%22%0A%22correct%20horse%20battery%20staple%22%0A%22PPCG121GCPP%22%0A%22%22%0A%22abc121cba%22%0A%22aaaaaaaaaaaa%22%0A%22abc99cba%22&debug=0). ``` &&<2l@`MTQ<9lQ!_IQ Implicit: Q=eval(input()), T=10 Trailing Q inferred `MT [0-10), as strings @ Q Take characters from input which are in the above l Length <2 Is the above greater than 2? lQ Length of Q <9 Is the above greater than 9? _IQ Is Q unchanged after reversal? ! Logical NOT && Logical AND the three results together ``` [Answer] # Groovy, (47 bytes) ``` {p->p=~/.{10}/&&p=~/(\d.*){3}/&&p!=p.reverse()} ``` (Bonus inclusion is left as an exercise to the reader) ]
[Question] [ [Machine epsilon](http://en.wikipedia.org/wiki/Machine_epsilon) is an important floating point number to know when doing numerical calculations. One way to understand it is when this relation ``` 1 + machine_epsilon > 1 ``` does not hold. One (iterative) way to extract it is executing a small program like the one above: ``` 10 EPS=1 20 EPS=EPS/2 30 EPS1 = 1+EPS 40 IF EPS1 > 1 GOTO 20 50 PRINT EPS ``` But there may be more ways. Write the shortest code to extract the machine epsilon of your computer. **NOTE:** epsilon should be a non-zero value :) [Answer] ## PowerShell, 5 Since .NET has certain guarantees for `double`, this number will not change, regardless of the implementation of the CLR or the platform it runs on. Therefore, the following suffices: ``` 1/8pb ``` If you desperately need an iteration that computes the value in the way you've given in the task description, then that'd be 25 characters: ``` for($e=1;1+$e-1){$e/=2}$e ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish) - 18 16 characters ``` 1>2,:1v n^?)1+<; ``` Usage and output using the [python interpreter](https://github.com/harpyon/fish.py): ``` $ fish scripts/epsilon.fish 1.1102230246251565e-16 ``` **Edit** Fixed code to return correct value (`1.1e-16`) [Answer] ## JavaScript, 28 characters ``` for(y=1;y+1-1;y/=2);alert(y) ``` I could replace the `y+1-1` with `y+1>1`, but I like for aesthetics of the former. [Answer] **Brainfuck, 16** Brainfuck doesn't support floating-point arithmetic, so epsilon is 0. ``` -[>-<+++++]>---. ``` According to [this](http://www.esolangs.org/wiki/Brainfuck_constants), this is the smallest such program. Program assumes that cells are unsigned bytes mod 256. [Answer] ## Perl ``` $x=1;push@a,$x/=2while$x;die@a[$#a-1]; ``` [Answer] **Python, 29** ``` t=1. while t+1>1:t/=2 print t ``` **Python3, 28** "true" division sucks, IMO... but I'll use it to cut a character out ``` t=1 while t+1>1:t/=2 print t ``` [Answer] ## Haskell Update ``` until((==1).(1+))(/2)1 ``` Previous: For doubles ``` last$takeWhile(/=0)$iterate(/2)1 ``` For floats ``` last$takeWhile(/=0)$iterate(/2)(1::Float) ``` [Answer] ## PHP, 13 chars For `1 + epsilon > 1`, to be true, `1 + epsilon` must fit into the number of bits allotted to the mantissa (`5` in `5 * 10^4`) in floating point numbers. 52 bits are allotted to the mantissa in 64-bit floating point numbers. It follows that `1 + epsilon` is `1.000...(52)...0001` (base 2), and that `episilon` is `0.000...(52)...0001`. Calculating this number in decimal gives: ``` <?=pow(2,-52); ``` You'll notice that negatively exponentiating 2 is the same as repeatedly dividing by 2 -- which is what many of the solutions here do. Bonus, more platform-independent solution (13 chars): ``` <?=sin(pi()); ``` [Answer] # MATLAB, 3 bytes I'm going to post this purely because it's one of the rare opportunities for MATLAB to be one of if not the shortest. I think it is in the rules for what the question asks. ``` eps ``` Granted, not the most ingenious or exciting code though! [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~9~~ 8 bytes ``` 1{:›1>|½ ``` LOTM finally gave me a reason to actually try Vyxal, and so far I like it! -1 byte thanks to Aaron Miller [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=1%7B%3A%E2%80%BA1%3E%7C%C2%BD&inputs=&header=&footer=) [Answer] ## Mathematica 15 chars ``` $MachineEpsilon -> 2.220446049250313*10^-16 ``` [Answer] ## Ada - 151 ``` generic type T is digits <>;function E return T;function E return T is A,B,C:T:=1.0;begin loop A:=A/2.0;B:=C+A;exit when B<=C;end loop;return A;end E; ``` example usage: ``` procedure Main is function F is new E (Float); function D is new E (Long_Float); begin Put_Line ("Epsilon:" & Float'Image (F)); Put_Line ("Epsilon:" & Long_Float'Image (D)); end Main; ``` output: ``` Epsilon: 5.96046E-08 Epsilon: 1.11022302462516E-16 ``` [Answer] # Pyth - 5 bytes ``` .IhG1 ``` [Try it online here](http://pyth.herokuapp.com/?code=.IhG1&debug=0). Invert goes through all positive reals till it finds something that makes the lambda of `G` equal the second arg. So the code just inverts `1+G` till it equals `1`. [Answer] # Excel, 35 bytes ``` =LET(x,2^-ROW(1:99),MAX((1+x=1)*x)) ``` ## Excel (2010), 37 bytes ``` =MAX(2^-ROW(1:99)*(1+2^-ROW(1:99)=1)) ``` [Answer] # Java, 13 bytes It is easy by using the [ulp](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#ulp-double-) method. ``` Math.ulp(1.0) ``` Result is `2.220446049250313E-16`. [Answer] # [Grok](https://github.com/AMiller42/Grok-Language), 21 bytes ``` 1Y j qzph >1+1hY/2p{ ``` [Try it Online!](http://grok.pythonanywhere.com?flags=&code=1Y%20%20j%20qzph%0A%3E1%2B1hY%2F2p%7B&inputs=) That's right, there's an online interpreter now! For those wondering, the framework is modified from the online Vyxal interpreter. Explanation: ``` 1Y j # Push 1 and copy it to the register +1h # Add 1 >1 # Is it greater than 1? p{ # If yes, retrieve value from register Y/2 # Divide by 2 and copy it to the register, then repeat this line qzph # If no, retrieve value from register, { # then print as a number ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` Ωoε→½□√2 ``` [Try it online!](https://tio.run/##ARkA5v9odXNr///OqW/OteKGksK94pah4oiaMv// "Husk – Try It Online") Formula is the exact same as the reference implementation. Fixed with Leo's help by using decimals. [Answer] ## Ruby, 18 Just for the sake of completeness: ``` p Float::EPSILON/2 ``` [Answer] # Mathematica, 21 bytes ``` Print@$MachineEpsilon ``` [Answer] # JavaScript ES6 in a REPL,14 ``` Number.EPSILON ``` # JavaScript ES5 in a REPL,15 ``` Math.pow(2,-52) ``` [Answer] # MMIX, 16 bytes (4 instrs) (jelly xxd) ``` 00000000: e0003ff0 21010001 06000100 f8010000 ṭ¡?ṅ!¢¡¢©¡¢¡ẏ¢¡¡ ``` A bit of a hack: add 1 as int to 1.0, then subtract off as float. Disassembled: ``` eps SETH $0,#3FF0 ADD $1,$0,1 FSUB $0,$1,$0 POP 1,0 ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 63 bytes ``` #import<iostream> int main(){long x=1;std::cout<<*(double*)&x;} ``` [Try it online!](https://tio.run/##Sy4o0E1PTv7/XzkztyC/qMQmM7@4pCg1MdeOKzOvRCE3MTNPQ7M6Jz8vXaHC1tC6uCTFyio5v7TExkZLIyW/NCknVUtTrcK69v9/AA "C++ (gcc) – Try It Online") [Answer] # [GNU AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 34 bytes ``` BEGIN{for(e=1;1+e>1;e/=2);print e} ``` [Try it online! Features different epsilons for different precisions.](https://tio.run/##pZHNSsNAFIX38xSXdNNipyXqLqRQpRYXU0rBB5hM7iRDJzNxfigifXXHBBfqRpBs7/nOx4HLL@eUHnb758O7tG6OZV7kN7jJC1yXt4uid8oEwCvMgL3B3T0VLXdcBHTQWC3BWx2DsoYQMoOtqaFWUqLDsdR7GJQ/Lr1DofxA@xUwNcChRaAM5pRWqjGxWwB3TexGNlhAwyuNsD@8ADs@nYZMhbbDoMSKkK/Jx9PuscxarmVW/DF/CSOYfQ/Irr8EXplG4yRFbWM1UfEaeT1JYEX4bz@lD9uPD/SJsk8 "AWK – Try It Online") Thanks to GNU MPFR arithmetic, GAWK can rely on any arbitrary byte precision. [GAWK's manual reference.](https://www.gnu.org/software/gawk/manual/gawk.html#Setting-precision) The standard precision (double) returns `1.11022e-16`. ``` Result: 0.000488281 half precision 5.96046e-08 single precision 1.11022e-16 double precision 9.62965e-35 quad precision 4.52784e-72 oct precision ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` 1[D>1›_#; ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fMNrFzvBRw654Zev//wE "05AB1E – Try It Online") ``` 1[D>1›_#; # full program [ _# # while... 1 D # literal... D # or top of stack if not first iteration... > # plus 1... › # is greater than... 1 # literal... ; # halve top of stack # implicit output ``` [Answer] ## JavaScript (ES6), 24 bytes ``` (e=n=>n+1>1?e(n/2):n)(1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvFfI9U2z9YuT9vQztA@VSNP30jTKk9Tw1Dzv@Z/AA "JavaScript (Node.js) – Try It Online") Recursive solution, using the same algorithm as in the question. Its body is an IIFE, so it's an expression that directly evaluates to the epsilon value. ``` ( e = n => //Set e to the function, so we can call it later n + 1 > 1 //If n+1 is still greater than 1... ? e(n / 2) //...perform next iteration by calling itself with n halved : n //...else, we found epsilon, return it )(1) //Call the function with the initial value 1 ``` Fun fact: this will return the *half* of `Number.EPSILON`, as its value represents the smallest number that *can* be represented, i.e. `Number.EPSILON + 1 > 1`, while `Number.EPSILON/2 + 1 === 1`. [Answer] # PostScript, 37 bytes ``` ([){2 div dup 1 add 1 gt{[}if}def 1[= ``` Run through ghostscript (with optional -q to clean up output): ``` $ gs -q epsilon.ps 5.96046e-08 GS> ``` ]
[Question] [ This is a fairly simple code golf challenge. Your program, given an ASCII string, is to parse that string into two strings, which it will evaluate. If the second string is "later" than the first one, it will return a 1, if it is "earlier" than the first one, it will return a -1, and if they are the same, it will return 0. To clarify what "later" and "earlier" mean, let's take a look at ASCII character codes. You need to compare each character of the string, treating each of them as digits of a number. Later refers to a larger number, occurring after a smaller number. Strings will be formatted with a hyphen character to separate the two input groups. Take a look at this example: > > `7-9` as an input should return `1`. > > > `7` converts to ASCII code `55`, and `9` converts to ASCII code `57`. > > > As `57` occurs numerically after `55`, `9` is later than `7`. > > > Another example: > > `LKzb-LKaj` as an input should return `-1` > > > The ASCII code sequences for this are `76-75-122-98` and `76-75-97-106` > > > This is a code golf challenge, and byte count is how entries will be scored. Any input from the 95 printable ASCII characters is accepted, excluding spaces, and hyphens for anything but separating the input. In addition, strings are not guaranteed to be the same length. Good luck! **EDIT:** To be more clear, each character is to be treated like a digit in a number. In the example `LKzb-LKaj`, though `j` is later than `b`, `z` is later than `a`, and since it is a more significant digit, it takes precedence. A string supplied will always be at minimum 3 characters, eliminating empty strings from the scope of this problem. **EDIT:** Here are some more test cases, for your help: * `A-9` -> `-1` * `11-Z` -> `-1` * `3h~J*-3h~J*` -> `0` * `Xv-Y0` -> `1` [Answer] # Pyth - 11 bytes Easy, uses `._` sign to get the sign and `C` to get char codes. ``` ._-F_CMcz\- ``` [Try it online here](http://pyth.herokuapp.com/?code=._-F_CMcz%5C-&input=LKzb-LKaj&debug=0). [Test suite](http://pyth.herokuapp.com/?code=V.z._-F_CMcN%5C-&input=7-9%0ALKzb-LKaj%0AA-9%0A11-Z%0A3h%7EJ*-3h%7EJ*%0AXv-Y0&debug=0). ``` ._ Sign of number -F Fold subtraction (this finds difference of a tuple) _ Reverse list to get correct order of operands when subtracting CM Map char, already treats strings as digits of base256 number c \- Split by "-" z Input ``` [Answer] # CJam, 12 bytes ``` l'-/esfb~\-g ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l'-%2Fesfb~%5C-g&input=LKzb-LKaj). ### How it works ``` l e# Read a line from STDIN. '-/ e# Split it at spaces. es e# Push the current time (milliseconds since epoch). fb e# Consider each string as digits in base huge-number. ~\ e# Dump the results and reverse their order. -g e# Subtract and apply sign function. ``` [Answer] # Java, ~~86~~ 118 ``` int f(String...s){return(int)Math.signum((s=s[0].split("-"))[1].compareTo(s[0])*(s[0].length()==s[1].length()?1:-1));} ``` --- A very strange way of comparing strings. Made a quick fix so it passes additional test cases, will look for more golfiness later. *Thanks to Vartan in comments for `signum` suggestion* [Answer] # Perl, 31 bytes ``` #!/usr/bin/perl -p /-/;$_=($`.$'^$`)cmp($'.$`^$') ``` 30 bytes + 1 byte for `-p`. Accepts input on STDIN. ## Explanation When the operands to `cmp` have different lengths, like `chicken` and `egg`, they are aligned like this: ``` c h i c k e n e g g \0 \0 \0 \0 ``` so that `egg` > `chicken` (`\0` is a null byte). But we want them to be aligned like this: ``` c h i c k e n \0 \0 \0 \0 e g g ``` so that `chicken` > `egg`. To do this, we concatenate them, once with `chicken` before `egg` and once with `egg` before `chicken`: ``` c h i c k e n e g g e g g c h i c k e n ``` Now that our two strings are the same length, we remove the leading word using an XOR to get: ``` \0 \0 \0 \0 \0 \0 \0 e g g \0 \0 \0 c h i c k e n ``` And *now* we can use `cmp` to find which came first. (There, I said it!) [Answer] ## Python 2, 88 characters ``` a=raw_input().split('-');print-cmp(*(map(ord,s.rjust(max(map(len,a)),'\0'))for s in a)) ``` `cmp` doesn't do the right thing when you have two different length strings, so I have to pad both of them with the null character (which `ord` converts to `0`) to handle that case. Unfortunately, that added about 35 characters, plus it's now two lines instead of one because I need both the length of the input and to iterate over it. [Answer] # R, 54 Bytes This requires the pracma library. It splits the input string on the `-`. Right justifies the strings. Ranks them and does a diff. So for 11-7 we end up with the strings "11" and " 7". The rank of these is [2, 1]. The difference is -1. For 3h~J\*-3h~J\* we get "3h~J\*" and "3h~J\*". The rank of these is [1.5, 1.5] with a diff of 0. ``` diff(rank(pracma::strjust(scan(,'',sep='-'),"right"))) ``` Test Examples ``` > diff(rank(pracma::strjust(scan(,'',sep='-'),"right"))) 1: LKzb-LKaj 3: Read 2 items [1] -1 > diff(rank(pracma::strjust(scan(,'',sep='-'),"right"))) 1: A-9 3: Read 2 items [1] -1 > diff(rank(pracma::strjust(scan(,'',sep='-'),"right"))) 1: 11-Z 3: Read 2 items [1] -1 > diff(rank(pracma::strjust(scan(,'',sep='-'),"right"))) 1: 3h~J*-3h~J* 3: Read 2 items [1] 0 > diff(rank(pracma::strjust(scan(,'',sep='-'),"right"))) 1: Xv-Y0 3: Read 2 items [1] 1 ``` [Answer] # CoffeeScript, 143 140 139 ``` f=(s)->[a,b]=((t=s.split '-').map (y)->Array((m=Math.max) 1, 1+(m ((l=(c)->c.length) t[0]),l t[1])-l y).join('\u0000')+y);`b<a?-1:(b>a?1:0)` ``` [Here](http://jsfiddle.net/p7x0gq1b/4/) is a jsfiddle with the results (look in the console) [Answer] # PERL, 46 36 Bytes ``` print$2cmp$1if"@ARGV"=~/(\S+)-(\S+)/ ``` Converts the argv list into a string, splits by the hyphen into a left and right sided no spaces arg, then returns a cmp call. [Answer] # Python 3, 84 bytes ``` x,y=[int.from_bytes(i.encode(),"big")for i in input().split("-")];print((x<y)-(y<x)) ``` Split the string input by `"-"`. Convert the unicode strings to bytes strings, then interpret these byte strings as big-endian integers. Finally do the comparison -- (un)fortunately `cmp` is no longer available in Python 3. # Python 2, 69 bytes ``` print -cmp(*[int(i.encode("hex"),16)for i in raw_input().split("-")]) ``` [Answer] # Python 2, 79 bytes Pretty simple solution, and it's easy to understand. Compares string lengths, then compares the strings lexigraphically. [**Try it here**](http://ideone.com/AIL8mF) ``` s,t=raw_input().split('-') x,y=len(s),len(t) print(x<y)*2-1if x-y else cmp(t,s) ``` [Answer] # perl5, 64 ``` perl -aF- -pe '@f=map{length}@F;$_=$f[1]<=>$f[0]||$F[1]cmp$F[0]' ``` Just run it from the commandline. although it would look better with a new line but that costs 1 char. ``` perl -laF- -pe '@f=map{length}@F;$_=$f[1]<=>$f[0]||$F[1]cmp$F[0]' ``` This longer version handles mismatched lengths correctly. [Answer] # F#, 53 ``` fun s->let[|a;b|]=s="";s.Split[|'-'|]in b.CompareTo a ``` This is in the form an anonymous function (lambda), so you have to paste it and provide the parameter directly after is (or, using the piping notation). For example (in FSI): ``` > "7-9" |> fun s->let[|a;b|]=s="";s.Split[|'-'|]in b.CompareTo a 1 > "abc-abc" |> fun s->let[|a;b|]=s="";s.Split[|'-'|]in b.CompareTo a 0 > "LKzb-LKaj" |> fun s->let[|a;b|]=s="";s.Split[|'-'|]in b.CompareTo a -1 ``` [Answer] # JavaScript ES6, 46 43 bytes ``` f=s=>((a=s.split('-'))[1]>a[0])-(a[1]<a[0]) ``` [Answer] # Ruby, 59 bytes ``` a,b=gets.chomp.split ?- p (b.size<=>a.size).nonzero?||b<=>a ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '-¡₄ö¥0.S ``` [Try it online](https://tio.run/##MzBNTDJM/f9fXffQwkdNLYe3HVpqoBf8/7@Pd1WSro93YhYA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TFnKxSevQykp7JYVHbZMUlOwr/6vrHlp4aN3hbYeWGugF/9f5b65ryeXjXZWk6@OdmMXlCOQZGupGcRln1Hlp6YJJrogy3UgDoJSjIwA). **Explanation:** ``` '-¡ # Split the (implicit) input on '-' # i.e. 'LKzb-LKaj' → ['LKzb','LKaj'] ₄ö # Convert both parts to a Base-1000 number # i.e. ['LKzb','LKaj'] → [21020061037,21020036045] ¥ # Push the deltas (subtraction between each sub sequential pair) of the list # i.e. [21020061037,21020036045] → [-24992] 0.S # Get the sign [1 for a>0; -1 for a<0; 0 for a==0] (and output implicitly) # i.e. [-24992] → [-1] ``` ]
[Question] [ [Grimm's conjecture](https://en.wikipedia.org/wiki/Grimm%27s_conjecture) states that, for any set of consecutive composite numbers \$n+1, n+2, ..., n+k\$, there exist \$k\$ distinct primes \$p\_i\$, such that \$p\_i\$ divides \$n+i\$ for each \$1 \le i \le k\$. For example, take \$\{24, 25, 26, 27, 28\}\$. We can see that if we take the primes \$2, 5, 13, 3, 7\$, each composite number is divisible by at least one of the primes: $$ 2 \mid 24 \quad 5 \mid 25 \quad 13 \mid 26 \\ 3 \mid 27 \quad 7 \mid 28 $$ Note that it doesn't matter that \$26\$ is also divisible by \$2\$, so long as, for each composite number, there is a corresponding prime that divides it. For the purposes of this challenge, we'll assume Grimm's conjecture is true. Given a list of \$n\$ consecutive composite integers \$C\$, in any reasonable format, return a list of \$n\$ distinct prime numbers \$P\$ such that, for each \$c\$ in \$C\$, there is a corresponding \$p\$ in \$P\$ such that \$c\$ is divisible by \$p\$. You may return any such list in any order, and in any reasonable format. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Test cases ``` [4] -> [2] [6] -> [2] [8, 9, 10] -> [2, 3, 5] [12] -> [2] [14, 15, 16] -> [7, 3, 2] [18] -> [2] [20, 21, 22] -> [2, 3, 11] [24, 25, 26, 27, 28] -> [2, 5, 13, 3, 7] [30] -> [2] [32, 33, 34, 35, 36] -> [2, 11, 17, 5, 3] [38, 39, 40] -> [2, 3, 5] [42] -> [2] [44, 45, 46] -> [2, 3, 23] [48, 49, 50, 51, 52] -> [2, 7, 5, 3, 13] [54, 55, 56, 57, 58] -> [2, 5, 7, 3, 29] [60] -> [2] [62, 63, 64, 65, 66] -> [31, 3, 2, 5, 11] [68, 69, 70] -> [2, 3, 5] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes [Try it online!](https://tio.run/##Fcy9DcJADEDhhV5x57/c7cAGUXokFIGEMgAMQc0UFJQMwBAscsSFLUufno/b9TQ@r/V3v43f430@bN/nehljzLMtzLFPo1PLflTJZVSnJtS2LylIRZLEEEcCmZA0zUoFVdRQRzPThnYszTIzwxxLsoZ1vOAVT3PDHQ98wvNlZBZCKGGEE9lFIzpTWZY/ "Husk – Try It Online") ``` mp -- prime factors of each number Π -- cartesian product of this list of lists ► -- find the element that maximizes: oLu -- (2 functions composed) the length of the unique values ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ÆfŒpQƑƇ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW9rRSQWBxyYea/8fbWSiY2SqY2SmY2SuY2QRe7j9PwA "Jelly – Try It Online") Are brownie points redeemable for actual brownies? Similar to ovs' answer and my Vyxal answer. Returns a bunch of duplicates because Jelly has no 'distinct prime factors' builtin. ``` Æf Prime factors Œp Cartesian product of all Ƈ Filter by Ƒ Remains same under Q Uniquify ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḋᵐ∋ᵐ.d ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7odbJzzqAJF6Kf//Rxua6Bia6hiaxf6PAgA "Brachylog – Try It Online") ``` ?ḋᵐ∋ᵐ.d. # implicit input and output ?ḋᵐ # prime decompositions of each number in the input ∋ᵐ. # for each prime decomposition one number is in the output .d. # and: the output without duplicates is still the output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` vǏΠ'Þu ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ2x4/OoCfDnnUiLCIiLCJbMjQsMjUsMjYsMjcsMjhdIl0=) Similar to ovs' answer. Outputs a list of lists of primes. ``` vǏ # Prime factors of each Π # Cartesian product ' # Filter by Þu # All unique ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 22 bytes [SBCS](https://github.com/abrudz/SBCS) ``` (⊢∩∪¨)∘,∘↑(∘.,/3∘pco¨) ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=Uy9Izld/1Dc1uVI9JS2vWB0A&c=03jUtehRx8pHHasOrdB81DFDB4gftU3UAFJ6OvrGQKogOR8oBQA&f=e9Q39VHbhDQFQxMFQ1MFQzMFAA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) -7 thanks to people on APLFarm. Requires `pco`. There is no `pco` on TryAPL, so you need Dyalog APL installed locally. Outputs all possibilities. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` ⊞υ⟦⟧FEAΦι∧›λ¹¬﹪ιλ«≔υη≔⟦⟧υFΦι⬤ι∨⁼κμ﹪κμFη¿¬№λκ⊞υ⁺λ⟦κ⟧»Iυ ``` [Try it online!](https://tio.run/##TY/LSgQxEEXX9lfUsgJx4eALXA2DiovR3ocswjzs0GVnTFJuxG@PVcEBA5dw63FusptC3qVArY1cJmQLzpuH4Zgy4Dac8GU5cUVj4SlSPWSMFtbLHp/zIaglC1fSfE0Vt2nPlHSATD/wPVysS4nvi2InoZ6t8xZYfY/5RybS6y3j4ycHKjhb@BD8H7q7Tu57k4F4BNTsTeKl6mNm7Z5/MhIXLbrZG0n7GcYcZWwTSkWWSmvOra4trG5Et6I70b337fKLfgE "Charcoal – Try It Online") Link is to verbose version of code. Outputs all sets. Explanation: ``` ⊞υ⟦⟧ ``` Start with the empty set for `k=0`. ``` FEAΦι∧›λ¹¬﹪ιλ« ``` For each input composite number, get its factors. ``` ≔υη≔⟦⟧υ ``` Make a backup of the sets found so far. ``` FΦι⬤ι∨⁼κμ﹪κμ ``` For each prime factor of the current composite number, ... ``` Fη ``` ... and for each set, ... ``` ¿¬№λκ ``` ... if the set doesn't have that prime factor yet, then... ``` ⊞υ⁺λ⟦κ⟧ ``` ... record a new set that does. ``` »Iυ ``` Output the sets that managed to acquire a prime factor for each input composite. [Answer] # JavaScript (ES6), 98 bytes ``` f=(A,b=[],k=2,[n,...a]=A)=>n?k>n?0:n%k?f(A,b,k+1):!b.includes(k)&&f(a,[...b,k])||f([n/k,...a],b):b ``` [Try it online!](https://tio.run/##lVLLboMwELz3K9xDI6y6gJ8kSDTKdyAfgECVEpmqaXvKv9MhQU2EU4lY2tPuPHbW78VPcag@dx9fL67b1n3fZMGGlVluWZsJljsWhmFhsw3NXt26RcWpe2rXzTDF2mdO08cy3Llq/72tD0FLF4smKFgOFNqWHo9NkLuoPdOwkqZlX3Xu0O3rcN@9BegqS6aPUhJFJBf2YTJr7phdMrJihMfWn2VEMqI9BBd2NjtX4Naoi6VxNjmx30As57OLGAwcJexN75z7EBgSMCQMCh7E0l4gg1F5QiYeUMbzfclBfiCCmASpNFciHIZ5chKTPhLnkLiHiu3Ma6g7rqHgR0FXmdvswjekYEjBkEbUGs61uFpl3GJIzQNqaGl0NYLWw@Ak6PH@K//z3hG0AZcBjYGYAan5C1ryM//5qP4/MNjLYK/k36D7Xw "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 105 bytes ``` ->l,*r{(2..l[0]).map{|x|r.any?{|y|x%y<1}||r<<x};r.permutation(l.size).find{|c|c.zip(l).all?{|a,b|b%a<1}}} ``` [Try it online!](https://tio.run/##Dc1BCsMgEADAr/QS0JAubQ9eatuHiAdNIwjGiklA4/p26wOGiYfOzbza9e2mMRbyAHDiJimsKhRMGEH5/CmYMQ2Z3yti5DzVZ4SwxPXY1W5/njjY7LlQMNZ/C844w2kDcRSUcx2rSaMeVOe1tnAxQoysR4xJ2f4 "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` f˜Igã.ΔÙÖ*Q ``` Outputs one result. [Try it online](https://tio.run/##yy9OTMpM/f8/7fQcz/TDi/XOTTk88/A0rcD//6ONDHSMDHWMjGIB) or [verify all test cases](https://tio.run/##Fcw9SgNhEIDhq4SU8iL7zd9@W@UM1ssWEaJYCQrCFrbWEoIg2KVKk0NkSyGH8CLrTjHDwMM7z6/b@6fd/DZu1qu/j/1qvRkvp/nh92d8nI6318PlPH2@TN/T183d/M7c9zbQxzKVjtIsR5FcRnFKQqnLkgYpSJIY4kggLZKmWamgihrqaGZa0Q5Ls8zMMMeSrGId3uAFT3PDHQ@8xfNlZBZCKGGEE9lFJTraZhj@AQ). Could output all results for the same byte-count by replacing `.Δ` with `Ùʒ`, but it's much slower and times out for the larger test cases: [try it online](https://tio.run/##ASUA2v9vc2FiaWX//2bLnElnw6PDmcqSw5nDlipR//9bMjAsMjEsMjJd) or [~~don't~~ verify all test cases](https://tio.run/##Fcw/SgNREIDxq4SU8hX75t@@rXIG62ULBROsBAVhC1trSSEE7KxsPERep7fIRTY7xQwDP755erm7f3xYXufddnN5P262u/n8s@z/v@ZD@26nv@P5t308t1P7vLld3ljG0SbGWKcyULr1KJLLKE5JKHVd0iEFSRJDHAmkR9I0KxVUUUMdzUwrOmBplpkZ5liSVWzAO7zgaW6444H3eL6MzEIIJYxwIruoxEDfTdMV). A port of *@ovs*' [Husk](https://codegolf.stackexchange.com/a/239833/52210) and [Brachylog](https://codegolf.stackexchange.com/a/239846/52210) answers, as well as *@emanresuA*'s [Vyxal](https://codegolf.stackexchange.com/a/239834/52210) and [Jelly](https://codegolf.stackexchange.com/a/239836/52210) answers, would be **13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** in 05AB1E... :/ Looks like 05AB1E draws the short straw (or I should say longest..) by far with this approach, primarily because there isn't a clean way to reduce-by-cartesian-product (which is `¯¸š.»â€˜`, 8 out of 13 bytes). ``` f¯¸š.»â€˜ʒDÙQ ``` Outputs all possible outputs. [Try it online](https://tio.run/##ASsA1P9vc2FiaWX//2bCr8K4xaEuwrvDouKCrMucypJEw5lR//9bMjAsMjEsMjJd) or [verify all test cases](https://tio.run/##Fcw9SgNhEIDhq4TUL7Lf/O23VRovkHrZwoCClYUQSJHGwgOkE2xMHUgr2G1Io7fIRdadYoaBh3deXh82z4/TdrdaLm7vh8VytZuexvP4ff26G38ux9vb6e/z93B/@VhPe6a@t4E@5ql0lGY@iuQyilMSSp2XNEhBksQQRwJpkTTNSgVV1FBHM9OKdliaZWaGOZZkFevwBi94mhvueOAtni8jsxBCCSOcyC4q0dE2w/AP). **Explanation:** ``` f # Map each integer in the (implicit) input-list to an inner list of # its unique prime factors ˜ # Flatten this list of lists Ig # Push the input-length ã # Take the cartesian product .Δ # Find the first result which is truthy for: Ù # Uniquify the list Ö # Check for each prime if it evenly divides the (implicit) inputs # at the same positions (1 if truthy; 0 if falsey) * # Multiply each by the (implicit) inputs at the same positions Q # And check if it's equal to the (implicit) input-list # (after which the found list is output implicitly) ``` If the inner list we're filtering on becomes smaller in length than the input-list after the `Ù`, it'll stay that same smaller size at the `Ö` and `*`. At the `Q` after that however, this smaller list can never be equal to the input-list. ``` f # Map each integer in the (implicit) input-list to an inner list of # its unique prime factors ¯¸š # Prepend [[]] at the front of this list .» # Left-reduce it by: â # Cartesian product of two lists €˜ # After the reduce, flatten each inner list ʒ # Filter it by: D # Duplicate the list Ù # Uniquify this copy Q # And check if the lists are still the same # (after which the list of lists is output implicitly) ``` [Answer] # [Factor](https://factorcode.org/) + `math.primes.factors`, 51 bytes ``` [ [ factors ] map [ members ] product-map longest ] ``` [Try it online!](https://tio.run/##TZDNTsNADITveYp5AaKs13YSeADEpRfEqeqhhC1UIj9NtgdU9dnDpioxPs3sfh5Lc9g3sR/nt9eXzfMj2n38yofx2IYpP9x@JkzhdA5dExYV/9nE9R/nJmIYQ4w/aauLeMqyS4Y0FzCud6WrqlDDFat1ZJLhBM5QV62SCpADGUwMEpCCSpBx3pI9wXt4hhd4C/UVfA02ji2UGSxgg7kC15AC4iDGCUMEopASYsfVQpWgHspQgVqeVtAa5cJds3mLLf4q3qXih@Tb0L6Hm793@7C8f/fdZ5gidvPi8vkX "Factor – Try It Online") ## Explanation * `[ factors ] map` Get the prime factors of each number in the input list. * `[ members ] product-map` Get every combination of picking one thing from each list. But remove duplicates. * `longest` Get the longest one. ``` ! { 14 15 16 } [ factors ] map ! { { 2 7 } { 3 5 } { 2 2 2 2 } } [ members ] product-map ! { { 2 3 } { 7 3 2 } { 2 5 } { 7 5 2 } { 2 3 } { 7 3 2 } { 2 5 } { 7 5 2 } { 2 3 } { 7 3 2 } { 2 5 } { 7 5 2 } { 2 3 } { 7 3 2 } { 2 5 } { 7 5 2 } } longest ! { 7 3 2 } ``` ]
[Question] [ Your task is to write a program which implements a bijection \$\mathbb{N}^n\to\mathbb{N}\$ for \$n \ge 1\$. Your program should take \$n\$ natural numbers as input, in any [acceptable method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) (including taking them as a single, \$n\$ element list/array) and output a unique natural number for all possible inputs. In layman's terms, a **bijection** \$\mathbb{N}^n\to\mathbb{N}\$ means: * Take \$n\$ natural numbers as input * Map these \$n\$ natural numbers to a single natural number output * For every possible input, the output is provably unique * For every possible output, there exists an input which will give that output For example, the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) \$\pi : \mathbb{N}^2\to\mathbb{N}\$ is a bijection that takes two natural numbers and maps each pair to a unique natural number. You may implement whatever bijective function you wish, so long as it is proven to be bijective for all possible inputs. Please include this proof (either directly or through a link) in your answer. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code, in bytes, wins. You may decide whether you'd like to use \$\mathbb{N} = \{1, 2, 3, \dots\}\$ or \$\mathbb{N} = \{0, 1, 2, \dots\}\$, so long as this is consistent for all \$n\$. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~13~~ 10 [bytes](https://github.com/abrudz/SBCS) ``` (⊢+1⊥∘⍳+)/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR1yJtw0ddSx91zHjUu1lbU/9/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/pykYGigYGnEBaUMorWCkYKxgAgA "APL (Dyalog Unicode) – Try It Online") Similar to other answers, since the Cantor pairing is bijective, compositing \$n-1\$ Cantor pairings is bijective as well. ``` ( )/ ⍝ reduce the input with following function + ⍝ left argument + right argument ⍳ ⍝ the first left+right positive integers 1⊥ ⍝ convert those from base 1 (sum) ⊢+ ⍝ + right argument ``` [Answer] # [J](http://jsoftware.com/), 8 bytes ``` ,@|:&.#: ``` [Try it online!](https://tio.run/##TYxBCsJAEATveUWzAXcXxnHG44RAQPDkyS@IS5JLPiB@fY0KyRwauqim5xo4FvSGCILA1hwZl/vtWml42YFbq7l5PsYFKZbYTaySyRLxr3UlKBIFOb0zJoZK8x@X9UigOyjEw2b0O/TgjHqj/k1wrh8 "J – Try It Online") (outputs the 10x10 matrix for f(A,B) and some consecutive numbers for n=3.) Basically uses Neil's initial idea, interweaving the bits by evenly distributing them (so for n=3, the bit mask for the output is `… 1 2 3 1 2 3 1 2 3`.). But instead of shifting the bits, we make use of shapes: Convert each number into base 2 and pad lists with zeros, f.e. `#: 2 3 8` is ``` 0 0 1 0 0 0 1 1 1 0 0 0 ``` Transpose the matrix with `|:`: ``` 0 0 1 0 0 0 1 1 0 0 1 0 ``` And 'deshape' with `,`, i.e. join the rows into a list: `0 0 1 0 0 0 1 1 0 0 1 0` and convert it back from base 2 `&.#:` into a number: 562. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page) Probably caird's 6 byter... ``` +RS+ʋ/ ``` **[Try it online!](https://tio.run/##y0rNyan8/187KFj7VLf@////ow11DHSMYgE "Jelly – Try It Online")** How? Implements a repeated application of the Cantor pairing function. A single application is \$f(a,b)=\frac{1}{2}(a+b)(a+b+1)+b\$ But note that \$\frac{1}{2}(a+b)(a+b+1)=\sum\_{i=1}^{a+b}i\$ So \$f(a,b)=b+\sum\_{i=1}^{a+b}i\$ ``` +RS+ʋ/ - Link: list of non-negative integers / - reduce by: ʋ - last four links as a dyad - f(a,b) + - add -> a+b R - range -> [1,2,3,...,a+b] S - sum -> (a+b)(a+b+1)/2 + - add (b) -> b+(a+b)(a+b+1)/2 ``` [Answer] # [Python 2](https://docs.python.org/2/), 38 bytes ``` f=lambda a,*l:l and(a-~a<<f(*l))-1or a ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVFHK8cqRyExL0UjUbcu0cYmTUMrR1NT1zC/SCHxf0FRZl6JAlAo2ljHSMcwVvM/AA "Python 2 – Try It Online") Takes input splatted like `f(1,2,3)`. Uses the pairing function \$p(a,b)=(2a+1)2^b\$. We use bit-shift `<<b` to shorten `*2**b`, and write `a-~a` to save a byte off of `2*a+1`. **41 bytes** ``` lambda l:reduce(lambda a,b:(a-~a<<b)-1,l) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHqig1pTQ5VQPKT9RJstJI1K1LtLFJ0tQ11MnR/F9QlJlXopCmEW2oY6RjHKv5HwA "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~21~~ 18 bytes ``` W⊖Lθ⊞θ⊖×⊕⊗⊟θX²⊟θIθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDJTW5KDU3Na8kNUXDJzUvvSRDo1BTU1MhoLQYyNJRQJYPycxNLdbwzEOIuOSXJuUA6YD8ArA2HYWA/PLUIg0jEAMipKlpzRVQlJlXouGcWFwCErL@/z862lRHwURHwVhHAajUMDb2v25ZDgA "Charcoal – Try It Online") Now uses @xnor's pairing function. Previous 21-byte answer: ``` W⊖Lθ⊞θΣE²×⊕κ↨↨⊟貦⁴Iθ ``` [Try it online!](https://tio.run/##RUw9C8IwFNz9FW98gedg1ambuhQUArqVDiE@TDBJa5Lqz4@piwd3HNyHNirqUblSPsY6Bjyxjuw5ZL7jmcMjG3wJIUDOqTqC6@zxoiZsCG7Wc8Iu/AdPQXBQifEncpzqlqCp3IkF7UpGGzIeVcrLbVtK3@9rSrCtPYLNMJT1230B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W⊖Lθ ``` Repeat until there is only one element left (i.e. reduce right)... ``` ⊞θΣE²×⊕κ↨↨⊟貦⁴ ``` Convert the last two elements to base 2 and then back from base 4, double one of them and take the sum, pushing the result back to the list. This is equivalent to interleaving their bits. I use this bijection rather than the Cantor pairing function as it only requires reading each value once, thus making it golfier in Charcoal. ``` Iθ ``` Output the final result. [Answer] # [Haskell](https://www.haskell.org/), 27 bytes ``` foldr1(\a b->2^a*(2*b+1)-1) ``` [Try it online!](https://tio.run/##BcHBEkAgEADQX9mDQ0WHcs6PiJktopE05fut905s154SBWMpPGmrilkEJye9omBauF5xqTjdGDMYKDXmFzoIMKtBD@NCnw8Jj0bSl/ID "Haskell – Try It Online") Uses a different bijection from the Cantor pairing function. Every positive integer can be uniquely split into a power of 2 times an odd number, that is \$2^a(2b+1)\$ for non-negative integers \$a,b\$. Subtracting 1 then means we get all non-negative integers including 0. Here's a table for the bijection, for \$a,b\$ from 0 to 6: ``` 0 2 4 6 8 10 12 ... 1 5 9 13 17 21 25 3 11 19 27 35 43 51 7 23 39 55 71 87 103 15 47 79 111 143 175 207 31 95 159 223 287 351 415 63 191 319 447 575 703 831 ... ... ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` +‘c2+µ/ ``` [Try it online!](https://tio.run/##y0rNyan8/1/7UcOMZCPtQ1v1////H22go2Coo2AUCwA "Jelly – Try It Online") 0 is a natural number. Implements Cantor Pairing, and reduces the list over that. (There's a 6 byte solution apparently so I'm sad) Cantor Pairing is bijective (I'm not sure of the proof but this is well known I think), so since compositions of bijections are bijective, this is bijective. In the edge case that n = 1, this is identity, so it's still bijective. At least, that's how I think that works. Please let me know if you find an unmapped value or a collision. [Answer] # JavaScript (ES6), 33 bytes Cantor pairing on the input array `a[]`. ``` a=>a.reduce((x,y)=>y-(x+=y)*~x/2) ``` [Try it online!](https://tio.run/##XYzJCsIwGAbvPsV3/NMltvVYU/ABfAIR@eniQpuUtEqDy6vHnDx4GhiGufGDp9pexznVpml9pzyriqVtm3vdEi2JE6pyKS2xciL6LOtC@M5Y0lDIS2hsUWSBcSzwXAEc/EFKubOWHe15vkjLujEDCUTYIEaOFzJxlAOPdIKq8B/l2a8qw7E2ejJ9K3tzJk7QEYvg3/4L "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Å«+LOy+}н ``` [Try it online](https://tio.run/##yy9OTMpM/f//cOuh1do@/pXatRf2/v8fbahjpGOsYxILAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/s5ulir6TwqG2SgpL9/8Oth1Zr@/hXatde2Ptf53@0oYGOoVEsV7ShIZTWMdIx1jGJBQA). Port of [*@ovs*' APL answer](https://codegolf.stackexchange.com/a/214140/52210), so make sure to upvote him! -1 byte thanks to *@ovs*. **9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative:** ``` ćsvy+LOy+ ``` [Try it online](https://tio.run/##yy9OTMpM/f//SHtxWaW2j3@l9v//0SbmOgrGRrEA) or [verify some more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/I@3FZZXaPv6V2v9rdf5HRxsa6BgaxepEGxpCaR0jHWMdk9hYAA). **Explanation:** ``` Å« # Cumulative right-reduce by (unfortunately keeping all intermediate steps): + # Add them together: a+b L # Pop and push a list in the range [a+b] O # Sum this list y+ # Add a to it }н # After the reduce-by, pop the list and leave just the first item # (after which it is output implicitly as result) ć # Extract head of the (implicit) input-list; pushing the remainder-list # and first item separated to the stack s # Swap so the remainder-list is at the top v # Loop over each integer `y` in this list: y+ # Add the current integer `y` to the top value L # Pop and push a list in the range [1,n] O # Sum this list y+ # And add `y` to it # (after the loop, the integer is output implicitly as result) ``` [Answer] # Haskell, 31 bytes ``` foldl1(\x y->(x+y)*(x+y+1)/2+y) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802LT8nJcdQI6ZCoVLXTqNCu1JTC0RqG2rqGwE5/3MTM/NsC4oy80pU0hSijXQMY/8DAA "Haskell – Try It Online") [Answer] # Scala, 34 bytes ``` _.reduce((x,y)=>(x+y)*(x+y+1)/2+y) ``` [Try it online](https://scastie.scala-lang.org/twOlbXP7TaW4thzMDTG8hg) An anonymous function of type `Seq[Int] => Int`. Applies the cantor pairing to two elements until the result is an a single integer. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~62~~ \$\cdots\$ ~~56~~ 55 bytes Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` f(a,l)int*a;{l=l?*++a=*a-(*a+=a[1])*~*a/2,f(a,l-1):*a;} ``` [Try it online!](https://tio.run/##dVXbrtowEHznKyykIyXB6GTjXEvTPlT9Cg6qoiS0SOEikgdaRH@dru1NyFoq4pLZGduzExbq9c@6fj73XiU7/3Aagmpz78rua7BaVWVQrb2gWpXVFnZ@8Deo3iNplGvwP6Hy8cQV4lgdTp6/uC8EPnRhaPsBtrvyXkiRP6SGkYYQSpFYrDSO7HWsr5NJmozSXAqwpZQUalqfmfVSZFKktpLrCkLatNAQd0infSHUpZiA8QeGz6hkPKoXViSJJh8Qz2yDMaoIpKMhwtlcabyNNowzPNZ0vBlDCzTXa8qIbGg2KhuSzcbGYSOwbdtuqUPqjfqhNsg6mSa75JL8kbOXHXMPf3TaT3/40573nlH474QCC@WMjDgZMVJxUjEy5mTMyISTCSNTTqaMzDiZMTLnZM7IgpMFIyF0Ugg57YbEUwInJuA5gRMU8KTAiQp4VuCEBTwtcOICnhc4gQFPDJzIgGcGTmiIZ1@n9nZp66FtzEileqJUaCarwEmANFcxfkCkiTjDsU30KMUFVvGZFjgrCVZjZdbge5yZK6wpBREdVP@qroG4bneiFPflx@179HErvuErWUoxx2pJK/bnq/C0v8OpaW@4LNzQ5WdBzYzOX91NlY1YrYzaF/bHb5pl3MnOs6F3mzkrOmJxvFz65acZ3TTaS2eOathB@nG5onjvLd8agS0OW5Ts/Nd2D@bqUh6rrjvXXhdQK1j1Z/Jje6wvv72LHOT/JNpbj872qBL6b4BTLVLTrXabG82K9ReBht/6j9NS9vK67cuyHW0/Fo/nPw "C (gcc) – Try It Online") Inputs an array of natural numbers and its length minus \$1\$ and returns a unique natural number using [Cantor pairing](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function). [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` FS+ȯΣḣ+ ``` [Try it online!](https://tio.run/##yygtzv7/3y1Y@8T6c4sf7lis/f///2hjHRMd01gA "Husk – Try It Online") Recursive Cantor pairing (same approach as [HyperNeutrino's answer](https://codegolf.stackexchange.com/a/214134/95126)). ``` FS+ȯΣḣ+ F # Fold over list (=recursively apply to pairs): S+ȯΣḣ+ # Cantor-pairing bijection: S # Hook: combine 2 functions using same (first) argument + # add first argument to ȯ # combination of 2 3 functions: Σ # sum of ḣ # series from 1 up to + # sum of first & second arguments ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 59 bytes ``` .+ * +`(_+)\1 $1@ @_ _ ^'@P`.+ N$`. $.%` ¶ _ @_ +`_@ @__ _ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4tLO0EjXlszxpBLxdCByyGeK54rTt0hIAEo56eSoMeloqeawHVoGxdQHCipnRAPUgRU9f@/IZcRlzGXCZcpAA "Retina – Try It Online") Explanation: ``` .+ * +`(_+)\1 $1@ @_ _ ``` Convert the input to binary, using `@` for `0` and `_` for `1`. ``` ^'@P`.+ ``` Left-pad all lines with `@` to the same length. ``` N$`. $.%` ¶ ``` Transpose and join the lines. ``` _ @_ +`_@ @__ _ ``` Convert from binary to decimal. ]
[Question] [ This function should take four integer inputs (`a`,`b`,`c`,`d`) and return a binary word based on which values equal the maximum of the four. The return value will be between `1` and `0xF`. For example: `a = 6, b = 77, c = 1, d = 4` returns `2` (binary `0010`; only 2nd-least significant bit is set corresponding to `b` being sole max value) `a = 4, b = 5, c = 10, d = 10` returns `0xC` (binary `1100`; 3rd- and 4th-least significant bits set corresponding to `c` and `d` equaling max value) `a = 1, b = 1, c = 1, d = 1` returns `0xF` (binary `1111`; all four bits set because all values equal the max) Here is a simple implementation: ``` int getWord(int a, int b, int c, int d) { int max = a; int word = 1; if (b > max) { max = b; word = 2; } else if (b == max) { word |= 2; } if (c > max) { max = c; word = 4; } else if (c == max) { word |= 4; } if (d > max) { word = 8; } else if (d == max) { word |= 8; } return word; } ``` return value can be string of 0's and 1's, bool / bit vector, or integer [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes Takes input as `[d,c,b,a]`. Returns a list of Booleans. ``` Ṁ= ``` [Try it online!](https://tio.run/##y0rNyan8///hzgbb////R5voGOqYm@uYxQIA "Jelly – Try It Online") `Ṁ` **M**aximum `=` equal to (implies the other argument is the original argument; vectorises) [Answer] # [R](https://www.r-project.org/), 17 bytes ``` max(a<-scan())==a ``` [Try it online!](https://tio.run/##K/r/PzexQiPRRrc4OTFPQ1PT1jbxv5mCubmCoYLJfwA "R – Try It Online") Returns a vector of booleans. Since this output has been confirmed, this is preferable over numerical output, as that one is almost twice longer: ### [R](https://www.r-project.org/), 33 bytes ``` sum(2^which(max(a<-scan())==a)/2) ``` [Try it online!](https://tio.run/##K/r/v7g0V8MorjwjMzlDIzexQiPRRrc4OTFPQ1PT1jZRU99I87@Zgrm5gqGCyX8A "R – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 [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. Takes `[a,b,c,d]` as argument. Returns a bit-Boolean array.\* ``` ⌈/=⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FPh77to569/9MetU141Nv3qG@qp/@jruZD640ftU0E8oKDnIFkiIdn8P80BTMFc3MFQwUTrjQFEwVTBUMDIAKyDSEQAA "APL (Dyalog Unicode) – Try It Online") `⌈/` Does the maximum of the argument `=` equal (vectorises) `⌽` the reverse of the argument? \* Note that APL stores arrays of Booleans using one bit per value, so this does indeed return a 4-bit word, despite the display form being `0 0 1 0`. [Answer] # [Haskell](https://www.haskell.org/), ~~20~~ 18 bytes *2 bytes saved thanks to [proud haskeller](https://codegolf.stackexchange.com/users/20370/proud-haskeller)* ``` map=<<(==).maximum ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802N7HA1sZGw9ZWUy83sSIztzT3f25iZp5tQVFmXolKWrSRjqEOEMf@BwA "Haskell – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 12 bytes ``` {$_ X==.max} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXiHC1lYvN7Gi9n9xYqVCmkK0iY6hjrm5jlmsNRdUxNBAB4hMdEyRhHTAMNb6PwA "Perl 6 – Try It Online") Anonymous code block that takes a list of integers and returns a list of booleans. If we need to return as a number, it's +4 bytes to wrap the inside of the code block with `2:[...]`. ### Explanation: ``` { } # Anonymous code block $_ # With the input X== # Which values are equal .max # To the maximum element ``` [Answer] # Japt, 5 ``` m¶Urw ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=bbZVcnc=&input=W1s0LDEsNzcsNl0sClsxMCwxMCw1LDRdLApbMSwxLDEsMV1dCi1tUg==) -4 bytes thanks to @Oliver! -2 bytes thanks to @Shaggy! Input is a 4-element array in the following format: ``` [d, c, b, a] ``` Output is an array of bits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~3~~ 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ZQ ``` Input as a list of `[d,c,b,a]`, output as a list of boolean. [Try it online](https://tio.run/##yy9OTMpM/f8/KvD//2gTHUMdc3Mds1gA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/qMD/Ov@jo010DHXMzXXMYnWiDQ10gMhUxwTE1gHD2FgA). **Explanation:** ``` Z # Take the maximum of the implicit input-list Q # Check for each in the (implicit) input-list if it equals this value # (and output implicitly as result) ``` [Answer] # x86 machine code (MMX/SSE1), 26 bytes (4x int16\_t) # x86 machine code (SSE4.1), 28 bytes (4x int32\_t or uint32\_t) # x86 machine code (SSE2), 24 bytes (4x float32) or 27B to cvt int32 (The last version that converts int32 to float isn't perfectly accurate for large integers that round to the same float. With float input, rounding is the caller's problem and this function works correctly if there are no NaNs, identifying floats that compare == to the max. The integer versions work for all inputs, treating them as signed 2's complement.) All of these work in 16/32/64-bit mode with the same machine code. A stack-args calling convention would make it possible to loop over the args twice (finding max and then comparing), possibly giving us a smaller implementation, but I haven't tried that approach. x86 SIMD has vector->integer bitmap as a single instruction ([`pmovmskb`](https://www.felixcloutier.com/x86/pmovmskb) or [`movmskps`](https://www.felixcloutier.com/x86/movmskps) or pd), so it was natural for this even though MMX/SSE instructions are at least 3 bytes long. SSSE3 and later instructions are longer than SSE2, and MMX/SSE1 instructions are the shortest. Different versions of `pmax*` (packed-integer vertical max) were introduced at different times, with SSE1 (for mmx regs) and SSE2 (for xmm regs) only having signed word (16-bit) and unsigned byte. (`pshufw` and `pmaxsw` on MMX registers are new with Katmai Pentium III, so really they require SSE1, not just the MMX CPU feature bit.) This is callable from C as `unsigned max4_mmx(__m64)` with the i386 System V ABI, which passes an `__m64` arg in `mm0`. (Not x86-64 System V, which passes `__m64` in `xmm0`!) ``` line code bytes num addr 1 global max4_mmx 2 ;; Input 4x int16_t in mm0 3 ;; output: bitmap in EAX 4 ;; clobbers: mm1, mm2 5 max4_mmx: 6 00000000 0F70C8B1 pshufw mm1, mm0, 0b10110001 ; swap adjacent pairs 7 00000004 0FEEC8 pmaxsw mm1, mm0 8 9 00000007 0F70D14E pshufw mm2, mm1, 0b01001110 ; swap high/low halves 10 0000000B 0FEECA pmaxsw mm1, mm2 11 12 0000000E 0F75C8 pcmpeqw mm1, mm0 ; 0 / -1 13 00000011 0F63C9 packsswb mm1, mm1 ; squish word elements to bytes, preserving sign bit 14 15 00000014 0FD7C1 pmovmskb eax, mm1 ; extract the high bit of each byte 16 00000017 240F and al, 0x0F ; zero out the 2nd copy of the bitmap in the high nibble 17 00000019 C3 ret size = 0x1A = 26 bytes ``` If there was a `pmovmskw`, what would have saved the `packsswb` and the `and` (3+2 bytes). We don't need `and eax, 0x0f` because `pmovmskb` on an MMX register already zeros the upper bytes. MMX registers are only 8 bytes wide, so 8-bit AL covers all the possible non-zero bits. **If we knew our inputs were non-negative, we could `packsswb mm1, mm0`** to produce non-negative signed bytes in the upper 4 bytes of `mm1`, avoiding the need for `and` after `pmovmskb`. **Thus 24 bytes.** x86 pack with signed saturation treats the input and output as signed, so it always preserves the sign bit. (<https://www.felixcloutier.com/x86/packsswb:packssdw>). Fun fact: x86 pack with unsigned saturation still treats the *input* as signed. This might be why `PACKUSDW` wasn't introduced until SSE4.1, while the other 3 combinations of size and signedness existed since MMX/SSE2. --- Or with 32-bit integers in an XMM register (and `pshufd` instead of `pshufw`), every instruction would need one more prefix byte, except for `movmskps` replacing the pack/and. But `pmaxsd` / `pmaxud` need an extra extra byte... **callable from C as `unsigned max4_sse4(__m128i);`** with x86-64 System V, or MSVC vectorcall (`-Gv`), both of which pass `__m128i`/`__m128d`/`__m128` args in XMM regs starting with `xmm0`. ``` 20 global max4_sse4 21 ;; Input 4x int32_t in xmm0 22 ;; output: bitmap in EAX 23 ;; clobbers: xmm1, xmm2 24 max4_sse4: 25 00000020 660F70C8B1 pshufd xmm1, xmm0, 0b10110001 ; swap adjacent pairs 26 00000025 660F383DC8 pmaxsd xmm1, xmm0 27 28 0000002A 660F70D14E pshufd xmm2, xmm1, 0b01001110 ; swap high/low halves 29 0000002F 660F383DCA pmaxsd xmm1, xmm2 30 31 00000034 660F76C8 pcmpeqd xmm1, xmm0 ; 0 / -1 32 33 00000038 0F50C1 movmskps eax, xmm1 ; extract the high bit of each dword 34 0000003B C3 ret size = 0x3C - 0x20 = 28 bytes ``` Or if we accept input as `float`, we can use SSE1 instructions. The `float` format can represent a wide range of integer values... Or if you think that's bending the rules too far, start with a 3-byte `0F 5B C0 cvtdq2ps xmm0, xmm0` to convert, making a 27-byte function that works for all integers that are exactly representable as IEEE binary32 `float`, and many combinations of inputs where some of the inputs get rounded to a multiple of 2, 4, 8, or whatever during conversion. (So it's 1 byte smaller than the SSE4.1 version, and works on any x86-64 with just SSE2.) If any of the float inputs are NaN, note that `maxps a,b` exactly implements `(a<b) ? a : b`, [keeping the element from the 2nd operand on unordered](https://stackoverflow.com/questions/40196817/what-is-the-instruction-that-gives-branchless-fp-min-and-max-on-x86). So it might be possible for this to return with a non-zero bitmap even if the input contains some NaN, depending on where they are. **`unsigned max4_sse2(__m128);`** ``` 37 global max4_sse2 38 ;; Input 4x float32 in xmm0 39 ;; output: bitmap in EAX 40 ;; clobbers: xmm1, xmm2 41 max4_sse2: 42 ; cvtdq2ps xmm0, xmm0 43 00000040 660F70C8B1 pshufd xmm1, xmm0, 0b10110001 ; swap adjacent pairs 44 00000045 0F5FC8 maxps xmm1, xmm0 45 46 00000048 660F70D14E pshufd xmm2, xmm1, 0b01001110 ; swap high/low halves 47 0000004D 0F5FCA maxps xmm1, xmm2 48 49 00000050 0FC2C800 cmpeqps xmm1, xmm0 ; 0 / -1 50 51 00000054 0F50C1 movmskps eax, xmm1 ; extract the high bit of each dword 52 00000057 C3 ret size = 0x58 - 0x40 = 24 bytes ``` copy-and-shuffle with `pshufd` is still our best bet: `shufps dst,src,imm8` reads the input for the low half of `dst` *from* `dst`. And we need a non-destructive copy-and-shuffle both times, so 3-byte `movhlps` and `unpckhps`/pd are both out. If we were narrowing to a scalar max, we could use those, but it costs another instruction to broadcast before compare if we don't have the max in all elements already. --- Related: SSE4.1 `phminposuw` can find the position and value of the minimum `uint16_t` in an XMM register. I don't think it's a win to subtract from 65535 to use it for max, but see [an SO answer about using it](https://stackoverflow.com/questions/22256525/horizontal-minimum-and-maximum-using-sse/22268350#22268350) for max of bytes or signed integers. [Answer] Here's a JS version that outputs as binary update: Shorter with join, and without the lookup: # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` a=>a.map(x=>+(x==Math.max(...a))).join('') ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKPC1k4bSNj6JpZkAAUqNPT09BI1NTX1svIz8zTU1TX/J@fnFefnpOrl5KdrpGlEK5joKBjqmJvrKJjFamoq6OsrGFQYcaEpMjTQASIFUx0FE7giZ3RFQGNgCK7I7T8A "JavaScript (Node.js) – Try It Online") Previous, with lookup, 49 bytes ``` a=>a.map(x=>[0,1][+(x==Math.max(...a))]).join('') ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKPC1i7aQMcwNlobyLT1TSzJAApXaOjp6SVqasZq6mXlZ@ZpqKtr/k/OzyvOz0nVy8lP10jTiFYw0VEw1DE311Ewi9XUVNDXVzCoMOJCU2QINNlAR8FUR8EErsgZXRHQGBiCK3L7DwA "JavaScript (Node.js) – Try It Online") Previous, with reduce, 52 bytes: ``` a=>a.reduce((y,x)=>y+[0,1][+(x==Math.max(...a))],'') ``` [Try it online!](https://tio.run/##Xcy9DoIwFEDh3ae4G224ltagTGUxcfMJmg43pfgTpAbQlKevLDKQnPHLedKXRjc83tO@D41PrU6kaxKDbz7OMzZj5LqecyNRWZOzqPWVprt4UWRCCOLcYpbx5EI/hs6LLtxYywyUCAqrCuFkOYeiABkPuw1Sy1MiHBHKFZ23aNn8W9El/QA "JavaScript (Node.js) – Try It Online") ``` fa=>a.map(x=>+(x==Math.max(...a))).join('') console.log(f([ 4, 1,77, 6])) // 0010 console.log(f([10,10, 5, 4])) // 1100 console.log(f([ 1, 1, 1, 1])) // 1111 ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 67 bytes Lambda function that takes in 4 integers, bit shifts the boolean result of their comparison to the maximum value with some help from Python 3.8's new [assignment operator](https://www.python.org/dev/peps/pep-0572/), and returns the bitwise OR of the results ``` lambda a,b,c,d:((m:=max(a,b,c,d))==d)<<3|(m==c)<<2|(m==b)<<2|(a==m) ``` [Try it online!](https://tio.run/##LcgxCoAwDADArzgmkEHtIsX8xCW1g4LRIoUq@Pco6nZcOvO0ra5LuxUebBENUSqhQCNFD6CeVQ74A5E5Yt@7C5R5fNS@Cp@EWdHSPq8ZCtTkqKUG0W4 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 78 bytes ``` a->{int m=a[0],w=1,p=1;for(int t:a){w=t<m?w:p|(t>m?(m=t)^m:w);p*=2;}return w;} ``` [Try it online!](https://tio.run/##ZVDLasMwELznK5ZAwAqKiUvagB059FLooaf0ZlxQkziVaz2w1jHB9be7cuy@qNAidmY1M2zOz3yRH947IY0uEXLX@xWKwp9Hk39YVqk9Cq16cl9wa@GJCwXNBMBUr4XYg0WO7jlrcQDpOG@HpVCnJAVeniy5jgI860eFD6PYRihM0hgyYB1fxI1rQTKeLFNas4AaFkSZLr0expCTpma4kds6NB8exnLrSYbkRYY1icyc3URtecSqVFBHbRdd3a76LgEeLVpgY4b@NHBHYb2mEFBYQUt/ESsKtw5f9vWXCejX/cHbwWnMOXqFgyP5NtxdLB6lryv0jdsKZt509jZTUwqZz40pLvfW7cXrfxEyKLaTvtruEw "Java (JDK) – Try It Online") * Takes the input as an array of `[a,b,c,d]`. [Answer] # JavaScript (ES6), 30 bytes Takes input as `([d,c,b,a])`. Returns 4 Boolean values. ``` a=>a.map(x=>x==Math.max(...a)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQKPC1q7C1tY3sSQDyK3Q0NPTS9TU/J@cn1ecn5Oql5OfrpGmEa1goqNgqGNurqNgFqupV5IfXFKUmZeuYWimqamgr69gUGHEhabD0EAHiBRMdRRMsOtwRtcBtACGsOtw@w8A "JavaScript (Node.js) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~34~~ 22 bytes Takes input as an array `[d, c, b, a]` and returns an array of 1s and 0s. ``` ->r{r.map{|e|e/r.max}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166oukgvN7Gguia1JlUfxKyorf1foJAWHW2io2Coo2BurqNgFhvLBRYyNACKAbGpjoIJXAysDIRiY/8DAA "Ruby – Try It Online") [Answer] ## [Python 3](https://www.python.org), ~~59 bytes~~ 66 bytes ``` def f(l): n=max(a) for i in 0,1,2,3:a[i]=a[i]==n return a[::-1] ``` [Try it online!](https://tio.run/##VYzLCoAgFET3fsVdKtwge4Lgl4gLoSQX3UIM6utNXAQxcBgOzJxP2g7q87J68NwJlYH07u5SGfgjQoBA0KLEDnvlTLC6QhODuKYrEjijVCNtPmOgxD03E85zGQxWCPbJAUeU5af9WYk1xeUX) Takes input as `[a,b,c,d]` and outputs a list of booleans. Edited to be a proper function, then saved 2 bytes by removing brackets around the conditional. [Answer] # 1. Python 3.5, 90 bytes Takes sequence of numbers as parameters. Returns "binary" string ``` import sys;v=[*map(int,sys.argv[1:])];m=max(v);s="" for e in v:s=str(int(e==m))+s print(s) ``` example: ``` $ ./script.py 6 77 1 4 77 10010 ``` ## Explanation ``` import sys # convert list of string parameters to list of integers v=[*map(int,sys.argv[1:])] # get max m=max(v) # init outstring s="" # walk through list for e in v: # prepend to outstring: int(True)=>1, int(False)=>0 s=str(int(e==m))+s # print out result print(s) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 26 bytes ``` n=>n.Select(a=>a==n.Max()) ``` [Try it online!](https://tio.run/##lc2xCsIwGATg3acInRKIwUK1Q5tsCpW66OAgDmn4K4H2rySp@Paxiou4KMeN353xc@Nt3Ixoyqq2PpQWg@LVGscenG46KJth6JRqZUSpUBygAxOolkpLiWKn75SxWMy@BAngAzh61U73nkyzpzPRTKqWalbMjs4GqC0C9cFZvIjtYJEmnCT8DVec5DknKScZE3u4gfMwff1kM06WE108@zdO@SufLj4A "C# (Visual C# Interactive Compiler) – Try It Online") Takes input in format `[d,c,b,a]`. All the others down below take input as `[a,b,c,d]` # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 35 bytes ``` n=>n.Select((a,b)=>n[3-b]==n.Max()) ``` Returns an `IEnumerable<bool>`. [Try it online!](https://tio.run/##jYuxCoMwFEV3vyJjAlEqtXWocSktCHbq0EEcniGWgL6W5An9@1SlU5eWyx3u5RztY@1tOE@oi6q2ngqLVMrqhNNoHHSDWY@yVwFVicnVDEYT5yA7Me9mG3etUphc4MWFCIfo22RkPBnHn@Bg9Gy@mpbB7PYcxCG6OUumtmi4J2fxnhwfqIH4x9pLlueSpZJlQvzGM8l2M71Z@g@fyjULGt4 "C# (Visual C# Interactive Compiler) – Try It Online") # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 39 bytes ``` n=>n.Select((a,b)=>n[3-b]==n.Max()?1:0) ``` Returns an `IEnumerable<int>`, which represent bits. [Try it online!](https://tio.run/##jYuxCoMwFEV3vyJjAlGU2grV2KG0INipQwdxiCGWgL6W5An9@1SlU5eWyx3u5RzlQuWMP0@giqo2DgsDWPLqBNOorewGvR5lLzyIEqKrHrRCSiXv2LybTdi1QkB0kS/KDsk@Zj4Pvm2C2qG29CmtHB2Zr6YlcvZ7Klke3KxBXRvQ1KE1cI@OD1AS6cfacZJlnCScpIz9xlNOtjMdL/2HT/iaBfVv "C# (Visual C# Interactive Compiler) – Try It Online") # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 49 bytes ``` n=>{for(int i=4;i-->0;Write(n[i]==n.Max()?1:0));} ``` Prints a binary string to STDOUT. [Try it online!](https://tio.run/##dYwxC8IwFIT3/oo3JpBKCtGCaSKOQp0dSocQU3hDU0mCCOJvj7EITnLc8O6@dzbWNmI@2oSL7049xtShT1pPKnuln9MSSLkBlZBY15rLS8DkiB9wVMpvzuZB6KHZc0rlK8vqvuAVkovJBXIzwcwRyvswgqFKT8RQWX3bHYO2ZdAwECVcV3v0jvwIwWBbAP7xH6Rhq6jMbw "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # PHP, 54 bytes ``` while($i<4)$argv[++$i]<max($argv)||$r+=1<<$i-1;echo$r; ``` or ``` while($i<4)$argv[++$i]<max($argv)||$r+=1<<$i;echo$r/2; ``` take input from command line arguments. Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/752f2f7747c560bce1d9acb7527cda1b2e1023f1). [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 51 bytes ``` x=>{for(int m=x.Max(),i=4;i-->0;)x[i]=x[i]==m?1:0;} ``` [Try it online!](https://tio.run/##TY7BCoMwEETvfsUeE1hLBFuhaSz9gELv4kGC0j0YwYQ2IPn2NFUsZZdl5h1mR9tcW4o37WgyFzKuaetBRa/qZZhmlgCMyh/unWccSZWS8rwWkvuGWrUeNV6Ls5AhyuzVzeB66ywoMP27aWHJYFNLiQVWFZ4C/lAhMO0Ry3@G6yQSZJYa9J1@AtuDgcz2gK/JA/saLpN8zKnqbkP8AA "C# (Visual C# Interactive Compiler) – Try It Online") Above is an anonymous function that [outputs by modifying an argument](https://codegolf.meta.stackexchange.com/a/4942/8340). Output is an array of 1's and 0's. Below is a recursive function that outputs an integer. # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 60 bytes ``` int f(int[]x,int i=3)=>i<0?0:2*f(x,i-1)|(x[i]==x.Max()?1:0); ``` [Try it online!](https://tio.run/##Tc29CoMwEAfw3acITkmJkvRL0Ka@QDu10EEcRJL2lggxtAHrs6dRaSl3HHe/4X9tn7Q9eA/aIoXDrGpHpwPEhogjHFjJ8vVK4aAJJ2/sKqiFcOm5cZiUPGek8M/GICt72yOBtHxVNRoitGzDlnKaZXQ/0h9xRkPv6Pbf6FxBxiJSnZFN@0D4G4xALw/InHwzYOUJtMQKT0zSa3exBvQdxy4mpIhG/wE "C# (Visual C# Interactive Compiler) – Try It Online") Both functions take input as a 4-element array. ``` [d, c, b, a] ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda i:[int(x==max(i))for x in i] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHTKjozr0SjwtY2N7FCI1NTMy2/SKFCITNPITP2f0ERUE4hTSPaRMdQx9xcxyxWkwsuZmigA0SmOiYogjpgGKv5HwA "Python 2 – Try It Online") Takes input in the format [d,c,b,a] as with the accepted answer from [Adám](https://codegolf.stackexchange.com/a/180833/56555) so I guess it is OK. Alternative for 41 if it's not... # [Python 2](https://docs.python.org/2/), 41 bytes ``` lambda i:[int(x==max(i))for x in i][::-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHTKjozr0SjwtY2N7FCI1NTMy2/SKFCITNPITM22spK1zD2f0ERUIVCmka0mY65uY6hjkmsJhdczETHVMfQAIiQBQ11wDBW8z8A "Python 2 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 42 bytes ``` f=lambda a:list(map(lambda x:x==max(a),a)) ``` Simply returns a list of whether the element is the max for each element in the input. -2 bytes if you don't count the `f=` assignment. [Try it online!](https://tio.run/##K6gsycjPM/6vrBCSmJ1arJCZV1BaopBYrBCdopOsk6STGPs/zTYnMTcpJVEh0Sons7hEIzexQAMqUmFVYWubm1ihkaipk6ip@b@gKDOvRCNNI9pQBwRNYzU1uZDEjIBiRkCx/wA "Python 3 – Try It Online") [Answer] ## Batch, 92 bytes ``` @set m=%1 @set f=@for %%i in (%*)do @ %f%set/a"m=m+(m-=%%i)*(m>>31) %f%cmd/cset/a!(m-%%i) ``` Takes arguments as command-line parameters in reverse order. Works by arithmetically calculating the maximum of the parameters by reducing over them and adding on only positive differences from the running maximum, then mapping over each parameter again this time comparing it to the maximum. Conveniently `cmd/cset/a` doesn't output a newline, so the results are automatically concatenated together. The `%f%` simply saves 5 bytes on what would be a repeated construct. ]
[Question] [ Related: [Interquine](/questions/129772) Program A outputs program B's code when run, and B outputs C's source, and C outputs A's source. This time you can't exchange two characters and exchange again :) ### Requirements: * Only one language across all programs * Standard loopholes restrictions apply * All programs are different. One program that outputs itself does not qualify. Two that output each other does not qualify, too. * All programs are non-empty, or at least 1 byte in length. * There's nothing to read because stdin is connected to `/dev/null` (You can abuse this rule if you *can*). Output goes to stdout. * Do not use functions that generate random results. Additional: * Give explanations if possible Score is **length of the shortest one** (can you generate a long program from a short one?). Please write the length of all programs and highlight the smallest number. Trailing newline does not count. [Lowest score wins](/questions/tagged/code-golf). [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` s='s=%r;print(s%%(s,%i*2%%7))';print(s%(s,1*2%7)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v9hWvdhWtci6oCgzr0SjWFVVo1hHNVPLSFXVXFNTHS4MFDUECgLFuP7/BwA "Python 3 – Try It Online") The last expression goes from `1*2%7` to `2*2%7` to `4*2%7` then back to `1*2%7`. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), ~~12~~ 8 bytes ``` 1 «\2*7% ``` ## Explained ``` 1 # Push the digit to the stack. «\2*7% « # Define a function from here to the matching ». As there is no matching », define it from here to the end of the program, and continue running. \ # Flip the function under the constant number. 2* # Multiply by 2. 7% # Modulo 7. ``` Due to the convenient nature of how RProgN defaultly outputs, this leaves the number, which loops between 1, 2, and 4, on the first line, and the stringified version of the function on the second. Inspired by [@LeakyNun](https://codegolf.stackexchange.com/users/48934/leaky-nun)'s [Python Answer](https://codegolf.stackexchange.com/a/130288/58375) [Try it online!](https://tio.run/##Kyooyk/P0zX6/9@E69DqGCMtc9X//wE "RProgN 2 – Try It Online") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 17 bytes ``` {sZZe\6Ye\"_~"}_~ ``` ``` {s6Ze\ZYe\"_~"}_~ ``` ``` {sZ6e\ZYe\"_~"}_~ ``` [Try it online!](https://tio.run/##S85KzP3/v7o4Kio1xiwyNUYpvk6pNr7u/38A "CJam – Try It Online") Probably not optimal, but this is a modification [of my approach to the previous challenge](https://codegolf.stackexchange.com/a/129786/8478). The basic idea is the same, but we perform two swaps, one of which is always a no-op. The affected indices are `2`, `3` and `6`: ``` 1: {sZZe\6Ye\"_~"}_~ ZZe\ does nothing {sZZe\6Ye\"_~"}_~ 6Ye\ \ / \ / X / \ / \ 2: {s6Ze\ZYe\"_~"}_~ 6Ze\ \ / \/ doesn't really do anything /\ / \ {s6Ze\ZYe\"_~"}_~ ZYe\ \/ /\ 3: {sZ6e\ZYe\"_~"}_~ Z6e\ \ / \/ /\ / \ {sZZe\6Ye\"_~"}_~ ZYe\ \/ doesn't really do anything /\ 1: {sZZe\6Ye\"_~"}_~ ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` {_]3/W="_~"}_~ ``` ``` {_]3/W="_~"}{_]3/W="_~"}_~ ``` ``` {_]3/W="_~"}{_]3/W="_~"}{_]3/W="_~"}_~ ``` [Try it online!](https://tio.run/##S85KzP3/vzo@1lg/3FYpvk6pNr7u/38A "CJam – Try It Online") The other programs are 26 and 38 bytes long, respectively. ### Explanation Yet another approach! ``` { e# Again, the usual quine framework. In this case, there might e# be one or two additional copies of the block on the stack. _ e# Duplicate the top copy of the block. ] e# Wrap all copies in an array. 3/ e# Split into chunks of 3. For the first two programs, this will e# just wrap all of them in an array. For the third program, this e# splits the fourth copy off from the first three. W= e# Select the last chunk. So `3/W=` does nothing for the first e# two programs, but discards three copies once we get to four. "_~" e# Push the remainder of the program. }_~ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` “Ḥ%7Øv;”Ṙv1 ``` This generated the same program with **1** replaced by **2**, which replaced **2** by **4**, which generates the original program. [Try it online!](https://tio.run/##AR0A4v9qZWxsef//4oCc4bikJTfDmHY74oCd4bmYdjH//w "Jelly – Try It Online") [Answer] **Python 3, 127, 127 and 127 bytes** ``` a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';print(b%(b,a,c)) ``` prints ``` b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';print(c%(c,a,b)) ``` prints ``` c='c=%r;a=%r;b=%r;print(a%%(a,b,c))';a='a=%r;b=%r;c=%r;print(b%%(b,a,c))';b='b=%r;a=%r;c=%r;print(c%%(c,a,b))';print(a%(a,b,c)) ``` This is based on my answer to the Interquine question, which is based on a normal Python quine. And I know exactly what to do when we get a quad-interquine question ;) [Answer] ## [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` 0{\)3%\"_~"}_~ ``` ``` 1{\)3%\"_~"}_~ ``` ``` 2{\)3%\"_~"}_~ ``` [Try it online!](https://tio.run/##S85KzP3/36A6RtNYNUYpvk6pNr7u/38A "CJam – Try It Online") ### Explanation ``` 0{ e# Again, the standard CJam quine framework, but this time we have a zero e# at the bottom of the stack. \ e# Bring the 0 to the top. ) e# Increment. 3% e# Mod 3 to loop from 2 back to 0. \ e# Put the result underneath the block again. "_~" e# Push the remainder of the source. }_~ ``` [Answer] # Javascript (ES6), ~~63~~ 55 bytes ``` eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=0) ``` ``` eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=1) ``` ``` eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=2) ``` ``` o1.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=0) o2.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=1) o3.innerText = eval(c="`eval(c=${JSON.stringify(c)},n=${++n%3})`",n=2) ``` ``` <pre id="o1"></pre> <pre id="o2"></pre> <pre id="o3"></pre> ``` Alternative solution using `Function.prototype.toString` (cheaty, 30 bytes) ``` (f=n=>`(f=${f})(${++n%3})`)(1) ``` [Answer] # [Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus), 38 characters, 44 bytes A simple solution based on the mother of all quines: the [y-combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus): ``` (λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx) ``` Using beta reductions we see that this indeed a tri-interquine: ``` (λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx) (λy.y)(λz.z)(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx) (λz.z)(λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx) (λx.(λy.y)(λz.z)xx)(λx.(λy.y)(λz.z)xx) etc. ``` [Answer] # Java 8, 118 bytes ``` v->{int i=0;String s="v->{int i=%d;String s=%c%s%2$c;return s.format(s,++i%%3,34,s);}";return s.format(s,++i%3,34,s);} ``` Only `int i=0;` is difference between the functions/outputs (it's either `0`, `1` or `2`). **Explanation:** [Try it online.](https://tio.run/##vZLRasMgFIbv@xSHUsHQNF10V5P0DdabwW7GLpyxw86YoCYwSp49O@3CirDBrgrnIP7@6gf/OcpBbtpOu2P9MU3KyhDgURp3WgAYF7U/SKVhf94CPEVv3Dso@tyaGoZMoDpiY2235QMuIcpoFOzBlVDBsNmd8BEw1Z2Y74ZqeVVJfZWJIoGwlRJex947CMWh9Y2MNOTrtSGE5/w@D5kYl384fgzigsNSHJbglDfH4SkOT3DYjXGwuv7NIspMNJzzbDB2@v3jy6vM5sg/Q9RN0fax6PAkWkddWSjqemuzywD87mH/8PDEMy7GafoC) ``` v->{ // Method with empty unused parameter and String return-type int i=0; // Integer, starting at 0, 1 or 2 depending on the version // (this is the only variation between the functions/outputs) String s="v->{int i=%d;String s=%c%s%2$c;return s.format(s,++i%%3,34,s);}"; // String containing the unformatted source code return s.format(s,++i%3,s);} // Quine to get the source code, which we return as result // ++i%3 is used to cycle 0→1→2→0 ``` Additional explanation: [quine](/questions/tagged/quine "show questions tagged 'quine'")-part: * `String s` contains the unformatted source code * `%s` is used to put this String into itself with `s.format(...)` * `%c`, `%2$c` and `34` are used to format the double-quotes (`"`) * `%%` is used to format the modulo-sign (`%`) * `s.format(s,...,34,s)` puts it all together Difference of the outputs/functions: Same approach as most other answers: * `int i` starts at either `0`, `1` or `2` * `++i%3` transforms this to the next (`0→1`; `1→2`; `2→0`) [Answer] # [><>](https://esolangs.org/wiki/Fish), 15 bytes ``` 1'~r2*7%nd3*>o< ``` [Try it online!](https://tio.run/##S8sszvj/31C9rshIy1w1L8VYyy7f5v9/AA "><> – Try It Online") Uses the same general form as other ><> quines, but has an extra character in front that is cycled through 1, 2 and 4. ]
[Question] [ Tired of always wondering how many more Pokémon you need to catch to get those high-tier evolutions? Wonder no more! Now you will write a complete program or function to calculate it for you! ## The Challenge: As input, your program will receive a list of the costs in candy to evolve a Pokémon to the next tier. (This list may be separated by any delimiter of your choosing, or as function arguments). Your program will then return or print the number of Pokémon that must be caught, including the one that will be evolved, to evolve through all the tiers given. How do you calculate this? Like so: 1. Add up all the candy costs: `12 + 50 = 62` 2. Subtract 3 candies from the total, this being from the one Pokémon you keep for evolving: `62 - 3 = 59` 3. Divide this number by 4 (3 for catching, 1 for giving it to the Professor), always taking the `ceil()` of the result: `ceil(59/4) = 15` 4. Finally, add 1 to this total to get the total number of Pokémon you must catch, 16! Example `Input -> Output`: ``` [4] -> 2 [50] -> 13 [12, 50] -> 16 [25, 100] -> 32 [19, 35, 5, 200] -> 65 ``` ## Winning: The app has already taken up most of the space on your phone, so your program needs to be as short as possible. The complete program or function with the smallest byte count will be accepted in two weeks! (with any ties being settled by the earliest submitted entry!) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` O4÷> ``` **Explanation** ``` O # sum 4÷ # integer division by 4 > # increment ``` [Try it online](http://05ab1e.tryitonline.net/#code=TzTDtz4&input=WzE5LCAzNSwgNSwgMjAwXQ) [Answer] # Jelly, ~~5~~ 4 bytes ``` S:4‘ ``` [Try it online!](http://jelly.tryitonline.net/#code=Uzo04oCY&input=&args=WzE5LCAzNSwgNSwgMjAwXQ) `S`um, integer divide `:` by `4` and increment `‘`. [Answer] # C# REPL, 15 bytes ``` n=>n.Sum()/4+1; ``` Casts to `Func<IEnumerable<int>, int>`. [Answer] ## Actually, 4 bytes ``` Σ¼≈u ``` [Try it online!](http://actually.tryitonline.net/#code=zqPCvOKJiHU&input=WzE5LCAzNSwgNSwgMjAwXQ) Explanation: ``` Σ¼≈u Σ sum ¼ divide by 4 ≈ floor u add 1 ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes ``` +:4/+ ``` [Try it online!](http://brachylog.tryitonline.net/#code=Kzo0Lys&input=WzE5OjM1OjU6MjAwXQ&args=Wg) ### Explanation A very original answer… ``` + Sum :4/ Integer division by 4 + Increment ``` [Answer] # BASH (sed + bc) 19 ``` sed 's~)~+4)/4~'|bc ``` Input is a `+` separate list on stdin E.g.: `echo '(19+35+5+200)'| sed 's~)~+4)/4~'|bc` [Answer] # Haskell, 17 bytes ``` (+1).(`div`4).sum ``` [Answer] ## Pyke, 4 bytes ``` seeh ``` [Try it here!](http://pyke.catbus.co.uk/?code=seeh&input=%5B19%2C+35%2C+5%2C+200%5D&warnings=0) ``` ((sum(input)/2)/2)+1 ``` [Answer] # Pyth, 5 bytes ``` h/sQ4 ``` [Try it here!](http://pyth.herokuapp.com/?code=h%2FsQ4&input=%5B19%2C35%2C5%2C200%5D&debug=0) Sum input with `sQ`, divide by 4 with `/4` and finally increment `h`. [Answer] # CJam, 7 bytes ``` {:+4/)} ``` [Try it here!](http://cjam.tryitonline.net/#code=WzE5IDM1IDUgMjAwXQp7Ois0Lyl9Cgp-cA&input=) Defines an unnamed block that expects the input on the stack and leaves the result there. `:+` sums the list, `4/` divides the result by 4 and `)` increments that. [Answer] ## [Retina](https://github.com/m-ender/retina/), ~~18~~ 17 bytes Byte count assumes ISO 8859-1 encoding. ``` $ ¶4 .+|¶ $* 1111 ``` Input is linefeed-separated. [Try it online!](http://retina.tryitonline.net/#code=JArCtjQKLit8wrYKJCoKMTExMQ&input=MTkKMzUKNQoyMDA) [Answer] # R, 22 bytes ``` floor(sum(scan())/4+1) ``` [Answer] # **JavaScript, 29 Bytes** ``` x=>x.reduce((a,b)=>a+b)/4+1|0 ``` [Answer] # S.I.L.O.S ~~100 99~~ 103 characters + 22 for sample input Code with testing harness. ``` set 512 52 set 513 10 GOSUB e GOTO f funce a = 0 i = 511 lblE i + 1 b = get i a + b if b E a / 4 a + 1 return lblf printInt a ``` input as a series of set commands to modify the spots of the heap starting at spot 512. [Try it Online!](http://silos.tryitonline.net/#code=c2V0IDUxMiA1MgpzZXQgNTEzIDEwCkdPU1VCIGUKR09UTyBmCmZ1bmNlCmEgPSAwCmkgPSA1MTEKbGJsRQppICsgMQpiID0gZ2V0IGkKYSArIGIKaWYgYiBFCmEgLyA0CmEgKyAxCnJldHVybgpsYmxmCnByaW50SW50IGE&input=) ]
[Question] [ Since jq is the [Language Of The Month for September 2021](https://codegolf.meta.stackexchange.com/questions/23836/language-of-the-month-for-september-2021-jq/23837#23837), what general tips do you have for golfing in [jq](https://stedolan.github.io/jq/)? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to jq (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] # Use try-// instead of if-then-else ~~`if A then B else C end`~~ The conditional expression is very lengthy and almost never1 worth it. Depending on your condition `A` and the values `B` and `C` there might be short alternatives based on indexing or arithmetic, but a general solution is to use `try` and `//`. `try` is part of the try-catch exception handler, and returns `empty` for faulty code if the `catch` part is omitted. `//` is the *alternative* operator which returns the left hand side if it evaluates to a truthy2 value, and the right hand side otherwise. Putting these two together we can rewrite the conditional expression as: ``` (try(A//C)*1//B) ``` The `*1` assumes `C` is a number or a string, for lists you might need `+[]` instead and if C is a stream of multiple values, this gets a bit trickier. The outer parentheses can be removed in some cases. The idea is that `A//C` returns `true` if `A` is `true`, and `true*1` throws an error, which is caught by `try`. This can be shortened further by using `EXP ?`, which should be a shorthand for `try EXP`, though it seems like it does a lot more stuff, for example causing all subsequent filters to not throw errors. In this case `(1?*(A//C)//B)` works, but you might need to do some trial and error in your specific situation. Note that `?//` is its own operator since 1.6, so you need to add a space there. --- **Practical example: Fibonacci** A recursive filter using a conditional expression comes in at [41 bytes](https://tio.run/##yyr8/z8lNU0hzSozTc/GqCQjNU9PITWnODVaT9dQR0/XqCYttiYxJUUhNS/F@n9RYl56qoahgWZN2v9/@QUlmfl5xf9184oA): ``` def f:if.<2then. else[.-1,.-2|f]|add end; ``` Applying the general approach gets this to [39 bytes](https://tio.run/##yyr8/z8lNU0hzaqkqFJDz8ZIX18jWk/XUEdP16gmLbYmMSVFU1PLUF9fz/p/UWJeeqqGoYFmTdr/f/kFJZn5ecX/dfOKAA): ``` def f:try(.<2//([.-1,.-2|f]|add))*1//.; ``` In this case `add` can be used to throw an error in the truthy case, [35 bytes](https://tio.run/##yyr8/z8lNU0hzaqkqFJDz8ZIXz9aT9dQR0/XqCYttiYxJUVTX1/P@n9RYl56qoahgWZN2v9/@QUlmfl5xf9184oA): ``` def f:try(.<2//[.-1,.-2|f]|add)//.; ``` Using `?` instead of `try` for [33 bytes](https://tio.run/##yyr8/z8lNU0hzUpDz8ZIXz9aT9dQR0/XqCYttiYxJcVeU19fz/p/UWJeeqqGoYFmTdr/f/kFJZn5ecX/dfOKAA): ``` def f:(.<2//[.-1,.-2|f]|add?)//.; ``` 1 If you have a practical example where this is not the case, I'd like to see it. 2 Falsy values are `null` and `false`; all others are truthy. `empty` represents the empty stream - the absence of a value. [Answer] # Consult Secret Reference **Spoiler: [github.com/stedolan/jq/wiki/](https://github.com/stedolan/jq/wiki/)** JQ has a tutorial & manual on the [official site](https://stedolan.github.io/jq/), both of which I highly recommend! However, on the github repo, there's an extensive wiki on the language with loads more info sure to help your golfing. It includes: * FAQ section with: + Unofficial tutorials + Editor bindings, including vim & emacs + Language bindings, including Python & Java + Interactive playgrounds for JQ * Sections for: + Processing invalid json + Modules + Cookbook + Implementation details for numbers, regex and other built-ins * Other goodies + Lazy evaluation, generators and backtracking + Implement finite state machines in JQ?! [Answer] # Avoid `split` When used on a string, the `/` operator behaves exactly like `split`, but is shorter by at least 3 bytes - and sometimes by as much as 7, such as when going from `now|todate|split(":")` to `now|todate/":"` [Answer] # Sugary JSON #### Overview Instead of `{foo:.foo, bar:.bar}`, use `{foo, bar}`. In both case, we're creating a new JSON object with the key `foo` mapping to the value of `foo` in the input. ### Example ``` CODE: {a, c} IN: {"a": 1, "b": 2, "c": 3, "d": 4} OUT: {"a": 1, "c": 3} ``` [Try it online](https://tio.run/##yyr8/786UUchuRZIKyUqWRnqKCglKVkZAalkJStjIJWiZGVSCwA) [Answer] # Pipe + Dot = Smell They're sometimes needed, but this is often a code (golf) smell. You should be wary of any pipes followed by an expression containing a dot. *Or could it be possible to rewrite every jq program with a period into one without?* ### Examples `[99|range(.)]` -> `[range(99)]` [Answer] # Avoid map()[] Ungolfed: `[1,2,3]|map(.+1)[]` Golfed: `[1,2,3][]|.+1` or even better: `1,2,3|.+1` Will add more here! [Answer] If the coding challenge calls for dealing with individual characters in the input using `explode` can be handy. It breaks a string into an array of codepoints, allowing you pipe the results to a loop to process each character. ]
[Question] [ This is a rock paper scissors competition. Algorithms will face each other in 100 rounds of rock paper scissors. Except that the algorithms will also be able to read the source code of each other! # Leaderboard ``` 1. Chaos Bot (by Aiden4) - 27 Points, 168 bytes 2. Anti-99%-of-posts (by Lyxal) - 24 Points, 489 bytes 3. Psuedo-Hash Cycle (by qwatry) - 23 Points, 143 bytes 4. Destroyer of Bots (by Baby_Boy) - 23 Points, 433 bytes 5. If-If (by PkmnQ) - 21 Points, 63 bytes 6. Biased-Cycler (by HighlyRadioactive) - 20 Points, 17 bytes 7. RadiationBot v0.1 (by HighlyRadioactive) - 18 Points, 121 bytes 8. Cycler (by petStorm) - 17 Points, 17 bytes 9. Craker (by petStorm) - 17 Points, 58 bytes 10. Lookup (by petStorm) - 17 Points, 61 bytes 11. Custom (by petStorm) - 16 Points, 56 bytes 12. Anti-Cycler (by Lyxal) - 14 Points, 17 bytes 13. Mr. Paper - 13 Points, 58 bytes 14. PseudoRandom (by HighlyRadioactive) - 13 Points, 89 bytes 15. Itna-Cycler (by petStorm) - 11 Points, 17 bytes 16. Lycler (by petStorm) - 11 Points, 24 bytes 17. Mr. Rock - 11 Points, 57 bytes 18. Mr. Scissors - 10 Points, 61 bytes ``` Submissions are graded automatically via an online judge [View Online Judge](https://react-ts-4ri9hm.stackblitz.io/#) # The Competition Your code will be a javascript anonymous function (sorry, other languages aren't supported!) that takes in two arguments: * The source code of your opponent AI (as a string) * The current round number It should then return one of "R", "P", or "S", indicating that it will throw a rock, paper, or scissors for that round. Your code must follow these rules, otherwise it will be disqualified: * **Your code may not be longer than 500 bytes** * **Your function must be pure** + That is, if your function is given the same set of arguments, your code must always return the same result + This is to ensure that the tournament results are consistent * **eval() calls are banned!** + If this were allowed, two submissions with eval() would end up calling each other in an endless loop which would never terminate. + (See the discussion in the comments for more details/reasoning) * Your code may not: + Access external resources (e.g. make web fetch/get requests) + Attempt to modify or tamper with the judge system code + Cause excessive lag or time delay + Modify any globals or object prototypes + Attempt to do an XSS attack or any other sketchy/illegal stuff ## Example submission ``` (code, round) => { if (round === 1) { // Throw rock if it's the first round return "R"; } else if (code.includes('"R"')) { // Throw paper if the opponent code includes "R" return "P"; } else { // Otherwise throw scissors return "S"; } } ``` # Tournament structure Each submission will play 100 rounds of rock paper scissors with each other submission. To get the ball rolling, the following three functions will be submitted by default: ``` (code, round) => { // Always throw rock return "R"; } ``` ``` (code, round) => { // Always throw paper return "P"; } ``` ``` (code, round) => { // Always throw scissors return "S"; } ``` # Scoring A submission gains 2 points for winning against another submission, and 1 point for tying against another submission (no points are awarded for losses). Leaderboard positions are ordered by most points first. If two submissions have the same number of points, they will be ranked in order of least bytes. If two submissions have the same number of points and bytes, the older submission will be ranked higher. # Judging & Testing Post your submissions here, I will periodically add submissions to the [online judge](https://react-ts-4ri9hm.stackblitz.io/#) which will automatically rank each algorithm. You can also test your algorithms using the [online judge](https://react-ts-4ri9hm.stackblitz.io/#) testing area. A testing area is provided at the bottom to test different algorithms against each other. [Answer] # Chaos Bot I lost track of what's going on here, but it seems to win or tie everything but the standard cycler. ``` (c,r) => {if(c.includes("else")){return "SSR"[r%3];}if(c.includes("/")){if(c.includes("P")){return "S";//17 } return "SRP"[r%3];} else{return "PPS"[(c.length + r)%3];}} ``` [Answer] # Anti-99%-of-posts ``` (code,r)=>{var S="S";var R="R";var P="P";var x=S+R+P;var y=R+P+S;var z=P+S+R if(code.includes("17")){return "P";} else if(code.includes("[r%2]")){return"RR"[r%2]} else if(code.includes("[r%3]")){ if (code.includes(x)){return (R+P+S)[r%3];} else if(code.includes(y)){return (P+S+R)[r%3];} else if(code.includes(z)){return (S+R+P)[r%3];} }else{if(code.includes("scissors")){return "R"}else if (code.includes("rock")){return "P"}else if (code.includes("paper") ){return "S"}else{return "P"}}} ``` Haha. Testing it on submissions gives either a win or a tie. [Answer] # If-If ``` (c,r)=>{if(c.includes("i")){return"RPS"[2]}else{return"P"}; 17} ``` This was built off of an algorithm that detected if "if" was in the code. [Answer] ## Cycler Picks depending on the round number. ``` (c,r)=>"RPS"[r%3] ``` [Answer] # Anti-Cycler ``` (c,r)=>"PSR"[r%3] ``` Someone had to do it. Why not me? ;P [Answer] ## Custom A bot designed to beat the default bots. I'm a horrible golfer indeed... Edit: I'm now also trying to get around RadiationBot, by changing the algorithm. ``` (c,r)=>["P","S","R"][-~[["P","S","R"].findIndex(i=>!c.indexOf(i))%3]] ``` [Answer] # RadiationBot v0.1 HighlyRadioactive's botty bot. ``` (c,r)=>{if(c.indexOf("RP")>=0){return "PSR"[r%3];}else if(c.indexOf("PS")>=0){return "SRP"[r%3];}else{return "RP"[r%2];}} ``` [Answer] ## Lycler Like Cycler, but this time with length. ``` (c,r)=>"RPS"[c.length%3] ``` [Answer] ## Lookup The lookup table here explains everything. ``` (c,r)=>({17:["R","P","S"][(r-(~-c.slice(8).indexOf(`S`)||(r-3+r%2))+3)%3],24:"S",56:"S",58:"S",63:["P","S","R"][2],69:"S",81:"P",121:"PS"[r%2],168:"SSR"[(c.length+r)%3],489:"S"})[c.length]||"R" ``` [Answer] # Destroyer of Bots ``` //"P" else (c,r) => {if(c.includes("SSR")){return "R";}else if(c.includes("PRPSRS")){return "S"}else if(c.includes("RRP")){return "F";return"S"}else if(c.includes("paper")){return"S"}else if(c.includes("rock")){return"P"}else if(c.includes(".findIndex")){return"F";return "PSR"[c.length%3]}else if(c.includes("SRP")){return "RPS"[r%3]}else if(c.includes("RPS")){return"F";return "PSR"[r%3]}else if(c.includes("RP")){return"S"}else{return "R";}} ``` This bot uses confusion tactics and targeted attacks to win or tie against all current bots. note: Wins against Chaos Bot, current #1 bot. [Answer] # PseudoRandom ``` (c,r)=>{a=0;for(i=0;i<c.length;i++){a+=c[i].charCodeAt()^r^i;}return "RPS"[a%3];} ``` Not too random I guess but I tried. [Answer] ## Craker Inspired by Custom. (Hopefully) does something different. ``` (c,r)=>"RPS"[-~[..."RPS"].findIndex(i=>c.indexOf(i)>-1)%3] ``` [Answer] ## Itna-Cycler Let's raise the maximum score of the cycler family to 8! ``` (c,r)=>"SRP"[r%3] ``` [Answer] # Biased-Cycler ``` (c,r)=>"RRP"[r%3] ``` Yay. [Answer] ## #</> Let's add an awful hash answer. ``` (c,r)=>"SPR"[c.split``.reduce((t,i)=>(t<<5)+i.charCodeAt(0),5381)%3] ``` [Answer] # Psuedo-Hash Cycle ``` (c, r) => {var hash = 0;for (var i = 0; i < c.length; i++){var char = c.charCodeAt(i);hash = hash + char;}return "PRPSRS"[(c.length+hash+r)%6]} ``` This function is intended to return nearly-random values that will be difficult to predict. ]
[Question] [ # Challenge Given a positive integer `n`, you must calculate the nth digit of \$e\$, where \$e\$ is Euler's number (2.71828...). The format of the output can be a number or a string (e.g., `3` or `'3'`) ## Example ``` # e = 2.71828... nthDigit(3) => 8 nthDigit(1) => 7 nthDigit(4) => 2 ``` Shortest code wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žtsè ``` Pretty convenient builtin ¯\\_(ツ)\_/¯ [Try it online](https://tio.run/##yy9OTMpM/f//6L6S4sMr/v83BgA) or [verify the first ten digits](https://tio.run/##yy9OTMpM/R/i6mevpPCobZKCkr3f/6P7SooPr/iv8x8A) or [output the infinite list of digits](https://tio.run/##yy9OTMpM/f//6L6S//8B). **Explanation:** ``` žt # Push the infinite list of decimal value of e (including leading 2) sè # And 0-based index the input-integer into it # (after which the result is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~34~~ 32 bytes *Solution provided by @l4m2* *-2 bytes thanks to @xnor* ``` lambda n:`(100**n+1)**100**n`[n] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKkHD0MBASytP21BTSwvCTIjOi/2fll@kkKmQmadQlJiXnqphrGnFpVBQlJlXopGmkamp@R8A "Python 2 – Try It Online") Very, very slow. [Verification](https://tio.run/##dZRda@NWEIbv/StOHQpx4sKZ831SXGgpXXLR3nQLhRA2SiwnYrOSkWXW@@vTZxw3uxetcYJkzXm/ZjTbL9PT0LuXl99//vvDr9fvrt//aVYmWjv75fodV2IvLr4@ms3OzEPz/LB/bqbWTE@teW43k/k07Caz7h67aWeGjTlcXJzruX6xpH4a9/2Dlh9Mt9F/OzMNg3luxsd2acZh36/NfmuG0ayHz71pdma3bR@6TdeuOd0PR6JmOqEeYdHF3SvJuesXi9m63Zhmux2Hw/lh2S/HxdXMbID8YLreHMamf2zPe/1RD67EcqFifsLkFZpWlE3nd4e7m6uvZm8X5tKMMzO2034EZXZk6aeno9NXuLMTa/dJHT4Pn9vRNEdDW67u1dzM7ASCu5O8VwuXsnQX/fK35nnXLmDlh1sK3f8Vvh/339Sdqfj7YXp6ZdiZ5vFxbMlpMP2pDzMtUeIVqFcnCzu5@UHPt7BqFqef/xj69uXMbLqRNkJr/8VoV3OXpbiifyFWG6Lz0SfrSg5ZfHQpuVBzjtmFbKtPtdZYYw41pZpycpkHNqfkLediyLGGyMHiJJfooqQUXNYvJVWqd9Z6G2t1UiQHGABy8HoYKs98cBVWSiKY2RfxzrsCUQ0@VKi4B76WYnP0UpXESrUikWofpOTKQeskBluqhFp9KCVIytFWF0JOEpJNqdjiXArFWkklZMRIiR6tPsQQXPBZlAFKnoHibKoxCsggFF/AcEm8x2yIxZNqjs5SqfJSJMOaqcngiNrW@IjVViEN0MkzZOdBTQTseIoPZFZXfCo4crDhrSTiTp4SEXH0p9RcEBhtRJDXNmRL2KqR9iSCSiUFTFRS1DQkAVgqXPb1nq75RIM0I9qLN0In2SiBTMgl1VIj3dKUcFigLSVVXwuNDwlVsahiMCu9IF9gMekTsiruRLK3glap2SZNX4L1XEstPqOR4lTIw3EXtAvad44Vq@1GGjgcDjEWiUDlmLKoaqVBnkZhccsYFSpouUbHEHJd@Kh62mKzYyoSXSix1OCAxiwuMIhR7GFEx5n5SmIDSvGIgeTJnGmpiC9Zu@kxRzx0DU8MJDoYWCcJGVbfGoaY/BnAwNQlj2EkeNEZ5kmwMZCOF4ZEZVNr0UnrmL9MFgSrQ0cxbeOtDLwA2kMsW0aDCcGUZcSZYx155p2pRQ0vcC2ITyUDUlOMThxpwUfXYyYUvmGuu31q2QC6N3W1d@yX4yLQnd7O9Ofum3Wqi0JX4Jqd9bYUu8Vx8ax1y@tauTLbkdVq5r1ZzZemW87/6j/27Pnlfy9LCHeN7rL5j@Z@bJuPuqyOgN@tTHvT3b4BXvcPwzi2D9MR1qyXZn4zv6Tkqrv0t5fz2/lRSWe@Z6XpGrRvR1fHz@u50w23L/8A) up to \$166\$ digits. The idea for this verification comes from @l4m2: calculates \$x^{100^n}\$ by calculating `x=x**10` repeatedly (\$2n\$ times), each time truncating \$x\$ to a few left most digits (the TIO link uses \$500\$ digits). By changing the truncation to round down or up, we obtain the lower and upper bound for the result. If the lower and upper bound agree to \$n\$ leftmost digits, we know that the exact calculation will also result in those \$n\$ digits. I have verified that this solution works up to \$n = 333\$, using `MAX_DIGITS = 1000`. **How** This solution uses the following well known approximation of \$e\$: $$ e = \lim\_{x \to \infty} \left(1 + \frac{1}{x} \right)^{x}$$ Substituting \$x = 100^n\$, we have: $$ e = \lim\_{n \to \infty} \left(1 + \frac{1}{100^n} \right)^{100^n} = \lim\_{n \to \infty} \frac{\left(100^n + 1 \right)^{100^n}}{\left(100^n\right)^{100^n}}$$ Since the denominator is a power of \$10\$, we can ignore it entirely. According to [this analysis on Math SE](https://math.stackexchange.com/a/3381351), the worst case error of this approximation is: $$ \Delta < \frac{3}{x} = \frac{3}{100^n}$$ which means roughly that every time \$n\$ increases by \$1\$, we gains 2 digits of precision. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 66 bytes ``` I?dF+k^1sF2sE2sN[q]sR[1lNlF*dsF/d0=RlE+sElN1+sNlLx]dsLx+lE*0k1/I%p ``` [Try it online!](https://tio.run/##S0n@/9/TPsVNOzvOsNjNqNjVqNgvujC2OCjaMMcvx00rpdhNP8XANijHVbvYNcfPULvYL8enIjal2KdCO8dVyyDbUN9TteD/f1MA "dc – Try It Online") [Or print more than 800 digits before TIO times out after a minute.](https://tio.run/##RY7LCoMwFET3fsUltGANonHro6sEBEnBrViwRiuYJtbbhYv@eyql0M0MHDjD3DqcXN@9oFhWe1@7B2QZ4RdBXHlWgs5XhiJBnqBsni3WDdNSi0ChiFSc15pT5FoyilJXW6uw2qjmQTyzqDwubt/xvNGu4Psmj9PUUHo6eQDK7gEw9JOF0AA5GMgLIH@4EwJvUD2EI/yOfT0z7OU@) I've verified these 800 digits against the published value at a [NASA web page with 2 million digits of e](https://apod.nasa.gov/htmltest/gifcity/e.2mil). (It may be possible to shorten the code a bit by keeping some of the variables on the stack and accessing them via stack manipulation instead of using dc's registers.) **Explanation** ``` I # 10. ? # Input value. d # Push on stack for later. F+k # Add 15 and make that the number of decimal places to calculate. ^ # 10 ^ input value, saved on stack for use at end. 1sF # 1!, stored in F. 2sE # 2 is starting value for e. 2sN # for (N=2; ... ) [q]sR # Macro R will be used to end loop. [ # Start loop L. 1 # Push 1 for later. lNlF*dsF # F = N! and push on stack. /d # 1 / N!, duplicate on stack 0=R # If 1/N! == 0 (to the number of decimal places being computed), end loop. lE+sE # Otherwise e += 1/N! lN1+sN # N++ lLx # Go back to start of loop L ]dsLx # End macro, save it in L, and execute it. + # Get rid of extra 0 on stack. lE # e, computed with sufficient accuracy * # Multiply by 10^input value, which was saved on the stack early on. 0k1/ # Truncate to integer. I% # Mod by 10 to get desired digit. p # Print digit. ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~146~~ 105 bytes ``` n=int(input()) N=n+3 q=2 e=[1]*N exec('q=i=0;exec("q,e[i]=divmod(10*e[i]+q,N-i+1);i+=1;"*N);'*n) print(q) ``` [Try it online!](https://tio.run/##Hc0xDoMwDEDR3cdgIU6oFJcx8hVyAcQEkeqhJq7Sqj19Ktj@m379tcehc@/Kos2J1ndziJBZwwzGdyi80OozlG/Z3GgsHNPVg01lkZV3@TyP3VH0J4NN@SaBMElgSoPPmEavCPV1Dgx7pxj/ "Python 3 – Try It Online") (thanks to @SurculoseSputum) This only uses small integers to calculate digits of \$e\$. With a modification to use a lazy upper bound for `N`, it uses the algorithm described in > > A. H. J. Sale. "The calculation of \$e\$ to many significant digits." The Computer Journal, Volume 11, Issue 2, August 1968, Pages 229–230, <https://doi.org/10.1093/comjnl/11.2.229> > > > Essentially, the idea is that \$e\$ can be written in "base-factorial" as \$1.11111\dots\$, where digit \$n\$ has place value \$1/n!\$. The algorithm repeatedly multiplies this number by 10 to extract digits one at a time. In fact, if one were to record each value of `q` in the outer `for` loop, the result would be the first `n` digits of \$e\$. One complexity is that we need to know how many digits in base-factorial to calculate. In this version, \$n+3\$ is (more than) sufficient. A previous version of this answer used an estimate from Taylor's theorem, and it looked for a value of `N` such that \$N!\geq 10^{n}\$, doing so by calculating all factorials until it exceeds this power of ten. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` °D>smI<è ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0AYXu@JcT5vDK/7/NwIA "05AB1E – Try It Online") Very, very slow. [Answer] # [SageMath](http://doc.sagemath.org/html/en/index.html), ~~35~~ 33 bytes ``` lambda n:str(N(e,digits=n+9))[-9] ``` [Try it online!](https://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTIsyouKdLw00jVSclMzywpts3TttTUjNa1jOVKyy9SyFTIzFPQMNYx1DHRMTQAAU0rLgUgKCjKzCvRSFOqzqxV0LVTqE7TyNSsVdIEAJFLGOc=&lang=sage&interacts=eJyLjgUAARUAuQ==) Very, very *fast!* [Answer] # [Python 2](https://docs.python.org/2/), ~~98~~ ~~100~~ ~~72~~, 71 bytes ``` f=lambda n,p=1,q=1,k=1:k<n+9and f(n,p*k+1,q*k,k+1)or str(p*100**n/q)[n] ``` [Try it online!](https://tio.run/##TZTNbtswEITvfgoCudiKgfJXJIP4SYoeXKRuDbeK4/qSp3eX366NghDFvx3OzK50/rz@el/i7XbY/d7/@f62d8v2vAvbD3lOu/Byel2e@355c4e1bEynZ9maTlt5b94v7u/1sj5PwftpWr58bL4u325PLrrqVk8uuCbD9nhnV1x3nnd0SfrkZpmPvSqrVU4m9mZpUVa6rFVZqcyqnO3EdFrhqZybWZ1lNnO9Rnjms8R4u6@AMyIzsePGwS7IuHF3kfGIyeDce0XpsjcYRMHzoBaYRDQGTqqGbhpUbzIN3eISuN20elOiPCuMArckvFFFHZwMRuVsBKmB1KR5lCU43pV4ZqMPcBjnEywbmHqjR0HBsYbKjK5xspG5gLeFDAxnMxwCzni0NmIjijIzT1TjrDoT8DiZr4kcZMaZ1fDQoCo1LpvHnhwXdCln5dBQpTwiKwkXktVcQ6U37EhGMurUvRnvPT5Ww6nGJzyyfa8@rVaPS9H4JatfTx@5T@uxWy1qrOZD3ewgJRzSHEXTpnlr8NLaS4YSaNG@nwZ6MwcLdaQOpcfXUGHezOdunHSvg93Il2aiWy3eayNw90wNdNPl/99fHeQfcHTHxV32y88f6@L95sWdL8flKv@L42a7uv0D "Python 2 – Try It Online") -1 byte, remove unneccesary whitespace. ### older answer ``` f=lambda n,p=1,q=1,k=1:k<n+9and f(n,p*k+1,q*k,k+1) or str(p*100**n/q)[n] ``` [Try it online!](https://tio.run/##TZTNbtswEITvfgoCudiKgfJXJIP4SYoeXKRuDbeK4/qSp3eX366NghDFvx3OzK50/rz@el/i7XbY/d7/@f62d8v2vAvbD3lOu/Byel2e@355c4e1bEynZ9maTlt5b9z7xf29XtbnKXg/TcuXj83X5dvtyUVX3erJBddk2B7v7IrrzvOOLkmf3CzzsVdltcrJxN4sLcpKl7UqK5VZlbOdmE4rPJVzM6uzzGau1wjPfJYYb/cVcEZkJnbcONgFGTfuLjIeMRmce68oXfYGgyh4HtQCk4jGwEnV0E2D6k2moVtcArebVm9KlGeFUeCWhDeqqIOTwaicjSA1kJo0j7IEx7sSz2z0AQ7jfIJlA1Nv9CgoONZQmdE1TjYyF/C2kIHhbIZDwBmP1kZsRFFm5olqnFVnAh4n8zWRg8w4sxoeGlSlxmXz2JPjgi7lrBwaqpRHZCXhQrKaa6j0hh3JSEadujfjvcfHajjV@IRHtu/Vp9XqcSkav2T16@kj92k9dqtFjdV8qJsdpIRDmqNo2jRvDV5ae8lQAi3a99NAb@ZgoY7UofT4GirMm/ncjZPudbAb@dJMdKvFe20E7p6pgW66/P/7q4P8A47uuLjLfvn5Y12837y48@W4XOWHcdxsV7d/ "Python 2 – Try It Online") -28 bytes simpler formula Simpler algorithm based on more usual formula: $$e = 1 + \frac 1 {1!} + \frac 1 {2!} + \frac 1 {3!} + \frac 1 {4!} + \cdots$$ But re-expressed as sequence of approximations: $$1, 1+1, \frac{(2(1+1)+1)}2, \frac{(3(2(1+1)+1)+1)}{(3\cdot2)}, \frac{(4(3(2(1+1)+1)+1)+1)}{(4\cdot(3\cdot2))},...$$ These can be expressed as ratio of recurrence relations $\frac {p\_k}, where $$p\_0 = q\_0 = 1 \\ p\_{k+1} = kp\_k + 1, q\_{k+1} = kq\_k, \: \forall k \ge 1$$ ### old answer ``` f=lambda n,p=3,q=1,r=19,s=7,b=10,x=1,y=0:x-y and f(n,r,s,r*b+p,s*b+q,b+4,p*100**n//q,x) or str(x)[n] ``` +2 bytes because I mistakenly omitted `f=` [Try it online!](https://tio.run/##DYzNDsIgEAZfZY@FfqbgT0yb8CTGA6RWSXRLlx7o0yOXSWYOk479s/K51sV9/S/MnhjJXbA5C3F2RHZ3BGcNSiuHM1M5HeR5pqVjCDJEhz4hN24I/RVJW2O05mHYUBStQnmXrqgHP@vSLFJkEs/vV3czRk2UJPLedlGh/gE "Python 2 – Try It Online") This approach is based on continued fractions. Not happy with it yet, but it seems good for a few hundred digits. Based on the continued fraction: $$e = 3 - \cfrac 2 {7 + \cfrac 1 {10 + \cfrac 1 {14 + \cfrac 1 {18 + \cfrac 1 {22 + \ddots}}}}}$$ Computed by the recurrence relation: $$\frac {p\_0} {q\_0} = \frac 3 1 , \: \frac {p\_1} {q\_1} = \frac {19} 7 \\ \frac {p\_{k+1}} {q\_{k+1}} = \frac {p\_k (4k+2) + p\_{k-1}} {q\_k (4k+2) + q\_{k-1}}, \: \forall k \ge 1$$ which was arrived at after a first reading of [An Essay on Continued Fractions](https://www.math.kth.se/optsyst/forskning/forskarutbildning/SF3881/Euler.pdf) by Leonard Euler. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ⁵*³ ¢‘µ*¢ŒṘḣ³Ṫ ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//4oG1KsKzCsKi4oCYwrUqwqLFkuG5mOG4o8Kz4bmq////Mw "Jelly – Try It Online") A monadic link taking a single integer, plus a niladic helper link. ## Explained ``` ⁵*³ ¢‘µ*¢ŒṘḣ³Ṫ Link f: *(10, input) # 10 * input Main Link: tail(head(str(*(Increment(f()), f())), input)) # str((f() + 1) * (f()))[:input][-1] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 21 bytes ``` Floor[E 10^#]~Mod~10& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2r73y0nP78o2lXB0CBOObbONz@lztBA7X9AUWZeiYNjUVFiZXSqTrWhgYFBbex/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ 12 bytes ``` P←×ψ⁺²N¤≕ET¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@3NKcks6AoM69Ew8onNa1ERyEkMze1WKNSRyEgp7RYw0hHwTOvoLTErzQ3KbVIQxMIrLncMnNyNNxTS8ISizITk3JSNZRclUDiIUWZuRqGmtb//1v@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Inspired by @ASCII-only's comment and his answer to [Bake a slice of Pi](https://codegolf.stackexchange.com/questions/93615) (compare my answer to [Music with pi and e](https://codegolf.stackexchange.com/questions/206906)). Explanation: ``` P←×ψ⁺²N ``` Input `n` and print `n+2` nulls to the left without moving the cursor, so it remains on the last null. ``` ¤≕E ``` Fill the nulls with the expansion of Euler's number. ``` T¹ ``` Trim away everything except the current character. Previous 30-byte answer calculated the Maclaurin expansion of `100ⁿe` to `n+10` terms: ``` Nθ≔Xχ⊗θη≔⁰ζF⁺χθ«≧⁺ηζ≧÷⊕ιη»§Iζθ ``` [Try it online!](https://tio.run/##XY1BDoIwEEXXcoouS4KJLg0rIpsuMMQbFKjQpEyxnaLBePY6ARMTlzPv/bx2kK610sQoYAp4CWOjHL@neVJ4r3vgtX3Q43jIWGlDY1RHMM3Y8DMILXTdrGO8NsGvMknslewqOW3WVfcDrpi22@AfCsBSz7pTGRPQOjUqQMrpb@2d1E4D8gIFdOrJz9IjX9I1lcd4ivvZfAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔Xχ⊗θη ``` Start with a term of `100ⁿ`. ``` ≔⁰ζ ``` Initialise the total to `0`. ``` F⁺χθ« ``` Repeat `n+10` times. ``` ≧⁺ηζ ``` Add the current term to the total. ``` ≧÷⊕ιη ``` Divide the term by the number of loop iterations. ``` »§Iζθ ``` Print the `n`th digit of the total. [Answer] # [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 52 bytes ``` > Input > eᵢ >> ≻1 >> 2ᶠ3 >> 4ⁿ1 >> Output 5 ``` [Try it on repl.it!](https://repl.it/join/wpjvvcdd-razetime) Run with `python3 whispers\ v3.py euler.wisp < input.txt 2> /dev/null` Input is the first line in input.txt. Euler digits builtin ftw! [Answer] # bc -l, 37 bytes ``` scale=s=read();(e(1)*A^s+scale=0)%A/1 ``` [Try test cases online!](https://tio.run/##RY0xCsIwAEX3nOITFBKlbepqUuigqzcQ0jRaoSYlqZN49hhaxOUt731@p@OQjJ7RTMHfg35CSnq6nGmKRo9WRRWs7hk/Mstqvmuvcb8KwbdtVaecEnLzAQ83veZMvEVZHsSHAL3PAKwZPAoHulkb1YAuojMoRpTV/1n@IrrMnU1f) Input on stdin, output on stdout. ]